summaryrefslogtreecommitdiff
path: root/lib/lsg_web/controllers
diff options
context:
space:
mode:
authorhref <href@random.sh>2018-02-02 21:35:46 +0100
committerhref <href@random.sh>2018-02-02 21:35:46 +0100
commitc98ddad3263f6859af3c5c76fa197876743d5ded (patch)
tree9e20617da1089e918e0445162dc9bd8eb54f3459 /lib/lsg_web/controllers
parentimport (diff)
sse / embedded player
Diffstat (limited to 'lib/lsg_web/controllers')
-rw-r--r--lib/lsg_web/controllers/icecast_see_controller.ex41
1 files changed, 41 insertions, 0 deletions
diff --git a/lib/lsg_web/controllers/icecast_see_controller.ex b/lib/lsg_web/controllers/icecast_see_controller.ex
new file mode 100644
index 0000000..1eecca1
--- /dev/null
+++ b/lib/lsg_web/controllers/icecast_see_controller.ex
@@ -0,0 +1,41 @@
+defmodule LSGWeb.IcecastSseController do
+ use LSGWeb, :controller
+ require Logger
+
+ @ping_interval 20_000
+
+ def sse(conn, _params) do
+ conn
+ |> put_resp_header("X-Accel-Buffering", "no")
+ |> put_resp_header("content-type", "text/event-stream")
+ |> send_chunked(200)
+ |> subscribe
+ |> send_sse_message("ping", "ping")
+ |> send_sse_message("icecast", LSG.IcecastAgent.get)
+ |> sse_loop
+ end
+
+ def subscribe(conn) do
+ :timer.send_interval(@ping_interval, {:event, :ping})
+ {:ok, _} = Registry.register(LSG.BroadcastRegistry, "icecast", [])
+ conn
+ end
+
+ def sse_loop(conn) do
+ {type, event} = receive do
+ {:event, :ping} -> {"ping", "ping"}
+ {:icecast, stats} -> {"icecast", stats}
+ end
+
+ conn
+ |> send_sse_message(type, event)
+ |> sse_loop()
+ end
+
+ defp send_sse_message(conn, type, data) do
+ json = Jason.encode!(%{type => data})
+ {:ok, conn} = chunk(conn, "event: #{type}\ndata: #{json}\n\n")
+ conn
+ end
+
+end