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