Merge branch 'develop' into refactor/gun-pool-registry
[akkoma] / lib / pleroma / web / chat_channel.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.ChatChannel do
6 use Phoenix.Channel
7 alias Pleroma.User
8 alias Pleroma.Web.ChatChannel.ChatChannelState
9
10 def join("chat:public", _message, socket) do
11 send(self(), :after_join)
12 {:ok, socket}
13 end
14
15 def handle_info(:after_join, socket) do
16 push(socket, "messages", %{messages: ChatChannelState.messages()})
17 {:noreply, socket}
18 end
19
20 def handle_in("new_msg", %{"text" => text}, %{assigns: %{user_name: user_name}} = socket) do
21 text = String.trim(text)
22
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
27 message = ChatChannelState.add_message(%{text: text, author: author})
28
29 broadcast!(socket, "new_msg", message)
30 end
31
32 {:noreply, socket}
33 end
34 end
35
36 defmodule Pleroma.Web.ChatChannel.ChatChannelState do
37 use Agent
38
39 @max_messages 20
40
41 def start_link(_) do
42 Agent.start_link(fn -> %{max_id: 1, messages: []} end, name: __MODULE__)
43 end
44
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}}
51 end)
52 end
53
54 def messages do
55 Agent.get(__MODULE__, fn state -> state[:messages] |> Enum.reverse() end)
56 end
57 end