Add the AirDef tablet web panel and battle archive (#153)
This commit is contained in:
@@ -0,0 +1,204 @@
|
||||
"""Single local game bridge. HTTP clients only see cached projections and the archive."""
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import re
|
||||
import secrets
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
TOKEN = re.compile(r"[0-9a-f]{16,32}\Z")
|
||||
MAX_PACKET = 1 << 20
|
||||
MAX_REPLY = 1 << 18
|
||||
|
||||
|
||||
def local_chat(endpoint: Path, text: str):
|
||||
"""Use Horizon's local transport, with no arbitrary commands from HTTP."""
|
||||
if not text.startswith("chat /airdef panel ") or "\n" in text or "\r" in text:
|
||||
raise ValueError("Invalid local bridge command")
|
||||
if os.name == "nt" or endpoint.suffix == ".json":
|
||||
config = read_json(endpoint, 4096)
|
||||
port, token = config["port"], config["token"]
|
||||
if type(port) is not int or not 1 <= port <= 65535 or not re.fullmatch(r"[a-zA-Z0-9_-]{16,256}", token):
|
||||
raise ValueError("Invalid local control endpoint")
|
||||
connection = socket.create_connection(("127.0.0.1", port), timeout=2.5)
|
||||
auth = f"auth {token}\n"
|
||||
else:
|
||||
connection = socket.socket(socket.AF_UNIX)
|
||||
connection.settimeout(2.5)
|
||||
try:
|
||||
connection.connect(str(endpoint))
|
||||
except OSError:
|
||||
connection.close()
|
||||
raise
|
||||
auth = None
|
||||
with connection, connection.makefile("rb") as lines:
|
||||
if auth:
|
||||
connection.sendall(auth.encode("ascii"))
|
||||
if not read_line(lines).get("ok"):
|
||||
raise OSError("Horizon rejected the local pairing")
|
||||
connection.sendall((text + "\n").encode("ascii"))
|
||||
result = read_line(lines)
|
||||
if result.get("error"):
|
||||
raise OSError(str(result["error"]))
|
||||
return result
|
||||
|
||||
|
||||
def read_line(stream):
|
||||
raw = stream.readline(MAX_REPLY + 1)
|
||||
if len(raw) > MAX_REPLY or not raw.endswith(b"\n"):
|
||||
raise ValueError("Invalid reply from Horizon")
|
||||
return json.loads(raw)
|
||||
|
||||
|
||||
def read_json(path, limit=MAX_PACKET):
|
||||
with path.open("rb") as stream:
|
||||
data = stream.read(limit + 1)
|
||||
if len(data) > limit:
|
||||
raise ValueError("Bridge packet exceeds its size limit")
|
||||
return json.loads(data)
|
||||
|
||||
|
||||
def validate_wave(payload, catalog):
|
||||
if type(payload) is not dict or set(payload) != {"counts", "distance", "approach", "aim"}:
|
||||
raise ValueError("Укажите состав, дальность, подход и цель сценария")
|
||||
counts = payload["counts"]
|
||||
distance, approach, aim = (payload[key] for key in ("distance", "approach", "aim"))
|
||||
if (type(counts) is not list or len(counts) != len(catalog["kinds"]) or
|
||||
any(type(n) is not int or not 0 <= n <= 80 for n in counts) or not any(counts)):
|
||||
raise ValueError("Укажите от 0 до 80 аппаратов каждого типа, хотя бы один суммарно")
|
||||
low, high = catalog["distance"]
|
||||
if type(distance) is not int or not low <= distance <= high:
|
||||
raise ValueError(f"Дальность должна быть целым числом от {low:.0f} до {high:.0f}")
|
||||
if type(approach) is not int or not 0 <= approach < len(catalog["approaches"]):
|
||||
raise ValueError("Неизвестный подход")
|
||||
if type(aim) is not int or not 0 <= aim < len(catalog["aims"]):
|
||||
raise ValueError("Неизвестная цель сценария")
|
||||
return f"{approach}:{distance}:{aim}:" + ",".join(map(str, counts))
|
||||
|
||||
|
||||
def public_view(raw):
|
||||
return {
|
||||
"version": 1, "session": raw["session"], "world": raw["world"], "tick": raw["tick"],
|
||||
"frame": raw["live"], "catalog": raw["catalog"],
|
||||
"selected": raw.get("selected"), "canLaunch": raw["canLaunch"],
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
self.debug, self.interval, self.transport = debug, interval, transport
|
||||
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.epoch = secrets.token_hex(8)
|
||||
self.cursors = {}
|
||||
self.thread = threading.Thread(target=self.worker, name="airdef-local-bridge", daemon=True)
|
||||
|
||||
def begin(self):
|
||||
self.thread.start()
|
||||
|
||||
def close(self):
|
||||
self.stop.set()
|
||||
if self.thread.is_alive():
|
||||
self.thread.join(timeout=8)
|
||||
|
||||
def worker(self):
|
||||
next_poll = time.monotonic()
|
||||
backoff = self.interval
|
||||
while not self.stop.is_set():
|
||||
now = time.monotonic()
|
||||
if now >= next_poll:
|
||||
try:
|
||||
self.poll()
|
||||
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
|
||||
next_poll = time.monotonic() + backoff
|
||||
try:
|
||||
job = self.queue.get(timeout=min(0.25, self.interval))
|
||||
except queue.Empty:
|
||||
continue
|
||||
self.dispatch(*job)
|
||||
|
||||
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())
|
||||
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"]):
|
||||
raise ValueError("Snapshot does not belong to this request")
|
||||
public = public_view(raw)
|
||||
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
|
||||
|
||||
def view(self, mode):
|
||||
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
|
||||
|
||||
def submit(self, key, owner, session, payload):
|
||||
state = self.view("network")
|
||||
# A retry obtains the stored receipt even if the game went away meanwhile.
|
||||
if "catalog" not in state:
|
||||
raise ValueError("Игра ещё не передала каталог. Статус принятого запроса доступен по его ID.")
|
||||
encoded = validate_wave(payload, state["catalog"])
|
||||
prior = self.store.previous_launch(key, owner, session, encoded)
|
||||
if prior:
|
||||
return prior
|
||||
if not state["canLaunch"] or session != state.get("session"):
|
||||
raise ValueError("Игра недоступна для запуска. Вернитесь к текущему бою.")
|
||||
receipt, created = self.store.reserve_launch(key, owner, session, encoded)
|
||||
if created:
|
||||
try:
|
||||
self.queue.put_nowait((key, session, encoded))
|
||||
except queue.Full:
|
||||
self.store.complete_launch(key, "rejected", "Очередь занята. Проверьте состояние игры.")
|
||||
return self.store.launch(key, owner)
|
||||
return receipt
|
||||
|
||||
def dispatch(self, key, session, encoded):
|
||||
state = self.view("network")
|
||||
if not state["canLaunch"] or state.get("session") != session:
|
||||
self.store.complete_launch(key, "rejected", "Игровая сессия или режим сменились")
|
||||
return
|
||||
self.store.complete_launch(key, "dispatching", "Запрос передан игре")
|
||||
try:
|
||||
self.transport(self.endpoint, f"chat /airdef panel launch {key} {session} {encoded}")
|
||||
receipt = read_json(self.data / "panel-receipt-v1.json", 4096)
|
||||
if receipt["id"] != key or type(receipt["accepted"]) is not bool:
|
||||
raise ValueError("Receipt does not belong to this request")
|
||||
self.store.complete_launch(key, "accepted" if receipt["accepted"] else "rejected", str(receipt["message"]))
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
self.store.complete_launch(key, "unknown", "Игра могла принять сценарий. Проверьте состояние карты.")
|
||||
@@ -0,0 +1,346 @@
|
||||
"""Optionally serve the AirDef PWA on a trusted LAN HTTPS origin."""
|
||||
import argparse
|
||||
import contextlib
|
||||
from http import HTTPStatus
|
||||
from http.cookies import CookieError, SimpleCookie
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import ssl
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from .bridge import Bridge, TOKEN
|
||||
from .store import SESSION_AGE, Store, compact
|
||||
|
||||
STATIC = Path(__file__).with_name("static")
|
||||
COOKIE = "airdef_panel"
|
||||
MAX_BODY = 8192
|
||||
ASSETS = {
|
||||
"/": ("index.html", "text/html; charset=utf-8"),
|
||||
"/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"),
|
||||
"/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"),
|
||||
**{f"/icons/icon-{size}.png": (f"icons/icon-{size}.png", "image/png") for size in (192, 512)},
|
||||
}
|
||||
|
||||
|
||||
class APIError(Exception):
|
||||
def __init__(self, status, message):
|
||||
self.status, self.message = status, message
|
||||
|
||||
|
||||
class Pairing:
|
||||
def __init__(self, allow_launch, allow_debug):
|
||||
roles = ["viewer"]
|
||||
if allow_launch:
|
||||
roles.append("operator")
|
||||
if allow_debug:
|
||||
roles.append("analysis")
|
||||
self.codes = {secrets.token_urlsafe(12): role for role in roles}
|
||||
self.expires = time.monotonic() + 10 * 60
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def claim(self, code):
|
||||
with self.lock:
|
||||
if time.monotonic() < self.expires:
|
||||
return self.codes.pop(code, None)
|
||||
return None
|
||||
|
||||
|
||||
class PanelServer(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
request_queue_size = 24
|
||||
|
||||
def __init__(self, bind, origin, store, bridge, pairing, *, tls=None, allow_launch=False, allow_debug=False):
|
||||
self.origin = origin
|
||||
self.host_header = urlsplit(origin).netloc.casefold()
|
||||
self.secure = origin.startswith("https:")
|
||||
self.store, self.bridge, self.pairing = store, bridge, pairing
|
||||
self.allow_launch, self.allow_debug = allow_launch, allow_debug
|
||||
self.connections = threading.BoundedSemaphore(24)
|
||||
self.tls = tls
|
||||
super().__init__(bind, Handler)
|
||||
|
||||
def get_request(self):
|
||||
conn, addr = super().get_request()
|
||||
conn.settimeout(8)
|
||||
if self.tls:
|
||||
conn = self.tls.wrap_socket(conn, server_side=True, do_handshake_on_connect=False)
|
||||
return conn, addr
|
||||
|
||||
def process_request(self, request, client_address):
|
||||
if not self.connections.acquire(blocking=False):
|
||||
self.shutdown_request(request)
|
||||
return
|
||||
try:
|
||||
super().process_request(request, client_address)
|
||||
except BaseException:
|
||||
self.connections.release()
|
||||
raise
|
||||
|
||||
def process_request_thread(self, request, client_address):
|
||||
try:
|
||||
super().process_request_thread(request, client_address)
|
||||
finally:
|
||||
self.connections.release()
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "AirDefPanel"
|
||||
sys_version = ""
|
||||
|
||||
def log_message(self, _format, *_args):
|
||||
return
|
||||
|
||||
def do_GET(self):
|
||||
self.route("GET")
|
||||
|
||||
def do_POST(self):
|
||||
self.route("POST")
|
||||
|
||||
def do_DELETE(self):
|
||||
self.route("DELETE")
|
||||
|
||||
def reply(self, status, payload=None, *, content_type="application/json; charset=utf-8", cookie=None):
|
||||
if payload is None:
|
||||
content = b""
|
||||
elif isinstance(payload, bytes):
|
||||
content = payload
|
||||
else:
|
||||
content = compact(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(content)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
self.send_header("Cross-Origin-Resource-Policy", "same-origin")
|
||||
self.send_header("Content-Security-Policy", "default-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'; object-src 'none'")
|
||||
if cookie:
|
||||
self.send_header("Set-Cookie", cookie)
|
||||
self.end_headers()
|
||||
if content:
|
||||
self.wfile.write(content)
|
||||
|
||||
def route(self, verb):
|
||||
try:
|
||||
if self.headers.get("Host", "").casefold() != self.server.host_header:
|
||||
raise APIError(HTTPStatus.BAD_REQUEST, "Откройте пульт по адресу, показанному на ПК")
|
||||
request = urlsplit(self.path)
|
||||
if request.scheme or request.netloc or len(request.query) > 1024:
|
||||
raise APIError(HTTPStatus.BAD_REQUEST, "Неверный адрес")
|
||||
if verb == "GET" and request.path in ASSETS:
|
||||
filename, mime = ASSETS[request.path]
|
||||
return self.reply(HTTPStatus.OK, (STATIC / filename).read_bytes(), content_type=mime)
|
||||
if verb != "GET" and self.headers.get("Origin") != self.server.origin:
|
||||
raise APIError(HTTPStatus.FORBIDDEN, "Запрос с другого адреса")
|
||||
query = {key: values[-1] for key, values in parse_qs(request.query, max_num_fields=16).items()}
|
||||
return self.api(verb, request.path, query)
|
||||
except APIError as error:
|
||||
return self.reply(error.status, {"error": error.message})
|
||||
except (ValueError, KeyError, TypeError, CookieError):
|
||||
return self.reply(HTTPStatus.BAD_REQUEST, {"error": "Неверный запрос"})
|
||||
except (BrokenPipeError, ConnectionResetError, TimeoutError):
|
||||
return
|
||||
|
||||
def body(self):
|
||||
if self.headers.get("Content-Type", "").split(";", 1)[0].strip() != "application/json":
|
||||
raise APIError(HTTPStatus.UNSUPPORTED_MEDIA_TYPE, "Ожидается JSON")
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
if not 0 < length <= MAX_BODY:
|
||||
raise APIError(HTTPStatus.REQUEST_ENTITY_TOO_LARGE, "Размер запроса вне лимита")
|
||||
data = json.loads(self.rfile.read(length))
|
||||
if type(data) is not dict:
|
||||
raise ValueError("JSON object expected")
|
||||
return data
|
||||
|
||||
def cookie(self, value, max_age):
|
||||
return f"{COOKIE}={value}; Max-Age={max_age}; Path=/; HttpOnly; SameSite=Strict" + ("; Secure" if self.server.secure else "")
|
||||
|
||||
def api(self, verb, path, query):
|
||||
auth = SimpleCookie(self.headers.get("Cookie", ""))
|
||||
token = auth.get(COOKIE)
|
||||
account = self.server.store.role(token.value) if token else None
|
||||
if (verb, path) == ("POST", "/api/pair"):
|
||||
code = self.body().get("code", "")
|
||||
role = self.server.pairing.claim(code.strip()) if isinstance(code, str) else None
|
||||
if not role:
|
||||
raise APIError(HTTPStatus.FORBIDDEN, "Код неверный, уже использован или истёк")
|
||||
value = self.server.store.pair(role)
|
||||
return self.reply(HTTPStatus.OK, {"role": role}, cookie=self.cookie(value, SESSION_AGE))
|
||||
if not account:
|
||||
raise APIError(HTTPStatus.UNAUTHORIZED, "Подключите устройство кодом с ПК")
|
||||
owner, role = account
|
||||
launch = self.server.allow_launch and role == "operator"
|
||||
debug = self.server.allow_debug and role == "analysis"
|
||||
if (verb, path) == ("GET", "/api/session"):
|
||||
return self.reply(HTTPStatus.OK, {"role": role, "permissions": {"launch": launch, "debug": debug}})
|
||||
if (verb, path) == ("DELETE", "/api/session"):
|
||||
self.server.store.revoke(owner)
|
||||
return self.reply(HTTPStatus.OK, {"ok": True}, cookie=self.cookie("", 0))
|
||||
if (verb, path) == ("GET", "/api/live"):
|
||||
mode = query.get("mode", "network")
|
||||
if mode not in {"network", "enemy", "truth"}:
|
||||
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"]:
|
||||
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/chain"):
|
||||
result = self.server.store.chain(number(query.get("event")))
|
||||
if result is None:
|
||||
raise APIError(HTTPStatus.NOT_FOUND, "Эта запись вышла из архива")
|
||||
return self.reply(HTTPStatus.OK, result)
|
||||
if (verb, path) == ("GET", "/api/events"):
|
||||
session = query.get("session")
|
||||
if session and not TOKEN.fullmatch(session):
|
||||
raise ValueError("bad session")
|
||||
args = {key: number(query.get(key)) for key in ("raid", "unit", "target", "object", "after", "before", "since", "until")}
|
||||
args["kind"] = query.get("kind")
|
||||
if args["kind"] not in {None, "observations", "decisions", "events"}:
|
||||
raise ValueError("bad event kind")
|
||||
if args["after"] is not None and args["before"] is not None:
|
||||
raise ValueError("choose a single cursor")
|
||||
args["limit"] = min(200, max(1, number(query.get("limit")) or 100))
|
||||
args["query"] = query.get("q", "")[:80].strip()
|
||||
return self.reply(HTTPStatus.OK, self.server.store.events(session=session, **args))
|
||||
if (verb, path) == ("GET", "/api/frame"):
|
||||
session, tick = query["session"], number(query["tick"])
|
||||
if not TOKEN.fullmatch(session) or tick is None:
|
||||
raise ValueError("bad frame")
|
||||
data = self.server.store.frame(session, tick)
|
||||
if data is None:
|
||||
raise APIError(HTTPStatus.NOT_FOUND, "Кадр отсутствует в сохранённой карте")
|
||||
return self.reply(HTTPStatus.OK, data)
|
||||
if path == "/api/launch" or path.startswith("/api/launch/"):
|
||||
if not launch:
|
||||
raise APIError(HTTPStatus.FORBIDDEN, "Запуск требует доступа оператора")
|
||||
if (verb, path) == ("POST", "/api/launch"):
|
||||
body = self.body()
|
||||
key, session = body["id"], body["session"]
|
||||
if not isinstance(key, str) or not TOKEN.fullmatch(key) or not isinstance(session, str) or not TOKEN.fullmatch(session):
|
||||
raise ValueError("bad launch identity")
|
||||
try:
|
||||
result = self.server.bridge.submit(key, owner, session, body["wave"])
|
||||
except ValueError as error:
|
||||
raise APIError(HTTPStatus.CONFLICT, str(error)) from error
|
||||
return self.reply(HTTPStatus.ACCEPTED, result)
|
||||
if verb == "GET":
|
||||
key = path.removeprefix("/api/launch/")
|
||||
result = self.server.store.launch(key, owner) if TOKEN.fullmatch(key) else None
|
||||
if result:
|
||||
return self.reply(HTTPStatus.OK, result)
|
||||
raise APIError(HTTPStatus.NOT_FOUND, "Такой страницы нет")
|
||||
|
||||
|
||||
def number(raw):
|
||||
if raw is None:
|
||||
return None
|
||||
value = int(raw)
|
||||
if not 0 <= value <= (1 << 53) - 1:
|
||||
raise ValueError("number out of range")
|
||||
return value
|
||||
|
||||
|
||||
def transport_options(args):
|
||||
ip = ipaddress.IPv4Address(args.listen)
|
||||
tls = None
|
||||
if args.cert or args.key:
|
||||
if not args.cert or not args.key:
|
||||
raise ValueError("Укажите сертификат и его ключ")
|
||||
tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
tls.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
tls.load_cert_chain(args.cert, args.key)
|
||||
if not ip.is_loopback and (not tls or not args.origin):
|
||||
raise ValueError("Для планшета укажите HTTPS-адрес, сертификат и ключ")
|
||||
origin = (args.origin or f"{'https' if tls else 'http'}://{ip}:{args.port}").rstrip("/")
|
||||
url = urlsplit(origin)
|
||||
if (url.scheme != ("https" if tls else "http") or not url.hostname or url.username
|
||||
or url.path or url.query or url.fragment or not 1 <= args.port <= 65535):
|
||||
raise ValueError("Укажите адрес пульта без пути, например https://airdef.home:8765")
|
||||
if not tls and url.hostname not in ("localhost", "127.0.0.1"):
|
||||
raise ValueError("HTTP доступен только на этом компьютере")
|
||||
return origin, tls
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def process_lock(path):
|
||||
with path.open("a+b") as lock:
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
if lock.tell() == 0:
|
||||
lock.write(b"0")
|
||||
lock.flush()
|
||||
lock.seek(0)
|
||||
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
yield
|
||||
|
||||
|
||||
def run(argv, *, game_home, game_command, default_mod_data):
|
||||
parser = argparse.ArgumentParser(description="Веб-пульт AirDef")
|
||||
parser.add_argument("--listen", default="127.0.0.1", help="IPv4-интерфейс веб-пульта")
|
||||
parser.add_argument("--port", type=int, default=8765)
|
||||
parser.add_argument("--origin", help="Точный HTTPS-адрес, по которому планшет открывает пульт")
|
||||
parser.add_argument("--cert", type=Path, help="Сертификат HTTPS в PEM")
|
||||
parser.add_argument("--key", type=Path, help="Ключ сертификата PEM")
|
||||
parser.add_argument("--allow-launch", action="store_true", help="Выдать отдельный код оператору")
|
||||
parser.add_argument("--allow-debug", action="store_true", help="Выдать отдельный код анализа")
|
||||
parser.add_argument("--reset-pairings", action="store_true", help="Отозвать все ранее подключённые устройства")
|
||||
parser.add_argument("--attach", type=Path, help="Локальный endpoint уже запущенного Horizon")
|
||||
parser.add_argument("--mod-data", type=Path, help="Другой каталог данных AirDef для dev-mod")
|
||||
parser.add_argument("game_args", nargs=argparse.REMAINDER, help="Аргументы игры после --")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
origin, tls = transport_options(args)
|
||||
except (OSError, ValueError) as error:
|
||||
parser.error(str(error))
|
||||
home = game_home.resolve()
|
||||
directory = home / "airdef-panel"
|
||||
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
endpoint = args.attach or (directory / ("game.json" if os.name == "nt" else "game.sock"))
|
||||
data = args.mod_data or default_mod_data
|
||||
with process_lock(directory / "panel.lock"):
|
||||
store = Store(directory / "history.sqlite3")
|
||||
if args.reset_pairings:
|
||||
store.revoke_all()
|
||||
pairing = Pairing(args.allow_launch, args.allow_debug)
|
||||
bridge = Bridge(endpoint, data, store, debug=args.allow_debug)
|
||||
with PanelServer((args.listen, args.port), origin, store, bridge, pairing, tls=tls,
|
||||
allow_launch=args.allow_launch, allow_debug=args.allow_debug) as server:
|
||||
child = None
|
||||
if not args.attach:
|
||||
extra = args.game_args[1:] if args.game_args[:1] == ["--"] else args.game_args
|
||||
if any(arg == "--control-socket" or arg.startswith("--control-socket=") for arg in extra):
|
||||
parser.error("Веб-пульт сам выбирает локальный endpoint игры")
|
||||
child = subprocess.Popen([*game_command(), "--control-socket", str(endpoint), *extra], cwd=home)
|
||||
print(f"Веб-пульт AirDef {origin}", flush=True)
|
||||
for code, role in pairing.codes.items():
|
||||
label = {"viewer": "Просмотр", "operator": "Оператор", "analysis": "Анализ"}[role]
|
||||
print(f"{label} {code} (одно подключение, 10 мин)", flush=True)
|
||||
bridge.begin()
|
||||
try:
|
||||
server.serve_forever(poll_interval=0.25)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
bridge.close()
|
||||
# The game remains a normal player-owned process when only the web panel closes.
|
||||
if child is not None and child.poll() is not None:
|
||||
child.wait()
|
||||
@@ -0,0 +1,105 @@
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
font-size: 16px;
|
||||
background: #0b121a;
|
||||
color: #e4edf1;
|
||||
--surface: #111e29;
|
||||
--surface-raised: #182936;
|
||||
--border: #2b4250;
|
||||
--muted: #9ab0bb;
|
||||
--accent: #70d7c9;
|
||||
--warning: #edbd6c;
|
||||
--danger: #f08c83;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-width: 280px; min-height: 100vh; min-height: 100dvh; }
|
||||
button, input, select, textarea { font: inherit; }
|
||||
button, select { cursor: pointer; }
|
||||
button, input, select, textarea {
|
||||
min-height: 44px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 9px;
|
||||
background: #12232e;
|
||||
color: inherit;
|
||||
}
|
||||
button { padding: .6rem .9rem; font-weight: 650; }
|
||||
button:hover:not(:disabled) { background: #213c48; border-color: #52717c; }
|
||||
button:active:not(:disabled) { transform: translateY(1px); }
|
||||
button:disabled { cursor: not-allowed; opacity: .48; }
|
||||
input, select, textarea { width: 100%; padding: .6rem .7rem; }
|
||||
select {
|
||||
appearance: none;
|
||||
padding-right: 1.8rem;
|
||||
background-image: linear-gradient(45deg, transparent 50%, #9ab0bb 50%), linear-gradient(135deg, #9ab0bb 50%, transparent 50%);
|
||||
background-position: calc(100% - 15px) center, calc(100% - 10px) center;
|
||||
background-size: 5px 5px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
input[type="checkbox"], input[type="radio"] { width: auto; min-height: auto; accent-color: var(--accent); }
|
||||
label { display: grid; gap: .35rem; color: var(--muted); font-size: .88rem; font-weight: 600; }
|
||||
a { color: var(--accent); }
|
||||
:focus-visible { outline: 3px solid #9af4e5; outline-offset: 3px; }
|
||||
h1, h2, h3, p { margin-top: 0; }
|
||||
h1 { font-size: clamp(1.15rem, 2.4vw, 1.55rem); margin-bottom: 0; }
|
||||
h2 { font-size: 1rem; margin-bottom: .8rem; }
|
||||
h3 { font-size: .9rem; margin-bottom: .55rem; }
|
||||
.shell { width: min(100%, 1680px); margin: 0 auto; padding: max(12px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) max(16px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left)); }
|
||||
.topbar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .65rem 1rem; padding: .3rem .1rem .9rem; }
|
||||
.topbar p { margin: .2rem 0 0; color: var(--muted); font-size: .82rem; }
|
||||
.status, [role="status"] { color: var(--muted); font-size: .85rem; }
|
||||
.tabs { display: flex; gap: .4rem; overflow-x: auto; padding: 0 0 .75rem; scrollbar-width: thin; }
|
||||
.tabs button, .tabs a { flex: 0 0 auto; }
|
||||
.tabs [aria-selected="true"], .tabs [aria-current="page"], .tabs .active { background: #1b4c4a; border-color: #70d7c9; color: #e6fffa; }
|
||||
.workspace { display: grid; grid-template-columns: minmax(0, 1fr) minmax(260px, 340px); gap: .85rem; align-items: start; }
|
||||
.map-column, .side-panel { min-width: 0; display: grid; gap: .75rem; }
|
||||
.map-wrap { position: relative; overflow: hidden; min-height: 260px; border: 1px solid #35515d; border-radius: 12px; background: #101c24; }
|
||||
.map-wrap canvas { display: block; width: 100%; height: auto; touch-action: none; }
|
||||
.map-tools, .toolbar, .row { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; }
|
||||
.map-tools > *, .toolbar > * { flex: 0 1 auto; }
|
||||
.card { min-width: 0; padding: 1rem; border: 1px solid var(--border); border-radius: 12px; background: var(--surface); }
|
||||
.card > :last-child { margin-bottom: 0; }
|
||||
.card + .card { margin-top: 0; }
|
||||
.list { display: grid; gap: .5rem; padding: 0; margin: 0; list-style: none; }
|
||||
.list > * { min-width: 0; padding: .7rem; border: 1px solid #29404c; border-radius: 8px; background: #142530; overflow-wrap: anywhere; }
|
||||
.empty { color: var(--muted); line-height: 1.5; padding: .6rem 0; }
|
||||
small, .muted { color: var(--muted); }
|
||||
.success { color: var(--accent); }
|
||||
.warning { color: var(--warning); }
|
||||
.error, .danger { color: var(--danger); }
|
||||
[hidden] { display: none !important; }
|
||||
dialog { width: min(90vw, 540px); max-height: min(85vh, 800px); overflow: auto; padding: 1.2rem; border: 1px solid #4d6974; border-radius: 14px; background: #152630; color: inherit; box-shadow: 0 20px 70px #0009; }
|
||||
dialog::backdrop { background: #02080dc9; }
|
||||
@media (max-width: 800px) {
|
||||
.workspace { grid-template-columns: minmax(0, 1fr); }
|
||||
.side-panel { grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr)); }
|
||||
.map-wrap { min-height: 200px; }
|
||||
}
|
||||
@media (max-width: 420px) {
|
||||
.shell { padding-left: max(8px, env(safe-area-inset-left)); padding-right: max(8px, env(safe-area-inset-right)); }
|
||||
.card { padding: .8rem; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { scroll-behavior: auto !important; transition-duration: 0s !important; animation-duration: 0s !important; } }
|
||||
|
||||
.map-wrap canvas { height: clamp(280px, 59dvh, 690px); }
|
||||
.map-tools { justify-content: space-between; }
|
||||
.map-actions { display: flex; gap: .35rem; }
|
||||
.map-actions button { min-width: 44px; }
|
||||
.legend { display: flex; flex-wrap: wrap; gap: .65rem 1rem; padding: .65rem .85rem; }
|
||||
.legend label { display: flex; align-items: center; min-height: 34px; cursor: pointer; }
|
||||
.side-panel > .card { display: grid; gap: .7rem; }
|
||||
.pairing { max-width: 410px; margin: clamp(36px, 15vh, 160px) auto 0; }
|
||||
.pairing form, #scenario-form { display: grid; gap: .7rem; }
|
||||
.scroller { max-height: 380px; overflow-y: auto; scrollbar-color: #42636f transparent; }
|
||||
.list button { text-align: left; min-height: 44px; font-size: .9rem; }
|
||||
.list [aria-pressed="true"] { border-color: var(--accent); background: #193b40; }
|
||||
.subcard, .object-card:not(:empty) { border-bottom: 1px solid var(--border); padding-bottom: .7rem; }
|
||||
.subcard h3:not(:first-child) { margin-top: .9rem; }
|
||||
.scroller.chain { max-height: 225px; }
|
||||
.detail-row { margin: .25rem 0; line-height: 1.4; font-size: .9rem; }
|
||||
.fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .55rem; }
|
||||
.object-card button { margin-top: .5rem; }
|
||||
#history-more, #preview, #confirm-launch { color: #b6f3eb; border-color: #447672; }
|
||||
#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); } }
|
||||
@@ -0,0 +1,774 @@
|
||||
import {createMap} from "./map.js";
|
||||
|
||||
const $ = id => document.getElementById(id);
|
||||
const make = (tag, text, cls) => {
|
||||
const element = document.createElement(tag);
|
||||
if (text !== undefined) element.textContent = text;
|
||||
if (cls) element.className = cls;
|
||||
return element;
|
||||
};
|
||||
const paragraph = text => make("p", text, "detail-row");
|
||||
const button = (text, action) => {
|
||||
const node = make("button", text);
|
||||
node.type = "button";
|
||||
node.addEventListener("click", action);
|
||||
return node;
|
||||
};
|
||||
const read = (key, fallback) => {
|
||||
try { return JSON.parse(localStorage.getItem(`airdef-${key}`)) ?? fallback; }
|
||||
catch { return fallback; }
|
||||
};
|
||||
const write = (key, value) => {
|
||||
try { localStorage.setItem(`airdef-${key}`, JSON.stringify(value)); } catch {}
|
||||
};
|
||||
const archive = new Promise(resolve => {
|
||||
if (!("indexedDB" in window)) return resolve(null);
|
||||
const request = indexedDB.open("airdef-panel", 1);
|
||||
request.onupgradeneeded = () => request.result.createObjectStore("content");
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => resolve(null);
|
||||
request.onblocked = () => resolve(null);
|
||||
});
|
||||
async function cache(key, value) {
|
||||
try {
|
||||
const db = await archive;
|
||||
if (!db) return;
|
||||
const tx = db.transaction("content", value === undefined ? "readonly" : "readwrite");
|
||||
const items = tx.objectStore("content");
|
||||
const op = value === undefined ? items.get(key) : value === null ? items.clear() : items.put(value, key);
|
||||
return await new Promise(resolve => {
|
||||
op.onsuccess = () => resolve(op.result);
|
||||
op.onerror = () => resolve(undefined);
|
||||
});
|
||||
} catch { return undefined; }
|
||||
}
|
||||
|
||||
class APIError extends Error {
|
||||
constructor(status, text) {
|
||||
super(text);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
async function api(path, {method = "GET", data} = {}) {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 6000);
|
||||
try {
|
||||
const response = await fetch(`/api${path}`, {
|
||||
method, signal: controller.signal, cache: "no-store",
|
||||
headers: data ? {"Content-Type": "application/json"} : {},
|
||||
body: data ? JSON.stringify(data) : undefined,
|
||||
});
|
||||
if (response.status === 204) return null;
|
||||
const body = await response.json();
|
||||
if (!response.ok) throw new APIError(response.status, body.error || "Запрос отклонён");
|
||||
return body;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
const groups = [["units", "unit"], ["objects", "object"], ["contacts", "contact"], ["interceptors", "interceptor"]];
|
||||
const prefs = read("view", {layers: {}, views: {}, selected: null});
|
||||
prefs.layers ||= {};
|
||||
prefs.views ||= {};
|
||||
let auth = null, network = null, live = null, historical = null, tab = "live", perspective = "network";
|
||||
let selected = prefs.selected, connected = false, http = false, polling = false, catalog = null;
|
||||
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: []};
|
||||
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 => {
|
||||
prefs.views[perspective] = view;
|
||||
write("view", prefs);
|
||||
},
|
||||
});
|
||||
map.restore(prefs.views.network);
|
||||
|
||||
function time(ticks) {
|
||||
const tenths = Math.floor(Math.max(0, ticks) / 2);
|
||||
return `${Math.floor(tenths / 600)}:${((tenths % 600) / 10).toFixed(1).padStart(4, "0")}`;
|
||||
}
|
||||
function when(value) {
|
||||
return value ? new Date(value * 1000).toLocaleTimeString("ru-RU") : "—";
|
||||
}
|
||||
function fullname(row) { return row.label || `№${row.id}`; }
|
||||
function showAuth() {
|
||||
$("pairing").hidden = !!auth;
|
||||
$("dashboard").hidden = !auth;
|
||||
$("logout").hidden = !auth;
|
||||
$("logout").disabled = !http;
|
||||
for (const option of $("perspective").options) {
|
||||
option.hidden = option.value !== "network" && !auth?.permissions?.debug;
|
||||
option.disabled = option.hidden;
|
||||
}
|
||||
if (!auth?.permissions?.debug) perspective = "network";
|
||||
updateStatus();
|
||||
}
|
||||
function updateStatus() {
|
||||
const status = $("connection");
|
||||
status.className = connected ? "success" : "warning";
|
||||
status.textContent = connected ? `Игра в сети · ${when(live?.updated)}`
|
||||
: auth ? live?.updated ? `Нет связи · снимок от ${when(live.updated)}` : "Ожидание игры"
|
||||
: http ? "Ожидает подключения" : "Нет соединения";
|
||||
$("logout").disabled = !http;
|
||||
}
|
||||
function activeFrame() {
|
||||
if (historical) return historical.frame?.frame ?? null;
|
||||
return live?.frame || (perspective === "network" ? network?.frame : null);
|
||||
}
|
||||
function select(key, centre = false) {
|
||||
selected = key;
|
||||
if (!historical && perspective === "network") {
|
||||
prefs.selected = key;
|
||||
write("view", prefs);
|
||||
}
|
||||
draw();
|
||||
if (centre) map.focus(key);
|
||||
}
|
||||
function draw() {
|
||||
const frame = activeFrame();
|
||||
map.draw(frame, {selected, layers: prefs.layers});
|
||||
$("return-live").hidden = !historical;
|
||||
$("perspective").disabled = !!historical;
|
||||
const status = [];
|
||||
if (historical) {
|
||||
const actual = historical.frame?.tick;
|
||||
status.push(actual === undefined ? "Карта для этого момента недоступна" :
|
||||
actual === historical.requested ? `Записанный кадр · ${time(actual - historical.start)}`
|
||||
: `Ближайший сохранённый кадр · ${time(actual - historical.start)}`);
|
||||
} else if (frame) {
|
||||
if (frame.summary) status.push(`Сбито ${frame.summary.kills} · попаданий ${frame.summary.hits}`);
|
||||
if (frame.summary?.planning) status.push("Игра готовит налёт");
|
||||
if (frame.summary?.hold) status.push("Огонь запрещён");
|
||||
if (perspective === "enemy") status.push(`Донесений ${frame.contacts?.length || 0} · вылетов разведки ${frame.sorties?.length || 0}`);
|
||||
if (perspective === "truth") status.push("Песочница · истинные позиции");
|
||||
}
|
||||
if (frame?.limited) status.push("Часть отметок за пределом отображения");
|
||||
$("map-status").textContent = status.join(" · ");
|
||||
|
||||
const data = groups.flatMap(([group, kind]) => prefs.layers[group] === false ? [] : (frame?.[group] || [])
|
||||
.map(row => ({row, kind, key: `${kind}:${row.id}`})));
|
||||
const opened = data.find(item => item.key === selected);
|
||||
showObject(opened, frame);
|
||||
const filter = $("object-search").value.toLocaleLowerCase("ru");
|
||||
const matched = data.filter(({row}) => !filter || fullname(row).toLocaleLowerCase("ru").includes(filter) || String(row.id) === filter);
|
||||
const oldScroll = $("object-list").scrollTop;
|
||||
const focused = document.activeElement?.dataset.objectKey;
|
||||
const nodes = matched.slice(0, 130).map(({row, key}) => {
|
||||
const node = button([fullname(row), row.status].filter(Boolean).join(" · "), () => select(key, true));
|
||||
node.dataset.objectKey = key;
|
||||
node.setAttribute("aria-pressed", String(key === selected));
|
||||
return node;
|
||||
});
|
||||
if (matched.length > nodes.length) nodes.push(paragraph(`Показано ${nodes.length} из ${matched.length}. Уточните поиск.`));
|
||||
if (!nodes.length) nodes.push(make("p", "Подходящих объектов нет", "empty"));
|
||||
$("object-list").replaceChildren(...nodes);
|
||||
$("object-list").scrollTop = oldScroll;
|
||||
if (focused) nodes.find(node => node.dataset.objectKey === focused)?.focus({preventScroll: true});
|
||||
drawScenario();
|
||||
}
|
||||
function showObject(opened, frame) {
|
||||
const card = $("object-card");
|
||||
if (!opened) {
|
||||
const nodes = [make("p", historical && selected ? "Этой отметки нет на сохранённом снимке" :
|
||||
"Коснитесь отметки или выберите объект из списка", "empty")];
|
||||
if (perspective === "enemy" && !historical && frame?.sorties?.length) {
|
||||
const phases = {outbound: "на маршруте", looking: "осматривает район", reporting: "передаёт донесение", done: "завершён"};
|
||||
nodes.push(make("h2", "Игровая разведка"));
|
||||
frame.sorties.slice(0, 8).forEach(s => nodes.push(paragraph(
|
||||
`${phases[s.phase] || s.phase} · районов осталось ${s.zones}`)));
|
||||
}
|
||||
card.replaceChildren(...nodes);
|
||||
return;
|
||||
}
|
||||
const {row, kind} = opened;
|
||||
const nodes = [make("h2", fullname(row)), paragraph([row.status, row.details].filter(Boolean).join(" · ")),
|
||||
paragraph(`X ${Math.round(row.x)} · Y ${Math.round(row.y)} · Z ${Math.round(row.z)} · ID ${row.id}`)];
|
||||
if (row.health != null) nodes.push(paragraph(`Состояние ${Math.round(row.health * 100)}%`));
|
||||
if (row.age != null) nodes.push(paragraph(`Давность ${(row.age / 20).toFixed(1)} с`));
|
||||
if (row.confidence) nodes.push(paragraph(`Достоверность · ${row.confidence}`));
|
||||
if (row.quality != null) nodes.push(paragraph(`Качество · ${row.quality}`));
|
||||
if (row.radius > 0) nodes.push(paragraph(`Область оценки · ±${Math.round(row.radius)} бл.`));
|
||||
if (row.target) nodes.push(button(`Контакт №${row.target}`, () => select(`contact:${row.target}`, true)));
|
||||
if (row.source) {
|
||||
const linked = frame?.units?.some(unit => unit.id === row.source);
|
||||
nodes.push(linked ? button(`Источник №${row.source}`, () => select(`unit:${row.source}`, true))
|
||||
: paragraph(`Источник · ${row.source}`));
|
||||
}
|
||||
const focus = historical ? historical.frame?.selected : live?.selected;
|
||||
if (focus?.unit === row.id && kind === "unit") {
|
||||
nodes.push(paragraph(`${historical ? "На сохранённом снимке" : "Текущая проверка"} · ${focus.reason}`));
|
||||
}
|
||||
if (perspective === "enemy" && !historical) {
|
||||
const reasons = frame?.reports?.filter(r => r.contact === row.id);
|
||||
const reasonNames = {plan: "задание плана", sead: "известная позиция ПВО", react: "свежее донесение",
|
||||
replace: "замена потерянной отметки", refresh: "обновлённое донесение"};
|
||||
for (const reason of reasons?.slice(0, 8) || []) nodes.push(paragraph(`Игровое назначение · ${reasonNames[reason.reason] || reason.reason}`));
|
||||
}
|
||||
if (eventFields[kind] && (perspective === "network" || historical)) {
|
||||
if (!historical && latestObject.key === `${live?.session}:${opened.key}` && latestObject.event) {
|
||||
const event = latestObject.event;
|
||||
nodes.push(paragraph(`${kind === "unit" ? "Последнее решение" : "Последняя запись"} · ${time(event.data.at)} · ${event.label}`));
|
||||
}
|
||||
if (!historical) updateObjectEvent(opened);
|
||||
nodes.push(button("События объекта", () => {
|
||||
for (const field of Object.values(eventFields)) $(`event-${field}`).value = field === eventFields[kind] ? row.id : "";
|
||||
setTab("history");
|
||||
}));
|
||||
}
|
||||
card.replaceChildren(...nodes);
|
||||
}
|
||||
|
||||
async function updateObjectEvent(opened) {
|
||||
if (!connected || !live?.session) return;
|
||||
const key = `${live.session}:${opened.key}`;
|
||||
if (latestObject.key === key && Date.now() - latestObject.checked < 3000) return;
|
||||
const check = {key, checked: Date.now(), event: latestObject.key === key ? latestObject.event : null};
|
||||
latestObject = check;
|
||||
const params = new URLSearchParams({session: live.session, limit: "1", [eventFields[opened.kind]]: opened.row.id});
|
||||
if (opened.kind === "unit") params.set("kind", "decisions");
|
||||
try {
|
||||
const data = await api(`/events?${params}`);
|
||||
if (latestObject === check && selected === opened.key) {
|
||||
check.event = data.events[0] ?? null;
|
||||
draw();
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function forgetCachedData() {
|
||||
cache("all", null);
|
||||
network = live = historical = null;
|
||||
connected = false;
|
||||
latestObject = {key: "", checked: 0, event: null};
|
||||
offlineEvents = [];
|
||||
offlineFrames = {};
|
||||
offlineRaids = {raids: []};
|
||||
events = [];
|
||||
raids = [];
|
||||
raid = null;
|
||||
latestRequest = null;
|
||||
write("launch-request", null);
|
||||
$("event-card").hidden = true;
|
||||
}
|
||||
|
||||
async function poll() {
|
||||
if (!auth || polling || document.hidden) return;
|
||||
polling = true;
|
||||
try {
|
||||
if (!http) {
|
||||
auth = await api("/session");
|
||||
cache("auth", {role: auth.role});
|
||||
http = true;
|
||||
showAuth();
|
||||
}
|
||||
const mode = perspective;
|
||||
const params = new URLSearchParams({mode});
|
||||
if (live?.perspective === mode) params.set("after", live.revision || "");
|
||||
const data = await api(`/live?${params}`);
|
||||
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.world = data.world;
|
||||
network = data;
|
||||
if (data.connected) cache("network", data);
|
||||
}
|
||||
if (data.catalog && JSON.stringify(catalog) !== JSON.stringify(data.catalog)) {
|
||||
catalog = data.catalog;
|
||||
setupScenario();
|
||||
}
|
||||
draw();
|
||||
if (tab === "history") {
|
||||
await refreshRaids();
|
||||
await newEvents();
|
||||
}
|
||||
}
|
||||
if (latestRequest && auth.permissions.launch) watchReceipt(latestRequest);
|
||||
} catch (error) {
|
||||
if (error.status === 401) {
|
||||
auth = null;
|
||||
forgetCachedData();
|
||||
showAuth();
|
||||
} else {
|
||||
http = connected = false;
|
||||
if (live?.perspective !== "network") {
|
||||
perspective = "network";
|
||||
$("perspective").value = "network";
|
||||
live = network;
|
||||
}
|
||||
draw();
|
||||
}
|
||||
} finally {
|
||||
polling = false;
|
||||
updateStatus();
|
||||
}
|
||||
}
|
||||
|
||||
function setTab(next) {
|
||||
tab = next;
|
||||
for (const control of document.querySelectorAll("[data-tab]")) {
|
||||
if (control.dataset.tab === next) control.setAttribute("aria-current", "page");
|
||||
else control.removeAttribute("aria-current");
|
||||
}
|
||||
$("live-panel").hidden = next !== "live";
|
||||
$("history-panel").hidden = next !== "history";
|
||||
$("scenario-panel").hidden = next !== "scenario";
|
||||
if (next === "history") {
|
||||
refreshRaids().then(() => readEvents());
|
||||
}
|
||||
draw();
|
||||
}
|
||||
function chooseRaid(value) {
|
||||
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;
|
||||
}
|
||||
async function refreshRaids() {
|
||||
let data;
|
||||
try {
|
||||
data = await api("/raids");
|
||||
offlineRaids = data;
|
||||
cache("raids", data);
|
||||
} catch { data = offlineRaids; }
|
||||
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}`));
|
||||
}
|
||||
$("raid").replaceChildren(...options);
|
||||
$("raid").value = options.some(o => o.value === previous) ? previous : "";
|
||||
const old = raid;
|
||||
raid = raids.find(r => `${r.session}:${r.raid}` === $("raid").value) || null;
|
||||
$("event-since").disabled = $("event-until").disabled = !raid;
|
||||
$("timeline").disabled = !raid;
|
||||
$("timeline").max = raid?.length || 0;
|
||||
if (!historical || !old) $("timeline").value = $("timeline").max;
|
||||
}
|
||||
function historyParams(before) {
|
||||
const params = new URLSearchParams({limit: "70"});
|
||||
if (raid) {
|
||||
params.set("session", raid.session);
|
||||
params.set("raid", raid.raid);
|
||||
}
|
||||
for (const key of Object.values(eventFields)) {
|
||||
const value = $(`event-${key}`).value;
|
||||
if (/^\d+$/.test(value)) params.set(key, value);
|
||||
}
|
||||
for (const key of ["since", "until"]) {
|
||||
const value = $(`event-${key}`).value;
|
||||
if (raid && /^\d+$/.test(value)) params.set(key, raid.start + Number(value) * 20);
|
||||
}
|
||||
if ($("event-query").value.trim()) params.set("q", $("event-query").value.trim());
|
||||
if (before) params.set("before", before);
|
||||
return params;
|
||||
}
|
||||
async function readEvents(older = false) {
|
||||
const token = ++historyGeneration;
|
||||
const params = historyParams(older && events.at(-1)?.id);
|
||||
let data;
|
||||
let saved = false;
|
||||
try {
|
||||
data = await api(`/events?${params}`);
|
||||
if (token !== historyGeneration) return;
|
||||
rememberEvents(data.events);
|
||||
} catch {
|
||||
saved = true;
|
||||
data = {events: offlineEvents.filter(event => [...params].every(([key, value]) => {
|
||||
if (key === "q") return JSON.stringify(event).toLocaleLowerCase("ru").includes(value.toLocaleLowerCase("ru"));
|
||||
if (key === "limit") return true;
|
||||
if (key === "before") return event.id < Number(value);
|
||||
if (key === "since") return event.tick >= Number(value);
|
||||
if (key === "until") return event.tick <= Number(value);
|
||||
return String(event[key]) === value;
|
||||
})), more: false};
|
||||
}
|
||||
if (token !== historyGeneration) return;
|
||||
events = older ? [...events, ...data.events] : data.events;
|
||||
more = data.more;
|
||||
renderEvents(saved);
|
||||
}
|
||||
function rememberEvents(incoming) {
|
||||
const merged = new Map(offlineEvents.map(e => [e.id, e]));
|
||||
for (const event of incoming) merged.set(event.id, event);
|
||||
offlineEvents = [...merged.values()].sort((a, b) => b.id - a.id).slice(0, 600);
|
||||
cache("events", offlineEvents);
|
||||
}
|
||||
async function newEvents() {
|
||||
if (!events.length) return readEvents();
|
||||
const generation = historyGeneration;
|
||||
const params = historyParams();
|
||||
params.set("after", events[0].id);
|
||||
try {
|
||||
const data = await api(`/events?${params}`);
|
||||
if (!data.events.length || generation !== historyGeneration) return;
|
||||
rememberEvents(data.events);
|
||||
events = [...data.events.reverse(), ...events].slice(0, 500);
|
||||
renderEvents(false);
|
||||
} catch {}
|
||||
}
|
||||
function renderEvents(saved) {
|
||||
const status = [];
|
||||
if (saved) status.push("Доступна история, загруженная на это устройство");
|
||||
if (raid?.gap) status.push("В журнале налёта есть пропуски");
|
||||
if (offlineRaids?.limited) status.push("Старые записи за пределом хранения");
|
||||
$("history-status").textContent = status.join(" · ");
|
||||
const starts = new Map(raids.map(r => [`${r.session}:${r.raid}`, r.time]));
|
||||
const at = event => (starts.get(`${event.session}:${event.raid}`) || 0) + event.data.at / 20;
|
||||
const chronological = [...events].sort((a, b) => at(b) - at(a) || b.id - a.id);
|
||||
const items = chronological.map(event => button(`№${event.raid} · ${time(event.data.at)} · ${event.label}`,
|
||||
() => openEvent(event)));
|
||||
$("events").replaceChildren(...(items.length ? items : [make("p", "События для этого фильтра отсутствуют", "empty")]));
|
||||
$("history-more").hidden = !more;
|
||||
}
|
||||
async function openEvent(event) {
|
||||
const chainRequest = ++chainGeneration;
|
||||
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)];
|
||||
if (!event.data.lines.length) nodes.push(paragraph(`Налёт №${event.raid} · ${time(event.data.at)}`));
|
||||
for (const line of event.data.lines) {
|
||||
if (!line.startsWith("На тот момент · ")) nodes.push(paragraph(line));
|
||||
}
|
||||
for (const [kind, field, label] of [["unit", "unit", "комплекс"], ["contact", "target", "контакт"], ["object", "object", "объект"]]) {
|
||||
if (event[field] == null) continue;
|
||||
nodes.push(button(`Открыть ${label} ${event[field]}`, () => {
|
||||
setTab("live");
|
||||
select(`${kind}:${event[field]}`, true);
|
||||
$("object-card").focus({preventScroll: true});
|
||||
$("object-card").scrollIntoView({block: "nearest"});
|
||||
}));
|
||||
}
|
||||
$("event-card").replaceChildren(...nodes);
|
||||
$("event-card").hidden = false;
|
||||
if (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;
|
||||
}
|
||||
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)]);
|
||||
}
|
||||
async function showChain(event, generation) {
|
||||
let chain;
|
||||
try {
|
||||
chain = await api(`/chain?event=${event.id}`);
|
||||
rememberEvents(chain.events);
|
||||
} catch {
|
||||
chain = {
|
||||
context: event.target == null, limited: true,
|
||||
events: offlineEvents.filter(item => item.session === event.session && item.raid === event.raid &&
|
||||
(event.target == null ? event.unit != null && item.unit === event.unit && Math.abs(event.tick - item.tick) <= 200
|
||||
: item.target === event.target))
|
||||
.sort((a, b) => Number(b.id === event.id) - Number(a.id === event.id) ||
|
||||
Math.abs(a.tick - event.tick) - Math.abs(b.tick - event.tick) || a.id - b.id).slice(0, 40)
|
||||
.sort((a, b) => a.tick - b.tick || eventOrder[a.kind] - eventOrder[b.kind] || a.id - b.id),
|
||||
};
|
||||
}
|
||||
if (generation !== chainGeneration || chain.events.length < 2) return;
|
||||
const card = $("event-card");
|
||||
card.append(make("h3", chain.context ? "События комплекса рядом по времени" : "Цепочка контакта"));
|
||||
if (chain.limited) card.append(paragraph("Показана доступная часть цепочки"));
|
||||
const items = make("div", undefined, "list scroller chain");
|
||||
for (const related of chain.events) {
|
||||
const links = [related.unit != null ? `комплекс ${related.unit}` : "",
|
||||
chain.context && related.target != null ? `контакт ${related.target}` : ""].filter(Boolean);
|
||||
const action = button([time(related.data.at), related.label, ...links].join(" · "), () => openEvent(related));
|
||||
action.setAttribute("aria-pressed", String(related.id === event.id));
|
||||
items.append(action);
|
||||
}
|
||||
card.append(items);
|
||||
}
|
||||
async function loadFrame(session, tick, start) {
|
||||
const generation = ++frameGeneration;
|
||||
const key = `${session}:${tick}`;
|
||||
let scene;
|
||||
try {
|
||||
scene = await api(`/frame?${new URLSearchParams({session, tick})}`);
|
||||
if (generation !== frameGeneration) return;
|
||||
delete offlineFrames[key];
|
||||
offlineFrames[key] = scene;
|
||||
const keys = Object.keys(offlineFrames);
|
||||
for (const old of keys.slice(0, -20)) delete offlineFrames[old];
|
||||
cache("frames", offlineFrames);
|
||||
} catch {
|
||||
scene = offlineFrames[key] || Object.entries(offlineFrames)
|
||||
.filter(([id]) => id.startsWith(`${session}:`))
|
||||
.map(([, item]) => item)
|
||||
.sort((a, b) => Math.abs(a.frame.tick - tick) - Math.abs(b.frame.tick - tick))[0];
|
||||
}
|
||||
if (generation !== frameGeneration) return;
|
||||
const frame = scene?.frame;
|
||||
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);
|
||||
}
|
||||
|
||||
function setupScenario() {
|
||||
if (!catalog) return;
|
||||
$("preset").replaceChildren(...catalog.presets.map((p, i) => new Option(p.name, i)), new Option("Черновик", "custom"));
|
||||
$("approach").replaceChildren(...catalog.approaches.map((name, i) => new Option(name, i)));
|
||||
$("aim").replaceChildren(...catalog.aims.map((name, i) => new Option(name, i)));
|
||||
$("distance").min = catalog.distance[0];
|
||||
$("distance").max = catalog.distance[1];
|
||||
$("counts").replaceChildren(...catalog.kinds.map((name, i) => {
|
||||
const label = make("label", name);
|
||||
const input = make("input");
|
||||
input.id = `count-${i}`;
|
||||
input.type = "number";
|
||||
input.inputMode = "numeric";
|
||||
input.min = 0;
|
||||
input.max = 80;
|
||||
input.value = 0;
|
||||
label.append(input);
|
||||
return label;
|
||||
}));
|
||||
const saved = read("draft", null);
|
||||
if (saved && saved.counts.length === catalog.kinds.length) {
|
||||
$("preset").value = "custom";
|
||||
applyDraft(saved);
|
||||
} else {
|
||||
$("preset").value = String(Math.min(catalog.presets.length - 1, 1));
|
||||
applyDraft(catalog.presets[Number($("preset").value)]);
|
||||
}
|
||||
}
|
||||
function applyDraft(value) {
|
||||
if (!value) return;
|
||||
$("distance").value = value.distance;
|
||||
$("approach").value = String(value.approach);
|
||||
$("aim").value = String(value.aim);
|
||||
value.counts.forEach((value, i) => { $(`count-${i}`).value = value; });
|
||||
drawScenario();
|
||||
}
|
||||
function draft() {
|
||||
if (!catalog) return null;
|
||||
return {
|
||||
distance: Number($("distance").value),
|
||||
approach: Number($("approach").value),
|
||||
aim: Number($("aim").value),
|
||||
counts: catalog.kinds.map((_, i) => Number($(`count-${i}`).value)),
|
||||
};
|
||||
}
|
||||
function draftValid(value) {
|
||||
return value && value.counts.some(n => n > 0) && $("scenario-form").checkValidity() &&
|
||||
value.counts.every(n => Number.isInteger(n) && n >= 0 && n <= 80);
|
||||
}
|
||||
function drawScenario() {
|
||||
const value = draft();
|
||||
$("preview").disabled = !draftValid(value);
|
||||
$("scenario-summary").textContent = value ? `Всего ${value.counts.reduce((sum, n) => sum + n, 0)} аппаратов` : "Состав появится после подключения игры";
|
||||
$("confirm-launch").disabled = !connected || !live?.canLaunch || !auth?.permissions?.launch || !!historical || !!latestRequest;
|
||||
}
|
||||
function finishReceipt(result) {
|
||||
$("launch-status").textContent = result.message;
|
||||
if (["queued", "dispatching"].includes(result.state)) {
|
||||
return;
|
||||
}
|
||||
latestRequest = null;
|
||||
write("launch-request", null);
|
||||
drawScenario();
|
||||
}
|
||||
async function watchReceipt(id) {
|
||||
if (receiptTimer || !http || !id) return;
|
||||
receiptTimer = true;
|
||||
try {
|
||||
finishReceipt(await api(`/launch/${id}`));
|
||||
} catch (error) {
|
||||
$("launch-status").textContent = error.status === 404
|
||||
? "Сервер не сохранил ответ. Запрос автоматически не повторяется."
|
||||
: "Ожидание ответа игры после восстановления связи";
|
||||
if (error.status === 404) {
|
||||
latestRequest = null;
|
||||
write("launch-request", null);
|
||||
}
|
||||
} finally {
|
||||
receiptTimer = false;
|
||||
}
|
||||
}
|
||||
let confirmedDraft = null;
|
||||
$("scenario-form").addEventListener("submit", event => {
|
||||
event.preventDefault();
|
||||
const value = draft();
|
||||
if (!draftValid(value)) return;
|
||||
confirmedDraft = value;
|
||||
const summary = [
|
||||
paragraph(`${catalog.approaches[value.approach]} · ${catalog.aims[value.aim]} · ${value.distance} бл.`),
|
||||
...value.counts.flatMap((n, i) => n ? [paragraph(`${catalog.kinds[i]} × ${n}`)] : []),
|
||||
];
|
||||
if (!auth?.permissions?.launch) summary.push(paragraph("Для запуска подключите устройство кодом оператора."));
|
||||
else if (!live?.canLaunch || historical) summary.push(paragraph("Запуск доступен при прямом эфире и готовой игре."));
|
||||
$("preview-details").replaceChildren(...summary);
|
||||
drawScenario();
|
||||
$("confirmation").showModal();
|
||||
});
|
||||
$("confirm-launch").addEventListener("click", async () => {
|
||||
if (!confirmedDraft || $("confirm-launch").disabled) return;
|
||||
const request = Array.from(crypto.getRandomValues(new Uint8Array(16)), n => n.toString(16).padStart(2, "0")).join("");
|
||||
latestRequest = request;
|
||||
write("launch-request", request);
|
||||
$("confirmation").close();
|
||||
drawScenario();
|
||||
$("launch-status").textContent = "Отправляем запрос…";
|
||||
try {
|
||||
finishReceipt(await api("/launch", {
|
||||
method: "POST", data: {id: request, session: live.session, wave: confirmedDraft},
|
||||
}));
|
||||
} catch (error) {
|
||||
if (error instanceof APIError) finishReceipt({message: error.message, state: "rejected"});
|
||||
else $("launch-status").textContent = "Связь прервалась. После подключения проверим результат.";
|
||||
}
|
||||
});
|
||||
$("cancel-launch").addEventListener("click", () => $("confirmation").close());
|
||||
$("preset").addEventListener("change", () => {
|
||||
applyDraft(catalog?.presets[Number($("preset").value)]);
|
||||
write("draft", draft());
|
||||
});
|
||||
$("scenario-form").addEventListener("input", event => {
|
||||
if (event.target !== $("preset")) {
|
||||
$("preset").value = "custom";
|
||||
write("draft", draft());
|
||||
drawScenario();
|
||||
}
|
||||
});
|
||||
|
||||
for (const node of document.querySelectorAll("[data-tab]")) node.addEventListener("click", () => setTab(node.dataset.tab));
|
||||
for (const node of document.querySelectorAll("[data-layer]")) {
|
||||
node.checked = prefs.layers[node.dataset.layer] !== false;
|
||||
node.addEventListener("change", () => {
|
||||
prefs.layers[node.dataset.layer] = node.checked;
|
||||
write("view", prefs);
|
||||
draw();
|
||||
});
|
||||
}
|
||||
$("object-search").addEventListener("input", draw);
|
||||
$("zoom-in").addEventListener("click", () => map.zoom(1.3));
|
||||
$("zoom-out").addEventListener("click", () => map.zoom(1 / 1.3));
|
||||
$("fit").addEventListener("click", map.fit);
|
||||
$("perspective").addEventListener("change", () => {
|
||||
perspective = $("perspective").value;
|
||||
selected = perspective === "network" ? prefs.selected : null;
|
||||
live = perspective === "network" ? network : null;
|
||||
map.restore(prefs.views[perspective]);
|
||||
draw();
|
||||
poll();
|
||||
});
|
||||
$("return-live").addEventListener("click", () => {
|
||||
frameGeneration++;
|
||||
historical = null;
|
||||
selected = prefs.selected;
|
||||
perspective = "network";
|
||||
$("perspective").value = "network";
|
||||
live = network;
|
||||
setTab("live");
|
||||
poll();
|
||||
});
|
||||
$("raid").addEventListener("change", () => {
|
||||
chooseRaid($("raid").value);
|
||||
readEvents();
|
||||
});
|
||||
$("timeline").addEventListener("input", () => {
|
||||
clearTimeout(frameTimer);
|
||||
const at = Number($("timeline").value);
|
||||
$("timeline-caption").textContent = `Момент ${time(at)}`;
|
||||
frameTimer = setTimeout(() => {
|
||||
if (raid) loadFrame(raid.session, raid.start + at, raid.start);
|
||||
}, 130);
|
||||
});
|
||||
for (const id of ["event-unit", "event-target", "event-object", "event-since", "event-until", "event-query"]) {
|
||||
$(id).addEventListener("input", () => {
|
||||
clearTimeout(eventTimer);
|
||||
eventTimer = setTimeout(readEvents, 150);
|
||||
});
|
||||
}
|
||||
$("history-more").addEventListener("click", () => readEvents(true));
|
||||
|
||||
$("pair-form").addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
try {
|
||||
await api("/pair", {method: "POST", data: {code: $("pair-code").value.trim()}});
|
||||
$("pair-code").value = "";
|
||||
$("pair-error").textContent = "";
|
||||
auth = await api("/session");
|
||||
http = true;
|
||||
cache("auth", {role: auth.role});
|
||||
showAuth();
|
||||
poll();
|
||||
} catch (error) { $("pair-error").textContent = error.message; }
|
||||
});
|
||||
$("logout").addEventListener("click", async () => {
|
||||
try { await api("/session", {method: "DELETE"}); }
|
||||
catch (error) { if (error.status !== 401) return; }
|
||||
auth = null;
|
||||
forgetCachedData();
|
||||
showAuth();
|
||||
});
|
||||
window.addEventListener("beforeinstallprompt", event => {
|
||||
event.preventDefault();
|
||||
installPrompt = event;
|
||||
$("install").hidden = false;
|
||||
});
|
||||
$("install").addEventListener("click", async () => {
|
||||
if (installPrompt) await installPrompt.prompt();
|
||||
$("install").hidden = true;
|
||||
});
|
||||
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)));
|
||||
network = live = savedNetwork ?? null;
|
||||
offlineEvents = cachedEvents ?? [];
|
||||
offlineRaids = cachedRaids ?? {raids: []};
|
||||
offlineFrames = cachedFrames ?? {};
|
||||
try {
|
||||
auth = await api("/session");
|
||||
http = true;
|
||||
cache("auth", {role: auth.role});
|
||||
} catch (error) {
|
||||
if (error.status === 401) {
|
||||
http = true;
|
||||
forgetCachedData();
|
||||
} else if (cachedAuth) {
|
||||
auth = {...cachedAuth, permissions: {launch: false, debug: false}};
|
||||
}
|
||||
}
|
||||
catalog = network?.catalog;
|
||||
setupScenario();
|
||||
showAuth();
|
||||
draw();
|
||||
poll();
|
||||
}
|
||||
window.addEventListener("online", async () => {
|
||||
if (auth) {
|
||||
try { auth = await api("/session"); showAuth(); } catch {}
|
||||
}
|
||||
poll();
|
||||
});
|
||||
document.addEventListener("visibilitychange", () => { if (!document.hidden) poll(); });
|
||||
setInterval(poll, 1200);
|
||||
start();
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 49 KiB |
@@ -0,0 +1,114 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="theme-color" content="#0b121a">
|
||||
<title>Веб-пульт AirDef</title>
|
||||
<link rel="stylesheet" href="./app.css">
|
||||
<link rel="manifest" href="./manifest.webmanifest">
|
||||
<link rel="apple-touch-icon" href="./icons/icon-192.png">
|
||||
<link rel="icon" href="./icons/icon-192.png">
|
||||
<script type="module" src="./app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<main class="shell">
|
||||
<header class="topbar">
|
||||
<div><h1>AirDef</h1><p>Командный пункт</p></div>
|
||||
<div class="row">
|
||||
<span id="connection" role="status">Подключение…</span>
|
||||
<button id="install" type="button" hidden>Установить</button>
|
||||
<button id="logout" type="button" hidden>Отвязать</button>
|
||||
</div>
|
||||
</header>
|
||||
<section id="pairing" class="card pairing" hidden>
|
||||
<h2>Подключить устройство</h2>
|
||||
<form id="pair-form">
|
||||
<label>Одноразовый код с ПК<input id="pair-code" type="password" maxlength="64" required autocomplete="off"></label>
|
||||
<button type="submit">Подключить</button>
|
||||
<p id="pair-error" class="error" role="alert"></p>
|
||||
</form>
|
||||
</section>
|
||||
<section id="dashboard" hidden>
|
||||
<nav class="tabs" aria-label="Разделы">
|
||||
<button type="button" data-tab="live" aria-current="page">Карта</button>
|
||||
<button type="button" data-tab="history">История</button>
|
||||
<button type="button" data-tab="scenario">Сценарий</button>
|
||||
</nav>
|
||||
<div class="workspace">
|
||||
<section id="map-panel" class="map-column" aria-label="Карта боя">
|
||||
<div class="map-tools">
|
||||
<label>Ракурс<select id="perspective">
|
||||
<option value="network">Картина игрока</option>
|
||||
<option value="enemy" hidden>Что известно противнику</option>
|
||||
<option value="truth" hidden>Истина · песочница</option>
|
||||
</select></label>
|
||||
<button type="button" id="return-live" hidden>К прямому эфиру</button>
|
||||
<div class="map-actions">
|
||||
<button type="button" id="zoom-in" aria-label="Приблизить">+</button>
|
||||
<button type="button" id="zoom-out" aria-label="Отдалить">−</button>
|
||||
<button type="button" id="fit">Вся карта</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="map-wrap"><canvas id="map" aria-label="Карта игровых объектов"></canvas></div>
|
||||
<div class="card legend" id="layer-options">
|
||||
<label><input type="checkbox" data-layer="units" checked> □ Техника</label>
|
||||
<label><input type="checkbox" data-layer="objects" checked> ◇ Объекты</label>
|
||||
<label><input type="checkbox" data-layer="contacts" checked> ○ Контакты</label>
|
||||
<label><input type="checkbox" data-layer="interceptors" checked> ▵ Перехватчики</label>
|
||||
</div>
|
||||
<p id="map-status" role="status"></p>
|
||||
</section>
|
||||
<aside class="side-panel">
|
||||
<section id="live-panel" class="card">
|
||||
<div id="object-card" class="object-card" tabindex="-1"></div>
|
||||
<label>Найти на карте<input id="object-search" type="search" autocomplete="off"></label>
|
||||
<div id="object-list" class="list scroller" aria-label="Объекты на карте"></div>
|
||||
</section>
|
||||
<section id="history-panel" class="card" hidden>
|
||||
<h2>История боя</h2>
|
||||
<label>Налёт<select id="raid"></select></label>
|
||||
<label>Момент повтора<input type="range" id="timeline" min="0" max="0" value="0" disabled></label>
|
||||
<p id="timeline-caption" aria-live="polite" class="muted"></p>
|
||||
<div class="fields">
|
||||
<label>ID комплекса<input id="event-unit" type="number" min="0" inputmode="numeric"></label>
|
||||
<label>ID контакта<input id="event-target" type="number" min="0" inputmode="numeric"></label>
|
||||
<label>ID объекта<input id="event-object" type="number" min="1" inputmode="numeric"></label>
|
||||
<label>От секунды<input id="event-since" type="number" min="0" inputmode="numeric" disabled></label>
|
||||
<label>До секунды<input id="event-until" type="number" min="0" inputmode="numeric" disabled></label>
|
||||
</div>
|
||||
<label>Поиск в журнале<input id="event-query" type="search" autocomplete="off"></label>
|
||||
<p id="history-status" role="status"></p>
|
||||
<article id="event-card" class="subcard" hidden></article>
|
||||
<div id="events" class="list scroller" aria-label="События боя"></div>
|
||||
<button type="button" id="history-more" hidden>Более ранние</button>
|
||||
</section>
|
||||
<section id="scenario-panel" class="card" hidden>
|
||||
<h2>Сценарий налёта</h2>
|
||||
<form id="scenario-form">
|
||||
<label>Готовый состав<select id="preset"></select></label>
|
||||
<div class="fields">
|
||||
<label>Подход<select id="approach"></select></label>
|
||||
<label>Цель<select id="aim"></select></label>
|
||||
<label>Расстояние, блоки<input id="distance" type="number" required inputmode="numeric"></label>
|
||||
</div>
|
||||
<div id="counts" class="fields"></div>
|
||||
<p id="scenario-summary" role="status"></p>
|
||||
<button id="preview" type="submit">Предпросмотр</button>
|
||||
</form>
|
||||
<p id="launch-status" role="status"></p>
|
||||
</section>
|
||||
</aside>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<dialog id="confirmation">
|
||||
<h2>Подтвердить сценарий</h2>
|
||||
<div id="preview-details"></div>
|
||||
<div class="toolbar">
|
||||
<button id="confirm-launch" type="button">Запустить</button>
|
||||
<button id="cancel-launch" type="button">Назад</button>
|
||||
</div>
|
||||
</dialog>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "AirDef — пульт управления",
|
||||
"short_name": "AirDef",
|
||||
"description": "Локальный планшетный пульт AirDef",
|
||||
"id": "./",
|
||||
"start_url": "./",
|
||||
"scope": "./",
|
||||
"display": "standalone",
|
||||
"background_color": "#0b121a",
|
||||
"theme_color": "#0b121a",
|
||||
"icons": [
|
||||
{ "src": "icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable" },
|
||||
{ "src": "icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
const styles = [
|
||||
["units", "unit", "#6adcd2"],
|
||||
["objects", "object", "#a9baf6"],
|
||||
["contacts", "contact", "#f0bf6a"],
|
||||
["interceptors", "interceptor", "#b2e68f"],
|
||||
];
|
||||
const clamp = (x, low, high) => Math.min(high, Math.max(low, x));
|
||||
|
||||
export function createMap(canvas, {onSelect, onView}) {
|
||||
const ctx = canvas.getContext("2d");
|
||||
const view = {x: 0, z: 0, scale: .22};
|
||||
const fingers = new Map();
|
||||
let points = [], visible = [], selected, width = 1, height = 1, drawnFrame;
|
||||
let moved = false, autoFit = true, queued = false;
|
||||
|
||||
function paint() {
|
||||
queued = false;
|
||||
const ratio = Math.min(2, window.devicePixelRatio || 1);
|
||||
width = Math.max(1, canvas.clientWidth);
|
||||
height = Math.max(1, canvas.clientHeight);
|
||||
const w = Math.round(width * ratio), h = Math.round(height * ratio);
|
||||
if (canvas.width !== w || canvas.height !== h) {
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
}
|
||||
ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
|
||||
ctx.fillStyle = "#101c24";
|
||||
ctx.fillRect(0, 0, width, height);
|
||||
const {x, z, scale} = view;
|
||||
const px = v => (v - x) * scale + width / 2;
|
||||
const py = v => (v - z) * scale + height / 2;
|
||||
const left = x - width / (2 * scale), top = z - height / (2 * scale);
|
||||
const steps = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000];
|
||||
const step = steps.find(s => s * scale >= 48) || steps.at(-1);
|
||||
ctx.strokeStyle = "#233947";
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
for (let a = Math.ceil(left / step) * step; px(a) < width; a += step) {
|
||||
const line = Math.round(px(a)) + .5;
|
||||
ctx.moveTo(line, 0);
|
||||
ctx.lineTo(line, height);
|
||||
}
|
||||
for (let a = Math.ceil(top / step) * step; py(a) < height; a += step) {
|
||||
const line = Math.round(py(a)) + .5;
|
||||
ctx.moveTo(0, line);
|
||||
ctx.lineTo(width, line);
|
||||
}
|
||||
ctx.stroke();
|
||||
ctx.font = "12px system-ui, sans-serif";
|
||||
ctx.fillStyle = "#b6c8d0";
|
||||
ctx.fillText("↑ N", width - 36, 20);
|
||||
ctx.fillText(`X ${Math.round(x)} · Z ${Math.round(z)}`, 14, 20);
|
||||
const bar = steps.find(s => s * scale >= 40) || steps.at(-1);
|
||||
ctx.fillText(`${bar} бл.`, 14, height - 23);
|
||||
ctx.fillRect(14, height - 16, bar * scale, 2);
|
||||
visible = [];
|
||||
for (const point of points) {
|
||||
const {row, color, kind} = point;
|
||||
const x = px(row.x), y = py(row.z);
|
||||
if (x < -40 || y < -40 || x > width + 40 || y > height + 40) continue;
|
||||
visible.push({...point, x, y});
|
||||
const r = point.key === selected ? 8 : 5;
|
||||
ctx.beginPath();
|
||||
if (kind === "unit") {
|
||||
ctx.rect(x - r, y - r, 2 * r, 2 * r);
|
||||
} else if (kind === "contact") {
|
||||
ctx.arc(x, y, r, 0, Math.PI * 2);
|
||||
} else {
|
||||
ctx.moveTo(x, y - r);
|
||||
ctx.lineTo(x + r, kind === "object" ? y : y + r);
|
||||
if (kind === "object") ctx.lineTo(x, y + r);
|
||||
ctx.lineTo(x - r, kind === "object" ? y : y + r);
|
||||
ctx.closePath();
|
||||
}
|
||||
ctx.strokeStyle = ctx.fillStyle = color;
|
||||
ctx.lineWidth = 2;
|
||||
if (kind !== "contact") ctx.fill();
|
||||
if (row.status?.startsWith("Оценка")) ctx.setLineDash([3, 2]);
|
||||
ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
if (point.key === selected && row.radius > 0) {
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y, Math.min(380, row.radius * scale), 0, Math.PI * 2);
|
||||
ctx.setLineDash([5, 5]);
|
||||
ctx.strokeStyle = "#798f98";
|
||||
ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
}
|
||||
if (Number.isFinite(row.vx) && Number.isFinite(row.vz)) {
|
||||
const n = Math.hypot(row.vx, row.vz) || 1;
|
||||
const length = clamp(n * scale / 3, 5, 28);
|
||||
ctx.strokeStyle = color;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x, y);
|
||||
ctx.lineTo(x + row.vx / n * length, y + row.vz / n * length);
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
const focus = visible.find(item => item.key === selected);
|
||||
if (focus) {
|
||||
const links = [
|
||||
focus.row.target != null ? `contact:${focus.row.target}` : null,
|
||||
focus.row.source != null ? `unit:${focus.row.source}` : null,
|
||||
];
|
||||
for (const key of links) {
|
||||
const other = visible.find(item => item.key === key);
|
||||
if (!other || other.key === focus.key) continue;
|
||||
ctx.strokeStyle = "#90bdc0";
|
||||
ctx.setLineDash([5, 5]);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(focus.x, focus.y);
|
||||
ctx.lineTo(other.x, other.y);
|
||||
ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
}
|
||||
ctx.font = "bold 13px system-ui, sans-serif";
|
||||
const label = focus.row.label || focus.key;
|
||||
const length = Math.min(width - 22, ctx.measureText(label).width + 12);
|
||||
const left = clamp(focus.x + 12, 8, Math.max(8, width - length - 8));
|
||||
const top = clamp(focus.y - 20, 6, Math.max(6, height - 27));
|
||||
ctx.fillStyle = "#081017";
|
||||
ctx.fillRect(left, top, length, 23);
|
||||
ctx.fillStyle = "#eaf7fa";
|
||||
ctx.fillText(label, left + 6, top + 16, length - 12);
|
||||
}
|
||||
if (!points.length) {
|
||||
ctx.fillStyle = "#9ab0bb";
|
||||
ctx.textAlign = "center";
|
||||
ctx.fillText(drawnFrame ? "На выбранных слоях нет объектов" : "Нет снимка карты", width / 2, height / 2);
|
||||
ctx.textAlign = "left";
|
||||
}
|
||||
}
|
||||
|
||||
function schedule() {
|
||||
if (!queued) {
|
||||
queued = true;
|
||||
requestAnimationFrame(paint);
|
||||
}
|
||||
}
|
||||
|
||||
function fit() {
|
||||
if (!points.length) return;
|
||||
let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity;
|
||||
for (const {row} of points) {
|
||||
minX = Math.min(minX, row.x);
|
||||
maxX = Math.max(maxX, row.x);
|
||||
minZ = Math.min(minZ, row.z);
|
||||
maxZ = Math.max(maxZ, row.z);
|
||||
}
|
||||
view.x = (maxX + minX) / 2;
|
||||
view.z = (maxZ + minZ) / 2;
|
||||
view.scale = clamp(Math.min((canvas.clientWidth - 64) / Math.max(80, maxX - minX),
|
||||
(canvas.clientHeight - 64) / Math.max(80, maxZ - minZ)), .006, 5);
|
||||
autoFit = false;
|
||||
onView({...view});
|
||||
schedule();
|
||||
}
|
||||
|
||||
function zoom(factor, x = width / 2, y = height / 2) {
|
||||
const before = view.scale;
|
||||
view.scale = clamp(before * factor, .006, 12);
|
||||
view.x += (x - width / 2) * (1 / before - 1 / view.scale);
|
||||
view.z += (y - height / 2) * (1 / before - 1 / view.scale);
|
||||
onView({...view});
|
||||
schedule();
|
||||
}
|
||||
|
||||
function coords(event) {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
return [event.clientX - rect.left, event.clientY - rect.top];
|
||||
}
|
||||
|
||||
canvas.addEventListener("wheel", event => {
|
||||
event.preventDefault();
|
||||
zoom(Math.exp(clamp(-event.deltaY * .002, -.4, .4)), ...coords(event));
|
||||
}, {passive: false});
|
||||
canvas.addEventListener("pointerdown", event => {
|
||||
if (fingers.size === 0) moved = false;
|
||||
if (fingers.size > 0) moved = true;
|
||||
canvas.setPointerCapture(event.pointerId);
|
||||
const at = coords(event);
|
||||
fingers.set(event.pointerId, {at, start: at});
|
||||
});
|
||||
canvas.addEventListener("pointermove", event => {
|
||||
const finger = fingers.get(event.pointerId);
|
||||
if (!finger) return;
|
||||
const at = coords(event), before = finger.at;
|
||||
finger.at = at;
|
||||
const dx = at[0] - before[0], dy = at[1] - before[1];
|
||||
if (fingers.size === 1) {
|
||||
if (Math.hypot(at[0] - finger.start[0], at[1] - finger.start[1]) > 5) moved = true;
|
||||
if (!moved) return;
|
||||
view.x -= dx / view.scale;
|
||||
view.z -= dy / view.scale;
|
||||
} else {
|
||||
const other = [...fingers.values()].find(value => value !== finger).at;
|
||||
const ratio = Math.hypot(at[0] - other[0], at[1] - other[1]) /
|
||||
Math.max(2, Math.hypot(before[0] - other[0], before[1] - other[1]));
|
||||
zoom(ratio, (at[0] + other[0]) / 2, (at[1] + other[1]) / 2);
|
||||
view.x -= dx / (2 * view.scale);
|
||||
view.z -= dy / (2 * view.scale);
|
||||
}
|
||||
onView({...view});
|
||||
schedule();
|
||||
});
|
||||
canvas.addEventListener("pointerup", event => {
|
||||
fingers.delete(event.pointerId);
|
||||
if (moved) return;
|
||||
const [x, y] = coords(event);
|
||||
let hit, distance = 21;
|
||||
for (const p of visible) {
|
||||
const d = Math.hypot(x - p.x, y - p.y);
|
||||
if (d < distance) [hit, distance] = [p, d];
|
||||
}
|
||||
if (hit) onSelect(hit.key);
|
||||
});
|
||||
canvas.addEventListener("pointercancel", event => fingers.delete(event.pointerId));
|
||||
new ResizeObserver(schedule).observe(canvas);
|
||||
|
||||
return {
|
||||
draw(frame, options) {
|
||||
drawnFrame = frame;
|
||||
selected = options.selected;
|
||||
points = styles.flatMap(([group, kind, color]) => options.layers[group] === false ? [] : (frame?.[group] || [])
|
||||
.filter(row => Number.isFinite(row.x) && Number.isFinite(row.z))
|
||||
.map(row => ({row, color, kind, key: `${kind}:${row.id}`})));
|
||||
if (autoFit && canvas.clientWidth > 100 && points.length) fit();
|
||||
schedule();
|
||||
},
|
||||
fit,
|
||||
zoom,
|
||||
restore(saved) {
|
||||
if (saved && [saved.x, saved.z, saved.scale].every(Number.isFinite)) {
|
||||
Object.assign(view, saved, {scale: clamp(saved.scale, .006, 12)});
|
||||
autoFit = false;
|
||||
} else {
|
||||
autoFit = true;
|
||||
}
|
||||
schedule();
|
||||
},
|
||||
focus(id) {
|
||||
const item = points.find(point => point.key === id);
|
||||
if (!item) return;
|
||||
view.x = item.row.x;
|
||||
view.z = item.row.z;
|
||||
onView({...view});
|
||||
schedule();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/* 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 scope = new URL(self.registration.scope);
|
||||
const shellUrls = FILES.map(path => new URL(path, scope).href);
|
||||
|
||||
self.addEventListener('install', event => {
|
||||
event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(shellUrls)).then(() => self.skipWaiting()));
|
||||
});
|
||||
self.addEventListener('activate', event => {
|
||||
event.waitUntil(caches.keys().then(keys => Promise.all(keys.filter(key => key.startsWith('airdef-shell-') && key !== CACHE).map(key => caches.delete(key)))).then(() => self.clients.claim()));
|
||||
});
|
||||
self.addEventListener('fetch', event => {
|
||||
const request = event.request;
|
||||
const url = new URL(request.url);
|
||||
if (request.method !== 'GET' || url.origin !== scope.origin || url.search ||
|
||||
!url.pathname.startsWith(scope.pathname) || /(^|\/)api(?:\/|$)/.test(url.pathname)) return;
|
||||
if (request.mode === 'navigate' && (url.pathname === scope.pathname || url.pathname === new URL('index.html', scope).pathname)) {
|
||||
event.respondWith(caches.match(new URL('index.html', scope).href).then(cached => cached || fetch(request)));
|
||||
} else if (shellUrls.includes(url.href)) {
|
||||
event.respondWith(caches.match(request).then(cached => cached || fetch(request)));
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,239 @@
|
||||
"""Durable, bounded local history and pairings. No game calls run under this lock."""
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
MAX_FRAMES = 3600
|
||||
MAX_FRAME_DISTANCE_TICKS = 100
|
||||
MAX_EVENTS = 30000
|
||||
MAX_RAIDS = 400
|
||||
SESSION_AGE = 30 * 24 * 60 * 60
|
||||
|
||||
|
||||
def compact(value):
|
||||
return json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
|
||||
|
||||
|
||||
def digest(token):
|
||||
return hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, path: Path):
|
||||
self.lock = threading.RLock()
|
||||
self.db = sqlite3.connect(path, check_same_thread=False)
|
||||
self.db.row_factory = sqlite3.Row
|
||||
self.db.executescript("""
|
||||
PRAGMA journal_mode=WAL;
|
||||
PRAGMA synchronous=NORMAL;
|
||||
CREATE TABLE IF NOT EXISTS frames (
|
||||
session TEXT, tick INTEGER, world TEXT, time REAL, data BLOB,
|
||||
PRIMARY KEY(session, tick)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS raids (
|
||||
session TEXT, raid INTEGER, world TEXT, time REAL, start INTEGER, length INTEGER,
|
||||
active INTEGER, gap INTEGER, PRIMARY KEY(session, raid)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, session TEXT, raid INTEGER, kind TEXT,
|
||||
seq INTEGER, tick INTEGER, unit INTEGER, target INTEGER, label TEXT, payload TEXT, object INTEGER,
|
||||
UNIQUE(session, raid, kind, seq)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS events_filter ON events(session, raid, tick);
|
||||
CREATE INDEX IF NOT EXISTS frames_retention ON frames(time);
|
||||
CREATE INDEX IF NOT EXISTS raids_retention ON raids(time);
|
||||
CREATE TABLE IF NOT EXISTS pairings (token TEXT PRIMARY KEY, role TEXT, expires REAL);
|
||||
CREATE TABLE IF NOT EXISTS launches (
|
||||
id TEXT PRIMARY KEY, owner TEXT, session TEXT, data TEXT, time REAL,
|
||||
state TEXT, message TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT);
|
||||
""")
|
||||
if not any(row["name"] == "object" for row in self.db.execute("PRAGMA table_info(events)")):
|
||||
self.db.execute("ALTER TABLE events ADD COLUMN object INTEGER")
|
||||
with self.db:
|
||||
self.db.execute("""UPDATE launches SET state='unknown', message=?
|
||||
WHERE state IN ('queued', 'dispatching')""",
|
||||
("Ответ предыдущего запуска неизвестен. Игра могла принять сценарий.",))
|
||||
|
||||
def pair(self, role):
|
||||
value = secrets.token_urlsafe(32)
|
||||
now = time.time()
|
||||
with self.lock, self.db:
|
||||
self.db.execute("DELETE FROM pairings WHERE expires < ?", (now,))
|
||||
self.db.execute("INSERT INTO pairings VALUES (?, ?, ?)", (digest(value), role, now + SESSION_AGE))
|
||||
return value
|
||||
|
||||
def role(self, value):
|
||||
if not value or len(value) != 43 or not value.isascii():
|
||||
return None
|
||||
key = digest(value)
|
||||
with self.lock:
|
||||
row = self.db.execute("SELECT role FROM pairings WHERE token=? AND expires>?", (key, time.time())).fetchone()
|
||||
return (key, row["role"]) if row else None
|
||||
|
||||
def revoke(self, key):
|
||||
with self.lock, self.db:
|
||||
self.db.execute("DELETE FROM pairings WHERE token=?", (key,))
|
||||
|
||||
def revoke_all(self):
|
||||
with self.lock, self.db:
|
||||
self.db.execute("DELETE FROM pairings")
|
||||
|
||||
def append(self, snapshot, public):
|
||||
session, world, tick = snapshot["session"], snapshot["world"], snapshot["tick"]
|
||||
active = next((raid["id"] for raid in snapshot["raids"] if raid["active"]), 0)
|
||||
now = time.time()
|
||||
frame = zlib.compress(compact(public).encode("utf-8"), level=1)
|
||||
with self.lock, self.db:
|
||||
self.db.execute("INSERT OR IGNORE INTO frames VALUES (?, ?, ?, ?, ?)",
|
||||
(session, tick, world, now, frame))
|
||||
for raid in snapshot["raids"]:
|
||||
fields = (session, raid["id"], world, now, raid["start"], raid["length"],
|
||||
int(raid["active"]), int(raid["gap"] or raid["limited"]))
|
||||
self.db.execute("""INSERT INTO raids VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(session,raid) DO UPDATE SET length=excluded.length, active=excluded.active,
|
||||
gap=max(raids.gap,excluded.gap)""", fields)
|
||||
for kind in ("events", "decisions", "observations"):
|
||||
self.db.executemany("""INSERT OR IGNORE INTO events
|
||||
(session,raid,kind,seq,tick,unit,target,label,payload,object) VALUES (?,?,?,?,?,?,?,?,?,?)""",
|
||||
((session, raid["id"], kind, e["seq"], raid["start"] + e["at"],
|
||||
e["unit"], e["target"], e["label"], compact(e), e.get("object")) for e in raid.get(kind, ())))
|
||||
self.db.execute("""UPDATE raids SET active=0, gap=1
|
||||
WHERE active=1 AND (session<>? OR raid<>?)""", (session, active))
|
||||
# Keep only the most recent bounded window. Tell clients when history has aged out.
|
||||
removed = self.db.execute("""DELETE FROM events WHERE id < coalesce(
|
||||
(SELECT id FROM events ORDER BY id DESC LIMIT 1 OFFSET ?),0)""", (MAX_EVENTS - 1,)).rowcount
|
||||
gone = self.db.execute("""DELETE FROM raids WHERE rowid IN
|
||||
(SELECT rowid FROM raids ORDER BY time DESC LIMIT -1 OFFSET ?)""", (MAX_RAIDS,)).rowcount
|
||||
if removed or gone:
|
||||
self.db.execute("INSERT OR REPLACE INTO metadata VALUES ('history_limited','1')")
|
||||
self.db.execute("""DELETE FROM frames WHERE rowid IN
|
||||
(SELECT rowid FROM frames ORDER BY time DESC LIMIT -1 OFFSET ?)""", (MAX_FRAMES,))
|
||||
|
||||
def raids(self):
|
||||
with self.lock:
|
||||
rows = self.db.execute("SELECT * FROM raids ORDER BY time DESC, raid DESC LIMIT ?", (MAX_RAIDS,)).fetchall()
|
||||
limited = self.db.execute("SELECT value FROM metadata WHERE key='history_limited'").fetchone()
|
||||
return {"raids": [dict(row) for row in rows], "limited": limited is not None}
|
||||
|
||||
def events(self, *, session=None, raid=None, unit=None, target=None, object=None, kind=None,
|
||||
after=None, before=None, since=None, until=None, query="", limit=100):
|
||||
conditions = []
|
||||
values = []
|
||||
for field, value in (("session", session), ("raid", raid), ("unit", unit), ("target", target),
|
||||
("object", object), ("kind", kind)):
|
||||
if value is not None:
|
||||
conditions.append(f"{field}=?")
|
||||
values.append(value)
|
||||
for clause, value in (("id>?", after), ("id<?", before), ("tick>=?", since), ("tick<=?", until)):
|
||||
if value is not None:
|
||||
conditions.append(clause)
|
||||
values.append(value)
|
||||
statement = "SELECT * FROM events"
|
||||
if conditions:
|
||||
statement += " WHERE " + " AND ".join(conditions)
|
||||
statement += " ORDER BY id " + ("ASC" if after is not None else "DESC")
|
||||
if not query:
|
||||
statement += " LIMIT ?"
|
||||
values.append(limit + 1)
|
||||
with self.lock:
|
||||
rows = self.db.execute(statement, values)
|
||||
if query:
|
||||
wanted = query.casefold()
|
||||
selected = []
|
||||
for row in rows:
|
||||
if wanted in row["label"].casefold() or wanted in row["payload"].casefold():
|
||||
selected.append(row)
|
||||
if len(selected) > limit:
|
||||
break
|
||||
rows = selected
|
||||
else:
|
||||
rows = rows.fetchall()
|
||||
output = [event_row(row) for row in rows[:limit]]
|
||||
first = output[0]["id"] if output else None
|
||||
last = output[-1]["id"] if output else None
|
||||
return {"events": output, "first": first, "last": last, "more": len(rows) > limit}
|
||||
|
||||
def chain(self, event_id):
|
||||
with self.lock:
|
||||
event = self.db.execute("SELECT * FROM events WHERE id=?", (event_id,)).fetchone()
|
||||
if not event:
|
||||
return None
|
||||
context = event["target"] is None
|
||||
if context and event["unit"] is None:
|
||||
return {"events": [], "context": True}
|
||||
base = "SELECT * FROM events WHERE session=? AND raid=?"
|
||||
args = [event["session"], event["raid"]]
|
||||
if context:
|
||||
base += " AND unit=? AND tick BETWEEN ? AND ?"
|
||||
args.extend([event["unit"], max(0, event["tick"] - 200), event["tick"] + 200])
|
||||
else:
|
||||
base += " AND target=?"
|
||||
args.append(event["target"])
|
||||
rows = self.db.execute(base + " ORDER BY id<>?, abs(tick - ?), id LIMIT 41",
|
||||
[*args, event_id, event["tick"]]).fetchall()
|
||||
kinds = {"observations": 0, "decisions": 1, "events": 2}
|
||||
return {
|
||||
"events": [event_row(row) for row in sorted(rows[:40], key=lambda row: (row["tick"], kinds[row["kind"]], row["id"]))],
|
||||
"context": context, "limited": len(rows) > 40,
|
||||
}
|
||||
|
||||
def frame(self, session, tick):
|
||||
with self.lock:
|
||||
before = self.db.execute("""SELECT data, tick FROM frames
|
||||
WHERE session=? AND tick<=? ORDER BY tick DESC LIMIT 1""", (session, tick)).fetchone()
|
||||
after = self.db.execute("""SELECT data, tick FROM frames
|
||||
WHERE session=? AND tick>=? ORDER BY tick ASC LIMIT 1""", (session, tick)).fetchone()
|
||||
candidates = [row for row in (before, after) if row is not None]
|
||||
if not candidates:
|
||||
return None
|
||||
nearest = min(candidates, key=lambda row: abs(tick - row["tick"]))
|
||||
if abs(tick - nearest["tick"]) > MAX_FRAME_DISTANCE_TICKS:
|
||||
return None
|
||||
data = nearest["data"]
|
||||
return {"requested": tick, "frame": json.loads(zlib.decompress(data) if isinstance(data, bytes) else data)}
|
||||
|
||||
def reserve_launch(self, key, owner, session, data):
|
||||
with self.lock, self.db:
|
||||
previous = self.db.execute("SELECT * FROM launches WHERE id=?", (key,)).fetchone()
|
||||
if previous:
|
||||
if (previous["owner"], previous["session"], previous["data"]) != (owner, session, data):
|
||||
raise ValueError("ID уже связан с другим запросом")
|
||||
return self.launch_result(previous), False
|
||||
self.db.execute("INSERT INTO launches VALUES (?, ?, ?, ?, ?, 'queued', ?)",
|
||||
(key, owner, session, data, time.time(), "Ожидает ответа игры"))
|
||||
return {"id": key, "state": "queued", "message": "Ожидает ответа игры"}, True
|
||||
|
||||
@staticmethod
|
||||
def launch_result(row):
|
||||
return {key: row[key] for key in ("id", "state", "message")}
|
||||
|
||||
def launch(self, key, owner):
|
||||
with self.lock:
|
||||
row = self.db.execute("SELECT * FROM launches WHERE id=? AND owner=?", (key, owner)).fetchone()
|
||||
return self.launch_result(row) if row else None
|
||||
|
||||
def previous_launch(self, key, owner, session, data):
|
||||
with self.lock:
|
||||
row = self.db.execute("SELECT * FROM launches WHERE id=?", (key,)).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
if (row["owner"], row["session"], row["data"]) != (owner, session, data):
|
||||
raise ValueError("ID уже связан с другим запросом")
|
||||
return self.launch_result(row)
|
||||
|
||||
def complete_launch(self, key, state, message):
|
||||
with self.lock, self.db:
|
||||
self.db.execute("UPDATE launches SET state=?, message=? WHERE id=?", (state, message, key))
|
||||
|
||||
|
||||
def event_row(row):
|
||||
row = dict(row)
|
||||
row["data"] = json.loads(row.pop("payload"))
|
||||
return row
|
||||
Reference in New Issue
Block a user