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