unit It-Screen App registartion data revised

This commit is contained in:
Andrei Smaliak 2026-04-25 10:32:11 +04:00
parent dbf660e149
commit b88b8e12a9
3 changed files with 205 additions and 60 deletions

View File

@ -39,7 +39,7 @@ APP_DIR = "/opt/iomatex-console"
PUBLIC_DIR = os.path.join(APP_DIR, "public") PUBLIC_DIR = os.path.join(APP_DIR, "public")
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d") PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
CONFIG_PATH = "/etc/iomatex/console.json" CONFIG_PATH = "/etc/iomatex/console.json"
UI_VERSION = "V 2.2.10" UI_VERSION = "V 2.2.17"
DEFAULT_CONFIG = { DEFAULT_CONFIG = {
"bind": "0.0.0.0", "bind": "0.0.0.0",
@ -421,21 +421,74 @@ def read_audio_device_status(card_index, pcm_index):
AUDIO_TARGETS = { AUDIO_TARGETS = {
"hdmi": { "hdmi": {
"label": "HDMI audio", "label": "HDMI audio",
"device": "hw:1,0", "default_device": "hw:1,0",
"card_index": 1, "default_card_index": 1,
"pcm_index": 0, "pcm_index": 0,
"description": "Digital audio over HDMI output", "description": "Digital audio over HDMI output",
"match_terms": ("hdmi",),
}, },
"analog": { "analog": {
"label": "Analog audio", "label": "Analog audio",
"device": "hw:0,0", "default_device": "hw:0,0",
"card_index": 0, "default_card_index": 0,
"pcm_index": 0, "pcm_index": 0,
"description": "Analog audio via rockchip-rk809 codec", "description": "Analog audio via rockchip-rk809 codec",
"match_terms": ("rk809", "codec", "analog", "headphone", "rockchip"),
}, },
} }
def resolve_audio_target_config(target, cards=None):
template = AUDIO_TARGETS.get(target)
if not template:
return None
cards = list(cards or parse_alsa_cards())
selected_card = None
selected_text = ""
for card in cards:
haystack = " ".join(
str(card.get(key, "")).strip().lower()
for key in ("id", "name", "description")
)
if target == "hdmi":
if "hdmi" in haystack:
selected_card = card
selected_text = haystack
break
continue
if "hdmi" in haystack:
continue
if any(term in haystack for term in template.get("match_terms", ())):
selected_card = card
selected_text = haystack
break
card_index = int(selected_card.get("index")) if selected_card else int(template["default_card_index"])
pcm_index = int(template["pcm_index"])
pcm_root = f"/proc/asound/card{card_index}/pcm{pcm_index}p"
present = os.path.exists(pcm_root)
if not present and not selected_card:
fallback_root = f"/proc/asound/card{template['default_card_index']}/pcm{pcm_index}p"
if os.path.exists(fallback_root):
card_index = int(template["default_card_index"])
pcm_root = fallback_root
present = True
return {
"target": target,
"label": template["label"],
"device": f"hw:{card_index},{pcm_index}",
"card_index": card_index,
"pcm_index": pcm_index,
"description": template["description"],
"detected": bool(selected_card),
"present": present,
"match_text": selected_text,
}
def get_audio_diagnostics(): def get_audio_diagnostics():
cards = parse_alsa_cards() 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)
@ -443,8 +496,12 @@ def get_audio_diagnostics():
route = audio_route_info() route = audio_route_info()
devices = {} devices = {}
for target, config in AUDIO_TARGETS.items(): for target in AUDIO_TARGETS:
config = resolve_audio_target_config(target, cards)
device_state = read_audio_device_status(config["card_index"], config["pcm_index"]) device_state = read_audio_device_status(config["card_index"], config["pcm_index"])
if not config.get("present") and device_state.get("status") == "error":
device_state["summary"] = "Audio device is not detected"
device_state["description"] = config["description"]
devices[target] = { devices[target] = {
"target": target, "target": target,
"label": config["label"], "label": config["label"],
@ -452,6 +509,8 @@ def get_audio_diagnostics():
"card_index": config["card_index"], "card_index": config["card_index"],
"pcm_index": config["pcm_index"], "pcm_index": config["pcm_index"],
"description": config["description"], "description": config["description"],
"detected": config["detected"],
"present": config["present"],
**device_state, **device_state,
} }
@ -477,11 +536,22 @@ def classify_audio_test_result(returncode, output):
def perform_audio_test(target): def perform_audio_test(target):
config = AUDIO_TARGETS.get(target) config = resolve_audio_target_config(target)
if not config: if not config:
raise ValueError("Unknown audio target") raise ValueError("Unknown audio target")
if not command_exists("speaker-test"): if not command_exists("speaker-test"):
raise RuntimeError("speaker-test command is not available") raise RuntimeError("speaker-test command is not available")
if not config.get("present"):
return {
"ok": False,
"target": target,
"device": config["device"],
"result": "failed",
"returncode": None,
"error": f"{config['label']} device is not detected",
"output": [f"{config['label']} device is not detected", f"Expected PCM: card{config['card_index']}/pcm{config['pcm_index']}p"],
"tested_at": utc_now_iso(),
}
cmd = [ cmd = [
"speaker-test", "speaker-test",
@ -506,15 +576,19 @@ def perform_audio_test(target):
check=False, check=False,
) )
output = "\n".join(part for part in [(proc.stdout or "").strip(), (proc.stderr or "").strip()] if part).strip() output = "\n".join(part for part in [(proc.stdout or "").strip(), (proc.stderr or "").strip()] if part).strip()
return { result = classify_audio_test_result(proc.returncode, output)
payload = {
"ok": proc.returncode == 0, "ok": proc.returncode == 0,
"target": target, "target": target,
"device": config["device"], "device": config["device"],
"result": classify_audio_test_result(proc.returncode, output), "result": result,
"returncode": proc.returncode, "returncode": proc.returncode,
"output": trim_output_lines(output, limit=10), "output": trim_output_lines(output, limit=10),
"tested_at": utc_now_iso(), "tested_at": utc_now_iso(),
} }
if not payload["ok"]:
payload["error"] = trim_output_lines(output, limit=1)[0] if trim_output_lines(output, limit=1) else f"{config['label']} test failed"
return payload
except subprocess.TimeoutExpired as exc: except subprocess.TimeoutExpired as exc:
output = "\n".join(part for part in [(exc.stdout or "").strip(), (exc.stderr or "").strip()] if part).strip() output = "\n".join(part for part in [(exc.stdout or "").strip(), (exc.stderr or "").strip()] if part).strip()
return { return {
@ -523,6 +597,7 @@ def perform_audio_test(target):
"device": config["device"], "device": config["device"],
"result": "failed", "result": "failed",
"returncode": None, "returncode": None,
"error": "Audio test timed out",
"output": trim_output_lines(output or "Audio test timed out", limit=10), "output": trim_output_lines(output or "Audio test timed out", limit=10),
"tested_at": utc_now_iso(), "tested_at": utc_now_iso(),
} }

View File

@ -29,10 +29,20 @@ ITSCREEN_CONFIG_PATH = "/var/lib/itscreen/config/it-screen/it-screen.conf"
SETTINGS_CONTRACTS = ( SETTINGS_CONTRACTS = (
{"contract_prefix": "it-screen", "base_prefix": "it-screen/$devices/settings"}, {"contract_prefix": "it-screen", "base_prefix": "it-screen/$devices/settings"},
{"contract_prefix": "iomatex", "base_prefix": "iomatex/$devices/settings"}, {"contract_prefix": "iomatex", "base_prefix": "iomatex/$devices/settings"},
{"contract_prefix": "universal", "base_prefix": "device/settings"}, {"contract_prefix": "universal", "base_prefix": "$devices/settings"},
) )
DEFAULT_CONTRACT_PREFIX = SETTINGS_CONTRACTS[0]["contract_prefix"] DEFAULT_CONTRACT_PREFIX = SETTINGS_CONTRACTS[0]["contract_prefix"]
DEVICE_TOPIC_PREFIXES = ("it-screen/devices", "iomatex/devices", "devices") DEVICE_TOPIC_PREFIXES = ("it-screen/devices", "iomatex/devices", "devices")
ITSCREEN_HOSTS = {
"dev.it-screen.com",
"rest.dev.it-screen.com",
}
IOMATEX_HOSTS = {
"uae.iomatex.com",
"ae.iomatex.com",
"rest.uae.iomatex.com",
"rest.ae.iomatex.com",
}
def _debug(message): def _debug(message):
@ -81,11 +91,11 @@ def _host_contract_hint(host):
value = str(host or "").strip().lower() value = str(host or "").strip().lower()
if not value: if not value:
return "" return ""
if "iomatex" in value: if value in ITSCREEN_HOSTS:
return "iomatex"
if "it-screen" in value:
return "it-screen" return "it-screen"
return "" if value in IOMATEX_HOSTS:
return "iomatex"
return "universal"
def get_candidate_device_topics(device_id, server_host_hint=None): def get_candidate_device_topics(device_id, server_host_hint=None):
@ -125,7 +135,20 @@ def _build_contract_topics(device_id, contract_prefix):
def get_candidate_settings_topics(device_id, preferred_contract=None, server_host_hint=None): def get_candidate_settings_topics(device_id, preferred_contract=None, server_host_hint=None):
ordered = [] ordered = []
seen = set() seen = set()
for candidate in (preferred_contract, _host_contract_hint(server_host_hint), DEFAULT_CONTRACT_PREFIX): host_contract = _host_contract_hint(server_host_hint)
for candidate in (preferred_contract, host_contract):
if candidate and candidate not in seen and _contract_by_prefix(candidate):
ordered.append(candidate)
seen.add(candidate)
if host_contract == "it-screen":
fallback_order = ("universal", "iomatex")
elif host_contract == "iomatex":
fallback_order = ("universal", "it-screen")
elif host_contract == "universal":
fallback_order = (DEFAULT_CONTRACT_PREFIX, "iomatex")
else:
fallback_order = (DEFAULT_CONTRACT_PREFIX, "iomatex", "universal")
for candidate in fallback_order:
if candidate and candidate not in seen and _contract_by_prefix(candidate): if candidate and candidate not in seen and _contract_by_prefix(candidate):
ordered.append(candidate) ordered.append(candidate)
seen.add(candidate) seen.add(candidate)
@ -305,22 +328,7 @@ def _load_registration_from_itscreen_config(device_id, persisted=None):
def _candidate_login_passwords(device_id, persisted=None): def _candidate_login_passwords(device_id, persisted=None):
candidates = [] return [LOGIN_PASSWORD]
seen = set()
def add(value):
text = _truncate_empty(value)
if not text or text in seen:
return
seen.add(text)
candidates.append(text)
persisted = persisted or {}
add((persisted or {}).get("password"))
config_payload = _load_registration_from_itscreen_config(device_id, persisted=persisted)
add(config_payload.get("password"))
add(LOGIN_PASSWORD)
return candidates
def _extract_response_payload(response_text): def _extract_response_payload(response_text):
@ -503,25 +511,34 @@ class MqttSettingsSession:
self.connected = threading.Event() self.connected = threading.Event()
self.error = None self.error = None
self.contract_meta = dict(contract_meta or {}) self.contract_meta = dict(contract_meta or {})
self._subscribe_lock = threading.Lock()
self._subscribe_status = {}
self._response_sub_mid = None
self.client = mqtt.Client(client_id=f"console-core-{device_id}-{int(time.time() * 1000)}", clean_session=True) self.client = mqtt.Client(client_id=f"console-core-{device_id}-{int(time.time() * 1000)}", clean_session=True)
self.client.on_connect = self._on_connect self.client.on_connect = self._on_connect
self.client.on_message = self._on_message self.client.on_message = self._on_message
self.client.on_disconnect = self._on_disconnect self.client.on_disconnect = self._on_disconnect
self.client.on_subscribe = self._on_subscribe
def _on_connect(self, client, userdata, flags, rc): def _on_connect(self, client, userdata, flags, rc):
if rc != 0: if rc != 0:
self.error = f"MQTT connect failed ({rc})" self.error = f"MQTT connect failed ({rc})"
return return
result, _ = client.subscribe(self.contract_meta["response_topic"], qos=0) result, mid = client.subscribe(self.contract_meta["response_topic"], qos=0)
if result != mqtt.MQTT_ERR_SUCCESS: if result != mqtt.MQTT_ERR_SUCCESS:
self.error = "Device settings service is unavailable" self.error = "Device settings service is unavailable"
return return
self._mark_subscribe_pending(mid)
self._response_sub_mid = mid
self.connected.set() self.connected.set()
def _on_disconnect(self, client, userdata, rc): def _on_disconnect(self, client, userdata, rc):
if rc not in (0, None) and not self.error: if rc not in (0, None) and not self.error:
self.error = "Device settings service is unavailable" self.error = "Device settings service is unavailable"
def _on_subscribe(self, client, userdata, mid, granted_qos):
self._mark_subscribe_done(mid)
def _on_message(self, client, userdata, msg): def _on_message(self, client, userdata, msg):
raw = msg.payload.decode("utf-8", errors="ignore") raw = msg.payload.decode("utf-8", errors="ignore")
try: try:
@ -530,6 +547,28 @@ class MqttSettingsSession:
payload = {"__invalid_json__": raw} payload = {"__invalid_json__": raw}
self.queue.put(payload) self.queue.put(payload)
def _mark_subscribe_pending(self, mid):
with self._subscribe_lock:
self._subscribe_status[mid] = self._subscribe_status.get(mid, False)
def _mark_subscribe_done(self, mid):
with self._subscribe_lock:
self._subscribe_status[mid] = True
def _wait_for_subscribe(self, mid, timeout=2.0):
if mid is None:
raise RuntimeError("Device settings service is unavailable")
deadline = time.time() + timeout
while time.time() < deadline:
if self.error:
raise RuntimeError(self.error)
with self._subscribe_lock:
done = self._subscribe_status.get(mid)
if done is True:
return
time.sleep(0.05)
raise TimeoutError("MQTT subscribe timeout")
def __enter__(self): def __enter__(self):
host, port = _parse_mqtt_url(MQTT_URL) host, port = _parse_mqtt_url(MQTT_URL)
try: try:
@ -540,6 +579,7 @@ class MqttSettingsSession:
if not self.connected.wait(5): if not self.connected.wait(5):
self.close() self.close()
raise RuntimeError(self.error or "Device settings service is unavailable") raise RuntimeError(self.error or "Device settings service is unavailable")
self._wait_for_subscribe(self._response_sub_mid, timeout=2.0)
return self return self
def __exit__(self, exc_type, exc, tb): def __exit__(self, exc_type, exc, tb):
@ -626,9 +666,11 @@ class MqttSettingsSession:
def read_retained_topic_payload(self, topic, timeout=1.5): def read_retained_topic_payload(self, topic, timeout=1.5):
self._drain() self._drain()
result, _ = self.client.subscribe(topic, qos=0) result, mid = self.client.subscribe(topic, qos=0)
if result != mqtt.MQTT_ERR_SUCCESS: if result != mqtt.MQTT_ERR_SUCCESS:
raise RuntimeError("Device registration topic subscribe failed") raise RuntimeError("Device registration topic subscribe failed")
self._mark_subscribe_pending(mid)
self._wait_for_subscribe(mid, timeout=2.0)
deadline = time.time() + timeout deadline = time.time() + timeout
try: try:
while time.time() < deadline: while time.time() < deadline:
@ -748,16 +790,7 @@ def get_registration_status():
try: try:
def _status_flow(session, _contract_meta): def _status_flow(session, _contract_meta):
session.login(_candidate_login_passwords(state["device_id"], persisted)) session.login(_candidate_login_passwords(state["device_id"], persisted))
server_state = session.get_server_state() return session.get_server_state()
device_state = _read_device_registration_snapshot(
session,
state["device_id"],
server_host_hint=_truncate_empty(server_state.get("host")) or _truncate_empty(server_state.get("server")),
)
return {
"server_state": server_state,
"device_state": device_state,
}
contract_meta, status_flow = _with_settings_contract( contract_meta, status_flow = _with_settings_contract(
state["device_id"], state["device_id"],
@ -766,9 +799,7 @@ def get_registration_status():
_status_flow, _status_flow,
server_host_hint=state.get("host", ""), server_host_hint=state.get("host", ""),
) )
server_state = status_flow["server_state"] merged_state = status_flow if isinstance(status_flow, dict) else {}
device_state = status_flow.get("device_state") or {}
merged_state = _merge_device_registration_payload(server_state, device_state)
current = { current = {
"host": _truncate_empty(merged_state.get("host")) or _truncate_empty(merged_state.get("server")), "host": _truncate_empty(merged_state.get("host")) or _truncate_empty(merged_state.get("server")),
"username": _truncate_empty(merged_state.get("username")), "username": _truncate_empty(merged_state.get("username")),

View File

@ -44,7 +44,7 @@
{ mode: "test_by", label: "TEST BY", host: "rest.test.it-screen.by" }, { mode: "test_by", label: "TEST BY", host: "rest.test.it-screen.by" },
{ mode: "custom", label: "Custom", host: "" } { mode: "custom", label: "Custom", host: "" }
]; ];
const UI_VERSION = "V 2.2.10"; const UI_VERSION = "V 2.2.17";
const ITSCREEN_LOG_INITIAL_LINES = 50; const ITSCREEN_LOG_INITIAL_LINES = 50;
const ITSCREEN_LOG_BUFFER_LIMIT = 300; const ITSCREEN_LOG_BUFFER_LIMIT = 300;
const ITSCREEN_LOG_BATCH_MS = 250; const ITSCREEN_LOG_BATCH_MS = 250;
@ -279,7 +279,8 @@
busy: false, busy: false,
error: "", error: "",
info: "", info: "",
expiresAt: 0 expiresAt: 0,
sessionRequestId: 0
}, },
accountPassword: { accountPassword: {
busy: false, busy: false,
@ -1067,12 +1068,18 @@
function itscreenContractLabel(payload) { function itscreenContractLabel(payload) {
const contract = textValue(payload && payload.contract_prefix, ""); const contract = textValue(payload && payload.contract_prefix, "");
if (contract === "it-screen") return "it-screen"; if (contract === "it-screen") return "it-screen/$devices/settings";
if (contract === "iomatex") return "iomatex"; if (contract === "iomatex") return "iomatex/$devices/settings";
if (contract === "universal") return "device/settings"; if (contract === "universal") return "$devices/settings";
return t("Not specified"); return t("Not specified");
} }
function itscreenMaskedPassword(payload) {
const password = textValue(payload && payload.password, "");
if (!password) return t("Not specified");
return "******";
}
function itscreenResponseDetails() { function itscreenResponseDetails() {
return textValue(state.itscreen.details, ""); return textValue(state.itscreen.details, "");
} }
@ -1141,7 +1148,7 @@
{ label: t("Device ID"), value: notSpecified(payload && payload.device_id) }, { label: t("Device ID"), value: notSpecified(payload && payload.device_id) },
{ label: t("Device name"), value: notSpecified(payload && payload.device_name) }, { label: t("Device name"), value: notSpecified(payload && payload.device_name) },
{ label: t("Username"), value: notSpecified(payload && payload.username) }, { label: t("Username"), value: notSpecified(payload && payload.username) },
{ label: t("Password"), value: notSpecified(payload && payload.password) }, { label: t("Password"), value: itscreenMaskedPassword(payload) },
{ label: t("Organization"), value: notSpecified(payload && payload.organization) }, { label: t("Organization"), value: notSpecified(payload && payload.organization) },
{ label: t("Token"), value: notSpecified(payload && payload.token) }, { label: t("Token"), value: notSpecified(payload && payload.token) },
{ label: t("Detected contract"), value: itscreenContractLabel(payload) }, { label: t("Detected contract"), value: itscreenContractLabel(payload) },
@ -1267,6 +1274,8 @@
function renderAudioDevice(device, buttonLabel) { function renderAudioDevice(device, buttonLabel) {
const testMeta = audioTestMeta(device && device.target); const testMeta = audioTestMeta(device && device.target);
const busy = audioBusyTarget === device.target; const busy = audioBusyTarget === device.target;
const deviceStatusMeta = audioStatusMeta(device && device.status);
const unavailable = textValue(device && device.status, "error").toLowerCase() === "error";
return ` return `
<article class="audioDeviceCard"> <article class="audioDeviceCard">
<div class="audioDeviceHead"> <div class="audioDeviceHead">
@ -1275,9 +1284,11 @@
<div class="audioDeviceSubhead">${esc(textValue(device.description, t("Not available")))}</div> <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(t("ALSA device: {device}", { device: textValue(device.device, t("Not available")) }))}</div>
</div> </div>
<span class="actionBadge actionBadge-${deviceStatusMeta.tone}">${esc(unavailable ? t("Unavailable") : deviceStatusMeta.label)}</span>
</div> </div>
${device && device.summary ? `<div class="audioDeviceMeta">${esc(device.summary)}</div>` : ""}
<div class="audioActionRow"> <div class="audioActionRow">
<button class="actionBtn" type="button" ${busy ? "disabled" : ""} onclick="window.__runAudioTest('${esc(device.target)}')">${esc(busy ? t("Testing...") : t(buttonLabel))}</button> <button class="actionBtn" type="button" ${(busy || unavailable) ? "disabled" : ""} onclick="window.__runAudioTest('${esc(device.target)}')">${esc(busy ? t("Testing...") : t(buttonLabel))}</button>
</div> </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.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>` : ""} ${testMeta.output.length ? `<pre class="diagBlock testOutput">${esc(testMeta.output.join("\n"))}</pre>` : ""}
@ -2059,7 +2070,7 @@
<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 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("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> <div class="key">${esc(t("Username"))}</div><div class="wrapValue monoValue">${esc(notSpecified(payload && payload.username))}</div>
<div class="key">${esc(t("Password"))}</div><div class="wrapValue monoValue">${esc(notSpecified(payload && payload.password))}</div> <div class="key">${esc(t("Password"))}</div><div class="wrapValue monoValue">${esc(itscreenMaskedPassword(payload))}</div>
<div class="key">${esc(t("Organization"))}</div><div class="wrapValue">${esc(notSpecified(payload && payload.organization))}</div> <div class="key">${esc(t("Organization"))}</div><div class="wrapValue">${esc(notSpecified(payload && payload.organization))}</div>
<div class="key">${esc(t("Token"))}</div><div class="wrapValue" title="${esc(notSpecified(payload && payload.token))}">${esc(compactToken(payload && payload.token))}</div> <div class="key">${esc(t("Token"))}</div><div class="wrapValue" title="${esc(notSpecified(payload && payload.token))}">${esc(compactToken(payload && payload.token))}</div>
<div class="key">${esc(t("Detected contract"))}</div><div>${esc(itscreenContractLabel(payload))}</div> <div class="key">${esc(t("Detected contract"))}</div><div>${esc(itscreenContractLabel(payload))}</div>
@ -3563,6 +3574,8 @@
async function loadAuthSession(options = {}) { async function loadAuthSession(options = {}) {
const silent = !!options.silent; const silent = !!options.silent;
const requestId = (Number(state.auth.sessionRequestId) || 0) + 1;
state.auth.sessionRequestId = requestId;
if (!silent) { if (!silent) {
state.auth.loading = true; state.auth.loading = true;
state.auth.error = ""; state.auth.error = "";
@ -3575,6 +3588,7 @@
if (!response.ok) { if (!response.ok) {
throw new Error(payload.error || `HTTP ${response.status}`); throw new Error(payload.error || `HTTP ${response.status}`);
} }
if (requestId !== state.auth.sessionRequestId) return payload;
if (payload.authenticated) { if (payload.authenticated) {
applyAuthSession(payload); applyAuthSession(payload);
} else { } else {
@ -3582,6 +3596,7 @@
} }
return payload; return payload;
} catch (error) { } catch (error) {
if (requestId !== state.auth.sessionRequestId) throw error;
setAuthRequired(t("Authorization required")); setAuthRequired(t("Authorization required"));
throw error; throw error;
} }
@ -3602,6 +3617,21 @@
return payload; return payload;
} }
async function fetchJsonAllowLogicalFailure(url, options) {
const response = await fetch(url, options || { cache: "no-store" });
const payload = await response.json().catch(() => ({}));
if (response.status === 401) {
if (String(url || "").indexOf("/api/auth/login") !== 0) {
setAuthRequired(t("Session expired, please sign in again"));
}
throw new Error(payload.error || t("Session expired, please sign in again"));
}
if (!response.ok) {
throw new Error(payload.error || `HTTP ${response.status}`);
}
return payload;
}
function replaceServiceCard(nextCard) { function replaceServiceCard(nextCard) {
if (!nextCard || !state.healthServices || !Array.isArray(state.healthServices.services)) return; if (!nextCard || !state.healthServices || !Array.isArray(state.healthServices.services)) return;
state.healthServices.services = state.healthServices.services.map((card) => (card && card.id === nextCard.id ? nextCard : card)); state.healthServices.services = state.healthServices.services.map((card) => (card && card.id === nextCard.id ? nextCard : card));
@ -3798,13 +3828,13 @@
state.itscreen.details = (payload && payload.details) || ""; state.itscreen.details = (payload && payload.details) || "";
state.itscreen.registrationLoadedAt = Date.now(); state.itscreen.registrationLoadedAt = Date.now();
syncItscreenFormFromBackend(); syncItscreenFormFromBackend();
if (state.activeTab === "tscreen") renderActiveTab(); if (state.activeTab === "tscreen" || state.activeTab === "health") renderActiveTab();
return state.itscreen.data.registration; return state.itscreen.data.registration;
} catch (error) { } catch (error) {
if (error && error.name === "AbortError") return itscreenRegistration(); if (error && error.name === "AbortError") return itscreenRegistration();
state.itscreen.error = error.message || t("Cloud registration status is unavailable"); state.itscreen.error = error.message || t("Cloud registration status is unavailable");
state.itscreen.details = ""; state.itscreen.details = "";
if (state.activeTab === "tscreen") renderActiveTab(); if (state.activeTab === "tscreen" || state.activeTab === "health") renderActiveTab();
return itscreenRegistration(); return itscreenRegistration();
} finally { } finally {
state.itscreen.registrationRequestController = null; state.itscreen.registrationRequestController = null;
@ -3837,7 +3867,7 @@
state.itscreen.loadedAt = Date.now(); state.itscreen.loadedAt = Date.now();
if (!state.itscreen.registrationLoadedAt || force) { if (!state.itscreen.registrationLoadedAt || force) {
window.setTimeout(() => { window.setTimeout(() => {
if (state.activeTab === "tscreen" && state.auth.authenticated) { if ((state.activeTab === "tscreen" || state.activeTab === "health") && state.auth.authenticated) {
loadItscreenRegistration({ force, maxAgeMs: 30000 }).catch(() => {}); loadItscreenRegistration({ force, maxAgeMs: 30000 }).catch(() => {});
} }
}, 0); }, 0);
@ -4181,14 +4211,14 @@
state.audioActions.busyTarget = target; state.audioActions.busyTarget = target;
if (state.activeTab === "health") renderActiveTab(); if (state.activeTab === "health") renderActiveTab();
try { try {
const payload = await fetchJson("/api/actions/audio-test", { const payload = await fetchJsonAllowLogicalFailure("/api/actions/audio-test", {
method: "POST", method: "POST",
cache: "no-store", cache: "no-store",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ target }) body: JSON.stringify({ target })
}); });
state.audioActions.results[target] = payload; state.audioActions.results[target] = payload;
showToast(payload.result === "success" ? "success" : (payload.result === "busy" ? "warn" : "error"), t("{target} audio test: {result}", { target: target === "hdmi" ? t("HDMI") : t("Analog"), result: payload.result || t("unknown") })); showToast(payload.result === "success" ? "success" : (payload.result === "busy" ? "warn" : "error"), payload.error || t("{target} audio test: {result}", { target: target === "hdmi" ? t("HDMI") : t("Analog"), result: payload.result || t("unknown") }));
await loadHealth(); await loadHealth();
} catch (error) { } catch (error) {
state.audioActions.results[target] = { state.audioActions.results[target] = {
@ -4960,6 +4990,7 @@
window.__authSubmit = async function (event) { window.__authSubmit = async function (event) {
if (event && typeof event.preventDefault === "function") event.preventDefault(); if (event && typeof event.preventDefault === "function") event.preventDefault();
if (state.auth.busy || state.auth.loading) return; if (state.auth.busy || state.auth.loading) return;
state.auth.sessionRequestId = (Number(state.auth.sessionRequestId) || 0) + 1;
const username = textValue(state.auth.username, "iomatex"); const username = textValue(state.auth.username, "iomatex");
const password = state.auth.password || ""; const password = state.auth.password || "";
if (!password.trim()) { if (!password.trim()) {
@ -4979,12 +5010,20 @@
body: JSON.stringify({ username, password }) body: JSON.stringify({ username, password })
}); });
applyAuthSession(payload); applyAuthSession(payload);
state.auth.loading = true;
renderActiveTab();
try {
await loadForActiveTab(); await loadForActiveTab();
} finally {
state.auth.loading = false;
}
if (state.activeTab === "tscreen") { if (state.activeTab === "tscreen") {
activateItscreenLogs().catch(() => {}); activateItscreenLogs().catch(() => {});
} }
renderActiveTab();
} catch (error) { } catch (error) {
state.auth.busy = false; state.auth.busy = false;
state.auth.loading = false;
state.auth.authenticated = false; state.auth.authenticated = false;
state.auth.error = error.message || t("Invalid password"); state.auth.error = error.message || t("Invalid password");
renderActiveTab(); renderActiveTab();