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 GenServer.cast(Pleroma.Web.Push, {:send, notification})
37 {:send, %{activity: %{data: %{"type" => type}}, user_id: user_id} = notification},
40 when type in @types do
41 actor = User.get_cached_by_ap_id(notification.activity.data["actor"])
42 body = notification |> format(actor) |> Jason.encode!()
45 |> where(user_id: ^user_id)
47 |> Enum.each(fn record ->
50 p256dh: record.key_p256dh,
53 endpoint: record.endpoint
56 case WebPushEncryption.send_web_push(body, subscription, @gcm_api_key) do
57 {:ok, %{status_code: code}} when 400 <= code and code < 500 ->
58 Logger.debug("Removing subscription record")
62 {:ok, %{status_code: code}} when 200 <= code and code < 300 ->
65 {:ok, %{status_code: code}} ->
66 Logger.error("Web Push Nonification failed with code: #{code}")
70 Logger.error("Web Push Nonification failed with unknown error")
79 def handle_cast({:send, _}, state) do
80 Logger.warn("Unknown notification type")
84 def format(%{activity: %{data: %{"type" => "Create"}}}, actor) do
87 body: "@#{actor.nickname} has mentiond you",
88 icon: get_avatar_url(actor)
92 def format(%{activity: %{data: %{"type" => "Follow"}}}, actor) do
94 title: "New Follower",
95 body: "@#{actor.nickname} has followed you",
96 icon: get_avatar_url(actor)
100 def format(%{activity: %{data: %{"type" => "Announce"}}}, actor) do
102 title: "New Announce",
103 body: "@#{actor.nickname} has announced your post",
104 icon: get_avatar_url(actor)
108 def format(%{activity: %{data: %{"type" => "Like"}}}, actor) do
111 body: "@#{actor.nickname} has liked your post",
112 icon: get_avatar_url(actor)
116 def get_avatar_url(%{avatar: %{"type" => "Image", "url" => urls}}) do
117 case List.first(urls) do
118 %{"href" => url} -> url
119 _ -> get_avatar_url(nil)
123 def get_avatar_url(_) do
124 Pleroma.Web.Endpoint.static_url() <> "/images/avi.png"