1 defmodule Pleroma.Web.ChatChannel do
3 alias Pleroma.Web.ChatChannel.ChatChannelState
6 def join("chat:public", _message, socket) do
7 send(self(), :after_join)
11 def handle_info(:after_join, socket) do
12 push(socket, "messages", %{messages: ChatChannelState.messages()})
16 def handle_in("new_msg", %{"text" => text}, %{assigns: %{user_name: user_name}} = socket) do
17 text = String.trim(text)
19 if String.length(text) > 0 do
20 author = User.get_cached_by_nickname(user_name)
21 author = Pleroma.Web.MastodonAPI.AccountView.render("account.json", user: author)
22 message = ChatChannelState.add_message(%{text: text, author: author})
24 broadcast!(socket, "new_msg", message)
31 defmodule Pleroma.Web.ChatChannel.ChatChannelState do
35 Agent.start_link(fn -> %{max_id: 1, messages: []} end, name: __MODULE__)
38 def add_message(message) do
39 Agent.get_and_update(__MODULE__, fn state ->
40 id = state[:max_id] + 1
41 message = Map.put(message, "id", id)
42 messages = [message | state[:messages]] |> Enum.take(@max_messages)
43 {message, %{max_id: id, messages: messages}}
48 Agent.get(__MODULE__, fn state -> state[:messages] |> Enum.reverse() end)