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")
81 def handle_cast({:send, _}, state) do
82 Logger.warn("Unknown notification type")
86 def format(%{activity: %{data: %{"type" => "Create"}}}, actor) do
89 body: "@#{actor.nickname} has mentiond you",
90 icon: get_avatar_url(actor)
94 def format(%{activity: %{data: %{"type" => "Follow"}}}, actor) do
96 title: "New Follower",
97 body: "@#{actor.nickname} has followed you",
98 icon: get_avatar_url(actor)
102 def format(%{activity: %{data: %{"type" => "Announce"}}}, actor) do
104 title: "New Announce",
105 body: "@#{actor.nickname} has announced your post",
106 icon: get_avatar_url(actor)
110 def format(%{activity: %{data: %{"type" => "Like"}}}, actor) do
113 body: "@#{actor.nickname} has liked your post",
114 icon: get_avatar_url(actor)
118 def get_avatar_url(%{avatar: %{"type" => "Image", "url" => urls}}) do
119 case List.first(urls) do
120 %{"href" => url} -> url
121 _ -> get_avatar_url(nil)
125 def get_avatar_url(_) do
126 Pleroma.Web.Endpoint.static_url() <> "/images/avi.png"