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
17 # - Views / Representers
20 def post_chat_message(%{assigns: %{user: %{id: user_id} = user}} = conn, %{
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"],
31 content: message.data["content"]
35 |> json(represented_message)
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
43 where: fragment("?->>'type' = ?", o.data, "ChatMessage"),
47 (?->>'actor' = ? and ?->'to' = ?)
48 OR (?->>'actor' = ? and ?->'to' = ?)
59 order_by: [desc: o.id]
63 represented_messages =
65 |> Enum.map(fn message ->
67 actor: message.data["actor"],
69 content: message.data["content"]
74 |> json(represented_messages)
78 def index(%{assigns: %{user: %{id: user_id}}} = conn, _params) do
81 where: c.user_id == ^user_id,
82 order_by: [desc: c.updated_at]
87 Enum.map(chats, fn chat ->
90 recipient: chat.recipient,
96 |> json(represented_chats)
99 def create(%{assigns: %{user: user}} = conn, params) do
100 recipient = params["ap_id"] |> URI.decode_www_form()
102 with {:ok, %Chat{} = chat} <- Chat.get_or_create(user.id, recipient) do
103 represented_chat = %{
105 recipient: chat.recipient,
110 |> json(represented_chat)