modulofcm 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: 756a3db83bff049923812f16b3c306b65acccd9878d8e23888d4fc6972d6b860
4
+ data.tar.gz: 90274c6c4c7bda319d1e7c804f1fbfd14083501c6712724587ac68b4a1ec83b7
5
+ SHA512:
6
+ metadata.gz: 62460e72622514d6607bace864a8f9befe393b3b892366cee5797e075a49d37679917f6a3762a3be9f9c7033b16a7fb9930868cff1ec956621b2892674028d48
7
+ data.tar.gz: 3115a67425c392403e781d828390fee9ced2ec5b11a0b2edb48f49cc6fa7a2447767cee1e08e83557663631d4c6a4832b0d4d0dd7fbe5b49e78217b05381270f
data/.rubocop.yml ADDED
@@ -0,0 +1,252 @@
1
+ # The behavior of RuboCop can be controlled via the .rubocop.yml
2
+ # configuration file. It makes it possible to enable/disable
3
+ # certain cops (checks) and to alter their behavior if they accept
4
+ # any parameters. The file can be placed either in your home
5
+ # directory or in some project directory.
6
+ #
7
+ # RuboCop will start looking for the configuration file in the directory
8
+ # where the inspected file is and continue its way up to the root directory.
9
+ #
10
+ # See https://docs.rubocop.org/rubocop/configuration
11
+
12
+ inherit_mode:
13
+ merge:
14
+ - Exclude
15
+ - Include
16
+
17
+ AllCops:
18
+ TargetRubyVersion: 3.0
19
+
20
+ # No suggestions since the gem is the sole truth for rubocop configuration.
21
+ SuggestExtensions: false
22
+
23
+ # Enable new cops by default
24
+ NewCops: enable
25
+
26
+ # Excluding most directories with generated files and directories with configuration files.
27
+ Exclude:
28
+ - 'bin'
29
+ - '**/Gemfile'
30
+ - '**/Guardfile'
31
+ - '**/Rakefile'
32
+ - 'test/**/*'
33
+ - 'node_modules/**/*'
34
+ - 'spec/**/*'
35
+
36
+ # Checks if String literals are using single quotes when no interpolation is required
37
+ Style/StringLiterals:
38
+ Enabled: true
39
+ EnforcedStyle: single_quotes
40
+ ConsistentQuotesInMultiline: false
41
+
42
+ # Checks if the quotes used for quoted symbols are single quotes when no interpolation is required
43
+ Style/QuotedSymbols:
44
+ Enabled: true
45
+ EnforcedStyle: same_as_string_literals
46
+
47
+ # This cop checks for uses of literal strings converted to a symbol where a literal symbol could be used instead.
48
+ Lint/SymbolConversion:
49
+ Enabled: true
50
+ EnforcedStyle: strict
51
+
52
+ # Useless cop. It checks for unnecessary safe navigations.
53
+ # Example:
54
+ # obj&.a && obj.b
55
+ # Triggers rubocop error: it requires to add safe navigation for "obj.b" call => "obj&.b".
56
+ # but it is not necessary. obj&.a will return nil if obj is nil, and it will stop
57
+ # execution of the operation because `&&` right part executes only when left part is truthy.
58
+ Lint/SafeNavigationConsistency:
59
+ Enabled: false
60
+
61
+ # Checks for places where keyword arguments can be used instead of boolean arguments when defining methods.
62
+ # Disabled because moving from default arguments to keywords is not that easy.
63
+ Style/OptionalBooleanParameter:
64
+ Enabled: false
65
+
66
+ # Checks for use of the lambda.(args) syntax.
67
+ # Disabled while the Ruby team has not voted on this.
68
+ Style/LambdaCall:
69
+ Enabled: false
70
+ EnforcedStyle: braces
71
+
72
+ # Checks for presence or absence of braces around hash literal as a last array item depending on configuration.
73
+ # Disabled because it would break a lot of permitted_params definitions
74
+ Style/HashAsLastArrayItem:
75
+ Enabled: false
76
+
77
+ # Checks for grouping of accessors in class and module bodies.
78
+ # Useless.
79
+ Style/AccessorGrouping:
80
+ Enabled: false
81
+
82
+ # Makes our lives happier: we don't need to disable it in each case/when method
83
+ # with more than 5 "when"s.
84
+ Metrics/CyclomaticComplexity:
85
+ Max: 10
86
+
87
+ # Commonly used screens these days easily fit more than 80 characters.
88
+ Layout/LineLength:
89
+ Max: 120
90
+
91
+ # Too short methods lead to extraction of single-use methods, which can make
92
+ # the code easier to read (by naming things), but can also clutter the class
93
+ Metrics/MethodLength:
94
+ Max: 25
95
+
96
+ # The guiding principle of classes is SRP, SRP can't be accurately measured by LoC
97
+ Metrics/ClassLength:
98
+ Max: 1500
99
+
100
+ # No space makes the method definition shorter and differentiates
101
+ # from a regular assignment.
102
+ Layout/SpaceAroundEqualsInParameterDefault:
103
+ EnforcedStyle: no_space
104
+
105
+ # We do not need to support Ruby 1.9, so this is good to use.
106
+ Style/SymbolArray:
107
+ Enabled: true
108
+
109
+ # Most readable form.
110
+ Layout/HashAlignment:
111
+ EnforcedHashRocketStyle: table
112
+ EnforcedColonStyle: table
113
+
114
+ # Mixing the styles looks just silly.
115
+ Style/HashSyntax:
116
+ EnforcedStyle: ruby19_no_mixed_keys
117
+
118
+ # has_key? and has_value? are far more readable than key? and value?
119
+ Style/PreferredHashMethods:
120
+ Enabled: false
121
+
122
+ # String#% is by far the least verbose and only object oriented variant.
123
+ Style/FormatString:
124
+ EnforcedStyle: percent
125
+
126
+ # Annotated or template are too verbose and rarely needed.
127
+ Style/FormatStringToken:
128
+ EnforcedStyle: unannotated
129
+
130
+ Style/CollectionMethods:
131
+ Enabled: true
132
+ PreferredMethods:
133
+ # inject seems more common in the community.
134
+ reduce: "inject"
135
+
136
+ # Either allow this style or don't. Marking it as safe with parenthesis
137
+ # is silly. Let's try to live without them for now.
138
+ Style/ParenthesesAroundCondition:
139
+ AllowSafeAssignment: false
140
+ Lint/AssignmentInCondition:
141
+ AllowSafeAssignment: false
142
+
143
+ # A specialized exception class will take one or more arguments and construct the message from it.
144
+ # So both variants make sense.
145
+ Style/RaiseArgs:
146
+ Enabled: false
147
+
148
+ # Indenting the chained dots beneath each other is not supported by this cop,
149
+ # see https://github.com/bbatsov/rubocop/issues/1633
150
+ Layout/MultilineOperationIndentation:
151
+ Enabled: false
152
+
153
+ # Fail is an alias of raise. Avoid aliases, it's more cognitive load for no gain.
154
+ # The argument that fail should be used to abort the program is wrong too,
155
+ # there's Kernel#abort for that.
156
+ Style/SignalException:
157
+ EnforcedStyle: only_raise
158
+
159
+ # Suppressing exceptions can be perfectly fine, and be it to avoid to
160
+ # explicitly type nil into the rescue since that's what you want to return,
161
+ # or suppressing LoadError for optional dependencies
162
+ Lint/SuppressedException:
163
+ Enabled: false
164
+
165
+ # { ... } for multi-line blocks is okay, follow Weirichs rule instead:
166
+ # https://web.archive.org/web/20140221124509/http://onestepback.org/index.cgi/Tech/Ruby/BraceVsDoEnd.rdoc
167
+ Style/BlockDelimiters:
168
+ Enabled: false
169
+
170
+ # do / end blocks should be used for side effects,
171
+ # methods that run a block for side effects and have
172
+ # a useful return value are rare, assign the return
173
+ # value to a local variable for those cases.
174
+ Style/MethodCalledOnDoEndBlock:
175
+ Enabled: true
176
+
177
+ # Enforcing the names of variables? To single letter ones? Just no.
178
+ Style/SingleLineBlockParams:
179
+ Enabled: false
180
+
181
+ # Shadowing outer local variables with block parameters is often useful
182
+ # to not reinvent a new name for the same thing, it highlights the relation
183
+ # between the outer variable and the parameter. The cases where it's actually
184
+ # confusing are rare, and usually bad for other reasons already, for example
185
+ # because the method is too long.
186
+ Lint/ShadowingOuterLocalVariable:
187
+ Enabled: false
188
+
189
+ # Check with yard instead.
190
+ Style/Documentation:
191
+ Enabled: false
192
+
193
+ # This is just silly. Calling the argument `other` in all cases makes no sense.
194
+ Naming/BinaryOperatorParameterName:
195
+ Enabled: false
196
+
197
+ # Disable frozen string
198
+ Style/FrozenStringLiteralComment:
199
+ Enabled: false
200
+
201
+ # Disable No ASCII char in comments
202
+ Style/AsciiComments:
203
+ Enabled: false
204
+
205
+ # Disable ordered Gems By ascii
206
+ Bundler/OrderedGems:
207
+ Enabled: false
208
+
209
+ # Change ABC max value
210
+ Metrics/AbcSize:
211
+ Max: 35
212
+
213
+ # Disable empty method in one line
214
+ Style/EmptyMethod:
215
+ EnforcedStyle: expanded
216
+
217
+ # Disable max height block
218
+ Metrics/BlockLength:
219
+ Enabled: true
220
+ Exclude:
221
+ - 'app/admin/**/*'
222
+ - 'lib/tasks/**/*'
223
+
224
+ # Checks if empty lines around the bodies of classes match the configuration.
225
+ Layout/EmptyLinesAroundClassBody:
226
+ EnforcedStyle: empty_lines
227
+ # Checks if empty lines around the bodies of modules match the configuration.
228
+ Layout/EmptyLinesAroundModuleBody:
229
+ EnforcedStyle: empty_lines
230
+
231
+ # Enforces the consistent usage of %-literal delimiters.
232
+ Style/PercentLiteralDelimiters:
233
+ PreferredDelimiters:
234
+ default: '()'
235
+ '%i': '[]'
236
+ '%I': '[]'
237
+ '%r': '{}'
238
+ '%w': '[]'
239
+ '%W': '[]'
240
+
241
+ # Unnecessary cop. In what universe "A || B && C" or "A && B || C && D" is ambiguous? looks
242
+ # like a cop for those who can't in boolean.
243
+ Lint/AmbiguousOperatorPrecedence:
244
+ Enabled: false
245
+
246
+ # Checks for simple usages of parallel assignment.
247
+ Style/ParallelAssignment:
248
+ Enabled: false
249
+
250
+ # Checks the style of children definitions at classes and modules.
251
+ Style/ClassAndModuleChildren:
252
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,6 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-04-24
4
+
5
+ - Initial release
6
+ - Send Legacy push notifications.
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at rails@modulotech.fr. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Modulotech
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,77 @@
1
+ # Modulofcm
2
+
3
+ Firebase Cloud Messaging client library
4
+
5
+ ## Installation
6
+
7
+ Install the gem and add to the application's Gemfile by executing:
8
+
9
+ $ bundle add modulofcm
10
+
11
+ If bundler is not being used to manage dependencies, install the gem by executing:
12
+
13
+ $ gem install modulofcm
14
+
15
+ ## Usage
16
+
17
+ ```ruby
18
+ Modulofcm.configure do |config|
19
+ config.client(:legacy_client) do |client|
20
+ client.api_key = 'My Legacy HTTP API key - will cease to function after June 2024.'
21
+ end
22
+
23
+ config.client(:new_client) do |client|
24
+ client.api_token = 'my_token'
25
+ client.google_application_credentials_path = ''
26
+ end
27
+ end
28
+
29
+ # Any data you want to add to your notification
30
+ data = {
31
+ id: 232_342,
32
+ key: 'asd9adfiu6bn',
33
+ mission_id: 234_323
34
+ }
35
+
36
+ # All keyword arguments are optional and references a field in Firebase documentation:
37
+ # Legacy API: https://firebase.google.com/docs/cloud-messaging/http-server-ref
38
+ # APIv1 : https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages
39
+ # title: The notification's title.
40
+ # Legacy: `notification.title`
41
+ # APIv1: `message.notification.title`
42
+ # body: The notification's body text.
43
+ # Legacy: `notification.body`
44
+ # APIv1: `message.notification.body`,
45
+ # sound: The sound to play when the device receives the notification.
46
+ # Legacy: `notification.sound`
47
+ # APIv1:
48
+ # android: `message.android.sound`
49
+ # ios: `message.apns.aps.sound`
50
+ # content_available: Allow to awaken the iOS app.
51
+ # Legacy: `content_available` - ignored on non-iOS devices.
52
+ # APIv1:
53
+ # ios: `message.apns.aps.content-available`
54
+ # data: Arbitrary key/value payload, which must be UTF-8 encoded. The key should not be a reserved word ("from", "message_type", or any word starting with "google" or "gcm").
55
+ # Legacy: `data`
56
+ # APIv1: `message.data`
57
+ Modulofcm.client(:legacy_client).push('Legacy device registration token', data: data, title: 'My title', body: 'The body', sound: 'notif.caf', content_available: true)
58
+ Modulofcm.client(:new_client).push('FCM new token', data: data, title: 'My title', body: 'The body', sound: 'notif.caf', content_available: true)
59
+ ```
60
+
61
+ ## Development
62
+
63
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
64
+
65
+ 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).
66
+
67
+ ## Contributing
68
+
69
+ Bug reports and pull requests are welcome on GitHub at https://github.com/modulotech/modulofcm. 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/modulotech/modulofcm/blob/master/CODE_OF_CONDUCT.md).
70
+
71
+ ## License
72
+
73
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
74
+
75
+ ## Code of Conduct
76
+
77
+ Everyone interacting in the Modulofcm project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/modulotech/modulofcm/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rubocop/rake_task"
5
+
6
+ RuboCop::RakeTask.new
7
+
8
+ task default: :rubocop
@@ -0,0 +1,172 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'response'
4
+
5
+ # rubocop:disable Metrics/ParameterLists
6
+ module Modulofcm
7
+
8
+ class Client
9
+
10
+ attr_reader :name, :api_key, :api_token, :google_application_credentials_path, :firebase_project_id, :mode
11
+
12
+ def initialize(name:, api_key: nil, api_token: nil, google_application_credentials_path: nil,
13
+ firebase_project_id: nil)
14
+ @name = name.to_sym
15
+ @api_key = api_key
16
+ @api_token = api_token
17
+ @google_application_credentials_path = google_application_credentials_path
18
+ @firebase_project_id = firebase_project_id
19
+ @mode = :api_v1
20
+ end
21
+
22
+ # All keyword arguments are optional and references a field in Firebase documentation:
23
+ # Legacy API: https://firebase.google.com/docs/cloud-messaging/http-server-ref
24
+ # APIv1 : https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages
25
+ # title: The notification's title.
26
+ # Legacy: `notification.title`
27
+ # APIv1: `message.notification.title`
28
+ # body: The notification's body text.
29
+ # Legacy: `notification.body`
30
+ # APIv1: `message.notification.body`,
31
+ # sound: The sound to play when the device receives the notification.
32
+ # Legacy: `notification.sound`
33
+ # APIv1:
34
+ # android: `message.android.sound`
35
+ # ios: `message.apns.aps.sound`
36
+ # content_available: Allow to awaken the iOS app.
37
+ # Legacy: `content_available` - ignored on non-iOS devices.
38
+ # APIv1:
39
+ # ios: `message.apns.aps.content-available`
40
+ # data: Arbitrary key/value payload, which must be UTF-8 encoded. The key should not be a reserved word
41
+ # ("from", "message_type", or any word starting with "google" or "gcm").
42
+ # Legacy: `data`
43
+ # APIv1: `message.data`
44
+ def push(token, data: nil, title: nil, body: nil, sound: nil, content_available: true)
45
+ raise NoTokenError if token.blank?
46
+ raise EmptyNotificationError if data.blank? && title.blank? && body.blank?
47
+
48
+ case @mode
49
+ when :legacy
50
+ push_legacy(token, data: data, title: title, body: body, sound: sound, content_available: content_available)
51
+ else
52
+ raise NotImplementedError, 'Only Legacy notifications are supported'
53
+ # push_v1(token, data: data, title: title, body: body, sound: sound, content_available: content_available)
54
+ end
55
+ end
56
+
57
+ %w[api_key api_token firebase_project_id google_application_credentials_path].each do |attribute|
58
+ define_method("#{attribute}=") do |value|
59
+ instance_variable_set(:"@#{attribute}", value)
60
+
61
+ update_mode
62
+ end
63
+ end
64
+
65
+ private
66
+
67
+ def update_mode
68
+ api_v1_fields_all_present = [api_token, google_application_credentials_path, firebase_project_id].all?(&:present?)
69
+ api_key_blank = api_key.blank?
70
+
71
+ @mode = if api_v1_fields_all_present || api_key_blank
72
+ :api_v1
73
+ else
74
+ :legacy
75
+ end
76
+
77
+ @client = case @mode
78
+ when :legacy
79
+ FCM.new(api_key)
80
+ else
81
+ FCM.new(api_token, google_application_credentials_path, firebase_project_id)
82
+ end
83
+ end
84
+
85
+ def push_legacy(token, data: nil, title: nil, body: nil, sound: nil, content_available: true)
86
+ payload = default_payload(content_available)
87
+
88
+ handle_data(payload, data)
89
+ handle_notification(payload, body, sound, title)
90
+
91
+ make_legacy_response(@client.send(token, payload))
92
+ end
93
+
94
+ def push_v1(token, data: nil, title: nil, body: nil, sound: nil, content_available: true)
95
+ payload = default_payload(content_available)
96
+ payload[:token] = token
97
+
98
+ handle_data(payload, data)
99
+ handle_notification(payload, body, sound, title)
100
+
101
+ make_v1_response(@client.send_v1(payload))
102
+ end
103
+
104
+ def default_payload(content_available)
105
+ case @mode
106
+ when :legacy
107
+ {
108
+ content_available: !content_available.nil?
109
+ }
110
+ else
111
+ {
112
+ android: {},
113
+ apns: {
114
+ aps: {
115
+ 'content-available' => content_available ? 1 : 0
116
+ }
117
+ }
118
+ }
119
+ end
120
+ end
121
+
122
+ def handle_notification(payload, body, sound, title)
123
+ payload[:notification] = {} if [title, body, sound].any?(&:present?)
124
+
125
+ { title: title, body: body, sound: sound }.each do |key, value|
126
+ next if value.blank?
127
+
128
+ send("handle_notification_#{key}", payload, value)
129
+ payload[:data].merge!(key => value) if payload[:data].present?
130
+ end
131
+ end
132
+
133
+ def handle_notification_title(payload, value)
134
+ payload[:notification][:title] = value
135
+ end
136
+
137
+ def handle_notification_body(payload, value)
138
+ payload[:notification][:body] = value
139
+ end
140
+
141
+ def handle_notification_sound(payload, value)
142
+ case @mode
143
+ when :legacy
144
+ payload[:notification][:sound] = value
145
+ else
146
+ payload[:apns][:aps][:sound] = value
147
+ payload[:android][:sound] = value
148
+ end
149
+ end
150
+
151
+ def handle_data(payload, data)
152
+ payload[:data] = data if data.present?
153
+ end
154
+
155
+ def make_v1_response(response)
156
+ response_body = JSON.parse(response[:body])
157
+
158
+ Response.new(success: response_body['message'].present?,
159
+ status: response[:status_code], body: response_body)
160
+ end
161
+
162
+ def make_legacy_response(response)
163
+ response_body = JSON.parse(response[:body])
164
+
165
+ Response.new(success: response_body['success'].positive? && response_body['failure'].zero?,
166
+ status: response[:status_code], body: response_body)
167
+ end
168
+
169
+ end
170
+
171
+ end
172
+ # rubocop:enable Metrics/ParameterLists
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Modulofcm
4
+
5
+ class Configurator
6
+
7
+ attr_reader :clients
8
+
9
+ def initialize
10
+ @clients = {}
11
+ end
12
+
13
+ def self.configure
14
+ raise ArgumentError, 'A block is needed for Modulofcm.configure' unless block_given?
15
+
16
+ builder = new
17
+ yield builder
18
+
19
+ Modulofcm.clients = builder.clients
20
+ end
21
+
22
+ def client(name)
23
+ raise ArgumentError, 'A block is needed for Modulofcm::Configurator.client' unless block_given?
24
+
25
+ client = Client.new(name: name)
26
+ yield client
27
+
28
+ validated_client, errors = validate_client(client)
29
+ raise InvalidClient, errors.join('; ') unless validated_client
30
+
31
+ @clients[name] = client
32
+ end
33
+
34
+ private
35
+
36
+ def validate_client(client)
37
+ @errors = []
38
+
39
+ @errors << 'Required field: name' if client.name.blank?
40
+
41
+ if [client.google_application_credentials_path, client.api_token, client.firebase_project_id].all?(:present?)
42
+ return [@errors.empty?, @errors]
43
+ end
44
+
45
+ return [@errors.empty?, @errors] if client.api_key.present?
46
+
47
+ # rubocop:disable Layout/LineLength
48
+ @errors << 'Either an API key for Legacy API (deprecated) either the API token, the Google application credentials path and the Firebase project id are required'
49
+ # rubocop:enable Layout/LineLength
50
+
51
+ [false, @errors]
52
+ end
53
+
54
+ end
55
+
56
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Modulofcm
4
+
5
+ class Error < StandardError; end
6
+
7
+ class InvalidClient < Error
8
+
9
+ def initialize(msg=nil)
10
+ super(msg.presence || 'Invalid client configuration')
11
+ end
12
+
13
+ end
14
+
15
+ class NoTokenError < Error
16
+
17
+ def initialize
18
+ super('Token required to send a notification')
19
+ end
20
+
21
+ end
22
+
23
+ class EmptyNotificationError < Error
24
+
25
+ def initialize
26
+ super('A data payload, a title or a body is required to send a notification')
27
+ end
28
+
29
+ end
30
+
31
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Modulofcm
4
+
5
+ class Response
6
+
7
+ attr_reader :success, :status, :body
8
+
9
+ def initialize(success:, status:, body:)
10
+ @success = success
11
+ @status = status
12
+ @body = body
13
+ end
14
+
15
+ def succcess? = success
16
+
17
+ end
18
+
19
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Modulofcm
4
+
5
+ VERSION = '0.1.0'
6
+
7
+ end
data/lib/modulofcm.rb ADDED
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_support/all'
4
+ require 'fcm'
5
+
6
+ require_relative 'modulofcm/version'
7
+ require_relative 'modulofcm/errors'
8
+ require_relative 'modulofcm/client'
9
+ require_relative 'modulofcm/configurator'
10
+
11
+ module Modulofcm
12
+
13
+ class << self
14
+
15
+ def configure(&block)
16
+ Configurator.configure(&block)
17
+ end
18
+
19
+ def client(name)
20
+ clients[name.to_sym]
21
+ end
22
+
23
+ attr_accessor :clients
24
+
25
+ end
26
+
27
+ end
data/modulofcm.gemspec ADDED
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/modulofcm/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'modulofcm'
7
+ spec.version = Modulofcm::VERSION
8
+ spec.authors = ['Matthieu Ciappara']
9
+ spec.email = ['ciappa_m@modulotech.fr']
10
+
11
+ spec.summary = 'Firebase Cloud Messaging client library'
12
+ spec.description = 'Firebase Cloud Messaging client library'
13
+ spec.homepage = 'https://github.com/moduloTech/modulofcm'
14
+ spec.license = 'MIT'
15
+ spec.required_ruby_version = '>= 3.0.0'
16
+
17
+ spec.metadata['homepage_uri'] = spec.homepage
18
+ spec.metadata['source_code_uri'] = spec.homepage
19
+ spec.metadata['changelog_uri'] = 'https://github.com/moduloTech/modulofcm/blob/master/CHANGELOG.md'
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(__dir__) do
24
+ `git ls-files -z`.split("\x0").reject do |f|
25
+ (File.expand_path(f) == __FILE__) ||
26
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git .github appveyor Gemfile])
27
+ end
28
+ end
29
+ spec.require_paths = ['lib']
30
+ spec.metadata['rubygems_mfa_required'] = 'true'
31
+
32
+ spec.add_dependency 'activesupport', '< 8.0'
33
+ spec.add_dependency 'fcm', '~> 1.0', '>= 1.0.8'
34
+ end
data/sig/modulofcm.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Modulofcm
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,95 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: modulofcm
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Matthieu Ciappara
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2024-04-24 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "<"
18
+ - !ruby/object:Gem::Version
19
+ version: '8.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "<"
25
+ - !ruby/object:Gem::Version
26
+ version: '8.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: fcm
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.0'
34
+ - - ">="
35
+ - !ruby/object:Gem::Version
36
+ version: 1.0.8
37
+ type: :runtime
38
+ prerelease: false
39
+ version_requirements: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - "~>"
42
+ - !ruby/object:Gem::Version
43
+ version: '1.0'
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: 1.0.8
47
+ description: Firebase Cloud Messaging client library
48
+ email:
49
+ - ciappa_m@modulotech.fr
50
+ executables: []
51
+ extensions: []
52
+ extra_rdoc_files: []
53
+ files:
54
+ - ".rubocop.yml"
55
+ - CHANGELOG.md
56
+ - CODE_OF_CONDUCT.md
57
+ - LICENSE.txt
58
+ - README.md
59
+ - Rakefile
60
+ - lib/modulofcm.rb
61
+ - lib/modulofcm/client.rb
62
+ - lib/modulofcm/configurator.rb
63
+ - lib/modulofcm/errors.rb
64
+ - lib/modulofcm/response.rb
65
+ - lib/modulofcm/version.rb
66
+ - modulofcm.gemspec
67
+ - sig/modulofcm.rbs
68
+ homepage: https://github.com/moduloTech/modulofcm
69
+ licenses:
70
+ - MIT
71
+ metadata:
72
+ homepage_uri: https://github.com/moduloTech/modulofcm
73
+ source_code_uri: https://github.com/moduloTech/modulofcm
74
+ changelog_uri: https://github.com/moduloTech/modulofcm/blob/master/CHANGELOG.md
75
+ rubygems_mfa_required: 'true'
76
+ post_install_message:
77
+ rdoc_options: []
78
+ require_paths:
79
+ - lib
80
+ required_ruby_version: !ruby/object:Gem::Requirement
81
+ requirements:
82
+ - - ">="
83
+ - !ruby/object:Gem::Version
84
+ version: 3.0.0
85
+ required_rubygems_version: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ requirements: []
91
+ rubygems_version: 3.5.3
92
+ signing_key:
93
+ specification_version: 4
94
+ summary: Firebase Cloud Messaging client library
95
+ test_files: []