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