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.Impl do
6 @moduledoc "The module represents implementation push web notification"
9 alias Pleroma.Notification
13 alias Pleroma.Web.Metadata.Utils
14 alias Pleroma.Web.Push.Subscription
19 @types ["Create", "Follow", "Announce", "Like"]
21 @doc "Performs sending notifications for user subscriptions"
22 @spec perform(Notification.t()) :: list(any) | :error
24 %{activity: %{data: %{"type" => activity_type}, id: activity_id}, user_id: user_id} =
27 when activity_type in @types do
28 actor = User.get_cached_by_ap_id(notif.activity.data["actor"])
30 type = Activity.mastodon_notification_type(notif.activity)
31 gcm_api_key = Application.get_env(:web_push_encryption, :gcm_api_key)
32 avatar_url = User.avatar_url(actor)
34 for subscription <- fetch_subsriptions(user_id),
35 get_in(subscription.data, ["alerts", type]) do
37 title: format_title(notif),
38 access_token: subscription.token.token,
39 body: format_body(notif, actor),
40 notification_id: notif.id,
41 notification_type: type,
43 preferred_locale: "en",
45 activity_id: activity_id
49 |> push_message(build_sub(subscription), gcm_api_key, subscription)
54 Logger.warn("Unknown notification type")
58 @doc "Push message to web"
59 def push_message(body, sub, api_key, subscription) do
60 case WebPushEncryption.send_web_push(body, sub, api_key) do
61 {:ok, %{status_code: code}} when 400 <= code and code < 500 ->
62 Logger.debug("Removing subscription record")
63 Repo.delete!(subscription)
66 {:ok, %{status_code: code}} when 200 <= code and code < 300 ->
69 {:ok, %{status_code: code}} ->
70 Logger.error("Web Push Notification failed with code: #{code}")
74 Logger.error("Web Push Notification failed with unknown error")
79 @doc "Gets user subscriptions"
80 def fetch_subsriptions(user_id) do
82 |> where(user_id: ^user_id)
87 def build_sub(subscription) do
90 p256dh: subscription.key_p256dh,
91 auth: subscription.key_auth
93 endpoint: subscription.endpoint
98 %{activity: %{data: %{"type" => "Create", "object" => %{"content" => content}}}},
101 "@#{actor.nickname}: #{Utils.scrub_html_and_truncate(content, 80)}"
105 %{activity: %{data: %{"type" => "Announce", "object" => activity_id}}},
108 %Activity{data: %{"object" => %{"id" => object_id}}} = Activity.get_by_ap_id(activity_id)
109 %Object{data: %{"content" => content}} = Object.get_by_ap_id(object_id)
111 "@#{actor.nickname} repeated: #{Utils.scrub_html_and_truncate(content, 80)}"
115 %{activity: %{data: %{"type" => type}}},
118 when type in ["Follow", "Like"] do
120 "Follow" -> "@#{actor.nickname} has followed you"
121 "Like" -> "@#{actor.nickname} has favorited your post"
125 def format_title(%{activity: %{data: %{"type" => type}}}) do
127 "Create" -> "New Mention"
128 "Follow" -> "New Follower"
129 "Announce" -> "New Repeat"
130 "Like" -> "New Favorite"