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)
27 message = ChatChannelState.add_message(%{text: text, author: author})
29 broadcast!(socket, "new_msg", message)
36 defmodule Pleroma.Web.ChatChannel.ChatChannelState do
42 Agent.start_link(fn -> %{max_id: 1, messages: []} end, name: __MODULE__)
45 def add_message(message) do
46 Agent.get_and_update(__MODULE__, fn state ->
47 id = state[:max_id] + 1
48 message = Map.put(message, "id", id)
49 messages = [message | state[:messages]] |> Enum.take(@max_messages)
50 {message, %{max_id: id, messages: messages}}
55 Agent.get(__MODULE__, fn state -> state[:messages] |> Enum.reverse() end)