Merge branch 'docs/debian-packages' into 'develop'
[akkoma] / lib / pleroma / web / mastodon_api / controllers / subscription_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.MastodonAPI.SubscriptionController do
6 @moduledoc "The module represents functions to manage user subscriptions."
7 use Pleroma.Web, :controller
8
9 alias Pleroma.Web.Push
10 alias Pleroma.Web.Push.Subscription
11
12 action_fallback(:errors)
13
14 plug(Pleroma.Plugs.OAuthScopesPlug, %{scopes: ["push"]})
15 plug(Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug)
16 plug(:restrict_push_enabled)
17
18 # Creates PushSubscription
19 # POST /api/v1/push/subscription
20 #
21 def create(%{assigns: %{user: user, token: token}} = conn, params) do
22 with {:ok, _} <- Subscription.delete_if_exists(user, token),
23 {:ok, subscription} <- Subscription.create(user, token, params) do
24 render(conn, "show.json", subscription: subscription)
25 end
26 end
27
28 # Gets PushSubscription
29 # GET /api/v1/push/subscription
30 #
31 def get(%{assigns: %{user: user, token: token}} = conn, _params) do
32 with {:ok, subscription} <- Subscription.get(user, token) do
33 render(conn, "show.json", subscription: subscription)
34 end
35 end
36
37 # Updates PushSubscription
38 # PUT /api/v1/push/subscription
39 #
40 def update(%{assigns: %{user: user, token: token}} = conn, params) do
41 with {:ok, subscription} <- Subscription.update(user, token, params) do
42 render(conn, "show.json", subscription: subscription)
43 end
44 end
45
46 # Deletes PushSubscription
47 # DELETE /api/v1/push/subscription
48 #
49 def delete(%{assigns: %{user: user, token: token}} = conn, _params) do
50 with {:ok, _response} <- Subscription.delete(user, token),
51 do: json(conn, %{})
52 end
53
54 defp restrict_push_enabled(conn, _) do
55 if Push.enabled() do
56 conn
57 else
58 conn
59 |> render_error(:forbidden, "Web push subscription is disabled on this Pleroma instance")
60 |> halt()
61 end
62 end
63
64 # fallback action
65 #
66 def errors(conn, {:error, :not_found}) do
67 conn
68 |> put_status(:not_found)
69 |> json(dgettext("errors", "Not found"))
70 end
71
72 def errors(conn, _) do
73 Pleroma.Web.MastodonAPI.FallbackController.call(conn, nil)
74 end
75 end