Merge branch 'bugfix/1395-email-activation' into 'develop'
[akkoma] / lib / pleroma / web / chat_channel.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 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) > 0 do
24 author = User.get_cached_by_nickname(user_name)
25 author = Pleroma.Web.MastodonAPI.AccountView.render("show.json", user: author)
26 message = ChatChannelState.add_message(%{text: text, author: author})
27
28 broadcast!(socket, "new_msg", message)
29 end
30
31 {:noreply, socket}
32 end
33 end
34
35 defmodule Pleroma.Web.ChatChannel.ChatChannelState do
36 use Agent
37
38 @max_messages 20
39
40 def start_link(_) do
41 Agent.start_link(fn -> %{max_id: 1, messages: []} end, name: __MODULE__)
42 end
43
44 def add_message(message) do
45 Agent.get_and_update(__MODULE__, fn state ->
46 id = state[:max_id] + 1
47 message = Map.put(message, "id", id)
48 messages = [message | state[:messages]] |> Enum.take(@max_messages)
49 {message, %{max_id: id, messages: messages}}
50 end)
51 end
52
53 def messages do
54 Agent.get(__MODULE__, fn state -> state[:messages] |> Enum.reverse() end)
55 end
56 end