mono0926
6/10/2017 - 5:20 AM

Firebaseで指定ユーザーID群に一気に1,000件ずつプッシュ通知送る処理、簡単( ´・‿・`) Amazon SNSよりかなり扱いやすい感( ´・‿・ #ruby #CodePiece

Firebaseで指定ユーザーID群に一気に1,000件ずつプッシュ通知送る処理、簡単( ´・‿・`) Amazon SNSよりかなり扱いやすい感( ´・‿・ #ruby #CodePiece

def publish(user_ids:, title:, body:, click_action:, badge: 1, sound: 'original1.caf', priority: 'high')
  registration_ids = Device.where(user: user_ids).pluck(:fcm_token)
  options = { notification: {
    badge: badge,
    title: title,
    body: body,
    sound: sound,
    click_action: click_action,
    priority: priority
  } }
  registration_ids.each_slice(1000) do |sliced_tokens|
    response = fcm.send(sliced_tokens, options)
    results = JSON.parse(response[:body])['results']
    errors = sliced_tokens.zip(results)
             .map { |token, result| { token: token, error: result['error'] } }
             .select { |e| e[:error].present? }
    next if errors.empty?
    Rails.logger.warn("Failed to publish. Errors:\n#{errors}")
    # See: https://developers.google.com/cloud-messaging/http-server-ref
    errors_to_delete = errors.select { |e| %w(MissingRegistration InvalidRegistration UnregisteredDevice).include?(e[:error]) }
    unless errors_to_delete.empty?
      Device.where(fcm_token: errors_to_delete.pluck(:token)).delete_all
      Rails.logger.warn("Device deleted:\n#{errors_to_delete}")
    end
  end
end