项目作者: yuki24

项目描述 :
Finally, push notification framework that does not hurt. currently supports Android (FCM) and iOS (APNs)
高级语言: Ruby
项目地址: git://github.com/yuki24/pushing.git
创建时间: 2017-03-13T02:14:52Z
项目社区:https://github.com/yuki24/pushing

开源协议:MIT License

下载


Pushing: ActionMailer for Push Notifications Build Status

Pushing is a push notification framework that implements interfaces similar to ActionMailer.

  • Convention over Configuration: Pushing brings Convention over Configuration to your app for organizing your push notification implementations.
  • Extremely Easy to Learn: If you know how to use ActionMailer, you already know how to use Pushing. Send notifications asynchronously with ActiveJob at no learning cost.
  • Testability: First-class support for push notification. No more hassle writing custom code or stubs/mocks for your tests.

Getting Started

Add this line to your application’s Gemfile:

  1. gem 'pushing'
  2. gem 'jbuilder' # if you don't have it in your Gemfile

At the time of writing, Pushing only has support for jbuilder (Rails’ default JSON constructor), but there are plans to add support for jb and rabl.

Supported Platforms

Pushing itself doesn’t make HTTP requests. Instead, it uses an adapter to make actual calls. Currently, Pushing has support for the following client gems:

If you are starting from scratch, it is recommended using anpotic for APNs and andpush for FCM due to their reliability and performance:

  1. gem 'apnotic' # APNs
  2. gem 'andpush' # FCM

Walkthrough to Writing a Notifier

Generate a new notifier:

  1. $ rails g pushing:notifier TweetNotifier new_direct_message
  1. # app/notifiers/tweet_notifier.rb
  2. class TweetNotifier < ApplicationNotifier
  3. def new_direct_message(message_id, token_id)
  4. @message = DirectMessage.find(message_id)
  5. @token = DeviceToken.find(token_id)
  6. push apn: @token.apn? && @token.device_token, fcm: @token.fcm?
  7. end
  8. end

Edit the push notification payload:

APNs:

  1. # app/views/tweet_notifier/new_direct_message.json+apn.jbuilder
  2. json.aps do
  3. json.alert do
  4. json.title "#{@tweet.user.display_name} tweeted:"
  5. json.body truncate(@tweet.body, length: 235)
  6. end
  7. json.badge 1
  8. json.sound 'bingbong.aiff'
  9. end

FCM:

  1. # app/views/tweet_notifier/new_direct_message.json+fcm.jbuilder
  2. json.to @token.registration_id
  3. json.notification do
  4. json.title "#{@tweet.user.display_name} tweeted:"
  5. json.body truncate(@tweet.body, length: 1024)
  6. json.icon 1
  7. json.sound 'default'
  8. end

Deliver the push notifications:

  1. TweetNotifier.new_direct_message(message_id, device_token.id).deliver_now!
  2. # => sends a push notification immediately
  3. TweetNotifier.new_direct_message(message_id, device_token.id).deliver_later!
  4. # => enqueues a job that sends a push notification later

Advanced Usage

Pushing only to one platform

Pushing only sends a notification for the platforms that are given a truthy value. For example, give the following code:

  1. push apn: @token.device_token, fcm: false
  2. # => only sends a push notification to APNs
  3. push apn: @token.device_token
  4. # => same as above but without the `:fcm` key, only sends a push notification to APNs

This will only send a push notification to APNs and skip the call to FCM.

APNs

It is often necessary to switch the environment endpoint or adjust the request headers depending on the notification you want to send. Pushing’s #push method allows for overriding APNs request headers on a delivery-basis:

Overriding the default environment:

  1. push apn: { device_token: @token.device_token, environment: @token.apn_environment }

Overriding the default APN topic:

  1. push apn: { device_token: @token.device_token, headers: { apns_topic: 'your.otherapp.ios' } }

Or all of the above:

  1. push fcm: @token.fcm?,
  2. apn: {
  3. device_token: @token.apn? && @token.device_token,
  4. environment: @token.apn_environment,
  5. headers: {
  6. apns_id: uuid,
  7. apns_expiration: 7.days.from_now,
  8. apns_priority: 5,
  9. apns_topic: 'your.otherapp.ios',
  10. apns_collapse_id: 'not-so-important-notification'
  11. }
  12. }

The :fcm key, on the other hand, doesn’t have any options as everything’s configurable through the request body.

Error Handling

Like ActionMailer, you can use the rescue_from hook to handle exceptions. A common use-case would be to handle a ‘BadDeviceToken’ response from APNs or a response with a ‘Retry-After’ header from FCM.

Handling a ‘BadDeviceToken’ response from APNs:

  1. class ApplicationNotifier < Pushing::Base
  2. rescue_from Pushing::ApnDeliveryError do |error|
  3. response = error.response
  4. if response.status == 410 || (response.status == 400 && response.json[:reason] == 'BadDeviceToken')
  5. token = error.notification.device_token
  6. Rails.logger.info("APN device token #{token} has been expired and will be removed.")
  7. # delete or expire device token accordingly
  8. else
  9. raise # Make sure to raise any other types of error to re-enqueue the job
  10. end
  11. end
  12. end

Handling a ‘Retry-After’ header from FCM:

  1. class ApplicationNotifier < Pushing::Base
  2. rescue_from Pushing::FcmDeliveryError do |error|
  3. if error.response&.headers['Retry-After']
  4. # re-enqueue the job honoring the 'Retry-After' header
  5. else
  6. raise # Make sure to raise any other types of error to re-enqueue the job
  7. end
  8. end
  9. end

Interceptors and Observers

Pushing implements the Interceptor and Observer patterns. A common use-case would be to update registration ids with canonical ids from FCM:

  1. # app/observers/fcm_token_handler.rb
  2. class FcmTokenHandler
  3. def delivered_notification(payload, response)
  4. return if response.json[:canonical_ids].to_i.zero?
  5. response.json[:results].select {|result| result[:registration_id] }.each do |result|
  6. result[:registration_id] # => returns a canonical id
  7. # Update registration ids accordingly
  8. end
  9. end
  10. end
  11. # app/notifiers/application_notifier.rb
  12. class ApplicationNotifier < Pushing::Base
  13. register_observer FcmTokenHandler.new
  14. ...
  15. end

Configuration

TODO: Make this section more helpful
  1. Pushing.configure do |config|
  2. # Adapter that is used to send push notifications through FCM
  3. config.fcm.adapter = Rails.env.test? ? :test : :andpush
  4. # Your FCM servery key that can be found here: https://console.firebase.google.com/project/_/settings/cloudmessaging
  5. config.fcm.server_key = 'YOUR_FCM_SERVER_KEY'
  6. # Adapter that is used to send push notifications through APNs
  7. config.apn.adapter = Rails.env.test? ? :test : :apnotic
  8. # The environment that is used by default to send push notifications through APNs
  9. config.apn.environment = Rails.env.production? ? :production : :development
  10. # The scheme that is used for negotiating connection trust between your provider
  11. # servers and Apple Push Notification service. As documented in the offitial doc,
  12. # there are two schemes available:
  13. #
  14. # :token - Token-based provider connection trust (default)
  15. # :certificate - Certificate-based provider connection trust
  16. #
  17. # This option is only applied when using an adapter that uses the HTTP/2-based
  18. # API.
  19. config.apn.connection_scheme = :token
  20. # Path to the certificate or auth key for establishing a connection to APNs.
  21. #
  22. # This config is always required.
  23. config.apn.certificate_path = 'path/to/your/certificate'
  24. # Password for the certificate specified above if there's any.
  25. # config.apn.certificate_password = 'passphrase'
  26. # A 10-character key identifier (kid) key, obtained from your developer account.
  27. # If you haven't created an Auth Key for your app, create a new one at:
  28. # https://developer.apple.com/account/ios/authkey/
  29. #
  30. # Required if the +connection_scheme+ is set to +:token+.
  31. config.apn.key_id = 'DEF123GHIJ'
  32. # The issuer (iss) registered claim key, whose value is your 10-character Team ID,
  33. # obtained from your developer account. Your team id could be found at:
  34. # https://developer.apple.com/account/#/membership
  35. #
  36. # Required if the +connection_scheme+ is set to +:token+.
  37. config.apn.team_id = 'ABC123DEFG'
  38. # Header values that are added to every request to APNs. documentation for the
  39. # headers available can be found here:
  40. # https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html#//apple_ref/doc/uid/TP40008194-CH11-SW13
  41. config.apn.default_headers = {
  42. apns_priority: 10,
  43. apns_topic: 'your.awesomeapp.ios',
  44. apns_collapse_id: 'wrong.topicname.com'
  45. }
  46. end

Testing

Pushing provides first-class support for testing. In order to test your notifier, use the :test adapter in the test environment instead of an actual adapter in development/production.

  1. # config/initializers/pushing.rb
  2. Pushing.configure do |config|
  3. config.apn.adapter = Rails.env.test? ? :test : :apnotic
  4. config.fcm.adapter = Rails.env.test? ? :test : :andpush
  5. end

Now you can call the #deliveries method on the notifier. Here is an example with ActiveSupport::TestCase:

  1. TweetNotifier.deliveries.clear # => clears the test inbox
  2. assert_changes -> { TweetNotifier.deliveries.apn.size }, from: 0, to: 1 do
  3. TweetNotifier.new_direct_message(message.id, apn_device_token.id).deliver_now!
  4. end
  5. apn_message = TweetNotifier.deliveries.apn.first
  6. assert_equal 'apn-device-token', apn_message.device_token
  7. assert_equal "Hey coffee break?", apn_message.payload[:aps][:alert][:body]
  8. assert_changes -> { TweetNotifier.deliveries.fcm.size }, from: 0, to: 1 do
  9. TweetNotifier.new_direct_message(message.id, fcm_registration_id.id).deliver_now!
  10. end
  11. fcm_payload = TweetNotifier.deliveries.fcm.first.payload
  12. assert_equal 'fcm-registration-id', fcm_payload[:to]
  13. assert_equal "Hey coffee break?", fcm_payload[:notification][:body]

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/yuki24/pushing. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.