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.Plugs.OAuthScopesPlug
12 alias Pleroma.Web.CommonAPI
13 alias Pleroma.Web.PleromaAPI.ChatView
14 alias Pleroma.Web.PleromaAPI.ChatMessageView
15 alias Pleroma.Pagination
24 %{scopes: ["write:statuses"]} when action in [:post_chat_message, :create]
29 %{scopes: ["read:statuses"]} when action in [:messages, :index]
32 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.ChatOperation
34 def post_chat_message(%{assigns: %{user: %{id: user_id} = user}} = conn, %{
38 with %Chat{} = chat <- Repo.get_by(Chat, id: id, user_id: user_id),
39 %User{} = recipient <- User.get_cached_by_ap_id(chat.recipient),
40 {:ok, activity} <- CommonAPI.post_chat_message(user, recipient, content),
41 message <- Object.normalize(activity) do
43 |> put_view(ChatMessageView)
44 |> render("show.json", for: user, object: message, chat: chat)
48 def messages(%{assigns: %{user: %{id: user_id} = user}} = conn, %{"id" => id} = params) do
49 with %Chat{} = chat <- Repo.get_by(Chat, id: id, user_id: user_id) do
52 where: fragment("?->>'type' = ?", o.data, "ChatMessage"),
56 (?->>'actor' = ? and ?->'to' = ?)
57 OR (?->>'actor' = ? and ?->'to' = ?)
69 |> Pagination.fetch_paginated(params)
72 |> put_view(ChatMessageView)
73 |> render("index.json", for: user, objects: messages, chat: chat)
77 |> put_status(:not_found)
78 |> json(%{error: "not found"})
82 def index(%{assigns: %{user: %{id: user_id}}} = conn, params) do
85 where: c.user_id == ^user_id,
86 order_by: [desc: c.updated_at]
88 |> Pagination.fetch_paginated(params)
92 |> render("index.json", chats: chats)
95 def create(%{assigns: %{user: user}} = conn, params) do
96 recipient = params["ap_id"] |> URI.decode_www_form()
98 with {:ok, %Chat{} = chat} <- Chat.get_or_create(user.id, recipient) do
100 |> put_view(ChatView)
101 |> render("show.json", chat: chat)