improve push message format (compatibility with mastodon)
[akkoma] / lib / pleroma / web / push / push.ex
1 defmodule Pleroma.Web.Push do
2 use GenServer
3
4 alias Pleroma.{Repo, User}
5 alias Pleroma.Web.Push.Subscription
6
7 require Logger
8 import Ecto.Query
9
10 @types ["Create", "Follow", "Announce", "Like"]
11
12 @gcm_api_key nil
13
14 def start_link() do
15 GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
16 end
17
18 def init(:ok) do
19 case Application.get_env(:web_push_encryption, :vapid_details) do
20 nil ->
21 Logger.warn(
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"
23 )
24
25 :ignore
26
27 _ ->
28 {:ok, %{}}
29 end
30 end
31
32 def send(notification) do
33 if Application.get_env(:web_push_encryption, :vapid_details) do
34 GenServer.cast(Pleroma.Web.Push, {:send, notification})
35 end
36 end
37
38 def handle_cast(
39 {:send, %{activity: %{data: %{"type" => type}}, user_id: user_id} = notification},
40 state
41 )
42 when type in @types do
43 actor = User.get_cached_by_ap_id(notification.activity.data["actor"])
44
45 Subscription
46 |> where(user_id: ^user_id)
47 |> preload(:token)
48 |> Repo.all()
49 |> Enum.each(fn record ->
50 subscription = %{
51 keys: %{
52 p256dh: record.key_p256dh,
53 auth: record.key_auth
54 },
55 endpoint: record.endpoint
56 }
57
58 body =
59 Jason.encode!(%{
60 title: format_title(notification),
61 body: format_body(notification, actor),
62 notification_id: notification.id,
63 icon: User.avatar_url(actor),
64 preferred_locale: "en",
65 access_token: record.token.token
66 })
67
68 case WebPushEncryption.send_web_push(body, subscription, @gcm_api_key) do
69 {:ok, %{status_code: code}} when 400 <= code and code < 500 ->
70 Logger.debug("Removing subscription record")
71 Repo.delete!(record)
72 :ok
73
74 {:ok, %{status_code: code}} when 200 <= code and code < 300 ->
75 :ok
76
77 {:ok, %{status_code: code}} ->
78 Logger.error("Web Push Nonification failed with code: #{code}")
79 :error
80
81 _ ->
82 Logger.error("Web Push Nonification failed with unknown error")
83 :error
84 end
85 end)
86
87 {:noreply, state}
88 end
89
90 def handle_cast({:send, _}, state) do
91 Logger.warn("Unknown notification type")
92 {:noreply, state}
93 end
94
95 defp format_title(%{activity: %{data: %{"type" => type}}}) do
96 case type do
97 "Create" -> "New Mention"
98 "Follow" -> "New Follower"
99 "Announce" -> "New Repeat"
100 "Like" -> "New Favorite"
101 end
102 end
103
104 defp format_body(%{activity: %{data: %{"type" => type}}}, actor) do
105 case type do
106 "Create" -> "@#{actor.nickname} has mentiond you"
107 "Follow" -> "@#{actor.nickname} has followed you"
108 "Announce" -> "@#{actor.nickname} has repeated your post"
109 "Like" -> "@#{actor.nickname} has favorited your post"
110 end
111 end
112 end