Merge branch 'develop' of https://git.pleroma.social/pleroma/pleroma into develop
[akkoma] / lib / pleroma / web / twitter_api / twitter_api_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.TwitterAPI.Controller do
6 use Pleroma.Web, :controller
7
8 alias Pleroma.Notification
9 alias Pleroma.Plugs.OAuthScopesPlug
10 alias Pleroma.User
11 alias Pleroma.Web.OAuth.Token
12 alias Pleroma.Web.TwitterAPI.TokenView
13
14 require Logger
15
16 plug(OAuthScopesPlug, %{scopes: ["write:notifications"]} when action == :notifications_read)
17
18 plug(:skip_plug, OAuthScopesPlug when action in [:oauth_tokens, :revoke_token])
19
20 plug(Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug)
21
22 action_fallback(:errors)
23
24 def confirm_email(conn, %{"user_id" => uid, "token" => token}) do
25 with %User{} = user <- User.get_cached_by_id(uid),
26 true <- user.local and user.confirmation_pending and user.confirmation_token == token,
27 {:ok, _} <-
28 user
29 |> User.confirmation_changeset(need_confirmation: false)
30 |> User.update_and_set_cache() do
31 redirect(conn, to: "/")
32 end
33 end
34
35 def oauth_tokens(%{assigns: %{user: user}} = conn, _params) do
36 with oauth_tokens <- Token.get_user_tokens(user) do
37 conn
38 |> put_view(TokenView)
39 |> render("index.json", %{tokens: oauth_tokens})
40 end
41 end
42
43 def revoke_token(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
44 Token.delete_user_token(user, id)
45
46 json_reply(conn, 201, "")
47 end
48
49 def errors(conn, {:param_cast, _}) do
50 conn
51 |> put_status(400)
52 |> json("Invalid parameters")
53 end
54
55 def errors(conn, _) do
56 conn
57 |> put_status(500)
58 |> json("Something went wrong")
59 end
60
61 defp json_reply(conn, status, json) do
62 conn
63 |> put_resp_content_type("application/json")
64 |> send_resp(status, json)
65 end
66
67 def notifications_read(%{assigns: %{user: user}} = conn, %{"latest_id" => latest_id} = params) do
68 Notification.set_read_up_to(user, latest_id)
69
70 notifications = Notification.for_user(user, params)
71
72 conn
73 # XXX: This is a hack because pleroma-fe still uses that API.
74 |> put_view(Pleroma.Web.MastodonAPI.NotificationView)
75 |> render("index.json", %{notifications: notifications, for: user})
76 end
77
78 def notifications_read(%{assigns: %{user: _user}} = conn, _) do
79 bad_request_reply(conn, "You need to specify latest_id")
80 end
81
82 defp bad_request_reply(conn, error_message) do
83 json = error_json(conn, error_message)
84 json_reply(conn, 400, json)
85 end
86
87 defp error_json(conn, error_message) do
88 %{"error" => error_message, "request" => conn.request_path} |> Jason.encode!()
89 end
90 end