diff --git a/.gitignore b/.gitignore index 028a97f09..5bdf665bc 100644 --- a/.gitignore +++ b/.gitignore @@ -75,4 +75,5 @@ yalc.lock yarn-debug.log* .yarn-integrity -/storybook-static \ No newline at end of file +/storybook-static +config/chatwoot-3b1a1-c9a7423d7411.json \ No newline at end of file diff --git a/app/services/notification/fcm_service.rb b/app/services/notification/fcm_service.rb new file mode 100644 index 000000000..94a270feb --- /dev/null +++ b/app/services/notification/fcm_service.rb @@ -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 diff --git a/app/services/notification/push_notification_service.rb b/app/services/notification/push_notification_service.rb index b7fc231fa..1c4920820 100644 --- a/app/services/notification/push_notification_service.rb +++ b/app/services/notification/push_notification_service.rb @@ -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))