Merge branch 'fix/theora-detection-read-bytes' into 'develop'
[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 body = notification |> format(actor) |> Jason.encode!()
45
46 Subscription
47 |> where(user_id: ^user_id)
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 case WebPushEncryption.send_web_push(body, subscription, @gcm_api_key) do
59 {:ok, %{status_code: code}} when 400 <= code and code < 500 ->
60 Logger.debug("Removing subscription record")
61 Repo.delete!(record)
62 :ok
63
64 {:ok, %{status_code: code}} when 200 <= code and code < 300 ->
65 :ok
66
67 {:ok, %{status_code: code}} ->
68 Logger.error("Web Push Nonification failed with code: #{code}")
69 :error
70
71 _ ->
72 Logger.error("Web Push Nonification failed with unknown error")
73 :error
74 end
75 end)
76
77 {:noreply, state}
78 end
79
80 def handle_cast({:send, _}, state) do
81 Logger.warn("Unknown notification type")
82 {:noreply, state}
83 end
84
85 def format(%{activity: %{data: %{"type" => "Create"}}}, actor) do
86 %{
87 title: "New Mention",
88 body: "@#{actor.nickname} has mentiond you",
89 icon: User.avatar_url(actor)
90 }
91 end
92
93 def format(%{activity: %{data: %{"type" => "Follow"}}}, actor) do
94 %{
95 title: "New Follower",
96 body: "@#{actor.nickname} has followed you",
97 icon: User.avatar_url(actor)
98 }
99 end
100
101 def format(%{activity: %{data: %{"type" => "Announce"}}}, actor) do
102 %{
103 title: "New Announce",
104 body: "@#{actor.nickname} has announced your post",
105 icon: User.avatar_url(actor)
106 }
107 end
108
109 def format(%{activity: %{data: %{"type" => "Like"}}}, actor) do
110 %{
111 title: "New Like",
112 body: "@#{actor.nickname} has liked your post",
113 icon: User.avatar_url(actor)
114 }
115 end
116 end