280 lines
8.4 KiB
Python
280 lines
8.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Kleine server voor Mama's Geheime Leeshoek.
|
|
|
|
Serveert de statische game, controleert de antwoorden van de boeken en geeft de
|
|
cadeauboncode pas vrij wanneer alle boeken gelezen zijn.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import sys
|
|
from dataclasses import dataclass
|
|
from http import HTTPStatus
|
|
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
|
from pathlib import Path
|
|
from typing import Any
|
|
from urllib.parse import urlparse
|
|
|
|
BASE_DIR = Path(__file__).resolve().parent
|
|
STATIC_DIR = BASE_DIR / "static"
|
|
GAME_FILE = BASE_DIR / "game.json"
|
|
DEFAULT_CODE = "VUL-JE-CADEAUBONCODE-IN"
|
|
MAX_BODY_BYTES = 16 * 1024
|
|
PUBLIC_BOOK_FIELDS = (
|
|
"id",
|
|
"title",
|
|
"author",
|
|
"intro",
|
|
"quote",
|
|
"question",
|
|
"options",
|
|
"hint",
|
|
"color",
|
|
"color2",
|
|
"ink",
|
|
"emblem",
|
|
)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class GameData:
|
|
books: dict[str, dict[str, Any]]
|
|
config: dict[str, Any]
|
|
gift_code: str
|
|
|
|
|
|
def load_game(path: Path) -> dict[str, Any]:
|
|
with path.open(encoding="utf-8") as handle:
|
|
game = json.load(handle)
|
|
|
|
books = game.get("books")
|
|
if not isinstance(books, list) or not books:
|
|
raise ValueError("game.json moet een niet-lege 'books'-lijst bevatten.")
|
|
|
|
ids = [book["id"] for book in books]
|
|
if len(ids) != len(set(ids)):
|
|
raise ValueError("Elke boek-id moet uniek zijn.")
|
|
|
|
for book in books:
|
|
answer = book.get("answer")
|
|
options = book.get("options")
|
|
if not isinstance(options, list) or not options:
|
|
raise ValueError(f"Boek {book['id']} heeft geen antwoordopties.")
|
|
if (
|
|
isinstance(answer, bool)
|
|
or not isinstance(answer, int)
|
|
or not 0 <= answer < len(options)
|
|
):
|
|
raise ValueError(f"Boek {book['id']} heeft een ongeldig antwoord.")
|
|
for field in ("letter", "fact", "done", "hint"):
|
|
if not isinstance(book.get(field), str) or not book[field]:
|
|
raise ValueError(f"Boek {book['id']} mist '{field}'.")
|
|
|
|
return game
|
|
|
|
|
|
def public_book(book: dict[str, Any]) -> dict[str, Any]:
|
|
return {field: book[field] for field in PUBLIC_BOOK_FIELDS if field in book}
|
|
|
|
|
|
def public_config(game: dict[str, Any]) -> dict[str, Any]:
|
|
return {
|
|
"recipient": os.environ.get("RECIPIENT", game.get("recipient", "Mama")),
|
|
"eventDate": os.environ.get("EVENT_DATE", game.get("eventDate", "vandaag")),
|
|
"title": os.environ.get("GAME_TITLE", game.get("title", "Mama's Geheime Leeshoek")),
|
|
"subtitle": os.environ.get(
|
|
"GAME_SUBTITLE",
|
|
game.get("subtitle", "Lees de acht boeken en open de geheime lade."),
|
|
),
|
|
"books": [public_book(book) for book in game["books"]],
|
|
}
|
|
|
|
|
|
class GameServer(ThreadingHTTPServer):
|
|
def __init__(self, address: tuple[str, int], data: GameData) -> None:
|
|
self.data = data
|
|
super().__init__(address, GameRequestHandler)
|
|
|
|
|
|
class GameRequestHandler(SimpleHTTPRequestHandler):
|
|
server_version = "MamaBoekGame/1.0"
|
|
|
|
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
super().__init__(*args, directory=str(STATIC_DIR), **kwargs)
|
|
|
|
@property
|
|
def data(self) -> GameData:
|
|
return self.server.data # type: ignore[attr-defined]
|
|
|
|
def end_headers(self) -> None:
|
|
self.send_header("X-Content-Type-Options", "nosniff")
|
|
self.send_header("Referrer-Policy", "no-referrer")
|
|
self.send_header("X-Frame-Options", "SAMEORIGIN")
|
|
self.send_header(
|
|
"Cache-Control",
|
|
"no-store" if self.path.startswith("/api/") else "no-cache",
|
|
)
|
|
super().end_headers()
|
|
|
|
def do_GET(self) -> None:
|
|
path = urlparse(self.path).path
|
|
if path == "/api/config":
|
|
self.send_json(HTTPStatus.OK, self.data.config)
|
|
return
|
|
if path == "/healthz":
|
|
self.send_json(HTTPStatus.OK, {"ok": True})
|
|
return
|
|
super().do_GET()
|
|
|
|
def do_POST(self) -> None:
|
|
path = urlparse(self.path).path
|
|
if path not in ("/api/solve", "/api/reveal"):
|
|
self.send_json(HTTPStatus.NOT_FOUND, {"ok": False, "error": "Onbekend pad."})
|
|
return
|
|
|
|
payload = self.read_json()
|
|
if payload is None:
|
|
self.send_json(
|
|
HTTPStatus.BAD_REQUEST,
|
|
{"ok": False, "error": "Ongeldige aanvraag."},
|
|
)
|
|
return
|
|
|
|
if path == "/api/solve":
|
|
self.handle_solve(payload)
|
|
else:
|
|
self.handle_reveal(payload)
|
|
|
|
def handle_solve(self, payload: dict[str, Any]) -> None:
|
|
book_id = payload.get("bookId")
|
|
answer = payload.get("answer")
|
|
book = self.data.books.get(book_id) if isinstance(book_id, str) else None
|
|
|
|
if book is None:
|
|
self.send_json(
|
|
HTTPStatus.NOT_FOUND,
|
|
{"ok": False, "error": "Dit boek staat niet in de kast."},
|
|
)
|
|
return
|
|
|
|
if (
|
|
isinstance(answer, bool)
|
|
or not isinstance(answer, int)
|
|
or not 0 <= answer < len(book["options"])
|
|
):
|
|
self.send_json(
|
|
HTTPStatus.BAD_REQUEST,
|
|
{"ok": False, "error": "Ongeldige aanvraag."},
|
|
)
|
|
return
|
|
|
|
if answer == book["answer"]:
|
|
self.send_json(
|
|
HTTPStatus.OK,
|
|
{
|
|
"ok": True,
|
|
"letter": book["letter"],
|
|
"explanation": book["fact"],
|
|
"done": book["done"],
|
|
},
|
|
)
|
|
return
|
|
|
|
self.send_json(
|
|
HTTPStatus.OK,
|
|
{
|
|
"ok": False,
|
|
"error": "Nog niet helemaal. Lees de vraag nog eens rustig.",
|
|
"hint": book["hint"],
|
|
},
|
|
)
|
|
|
|
def handle_reveal(self, payload: dict[str, Any]) -> None:
|
|
completed = payload.get("completed")
|
|
if not isinstance(completed, list) or not all(
|
|
isinstance(item, str) for item in completed
|
|
):
|
|
self.send_json(
|
|
HTTPStatus.BAD_REQUEST,
|
|
{"ok": False, "error": "Ongeldige aanvraag."},
|
|
)
|
|
return
|
|
|
|
missing = sorted(set(self.data.books).difference(completed))
|
|
if missing:
|
|
self.send_json(
|
|
HTTPStatus.CONFLICT,
|
|
{
|
|
"ok": False,
|
|
"error": "De leeshoek is nog niet volledig gelezen.",
|
|
"missing": missing,
|
|
},
|
|
)
|
|
return
|
|
|
|
self.send_json(
|
|
HTTPStatus.OK,
|
|
{
|
|
"ok": True,
|
|
"code": self.data.gift_code,
|
|
"recipient": self.data.config["recipient"],
|
|
"eventDate": self.data.config["eventDate"],
|
|
},
|
|
)
|
|
|
|
def read_json(self) -> dict[str, Any] | None:
|
|
try:
|
|
length = int(self.headers.get("Content-Length", "0"))
|
|
except ValueError:
|
|
return None
|
|
|
|
if length <= 0 or length > MAX_BODY_BYTES:
|
|
return None
|
|
|
|
try:
|
|
payload = json.loads(self.rfile.read(length))
|
|
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
return None
|
|
|
|
return payload if isinstance(payload, dict) else None
|
|
|
|
def send_json(self, status: HTTPStatus, payload: dict[str, Any]) -> None:
|
|
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
|
|
def main() -> None:
|
|
game = load_game(GAME_FILE)
|
|
gift_code = (os.environ.get("GIFT_CODE") or DEFAULT_CODE).strip()
|
|
data = GameData(
|
|
books={book["id"]: book for book in game["books"]},
|
|
config=public_config(game),
|
|
gift_code=gift_code,
|
|
)
|
|
|
|
port = int(os.environ.get("PORT", "8000"))
|
|
if gift_code == DEFAULT_CODE:
|
|
print(
|
|
"WAARSCHUWING: GIFT_CODE is niet ingesteld; de placeholder wordt getoond.",
|
|
file=sys.stderr,
|
|
)
|
|
|
|
server = GameServer(("0.0.0.0", port), data)
|
|
print(f"Boekenspel draait op http://0.0.0.0:{port}", flush=True)
|
|
try:
|
|
server.serve_forever()
|
|
except KeyboardInterrupt:
|
|
pass
|
|
finally:
|
|
server.server_close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|