1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Push do
8 alias Pleroma.{Repo, User}
9 alias Pleroma.Web.Push.Subscription
14 @types ["Create", "Follow", "Announce", "Like"]
17 GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
21 Application.get_env(:web_push_encryption, :vapid_details, [])
25 case vapid_config() do
27 list when is_list(list) -> true
32 def send(notification) do
34 GenServer.cast(Pleroma.Web.Push, {:send, notification})
41 VAPID key pair is not found. If you wish to enabled web push, please run
43 mix web_push.gen.keypair
45 and add the resulting output to your configuration file.
55 {:send, %{activity: %{data: %{"type" => type}}, user_id: user_id} = notification},
58 when type in @types do
59 actor = User.get_cached_by_ap_id(notification.activity.data["actor"])
61 type = Pleroma.Activity.mastodon_notification_type(notification.activity)
64 |> where(user_id: ^user_id)
67 |> Enum.filter(fn subscription ->
68 get_in(subscription.data, ["alerts", type]) || false
70 |> Enum.each(fn subscription ->
73 p256dh: subscription.key_p256dh,
74 auth: subscription.key_auth
76 endpoint: subscription.endpoint
81 title: format_title(notification),
82 access_token: subscription.token.token,
83 body: format_body(notification, actor),
84 notification_id: notification.id,
85 notification_type: type,
86 icon: User.avatar_url(actor),
87 preferred_locale: "en"
90 case WebPushEncryption.send_web_push(
93 Application.get_env(:web_push_encryption, :gcm_api_key)
95 {:ok, %{status_code: code}} when 400 <= code and code < 500 ->
96 Logger.debug("Removing subscription record")
97 Repo.delete!(subscription)
100 {:ok, %{status_code: code}} when 200 <= code and code < 300 ->
103 {:ok, %{status_code: code}} ->
104 Logger.error("Web Push Notification failed with code: #{code}")
108 Logger.error("Web Push Notification failed with unknown error")
116 def handle_cast({:send, _}, state) do
117 Logger.warn("Unknown notification type")
121 defp format_title(%{activity: %{data: %{"type" => type}}}) do
123 "Create" -> "New Mention"
124 "Follow" -> "New Follower"
125 "Announce" -> "New Repeat"
126 "Like" -> "New Favorite"
130 defp format_body(%{activity: %{data: %{"type" => type}}}, actor) do
132 "Create" -> "@#{actor.nickname} has mentioned you"
133 "Follow" -> "@#{actor.nickname} has followed you"
134 "Announce" -> "@#{actor.nickname} has repeated your post"
135 "Like" -> "@#{actor.nickname} has favorited your post"