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"])
46 |> where(user_id: ^user_id)
49 |> Enum.each(fn record ->
52 p256dh: record.key_p256dh,
55 endpoint: record.endpoint
60 title: format_title(notification),
61 access_token: record.token.token,
62 body: format_body(notification, actor),
63 notification_id: notification.id,
64 notification_type: format_type(notification),
65 icon: User.avatar_url(actor),
66 preferred_locale: "en"
69 case WebPushEncryption.send_web_push(body, subscription) do
70 {:ok, %{status_code: code}} when 400 <= code and code < 500 ->
71 Logger.debug("Removing subscription record")
75 {:ok, %{status_code: code}} when 200 <= code and code < 300 ->
78 {:ok, %{status_code: code}} ->
79 Logger.error("Web Push Nonification failed with code: #{code}")
83 Logger.error("Web Push Nonification failed with unknown error")
91 def handle_cast({:send, _}, state) do
92 Logger.warn("Unknown notification type")
96 # https://github.com/tootsuite/mastodon/blob/master/app/models/notification.rb#L19
97 defp format_type(%{activity: %{data: %{"type" => type}}}) do
101 "Announce" -> "reblog"
102 "Favorite" -> "favourite"
106 defp format_title(%{activity: %{data: %{"type" => type}}}) do
108 "Create" -> "New Mention"
109 "Follow" -> "New Follower"
110 "Announce" -> "New Repeat"
111 "Like" -> "New Favorite"
115 defp format_body(%{activity: %{data: %{"type" => type}}}, actor) do
117 "Create" -> "@#{actor.nickname} has mentiond you"
118 "Follow" -> "@#{actor.nickname} has followed you"
119 "Announce" -> "@#{actor.nickname} has repeated your post"
120 "Like" -> "@#{actor.nickname} has favorited your post"