Class: NewsmastMastodon::FirebaseNotificationService

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
app/services/newsmast_mastodon/firebase_notification_service.rb

Constant Summary collapse

BASE_URL =
if ENV['FIREBASE_PROJECT_ID'].present?
  "https://fcm.googleapis.com/v1/projects/#{ENV['FIREBASE_PROJECT_ID']}/messages:send"
else
  nil
end
FILE_NAME =
if ENV['FIREBASE_KEY_FILE_NAME'].present?
  ENV['FIREBASE_KEY_FILE_NAME']
else
  nil
end

Class Method Summary collapse

Class Method Details

.send_notification(token, title, body, data = {}) ⇒ Object



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

  # Path to your service account JSON file
   = Rails.root.join('config', FILE_NAME)
  unless File.exist?()
    Rails.logger.error("Service account file not found at #{}")
    return nil
  end

  # Define the required scope
  scope = 'https://www.googleapis.com/auth/firebase.messaging'

  # Authenticate and get the token
  authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
    json_key_io: File.open(),
    scope: scope
  )

  # Fetch the access token
  access_token = authorizer.fetch_access_token!['access_token']

  return nil if access_token.blank?

  headers = {
    '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: 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