Add ability to follow hashtags (#336)
[akkoma] / lib / pleroma / web / mastodon_api / controllers / subscription_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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.Web.ApiSpec.CastAndValidate)
15 plug(:restrict_push_enabled)
16 plug(Pleroma.Web.Plugs.OAuthScopesPlug, %{scopes: ["push"]})
17
18 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.SubscriptionOperation
19
20 # Creates PushSubscription
21 # POST /api/v1/push/subscription
22 #
23 def create(%{assigns: %{user: user, token: token}, body_params: params} = conn, _) do
24 with {:ok, _} <- Subscription.delete_if_exists(user, token),
25 {:ok, subscription} <- Subscription.create(user, token, params) do
26 render(conn, "show.json", subscription: subscription)
27 end
28 end
29
30 # Gets PushSubscription
31 # GET /api/v1/push/subscription
32 #
33 def show(%{assigns: %{user: user, token: token}} = conn, _params) do
34 with {:ok, subscription} <- Subscription.get(user, token) do
35 render(conn, "show.json", subscription: subscription)
36 end
37 end
38
39 # Updates PushSubscription
40 # PUT /api/v1/push/subscription
41 #
42 def update(%{assigns: %{user: user, token: token}, body_params: params} = conn, _) do
43 with {:ok, subscription} <- Subscription.update(user, token, params) do
44 render(conn, "show.json", subscription: subscription)
45 end
46 end
47
48 # Deletes PushSubscription
49 # DELETE /api/v1/push/subscription
50 #
51 def delete(%{assigns: %{user: user, token: token}} = conn, _params) do
52 with {:ok, _response} <- Subscription.delete(user, token),
53 do: json(conn, %{})
54 end
55
56 defp restrict_push_enabled(conn, _) do
57 if Push.enabled() do
58 conn
59 else
60 conn
61 |> render_error(:forbidden, "Web push subscription is disabled on this Pleroma instance")
62 |> halt()
63 end
64 end
65
66 # fallback action
67 #
68 def errors(conn, {:error, :not_found}) do
69 conn
70 |> put_status(:not_found)
71 |> json(%{error: dgettext("errors", "Record not found")})
72 end
73
74 def errors(conn, _) do
75 Pleroma.Web.MastodonAPI.FallbackController.call(conn, nil)
76 end
77 end