logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://hacktivis.me/git/pleroma.git

chat_channel.ex (1698B)


  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. defmodule Pleroma.Web.ChatChannel do
  5. use Phoenix.Channel
  6. alias Pleroma.User
  7. alias Pleroma.Web.ChatChannel.ChatChannelState
  8. alias Pleroma.Web.MastodonAPI.AccountView
  9. def join("chat:public", _message, socket) do
  10. send(self(), :after_join)
  11. {:ok, socket}
  12. end
  13. def handle_info(:after_join, socket) do
  14. push(socket, "messages", %{messages: ChatChannelState.messages()})
  15. {:noreply, socket}
  16. end
  17. def handle_in("new_msg", %{"text" => text}, %{assigns: %{user_name: user_name}} = socket) do
  18. text = String.trim(text)
  19. if String.length(text) in 1..Pleroma.Config.get([:instance, :chat_limit]) do
  20. author = User.get_cached_by_nickname(user_name)
  21. author_json = AccountView.render("show.json", user: author, skip_visibility_check: true)
  22. message = ChatChannelState.add_message(%{text: text, author: author_json})
  23. broadcast!(socket, "new_msg", message)
  24. end
  25. {:noreply, socket}
  26. end
  27. end
  28. defmodule Pleroma.Web.ChatChannel.ChatChannelState do
  29. use Agent
  30. @max_messages 20
  31. def start_link(_) do
  32. Agent.start_link(fn -> %{max_id: 1, messages: []} end, name: __MODULE__)
  33. end
  34. def add_message(message) do
  35. Agent.get_and_update(__MODULE__, fn state ->
  36. id = state[:max_id] + 1
  37. message = Map.put(message, "id", id)
  38. messages = [message | state[:messages]] |> Enum.take(@max_messages)
  39. {message, %{max_id: id, messages: messages}}
  40. end)
  41. end
  42. def messages do
  43. Agent.get(__MODULE__, fn state -> state[:messages] |> Enum.reverse() end)
  44. end
  45. end