2017-01-28 16:30:32 -08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class SendPushNotificationService < BaseService
|
|
|
|
def call(notification)
|
2017-01-29 03:25:10 -08:00
|
|
|
return if ENV['FCM_API_KEY'].blank?
|
2017-01-28 16:30:32 -08:00
|
|
|
|
2017-01-29 03:25:10 -08:00
|
|
|
devices = Device.where(account: notification.account).pluck(:registration_id)
|
|
|
|
fcm = FCM.new(ENV['FCM_API_KEY'])
|
2017-01-28 16:30:32 -08:00
|
|
|
|
2017-01-29 03:25:10 -08:00
|
|
|
response = fcm.send(devices, data: { notification_id: notification.id }, collapse_key: :notifications, priority: :high)
|
|
|
|
handle_response(response)
|
2017-01-28 16:30:32 -08:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def handle_response(response)
|
|
|
|
update_canonical_ids(response[:canonical_ids]) if response[:canonical_ids]
|
|
|
|
remove_bad_ids(response[:not_registered_ids]) if response[:not_registered_ids]
|
|
|
|
end
|
|
|
|
|
|
|
|
def update_canonical_ids(ids)
|
2017-01-29 03:25:10 -08:00
|
|
|
ids.each { |pair| Device.find_by(registration_id: pair[:old]).update(registration_id: pair[:new]) }
|
2017-01-28 16:30:32 -08:00
|
|
|
end
|
|
|
|
|
|
|
|
def remove_bad_ids(bad_ids)
|
2017-01-29 03:25:10 -08:00
|
|
|
Device.where(registration_id: bad_ids).delete_all unless bad_ids.empty?
|
2017-01-28 16:30:32 -08:00
|
|
|
end
|
|
|
|
end
|