2021-03-23 14:18:03 +00:00
|
|
|
defmodule Mobilizon.Service.Notifier.Push do
|
|
|
|
@moduledoc """
|
|
|
|
WebPush notifier
|
|
|
|
"""
|
|
|
|
alias Mobilizon.Activities.Activity
|
2021-05-06 10:27:04 +00:00
|
|
|
alias Mobilizon.{Config, Users}
|
2021-05-06 16:39:59 +00:00
|
|
|
alias Mobilizon.Service.Activity.{Renderer, Utils}
|
2021-03-23 14:18:03 +00:00
|
|
|
alias Mobilizon.Service.Notifier
|
|
|
|
alias Mobilizon.Service.Notifier.Push
|
2021-05-06 10:27:04 +00:00
|
|
|
alias Mobilizon.Storage.Page
|
2021-05-06 16:39:59 +00:00
|
|
|
alias Mobilizon.Users.{PushSubscription, User}
|
2021-03-23 14:18:03 +00:00
|
|
|
|
|
|
|
@behaviour Notifier
|
|
|
|
|
|
|
|
@impl Notifier
|
|
|
|
def ready? do
|
|
|
|
Config.get(__MODULE__, :enabled)
|
|
|
|
end
|
|
|
|
|
|
|
|
@impl Notifier
|
2021-05-06 16:39:59 +00:00
|
|
|
def send(user, activity, options \\ [])
|
|
|
|
|
|
|
|
def send(%User{id: user_id, locale: locale} = _user, %Activity{} = activity, options) do
|
|
|
|
options = Keyword.put_new(options, :locale, locale)
|
|
|
|
|
2021-05-06 10:27:04 +00:00
|
|
|
%Page{elements: subscriptions} = Users.list_user_push_subscriptions(user_id, 1, 100)
|
2021-05-06 16:39:59 +00:00
|
|
|
Enum.map(subscriptions, &send_subscription(activity, convert_subscription(&1), options))
|
2021-03-23 14:18:03 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
@impl Notifier
|
2021-05-06 16:39:59 +00:00
|
|
|
def send(%User{} = user, activities, options) when is_list(activities) do
|
|
|
|
Enum.map(activities, &Push.send(user, &1, options))
|
2021-03-23 14:18:03 +00:00
|
|
|
end
|
|
|
|
|
2021-05-06 16:39:59 +00:00
|
|
|
defp send_subscription(activity, subscription, options) do
|
|
|
|
activity
|
|
|
|
|> payload(options)
|
|
|
|
|> WebPushEncryption.send_web_push(subscription)
|
2021-03-23 14:18:03 +00:00
|
|
|
end
|
2021-05-06 10:27:04 +00:00
|
|
|
|
2021-05-06 16:39:59 +00:00
|
|
|
defp payload(%Activity{} = activity, options) do
|
2021-05-06 10:27:04 +00:00
|
|
|
activity
|
2021-05-06 16:39:59 +00:00
|
|
|
|> Utils.add_activity_object()
|
|
|
|
|> Renderer.render(options)
|
|
|
|
|> Jason.encode!()
|
|
|
|
end
|
|
|
|
|
|
|
|
defp convert_subscription(%PushSubscription{} = subscription) do
|
|
|
|
%{
|
|
|
|
endpoint: subscription.endpoint,
|
|
|
|
keys: %{auth: subscription.auth, p256dh: subscription.p256dh}
|
|
|
|
}
|
2021-05-06 10:27:04 +00:00
|
|
|
end
|
2021-03-23 14:18:03 +00:00
|
|
|
end
|