ChatController: Add creation and return of chats.
[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.Repo
9
10 import Ecto.Query
11
12 def index(%{assigns: %{user: %{id: user_id}}} = conn, _params) do
13 chats =
14 from(c in Chat,
15 where: c.user_id == ^user_id,
16 order_by: [desc: c.updated_at]
17 )
18 |> Repo.all()
19
20 represented_chats =
21 Enum.map(chats, fn chat ->
22 %{
23 id: chat.id,
24 recipient: chat.recipient,
25 unread: chat.unread
26 }
27 end)
28
29 conn
30 |> json(represented_chats)
31 end
32
33 def create(%{assigns: %{user: user}} = conn, params) do
34 recipient = params["ap_id"] |> URI.decode_www_form()
35
36 with {:ok, %Chat{} = chat} <- Chat.get_or_create(user.id, recipient) do
37 represented_chat = %{
38 id: chat.id,
39 recipient: chat.recipient,
40 unread: chat.unread
41 }
42
43 conn
44 |> json(represented_chat)
45 end
46 end
47 end