commit dd281e1bd050ed9648a31442d8ce363ca4dc3586 Author: optimx Date: Wed Nov 4 23:11:42 2026 +0800 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 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..9029600 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +.DS_Store +.git +.local-data +__pycache__ +*.pyc +source +tests +docs diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..7943d48 --- /dev/null +++ b/.env.example @@ -0,0 +1,3 @@ +# Confirm these two server-side paths in Synology DSM before deployment. +SSS_ASSET_PATH=/volume1/study/Assets/SSS50 +SSS_DATA_PATH=/volume1/docker/sss-checkin/data diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d153469 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.DS_Store +.local-data/ +__pycache__/ +*.pyc +.env diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..145b0a7 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,21 @@ +FROM python:3.12-alpine + +WORKDIR /app + +# The one-key weekly audio loop is composed lazily when first requested. +# Keep ffmpeg in the NAS image so this also works after moving off the Mac. +RUN apk add --no-cache ffmpeg + +COPY app.py curriculum.json ./ +COPY public ./public + +ENV HOST=0.0.0.0 \ + PORT=8000 \ + ASSET_ROOT=/assets \ + DATA_DIR=/data \ + PYTHONUNBUFFERED=1 + +EXPOSE 8000 +VOLUME ["/data"] + +CMD ["python", "app.py"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..db2f73c --- /dev/null +++ b/README.md @@ -0,0 +1,75 @@ +# SSS 50周局域网自动打卡工具 + +面向家庭手机浏览器的局域网应用。应用直接读取 NAS 上同一套课程的视频、音频和歌词图片;歌曲完整播放后记录播放并解锁小红花,让宝宝保留亲手打卡的快乐。 + +## 当前功能 + +- 50 周课程、100 首歌曲,视频、音频、歌词按课程编号自动匹配。 +- 本周每首歌都有一张独立媒体卡,视频、音频、歌词在各自卡片内切换,不再通过统一播放器切歌。 +- 同一张歌曲卡片切换视频、音频或歌词标签时不会暂停正在播放的媒体,因此可以一边听音频或视频,一边打开歌词查看;只有主动播放另一种媒体或另一首歌时才切换声源。 +- 视频与音频画面固定为相同的 16:9 尺寸;音频点击画面中央即可播放或暂停,进度条收在画面底部,切换时页面不跳动。 +- 成长足迹下方提供“播放本周音频”控制:从第一首开始依次播放整周歌单,播完最后一首后从头循环;直接播放某张歌曲卡片时,则自动单曲循环当前视频或音频。 +- 歌词在主页面原位展示,不会把宝宝带到新页面。 +- 单宝宝模式,没有孩子档案切换。 +- 每台设备首次选择“宝宝、爸爸、妈妈、爷爷、奶奶、外公、外婆”,以后自动记住;右上角只显示当前角色,点击即可切换。 +- 开课日期固定为 2026 年 10 月 12 日,每 7 天自动进入下一周;每次打开默认显示今天对应的课程周。 +- 上一周、下一周和 50 周课程地图可以独立浏览全部周次:过去周可以补学习,未来周可以提前试听,但预习播放不会提前解锁任何歌曲或整轮红花。 +- 每次完整播放计一次播放并解锁一次领取资格;每首歌每天最多领取 3 朵小红花,按“上午领取、下午领取、晚上领取”大尺寸展示,同一首歌默认间隔 60 分钟。 +- 每完成一轮本周歌单,就会解锁 1 朵整轮大红花;每天最多 3 轮,宝宝可亲手领取,页面直接提示需听完全部歌曲。歌曲或整轮奖励若已满足条件却没有领取,会在下次进入时自动补记并播放奖励动画。 +- 自动补领会检查所有学习日期:即使补学后跨天重新打开,已经完成的努力也不会漏掉。 +- 首页展示连续 14 天成长日历,固定为 2 行 × 7 天;今天永远位于第二行最后一格,星期标题随日期动态变化。过去日期可直接进入补学习、补红花。 +- 歌曲红花和整轮红花均提供大尺寸点击区域;尚未满足条件、仍在冷却或已经领取时,点击会直接说明原因。 +- 多台设备可以同时使用:每台设备记录自己的身份,领取请求由 SQLite 事务串行处理;歌曲及整轮的一小时领取间隔按家庭共享,避免两个设备重复领取。 +- 播放和红花都保留实际时间、学习日期、设备身份、歌曲、课程周和媒体类型。 +- 设置中可进入统计页,查看最近 42 天、完整 50 周、每首歌、每位操作者和最近红花。 +- 家长设置入口位于页面最底部,避免宝宝误触;开始学习日期仅灰色展示,不允许修改。 +- 设置中可进入全部资源库,搜索或按周筛选 100 首歌;点击歌曲卡片后在卡片下方展开视频、音频和歌词,切换歌曲时上一张会自动收起。主页与资源库的视频都只有点击播放后才从 NAS 读取。 +- SQLite 保存记录;NAS 资源目录以只读方式挂载。 + +## 在 Mac 上运行 + +当前 Mac 使用已登录用户的后台会话常驻运行,以保留对 NAS SMB 挂载 `/Volumes/study` 的读取权限。服务异常退出后会在两秒后自动重新启动;正常情况下不需要保持 Codex 或终端窗口打开。 + + +常用检查命令: + +```bash +./scripts/local_server.sh status +./scripts/local_server.sh logs +``` + +启动或停止服务: + +```bash +cd /Users/optimx/CODE/nas/project_sss +./scripts/local_server.sh start +./scripts/local_server.sh stop +``` + +打开 。同一局域网的手机使用这台 Mac 的局域网 IP,例如 `http://192.168.50.x:8787`。 + +## 在群晖上部署 + +详细步骤见 [群晖部署说明](docs/群晖部署说明.md)。群晖容器必须使用群晖本机路径,不能直接使用 Mac 的 `/Volumes/...` 路径。 + +```bash +cp .env.example .env +docker compose up -d --build +``` + +默认访问地址为 `http://群晖IP:8787`。 + +## 测试 + +```bash +python3 -m unittest discover -s tests -v +``` + +## 目录 + +- `app.py`:HTTP 服务、自动打卡、统计、SQLite 和媒体 Range 流式传输。 +- `curriculum.json`:从课程表与统一资源目录生成的映射。 +- `public/`:宝宝友好的主页面,以及家长统计页和全部资源库。 +- `source/`:课程 Excel 的项目内副本。 +- `scripts/build_curriculum.py`:重新扫描视频、音频、歌词并生成课程数据。 +- `docs/`:产品规则和群晖部署说明。 diff --git a/app.py b/app.py new file mode 100644 index 0000000..9f5a07a --- /dev/null +++ b/app.py @@ -0,0 +1,1884 @@ +#!/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() diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..15182b5 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,14 @@ +services: + sss-checkin: + build: . + container_name: sss-checkin + restart: unless-stopped + ports: + - "8787:8000" + environment: + TZ: Asia/Shanghai + ASSET_ROOT: /assets + DATA_DIR: /data + volumes: + - "${SSS_ASSET_PATH:-/volume1/study/Assets/SSS50}:/assets:ro" + - "${SSS_DATA_PATH:-/volume1/docker/sss-checkin/data}:/data" diff --git a/curriculum.json b/curriculum.json new file mode 100644 index 0000000..3b2cc23 --- /dev/null +++ b/curriculum.json @@ -0,0 +1,1177 @@ +{ + "meta": { + "title": "SSS 50周学习计划", + "source_workbook": "SSS 儿歌 50周打卡表.xlsx", + "asset_root_name": "SSS50", + "song_count": 100, + "week_count": 50 + }, + "weeks": [ + { + "number": 1, + "kind": "lesson", + "category": "宠物\n农场动物", + "songs": [ + { + "id": "1-1", + "slot": 1, + "title": "Good Morning Mr Rooster", + "video_file": "1-1 Good Morning Mr Rooster.mp4", + "audio_file": "1-1 Good Morning Mr Rooster.mp3", + "lyrics_file": "1-1 Good Morning Mr Rooster.jpg" + }, + { + "id": "1-2", + "slot": 2, + "title": "BINGO", + "video_file": "1-2 BINGO.mp4", + "audio_file": "1-2 BINGO.mp3", + "lyrics_file": "1-2 BINGO.jpg" + }, + { + "id": "1-3", + "slot": 3, + "title": "I Have A Pet", + "video_file": "1-3 I Have A Pet.mp4", + "audio_file": "1-3 I Have A Pet.mp3", + "lyrics_file": "1-3 I Have A Pet.jpg" + } + ] + }, + { + "number": 2, + "kind": "lesson", + "category": "宠物\n农场动物", + "songs": [ + { + "id": "2-1", + "slot": 1, + "title": "The Animals On The Farm", + "video_file": "2-1 The Animals On The Farm.mp4", + "audio_file": "2-1 The Animals On The Farm.mp3", + "lyrics_file": "2-1 The Animals On The Farm.jpg" + }, + { + "id": "2-2", + "slot": 2, + "title": "The Farmer In The Dell", + "video_file": "2-2 The Farmer In The Dell.mp4", + "audio_file": "2-2 The Farmer In The Dell.mp3", + "lyrics_file": "2-2 The Farmer In The Dell.jpg" + }, + { + "id": "2-3", + "slot": 3, + "title": "Five Little Ducks", + "video_file": "2-3 Five Little Ducks.mp4", + "audio_file": "2-3 Five Little Ducks.mp3", + "lyrics_file": "2-3 Five Little Ducks.jpg" + } + ] + }, + { + "number": 3, + "kind": "lesson", + "category": "宠物\n农场动物", + "songs": [ + { + "id": "3-1", + "slot": 1, + "title": "Old MacDonald", + "video_file": "3-1 Old MacDonald.mp4", + "audio_file": "3-1 Old MacDonald.mp3", + "lyrics_file": "3-1 Old MacDonald.jpg" + }, + { + "id": "3-2", + "slot": 2, + "title": "Little Robin Redbreast", + "video_file": "3-2 Little Robin Redbreast.mp4", + "audio_file": "3-2 Little Robin Redbreast.mp3", + "lyrics_file": "3-2 Little Robin Redbreast.jpg" + }, + { + "id": "3-3", + "slot": 3, + "title": "After A While Crocodile", + "video_file": "3-3 After A While Crocodile.mp4", + "audio_file": "3-3 After A While Crocodile.mp3", + "lyrics_file": "3-3 After A While Crocodile.jpg" + } + ] + }, + { + "number": 4, + "kind": "lesson", + "category": "森林动物", + "songs": [ + { + "id": "4-1", + "slot": 1, + "title": "What Do You Hear", + "video_file": "4-1 What Do You Hear.mp4", + "audio_file": "4-1 What Do You Hear.mp3", + "lyrics_file": "4-1 What Do You Hear.jpg" + }, + { + "id": "4-2", + "slot": 2, + "title": "Eeney Meeney Miney Moe", + "video_file": "4-2 Eeney Meeney Miney Moe.mp4", + "audio_file": "4-2 Eeney Meeney Miney Moe.mp3", + "lyrics_file": "4-2 Eeney Meeney Miney Moe.jpg" + }, + { + "id": "4-3", + "slot": 3, + "title": "Mary Had A Kangaroo", + "video_file": "4-3 Mary Had A Kangaroo.mp4", + "audio_file": "4-3 Mary Had A Kangaroo.mp3", + "lyrics_file": "4-3 Mary Had A Kangaroo.jpg" + } + ] + }, + { + "number": 5, + "kind": "review", + "category": "复习1-4周", + "songs": [], + "review_from": 1, + "review_to": 4 + }, + { + "number": 6, + "kind": "review", + "category": "复习1-4周", + "songs": [], + "review_from": 1, + "review_to": 4 + }, + { + "number": 7, + "kind": "lesson", + "category": "森林动物", + "songs": [ + { + "id": "7-1", + "slot": 1, + "title": "Alice The Camel", + "video_file": "7-1 Alice The Camel.mp4", + "audio_file": "7-1 Alice The Camel.mp3", + "lyrics_file": "7-1 Alice The Camel.jpg" + }, + { + "id": "7-2", + "slot": 2, + "title": "Five Little Monkeys", + "video_file": "7-2 Five Little Monkeys.mp4", + "audio_file": "7-2 Five Little Monkeys.mp3", + "lyrics_file": "7-2 Five Little Monkeys.jpg" + }, + { + "id": "7-3", + "slot": 3, + "title": "Yes I Can", + "video_file": "7-3 Yes I Can.mp4", + "audio_file": "7-3 Yes I Can.mp3", + "lyrics_file": "7-3 Yes I Can.jpg" + } + ] + }, + { + "number": 8, + "kind": "lesson", + "category": "森林动物", + "songs": [ + { + "id": "8-1", + "slot": 1, + "title": "Let's Go To The Zoo", + "video_file": "8-1 Let's Go To The Zoo.mp4", + "audio_file": "8-1 Let's Go To The Zoo.mp3", + "lyrics_file": "8-1 Let's Go To The Zoo.jpg" + }, + { + "id": "8-2", + "slot": 2, + "title": "Five Little Speckled Frogs", + "video_file": "8-2 Five Little Speckled Frogs.mp4", + "audio_file": "8-2 Five Little Speckled Frogs.mp3", + "lyrics_file": "8-2 Five Little Speckled Frogs.jpg" + }, + { + "id": "8-3", + "slot": 3, + "title": "Walking In The Jungle", + "video_file": "8-3 Walking In The Jungle.mp4", + "audio_file": "8-3 Walking In The Jungle.mp3", + "lyrics_file": "8-3 Walking In The Jungle.jpg" + } + ] + }, + { + "number": 9, + "kind": "lesson", + "category": "昆虫\n海洋动物", + "songs": [ + { + "id": "9-1", + "slot": 1, + "title": "Baby Shark", + "video_file": "9-1 Baby Shark.mp4", + "audio_file": "9-1 Baby Shark.mp3", + "lyrics_file": "9-1 Baby Shark.jpg" + }, + { + "id": "9-2", + "slot": 2, + "title": "The Itsy Bitsy Spider", + "video_file": "9-2 The Itsy Bitsy Spider.mp4", + "audio_file": "9-2 The Itsy Bitsy Spider.mp3", + "lyrics_file": "9-2 The Itsy Bitsy Spider.jpg" + }, + { + "id": "9-3", + "slot": 3, + "title": "The Ants Go Marching", + "video_file": "9-3 The Ants Go Marching.mp4", + "audio_file": "9-3 The Ants Go Marching.mp3", + "lyrics_file": "9-3 The Ants Go Marching.jpg" + } + ] + }, + { + "number": 10, + "kind": "lesson", + "category": "动作", + "songs": [ + { + "id": "10-1", + "slot": 1, + "title": "Hello Hello", + "video_file": "10-1 Hello Hello.mp4", + "audio_file": "10-1 Hello Hello.mp3", + "lyrics_file": "10-1 Hello Hello.jpg" + }, + { + "id": "10-2", + "slot": 2, + "title": "Bye Bye Goodbye", + "video_file": "10-2 Bye Bye Goodbye.mp4", + "audio_file": "10-2 Bye Bye Goodbye.mp3", + "lyrics_file": "10-2 Bye Bye Goodbye.jpg" + }, + { + "id": "10-3", + "slot": 3, + "title": "Make A Circle", + "video_file": "10-3 Make A Circle.mp4", + "audio_file": "10-3 Make A Circle.mp3", + "lyrics_file": "10-3 Make A Circle.jpg" + } + ] + }, + { + "number": 11, + "kind": "review", + "category": "复习7-10周", + "songs": [], + "review_from": 7, + "review_to": 10 + }, + { + "number": 12, + "kind": "review", + "category": "复习7-10周", + "songs": [], + "review_from": 7, + "review_to": 10 + }, + { + "number": 13, + "kind": "lesson", + "category": "动作", + "songs": [ + { + "id": "13-1", + "slot": 1, + "title": "One Little Finger", + "video_file": "13-1 One Little Finger.mp4", + "audio_file": "13-1 One Little Finger.mp3", + "lyrics_file": "13-1 One Little Finger.jpg" + }, + { + "id": "13-2", + "slot": 2, + "title": "If You're Happy", + "video_file": "13-2 If You're Happy.mp4", + "audio_file": "13-2 If You're Happy.mp3", + "lyrics_file": "13-2 If You're Happy.jpg" + }, + { + "id": "13-3", + "slot": 3, + "title": "Walking Walking", + "video_file": "13-3 Walking Walking.mp4", + "audio_file": "13-3 Walking Walking.mp3", + "lyrics_file": "13-3 Walking Walking.jpg" + } + ] + }, + { + "number": 14, + "kind": "lesson", + "category": "动作", + "songs": [ + { + "id": "14-1", + "slot": 1, + "title": "Follow Me", + "video_file": "14-1 Follow Me.mp4", + "audio_file": "14-1 Follow Me.mp3", + "lyrics_file": "14-1 Follow Me.jpg" + }, + { + "id": "14-2", + "slot": 2, + "title": "Say Cheese", + "video_file": "14-2 Say Cheese.mp4", + "audio_file": "14-2 Say Cheese.mp3", + "lyrics_file": "14-2 Say Cheese.jpg" + }, + { + "id": "14-3", + "slot": 3, + "title": "Pat A Cake", + "video_file": "14-3 Pat A Cake.mp4", + "audio_file": "14-3 Pat A Cake.mp3", + "lyrics_file": "14-3 Pat A Cake.jpg" + } + ] + }, + { + "number": 15, + "kind": "lesson", + "category": "动作", + "songs": [ + { + "id": "15-1", + "slot": 1, + "title": "The Pinocchio", + "video_file": "15-1 The Pinocchio.mp4", + "audio_file": "15-1 The Pinocchio.mp3", + "lyrics_file": "15-1 The Pinocchio.jpg" + }, + { + "id": "15-2", + "slot": 2, + "title": "What Do You Like To Do", + "video_file": "15-2 What Do You Like To Do.mp4", + "audio_file": "15-2 What Do You Like To Do.mp3", + "lyrics_file": "15-2 What Do You Like To Do.jpg" + }, + { + "id": "15-3", + "slot": 3, + "title": "Peekaboo", + "video_file": "15-3 Peekaboo.mp4", + "audio_file": "15-3 Peekaboo.mp3", + "lyrics_file": "15-3 Peekaboo.jpg" + } + ] + }, + { + "number": 16, + "kind": "lesson", + "category": "游戏", + "songs": [ + { + "id": "16-1", + "slot": 1, + "title": "Mystery Box #1", + "video_file": "16-1 Mystery Box #1.mp4", + "audio_file": "16-1 Mystery Box #1.mp3", + "lyrics_file": "16-1 Mystery Box #1.jpg" + }, + { + "id": "16-2", + "slot": 2, + "title": "Hide & Seek", + "video_file": "16-2 Hide & Seek.mp4", + "audio_file": "16-2 Hide & Seek.mp3", + "lyrics_file": "16-2 Hide & Seek.jpg" + }, + { + "id": "16-3", + "slot": 3, + "title": "Rock Scissors Paper #1", + "video_file": "16-3 Rock Scissors Paper #1.mp4", + "audio_file": "16-3 Rock Scissors Paper #1.mp3", + "lyrics_file": "16-3 Rock Scissors Paper #1.jpg" + } + ] + }, + { + "number": 17, + "kind": "review", + "category": "复习13-16周", + "songs": [], + "review_from": 13, + "review_to": 16 + }, + { + "number": 18, + "kind": "review", + "category": "复习13-16周", + "songs": [], + "review_from": 13, + "review_to": 16 + }, + { + "number": 19, + "kind": "lesson", + "category": "反义词\n身体部位", + "songs": [ + { + "id": "19-1", + "slot": 1, + "title": "Head Shoulders Knees & Toes", + "video_file": "19-1 Head Shoulders Knees & Toes.mp4", + "audio_file": "19-1 Head Shoulders Knees & Toes.mp3", + "lyrics_file": "19-1 Head Shoulders Knees & Toes.jpg" + }, + { + "id": "19-2", + "slot": 2, + "title": "Uh Huh", + "video_file": "19-2 Uh Huh.mp4", + "audio_file": "19-2 Uh Huh.mp3", + "lyrics_file": "19-2 Uh Huh.jpg" + }, + { + "id": "19-3", + "slot": 3, + "title": "Open Shut Them", + "video_file": "19-3 Open Shut Them.mp4", + "audio_file": "19-3 Open Shut Them.mp3", + "lyrics_file": "19-3 Open Shut Them.jpg" + } + ] + }, + { + "number": 20, + "kind": "lesson", + "category": "数字", + "songs": [ + { + "id": "20-1", + "slot": 1, + "title": "Count & Move", + "video_file": "20-1 Count & Move.mp4", + "audio_file": "20-1 Count & Move.mp3", + "lyrics_file": "20-1 Count & Move.jpg" + }, + { + "id": "20-2", + "slot": 2, + "title": "Count Down & Move", + "video_file": "20-2 Count Down & Move.mp4", + "audio_file": "20-2 Count Down & Move.mp3", + "lyrics_file": "20-2 Count Down & Move.jpg" + }, + { + "id": "20-3", + "slot": 3, + "title": "Seven Steps", + "video_file": "20-3 Seven Steps.mp4", + "audio_file": "20-3 Seven Steps.mp3", + "lyrics_file": "20-3 Seven Steps.jpg" + } + ] + }, + { + "number": 21, + "kind": "lesson", + "category": "数字", + "songs": [ + { + "id": "21-1", + "slot": 1, + "title": "Counting Bananas", + "video_file": "21-1 Counting Bananas.mp4", + "audio_file": "21-1 Counting Bananas.mp3", + "lyrics_file": "21-1 Counting Bananas.jpg" + }, + { + "id": "21-2", + "slot": 2, + "title": "One Potato Two Potatoes", + "video_file": "21-2 One Potato Two Potatoes.mp4", + "audio_file": "21-2 One Potato Two Potatoes.mp3", + "lyrics_file": "21-2 One Potato Two Potatoes.jpg" + }, + { + "id": "21-3", + "slot": 3, + "title": "Ten Little Dinosaurs", + "video_file": "21-3 Ten Little Dinosaurs.mp4", + "audio_file": "21-3 Ten Little Dinosaurs.mp3", + "lyrics_file": "21-3 Ten Little Dinosaurs.jpg" + } + ] + }, + { + "number": 22, + "kind": "lesson", + "category": "数字", + "songs": [ + { + "id": "22-1", + "slot": 1, + "title": "Ten Little Tractors", + "video_file": "22-1 Ten Little Tractors.mp4", + "audio_file": "22-1 Ten Little Tractors.mp3", + "lyrics_file": "22-1 Ten Little Tractors.jpg" + }, + { + "id": "22-2", + "slot": 2, + "title": "Ten In The Bed", + "video_file": "22-2 Ten In The Bed.mp4", + "audio_file": "22-2 Ten In The Bed.mp3", + "lyrics_file": "22-2 Ten In The Bed.jpg" + }, + { + "id": "22-3", + "slot": 3, + "title": "How Many Fingers", + "video_file": "22-3 How Many Fingers.mp4", + "audio_file": "22-3 How Many Fingers.mp3", + "lyrics_file": "22-3 How Many Fingers.jpg" + } + ] + }, + { + "number": 23, + "kind": "review", + "category": "复习19-22周", + "songs": [], + "review_from": 19, + "review_to": 22 + }, + { + "number": 24, + "kind": "review", + "category": "复习19-22周", + "songs": [], + "review_from": 19, + "review_to": 22 + }, + { + "number": 25, + "kind": "lesson", + "category": "食物", + "songs": [ + { + "id": "25-1", + "slot": 1, + "title": "Five Little Monsters Jumping On The Bed", + "video_file": "25-1 Five Little Monsters Jumping On The Bed.mp4", + "audio_file": "25-1 Five Little Monsters Jumping On The Bed.mp3", + "lyrics_file": "25-1 Five Little Monsters Jumping On The Bed.jpg" + }, + { + "id": "25-2", + "slot": 2, + "title": "Are You Hungry", + "video_file": "25-2 Are You Hungry.mp4", + "audio_file": "25-2 Are You Hungry.mp3", + "lyrics_file": "25-2 Are You Hungry.jpg" + }, + { + "id": "25-3", + "slot": 3, + "title": "Do You Like Broccoli Ice Cream", + "video_file": "25-3 Do You Like Broccoli Ice Cream.mp4", + "audio_file": "25-3 Do You Like Broccoli Ice Cream.mp3", + "lyrics_file": "25-3 Do You Like Broccoli Ice Cream.jpg" + } + ] + }, + { + "number": 26, + "kind": "lesson", + "category": "食物", + "songs": [ + { + "id": "26-1", + "slot": 1, + "title": "Do You Like Spaghetti Yogurt", + "video_file": "26-1 Do You Like Spaghetti Yogurt.mp4", + "audio_file": "26-1 Do You Like Spaghetti Yogurt.mp3", + "lyrics_file": "26-1 Do You Like Spaghetti Yogurt.jpg" + }, + { + "id": "26-2", + "slot": 2, + "title": "Who Took The Cookie", + "video_file": "26-2 Who Took The Cookie.mp4", + "audio_file": "26-2 Who Took The Cookie.mp3", + "lyrics_file": "26-2 Who Took The Cookie.jpg" + }, + { + "id": "26-3", + "slot": 3, + "title": "Apples & Bananas", + "video_file": "26-3 Apples & Bananas.mp4", + "audio_file": "26-3 Apples & Bananas.mp3", + "lyrics_file": "26-3 Apples & Bananas.jpg" + } + ] + }, + { + "number": 27, + "kind": "lesson", + "category": "食物", + "songs": [ + { + "id": "27-1", + "slot": 1, + "title": "The Muffin Man", + "video_file": "27-1 The Muffin Man.mp4", + "audio_file": "27-1 The Muffin Man.mp3", + "lyrics_file": "27-1 The Muffin Man.jpg" + }, + { + "id": "27-2", + "slot": 2, + "title": "Peanut Butter & Jelly", + "video_file": "27-2 Peanut Butter & Jelly.mp4", + "audio_file": "27-2 Peanut Butter & Jelly.mp3", + "lyrics_file": "27-2 Peanut Butter & Jelly.jpg" + }, + { + "id": "27-3", + "slot": 3, + "title": "The Ice Cream Song", + "video_file": "27-3 The Ice Cream Song.mp4", + "audio_file": "27-3 The Ice Cream Song.mp3", + "lyrics_file": "27-3 The Ice Cream Song.jpg" + } + ] + }, + { + "number": 28, + "kind": "lesson", + "category": "颜色\n形状", + "songs": [ + { + "id": "28-1", + "slot": 1, + "title": "I See Something Blue", + "video_file": "28-1 I See Something Blue.mp4", + "audio_file": "28-1 I See Something Blue.mp3", + "lyrics_file": "28-1 I See Something Blue.jpg" + }, + { + "id": "28-2", + "slot": 2, + "title": "What's Your Favorite Color", + "video_file": "28-2 What's Your Favorite Color.mp4", + "audio_file": "28-2 What's Your Favorite Color.mp3", + "lyrics_file": "28-2 What's Your Favorite Color.jpg" + }, + { + "id": "28-3", + "slot": 3, + "title": "The Shape Song #1", + "video_file": "28-3 The Shape Song.mp4", + "audio_file": "28-3 The Shape Song.mp3", + "lyrics_file": "28-3 The Shape Song.jpg" + } + ] + }, + { + "number": 29, + "kind": "review", + "category": "复习25-28周", + "songs": [], + "review_from": 25, + "review_to": 28 + }, + { + "number": 30, + "kind": "review", + "category": "复习25-28周", + "songs": [], + "review_from": 25, + "review_to": 28 + }, + { + "number": 31, + "kind": "lesson", + "category": "交通工具", + "songs": [ + { + "id": "31-1", + "slot": 1, + "title": "The Shape Song #2", + "video_file": "31-1 The Shape Song.mp4", + "audio_file": "31-1 The Shape Song.mp3", + "lyrics_file": "31-1 The Shape Song.jpg" + }, + { + "id": "31-2", + "slot": 2, + "title": "Row Row Row Your Boat", + "video_file": "31-2 Row Row Row Your Boat.mp4", + "audio_file": "31-2 Row Row Row Your Boat.mp3", + "lyrics_file": "31-2 Row Row Row Your Boat.jpg" + }, + { + "id": "31-3", + "slot": 3, + "title": "A Sailor Went To Sea", + "video_file": "31-3 A Sailor Went To Sea.mp4", + "audio_file": "31-3 A Sailor Went To Sea.mp3", + "lyrics_file": "31-3 A Sailor Went To Sea.jpg" + } + ] + }, + { + "number": 32, + "kind": "lesson", + "category": "日常生活\n好习惯", + "songs": [ + { + "id": "32-1", + "slot": 1, + "title": "The Wheels On The Bus", + "video_file": "32-1 The Wheels On The Bus.mp4", + "audio_file": "32-1 The Wheels On The Bus.mp3", + "lyrics_file": "32-1 The Wheels On The Bus.jpg" + }, + { + "id": "32-2", + "slot": 2, + "title": "See You Later Alligator", + "video_file": "32-2 See You Later Alligator.mp4", + "audio_file": "32-2 See You Later Alligator.mp3", + "lyrics_file": "32-2 See You Later Alligator.jpg" + }, + { + "id": "32-3", + "slot": 3, + "title": "Hello", + "video_file": "32-3 Hello.mp4", + "audio_file": "32-3 Hello.mp3", + "lyrics_file": "32-3 Hello.jpg" + } + ] + }, + { + "number": 33, + "kind": "lesson", + "category": "日常生活\n好习惯", + "songs": [ + { + "id": "33-1", + "slot": 1, + "title": "Clean Up", + "video_file": "33-1 Clean Up.mp4", + "audio_file": "33-1 Clean Up.mp3", + "lyrics_file": "33-1 Clean Up.jpg" + }, + { + "id": "33-2", + "slot": 2, + "title": "Brush Your Teeth", + "video_file": "33-2 Brush Your Teeth.mp4", + "audio_file": "33-2 Brush Your Teeth.mp3", + "lyrics_file": "33-2 Brush Your Teeth.jpg" + }, + { + "id": "33-3", + "slot": 3, + "title": "The Bath Song", + "video_file": "33-3 The Bath Song.mp4", + "audio_file": "33-3 The Bath Song.mp3", + "lyrics_file": "33-3 The Bath Song.jpg" + } + ] + }, + { + "number": 34, + "kind": "lesson", + "category": "日常生活\n好习惯", + "songs": [ + { + "id": "34-1", + "slot": 1, + "title": "This is the Way", + "video_file": "34-1 This is the Way.mp4", + "audio_file": "34-1 This is the Way.mp3", + "lyrics_file": "34-1 This is the Way.jpg" + }, + { + "id": "34-2", + "slot": 2, + "title": "This Is The Way We Get Dressed", + "video_file": "34-2 This Is The Way We Get Dressed.mp4", + "audio_file": "34-2 This Is The Way We Get Dressed.mp3", + "lyrics_file": "34-2 This Is The Way We Get Dressed.jpg" + }, + { + "id": "34-3", + "slot": 3, + "title": "Put On Your Shoes", + "video_file": "34-3 Put On Your Shoes.mp4", + "audio_file": "34-3 Put On Your Shoes.mp3", + "lyrics_file": "34-3 Put On Your Shoes.jpg" + } + ] + }, + { + "number": 35, + "kind": "review", + "category": "复习31-34周", + "songs": [], + "review_from": 31, + "review_to": 34 + }, + { + "number": 36, + "kind": "review", + "category": "复习31-34周", + "songs": [], + "review_from": 31, + "review_to": 34 + }, + { + "number": 37, + "kind": "lesson", + "category": "晚安曲", + "songs": [ + { + "id": "37-1", + "slot": 1, + "title": "Sweet Dreams", + "video_file": "37-1 Sweet Dreams.mp4", + "audio_file": "37-1 Sweet Dreams.mp3", + "lyrics_file": "37-1 Sweet Dreams.jpg" + }, + { + "id": "37-2", + "slot": 2, + "title": "Twinkle Twinkle Little Star", + "video_file": "37-2 Twinkle Twinkle Little Star.mp4", + "audio_file": "37-2 Twinkle Twinkle Little Star.mp3", + "lyrics_file": "37-2 Twinkle Twinkle Little Star.jpg" + }, + { + "id": "37-3", + "slot": 3, + "title": "My Teddy Bear", + "video_file": "37-3 My Teddy Bear.mp4", + "audio_file": "37-3 My Teddy Bear.mp3", + "lyrics_file": "37-3 My Teddy Bear.jpg" + } + ] + }, + { + "number": 38, + "kind": "lesson", + "category": "天气", + "songs": [ + { + "id": "38-1", + "slot": 1, + "title": "Rain Rain Go Away", + "video_file": "38-1 Rain Rain Go Away.mp4", + "audio_file": "38-1 Rain Rain Go Away.mp3", + "lyrics_file": "38-1 Rain Rain Go Away.jpg" + }, + { + "id": "38-2", + "slot": 2, + "title": "I'm A Little Snowman", + "video_file": "38-2 I'm A Little Snowman.mp4", + "audio_file": "38-2 I'm A Little Snowman.mp3", + "lyrics_file": "38-2 I'm A Little Snowman.jpg" + }, + { + "id": "38-3", + "slot": 3, + "title": "Mr Golden Sun", + "video_file": "38-3 Mr Golden Sun.mp4", + "audio_file": "38-3 Mr Golden Sun.mp3", + "lyrics_file": "38-3 Mr Golden Sun.jpg" + } + ] + }, + { + "number": 39, + "kind": "lesson", + "category": "时间", + "songs": [ + { + "id": "39-1", + "slot": 1, + "title": "How's The Weather", + "video_file": "39-1 How's The Weather.mp4", + "audio_file": "39-1 How's The Weather.mp3", + "lyrics_file": "39-1 How's The Weather.jpg" + }, + { + "id": "39-2", + "slot": 2, + "title": "Little Snowflake", + "video_file": "39-2 Little Snowflake.mp4", + "audio_file": "39-2 Little Snowflake.mp3", + "lyrics_file": "39-2 Little Snowflake.jpg" + }, + { + "id": "39-3", + "slot": 3, + "title": "Days Of The Week", + "video_file": "39-3 Days Of The Week.mp4", + "audio_file": "39-3 Days Of The Week.mp3", + "lyrics_file": "39-3 Days Of The Week.jpg" + } + ] + }, + { + "number": 40, + "kind": "lesson", + "category": "圣诞节", + "songs": [ + { + "id": "40-1", + "slot": 1, + "title": "The Months Chant", + "video_file": "40-1 The Months Chant.mp4", + "audio_file": "40-1 The Months Chant.mp3", + "lyrics_file": "40-1 The Months Chant.jpg" + }, + { + "id": "40-2", + "slot": 2, + "title": "Hello Reindeer", + "video_file": "40-2 Hello Reindeer.mp4", + "audio_file": "40-2 Hello Reindeer.mp3", + "lyrics_file": "40-2 Hello Reindeer.jpg" + }, + { + "id": "40-3", + "slot": 3, + "title": "Decorate The Christmas Tree", + "video_file": "40-3 Decorate The Christmas Tree.mp4", + "audio_file": "40-3 Decorate The Christmas Tree.mp3", + "lyrics_file": "40-3 Decorate The Christmas Tree.jpg" + } + ] + }, + { + "number": 41, + "kind": "review", + "category": "复习37-40周", + "songs": [], + "review_from": 37, + "review_to": 40 + }, + { + "number": 42, + "kind": "review", + "category": "复习37-40周", + "songs": [], + "review_from": 37, + "review_to": 40 + }, + { + "number": 43, + "kind": "lesson", + "category": "圣诞节", + "songs": [ + { + "id": "43-1", + "slot": 1, + "title": "We Wish You A Merry Christmas", + "video_file": "43-1 We Wish You A Merry Christmas.mp4", + "audio_file": "43-1 We Wish You A Merry Christmas.mp3", + "lyrics_file": "43-1 We Wish You A Merry Christmas.jpg" + }, + { + "id": "43-2", + "slot": 2, + "title": "Jingle Bells", + "video_file": "43-2 Jingle Bells.mp4", + "audio_file": "43-2 Jingle Bells.mp3", + "lyrics_file": "43-2 Jingle Bells.jpg" + }, + { + "id": "43-3", + "slot": 3, + "title": "Santa Where Are You", + "video_file": "43-3 Santa Where Are You.mp4", + "audio_file": "43-3 Santa Where Are You.mp3", + "lyrics_file": "43-3 Santa Where Are You.jpg" + } + ] + }, + { + "number": 44, + "kind": "lesson", + "category": "万圣节", + "songs": [ + { + "id": "44-1", + "slot": 1, + "title": "Santa's On His Way", + "video_file": "44-1 Santa's On His Way.mp4", + "audio_file": "44-1 Santa's On His Way.mp3", + "lyrics_file": "44-1 Santa's On His Way.jpg" + }, + { + "id": "44-2", + "slot": 2, + "title": "Go Away", + "video_file": "44-2 Go Away.mp4", + "audio_file": "44-2 Go Away.mp3", + "lyrics_file": "44-2 Go Away.jpg" + }, + { + "id": "44-3", + "slot": 3, + "title": "Knock Knock Trick Or Treat", + "video_file": "44-3 Knock Knock Trick Or Treat.mp4", + "audio_file": "44-3 Knock Knock Trick Or Treat.mp3", + "lyrics_file": "44-3 Knock Knock Trick Or Treat.jpg" + } + ] + }, + { + "number": 45, + "kind": "lesson", + "category": "童谣", + "songs": [ + { + "id": "45-1", + "slot": 1, + "title": "One For You One For Me", + "video_file": "45-1 One For You One For Me.mp4", + "audio_file": "45-1 One For You One For Me.mp3", + "lyrics_file": "45-1 One For You One For Me.jpg" + }, + { + "id": "45-2", + "slot": 2, + "title": "Five Creepy Spiders", + "video_file": "45-2 Five Creepy Spiders.mp4", + "audio_file": "45-2 Five Creepy Spiders.mp3", + "lyrics_file": "45-2 Five Creepy Spiders.jpg" + }, + { + "id": "45-3", + "slot": 3, + "title": "Jack & Jill", + "video_file": "45-3 Jack & Jill.mp4", + "audio_file": "45-3 Jack & Jill.mp3", + "lyrics_file": "45-3 Jack & Jill.jpg" + } + ] + }, + { + "number": 46, + "kind": "lesson", + "category": "童谣", + "songs": [ + { + "id": "46-1", + "slot": 1, + "title": "Humpty Dumpty", + "video_file": "46-1 Humpty Dumpty.mp4", + "audio_file": "46-1 Humpty Dumpty.mp3", + "lyrics_file": "46-1 Humpty Dumpty.jpg" + }, + { + "id": "46-2", + "slot": 2, + "title": "Skidamarink", + "video_file": "46-2 Skidamarink.mp4", + "audio_file": "46-2 Skidamarink.mp3", + "lyrics_file": "46-2 Skidamarink.jpg" + }, + { + "id": "46-3", + "slot": 3, + "title": "Down By The Bay", + "video_file": "46-3 Down By The Bay.mp4", + "audio_file": "46-3 Down By The Bay.mp3", + "lyrics_file": "46-3 Down By The Bay.jpg" + } + ] + }, + { + "number": 47, + "kind": "review", + "category": "复习43-46周", + "songs": [], + "review_from": 43, + "review_to": 46 + }, + { + "number": 48, + "kind": "review", + "category": "复习43-46周", + "songs": [], + "review_from": 43, + "review_to": 46 + }, + { + "number": 49, + "kind": "lesson", + "category": "字母", + "songs": [ + { + "id": "49-1", + "slot": 1, + "title": "Hickory Dickory Crash", + "video_file": "49-1 Hickory Dickory Crash.mp4", + "audio_file": "49-1 Hickory Dickory Crash.mp3", + "lyrics_file": "49-1 Hickory Dickory Crash.jpg" + }, + { + "id": "49-2", + "slot": 2, + "title": "The Alphabet Song", + "video_file": "49-2 The Alphabet Song.mp4", + "audio_file": "49-2 The Alphabet Song.mp3", + "lyrics_file": "49-2 The Alphabet Song.jpg" + }, + { + "id": "49-3", + "slot": 3, + "title": "The Alphabet Chant", + "video_file": "49-3 The Alphabet Chant.mp4", + "audio_file": "49-3 The Alphabet Chant.mp3", + "lyrics_file": "49-3 The Alphabet Chant.jpg" + } + ] + }, + { + "number": 50, + "kind": "lesson", + "category": "", + "songs": [ + { + "id": "50-1", + "slot": 1, + "title": "Take Me Out To The Ball Game", + "video_file": "50-1 Take Me Out To The Ball Game.mp4", + "audio_file": "50-1 Take Me Out To The Ball Game.mp3", + "lyrics_file": "50-1 Take Me Out To The Ball Game.jpg" + } + ] + } + ] +} diff --git a/deploy/mariadb/01-create-sss-database.sql b/deploy/mariadb/01-create-sss-database.sql new file mode 100644 index 0000000..05de195 --- /dev/null +++ b/deploy/mariadb/01-create-sss-database.sql @@ -0,0 +1,7 @@ +-- Run this once in Synology phpMyAdmin as a MariaDB administrator. +-- This creates only the isolated database. The application account is created +-- separately after the SSS service's final network location is decided. + +CREATE DATABASE IF NOT EXISTS `sss_checkin` + CHARACTER SET utf8mb4 + COLLATE utf8mb4_unicode_ci; diff --git a/deploy/mariadb/README.md b/deploy/mariadb/README.md new file mode 100644 index 0000000..3318435 --- /dev/null +++ b/deploy/mariadb/README.md @@ -0,0 +1,11 @@ +# SSS MariaDB bootstrap + +Run `01-create-sss-database.sql` in Synology phpMyAdmin using a MariaDB +administrator. It creates the dedicated `sss_checkin` database with UTF-8 +support suitable for the Chinese interface and role names. + +Do not create an application account with host `%`. The account and grants +must be created after the SSS application has been migrated from SQLite and +its final location is known. The intended final layout is the SSS service and +MariaDB both on the NAS, so the account can be restricted to that application +network rather than opened to every LAN device. diff --git a/docs/产品设计.md b/docs/产品设计.md new file mode 100644 index 0000000..07e62cf --- /dev/null +++ b/docs/产品设计.md @@ -0,0 +1,83 @@ +# SSS 50周打卡工具产品设计 + +## 核心体验 + +宝宝在主页面完成所有日常操作:看视频、听音频、看歌词和领取红花。每首歌有自己的媒体卡,不需要先选歌;只有家长从设置中主动进入统计页或资源库时才离开主页面。 + +系统只维护一个宝宝的学习进度,不再提供多孩子档案。 + +## 身份与设备 + +- 首次访问必须选择当前设备对应的身份:宝宝、爸爸、妈妈、爷爷、奶奶、外公、外婆。 +- 浏览器生成并保存设备标识,服务器保存“设备标识 → 身份”的映射。 +- 以后从同一浏览器访问时自动恢复身份。 +- 点击右上角当前角色会打开角色切换,修改后更新设备映射;已有历史播放仍保留播放发生时的身份,不随映射变化。 +- 清除浏览器网站数据或更换浏览器后,会被视为新设备,需要重新选择身份。 + +## 播放与小红花打卡 + +- 每首歌独立展示“视频 / 音频 / 歌词”三个标签,从上到下依次排列,不再使用一个公共播放器切歌。 +- 视频和音频共用相同的 16:9 媒体框尺寸;切换两种模式时,页面高度和后续内容位置保持不变。 +- 音频点击画面中央即可播放或暂停,自定义进度条位于画面底部,不再额外占用一行,也不提供上一首、下一首按钮。 +- 点击某一张歌曲卡片的视频或音频后,该媒体自动单曲循环;成长足迹下方另设整周音频播放控制,从第一首开始依次播放,最后一首结束后回到第一首循环。 +- 歌词是每首歌对应的一张图片,可在媒体卡内原位查看;歌词允许按图片内容改变高度并滚动。 +- 媒体标签只改变当前看见的面板,不暂停同一首正在播放的视频或音频;因此打开歌词时声音继续。只有主动播放另一种媒体或另一首歌时,才暂停原声源。 +- 播放开始时建立记录,只有播放器触发完整播放结束后才计为一次完成播放,并解锁该歌曲的一次红花领取资格。 +- 每首歌在每个学习日最多有 3 朵红花;一遍完整播放只能兑换其中一朵。 +- 同一首歌相邻两次领取默认至少间隔 60 分钟,设置中可选 30、60、90 或 120 分钟;不同歌曲互不占用彼此的间隔。 +- 孩子可以亲手点击每张歌曲卡片下方正在跳动的大尺寸红花领取奖励,并看到居中的红花、光圈、闪光和花瓣动画。 +- 红花未解锁、冷却尚未结束、前一朵未领取或已经领取时,按钮仍可点击并明确说明原因。 +- 若已有资格但离开页面时没有点击,下次进入时系统会检查全部历史学习日并自动补记,同时播放“努力没有漏掉”的补领仪式;补学后跨天也不会遗漏。 +- 主页面和资源库的视频都使用按需读取:打开页面或切换标签不会设置视频地址,只有点击播放才向 NAS 请求视频数据。主页音频也只在点击播放后读取。 +- 当前歌单全部歌曲至少完整播放一遍后,解锁第一朵整轮红花;全部歌曲分别完成第二遍、第三遍后继续解锁第二、第三朵。孩子在歌单下方亲手领取,每个学习日最多 3 朵。 +- 整轮红花沿用领取间隔。多台设备并发领取时,由数据库事务和唯一约束串行裁决;冷却按整个家庭共享,后到的请求会收到已经领取或仍在冷却的提示。 +- 每个完成播放保存:歌曲、课程周、学习日期、视频或音频、开始时间、完成时间、时长、设备和身份。 + +## 课程规则 + +- 保留原始课程表的 50 周结构,共 100 首唯一歌曲。 +- 开课日期固定为 2026 年 10 月 12 日;当天至第 7 天为第 1 周,之后每 7 天自动进入下一周,超过计划长度时停留在第 50 周。 +- 每次打开主页默认显示今天对应的课程周,不依赖手工推进。 +- 周次浏览与成长日历解耦:上一周、下一周和 50 周地图都能进入任意周。过去周进入补学习;未来周显示为提前试听,允许播放但不产生红花领取资格,预习记录也不会在未来自动转成打卡。 +- 学习周直接列出本周歌曲。 +- 复习周列出其指定范围内的学习周歌曲,例如第 5 周展示第 1–4 周共 12 首歌。 +- 成长日历展示截至今天的连续 14 天,固定为 2 行 × 7 天;今天始终位于第二行第 7 列,星期标题根据今天动态平移。整轮完成、部分学习、遗漏待补和开课前日期有明显不同的视觉状态。 +- 点击开课日之后、今天之前的日期会进入补学习模式;播放和红花记在所选学习日期,同时保留真实操作时间。 +- 50 周网格中只能进入已经开始的周,点击后选择该周的第一天作为补学日期。 + +## 页面结构 + +### 主页面 + +- 顶部:标题为“SSS 50 周打卡”,右侧只显示当前设备角色;点击角色只进入角色切换,不打开设置。 +- 周概览:当前周、今日红花数、今日完成播放次数、前后周切换。 +- 十四天成长:2 行 × 7 天的红花与学习进度,遗漏日期可直接点入补学。 +- 播放模式:成长足迹下方的一键控制负责整周音频顺序循环,并显示当前歌曲与暂停状态。 +- 歌曲媒体卡:本周每首歌一张卡片,显示歌名、视频/音频/歌词标签、固定尺寸媒体框和卡片下方 3 个大红花;红花占据卡片中部约一半宽度,下方分别标注上午领取、下午领取、晚上领取,可领取时轻微跳动。 +- 整轮奖励:歌单下方摆放占据约 85% 宽度的 3 朵大花,并提示需要把当前歌单全部听完才能领取;完成对应轮次后点亮,由宝宝亲手领取。 +- 50 周地图:快速查看和切换课程周。 +- 页面底部:单独放置齿轮设置入口;开课日期灰色只读,避免宝宝或家长误改。 + +### 统计页面 + +- 最近 42 天日历和逐日播放、红花、时长、操作者。 +- 50 周完成播放、红花、活跃天和覆盖歌曲统计。 +- 每首歌的视频/音频开始次数、完成次数、红花数、操作者和最后播放时间。 +- 每位操作者的完成播放与领取红花次数。 +- 最近歌曲红花和整轮红花的时间、歌曲及操作者。 + +### 全部资源库 + +- 从家长设置进入,集中列出 100 首唯一歌曲的编号、原始周次、主题和三类资源完整状态。 +- 支持按歌名、编号、主题和文件名搜索,并可按周次或资源是否齐全筛选。 +- 初始只展示歌曲卡片;点击一首歌后,直接在该卡片下方展开“视频 / 音频 / 歌词”面板,点击另一首时自动收起上一首,页面不再保留固定在顶部的公共播放器。 +- 展开面板沿用首页的 16:9 播放样式,只展示视频、音频和歌词,不再显示独立资料页或真实文件名。 +- 视频和音频均不在列表或展开时预读;只有家长点击播放后才读取单个文件。歌词也只在打开歌词标签时加载。 +- 资源库用于家长查找和试听,不产生课程播放或红花记录,避免预览资源误触发宝宝打卡。 + +## 数据与安全边界 + +- 资源入口固定为一个根目录,其下为 `视频/`、`音频/`、`歌词/`。 +- 应用按稳定的 `周次-序号` 匹配三种资源,不修改或复制原文件。 +- 资源目录只读挂载;应用只写自己的 SQLite 数据库。 +- 仅为家庭局域网设计,不提供公网认证,不应直接暴露到互联网。 diff --git a/docs/群晖部署说明.md b/docs/群晖部署说明.md new file mode 100644 index 0000000..ea4e929 --- /dev/null +++ b/docs/群晖部署说明.md @@ -0,0 +1,102 @@ +# 群晖部署说明 + +## 前提 + +- 群晖已安装 Container Manager,或系统可运行 Docker Compose。 +- 资源根目录下存在 `视频`、`音频`、`歌词` 三个子目录,每类各 100 个课程文件。 +- 群晖使用固定局域网地址或路由器 DHCP 地址保留。 + +## 1. 确认群晖本机路径 + +开发机看到的资源路径是: + +```text +/Volumes/study/Assets/SSS50 +``` + +容器不能使用这个 Mac 路径。若 `study` 是群晖共享文件夹,群晖上的路径通常为: + +```text +/volume1/study/Assets/SSS50 +``` + +请在 DSM 中确认它实际位于哪个存储空间;如果不是 `volume1`,必须修改为真实路径。 + +## 2. 放置项目并配置 + +把整个 `project_sss` 目录复制到群晖,例如: + +```text +/volume1/docker/sss-checkin/app +``` + +进入该目录,创建本机配置: + +```bash +cp .env.example .env +``` + +检查 `.env`: + +```dotenv +SSS_ASSET_PATH=/volume1/study/Assets/SSS50 +SSS_DATA_PATH=/volume1/docker/sss-checkin/data +``` + +`SSS_ASSET_PATH` 是三类课程资源的共同根目录;`SSS_DATA_PATH` 用于持久保存开课日期、设备身份、播放和小红花记录。 + +## 3. 启动与验证 + +```bash +docker compose up -d --build +curl http://127.0.0.1:8787/api/health +``` + +镜像会自动安装 ffmpeg,用于在第一次点击“一键播放”时按需生成本周的循环音频合辑;合辑缓存只会写入 `SSS_DATA_PATH/weekly-mixes`,不会改动课程原始音频。 + +健康接口应返回 `status: ok`,并显示 video、audio、lyrics 都为 100。随后让手机连接家庭 Wi-Fi,打开: + +```text +http://群晖IP:8787 +``` + +第一次打开时选择这台设备的身份,然后在设置中确认开课日期。不同手机或不同浏览器会各自选择并记住自己的身份,课程周次则由全家共用的开课日期自动计算。 + +家长可从设置进入“全部资源库”,搜索全部 100 首歌曲并检查三类资源。资源库和主播放器的视频均为点击后才读取,不会在页面打开时预先缓存视频。 + +## 4. 权限 + +- 容器只需读取 `SSS_ASSET_PATH`,Compose 已按只读方式挂载到 `/assets`。 +- `SSS_DATA_PATH` 必须可读写,SQLite 数据库位于其中的 `sss.db`。 +- 若健康接口显示 `degraded`,优先检查目录拼写、共享文件夹权限以及三类资源数量。 + +## 5. 更新资源映射 + +课程文件名发生变化后,应在开发机重新生成 `curriculum.json` 并连同项目一起部署: + +```bash +python3 scripts/build_curriculum.py \ + 'source/SSS 儿歌 50周打卡表.xlsx' \ + '/Volumes/study/Assets/SSS50' \ + curriculum.json +``` + +脚本会要求 Excel 中的每首歌都同时存在视频、音频和歌词;缺少任意一种资源时会停止并报告课程编号。 + +## 6. 备份 + +可以短暂停止容器后复制数据库: + +```bash +docker compose stop +cp /volume1/docker/sss-checkin/data/sss.db /目标备份目录/sss-日期.db +docker compose start +``` + +建议用群晖任务计划每天备份并保留最近若干份。开课日期、身份映射、播放历史和红花记录都在同一个数据库中。 + +## 7. 局域网安全 + +- 不要把 8787 端口直接映射到公网。 +- 应用没有面向公网的账号密码体系,只应在可信家庭局域网使用。 +- 若以后确实需要外网访问,优先通过 VPN 或 Tailscale 进入家庭网络。 diff --git a/public/app.js b/public/app.js new file mode 100644 index 0000000..0ffeb44 --- /dev/null +++ b/public/app.js @@ -0,0 +1,1099 @@ +const CHILD_MODE_STORAGE_KEY = "sss-child-mode"; + +const appState = { + deviceId: getDeviceId(), + childMode: getChildMode(), + data: null, + studyDate: null, + viewWeek: null, + cardModes: {}, + playRecords: {}, + playback: { + mode: null, + mediaType: null, + songId: null, + playlistIndex: 0, + expected: null, + }, + fetchedAt: Date.now(), +}; + +const elements = { + identityButton: document.querySelector("#identity-button"), + bottomSettingsButton: document.querySelector("#bottom-settings-button"), + identityEmoji: document.querySelector("#identity-emoji"), + identityLabel: document.querySelector("#identity-label"), + weekKind: document.querySelector("#week-kind"), + weekTitle: document.querySelector("#week-title"), + weekCategory: document.querySelector("#week-category"), + studyDateLabel: document.querySelector("#study-date-label"), + previousWeek: document.querySelector("#previous-week"), + nextWeek: document.querySelector("#next-week"), + currentWeek: document.querySelector("#current-week"), + todayCheckins: document.querySelector("#today-checkins"), + todayPlays: document.querySelector("#today-plays"), + dayFlowerLabel: document.querySelector("#day-flower-label"), + dayPlayLabel: document.querySelector("#day-play-label"), + achievementCount: document.querySelector("#achievement-count"), + progressWeekdays: document.querySelector("#progress-weekdays"), + progressGrid: document.querySelector("#progress-grid"), + playlistLoopButton: document.querySelector("#playlist-loop-button"), + playlistLoopStatus: document.querySelector("#playlist-loop-status"), + weeklyLoopPlayer: document.querySelector("#weekly-loop-player"), + playerHeading: document.querySelector("#player-heading"), + songCards: document.querySelector("#song-cards"), + roundCheckin: document.querySelector("#round-checkin"), + roundFlowers: document.querySelector("#round-flowers"), + roundHint: document.querySelector("#round-hint"), + weekGrid: document.querySelector("#week-grid"), + planSummary: document.querySelector("#plan-summary"), + assetStatus: document.querySelector("#asset-status"), + identityDialog: document.querySelector("#identity-dialog"), + identityOptions: document.querySelector("#identity-options"), + settingsDialog: document.querySelector("#settings-dialog"), + settingsForm: document.querySelector("#settings-form"), + closeSettings: document.querySelector("#close-settings"), + startDate: document.querySelector("#start-date"), + checkinWindow: document.querySelector("#checkin-window"), + childMode: document.querySelector("#child-mode"), + toast: document.querySelector("#toast"), + celebration: document.querySelector("#celebration"), + celebrationTitle: document.querySelector("#celebration-title"), + celebrationCopy: document.querySelector("#celebration-copy"), + startupStatus: document.querySelector("#startup-status"), +}; + +function getDeviceId() { + let id = localStorage.getItem("sss-device-id"); + if (!id) { + const browserCrypto = window.crypto; + id = browserCrypto && browserCrypto.randomUUID + ? browserCrypto.randomUUID() + : `device-${Date.now()}-${Math.random().toString(36).slice(2)}`; + localStorage.setItem("sss-device-id", id); + } + return id; +} + +function isIPhone5sOnIOS10() { + const userAgent = navigator.userAgent || ""; + const screenWidth = Math.min(window.screen.width, window.screen.height); + const screenHeight = Math.max(window.screen.width, window.screen.height); + // Safari does not expose an iPhone model in its UA. 320 × 568 @ iOS 10 + // identifies the 5s-sized device family, which is the intended target. + return /iPhone/.test(userAgent) + && /OS 10[_\.]/.test(userAgent) + && screenWidth === 320 + && screenHeight === 568; +} + +function getChildMode() { + const stored = localStorage.getItem(CHILD_MODE_STORAGE_KEY); + if (stored === "1") return true; + if (stored === "0") return false; + return isIPhone5sOnIOS10(); +} + +function setChildMode(enabled) { + const next = Boolean(enabled); + if (appState.childMode !== next) { + pauseAll(); + resetPlaybackMode(); + appState.cardModes = {}; + } + appState.childMode = next; + localStorage.setItem(CHILD_MODE_STORAGE_KEY, next ? "1" : "0"); +} + +function applyChildMode() { + document.body.classList.toggle("child-mode", appState.childMode); + elements.childMode.checked = appState.childMode; +} + +function escapeHtml(value) { + return String(value == null ? "" : value) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +function forEachNode(nodes, callback) { + for (let index = 0; index < nodes.length; index += 1) { + callback(nodes[index], index); + } +} + +function isModalOpen(modal) { + return modal && !modal.hasAttribute("hidden"); +} + +function showModal(modal) { + if (!modal) return; + modal.removeAttribute("hidden"); + modal.style.display = "flex"; + document.body.classList.add("modal-open"); +} + +function hideModal(modal) { + if (!modal) return; + modal.setAttribute("hidden", "hidden"); + modal.style.display = "none"; + if (!isModalOpen(elements.identityDialog) && !isModalOpen(elements.settingsDialog)) { + document.body.classList.remove("modal-open"); + } +} + +function localDate(value) { + return new Date(`${value}T12:00:00`); +} + +function dateString(value) { + const year = value.getFullYear(); + const month = String(value.getMonth() + 1).padStart(2, "0"); + const day = String(value.getDate()).padStart(2, "0"); + return `${year}-${month}-${day}`; +} + +function shiftDate(value, days) { + const next = localDate(value); + next.setDate(next.getDate() + days); + return dateString(next); +} + +function formatStudyDate(value) { + return new Intl.DateTimeFormat("zh-CN", { + month: "long", + day: "numeric", + weekday: "short", + }).format(localDate(value)); +} + +async function request(path, options = {}) { + const requestOptions = {}; + Object.keys(options).forEach((key) => { + requestOptions[key] = options[key]; + }); + requestOptions.headers = { "Content-Type": "application/json" }; + Object.keys(options.headers || {}).forEach((key) => { + requestOptions.headers[key] = options.headers[key]; + }); + const response = await fetch(path, requestOptions); + const payload = await response.json(); + if (!response.ok) throw new Error(payload.error || "请求失败"); + return payload; +} + +function stateQuery(recover) { + const pairs = [ + ["device_id", appState.deviceId], + ["recover", recover ? "1" : "0"], + ]; + if (appState.studyDate) pairs.push(["study_date", appState.studyDate]); + if (appState.viewWeek) pairs.push(["week", appState.viewWeek]); + return pairs + .map((pair) => `${encodeURIComponent(pair[0])}=${encodeURIComponent(pair[1])}`) + .join("&"); +} + +async function loadState({ recover = true, celebrateRecovered = true } = {}) { + const requestQuery = stateQuery(recover); + try { + appState.data = await request(`/api/state?${requestQuery}`); + appState.studyDate = appState.data.study_date; + appState.viewWeek = appState.data.week.number; + appState.fetchedAt = Date.now(); + render(); + elements.startupStatus.hidden = true; + if (celebrateRecovered && !appState.childMode && appState.data.recovered_awards.length) { + const awards = appState.data.recovered_awards; + const round = awards.some((award) => award.kind === "round"); + window.setTimeout(() => { + celebrate( + round ? "整轮小红花补上啦!" : `欢迎回来,补上 ${awards.length} 朵小红花!`, + "上次已经认真听完,系统没有让努力漏掉。", + ); + }, 220); + } + } catch (error) { + elements.startupStatus.hidden = false; + elements.startupStatus.textContent = "暂时无法连接学习记录,请检查家庭 Wi-Fi 后刷新页面。"; + showToast(error.message); + } +} + +function render() { + const { device, settings, week, day, weeks, actors } = appState.data; + applyChildMode(); + elements.identityEmoji.textContent = device.actor_emoji || "●"; + elements.identityLabel.textContent = device.actor || "选择身份"; + elements.weekKind.textContent = appState.data.viewing_future + ? "提前试听" + : appState.data.is_today + ? "今日学习" + : "补学习"; + elements.weekTitle.textContent = `第 ${week.number} 周`; + elements.weekCategory.textContent = (week.category || "综合复习").replace(/\n/g, " · "); + elements.studyDateLabel.textContent = appState.data.viewing_future + ? `开课时间 · ${formatStudyDate(week.scheduled_start)}` + : `${appState.data.is_today ? "今天" : "补学日"} · ${formatStudyDate(appState.data.study_date)}`; + elements.playerHeading.textContent = week.kind === "review" ? `复习第 ${week.review_from}–${week.review_to} 周` : "本周歌单"; + elements.previousWeek.disabled = week.number <= 1; + elements.nextWeek.disabled = week.number >= 50; + elements.currentWeek.hidden = appState.data.is_today; + elements.todayCheckins.textContent = day.flowers; + elements.todayPlays.textContent = day.video_plays + day.audio_plays; + elements.dayFlowerLabel.textContent = appState.data.viewing_future + ? "暂不可领" + : appState.data.is_today + ? "今日红花" + : "当日红花"; + elements.dayPlayLabel.textContent = appState.data.viewing_future + ? "预习播放" + : appState.data.is_today + ? "今日播放" + : "当日播放"; + elements.startDate.value = settings.start_date; + elements.startDate.max = appState.data.today_date; + setSelectValue(elements.checkinWindow, settings.checkin_window_minutes); + + renderIdentityOptions(actors, device.actor); + if (!appState.childMode) renderProgress(); + renderSongCards(); + renderPlaylistControl(); + if (!appState.childMode) { + renderRoundAward(); + renderWeeks(weeks); + } + + const assetsReady = week.songs.every((song) => appState.childMode + ? song.audio_available + : song.video_available && song.audio_available && song.lyrics_available, + ); + elements.assetStatus.textContent = assetsReady + ? appState.childMode ? "音频已连接" : "视频、音频和歌词已连接" + : "有课程资源未连接"; + if (device.needs_identity && !isModalOpen(elements.identityDialog)) { + showModal(elements.identityDialog); + } +} + +function setSelectValue(select, value) { + const stringValue = String(value); + const hasValue = Array.prototype.some.call(select.options, (option) => option.value === stringValue); + if (!hasValue) { + const option = document.createElement("option"); + option.value = stringValue; + option.textContent = `${stringValue} 分钟后可再领`; + select.append(option); + } + select.value = stringValue; +} + +function formatWindow(minutes) { + if (minutes === 60) return "1 小时"; + if (minutes === 120) return "2 小时"; + return `${minutes} 分钟`; +} + +function renderIdentityOptions(actors, currentActor) { + const html = actors + .map( + (actor) => ` + `, + ) + .join(""); + elements.identityOptions.innerHTML = html; + forEachNode(elements.identityOptions.querySelectorAll("[data-actor]"), (button) => { + button.addEventListener("click", () => chooseIdentity(button.dataset.actor, true)); + }); +} + +async function chooseIdentity(actor, closeFirstUse) { + if (closeFirstUse) hideModal(elements.identityDialog); + try { + const result = await request("/api/device/identity", { + method: "POST", + body: JSON.stringify({ device_id: appState.deviceId, actor }), + }); + appState.data.device.actor = result.actor; + appState.data.device.actor_emoji = result.emoji; + appState.data.device.needs_identity = false; + showToast(`这台设备已设为${actor}`); + await loadState({ celebrateRecovered: false }); + } catch (error) { + if (closeFirstUse) showModal(elements.identityDialog); + showToast(error.message); + } +} + +function renderProgress() { + const days = appState.data.progress_14d; + elements.achievementCount.textContent = days.reduce((sum, day) => sum + day.flowers, 0); + elements.progressWeekdays.innerHTML = days + .slice(0, 7) + .map((day) => `${day.weekday}`) + .join(""); + elements.progressGrid.innerHTML = days + .map((day) => { + let marker = ""; + let detail = ""; + if (day.status === "complete") { + marker = "🌸"; + detail = `${day.flowers} 朵`; + } else if (day.status === "progress") { + marker = "🌱"; + detail = `${day.completed_songs}/${day.total_songs} 首`; + } else if (day.status === "missed") { + marker = "○"; + detail = "待补"; + } else if (day.status === "today") { + marker = "+"; + detail = "今天"; + } + const selected = day.date === appState.studyDate ? "selected" : ""; + const label = `${day.date},第 ${day.week || "—"} 周,${detail || (day.status === "future" ? "未来日期" : "课程未开始")}`; + return ` + `; + }) + .join(""); + forEachNode(elements.progressGrid.querySelectorAll("[data-study-date]:not(:disabled)"), (button) => { + button.addEventListener("click", () => changeStudyDate(button.dataset.studyDate, true)); + }); +} + +function currentCooldown(song) { + const elapsed = Math.floor((Date.now() - appState.fetchedAt) / 1000); + return Math.max(0, song.cooldown_seconds - elapsed); +} + +function songFlowerFeedback(song, slot) { + if (!appState.data.can_checkin) { + return appState.data.viewing_future + ? "这是未来课程,可以先听歌;到开课后才能领取小红花" + : "请先选择这周对应的补学日期,再领取小红花"; + } + if (slot < song.checkin_count) return "这朵小红花已经领过啦"; + if (slot > song.checkin_count) return "先领取前面的小红花,再来点这一朵"; + const remaining = currentCooldown(song); + if (song.ready_count > 0 && remaining > 0) { + return `同一首歌 ${formatWindow(appState.data.settings.checkin_window_minutes)}只能领一次,还要等待 ${Math.ceil(remaining / 60)} 分钟`; + } + if (song.ready_count <= 0) return `先把 ${song.title} 完整听完一次,就能领取这朵小红花`; + return "可以领取"; +} + +function songRewardMarkup(song) { + const timeLabels = ["上午领取", "下午领取", "晚上领取"]; + const remaining = currentCooldown(song); + const canCheckin = appState.data.can_checkin && song.checkin_count < 3 && song.ready_count > 0 && remaining === 0; + const flowers = [0, 1, 2] + .map((slot) => { + const filled = slot < song.checkin_count; + const ready = slot === song.checkin_count && canCheckin; + const state = filled ? "filled" : ready ? "ready" : "empty"; + const label = filled + ? `${song.title} 第 ${slot + 1} 朵小红花已领取` + : ready + ? `领取 ${song.title} 第 ${slot + 1} 朵小红花` + : `${song.title} 第 ${slot + 1} 朵小红花尚未解锁`; + const action = ready + ? `data-checkin-song="${song.id}"` + : `data-feedback="${escapeHtml(songFlowerFeedback(song, slot))}" aria-disabled="true"`; + return ` + + + ${timeLabels[slot]} + `; + }) + .join(""); + return flowers; +} + +function cardMode(songId) { + return appState.childMode ? "audio" : appState.cardModes[songId] || "video"; +} + +function childSongCardMarkup(song, index) { + return ` +
+
+
+

歌曲 ${index + 1}

+

${escapeHtml(song.title)}

+
+ +
+
+ +
+ 0:00 + + --:-- +
+ +
+
`; +} + +function renderSongCards() { + elements.songCards.innerHTML = appState.data.week.songs + .map((song, index) => { + if (appState.childMode) return childSongCardMarkup(song, index); + const mode = cardMode(song.id); + return ` +
+
+
+

本周歌曲 ${index + 1}

+

${escapeHtml(song.title)}

+
+ +
+ +
+ + + +
+ +
+
+ + +
+ +
+ + +
+ 0:00 + + --:-- +
+ +
+ +
+ ${escapeHtml(song.title)} 歌词 +
+
+ +
+
${songRewardMarkup(song)}
+
+
`; + }) + .join(""); + bindSongCards(); +} + +function bindRewardButtons(container) { + forEachNode(container.querySelectorAll("[data-checkin-song]"), (button) => { + button.addEventListener("click", () => claimFlower(button.dataset.checkinSong)); + }); + forEachNode(container.querySelectorAll("[data-feedback]"), (button) => { + button.addEventListener("click", () => showToast(button.dataset.feedback)); + }); +} + +function bindSongCards() { + forEachNode(elements.songCards.querySelectorAll("[data-song-card]"), (card) => { + const songId = card.dataset.songCard; + const song = appState.data.week.songs.find((item) => item.id === songId); + forEachNode(card.querySelectorAll("[data-card-mode]"), (button) => { + button.addEventListener("click", () => activateCardMode(card, songId, button.dataset.cardMode)); + }); + const video = card.querySelector("[data-video-player]"); + const audio = card.querySelector("[data-audio-player]"); + const videoToggle = card.querySelector("[data-video-toggle]"); + if (video && videoToggle) { + videoToggle.addEventListener("click", () => toggleVideo(card, song)); + video.addEventListener("play", () => onMediaPlay(card, song, "video", video)); + video.addEventListener("pause", () => { + updateVideoButton(card, video); + updatePausedStatus(card, video); + renderPlaylistControl(); + }); + video.addEventListener("ended", () => completePlayback(song, "video", video)); + } + const audioToggle = card.querySelector("[data-audio-toggle]"); + const audioPanel = card.querySelector("[data-card-panel='audio']"); + const progress = card.querySelector("[data-audio-progress]"); + if (audio && audioToggle && audioPanel && progress) { + audioToggle.addEventListener("click", () => toggleAudio(card, song)); + audioPanel.addEventListener("click", (event) => { + if (event.target.closest("[data-audio-toggle], .audio-timeline")) return; + toggleAudio(card, song); + }); + audio.addEventListener("play", () => onMediaPlay(card, song, "audio", audio)); + audio.addEventListener("pause", () => { + updateAudioControls(card, audio); + updatePausedStatus(card, audio); + renderPlaylistControl(); + }); + audio.addEventListener("timeupdate", () => updateAudioControls(card, audio)); + audio.addEventListener("loadedmetadata", () => updateAudioControls(card, audio)); + audio.addEventListener("ended", () => completePlayback(song, "audio", audio)); + progress.addEventListener("input", () => { + if (Number.isFinite(audio.duration)) audio.currentTime = Number(progress.value); + }); + } + bindRewardButtons(card); + activateCardMode(card, songId, cardMode(songId), false); + }); +} + +function renderRoundAward() { + const round = appState.data.round_award; + const elapsed = Math.floor((Date.now() - appState.fetchedAt) / 1000); + const remaining = Math.max(0, round.cooldown_seconds - elapsed); + const canCheckin = appState.data.can_checkin && round.checkin_count < 3 && round.ready_count > 0 && remaining === 0; + elements.roundHint.textContent = appState.data.viewing_future + ? "可以提前听歌,等这周正式开始后再来领取大红花哦" + : `${round.total_songs} 首歌都听完,才能领取一朵大红花哦`; + elements.roundFlowers.innerHTML = [0, 1, 2] + .map((slot) => { + const filled = slot < round.checkin_count; + const ready = slot === round.checkin_count && canCheckin; + let feedback = ""; + if (!appState.data.can_checkin) { + feedback = appState.data.viewing_future + ? "这是未来课程,可以先听歌;到开课后才能领取大红花" + : "请先选择这周对应的补学日期,再领取大红花"; + } else if (filled) { + feedback = "这朵整轮小红花已经领过啦"; + } else if (slot > round.checkin_count) { + feedback = "先完成并领取前一轮的小红花"; + } else if (round.ready_count > 0 && remaining > 0) { + feedback = `整轮小红花 ${formatWindow(appState.data.settings.checkin_window_minutes)}只能领一次,还要等待 ${Math.ceil(remaining / 60)} 分钟`; + } else { + const missing = Math.max(0, round.total_songs - round.completed_songs); + feedback = `这一轮还差 ${missing} 首歌没有完整听完`; + } + const action = ready + ? "data-checkin-round" + : `data-feedback="${escapeHtml(feedback)}" aria-disabled="true"`; + const label = filled + ? `第 ${slot + 1} 朵整轮小红花已领取` + : ready + ? `领取第 ${slot + 1} 朵整轮小红花` + : `第 ${slot + 1} 朵整轮小红花尚未解锁`; + return ``; + }) + .join(""); + forEachNode(elements.roundFlowers.querySelectorAll("[data-checkin-round]"), (button) => { + button.addEventListener("click", claimRoundFlower); + }); + forEachNode(elements.roundFlowers.querySelectorAll("[data-feedback]"), (button) => { + button.addEventListener("click", () => showToast(button.dataset.feedback)); + }); +} + +function renderWeeks(weeks) { + const studied = weeks.filter((week) => week.studied).length; + elements.planSummary.textContent = `${studied}/50 周有记录`; + elements.weekGrid.innerHTML = weeks + .map((week) => { + const classes = ["week-cell", week.kind]; + if (week.studied) classes.push("studied"); + if (week.number === appState.data.week.number) classes.push("selected"); + const details = week.kind === "review" ? `第 ${week.number} 周,复习周` : `第 ${week.number} 周`; + if (!week.checkin_open) classes.push("preview"); + return ``; + }) + .join(""); + forEachNode(elements.weekGrid.querySelectorAll("[data-week-number]"), (button) => { + button.addEventListener("click", () => changeWeek(Number(button.dataset.weekNumber), true)); + }); +} + +function activateCardMode(card, songId, mode, persist = true) { + if (!["video", "audio", "lyrics"].includes(mode)) return; + if (persist) appState.cardModes[songId] = mode; + forEachNode(card.querySelectorAll("[data-card-mode]"), (button) => { + const selected = button.dataset.cardMode === mode; + button.classList.toggle("selected", selected); + button.setAttribute("aria-selected", String(selected)); + }); + forEachNode(card.querySelectorAll("[data-card-panel]"), (panel) => { + panel.hidden = panel.dataset.cardPanel !== mode; + }); + if (mode === "audio") { + const art = card.querySelector("[data-audio-art]"); + if (art && !art.getAttribute("src")) art.src = art.dataset.src; + } + if (mode === "lyrics") { + const image = card.querySelector("[data-lyrics-image]"); + if (!image.getAttribute("src")) image.src = image.dataset.src; + } +} + +function pauseAll(except = null) { + forEachNode(elements.songCards.querySelectorAll("video, audio"), (player) => { + if (player !== except) player.pause(); + }); + if (elements.weeklyLoopPlayer && elements.weeklyLoopPlayer !== except) { + elements.weeklyLoopPlayer.pause(); + } +} + +function currentPlaybackPlayer() { + if (appState.playback.mode === "weekly-loop") return elements.weeklyLoopPlayer; + const { songId, mediaType } = appState.playback; + if (!songId || !mediaType) return null; + const card = elements.songCards.querySelector(`[data-song-card="${songId}"]`); + return card ? card.querySelector(mediaType === "audio" ? "[data-audio-player]" : "[data-video-player]") : null; +} + +function renderPlaylistControl() { + const playback = appState.playback; + const player = currentPlaybackPlayer(); + const isWeeklyLoop = playback.mode === "weekly-loop"; + const isPlaylist = playback.mode === "playlist"; + const isPlaying = (isWeeklyLoop || isPlaylist) && player && !player.paused && !player.ended; + const icon = elements.playlistLoopButton.querySelector("span"); + const label = elements.playlistLoopButton.querySelector("strong"); + elements.playlistLoopButton.classList.toggle("playing", Boolean(isPlaying)); + elements.playlistLoopButton.setAttribute("aria-pressed", String(Boolean(isPlaying))); + icon.textContent = isPlaying ? "Ⅱ" : "▶"; + label.textContent = isPlaying ? "暂停播放" : (isWeeklyLoop || isPlaylist) ? "继续播放" : "一键播放"; + + const week = appState.data && appState.data.week; + const song = week ? week.songs.find((item) => item.id === playback.songId) : null; + if (isWeeklyLoop && week) { + elements.playlistLoopStatus.textContent = `${isPlaying ? "正在播放" : "已暂停"} · 第 ${week.number} 周连续循环`; + } else if (isPlaylist && song) { + elements.playlistLoopStatus.textContent = `${isPlaying ? "正在循环" : "已暂停"} · ${playback.playlistIndex + 1}/${appState.data.week.songs.length} ${song.title}`; + } else if (playback.mode === "single" && song) { + elements.playlistLoopStatus.textContent = `单曲循环 · ${song.title}(${playback.mediaType === "video" ? "视频" : "音频"})`; + } else { + elements.playlistLoopStatus.textContent = "等待播放"; + } +} + +function resetPlaybackMode() { + appState.playback = { + mode: null, + mediaType: null, + songId: null, + playlistIndex: 0, + expected: null, + }; + renderPlaylistControl(); +} + +async function playCardMedia(songId, mediaType, mode, playlistIndex = 0) { + const song = appState.data.week.songs.find((item) => item.id === songId); + const card = elements.songCards.querySelector(`[data-song-card="${songId}"]`); + if (!song || !card) throw new Error("没有找到要播放的歌曲"); + requireIdentity(); + activateCardMode(card, songId, mediaType); + const player = card.querySelector(mediaType === "audio" ? "[data-audio-player]" : "[data-video-player]"); + const urlKey = mediaType === "audio" ? "audioUrl" : "videoUrl"; + if (!player.getAttribute("src")) { + player.src = player.dataset[urlKey]; + player.load(); + } + if (player.ended) player.currentTime = 0; + pauseAll(player); + appState.playback = { + mode, + mediaType, + songId, + playlistIndex, + expected: { mode, mediaType, songId }, + }; + renderPlaylistControl(); + await player.play(); +} + +async function startPlaylistAt(index) { + const songs = appState.data.week.songs; + if (!songs.length) return; + const normalized = ((index % songs.length) + songs.length) % songs.length; + await playCardMedia(songs[normalized].id, "audio", "playlist", normalized); + const card = elements.songCards.querySelector(`[data-song-card="${songs[normalized].id}"]`); + if (card && card.scrollIntoView) card.scrollIntoView({ behavior: "smooth", block: "center" }); +} + +async function togglePlaylistLoop() { + try { + requireIdentity(); + const player = elements.weeklyLoopPlayer; + if (appState.playback.mode === "weekly-loop" && !player.paused) { + player.pause(); + renderPlaylistControl(); + return; + } + const weekNumber = appState.data.week.number; + if (player.dataset.weekNumber !== String(weekNumber)) { + player.src = `/api/week-audio/${weekNumber}`; + player.dataset.weekNumber = String(weekNumber); + player.load(); + } + pauseAll(player); + appState.playback = { + mode: "weekly-loop", + mediaType: "audio", + songId: null, + playlistIndex: 0, + expected: null, + }; + await player.play(); + renderPlaylistControl(); + } catch (error) { + showToast(error.message || "音频正在准备,请再点一次播放"); + } +} + +function requireIdentity() { + if (appState.data.device.needs_identity) { + pauseAll(); + if (!isModalOpen(elements.identityDialog)) showModal(elements.identityDialog); + throw new Error("请先选择这台设备的身份"); + } +} + +function playbackKey(songId, mediaType) { + return `${songId}:${mediaType}`; +} + +async function ensurePlaybackStarted(song, mediaType, statusElement) { + requireIdentity(); + const key = playbackKey(song.id, mediaType); + const existing = appState.playRecords[key]; + if (existing) { + if (existing.playId) return existing.playId; + return (await existing.promise).play_id; + } + const promise = request("/api/playback/start", { + method: "POST", + body: JSON.stringify({ + device_id: appState.deviceId, + song_id: song.id, + study_date: appState.studyDate, + course_week: appState.data.week.number, + media_type: mediaType, + }), + }); + const record = { playId: null, promise }; + appState.playRecords[key] = record; + let result; + try { + result = await promise; + } catch (error) { + delete appState.playRecords[key]; + throw error; + } + record.playId = result.play_id; + if (statusElement) statusElement.textContent = "正在播放"; + if (statusElement) statusElement.hidden = false; + return result.play_id; +} + +async function onMediaPlay(card, song, mediaType, player) { + pauseAll(player); + const expected = appState.playback.expected; + if (!expected || expected.songId !== song.id || expected.mediaType !== mediaType) { + appState.playback = { + mode: "single", + mediaType, + songId: song.id, + playlistIndex: appState.data.week.songs.findIndex((item) => item.id === song.id), + expected: null, + }; + } else { + appState.playback.expected = null; + } + renderPlaylistControl(); + try { + await ensurePlaybackStarted(song, mediaType, card.querySelector("[data-card-status]")); + if (mediaType === "video") updateVideoButton(card, player); + if (mediaType === "audio") updateAudioControls(card, player); + } catch (error) { + player.pause(); + showToast(error.message); + } +} + +function updateVideoButton(card, video) { + const button = card.querySelector("[data-video-toggle]"); + button.hidden = !video.paused; + if (video.ended) button.textContent = "重新播放视频"; + else button.textContent = video.currentTime > 0 ? "继续播放视频" : "播放本首视频"; +} + +function updatePausedStatus(card, player) { + if (player.currentTime > 0 && !player.ended) { + const status = card.querySelector("[data-card-status]"); + status.textContent = "已暂停"; + status.hidden = false; + } +} + +async function toggleVideo(card, song) { + try { + requireIdentity(); + const video = card.querySelector("[data-video-player]"); + if (video.paused) await playCardMedia(song.id, "video", "single"); + else { + video.pause(); + renderPlaylistControl(); + } + } catch (error) { + showToast(error.message || "请点一下播放按钮继续"); + } +} + +function formatMediaTime(value) { + if (!Number.isFinite(value) || value < 0) return "0:00"; + const minutes = Math.floor(value / 60); + const seconds = Math.floor(value % 60).toString().padStart(2, "0"); + return `${minutes}:${seconds}`; +} + +function updateAudioControls(card, audio) { + const toggle = card.querySelector("[data-audio-toggle]"); + const label = toggle.querySelector("strong"); + const progress = card.querySelector("[data-audio-progress]"); + const duration = Number.isFinite(audio.duration) ? audio.duration : 0; + progress.max = String(duration); + progress.value = String(Math.min(audio.currentTime || 0, duration)); + card.querySelector("[data-audio-current]").textContent = formatMediaTime(audio.currentTime); + card.querySelector("[data-audio-duration]").textContent = duration ? formatMediaTime(duration) : "--:--"; + card.querySelector("[data-card-panel='audio']").classList.toggle("playing", !audio.paused); + label.textContent = audio.paused + ? audio.currentTime > 0 && !audio.ended + ? "继续播放音频" + : audio.ended + ? "重新播放音频" + : "播放本首音频" + : "暂停音频"; + toggle.setAttribute("aria-label", `${label.textContent} ${toggle.querySelector("small").textContent}`); +} + +async function toggleAudio(card, song) { + try { + requireIdentity(); + const audio = card.querySelector("[data-audio-player]"); + if (audio.paused) await playCardMedia(song.id, "audio", "single"); + else { + audio.pause(); + renderPlaylistControl(); + } + } catch (error) { + showToast(error.message || "请点一下播放按钮继续"); + } +} + +async function completePlayback(song, mediaType, player) { + try { + const playback = { + mode: appState.playback.mode, + mediaType: appState.playback.mediaType, + songId: appState.playback.songId, + playlistIndex: appState.playback.playlistIndex, + expected: appState.playback.expected, + }; + const playId = await ensurePlaybackStarted( + song, + mediaType, + player.closest("[data-song-card]").querySelector("[data-card-status]"), + ); + const result = await request("/api/playback/complete", { + method: "POST", + body: JSON.stringify({ + device_id: appState.deviceId, + play_id: playId, + duration_seconds: Number.isFinite(player.duration) ? player.duration : null, + }), + }); + delete appState.playRecords[playbackKey(song.id, mediaType)]; + if (result.song_progress) Object.assign(song, result.song_progress); + if (result.round_award) appState.data.round_award = result.round_award; + appState.data.day[`${mediaType}_plays`] += result.already_completed ? 0 : 1; + elements.todayPlays.textContent = appState.data.day.video_plays + appState.data.day.audio_plays; + refreshRewardDisplays(); + if (!result.already_completed) { + showToast( + appState.childMode + ? `${song.title} 播放完成!` + : result.checkin_eligible + ? `${song.title} 播放完成,小红花亮起来啦!` + : `${song.title} 预习完成,本次不会提前解锁小红花`, + ); + } + if (result.round_ready && !appState.childMode) { + showToast("整轮大红花亮起来啦,快去亲手领取!"); + } + if (playback.mode === "single" && playback.songId === song.id && playback.mediaType === mediaType) { + await playCardMedia(song.id, mediaType, "single", playback.playlistIndex); + } else if (playback.mode === "playlist" && mediaType === "audio") { + await startPlaylistAt(playback.playlistIndex + 1); + } + } catch (error) { + resetPlaybackMode(); + showToast(error.message); + } +} + +async function claimFlower(songId) { + try { + await request("/api/song-checkin", { + method: "POST", + body: JSON.stringify({ + device_id: appState.deviceId, + song_id: songId, + study_date: appState.studyDate, + }), + }); + await loadState({ recover: false, celebrateRecovered: false }); + const song = appState.data.week.songs.find((item) => item.id === songId); + celebrate("获得一朵小红花!", `${song ? song.title : "这首歌"}认真听完啦,真棒!`); + } catch (error) { + showToast(error.message); + } +} + +async function claimRoundFlower() { + try { + const result = await request("/api/round-checkin", { + method: "POST", + body: JSON.stringify({ + device_id: appState.deviceId, + study_date: appState.studyDate, + }), + }); + await loadState({ recover: false, celebrateRecovered: false }); + celebrate("整轮大奖到手啦!", `第 ${result.round_number} 轮全部听完,送你一朵大红花!`); + } catch (error) { + showToast(error.message); + } +} + +async function changeStudyDate(value, scrollToPlayer = false) { + pauseAll(); + resetPlaybackMode(); + appState.studyDate = value; + appState.viewWeek = null; + appState.playRecords = {}; + await loadState(); + if (scrollToPlayer) document.querySelector(".player-section").scrollIntoView({ behavior: "smooth" }); +} + +async function changeWeek(weekNumber, scrollToPlayer = false) { + const target = Math.max(1, Math.min(50, Number(weekNumber))); + const summary = appState.data.weeks.find((week) => week.number === target); + if (!summary) return; + pauseAll(); + resetPlaybackMode(); + appState.viewWeek = target; + appState.studyDate = target < appState.data.settings.current_week + ? summary.start_date + : appState.data.today_date; + appState.playRecords = {}; + await loadState(); + if (scrollToPlayer) document.querySelector(".player-section").scrollIntoView({ behavior: "smooth" }); +} + +let celebrationTimer; +function celebrate(title, copy) { + clearTimeout(celebrationTimer); + elements.celebration.classList.remove("celebrating"); + elements.celebrationTitle.textContent = title; + elements.celebrationCopy.textContent = copy; + elements.celebration.hidden = false; + void elements.celebration.offsetWidth; + elements.celebration.classList.add("celebrating"); + celebrationTimer = window.setTimeout(() => { + elements.celebration.hidden = true; + elements.celebration.classList.remove("celebrating"); + }, 3000); +} + +let toastTimer; +function showToast(message) { + elements.toast.textContent = message; + elements.toast.classList.add("visible"); + clearTimeout(toastTimer); + toastTimer = setTimeout(() => elements.toast.classList.remove("visible"), 2600); +} + +elements.identityButton.addEventListener("click", () => showModal(elements.identityDialog)); +elements.bottomSettingsButton.addEventListener("click", () => showModal(elements.settingsDialog)); +elements.closeSettings.addEventListener("click", () => hideModal(elements.settingsDialog)); +elements.previousWeek.addEventListener("click", () => changeWeek(appState.data.week.number - 1)); +elements.nextWeek.addEventListener("click", () => changeWeek(appState.data.week.number + 1)); +elements.currentWeek.addEventListener("click", () => changeWeek(appState.data.settings.current_week)); +elements.playlistLoopButton.addEventListener("click", togglePlaylistLoop); +elements.weeklyLoopPlayer.addEventListener("play", () => { + if (appState.playback.mode === "weekly-loop") renderPlaylistControl(); +}); +elements.weeklyLoopPlayer.addEventListener("pause", () => { + if (appState.playback.mode === "weekly-loop") renderPlaylistControl(); +}); +elements.celebration.addEventListener("click", () => { + clearTimeout(celebrationTimer); + elements.celebration.hidden = true; + elements.celebration.classList.remove("celebrating"); +}); +elements.settingsForm.addEventListener("submit", async (event) => { + event.preventDefault(); + try { + await request("/api/settings", { + method: "POST", + body: JSON.stringify({ + start_date: elements.startDate.value, + checkin_window_minutes: Number(elements.checkinWindow.value), + }), + }); + setChildMode(elements.childMode.checked); + hideModal(elements.settingsDialog); + appState.studyDate = null; + appState.viewWeek = null; + showToast("学习设置已保存"); + await loadState(); + } catch (error) { + showToast(error.message); + } +}); + +function refreshRewardDisplays() { + if (!appState.data || appState.childMode) return; + appState.data.week.songs.forEach((song) => { + const card = elements.songCards.querySelector(`[data-song-card="${song.id}"]`); + const container = card ? card.querySelector("[data-song-reward]") : null; + if (!container) return; + container.innerHTML = songRewardMarkup(song); + bindRewardButtons(container); + }); + renderRoundAward(); +} + +setInterval(refreshRewardDisplays, 15000); +applyChildMode(); +loadState(); diff --git a/public/icon.svg b/public/icon.svg new file mode 100644 index 0000000..216345e --- /dev/null +++ b/public/icon.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..8e77031 --- /dev/null +++ b/public/index.html @@ -0,0 +1,203 @@ + + + + + + + + + + + SSS 50 周打卡 + + +
+
+

第 1 周

+
+ +
+

正在连接学习记录…

+
+
+
+

今日学习

+

今天 · 10月12日

+
+

宠物 · 农场动物

+
+
+ +
+ 0今日红花 + 0今日播放 +
+
+
+ + + +
+
+ +
+ +

三首本周歌曲依次播放,锁屏后也会自动循环。

+ + +
+ +
+ + +
+ +
+
+

三首歌都听完,才能领取一朵大红花哦

+
+
+ +
+
+
+

成长足迹

+

最近 14 天

+
+
+ + 0 + 朵红花 +
+
+

今天永远在右下角。点过去的日期,可以补学习、补红花。

+
+ +
+
+ +
+ +
+
+
+

课程地图

+

50 周学习计划

+
+ 0/50 周学过 +
+
+
+
+ +
+
+ 播放与打卡数据只保存在家庭服务器 + 正在检查视频、音频和歌词… +
+ +
+
+ + + + + +
+ + + + + diff --git a/public/manifest.webmanifest b/public/manifest.webmanifest new file mode 100644 index 0000000..d58726c --- /dev/null +++ b/public/manifest.webmanifest @@ -0,0 +1,17 @@ +{ + "name": "SSS 50 周打卡", + "short_name": "SSS打卡", + "description": "家庭局域网中的 SSS 儿歌独立播放、小红花打卡与统计工具", + "start_url": "/", + "display": "standalone", + "background_color": "#f8f3e8", + "theme_color": "#f5a65b", + "icons": [ + { + "src": "/static/icon.svg", + "sizes": "any", + "type": "image/svg+xml", + "purpose": "any" + } + ] +} diff --git a/public/resources.css b/public/resources.css new file mode 100644 index 0000000..25afc54 --- /dev/null +++ b/public/resources.css @@ -0,0 +1,576 @@ +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +.resource-shell { + width: calc(100% - 32px); + max-width: 1240px; + width: min(1240px, calc(100% - 32px)); + margin: 0 auto; + padding-bottom: 54px; +} + +.resource-topbar { + min-height: 168px; + display: grid; + grid-template-columns: 1fr auto 1fr; + align-items: center; + gap: 24px; +} + +.resource-topbar > div { + text-align: center; +} + +.resource-topbar h1 { + margin: 0; + font-size: 48px; + font-size: clamp(38px, 6vw, 64px); +} + +.resource-topbar p:last-child { + margin: 8px 0 0; + color: var(--muted); + font-size: 13px; +} + +.back-link { + justify-self: start; + padding: 10px 14px; + border-radius: 13px; + color: var(--ink); + background: rgba(255, 253, 248, 0.78); + text-decoration: none; + font-weight: 800; +} + +.resource-total { + justify-self: end; + padding: 9px 13px; + border-radius: 999px; + color: var(--sage-dark); + background: var(--sage-soft); + font-size: 12px; + font-weight: 800; +} + +.resource-summary { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 12px; +} + +.resource-summary article { + min-height: 104px; + display: flex; + align-items: center; + gap: 15px; + padding: 18px; + border: 1px solid rgba(255, 255, 255, 0.9); + border-radius: 22px; + background: rgba(255, 253, 248, 0.84); + box-shadow: 0 12px 30px rgba(78, 62, 38, 0.06); +} + +.resource-summary article:nth-child(2) { background: rgba(255, 241, 220, 0.86); } +.resource-summary article:nth-child(3) { background: rgba(223, 238, 231, 0.84); } +.resource-summary article:nth-child(4) { background: rgba(255, 230, 230, 0.72); } + +.summary-icon { + width: 47px; + height: 47px; + flex: 0 0 47px; + display: grid; + place-items: center; + border-radius: 15px; + color: white; + background: var(--peach); + font-size: 21px; +} + +.resource-summary small, +.resource-summary strong { + display: block; +} + +.resource-summary small { + color: var(--muted); +} + +.resource-summary strong { + margin-top: 6px; + font-size: 25px; +} + +.resource-summary em { + color: var(--muted); + font-size: 12px; + font-style: normal; +} + +.resource-toolbar { + position: sticky; + top: 10px; + z-index: 8; + display: grid; + grid-template-columns: minmax(280px, 1fr) 160px 160px; + gap: 10px; + margin: 26px 0; + padding: 11px; + border: 1px solid rgba(255, 255, 255, 0.9); + border-radius: 20px; + background: rgba(249, 245, 235, 0.92); + box-shadow: 0 12px 34px rgba(78, 62, 38, 0.1); + backdrop-filter: blur(12px); +} + +.resource-search { + display: flex; + align-items: center; + gap: 8px; + padding-left: 12px; + border-radius: 13px; + background: white; +} + +.resource-toolbar input, +.resource-toolbar select { + width: 100%; + min-height: 47px; + border: 1px solid var(--border); + border-radius: 13px; + color: var(--ink); + background: white; +} + +.resource-search input { + padding: 10px 12px 10px 0; + border: 0; + outline: 0; +} + +.resource-toolbar select { + padding: 10px 12px; +} + +.resource-layout { + display: block; +} + +.catalog-panel { + border: 1px solid rgba(255, 255, 255, 0.88); + border-radius: 27px; + background: rgba(255, 253, 248, 0.78); + box-shadow: 0 14px 38px rgba(78, 62, 38, 0.07); +} + +.catalog-panel { + padding: 22px; +} + +.catalog-heading { + display: flex; + align-items: end; + justify-content: space-between; + gap: 16px; + margin-bottom: 16px; +} + +.catalog-heading h2 { + margin: 2px 0 0; + font-size: 28px; +} + +.result-count { + color: var(--muted); + font-size: 12px; +} + +.resource-list { + display: grid; + gap: 9px; + max-width: 940px; + margin: 0 auto; +} + +.resource-item { + overflow: hidden; + border: 1px solid var(--border); + border-radius: 20px; + background: rgba(255, 255, 255, 0.68); + transition: 180ms ease; +} + +.resource-item.expanded { + border-color: rgba(245, 166, 91, 0.62); + background: #fff8eb; + box-shadow: 0 12px 30px rgba(217, 121, 53, 0.12); +} + +.resource-card { + width: 100%; + min-width: 0; + display: grid; + grid-template-columns: 62px minmax(0, 1fr) auto; + align-items: center; + gap: 13px; + padding: 13px; + border: 0; + border-radius: 19px; + color: var(--ink); + background: rgba(255, 255, 255, 0.68); + text-align: left; + transition: 160ms ease; +} + +.resource-card:hover, +.resource-card.selected { + background: #fff8eb; + box-shadow: none; + transform: none; +} + +.resource-item.expanded .resource-card { + border-radius: 19px 19px 0 0; + border-bottom: 1px solid rgba(217, 121, 53, 0.14); +} + +.resource-number { + min-height: 48px; + display: grid; + place-items: center; + border-radius: 14px; + color: #9a5828; + background: #ffe9c9; + font-size: 13px; + font-weight: 900; +} + +.resource-card-copy, +.resource-card-copy strong, +.resource-card-copy small { + display: block; + min-width: 0; +} + +.resource-card-copy strong { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.resource-card-copy small { + margin-top: 4px; + color: var(--muted); +} + +.asset-badges { + display: flex; + flex-wrap: wrap; + gap: 5px; + margin-top: 8px; +} + +.asset-badge { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 4px 7px; + border-radius: 999px; + color: var(--muted); + background: rgba(37, 50, 45, 0.05); + font-size: 9px; + font-weight: 800; +} + +.asset-badge i { + width: 6px; + height: 6px; + border-radius: 50%; + background: #c9beb4; +} + +.asset-badge.ready { + color: var(--sage-dark); + background: var(--sage-soft); +} + +.asset-badge.ready i { background: var(--sage); } +.asset-badge.missing { color: #a95b62; background: #ffe7e8; } +.asset-badge.missing i { background: #dc717a; } + +.resource-arrow { + color: var(--muted); + font-size: 24px; + transition: transform 180ms ease; +} + +.resource-item.expanded .resource-arrow { + transform: rotate(180deg); +} + +.resource-empty { + display: grid; + justify-items: center; + padding: 58px 20px; + color: var(--muted); + text-align: center; +} + +.resource-empty[hidden] { display: none; } +.resource-empty > span { font-size: 38px; } +.resource-empty strong { margin-top: 10px; color: var(--ink); } +.resource-empty p { margin-bottom: 0; } + +.resource-inline-viewer { + margin: 12px; + overflow: hidden; + border: 1px solid rgba(37, 50, 45, 0.08); + border-radius: 22px; + background: rgba(255, 253, 248, 0.96); + animation: resource-unfold 210ms ease-out both; +} + +.resource-inline-tabs { + border-bottom: 1px solid rgba(37, 50, 45, 0.06); +} + +.resource-inline-viewer .song-media-shell { + width: 100%; +} + +.resource-inline-viewer .center-play:disabled, +.resource-inline-viewer .audio-toggle:disabled { + cursor: not-allowed; + opacity: 0.6; +} + +.resource-inline-note { + margin: 0; + padding: 12px 16px; + color: var(--sage-dark); + background: var(--sage-soft); + font-size: 11px; + line-height: 1.5; + text-align: center; +} + +@keyframes resource-unfold { + from { opacity: 0; transform: translateY(-8px); } + to { opacity: 1; transform: translateY(0); } +} + +.resource-viewer { + position: sticky; + top: 102px; + overflow: hidden; +} + +.viewer-heading { + padding: 25px 25px 20px; +} + +.viewer-heading h2 { + margin: 9px 0 6px; + font-size: clamp(25px, 3vw, 37px); + line-height: 1.08; +} + +.viewer-heading p { + margin: 0; + color: var(--muted); +} + +.resource-tabs { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 6px; + padding: 8px; + border-top: 1px solid var(--border); + border-bottom: 1px solid var(--border); + background: rgba(245, 241, 231, 0.84); +} + +.resource-tab { + min-height: 43px; + border-radius: 12px; + color: var(--muted); + background: transparent; + font-size: 12px; + font-weight: 800; +} + +.resource-tab.selected { + color: var(--peach-dark); + background: white; + box-shadow: 0 5px 14px rgba(78, 62, 38, 0.08); +} + +.resource-panel { + min-height: 360px; +} + +.info-panel { + padding: 23px; +} + +.viewer-note { + margin: 0 0 18px; + padding: 13px 14px; + border-radius: 15px; + color: var(--sage-dark); + background: var(--sage-soft); + font-size: 12px; + line-height: 1.55; +} + +.file-list { + display: grid; + gap: 10px; + margin: 0; +} + +.file-list div { + padding: 13px 14px; + border: 1px solid var(--border); + border-radius: 15px; + background: rgba(255, 255, 255, 0.6); +} + +.file-list dt { + color: var(--muted); + font-size: 10px; + font-weight: 800; +} + +.file-list dd { + margin: 5px 0 0; + overflow-wrap: anywhere; + font-size: 12px; + font-weight: 700; +} + +.media-preview, +.lyrics-preview { + background: #202621; +} + +.media-preview video { + width: 100%; + min-height: 360px; + display: block; + background: #111; +} + +.media-preview audio { + width: calc(100% - 42px); + margin: 142px 21px 0; +} + +.lazy-placeholder { + min-height: 360px; + display: grid; + place-content: center; + justify-items: center; + padding: 34px; + color: white; + background: radial-gradient(circle at top right, rgba(245,166,91,.42), transparent 42%), #25322d; + text-align: center; +} + +.lazy-placeholder > span { + width: 68px; + height: 68px; + display: grid; + place-items: center; + margin-bottom: 16px; + border-radius: 23px; + color: white; + background: var(--peach); + font-size: 28px; +} + +.lazy-placeholder p { + max-width: 290px; + margin: 8px 0 19px; + color: rgba(255,255,255,.72); + font-size: 12px; + line-height: 1.55; +} + +.lazy-placeholder .primary-button:disabled { + opacity: .5; +} + +.audio-lazy { + background: radial-gradient(circle at top right, rgba(118,168,150,.4), transparent 42%), #25322d; +} + +.lyrics-preview { + display: grid; + place-items: center; + min-height: 360px; + padding: 12px; + background: #f0ece3; +} + +.lyrics-preview img { + max-width: 100%; + max-height: 68vh; + border-radius: 12px; +} + +.resource-footer { + display: flex; + justify-content: space-between; + gap: 18px; + padding: 38px 4px 0; + color: var(--muted); + font-size: 12px; +} + +@media (max-width: 900px) { + .resource-summary { grid-template-columns: repeat(2, 1fr); } + .resource-layout { grid-template-columns: 1fr; } + .resource-viewer { position: static; order: -1; scroll-margin-top: 96px; } + .resource-panel { min-height: 330px; } + .lazy-placeholder, .media-preview video { min-height: 330px; } +} + +@media (max-width: 620px) { + .resource-shell { width: calc(100% - 22px); max-width: 580px; width: min(calc(100% - 22px), 580px); } + .resource-topbar { min-height: 150px; grid-template-columns: 1fr auto; } + .resource-topbar > div { grid-column: 1 / -1; grid-row: 1; } + .back-link { grid-column: 1; grid-row: 2; } + .resource-total { grid-column: 2; grid-row: 2; } + .resource-topbar h1 { font-size: 36px; } + .resource-summary { gap: 8px; } + .resource-summary article { min-height: 89px; gap: 10px; padding: 13px; border-radius: 18px; } + .summary-icon { width: 39px; height: 39px; flex-basis: 39px; border-radius: 12px; font-size: 17px; } + .resource-summary strong { font-size: 21px; } + .resource-toolbar { top: 6px; grid-template-columns: repeat(2, 1fr); margin: 18px 0; } + .resource-search { grid-column: 1 / -1; } + .catalog-panel { padding: 13px; border-radius: 22px; } + .resource-card { grid-template-columns: 52px minmax(0, 1fr) 22px; padding: 11px; } + .resource-number { min-height: 45px; } + .resource-arrow { display: block; text-align: center; } + .asset-badge { font-size: 8px; } + .resource-inline-viewer { margin: 7px; border-radius: 18px; } + .resource-inline-note { padding: 10px 12px; font-size: 10px; } + .resource-viewer { border-radius: 22px; } + .viewer-heading { padding: 21px 18px 17px; } + .resource-tabs { gap: 3px; padding: 6px; } + .resource-tab { font-size: 11px; } + .resource-panel, .lazy-placeholder, .media-preview video { min-height: 290px; } + .info-panel { padding: 17px; } + .media-preview audio { margin-top: 116px; } + .resource-footer { flex-direction: column; } +} diff --git a/public/resources.html b/public/resources.html new file mode 100644 index 0000000..911f5ff --- /dev/null +++ b/public/resources.html @@ -0,0 +1,75 @@ + + + + + + + + + + + SSS 全部资源库 + + +
+
+ ‹ 返回播放 +
+

家长工具

+

全部资源库

+

快速找到每一首歌的视频、音频和歌词

+
+ 正在读取… +
+ +
+
+ +
+ + + +
+ +
+
+
+
+

课程清单

+

100 首歌

+
+ 0 项 +
+
+ +
+
+
+ +
+ 只在局域网内读取群晖资源 + 视频、音频均按需加载 +
+
+ +
+ + + diff --git a/public/resources.js b/public/resources.js new file mode 100644 index 0000000..a5be1c1 --- /dev/null +++ b/public/resources.js @@ -0,0 +1,368 @@ +const resourceState = { + catalog: null, + selectedId: null, + mode: "video", +}; + +const resourceElements = { + total: document.querySelector("#resource-total"), + summary: document.querySelector("#resource-summary"), + search: document.querySelector("#resource-search"), + weekFilter: document.querySelector("#week-filter"), + availabilityFilter: document.querySelector("#availability-filter"), + catalogHeading: document.querySelector("#catalog-heading"), + resultCount: document.querySelector("#result-count"), + list: document.querySelector("#resource-list"), + empty: document.querySelector("#resource-empty"), + toast: document.querySelector("#resource-toast"), +}; + +function escapeHtml(value) { + return String(value == null ? "" : value) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +function forEachNode(nodes, callback) { + for (let index = 0; index < nodes.length; index += 1) { + callback(nodes[index], index); + } +} + +function currentSong() { + return resourceState.catalog + ? resourceState.catalog.songs.find((song) => song.id === resourceState.selectedId) || null + : null; +} + +function isComplete(song) { + return song.available.video && song.available.audio && song.available.lyrics; +} + +function availabilityBadge(label, available) { + return `${label}${available ? "齐全" : "缺失"}`; +} + +function renderSummary() { + const { songs, available } = resourceState.catalog.summary; + resourceElements.total.textContent = `${songs} 首歌`; + resourceElements.summary.innerHTML = [ + ["全部歌曲", songs, "首", "♫"], + ["视频文件", available.video, "/ 100", "▶"], + ["音频文件", available.audio, "/ 100", "♬"], + ["歌词图片", available.lyrics, "/ 100", "▤"], + ] + .map( + ([label, value, unit, icon]) => ` +
+ +
${label}${value} ${unit}
+
`, + ) + .join(""); +} + +function populateWeeks() { + const weeks = []; + resourceState.catalog.songs.forEach((song) => { + if (weeks.indexOf(song.week) === -1) weeks.push(song.week); + }); + resourceElements.weekFilter.insertAdjacentHTML( + "beforeend", + weeks.map((week) => ``).join(""), + ); +} + +function filteredSongs() { + const needle = resourceElements.search.value.trim().toLowerCase(); + const week = resourceElements.weekFilter.value; + const availability = resourceElements.availabilityFilter.value; + return resourceState.catalog.songs.filter((song) => { + const haystack = [song.id, song.title, song.category, song.files.video, song.files.audio, song.files.lyrics] + .join(" ") + .toLowerCase(); + const matchesText = !needle || haystack.includes(needle); + const matchesWeek = week === "all" || song.week === Number(week); + const complete = isComplete(song); + const matchesAvailability = availability === "all" || (availability === "complete" ? complete : !complete); + return matchesText && matchesWeek && matchesAvailability; + }); +} + +function resourceDetailMarkup(song) { + const videoDisabled = song.available.video ? "" : " disabled"; + const audioDisabled = song.available.audio ? "" : " disabled"; + return ` +
+
+ + + +
+ +
+
+ + +
+ +
+ + +
+ 0:00 + + --:-- +
+ +
+ +
+ ${escapeHtml(song.title)} 歌词 +
+
+

资源库试听不会产生打卡记录;要记录学习,请回到主页面完整播放。

+
`; +} + +function resourceItemMarkup(song) { + const expanded = song.id === resourceState.selectedId; + return ` +
+ + ${expanded ? resourceDetailMarkup(song) : ""} +
`; +} + +function stopOpenMedia() { + forEachNode(resourceElements.list.querySelectorAll("video, audio"), (media) => { + media.pause(); + media.removeAttribute("src"); + media.load(); + }); +} + +function renderList() { + const songs = filteredSongs(); + if (resourceState.selectedId && !songs.some((song) => song.id === resourceState.selectedId)) { + resourceState.selectedId = null; + resourceState.mode = "video"; + } + resourceElements.resultCount.textContent = `${songs.length} 项`; + resourceElements.empty.hidden = songs.length > 0; + resourceElements.list.innerHTML = songs.map(resourceItemMarkup).join(""); + bindList(); +} + +function selectSong(songId) { + stopOpenMedia(); + const shouldClose = resourceState.selectedId === songId; + resourceState.selectedId = shouldClose ? null : songId; + resourceState.mode = "video"; + renderList(); + if (!shouldClose) { + const item = resourceElements.list.querySelector(`[data-resource-item="${songId}"]`); + if (item && item.scrollIntoView) item.scrollIntoView({ behavior: "smooth", block: "nearest" }); + } +} + +function openPanel() { + return resourceElements.list.querySelector("[data-resource-detail]"); +} + +function pauseOpenMedia(except = null) { + const panel = openPanel(); + if (!panel) return; + forEachNode(panel.querySelectorAll("video, audio"), (media) => { + if (media !== except) media.pause(); + }); +} + +function loadLazyImage(image) { + if (image && !image.hasAttribute("src") && image.dataset.src) image.src = image.dataset.src; +} + +function changeMode(mode) { + if (!currentSong()) return; + resourceState.mode = mode; + const detail = openPanel(); + forEachNode(detail.querySelectorAll("[data-resource-mode]"), (tab) => { + const selected = tab.dataset.resourceMode === mode; + tab.classList.toggle("selected", selected); + tab.setAttribute("aria-selected", String(selected)); + }); + forEachNode(detail.querySelectorAll("[data-resource-panel]"), (panel) => { + panel.hidden = panel.dataset.resourcePanel !== mode; + }); + if (mode === "audio") loadLazyImage(detail.querySelector("[data-resource-audio-art]")); + if (mode === "lyrics") loadLazyImage(detail.querySelector("[data-resource-lyrics]")); +} + +function updateVideoButton(detail) { + const video = detail.querySelector("[data-resource-video]"); + const button = detail.querySelector("[data-resource-video-toggle]"); + if (!video || !button || button.disabled) return; + button.hidden = !video.paused && !video.ended; + button.textContent = video.currentTime > 0 && !video.ended ? "继续播放" : "播放视频"; +} + +async function toggleVideo() { + const song = currentSong(); + if (!song || !song.available.video) return; + const detail = openPanel(); + const video = detail ? detail.querySelector("[data-resource-video]") : null; + if (!video) return; + if (!video.src) { + video.src = video.dataset.videoUrl; + video.load(); + } + pauseOpenMedia(video); + if (video.paused) { + try { + await video.play(); + } catch (error) { + showToast("视频已加载,点播放器开始播放"); + } + } else { + video.pause(); + } + updateVideoButton(detail); +} + +function formatTime(value) { + if (!Number.isFinite(value) || value < 0) return "0:00"; + const minutes = Math.floor(value / 60); + const seconds = Math.floor(value % 60); + return `${minutes}:${String(seconds).padStart(2, "0")}`; +} + +function updateAudioControls(detail) { + const audio = detail.querySelector("[data-resource-audio]"); + const panel = detail.querySelector("[data-resource-panel='audio']"); + const button = detail.querySelector("[data-resource-audio-toggle]"); + const label = button.querySelector("strong"); + const progress = detail.querySelector("[data-resource-audio-progress]"); + const current = detail.querySelector("[data-resource-audio-current]"); + const duration = detail.querySelector("[data-resource-audio-duration]"); + const playing = !audio.paused && !audio.ended; + panel.classList.toggle("playing", playing); + label.textContent = playing ? "暂停音频" : audio.currentTime > 0 && !audio.ended ? "继续播放音频" : "播放音频"; + current.textContent = formatTime(audio.currentTime); + duration.textContent = Number.isFinite(audio.duration) ? formatTime(audio.duration) : "--:--"; + progress.max = Number.isFinite(audio.duration) ? audio.duration : 0; + progress.value = audio.currentTime || 0; +} + +async function toggleAudio() { + const song = currentSong(); + if (!song || !song.available.audio) return; + const detail = openPanel(); + const audio = detail ? detail.querySelector("[data-resource-audio]") : null; + if (!audio) return; + loadLazyImage(detail.querySelector("[data-resource-audio-art]")); + if (!audio.src) { + audio.src = audio.dataset.audioUrl; + audio.load(); + } + pauseOpenMedia(audio); + if (audio.paused) { + try { + await audio.play(); + } catch (error) { + showToast("音频已加载,点中间按钮开始播放"); + } + } else { + audio.pause(); + } + updateAudioControls(detail); +} + +function bindList() { + forEachNode(resourceElements.list.querySelectorAll("[data-song-id]"), (button) => { + button.addEventListener("click", () => selectSong(button.dataset.songId)); + }); + const detail = openPanel(); + if (!detail) return; + forEachNode(detail.querySelectorAll("[data-resource-mode]"), (tab) => { + tab.addEventListener("click", () => changeMode(tab.dataset.resourceMode)); + }); + const video = detail.querySelector("[data-resource-video]"); + const videoButton = detail.querySelector("[data-resource-video-toggle]"); + videoButton.addEventListener("click", toggleVideo); + video.addEventListener("play", () => updateVideoButton(detail)); + video.addEventListener("pause", () => updateVideoButton(detail)); + video.addEventListener("ended", () => updateVideoButton(detail)); + + const audioPanel = detail.querySelector("[data-resource-panel='audio']"); + const audio = detail.querySelector("[data-resource-audio]"); + const audioButton = detail.querySelector("[data-resource-audio-toggle]"); + audioButton.addEventListener("click", toggleAudio); + audioPanel.addEventListener("click", (event) => { + if (event.target.closest("[data-resource-audio-toggle], .audio-timeline")) return; + toggleAudio(); + }); + ["play", "pause", "timeupdate", "loadedmetadata", "ended"].forEach((eventName) => { + audio.addEventListener(eventName, () => updateAudioControls(detail)); + }); + detail.querySelector("[data-resource-audio-progress]").addEventListener("input", (event) => { + if (Number.isFinite(audio.duration)) audio.currentTime = Number(event.target.value); + }); + if (resourceState.mode === "audio") loadLazyImage(detail.querySelector("[data-resource-audio-art]")); + if (resourceState.mode === "lyrics") loadLazyImage(detail.querySelector("[data-resource-lyrics]")); +} + +function refreshList() { + stopOpenMedia(); + renderList(); +} + +let toastTimer; +function showToast(message) { + resourceElements.toast.textContent = message; + resourceElements.toast.classList.add("visible"); + clearTimeout(toastTimer); + toastTimer = window.setTimeout(() => resourceElements.toast.classList.remove("visible"), 2400); +} + +async function loadCatalog() { + const response = await fetch("/api/resources"); + if (!response.ok) throw new Error("无法读取资源目录"); + resourceState.catalog = await response.json(); + renderSummary(); + populateWeeks(); + renderList(); +} + +resourceElements.search.addEventListener("input", refreshList); +resourceElements.weekFilter.addEventListener("change", refreshList); +resourceElements.availabilityFilter.addEventListener("change", refreshList); + +loadCatalog().catch((error) => { + resourceElements.total.textContent = error.message; + showToast(error.message); +}); diff --git a/public/stats.css b/public/stats.css new file mode 100644 index 0000000..295c3a6 --- /dev/null +++ b/public/stats.css @@ -0,0 +1,522 @@ +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +.stats-shell { + width: calc(100% - 32px); + max-width: 1180px; + width: min(1180px, calc(100% - 32px)); + margin: 0 auto; + padding-bottom: 60px; +} + +.stats-topbar { + min-height: 160px; + display: grid; + grid-template-columns: 1fr auto 1fr; + align-items: center; + gap: 24px; +} + +.stats-topbar h1 { + margin: 0; + font-size: 50px; + font-size: clamp(38px, 7vw, 66px); + text-align: center; +} + +.stats-topbar .eyebrow { + text-align: center; +} + +.back-link { + justify-self: start; + padding: 10px 14px; + border-radius: 13px; + color: var(--ink); + background: rgba(255, 253, 248, 0.78); + text-decoration: none; + font-weight: 800; +} + +.updated-at { + justify-self: end; + color: var(--muted); + font-size: 12px; +} + +.summary-cards { + display: grid; + grid-template-columns: repeat(6, 1fr); + gap: 12px; +} + +.summary-card { + min-height: 130px; + padding: 19px; + border: 1px solid rgba(255, 255, 255, 0.9); + border-radius: 22px; + background: rgba(255, 253, 248, 0.88); + box-shadow: 0 12px 32px rgba(78, 62, 38, 0.07); +} + +.summary-card:nth-child(1), +.summary-card:nth-child(4) { + background: rgba(223, 238, 231, 0.88); +} + +.summary-card:nth-child(2), +.summary-card:nth-child(5) { + background: rgba(255, 241, 220, 0.9); +} + +.summary-card strong, +.summary-card span { + display: block; +} + +.summary-card strong { + margin-top: 22px; + font-size: 30px; +} + +.summary-card span { + color: var(--muted); + font-size: 13px; +} + +.stats-section { + padding-top: 56px; +} + +.stats-heading { + display: flex; + align-items: end; + justify-content: space-between; + gap: 18px; + margin-bottom: 19px; +} + +.legend { + display: inline-flex; + align-items: center; + gap: 6px; + color: var(--muted); + font-size: 12px; +} + +.legend i { + width: 12px; + height: 12px; + border-radius: 4px; + background: var(--sage); +} + +.calendar-card { + padding: 18px; + border-radius: 24px; + background: rgba(255, 253, 248, 0.84); + box-shadow: 0 12px 34px rgba(78, 62, 38, 0.07); +} + +.weekday-row, +.daily-grid { + display: grid; + grid-template-columns: repeat(7, 1fr); + gap: 8px; +} + +.weekday-row { + margin-bottom: 8px; + color: var(--muted); + text-align: center; + font-size: 11px; +} + +.day-cell { + min-height: 72px; + padding: 9px; + border: 1px solid var(--border); + border-radius: 15px; + background: rgba(37, 50, 45, 0.025); +} + +.day-cell.active { + border-color: rgba(118, 168, 150, 0.35); + background: var(--sage-soft); +} + +.day-cell strong, +.day-cell span { + display: block; +} + +.day-cell strong { + font-size: 14px; +} + +.day-cell span { + margin-top: 9px; + color: var(--muted); + font-size: 11px; +} + +.daily-list { + display: grid; + gap: 9px; + margin-top: 14px; +} + +.daily-row { + display: grid; + grid-template-columns: 100px repeat(4, 1fr); + gap: 12px; + padding: 13px 16px; + border-radius: 16px; + background: rgba(255, 253, 248, 0.72); +} + +.daily-row strong { + color: var(--peach-dark); +} + +.daily-row span { + color: var(--muted); +} + +.stats-week-grid { + display: grid; + grid-template-columns: repeat(5, 1fr); + gap: 10px; +} + +.stats-week-card { + padding: 14px; + border: 1px solid var(--border); + border-radius: 18px; + background: rgba(255, 253, 248, 0.76); +} + +.stats-week-card.review { + background: rgba(223, 238, 231, 0.66); +} + +.stats-week-card.active { + border-color: rgba(245, 166, 91, 0.55); + box-shadow: 0 7px 19px rgba(217, 121, 53, 0.09); +} + +.stats-week-card header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.stats-week-card header strong { + font-size: 18px; +} + +.stats-week-card header span { + color: var(--muted); + font-size: 11px; +} + +.week-metrics { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 7px; + margin-top: 12px; + color: var(--muted); + font-size: 12px; +} + +.two-column { + display: grid; + grid-template-columns: 0.8fr 1.2fr; + gap: 28px; +} + +.actor-stats, +.session-list { + display: grid; + gap: 9px; +} + +.actor-card, +.session-card { + padding: 14px 16px; + border-radius: 17px; + background: rgba(255, 253, 248, 0.78); +} + +.actor-card header, +.session-card header { + display: flex; + justify-content: space-between; + gap: 12px; +} + +.actor-card p, +.session-card p { + margin: 8px 0 0; + color: var(--muted); + font-size: 12px; + line-height: 1.5; +} + +.song-search input { + width: min(300px, 48vw); + min-height: 44px; + padding: 10px 13px; + border: 1px solid var(--border); + border-radius: 14px; + color: var(--ink); + background: rgba(255, 253, 248, 0.9); +} + +.song-table-wrap { + overflow-x: auto; + border-radius: 22px; + background: rgba(255, 253, 248, 0.84); + box-shadow: 0 12px 34px rgba(78, 62, 38, 0.07); +} + +table { + width: 100%; + border-collapse: collapse; + min-width: 900px; +} + +th, +td { + padding: 13px 15px; + border-bottom: 1px solid var(--border); + text-align: left; + vertical-align: top; +} + +th { + position: sticky; + top: 0; + color: var(--muted); + background: #f3eee3; + font-size: 12px; +} + +td { + font-size: 13px; +} + +td strong, +td small { + display: block; +} + +td small { + margin-top: 4px; + color: var(--muted); +} + +.stats-empty { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + inset: 0; + z-index: 10; + display: grid; + place-content: center; + justify-items: center; + padding: 28px; + background: var(--cream); + text-align: center; +} + +.stats-empty[hidden] { + display: none; +} + +.stats-empty > span { + width: 78px; + height: 78px; + display: grid; + place-items: center; + margin-bottom: 18px; + border-radius: 26px; + color: white; + background: var(--peach); + font-size: 36px; +} + +.stats-empty p { + max-width: 420px; + color: var(--muted); +} + +.stats-empty .primary-button { + display: inline-grid; + place-items: center; + margin-top: 8px; + text-decoration: none; +} + +@media (max-width: 900px) { + .summary-cards { + grid-template-columns: repeat(3, 1fr); + } + + .stats-week-grid { + grid-template-columns: repeat(4, 1fr); + } + + .two-column { + grid-template-columns: 1fr; + } +} + +@media (max-width: 620px) { + .stats-shell { + width: min(calc(100% - 22px), 580px); + } + + .stats-topbar { + min-height: 128px; + grid-template-columns: 1fr auto; + } + + .stats-topbar > div { + grid-column: 1 / -1; + grid-row: 1; + } + + .back-link { + grid-column: 1; + grid-row: 2; + } + + .updated-at { + grid-column: 2; + grid-row: 2; + } + + .summary-cards { + grid-template-columns: repeat(2, 1fr); + } + + .summary-card { + min-height: 110px; + } + + .summary-card strong { + margin-top: 14px; + } + + .stats-section { + padding-top: 42px; + } + + .calendar-card { + padding: 10px; + } + + .weekday-row, + .daily-grid { + gap: 5px; + } + + .day-cell { + min-height: 58px; + padding: 6px; + border-radius: 11px; + } + + .day-cell span { + margin-top: 5px; + font-size: 9px; + } + + .daily-row { + grid-template-columns: 82px repeat(2, 1fr); + } + + .daily-row span:nth-last-child(-n + 2) { + display: none; + } + + .stats-week-grid { + grid-template-columns: repeat(2, 1fr); + } + + .song-heading-row { + align-items: stretch; + flex-direction: column; + } + + .song-search input { + width: 100%; + } + + .song-table-wrap { + overflow: visible; + background: transparent; + box-shadow: none; + } + + table, + tbody { + width: 100%; + min-width: 0; + display: block; + } + + thead { + display: none; + } + + tbody { + display: grid; + gap: 10px; + } + + tbody tr { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 7px 12px; + padding: 15px; + border: 1px solid var(--border); + border-radius: 17px; + background: rgba(255, 253, 248, 0.82); + } + + tbody td { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + padding: 0; + border: 0; + } + + tbody td:first-child { + display: block; + grid-column: 1 / -1; + padding-bottom: 7px; + border-bottom: 1px solid var(--border); + } + + tbody td[data-label]::before { + content: attr(data-label); + color: var(--muted); + font-size: 10px; + } +} diff --git a/public/stats.html b/public/stats.html new file mode 100644 index 0000000..e1d0df2 --- /dev/null +++ b/public/stats.html @@ -0,0 +1,113 @@ + + + + + + + + + + SSS 红花与播放统计 + + +
+
+ ‹ 返回播放 +
+

家长查看

+

红花统计

+
+ 正在更新… +
+ +
+
+ +
+
+
+

最近六周

+

每天红花情况

+
+ 有红花 +
+
+ +
+
+
+
+ +
+
+
+

完整计划

+

50 周学习情况

+
+
+
+
+ +
+
+
+
+

操作记录

+

家庭成员

+
+
+
+
+
+
+
+

最近记录

+

最近小红花

+
+
+
+
+
+ +
+
+
+

逐首查看

+

每首歌的播放与红花

+
+ +
+
+ + + + + + + + + + + + +
歌曲视频完成/开始音频完成/开始小红花操作者最近播放
+
+
+
+
+ + + + + + diff --git a/public/stats.js b/public/stats.js new file mode 100644 index 0000000..de6eed0 --- /dev/null +++ b/public/stats.js @@ -0,0 +1,186 @@ +const elements = { + updatedAt: document.querySelector("#updated-at"), + summaryCards: document.querySelector("#summary-cards"), + dailyGrid: document.querySelector("#daily-grid"), + dailyList: document.querySelector("#daily-list"), + weekGrid: document.querySelector("#stats-week-grid"), + actorStats: document.querySelector("#actor-stats"), + sessionList: document.querySelector("#session-list"), + songSearch: document.querySelector("#song-search"), + songTableBody: document.querySelector("#song-table-body"), + empty: document.querySelector("#stats-empty"), +}; + +let statistics = null; + +function escapeHtml(value) { + return String(value == null ? "" : value) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +function formatDateTime(value) { + if (!value) return "—"; + return new Intl.DateTimeFormat("zh-CN", { + month: "numeric", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + }).format(new Date(value)); +} + +function formatDay(value) { + const date = new Date(`${value}T12:00:00`); + return `${date.getMonth() + 1}/${date.getDate()}`; +} + +async function loadStatistics() { + const response = await fetch("/api/statistics"); + if (!response.ok) throw new Error("无法读取统计数据"); + statistics = await response.json(); + render(); +} + +function render() { + const { summary } = statistics; + elements.updatedAt.textContent = `更新于 ${formatDateTime(statistics.generated_at)}`; + elements.empty.hidden = summary.video_plays + summary.audio_plays > 0; + renderSummary(); + renderDaily(); + renderWeeks(); + renderActors(); + renderSessions(); + renderSongs(elements.songSearch.value); +} + +function renderSummary() { + const summary = statistics.summary; + const cards = [ + ["获得小红花", summary.checkins, "朵"], + ["完成整轮", summary.round_checkins, "轮"], + ["学习天数", summary.active_days, "天"], + ["连续学习", summary.streak, "天"], + ["视频完整播放", summary.video_plays, "次"], + ["音频完整播放", summary.audio_plays, "次"], + ]; + elements.summaryCards.innerHTML = cards + .map( + ([label, value, unit]) => ` +
+ ${escapeHtml(label)} + ${escapeHtml(value)} ${escapeHtml(unit)} +
`, + ) + .join(""); +} + +function renderDaily() { + elements.dailyGrid.innerHTML = statistics.daily + .map((day) => { + const active = day.checkins > 0; + const details = active + ? `${day.checkins} 朵红花 · ${day.video_plays + day.audio_plays} 次播放` + : "没有红花"; + return ` +
+ ${formatDay(day.date)} + ${active ? `${day.checkins} 朵` : "—"} +
`; + }) + .join(""); + + const activeDays = statistics.daily.slice().reverse().filter((day) => day.checkins || day.video_plays || day.audio_plays); + elements.dailyList.innerHTML = activeDays.length + ? activeDays + .slice(0, 12) + .map( + (day) => ` +
+ ${formatDay(day.date)} + ${day.checkins} 朵红花 + ${day.video_plays} 次视频 + ${day.audio_plays} 次音频 + ${escapeHtml(day.actors.join("、") || "—")} +
`, + ) + .join("") + : '
暂无完整播放后自动生成
'; +} + +function renderWeeks() { + elements.weekGrid.innerHTML = statistics.weeks + .map((week) => { + const active = week.video_plays + week.audio_plays > 0; + return ` +
+
+ 第 ${week.number} 周 + ${week.kind === "review" ? "复习" : escapeHtml(week.category || "课程")} +
+
+ ${week.checkins} 红花 + ${week.active_days} 天 + ${week.video_plays} 视频 + ${week.audio_plays} 音频 +
+
`; + }) + .join(""); +} + +function renderActors() { + elements.actorStats.innerHTML = statistics.actors.length + ? statistics.actors + .map( + (actor) => ` +
+
${escapeHtml(actor.actor)}${actor.checkins_started} 朵红花
+

${actor.video_plays} 次视频 · ${actor.audio_plays} 次音频

+
`, + ) + .join("") + : '
暂无操作记录
'; +} + +function renderSessions() { + elements.sessionList.innerHTML = statistics.recent_sessions.length + ? statistics.recent_sessions + .slice(0, 12) + .map( + (session) => ` +
+
${formatDateTime(session.started_at)}${escapeHtml(session.actor)}获得
+

${session.kind === "round" ? "完成整轮小红花" : `${escapeHtml(session.songs.join("、"))} 歌曲小红花`}

+
`, + ) + .join("") + : '
暂无小红花
'; +} + +function renderSongs(query = "") { + const needle = query.trim().toLowerCase(); + const songs = statistics.songs.filter( + (song) => !needle || song.id.includes(needle) || song.title.toLowerCase().includes(needle), + ); + elements.songTableBody.innerHTML = songs + .map( + (song) => ` + + ${escapeHtml(song.title)}${escapeHtml(song.id)} · 第 ${song.week} 周 + ${song.video_plays} / ${song.video_starts} + ${song.audio_plays} / ${song.audio_starts} + ${song.checkins} + ${escapeHtml(song.actors.join("、") || "—")} + ${formatDateTime(song.last_played_at)} + `, + ) + .join(""); +} + +elements.songSearch.addEventListener("input", () => renderSongs(elements.songSearch.value)); +loadStatistics().catch((error) => { + elements.updatedAt.textContent = error.message; +}); diff --git a/public/styles.css b/public/styles.css new file mode 100644 index 0000000..9e5c004 --- /dev/null +++ b/public/styles.css @@ -0,0 +1,2169 @@ +:root { + color-scheme: light; + --ink: #25322d; + --muted: #718079; + --paper: #fffdf8; + --cream: #f8f3e8; + --peach: #f5a65b; + --peach-dark: #d97935; + --sage: #76a896; + --sage-dark: #4e7567; + --sage-soft: #dfeee7; + --sun: #f8cf67; + --border: rgba(37, 50, 45, 0.12); + --shadow: 0 18px 45px rgba(78, 62, 38, 0.11); + font-family: ui-rounded, "SF Pro Rounded", "PingFang SC", "Microsoft YaHei", sans-serif; +} + +* { + box-sizing: border-box; +} + +[hidden] { + display: none !important; +} + +html { + scroll-behavior: smooth; +} + +body { + min-height: 100vh; + margin: 0; + color: var(--ink); + background: + radial-gradient(circle at 8% 5%, rgba(248, 207, 103, 0.28), transparent 25rem), + radial-gradient(circle at 92% 20%, rgba(118, 168, 150, 0.22), transparent 24rem), + var(--cream); +} + +body.modal-open { + overflow: hidden; +} + +button, +input, +select, +audio { + font: inherit; +} + +button, +select { + cursor: pointer; +} + +button:focus-visible, +input:focus-visible, +select:focus-visible, +video:focus-visible, +audio:focus-visible, +a:focus-visible { + outline: 3px solid rgba(245, 166, 91, 0.46); + outline-offset: 3px; +} + +.page-shell { + width: calc(100% - 32px); + max-width: 1080px; + width: min(1080px, calc(100% - 32px)); + margin: 0 auto; +} + +.startup-status { + margin: 12px 0; + padding: 11px 14px; + border-radius: 14px; + color: var(--sage-dark); + background: var(--sage-soft); + font-size: 13px; + font-weight: 800; + text-align: center; +} + +.topbar { + min-height: 68px; + display: flex; + align-items: center; +} + +.week-top-title { + margin: 0; + font-size: 42px; + line-height: 1; + letter-spacing: -0.05em; +} + +.brand { + display: inline-flex; + align-items: center; + gap: 12px; + color: var(--ink); + text-decoration: none; +} + +.brand-mark { + width: 46px; + height: 46px; + display: grid; + place-items: center; + border-radius: 16px 16px 16px 6px; + color: white; + background: var(--peach); + box-shadow: 0 9px 22px rgba(217, 121, 53, 0.28); + font-size: 26px; +} + +.brand strong, +.brand small { + display: block; +} + +.brand strong { + font-size: 18px; +} + +.brand small { + margin-top: 2px; + color: var(--muted); +} + +.identity-chip { + min-height: 44px; + display: inline-flex; + align-items: center; + gap: 8px; + padding: 10px 14px; + border: 1px solid var(--border); + border-radius: 15px; + color: var(--ink); + background: rgba(255, 253, 248, 0.88); +} + +.hero { + position: relative; + overflow: hidden; + min-height: 190px; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + grid-template-rows: auto auto; + align-items: center; + gap: 28px; + padding: 28px 34px; + border: 1px solid rgba(255, 255, 255, 0.9); + border-radius: 34px; + background: linear-gradient(135deg, #fffdf8, #fff6df); + box-shadow: var(--shadow); +} + +.hero::before, +.hero::after { + content: ""; + position: absolute; + border-radius: 50%; + pointer-events: none; +} + +.hero::before { + width: 230px; + height: 230px; + right: -72px; + top: -90px; + background: rgba(118, 168, 150, 0.15); +} + +.hero::after { + width: 132px; + height: 132px; + right: 29%; + bottom: -84px; + background: rgba(248, 207, 103, 0.2); +} + +.hero-copy, +.today-card { + position: relative; + z-index: 1; +} + +.hero-copy { + grid-column: 1; + grid-row: 1; +} + +.today-card { + grid-column: 2; + grid-row: 1 / span 2; +} + +.eyebrow { + margin: 0 0 8px; + color: var(--peach-dark); + font-size: 12px; + font-weight: 800; + letter-spacing: 0.12em; +} + +h1, +h2, +h3, +p { + margin-top: 0; +} + +h1 { + margin-bottom: 10px; + font-size: 56px; + font-size: clamp(40px, 7vw, 68px); + line-height: 1; + letter-spacing: -0.05em; +} + +h2 { + margin-bottom: 0; + font-size: 30px; + font-size: clamp(24px, 4vw, 34px); + letter-spacing: -0.035em; +} + +.week-category { + margin-bottom: 0; + color: var(--muted); + font-size: 18px; +} + +.study-date-label { + margin: 0; + color: var(--peach-dark); + font-size: 13px; + font-weight: 800; +} + +.study-line { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px; +} + +.study-line .eyebrow { + margin: 0; +} + +.week-nav { + grid-column: 1; + grid-row: 2; + display: flex; + flex-wrap: nowrap; + gap: 9px; + margin-top: 25px; +} + +.soft-button, +.primary-button, +.round-button, +.icon-button { + border: 0; +} + +.soft-button { + white-space: nowrap; + min-height: 42px; + padding: 10px 15px; + border-radius: 13px; + color: var(--ink); + background: rgba(37, 50, 45, 0.07); +} + +.soft-button.accent { + color: #855024; + background: rgba(245, 166, 91, 0.18); +} + +.primary-button { + min-height: 46px; + padding: 12px 20px; + border-radius: 14px; + color: white; + background: var(--peach-dark); + box-shadow: 0 10px 24px rgba(217, 121, 53, 0.22); + font-weight: 800; +} + +.today-card { + min-width: 210px; + display: grid; + gap: 9px; + padding: 12px; + border-radius: 22px; + background: rgba(255, 253, 248, 0.76); + box-shadow: 0 15px 35px rgba(78, 62, 38, 0.08); + text-align: center; +} + +.today-card .identity-chip { + width: 100%; + min-height: 39px; + justify-content: center; + padding: 7px 10px; + background: rgba(255, 255, 255, 0.76); +} + +.today-metrics { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 7px; +} + +.today-metrics > span { + display: block; + padding: 3px 0; +} + +.today-metrics strong, +.today-metrics small { + display: block; +} + +.today-metrics strong { + font-size: 22px; + line-height: 1; +} + +.today-metrics small { + margin-top: 4px; + color: var(--muted); + font-size: 11px; +} + +.achievement-section { + margin-top: 42px; + padding: 24px; + border: 1px solid rgba(255, 255, 255, 0.9); + border-radius: 28px; + background: linear-gradient(135deg, rgba(255, 253, 248, 0.9), rgba(255, 241, 220, 0.8)); + box-shadow: 0 14px 36px rgba(78, 62, 38, 0.07); +} + +.achievement-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 18px; +} + +.achievement-summary { + display: flex; + align-items: center; + gap: 5px; + padding: 10px 14px; + border-radius: 999px; + color: #a74a52; + background: rgba(255, 226, 228, 0.86); +} + +.achievement-summary span { + font-size: 20px; +} + +.achievement-summary strong { + font-size: 20px; +} + +.achievement-summary small { + color: #a56a70; +} + +.achievement-copy { + margin: 8px 0 18px; + color: var(--muted); + font-size: 13px; +} + +.progress-calendar { + padding: 13px; + border-radius: 21px; + background: rgba(255, 255, 255, 0.62); +} + +.progress-weekdays, +.progress-grid { + display: grid; + grid-template-columns: repeat(7, minmax(0, 1fr)); + gap: 7px; +} + +.progress-weekdays { + margin-bottom: 7px; + color: var(--muted); + text-align: center; + font-size: 11px; + font-weight: 800; +} + +.progress-day { + position: relative; + min-width: 0; + min-height: 70px; + display: grid; + place-items: center; + align-content: center; + gap: 4px; + padding: 7px 3px; + border: 1px solid var(--border); + border-radius: 14px; + color: var(--ink); + background: rgba(255, 253, 248, 0.82); +} + +.progress-day strong { + font-size: 13px; +} + +.progress-day small { + min-height: 15px; + color: var(--muted); + font-size: 9px; + line-height: 1.2; +} + +.progress-day.complete { + border-color: rgba(235, 119, 129, 0.42); + background: linear-gradient(145deg, #fff4e8, #ffe2e4); +} + +.progress-day.progress { + border-color: rgba(118, 168, 150, 0.42); + background: var(--sage-soft); +} + +.progress-day.missed { + color: #9b8371; + border-style: dashed; + background: rgba(255, 255, 255, 0.42); +} + +.progress-day.future, +.progress-day.locked { + opacity: 0.34; + cursor: default; +} + +.progress-day.is-today { + box-shadow: 0 0 0 3px rgba(245, 166, 91, 0.35); +} + +.progress-day.selected { + border-color: var(--peach); + box-shadow: 0 0 0 3px rgba(245, 166, 91, 0.35); +} + +.progress-day .day-flower { + font-size: 16px; + line-height: 1; +} + +.progress-day.missed .day-flower { + color: #c7b9ad; + filter: grayscale(1); +} + +.progress-legend { + display: flex; + flex-wrap: wrap; + gap: 15px; + margin-top: 12px; + color: var(--muted); + font-size: 11px; +} + +.progress-legend span { + display: inline-flex; + align-items: center; + gap: 5px; +} + +.legend-dot { + width: 10px; + height: 10px; + border-radius: 50%; +} + +.legend-dot.complete { + background: #eb7781; +} + +.legend-dot.progress { + background: var(--sage); +} + +.legend-dot.missed { + border: 1px dashed #a9988a; +} + +.playlist-control { + margin-top: 18px; + display: flex; + align-items: center; + justify-content: center; + gap: 14px; + padding: 12px 16px; + border: 1px solid rgba(118, 168, 150, 0.28); + border-radius: 25px; + background: linear-gradient(135deg, rgba(239, 248, 243, 0.94), rgba(255, 250, 225, 0.9)); + box-shadow: 0 14px 34px rgba(78, 62, 38, 0.07); +} + +.playlist-description { + margin: 0; + color: var(--muted); + font-size: 12px; +} + +.playlist-loop-button { + min-width: 132px; + min-height: 46px; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 9px; + padding: 10px 15px; + border-radius: 15px; + color: white; + background: var(--peach-dark); + box-shadow: 0 11px 26px rgba(217, 121, 53, 0.2); + font-weight: 900; +} + +.playlist-loop-button.playing { + background: var(--sage-dark); +} + +.playlist-loop-button span { + font-size: 18px; +} + +/* Keep the native audio element alive for iOS lock-screen playback without + giving it a second visible control bar. */ +.weekly-loop-player { + position: absolute; + width: 1px; + height: 1px; + opacity: 0; + pointer-events: none; +} + +/* The 5s-sized iOS 10 device defaults here. Keep only listening controls in + reach; the quiet settings button remains available to a parent. */ +body.child-mode .hero, +body.child-mode .achievement-section, +body.child-mode .plan-section, +body.child-mode .round-checkin { + display: none; +} + +body.child-mode .topbar { + justify-content: center; + min-height: 68px; +} + +body.child-mode .week-top-title { + font-size: clamp(27px, 8vw, 38px); +} + +body.child-mode .playlist-control { + margin-top: 6px; + padding: 16px; +} + +body.child-mode .playlist-description { + max-width: 150px; + font-size: 11px; + line-height: 1.45; +} + +body.child-mode .player-section { + padding-top: 18px; +} + +body.child-mode .child-song-card { + border-radius: 23px; +} + +body.child-mode .child-song-card .song-card-heading { + padding: 15px 17px 11px; +} + +body.child-mode .child-song-card .song-card-heading p { + margin-bottom: 2px; + font-size: 10px; +} + +body.child-mode .child-song-card .song-card-heading h3 { + font-size: clamp(20px, 6.2vw, 27px); +} + +body.child-mode .child-audio-panel { + background: linear-gradient(135deg, #5e9584, #335f55); +} + +body.child-mode .child-audio-panel::after { + background: linear-gradient(180deg, rgba(20, 29, 25, 0.04), rgba(20, 29, 25, 0.42)); +} + +body.child-mode footer { + justify-content: center; + margin-top: 24px; + padding: 4px 0 15px; + background: transparent; + box-shadow: none; +} + +body.child-mode footer > div { + display: none; +} + +body.child-mode .footer-settings-button { + width: auto; + min-height: 35px; + padding: 6px 10px; + color: var(--muted); + background: rgba(37, 50, 45, 0.05); + box-shadow: none; + font-size: 11px; + opacity: 0.72; +} + +.player-section { + padding-top: 24px; +} + +.plan-section { + padding-top: 58px; +} + +.section-heading { + display: flex; + align-items: end; + justify-content: space-between; + gap: 18px; + margin-bottom: 20px; +} + +.loop-toggle { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 9px 12px; + border: 1px solid var(--border); + border-radius: 999px; + color: var(--muted); + background: rgba(255, 253, 248, 0.75); + font-size: 14px; + font-weight: 700; +} + +.loop-toggle input { + width: 18px; + height: 18px; + accent-color: var(--sage); +} + +.media-card { + overflow: hidden; + border: 1px solid rgba(255, 255, 255, 0.9); + border-radius: 28px; + background: rgba(255, 253, 248, 0.92); + box-shadow: var(--shadow); +} + +.mode-tabs { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 7px; + padding: 10px; + background: rgba(37, 50, 45, 0.04); +} + +.mode-tab { + min-height: 50px; + border: 0; + border-radius: 15px; + color: var(--muted); + background: transparent; + font-weight: 800; +} + +.mode-tab span { + margin: 0; + font-size: 21px; +} + +.mode-tab.selected { + color: var(--peach-dark); + background: var(--paper); + box-shadow: 0 6px 20px rgba(78, 62, 38, 0.08); +} + +.media-panel { + position: relative; + background: #17211d; +} + +.video-panel { + aspect-ratio: 16 / 9; +} + +.video-panel video { + width: 100%; + height: 100%; + display: block; + object-fit: contain; +} + +.center-play { + position: absolute; + top: 50%; + left: 50%; + inset: 50% auto auto 50%; + transform: translate(-50%, -50%); + min-width: 170px; + min-height: 52px; + padding: 12px 20px; + border: 0; + border-radius: 999px; + color: white; + background: rgba(217, 121, 53, 0.94); + box-shadow: 0 14px 34px rgba(0, 0, 0, 0.25); + font-weight: 800; +} + +.audio-panel { + min-height: 430px; + overflow: hidden; +} + +.audio-panel > img { + width: 100%; + height: 430px; + display: block; + object-fit: cover; + filter: blur(16px) brightness(0.58) saturate(1.2); + transform: scale(1.08); +} + +.audio-overlay { + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + inset: 0; + display: grid; + place-content: center; + justify-items: center; + padding: 28px; + color: white; + text-align: center; +} + +.audio-disc { + width: 110px; + height: 110px; + display: grid; + place-items: center; + margin-bottom: 20px; + border-radius: 50%; + color: var(--ink); + background: var(--sun); + box-shadow: 0 12px 35px rgba(0, 0, 0, 0.28); + font-size: 42px; +} + +.audio-overlay p { + margin-bottom: 8px; + opacity: 0.75; +} + +.audio-overlay strong { + max-width: 620px; + font-size: clamp(24px, 5vw, 40px); +} + +.lyrics-panel { + max-height: min(76vh, 940px); + overflow: auto; + background: #edf0e8; +} + +.lyrics-panel img { + width: min(100%, 760px); + height: auto; + display: block; + margin: 0 auto; + background: white; +} + +.audio-controls { + display: grid; + grid-template-columns: 46px minmax(0, 1fr) 46px; + align-items: center; + gap: 12px; + padding: 14px 18px; + background: var(--sage-soft); +} + +.audio-controls audio { + width: 100%; +} + +.round-button { + width: 44px; + height: 44px; + border-radius: 50%; + color: white; + background: var(--sage); + font-size: 28px; + line-height: 1; +} + +.now-playing { + display: flex; + align-items: center; + justify-content: space-between; + gap: 18px; + padding: 20px 22px 22px; +} + +.song-id { + display: inline-flex; + padding: 5px 9px; + border-radius: 999px; + color: var(--sage-dark); + background: var(--sage-soft); + font-size: 12px; + font-weight: 800; +} + +.now-playing h3 { + margin: 9px 0 0; + font-size: clamp(20px, 4vw, 29px); +} + +.play-status { + flex: 0 0 auto; + padding: 8px 11px; + border-radius: 999px; + color: #855024; + background: #fff1dc; + font-size: 12px; + font-weight: 700; +} + +.playlist { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 12px; + margin-top: 16px; +} + +.playlist-item { + min-width: 0; + min-height: 118px; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: stretch; + border: 1px solid var(--border); + border-radius: 19px; + color: var(--ink); + background: rgba(255, 253, 248, 0.82); + text-align: left; + overflow: hidden; +} + +.playlist-item.selected { + border-color: rgba(245, 166, 91, 0.7); + background: #fff4e2; + box-shadow: 0 8px 24px rgba(217, 121, 53, 0.12); +} + +.playlist-select { + min-width: 0; + display: flex; + align-items: center; + gap: 12px; + padding: 13px 8px 13px 13px; + border: 0; + color: inherit; + background: transparent; + text-align: left; +} + +.playlist-index { + flex: 0 0 auto; + width: 46px; + height: 46px; + display: grid; + place-items: center; + border-radius: 16px; + color: var(--sage-dark); + background: var(--sage-soft); + font-weight: 900; +} + +.playlist-item.selected .playlist-index { + color: white; + background: var(--peach); +} + +.playlist-text { + min-width: 0; +} + +.playlist-text strong, +.playlist-text small { + display: block; +} + +.playlist-text strong { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.playlist-text small { + margin-top: 5px; + color: var(--muted); +} + +.flower-strip { + min-width: 158px; + display: grid; + grid-template-columns: repeat(3, 44px); + justify-content: center; + align-content: center; + gap: 6px; + padding: 10px; + border-left: 1px solid var(--border); + background: rgba(255, 255, 255, 0.48); +} + +.flower-slot { + width: 44px; + height: 44px; + display: grid; + place-items: center; + padding: 0; + border: 1px solid rgba(37, 50, 45, 0.08); + border-radius: 14px; + color: #c8bdb3; + background: rgba(37, 50, 45, 0.055); + filter: grayscale(1); + font-size: 25px; + line-height: 1; +} + +.flower-slot.filled { + color: #eb7781; + border-color: rgba(235, 119, 129, 0.2); + background: #fff0f1; + filter: none; +} + +.flower-slot.ready { + color: #eb7781; + border-color: rgba(235, 119, 129, 0.46); + background: #ffe2e4; + box-shadow: 0 7px 18px rgba(235, 119, 129, 0.24); + filter: none; + animation: flower-ready 1.15s ease-in-out infinite; +} + +.flower-slot[aria-disabled="true"] { + cursor: help; +} + +.flower-hint { + grid-column: 1 / -1; + margin-top: 2px; + color: var(--muted); + text-align: center; + font-size: 9px; + line-height: 1.2; +} + +@keyframes flower-ready { + 0%, 100% { transform: scale(1); } + 50% { transform: scale(1.26) rotate(-7deg); } +} + +.song-cards { + display: block; +} + +.song-media-card + .song-media-card { + margin-top: 24px; +} + +.song-media-card { + overflow: hidden; + border: 1px solid rgba(255, 255, 255, 0.92); + border-radius: 28px; + background: rgba(255, 253, 248, 0.94); + box-shadow: var(--shadow); +} + +.song-card-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 18px; + padding: 20px 22px 14px; +} + +.song-card-heading p { + margin: 0 0 4px; + color: var(--peach-dark); + font-size: 11px; + font-weight: 900; + letter-spacing: 0.12em; +} + +.song-card-heading h3 { + margin: 0; + font-size: 25px; + font-size: clamp(21px, 4vw, 30px); + line-height: 1.15; +} + +.song-media-card .mode-tabs { + border-top: 1px solid rgba(37, 50, 45, 0.06); +} + +.song-media-shell { + background: #17211d; +} + +.song-media-panel { + position: relative; + width: 100%; + height: 0; + padding-top: 56.25%; + overflow: hidden; + background: #17211d; +} + +.song-video-panel video { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: auto; + display: block; + object-fit: contain; + background: #17211d; +} + +.song-audio-panel { + cursor: pointer; + isolation: isolate; +} + +@supports (aspect-ratio: 16 / 9) { + .song-media-panel { + height: auto; + padding-top: 0; + aspect-ratio: 16 / 9; + } + + .song-video-panel video { + top: 0; + right: 0; + bottom: 0; + left: 0; + inset: 0; + height: 100%; + } +} + +.song-audio-panel > img { + position: absolute; + top: -5%; + right: -5%; + bottom: -5%; + left: -5%; + inset: -5%; + z-index: -2; + width: 110%; + height: 110%; + object-fit: cover; + filter: blur(17px) brightness(0.5) saturate(1.2); +} + +.song-audio-panel::after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + inset: 0; + z-index: -1; + background: linear-gradient(180deg, rgba(20, 29, 25, 0.08), rgba(20, 29, 25, 0.54)); +} + +.audio-toggle { + position: absolute; + top: 0; + right: 0; + bottom: 58px; + left: 0; + inset: 0 0 58px; + width: 100%; + display: grid; + place-content: center; + justify-items: center; + gap: 8px; + padding: 22px; + border: 0; + color: white; + background: transparent; + text-align: center; +} + +.audio-toggle .audio-disc { + width: 88px; + height: 88px; + width: clamp(72px, 12vw, 104px); + height: clamp(72px, 12vw, 104px); + margin: 0 0 4px; + font-size: 36px; + font-size: clamp(30px, 5vw, 42px); + transition: 220ms ease; +} + +.song-audio-panel.playing .audio-disc { + transform: scale(1.07) rotate(7deg); + box-shadow: 0 0 0 9px rgba(248, 207, 103, 0.18), 0 16px 38px rgba(0, 0, 0, 0.3); +} + +.audio-toggle strong { + font-size: 22px; + font-size: clamp(18px, 3.5vw, 27px); +} + +.audio-toggle small { + max-width: 80%; + overflow: hidden; + color: rgba(255, 255, 255, 0.78); + text-overflow: ellipsis; + white-space: nowrap; +} + +.audio-timeline { + position: absolute; + right: 0; + bottom: 0; + left: 0; + inset: auto 0 0; + height: 58px; + display: grid; + grid-template-columns: 48px minmax(0, 1fr) 48px; + align-items: center; + gap: 10px; + padding: 0 18px; + color: white; + background: rgba(15, 23, 20, 0.72); + backdrop-filter: blur(12px); + font-size: 12px; + font-variant-numeric: tabular-nums; +} + +.audio-timeline input { + width: 100%; + accent-color: var(--sun); +} + +.audio-timeline span:last-child { + text-align: right; +} + +.song-lyrics-panel { + max-height: min(78vh, 960px); + overflow: auto; + background: #edf0e8; +} + +.song-lyrics-panel img { + width: min(100%, 760px); + height: auto; + display: block; + margin: 0 auto; + background: white; +} + +.song-card-reward { + display: flex; + justify-content: center; + padding: 20px 18px 22px; + background: rgba(255, 253, 248, 0.96); +} + +.song-card-reward .flower-strip { + width: 50%; + min-width: 360px; + max-width: 520px; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 14px; + border: 0; + padding: 0; + background: transparent; +} + +.flower-time-slot { + min-width: 0; + display: grid; + justify-items: center; + gap: 8px; + color: var(--muted); + font-size: 11px; + font-weight: 800; + white-space: nowrap; +} + +.song-card-reward .flower-slot { + width: 70px; + height: 70px; + border-radius: 22px; + font-size: 39px; +} + +.round-checkin { + display: grid; + justify-items: center; + gap: 13px; + margin-top: 18px; + padding: 22px 16px 17px; + border: 1px solid rgba(235, 119, 129, 0.2); + border-radius: 24px; + background: linear-gradient(135deg, rgba(255, 253, 248, 0.86), rgba(255, 226, 228, 0.55)); +} + +.round-flower-strip { + width: 85%; + max-width: 820px; + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + justify-items: center; + gap: 22px; +} + +.round-flower-button { + width: 88px; + height: 88px; + display: grid; + place-items: center; + padding: 0; + border: 1px solid rgba(37, 50, 45, 0.1); + border-radius: 22px; + color: #c8bdb3; + background: rgba(255, 255, 255, 0.78); + filter: grayscale(1); + font-size: 51px; + transition: 280ms ease; +} + +.round-hint { + margin: 0; + color: #9a6570; + font-size: 12px; + font-weight: 800; + text-align: center; +} + +.round-flower-button[aria-disabled="true"] { + cursor: help; +} + +.round-flower-button.filled { + color: #eb7781; + border-color: rgba(235, 119, 129, 0.25); + background: #fff0f1; + filter: none; + transform: rotate(-8deg) scale(1.08); +} + +.round-flower-button.ready { + color: #eb7781; + border-color: rgba(235, 119, 129, 0.5); + background: #ffe2e4; + box-shadow: 0 10px 28px rgba(235, 119, 129, 0.34); + filter: none; + animation: flower-ready 1.05s ease-in-out infinite; +} + +.week-grid { + display: grid; + grid-template-columns: repeat(10, 1fr); + gap: 9px; +} + +.week-cell { + aspect-ratio: 1; + display: grid; + place-items: center; + border: 1px solid var(--border); + border-radius: 13px; + color: var(--ink); + background: rgba(255, 253, 248, 0.74); + font-weight: 800; +} + +.week-cell.review { + color: var(--sage-dark); + background: rgba(223, 238, 231, 0.7); +} + +.week-cell.preview { + border-style: dashed; + opacity: 0.72; +} + +.week-cell.studied { + color: white; + border-color: var(--sage); + background: var(--sage); +} + +.week-cell.selected { + box-shadow: 0 0 0 3px rgba(245, 166, 91, 0.4); +} + +.summary-pill { + padding: 8px 12px; + border-radius: 999px; + color: var(--sage-dark); + background: var(--sage-soft); + font-weight: 800; +} + +footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 18px; + padding: 54px 0 34px; + color: var(--muted); + font-size: 13px; +} + +footer > div { + display: grid; + gap: 5px; +} + +.footer-settings-button { + min-height: 46px; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 7px; + padding: 10px 15px; + border: 1px solid var(--border); + border-radius: 15px; + color: var(--ink); + background: rgba(255, 253, 248, 0.82); + font-weight: 800; +} + +.modal { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + inset: 0; + z-index: 40; + display: flex; + align-items: center; + justify-content: center; + padding: 14px; + background: rgba(37, 50, 45, 0.48); + backdrop-filter: blur(6px); + overflow-y: auto; +} + +.modal > .dialog-body, +.modal > form { + width: calc(100% - 28px); + max-width: 500px; + margin: auto; + border-radius: 27px; + color: var(--ink); + background: var(--paper); + box-shadow: 0 30px 90px rgba(37, 50, 45, 0.3); +} + +.dialog-body, +.modal form { + padding: 28px; +} + +.dialog-heading, +.dialog-actions { + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; +} + +.dialog-copy { + margin: 12px 0 22px; + color: var(--muted); + line-height: 1.6; +} + +.icon-button { + width: 42px; + height: 42px; + border-radius: 14px; + color: var(--ink); + background: rgba(37, 50, 45, 0.06); + font-size: 22px; +} + +.identity-options { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 10px; +} + +.identity-option { + min-height: 86px; + display: grid; + place-items: center; + gap: 4px; + padding: 10px 6px; + border: 1px solid var(--border); + border-radius: 18px; + color: var(--ink); + background: #fff; + font-weight: 800; +} + +.identity-option span { + font-size: 25px; +} + +.identity-option.selected { + border-color: var(--peach); + background: #fff1dc; + box-shadow: 0 6px 18px rgba(217, 121, 53, 0.12); +} + +.modal form { + display: grid; + gap: 18px; +} + +.modal form > label, +.modal fieldset { + display: grid; + gap: 8px; + color: var(--muted); + font-size: 14px; + font-weight: 800; +} + +.modal fieldset { + padding: 0; + border: 0; +} + +.modal legend { + margin-bottom: 9px; +} + +.modal input, +.modal select { + width: 100%; + min-height: 48px; + padding: 11px 13px; + border: 1px solid var(--border); + border-radius: 14px; + color: var(--ink); + background: white; +} + +.modal input:disabled { + color: #918a82; + background: #ece9e2; + cursor: not-allowed; + opacity: 1; +} + +.field-help { + color: var(--muted); + font-size: 11px; + font-weight: 500; + line-height: 1.5; +} + +.modal form > label.mode-setting { + grid-template-columns: 24px minmax(0, 1fr); + align-items: center; + gap: 11px; + padding: 13px; + border-radius: 14px; + background: var(--sage-soft); + color: var(--ink); +} + +.mode-setting input[type="checkbox"] { + width: 21px; + min-height: 21px; + margin: 0; + padding: 0; + accent-color: var(--sage-dark); +} + +.mode-setting strong, +.mode-setting small { + display: block; +} + +.mode-setting small { + margin-top: 3px; + color: var(--muted); + font-size: 11px; + font-weight: 500; + line-height: 1.4; +} + +.stats-link { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 15px; + border-radius: 17px; + color: var(--ink); + background: var(--sage-soft); + text-decoration: none; +} + +.stats-link strong, +.stats-link small { + display: block; +} + +.stats-link small { + margin-top: 4px; + color: var(--sage-dark); +} + +.dialog-actions { + justify-content: flex-end; +} + +.toast { + position: fixed; + left: 50%; + bottom: max(22px, env(safe-area-inset-bottom)); + z-index: 20; + max-width: calc(100% - 32px); + padding: 11px 16px; + border-radius: 999px; + color: white; + background: rgba(37, 50, 45, 0.94); + opacity: 0; + pointer-events: none; + transform: translate(-50%, 10px); + transition: 180ms ease; +} + +.toast.visible { + opacity: 1; + transform: translate(-50%, 0); +} + +.celebration { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + inset: 0; + z-index: 50; + display: grid; + place-items: center; + padding: 24px; + background: rgba(37, 50, 45, 0.24); + backdrop-filter: blur(3px); +} + +.celebration-card { + position: relative; + z-index: 2; + width: calc(100vw - 42px); + max-width: 430px; + min-width: 0; + min-width: min(330px, calc(100vw - 42px)); + padding: 28px 26px; + border-radius: 30px; + background: linear-gradient(145deg, #fffdf8, #fff0d4); + box-shadow: 0 28px 80px rgba(73, 52, 34, 0.3); + text-align: center; + overflow: hidden; +} + +.celebration.celebrating .celebration-card { + animation: celebration-pop 700ms cubic-bezier(.18,.89,.32,1.28), reward-glow 1.4s ease-in-out 500ms; +} + +.reward-kicker { + display: inline-block; + margin-bottom: 2px; + color: var(--peach-dark); + font-size: 11px; + font-weight: 900; + letter-spacing: .22em; +} + +.celebration-flower { + display: block; + margin-bottom: 8px; + font-size: 82px; +} + +.celebration.celebrating .celebration-flower { + animation: celebration-flower 1050ms cubic-bezier(.18,.89,.32,1.28); +} + +.celebration-card strong { + display: block; + color: #a74a52; + font-size: 23px; +} + +.celebration-card p { + margin: 8px 0 0; + color: var(--muted); +} + +.petal-burst { + position: absolute; + inset: 50%; + z-index: 1; +} + +.petal-burst i { + position: absolute; + width: 18px; + height: 30px; + border-radius: 70% 30% 65% 35%; + background: #f28d97; + opacity: 0; +} + +.celebration.celebrating .petal-burst i { + animation: petal-fly 1.35s ease-out forwards; +} + +.petal-burst i:nth-child(2n) { background: var(--sun); } +.petal-burst i:nth-child(3n) { background: var(--sage); } +.petal-burst i:nth-child(1) { --x: -150px; --y: -120px; --r: -80deg; } +.petal-burst i:nth-child(2) { --x: -35px; --y: -180px; --r: 40deg; } +.petal-burst i:nth-child(3) { --x: 95px; --y: -145px; --r: 95deg; } +.petal-burst i:nth-child(4) { --x: 165px; --y: -30px; --r: 150deg; } +.petal-burst i:nth-child(5) { --x: 135px; --y: 115px; --r: 210deg; } +.petal-burst i:nth-child(6) { --x: 5px; --y: 175px; --r: 280deg; } +.petal-burst i:nth-child(7) { --x: -130px; --y: 120px; --r: 330deg; } +.petal-burst i:nth-child(8) { --x: -170px; --y: 0; --r: 390deg; } +.petal-burst i:nth-child(9) { --x: -110px; --y: -175px; --r: 450deg; } +.petal-burst i:nth-child(10) { --x: 55px; --y: -190px; --r: 510deg; } +.petal-burst i:nth-child(11) { --x: 185px; --y: 65px; --r: 560deg; } +.petal-burst i:nth-child(12) { --x: -35px; --y: 195px; --r: 620deg; } + +.spark-ring { + position: absolute; + z-index: 0; + width: 110px; + height: 110px; + border: 6px solid rgba(248, 207, 103, 0.8); + border-radius: 50%; + opacity: 0; +} + +.celebration.celebrating .spark-ring { + animation: spark-ring 1.05s ease-out 140ms; +} + +.sparkles { + position: absolute; + inset: 50%; + z-index: 3; + pointer-events: none; +} + +.sparkles i { + position: absolute; + color: #ffd75f; + opacity: 0; + font-size: 27px; + font-style: normal; + text-shadow: 0 0 14px rgba(255, 215, 95, 0.8); +} + +.celebration.celebrating .sparkles i { + animation: sparkle-pop 1.2s ease-out forwards; +} + +.sparkles i:nth-child(1) { --sx: -175px; --sy: -145px; animation-delay: .08s !important; } +.sparkles i:nth-child(2) { --sx: -75px; --sy: -205px; animation-delay: .18s !important; } +.sparkles i:nth-child(3) { --sx: 45px; --sy: -195px; animation-delay: .04s !important; } +.sparkles i:nth-child(4) { --sx: 165px; --sy: -120px; animation-delay: .22s !important; } +.sparkles i:nth-child(5) { --sx: 205px; --sy: 0; animation-delay: .12s !important; } +.sparkles i:nth-child(6) { --sx: 165px; --sy: 135px; animation-delay: .25s !important; } +.sparkles i:nth-child(7) { --sx: 55px; --sy: 200px; animation-delay: .15s !important; } +.sparkles i:nth-child(8) { --sx: -70px; --sy: 195px; animation-delay: .03s !important; } +.sparkles i:nth-child(9) { --sx: -185px; --sy: 125px; animation-delay: .2s !important; } +.sparkles i:nth-child(10) { --sx: -210px; --sy: -10px; animation-delay: .1s !important; } +.sparkles i:nth-child(11) { --sx: 110px; --sy: -170px; animation-delay: .3s !important; } +.sparkles i:nth-child(12) { --sx: -135px; --sy: 175px; animation-delay: .28s !important; } + +@keyframes celebration-pop { + 0% { opacity: 0; transform: scale(0.62) translateY(22px); } + 70% { transform: scale(1.04) translateY(0); } + 100% { opacity: 1; transform: scale(1); } +} + +@keyframes celebration-flower { + 0% { transform: scale(0.25) rotate(-30deg); } + 60% { transform: scale(1.18) rotate(12deg); } + 100% { transform: scale(1) rotate(0); } +} + +@keyframes petal-fly { + 0% { opacity: 0; transform: translate(0, 0) scale(0.2); } + 20% { opacity: 1; } + 100% { opacity: 0; transform: translate(var(--x), var(--y)) rotate(var(--r)) scale(1); } +} + +@keyframes spark-ring { + 0% { opacity: .95; transform: scale(.35); } + 100% { opacity: 0; transform: scale(4.2); } +} + +@keyframes sparkle-pop { + 0% { opacity: 0; transform: translate(0, 0) scale(.2) rotate(0); } + 35% { opacity: 1; } + 100% { opacity: 0; transform: translate(var(--sx), var(--sy)) scale(1.35) rotate(190deg); } +} + +@keyframes reward-glow { + 0%, 100% { box-shadow: 0 28px 80px rgba(73, 52, 34, 0.3); } + 50% { box-shadow: 0 28px 90px rgba(235, 119, 129, 0.58), 0 0 0 10px rgba(248, 207, 103, 0.18); } +} + +@media (max-width: 760px) { + .page-shell { + width: min(calc(100% - 22px), 680px); + } + + .topbar { + min-height: 58px; + } + + .brand small { + display: none; + } + + .hero { + min-height: 180px; + padding: 21px 20px; + border-radius: 27px; + } + + .today-card { + min-width: 170px; + display: grid; + padding: 10px; + } + + .playlist { + grid-template-columns: 1fr; + gap: 8px; + } + + .playlist-item { + min-height: 92px; + } + + .week-grid { + grid-template-columns: repeat(5, 1fr); + } + + .audio-panel, + .audio-panel > img { + min-height: 330px; + height: 330px; + } +} + +@media (max-width: 520px) { + .brand strong { + font-size: 16px; + } + + .brand-mark { + width: 40px; + height: 40px; + border-radius: 13px 13px 13px 5px; + } + + .identity-chip { + max-width: 150px; + } + + #identity-label { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .hero { + align-items: flex-start; + grid-template-columns: minmax(0, 1fr) 105px; + gap: 14px; + } + + .today-card { + min-width: 105px; + } + + .week-nav { + grid-column: 1 / -1; + grid-row: 2; + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + width: 100%; + margin-top: 4px; + } + + .week-nav .soft-button { + min-width: 0; + padding-inline: 7px; + } + + .achievement-section { + padding: 18px 12px; + border-radius: 23px; + } + + .achievement-copy { + padding-right: 12px; + } + + .progress-calendar { + padding: 8px; + } + + .progress-weekdays, + .progress-grid { + gap: 4px; + } + + .progress-day { + min-height: 61px; + border-radius: 11px; + } + + .progress-day small { + font-size: 8px; + } + + .playlist-control { + padding: 12px 14px; + } + + .playlist-loop-button { + width: 100%; + } + + .player-section { + padding-top: 22px; + } + + .plan-section { + padding-top: 43px; + } + + .section-heading { + align-items: center; + } + + .loop-toggle { + padding: 8px 10px; + font-size: 12px; + } + + .media-card { + border-radius: 23px; + } + + .song-media-card { + border-radius: 23px; + } + + .song-card-heading { + align-items: flex-start; + flex-direction: column; + gap: 10px; + padding: 17px 17px 13px; + } + + .song-card-heading .play-status { + align-self: flex-start; + } + + .audio-toggle { + bottom: 52px; + gap: 5px; + padding: 14px; + } + + .audio-toggle .audio-disc { + width: 68px; + height: 68px; + font-size: 29px; + } + + .audio-toggle small { + display: none; + } + + .audio-timeline { + height: 52px; + grid-template-columns: 42px minmax(0, 1fr) 42px; + gap: 7px; + padding: 0 11px; + font-size: 10px; + } + + .mode-tab { + min-height: 46px; + } + + .now-playing { + align-items: flex-start; + flex-direction: column; + padding: 17px; + } + + .play-status { + white-space: normal; + } + + .playlist-item { + grid-template-columns: 1fr; + } + + .song-card-reward .flower-strip { + width: 88%; + min-width: 0; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 8px; + border: 0; + } + + .song-card-reward .flower-slot { + width: 64px; + height: 64px; + font-size: 35px; + } + + .flower-time-slot { + gap: 6px; + font-size: 10px; + } + + .round-flower-strip { + width: 85%; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 10px; + } + + .round-flower-button { + width: 86px; + height: 86px; + width: min(86px, 100%); + height: auto; + aspect-ratio: 1; + font-size: 48px; + } + + .round-checkin { + padding-inline: 0; + } + + .round-hint { + padding-inline: 14px; + } + + .identity-options { + grid-template-columns: repeat(2, 1fr); + } + + .identity-options.compact { + grid-template-columns: repeat(4, 1fr); + } + + .identity-options.compact .identity-option { + min-height: 67px; + font-size: 12px; + } + + .identity-options.compact .identity-option span { + font-size: 20px; + } + + footer { + align-items: stretch; + flex-direction: column; + } + + .footer-settings-button { + width: 100%; + } +} + +@media (max-width: 375px) { + .page-shell { + width: calc(100% - 16px); + } + + .topbar { + min-height: 54px; + gap: 7px; + } + + .brand { + gap: 7px; + } + + .brand strong { + font-size: 14px; + } + + .brand-mark { + width: 35px; + height: 35px; + font-size: 21px; + } + + .identity-chip { + max-width: 118px; + min-height: 38px; + padding: 7px 9px; + font-size: 13px; + } + + .hero { + grid-template-columns: minmax(0, 1fr) 95px; + gap: 9px; + min-height: 170px; + padding: 18px 13px; + } + + h1 { + font-size: 42px; + } + + h2 { + font-size: 24px; + } + + .week-category { + font-size: 15px; + } + + .today-card { + min-width: 95px; + padding: 7px; + } + + .today-card .identity-chip { + min-height: 34px; + padding: 5px; + font-size: 11px; + } + + .today-metrics { + gap: 3px; + } + + .today-metrics strong { + font-size: 18px; + } + + .today-metrics small { + margin-top: 2px; + font-size: 9px; + } + + .week-nav .soft-button { + min-height: 42px; + font-size: 13px; + } + + .song-card-reward .flower-slot { + width: 58px; + height: 58px; + font-size: 31px; + } + + .modal { + padding: 9px; + } + + .modal > .dialog-body, + .modal > form { + width: 100%; + border-radius: 21px; + } + + .dialog-body, + .modal form { + padding: 20px 17px; + } + + .identity-options { + grid-template-columns: repeat(4, 1fr); + gap: 6px; + } + + .identity-option { + min-height: 61px; + padding: 6px 2px; + border-radius: 13px; + font-size: 11px; + } + + .identity-option span { + font-size: 19px; + } +} + +@media (prefers-reduced-motion: reduce) { + html { + scroll-behavior: auto; + } + + *, + *::before, + *::after { + transition-duration: 0.01ms !important; + animation-duration: 0.01ms !important; + } +} diff --git a/scripts/build_curriculum.py b/scripts/build_curriculum.py new file mode 100644 index 0000000..5483c3c --- /dev/null +++ b/scripts/build_curriculum.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Build curriculum.json from the workbook and unified SSS asset root.""" + +from __future__ import annotations + +import argparse +import json +import re +from pathlib import Path + +from openpyxl import load_workbook + + +SONG_PATTERN = re.compile(r"^(\d+)-(\d+)\s+(.+)$") +REVIEW_PATTERN = re.compile(r"复习(\d+)-(\d+)周") +ASSET_SPECS = { + "video_file": ("视频", ".mp4"), + "audio_file": ("音频", ".mp3"), + "lyrics_file": ("歌词", ".jpg"), +} + + +def files_by_song_id(folder: Path, extension: str) -> dict[str, str]: + result = {} + for path in sorted(folder.glob(f"*{extension}")): + match = re.match(r"^(\d+-\d+)\s+", path.stem) + if match: + result[match.group(1)] = path.name + return result + + +def build_curriculum(workbook_path: Path, asset_root: Path) -> dict: + workbook = load_workbook(workbook_path, data_only=True, read_only=True) + worksheet = workbook["50周打卡"] + assets = { + field: files_by_song_id(asset_root / folder, extension) + for field, (folder, extension) in ASSET_SPECS.items() + } + + weeks: dict[int, dict] = {} + current_week = None + for week_value, category_value, song_value in worksheet.iter_rows( + min_row=3, max_col=3, values_only=True + ): + if isinstance(week_value, int): + current_week = week_value + category = str(category_value or "").strip() + review_match = REVIEW_PATTERN.search(category) + weeks[current_week] = { + "number": current_week, + "kind": "review" if review_match else "lesson", + "category": category, + "songs": [], + } + if review_match: + weeks[current_week]["review_from"] = int(review_match.group(1)) + weeks[current_week]["review_to"] = int(review_match.group(2)) + + if current_week is None or not isinstance(song_value, str): + continue + match = SONG_PATTERN.match(song_value.strip()) + if not match: + continue + song_id = f"{match.group(1)}-{match.group(2)}" + song = { + "id": song_id, + "slot": int(match.group(2)), + "title": match.group(3), + } + for field, mapping in assets.items(): + if song_id not in mapping: + raise RuntimeError(f"Missing {field} for {song_id}") + song[field] = mapping[song_id] + weeks[current_week]["songs"].append(song) + + if sorted(weeks) != list(range(1, 51)): + raise RuntimeError("Workbook must contain weeks 1 through 50") + + songs = [song for week in weeks.values() for song in week["songs"]] + song_ids = {song["id"] for song in songs} + for field, mapping in assets.items(): + unused = sorted(set(mapping) - song_ids) + if unused: + raise RuntimeError(f"Unused {field}: {unused}") + + return { + "meta": { + "title": "SSS 50周学习计划", + "source_workbook": workbook_path.name, + "asset_root_name": asset_root.name, + "song_count": len(songs), + "week_count": 50, + }, + "weeks": [weeks[number] for number in sorted(weeks)], + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("workbook", type=Path) + parser.add_argument("asset_root", type=Path) + parser.add_argument("output", type=Path) + args = parser.parse_args() + result = build_curriculum(args.workbook, args.asset_root) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text( + json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + print( + f"Wrote {result['meta']['week_count']} weeks and " + f"{result['meta']['song_count']} songs to {args.output}" + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/local_server.sh b/scripts/local_server.sh new file mode 100755 index 0000000..57d5a9a --- /dev/null +++ b/scripts/local_server.sh @@ -0,0 +1,37 @@ +#!/bin/zsh + +# Keep the local LAN server in a detached user session. It intentionally runs +# in the logged-in user's context so it can read the authenticated SMB mount at +# /Volumes/study. +set -eu + +session_name='sss50' +project_dir='/Users/optimx/CODE/nas/project_sss' +log_file='/Users/optimx/CODE/nas/project_sss/.local-data/server-tmux.log' +server_command="cd '${project_dir}' && while true; do env ASSET_ROOT='/Volumes/study/Assets/SSS50' DATA_DIR='${project_dir}/.local-data' PORT=8787 PYTHONUNBUFFERED=1 /usr/bin/python3 app.py >> '${log_file}' 2>&1; sleep 2; done" + +case "${1:-start}" in + start) + if tmux has-session -t "${session_name}" 2>/dev/null; then + echo "SSS server is already running in tmux session: ${session_name}" + else + tmux new-session -d -s "${session_name}" "${server_command}" + echo "SSS server started: http://127.0.0.1:8787" + fi + ;; + status) + tmux has-session -t "${session_name}" + curl -fsS http://127.0.0.1:8787/api/health + ;; + logs) + tail -n "${2:-80}" "${log_file}" + ;; + stop) + tmux kill-session -t "${session_name}" + echo "SSS server stopped" + ;; + *) + echo "Usage: $0 {start|status|logs|stop}" >&2 + exit 2 + ;; +esac diff --git a/source/SSS 儿歌 50周打卡表.xlsx b/source/SSS 儿歌 50周打卡表.xlsx new file mode 100644 index 0000000..bd6b4fe Binary files /dev/null and b/source/SSS 儿歌 50周打卡表.xlsx differ diff --git a/tests/test_app.py b/tests/test_app.py new file mode 100644 index 0000000..02f72de --- /dev/null +++ b/tests/test_app.py @@ -0,0 +1,539 @@ +import sqlite3 +import tempfile +import unittest +from contextlib import closing +from datetime import date, datetime, timedelta, timezone +from pathlib import Path + +import app + + +BASE_TIME = datetime(2026, 10, 12, 2, 0, tzinfo=timezone.utc) + + +class SSSAppTests(unittest.TestCase): + def make_database(self, directory: str, at: datetime = BASE_TIME) -> Path: + db_path = Path(directory) / "sss.db" + app.initialize_database(db_path, at) + return db_path + + def bind(self, connection, device="device-test0001", actor="妈妈", at=BASE_TIME): + app.bind_device(connection, device, actor, at) + return device + + def play_and_complete( + self, + connection, + device, + song_id, + at, + study_date="2026-10-12", + media_type="video", + ): + play_id = app.start_playback_event( + connection, device, song_id, study_date, media_type, at + ) + result = app.complete_playback_event( + connection, device, play_id, 90, at + timedelta(minutes=1) + ) + return play_id, result + + def test_curriculum_has_all_three_asset_types(self): + self.assertEqual(app.CURRICULUM["meta"]["week_count"], 50) + self.assertEqual(app.CURRICULUM["meta"]["song_count"], 100) + song = app.CURRICULUM["songs_by_id"]["28-3"] + self.assertEqual(song["video_file"], "28-3 The Shape Song.mp4") + self.assertEqual(song["audio_file"], "28-3 The Shape Song.mp3") + self.assertEqual(song["lyrics_file"], "28-3 The Shape Song.jpg") + + def test_active_asset_root_finds_macos_suffixed_study_mount(self): + with tempfile.TemporaryDirectory() as temp_dir: + volumes_root = Path(temp_dir) / "Volumes" + configured_root = volumes_root / "study" / "Assets" / "SSS50" + fallback_root = volumes_root / "study-1" / "Assets" / "SSS50" + (fallback_root / "视频").mkdir(parents=True) + self.assertEqual( + app.active_asset_root(configured_root, volumes_root), fallback_root + ) + + def test_resource_catalog_lists_every_song_and_three_lazy_assets(self): + with tempfile.TemporaryDirectory() as temp_dir: + payload = app.resources_payload(Path(temp_dir)) + self.assertEqual(payload["summary"]["songs"], 100) + self.assertEqual(len(payload["songs"]), 100) + first = payload["songs"][0] + self.assertEqual(first["id"], "1-1") + self.assertEqual(first["week"], 1) + self.assertEqual(set(first["urls"]), {"video", "audio", "lyrics"}) + self.assertFalse(any(first["available"].values())) + + resource_html = (app.PUBLIC_DIR / "resources.html").read_text(encoding="utf-8") + resource_js = (app.PUBLIC_DIR / "resources.js").read_text(encoding="utf-8") + self.assertNotIn('id="resource-viewer"', resource_html) + self.assertIn('data-resource-detail', resource_js) + self.assertIn('data-resource-video data-video-url=', resource_js) + self.assertIn('data-resource-audio data-audio-url=', resource_js) + self.assertIn('video.src = video.dataset.videoUrl', resource_js) + self.assertIn('audio.src = audio.dataset.audioUrl', resource_js) + self.assertNotIn('mode: "info"', resource_js) + self.assertNotIn('songs[0]?.id', resource_js) + + def test_home_uses_one_lazy_media_card_per_song(self): + home_html = (app.PUBLIC_DIR / "index.html").read_text(encoding="utf-8") + home_js = (app.PUBLIC_DIR / "app.js").read_text(encoding="utf-8") + resource_js = (app.PUBLIC_DIR / "resources.js").read_text(encoding="utf-8") + stats_js = (app.PUBLIC_DIR / "stats.js").read_text(encoding="utf-8") + self.assertIn('id="song-cards"', home_html) + self.assertNotIn('id="current-song-id"', home_html) + self.assertNotIn('id="audio-previous"', home_html) + self.assertNotIn('id="loop-toggle"', home_html) + self.assertIn('data-video-url="${song.video_url}"', home_js) + self.assertIn('data-audio-url="${song.audio_url}"', home_js) + self.assertIn('player.src = player.dataset[urlKey]', home_js) + self.assertIn('const urlKey = mediaType === "audio" ? "audioUrl" : "videoUrl"', home_js) + self.assertNotIn("独立播放", home_html) + self.assertNotIn("一首歌一个窗口", home_html) + self.assertIn('id="round-hint"', home_html) + self.assertIn('"上午领取", "下午领取", "晚上领取"', home_js) + self.assertIn('id="playlist-loop-button"', home_html) + self.assertIn('id="weekly-loop-player"', home_html) + self.assertIn('loop playsinline webkit-playsinline', home_html) + self.assertIn('id="child-mode"', home_html) + self.assertIn("async function startPlaylistAt", home_js) + self.assertIn('playCardMedia(song.id, "audio", "single")', home_js) + self.assertIn('player.src = `/api/week-audio/${weekNumber}`', home_js) + self.assertIn('mode: "weekly-loop"', home_js) + self.assertIn('elements.weeklyLoopPlayer.pause()', home_js) + self.assertIn('function isIPhone5sOnIOS10()', home_js) + self.assertIn('function childSongCardMarkup(song, index)', home_js) + self.assertIn('appState.childMode ? "audio"', home_js) + self.assertIn('course_week: appState.data.week.number', home_js) + self.assertIn('data-week-number=', home_js) + self.assertIn('SSS 50 周打卡', home_html) + self.assertIn('id="identity-button"', home_html) + self.assertIn('id="bottom-settings-button"', home_html) + self.assertIn('id="start-date" name="start_date" type="date" value="2026-10-12" disabled', home_html) + self.assertNotIn('id="settings-button"', home_html) + self.assertNotIn('if (mode !== "video") video.pause()', home_js) + self.assertNotIn('if (mode !== "audio") audio.pause()', home_js) + self.assertNotIn("