- Notifications
You must be signed in to change notification settings - Fork378
The push notification service for Ruby.
License
rpush/rpush
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Rpush aims to be thede facto gem for sending push notifications in Ruby. Its core goals are ease of use, reliability and a rich feature set. Rpush provides numerous advanced features not found in others gems, giving you greater control & insight as your project grows. These are a few of the reasons why companies worldwide rely on Rpush to deliver their notifications.
- Apple Push Notification Service
- Including Safari Push Notifications.
- Firebase Cloud Messaging (used to be Google Cloud Messaging)
- Amazon Device Messaging
- Windows Phone Push Notification Service
- Pushy
- Webpush
- UseActiveRecord orRedis for storage.
- Plugins forBugsnag,Sentry,StatsD. Third party plugins:Prometheus Exporter. Orwrite your own.
- Seamless integration with your projects, includingRails.
- Run as adaemon, inside ajob queue, on thecommand-line orembedded in another process.
- Scales vertically (threading) and horizontally (multiple processes).
- Designed for uptime - new apps are loaded automatically, signal
HUP
to update running apps. - Hooks for fine-grained instrumentation and error handling (Reflection API).
- Tested withMRI
Add it to your Gemfile:
gem'rpush'
Initialize Rpush into your project.Rails will be detected automatically.
$cd /path/to/project$ bundle$ bundleexec rpush init
There is a choice of two modes (and one legacy mode) using certificates or using tokens:
Rpush::Apns2
This requires an annually renewable certificate. seehttps://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/establishing_a_certificate-based_connection_to_apnsRpush::Apnsp8
This uses encrypted tokens and requires an encryption key id and encryption key (provide as a p8 file). (seehttps://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/establishing_a_token-based_connection_to_apns)Apple haveannounced that this is not supported after March 31, 2021.
If this is your first time using the APNs, you will need to generate either SSL certificates (for standard Apns) or an Encryption Key (p8) and an Encryption Key ID (for Apnsp8). SeeGenerating Certificates for instructions.
To use the p8 APNs Api:
app=Rpush::Apnsp8::App.newapp.name="ios_app"app.apn_key=File.read("/path/to/sandbox.p8")app.environment="development"# APNs environment.app.apn_key_id="APN KEY ID"# This is the Encryption Key ID provided by appleapp.team_id="TEAM ID"# the team id - e.g. ABCDE12345app.bundle_id="BUNDLE ID"# the unique bundle id of the app, like com.example.appnameapp.connections=1app.save!
n=Rpush::Apnsp8::Notification.newn.app=Rpush::Apnsp8::App.find_by_name("ios_app")n.device_token="..."# hex stringn.alert="hi mom!"# n.alert = { title: "push title", subtitle: "more to say", body: "hi mom!" }n.data={foo::bar}n.save!
(NB this uses the same protocol as Apnsp8, but authenticates with a certificate rather than tokens)
app=Rpush::Apns2::App.newapp.name="ios_app"app.certificate=File.read("/path/to/sandbox.pem")app.environment="development"app.password="certificate password"app.bundle_id="BUNDLE ID"# the unique bundle id of the app, like com.example.appnameapp.connections=1app.save!
n=Rpush::Apns2::Notification.newn.app=Rpush::Apns2::App.find_by_name("ios_app")n.device_token="..."# hex stringn.alert="hi mom!"# n.alert = { title: "push title", subtitle: "more to say", body: "hi mom!" }n.data={headers:{'apns-topic':"BUNDLE ID"},# the bundle id of the app, like com.example.appname. Not necessary if set on the app (see above)foo::bar}n.save!
You should also implement thessl_certificate_will_expire reflection to monitor when your certificate is due to expire.
Using one of the notifications methods above, theurl_args
attribute is available for Safari Push Notifications.
The appenvironment
for any Apns* option is "development" for XCode installs, and "production" for app store and TestFlight. Note that you can now use one (production + sandbox) certificate (you don't need a separate "sandbox" or development certificate), but if you do generate a development/sandbox certificate it can only be used for "development". With Apnsp8 tokens, you can target either "development" or "production" environments.
You will need two params to make use of FCM via Rpush.
firebase_project_id
- TheProject number
in your Firebase Project Settingsjson_key
- The JSON key file for a service account with theFirebase Admin SDK Administrator Service Agent
role.
Create service account in the google cloud account attached to your firebase account:https://console.cloud.google.com/iam-admin/serviceaccountsMake sure it has RoleFirebase Admin SDK Administrator Service Agent
Add + Download the json key for the service account.
Once you have those two params, you can create an FCM app and send notifications.
fcm_app=Rpush::Fcm::App.newfcm_app.name="fcm_app"fcm_app.firebase_project_id="someapp-123456"fcm_app.json_key=Rails.root.join("your/key/somewhere.json").read# or from a ENV variable - just needs to be the whole json filefcm_app.connections=30fcm_app.save!
n=Rpush::Fcm::Notification.newn.app=Rpush::Fcm::App.where(name:"fcm_app").firstn.device_token=device_token# Note that device_token is used here instead of registration_idsn.notification={title:"push title",body:"hi mom!"}# either title or body needs to be set, or nothing goes throughn.data={}.transform_values(&:to_s)# All values going in here have to be strings, if you have anything else - nothing goes throughn.save!
FCM also requires you to respond toCanonical IDs.
Check theFCM reference for what keys you can use and are available to you.Note: Not all are yet implemented in Rpush.
app=Rpush::Adm::App.newapp.name="kindle_app"app.client_id="..."app.client_secret="..."app.connections=1app.save!
n=Rpush::Adm::Notification.newn.app=Rpush::Adm::App.find_by_name("kindle_app")n.registration_ids=["..."]n.data={message:"hi mom!"}n.collapse_key="Optional consolidationKey"n.save!
For more documentation onADM.
Uses the olderWindows Phone 8 Toast template
app=Rpush::Wpns::App.newapp.name="windows_phone_app"app.client_id=# Get this from your apps dashboard https://dev.windows.comapp.client_secret=# Get this from your apps dashboard https://dev.windows.comapp.connections=1app.save!
n=Rpush::Wpns::Notification.newn.app=Rpush::Wpns::App.find_by_name("windows_phone_app")n.uri="http://..."n.data={title:"MyApp",body:"Hello world",param:"user_param1"}n.save!
Uses the more recentToast template
Theclient_id
here is the SID URL as seenhere. Do not confuse it with theclient_id
on dashboard.
You can (optionally) include a launch argument by adding alaunch
key to the notification data.
You can (optionally) include anaudio element by setting the sound on the notification.
app=Rpush::Wns::App.newapp.name="windows_phone_app"app.client_id=YOUR_SID_URLapp.client_secret=YOUR_CLIENT_SECRETapp.connections=1app.save!
n=Rpush::Wns::Notification.newn.app=Rpush::Wns::App.find_by_name("windows_phone_app")n.uri="http://..."n.data={title:"MyApp",body:"Hello world",launch:"launch-argument"}n.sound="ms-appx:///mynotificationsound.wav"n.save!
Note: The data is passed as.to_json
so only this format is supported, although raw notifications are meant to support any kind of data.Current data structure enforces hashes and.to_json
representation is natural presentation of it.
n=Rpush::Wns::RawNotification.newn.app=Rpush::Wns::App.find_by_name("windows_phone_app")n.uri='http://...'n.data={foo:'foo',bar:'bar'}n.save!
Uses thebadge template and the typewns/badge
.
n=Rpush::Wns::BadgeNotification.newn.app=Rpush::Wns::App.find_by_name("windows_phone_app")n.uri='http://...'n.badge=4n.save!
Pushy is a highly-reliable push notification gateway, based onMQTT protocol for cross platform push notification delivery that includes web, Android, and iOS. One of its advantages is it allows for reliable notification delivery to Android devices in China where Google Cloud Messaging and Firebase Cloud Messaging are blocked and to custom hardware devices that use Android OS but are not using Google Play Services.
Note: current implementation of Pushy only supports Android devices and does not includesubscriptions.
app=Rpush::Pushy::App.newapp.name="android_app"app.api_key=YOUR_API_KEYapp.connections=1app.save!
n=Rpush::Pushy::Notification.newn.app=Rpush::Pushy::App.find_by_name("android_app")n.registration_ids=["..."]n.data={message:"hi mom!"}n.time_to_live=60# secondsn.save!
For more documentation onPushy.
Webpush is aprotocol for delivering push messages to desktop browsers. It's supported byall major browsers (except Safari, you have to use one of the Apns transportsfor that).
UsingVAPID, thereis no need for the sender of push notifications to register upfront with pushservices (as was the case with the now legacy Mozilla or Google desktop pushproviders).
Instead, you generate a pair of keys and use the public key when subscribingusers in your web app. The keys are stored along with an email address (which,according to the spec, can be used by push service providers to contact you incase of problems) in thecertificates
field of the Rpush Application record:
vapid_keypair=Webpush.generate_key.to_hashapp=Rpush::Webpush::App.newapp.name='webpush'app.certificate=vapid_keypair.merge(subject:'mailto:user@example.org').to_jsonapp.connections=1app.save!
Thesubscription
object you obtain from a subscribed browser holds anendpoint URL and cryptographic keys. When sending a notification, simply passthe whole subscription as sole member of theregistration_ids
collection:
n=Rpush::Webpush::Notification.newn.app=Rpush::App.find_by_name("webpush")n.registration_ids=[subscription]n.data={message:"hi mom!"}n.save!
In order to send the same message to multiple devices, create oneNotification
per device, as passing multiple subscriptions at once asregistration_ids
is not supported.
It is recommended to run Rpush as a separate process in most cases, though embedding and manual modes are provided for low-workload environments.
Seerpush help
for all available commands and options.
$cd /path/to/project$ rpush start
$cd /path/to/project$ rpush start -f
$ rpush push
Rpush will deliver all pending notifications and then exit.
Rpush.push
SeePush API for more details.
ifdefined?(Rails)ActiveSupport.on_load(:after_initialize)doRpush.embedendelseRpush.embedend
Call this during startup of your application, for example, by adding it to the end ofconfig/rpush.rb
. SeeEmbedding API for more details.
If you're usingmina, there is a gem calledmina-rpush which helps you control rpush.
Rpush leaves delivered notifications in the database. If you do not clear them out, they will take up more and more space. This isn't great for any database, but is especially problematic if using Redis as the Rpush store.Here is an example solution for cleaning up delivered notifications in Redis.
SeeConfiguration for a list of options.
You should runrpush init
after upgrading Rpush to check for configuration and migration changes.
- Using Redis
- Using ActiveRecord
- Configuration
- Moving from Rapns
- Deploying to Heroku
- Hot App Updates
- Signals
- Reflection API
- Push API
- Embedding API
- Writing a Plugin
- Implementing your own storage backend
- Upgrading from 2.x to 3.0
- Generating Certificates
- Advanced APNs Features
- APNs Delivery Failure Handling
- Why open multiple connections to the APNs?
- Silent failures might be dropped connections
Rpush usesAppraisal to run tests against multiple versions of Ruby on Rails. This helps making sure that Rpush performs correctly with multiple Rails versions.
Rpush also uses RSpec for its tests.
First, we need to setup a test database,rpush_test
.
E.g. (postgres):psql -c 'create database rpush_test;' -U postgres >/dev/null
bundle installbundle exec appraisal install
This will install all the required gems that requires to test against each version of Rails, which defined ingemfiles/*.gemfile
.
bundle exec appraisal rake
This will run RSpec against all versions of Rails.
You need to specify aBUNDLE_GEMFILE
pointing to the gemfile before running the normal test command:
BUNDLE_GEMFILE=gemfiles/rails_6.0.gemfile rspec spec/unit/apns_feedback_spec.rb
When running specs, please note that the ActiveRecord adapter can be changed by setting theADAPTER
environment variable. For example:ADAPTER=postgresql rake
.
Available adapters for testing arepostgresql
,jdbcpostgresql
,mysql2
,jdbcmysql
,jdbch2
, andsqlite3
.
Note that the database username is changed at runtime to be the currently logged in user's name. So if you're testingwith mysql and you're using a user named 'bob', you will need to grant a mysql user 'bob' access to the 'rpush_test'mysql database.
To switch between ActiveRecord and Redis, set theCLIENT
environment variable to eitheractive_record
orredis
.
About
The push notification service for Ruby.