Class: Decidim::SendPushNotification

Inherits:
Object
  • Object
show all
Includes:
ActionView::Helpers::UrlHelper
Defined in:
app/services/decidim/send_push_notification.rb

Overview

This class generates a notification based on the given event, for the given resource/recipient couple. It is intended to be used by the ‘Decidim::NotificationGenerator` class, which schedules a job for each recipient of the event, so that we can easily control which jobs fail.

Instance Method Summary collapse

Instance Method Details

#perform(notification) ⇒ Object

Send the push notification. Returns ‘nil` if the user didn’t allowed push notifications or if the subscription to push notifications doesn’t exist

Returns the result of the dispatch or nil if user or subscription are empty



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/services/decidim/send_push_notification.rb', line 18

def perform(notification)
  return unless Rails.application.secrets.dig(:vapid, :enabled)

  I18n.with_locale(notification.user.locale || notification.user.organization.default_locale) do
    notification.user.notifications_subscriptions.values.map do |subscription|
      message_params = notification_params(Decidim::PushNotificationPresenter.new(notification))
      payload = build_payload(message_params, subscription)
      # Capture webpush exceptions in order to avoid this call to be repeated by the background job runner
      # Webpush::Error class is the parent class of all defined errors
      begin
        Webpush.payload_send(**payload)
      rescue Webpush::Error => e
        Rails.logger.warn("[ERROR] Push notification delivery failed due to #{e.message}")
        nil
      end
    end.compact
  end
end