This commit is contained in:
1 parent
94f1021fd0
commit
2aad61c81f
12 files changed
+2673
No files matched your search
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Kleine server voor het sloopspel.
|
||||
|
||||
Serveert de statische game en geeft de cadeauboncode pas vrij wanneer de
|
||||
client meldt dat alle objecten gesloopt zijn.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from http import HTTPStatus
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
STATIC_DIR = BASE_DIR / "static"
|
||||
GAME_FILE = BASE_DIR / "game.json"
|
||||
|
||||
with GAME_FILE.open(encoding="utf-8") as handle:
|
||||
GAME = json.load(handle)
|
||||
|
||||
REQUIRED_OBJECTS = frozenset(item["id"] for item in GAME["objects"])
|
||||
DEFAULT_CODE = "VUL-JE-CADEAUBONCODE-IN"
|
||||
GIFT_CODE = (os.environ.get("GIFT_CODE") or DEFAULT_CODE).strip()
|
||||
MAX_BODY_BYTES = 16 * 1024
|
||||
|
||||
|
||||
def public_config() -> dict:
|
||||
config = {
|
||||
"recipient": GAME.get("recipient", "Jos"),
|
||||
"eventDate": GAME.get("eventDate", "18 oktober"),
|
||||
"title": GAME.get("title", "De Grote Sloop"),
|
||||
"subtitle": GAME.get("subtitle", "Sloop de kamer, vind je cadeaubon"),
|
||||
"objects": GAME["objects"],
|
||||
}
|
||||
config["recipient"] = os.environ.get("RECIPIENT", config["recipient"])
|
||||
config["eventDate"] = os.environ.get("EVENT_DATE", config["eventDate"])
|
||||
config["title"] = os.environ.get("GAME_TITLE", config["title"])
|
||||
config["subtitle"] = os.environ.get("GAME_SUBTITLE", config["subtitle"])
|
||||
return config
|
||||
|
||||
|
||||
class GameRequestHandler(SimpleHTTPRequestHandler):
|
||||
server_version = "JosSloopGame/1.0"
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, directory=str(STATIC_DIR), **kwargs)
|
||||
|
||||
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, public_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 != "/api/reveal":
|
||||
self.send_json(HTTPStatus.NOT_FOUND, {"ok": False, "error": "Onbekend pad."})
|
||||
return
|
||||
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
except ValueError:
|
||||
length = 0
|
||||
if length <= 0 or length > MAX_BODY_BYTES:
|
||||
self.send_json(
|
||||
HTTPStatus.BAD_REQUEST,
|
||||
{"ok": False, "error": "Ongeldige aanvraag."},
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
payload = json.loads(self.rfile.read(length))
|
||||
except (json.JSONDecodeError, UnicodeDecodeError):
|
||||
self.send_json(
|
||||
HTTPStatus.BAD_REQUEST,
|
||||
{"ok": False, "error": "Ongeldige aanvraag."},
|
||||
)
|
||||
return
|
||||
|
||||
completed = payload.get("completed") if isinstance(payload, dict) else None
|
||||
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(REQUIRED_OBJECTS.difference(completed))
|
||||
if missing:
|
||||
self.send_json(
|
||||
HTTPStatus.CONFLICT,
|
||||
{
|
||||
"ok": False,
|
||||
"error": "De kamer is nog niet volledig gesloopt.",
|
||||
"missing": missing,
|
||||
},
|
||||
)
|
||||
return
|
||||
|
||||
self.send_json(
|
||||
HTTPStatus.OK,
|
||||
{
|
||||
"ok": True,
|
||||
"code": GIFT_CODE,
|
||||
"recipient": public_config()["recipient"],
|
||||
"eventDate": public_config()["eventDate"],
|
||||
},
|
||||
)
|
||||
|
||||
def send_json(self, status: HTTPStatus, payload: dict) -> 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:
|
||||
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 = ThreadingHTTPServer(("0.0.0.0", port), GameRequestHandler)
|
||||
print(f"Sloopspel 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()
|
||||
Reference in new issue
Block a user