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
9 alias Pleroma.Pagination
10 alias Pleroma.Plugs.OAuthScopesPlug
13 alias Pleroma.Web.CommonAPI
14 alias Pleroma.Web.PleromaAPI.ChatMessageView
15 alias Pleroma.Web.PleromaAPI.ChatView
17 import Pleroma.Web.ActivityPub.ObjectValidator, only: [stringify_keys: 1]
26 %{scopes: ["write:statuses"]} when action in [:post_chat_message, :create]
31 %{scopes: ["read:statuses"]} when action in [:messages, :index]
34 plug(OpenApiSpex.Plug.CastAndValidate, render_error: Pleroma.Web.ApiSpec.RenderError)
36 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.ChatOperation
38 def post_chat_message(
39 %{body_params: %{content: content}, assigns: %{user: %{id: user_id} = user}} = conn,
44 with %Chat{} = chat <- Repo.get_by(Chat, id: id, user_id: user_id),
45 %User{} = recipient <- User.get_cached_by_ap_id(chat.recipient),
46 {:ok, activity} <- CommonAPI.post_chat_message(user, recipient, content),
47 message <- Object.normalize(activity) do
49 |> put_view(ChatMessageView)
50 |> render("show.json", for: user, object: message, chat: chat)
54 def messages(%{assigns: %{user: %{id: user_id} = user}} = conn, %{id: id} = params) do
55 with %Chat{} = chat <- Repo.get_by(Chat, id: id, user_id: user_id) do
58 where: fragment("?->>'type' = ?", o.data, "ChatMessage"),
62 (?->>'actor' = ? and ?->'to' = ?)
63 OR (?->>'actor' = ? and ?->'to' = ?)
75 |> Pagination.fetch_paginated(params |> stringify_keys())
78 |> put_view(ChatMessageView)
79 |> render("index.json", for: user, objects: messages, chat: chat)
83 |> put_status(:not_found)
84 |> json(%{error: "not found"})
88 def index(%{assigns: %{user: %{id: user_id}}} = conn, params) do
91 where: c.user_id == ^user_id,
92 order_by: [desc: c.updated_at]
94 |> Pagination.fetch_paginated(params |> stringify_keys)
98 |> render("index.json", chats: chats)
101 def create(%{assigns: %{user: user}} = conn, params) do
102 with %User{ap_id: recipient} <- User.get_by_id(params[:id]),
103 {:ok, %Chat{} = chat} <- Chat.get_or_create(user.id, recipient) do
105 |> put_view(ChatView)
106 |> render("show.json", chat: chat)