e2b17aab1ebd7e7bc894bc65f0d6a11f4203ad08
[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 # Creates PushSubscription
16 # POST /api/v1/push/subscription
17 #
18 def create(%{assigns: %{user: user, token: token}} = conn, params) do
19 with true <- Push.enabled(),
20 {:ok, _} <- Subscription.delete_if_exists(user, token),
21 {:ok, subscription} <- Subscription.create(user, token, params) do
22 view = View.render("push_subscription.json", subscription: subscription)
23 json(conn, view)
24 end
25 end
26
27 # Gets PushSubscription
28 # GET /api/v1/push/subscription
29 #
30 def get(%{assigns: %{user: user, token: token}} = conn, _params) do
31 with true <- Push.enabled(),
32 {:ok, subscription} <- Subscription.get(user, token) do
33 view = View.render("push_subscription.json", subscription: subscription)
34 json(conn, view)
35 end
36 end
37
38 # Updates PushSubscription
39 # PUT /api/v1/push/subscription
40 #
41 def update(%{assigns: %{user: user, token: token}} = conn, params) do
42 with true <- Push.enabled(),
43 {:ok, subscription} <- Subscription.update(user, token, params) do
44 view = View.render("push_subscription.json", subscription: subscription)
45 json(conn, view)
46 end
47 end
48
49 # Deletes PushSubscription
50 # DELETE /api/v1/push/subscription
51 #
52 def delete(%{assigns: %{user: user, token: token}} = conn, _params) do
53 with true <- Push.enabled(),
54 {:ok, _response} <- Subscription.delete(user, token),
55 do: json(conn, %{})
56 end
57
58 # fallback action
59 #
60 def errors(conn, {:error, :not_found}) do
61 conn
62 |> put_status(:not_found)
63 |> json(dgettext("errors", "Not found"))
64 end
65
66 def errors(conn, _) do
67 Pleroma.Web.MastodonAPI.FallbackController.call(conn, nil)
68 end
69 end