Class: Unipush::Android_push

Inherits:
Object
  • Object
show all
Defined in:
lib/unipush.rb

Overview

Android

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mode = 'production') ⇒ Android_push

Returns a new instance of Android_push.



230
231
232
233
234
235
236
# File 'lib/unipush.rb', line 230

def initialize(mode='production')
  @gcm_url = 'https://android.googleapis.com/gcm/send'
  @gcm_key = nil

  @last_error = []
  @unsent_messages = []
end

Instance Attribute Details

#gcm_keyObject

variable for store the response



225
226
227
# File 'lib/unipush.rb', line 225

def gcm_key
  @gcm_key
end

#gcm_urlObject

variable for store the response



225
226
227
# File 'lib/unipush.rb', line 225

def gcm_url
  @gcm_url
end

#retObject

variable for store the response



225
226
227
# File 'lib/unipush.rb', line 225

def ret
  @ret
end

Instance Method Details

#get_last_errorObject



238
239
240
# File 'lib/unipush.rb', line 238

def get_last_error
  @last_error.empty? ? false : @last_error
end

#get_unsent_messagesObject



242
243
244
# File 'lib/unipush.rb', line 242

def get_unsent_messages
  @unsent_messages.nil? ? false : @unsent_messages
end

#send_android_messages(message, registration_ids, add = {}) ⇒ Object

message - text message registration_ids - array of devices



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/unipush.rb', line 251

def send_android_messages(message, registration_ids, add={})
  changed_registration_ids = []
  invalid_registration_ids = []

  if @gcm_key.nil?
    @last_error.push('GCM api key is null')
    false
  else
    if message && registration_ids.size>0
      err_mes = []
      ok_mes = []

      # сформируем пакеты по 1000 сообщений в каждом
      t_cnt = 0
      data_packets = []
      current_packet = []

      registration_ids.each do |tt|
        t_cnt+=1 #надо отсчитать 1000 токенов
        current_packet.push(tt)
        if t_cnt == 1000 # отсчитали 1000, запишем пакет и сбросим счетчик
          data_packets.push(current_packet)
          current_packet = []
          t_cnt = 0
        end
      end
      # last packet
      if t_cnt>0
        data_packets.push(current_packet)
      end


      # а теперь отправим пакеты сообщений
      data_packets.each_with_index do |dp, p_num|
        if dp.size>0
          data = {'registration_ids'=> dp,
                  'data' => {'message'=>message}
          }
          add.each do |key, val|
            data['data'][key] = val
          end
          data = data.to_json
          headers = { "Authorization" => "key=#{@gcm_key}",
                      "Content-type" => "application/json"}
          uri = URI.parse(@gcm_url)
          http = Net::HTTP.new(uri.host, uri.port)
          http.use_ssl = true
          http.verify_mode = OpenSSL::SSL::VERIFY_NONE

          response = http.post(uri.path, data, headers)

          if response.code == '200'
            result = JSON.parse(response.body)
            if result['failure']<=0 && result['canonical_ids']<=0 # ошибок нет, все отправилось
              ok_mes.push('Success')
            else
              result['results'].each_with_index do |res, k|
                if res['message_id'] && res['registration_id'] # если сменился ID девайса
                  changed_registration_ids.push([dp[k]], res['registration_id'])
                elsif res['error']
                  case res['error']
                    when 'NotRegistered', 'InvalidRegistration' # удалим токен
                      if dp[k].size>0
                        invalid_registration_ids.push(dp[k])
                      end
                    else
                      @last_error.push(res['error'])
                  end
                end
              end
            end
          else
            @last_error.push("Could not sent packet #{p_num}, code: #{response.code}")
          end
        end
      end
      if @last_error.size > 0
        false
      else
        true
      end
    else
      @last_error.push('No data given for sending')
      false
    end
  end
end