11require 'faraday'
22require 'cgi'
33require 'json'
4+ require 'googleauth'
45
56class FCM
67 BASE_URI = 'https://fcm.googleapis.com'
8+ BASE_URI_V1 = 'https://fcm.googleapis.com/v1/projects/'
79 DEFAULT_TIMEOUT = 30
810 FORMAT = :json
911
@@ -12,13 +14,57 @@ class FCM
1214 INSTANCE_ID_API = 'https://iid.googleapis.com'
1315 TOPIC_REGEX = /[a-zA-Z0-9\- _.~%]+/
1416
15- attr_accessor :timeout , :api_key
17+ attr_accessor :timeout , :api_key , :json_key_path , :project_base_uri
1618
17- def initialize ( api_key , client_options = { } )
19+ def initialize ( api_key , json_key_path = '' , project_name = '' , client_options = { } )
1820 @api_key = api_key
1921 @client_options = client_options
22+ @json_key_path = json_key_path
23+ @project_base_uri = BASE_URI_V1 + project_name . to_s
2024 end
2125
26+ # See https://firebase.google.com/docs/cloud-messaging/send-message
27+ # {
28+ # "token": "4sdsx",
29+ # "notification": {
30+ # "title": "Breaking News",
31+ # "body": "New news story available."
32+ # },
33+ # "data": {
34+ # "story_id": "story_12345"
35+ # },
36+ # "android": {
37+ # "notification": {
38+ # "click_action": "TOP_STORY_ACTIVITY",
39+ # "body": "Check out the Top Story"
40+ # }
41+ # },
42+ # "apns": {
43+ # "payload": {
44+ # "aps": {
45+ # "category" : "NEW_MESSAGE_CATEGORY"
46+ # }
47+ # }
48+ # }
49+ # }
50+ # fcm = FCM.new(api_key, json_key_path, project_name)
51+ # fcm.send(
52+ # { "token": "4sdsx",, "to" : "notification": {}.. }
53+ # )
54+ def send_notification_v1 ( message )
55+ return if @project_base_uri . empty?
56+
57+ post_body = { 'message' : message }
58+
59+ response = Faraday . post ( "#{ @project_base_uri } /messages:send" ) do |req |
60+ req . headers [ 'Content-Type' ] = 'application/json'
61+ req . headers [ 'Authorization' ] = "Bearer #{ jwt_token } "
62+ req . body = post_body . to_json
63+ end
64+ build_response ( response )
65+ end
66+ alias send_v1 send_notification_v1
67+
2268 # See https://developers.google.com/cloud-messaging/http for more details.
2369 # { "notification": {
2470 # "title": "Portugal vs. Denmark",
@@ -265,4 +311,14 @@ def validate_condition_topics?(condition)
265311 topics = condition . scan ( /(?:^|\S |\s )'([^']*?)'(?:$|\S |\s )/ ) . flatten
266312 topics . all? { |topic | topic . gsub ( TOPIC_REGEX , "" ) . length == 0 }
267313 end
314+
315+ def jwt_token
316+ scope = 'https://www.googleapis.com/auth/firebase.messaging'
317+ authorizer = Google ::Auth ::ServiceAccountCredentials . make_creds (
318+ json_key_io : File . open ( @json_key_path ) ,
319+ scope : scope
320+ )
321+ token = authorizer . fetch_access_token!
322+ token [ 'access_token' ]
323+ end
268324end
0 commit comments