1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.ChatChannel do
8 alias Pleroma.Web.ChatChannel.ChatChannelState
10 def join("chat:public", _message, socket) do
11 send(self(), :after_join)
15 def handle_info(:after_join, socket) do
16 push(socket, "messages", %{messages: ChatChannelState.messages()})
20 def handle_in("new_msg", %{"text" => text}, %{assigns: %{user_name: user_name}} = socket) do
21 text = String.trim(text)
23 if String.length(text) in 1..Pleroma.Config.get([:instance, :chat_limit]) do
24 author = User.get_cached_by_nickname(user_name)
25 author = Pleroma.Web.MastodonAPI.AccountView.render("show.json", user: author)
26 message = ChatChannelState.add_message(%{text: text, author: author})
28 broadcast!(socket, "new_msg", message)
35 defmodule Pleroma.Web.ChatChannel.ChatChannelState do
41 Agent.start_link(fn -> %{max_id: 1, messages: []} end, name: __MODULE__)
44 def add_message(message) do
45 Agent.get_and_update(__MODULE__, fn state ->
46 id = state[:max_id] + 1
47 message = Map.put(message, "id", id)
48 messages = [message | state[:messages]] |> Enum.take(@max_messages)
49 {message, %{max_id: id, messages: messages}}
54 Agent.get(__MODULE__, fn state -> state[:messages] |> Enum.reverse() end)