Compare commits

...
40 Commits
Author SHA1 Message Date
Legrems 407cc22911 opus-stats-score 2026-10-25 14:20:49 +01:00
Legrems 5fc79197f6 feat: add final.png export 2026-10-25 14:07:57 +01:00
Legrems 73b279d7fe feat(place): final end time + destruction wave 2026-10-25 12:55:24 +01:00
Legrems 1844b973e9 feat: add admin stats 2026-10-25 10:48:54 +01:00
Legrems 6cee1135a8 feat: add option to disable pixel placement 2026-10-25 10:42:58 +01:00
Legrems 4f2cf08b27 feat: heatmap time decay also in addition of placements 2026-10-25 10:29:20 +01:00
Legrems 9bb02463da feat: heatmap + evo + decay 2026-10-25 10:25:29 +01:00
Legrems 0b34e66d81 show opus submissions for admin 2026-10-24 04:27:40 +02:00
Legrems d180eb3c90 deploy scripts 2026-10-24 04:15:31 +02:00
Legrems 5c70c38523 feat: systemd deployment 2026-10-24 04:04:38 +02:00
Legrems 026d592483 feat: evolution per player (optional) 2026-10-24 03:49:34 +02:00
Legrems 87e6e38291 add place csv export 2026-10-24 02:11:09 +02:00
Legrems 723da9aa38 repair legacy table in migration 2026-10-24 01:18:08 +02:00
Legrems 421106bf71 fix staleTime to 5m instead of infinity 2026-10-23 23:56:20 +02:00
Legrems f42649b888 fix submittion null score 2026-10-23 23:35:38 +02:00
Legrems f75a1b0338 reset opus-magnum sequence 2026-10-23 21:26:22 +02:00
Legrems 1c6d9202fc increase place size 2026-10-23 20:21:57 +02:00
Legrems bc3d8158ec fetch steam collection from event path 2026-10-23 18:53:28 +02:00
Legrems 6e7a68d509 proxy headers 2026-10-23 18:38:48 +02:00
Legrems 2c4dac628e feat(games): disable games inline 2026-10-23 18:06:59 +02:00
Legrems cf51b187d2 opus-magnum steam collection linked to event in admin 2026-10-23 18:03:33 +02:00
Legrems b5716d6dcd various display fixes 2026-10-16 13:25:56 +02:00
Legrems ad7726d978 try to match to steam game 2026-10-16 05:28:15 +02:00
Legrems 89fb745e74 wip: planning-slot test 2026-10-16 05:20:52 +02:00
Legrems 2f8fdb755b feat(games): show games in library mode also 2026-10-16 02:41:27 +02:00
Legrems 54ffe89445 fix(clock): colliding points annotation with CustomUser.points field 2026-10-16 02:30:06 +02:00
Legrems 377bc91bcb fix: small return fixes in api schema 2026-10-16 02:29:39 +02:00
Legrems 60d730a683 feat(submissions): add small file preview before submitting 2026-10-16 02:24:41 +02:00
Legrems 1daf2757b8 fix(submissions): broadcast crop delete + fix for crop admin 2026-10-16 02:19:18 +02:00
Legrems a110575e0a feat(submissions): show all submissions for admin 2026-10-16 02:11:04 +02:00
Legrems bfaef2e402 fix: move other (clock+place) live icon to top ehader too 2026-10-16 02:06:33 +02:00
Legrems 3d040dd377 fix(submissions): top-header icon for live connection (ws) 2026-10-16 02:03:54 +02:00
Legrems a6ea3719b9 fix(submissions): default to frontend search to prevent wrong 404 on hard refresh 2026-10-16 01:55:38 +02:00
Legrems 13c09adff3 feat(submissions): auto-replace player in scopes, cancel sync + info about the sync 2026-10-16 01:49:53 +02:00
Legrems de5ee8ae7a feat(submissions): sync scopes admin from token 2026-10-16 01:34:56 +02:00
Legrems 8daa91d6c5 fix(submissions): better reconnect for ws 2026-10-16 01:26:43 +02:00
Legrems acd08e216a fix: use vue-query; make less useless api call 2026-10-16 01:22:16 +02:00
Legrems b403311ce1 fix(games): card fixes; colors + width 2026-10-16 01:13:24 +02:00
Legrems 1ca4643774 fix(clock): dedup tasks lock bug removal 2026-10-16 01:08:50 +02:00
Legrems 27d3c08a72 feat(games): add steam pages with steam price/reduc 2026-10-16 01:03:46 +02:00
104 changed files with 8200 additions and 446 deletions
+4
View File
@@ -16,4 +16,8 @@ if [ "${MIGRATE_ON_START:-true}" = "true" ]; then
python manage.py migrate --noinput
fi
# Kick off the periodic Steam store refresh (games.tasks). No-op when a refresh
# is already queued, so every replica can safely run it on start.
python manage.py schedule_steam_refresh || echo "Could not schedule Steam store refresh"
exec "$@"
+4
View File
@@ -16,6 +16,8 @@
DJANGO_SECRET_KEY=
DJANGO_DEBUG=false
DJANGO_ALLOWED_HOSTS=submitter.polylan.ch
DJANGO_CSRF_TRUSTED_ORIGINS=https://polylan-submitter.legrems.xyz
DJANGO_BEHIND_TLS_PROXY=true
POSTGRES_DB=
POSTGRES_USER=
@@ -36,5 +38,7 @@ SENTRY_ENVIRONMENT=production
SENTRY_DSN=
STEAM_API_KEY=
STEAM_STORE_REFRESH_MINUTES=360
STEAM_STORE_COUNTRY=ch
AANDT_API_BASE_URL=
SUBMITTER_BASE_URL=
+125
View File
@@ -0,0 +1,125 @@
#!/usr/bin/env bash
# Zero-downtime prod deploy: pull, sync deps, build front, migrate, then
# gracefully reload gunicorn (see polylan-submitter.service, installed and
# restarted instead when it changed) and restart the RQ worker (see
# polylan-submitter-worker.conf).
#
# Run from anywhere as the user owning the checkout, needs sudo for
# systemctl/supervisorctl (no-op when already root):
# ./deploy/systemd/deploy.sh
#
# Migrations run while the old code still serves requests, so keep them
# backward compatible (nullable/default columns, drop/rename in a later deploy).
set -euo pipefail
SERVICE="${SERVICE:-polylan-submitter}"
WORKER="${WORKER:-polylan-submitter-worker}"
SUPERVISOR_CONF_DIR="${SUPERVISOR_CONF_DIR:-/etc/supervisor/conf.d}"
WEB_URL="${WEB_URL:-https://polylan-submitter.legrems.xyz/}"
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
DEPLOY_DIR="$REPO_DIR/deploy/systemd"
APP_DIR="$REPO_DIR/polylan_submitter"
PYTHON="$REPO_DIR/.venv/bin/python"
# Same as the unit's Environment=, so migrate/collectstatic see the prod settings.
# Relative to $APP_DIR, where manage.py runs.
export SETTINGS_ENV_FILE_LOCATION="${SETTINGS_ENV_FILE_LOCATION:-polylan_submitter/.env}"
# gunicorn's master doesn't reload itself on HUP, so a server upgrade needs a
# full restart instead.
server_versions() {
"$PYTHON" - <<'EOF' 2>/dev/null || true
import importlib.metadata as m
for pkg in ("gunicorn", "uvicorn", "uvicorn-worker"):
try:
print(pkg, m.version(pkg))
except m.PackageNotFoundError:
print(pkg, "missing")
EOF
}
# wait_for <description> <command...>: retry for ~30s, fail the deploy if it
# never succeeds.
wait_for() {
local what="$1"
shift
for _ in $(seq 1 30); do
if "$@" >/dev/null 2>&1; then
echo " $what: ok"
return 0
fi
sleep 1
done
echo " $what: FAILED" >&2
return 1
}
web_responds() {
# 000 = nothing listening, 5xx = Caddy up but gunicorn down (502) or broken.
local code
code="$(curl -s -o /dev/null -w '%{http_code}' "$WEB_URL")"
[ "$code" != "000" ] && [ "$code" -lt 500 ]
}
worker_running() {
sudo supervisorctl status "$WORKER" | grep -q RUNNING
}
cd "$REPO_DIR"
echo "==> git pull"
git pull --ff-only
before="$(server_versions)"
echo "==> uv sync"
uv sync --frozen --no-dev
after="$(server_versions)"
echo "==> frontend build"
cd "$APP_DIR"
pnpm install --frozen-lockfile
pnpm build
echo "==> migrate"
"$PYTHON" manage.py migrate --noinput
echo "==> collectstatic"
"$PYTHON" manage.py collectstatic --noinput
echo "==> $SERVICE (systemd)"
unit_changed=false
if ! cmp -s "$DEPLOY_DIR/$SERVICE.service" "/etc/systemd/system/$SERVICE.service"; then
sudo install -m 644 "$DEPLOY_DIR/$SERVICE.service" "/etc/systemd/system/$SERVICE.service"
sudo systemctl daemon-reload
sudo systemctl enable "$SERVICE"
unit_changed=true
fi
# HUP re-forks workers with the master's original args, so a new ExecStart
# (unit change) or a new gunicorn/uvicorn needs a full restart.
if [ "$unit_changed" = true ]; then
echo "==> unit file changed, full restart of $SERVICE"
sudo systemctl restart "$SERVICE"
elif [ "$before" != "$after" ]; then
echo "==> server packages changed, full restart of $SERVICE"
sudo systemctl restart "$SERVICE"
else
echo "==> graceful reload of $SERVICE"
sudo systemctl reload "$SERVICE"
fi
wait_for "$SERVICE active" systemctl is-active --quiet "$SERVICE"
wait_for "$SERVICE responds on $WEB_URL" web_responds
echo "==> $WORKER (supervisor)"
sudo install -m 644 "$DEPLOY_DIR/$WORKER.conf" "$SUPERVISOR_CONF_DIR/$WORKER.conf"
# reread+update picks up config changes (and starts it on first install),
# restart loads the new code - TERM is a warm shutdown, the running job ends first.
sudo supervisorctl reread
sudo supervisorctl update "$WORKER"
sudo supervisorctl restart "$WORKER"
wait_for "$WORKER running" worker_running
echo "==> done"
@@ -0,0 +1,24 @@
; Prod RQ worker (submission OCR, AAndT sync, Steam refresh...), run by the
; host's supervisord next to the polylan-submitter systemd unit (web).
;
; Installed to /etc/supervisor/conf.d/ by deploy/systemd/deploy.sh, which also
; restarts it on every deploy so it picks up the new code.
;
; Logs: supervisorctl tail -f polylan-submitter-worker
[program:polylan-submitter-worker]
command=/home/caddy/polylan-submitter/.venv/bin/python manage.py rqworker default --job-class django_tasks_rq.Job --with-scheduler
directory=/home/caddy/polylan-submitter/polylan_submitter
; Relative to directory, same as the systemd unit.
environment=SETTINGS_ENV_FILE_LOCATION="polylan_submitter/.env",PYTHONUNBUFFERED="1"
user=root
autostart=true
autorestart=true
startsecs=5
; rqworker does a warm shutdown on TERM: it finishes the current job (OCR can
; take a while) before exiting, only SIGKILLed after stopwaitsecs.
stopsignal=TERM
stopwaitsecs=120
stopasgroup=true
killasgroup=true
redirect_stderr=true
+39
View File
@@ -0,0 +1,39 @@
# Prod web process: gunicorn master + uvicorn ASGI workers, behind Caddy.
#
# `systemctl reload polylan-submitter` sends HUP to the gunicorn master: it
# keeps the :7777 socket open, boots new workers on the new code, then
# gracefully stops the old ones - no downtime. See deploy/systemd/deploy.sh.
#
# Installed to /etc/systemd/system/ by deploy.sh: when this file changed it
# does daemon-reload + a full restart (HUP keeps the old ExecStart args).
[Unit]
Description=PolyLAN submitter (gunicorn + uvicorn workers)
After=network.target
[Service]
Type=simple
Restart=always
RestartSec=1
User=root
WorkingDirectory=/home/caddy/polylan-submitter/polylan_submitter
# Relative to WorkingDirectory, loaded by settings.py via python-dotenv.
Environment="SETTINGS_ENV_FILE_LOCATION=polylan_submitter/.env"
# No --preload: with it, HUP re-forks from the already imported (old) code.
# --forwarded-allow-ips replaces daphne's --proxy-headers: trust
# X-Forwarded-* only from Caddy (local here).
ExecStart=/home/caddy/polylan-submitter/.venv/bin/gunicorn polylan_submitter.asgi:application \
--worker-class uvicorn_worker.UvicornWorker \
--workers 2 \
--bind 0.0.0.0:7777 \
--graceful-timeout 20 \
--forwarded-allow-ips 127.0.0.1
ExecReload=/bin/kill -s HUP $MAINPID
# SIGTERM to the master only, it then drains its workers (graceful-timeout).
KillMode=mixed
TimeoutStopSec=30
[Install]
WantedBy=multi-user.target
+5 -5
View File
@@ -54,8 +54,8 @@ def current_state(request: HttpRequest, event_path: str):
def my_stats(request: HttpRequest, event_path: str):
ranked = list(
ranked_players(request.event)
.values("id", "points", "rank")
.order_by("-points", "id")
.values("id", "clock_points", "rank")
.order_by("-clock_points", "id")
)
total_players = len(ranked)
my_index = next(
@@ -71,9 +71,9 @@ def my_stats(request: HttpRequest, event_path: str):
)
return {
"points": mine["points"] if mine else 0.0,
"points": mine["clock_points"] if mine else 0.0,
"rank": mine["rank"] if mine else total_players,
"total_players": total_players,
"points_above": above["points"] if above else None,
"points_below": below["points"] if below else None,
"points_above": above["clock_points"] if above else None,
"points_below": below["clock_points"] if below else None,
}
+4 -3
View File
@@ -22,7 +22,8 @@ def _press_points_expression():
def ranked_players(event: Event):
"""All users annotated with their live total points for this event and
"""All users annotated with their live total `clock_points` (not `points`,
that one is the market balance field on CustomUser) for this event and
DB-computed RANK(). Points only ever come from presses made in `event` -
a player's history in another event never leaks into this leaderboard."""
from accounts.models import CustomUser
@@ -32,6 +33,6 @@ def ranked_players(event: Event):
Value(0.0),
output_field=FloatField(),
)
return CustomUser.objects.annotate(points=points).annotate(
rank=Window(expression=Rank(), order_by=F("points").desc())
return CustomUser.objects.annotate(clock_points=points).annotate(
rank=Window(expression=Rank(), order_by=F("clock_points").desc())
)
+16 -6
View File
@@ -12,6 +12,7 @@ acts.
"""
from datetime import timedelta
from uuid import uuid4
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
@@ -30,13 +31,20 @@ HEARTBEAT_INTERVAL_SECONDS = 1
# One chain ticks every event with the game enabled - this lock keeps a
# second chain from starting underneath an already-running one (e.g. two
# EventGame saves close together). Refreshed every tick, wide enough that a
# single slow tick doesn't let a second chain slip in.
# single slow tick doesn't let a second chain slip in. The lock holds the
# chain id: if it expires anyway (worker down/restarted for a few seconds) and
# a new chain starts, the old one stops at its next tick (instead of both
# ticking forever).
HEARTBEAT_LOCK_KEY = "clock:heartbeat:lock"
HEARTBEAT_LOCK_TIMEOUT_SECONDS = HEARTBEAT_INTERVAL_SECONDS * 5
@task
def clock_heartbeat_task():
def clock_heartbeat_task(chain_id: str):
if cache.get(HEARTBEAT_LOCK_KEY) != chain_id:
# Another chain owns the lock (or it expired), stop this one
return
event_games = list(
EventGame.objects.filter(game__path="clock", enabled=True).select_related(
"event"
@@ -46,6 +54,7 @@ def clock_heartbeat_task():
if not event_games:
# Nothing left to tick - let the chain die. start_clock_heartbeat()
# starts a fresh one next time an event enables the game.
if cache.get(HEARTBEAT_LOCK_KEY) == chain_id:
cache.delete(HEARTBEAT_LOCK_KEY)
return
@@ -67,13 +76,14 @@ def clock_heartbeat_task():
},
)
cache.set(HEARTBEAT_LOCK_KEY, 1, timeout=HEARTBEAT_LOCK_TIMEOUT_SECONDS)
cache.set(HEARTBEAT_LOCK_KEY, chain_id, timeout=HEARTBEAT_LOCK_TIMEOUT_SECONDS)
clock_heartbeat_task.using(
run_after=timezone.now() + timedelta(seconds=HEARTBEAT_INTERVAL_SECONDS)
).enqueue()
).enqueue(chain_id)
def start_clock_heartbeat():
"""Enqueues the heartbeat chain, unless one is already running."""
if cache.add(HEARTBEAT_LOCK_KEY, 1, timeout=HEARTBEAT_LOCK_TIMEOUT_SECONDS):
clock_heartbeat_task.enqueue()
chain_id = uuid4().hex
if cache.add(HEARTBEAT_LOCK_KEY, chain_id, timeout=HEARTBEAT_LOCK_TIMEOUT_SECONDS):
clock_heartbeat_task.enqueue(chain_id)
+57
View File
@@ -0,0 +1,57 @@
from unittest import mock
from django.core.cache import cache
from django.test import TestCase, override_settings
from events.models import Event
from games.models import EventGame, Game
from .tasks import HEARTBEAT_LOCK_KEY, clock_heartbeat_task, start_clock_heartbeat
LOCMEM_CACHE = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
@override_settings(CACHES=LOCMEM_CACHE)
@mock.patch("clock.tasks.get_channel_layer")
class ClockHeartbeatTests(TestCase):
def setUp(self):
cache.clear()
event = Event.objects.create(name="Event", path="event")
clock = Game.objects.create(name="Clock", path="clock", custom_path=True)
self.event_game = EventGame.objects.create(event=event, game=clock)
cache.clear() # post_save signal can start a chain
@mock.patch("clock.tasks.clock_heartbeat_task")
def test_only_one_chain_is_started(self, task, _):
start_clock_heartbeat()
start_clock_heartbeat()
task.enqueue.assert_called_once_with(cache.get(HEARTBEAT_LOCK_KEY))
def test_owning_chain_reschedules_itself(self, channel_layer):
channel_layer.return_value.group_send = mock.AsyncMock()
cache.set(HEARTBEAT_LOCK_KEY, "chain")
with mock.patch("clock.tasks.clock_heartbeat_task") as patched:
clock_heartbeat_task.call("chain")
patched.using.return_value.enqueue.assert_called_once_with("chain")
channel_layer.return_value.group_send.assert_awaited_once()
self.assertEqual(cache.get(HEARTBEAT_LOCK_KEY), "chain")
def test_superseded_chain_stops(self, channel_layer):
cache.set(HEARTBEAT_LOCK_KEY, "new-chain")
with mock.patch("clock.tasks.clock_heartbeat_task") as patched:
clock_heartbeat_task.call("old-chain")
patched.using.assert_not_called()
channel_layer.assert_not_called()
self.assertEqual(cache.get(HEARTBEAT_LOCK_KEY), "new-chain")
def test_chain_dies_and_releases_lock_when_game_disabled(self, _):
EventGame.objects.filter(pk=self.event_game.pk).update(enabled=False)
cache.set(HEARTBEAT_LOCK_KEY, "chain")
with mock.patch("clock.tasks.clock_heartbeat_task") as patched:
clock_heartbeat_task.call("chain")
patched.using.assert_not_called()
self.assertIsNone(cache.get(HEARTBEAT_LOCK_KEY))
+71 -8
View File
@@ -5,9 +5,10 @@ from django_object_actions import (
takes_instance_or_queryset,
)
from submissions.tasks import sync_event_game_scopes_task
from submissions.tasks import schedule_scope_sync, stop_scope_sync
from .models import EventGame, Game
from .models import EventGame, Game, PlanningSlot
from .tasks import refresh_steam_games_task
class EventGameInline(admin.TabularInline):
@@ -19,8 +20,30 @@ class EventGameInline(admin.TabularInline):
class GameAdmin(admin.ModelAdmin):
list_display = ["name", "steam_app_id", "updated_at"]
search_fields = ["name", "steam_app_id"]
readonly_fields = ["created_at", "updated_at"]
readonly_fields = [
"created_at",
"updated_at",
"steam_price_initial",
"steam_price_final",
"steam_discount_percent",
"steam_currency",
"steam_is_free",
"steam_short_description",
"steam_header_image",
"steam_info_updated_at",
]
inlines = [EventGameInline]
actions = ["refresh_steam_info"]
@admin.action(description="Refresh Steam store info")
def refresh_steam_info(self, request, queryset):
game_ids = list(
queryset.filter(steam_app_id__isnull=False).values_list("id", flat=True)
)
refresh_steam_games_task.enqueue(game_ids=game_ids)
self.message_user(
request, f"Queued Steam store refresh for {len(game_ids)} game(s)."
)
@admin.register(EventGame)
@@ -28,13 +51,35 @@ class EventGameAdmin(DjangoObjectActions, admin.ModelAdmin):
list_display = ["game", "event", "enabled", "has_apibot_token"]
list_filter = ["event", "enabled"]
search_fields = ["game__name", "event__name"]
actions = ["sync_scopes"]
change_actions = ["sync_scopes"]
actions = ["enable", "disable", "sync_scopes", "stop_scope_sync"]
change_actions = ["sync_scopes", "stop_scope_sync"]
@admin.display(description="AAndT token", boolean=True)
def has_apibot_token(self, obj):
return bool(obj.apibot_token)
def _set_enabled(self, request, queryset, enabled: bool):
# save() per row (not update()) so post_save fires, e.g. the clock heartbeat
changed = 0
for event_game in queryset.select_related("game").filter(enabled=not enabled):
event_game.enabled = enabled
event_game.save(update_fields=["enabled"])
changed += 1
self.message_user(
request,
f"{'Enabled' if enabled else 'Disabled'} {changed} EventGame(s)"
f" ({queryset.count() - changed} already {'enabled' if enabled else 'disabled'}).",
)
@admin.action(description="Enable selected EventGames")
def enable(self, request, queryset):
self._set_enabled(request, queryset, enabled=True)
@admin.action(description="Disable selected EventGames")
def disable(self, request, queryset):
self._set_enabled(request, queryset, enabled=False)
@action(
label="Sync scopes",
description="Sync scopes from AAndT for selected EventGames",
@@ -44,11 +89,12 @@ class EventGameAdmin(DjangoObjectActions, admin.ModelAdmin):
tokened = queryset.exclude(apibot_token__isnull=True).exclude(apibot_token="")
skipped = queryset.count() - tokened.count()
for event_game in tokened:
sync_event_game_scopes_task.enqueue(event_game.id)
started = sum(schedule_scope_sync(event_game.id) for event_game in tokened)
self.message_user(
request, f"Queued scope sync for {tokened.count()} EventGame(s)."
request,
f"Started scope sync for {started} EventGame(s)"
f" ({tokened.count() - started} already running).",
)
if skipped:
self.message_user(
@@ -56,3 +102,20 @@ class EventGameAdmin(DjangoObjectActions, admin.ModelAdmin):
f"Skipped {skipped} EventGame(s) with no AAndT token configured.",
level=messages.WARNING,
)
@action(
label="Stop scope sync",
description="Stop the scope sync loop of selected EventGames",
)
@takes_instance_or_queryset
def stop_scope_sync(self, request, queryset):
stopped = sum(stop_scope_sync(event_game.id) for event_game in queryset)
self.message_user(request, f"Stopped scope sync for {stopped} EventGame(s).")
@admin.register(PlanningSlot)
class PlanningSlotAdmin(admin.ModelAdmin):
list_display = ["title", "event", "begin", "end", "column", "is_multi_anims"]
list_filter = ["event", "is_multi_anims"]
search_fields = ["title"]
+19 -1
View File
@@ -3,7 +3,9 @@ from typing import List
from ninja import Router
from .models import Game
from .schemas import GameOut
from .schemas import GameOut, PlanningSlotOut, SteamGameOut
from .services.planning import planning_with_games
from .tasks import schedule_steam_refresh
router = Router()
event_router = Router()
@@ -17,3 +19,19 @@ def list_games(request):
@event_router.get("/events/{event_path}/games", response=List[GameOut])
def list_event_games(request, event_path: str):
return Game.objects.enabled_for_event(request.event)
@event_router.get("/events/{event_path}/games/steam", response=List[SteamGameOut])
def list_event_steam_games(request, event_path: str):
"""The event's Steam games with their store info (price, discount, blurb)."""
# Safety net in case the periodic refresh loop isn't running (no-op otherwise).
schedule_steam_refresh()
return Game.objects.enabled_for_event(request.event).filter(
steam_app_id__isnull=False
)
@event_router.get("/events/{event_path}/planning", response=List[PlanningSlotOut])
def list_event_planning(request, event_path: str):
"""The event planning, with the covers of the games we know."""
return planning_with_games(request.event.planning_slots.all())
@@ -0,0 +1,64 @@
import json
import sys
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from events.models import Event
from games.services.planning import (
create_missing_steam_games,
import_planning,
slot_game_names,
)
from games.tasks import refresh_steam_games_task
class Command(BaseCommand):
help = (
"Import an event planning from the legacy PolyLAN planning JSON "
"(slots missing from the file are deleted)"
)
def add_arguments(self, parser):
parser.add_argument("event_path", help="Path of the event, e.g. polylan-43")
parser.add_argument("json_file", help="Planning JSON file, '-' for stdin")
parser.add_argument(
"--no-steam",
action="store_true",
help="Don't look up unknown games on the Steam store",
)
def handle(self, *args, **options):
try:
event = Event.objects.get(path=options["event_path"])
except Event.DoesNotExist:
raise CommandError(f"No event with path {options['event_path']!r}")
if options["json_file"] == "-":
data = json.load(sys.stdin)
else:
with open(options["json_file"], encoding="utf-8") as f:
data = json.load(f)
entries = data["list"] if isinstance(data, dict) else data
with transaction.atomic():
created, updated, deleted = import_planning(event, entries)
self.stdout.write(
self.style.SUCCESS(
f"Planning of {event}: {created} created, {updated} updated, {deleted} deleted"
)
)
if options["no_steam"]:
return
games = create_missing_steam_games(event, slot_game_names(entries))
for game in games:
self.stdout.write(f"+ {game.name} (Steam app {game.steam_app_id})")
if games:
# Prices, blurb, ... for the games page
refresh_steam_games_task.enqueue(game_ids=[game.id for game in games])
self.stdout.write(
self.style.SUCCESS(f"{len(games)} game(s) found on Steam and added to {event}")
)
@@ -0,0 +1,13 @@
from django.core.management.base import BaseCommand
from games.tasks import schedule_steam_refresh
class Command(BaseCommand):
help = "Start the periodic Steam store refresh loop (no-op if already running)"
def handle(self, *args, **options):
if schedule_steam_refresh():
self.stdout.write(self.style.SUCCESS("Steam store refresh scheduled"))
else:
self.stdout.write("Steam store refresh already scheduled")
@@ -0,0 +1,52 @@
# Generated by Django 6.0.5 on 2026-10-15 22:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("games", "0009_game_description"),
]
operations = [
migrations.AddField(
model_name="game",
name="steam_currency",
field=models.CharField(blank=True, default="", max_length=3),
),
migrations.AddField(
model_name="game",
name="steam_discount_percent",
field=models.PositiveSmallIntegerField(default=0),
),
migrations.AddField(
model_name="game",
name="steam_header_image",
field=models.URLField(blank=True, default="", max_length=500),
),
migrations.AddField(
model_name="game",
name="steam_info_updated_at",
field=models.DateTimeField(blank=True, null=True),
),
migrations.AddField(
model_name="game",
name="steam_is_free",
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name="game",
name="steam_price_final",
field=models.PositiveIntegerField(blank=True, null=True),
),
migrations.AddField(
model_name="game",
name="steam_price_initial",
field=models.PositiveIntegerField(blank=True, null=True),
),
migrations.AddField(
model_name="game",
name="steam_short_description",
field=models.TextField(blank=True, default=""),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 6.0.5 on 2026-10-16 00:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("games", "0010_game_steam_store_info"),
]
operations = [
migrations.AddField(
model_name="game",
name="library_image",
field=models.URLField(blank=True, default="", max_length=500),
),
]
@@ -0,0 +1,53 @@
# Generated by Django 6.0.5 on 2026-10-16 03:14
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("events", "0003_event_is_available"),
("games", "0011_game_library_image"),
]
operations = [
migrations.CreateModel(
name="PlanningSlot",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("source_pk", models.PositiveIntegerField()),
("title", models.CharField(max_length=255)),
("begin", models.DateTimeField()),
("end", models.DateTimeField()),
("column", models.PositiveSmallIntegerField(default=0)),
("color", models.CharField(blank=True, default="", max_length=7)),
("is_multi_anims", models.BooleanField(default=False)),
("game_names", models.JSONField(blank=True, default=list)),
(
"event",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="planning_slots",
to="events.event",
),
),
],
options={
"ordering": ["begin", "column"],
"constraints": [
models.UniqueConstraint(
fields=("event", "source_pk"), name="unique_event_planning_slot"
)
],
},
),
]
+60
View File
@@ -15,6 +15,19 @@ class Game(models.Model):
custom_path = models.BooleanField(default=False)
image = models.URLField(null=True, blank=True)
description = models.TextField(blank=True, default="")
# Vertical (600x900) cover for games/showcase, empty = Steam's library capsule
library_image = models.URLField(max_length=500, blank=True, default="")
# Steam store info, refreshed in the background (see games.tasks).
# Prices are in cents, in steam_currency.
steam_price_initial = models.PositiveIntegerField(null=True, blank=True)
steam_price_final = models.PositiveIntegerField(null=True, blank=True)
steam_discount_percent = models.PositiveSmallIntegerField(default=0)
steam_currency = models.CharField(max_length=3, blank=True, default="")
steam_is_free = models.BooleanField(default=False)
steam_short_description = models.TextField(blank=True, default="")
steam_header_image = models.URLField(max_length=500, blank=True, default="")
steam_info_updated_at = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
@@ -29,6 +42,19 @@ class Game(models.Model):
return f"{self.name} ({self.steam_app_id})"
return self.name
@property
def store_url(self) -> str:
if not self.steam_app_id:
return ""
return f"https://store.steampowered.com/app/{self.steam_app_id}"
@property
def library_image_url(self) -> str:
"""Vertical cover, like in the Steam library. Empty if there's none."""
if self.library_image or not self.steam_app_id:
return self.library_image
return f"https://shared.akamai.steamstatic.com/store_item_assets/steam/apps/{self.steam_app_id}/library_600x900.jpg"
class EventGame(models.Model):
event = models.ForeignKey(
@@ -63,3 +89,37 @@ class EventGame(models.Model):
def __str__(self) -> str:
return f"{self.game.name} @ {self.event.name} ({'enabled' if self.enabled else 'disabled'})"
class PlanningSlot(models.Model):
"""One slot of the event planning, imported from the legacy PolyLAN planning
(see the import_planning command)."""
event = models.ForeignKey(
Event,
on_delete=models.CASCADE,
related_name="planning_slots",
)
# pk of the slot in the legacy planning, to update it on re-import
source_pk = models.PositiveIntegerField()
title = models.CharField(max_length=255)
begin = models.DateTimeField()
end = models.DateTimeField()
column = models.PositiveSmallIntegerField(default=0)
color = models.CharField(max_length=7, blank=True, default="")
# Multi-anims (e.g. "Fils rouges") run several games over the whole event
is_multi_anims = models.BooleanField(default=False)
# Names of the games run in this slot (the legacy "aandts")
game_names = models.JSONField(default=list, blank=True)
class Meta:
ordering = ["begin", "column"]
constraints = [
models.UniqueConstraint(
fields=["event", "source_pk"],
name="unique_event_planning_slot",
),
]
def __str__(self) -> str:
return f"{self.title} @ {self.event.name} ({self.begin:%a %H:%M})"
+85
View File
@@ -1,3 +1,4 @@
from datetime import datetime
from typing import Optional
from ninja import Schema
@@ -11,3 +12,87 @@ class GameOut(Schema):
custom_path: bool
image: Optional[str] = None
description: str
@staticmethod
def resolve_description(obj) -> str:
# The admin one wins, Steam games fall back to their store blurb
return obj.description or obj.steam_short_description
class SteamGameOut(Schema):
id: int
name: str
steam_app_id: int
store_url: str
header_image: str
library_image: str
short_description: str
is_free: bool
currency: str
price_initial: Optional[int] = None
price_final: Optional[int] = None
discount_percent: int
updated_at: Optional[datetime] = None
@staticmethod
def resolve_store_url(obj) -> str:
return obj.store_url
@staticmethod
def resolve_header_image(obj) -> str:
return (
obj.steam_header_image
or f"https://cdn.akamai.steamstatic.com/steam/apps/{obj.steam_app_id}/header.jpg"
)
@staticmethod
def resolve_library_image(obj) -> str:
return obj.library_image_url
@staticmethod
def resolve_short_description(obj) -> str:
return obj.steam_short_description
@staticmethod
def resolve_is_free(obj) -> bool:
return obj.steam_is_free
@staticmethod
def resolve_currency(obj) -> str:
return obj.steam_currency
@staticmethod
def resolve_price_initial(obj) -> Optional[int]:
return obj.steam_price_initial
@staticmethod
def resolve_price_final(obj) -> Optional[int]:
return obj.steam_price_final
@staticmethod
def resolve_discount_percent(obj) -> int:
return obj.steam_discount_percent
@staticmethod
def resolve_updated_at(obj) -> Optional[datetime]:
return obj.steam_info_updated_at
class PlanningGameOut(Schema):
name: str
# Empty when the name didn't match any of our games
library_image: str = ""
store_url: str = ""
steam_app_id: Optional[int] = None
class PlanningSlotOut(Schema):
id: int
title: str
begin: datetime
end: datetime
column: int
color: str
is_multi_anims: bool
# Single slot: the slot's game. Multi-anims: each of their games.
games: list[PlanningGameOut]
@@ -0,0 +1,172 @@
import logging
import re
import unicodedata
import httpx
from django.utils.text import slugify
from ..models import EventGame, Game, PlanningSlot
from .steam_store import search_store
logger = logging.getLogger(__name__)
# "Cosmoteer: Starship Architect & Commander" is still "Cosmoteer"
SUBTITLE_SEPARATOR = re.compile(r"\s*(?::|\s-\s|\s–\s|\s—\s)")
def normalize_name(name: str) -> str:
"""'Towerfall: Ascension' and 'TowerFall Ascension' are the same game:
no accents, no case, letters and digits only."""
# Before NFKD, which turns ™ into "TM"
name = re.sub(r"[™®©]", "", name)
name = unicodedata.normalize("NFKD", name)
name = "".join(c for c in name if not unicodedata.combining(c))
return re.sub(r"[^0-9a-z]", "", name.casefold())
def _steam_match(name: str) -> dict | None:
"""The Steam store app named name (or name + a subtitle), if there's one.
Strict on purpose: "Jass" or "Crochet" must not end up as some random game."""
wanted = normalize_name(name)
if not wanted:
return None
# Steam's search chokes on punctuation ("Puyo Puyo — Tetris" finds nothing)
term = " ".join(re.sub(r"[^\w\s]", " ", name).split())
for item in search_store(term):
steam_name = item.get("name") or ""
if wanted in (
normalize_name(steam_name),
normalize_name(SUBTITLE_SEPARATOR.split(steam_name, maxsplit=1)[0]),
):
return item
return None
def _unique_path(name: str) -> str:
base = slugify(name)[:90] or "game"
path, n = base, 2
while Game.objects.filter(path=path).exists():
path, n = f"{base}-{n}", n + 1
return path
def create_missing_steam_games(event, names: list[str]) -> list[Game]:
"""For each name without a Game, look it up on the Steam store and create
the Game + its EventGame when found. Returns the created games."""
known = {normalize_name(game.name) for game in Game.objects.all()}
created = []
for name in dict.fromkeys(names): # unique, keeps order
if normalize_name(name) in known:
continue
try:
item = _steam_match(name)
except (httpx.HTTPError, ValueError) as exc:
logger.warning("Steam store search failed for %r: %s", name, exc)
continue
if item is None:
continue
if Game.objects.filter(steam_app_id=item["id"]).exists():
# Already there under another name, the planning won't match it
logger.warning(
"%r is Steam app %s, already a Game under another name",
name,
item["id"],
)
continue
# Named like in the planning, so the slot matches it
game = Game.objects.create(
name=name, steam_app_id=item["id"], path=_unique_path(name)
)
EventGame.objects.get_or_create(event=event, game=game)
known.add(normalize_name(name))
created.append(game)
return created
def slot_game_names(entries: list[dict]) -> list[str]:
"""Names to look for in a planning: titles of single slots, game names of
multi-anims (their title, like "Fils rouges", isn't a game)."""
names = []
for entry in entries:
if not entry.get("is_multi_anims"):
names.append(entry["title"])
names += [a["name"] for a in entry.get("aandts") or []]
return names
def _game_out(name: str, game: Game | None) -> dict:
if game is None:
return {"name": name}
return {
"name": game.name,
"library_image": game.library_image_url,
"store_url": game.store_url,
"steam_app_id": game.steam_app_id,
}
def planning_with_games(slots) -> list[dict]:
"""Slots as PlanningSlotOut dicts, with their games matched by name to ours."""
games_by_name = {normalize_name(game.name): game for game in Game.objects.all()}
def match(name: str) -> Game | None:
return games_by_name.get(normalize_name(name))
out = []
for slot in slots:
if slot.is_multi_anims:
games = [_game_out(name, match(name)) for name in slot.game_names]
else:
# The title is the usual match, the legacy game names are a fallback
# ("Golf it!" slot running the "Golf It!" game)
game = next(
filter(None, map(match, [slot.title, *slot.game_names])), None
)
games = [_game_out(slot.title, game)]
out.append(
{
"id": slot.id,
"title": slot.title,
"begin": slot.begin,
"end": slot.end,
"column": slot.column,
"color": slot.color,
"is_multi_anims": slot.is_multi_anims,
"games": games,
}
)
return out
def import_planning(event, entries: list[dict]) -> tuple[int, int, int]:
"""Sync the event planning with the legacy planning entries (its "list").
Returns (created, updated, deleted)."""
created = updated = 0
for entry in entries:
_, was_created = PlanningSlot.objects.update_or_create(
event=event,
source_pk=entry["pk"],
defaults={
"title": entry["title"],
"begin": entry["begin"],
"end": entry["end"],
"column": entry.get("colonneS") or 0,
"color": entry.get("color_code") or "",
"is_multi_anims": bool(entry.get("is_multi_anims")),
"game_names": [a["name"] for a in entry.get("aandts") or []],
},
)
if was_created:
created += 1
else:
updated += 1
deleted, _ = (
PlanningSlot.objects.filter(event=event)
.exclude(source_pk__in=[entry["pk"] for entry in entries])
.delete()
)
return created, updated, deleted
@@ -0,0 +1,91 @@
import logging
import httpx
from django.conf import settings
from django.utils import timezone
from ..models import Game
logger = logging.getLogger(__name__)
# Public store endpoint, no API key needed. Rate limited to ~200 calls / 5 min,
# which is plenty for a handful of games every few hours.
APP_DETAILS_URL = "https://store.steampowered.com/api/appdetails"
STORE_SEARCH_URL = "https://store.steampowered.com/api/storesearch/"
class SteamStoreError(Exception):
"""Raised when the Steam store didn't return usable details for an app."""
def fetch_app_details(steam_app_id: int) -> dict:
response = httpx.get(
APP_DETAILS_URL,
params={
"appids": steam_app_id,
"cc": settings.STEAM_STORE_COUNTRY,
"l": "en",
"filters": "basic,price_overview",
},
timeout=10,
)
response.raise_for_status()
entry = (response.json() or {}).get(str(steam_app_id)) or {}
if not entry.get("success"):
raise SteamStoreError(f"No store details for app {steam_app_id}")
return entry["data"]
def search_store(term: str) -> list[dict]:
"""Store search results for term, as [{"id": app id, "name": ...}, ...]."""
response = httpx.get(
STORE_SEARCH_URL,
params={"term": term, "cc": settings.STEAM_STORE_COUNTRY, "l": "english"},
timeout=10,
)
response.raise_for_status()
return (response.json() or {}).get("items") or []
def refresh_steam_game(game: Game) -> None:
"""Pull the current store info for a Steam game into its steam_* fields."""
data = fetch_app_details(game.steam_app_id)
price = data.get("price_overview") or {}
game.steam_is_free = bool(data.get("is_free"))
game.steam_price_initial = price.get("initial")
game.steam_price_final = price.get("final")
game.steam_discount_percent = price.get("discount_percent") or 0
game.steam_currency = price.get("currency") or ""
game.steam_short_description = data.get("short_description") or ""
game.steam_header_image = data.get("header_image") or ""
game.steam_info_updated_at = timezone.now()
game.save(
update_fields=[
"steam_is_free",
"steam_price_initial",
"steam_price_final",
"steam_discount_percent",
"steam_currency",
"steam_short_description",
"steam_header_image",
"steam_info_updated_at",
"updated_at",
]
)
def refresh_steam_games(game_ids: list[int] | None = None) -> None:
"""Refresh every Steam game (or just game_ids). A failing game keeps its
previous info and doesn't stop the others."""
games = Game.objects.filter(steam_app_id__isnull=False)
if game_ids is not None:
games = games.filter(id__in=game_ids)
for game in games:
try:
refresh_steam_game(game)
except (httpx.HTTPError, ValueError, SteamStoreError) as exc:
logger.warning("Steam store refresh failed for %s: %s", game, exc)
+61
View File
@@ -0,0 +1,61 @@
from datetime import timedelta
from uuid import uuid4
from django.conf import settings
from django.core.cache import cache
from django.tasks import task
from django.utils import timezone
from .services.steam_store import refresh_steam_games
# Set while a periodic refresh is queued, so there's only ever one loop running,
# whatever the number of workers/containers trying to start it. It expires on
# its own if the loop dies (worker killed mid-job, Redis queue flushed, ...),
# letting the next schedule_steam_refresh() start a new one. The guard holds the
# loop id, so if it expires while the old loop is just late, the old one stops
# at its next run (instead of 2 loops running side by side).
STEAM_REFRESH_GUARD_KEY = "games:steam_refresh:scheduled"
def steam_refresh_interval() -> timedelta:
return timedelta(minutes=settings.STEAM_STORE_REFRESH_MINUTES)
def _guard_timeout() -> int:
return int(steam_refresh_interval().total_seconds() * 2)
def schedule_steam_refresh() -> bool:
"""Start the periodic refresh loop right away, unless one is already queued.
Safe to call from anywhere, any number of times."""
loop_id = uuid4().hex
if not cache.add(STEAM_REFRESH_GUARD_KEY, loop_id, timeout=_guard_timeout()):
return False
refresh_steam_games_task.enqueue(loop_id=loop_id)
return True
@task
def refresh_steam_games_task(
game_ids: list[int] | None = None, loop_id: str | None = None
):
"""Refresh Steam store info, then re-enqueue itself every
STEAM_STORE_REFRESH_MINUTES (same self-rescheduling idea as
sync_event_game_scopes_task, no external scheduler needed).
Without loop_id it's a one-off run (e.g. the admin action) that leaves the
periodic loop alone. With loop_id, it only continues while the guard still
holds this loop_id."""
if loop_id is not None and cache.get(STEAM_REFRESH_GUARD_KEY) != loop_id:
# Another loop owns the guard (or it expired), stop this one
return
try:
refresh_steam_games(game_ids)
finally:
if loop_id is not None:
cache.set(STEAM_REFRESH_GUARD_KEY, loop_id, timeout=_guard_timeout())
refresh_steam_games_task.using(
run_after=timezone.now() + steam_refresh_interval()
).enqueue(loop_id=loop_id)
+172
View File
@@ -0,0 +1,172 @@
from unittest import mock
import httpx
from django.core.cache import cache
from django.test import TestCase, override_settings
from accounts.models import CustomUser
from events.models import Event
from .models import EventGame, Game
from .services.steam_store import refresh_steam_games
from .tasks import (
STEAM_REFRESH_GUARD_KEY,
refresh_steam_games_task,
schedule_steam_refresh,
)
LOCMEM_CACHE = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
def steam_response(app_id, data, success=True):
return httpx.Response(
200,
json={str(app_id): {"success": success, "data": data}},
request=httpx.Request("GET", "https://store.steampowered.com"),
)
class RefreshSteamGamesTests(TestCase):
def setUp(self):
self.game = Game.objects.create(name="Noita", path="noita", steam_app_id=881100)
@mock.patch("games.services.steam_store.httpx.get")
def test_stores_price_and_discount(self, get):
get.return_value = steam_response(
881100,
{
"is_free": False,
"short_description": "Every pixel is simulated.",
"header_image": "https://example.com/header.jpg",
"price_overview": {
"currency": "CHF",
"initial": 1950,
"final": 780,
"discount_percent": 60,
},
},
)
refresh_steam_games()
self.game.refresh_from_db()
self.assertEqual(self.game.steam_price_initial, 1950)
self.assertEqual(self.game.steam_price_final, 780)
self.assertEqual(self.game.steam_discount_percent, 60)
self.assertEqual(self.game.steam_currency, "CHF")
self.assertEqual(self.game.steam_short_description, "Every pixel is simulated.")
self.assertIsNotNone(self.game.steam_info_updated_at)
@mock.patch("games.services.steam_store.httpx.get")
def test_free_game_has_no_price(self, get):
get.return_value = steam_response(881100, {"is_free": True})
refresh_steam_games()
self.game.refresh_from_db()
self.assertTrue(self.game.steam_is_free)
self.assertIsNone(self.game.steam_price_final)
@mock.patch("games.services.steam_store.httpx.get")
def test_failure_keeps_previous_info(self, get):
Game.objects.filter(pk=self.game.pk).update(steam_price_final=999)
get.side_effect = httpx.ConnectError("down")
refresh_steam_games()
self.game.refresh_from_db()
self.assertEqual(self.game.steam_price_final, 999)
@override_settings(CACHES=LOCMEM_CACHE)
class ScheduleSteamRefreshTests(TestCase):
def setUp(self):
cache.clear()
@mock.patch("games.tasks.refresh_steam_games_task")
def test_only_one_loop_is_scheduled(self, task):
self.assertTrue(schedule_steam_refresh())
self.assertFalse(schedule_steam_refresh())
task.enqueue.assert_called_once_with(loop_id=cache.get(STEAM_REFRESH_GUARD_KEY))
@mock.patch("games.tasks.refresh_steam_games")
def test_task_reschedules_itself_even_on_failure(self, refresh):
cache.set(STEAM_REFRESH_GUARD_KEY, "loop")
refresh.side_effect = RuntimeError("boom")
with mock.patch("games.tasks.refresh_steam_games_task") as patched:
with self.assertRaises(RuntimeError):
refresh_steam_games_task.call(loop_id="loop")
patched.using.return_value.enqueue.assert_called_once_with(loop_id="loop")
@mock.patch("games.tasks.refresh_steam_games")
def test_superseded_loop_stops(self, refresh):
cache.set(STEAM_REFRESH_GUARD_KEY, "new-loop")
with mock.patch("games.tasks.refresh_steam_games_task") as patched:
refresh_steam_games_task.call(loop_id="old-loop")
refresh.assert_not_called()
patched.using.assert_not_called()
self.assertEqual(cache.get(STEAM_REFRESH_GUARD_KEY), "new-loop")
@mock.patch("games.tasks.refresh_steam_games")
def test_one_off_run_does_not_reschedule(self, refresh):
with mock.patch("games.tasks.refresh_steam_games_task") as patched:
refresh_steam_games_task.call(game_ids=[1])
refresh.assert_called_once_with([1])
patched.using.assert_not_called()
@override_settings(CACHES=LOCMEM_CACHE)
class EventSteamGamesApiTests(TestCase):
def setUp(self):
self.event = Event.objects.create(name="Event", path="event")
noita = Game.objects.create(
name="Noita", path="noita", steam_app_id=881100, steam_price_final=780
)
clock = Game.objects.create(name="Clock", path="clock", custom_path=True)
EventGame.objects.create(event=self.event, game=noita)
EventGame.objects.create(event=self.event, game=clock)
user = CustomUser.objects.create_user(username="user", password="x")
self.client.force_login(user)
@mock.patch("games.api.schedule_steam_refresh")
def test_lists_only_steam_games_with_store_info(self, schedule):
response = self.client.get("/api/events/event/games/steam")
self.assertEqual(response.status_code, 200)
[game] = response.json()
self.assertEqual(game["name"], "Noita")
self.assertEqual(game["price_final"], 780)
self.assertEqual(game["store_url"], "https://store.steampowered.com/app/881100")
schedule.assert_called_once()
class EventGamesDescriptionTests(TestCase):
def setUp(self):
self.event = Event.objects.create(name="Event", path="event")
self.user = CustomUser.objects.create_user(username="user", password="x")
self.client.force_login(self.user)
def test_steam_description_is_fallback_for_admin_one(self):
steam = Game.objects.create(
name="Noita",
path="noita",
steam_app_id=881100,
steam_short_description="From Steam",
)
custom = Game.objects.create(
name="Opus",
path="opus",
steam_app_id=558990,
description="From admin",
steam_short_description="From Steam",
)
EventGame.objects.create(event=self.event, game=steam)
EventGame.objects.create(event=self.event, game=custom)
response = self.client.get("/api/events/event/games")
descriptions = {g["name"]: g["description"] for g in response.json()}
self.assertEqual(descriptions, {"Noita": "From Steam", "Opus": "From admin"})
+3 -1
View File
@@ -239,7 +239,9 @@ def get_leaderboard(request: HttpRequest, event_path: str):
return data
@router.post(f"{PREFIX}/submit", response={200: NoitaSubmissionOut, 400: dict})
@router.post(
f"{PREFIX}/submit", response={200: NoitaSubmissionOut, 400: dict, 500: dict}
)
@decorate_view(require_game_enabled(NOITA_APP_ID))
def submit_log_file(
request: HttpRequest, event_path: str, file: UploadedFile = File(...)
+1
View File
@@ -3,4 +3,5 @@ import { defineConfig } from '@hey-api/openapi-ts';
export default defineConfig({
input: `http://localhost:7777/api/openapi.json`,
output: 'src/api/',
plugins: ['@hey-api/typescript', '@hey-api/sdk', '@tanstack/vue-query'],
});
+10 -1
View File
@@ -95,7 +95,16 @@ class SteamCollectionAdmin(admin.ModelAdmin):
fieldsets = (
(
"Basic Information",
{"fields": ("steam_id", "url", "title", "description", "is_active")},
{
"fields": (
"event",
"steam_id",
"url",
"title",
"description",
"is_active",
)
},
),
("Author Information", {"fields": ("author_name", "author_steam_id")}),
(
+89 -10
View File
@@ -1,3 +1,5 @@
import csv
from ninja import Router, File
from ninja.files import UploadedFile
from ninja.pagination import paginate
@@ -5,6 +7,8 @@ from ninja.errors import HttpError
from django.db import transaction
from django.core.files.base import ContentFile
from django.core.cache import cache
from django.http import HttpRequest, HttpResponse
from ninja.security import django_auth_is_staff
from django.utils import timezone
from django.shortcuts import get_object_or_404
from typing import List
@@ -25,6 +29,7 @@ from .schemas import (
SubmissionOut,
PuzzleResponseOut,
ValidationIn,
SubmissionFileOut,
SteamCollectionItemOut,
SteamCollectionOut,
)
@@ -73,7 +78,9 @@ def get_submission(request, event_path: str, submission_id: str):
)
@router.post(f"{PREFIX}/submissions", response=SubmissionOut)
@router.post(
f"{PREFIX}/submissions", response={200: SubmissionOut, 400: dict, 500: dict}
)
@decorate_view(require_game_enabled(OPUS_MAGNUM_APP_ID))
def create_submission(
request, event_path: str, data: SubmissionIn, files: List[UploadedFile] = File(...)
@@ -120,13 +127,17 @@ def create_submission(
for response_data in data.responses
)
# Non-admin submissions always go through manual validation
needs_validation = (
data.manual_validation_requested or not request.user.is_staff
)
# Create the submission
submission = Submission.objects.create(
event=request.event,
user=request.user if request.user.is_authenticated else None,
notes=data.notes,
manual_validation_requested=data.manual_validation_requested
or auto_request_validation,
manual_validation_requested=needs_validation or auto_request_validation,
)
file_index = 0
@@ -146,7 +157,7 @@ def create_submission(
cost=response_data.cost,
cycles=response_data.cycles,
area=response_data.area,
needs_manual_validation=data.manual_validation_requested,
needs_manual_validation=needs_validation,
ocr_confidence_cost=response_data.ocr_confidence_cost,
ocr_confidence_cycles=response_data.ocr_confidence_cycles,
ocr_confidence_area=response_data.ocr_confidence_area,
@@ -156,7 +167,7 @@ def create_submission(
"validated_cycles": response_data.cycles,
"validated_area": response_data.area,
}
if not data.manual_validation_requested
if not needs_validation
else {},
)
@@ -211,7 +222,10 @@ def create_submission(
return 500, {"detail": f"Error creating submission: {str(e)}"}
@router.put(f"{PREFIX}/responses/{{response_id}}/validate", response=PuzzleResponseOut)
@router.put(
f"{PREFIX}/responses/{{response_id}}/validate",
response={200: PuzzleResponseOut, 403: dict},
)
@decorate_view(require_game_enabled(OPUS_MAGNUM_APP_ID))
def validate_response(request, event_path: str, response_id: int, data: ValidationIn):
"""Manually validate a puzzle response"""
@@ -252,7 +266,8 @@ def validate_response(request, event_path: str, response_id: int, data: Validati
@router.put(
f"{PREFIX}/responses/{{response_id}}/validate/auto", response=PuzzleResponseOut
f"{PREFIX}/responses/{{response_id}}/validate/auto",
response={200: PuzzleResponseOut, 403: dict},
)
@decorate_view(require_game_enabled(OPUS_MAGNUM_APP_ID))
def validate_auto(request, event_path: str, response_id: int):
@@ -271,7 +286,10 @@ def validate_auto(request, event_path: str, response_id: int):
return response
@router.get(f"{PREFIX}/responses/needs-validation", response=List[PuzzleResponseOut])
@router.get(
f"{PREFIX}/responses/needs-validation",
response={200: List[PuzzleResponseOut], 403: dict},
)
@decorate_view(require_game_enabled(OPUS_MAGNUM_APP_ID))
def list_responses_needing_validation(request, event_path: str):
"""Get all responses that need manual validation"""
@@ -289,7 +307,28 @@ def list_responses_needing_validation(request, event_path: str):
)
@router.post(f"{PREFIX}/submissions/{{submission_id}}/validate", response=SubmissionOut)
@router.get(
f"{PREFIX}/responses/{{response_id}}/files",
response={200: List[SubmissionFileOut], 403: dict},
)
@decorate_view(require_game_enabled(OPUS_MAGNUM_APP_ID))
def list_response_files(request, event_path: str, response_id: int):
"""Get the solution files of any player's response (admin only)"""
if not request.user.is_authenticated or not request.user.is_staff:
return 403, {"detail": "Admin access required"}
response = get_object_or_404(
PuzzleResponse, id=response_id, submission__event=request.event
)
return response.files.all()
@router.post(
f"{PREFIX}/submissions/{{submission_id}}/validate",
response={200: SubmissionOut, 403: dict},
)
@decorate_view(require_game_enabled(OPUS_MAGNUM_APP_ID))
def validate_submission(request, event_path: str, submission_id: str):
"""Mark entire submission as validated"""
@@ -318,7 +357,9 @@ def validate_submission(request, event_path: str, submission_id: str):
return submission
@router.delete(f"{PREFIX}/submissions/{{submission_id}}")
@router.delete(
f"{PREFIX}/submissions/{{submission_id}}", response={200: dict, 403: dict}
)
@decorate_view(require_game_enabled(OPUS_MAGNUM_APP_ID))
def delete_submission(request, event_path: str, submission_id: str):
"""Delete a submission (admin only)"""
@@ -358,3 +399,41 @@ def get_stats(request, event_path: str):
if total_responses
else 0,
}
@router.get(f"{PREFIX}/points.csv", auth=django_auth_is_staff)
@decorate_view(require_game_enabled(OPUS_MAGNUM_APP_ID))
def points_csv(request: HttpRequest, event_path: str):
"""Admin-only: points per player for each puzzle of the active collection,
one column per puzzle (1 puzzle = 1 round), `;` separated."""
puzzles = list(
SteamCollectionItem.objects.filter(
collection__is_active=True, collection__event=request.event
).order_by("order_index")
)
points = {}
for response in (
PuzzleResponse.objects.filter(
needs_manual_validation=False,
submission__event=request.event,
submission__user__isnull=False,
puzzle__in=puzzles,
)
.filter_user_best_response()
.select_related("submission__user")
):
user_points = points.setdefault(response.submission.user.username, {})
user_points[response.puzzle_id] = response.rank_points or 0
# text/plain so browsers render it inline - most force-download text/csv
response = HttpResponse(content_type="text/plain; charset=utf-8")
writer = csv.writer(response, delimiter=";")
writer.writerow(["username", *(puzzle.title for puzzle in puzzles)])
for username, user_points in sorted(
points.items(), key=lambda item: (-sum(item[1].values()), item[0])
):
writer.writerow(
[username, *(user_points.get(puzzle.id, 0) for puzzle in puzzles)]
)
return response
@@ -4,6 +4,7 @@ Django management command to fetch Steam Workshop collections
from django.core.management.base import BaseCommand, CommandError
from opus_magnum.utils import create_or_update_collection
from events.models import Event
from opus_magnum.models import SteamAPIKey, SteamCollection
@@ -12,6 +13,12 @@ class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("url", type=str, help="Steam Workshop collection URL")
parser.add_argument(
"--event",
type=str,
required=True,
help="Path of the event the collection belongs to",
)
parser.add_argument(
"--force",
action="store_true",
@@ -22,6 +29,11 @@ class Command(BaseCommand):
url = options["url"]
force = options["force"]
try:
event = Event.objects.get(path=options["event"])
except Event.DoesNotExist:
raise CommandError(f"No event with path '{options['event']}'")
self.stdout.write(f"Fetching Steam collection from: {url}")
api_key = SteamAPIKey.objects.filter(is_active=True).first()
@@ -53,7 +65,7 @@ class Command(BaseCommand):
return
# Fetch and create/update collection
collection, created = create_or_update_collection(url)
collection, created = create_or_update_collection(url, event)
if created:
self.stdout.write(
@@ -0,0 +1,33 @@
# 0015 copied rows with their ids via raw INSERT ... SELECT *, which doesn't
# bump postgres sequences -> new inserts collide on the pkey. Resync them.
from django.core.management.color import no_style
from django.db import migrations
MODEL_NAMES = [
"SteamAPIKey",
"SteamCollection",
"SteamCollectionItem",
"Submission",
"PuzzleResponse",
"SubmissionFile",
]
def reset_sequences(apps, schema_editor):
connection = schema_editor.connection
models = [apps.get_model("opus_magnum", name) for name in MODEL_NAMES]
statements = connection.ops.sequence_reset_sql(no_style(), models)
with connection.cursor() as cursor:
for sql in statements:
cursor.execute(sql)
class Migration(migrations.Migration):
dependencies = [
("opus_magnum", "0018_event_required"),
]
operations = [
migrations.RunPython(reset_sequences, migrations.RunPython.noop),
]
@@ -0,0 +1,34 @@
# Generated by Django 6.0.5 on 2026-10-23 21:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("opus_magnum", "0019_reset_sequences"),
]
operations = [
migrations.AlterField(
model_name="puzzleresponse",
name="area",
field=models.IntegerField(
blank=True, help_text="Area value from OCR", null=True
),
),
migrations.AlterField(
model_name="puzzleresponse",
name="cost",
field=models.IntegerField(
blank=True, help_text="Cost value from OCR", null=True
),
),
migrations.AlterField(
model_name="puzzleresponse",
name="cycles",
field=models.IntegerField(
blank=True, help_text="Cycles value from OCR", null=True
),
),
]
+3 -3
View File
@@ -400,9 +400,9 @@ class PuzzleResponse(models.Model):
puzzle_name = models.CharField(
max_length=255, help_text="Puzzle name as detected by OCR"
)
cost = models.IntegerField(blank=True, help_text="Cost value from OCR")
cycles = models.IntegerField(blank=True, help_text="Cycles value from OCR")
area = models.IntegerField(blank=True, help_text="Area value from OCR")
cost = models.IntegerField(null=True, blank=True, help_text="Cost value from OCR")
cycles = models.IntegerField(null=True, blank=True, help_text="Cycles value from OCR")
area = models.IntegerField(null=True, blank=True, help_text="Area value from OCR")
# Validation flags
needs_manual_validation = models.BooleanField(
+74 -1
View File
@@ -1 +1,74 @@
# Create your tests here.
from django.test import TestCase
from accounts.models import CustomUser
from animations.models import PuzzlePointsFactor, PuzzlePointsValue
from events.models import Event
from games.models import EventGame, Game
from .api import OPUS_MAGNUM_APP_ID
from .models import PuzzleResponse, SteamCollection, SteamCollectionItem, Submission
URL = "/api/events/event/opus-magnum/points.csv"
class PointsCsvTests(TestCase):
def setUp(self):
self.event = Event.objects.create(name="Event", path="event")
game = Game.objects.create(name="Opus Magnum", steam_app_id=OPUS_MAGNUM_APP_ID)
EventGame.objects.create(event=self.event, game=game)
collection = SteamCollection.objects.create(
event=self.event, steam_id="1", url="https://example.com", is_active=True
)
factor = PuzzlePointsFactor.objects.create(cost=1, cycles=1, area=1)
value = PuzzlePointsValue.objects.create(points=[10, 5, 1])
self.p1, self.p2 = (
SteamCollectionItem.objects.create(
collection=collection,
steam_item_id=str(i),
title=f"Puzzle {i}",
order_index=i,
points_factor=factor,
points_value=value,
)
for i in (1, 2)
)
self.alice = CustomUser.objects.create_user(username="alice", password="x")
self.bob = CustomUser.objects.create_user(username="bob", password="x")
self.admin = CustomUser.objects.create_user(
username="admin", password="x", is_staff=True
)
def respond(self, user, puzzle, score):
submission = Submission.objects.create(event=self.event, user=user)
PuzzleResponse.objects.create(
submission=submission,
puzzle=puzzle,
puzzle_name=puzzle.title,
validated_cost=score,
validated_cycles=0,
validated_area=0,
)
def test_requires_staff(self):
self.client.force_login(self.alice)
response = self.client.get(URL)
self.assertEqual(response.status_code, 401)
def test_points_per_puzzle(self):
self.respond(self.alice, self.p1, 10)
self.respond(self.bob, self.p1, 20)
self.respond(self.bob, self.p2, 30)
self.client.force_login(self.admin)
response = self.client.get(URL)
self.assertEqual(
response.content.decode().splitlines(),
[
"username;Puzzle 1;Puzzle 2",
"bob;5;10",
"alice;10;0",
],
)
+6 -1
View File
@@ -4,6 +4,7 @@ Utilities for fetching Steam Workshop collection data using Steam Web API
import re
import requests
from events.models import Event
from opus_magnum.models import SteamCollection, SteamCollectionItem, SubmissionFile
from datetime import datetime
from django.utils import timezone
@@ -373,12 +374,15 @@ def fetch_steam_collection(url: str) -> Dict:
return fetcher.fetch_collection_data(url)
def create_or_update_collection(url: str) -> Tuple[SteamCollection, bool]:
def create_or_update_collection(
url: str, event: Event
) -> Tuple[SteamCollection, bool]:
"""
Create or update a Steam collection in the database
Args:
url: Steam Workshop collection URL
event: Event the collection belongs to
Returns:
Tuple of (SteamCollection instance, created_flag)
@@ -395,6 +399,7 @@ def create_or_update_collection(url: str) -> Tuple[SteamCollection, bool]:
collection, created = SteamCollection.objects.update_or_create(
steam_id=data["steam_id"],
defaults={
"event": event,
"url": data["url"],
"title": data["title"],
"description": data["description"],
+3
View File
@@ -12,6 +12,9 @@
},
"dependencies": {
"@tailwindcss/vite": "^4.1.16",
"@tanstack/query-persist-client-core": "^5.104.3",
"@tanstack/query-sync-storage-persister": "^5.104.3",
"@tanstack/vue-query": "^5.104.3",
"@tanstack/vue-table": "^8.21.3",
"@vueuse/core": "^14.0.0",
"dayjs": "^1.11.20",
+2 -2
View File
@@ -7,8 +7,8 @@ from .models import PixelPlacement, PlaceSettings
@admin.register(PlaceSettings)
class PlaceSettingsAdmin(DjangoObjectActions, admin.ModelAdmin):
list_display = ("event", "width", "height")
list_editable = ("width", "height")
list_display = ("event", "width", "height", "placement_ends_at")
list_editable = ("width", "height", "placement_ends_at")
list_filter = ("event",)
change_actions = ("resync_canvas",)
+117 -5
View File
@@ -1,5 +1,7 @@
import csv
import struct
from django.db.models import Count
from django.http import HttpRequest, HttpResponse
from ninja import Router
from ninja.decorators import decorate_view
@@ -8,8 +10,17 @@ from ninja.security import django_auth_is_staff
from games.decorators import require_game_enabled
from .canvas import read_canvas
from .export import build_final_png
from .gif import build_evolution_gif
from .models import PlaceSettings
from .heatmap import (
DecayMode,
build_heatmap_decay_gif,
build_heatmap_evolution_gif,
build_heatmap_png,
)
from .models import PixelPlacement, PlaceSettings
from .schemas import PlaceStatsOut
from .stats import build_place_stats
router = Router()
@@ -25,15 +36,116 @@ HEADER_FORMAT = "<HH"
@decorate_view(require_game_enabled(path="place"))
def canvas(request: HttpRequest, event_path: str):
"""The one-time full-grid load. Every placement after that arrives as a
single websocket message, never a re-fetch."""
single websocket message, never a re-fetch. Once placement is over the
board is shown wiped (Redis keeps the real final board, see tasks.py)."""
place_settings = PlaceSettings.current(request.event)
header = struct.pack(HEADER_FORMAT, place_settings.width, place_settings.height)
if place_settings.placement_ended:
pixels = bytes(place_settings.width * place_settings.height)
else:
pixels = read_canvas(event_path, place_settings.width, place_settings.height)
return HttpResponse(header + pixels, content_type="application/octet-stream")
@router.get(f"{PREFIX}/evolution.gif", auth=django_auth_is_staff)
@decorate_view(require_game_enabled(path="place"))
def evolution_gif(request: HttpRequest, event_path: str):
"""Admin-only: replays the full placement history as an animated GIF."""
return HttpResponse(build_evolution_gif(request.event), content_type="image/gif")
def evolution_gif(request: HttpRequest, event_path: str, players: str = ""):
"""Admin-only: replays the full placement history as an animated GIF.
`players` is an optional comma-separated list of usernames to only
replay those players' placements (combined)."""
usernames = [name.strip() for name in players.split(",") if name.strip()]
return HttpResponse(
build_evolution_gif(request.event, usernames), content_type="image/gif"
)
@router.get(f"{PREFIX}/final.png", auth=django_auth_is_staff)
@decorate_view(require_game_enabled(path="place"))
def final_png(request: HttpRequest, event_path: str):
"""Admin-only: the real final board as a PNG, even once placement is
over and everyone else sees it wiped."""
return HttpResponse(build_final_png(request.event), content_type="image/png")
@router.get(f"{PREFIX}/heatmap.png", auth=django_auth_is_staff)
@decorate_view(require_game_enabled(path="place"))
def heatmap_png(request: HttpRequest, event_path: str, players: str = ""):
"""Admin-only: how many times each pixel was placed, as a heatmap PNG.
`players` is an optional comma-separated list of usernames to only
count those players' placements (combined)."""
usernames = [name.strip() for name in players.split(",") if name.strip()]
return HttpResponse(
build_heatmap_png(request.event, usernames), content_type="image/png"
)
@router.get(f"{PREFIX}/heatmap-evolution.gif", auth=django_auth_is_staff)
@decorate_view(require_game_enabled(path="place"))
def heatmap_evolution_gif(request: HttpRequest, event_path: str, players: str = ""):
"""Admin-only: the heatmap building up over time, as an animated GIF.
`players` is an optional comma-separated list of usernames to only
count those players' placements (combined)."""
usernames = [name.strip() for name in players.split(",") if name.strip()]
return HttpResponse(
build_heatmap_evolution_gif(request.event, usernames),
content_type="image/gif",
)
@router.get(f"{PREFIX}/heatmap-decay.gif", auth=django_auth_is_staff)
@decorate_view(require_game_enabled(path="place"))
def heatmap_decay_gif(
request: HttpRequest,
event_path: str,
players: str = "",
half_life: float | None = None,
mode: DecayMode = "placements",
):
"""Admin-only: the heatmap over time, but heat decays so pixels nobody
touches anymore fade back to white.
`players` is an optional comma-separated list of usernames to only
count those players' placements (combined). `mode` is "placements"
(decay per placement, `half_life` in placements, defaults to 10 frames'
worth) or "time" (decay over time, `half_life` in minutes, defaults
to 60)."""
usernames = [name.strip() for name in players.split(",") if name.strip()]
return HttpResponse(
build_heatmap_decay_gif(request.event, usernames, half_life, mode),
content_type="image/gif",
)
@router.get(f"{PREFIX}/stats", auth=django_auth_is_staff, response=PlaceStatsOut)
@decorate_view(require_game_enabled(path="place"))
def stats(request: HttpRequest, event_path: str):
"""Admin-only: aggregated stats about the game - totals, coverage, top
players, most contested pixels, color usage and activity per hour."""
return build_place_stats(request.event)
@router.get(f"{PREFIX}/placements.csv", auth=django_auth_is_staff)
@decorate_view(require_game_enabled(path="place"))
def placements_csv(request: HttpRequest, event_path: str):
"""Admin-only: pixel placement count per player, most active first."""
rows = (
PixelPlacement.objects.filter(event=request.event)
.values("player__username")
.annotate(count=Count("id"))
.order_by("-count", "player__username")
)
# text/plain so browsers render it inline - most force-download text/csv
response = HttpResponse(content_type="text/plain; charset=utf-8")
writer = csv.writer(response)
writer.writerow(["username", "placements"])
for row in rows:
writer.writerow(
[
row["player__username"],
row["count"],
]
)
return response
+20 -1
View File
@@ -13,6 +13,10 @@ from .models import PALETTE, PLACE_COOLDOWN_SECONDS, PixelPlacement, PlaceSettin
from .wire import encode, to_epoch_ms
def _epoch_ms_or_none(dt):
return None if dt is None else to_epoch_ms(dt)
class PlaceConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.event_path = self.scope["url_route"]["kwargs"]["event_path"]
@@ -45,6 +49,10 @@ class PlaceConsumer(AsyncWebsocketConsumer):
await self.send(text_data=encode("r", "a"))
return
if place_settings.placement_ended:
await self.send(text_data=encode("r", "d"))
return
parts = text_data.split("|")
if len(parts) != 4:
await self.send(text_data=encode("r", "i"))
@@ -142,6 +150,7 @@ class PlaceConsumer(AsyncWebsocketConsumer):
next_placement_at,
place_settings.width,
place_settings.height,
_epoch_ms_or_none(place_settings.placement_ends_at),
)
@database_sync_to_async
@@ -152,4 +161,14 @@ class PlaceConsumer(AsyncWebsocketConsumer):
await self.send(text_data=encode("p", event["x"], event["y"], event["c"]))
async def settings_changed(self, event):
await self.send(text_data=encode("e", event["width"], event["height"]))
await self.send(
text_data=encode(
"e",
event["width"],
event["height"],
event["ends_at"],
)
)
async def wipe(self, event):
await self.send(text_data=encode("w"))
+31
View File
@@ -0,0 +1,31 @@
"""Exports one event's final board as a PNG.
Reads the live Redis canvas rather than replaying the history like gif.py -
once placement is over the canvas endpoint serves a wiped board, but Redis
still holds the real final one (see tasks.py).
"""
from io import BytesIO
from events.models import Event
from .canvas import read_canvas
from .gif import _render_frame
from .models import PlaceSettings
def build_final_png(event: Event) -> bytes:
"""Renders `event`'s current board as a PNG, upscaled like gif.py.
Redis only pads up to the last written pixel, so a short canvas is
padded with white (and a longer one, e.g. from before a shrink, cut)
to the current grid dimensions."""
place_settings = PlaceSettings.current(event)
width, height = place_settings.width, place_settings.height
size = width * height
canvas = read_canvas(event.path, width, height)[:size].ljust(size, b"\0")
buffer = BytesIO()
_render_frame(bytearray(canvas), width, height).save(buffer, format="PNG")
return buffer.getvalue()
+9 -6
View File
@@ -25,22 +25,25 @@ _PALETTE_RGB = [
]
def build_evolution_gif(event: Event) -> bytes:
def build_evolution_gif(event: Event, usernames: list[str] | None = None) -> bytes:
"""Renders `event`'s full placement history as an animated GIF, upscaled
for visibility. Returns GIF bytes, even if there are zero placements.
If `usernames` is given, only those players' placements are replayed
(combined on the same board).
Always replays at the *current* grid dimensions - a placement made
before a resize that now falls outside them is skipped rather than
raising."""
place_settings = PlaceSettings.current(event)
width, height = place_settings.width, place_settings.height
placements = (
PixelPlacement.objects.filter(event=event)
.order_by("placed_at")
.values_list("x", "y", "color_index")
placements = PixelPlacement.objects.filter(event=event)
if usernames:
placements = placements.filter(player__username__in=usernames)
placements = list(
placements.order_by("placed_at").values_list("x", "y", "color_index")
)
placements = list(placements)
grid = bytearray(width * height)
frames: list[Image.Image] = []
+240
View File
@@ -0,0 +1,240 @@
"""Renders one event's pixel placement history as a heatmap.
Same source as gif.py (the durable PixelPlacement history), but instead of
replaying colors, counts how many times each pixel was placed and maps that
count to a white -> red gradient, so an admin can see
where the action was - either as a single PNG of the final counts, as an
animated GIF of the counts building up over time, or as an animated GIF
where the heat decays so only recent activity stays red.
"""
import math
from io import BytesIO
from typing import Literal
from django.db.models import Count
from PIL import Image
from events.models import Event
from .gif import FINAL_FRAME_HOLD_MS, FRAME_DURATION_MS, MAX_FRAMES
from .models import PixelPlacement, PlaceSettings
SCALE = 8
# Gradient stops, from "never placed" to "most placed"
_GRADIENT = [
(255, 255, 255),
(193, 1, 2),
]
def build_heatmap_png(event: Event, usernames: list[str] | None = None) -> bytes:
"""Renders `event`'s placement counts per pixel as a PNG heatmap,
upscaled for visibility. Returns PNG bytes, even if there are zero
placements (all white).
If `usernames` is given, only those players' placements are counted
(combined on the same board).
Counts are log-scaled, otherwise a few heavily fought-over pixels make
everything else look white. Placements outside the *current* grid
dimensions are skipped, like in gif.py."""
place_settings = PlaceSettings.current(event)
width, height = place_settings.width, place_settings.height
placements = _placements(event, usernames)
counts = placements.values("x", "y").annotate(count=Count("id")).order_by()
grid = [0] * (width * height)
for row in counts:
if row["x"] >= width or row["y"] >= height:
continue
grid[row["y"] * width + row["x"]] = row["count"]
colors = _color_table(max(grid, default=0))
buffer = BytesIO()
_render_frame(grid, width, height, colors).save(buffer, format="PNG")
return buffer.getvalue()
def build_heatmap_evolution_gif(
event: Event, usernames: list[str] | None = None
) -> bytes:
"""Same as build_heatmap_png, but as an animated GIF where the counts
accumulate placement by placement (sampled down to MAX_FRAMES, like
gif.py). Returns GIF bytes, even if there are zero placements.
Every frame uses the *final* max count for its color scale, so a pixel's
color only ever heats up - otherwise early frames would look as hot as
the end."""
place_settings = PlaceSettings.current(event)
width, height = place_settings.width, place_settings.height
placements = [
(x, y)
for x, y in _placements(event, usernames)
.order_by("placed_at")
.values_list("x", "y")
if x < width and y < height
]
final_grid = [0] * (width * height)
for x, y in placements:
final_grid[y * width + x] += 1
colors = _color_table(max(final_grid, default=0))
grid = [0] * (width * height)
frames: list[Image.Image] = []
step = max(1, len(placements) // MAX_FRAMES)
for i, (x, y) in enumerate(placements):
grid[y * width + x] += 1
if i % step == 0 or i == len(placements) - 1:
frames.append(_render_frame(grid, width, height, colors))
if not frames:
frames.append(_render_frame(grid, width, height, colors))
return _save_gif(frames)
DecayMode = Literal["placements", "time"]
DEFAULT_HALF_LIFE_MINUTES = 60
def build_heatmap_decay_gif(
event: Event,
usernames: list[str] | None = None,
half_life: float | None = None,
mode: DecayMode = "placements",
) -> bytes:
"""Like build_heatmap_evolution_gif, but every pixel's heat decays
exponentially, so a pixel nobody touches anymore fades back to white
and the GIF shows where the activity is *right now*.
`mode` picks what drives the decay (and the frame spacing):
- "placements": `half_life` is in placements (after that many more
placements anywhere on the board, a pixel's heat is halved), defaults
to 10 frames' worth. Frames are one every N placements, so quiet
periods take almost no frames and nothing fades during them.
- "time": `half_life` is in minutes, defaults to an hour. Frames are
evenly spaced in time between the first and last placement, so quiet
periods actually show the board fading out.
Every frame shares the same color scale (the hottest pixel across the
whole replay), so a quiet period actually looks quiet."""
place_settings = PlaceSettings.current(event)
width, height = place_settings.width, place_settings.height
rows = [
(placed_at, x, y)
for placed_at, x, y in _placements(event, usernames)
.order_by("placed_at")
.values_list("placed_at", "x", "y")
if x < width and y < height
]
# Both modes boil down to a "clock" per placement, the clock values to
# snapshot a frame at, and a half-life in that clock's unit.
if mode == "time":
clocks = [placed_at.timestamp() for placed_at, _, _ in rows]
frame_clocks = _evenly_spaced(clocks, MAX_FRAMES)
half_life_clock = (half_life or DEFAULT_HALF_LIFE_MINUTES) * 60
else:
clocks = list(range(len(rows)))
step = max(1, len(rows) // MAX_FRAMES)
frame_clocks = [i for i in clocks if i % step == 0 or i == len(rows) - 1]
half_life_clock = half_life or step * 10
decay = 0.5 ** (1 / max(1e-9, half_life_clock))
# Decay is applied lazily: each pixel stores its heat as of the clock it
# was last touched at, so a placement is O(1) instead of decaying the
# whole grid every time.
heat = [0.0] * (width * height)
touched_at = [0.0] * (width * height)
snapshots: list[list[float]] = []
placement_index = 0
for frame_clock in frame_clocks:
while placement_index < len(rows) and clocks[placement_index] <= frame_clock:
_, x, y = rows[placement_index]
clock = clocks[placement_index]
index = y * width + x
heat[index] = heat[index] * decay ** (clock - touched_at[index]) + 1
touched_at[index] = clock
placement_index += 1
snapshots.append(
[h * decay ** (frame_clock - t) for h, t in zip(heat, touched_at)]
)
if not snapshots:
snapshots.append(heat)
max_log = math.log1p(max(max(snapshot) for snapshot in snapshots)) or 1
colors = [_gradient(i / 255) for i in range(256)]
frames = []
for snapshot in snapshots:
image = Image.new("RGB", (width, height))
image.putdata([colors[round(math.log1p(h) / max_log * 255)] for h in snapshot])
frames.append(image.resize((width * SCALE, height * SCALE), Image.NEAREST))
return _save_gif(frames)
def _evenly_spaced(clocks: list[float], count: int) -> list[float]:
"""`count` clock values evenly spread from the first to the last one
(just the one if they're all the same, none if `clocks` is empty)."""
if not clocks:
return []
first, last = clocks[0], clocks[-1]
if first == last:
return [first]
return [first + (last - first) * i / (count - 1) for i in range(count)]
def _save_gif(frames: list[Image.Image]) -> bytes:
buffer = BytesIO()
durations = [FRAME_DURATION_MS] * len(frames)
durations[-1] = FINAL_FRAME_HOLD_MS
frames[0].save(
buffer,
format="GIF",
save_all=True,
append_images=frames[1:],
duration=durations,
loop=0,
disposal=2,
)
return buffer.getvalue()
def _placements(event: Event, usernames: list[str] | None):
placements = PixelPlacement.objects.filter(event=event)
if usernames:
placements = placements.filter(player__username__in=usernames)
return placements
def _color_table(max_count: int) -> list[tuple[int, int, int]]:
"""Color for every count in [0, max_count], log-scaled."""
max_log = math.log1p(max_count) or 1
return [_gradient(math.log1p(count) / max_log) for count in range(max_count + 1)]
def _render_frame(
grid: list[int], width: int, height: int, colors: list[tuple[int, int, int]]
) -> Image.Image:
image = Image.new("RGB", (width, height))
image.putdata([colors[count] for count in grid])
return image.resize((width * SCALE, height * SCALE), Image.NEAREST)
def _gradient(t: float) -> tuple[int, int, int]:
"""Linearly interpolates `_GRADIENT` at `t` in [0, 1]."""
position = t * (len(_GRADIENT) - 1)
index = min(int(position), len(_GRADIENT) - 2)
frac = position - index
start, end = _GRADIENT[index], _GRADIENT[index + 1]
r, g, b = (round(a + (z - a) * frac) for a, z in zip(start, end))
return r, g, b
@@ -0,0 +1,18 @@
# Generated by Django 6.0.5 on 2026-10-25 09:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("place", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="placesettings",
name="placement_enabled",
field=models.BooleanField(default=True),
),
]
@@ -0,0 +1,21 @@
# Generated by Django 6.0.5 on 2026-10-25 09:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("place", "0002_placesettings_placement_enabled"),
]
operations = [
migrations.RemoveField(
model_name="placesettings",
name="placement_enabled",
),
migrations.AddField(
model_name="placesettings",
name="placement_ends_at",
field=models.DateTimeField(blank=True, null=True),
),
]
+13
View File
@@ -1,5 +1,6 @@
from django.conf import settings
from django.db import models
from django.utils import timezone
from events.models import Event
from events.scoping import EventScopedManager
@@ -47,10 +48,22 @@ class PlaceSettings(models.Model):
)
width = models.PositiveSmallIntegerField(default=DEFAULT_GRID_WIDTH)
height = models.PositiveSmallIntegerField(default=DEFAULT_GRID_HEIGHT)
# Past this, the game is over without taking it down: every placement
# is rejected and the board is shown wiped (see tasks.py). Only visual -
# the PixelPlacement history and the Redis canvas are kept as-is, so
# admin stats/heatmaps still see the final board. Empty = no end.
placement_ends_at = models.DateTimeField(null=True, blank=True)
def __str__(self):
return f"PlaceSettings({self.event}, size={self.width}x{self.height})"
@property
def placement_ended(self) -> bool:
return (
self.placement_ends_at is not None
and self.placement_ends_at <= timezone.now()
)
@classmethod
def current(cls, event: Event) -> "PlaceSettings":
obj, _ = cls.objects.get_or_create(event=event)
+48
View File
@@ -0,0 +1,48 @@
from datetime import datetime
from ninja import Schema
class PlayerCountOut(Schema):
username: str
placements: int
class PixelCountOut(Schema):
x: int
y: int
placements: int
players: int
class ColorCountOut(Schema):
color_index: int
color: str
placements: int
# How many pixels of the live board currently have this color
on_canvas: int
class HourCountOut(Schema):
hour: datetime
placements: int
players: int
class PlaceStatsOut(Schema):
width: int
height: int
total_placements: int
total_players: int
first_placement_at: datetime | None
last_placement_at: datetime | None
# Distinct pixels placed at least once (within the current grid)
pixels_touched: int
coverage: float
# Placements that landed on an already placed pixel
overwrites: int
avg_placements_per_player: float
top_players: list[PlayerCountOut]
most_contested_pixels: list[PixelCountOut]
colors: list[ColorCountOut]
per_hour: list[HourCountOut]
+11 -2
View File
@@ -1,13 +1,14 @@
"""Reacts to an admin editing a PlaceSettings row (grid size) by:
"""Reacts to an admin editing a PlaceSettings row (grid size, end time) by:
1. Rebuilding that event's Redis canvas from history at the (possibly new)
dimensions - a resize invalidates the old Redis bytes (wrong length,
wrong meaning), so this keeps Redis self-healing instead of relying on
the admin remembering to click "Resync canvas from DB" after every
resize.
2. Pushing the new size to that event's already-connected clients. Unlike
2. Pushing the new settings to that event's already-connected clients. Unlike
the clock app, place has no periodic heartbeat broadcast to piggyback
this onto, so it's broadcast explicitly here instead.
3. Queueing the wipe for the end time, if any (see tasks.py).
"""
from asgiref.sync import async_to_sync
@@ -18,11 +19,14 @@ from django.dispatch import receiver
from .broadcast import place_group
from .canvas import rebuild_canvas_from_history
from .models import PlaceSettings
from .tasks import schedule_wipe
from .wire import to_epoch_ms
@receiver(post_save, sender=PlaceSettings)
def on_settings_saved(sender, instance, **kwargs):
rebuild_canvas_from_history(instance.event, instance.width, instance.height)
schedule_wipe(instance)
channel_layer = get_channel_layer()
if channel_layer is None:
@@ -33,5 +37,10 @@ def on_settings_saved(sender, instance, **kwargs):
"type": "settings_changed",
"width": instance.width,
"height": instance.height,
"ends_at": (
None
if instance.placement_ends_at is None
else to_epoch_ms(instance.placement_ends_at)
),
},
)
+97
View File
@@ -0,0 +1,97 @@
"""Aggregated stats about one event's place game, for the admin stats
endpoint. Everything comes from the durable PixelPlacement history, except
the colors currently on the board, which are read off the live Redis canvas.
"""
from django.db.models import Count, Max, Min
from django.db.models.functions import TruncHour
from events.models import Event
from .canvas import read_canvas
from .models import PALETTE, PixelPlacement, PlaceSettings
TOP_N = 10
def build_place_stats(event: Event) -> dict:
place_settings = PlaceSettings.current(event)
width, height = place_settings.width, place_settings.height
placements = PixelPlacement.objects.filter(event=event)
totals = placements.aggregate(
total=Count("id"),
players=Count("player", distinct=True),
first=Min("placed_at"),
last=Max("placed_at"),
)
total, players = totals["total"], totals["players"]
# Same as heatmap.py, placements outside the current grid are skipped
in_grid = placements.filter(x__lt=width, y__lt=height)
pixels_touched = in_grid.values("x", "y").distinct().count()
top_players = (
placements.values("player__username")
.annotate(count=Count("id"))
.order_by("-count", "player__username")[:TOP_N]
)
contested = (
in_grid.values("x", "y")
.annotate(count=Count("id"), players=Count("player", distinct=True))
.order_by("-count", "-players", "y", "x")[:TOP_N]
)
color_counts = dict(
placements.values_list("color_index")
.annotate(count=Count("id"))
.order_by()
)
# Redis only pads up to the last written pixel, and keeps old bytes
# after a shrink, so normalize to the current grid size
size = width * height
canvas = read_canvas(event.path, width, height)[:size].ljust(size, b"\0")
per_hour = (
placements.annotate(hour=TruncHour("placed_at"))
.values("hour")
.annotate(count=Count("id"), players=Count("player", distinct=True))
.order_by("hour")
)
return {
"width": width,
"height": height,
"total_placements": total,
"total_players": players,
"first_placement_at": totals["first"],
"last_placement_at": totals["last"],
"pixels_touched": pixels_touched,
"coverage": pixels_touched / size if size else 0.0,
"overwrites": in_grid.count() - pixels_touched,
"avg_placements_per_player": total / players if players else 0.0,
"top_players": [
{"username": row["player__username"], "placements": row["count"]}
for row in top_players
],
"most_contested_pixels": [
{
"x": row["x"],
"y": row["y"],
"placements": row["count"],
"players": row["players"],
}
for row in contested
],
"colors": [
{
"color_index": index,
"color": color,
"placements": color_counts.get(index, 0),
"on_canvas": canvas.count(index),
}
for index, color in enumerate(PALETTE)
],
"per_hour": [
{"hour": row["hour"], "placements": row["count"], "players": row["players"]}
for row in per_hour
],
}
+65
View File
@@ -0,0 +1,65 @@
"""Ends the game at PlaceSettings.placement_ends_at: a task queued to run at
that time broadcasts the wipe to everyone connected, so they all see the
board cleared at the same moment (no client-side timer to drift).
The wipe is only visual. Nothing is deleted, the Redis canvas still holds the
final board (admin stats, heatmaps, resync keep working), it's just that the
canvas endpoint serves a blank board once placement is over (see api.py).
"""
from datetime import timedelta
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.core.cache import cache
from django.tasks import task
from django.utils import timezone
from .broadcast import place_group
from .models import PlaceSettings
from .wire import to_epoch_ms
# Kept a bit past the end time, so re-saving the settings with the same end
# time (or with only the size changed) doesn't queue the same wipe twice.
WIPE_GUARD_MARGIN = timedelta(hours=1)
def _wipe_guard_key(settings_id: int, ends_at_ms: int) -> str:
return f"place:wipe:{settings_id}:{ends_at_ms}"
def schedule_wipe(place_settings: PlaceSettings) -> bool:
"""Queue the wipe for this end time, unless it's already queued or the end
time is already past. Safe to call on every save."""
ends_at = place_settings.placement_ends_at
if ends_at is None or ends_at <= timezone.now():
return False
ends_at_ms = to_epoch_ms(ends_at)
timeout = int((ends_at - timezone.now() + WIPE_GUARD_MARGIN).total_seconds())
if not cache.add(_wipe_guard_key(place_settings.id, ends_at_ms), True, timeout):
return False
wipe_canvas_task.using(run_after=ends_at).enqueue(place_settings.id, ends_at_ms)
return True
@task
def wipe_canvas_task(settings_id: int, ends_at_ms: int):
"""Broadcast the wipe wave, if `ends_at_ms` is still the event's end time -
an admin moving or clearing it leaves the old job queued, it just stops
here."""
place_settings = (
PlaceSettings.objects.filter(id=settings_id).select_related("event").first()
)
if place_settings is None or place_settings.placement_ends_at is None:
return
if to_epoch_ms(place_settings.placement_ends_at) != ends_at_ms:
return
channel_layer = get_channel_layer()
if channel_layer is None:
return
async_to_sync(channel_layer.group_send)(
place_group(place_settings.event.path), {"type": "wipe"}
)
+210
View File
@@ -0,0 +1,210 @@
from datetime import timedelta
from io import BytesIO
from unittest import mock
from django.core.cache import cache
from django.test import TestCase, override_settings
from django.utils import timezone
from PIL import Image
from accounts.models import CustomUser
from events.models import Event
from games.models import EventGame, Game
from .models import PixelPlacement, PlaceSettings
from .tasks import schedule_wipe, wipe_canvas_task
from .wire import to_epoch_ms
URL = "/api/events/event/place/stats"
CANVAS_URL = "/api/events/event/place/canvas"
FINAL_URL = "/api/events/event/place/final.png"
LOCMEM_CACHE = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
@mock.patch("place.stats.read_canvas")
class PlaceStatsTests(TestCase):
def setUp(self):
self.event = Event.objects.create(name="Event", path="event")
place = Game.objects.create(name="Place", path="place", custom_path=True)
EventGame.objects.create(event=self.event, game=place)
PlaceSettings.objects.create(event=self.event, width=4, height=2)
self.alice = CustomUser.objects.create_user(username="alice", password="x")
self.bob = CustomUser.objects.create_user(username="bob", password="x")
self.admin = CustomUser.objects.create_user(
username="admin", password="x", is_staff=True
)
def place(self, player, x, y, color_index):
PixelPlacement.objects.create(
event=self.event, player=player, x=x, y=y, color_index=color_index
)
def test_requires_staff(self, _):
self.client.force_login(self.alice)
response = self.client.get(URL)
self.assertEqual(response.status_code, 401)
def test_empty_game(self, read_canvas):
read_canvas.return_value = b""
self.client.force_login(self.admin)
data = self.client.get(URL).json()
self.assertEqual(data["total_placements"], 0)
self.assertEqual(data["total_players"], 0)
self.assertEqual(data["coverage"], 0.0)
self.assertEqual(data["avg_placements_per_player"], 0.0)
self.assertEqual(data["colors"][0]["on_canvas"], 8)
self.assertEqual(data["per_hour"], [])
def test_stats(self, read_canvas):
self.place(self.alice, 0, 0, 5)
self.place(self.bob, 0, 0, 3)
self.place(self.alice, 0, 0, 5)
self.place(self.alice, 1, 0, 3)
# Outside the current grid, e.g. from before a shrink
self.place(self.bob, 9, 9, 3)
# Short canvas, Redis only padded up to the last written pixel
read_canvas.return_value = bytes([5, 3])
self.client.force_login(self.admin)
data = self.client.get(URL).json()
self.assertEqual(data["total_placements"], 5)
self.assertEqual(data["total_players"], 2)
self.assertEqual(data["pixels_touched"], 2)
self.assertEqual(data["coverage"], 0.25)
self.assertEqual(data["overwrites"], 2)
self.assertEqual(data["avg_placements_per_player"], 2.5)
self.assertEqual(
data["top_players"],
[
{"username": "alice", "placements": 3},
{"username": "bob", "placements": 2},
],
)
self.assertEqual(
data["most_contested_pixels"][0],
{"x": 0, "y": 0, "placements": 3, "players": 2},
)
colors = {row["color_index"]: row for row in data["colors"]}
self.assertEqual(colors[5]["placements"], 2)
self.assertEqual(colors[3]["placements"], 3)
self.assertEqual(colors[5]["on_canvas"], 1)
self.assertEqual(colors[0]["on_canvas"], 6)
self.assertEqual(sum(row["placements"] for row in data["per_hour"]), 5)
@mock.patch("place.export.read_canvas")
class FinalPngTests(TestCase):
def setUp(self):
self.event = Event.objects.create(name="Event", path="event")
place = Game.objects.create(name="Place", path="place", custom_path=True)
EventGame.objects.create(event=self.event, game=place)
PlaceSettings.objects.create(
event=self.event,
width=2,
height=1,
# Ended, the real board is still exported
placement_ends_at=timezone.now() - timedelta(hours=1),
)
self.alice = CustomUser.objects.create_user(username="alice", password="x")
self.admin = CustomUser.objects.create_user(
username="admin", password="x", is_staff=True
)
def test_requires_staff(self, _):
self.client.force_login(self.alice)
response = self.client.get(FINAL_URL)
self.assertEqual(response.status_code, 401)
def test_final_png(self, read_canvas):
# Short canvas, Redis only padded up to the last written pixel
read_canvas.return_value = bytes([5])
self.client.force_login(self.admin)
response = self.client.get(FINAL_URL)
self.assertEqual(response["Content-Type"], "image/png")
image = Image.open(BytesIO(response.content))
self.assertEqual(image.size, (16, 8))
self.assertEqual(image.getpixel((0, 0)), (229, 0, 0))
self.assertEqual(image.getpixel((15, 0)), (255, 255, 255))
@override_settings(CACHES=LOCMEM_CACHE)
@mock.patch("place.signals.rebuild_canvas_from_history")
class PlacementEndTests(TestCase):
def setUp(self):
cache.clear()
self.event = Event.objects.create(name="Event", path="event")
place = Game.objects.create(name="Place", path="place", custom_path=True)
EventGame.objects.create(event=self.event, game=place)
self.alice = CustomUser.objects.create_user(username="alice", password="x")
def settings(self, ends_at):
with mock.patch("place.signals.schedule_wipe"):
return PlaceSettings.objects.create(
event=self.event, width=2, height=1, placement_ends_at=ends_at
)
@mock.patch("place.api.read_canvas")
def test_canvas_is_blank_once_ended(self, read_canvas, _):
read_canvas.return_value = bytes([5, 3])
place_settings = self.settings(timezone.now() + timedelta(hours=1))
self.client.force_login(self.alice)
self.assertEqual(self.client.get(CANVAS_URL).content[4:], bytes([5, 3]))
place_settings.placement_ends_at = timezone.now() - timedelta(seconds=1)
with mock.patch("place.signals.schedule_wipe"):
place_settings.save()
self.assertEqual(self.client.get(CANVAS_URL).content[4:], bytes(2))
@mock.patch("place.tasks.wipe_canvas_task")
def test_wipe_is_scheduled_once_per_end_time(self, task, _):
ends_at = timezone.now() + timedelta(hours=1)
place_settings = self.settings(ends_at)
self.assertTrue(schedule_wipe(place_settings))
self.assertFalse(schedule_wipe(place_settings))
task.using.assert_called_once_with(run_after=ends_at)
task.using.return_value.enqueue.assert_called_once_with(
place_settings.id, to_epoch_ms(ends_at)
)
@mock.patch("place.tasks.wipe_canvas_task")
def test_no_wipe_without_future_end(self, task, _):
self.assertFalse(schedule_wipe(self.settings(None)))
past = PlaceSettings(placement_ends_at=timezone.now() - timedelta(seconds=1))
self.assertFalse(schedule_wipe(past))
task.using.assert_not_called()
@mock.patch("place.tasks.get_channel_layer")
def test_task_broadcasts_wipe(self, get_channel_layer, _):
ends_at = timezone.now()
place_settings = self.settings(ends_at)
layer = get_channel_layer.return_value
layer.group_send = mock.AsyncMock()
wipe_canvas_task.call(place_settings.id, to_epoch_ms(ends_at))
layer.group_send.assert_awaited_once_with("place_room_event", {"type": "wipe"})
@mock.patch("place.tasks.get_channel_layer")
def test_task_skips_moved_end_time(self, get_channel_layer, _):
ends_at = timezone.now()
place_settings = self.settings(ends_at + timedelta(hours=1))
layer = get_channel_layer.return_value
layer.group_send = mock.AsyncMock()
wipe_canvas_task.call(place_settings.id, to_epoch_ms(ends_at))
layer.group_send.assert_not_awaited()
+14 -6
View File
@@ -6,8 +6,10 @@ either). Each message is a short string: a one-letter type tag followed by
'|'-separated fields, in a fixed order the client already knows from this
table:
s|<next>|<width>|<height> initial personal state, once per connection
(next = epoch ms cooldown ends, or empty if free now)
s|<next>|<width>|<height>|<end>
initial personal state, once per connection
(next = epoch ms cooldown ends, or empty if free now;
end = epoch ms placement ends, or empty if never)
p|<x>|<y>|<c> a pixel was placed - broadcast to everyone,
including the placer (no separate ack needed)
k|<next> your own placement was accepted; carries your
@@ -15,10 +17,16 @@ table:
r|c|<next> rejected: still on cooldown
r|a rejected: not logged in
r|i rejected: invalid x/y/color
e|<width>|<height> an admin resized the grid for this event -
broadcast to everyone. A client that sees this
should re-fetch /api/.../place/canvas rather than
try to remap its local pixels.
r|d rejected: placement is over (past <end>)
e|<width>|<height>|<end>
an admin edited this event's settings (grid size
and/or end time) - broadcast to everyone.
If the size changed, a client should re-fetch
/api/.../place/canvas rather than try to remap its
local pixels.
w placement just ended - broadcast to everyone at
<end> (see tasks.py). Clients play the wipe wave
and blank their board.
Client -> server has exactly one message shape, the same as the broadcast:
p|<x>|<y>|<c>
+74
View File
@@ -11,6 +11,15 @@ importers:
'@tailwindcss/vite':
specifier: ^4.1.16
version: 4.1.16(vite@7.1.12(@types/node@24.9.2)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.4))
'@tanstack/query-persist-client-core':
specifier: ^5.104.3
version: 5.104.3
'@tanstack/query-sync-storage-persister':
specifier: ^5.104.3
version: 5.104.3
'@tanstack/vue-query':
specifier: ^5.104.3
version: 5.104.3(vue@3.5.22(typescript@5.9.3))
'@tanstack/vue-table':
specifier: ^8.21.3
version: 8.21.3(vue@3.5.22(typescript@5.9.3))
@@ -515,10 +524,32 @@ packages:
peerDependencies:
vite: ^5.2.0 || ^6 || ^7
'@tanstack/match-sorter-utils@9.2.6':
resolution: {integrity: sha512-DIpUSOhPfQ7u/qfUi/Wgm0wBO56MyBYXGvnlI0NcauDRPqdBUlAZZjW2Dxm92m+k1UWVhKw8YJ4f47+75Aujyw==}
engines: {node: '>=20'}
'@tanstack/query-core@5.104.3':
resolution: {integrity: sha512-DZY9TuJAOgU3UyHUhXb4CcTYEHNZszlwkPg4VViIwTxOKzLprPUU+rbaPZQd3srqkGOtpaDdKpW972UV/LKlcg==}
'@tanstack/query-persist-client-core@5.104.3':
resolution: {integrity: sha512-6nhc/QbMpkKeuAM81SFSdcsJ9B8dm3fGHPODbau2cRSDyqcXiSl7sXQM7POVktch/YdgIGYPIQyZOQQaRarHMA==}
'@tanstack/query-sync-storage-persister@5.104.3':
resolution: {integrity: sha512-sNM9X7QZdTHBlzHuNxuHQjECn3/zncuMgw5pesOFXu8XQ01UXBGASdMKZSRaxfNOhigRjm5souHhfmByN97NEg==}
'@tanstack/table-core@8.21.3':
resolution: {integrity: sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==}
engines: {node: '>=12'}
'@tanstack/vue-query@5.104.3':
resolution: {integrity: sha512-bdVlhyEFPllLfHioHx8kwtCAQ1YJQrvYczlsNzyiYFsp6n5yz9isNXiy6MIu+QGmG+RyghVdnp1UmiNDqLS22g==}
peerDependencies:
'@vue/composition-api': ^1.1.2
vue: ^2.6.0 || ^3.3.0
peerDependenciesMeta:
'@vue/composition-api':
optional: true
'@tanstack/vue-table@8.21.3':
resolution: {integrity: sha512-rusRyd77c5tDPloPskctMyPLFEQUeBzxdQ+2Eow4F7gDPlPOB1UnnhzfpdvqZ8ZyX2rRNGmqNnQWm87OI2OQPw==}
engines: {node: '>=12'}
@@ -961,6 +992,9 @@ packages:
regenerator-runtime@0.13.11:
resolution: {integrity: sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==}
remove-accents@0.5.0:
resolution: {integrity: sha512-8g3/Otx1eJaVD12e31UbJj1YzdtVvzH85HV7t+9MJYk/u3XmkOUJ5Ys9wQrf9PCPK8+xn4ymzqYCiZl6QWKn+A==}
resolve-pkg-maps@1.0.0:
resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==}
@@ -1072,6 +1106,17 @@ packages:
vscode-uri@3.1.0:
resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==}
vue-demi@0.14.10:
resolution: {integrity: sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==}
engines: {node: '>=12'}
hasBin: true
peerDependencies:
'@vue/composition-api': ^1.0.0-rc.1
vue: ^3.0.0-0 || ^2.6.0
peerDependenciesMeta:
'@vue/composition-api':
optional: true
vue-i18n@11.4.12:
resolution: {integrity: sha512-yvArvvo3ErLKFNlQrZUGmRkxL/ctM5xFYtE9FxTKiE/PalWP1bnTopBgbSRGLluYEyYSNl1Pt8l2J7zVavbXww==}
engines: {node: '>= 22'}
@@ -1445,8 +1490,31 @@ snapshots:
tailwindcss: 4.1.16
vite: 7.1.12(@types/node@24.9.2)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.4)
'@tanstack/match-sorter-utils@9.2.6':
dependencies:
remove-accents: 0.5.0
'@tanstack/query-core@5.104.3': {}
'@tanstack/query-persist-client-core@5.104.3':
dependencies:
'@tanstack/query-core': 5.104.3
'@tanstack/query-sync-storage-persister@5.104.3':
dependencies:
'@tanstack/query-core': 5.104.3
'@tanstack/query-persist-client-core': 5.104.3
'@tanstack/table-core@8.21.3': {}
'@tanstack/vue-query@5.104.3(vue@3.5.22(typescript@5.9.3))':
dependencies:
'@tanstack/match-sorter-utils': 9.2.6
'@tanstack/query-core': 5.104.3
'@vue/devtools-api': 6.6.4
vue: 3.5.22(typescript@5.9.3)
vue-demi: 0.14.10(vue@3.5.22(typescript@5.9.3))
'@tanstack/vue-table@8.21.3(vue@3.5.22(typescript@5.9.3))':
dependencies:
'@tanstack/table-core': 8.21.3
@@ -1863,6 +1931,8 @@ snapshots:
regenerator-runtime@0.13.11: {}
remove-accents@0.5.0: {}
resolve-pkg-maps@1.0.0: {}
rfdc@1.4.1: {}
@@ -1962,6 +2032,10 @@ snapshots:
vscode-uri@3.1.0: {}
vue-demi@0.14.10(vue@3.5.22(typescript@5.9.3)):
dependencies:
vue: 3.5.22(typescript@5.9.3)
vue-i18n@11.4.12(vue@3.5.22(typescript@5.9.3)):
dependencies:
'@intlify/core-base': 11.4.12
+2 -2
View File
@@ -57,14 +57,14 @@ api.add_router("", market_router, tags=["market"])
# Health check endpoint
@api.get("/health")
@api.get("/health", response=dict)
def health_check(request):
"""Health check endpoint"""
return {"status": "healthy", "service": "polylan-submitter-api"}
# Cache management endpoint
@api.post("/cache/clear")
@api.post("/cache/clear", response={200: dict, 403: dict})
def clear_cache(request: HttpRequest, event_path: str | None = None):
"""Clear API caches (admin only). Pass event_path to clear just that event's keys."""
if not request.user.is_authenticated or not request.user.is_staff:
@@ -64,6 +64,26 @@ ALLOWED_HOSTS = [
if host
]
# TLS is terminated by the reverse proxy in front of the container, so daphne
# only ever sees plain http. Without these, Django compares the browser's
# `Origin: https://...` against `http://...` and rejects every POST (admin
# login included) with "CSRF verification failed - Origin checking failed".
# Full origins with scheme, e.g. "https://submitter.polylan.ch".
CSRF_TRUSTED_ORIGINS = [
origin
for origin in (os.environ.get("DJANGO_CSRF_TRUSTED_ORIGINS") or "").split(",")
if origin
]
# Trust the proxy's X-Forwarded-Proto so request.is_secure() /
# build_absolute_uri() report https. Only safe if the proxy overwrites that
# header (client-supplied values must not pass through) - opt-in for that
# reason.
if os.environ.get("DJANGO_BEHIND_TLS_PROXY", "false").lower() == "true":
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
# Application definition
@@ -231,6 +251,12 @@ LOAD_TEST_LOGIN_ENABLED = (
# Steam API Configuration
STEAM_API_KEY = os.environ.get("STEAM_API_KEY") or None # Set via environment variable
# Steam store info (price, discount, blurb) for the event's Steam games, refreshed
# in the background every STEAM_STORE_REFRESH_MINUTES (see games.tasks)
STEAM_STORE_REFRESH_MINUTES = int(os.environ.get("STEAM_STORE_REFRESH_MINUTES") or 360)
# Store region the prices are fetched for (ISO country code, drives the currency)
STEAM_STORE_COUNTRY = os.environ.get("STEAM_STORE_COUNTRY") or "ch"
# Base URL of the legacy PolyLAN site, used to sync AAndT matches/members
# (see submissions.services.aandt_sync)
AANDT_API_BASE_URL = os.environ.get("AANDT_API_BASE_URL") or "https://polylan.ch"
@@ -376,6 +402,6 @@ sentry_sdk.init(
dsn=SENTRY_DSN,
# Set traces_sample_rate to 1.0 to capture 100%
# of transactions for tracing.
traces_sample_rate=1.0,
traces_sample_rate=0.1,
environment=SENTRY_ENVIRONMENT,
)
@@ -50,6 +50,18 @@ def event_home(request: HttpRequest, event_path: str):
return render(request, "app.html")
@login_required
def games_home(request: HttpRequest, event_path: str):
get_object_or_404(Event, path=event_path)
return render(request, "app.html")
@login_required
def planning_home(request: HttpRequest, event_path: str):
get_object_or_404(Event, path=event_path)
return render(request, "app.html")
@login_required
@require_game_enabled(OPUS_MAGNUM_APP_ID)
def opus_magnum_home(request: HttpRequest, event_path: str):
@@ -95,6 +107,8 @@ urlpatterns = [
path("cas/login/", SimpleCASLoginView.as_view(), name="cas_ng_login"),
path("cas/logout/", SimpleCASLogoutView.as_view(), name="cas_ng_logout"),
path("api/", api.urls),
path("<slug:event_path>/games", games_home, name="games.home"),
path("<slug:event_path>/planning", planning_home, name="planning.home"),
path("<slug:event_path>/market", market_home, name="market.home"),
path("<slug:event_path>/opus-magnum", opus_magnum_home, name="opus-magnum.home"),
path("<slug:event_path>/noita", noita_home, name="noita.home"),
+1 -7
View File
@@ -1,20 +1,14 @@
<script setup lang="ts">
import { computed, onMounted } from "vue";
import { computed } from "vue";
import { RouterView, useRoute } from "vue-router";
import AppHeader from "@/layout/AppHeader.vue";
import AppFooter from "@/layout/AppFooter.vue";
import { useUserStore } from "@/stores/user";
const userStore = useUserStore();
const route = useRoute();
// Embed routes (e.g. place/embed) are meant to be dropped into an <iframe>
// as-is - the header/footer chrome would just eat into the fixed space a
// stream overlay or OBS browser source gives it.
const isEmbed = computed(() => route.meta.embed === true);
onMounted(() => {
userStore.loadUserData();
});
</script>
<template>
+2 -4
View File
@@ -3,6 +3,7 @@ import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { useTitle } from "@vueuse/core";
import { useClockSocket } from "@/composables/useClockSocket";
import { useLiveBadge } from "@/composables/useLiveBadge";
interface Props {
eventPath: string;
@@ -25,6 +26,7 @@ const {
cooldownDurationSeconds,
press,
} = useClockSocket(props.eventPath);
useLiveBadge("clock", connected);
const remainingDisplay = computed(() => {
const totalSeconds = Math.floor(remainingMs.value / 1000);
@@ -38,10 +40,6 @@ const onCooldown = computed(() => cooldownRemainingMs.value > 0);
<template>
<div class="flex-1 bg-base-200 flex flex-col items-center px-4 py-8 gap-8">
<span class="badge" :class="connected ? 'badge-success' : 'badge-error'">
{{ connected ? t("clock.connected") : t("clock.reconnecting") }}
</span>
<div class="font-bold text-7xl tabular-nums">
{{ remainingDisplay }}
</div>
+70
View File
@@ -0,0 +1,70 @@
<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useI18n } from "vue-i18n";
import { useStorage, useTitle } from "@vueuse/core";
import { gamesApiListEventSteamGames } from "./api";
import type { SteamGameOut } from "./api/types.gen";
import SteamLibraryCard from "./components/SteamLibraryCard.vue";
import SteamStoreCard from "./components/SteamStoreCard.vue";
interface Props {
eventPath: string;
}
const props = defineProps<Props>();
const { t } = useI18n();
useTitle(computed(() => t("games.title")));
const games = ref<SteamGameOut[]>([]);
const loading = ref(true);
// Library (vertical covers) by default, the store cards show the prices
const showPrices = useStorage("games.showPrices", true);
onMounted(async () => {
const response = await gamesApiListEventSteamGames({
path: { event_path: props.eventPath },
});
if (response.data) {
games.value = response.data;
}
loading.value = false;
});
</script>
<template>
<div class="flex-1 bg-base-300 flex justify-center px-4 py-12">
<div class="w-full max-w-7xl">
<!-- Header -->
<div class="text-center mb-8">
<h1 class="text-5xl font-bold mb-4">{{ t("games.title") }}</h1>
<p class="text-xl text-base-content/70">{{ t("games.subtitle") }}</p>
</div>
<div class="flex justify-end mb-6">
<label class="label cursor-pointer gap-2">
<span>{{ t("games.showPrices") }}</span>
<input v-model="showPrices" type="checkbox" class="toggle toggle-primary" />
</label>
</div>
<!-- Loading -->
<div v-if="loading" class="flex justify-center py-20">
<span class="loading loading-spinner loading-lg"></span>
</div>
<p v-else-if="!games.length" class="text-center text-base-content/50 py-20">
{{ t("games.empty") }}
</p>
<div v-else-if="showPrices" class="grid grid-cols-1 lg:grid-cols-2 gap-8">
<SteamStoreCard v-for="game in games" :key="game.id" :game="game" />
</div>
<div v-else
class="grid grid-cols-[repeat(auto-fill,minmax(9rem,1fr))] sm:grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-4 sm:gap-6">
<SteamLibraryCard v-for="game in games" :key="game.id" :game="game" />
</div>
</div>
</div>
</template>
+21 -15
View File
@@ -1,9 +1,10 @@
<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { ref, computed } from "vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { useTitle } from "@vueuse/core";
import { gamesApiListEventGames } from "./api";
import { useQuery } from "@tanstack/vue-query";
import { eventGamesQuery, eventPlanningQuery } from "@/queries";
import type { GamesApiListEventGamesResponse } from "./api/types.gen";
interface Props {
@@ -16,8 +17,10 @@ const router = useRouter();
const { t } = useI18n();
useTitle(computed(() => t("home.title")));
const games = ref<GamesApiListEventGamesResponse | undefined>();
const loading = ref(true);
const { data: games, isPending: loading } = useQuery(eventGamesQuery(props.eventPath));
const hasSteamGames = computed(() => games.value?.some((game) => game.steam_app_id) ?? false);
const { data: planning } = useQuery(eventPlanningQuery(props.eventPath));
const hasPlanning = computed(() => !!planning.value?.length);
const imageErrors = ref<Set<number>>(new Set());
const getHeaderImage = (game: GamesApiListEventGamesResponse[number]) => {
@@ -39,20 +42,11 @@ const goToGame = (game: GamesApiListEventGamesResponse[number]) => {
router.push(`/${props.eventPath}${path}`);
};
onMounted(async () => {
const gamesResponse = await gamesApiListEventGames({
path: { event_path: props.eventPath },
});
if (gamesResponse.data) {
games.value = gamesResponse.data;
}
loading.value = false;
});
</script>
<template>
<div class="flex-1 bg-base-300 flex items-center justify-center px-4">
<div class="w-full max-w-6xl">
<div class="w-full max-w-7xl">
<!-- Header -->
<div class="text-center mb-12">
<h1 class="text-5xl font-bold mb-4">{{ t("home.title") }}</h1>
@@ -83,7 +77,7 @@ onMounted(async () => {
</figure>
<div class="card-body">
<h2 class="card-title text-2xl">{{ game.name }}</h2>
<p v-if="game.description" class="text-base-content/70">{{ game.description }}</p>
<p v-if="game.description" class="text-sm text-base-content/70 line-clamp-2" :title="game.description">{{ game.description }}</p>
<div class="card-actions justify-end mt-4">
<button class="btn btn-primary">
<i class="mdi mdi-arrow-right mr-2"></i>
@@ -94,6 +88,18 @@ onMounted(async () => {
</div>
</div>
<!-- Links to the planning and the Steam games page -->
<div v-if="!loading && (hasPlanning || hasSteamGames)" class="flex flex-wrap justify-center gap-4 mt-12">
<RouterLink v-if="hasPlanning" :to="{ name: 'planning', params: { eventPath } }" class="btn btn-outline">
<i class="mdi mdi-calendar-clock mr-2"></i>
{{ t("home.planning") }}
</RouterLink>
<RouterLink v-if="hasSteamGames" :to="{ name: 'games', params: { eventPath } }" class="btn btn-outline">
<i class="mdi mdi-steam mr-2"></i>
{{ t("home.getTheGames") }}
</RouterLink>
</div>
<!-- Footer -->
<div class="text-center mt-12 text-base-content/50">
<p>{{ t("home.footer") }}</p>
+3 -8
View File
@@ -9,10 +9,11 @@ import Results from "@/components/Results.vue";
import Winners from "@/components/Winners.vue";
import PuzzleResults from "@/components/PuzzleResults.vue";
import TopUsersLeaderboard from "@/components/TopUsersLeaderboard.vue";
import { polylanSubmitterApiGetUserInfo, opusMagnumApiGetCollection } from "@/api";
import { opusMagnumApiGetCollection } from "@/api";
import { apiService, errorHelpers } from "@/services/apiService";
import { usePuzzlesStore } from "@/stores/puzzles";
import { useSubmissionsStore } from "@/stores/submissions";
import { queryClient, userQuery } from "@/queries";
import { provideEventPath } from "@/composables/useEventPath";
import type { PuzzleResponse, UserInfo, SteamCollection } from "@/types";
import { useCountdown } from "@vueuse/core";
@@ -74,13 +75,7 @@ async function initialize() {
// Load user info
console.log("Loading user info...");
const userResponse = await polylanSubmitterApiGetUserInfo();
if (userResponse.data) {
userInfo.value = userResponse.data as UserInfo;
console.log("User info loaded:", userResponse.data);
} else if (userResponse.error) {
console.warn("User info error:", userResponse.error);
}
userInfo.value = (await queryClient.fetchQuery(userQuery()).catch(() => null)) as UserInfo | null;
// Load collection data
console.log("Loading collection...");
+45 -20
View File
@@ -1,9 +1,11 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useTitle } from "@vueuse/core";
import { usePlaceSocket } from "@/composables/usePlaceSocket";
import { useLiveBadge } from "@/composables/useLiveBadge";
import { PALETTE } from "@/palette";
import { playWipeWave } from "@/placeWipe";
interface Props {
eventPath: string;
@@ -39,20 +41,39 @@ function drawPixel(x: number, y: number, colorIndex: number) {
pixelCtx.fillRect(x, y, 1, 1);
}
let cancelWipe: (() => void) | null = null;
function wipe() {
if (!pixelCtx) return;
cancelWipe?.();
cancelWipe = playWipeWave(pixelCtx, gridWidth.value, gridHeight.value);
}
onBeforeUnmount(() => cancelWipe?.());
const {
connected,
cooldownRemainingMs,
placementEndMs,
placementEnded,
cooldownDurationSeconds,
gridWidth,
gridHeight,
place,
} = usePlaceSocket(props.eventPath, drawPixel);
} = usePlaceSocket(props.eventPath, drawPixel, undefined, wipe);
useLiveBadge("place", connected);
const overlayWidth = computed(() => gridWidth.value * PX_PER_CELL);
const overlayHeight = computed(() => gridHeight.value * PX_PER_CELL);
const cooldownSecondsDisplay = computed(() => (cooldownRemainingMs.value / 1000).toFixed(1));
const onCooldown = computed(() => cooldownRemainingMs.value > 0);
const canPlace = computed(() => !placementEnded.value && !onCooldown.value);
const placementEndDisplay = computed(() =>
placementEndMs.value !== null
? new Date(placementEndMs.value).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
: null,
);
// The overlay canvas never touches the pixel colors - it only draws grid
// lines plus a preview of the hovered cell, so it can freely redraw on
@@ -84,7 +105,7 @@ function drawOverlay() {
}
}
if (hoveredCell.value && !onCooldown.value) {
if (hoveredCell.value && canPlace.value) {
const { x, y } = hoveredCell.value;
gridCtx.fillStyle = `${PALETTE[selectedColorIndex.value]}80`;
gridCtx.fillRect(x * PX_PER_CELL, y * PX_PER_CELL, PX_PER_CELL, PX_PER_CELL);
@@ -94,7 +115,7 @@ function drawOverlay() {
}
}
watch([selectedColorIndex, onCooldown, showGrid, gridWidth, gridHeight], drawOverlay);
watch([selectedColorIndex, canPlace, showGrid, gridWidth, gridHeight], drawOverlay);
onMounted(() => {
pixelCtx = pixelCanvasRef.value?.getContext("2d") ?? null;
@@ -123,7 +144,7 @@ function handleMouseLeave() {
}
function handleClick(event: MouseEvent) {
if (onCooldown.value) return;
if (!canPlace.value) return;
const { x, y } = cellFromEvent(event);
place(x, y, selectedColorIndex.value);
}
@@ -131,24 +152,36 @@ function handleClick(event: MouseEvent) {
<template>
<div class="flex-1 bg-base-200 flex flex-col items-center px-4 py-8 gap-6">
<span class="badge" :class="connected ? 'badge-success' : 'badge-error'">
{{ connected ? t("place.connected") : t("place.reconnecting") }}
</span>
<div class="relative w-full max-w-[512px]" :style="{ aspectRatio: `${gridWidth} / ${gridHeight}` }">
<!-- Sized to fill the width, but capped so the full height (minus the
navbar and the controls below) still fits in the viewport. -->
<div class="relative" :style="{
aspectRatio: `${gridWidth} / ${gridHeight}`,
width: `min(100%, calc((100dvh - 16rem) * ${gridWidth} / ${gridHeight}))`,
}">
<canvas ref="pixelCanvasRef" :width="gridWidth" :height="gridHeight"
class="absolute inset-0 w-full h-full border border-base-300 rounded-box shadow-lg" :style="{
imageRendering: 'pixelated',
cursor: onCooldown ? 'not-allowed' : 'crosshair',
cursor: canPlace ? 'crosshair' : 'not-allowed',
}" @click="handleClick" @mousemove="handleMouseMove" @mouseleave="handleMouseLeave" />
<canvas ref="gridCanvasRef" :width="overlayWidth" :height="overlayHeight"
class="absolute inset-0 w-full h-full rounded-box pointer-events-none" />
</div>
<div class="flex items-center gap-2">
<!-- Timer shares the toggle row so showing it doesn't push the page past
the viewport height the grid is sized against. -->
<div class="flex items-center gap-4 h-8">
<button class="btn btn-ghost btn-sm" @click="showGrid = !showGrid">
{{ showGrid ? t("place.hideGrid") : t("place.showGrid") }}
</button>
<span v-if="placementEnded" class="badge badge-warning">{{ t("place.placementEnded") }}</span>
<template v-else-if="onCooldown">
<span class="font-bold text-xl tabular-nums">{{ cooldownSecondsDisplay }}s</span>
<progress class="progress progress-primary w-48"
:value="cooldownDurationSeconds - cooldownRemainingMs / 1000" :max="cooldownDurationSeconds" />
</template>
<span v-if="placementEndDisplay && !placementEnded" class="text-sm opacity-70">
{{ t("place.endsAt", { time: placementEndDisplay }) }}
</span>
</div>
<div class="flex flex-wrap justify-center gap-2 max-w-md">
@@ -156,13 +189,5 @@ function handleClick(event: MouseEvent) {
:class="selectedColorIndex === index ? 'border-primary scale-110' : 'border-base-300'"
:style="{ backgroundColor: color }" @click="selectedColorIndex = index" />
</div>
<div class="flex flex-col items-center gap-2">
<span v-if="onCooldown" class="font-bold text-2xl tabular-nums">
{{ cooldownSecondsDisplay }}s
</span>
<progress v-if="onCooldown" class="progress progress-primary w-48"
:value="cooldownDurationSeconds - cooldownRemainingMs / 1000" :max="cooldownDurationSeconds" />
</div>
</div>
</template>
+18 -2
View File
@@ -1,7 +1,8 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { onBeforeUnmount, onMounted, ref } from "vue";
import { usePlaceSocket } from "@/composables/usePlaceSocket";
import { PALETTE } from "@/palette";
import { playWipeWave } from "@/placeWipe";
interface Props {
eventPath: string;
@@ -22,7 +23,22 @@ function drawPixel(x: number, y: number, colorIndex: number) {
ctx.fillRect(x, y, 1, 1);
}
const { connected, gridWidth, gridHeight } = usePlaceSocket(props.eventPath, drawPixel);
let cancelWipe: (() => void) | null = null;
function wipe() {
if (!ctx) return;
cancelWipe?.();
cancelWipe = playWipeWave(ctx, gridWidth.value, gridHeight.value);
}
onBeforeUnmount(() => cancelWipe?.());
const { connected, gridWidth, gridHeight } = usePlaceSocket(
props.eventPath,
drawPixel,
undefined,
wipe,
);
onMounted(() => {
ctx = canvasRef.value?.getContext("2d") ?? null;
+245
View File
@@ -0,0 +1,245 @@
<script setup lang="ts">
import { computed, useTemplateRef } from "vue";
import { useI18n } from "vue-i18n";
import { useElementSize, useTitle } from "@vueuse/core";
import { useQuery } from "@tanstack/vue-query";
import { eventPlanningQuery } from "@/queries";
import type { PlanningSlotOut } from "./api/types.gen";
import PlanningCover from "./components/PlanningCover.vue";
import PlanningMultiSlot from "./components/PlanningMultiSlot.vue";
interface Props {
eventPath: string;
}
const props = defineProps<Props>();
const { t } = useI18n();
useTitle(computed(() => t("planning.title")));
const { data: slots, isPending: loading } = useQuery(eventPlanningQuery(props.eventPath));
const HOUR = 3600e3;
// Hour height per px of column width: a 2h slot ends up close to the 2:3 cover ratio
const HOUR_RATIO = 104 / 150;
const BREAK_PX = 34;
const DAY_PX = 32;
const AXIS_PX = 56;
// Columns shrink to fit the page, the planning only scrolls sideways below the min
const MIN_COL_PX = 80;
const MAX_COL_PX = 150;
const GAP_PX = 10;
// The multi-anims column is the big one, its covers 1.75x the size of the others
const WIDE_RATIO = 1.75;
// Room on the left for the day names, they stick out of the time axis
const DAY_LABEL_ROOM_PX = 120;
// Empty runs at least this long (nights) get squashed into a thin break
const MIN_BREAK_HOURS = 3;
const fmtTime = new Intl.DateTimeFormat(undefined, { hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
const fmtDay = new Intl.DateTimeFormat(undefined, { weekday: "long", day: "numeric", month: "short" });
interface Segment {
from: number;
to: number;
y: number;
h: number;
kind: "hour" | "idle" | "break" | "day";
label?: string;
}
interface Placed {
slot: PlanningSlotOut;
top: number;
height: number;
when: string;
}
const scroller = useTemplateRef<HTMLElement>("scroller");
const { width: available } = useElementSize(scroller);
const layout = computed(() => {
const list = (slots.value ?? []).map((slot) => ({
slot,
b: Date.parse(slot.begin),
e: Date.parse(slot.end),
}));
if (!list.length) return null;
// Unused columns are dropped, the multi-anims ones are wider
const columnIds = [...new Set(list.map(({ slot }) => slot.column))].sort((a, b) => a - b);
const isWide = (id: number) => list.some(({ slot }) => slot.column === id && slot.is_multi_anims);
const wideCount = columnIds.filter(isWide).length;
const fit =
(available.value - DAY_LABEL_ROOM_PX - AXIS_PX - (columnIds.length - 1) * GAP_PX) /
(columnIds.length + (WIDE_RATIO - 1) * wideCount);
const colPx = available.value ? Math.min(MAX_COL_PX, Math.max(MIN_COL_PX, fit)) : MAX_COL_PX;
const hourPx = colPx * HOUR_RATIO;
// Multi-anims run the whole event, only the other slots decide what's busy
const singles = list.filter(({ slot }) => !slot.is_multi_anims);
const busy = (t: number) => singles.some(({ b, e }) => b < t + HOUR && e > t);
const start = Math.floor(Math.min(...list.map(({ b }) => b)) / HOUR) * HOUR;
const end = Math.ceil(Math.max(...list.map(({ e }) => e)) / HOUR) * HOUR;
const segments: Segment[] = [];
let y = 0;
let lastDay = "";
for (let t = start; t < end;) {
if (busy(t)) {
// Each day gets its own header row, takes no time
const day = fmtDay.format(t);
if (day !== lastDay) {
segments.push({ from: t, to: t, y, h: DAY_PX, kind: "day", label: day });
y += DAY_PX;
lastDay = day;
}
segments.push({ from: t, to: t + HOUR, y, h: hourPx, kind: "hour" });
y += hourPx;
t += HOUR;
continue;
}
let u = t;
while (u < end && !busy(u)) u += HOUR;
const hours = (u - t) / HOUR;
const isBreak = hours >= MIN_BREAK_HOURS;
const h = isBreak ? BREAK_PX : hourPx * hours;
segments.push({ from: t, to: u, y, h, kind: isBreak ? "break" : "idle" });
y += h;
t = u;
}
// Day headers have no duration, they never contain a time
const timed = segments.filter((s) => s.kind !== "day");
const yOf = (t: number) => {
const s = timed.find((s) => t >= s.from && t < s.to) ?? timed[timed.length - 1]!;
return s.y + s.h * Math.min(1, (t - s.from) / (s.to - s.from));
};
const days = segments
.filter((s) => s.kind === "day")
.map((s) => ({ y: s.y, label: s.label! }));
// No tick right under a day header, it would sit on its line
const dayEnds = new Set(days.map((d) => d.y + DAY_PX));
const ticks = timed
.filter((s) => s.kind !== "break")
.flatMap((s) => {
const out = [];
for (let t = s.from; t < s.to; t += HOUR) out.push({ y: yOf(t), label: fmtTime.format(t) });
return out;
})
.filter((tick) => !dayEnds.has(tick.y));
const breaks = segments
.filter((s) => s.kind === "break")
.map((s) => ({ y: s.y, h: s.h, label: `${fmtTime.format(s.from)} – ${fmtTime.format(s.to)}` }));
let left = AXIS_PX;
const columns = columnIds.map((id) => {
const placed = list
.filter(({ slot }) => slot.column === id)
.map<Placed>(({ slot, b, e }) => ({
slot,
top: yOf(b) + 3,
height: yOf(e) - yOf(b) - 6,
when: `${fmtTime.format(b)} – ${fmtTime.format(e)}`,
}));
const width = isWide(id) ? WIDE_RATIO * colPx : colPx;
const column = { left, width, placed };
left += width + GAP_PX;
return column;
});
return {
height: y,
width: left - GAP_PX,
days,
ticks,
breaks,
columns,
};
});
</script>
<template>
<div class="flex-1 bg-base-300 flex justify-center px-4 py-12">
<!-- min-w-0: lets the planning scroll sideways instead of overflowing the page -->
<div class="w-full max-w-7xl min-w-0">
<div class="text-center mb-12">
<h1 class="text-5xl font-bold mb-4">{{ t("planning.title") }}</h1>
</div>
<div v-if="loading" class="flex justify-center py-20">
<span class="loading loading-spinner loading-lg"></span>
</div>
<p v-else-if="!layout" class="text-center text-base-content/50 py-20">
{{ t("planning.empty") }}
</p>
<!-- pr/pt/pb: room for the Fils rouges glow, the scroll box would clip it -->
<div v-else ref="scroller" class="overflow-x-auto pr-10 pt-4 pb-10">
<div class="relative" :style="{
width: `${layout.width}px`,
height: `${layout.height}px`,
marginLeft: `max(${DAY_LABEL_ROOM_PX}px, (100% - ${layout.width}px) / 2)`,
}">
<!-- Time axis: a header row per day, hour ticks on the side -->
<!-- Above the cards: slots running past midnight go over the header row -->
<div v-for="day in layout.days" :key="`day-${day.y}`"
class="absolute left-0 right-0 z-20 pointer-events-none border-b border-base-content/20 flex items-end text-sm font-semibold uppercase tracking-wide"
:style="{ top: `${day.y}px`, height: `${DAY_PX}px` }">
<!-- Ends at the time axis and grows to the left, never over the cards -->
<span class="absolute bottom-0 whitespace-nowrap bg-base-300 rounded-t px-2 py-0.5"
:style="{ right: `calc(100% - ${AXIS_PX}px)` }">{{ day.label }}</span>
</div>
<template v-for="tick in layout.ticks" :key="tick.y">
<span class="absolute -translate-y-1/2 text-xs text-base-content/40 text-right pr-2"
:style="{ top: `${tick.y}px`, width: `${AXIS_PX}px` }">
{{ tick.label }}
</span>
<div class="absolute right-0 border-t border-dashed border-base-content/5"
:style="{ top: `${tick.y}px`, left: `${AXIS_PX}px` }"></div>
</template>
<!-- Nights -->
<div v-for="b in layout.breaks" :key="`break-${b.y}`"
class="planning-break absolute left-0 right-0 rounded flex items-center justify-center text-xs text-base-content/40"
:style="{ top: `${b.y}px`, height: `${b.h}px` }">
{{ b.label }}
</div>
<!-- Slots -->
<div v-for="column in layout.columns" :key="column.left" class="absolute top-0 h-full"
:style="{ left: `${column.left}px`, width: `${column.width}px` }">
<template v-for="{ slot, top, height, when } in column.placed" :key="slot.id">
<!-- Multi-anims: one long shiny card, its games follow the scroll -->
<PlanningMultiSlot v-if="slot.is_multi_anims" :entry="slot" class="absolute inset-x-0"
:style="{ top: `${top}px`, height: `${height}px` }" />
<component :is="slot.games[0]?.store_url ? 'a' : 'div'" v-else
:href="slot.games[0]?.store_url || undefined" target="_blank" rel="noopener noreferrer"
class="group absolute inset-x-0 block rounded-md overflow-hidden bg-base-200 hover:bg-base-100
shadow-xl hover:shadow-2xl transition-all transform hover:-translate-y-2 hover:scale-[1.05] hover:z-10"
:style="{ top: `${top}px`, height: `${height}px` }">
<PlanningCover :game="slot.games[0] ?? { name: slot.title }" :color="slot.color" :when="when" />
<span class="absolute top-1.5 left-1.5 text-xs px-1.5 rounded bg-black/70 text-white opacity-0
group-hover:opacity-100 transition-opacity">
{{ when }}
</span>
</component>
</template>
</div>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.planning-break {
background: repeating-linear-gradient(45deg, color-mix(in srgb, currentColor 6%, transparent) 0 6px, transparent 6px 12px);
}
</style>
+90 -40
View File
@@ -1,12 +1,14 @@
<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from "vue";
import { ref, onMounted, onUnmounted, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import { useI18n } from "vue-i18n";
import { useTitle } from "@vueuse/core";
import { useUserStore } from "@/stores/user";
import { useQueryClient } from "@tanstack/vue-query";
import { useUser } from "@/composables/useUser";
import { eventGamesQuery } from "@/queries";
import { usePageHeaderStore } from "@/stores/pageHeader";
import { gamesApiListEventGames, submissionsApiListAvailableScopes, submissionsApiCreateSubmission, submissionsApiListUserSubmissions, submissionsApiCreateImageCrop, submissionsApiDeleteImageCrop, submissionsApiProcessFileOcr, submissionsApiProcessCropOcr } from "@/api";
import { submissionsApiListAvailableScopes, submissionsApiCreateSubmission, submissionsApiListUserSubmissions, submissionsApiCreateImageCrop, submissionsApiDeleteImageCrop, submissionsApiProcessFileOcr, submissionsApiProcessCropOcr } from "@/api";
import type { SubmissionOut } from "@/api";
import { useSubmissionsWebSocket } from "@/composables/useSubmissionsWebSocket";
import { provideEventPath } from "@/composables/useEventPath";
@@ -31,8 +33,8 @@ const gameSteamId = ref("");
useTitle(computed(() => t("submissions.pageTitle", { game: gameName.value, scope: scopeName.value })));
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const queryClient = useQueryClient();
const userInfo = useUser();
const uploadedFiles = ref<File[]>([]);
const isDragover = ref(false);
@@ -41,11 +43,12 @@ const notes = ref("");
const selectedFile = ref<File | null>(null);
const filePreviewUrl = ref<string>("");
const isModalOpen = ref(false);
const userSubmissions = ref<any[]>([]);
const userSubmissions = ref<SubmissionOut[]>([]);
const isLoadingSubmissions = ref(false);
const selectedSubmissionFile = ref<any>(null);
const isSubmissionFileModalOpen = ref(false);
const copyFeedback = ref<string>("");
// Feedback shown on the copy button that was clicked, keyed by "file" or crop id
const copyFeedback = ref<{ key: string; message: string } | null>(null);
const isDrawingCrop = ref(false);
const cropStartX = ref(0);
const cropStartY = ref(0);
@@ -139,23 +142,23 @@ const closeSubmissionFileModal = () => {
selectedSubmissionFile.value = null;
};
const copyOCRText = async () => {
if (selectedSubmissionFile.value?.ocr_raw_data) {
const copyOCRText = async (text: string | undefined, key: string) => {
if (!text) return;
try {
await navigator.clipboard.writeText(selectedSubmissionFile.value.ocr_raw_data);
copyFeedback.value = t("common.copied");
setTimeout(() => {
copyFeedback.value = "";
}, 2000);
await navigator.clipboard.writeText(text);
copyFeedback.value = { key, message: t("common.copied") };
} catch (err) {
copyFeedback.value = t("submissions.copyFailed");
copyFeedback.value = { key, message: t("submissions.copyFailed") };
}
setTimeout(() => {
copyFeedback.value = "";
if (copyFeedback.value?.key === key) copyFeedback.value = null;
}, 2000);
}
}
};
const copyLabel = (key: string) =>
copyFeedback.value?.key === key ? copyFeedback.value.message : t("common.copy");
const getCanvasCoordinates = (canvas: HTMLCanvasElement, clientX: number, clientY: number) => {
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
@@ -244,6 +247,12 @@ const redrawCropCanvas = () => {
img.src = selectedSubmissionFile.value?.file_url;
};
// Crops can also arrive over the websocket (e.g. drawn by another admin)
watch(
() => selectedSubmissionFile.value?.crops?.length,
() => redrawCropCanvas(),
);
const submitCrop = async () => {
if (!currentCrop.value || !selectedSubmissionFile.value) return;
@@ -260,11 +269,13 @@ const submitCrop = async () => {
},
});
// Add the new crop to the list immediately
// Add the new crop to the list immediately, unless the websocket beat us to it
if (newCrop) {
selectedSubmissionFile.value.crops = selectedSubmissionFile.value.crops || [];
if (!selectedSubmissionFile.value.crops.some((c: any) => c.id === newCrop.id)) {
selectedSubmissionFile.value.crops.push(newCrop);
}
}
currentCrop.value = null;
cropLabel.value = "";
@@ -404,6 +415,26 @@ const removeFile = (index: number) => {
uploadedFiles.value.splice(index, 1);
};
// Thumbnails of the selected images, revoked once the file is removed/submitted
const thumbnailUrls = new Map<File, string>();
const thumbnails = computed(() =>
uploadedFiles.value.map((file) => {
if (!file.type.startsWith("image/")) return null;
if (!thumbnailUrls.has(file)) thumbnailUrls.set(file, URL.createObjectURL(file));
return thumbnailUrls.get(file)!;
}),
);
const revokeThumbnails = (keep: File[] = []) => {
thumbnailUrls.forEach((url, file) => {
if (keep.includes(file)) return;
URL.revokeObjectURL(url);
thumbnailUrls.delete(file);
});
};
watch(uploadedFiles, (files) => revokeThumbnails(files), { deep: true });
const submitSubmission = async () => {
if (uploadedFiles.value.length === 0) return;
@@ -474,7 +505,17 @@ const loadUserSubmissions = async () => {
}
};
const { isConnected: wsConnected } = useSubmissionsWebSocket(userSubmissions);
// Match over (or user moved off it): back to the picker, which auto-enters
// the next match when there's only one, so players follow along without a refresh.
useSubmissionsWebSocket({
userSubmissions,
scopeId: props.scopeId,
onScopeUpdate: (scope) => {
if (scope.id !== props.scopeId || (scope.is_active && scope.assigned)) return;
router.replace({ name: "submissions-select", params: { eventPath: props.eventPath, gamePath: props.gamePath } });
},
});
const isUploadAreaHovered = ref(false);
const handlePasteOnUploadArea = (event: ClipboardEvent) => {
@@ -503,17 +544,16 @@ const handlePasteOnUploadArea = (event: ClipboardEvent) => {
};
onMounted(async () => {
userStore.loadUserData();
loadUserSubmissions();
const [gamesResponse, scopesResponse] = await Promise.all([
gamesApiListEventGames({ path: { event_path: props.eventPath } }),
const [games, scopesResponse] = await Promise.all([
queryClient.ensureQueryData(eventGamesQuery(props.eventPath)),
submissionsApiListAvailableScopes({
path: { event_path: props.eventPath, game_path: props.gamePath },
}),
]);
const game = gamesResponse.data?.find((g) => g.path === props.gamePath);
const game = games.find((g) => g.path === props.gamePath);
if (game) {
gameName.value = game.name;
gameImage.value = game.image ?? "";
@@ -541,6 +581,7 @@ onMounted(async () => {
onUnmounted(() => {
window.removeEventListener('paste', handlePasteOnUploadArea);
revokeThumbnails();
});
</script>
@@ -548,14 +589,6 @@ onUnmounted(() => {
<div class="flex-1 bg-base-200">
<!-- Main Content -->
<div class="container min-w-3/4 mx-auto px-4 py-8">
<!-- WebSocket Status Indicator -->
<div class="flex justify-end mb-4">
<div :class="['badge', wsConnected ? 'badge-success' : 'badge-warning']">
<i :class="['mdi mr-1', wsConnected ? 'mdi-wifi' : 'mdi-wifi-off']"></i>
{{ wsConnected ? t("submissions.live") : t("submissions.offline") }}
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
<!-- Right Column: Upload -->
<div class="lg:col-span-1 flex flex-col gap-8 order-1 lg:order-2">
@@ -617,17 +650,24 @@ onUnmounted(() => {
<!-- Uploaded Files List -->
<div v-if="uploadedFiles.length > 0" class="mb-6">
<p class="font-semibold mb-3">{{ t("common.selectedFiles") }}</p>
<div class="space-y-2">
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
<div v-for="(file, index) in uploadedFiles" :key="index"
class="flex items-center gap-3 bg-base-200 p-3 rounded-lg cursor-pointer hover:bg-base-300 transition-colors group"
class="relative bg-base-200 rounded-lg overflow-hidden cursor-pointer hover:bg-base-300 transition-colors group"
@click="openFilePreview(file)">
<div class="aspect-video bg-base-300 flex items-center justify-center">
<img v-if="thumbnails[index]" :src="thumbnails[index]" :alt="file.name"
class="w-full h-full object-contain" />
<i v-else :class="['mdi text-5xl text-primary', getFileIcon(file)]"></i>
</div>
<div class="flex items-center gap-2 p-2">
<i :class="['mdi text-primary', getFileIcon(file)]"></i>
<div class="flex-1 min-w-0">
<p class="font-medium truncate group-hover:text-primary">{{ file.name }}</p>
<p class="text-sm font-medium truncate group-hover:text-primary" :title="file.name">{{ file.name }}</p>
<p class="text-xs text-base-content/70">{{ formatFileSize(file.size) }}</p>
</div>
</div>
<button @click.stop="removeFile(index)"
class="btn btn-ghost btn-xs opacity-0 group-hover:opacity-100">
class="btn btn-circle btn-xs absolute top-2 right-2 sm:opacity-0 sm:group-hover:opacity-100">
<i class="mdi mdi-close"></i>
</button>
</div>
@@ -727,7 +767,7 @@ onUnmounted(() => {
<div class="card-body">
<h2 class="card-title text-2xl mb-6">
<i class="mdi mdi-history text-primary mr-2"></i>
{{ t("submissions.yourSubmissions") }}
{{ userInfo.isStaff ? t("submissions.allSubmissions") : t("submissions.yourSubmissions") }}
</h2>
<div v-if="isLoadingSubmissions" class="flex justify-center py-8">
@@ -744,6 +784,7 @@ onUnmounted(() => {
<thead>
<tr>
<th>{{ t("common.date") }}</th>
<th v-if="userInfo.isStaff">{{ t("common.user") }}</th>
<th>{{ t("common.files") }}</th>
<th>{{ t("submissions.fileStatus") }}</th>
<th>{{ t("submissions.ocrStatus") }}</th>
@@ -753,6 +794,7 @@ onUnmounted(() => {
<tbody>
<tr v-for="submission in userSubmissions" :key="submission.id" class="hover">
<td class="text-sm">{{ formatDate(submission.created_at) }}</td>
<td v-if="userInfo.isStaff" class="text-sm">{{ submission.username ?? "-" }}</td>
<td class="text-sm">
<div class="flex flex-col gap-1">
<div v-for="file in submission.files" :key="file.id" class="flex items-center gap-2">
@@ -905,9 +947,10 @@ onUnmounted(() => {
<div>
<div class="flex items-center justify-between mb-2">
<p class="text-xs font-semibold text-base-content/70">{{ t("submissions.extractedText") }}</p>
<button @click="copyOCRText" class="btn btn-xs btn-ghost gap-1">
<button @click="copyOCRText(selectedSubmissionFile.ocr_raw_data, 'file')"
class="btn btn-xs btn-ghost gap-1">
<i class="mdi mdi-content-copy"></i>
{{ copyFeedback || t("common.copy") }}
{{ copyLabel("file") }}
</button>
</div>
<div
@@ -944,8 +987,15 @@ onUnmounted(() => {
<div v-for="crop in selectedSubmissionFile.crops" :key="crop.id" class="space-y-2">
<div class="flex items-center justify-between">
<p class="text-xs font-medium">{{ crop.label || t("submissions.cropLabelFallback", { x: crop.x1, y: crop.y1 }) }}</p>
<div class="flex items-center gap-1">
<button v-if="crop.ocr_status === 'processed' && crop.ocr_raw_data"
@click="copyOCRText(crop.ocr_raw_data, crop.id)" class="btn btn-xs btn-ghost gap-1">
<i class="mdi mdi-content-copy"></i>
{{ copyLabel(crop.id) }}
</button>
<span :class="getOCRStatusColor(crop.ocr_status)">{{ crop.ocr_status }}</span>
</div>
</div>
<div v-if="crop.ocr_status === 'processed' && crop.ocr_raw_data"
class="bg-base-100 p-2 rounded text-xs whitespace-pre-wrap break-words font-mono max-h-32 overflow-y-auto">
{{ crop.ocr_raw_data }}
+54 -14
View File
@@ -3,7 +3,12 @@ import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { useTitle } from "@vueuse/core";
import { gamesApiListEventGames, submissionsApiListAvailableScopes } from "@/api";
import { submissionsApiListAvailableScopes } from "@/api";
import { useQueryClient } from "@tanstack/vue-query";
import { eventGamesQuery, userQuery } from "@/queries";
import { useUser } from "@/composables/useUser";
import { useSubmissionsWebSocket } from "@/composables/useSubmissionsWebSocket";
import ScopeSyncModal from "@/components/ScopeSyncModal.vue";
import type { ScopeOut } from "@/api/types.gen";
interface Props {
@@ -14,13 +19,18 @@ interface Props {
const props = defineProps<Props>();
const router = useRouter();
const queryClient = useQueryClient();
const { t } = useI18n();
const userInfo = useUser();
useTitle(computed(() => t("submissionsSelect.title")));
const gameName = ref("");
const scopes = ref<ScopeOut[]>([]);
const loading = ref(true);
const notAssigned = ref(false);
const notFound = ref(false);
const isSyncModalOpen = ref(false);
const scopeRoute = (scope: ScopeOut) => ({
name: "submissions",
@@ -31,40 +41,67 @@ const goToScope = (scope: ScopeOut) => {
router.push(scopeRoute(scope));
};
onMounted(async () => {
const [gamesResponse, scopesResponse] = await Promise.all([
gamesApiListEventGames({ path: { event_path: props.eventPath } }),
const loadScopes = async () => {
const [games, scopesResponse, user] = await Promise.all([
queryClient.ensureQueryData(eventGamesQuery(props.eventPath)),
submissionsApiListAvailableScopes({
path: { event_path: props.eventPath, game_path: props.gamePath },
}),
queryClient.ensureQueryData(userQuery()),
]);
gameName.value = gamesResponse.data?.find((game) => game.path === props.gamePath)?.name ?? "";
// Not a game of this event (or one with its own page, not submissions):
// the backend just serves the app for any game path, this is our 404.
const game = games.find((game) => game.path === props.gamePath && !game.custom_path);
if (!game || scopesResponse.error) {
notFound.value = true;
loading.value = false;
return;
}
gameName.value = game.name;
const availableScopes = scopesResponse.data ?? [];
// Mirrors the server-side behavior this replaced: skip the picker
// straight to the only option, or bounce out if there's nothing to pick.
if (availableScopes.length === 1) {
// Superusers always land here, it's where the scope sync button lives.
if (availableScopes.length === 1 && !user.is_superuser) {
router.replace(scopeRoute(availableScopes[0]));
return;
}
if (availableScopes.length === 0) {
notAssigned.value = true;
loading.value = false;
return;
}
scopes.value = availableScopes;
notAssigned.value = availableScopes.length === 0;
loading.value = false;
});
};
// A match opened/closed or players got (re)assigned: reload, so waiting
// players get auto-entered into their next match without a refresh.
useSubmissionsWebSocket({ onScopeUpdate: () => loadScopes() });
onMounted(loadScopes);
</script>
<template>
<div class="flex-1 bg-base-200 flex items-center justify-center p-4">
<div class="flex-1 bg-base-200 flex flex-col items-center justify-center gap-4 p-4">
<div v-if="userInfo.isSuperuser && !loading && !notFound" class="w-full max-w-md flex justify-end">
<button @click="isSyncModalOpen = true" class="btn btn-primary btn-sm">
<i class="mdi mdi-sync"></i>
{{ t("submissionsSelect.syncScopes") }}
</button>
</div>
<div v-if="loading" class="flex justify-center py-20">
<span class="loading loading-spinner loading-lg"></span>
</div>
<div v-else-if="notFound" class="text-center max-w-md">
<i class="mdi mdi-alert-circle-outline text-6xl text-primary"></i>
<h2 class="text-2xl font-semibold mt-4">{{ t("errorPage.notFound.title") }}</h2>
<p class="text-base-content/70 mt-2">{{ t("errorPage.notFound.message") }}</p>
<RouterLink :to="{ name: 'home', params: { eventPath } }" class="btn btn-primary mt-6">
<i class="mdi mdi-home mr-2"></i>
{{ t("errorPage.goHome") }}
</RouterLink>
</div>
<div v-else-if="notAssigned" class="text-center max-w-md">
<i class="mdi mdi-account-alert-outline text-6xl text-warning"></i>
<h2 class="text-2xl font-semibold mt-4">{{ t("submissionsSelect.notAssignedTitle") }}</h2>
@@ -86,5 +123,8 @@ onMounted(async () => {
</div>
</div>
</div>
<ScopeSyncModal v-if="userInfo.isSuperuser && !notFound" v-model:open="isSyncModalOpen" :event-path="eventPath"
:game-path="gamePath" :game-name="gameName" />
</div>
</template>
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+177 -15
View File
@@ -2,7 +2,7 @@
import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape } from './client';
import { client } from './client.gen';
import type { AnimationsApiPuzzleResultsData, AnimationsApiPuzzleResultsResponses, AnimationsApiResultsData, AnimationsApiResultsResponses, AnimationsApiTopSubmissionsData, AnimationsApiTopSubmissionsResponses, ClockApiCurrentStateData, ClockApiCurrentStateResponses, ClockApiMyStatsData, ClockApiMyStatsResponses, GamesApiListEventGamesData, GamesApiListEventGamesResponses, GamesApiListGamesData, GamesApiListGamesResponses, MarketApiBetHistoryData, MarketApiBetHistoryResponses, MarketApiCloseMarketData, MarketApiCloseMarketResponses, MarketApiCreateBetData, MarketApiCreateBetResponses, MarketApiGetUserPointsData, MarketApiGetUserPointsResponses, MarketApiListMarketsData, MarketApiListMarketsResponses, MarketApiListUserBetsData, MarketApiListUserBetsResponses, MarketApiResolveMarketData, MarketApiResolveMarketResponses, NoitaApiGetLeaderboardData, NoitaApiGetLeaderboardResponses, NoitaApiGetResultsData, NoitaApiGetResultsResponses, NoitaApiSubmitLogFileData, NoitaApiSubmitLogFileErrors, NoitaApiSubmitLogFileResponses, OpusMagnumApiCreateSubmissionData, OpusMagnumApiCreateSubmissionResponses, OpusMagnumApiDeleteSubmissionData, OpusMagnumApiDeleteSubmissionResponses, OpusMagnumApiGetCollectionData, OpusMagnumApiGetCollectionResponses, OpusMagnumApiGetStatsData, OpusMagnumApiGetStatsResponses, OpusMagnumApiGetSubmissionData, OpusMagnumApiGetSubmissionResponses, OpusMagnumApiListPuzzlesData, OpusMagnumApiListPuzzlesResponses, OpusMagnumApiListResponsesNeedingValidationData, OpusMagnumApiListResponsesNeedingValidationResponses, OpusMagnumApiListSubmissionsData, OpusMagnumApiListSubmissionsResponses, OpusMagnumApiValidateAutoData, OpusMagnumApiValidateAutoResponses, OpusMagnumApiValidateResponseData, OpusMagnumApiValidateResponseResponses, OpusMagnumApiValidateSubmissionData, OpusMagnumApiValidateSubmissionResponses, PlaceApiCanvasData, PlaceApiCanvasResponses, PlaceApiEvolutionGifData, PlaceApiEvolutionGifResponses, PolylanSubmitterApiClearCacheData, PolylanSubmitterApiClearCacheResponses, PolylanSubmitterApiGetUserInfoData, PolylanSubmitterApiGetUserInfoResponses, PolylanSubmitterApiHealthCheckData, PolylanSubmitterApiHealthCheckResponses, SubmissionsApiCreateImageCropData, SubmissionsApiCreateImageCropResponses, SubmissionsApiCreateSubmissionData, SubmissionsApiCreateSubmissionErrors, SubmissionsApiCreateSubmissionResponses, SubmissionsApiDeleteImageCropData, SubmissionsApiDeleteImageCropResponses, SubmissionsApiGetSubmissionData, SubmissionsApiGetSubmissionResponses, SubmissionsApiListAvailableScopesData, SubmissionsApiListAvailableScopesErrors, SubmissionsApiListAvailableScopesResponses, SubmissionsApiListMyScopesData, SubmissionsApiListMyScopesErrors, SubmissionsApiListMyScopesResponses, SubmissionsApiListSubmissionsByGameData, SubmissionsApiListSubmissionsByGameResponses, SubmissionsApiListUserSubmissionsData, SubmissionsApiListUserSubmissionsErrors, SubmissionsApiListUserSubmissionsResponses, SubmissionsApiProcessCropOcrData, SubmissionsApiProcessCropOcrResponses, SubmissionsApiProcessFileOcrData, SubmissionsApiProcessFileOcrResponses } from './types.gen';
import type { AnimationsApiPuzzleResultsData, AnimationsApiPuzzleResultsResponses, AnimationsApiResultsData, AnimationsApiResultsResponses, AnimationsApiTopSubmissionsData, AnimationsApiTopSubmissionsResponses, ClockApiCurrentStateData, ClockApiCurrentStateResponses, ClockApiMyStatsData, ClockApiMyStatsResponses, GamesApiListEventGamesData, GamesApiListEventGamesResponses, GamesApiListEventPlanningData, GamesApiListEventPlanningResponses, GamesApiListEventSteamGamesData, GamesApiListEventSteamGamesResponses, GamesApiListGamesData, GamesApiListGamesResponses, MarketApiBetHistoryData, MarketApiBetHistoryResponses, MarketApiCloseMarketData, MarketApiCloseMarketResponses, MarketApiCreateBetData, MarketApiCreateBetResponses, MarketApiGetUserPointsData, MarketApiGetUserPointsResponses, MarketApiListMarketsData, MarketApiListMarketsResponses, MarketApiListUserBetsData, MarketApiListUserBetsResponses, MarketApiResolveMarketData, MarketApiResolveMarketResponses, NoitaApiGetLeaderboardData, NoitaApiGetLeaderboardResponses, NoitaApiGetResultsData, NoitaApiGetResultsResponses, NoitaApiSubmitLogFileData, NoitaApiSubmitLogFileErrors, NoitaApiSubmitLogFileResponses, OpusMagnumApiCreateSubmissionData, OpusMagnumApiCreateSubmissionErrors, OpusMagnumApiCreateSubmissionResponses, OpusMagnumApiDeleteSubmissionData, OpusMagnumApiDeleteSubmissionErrors, OpusMagnumApiDeleteSubmissionResponses, OpusMagnumApiGetCollectionData, OpusMagnumApiGetCollectionResponses, OpusMagnumApiGetStatsData, OpusMagnumApiGetStatsResponses, OpusMagnumApiGetSubmissionData, OpusMagnumApiGetSubmissionResponses, OpusMagnumApiListPuzzlesData, OpusMagnumApiListPuzzlesResponses, OpusMagnumApiListResponseFilesData, OpusMagnumApiListResponseFilesErrors, OpusMagnumApiListResponseFilesResponses, OpusMagnumApiListResponsesNeedingValidationData, OpusMagnumApiListResponsesNeedingValidationErrors, OpusMagnumApiListResponsesNeedingValidationResponses, OpusMagnumApiListSubmissionsData, OpusMagnumApiListSubmissionsResponses, OpusMagnumApiValidateAutoData, OpusMagnumApiValidateAutoErrors, OpusMagnumApiValidateAutoResponses, OpusMagnumApiValidateResponseData, OpusMagnumApiValidateResponseErrors, OpusMagnumApiValidateResponseResponses, OpusMagnumApiValidateSubmissionData, OpusMagnumApiValidateSubmissionErrors, OpusMagnumApiValidateSubmissionResponses, PlaceApiCanvasData, PlaceApiCanvasResponses, PlaceApiEvolutionGifData, PlaceApiEvolutionGifResponses, PlaceApiFinalPngData, PlaceApiFinalPngResponses, PlaceApiHeatmapDecayGifData, PlaceApiHeatmapDecayGifResponses, PlaceApiHeatmapEvolutionGifData, PlaceApiHeatmapEvolutionGifResponses, PlaceApiHeatmapPngData, PlaceApiHeatmapPngResponses, PlaceApiPlacementsCsvData, PlaceApiPlacementsCsvResponses, PlaceApiStatsData, PlaceApiStatsResponses, PolylanSubmitterApiClearCacheData, PolylanSubmitterApiClearCacheErrors, PolylanSubmitterApiClearCacheResponses, PolylanSubmitterApiGetUserInfoData, PolylanSubmitterApiGetUserInfoResponses, PolylanSubmitterApiHealthCheckData, PolylanSubmitterApiHealthCheckResponses, SubmissionsApiCreateImageCropData, SubmissionsApiCreateImageCropErrors, SubmissionsApiCreateImageCropResponses, SubmissionsApiCreateSubmissionData, SubmissionsApiCreateSubmissionErrors, SubmissionsApiCreateSubmissionResponses, SubmissionsApiDeleteImageCropData, SubmissionsApiDeleteImageCropErrors, SubmissionsApiDeleteImageCropResponses, SubmissionsApiGetSubmissionData, SubmissionsApiGetSubmissionErrors, SubmissionsApiGetSubmissionResponses, SubmissionsApiListAvailableScopesData, SubmissionsApiListAvailableScopesErrors, SubmissionsApiListAvailableScopesResponses, SubmissionsApiListMyScopesData, SubmissionsApiListMyScopesErrors, SubmissionsApiListMyScopesResponses, SubmissionsApiListSubmissionsByGameData, SubmissionsApiListSubmissionsByGameErrors, SubmissionsApiListSubmissionsByGameResponses, SubmissionsApiListUserSubmissionsData, SubmissionsApiListUserSubmissionsErrors, SubmissionsApiListUserSubmissionsResponses, SubmissionsApiProcessCropOcrData, SubmissionsApiProcessCropOcrErrors, SubmissionsApiProcessCropOcrResponses, SubmissionsApiProcessFileOcrData, SubmissionsApiProcessFileOcrErrors, SubmissionsApiProcessFileOcrResponses, SubmissionsApiStopSyncScopesData, SubmissionsApiStopSyncScopesErrors, SubmissionsApiStopSyncScopesResponses, SubmissionsApiSyncScopesData, SubmissionsApiSyncScopesErrors, SubmissionsApiSyncScopesResponses, SubmissionsApiSyncScopesStatusData, SubmissionsApiSyncScopesStatusErrors, SubmissionsApiSyncScopesStatusResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -30,7 +30,7 @@ export const polylanSubmitterApiHealthCheck = <ThrowOnError extends boolean = fa
*
* Clear API caches (admin only). Pass event_path to clear just that event's keys.
*/
export const polylanSubmitterApiClearCache = <ThrowOnError extends boolean = false>(options?: Options<PolylanSubmitterApiClearCacheData, ThrowOnError>) => (options?.client ?? client).post<PolylanSubmitterApiClearCacheResponses, unknown, ThrowOnError>({ url: '/api/cache/clear', ...options });
export const polylanSubmitterApiClearCache = <ThrowOnError extends boolean = false>(options?: Options<PolylanSubmitterApiClearCacheData, ThrowOnError>) => (options?.client ?? client).post<PolylanSubmitterApiClearCacheResponses, PolylanSubmitterApiClearCacheErrors, ThrowOnError>({ url: '/api/cache/clear', ...options });
/**
* Get User Info
@@ -70,7 +70,7 @@ export const opusMagnumApiListSubmissions = <ThrowOnError extends boolean = fals
*
* Create a new submission with multiple puzzle responses
*/
export const opusMagnumApiCreateSubmission = <ThrowOnError extends boolean = false>(options: Options<OpusMagnumApiCreateSubmissionData, ThrowOnError>) => (options.client ?? client).post<OpusMagnumApiCreateSubmissionResponses, unknown, ThrowOnError>({
export const opusMagnumApiCreateSubmission = <ThrowOnError extends boolean = false>(options: Options<OpusMagnumApiCreateSubmissionData, ThrowOnError>) => (options.client ?? client).post<OpusMagnumApiCreateSubmissionResponses, OpusMagnumApiCreateSubmissionErrors, ThrowOnError>({
...formDataBodySerializer,
url: '/api/events/{event_path}/opus-magnum/submissions',
...options,
@@ -85,7 +85,7 @@ export const opusMagnumApiCreateSubmission = <ThrowOnError extends boolean = fal
*
* Delete a submission (admin only)
*/
export const opusMagnumApiDeleteSubmission = <ThrowOnError extends boolean = false>(options: Options<OpusMagnumApiDeleteSubmissionData, ThrowOnError>) => (options.client ?? client).delete<OpusMagnumApiDeleteSubmissionResponses, unknown, ThrowOnError>({ url: '/api/events/{event_path}/opus-magnum/submissions/{submission_id}', ...options });
export const opusMagnumApiDeleteSubmission = <ThrowOnError extends boolean = false>(options: Options<OpusMagnumApiDeleteSubmissionData, ThrowOnError>) => (options.client ?? client).delete<OpusMagnumApiDeleteSubmissionResponses, OpusMagnumApiDeleteSubmissionErrors, ThrowOnError>({ url: '/api/events/{event_path}/opus-magnum/submissions/{submission_id}', ...options });
/**
* Get Submission
@@ -99,7 +99,7 @@ export const opusMagnumApiGetSubmission = <ThrowOnError extends boolean = false>
*
* Manually validate a puzzle response
*/
export const opusMagnumApiValidateResponse = <ThrowOnError extends boolean = false>(options: Options<OpusMagnumApiValidateResponseData, ThrowOnError>) => (options.client ?? client).put<OpusMagnumApiValidateResponseResponses, unknown, ThrowOnError>({
export const opusMagnumApiValidateResponse = <ThrowOnError extends boolean = false>(options: Options<OpusMagnumApiValidateResponseData, ThrowOnError>) => (options.client ?? client).put<OpusMagnumApiValidateResponseResponses, OpusMagnumApiValidateResponseErrors, ThrowOnError>({
url: '/api/events/{event_path}/opus-magnum/responses/{response_id}/validate',
...options,
headers: {
@@ -113,21 +113,28 @@ export const opusMagnumApiValidateResponse = <ThrowOnError extends boolean = fal
*
* Try to auto validate a puzzle response
*/
export const opusMagnumApiValidateAuto = <ThrowOnError extends boolean = false>(options: Options<OpusMagnumApiValidateAutoData, ThrowOnError>) => (options.client ?? client).put<OpusMagnumApiValidateAutoResponses, unknown, ThrowOnError>({ url: '/api/events/{event_path}/opus-magnum/responses/{response_id}/validate/auto', ...options });
export const opusMagnumApiValidateAuto = <ThrowOnError extends boolean = false>(options: Options<OpusMagnumApiValidateAutoData, ThrowOnError>) => (options.client ?? client).put<OpusMagnumApiValidateAutoResponses, OpusMagnumApiValidateAutoErrors, ThrowOnError>({ url: '/api/events/{event_path}/opus-magnum/responses/{response_id}/validate/auto', ...options });
/**
* List Responses Needing Validation
*
* Get all responses that need manual validation
*/
export const opusMagnumApiListResponsesNeedingValidation = <ThrowOnError extends boolean = false>(options: Options<OpusMagnumApiListResponsesNeedingValidationData, ThrowOnError>) => (options.client ?? client).get<OpusMagnumApiListResponsesNeedingValidationResponses, unknown, ThrowOnError>({ url: '/api/events/{event_path}/opus-magnum/responses/needs-validation', ...options });
export const opusMagnumApiListResponsesNeedingValidation = <ThrowOnError extends boolean = false>(options: Options<OpusMagnumApiListResponsesNeedingValidationData, ThrowOnError>) => (options.client ?? client).get<OpusMagnumApiListResponsesNeedingValidationResponses, OpusMagnumApiListResponsesNeedingValidationErrors, ThrowOnError>({ url: '/api/events/{event_path}/opus-magnum/responses/needs-validation', ...options });
/**
* List Response Files
*
* Get the solution files of any player's response (admin only)
*/
export const opusMagnumApiListResponseFiles = <ThrowOnError extends boolean = false>(options: Options<OpusMagnumApiListResponseFilesData, ThrowOnError>) => (options.client ?? client).get<OpusMagnumApiListResponseFilesResponses, OpusMagnumApiListResponseFilesErrors, ThrowOnError>({ url: '/api/events/{event_path}/opus-magnum/responses/{response_id}/files', ...options });
/**
* Validate Submission
*
* Mark entire submission as validated
*/
export const opusMagnumApiValidateSubmission = <ThrowOnError extends boolean = false>(options: Options<OpusMagnumApiValidateSubmissionData, ThrowOnError>) => (options.client ?? client).post<OpusMagnumApiValidateSubmissionResponses, unknown, ThrowOnError>({ url: '/api/events/{event_path}/opus-magnum/submissions/{submission_id}/validate', ...options });
export const opusMagnumApiValidateSubmission = <ThrowOnError extends boolean = false>(options: Options<OpusMagnumApiValidateSubmissionData, ThrowOnError>) => (options.client ?? client).post<OpusMagnumApiValidateSubmissionResponses, OpusMagnumApiValidateSubmissionErrors, ThrowOnError>({ url: '/api/events/{event_path}/opus-magnum/submissions/{submission_id}/validate', ...options });
/**
* Get Stats
@@ -196,6 +203,20 @@ export const noitaApiSubmitLogFile = <ThrowOnError extends boolean = false>(opti
*/
export const gamesApiListEventGames = <ThrowOnError extends boolean = false>(options: Options<GamesApiListEventGamesData, ThrowOnError>) => (options.client ?? client).get<GamesApiListEventGamesResponses, unknown, ThrowOnError>({ url: '/api/events/{event_path}/games', ...options });
/**
* List Event Steam Games
*
* The event's Steam games with their store info (price, discount, blurb).
*/
export const gamesApiListEventSteamGames = <ThrowOnError extends boolean = false>(options: Options<GamesApiListEventSteamGamesData, ThrowOnError>) => (options.client ?? client).get<GamesApiListEventSteamGamesResponses, unknown, ThrowOnError>({ url: '/api/events/{event_path}/games/steam', ...options });
/**
* List Event Planning
*
* The event planning, with the covers of the games we know.
*/
export const gamesApiListEventPlanning = <ThrowOnError extends boolean = false>(options: Options<GamesApiListEventPlanningData, ThrowOnError>) => (options.client ?? client).get<GamesApiListEventPlanningResponses, unknown, ThrowOnError>({ url: '/api/events/{event_path}/planning', ...options });
/**
* List My Scopes
*/
@@ -212,6 +233,38 @@ export const submissionsApiListMyScopes = <ThrowOnError extends boolean = false>
*/
export const submissionsApiListAvailableScopes = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiListAvailableScopesData, ThrowOnError>) => (options.client ?? client).get<SubmissionsApiListAvailableScopesResponses, SubmissionsApiListAvailableScopesErrors, ThrowOnError>({ url: '/api/events/{event_path}/submissions/{game_path}/available-scopes', ...options });
/**
* Stop Sync Scopes
*
* Stop the AAndT scope sync loop of a (non custom path) game, superusers
* only. Cancels its scheduled job, scopes are left as they are.
*/
export const submissionsApiStopSyncScopes = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiStopSyncScopesData, ThrowOnError>) => (options.client ?? client).delete<SubmissionsApiStopSyncScopesResponses, SubmissionsApiStopSyncScopesErrors, ThrowOnError>({ url: '/api/events/{event_path}/submissions/{game_path}/sync-scopes', ...options });
/**
* Sync Scopes Status
*
* State of the AAndT scope sync loop of a (non custom path) game,
* superusers only.
*/
export const submissionsApiSyncScopesStatus = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiSyncScopesStatusData, ThrowOnError>) => (options.client ?? client).get<SubmissionsApiSyncScopesStatusResponses, SubmissionsApiSyncScopesStatusErrors, ThrowOnError>({ url: '/api/events/{event_path}/submissions/{game_path}/sync-scopes', ...options });
/**
* Sync Scopes
*
* Start the AAndT scope sync loop for a (non custom path) game, superusers
* only. Stores `apibot_token` first when given; without one and none stored
* yet, answers 400 with `token_required` so the frontend asks for it.
*/
export const submissionsApiSyncScopes = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiSyncScopesData, ThrowOnError>) => (options.client ?? client).post<SubmissionsApiSyncScopesResponses, SubmissionsApiSyncScopesErrors, ThrowOnError>({
url: '/api/events/{event_path}/submissions/{game_path}/sync-scopes',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/**
* Create Submission
*/
@@ -233,17 +286,17 @@ export const submissionsApiListUserSubmissions = <ThrowOnError extends boolean =
/**
* List Submissions By Game
*/
export const submissionsApiListSubmissionsByGame = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiListSubmissionsByGameData, ThrowOnError>) => (options.client ?? client).get<SubmissionsApiListSubmissionsByGameResponses, unknown, ThrowOnError>({ url: '/api/events/{event_path}/submissions/submission/by/game', ...options });
export const submissionsApiListSubmissionsByGame = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiListSubmissionsByGameData, ThrowOnError>) => (options.client ?? client).get<SubmissionsApiListSubmissionsByGameResponses, SubmissionsApiListSubmissionsByGameErrors, ThrowOnError>({ url: '/api/events/{event_path}/submissions/submission/by/game', ...options });
/**
* Get Submission
*/
export const submissionsApiGetSubmission = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiGetSubmissionData, ThrowOnError>) => (options.client ?? client).get<SubmissionsApiGetSubmissionResponses, unknown, ThrowOnError>({ url: '/api/events/{event_path}/submissions/submission/{submission_id}', ...options });
export const submissionsApiGetSubmission = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiGetSubmissionData, ThrowOnError>) => (options.client ?? client).get<SubmissionsApiGetSubmissionResponses, SubmissionsApiGetSubmissionErrors, ThrowOnError>({ url: '/api/events/{event_path}/submissions/submission/{submission_id}', ...options });
/**
* Create Image Crop
*/
export const submissionsApiCreateImageCrop = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiCreateImageCropData, ThrowOnError>) => (options.client ?? client).post<SubmissionsApiCreateImageCropResponses, unknown, ThrowOnError>({
export const submissionsApiCreateImageCrop = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiCreateImageCropData, ThrowOnError>) => (options.client ?? client).post<SubmissionsApiCreateImageCropResponses, SubmissionsApiCreateImageCropErrors, ThrowOnError>({
url: '/api/events/{event_path}/submissions/crops/s/{submission_file_id}',
...options,
headers: {
@@ -255,17 +308,17 @@ export const submissionsApiCreateImageCrop = <ThrowOnError extends boolean = fal
/**
* Delete Image Crop
*/
export const submissionsApiDeleteImageCrop = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiDeleteImageCropData, ThrowOnError>) => (options.client ?? client).delete<SubmissionsApiDeleteImageCropResponses, unknown, ThrowOnError>({ url: '/api/events/{event_path}/submissions/crops/{crop_id}', ...options });
export const submissionsApiDeleteImageCrop = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiDeleteImageCropData, ThrowOnError>) => (options.client ?? client).delete<SubmissionsApiDeleteImageCropResponses, SubmissionsApiDeleteImageCropErrors, ThrowOnError>({ url: '/api/events/{event_path}/submissions/crops/{crop_id}', ...options });
/**
* Process File Ocr
*/
export const submissionsApiProcessFileOcr = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiProcessFileOcrData, ThrowOnError>) => (options.client ?? client).post<SubmissionsApiProcessFileOcrResponses, unknown, ThrowOnError>({ url: '/api/events/{event_path}/submissions/files/{file_id}/process-ocr', ...options });
export const submissionsApiProcessFileOcr = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiProcessFileOcrData, ThrowOnError>) => (options.client ?? client).post<SubmissionsApiProcessFileOcrResponses, SubmissionsApiProcessFileOcrErrors, ThrowOnError>({ url: '/api/events/{event_path}/submissions/files/{file_id}/process-ocr', ...options });
/**
* Process Crop Ocr
*/
export const submissionsApiProcessCropOcr = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiProcessCropOcrData, ThrowOnError>) => (options.client ?? client).post<SubmissionsApiProcessCropOcrResponses, unknown, ThrowOnError>({ url: '/api/events/{event_path}/submissions/crops/{crop_id}/process-ocr', ...options });
export const submissionsApiProcessCropOcr = <ThrowOnError extends boolean = false>(options: Options<SubmissionsApiProcessCropOcrData, ThrowOnError>) => (options.client ?? client).post<SubmissionsApiProcessCropOcrResponses, SubmissionsApiProcessCropOcrErrors, ThrowOnError>({ url: '/api/events/{event_path}/submissions/crops/{crop_id}/process-ocr', ...options });
/**
* Current State
@@ -281,7 +334,8 @@ export const clockApiMyStats = <ThrowOnError extends boolean = false>(options: O
* Canvas
*
* The one-time full-grid load. Every placement after that arrives as a
* single websocket message, never a re-fetch.
* single websocket message, never a re-fetch. Once placement is over the
* board is shown wiped (Redis keeps the real final board, see tasks.py).
*/
export const placeApiCanvas = <ThrowOnError extends boolean = false>(options: Options<PlaceApiCanvasData, ThrowOnError>) => (options.client ?? client).get<PlaceApiCanvasResponses, unknown, ThrowOnError>({ url: '/api/events/{event_path}/place/canvas', ...options });
@@ -289,6 +343,9 @@ export const placeApiCanvas = <ThrowOnError extends boolean = false>(options: Op
* Evolution Gif
*
* Admin-only: replays the full placement history as an animated GIF.
*
* `players` is an optional comma-separated list of usernames to only
* replay those players' placements (combined).
*/
export const placeApiEvolutionGif = <ThrowOnError extends boolean = false>(options: Options<PlaceApiEvolutionGifData, ThrowOnError>) => (options.client ?? client).get<PlaceApiEvolutionGifResponses, unknown, ThrowOnError>({
security: [{
@@ -300,6 +357,111 @@ export const placeApiEvolutionGif = <ThrowOnError extends boolean = false>(optio
...options
});
/**
* Final Png
*
* Admin-only: the real final board as a PNG, even once placement is
* over and everyone else sees it wiped.
*/
export const placeApiFinalPng = <ThrowOnError extends boolean = false>(options: Options<PlaceApiFinalPngData, ThrowOnError>) => (options.client ?? client).get<PlaceApiFinalPngResponses, unknown, ThrowOnError>({
security: [{
in: 'cookie',
name: 'sessionid',
type: 'apiKey'
}],
url: '/api/events/{event_path}/place/final.png',
...options
});
/**
* Heatmap Png
*
* Admin-only: how many times each pixel was placed, as a heatmap PNG.
*
* `players` is an optional comma-separated list of usernames to only
* count those players' placements (combined).
*/
export const placeApiHeatmapPng = <ThrowOnError extends boolean = false>(options: Options<PlaceApiHeatmapPngData, ThrowOnError>) => (options.client ?? client).get<PlaceApiHeatmapPngResponses, unknown, ThrowOnError>({
security: [{
in: 'cookie',
name: 'sessionid',
type: 'apiKey'
}],
url: '/api/events/{event_path}/place/heatmap.png',
...options
});
/**
* Heatmap Evolution Gif
*
* Admin-only: the heatmap building up over time, as an animated GIF.
*
* `players` is an optional comma-separated list of usernames to only
* count those players' placements (combined).
*/
export const placeApiHeatmapEvolutionGif = <ThrowOnError extends boolean = false>(options: Options<PlaceApiHeatmapEvolutionGifData, ThrowOnError>) => (options.client ?? client).get<PlaceApiHeatmapEvolutionGifResponses, unknown, ThrowOnError>({
security: [{
in: 'cookie',
name: 'sessionid',
type: 'apiKey'
}],
url: '/api/events/{event_path}/place/heatmap-evolution.gif',
...options
});
/**
* Heatmap Decay Gif
*
* Admin-only: the heatmap over time, but heat decays so pixels nobody
* touches anymore fade back to white.
*
* `players` is an optional comma-separated list of usernames to only
* count those players' placements (combined). `mode` is "placements"
* (decay per placement, `half_life` in placements, defaults to 10 frames'
* worth) or "time" (decay over time, `half_life` in minutes, defaults
* to 60).
*/
export const placeApiHeatmapDecayGif = <ThrowOnError extends boolean = false>(options: Options<PlaceApiHeatmapDecayGifData, ThrowOnError>) => (options.client ?? client).get<PlaceApiHeatmapDecayGifResponses, unknown, ThrowOnError>({
security: [{
in: 'cookie',
name: 'sessionid',
type: 'apiKey'
}],
url: '/api/events/{event_path}/place/heatmap-decay.gif',
...options
});
/**
* Stats
*
* Admin-only: aggregated stats about the game - totals, coverage, top
* players, most contested pixels, color usage and activity per hour.
*/
export const placeApiStats = <ThrowOnError extends boolean = false>(options: Options<PlaceApiStatsData, ThrowOnError>) => (options.client ?? client).get<PlaceApiStatsResponses, unknown, ThrowOnError>({
security: [{
in: 'cookie',
name: 'sessionid',
type: 'apiKey'
}],
url: '/api/events/{event_path}/place/stats',
...options
});
/**
* Placements Csv
*
* Admin-only: pixel placement count per player, most active first.
*/
export const placeApiPlacementsCsv = <ThrowOnError extends boolean = false>(options: Options<PlaceApiPlacementsCsvData, ThrowOnError>) => (options.client ?? client).get<PlaceApiPlacementsCsvResponses, unknown, ThrowOnError>({
security: [{
in: 'cookie',
name: 'sessionid',
type: 'apiKey'
}],
url: '/api/events/{event_path}/place/placements.csv',
...options
});
/**
* List Markets
*
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,33 @@
<script setup lang="ts">
import { ref } from "vue";
import type { PlanningGameOut } from "../api/types.gen";
defineProps<{
game: PlanningGameOut;
color: string;
// Slot time, shown on the colored card (the cover has its own hover badge)
when?: string;
}>();
// Not every game has a library capsule on Steam, fall back to the colored card
const coverFailed = ref(false);
</script>
<template>
<img v-if="game.library_image && !coverFailed" :src="game.library_image" :alt="game.name" :title="game.name"
loading="lazy" class="w-full h-full object-cover object-top" @error="coverFailed = true" />
<div v-else class="planning-fallback w-full h-full flex flex-col justify-center gap-1 p-3 border-l-4"
:style="{ '--slot-color': color }">
<span class="font-semibold leading-tight text-base-content">{{ game.name }}</span>
<span v-if="when" class="text-xs text-base-content/70">{{ when }}</span>
</div>
</template>
<style scoped>
.planning-fallback {
border-color: var(--slot-color);
background: linear-gradient(160deg,
color-mix(in srgb, var(--slot-color) 35%, var(--color-base-200)),
var(--color-base-200));
}
</style>
@@ -0,0 +1,127 @@
<script setup lang="ts">
import { computed, useTemplateRef } from "vue";
import { useElementBounding, useElementSize, useWindowSize } from "@vueuse/core";
import type { PlanningSlotOut } from "../api/types.gen";
import PlanningCover from "./PlanningCover.vue";
defineProps<{ entry: PlanningSlotOut }>();
const track = useTemplateRef<HTMLElement>("track");
const stack = useTemplateRef<HTMLElement>("stack");
const { top: trackTop, height: trackHeight } = useElementBounding(track);
const { height: stackHeight } = useElementSize(stack);
const { height: windowHeight } = useWindowSize();
// The games follow the scroll: kept in the middle of the screen, but never
// leaving the slot (stuck to its top/bottom when it's only partly visible)
const offset = computed(() => {
const wanted = windowHeight.value / 2 - stackHeight.value / 2 - trackTop.value;
const max = Math.max(0, trackHeight.value - stackHeight.value);
return Math.min(max, Math.max(0, wanted));
});
</script>
<template>
<div class="planning-multi h-full rounded-md p-[2px]" :style="{ '--slot-color': entry.color }">
<div class="planning-multi-inner relative h-full rounded-[5px] p-2 flex flex-col overflow-hidden">
<div class="planning-multi-title font-black uppercase text-sm tracking-widest mb-2">
<i class="mdi mdi-star-four-points mr-1"></i>{{ entry.title }}
</div>
<div ref="track" class="relative flex-1">
<div ref="stack" class="absolute inset-x-0 flex flex-col gap-3"
:style="{ transform: `translateY(${offset}px)` }">
<component :is="game.store_url ? 'a' : 'div'" v-for="game in entry.games" :key="game.name"
:href="game.store_url || undefined" target="_blank" rel="noopener noreferrer"
class="block aspect-[2/3] rounded overflow-hidden shadow-lg bg-base-200
transition-transform hover:scale-[1.05]">
<PlanningCover :game="game" :color="entry.color" />
</component>
</div>
</div>
<!-- Light sweeping down the whole slot -->
<div class="planning-multi-sheen pointer-events-none absolute inset-0"></div>
</div>
</div>
</template>
<style scoped>
@property --planning-angle {
syntax: "<angle>";
initial-value: 0deg;
inherits: false;
}
/* Rotating gradient border + glow in the slot color */
.planning-multi {
background: conic-gradient(from var(--planning-angle),
var(--slot-color), #ffd76a, var(--slot-color), #ffffff, var(--slot-color));
box-shadow: 0 0 24px -4px var(--slot-color);
animation: planning-spin 6s linear infinite, planning-glow 3s ease-in-out infinite alternate;
}
.planning-multi-inner {
background: linear-gradient(180deg,
color-mix(in srgb, var(--slot-color) 35%, var(--color-base-200)),
var(--color-base-200) 40%,
color-mix(in srgb, var(--slot-color) 20%, var(--color-base-200)));
}
.planning-multi-title {
background: linear-gradient(90deg, #fff 20%, #ffd76a 40%, #fff 60%);
background-size: 200% 100%;
background-clip: text;
color: transparent;
animation: planning-shimmer 3s linear infinite;
}
.planning-multi-sheen {
background: linear-gradient(180deg, transparent 0%, rgb(255 255 255 / 0.12) 50%, transparent 100%);
background-size: 100% 600px;
background-repeat: no-repeat;
animation: planning-sheen 7s ease-in-out infinite;
}
@keyframes planning-spin {
to {
--planning-angle: 360deg;
}
}
@keyframes planning-glow {
to {
box-shadow: 0 0 40px 0 var(--slot-color);
}
}
@keyframes planning-shimmer {
from {
background-position: 100% 0;
}
to {
background-position: -100% 0;
}
}
@keyframes planning-sheen {
from {
background-position: 0 -600px;
}
to {
background-position: 0 calc(100% + 600px);
}
}
@media (prefers-reduced-motion: reduce) {
.planning-multi,
.planning-multi-title,
.planning-multi-sheen {
animation: none;
}
}
</style>
+87 -3
View File
@@ -2,7 +2,13 @@
import { ref, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import RankBadge from "./RankBadge.vue";
import { animationsApiResults, polylanSubmitterApiClearCache, polylanSubmitterApiGetUserInfo } from "@/api";
import {
animationsApiResults,
opusMagnumApiListResponseFiles,
polylanSubmitterApiClearCache,
} from "@/api";
import type { SubmissionFileOut } from "@/api/types.gen";
import { queryClient, userQuery } from "@/queries";
import { useEventPath } from "@/composables/useEventPath";
const { t } = useI18n();
@@ -60,6 +66,32 @@ const isLoading = ref(true);
const resultsData = ref<ResultsData | null>(null);
const selectedTab = ref<"overall" | "byPuzzle">("overall");
const expandedPuzzleId = ref<number | null>(null);
// Solution viewer (staff only)
const solutionModal = ref<{ username: string; puzzleTitle: string } | null>(null);
const solutionFiles = ref<SubmissionFileOut[]>([]);
const isLoadingSolution = ref(false);
const openSolution = async (responseId: number, username: string, puzzleTitle: string) => {
solutionModal.value = { username, puzzleTitle };
solutionFiles.value = [];
isLoadingSolution.value = true;
try {
const response = await opusMagnumApiListResponseFiles({
path: { event_path: eventPath, response_id: responseId },
});
solutionFiles.value = response.data ?? [];
} catch (error) {
console.error("Error fetching solution files:", error);
} finally {
isLoadingSolution.value = false;
}
};
const closeSolution = () => {
solutionModal.value = null;
solutionFiles.value = [];
};
const userInfo = ref({
username: "Player",
rank: null as number | null,
@@ -107,6 +139,7 @@ const getPuzzleRanking = (puzzleId: number) => {
return ranking.map((response) => {
const user = resultsData.value!.users.find((u) => u.id === response.user_id) as User;
return {
id: response.id,
user: user,
cost: response.final_cost,
cycles: response.final_cycles,
@@ -142,8 +175,7 @@ const clearCache = async () => {
const loadUserData = async () => {
try {
const response = await polylanSubmitterApiGetUserInfo();
const user = response.data;
const user = await queryClient.fetchQuery(userQuery());
if (user?.is_authenticated) {
userInfo.value.username = user.username ?? "";
userInfo.value.isStaff = user.is_staff || false;
@@ -408,6 +440,7 @@ onMounted(() => {
</th>
<th class="text-center">{{ t("components.results.totalWithCoef") }}</th>
<th class="text-right">{{ t("common.points") }}</th>
<th v-if="userInfo.isStaff" class="w-12"></th>
</tr>
</thead>
<tbody>
@@ -437,6 +470,12 @@ onMounted(() => {
<span v-else class="text-base-content/40">—</span>
</td>
<td class="text-right font-bold text-primary text-lg">{{ response.rank_points }}</td>
<td v-if="userInfo.isStaff">
<button @click="openSolution(response.id, response.user.username, puzzle.title)"
class="btn btn-ghost btn-xs" :title="t('components.results.viewSolution')">
<i class="mdi mdi-eye"></i>
</button>
</td>
</tr>
</tbody>
</table>
@@ -450,5 +489,50 @@ onMounted(() => {
</div>
</div>
</div>
<!-- Solution Modal (staff only) -->
<div v-if="solutionModal" class="modal modal-open">
<div class="modal-box max-w-7xl w-full">
<div class="flex justify-between items-center mb-4">
<h3 class="font-bold text-lg">
{{ t("components.results.solutionTitle", solutionModal) }}
</h3>
<button @click="closeSolution" class="btn btn-sm btn-circle btn-ghost">
<i class="mdi mdi-close"></i>
</button>
</div>
<div v-if="isLoadingSolution" class="flex justify-center py-8">
<span class="loading loading-spinner loading-lg"></span>
</div>
<div v-else-if="solutionFiles.length === 0" class="text-center py-8">
<p class="text-base-content/70">{{ t("components.results.noSolutionFiles") }}</p>
</div>
<div v-else class="space-y-4">
<div v-for="file in solutionFiles" :key="file.id" class="bg-base-200 rounded-lg p-4">
<div class="flex justify-center">
<video v-if="file.content_type.startsWith('video/')" :src="file.file_url ?? undefined" controls
autoplay loop class="max-h-[70vh] object-contain"></video>
<img v-else :src="file.file_url ?? undefined" :alt="file.original_filename"
class="max-h-[70vh] object-contain" />
</div>
<div class="flex justify-between items-center mt-2 text-sm">
<span class="text-base-content/70">{{ file.original_filename }}</span>
<a v-if="file.file_url" :href="file.file_url" target="_blank" class="btn btn-primary btn-xs">
<i class="mdi mdi-download"></i>
{{ t("common.download") }}
</a>
</div>
</div>
</div>
<div class="modal-action mt-4">
<button @click="closeSolution" class="btn btn-sm">{{ t("common.close") }}</button>
</div>
</div>
<div class="modal-backdrop" @click="closeSolution"></div>
</div>
</div>
</template>
@@ -0,0 +1,203 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useMutation, useQuery, useQueryClient } from "@tanstack/vue-query";
import dayjs from "dayjs";
import {
submissionsApiStopSyncScopesMutation,
submissionsApiSyncScopesMutation,
submissionsApiSyncScopesStatusOptions,
submissionsApiSyncScopesStatusQueryKey,
} from "@/api/@tanstack/vue-query.gen";
interface Props {
eventPath: string;
gamePath: string;
gameName: string;
}
const props = defineProps<Props>();
const open = defineModel<boolean>("open", { required: true });
const { t } = useI18n();
const queryClient = useQueryClient();
const path = computed(() => ({ event_path: props.eventPath, game_path: props.gamePath }));
const statusKey = computed(() => submissionsApiSyncScopesStatusQueryKey({ path: path.value }));
// Polled while open, so admins see each run land (last/next run, errors).
const { data: status, isLoading } = useQuery(
computed(() => ({
...submissionsApiSyncScopesStatusOptions({ path: path.value }),
enabled: open.value,
refetchInterval: 5000,
})),
);
const apibotToken = ref("");
const message = ref<{ type: "success" | "info" | "error"; text: string } | null>(null);
watch(open, (isOpen) => {
if (!isOpen) {
apibotToken.value = "";
message.value = null;
}
});
const refreshStatus = () => queryClient.invalidateQueries({ queryKey: statusKey.value });
const start = useMutation({
...submissionsApiSyncScopesMutation(),
onSuccess: (data) => {
apibotToken.value = "";
message.value = data.started
? { type: "success", text: t("scopeSync.started") }
: { type: "info", text: t("scopeSync.alreadyRunning") };
},
onError: () => {
message.value = { type: "error", text: t("scopeSync.startFailed") };
},
onSettled: refreshStatus,
});
const stop = useMutation({
...submissionsApiStopSyncScopesMutation(),
onSuccess: (data) => {
message.value = data.stopped
? { type: "success", text: t("scopeSync.stopped") }
: { type: "info", text: t("scopeSync.notRunning") };
},
onError: () => {
message.value = { type: "error", text: t("scopeSync.stopFailed") };
},
onSettled: refreshStatus,
});
const busy = computed(() => start.isPending.value || stop.isPending.value);
const hasToken = computed(() => status.value?.has_token ?? false);
const tokenTyped = computed(() => apibotToken.value.trim() !== "");
const submit = () => {
start.mutate({
path: path.value,
body: { apibot_token: tokenTyped.value ? apibotToken.value.trim() : null },
});
};
const AANDT_STATUSES: Record<string, string> = {
"0prep": "prep",
"1publ": "published",
"3insc": "registrations",
"5inscdone": "registrationsDone",
"7inprog": "inProgress",
"9done": "done",
"11reviewed": "reviewed",
};
const aandtStatusLabel = computed(() => {
const value = status.value?.aandt_status;
if (!value) return t("scopeSync.unknown");
return AANDT_STATUSES[value] ? t(`scopeSync.aandtStatus.${AANDT_STATUSES[value]}`) : value;
});
const formatDate = (value?: string | null) =>
value ? dayjs(value).format("DD/MM HH:mm:ss") : t("scopeSync.never");
</script>
<template>
<div :class="['modal', { 'modal-open': open }]">
<div class="modal-box w-11/12 max-w-4xl max-h-[90vh] overflow-y-auto">
<h3 class="font-bold text-xl flex items-center gap-2">
<i class="mdi mdi-sync"></i>
{{ t("scopeSync.title", { game: gameName }) }}
</h3>
<!-- What this actually does -->
<div class="mt-4 space-y-3 text-base-content/80">
<p>{{ t("scopeSync.intro") }}</p>
<ul class="list-disc pl-6 space-y-1">
<li>{{ t("scopeSync.whatScopes") }}</li>
<li>{{ t("scopeSync.whatPlayers") }}</li>
<li>{{ t("scopeSync.whatClose") }}</li>
<li>{{ t("scopeSync.whatLink") }}</li>
<li>{{ t("scopeSync.whatLive") }}</li>
</ul>
</div>
<div class="alert alert-info mt-4 items-start">
<i class="mdi mdi-autorenew text-2xl"></i>
<div>
<h4 class="font-semibold">{{ t("scopeSync.autoTitle") }}</h4>
<p class="text-sm">{{ t("scopeSync.autoInterval") }}</p>
<p class="text-sm">{{ t("scopeSync.autoStop") }}</p>
<p class="text-sm">{{ t("scopeSync.autoErrors") }}</p>
</div>
</div>
<!-- Current state -->
<div class="mt-6">
<h4 class="font-semibold mb-2">{{ t("scopeSync.statusTitle") }}</h4>
<div v-if="isLoading" class="flex justify-center py-6">
<span class="loading loading-spinner"></span>
</div>
<div v-else-if="status" class="stats stats-vertical md:stats-horizontal shadow w-full">
<div class="stat">
<div class="stat-title">{{ t("scopeSync.loop") }}</div>
<div class="stat-value text-lg flex items-center gap-2">
<span :class="['badge', status.running ? 'badge-success' : 'badge-ghost']">
{{ status.running ? t("scopeSync.running") : t("scopeSync.notRunningShort") }}
</span>
</div>
<div class="stat-desc">
{{ t("scopeSync.nextRun") }}: {{ status.running ? formatDate(status.next_run_at) : "—" }}
</div>
</div>
<div class="stat">
<div class="stat-title">{{ t("scopeSync.aandt") }}</div>
<div class="stat-value text-lg">{{ aandtStatusLabel }}</div>
<div class="stat-desc">{{ t("scopeSync.lastRun") }}: {{ formatDate(status.last_run_at) }}</div>
</div>
<div class="stat">
<div class="stat-title">{{ t("scopeSync.scopes") }}</div>
<div class="stat-value text-lg">{{ status.active_scope_count }} / {{ status.scope_count }}</div>
<div class="stat-desc">{{ t("scopeSync.activeOfTotal") }}</div>
</div>
</div>
<div v-if="status?.error" class="alert alert-error mt-3">
<i class="mdi mdi-alert-circle-outline"></i>
<span>{{ t("scopeSync.lastError") }}: {{ status.error }}</span>
</div>
</div>
<!-- Token -->
<form class="mt-6" @submit.prevent="submit">
<label class="font-semibold block mb-1" for="apibot-token">{{ t("scopeSync.tokenTitle") }}</label>
<p class="text-sm text-base-content/70 mb-2">
{{ hasToken ? t("scopeSync.tokenReplace") : t("scopeSync.tokenMissing") }}
</p>
<input id="apibot-token" v-model="apibotToken" type="password" autocomplete="off"
:placeholder="hasToken ? t('scopeSync.tokenConfigured') : t('scopeSync.tokenPlaceholder')"
class="input input-bordered w-full" />
<div v-if="message" :class="['alert mt-4', `alert-${message.type}`]">{{ message.text }}</div>
<div class="modal-action flex-wrap">
<button type="button" @click="open = false" class="btn">{{ t("common.close") }}</button>
<button v-if="status?.running" type="button" :disabled="busy" class="btn btn-error"
@click="stop.mutate({ path })">
<span v-if="stop.isPending.value" class="loading loading-spinner loading-xs"></span>
<i v-else class="mdi mdi-stop"></i>
{{ t("scopeSync.stop") }}
</button>
<button type="submit" class="btn btn-primary"
:disabled="busy || (!hasToken && !tokenTyped) || (status?.running && !tokenTyped)">
<span v-if="start.isPending.value" class="loading loading-spinner loading-xs"></span>
<i v-else class="mdi mdi-play"></i>
{{ status?.running ? t("scopeSync.saveToken") : t("scopeSync.start") }}
</button>
</div>
</form>
</div>
<div class="modal-backdrop" @click="open = false"></div>
</div>
</template>
@@ -0,0 +1,44 @@
<script setup lang="ts">
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import type { SteamGameOut } from "../api/types.gen";
defineProps<{ game: SteamGameOut }>();
const { t } = useI18n();
// Not every game has a library capsule on Steam, fall back to the header + name
const capsuleFailed = ref(false);
</script>
<template>
<div class="group relative aspect-[2/3] rounded-md overflow-hidden bg-base-200 hover:bg-base-100
shadow-xl hover:shadow-2xl transition-all transform hover:-translate-y-2 hover:scale-[1.05]">
<a :href="game.store_url" target="_blank" rel="noopener noreferrer" :title="game.name" class="block w-full h-full">
<img v-if="!capsuleFailed" :src="game.library_image" :alt="game.name" loading="lazy"
class="w-full h-full object-cover" @error="capsuleFailed = true" />
<div v-else class="w-full h-full flex flex-col justify-center gap-4 p-3 bg-gradient-to-b from-base-100 to-base-300">
<img :src="game.header_image" :alt="game.name" loading="lazy" class="w-full rounded-sm" />
<span class="text-center font-medium line-clamp-3">{{ game.name }}</span>
</div>
</a>
<!-- Opens the Steam client: launches the game if installed, offers to install it otherwise -->
<a :href="`steam://run/${game.steam_app_id}`" :title="t('games.play')"
class="steam-play absolute bottom-2 right-2 rounded-full w-10 h-10 flex items-center justify-center text-2xl
opacity-0 translate-y-1 transition-all group-hover:opacity-100 group-hover:translate-y-0 focus:opacity-100">
<i class="mdi mdi-play"></i>
</a>
</div>
</template>
<style scoped>
.steam-play {
color: #ffffff;
background: linear-gradient(to right, #47bfff 5%, #1a44c2 95%);
}
.steam-play:hover {
background: linear-gradient(to right, #6fceff 5%, #2d5fd8 95%);
}
</style>
@@ -0,0 +1,96 @@
<script setup lang="ts">
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import type { SteamGameOut } from "../api/types.gen";
const props = defineProps<{ game: SteamGameOut }>();
const { t } = useI18n();
// Steam gives prices in cents
const formatPrice = (cents: number) =>
new Intl.NumberFormat(undefined, {
style: "currency",
currency: props.game.currency || "CHF",
}).format(cents / 100);
const hasPrice = computed(() => props.game.price_final != null && !!props.game.currency);
const isDiscounted = computed(() => hasPrice.value && props.game.discount_percent > 0);
</script>
<template>
<div
class="card card-xl bg-base-200 hover:bg-base-100 overflow-hidden shadow-xl hover:shadow-2xl transition-all transform hover:-translate-y-2 hover:scale-[1.05]">
<a :href="game.store_url" target="_blank" rel="noopener noreferrer">
<img :src="game.header_image" :alt="game.name" loading="lazy"
class="w-full aspect-[460/215] object-cover" />
</a>
<div class="card-body min-w-0">
<a :href="game.store_url" target="_blank" rel="noopener noreferrer"
class="card-title text-2xl block truncate hover:underline">
{{ t("games.buy", { game: game.name }) }}
</a>
<p v-if="game.short_description" class="text-sm text-base-content/70 line-clamp-3">
{{ game.short_description }}
</p>
<div class="mt-auto pt-2 flex flex-wrap sm:flex-nowrap justify-end gap-2 whitespace-nowrap">
<!-- Opens the Steam client: launches the game if installed, offers to install it otherwise -->
<a :href="`steam://run/${game.steam_app_id}`"
class="steam-play rounded-sm px-5 py-2 flex items-center gap-1">
<i class="mdi mdi-play"></i>
{{ t("games.play") }}
</a>
<div class="bg-base-300 flex items-stretch rounded-sm overflow-hidden">
<template v-if="game.is_free">
<span class="px-3 py-2 flex items-center">{{ t("games.free") }}</span>
</template>
<template v-else-if="hasPrice">
<span v-if="isDiscounted" class="steam-discount px-3 flex items-center text-xl font-medium">
-{{ game.discount_percent }}%
</span>
<span class="px-3 flex flex-col justify-center leading-tight">
<span v-if="isDiscounted" class="text-base-content/50 text-xs line-through">
{{ formatPrice(game.price_initial!) }}
</span>
<span :class="{ 'text-success font-medium': isDiscounted }">{{ formatPrice(game.price_final!) }}</span>
</span>
</template>
<a :href="game.store_url" target="_blank" rel="noopener noreferrer"
class="steam-button px-5 py-2 flex items-center gap-1">
<i class="mdi mdi-steam"></i>
{{ t("games.viewOnSteam") }}
</a>
</div>
</div>
</div>
</div>
</template>
<style scoped>
/* Steam palette for the purchase buttons, the card itself follows the site theme */
.steam-discount {
background: #4c6b22;
color: #beee11;
}
.steam-button {
color: #d2efa9;
background: linear-gradient(to right, #75b022 5%, #588a1b 95%);
}
.steam-button:hover {
color: #ffffff;
background: linear-gradient(to right, #8ed629 5%, #6aa621 95%);
}
.steam-play {
color: #ffffff;
background: linear-gradient(to right, #47bfff 5%, #1a44c2 95%);
}
.steam-play:hover {
background: linear-gradient(to right, #6fceff 5%, #2d5fd8 95%);
}
</style>
@@ -0,0 +1,10 @@
import { watch, type Ref } from "vue";
import { usePageHeaderStore, type LiveKind } from "@/stores/pageHeader";
// Shows the page's live (websocket) state as a badge mid-header, with a
// popover explaining what it means on this page (liveStatus.<kind> strings).
// Reset by the router on the next navigation.
export const useLiveBadge = (kind: LiveKind, connected: Ref<boolean>) => {
const pageHeaderStore = usePageHeaderStore();
watch(connected, (value) => pageHeaderStore.setLive(value, kind), { immediate: true });
};
@@ -1,4 +1,4 @@
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useWebSocket } from '@vueuse/core'
import { placeApiCanvas } from '@/api'
@@ -16,6 +16,7 @@ const PLACE_COOLDOWN_SECONDS = 30
export type OnPixel = (x: number, y: number, colorIndex: number) => void
export type OnResize = (width: number, height: number) => void
export type OnWipe = () => void
// Plain (non-reactive) - a several-thousand-cell reactive array is
// pointless overhead. Kept module-level, alongside its dimensions, so the
@@ -26,9 +27,18 @@ let grid = new Uint8Array(DEFAULT_GRID_SIZE * DEFAULT_GRID_SIZE)
const gridWidth = ref(DEFAULT_GRID_SIZE)
const gridHeight = ref(DEFAULT_GRID_SIZE)
export function usePlaceSocket(eventPath: string, onPixel?: OnPixel, onResize?: OnResize) {
export function usePlaceSocket(
eventPath: string,
onPixel?: OnPixel,
onResize?: OnResize,
onWipe?: OnWipe,
) {
const cooldownEndMs = ref<number | null>(null)
const cooldownRemainingMs = ref(0)
// PlaceSettings.placement_ends_at - the server rejects placements past it
// anyway, this just lets the UI say so.
const placementEndMs = ref<number | null>(null)
const placementEnded = ref(false)
let animationFrame: number | null = null
@@ -36,9 +46,23 @@ export function usePlaceSocket(eventPath: string, onPixel?: OnPixel, onResize?:
cooldownEndMs.value = nextMs ?? null
}
// Returns true if placement went from over to open again (an admin moved
// the end time later or cleared it), so the caller can bring the real
// board back - the server serves it again.
function applyPlacementEnd(endMs: string): boolean {
const wasEnded = placementEnded.value
placementEndMs.value = endMs !== '' ? Number(endMs) : null
placementEnded.value = placementEndMs.value !== null && placementEndMs.value <= Date.now()
return wasEnded && !placementEnded.value
}
function tickCooldown() {
const now = Date.now()
cooldownRemainingMs.value =
cooldownEndMs.value !== null ? Math.max(0, cooldownEndMs.value - Date.now()) : 0
cooldownEndMs.value !== null ? Math.max(0, cooldownEndMs.value - now) : 0
// Only ever flips it on: the server's own 'w'/'r|d' may beat a skewed
// local clock, and reopening goes through applyPlacementEnd.
if (placementEndMs.value !== null && placementEndMs.value <= now) placementEnded.value = true
animationFrame = requestAnimationFrame(tickCooldown)
}
@@ -65,9 +89,10 @@ export function usePlaceSocket(eventPath: string, onPixel?: OnPixel, onResize?:
switch (parts[0]) {
case 's': {
const [, next, width, height] = parts
const [, next, width, height, end] = parts
applyCooldown(next !== '' ? Number(next) : null)
applyGridSize(Number(width), Number(height))
applyPlacementEnd(end)
break
}
case 'p': {
@@ -81,14 +106,24 @@ export function usePlaceSocket(eventPath: string, onPixel?: OnPixel, onResize?:
}
case 'r': {
if (parts[1] === 'c') applyCooldown(Number(parts[2]))
if (parts[1] === 'd') placementEnded.value = true
break
}
case 'e': {
const [, width, height] = parts
const [, width, height, end] = parts
const reopened = applyPlacementEnd(end)
// The server already rebuilt its canvas at the new size (see
// place/signals.py) - just re-fetch it rather than guess how to
// remap our local pixels.
if (applyGridSize(Number(width), Number(height))) loadCanvas()
if (applyGridSize(Number(width), Number(height)) || reopened) loadCanvas()
break
}
case 'w': {
// Placement is over: the server now serves a blank canvas, match it
// locally and let the page animate the wipe instead of redrawing.
placementEnded.value = true
grid.fill(0)
onWipe?.()
break
}
default:
@@ -108,6 +143,15 @@ export function usePlaceSocket(eventPath: string, onPixel?: OnPixel, onResize?:
const connected = computed(() => status.value === 'OPEN')
// Pixels placed while disconnected never reach us: catch up by reloading
// the whole canvas on every reconnect (the first load is done on mount).
let hasConnected = false
watch(connected, (isConnected) => {
if (!isConnected) return
if (hasConnected) loadCanvas()
hasConnected = true
})
async function loadCanvas() {
const response = await placeApiCanvas({ path: { event_path: eventPath } })
if (!response.data) return
@@ -142,6 +186,8 @@ export function usePlaceSocket(eventPath: string, onPixel?: OnPixel, onResize?:
return {
connected,
cooldownRemainingMs,
placementEndMs,
placementEnded,
cooldownDurationSeconds: PLACE_COOLDOWN_SECONDS,
gridWidth,
gridHeight,
@@ -1,9 +1,11 @@
import { ref, computed, onBeforeUnmount } from 'vue'
import { ref, computed } from 'vue'
import { useWebSocket } from '@vueuse/core'
import { useLiveBadge } from '@/composables/useLiveBadge'
interface SubmissionUpdate {
id: string
scope_id?: string
username?: string | null
notes?: string
files?: SubmissionFileUpdate[]
created_at: string
@@ -23,6 +25,7 @@ interface SubmissionFileUpdate {
interface ImageCropUpdate {
id: string
submission_file_id: string
x1: number
y1: number
x2: number
@@ -33,13 +36,36 @@ interface ImageCropUpdate {
created_at: string
}
type WebSocketData = SubmissionUpdate | SubmissionFileUpdate | ImageCropUpdate
// A scope (match) the user was or is assigned to opened/closed, or the user
// got (un)assigned from it - see broadcast_scope_updates in signals.py.
export interface ScopeUpdate {
id: string
is_active: boolean
assigned: boolean
}
export function useSubmissionsWebSocket(userSubmissions: any) {
// See broadcast_image_crop_delete in signals.py
interface DeletedCrop {
id: string
submission_file_id: string
}
type WebSocketData =
| { deleted_crop: DeletedCrop }
| SubmissionUpdate
| SubmissionFileUpdate
| ImageCropUpdate
| { scope: ScopeUpdate }
interface Options {
userSubmissions?: any
// Only submissions of this scope get added to the list (staff get them all)
scopeId?: string
onScopeUpdate?: (scope: ScopeUpdate) => void
}
export function useSubmissionsWebSocket({ userSubmissions, scopeId, onScopeUpdate }: Options) {
const isConnected = ref(false)
const reconnectAttempts = ref(0)
const maxReconnectAttempts = 10
const reconnectDelay = ref(3000)
const wsUrl = computed(() => {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
@@ -53,14 +79,11 @@ export function useSubmissionsWebSocket(userSubmissions: any) {
} = useWebSocket(wsUrl.value, {
onConnected: () => {
isConnected.value = true
reconnectAttempts.value = 0
reconnectDelay.value = 3000
console.log('✓ Connected to submissions WebSocket')
},
onDisconnected: () => {
isConnected.value = false
console.log('✗ Disconnected from submissions WebSocket, attempting to reconnect...')
attemptReconnect()
console.log('✗ Disconnected from submissions WebSocket')
},
onError: (event) => {
console.error('WebSocket error:', event)
@@ -70,7 +93,13 @@ export function useSubmissionsWebSocket(userSubmissions: any) {
const messageData = event.data as string
const data = JSON.parse(messageData) as WebSocketData
if ('files' in data) {
if ('scope' in data) {
onScopeUpdate?.(data.scope)
} else if (!userSubmissions) {
return
} else if ('deleted_crop' in data) {
handleCropDelete(data.deleted_crop)
} else if ('files' in data) {
handleSubmissionUpdate(data as SubmissionUpdate)
} else if ('original_filename' in data) {
handleFileUpdate(data as SubmissionFileUpdate)
@@ -82,25 +111,21 @@ export function useSubmissionsWebSocket(userSubmissions: any) {
}
},
immediate: true,
// vueuse's own reconnect stops once close() is called (it also closes
// on unmount), unlike a hand-rolled setTimeout(open) that would reopen
// the socket after leaving the page.
autoReconnect: {
retries: 10,
delay: 3000,
onFailed: () => console.error('Max reconnection attempts reached'),
},
})
const attemptReconnect = () => {
if (reconnectAttempts.value >= maxReconnectAttempts) {
console.error('Max reconnection attempts reached')
return
}
reconnectAttempts.value++
const delay = reconnectDelay.value * Math.pow(1.5, reconnectAttempts.value - 1)
console.log(`Reconnecting (attempt ${reconnectAttempts.value}/${maxReconnectAttempts}) in ${Math.round(delay / 1000)}s...`)
setTimeout(() => {
open()
}, delay)
}
useLiveBadge('submissions', isConnected)
const handleSubmissionUpdate = (submission: SubmissionUpdate) => {
if (scopeId && submission.scope_id !== scopeId) return
const existingIndex = userSubmissions.value.findIndex((s: any) => s.id === submission.id)
if (existingIndex >= 0) {
@@ -127,6 +152,8 @@ export function useSubmissionsWebSocket(userSubmissions: any) {
}
const handleCropUpdate = (crop: ImageCropUpdate) => {
let found = false
userSubmissions.value.forEach((submission: any) => {
if (!submission.files) return
@@ -137,15 +164,38 @@ export function useSubmissionsWebSocket(userSubmissions: any) {
if (cropIndex >= 0) {
// Merge into existing object to preserve references
Object.assign(file.crops[cropIndex], crop)
found = true
console.log('Updated crop:', crop.id)
}
})
})
if (!found) handleNewCrop(crop)
}
onBeforeUnmount(() => {
close()
const handleCropDelete = (crop: DeletedCrop) => {
userSubmissions.value.forEach((submission: any) => {
submission.files?.forEach((file: any) => {
if (file.id !== crop.submission_file_id || !file.crops) return
file.crops = file.crops.filter((c: any) => c.id !== crop.id)
console.log('Deleted crop:', crop.id)
})
})
}
// New crop (e.g. drawn by another admin): add it to its file
const handleNewCrop = (crop: ImageCropUpdate) => {
userSubmissions.value.forEach((submission: any) => {
submission.files?.forEach((file: any) => {
if (file.id !== crop.submission_file_id) return
file.crops = file.crops || []
file.crops.push(crop)
console.log('Added crop:', crop.id)
})
})
}
return {
isConnected,
@@ -0,0 +1,14 @@
import { computed } from "vue";
import { useQuery } from "@tanstack/vue-query";
import { userQuery } from "@/queries";
export const useUser = () => {
const { data } = useQuery(userQuery());
return computed(() => ({
username: data.value?.username ?? "",
isAuthenticated: data.value?.is_authenticated ?? false,
isStaff: data.value?.is_staff ?? false,
isSuperuser: data.value?.is_superuser ?? false,
}));
};
+46 -8
View File
@@ -3,16 +3,27 @@ import { computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { storeToRefs } from "pinia";
import { useUserStore } from "@/stores/user";
import { useUser } from "@/composables/useUser";
import { usePageHeaderStore } from "@/stores/pageHeader";
const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const { t, tm, rt } = useI18n();
const userInfo = useUser();
const pageHeaderStore = usePageHeaderStore();
const { title: dynamicTitle, backRoute: dynamicBackRoute } = storeToRefs(pageHeaderStore);
const { title: dynamicTitle, backRoute: dynamicBackRoute, live, liveKind } = storeToRefs(pageHeaderStore);
// Popover text of the live badge, per page (liveStatus.<kind>.live/offline)
const liveHelp = computed(() => {
if (!liveKind.value) return null;
const key = `liveStatus.${liveKind.value}.${live.value ? "live" : "offline"}`;
return {
title: t(`${key}.title`),
intro: t(`${key}.intro`),
points: (tm(`${key}.points`) as unknown[]).map((point) => rt(point as Parameters<typeof rt>[0])),
outro: t(`${key}.outro`),
};
});
const title = computed(() => {
if (dynamicTitle.value) return dynamicTitle.value;
@@ -30,13 +41,39 @@ const goBack = () => {
<template>
<div class="navbar bg-base-100 shadow-lg">
<div class="container min-w-3/4 mx-auto w-full flex items-center gap-4">
<!-- 3 columns so the live badge stays centered whatever the sides' width -->
<div class="container min-w-3/4 mx-auto w-full grid grid-cols-[1fr_auto_1fr] items-center gap-4">
<div class="flex items-center gap-4 min-w-0">
<button v-if="route.meta.getBackRoute" @click="goBack" class="btn btn-primary btn-sm">
<i class="mdi mdi-arrow-left"></i>
{{ t("common.back") }}
</button>
<h1 class="text-xl font-bold">{{ title }}</h1>
<div class="flex-1"></div>
<h1 class="text-xl font-bold truncate">{{ title }}</h1>
</div>
<div>
<!-- Hover (or tap, on mobile) to explain what live means for the player -->
<div v-if="live !== null" class="dropdown dropdown-hover dropdown-center">
<div tabindex="0" role="button" :class="['badge cursor-help', live ? 'badge-success' : 'badge-warning']">
<i :class="['mdi mr-1', live ? 'mdi-wifi' : 'mdi-wifi-off']"></i>
{{ live ? t("submissions.live") : t("submissions.offline") }}
<i class="mdi mdi-information-outline ml-1 opacity-70"></i>
</div>
<div tabindex="0" class="dropdown-content card card-sm bg-base-200 shadow-xl z-50 w-80 mt-2">
<div v-if="liveHelp" class="card-body">
<h3 class="card-title text-base">
<i :class="['mdi', live ? 'mdi-wifi text-success' : 'mdi-wifi-off text-warning']"></i>
{{ liveHelp.title }}
</h3>
<p>{{ liveHelp.intro }}</p>
<ul v-if="liveHelp.points.length" class="list-disc pl-5 space-y-1">
<li v-for="point in liveHelp.points" :key="point">{{ point }}</li>
</ul>
<p class="text-base-content/70">{{ liveHelp.outro }}</p>
</div>
</div>
</div>
</div>
<div class="flex items-center justify-end gap-4">
<div v-if="userInfo.isAuthenticated" class="flex items-center gap-2">
<div class="text-sm">
<span class="font-medium">{{ userInfo.username }}</span>
@@ -48,4 +85,5 @@ const goBack = () => {
<a v-if="userInfo.isStaff" href="/admin" class="btn btn-xs btn-warning">{{ t("common.adminPanel") }}</a>
</div>
</div>
</div>
</template>
+139 -7
View File
@@ -24,6 +24,7 @@
"puzzle": "Puzzle",
"files": "Files",
"date": "Date",
"user": "User",
"notes": "Notes",
"actions": "Actions",
"noRankYet": "No rank yet",
@@ -64,13 +65,29 @@
"title": "PolyLAN Submitter",
"subtitle": "Choose a game and submit your best solutions",
"submitResults": "Submit results",
"getTheGames": "Get the games",
"planning": "Planning",
"footer": "Select a game above to begin submitting"
},
"games": {
"header": "Games",
"title": "Get the games",
"subtitle": "Don't own them yet? Grab them on Steam",
"empty": "No Steam games for this event",
"buy": "Buy {game}",
"free": "Free to Play",
"viewOnSteam": "View on Steam",
"play": "Play",
"showPrices": "Show prices"
},
"planning": {
"header": "Planning",
"title": "Planning",
"empty": "No planning for this event yet"
},
"clock": {
"pageTitle": "Beat the Clock",
"header": "Beat the Clock",
"connected": "connected",
"reconnecting": "reconnecting…",
"press": "PRESS",
"nextPlayer": "▲ next player",
"chasingYou": "▼ chasing you",
@@ -79,10 +96,10 @@
"place": {
"pageTitle": "Place",
"header": "Place",
"connected": "connected",
"reconnecting": "reconnecting…",
"showGrid": "Show grid",
"hideGrid": "Hide grid"
"hideGrid": "Hide grid",
"placementEnded": "Pixel placement is over",
"endsAt": "Ends at {time}"
},
"market": {
"pageTitle": "Market",
@@ -161,6 +178,7 @@
}
},
"yourSubmissions": "Your Submissions",
"allSubmissions": "All Submissions",
"noSubmissionsHint": "Upload your first submission above to get started",
"fileStatus": "File Status",
"ocrStatus": "OCR Status",
@@ -198,7 +216,118 @@
"title": "Select your match",
"description": "You're assigned to multiple matches for {game}. Pick which one you want to submit for.",
"notAssignedTitle": "No match assigned",
"notAssignedMessage": "You are not assigned to a scope/matches, you cannot submit a score."
"notAssignedMessage": "You are not assigned to a scope/matches, you cannot submit a score.",
"syncScopes": "Sync scopes"
},
"scopeSync": {
"title": "AAndT scope sync — {game}",
"intro": "Keeps this game's matches (scopes) in line with its AAndT on the PolyLAN site, using the AAndT's apibot API.",
"whatScopes": "Every AAndT match becomes a scope here, created or updated (name, open/closed) on each sync.",
"whatPlayers": "Players of each match are assigned to its scope, matched through their PolyLAN account. Players without an account here yet are skipped until they log in once.",
"whatClose": "A scope is open only while its match is playing. Finished matches, and matches removed from the AAndT, get closed.",
"whatLink": "Each playing match gets a \"Submit your proof here\" link on the PolyLAN site, pointing to its submission page here.",
"whatLive": "Players are moved live: when their match closes, they're sent back to the match list, and straight into their next match if there's only one. No refresh needed.",
"autoTitle": "Starts once, then keeps going on its own",
"autoInterval": "After starting, the sync re-triggers itself: every 15 seconds while the AAndT is in progress, every minute before that (registrations, preparation, ...).",
"autoStop": "It stops by itself once the AAndT is done or reviewed, or when you stop it here (or with the \"Stop scope sync\" admin action). Scopes are kept as they are when it stops.",
"autoErrors": "If a sync fails (AAndT site down, wrong token, ...), it's retried a minute later. The last error is shown below.",
"statusTitle": "Current state",
"loop": "Sync",
"running": "Running",
"notRunningShort": "Stopped",
"nextRun": "Next run",
"lastRun": "Last run",
"aandt": "AAndT status",
"scopes": "Scopes",
"activeOfTotal": "open / total",
"lastError": "Last run failed",
"never": "never",
"unknown": "Unknown",
"aandtStatus": {
"prep": "Preparation",
"published": "Published",
"registrations": "Registrations",
"registrationsDone": "Registrations closed",
"inProgress": "In progress",
"done": "Done",
"reviewed": "Reviewed"
},
"tokenTitle": "AAndT apibot token",
"tokenMissing": "No token is configured for this game yet. Paste the one from the AAndT's \"apibot\" admin page on the PolyLAN site.",
"tokenReplace": "A token is already configured. Paste a new one only to replace it (e.g. for a new AAndT); a running sync picks it up on its next run.",
"tokenPlaceholder": "Apibot token",
"tokenConfigured": "Token configured (leave empty to keep it)",
"start": "Start sync",
"saveToken": "Save token",
"stop": "Stop sync",
"started": "Sync started. It keeps running on its own until the AAndT is done.",
"alreadyRunning": "Sync is already running.",
"startFailed": "Failed to start the sync.",
"stopped": "Sync stopped.",
"notRunning": "Sync wasn't running.",
"stopFailed": "Failed to stop the sync."
},
"liveStatus": {
"submissions": {
"live": {
"title": "You're connected live",
"intro": "This page updates on its own, you don't need to refresh it:",
"points": [
"Your submissions update as they're processed (uploaded files, text read from your screenshots).",
"When your match ends, you're sent back to the match list, and straight into your next match if you have only one."
],
"outro": "Just keep this page open between matches."
},
"offline": {
"title": "Live connection lost",
"intro": "The page can't get updates right now:",
"points": [
"It won't move you to your next match on its own.",
"Processing results of your submissions won't show up by themselves."
],
"outro": "It reconnects automatically, usually within a few seconds. Still offline after a while? Refresh the page, anything you already submitted is saved."
}
},
"clock": {
"live": {
"title": "You're connected live",
"intro": "Everything here is real time, shared with every player:",
"points": [
"The countdown is the same for everyone, and moves as soon as someone presses.",
"Your points and rank update right after each of your presses."
],
"outro": "Presses go through this live connection, keep it green to play."
},
"offline": {
"title": "Live connection lost",
"intro": "You can't play right now:",
"points": [
"Your presses can't reach the server.",
"The countdown shown may be off, other players' presses aren't coming in."
],
"outro": "It reconnects automatically within a second or so, and your stats are refreshed when it does. Still offline? Refresh the page."
}
},
"place": {
"live": {
"title": "You're connected live",
"intro": "The canvas is shared with every player, in real time:",
"points": [
"Pixels placed by others show up as soon as they're placed.",
"Your pixels go through this live connection, then the cooldown starts."
],
"outro": "Just keep this page open, no refresh needed."
},
"offline": {
"title": "Live connection lost",
"intro": "You can't place pixels right now:",
"points": [
"Your clicks can't reach the server.",
"Pixels placed by others aren't coming in, the canvas may be out of date."
],
"outro": "It reconnects automatically within a second or so, and reloads the whole canvas to catch up. Still offline? Refresh the page."
}
}
},
"errorPage": {
"notFound": {
@@ -350,7 +479,10 @@
"second": "🥈 2nd Place",
"third": "🥉 3rd Place"
},
"totalWithCoef": "Total (with coef.)"
"totalWithCoef": "Total (with coef.)",
"viewSolution": "View solution",
"solutionTitle": "{username} — {puzzleTitle}",
"noSolutionFiles": "No file attached to this solution"
},
"topUsersLeaderboard": {
"title": "Top 10 Users"
+7
View File
@@ -1,12 +1,19 @@
import { createApp } from "vue";
import { VueQueryPlugin } from "@tanstack/vue-query";
import App from "@/App.vue";
import { router } from "@/router";
import { pinia } from "@/stores";
import { i18n } from "@/i18n";
import { onQueryCacheRestored, queryClient, restoreQueryCache } from "@/queries";
import "@/style.css";
const app = createApp(App);
app.use(pinia);
app.use(VueQueryPlugin, {
queryClient,
clientPersister: restoreQueryCache,
clientPersisterOnSuccess: onQueryCacheRestored,
});
app.use(router);
app.use(i18n);
app.mount("#app");
+68
View File
@@ -0,0 +1,68 @@
// The end-of-game wipe (see place/tasks.py): a wavy front sweeps the board
// diagonally from the top-left, a cyan crest leaving plain white (palette
// index 0, what the server's blank canvas holds) behind it.
const WIPE_DURATION_MS = 2200
// Crest thickness and front wobble, in cells
const CREST_WIDTH = 6
const WOBBLE = 2.5
const CREST_RGB = [0x00, 0xd3, 0xdd]
function easeInOut(t: number) {
return t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2
}
// Works on a snapshot of the canvas through ImageData rather than per-cell
// fillRect, so it stays smooth on a big grid. Returns a cancel function.
export function playWipeWave(ctx: CanvasRenderingContext2D, width: number, height: number) {
const before = ctx.getImageData(0, 0, width, height)
const frame = ctx.createImageData(width, height)
const out = frame.data
const src = before.data
// Distance of each cell from the start corner, wobbled so the front reads
// as a wave rather than a straight line.
const distance = new Float32Array(width * height)
const wobblePeriod = Math.max(width, height) / 5
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
distance[y * width + x] = x + y + WOBBLE * Math.sin((x - y) / wobblePeriod)
}
}
const travel = width + height + 2 * WOBBLE + CREST_WIDTH
let start: number | null = null
let animationFrame: number | null = null
function step(now: number) {
start ??= now
const progress = Math.min(1, (now - start) / WIPE_DURATION_MS)
const front = easeInOut(progress) * travel - WOBBLE
for (let i = 0; i < distance.length; i++) {
const o = i * 4
const behind = front - distance[i]
if (behind <= 0) {
out[o] = src[o]
out[o + 1] = src[o + 1]
out[o + 2] = src[o + 2]
} else if (behind < CREST_WIDTH) {
// Cyan at the leading edge, fading to white at the back of the crest
const t = behind / CREST_WIDTH
out[o] = CREST_RGB[0] + (255 - CREST_RGB[0]) * t
out[o + 1] = CREST_RGB[1] + (255 - CREST_RGB[1]) * t
out[o + 2] = CREST_RGB[2] + (255 - CREST_RGB[2]) * t
} else {
out[o] = out[o + 1] = out[o + 2] = 255
}
out[o + 3] = 255
}
ctx.putImageData(frame, 0, 0)
animationFrame = progress < 1 ? requestAnimationFrame(step) : null
}
animationFrame = requestAnimationFrame(step)
return () => {
if (animationFrame !== null) cancelAnimationFrame(animationFrame)
}
}
+52
View File
@@ -0,0 +1,52 @@
import { QueryClient } from "@tanstack/vue-query";
import { persistQueryClient } from "@tanstack/query-persist-client-core";
import { createSyncStoragePersister } from "@tanstack/query-sync-storage-persister";
import {
gamesApiListEventGamesOptions,
gamesApiListEventPlanningOptions,
polylanSubmitterApiGetUserInfoOptions,
polylanSubmitterApiGetUserInfoQueryKey,
} from "@/api/@tanstack/vue-query.gen";
// Exported (not just provided by VueQueryPlugin) so Pinia stores can
// fetchQuery() through the same cache.
export const queryClient = new QueryClient();
// Login/logout are full-page redirects, but roles/scopes can still change
// server-side, so don't keep the user forever.
export const userQuery = () => ({
...polylanSubmitterApiGetUserInfoOptions(),
staleTime: 5 * 60 * 1000,
});
// Games only change when staff enable/disable one, a few minutes of
// staleness is fine.
export const eventGamesQuery = (eventPath: string) => ({
...gamesApiListEventGamesOptions({ path: { event_path: eventPath } }),
staleTime: 5 * 60 * 1000,
});
// Imported by staff a handful of times per event.
export const eventPlanningQuery = (eventPath: string) => ({
...gamesApiListEventPlanningOptions({ path: { event_path: eventPath } }),
staleTime: 5 * 60 * 1000,
});
const PERSISTED_QUERIES = new Set(["polylanSubmitterApiGetUserInfo", "gamesApiListEventGames"]);
// Restores user + games from localStorage before the app mounts, so pages
// render right away on reload instead of waiting on the API.
export const restoreQueryCache = (client: QueryClient) =>
persistQueryClient({
queryClient: client,
persister: createSyncStoragePersister({ storage: window.localStorage }),
dehydrateOptions: {
shouldDehydrateQuery: (query) =>
query.state.status === "success" &&
PERSISTED_QUERIES.has((query.queryKey[0] as { _id: string })._id),
},
});
// The restored user is only a placeholder until the real one comes back.
export const onQueryCacheRestored = (client: QueryClient) =>
client.invalidateQueries({ queryKey: polylanSubmitterApiGetUserInfoQueryKey() });
+16
View File
@@ -1,9 +1,11 @@
import { createRouter, createWebHistory, type RouteLocationNormalizedLoaded, type RouteLocationRaw } from "vue-router";
import Clock from "@/Clock.vue";
import Games from "@/Games.vue";
import Home from "@/Home.vue";
import Market from "@/Market.vue";
import Noita from "@/Noita.vue";
import OpusMagnum from "@/OpusMagnum.vue";
import Planning from "@/Planning.vue";
import Place from "@/Place.vue";
import PlaceEmbed from "@/PlaceEmbed.vue";
import Submissions from "@/Submissions.vue";
@@ -37,6 +39,20 @@ export const router = createRouter({
component: Home,
props: true,
},
{
path: "/:eventPath/games",
name: "games",
component: Games,
props: true,
meta: { titleKey: "games.header", getBackRoute: eventHome },
},
{
path: "/:eventPath/planning",
name: "planning",
component: Planning,
props: true,
meta: { titleKey: "planning.header", getBackRoute: eventHome },
},
{
path: "/:eventPath/market",
name: "market",
+3 -10
View File
@@ -1,7 +1,8 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { polylanSubmitterApiGetUserInfo, marketApiListMarkets, marketApiListUserBets, marketApiGetUserPoints } from '@/api'
import { marketApiListMarkets, marketApiListUserBets, marketApiGetUserPoints } from '@/api'
import type { Market } from '@/types'
import { queryClient, userQuery } from '@/queries'
import type { UserInfoOut, UserBetSchema } from '@/api/types.gen'
export const useMarketStore = defineStore('market', () => {
@@ -15,15 +16,7 @@ export const useMarketStore = defineStore('market', () => {
// Actions
const loadUserInfo = async () => {
try {
const response = await polylanSubmitterApiGetUserInfo()
if (response.data) {
userInfo.value = response.data
}
} catch (err) {
error.value = 'Failed to load user info'
console.error('Error loading user info:', err)
}
userInfo.value = await queryClient.fetchQuery(userQuery()).catch(() => undefined)
}
const loadMarkets = async (eventPath: string) => {
+5 -9
View File
@@ -4,10 +4,10 @@ import {
noitaApiGetResults,
noitaApiGetLeaderboard,
noitaApiSubmitLogFile,
polylanSubmitterApiGetUserInfo,
polylanSubmitterApiClearCache,
} from '@/api'
import type { ObjectivResultOut, LeaderboardEntryOut } from '@/api/types.gen'
import { queryClient, userQuery } from '@/queries'
export type Objective = ObjectivResultOut
@@ -80,14 +80,10 @@ export const useNoitaStore = defineStore('noita', () => {
}
const loadUserData = async (eventPath: string) => {
try {
const response = await polylanSubmitterApiGetUserInfo()
if (response.data?.is_authenticated) {
userInfo.value.username = response.data.username ?? ''
userInfo.value.isStaff = response.data.is_staff || false
}
} catch (err) {
console.error('Error fetching user info:', err)
const user = await queryClient.fetchQuery(userQuery()).catch(() => undefined)
if (user?.is_authenticated) {
userInfo.value.username = user.username ?? ''
userInfo.value.isStaff = user.is_staff || false
}
await Promise.all([fetchUserResults(eventPath), fetchLeaderboard(eventPath)])
+15 -1
View File
@@ -2,6 +2,9 @@ import { defineStore } from "pinia";
import { ref } from "vue";
import type { RouteLocationRaw } from "vue-router";
// Which page's explanation the live badge popover shows (liveStatus.<kind>)
export type LiveKind = "submissions" | "clock" | "place";
// Lets a routed page hand AppHeader a title built from data only that page
// has fetched (e.g. "Noita Submissions — Semifinal", assembled from an API
// call keyed by the scopeId route param). Cleared on every navigation so a
@@ -11,6 +14,10 @@ export const usePageHeaderStore = defineStore("pageHeader", () => {
// Overrides route.meta.getBackRoute when the right target depends on
// fetched data (e.g. skip the scope picker when it would auto-redirect).
const backRoute = ref<RouteLocationRaw | null>(null);
// Live (websocket) connection state of the page, shown mid-header; null
// when the page has no live connection (no badge at all).
const live = ref<boolean | null>(null);
const liveKind = ref<LiveKind | null>(null);
const setTitle = (value: string) => {
title.value = value;
@@ -20,10 +27,17 @@ export const usePageHeaderStore = defineStore("pageHeader", () => {
backRoute.value = value;
};
const setLive = (value: boolean, kind: LiveKind) => {
live.value = value;
liveKind.value = kind;
};
const clear = () => {
title.value = "";
backRoute.value = null;
live.value = null;
liveKind.value = null;
};
return { title, backRoute, setTitle, setBackRoute, clear };
return { title, backRoute, live, liveKind, setTitle, setBackRoute, setLive, clear };
});
-44
View File
@@ -1,44 +0,0 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { polylanSubmitterApiGetUserInfo } from '@/api'
interface UserInfo {
username: string
isAuthenticated: boolean
isStaff: boolean
}
export const useUserStore = defineStore('user', () => {
const userInfo = ref<UserInfo>({
username: '',
isAuthenticated: false,
isStaff: false,
})
const isLoading = ref(false)
const error = ref<string>('')
const loadUserData = async () => {
isLoading.value = true
try {
const response = await polylanSubmitterApiGetUserInfo()
if (response.data) {
const user = response.data
userInfo.value.isAuthenticated = user.is_authenticated || false
userInfo.value.username = user.username || ''
userInfo.value.isStaff = user.is_staff || false
}
} catch (err) {
error.value = 'Failed to fetch user info'
console.error('Error fetching user info:', err)
} finally {
isLoading.value = false
}
}
return {
userInfo,
isLoading,
error,
loadUserData,
}
})
+40
View File
@@ -1,6 +1,7 @@
from django.contrib import admin
from django.urls import reverse
from .models import Submission, SubmissionFile, ImageCrop, Scope
from .signals import broadcast_scope_updates
class ImageCropInline(admin.TabularInline):
@@ -77,6 +78,45 @@ class ScopeAdmin(admin.ModelAdmin):
},
)
# Players on a scope edited here get moved like with the AAndT sync (see
# broadcast_scope_updates): state before the save is kept on the instance,
# compared once the assigned users (m2m) are saved too in save_related.
def save_model(self, request, obj, form, change):
previous = Scope.objects.filter(pk=obj.pk).first() if change else None
obj._state_before_save = (
(
previous.is_active,
set(previous.assigned_users.values_list("id", flat=True)),
)
if previous
else (False, set())
)
super().save_model(request, obj, form, change)
def save_related(self, request, form, formsets, change):
super().save_related(request, form, formsets, change)
scope = form.instance
was_active, previous_user_ids = scope._state_before_save
user_ids = set(scope.assigned_users.values_list("id", flat=True))
if scope.is_active != was_active or user_ids != previous_user_ids:
broadcast_scope_updates({scope: user_ids | previous_user_ids})
def delete_model(self, request, obj):
self.delete_queryset(request, Scope.objects.filter(pk=obj.pk))
def delete_queryset(self, request, queryset):
changes = {
scope: {user.id for user in scope.assigned_users.all()}
for scope in queryset.prefetch_related("assigned_users")
}
for scope in changes:
scope.is_active = False
super().delete_queryset(request, queryset)
broadcast_scope_updates(changes)
@admin.register(Submission)
class SubmissionAdmin(admin.ModelAdmin):
+111 -13
View File
@@ -5,10 +5,25 @@ from ninja import Router, File, Form
from ninja.files import UploadedFile
from django.shortcuts import get_object_or_404
from games.models import Game
from games.models import EventGame, Game
from .models import Submission, SubmissionFile, ImageCrop, OCRStatus, Scope
from .schemas import SubmissionOut, ImageCropIn, ImageCropOut, ScopeOut
from .tasks import process_submission_file, process_crop
from .schemas import (
SubmissionOut,
ImageCropIn,
ImageCropOut,
ScopeOut,
SyncScopesIn,
SyncScopesOut,
SyncScopesStatusOut,
SyncScopesStopOut,
)
from .tasks import (
get_scope_sync_state,
process_submission_file,
process_crop,
schedule_scope_sync,
stop_scope_sync,
)
router = Router()
@@ -66,6 +81,81 @@ def list_available_scopes(request: HttpRequest, event_path: str, game_path: str)
return list(scopes.order_by("name"))
def _syncable_event_game(request: HttpRequest, game_path: str) -> EventGame:
return get_object_or_404(
EventGame,
event=request.event,
game__path=game_path,
game__custom_path=False,
enabled=True,
)
@router.get(
f"{PREFIX}/{{game_path}}/sync-scopes",
response={200: SyncScopesStatusOut, 403: dict},
)
def sync_scopes_status(request: HttpRequest, event_path: str, game_path: str):
"""State of the AAndT scope sync loop of a (non custom path) game,
superusers only."""
if not request.user.is_superuser:
return 403, {"detail": "Superuser required"}
event_game = _syncable_event_game(request, game_path)
scopes = Scope.objects.filter(event_game=event_game)
return {
**vars(get_scope_sync_state(event_game.id)),
"has_token": bool(event_game.apibot_token),
"scope_count": scopes.count(),
"active_scope_count": scopes.filter(is_active=True).count(),
}
@router.post(
f"{PREFIX}/{{game_path}}/sync-scopes",
response={200: SyncScopesOut, 400: dict, 403: dict},
)
def sync_scopes(
request: HttpRequest, event_path: str, game_path: str, payload: SyncScopesIn
):
"""Start the AAndT scope sync loop for a (non custom path) game, superusers
only. Stores `apibot_token` first when given; without one and none stored
yet, answers 400 with `token_required` so the frontend asks for it."""
if not request.user.is_superuser:
return 403, {"detail": "Superuser required"}
event_game = _syncable_event_game(request, game_path)
token = (payload.apibot_token or "").strip()
if token:
event_game.apibot_token = token
event_game.save(update_fields=["apibot_token"])
if not event_game.apibot_token:
return 400, {
"detail": "No AAndT apibot token configured",
"token_required": True,
}
return {"started": schedule_scope_sync(event_game.id)}
@router.delete(
f"{PREFIX}/{{game_path}}/sync-scopes",
response={200: SyncScopesStopOut, 403: dict},
)
def stop_sync_scopes(request: HttpRequest, event_path: str, game_path: str):
"""Stop the AAndT scope sync loop of a (non custom path) game, superusers
only. Cancels its scheduled job, scopes are left as they are."""
if not request.user.is_superuser:
return 403, {"detail": "Superuser required"}
event_game = _syncable_event_game(request, game_path)
return {"stopped": stop_scope_sync(event_game.id)}
@router.post(f"{PREFIX}/submission/create", response={200: SubmissionOut, 403: dict})
def create_submission(
request: HttpRequest,
@@ -112,13 +202,17 @@ def list_user_submissions(request: HttpRequest, event_path: str, scope_id: UUID)
if not request.user.is_authenticated:
return 403, {"detail": "Authentication required"}
submissions = Submission.for_event.filter(
scope_id=scope_id, user=request.user
).order_by("-created_at")
return submissions
submissions = Submission.for_event.filter(scope_id=scope_id)
# Admins see every player's submissions for the scope
if not request.user.is_staff:
submissions = submissions.filter(user=request.user)
return submissions.select_related("user").order_by("-created_at")
@router.get(f"{PREFIX}/submission/by/game", response=list[SubmissionOut])
@router.get(
f"{PREFIX}/submission/by/game", response={200: list[SubmissionOut], 403: dict}
)
def list_submissions_by_game(request: HttpRequest, event_path: str, game_path: str):
game = get_object_or_404(Game, path=game_path)
@@ -128,7 +222,9 @@ def list_submissions_by_game(request: HttpRequest, event_path: str, game_path: s
return Submission.for_event.filter(scope__event_game__game=game)
@router.get(f"{PREFIX}/submission/{{submission_id}}", response=SubmissionOut)
@router.get(
f"{PREFIX}/submission/{{submission_id}}", response={200: SubmissionOut, 403: dict}
)
def get_submission(request: HttpRequest, event_path: str, submission_id: UUID):
submission = get_object_or_404(Submission.for_event, id=submission_id)
@@ -138,7 +234,9 @@ def get_submission(request: HttpRequest, event_path: str, submission_id: UUID):
return submission
@router.post(f"{PREFIX}/crops/s/{{submission_file_id}}", response=ImageCropOut)
@router.post(
f"{PREFIX}/crops/s/{{submission_file_id}}", response={200: ImageCropOut, 403: dict}
)
def create_image_crop(
request: HttpRequest,
event_path: str,
@@ -165,7 +263,7 @@ def create_image_crop(
return crop
@router.delete(f"{PREFIX}/crops/{{crop_id}}", response=dict)
@router.delete(f"{PREFIX}/crops/{{crop_id}}", response={200: dict, 403: dict})
def delete_image_crop(request: HttpRequest, event_path: str, crop_id: UUID):
if not request.user.is_staff:
return 403, {"detail": "Admin access required"}
@@ -178,7 +276,7 @@ def delete_image_crop(request: HttpRequest, event_path: str, crop_id: UUID):
return {"status": "deleted"}
@router.post(f"{PREFIX}/files/{{file_id}}/process-ocr", response=dict)
@router.post(f"{PREFIX}/files/{{file_id}}/process-ocr", response={200: dict, 403: dict})
def process_file_ocr(request: HttpRequest, event_path: str, file_id: UUID):
if not request.user.is_staff:
return 403, {"detail": "Admin access required"}
@@ -195,7 +293,7 @@ def process_file_ocr(request: HttpRequest, event_path: str, file_id: UUID):
return {"status": "queued"}
@router.post(f"{PREFIX}/crops/{{crop_id}}/process-ocr", response=dict)
@router.post(f"{PREFIX}/crops/{{crop_id}}/process-ocr", response={200: dict, 403: dict})
def process_crop_ocr(request: HttpRequest, event_path: str, crop_id: UUID):
if not request.user.is_staff:
return 403, {"detail": "Admin access required"}
+17 -3
View File
@@ -2,6 +2,8 @@ import json
from channels.generic.websocket import AsyncWebsocketConsumer
from django.contrib.auth.models import AnonymousUser
from submissions.signals import STAFF_GROUP_NAME
class SubmissionsConsumer(AsyncWebsocketConsumer):
async def connect(self):
@@ -11,12 +13,18 @@ class SubmissionsConsumer(AsyncWebsocketConsumer):
await self.close()
return
self.user_group_name = f"submissions_user_{self.user.id}"
await self.channel_layer.group_add(self.user_group_name, self.channel_name)
self.group_names = [f"submissions_user_{self.user.id}"]
if self.user.is_staff:
self.group_names.append(STAFF_GROUP_NAME)
for group_name in self.group_names:
await self.channel_layer.group_add(group_name, self.channel_name)
await self.accept()
async def disconnect(self, close_code):
await self.channel_layer.group_discard(self.user_group_name, self.channel_name)
# closed before joining (anonymous)
for group_name in getattr(self, "group_names", []):
await self.channel_layer.group_discard(group_name, self.channel_name)
async def submission_updated(self, event):
submission_data = event["submission"]
@@ -29,3 +37,9 @@ class SubmissionsConsumer(AsyncWebsocketConsumer):
async def submission_crop_updated(self, event):
crop_data = event["crop"]
await self.send(text_data=json.dumps(crop_data))
async def submission_crop_deleted(self, event):
await self.send(text_data=json.dumps({"deleted_crop": event["crop"]}))
async def scope_updated(self, event):
await self.send(text_data=json.dumps({"scope": event["scope"]}))
@@ -1,7 +1,7 @@
from django.core.management.base import BaseCommand, CommandError
from games.models import EventGame
from submissions.tasks import sync_all_event_games_task, sync_event_game_scopes_task
from submissions.tasks import schedule_scope_sync, sync_all_event_games_task
class Command(BaseCommand):
@@ -25,9 +25,15 @@ class Command(BaseCommand):
if not EventGame.objects.filter(id=event_game_id).exists():
raise CommandError(f"No EventGame with id={event_game_id}")
sync_event_game_scopes_task.enqueue(event_game_id)
if schedule_scope_sync(event_game_id):
self.stdout.write(
self.style.SUCCESS(f"Queued sync for EventGame {event_game_id}")
self.style.SUCCESS(f"Started sync for EventGame {event_game_id}")
)
else:
self.stdout.write(
self.style.WARNING(
f"Sync already running for EventGame {event_game_id}"
)
)
return
@@ -0,0 +1,58 @@
from django.db import migrations
# Before the submissions -> opus_magnum rename, this app owned the opus magnum
# tables and its 0001_initial was already applied. The new 0001_initial has the
# same name, so on those databases Django skipped it and kept the legacy
# submissions_submission / submissions_submissionfile layout (is_validated NOT
# NULL, response_id, ...) and never created submissions_imagecrop.
LEGACY_TABLES = [
"submissions_imagecrop",
"submissions_submissionfile",
"submissions_puzzleresponse",
"submissions_submission",
"submissions_steamcollectionitem",
"submissions_steamcollection",
"submissions_steamapikey",
]
def repair_legacy_tables(apps, schema_editor):
connection = schema_editor.connection
with connection.cursor() as cursor:
columns = {
col.name
for col in connection.introspection.get_table_description(
cursor, "submissions_submission"
)
}
if "is_validated" not in columns:
return
# Data was copied to opus_magnum (0015) and 0007 wiped submissions, so
# this should be empty: refuse to drop anything otherwise.
cursor.execute("SELECT COUNT(*) FROM submissions_submission")
if cursor.fetchone()[0]:
raise RuntimeError(
"submissions_submission has the legacy layout but is not empty"
)
existing_tables = set(connection.introspection.table_names())
for table in LEGACY_TABLES:
if table in existing_tables:
schema_editor.execute(f"DROP TABLE {schema_editor.quote_name(table)}")
for model_name in ["Submission", "SubmissionFile", "ImageCrop"]:
schema_editor.create_model(apps.get_model("submissions", model_name))
class Migration(migrations.Migration):
dependencies = [
("submissions", "0008_remove_submission_game"),
]
operations = [
migrations.RunPython(repair_legacy_tables, migrations.RunPython.noop),
]
+33
View File
@@ -10,6 +10,33 @@ class ScopeOut(Schema):
created_at: datetime
class SyncScopesIn(Schema):
apibot_token: str | None = None
class SyncScopesOut(Schema):
# False when a sync loop was already running for this game
started: bool
class SyncScopesStopOut(Schema):
# False when no sync loop was running
stopped: bool
class SyncScopesStatusOut(Schema):
running: bool
has_token: bool
# Last AAndT status seen (e.g. "7inprog"), see games' AAndT status values
aandt_status: str | None = None
last_run_at: datetime | None = None
next_run_at: datetime | None = None
# Last run's error, if it failed
error: str | None = None
scope_count: int
active_scope_count: int
class ImageCropIn(Schema):
x1: int
y1: int
@@ -20,6 +47,7 @@ class ImageCropIn(Schema):
class ImageCropOut(Schema):
id: UUID
submission_file_id: UUID
x1: int
y1: int
x2: int
@@ -44,7 +72,12 @@ class SubmissionFileOut(Schema):
class SubmissionOut(Schema):
id: UUID
scope_id: UUID
username: str | None = None
notes: str | None = None
files: list[SubmissionFileOut] = []
created_at: datetime
updated_at: datetime
@staticmethod
def resolve_username(obj) -> str | None:
return obj.user.username if obj.user else None
@@ -12,6 +12,7 @@ from accounts.models import CustomUser
from games.models import EventGame
from ..models import Scope
from ..signals import broadcast_scope_updates
from .aandt_client import AuthenticatedClient
from .aandt_client.api.default import (
aandt_api_infos,
@@ -120,6 +121,9 @@ def sync_event_game_scopes(event_game: EventGame, /) -> ScopeSyncResult:
Scopes whose match is no longer returned by the API (deleted, or from a
previous AAndT run reusing the same token) are deactivated.
Users of scopes that opened/closed or got their players changed are
notified over the submissions websocket (see `broadcast_scope_updates`).
Args:
event_game: The EventGame to sync; must have `apibot_token` set.
@@ -173,10 +177,11 @@ def sync_event_game_scopes(event_game: EventGame, /) -> ScopeSyncResult:
result = ScopeSyncResult(status=status.value if status is not None else None)
now = timezone.now()
synced_match_ids: set[int] = set()
changes: dict[Scope, set[int]] = {}
for match in matches:
match_id = _unwrap(match.id)
created, warnings = _sync_match(
created, warnings, change = _sync_match(
event_game, client, match, userids_by_member_id, now
)
if created is None:
@@ -185,14 +190,22 @@ def sync_event_game_scopes(event_game: EventGame, /) -> ScopeSyncResult:
result.created += created
result.updated += not created
result.warnings.extend(warnings)
if change is not None:
changes[change[0]] = change[1]
(
gone = list(
Scope.objects.filter(
event_game=event_game, is_active=True, external_id__isnull=False
)
.exclude(external_id__in=synced_match_ids)
.update(is_active=False)
.prefetch_related("assigned_users")
)
Scope.objects.filter(id__in=[scope.id for scope in gone]).update(is_active=False)
for scope in gone:
scope.is_active = False
changes[scope] = {user.id for user in scope.assigned_users.all()}
broadcast_scope_updates(changes)
return result
@@ -203,10 +216,17 @@ def _sync_match(
match: Match,
userids_by_member_id: dict[int, set[int]],
now: datetime,
) -> tuple[bool | None, list[str]]:
) -> tuple[bool | None, list[str], tuple[Scope, set[int]] | None]:
"""Upsert the Scope of one match.
Returns:
Whether the Scope was created (None when the match has no id), the
warnings, and when it opened/closed or its players changed, the Scope
with every user id that was or now is assigned to it.
"""
match_id = _unwrap(match.id)
if match_id is None:
return None, []
return None, [], None
warnings: list[str] = []
@@ -218,6 +238,12 @@ def _sync_match(
users = list(CustomUser.objects.filter(cas_user_id__in=userids))
previous = Scope.objects.filter(event_game=event_game, external_id=match_id).first()
was_active = previous.is_active if previous else False
previous_user_ids = (
set(previous.assigned_users.values_list("id", flat=True)) if previous else set()
)
scope, created = Scope.objects.update_or_create(
event_game=event_game,
external_id=match_id,
@@ -241,7 +267,12 @@ def _sync_match(
if scope.is_active:
warnings.extend(_push_submission_link(client, match_id, scope))
return created, warnings
user_ids = {user.id for user in users}
change = None
if scope.is_active != was_active or user_ids != previous_user_ids:
change = (scope, user_ids | previous_user_ids)
return created, warnings, change
def _push_submission_link(
+70 -31
View File
@@ -1,63 +1,102 @@
from django.db.models.signals import post_save
from django.db import transaction
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from submissions.models import Submission, SubmissionFile, ImageCrop
from submissions.models import Submission, SubmissionFile, ImageCrop, Scope
from submissions.schemas import SubmissionOut, SubmissionFileOut, ImageCropOut
# Staff see (and OCR/crop) every player's submissions, so they get every update
STAFF_GROUP_NAME = "submissions_staff"
def _broadcast_submission_event(submission: Submission, message: dict):
channel_layer = get_channel_layer()
groups = [STAFF_GROUP_NAME]
if submission.user_id:
groups.append(f"submissions_user_{submission.user_id}")
for group_name in groups:
async_to_sync(channel_layer.group_send)(group_name, message)
@receiver(post_save, sender=Submission)
def broadcast_submission_update(sender, instance, created, **kwargs):
if not instance.user:
return
user_group_name = f"submissions_user_{instance.user.id}"
submission_data = SubmissionOut.from_orm(instance).dict()
async_to_sync(channel_layer.group_send)(
user_group_name,
_broadcast_submission_event(
instance,
{
"type": "submission.updated",
"submission": submission_data,
"submission": SubmissionOut.from_orm(instance).dict(),
},
)
@receiver(post_save, sender=SubmissionFile)
def broadcast_submission_file_update(sender, instance, created, **kwargs):
submission = instance.submission
if not submission.user:
return
user_group_name = f"submissions_user_{submission.user.id}"
file_data = SubmissionFileOut.from_orm(instance).dict()
async_to_sync(channel_layer.group_send)(
user_group_name,
_broadcast_submission_event(
instance.submission,
{
"type": "submission.file.updated",
"file": file_data,
"file": SubmissionFileOut.from_orm(instance).dict(),
},
)
@receiver(post_save, sender=ImageCrop)
def broadcast_image_crop_update(sender, instance, created, **kwargs):
submission = instance.submission_file.submission
if not submission.user:
return
user_group_name = f"submissions_user_{submission.user.id}"
crop_data = ImageCropOut.from_orm(instance).dict()
async_to_sync(channel_layer.group_send)(
user_group_name,
_broadcast_submission_event(
instance.submission_file.submission,
{
"type": "submission.crop.updated",
"crop": crop_data,
"crop": ImageCropOut.from_orm(instance).dict(),
},
)
@receiver(post_delete, sender=ImageCrop)
def broadcast_image_crop_delete(sender, instance, **kwargs):
_broadcast_submission_event(
instance.submission_file.submission,
{
"type": "submission.crop.deleted",
"crop": {
"id": str(instance.id),
"submission_file_id": str(instance.submission_file_id),
},
},
)
def broadcast_scope_updates(changes: dict[Scope, set[int]], /):
"""Tell users their scope changed (closed/opened, (un)assigned), once the
current transaction commits, so the frontend can move them to the right
match without a refresh.
Args:
changes: Changed scopes, each with every user id that was or now is
assigned to it.
"""
def send():
channel_layer = get_channel_layer()
for scope, user_ids in changes.items():
assigned_ids = set(scope.assigned_users.values_list("id", flat=True))
for user_id in user_ids:
async_to_sync(channel_layer.group_send)(
f"submissions_user_{user_id}",
{
"type": "scope.updated",
"scope": {
"id": str(scope.id),
"is_active": scope.is_active,
"assigned": user_id in assigned_ids,
},
},
)
if changes:
# robust: a websocket hiccup only gets logged, it mustn't fail the
# (already committed) sync or admin save
transaction.on_commit(send, robust=True)
+177 -17
View File
@@ -1,5 +1,10 @@
from datetime import timedelta
import logging
from dataclasses import dataclass
from datetime import datetime, timedelta
from uuid import uuid4
import django_rq
from django.core.cache import cache
from django.tasks import task
from django.utils import timezone
from games.models import EventGame
@@ -11,9 +16,117 @@ from submissions.services.aandt_sync import (
from PIL import Image
import pytesseract
from rq.exceptions import InvalidJobOperation, NoSuchJobError
from rq.job import Job, JobStatus
# How often to repoll an EventGame's AAndT while it's still "in progress".
logger = logging.getLogger(__name__)
# How often to repoll an EventGame's AAndT while it's "in progress", and while
# it isn't yet (registrations, preparation, ...) or the run failed.
SCOPE_SYNC_REPOLL_INTERVAL = timedelta(seconds=15)
SCOPE_SYNC_IDLE_INTERVAL = timedelta(minutes=1)
# AAndT statuses after which there's nothing left to sync, the loop stops.
AANDT_FINISHED_STATUSES = {"9done", "11reviewed"}
def _scope_sync_guard_key(event_game_id: int) -> str:
return f"submissions:scope_sync:{event_game_id}"
def _scope_sync_job_key(event_game_id: int) -> str:
return f"submissions:scope_sync:{event_game_id}:job"
def _scope_sync_state_key(event_game_id: int) -> str:
return f"submissions:scope_sync:{event_game_id}:state"
def _scope_sync_guard_timeout() -> int:
return int(SCOPE_SYNC_IDLE_INTERVAL.total_seconds() * 3)
# Last run's outcome, shown to admins in the sync modal. Kept around a while
# after the loop stops, so they still see why it stopped.
SCOPE_SYNC_STATE_TIMEOUT = int(timedelta(days=1).total_seconds())
@dataclass
class ScopeSyncState:
running: bool
aandt_status: str | None = None
last_run_at: datetime | None = None
next_run_at: datetime | None = None
error: str | None = None
def get_scope_sync_state(event_game_id: int, /) -> ScopeSyncState:
state = cache.get(_scope_sync_state_key(event_game_id)) or {}
running = cache.get(_scope_sync_guard_key(event_game_id)) is not None
return ScopeSyncState(
running=running,
aandt_status=state.get("aandt_status"),
last_run_at=state.get("last_run_at"),
next_run_at=state.get("next_run_at") if running else None,
error=state.get("error"),
)
def _enqueue_scope_sync(event_game_id: int, loop_id: str, run_after: datetime | None):
task = (
sync_event_game_scopes_task.using(run_after=run_after)
if run_after
else sync_event_game_scopes_task
)
result = task.enqueue(event_game_id, loop_id=loop_id)
# Same id as the rq job (see django_tasks_rq), so stop_scope_sync can cancel it
cache.set(
_scope_sync_job_key(event_game_id),
result.id,
timeout=_scope_sync_guard_timeout(),
)
def schedule_scope_sync(event_game_id: int, /) -> bool:
"""Start the sync loop of an EventGame, unless one is already running.
Safe to call any number of times (admin button spam, multiple workers...).
The loop holds a per-EventGame guard with its id (same idea as
games.tasks.schedule_steam_refresh), so if the guard expires while an old
loop is just late, the old one stops at its next run."""
loop_id = uuid4().hex
if not cache.add(
_scope_sync_guard_key(event_game_id),
loop_id,
timeout=_scope_sync_guard_timeout(),
):
return False
_enqueue_scope_sync(event_game_id, loop_id, run_after=None)
return True
def stop_scope_sync(event_game_id: int, /) -> bool:
"""Stop the sync loop of an EventGame: cancels its scheduled rq job and
releases the guard (a run already in progress won't reschedule itself).
Returns:
Whether a loop was running.
"""
running = cache.get(_scope_sync_guard_key(event_game_id)) is not None
job_id = cache.get(_scope_sync_job_key(event_game_id))
cache.delete_many(
[_scope_sync_guard_key(event_game_id), _scope_sync_job_key(event_game_id)]
)
if job_id:
try:
job = Job.fetch(job_id, connection=django_rq.get_connection())
if job.get_status() in (JobStatus.SCHEDULED, JobStatus.QUEUED):
job.cancel()
except (NoSuchJobError, InvalidJobOperation):
pass
return running
def _process_ocr_file(obj, file, crop: ImageCrop | None = None) -> bool:
@@ -90,26 +203,73 @@ def sync_all_event_games_task():
)
for event_game in event_games:
sync_event_game_scopes_task.enqueue(event_game.id)
schedule_scope_sync(event_game.id)
@task
def sync_event_game_scopes_task(event_game_id: int):
"""Sync an EventGame's Scopes, repolling every minute while matches are in progress.
def sync_event_game_scopes_task(event_game_id: int, loop_id: str | None = None):
"""Sync an EventGame's Scopes, then re-enqueue itself until the AAndT is done.
Each run re-checks the AAndT's status (from the `/` endpoint). While it's
still "in progress" (`7inprog`), the task re-enqueues itself with a delay
instead of relying on an external scheduler; once the status moves on, it
simply doesn't reschedule and the loop stops.
Started once (see schedule_scope_sync), it keeps going on its own without
an external scheduler: every SCOPE_SYNC_REPOLL_INTERVAL while the AAndT is
"in progress" (`7inprog`), every SCOPE_SYNC_IDLE_INTERVAL before that or
when the run failed. Stops once the AAndT is done/reviewed, when the
EventGame (or its token) is gone, or when another loop took the guard.
Without loop_id it's a one-off run that leaves the loop alone.
"""
event_game = EventGame.objects.filter(id=event_game_id).first()
if not event_game:
guard_key = _scope_sync_guard_key(event_game_id)
if loop_id is not None and cache.get(guard_key) != loop_id:
# Another loop owns the guard (or it expired/was stopped), stop this one
return
result = sync_event_game_scopes(event_game)
event_game = EventGame.objects.filter(id=event_game_id).first()
if result.status == AANDT_STATUS_IN_PROGRESS:
sync_event_game_scopes_task.using(
run_after=timezone.now() + SCOPE_SYNC_REPOLL_INTERVAL
).enqueue(event_game_id)
if not event_game or not event_game.apibot_token:
if loop_id is not None:
cache.delete(guard_key)
return
status = None
error = None
try:
status = sync_event_game_scopes(event_game).status
except Exception as exc:
if loop_id is None:
raise
# Retry later rather than letting the loop die (AAndT site down, bug, ...),
# it'd otherwise only restart once the guard expires and someone restarts it
logger.exception("Scope sync failed for EventGame %s", event_game_id)
error = str(exc) or exc.__class__.__name__
if loop_id is None:
return
now = timezone.now()
next_run_at = None
# Re-checked: the loop may have been stopped while this run was syncing
if status not in AANDT_FINISHED_STATUSES and cache.get(guard_key) == loop_id:
next_run_at = now + (
SCOPE_SYNC_REPOLL_INTERVAL
if status == AANDT_STATUS_IN_PROGRESS
else SCOPE_SYNC_IDLE_INTERVAL
)
cache.set(
_scope_sync_state_key(event_game_id),
{
"aandt_status": status,
"last_run_at": now,
"next_run_at": next_run_at,
"error": error,
},
timeout=SCOPE_SYNC_STATE_TIMEOUT,
)
if next_run_at is None:
if cache.get(guard_key) == loop_id:
cache.delete(guard_key)
return
cache.set(guard_key, loop_id, timeout=_scope_sync_guard_timeout())
_enqueue_scope_sync(event_game_id, loop_id, run_after=next_run_at)
+488 -1
View File
@@ -1 +1,488 @@
# Create your tests here.
from contextlib import ExitStack
from unittest import mock
from django.core.cache import cache
from django.test import TestCase
from rq.job import JobStatus
from accounts.models import CustomUser
from events.models import Event
from games.models import EventGame, Game
from . import tasks
from .models import ImageCrop, Scope, Submission, SubmissionFile
from .services.aandt_client.models import (
AandtApiInfosResponse200,
AandtApiMatchesResponse200,
AandtApiMembersResponse200,
)
from .services.aandt_sync import ScopeSyncError, ScopeSyncResult, sync_event_game_scopes
class SyncScopesApiTests(TestCase):
def setUp(self):
self.event = Event.objects.create(name="Event", path="event")
self.game = Game.objects.create(name="Game", path="game")
self.event_game = EventGame.objects.create(event=self.event, game=self.game)
self.url = (
f"/api/events/{self.event.path}/submissions/{self.game.path}/sync-scopes"
)
self.superuser = CustomUser.objects.create_user(
username="admin", password="x", is_staff=True, is_superuser=True
)
patcher = mock.patch("submissions.api.schedule_scope_sync", return_value=True)
self.schedule = patcher.start()
self.addCleanup(patcher.stop)
def _post(self, body=None):
return self.client.post(self.url, body or {}, content_type="application/json")
def test_staff_is_forbidden(self):
staff = CustomUser.objects.create_user(
username="staff", password="x", is_staff=True
)
self.client.force_login(staff)
self.assertEqual(self._post().status_code, 403)
self.schedule.assert_not_called()
def test_asks_for_token_when_missing(self):
self.client.force_login(self.superuser)
response = self._post()
self.assertEqual(response.status_code, 400)
self.assertTrue(response.json()["token_required"])
self.schedule.assert_not_called()
def test_stores_token_and_starts_sync(self):
self.client.force_login(self.superuser)
response = self._post({"apibot_token": " abc "})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {"started": True})
self.event_game.refresh_from_db()
self.assertEqual(self.event_game.apibot_token, "abc")
self.schedule.assert_called_once_with(self.event_game.id)
def test_status(self):
Scope.objects.create(event_game=self.event_game, name="M1")
Scope.objects.create(event_game=self.event_game, name="M2", is_active=False)
self.client.force_login(self.superuser)
with mock.patch(
"submissions.api.get_scope_sync_state",
return_value=tasks.ScopeSyncState(running=True, aandt_status="7inprog"),
):
response = self.client.get(self.url)
self.assertEqual(response.status_code, 200)
data = response.json()
self.assertTrue(data["running"])
self.assertFalse(data["has_token"])
self.assertEqual(data["aandt_status"], "7inprog")
self.assertEqual((data["active_scope_count"], data["scope_count"]), (1, 2))
def test_stop(self):
self.client.force_login(self.superuser)
with mock.patch("submissions.api.stop_scope_sync", return_value=True) as stop:
response = self.client.delete(self.url)
self.assertEqual(response.json(), {"stopped": True})
stop.assert_called_once_with(self.event_game.id)
def test_status_and_stop_forbidden_for_staff(self):
staff = CustomUser.objects.create_user(
username="staff", password="x", is_staff=True
)
self.client.force_login(staff)
self.assertEqual(self.client.get(self.url).status_code, 403)
self.assertEqual(self.client.delete(self.url).status_code, 403)
def test_custom_path_game_is_404(self):
self.game.custom_path = True
self.game.save()
self.client.force_login(self.superuser)
self.assertEqual(self._post({"apibot_token": "abc"}).status_code, 404)
class SyncEventGameScopesTaskTests(TestCase):
def setUp(self):
event = Event.objects.create(name="Event", path="event")
game = Game.objects.create(name="Game", path="game")
self.event_game = EventGame.objects.create(
event=event, game=game, apibot_token="abc"
)
self.guard_key = tasks._scope_sync_guard_key(self.event_game.id)
self.loop_id = "loop"
self.job_key = tasks._scope_sync_job_key(self.event_game.id)
self.state_key = tasks._scope_sync_state_key(self.event_game.id)
cache.set(self.guard_key, self.loop_id)
self.addCleanup(
cache.delete_many, [self.guard_key, self.job_key, self.state_key]
)
@staticmethod
def _task_mock(task):
# enqueue() returns a TaskResult, whose id ends up in the cache
task.enqueue.return_value.id = "job-1"
task.using.return_value.enqueue.return_value.id = "job-2"
return task
def _run(self, status=None, exc=None, during_sync=None):
run = tasks.sync_event_game_scopes_task.func
def sync_side_effect(_event_game):
if during_sync:
during_sync()
if exc:
raise exc
return ScopeSyncResult(status=status)
with (
mock.patch.object(
tasks, "sync_event_game_scopes", side_effect=sync_side_effect
) as sync,
mock.patch.object(tasks, "sync_event_game_scopes_task") as task,
mock.patch.object(tasks, "logger"),
):
self._task_mock(task)
run(self.event_game.id, loop_id=self.loop_id)
return sync, task
def test_schedule_starts_only_one_loop(self):
cache.delete(self.guard_key)
with mock.patch.object(tasks, "sync_event_game_scopes_task") as task:
self._task_mock(task)
self.assertTrue(tasks.schedule_scope_sync(self.event_game.id))
self.assertFalse(tasks.schedule_scope_sync(self.event_game.id))
task.enqueue.assert_called_once()
def test_reschedules_before_and_during_aandt(self):
for status in ["3insc", "7inprog"]:
with self.subTest(status=status):
_, task = self._run(status=status)
task.using.assert_called_once()
def test_reschedules_after_api_failure(self):
_, task = self._run(exc=ScopeSyncError("down"))
task.using.assert_called_once()
def test_reschedules_after_unexpected_error(self):
_, task = self._run(exc=RuntimeError("boom"))
task.using.assert_called_once()
state = tasks.get_scope_sync_state(self.event_game.id)
self.assertEqual(state.error, "boom")
self.assertTrue(state.running)
def test_records_job_and_state(self):
self._run(status="7inprog")
self.assertEqual(cache.get(self.job_key), "job-2")
state = tasks.get_scope_sync_state(self.event_game.id)
self.assertEqual(state.aandt_status, "7inprog")
self.assertIsNotNone(state.next_run_at)
def test_stop_cancels_scheduled_job(self):
cache.set(self.job_key, "job-1")
job = mock.Mock(get_status=mock.Mock(return_value=JobStatus.SCHEDULED))
with (
mock.patch.object(tasks.Job, "fetch", return_value=job) as fetch,
mock.patch.object(tasks.django_rq, "get_connection"),
):
self.assertTrue(tasks.stop_scope_sync(self.event_game.id))
fetch.assert_called_once_with("job-1", connection=mock.ANY)
job.cancel.assert_called_once()
self.assertIsNone(cache.get(self.guard_key))
self.assertFalse(tasks.stop_scope_sync(self.event_game.id))
def test_stop_during_run_does_not_reschedule(self):
_, task = self._run(
status="7inprog", during_sync=lambda: cache.delete(self.guard_key)
)
task.using.assert_not_called()
self.assertIsNone(cache.get(self.guard_key))
def test_stops_once_aandt_is_done(self):
_, task = self._run(status="9done")
task.using.assert_not_called()
self.assertIsNone(cache.get(self.guard_key))
def test_stale_loop_stops(self):
cache.set(self.guard_key, "another-loop")
sync, task = self._run(status="7inprog")
sync.assert_not_called()
task.using.assert_not_called()
class SyncScopeBroadcastTests(TestCase):
def setUp(self):
event = Event.objects.create(name="Event", path="event")
game = Game.objects.create(name="Game", path="game")
self.event_game = EventGame.objects.create(
event=event, game=game, apibot_token="abc"
)
self.player = CustomUser.objects.create_user(
username="player", password="x", cas_user_id="42"
)
def _sync(self, matches):
api = "submissions.services.aandt_sync"
responses = {
"aandt_api_infos": AandtApiInfosResponse200.from_dict(
{"aandt": {"status": "7inprog"}}
),
"aandt_api_members": AandtApiMembersResponse200.from_dict(
{"members": [{"id": 1, "user": {"id": 42}}]}
),
"aandt_api_matches": AandtApiMatchesResponse200.from_dict(
{"matches": matches}
),
}
with ExitStack() as stack:
for module, parsed in responses.items():
stack.enter_context(
mock.patch(
f"{api}.{module}.sync_detailed",
return_value=mock.Mock(parsed=parsed),
)
)
stack.enter_context(
mock.patch(f"{api}._push_submission_link", return_value=[])
)
stack.enter_context(mock.patch("submissions.signals.get_channel_layer"))
send = stack.enter_context(mock.patch("submissions.signals.async_to_sync"))
with self.captureOnCommitCallbacks(execute=True):
sync_event_game_scopes(self.event_game)
return [c.args[1]["scope"] for c in send.return_value.call_args_list]
@staticmethod
def _match(match_id, status):
return {
"id": match_id,
"title": f"M{match_id}",
"status": status,
"players": {"1": 0},
}
def test_match_done_and_next_one_playing_notifies_player(self):
self._sync([self._match(1, "playing"), self._match(2, "waitPlayer")])
sent = self._sync([self._match(1, "done"), self._match(2, "playing")])
by_external_id = {
Scope.objects.get(id=scope["id"]).external_id: scope for scope in sent
}
self.assertFalse(by_external_id[1]["is_active"])
self.assertTrue(by_external_id[2]["is_active"])
self.assertTrue(by_external_id[2]["assigned"])
def test_unchanged_scopes_send_nothing(self):
self._sync([self._match(1, "playing")])
self.assertEqual(self._sync([self._match(1, "playing")]), [])
def test_removed_match_is_closed_and_notified(self):
self._sync([self._match(1, "playing")])
sent = self._sync([])
self.assertEqual(len(sent), 1)
self.assertFalse(sent[0]["is_active"])
class ScopeAdminBroadcastTests(TestCase):
def setUp(self):
event = Event.objects.create(name="Event", path="event")
game = Game.objects.create(name="Game", path="game")
event_game = EventGame.objects.create(event=event, game=game)
self.player = CustomUser.objects.create_user(username="player", password="x")
self.scope = Scope.objects.create(event_game=event_game, name="Match 1")
self.scope.assigned_users.set([self.player])
self.client.force_login(
CustomUser.objects.create_user(
username="admin", password="x", is_staff=True, is_superuser=True
)
)
self.form = {
"event_game": event_game.id,
"name": "Match 1",
"assigned_users": [self.player.id],
"is_active": "on",
}
def _sent(self, request):
with (
mock.patch("submissions.signals.get_channel_layer"),
mock.patch("submissions.signals.async_to_sync") as send,
self.captureOnCommitCallbacks(execute=True),
):
response = request()
self.assertEqual(response.status_code, 302)
return [c.args[1]["scope"] for c in send.return_value.call_args_list]
def _change(self, **changes):
url = f"/admin/submissions/scope/{self.scope.id}/change/"
data = {k: v for k, v in {**self.form, **changes}.items() if v is not None}
return self._sent(lambda: self.client.post(url, data))
def test_closing_scope_notifies_player(self):
sent = self._change(is_active=None)
self.assertEqual(
sent, [{"id": str(self.scope.id), "is_active": False, "assigned": True}]
)
def test_unassigning_player_notifies_them(self):
sent = self._change(assigned_users=[])
self.assertEqual(
sent, [{"id": str(self.scope.id), "is_active": True, "assigned": False}]
)
def test_unchanged_save_sends_nothing(self):
self.assertEqual(self._change(name="Renamed"), [])
def test_delete_notifies_player(self):
url = f"/admin/submissions/scope/{self.scope.id}/delete/"
sent = self._sent(lambda: self.client.post(url, {"post": "yes"}))
self.assertEqual(
sent, [{"id": str(self.scope.id), "is_active": False, "assigned": False}]
)
class SubmissionHomeViewTests(TestCase):
def setUp(self):
self.event = Event.objects.create(name="Event", path="event")
self.client.force_login(
CustomUser.objects.create_user(username="player", password="x")
)
def test_any_game_path_serves_the_app(self):
# Unknown game / no scope: the frontend shows its own not-found state
response = self.client.get(f"/{self.event.path}/submissions/unknown-game")
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "app.html")
def test_unknown_event_is_404(self):
response = self.client.get("/nope/submissions/unknown-game")
self.assertEqual(response.status_code, 404)
class ListUserSubmissionsApiTests(TestCase):
def setUp(self):
self.event = Event.objects.create(name="Event", path="event")
game = Game.objects.create(name="Game", path="game")
event_game = EventGame.objects.create(event=self.event, game=game)
self.scope = Scope.objects.create(event_game=event_game, name="M1")
other_scope = Scope.objects.create(event_game=event_game, name="M2")
self.player = CustomUser.objects.create_user(username="player", password="x")
other = CustomUser.objects.create_user(username="other", password="x")
self.mine = Submission.objects.create(
event=self.event, scope=self.scope, user=self.player
)
self.theirs = Submission.objects.create(
event=self.event, scope=self.scope, user=other
)
Submission.objects.create(event=self.event, scope=other_scope, user=other)
self.url = f"/api/events/{self.event.path}/submissions/submission/by/user"
def _list(self):
response = self.client.get(self.url, {"scope_id": self.scope.id})
self.assertEqual(response.status_code, 200)
return response.json()
def test_player_sees_only_own_submissions(self):
self.client.force_login(self.player)
data = self._list()
self.assertEqual([s["id"] for s in data], [str(self.mine.id)])
self.assertEqual(data[0]["username"], "player")
def test_staff_sees_all_submissions_of_scope(self):
staff = CustomUser.objects.create_user(
username="staff", password="x", is_staff=True
)
self.client.force_login(staff)
data = self._list()
self.assertEqual(
{s["id"] for s in data}, {str(self.mine.id), str(self.theirs.id)}
)
class SubmissionBroadcastTests(TestCase):
def setUp(self):
event = Event.objects.create(name="Event", path="event")
game = Game.objects.create(name="Game", path="game")
event_game = EventGame.objects.create(event=event, game=game)
scope = Scope.objects.create(event_game=event_game, name="M1")
self.player = CustomUser.objects.create_user(username="player", password="x")
submission = Submission.objects.create(
event=event, scope=scope, user=self.player
)
# bulk_create: skips the file broadcast, which would sign an S3 url
[submission_file] = SubmissionFile.objects.bulk_create(
[
SubmissionFile(
submission=submission,
file="shot.png",
original_filename="shot.png",
file_size=1,
content_type="image/png",
)
]
)
self.crop = ImageCrop.objects.create(
submission_file=submission_file, x1=0, y1=0, x2=1, y2=1
)
def test_crop_update_reaches_owner_and_staff(self):
with mock.patch("submissions.signals.get_channel_layer") as get_layer:
get_layer.return_value.group_send = mock.AsyncMock()
self.crop.save()
groups = [c.args[0] for c in get_layer.return_value.group_send.call_args_list]
self.assertEqual(
groups, ["submissions_staff", f"submissions_user_{self.player.id}"]
)
def test_crop_delete_reaches_owner_and_staff(self):
crop_id = str(self.crop.id)
with mock.patch("submissions.signals.get_channel_layer") as get_layer:
get_layer.return_value.group_send = mock.AsyncMock()
self.crop.delete()
calls = get_layer.return_value.group_send.call_args_list
self.assertEqual(
[c.args[0] for c in calls],
["submissions_staff", f"submissions_user_{self.player.id}"],
)
self.assertEqual(calls[0].args[1]["type"], "submission.crop.deleted")
self.assertEqual(calls[0].args[1]["crop"]["id"], crop_id)
+4 -31
View File
@@ -1,44 +1,17 @@
from uuid import UUID
from django.http import HttpRequest, Http404
from django.shortcuts import redirect, render, get_object_or_404
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from events.models import Event
from games.models import Game
from .models import Scope
@login_required
def submission_home(request: HttpRequest, event_path: str, game_path: str):
event = get_object_or_404(Event, path=event_path)
game = get_object_or_404(Game, path=game_path)
scopes = (
Scope.objects.filter(
event_game__event=event,
event_game__game=game,
is_active=True,
)
if request.user.is_superuser
else Scope.objects.filter(
event_game__event=event,
event_game__game=game,
assigned_users=request.user,
is_active=True,
)
)
if scopes.count() == 1:
return redirect(
"submissions.view",
event_path=event.path,
game_path=game.path,
scope_id=scopes[0].id,
)
if not scopes:
raise Http404
# Unknown game, no scope assigned, auto-entering the only scope: all
# handled by the frontend (SubmissionsSelect.vue)
get_object_or_404(Event, path=event_path)
return render(request, "app.html")

Some files were not shown because too many files have changed in this diff Show More