1 defmodule Pleroma.Web.Streamer do
4 alias Pleroma.{User, Notification}
9 Process.sleep(1000 * 30)
10 GenServer.cast(__MODULE__, %{action: :ping})
13 GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
16 def add_socket(topic, socket) do
17 GenServer.cast(__MODULE__, %{action: :add, socket: socket, topic: topic})
20 def remove_socket(topic, socket) do
21 GenServer.cast(__MODULE__, %{action: :remove, socket: socket, topic: topic})
24 def stream(topic, item) do
25 GenServer.cast(__MODULE__, %{action: :stream, topic: topic, item: item})
28 def handle_cast(%{action: :ping}, topics) do
31 |> Enum.each(fn socket ->
32 Logger.debug("Sending keepalive ping")
33 send(socket.transport_pid, {:text, ""})
38 Process.sleep(1000 * 30)
39 GenServer.cast(__MODULE__, %{action: :ping})
45 def handle_cast(%{action: :stream, topic: "user", item: %Notification{} = item}, topics) do
46 topic = "user:#{item.user_id}"
48 Enum.each(topics[topic] || [], fn socket ->
51 event: "notification",
53 Pleroma.Web.MastodonAPI.MastodonAPIController.render_notification(
54 socket.assigns["user"],
61 send(socket.transport_pid, {:text, json})
67 def handle_cast(%{action: :stream, topic: "user", item: item}, topics) do
68 Logger.debug("Trying to push to users")
71 User.get_recipients_from_activity(item)
72 |> Enum.map(fn %{id: id} -> "user:#{id}" end)
74 Enum.each(recipient_topics, fn topic ->
75 push_to_socket(topics, topic, item)
81 def handle_cast(%{action: :stream, topic: topic, item: item}, topics) do
82 Logger.debug("Trying to push to #{topic}")
83 Logger.debug("Pushing item to #{topic}")
84 push_to_socket(topics, topic, item)
88 def handle_cast(%{action: :add, topic: topic, socket: socket}, sockets) do
89 topic = internal_topic(topic, socket)
90 sockets_for_topic = sockets[topic] || []
91 sockets_for_topic = Enum.uniq([socket | sockets_for_topic])
92 sockets = Map.put(sockets, topic, sockets_for_topic)
93 Logger.debug("Got new conn for #{topic}")
97 def handle_cast(%{action: :remove, topic: topic, socket: socket}, sockets) do
98 topic = internal_topic(topic, socket)
99 sockets_for_topic = sockets[topic] || []
100 sockets_for_topic = List.delete(sockets_for_topic, socket)
101 sockets = Map.put(sockets, topic, sockets_for_topic)
102 Logger.debug("Removed conn for #{topic}")
106 def handle_cast(m, state) do
107 Logger.info("Unknown: #{inspect(m)}, #{inspect(state)}")
111 def push_to_socket(topics, topic, item) do
112 Enum.each(topics[topic] || [], fn socket ->
117 Pleroma.Web.MastodonAPI.StatusView.render(
120 for: socket.assigns[:user]
126 send(socket.transport_pid, {:text, json})
130 defp internal_topic("user", socket) do
131 "user:#{socket.assigns[:user].id}"
134 defp internal_topic(topic, _), do: topic