1 defmodule Pleroma.Web.Streamer do
4 alias Pleroma.{User, Notification}
13 Process.sleep(1000 * 30)
14 GenServer.cast(__MODULE__, %{action: :ping})
17 GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
20 def add_socket(topic, socket) do
21 GenServer.cast(__MODULE__, %{action: :add, socket: socket, topic: topic})
24 def remove_socket(topic, socket) do
25 GenServer.cast(__MODULE__, %{action: :remove, socket: socket, topic: topic})
28 def stream(topic, item) do
29 GenServer.cast(__MODULE__, %{action: :stream, topic: topic, item: item})
32 def handle_cast(%{action: :ping}, topics) do
35 |> Enum.each(fn socket ->
36 Logger.debug("Sending keepalive ping")
37 send(socket.transport_pid, {:text, ""})
42 Process.sleep(1000 * 30)
43 GenServer.cast(__MODULE__, %{action: :ping})
49 def handle_cast(%{action: :stream, topic: "user", item: %Notification{} = item}, topics) do
50 topic = "user:#{item.user_id}"
52 Enum.each(topics[topic] || [], fn socket ->
55 event: "notification",
57 Pleroma.Web.MastodonAPI.MastodonAPIController.render_notification(
58 socket.assigns["user"],
65 send(socket.transport_pid, {:text, json})
71 def handle_cast(%{action: :stream, topic: "user", item: item}, topics) do
72 Logger.debug("Trying to push to users")
75 User.get_recipients_from_activity(item)
76 |> Enum.map(fn %{id: id} -> "user:#{id}" end)
78 Enum.each(recipient_topics, fn topic ->
79 push_to_socket(topics, topic, item)
85 def handle_cast(%{action: :stream, topic: topic, item: item}, topics) do
86 Logger.debug("Trying to push to #{topic}")
87 Logger.debug("Pushing item to #{topic}")
88 push_to_socket(topics, topic, item)
92 def handle_cast(%{action: :add, topic: topic, socket: socket}, sockets) do
93 topic = internal_topic(topic, socket)
94 sockets_for_topic = sockets[topic] || []
95 sockets_for_topic = Enum.uniq([socket | sockets_for_topic])
96 sockets = Map.put(sockets, topic, sockets_for_topic)
97 Logger.debug("Got new conn for #{topic}")
101 def handle_cast(%{action: :remove, topic: topic, socket: socket}, sockets) do
102 topic = internal_topic(topic, socket)
103 sockets_for_topic = sockets[topic] || []
104 sockets_for_topic = List.delete(sockets_for_topic, socket)
105 sockets = Map.put(sockets, topic, sockets_for_topic)
106 Logger.debug("Removed conn for #{topic}")
110 def handle_cast(m, state) do
111 Logger.info("Unknown: #{inspect(m)}, #{inspect(state)}")
115 def push_to_socket(topics, topic, item) do
116 Enum.each(topics[topic] || [], fn socket ->
117 # Get the current user so we have up-to-date blocks etc.
118 user = User.get_cached_by_ap_id(socket.assigns[:user].ap_id)
119 blocks = user.info["blocks"] || []
121 unless item.actor in blocks do
126 Pleroma.Web.MastodonAPI.StatusView.render(
135 send(socket.transport_pid, {:text, json})
140 defp internal_topic("user", socket) do
141 "user:#{socket.assigns[:user].id}"
144 defp internal_topic(topic, _), do: topic