Files
optimxandCursor dd281e1bd0 Initial commit: SSS 50-week LAN check-in app.
Ship the Synology/Mac deployable player with curriculum mapping, stats, and resource library.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 23:11:42 +08:00

1885 lines
67 KiB
Python

#!/usr/bin/env python3
"""SSS 50-week LAN player, flower check-ins, and progress service."""
from __future__ import annotations
import json
import mimetypes
import os
import re
import sqlite3
import subprocess
import sys
import tempfile
import threading
from collections import defaultdict
from contextlib import closing
from datetime import date, datetime, time, timedelta, timezone
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse
from zoneinfo import ZoneInfo
BASE_DIR = Path(__file__).resolve().parent
PUBLIC_DIR = BASE_DIR / "public"
CURRICULUM_PATH = BASE_DIR / "curriculum.json"
ASSET_ROOT = Path(os.environ.get("ASSET_ROOT", "/assets")).expanduser()
DATA_DIR = Path(os.environ.get("DATA_DIR", BASE_DIR / ".local-data")).expanduser()
DB_PATH = Path(os.environ.get("DB_PATH", DATA_DIR / "sss.db")).expanduser()
WEEKLY_MIX_DIR = Path(
os.environ.get("WEEKLY_MIX_DIR", DATA_DIR / "weekly-mixes")
).expanduser()
HOST = os.environ.get("HOST", "0.0.0.0")
PORT = int(os.environ.get("PORT", "8000"))
LOCAL_TZ = ZoneInfo(os.environ.get("TZ", "Asia/Shanghai"))
DEFAULT_START_DATE = date(2026, 10, 12)
ACTORS = ["宝宝", "爸爸", "妈妈", "爷爷", "奶奶", "外公", "外婆"]
ACTOR_EMOJI = {
"宝宝": "🌱",
"爸爸": "👨",
"妈妈": "👩",
"爷爷": "👴",
"奶奶": "👵",
"外公": "🧓",
"外婆": "👵",
}
ASSET_FIELDS = {
"video": ("视频", "video_file", "video/mp4"),
"audio": ("音频", "audio_file", "audio/mpeg"),
"lyrics": ("歌词", "lyrics_file", "image/jpeg"),
}
WEEKLY_MIX_LOCKS: defaultdict[int, threading.Lock] = defaultdict(threading.Lock)
def active_asset_root(
configured_root: Path | None = None, volumes_root: Path = Path("/Volumes")
) -> Path:
"""Return the configured root, or macOS's suffixed SMB mount when needed.
AutoMounter may mount the ``study`` share as ``/Volumes/study-1`` when a
stale mount point already exists. The application is configured for the
stable share name, so resolve that macOS-only suffix at request time rather
than making media availability depend on an exact mount-point spelling.
"""
configured_root = configured_root or ASSET_ROOT
if (configured_root / "视频").is_dir():
return configured_root
try:
relative_path = configured_root.relative_to(volumes_root / "study")
except ValueError:
return configured_root
for mount_point in sorted(volumes_root.glob("study-*")):
candidate = mount_point / relative_path
if (candidate / "视频").is_dir():
return candidate
return configured_root
def load_curriculum(path: Path = CURRICULUM_PATH) -> dict:
with path.open("r", encoding="utf-8") as handle:
curriculum = json.load(handle)
curriculum["weeks_by_no"] = {
int(week["number"]): week for week in curriculum["weeks"]
}
curriculum["songs_by_id"] = {
song["id"]: song
for week in curriculum["weeks"]
for song in week.get("songs", [])
}
return curriculum
CURRICULUM = load_curriculum()
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def iso_timestamp(value: datetime | None = None) -> str:
value = value or utc_now()
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc).isoformat(timespec="seconds")
def parse_timestamp(value: str) -> datetime:
parsed = datetime.fromisoformat(value)
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed.astimezone(timezone.utc)
def local_date(value: str | datetime) -> date:
parsed = parse_timestamp(value) if isinstance(value, str) else value
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed.astimezone(LOCAL_TZ).date()
def local_today(at: datetime | None = None) -> date:
return (at or utc_now()).astimezone(LOCAL_TZ).date()
def parse_study_date(value: str | date | None, fallback: date) -> date:
if value is None:
return fallback
if isinstance(value, date):
return value
try:
return date.fromisoformat(str(value))
except ValueError as error:
raise ValueError("Study date must use YYYY-MM-DD") from error
def connect_db(path: Path = DB_PATH) -> sqlite3.Connection:
connection = sqlite3.connect(path, timeout=15)
connection.row_factory = sqlite3.Row
connection.execute("PRAGMA foreign_keys = ON")
connection.execute("PRAGMA journal_mode = WAL")
connection.execute("PRAGMA busy_timeout = 15000")
return connection
def column_exists(connection: sqlite3.Connection, table: str, column: str) -> bool:
return any(row["name"] == column for row in connection.execute(f"PRAGMA table_info({table})"))
def initialize_database(path: Path = DB_PATH, at: datetime | None = None) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
today = local_today(at)
with closing(connect_db(path)) as connection:
connection.executescript(
"""
CREATE TABLE IF NOT EXISTS household_settings (
id INTEGER PRIMARY KEY CHECK(id = 1),
active_week INTEGER NOT NULL DEFAULT 1 CHECK(active_week BETWEEN 1 AND 50),
checkin_window_minutes INTEGER NOT NULL DEFAULT 60
CHECK(checkin_window_minutes BETWEEN 5 AND 240),
start_date TEXT,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS devices (
device_id TEXT PRIMARY KEY,
actor TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS checkin_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
started_at TEXT NOT NULL,
window_ends_at TEXT NOT NULL,
started_by_device_id TEXT NOT NULL,
started_by_actor TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS playback_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id TEXT NOT NULL,
actor TEXT NOT NULL,
song_id TEXT NOT NULL,
course_week INTEGER NOT NULL CHECK(course_week BETWEEN 1 AND 50),
study_date TEXT,
media_type TEXT NOT NULL CHECK(media_type IN ('video', 'audio')),
started_at TEXT NOT NULL,
completed_at TEXT,
duration_seconds REAL,
checkin_session_id INTEGER,
FOREIGN KEY(checkin_session_id) REFERENCES checkin_sessions(id)
);
CREATE TABLE IF NOT EXISTS song_checkins (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id TEXT NOT NULL,
actor TEXT NOT NULL,
song_id TEXT NOT NULL,
course_week INTEGER NOT NULL CHECK(course_week BETWEEN 1 AND 50),
study_date TEXT NOT NULL,
claimed_at TEXT NOT NULL,
source TEXT NOT NULL CHECK(source IN ('manual', 'recovery')),
playback_event_id INTEGER NOT NULL UNIQUE,
FOREIGN KEY(playback_event_id) REFERENCES playback_events(id)
);
CREATE TABLE IF NOT EXISTS round_checkins (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id TEXT NOT NULL,
actor TEXT NOT NULL,
course_week INTEGER NOT NULL CHECK(course_week BETWEEN 1 AND 50),
study_date TEXT NOT NULL,
awarded_at TEXT NOT NULL,
source TEXT NOT NULL CHECK(source IN ('manual', 'recovery')),
round_number INTEGER NOT NULL CHECK(round_number BETWEEN 1 AND 3),
UNIQUE(course_week, study_date, round_number)
);
"""
)
if not column_exists(connection, "household_settings", "start_date"):
connection.execute("ALTER TABLE household_settings ADD COLUMN start_date TEXT")
if not column_exists(connection, "playback_events", "study_date"):
connection.execute("ALTER TABLE playback_events ADD COLUMN study_date TEXT")
if not column_exists(connection, "round_checkins", "round_number"):
connection.executescript(
"""
ALTER TABLE round_checkins RENAME TO round_checkins_legacy;
CREATE TABLE round_checkins (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id TEXT NOT NULL,
actor TEXT NOT NULL,
course_week INTEGER NOT NULL CHECK(course_week BETWEEN 1 AND 50),
study_date TEXT NOT NULL,
awarded_at TEXT NOT NULL,
source TEXT NOT NULL CHECK(source IN ('manual', 'recovery')),
round_number INTEGER NOT NULL CHECK(round_number BETWEEN 1 AND 3),
UNIQUE(course_week, study_date, round_number)
);
INSERT INTO round_checkins
(id, device_id, actor, course_week, study_date, awarded_at, source, round_number)
SELECT id, device_id, actor, course_week, study_date, awarded_at, 'recovery', 1
FROM round_checkins_legacy;
DROP TABLE round_checkins_legacy;
"""
)
existing = connection.execute(
"SELECT active_week, start_date FROM household_settings WHERE id = 1"
).fetchone()
if not existing:
start_date = DEFAULT_START_DATE
active_week = week_for_date(start_date, today)
connection.execute(
"INSERT INTO household_settings"
"(id, active_week, checkin_window_minutes, start_date, updated_at) "
"VALUES (1, ?, 60, ?, ?)",
(active_week, start_date.isoformat(), iso_timestamp(at)),
)
elif not existing["start_date"]:
start_date = DEFAULT_START_DATE
connection.execute(
"UPDATE household_settings SET start_date = ?, updated_at = ? WHERE id = 1",
(start_date.isoformat(), iso_timestamp(at)),
)
rows = connection.execute(
"SELECT id, started_at FROM playback_events WHERE study_date IS NULL"
).fetchall()
for row in rows:
connection.execute(
"UPDATE playback_events SET study_date = ? WHERE id = ?",
(local_date(row["started_at"]).isoformat(), row["id"]),
)
connection.executescript(
"""
CREATE INDEX IF NOT EXISTS idx_playback_completed
ON playback_events(completed_at);
CREATE INDEX IF NOT EXISTS idx_playback_song
ON playback_events(song_id, completed_at);
CREATE INDEX IF NOT EXISTS idx_playback_week
ON playback_events(course_week, completed_at);
CREATE INDEX IF NOT EXISTS idx_playback_study_date
ON playback_events(study_date, completed_at);
CREATE INDEX IF NOT EXISTS idx_song_checkins_day
ON song_checkins(study_date, song_id);
CREATE INDEX IF NOT EXISTS idx_song_checkins_claimed
ON song_checkins(song_id, claimed_at);
CREATE INDEX IF NOT EXISTS idx_round_checkins_day
ON round_checkins(study_date);
"""
)
connection.commit()
def validate_device_id(device_id: str) -> str:
device_id = str(device_id).strip()
if not re.fullmatch(r"[A-Za-z0-9_-]{8,128}", device_id):
raise ValueError("Invalid device identifier")
return device_id
def get_settings(connection: sqlite3.Connection) -> dict:
row = connection.execute(
"SELECT start_date, checkin_window_minutes FROM household_settings WHERE id = 1"
).fetchone()
if not row or not row["start_date"]:
raise LookupError("Household settings are unavailable")
return {
"start_date": row["start_date"],
"checkin_window_minutes": int(row["checkin_window_minutes"]),
}
def week_for_date(start_date: date, study_date: date) -> int:
return max(1, min(50, (study_date - start_date).days // 7 + 1))
def week_start_date(start_date: date, week_no: int) -> date:
return start_date + timedelta(days=(week_no - 1) * 7)
def get_device_actor(connection: sqlite3.Connection, device_id: str | None) -> str | None:
if not device_id:
return None
row = connection.execute(
"SELECT actor FROM devices WHERE device_id = ?", (device_id,)
).fetchone()
return row["actor"] if row else None
def bind_device(
connection: sqlite3.Connection,
device_id: str,
actor: str,
at: datetime | None = None,
) -> None:
device_id = validate_device_id(device_id)
if actor not in ACTORS:
raise ValueError("Unknown identity")
timestamp = iso_timestamp(at)
connection.execute(
"INSERT INTO devices(device_id, actor, created_at, updated_at) "
"VALUES (?, ?, ?, ?) "
"ON CONFLICT(device_id) DO UPDATE SET actor = excluded.actor, "
"updated_at = excluded.updated_at",
(device_id, actor, timestamp, timestamp),
)
connection.commit()
def playlist_for_week(week: dict) -> list[dict]:
if week["kind"] != "review":
result = []
for song in week.get("songs", []):
item = dict(song)
item["source_week"] = week["number"]
result.append(item)
return result
result = []
for week_no in range(week["review_from"], week["review_to"] + 1):
source_week = CURRICULUM["weeks_by_no"][week_no]
for song in source_week.get("songs", []):
item = dict(song)
item["source_week"] = week_no
result.append(item)
return result
def weekly_mix_sources(week_number: int) -> list[Path]:
"""Return the audio files used by a week's one-key native audio loop."""
week = CURRICULUM["weeks_by_no"].get(week_number)
if not week:
raise LookupError("Unknown week")
root = active_asset_root()
return [root / "音频" / song["audio_file"] for song in playlist_for_week(week)]
def weekly_mix_signature(sources: list[Path]) -> list[dict]:
"""Identify source files so a changed NAS file safely rebuilds its mix."""
signature = []
for source in sources:
stat = source.stat()
signature.append(
{
"path": str(source),
"size": stat.st_size,
"mtime_ns": stat.st_mtime_ns,
}
)
return signature
def ffconcat_path(path: Path) -> str:
"""Quote a filename for ffmpeg's concat demuxer."""
return "file '" + str(path).replace("'", r"'\\''") + "'"
def ensure_weekly_mix(week_number: int) -> Path:
"""Build one cached MP3 for native iPhone background looping on demand.
The mix lives under the application's data directory, never on the NAS.
It is made only after a user presses the one-key play button.
"""
sources = weekly_mix_sources(week_number)
missing = [source.name for source in sources if not source.is_file()]
if missing:
raise FileNotFoundError("Weekly audio is unavailable: " + ", ".join(missing))
signature = weekly_mix_signature(sources)
output = WEEKLY_MIX_DIR / f"week-{week_number:02d}.mp3"
metadata = output.with_suffix(".json")
with WEEKLY_MIX_LOCKS[week_number]:
if output.is_file() and metadata.is_file():
try:
if json.loads(metadata.read_text(encoding="utf-8")) == signature:
return output
except (OSError, json.JSONDecodeError):
pass
WEEKLY_MIX_DIR.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=WEEKLY_MIX_DIR) as work_dir:
work = Path(work_dir)
manifest = work / "week.ffconcat"
manifest.write_text(
"ffconcat version 1.0\n"
+ "\n".join(ffconcat_path(source) for source in sources)
+ "\n",
encoding="utf-8",
)
temporary_output = work / "week.mp3"
command = [
"ffmpeg",
"-hide_banner",
"-loglevel",
"error",
"-y",
"-f",
"concat",
"-safe",
"0",
"-i",
str(manifest),
"-c",
"copy",
str(temporary_output),
]
result = subprocess.run(
command, capture_output=True, text=True, timeout=120, check=False
)
if result.returncode != 0 or not temporary_output.is_file():
# A source with different MP3 parameters cannot be byte-concatenated.
# Re-encode only in that exceptional case so normal first play stays fast.
command[-3:-1] = ["-c:a", "libmp3lame", "-q:a", "4"]
result = subprocess.run(
command, capture_output=True, text=True, timeout=120, check=False
)
if result.returncode != 0 or not temporary_output.is_file():
detail = (result.stderr or "ffmpeg could not create weekly audio").strip()
raise RuntimeError(detail[-400:])
os.replace(temporary_output, output)
metadata.write_text(
json.dumps(signature, ensure_ascii=False, separators=(",", ":")),
encoding="utf-8",
)
return output
def decorate_song(song: dict) -> dict:
asset_root = active_asset_root()
item = dict(song)
item.update(
{
"video_url": f"/api/assets/video/{song['id']}",
"audio_url": f"/api/assets/audio/{song['id']}",
"lyrics_url": f"/api/assets/lyrics/{song['id']}",
"video_available": (asset_root / "视频" / song["video_file"]).is_file(),
"audio_available": (asset_root / "音频" / song["audio_file"]).is_file(),
"lyrics_available": (asset_root / "歌词" / song["lyrics_file"]).is_file(),
}
)
return item
def resources_payload(asset_root: Path | None = None) -> dict:
asset_root = asset_root or active_asset_root()
songs = []
for week in CURRICULUM["weeks"]:
for raw_song in week.get("songs", []):
song = dict(raw_song)
availability = {}
urls = {}
for asset_type, (folder, field, _) in ASSET_FIELDS.items():
availability[asset_type] = (asset_root / folder / song[field]).is_file()
urls[asset_type] = f"/api/assets/{asset_type}/{song['id']}"
songs.append(
{
"id": song["id"],
"title": song["title"],
"week": int(week["number"]),
"slot": int(song["slot"]),
"category": week.get("category", "").replace("\n", " · "),
"files": {
"video": song["video_file"],
"audio": song["audio_file"],
"lyrics": song["lyrics_file"],
},
"available": availability,
"urls": urls,
}
)
return {
"songs": songs,
"summary": {
"songs": len(songs),
"available": {
asset_type: sum(song["available"][asset_type] for song in songs)
for asset_type in ASSET_FIELDS
},
},
}
def validate_course_day(
connection: sqlite3.Connection,
study_date_value: str | date | None,
at: datetime | None = None,
) -> tuple[date, int, dict]:
today = local_today(at)
settings = get_settings(connection)
start_date = date.fromisoformat(settings["start_date"])
study_date = parse_study_date(study_date_value, today)
if study_date < start_date:
raise ValueError("Study date cannot be earlier than the course start date")
if study_date > today:
raise ValueError("Study date cannot be in the future")
return study_date, week_for_date(start_date, study_date), settings
def cooldown_seconds(
connection: sqlite3.Connection,
song_id: str,
now: datetime,
window_minutes: int,
) -> int:
row = connection.execute(
"SELECT claimed_at FROM song_checkins WHERE song_id = ? "
"ORDER BY claimed_at DESC LIMIT 1",
(song_id,),
).fetchone()
if not row:
return 0
unlock_at = parse_timestamp(row["claimed_at"]) + timedelta(minutes=window_minutes)
return max(0, int((unlock_at - now.astimezone(timezone.utc)).total_seconds()))
def song_progress(
connection: sqlite3.Connection,
song_id: str,
course_week: int,
study_date: date,
now: datetime,
window_minutes: int,
) -> dict:
day = study_date.isoformat()
checkins = connection.execute(
"SELECT id, claimed_at, source, actor FROM song_checkins "
"WHERE song_id = ? AND course_week = ? AND study_date = ? "
"ORDER BY claimed_at",
(song_id, course_week, day),
).fetchall()
completed = connection.execute(
"SELECT id FROM playback_events WHERE song_id = ? AND course_week = ? "
"AND study_date = ? AND completed_at IS NOT NULL ORDER BY completed_at",
(song_id, course_week, day),
).fetchall()
used_ids = {
row["playback_event_id"]
for row in connection.execute(
"SELECT playback_event_id FROM song_checkins WHERE playback_event_id IN "
"(SELECT id FROM playback_events WHERE song_id = ? AND course_week = ? "
"AND study_date = ?)",
(song_id, course_week, day),
)
}
ready_count = sum(row["id"] not in used_ids for row in completed)
remaining = cooldown_seconds(connection, song_id, now, window_minutes)
count = len(checkins)
return {
"checkin_count": count,
"completed_plays_on_day": len(completed),
"ready_count": ready_count,
"can_checkin": count < 3 and ready_count > 0 and remaining == 0,
"cooldown_seconds": remaining,
"checkins": [dict(row) for row in checkins],
}
def _find_unused_playback(
connection: sqlite3.Connection,
song_id: str,
course_week: int,
study_date: date,
) -> sqlite3.Row | None:
return connection.execute(
"SELECT pe.* FROM playback_events pe "
"WHERE pe.song_id = ? AND pe.course_week = ? AND pe.study_date = ? "
"AND pe.completed_at IS NOT NULL "
"AND NOT EXISTS (SELECT 1 FROM song_checkins sc "
"WHERE sc.playback_event_id = pe.id) "
"ORDER BY pe.completed_at LIMIT 1",
(song_id, course_week, study_date.isoformat()),
).fetchone()
def _insert_song_checkin(
connection: sqlite3.Connection,
playback: sqlite3.Row,
course_week: int,
study_date: date,
claimed_at: datetime,
source: str,
) -> int:
cursor = connection.execute(
"INSERT INTO song_checkins"
"(device_id, actor, song_id, course_week, study_date, claimed_at, source, playback_event_id) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
(
playback["device_id"],
playback["actor"],
playback["song_id"],
course_week,
study_date.isoformat(),
iso_timestamp(claimed_at),
source,
playback["id"],
),
)
return int(cursor.lastrowid)
def claim_song_checkin(
connection: sqlite3.Connection,
device_id: str,
song_id: str,
study_date_value: str | date,
at: datetime | None = None,
) -> dict:
device_id = validate_device_id(device_id)
now = at or utc_now()
study_date, course_week, settings = validate_course_day(
connection, study_date_value, now
)
week = CURRICULUM["weeks_by_no"][course_week]
if song_id not in {song["id"] for song in playlist_for_week(week)}:
raise ValueError("Song is not part of this study date")
connection.execute("BEGIN IMMEDIATE")
actor = get_device_actor(connection, device_id)
if not actor:
connection.rollback()
raise LookupError("Please choose an identity on this device first")
count = connection.execute(
"SELECT COUNT(*) FROM song_checkins WHERE song_id = ? "
"AND course_week = ? AND study_date = ?",
(song_id, course_week, study_date.isoformat()),
).fetchone()[0]
if count >= 3:
connection.rollback()
raise ValueError("这首歌今天已经集齐 3 朵小红花")
remaining = cooldown_seconds(
connection, song_id, now, settings["checkin_window_minutes"]
)
if remaining:
connection.rollback()
minutes = max(1, (remaining + 59) // 60)
raise ValueError(f"还要等待 {minutes} 分钟才能再领取这首歌的小红花")
playback = _find_unused_playback(connection, song_id, course_week, study_date)
if not playback:
connection.rollback()
raise ValueError("先完整播放一次这首歌,就能领取小红花")
checkin_id = _insert_song_checkin(
connection, playback, course_week, study_date, now, "manual"
)
connection.commit()
return {
"checkin_id": checkin_id,
"song_id": song_id,
"study_date": study_date.isoformat(),
"actor": actor,
"checkin_count": count + 1,
}
def round_cooldown_seconds(
connection: sqlite3.Connection,
now: datetime,
window_minutes: int,
) -> int:
row = connection.execute(
"SELECT awarded_at FROM round_checkins ORDER BY awarded_at DESC LIMIT 1"
).fetchone()
if not row:
return 0
elapsed = (now - parse_timestamp(row["awarded_at"])).total_seconds()
return max(0, int(window_minutes * 60 - elapsed))
def round_progress(
connection: sqlite3.Connection,
course_week: int,
study_date: date,
now: datetime,
window_minutes: int,
) -> dict:
playlist = playlist_for_week(CURRICULUM["weeks_by_no"][course_week])
song_ids = [song["id"] for song in playlist]
completed_rows = connection.execute(
"SELECT song_id, COUNT(*) AS count FROM playback_events "
"WHERE course_week = ? AND study_date = ? AND completed_at IS NOT NULL "
"GROUP BY song_id",
(course_week, study_date.isoformat()),
).fetchall()
completed_counts = {row["song_id"]: int(row["count"]) for row in completed_rows}
checkins = connection.execute(
"SELECT * FROM round_checkins WHERE course_week = ? AND study_date = ? "
"ORDER BY round_number",
(course_week, study_date.isoformat()),
).fetchall()
count = len(checkins)
eligible_rounds = min(
3,
min((completed_counts.get(song_id, 0) for song_id in song_ids), default=0),
)
next_round = count + 1
completed_songs = sum(
completed_counts.get(song_id, 0) >= next_round for song_id in song_ids
)
# The round reward interval belongs to the household, not to one date.
# This prevents switching to a make-up day or another device to bypass it.
remaining = round_cooldown_seconds(connection, now, window_minutes)
ready_count = max(0, eligible_rounds - count)
return {
"checkin_count": count,
"ready_count": ready_count,
"can_checkin": count < 3 and ready_count > 0 and remaining == 0,
"cooldown_seconds": remaining,
"completed_songs": completed_songs,
"total_songs": len(song_ids),
"eligible_rounds": eligible_rounds,
"checkins": [
{
"round_number": row["round_number"],
"actor": row["actor"],
"awarded_at": row["awarded_at"],
"source": row["source"],
}
for row in checkins
],
}
def _insert_round_checkin(
connection: sqlite3.Connection,
device_id: str,
actor: str,
course_week: int,
study_date: date,
round_number: int,
claimed_at: datetime,
source: str,
) -> int:
cursor = connection.execute(
"INSERT INTO round_checkins"
"(device_id, actor, course_week, study_date, awarded_at, source, round_number) "
"VALUES (?, ?, ?, ?, ?, ?, ?)",
(
device_id,
actor,
course_week,
study_date.isoformat(),
iso_timestamp(claimed_at),
source,
round_number,
),
)
return int(cursor.lastrowid)
def claim_round_checkin(
connection: sqlite3.Connection,
device_id: str,
study_date_value: str | date,
at: datetime | None = None,
) -> dict:
device_id = validate_device_id(device_id)
now = at or utc_now()
study_date, course_week, settings = validate_course_day(
connection, study_date_value, now
)
connection.execute("BEGIN IMMEDIATE")
actor = get_device_actor(connection, device_id)
if not actor:
connection.rollback()
raise LookupError("Please choose an identity on this device first")
progress = round_progress(
connection,
course_week,
study_date,
now,
settings["checkin_window_minutes"],
)
if progress["checkin_count"] >= 3:
connection.rollback()
raise ValueError("今天已经集齐 3 朵整轮小红花")
if progress["ready_count"] <= 0:
connection.rollback()
missing = progress["total_songs"] - progress["completed_songs"]
raise ValueError(f"这一轮还差 {missing} 首歌没有完整听完")
if progress["cooldown_seconds"]:
connection.rollback()
minutes = max(1, (progress["cooldown_seconds"] + 59) // 60)
raise ValueError(f"整轮小红花还要等待 {minutes} 分钟才能再次领取")
round_number = progress["checkin_count"] + 1
checkin_id = _insert_round_checkin(
connection,
device_id,
actor,
course_week,
study_date,
round_number,
now,
"manual",
)
connection.commit()
return {
"checkin_id": checkin_id,
"round_number": round_number,
"study_date": study_date.isoformat(),
"actor": actor,
}
def reconcile_pending_awards(
connection: sqlite3.Connection,
course_week: int,
study_date: date,
at: datetime | None = None,
) -> list[dict]:
now = at or utc_now()
settings = get_settings(connection)
awards: list[dict] = []
connection.execute("BEGIN IMMEDIATE")
round_state = round_progress(
connection,
course_week,
study_date,
now,
settings["checkin_window_minutes"],
)
if round_state["can_checkin"]:
latest = connection.execute(
"SELECT device_id, actor FROM playback_events WHERE course_week = ? "
"AND study_date = ? AND completed_at IS NOT NULL "
"ORDER BY completed_at DESC LIMIT 1",
(course_week, study_date.isoformat()),
).fetchone()
round_number = round_state["checkin_count"] + 1
checkin_id = _insert_round_checkin(
connection,
latest["device_id"],
latest["actor"],
course_week,
study_date,
round_number,
now,
"recovery",
)
awards.append(
{
"kind": "round",
"course_week": course_week,
"round_number": round_number,
"checkin_id": checkin_id,
"study_date": study_date.isoformat(),
}
)
for song in playlist_for_week(CURRICULUM["weeks_by_no"][course_week]):
count = connection.execute(
"SELECT COUNT(*) FROM song_checkins WHERE song_id = ? "
"AND course_week = ? AND study_date = ?",
(song["id"], course_week, study_date.isoformat()),
).fetchone()[0]
if count >= 3:
continue
remaining = cooldown_seconds(
connection,
song["id"],
now,
settings["checkin_window_minutes"],
)
if remaining:
continue
playback = _find_unused_playback(
connection, song["id"], course_week, study_date
)
if not playback:
continue
checkin_id = _insert_song_checkin(
connection, playback, course_week, study_date, now, "recovery"
)
awards.append(
{
"kind": "song",
"song_id": song["id"],
"title": song["title"],
"checkin_id": checkin_id,
"study_date": study_date.isoformat(),
}
)
connection.commit()
return awards
def reconcile_all_pending_awards(
connection: sqlite3.Connection,
at: datetime | None = None,
) -> list[dict]:
"""Recover eligible flowers from every completed study day, not just today.
This matters when a child finishes a make-up lesson and closes the page before
tapping the flower: the next normal visit opens on today, but the older effort
still needs to be preserved.
"""
now = at or utc_now()
today = local_today(now)
settings = get_settings(connection)
start_date = date.fromisoformat(settings["start_date"])
rows = connection.execute(
"SELECT DISTINCT course_week, study_date FROM playback_events "
"WHERE completed_at IS NOT NULL AND study_date IS NOT NULL "
"ORDER BY study_date DESC, course_week DESC"
).fetchall()
awards: list[dict] = []
for row in rows:
try:
study_date = date.fromisoformat(row["study_date"])
except (TypeError, ValueError):
continue
if study_date < start_date or study_date > today:
continue
course_week = week_for_date(start_date, study_date)
if course_week != int(row["course_week"]):
continue
day_awards = reconcile_pending_awards(
connection, course_week, study_date, now
)
for award in day_awards:
award.setdefault("study_date", study_date.isoformat())
awards.extend(day_awards)
return awards
def start_playback_event(
connection: sqlite3.Connection,
device_id: str,
song_id: str,
study_date_value: str | date,
media_type: str,
at: datetime | None = None,
course_week_value: int | str | None = None,
) -> int:
device_id = validate_device_id(device_id)
now = at or utc_now()
actor = get_device_actor(connection, device_id)
if not actor:
raise LookupError("Please choose an identity on this device first")
if song_id not in CURRICULUM["songs_by_id"]:
raise ValueError("Unknown song")
if media_type not in ("video", "audio"):
raise ValueError("Unsupported media type")
study_date, scheduled_week, settings = validate_course_day(
connection, study_date_value, now
)
today = local_today(now)
current_week = week_for_date(date.fromisoformat(settings["start_date"]), today)
course_week = scheduled_week if course_week_value is None else int(course_week_value)
if not 1 <= course_week <= 50:
raise ValueError("Course week must be between 1 and 50")
if course_week <= current_week and course_week != scheduled_week:
raise ValueError("Song is not part of this study date")
if course_week > current_week:
# Future lessons may be previewed, but the play is stored on the real
# operation date so it can never unlock a future check-in in advance.
study_date = today
playlist_ids = {
song["id"]
for song in playlist_for_week(CURRICULUM["weeks_by_no"][course_week])
}
if song_id not in playlist_ids:
raise ValueError("Song is not part of this study date")
cursor = connection.execute(
"INSERT INTO playback_events"
"(device_id, actor, song_id, course_week, study_date, media_type, started_at) "
"VALUES (?, ?, ?, ?, ?, ?, ?)",
(
device_id,
actor,
song_id,
course_week,
study_date.isoformat(),
media_type,
iso_timestamp(now),
),
)
connection.commit()
return int(cursor.lastrowid)
def complete_playback_event(
connection: sqlite3.Connection,
device_id: str,
play_id: int,
duration_seconds: float | None,
at: datetime | None = None,
) -> dict:
device_id = validate_device_id(device_id)
now = at or utc_now()
duration = None
if duration_seconds is not None:
duration = max(0.0, min(float(duration_seconds), 24 * 60 * 60))
connection.execute("BEGIN IMMEDIATE")
event = connection.execute(
"SELECT * FROM playback_events WHERE id = ? AND device_id = ?",
(int(play_id), device_id),
).fetchone()
if not event:
connection.rollback()
raise LookupError("Playback record was not found")
if event["completed_at"]:
connection.commit()
return {
"already_completed": True,
"round_ready": False,
"checkin_eligible": False,
"song_id": event["song_id"],
}
study_date = date.fromisoformat(
event["study_date"] or local_date(now).isoformat()
)
connection.execute(
"UPDATE playback_events SET completed_at = ?, duration_seconds = ?, "
"study_date = ? WHERE id = ?",
(iso_timestamp(now), duration, study_date.isoformat(), int(play_id)),
)
settings = get_settings(connection)
start_date = date.fromisoformat(settings["start_date"])
checkin_eligible = (
study_date <= local_today(now)
and int(event["course_week"]) == week_for_date(start_date, study_date)
)
if checkin_eligible:
round_state = round_progress(
connection,
int(event["course_week"]),
study_date,
now,
settings["checkin_window_minutes"],
)
song_state = song_progress(
connection,
event["song_id"],
int(event["course_week"]),
study_date,
now,
settings["checkin_window_minutes"],
)
else:
song_state = None
round_state = {
"checkin_count": 0,
"ready_count": 0,
"can_checkin": False,
"cooldown_seconds": 0,
"completed_songs": 0,
"total_songs": len(
playlist_for_week(
CURRICULUM["weeks_by_no"][int(event["course_week"])]
)
),
"eligible_rounds": 0,
"checkins": [],
}
connection.commit()
return {
"already_completed": False,
"round_ready": round_state["can_checkin"],
"round_award": round_state,
"song_progress": song_state,
"checkin_eligible": checkin_eligible,
"song_id": event["song_id"],
"media_type": event["media_type"],
"actor": event["actor"],
"study_date": study_date.isoformat(),
}
def scheduled_week_summaries(
connection: sqlite3.Connection,
start_date: date,
today: date,
) -> list[dict]:
plays = connection.execute(
"SELECT course_week, study_date FROM playback_events "
"WHERE completed_at IS NOT NULL"
).fetchall()
song_awards = connection.execute(
"SELECT course_week, study_date FROM song_checkins"
).fetchall()
round_awards = connection.execute(
"SELECT course_week, study_date FROM round_checkins"
).fetchall()
grouped: dict[int, dict] = defaultdict(
lambda: {"plays": 0, "flowers": 0, "days": set()}
)
for row in plays:
item = grouped[row["course_week"]]
item["plays"] += 1
item["days"].add(row["study_date"])
for row in [*song_awards, *round_awards]:
item = grouped[row["course_week"]]
item["flowers"] += 1
item["days"].add(row["study_date"])
result = []
for week in CURRICULUM["weeks"]:
week_start = week_start_date(start_date, week["number"])
item = grouped[week["number"]]
result.append(
{
"number": week["number"],
"kind": week["kind"],
"category": week.get("category", ""),
"plays": item["plays"],
"checkins": item["flowers"],
"active_days": len(item["days"]),
"studied": bool(item["plays"] or item["flowers"]),
"start_date": week_start.isoformat(),
"end_date": (week_start + timedelta(days=6)).isoformat(),
"unlocked": True,
"checkin_open": week_start <= today,
}
)
return result
def progress_14_days(
connection: sqlite3.Connection,
start_date: date,
today: date,
) -> list[dict]:
calendar_start = today - timedelta(days=13)
plays = connection.execute(
"SELECT study_date, COUNT(*) AS plays, COUNT(DISTINCT song_id) AS songs "
"FROM playback_events WHERE completed_at IS NOT NULL "
"GROUP BY study_date"
).fetchall()
play_map = {row["study_date"]: dict(row) for row in plays}
song_flowers = {
row["study_date"]: row["count"]
for row in connection.execute(
"SELECT study_date, COUNT(*) AS count FROM song_checkins GROUP BY study_date"
)
}
round_flowers = {
row["study_date"]: row["count"]
for row in connection.execute(
"SELECT study_date, COUNT(*) AS count FROM round_checkins GROUP BY study_date"
)
}
result = []
weekday_labels = "一二三四五六日"
for offset in range(14):
day = calendar_start + timedelta(days=offset)
key = day.isoformat()
before_start = day < start_date
future = day > today
week_no = week_for_date(start_date, day) if not before_start else None
total_songs = 0
if week_no:
total_songs = len(
playlist_for_week(CURRICULUM["weeks_by_no"][week_no])
)
play_item = play_map.get(key, {"plays": 0, "songs": 0})
round_count = round_flowers.get(key, 0)
flowers = song_flowers.get(key, 0) + round_count
if future:
status = "future"
elif before_start:
status = "locked"
elif round_count:
status = "complete"
elif play_item["plays"] or flowers:
status = "progress"
elif day < today:
status = "missed"
else:
status = "today"
result.append(
{
"date": key,
"day": day.day,
"weekday": weekday_labels[day.weekday()],
"week": week_no,
"is_today": day == today,
"clickable": not future and not before_start,
"status": status,
"plays": play_item["plays"],
"completed_songs": play_item["songs"],
"total_songs": total_songs,
"song_flowers": song_flowers.get(key, 0),
"round_flowers": round_count,
"flowers": flowers,
}
)
return result
def state_payload(
connection: sqlite3.Connection,
device_id: str | None,
study_date_value: str | date | None = None,
at: datetime | None = None,
recover: bool = True,
view_week_value: int | str | None = None,
) -> dict:
now = at or utc_now()
today = local_today(now)
study_date, scheduled_week, settings = validate_course_day(
connection, study_date_value, now
)
start_date = date.fromisoformat(settings["start_date"])
current_week = week_for_date(start_date, today)
course_week = scheduled_week if view_week_value is None else int(view_week_value)
if not 1 <= course_week <= 50:
raise ValueError("Course week must be between 1 and 50")
viewing_future = course_week > current_week
can_checkin = not viewing_future and course_week == scheduled_week
recovered_awards = reconcile_all_pending_awards(connection, now) if recover else []
actor = get_device_actor(connection, device_id)
week = CURRICULUM["weeks_by_no"][course_week]
playlist = []
for raw_song in playlist_for_week(week):
song = decorate_song(raw_song)
if can_checkin:
song.update(
song_progress(
connection,
song["id"],
course_week,
study_date,
now,
settings["checkin_window_minutes"],
)
)
else:
song.update(
{
"checkin_count": 0,
"completed_plays_on_day": 0,
"ready_count": 0,
"can_checkin": False,
"cooldown_seconds": 0,
"checkins": [],
}
)
playlist.append(song)
if can_checkin:
round_award = round_progress(
connection,
course_week,
study_date,
now,
settings["checkin_window_minutes"],
)
else:
round_award = {
"checkin_count": 0,
"ready_count": 0,
"can_checkin": False,
"cooldown_seconds": 0,
"completed_songs": 0,
"total_songs": len(playlist),
"eligible_rounds": 0,
"checkins": [],
}
completed_plays = connection.execute(
"SELECT media_type, COUNT(*) AS count FROM playback_events "
"WHERE study_date = ? AND course_week = ? AND completed_at IS NOT NULL "
"GROUP BY media_type",
(study_date.isoformat(), course_week),
).fetchall()
play_counts = {row["media_type"]: row["count"] for row in completed_plays}
song_flower_count = connection.execute(
"SELECT COUNT(*) FROM song_checkins WHERE study_date = ? AND course_week = ?",
(study_date.isoformat(), course_week),
).fetchone()[0]
round_flower_count = connection.execute(
"SELECT COUNT(*) FROM round_checkins WHERE study_date = ? AND course_week = ?",
(study_date.isoformat(), course_week),
).fetchone()[0]
week_data = {key: value for key, value in week.items() if key != "songs"}
week_data["songs"] = playlist
week_data["scheduled_start"] = week_start_date(start_date, course_week).isoformat()
week_data["scheduled_end"] = (
week_start_date(start_date, course_week) + timedelta(days=6)
).isoformat()
return {
"device": {
"id": device_id,
"actor": actor,
"actor_emoji": ACTOR_EMOJI.get(actor),
"needs_identity": actor is None,
},
"actors": [
{"name": actor_name, "emoji": ACTOR_EMOJI[actor_name]}
for actor_name in ACTORS
],
"settings": {
**settings,
"current_week": current_week,
},
"study_date": study_date.isoformat(),
"today_date": today.isoformat(),
"is_today": study_date == today and course_week == current_week,
"viewing_future": viewing_future,
"can_checkin": can_checkin,
"week": week_data,
"day": {
"flowers": song_flower_count + round_flower_count,
"song_flowers": song_flower_count,
"round_flowers": round_flower_count,
"video_plays": play_counts.get("video", 0),
"audio_plays": play_counts.get("audio", 0),
},
"round_award": round_award,
"progress_14d": progress_14_days(connection, start_date, today),
"weeks": scheduled_week_summaries(connection, start_date, today),
"recovered_awards": recovered_awards,
"meta": CURRICULUM["meta"],
}
def statistics_payload(connection: sqlite3.Connection, at: datetime | None = None) -> dict:
now = at or utc_now()
today = local_today(now)
events = connection.execute(
"SELECT * FROM playback_events ORDER BY started_at"
).fetchall()
completed = [row for row in events if row["completed_at"]]
song_awards = connection.execute(
"SELECT * FROM song_checkins ORDER BY claimed_at"
).fetchall()
round_awards = connection.execute(
"SELECT * FROM round_checkins ORDER BY awarded_at"
).fetchall()
plays_by_day: dict[str, list[sqlite3.Row]] = defaultdict(list)
song_awards_by_day: dict[str, list[sqlite3.Row]] = defaultdict(list)
rounds_by_day: dict[str, list[sqlite3.Row]] = defaultdict(list)
for event in completed:
key = event["study_date"] or local_date(event["completed_at"]).isoformat()
plays_by_day[key].append(event)
for award in song_awards:
song_awards_by_day[award["study_date"]].append(award)
for award in round_awards:
rounds_by_day[award["study_date"]].append(award)
daily = []
for offset in range(41, -1, -1):
day = today - timedelta(days=offset)
key = day.isoformat()
day_events = plays_by_day.get(key, [])
day_song_awards = song_awards_by_day.get(key, [])
day_rounds = rounds_by_day.get(key, [])
actors = {event["actor"] for event in day_events}
actors.update(award["actor"] for award in day_song_awards)
daily.append(
{
"date": key,
"checkins": len(day_song_awards) + len(day_rounds),
"song_checkins": len(day_song_awards),
"round_checkins": len(day_rounds),
"video_plays": sum(e["media_type"] == "video" for e in day_events),
"audio_plays": sum(e["media_type"] == "audio" for e in day_events),
"minutes": round(
sum(e["duration_seconds"] or 0 for e in day_events) / 60, 1
),
"actors": sorted(actors),
}
)
active_days = {
*song_awards_by_day.keys(),
*rounds_by_day.keys(),
}
streak = 0
cursor = today
while cursor.isoformat() in active_days:
streak += 1
cursor -= timedelta(days=1)
week_groups: dict[int, dict] = defaultdict(
lambda: {
"video_plays": 0,
"audio_plays": 0,
"checkins": 0,
"days": set(),
"songs": set(),
}
)
song_groups: dict[str, dict] = defaultdict(
lambda: {
"video_starts": 0,
"audio_starts": 0,
"video_plays": 0,
"audio_plays": 0,
"checkins": 0,
"actors": set(),
"last_played_at": None,
}
)
actor_groups: dict[str, dict] = defaultdict(
lambda: {"video_plays": 0, "audio_plays": 0, "checkins_started": 0}
)
for event in events:
item = song_groups[event["song_id"]]
item[f"{event['media_type']}_starts"] += 1
if not event["completed_at"]:
continue
item[f"{event['media_type']}_plays"] += 1
item["actors"].add(event["actor"])
item["last_played_at"] = event["completed_at"]
week_item = week_groups[event["course_week"]]
week_item[f"{event['media_type']}_plays"] += 1
week_item["days"].add(event["study_date"])
week_item["songs"].add(event["song_id"])
actor_groups[event["actor"]][f"{event['media_type']}_plays"] += 1
for award in song_awards:
song_groups[award["song_id"]]["checkins"] += 1
song_groups[award["song_id"]]["actors"].add(award["actor"])
week_groups[award["course_week"]]["checkins"] += 1
week_groups[award["course_week"]]["days"].add(award["study_date"])
actor_groups[award["actor"]]["checkins_started"] += 1
for award in round_awards:
week_groups[award["course_week"]]["checkins"] += 1
week_groups[award["course_week"]]["days"].add(award["study_date"])
actor_groups[award["actor"]]["checkins_started"] += 1
weeks = []
for week in CURRICULUM["weeks"]:
item = week_groups[week["number"]]
weeks.append(
{
"number": week["number"],
"kind": week["kind"],
"category": week.get("category", ""),
"video_plays": item["video_plays"],
"audio_plays": item["audio_plays"],
"checkins": item["checkins"],
"active_days": len(item["days"]),
"songs_played": len(item["songs"]),
"songs_total": len(playlist_for_week(week)),
}
)
songs = []
for song_id, song in CURRICULUM["songs_by_id"].items():
item = song_groups[song_id]
songs.append(
{
"id": song_id,
"week": int(song_id.split("-")[0]),
"title": song["title"],
"video_starts": item["video_starts"],
"audio_starts": item["audio_starts"],
"video_plays": item["video_plays"],
"audio_plays": item["audio_plays"],
"checkins": item["checkins"],
"actors": sorted(item["actors"]),
"last_played_at": item["last_played_at"],
}
)
songs.sort(
key=lambda item: (
-(item["video_plays"] + item["audio_plays"] + item["checkins"]),
item["week"],
item["id"],
)
)
combined_awards = [
{
"id": f"song-{row['id']}",
"started_at": row["claimed_at"],
"actor": row["actor"],
"plays": 1,
"songs": [row["song_id"]],
"actors": [row["actor"]],
"kind": "song",
}
for row in song_awards
] + [
{
"id": f"round-{row['id']}",
"started_at": row["awarded_at"],
"actor": row["actor"],
"plays": 1,
"songs": [],
"actors": [row["actor"]],
"kind": "round",
}
for row in round_awards
]
combined_awards.sort(key=lambda item: item["started_at"], reverse=True)
actor_stats = [
{"actor": actor, **actor_groups[actor]}
for actor in ACTORS
if actor in actor_groups
]
return {
"summary": {
"checkins": len(song_awards) + len(round_awards),
"song_checkins": len(song_awards),
"round_checkins": len(round_awards),
"active_days": len(active_days),
"streak": streak,
"video_plays": sum(e["media_type"] == "video" for e in completed),
"audio_plays": sum(e["media_type"] == "audio" for e in completed),
"completed_minutes": round(
sum(e["duration_seconds"] or 0 for e in completed) / 60, 1
),
},
"daily": daily,
"weeks": weeks,
"songs": songs,
"actors": actor_stats,
"recent_sessions": combined_awards[:50],
"generated_at": iso_timestamp(now),
}
class SSSRequestHandler(BaseHTTPRequestHandler):
server_version = "SSSCheckin/0.4"
def log_message(self, format_string: str, *args: object) -> None:
sys.stderr.write(
f"{self.address_string()} - [{self.log_date_time_string()}] "
f"{format_string % args}\n"
)
def send_json(self, payload: dict | list, status: int = HTTPStatus.OK) -> None:
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
if self.command != "HEAD":
self.wfile.write(body)
def send_error_json(self, message: str, status: int) -> None:
self.send_json({"error": message}, status)
def read_json(self) -> dict:
length = int(self.headers.get("Content-Length", "0"))
if length > 64 * 1024:
raise ValueError("Request body is too large")
raw = self.rfile.read(length) if length else b"{}"
return json.loads(raw.decode("utf-8"))
def do_HEAD(self) -> None: # noqa: N802
self.do_GET()
def do_GET(self) -> None: # noqa: N802
parsed = urlparse(self.path)
if parsed.path == "/api/health":
self.handle_health()
return
if parsed.path == "/api/state":
self.handle_state(parsed.query)
return
if parsed.path == "/api/statistics":
with closing(connect_db()) as connection:
self.send_json(statistics_payload(connection))
return
if parsed.path == "/api/resources":
self.send_json(resources_payload())
return
weekly_audio_match = re.fullmatch(r"/api/week-audio/(\d{1,2})", parsed.path)
if weekly_audio_match:
self.handle_weekly_audio(int(weekly_audio_match.group(1)))
return
asset_match = re.fullmatch(r"/api/assets/(video|audio|lyrics)/([^/]+)", parsed.path)
if asset_match:
self.handle_asset(asset_match.group(1), unquote(asset_match.group(2)))
return
if parsed.path == "/":
self.serve_static("index.html")
return
if parsed.path in ("/stats", "/stats/"):
self.serve_static("stats.html")
return
if parsed.path in ("/resources", "/resources/"):
self.serve_static("resources.html")
return
if parsed.path.startswith("/static/"):
self.serve_static(unquote(parsed.path.removeprefix("/static/")))
return
self.send_error_json("Not found", HTTPStatus.NOT_FOUND)
def do_POST(self) -> None: # noqa: N802
parsed = urlparse(self.path)
try:
payload = self.read_json()
if parsed.path == "/api/device/identity":
self.update_identity(payload)
elif parsed.path == "/api/settings":
self.update_settings(payload)
elif parsed.path == "/api/playback/start":
self.start_playback(payload)
elif parsed.path == "/api/playback/complete":
self.complete_playback(payload)
elif parsed.path == "/api/song-checkin":
self.claim_song(payload)
elif parsed.path == "/api/round-checkin":
self.claim_round(payload)
else:
self.send_error_json("Not found", HTTPStatus.NOT_FOUND)
except (ValueError, KeyError, TypeError, json.JSONDecodeError) as error:
self.send_error_json(str(error), HTTPStatus.BAD_REQUEST)
except LookupError as error:
self.send_error_json(str(error), HTTPStatus.NOT_FOUND)
def handle_health(self) -> None:
asset_root = active_asset_root()
counts = {}
for asset_type, (folder, field, _) in ASSET_FIELDS.items():
counts[asset_type] = sum(
(asset_root / folder / song[field]).is_file()
for song in CURRICULUM["songs_by_id"].values()
)
self.send_json(
{
"status": "ok" if all(value == 100 for value in counts.values()) else "degraded",
"asset_root": str(asset_root),
"asset_counts": counts,
"songs": len(CURRICULUM["songs_by_id"]),
}
)
def handle_state(self, query: str) -> None:
params = parse_qs(query)
try:
device_id = params.get("device_id", [None])[0]
if device_id:
validate_device_id(device_id)
study_date_value = params.get("study_date", [None])[0]
view_week_value = params.get("week", [None])[0]
recover = params.get("recover", ["1"])[0] != "0"
with closing(connect_db()) as connection:
self.send_json(
state_payload(
connection,
device_id,
study_date_value,
recover=recover,
view_week_value=view_week_value,
)
)
except (ValueError, LookupError) as error:
self.send_error_json(str(error), HTTPStatus.BAD_REQUEST)
def update_identity(self, payload: dict) -> None:
with closing(connect_db()) as connection:
bind_device(connection, payload["device_id"], payload["actor"])
self.send_json(
{
"saved": True,
"actor": payload["actor"],
"emoji": ACTOR_EMOJI[payload["actor"]],
}
)
def update_settings(self, payload: dict) -> None:
window = int(payload["checkin_window_minutes"])
if not 5 <= window <= 240:
raise ValueError("Check-in window must be between 5 and 240 minutes")
with closing(connect_db()) as connection:
start_date = date.fromisoformat(get_settings(connection)["start_date"])
active_week = week_for_date(start_date, local_today())
connection.execute(
"UPDATE household_settings SET start_date = ?, active_week = ?, "
"checkin_window_minutes = ?, updated_at = ? WHERE id = 1",
(start_date.isoformat(), active_week, window, iso_timestamp()),
)
connection.commit()
self.send_json({"saved": True, "current_week": active_week})
def start_playback(self, payload: dict) -> None:
with closing(connect_db()) as connection:
play_id = start_playback_event(
connection,
payload["device_id"],
payload["song_id"],
payload["study_date"],
payload["media_type"],
course_week_value=payload.get("course_week"),
)
self.send_json({"play_id": play_id}, HTTPStatus.CREATED)
def complete_playback(self, payload: dict) -> None:
with closing(connect_db()) as connection:
result = complete_playback_event(
connection,
payload["device_id"],
int(payload["play_id"]),
payload.get("duration_seconds"),
)
self.send_json(result)
def claim_song(self, payload: dict) -> None:
with closing(connect_db()) as connection:
result = claim_song_checkin(
connection,
payload["device_id"],
payload["song_id"],
payload["study_date"],
)
self.send_json(result, HTTPStatus.CREATED)
def claim_round(self, payload: dict) -> None:
with closing(connect_db()) as connection:
result = claim_round_checkin(
connection,
payload["device_id"],
payload["study_date"],
)
self.send_json(result, HTTPStatus.CREATED)
def serve_static(self, relative_path: str) -> None:
candidate = (PUBLIC_DIR / relative_path).resolve()
public = PUBLIC_DIR.resolve()
if public not in candidate.parents and candidate != public:
self.send_error_json("Not found", HTTPStatus.NOT_FOUND)
return
if not candidate.is_file():
self.send_error_json("Not found", HTTPStatus.NOT_FOUND)
return
content_type = mimetypes.guess_type(candidate.name)[0] or "application/octet-stream"
body = candidate.read_bytes()
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-cache")
self.end_headers()
if self.command != "HEAD":
self.wfile.write(body)
def handle_asset(self, asset_type: str, song_id: str) -> None:
song = CURRICULUM["songs_by_id"].get(song_id)
if not song:
self.send_error_json("Unknown song", HTTPStatus.NOT_FOUND)
return
folder, field, content_type = ASSET_FIELDS[asset_type]
self.serve_file(active_asset_root() / folder / song[field], content_type)
def handle_weekly_audio(self, week_number: int) -> None:
if not 1 <= week_number <= 50:
self.send_error_json("Unknown week", HTTPStatus.NOT_FOUND)
return
try:
self.serve_file(ensure_weekly_mix(week_number), "audio/mpeg")
except FileNotFoundError as error:
self.send_error_json(str(error), HTTPStatus.NOT_FOUND)
except (OSError, RuntimeError, subprocess.TimeoutExpired) as error:
self.send_error_json(f"Weekly audio could not be prepared: {error}", HTTPStatus.SERVICE_UNAVAILABLE)
def serve_file(self, path: Path, content_type: str) -> None:
if not path.is_file():
self.send_error_json("Asset is unavailable", HTTPStatus.NOT_FOUND)
return
size = path.stat().st_size
start, end = 0, size - 1
status = HTTPStatus.OK
range_header = self.headers.get("Range")
if range_header:
match = re.fullmatch(r"bytes=(\d*)-(\d*)", range_header.strip())
if not match:
self.send_range_error(size)
return
first, last = match.groups()
if first:
start = int(first)
end = int(last) if last else size - 1
elif last:
start = max(0, size - int(last))
if start >= size or end < start:
self.send_range_error(size)
return
end = min(end, size - 1)
status = HTTPStatus.PARTIAL_CONTENT
length = end - start + 1
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(length))
self.send_header("Accept-Ranges", "bytes")
self.send_header("Cache-Control", "private, max-age=3600")
self.send_header("X-Content-Type-Options", "nosniff")
if status == HTTPStatus.PARTIAL_CONTENT:
self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
self.end_headers()
if self.command == "HEAD":
return
with path.open("rb") as handle:
handle.seek(start)
remaining = length
try:
while remaining:
chunk = handle.read(min(1024 * 1024, remaining))
if not chunk:
break
self.wfile.write(chunk)
remaining -= len(chunk)
except (BrokenPipeError, ConnectionResetError):
pass
def send_range_error(self, size: int) -> None:
self.send_response(HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
self.send_header("Content-Range", f"bytes */{size}")
self.end_headers()
def create_server(host: str = HOST, port: int = PORT) -> ThreadingHTTPServer:
initialize_database()
return ThreadingHTTPServer((host, port), SSSRequestHandler)
def main() -> None:
server = create_server()
print(f"SSS check-in is running at http://{HOST}:{PORT}")
print(f"Asset root: {active_asset_root()}")
print(f"Database: {DB_PATH}")
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nStopping server")
finally:
server.server_close()
if __name__ == "__main__":
main()