update mastofe paths (#95)
[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 def join("chat:public", _message, socket) do
13 send(self(), :after_join)
14 {:ok, socket}
15 end
16
17 def handle_info(:after_join, socket) do
18 push(socket, "messages", %{messages: ShoutChannelState.messages()})
19 {:noreply, socket}
20 end
21
22 def handle_in("new_msg", %{"text" => text}, %{assigns: %{user_name: user_name}} = socket) do
23 text = String.trim(text)
24
25 if String.length(text) in 1..Pleroma.Config.get([:shout, :limit]) do
26 author = User.get_cached_by_nickname(user_name)
27 author_json = AccountView.render("show.json", user: author, skip_visibility_check: true)
28
29 message = ShoutChannelState.add_message(%{text: text, author: author_json})
30
31 broadcast!(socket, "new_msg", message)
32 end
33
34 {:noreply, socket}
35 end
36 end
37
38 defmodule Pleroma.Web.ShoutChannel.ShoutChannelState do
39 use Agent
40
41 @max_messages 20
42
43 def start_link(_) do
44 Agent.start_link(fn -> %{max_id: 1, messages: []} end, name: __MODULE__)
45 end
46
47 def add_message(message) do
48 Agent.get_and_update(__MODULE__, fn state ->
49 id = state[:max_id] + 1
50 message = Map.put(message, "id", id)
51 messages = [message | state[:messages]] |> Enum.take(@max_messages)
52 {message, %{max_id: id, messages: messages}}
53 end)
54 end
55
56 def messages do
57 Agent.get(__MODULE__, fn state -> state[:messages] |> Enum.reverse() end)
58 end
59 end