[#1234] Merge remote-tracking branch 'remotes/upstream/develop' into 1234-mastodon...
[akkoma] / lib / pleroma / web / mastodon_api / controllers / subscription_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 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 alias Pleroma.Web.MastodonAPI.PushSubscriptionView, as: View
12
13 action_fallback(:errors)
14
15 plug(Pleroma.Plugs.OAuthScopesPlug, %{scopes: ["push"]})
16
17 # Creates PushSubscription
18 # POST /api/v1/push/subscription
19 #
20 def create(%{assigns: %{user: user, token: token}} = conn, params) do
21 with true <- Push.enabled(),
22 {:ok, _} <- Subscription.delete_if_exists(user, token),
23 {:ok, subscription} <- Subscription.create(user, token, params) do
24 view = View.render("push_subscription.json", subscription: subscription)
25 json(conn, view)
26 end
27 end
28
29 # Gets PushSubscription
30 # GET /api/v1/push/subscription
31 #
32 def get(%{assigns: %{user: user, token: token}} = conn, _params) do
33 with true <- Push.enabled(),
34 {:ok, subscription} <- Subscription.get(user, token) do
35 view = View.render("push_subscription.json", subscription: subscription)
36 json(conn, view)
37 end
38 end
39
40 # Updates PushSubscription
41 # PUT /api/v1/push/subscription
42 #
43 def update(%{assigns: %{user: user, token: token}} = conn, params) do
44 with true <- Push.enabled(),
45 {:ok, subscription} <- Subscription.update(user, token, params) do
46 view = View.render("push_subscription.json", subscription: subscription)
47 json(conn, view)
48 end
49 end
50
51 # Deletes PushSubscription
52 # DELETE /api/v1/push/subscription
53 #
54 def delete(%{assigns: %{user: user, token: token}} = conn, _params) do
55 with true <- Push.enabled(),
56 {:ok, _response} <- Subscription.delete(user, token),
57 do: json(conn, %{})
58 end
59
60 # fallback action
61 #
62 def errors(conn, {:error, :not_found}) do
63 conn
64 |> put_status(:not_found)
65 |> json(dgettext("errors", "Not found"))
66 end
67
68 def errors(conn, _) do
69 Pleroma.Web.MastodonAPI.FallbackController.call(conn, nil)
70 end
71 end