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