From 3a66c380a49353e976b98ee3a9563101c3755af6 Mon Sep 17 00:00:00 2001 From: Andrei Smaliak Date: Sun, 4 Oct 2026 11:15:17 +0200 Subject: [PATCH] Release Console 3.1.7 with legacy-compatible module updates and camera previews --- docs/releases/console-3.1.4.md | 8 + docs/releases/console-3.1.5.md | 7 + docs/releases/console-3.1.6.md | 7 + docs/releases/console-3.1.7.md | 10 + docs/releases/stage-ip-stream-1.0.1.md | 8 + docs/releases/stage-ip-stream-1.0.2.md | 8 + install_iomatex_edge.sh | 3 +- local_installer.sh | 8 +- offline/bump_stage_version.py | 3 + offline/stage_versions.py | 25 +- offline/test_stage_versions.py | 47 +++ stage-releases.json | 7 +- stage_ip_stream/iomatex-ip-stream.service | 24 ++ stage_ip_stream/ip-stream.py | 310 ++++++++++++++++++ stage_ip_stream/stage_ip_stream_install.sh | 26 ++ stage_ip_stream/test_ip_stream.py | 83 +++++ stage_ip_stream/version.json | 3 + stage_ui/console_core/backend/app.py | 130 +++++++- .../backend/test_camera_preview_contract.py | 23 ++ .../backend/test_ip_stream_health_contract.py | 24 ++ .../backend/test_stage_updates_ui.js | 8 +- .../console_core/frontend/console.i18n.js | 1 + stage_ui/console_core/frontend/console.js | 14 +- stage_ui/console_core/frontend/index.html | 6 +- .../providers/00_core_services.py | 38 ++- stage_ui/version.json | 2 +- 26 files changed, 812 insertions(+), 21 deletions(-) create mode 100644 docs/releases/console-3.1.4.md create mode 100644 docs/releases/console-3.1.5.md create mode 100644 docs/releases/console-3.1.6.md create mode 100644 docs/releases/console-3.1.7.md create mode 100644 docs/releases/stage-ip-stream-1.0.1.md create mode 100644 docs/releases/stage-ip-stream-1.0.2.md create mode 100644 stage_ip_stream/iomatex-ip-stream.service create mode 100644 stage_ip_stream/ip-stream.py create mode 100644 stage_ip_stream/stage_ip_stream_install.sh create mode 100644 stage_ip_stream/test_ip_stream.py create mode 100644 stage_ip_stream/version.json create mode 100644 stage_ui/console_core/backend/test_camera_preview_contract.py create mode 100644 stage_ui/console_core/backend/test_ip_stream_health_contract.py diff --git a/docs/releases/console-3.1.4.md b/docs/releases/console-3.1.4.md new file mode 100644 index 0000000..f61da73 --- /dev/null +++ b/docs/releases/console-3.1.4.md @@ -0,0 +1,8 @@ +# Console 3.1.4 + +Released 2026-10-04. + +- Keep version checks working when an older published catalog does not yet contain a newly introduced stage. +- Show `Release is not published` for an installed stage missing from the catalog instead of failing the complete check. +- Retry a manual version check immediately even when the previous attempt failed. +- Wait for the asynchronous Git check before refreshing the Health view and surface its final error to the operator. diff --git a/docs/releases/console-3.1.5.md b/docs/releases/console-3.1.5.md new file mode 100644 index 0000000..dc9944d --- /dev/null +++ b/docs/releases/console-3.1.5.md @@ -0,0 +1,7 @@ +# Console 3.1.5 + +Released 2026-10-04. + +- Serve authenticated camera preview manifests and fragmented MP4 segments through the existing WebUI reverse tunnel. +- Start camera preview through the local IP streaming service without exposing another Edge port. +- Keep the Console runtime version and versioned frontend assets synchronized with the stage manifest. diff --git a/docs/releases/console-3.1.6.md b/docs/releases/console-3.1.6.md new file mode 100644 index 0000000..3330fbf --- /dev/null +++ b/docs/releases/console-3.1.6.md @@ -0,0 +1,7 @@ +# Console 3.1.6 + +Released 2026-10-04. + +- Request camera snapshots through the local IP streaming service. +- Serve snapshot JPEG files through the authenticated WebUI reverse tunnel. +- Prevent stale snapshots from satisfying a new capture request. diff --git a/docs/releases/console-3.1.7.md b/docs/releases/console-3.1.7.md new file mode 100644 index 0000000..f02114c --- /dev/null +++ b/docs/releases/console-3.1.7.md @@ -0,0 +1,10 @@ +# Console 3.1.7 + +Release date: 2026-10-04. + +- Publish the pending version-check fixes, IP Camera Streaming health card, authenticated preview and fresh snapshot support described in 3.1.4–3.1.6. +- Keep the original nine stages in the public catalog's stages map, so Console 3.1.2 can discover and install this release without a bootstrap update. +- Publish additional stages in optional_stages, merged by the new shared version owner. Validate duplicates and invalid versions; preserve this format when bumping future releases. +- Wait for background version checks and display their final result; manual checks bypass the previous error throttle. + +Validation: stage release compatibility, update UI, camera preview, IP streaming and client contracts. No installed Edge modules are updated during publication. diff --git a/docs/releases/stage-ip-stream-1.0.1.md b/docs/releases/stage-ip-stream-1.0.1.md new file mode 100644 index 0000000..607c861 --- /dev/null +++ b/docs/releases/stage-ip-stream-1.0.1.md @@ -0,0 +1,8 @@ +# IP Camera Streaming 1.0.1 + +Released 2026-10-04. + +- Add one shared on-demand HLS preview per camera for installation checks with two or three viewers. +- Keep camera RTSP credentials inside the server-to-Edge request and out of browser responses. +- Stop inactive preview processes automatically after ten minutes. +- Produce browser-ready fragmented MP4 segments without video transcoding. diff --git a/docs/releases/stage-ip-stream-1.0.2.md b/docs/releases/stage-ip-stream-1.0.2.md new file mode 100644 index 0000000..7b69873 --- /dev/null +++ b/docs/releases/stage-ip-stream-1.0.2.md @@ -0,0 +1,8 @@ +# IP Camera Streaming 1.0.2 + +Released 2026-10-04. + +- Add an authenticated on-demand JPEG snapshot action for installation checks. +- Keep FFmpeg ownership inside `stage_ip_stream` and publish snapshots atomically. +- Preserve camera credentials inside the server-to-Edge request path. +- Restart an already running streaming service when the stage is upgraded. diff --git a/install_iomatex_edge.sh b/install_iomatex_edge.sh index 60c5b4b..4b84f0a 100755 --- a/install_iomatex_edge.sh +++ b/install_iomatex_edge.sh @@ -11,12 +11,13 @@ STAGES=stage_env,stage_wifi,stage_mqtt,stage_ui,stage_avahi,stage_cockpit,stage_ while [[ $# -gt 0 ]]; do case "$1" in --with-z2m) STAGES=stage_env,stage_wifi,stage_mqtt,stage_z2m,stage_ui,stage_avahi,stage_cockpit,stage_itscreen,stage_reverse_tunnels; shift ;; + --with-ip-stream) STAGES=stage_env,stage_wifi,stage_mqtt,stage_ui,stage_avahi,stage_cockpit,stage_itscreen,stage_ip_stream,stage_reverse_tunnels; shift ;; --default-only) STAGES=stage_env,stage_mqtt,stage_ui,stage_avahi,stage_cockpit,stage_itscreen; shift ;; --only) STAGES=${2:?Missing stages}; shift 2 ;; --branch) GIT_BRANCH=${2:?Missing branch}; shift 2 ;; --git-url) GIT_URL=${2:?Missing URL}; shift 2 ;; --checkout-dir) CHECKOUT_DIR=${2:?Missing directory}; shift 2 ;; - -h|--help) echo 'sudo bash install_iomatex_edge.sh [--with-z2m] [--only stages] [--branch branch] [--checkout-dir path]'; exit 0 ;; + -h|--help) echo 'sudo bash install_iomatex_edge.sh [--with-z2m] [--with-ip-stream] [--only stages] [--branch branch] [--checkout-dir path]'; exit 0 ;; *) echo "Unknown argument: $1" >&2; exit 1 ;; esac done diff --git a/local_installer.sh b/local_installer.sh index 1c08ada..bd19d71 100755 --- a/local_installer.sh +++ b/local_installer.sh @@ -88,6 +88,7 @@ STAGE_ORDER=( "stage_avahi" "stage_cockpit" "stage_itscreen" + "stage_ip_stream" "stage_reverse_tunnels" ) @@ -103,6 +104,7 @@ OPTIONAL_STAGES=( "stage_z2m" "stage_avahi" "stage_cockpit" + "stage_ip_stream" "stage_reverse_tunnels" ) @@ -433,7 +435,8 @@ stage_number_to_name() { 6) echo "stage_avahi" ;; 7) echo "stage_cockpit" ;; 8) echo "stage_itscreen" ;; - 9) echo "stage_reverse_tunnels" ;; + 9) echo "stage_ip_stream" ;; + 10) echo "stage_reverse_tunnels" ;; *) return 1 ;; esac } @@ -731,6 +734,9 @@ stage_candidates() { stage_itscreen) printf '%s\n' "stage_itscreen_install.sh" ;; + stage_ip_stream) + printf '%s\n' "stage_ip_stream_install.sh" + ;; esac } diff --git a/offline/bump_stage_version.py b/offline/bump_stage_version.py index f5f43d1..8d88a3f 100644 --- a/offline/bump_stage_version.py +++ b/offline/bump_stage_version.py @@ -18,6 +18,9 @@ def bump(root, stage, version): releases = {key: json.loads((root / key / 'version.json').read_text()) for key in STAGES} releases[stage] = {**old, 'version':version} catalog = validate_manifest({'schema':1, 'stages':releases}) + # Console <= 3.1.2 requires exactly the original nine stages. + # New Console merges optional_stages before validation and comparison. + catalog['optional_stages'] = {'stage_ip_stream': catalog['stages'].pop('stage_ip_stream')} path.write_text(json.dumps(releases[stage], indent=2) + '\n') (root / 'stage-releases.json').write_text(json.dumps(catalog, indent=2) + '\n') diff --git a/offline/stage_versions.py b/offline/stage_versions.py index 5a09c63..9ff8f1b 100644 --- a/offline/stage_versions.py +++ b/offline/stage_versions.py @@ -30,6 +30,7 @@ STAGES = { 'stage_avahi': ('Avahi / mDNS', ['avahi']), 'stage_cockpit': ('Cockpit', ['cockpit']), 'stage_itscreen': ('IT-Screen / Display', ['itscreen', 'display']), + 'stage_ip_stream': ('IP Camera Streaming', ['ip_stream']), 'stage_reverse_tunnels': ('Reverse Tunnels', ['reverse_tunnel']), } CHECK_TTL = 900 @@ -45,8 +46,17 @@ def read_json(path, default=None): return {} if default is None else default -def validate_manifest(value): - if not isinstance(value, dict) or value.get('schema') != 1 or set(value.get('stages', {})) != set(STAGES): +def validate_manifest(value, allow_missing=False): + if not isinstance(value, dict) or value.get('schema') != 1 or not isinstance(value.get('stages'), dict): + raise ValueError('Invalid stage release catalog') + optional = value.get('optional_stages', {}) + if not isinstance(optional, dict) or set(optional) & set(value['stages']): + raise ValueError('Invalid optional stage release catalog') + value = {**value, 'stages': {**value['stages'], **optional}} + value.pop('optional_stages', None) + published = set(value['stages']) + expected = set(STAGES) + if published - expected or (not allow_missing and published != expected): raise ValueError('Invalid stage release catalog') for stage, release in value['stages'].items(): if not isinstance(release, dict) or not re.fullmatch(r'\d+\.\d+\.\d+', str(release.get('version', ''))): @@ -92,7 +102,7 @@ def refresh(): commit = json.load(response)['commit']['id'] phase = 'catalog' with delivery.open_git(repo, delivery.raw_endpoint('stage-releases.json', commit), auth, timeout=15) as response: - catalog = validate_manifest(json.load(response)) + catalog = validate_manifest(json.load(response), allow_missing=True) delivery.write_json(STATE / 'available.json', { **catalog, 'commit': commit, 'checked_at': int(time.time()), 'attempt_at': int(time.time()), 'error': '', @@ -118,7 +128,8 @@ def request_check(force=False): with _guard: cached = read_json(STATE / 'available.json') age = time.time() - cached.get('attempt_at', 0) - if _checking or age < (30 if force or cached.get('error') else CHECK_TTL): + minimum_age = 0 if force else (30 if cached.get('error') else CHECK_TTL) + if _checking or age < minimum_age: return _checking = True threading.Thread(target=refresh, daemon=True, name='stage-release-check').start() @@ -164,7 +175,9 @@ def snapshot(cards): latest = available.get('stages', {}).get(stage, {}).get('version') current = receipt.get('version') if installed else None status = 'not_installed' if not installed else ('not_checked' if not fresh else 'unknown') - if fresh and installed and current: + if fresh and latest is None: + status = 'not_published' + elif fresh and installed and current: current_tuple = tuple(map(int, current.split('.'))) latest_tuple = tuple(map(int, latest.split('.'))) status = 'latest' if current_tuple == latest_tuple else ('update_available' if current_tuple < latest_tuple else 'ahead') @@ -174,7 +187,7 @@ def snapshot(cards): 'stage': stage, 'title': title, 'installed': installed, 'current': current, 'latest': latest, 'status': status, 'commit': available.get('commit'), - 'can_install': bool(fresh and not busy and status in ('not_installed', 'unknown', 'update_available', 'local_build')), + 'can_install': bool(fresh and latest and not busy and status in ('not_installed', 'unknown', 'update_available', 'local_build')), 'reboot': stage == 'stage_env', 'services': ids, } return {'stages': versions, 'checking': _checking, 'checked_at': available.get('checked_at'), diff --git a/offline/test_stage_versions.py b/offline/test_stage_versions.py index b32ca73..43cbeba 100644 --- a/offline/test_stage_versions.py +++ b/offline/test_stage_versions.py @@ -29,6 +29,27 @@ class StageVersionsTest(unittest.TestCase): versions.delivery.write_json(versions.STATE / 'available.json', self.available) versions.delivery.write_json(versions.CONFIG, {'repo':'An-J/Iomatex_OS', 'branch':'ci-cd', 'checkout':str(root / 'checkout')}) + def test_published_catalog_is_accepted_by_legacy_console(self): + raw = json.loads((ROOT / 'stage-releases.json').read_text()) + # This is the exact set checked by Console 3.1.2's validator. + legacy = {'stage_env', 'stage_wifi', 'stage_mqtt', 'stage_z2m', + 'stage_ui', 'stage_avahi', 'stage_cockpit', + 'stage_itscreen', 'stage_reverse_tunnels'} + self.assertEqual(legacy, set(raw['stages'])) + self.assertEqual({'stage_ip_stream'}, set(raw['optional_stages'])) + normalized = versions.validate_manifest(raw) + self.assertEqual(set(versions.STAGES), set(normalized['stages'])) + self.assertNotIn('optional_stages', normalized) + self.assertEqual(normalized, versions.validate_manifest(normalized)) + + def test_optional_catalog_rejects_duplicate_or_invalid_entries(self): + for optional in [{'stage_ui': {'version': '9.0.0'}}, [], + {'stage_ip_stream': {'version': 'invalid'}}]: + raw = json.loads((ROOT / 'stage-releases.json').read_text()) + raw['optional_stages'] = optional + with self.assertRaises(ValueError): + versions.validate_manifest(raw) + def test_every_stage_has_matching_manifest(self): for stage, release in self.catalog['stages'].items(): self.assertEqual(release, json.loads((ROOT / stage / 'version.json').read_text())) @@ -62,6 +83,29 @@ class StageVersionsTest(unittest.TestCase): self.assertEqual('not_checked', result['status']) self.assertFalse(result['can_install']) + def test_older_catalog_keeps_published_stages_available(self): + legacy = json.loads(json.dumps(self.catalog)) + legacy['stages'].pop('stage_ip_stream') + validated = versions.validate_manifest(legacy, allow_missing=True) + versions.delivery.write_json(versions.STATE / 'available.json', { + **validated, 'commit': COMMIT, 'checked_at': int(time.time()), + 'attempt_at': int(time.time()), 'error': '', + }) + versions.delivery.write_json(versions.STATE / 'stage_ip_stream.json', {'version': '1.0.0'}) + with mock.patch.object(versions, 'request_check'): + result = versions.snapshot([{'id': 'ip_stream', 'installed': True}]) + self.assertEqual('not_published', result['stages']['stage_ip_stream']['status']) + self.assertFalse(result['stages']['stage_ip_stream']['can_install']) + self.assertEqual(self.catalog['stages']['stage_itscreen']['version'], result['stages']['stage_itscreen']['latest']) + + def test_forced_check_is_not_throttled_by_previous_error(self): + versions.delivery.write_json(versions.STATE / 'available.json', { + 'attempt_at': int(time.time()), 'error': 'previous error' + }) + with mock.patch.object(versions.threading.Thread, 'start') as start: + versions.request_check(force=True) + self.assertTrue(start.called) + def test_install_rejects_path_injection_stale_and_duplicate(self): with self.assertRaises(ValueError): versions.start_install('../../bin/sh', COMMIT) with self.assertRaises(ValueError): versions.start_install('stage_z2m', 'b'*40) @@ -136,6 +180,9 @@ class StageVersionsTest(unittest.TestCase): bump_stage_version.bump(root, 'stage_z2m', '1.0.1') catalog = versions.validate_manifest(json.loads((root / 'stage-releases.json').read_text())) self.assertEqual({'version':'1.0.1'},catalog['stages']['stage_z2m']) + raw = json.loads((root / 'stage-releases.json').read_text()) + self.assertNotIn('stage_ip_stream', raw['stages']) + self.assertIn('stage_ip_stream', raw['optional_stages']) self.assertEqual(catalog['stages']['stage_z2m'],json.loads((root / 'stage_z2m/version.json').read_text())) with self.assertRaises(ValueError): bump_stage_version.bump(root, 'stage_z2m', '1.0.0') diff --git a/stage-releases.json b/stage-releases.json index 395793a..16d8b89 100644 --- a/stage-releases.json +++ b/stage-releases.json @@ -14,7 +14,7 @@ "version": "1.0.0" }, "stage_ui": { - "version": "3.1.2" + "version": "3.1.7" }, "stage_avahi": { "version": "1.0.0" @@ -28,5 +28,10 @@ "stage_reverse_tunnels": { "version": "1.0.1" } + }, + "optional_stages": { + "stage_ip_stream": { + "version": "1.0.2" + } } } diff --git a/stage_ip_stream/iomatex-ip-stream.service b/stage_ip_stream/iomatex-ip-stream.service new file mode 100644 index 0000000..81d1883 --- /dev/null +++ b/stage_ip_stream/iomatex-ip-stream.service @@ -0,0 +1,24 @@ +[Unit] +Description=IOMATEX IP camera streaming service +After=network-online.target mosquitto.service +Wants=network-online.target +Requires=mosquitto.service + +[Service] +Type=simple +ExecStart=/usr/local/lib/iomatex/ip-stream.py +Restart=on-failure +RestartSec=5 +User=iomatex-stream +Group=iomatex-stream +RuntimeDirectory=iomatex-ip-stream +RuntimeDirectoryMode=0755 +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true +ProtectSystem=strict +ReadOnlyPaths=/userdata/device-id /var/lib/itscreen/config/it-screen/it-screen.conf +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 + +[Install] +WantedBy=multi-user.target diff --git a/stage_ip_stream/ip-stream.py b/stage_ip_stream/ip-stream.py new file mode 100644 index 0000000..2679b81 --- /dev/null +++ b/stage_ip_stream/ip-stream.py @@ -0,0 +1,310 @@ +#!/usr/bin/env python3 +import configparser +import json +import os +import re +import signal +import socket +import subprocess +import shutil +import time +from pathlib import Path +from urllib.parse import urlparse + + +DEVICE_ID_PATH = Path("/userdata/device-id") +ITSCREEN_CONFIG_PATH = Path("/var/lib/itscreen/config/it-screen/it-screen.conf") +STATUS_PATH = Path("/run/iomatex-ip-stream/status.json") +PREVIEW_ROOT = Path("/run/iomatex-ip-stream/hls") +SUPPORTED_INPUT_SCHEMES = {"rtsp"} +SUPPORTED_OUTPUT_SCHEMES = {"rtsp", "rtmp", "srt", "udp"} +MAX_STREAMS = 8 +PREVIEW_TTL_SEC = 10 * 60 + + +def edge_id(): + value = DEVICE_ID_PATH.read_text(encoding="utf-8").strip() + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}", value): + raise RuntimeError("invalid Edge device id") + return value + + +def mqtt_prefix(): + parser = configparser.RawConfigParser(strict=False) + parser.optionxform = str + parser.read(ITSCREEN_CONFIG_PATH, encoding="utf-8") + value = parser.get("%General", "mqttPrefix", fallback="").strip().strip("/") + if not value or any(not re.fullmatch(r"[A-Za-z0-9._-]+", part) for part in value.split("/")): + raise RuntimeError("mqttPrefix is not configured") + return value + + +def validate_stream_id(value): + value = str(value or "") + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}", value): + raise ValueError("invalid stream_id") + return value + + +def validate_url(value, schemes): + parsed = urlparse(str(value or "")) + if parsed.scheme.lower() not in schemes or not parsed.hostname: + raise ValueError("unsupported stream URL") + return str(value) + + +def output_arguments(output_url): + scheme = urlparse(output_url).scheme.lower() + if scheme == "rtmp": + return ["-f", "flv", output_url] + if scheme == "rtsp": + return ["-f", "rtsp", "-rtsp_transport", "tcp", output_url] + return ["-f", "mpegts", output_url] + + +class StreamManager: + def __init__(self, device=None, prefix=None): + self.device = device or edge_id() + self.prefix = prefix or mqtt_prefix() + self.subscribe_topic = f"{self.prefix}/client/sub/camera/{self.device}/stream" + self.publish_topic = f"{self.prefix}/client/pub/camera/{self.device}/stream" + self.processes = {} + self.started_at = int(time.time()) + self.running = True + + def publish(self, payload): + subprocess.run([ + "mosquitto_pub", "-h", "127.0.0.1", "-p", "1883", + "-t", self.publish_topic, + "-m", json.dumps(payload, separators=(",", ":")), + ], check=True, timeout=5) + + def reap(self): + stopped = [] + now = time.time() + for stream_id, record in list(self.processes.items()): + process = record["process"] + if record.get("expires_at", 0) and record["expires_at"] <= now and process.poll() is None: + self.stop({"stream_id": stream_id}) + stopped.append({"stream_id": stream_id, "exit_code": 0, "reason": "expired"}) + continue + code = process.poll() + if code is None: + continue + stopped.append({"stream_id": stream_id, "exit_code": code}) + self.processes.pop(stream_id, None) + self.write_status() + return stopped + + def write_status(self): + STATUS_PATH.parent.mkdir(parents=True, exist_ok=True) + temporary = STATUS_PATH.with_suffix(".tmp") + temporary.write_text(json.dumps({ + "status": "active", + "started_at": self.started_at, + "updated_at": int(time.time()), + "active_streams": sorted(self.processes), + "streams": { + stream_id: { + "kind": record.get("kind", "forward"), + "expires_at": int(record.get("expires_at", 0)), + } + for stream_id, record in self.processes.items() + }, + "active_count": len(self.processes), + "max_streams": MAX_STREAMS, + }), encoding="utf-8") + os.replace(temporary, STATUS_PATH) + + def start(self, payload): + stream_id = validate_stream_id(payload.get("stream_id")) + if stream_id in self.processes: + return {"action": "start", "status": "ok", "stream_id": stream_id, "already_running": True} + if len(self.processes) >= MAX_STREAMS: + raise RuntimeError("stream limit reached") + input_url = validate_url(payload.get("input_url"), SUPPORTED_INPUT_SCHEMES) + output_url = validate_url(payload.get("output_url"), SUPPORTED_OUTPUT_SCHEMES) + command = [ + "ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "warning", + "-rtsp_transport", "tcp", "-i", input_url, + "-map", "0:v:0", "-map", "0:a?", "-c", "copy", + *output_arguments(output_url), + ] + self.processes[stream_id] = { + "process": self.spawn(command), + "kind": "forward", + "expires_at": 0, + } + self.write_status() + return {"action": "start", "status": "ok", "stream_id": stream_id, "already_running": False} + + def spawn(self, command): + return subprocess.Popen( + command, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + ) + + def preview_start(self, payload): + stream_id = validate_stream_id(payload.get("stream_id")) + expires_at = time.time() + PREVIEW_TTL_SEC + if stream_id in self.processes: + record = self.processes[stream_id] + if record.get("kind") != "preview": + raise RuntimeError("stream_id is already used by a forwarding stream") + record["expires_at"] = expires_at + self.write_status() + return { + "action": "preview_start", + "status": "ok", + "stream_id": stream_id, + "already_running": True, + "manifest": f"/api/camera-preview/{stream_id}/index.m3u8", + } + if len(self.processes) >= MAX_STREAMS: + raise RuntimeError("stream limit reached") + + input_url = validate_url(payload.get("input_url"), SUPPORTED_INPUT_SCHEMES) + preview_dir = PREVIEW_ROOT / stream_id + shutil.rmtree(preview_dir, ignore_errors=True) + preview_dir.mkdir(parents=True, mode=0o750) + manifest_path = preview_dir / "index.m3u8" + segment_pattern = preview_dir / "segment-%06d.m4s" + command = [ + "ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "warning", + "-rtsp_transport", "tcp", "-i", input_url, + "-map", "0:v:0", "-an", "-c:v", "copy", + "-f", "hls", "-hls_time", "1", "-hls_list_size", "5", + "-hls_segment_type", "fmp4", "-hls_fmp4_init_filename", "init.mp4", + "-hls_flags", "delete_segments+omit_endlist+independent_segments", + "-hls_segment_filename", str(segment_pattern), str(manifest_path), + ] + self.processes[stream_id] = { + "process": self.spawn(command), + "kind": "preview", + "expires_at": expires_at, + } + self.write_status() + return { + "action": "preview_start", + "status": "ok", + "stream_id": stream_id, + "already_running": False, + "manifest": f"/api/camera-preview/{stream_id}/index.m3u8", + } + + def snapshot(self, payload): + stream_id = validate_stream_id(payload.get("stream_id")) + input_url = validate_url(payload.get("input_url"), SUPPORTED_INPUT_SCHEMES) + preview_dir = PREVIEW_ROOT / stream_id + preview_dir.mkdir(parents=True, mode=0o750, exist_ok=True) + snapshot_path = preview_dir / "snapshot.jpg" + temporary_path = preview_dir / "snapshot.tmp.jpg" + command = [ + "ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-y", + "-rtsp_transport", "tcp", "-i", input_url, + "-map", "0:v:0", "-frames:v", "1", "-q:v", "2", str(temporary_path), + ] + try: + result = subprocess.run( + command, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=18, + check=False, + ) + except subprocess.TimeoutExpired as exc: + temporary_path.unlink(missing_ok=True) + raise RuntimeError("Camera snapshot timed out") from exc + if result.returncode != 0 or not temporary_path.is_file() or temporary_path.stat().st_size == 0: + temporary_path.unlink(missing_ok=True) + raise RuntimeError("Camera did not produce a snapshot") + os.replace(temporary_path, snapshot_path) + return { + "action": "snapshot", + "status": "ok", + "stream_id": stream_id, + "snapshot": f"/api/camera-preview/{stream_id}/snapshot.jpg", + } + + def stop(self, payload): + stream_id = validate_stream_id(payload.get("stream_id")) + record = self.processes.pop(stream_id, None) + process = record["process"] if record is not None else None + if process is not None and process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=2) + self.write_status() + return {"action": "stop", "status": "ok", "stream_id": stream_id} + + def status(self): + stopped = self.reap() + return { + "action": "status", + "status": "ok", + "active_streams": sorted(self.processes), + "active_count": len(self.processes), + "max_streams": MAX_STREAMS, + "stopped": stopped, + } + + def handle(self, payload): + action = str(payload.get("action") or "") + try: + if action == "start": + response = self.start(payload) + elif action == "preview_start": + response = self.preview_start(payload) + elif action == "snapshot": + response = self.snapshot(payload) + elif action == "stop": + response = self.stop(payload) + elif action == "status": + response = self.status() + else: + return + except Exception as exc: + response = {"action": action, "status": "error", "error": str(exc)} + if payload.get("stream_id"): + response["stream_id"] = str(payload["stream_id"]) + self.publish(response) + + def shutdown(self, *_): + self.running = False + for stream_id in list(self.processes): + self.stop({"stream_id": stream_id}) + + def run(self): + signal.signal(signal.SIGTERM, self.shutdown) + signal.signal(signal.SIGINT, self.shutdown) + self.write_status() + command = [ + "mosquitto_sub", "-h", "127.0.0.1", "-p", "1883", + "-t", self.subscribe_topic, + ] + process = subprocess.Popen(command, stdout=subprocess.PIPE, text=True) + if process.stdout is None: + raise RuntimeError("mosquitto_sub did not provide stdout") + while self.running: + line = process.stdout.readline() + if not line: + break + try: + payload = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(payload, dict): + self.handle(payload) + process.terminate() + return process.wait(timeout=5) + + +if __name__ == "__main__": + raise SystemExit(StreamManager().run()) diff --git a/stage_ip_stream/stage_ip_stream_install.sh b/stage_ip_stream/stage_ip_stream_install.sh new file mode 100644 index 0000000..369b4da --- /dev/null +++ b/stage_ip_stream/stage_ip_stream_install.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -euo pipefail + +source "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/offline/require-local.sh" +[[ ${EUID:-$(id -u)} -eq 0 ]] || exec sudo -E bash "$0" "$@" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +command -v python3 >/dev/null +command -v mosquitto_pub >/dev/null +command -v mosquitto_sub >/dev/null +command -v ffmpeg >/dev/null || { + echo "ffmpeg is required; install stage_itscreen/base multimedia packages first" >&2 + exit 1 +} + +getent group iomatex-stream >/dev/null 2>&1 || groupadd --system iomatex-stream +id iomatex-stream >/dev/null 2>&1 || useradd --system --gid iomatex-stream --home-dir /nonexistent --shell /usr/sbin/nologin iomatex-stream +getent group itscreen >/dev/null 2>&1 && usermod -a -G itscreen iomatex-stream +install -d -m 0755 /usr/local/lib/iomatex +install -m 0755 "$SCRIPT_DIR/ip-stream.py" /usr/local/lib/iomatex/ip-stream.py +install -m 0644 "$SCRIPT_DIR/iomatex-ip-stream.service" /etc/systemd/system/iomatex-ip-stream.service +systemctl daemon-reload +systemctl enable iomatex-ip-stream.service +systemctl restart iomatex-ip-stream.service +systemctl is-active --quiet iomatex-ip-stream.service +iomatex_record_stage stage_ip_stream diff --git a/stage_ip_stream/test_ip_stream.py b/stage_ip_stream/test_ip_stream.py new file mode 100644 index 0000000..805d139 --- /dev/null +++ b/stage_ip_stream/test_ip_stream.py @@ -0,0 +1,83 @@ +import importlib.util +import pathlib +import tempfile +import unittest +from unittest.mock import MagicMock, patch + + +MODULE_PATH = pathlib.Path(__file__).with_name("ip-stream.py") +SPEC = importlib.util.spec_from_file_location("iomatex_ip_stream", MODULE_PATH) +stream = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(stream) + + +class IpStreamTest(unittest.TestCase): + def test_installer_restarts_an_existing_service(self): + installer = MODULE_PATH.with_name("stage_ip_stream_install.sh").read_text(encoding="utf-8") + self.assertIn("systemctl restart iomatex-ip-stream.service", installer) + self.assertNotIn("enable --now iomatex-ip-stream.service", installer) + + def test_topics_follow_edge_profile(self): + manager = stream.StreamManager("g-box-test", "it-screen/dev") + self.assertEqual(manager.subscribe_topic, "it-screen/dev/client/sub/camera/g-box-test/stream") + self.assertEqual(manager.publish_topic, "it-screen/dev/client/pub/camera/g-box-test/stream") + + def test_output_arguments_are_protocol_specific(self): + self.assertEqual(stream.output_arguments("rtmp://host/live/cam")[:2], ["-f", "flv"]) + self.assertEqual(stream.output_arguments("udp://host:9000")[:2], ["-f", "mpegts"]) + + def test_rejects_unsafe_urls(self): + with self.assertRaises(ValueError): + stream.validate_url("file:///etc/passwd", stream.SUPPORTED_INPUT_SCHEMES) + + def test_preview_uses_one_hls_process_and_refreshes_ttl(self): + manager = stream.StreamManager("g-box-test", "it-screen/dev") + process = MagicMock() + process.poll.return_value = None + manager.spawn = MagicMock(return_value=process) + with tempfile.TemporaryDirectory() as directory, \ + patch.object(stream, "PREVIEW_ROOT", pathlib.Path(directory)), \ + patch.object(manager, "write_status"): + payload = { + "stream_id": "camera-a1b2", + "input_url": "rtsp://camera.local/stream2", + } + first = manager.preview_start(payload) + first_expiry = manager.processes["camera-a1b2"]["expires_at"] + second = manager.preview_start(payload) + + self.assertFalse(first["already_running"]) + self.assertTrue(second["already_running"]) + self.assertGreaterEqual(manager.processes["camera-a1b2"]["expires_at"], first_expiry) + self.assertEqual(manager.spawn.call_count, 1) + command = manager.spawn.call_args.args[0] + self.assertIn("hls", command) + self.assertNotIn("-c:a", command) + + def test_snapshot_is_written_atomically_as_jpeg(self): + manager = stream.StreamManager("g-box-test", "it-screen/dev") + completed = MagicMock(returncode=0) + with tempfile.TemporaryDirectory() as directory, \ + patch.object(stream, "PREVIEW_ROOT", pathlib.Path(directory)), \ + patch.object(stream.subprocess, "run", return_value=completed) as command: + temporary = pathlib.Path(directory) / "camera-a1b2" / "snapshot.tmp.jpg" + + def write_snapshot(*_args, **_kwargs): + temporary.write_bytes(b"jpeg") + return completed + + command.side_effect = write_snapshot + result = manager.snapshot({ + "stream_id": "camera-a1b2", + "input_url": "rtsp://camera.local/stream2", + }) + + self.assertEqual(result["snapshot"], "/api/camera-preview/camera-a1b2/snapshot.jpg") + self.assertEqual((pathlib.Path(directory) / "camera-a1b2" / "snapshot.jpg").read_bytes(), b"jpeg") + ffmpeg = command.call_args.args[0] + self.assertIn("-frames:v", ffmpeg) + self.assertIn("snapshot.tmp.jpg", ffmpeg[-1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/stage_ip_stream/version.json b/stage_ip_stream/version.json new file mode 100644 index 0000000..9a8bfb2 --- /dev/null +++ b/stage_ip_stream/version.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.2" +} diff --git a/stage_ui/console_core/backend/app.py b/stage_ui/console_core/backend/app.py index 823d82c..c89c7e6 100644 --- a/stage_ui/console_core/backend/app.py +++ b/stage_ui/console_core/backend/app.py @@ -54,7 +54,7 @@ APP_DIR = "/opt/iomatex-console" PUBLIC_DIR = os.path.join(APP_DIR, "public") PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d") CONFIG_PATH = "/etc/iomatex/console.json" -UI_VERSION = "V 3.1.2" +UI_VERSION = "V 3.1.7" STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health" ZONEINFO_ROOT = "/usr/share/zoneinfo" @@ -99,6 +99,8 @@ IOMATEX_PULSE_SERVICE_UNIT = "iomatex-pulseaudio.service" IOMATEX_PULSE_SERVER = "unix:/run/iomatex-pulse/native" IOMATEX_PULSE_APPLY_SCRIPT = "/usr/local/bin/iomatex-pulse-apply-route" IOMATEX_AUDIO_ROUTE_PATH = "/etc/iomatex/audio-route.env" +IOMATEX_IP_STREAM_STATUS_PATH = "/run/iomatex-ip-stream/status.json" +IOMATEX_IP_STREAM_HLS_ROOT = "/run/iomatex-ip-stream/hls" IOMATEX_DUAL_SINK_NAME = "iomatex_dual_output" ITSCREEN_CONFIG_CACHE_TTL_SEC = 3.0 ITSCREEN_LOG_DEFAULT_LINES = 100 @@ -160,6 +162,10 @@ STATIC_NO_CACHE_HEADERS = { } _AUTH_SESSIONS = {} _AUTH_SESSIONS_LOCK = threading.Lock() +CAMERA_PREVIEW_PATH_RE = re.compile( + r"^/api/camera-preview/(?P[A-Za-z0-9][A-Za-z0-9_.-]{0,63})/" + r"(?Pindex\.m3u8|init\.mp4|snapshot\.jpg|segment-[0-9]{6}\.m4s)$" +) def load_config(): @@ -205,6 +211,50 @@ def run(cmd, timeout=4, env=None): return 1, "", str(exc) +def publish_camera_preview(payload): + with open(DEVICE_ID_PATH, "r", encoding="utf-8") as device_file: + device_id = device_file.read().strip() + prefix = read_simple_key_value_file(ITSCREEN_CONFIG_PATH).get("mqttPrefix", "").strip().strip("/") + if not prefix: + raise RuntimeError("MQTT prefix is not configured") + topic = f"{prefix}/client/sub/camera/{device_id}/stream" + process = subprocess.run( + ["mosquitto_pub", "-h", "127.0.0.1", "-p", "1883", "-t", topic, "-s"], + input=json.dumps(payload, separators=(",", ":")), + stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + text=True, + timeout=5, + check=False, + ) + if process.returncode != 0: + raise RuntimeError((process.stderr or "Unable to start camera preview").strip()) + + +def wait_camera_preview(stream_id, timeout=12): + manifest = os.path.join(IOMATEX_IP_STREAM_HLS_ROOT, stream_id, "index.m3u8") + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if os.path.isfile(manifest) and os.path.getsize(manifest) > 0: + return manifest + time.sleep(0.25) + raise RuntimeError("Camera did not produce a preview in time") + + +def wait_camera_snapshot(stream_id, previous_mtime_ns=0, timeout=20): + snapshot = os.path.join(IOMATEX_IP_STREAM_HLS_ROOT, stream_id, "snapshot.jpg") + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + stat = os.stat(snapshot) + if stat.st_size > 0 and stat.st_mtime_ns > previous_mtime_ns: + return snapshot + except FileNotFoundError: + pass + time.sleep(0.25) + raise RuntimeError("Camera did not produce a snapshot in time") + + def _auth_now(): return time.time() @@ -1862,6 +1912,8 @@ def get_network_summary(): "iface": iface, "service_state": "unknown", } + cards, _ = collect_provider_cards(build_provider_context()) + avahi_card = next((card for card in cards if card.get("id") == "avahi"), None) return { "ok": True, "generated_at": utc_now_iso(), @@ -1869,6 +1921,7 @@ def get_network_summary(): "desired_profile": profile, "ap_status": ap_status, "access_point": normalize_card(ap_status_card()), + "avahi": normalize_card(avahi_card) if avahi_card else None, "wifi": { "connected": wifi_summary["connected"], "state": wifi_summary["state"] or script_status.get("NM_STATE", "unknown"), @@ -2377,10 +2430,9 @@ def build_health_services_payload(): "reverse_tunnel", "display", "edge_api", - "access_point", + "ip_stream", "environment", "console", - "avahi", } cards, _ = collect_provider_cards(build_provider_context()) payload = { @@ -3153,6 +3205,12 @@ class Handler(BaseHTTPRequestHandler): return get_auth_session(cookies.get(AUTH_COOKIE_NAME), refresh=refresh) def require_auth(self, parsed): + if ( + parsed.path.startswith("/api/camera-preview/") + and self.headers.get("X-Iomatex-Gateway-Authorized") == "1" + and self.client_address[0] in {"127.0.0.1", "::1"} + ): + return True if parsed.path in PUBLIC_PATHS or parsed.path in PUBLIC_API_PATHS: return True session = self.auth_session(refresh=True) @@ -3252,6 +3310,24 @@ class Handler(BaseHTTPRequestHandler): return if not self.require_auth(parsed): return + preview_match = CAMERA_PREVIEW_PATH_RE.fullmatch(parsed.path) + if preview_match: + filename = preview_match.group("file") + if filename == "index.m3u8": + content_type = "application/vnd.apple.mpegurl" + elif filename == "snapshot.jpg": + content_type = "image/jpeg" + else: + content_type = "video/mp4" + self.send_file( + os.path.join(IOMATEX_IP_STREAM_HLS_ROOT, preview_match.group("stream"), filename), + content_type, + extra_headers={ + "Access-Control-Allow-Origin": "*", + "Cache-Control": "no-store" if filename in {"index.m3u8", "snapshot.jpg"} else "public, max-age=30", + }, + ) + return if parsed.path == "/api/status": self.send_json(build_status_payload()) return @@ -3448,6 +3524,54 @@ class Handler(BaseHTTPRequestHandler): return if not self.require_auth(parsed): return + if parsed.path == "/api/camera-preview/start": + payload = self.read_json_body() + stream_id = str((payload or {}).get("stream_id", "")) + input_url = str((payload or {}).get("input_url", "")) + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}", stream_id) or not input_url.startswith("rtsp://"): + self.send_json({"ok": False, "error": "Invalid camera preview request"}, code=400) + return + try: + publish_camera_preview({ + "action": "preview_start", + "stream_id": stream_id, + "input_url": input_url, + }) + wait_camera_preview(stream_id) + self.send_json({ + "ok": True, + "manifest": f"/api/camera-preview/{stream_id}/index.m3u8", + "expires_in": 600, + }) + except Exception as exc: + self.send_json({"ok": False, "error": str(exc)}, code=503) + return + if parsed.path == "/api/camera-preview/snapshot": + payload = self.read_json_body() + stream_id = str((payload or {}).get("stream_id", "")) + input_url = str((payload or {}).get("input_url", "")) + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}", stream_id) or not input_url.startswith("rtsp://"): + self.send_json({"ok": False, "error": "Invalid camera snapshot request"}, code=400) + return + snapshot_path = os.path.join(IOMATEX_IP_STREAM_HLS_ROOT, stream_id, "snapshot.jpg") + try: + previous_mtime_ns = os.stat(snapshot_path).st_mtime_ns + except FileNotFoundError: + previous_mtime_ns = 0 + try: + publish_camera_preview({ + "action": "snapshot", + "stream_id": stream_id, + "input_url": input_url, + }) + wait_camera_snapshot(stream_id, previous_mtime_ns) + self.send_json({ + "ok": True, + "snapshot": f"/api/camera-preview/{stream_id}/snapshot.jpg", + }) + except Exception as exc: + self.send_json({"ok": False, "error": str(exc)}, code=503) + return if parsed.path in ("/api/stages/check", "/api/stages/install"): if self.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() != "application/json": self.send_json({"ok": False, "error": "JSON content type required"}, code=415) diff --git a/stage_ui/console_core/backend/test_camera_preview_contract.py b/stage_ui/console_core/backend/test_camera_preview_contract.py new file mode 100644 index 0000000..b702fb1 --- /dev/null +++ b/stage_ui/console_core/backend/test_camera_preview_contract.py @@ -0,0 +1,23 @@ +import pathlib +import unittest + + +ROOT = pathlib.Path(__file__).with_name("app.py") + + +class CameraPreviewContractTest(unittest.TestCase): + def test_preview_is_gateway_authorized_and_serves_only_expected_files(self): + source = ROOT.read_text(encoding="utf-8") + self.assertIn('X-Iomatex-Gateway-Authorized', source) + self.assertIn('self.client_address[0] in {"127.0.0.1", "::1"}', source) + self.assertIn('CAMERA_PREVIEW_PATH_RE.fullmatch', source) + self.assertIn('snapshot\\.jpg', source) + self.assertIn('"action": "preview_start"', source) + self.assertIn('"action": "snapshot"', source) + self.assertIn('wait_camera_snapshot(stream_id, previous_mtime_ns)', source) + self.assertIn('content_type = "image/jpeg"', source) + self.assertIn('"Access-Control-Allow-Origin": "*"', source) + + +if __name__ == "__main__": + unittest.main() diff --git a/stage_ui/console_core/backend/test_ip_stream_health_contract.py b/stage_ui/console_core/backend/test_ip_stream_health_contract.py new file mode 100644 index 0000000..7fb1aca --- /dev/null +++ b/stage_ui/console_core/backend/test_ip_stream_health_contract.py @@ -0,0 +1,24 @@ +import pathlib +import unittest + + +ROOT = pathlib.Path(__file__).parents[1] + + +class IpStreamHealthContractTest(unittest.TestCase): + def test_streaming_replaces_network_services_in_health(self): + app = (ROOT / "backend" / "app.py").read_text() + provider = (ROOT / "providers" / "00_core_services.py").read_text() + frontend = (ROOT / "frontend" / "console.js").read_text() + + allowed = app.split("allowed_ids = {", 1)[1].split("}", 1)[0] + self.assertIn('"ip_stream"', allowed) + self.assertNotIn('"access_point"', allowed) + self.assertNotIn('"avahi"', allowed) + self.assertIn("def ip_stream_card(ctx):", provider) + self.assertIn('network.access_point || null', frontend) + self.assertIn('network.avahi || null', frontend) + + +if __name__ == "__main__": + unittest.main() diff --git a/stage_ui/console_core/backend/test_stage_updates_ui.js b/stage_ui/console_core/backend/test_stage_updates_ui.js index 4169bc7..0bccc92 100644 --- a/stage_ui/console_core/backend/test_stage_updates_ui.js +++ b/stage_ui/console_core/backend/test_stage_updates_ui.js @@ -9,14 +9,18 @@ const release = {stage:'stage_z2m',current:null,latest:'1.0.0',status:'not_insta const card = {id:'zigbee2mqtt', title:'Zigbee2MQTT', release}; const requests=[]; let confirmed=false; -const context = {window:{}, state:{activeTab:'health',healthServices:{services:[card],updates:{}}}, +const context = {window:{setTimeout:callback=>callback()}, state:{activeTab:'health',healthServices:{services:[card],updates:{}}}, t:x=>x, esc:x=>String(x), renderKeyValueRows:rows=>rows.map(row=>row.value).join(' '), renderServiceCardContent:()=>'
original
', confirmAction:async()=>confirmed, platformDialog:async()=>{}, fetchJson:async(url,options)=>{ requests.push({url,...JSON.parse(options.body)}); return {}; }, - showToast:()=>{}, loadHealth:async()=>{}, renderActiveTab:()=>{}}; + showToast:()=>{}, loadHealth:async()=>{ context.state.healthServices.updates.checking=false; }, renderActiveTab:()=>{}}; vm.createContext(context); vm.runInContext(owner+handlers,context); (async()=>{ + context.state.healthServices.updates.checking=true; + await context.window.__checkStageVersions(); + assert.equal(requests[0].url,'/api/stages/check'); + requests.length=0; assert.match(context.renderServiceCard(card),/original/); assert.match(context.renderServiceCard(card),/Install 1.0.0/); await context.window.__stageVersion('zigbee2mqtt'); diff --git a/stage_ui/console_core/frontend/console.i18n.js b/stage_ui/console_core/frontend/console.i18n.js index b8c0407..93f7594 100644 --- a/stage_ui/console_core/frontend/console.i18n.js +++ b/stage_ui/console_core/frontend/console.i18n.js @@ -62,6 +62,7 @@ "Checking versions...": "Проверка версий…", "Check versions": "Проверить версии", "Last version check": "Последняя проверка версий", + "Release is not published": "Релиз не опубликован", "Cannot check releases on our Git": "Не удалось проверить версии в нашем Git", "See installation log": "Смотрите журнал установки", "Only the selected stage will be installed. Related services may restart and the connection may be interrupted.": "Будет установлена только выбранная стадия. Связанные сервисы могут перезапуститься, соединение может прерваться.", diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js index c25d6b8..60edd38 100644 --- a/stage_ui/console_core/frontend/console.js +++ b/stage_ui/console_core/frontend/console.js @@ -48,7 +48,7 @@ { mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" }, { mode: "custom", label: "Custom", host: "" } ]; - const UI_VERSION = "V 3.1.2"; + const UI_VERSION = "V 3.1.7"; const ITSCREEN_LOG_INITIAL_LINES = 50; const ITSCREEN_LOG_BUFFER_LIMIT = 300; const ITSCREEN_LOG_BATCH_MS = 250; @@ -2252,6 +2252,7 @@ const labels = { latest: "Latest version installed", update_available: "Update available", local_build: "Local build installed", not_installed: "Not installed", unknown: "Installed version is unknown", not_checked: "Version check required", + not_published: "Release is not published", ahead: "Installed version is newer than the published release" }; return t(labels[release.status] || "Unknown"); @@ -2556,6 +2557,7 @@ zigbee2mqtt: 40, cockpit: 50, reverse_tunnel: 60, + ip_stream: 65, display: 70, edge_api: 80 }; @@ -2753,6 +2755,7 @@ is_default_route: network.active_uplink === "eth0" }; const accessPointCard = network.access_point || null; + const avahiCard = network.avahi || null; return `
@@ -2817,6 +2820,7 @@ ${accessPointCard ? `
${renderAccessPointCard(accessPointCard)}
` : ""} + ${avahiCard ? `
${renderServiceCardContent(avahiCard)}
` : ""}
`; } @@ -5247,8 +5251,14 @@ window.__checkStageVersions = async function () { try { await fetchJson("/api/stages/check", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" }); - await loadHealth(); + for (let attempt = 0; attempt < 30; attempt += 1) { + await new Promise(resolve => window.setTimeout(resolve, 500)); + await loadHealth(); + if (!state.healthServices?.updates?.checking) break; + } if (state.activeTab === "health") renderActiveTab(); + const error = state.healthServices?.updates?.error; + if (error) showToast("error", t(error)); } catch (error) { showToast("error", error.message); } }; diff --git a/stage_ui/console_core/frontend/index.html b/stage_ui/console_core/frontend/index.html index c65924f..2608023 100644 --- a/stage_ui/console_core/frontend/index.html +++ b/stage_ui/console_core/frontend/index.html @@ -23,7 +23,7 @@ } catch (error) {} })(); - +
@@ -108,7 +108,7 @@
- - + + diff --git a/stage_ui/console_core/providers/00_core_services.py b/stage_ui/console_core/providers/00_core_services.py index 8b247eb..c0977b4 100644 --- a/stage_ui/console_core/providers/00_core_services.py +++ b/stage_ui/console_core/providers/00_core_services.py @@ -1,4 +1,5 @@ import glob +import json import math import os import re @@ -966,6 +967,41 @@ def access_point_card(ctx): ) +def ip_stream_card(ctx): + unit = ctx["systemd_unit"]("iomatex-ip-stream.service") + installed = unit["installed"] + active = unit["active"] + state, status_text = _lifecycle( + installed, + installed, + active, + failed=unit["active_state"] == "failed", + ) + details = [] + try: + status = json.loads(ctx["read_text"]("/run/iomatex-ip-stream/status.json")) + details = [ + {"label": "Active streams", "value": str(status.get("active_count", 0))}, + {"label": "Stream limit", "value": str(status.get("max_streams", 0))}, + ] + except (OSError, ValueError, TypeError): + if active: + status_text = "Active; waiting for runtime status" + return _service_card( + "ip_stream", + "IP Camera Streaming", + "iomatex-ip-stream.service", + installed, + installed, + active, + state, + status_text, + _short_unit_errors(unit), + [], + details=details, + ) + + def placeholder_card(service_id, title): state, status_text = _lifecycle(False, False, False) return _service_card( @@ -1009,7 +1045,7 @@ def get_cards(ctx): mqtt_bridge_card(ctx), zigbee_card(ctx), reverse_tunnel_card(ctx), - access_point_card(ctx), + ip_stream_card(ctx), display_card(ctx), *managed_system_cards(ctx), ] diff --git a/stage_ui/version.json b/stage_ui/version.json index 9a9f9b5..e3c5bbe 100644 --- a/stage_ui/version.json +++ b/stage_ui/version.json @@ -1,3 +1,3 @@ { - "version": "3.1.2" + "version": "3.1.7" }