feat: add resumable sudoku game
This commit is contained in:
1 parent
010871474b
commit
83e958e840
12 files changed
+399
-3
No files matched your search
+54
-3
@@ -18,6 +18,7 @@ from .belki.applications import ApplicationError, ApplicationStore, validate_app
|
||||
from .belki.google_sheets_export import GoogleSheetsExportService
|
||||
from .belki.identity import IdentityDirectory
|
||||
from .belki.image_host import ImageHostClient, ImageHostError
|
||||
from .sudoku import SudokuError, SudokuStore
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -25,6 +26,7 @@ WEB_ROOT = ROOT / "web"
|
||||
_HISTORY_STORE: CalculationStore | None = None
|
||||
_IDENTITY_DIR: IdentityDirectory | None = None
|
||||
_APPLICATION_STORE: ApplicationStore | None = None
|
||||
_SUDOKU_STORE: SudokuStore | None = None
|
||||
_ADMIN_SESSIONS: dict[str, float] = {}
|
||||
_ADMIN_SESSIONS_LOCK = threading.Lock()
|
||||
_ISSUED_WEB_UPLOAD_URLS: dict[str, float] = {}
|
||||
@@ -166,6 +168,19 @@ def history_store() -> CalculationStore:
|
||||
return _HISTORY_STORE
|
||||
|
||||
|
||||
def sudoku_store() -> SudokuStore:
|
||||
"""Return the lazily initialized store for resumable Sudoku games."""
|
||||
global _SUDOKU_STORE
|
||||
if _SUDOKU_STORE is None:
|
||||
_SUDOKU_STORE = SudokuStore.from_environment()
|
||||
return _SUDOKU_STORE
|
||||
|
||||
|
||||
def public_sudoku_game(game: dict) -> dict:
|
||||
"""Keep the answer key on the server while returning a playable game."""
|
||||
return {key: value for key, value in game.items() if key != "solution"}
|
||||
|
||||
|
||||
def identity_dir() -> IdentityDirectory:
|
||||
"""Лениво создаёт справочник персонажей из окружения."""
|
||||
global _IDENTITY_DIR
|
||||
@@ -311,6 +326,17 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if path in ("/applications", "/applications/"):
|
||||
self._file(WEB_ROOT / "applications.html")
|
||||
return
|
||||
if path in ("/sudoku", "/sudoku/"):
|
||||
self._file(WEB_ROOT / "sudoku.html")
|
||||
return
|
||||
if path == "/api/sudoku/games":
|
||||
try:
|
||||
nickname = parse_qs(urlparse(self.path).query).get("nickname", [""])[0]
|
||||
game = sudoku_store().current(nickname)
|
||||
self._json(200, {"game": public_sudoku_game(game) if game else None})
|
||||
except SudokuError as exc:
|
||||
self._json(400, {"error": str(exc)})
|
||||
return
|
||||
if path == "/api/admin/session":
|
||||
self._json(200, {"authenticated": self._admin_session_authorized()})
|
||||
return
|
||||
@@ -374,13 +400,22 @@ class Handler(BaseHTTPRequestHandler):
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
"""Обрабатывает вход, авторизацию и создание заявок через POST API."""
|
||||
parsed = urlparse(self.path)
|
||||
is_sudoku_create = parsed.path == "/api/sudoku/games"
|
||||
is_sudoku_regenerate = parsed.path.startswith("/api/sudoku/games/") and parsed.path.endswith("/regenerate")
|
||||
if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity",
|
||||
"/api/applications"):
|
||||
"/api/applications") and not is_sudoku_create and not is_sudoku_regenerate:
|
||||
self._json(404, {"error": "Не найдено"})
|
||||
return
|
||||
try:
|
||||
payload = self._read_json_body()
|
||||
if self.path == "/api/admin/auth":
|
||||
if is_sudoku_create:
|
||||
self._json(201, {"game": public_sudoku_game(sudoku_store().create(payload.get("nickname"), payload.get("difficulty")))})
|
||||
elif is_sudoku_regenerate:
|
||||
game_id = parsed.path.removeprefix("/api/sudoku/games/").removesuffix("/regenerate").strip("/")
|
||||
sudoku_store().get(game_id, payload.get("nickname"))
|
||||
self._json(201, {"game": public_sudoku_game(sudoku_store().create(payload.get("nickname"), payload.get("difficulty")))})
|
||||
elif self.path == "/api/admin/auth":
|
||||
client_ip = self.client_address[0]
|
||||
if not allow_admin_auth_attempt(client_ip):
|
||||
self._json(429, {"error": "Слишком много попыток. Повторите через 15 минут."})
|
||||
@@ -435,13 +470,29 @@ class Handler(BaseHTTPRequestHandler):
|
||||
else:
|
||||
payload["attachments"] = validate_web_attachments(payload.get("attachments", []))
|
||||
self._json(200, calculate_and_store(payload, actor_id=None, source="web"))
|
||||
except (ApiError, ApplicationError) as exc:
|
||||
except (ApiError, ApplicationError, SudokuError) as exc:
|
||||
self._json(400, {"error": str(exc)})
|
||||
except (ValueError, json.JSONDecodeError) as exc:
|
||||
self._json(400, {"error": str(exc)})
|
||||
except Exception:
|
||||
self._json(500, {"error": "Внутренняя ошибка калькулятора"})
|
||||
|
||||
def do_PUT(self) -> None: # noqa: N802
|
||||
"""Save an in-progress Sudoku board for resuming on another device."""
|
||||
parsed = urlparse(self.path)
|
||||
prefix = "/api/sudoku/games/"
|
||||
if not parsed.path.startswith(prefix) or not parsed.path.removeprefix(prefix):
|
||||
self._json(404, {"error": "Не найдено"})
|
||||
return
|
||||
try:
|
||||
payload = self._read_json_body()
|
||||
game = sudoku_store().save(parsed.path.removeprefix(prefix), payload.get("nickname"), payload.get("board"), payload.get("elapsedSeconds"))
|
||||
self._json(200, {"game": public_sudoku_game(game)})
|
||||
except (ApiError, SudokuError) as exc:
|
||||
self._json(400, {"error": str(exc)})
|
||||
except Exception:
|
||||
self._json(500, {"error": "Не удалось сохранить игру"})
|
||||
|
||||
def do_DELETE(self) -> None: # noqa: N802
|
||||
"""Удаляет заявку после проверки административной авторизации."""
|
||||
parsed = urlparse(self.path)
|
||||
|
||||
Reference in new issue
Block a user