Merge branch 'develop' of git.pleroma.social:pleroma/pleroma into remake-remodel-dms
[akkoma] / lib / pleroma / web / pleroma_api / controllers / chat_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4 defmodule Pleroma.Web.PleromaAPI.ChatController do
5 use Pleroma.Web, :controller
6
7 alias Pleroma.Chat
8 alias Pleroma.Object
9 alias Pleroma.Pagination
10 alias Pleroma.Plugs.OAuthScopesPlug
11 alias Pleroma.Repo
12 alias Pleroma.User
13 alias Pleroma.Web.CommonAPI
14 alias Pleroma.Web.PleromaAPI.ChatMessageView
15 alias Pleroma.Web.PleromaAPI.ChatView
16
17 import Ecto.Query
18
19 # TODO
20 # - Error handling
21
22 plug(
23 OAuthScopesPlug,
24 %{scopes: ["write:statuses"]} when action in [:post_chat_message, :create]
25 )
26
27 plug(
28 OAuthScopesPlug,
29 %{scopes: ["read:statuses"]} when action in [:messages, :index]
30 )
31
32 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.ChatOperation
33
34 def post_chat_message(%{assigns: %{user: %{id: user_id} = user}} = conn, %{
35 "id" => id,
36 "content" => content
37 }) do
38 with %Chat{} = chat <- Repo.get_by(Chat, id: id, user_id: user_id),
39 %User{} = recipient <- User.get_cached_by_ap_id(chat.recipient),
40 {:ok, activity} <- CommonAPI.post_chat_message(user, recipient, content),
41 message <- Object.normalize(activity) do
42 conn
43 |> put_view(ChatMessageView)
44 |> render("show.json", for: user, object: message, chat: chat)
45 end
46 end
47
48 def messages(%{assigns: %{user: %{id: user_id} = user}} = conn, %{"id" => id} = params) do
49 with %Chat{} = chat <- Repo.get_by(Chat, id: id, user_id: user_id) do
50 messages =
51 from(o in Object,
52 where: fragment("?->>'type' = ?", o.data, "ChatMessage"),
53 where:
54 fragment(
55 """
56 (?->>'actor' = ? and ?->'to' = ?)
57 OR (?->>'actor' = ? and ?->'to' = ?)
58 """,
59 o.data,
60 ^user.ap_id,
61 o.data,
62 ^[chat.recipient],
63 o.data,
64 ^chat.recipient,
65 o.data,
66 ^[user.ap_id]
67 )
68 )
69 |> Pagination.fetch_paginated(params)
70
71 conn
72 |> put_view(ChatMessageView)
73 |> render("index.json", for: user, objects: messages, chat: chat)
74 else
75 _ ->
76 conn
77 |> put_status(:not_found)
78 |> json(%{error: "not found"})
79 end
80 end
81
82 def index(%{assigns: %{user: %{id: user_id}}} = conn, params) do
83 chats =
84 from(c in Chat,
85 where: c.user_id == ^user_id,
86 order_by: [desc: c.updated_at]
87 )
88 |> Pagination.fetch_paginated(params)
89
90 conn
91 |> put_view(ChatView)
92 |> render("index.json", chats: chats)
93 end
94
95 def create(%{assigns: %{user: user}} = conn, params) do
96 recipient = params["ap_id"] |> URI.decode_www_form()
97
98 with {:ok, %Chat{} = chat} <- Chat.get_or_create(user.id, recipient) do
99 conn
100 |> put_view(ChatView)
101 |> render("show.json", chat: chat)
102 end
103 end
104 end