Expose unannounce activity so that it can be tested
[akkoma] / lib / pleroma / web / chat_channel.ex
1 defmodule Pleroma.Web.ChatChannel do
2 use Phoenix.Channel
3 alias Pleroma.Web.ChatChannel.ChatChannelState
4 alias Pleroma.User
5
6 def join("chat:public", _message, socket) do
7 send(self(), :after_join)
8 {:ok, socket}
9 end
10
11 def handle_info(:after_join, socket) do
12 push(socket, "messages", %{messages: ChatChannelState.messages()})
13 {:noreply, socket}
14 end
15
16 def handle_in("new_msg", %{"text" => text}, %{assigns: %{user_name: user_name}} = socket) do
17 text = String.trim(text)
18
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})
23
24 broadcast!(socket, "new_msg", message)
25 end
26
27 {:noreply, socket}
28 end
29 end
30
31 defmodule Pleroma.Web.ChatChannel.ChatChannelState do
32 @max_messages 20
33
34 def start_link do
35 Agent.start_link(fn -> %{max_id: 1, messages: []} end, name: __MODULE__)
36 end
37
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}}
44 end)
45 end
46
47 def messages() do
48 Agent.get(__MODULE__, fn state -> state[:messages] |> Enum.reverse() end)
49 end
50 end