1 defmodule Pleroma.Web.Streamer do
4 alias Pleroma.{User, Notification}
8 Process.sleep(1000 * 30) # 30 seconds
9 GenServer.cast(__MODULE__, %{action: :ping})
11 GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
14 def add_socket(topic, socket) do
15 GenServer.cast(__MODULE__, %{action: :add, socket: socket, topic: topic})
18 def remove_socket(topic, socket) do
19 GenServer.cast(__MODULE__, %{action: :remove, socket: socket, topic: topic})
22 def stream(topic, item) do
23 GenServer.cast(__MODULE__, %{action: :stream, topic: topic, item: item})
26 def handle_cast(%{action: :ping}, topics) do
29 |> Enum.each(fn (socket) ->
30 Logger.debug("Sending keepalive ping")
31 send socket.transport_pid, {:text, ""}
34 Process.sleep(1000 * 30) # 30 seconds
35 GenServer.cast(__MODULE__, %{action: :ping})
40 def handle_cast(%{action: :stream, topic: "user", item: %Notification{} = item}, topics) do
41 topic = "user:#{item.user_id}"
42 Enum.each(topics[topic] || [], fn (socket) ->
44 event: "notification",
45 payload: Pleroma.Web.MastodonAPI.MastodonAPIController.render_notification(socket.assigns["user"], item) |> Poison.encode!
48 send socket.transport_pid, {:text, json}
53 def handle_cast(%{action: :stream, topic: "user", item: item}, topics) do
54 Logger.debug("Trying to push to users")
55 recipient_topics = User.get_recipients_from_activity(item)
56 |> Enum.map(fn (%{id: id}) -> "user:#{id}" end)
58 Enum.each(recipient_topics, fn (topic) ->
59 push_to_socket(topics, topic, item)
64 def handle_cast(%{action: :stream, topic: topic, item: item}, topics) do
65 Logger.debug("Trying to push to #{topic}")
66 Logger.debug("Pushing item to #{topic}")
67 push_to_socket(topics, topic, item)
71 def handle_cast(%{action: :add, topic: topic, socket: socket}, sockets) do
72 topic = internal_topic(topic, socket)
73 sockets_for_topic = sockets[topic] || []
74 sockets_for_topic = Enum.uniq([socket | sockets_for_topic])
75 sockets = Map.put(sockets, topic, sockets_for_topic)
76 Logger.debug("Got new conn for #{topic}")
80 def handle_cast(%{action: :remove, topic: topic, socket: socket}, sockets) do
81 topic = internal_topic(topic, socket)
82 sockets_for_topic = sockets[topic] || []
83 sockets_for_topic = List.delete(sockets_for_topic, socket)
84 sockets = Map.put(sockets, topic, sockets_for_topic)
85 Logger.debug("Removed conn for #{topic}")
89 def handle_cast(m, state) do
90 Logger.info("Unknown: #{inspect(m)}, #{inspect(state)}")
94 def push_to_socket(topics, topic, item) do
95 Enum.each(topics[topic] || [], fn (socket) ->
98 payload: Pleroma.Web.MastodonAPI.StatusView.render("status.json", activity: item, for: socket.assigns[:user]) |> Poison.encode!
101 send socket.transport_pid, {:text, json}
105 defp internal_topic("user", socket) do
106 "user:#{socket.assigns[:user].id}"
109 defp internal_topic(topic, _), do: topic