On rapns, how can I know the token for unregistere

2019-06-08 06:29发布

问题:

I am using rapns to provide GCM and APNS support. For APNS, I know what unregistered device I must delete via on.apns_feedback (rapns.rb):

on.apns_feedback do |feedback|
    device = AppleDevice.find_by_token(feedback.device_token)
    device.destroy if device
end

but for GCM, I can't find a way to know what device is unregistered so I can delete it from my database.

I tried with the reflection API, but I'm not getting on.notification_failed and on.error called whenever a Rapns::DeliveryError exception is raised and those methods doesn't seem to give me a way to know the unregistered tokens.

I tried catching the Rapns::DeliveryError, but it doesn't seem to work.

messenger = PushMessenger::Gcm.new
GoogleDevice.find_in_batches :batch_size => 1000 do |devices|
  tokens = devices.map(&:token)
  begin
    messenger.deliver(app, tokens, payload, nil, true)
  rescue Rapns::DeliveryError => error
    GoogleDevice.destroy_all # Just to see it works
  end
end

PushMessenger:

module PushMessenger
    class Gcm
        def deliver(app, tokens, payload, collapse_key=nil, delay_while_idle=nil, expiry=1.day.to_i)
            tokens = *tokens
            n = Rapns::Gcm::Notification.new
            n.app = app
            n.registration_ids = tokens
            n.collapse_key = collapse_key
            n.delay_while_idle = delay_while_idle
            n.expiry = expiry
            n.data = payload
            n.save!
        end
    end
end

How can I know the token for these unregistered devices so I can remove them from my database?

回答1:

I'm using rapns to do pretty much the same, so here my two cents:

First, for Android devices you don't need the device_token to deactivate/remove the device (On GCM device_token == registration_id). You can get that registration_id from the on.notification_failed callback with the Reflection API.

Last, which version of rapns are you using? Right now the last version (3.4.1) has a bug with on.notification_failed, but version 3.3.2 works just fine and you'll be able to do something like:

on.notification_failed do |notification|
  device = Device.find_by_token(notification.registration_ids.first)
  device.destroy if device
end

Hope that helps.