1 defmodule Pleroma.Web.Streamer do
5 alias Pleroma.{User, Notification}
9 Process.sleep(1000 * 30) # 30 seconds
10 GenServer.cast(__MODULE__, %{action: :ping})
12 GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
15 def add_socket(topic, socket) do
16 GenServer.cast(__MODULE__, %{action: :add, socket: socket, topic: topic})
19 def remove_socket(topic, socket) do
20 GenServer.cast(__MODULE__, %{action: :remove, socket: socket, topic: topic})
23 def stream(topic, item) do
24 GenServer.cast(__MODULE__, %{action: :stream, topic: topic, item: item})
27 def handle_cast(%{action: :ping}, topics) do
30 |> Enum.each(fn (socket) ->
31 Logger.debug("Sending keepalive ping")
32 send socket.transport_pid, {:text, ""}
35 Process.sleep(1000 * 30) # 30 seconds
36 GenServer.cast(__MODULE__, %{action: :ping})
41 def push_to_socket(topics, topic, item) do
42 Enum.each(topics[topic] || [], fn (socket) ->
45 payload: Pleroma.Web.MastodonAPI.StatusView.render("status.json", activity: item, for: socket.assigns[:user]) |> Poison.encode!
48 send socket.transport_pid, {:text, json}
52 def handle_cast(%{action: :stream, topic: "user", item: %Notification{} = item}, topics) do
53 topic = "user:#{item.user_id}"
54 Enum.each(topics[topic] || [], fn (socket) ->
56 event: "notification",
57 payload: Pleroma.Web.MastodonAPI.MastodonAPIController.render_notification(socket.assigns["user"], item) |> Poison.encode!
60 send socket.transport_pid, {:text, json}
65 def handle_cast(%{action: :stream, topic: "user", item: item}, topics) do
66 Logger.debug("Trying to push to users")
67 recipient_topics = User.get_recipients_from_activity(item)
68 |> Enum.map(fn (%{id: id}) -> "user:#{id}" end)
70 Enum.each(recipient_topics, fn (topic) ->
71 push_to_socket(topics, topic, item)
76 def handle_cast(%{action: :stream, topic: topic, item: item}, topics) do
77 Logger.debug("Trying to push to #{topic}")
78 Logger.debug("Pushing item to #{topic}")
79 push_to_socket(topics, topic, item)
83 defp internal_topic("user", socket) do
84 "user:#{socket.assigns[:user].id}"
86 defp internal_topic(topic, socket), do: topic
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}")
98 def handle_cast(%{action: :remove, topic: topic, socket: socket}, sockets) do
99 topic = internal_topic(topic, socket)
100 sockets_for_topic = sockets[topic] || []
101 sockets_for_topic = List.delete(sockets_for_topic, socket)
102 sockets = Map.put(sockets, topic, sockets_for_topic)
103 Logger.debug("Removed conn for #{topic}")
108 def handle_cast(m, state) do
109 IO.inspect("Unknown: #{inspect(m)}, #{inspect(state)}")