Registration

This commit is contained in:
Andrei Smaliak 2026-04-29 16:14:40 +04:00
parent b88b8e12a9
commit 5fda088dd4
4 changed files with 412 additions and 49 deletions

View File

@ -39,7 +39,7 @@ APP_DIR = "/opt/iomatex-console"
PUBLIC_DIR = os.path.join(APP_DIR, "public")
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
CONFIG_PATH = "/etc/iomatex/console.json"
UI_VERSION = "V 2.2.17"
UI_VERSION = "V 2.2.25"
DEFAULT_CONFIG = {
"bind": "0.0.0.0",
@ -69,6 +69,7 @@ AP_PASSWORD_RE = re.compile(r"^[a-z0-9]{8,}$")
ITSCREEN_SERVICE_UNIT = "itscreen-x11.service"
ITSCREEN_CONFIG_PATH = "/var/lib/itscreen/config/it-screen/it-screen.conf"
ITSCREEN_LOG_PATH = "/var/lib/itscreen/logs/itscreen.log"
ITSCREEN_AUDIO_CONFIG_PATH = "/var/lib/itscreen/.asoundrc"
ITSCREEN_CONFIG_CACHE_TTL_SEC = 3.0
ITSCREEN_LOG_DEFAULT_LINES = 100
ITSCREEN_LOG_MAX_LINES = 100
@ -437,7 +438,6 @@ AUDIO_TARGETS = {
},
}
def resolve_audio_target_config(target, cards=None):
template = AUDIO_TARGETS.get(target)
if not template:
@ -489,11 +489,110 @@ def resolve_audio_target_config(target, cards=None):
}
def render_itscreen_audio_config(target):
config = resolve_audio_target_config(target)
if not config:
raise ValueError("Unknown audio target")
return (
"pcm.!default {\n"
" type hw\n"
f" card {config['card_index']}\n"
f" device {config['pcm_index']}\n"
"}\n"
"\n"
"ctl.!default {\n"
" type hw\n"
f" card {config['card_index']}\n"
"}\n"
)
def parse_itscreen_audio_config(path=ITSCREEN_AUDIO_CONFIG_PATH):
if not os.path.exists(path):
return {"status": "not_configured", "path": path}
raw = read_text(path)
card_match = re.search(r"pcm\.\!default\s*\{[^}]*\bcard\s+(\d+)\b", raw, flags=re.IGNORECASE | re.DOTALL)
device_match = re.search(r"pcm\.\!default\s*\{[^}]*\bdevice\s+(\d+)\b", raw, flags=re.IGNORECASE | re.DOTALL)
card_index = int(card_match.group(1)) if card_match else None
pcm_index = int(device_match.group(1)) if device_match else 0
configured_device = f"hw:{card_index},{pcm_index}" if card_index is not None else ""
matched_target = ""
config_by_target = {}
for target in AUDIO_TARGETS:
config = resolve_audio_target_config(target)
config_by_target[target] = config
if configured_device and configured_device == config.get("device"):
matched_target = target
return {
"status": "configured",
"path": path,
"card_index": card_index,
"pcm_index": pcm_index,
"device": configured_device,
"target": matched_target,
"label": config_by_target.get(matched_target, {}).get("label", ""),
"details": trim_output_lines(raw, limit=12),
}
def write_itscreen_audio_config(target):
config = resolve_audio_target_config(target)
if not config:
raise ValueError("Unknown audio target")
if not config.get("present"):
raise RuntimeError(f"{config['label']} device is not detected")
content = render_itscreen_audio_config(target)
directory = os.path.dirname(ITSCREEN_AUDIO_CONFIG_PATH) or "."
os.makedirs(directory, exist_ok=True)
fd, tmp_path = tempfile.mkstemp(prefix=".tmp-audio-", dir=directory, text=True)
try:
with os.fdopen(fd, "w", encoding="utf-8") as fh:
fh.write(content)
os.chmod(tmp_path, 0o644)
try:
shutil.chown(tmp_path, user="itscreen", group="itscreen")
except Exception:
pass
os.replace(tmp_path, ITSCREEN_AUDIO_CONFIG_PATH)
finally:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
try:
shutil.chown(ITSCREEN_AUDIO_CONFIG_PATH, user="itscreen", group="itscreen")
except Exception:
pass
service = get_itscreen_service_status()
restarted = False
if service.get("installed") and service.get("active"):
rc, _, stderr = run(["systemctl", "restart", ITSCREEN_SERVICE_UNIT], timeout=20)
if rc != 0:
raise RuntimeError(stderr or "Audio route was written but failed to restart IT-Screen")
restarted = True
invalidate_cache()
return {
"ok": True,
"target": target,
"label": config["label"],
"device": config["device"],
"path": ITSCREEN_AUDIO_CONFIG_PATH,
"message": f"IT-Screen audio route set to {config['label']}",
"applied_at": utc_now_iso(),
"service_restarted": restarted,
"route": parse_itscreen_audio_config(),
}
def get_audio_diagnostics():
cards = parse_alsa_cards()
aplay_l_rc, aplay_l_out, aplay_l_err = run(["aplay", "-l"], timeout=4)
aplay_L_rc, aplay_L_out, aplay_L_err = run(["aplay", "-L"], timeout=4)
route = audio_route_info()
itscreen_route = parse_itscreen_audio_config()
devices = {}
for target in AUDIO_TARGETS:
@ -520,6 +619,7 @@ def get_audio_diagnostics():
"aplay_hardware": trim_output_lines(aplay_l_out if aplay_l_rc == 0 else (aplay_l_err or aplay_l_out), limit=12),
"aplay_logical": trim_output_lines(aplay_L_out if aplay_L_rc == 0 else (aplay_L_err or aplay_L_out), limit=12),
"default_route": route,
"itscreen_route": itscreen_route,
"alsa_cards": cards,
},
"generated_at": utc_now_iso(),
@ -1791,6 +1891,7 @@ def get_itscreen_service_status():
status, status_label = normalize_service_status(unit)
configured = bool(unit.get("installed"))
active = bool(unit.get("active", False))
version = get_itscreen_app_version()
errors = []
if unit.get("active_state") == "failed":
errors.append("Service failed")
@ -1807,6 +1908,7 @@ def get_itscreen_service_status():
"name": "itscreen",
"title": "IT-Screen App",
"unit": ITSCREEN_SERVICE_UNIT,
"version": version,
"installed": bool(unit.get("installed", False)),
"configured": configured,
"active": active,
@ -1830,6 +1932,7 @@ def get_itscreen_service_status():
"name": "itscreen",
"title": "IT-Screen App",
"unit": ITSCREEN_SERVICE_UNIT,
"version": "",
"installed": False,
"configured": False,
"active": False,
@ -1877,6 +1980,62 @@ def systemctl_show_property(unit_name, property_name, timeout=5):
return value.strip()
def parse_systemd_execstart_path(raw_value):
text = str(raw_value or "").strip()
if not text:
return ""
match = re.search(r"path=([^ ;]+)", text)
if match:
return match.group(1).strip()
match = re.search(r"(/[^ ;]+)", text)
return match.group(1).strip() if match else ""
def get_itscreen_binary_candidates():
candidates = []
seen = set()
def add(path):
value = str(path or "").strip()
if not value or value in seen:
return
seen.add(value)
candidates.append(value)
try:
main_pid = parse_int_value(systemctl_show_property(ITSCREEN_SERVICE_UNIT, "MainPID"))
if main_pid and main_pid > 0:
add(os.path.realpath(f"/proc/{main_pid}/exe"))
except Exception:
pass
try:
add(parse_systemd_execstart_path(systemctl_show_property(ITSCREEN_SERVICE_UNIT, "ExecStart")))
except Exception:
pass
add("/home/iomatex/It-screenClient/itscreen")
add("/usr/local/bin/itscreen")
add("/usr/bin/itscreen")
return [path for path in candidates if os.path.exists(path)]
def get_itscreen_app_version():
version_re = re.compile(r"\b(\d+\.\d+\.\d+(?:\.\d+)?)\b")
for binary_path in get_itscreen_binary_candidates():
try:
rc, stdout, stderr = run([binary_path, "--version"], timeout=4)
except Exception:
continue
output = "\n".join(part for part in ((stdout or "").strip(), (stderr or "").strip()) if part).strip()
if rc != 0 and not output:
continue
match = version_re.search(output)
if match:
return match.group(1)
return ""
def parse_systemctl_timestamp(raw_value):
text = str(raw_value or "").strip()
if not text or text.lower() in ("n/a", "0"):
@ -2880,6 +3039,24 @@ class Handler(BaseHTTPRequestHandler):
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
if parsed.path == "/api/actions/audio-route":
payload = self.read_json_body()
if payload is None:
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return
target = str(payload.get("target", "")).strip().lower()
if target not in AUDIO_TARGETS:
self.send_json({"ok": False, "error": "target must be hdmi or analog"}, code=400)
return
try:
self.send_json(write_itscreen_audio_config(target))
except ValueError as exc:
self.send_json({"ok": False, "error": str(exc)}, code=400)
except RuntimeError as exc:
self.send_json({"ok": False, "error": str(exc)}, code=409)
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
if parsed.path == "/api/actions/reboot":
try:
self.send_json(request_reboot())
@ -2894,7 +3071,7 @@ class Handler(BaseHTTPRequestHandler):
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return
try:
response = register_device(str(payload.get("host", "")))
response = register_device(str(payload.get("host", "")), str(payload.get("token", "")))
invalidate_cache()
self.send_json(response)
except ValueError as exc:
@ -2910,7 +3087,7 @@ class Handler(BaseHTTPRequestHandler):
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return
try:
response = register_device(str(payload.get("host", "")))
response = register_device(str(payload.get("host", "")), str(payload.get("token", "")))
invalidate_cache()
self.send_json(response)
except ValueError as exc:

View File

@ -4,6 +4,7 @@ import os
import queue
import re
import sys
import tempfile
import threading
import time
from urllib.parse import urlparse
@ -223,7 +224,8 @@ def load_state():
def save_state(state):
os.makedirs(os.path.dirname(STATE_PATH), exist_ok=True)
directory = os.path.dirname(STATE_PATH)
os.makedirs(directory, exist_ok=True)
safe = _default_state()
safe.update({
"host": str(state.get("host", "") or ""),
@ -248,11 +250,15 @@ def save_state(state):
"status": str(last_event.get("status", "") or ""),
"timestamp": str(last_event.get("timestamp", "") or ""),
})
tmp_path = f"{STATE_PATH}.tmp"
with open(tmp_path, "w", encoding="utf-8") as fh:
json.dump(safe, fh, indent=2)
fh.write("\n")
os.replace(tmp_path, STATE_PATH)
fd, tmp_path = tempfile.mkstemp(prefix="itscreen_registration.", suffix=".tmp", dir=directory, text=True)
try:
with os.fdopen(fd, "w", encoding="utf-8") as fh:
json.dump(safe, fh, indent=2)
fh.write("\n")
os.replace(tmp_path, STATE_PATH)
finally:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
def _parse_mqtt_url(raw_url):
@ -269,6 +275,15 @@ def _truncate_empty(value):
return text
def _normalize_registration_token(value):
text = _truncate_empty(value)
if not text:
return ""
if text == NOT_SPECIFIED:
return ""
return text
def _text_or_default(value, default=NOT_SPECIFIED):
text = _truncate_empty(value)
return text or default
@ -342,6 +357,13 @@ def _extract_response_payload(response_text):
raise RuntimeError(f"Could not parse backend response: {exc}") from exc
def _extract_response_payload_safe(response_text):
try:
return _extract_response_payload(response_text)
except Exception:
return {}
def _event_timestamp():
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
@ -365,7 +387,7 @@ def _extract_registration_fields(server_state, event_payload, persisted):
merged["device_id"] = str(source.get("deviceId"))
merged["device_name"] = merged.get("device_name") or _device_identity()["device_name"]
merged["device_id"] = _device_identity()["device_id"]
merged["registered"] = bool((server_state or {}).get("registered") or merged.get("token"))
merged["registered"] = _bool_value((server_state or {}).get("registered"), default=False)
merged["logged"] = bool((server_state or {}).get("logged"))
return merged
@ -664,6 +686,13 @@ class MqttSettingsSession:
timeout=REPLY_TIMEOUT_SEC,
)
def clear_server_registration(self):
return self.publish_and_wait(
{"action": "clear", "category": SETTINGS_CATEGORY},
lambda item: isinstance(item, dict) and item.get("action") == "clear" and item.get("category") == SETTINGS_CATEGORY,
timeout=REPLY_TIMEOUT_SEC,
)
def read_retained_topic_payload(self, topic, timeout=1.5):
self._drain()
result, mid = self.client.subscribe(topic, qos=0)
@ -695,6 +724,13 @@ class MqttSettingsSession:
def set_server(self, host):
self.publish({"action": "set", "category": SETTINGS_CATEGORY, "host": host})
def register_device(self, host, token=""):
payload = {"action": "register", "host": host}
token_value = _truncate_empty(token)
if token_value:
payload["token"] = token_value
self.publish(payload)
def wait_registered_event(self, timeout=REGISTER_TIMEOUT_SEC):
deadline = time.time() + timeout
seen = set()
@ -707,7 +743,7 @@ class MqttSettingsSession:
continue
if not isinstance(candidate, dict):
continue
if candidate.get("action") != "registered" or candidate.get("operation") != "register":
if candidate.get("action") != "registered":
continue
fingerprint = (
candidate.get("action"),
@ -718,10 +754,43 @@ class MqttSettingsSession:
if fingerprint in seen:
continue
seen.add(fingerprint)
operation = str(candidate.get("operation", "") or "")
status_code = _event_status_code(candidate)
payload = _extract_response_payload_safe(candidate.get("responseText"))
if operation == "register" and status_code is not None and status_code < 300 and payload.get("password"):
continue
return candidate
raise TimeoutError("Registration timeout")
def _event_status_code(event):
raw = (event or {}).get("status")
try:
return int(raw)
except Exception:
return None
def _registration_error_message(event):
payload = _extract_response_payload_safe((event or {}).get("responseText"))
error_text = _truncate_empty(payload.get("error"))
if error_text:
return error_text
response_text = _truncate_empty((event or {}).get("responseText"))
if response_text == "ERR_CONNECTION_TIMED_OUT":
return "Connection timed out while contacting registration server"
status_code = _event_status_code(event)
if status_code == 422:
return "Device with current ID is already registered"
if status_code is not None and status_code >= 300:
return f"Registration failed ({status_code})"
if _truncate_empty((event or {}).get("operation")) == "confirm":
return "Registration confirmation failed"
if response_text:
return response_text
return "Cloud registration failed"
def _build_public_status(state, error_text=""):
normalized = _normalize_registration_payload(state, persisted=state)
normalized["status"] = _truncate_empty(state.get("status")) or normalized.get("status") or "idle"
@ -859,11 +928,13 @@ def get_registration_status():
}
def register_device(host):
def register_device(host, token=""):
validated_host = validate_host(host)
validated_token = _normalize_registration_token(token)
persisted = load_state()
working = dict(persisted)
working["host"] = validated_host
working["token"] = validated_token
working["status"] = "registering"
save_state(working)
@ -873,9 +944,15 @@ def register_device(host):
current_server_state = session.get_server_state()
if _bool_value((current_server_state or {}).get("registered"), default=False):
raise RuntimeError("Device is already registered")
session.set_server(validated_host)
session.register_device(validated_host, validated_token)
event = session.wait_registered_event()
event_payload = _extract_response_payload(event.get("responseText"))
event_payload = _extract_response_payload_safe(event.get("responseText"))
status_code = _event_status_code(event)
operation = _truncate_empty(event.get("operation"))
confirm_ok = operation == "confirm" and status_code is not None and status_code < 300 and bool(event_payload.get("result"))
register_ok = operation == "register" and status_code is not None and status_code < 300 and bool(event_payload.get("password"))
if not confirm_ok and not register_ok:
raise RuntimeError(_registration_error_message(event))
server_state = session.get_server_state()
return {
"event": event,
@ -896,6 +973,7 @@ def register_device(host):
server_state = flow["server_state"]
merged = _extract_registration_fields(server_state, event_payload, working)
merged["host"] = validated_host
merged["token"] = validated_token or _truncate_empty(merged.get("token"))
merged["contract_prefix"] = _truncate_empty(contract_meta.get("contract_prefix"))
merged["request_topic"] = _truncate_empty(contract_meta.get("request_topic"))
merged["response_topic"] = _truncate_empty(contract_meta.get("response_topic"))
@ -924,26 +1002,55 @@ def register_device(host):
def reset_registration():
state = load_state()
state.update({
"username": "",
"password": "",
"token": "",
"organization": "",
"registered": False,
"logged": False,
"status": "idle",
"last_event": {
"action": "reset",
"operation": "local",
"status": "warning",
"timestamp": _event_timestamp(),
},
})
save_state(state)
return {
"ok": True,
"message": "Cloud registration has been reset.",
"warning": "Local registration cache was cleared. Device-side unbind is not implemented in this runtime.",
"data": _build_public_status(state),
}
persisted = load_state()
working = dict(persisted)
working["status"] = "resetting"
save_state(working)
try:
def _reset_flow(session, _contract_meta):
session.login(_candidate_login_passwords(working["device_id"], persisted))
cleared = session.clear_server_registration()
if not _bool_value((cleared or {}).get("result"), default=False):
raise RuntimeError(_truncate_empty((cleared or {}).get("error")) or "Device reset rejected")
return session.get_server_state()
contract_meta, server_state = _with_settings_contract(
working["device_id"],
persisted,
"reset",
_reset_flow,
server_host_hint=working.get("host", ""),
)
merged = _default_state()
merged.update({
"host": _truncate_empty((server_state or {}).get("host")) or _truncate_empty((server_state or {}).get("server")),
"username": _truncate_empty((server_state or {}).get("username")),
"password": _truncate_empty((server_state or {}).get("password")),
"token": _truncate_empty((server_state or {}).get("token")),
"organization": _truncate_empty((server_state or {}).get("organization")),
"device_name": _device_name_from_payload(server_state),
"device_id": _device_identity()["device_id"],
"contract_prefix": _truncate_empty(contract_meta.get("contract_prefix")),
"request_topic": _truncate_empty(contract_meta.get("request_topic")),
"response_topic": _truncate_empty(contract_meta.get("response_topic")),
"registered": _bool_value((server_state or {}).get("registered"), default=False),
"logged": _bool_value((server_state or {}).get("logged"), default=False),
"status": "idle",
"last_event": {
"action": "clear",
"operation": "device",
"status": "success",
"timestamp": _event_timestamp(),
},
})
save_state(merged)
return {
"ok": True,
"message": "Cloud registration has been reset on device.",
"data": _build_public_status(merged),
}
except Exception:
working["status"] = "error"
save_state(working)
raise

View File

@ -369,6 +369,10 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
}
.splitMeta section{min-width:0}
.meta .key{color:var(--muted)}
.meta .key.registrationWarn{color:var(--warn);font-weight:700}
.registrationWarn{color:var(--warn);font-weight:700}
.meta.registrationWarnGrid .key{color:var(--warn);font-weight:700}
.meta.registrationWarnGrid > div:not(.key){color:var(--warn);font-weight:700}
.metricValueStack{display:grid;gap:4px}
.metricHeadline{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.metricState{
@ -957,6 +961,7 @@ html[dir="rtl"] .itscreenLogsActions{
margin-top:14px;padding:12px 14px;border-radius:14px;font-size:13px;font-weight:600;
}
.banner.success{background:rgba(14,122,83,.10);color:var(--accent)}
.banner.warn{background:rgba(154,106,0,.10);color:var(--warn)}
.banner.error{background:rgba(185,52,52,.10);color:var(--error)}
.scanList{display:grid;gap:10px}
.scanCollapsedHint{

View File

@ -44,7 +44,7 @@
{ mode: "test_by", label: "TEST BY", host: "rest.test.it-screen.by" },
{ mode: "custom", label: "Custom", host: "" }
];
const UI_VERSION = "V 2.2.17";
const UI_VERSION = "V 2.2.25";
const ITSCREEN_LOG_INITIAL_LINES = 50;
const ITSCREEN_LOG_BUFFER_LIMIT = 300;
const ITSCREEN_LOG_BATCH_MS = 250;
@ -166,6 +166,7 @@
registrationLoadedAt: 0,
serverMode: "uae",
customHost: "",
customToken: "",
focused: false,
loadedAt: 0,
request: null,
@ -268,6 +269,7 @@
language: "en",
audioActions: {
busyTarget: "",
busyRouteTarget: "",
results: {}
},
auth: {
@ -685,6 +687,19 @@
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
}
function formatMinuteTimestamp(value) {
const text = (value ?? "").toString().trim();
if (!text) return "—";
const date = new Date(text);
if (Number.isNaN(date.getTime())) {
const normalized = text.replace("T", " ").replace(/\.\d+Z?$/, "").replace(/Z$/, "");
const match = normalized.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2})/);
return match ? match[1] : normalized;
}
const pad = (number) => String(number).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
function showToast(kind, message) {
if (!nodes.toastStack || !message) return;
const toast = document.createElement("div");
@ -1066,6 +1081,11 @@
return notSpecified(payload && (payload.server || payload.host));
}
function itscreenTokenInputValue(value) {
const text = textValue(value, "");
return text === t("Not specified") ? "" : text;
}
function itscreenContractLabel(payload) {
const contract = textValue(payload && payload.contract_prefix, "");
if (contract === "it-screen") return "it-screen/$devices/settings";
@ -1142,8 +1162,15 @@
return !itscreenHostValidationError();
}
function renderItscreenInfoRows(payload) {
function formatItscreenAppVersion(value) {
const text = textValue(value, "");
if (!text) return t("Not specified");
return text.startsWith("v.") || text.startsWith("v ") ? text : `v. ${text}`;
}
function renderItscreenInfoRows(payload, appVersion) {
return renderKeyValueRows([
{ label: t("App version"), value: formatItscreenAppVersion(appVersion) },
{ label: t("Server"), value: itscreenServerValue(payload) },
{ label: t("Device ID"), value: notSpecified(payload && payload.device_id) },
{ label: t("Device name"), value: notSpecified(payload && payload.device_name) },
@ -1165,6 +1192,7 @@
const tone = statusTone(card);
const warnings = Array.isArray(card.warnings) ? card.warnings : [];
const errors = Array.isArray(card.errors) ? card.errors : [];
const registrationRequired = !!(payload && !payload.registered && !state.itscreen.error);
return `
<article class="panel card serviceCard">
@ -1184,7 +1212,8 @@
${state.itscreen.loading && !payload ? `<div class="emptyInline">${esc(t("Loading It-screen status..."))}</div>` : `
<div class="list">
<div class="listTitle">${esc(t("Registration"))}</div>
<div class="meta compactMeta">${renderItscreenInfoRows(payload || {})}</div>
${registrationRequired ? `<div class="banner warn">${esc(t("Registration required. Device is not bound to cloud."))}</div>` : ""}
<div class="meta compactMeta ${registrationRequired ? "registrationWarnGrid" : ""}">${renderItscreenInfoRows(payload || {}, card && card.version)}</div>
</div>
`}
<div class="list">
@ -1249,8 +1278,11 @@
const status = card.display_status || {};
const audio = card.audio_diagnostics || {};
const audioDevices = audio.devices || {};
const audioParams = audio.parameters || {};
const itscreenRoute = audioParams.itscreen_route || {};
const connectorsOpen = !!state.displayUi.connectorsOpen;
const audioBusyTarget = state.audioActions.busyTarget;
const audioBusyRouteTarget = state.audioActions.busyRouteTarget;
function audioStatusMeta(value) {
const key = textValue(value, "error").toLowerCase();
@ -1274,8 +1306,10 @@
function renderAudioDevice(device, buttonLabel) {
const testMeta = audioTestMeta(device && device.target);
const busy = audioBusyTarget === device.target;
const busyRoute = audioBusyRouteTarget === device.target;
const deviceStatusMeta = audioStatusMeta(device && device.status);
const unavailable = textValue(device && device.status, "error").toLowerCase() === "error";
const routeActive = textValue(itscreenRoute.target, "") === textValue(device && device.target, "");
return `
<article class="audioDeviceCard">
<div class="audioDeviceHead">
@ -1283,12 +1317,14 @@
<strong>${esc(displayValue(device.label, t("Audio device")))}</strong>
<div class="audioDeviceSubhead">${esc(textValue(device.description, t("Not available")))}</div>
<div class="audioDeviceMeta">${esc(t("ALSA device: {device}", { device: textValue(device.device, t("Not available")) }))}</div>
<div class="audioDeviceMeta">${esc(routeActive ? t("IT-Screen route: active") : t("IT-Screen route: inactive"))}</div>
</div>
<span class="actionBadge actionBadge-${deviceStatusMeta.tone}">${esc(unavailable ? t("Unavailable") : deviceStatusMeta.label)}</span>
</div>
${device && device.summary ? `<div class="audioDeviceMeta">${esc(device.summary)}</div>` : ""}
<div class="audioActionRow">
<button class="actionBtn" type="button" ${(busy || unavailable) ? "disabled" : ""} onclick="window.__runAudioTest('${esc(device.target)}')">${esc(busy ? t("Testing...") : t(buttonLabel))}</button>
<button class="actionBtn" type="button" ${(busyRoute || unavailable || routeActive) ? "disabled" : ""} onclick="window.__setAudioRoute('${esc(device.target)}')">${esc(routeActive ? t("Route active") : (busyRoute ? t("Applying...") : t("Use For IT-Screen")))}</button>
</div>
${testMeta.hasResult ? `<div class="audioTestSummary"><span class="actionBadge actionBadge-${testMeta.tone}">${esc(testMeta.label)}</span><span class="audioTestTime">${esc(testMeta.testedAt)}</span></div>` : ""}
${testMeta.output.length ? `<pre class="diagBlock testOutput">${esc(testMeta.output.join("\n"))}</pre>` : ""}
@ -1339,6 +1375,7 @@
<div class="meta">${renderKeyValueRows(details)}</div>
<div class="list">
<div class="listTitle">${esc(t("Audio diagnostics"))}</div>
<div class="audioDeviceMeta">${esc(t("IT-Screen default route: {route}", { route: textValue(itscreenRoute.label || itscreenRoute.device, t("Not configured")) }))}</div>
<div class="audioDeviceGrid">
${renderAudioDevice(audioDevices.hdmi || { target: "hdmi", label: "HDMI audio", device: "hw:1,0" }, "Test HDMI sound")}
${renderAudioDevice(audioDevices.analog || { target: "analog", label: "Analog audio", device: "hw:0,0" }, "Test Analog sound")}
@ -2024,6 +2061,9 @@
const registerHelper = payload && payload.registered ? t("Device is already registered") : (hostError || t("Select the target cloud server and start registration."));
const serviceWarnings = Array.isArray(service && service.warnings) ? service.warnings : [];
const serviceErrors = Array.isArray(service && service.errors) ? service.errors : [];
const registrationRequired = !!(payload && !payload.registered && !state.itscreen.error);
const registrationWarnClass = registrationRequired ? "registrationWarn" : "";
const registrationWarnKeyClass = registrationRequired ? "key registrationWarn" : "key";
if (state.itscreen.loading && !hasStatusPayload) {
return `<section class="tabPanel"><div class="empty">${esc(t("Loading cloud registration status..."))}</div></section>`;
@ -2063,10 +2103,12 @@
<div class="badge"><span class="dot ${statusMeta.tone}"></span>${esc(statusMeta.label)}</div>
</div>
</div>
${registrationRequired ? `<div class="banner warn">${esc(t("Registration required. Device is not bound to cloud."))}</div>` : ""}
${state.itscreen.error ? `<div class="banner error">${esc(state.itscreen.error)}${itscreenResponseDetails() ? `: ${esc(itscreenResponseDetails())}` : ""}</div>` : ""}
<div class="meta">
<div class="key">${esc(t("Status"))}</div><div>${esc(statusMeta.label)}</div>
<div class="key">${esc(t("Server"))}</div><div class="wrapValue">${esc(itscreenServerValue(payload))}</div>
<div class="${registrationWarnKeyClass}">${esc(t("Status"))}</div><div class="${registrationWarnClass}">${esc(registrationRequired ? t("Registration required") : statusMeta.label)}</div>
<div class="key">${esc(t("App version"))}</div><div>${esc(formatItscreenAppVersion(service && service.version))}</div>
<div class="${registrationWarnKeyClass}">${esc(t("Server"))}</div><div class="wrapValue ${registrationWarnClass}">${esc(itscreenServerValue(payload))}</div>
<div class="key">${esc(t("Device ID"))}</div><div class="wrapValue monoValue">${esc(notSpecified(payload && payload.device_id))}</div>
<div class="key">${esc(t("Device name"))}</div><div class="wrapValue">${esc(notSpecified(payload && payload.device_name))}</div>
<div class="key">${esc(t("Username"))}</div><div class="wrapValue monoValue">${esc(notSpecified(payload && payload.username))}</div>
@ -2076,9 +2118,9 @@
<div class="key">${esc(t("Detected contract"))}</div><div>${esc(itscreenContractLabel(payload))}</div>
<div class="key">${esc(t("Request topic"))}</div><div class="wrapValue monoValue">${esc(notSpecified(payload && payload.request_topic))}</div>
<div class="key">${esc(t("Response topic"))}</div><div class="wrapValue monoValue">${esc(notSpecified(payload && payload.response_topic))}</div>
<div class="key">${esc(t("Registered"))}</div><div>${esc(itscreenBooleanLabel(!!(payload && payload.registered), "registered"))}</div>
<div class="key">${esc(t("Logged"))}</div><div>${esc(itscreenBooleanLabel(!!(payload && payload.logged), "logged"))}</div>
<div class="key">${esc(t("Password state"))}</div><div>${esc(displayValue(payload && payload.password_state, t("Not specified")))}</div>
<div class="${registrationWarnKeyClass}">${esc(t("Registered"))}</div><div class="${registrationWarnClass}">${esc(itscreenBooleanLabel(!!(payload && payload.registered), "registered"))}</div>
<div class="${registrationWarnKeyClass}">${esc(t("Logged"))}</div><div class="${registrationWarnClass}">${esc(itscreenBooleanLabel(!!(payload && payload.logged), "logged"))}</div>
<div class="${registrationWarnKeyClass}">${esc(t("Password state"))}</div><div class="${registrationWarnClass}">${esc(displayValue(payload && payload.password_state, t("Not specified")))}</div>
</div>
</article>
@ -2096,7 +2138,11 @@
<input id="itscreenCustomHost" type="text" value="${esc(state.itscreen.customHost)}" oninput="window.__setItscreenCustomHost(this.value)" onfocus="window.__setItscreenFocus(true)" onblur="window.__setItscreenFocus(false)" placeholder="${esc(t("rest.custom.example.com"))}">
</label>
` : ""}
<div class="formHint">${esc(t("The backend sends the final hostname in MQTT set server, always in rest.* form."))}</div>
<label class="field">
<span>${esc(t("Registration token (optional)"))}</span>
<input id="itscreenCustomToken" type="text" value="${esc(state.itscreen.customToken)}" oninput="window.__setItscreenCustomToken(this.value)" placeholder="${esc(t("Paste organization token if required"))}">
</label>
<div class="formHint">${esc(t("The backend passes the initial registration payload to itscreen through local MQTT and runs the same headless registration flow as Registration.qml."))}</div>
<div id="itscreenResolvedHost" class="formHint">${esc(t("Resolved host: {host}", { host: serverHost }))}</div>
<div id="itscreenHostError" class="formError" ${hostError ? "" : "hidden"}>${esc(hostError)}</div>
<div class="actionColumn">
@ -2113,7 +2159,7 @@
<div class="key">${esc(t("Action"))}</div><div>${esc(textValue(lastEvent.action, "—"))}</div>
<div class="key">${esc(t("Operation"))}</div><div>${esc(textValue(lastEvent.operation, "—"))}</div>
<div class="key">${esc(t("Status"))}</div><div>${esc(displayValue(lastEvent.status, "—"))}</div>
<div class="key">${esc(t("Timestamp"))}</div><div>${esc(textValue(lastEvent.timestamp, "—"))}</div>
<div class="key">${esc(t("Timestamp"))}</div><div>${esc(formatMinuteTimestamp(lastEvent.timestamp))}</div>
</div>
<div class="list">
<div class="listTitle">${esc(t("Runtime"))}</div>
@ -3748,6 +3794,9 @@
state.itscreen.customHost = textValue(host, "");
}
}
if (!state.itscreen.busyAction) {
state.itscreen.customToken = itscreenTokenInputValue(payload && payload.token);
}
}
async function requestItscreenStatus() {
@ -4233,6 +4282,27 @@
}
};
window.__setAudioRoute = async function (target) {
if (!target || state.audioActions.busyRouteTarget) return;
state.audioActions.busyRouteTarget = target;
if (state.activeTab === "health") renderActiveTab();
try {
const payload = await fetchJson("/api/actions/audio-route", {
method: "POST",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ target })
});
showToast("success", payload.message || t("Audio route updated"));
await loadHealth();
} catch (error) {
showToast("error", error.message || t("Failed to update audio route"));
} finally {
state.audioActions.busyRouteTarget = "";
if (state.activeTab === "health") renderActiveTab();
}
};
window.__rebootDevice = async function () {
if (state.rebootPending) return;
if (!window.confirm(t("Reboot this device?"))) return;
@ -4284,6 +4354,10 @@
}
};
window.__setItscreenCustomToken = function (value) {
state.itscreen.customToken = value;
};
window.__setItscreenFocus = function (focused) {
state.itscreen.focused = !!focused;
};
@ -4318,7 +4392,7 @@
method: "POST",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ host: itscreenResolvedHost() })
body: JSON.stringify({ host: itscreenResolvedHost(), token: itscreenTokenInputValue(state.itscreen.customToken) })
});
const nextData = state.itscreen.data || {};
state.itscreen.data = { ...nextData, registration: payload.data || itscreenRegistration(), service: itscreenService() };