feat: add fcm service

This commit is contained in:
Muhsin Keloth
2024-06-05 11:09:22 +05:30
parent 00ef9c475f
commit 61eaa96b85
3 changed files with 71 additions and 4 deletions
+2 -1
View File
@@ -75,4 +75,5 @@ yalc.lock
yarn-debug.log*
.yarn-integrity
/storybook-static
/storybook-static
config/chatwoot-3b1a1-c9a7423d7411.json
+36
View File
@@ -0,0 +1,36 @@
class FCMService
SCOPES = ['https://www.googleapis.com/auth/firebase.messaging'].freeze
def initialize(credentials_path, project_id)
@credentials_path = credentials_path
@project_id = project_id
@token_info = nil
end
def fcm_client
FCM.new(current_token, @credentials_path, @project_id)
end
private
def current_token
@token_info = generate_token if @token_info.nil? || token_expired?
@token_info[:token]
end
def token_expired?
Time.now >= @token_info[:expires_at]
end
def generate_token
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: File.open(@credentials_path),
scope: SCOPES
)
token = authorizer.fetch_access_token!
{
token: token['access_token'],
expires_at: Time.now + token['expires_in'].to_i
}
end
end
@@ -1,3 +1,4 @@
require_relative 'fcm_service'
class Notification::PushNotificationService
include Rails.application.routes.url_helpers
@@ -70,14 +71,43 @@ class Notification::PushNotificationService
end
def send_fcm_push(subscription)
return unless ENV['FCM_SERVER_KEY']
return unless ENV['GOOGLE_APPLICATION_CREDENTIALS'] && ENV['FIREBASE_PROJECT_ID']
return unless subscription.fcm?
fcm = FCM.new(ENV.fetch('FCM_SERVER_KEY', nil))
response = fcm.send([subscription.subscription_attributes['push_token']], fcm_options)
fcm_service = FCMService.new(ENV.fetch('GOOGLE_APPLICATION_CREDENTIALS', nil),
ENV.fetch('FIREBASE_PROJECT_ID', nil))
fcm = fcm_service.fcm_client
message = {
'token': subscription.subscription_attributes['push_token'],
'data': {
payload: {
data: {
id: 1
}
}.to_json
},
'notification': {
title: notification.push_message_title,
body: notification.push_message_body
},
'android': {},
'apns': {
payload: {
aps: {
sound: 'default',
category: "#{Time.zone.now.to_i}"
}
}
},
'fcm_options': {
analytics_label: 'Label'
}
}
response = fcm.send_v1(message)
remove_subscription_if_error(subscription, response)
end
def send_push_via_chatwoot_hub(subscription)
return if ENV['FCM_SERVER_KEY']
return unless ActiveModel::Type::Boolean.new.cast(ENV.fetch('ENABLE_PUSH_RELAY_SERVER', true))