File size: 2,514 Bytes
30fa1aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""EatBack inside the browser (Pyodide). Same routes and rules as server/app.py, no HTTP server:
the page's fetch('/api/...') calls are handed to handle() by eatback-worker.js.

Each visitor gets their own demo database, kept in the browser (IndexedDB) and reset to the
"ready" demo when the school day changes.
"""
from __future__ import annotations

import json
import traceback
from urllib.parse import parse_qs, urlparse

import app
import devices
from db import LOCK, one, run, settings
from seed import SEED_VERSION, seed
from util import today

app.lan_urls = lambda: []  # no LAN in the browser


def _boot() -> None:
    with LOCK:
        stored = one("SELECT value FROM settings WHERE key = 'seed_version'")
        day = one("SELECT value FROM settings WHERE key = 'browser_seed_day'")
        fresh_day = (day or {}).get("value") != today()
        if not one("SELECT COUNT(*) AS n FROM menus")["n"] or (stored or {}).get("value") != str(SEED_VERSION) or fresh_day:
            seed("ready")
            run("INSERT INTO settings (key, value) VALUES ('browser_seed_day', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", today())
        devices.set_stable_band(settings()["stable_band_g"])
        app.bump()


def handle(method: str, path: str, body_text: str | None) -> str:
    """Returns JSON: {"status": int, "body": str} — same answers as the laptop server."""
    url = urlparse(path)
    method = method.upper()
    handler = app.ROUTES.get((method, url.path))
    if not handler:
        return json.dumps({"status": 404, "body": json.dumps({"error": "not found"})})
    try:
        body = {}
        if method == "POST" and body_text:
            try:
                body = json.loads(body_text)
            except json.JSONDecodeError:
                app.fail(400, "invalid JSON")
        with LOCK:
            out = handler(parse_qs(url.query), body)
        return json.dumps({"status": 200, "body": json.dumps(out, ensure_ascii=False, default=str)}, ensure_ascii=False)
    except app.HttpError as e:
        return json.dumps({"status": e.status, "body": json.dumps({"error": str(e)}, ensure_ascii=False)}, ensure_ascii=False)
    except Exception as e:  # noqa: BLE001 — report, never break the page
        traceback.print_exc()
        return json.dumps({"status": 500, "body": json.dumps({"error": str(e)}, ensure_ascii=False)}, ensure_ascii=False)


def sim_tick() -> None:
    devices.sim_tick()


def version() -> int:
    return app.state["version"]


_boot()