dotfiles/app/lib/prymn_web/live/server_live/show.ex
2023-11-20 18:50:08 +02:00

69 lines
2 KiB
Elixir

defmodule PrymnWeb.ServerLive.Show do
use PrymnWeb, :live_view
require Logger
alias Prymn.{Agents, Servers}
@impl true
def mount(_params, _session, socket) do
{:ok, socket}
end
@impl true
def handle_params(%{"id" => id}, _, socket) do
server = Servers.get_server!(id)
if connected?(socket) and server.status == :registered do
Agents.subscribe_to_health(server.public_ip)
Agents.start_connection(server.public_ip)
end
health = Agents.get_health(server.public_ip)
{:noreply,
socket
|> assign(:page_title, server.name)
|> assign(:health, health || %{message: "Connecting...", tasks: []})
|> assign(:server, server)
|> assign(:dry_run, false)
|> assign(:update_output, [])
# TODO: Do not assign this to the socket - instead generate it in the HTML
|> assign(:registration_command, Servers.create_setup_command(server))}
end
@impl true
def handle_info(%PrymnProto.Prymn.SysUpdateResponse{} = response, socket) do
output = String.split(response.output, "\n")
socket = assign(socket, :update_output, output)
{:noreply, socket}
end
def handle_info(%Agents.Health{} = health, socket) do
{:noreply, assign(socket, :health, health)}
end
@impl true
def handle_event("system_update", _params, socket) do
host_address = get_in(socket.assigns, [:server, Access.key(:public_ip)])
server_name = get_in(socket.assigns, [:server, Access.key(:name)])
socket =
if host_address do
Agents.sys_update(host_address, socket.assigns.dry_run)
put_flash(socket, :info, "Started a system update on server #{server_name}.")
else
put_flash(
socket,
:error,
"Could not perform the update. Your server does not seem to have an address"
)
end
{:noreply, socket}
end
def handle_event("change_dry_run", %{"dry_run" => enabled}, socket) do
enabled = (enabled == "true" && true) || false
{:noreply, assign(socket, :dry_run, enabled)}
end
end