defmodule ChronoscopeWeb.ClientActivator do use GenServer require Logger alias Chronoscope.NTS alias Chronoscope.NTS.Parse alias ChronoscopeWeb.Endpoint @topic Application.compile_env(:chronoscope, :nts_topic) @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) {:ok, %{nts_servers: nts_servers() |> tap(&start_clients/1)}} 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 {:noreply, state} 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 {:noreply, state} end @impl true def handle_info(_, state) do {:noreply, state} 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 defp nts_servers() do File.touch(Application.app_dir(:chronoscope, @nts_file)) Application.app_dir(:chronoscope, @nts_file) |> File.stream!() |> Stream.map(&String.trim/1) |> Stream.filter(&(&1 != "")) |> Stream.map(&Parse.parse_nts_server/1) |> Enum.to_list() end end