First
[anni] / lib / pleroma / web / admin_api / controllers / chat_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.AdminAPI.ChatController do
6   use Pleroma.Web, :controller
7
8   alias Pleroma.Activity
9   alias Pleroma.Chat
10   alias Pleroma.Chat.MessageReference
11   alias Pleroma.Pagination
12   alias Pleroma.Web.AdminAPI
13   alias Pleroma.Web.CommonAPI
14   alias Pleroma.Web.PleromaAPI.Chat.MessageReferenceView
15   alias Pleroma.Web.Plugs.OAuthScopesPlug
16
17   require Logger
18
19   plug(Pleroma.Web.ApiSpec.CastAndValidate)
20
21   plug(
22     OAuthScopesPlug,
23     %{scopes: ["admin:read:chats"]} when action in [:show, :messages]
24   )
25
26   plug(
27     OAuthScopesPlug,
28     %{scopes: ["admin:write:chats"]} when action in [:delete_message]
29   )
30
31   action_fallback(Pleroma.Web.AdminAPI.FallbackController)
32
33   defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.Admin.ChatOperation
34
35   def delete_message(%{assigns: %{user: user}} = conn, %{
36         message_id: message_id,
37         id: chat_id
38       }) do
39     with %MessageReference{object: %{data: %{"id" => object_ap_id}}} = cm_ref <-
40            MessageReference.get_by_id(message_id),
41          ^chat_id <- to_string(cm_ref.chat_id),
42          %Activity{id: activity_id} <- Activity.get_create_by_object_ap_id(object_ap_id),
43          {:ok, _} <- CommonAPI.delete(activity_id, user) do
44       conn
45       |> put_view(MessageReferenceView)
46       |> render("show.json", chat_message_reference: cm_ref)
47     else
48       _e ->
49         {:error, :could_not_delete}
50     end
51   end
52
53   def messages(conn, %{id: id} = params) do
54     with %Chat{} = chat <- Chat.get_by_id(id) do
55       cm_refs =
56         chat
57         |> MessageReference.for_chat_query()
58         |> Pagination.fetch_paginated(params)
59
60       conn
61       |> put_view(MessageReferenceView)
62       |> render("index.json", chat_message_references: cm_refs)
63     else
64       _ ->
65         conn
66         |> put_status(:not_found)
67         |> json(%{error: "not found"})
68     end
69   end
70
71   def show(conn, %{id: id}) do
72     with %Chat{} = chat <- Chat.get_by_id(id) do
73       conn
74       |> put_view(AdminAPI.ChatView)
75       |> render("show.json", chat: chat)
76     end
77   end
78 end