1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Push.Subscription do
12 alias Pleroma.Web.OAuth.Token
13 alias Pleroma.Web.Push.Subscription
15 @type t :: %__MODULE__{}
17 schema "push_subscriptions" do
18 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
19 belongs_to(:token, Token)
20 field(:endpoint, :string)
21 field(:key_p256dh, :string)
22 field(:key_auth, :string)
23 field(:data, :map, default: %{})
28 @supported_alert_types ~w[follow favourite mention reblog]a
30 defp alerts(%{data: %{alerts: alerts}}) do
31 alerts = Map.take(alerts, @supported_alert_types)
35 def enabled?(subscription, "follow_request") do
36 enabled?(subscription, "follow")
39 def enabled?(subscription, alert_type) do
40 get_in(subscription.data, ["alerts", alert_type])
49 keys: %{auth: key_auth, p256dh: key_p256dh}
53 Repo.insert(%Subscription{
57 key_auth: ensure_base64_urlsafe(key_auth),
58 key_p256dh: ensure_base64_urlsafe(key_p256dh),
63 @doc "Gets subsciption by user & token"
64 @spec get(User.t(), Token.t()) :: {:ok, t()} | {:error, :not_found}
65 def get(%User{id: user_id}, %Token{id: token_id}) do
66 case Repo.get_by(Subscription, user_id: user_id, token_id: token_id) do
67 nil -> {:error, :not_found}
68 subscription -> {:ok, subscription}
72 def update(user, token, params) do
73 with {:ok, subscription} <- get(user, token) do
75 |> change(data: alerts(params))
80 def delete(user, token) do
81 with {:ok, subscription} <- get(user, token),
82 do: Repo.delete(subscription)
85 def delete_if_exists(user, token) do
86 case get(user, token) do
87 {:error, _} -> {:ok, nil}
88 {:ok, sub} -> Repo.delete(sub)
92 # Some webpush clients (e.g. iOS Toot!) use an non urlsafe base64 as an encoding for the key.
93 # However, the web push rfs specify to use base64 urlsafe, and the `web_push_encryption` library
94 # we use requires the key to be properly encoded. So we just convert base64 to urlsafe base64.
95 defp ensure_base64_urlsafe(string) do
97 |> String.replace("+", "-")
98 |> String.replace("/", "_")
99 |> String.replace("=", "")