diff --git a/docs/WEB-PANEL.md b/docs/WEB-PANEL.md index 82cb5cc..8034f6c 100644 --- a/docs/WEB-PANEL.md +++ b/docs/WEB-PANEL.md @@ -1,6 +1,6 @@ # Веб-пульт AirDef -Пульт работает рядом с Horizon. На карте видны отметки сети, своя техника, объекты и перехватчики. Карточка показывает состояние, источник отметки и связанные записи. В «Истории» можно выбрать налёт, отфильтровать события по времени или ID и собрать доступные звенья цепочки контакта. Нажатие на запись открывает её детали и ближайший сохранённый кадр в пределах пяти игровых секунд. Событие хранит своё точное игровое время. Карта сохраняется примерно раз в секунду, поэтому её время может отличаться. +Пульт работает рядом с Horizon. На карте видны отметки сети, своя техника, объекты и перехватчики. Карточка показывает состояние, источник отметки и связанные записи. В «Истории» можно выбрать налёт, отфильтровать события по времени или ID и собрать доступные звенья цепочки контакта. Под шкалой отмечены попадания, промахи и отказы. События рядом по времени открываются списком из одного маркера. Нажатие на запись или отметку открывает детали и ближайший сохранённый кадр в пределах пяти игровых секунд. Событие хранит своё точное игровое время. Карта сохраняется примерно раз в секунду, поэтому её время может отличаться. ## Запуск на компьютере с игрой @@ -34,9 +34,9 @@ python3 tools/airdef.py web --listen 192.168.1.170 --port 8765 --origin https:// ## Архив и подключение -Сервер хранит журнал в `airdef-panel/history.sqlite3` внутри каталога игры. Он переживает перезапуск игры и пульта. Хранятся до 3 600 снимков карты, 30 000 событий и 400 налётов. В интерфейсе видны пропуски журнала и ограничения хранения. Браузер дополнительно хранит до 600 загруженных событий и 20 открытых исторических кадров. Отвязка устройства очищает браузерный архив. +Сервер хранит журнал в `airdef-panel/history.sqlite3` внутри каталога игры. Он переживает перезапуск игры и пульта. Хранятся до 3 600 снимков карты, 30 000 событий и 400 налётов. В интерфейсе видны пропуски журнала и ограничения хранения. Браузер дополнительно хранит до 600 загруженных событий, 20 открытых исторических кадров и отметки шкалы последних восьми просмотренных налётов. Отвязка устройства очищает браузерный архив. -Для присоединения к уже запущенному Horizon укажите `--attach путь_к_локальному_сокету`. На Windows это JSON-файл с локальным пор­том и токеном Horizon. Для `--dev-mod` путь к данным мода можно задать через `--mod-data`. Пульт опрашивает игру из одного фонового потока. HTTP-клиентам доступны готовые снимки и SQLite; сам сокет Horizon доступен только на ПК. Внутренние команды мода экспортируют ограниченный снимок и подтверждают структурированный сценарий. Сериализация HTTP, обработка подключений и запись архива происходят в процессе пульта. +Для присоединения к уже запущенному Horizon укажите `--attach путь_к_локальному_сокету`. На Windows это JSON-файл с локальным портом и токеном Horizon. Для `--dev-mod` путь к данным мода можно задать через `--mod-data`. Пульт опрашивает игру из одного фонового потока. После первой загрузки браузер получает изменения карты от своей версии. После долгого обрыва связи, перезапуска пульта или смены мира браузер получает полный снимок. Сам сокет Horizon доступен только на ПК. Внутренние команды мода экспортируют ограниченный снимок и подтверждают структурированный сценарий. Сериализация HTTP, обработка подключений и запись архива происходят в процессе пульта. Полезные проверки из каталога проекта @@ -56,3 +56,5 @@ python3 tools/airdef.py test-wasm | Дополнительный медленный запрос | 34,84–35,04 | 35,50–35,64 | Эти числа относятся к короткой записи на Mac. Для большого налёта и Windows сопоставимых замеров времени кадра пока нет. + +В отдельной проверке переподключения карта с 77 комплексами получила 391 байт изменений при полном размере снимка 18 621 байт. Объём обновления зависит от числа изменившихся отметок. diff --git a/tools/test_web_panel.py b/tools/test_web_panel.py index 406298b..bf077b0 100644 --- a/tools/test_web_panel.py +++ b/tools/test_web_panel.py @@ -27,6 +27,9 @@ class PanelTest(unittest.TestCase): self.home = Path(self.tmp.name) self.store = Store(self.home / "db.sqlite") self.launches = [] + self.live_frame = EMPTY + self.world_session = WORLD_SESSION + self.tick = 210 self.bridge = Bridge(None, self.home, self.store, debug=True, transport=self.transport) pairing = Pairing(True, True) self.codes = {role: key for key, role in pairing.codes.items()} @@ -49,9 +52,9 @@ class PanelTest(unittest.TestCase): if words[3] == "snapshot": _, nonce, _, _cursor = words[3:] response = { - "version": 1, "nonce": nonce, "session": WORLD_SESSION, "world": "fixture", - "tick": 210, "live": EMPTY, "catalog": CATALOG, "canLaunch": True, - "enemy": dict(EMPTY, secret="enemy-only"), "truth": [{"label": "truth-only"}], + "version": 1, "nonce": nonce, "session": self.world_session, "world": "fixture", + "tick": self.tick, "live": self.live_frame, "catalog": CATALOG, "canLaunch": True, + "enemy": dict(EMPTY, secret="enemy-only"), "truth": [{"id": 99, "label": "truth-only"}], "raids": [{"id": 1, "start": 200, "length": 15, "active": True, "gap": False, "limited": False, "next": [1, 1, 1], "events": [{"seq": 0, "at": 10, "unit": None, "target": 99, "object": 1, @@ -126,6 +129,58 @@ class PanelTest(unittest.TestCase): self.assertEqual(self.request("/api/launch", method="POST", cookie=operator, body=dict(body, wave=dict(WAVE, counts=[3])))[0], 409) + def test_live_changes_resume_or_resync_without_crossing_perspectives(self): + viewer, analysis = self.pair("viewer"), self.pair("analysis") + self.live_frame = dict(EMPTY, units=[{"id": 1, "health": 1}, {"id": 2}, {"id": 4}], summary={"hits": 0}) + self.bridge.poll() + _, _, base = self.request("/api/live?delta=1", cookie=viewer) + url = f"/api/live?delta=1&after={base['revision']}" + self.assertEqual(self.request(url, cookie=viewer)[0], 204) + + self.tick += 20 + self.live_frame = dict(EMPTY, units=[{"id": 5}, {"id": 4}, {"id": 1, "health": 0.5}]) + self.bridge.poll() + _, _, delta = self.request(url, cookie=viewer) + self.assertEqual(delta["base"], base["revision"]) + self.assertEqual(delta["frameChange"], { + "unset": ["summary"], + "layers": {"units": {"upsert": [{"id": 5}, {"id": 1, "health": 0.5}], "remove": [2], "order": [5, 4, 1]}}, + }) + self.assertNotIn("catalog", delta["change"]["set"]) + self.assertNotIn("truth-only", json.dumps(delta)) + self.assertEqual(self.request(url + "&mode=truth", cookie=viewer)[0], 403) + _, _, truth = self.request(url + "&mode=truth", cookie=analysis) + self.assertEqual(truth["frame"]["contacts"][0]["label"], "truth-only") + + self.bridge.disconnect() + _, _, disconnected = self.request(f"/api/live?delta=1&after={delta['revision']}", cookie=viewer) + self.assertFalse(disconnected["change"]["set"]["connected"]) + self.assertEqual(disconnected["frameChange"], {}) + self.bridge.poll() + _, _, resumed = self.request(f"/api/live?delta=1&after={disconnected['revision']}", cookie=viewer) + self.assertTrue(resumed["change"]["set"]["connected"]) + + for _ in range(self.bridge.revisions.maxlen): + self.bridge.poll() + self.assertEqual(self.request(url, cookie=viewer)[2]["frame"], self.live_frame) + _, _, latest = self.request("/api/live", cookie=viewer) + self.world_session = "abcd" * 4 + self.bridge.poll() + _, _, changed_world = self.request(f"/api/live?delta=1&after={latest['revision']}", cookie=viewer) + self.assertEqual(changed_world["session"], self.world_session) + self.assertIn("frame", changed_world) + + def test_timeline_lists_recorded_outcomes_and_refusals(self): + viewer = self.pair("viewer") + url = f"/api/timeline?session={WORLD_SESSION}&raid=1" + self.assertEqual(self.request(url)[0], 401) + status, _, data = self.request(url, cookie=viewer) + self.assertEqual(status, 200) + self.assertEqual([(event["tick"], event["marker"]) for event in data["events"]], + [(208, "refusal"), (210, "impact")]) + self.assertFalse(data["limited"]) + self.assertEqual(self.request(f"{url}&after={data['revision']}", cookie=viewer)[0], 204) + def test_history_and_gaps_survive_restart(self): cookie = self.pair("viewer") self.bridge.poll() diff --git a/tools/web_remote/bridge.py b/tools/web_remote/bridge.py index 0087d20..602426a 100644 --- a/tools/web_remote/bridge.py +++ b/tools/web_remote/bridge.py @@ -1,4 +1,6 @@ """Single local game bridge. HTTP clients only see cached projections and the archive.""" +from collections import deque +from dataclasses import dataclass, replace import json import os import queue @@ -12,6 +14,8 @@ from pathlib import Path TOKEN = re.compile(r"[0-9a-f]{16,32}\Z") MAX_PACKET = 1 << 20 MAX_REPLY = 1 << 18 +MAP_LAYERS = ("units", "objects", "contacts", "interceptors") +LIVE_REVISIONS = 12 def local_chat(endpoint: Path, text: str): @@ -87,6 +91,68 @@ def public_view(raw): } +def changed_fields(before, after): + change = {} + fields = {key: value for key, value in after.items() if key not in before or before[key] != value} + if fields: + change["set"] = fields + removed = [key for key in before if key not in after] + if removed: + change["unset"] = removed + return change + + +def live_delta(before, after): + old_frame, new_frame = before["frame"], after["frame"] + fields = changed_fields({k: v for k, v in before.items() if k not in {"frame", "revision"}}, + {k: v for k, v in after.items() if k not in {"frame", "revision"}}) + frame = changed_fields({k: v for k, v in old_frame.items() if k not in MAP_LAYERS}, + {k: v for k, v in new_frame.items() if k not in MAP_LAYERS}) + layers = {} + for key in MAP_LAYERS: + old = {row["id"]: row for row in old_frame[key]} + new = {row["id"]: row for row in new_frame[key]} + upsert = [row for ident, row in new.items() if ident not in old or old[ident] != row] + removed = [ident for ident in old if ident not in new] + natural_order = [ident for ident in old if ident in new] + [ident for ident in new if ident not in old] + changes = {} + if upsert: + changes["upsert"] = upsert + if removed: + changes["remove"] = removed + if natural_order != list(new): + changes["order"] = list(new) + if changes: + layers[key] = changes + if layers: + frame["layers"] = layers + return {"base": before["revision"], "revision": after["revision"], "change": fields, "frameChange": frame} + + +@dataclass(frozen=True) +class LiveRevision: + number: int + network: dict + enemy: object = None + truth: object = None + connected: bool = False + updated: object = None + + def project(self, epoch, mode, launch): + result = dict(self.network) + result.update({ + "revision": f"{epoch}-{self.number}-{mode}", "connected": self.connected, + "updated": self.updated, "perspective": mode, + "canLaunch": launch and self.connected and mode == "network" and result.get("canLaunch", False), + }) + if mode == "enemy": + result["frame"] = self.enemy + result.pop("selected", None) + if mode == "truth": + result["frame"] = dict(result.get("frame") or {}, contacts=self.truth or []) + return result + + class Bridge: def __init__(self, endpoint, data, store, *, debug=False, interval=1.0, transport=local_chat): self.endpoint, self.data, self.store = endpoint, data, store @@ -94,11 +160,7 @@ class Bridge: self.lock = threading.Lock() self.stop = threading.Event() self.queue = queue.Queue(maxsize=8) - self.snapshot = None - self.raw_enemy, self.raw_truth = None, None - self.connected = False - self.updated = None - self.revision = 0 + self.revisions = deque([LiveRevision(0, {})], maxlen=LIVE_REVISIONS) self.epoch = secrets.token_hex(8) self.cursors = {} self.thread = threading.Thread(target=self.worker, name="airdef-local-bridge", daemon=True) @@ -122,10 +184,7 @@ class Bridge: backoff = self.interval except (OSError, ValueError, TypeError, KeyError): backoff = min(4.0, backoff * 1.5) - with self.lock: - if self.connected: - self.connected = False - self.revision += 1 + self.disconnect() next_poll = time.monotonic() + backoff try: job = self.queue.get(timeout=min(0.25, self.interval)) @@ -136,8 +195,8 @@ class Bridge: def poll(self): nonce = secrets.token_hex(12) mode = "debug" if self.debug else "public" - epoch = self.snapshot["session"] if self.snapshot else "-" - cursor = epoch + ":" + ",".join(".".join(map(str, [raid, *indices])) for raid, indices in self.cursors.items()) + session = self.revisions[-1].network.get("session", "-") + cursor = session + ":" + ",".join(".".join(map(str, [raid, *indices])) for raid, indices in self.cursors.items()) self.transport(self.endpoint, f"chat /airdef panel snapshot {nonce} {mode} {cursor}") raw = read_json(self.data / "panel-snapshot-v1.json") if raw.get("nonce") != nonce or raw.get("version") != 1 or not TOKEN.fullmatch(raw["session"]): @@ -146,27 +205,28 @@ class Bridge: self.store.append(raw, public) self.cursors = {raid["id"]: raid["next"] for raid in raw["raids"]} with self.lock: - self.snapshot = public - self.raw_enemy, self.raw_truth = raw.get("enemy"), raw.get("truth") - self.connected = True - self.updated = time.time() - self.revision += 1 + number = self.revisions[-1].number + 1 + self.revisions.append(LiveRevision(number, public, raw.get("enemy"), raw.get("truth"), True, time.time())) - def view(self, mode): + def disconnect(self): with self.lock: - result = dict(self.snapshot or {}) - connected = self.connected - result.update({ - "revision": f"{self.epoch}-{self.revision}", "connected": connected, - "updated": self.updated, "perspective": mode, - "canLaunch": connected and mode == "network" and result.get("canLaunch", False), - }) - if mode == "enemy": - result["frame"] = self.raw_enemy - result.pop("selected", None) - if mode == "truth": - result["frame"] = dict(result.get("frame") or {}, contacts=self.raw_truth or []) - return result + current = self.revisions[-1] + if current.connected: + self.revisions.append(replace(current, number=current.number + 1, connected=False)) + + def view(self, mode, *, after=None, delta=False, launch=True): + with self.lock: + current = self.revisions[-1] + previous = next((entry for entry in self.revisions + if after == f"{self.epoch}-{entry.number}-{mode}"), None) if after else None + if previous is current: + return None + result = current.project(self.epoch, mode, launch) + if delta and previous and previous.network.get("session") == result.get("session"): + base = previous.project(self.epoch, mode, launch) + if result.get("session") and base.get("frame") is not None and result.get("frame") is not None: + return live_delta(base, result) + return result def submit(self, key, owner, session, payload): state = self.view("network") diff --git a/tools/web_remote/server.py b/tools/web_remote/server.py index 4055b6c..a204fea 100644 --- a/tools/web_remote/server.py +++ b/tools/web_remote/server.py @@ -26,6 +26,8 @@ ASSETS = { "/index.html": ("index.html", "text/html; charset=utf-8"), "/app.js": ("app.js", "text/javascript; charset=utf-8"), "/map.js": ("map.js", "text/javascript; charset=utf-8"), + "/live.js": ("live.js", "text/javascript; charset=utf-8"), + "/timeline.js": ("timeline.js", "text/javascript; charset=utf-8"), "/app.css": ("app.css", "text/css; charset=utf-8"), "/sw.js": ("sw.js", "text/javascript; charset=utf-8"), "/manifest.webmanifest": ("manifest.webmanifest", "application/manifest+json"), @@ -193,13 +195,18 @@ class Handler(BaseHTTPRequestHandler): raise ValueError("bad perspective") if mode != "network" and not debug: raise APIError(HTTPStatus.FORBIDDEN, "Этот ракурс требует отдельного доступа") - data = self.server.bridge.view(mode) - data["canLaunch"] = data["canLaunch"] and launch - if query.get("after") == data["revision"]: + data = self.server.bridge.view(mode, after=query.get("after"), delta=query.get("delta") == "1", launch=launch) + if data is None: return self.reply(HTTPStatus.NO_CONTENT) return self.reply(HTTPStatus.OK, data) if (verb, path) == ("GET", "/api/raids"): return self.reply(HTTPStatus.OK, self.server.store.raids()) + if (verb, path) == ("GET", "/api/timeline"): + session, raid = query.get("session", ""), number(query.get("raid")) + if not TOKEN.fullmatch(session) or raid is None: + raise ValueError("bad timeline") + data = self.server.store.timeline(session, raid, after=query.get("after")) + return self.reply(HTTPStatus.NO_CONTENT) if data is None else self.reply(HTTPStatus.OK, data) if (verb, path) == ("GET", "/api/chain"): result = self.server.store.chain(number(query.get("event"))) if result is None: diff --git a/tools/web_remote/static/app.css b/tools/web_remote/static/app.css index 29679f4..6d12013 100644 --- a/tools/web_remote/static/app.css +++ b/tools/web_remote/static/app.css @@ -103,3 +103,16 @@ dialog::backdrop { background: #02080dc9; } #launch-status:empty, #pair-error:empty, #map-status:empty { display: none; } @media (min-width: 801px) and (min-height: 680px) { .map-column { position: sticky; top: .75rem; } } @media (max-width: 800px) { .map-wrap canvas { height: clamp(240px, 46dvh, 580px); } } + +.timeline-marker-rail { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: .1rem; } +.timeline-marker-slot { display: flex; justify-content: center; min-width: 0; } +.timeline-marker { min-width: 44px; padding: .25rem; border-color: #526977; font-size: .9rem; } +.timeline-marker[data-type="impact"] { color: var(--danger); } +.timeline-marker[data-type="refusal"] { color: var(--warning); } +.timeline-marker[data-type="miss"] { color: #b7c8fa; } +.timeline-marker[data-type="mixed"] { color: var(--accent); } +.timeline-marker.selected, .timeline-marker[aria-expanded="true"] { border-color: var(--accent); background: #193b40; } +.timeline-marker-details:not(:empty) { display: grid; gap: .35rem; max-height: 220px; overflow-y: auto; margin-top: .4rem; } +.timeline-marker-heading { margin: 0; font-size: .8rem; } +.timeline-marker-choice { text-align: left; font-size: .82rem; overflow-wrap: anywhere; } +.timeline-marker-choice[aria-current="true"] { border-color: var(--accent); } diff --git a/tools/web_remote/static/app.js b/tools/web_remote/static/app.js index 25795d4..ebc9e56 100644 --- a/tools/web_remote/static/app.js +++ b/tools/web_remote/static/app.js @@ -1,4 +1,6 @@ import {createMap} from "./map.js"; +import {applyLiveUpdate} from "./live.js"; +import {createTimeline} from "./timeline.js"; const $ = id => document.getElementById(id); const make = (tag, text, cls) => { @@ -76,12 +78,16 @@ let selected = prefs.selected, connected = false, http = false, polling = false, let events = [], raids = [], raid = null, more = false, historyGeneration = 0, frameGeneration = 0, chainGeneration = 0; let eventTimer, frameTimer, receiptTimer, latestRequest = read("launch-request", null), installPrompt; let offlineEvents = [], offlineFrames = {}, offlineRaids = {raids: []}; +let offlineTimelines = {}, selectedEvent = null, timelineGeneration = 0; +const timelineRequests = new Map(); +const timeline = createTimeline($("timeline-markers"), openEvent, time); const eventFields = {unit: "unit", contact: "target", object: "object"}; const eventOrder = {observations: 0, decisions: 1, events: 2}; let latestObject = {key: "", checked: 0, event: null}; const map = createMap($("map"), { onSelect: key => select(key), onView: view => { + if (historical) return; prefs.views[perspective] = view; write("view", prefs); }, @@ -110,9 +116,10 @@ function showAuth() { } function updateStatus() { const status = $("connection"); + const updated = live?.updated ?? network?.updated; status.className = connected ? "success" : "warning"; status.textContent = connected ? `Игра в сети · ${when(live?.updated)}` - : auth ? live?.updated ? `Нет связи · снимок от ${when(live.updated)}` : "Ожидание игры" + : auth ? updated ? `Нет связи · снимок от ${when(updated)}` : "Ожидание игры" : http ? "Ожидает подключения" : "Нет соединения"; $("logout").disabled = !http; } @@ -133,6 +140,7 @@ function draw() { const frame = activeFrame(); map.draw(frame, {selected, layers: prefs.layers}); $("return-live").hidden = !historical; + $("history-live").hidden = !historical; $("perspective").disabled = !!historical; const status = []; if (historical) { @@ -241,6 +249,11 @@ async function updateObjectEvent(opened) { } function forgetCachedData() { + clearTimeout(frameTimer); + clearTimeout(eventTimer); + frameGeneration++; + historyGeneration++; + clearEvent(); cache("all", null); network = live = historical = null; connected = false; @@ -248,12 +261,14 @@ function forgetCachedData() { offlineEvents = []; offlineFrames = {}; offlineRaids = {raids: []}; + offlineTimelines = {}; + timelineGeneration++; + timelineRequests.clear(); events = []; raids = []; raid = null; latestRequest = null; write("launch-request", null); - $("event-card").hidden = true; } async function poll() { @@ -267,20 +282,30 @@ async function poll() { showAuth(); } const mode = perspective; - const params = new URLSearchParams({mode}); - if (live?.perspective === mode) params.set("after", live.revision || ""); - const data = await api(`/live?${params}`); + const account = auth; + const base = live?.perspective === mode ? live : null; + const params = new URLSearchParams({mode, delta: "1"}); + if (base?.revision) params.set("after", base.revision); + const update = await api(`/live?${params}`); + let data = update ? applyLiveUpdate(base, update) : null; + if (update && !data) data = await api(`/live?${new URLSearchParams({mode})}`); + if (account !== auth || mode !== perspective) return; http = true; - if (mode !== perspective) return; if (data) { live = data; connected = data.connected; if (mode === "network" && data.frame) { if (prefs.world && prefs.world !== data.world) { - prefs.selected = selected = null; - map.restore(null); + prefs.selected = null; + delete prefs.views.network; + if (!historical) { + selected = null; + map.restore(null); + } } + const worldChanged = prefs.world !== data.world; prefs.world = data.world; + if (worldChanged) write("view", prefs); network = data; if (data.connected) cache("network", data); } @@ -293,7 +318,11 @@ async function poll() { await refreshRaids(); await newEvents(); } + } else { + connected = Boolean(base?.connected); + drawScenario(); } + if (tab === "history") refreshTimeline(); if (latestRequest && auth.permissions.launch) watchReceipt(latestRequest); } catch (error) { if (error.status === 401) { @@ -325,39 +354,56 @@ function setTab(next) { $("history-panel").hidden = next !== "history"; $("scenario-panel").hidden = next !== "scenario"; if (next === "history") { - refreshRaids().then(() => readEvents()); + refreshRaids().then(() => { + readEvents(); + refreshTimeline(); + }); } draw(); } function chooseRaid(value) { + clearTimeout(frameTimer); + frameGeneration++; + clearEvent(); raid = raids.find(r => `${r.session}:${r.raid}` === value) || null; $("event-since").disabled = $("event-until").disabled = !raid; $("timeline").disabled = !raid; $("timeline").max = raid?.length || 0; $("timeline").value = $("timeline").max; - $("timeline-caption").textContent = raid ? `Начало · ${time(raid.length)}` : ""; - $("event-card").hidden = true; + $("timeline-caption").textContent = raid ? `Момент ${time(raid.length)}` : ""; + if (raid) loadFrame(raid.session, raid.start + raid.length, raid.start); + else { + historical = null; + selected = perspective === "network" ? prefs.selected : null; + map.restore(prefs.views[perspective]); + draw(); + } + refreshTimeline(); } async function refreshRaids() { let data; + const generation = timelineGeneration; try { data = await api("/raids"); + if (generation !== timelineGeneration) return; offlineRaids = data; cache("raids", data); } catch { data = offlineRaids; } + if (generation !== timelineGeneration) return; const previous = $("raid").value; const incoming = data?.raids || []; - const changed = incoming.length !== raids.length || incoming.some((r, i) => - r.session !== raids[i]?.session || r.raid !== raids[i]?.raid || r.length !== raids[i]?.length || r.active !== raids[i]?.active); - if (!changed) return; - raids = incoming; - const options = [new Option("Все налёты", "")]; - for (const r of raids) { - const date = new Date(r.time * 1000).toLocaleString("ru-RU", {dateStyle: "short", timeStyle: "short"}); - options.push(new Option(`№${r.raid} · ${date}${r.active ? " · идёт" : ""}`, `${r.session}:${r.raid}`)); + const optionsChanged = incoming.length !== raids.length || incoming.some((r, i) => + raidKey(r) !== raidKey(raids[i]) || r.active !== raids[i]?.active); + if (optionsChanged) { + const options = [new Option("Все налёты", "")]; + for (const r of incoming) { + const date = new Date(r.time * 1000).toLocaleString("ru-RU", {dateStyle: "short", timeStyle: "short"}); + options.push(new Option(`№${r.raid} · ${date}${r.active ? " · идёт" : ""}`, raidKey(r))); + } + $("raid").replaceChildren(...options); + $("raid").value = options.some(o => o.value === previous) ? previous : ""; } - $("raid").replaceChildren(...options); - $("raid").value = options.some(o => o.value === previous) ? previous : ""; + raids = incoming; const old = raid; raid = raids.find(r => `${r.session}:${r.raid}` === $("raid").value) || null; $("event-since").disabled = $("event-until").disabled = !raid; @@ -365,6 +411,51 @@ async function refreshRaids() { $("timeline").max = raid?.length || 0; if (!historical || !old) $("timeline").value = $("timeline").max; } +function raidKey(value) { + return value ? `${value.session}:${value.raid}` : ""; +} +function paintTimeline() { + const saved = offlineTimelines[raidKey(raid)]; + const markers = saved?.events ?? offlineEvents.filter(event => raidKey(event) === raidKey(raid)); + timeline.render(raid, markers, selectedEvent); + const status = $("timeline-status"); + status.hidden = !raid || !saved?.limited; + status.textContent = "На шкале показана часть отметок. Все доступные события есть в журнале."; +} +async function refreshTimeline() { + paintTimeline(); + if (!raid || !http) return; + const key = raidKey(raid); + const previous = timelineRequests.get(key); + const interval = raid.active ? 4000 : 10000; + if (previous?.pending || (previous && previous.active === raid.active && Date.now() - previous.at < interval)) return; + const generation = timelineGeneration; + const params = new URLSearchParams({session: raid.session, raid: raid.raid}); + if (offlineTimelines[key]?.revision) params.set("after", offlineTimelines[key].revision); + const request = {pending: true, at: Date.now(), active: raid.active}; + timelineRequests.set(key, request); + try { + const data = await api(`/timeline?${params}`); + if (!data || generation !== timelineGeneration) return; + delete offlineTimelines[key]; + offlineTimelines[key] = data; + for (const old of Object.keys(offlineTimelines).slice(0, -8)) { + delete offlineTimelines[old]; + timelineRequests.delete(old); + } + cache("timelines", offlineTimelines); + if (raidKey(raid) === key) paintTimeline(); + } catch { + if (timelineRequests.get(key) === request) timelineRequests.delete(key); + } finally { + request.pending = false; + } +} +function clearEvent() { + chainGeneration++; + selectedEvent = null; + $("event-card").hidden = true; +} function historyParams(before) { const params = new URLSearchParams({limit: "70"}); if (raid) { @@ -440,9 +531,12 @@ function renderEvents(saved) { () => openEvent(event))); $("events").replaceChildren(...(items.length ? items : [make("p", "События для этого фильтра отсутствуют", "empty")])); $("history-more").hidden = !more; + paintTimeline(); } async function openEvent(event) { + clearTimeout(frameTimer); const chainRequest = ++chainGeneration; + selectedEvent = event.id; const thisRaid = raids.find(r => r.session === event.session && r.raid === event.raid); const start = thisRaid?.start ?? event.tick - event.data.at; const nodes = [make("h3", event.label)]; @@ -462,21 +556,25 @@ async function openEvent(event) { $("event-card").replaceChildren(...nodes); $("event-card").hidden = false; if (thisRaid) { + const changed = raidKey(raid) !== raidKey(thisRaid); raid = thisRaid; $("event-since").disabled = $("event-until").disabled = false; $("raid").value = `${raid.session}:${raid.raid}`; $("timeline").max = raid.length; $("timeline").value = event.data.at; $("timeline").disabled = false; + if (changed) readEvents(); } + refreshTimeline(); selected = event.unit != null ? `unit:${event.unit}` : event.object != null ? `object:${event.object}` : event.target != null ? `contact:${event.target}` : null; - await Promise.all([loadFrame(event.session, event.tick, start), showChain(event, chainRequest)]); + await Promise.all([loadFrame(event.session, event.tick, start, true), showChain(event, chainRequest)]); } async function showChain(event, generation) { let chain; try { chain = await api(`/chain?event=${event.id}`); + if (generation !== chainGeneration) return; rememberEvents(chain.events); } catch { chain = { @@ -503,7 +601,7 @@ async function showChain(event, generation) { } card.append(items); } -async function loadFrame(session, tick, start) { +async function loadFrame(session, tick, start, focus = false) { const generation = ++frameGeneration; const key = `${session}:${tick}`; let scene; @@ -526,7 +624,7 @@ async function loadFrame(session, tick, start) { historical = {requested: tick, start, frame: frame && Math.abs(frame.tick - tick) <= 100 ? frame : null}; $("timeline-caption").textContent = `Момент ${time(tick - start)}`; draw(); - if (selected) map.focus(selected); + if (focus && selected) map.focus(selected); } function setupScenario() { @@ -677,22 +775,30 @@ $("perspective").addEventListener("change", () => { draw(); poll(); }); -$("return-live").addEventListener("click", () => { +function returnLive() { + clearTimeout(frameTimer); + clearEvent(); frameGeneration++; historical = null; selected = prefs.selected; perspective = "network"; $("perspective").value = "network"; live = network; + map.restore(prefs.views.network); setTab("live"); poll(); -}); +} +$("return-live").addEventListener("click", returnLive); +$("history-live").addEventListener("click", returnLive); $("raid").addEventListener("change", () => { chooseRaid($("raid").value); readEvents(); }); $("timeline").addEventListener("input", () => { clearTimeout(frameTimer); + frameGeneration++; + clearEvent(); + paintTimeline(); const at = Number($("timeline").value); $("timeline-caption").textContent = `Момент ${time(at)}`; frameTimer = setTimeout(() => { @@ -739,12 +845,13 @@ $("install").addEventListener("click", async () => { if ("serviceWorker" in navigator && window.isSecureContext) navigator.serviceWorker.register("./sw.js").catch(() => {}); async function start() { - const [cachedAuth, savedNetwork, cachedEvents, cachedRaids, cachedFrames] = await Promise.all( - ["auth", "network", "events", "raids", "frames"].map(key => cache(key))); + const [cachedAuth, savedNetwork, cachedEvents, cachedRaids, cachedFrames, cachedTimelines] = await Promise.all( + ["auth", "network", "events", "raids", "frames", "timelines"].map(key => cache(key))); network = live = savedNetwork ?? null; offlineEvents = cachedEvents ?? []; offlineRaids = cachedRaids ?? {raids: []}; offlineFrames = cachedFrames ?? {}; + offlineTimelines = cachedTimelines ?? {}; try { auth = await api("/session"); http = true; diff --git a/tools/web_remote/static/index.html b/tools/web_remote/static/index.html index 1df7652..ab1662e 100644 --- a/tools/web_remote/static/index.html +++ b/tools/web_remote/static/index.html @@ -69,7 +69,11 @@

История боя

+
+ +

+
@@ -79,7 +83,6 @@

-
diff --git a/tools/web_remote/static/live.js b/tools/web_remote/static/live.js new file mode 100644 index 0000000..321c1d4 --- /dev/null +++ b/tools/web_remote/static/live.js @@ -0,0 +1,20 @@ +function mergeFields(base, change) { + const result = {...base, ...change.set}; + for (const key of change.unset || []) delete result[key]; + return result; +} + +export function applyLiveUpdate(base, update) { + if (!Object.hasOwn(update, "base")) return update; + if (!base?.frame || update.base !== base.revision) return null; + + const result = {...mergeFields(base, update.change), revision: update.revision}; + result.frame = mergeFields(base.frame, update.frameChange); + for (const [layer, {remove = [], upsert = [], order}] of Object.entries(update.frameChange.layers || {})) { + const entities = new Map(base.frame[layer].map(row => [row.id, row])); + for (const id of remove) entities.delete(id); + for (const entity of upsert) entities.set(entity.id, entity); + result.frame[layer] = order ? order.map(id => entities.get(id)) : [...entities.values()]; + } + return result; +} diff --git a/tools/web_remote/static/sw.js b/tools/web_remote/static/sw.js index 1c3e22a..29ecd85 100644 --- a/tools/web_remote/static/sw.js +++ b/tools/web_remote/static/sw.js @@ -1,6 +1,6 @@ /* Cache only the public, versioned application shell. API responses are never cached. */ -const CACHE = 'airdef-shell-v7'; -const FILES = ['index.html', 'app.css', 'app.js', 'map.js', 'manifest.webmanifest', 'icons/icon-192.png', 'icons/icon-512.png']; +const CACHE = 'airdef-shell-v8'; +const FILES = ['index.html', 'app.css', 'app.js', 'map.js', 'live.js', 'timeline.js', 'manifest.webmanifest', 'icons/icon-192.png', 'icons/icon-512.png']; const scope = new URL(self.registration.scope); const shellUrls = FILES.map(path => new URL(path, scope).href); diff --git a/tools/web_remote/static/timeline.js b/tools/web_remote/static/timeline.js new file mode 100644 index 0000000..7ea2bc0 --- /dev/null +++ b/tools/web_remote/static/timeline.js @@ -0,0 +1,99 @@ +// Markers are grouped into a small number of time buckets so every control +// remains large enough to tap, including on narrow screens. +const names = { impact: "Попадание", refusal: "Отказ", miss: "Промах" }; +const symbols = {impact: "◆", miss: "×", refusal: "!"}; +const refusalLabels = new Set([ + "Огонь запрещён", "Комплекс на марше", "Перезарядка", "Ожидает пополнения", + "Ожидает данных о рельефе", "Траектория перекрыта", + "Орудие недоступно", "Пусковая недоступна", "Нет свежего захвата", "Вне дальности орудия", +]); + +function markerType(event) { + if (Object.hasOwn(names, event.marker)) return event.marker; + const label = event.label || ""; + if (label.startsWith("Попадание") || label === "Комплекс уничтожен") return "impact"; + if (label.startsWith("Промах")) return "miss"; + if (event.kind === "decisions" && refusalLabels.has(label)) return "refusal"; + return null; +} + +export function createTimeline(container, onOpen, clock) { + let expanded = null; + let raidKey = null; + let signature = ""; + return { + render(raid, events, selectedId) { + const key = raid ? `${raid.session}:${raid.raid}` : null; + if (key !== raidKey) { expanded = null; raidKey = key; } + const buckets = Array.from({ length: 5 }, () => []); + for (const event of events) { + const type = markerType(event); + const at = event.data?.at; + if (!raid || !type || !Number.isFinite(at) || at < 0) continue; + // A terminal event can be a tick beyond the sampled replay length. + const slot = Math.min(4, Math.floor(at / Math.max(1, raid.length) * 5)); + buckets[slot].push({ event, type, at }); + } + const next = JSON.stringify([key, expanded, selectedId, buckets.map(bucket => bucket.map(item => item.event.id))]); + if (next === signature) return; + signature = next; + const focused = container.contains(document.activeElement) ? document.activeElement.dataset.markerFocus : null; + const oldScroll = container.querySelector(".timeline-marker-details")?.scrollTop ?? 0; + container.replaceChildren(); + if (buckets.every(bucket => !bucket.length)) return; + const rail = document.createElement("div"); + rail.className = "timeline-marker-rail"; + rail.setAttribute("role", "group"); + rail.setAttribute("aria-label", "Маркеры событий повтора"); + const details = document.createElement("div"); + details.className = "timeline-marker-details"; + for (const [index, bucket] of buckets.entries()) { + const slot = document.createElement("div"); + slot.className = "timeline-marker-slot"; + rail.append(slot); + if (!bucket.length) continue; + bucket.sort((a, b) => a.at - b.at || a.event.id - b.event.id); + const button = document.createElement("button"); + button.type = "button"; + button.className = "timeline-marker"; + button.dataset.markerFocus = `group-${index}`; + const types = [...new Set(bucket.map(item => item.type))]; + button.dataset.type = types.length === 1 ? types[0] : "mixed"; + const description = types.map(type => `${names[type]} × ${bucket.filter(item => item.type === type).length}`).join(", "); + const span = bucket.length === 1 ? clock(bucket[0].at) : `${clock(bucket[0].at)}–${clock(bucket.at(-1).at)}`; + button.setAttribute("aria-label", `${span} · ${description} · ${bucket.length === 1 ? bucket[0].event.label : `${bucket.length} событий`}`); + if (bucket.some(item => String(item.event.id) === String(selectedId))) button.classList.add("selected"); + const primary = Object.keys(symbols).find(type => types.includes(type)); + button.textContent = bucket.length === 1 ? symbols[primary] : `${symbols[primary]} ${bucket.length}`; + if (bucket.length > 1) button.setAttribute("aria-expanded", String(expanded === index)); + button.addEventListener("click", () => { + if (bucket.length === 1) { onOpen(bucket[0].event); return; } + expanded = expanded === index ? null : index; + this.render(raid, events, selectedId); + }); + slot.append(button); + if (expanded === index && bucket.length > 1) { + const heading = document.createElement("p"); + heading.className = "muted timeline-marker-heading"; + heading.textContent = `Событий в группе ${bucket.length}`; + details.append(heading); + for (const { event, at } of bucket) { + const choice = document.createElement("button"); + choice.type = "button"; + choice.className = "timeline-marker-choice"; + choice.dataset.markerFocus = `event-${event.id}`; + choice.textContent = `${clock(at)} · ${event.label}`; + if (String(event.id) === String(selectedId)) choice.setAttribute("aria-current", "true"); + choice.addEventListener("click", () => onOpen(event)); + details.append(choice); + } + } + } + container.append(rail, details); + details.scrollTop = oldScroll; + if (focused) { + [...container.querySelectorAll("button")].find(node => node.dataset.markerFocus === focused)?.focus({preventScroll: true}); + } + }, + }; +} diff --git a/tools/web_remote/store.py b/tools/web_remote/store.py index 6d9bdc5..23521f0 100644 --- a/tools/web_remote/store.py +++ b/tools/web_remote/store.py @@ -12,7 +12,16 @@ MAX_FRAMES = 3600 MAX_FRAME_DISTANCE_TICKS = 100 MAX_EVENTS = 30000 MAX_RAIDS = 400 +MAX_TIMELINE_MARKERS = 480 SESSION_AGE = 30 * 24 * 60 * 60 +TIMELINE_LABELS = { + "Попадание по объекту": "impact", "Попадание по комплексу": "impact", "Комплекс уничтожен": "impact", + "Промах перехватчика": "miss", "Промах очереди": "miss", + "Огонь запрещён": "refusal", "Комплекс на марше": "refusal", "Перезарядка": "refusal", + "Ожидает пополнения": "refusal", "Ожидает данных о рельефе": "refusal", "Траектория перекрыта": "refusal", + "Орудие недоступно": "refusal", "Пусковая недоступна": "refusal", "Нет свежего захвата": "refusal", + "Вне дальности орудия": "refusal", +} def compact(value): @@ -184,6 +193,31 @@ class Store: "context": context, "limited": len(rows) > 40, } + def timeline(self, session, raid, after=None): + placeholders = ",".join("?" for _ in TIMELINE_LABELS) + matching = f"FROM events WHERE session=? AND raid=? AND label IN ({placeholders})" + args = (session, raid, *TIMELINE_LABELS) + with self.lock: + count, last = self.db.execute(f"SELECT count(*), coalesce(max(id), 0) {matching}", args).fetchone() + revision = f"{count}:{last}" + if after == revision: + return None + rows = self.db.execute(f"SELECT * {matching} ORDER BY tick, id", args).fetchall() + markers = [] + for marker in ("impact", "miss", "refusal"): + candidates = [row for row in rows if TIMELINE_LABELS[row["label"]] == marker] + available = MAX_TIMELINE_MARKERS - len(markers) + if not available: + break + if len(candidates) > available: + if available == 1: + candidates = candidates[-1:] + else: + candidates = [candidates[i * (len(candidates) - 1) // (available - 1)] for i in range(available)] + markers.extend(dict(event_row(row), marker=marker) for row in candidates) + markers.sort(key=lambda event: (event["tick"], event["id"])) + return {"events": markers, "limited": len(markers) < len(rows), "revision": revision} + def frame(self, session, tick): with self.lock: before = self.db.execute("""SELECT data, tick FROM frames