1 defmodule Pleroma.Web.Push do
4 alias Pleroma.{Repo, User}
5 alias Pleroma.Web.Push.Subscription
10 @types ["Create", "Follow", "Announce", "Like"]
15 GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
19 case Application.get_env(:web_push_encryption, :vapid_details) do
22 "VAPID key pair is not found. Please, add VAPID configuration to config. Run `mix web_push.gen.keypair` mix task to create a key pair"
32 def send(notification) do
33 if Application.get_env(:web_push_encryption, :vapid_details) do
34 GenServer.cast(Pleroma.Web.Push, {:send, notification})
39 {:send, %{activity: %{data: %{"type" => type}}, user_id: user_id} = notification},
42 when type in @types do
43 actor = User.get_cached_by_ap_id(notification.activity.data["actor"])
45 type = format_type(notification)
48 |> where(user_id: ^user_id)
51 |> Enum.filter(fn subscription ->
52 get_in(subscription.data, ["alerts", type]) || false
54 |> Enum.each(fn subscription ->
57 p256dh: subscription.key_p256dh,
58 auth: subscription.key_auth
60 endpoint: subscription.endpoint
65 title: format_title(notification),
66 access_token: subscription.token.token,
67 body: format_body(notification, actor),
68 notification_id: notification.id,
69 notification_type: type,
70 icon: User.avatar_url(actor),
71 preferred_locale: "en"
74 case WebPushEncryption.send_web_push(body, sub) do
75 {:ok, %{status_code: code}} when 400 <= code and code < 500 ->
76 Logger.debug("Removing subscription record")
77 Repo.delete!(subscription)
80 {:ok, %{status_code: code}} when 200 <= code and code < 300 ->
83 {:ok, %{status_code: code}} ->
84 Logger.error("Web Push Notification failed with code: #{code}")
88 Logger.error("Web Push Notification failed with unknown error")
96 def handle_cast({:send, _}, state) do
97 Logger.warn("Unknown notification type")
101 # https://github.com/tootsuite/mastodon/blob/master/app/models/notification.rb#L19
102 defp format_type(%{activity: %{data: %{"type" => type}}}) do
104 "Create" -> "mention"
106 "Announce" -> "reblog"
107 "Favorite" -> "favourite"
111 defp format_title(%{activity: %{data: %{"type" => type}}}) do
113 "Create" -> "New Mention"
114 "Follow" -> "New Follower"
115 "Announce" -> "New Repeat"
116 "Like" -> "New Favorite"
120 defp format_body(%{activity: %{data: %{"type" => type}}}, actor) do
122 "Create" -> "@#{actor.nickname} has mentiond you"
123 "Follow" -> "@#{actor.nickname} has followed you"
124 "Announce" -> "@#{actor.nickname} has repeated your post"
125 "Like" -> "@#{actor.nickname} has favorited your post"