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"])
44 body = notification |> format(actor) |> Jason.encode!()
47 |> where(user_id: ^user_id)
49 |> Enum.each(fn record ->
52 p256dh: record.key_p256dh,
55 endpoint: record.endpoint
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")
64 {:ok, %{status_code: code}} when 200 <= code and code < 300 ->
67 {:ok, %{status_code: code}} ->
68 Logger.error("Web Push Nonification failed with code: #{code}")
72 Logger.error("Web Push Nonification failed with unknown error")
80 def handle_cast({:send, _}, state) do
81 Logger.warn("Unknown notification type")
85 def format(%{activity: %{data: %{"type" => "Create"}}}, actor) do
88 body: "@#{actor.nickname} has mentiond you",
89 icon: User.avatar_url(actor)
93 def format(%{activity: %{data: %{"type" => "Follow"}}}, actor) do
95 title: "New Follower",
96 body: "@#{actor.nickname} has followed you",
97 icon: User.avatar_url(actor)
101 def format(%{activity: %{data: %{"type" => "Announce"}}}, actor) do
103 title: "New Announce",
104 body: "@#{actor.nickname} has announced your post",
105 icon: User.avatar_url(actor)
109 def format(%{activity: %{data: %{"type" => "Like"}}}, actor) do
112 body: "@#{actor.nickname} has liked your post",
113 icon: User.avatar_url(actor)