chronoscope/lib/chronoscope_web/client_activator.ex

68 lines
1.5 KiB
Elixir
Raw Normal View History

2024-06-05 14:21:26 -04:00
defmodule ChronoscopeWeb.ClientActivator do
2024-06-04 20:03:02 -04:00
use GenServer
require Logger
alias Chronoscope.NTS
alias Chronoscope.NTS.Parse
alias ChronoscopeWeb.Endpoint
2024-06-04 20:03:02 -04:00
@topic Application.compile_env(:chronoscope, :nts_topic)
2024-06-04 20:03:02 -04:00
@nts_file Application.compile_env(:chronoscope, :nts_file)
def start_link(_) do
GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
end
@impl true
def init(_) do
Endpoint.subscribe(@topic)
2024-06-05 17:01:57 -04:00
{:ok, %{nts_servers: nts_servers() |> tap(&start_clients/1)}}
2024-06-05 17:01:57 -04:00
end
@impl true
def handle_info(%{topic: @topic, event: "initializing", payload: server}, state) do
if server in state.nts_servers do
Logger.info("activating #{inspect(server)}")
NTS.auto_refresh(server)
end
2024-06-05 17:01:57 -04:00
{:noreply, state}
2024-06-04 20:03:02 -04:00
end
@impl true
def handle_info(%{topic: @topic, event: "cancel-auto-refresh", payload: server}, state) do
if server in state.nts_servers do
Logger.info("#{inspect(server)} was deactivated")
end
2024-06-05 17:01:57 -04:00
{:noreply, state}
end
@impl true
def handle_info(_, state) do
{:noreply, state}
2024-06-04 20:03:02 -04:00
end
@impl true
def handle_call(:get_nts_servers, _from, state) do
{:reply, state.nts_servers, state}
end
defp start_clients(servers) do
Enum.each(servers, &NTS.start_client/1)
end
2024-06-05 17:01:57 -04:00
defp nts_servers() do
File.touch(Application.app_dir(:chronoscope, @nts_file))
2024-06-05 14:21:26 -04:00
Application.app_dir(:chronoscope, @nts_file)
2024-06-04 20:03:02 -04:00
|> File.stream!()
|> Stream.map(&String.trim/1)
|> Stream.filter(&(&1 != ""))
2024-06-04 20:03:02 -04:00
|> Stream.map(&Parse.parse_nts_server/1)
|> Enum.to_list()
end
end