Method: Unipush::Android_push#send_android_messages

Defined in:
lib/unipush.rb

#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