Git Product home page Git Product logo

fcmpush's Introduction

Fcmpush Build Status Gem Version

Fcmpush is an Firebase Cloud Messaging(FCM) Client. It implements FCM HTTP v1 API, including Auto Refresh access_token feature, and batch request!! This gem supports HTTP v1 API only, NOT supported legacy HTTP protocol.

fcmpush is highly inspired by andpush gem.

Installation

Add this line to your application's Gemfile:

gem 'fcmpush'

And then execute:

$ bundle

Or install it yourself as:

$ gem install fcmpush

Usage

on Rails, config/initializers/fcmpush.rb

Fcmpush.configure do |config|
  ## for message push
  # firebase web console => project settings => service account => firebase admin sdk => generate new private key

  # pass string of path to credential file to config.json_key_io
  config.json_key_io = "#{Rails.root}/path/to/service_account_credentials.json"
  # Or content of json key file wrapped with StringIO
  # config.json_key_io = StringIO.new('{ ... }')

  # Or set environment variables
  # ENV['GOOGLE_ACCOUNT_TYPE'] = 'service_account'
  # ENV['GOOGLE_CLIENT_ID'] = '000000000000000000000'
  # ENV['GOOGLE_CLIENT_EMAIL'] = '[email protected]'
  # ENV['GOOGLE_PRIVATE_KEY'] = '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n\'

  ## for topic subscribe/unsubscribe because they use regacy auth
  # firebase web console => project settings => cloud messaging => Project credentials => Server key
  # @deprecated: This attribute will be removed next version.
  config.server_key = 'your firebase server key'
  # Or set environment variables
  # @deprecated: This attribute will be removed next version.
  # ENV['FCM_SERVER_KEY'] = 'your firebase server key'

  # Proxy ENV variables are considered by default if set by net/http, but you can explicitly define your proxy host here
  # user and password are optional
  # config.proxy = { uri: "http://proxy.host:3128", user: nil, password: nil }
  # explicitly disable using proxy, even ignore environment variables if set
  # config.proxy = false

  # HTTP connection open and read timeouts (in seconds) are set for all client requests.
  # If unset, the default values for Net::HTTP::Persistent are used (currently 60 seconds).
  # config.open_timeout = 30
  # config.read_timeout = 15
end

for more detail. see here.

push message

require 'fcmpush'

project_id   = "..." # Your project_id
device_token = "..." # The device token of the device you'd like to push a message to

client  = Fcmpush.new(project_id)
payload = { # ref. https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages
  message: {
    token: device_token,
    notification: {
      title: "this is title",
      body: "this is message body"
    }
  }
}

response = client.push(payload)

json = response.json
json[:name] # => "projects/[your_project_id]/messages/0:1571037134532751%31bd1c9631bd1c96"

push messages in batch

require 'fcmpush'

project_id   = "..." # Your project_id
device_tokens = ["...A", "...B", "...C"] # The device token of the device you'd like to push a message to

client  = Fcmpush.new(project_id)

payloads = device_tokens.map do |token|
  { # ref. https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages
    message: {
      token: token,
      notification: {
        title: "this is title",
        body: "this is message body"
      }
    }
  }
end

response = client.batch_push(payloads)

response_array = response.json
response_array.first[:name] # => "projects/[your_project_id]/messages/0:1571037134532751%31bd1c9631bd1c96"

topic subscribe/unsubscribe

require 'fcmpush'

project_id   = "..." # Your project_id
topic = "your_topic_name"
device_tokens = ["device_tokenA", "device_tokenB", ...] # The device tokens of the device you'd like to subscribe

client  = Fcmpush.new(project_id)

response = client.subscribe(topic, device_tokens)
# response = client.unsubscribe(topic, device_tokens)

json = response.json
json[:results] # => [{}, {"error":"NOT_FOUND"}, ...]  ref. https://developers.google.com/instance-id/reference/server#example_result_3

Performance

  • fcmpush's performance is good. (about the same as fastest one!)
  • And fcmpush supports batch request feature! batch request not use in benchmarking. Because, it not supported by other gems.
  • andpush is the fastest, but it uses legacy HTTP API.
  • fcmpush is fastest in gems using V1 HTTP API(fcmpush, google-api-fcm, firebase_cloud_messenger).
  • I excluded google-api-fcm gem because it can't run in ruby 3.
  • benchmark detail is here.
Warming up --------------------------------------
             andpush     1.000  i/100ms
                 fcm     1.000  i/100ms
             fcmpush     1.000  i/100ms
firebase_cloud_messenger
                         1.000  i/100ms
Calculating -------------------------------------
             andpush     19.236  (±10.4%) i/s -     95.000  in   5.048723s
                 fcm      6.536  (±15.3%) i/s -     33.000  in   5.083179s
             fcmpush     18.871  (±10.6%) i/s -     93.000  in   5.031072s
firebase_cloud_messenger
                          3.238  (± 0.0%) i/s -     17.000  in   5.265755s

Comparison:
             andpush:       19.2 i/s
             fcmpush:       18.9 i/s - same-ish: difference falls within error
                 fcm:        6.5 i/s - 2.94x  (± 0.00) slower
firebase_cloud_messenger:        3.2 i/s - 5.94x  (± 0.00) slower

Experimental Features

  • proxy
    • LIMITATION: support http_proxy only. NOT supports HTTPS_PROXY.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/miyataka/fcmpush.

License

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

fcmpush's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

fcmpush's Issues

Raise custom error if missing configuration

This is an improvement suggestion.

How?

  • #push method is called
  • config.json_key_io is nil
  • Some Google's env var is nil

Reference: https://github.com/miyataka/fcmpush#usage

What?

The following error is raised:

NoMethodError:
 undefined method `gsub' for nil:NilClass

Suggestion

Rescue the NoMethodError and raises a custom error with information regarding the missing configuration


Thanks for your time and for the good work.

Using fcmpush behind a proxy

I i use fcmpush behind a proxy, the http_proxy or https_proxy environment variable is not considered, so the push will run into timeout:

A network error occurred: Net::OpenTimeout (Failed to open TCP connection to fcm.googleapis.com:443 (execution expired))

It would be nice, if i can set a proxy server in the fcmpush configuration, which is used for the requests, like this:

Fcmpush.configure do |config|
  config.json_key_io = "#{Rails.root}/path/to/service_account_credentials.json"
  config.server_key = 'your firebase server key'
  config.proxy_server = 'http://myproxyserver:3128'
end

Otherwise if the environment variables http_proxy / https_proxy / HTTP_PROXY / HTTPS_PROXY would be used if set, might be another approach.

configuring json_key_io as StringIO breaks Fcmpush config if google reponds with 403

I've noticed when setting up fcmpush that it would break if getting a 403 from push call.

I noticed it since I have multiple projects and tried to send to a device token generated by the other project.

I got the following response:

Fcmpush::Forbidden: Receieved an error response 403 Forbidden: {
  "error": {
    "code": 403,
    "message": "SenderId mismatch",
    "status": "PERMISSION_DENIED",
    "details": [
      {
        "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError",
        "errorCode": "SENDER_ID_MISMATCH"
      }
    ]
  }
}

subsequent calls to Fcmpush.new(project_id) would throw this error: MultiJson::ParseError: compile error

This is because I guess it was trying to re-auth against google and thus calling .read on json_key_io.
However reading the same StringIO multiple times would just return empty string on subsequent calls.

2.4.10 :005 > sio = StringIO.new("test")
 => #<StringIO:0x00007fc49d683670>
2.4.10 :006 > sio.read
 => "test"
2.4.10 :007 > sio.read
 => ""

There might be some other edgecases when specifying json_key_io as an instance of StringIO

Is there some other ruby-class that would provide the same interface as IO but keeping string buffer upon read?

My ugly hack as of now was just to wrap the string in a struct with an accessor for the attribute read

config.json_key_io = Struct.new(:read).new credentials

Sender id mismatch

Always getting this error
Please make clear overview which steps to take with fcm
I think but don’t understand why the android app is using something different as the fcm credentials

Server Key Deprecation

I recently received a notice from FCM indicating that the Server Key feature will be deprecated on June 20, 2024.

CleanShot 2023-12-25 at 09 21 13

However, I'm not sure if he meant the auth method that would affect subscribe/unsubscribe or if the entire API would be affected. Google developer documentation is so hard to read.

CleanShot 2023-12-25 at 09 24 08

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.