simple_fcm 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 7f5835dfac2bd3ba0b04f1da11a401bc99f64660286418529a9a5050ed3ef236
4
+ data.tar.gz: 5c1114761715ecd29153cfebb6fbbeffe2dfce1968acc6a5aa4b2463eb1d53ea
5
+ SHA512:
6
+ metadata.gz: 7579a0e9c42034965f92f384b1faa9778038e4536b9b7ddbb4964886eff0edd116530dfe126b974cc5c03d26a7643e263ad24d373cef0423f5f5f4104a76faf5
7
+ data.tar.gz: fc467f2fcb1f5005c2b7f5e8c29e6e36d72bfcde66e398afaa950055e77569ca56121d62dfe215028d46b239ad785f2b1a1d29cd4231087f88cc2b6a915e29c8
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.standard.yml ADDED
@@ -0,0 +1,3 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/standardrb/standard
3
+ ruby_version: 3.0
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-06-24
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Chris Gaffney
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # SimpleFCM
2
+
3
+ SimpleFCM is a minimalist client for Firebase Cloud Messaging to send Push
4
+ Notifications.
5
+
6
+ ## Installation
7
+
8
+ Install the gem and add to the application's Gemfile by executing:
9
+
10
+ $ bundle add simple_fcm
11
+
12
+ If bundler is not being used to manage dependencies, install the gem by executing:
13
+
14
+ $ gem install simple_fcm
15
+
16
+ ## Usage
17
+
18
+ ```ruby
19
+ # Initialize a new client for talking to Firebase Cloud Messaging. Client.new
20
+ # takes an optional parameter which is either the path to a service account
21
+ # config file or the raw config JSON. Not passing a config or passing nil will
22
+ # pull the configuration from environment variables.
23
+ client = SimpleFCM::Client.new("path/to/service_account.json")
24
+
25
+ # See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages/send
26
+ client.push({
27
+ message: {
28
+ token: device.token,
29
+ data: {
30
+ message: "Jinkies! Something happened",
31
+ id: snitch.id,
32
+ }
33
+ }
34
+ })
35
+ ```
36
+
37
+ ## Development
38
+
39
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
40
+
41
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
42
+
43
+ ## Contributing
44
+
45
+ Bug reports and pull requests are welcome on GitHub at https://github.com/deadmanssnitch/simple_fcm. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/deadmanssnitch/simple_fcm/blob/main/CODE_OF_CONDUCT.md).
46
+
47
+ ## License
48
+
49
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
50
+
51
+ ## Code of Conduct
52
+
53
+ Everyone interacting in the SimpleFCM project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/deadmanssnitch/simple_fcm/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "standard/rake"
9
+
10
+ task default: %i[spec standard]
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "faraday"
4
+
5
+ module SimpleFCM
6
+ class AuthorizationMiddleware < Faraday::Middleware
7
+ # Automatically refresh the access token when it is due to expire within
8
+ # the next 3 minutes.
9
+ DEFAULT_EXPIRY_THRESHOLD = 180
10
+
11
+ def initialize(app, credentials, expiry_threshold: DEFAULT_EXPIRY_THRESHOLD)
12
+ @credentials = credentials
13
+ @expiry_threshold = expiry_threshold
14
+
15
+ if @expiry_threshold < 0
16
+ raise ArugmentError, "expiry_threshold must be greater than or equal to 0"
17
+ end
18
+
19
+ super(app)
20
+ end
21
+
22
+ # Force a refresh of the access token
23
+ def refresh!
24
+ fetched = @credentials.fetch_access_token!
25
+
26
+ @token = fetched["access_token"]
27
+ @type = fetched["token_type"]
28
+ @expires_at = Time.now.utc + fetched["expires_in"]
29
+ end
30
+
31
+ # Returns true when the access token should be fetched or refreshed.
32
+ def refresh?
33
+ @expires_at.nil? || @expires_at <= (Time.now.utc - @expiry_threshold)
34
+ end
35
+
36
+ def on_request(env)
37
+ if refresh?
38
+ refresh!
39
+ end
40
+
41
+ env.request_headers["Authorization"] = "#{@type} #{@token}"
42
+ end
43
+ end
44
+ end
45
+
46
+ Faraday::Request.register_middleware(simple_fcm_auth: SimpleFCM::AuthorizationMiddleware)
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "googleauth/service_account"
4
+
5
+ require "simple_fcm/error"
6
+ require "simple_fcm/authorization_middleware"
7
+
8
+ module SimpleFCM
9
+ class Client
10
+ ENDPOINT = "https://fcm.googleapis.com"
11
+ private_constant :ENDPOINT
12
+
13
+ SCOPE = "https://www.googleapis.com/auth/firebase.messaging"
14
+ private_constant :SCOPE
15
+
16
+ # @param config [string, nil] Either the path to a service account json
17
+ # config file, the contents of that file as a string, or nil to load
18
+ # config options from environment configs.
19
+ #
20
+ # @yield [conn] Yields into the connection building process
21
+ # @yieldparam [Faraday::Connection] The backend connection used for requests
22
+ def initialize(config = nil)
23
+ @credentials = build_credentials(config)
24
+
25
+ @client = Faraday::Connection.new(ENDPOINT) do |conn|
26
+ conn.request :simple_fcm_auth, @credentials
27
+ conn.request :json
28
+ conn.response :json, parser_options: {symbolize_names: true}
29
+
30
+ if block_given?
31
+ yield conn
32
+ end
33
+ end
34
+ end
35
+
36
+ # Send a push notification to a device or topic through Firebase Cloud
37
+ # Messaging.
38
+ #
39
+ # @see https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages/send
40
+ #
41
+ # @param message [Hash] Message payload
42
+ #
43
+ # @raise [APIError]
44
+ # @return [string] Message ID returned by the API
45
+ def push(message)
46
+ resp = @client.post("/v1/projects/#{project_id}/messages:send", message)
47
+
48
+ if !resp.success?
49
+ raise ::SimpleFCM::APIError, resp
50
+ end
51
+
52
+ resp.body[:name]
53
+ end
54
+
55
+ private
56
+
57
+ def build_credentials(config = nil)
58
+ # Config options are pulled from environment variables.
59
+ if config.nil?
60
+ return Google::Auth::ServiceAccountCredentials.make_creds(scope: SCOPE)
61
+ end
62
+
63
+ if !config.is_a?(String)
64
+ raise ArgumentError, "config must be a string"
65
+ end
66
+
67
+ if File.exist?(config)
68
+ config = File.read(config)
69
+ end
70
+
71
+ ::Google::Auth::ServiceAccountCredentials.make_creds(
72
+ json_key_io: StringIO.new(config),
73
+ scope: SCOPE
74
+ )
75
+ end
76
+
77
+ def project_id
78
+ @credentials.project_id
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleFCM
4
+ # Error is the root class for all errors generated by SimpleFCM.
5
+ class Error < StandardError; end
6
+
7
+ # API errors are raised when there is an issue making a request to the
8
+ # Firebase Cloud Messaging API.
9
+ #
10
+ # @see https://firebase.google.com/docs/reference/fcm/rest/v1/ErrorCode
11
+ class APIError < Error
12
+ attr_reader :code
13
+ attr_reader :status
14
+ attr_reader :details
15
+
16
+ def initialize(response)
17
+ if response.body.is_a?(String)
18
+ @code = response.status
19
+
20
+ super("FCM returned #{response.status}: #{response.body}")
21
+ else
22
+ payload = response.body[:error]
23
+
24
+ @code = payload[:code]
25
+ @status = payload[:status]
26
+ @details = payload[:details]
27
+
28
+ super(payload[:message])
29
+ end
30
+ end
31
+
32
+ def retriable?
33
+ true
34
+ end
35
+
36
+ # exception is called instead of `new` when using the form:
37
+ # raise SimpleFCM::APIError, response
38
+ #
39
+ # @param response [Faraday::Response]
40
+ def self.exception(response)
41
+ klass =
42
+ case response.status
43
+ when 400 then InvalidArgumentError
44
+ when 401 then ThirdPartyAuthenticationError
45
+ when 403 then SenderMismatchError
46
+ when 404 then UnregisteredError
47
+ when 429 then QuotaExceededError
48
+ when 500 then InternalServerError
49
+ when 503 then ServiceUnavailableError
50
+ else
51
+ APIError
52
+ end
53
+
54
+ klass.new(response)
55
+ end
56
+ end
57
+
58
+ # InvalidArgumentError is raised when an invalid parameter or request payload
59
+ # was sent to Firebase Cloud Messaging.
60
+ #
61
+ # @see https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages/send
62
+ # @see https://firebase.google.com/docs/reference/fcm/rest/v1/ErrorCode
63
+ class InvalidArgumentError < APIError
64
+ def retriable?
65
+ false
66
+ end
67
+ end
68
+
69
+ # ThirdPartyAuthenticationError is raised when sending a message targeted at
70
+ # an iOS device or sending a web push registration and the third party
71
+ # credentials are incorrect.
72
+ #
73
+ # @see https://firebase.google.com/docs/reference/fcm/rest/v1/ErrorCode
74
+ class ThirdPartyAuthenticationError < APIError
75
+ def retriable?
76
+ false
77
+ end
78
+ end
79
+
80
+ # SenderMismatchError is raised when the given Sender ID is not tied to the
81
+ # registration token the message is being sent to.
82
+ #
83
+ # @see https://firebase.google.com/docs/reference/fcm/rest/v1/ErrorCode
84
+ class SenderMismatchError < APIError
85
+ def retriable?
86
+ false
87
+ end
88
+ end
89
+
90
+ # UnregisteredError is raised when the given device token is no longer valid.
91
+ #
92
+ # @see https://firebase.google.com/docs/reference/fcm/rest/v1/ErrorCode
93
+ class UnregisteredError < APIError
94
+ def retriable?
95
+ false
96
+ end
97
+ end
98
+
99
+ # QuotaExceededError is raised when the quota for sending push notifications
100
+ # to either a device or topic has been exceeded. Firebase recommends using an
101
+ # exponential backoff with a minimum delay of 1 minute before retrying the
102
+ # message.
103
+ #
104
+ # @see https://firebase.google.com/docs/reference/fcm/rest/v1/ErrorCode
105
+ class QuotaExceededError < APIError
106
+ def retriable?
107
+ true
108
+ end
109
+ end
110
+
111
+ # InternalServerError is raised when Firebase encountered an unknown internal
112
+ # error.
113
+ #
114
+ # @see https://firebase.google.com/docs/reference/fcm/rest/v1/ErrorCode
115
+ class InternalServerError < APIError
116
+ def retriable?
117
+ true
118
+ end
119
+ end
120
+
121
+ # ServiceUnavailableError is raised when Firebase's push notification
122
+ # services are overloaded in some way.
123
+ #
124
+ # @see https://firebase.google.com/docs/reference/fcm/rest/v1/ErrorCode
125
+ class ServiceUnavailableError < APIError
126
+ def retriable?
127
+ true
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleFCM
4
+ VERSION = "0.1.0"
5
+ end
data/lib/simple_fcm.rb ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "simple_fcm/version"
4
+ require "simple_fcm/error"
5
+ require "simple_fcm/client"
6
+
7
+ module SimpleFCM
8
+ end
metadata ADDED
@@ -0,0 +1,88 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: simple_fcm
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Chris Gaffney
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2024-06-26 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: faraday
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: googleauth
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.0'
41
+ description: |
42
+ SimpleFCM is a minimal client for sending push notifications using the the
43
+ Firebase Cloud Messaging V1 API.
44
+ email:
45
+ - chris@collectiveidea.com
46
+ executables: []
47
+ extensions: []
48
+ extra_rdoc_files: []
49
+ files:
50
+ - ".rspec"
51
+ - ".standard.yml"
52
+ - CHANGELOG.md
53
+ - CODE_OF_CONDUCT.md
54
+ - LICENSE.txt
55
+ - README.md
56
+ - Rakefile
57
+ - lib/simple_fcm.rb
58
+ - lib/simple_fcm/authorization_middleware.rb
59
+ - lib/simple_fcm/client.rb
60
+ - lib/simple_fcm/error.rb
61
+ - lib/simple_fcm/version.rb
62
+ homepage: https://github.com/deadmanssnitch/simple_fcm
63
+ licenses:
64
+ - MIT
65
+ metadata:
66
+ homepage_uri: https://github.com/deadmanssnitch/simple_fcm
67
+ source_code_uri: https://github.com/deadmanssnitch/simple_fcm
68
+ changelog_uri: https://github.com/deadmanssnitch/simple_fcm/blog/main/CHANGELOG.md
69
+ post_install_message:
70
+ rdoc_options: []
71
+ require_paths:
72
+ - lib
73
+ required_ruby_version: !ruby/object:Gem::Requirement
74
+ requirements:
75
+ - - ">="
76
+ - !ruby/object:Gem::Version
77
+ version: 3.0.0
78
+ required_rubygems_version: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ requirements: []
84
+ rubygems_version: 3.5.14
85
+ signing_key:
86
+ specification_version: 4
87
+ summary: Firebase Cloud Messaging V1 API Client
88
+ test_files: []