1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Push do
10 alias Pleroma.Web.Push.Subscription
15 @types ["Create", "Follow", "Announce", "Like"]
18 GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
22 Application.get_env(:web_push_encryption, :vapid_details, [])
26 case vapid_config() do
28 list when is_list(list) -> true
33 def send(notification) do
35 GenServer.cast(Pleroma.Web.Push, {:send, notification})
42 VAPID key pair is not found. If you wish to enabled web push, please run
44 mix web_push.gen.keypair
46 and add the resulting output to your configuration file.
56 {:send, %{activity: %{data: %{"type" => type}}, user_id: user_id} = notification},
59 when type in @types do
60 actor = User.get_cached_by_ap_id(notification.activity.data["actor"])
62 type = Pleroma.Activity.mastodon_notification_type(notification.activity)
65 |> where(user_id: ^user_id)
68 |> Enum.filter(fn subscription ->
69 get_in(subscription.data, ["alerts", type]) || false
71 |> Enum.each(fn subscription ->
74 p256dh: subscription.key_p256dh,
75 auth: subscription.key_auth
77 endpoint: subscription.endpoint
82 title: format_title(notification),
83 access_token: subscription.token.token,
84 body: format_body(notification, actor),
85 notification_id: notification.id,
86 notification_type: type,
87 icon: User.avatar_url(actor),
88 preferred_locale: "en"
91 case WebPushEncryption.send_web_push(
94 Application.get_env(:web_push_encryption, :gcm_api_key)
96 {:ok, %{status_code: code}} when 400 <= code and code < 500 ->
97 Logger.debug("Removing subscription record")
98 Repo.delete!(subscription)
101 {:ok, %{status_code: code}} when 200 <= code and code < 300 ->
104 {:ok, %{status_code: code}} ->
105 Logger.error("Web Push Notification failed with code: #{code}")
109 Logger.error("Web Push Notification failed with unknown error")
117 def handle_cast({:send, _}, state) do
118 Logger.warn("Unknown notification type")
122 defp format_title(%{activity: %{data: %{"type" => type}}}) do
124 "Create" -> "New Mention"
125 "Follow" -> "New Follower"
126 "Announce" -> "New Repeat"
127 "Like" -> "New Favorite"
131 defp format_body(%{activity: %{data: %{"type" => type}}}, actor) do
133 "Create" -> "@#{actor.nickname} has mentioned you"
134 "Follow" -> "@#{actor.nickname} has followed you"
135 "Announce" -> "@#{actor.nickname} has repeated your post"
136 "Like" -> "@#{actor.nickname} has favorited your post"