1 defmodule Pleroma.Web.Push do
4 alias Pleroma.{Repo, User}
5 alias Pleroma.Web.Push.Subscription
10 @types ["Create", "Follow", "Announce", "Like"]
13 GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
17 Application.get_env(:web_push_encryption, :vapid_details, [])
21 case vapid_config() do
23 list when is_list(list) -> true
28 def send(notification) do
30 GenServer.cast(Pleroma.Web.Push, {:send, notification})
37 VAPID key pair is not found. If you wish to enabled web push, please run
39 mix web_push.gen.keypair
41 and add the resulting output to your configuration file.
51 {:send, %{activity: %{data: %{"type" => type}}, user_id: user_id} = notification},
54 when type in @types do
55 actor = User.get_cached_by_ap_id(notification.activity.data["actor"])
57 type = Pleroma.Activity.mastodon_notification_type(notification.activity)
60 |> where(user_id: ^user_id)
63 |> Enum.filter(fn subscription ->
64 get_in(subscription.data, ["alerts", type]) || false
66 |> Enum.each(fn subscription ->
69 p256dh: subscription.key_p256dh,
70 auth: subscription.key_auth
72 endpoint: subscription.endpoint
77 title: format_title(notification),
78 access_token: subscription.token.token,
79 body: format_body(notification, actor),
80 notification_id: notification.id,
81 notification_type: type,
82 icon: User.avatar_url(actor),
83 preferred_locale: "en"
86 case WebPushEncryption.send_web_push(
89 Application.get_env(:web_push_encryption, :gcm_api_key)
91 {:ok, %{status_code: code}} when 400 <= code and code < 500 ->
92 Logger.debug("Removing subscription record")
93 Repo.delete!(subscription)
96 {:ok, %{status_code: code}} when 200 <= code and code < 300 ->
99 {:ok, %{status_code: code}} ->
100 Logger.error("Web Push Notification failed with code: #{code}")
104 Logger.error("Web Push Notification failed with unknown error")
112 def handle_cast({:send, _}, state) do
113 Logger.warn("Unknown notification type")
117 defp format_title(%{activity: %{data: %{"type" => type}}}) do
119 "Create" -> "New Mention"
120 "Follow" -> "New Follower"
121 "Announce" -> "New Repeat"
122 "Like" -> "New Favorite"
126 defp format_body(%{activity: %{data: %{"type" => type}}}, actor) do
128 "Create" -> "@#{actor.nickname} has mentioned you"
129 "Follow" -> "@#{actor.nickname} has followed you"
130 "Announce" -> "@#{actor.nickname} has repeated your post"
131 "Like" -> "@#{actor.nickname} has favorited your post"