diff options
author | href <href@random.sh> | 2018-02-02 21:35:46 +0100 |
---|---|---|
committer | href <href@random.sh> | 2018-02-02 21:35:46 +0100 |
commit | c98ddad3263f6859af3c5c76fa197876743d5ded (patch) | |
tree | 9e20617da1089e918e0445162dc9bd8eb54f3459 /lib/lsg_web/controllers | |
parent | import (diff) |
sse / embedded player
Diffstat (limited to 'lib/lsg_web/controllers')
-rw-r--r-- | lib/lsg_web/controllers/icecast_see_controller.ex | 41 |
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 |