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 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
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")
74 {:ok, %{status_code: code}} when 200 <= code and code < 300 ->
77 {:ok, %{status_code: code}} ->
78 Logger.error("Web Push Nonification failed with code: #{code}")
82 Logger.error("Web Push Nonification failed with unknown error")
90 def handle_cast({:send, _}, state) do
91 Logger.warn("Unknown notification type")
95 defp format_title(%{activity: %{data: %{"type" => type}}}) do
97 "Create" -> "New Mention"
98 "Follow" -> "New Follower"
99 "Announce" -> "New Repeat"
100 "Like" -> "New Favorite"
104 defp format_body(%{activity: %{data: %{"type" => type}}}, actor) 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"