#!/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", "kind", "title", "author", "intro", "quote", "question", "options", "prompt", "pairs", "shelves", "items", "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: kind = book.get("kind") if kind not in ("quiz", "memory", "shelf"): raise ValueError(f"Boek {book['id']} heeft een onbekend soort opdracht.") 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}'.") if kind == "quiz": answer = book.get("answer") options = book.get("options") if not isinstance(options, list) or len(options) < 2: 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.") if kind == "memory": pairs = book.get("pairs") if not isinstance(pairs, list) or len(pairs) < 2: raise ValueError(f"Boek {book['id']} heeft te weinig memoryparen.") pair_ids = [pair.get("id") for pair in pairs] if len(pair_ids) != len(set(pair_ids)): raise ValueError(f"Boek {book['id']} heeft dubbele memoryparen.") for pair in pairs: for field in ("id", "label", "emblem"): if not isinstance(pair.get(field), str) or not pair[field]: raise ValueError(f"Memorypaar in {book['id']} mist '{field}'.") if kind == "shelf": shelves = book.get("shelves") items = book.get("items") if not isinstance(shelves, list) or not shelves: raise ValueError(f"Boek {book['id']} heeft geen rekken.") if not isinstance(items, list) or not items: raise ValueError(f"Boek {book['id']} heeft geen boeken om te plaatsen.") shelf_ids = {shelf.get("id") for shelf in shelves} if len(shelf_ids) != len(shelves): raise ValueError(f"Boek {book['id']} heeft dubbele rekken.") item_ids = [item.get("id") for item in items] if len(item_ids) != len(set(item_ids)): raise ValueError(f"Boek {book['id']} heeft dubbele boeken.") for item in items: if item.get("shelf") not in shelf_ids: raise ValueError(f"Boek {book['id']} verwijst naar een onbekend rek.") for field in ("id", "label", "shelf", "emblem"): if not isinstance(item.get(field), str) or not item[field]: raise ValueError(f"Boek in {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", "Open de vier 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/complete", "/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) elif path == "/api/complete": self.handle_complete(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 book["kind"] != "quiz": self.send_json( HTTPStatus.BAD_REQUEST, {"ok": False, "error": "Dit boek heeft geen quizvraag."}, ) 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_complete(self, payload: dict[str, Any]) -> None: book_id = payload.get("bookId") 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 book["kind"] not in ("memory", "shelf"): self.send_json( HTTPStatus.BAD_REQUEST, {"ok": False, "error": "Dit boek heeft geen minigame."}, ) return self.send_json( HTTPStatus.OK, { "ok": True, "letter": book["letter"], "explanation": book["fact"], "done": book["done"], }, ) 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()