Wire up join requests to the old "chat:public" channel into the new "shout:public...
[akkoma] / lib / pleroma / web / shout_channel.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.ShoutChannel do
6 use Phoenix.Channel
7
8 alias Pleroma.User
9 alias Pleroma.Web.MastodonAPI.AccountView
10 alias Pleroma.Web.ShoutChannel.ShoutChannelState
11
12 # Backwards compatibility
13 def join("chat:public", message, socket), do: join("shout:public", message, socket)
14
15 def join("shout:public", _message, socket) do
16 send(self(), :after_join)
17 {:ok, socket}
18 end
19
20 def handle_info(:after_join, socket) do
21 push(socket, "messages", %{messages: ShoutChannelState.messages()})
22 {:noreply, socket}
23 end
24
25 def handle_in("new_msg", %{"text" => text}, %{assigns: %{user_name: user_name}} = socket) do
26 text = String.trim(text)
27
28 if String.length(text) in 1..Pleroma.Config.get([:shout, :limit]) do
29 author = User.get_cached_by_nickname(user_name)
30 author_json = AccountView.render("show.json", user: author, skip_visibility_check: true)
31
32 message = ShoutChannelState.add_message(%{text: text, author: author_json})
33
34 broadcast!(socket, "new_msg", message)
35 end
36
37 {:noreply, socket}
38 end
39 end
40
41 defmodule Pleroma.Web.ShoutChannel.ShoutChannelState do
42 use Agent
43
44 @max_messages 20
45
46 def start_link(_) do
47 Agent.start_link(fn -> %{max_id: 1, messages: []} end, name: __MODULE__)
48 end
49
50 def add_message(message) do
51 Agent.get_and_update(__MODULE__, fn state ->
52 id = state[:max_id] + 1
53 message = Map.put(message, "id", id)
54 messages = [message | state[:messages]] |> Enum.take(@max_messages)
55 {message, %{max_id: id, messages: messages}}
56 end)
57 end
58
59 def messages do
60 Agent.get(__MODULE__, fn state -> state[:messages] |> Enum.reverse() end)
61 end
62 end