26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
# File 'app/services/newsmast_mastodon/firebase_notification_service.rb', line 26
def self.send_notification(token, title, body, data = {})
if BASE_URL.blank?
Rails.logger.error("Firebase notifications are disabled: FIREBASE_PROJECT_ID environment variable is not set")
return nil
end
if FILE_NAME.blank?
Rails.logger.error("FIREBASE_KEY_FILE_NAME environment variable is not set")
return nil
end
service_account_file = Rails.root.join('config', FILE_NAME)
unless File.exist?(service_account_file)
Rails.logger.error("Service account file not found at #{service_account_file}")
return nil
end
scope = 'https://www.googleapis.com/auth/firebase.messaging'
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: File.open(service_account_file),
scope: scope
)
access_token = authorizer.fetch_access_token!['access_token']
return nil if access_token.blank?
= {
'Authorization' => "Bearer #{access_token}",
'Content-Type' => 'application/json',
}
payload = {
message: {
token: token,
notification: {
title: title,
body: body,
},
data: data,
},
}.to_json
response = post(BASE_URL, headers: , body: payload)
Rails.logger.error("Error sending notification: #{response.body}") unless response.success?
response
rescue StandardError => e
Rails.logger.error("Exception sending notification: #{e.message}")
nil
end
|