1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.ChatChannel do
9 alias Pleroma.Web.ChatChannel.ChatChannelState
10 alias Pleroma.Web.MastodonAPI.AccountView
12 def join("chat:public", _message, socket) do
13 send(self(), :after_join)
17 def handle_info(:after_join, socket) do
18 push(socket, "messages", %{messages: ChatChannelState.messages()})
22 def handle_in("new_msg", %{"text" => text}, %{assigns: %{user_name: user_name}} = socket) do
23 text = String.trim(text)
25 if String.length(text) in 1..Pleroma.Config.get([:instance, :chat_limit]) do
26 author = User.get_cached_by_nickname(user_name)
27 author_json = AccountView.render("show.json", user: author, skip_visibility_check: true)
29 message = ChatChannelState.add_message(%{text: text, author: author_json})
31 broadcast!(socket, "new_msg", message)
38 defmodule Pleroma.Web.ChatChannel.ChatChannelState do
44 Agent.start_link(fn -> %{max_id: 1, messages: []} end, name: __MODULE__)
47 def add_message(message) do
48 Agent.get_and_update(__MODULE__, fn state ->
49 id = state[:max_id] + 1
50 message = Map.put(message, "id", id)
51 messages = [message | state[:messages]] |> Enum.take(@max_messages)
52 {message, %{max_id: id, messages: messages}}
57 Agent.get(__MODULE__, fn state -> state[:messages] |> Enum.reverse() end)