MastodonAPI: Stream fixes.
[akkoma] / lib / pleroma / web / streamer.ex
1 defmodule Pleroma.Web.Streamer do
2 use GenServer
3 require Logger
4 import Plug.Conn
5
6 def start_link do
7 spawn(fn ->
8 Process.sleep(1000 * 30) # 30 seconds
9 GenServer.cast(__MODULE__, %{action: :ping})
10 end)
11 GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
12 end
13
14 def add_socket(topic, socket) do
15 GenServer.cast(__MODULE__, %{action: :add, socket: socket, topic: topic})
16 end
17
18 def remove_socket(topic, socket) do
19 GenServer.cast(__MODULE__, %{action: :remove, socket: socket, topic: topic})
20 end
21
22 def stream(topic, item) do
23 GenServer.cast(__MODULE__, %{action: :stream, topic: topic, item: item})
24 end
25
26 def handle_cast(%{action: :ping}, topics) do
27 Map.values(topics)
28 |> List.flatten
29 |> Enum.each(fn (socket) ->
30 Logger.debug("Sending keepalive ping")
31 send socket.transport_pid, {:text, ""}
32 end)
33 spawn(fn ->
34 Process.sleep(1000 * 30) # 30 seconds
35 GenServer.cast(__MODULE__, %{action: :ping})
36 end)
37 {:noreply, topics}
38 end
39
40 def handle_cast(%{action: :stream, topic: topic, item: item}, topics) do
41 Logger.debug("Trying to push to #{topic}")
42 Logger.debug("Pushing item to #{topic}")
43 Enum.each(topics[topic] || [], fn (socket) ->
44 json = %{
45 event: "update",
46 payload: Pleroma.Web.MastodonAPI.StatusView.render("status.json", activity: item, for: socket.assigns[:user]) |> Poison.encode!
47 } |> Poison.encode!
48
49 send socket.transport_pid, {:text, json}
50 end)
51 {:noreply, topics}
52 end
53
54 def handle_cast(%{action: :add, topic: topic, socket: socket}, sockets) do
55 sockets_for_topic = sockets[topic] || []
56 sockets_for_topic = Enum.uniq([socket | sockets_for_topic])
57 sockets = Map.put(sockets, topic, sockets_for_topic)
58 Logger.debug("Got new conn for #{topic}")
59 IO.inspect(sockets)
60 {:noreply, sockets}
61 end
62
63 def handle_cast(%{action: :remove, topic: topic, socket: socket}, sockets) do
64 sockets_for_topic = sockets[topic] || []
65 sockets_for_topic = List.delete(sockets_for_topic, socket)
66 sockets = Map.put(sockets, topic, sockets_for_topic)
67 Logger.debug("Removed conn for #{topic}")
68 IO.inspect(sockets)
69 {:noreply, sockets}
70 end
71
72 def handle_cast(m, state) do
73 IO.inspect("Unknown: #{inspect(m)}, #{inspect(state)}")
74 {:noreply, state}
75 end
76 end