Устройство не поддерживает WebGL 2. Работа с участками и консолью доступна.
diff --git a/greenhouse/.dockerignore b/greenhouse/.dockerignore new file mode 100644 index 0000000..7448b49 --- /dev/null +++ b/greenhouse/.dockerignore @@ -0,0 +1,3 @@ +**/__pycache__ +*.pyc +.git diff --git a/greenhouse/.gitignore b/greenhouse/.gitignore new file mode 100644 index 0000000..93fcd87 --- /dev/null +++ b/greenhouse/.gitignore @@ -0,0 +1,2 @@ +**/__pycache__/ +*.pyc diff --git a/greenhouse/.goctf-compose b/greenhouse/.goctf-compose new file mode 100644 index 0000000..e69de29 diff --git a/greenhouse/Dockerfile b/greenhouse/Dockerfile new file mode 100644 index 0000000..f1d29ed --- /dev/null +++ b/greenhouse/Dockerfile @@ -0,0 +1,12 @@ +FROM python:3.12-slim +WORKDIR /greenhouse +COPY native/greenhouse-console /greenhouse/greenhouse-console +COPY app/ /greenhouse/app/ +COPY frontend/ /greenhouse/frontend/ +COPY start.sh /greenhouse/start.sh +RUN chmod +x /greenhouse/greenhouse-console /greenhouse/start.sh && mkdir -p /data && useradd -m -u 10001 greenhouse && chown greenhouse:greenhouse /data +USER greenhouse +ENV GREENHOUSE_DATA=/data PORT=8080 +VOLUME ["/data"] +EXPOSE 8080 +CMD ["/greenhouse/start.sh"] diff --git a/greenhouse/app/server.py b/greenhouse/app/server.py new file mode 100644 index 0000000..9217004 --- /dev/null +++ b/greenhouse/app/server.py @@ -0,0 +1,299 @@ +import hashlib +import json +import mimetypes +import os +import re +import secrets +import socket +import sqlite3 +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + +ROOT = Path(__file__).resolve().parent.parent +DATA = Path(os.environ.get("GREENHOUSE_DATA", "/data")) +DATA.mkdir(parents=True, exist_ok=True) +DB = DATA / "greenhouse.sqlite3" +PUBLIC_ID = "public" +PUBLIC_TOKEN = "visitor" +CONSOLE_SOCKET = DATA / "console.sock" +CONSOLE_SESSIONS = {} +CONSOLE_LOCK = threading.Lock() +CONSOLE_IDLE_SECONDS = 300 +CONSOLE_LIMIT = 64 + + +class ConsoleSession: + def __init__(self): + self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + self.socket.settimeout(4) + self.socket.connect(str(CONSOLE_SOCKET)) + self.stream = self.socket.makefile("rwb", buffering=0) + self.lock = threading.Lock() + self.last_used = time.monotonic() + self.closed = False + self.banner = [self.read_line(), self.read_line()] + except Exception: + if hasattr(self, "stream"): + self.stream.close() + self.socket.close() + raise + + def read_line(self): + line = self.stream.readline(65537) + if not line or len(line) > 65536 or not line.endswith(b"\n"): + raise ConnectionError("specimen console disconnected") + return line.decode("utf-8", errors="replace").rstrip("\r\n") + + def command(self, line): + with self.lock: + if self.closed: + raise ConnectionError("operator session closed") + self.last_used = time.monotonic() + self.stream.write((line + "\n").encode()) + reply = self.read_line() + self.last_used = time.monotonic() + return reply + + def close(self): + with self.lock: + if self.closed: + return + self.closed = True + try: + self.stream.close() + finally: + self.socket.close() + + +def prune_consoles(): + now = time.monotonic() + for session_id, session in list(CONSOLE_SESSIONS.items()): + if now - session.last_used > CONSOLE_IDLE_SECONDS: + CONSOLE_SESSIONS.pop(session_id, None) + session.close() + + +def connection(): + db = sqlite3.connect(DB, timeout=10) + db.row_factory = sqlite3.Row + db.execute("PRAGMA journal_mode=WAL") + db.execute("""CREATE TABLE IF NOT EXISTS plots ( + id TEXT PRIMARY KEY, token TEXT NOT NULL, name TEXT NOT NULL, + cultivar TEXT NOT NULL, note TEXT NOT NULL, archive TEXT NOT NULL, + created INTEGER DEFAULT (unixepoch()))""") + db.execute("""CREATE TABLE IF NOT EXISTS telemetry ( + id INTEGER PRIMARY KEY, plot TEXT NOT NULL, kind TEXT NOT NULL, + value TEXT NOT NULL, created INTEGER DEFAULT (unixepoch()))""") + db.execute("INSERT OR IGNORE INTO plots(id,token,name,cultivar,note,archive) VALUES (?,?,?,?,?,?)", + (PUBLIC_ID, PUBLIC_TOKEN, "Публичный купол", "Helianthus orbitalis", + "Добро пожаловать на станцию ОРБИТА.КВАНТУМ", "Калибровка открытого контура")) + db.commit() + return db + + +def row_public(row): + return {"id": row["id"], "name": row["name"], "cultivar": row["cultivar"], + "created": row["created"]} + + +def mask(id_, n): + out = [] + counter = 0 + while len(out) < n: + out.extend(hashlib.sha256(f"orbita-spectrum:{id_}:{counter}".encode()).digest()) + counter += 1 + return out[:n] + + +class Handler(BaseHTTPRequestHandler): + server_version = "OrbitaOrangery/2126" + + def log_message(self, fmt, *args): + print("%s %s" % (self.address_string(), fmt % args), flush=True) + + def reply(self, code, payload): + body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Cache-Control", "no-store") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def body(self): + length = int(self.headers.get("Content-Length", "0")) + if length > 8192 or length < 0: + raise ValueError("payload too large") + return json.loads(self.rfile.read(length)) + + def token(self, query): + return self.headers.get("X-Greenhouse-Key", "") or query.get("key", [""])[0] + + def do_GET(self): + parts = urlsplit(self.path) + path = parts.path + q = parse_qs(parts.query, keep_blank_values=True) + if path == "/api/status": + return self.reply(200, {"station": "ОРБИТА.КВАНТУМ", "module": "ОРАНЖЕРЕЯ", + "year": 2126, "oxygen": 98.7, "temperature": 23.4, + "state": "nominal"}) + if path.startswith("/api/"): + return self.get_api(path, q) + relative = path.lstrip("/") or "index.html" + if relative.startswith("frontend/"): + relative = relative.removeprefix("frontend/") + frontend = ROOT / "frontend" + target = (frontend / relative).resolve() + if not target.is_relative_to(frontend) or not target.is_file(): + self.send_error(404) + return + content_type = mimetypes.guess_type(target.name)[0] or "application/octet-stream" + if target.suffix == ".js": + content_type = "text/javascript" + content = target.read_bytes() + self.send_response(200) + self.send_header("Content-Type", content_type + ("; charset=utf-8" if content_type.startswith("text/") or content_type in {"image/svg+xml", "application/json"} else "")) + self.send_header("Content-Length", str(len(content))) + self.end_headers() + self.wfile.write(content) + + def get_api(self, path, q): + with connection() as db: + if path == "/api/plots": + rows = db.execute("SELECT * FROM plots ORDER BY created DESC LIMIT 100").fetchall() + return self.reply(200, {"plots": [row_public(r) for r in rows]}) + if path.startswith("/api/plots/"): + id_ = path[len("/api/plots/"):] + row = db.execute("SELECT * FROM plots WHERE id=?", (id_,)).fetchone() + if row is None: + return self.reply(404, {"error": "unknown plot"}) + if self.token(q) != row["token"]: + return self.reply(403, {"error": "capability required"}) + return self.reply(200, {**row_public(row), "note": row["note"]}) + if path == "/api/archive": + id_ = q.get("plot", [""])[0] + row = db.execute("SELECT * FROM plots WHERE id=?", (id_,)).fetchone() + if row is None: + return self.reply(404, {"error": "unknown plot"}) + if self.token(q) != row["token"]: + return self.reply(403, {"error": "capability required"}) + return self.reply(200, {"plot": id_, "archive": row["archive"]}) + if path == "/api/telemetry": + id_ = q.get("plot", [""])[0] + rows = db.execute("SELECT kind,value,created FROM telemetry WHERE plot=? ORDER BY id DESC LIMIT 40", (id_,)).fetchall() + return self.reply(200, {"plot": id_, "telemetry": [dict(r) for r in rows]}) + if path == "/api/projection": + target = q.get("target", [PUBLIC_ID])[0] + anchor = target.split("#", 1)[0] + anchor_row = db.execute("SELECT * FROM plots WHERE id=?", (anchor,)).fetchone() + if anchor_row is None or self.token(q) != anchor_row["token"]: + return self.reply(403, {"error": "lens capability required"}) + focus = target.rsplit("#", 1)[-1] + row = db.execute("SELECT * FROM plots WHERE id=?", (focus,)).fetchone() + if row is None: + return self.reply(404, {"error": "no focus"}) + return self.reply(200, {"anchor": anchor, "focus": focus, + "projection": {**row_public(row), "biometric_note": row["note"]}}) + if path == "/api/spectrum": + id_ = q.get("plot", [""])[0] + row = db.execute("SELECT archive FROM plots WHERE id=?", (id_,)).fetchone() + if row is None: + return self.reply(404, {"error": "unknown plot"}) + raw = row["archive"].encode() + salt = mask(id_, len(raw)) + previous = 0 + samples = [] + for byte, offset in zip(raw, salt): + value = (byte + previous + offset) % 257 + samples.append(value) + previous = value + return self.reply(200, {"plot": id_, "field": 257, "phase": "orbita-spectrum", + "samples": samples}) + return self.reply(404, {"error": "unknown endpoint"}) + + def do_POST(self): + try: + payload = self.body() + if not isinstance(payload, dict): + raise ValueError("object expected") + if self.path == "/api/console/open": + with CONSOLE_LOCK: + prune_consoles() + if len(CONSOLE_SESSIONS) >= CONSOLE_LIMIT: + return self.reply(429, {"error": "operator channels busy"}) + try: + console = ConsoleSession() + except (OSError, ConnectionError) as exc: + return self.reply(503, {"error": f"specimen console unavailable: {exc}"}) + session_id = secrets.token_hex(16) + CONSOLE_SESSIONS[session_id] = console + return self.reply(201, {"session": session_id, "banner": console.banner}) + if self.path == "/api/console/command": + session_id = payload.get("session") + line = payload.get("command") + if not isinstance(session_id, str) or not re.fullmatch(r"[0-9a-f]{32}", session_id): + raise ValueError("invalid operator session") + if not isinstance(line, str) or not line.strip() or len(line) > 1024 or any(c in line for c in "\r\n\x00"): + raise ValueError("invalid console command") + with CONSOLE_LOCK: + console = CONSOLE_SESSIONS.get(session_id) + if console is None: + return self.reply(404, {"error": "operator session expired"}) + try: + result = console.command(line.strip()) + except (OSError, ConnectionError) as exc: + with CONSOLE_LOCK: + CONSOLE_SESSIONS.pop(session_id, None) + console.close() + return self.reply(502, {"error": f"specimen console disconnected: {exc}"}) + return self.reply(200, {"reply": result}) + if self.path == "/api/console/close": + session_id = payload.get("session") + if not isinstance(session_id, str) or not re.fullmatch(r"[0-9a-f]{32}", session_id): + raise ValueError("invalid operator session") + with CONSOLE_LOCK: + console = CONSOLE_SESSIONS.pop(session_id, None) + if console is not None: + console.close() + return self.reply(200, {"ok": True}) + if self.path == "/api/plots": + name = str(payload.get("name", ""))[:160] + cultivar = str(payload.get("cultivar", ""))[:160] + note = str(payload.get("note", ""))[:4000] + archive = str(payload.get("archive", ""))[:512] + if not name or not cultivar: + raise ValueError("name and cultivar required") + id_ = secrets.token_hex(8) + supplied = payload.get("key") + token = str(supplied) if supplied is not None else secrets.token_hex(16) + if not re.fullmatch(r"[0-9a-f]{32}", token): + raise ValueError("invalid capability") + with connection() as db: + db.execute("INSERT INTO plots(id,token,name,cultivar,note,archive) VALUES (?,?,?,?,?,?)", + (id_, token, name, cultivar, note, archive)) + db.commit() + return self.reply(201, {"id": id_, "key": token}) + if self.path == "/api/telemetry": + id_ = str(payload.get("plot", "")) + kind = str(payload.get("kind", ""))[:32] + value = str(payload.get("value", ""))[:128] + if not id_ or not kind: + raise ValueError("invalid telemetry") + with connection() as db: + if not db.execute("SELECT 1 FROM plots WHERE id=?", (id_,)).fetchone(): + return self.reply(404, {"error": "unknown plot"}) + db.execute("INSERT INTO telemetry(plot,kind,value) VALUES (?,?,?)", (id_, kind, value)) + db.commit() + return self.reply(201, {"ok": True}) + return self.reply(404, {"error": "unknown endpoint"}) + except (ValueError, json.JSONDecodeError) as exc: + return self.reply(400, {"error": str(exc)}) + + +if __name__ == "__main__": + connection().close() + ThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8080"))), Handler).serve_forever() diff --git a/greenhouse/compose.yml b/greenhouse/compose.yml new file mode 100644 index 0000000..951bc8c --- /dev/null +++ b/greenhouse/compose.yml @@ -0,0 +1,15 @@ +name: greenhouse + +services: + greenhouse: + platform: linux/amd64 + build: . + restart: unless-stopped + ports: + - "8080:8080" + volumes: + - greenhouse_data:/data + pids_limit: 256 + mem_limit: 512m +volumes: + greenhouse_data: diff --git a/greenhouse/frontend/app.js b/greenhouse/frontend/app.js new file mode 100644 index 0000000..1c3e5f6 --- /dev/null +++ b/greenhouse/frontend/app.js @@ -0,0 +1,228 @@ +'use strict'; +(() => { + const $ = selector => document.querySelector(selector); + const state = { plots: [], selected: null, detail: null, selectionVersion: 0, listLoaded: false }; + const keyStorage = 'greenhouse.plot-keys.v1'; + let plotKeys = Object.create(null); + try { const saved = JSON.parse(localStorage.getItem(keyStorage) || '{}'); if (saved && typeof saved === 'object' && !Array.isArray(saved)) Object.assign(plotKeys, saved); } catch {} + const keyFor = id => String(id) === 'public' ? 'visitor' : plotKeys[String(id)]; + function saveKey(id, key) { + plotKeys[String(id)] = key; + try { localStorage.setItem(keyStorage, JSON.stringify(plotKeys)); return true; } catch { return false; } + } + const labels = { temperature: 'Температура', humidity: 'Влажность', oxygen: 'Кислород', biometrics: 'Биометрия', co2: 'Углекислый газ', light: 'Освещённость', ph: 'Кислотность' }; + const text = value => value == null ? '—' : typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value); + const node = (tag, className, content) => { const el = document.createElement(tag); if (className) el.className = className; if (content != null) el.textContent = text(content); return el; }; + const idOf = plot => plot && typeof plot === 'object' ? plot.id ?? plot.plot_id : plot; + const unwrap = (data, key) => data && typeof data === 'object' ? data[key] ?? data.data ?? data : data; + function collection(data, keys) { + if (Array.isArray(data)) return data; + for (const key of [...keys, 'items', 'data']) { + if (Array.isArray(data?.[key])) return data[key]; + if (data?.[key] && typeof data[key] === 'object') return collection(data[key], keys); + } + return data == null ? [] : [data]; + } + async function api(path, payload, capability) { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 15000); + try { + const response = await fetch(`/api${path}`, { method: payload === undefined ? 'GET' : 'POST', headers: { Accept: 'application/json', ...(capability ? { 'X-Greenhouse-Key': capability } : {}), ...(payload === undefined ? {} : { 'Content-Type': 'application/json' }) }, ...(payload === undefined ? {} : { body: JSON.stringify(payload) }), signal: controller.signal, cache: 'no-store' }); + const raw = await response.text(); + let data; + try { data = raw ? JSON.parse(raw) : null; } catch { if (response.ok) throw new Error('Сервис вернул некорректный JSON.'); } + if (!response.ok) throw new Error(`Ошибка ${response.status}: ${text(data?.error ?? data?.message ?? response.statusText).slice(0, 240)}`); + return data; + } catch (error) { + if (error.name === 'AbortError') throw new Error('Станция не ответила за 15 секунд. Повторите запрос.'); + if (error instanceof TypeError) throw new Error('Нет связи с API. Проверьте подключение к станции.'); + throw error; + } finally { clearTimeout(timer); } + } + let toastTimer; + function toast(message) { $('#toast').textContent = message; $('#toast').hidden = false; clearTimeout(toastTimer); toastTimer = setTimeout(() => { $('#toast').hidden = true; }, 5000); } + function empty(target, message, error = false) { target.replaceChildren(node('p', error ? 'inline-error' : 'empty', message)); } + function renderPlots() { + const query = $('#plot-search').value.trim().toLocaleLowerCase('ru'); + const filtered = state.plots.filter(plot => `${text(plot.name)} ${text(plot.cultivar)} ${text(idOf(plot))}`.toLocaleLowerCase('ru').includes(query)); + const target = $('#plot-list'); target.replaceChildren(); + if (!filtered.length) return empty(target, query ? 'Участки не найдены. Попробуйте другой запрос.' : 'Здесь пока нет участков. Создайте первый, чтобы начать наблюдения.'); + for (const plot of filtered) { + const id = idOf(plot); + const button = node('button', 'plot-card'); button.type = 'button'; button.setAttribute('aria-pressed', String(String(id) === String(state.selected))); button.setAttribute('aria-controls', 'plot-detail'); + const icon = node('span', 'plant-icon', '•'); icon.setAttribute('aria-hidden', 'true'); + const copy = node('span', 'plot-card-copy'); copy.append(node('strong', '', plot.name ?? `Участок ${text(id)}`), node('small', '', plot.cultivar ?? 'Культура не указана')); + button.append(icon, copy, node('span', 'arrow', '↗')); + if (id == null) { button.disabled = true; button.title = 'API не передал идентификатор участка'; } + else button.addEventListener('click', () => selectPlot(id)); + target.append(button); + } + } + function renderDetail(plot) { + const target = $('#plot-detail'); target.replaceChildren(); + const top = node('div', 'detail-top'); top.append(node('span', 'eyebrow', 'Паспорт'), node('span', 'pill', `ID / ${text(idOf(plot) ?? state.selected)}`)); + target.append(top, node('h3', '', plot.name ?? 'Участок')); + const dl = node('dl'); + for (const [label, value] of [['Культура', plot.cultivar], ['Заметка', plot.note ?? 'Заметок пока нет.']]) dl.append(node('dt', '', label), node('dd', '', value)); + target.append(dl); + } + function timestamp(value) { if (value == null) return ''; const date = new Date(typeof value === 'number' && value < 1e12 ? value * 1000 : value); return Number.isNaN(date.getTime()) ? text(value) : date.toLocaleString('ru-RU', { dateStyle: 'short', timeStyle: 'short' }); } + function renderRecords(target, data, archive) { + if (archive && typeof data?.archive === 'string') { + target.replaceChildren(); + if (data.archive) target.append(node('pre', 'raw-data', data.archive)); + else empty(target, 'Архив этого участка пока пуст.'); + return; + } + const rows = collection(data, archive ? ['archive', 'records', 'entries'] : ['telemetry', 'records', 'readings']); + target.replaceChildren(); + if (!rows.length) return empty(target, archive ? 'Архив этого участка пока пуст.' : 'Показаний пока нет. Добавьте первое наблюдение.'); + for (const row of rows) { + if (row == null || typeof row !== 'object' || (!('kind' in row) && !('value' in row) && !('message' in row) && !('note' in row))) { target.append(node('pre', 'raw-data', row)); continue; } + const item = node('div', 'record'), copy = node('div'); + copy.append(node('strong', '', labels[row.kind] ?? row.kind ?? row.title ?? 'Наблюдение')); + const date = timestamp(row.timestamp ?? row.created_at ?? row.created ?? row.time); if (date) copy.append(node('small', '', date)); + item.append(copy, node('span', 'record-value', row.value ?? row.message ?? row.note)); target.append(item); + } + } + async function loadRecords(id, version, archive = false) { + const target = $(archive ? '#archive-content' : '#telemetry-content'); + if (archive && !keyFor(id)) { target.removeAttribute('aria-busy'); empty(target, 'Для чтения архива нужен ключ доступа к этому участку. В этом браузере ключ не сохранён.'); return; } + empty(target, 'Получаем данные станции…'); target.setAttribute('aria-busy', 'true'); + try { + const data = await api(`/${archive ? 'archive' : 'telemetry'}?plot=${encodeURIComponent(id)}`, undefined, archive ? keyFor(id) : undefined); + if (version !== state.selectionVersion) return; + renderRecords(target, data, archive); + } catch (error) { if (version === state.selectionVersion) empty(target, `${error.message} Нажмите «Обновить», чтобы повторить.`, true); } + finally { if (version === state.selectionVersion) target.removeAttribute('aria-busy'); } + } + async function selectPlot(id) { + state.selected = id; state.detail = null; + $('#selected-label').textContent = state.plots.find(plot => String(idOf(plot)) === String(id))?.name ?? `Участок ${id}`; + $('#key-form').hidden = Boolean(keyFor(id)); + const version = ++state.selectionVersion; + renderPlots(); $('#open-telemetry').disabled = false; + empty($('#plot-detail'), 'Загружаем паспорт участка…'); $('#plot-detail').setAttribute('aria-busy', 'true'); + const detailRequest = (async () => { + try { + if (!keyFor(id)) { + empty($('#plot-detail'), 'Нужен ключ доступа. Паспорт этого участка закрыт: создайте собственный участок или откройте его в браузере, где сохранён выданный ключ. Телеметрия доступна без ключа.'); + return; + } + const plot = unwrap(await api(`/plots/${encodeURIComponent(id)}`, undefined, keyFor(id)), 'plot'); + if (version !== state.selectionVersion) return; + if (!plot || typeof plot !== 'object' || Array.isArray(plot)) throw new Error('Сервис не вернул паспорт участка.'); + state.detail = plot; renderDetail(plot); $('#open-telemetry').disabled = false; + } catch (error) { if (version === state.selectionVersion) { empty($('#plot-detail'), `${error.message} Нажмите «Обновить», чтобы повторить.`, true); $('#key-form').hidden = String(id) === 'public'; } } + finally { if (version === state.selectionVersion) $('#plot-detail').removeAttribute('aria-busy'); } + })(); + await Promise.allSettled([detailRequest, loadRecords(id, version), loadRecords(id, version, true)]); + } + async function loadPlots() { + const data = await api('/plots'); + state.plots = collection(data, ['plots']).map(plot => typeof plot === 'object' && plot !== null ? plot : { id: plot }); state.listLoaded = true; + $('#plot-count').textContent = state.plots.length; $('#nav-count').textContent = String(state.plots.length).padStart(2, '0'); $('#metric-plots').textContent = state.plots.length; + renderPlots(); + } + async function loadStatus() { + try { + const data = await api('/status'); const status = data?.data ?? data; + const statusText = typeof status === 'string' ? status : status?.status ?? status?.state ?? (status?.ok === true ? 'ok' : 'На связи'); + $('#metric-status').textContent = ({ nominal: 'В норме', ok: 'В норме', healthy: 'В норме', online: 'На связи', degraded: 'Внимание', error: 'Ошибка', offline: 'Не в сети' })[statusText] ?? text(statusText); + $('#metric-oxygen').textContent = text(status?.oxygen ?? status?.o2 ?? status?.oxygen_regeneration); + $('#metric-temperature').textContent = status?.temperature == null ? '—' : `${text(status.temperature)} °C`; + $('#last-update').textContent = `Обновлено в ${new Date().toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' })}`; + } catch (error) { + $('#metric-status').textContent = 'Нет данных'; $('#metric-oxygen').textContent = '—'; $('#metric-temperature').textContent = '—'; + $('#last-update').textContent = 'Нет актуального ответа'; throw error; + } + } + let refreshing = false; + async function refresh() { + if (refreshing) return; refreshing = true; $('#refresh').disabled = true; $('#global-error').hidden = true; + const results = await Promise.allSettled([loadStatus(), loadPlots()]); + const failures = results.filter(result => result.status === 'rejected'); + if (failures.length) { + $('#global-error').textContent = `${failures.map(result => result.reason.message).filter((v, i, a) => a.indexOf(v) === i).join(' ')} Нажмите «Обновить», чтобы повторить.${state.listLoaded && results[1].status === 'rejected' ? ' В реестре показаны ранее загруженные данные.' : ''}`; $('#global-error').hidden = false; + if (!state.listLoaded) empty($('#plot-list'), 'Реестр недоступен. Повторите загрузку кнопкой «Обновить».', true); + } + if (state.selected != null) await selectPlot(state.selected); + else if (state.plots.some(plot => String(idOf(plot)) === 'public')) await selectPlot('public'); + refreshing = false; $('#refresh').disabled = false; + } + function openDialog(selector) { const dialog = $(selector); dialog.querySelector('.form-error').textContent = ''; dialog.showModal(); } + document.querySelectorAll('[data-close]').forEach(button => button.addEventListener('click', () => button.closest('dialog').close())); + document.querySelectorAll('dialog').forEach(dialog => dialog.addEventListener('cancel', event => { if (dialog.dataset.busy === 'true') event.preventDefault(); })); + $('#open-create').addEventListener('click', () => openDialog('#create-dialog')); + $('#open-telemetry').addEventListener('click', () => { if (state.selected == null) return; $('#telemetry-plot-name').textContent = `Участок: ${text(state.detail?.name ?? state.selected)}`; $('#telemetry-form').dataset.plot = state.selected; openDialog('#telemetry-dialog'); }); + async function submit(event, operation) { + event.preventDefault(); const form = event.currentTarget, dialog = form.closest('dialog'); + if (dialog.dataset.busy === 'true') return; + const payload = Object.fromEntries(new FormData(form)); + for (const key of Object.keys(payload)) payload[key] = payload[key].trim(); + const errorTarget = form.querySelector('.form-error'); errorTarget.textContent = ''; + if (Object.entries(payload).some(([key, value]) => key !== 'note' && !value)) { errorTarget.textContent = 'Заполните обязательные поля.'; return; } + dialog.dataset.busy = 'true'; form.setAttribute('aria-busy', 'true'); + const controls = [...form.querySelectorAll('button,input,textarea,select')]; controls.forEach(el => { el.disabled = true; }); + try { await operation(payload, form, dialog); } + catch (error) { errorTarget.textContent = error.message; } + finally { dialog.dataset.busy = 'false'; form.removeAttribute('aria-busy'); controls.forEach(el => { el.disabled = false; }); } + } + $('#create-form').addEventListener('submit', event => submit(event, async (payload, form, dialog) => { + const data = await api('/plots', payload); const id = idOf(unwrap(data, 'plot')); + + const created = unwrap(data, 'plot'); + const key = created?.key ?? data?.key; + const stored = id != null && typeof key === 'string' && key ? saveKey(id, key) : null; + dialog.close(); form.reset(); toast('Участок создан. Ключ доступа сохранён.'); + if (stored === false) { $('#global-error').textContent = 'Участок создан. Браузер запретил localStorage: ключ доступен только до перезагрузки этой страницы.'; $('#global-error').hidden = false; } + if (stored === null) { $('#global-error').textContent = 'Участок создан, но API не вернул ключ доступа. Паспорт и архив недоступны.'; $('#global-error').hidden = false; } + try { await loadPlots(); } catch (error) { $('#global-error').textContent = `Участок создан, но реестр не обновлён. ${error.message}`; $('#global-error').hidden = false; } + if (id != null) { $('#plot-search').value = ''; await selectPlot(id); showTerminal('plots', $('#terminal-launch')); } + else { $('#global-error').textContent = 'Участок создан, но API не вернул его ID. Выберите его в реестре или обновите список.'; $('#global-error').hidden = false; } + })); + $('#telemetry-form').addEventListener('submit', event => submit(event, async (payload, form, dialog) => { + const value = Number(payload.value); if (!Number.isFinite(value)) throw new Error('Введите конечное числовое значение.'); + const plot = state.plots.find(item => String(idOf(item)) === form.dataset.plot); + const id = plot ? idOf(plot) : form.dataset.plot; + await api('/telemetry', { plot: id, kind: payload.kind, value }); dialog.close(); form.reset(); toast('Показание сохранено.'); + if (String(state.selected) === String(id)) await Promise.allSettled([loadRecords(id, state.selectionVersion), loadRecords(id, state.selectionVersion, true)]); + })); + $('#plot-search').addEventListener('input', renderPlots); $('#refresh').addEventListener('click', refresh); + let terminalTrigger = null; + function showTerminal(panel, trigger) { + const terminal = $('#terminal'); + if (trigger && !terminal.contains(trigger)) terminalTrigger = trigger; + terminal.hidden = false; document.body.classList.add('terminal-open'); terminal.dispatchEvent(new Event('greenhouse:raise')); + document.querySelectorAll('[data-panel]').forEach(section => { section.hidden = section.dataset.panel !== panel; }); + document.querySelectorAll('[data-terminal]').forEach(button => { + const active = button.dataset.terminal === panel; + if (button.closest('.terminal-tabs')) button.setAttribute('aria-pressed', String(active)); + else { button.setAttribute('aria-expanded', String(active)); button.setAttribute('aria-controls', 'terminal'); } + }); + $('#terminal-title').textContent = { plots: 'Участки', telemetry: 'Телеметрия', archive: 'Архив наблюдений' }[panel]; + $('#terminal-title').focus({ preventScroll: true }); + } + function hideTerminal() { + $('#terminal').hidden = true; document.body.classList.remove('terminal-open'); + document.querySelectorAll('[data-terminal][aria-expanded]').forEach(button => button.setAttribute('aria-expanded', 'false')); + (terminalTrigger ?? $('#terminal-launch')).focus({ preventScroll: true }); + } + document.querySelectorAll('[data-terminal]').forEach(button => { + button.setAttribute('aria-controls', 'terminal'); + if (!button.closest('.terminal-tabs')) button.setAttribute('aria-expanded', 'false'); + button.addEventListener('click', () => showTerminal(button.dataset.terminal, button)); + }); + $('#terminal-close').addEventListener('click', hideTerminal); + document.addEventListener('keydown', event => { if (event.key === 'Escape' && !document.querySelector('dialog[open]') && !$('#terminal').hidden && !event.target.closest('#operator-console')) { event.preventDefault(); hideTerminal(); } }); + $('#key-form').addEventListener('submit', async event => { + event.preventDefault(); const key = $('#access-key').value.trim(); if (!key || state.selected == null) return; + const stored = saveKey(state.selected, key); $('#access-key').value = ''; + if (!stored) toast('Хранилище браузера недоступно: ключ сохранён только на время сеанса.'); + await selectPlot(state.selected); + }); + setTimeout(() => { + if (!$('#space').dataset.ready) { $('#scene-loading').hidden = true; $('#scene-fallback').hidden = false; } + }, 20000); + refresh(); +})(); diff --git a/greenhouse/frontend/console.js b/greenhouse/frontend/console.js new file mode 100644 index 0000000..8c909b2 --- /dev/null +++ b/greenhouse/frontend/console.js @@ -0,0 +1,136 @@ +'use strict'; +(() => { + const $ = selector => document.querySelector(selector); + const pane = $('#operator-console'), output = $('#console-output'), input = $('#console-input'); + let session = null, busy = false, unloading = false; + const history = []; + let historyIndex = 0, draft = ''; + const stringify = value => typeof value === 'string' ? value : JSON.stringify(value) ?? ''; + + function lines(value, className = '') { + const nearBottom = output.scrollHeight - output.scrollTop - output.clientHeight < 45; + const values = Array.isArray(value) ? value : [value]; + const fragment = document.createDocumentFragment(); + for (const item of values) for (const line of stringify(item).slice(0, 131072).split(/\r?\n/).slice(0, 500)) { + const row = document.createElement('div'); row.className = `console-line ${className}`; + + row.textContent = line.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').slice(0, 8192) || ' '; + fragment.append(row); + } + output.append(fragment); + while (output.childElementCount > 1000) output.firstElementChild.remove(); + if (nearBottom) output.scrollTop = output.scrollHeight; + } + function update(message) { + $('#console-state').textContent = message ?? (session ? 'Подключено' : 'Нет сеанса'); + $('#console-indicator').classList.toggle('connected', session !== null); + input.disabled = busy || session === null; + $('#console-send').disabled = busy || session === null; + $('#console-reconnect').disabled = busy; + $('#console-disconnect').disabled = busy || session === null; + $('#console-reconnect').textContent = session ? 'Переподключить' : 'Подключить'; + pane.setAttribute('aria-busy', String(busy)); + } + function error(message) { + $('#console-error').textContent = message; $('#console-error').hidden = !message; + } + async function request(action, payload) { + const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 15000); + try { + const response = await fetch(`/api/console/${action}`, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify(payload), signal: controller.signal, cache: 'no-store' }); + let data; try { data = await response.json(); } catch { const problem = new Error(`Некорректный ответ консоли (HTTP ${response.status}).`); problem.status = response.status; throw problem; } + if (!response.ok) { + const problem = new Error(`HTTP ${response.status}: ${stringify(data?.error ?? data?.message ?? 'запрос отклонён').slice(0, 300)}`); + problem.status = response.status; throw problem; + } + return data; + } catch (problem) { + if (problem.name === 'AbortError') throw new Error('Консоль не ответила за 15 секунд.'); + if (problem instanceof TypeError) throw new Error('Нет связи с консолью. Проверьте соединение.'); + throw problem; + } finally { clearTimeout(timeout); } + } + async function closeSession() { + if (session === null) return; + try { + const result = await request('close', { session }); + if (result?.ok !== true) throw new Error('Сервер не подтвердил закрытие сеанса.'); + } catch (problem) { + if (![404, 410].includes(problem.status)) throw problem; + + } + session = null; lines('Сеанс закрыт.', 'console-system'); + } + async function connect() { + if (busy || unloading) return; + busy = true; error(''); update('Подключение…'); + try { + await closeSession(); + const data = await request('open', {}); + if (data?.session == null || !['string', 'number'].includes(typeof data.session) || String(data.session) === '') throw new Error('Сервер не выдал идентификатор сеанса.'); + session = data.session; + if (unloading) { release(); return; } + lines('Соединение установлено.', 'console-system'); + if (data.banner != null) lines(data.banner); + } catch (problem) { error(`${problem.message} Автоматического повтора не было.`); } + finally { busy = false; update(); if (session !== null && !pane.hidden) input.focus(); } + } + async function disconnect() { + if (busy || session === null) return; + busy = true; error(''); update('Отключение…'); + try { await closeSession(); } + catch (problem) { error(`${problem.message} Сеанс не подтверждён как закрытый; можно повторить отключение.`); } + finally { busy = false; update(); } + } + function show() { + document.body.classList.add('console-open'); + pane.hidden = false; pane.dispatchEvent(new Event('greenhouse:raise')); $('#console-launch').setAttribute('aria-expanded', 'true'); + if (session !== null && !busy) input.focus(); else $('#console-title').focus(); + if (session === null && !busy) connect(); + } + function hide() { document.body.classList.remove('console-open'); pane.hidden = true; $('#console-launch').setAttribute('aria-expanded', 'false'); $('#console-launch').focus(); } + $('#console-launch').addEventListener('click', () => pane.hidden ? show() : hide()); + $('#console-hide').addEventListener('click', hide); + $('#console-reconnect').addEventListener('click', connect); + $('#console-disconnect').addEventListener('click', disconnect); + $('#console-clear').addEventListener('click', () => { output.replaceChildren(); if (!input.disabled) input.focus(); }); + $('#console-form').addEventListener('submit', async event => { + event.preventDefault(); const command = input.value; + if (busy || session === null || !command.trim()) return; + if (command.length > 1024) { error('Команда не должна превышать 1024 символа.'); return; } + const currentSession = session; + busy = true; error(''); update('Выполнение…'); lines(`> ${command}`, 'console-command'); + if (history.at(-1) !== command) { history.push(command); if (history.length > 100) history.shift(); } + historyIndex = history.length; draft = ''; input.value = ''; + try { + const result = await request('command', { session: currentSession, command }); + if (!result || !Object.hasOwn(result, 'reply')) throw new Error('Сервер не передал ответ команды.'); + lines(result.reply); + } catch (problem) { + if ([401, 403, 404, 410].includes(problem.status)) { session = null; error(`${problem.message} Сеанс недоступен. Нажмите «Подключить».`); } + else error(`${problem.message} Результат команды не подтверждён. Повторите её вручную только при необходимости.`); + lines('Ответ не получен.', 'console-system'); + } finally { busy = false; update(); if (session !== null && !pane.hidden) input.focus(); } + }); + input.addEventListener('keydown', event => { + if (event.isComposing) return; + if (event.key === 'ArrowUp' || event.key === 'ArrowDown') { + event.preventDefault(); + if (historyIndex === history.length) draft = input.value; + historyIndex = Math.max(0, Math.min(history.length, historyIndex + (event.key === 'ArrowUp' ? -1 : 1))); + input.value = historyIndex === history.length ? draft : history[historyIndex]; + input.setSelectionRange(input.value.length, input.value.length); + } + if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'l') { event.preventDefault(); output.replaceChildren(); } + }); + pane.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); hide(); } }); + function release() { + if (session === null) return; + const closing = session; session = null; + + fetch('/api/console/close', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ session: closing }), keepalive: true }).catch(() => {}); + } + addEventListener('pagehide', () => { unloading = true; release(); }); + addEventListener('pageshow', event => { if (event.persisted) { unloading = false; busy = false; update(); } }); + update(); +})(); diff --git a/greenhouse/frontend/fonts/DepartureMono-OFL.txt b/greenhouse/frontend/fonts/DepartureMono-OFL.txt new file mode 100644 index 0000000..de52476 --- /dev/null +++ b/greenhouse/frontend/fonts/DepartureMono-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2022–2024 Helena Zhang (helenazhang.com). + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/greenhouse/frontend/fonts/DepartureMono-Regular.woff2 b/greenhouse/frontend/fonts/DepartureMono-Regular.woff2 new file mode 100644 index 0000000..b4a23dc Binary files /dev/null and b/greenhouse/frontend/fonts/DepartureMono-Regular.woff2 differ diff --git a/greenhouse/frontend/fonts/SOURCE.txt b/greenhouse/frontend/fonts/SOURCE.txt new file mode 100644 index 0000000..5e067ac --- /dev/null +++ b/greenhouse/frontend/fonts/SOURCE.txt @@ -0,0 +1,4 @@ +Departure Mono 1.500, unmodified WOFF2 from the official release. +Source: https://github.com/rektdeckard/departure-mono/releases/download/v1.500/DepartureMono-1.500.zip +License: SIL Open Font License 1.1; see DepartureMono-OFL.txt. +DepartureMono-Regular.woff2 SHA256 5b4fed1daa90708aa9c6ee1190abca9dc22164a1c1def0020386e46b61038cfb diff --git a/greenhouse/frontend/index.html b/greenhouse/frontend/index.html new file mode 100644 index 0000000..5793540 --- /dev/null +++ b/greenhouse/frontend/index.html @@ -0,0 +1,37 @@ + + +
+ +Устройство не поддерживает WebGL 2. Работа с участками и консолью доступна.
=r)){const a=e[1];t=r)break e}n=s,s=0;break s}break t}for(;s0){i=new Sc(this.manager),i.setCrossOrigin(this.crossOrigin);for(let e=0,i=t.length;e{let e=null,s=null;return void 0!==t.boundingBox&&(e=(new Ri).fromJSON(t.boundingBox)),void 0!==t.boundingSphere&&(s=(new $i).fromJSON(t.boundingSphere)),{...t,boundingBox:e,boundingSphere:s}}),n._instanceInfo=t.instanceInfo,n._availableInstanceIds=t._availableInstanceIds,n._availableGeometryIds=t._availableGeometryIds,n._nextIndexStart=t.nextIndexStart,n._nextVertexStart=t.nextVertexStart,n._geometryCount=t.geometryCount,n._maxInstanceCount=t.maxInstanceCount,n._maxVertexCount=t.maxVertexCount,n._maxIndexCount=t.maxIndexCount,n._geometryInitialized=t.geometryInitialized,n._matricesTexture=c(t.matricesTexture.uuid),n._indirectTexture=c(t.indirectTexture.uuid),void 0!==t.colorsTexture&&(n._colorsTexture=c(t.colorsTexture.uuid)),void 0!==t.boundingSphere&&(n.boundingSphere=(new $i).fromJSON(t.boundingSphere)),void 0!==t.boundingBox&&(n.boundingBox=(new Ri).fromJSON(t.boundingBox));break;case"LOD":n=new ka;break;case"Line":n=new Do(h(t.geometry),l(t.material));break;case"LineLoop":n=new Jo(h(t.geometry),l(t.material));break;case"LineSegments":n=new qo(h(t.geometry),l(t.material));break;case"PointCloud":case"Points":n=new Qo(h(t.geometry),l(t.material));break;case"Sprite":n=new za(l(t.material));break;case"Group":n=new ra;break;case"Bone":n=new Wa;break;default:n=new Rr}if(n.uuid=t.uuid,void 0!==t.name&&(n.name=t.name),void 0!==t.matrix?(n.matrix.fromArray(t.matrix),void 0!==t.matrixAutoUpdate&&(n.matrixAutoUpdate=t.matrixAutoUpdate),n.matrixAutoUpdate&&n.matrix.decompose(n.position,n.quaternion,n.scale)):(void 0!==t.position&&n.position.fromArray(t.position),void 0!==t.rotation&&n.rotation.fromArray(t.rotation),void 0!==t.quaternion&&n.quaternion.fromArray(t.quaternion),void 0!==t.scale&&n.scale.fromArray(t.scale)),void 0!==t.up&&n.up.fromArray(t.up),void 0!==t.castShadow&&(n.castShadow=t.castShadow),void 0!==t.receiveShadow&&(n.receiveShadow=t.receiveShadow),t.shadow&&(void 0!==t.shadow.intensity&&(n.shadow.intensity=t.shadow.intensity),void 0!==t.shadow.bias&&(n.shadow.bias=t.shadow.bias),void 0!==t.shadow.normalBias&&(n.shadow.normalBias=t.shadow.normalBias),void 0!==t.shadow.radius&&(n.shadow.radius=t.shadow.radius),void 0!==t.shadow.mapSize&&n.shadow.mapSize.fromArray(t.shadow.mapSize),void 0!==t.shadow.camera&&(n.shadow.camera=this.parseObject(t.shadow.camera))),void 0!==t.visible&&(n.visible=t.visible),void 0!==t.frustumCulled&&(n.frustumCulled=t.frustumCulled),void 0!==t.renderOrder&&(n.renderOrder=t.renderOrder),void 0!==t.userData&&(n.userData=t.userData),void 0!==t.layers&&(n.layers.mask=t.layers),void 0!==t.children){const a=t.children;for(let t=0;t1)for(let s=0;sNumber.EPSILON){if(h<0&&(s=e[n],o=-o,a=e[r],h=-h),t.y