972330f4e0c4f7dfaedf604e352528d86e90b359
[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.Repo
10 alias Pleroma.User
11 alias Pleroma.Web.CommonAPI
12
13 import Ecto.Query
14
15 # TODO
16 # - Oauth stuff
17 # - Views / Representers
18 # - Error handling
19
20 def post_chat_message(%{assigns: %{user: %{id: user_id} = user}} = conn, %{
21 "id" => id,
22 "content" => content
23 }) do
24 with %Chat{} = chat <- Repo.get_by(Chat, id: id, user_id: user_id),
25 %User{} = recipient <- User.get_cached_by_ap_id(chat.recipient),
26 {:ok, activity} <- CommonAPI.post_chat_message(user, recipient, content),
27 message <- Object.normalize(activity) do
28 represented_message = %{
29 actor: message.data["actor"],
30 id: message.id,
31 content: message.data["content"]
32 }
33
34 conn
35 |> json(represented_message)
36 end
37 end
38
39 def messages(%{assigns: %{user: %{id: user_id} = user}} = conn, %{"id" => id}) do
40 with %Chat{} = chat <- Repo.get_by(Chat, id: id, user_id: user_id) do
41 messages =
42 from(o in Object,
43 where: fragment("?->>'type' = ?", o.data, "ChatMessage"),
44 where:
45 fragment(
46 """
47 (?->>'actor' = ? and ?->'to' = ?)
48 OR (?->>'actor' = ? and ?->'to' = ?)
49 """,
50 o.data,
51 ^user.ap_id,
52 o.data,
53 ^[chat.recipient],
54 o.data,
55 ^chat.recipient,
56 o.data,
57 ^[user.ap_id]
58 ),
59 order_by: [desc: o.id]
60 )
61 |> Repo.all()
62
63 represented_messages =
64 messages
65 |> Enum.map(fn message ->
66 %{
67 actor: message.data["actor"],
68 id: message.id,
69 content: message.data["content"]
70 }
71 end)
72
73 conn
74 |> json(represented_messages)
75 end
76 end
77
78 def index(%{assigns: %{user: %{id: user_id}}} = conn, _params) do
79 chats =
80 from(c in Chat,
81 where: c.user_id == ^user_id,
82 order_by: [desc: c.updated_at]
83 )
84 |> Repo.all()
85
86 represented_chats =
87 Enum.map(chats, fn chat ->
88 %{
89 id: chat.id,
90 recipient: chat.recipient,
91 unread: chat.unread
92 }
93 end)
94
95 conn
96 |> json(represented_chats)
97 end
98
99 def create(%{assigns: %{user: user}} = conn, params) do
100 recipient = params["ap_id"] |> URI.decode_www_form()
101
102 with {:ok, %Chat{} = chat} <- Chat.get_or_create(user.id, recipient) do
103 represented_chat = %{
104 id: chat.id,
105 recipient: chat.recipient,
106 unread: chat.unread
107 }
108
109 conn
110 |> json(represented_chat)
111 end
112 end
113 end