${esc(card.title)}
+ ${card.subtitle ? `${esc(card.subtitle)}
` : ""} +- ${warnings.map((x) => `
- ${esc(x)} `).join("")}
- ${errors.map((x) => `
- ${esc(x)} `).join("")}
diff --git a/local_installer.sh b/local_installer.sh
index e7fe72e..8666d34 100755
--- a/local_installer.sh
+++ b/local_installer.sh
@@ -479,7 +479,6 @@ stage_candidates() {
stage_ui)
printf '%s\n' "ui_installer.sh"
printf '%s\n' "stage_ui_install.sh"
- printf '%s\n' "stage_display_addon.sh"
;;
stage_itscreen)
printf '%s\n' "stage_itscreen_install.sh"
diff --git a/stage_ui/console_core/backend/app.py b/stage_ui/console_core/backend/app.py
index abf4b2c..4028348 100644
--- a/stage_ui/console_core/backend/app.py
+++ b/stage_ui/console_core/backend/app.py
@@ -6,12 +6,14 @@ import json
import os
import shutil
import re
+import select
import subprocess
import sys
import tempfile
import time
+from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-from urllib.parse import urlparse
+from urllib.parse import parse_qs, urlparse
from itscreen_registration import get_registration_status, register_device, reset_registration
APP_DIR = "/opt/iomatex-console"
@@ -29,6 +31,7 @@ _CACHE = {"expires_at": 0.0, "payload": None}
_CPU_SAMPLE = {"total": None, "idle": None}
_NET_SAMPLE = {}
_WIFI_SCAN_CACHE = {"expires_at": 0.0, "payload": None}
+_ITSCREEN_CONFIG_CACHE = {"expires_at": 0.0, "payload": None}
_WIFI_RESCAN_MIN_INTERVAL_SEC = 30.0
AP_ENV_PATH = "/etc/iomatex/ap.env"
WIFI_ENV_PATH = "/etc/iomatex/wifi.env"
@@ -41,6 +44,11 @@ WIFI_SETUP_SCRIPT = "/usr/local/sbin/iomatex-wifi-setup"
DEVICE_ID_PATH = "/userdata/device-id"
DEVICE_ID_RE = re.compile(r"^g-box-[a-f0-9]{8}$")
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_CONFIG_CACHE_TTL_SEC = 3.0
+ITSCREEN_LOG_DEFAULT_LINES = 50
+ITSCREEN_LOG_MAX_LINES = 300
DEFAULT_AP_UI_PORT = "80"
CAPTIVE_PORTAL_PATH = "/portal"
CAPTIVE_PORTAL_ALIASES = {
@@ -102,6 +110,274 @@ def run(cmd, timeout=4):
return 1, "", str(exc)
+def command_exists(name):
+ return shutil.which(name) is not None
+
+
+def utc_now_iso():
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+
+
+def trim_output_lines(text, limit=12, width=220):
+ lines = []
+ for raw in (text or "").splitlines():
+ line = raw.strip()
+ if not line:
+ continue
+ if len(line) > width:
+ line = line[: width - 3] + "..."
+ lines.append(line)
+ if len(lines) > limit:
+ lines = lines[:limit] + [f"... ({len(lines) - limit} more lines)"]
+ return lines
+
+
+def parse_alsa_cards():
+ raw = read_text("/proc/asound/cards")
+ cards = []
+ current = None
+ for line in raw.splitlines():
+ match = re.match(r"^\s*(\d+)\s+\[(.*?)\s*\]:\s*(.*)$", line)
+ if match:
+ current = {
+ "index": int(match.group(1)),
+ "id": match.group(2).strip(),
+ "name": match.group(3).strip(),
+ "description": "",
+ }
+ cards.append(current)
+ continue
+ if current and line.startswith(" "):
+ extra = line.strip()
+ if extra:
+ current["description"] = extra
+ return cards
+
+
+def get_alsa_card(card_index):
+ for card in parse_alsa_cards():
+ if card.get("index") == card_index:
+ return card
+ return {}
+
+
+def audio_route_info():
+ pactl_error_lines = []
+ if command_exists("pactl"):
+ rc, stdout, stderr = run(["pactl", "info"], timeout=4)
+ if rc == 0:
+ info = {}
+ for line in (stdout or "").splitlines():
+ if ":" not in line:
+ continue
+ key, value = line.split(":", 1)
+ info[key.strip()] = value.strip()
+ sink = info.get("Default Sink")
+ server_name = info.get("Server Name")
+ summary = sink or server_name or "PulseAudio/PipeWire route detected"
+ return {
+ "type": "pulse",
+ "summary": summary,
+ "details": trim_output_lines(stdout, limit=6),
+ }
+ pactl_error_lines = trim_output_lines(stderr or stdout, limit=4)
+
+ rc, stdout, stderr = run(["aplay", "-L"], timeout=4)
+ if rc == 0:
+ has_default = any(line.strip() == "default" for line in (stdout or "").splitlines())
+ return {
+ "type": "alsa" if has_default else "unknown",
+ "summary": "ALSA default device is available" if has_default else "Logical ALSA devices listed",
+ "details": pactl_error_lines + trim_output_lines(stdout, limit=8 - len(pactl_error_lines)),
+ }
+ return {
+ "type": "unknown",
+ "summary": trim_output_lines(stderr or stdout, limit=1)[0] if trim_output_lines(stderr or stdout, limit=1) else "Audio route unavailable",
+ "details": pactl_error_lines + trim_output_lines(stderr or stdout, limit=max(1, 4 - len(pactl_error_lines))),
+ }
+
+
+def read_audio_device_status(card_index, pcm_index):
+ card = get_alsa_card(card_index)
+ pcm_root = f"/proc/asound/card{card_index}/pcm{pcm_index}p"
+ info_path = os.path.join(pcm_root, "info")
+ status_path = os.path.join(pcm_root, "sub0/status")
+ hw_params_path = os.path.join(pcm_root, "sub0/hw_params")
+
+ info_text = read_text(info_path).strip()
+ status_text = read_text(status_path).strip()
+ hw_params_text = read_text(hw_params_path).strip()
+
+ status_lower = status_text.lower()
+ if not os.path.exists(pcm_root):
+ status = "error"
+ summary = "PCM playback device not found"
+ elif not status_text:
+ status = "error"
+ summary = "Playback status is unavailable"
+ elif "closed" in status_lower:
+ status = "available"
+ summary = "Playback device is idle"
+ else:
+ status = "busy"
+ summary = trim_output_lines(status_text, limit=1)[0] if trim_output_lines(status_text, limit=1) else "Playback device is busy"
+
+ short_description = ""
+ info_lines = trim_output_lines(info_text, limit=6)
+ if info_lines:
+ short_description = info_lines[0]
+ elif card.get("description"):
+ short_description = card["description"]
+
+ return {
+ "status": status,
+ "summary": summary,
+ "card_name": card.get("name") or card.get("id") or f"card {card_index}",
+ "card_id": card.get("id", ""),
+ "description": short_description,
+ "info_lines": info_lines,
+ "status_lines": trim_output_lines(status_text, limit=6),
+ "hw_params_lines": trim_output_lines(hw_params_text, limit=6),
+ }
+
+
+AUDIO_TARGETS = {
+ "hdmi": {
+ "label": "HDMI audio",
+ "device": "hw:1,0",
+ "card_index": 1,
+ "pcm_index": 0,
+ "description": "Digital audio over HDMI output",
+ },
+ "analog": {
+ "label": "Analog audio",
+ "device": "hw:0,0",
+ "card_index": 0,
+ "pcm_index": 0,
+ "description": "Analog audio via rockchip-rk809 codec",
+ },
+}
+
+
+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()
+ devices = {}
+
+ for target, config in AUDIO_TARGETS.items():
+ device_state = read_audio_device_status(config["card_index"], config["pcm_index"])
+ devices[target] = {
+ "target": target,
+ "label": config["label"],
+ "device": config["device"],
+ "card_index": config["card_index"],
+ "pcm_index": config["pcm_index"],
+ "description": config["description"],
+ **device_state,
+ }
+
+ return {
+ "devices": devices,
+ "parameters": {
+ "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,
+ "alsa_cards": cards,
+ },
+ "generated_at": utc_now_iso(),
+ }
+
+
+def classify_audio_test_result(returncode, output):
+ text = (output or "").lower()
+ if returncode == 0:
+ return "success"
+ if "device or resource busy" in text or "busy" in text:
+ return "busy"
+ return "failed"
+
+
+def perform_audio_test(target):
+ config = AUDIO_TARGETS.get(target)
+ if not config:
+ raise ValueError("Unknown audio target")
+ if not command_exists("speaker-test"):
+ raise RuntimeError("speaker-test command is not available")
+
+ cmd = [
+ "speaker-test",
+ "-D",
+ config["device"],
+ "-c",
+ "2",
+ "-l",
+ "1",
+ "-t",
+ "sine",
+ "-f",
+ "440",
+ ]
+ try:
+ proc = subprocess.run(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ timeout=6,
+ check=False,
+ )
+ output = "\n".join(part for part in [(proc.stdout or "").strip(), (proc.stderr or "").strip()] if part).strip()
+ return {
+ "ok": proc.returncode == 0,
+ "target": target,
+ "device": config["device"],
+ "result": classify_audio_test_result(proc.returncode, output),
+ "returncode": proc.returncode,
+ "output": trim_output_lines(output, limit=10),
+ "tested_at": utc_now_iso(),
+ }
+ except subprocess.TimeoutExpired as exc:
+ output = "\n".join(part for part in [(exc.stdout or "").strip(), (exc.stderr or "").strip()] if part).strip()
+ return {
+ "ok": False,
+ "target": target,
+ "device": config["device"],
+ "result": "failed",
+ "returncode": None,
+ "output": trim_output_lines(output or "Audio test timed out", limit=10),
+ "tested_at": utc_now_iso(),
+ }
+
+
+def request_reboot():
+ try:
+ proc = subprocess.run(
+ ["sudo", "-n", "reboot"],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ timeout=4,
+ check=False,
+ )
+ except subprocess.TimeoutExpired:
+ return {
+ "ok": True,
+ "message": "Reboot requested. Connection may drop shortly.",
+ "requested_at": utc_now_iso(),
+ }
+ stdout = (proc.stdout or "").strip()
+ stderr = (proc.stderr or "").strip()
+ if proc.returncode != 0:
+ raise RuntimeError(stderr or stdout or "Failed to request reboot")
+ return {
+ "ok": True,
+ "message": "Reboot requested. Connection may drop shortly.",
+ "requested_at": utc_now_iso(),
+ }
+
+
def file_exists(path):
return os.path.exists(path)
@@ -1076,6 +1352,7 @@ def build_status_payload():
"run": run,
"get_ap_status_card": ap_status_card,
"get_identity_payload": get_identity_payload,
+ "get_audio_diagnostics": get_audio_diagnostics,
}
cards = []
provider_names = []
@@ -1123,6 +1400,394 @@ def find_service_card(service_id):
return None
+def normalize_service_status(unit):
+ if not isinstance(unit, dict):
+ return "unknown", "Unknown"
+ if not unit.get("installed"):
+ return "not_installed", "Not installed"
+ active_state = str(unit.get("active_state", "") or "").strip().lower()
+ result = str(unit.get("result", "") or "").strip().lower()
+ if active_state == "active":
+ return "running", "Running"
+ if active_state == "failed" or result == "failed":
+ return "failed", "Failed"
+ if active_state in ("inactive", "deactivating", "activating", "reloading"):
+ return "stopped", "Stopped"
+ return "unknown", "Unknown"
+
+
+def get_itscreen_service_status():
+ try:
+ unit = systemd_unit(ITSCREEN_SERVICE_UNIT)
+ status, status_label = normalize_service_status(unit)
+ return {
+ "ok": True,
+ "name": "itscreen",
+ "unit": ITSCREEN_SERVICE_UNIT,
+ "installed": bool(unit.get("installed", False)),
+ "active": bool(unit.get("active", False)),
+ "status": status,
+ "status_label": status_label,
+ "active_state": str(unit.get("active_state", "") or ""),
+ "sub_state": str(unit.get("sub_state", "") or ""),
+ }
+ except Exception as exc:
+ return {
+ "ok": False,
+ "name": "itscreen",
+ "unit": ITSCREEN_SERVICE_UNIT,
+ "installed": False,
+ "active": False,
+ "status": "unknown",
+ "status_label": "Unknown",
+ "error": "Could not read service status",
+ "details": str(exc),
+ }
+
+
+def build_itscreen_status_payload():
+ return {
+ "ok": True,
+ "service": get_itscreen_service_status(),
+ "registration": get_registration_status(),
+ }
+
+
+def systemctl_show_property(unit_name, property_name, timeout=5):
+ rc, stdout, stderr = run(["systemctl", "show", unit_name, "-p", property_name], timeout=timeout)
+ if rc != 0:
+ raise RuntimeError(stderr or f"Failed to read {property_name}")
+ line = (stdout or "").strip()
+ if not line:
+ return ""
+ if "=" not in line:
+ return line
+ _, _, value = line.partition("=")
+ return value.strip()
+
+
+def parse_systemctl_timestamp(raw_value):
+ text = str(raw_value or "").strip()
+ if not text or text.lower() in ("n/a", "0"):
+ return None
+ parts = text.split()
+ if len(parts) >= 3 and parts[0].isalpha():
+ text = " ".join(parts[1:3])
+ for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f"):
+ try:
+ return datetime.strptime(text, fmt)
+ except ValueError:
+ continue
+ return None
+
+
+def parse_int_value(raw_value):
+ text = str(raw_value or "").strip()
+ if not text:
+ return None
+ try:
+ return int(text)
+ except Exception:
+ return None
+
+
+def parse_text_value(raw_value):
+ text = str(raw_value or "").strip()
+ return text or None
+
+
+def parse_bool_value(raw_value):
+ text = str(raw_value or "").strip().lower()
+ if text == "true":
+ return True
+ if text == "false":
+ return False
+ return None
+
+
+def format_local_iso_from_ms(timestamp_ms):
+ parsed = parse_int_value(timestamp_ms)
+ if parsed is None or parsed <= 0:
+ return None
+ try:
+ return datetime.fromtimestamp(parsed / 1000.0).strftime("%Y-%m-%dT%H:%M:%S")
+ except Exception:
+ return None
+
+
+def format_interval_human(seconds_value):
+ seconds = parse_int_value(seconds_value)
+ if seconds is None:
+ return None
+ if seconds <= 0:
+ return "0 min" if seconds == 0 else None
+ if seconds % 60 == 0:
+ minutes = seconds // 60
+ return f"{minutes} min"
+ return f"{seconds} sec"
+
+
+def normalize_timestamp_ms(raw_value):
+ parsed = parse_int_value(raw_value)
+ if parsed is None:
+ return None
+ if parsed == 0:
+ return 0
+ if abs(parsed) < 10 ** 11:
+ return parsed * 1000
+ return parsed
+
+
+def read_simple_key_value_file(path):
+ data = {}
+ try:
+ with open(path, "r", encoding="utf-8", errors="ignore") as fh:
+ for raw in fh:
+ line = raw.strip()
+ if not line or "=" not in line:
+ continue
+ if line.startswith("[") and line.endswith("]"):
+ continue
+ key, value = line.split("=", 1)
+ key = key.strip()
+ if not key:
+ continue
+ data[key] = value.strip()
+ except Exception:
+ return {}
+ return data
+
+
+def parse_itscreen_config_file(path):
+ if not os.path.exists(path):
+ return {"status": "not_installed"}
+ try:
+ raw = read_simple_key_value_file(path)
+ except Exception:
+ return {"status": "error", "message": "invalid config format"}
+ if not isinstance(raw, dict) or not raw:
+ return {"status": "error", "message": "invalid config format"}
+
+ interval_sec = parse_int_value(raw.get("updateInterval"))
+ last_update_ms = normalize_timestamp_ms(raw.get("lastUpdateTime"))
+ updated_at_sec = parse_int_value(raw.get("updatedAt"))
+ last_contact_ts = last_update_ms
+ if last_contact_ts is None and updated_at_sec is not None and updated_at_sec > 0:
+ last_contact_ts = updated_at_sec * 1000
+
+ next_contact_ts = None
+ if last_contact_ts is not None and interval_sec is not None:
+ next_contact_ts = last_contact_ts + (interval_sec * 1000)
+
+ next_shutdown_ts = normalize_timestamp_ms(raw.get("nextOffTime"))
+ next_startup_ts = normalize_timestamp_ms(raw.get("nextOnTime"))
+ if next_shutdown_ts == 0:
+ next_shutdown_ts = None
+ if next_startup_ts == 0:
+ next_startup_ts = None
+
+ return {
+ "registration": {
+ "registered": parse_bool_value(raw.get("isRegistered")),
+ "server": parse_text_value(raw.get("server")),
+ },
+ "sync": {
+ "interval_sec": interval_sec,
+ "interval_human": format_interval_human(interval_sec),
+ "last_contact_ts": last_contact_ts,
+ "last_contact_iso": format_local_iso_from_ms(last_contact_ts),
+ },
+ "schedule": {
+ "shutdown_enabled": parse_bool_value(raw.get("enableOffTime")),
+ "shutdown_time": parse_text_value(raw.get("strOffTime")),
+ "startup_enabled": parse_bool_value(raw.get("enableOnTime")),
+ "startup_time": parse_text_value(raw.get("strOnTime")),
+ "next_shutdown_ts": next_shutdown_ts,
+ "next_shutdown_iso": format_local_iso_from_ms(next_shutdown_ts),
+ "next_startup_ts": next_startup_ts,
+ "next_startup_iso": format_local_iso_from_ms(next_startup_ts),
+ },
+ "reboot": {
+ "enabled": parse_bool_value(raw.get("enableReboot")),
+ "repeat_enabled": parse_bool_value(raw.get("enableRebootRepeat")),
+ "repeat_interval": parse_int_value(raw.get("rebootRepeatTime")),
+ "daily_time": parse_text_value(raw.get("rebootTime")),
+ },
+ "meta": {
+ "updated_at_sec": updated_at_sec,
+ "startup_delay": parse_int_value(raw.get("startupDelay")),
+ },
+ }
+
+
+def read_itscreen_config_status():
+ now = time.time()
+ cached = _ITSCREEN_CONFIG_CACHE
+ if cached["payload"] is not None and cached["expires_at"] > now:
+ return cached["payload"]
+ payload = parse_itscreen_config_file(ITSCREEN_CONFIG_PATH)
+ cached["payload"] = payload
+ cached["expires_at"] = now + ITSCREEN_CONFIG_CACHE_TTL_SEC
+ return payload
+
+
+def get_itscreen_runtime_payload():
+ now = datetime.now()
+ payload = {
+ "current_time": now.strftime("%Y-%m-%d %H:%M:%S"),
+ "service_started_at": None,
+ "uptime_seconds": None,
+ "service_state": "unknown",
+ "registration": {
+ "registered": None,
+ "server": None,
+ },
+ "sync": {
+ "interval_sec": None,
+ "interval_human": None,
+ "last_contact_ts": None,
+ "last_contact_iso": None,
+ "next_contact_ts": None,
+ "next_contact_iso": None,
+ },
+ "schedule": {
+ "shutdown_enabled": None,
+ "shutdown_time": None,
+ "startup_enabled": None,
+ "startup_time": None,
+ "next_shutdown_ts": None,
+ "next_shutdown_iso": None,
+ "next_startup_ts": None,
+ "next_startup_iso": None,
+ },
+ "reboot": {
+ "enabled": None,
+ "repeat_enabled": None,
+ "repeat_interval": None,
+ "daily_time": None,
+ },
+ "meta": {
+ "updated_at_sec": None,
+ "startup_delay": None,
+ },
+ }
+ config_status = read_itscreen_config_status()
+ if isinstance(config_status, dict):
+ if config_status.get("status") == "not_installed":
+ return {"status": "not_installed"}
+ if config_status.get("status") == "error":
+ return {"status": "error", "message": "invalid config format"}
+ payload.update(config_status)
+ sync = payload.get("sync") or {}
+ payload["sync"]["next_contact_ts"] = (
+ sync.get("last_contact_ts") + (sync.get("interval_sec") * 1000)
+ if sync.get("last_contact_ts") is not None and sync.get("interval_sec") is not None
+ else None
+ )
+ payload["sync"]["next_contact_iso"] = format_local_iso_from_ms(payload["sync"]["next_contact_ts"])
+ try:
+ active_state = str(systemctl_show_property(ITSCREEN_SERVICE_UNIT, "ActiveState") or "").strip().lower()
+ if active_state in ("active", "inactive", "failed"):
+ payload["service_state"] = active_state
+ elif active_state:
+ payload["service_state"] = "unknown"
+ if payload["service_state"] != "active":
+ return payload
+ started_at = parse_systemctl_timestamp(systemctl_show_property(ITSCREEN_SERVICE_UNIT, "ActiveEnterTimestamp"))
+ if not started_at:
+ return payload
+ uptime_seconds = int(max(0, (now - started_at).total_seconds()))
+ payload["service_started_at"] = started_at.strftime("%Y-%m-%d %H:%M:%S")
+ payload["uptime_seconds"] = uptime_seconds
+ return payload
+ except Exception:
+ return payload
+
+
+def control_itscreen_service(action):
+ action_name = str(action or "").strip().lower()
+ if action_name not in ("start", "stop"):
+ raise ValueError("Unsupported action")
+ current = get_itscreen_service_status()
+ if not current.get("installed"):
+ raise RuntimeError("It-screen service is not installed")
+ rc, _, stderr = run(["systemctl", action_name, ITSCREEN_SERVICE_UNIT], timeout=20)
+ if rc != 0:
+ verb = "start" if action_name == "start" else "stop"
+ raise RuntimeError(f"Failed to {verb} service")
+ invalidate_cache()
+ return {
+ "ok": True,
+ "message": "Service started" if action_name == "start" else "Service stopped",
+ **build_itscreen_status_payload(),
+ }
+
+
+def clamp_itscreen_log_lines(value, default=ITSCREEN_LOG_DEFAULT_LINES):
+ try:
+ parsed = int(value)
+ except Exception:
+ parsed = default
+ return max(1, min(parsed, ITSCREEN_LOG_MAX_LINES))
+
+
+def read_itscreen_logs(lines):
+ count = clamp_itscreen_log_lines(lines)
+ if not shutil.which("journalctl"):
+ raise RuntimeError("journalctl is unavailable")
+ cmd = [
+ "journalctl",
+ "-u",
+ ITSCREEN_SERVICE_UNIT,
+ "-n",
+ str(count),
+ "--no-pager",
+ "-o",
+ "short-iso",
+ ]
+ try:
+ proc = subprocess.run(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ check=False,
+ timeout=10,
+ )
+ except FileNotFoundError as exc:
+ raise RuntimeError("journalctl is unavailable") from exc
+ except Exception as exc:
+ raise RuntimeError(str(exc)) from exc
+ if proc.returncode != 0:
+ raise RuntimeError((proc.stderr or "").strip() or "Failed to read service logs")
+ return {
+ "ok": True,
+ "unit": ITSCREEN_SERVICE_UNIT,
+ "lines": [line.rstrip("\n") for line in (proc.stdout or "").splitlines()],
+ }
+
+
+def terminate_process(proc):
+ if not proc:
+ return
+ try:
+ if proc.poll() is None:
+ proc.terminate()
+ proc.wait(timeout=2)
+ except Exception:
+ try:
+ proc.kill()
+ proc.wait(timeout=2)
+ except Exception:
+ pass
+ finally:
+ try:
+ if proc.stdout:
+ proc.stdout.close()
+ except Exception:
+ pass
+
+
def restart_service_card(service_id):
allowed_units = {
"zigbee2mqtt": "zigbee2mqtt.service",
@@ -1201,6 +1866,83 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(data)
+ def send_sse_headers(self):
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream; charset=utf-8")
+ self.send_header("Cache-Control", "no-store, no-cache, must-revalidate")
+ self.send_header("Pragma", "no-cache")
+ self.send_header("Connection", "keep-alive")
+ self.send_header("X-Accel-Buffering", "no")
+ self.end_headers()
+
+ def stream_itscreen_logs(self):
+ if not shutil.which("journalctl"):
+ self.send_json({"ok": False, "error": "Logs are unavailable"}, code=503)
+ return
+ proc = None
+ try:
+ proc = subprocess.Popen(
+ [
+ "journalctl",
+ "-u",
+ ITSCREEN_SERVICE_UNIT,
+ "-f",
+ "-n",
+ "0",
+ "--no-pager",
+ "-o",
+ "short-iso",
+ ],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ bufsize=1,
+ )
+ self.send_sse_headers()
+ self.wfile.write(b": connected\n\n")
+ self.wfile.flush()
+ last_keepalive_at = time.time()
+ while True:
+ if proc.poll() is not None:
+ stderr_text = ""
+ try:
+ stderr_text = (proc.stderr.read() or "").strip() if proc.stderr else ""
+ except Exception:
+ stderr_text = ""
+ if proc.returncode not in (0, None):
+ payload = json.dumps({"message": stderr_text or "Log stream disconnected"})
+ self.wfile.write(f"event: error\ndata: {payload}\n\n".encode("utf-8"))
+ self.wfile.flush()
+ break
+ ready = []
+ if proc.stdout:
+ try:
+ ready, _, _ = select.select([proc.stdout], [], [], 1.0)
+ except Exception:
+ ready = []
+ if not ready:
+ if time.time() - last_keepalive_at >= 15:
+ self.wfile.write(b": keepalive\n\n")
+ self.wfile.flush()
+ last_keepalive_at = time.time()
+ continue
+ line = proc.stdout.readline() if proc.stdout else ""
+ if not line:
+ continue
+ payload = json.dumps({"line": line.rstrip("\n")})
+ self.wfile.write(f"event: log\ndata: {payload}\n\n".encode("utf-8"))
+ self.wfile.flush()
+ last_keepalive_at = time.time()
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+ except Exception as exc:
+ try:
+ self.send_json({"ok": False, "error": str(exc)}, code=503)
+ except Exception:
+ pass
+ finally:
+ terminate_process(proc)
+
def handle_captive_portal_probe(self, parsed):
if not captive_portal_is_active():
return False
@@ -1223,6 +1965,7 @@ class Handler(BaseHTTPRequestHandler):
def do_GET(self):
parsed = urlparse(self.path)
+ query = parse_qs(parsed.query or "")
if self.handle_captive_portal_probe(parsed):
return
if parsed.path == "/api/status":
@@ -1265,6 +2008,45 @@ class Handler(BaseHTTPRequestHandler):
except Exception as exc:
self.send_json({"ok": False, "error": str(exc), "networks": []}, code=500)
return
+ if parsed.path == "/api/itscreen/status":
+ try:
+ self.send_json(build_itscreen_status_payload())
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ return
+ if parsed.path == "/api/itscreen/runtime":
+ try:
+ self.send_json(get_itscreen_runtime_payload())
+ except Exception as exc:
+ self.send_json({
+ "current_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
+ "service_started_at": None,
+ "uptime_seconds": None,
+ "service_state": "unknown",
+ "update_interval": None,
+ "last_contact_ts": None,
+ "next_contact_ts": None,
+ "enable_reboot": None,
+ "enable_reboot_repeat": None,
+ "reboot_repeat_time": None,
+ "reboot_time": None,
+ "enable_off_time": None,
+ "enable_on_time": None,
+ "next_off_time": None,
+ "next_on_time": None,
+ "error": str(exc),
+ })
+ return
+ if parsed.path == "/api/itscreen/logs":
+ try:
+ lines = clamp_itscreen_log_lines((query.get("lines") or [ITSCREEN_LOG_DEFAULT_LINES])[0])
+ self.send_json(read_itscreen_logs(lines))
+ except Exception as exc:
+ self.send_json({"ok": False, "error": "Logs are unavailable", "details": str(exc), "lines": []}, code=503)
+ return
+ if parsed.path == "/api/itscreen/logs/stream":
+ self.stream_itscreen_logs()
+ return
if parsed.path == "/api/itscreen/registration":
try:
self.send_json(get_registration_status())
@@ -1395,6 +2177,30 @@ class Handler(BaseHTTPRequestHandler):
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
+ if parsed.path == "/api/actions/audio-test":
+ 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(perform_audio_test(target))
+ except ValueError as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=400)
+ 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())
+ except RuntimeError as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ return
if parsed.path == "/api/itscreen/registration/register":
payload = self.read_json_body()
if payload is None:
@@ -1409,12 +2215,46 @@ class Handler(BaseHTTPRequestHandler):
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
+ if parsed.path == "/api/itscreen/register":
+ payload = self.read_json_body()
+ if payload is None:
+ self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
+ return
+ try:
+ self.send_json(register_device(str(payload.get("host", ""))))
+ 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=502)
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ return
if parsed.path == "/api/itscreen/registration/reset":
try:
self.send_json(reset_registration())
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
+ if parsed.path == "/api/itscreen/service/start":
+ try:
+ self.send_json(control_itscreen_service("start"))
+ 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=502)
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ return
+ if parsed.path == "/api/itscreen/service/stop":
+ try:
+ self.send_json(control_itscreen_service("stop"))
+ 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=502)
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ return
if parsed.path == "/api/service/restart":
payload = self.read_json_body()
if payload is None:
diff --git a/stage_ui/console_core/backend/itscreen_registration.py b/stage_ui/console_core/backend/itscreen_registration.py
index 0d5c876..ffd02c1 100644
--- a/stage_ui/console_core/backend/itscreen_registration.py
+++ b/stage_ui/console_core/backend/itscreen_registration.py
@@ -3,7 +3,6 @@ import json
import os
import queue
import re
-import socket
import threading
import time
from urllib.parse import urlparse
@@ -17,9 +16,10 @@ except Exception:
STATE_PATH = "/etc/iomatex/itscreen_registration.json"
MQTT_URL = os.environ.get("ITSCREEN_MQTT_URL", "mqtt://127.0.0.1:1883").strip() or "mqtt://127.0.0.1:1883"
LOGIN_PASSWORD = os.environ.get("ITSCREEN_DEVICE_PASSWORD", "eXXI0wkHBmNBnVbE").strip() or "eXXI0wkHBmNBnVbE"
-DEFAULT_SERVER = "rest.uae.iomatex.com"
REGISTER_TIMEOUT_SEC = 25
REPLY_TIMEOUT_SEC = 6
+PUBLISH_TIMEOUT_SEC = 2
+NOT_SPECIFIED = "Not specified"
HOST_RE = re.compile(r"^(?=.{1,253}$)(?!-)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.(?!-)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$")
DEVICE_ID_PATH = "/userdata/device-id"
DEVICE_ID_RE = re.compile(r"^g-box-[a-f0-9]{8}$")
@@ -56,12 +56,16 @@ def validate_host(host):
value = str(host or "").strip().lower()
if not value:
raise ValueError("Invalid server host")
+ if any(ch.isspace() for ch in value):
+ raise ValueError("Invalid server host")
if "://" in value:
raise ValueError("Invalid server host")
if "/" in value:
raise ValueError("Invalid server host")
if value.endswith("."):
value = value[:-1]
+ if value and not value.startswith("rest."):
+ value = f"rest.{value}"
if not HOST_RE.fullmatch(value):
raise ValueError("Invalid server host")
return value
@@ -70,12 +74,12 @@ def validate_host(host):
def _default_state():
identity = _device_identity()
return {
- "host": DEFAULT_SERVER,
+ "host": "",
"username": "",
"password": "",
"token": "",
"organization": "",
- "device_name": identity["device_name"],
+ "device_name": "",
"device_id": identity["device_id"],
"registered": False,
"logged": False,
@@ -103,8 +107,6 @@ def load_state():
pass
identity = _device_identity()
state["device_id"] = identity["device_id"]
- state["device_name"] = state.get("device_name") or identity["device_name"]
- state["host"] = state.get("host") or DEFAULT_SERVER
return state
@@ -112,12 +114,12 @@ def save_state(state):
os.makedirs(os.path.dirname(STATE_PATH), exist_ok=True)
safe = _default_state()
safe.update({
- "host": str(state.get("host", DEFAULT_SERVER) or DEFAULT_SERVER),
+ "host": str(state.get("host", "") or ""),
"username": str(state.get("username", "") or ""),
"password": str(state.get("password", "") or ""),
"token": str(state.get("token", "") or ""),
"organization": str(state.get("organization", "") or ""),
- "device_name": str(state.get("device_name", "") or _device_identity()["device_name"]),
+ "device_name": str(state.get("device_name", "") or ""),
"device_id": str(state.get("device_id", "") or _device_identity()["device_id"]),
"registered": bool(state.get("registered", False)),
"logged": bool(state.get("logged", False)),
@@ -157,6 +159,25 @@ def _truncate_empty(value):
return text
+def _text_or_default(value, default=NOT_SPECIFIED):
+ text = _truncate_empty(value)
+ return text or default
+
+
+def _bool_value(value, default=False):
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, str):
+ normalized = value.strip().lower()
+ if normalized in ("true", "1", "yes", "on"):
+ return True
+ if normalized in ("false", "0", "no", "off", ""):
+ return False
+ if value is None:
+ return default
+ return bool(value)
+
+
def _extract_response_payload(response_text):
raw = str(response_text or "").strip()
if not raw:
@@ -196,6 +217,56 @@ def _extract_registration_fields(server_state, event_payload, persisted):
return merged
+def _device_name_from_payload(payload):
+ if not isinstance(payload, dict):
+ return ""
+ for key in ("device_name", "name", "given_name", "display_name", "username"):
+ text = _truncate_empty(payload.get(key))
+ if text:
+ return text
+ return ""
+
+
+def _normalize_registration_payload(server_state, persisted=None, source="mqtt"):
+ payload = server_state if isinstance(server_state, dict) else {}
+ identity = _device_identity()
+ username = _text_or_default(payload.get("username"))
+ device_name = _device_name_from_payload(payload)
+ return {
+ "ok": True,
+ "source": source,
+ "device_id": identity["device_id"],
+ "device_name": _text_or_default(device_name),
+ "server": _text_or_default(payload.get("host")),
+ "host": _text_or_default(payload.get("host")),
+ "organization": _text_or_default(payload.get("organization")),
+ "token": _text_or_default(payload.get("token")),
+ "registered": _bool_value(payload.get("registered"), default=False),
+ "logged": _bool_value(payload.get("logged"), default=False),
+ "password_state": "Password set" if _truncate_empty(payload.get("password")) else NOT_SPECIFIED,
+ "username": username,
+ "status": "ready" if _bool_value(payload.get("registered"), default=False) else "not_registered",
+ "last_event": (persisted or {}).get("last_event", {
+ "action": "",
+ "operation": "",
+ "status": "",
+ "timestamp": "",
+ }),
+ "raw": dict(payload),
+ }
+
+
+def _public_error(exc):
+ text = _truncate_empty(str(exc))
+ if isinstance(exc, TimeoutError):
+ return "It-screen status is unavailable", "MQTT response timeout"
+ if text == "Invalid MQTT payload":
+ return "It-screen status is unavailable", "Invalid MQTT payload"
+ if text:
+ return "It-screen status is unavailable", text
+ return "It-screen status is unavailable", "Unknown backend error"
+
+
class MqttSettingsSession:
def __init__(self, device_id):
if mqtt is None:
@@ -229,7 +300,7 @@ class MqttSettingsSession:
try:
payload = json.loads(raw)
except Exception:
- payload = {"raw": raw}
+ payload = {"__invalid_json__": raw}
self.queue.put(payload)
def __enter__(self):
@@ -267,7 +338,11 @@ class MqttSettingsSession:
def publish(self, payload):
self._drain()
result = self.client.publish(self.topics["sub"], json.dumps(payload), qos=0, retain=False)
- result.wait_for_publish(timeout=2)
+ deadline = time.time() + PUBLISH_TIMEOUT_SEC
+ while time.time() < deadline:
+ if result.is_published():
+ return
+ time.sleep(0.05)
if not result.is_published():
raise RuntimeError("MQTT publish failed")
@@ -281,19 +356,31 @@ class MqttSettingsSession:
candidate = self.queue.get(timeout=0.25)
except queue.Empty:
continue
+ if isinstance(candidate, dict) and candidate.get("__invalid_json__") is not None:
+ raise RuntimeError("Invalid MQTT payload")
if predicate(candidate):
return candidate
raise TimeoutError("No response from device")
def login(self):
- reply = self.publish_and_wait(
- {"action": "login", "password": LOGIN_PASSWORD},
- lambda item: isinstance(item, dict) and item.get("action") == "login",
- timeout=REPLY_TIMEOUT_SEC,
- )
- if not reply.get("result"):
- raise RuntimeError(reply.get("note") or reply.get("error") or "Login failed")
- return reply
+ self.publish({"action": "login", "password": LOGIN_PASSWORD})
+ deadline = time.time() + 1.0
+ while time.time() < deadline:
+ try:
+ candidate = self.queue.get(timeout=0.1)
+ except queue.Empty:
+ continue
+ if isinstance(candidate, dict) and candidate.get("__invalid_json__") is not None:
+ raise RuntimeError("Invalid MQTT payload")
+ if not isinstance(candidate, dict):
+ continue
+ if candidate.get("action") != "login":
+ continue
+ if candidate.get("result") is False:
+ raise RuntimeError(candidate.get("note") or candidate.get("error") or "Login failed")
+ if candidate.get("result") is True:
+ return True
+ return True
def get_server_state(self):
return self.publish_and_wait(
@@ -333,25 +420,9 @@ class MqttSettingsSession:
def _build_public_status(state, error_text=""):
- output = {
- "ok": True,
- "registered": bool(state.get("registered", False)),
- "logged": bool(state.get("logged", False)),
- "host": _truncate_empty(state.get("host")) or DEFAULT_SERVER,
- "username": _truncate_empty(state.get("username")),
- "password": _truncate_empty(state.get("password")),
- "token": _truncate_empty(state.get("token")) or None,
- "organization": _truncate_empty(state.get("organization")) or None,
- "device_name": _truncate_empty(state.get("device_name")) or _device_identity()["device_name"],
- "device_id": _device_identity()["device_id"],
- "status": _truncate_empty(state.get("status")) or "idle",
- "last_event": state.get("last_event", {
- "action": "",
- "operation": "",
- "status": "",
- "timestamp": "",
- }),
- }
+ normalized = _normalize_registration_payload(state, persisted=state)
+ normalized["status"] = _truncate_empty(state.get("status")) or normalized.get("status") or "idle"
+ output = dict(normalized)
if error_text:
output["error"] = error_text
return output
@@ -364,15 +435,36 @@ def get_registration_status():
with MqttSettingsSession(state["device_id"]) as session:
session.login()
server_state = session.get_server_state()
- state = _extract_registration_fields(server_state, {}, state)
- state["logged"] = bool(server_state.get("logged"))
- state["registered"] = bool(server_state.get("registered"))
- state["status"] = "ready" if state["registered"] else "not_registered"
- save_state(state)
- return _build_public_status(state)
+ current = {
+ "host": _truncate_empty(server_state.get("host")),
+ "username": _truncate_empty(server_state.get("username")),
+ "password": _truncate_empty(server_state.get("password")),
+ "token": _truncate_empty(server_state.get("token")),
+ "organization": _truncate_empty(server_state.get("organization")),
+ "device_name": _device_name_from_payload(server_state),
+ "device_id": _device_identity()["device_id"],
+ "registered": _bool_value(server_state.get("registered"), default=False),
+ "logged": _bool_value(server_state.get("logged"), default=False),
+ "status": "ready" if _bool_value(server_state.get("registered"), default=False) else "not_registered",
+ "last_event": persisted.get("last_event", {
+ "action": "",
+ "operation": "",
+ "status": "",
+ "timestamp": "",
+ }),
+ }
+ save_state(current)
+ return _build_public_status(current)
except Exception as exc:
state["status"] = "error" if persisted.get("status") != "registering" else persisted.get("status")
- return _build_public_status(state, str(exc))
+ fallback = _build_public_status(state)
+ error_text, details = _public_error(exc)
+ return {
+ "ok": False,
+ "error": error_text,
+ "details": details,
+ "data": fallback,
+ }
def register_device(host):
@@ -386,7 +478,9 @@ def register_device(host):
try:
with MqttSettingsSession(working["device_id"]) as session:
session.login()
- session.get_server_state()
+ 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)
event = session.wait_registered_event()
event_payload = _extract_response_payload(event.get("responseText"))
diff --git a/stage_ui/console_core/frontend/console.css b/stage_ui/console_core/frontend/console.css
index 5926629..f15f7b9 100644
--- a/stage_ui/console_core/frontend/console.css
+++ b/stage_ui/console_core/frontend/console.css
@@ -7,15 +7,58 @@
--accent:#0e7a53;
--warn:#9a6a00;
--error:#b93434;
+ --surface-soft:#fbfcfb;
+ --surface-muted:#f5f7f6;
+ --surface-strong:#edf4f0;
+ --bg-top:#f7faf8;
+ --surface-empty:rgba(255,255,255,.6);
+ --surface-connected:rgba(14,122,83,.08);
+ --surface-idle:#f7f8f7;
+ --button-primary:#16211d;
+ --button-primary-hover:#22302b;
+ --button-secondary:#eef3f1;
+ --button-secondary-hover:#e4ece8;
+ --button-danger:#7a1f1f;
+ --button-danger-hover:#632020;
+ --log-bg:#0f1714;
+ --log-ink:#d9e4de;
+ --log-empty:#93a39a;
--shadow:0 12px 32px rgba(16,24,20,.08);
}
+[data-theme="dark"]{
+ --bg:#0f1513;
+ --panel:#16211d;
+ --ink:#eef5f1;
+ --muted:#9cac9f;
+ --line:#2a3833;
+ --accent:#46c48d;
+ --warn:#f0bc4f;
+ --error:#ff7f7f;
+ --surface-soft:#1a2622;
+ --surface-muted:#1d2b26;
+ --surface-strong:#21312b;
+ --bg-top:#18211e;
+ --surface-empty:rgba(22,33,29,.78);
+ --surface-connected:rgba(70,196,141,.12);
+ --surface-idle:#1a2521;
+ --button-primary:#46c48d;
+ --button-primary-hover:#59d89f;
+ --button-secondary:#21312b;
+ --button-secondary-hover:#294038;
+ --button-danger:#c44b4b;
+ --button-danger-hover:#d55f5f;
+ --log-bg:#0b1110;
+ --log-ink:#d8e6df;
+ --log-empty:#86968e;
+ --shadow:0 16px 40px rgba(0,0,0,.28);
+}
*{box-sizing:border-box}
body{
margin:0;
font-family:system-ui,-apple-system,"Segoe UI",sans-serif;
background:
radial-gradient(circle at top left, rgba(14,122,83,.10), transparent 32%),
- linear-gradient(180deg, #f7faf8 0%, var(--bg) 100%);
+ linear-gradient(180deg, var(--bg-top) 0%, var(--bg) 100%);
color:var(--ink);
}
.shell{max-width:1180px;margin:0 auto;padding:28px 18px 40px}
@@ -57,18 +100,119 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
padding-top:6px;
}
.identityItem strong{font-size:15px}
+.hero{
+ grid-template-columns:minmax(0,1.7fr) minmax(280px,.95fr) auto;
+ align-items:start;
+}
.actions{
+ position:static;
+ min-width:0;
+ padding-top:0;
+}
+.menuToggleBtn{
+ position:fixed;
+ top:18px;
+ right:18px;
+ width:42px;
+ height:42px;
+ min-width:42px;
+ padding:0;
+ border:1px solid var(--line);
+ border-radius:14px;
+ background:var(--surface-soft);
+ color:var(--ink);
+ display:inline-flex;
+ flex-direction:column;
+ align-items:center;
+ justify-content:center;
+ gap:4px;
+ cursor:pointer;
+ box-shadow:var(--shadow);
+ z-index:90;
+}
+.menuToggleBtn span{
+ width:16px;
+ height:2px;
+ border-radius:999px;
+ background:currentColor;
+ display:block;
+}
+.menuToggleBtn.is-open{
+ background:var(--surface-strong);
+}
+.actionMenu{
+ position:fixed;
+ top:68px;
+ right:18px;
+ width:min(240px,calc(100vw - 32px));
+ display:grid;
+ gap:6px;
+ padding:10px;
+ border:1px solid var(--line);
+ border-radius:16px;
+ background:var(--panel);
+ box-shadow:var(--shadow);
+ z-index:85;
+}
+.actionMenu[hidden]{
+ display:none !important;
+}
+.menuActionBtn{
+ width:100%;
+ border:0;
+ border-radius:12px;
+ background:transparent;
+ color:var(--ink);
+ padding:10px 12px;
display:flex;
align-items:center;
- justify-content:flex-end;
- gap:12px;
- flex-wrap:wrap;
+ justify-content:flex-start;
+ gap:10px;
+ text-align:left;
+ cursor:pointer;
+ font:inherit;
+ font-weight:600;
}
-.actions button{
- border:0;border-radius:999px;background:var(--ink);color:#fff;padding:12px 18px;font-weight:700;cursor:pointer;
- box-shadow:var(--shadow);
+.menuActionBtn:hover:not(:disabled){
+ background:var(--surface-soft);
}
-.actions button,
+.menuActionBtn.is-danger{
+ color:var(--error);
+}
+.menuActionBtn.is-danger:hover:not(:disabled){
+ background:rgba(185,52,52,.10);
+}
+.menuActionIcon{
+ width:18px;
+ height:18px;
+ display:inline-flex;
+ align-items:center;
+ justify-content:center;
+ flex:0 0 18px;
+}
+.menuActionIcon svg{
+ width:18px;
+ height:18px;
+ fill:none;
+ stroke:currentColor;
+ stroke-width:1.8;
+ stroke-linecap:round;
+ stroke-linejoin:round;
+}
+.menuActionLabel{
+ flex:1 1 auto;
+}
+.menuBackdrop{
+ position:fixed;
+ inset:0;
+ background:rgba(9,13,12,.14);
+ z-index:80;
+}
+.menuBackdrop[hidden]{
+ display:none !important;
+}
+.menuToggleBtn,
+.menuActionBtn,
.tabBtn,
.actionBtn,
.toggleInlineBtn,
@@ -76,20 +220,23 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.field input{
transition:background-color .16s ease,border-color .16s ease,color .16s ease,box-shadow .16s ease,transform .06s ease,opacity .16s ease;
}
-.actions button:hover,
+.menuToggleBtn:hover,
+.menuActionBtn:hover:not(:disabled),
.actionBtn:hover:not(:disabled),
.tabBtn:hover:not(:disabled),
.toggleInlineBtn:hover:not(:disabled){
box-shadow:0 10px 24px rgba(16,24,20,.10);
}
-.actions button:active,
+.menuToggleBtn:active,
+.menuActionBtn:active:not(:disabled),
.actionBtn:active:not(:disabled),
.tabBtn:active:not(:disabled),
.toggleInlineBtn:active:not(:disabled),
.scanRow:active{
transform:translateY(1px);
}
-.actions button:focus-visible,
+.menuToggleBtn:focus-visible,
+.menuActionBtn:focus-visible,
.tabBtn:focus-visible,
.actionBtn:focus-visible,
.toggleInlineBtn:focus-visible,
@@ -105,14 +252,14 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
display:flex;gap:10px;flex-wrap:wrap;margin-bottom:18px;
}
.tabBtn{
- border:1px solid var(--line);background:rgba(255,255,255,.8);color:var(--ink);
+ border:1px solid var(--line);background:var(--surface-soft);color:var(--ink);
border-radius:999px;padding:10px 16px;font-size:14px;font-weight:700;cursor:pointer;
}
.tabBtn.is-active{
- background:var(--ink);color:#fff;border-color:var(--ink);
+ background:var(--button-primary);color:#fff;border-color:var(--button-primary);
}
.tabBtn:hover:not(.is-active):not(:disabled){
- background:#f7faf8;border-color:#bfd0c8;
+ background:var(--surface-soft);border-color:var(--line);
}
.tabContent{display:grid;gap:18px}
.tabPanel{display:grid;gap:18px}
@@ -130,15 +277,15 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
padding:12px 14px;
border-radius:14px;
box-shadow:var(--shadow);
- background:#ffffff;
+ background:var(--panel);
border:1px solid var(--line);
color:var(--ink);
font-size:13px;
transition:opacity .2s ease,transform .2s ease;
}
-.toast.success{border-color:rgba(14,122,83,.22);background:#f2faf6}
-.toast.error{border-color:rgba(185,52,52,.22);background:#fff4f4}
-.toast.warn{border-color:rgba(154,106,0,.24);background:#fff8ec}
+.toast.success{border-color:rgba(14,122,83,.22);background:rgba(14,122,83,.10)}
+.toast.error{border-color:rgba(185,52,52,.22);background:rgba(185,52,52,.10)}
+.toast.warn{border-color:rgba(154,106,0,.24);background:rgba(154,106,0,.10)}
.toast.is-leaving{opacity:0;transform:translateY(8px)}
.sectionHead{display:flex;justify-content:space-between;gap:12px;align-items:flex-end;flex-wrap:wrap}
.sectionHead h2{margin:0;font-size:22px}
@@ -147,6 +294,10 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.cards{
display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px;
}
+.itscreenCards{
+ grid-template-columns:repeat(2,minmax(0,1fr));
+ align-items:start;
+}
.wideCard{grid-column:span 2}
.card{padding:18px}
.cards > .card{height:100%}
@@ -156,7 +307,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.cardSubtitle{margin:6px 0 0;color:var(--muted);font-size:13px}
.badge{
display:inline-flex;align-items:center;gap:8px;border-radius:999px;padding:7px 10px;font-size:12px;font-weight:700;
- background:#edf4f0;color:var(--ink);
+ background:var(--surface-strong);color:var(--ink);
}
.dot{width:9px;height:9px;border-radius:50%}
.dot.ok{background:var(--accent)}
@@ -188,7 +339,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.listTitle{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);margin-bottom:8px}
.pillRow{display:flex;gap:8px;flex-wrap:wrap}
.pill{
- display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;font-size:12px;font-weight:700;background:#f5f7f6;color:var(--ink);
+ display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;font-size:12px;font-weight:700;background:var(--surface-muted);color:var(--ink);
}
.pill.good{background:rgba(14,122,83,.10);color:var(--accent)}
.pill.bad{background:rgba(185,52,52,.10);color:var(--error)}
@@ -202,7 +353,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.tunnelSummaryItem{
border:1px solid var(--line);
border-radius:12px;
- background:#fbfcfb;
+ background:var(--surface-soft);
padding:10px 12px;
display:grid;
gap:4px;
@@ -224,7 +375,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.tunnelAccordion{
border:1px solid var(--line);
border-radius:14px;
- background:#fbfcfb;
+ background:var(--surface-soft);
overflow:hidden;
}
.tunnelAccordionToggle{
@@ -241,7 +392,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
cursor:pointer;
font:inherit;
}
-.tunnelAccordionToggle:hover{background:#f3f7f5}
+.tunnelAccordionToggle:hover{background:var(--surface-muted)}
.tunnelAccordionLabel{font-size:13px;font-weight:700}
.connectorSummaryText{
margin-left:auto;
@@ -312,7 +463,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
}
.msgList{margin:8px 0 0;padding-left:18px;color:var(--muted)}
.empty{
- padding:32px;border:1px dashed var(--line);border-radius:18px;background:rgba(255,255,255,.6);color:var(--muted);text-align:center;
+ padding:32px;border:1px dashed var(--line);border-radius:18px;background:var(--surface-empty);color:var(--muted);text-align:center;
}
.emptyInline{color:var(--muted);font-size:14px}
.displayCard,.accessPointCard{grid-column:span 2}
@@ -320,14 +471,14 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
margin-top:16px;padding:16px 18px;border-radius:16px;border:1px solid var(--line);
display:flex;justify-content:space-between;gap:14px;align-items:flex-start;flex-wrap:wrap;
}
-.displayHero.is-connected,.apHero.is-enabled{background:rgba(14,122,83,.08)}
-.displayHero.is-empty,.apHero.is-disabled{background:#f7f8f7}
+.displayHero.is-connected,.apHero.is-enabled{background:var(--surface-connected)}
+.displayHero.is-empty,.apHero.is-disabled{background:var(--surface-idle)}
.apExplanation{
margin-top:14px;
padding:14px 16px;
border:1px solid var(--line);
border-radius:14px;
- background:#fbfcfb;
+ background:var(--surface-soft);
}
.apExplanation p{
margin:8px 0 0;
@@ -347,7 +498,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.networkInterfaceBlock{
border:1px solid var(--line);
border-radius:14px;
- background:#fbfcfb;
+ background:var(--surface-soft);
padding:14px;
}
.networkInterfaceHead{
@@ -397,7 +548,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
border:1px solid var(--line);
border-radius:14px;
padding:14px;
- background:#fbfcfb;
+ background:var(--surface-soft);
}
.manualSteps{
margin:10px 0 0;
@@ -408,18 +559,83 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.manualNotes{margin-top:10px}
.connectorList{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px}
.connectorListCompact{gap:10px}
-.connectorCard{border:1px solid var(--line);border-radius:14px;padding:11px 12px;background:#fbfcfb}
+.connectorCard{border:1px solid var(--line);border-radius:14px;padding:11px 12px;background:var(--surface-soft)}
.connectorHead{display:flex;justify-content:space-between;gap:10px;align-items:flex-start;margin-bottom:8px}
.connectorSubhead{margin-top:3px;color:var(--muted);font-size:12px}
.connectorState{font-size:12px;font-weight:700;border-radius:999px;padding:6px 10px}
.connectorState.is-connected{background:rgba(14,122,83,.10);color:var(--accent)}
.connectorState.is-idle{background:rgba(154,106,0,.10);color:var(--warn)}
+.connectorState.is-error{background:rgba(185,52,52,.10);color:var(--error)}
.connectorMeta{
margin-top:0;
grid-template-columns:110px 1fr;
gap:6px 10px;
font-size:12px;
}
+.audioDeviceGrid{
+ display:grid;
+ grid-template-columns:repeat(2,minmax(0,1fr));
+ gap:12px;
+ margin-top:12px;
+}
+.audioDeviceCard,
+.audioParamsCard{
+ border:1px solid var(--line);
+ border-radius:14px;
+ background:var(--surface-soft);
+ padding:14px;
+}
+.audioDeviceHead{
+ display:flex;
+ justify-content:space-between;
+ gap:10px;
+ align-items:flex-start;
+ flex-wrap:wrap;
+}
+.audioDeviceSubhead{
+ margin-top:4px;
+ color:var(--muted);
+ font-size:12px;
+}
+.audioDeviceMeta{
+ margin-top:6px;
+ color:var(--muted);
+ font-size:12px;
+}
+.audioActionRow{
+ display:flex;
+ gap:10px;
+ align-items:center;
+ flex-wrap:wrap;
+ margin-top:12px;
+}
+.audioTestSummary{
+ display:flex;
+ gap:8px;
+ align-items:center;
+ flex-wrap:wrap;
+ margin-top:12px;
+}
+.audioTestTime{
+ color:var(--muted);
+ font-size:12px;
+}
+.diagBlock{
+ margin:0;
+ padding:10px 12px;
+ border:1px solid var(--line);
+ border-radius:12px;
+ background:var(--panel);
+ color:var(--ink);
+ font-family:ui-monospace,SFMono-Regular,Menlo,monospace;
+ font-size:12px;
+ line-height:1.45;
+ white-space:pre-wrap;
+ word-break:break-word;
+}
+.testOutput{
+ margin-top:12px;
+}
.modeBadge{
display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;font-size:12px;font-weight:700;
}
@@ -430,22 +646,31 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
border:0;border-radius:12px;background:var(--ink);color:#fff;padding:10px 14px;font-weight:700;cursor:pointer;
display:inline-flex;align-items:center;justify-content:center;text-decoration:none;
}
-.actionBtn:hover:not(:disabled){background:#22302b}
-.actionBtn.secondary{background:#eef3f1;color:var(--ink);border:1px solid var(--line)}
-.actionBtn.secondary:hover:not(:disabled){background:#e4ece8}
+.actionBtn{background:var(--button-primary)}
+.actionBtn:hover:not(:disabled){background:var(--button-primary-hover)}
+.actionBtn.secondary{background:var(--button-secondary);color:var(--ink);border:1px solid var(--line)}
+.actionBtn.secondary:hover:not(:disabled){background:var(--button-secondary-hover)}
.actionBtn:disabled{opacity:.5;cursor:not-allowed}
.serviceActionRow{align-items:center}
.actionBadge{
display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;
- background:#edf3f1;color:var(--muted);font-size:12px;font-weight:700;
+ background:var(--surface-strong);color:var(--muted);font-size:12px;font-weight:700;
}
+.actionBadge-ok{color:var(--accent)}
+.actionBadge-warn{color:var(--warn)}
+.actionBadge-error{color:var(--error)}
.apForm{display:grid;gap:12px}
.field{display:grid;gap:6px;font-size:13px;color:var(--ink)}
.field input{
- width:100%;padding:10px 12px;border-radius:12px;border:1px solid var(--line);background:#fff;color:var(--ink);
+ width:100%;padding:10px 12px;border-radius:12px;border:1px solid var(--line);background:var(--panel);color:var(--ink);
}
-.field input:hover{border-color:#bfd0c8}
+.field select{
+ width:100%;padding:10px 12px;border-radius:12px;border:1px solid var(--line);background:var(--panel);color:var(--ink);
+}
+.field input:hover{border-color:var(--line)}
+.field select:hover{border-color:var(--line)}
.field input:focus-visible{border-color:var(--accent)}
+.field select:focus-visible{border-color:var(--accent)}
.wrapValue{
display:flex;
align-items:center;
@@ -470,7 +695,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
padding:12px 14px;
border:1px solid var(--line);
border-radius:14px;
- background:#fbfcfb;
+ background:var(--surface-soft);
}
.choiceRow input{margin-top:3px}
.choiceRow span{font-weight:700}
@@ -483,9 +708,9 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.passwordField{display:flex;gap:8px;align-items:center}
.passwordField input{flex:1 1 auto}
.toggleInlineBtn{
- border:1px solid var(--line);border-radius:12px;background:#f6f8f7;color:var(--ink);padding:10px 12px;font-weight:700;cursor:pointer;white-space:nowrap;
+ border:1px solid var(--line);border-radius:12px;background:var(--surface-muted);color:var(--ink);padding:10px 12px;font-weight:700;cursor:pointer;white-space:nowrap;
}
-.toggleInlineBtn:hover:not(:disabled){background:#edf3f0}
+.toggleInlineBtn:hover:not(:disabled){background:var(--surface-strong)}
.formHint{font-size:12px;color:var(--muted)}
.formError{font-size:12px;color:var(--error);font-weight:600}
.banner{
@@ -501,9 +726,9 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
}
.scanRow{
display:flex;justify-content:space-between;gap:12px;align-items:center;
- border:1px solid var(--line);border-radius:12px;background:#fbfcfb;padding:12px 14px;
+ border:1px solid var(--line);border-radius:12px;background:var(--surface-soft);padding:12px 14px;
}
-.scanRow:hover{background:#f4f8f6;border-color:#bfd0c8}
+.scanRow:hover{background:var(--surface-muted);border-color:var(--line)}
.scanMain{display:grid;gap:6px;min-width:0}
.scanTopLine{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.scanSsid{font-weight:700}
@@ -514,7 +739,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
display:inline-flex;align-items:center;border-radius:999px;padding:4px 8px;font-size:11px;font-weight:700;
}
.scanActiveBadge{background:rgba(14,122,83,.10);color:var(--accent)}
-.scanHiddenBadge{background:#edf3f1;color:var(--muted)}
+.scanHiddenBadge{background:var(--surface-strong);color:var(--muted)}
.scanSignalRow{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
.scanSignalText{font-size:13px;color:var(--muted)}
.signalBars{display:inline-flex;align-items:flex-end;gap:3px;height:16px}
@@ -531,6 +756,86 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
width:10px;height:10px;border-radius:50%;background:var(--accent);display:inline-block;
animation:pulse 1s ease-in-out infinite;
}
+.itscreenLogsCard{
+ display:grid;
+ gap:14px;
+ grid-column:1 / -1;
+}
+.itscreenLogsToolbar{
+ display:grid;
+ grid-template-columns:minmax(220px,1fr) auto auto;
+ gap:12px;
+ align-items:end;
+}
+.itscreenLogsSearchField{margin:0}
+.itscreenLogsActions{
+ display:flex;
+ gap:10px;
+ flex-wrap:wrap;
+ justify-content:flex-end;
+}
+.itscreenLogsToggle{
+ display:inline-flex;
+ align-items:center;
+ gap:8px;
+ align-self:center;
+ padding:10px 12px;
+ border:1px solid var(--line);
+ border-radius:12px;
+ background:var(--surface-soft);
+ font-size:13px;
+ font-weight:600;
+}
+.itscreenLogsToggle input{margin:0}
+.itscreenLogsSummary{
+ display:flex;
+ justify-content:space-between;
+ gap:10px;
+ align-items:center;
+ flex-wrap:wrap;
+}
+.logStatus{
+ display:inline-flex;
+ align-items:center;
+ border-radius:999px;
+ padding:6px 10px;
+ font-size:12px;
+ font-weight:700;
+}
+.logStatus-ok{background:rgba(14,122,83,.10);color:var(--accent)}
+.logStatus-warn{background:rgba(154,106,0,.10);color:var(--warn)}
+.logStatus-error{background:rgba(185,52,52,.10);color:var(--error)}
+.itscreenLogsCount{
+ color:var(--muted);
+ font-size:12px;
+}
+.itscreenLogsBody{
+ min-height:340px;
+ max-height:420px;
+ overflow:auto;
+ padding:12px 14px;
+ border:1px solid var(--line);
+ border-radius:14px;
+ background:var(--log-bg);
+ color:var(--log-ink);
+ font-family:ui-monospace,SFMono-Regular,Menlo,monospace;
+ font-size:12px;
+ line-height:1.45;
+}
+.logLine{
+ white-space:pre-wrap;
+ word-break:break-word;
+}
+.logLine + .logLine{margin-top:4px}
+.itscreenLogsBody mark{
+ background:rgba(255,214,102,.35);
+ color:#fff4cc;
+ padding:0 1px;
+ border-radius:3px;
+}
+.logEmpty{
+ color:var(--log-empty);
+}
@keyframes pulse{
0%,100%{opacity:.35;transform:scale(.9)}
50%{opacity:1;transform:scale(1)}
@@ -539,6 +844,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.hero{grid-template-columns:1fr}
.identityPanel{min-width:0}
.gboxHero{grid-template-columns:1fr}
+ .itscreenCards{grid-template-columns:repeat(2,minmax(0,1fr))}
}
@media (max-width:720px){
.meta{grid-template-columns:1fr 1fr}
@@ -549,9 +855,22 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.tunnelSummaryGrid{grid-template-columns:repeat(2,minmax(0,1fr))}
.brandDevice{width:min(70vw, 260px);max-height:180px}
.wideCard,.displayCard,.accessPointCard{grid-column:auto}
+ .audioDeviceGrid{grid-template-columns:1fr}
.displayHeroText{font-size:18px}
+ .itscreenCards{grid-template-columns:1fr}
+ .itscreenLogsToolbar{grid-template-columns:1fr}
+ .itscreenLogsActions{justify-content:flex-start}
}
@media (max-width:680px){
+ .menuToggleBtn{
+ top:16px;
+ right:16px;
+ }
+ .actionMenu{
+ top:64px;
+ right:16px;
+ width:min(240px,calc(100vw - 24px));
+ }
.connectorSummaryText{
width:100%;
margin-left:0;
diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js
index d5bb117..d5b01ed 100644
--- a/stage_ui/console_core/frontend/console.js
+++ b/stage_ui/console_core/frontend/console.js
@@ -2,7 +2,13 @@
"use strict";
const nodes = {
+ menuToggleBtn: document.getElementById("menuToggleBtn"),
+ actionMenu: document.getElementById("actionMenu"),
+ menuBackdrop: document.getElementById("menuBackdrop"),
refreshBtn: document.getElementById("refreshBtn"),
+ rebootBtn: document.getElementById("rebootBtn"),
+ themeToggleBtn: document.getElementById("themeToggleBtn"),
+ themeToggleIcon: document.getElementById("themeToggleIcon"),
tabs: Array.from(document.querySelectorAll("[data-tab]")),
edgeId: document.getElementById("edgeId"),
hostName: document.getElementById("hostName"),
@@ -12,6 +18,17 @@
toastStack: document.getElementById("toastStack")
};
+ const ITSCREEN_SERVER_OPTIONS = [
+ { mode: "dev", label: "DEV", host: "rest.dev.it-screen.com" },
+ { mode: "uae", label: "UAE", host: "rest.uae.iomatex.com" },
+ { mode: "public_by", label: "PUBLIC BY", host: "rest.public.it-screen.by" },
+ { mode: "test_by", label: "TEST BY", host: "rest.test.it-screen.by" },
+ { mode: "custom", label: "Custom", host: "" }
+ ];
+ const ITSCREEN_LOG_INITIAL_LINES = 50;
+ const ITSCREEN_LOG_BUFFER_LIMIT = 300;
+ const ITSCREEN_LOG_BATCH_MS = 250;
+
const state = {
activeTab: "health",
status: null,
@@ -21,11 +38,32 @@
loading: false,
busyAction: "",
data: null,
+ runtime: null,
error: "",
+ details: "",
+ message: "",
serverMode: "uae",
customHost: "",
- showPassword: false,
- focused: false
+ focused: false,
+ loadedAt: 0,
+ request: null,
+ logs: {
+ buffer: [],
+ queue: [],
+ request: null,
+ eventSource: null,
+ flushTimer: null,
+ search: "",
+ autoScroll: true,
+ paused: false,
+ status: "disconnected",
+ error: "",
+ available: true,
+ bootstrapped: false,
+ followingBottom: true,
+ viewportOffsetFromBottom: 0,
+ forceScroll: false
+ }
},
scan: { ok: true, networks: [], error: "", warning: "", message: "", loading: false, scannedAt: "", expanded: false, lastTriggeredAt: 0 },
networkForm: {
@@ -47,6 +85,13 @@
reverseTunnelUi: {
openGroups: {}
},
+ theme: "light",
+ audioActions: {
+ busyTarget: "",
+ results: {}
+ },
+ menuOpen: false,
+ rebootPending: false,
isPolling: false
};
@@ -85,6 +130,76 @@
return text || fallback;
}
+ function loadThemePreference() {
+ try {
+ const saved = window.localStorage.getItem("consoleTheme");
+ if (saved === "dark" || saved === "light") return saved;
+ } catch (error) {}
+ return document.documentElement.getAttribute("data-theme") === "dark" ? "dark" : "light";
+ }
+
+ function renderThemeIcon(theme) {
+ if (theme === "dark") {
+ return `
+
+ `;
+ }
+ return `
+
+ `;
+ }
+
+ function syncActionMenu() {
+ const isOpen = !!state.menuOpen;
+ if (nodes.actionMenu) nodes.actionMenu.hidden = !isOpen;
+ if (nodes.menuBackdrop) nodes.menuBackdrop.hidden = !isOpen;
+ if (nodes.menuToggleBtn) {
+ nodes.menuToggleBtn.setAttribute("aria-expanded", isOpen ? "true" : "false");
+ nodes.menuToggleBtn.setAttribute("title", isOpen ? "Close menu" : "Open menu");
+ nodes.menuToggleBtn.classList.toggle("is-open", isOpen);
+ }
+ }
+
+ function closeActionMenu() {
+ if (!state.menuOpen) return;
+ state.menuOpen = false;
+ syncActionMenu();
+ }
+
+ function toggleActionMenu() {
+ state.menuOpen = !state.menuOpen;
+ syncActionMenu();
+ }
+
+ function applyTheme(theme) {
+ state.theme = theme === "dark" ? "dark" : "light";
+ document.documentElement.setAttribute("data-theme", state.theme);
+ try {
+ window.localStorage.setItem("consoleTheme", state.theme);
+ } catch (error) {}
+ if (nodes.themeToggleBtn) {
+ nodes.themeToggleBtn.setAttribute("aria-label", "Switch theme");
+ nodes.themeToggleBtn.setAttribute("title", "Switch theme");
+ nodes.themeToggleBtn.setAttribute("aria-pressed", state.theme === "dark" ? "true" : "false");
+ }
+ if (nodes.themeToggleIcon) {
+ nodes.themeToggleIcon.innerHTML = renderThemeIcon(state.theme);
+ }
+ }
+
+ function toggleTheme() {
+ applyTheme(state.theme === "dark" ? "light" : "dark");
+ closeActionMenu();
+ }
+
+ function notSpecified(value) {
+ return textValue(value, "Not specified");
+ }
+
function boolPill(label, value) {
return `${esc(label)}: ${value ? "yes" : "no"}`;
}
@@ -203,6 +318,55 @@
`;
}
+ function itscreenLogs() {
+ return state.itscreen.logs;
+ }
+
+ function itscreenLogStatusMeta() {
+ const logs = itscreenLogs();
+ if (!logs.available) return { label: "Unavailable", tone: "error" };
+ if (logs.paused) return { label: "Paused", tone: "warn" };
+ if (logs.status === "live") return { label: "Live", tone: "ok" };
+ return { label: "Disconnected", tone: "warn" };
+ }
+
+ function trimItscreenLogBuffer(lines) {
+ if (!Array.isArray(lines)) return [];
+ return lines.slice(-ITSCREEN_LOG_BUFFER_LIMIT);
+ }
+
+ function itscreenLogMatches(line, search) {
+ const haystack = (line ?? "").toString().toLowerCase();
+ const needle = (search ?? "").toString().trim().toLowerCase();
+ return !needle || haystack.includes(needle);
+ }
+
+ function highlightItscreenLogLine(line, search) {
+ const raw = (line ?? "").toString();
+ const needle = (search ?? "").toString().trim();
+ if (!needle) return esc(raw);
+ const lowerRaw = raw.toLowerCase();
+ const lowerNeedle = needle.toLowerCase();
+ let cursor = 0;
+ let html = "";
+ while (cursor < raw.length) {
+ const index = lowerRaw.indexOf(lowerNeedle, cursor);
+ if (index === -1) {
+ html += esc(raw.slice(cursor));
+ break;
+ }
+ html += esc(raw.slice(cursor, index));
+ html += `${esc(raw.slice(index, index + needle.length))}`;
+ cursor = index + needle.length;
+ }
+ return html;
+ }
+
+ function visibleItscreenLogLines() {
+ const logs = itscreenLogs();
+ return logs.buffer.filter((line) => itscreenLogMatches(line, logs.search));
+ }
+
function tunnelTone(tunnel) {
if (tunnel && tunnel.state === "failed") return "error";
if (tunnel && tunnel.active) return "ok";
@@ -313,23 +477,47 @@
`;
}
+ function normalizeItscreenHostCandidate(value) {
+ const raw = textValue(value, "").trim().toLowerCase();
+ if (!raw) return "";
+ if (raw.includes("://") || raw.includes("/") || /\s/.test(raw)) return raw;
+ if (raw.endsWith(".")) return raw.slice(0, -1);
+ return raw.startsWith("rest.") ? raw : `rest.${raw}`;
+ }
+
+ function itscreenPayload() {
+ return state.itscreen.data || {};
+ }
+
+ function itscreenRegistration() {
+ return itscreenPayload().registration || {};
+ }
+
+ function itscreenService() {
+ return itscreenPayload().service || {};
+ }
+
+ function itscreenRuntime() {
+ return state.itscreen.runtime || {};
+ }
+
function itscreenServerMode(host) {
const value = textValue(host, "").toLowerCase();
- if (value === "rest.uae.iomatex.com") return "uae";
- if (value === "rest.dev.it-screen.com") return "dev";
+ const option = ITSCREEN_SERVER_OPTIONS.find((item) => item.host === value);
+ if (option) return option.mode;
return "custom";
}
function itscreenResolvedHost() {
- if (state.itscreen.serverMode === "uae") return "rest.uae.iomatex.com";
- if (state.itscreen.serverMode === "dev") return "rest.dev.it-screen.com";
- return textValue(state.itscreen.customHost, "");
+ const option = ITSCREEN_SERVER_OPTIONS.find((item) => item.mode === state.itscreen.serverMode && item.host);
+ if (option) return option.host;
+ return normalizeItscreenHostCandidate(state.itscreen.customHost);
}
function itscreenHostValidationError() {
const host = itscreenResolvedHost().trim().toLowerCase();
if (!host) return "Invalid server host";
- if (host.includes("://") || host.includes("/")) return "Invalid server host";
+ if (host.includes("://") || host.includes("/") || /\s/.test(host)) return "Invalid server host";
if (!/^(?=.{1,253}$)(?!-)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.(?!-)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/.test(host)) {
return "Invalid server host";
}
@@ -344,13 +532,135 @@
return { label: "Not registered", tone: "warn" };
}
- function maskValue(value) {
- return textValue(value, "") ? "••••••••" : "—";
+ function itscreenServiceMeta(service) {
+ const status = textValue(service && service.status, "unknown");
+ if (status === "running") return { label: "Running", tone: "ok" };
+ if (status === "failed") return { label: "Failed", tone: "error" };
+ if (status === "stopped") return { label: "Stopped", tone: "warn" };
+ if (status === "not_installed") return { label: "Not installed", tone: "warn" };
+ return { label: "Unknown", tone: "warn" };
+ }
+
+ function itscreenBooleanLabel(value, kind) {
+ if (kind === "registered") return value ? "Registered" : "Not registered";
+ if (kind === "logged") return value ? "Logged in" : "Not logged in";
+ return value ? "Yes" : "No";
+ }
+
+ function itscreenServerValue(payload) {
+ return notSpecified(payload && (payload.server || payload.host));
+ }
+
+ function itscreenResponseDetails() {
+ return textValue(state.itscreen.details, "");
+ }
+
+ function formatItscreenUptime(value) {
+ const seconds = Number(value);
+ if (!Number.isFinite(seconds) || seconds < 0) return "—";
+ if (seconds < 60) return `${Math.floor(seconds)}s`;
+ if (seconds < 3600) {
+ const minutes = Math.floor(seconds / 60);
+ const remSeconds = Math.floor(seconds % 60);
+ return `${minutes}m ${remSeconds}s`;
+ }
+ if (seconds < 86400) {
+ const hours = Math.floor(seconds / 3600);
+ const minutes = Math.floor((seconds % 3600) / 60);
+ return `${hours}h ${minutes}m`;
+ }
+ const days = Math.floor(seconds / 86400);
+ const hours = Math.floor((seconds % 86400) / 3600);
+ return `${days}d ${hours}h`;
+ }
+
+ function formatTimestamp(value) {
+ const ms = Number(value);
+ if (!Number.isFinite(ms) || ms <= 0) return "—";
+ const date = new Date(ms);
+ if (Number.isNaN(date.getTime())) return "—";
+ const pad = (number) => String(number).padStart(2, "0");
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
+ }
+
+ function formatInterval(value, disabledLabel = "Disabled") {
+ const seconds = Number(value);
+ if (!Number.isFinite(seconds)) return "—";
+ if (seconds === 0) return disabledLabel;
+ return `Every ${Math.floor(seconds)} seconds`;
+ }
+
+ function formatRepeatInterval(value) {
+ const seconds = Number(value);
+ if (!Number.isFinite(seconds)) return "—";
+ if (seconds === 0) return "0 seconds";
+ return `Every ${Math.floor(seconds)} seconds`;
+ }
+
+ function itscreenCanRegister(registration) {
+ if (state.itscreen.busyAction || state.itscreen.loading) return false;
+ if (!!(registration && registration.registered)) return false;
+ return !itscreenHostValidationError();
+ }
+
+ function renderItscreenInfoRows(payload) {
+ return renderKeyValueRows([
+ { label: "Server", value: itscreenServerValue(payload) },
+ { label: "Device ID", value: notSpecified(payload && payload.device_id) },
+ { label: "Device name", value: notSpecified(payload && payload.device_name) },
+ { label: "Organization", value: notSpecified(payload && payload.organization) },
+ { label: "Token", value: notSpecified(payload && payload.token) },
+ { label: "Registered", value: itscreenBooleanLabel(!!(payload && payload.registered), "registered") },
+ { label: "Logged", value: itscreenBooleanLabel(!!(payload && payload.logged), "logged") },
+ { label: "Password state", value: notSpecified(payload && payload.password_state) }
+ ]);
+ }
+
+ function renderItscreenServiceCard(card) {
+ const payload = itscreenRegistration();
+ const tone = statusTone(card);
+ const warnings = Array.isArray(card.warnings) ? card.warnings : [];
+ const errors = Array.isArray(card.errors) ? card.errors : [];
+
+ return `
+ ${esc(card.subtitle)}${esc(card.title)}
+ ${card.subtitle ? `${warnings.map((x) => `
${errors.map((x) => `
${esc(testMeta.output.join("\n"))}` : ""}
+