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
11 alias Pleroma.Web.CommonAPI
12 alias Pleroma.Web.PleromaAPI.ChatView
13 alias Pleroma.Web.PleromaAPI.ChatMessageView
14 alias Pleroma.Pagination
20 # - Views / Representers
23 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.ChatOperation
25 def post_chat_message(%{assigns: %{user: %{id: user_id} = user}} = conn, %{
29 with %Chat{} = chat <- Repo.get_by(Chat, id: id, user_id: user_id),
30 %User{} = recipient <- User.get_cached_by_ap_id(chat.recipient),
31 {:ok, activity} <- CommonAPI.post_chat_message(user, recipient, content),
32 message <- Object.normalize(activity) do
34 |> put_view(ChatMessageView)
35 |> render("show.json", for: user, object: message, chat: chat)
39 def messages(%{assigns: %{user: %{id: user_id} = user}} = conn, %{"id" => id} = params) do
40 with %Chat{} = chat <- Repo.get_by(Chat, id: id, user_id: user_id) do
43 where: fragment("?->>'type' = ?", o.data, "ChatMessage"),
47 (?->>'actor' = ? and ?->'to' = ?)
48 OR (?->>'actor' = ? and ?->'to' = ?)
60 |> Pagination.fetch_paginated(params)
63 |> put_view(ChatMessageView)
64 |> render("index.json", for: user, objects: messages, chat: chat)
68 def index(%{assigns: %{user: %{id: user_id}}} = conn, params) do
71 where: c.user_id == ^user_id,
72 order_by: [desc: c.updated_at]
74 |> Pagination.fetch_paginated(params)
78 |> render("index.json", chats: chats)
81 def create(%{assigns: %{user: user}} = conn, params) do
82 recipient = params["ap_id"] |> URI.decode_www_form()
84 with {:ok, %Chat{} = chat} <- Chat.get_or_create(user.id, recipient) do
87 |> render("show.json", chat: chat)