services
This commit is contained in:
1 parent
fd2a9af45c
commit
4f70df55dd
1392 files changed
+10026
No files matched your search
@@ -0,0 +1,3 @@
|
|||||||
|
**/__pycache__
|
||||||
|
*.pyc
|
||||||
|
.git
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
**/__pycache__/
|
||||||
|
*.pyc
|
||||||
Whitespace-only changes.
@@ -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"]
|
||||||
@@ -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()
|
||||||
@@ -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:
|
||||||
@@ -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();
|
||||||
|
})();
|
||||||
@@ -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();
|
||||||
|
})();
|
||||||
@@ -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.
|
||||||
Binary file not shown.
@@ -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
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
<!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="#030b12">
|
||||||
|
<title>Оранжерея / Орбита.Квантум 2126</title><link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Cpath fill='%239aead2' d='M32 3 59 18v28L32 61 5 46V18zm0 8L12 23v19l20 11 20-11V23z'/%3E%3C/svg%3E">
|
||||||
|
<link rel="stylesheet" href="./styles.css">
|
||||||
|
<script type="importmap">{"imports":{"three":"./vendor/three/three.module.min.js","three/addons/controls/OrbitControls.js":"./vendor/three/OrbitControls.js"}}</script>
|
||||||
|
<script src="./app.js" defer></script><script src="./console.js" defer></script><script src="./window-drag.js" defer></script><script type="module" src="./scene.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<a href="#terminal-launch" class="skip">К управлению оранжереей</a>
|
||||||
|
<main id="observatory" aria-label="Орбитальная оранжерея">
|
||||||
|
<canvas id="space" tabindex="0" aria-label="Трёхмерная орбитальная оранжерея. Перетаскивайте для осмотра. Стрелки вращают камеру, плюс и минус меняют масштаб, Home возвращает вид. I или двойной щелчок открывает внутренний ракурс. Enter осматривает предмет в центре вида. Shift и перетаскивание смещают камеру."></canvas>
|
||||||
|
<div class="vignette" aria-hidden="true"></div>
|
||||||
|
<div id="scene-loading" role="status"><span class="loading-orbit" aria-hidden="true"></span><span>Загрузка 3D-модели</span><small>Инструменты оператора доступны во время загрузки.</small></div>
|
||||||
|
<div id="scene-fallback" hidden role="status"><strong>3D недоступно</strong><p>Устройство не поддерживает WebGL 2. Работа с участками и консолью доступна.</p><button class="button primary" data-terminal="plots">Открыть терминал</button></div>
|
||||||
|
<nav class="command-dock" aria-label="Инструменты оператора"><button id="terminal-launch" data-terminal="plots"><span class="dock-label">Данные</span><span class="dock-end"><small id="nav-count">—</small><span aria-hidden="true">↗</span></span></button><button id="console-launch" aria-expanded="false" aria-controls="operator-console"><span class="dock-label">Консоль <span id="console-indicator" aria-hidden="true"></span></span><span class="dock-end" aria-hidden="true">↗</span></button></nav>
|
||||||
|
<div class="operator-rail"><section class="vitals" aria-label="Состояние оранжереи"><div class="vitals-heading"><span>СОСТОЯНИЕ ОРАНЖЕРЕИ</span><strong id="metric-status">Загрузка</strong></div><div class="vital-line"><span>O₂ / кислород</span><strong id="metric-oxygen">—</strong></div><div class="vital-line"><span>T° / воздух</span><strong id="metric-temperature">—</strong></div><div class="vital-line"><span>Участки</span><strong id="metric-plots">—</strong></div><small id="last-update">Нет данных</small></section></div>
|
||||||
|
<div class="camera-controls" role="group" aria-label="Камера и анимация"><button id="camera-zoom-in" aria-label="Приблизить">+</button><button id="camera-zoom-out" aria-label="Отдалить">−</button><button id="motion-toggle" aria-pressed="false">Пауза</button></div>
|
||||||
|
|
||||||
|
<div id="object-hint" role="status" hidden></div>
|
||||||
|
<aside id="terminal" class="terminal" hidden aria-labelledby="terminal-title"><div class="terminal-header" tabindex="0" aria-label="Переместить окно данных"><div><span class="eyebrow">ДАННЫЕ ОРАНЖЕРЕИ</span><h2 id="terminal-title" tabindex="-1">Участки</h2></div><button id="terminal-close" class="close" aria-label="Закрыть терминал">×</button></div><div class="terminal-tabs" role="group" aria-label="Раздел терминала"><button data-terminal="plots" aria-pressed="true">Участки <span id="plot-count">—</span></button><button data-terminal="telemetry" aria-pressed="false">Телеметрия</button><button data-terminal="archive" aria-pressed="false">Архив</button></div><div class="terminal-toolbar"><span id="selected-label">Участок не выбран</span><button id="refresh" class="text-button">↻ Обновить</button></div><div class="terminal-body"><section id="plots" data-panel="plots"><div class="section-heading"><span class="eyebrow">РЕЕСТР ПОСАДОК</span><button id="open-create" class="button">Новый участок ↗</button></div><label class="search"><span aria-hidden="true">⌕</span><input id="plot-search" type="search" aria-label="Найти участок" placeholder="Поиск участка / культуры"></label><div id="plot-list" class="plot-list" aria-live="polite"><p class="empty">Получаем реестр…</p></div><div class="section-divider"><span>Паспорт участка</span><span>↓</span></div><article id="plot-detail" aria-live="polite"><p class="empty">Выберите участок для чтения паспорта и заметок.</p></article><form id="key-form" hidden><label for="access-key">Ключ доступа к выбранному участку</label><div class="key-row"><input id="access-key" type="password" autocomplete="off" required placeholder="Вставьте выданный ключ"><button type="submit" class="button">Открыть</button></div><p class="form-error" role="alert"></p></form></section><section id="telemetry" data-panel="telemetry" hidden><div class="section-heading"><span class="eyebrow">Показания</span><button id="open-telemetry" class="button" disabled>+ Запись</button></div><div id="telemetry-content" class="records" aria-live="polite"><p class="empty">Выберите участок в реестре.</p></div></section><section id="archive" data-panel="archive" hidden><div class="eyebrow">Архив участка</div><div id="archive-content" class="records" aria-live="polite"><p class="empty">Выберите участок в реестре.</p></div></section></div></aside>
|
||||||
|
<section id="operator-console" class="operator-console" hidden aria-labelledby="console-title">
|
||||||
|
<div class="console-titlebar" tabindex="0" aria-label="Переместить окно консоли"><h2 id="console-title" tabindex="-1">Консоль</h2><span id="console-state" role="status">Нет сеанса</span><button id="console-hide" class="close" aria-label="Скрыть консоль">×</button></div>
|
||||||
|
<div class="console-tools"><button id="console-reconnect">Подключить</button><button id="console-disconnect" disabled>Отключить</button><button id="console-clear">Очистить вывод</button></div>
|
||||||
|
<div id="console-output" class="console-output" role="log" aria-label="Вывод консоли" aria-live="polite" aria-relevant="additions" tabindex="0"></div>
|
||||||
|
<p id="console-error" class="console-error" role="alert" hidden></p>
|
||||||
|
<form id="console-form" autocomplete="off"><label for="console-input">Команда</label><div class="console-input-row"><span aria-hidden="true">></span><input id="console-input" type="text" spellcheck="false" autocapitalize="off" autocomplete="off" maxlength="1024" aria-describedby="console-help" disabled><button id="console-send" type="submit" disabled>Выполнить</button></div></form>
|
||||||
|
<div class="console-footer" id="console-help">Enter — выполнить · ↑ ↓ — история · Ctrl+L — очистить</div>
|
||||||
|
</section>
|
||||||
|
<div id="global-error" class="notice" role="alert" hidden></div>
|
||||||
|
</main>
|
||||||
|
<dialog id="create-dialog" aria-labelledby="create-title"><form id="create-form"><div class="dialog-heading"><span class="eyebrow">Регистрация участка</span><button type="button" class="close" data-close aria-label="Закрыть">×</button></div><h2 id="create-title">Новый участок</h2><p>Название и культура обязательны. Ключ доступа сохранится в этом браузере.</p><label>Название участка<input name="name" required maxlength="160" placeholder="Например, Грядка 04" autocomplete="off"></label><label>Культура<input name="cultivar" required maxlength="160" placeholder="Например, базилик" autocomplete="off"></label><label>Заметка<textarea name="note" rows="3" maxlength="4000" placeholder="Условия выращивания и ваши наблюдения"></textarea></label><p class="form-error" role="alert"></p><button class="button primary" type="submit">Создать участок</button></form></dialog>
|
||||||
|
<dialog id="telemetry-dialog" aria-labelledby="telemetry-form-title"><form id="telemetry-form"><div class="dialog-heading"><span class="eyebrow">Телеметрия</span><button type="button" class="close" data-close aria-label="Закрыть">×</button></div><h2 id="telemetry-form-title">Запись телеметрии</h2><p id="telemetry-plot-name"></p><label>Тип измерения<select name="kind" required><option value="temperature">Температура / temperature</option><option value="humidity">Влажность / humidity</option><option value="oxygen">Кислород / oxygen</option><option value="biometrics">Биометрия / biometrics</option></select></label><label>Значение<input name="value" type="number" step="any" required placeholder="23.5"></label><p class="form-error" role="alert"></p><button class="button primary" type="submit">Сохранить показание</button></form></dialog>
|
||||||
|
<div class="toast" id="toast" role="status" hidden></div>
|
||||||
|
<noscript><div class="noscript-message">Для 3D-сцены и API включите JavaScript в браузере.</div></noscript>
|
||||||
|
</body></html>
|
||||||
@@ -0,0 +1,554 @@
|
|||||||
|
import * as THREE from 'three';
|
||||||
|
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
|
||||||
|
|
||||||
|
const canvas = document.querySelector('#space');
|
||||||
|
const loading = document.querySelector('#scene-loading');
|
||||||
|
const fallback = document.querySelector('#scene-fallback');
|
||||||
|
const motionButton = document.querySelector('#motion-toggle');
|
||||||
|
const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)');
|
||||||
|
let renderer;
|
||||||
|
try {
|
||||||
|
renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: false, powerPreference: 'high-performance' });
|
||||||
|
} catch {
|
||||||
|
loading.hidden = true;
|
||||||
|
fallback.hidden = false;
|
||||||
|
document.querySelectorAll('.camera-controls button').forEach(button => { button.disabled = true; });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (renderer) {
|
||||||
|
const boot = () => setTimeout(initialize, 100);
|
||||||
|
if (document.readyState === 'complete') boot();
|
||||||
|
else window.addEventListener('load', boot, { once: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
function initialize() {
|
||||||
|
const mobile = () => innerWidth < 701;
|
||||||
|
const gl = renderer.getContext();
|
||||||
|
const debug = gl.getExtension('WEBGL_debug_renderer_info');
|
||||||
|
const gpu = debug ? gl.getParameter(debug.UNMASKED_RENDERER_WEBGL) : '';
|
||||||
|
const software = /swiftshader|llvmpipe|software|softpipe/i.test(gpu);
|
||||||
|
const pixelRatio = () => software ? .8 : Math.min(devicePixelRatio, mobile() ? 1.2 : 1.5);
|
||||||
|
renderer.setPixelRatio(pixelRatio());
|
||||||
|
renderer.setSize(innerWidth, innerHeight, false);
|
||||||
|
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
||||||
|
renderer.toneMapping = THREE.ACESFilmicToneMapping;
|
||||||
|
renderer.toneMappingExposure = 1.18;
|
||||||
|
renderer.shadowMap.enabled = !software;
|
||||||
|
renderer.shadowMap.type = software ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
|
||||||
|
renderer.shadowMap.autoUpdate = false;
|
||||||
|
const scene = new THREE.Scene();
|
||||||
|
const camera = new THREE.PerspectiveCamera(mobile() ? 50 : 39, innerWidth / innerHeight, .1, 350);
|
||||||
|
const controls = new OrbitControls(camera, canvas);
|
||||||
|
controls.enablePan = true;
|
||||||
|
controls.screenSpacePanning = true;
|
||||||
|
controls.maxTargetRadius = 4;
|
||||||
|
controls.enableDamping = !reducedMotion.matches;
|
||||||
|
controls.dampingFactor = .065;
|
||||||
|
controls.minPolarAngle = .22;
|
||||||
|
controls.maxPolarAngle = Math.PI * .61;
|
||||||
|
controls.minDistance = 2.4;
|
||||||
|
controls.maxDistance = 48;
|
||||||
|
controls.rotateSpeed = .5;
|
||||||
|
controls.zoomSpeed = .65;
|
||||||
|
controls.target.set(0, .9, 0);
|
||||||
|
let paused = reducedMotion.matches;
|
||||||
|
let elapsed = 0;
|
||||||
|
let previous = 0;
|
||||||
|
let lastPaint = 0;
|
||||||
|
let paintCount = 0;
|
||||||
|
let gpuFence = null;
|
||||||
|
const frameInterval = 1000 / (software ? 24 : 30);
|
||||||
|
let frame = 0;
|
||||||
|
let interacting = false;
|
||||||
|
let hidden = document.hidden;
|
||||||
|
let contextLost = false;
|
||||||
|
const station = new THREE.Group(); scene.add(station);
|
||||||
|
station.rotation.y = -.2;
|
||||||
|
|
||||||
|
let seed = 212607;
|
||||||
|
const random = () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; };
|
||||||
|
function material(color, metalness = .6, roughness = .4, emissive = 0, emissiveIntensity = 0) {
|
||||||
|
return software ? new THREE.MeshPhongMaterial({ color, shininess: (1 - roughness) * 50, specular: 0x40505a, emissive, emissiveIntensity }) : new THREE.MeshStandardMaterial({ color, metalness, roughness, emissive, emissiveIntensity });
|
||||||
|
}
|
||||||
|
const titanium = material(0x799398, .8, .3);
|
||||||
|
const darkMetal = material(0x162b36, .8, .38);
|
||||||
|
const ceramic = material(0xa9bbb4, .5, .36);
|
||||||
|
const gold = material(0xb49a64, .72, .36);
|
||||||
|
const black = material(0x0a141c, .55, .52);
|
||||||
|
const mint = material(0x82ffcf, .2, .25, 0x67ffc1, 3);
|
||||||
|
const amber = material(0xffc473, .2, .3, 0xffa94f, 2.8);
|
||||||
|
const blue = material(0x97d9ff, .2, .25, 0x54baff, 2);
|
||||||
|
const mesh = (geo, mat, parent = station, position = [0, 0, 0]) => {
|
||||||
|
const object = new THREE.Mesh(geo, mat); object.position.set(...position); parent.add(object);
|
||||||
|
object.castShadow = true; object.receiveShadow = true; return object;
|
||||||
|
};
|
||||||
|
const box = (size, mat, parent, position) => mesh(new THREE.BoxGeometry(...size), mat, parent, position);
|
||||||
|
const cylinder = (top, bottom, height, mat, parent, position, segments = 48) => mesh(new THREE.CylinderGeometry(top, bottom, height, segments), mat, parent, position);
|
||||||
|
function torus(radius, tube, mat, parent = station, y = 0, arc = Math.PI * 2) {
|
||||||
|
const object = mesh(new THREE.TorusGeometry(radius, tube, 6, 96, arc), mat, parent, [0, y, 0]); object.rotation.x = Math.PI / 2; return object;
|
||||||
|
}
|
||||||
|
function beam(start, end, thickness, mat, parent = station) {
|
||||||
|
const a = new THREE.Vector3(...start), b = new THREE.Vector3(...end), direction = b.clone().sub(a);
|
||||||
|
const object = mesh(new THREE.CylinderGeometry(thickness, thickness, direction.length(), 6), mat, parent);
|
||||||
|
object.position.copy(a.add(b).multiplyScalar(.5)); object.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction.normalize()); return object;
|
||||||
|
}
|
||||||
|
function glowTexture() {
|
||||||
|
const c = document.createElement('canvas'); c.width = c.height = 128;
|
||||||
|
const ctx = c.getContext('2d'), gradient = ctx.createRadialGradient(64, 64, 0, 64, 64, 64);
|
||||||
|
gradient.addColorStop(0, 'rgba(255,255,255,1)'); gradient.addColorStop(.07, 'rgba(230,255,249,.85)'); gradient.addColorStop(.23, 'rgba(140,233,217,.22)'); gradient.addColorStop(1, 'rgba(90,170,190,0)');
|
||||||
|
ctx.fillStyle = gradient; ctx.fillRect(0, 0, 128, 128);
|
||||||
|
return new THREE.CanvasTexture(c);
|
||||||
|
}
|
||||||
|
const glowMap = glowTexture();
|
||||||
|
function glow(parent, position, color, size, opacity = .7) {
|
||||||
|
const object = new THREE.Sprite(new THREE.SpriteMaterial({ map: glowMap, color, transparent: true, opacity, blending: THREE.AdditiveBlending, depthWrite: false }));
|
||||||
|
object.position.set(...position); object.scale.setScalar(size); parent.add(object); return object;
|
||||||
|
}
|
||||||
|
|
||||||
|
scene.add(new THREE.HemisphereLight(0x94cfdf, 0x1e3335, 1.5));
|
||||||
|
const sun = new THREE.DirectionalLight(0xffe3ad, 4.8); sun.position.set(-8, 13, 7); sun.castShadow = true;
|
||||||
|
sun.shadow.mapSize.set(software || mobile() ? 512 : 1024, software || mobile() ? 512 : 1024); sun.shadow.camera.left = -10; sun.shadow.camera.right = 10; sun.shadow.camera.top = 10; sun.shadow.camera.bottom = -10; sun.shadow.camera.far = 55; sun.shadow.normalBias = .025; sun.shadow.bias = -.0002; scene.add(sun);
|
||||||
|
const rim = new THREE.DirectionalLight(0x60c7fa, 3.5); rim.position.set(6, 4, -9); scene.add(rim);
|
||||||
|
const underlight = new THREE.PointLight(0x31dfc6, 35, 18, 2); underlight.position.set(0, -3, 2); scene.add(underlight);
|
||||||
|
|
||||||
|
const backgroundSeed = seed;
|
||||||
|
|
||||||
|
const skyCanvas = document.createElement('canvas'); skyCanvas.width = 2048; skyCanvas.height = 1024;
|
||||||
|
const skyContext = skyCanvas.getContext('2d'); skyContext.scale(2, 2); skyContext.fillStyle = '#030914'; skyContext.fillRect(0, 0, 1024, 512);
|
||||||
|
for (let i = 0; i < 60; i++) {
|
||||||
|
const x = random() * 1024, y = 180 + Math.sin(x * .007) * 90 + random() * 100, r = 50 + random() * 170;
|
||||||
|
const gradient = skyContext.createRadialGradient(x, y, 0, x, y, r);
|
||||||
|
gradient.addColorStop(0, i % 3 ? 'rgba(20,66,70,.15)' : 'rgba(46,33,74,.12)'); gradient.addColorStop(1, 'rgba(0,0,0,0)');
|
||||||
|
skyContext.fillStyle = gradient; skyContext.fillRect(x-r, y-r, r*2, r*2);
|
||||||
|
}
|
||||||
|
|
||||||
|
skyContext.setTransform(1, 0, 0, 1, 0, 0);
|
||||||
|
for (let i = 0; i < 2800; i++) {
|
||||||
|
const x = random() * 2048, y = (Math.asin(random()*2-1)/Math.PI+.5) * 1024;
|
||||||
|
const radius = .45 + random()*.38, opacity = .25 + random()*.55;
|
||||||
|
skyContext.fillStyle = `rgba(193,210,226,${opacity})`;
|
||||||
|
skyContext.beginPath(); skyContext.arc(x,y,radius,0,Math.PI*2); skyContext.fill();
|
||||||
|
if (i % 55 === 0) {
|
||||||
|
const halo=skyContext.createRadialGradient(x,y,0,x,y,4.5);
|
||||||
|
halo.addColorStop(0,'rgba(215,231,242,.72)'); halo.addColorStop(.22,'rgba(155,184,211,.17)'); halo.addColorStop(1,'rgba(130,160,190,0)');
|
||||||
|
skyContext.fillStyle=halo;skyContext.fillRect(x-4.5,y-4.5,9,9);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const skyTexture = new THREE.CanvasTexture(skyCanvas); skyTexture.colorSpace = THREE.SRGBColorSpace;
|
||||||
|
skyTexture.magFilter = THREE.LinearFilter; skyTexture.minFilter = THREE.LinearMipmapLinearFilter; skyTexture.generateMipmaps = true;
|
||||||
|
const skyMaterial = new THREE.MeshBasicMaterial({ map: skyTexture, side: THREE.BackSide, depthWrite: false, toneMapped: false });
|
||||||
|
const sky = mesh(new THREE.SphereGeometry(140, 32, 20), skyMaterial, scene); sky.castShadow = false; sky.receiveShadow = false; sky.renderOrder = -10;
|
||||||
|
|
||||||
|
const planetCanvas=document.createElement('canvas');planetCanvas.width=1024;planetCanvas.height=512;
|
||||||
|
const pc=planetCanvas.getContext('2d');pc.fillStyle='#173a50';pc.fillRect(0,0,1024,512);
|
||||||
|
const elevationCanvas=document.createElement('canvas');elevationCanvas.width=1024;elevationCanvas.height=512;
|
||||||
|
const elevation=elevationCanvas.getContext('2d');elevation.fillStyle='#151515';elevation.fillRect(0,0,1024,512);
|
||||||
|
for(let i=0;i<26;i++){
|
||||||
|
const cx=random()*1024,cy=50+random()*412,rx=30+random()*95,ry=18+random()*52,phase=random()*6.28;
|
||||||
|
const outline=new Path2D();
|
||||||
|
for(let j=0;j<=54;j++){const a=j/54*Math.PI*2;const r=1+.2*Math.sin(a*3+phase)+.12*Math.cos(a*7-phase);const x=cx+Math.cos(a)*rx*r,y=cy+Math.sin(a)*ry*r;j?outline.lineTo(x,y):outline.moveTo(x,y);}outline.closePath();
|
||||||
|
pc.strokeStyle='#355e64';pc.lineWidth=8;pc.stroke(outline);
|
||||||
|
const land=pc.createLinearGradient(cx-rx,cy-ry,cx+rx,cy+ry);land.addColorStop(0,'#748273');land.addColorStop(.5,'#465f55');land.addColorStop(1,'#263f40');pc.fillStyle=land;pc.fill(outline);
|
||||||
|
elevation.fillStyle='#929292';elevation.fill(outline);
|
||||||
|
for(let j=0;j<6;j++){pc.save();pc.clip(outline);pc.beginPath();pc.moveTo(cx-rx,cy+j*4-14);pc.bezierCurveTo(cx-rx*.4,cy-ry*.5+j*4,cx+rx*.3,cy+ry*.4+j*2,cx+rx,cy+j*3);pc.strokeStyle='rgba(183,179,151,.15)';pc.lineWidth=1.5;pc.stroke();pc.restore();}
|
||||||
|
}
|
||||||
|
const polar=pc.createLinearGradient(0,0,0,512);polar.addColorStop(0,'rgba(173,196,194,.8)');polar.addColorStop(.1,'rgba(173,196,194,0)');polar.addColorStop(.9,'rgba(173,196,194,0)');polar.addColorStop(1,'rgba(173,196,194,.65)');pc.fillStyle=polar;pc.fillRect(0,0,1024,512);
|
||||||
|
const planetTexture=new THREE.CanvasTexture(planetCanvas);planetTexture.colorSpace=THREE.SRGBColorSpace;
|
||||||
|
const reliefTexture=new THREE.CanvasTexture(elevationCanvas);
|
||||||
|
const planetMaterial=new THREE.MeshPhongMaterial({map:planetTexture,color:0xacc5ce,emissive:0x416071,emissiveMap:planetTexture,emissiveIntensity:.3,bumpMap:reliefTexture,bumpScale:.085,shininess:12,specular:0x294452});
|
||||||
|
const planet=mesh(new THREE.SphereGeometry(17,48,32),planetMaterial,scene,[21,-15,-43]);planet.castShadow=false;planet.receiveShadow=false;
|
||||||
|
const cloudCanvas=document.createElement('canvas');cloudCanvas.width=1024;cloudCanvas.height=512;
|
||||||
|
const cc=cloudCanvas.getContext('2d');
|
||||||
|
for(let i=0;i<230;i++){
|
||||||
|
const x=random()*1024,y=random()*512,len=12+random()*100;
|
||||||
|
cc.beginPath();cc.moveTo(x,y);cc.bezierCurveTo(x+len*.3,y-15,x+len*.65,y+19,x+len,y-3);
|
||||||
|
cc.strokeStyle=`rgba(203,219,221,${.06+random()*.25})`;cc.lineWidth=1+random()*6;cc.lineCap='round';cc.stroke();
|
||||||
|
}
|
||||||
|
const cloudTexture=new THREE.CanvasTexture(cloudCanvas);cloudTexture.colorSpace=THREE.SRGBColorSpace;
|
||||||
|
const clouds=mesh(new THREE.SphereGeometry(17.1,48,32),new THREE.MeshLambertMaterial({map:cloudTexture,transparent:true,opacity:.6,depthWrite:false}),scene,[21,-15,-43]);clouds.castShadow=false;clouds.receiveShadow=false;
|
||||||
|
const atmosphereMaterial = new THREE.ShaderMaterial({ transparent: true, side: THREE.BackSide, blending: THREE.AdditiveBlending, depthWrite: false,
|
||||||
|
vertexShader: `varying vec3 n;varying vec3 v;void main(){vec4 p=modelViewMatrix*vec4(position,1.);n=normalize(normalMatrix*normal);v=normalize(-p.xyz);gl_Position=projectionMatrix*p;}`,
|
||||||
|
fragmentShader: `varying vec3 n;varying vec3 v;void main(){float rim=pow(1.-abs(dot(normalize(n),normalize(v))),4.);gl_FragColor=vec4(.08,.46,.62,rim*.52);}` });
|
||||||
|
const atmosphere = mesh(new THREE.SphereGeometry(17.22, 48, 32), atmosphereMaterial, scene, [21, -15, -43]); atmosphere.castShadow = false;
|
||||||
|
|
||||||
|
seed = backgroundSeed;
|
||||||
|
for (let i=0;i<15688;i++) random();
|
||||||
|
|
||||||
|
cylinder(4.55, 4.08, .55, darkMetal, station, [0, -.25, 0]);
|
||||||
|
cylinder(4.58, 4.58, .14, ceramic, station, [0, .095, 0]);
|
||||||
|
cylinder(4.05, 3.45, .42, titanium, station, [0, -.73, 0]);
|
||||||
|
cylinder(2.75, 2.05, .55, darkMetal, station, [0, -1.15, 0]);
|
||||||
|
torus(4.48, .045, mint, station, -.13); torus(4.13, .06, gold, station, -.61); torus(3.5, .035, blue, station, -.92);
|
||||||
|
cylinder(4.33, 4.33, .08, black, station, [0, .23, 0]);
|
||||||
|
const flooring = material(0x617973, .4, .65);
|
||||||
|
cylinder(4.2, 4.2, .07, flooring, station, [0, .3, 0]);
|
||||||
|
torus(4.24, .035, mint, station, .34);
|
||||||
|
for (let i = 0; i < 64; i++) {
|
||||||
|
const angle = i / 64 * Math.PI * 2;
|
||||||
|
const rib = box([.12, .34, .17], i % 8 ? titanium : gold, station, [Math.cos(angle) * 4.35, -.37, Math.sin(angle) * 4.35]); rib.rotation.y = -angle;
|
||||||
|
if (i % 4 === 0) { const light = box([.25, .09, .065], i % 8 ? amber : mint, station, [Math.cos(angle) * 4.53, -.23, Math.sin(angle) * 4.53]); light.rotation.y = -angle + Math.PI / 2; }
|
||||||
|
}
|
||||||
|
for (let i = 0; i < 6; i++) {
|
||||||
|
const a = i * Math.PI / 3;
|
||||||
|
beam([Math.cos(a) * .8, .36, Math.sin(a) * .8], [Math.cos(a) * 4.1, .36, Math.sin(a) * 4.1], .026, ceramic);
|
||||||
|
const stripe = box([.045, .012, 3.1], mint, station, [Math.sin(a) * 2.5, .35, Math.cos(a) * 2.5]); stripe.rotation.y = a;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fans = [];
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
const a = i * Math.PI * 2 / 3 + .3, unit = new THREE.Group();
|
||||||
|
unit.position.set(Math.cos(a) * 3.45, 1.3, Math.sin(a) * 3.45); unit.rotation.y = -a + Math.PI / 2; station.add(unit);
|
||||||
|
box([.52, .55, .15], darkMetal, unit); const housing = torus(.205, .03, ceramic, unit); housing.rotation.x = 0; housing.position.z = .09;
|
||||||
|
const rotor = new THREE.Group(); rotor.position.z = .105; unit.add(rotor);
|
||||||
|
for (let blade = 0; blade < 4; blade++) { const fin = box([.07, .19, .016], titanium, rotor, [0, .09, 0]); fin.rotation.z = blade * Math.PI / 2; fin.position.set(Math.sin(blade * Math.PI / 2) * .085, Math.cos(blade * Math.PI / 2) * .085, 0); }
|
||||||
|
fans.push(rotor);
|
||||||
|
beam([-.24, -.72, 0], [-.24, -.25, 0], .025, titanium, unit); beam([.24, -.72, 0], [.24, -.25, 0], .025, titanium, unit);
|
||||||
|
}
|
||||||
|
for (let i = 0; i < 6; i++) {
|
||||||
|
const a = i * Math.PI / 3 + .12, pipe = new THREE.Group(); pipe.rotation.y = a; station.add(pipe);
|
||||||
|
beam([1.4, .7, 0], [3.85, .7, 0], .025, darkMetal, pipe);
|
||||||
|
for (let j = 0; j < 6; j++) { beam([1.55 + j * .39, .69, 0], [1.55 + j * .39, .66, -.15], .012, titanium, pipe); }
|
||||||
|
beam([3.82, .37, 0], [3.82, 1.65, 0], .026, titanium, pipe);
|
||||||
|
box([.72, .075, .2], darkMetal, pipe, [3.45, 1.65, 0]); box([.61, .012, .14], mint, pipe, [3.45, 1.603, 0]);
|
||||||
|
for (let j = 0; j < 4; j++) box([.018, .6, .03], titanium, pipe, [2.05 + j * .25, .94, -.5]);
|
||||||
|
beam([2.02, 1.2, -.5], [2.85, 1.2, -.5], .012, ceramic, pipe);
|
||||||
|
}
|
||||||
|
|
||||||
|
const bench = new THREE.Group(); bench.position.set(-1.05, 0, -.9); bench.rotation.y = -.35; station.add(bench);
|
||||||
|
box([1.05, .065, .7], darkMetal, bench, [0, 1.30, 0]);
|
||||||
|
for (const x of [-.45, .45]) for (const z of [-.28, .28]) box([.045, .94, .045], titanium, bench, [x, .81, z]);
|
||||||
|
box([.22, .035, .14], gold, bench, [.23, 1.36, -.13]);
|
||||||
|
box([.30, .02, .21], ceramic, bench, [-.21, 1.35, .07]);
|
||||||
|
const packageGroup = new THREE.Group(); packageGroup.position.set(-1.1, .64, -.78); packageGroup.rotation.y = -.35; station.add(packageGroup);
|
||||||
|
box([.68, .035, .52], ceramic, packageGroup, [0, -.02, 0]);
|
||||||
|
const cardboard = material(0x9d764b, .02, .86);
|
||||||
|
const labelCanvas = document.createElement('canvas'); labelCanvas.width = 512; labelCanvas.height = 256;
|
||||||
|
const lc = labelCanvas.getContext('2d'); lc.fillStyle = '#b49160'; lc.fillRect(0, 0, 512, 256);
|
||||||
|
lc.fillStyle = '#eadab5'; lc.fillRect(30, 35, 452, 178); lc.strokeStyle = '#705c42'; lc.lineWidth = 3; lc.strokeRect(30,35,452,178);
|
||||||
|
lc.fillStyle = '#302c25'; lc.font = 'bold 54px sans-serif'; lc.textAlign = 'center'; lc.fillText('ЧАК ЧАК', 256, 139); lc.font = '22px sans-serif'; lc.fillText('к чаю',256,181);
|
||||||
|
const labelTexture = new THREE.CanvasTexture(labelCanvas); labelTexture.colorSpace = THREE.SRGBColorSpace;
|
||||||
|
const labelMaterial = new THREE.MeshLambertMaterial({ map: labelTexture });
|
||||||
|
box([.56, .04, .42], cardboard, packageGroup, [0, .02, 0]);
|
||||||
|
for (const x of [-.265, .265]) box([.03, .25, .42], cardboard, packageGroup, [x, .135, 0]);
|
||||||
|
for (const z of [-.195, .195]) box([.53, .25, .03], cardboard, packageGroup, [0, .135, z]);
|
||||||
|
mesh(new THREE.PlaneGeometry(.48, .18), labelMaterial, packageGroup, [0, .15, .212]);
|
||||||
|
const lid = new THREE.Group(); lid.position.set(0, .27, -.21); packageGroup.add(lid);
|
||||||
|
box([.58, .03, .44], cardboard, lid, [0, 0, .21]);
|
||||||
|
const topLabel = mesh(new THREE.PlaneGeometry(.53, .36), labelMaterial, lid, [0, .016, .21]); topLabel.rotation.x = -Math.PI / 2;
|
||||||
|
const bites = new THREE.InstancedMesh(new THREE.CylinderGeometry(.026,.024,.08,5),gold,18); const biteTransform = new THREE.Object3D();
|
||||||
|
for(let i=0;i<18;i++){biteTransform.position.set((random()-.5)*.4,.095+random()*.07,(random()-.5)*.28);biteTransform.rotation.set(random()*Math.PI,random()*Math.PI,random()*Math.PI);biteTransform.updateMatrix();bites.setMatrixAt(i,biteTransform.matrix);}packageGroup.add(bites);
|
||||||
|
let packageOpen = false;
|
||||||
|
|
||||||
|
const soilCanvas = document.createElement('canvas'); soilCanvas.width = soilCanvas.height = 128; const soilContext = soilCanvas.getContext('2d');
|
||||||
|
soilContext.fillStyle = '#31271b'; soilContext.fillRect(0, 0, 128, 128);
|
||||||
|
for (let i = 0; i < 2000; i++) { const b = 25 + random() * 70; soilContext.fillStyle = `rgb(${b + 12},${b},${b * .65})`; soilContext.fillRect(random() * 128, random() * 128, 1 + random() * 2, 1 + random() * 2); }
|
||||||
|
const soilTexture = new THREE.CanvasTexture(soilCanvas); soilTexture.wrapS = soilTexture.wrapT = THREE.RepeatWrapping; soilTexture.repeat.set(2, 2); soilTexture.colorSpace = THREE.SRGBColorSpace;
|
||||||
|
const soil = (software ? new THREE.MeshLambertMaterial({ map: soilTexture }) : new THREE.MeshStandardMaterial({ map: soilTexture, roughness: 1 }));
|
||||||
|
const leafGeometry = new THREE.BufferGeometry();
|
||||||
|
const leafVertices = [], leafIndices = [];
|
||||||
|
for (let i = 0; i <= 8; i++) { const t = i / 8, width = Math.pow(Math.sin(t * Math.PI), .85) * .27; for (const side of [-1, 0, 1]) leafVertices.push(side * width, t * .9, Math.sin(t * Math.PI) * .19 - t * t * .18 + (side === 0 ? .055 : 0)); }
|
||||||
|
for (let i = 0; i < 8; i++) for (let j = 0; j < 2; j++) { const a = i * 3 + j; leafIndices.push(a, a + 1, a + 3, a + 1, a + 4, a + 3); }
|
||||||
|
leafGeometry.setAttribute('position', new THREE.Float32BufferAttribute(leafVertices, 3)); leafGeometry.setIndex(leafIndices); leafGeometry.computeVertexNormals();
|
||||||
|
const leafMaterials = [0x70b940, 0xa2c866, 0x358251, 0x509847].map(color => software ? new THREE.MeshLambertMaterial({ color, side: THREE.DoubleSide }) : new THREE.MeshStandardMaterial({ color, roughness: .52, metalness: .02, side: THREE.DoubleSide }));
|
||||||
|
const stemMat = material(0x5e8641, .02, .9);
|
||||||
|
const vegetation = [];
|
||||||
|
const fruitMaterials = [material(0xaf482b, .05, .6), material(0xe8a846, .05, .6)];
|
||||||
|
function plant(parent, x, z, size, species) {
|
||||||
|
const plantGroup = new THREE.Group(); plantGroup.position.set(x, .62, z); plantGroup.scale.setScalar(size); parent.add(plantGroup);
|
||||||
|
cylinder(.024, .037, .9, stemMat, plantGroup, [0, .43, 0], 5);
|
||||||
|
for (let j = 0; j < 7; j++) {
|
||||||
|
const leaf = mesh(leafGeometry, leafMaterials[(j + species) % 4], plantGroup, [0, .18 + j * .093, 0]);
|
||||||
|
leaf.rotation.set(.55 + j * .08, j * 2.4 + species, -.25); leaf.scale.setScalar(1.05 - j * .055);
|
||||||
|
}
|
||||||
|
if (species % 3 === 0) for (let j = 0; j < 3; j++) { const a = j * 2.1; mesh(new THREE.SphereGeometry(.09, 8, 6), fruitMaterials[j % 2], plantGroup, [Math.cos(a) * .15, .62 + j * .07, Math.sin(a) * .15]); }
|
||||||
|
vegetation.push({ group: plantGroup, phase: random() * Math.PI * 2 });
|
||||||
|
}
|
||||||
|
for (let bed = 0; bed < 6; bed++) {
|
||||||
|
const angle = bed * Math.PI / 3 + .11;
|
||||||
|
const bedGroup = new THREE.Group(); bedGroup.rotation.y = angle; station.add(bedGroup);
|
||||||
|
const shape = new THREE.Shape(); const start = .08, end = Math.PI / 3 - .12;
|
||||||
|
shape.absarc(0, 0, 3.77, start, end, false); shape.lineTo(Math.cos(end) * 1.35, Math.sin(end) * 1.35); shape.absarc(0, 0, 1.35, end, start, true); shape.closePath();
|
||||||
|
const bedGeo = new THREE.ExtrudeGeometry(shape, { depth: .23, bevelEnabled: true, bevelSize: .035, bevelThickness: .025, bevelSegments: 1, steps: 1, curveSegments: 12 }); bedGeo.rotateX(-Math.PI / 2);
|
||||||
|
mesh(bedGeo, ceramic, bedGroup, [0, .35, 0]);
|
||||||
|
const soilGeo = new THREE.ShapeGeometry(shape, 12); soilGeo.rotateX(-Math.PI / 2); const ground = mesh(soilGeo, soil, bedGroup, [0, .618, 0]); ground.scale.set(.965, 1, .965);
|
||||||
|
for (let row = 0; row < 3; row++) for (let col = 0; col < 3 + row; col++) {
|
||||||
|
const a = start + .11 + col / (2 + row) * (end - start - .23), r = 1.8 + row * .75;
|
||||||
|
plant(bedGroup, Math.cos(a) * r, -Math.sin(a) * r, .63 + random() * .6, bed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cylinder(.7, .85, .32, ceramic, station, [0, .47, 0], 32);
|
||||||
|
cylinder(.31, .45, 1.55, darkMetal, station, [0, 1.38, 0], 16);
|
||||||
|
for (let i = 0; i < 6; i++) { const a = i * Math.PI / 3; beam([Math.cos(a) * .33, .7, Math.sin(a) * .33], [Math.cos(a) * .27, 2.12, Math.sin(a) * .27], .027, mint); }
|
||||||
|
torus(.36, .055, gold, station, 2.13);
|
||||||
|
const crown = new THREE.Group(); crown.position.y = 1.5; station.add(crown);
|
||||||
|
for (let i = 0; i < 12; i++) { const leaf = mesh(leafGeometry, leafMaterials[i % 4], crown, [0, .6 + (i % 3) * .18, 0]); leaf.rotation.set(.75 + (i % 4) * .2, i * 2.4, 0); leaf.scale.set(1.5, 1.65, 1.5); }
|
||||||
|
|
||||||
|
const domeRadius = 4.22, domeY = .39;
|
||||||
|
const ico = new THREE.IcosahedronGeometry(domeRadius, 2); const positions = ico.attributes.position;
|
||||||
|
const triangles = [];
|
||||||
|
for (let i = 0; i < positions.count; i += 3) {
|
||||||
|
let polygon = [0, 1, 2].map(j => new THREE.Vector3().fromBufferAttribute(positions, i + j));
|
||||||
|
const clipped = [];
|
||||||
|
for (let j = 0; j < polygon.length; j++) {
|
||||||
|
const a = polygon[j], b = polygon[(j + 1) % polygon.length], insideA = a.y >= -.00001, insideB = b.y >= -.00001;
|
||||||
|
if (insideA) clipped.push(a);
|
||||||
|
if (insideA !== insideB) clipped.push(a.clone().lerp(b, -a.y / (b.y - a.y)));
|
||||||
|
}
|
||||||
|
for (let j = 1; j < clipped.length - 1; j++) for (const vertex of [clipped[0], clipped[j], clipped[j + 1]]) triangles.push(vertex.x, Math.max(0, vertex.y), vertex.z);
|
||||||
|
}
|
||||||
|
ico.dispose();
|
||||||
|
const domeGeo = new THREE.BufferGeometry(); domeGeo.setAttribute('position', new THREE.Float32BufferAttribute(triangles, 3)); domeGeo.computeVertexNormals();
|
||||||
|
const glassMat = software ? new THREE.MeshPhongMaterial({ color: 0x9dcfc6, transparent: true, opacity: .1, shininess: 90, side: THREE.DoubleSide, depthWrite: false }) : new THREE.MeshPhysicalMaterial({ color: 0xa8d9d1, transparent: true, opacity: .095, roughness: .13, metalness: .42, clearcoat: 1, clearcoatRoughness: .15, side: THREE.DoubleSide, depthWrite: false });
|
||||||
|
const glass = mesh(domeGeo, glassMat, station, [0, domeY, 0]); glass.castShadow = false; glass.receiveShadow = false; glass.renderOrder = 3;
|
||||||
|
const edges = new THREE.EdgesGeometry(domeGeo, 1); const edgePos = edges.attributes.position;
|
||||||
|
const struts = new THREE.InstancedMesh(new THREE.CylinderGeometry(.018, .018, 1, 5), titanium, edgePos.count / 2);
|
||||||
|
const dummy = new THREE.Object3D(), up = new THREE.Vector3(0, 1, 0), joints = new Map();
|
||||||
|
for (let i = 0; i < edgePos.count; i += 2) {
|
||||||
|
const a = new THREE.Vector3().fromBufferAttribute(edgePos, i), b = new THREE.Vector3().fromBufferAttribute(edgePos, i + 1);
|
||||||
|
const direction = b.clone().sub(a); dummy.position.copy(a).add(b).multiplyScalar(.5); dummy.position.y += domeY; dummy.quaternion.setFromUnitVectors(up, direction.clone().normalize()); dummy.scale.set(1, direction.length(), 1); dummy.updateMatrix(); struts.setMatrixAt(i / 2, dummy.matrix);
|
||||||
|
for (const vertex of [a, b]) joints.set(vertex.toArray().map(n => n.toFixed(3)).join(','), vertex);
|
||||||
|
}
|
||||||
|
struts.castShadow = true; station.add(struts);
|
||||||
|
const nodes = new THREE.InstancedMesh(new THREE.SphereGeometry(.043, 6, 5), gold, joints.size); let jointIndex = 0;
|
||||||
|
for (const vertex of joints.values()) { dummy.position.copy(vertex); dummy.position.y += domeY; dummy.rotation.set(0, 0, 0); dummy.scale.setScalar(1); dummy.updateMatrix(); nodes.setMatrixAt(jointIndex++, dummy.matrix); } station.add(nodes);
|
||||||
|
edges.dispose();
|
||||||
|
torus(4.22, .073, ceramic, station, domeY);
|
||||||
|
torus(4.28, .025, amber, station, domeY + .02);
|
||||||
|
cylinder(.19, .25, .2, gold, station, [0, 4.65, 0], 16); beam([0, 4.7, 0], [0, 5.38, 0], .024, titanium);
|
||||||
|
const beacon = mesh(new THREE.SphereGeometry(.07, 12, 8), amber, station, [0, 5.38, 0]);
|
||||||
|
const beaconGlow = glow(station, [0, 5.38, 0], 0xffc989, 1.1, .9);
|
||||||
|
const beaconLight = new THREE.PointLight(0xffc175, 5, 5); beaconLight.position.copy(beacon.position); station.add(beaconLight);
|
||||||
|
|
||||||
|
const ring = new THREE.Group(); ring.position.y = -.42; station.add(ring);
|
||||||
|
torus(6.03, .095, titanium, ring); torus(6.53, .065, gold, ring); torus(6.5, .022, amber, ring, .1); torus(6.03, .018, mint, ring, -.15);
|
||||||
|
const ringDeck = mesh(new THREE.RingGeometry(6.07, 6.47, 128), (software ? new THREE.MeshPhongMaterial({ color: 0x43575b, shininess: 30, side: THREE.DoubleSide }) : new THREE.MeshStandardMaterial({ color: 0x43575b, metalness: .8, roughness: .4, side: THREE.DoubleSide })), ring); ringDeck.rotation.x = -Math.PI / 2;
|
||||||
|
for (let i = 0; i < 48; i++) {
|
||||||
|
const a = i * Math.PI / 24, b = a + Math.PI / 24;
|
||||||
|
beam([Math.cos(a) * 6.05, 0, Math.sin(a) * 6.05], [Math.cos(b) * 6.5, 0, Math.sin(b) * 6.5], .026, ceramic, ring);
|
||||||
|
if (i % 4 === 0) { const lamp = box([.12, .04, .35], i % 8 ? mint : amber, ring, [Math.cos(a) * 6.29, .055, Math.sin(a) * 6.29]); lamp.rotation.y = -a; }
|
||||||
|
}
|
||||||
|
const pods = new THREE.Group(); station.add(pods);
|
||||||
|
for (let i = 0; i < 4; i++) {
|
||||||
|
const a = i * Math.PI / 2 + Math.PI / 4, pod = new THREE.Group(); pod.rotation.y = a; pods.add(pod);
|
||||||
|
box([.6, .24, 2.25], titanium, pod, [0, -.5, 5.35]); box([.3, .05, 2.0], black, pod, [0, -.355, 5.4]);
|
||||||
|
for (const side of [-1, 1]) beam([side * .2, -.8, 4], [side * .32, -.5, 6.2], .045, gold, pod);
|
||||||
|
const tube = cylinder(.42, .42, 1.55, ceramic, pod, [0, -.35, 6.24], 20); tube.rotation.x = Math.PI / 2;
|
||||||
|
for (const z of [5.6, 6.0, 6.6, 6.9]) { const collar = torus(.43, .035, titanium, pod); collar.position.set(0, -.35, z); collar.rotation.x = 0; }
|
||||||
|
const hatch = cylinder(.3, .3, .1, darkMetal, pod, [0, -.35, 7.05], 16); hatch.rotation.x = Math.PI / 2;
|
||||||
|
glow(pod, [0, -.35, 7.13], 0x72f6d0, .5, .6);
|
||||||
|
}
|
||||||
|
|
||||||
|
const solarMat = material(0x173c59, .72, .26);
|
||||||
|
const solarLines = material(0x53838c, .55, .45);
|
||||||
|
for (const sign of [-1, 1]) {
|
||||||
|
const wing = new THREE.Group(); wing.position.set(sign * 6.7, -.65, -.65); wing.rotation.z = sign * .1; station.add(wing);
|
||||||
|
box([3.9, .14, .22], gold, wing, [sign * .35, 0, 0]);
|
||||||
|
for (const z of [-1.05, 1.05]) {
|
||||||
|
box([3.0, .09, 1.72], titanium, wing, [sign * .55, 0, z]); box([2.9, .02, 1.62], solarMat, wing, [sign * .55, .058, z]);
|
||||||
|
for (let i = 0; i < 10; i++) box([.012, .015, 1.6], solarLines, wing, [sign * .55 - 1.4 + i * .31, .074, z]);
|
||||||
|
for (let j = 0; j < 5; j++) box([2.9, .015, .009], solarLines, wing, [sign * .55, .075, z - .8 + j * .4]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const orbit = new THREE.Group(); orbit.rotation.z = .16; station.add(orbit);
|
||||||
|
const orbitRail = torus(7.32, .012, material(0x3d6e73, .4, .6), orbit, .15);
|
||||||
|
const dronePivot = new THREE.Group(); orbit.add(dronePivot);
|
||||||
|
const drone = new THREE.Group(); drone.position.set(7.32, .15, 0); dronePivot.add(drone);
|
||||||
|
mesh(new THREE.OctahedronGeometry(.21), ceramic, drone); box([.95, .04, .25], solarMat, drone); glow(drone, [0, 0, .22], 0x8fdfff, 1, .8);
|
||||||
|
const dish = mesh(new THREE.SphereGeometry(.43, 20, 10, 0, Math.PI * 2, 0, Math.PI / 2), ceramic, station, [-3.5, -.6, 4.5]); dish.rotation.z = -.6; dish.rotation.x = .8;
|
||||||
|
|
||||||
|
const windTime = { value: 0 };
|
||||||
|
for (const leafMaterial of leafMaterials) {
|
||||||
|
leafMaterial.onBeforeCompile = shader => {
|
||||||
|
shader.uniforms.windTime = windTime;
|
||||||
|
shader.vertexShader = 'uniform float windTime;\n' + shader.vertexShader;
|
||||||
|
shader.vertexShader = shader.vertexShader.replace('#include <begin_vertex>', '#include <begin_vertex>\ntransformed.x += sin(windTime*.9+position.x*1.7+position.z)*.035*max(0.,position.y-.65);');
|
||||||
|
};
|
||||||
|
leafMaterial.customProgramCacheKey = () => 'greenhouse-wind-v1';
|
||||||
|
}
|
||||||
|
function batch(root, excluded = new Set()) {
|
||||||
|
scene.updateMatrixWorld(true);
|
||||||
|
const inverse = root.matrixWorld.clone().invert(), groups = new Map(), sources = [];
|
||||||
|
function visit(object) {
|
||||||
|
if (excluded.has(object)) return;
|
||||||
|
if (object.isMesh && !object.isInstancedMesh && !Array.isArray(object.material)) {
|
||||||
|
const key = object.material.uuid;
|
||||||
|
if (!groups.has(key)) groups.set(key, { material: object.material, position: [], normal: [], uv: [], cast: false, receive: false });
|
||||||
|
const group = groups.get(key), geometry = object.geometry.index ? object.geometry.toNonIndexed() : object.geometry.clone();
|
||||||
|
geometry.applyMatrix4(new THREE.Matrix4().multiplyMatrices(inverse, object.matrixWorld));
|
||||||
|
const attributes = geometry.attributes;
|
||||||
|
for (let i = 0; i < attributes.position.array.length; i++) group.position.push(attributes.position.array[i]);
|
||||||
|
for (let i = 0; i < attributes.normal.array.length; i++) group.normal.push(attributes.normal.array[i]);
|
||||||
|
if (attributes.uv) for (let i = 0; i < attributes.uv.array.length; i++) group.uv.push(attributes.uv.array[i]);
|
||||||
|
else for (let i = 0; i < attributes.position.count * 2; i++) group.uv.push(0);
|
||||||
|
group.cast ||= object.castShadow; group.receive ||= object.receiveShadow;
|
||||||
|
sources.push(object); geometry.dispose();
|
||||||
|
}
|
||||||
|
for (const child of object.children) visit(child);
|
||||||
|
}
|
||||||
|
for (const child of root.children) visit(child);
|
||||||
|
for (const source of sources) source.removeFromParent();
|
||||||
|
for (const group of groups.values()) {
|
||||||
|
const geometry = new THREE.BufferGeometry();
|
||||||
|
geometry.setAttribute('position', new THREE.Float32BufferAttribute(group.position, 3)); geometry.setAttribute('normal', new THREE.Float32BufferAttribute(group.normal, 3)); geometry.setAttribute('uv', new THREE.Float32BufferAttribute(group.uv, 2));
|
||||||
|
const merged = new THREE.Mesh(geometry, group.material); merged.castShadow = group.cast; merged.receiveShadow = group.receive; root.add(merged);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
batch(station, new Set([glass, ring, orbit, crown, packageGroup, ...fans])); batch(ring); batch(crown); batch(drone); fans.forEach(fan => batch(fan));
|
||||||
|
|
||||||
|
let interior = false;
|
||||||
|
let inspectingPackage = false;
|
||||||
|
let inspectionTween = null;
|
||||||
|
const normalMinDistance = 2.4;
|
||||||
|
const lidOpenAngle = -.65;
|
||||||
|
function endInspection() {
|
||||||
|
inspectingPackage = false; inspectionTween = null;
|
||||||
|
controls.enabled = true; controls.enableDamping = !paused;
|
||||||
|
controls.minDistance = normalMinDistance;
|
||||||
|
camera.fov = mobile() ? 50 : 39; camera.updateProjectionMatrix();
|
||||||
|
}
|
||||||
|
function focusPackage() {
|
||||||
|
interior = true; inspectingPackage = true;
|
||||||
|
controls.minDistance = .7;
|
||||||
|
camera.fov = 65; camera.updateProjectionMatrix();
|
||||||
|
controls.enableDamping = false;
|
||||||
|
scene.updateMatrixWorld(true);
|
||||||
|
const destination = packageGroup.localToWorld(new THREE.Vector3(0, .45, .9));
|
||||||
|
const target = packageGroup.localToWorld(new THREE.Vector3(0, .2, 0));
|
||||||
|
if (paused || reducedMotion.matches) {
|
||||||
|
inspectionTween = null; camera.position.copy(destination); controls.target.copy(target);
|
||||||
|
controls.enabled = true; controls.update();
|
||||||
|
} else {
|
||||||
|
inspectionTween = { from: camera.position.clone(), fromTarget: controls.target.clone(), to: destination, target, start: performance.now() };
|
||||||
|
controls.enabled = false;
|
||||||
|
}
|
||||||
|
requestRender();
|
||||||
|
}
|
||||||
|
function updateInspection(now) {
|
||||||
|
if (!inspectionTween) return;
|
||||||
|
const t = paused || reducedMotion.matches ? 1 : Math.min(1, (now - inspectionTween.start) / 650);
|
||||||
|
const eased = t*t*(3-2*t);
|
||||||
|
camera.position.lerpVectors(inspectionTween.from, inspectionTween.to, eased);
|
||||||
|
controls.target.lerpVectors(inspectionTween.fromTarget, inspectionTween.target, eased);
|
||||||
|
if(t === 1) { inspectionTween = null; controls.enabled = true; controls.enableDamping = !paused; }
|
||||||
|
}
|
||||||
|
function interiorCamera() {
|
||||||
|
endInspection();
|
||||||
|
interior = true;
|
||||||
|
scene.updateMatrixWorld(true);
|
||||||
|
controls.target.copy(station.localToWorld(new THREE.Vector3(0, .95, -.15)));
|
||||||
|
camera.position.copy(station.localToWorld(new THREE.Vector3(2.6, 2.25, 3.2)));
|
||||||
|
controls.update(); requestRender();
|
||||||
|
}
|
||||||
|
canvas.addEventListener('dblclick', event => { event.preventDefault(); if (!packageHit(pointAt(event))) interiorCamera(); });
|
||||||
|
const hint = document.querySelector('#object-hint'), raycaster = new THREE.Raycaster();
|
||||||
|
const opaque = [];
|
||||||
|
station.traverse(object => { if (object.isMesh && object !== glass && !object.material?.transparent) opaque.push(object); });
|
||||||
|
function packageHit(point) {
|
||||||
|
if (camera.position.distanceTo(controls.target) > 16) return false;
|
||||||
|
scene.updateMatrixWorld(true); camera.updateMatrixWorld(); raycaster.setFromCamera(point, camera);
|
||||||
|
const candidate = raycaster.intersectObject(packageGroup, true)[0];
|
||||||
|
if (!candidate) return false;
|
||||||
|
raycaster.far = candidate.distance + .02;
|
||||||
|
const first = raycaster.intersectObjects(opaque, false)[0]; raycaster.far = Infinity;
|
||||||
|
return !first || first.distance >= candidate.distance - .025;
|
||||||
|
}
|
||||||
|
function pointAt(event) { const b=canvas.getBoundingClientRect();return new THREE.Vector2((event.clientX-b.left)/b.width*2-1,-(event.clientY-b.top)/b.height*2+1); }
|
||||||
|
function inspectPackage() {
|
||||||
|
packageOpen = !packageOpen; canvas.dataset.discovered = 'true';
|
||||||
|
if (paused || reducedMotion.matches) lid.rotation.x = packageOpen ? lidOpenAngle : 0;
|
||||||
|
if (packageOpen) focusPackage();
|
||||||
|
hint.textContent = packageOpen ? 'ЧАК ЧАК. Коробка открыта. К чаю.' : 'ЧАК ЧАК. Коробка закрыта.'; hint.hidden=false; requestRender();
|
||||||
|
}
|
||||||
|
let down = null, hoverTime = 0;
|
||||||
|
canvas.addEventListener('pointerdown', event => { down={x:event.clientX,y:event.clientY}; });
|
||||||
|
canvas.addEventListener('pointerup', event => { if(down && Math.hypot(event.clientX-down.x,event.clientY-down.y)<5 && packageHit(pointAt(event))) inspectPackage(); down=null; });
|
||||||
|
canvas.addEventListener('pointercancel',()=>{down=null;});
|
||||||
|
canvas.addEventListener('pointermove',event=>{
|
||||||
|
if(down || performance.now()-hoverTime<150)return;hoverTime=performance.now();
|
||||||
|
const hit=packageHit(pointAt(event)); canvas.style.cursor=hit?'pointer':'';
|
||||||
|
if(hit){hint.textContent='Коробка под столом · нажмите, чтобы осмотреть';hint.hidden=false;}
|
||||||
|
else if(!packageOpen)hint.hidden=true;
|
||||||
|
},{passive:true});
|
||||||
|
canvas.addEventListener('pointerleave',()=>{canvas.style.cursor='';if(!packageOpen)hint.hidden=true;});
|
||||||
|
canvas.addEventListener('keydown',event=>{if(event.key==='Enter'&&packageHit(new THREE.Vector2(0,0))){event.preventDefault();inspectPackage();}});
|
||||||
|
function resetCamera() {
|
||||||
|
endInspection();
|
||||||
|
interior = false;
|
||||||
|
controls.target.set(0, mobile() ? .2 : .9, 0);
|
||||||
|
const distance = mobile() ? 42 : (innerWidth / innerHeight < 1.35 ? 26 : 23);
|
||||||
|
const vector = new THREE.Vector3(10.5, 9, 15.5).normalize().multiplyScalar(distance);
|
||||||
|
camera.position.copy(controls.target).add(vector); controls.update(); requestRender();
|
||||||
|
}
|
||||||
|
function zoom(factor) { const offset = camera.position.clone().sub(controls.target); offset.setLength(THREE.MathUtils.clamp(offset.length() * factor, controls.minDistance, controls.maxDistance)); camera.position.copy(controls.target).add(offset); controls.update(); requestRender(); }
|
||||||
|
function rotateCamera(horizontal, vertical) { const spherical = new THREE.Spherical().setFromVector3(camera.position.clone().sub(controls.target)); spherical.theta += horizontal; spherical.phi = THREE.MathUtils.clamp(spherical.phi + vertical, controls.minPolarAngle, controls.maxPolarAngle); camera.position.copy(controls.target).add(new THREE.Vector3().setFromSpherical(spherical)); controls.update(); requestRender(); }
|
||||||
|
function syncMotion() {
|
||||||
|
motionButton.setAttribute('aria-pressed', String(paused)); motionButton.textContent = paused ? 'Анимация' : 'Пауза';
|
||||||
|
motionButton.setAttribute('aria-label', paused ? 'Включить анимацию' : 'Остановить анимацию'); motionButton.title = paused ? 'Включить анимацию' : 'Остановить анимацию';
|
||||||
|
controls.enableDamping = !paused; previous = 0; requestRender();
|
||||||
|
}
|
||||||
|
document.querySelector('#camera-zoom-in').addEventListener('click', () => zoom(.86));
|
||||||
|
document.querySelector('#camera-zoom-out').addEventListener('click', () => zoom(1.16));
|
||||||
|
motionButton.addEventListener('click', () => { paused = !paused; syncMotion(); });
|
||||||
|
reducedMotion.addEventListener('change', () => { paused = reducedMotion.matches; syncMotion(); });
|
||||||
|
canvas.addEventListener('keydown', event => {
|
||||||
|
const orbitStep = event.shiftKey ? .002 : .1;
|
||||||
|
const actions = { i: interiorCamera, I: interiorCamera, ArrowLeft: () => rotateCamera(-orbitStep, 0), ArrowRight: () => rotateCamera(orbitStep, 0), ArrowUp: () => rotateCamera(0, -.08), ArrowDown: () => rotateCamera(0, .08), '+': () => zoom(.9), '=': () => zoom(.9), '-': () => zoom(1.1), Home: resetCamera, ' ': () => { paused = !paused; syncMotion(); } };
|
||||||
|
if (actions[event.key]) { event.preventDefault(); actions[event.key](); }
|
||||||
|
});
|
||||||
|
controls.addEventListener('start', () => { interacting = true; });
|
||||||
|
controls.addEventListener('end', () => { interacting = false; });
|
||||||
|
controls.addEventListener('change', requestRender);
|
||||||
|
canvas.addEventListener('webglcontextlost', event => { event.preventDefault(); contextLost = true; gpuFence = null; cancelAnimationFrame(frame); frame = 0; fallback.hidden = false; fallback.querySelector('strong').textContent = 'Визуальный канал приостановлен'; fallback.querySelector('p').textContent = 'Графический контекст потерян. Перезагрузите страницу, чтобы восстановить сцену. Терминал доступен.'; });
|
||||||
|
canvas.addEventListener('webglcontextrestored', () => { contextLost = false; fallback.hidden = true; requestRender(); });
|
||||||
|
document.addEventListener('visibilitychange', () => { hidden = document.hidden; if (hidden) { cancelAnimationFrame(frame); frame = 0; } else { previous = 0; requestRender(); } });
|
||||||
|
let wasMobile = mobile();
|
||||||
|
addEventListener('resize', () => { camera.aspect = innerWidth / innerHeight; camera.fov = inspectingPackage ? 65 : (mobile() ? 50 : 39); camera.updateProjectionMatrix(); renderer.setPixelRatio(pixelRatio()); renderer.setSize(innerWidth, innerHeight, false); if (wasMobile !== mobile()) { wasMobile = mobile(); resetCamera(); } requestRender(); });
|
||||||
|
function requestRender() { if (!frame && !hidden && !contextLost) frame = requestAnimationFrame(render); }
|
||||||
|
function render(now) {
|
||||||
|
frame = 0;
|
||||||
|
|
||||||
|
if (gpuFence) {
|
||||||
|
const ready = gl.clientWaitSync(gpuFence, 0, 0);
|
||||||
|
if (ready === gl.TIMEOUT_EXPIRED) { requestRender(); return; }
|
||||||
|
gl.deleteSync(gpuFence); gpuFence = null;
|
||||||
|
}
|
||||||
|
if (!paused && now - lastPaint < frameInterval) { requestRender(); return; }
|
||||||
|
lastPaint = now;
|
||||||
|
const delta = previous ? Math.min((now - previous) / 1000, .05) : 0; previous = now;
|
||||||
|
if (!paused) {
|
||||||
|
elapsed += delta;
|
||||||
|
if (!interacting && !interior) station.rotation.y += delta * .019;
|
||||||
|
if (!inspectingPackage) station.position.y = Math.sin(elapsed * .36) * .06;
|
||||||
|
dronePivot.rotation.y = elapsed * .13;
|
||||||
|
ring.rotation.y = -elapsed * .013;
|
||||||
|
beaconGlow.material.opacity = .42 + (Math.sin(elapsed * 2.2) + 1) * .26;
|
||||||
|
beaconLight.intensity = 3 + (Math.sin(elapsed * 2.2) + 1) * 2;
|
||||||
|
windTime.value = elapsed;
|
||||||
|
fans.forEach((fan, i) => { fan.rotation.z = elapsed * (2.3 + i*.3); });
|
||||||
|
lid.rotation.x += ((packageOpen ? lidOpenAngle : 0) - lid.rotation.x) * Math.min(1, delta * 8);
|
||||||
|
drone.rotation.y = Math.sin(elapsed*.4)*.2;
|
||||||
|
crown.rotation.y = Math.sin(elapsed * .35) * .06;
|
||||||
|
planet.rotation.y = elapsed * .003;
|
||||||
|
clouds.rotation.y = elapsed * .0038;
|
||||||
|
underlight.intensity = 32 + Math.sin(elapsed * .5) * 4;
|
||||||
|
}
|
||||||
|
updateInspection(now);
|
||||||
|
controls.update();
|
||||||
|
if (paintCount++ % 6 === 0 || paused) renderer.shadowMap.needsUpdate = true;
|
||||||
|
renderer.render(scene, camera);
|
||||||
|
if (software) { gpuFence = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0); gl.flush(); }
|
||||||
|
canvas.dataset.ready = 'true'; loading.hidden = true; fallback.hidden = true;
|
||||||
|
if (!paused) requestRender();
|
||||||
|
}
|
||||||
|
function inspectionView() {
|
||||||
|
const samples = [[0,.15,.214],[-.19,.09,.214],[.19,.09,.214],[-.19,.21,.214],[.19,.21,.214]];
|
||||||
|
const projected = samples.map(point => packageGroup.localToWorld(new THREE.Vector3(...point)).project(camera));
|
||||||
|
const corners = projected.slice(1).map(p=>({x:(p.x+1)*innerWidth/2,y:(1-p.y)*innerHeight/2}));
|
||||||
|
return { focused: inspectingPackage, open: packageOpen, labelCenterVisible: packageHit(new THREE.Vector2(projected[0].x, projected[0].y)), tweening: Boolean(inspectionTween), visibleSamples: projected.filter(p=>Math.abs(p.x)<1 && Math.abs(p.y)<1 && p.z<1 && packageHit(new THREE.Vector2(p.x,p.y))).length, labelWidth: Math.max(...corners.map(p=>p.x))-Math.min(...corners.map(p=>p.x)), labelHeight: Math.max(...corners.map(p=>p.y))-Math.min(...corners.map(p=>p.y)), corners };
|
||||||
|
}
|
||||||
|
|
||||||
|
window.greenhouseScene = { getInspectionView: inspectionView, getInspectionPoint: () => { const v=packageGroup.localToWorld(new THREE.Vector3(0,.15,.23)).project(camera);return {x:(v.x+1)*innerWidth/2,y:(1-v.y)*innerHeight/2,visible:packageHit(new THREE.Vector2(v.x,v.y))}; }, getStats: () => ({ revision: THREE.REVISION, starfield: { mode: 'baked-texture', width: skyCanvas.width, height: skyCanvas.height, version: skyTexture.version }, calls: renderer.info.render.calls, triangles: renderer.info.render.triangles, geometries: renderer.info.memory.geometries, paused, software, orbitMinDistance: controls.minDistance, fov: camera.fov, inspectingPackage, pixelRatio: renderer.getPixelRatio(), shadows: renderer.shadowMap.enabled, frameLimit: software ? 24 : 30, frames: paintCount, camera: camera.position.toArray(), rotation: station.rotation.y, contextLost }) };
|
||||||
|
resetCamera(); syncMotion(); requestRender();
|
||||||
|
}
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
:root{color-scheme:dark;--ink:#e0e6e7;--muted:#a2adb3;--line:#3b464e;--mint:#b7d9c7;--amber:#e3ba79;--mono:ui-monospace,'DejaVu Sans Mono',monospace;font-family:Arial,Helvetica,sans-serif;font-size:13px}*{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;overflow:hidden;background:#070d13;color:var(--ink)}button,input,textarea,select{font:inherit}button{cursor:pointer;touch-action:manipulation}a{color:inherit}button:disabled{opacity:.45;cursor:not-allowed}button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible,[tabindex]:focus-visible{outline:2px solid #f0cb82;outline-offset:2px}[hidden]{display:none!important}button{border:1px solid var(--line);background:#202a31;color:var(--ink);min-height:34px;padding:6px 12px;border-radius:3px}button:hover:not(:disabled){background:#303c43}button[aria-pressed=true],button[aria-expanded=true]{background:#34483f;border-color:#789a87}input,textarea,select{color:var(--ink);background:#0c141b;border:1px solid #55616b;padding:10px;width:100%;border-radius:2px;min-width:0}input::placeholder,textarea::placeholder{color:#96a0a9}label{display:block;font-size:12px;color:#c5cdd0}textarea{resize:vertical}.skip{position:absolute;top:-80px;left:20px;padding:12px;background:#dae9df;color:#111;z-index:60}.skip:focus{top:12px}#observatory{position:relative;width:100%;height:100%;height:100svh;overflow:hidden;background:#070d13}#space{position:absolute;inset:0;display:block;width:100%;height:100%;touch-action:none;cursor:grab;outline-offset:-5px}#space:active{cursor:grabbing}.vignette{position:absolute;inset:0;pointer-events:none;background:linear-gradient(#070d1333,transparent 18%,transparent 80%,#070d1333)}.vitals{position:absolute;bottom:105px;left:20px;width:213px;padding:14px;background:#101921e8;border:1px solid #3a464e;border-radius:3px;pointer-events:none}.vitals-heading{font-size:12px;display:flex;justify-content:space-between;border-bottom:1px solid var(--line);padding-bottom:10px}.vitals-heading strong{font-size:12px;color:var(--mint);font-weight:400}.vital-line{display:flex;align-items:center;justify-content:space-between;font-size:12px;margin-top:11px}.vital-line>span{color:var(--muted)}.vital-line strong{font:13px var(--mono);font-weight:400}.vitals>small{display:block;font-size:10px;color:var(--muted);margin-top:14px}.camera-controls{position:absolute;right:20px;bottom:105px;display:flex;gap:5px}.camera-controls button{min-width:36px;background:#111c24ed}.command-dock{position:absolute;left:0;right:0;bottom:28px;display:flex;align-items:stretch;gap:6px;padding:9px 20px;background:#111921fa;border-top:1px solid #465059;border-bottom:1px solid #39434a;min-height:56px}.command-dock button{font-size:13px;min-width:105px;white-space:nowrap}.command-dock #open-create{margin-left:auto}.command-dock small{display:inline-block;font-size:11px;color:var(--muted);margin-left:7px}.terminal{position:absolute;z-index:10;right:20px;top:112px;bottom:105px;width:420px;max-height:730px;border:1px solid #69767e;box-shadow:0 12px 40px #0007;background:#121c24;display:flex;flex-direction:column;border-radius:4px;overflow:hidden}.terminal-header{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:12px 16px;background:#26313a;border-bottom:1px solid #54606a}.terminal-header .eyebrow{font-size:10px;color:#b2bdc4}h2{font-size:17px;font-weight:500;margin:4px 0 0}.close{font-size:23px;line-height:1;border:0;background:transparent;min-width:34px;min-height:34px;padding:4px}.terminal-tabs{display:flex;padding:12px 14px 0;gap:5px}.terminal-tabs button{flex:1;font-size:12px;padding:6px}.terminal-tabs span{font-size:10px;margin-left:4px;color:var(--muted)}.terminal-toolbar{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:10px 16px;font-size:11px;border-bottom:1px solid var(--line);color:var(--muted)}#selected-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-button{font-size:11px;padding:4px 8px;min-height:29px;white-space:nowrap}.terminal-body{flex:1;overflow:auto;overscroll-behavior:contain;padding:14px 16px;scrollbar-width:thin;scrollbar-color:#67767b #16212a}.terminal-footer{display:flex;justify-content:space-between;padding:9px 16px;border-top:1px solid var(--line);font-size:10px;color:var(--muted)}.search{display:flex;align-items:center;gap:8px}.search>span{font-size:24px;color:var(--muted)}.search input{font-size:12px;padding:9px}.plot-list{max-height:235px;overflow:auto;margin-top:12px}.plot-card{display:flex;align-items:center;gap:10px;width:100%;border:0;border-bottom:1px solid #38444c;border-radius:0;background:transparent;text-align:left;padding:12px 6px}.plot-card[aria-pressed=true]{background:#243e32;border-left:3px solid #a4c8b4;padding-left:3px}.plant-icon{font-size:18px;color:var(--mint)}.plot-card-copy{flex:1;min-width:0}.plot-card strong{display:block;font-size:13px;font-weight:500;overflow-wrap:anywhere}.plot-card small{display:block;color:var(--muted);font-size:11px;Line truncated
|
||||||
|
@media(max-width:1000px){.operator-console{width:570px}.terminal{width:390px}.camera-controls{bottom:105px}}
|
||||||
|
@media(max-width:700px){.vitals{left:12px;bottom:125px;width:178px;padding:10px}.vitals-heading{font-size:11px;padding-bottom:7px}.vitals-heading strong{font-size:11px}.vital-line{font-size:11px;margin-top:8px}.vital-line strong{font-size:12px}.vitals>small{font-size:9px;margin-top:10px}.camera-controls{right:12px;bottom:125px;max-width:130px;flex-wrap:wrap;justify-content:flex-end}.camera-controls button{font-size:12px;padding:7px 9px;min-width:34px}.camera-controls button:last-child{flex-basis:100%}.command-dock{bottom:24px;min-height:78px;padding:8px 10px;display:grid;grid-template-columns:repeat(3,1fr);gap:5px}.command-dock button{min-width:0;font-size:11px;min-height:30px;padding:5px 7px}.command-dock #open-create{margin-left:0}.command-dock #console-launch{grid-column:1/3}.command-dock small{font-size:10px;margin-left:3px}.terminal{inset:auto 10px 118px;width:auto;height:57svh;max-height:570px}.terminal-header{padding:10px 13px}.terminal-header h2{font-size:16px}.terminal-tabs{padding:9px 12px 0}.terminal-toolbar{padding:8px 12px;font-size:10px}.terminal-body{padding:12px}.terminal-footer{padding:8px 12px;font-size:9px}.plot-list{max-height:155px}.terminal-open .vitals,.terminal-open .camera-controls{visibility:hidden}.notice{left:12px;top:118px;max-width:calc(100% - 24px);padding:9px 12px;font-size:11px;max-height:105px}.toast{top:116px;font-size:11px}dialog{padding:19px}dialog input,dialog textarea,dialog select{font-size:16px}.operator-console{left:10px;right:10px;bottom:118px;width:auto;height:54svh;max-height:calc(100svh - 235px);max-width:none;min-width:0;min-height:225px;resize:none}.console-titlebar{padding:6px 10px;gap:10px}.console-titlebar h2{font-size:13px}.console-titlebar #console-state{font-size:10px}.console-tools{padding:7px 10px;gap:5px}.console-tools button{font-size:10px;padding:4px 7px}.console-output{font-size:11px;padding:10px}.console-input-row input{font-size:16px;padding:8px;min-width:0}.console-input-row button{font-size:10px;padding:7px}.console-footer{font-size:9px}.console-error{font-size:10px;max-height:70px}#object-hint{bottom:113px;z-index:16;font-size:11px;max-width:calc(100% - 24px)}#scene-loading{padding:15px 18px}}
|
||||||
|
@media(max-height:600px) and (min-width:701px){.terminal{top:108px;bottom:96px}.operator-console{max-height:calc(100% - 210px);bottom:96px;min-height:200px}.vitals,.camera-controls{bottom:96px}.vitals{padding:9px}.vital-line{margin-top:7px}}
|
||||||
|
@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}
|
||||||
|
|
||||||
|
@font-face{font-family:DepartureMono;src:url('./fonts/DepartureMono-Regular.woff2') format('woff2');font-weight:400;font-display:swap}
|
||||||
|
:root{
|
||||||
|
--ink:#e6f1ef;--muted:#b4ced1;--line:#d6f0ed41;--mint:#d8f0e9;
|
||||||
|
--surface:#0b1b24a8;--surface-solid:#0b1b24;--signal:#d8f0e9;
|
||||||
|
--sans:DepartureMono,monospace;--mono:DepartureMono,monospace;--display:DepartureMono,monospace;
|
||||||
|
font-family:var(--sans);font-size:14px;
|
||||||
|
}
|
||||||
|
body,#observatory{background:#071017;color:var(--ink)}
|
||||||
|
button,input,textarea,select{font-family:var(--sans)}
|
||||||
|
button{border:0;border-radius:0;background:transparent;color:var(--ink);transition:color .18s,background .18s,opacity .18s}
|
||||||
|
button:hover:not(:disabled),button[aria-pressed=true],button[aria-expanded=true]{background:transparent;color:#dff9f2}
|
||||||
|
button:active:not(:disabled){background:transparent;color:var(--signal)}
|
||||||
|
button:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible,[tabindex]:focus-visible{outline:2px solid var(--signal);outline-offset:3px}
|
||||||
|
input,textarea,select{border-radius:0;background:#0b1b24;border:0;border-bottom:1px solid #d6f0ed6e;color:var(--ink);font-size:14px}
|
||||||
|
input::placeholder,textarea::placeholder{color:#a9c5c8}
|
||||||
|
.vignette{background:linear-gradient(90deg,#071017c9 0,transparent 32%,transparent 74%,#07101736 100%)}
|
||||||
|
|
||||||
|
.vitals{
|
||||||
|
left:40px;bottom:246px;width:282px;padding:0;border:0;background:transparent;box-shadow:none;
|
||||||
|
text-shadow:0 2px 14px #000d;pointer-events:none;
|
||||||
|
}
|
||||||
|
.vitals-heading{display:flex;justify-content:space-between;align-items:center;border:0;padding:0 0 23px;margin:0 0 4px;font:10px var(--mono);letter-spacing:.08em;color:#c7dddb}
|
||||||
|
.vitals-heading strong{font:11px var(--mono);letter-spacing:0;color:var(--signal)}
|
||||||
|
.vital-line{margin-top:11px;font:12px var(--mono)}
|
||||||
|
.vital-line>span{color:#a9c5c8}.vital-line strong{font:13px var(--mono);color:#e6f1ef}
|
||||||
|
.vitals>small{font:10px var(--mono);color:#a9c5c8;margin-top:22px}
|
||||||
|
.command-dock{
|
||||||
|
left:40px;right:auto;bottom:42px;width:282px;min-height:0;padding:0;gap:0;
|
||||||
|
display:block;background:transparent;border:0;box-shadow:none;
|
||||||
|
backdrop-filter:none;-webkit-backdrop-filter:none;
|
||||||
|
}
|
||||||
|
.command-dock button{
|
||||||
|
width:100%;min-width:0;min-height:67px;display:flex;align-items:center;justify-content:space-between;
|
||||||
|
padding:0 2px;text-align:left;white-space:nowrap;background:transparent;border:0;
|
||||||
|
border-top:1px solid #d6f0ed60;font-size:23px;font-weight:400;letter-spacing:-.035em;
|
||||||
|
}
|
||||||
|
.command-dock button:last-child{border-bottom:1px solid #d6f0ed60}
|
||||||
|
.command-dock button:hover,.command-dock button[aria-expanded=true]{color:var(--signal);background:transparent}
|
||||||
|
.command-dock button:hover .dock-label{transform:translateX(4px)}
|
||||||
|
.command-dock button[aria-expanded=true] .dock-label{color:var(--signal)}
|
||||||
|
.dock-label{transition:transform .18s,color .18s;line-height:1.1}
|
||||||
|
.dock-end{display:flex;align-items:center;gap:17px;font:17px var(--sans);color:#c7dddb}
|
||||||
|
.command-dock small{font:11px var(--mono);color:#c7dddb;margin:0}
|
||||||
|
#console-indicator{display:inline-block;width:5px;height:5px;border-radius:50%;background:#718e95;margin-left:6px;vertical-align:middle}
|
||||||
|
#console-indicator.connected{background:var(--signal)}
|
||||||
|
|
||||||
|
.camera-controls{
|
||||||
|
right:40px;bottom:43px;display:flex;align-items:center;gap:12px;
|
||||||
|
padding:0;background:transparent;border:0;border-radius:0;box-shadow:none;
|
||||||
|
backdrop-filter:none;-webkit-backdrop-filter:none;
|
||||||
|
}
|
||||||
|
.camera-controls button{min-width:29px;min-height:34px;padding:0;background:transparent;border:0;border-radius:0;font:19px var(--sans);color:#c7dddb;opacity:.84}
|
||||||
|
.camera-controls button:hover{background:transparent;color:#dff9f2;opacity:1}
|
||||||
|
.camera-controls #motion-toggle{min-width:0;padding-left:18px;border-left:1px solid #d6f0ed57;font:12px var(--sans);letter-spacing:.01em}
|
||||||
|
|
||||||
|
.terminal,.operator-console{
|
||||||
|
z-index:10;right:0;top:0;bottom:0;left:auto;width:460px;height:auto;max-height:none;max-width:min(100vw,700px);min-width:0;min-height:0;
|
||||||
|
border:0;border-left:1px solid #d6f0ed5c;border-radius:0;background:var(--surface);
|
||||||
|
box-shadow:-30px 0 80px #0008;backdrop-filter:blur(24px);-webkit-backdrop-filter:blur(24px);
|
||||||
|
animation:surface-in .25s ease-out;overflow:hidden;
|
||||||
|
}
|
||||||
|
@keyframes surface-in{from{transform:translateX(16px);opacity:.75}to{transform:translateX(0);opacity:1}}
|
||||||
|
.terminal-header{display:flex;align-items:flex-start;gap:16px;padding:44px 42px 21px;background:transparent;border:0}
|
||||||
|
.terminal-header .eyebrow,.eyebrow{font:11px var(--mono);letter-spacing:.055em;color:#a9c5c8}
|
||||||
|
.terminal-header h2{margin:12px 0 0;font:400 38px/1.1 var(--sans);letter-spacing:-.045em;color:#e6f1ef}
|
||||||
|
.close{margin:0 0 0 auto;width:34px;min-width:34px;min-height:34px;padding:0;border:0;border-radius:0;background:transparent;font:28px/1 var(--sans);color:#a9c5c8}
|
||||||
|
.close:hover{background:transparent;color:#dff9f2}
|
||||||
|
.terminal-tabs{display:flex;gap:27px;padding:0 42px;border-bottom:1px solid #d6f0ed44}
|
||||||
|
.terminal-tabs button{flex:0 0 auto;min-height:49px;padding:0 0 1px;font:14px var(--sans);border:0;border-bottom:2px solid transparent;border-radius:0;background:transparent;color:#a9c5c8}
|
||||||
|
.terminal-tabs button:hover{background:transparent;color:#dff9f2}
|
||||||
|
.terminal-tabs button[aria-pressed=true]{background:transparent;border-color:var(--signal);color:#e6f1ef}
|
||||||
|
.terminal-tabs span{font:10px var(--mono);color:#a9c5c8;margin-left:4px}
|
||||||
|
.terminal-toolbar{padding:17px 42px;border:0;background:transparent;color:#a9c5c8;font:11px var(--mono)}
|
||||||
|
.text-button{min-height:25px;padding:0;border:0;border-bottom:1px solid #d6f0ed81;border-radius:0;background:transparent;font:11px var(--mono);color:#e6f1ef}
|
||||||
|
.text-button:hover{background:transparent;border-color:#dff9f2}
|
||||||
|
.terminal-body{padding:21px 42px 34px;background:transparent;scrollbar-color:#718e95 #0b1b24}
|
||||||
|
.terminal-footer{display:none}
|
||||||
|
.section-heading{margin:0 0 18px;min-height:30px}
|
||||||
|
.section-heading .eyebrow{font:11px var(--mono)}
|
||||||
|
.section-heading .button{min-height:27px;padding:0;border:0;border-bottom:1px solid #d6f0eda3;border-radius:0;background:transparent;color:#e6f1ef;font:12px var(--sans)}
|
||||||
|
.section-heading .button:hover{background:transparent;color:#dff9f2;border-color:#dff9f2}
|
||||||
|
.search{display:flex;align-items:center;gap:5px;border:0;border-bottom:1px solid #d6f0ed6d;background:transparent}
|
||||||
|
.search>span{font-size:22px;color:#a9c5c8}.search input{padding:9px 2px;font:13px var(--sans);background:transparent;border:0;outline-offset:1px}
|
||||||
|
.plot-list{max-height:235px;margin-top:13px}
|
||||||
|
.plot-card{border:0;border-bottom:1px solid #d6f0ed42;border-radius:0;padding:14px 4px;background:transparent}
|
||||||
|
.plot-card:hover{background:transparent;color:#dff9f2}
|
||||||
|
.plot-card[aria-pressed=true]{background:transparent;border:0;border-bottom:1px solid #d6f0ed42;border-left:0;padding-left:4px;color:var(--signal);box-shadow:none}
|
||||||
|
.plot-card[aria-pressed=true] .arrow{color:var(--signal)}
|
||||||
|
.plot-card strong{font:500 15px var(--sans)}.plot-card small{font:11px var(--sans);color:#a9c5c8;margin-top:3px}
|
||||||
|
.plant-icon{font-size:10px;color:#c7dddb}.arrow{font:16px var(--sans)}
|
||||||
|
.section-divider{border-top:1px solid #d6f0ed50;margin:29px 0 17px;padding-top:18px;font:11px var(--mono);color:#a9c5c8}
|
||||||
|
#plot-detail h3{font:400 24px var(--sans);letter-spacing:-.025em;margin:14px 0 19px}
|
||||||
|
dt{font:11px var(--mono);color:#a9c5c8}dd{font:14px/1.65 var(--sans)}
|
||||||
|
.record{border-color:#d6f0ed42}.record strong{font:13px var(--sans)}.record-value{font:13px var(--mono)}
|
||||||
|
.empty{font:13px/1.6 var(--sans);color:#a9c5c8}
|
||||||
|
.pill{font:11px var(--mono);color:#a9c5c8}
|
||||||
|
#key-form .button{border:1px solid #d6f0ed66;padding:7px 14px;background:#d6f0ed37;color:#e6f1ef}
|
||||||
|
|
||||||
|
.operator-console{width:600px;resize:none;z-index:15;display:flex;flex-direction:column}
|
||||||
|
.console-titlebar{display:flex;align-items:flex-start;gap:17px;padding:44px 42px 22px;border:0;background:transparent}
|
||||||
|
.console-titlebar h2{margin:0;font:400 30px/1.2 var(--sans);letter-spacing:-.04em}
|
||||||
|
.console-titlebar #console-state{margin-top:11px;font:11px var(--mono);color:#a9c5c8}
|
||||||
|
.console-titlebar .close{margin-left:auto}
|
||||||
|
.console-tools{gap:25px;padding:6px 42px 20px;background:transparent;border-bottom:1px solid #d6f0ed44}
|
||||||
|
.console-tools button{min-height:26px;padding:0;border:0;border-bottom:1px solid transparent;border-radius:0;background:transparent;font:12px var(--sans);color:#a9c5c8}
|
||||||
|
.console-tools button:hover{background:transparent;border-color:#a9c5c8;color:#dff9f2}
|
||||||
|
.console-tools button:last-child{margin-left:auto}
|
||||||
|
.console-output{flex:1;padding:24px 42px;background:transparent;color:#e6f1ef;font:13px/1.7 var(--mono)}
|
||||||
|
.console-system{color:#a9c5c8}.console-command{color:#e6f1ef}
|
||||||
|
.console-error{border:0;background:#213642;color:#ffc4a0;padding:9px 42px}
|
||||||
|
#console-form{padding:16px 42px 7px;background:#0b1b24;border-top:1px solid #d6f0ed44}
|
||||||
|
#console-form label{font:11px var(--mono);color:#a9c5c8}
|
||||||
|
.console-input-row{gap:11px;border-bottom:1px solid #d6f0ed93}
|
||||||
|
.console-input-row>span{font:18px var(--mono);color:var(--signal)}
|
||||||
|
.console-input-row input{background:transparent;border:0;padding:11px 0;font:14px var(--mono)}
|
||||||
|
.console-input-row button{min-height:32px;padding:0;border:0;border-radius:0;background:transparent;font:12px var(--sans);color:var(--signal)}
|
||||||
|
.console-input-row button:hover{background:transparent;color:#dff9f2}
|
||||||
|
.console-footer{padding:10px 42px 21px;background:#0b1b24;font:10px var(--mono);color:#a9c5c8}
|
||||||
|
body.console-open .vitals,body.terminal-open .vitals{visibility:hidden}
|
||||||
|
|
||||||
|
dialog{border:1px solid #d6f0ed70;border-radius:0;padding:32px;background:#09202c;box-shadow:0 30px 80px #000b;font-family:var(--sans)}
|
||||||
|
dialog::backdrop{background:#02080bd1}
|
||||||
|
dialog h2{font:400 27px var(--sans);letter-spacing:-.025em}dialog p{font:13px/1.65 var(--sans)}
|
||||||
|
dialog input,dialog textarea,dialog select{background:#0b1b24}
|
||||||
|
dialog form>.button,.primary{background:var(--signal);border:1px solid var(--signal);color:#09202c;font:500 14px var(--sans);border-radius:0}
|
||||||
|
dialog form>.button:hover,.primary:hover:not(:disabled){background:#e6f1ef;border-color:#e6f1ef;color:#09202c}
|
||||||
|
.notice{top:28px;left:40px;border-radius:0;background:#213642}.toast{top:28px;border-radius:0;background:#e9f6f2;color:#09202c}
|
||||||
|
#object-hint{bottom:43px;border-radius:0;background:#213642}
|
||||||
|
#scene-loading,#scene-fallback{border-radius:0;background:#09202c}
|
||||||
|
|
||||||
|
:root{font-size:16px}
|
||||||
|
button,input,textarea,select,label{font-family:var(--sans)}
|
||||||
|
.vitals-heading,.vitals-heading strong,.vital-line,.vital-line strong,.vitals>small{font-size:16px;letter-spacing:0}
|
||||||
|
.vitals-heading{padding-bottom:20px}.vital-line{margin-top:8px}.vitals>small{margin-top:16px}
|
||||||
|
.command-dock button{font:22px var(--display);letter-spacing:0}
|
||||||
|
.dock-end,.command-dock small{font-size:16px}
|
||||||
|
.camera-controls button{font:24px var(--display)}.camera-controls #motion-toggle{font:16px var(--sans)}
|
||||||
|
.terminal{width:500px}.operator-console{width:620px}
|
||||||
|
.terminal-header .eyebrow,.eyebrow{font-size:16px;letter-spacing:0}
|
||||||
|
.terminal-header h2{font:33px/1.2 var(--display);letter-spacing:0}
|
||||||
|
.close{font:22px var(--display)}
|
||||||
|
.terminal-tabs button,.terminal-tabs span,.terminal-toolbar,.text-button{font-size:16px}
|
||||||
|
.section-heading .button,.search input,.section-divider,.plot-card strong,.plot-card small,#plot-detail h3,dt,dd,.record strong,.record-value,.empty,.pill,#key-form .button{font-size:16px}
|
||||||
|
#plot-detail h3{font:22px var(--display);letter-spacing:0}
|
||||||
|
.plot-card strong{font-family:var(--display)}
|
||||||
|
.console-titlebar h2{font:33px var(--display);letter-spacing:0}
|
||||||
|
.console-titlebar #console-state,.console-tools button,.console-output,#console-form label,.console-input-row input,.console-input-row button,.console-footer{font-size:16px}
|
||||||
|
.console-output{line-height:1.5}.console-input-row>span{font-size:24px}
|
||||||
|
dialog h2{font:33px var(--display);letter-spacing:0}dialog p,dialog form>.button{font-size:16px}
|
||||||
|
|
||||||
|
@media(max-width:900px){.vitals,.command-dock{left:24px}.terminal{width:430px}.operator-console{width:520px}.camera-controls{right:24px}}
|
||||||
|
@media(max-width:700px){
|
||||||
|
.vitals{left:16px;bottom:153px;width:calc(100% - 32px);padding:0;background:linear-gradient(90deg,#071017e8,transparent)}
|
||||||
|
.vitals-heading{padding:0 0 4px;font-size:9px}.vitals-heading strong{font-size:9px}
|
||||||
|
.vital-line{display:inline-flex;gap:5px;margin:8px 12px 0 0;font-size:9px}.vital-line strong{font-size:10px}.vitals>small{font-size:8px;margin-top:7px}
|
||||||
|
.command-dock{left:16px;right:16px;bottom:max(12px,env(safe-area-inset-bottom));width:auto;display:flex;gap:18px;min-height:0;padding:0;grid-template-columns:none}
|
||||||
|
.command-dock button{flex:1;width:auto;min-height:49px;padding:0 1px;font-size:17px;border-top:1px solid #d6f0ed60}
|
||||||
|
.command-dock button:last-child{border-bottom:0}.command-dock #console-launch{grid-column:auto}
|
||||||
|
.dock-end{font-size:14px;gap:7px}.command-dock small{font-size:9px}
|
||||||
|
.camera-controls{right:16px;bottom:95px;display:flex;gap:9px;max-width:none;background:transparent;flex-wrap:nowrap;justify-content:initial}
|
||||||
|
.camera-controls button{min-width:24px;min-height:31px;padding:0;font-size:17px}.camera-controls button:last-child{flex-basis:auto}.camera-controls #motion-toggle{font-size:11px;min-width:0;padding-left:11px}
|
||||||
|
.terminal,.operator-console{inset:0;width:100%;height:100svh;max-width:none;max-height:none;min-height:0;border-left:0}
|
||||||
|
.terminal-header{padding:27px 24px 14px}.terminal-header h2{font-size:31px}.terminal-tabs{padding:0 24px;gap:20px}.terminal-tabs button{font-size:13px;min-height:43px}
|
||||||
|
.terminal-toolbar{padding:12px 24px}.terminal-body{padding:17px 24px 30px}.plot-list{max-height:185px}
|
||||||
|
.operator-console{width:100%;resize:none}.console-titlebar{padding:27px 24px 17px}.console-titlebar h2{font-size:25px}
|
||||||
|
.console-tools{padding:7px 24px 16px;gap:13px}.console-tools button{font-size:11px}.console-output{padding:20px 24px;font-size:12px}
|
||||||
|
#console-form{padding:13px 24px 5px}.console-input-row input{font-size:16px;padding:9px 0}.console-footer{padding:9px 24px 17px;font-size:9px}
|
||||||
|
.notice{top:14px;left:16px}.toast{top:14px}#object-hint{bottom:114px}dialog{padding:22px}
|
||||||
|
}
|
||||||
|
@media(max-height:600px) and (min-width:701px){.vitals{bottom:218px}.terminal-header,.console-titlebar{padding-top:24px}}
|
||||||
|
@media(prefers-reduced-motion:reduce){.terminal,.operator-console{animation:none}}
|
||||||
|
@media(prefers-contrast:more),(prefers-reduced-transparency:reduce){.terminal,.operator-console,dialog{background:#0b1b24;backdrop-filter:none;-webkit-backdrop-filter:none}.vitals{background:#071017}}
|
||||||
|
@supports not (backdrop-filter:blur(1px)){.terminal,.operator-console{background:#0b1b24f5}}
|
||||||
|
|
||||||
|
:root{--ink:#edf8f5;--muted:#b7cece;--line:#e5ffff32;--surface:#0b2330a8;--signal:#d9f3e9}
|
||||||
|
button{color:var(--ink)}button:hover:not(:disabled),button[aria-pressed=true],button[aria-expanded=true]{color:#fff}
|
||||||
|
button:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible,[tabindex]:focus-visible{outline-color:#ecfffb}
|
||||||
|
input,textarea,select{background:#09212d8a;border-color:#dcfaf680;color:#effbf8}
|
||||||
|
input::placeholder,textarea::placeholder{color:#abc6c7}
|
||||||
|
.operator-rail{
|
||||||
|
position:absolute;z-index:6;left:24px;bottom:24px;width:330px;padding:24px 24px 17px;
|
||||||
|
border:1px solid #e1ffff30;border-radius:16px;
|
||||||
|
background:#1b2d365c;
|
||||||
|
box-shadow:0 20px 54px #0006,inset 0 1px 0 #ffffff25;
|
||||||
|
backdrop-filter:blur(28px) saturate(112%);-webkit-backdrop-filter:blur(28px) saturate(112%);
|
||||||
|
}
|
||||||
|
.operator-rail .vitals,.operator-rail .command-dock{position:relative;left:auto;right:auto;bottom:auto;width:auto;margin:0;background:transparent;border:0;box-shadow:none;backdrop-filter:none;-webkit-backdrop-filter:none}
|
||||||
|
.operator-rail .vitals{padding:0 0 22px}
|
||||||
|
.operator-rail .command-dock{display:block;padding:0}
|
||||||
|
body.terminal-open .operator-rail .vitals,body.console-open .operator-rail .vitals{visibility:visible}
|
||||||
|
.vitals-heading,.vital-line>span,.vitals>small{color:#c8dcda}.vitals-heading strong,.vital-line strong{color:#f2fffb}
|
||||||
|
.command-dock button{border-color:#d8f9f754;min-height:62px}.command-dock button:last-child{border-color:#d8f9f754}
|
||||||
|
.command-dock button:hover,.command-dock button[aria-expanded=true],.command-dock button[aria-expanded=true] .dock-label{color:#fff}
|
||||||
|
.dock-end,.command-dock small{color:#d7edeb}
|
||||||
|
#console-indicator{background:#91acac}#console-indicator.connected{background:#ddfff2;box-shadow:0 0 8px #b4eed9}
|
||||||
|
.camera-controls{
|
||||||
|
right:24px;bottom:24px;gap:11px;padding:5px 17px;
|
||||||
|
background:#1b2d3666;border:1px solid #e1ffff30;border-radius:12px;
|
||||||
|
box-shadow:0 14px 36px #0005,inset 0 1px 0 #ffffff20;
|
||||||
|
backdrop-filter:blur(22px) saturate(110%);-webkit-backdrop-filter:blur(22px) saturate(110%);
|
||||||
|
}
|
||||||
|
.camera-controls button{color:#e7f8f5;opacity:1}.camera-controls #motion-toggle{border-color:#dcf9f65c}
|
||||||
|
.terminal,.operator-console{
|
||||||
|
top:18px;right:18px;bottom:18px;height:auto;border:1px solid #e4ffff38;border-radius:16px;
|
||||||
|
background:#1b2e39a8;
|
||||||
|
box-shadow:0 26px 76px #0008,inset 0 1px 0 #ffffff27;
|
||||||
|
backdrop-filter:blur(30px) saturate(112%) brightness(.82);-webkit-backdrop-filter:blur(30px) saturate(112%) brightness(.82);
|
||||||
|
}
|
||||||
|
.terminal-header,.terminal-toolbar,.terminal-body,.console-titlebar,.console-tools,.console-output{background:transparent}
|
||||||
|
.terminal-header .eyebrow,.eyebrow,.terminal-toolbar,.section-divider,dt,.record small,.console-titlebar #console-state{color:#c4dcdb}
|
||||||
|
.terminal-header h2,#plot-detail h3,.console-titlebar h2{color:#f2fffb}
|
||||||
|
.terminal-tabs,.console-tools{border-color:#d8f9f744}
|
||||||
|
.terminal-tabs button{color:#c9dddd}.terminal-tabs button[aria-pressed=true]{border-color:#e1fff3;color:#fff}
|
||||||
|
.terminal-tabs span,.text-button,.section-heading .button{color:#e1f7f4}
|
||||||
|
.text-button,.section-heading .button,.search,.console-input-row{border-color:#d8f9f779}
|
||||||
|
.plot-card,.plot-card[aria-pressed=true],.record,.section-divider{border-color:#d8f9f741}
|
||||||
|
.plot-card[aria-pressed=true],.plot-card[aria-pressed=true] .arrow{color:#e8fff0}
|
||||||
|
.plot-card small,.empty,.pill{color:#bfd6d3}
|
||||||
|
.console-tools button{color:#d0e5e2}.console-output{color:#eefcf7}.console-system{color:#bcd9cf}.console-command{color:#e5f6d7}
|
||||||
|
#console-form,.console-footer{background:#071e2b72;border-color:#d8f9f741}
|
||||||
|
.console-input-row input{background:transparent;border:0}.console-input-row>span,.console-input-row button{color:#e7fff0}
|
||||||
|
.console-footer{color:#bdd6d3}
|
||||||
|
#key-form .button{background:#d8f5e124;border-color:#d8f5e16e;color:#f0fff6}
|
||||||
|
dialog{background:#1b2e39c9;border-color:#e4ffff48;border-radius:16px;backdrop-filter:blur(28px);-webkit-backdrop-filter:blur(28px)}
|
||||||
|
dialog input,dialog textarea,dialog select{background:#081f2bbb}
|
||||||
|
dialog form>.button,.primary{background:#e0f7ea;border-color:#e0f7ea;color:#12312b}
|
||||||
|
dialog form>.button:hover,.primary:hover:not(:disabled){background:#fff;border-color:#fff;color:#12312b}
|
||||||
|
.toast{background:#e8faf5;color:#11302b;border-color:#e8faf5;border-radius:16px}
|
||||||
|
.notice{background:#263c43d9;border-color:#dff5ed6b;border-radius:16px;color:#f0fff9}
|
||||||
|
#object-hint{background:#0a2b37ca;border-color:#e2f6e878;border-radius:14px;color:#f5fff3}
|
||||||
|
#scene-loading,#scene-fallback{background:#0b2936c9;border-color:#e4ffff71;border-radius:20px;backdrop-filter:blur(22px)}
|
||||||
|
@media(max-width:900px){.operator-rail{left:18px}.terminal{width:440px}.operator-console{width:540px}.camera-controls{right:18px}}
|
||||||
|
@media(max-width:700px){
|
||||||
|
.operator-rail{left:10px;right:10px;bottom:10px;width:auto;padding:13px 16px 9px;border-radius:14px}
|
||||||
|
.operator-rail .vitals{width:auto;padding:0 0 8px;background:transparent}
|
||||||
|
.operator-rail .command-dock{display:flex;gap:14px;width:auto}
|
||||||
|
.command-dock button{min-height:44px}.command-dock button:last-child{border-bottom:0}
|
||||||
|
.camera-controls{right:12px;bottom:150px;padding:2px 11px;border-radius:12px}
|
||||||
|
.terminal,.operator-console{inset:0;width:100%;height:100svh;max-width:none;max-height:none;border:0;border-radius:0}
|
||||||
|
}
|
||||||
|
@media(prefers-contrast:more),(prefers-reduced-transparency:reduce){
|
||||||
|
.operator-rail,.camera-controls,.terminal,.operator-console,dialog{background:#102a35f7;border-color:#e8fffa9c;backdrop-filter:none;-webkit-backdrop-filter:none}
|
||||||
|
.operator-rail::before{display:none}
|
||||||
|
}
|
||||||
|
@supports not (backdrop-filter:blur(1px)){.operator-rail,.camera-controls,.terminal,.operator-console,dialog{background:#102a35ef}}
|
||||||
|
|
||||||
|
.command-dock{
|
||||||
|
position:absolute;z-index:8;left:24px;right:auto;top:24px;bottom:auto;width:auto;min-height:0;
|
||||||
|
display:flex;gap:0;padding:3px 8px;
|
||||||
|
background:#1b2d3666;border:1px solid #e1ffff30;border-radius:12px;
|
||||||
|
box-shadow:0 14px 36px #0005,inset 0 1px 0 #ffffff20;
|
||||||
|
backdrop-filter:blur(22px) saturate(110%);-webkit-backdrop-filter:blur(22px) saturate(110%);
|
||||||
|
}
|
||||||
|
.command-dock button{width:auto;min-width:143px;min-height:46px;padding:0 13px;border:0;font-size:16px;gap:17px}
|
||||||
|
.command-dock button+button{border-left:1px solid #d8f9f73c}.command-dock button:last-child{border-bottom:0}
|
||||||
|
.command-dock .dock-end{gap:7px;font-size:13px}.command-dock small{font-size:12px}
|
||||||
|
.operator-rail{left:24px;bottom:24px;width:344px;padding:19px 21px}
|
||||||
|
.operator-rail .vitals{padding:0}
|
||||||
|
.camera-controls{top:24px;bottom:auto;right:24px}
|
||||||
|
.terminal,.operator-console{
|
||||||
|
position:absolute;top:87px;right:24px;bottom:auto;left:auto;
|
||||||
|
width:500px;height:min(680px,calc(100svh - 111px));max-height:calc(100svh - 48px);min-height:270px;
|
||||||
|
}
|
||||||
|
.operator-console{top:100px;right:auto;left:max(24px,calc(50% - 430px));width:540px;height:min(500px,calc(100svh - 140px));max-width:calc(100vw - 48px)}
|
||||||
|
.terminal-header,.console-titlebar{cursor:grab;touch-action:none;user-select:none}
|
||||||
|
.terminal-header:active,.console-titlebar:active{cursor:grabbing}
|
||||||
|
.terminal-header button,.console-titlebar button{cursor:pointer}
|
||||||
|
@media(max-width:900px){
|
||||||
|
.command-dock{left:18px;top:18px}.camera-controls{top:18px;right:18px}
|
||||||
|
.terminal{width:min(450px,calc(100vw - 36px));right:18px}
|
||||||
|
.operator-console{left:18px;width:min(540px,calc(100vw - 36px))}
|
||||||
|
}
|
||||||
|
@media(max-width:700px){
|
||||||
|
.command-dock{left:10px;right:auto;top:10px;bottom:auto;width:calc(100% - 115px);padding:1px 3px;gap:0;display:flex}
|
||||||
|
.command-dock button{flex:1;width:auto;min-width:0;min-height:40px;padding:0 6px;font-size:12px}
|
||||||
|
.command-dock button+button{border-left:1px solid #d8f9f73c}.command-dock .dock-end{font-size:11px;gap:2px}.command-dock small{font-size:10px}
|
||||||
|
.camera-controls{top:62px;right:10px;bottom:auto;padding:2px 9px}
|
||||||
|
.operator-rail{left:10px;right:10px;bottom:10px;width:auto;padding:13px 16px}
|
||||||
|
.terminal,.operator-console{inset:0;width:100%;height:100svh;max-width:none;max-height:none;min-height:0;border:0;border-radius:0}
|
||||||
|
.terminal-header,.console-titlebar{cursor:default;touch-action:auto}
|
||||||
|
}
|
||||||
|
@media(prefers-contrast:more),(prefers-reduced-transparency:reduce){.command-dock{background:#102a35f7;backdrop-filter:none;-webkit-backdrop-filter:none}}
|
||||||
|
@supports not (backdrop-filter:blur(1px)){.command-dock{background:#102a35ef}}
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
The MIT License
|
||||||
|
|
||||||
|
Copyright © 2010-2025 three.js authors
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
+1490
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,5 @@
|
|||||||
|
Three.js 0.180.0 (r180)
|
||||||
|
https://github.com/mrdoob/three.js
|
||||||
|
Source: https://registry.npmjs.org/three/-/three-0.180.0.tgz
|
||||||
|
Archive SHA256: ad66d724565ee29a2467277fa84daa5ed0211d6b8d446e9ef29f6bae0cd14144
|
||||||
|
License: MIT; see LICENSE. Unmodified distribution files.
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
/**
|
||||||
|
* @license
|
||||||
|
* Copyright 2010-2025 Three.js Authors
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
const t="180",e={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},s={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},i=0,r=1,n=2,a=3,o=0,h=1,l=2,c=3,u=0,d=1,p=2,m=0,y=1,g=2,f=3,x=4,b=5,v=100,w=101,M=102,S=103,_=104,A=200,T=201,z=202,C=203,I=204,B=205,k=206,E=207,R=208,P=209,O=210,N=211,V=212,F=213,L=214,j=0,D=1,W=2,U=3,H=4,q=5,J=6,X=7,Y=0,Z=1,G=2,$=0,Q=1,K=2,tt=3,et=4,st=5,it=6,rt=7,nt="attached",at="detached",ot=300,ht=301,lt=302,ct=303,ut=304,dt=306,pt=1e3,mt=1001,yt=1002,gt=1003,ft=1004,xt=1004,bt=1005,vt=1005,wt=1006,Mt=1007,St=1007,_t=1008,At=1008,Tt=1009,zt=1010,Ct=1011,It=1012,Bt=1013,kt=1014,Et=1015,Rt=1016,Pt=1017,Ot=1018,Nt=1020,Vt=35902,Ft=35899,Lt=1021,jt=1022,Dt=1023,Wt=1026,Ut=1027,Ht=1028,qt=1029,Jt=1030,Xt=1031,Yt=1032,Zt=1033,Gt=33776,$t=33777,Qt=33778,Kt=33779,te=35840,ee=35841,se=35842,ie=35843,re=36196,ne=37492,ae=37496,oe=37808,he=37809,le=37810,ce=37811,ue=37812,de=37813,pe=37814,me=37815,ye=37816,ge=37817,fe=37818,xe=37819,be=37820,ve=37821,we=36492,Me=36494,Se=36495,_e=36283,Ae=36284,Te=36285,ze=36286,Ce=2200,Ie=2201,Be=2202,ke=2300,Ee=2301,Re=2302,Pe=2400,Oe=2401,Ne=2402,Ve=2500,Fe=2501,Le=0,je=1,De=2,We=3200,Ue=3201,He=3202,qe=3203,Je=0,Xe=1,Ye="",Ze="srgb",Ge="srgb-linear",$e="linear",Qe="srgb",Ke=0,ts=7680,es=7681,ss=7682,is=7683,rs=34055,ns=34056,as=5386,os=512,hs=513,ls=514,cs=515,us=516,ds=517,ps=518,ms=519,ys=512,gs=513,fs=514,xs=515,bs=516,vs=517,ws=518,Ms=519,Ss=35044,_s=35048,As=35040,Ts=35045,zs=35049,Cs=35041,Is=35046,Bs=35050,ks=35042,Es="100",Rs="300 es",Ps=2e3,Os=2001,Ns={COMPUTE:"compute",RENDER:"render"},Vs={PERSPECTIVE:"perspective",LINEAR:"linear",FLAT:"flat"},Fs={NORMAL:"normal",CENTROID:"centroid",SAMPLE:"sample",FIRST:"first",EITHER:"either"};class Ls{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const s=this._listeners;void 0===s[t]&&(s[t]=[]),-1===s[t].indexOf(e)&&s[t].push(e)}hasEventListener(t,e){const s=this._listeners;return void 0!==s&&(void 0!==s[t]&&-1!==s[t].indexOf(e))}removeEventListener(t,e){const s=this._listeners;if(void 0===s)return;const i=s[t];if(void 0!==i){const t=i.indexOf(e);-1!==t&&i.splice(t,1)}}dispatchEvent(t){const e=this._listeners;if(void 0===e)return;const s=e[t.type];if(void 0!==s){t.target=this;const e=s.slice(0);for(let s=0,i=e.length;s<i;s++)e[s].call(this,t);t.target=null}}}const js=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let Ds=1234567;const Ws=Math.PI/180,Us=180/Math.PI;function Hs(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(js[255&t]+js[t>>8&255]+js[t>>16&255]+js[t>>24&255]+"-"+js[255&e]+js[e>>8&255]+"-"+js[e>>16&15|64]+js[e>>24&255]+"-"+js[63&s|128]+js[s>>8&255]+"-"+js[s>>16&255]+js[s>>24&255]+js[255&i]+js[i>>8&255]+js[i>>16&255]+js[i>>24&255]).toLowerCase()}function qs(t,e,s){return Math.max(e,Math.min(s,t))}function Js(t,e){return(t%e+e)%e}function Xs(t,e,s){return(1-s)*t+s*e}function Ys(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function Zs(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}const Gs={DEG2RAD:Ws,RAD2DEG:Us,generateUUID:Hs,clamp:qs,euclideanModulo:Js,mapLinear:function(t,e,s,i,r){rLine truncated
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
/**
|
||||||
|
* @license
|
||||||
|
* Copyright 2010-2025 Three.js Authors
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
import{Matrix3 as e,Vector2 as t,Color as n,mergeUniforms as r,Vector3 as i,CubeUVReflectionMapping as a,Mesh as o,BoxGeometry as s,ShaderMaterial as l,BackSide as c,cloneUniforms as d,Euler as u,Matrix4 as f,ColorManagement as p,SRGBTransfer as m,PlaneGeometry as h,FrontSide as _,getUnlitUniformColorSpace as g,IntType as v,HalfFloatType as E,UnsignedByteType as S,FloatType as T,RGBAFormat as M,Plane as x,EquirectangularReflectionMapping as R,EquirectangularRefractionMapping as A,WebGLCubeRenderTarget as b,CubeReflectionMapping as C,CubeRefractionMapping as L,OrthographicCamera as P,PerspectiveCamera as U,NoToneMapping as D,MeshBasicMaterial as w,NoBlending as I,WebGLRenderTarget as y,BufferGeometry as N,BufferAttribute as O,LinearSRGBColorSpace as F,LinearFilter as B,warnOnce as H,Uint32BufferAttribute as G,Uint16BufferAttribute as V,arrayNeedsUint32 as z,Vector4 as k,DataArrayTexture as W,CubeTexture as X,Data3DTexture as Y,LessEqualCompare as K,DepthTexture as q,Texture as j,GLSL3 as Z,PCFShadowMap as $,PCFSoftShadowMap as Q,VSMShadowMap as J,CustomToneMapping as ee,NeutralToneMapping as te,AgXToneMapping as ne,ACESFilmicToneMapping as re,CineonToneMapping as ie,ReinhardToneMapping as ae,LinearToneMapping as oe,LinearTransfer as se,AddOperation as le,MixOperation as ce,MultiplyOperation as de,UniformsUtils as ue,DoubleSide as fe,NormalBlending as pe,TangentSpaceNormalMap as me,ObjectSpaceNormalMap as he,Layers as _e,Frustum as ge,MeshDepthMaterial as ve,RGBADepthPacking as Ee,MeshDistanceMaterial as Se,NearestFilter as Te,LessEqualDepth as Me,ReverseSubtractEquation as xe,SubtractEquation as Re,AddEquation as Ae,OneMinusConstantAlphaFactor as be,ConstantAlphaFactor as Ce,OneMinusConstantColorFactor as Le,ConstantColorFactor as Pe,OneMinusDstAlphaFactor as Ue,OneMinusDstColorFactor as De,OneMinusSrcAlphaFactor as we,OneMinusSrcColorFactor as Ie,DstAlphaFactor as ye,DstColorFactor as Ne,SrcAlphaSaturateFactor as Oe,SrcAlphaFactor as Fe,SrcColorFactor as Be,OneFactor as He,ZeroFactor as Ge,NotEqualDepth as Ve,GreaterDepth as ze,GreaterEqualDepth as ke,EqualDepth as We,LessDepth as Xe,AlwaysDepth as Ye,NeverDepth as Ke,CullFaceNone as qe,CullFaceBack as je,CullFaceFront as Ze,CustomBlending as $e,MultiplyBlending as Qe,SubtractiveBlending as Je,AdditiveBlending as et,MinEquation as tt,MaxEquation as nt,MirroredRepeatWrapping as rt,ClampToEdgeWrapping as it,RepeatWrapping as at,LinearMipmapLinearFilter as ot,LinearMipmapNearestFilter as st,NearestMipmapLinearFilter as lt,NearestMipmapNearestFilter as ct,NotEqualCompare as dt,GreaterCompare as ut,GreaterEqualCompare as ft,EqualCompare as pt,LessCompare as mt,AlwaysCompare as ht,NeverCompare as _t,NoColorSpace as gt,DepthStencilFormat as vt,getByteLength as Et,DepthFormat as St,UnsignedIntType as Tt,UnsignedInt248Type as Mt,UnsignedShortType as xt,createElementNS as Rt,UnsignedShort4444Type as At,UnsignedShort5551Type as bt,UnsignedInt5999Type as Ct,UnsignedInt101111Type as Lt,ByteType as Pt,ShortType as Ut,AlphaFormat as Dt,RGBFormat as wt,RedFormat as It,RedIntegerFormat as yt,RGFormat as Nt,RGIntegerFormat as Ot,RGBAIntegerFormat as Ft,RGB_S3TC_DXT1_Format as Bt,RGBA_S3TC_DXT1_Format as Ht,RGBA_S3TC_DXT3_Format as Gt,RGBA_S3TC_DXT5_Format as Vt,RGB_PVRTC_4BPPV1_Format as zt,RGB_PVRTC_2BPPV1_Format as kt,RGBA_PVRTC_4BPPV1_Format as Wt,RGBA_PVRTC_2BPPV1_Format as Xt,RGB_ETC1_Format as Yt,RGB_ETC2_Format as Kt,RGBA_ETC2_EAC_Format as qt,RGBA_ASTC_4x4_Format as jt,RGBA_ASTC_5x4_Format as Zt,RGBA_ASTC_5x5_Format as $t,RGBA_ASTC_6x5_Format as Qt,RGBA_ASTC_6x6_Format as Jt,RGBA_ASTC_8x5_Format as en,RGBA_ASTC_8x6_Format as tn,RGBA_ASTC_8x8_Format as nn,RGBA_ASTC_10x5_Format as rn,RGBA_ASTC_10x6_Format as an,RGBA_ASTC_10x8_Format as on,RGBA_ASTC_10x10_Format as sn,RGBA_ASTC_12x10_Format as ln,RGBA_ASTC_12x12_Format as cn,RGBA_BPTC_Format as dn,RGB_BPTC_SIGNED_Format as un,RGB_BPTC_UNSIGNED_Format as fn,RED_RGTC1_Format as pn,SIGNED_RED_RGTC1_Format as mn,RED_GREEN_RGTC2_Format as hn,SIGNED_RED_GREEN_RGTC2_Format as _n,ExternalTexture as gn,EventDispatcher as vn,ArrayCamera as En,WebXRController as Sn,RAD2DEG as Tn,createCanvasElement as Mn,SRGBColorSpace as xn,REVISION as Rn,WebGLCoordinateSystem as An,probeAsync as bn}from"./three.core.min.js";export{AdditiveAnimationBlendMode,AlwaysStencilFunc,AmbientLight,AnimationAction,AnimationClip,AnimationLoader,AnimationMixer,AnimationObjectGroup,AnimationUtils,ArcCurve,ArrowHelper,AttachedBindMode,Audio,AudioAnalyser,AudioContext,AudioListener,AudioLoader,AxesHelper,BasicDepthPacking,BasicShadowMap,BatchedMesh,Bone,BooleanKeyframeTrack,Box2,Box3,Box3Helper,BoxHelper,BufferGeometryLoader,Cache,Camera,CameraHelper,CanvasTexture,CapsuleGeometry,CatmullRomCurve3,CircleGeometry,Clock,ColorKeyframeTrack,CompressedArrayTexture,CompressedCubeTexture,CompressedTexture,CompressedTextureLoader,ConeGeometry,Controls,CubeCamera,CubeTextureLoader,CubicBezierCurve,CubicBezierCurve3,CubicInterpolant,CullFaceFrontBack,Curve,CurvePath,CyliLine truncated
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
(() => {
|
||||||
|
let front = 30;
|
||||||
|
const margin = 12;
|
||||||
|
const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
|
||||||
|
|
||||||
|
for (const [panelSelector, handleSelector] of [
|
||||||
|
['#terminal', '.terminal-header'],
|
||||||
|
['#operator-console', '.console-titlebar'],
|
||||||
|
]) {
|
||||||
|
const panel = document.querySelector(panelSelector);
|
||||||
|
const handle = panel.querySelector(handleSelector);
|
||||||
|
let drag = null;
|
||||||
|
|
||||||
|
function bringFront() { panel.style.zIndex = String(++front); }
|
||||||
|
panel.addEventListener('greenhouse:raise', bringFront);
|
||||||
|
function place(x, y, width, height) {
|
||||||
|
panel.style.width = `${width}px`;
|
||||||
|
panel.style.height = `${height}px`;
|
||||||
|
panel.style.left = `${clamp(x, margin, Math.max(margin, innerWidth - width - margin))}px`;
|
||||||
|
panel.style.top = `${clamp(y, margin, Math.max(margin, innerHeight - height - margin))}px`;
|
||||||
|
panel.style.right = 'auto';
|
||||||
|
panel.style.bottom = 'auto';
|
||||||
|
}
|
||||||
|
|
||||||
|
panel.addEventListener('pointerdown', bringFront);
|
||||||
|
handle.addEventListener('pointerdown', event => {
|
||||||
|
if (innerWidth <= 700 || event.button !== 0 || event.target.closest('button, input, a, select, textarea')) return;
|
||||||
|
const rect = panel.getBoundingClientRect();
|
||||||
|
bringFront();
|
||||||
|
drag = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, left: rect.left, top: rect.top, width: rect.width, height: rect.height };
|
||||||
|
handle.setPointerCapture(event.pointerId);
|
||||||
|
handle.focus({ preventScroll: true });
|
||||||
|
event.preventDefault();
|
||||||
|
});
|
||||||
|
handle.addEventListener('pointermove', event => {
|
||||||
|
if (!drag || event.pointerId !== drag.pointerId) return;
|
||||||
|
place(drag.left + event.clientX - drag.x, drag.top + event.clientY - drag.y, drag.width, drag.height);
|
||||||
|
});
|
||||||
|
function stop(event) {
|
||||||
|
if (drag && event.pointerId === drag.pointerId) drag = null;
|
||||||
|
}
|
||||||
|
handle.addEventListener('pointerup', stop);
|
||||||
|
handle.addEventListener('pointercancel', stop);
|
||||||
|
handle.addEventListener('lostpointercapture', stop);
|
||||||
|
handle.addEventListener('keydown', event => {
|
||||||
|
if (!event.altKey || innerWidth <= 700) return;
|
||||||
|
if (event.key === 'Home') {
|
||||||
|
for (const property of ['left', 'top', 'right', 'bottom', 'width', 'height']) panel.style[property] = '';
|
||||||
|
bringFront(); event.preventDefault(); return;
|
||||||
|
}
|
||||||
|
const move = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[event.key];
|
||||||
|
if (!move) return;
|
||||||
|
const rect = panel.getBoundingClientRect();
|
||||||
|
const step = event.shiftKey ? 48 : 16;
|
||||||
|
place(rect.left + move[0] * step, rect.top + move[1] * step, rect.width, rect.height);
|
||||||
|
bringFront(); event.preventDefault();
|
||||||
|
});
|
||||||
|
addEventListener('resize', () => {
|
||||||
|
if (!panel.style.left || innerWidth <= 700) {
|
||||||
|
if (innerWidth <= 700) for (const property of ['left', 'top', 'right', 'bottom', 'width', 'height']) panel.style[property] = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const rect = panel.getBoundingClientRect();
|
||||||
|
place(rect.left, rect.top, rect.width, rect.height);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})();
|
||||||
Executable
BIN
Binary file not shown.
@@ -0,0 +1,19 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
python3 -c 'from pathlib import Path; Path("/data/console.sock").unlink(missing_ok=True)'
|
||||||
|
/greenhouse/greenhouse-console &
|
||||||
|
console_pid=$!
|
||||||
|
attempt=0
|
||||||
|
while [ ! -S /data/console.sock ]; do
|
||||||
|
if ! kill -0 "$console_pid" 2>/dev/null; then
|
||||||
|
echo 'specimen console failed to start' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
attempt=$((attempt + 1))
|
||||||
|
if [ "$attempt" -ge 50 ]; then
|
||||||
|
echo 'specimen console socket not ready' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
sleep 0.1
|
||||||
|
done
|
||||||
|
exec python3 /greenhouse/app/server.py
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
client/node_modules
|
||||||
|
client/dist
|
||||||
|
**/__pycache__
|
||||||
|
**/*.pyc
|
||||||
Whitespace-only changes.
@@ -0,0 +1,35 @@
|
|||||||
|
FROM node:22-bookworm AS web
|
||||||
|
WORKDIR /web
|
||||||
|
COPY client/package.json ./
|
||||||
|
RUN npm install
|
||||||
|
COPY client/index.html ./index.html
|
||||||
|
COPY client/src/ ./src/
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
FROM debian:bookworm-slim AS wasmtime
|
||||||
|
ARG WASMTIME_VERSION=24.0.0
|
||||||
|
ARG TARGETARCH
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl xz-utils && rm -rf /var/lib/apt/lists/* \
|
||||||
|
&& case "$TARGETARCH" in amd64) WASMTIME_ARCH=x86_64 ;; arm64) WASMTIME_ARCH=aarch64 ;; *) echo "Unsupported architecture: $TARGETARCH" >&2; exit 1 ;; esac \
|
||||||
|
&& curl -fsSL "https://github.com/bytecodealliance/wasmtime/releases/download/v${WASMTIME_VERSION}/wasmtime-v${WASMTIME_VERSION}-${WASMTIME_ARCH}-linux-c-api.tar.xz" -o /tmp/wasmtime.tar.xz \
|
||||||
|
&& tar -xJf /tmp/wasmtime.tar.xz -C /tmp \
|
||||||
|
&& mkdir -p /out/include /out/lib \
|
||||||
|
&& cp -a /tmp/wasmtime-v${WASMTIME_VERSION}-${WASMTIME_ARCH}-linux-c-api/include/. /out/include/ \
|
||||||
|
&& cp -a /tmp/wasmtime-v${WASMTIME_VERSION}-${WASMTIME_ARCH}-linux-c-api/lib/libwasmtime.so* /out/lib/
|
||||||
|
|
||||||
|
FROM debian:bookworm-slim
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends cmake make g++ clang llvm lld libcpp-httplib-dev libsqlite3-dev nlohmann-json3-dev sqlite3 util-linux \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
COPY --from=wasmtime /out/include/ /usr/local/include/
|
||||||
|
COPY --from=wasmtime /out/lib/ /usr/local/lib/
|
||||||
|
RUN ldconfig
|
||||||
|
WORKDIR /srv/lighthouse
|
||||||
|
COPY server/ ./server/
|
||||||
|
RUN /bin/sh ./server/build.sh
|
||||||
|
COPY --from=web /web/dist ./public/
|
||||||
|
RUN mkdir -p /data /var/log/lighthouse /srv/lighthouse/work \
|
||||||
|
&& chmod 0700 /data \
|
||||||
|
&& chmod 0755 /var/log/lighthouse \
|
||||||
|
&& chmod 0711 /srv/lighthouse/work
|
||||||
|
EXPOSE 8080
|
||||||
|
CMD ["/srv/lighthouse/server/lighthouse"]
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Lighthouse</title></head>
|
||||||
|
<body><div id="app"></div><script type="module" src="/src/main.js"></script></body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"scripts":{"build":"vite build","dev":"vite --host 0.0.0.0"},"dependencies":{"@vitejs/plugin-vue":"latest","vite":"latest","vue":"latest"}}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
const unbytes = new TextDecoder();
|
||||||
|
|
||||||
|
function g(a, b, carry) {
|
||||||
|
const value = (a + b + carry) & 255;
|
||||||
|
return ((value << 2) | (value >>> 6)) & 255;
|
||||||
|
}
|
||||||
|
|
||||||
|
function f(x) {
|
||||||
|
const a = x >>> 24, b = (x >>> 16) & 255, c = (x >>> 8) & 255, d = x & 255;
|
||||||
|
const y1 = g(a ^ b, c ^ d, 1);
|
||||||
|
const y2 = g(c ^ d, y1, 0);
|
||||||
|
return (g(a, y1, 0) << 24 | y1 << 16 | y2 << 8 | g(d, y2, 1)) >>> 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function fk(x, y) {
|
||||||
|
const a = x >>> 24, b = (x >>> 16) & 255, c = (x >>> 8) & 255, d = x & 255;
|
||||||
|
const u = y >>> 24, v = (y >>> 16) & 255, w = (y >>> 8) & 255, z = y & 255;
|
||||||
|
const middle1 = g(a ^ b, (c ^ d) ^ u, 1);
|
||||||
|
const middle2 = g(c ^ d, middle1 ^ v, 0);
|
||||||
|
return (g(a, middle1 ^ w, 0) << 24 | middle1 << 16 | middle2 << 8 | g(d, middle2 ^ z, 1)) >>> 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function block(left, right, keys) {
|
||||||
|
let x = left, y = (right ^ left) >>> 0;
|
||||||
|
for (let round = 3; round >= 1; round--) {
|
||||||
|
const next = (x ^ f(y ^ keys[round])) >>> 0;
|
||||||
|
x = y;
|
||||||
|
y = next;
|
||||||
|
}
|
||||||
|
const initial = (x ^ f(y ^ keys[0])) >>> 0;
|
||||||
|
return [(initial ^ keys[4]) >>> 0, (initial ^ y ^ keys[5]) >>> 0];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decrypt(secret, cipher) {
|
||||||
|
if (!/^[0-9a-f]+$/.test(cipher) || cipher.length % 16 || !/^[0-9a-f]{48}$/.test(secret))
|
||||||
|
throw Error('Invalid message');
|
||||||
|
const material = Array.from({ length: 6 }, (_, i) => parseInt(secret.slice(i * 8, i * 8 + 8), 16) >>> 0);
|
||||||
|
let left = material[0], right = material[1], previous = material[5];
|
||||||
|
const words = [];
|
||||||
|
for (let i = 0; i < 6; i++) {
|
||||||
|
const next = fk(left, (right ^ previous ^ material[i]) >>> 0);
|
||||||
|
previous = left;
|
||||||
|
left = right;
|
||||||
|
right = next;
|
||||||
|
words.push(next >>> 16, next & 65535);
|
||||||
|
}
|
||||||
|
const outputLeft = ((words[8] << 16 | words[9]) ^ material[2]) >>> 0;
|
||||||
|
const outputRight = ((words[10] << 16 | words[11]) ^ material[3]) >>> 0;
|
||||||
|
const keys = Array.from({ length: 4 }, (_, i) =>
|
||||||
|
(((words[i] >>> 8) << 16 | (words[i] & 255) << 8) ^ outputLeft ^
|
||||||
|
(i % 2 ? outputRight : 0) ^ material[i]) >>> 0);
|
||||||
|
keys.push(((words[4] << 16 | words[5]) ^ outputLeft ^ outputRight ^ material[4]) >>> 0,
|
||||||
|
((words[6] << 16 | words[7]) ^ outputRight ^ material[5]) >>> 0);
|
||||||
|
const output = new Uint8Array(cipher.length / 2);
|
||||||
|
for (let offset = 0; offset < output.length; offset += 8) {
|
||||||
|
const [left, right] = block(
|
||||||
|
parseInt(cipher.slice(offset * 2, offset * 2 + 8), 16) >>> 0,
|
||||||
|
parseInt(cipher.slice(offset * 2 + 8, offset * 2 + 16), 16) >>> 0, keys
|
||||||
|
);
|
||||||
|
for (let i = 0; i < 4; i++) {
|
||||||
|
output[offset + i] = left >>> (24 - 8 * i);
|
||||||
|
output[offset + 4 + i] = right >>> (24 - 8 * i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const padding = output[output.length - 1];
|
||||||
|
if (padding < 1 || padding > 8 || !output.slice(-padding).every(byte => byte === padding))
|
||||||
|
throw Error('Invalid message padding');
|
||||||
|
return unbytes.decode(output.slice(0, -padding));
|
||||||
|
}
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
import { createApp, ref } from 'vue/dist/vue.esm-bundler.js';
|
||||||
|
import { decrypt } from './crypto.js';
|
||||||
|
import './style.css';
|
||||||
|
|
||||||
|
const textBytes = new TextEncoder();
|
||||||
|
|
||||||
|
createApp({
|
||||||
|
setup() {
|
||||||
|
const queue = ref(''), key = ref(''), pass = ref(''), recipient = ref('');
|
||||||
|
const queueLabel = ref('untitled'), retention = ref(3600);
|
||||||
|
const topic = ref('inbox'), delay = ref(0), text = ref('');
|
||||||
|
const source = ref('int filter(int length) {\n return length <= 4096;\n}');
|
||||||
|
const filterLabel = ref('unnamed'), revision = ref('');
|
||||||
|
const selectedFilter = ref(null);
|
||||||
|
const received = ref([]), filters = ref([]);
|
||||||
|
const state = ref(null), view = ref('messages'), showRead = ref(false);
|
||||||
|
const feedback = ref({}), compiler = ref(''), listing = ref('');
|
||||||
|
const path = suffix => '/api/queues/' + queue.value + suffix;
|
||||||
|
const credentials = () => queue.value + ':' + key.value;
|
||||||
|
|
||||||
|
async function api(url, options = {}, accepted = []) {
|
||||||
|
const response = await fetch(url, {
|
||||||
|
...options,
|
||||||
|
headers: { 'Content-Type': 'application/json', ...options.headers }
|
||||||
|
});
|
||||||
|
const body = await response.json();
|
||||||
|
if (!response.ok && !accepted.includes(response.status)) throw Error(body.error || body.compiler || 'Request failed');
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function action(name, work) {
|
||||||
|
feedback.value[name] = null;
|
||||||
|
try {
|
||||||
|
const result = await work();
|
||||||
|
feedback.value[name] = typeof result === 'string' ? { kind: 'ok', text: result } : result;
|
||||||
|
}
|
||||||
|
catch (problem) { feedback.value[name] = { kind: 'error', text: problem.message }; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refresh() {
|
||||||
|
state.value = await api(path(''));
|
||||||
|
}
|
||||||
|
const headers = () => ({ 'X-Queue-Key': key.value });
|
||||||
|
|
||||||
|
const create = () => action('access', async () => {
|
||||||
|
const created = await api('/api/queues', {
|
||||||
|
method: 'POST', body: JSON.stringify({ label: queueLabel.value, retention_seconds: Number(retention.value) })
|
||||||
|
});
|
||||||
|
queue.value = created.id;
|
||||||
|
key.value = created.read_key;
|
||||||
|
pass.value = credentials();
|
||||||
|
state.value = created;
|
||||||
|
recipient.value = created.id;
|
||||||
|
received.value = [];
|
||||||
|
filters.value = [];
|
||||||
|
selectedFilter.value = null;
|
||||||
|
view.value = 'messages';
|
||||||
|
return 'Mailbox created. Save your access pass.';
|
||||||
|
});
|
||||||
|
const open = () => action('open', async () => {
|
||||||
|
const [id, secret, extra] = pass.value.trim().split(':');
|
||||||
|
if (!id || !secret || extra) throw Error('Enter a mailbox access pass in the form UUID:read_key.');
|
||||||
|
const info = await api('/api/queues/' + id);
|
||||||
|
await api('/api/queues/' + id + '/messages?show_read=true', { headers: { 'X-Queue-Key': secret } });
|
||||||
|
queue.value = id;
|
||||||
|
key.value = secret;
|
||||||
|
state.value = info;
|
||||||
|
recipient.value = id;
|
||||||
|
received.value = [];
|
||||||
|
filters.value = [];
|
||||||
|
selectedFilter.value = null;
|
||||||
|
view.value = 'messages';
|
||||||
|
feedback.value.access = { kind: 'ok', text: 'Mailbox opened.' };
|
||||||
|
});
|
||||||
|
const leave = () => {
|
||||||
|
queue.value = '';
|
||||||
|
key.value = '';
|
||||||
|
pass.value = '';
|
||||||
|
state.value = null;
|
||||||
|
received.value = [];
|
||||||
|
filters.value = [];
|
||||||
|
selectedFilter.value = null;
|
||||||
|
compiler.value = '';
|
||||||
|
listing.value = '';
|
||||||
|
feedback.value = {};
|
||||||
|
feedback.value.open = { kind: 'ok', text: 'Mailbox closed.' };
|
||||||
|
};
|
||||||
|
const send = () => action('send', async () => {
|
||||||
|
const id = recipient.value.trim();
|
||||||
|
if (!text.value) throw Error('Write a message first.');
|
||||||
|
const raw = textBytes.encode(text.value);
|
||||||
|
if (raw.length > 4096) throw Error('Messages must be at most 4096 bytes.');
|
||||||
|
await api('/api/queues/' + id + '/messages', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({
|
||||||
|
message: btoa(Array.from(raw, byte => String.fromCharCode(byte)).join('')),
|
||||||
|
topic: topic.value,
|
||||||
|
delay_ms: Number(delay.value)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
text.value = '';
|
||||||
|
if (state.value) await refresh();
|
||||||
|
return 'Message sent.';
|
||||||
|
});
|
||||||
|
const receive = () => action('receive', async () => {
|
||||||
|
await refresh();
|
||||||
|
const result = await api(path('/messages' + (showRead.value ? '?show_read=true' : '')), { headers: headers() });
|
||||||
|
received.value = result.messages.map(message => {
|
||||||
|
try {
|
||||||
|
return { id: message.id, topic: message.topic, text: decrypt(key.value, message.ciphertext) };
|
||||||
|
} catch {
|
||||||
|
return { id: message.id, topic: message.topic, text: 'Cannot open this message.' };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await refresh();
|
||||||
|
return result.messages.length ? result.messages.length + ' message(s) displayed.' : 'No messages to display.';
|
||||||
|
});
|
||||||
|
const loadFilters = () => action('refreshFilters', async () => {
|
||||||
|
filters.value = (await api(path('/filters'))).filters;
|
||||||
|
return 'Revision list updated.';
|
||||||
|
});
|
||||||
|
const selectFilter = filter => action('selectFilter', async () => {
|
||||||
|
const details = await api(path('/filters/' + filter.revision), { headers: headers() });
|
||||||
|
revision.value = details.revision;
|
||||||
|
selectedFilter.value = details;
|
||||||
|
return 'Revision #' + details.revision + ' selected.';
|
||||||
|
});
|
||||||
|
const newDraft = () => {
|
||||||
|
selectedFilter.value = null;
|
||||||
|
revision.value = '';
|
||||||
|
compiler.value = '';
|
||||||
|
listing.value = '';
|
||||||
|
feedback.value.compile = null;
|
||||||
|
feedback.value.selectFilter = { kind: 'ok', text: 'Draft editor ready.' };
|
||||||
|
};
|
||||||
|
const install = () => action('compile', async () => {
|
||||||
|
compiler.value = '';
|
||||||
|
listing.value = '';
|
||||||
|
const result = await api(path('/filter'), {
|
||||||
|
method: 'POST', body: JSON.stringify({ source: source.value, label: filterLabel.value })
|
||||||
|
}, [422]);
|
||||||
|
compiler.value = result.compiler || '';
|
||||||
|
listing.value = result.listing || '';
|
||||||
|
filters.value = (await api(path('/filters'))).filters;
|
||||||
|
if (!result.ok) {
|
||||||
|
return { kind: 'error', text: 'Revision #' + result.revision + ' rejected. See compiler output below.' };
|
||||||
|
}
|
||||||
|
return 'Revision #' + result.revision + ' ready. Select it to activate.';
|
||||||
|
});
|
||||||
|
const draftFrom = () => {
|
||||||
|
if (!selectedFilter.value?.source) return;
|
||||||
|
source.value = selectedFilter.value.source;
|
||||||
|
filterLabel.value = selectedFilter.value.label;
|
||||||
|
newDraft();
|
||||||
|
};
|
||||||
|
const activate = () => action('activate', async () => {
|
||||||
|
await api(path('/filters/' + revision.value + '/activate'), {
|
||||||
|
method: 'POST', headers: headers()
|
||||||
|
});
|
||||||
|
filters.value = (await api(path('/filters'))).filters;
|
||||||
|
if (selectedFilter.value) selectedFilter.value.active = true;
|
||||||
|
await refresh();
|
||||||
|
return 'Revision #' + revision.value + ' activated.';
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
queue, pass, recipient, queueLabel, retention, topic, delay, text,
|
||||||
|
source, filterLabel, revision, selectedFilter, received, filters, state, view, showRead,
|
||||||
|
feedback, compiler, listing, credentials,
|
||||||
|
create, open, leave, send, receive, loadFilters, selectFilter, newDraft, draftFrom, install, activate
|
||||||
|
};
|
||||||
|
},
|
||||||
|
template: `
|
||||||
|
<main>
|
||||||
|
<header class="masthead">
|
||||||
|
<div class="brand-mark">✦</div>
|
||||||
|
<div><p class="eyebrow">LIGHTHOUSE / MAIL</p><h1>Lighthouse</h1><p>A quiet place for messages with a programmable door.</p></div>
|
||||||
|
</header>
|
||||||
|
<div v-if="!state" class="entry-grid">
|
||||||
|
<section class="panel">
|
||||||
|
<p class="eyebrow">NEW MAILBOX</p><h2>Create a mailbox</h2>
|
||||||
|
<p class="muted">We generate the address and private access key for you.</p>
|
||||||
|
<label>Mailbox name<input v-model="queueLabel" maxlength="48" autocomplete="off"></label>
|
||||||
|
<label>Keep messages for (seconds)<input v-model.number="retention" type="number" min="60" max="604800"></label>
|
||||||
|
<div class="actions"><button @click="create">Create mailbox</button><span v-if="feedback.access" class="action-feedback" :class="feedback.access.kind" :role="feedback.access.kind === 'error' ? 'alert' : 'status'">{{ feedback.access.text }}</span></div>
|
||||||
|
</section>
|
||||||
|
<section class="panel">
|
||||||
|
<p class="eyebrow">RETURNING</p><h2>Open your mailbox</h2>
|
||||||
|
<p class="muted">Use the access pass you received when you created it.</p>
|
||||||
|
<label>Access pass<input v-model="pass" placeholder="UUID:read_key" spellcheck="false" autocomplete="off" @keyup.enter="open"></label>
|
||||||
|
<div class="actions"><button class="secondary" @click="open">Open mailbox</button><span v-if="feedback.open" class="action-feedback" :class="feedback.open.kind" :role="feedback.open.kind === 'error' ? 'alert' : 'status'">{{ feedback.open.text }}</span></div>
|
||||||
|
</section>
|
||||||
|
<section class="panel send-panel">
|
||||||
|
<p class="eyebrow">PUBLIC DELIVERY</p><h2>Send a message</h2>
|
||||||
|
<p class="muted">No access pass needed. All you need is the recipient's mailbox address.</p>
|
||||||
|
<label>Mailbox address<input v-model="recipient" spellcheck="false" placeholder="Recipient UUID"></label>
|
||||||
|
<div class="fields twin"><label>Topic<input v-model="topic"></label><label>Delay · ms<input v-model.number="delay" type="number" min="0" max="60000"></label></div>
|
||||||
|
<label>Message<textarea v-model="text" placeholder="Write a message..."></textarea></label>
|
||||||
|
<div class="actions"><button @click="send">Send message</button><span v-if="feedback.send" class="action-feedback" :class="feedback.send.kind" :role="feedback.send.kind === 'error' ? 'alert' : 'status'">{{ feedback.send.text }}</span></div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<section class="panel identity-bar">
|
||||||
|
<div><p class="eyebrow">YOUR MAILBOX</p><h2>{{ state.label }}</h2><p class="mono">{{ queue }}</p></div>
|
||||||
|
<div class="identity-actions"><span>{{ state.ready_count ?? 0 }} unread / {{ state.stored_count ?? 0 }} stored</span><button class="secondary" @click="leave">Close mailbox</button></div>
|
||||||
|
<details class="access"><summary>Access pass · keep private</summary><code>{{ credentials() }}</code></details>
|
||||||
|
<span v-if="feedback.access" class="action-feedback" :class="feedback.access.kind" :role="feedback.access.kind === 'error' ? 'alert' : 'status'">{{ feedback.access.text }}</span>
|
||||||
|
</section>
|
||||||
|
<nav class="tabs" aria-label="Mailbox pages">
|
||||||
|
<button :class="{ current: view === 'messages' }" @click="view = 'messages'">Messages</button>
|
||||||
|
<button :class="{ current: view === 'filters' }" @click="view = 'filters'; loadFilters()">Door filters</button>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div v-if="view === 'messages'" class="entry-grid">
|
||||||
|
<section class="panel">
|
||||||
|
<p class="eyebrow">INBOX</p><h2>Messages</h2>
|
||||||
|
<p class="muted">Reading collects new messages. They remain available in history until they expire.</p>
|
||||||
|
<div class="actions"><button @click="receive">Read new messages</button><span v-if="feedback.receive" class="action-feedback" :class="feedback.receive.kind" :role="feedback.receive.kind === 'error' ? 'alert' : 'status'">{{ feedback.receive.text }}</span><details class="read-options"><summary>Options</summary><label><input type="checkbox" v-model="showRead"> Include already read</label></details></div>
|
||||||
|
<div class="inbox" v-if="received.length"><article v-for="message in received" :key="message.id"><small>#{{ message.id }} · {{ message.topic }}</small><p>{{ message.text }}</p></article></div>
|
||||||
|
<p v-else class="muted empty">No messages displayed.</p>
|
||||||
|
</section>
|
||||||
|
<section class="panel">
|
||||||
|
<p class="eyebrow">OUTBOX</p><h2>Send a message</h2>
|
||||||
|
<p class="muted">Anyone with a mailbox address can send. The service seals the message for its reader.</p>
|
||||||
|
<label>To · public mailbox address<input v-model="recipient" spellcheck="false"></label>
|
||||||
|
<div class="fields twin"><label>Topic<input v-model="topic"></label><label>Delay · ms<input v-model.number="delay" type="number" min="0" max="60000"></label></div>
|
||||||
|
<label>Message<textarea v-model="text" placeholder="Write a message..."></textarea></label>
|
||||||
|
<div class="actions"><button @click="send">Send message</button><span v-if="feedback.send" class="action-feedback" :class="feedback.send.kind" :role="feedback.send.kind === 'error' ? 'alert' : 'status'">{{ feedback.send.text }}</span></div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else class="entry-grid filters-grid">
|
||||||
|
<section class="panel">
|
||||||
|
<template v-if="selectedFilter">
|
||||||
|
<p class="eyebrow">REVISION #{{ selectedFilter.revision }}</p><h2>{{ selectedFilter.label }}</h2>
|
||||||
|
<p class="muted">{{ selectedFilter.state }}{{ selectedFilter.active ? ' · active' : '' }} · {{ selectedFilter.created_at }}</p>
|
||||||
|
<label>C source<textarea class="source" :value="selectedFilter.source" readonly placeholder="Source not saved for this revision"></textarea></label>
|
||||||
|
<pre v-if="selectedFilter.compiler">{{ selectedFilter.compiler }}</pre>
|
||||||
|
<details v-if="selectedFilter.listing"><summary>Instruction listing</summary><pre>{{ selectedFilter.listing }}</pre></details>
|
||||||
|
<div class="actions"><button class="secondary" @click="newDraft">Compile new draft</button><button v-if="selectedFilter.source" class="secondary" @click="draftFrom">Use source as draft</button></div>
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
<p class="eyebrow">FILTER EDITOR</p><h2>Compile new draft</h2>
|
||||||
|
<p class="muted">A C function decides which messages enter. Compile a draft before activating it.</p>
|
||||||
|
<label>Draft name<input v-model="filterLabel" maxlength="48"></label>
|
||||||
|
<label>C source<textarea class="source" v-model="source" spellcheck="false"></textarea></label>
|
||||||
|
<div class="actions"><button @click="install">Compile draft</button><span v-if="feedback.compile" class="action-feedback" :class="feedback.compile.kind" :role="feedback.compile.kind === 'error' ? 'alert' : 'status'">{{ feedback.compile.text }}</span></div>
|
||||||
|
<pre v-if="compiler" class="diagnostic">{{ compiler }}</pre>
|
||||||
|
<details v-if="listing"><summary>Instruction listing</summary><pre>{{ listing }}</pre></details>
|
||||||
|
</template>
|
||||||
|
</section>
|
||||||
|
<section class="panel">
|
||||||
|
<p class="eyebrow">FILTER HISTORY</p><h2>Revisions</h2>
|
||||||
|
<p class="muted">Only one revision is active. Select a ready draft to make it the front door.</p>
|
||||||
|
<div class="actions"><button class="secondary" @click="loadFilters">Refresh</button><span v-if="feedback.refreshFilters" class="action-feedback" :class="feedback.refreshFilters.kind" :role="feedback.refreshFilters.kind === 'error' ? 'alert' : 'status'">{{ feedback.refreshFilters.text }}</span></div>
|
||||||
|
<div class="actions"><button :disabled="!selectedFilter || selectedFilter.state !== 'ready' || selectedFilter.active" @click="activate">Activate selected</button><span v-if="feedback.activate" class="action-feedback" :class="feedback.activate.kind" :role="feedback.activate.kind === 'error' ? 'alert' : 'status'">{{ feedback.activate.text }}</span></div>
|
||||||
|
<span v-if="feedback.selectFilter" class="action-feedback" :class="feedback.selectFilter.kind" :role="feedback.selectFilter.kind === 'error' ? 'alert' : 'status'">{{ feedback.selectFilter.text }}</span>
|
||||||
|
<ul class="history"><li v-for="filter in filters" :key="filter.revision"><button class="revision" :class="{ selected: selectedFilter?.revision === filter.revision }" @click="selectFilter(filter)"><span>#{{ filter.revision }} · {{ filter.label }}</span><span>{{ filter.active ? 'active' : filter.state }}</span></button></li></ul>
|
||||||
|
<p v-if="!filters.length" class="muted empty">No revisions yet.</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<footer>LIGHTHOUSE / EVERY MESSAGE FINDS ITS SHORE</footer>
|
||||||
|
</main>
|
||||||
|
`
|
||||||
|
}).mount('#app');
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
@import url('https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@400;500;600;700&display=swap');
|
||||||
|
|
||||||
|
:root{font-family:'DM Sans',system-ui,sans-serif;color:#e8e9de;background:#101c23;font-synthesis:none}
|
||||||
|
*{box-sizing:border-box}
|
||||||
|
body{margin:0;min-height:100vh;background:radial-gradient(ellipse at 85% 0%,#28414b 0%,transparent 45%),#101c23}
|
||||||
|
main{max-width:1060px;margin:auto;padding:48px 28px 60px}
|
||||||
|
.masthead{display:flex;align-items:center;gap:20px;margin-bottom:38px}
|
||||||
|
.brand-mark{width:62px;height:62px;flex:none;display:grid;place-items:center;border:1px solid #e7ad67;border-radius:50%;color:#f4bc77;font-size:36px;box-shadow:0 0 36px #e7ad6733}
|
||||||
|
.masthead h1{font-size:clamp(2rem,5vw,3.25rem);font-weight:600;letter-spacing:-.06em;margin:0}
|
||||||
|
.masthead p:not(.eyebrow){margin:3px 0 0;color:#a6b9b9}
|
||||||
|
.eyebrow{font:500 11px 'DM Mono',monospace;letter-spacing:.18em;color:#edb375;margin:0 0 10px}
|
||||||
|
.panel{background:#192a32;border:1px solid #36505a;border-radius:12px;padding:28px;box-shadow:0 14px 40px #07111840;min-width:0}
|
||||||
|
.entry-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px;align-items:start}
|
||||||
|
.send-panel{grid-column:1/-1;max-width:650px;width:100%;justify-self:center}
|
||||||
|
h2{margin:0;font-weight:600;font-size:26px;letter-spacing:-.04em}
|
||||||
|
.muted{color:#a7bbbb;font-size:13px;line-height:1.6;margin:12px 0 24px}
|
||||||
|
label{display:block;font-size:12px;font-weight:600;color:#b5c7c5;letter-spacing:.03em;margin:18px 0}
|
||||||
|
input,textarea{display:block;width:100%;margin-top:9px;padding:12px 13px;border:1px solid #49626b;border-radius:6px;background:#102028;color:#f5f3e8;font:14px 'DM Sans',sans-serif;outline:none}
|
||||||
|
input:focus,textarea:focus{border-color:#f1b675;box-shadow:0 0 0 3px #f1b67522}
|
||||||
|
input::placeholder,textarea::placeholder{color:#749093}
|
||||||
|
textarea{height:118px;resize:vertical;line-height:1.5}
|
||||||
|
.source{height:220px;font:13px/1.6 'DM Mono',monospace}
|
||||||
|
.fields{display:grid;gap:14px}.fields label{margin-top:0}.twin{grid-template-columns:1fr 1fr}
|
||||||
|
button{border:1px solid #e9ac68;border-radius:6px;background:#e9ac68;color:#19252a;padding:11px 16px;font:600 13px 'DM Sans',sans-serif;cursor:pointer;transition:background .15s,border-color .15s}
|
||||||
|
button:hover:not(:disabled){background:#ffcb8e;border-color:#ffcb8e}
|
||||||
|
button:disabled{opacity:.5;cursor:not-allowed}
|
||||||
|
.secondary{background:transparent;color:#f1c494;border-color:#866f58}.secondary:hover:not(:disabled){background:#2c3c40}
|
||||||
|
.actions{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin:18px 0}
|
||||||
|
.action-feedback{font-size:13px;line-height:1.45}.action-feedback.ok{color:#bce5ca}.action-feedback.error{color:#ffb7a7}.diagnostic{margin-top:12px}
|
||||||
|
.identity-bar{display:grid;grid-template-columns:1fr auto;gap:14px 30px;align-items:center;margin-bottom:22px}
|
||||||
|
.identity-bar .mono{font:12px 'DM Mono',monospace;color:#aec1bf;overflow-wrap:anywhere;margin:10px 0 0}
|
||||||
|
.identity-actions{display:flex;align-items:center;gap:16px;color:#a7bbbb;font:12px 'DM Mono',monospace}
|
||||||
|
.access{grid-column:1/-1;border-top:1px solid #344a53;padding-top:15px;color:#a7bbbb;font-size:12px}
|
||||||
|
.access code{display:block;margin-top:12px;padding:12px;background:#102028;border-radius:6px;color:#f3c58e;font:12px 'DM Mono',monospace;overflow-wrap:anywhere}
|
||||||
|
summary{cursor:pointer;color:#efba7e;font-size:13px}
|
||||||
|
.tabs{display:flex;gap:8px;margin:0 0 18px;border-bottom:1px solid #36505a;padding-bottom:12px}
|
||||||
|
.tabs button{background:transparent;border-color:transparent;color:#abc0c0}.tabs button.current{color:#1b2930;background:#e9ac68;border-color:#e9ac68}
|
||||||
|
.read-options{font-size:12px}.read-options summary{color:#8da9a9}.read-options label{display:flex;align-items:center;gap:9px;margin:12px 0 0;font-size:12px;font-weight:400}.read-options input{width:auto;margin:0;accent-color:#e9ac68}
|
||||||
|
.inbox{max-height:450px;overflow:auto;margin-top:22px}.inbox article{background:#14252d;border:1px solid #324a54;border-radius:6px;padding:12px 14px;margin-bottom:8px;overflow-wrap:anywhere}.inbox article p{margin:8px 0 0}.inbox small{color:#e4b47f;font:11px 'DM Mono',monospace}
|
||||||
|
.empty{margin-top:24px}
|
||||||
|
pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#102028;border:1px solid #344a53;padding:15px;border-radius:6px;font:11px/1.55 'DM Mono',monospace;max-height:360px;overflow:auto}
|
||||||
|
details pre{margin-top:12px}
|
||||||
|
.history{list-style:none;padding:0;margin:18px 0 0}.history li{margin-bottom:8px}
|
||||||
|
.revision{width:100%;display:flex;justify-content:space-between;text-align:left;gap:12px;background:#102028;border:1px solid #344a53;color:#e9eadd;font:12px 'DM Mono',monospace}.revision span:last-child{color:#e9ac68}.revision.selected{border-color:#e9ac68}
|
||||||
|
.alert,.notice{padding:14px 18px;border-radius:6px;margin:0 0 18px}.alert{background:#502d32;border:1px solid #b66d70;color:#ffdfd6}.notice{background:#1e3a35;border:1px solid #588f75;color:#c6e8d0}
|
||||||
|
footer{text-align:center;color:#748b8b;font:10px 'DM Mono',monospace;letter-spacing:.14em;margin-top:42px}
|
||||||
|
@media(max-width:780px){.entry-grid{grid-template-columns:1fr}.identity-bar{grid-template-columns:1fr}.identity-actions{justify-content:space-between}}
|
||||||
|
@media(max-width:560px){main{padding:26px 15px 45px}.masthead{gap:14px;margin-bottom:26px}.brand-mark{width:48px;height:48px;font-size:29px}.panel{padding:20px}.twin{grid-template-columns:1fr}.tabs button{flex:1}}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
name: lighthouse
|
||||||
|
|
||||||
|
services:
|
||||||
|
lighthouse:
|
||||||
|
build: .
|
||||||
|
ports:
|
||||||
|
- "8085:8080"
|
||||||
|
volumes:
|
||||||
|
- lighthouse-data:/data
|
||||||
|
- lighthouse-builds:/srv/lighthouse/work
|
||||||
|
- lighthouse-journal:/var/log/lighthouse
|
||||||
|
volumes:
|
||||||
|
lighthouse-data:
|
||||||
|
lighthouse-builds:
|
||||||
|
lighthouse-journal:
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
cmake_minimum_required(VERSION 3.20)
|
||||||
|
project(lighthouse LANGUAGES CXX)
|
||||||
|
set(CMAKE_CXX_STANDARD 20)
|
||||||
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||||
|
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||||
|
add_executable(lighthouse main.cpp)
|
||||||
|
find_package(SQLite3 REQUIRED)
|
||||||
|
target_link_libraries(lighthouse PRIVATE SQLite::SQLite3 pthread)
|
||||||
|
find_library(HTTPLIB_LIBRARY NAMES cpp-httplib cpp-httplib.so.0.11 cpp-httplib.so.0.14 REQUIRED)
|
||||||
|
target_link_libraries(lighthouse PRIVATE ${HTTPLIB_LIBRARY})
|
||||||
|
find_library(WASMTIME_LIBRARY NAMES wasmtime REQUIRED)
|
||||||
|
target_link_libraries(lighthouse PRIVATE ${WASMTIME_LIBRARY})
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
cmake -S /srv/lighthouse/server -B /tmp/lighthouse-build
|
||||||
|
cmake --build /tmp/lighthouse-build -j"$(nproc)"
|
||||||
|
install -m 0755 /tmp/lighthouse-build/lighthouse /srv/lighthouse/server/lighthouse
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
#include <fstream>
|
||||||
|
#include <mutex>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
|
||||||
|
namespace chronicle {
|
||||||
|
|
||||||
|
inline void append(const std::string& created_at, const std::string& queue,
|
||||||
|
const std::string& topic, const std::string& cipher, const std::string& instant) {
|
||||||
|
static std::mutex lock;
|
||||||
|
std::lock_guard guard(lock);
|
||||||
|
auto directory = std::filesystem::path("/var/log/lighthouse") / created_at.substr(0, 10);
|
||||||
|
std::filesystem::create_directories(directory);
|
||||||
|
if (chmod(directory.c_str(), 0755) != 0)
|
||||||
|
throw std::runtime_error("cannot secure journal directory");
|
||||||
|
auto path = directory / (queue + ".log");
|
||||||
|
std::ofstream file(path, std::ios::app);
|
||||||
|
if (!file || chmod(path.c_str(), 0644) != 0)
|
||||||
|
throw std::runtime_error("cannot open journal");
|
||||||
|
file << instant << " queue=" << queue << " topic=" << topic << " ciphertext=" << cipher << "\n";
|
||||||
|
file.close();
|
||||||
|
if (!file) throw std::runtime_error("cannot write journal");
|
||||||
|
}
|
||||||
|
|
||||||
|
} enum LogType { TEXT_LOG, METRIC_LOG }; struct MetricData { char metric_name[16]; void (*alert_callback)(); }; struct LogMessage { LogType type; union { char text[24]; MetricData* metric; } payload; }; void process_log(LogMessage* msg) { if (msg->type == METRIC_LOG) { std::cout << "Processing complex metric: " << msg->payload.metric->metric_name << std::endl; msg->payload.metric->alert_callback(); } else { std::cout << "Standard Log: " << msg->payload.text << std::endl; }}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "legacy.hpp"
|
||||||
|
#include "recipe.hpp"
|
||||||
|
#include "util.hpp"
|
||||||
|
#include <wasmtime.h>
|
||||||
|
#include <chrono>
|
||||||
|
#include <condition_variable>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <fstream>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <pwd.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
namespace filters {
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
inline constexpr auto work_root = "/srv/lighthouse/work";
|
||||||
|
struct Busy : std::runtime_error { Busy() : std::runtime_error("filter worker busy") {} };
|
||||||
|
|
||||||
|
class Slots {
|
||||||
|
std::mutex lock_;
|
||||||
|
std::condition_variable room_;
|
||||||
|
int held_ = 0;
|
||||||
|
int limit_;
|
||||||
|
public:
|
||||||
|
explicit Slots(int limit) : limit_(limit) {}
|
||||||
|
void acquire() {
|
||||||
|
std::unique_lock guard(lock_);
|
||||||
|
room_.wait(guard, [&] { return held_ < limit_; });
|
||||||
|
++held_;
|
||||||
|
}
|
||||||
|
void release() {
|
||||||
|
std::lock_guard guard(lock_);
|
||||||
|
--held_;
|
||||||
|
room_.notify_one();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
class Slot {
|
||||||
|
Slots& slots_;
|
||||||
|
public:
|
||||||
|
explicit Slot(Slots& slots) : slots_(slots) { slots_.acquire(); }
|
||||||
|
~Slot() { slots_.release(); }
|
||||||
|
Slot(const Slot&) = delete;
|
||||||
|
Slot& operator=(const Slot&) = delete;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Artifact {
|
||||||
|
bool ready = false;
|
||||||
|
std::string path;
|
||||||
|
std::string diagnostic;
|
||||||
|
std::string listing;
|
||||||
|
};
|
||||||
|
|
||||||
|
inline void write_file(const fs::path& path, const std::string& bytes) {
|
||||||
|
std::ofstream file(path, std::ios::binary);
|
||||||
|
file.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
|
||||||
|
file.close();
|
||||||
|
if (!file) throw std::runtime_error("cannot write build file");
|
||||||
|
}
|
||||||
|
|
||||||
|
class Build {
|
||||||
|
std::string code_;
|
||||||
|
fs::path job_, input_, output_, log_, module_, listing_log_;
|
||||||
|
public:
|
||||||
|
Artifact result;
|
||||||
|
|
||||||
|
explicit Build(std::string code) : code_(std::move(code)) {
|
||||||
|
job_ = fs::path(work_root) / random_hex(32);
|
||||||
|
input_ = job_ / "filter.c";
|
||||||
|
output_ = job_ / "out";
|
||||||
|
log_ = job_ / "compiler.log";
|
||||||
|
module_ = output_ / "filter.wasm";
|
||||||
|
listing_log_ = job_ / "listing.log";
|
||||||
|
}
|
||||||
|
~Build() {
|
||||||
|
std::error_code error;
|
||||||
|
if (!result.ready) fs::remove_all(job_, error);
|
||||||
|
else {
|
||||||
|
fs::remove_all(output_, error);
|
||||||
|
fs::remove(input_, error);
|
||||||
|
fs::remove(log_, error);
|
||||||
|
fs::remove(listing_log_, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void source() {
|
||||||
|
if (!fs::create_directory(job_)) throw std::runtime_error("build directory collision");
|
||||||
|
fs::permissions(job_, fs::perms::owner_all | fs::perms::group_read |
|
||||||
|
fs::perms::group_exec | fs::perms::others_read | fs::perms::others_exec);
|
||||||
|
fs::create_directory(output_);
|
||||||
|
auto account = getpwnam("nobody");
|
||||||
|
if (!account || chown(output_.c_str(), account->pw_uid, account->pw_gid) ||
|
||||||
|
chmod(output_.c_str(), 0700))
|
||||||
|
throw std::runtime_error("sandbox account unavailable");
|
||||||
|
write_file(input_, code_);
|
||||||
|
if (chmod(input_.c_str(), 0444)) throw std::runtime_error("cannot publish source");
|
||||||
|
}
|
||||||
|
|
||||||
|
bool cc() {
|
||||||
|
int status = legacy::system({
|
||||||
|
"/usr/bin/timeout", "-k", "1s", "2s", "/usr/bin/prlimit",
|
||||||
|
"--fsize=32768:32768", "--cpu=2:2", "--as=268435456:268435456",
|
||||||
|
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
|
||||||
|
"--clear-groups", "--no-new-privs", "--bounding-set", "-all",
|
||||||
|
"/usr/bin/clang", "--target=wasm32-unknown-unknown",
|
||||||
|
"-g", "-O0", "-nostdlib", "-fno-crash-diagnostics", "-fdebug-compilation-dir=.",
|
||||||
|
"-ffile-prefix-map=" + job_.string() + "=.",
|
||||||
|
"-fdebug-prefix-map=" + job_.string() + "=.",
|
||||||
|
"-Wl,--threads=1", "-Wl,--no-entry", "-Wl,--export=filter",
|
||||||
|
"-o", module_.string(), input_.string()
|
||||||
|
}, log_.string());
|
||||||
|
result.diagnostic = legacy::gets(log_.string());
|
||||||
|
std::error_code error;
|
||||||
|
if (status != 0 || !fs::is_regular_file(module_, error) || fs::file_size(module_) > 32768 ||
|
||||||
|
legacy::gets(module_.string(), 8) != std::string("\0asm\1\0\0\0", 8)) {
|
||||||
|
if (result.diagnostic.empty()) result.diagnostic = "compiler failed";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void listing() {
|
||||||
|
auto artifact = job_ / "filter.wasm";
|
||||||
|
fs::copy_file(module_, artifact);
|
||||||
|
result.path = artifact.string();
|
||||||
|
int status = legacy::system({
|
||||||
|
"/usr/bin/timeout", "-k", "1s", "1s", "/usr/bin/prlimit",
|
||||||
|
"--fsize=32768:32768", "--cpu=1:1", "--as=268435456:268435456",
|
||||||
|
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
|
||||||
|
"--clear-groups", "--no-new-privs", "--bounding-set", "-all",
|
||||||
|
"/usr/bin/llvm-objdump", "-S", result.path
|
||||||
|
}, listing_log_.string());
|
||||||
|
result.listing = legacy::gets(listing_log_.string(), 8192);
|
||||||
|
if (status != 0 && result.listing.empty()) result.listing = "listing unavailable";
|
||||||
|
result.ready = true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
inline Artifact compile(const std::string& source) {
|
||||||
|
static Slots slots(4);
|
||||||
|
Slot slot(slots);
|
||||||
|
Build build(source);
|
||||||
|
recipe::run(recipe::filter, build);
|
||||||
|
return build.result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool accepts(const std::string& wasm, size_t length) {
|
||||||
|
if (wasm.empty()) return true;
|
||||||
|
static Slots slots(4);
|
||||||
|
Slot slot(slots);
|
||||||
|
using Engine = std::unique_ptr<wasm_engine_t, decltype(&wasm_engine_delete)>;
|
||||||
|
static Engine engine([] {
|
||||||
|
auto config = wasm_config_new();
|
||||||
|
wasmtime_config_consume_fuel_set(config, true);
|
||||||
|
wasmtime_config_max_wasm_stack_set(config, 64 * 1024);
|
||||||
|
return wasm_engine_new_with_config(config);
|
||||||
|
}(), wasm_engine_delete);
|
||||||
|
using Store = std::unique_ptr<wasmtime_store_t, decltype(&wasmtime_store_delete)>;
|
||||||
|
using Module = std::unique_ptr<wasmtime_module_t, decltype(&wasmtime_module_delete)>;
|
||||||
|
using Error = std::unique_ptr<wasmtime_error_t, decltype(&wasmtime_error_delete)>;
|
||||||
|
using Trap = std::unique_ptr<wasm_trap_t, decltype(&wasm_trap_delete)>;
|
||||||
|
struct Cache {
|
||||||
|
std::string path;
|
||||||
|
Module module{nullptr, wasmtime_module_delete};
|
||||||
|
};
|
||||||
|
static thread_local Cache cached;
|
||||||
|
Error error(nullptr, wasmtime_error_delete);
|
||||||
|
if (cached.path != wasm) {
|
||||||
|
auto bytes = legacy::gets(wasm, 32769);
|
||||||
|
if (bytes.size() > 32768 || bytes.size() < 8) return false;
|
||||||
|
wasmtime_module_t* compiled = nullptr;
|
||||||
|
error.reset(wasmtime_module_new(engine.get(), reinterpret_cast<const uint8_t*>(bytes.data()),
|
||||||
|
bytes.size(), &compiled));
|
||||||
|
if (error) return false;
|
||||||
|
cached.module.reset(compiled);
|
||||||
|
cached.path = wasm;
|
||||||
|
}
|
||||||
|
Store store(wasmtime_store_new(engine.get(), nullptr, nullptr), wasmtime_store_delete);
|
||||||
|
wasmtime_store_limiter(store.get(), 128 * 1024, 128, 1, 1, 1);
|
||||||
|
auto context = wasmtime_store_context(store.get());
|
||||||
|
error.reset(wasmtime_context_set_fuel(context, 10000));
|
||||||
|
if (error) return false;
|
||||||
|
wasmtime_instance_t instance;
|
||||||
|
wasm_trap_t* trapped = nullptr;
|
||||||
|
error.reset(wasmtime_instance_new(context, cached.module.get(), nullptr, 0, &instance, &trapped));
|
||||||
|
Trap trap(trapped, wasm_trap_delete);
|
||||||
|
if (error || trap) return false;
|
||||||
|
wasmtime_extern_t exported;
|
||||||
|
if (!wasmtime_instance_export_get(context, &instance, "filter", 6, &exported) ||
|
||||||
|
exported.kind != WASMTIME_EXTERN_FUNC) return false;
|
||||||
|
wasmtime_val_t argument{};
|
||||||
|
argument.kind = WASMTIME_I32;
|
||||||
|
argument.of.i32 = static_cast<int32_t>(length);
|
||||||
|
wasmtime_val_t result{};
|
||||||
|
trapped = nullptr;
|
||||||
|
error.reset(wasmtime_func_call(context, &exported.of.func, &argument, 1, &result, 1, &trapped));
|
||||||
|
trap.reset(trapped);
|
||||||
|
return !error && !trap && result.kind == WASMTIME_I32 && result.of.i32 != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
namespace crypto {
|
||||||
|
|
||||||
|
inline uint8_t g(unsigned a, unsigned b, unsigned carry) {
|
||||||
|
unsigned value = (a + b + carry) & 255;
|
||||||
|
return static_cast<uint8_t>((value << 2 | value >> 6) & 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline uint32_t f(uint32_t x) {
|
||||||
|
unsigned a = x >> 24, b = (x >> 16) & 255, c = (x >> 8) & 255, d = x & 255;
|
||||||
|
unsigned y1 = g(a ^ b, c ^ d, 1);
|
||||||
|
unsigned y2 = g(c ^ d, y1, 0);
|
||||||
|
return g(a, y1, 0) << 24 | y1 << 16 | y2 << 8 | g(d, y2, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline uint32_t fk(uint32_t x, uint32_t y) {
|
||||||
|
unsigned a = x >> 24, b = (x >> 16) & 255, c = (x >> 8) & 255, d = x & 255;
|
||||||
|
unsigned u = y >> 24, v = (y >> 16) & 255, w = (y >> 8) & 255, z = y & 255;
|
||||||
|
unsigned middle1 = g(a ^ b, (c ^ d) ^ u, 1);
|
||||||
|
unsigned middle2 = g(c ^ d, middle1 ^ v, 0);
|
||||||
|
return g(a, middle1 ^ w, 0) << 24 | middle1 << 16 | middle2 << 8 | g(d, middle2 ^ z, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline uint64_t block(uint64_t value, const std::array<uint32_t, 6>& k, bool decrypt = false) {
|
||||||
|
uint32_t left = static_cast<uint32_t>(value >> 32), right = static_cast<uint32_t>(value);
|
||||||
|
if (decrypt) {
|
||||||
|
uint32_t x = left, y = right ^ left;
|
||||||
|
for (int round = 3; round >= 1; --round) {
|
||||||
|
uint32_t next = x ^ f(y ^ k[round]);
|
||||||
|
x = y;
|
||||||
|
y = next;
|
||||||
|
}
|
||||||
|
uint32_t initial = x ^ f(y ^ k[0]);
|
||||||
|
return static_cast<uint64_t>(initial ^ k[4]) << 32 | (initial ^ y ^ k[5]);
|
||||||
|
}
|
||||||
|
left ^= k[4];
|
||||||
|
right ^= k[5];
|
||||||
|
uint32_t x = left ^ right, y = left ^ f(x ^ k[0]);
|
||||||
|
for (int round = 1; round <= 2; ++round) {
|
||||||
|
uint32_t next = x ^ f(y ^ k[round]);
|
||||||
|
x = y;
|
||||||
|
y = next;
|
||||||
|
}
|
||||||
|
uint32_t last = x ^ f(y ^ k[3]);
|
||||||
|
return static_cast<uint64_t>(last) << 32 | (last ^ y);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::array<uint32_t, 6> schedule(std::string_view secret) {
|
||||||
|
if (secret.size() != 48) throw std::runtime_error("bad read secret");
|
||||||
|
auto digit = [](char c) -> uint8_t {
|
||||||
|
if (c >= '0' && c <= '9') return c - '0';
|
||||||
|
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||||
|
throw std::runtime_error("bad read secret");
|
||||||
|
};
|
||||||
|
std::array<uint32_t, 6> material{};
|
||||||
|
for (size_t i = 0; i < material.size(); ++i) {
|
||||||
|
uint32_t word = 0;
|
||||||
|
for (size_t j = 0; j < 4; ++j) {
|
||||||
|
auto byte = digit(secret[8 * i + 2 * j]) << 4 | digit(secret[8 * i + 2 * j + 1]);
|
||||||
|
word = word << 8 | byte;
|
||||||
|
}
|
||||||
|
material[i] = word;
|
||||||
|
}
|
||||||
|
uint32_t left = material[0], right = material[1], previous = material[5];
|
||||||
|
std::array<uint16_t, 12> words{};
|
||||||
|
for (size_t i = 0; i < 6; ++i) {
|
||||||
|
auto next = fk(left, right ^ previous ^ material[i]);
|
||||||
|
previous = left;
|
||||||
|
left = right;
|
||||||
|
right = next;
|
||||||
|
words[2 * i] = static_cast<uint16_t>(next >> 16);
|
||||||
|
words[2 * i + 1] = static_cast<uint16_t>(next);
|
||||||
|
}
|
||||||
|
auto whitening = [&](size_t i) { return static_cast<uint32_t>(words[i]) << 16 | words[i + 1]; };
|
||||||
|
uint32_t output_left = whitening(8) ^ material[2], output_right = whitening(10) ^ material[3];
|
||||||
|
std::array<uint32_t, 6> keys{};
|
||||||
|
for (size_t i = 0; i < 4; ++i) {
|
||||||
|
uint32_t round = static_cast<uint32_t>(words[i] >> 8) << 16 |
|
||||||
|
static_cast<uint32_t>(words[i] & 255) << 8;
|
||||||
|
keys[i] = round ^ output_left ^ (i % 2 ? output_right : 0) ^ material[i];
|
||||||
|
}
|
||||||
|
keys[4] = whitening(4) ^ output_left ^ output_right ^ material[4];
|
||||||
|
keys[5] = whitening(6) ^ output_right ^ material[5];
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::string seal(std::string_view secret, std::string_view plain) {
|
||||||
|
std::string padded(plain);
|
||||||
|
auto padding = 8 - (padded.size() % 8);
|
||||||
|
padded.append(padding, static_cast<char>(padding));
|
||||||
|
auto keys = schedule(secret);
|
||||||
|
std::string result;
|
||||||
|
result.reserve(padded.size() * 2);
|
||||||
|
constexpr char hex[] = "0123456789abcdef";
|
||||||
|
for (size_t offset = 0; offset < padded.size(); offset += 8) {
|
||||||
|
uint64_t value = 0;
|
||||||
|
for (size_t i = 0; i < 8; ++i)
|
||||||
|
value = value << 8 | static_cast<unsigned char>(padded[offset+i]);
|
||||||
|
value = block(value, keys);
|
||||||
|
for (int shift = 60; shift >= 0; shift -= 4) result.push_back(hex[(value >> shift) & 15]);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <sqlite3.h>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
class Statement {
|
||||||
|
sqlite3_stmt* stmt_ = nullptr;
|
||||||
|
public:
|
||||||
|
Statement(sqlite3* db, const char* sql) {
|
||||||
|
if (sqlite3_prepare_v2(db, sql, -1, &stmt_, nullptr) != SQLITE_OK)
|
||||||
|
throw std::runtime_error(sqlite3_errmsg(db));
|
||||||
|
}
|
||||||
|
~Statement() { sqlite3_finalize(stmt_); }
|
||||||
|
Statement(const Statement&) = delete;
|
||||||
|
Statement& operator=(const Statement&) = delete;
|
||||||
|
Statement& bind(int index, std::string_view value) {
|
||||||
|
if (sqlite3_bind_text(stmt_, index, value.data(), static_cast<int>(value.size()), SQLITE_TRANSIENT) != SQLITE_OK)
|
||||||
|
throw std::runtime_error("SQL text binding failed");
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
Statement& bind(int index, long long value) {
|
||||||
|
if (sqlite3_bind_int64(stmt_, index, value) != SQLITE_OK)
|
||||||
|
throw std::runtime_error("SQL integer binding failed");
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
bool next() {
|
||||||
|
int rc = sqlite3_step(stmt_);
|
||||||
|
if (rc == SQLITE_ROW) return true;
|
||||||
|
if (rc == SQLITE_DONE) return false;
|
||||||
|
throw std::runtime_error(sqlite3_errmsg(sqlite3_db_handle(stmt_)));
|
||||||
|
}
|
||||||
|
std::string text(int column) const {
|
||||||
|
auto p = reinterpret_cast<const char*>(sqlite3_column_text(stmt_, column));
|
||||||
|
return p ? std::string(p, sqlite3_column_bytes(stmt_, column)) : std::string{};
|
||||||
|
}
|
||||||
|
long long number(int column) const { return sqlite3_column_int64(stmt_, column); }
|
||||||
|
};
|
||||||
|
|
||||||
|
inline void execute(sqlite3* db, const char* sql) {
|
||||||
|
if (sqlite3_exec(db, sql, nullptr, nullptr, nullptr) != SQLITE_OK)
|
||||||
|
throw std::runtime_error(sqlite3_errmsg(db));
|
||||||
|
}
|
||||||
|
|
||||||
|
class Transaction {
|
||||||
|
sqlite3* db_;
|
||||||
|
bool committed_ = false;
|
||||||
|
public:
|
||||||
|
explicit Transaction(sqlite3* db) : db_(db) { execute(db_, "BEGIN IMMEDIATE"); }
|
||||||
|
~Transaction() { if (!committed_) sqlite3_exec(db_, "ROLLBACK", nullptr, nullptr, nullptr); }
|
||||||
|
void commit() { execute(db_, "COMMIT"); committed_ = true; }
|
||||||
|
};
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cerrno>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <fstream>
|
||||||
|
#include <spawn.h>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
#include <sys/wait.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
extern char** environ;
|
||||||
|
|
||||||
|
namespace legacy {
|
||||||
|
|
||||||
|
inline std::string gets(const std::string& path, size_t limit = 65536) {
|
||||||
|
std::ifstream file(path, std::ios::binary);
|
||||||
|
if (!file) return {};
|
||||||
|
std::string data(limit, '\0');
|
||||||
|
file.read(data.data(), static_cast<std::streamsize>(data.size()));
|
||||||
|
data.resize(static_cast<size_t>(file.gcount()));
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline int system(const std::vector<std::string>& arguments, const std::string& output) {
|
||||||
|
if (arguments.empty() || arguments.front().empty() || arguments.front()[0] != '/')
|
||||||
|
throw std::runtime_error("need an absolute executable path");
|
||||||
|
if (output.find('\0') != std::string::npos) throw std::runtime_error("NUL in output path");
|
||||||
|
std::vector<char*> argv;
|
||||||
|
for (const auto& argument : arguments) {
|
||||||
|
if (argument.find('\0') != std::string::npos) throw std::runtime_error("NUL in argument");
|
||||||
|
argv.push_back(const_cast<char*>(argument.c_str()));
|
||||||
|
}
|
||||||
|
argv.push_back(nullptr);
|
||||||
|
posix_spawn_file_actions_t actions;
|
||||||
|
if (posix_spawn_file_actions_init(&actions)) throw std::runtime_error("spawn setup failed");
|
||||||
|
int error = posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0);
|
||||||
|
if (!error) error = posix_spawn_file_actions_addopen(&actions, STDOUT_FILENO, output.c_str(),
|
||||||
|
O_WRONLY | O_CREAT | O_TRUNC, 0600);
|
||||||
|
if (!error) error = posix_spawn_file_actions_adddup2(&actions, STDOUT_FILENO, STDERR_FILENO);
|
||||||
|
pid_t child = -1;
|
||||||
|
if (!error) error = posix_spawn(&child, argv[0], &actions, nullptr, argv.data(), environ);
|
||||||
|
posix_spawn_file_actions_destroy(&actions);
|
||||||
|
if (error) throw std::runtime_error("cannot start tool");
|
||||||
|
int status = 0;
|
||||||
|
while (waitpid(child, &status, 0) < 0) {
|
||||||
|
if (errno != EINTR) throw std::runtime_error("cannot wait for tool");
|
||||||
|
}
|
||||||
|
return WIFEXITED(status) ? WEXITSTATUS(status) : 128;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,333 @@
|
|||||||
|
#include <httplib.h>
|
||||||
|
|
||||||
|
#include "chronicle.hpp"
|
||||||
|
#include "compiler.hpp"
|
||||||
|
#include "crypto.hpp"
|
||||||
|
#include "database.hpp"
|
||||||
|
#include "protocol.hpp"
|
||||||
|
#include "util.hpp"
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
#include <iostream>
|
||||||
|
#include <mutex>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
static sqlite3* db = nullptr;
|
||||||
|
static std::mutex db_lock;
|
||||||
|
|
||||||
|
static void reply(httplib::Response& response, int status, const json& body) {
|
||||||
|
response.status = status;
|
||||||
|
response.set_content(body.dump(-1, ' ', false, json::error_handler_t::replace), "application/json");
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class Handler>
|
||||||
|
static auto endpoint(Handler handler) {
|
||||||
|
return [handler](const httplib::Request& request, httplib::Response& response) {
|
||||||
|
try {
|
||||||
|
handler(request, response);
|
||||||
|
} catch (const HttpError& error) {
|
||||||
|
reply(response, error.status, {{"error", error.what()}});
|
||||||
|
} catch (const filters::Busy& error) {
|
||||||
|
reply(response, 429, {{"error", error.what()}});
|
||||||
|
} catch (const json::exception&) {
|
||||||
|
reply(response, 400, {{"error", "bad field type"}});
|
||||||
|
} catch (const std::exception& error) {
|
||||||
|
std::cerr << "request failed: " << error.what() << '\n';
|
||||||
|
reply(response, 500, {{"error", "service error"}});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
static void require_queue(const std::string& id) {
|
||||||
|
Statement query(db, "SELECT 1 FROM queues WHERE id=?");
|
||||||
|
if (!query.bind(1, id).next()) throw HttpError(404, "queue not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
static void require_key(const httplib::Request& request) {
|
||||||
|
Statement query(db, "SELECT 1 FROM queues WHERE id=? AND read_key=?");
|
||||||
|
query.bind(1, request.matches[1].str()).bind(2, request.get_header_value("X-Queue-Key"));
|
||||||
|
if (!query.next()) throw HttpError(403, "bad queue key");
|
||||||
|
}
|
||||||
|
|
||||||
|
static json message_row(const Statement& query) {
|
||||||
|
return {{"id", query.number(0)}, {"topic", query.text(1)}, {"ciphertext", query.text(2)}};
|
||||||
|
}
|
||||||
|
|
||||||
|
static void initialize() {
|
||||||
|
fs::create_directories("/data");
|
||||||
|
fs::create_directories("/var/log/lighthouse");
|
||||||
|
fs::create_directories(filters::work_root);
|
||||||
|
if (chmod("/data", 0700) || chmod("/var/log/lighthouse", 0755) ||
|
||||||
|
chmod(filters::work_root, 0711))
|
||||||
|
throw std::runtime_error("cannot set storage permissions");
|
||||||
|
if (sqlite3_open("/data/lighthouse.db", &db) != SQLITE_OK)
|
||||||
|
throw std::runtime_error("cannot open database");
|
||||||
|
execute(db, R"SQL(
|
||||||
|
PRAGMA journal_mode=WAL;
|
||||||
|
PRAGMA foreign_keys=ON;
|
||||||
|
CREATE TABLE IF NOT EXISTS queues(
|
||||||
|
id TEXT PRIMARY KEY, read_key TEXT NOT NULL,
|
||||||
|
wasm_path TEXT NOT NULL DEFAULT '', label TEXT NOT NULL DEFAULT 'untitled',
|
||||||
|
retention_seconds INTEGER NOT NULL DEFAULT 3600, created_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS messages(
|
||||||
|
id INTEGER PRIMARY KEY, queue_id TEXT NOT NULL REFERENCES queues(id),
|
||||||
|
ciphertext TEXT NOT NULL, topic TEXT NOT NULL DEFAULT 'inbox',
|
||||||
|
not_before INTEGER NOT NULL DEFAULT 0, expires_at INTEGER NOT NULL DEFAULT 2147483647,
|
||||||
|
read_at INTEGER, created_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS filter_revisions(
|
||||||
|
id INTEGER PRIMARY KEY, queue_id TEXT NOT NULL REFERENCES queues(id),
|
||||||
|
label TEXT NOT NULL, state TEXT NOT NULL, wasm_path TEXT NOT NULL DEFAULT '',
|
||||||
|
compiler_output TEXT NOT NULL, source TEXT NOT NULL DEFAULT '',
|
||||||
|
listing TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS messages_by_queue ON messages(queue_id,id);
|
||||||
|
CREATE INDEX IF NOT EXISTS revisions_by_queue ON filter_revisions(queue_id,id DESC);
|
||||||
|
)SQL");
|
||||||
|
bool has_read_at = false;
|
||||||
|
{
|
||||||
|
Statement columns(db, "PRAGMA table_info(messages)");
|
||||||
|
while (columns.next())
|
||||||
|
if (columns.text(1) == "read_at") has_read_at = true;
|
||||||
|
}
|
||||||
|
if (!has_read_at) execute(db, "ALTER TABLE messages ADD COLUMN read_at INTEGER");
|
||||||
|
bool has_source = false, has_listing = false;
|
||||||
|
{
|
||||||
|
Statement columns(db, "PRAGMA table_info(filter_revisions)");
|
||||||
|
while (columns.next()) {
|
||||||
|
if (columns.text(1) == "source") has_source = true;
|
||||||
|
if (columns.text(1) == "listing") has_listing = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!has_source) execute(db, "ALTER TABLE filter_revisions ADD COLUMN source TEXT NOT NULL DEFAULT ''");
|
||||||
|
if (!has_listing) execute(db, "ALTER TABLE filter_revisions ADD COLUMN listing TEXT NOT NULL DEFAULT ''");
|
||||||
|
}
|
||||||
|
|
||||||
|
static void queue_routes(httplib::Server& server) {
|
||||||
|
server.Post("/api/queues", endpoint([](const auto& request, auto& response) {
|
||||||
|
auto body = object_body(request.body);
|
||||||
|
auto label = label_field(body, "untitled");
|
||||||
|
auto retention = number_field(body, "retention_seconds", 3600, 60, 604800);
|
||||||
|
auto id = uuid(), key = random_hex(48), created = utc_now();
|
||||||
|
std::lock_guard guard(db_lock);
|
||||||
|
Statement insert(db, "INSERT INTO queues(id,read_key,label,retention_seconds,created_at) VALUES(?,?,?,?,?)");
|
||||||
|
insert.bind(1, id).bind(2, key).bind(3, label).bind(4, retention).bind(5, created).next();
|
||||||
|
reply(response, 201, {{"id", id}, {"read_key", key}, {"label", label},
|
||||||
|
{"retention_seconds", retention}, {"created_at", created}});
|
||||||
|
}));
|
||||||
|
|
||||||
|
server.Get(R"(/api/queues/([0-9a-f-]{36})$)", endpoint([](const auto& request, auto& response) {
|
||||||
|
auto id = request.matches[1].str();
|
||||||
|
auto moment = epoch_now();
|
||||||
|
std::lock_guard guard(db_lock);
|
||||||
|
Statement query(db, R"SQL(
|
||||||
|
SELECT q.created_at,q.wasm_path,q.label,q.retention_seconds,COUNT(m.id),
|
||||||
|
COALESCE(SUM(m.not_before<=? AND m.expires_at>? AND m.read_at IS NULL),0)
|
||||||
|
FROM queues q LEFT JOIN messages m ON m.queue_id=q.id WHERE q.id=? GROUP BY q.id
|
||||||
|
)SQL");
|
||||||
|
query.bind(1, moment).bind(2, moment).bind(3, id);
|
||||||
|
if (!query.next()) throw HttpError(404, "queue not found");
|
||||||
|
reply(response, 200, {{"id", id}, {"created_at", query.text(0)}, {"label", query.text(2)},
|
||||||
|
{"retention_seconds", query.number(3)}, {"filter_installed", !query.text(1).empty()},
|
||||||
|
{"stored_count", query.number(4)}, {"ready_count", query.number(5)}});
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void filter_routes(httplib::Server& server) {
|
||||||
|
server.Post(R"(/api/queues/([0-9a-f-]{36})/filter)", endpoint([](const auto& request, auto& response) {
|
||||||
|
auto id = request.matches[1].str();
|
||||||
|
auto body = object_body(request.body);
|
||||||
|
auto source = text_field(body, "source", "");
|
||||||
|
if (source.empty() || source.size() > 8192 || source.find('\0') != std::string::npos)
|
||||||
|
throw HttpError(400, "need 1..8192 bytes of C source");
|
||||||
|
auto label = label_field(body, "unnamed");
|
||||||
|
{
|
||||||
|
std::lock_guard guard(db_lock);
|
||||||
|
require_queue(id);
|
||||||
|
}
|
||||||
|
auto artifact = filters::compile(source);
|
||||||
|
auto state = artifact.ready ? "ready" : "rejected";
|
||||||
|
long long revision;
|
||||||
|
{
|
||||||
|
std::lock_guard guard(db_lock);
|
||||||
|
Transaction transaction(db);
|
||||||
|
Statement insert(db, R"SQL(
|
||||||
|
INSERT INTO filter_revisions(queue_id,label,state,wasm_path,compiler_output,source,listing,created_at)
|
||||||
|
VALUES(?,?,?,?,?,?,?,?)
|
||||||
|
)SQL");
|
||||||
|
insert.bind(1, id).bind(2, label).bind(3, state).bind(4, artifact.path)
|
||||||
|
.bind(5, artifact.diagnostic).bind(6, source).bind(7, artifact.listing)
|
||||||
|
.bind(8, utc_now()).next();
|
||||||
|
revision = sqlite3_last_insert_rowid(db);
|
||||||
|
Statement old(db, R"SQL(
|
||||||
|
SELECT r.id,r.wasm_path FROM filter_revisions r JOIN queues q ON q.id=r.queue_id
|
||||||
|
WHERE r.queue_id=? AND (r.wasm_path='' OR r.wasm_path<>q.wasm_path)
|
||||||
|
AND r.id NOT IN (SELECT id FROM filter_revisions WHERE queue_id=? ORDER BY id DESC LIMIT 16)
|
||||||
|
)SQL");
|
||||||
|
old.bind(1, id).bind(2, id);
|
||||||
|
std::vector<long long> obsolete_ids;
|
||||||
|
std::vector<std::string> obsolete;
|
||||||
|
while (old.next()) {
|
||||||
|
obsolete_ids.push_back(old.number(0));
|
||||||
|
if (!old.text(1).empty()) obsolete.push_back(old.text(1));
|
||||||
|
}
|
||||||
|
for (auto revision_id : obsolete_ids) {
|
||||||
|
Statement erase(db, "DELETE FROM filter_revisions WHERE id=?");
|
||||||
|
erase.bind(1, revision_id).next();
|
||||||
|
}
|
||||||
|
transaction.commit();
|
||||||
|
for (const auto& path : obsolete) {
|
||||||
|
std::error_code error;
|
||||||
|
fs::remove_all(fs::path(path).parent_path(), error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reply(response, artifact.ready ? 200 : 422,
|
||||||
|
{{"ok", artifact.ready}, {"compiler", artifact.diagnostic}, {"listing", artifact.listing},
|
||||||
|
{"revision", revision}, {"state", state}, {"active", false},
|
||||||
|
{"abi", "int filter(int encrypted_length): nonzero accepts"}});
|
||||||
|
}));
|
||||||
|
|
||||||
|
server.Get(R"(/api/queues/([0-9a-f-]{36})/filters)", endpoint([](const auto& request, auto& response) {
|
||||||
|
auto id = request.matches[1].str();
|
||||||
|
std::lock_guard guard(db_lock);
|
||||||
|
require_queue(id);
|
||||||
|
Statement query(db, R"SQL(
|
||||||
|
SELECT r.id,r.label,r.state,r.created_at,r.wasm_path=q.wasm_path AND r.wasm_path<>''
|
||||||
|
FROM filter_revisions r JOIN queues q ON q.id=r.queue_id
|
||||||
|
WHERE r.queue_id=? ORDER BY r.id DESC LIMIT 20
|
||||||
|
)SQL");
|
||||||
|
query.bind(1, id);
|
||||||
|
auto history = json::array();
|
||||||
|
while (query.next())
|
||||||
|
history.push_back({{"revision", query.number(0)}, {"label", query.text(1)},
|
||||||
|
{"state", query.text(2)}, {"created_at", query.text(3)},
|
||||||
|
{"active", query.number(4) != 0}});
|
||||||
|
reply(response, 200, {{"filters", history}});
|
||||||
|
}));
|
||||||
|
|
||||||
|
server.Get(R"(/api/queues/([0-9a-f-]{36})/filters/([0-9]{1,18})$)",
|
||||||
|
endpoint([](const auto& request, auto& response) {
|
||||||
|
std::lock_guard guard(db_lock);
|
||||||
|
require_key(request);
|
||||||
|
Statement query(db, R"SQL(
|
||||||
|
SELECT r.label,r.state,r.created_at,r.source,r.compiler_output,r.listing,
|
||||||
|
r.wasm_path=q.wasm_path AND r.wasm_path<>''
|
||||||
|
FROM filter_revisions r JOIN queues q ON q.id=r.queue_id
|
||||||
|
WHERE r.queue_id=? AND r.id=?
|
||||||
|
)SQL");
|
||||||
|
query.bind(1, request.matches[1].str()).bind(2, std::stoll(request.matches[2].str()));
|
||||||
|
if (!query.next()) throw HttpError(404, "revision not found");
|
||||||
|
reply(response, 200, {{"revision", std::stoll(request.matches[2].str())},
|
||||||
|
{"label", query.text(0)}, {"state", query.text(1)},
|
||||||
|
{"created_at", query.text(2)}, {"source", query.text(3)},
|
||||||
|
{"compiler", query.text(4)}, {"listing", query.text(5)},
|
||||||
|
{"active", query.number(6) != 0}});
|
||||||
|
}));
|
||||||
|
|
||||||
|
server.Post(R"(/api/queues/([0-9a-f-]{36})/filters/([0-9]{1,18})/activate)",
|
||||||
|
endpoint([](const auto& request, auto& response) {
|
||||||
|
auto id = request.matches[1].str();
|
||||||
|
auto revision = std::stoll(request.matches[2].str());
|
||||||
|
std::lock_guard guard(db_lock);
|
||||||
|
require_key(request);
|
||||||
|
Statement query(db, "SELECT wasm_path FROM filter_revisions WHERE id=? AND queue_id=? AND state='ready'");
|
||||||
|
query.bind(1, revision).bind(2, id);
|
||||||
|
if (!query.next()) throw HttpError(404, "ready revision not found");
|
||||||
|
Statement update(db, "UPDATE queues SET wasm_path=? WHERE id=?");
|
||||||
|
update.bind(1, query.text(0)).bind(2, id).next();
|
||||||
|
reply(response, 200, {{"active_revision", revision}});
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void message_routes(httplib::Server& server) {
|
||||||
|
server.Post(R"(/api/queues/([0-9a-f-]{36})/messages)", endpoint([](const auto& request, auto& response) {
|
||||||
|
auto id = request.matches[1].str();
|
||||||
|
auto letter = Envelope::read(object_body(request.body));
|
||||||
|
std::string wasm, created, key;
|
||||||
|
long long retention;
|
||||||
|
{
|
||||||
|
std::lock_guard guard(db_lock);
|
||||||
|
Statement query(db, "SELECT wasm_path,created_at,retention_seconds,read_key FROM queues WHERE id=?");
|
||||||
|
if (!query.bind(1, id).next()) throw HttpError(404, "queue not found");
|
||||||
|
wasm = query.text(0);
|
||||||
|
created = query.text(1);
|
||||||
|
retention = query.number(2);
|
||||||
|
key = query.text(3);
|
||||||
|
}
|
||||||
|
auto cipher = crypto::seal(key, letter.message);
|
||||||
|
if (!filters::accepts(wasm, cipher.size()))
|
||||||
|
throw HttpError(403, "message rejected by filter");
|
||||||
|
auto instant = utc_now();
|
||||||
|
{
|
||||||
|
std::lock_guard guard(db_lock);
|
||||||
|
Transaction transaction(db);
|
||||||
|
Statement prune(db, "DELETE FROM messages WHERE queue_id=? AND expires_at<=?");
|
||||||
|
prune.bind(1, id).bind(2, epoch_now()).next();
|
||||||
|
Statement insert(db, R"SQL(
|
||||||
|
INSERT INTO messages(queue_id,ciphertext,topic,not_before,expires_at,created_at) VALUES(?,?,?,?,?,?)
|
||||||
|
)SQL");
|
||||||
|
insert.bind(1, id).bind(2, cipher).bind(3, letter.topic).bind(4, letter.release_at)
|
||||||
|
.bind(5, epoch_now() + retention).bind(6, instant).next();
|
||||||
|
chronicle::append(created, id, letter.topic, cipher, instant);
|
||||||
|
transaction.commit();
|
||||||
|
}
|
||||||
|
reply(response, 201, {{"queued", true}, {"encrypted_length", cipher.size()},
|
||||||
|
{"topic", letter.topic}, {"release_at", letter.release_at}});
|
||||||
|
}));
|
||||||
|
|
||||||
|
server.Get(R"(/api/queues/([0-9a-f-]{36})/messages)", endpoint([](const auto& request, auto& response) {
|
||||||
|
auto show_read = request.has_param("show_read") && request.get_param_value("show_read") == "true";
|
||||||
|
std::lock_guard guard(db_lock);
|
||||||
|
require_key(request);
|
||||||
|
auto moment = epoch_now();
|
||||||
|
Transaction transaction(db);
|
||||||
|
Statement query(db, R"SQL(
|
||||||
|
SELECT id,topic,ciphertext FROM messages
|
||||||
|
WHERE queue_id=? AND not_before<=? AND expires_at>?
|
||||||
|
AND (? OR read_at IS NULL) ORDER BY id
|
||||||
|
)SQL");
|
||||||
|
query.bind(1, request.matches[1].str()).bind(2, moment).bind(3, moment).bind(4, show_read ? 1LL : 0LL);
|
||||||
|
auto messages = json::array();
|
||||||
|
while (query.next()) messages.push_back(message_row(query));
|
||||||
|
if (!show_read) {
|
||||||
|
Statement mark(db, R"SQL(
|
||||||
|
UPDATE messages SET read_at=? WHERE queue_id=? AND not_before<=?
|
||||||
|
AND expires_at>? AND read_at IS NULL
|
||||||
|
)SQL");
|
||||||
|
mark.bind(1, moment).bind(2, request.matches[1].str()).bind(3, moment).bind(4, moment).next();
|
||||||
|
}
|
||||||
|
transaction.commit();
|
||||||
|
reply(response, 200, {{"messages", messages}});
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
try {
|
||||||
|
initialize();
|
||||||
|
httplib::Server server;
|
||||||
|
server.set_payload_max_length(32768);
|
||||||
|
server.set_pre_routing_handler([](const httplib::Request& request, httplib::Response& response) {
|
||||||
|
if (request.has_header("Range")) {
|
||||||
|
reply(response, 400, {{"error", "range requests are not supported"}});
|
||||||
|
return httplib::Server::HandlerResponse::Handled;
|
||||||
|
}
|
||||||
|
return httplib::Server::HandlerResponse::Unhandled;
|
||||||
|
});
|
||||||
|
server.Get("/api/health", endpoint([](const auto&, auto& response) {
|
||||||
|
reply(response, 200, {{"status", "ok"}});
|
||||||
|
}));
|
||||||
|
queue_routes(server);
|
||||||
|
filter_routes(server);
|
||||||
|
message_routes(server);
|
||||||
|
server.set_mount_point("/", "/srv/lighthouse/public");
|
||||||
|
bool listening = server.listen("0.0.0.0", 8080);
|
||||||
|
sqlite3_close(db);
|
||||||
|
return listening ? 0 : 1;
|
||||||
|
} catch (const std::exception& error) {
|
||||||
|
std::cerr << "startup failed: " << error.what() << '\n';
|
||||||
|
if (db) sqlite3_close(db);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
|
#include <regex>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
using json = nlohmann::json;
|
||||||
|
|
||||||
|
struct HttpError : std::runtime_error {
|
||||||
|
int status;
|
||||||
|
HttpError(int code, const std::string& message) : std::runtime_error(message), status(code) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
inline long long epoch_now() {
|
||||||
|
return std::chrono::duration_cast<std::chrono::seconds>(
|
||||||
|
std::chrono::system_clock::now().time_since_epoch()).count();
|
||||||
|
}
|
||||||
|
|
||||||
|
inline json object_body(const std::string& input) {
|
||||||
|
auto body = json::parse(input, nullptr, false);
|
||||||
|
if (!body.is_object()) throw HttpError(400, "need a JSON object");
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::string text_field(const json& body, const char* name, const std::string& fallback) {
|
||||||
|
if (!body.contains(name)) return fallback;
|
||||||
|
if (!body[name].is_string()) throw HttpError(400, std::string(name) + " must be a string");
|
||||||
|
return body[name].get<std::string>();
|
||||||
|
}
|
||||||
|
|
||||||
|
inline long long number_field(const json& body, const char* name, long long fallback,
|
||||||
|
long long low, long long high) {
|
||||||
|
if (!body.contains(name)) return fallback;
|
||||||
|
const auto& field = body[name];
|
||||||
|
if (!field.is_number_integer() || field < low || field > high)
|
||||||
|
throw HttpError(400, std::string(name) + " out of range");
|
||||||
|
return field.get<long long>();
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::string label_field(const json& body, const std::string& fallback) {
|
||||||
|
auto label = text_field(body, "label", fallback);
|
||||||
|
if (!std::regex_match(label, std::regex("[A-Za-z0-9 _.-]{1,48}")))
|
||||||
|
throw HttpError(400, "bad label");
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Envelope {
|
||||||
|
std::string message;
|
||||||
|
std::string topic;
|
||||||
|
long long release_at;
|
||||||
|
|
||||||
|
static Envelope read(const json& body) {
|
||||||
|
auto encoded = text_field(body, "message", "");
|
||||||
|
if (encoded.empty() || encoded.size() > 5464 || encoded.size() % 4)
|
||||||
|
throw HttpError(400, "message must be 1..4096 bytes of base64 data");
|
||||||
|
static constexpr std::string_view alphabet =
|
||||||
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||||
|
std::string message;
|
||||||
|
message.reserve(encoded.size() / 4 * 3);
|
||||||
|
for (size_t offset = 0; offset < encoded.size(); offset += 4) {
|
||||||
|
unsigned values[4]{};
|
||||||
|
unsigned padding = 0;
|
||||||
|
for (size_t i = 0; i < 4; ++i) {
|
||||||
|
auto c = encoded[offset + i];
|
||||||
|
if (c == '=') {
|
||||||
|
if (i < 2 || offset + 4 != encoded.size())
|
||||||
|
throw HttpError(400, "invalid base64 message");
|
||||||
|
++padding;
|
||||||
|
} else {
|
||||||
|
if (padding) throw HttpError(400, "invalid base64 message");
|
||||||
|
auto digit = alphabet.find(c);
|
||||||
|
if (digit == std::string_view::npos) throw HttpError(400, "invalid base64 message");
|
||||||
|
values[i] = static_cast<unsigned>(digit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ((padding == 1 && (values[2] & 3)) || (padding == 2 && (values[1] & 15)))
|
||||||
|
throw HttpError(400, "invalid base64 message");
|
||||||
|
unsigned word = values[0] << 18 | values[1] << 12 | values[2] << 6 | values[3];
|
||||||
|
message.push_back(static_cast<char>(word >> 16));
|
||||||
|
if (padding < 2) message.push_back(static_cast<char>(word >> 8));
|
||||||
|
if (!padding) message.push_back(static_cast<char>(word));
|
||||||
|
}
|
||||||
|
if (message.empty() || message.size() > 4096)
|
||||||
|
throw HttpError(400, "message must be 1..4096 bytes of base64 data");
|
||||||
|
auto topic = text_field(body, "topic", "inbox");
|
||||||
|
if (!std::regex_match(topic, std::regex("[a-z0-9_.-]{1,32}")))
|
||||||
|
throw HttpError(400, "bad topic");
|
||||||
|
auto delay = number_field(body, "delay_ms", 0, 0, 60000);
|
||||||
|
return {message, topic, epoch_now() + (delay + 999) / 1000};
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
namespace recipe {
|
||||||
|
|
||||||
|
enum class Op : uint8_t { source = 1, cc, listing };
|
||||||
|
struct Program {
|
||||||
|
std::array<Op, 3> code{};
|
||||||
|
size_t size = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
consteval Program compile(std::string_view text) {
|
||||||
|
Program program;
|
||||||
|
unsigned effects = 0;
|
||||||
|
while (!text.empty()) {
|
||||||
|
auto end = text.find('|');
|
||||||
|
auto word = text.substr(0, end);
|
||||||
|
while (!word.empty() && word.front() == ' ') word.remove_prefix(1);
|
||||||
|
while (!word.empty() && word.back() == ' ') word.remove_suffix(1);
|
||||||
|
Op op;
|
||||||
|
unsigned needs, gives;
|
||||||
|
if (word == "source") { op = Op::source; needs = 0; gives = 1; }
|
||||||
|
else if (word == "cc") { op = Op::cc; needs = 1; gives = 2; }
|
||||||
|
else if (word == "listing") { op = Op::listing; needs = 2; gives = 4; }
|
||||||
|
else throw "unknown recipe stage";
|
||||||
|
if ((effects & needs) != needs || (effects & gives) || program.size == program.code.size())
|
||||||
|
throw "recipe stages out of order or repeated";
|
||||||
|
effects |= gives;
|
||||||
|
program.code[program.size++] = op;
|
||||||
|
if (end == std::string_view::npos) break;
|
||||||
|
text.remove_prefix(end + 1);
|
||||||
|
if (text.empty()) throw "empty recipe stage";
|
||||||
|
}
|
||||||
|
if (effects != 7) throw "incomplete filter recipe";
|
||||||
|
return program;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline constexpr auto filter = compile("source | cc | listing");
|
||||||
|
|
||||||
|
template <class Build>
|
||||||
|
void run(const Program& program, Build& build) {
|
||||||
|
for (size_t pc = 0; pc < program.size; ++pc) {
|
||||||
|
switch (program.code[pc]) {
|
||||||
|
case Op::source: build.source(); break;
|
||||||
|
case Op::cc: if (!build.cc()) return; break;
|
||||||
|
case Op::listing: build.listing(); break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cerrno>
|
||||||
|
#include <ctime>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
#include <sys/random.h>
|
||||||
|
|
||||||
|
inline std::string random_hex(size_t count) {
|
||||||
|
std::string bytes(count, '\0');
|
||||||
|
size_t offset = 0;
|
||||||
|
while (offset < count) {
|
||||||
|
auto got = getrandom(bytes.data() + offset, count - offset, 0);
|
||||||
|
if (got < 0 && errno == EINTR) continue;
|
||||||
|
if (got <= 0) throw std::runtime_error("random source failed");
|
||||||
|
offset += static_cast<size_t>(got);
|
||||||
|
}
|
||||||
|
for (auto& byte : bytes) byte = "0123456789abcdef"[static_cast<unsigned char>(byte) & 15];
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::string uuid() {
|
||||||
|
auto value = random_hex(32);
|
||||||
|
value[12] = '4';
|
||||||
|
value[16] = "89ab"[static_cast<unsigned char>(value[16]) & 3];
|
||||||
|
return value.substr(0,8) + "-" + value.substr(8,4) + "-" + value.substr(12,4) +
|
||||||
|
"-" + value.substr(16,4) + "-" + value.substr(20);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::string utc_now() {
|
||||||
|
auto time = std::time(nullptr);
|
||||||
|
std::tm utc{};
|
||||||
|
gmtime_r(&time, &utc);
|
||||||
|
char text[32];
|
||||||
|
std::strftime(text, sizeof(text), "%FT%TZ", &utc);
|
||||||
|
return text;
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
target/
|
||||||
|
data/
|
||||||
|
tests/
|
||||||
Whitespace-only changes.
Generated
+107
@@ -0,0 +1,107 @@
|
|||||||
|
# This file is automatically @generated by Cargo.
|
||||||
|
# It is not intended for manual editing.
|
||||||
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "itoa"
|
||||||
|
version = "1.0.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "memchr"
|
||||||
|
version = "2.8.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "orbit-ctf"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "proc-macro2"
|
||||||
|
version = "1.0.107"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||||
|
dependencies = [
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quote"
|
||||||
|
version = "1.0.47"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde"
|
||||||
|
version = "1.0.229"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||||
|
dependencies = [
|
||||||
|
"serde_core",
|
||||||
|
"serde_derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_core"
|
||||||
|
version = "1.0.229"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||||
|
dependencies = [
|
||||||
|
"serde_derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_derive"
|
||||||
|
version = "1.0.229"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_json"
|
||||||
|
version = "1.0.154"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||||
|
dependencies = [
|
||||||
|
"itoa",
|
||||||
|
"memchr",
|
||||||
|
"serde",
|
||||||
|
"serde_core",
|
||||||
|
"zmij",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "syn"
|
||||||
|
version = "3.0.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-ident"
|
||||||
|
version = "1.0.27"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zmij"
|
||||||
|
version = "1.0.23"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
[package]
|
||||||
|
name = "orbit-ctf"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
serde_json = "1.0"
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
FROM rust:1.90-bookworm AS build
|
||||||
|
WORKDIR /build
|
||||||
|
COPY Cargo.toml Cargo.lock ./
|
||||||
|
COPY src/ ./src/
|
||||||
|
RUN cargo build --release --locked
|
||||||
|
|
||||||
|
FROM debian:bookworm-slim
|
||||||
|
RUN useradd --system --uid 10001 --create-home orbit \
|
||||||
|
&& mkdir /data && chown orbit:orbit /data
|
||||||
|
COPY --from=build /build/target/release/orbit-ctf /usr/local/bin/orbit-ctf
|
||||||
|
USER orbit
|
||||||
|
ENV LISTEN_ADDR=0.0.0.0:8080 DATA_DIR=/data
|
||||||
|
VOLUME ["/data"]
|
||||||
|
EXPOSE 8080
|
||||||
|
ENTRYPOINT ["/usr/local/bin/orbit-ctf"]
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
name: orbital_navigation
|
||||||
|
|
||||||
|
services:
|
||||||
|
orbital_navigation:
|
||||||
|
build: .
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
LISTEN_ADDR: 0.0.0.0:8080
|
||||||
|
DATA_DIR: /data
|
||||||
|
ports:
|
||||||
|
- "8086:8080"
|
||||||
|
volumes:
|
||||||
|
- orbital-data:/data
|
||||||
|
pids_limit: 256
|
||||||
|
mem_limit: 1g
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "bash -c 'exec 3<>/dev/tcp/127.0.0.1/8080'"]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 15
|
||||||
|
volumes:
|
||||||
|
orbital-data:
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,15 @@
|
|||||||
|
use orbit_ctf::Server;
|
||||||
|
use std::net::TcpListener;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
fn main() -> std::io::Result<()> {
|
||||||
|
let addr = std::env::var("LISTEN_ADDR").unwrap_or_else(|_| "127.0.0.1:8080".into());
|
||||||
|
|
||||||
|
let root = PathBuf::from(std::env::var("DATA_DIR").unwrap_or_else(|_| "./data".into()));
|
||||||
|
|
||||||
|
let listener = TcpListener::bind(&addr)?;
|
||||||
|
|
||||||
|
eprintln!("orbit-navigation-service listening on {addr}");
|
||||||
|
|
||||||
|
Server::new(root)?.serve(listener)
|
||||||
|
}
|
||||||
Whitespace-only changes.
@@ -0,0 +1,2 @@
|
|||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
FROM python:3.12-alpine
|
||||||
|
|
||||||
|
RUN apk add --no-cache ttf-dejavu
|
||||||
|
COPY requirements.txt /app/requirements.txt
|
||||||
|
RUN pip install --no-cache-dir -r /app/requirements.txt
|
||||||
|
COPY *.py /app/
|
||||||
|
WORKDIR /app
|
||||||
|
CMD ["gunicorn", "--preload", "--workers", "2", "--threads", "4", "--bind", "0.0.0.0:5000", "app:app"]
|
||||||
@@ -0,0 +1,740 @@
|
|||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json as _json
|
||||||
|
import mimetypes
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from functools import wraps
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from flask import Flask, jsonify, request, send_file, session
|
||||||
|
from werkzeug.security import check_password_hash, generate_password_hash
|
||||||
|
|
||||||
|
from contracts import CONTRACT_DIR, create_contract
|
||||||
|
from database import connect as db, migrate
|
||||||
|
from warehouse_client import CALLBACK_TOKEN as WAREHOUSE_CALLBACK_TOKEN
|
||||||
|
from warehouse_client import get_health as get_warehouse_health
|
||||||
|
from warehouse_client import submit_jobs as submit_warehouse_jobs
|
||||||
|
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.config.update(
|
||||||
|
SECRET_KEY=os.environ["SECRET_KEY"],
|
||||||
|
SESSION_COOKIE_HTTPONLY=True,
|
||||||
|
SESSION_COOKIE_SAMESITE="Lax",
|
||||||
|
SESSION_COOKIE_PATH="/",
|
||||||
|
MAX_CONTENT_LENGTH=32 * 1024,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
migrate()
|
||||||
|
|
||||||
|
|
||||||
|
def now():
|
||||||
|
return datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def body():
|
||||||
|
data = request.get_json(silent=True)
|
||||||
|
return data if isinstance(data, dict) else None
|
||||||
|
|
||||||
|
|
||||||
|
def error(message, status=400):
|
||||||
|
return jsonify(error=message), status
|
||||||
|
|
||||||
|
|
||||||
|
def text(value, field, minimum=1, maximum=200):
|
||||||
|
if not isinstance(value, str) or not minimum <= len(value.strip()) <= maximum:
|
||||||
|
raise ValueError(f"{field} length must be {minimum}..{maximum}")
|
||||||
|
return value.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def auth(role=None):
|
||||||
|
def decorator(handler):
|
||||||
|
@wraps(handler)
|
||||||
|
def wrapped(*args, **kwargs):
|
||||||
|
if "user_id" not in session:
|
||||||
|
return error("authentication required", 401)
|
||||||
|
if role and session["role"] != role:
|
||||||
|
return error("forbidden", 403)
|
||||||
|
return handler(*args, **kwargs)
|
||||||
|
return wrapped
|
||||||
|
return decorator
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
def health():
|
||||||
|
try:
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT 1 FROM users LIMIT 1")
|
||||||
|
except psycopg.Error:
|
||||||
|
return jsonify(status="starting", service="starpost-api"), 503
|
||||||
|
return jsonify(status="ok", service="starpost-api")
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/integrity")
|
||||||
|
def integrity():
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT contract_file FROM users WHERE role='seller' AND contract_file IS NOT NULL")
|
||||||
|
contracts = [row["contract_file"] for row in cur.fetchall()]
|
||||||
|
missing = sum(not (CONTRACT_DIR / filename).is_file() for filename in contracts)
|
||||||
|
return jsonify(contracts=len(contracts), missing_contracts=missing, status="ok" if missing == 0 else "corrupt")
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/warehouse")
|
||||||
|
def warehouse():
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT count(*) delivered FROM orders WHERE status='delivered'")
|
||||||
|
delivered = cur.fetchone()["delivered"]
|
||||||
|
cur.execute("SELECT warehouse_status,count(*) count FROM orders GROUP BY warehouse_status")
|
||||||
|
stages = {row["warehouse_status"]: row["count"] for row in cur.fetchall()}
|
||||||
|
try:
|
||||||
|
warehouse_health = get_warehouse_health()
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return jsonify(bot="ATLAS-7", status="offline", mode="automatic", delivered=delivered, stages=stages), 503
|
||||||
|
if warehouse_health.get("status") != "ok":
|
||||||
|
return jsonify(bot="ATLAS-7", status="offline", mode="automatic", delivered=delivered, stages=stages), 503
|
||||||
|
return jsonify(bot=warehouse_health.get("bot", "ATLAS-7"), status="online", mode="automatic", delivered=delivered, stages=stages)
|
||||||
|
|
||||||
|
|
||||||
|
def worker_token_valid():
|
||||||
|
return request.headers.get("X-Warehouse-Token") == WAREHOUSE_CALLBACK_TOKEN
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/warehouse/pending")
|
||||||
|
def warehouse_pending():
|
||||||
|
if not worker_token_valid():
|
||||||
|
return error("forbidden", 403)
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT id FROM orders WHERE status='pending' ORDER BY id LIMIT 50")
|
||||||
|
return jsonify(cur.fetchall())
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/warehouse/callback")
|
||||||
|
def warehouse_callback():
|
||||||
|
if not worker_token_valid():
|
||||||
|
return error("forbidden", 403)
|
||||||
|
data = body() or {}
|
||||||
|
try:
|
||||||
|
order_id = int(data["order_id"])
|
||||||
|
stage = text(data.get("stage"), "stage", 3, 32)
|
||||||
|
job_id = text(data.get("job_id"), "job_id", 3, 64)
|
||||||
|
except (KeyError, TypeError, ValueError) as exc:
|
||||||
|
return error(str(exc))
|
||||||
|
allowed = {"accepted", "picking", "in_transit", "arriving", "delivered"}
|
||||||
|
if stage not in allowed:
|
||||||
|
return error("invalid warehouse stage")
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
if stage == "delivered":
|
||||||
|
cur.execute("UPDATE orders SET status='delivered',delivered_at=now(),warehouse_status=%s,warehouse_job_id=%s,warehouse_updated_at=now() WHERE id=%s AND status='pending' RETURNING id", (stage, job_id, order_id))
|
||||||
|
else:
|
||||||
|
cur.execute("UPDATE orders SET warehouse_status=%s,warehouse_job_id=%s,warehouse_updated_at=now() WHERE id=%s AND status='pending' RETURNING id", (stage, job_id, order_id))
|
||||||
|
if not cur.fetchone():
|
||||||
|
return error("pending order not found", 404)
|
||||||
|
return jsonify(ok=True, order_id=order_id, job_id=job_id, stage=stage)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/register")
|
||||||
|
def register():
|
||||||
|
data = body()
|
||||||
|
if not data:
|
||||||
|
return error("invalid JSON")
|
||||||
|
try:
|
||||||
|
username, password = text(data.get("username"), "username", 3, 48), text(data.get("password"), "password", 8, 128)
|
||||||
|
role = data.get("role")
|
||||||
|
if role not in ("buyer", "seller"):
|
||||||
|
raise ValueError("role must be buyer or seller")
|
||||||
|
company = tax_id = signature = None
|
||||||
|
if role == "seller":
|
||||||
|
company, tax_id, signature = text(data.get("company_name"), "company_name", 2, 120), text(data.get("tax_id"), "tax_id", 4, 40), text(data.get("signature"), "signature", 4, 512)
|
||||||
|
except ValueError as exc:
|
||||||
|
return error(str(exc))
|
||||||
|
try:
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("INSERT INTO users(username,password_hash,role,company_name,tax_id) VALUES(%s,%s,%s,%s,%s) RETURNING id", (username, generate_password_hash(password), role, company, tax_id))
|
||||||
|
user_id = cur.fetchone()["id"]
|
||||||
|
if role == "seller":
|
||||||
|
cur.execute("UPDATE users SET contract_file=%s WHERE id=%s", (create_contract(user_id, company, tax_id, signature), user_id))
|
||||||
|
else:
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO promo_codes(user_id,code) VALUES(%s,%s)",
|
||||||
|
(user_id, "SP10-" + secrets.token_urlsafe(12).upper()),
|
||||||
|
)
|
||||||
|
except psycopg.errors.UniqueViolation:
|
||||||
|
return error("username already exists", 409)
|
||||||
|
session.clear()
|
||||||
|
session.update(user_id=user_id, username=username, role=role)
|
||||||
|
return jsonify(id=user_id, username=username, role=role), 201
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/login")
|
||||||
|
def login():
|
||||||
|
data = body() or {}
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT * FROM users WHERE username=%s", (data.get("username"),))
|
||||||
|
user = cur.fetchone()
|
||||||
|
if not user or not isinstance(data.get("password"), str) or not check_password_hash(user["password_hash"], data["password"]):
|
||||||
|
return error("invalid credentials", 401)
|
||||||
|
session.clear()
|
||||||
|
session.update(user_id=user["id"], username=user["username"], role=user["role"])
|
||||||
|
return jsonify(id=user["id"], username=user["username"], role=user["role"])
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/logout")
|
||||||
|
def logout():
|
||||||
|
session.clear()
|
||||||
|
return jsonify(ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/me")
|
||||||
|
@auth()
|
||||||
|
def me():
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT id,username,role,balance,company_name,tax_id,contract_file FROM users WHERE id=%s", (session["user_id"],))
|
||||||
|
return jsonify(cur.fetchone())
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/account")
|
||||||
|
@auth()
|
||||||
|
def account_summary():
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id,username,role,balance,company_name,tax_id,created_at
|
||||||
|
FROM users WHERE id=%s
|
||||||
|
""",
|
||||||
|
(session["user_id"],),
|
||||||
|
)
|
||||||
|
user = cur.fetchone()
|
||||||
|
if user["role"] == "buyer":
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT count(*) orders_count,
|
||||||
|
count(*) FILTER (WHERE status='delivered') delivered_count,
|
||||||
|
COALESCE(sum(price),0) spent
|
||||||
|
FROM orders WHERE buyer_id=%s
|
||||||
|
""",
|
||||||
|
(session["user_id"],),
|
||||||
|
)
|
||||||
|
stats = cur.fetchone()
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT o.id,o.status,o.warehouse_status,o.price,o.tracking_code,o.created_at,p.name
|
||||||
|
FROM orders o JOIN products p ON p.id=o.product_id
|
||||||
|
WHERE o.buyer_id=%s ORDER BY o.id DESC LIMIT 5
|
||||||
|
""",
|
||||||
|
(session["user_id"],),
|
||||||
|
)
|
||||||
|
recent_orders = cur.fetchall()
|
||||||
|
cur.execute(
|
||||||
|
"SELECT count(*) reviews_count FROM reviews WHERE buyer_id=%s",
|
||||||
|
(session["user_id"],),
|
||||||
|
)
|
||||||
|
reviews_count = cur.fetchone()["reviews_count"]
|
||||||
|
cur.execute("SELECT code,amount FROM promo_codes WHERE user_id=%s", (session["user_id"],))
|
||||||
|
return jsonify(user=user, stats=stats, reviews_count=reviews_count, recent_orders=recent_orders, promo=cur.fetchone())
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT count(*) products_count,
|
||||||
|
count(*) FILTER (WHERE is_active=true) active_products_count
|
||||||
|
FROM products WHERE seller_id=%s
|
||||||
|
""",
|
||||||
|
(session["user_id"],),
|
||||||
|
)
|
||||||
|
stats = cur.fetchone()
|
||||||
|
cur.execute(
|
||||||
|
"SELECT count(*) reviews_count FROM reviews WHERE seller_id=%s",
|
||||||
|
(session["user_id"],),
|
||||||
|
)
|
||||||
|
reviews_count = cur.fetchone()["reviews_count"]
|
||||||
|
return jsonify(user=user, stats=stats, reviews_count=reviews_count)
|
||||||
|
|
||||||
|
|
||||||
|
def current_promo(code):
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT * FROM promo_codes WHERE user_id=%s AND code=%s", (session["user_id"], code))
|
||||||
|
return conn, cur, cur.fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/promo/credit")
|
||||||
|
@auth("buyer")
|
||||||
|
def credit_promo():
|
||||||
|
data = body() or {}
|
||||||
|
code = data.get("code")
|
||||||
|
if not isinstance(code, str) or not 1 <= len(code) <= 100:
|
||||||
|
return error("invalid promo code")
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT amount FROM promo_codes WHERE user_id=%s AND code=%s", (session["user_id"], code.strip()))
|
||||||
|
promo = cur.fetchone()
|
||||||
|
if not promo:
|
||||||
|
return error("promo code is unavailable", 409)
|
||||||
|
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (promo["amount"], session["user_id"]))
|
||||||
|
return jsonify(credited=promo["amount"], code=code.strip())
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/promo/invalidate")
|
||||||
|
@auth("buyer")
|
||||||
|
def invalidate_promo():
|
||||||
|
data = body() or {}
|
||||||
|
code = data.get("code")
|
||||||
|
if not isinstance(code, str) or not 1 <= len(code) <= 100:
|
||||||
|
return error("invalid promo code")
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("DELETE FROM promo_codes WHERE user_id=%s AND code=%s", (session["user_id"], code.strip()))
|
||||||
|
if cur.rowcount == 0:
|
||||||
|
return error("promo code is unavailable", 409)
|
||||||
|
return jsonify(invalidated=True, code=code.strip())
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/products")
|
||||||
|
def products():
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT p.id,p.name,p.description,p.price,p.created_at,u.company_name seller,
|
||||||
|
(SELECT count(*) FROM reviews r JOIN orders o ON o.id=r.order_id
|
||||||
|
WHERE o.product_id=p.id AND r.is_private=false) review_count,
|
||||||
|
COALESCE((
|
||||||
|
SELECT json_agg(item) FROM (
|
||||||
|
SELECT r.rating,r.body,b.username buyer,r.created_at
|
||||||
|
FROM reviews r
|
||||||
|
JOIN orders o ON o.id=r.order_id
|
||||||
|
JOIN users b ON b.id=r.buyer_id
|
||||||
|
WHERE o.product_id=p.id AND r.is_private=false
|
||||||
|
ORDER BY r.id DESC LIMIT 3
|
||||||
|
) item
|
||||||
|
), '[]'::json) reviews
|
||||||
|
FROM products p JOIN users u ON u.id=p.seller_id
|
||||||
|
WHERE p.is_active=true
|
||||||
|
ORDER BY p.id DESC LIMIT 100
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
return jsonify(cur.fetchall())
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/products/<int:product_id>")
|
||||||
|
def product_details(product_id):
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT p.id,p.name,p.description,p.price,p.created_at,
|
||||||
|
u.company_name seller,u.tax_id seller_tax_id,
|
||||||
|
count(r.id) FILTER (WHERE r.is_private=false) review_count,
|
||||||
|
COALESCE(round(avg(r.rating) FILTER (WHERE r.is_private=false), 1), 0) rating
|
||||||
|
FROM products p
|
||||||
|
JOIN users u ON u.id=p.seller_id
|
||||||
|
LEFT JOIN orders o ON o.product_id=p.id
|
||||||
|
LEFT JOIN reviews r ON r.order_id=o.id
|
||||||
|
WHERE p.id=%s AND p.is_active=true
|
||||||
|
GROUP BY p.id,u.company_name,u.tax_id
|
||||||
|
""",
|
||||||
|
(product_id,),
|
||||||
|
)
|
||||||
|
product = cur.fetchone()
|
||||||
|
if not product:
|
||||||
|
return error("product not found", 404)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT r.id,r.rating,r.body,r.created_at,b.username buyer
|
||||||
|
FROM reviews r
|
||||||
|
JOIN orders o ON o.id=r.order_id
|
||||||
|
JOIN users b ON b.id=r.buyer_id
|
||||||
|
WHERE o.product_id=%s AND r.is_private=false
|
||||||
|
ORDER BY r.id DESC LIMIT 50
|
||||||
|
""",
|
||||||
|
(product_id,),
|
||||||
|
)
|
||||||
|
product["reviews"] = cur.fetchall()
|
||||||
|
return jsonify(product)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/products")
|
||||||
|
@auth("seller")
|
||||||
|
def add_product():
|
||||||
|
data = body() or {}
|
||||||
|
try:
|
||||||
|
name, description, cargo = text(data.get("name"), "name", 2, 100), text(data.get("description"), "description", 2, 500), text(data.get("cargo"), "cargo", 1, 1024)
|
||||||
|
price = int(data.get("price"))
|
||||||
|
if not 1 <= price <= 1000:
|
||||||
|
raise ValueError("price must be 1..1000")
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
return error(str(exc))
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("INSERT INTO products(seller_id,name,description,price,cargo) VALUES(%s,%s,%s,%s,%s) RETURNING id", (session["user_id"], name, description, price, cargo))
|
||||||
|
return jsonify(id=cur.fetchone()["id"]), 201
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/seller/products")
|
||||||
|
@auth("seller")
|
||||||
|
def seller_products():
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT p.id,p.name,p.description,p.price,p.cargo,p.is_active,p.created_at,
|
||||||
|
count(o.id) sales_count,COALESCE(sum(o.price),0) income
|
||||||
|
FROM products p
|
||||||
|
LEFT JOIN orders o ON o.product_id=p.id
|
||||||
|
WHERE p.seller_id=%s
|
||||||
|
GROUP BY p.id
|
||||||
|
ORDER BY p.id DESC
|
||||||
|
""",
|
||||||
|
(session["user_id"],),
|
||||||
|
)
|
||||||
|
return jsonify(cur.fetchall())
|
||||||
|
|
||||||
|
|
||||||
|
@app.patch("/api/seller/products/<int:product_id>")
|
||||||
|
@auth("seller")
|
||||||
|
def update_seller_product(product_id):
|
||||||
|
data = body() or {}
|
||||||
|
try:
|
||||||
|
name = text(data.get("name"), "name", 2, 100)
|
||||||
|
description = text(data.get("description"), "description", 2, 500)
|
||||||
|
price = int(data.get("price"))
|
||||||
|
if not 1 <= price <= 1000:
|
||||||
|
raise ValueError("price must be 1..1000")
|
||||||
|
is_active = data.get("is_active")
|
||||||
|
if not isinstance(is_active, bool):
|
||||||
|
raise ValueError("is_active must be boolean")
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
return error(str(exc))
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE products SET name=%s,description=%s,price=%s,is_active=%s
|
||||||
|
WHERE id=%s AND seller_id=%s RETURNING id,is_active
|
||||||
|
""",
|
||||||
|
(name, description, price, is_active, product_id, session["user_id"]),
|
||||||
|
)
|
||||||
|
product = cur.fetchone()
|
||||||
|
if not product:
|
||||||
|
return error("product not found", 404)
|
||||||
|
return jsonify(product)
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/seller/products/<int:product_id>")
|
||||||
|
@auth("seller")
|
||||||
|
def archive_seller_product(product_id):
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE products SET is_active=false WHERE id=%s AND seller_id=%s RETURNING id",
|
||||||
|
(product_id, session["user_id"]),
|
||||||
|
)
|
||||||
|
if not cur.fetchone():
|
||||||
|
return error("product not found", 404)
|
||||||
|
return jsonify(ok=True, archived=True)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/cart")
|
||||||
|
@auth("buyer")
|
||||||
|
def add_cart():
|
||||||
|
data = body() or {}
|
||||||
|
product_id = data.get("product_id")
|
||||||
|
try:
|
||||||
|
quantity = int(data.get("quantity", 1))
|
||||||
|
if not 1 <= quantity <= 10:
|
||||||
|
raise ValueError("quantity must be 1..10")
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
return error(str(exc))
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT seller_id FROM products WHERE id=%s AND is_active=true", (product_id,))
|
||||||
|
product = cur.fetchone()
|
||||||
|
if not product:
|
||||||
|
return error("product not found", 404)
|
||||||
|
if product["seller_id"] == session["user_id"]:
|
||||||
|
return error("cannot add your own product")
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO cart_items(buyer_id,product_id,quantity) VALUES(%s,%s,%s)
|
||||||
|
ON CONFLICT(buyer_id,product_id) DO UPDATE
|
||||||
|
SET quantity=LEAST(10, cart_items.quantity + EXCLUDED.quantity)
|
||||||
|
RETURNING quantity
|
||||||
|
""",
|
||||||
|
(session["user_id"], product_id, quantity),
|
||||||
|
)
|
||||||
|
quantity = cur.fetchone()["quantity"]
|
||||||
|
return jsonify(ok=True, quantity=quantity), 201
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/cart")
|
||||||
|
@auth("buyer")
|
||||||
|
def get_cart():
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT p.id,p.name,p.description,p.price,c.quantity,u.company_name seller FROM cart_items c JOIN products p ON p.id=c.product_id JOIN users u ON u.id=p.seller_id WHERE c.buyer_id=%s ORDER BY c.created_at", (session["user_id"],))
|
||||||
|
return jsonify(cur.fetchall())
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/cart/<int:product_id>")
|
||||||
|
@auth("buyer")
|
||||||
|
def delete_cart(product_id):
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("DELETE FROM cart_items WHERE buyer_id=%s AND product_id=%s", (session["user_id"], product_id))
|
||||||
|
return jsonify(ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
@app.patch("/api/cart/<int:product_id>")
|
||||||
|
@auth("buyer")
|
||||||
|
def update_cart_quantity(product_id):
|
||||||
|
try:
|
||||||
|
quantity = int((body() or {}).get("quantity"))
|
||||||
|
if not 1 <= quantity <= 10:
|
||||||
|
raise ValueError("quantity must be 1..10")
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
return error(str(exc))
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("UPDATE cart_items SET quantity=%s WHERE buyer_id=%s AND product_id=%s RETURNING quantity", (quantity, session["user_id"], product_id))
|
||||||
|
if not cur.fetchone():
|
||||||
|
return error("cart item not found", 404)
|
||||||
|
return jsonify(ok=True, quantity=quantity)
|
||||||
|
|
||||||
|
|
||||||
|
def order_product(product_id):
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT p.*,u.balance FROM products p CROSS JOIN users u WHERE p.id=%s AND p.is_active=true AND u.id=%s FOR UPDATE OF u", (product_id, session["user_id"]))
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return None, error("product not found", 404)
|
||||||
|
if row["seller_id"] == session["user_id"]:
|
||||||
|
return None, error("cannot buy your own product")
|
||||||
|
if row["balance"] < row["price"]:
|
||||||
|
return None, error("insufficient balance", 409)
|
||||||
|
cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (row["price"], session["user_id"]))
|
||||||
|
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (row["price"], row["seller_id"]))
|
||||||
|
tracking = "ORB-" + secrets.token_hex(8).upper()
|
||||||
|
cur.execute("INSERT INTO orders(buyer_id,product_id,price,status,tracking_code) VALUES(%s,%s,%s,'pending',%s) RETURNING id", (session["user_id"], product_id, row["price"], tracking))
|
||||||
|
return {"id": cur.fetchone()["id"], "status": "pending", "tracking_code": tracking}, None
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/products/<int:product_id>/buy")
|
||||||
|
@auth("buyer")
|
||||||
|
def buy_product(product_id):
|
||||||
|
result, failure = order_product(product_id)
|
||||||
|
if failure:
|
||||||
|
return failure
|
||||||
|
submit_warehouse_jobs([result])
|
||||||
|
return jsonify(result), 201
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/cart/checkout")
|
||||||
|
@auth("buyer")
|
||||||
|
def checkout():
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT balance FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
|
||||||
|
buyer = cur.fetchone()
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT p.id product_id,p.seller_id,p.price,p.is_active,c.quantity
|
||||||
|
FROM cart_items c JOIN products p ON p.id=c.product_id
|
||||||
|
WHERE c.buyer_id=%s ORDER BY c.created_at
|
||||||
|
""",
|
||||||
|
(session["user_id"],),
|
||||||
|
)
|
||||||
|
items = cur.fetchall()
|
||||||
|
if not items:
|
||||||
|
return error("cart is empty", 409)
|
||||||
|
if any(not item["is_active"] for item in items):
|
||||||
|
return error("cart contains archived product", 409)
|
||||||
|
total = sum(item["price"] * item["quantity"] for item in items)
|
||||||
|
if buyer["balance"] < total:
|
||||||
|
return error("insufficient balance", 409)
|
||||||
|
cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (total, session["user_id"]))
|
||||||
|
orders = []
|
||||||
|
for item in items:
|
||||||
|
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (item["price"] * item["quantity"], item["seller_id"]))
|
||||||
|
for _ in range(item["quantity"]):
|
||||||
|
tracking = "ORB-" + secrets.token_hex(8).upper()
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO orders(buyer_id,product_id,price,status,tracking_code) VALUES(%s,%s,%s,'pending',%s) RETURNING id",
|
||||||
|
(session["user_id"], item["product_id"], item["price"], tracking),
|
||||||
|
)
|
||||||
|
orders.append({"id": cur.fetchone()["id"], "status": "pending", "tracking_code": tracking})
|
||||||
|
cur.execute("DELETE FROM cart_items WHERE buyer_id=%s", (session["user_id"],))
|
||||||
|
submit_warehouse_jobs(orders)
|
||||||
|
return jsonify(orders=orders), 201
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/orders")
|
||||||
|
@auth("buyer")
|
||||||
|
def buyer_orders():
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT o.id,o.status,o.warehouse_status,o.warehouse_updated_at,o.tracking_code,o.price,o.created_at,o.delivered_at,p.name,CASE WHEN o.status='delivered' THEN p.cargo ELSE NULL END cargo FROM orders o JOIN products p ON p.id=o.product_id WHERE o.buyer_id=%s ORDER BY o.id DESC", (session["user_id"],))
|
||||||
|
return jsonify(cur.fetchall())
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/seller/sales")
|
||||||
|
@auth("seller")
|
||||||
|
def seller_sales():
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT o.id,o.price,o.status,o.tracking_code,o.created_at,p.name,b.username buyer FROM orders o JOIN products p ON p.id=o.product_id JOIN users b ON b.id=o.buyer_id WHERE p.seller_id=%s ORDER BY o.id DESC", (session["user_id"],))
|
||||||
|
sales = cur.fetchall()
|
||||||
|
return jsonify(income=sum(row["price"] for row in sales), sales=sales)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/orders/<int:order_id>/review")
|
||||||
|
@auth("buyer")
|
||||||
|
def review(order_id):
|
||||||
|
data = body() or {}
|
||||||
|
try:
|
||||||
|
review_body, rating = text(data.get("body"), "body", 1, 1000), int(data.get("rating"))
|
||||||
|
if rating not in range(1, 6):
|
||||||
|
raise ValueError("rating must be 1..5")
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
return error(str(exc))
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT p.seller_id FROM orders o JOIN products p ON p.id=o.product_id WHERE o.id=%s AND o.buyer_id=%s AND o.status='delivered'", (order_id, session["user_id"]))
|
||||||
|
order = cur.fetchone()
|
||||||
|
if not order:
|
||||||
|
return error("delivered order not found", 404)
|
||||||
|
try:
|
||||||
|
cur.execute("INSERT INTO reviews(order_id,buyer_id,seller_id,rating,body,is_private) VALUES(%s,%s,%s,%s,%s,%s) RETURNING id", (order_id, session["user_id"], order["seller_id"], rating, review_body, data.get("private") is True))
|
||||||
|
except psycopg.errors.UniqueViolation:
|
||||||
|
return error("order already reviewed", 409)
|
||||||
|
return jsonify(id=cur.fetchone()["id"]), 201
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/seller/reviews")
|
||||||
|
@auth("seller")
|
||||||
|
def seller_reviews():
|
||||||
|
cursor = request.args.get("cursor")
|
||||||
|
limit_raw = request.args.get("limit")
|
||||||
|
def _b64e(b: bytes) -> str:
|
||||||
|
return base64.urlsafe_b64encode(b).decode().rstrip("=")
|
||||||
|
|
||||||
|
def _b64d(s: str) -> bytes:
|
||||||
|
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
|
||||||
|
|
||||||
|
def _sign(payload_b64: str) -> str:
|
||||||
|
return hmac.new(app.config["SECRET_KEY"].encode(), payload_b64.encode(), hashlib.sha256).hexdigest()[:16]
|
||||||
|
|
||||||
|
def _make_cursor(state: dict) -> str:
|
||||||
|
p = _b64e(_json.dumps(state, separators=(",", ":")).encode())
|
||||||
|
return f"{p}.{_sign(p)}"
|
||||||
|
|
||||||
|
def _parse_cursor(cur_token: str, lim_raw):
|
||||||
|
try:
|
||||||
|
lim = int(lim_raw) if lim_raw is not None else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
lim = None
|
||||||
|
if lim is not None and lim <= 3:
|
||||||
|
return _json.loads(_b64d(cur_token.split(".")[0]).decode())
|
||||||
|
if "." not in cur_token:
|
||||||
|
raise ValueError("missing signature")
|
||||||
|
payload_b64, sig = cur_token.rsplit(".", 1)
|
||||||
|
if not hmac.compare_digest(_sign(payload_b64), sig):
|
||||||
|
raise ValueError("bad cursor signature")
|
||||||
|
return _json.loads(_b64d(payload_b64).decode())
|
||||||
|
|
||||||
|
limit = 20
|
||||||
|
if limit_raw is not None:
|
||||||
|
try:
|
||||||
|
limit = int(limit_raw)
|
||||||
|
if not 1 <= limit <= 100:
|
||||||
|
return error("limit must be 1..100")
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return error("invalid limit")
|
||||||
|
|
||||||
|
if cursor:
|
||||||
|
try:
|
||||||
|
state = _parse_cursor(cursor, limit_raw)
|
||||||
|
except Exception as exc:
|
||||||
|
return error(f"invalid cursor: {exc}", 400)
|
||||||
|
try:
|
||||||
|
q_seller = int(state["seller_id"])
|
||||||
|
q_private = bool(state["is_private"])
|
||||||
|
q_last = int(state["last_id"])
|
||||||
|
except (KeyError, TypeError, ValueError):
|
||||||
|
return error("invalid cursor payload", 400)
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT r.id,r.rating,r.body,r.is_private,r.created_at,p.name,b.username buyer "
|
||||||
|
"FROM reviews r JOIN orders o ON o.id=r.order_id "
|
||||||
|
"JOIN products p ON p.id=o.product_id JOIN users b ON b.id=r.buyer_id "
|
||||||
|
"WHERE r.seller_id=%s AND r.is_private=%s AND r.id < %s "
|
||||||
|
"ORDER BY r.id DESC LIMIT %s",
|
||||||
|
(q_seller, q_private, q_last, limit),
|
||||||
|
)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
next_cursor = None
|
||||||
|
if rows:
|
||||||
|
next_cursor = _make_cursor(
|
||||||
|
{"seller_id": q_seller, "is_private": q_private, "last_id": rows[-1]["id"], "v": 2}
|
||||||
|
)
|
||||||
|
return jsonify(reviews=rows, next_cursor=next_cursor)
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT r.id,r.rating,r.body,r.is_private,r.created_at,p.name,b.username buyer "
|
||||||
|
"FROM reviews r JOIN orders o ON o.id=r.order_id "
|
||||||
|
"JOIN products p ON p.id=o.product_id JOIN users b ON b.id=r.buyer_id "
|
||||||
|
"WHERE r.seller_id=%s AND r.id < %s "
|
||||||
|
"ORDER BY r.id DESC LIMIT %s",
|
||||||
|
(session["user_id"], 1_000_000_000, limit),
|
||||||
|
)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
next_cursor = None
|
||||||
|
if rows:
|
||||||
|
last_private = rows[-1]["is_private"]
|
||||||
|
next_cursor = _make_cursor(
|
||||||
|
{"seller_id": session["user_id"], "is_private": bool(last_private), "last_id": rows[-1]["id"], "v": 2}
|
||||||
|
)
|
||||||
|
return jsonify(reviews=rows, next_cursor=next_cursor)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/contract", methods=["GET", "POST"])
|
||||||
|
@auth("seller")
|
||||||
|
def get_contract():
|
||||||
|
if request.method == "POST":
|
||||||
|
import re
|
||||||
|
contract_id = request.headers.get("X-Contract-Id", "").strip()
|
||||||
|
if not re.fullmatch(r"\d+", contract_id):
|
||||||
|
return error("invalid contract id", 400)
|
||||||
|
_dir = CONTRACT_DIR.resolve()
|
||||||
|
hits = sorted(CONTRACT_DIR.glob(f"contract-{contract_id}-*.pdf"))
|
||||||
|
deleted = 0
|
||||||
|
for path in hits:
|
||||||
|
try:
|
||||||
|
if path.resolve().parent == _dir:
|
||||||
|
path.unlink()
|
||||||
|
deleted += 1
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
if deleted == 0:
|
||||||
|
return error("contract not found", 404)
|
||||||
|
return jsonify(status="deleted", deleted=deleted)
|
||||||
|
|
||||||
|
requested = request.args.get("file")
|
||||||
|
|
||||||
|
if requested:
|
||||||
|
import re
|
||||||
|
m = re.match(r"^\s*contract-(\d+)", requested)
|
||||||
|
if m:
|
||||||
|
uid = m.group(1)
|
||||||
|
hits = sorted(CONTRACT_DIR.glob(f"contract-{uid}-*.pdf"))
|
||||||
|
if hits:
|
||||||
|
return send_file(hits[0], mimetype="application/pdf", download_name=hits[0].name)
|
||||||
|
return error("contract not found", 404)
|
||||||
|
raw = requested.strip()
|
||||||
|
candidates: list[Path] = []
|
||||||
|
candidates.append((CONTRACT_DIR / raw).resolve())
|
||||||
|
candidates.append(Path(raw).resolve())
|
||||||
|
candidates.append(CONTRACT_DIR / raw)
|
||||||
|
candidates.append(Path(raw))
|
||||||
|
for target in candidates:
|
||||||
|
try:
|
||||||
|
if target.is_file():
|
||||||
|
guessed, _ = mimetypes.guess_type(str(target))
|
||||||
|
return send_file(target, mimetype=guessed or "application/octet-stream", download_name=target.name)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return error("contract not found", 404)
|
||||||
|
|
||||||
|
with db() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT contract_file FROM users WHERE id=%s", (session["user_id"],))
|
||||||
|
filename = cur.fetchone()["contract_file"]
|
||||||
|
path = CONTRACT_DIR / filename
|
||||||
|
if not path.is_file():
|
||||||
|
return error("contract not found", 404)
|
||||||
|
return send_file(path, mimetype="application/pdf", download_name="starpost-contract.pdf")
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
import secrets
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from reportlab.lib.pagesizes import A4
|
||||||
|
from reportlab.pdfgen import canvas
|
||||||
|
|
||||||
|
|
||||||
|
CONTRACT_DIR = Path("/contracts")
|
||||||
|
CONTRACT_DIR.mkdir(exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def create_contract(user_id, company, tax_id, signature):
|
||||||
|
CONTRACT_DIR.mkdir(exist_ok=True)
|
||||||
|
filename = f"contract-{user_id}-{secrets.token_hex(8)}.pdf"
|
||||||
|
path = CONTRACT_DIR / filename
|
||||||
|
pdf = canvas.Canvas(str(path), pagesize=A4, pageCompression=0)
|
||||||
|
pdf.setTitle("Starpost marketplace contract")
|
||||||
|
pdf.setFont("Helvetica", 16)
|
||||||
|
pdf.drawString(55, 790, "STARPOST MARKETPLACE CONTRACT")
|
||||||
|
pdf.setFont("Helvetica", 10)
|
||||||
|
lines = [
|
||||||
|
"MARKETPLACE SELLER AGREEMENT",
|
||||||
|
"",
|
||||||
|
"1. PARTIES TO THE AGREEMENT",
|
||||||
|
f"Company Name: {company}",
|
||||||
|
f"Tax Identification Number: {tax_id}",
|
||||||
|
f"Seller Account ID: {user_id}",
|
||||||
|
f"Agreement Date (UTC): {datetime.now(timezone.utc).isoformat()}",
|
||||||
|
"",
|
||||||
|
"2. PURPOSE AND SCOPE OF THE AGREEMENT",
|
||||||
|
"This Agreement establishes the terms and conditions under",
|
||||||
|
"which the Seller may use the Starpost Marketplace platform",
|
||||||
|
"to publish cargo listings, offer goods for sale, receive",
|
||||||
|
"customer orders, and manage marketplace transactions.",
|
||||||
|
"Starpost provides the technical infrastructure necessary",
|
||||||
|
"for publishing listings, processing orders, maintaining",
|
||||||
|
"transaction records, and facilitating marketplace activity.",
|
||||||
|
"The Seller agrees to comply with the terms of this Agreement",
|
||||||
|
"and the operational requirements of the platform.",
|
||||||
|
"",
|
||||||
|
"3. SELLER RIGHTS AND RESPONSIBILITIES",
|
||||||
|
"The Seller may create and manage cargo listings, specify",
|
||||||
|
"prices, update product availability, and receive orders",
|
||||||
|
"through the Starpost Marketplace system.",
|
||||||
|
"The Seller is responsible for ensuring that all submitted",
|
||||||
|
"information is accurate, complete, and up to date.",
|
||||||
|
"Cargo descriptions must correctly represent the goods,",
|
||||||
|
"their condition, quantity, characteristics, and availability.",
|
||||||
|
"The Seller must not publish fraudulent, deceptive, or",
|
||||||
|
"intentionally misleading offers or transaction information.",
|
||||||
|
"The Seller is responsible for fulfilling accepted orders",
|
||||||
|
"and providing reasonable customer support regarding sales,",
|
||||||
|
"delivery conditions, product information, and complaints.",
|
||||||
|
"",
|
||||||
|
"4. STARPOST MARKETPLACE SERVICES",
|
||||||
|
"Starpost provides access to marketplace functionality",
|
||||||
|
"for creating listings, receiving orders, and reviewing",
|
||||||
|
"transaction history and order statuses.",
|
||||||
|
"The platform records relevant sales information and may",
|
||||||
|
"provide tools for calculating and reviewing revenue.",
|
||||||
|
"Starpost may perform maintenance, deploy security updates,",
|
||||||
|
"and modify technical components to maintain platform",
|
||||||
|
"stability, availability, and operational security.",
|
||||||
|
"Temporary interruptions may occur during maintenance",
|
||||||
|
"or due to circumstances outside the platform's control.",
|
||||||
|
"",
|
||||||
|
"5. CARGO LISTINGS AND ORDER PROCESSING",
|
||||||
|
"Each listing must contain a valid description of the goods,",
|
||||||
|
"the applicable price, available quantity, and any relevant",
|
||||||
|
"conditions necessary for a customer to place an order.",
|
||||||
|
"The Seller must review incoming orders and ensure that",
|
||||||
|
"accepted orders are processed in accordance with the",
|
||||||
|
"information published in the corresponding listing.",
|
||||||
|
"Changes to a listing must not intentionally misrepresent",
|
||||||
|
"the terms of an order that has already been accepted.",
|
||||||
|
"The Seller should promptly report technical errors that",
|
||||||
|
"affect order creation, order status, or transaction records.",
|
||||||
|
"",
|
||||||
|
"6. SALES RECORDS AND REVENUE",
|
||||||
|
"Starpost maintains marketplace records relating to orders,",
|
||||||
|
"completed sales, and other supported transaction events.",
|
||||||
|
"These records may be used to calculate marketplace revenue",
|
||||||
|
"and determine the amounts eligible for transfer to the Seller.",
|
||||||
|
"Revenue transfers are subject to the platform's payment",
|
||||||
|
"procedures and the status of the relevant transactions.",
|
||||||
|
"The Seller is responsible for reviewing transaction records",
|
||||||
|
"and reporting discrepancies through the available support",
|
||||||
|
"or dispute resolution procedures.",
|
||||||
|
"Starpost may retain transaction records for accounting,",
|
||||||
|
"security auditing, and investigation of disputed orders.",
|
||||||
|
"",
|
||||||
|
"7. CUSTOMER SUPPORT AND DISPUTE HANDLING",
|
||||||
|
"The Seller is responsible for responding to reasonable",
|
||||||
|
"customer inquiries concerning the Seller's cargo listings",
|
||||||
|
"and the fulfillment of accepted orders.",
|
||||||
|
"In the event of a disagreement regarding an order, the",
|
||||||
|
"parties should review the relevant listing, order details,",
|
||||||
|
"transaction history, and other available evidence.",
|
||||||
|
"Suspected fraudulent activity or technical manipulation",
|
||||||
|
"of marketplace transactions may be subject to investigation.",
|
||||||
|
"The parties should cooperate in resolving disputes and",
|
||||||
|
"provide relevant information when reasonably requested.",
|
||||||
|
"",
|
||||||
|
"8. ACCOUNT SECURITY AND DATA PROTECTION",
|
||||||
|
"The Seller is responsible for maintaining the security",
|
||||||
|
"of the Seller's account and associated authentication data.",
|
||||||
|
"Credentials and authorization secrets must not be disclosed",
|
||||||
|
"to unauthorized persons or exposed through public listings.",
|
||||||
|
"Information submitted to Starpost may be processed to",
|
||||||
|
"operate the marketplace, manage orders, maintain records,",
|
||||||
|
"provide support, and investigate security incidents.",
|
||||||
|
"Customer information must be handled responsibly and used",
|
||||||
|
"only for legitimate purposes connected with marketplace",
|
||||||
|
"operations and order fulfillment.",
|
||||||
|
"",
|
||||||
|
"9. PROHIBITED ACTIVITIES",
|
||||||
|
"The Seller must not intentionally exploit technical flaws",
|
||||||
|
"to create unauthorized orders, manipulate revenue records,",
|
||||||
|
"obtain goods or services without proper authorization,",
|
||||||
|
"or interfere with the normal operation of the platform.",
|
||||||
|
"The Seller must not submit forged business information,",
|
||||||
|
"misuse another user's account, or attempt to gain access",
|
||||||
|
"to information or functions without authorization.",
|
||||||
|
"Starpost may investigate suspected violations and apply",
|
||||||
|
"appropriate restrictions in accordance with its policies.",
|
||||||
|
"",
|
||||||
|
"10. LIABILITY AND LIMITATIONS",
|
||||||
|
"The Seller remains responsible for the accuracy of listings,",
|
||||||
|
"the fulfillment of accepted orders, and the handling of",
|
||||||
|
"customer inquiries relating to the Seller's goods.",
|
||||||
|
"Each party is responsible for its own actions and failures",
|
||||||
|
"to comply with the obligations established by this Agreement.",
|
||||||
|
"Neither party should knowingly provide false information",
|
||||||
|
"or interfere with the proper recording of transactions.",
|
||||||
|
"Any limitation of liability must be interpreted in",
|
||||||
|
"accordance with the applicable terms and governing law.",
|
||||||
|
"",
|
||||||
|
"11. TERM AND TERMINATION",
|
||||||
|
"This Agreement becomes effective upon its acceptance and",
|
||||||
|
"the recording of the Seller's signature or authorization.",
|
||||||
|
"The Agreement remains effective while the Seller uses",
|
||||||
|
"the marketplace, unless terminated in accordance with",
|
||||||
|
"the applicable platform procedures.",
|
||||||
|
"Access may be restricted when there is evidence of fraud,",
|
||||||
|
"unauthorized activity, or a material violation of the",
|
||||||
|
"platform's requirements.",
|
||||||
|
"Termination does not automatically eliminate outstanding",
|
||||||
|
"obligations associated with previously accepted orders,",
|
||||||
|
"completed transactions, or unresolved disputes.",
|
||||||
|
"",
|
||||||
|
"12. FINAL PROVISIONS",
|
||||||
|
"This document records the terms presented to the Seller",
|
||||||
|
"at the time the Agreement is generated.",
|
||||||
|
"Any amendments or additional conditions should be recorded",
|
||||||
|
"in an appropriate form and communicated to the parties.",
|
||||||
|
"Questions concerning the interpretation of this Agreement",
|
||||||
|
"should be addressed through the established support process.",
|
||||||
|
"",
|
||||||
|
"SELLER ACKNOWLEDGMENT",
|
||||||
|
"By signing this Agreement, the Seller confirms that the",
|
||||||
|
"provided company information is accurate and acknowledges",
|
||||||
|
"the responsibilities associated with marketplace activity.",
|
||||||
|
"The Seller agrees to comply with the terms described above",
|
||||||
|
"and to act in good faith when processing customer orders.",
|
||||||
|
"",
|
||||||
|
"Seller Signature / Authorization Key:",
|
||||||
|
]
|
||||||
|
y = 745
|
||||||
|
for line in lines:
|
||||||
|
pdf.drawString(55, y, line)
|
||||||
|
y -= 28
|
||||||
|
for offset in range(0, len(signature), 88):
|
||||||
|
pdf.drawString(55, y, signature[offset:offset + 88])
|
||||||
|
y -= 16
|
||||||
|
pdf.save()
|
||||||
|
return filename
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
|
||||||
|
|
||||||
|
DATABASE_URL = os.environ["DATABASE_URL"]
|
||||||
|
|
||||||
|
|
||||||
|
def connect():
|
||||||
|
return psycopg.connect(DATABASE_URL, row_factory=dict_row)
|
||||||
|
|
||||||
|
|
||||||
|
def migrate():
|
||||||
|
with connect() as connection, connection.cursor() as cursor:
|
||||||
|
cursor.execute("DROP TABLE IF EXISTS promos")
|
||||||
|
cursor.execute("DROP TABLE IF EXISTS private_promos")
|
||||||
|
cursor.execute("ALTER TABLE cart_items ADD COLUMN IF NOT EXISTS quantity INTEGER NOT NULL DEFAULT 1")
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE cart_items ADD CONSTRAINT cart_items_quantity_check CHECK(quantity BETWEEN 1 AND 10);
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL;
|
||||||
|
END $$;
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
cursor.execute("ALTER TABLE products ADD COLUMN IF NOT EXISTS is_active BOOLEAN NOT NULL DEFAULT true")
|
||||||
|
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_status TEXT NOT NULL DEFAULT 'queued'")
|
||||||
|
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_job_id TEXT")
|
||||||
|
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_updated_at TIMESTAMPTZ NOT NULL DEFAULT now()")
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS promo_codes (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
user_id BIGINT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
code TEXT NOT NULL UNIQUE,
|
||||||
|
amount INTEGER NOT NULL DEFAULT 100 CHECK(amount = 100)
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS is_active")
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
DO $$ DECLARE r RECORD; BEGIN
|
||||||
|
FOR r IN SELECT conname FROM pg_constraint
|
||||||
|
WHERE conrelid = 'promo_codes'::regclass AND contype = 'c' LOOP
|
||||||
|
EXECUTE format('ALTER TABLE promo_codes DROP CONSTRAINT %I', r.conname);
|
||||||
|
END LOOP;
|
||||||
|
ALTER TABLE promo_codes ADD CONSTRAINT promo_codes_amount_check CHECK(amount = 100);
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL;
|
||||||
|
END $$;
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
cursor.execute("ALTER TABLE promo_codes ALTER COLUMN amount SET DEFAULT 100")
|
||||||
|
cursor.execute("ALTER TABLE users ALTER COLUMN balance SET DEFAULT 100")
|
||||||
|
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS credited_at")
|
||||||
|
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS invalidated_at")
|
||||||
|
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS created_at")
|
||||||
|
cursor.execute("CREATE INDEX IF NOT EXISTS orders_buyer_idx ON orders(buyer_id, id DESC)")
|
||||||
|
cursor.execute("CREATE INDEX IF NOT EXISTS orders_product_idx ON orders(product_id)")
|
||||||
|
cursor.execute("CREATE INDEX IF NOT EXISTS products_seller_idx ON products(seller_id, id DESC)")
|
||||||
|
cursor.execute("CREATE INDEX IF NOT EXISTS reviews_seller_idx ON reviews(seller_id, id DESC)")
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
Flask==3.1.0
|
||||||
|
gunicorn==23.0.0
|
||||||
|
psycopg[binary]==3.2.3
|
||||||
|
reportlab==4.2.5
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
|
||||||
|
WAREHOUSE_URL = os.getenv("WAREHOUSE_URL", "http://warehouse:6000")
|
||||||
|
CALLBACK_TOKEN = os.environ["WAREHOUSE_CALLBACK_TOKEN"]
|
||||||
|
|
||||||
|
|
||||||
|
def submit_jobs(orders):
|
||||||
|
for order in orders:
|
||||||
|
try:
|
||||||
|
payload = json.dumps({"order_id": order["id"]}).encode()
|
||||||
|
request = urllib.request.Request(
|
||||||
|
f"{WAREHOUSE_URL}/jobs",
|
||||||
|
data=payload,
|
||||||
|
headers={"Content-Type": "application/json", "X-Warehouse-Token": CALLBACK_TOKEN},
|
||||||
|
method="POST",
|
||||||
|
)
|
||||||
|
with urllib.request.urlopen(request, timeout=.4):
|
||||||
|
pass
|
||||||
|
except (OSError, ValueError):
|
||||||
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
def get_health():
|
||||||
|
with urllib.request.urlopen(f"{WAREHOUSE_URL}/health", timeout=.5) as response:
|
||||||
|
return json.loads(response.read())
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
name: starpost.yml
|
||||||
|
|
||||||
|
services:
|
||||||
|
web:
|
||||||
|
restart: unless-stopped
|
||||||
|
build: ./web
|
||||||
|
pids_limit: 256
|
||||||
|
mem_limit: 64M
|
||||||
|
cpus: 0.25
|
||||||
|
ports:
|
||||||
|
- 8090:80
|
||||||
|
depends_on:
|
||||||
|
api:
|
||||||
|
condition: service_healthy
|
||||||
|
|
||||||
|
api:
|
||||||
|
restart: unless-stopped
|
||||||
|
build: ./api
|
||||||
|
pids_limit: 256
|
||||||
|
mem_limit: 256M
|
||||||
|
cpus: 1.0
|
||||||
|
volumes:
|
||||||
|
- ./contracts:/contracts
|
||||||
|
environment:
|
||||||
|
- DATABASE_URL=postgresql://starpost:starpost@postgres/starpost
|
||||||
|
- SECRET_KEY=starpost-development-session-key-change-before-production
|
||||||
|
- WAREHOUSE_URL=http://warehouse:6000
|
||||||
|
- WAREHOUSE_CALLBACK_TOKEN=starpost-warehouse-callback-token
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:5000/health', timeout=2)"]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 15
|
||||||
|
|
||||||
|
warehouse:
|
||||||
|
restart: unless-stopped
|
||||||
|
build: ./warehouse
|
||||||
|
pids_limit: 128
|
||||||
|
mem_limit: 64M
|
||||||
|
cpus: 0.25
|
||||||
|
environment:
|
||||||
|
- WAREHOUSE_API_URL=http://api:5000
|
||||||
|
- WAREHOUSE_CALLBACK_TOKEN=starpost-warehouse-callback-token
|
||||||
|
depends_on:
|
||||||
|
api:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:6000/health', timeout=2)"]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 15
|
||||||
|
|
||||||
|
postgres:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
restart: unless-stopped
|
||||||
|
pids_limit: 256
|
||||||
|
mem_limit: 256M
|
||||||
|
cpus: 0.5
|
||||||
|
environment:
|
||||||
|
- POSTGRES_DB=starpost
|
||||||
|
- POSTGRES_USER=starpost
|
||||||
|
- POSTGRES_PASSWORD=starpost
|
||||||
|
volumes:
|
||||||
|
- ./postgres:/var/lib/postgresql/data
|
||||||
|
- ./db/init.sql:/docker-entrypoint-initdb.d/01-init.sql:ro
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U starpost -d starpost && psql -U starpost -d starpost -tAc 'SELECT 1 FROM users LIMIT 1' >/dev/null"]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 30
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
CREATE TABLE users (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
username TEXT NOT NULL UNIQUE,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
role TEXT NOT NULL CHECK(role IN ('buyer', 'seller')),
|
||||||
|
balance INTEGER NOT NULL DEFAULT 100,
|
||||||
|
company_name TEXT,
|
||||||
|
tax_id TEXT,
|
||||||
|
contract_file TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE TABLE products (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
seller_id BIGINT NOT NULL REFERENCES users(id),
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
description TEXT NOT NULL,
|
||||||
|
price INTEGER NOT NULL CHECK(price > 0),
|
||||||
|
cargo TEXT NOT NULL,
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE TABLE cart_items (
|
||||||
|
buyer_id BIGINT REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
product_id BIGINT NOT NULL REFERENCES products(id) ON DELETE CASCADE,
|
||||||
|
quantity INTEGER NOT NULL DEFAULT 1 CHECK(quantity BETWEEN 1 AND 10),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY(buyer_id, product_id)
|
||||||
|
);
|
||||||
|
CREATE TABLE orders (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
buyer_id BIGINT NOT NULL REFERENCES users(id),
|
||||||
|
product_id BIGINT NOT NULL REFERENCES products(id),
|
||||||
|
price INTEGER NOT NULL,
|
||||||
|
status TEXT NOT NULL CHECK(status IN ('pending', 'delivered')),
|
||||||
|
tracking_code TEXT NOT NULL UNIQUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
delivered_at TIMESTAMPTZ
|
||||||
|
,warehouse_status TEXT NOT NULL DEFAULT 'queued'
|
||||||
|
,warehouse_job_id TEXT
|
||||||
|
,warehouse_updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE TABLE reviews (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
order_id BIGINT NOT NULL UNIQUE REFERENCES orders(id),
|
||||||
|
buyer_id BIGINT NOT NULL REFERENCES users(id),
|
||||||
|
seller_id BIGINT NOT NULL REFERENCES users(id),
|
||||||
|
rating INTEGER NOT NULL CHECK(rating BETWEEN 1 AND 5),
|
||||||
|
body TEXT NOT NULL,
|
||||||
|
is_private BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE INDEX orders_pending_idx ON orders(status) WHERE status = 'pending';
|
||||||
|
CREATE TABLE promo_codes (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
user_id BIGINT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
code TEXT NOT NULL UNIQUE,
|
||||||
|
amount INTEGER NOT NULL DEFAULT 100 CHECK(amount = 100)
|
||||||
|
);
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
16
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Whitespace-only changes.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 1392 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user