From 64e7cc5d8be48c45ef48987d7fc3e0bf74875382 Mon Sep 17 00:00:00 2001 From: TTlaji Date: Mon, 15 Jun 2026 12:52:20 +0800 Subject: [PATCH] feat: sync learning progress to backend --- admin.js | 69 ++++----- app.js | 31 ++++ backend/db.py | 160 ++++++++++++++++++++- backend/main.py | 41 +++++- home.js | 29 ++++ index.html | 1 + progress-sync.js | 167 ++++++++++++++++++++++ study.html | 1 + tests/admin-activation-code-copy.test.mjs | 12 ++ tests/admin-ai-state.test.mjs | 14 +- tests/auth_helpers_test.py | 3 +- tests/auth_routes_test.py | 1 + tests/learning_progress_routes_test.py | 155 ++++++++++++++++++++ tests/progress-sync-helpers.test.mjs | 55 +++++++ 14 files changed, 689 insertions(+), 50 deletions(-) create mode 100644 progress-sync.js create mode 100644 tests/admin-activation-code-copy.test.mjs create mode 100644 tests/learning_progress_routes_test.py create mode 100644 tests/progress-sync-helpers.test.mjs diff --git a/admin.js b/admin.js index 6f4affa..50a3246 100644 --- a/admin.js +++ b/admin.js @@ -1,5 +1,5 @@ const STORAGE_KEY = "speaking-lab-state-v1"; -const ADMIN_CREDENTIALS_KEY = "speaking-lab-admin-credentials-v1"; +const ADMIN_TOKEN_KEY = "speaking-lab-auth-token-v1"; const IS_BROWSER = typeof document !== "undefined"; const els = { @@ -40,7 +40,6 @@ let users = []; let activationCodes = []; let editingVideo = null; let editableSubtitles = createEmptySubtitleEditState(); -let adminCredentials = IS_BROWSER ? getStoredAdminCredentials(window.sessionStorage) : null; if (IS_BROWSER) initializeAdmin(); @@ -60,7 +59,7 @@ async function apiRequest(path, options = {}) { if (IS_BROWSER && window.SpeakingAuth) { return window.SpeakingAuth.apiRequest(path, options); } - const response = await fetch(path, withAdminAuth(options)); + const response = await fetch(path, withAdminToken(options)); if (!response.ok) { let message = "请求失败,请重试。"; try { @@ -118,16 +117,17 @@ async function loginAdmin(event) { const password = els.adminPassword.value; if (!username || !password) return; - adminCredentials = { username, password }; try { - const result = await apiRequest("/api/admin/session"); - setStoredAdminCredentials(window.sessionStorage, username, password); + const result = await window.SpeakingAuth.login(username, password); + if (result?.role !== "admin") { + window.SpeakingAuth.clearSession(); + throw new Error("需要管理员账号。"); + } if (els.adminLoginMessage) els.adminLoginMessage.hidden = true; els.adminLoginForm.reset(); unlockAdmin(result.username || username); } catch (error) { - adminCredentials = null; - clearStoredAdminCredentials(window.sessionStorage); + clearStoredAdminToken(window.sessionStorage); lockAdmin(error.message || "管理员账号或密码错误。"); } } @@ -135,40 +135,31 @@ async function loginAdmin(event) { async function verifyStoredAdminCredentials() { try { const result = await apiRequest("/api/admin/session"); - unlockAdmin(result.username || adminCredentials.username); + unlockAdmin(result.username || ""); } catch { - adminCredentials = null; - clearStoredAdminCredentials(window.sessionStorage); + clearStoredAdminToken(window.sessionStorage); lockAdmin("管理员登录已失效,请重新登录。"); } } -function withAdminAuth(options = {}) { - if (!adminCredentials) return options; +function withAdminToken(options = {}) { + const token = IS_BROWSER ? getStoredAdminToken(window.sessionStorage) : ""; + if (!token) return options; const headers = new Headers(options.headers || {}); - headers.set("Authorization", `Basic ${btoa(`${adminCredentials.username}:${adminCredentials.password}`)}`); + headers.set("Authorization", `Bearer ${token}`); return { ...options, headers }; } -function getStoredAdminCredentials(storage) { - try { - const value = JSON.parse(storage.getItem(ADMIN_CREDENTIALS_KEY) || "null"); - if (!value?.username || !value?.password) return null; - return { - username: String(value.username), - password: String(value.password), - }; - } catch { - return null; - } +function getStoredAdminToken(storage) { + return String(storage.getItem(ADMIN_TOKEN_KEY) || ""); } -function setStoredAdminCredentials(storage, username, password) { - storage.setItem(ADMIN_CREDENTIALS_KEY, JSON.stringify({ username, password })); +function setStoredAdminToken(storage, token) { + storage.setItem(ADMIN_TOKEN_KEY, String(token || "")); } -function clearStoredAdminCredentials(storage) { - storage.removeItem(ADMIN_CREDENTIALS_KEY); +function clearStoredAdminToken(storage) { + storage.removeItem(ADMIN_TOKEN_KEY); } function getFileInputState(file, defaultLabel) { @@ -593,15 +584,23 @@ function renderActivationCodes() { async function copyActivationCode(code, button) { try { await navigator.clipboard.writeText(code); - button.textContent = "已复制"; + button.textContent = getActivationCodeCopiedLabel(); window.setTimeout(() => { button.textContent = "复制"; }, 1200); } catch { - showMessage(`卡密:${code}`, false); + showMessage(getActivationCodeCopyFallbackMessage(code), false); } } +function getActivationCodeCopiedLabel() { + return "已复制"; +} + +function getActivationCodeCopyFallbackMessage(code) { + return `复制失败,请手动复制:${code}`; +} + async function deleteActivationCode(code) { const confirmed = window.confirm(`确定删除卡密 ${code.code} 吗?`); if (!confirmed) return; @@ -738,9 +737,11 @@ if (typeof module !== "undefined" && module.exports) { getLocalWhisperButtonState, shouldConfirmSubtitleOverwrite, pickVideoAfterSave, - getStoredAdminCredentials, - setStoredAdminCredentials, - clearStoredAdminCredentials, + getActivationCodeCopiedLabel, + getActivationCodeCopyFallbackMessage, + getStoredAdminToken, + setStoredAdminToken, + clearStoredAdminToken, }; } diff --git a/app.js b/app.js index 454e909..a28bb2b 100644 --- a/app.js +++ b/app.js @@ -147,8 +147,12 @@ let libraryLoadMessage = ""; let lastProgressSaveAt = 0; let pendingRestoreProgress = null; let currentSessionUser = null; +let progressSyncQueue = null; async function apiRequest(path, options = {}) { + if (IS_BROWSER && window.SpeakingAuth) { + return window.SpeakingAuth.apiRequest(path, options); + } const response = await fetch(path, options); if (!response.ok) { let message = "请求失败,请重试。"; @@ -197,6 +201,11 @@ async function initializeApp() { currentSessionUser = await window.SpeakingAuth.requireSession(); if (!currentSessionUser) return; ensureLocalUserForSession(currentSessionUser); + progressSyncQueue = window.SpeakingProgressSync?.createProgressSyncQueue({ + getUser: getCurrentUser, + apiRequest, + saveState, + }) || null; try { libraryLoadMessage = ""; @@ -211,6 +220,8 @@ async function initializeApp() { libraryLoadMessage = "后端视频库加载失败,当前显示示例素材。"; } + await syncLearningProgressFromBackend(); + const requestedVideoId = getRequestedVideoId(); if (requestedVideoId && getVideo(requestedVideoId)) { activeVideoId = requestedVideoId; @@ -649,6 +660,7 @@ function saveActiveProgress(partial = {}, immediate = false) { lastProgressSaveAt = now; saveState(); renderLibrary(); + scheduleProgressSync(); } } @@ -683,6 +695,7 @@ function toggleLineStatus(index, status, event) { progress.updatedAt = new Date().toISOString(); saveState(); + scheduleProgressSync(); renderTranscript(); renderLibrary(); } @@ -700,10 +713,28 @@ function toggleSaved(field) { user[field] = [...list, activeVideoId]; } saveState(); + scheduleProgressSync(); renderVideoMeta(); renderSavedLists(); } +async function syncLearningProgressFromBackend() { + if (!window.SpeakingProgressSync) return; + try { + await window.SpeakingProgressSync.syncLearningState({ + user: getCurrentUser(), + apiRequest, + saveState, + }); + } catch (error) { + console.warn("Learning progress sync failed", error); + } +} + +function scheduleProgressSync() { + progressSyncQueue?.schedule(); +} + function renderSavedLists() { if (!els.savedLists) return; diff --git a/backend/db.py b/backend/db.py index 492536e..25f4068 100644 --- a/backend/db.py +++ b/backend/db.py @@ -91,6 +91,12 @@ def initialize_database() -> None: connection.execute("ALTER TABLE users ADD COLUMN is_active INTEGER NOT NULL DEFAULT 1") if "last_login_at" not in user_columns: connection.execute("ALTER TABLE users ADD COLUMN last_login_at TEXT") + interaction_columns = { + row["name"] + for row in connection.execute("PRAGMA table_info(user_interactions)").fetchall() + } + if "payload_json" not in interaction_columns: + connection.execute("ALTER TABLE user_interactions ADD COLUMN payload_json TEXT") connection.executescript( """ CREATE TABLE IF NOT EXISTS activation_codes ( @@ -219,6 +225,153 @@ def update_user_active(user_id: int, is_active: bool) -> dict[str, object] | Non return get_user_by_id(user_id) +def normalize_interaction_indexes(value: object) -> list[int]: + if not isinstance(value, list): + return [] + indexes = { + int(item) + for item in value + if isinstance(item, int) or (isinstance(item, str) and item.isdigit()) + } + return sorted(index for index in indexes if index >= 0) + + +def normalize_progress_payload(payload: dict[str, object] | None, current_time_ms: int | None = None) -> dict[str, object]: + payload = payload if isinstance(payload, dict) else {} + current_time = payload.get("currentTime") + if not isinstance(current_time, (int, float)): + current_time = (current_time_ms or 0) / 1000 + active_line_index = payload.get("activeLineIndex") + if not isinstance(active_line_index, int) or active_line_index < 0: + active_line_index = 0 + return { + "currentTime": float(current_time or 0), + "activeLineIndex": active_line_index, + "practicedLineIndexes": normalize_interaction_indexes(payload.get("practicedLineIndexes")), + "difficultLineIndexes": normalize_interaction_indexes(payload.get("difficultLineIndexes")), + "updatedAt": str(payload.get("updatedAt") or ""), + } + + +def get_existing_video_ids(connection: sqlite3.Connection) -> set[int]: + rows = connection.execute("SELECT id FROM videos").fetchall() + return {int(row["id"]) for row in rows} + + +def parse_interaction_video_id(video_id: str | int) -> int | None: + try: + parsed = int(video_id) + except (TypeError, ValueError): + return None + return parsed if parsed > 0 else None + + +def get_user_learning_state(user_id: int) -> dict[str, object]: + with get_connection() as connection: + rows = connection.execute( + """ + SELECT video_id, interaction_type, current_time_ms, payload_json, updated_at + FROM user_interactions + WHERE user_id = ? + AND interaction_type IN ('favorite', 'progress') + ORDER BY video_id ASC + """, + (user_id,), + ).fetchall() + + favorites: list[str] = [] + progress: dict[str, dict[str, object]] = {} + for row in rows: + video_id = str(row["video_id"]) + if row["interaction_type"] == "favorite": + favorites.append(video_id) + continue + + try: + payload = json.loads(row["payload_json"] or "{}") + except json.JSONDecodeError: + payload = {} + normalized = normalize_progress_payload(payload, row["current_time_ms"]) + if not normalized["updatedAt"]: + normalized["updatedAt"] = row["updated_at"] or "" + progress[video_id] = normalized + + return { + "favorites": sorted(set(favorites), key=lambda item: int(item)), + "progress": progress, + } + + +def save_user_learning_state( + user_id: int, + *, + favorites: list[str], + progress: dict[str, dict[str, object]], +) -> dict[str, object]: + with get_connection() as connection: + existing_video_ids = get_existing_video_ids(connection) + favorite_ids = [ + parsed + for item in favorites + if (parsed := parse_interaction_video_id(item)) in existing_video_ids + ] + progress_items = { + parsed: normalize_progress_payload(payload) + for item, payload in progress.items() + if (parsed := parse_interaction_video_id(item)) in existing_video_ids + } + + connection.execute( + """ + DELETE FROM user_interactions + WHERE user_id = ? + AND interaction_type = 'favorite' + """, + (user_id,), + ) + for video_id in sorted(set(favorite_ids)): + connection.execute( + """ + INSERT INTO user_interactions (user_id, video_id, interaction_type) + VALUES (?, ?, 'favorite') + ON CONFLICT(user_id, video_id, interaction_type) DO UPDATE SET + updated_at = CURRENT_TIMESTAMP + """, + (user_id, video_id), + ) + + connection.execute( + """ + DELETE FROM user_interactions + WHERE user_id = ? + AND interaction_type = 'progress' + """, + (user_id,), + ) + for video_id, payload in progress_items.items(): + current_time_ms = int(round(float(payload["currentTime"]) * 1000)) + connection.execute( + """ + INSERT INTO user_interactions ( + user_id, video_id, interaction_type, current_time_ms, payload_json + ) + VALUES (?, ?, 'progress', ?, ?) + ON CONFLICT(user_id, video_id, interaction_type) DO UPDATE SET + current_time_ms = excluded.current_time_ms, + payload_json = excluded.payload_json, + updated_at = CURRENT_TIMESTAMP + """, + ( + user_id, + video_id, + current_time_ms, + json.dumps(payload, ensure_ascii=False), + ), + ) + + return get_user_learning_state(user_id) + + def mark_user_login(user_id: int) -> None: with get_connection() as connection: connection.execute( @@ -264,13 +417,10 @@ def register_user_with_activation(*, username: str, password_hash: str, activati user_id = int(cursor.lastrowid) connection.execute( """ - UPDATE activation_codes - SET status = 'used', - used_by_user_id = ?, - used_at = CURRENT_TIMESTAMP + DELETE FROM activation_codes WHERE id = ? """, - (user_id, code_row["id"]), + (code_row["id"],), ) user = get_user_by_id(user_id) diff --git a/backend/main.py b/backend/main.py index 1aeaced..abf0662 100644 --- a/backend/main.py +++ b/backend/main.py @@ -4,7 +4,7 @@ from urllib.parse import urlparse from uuid import uuid4 from fastapi import Depends, FastAPI, File, Form, HTTPException, UploadFile -from pydantic import BaseModel +from pydantic import BaseModel, Field from fastapi.responses import FileResponse from fastapi.security import HTTPAuthorizationCredentials, HTTPBasic, HTTPBasicCredentials, HTTPBearer from fastapi.staticfiles import StaticFiles @@ -26,6 +26,7 @@ from .db import ( delete_unused_activation_code, get_user_auth_record, get_user_by_id, + get_user_learning_state, initialize_database, list_activation_codes, list_users, @@ -33,6 +34,7 @@ from .db import ( mark_user_login, parse_tags, register_user_with_activation, + save_user_learning_state, table_names, get_video, update_user_active, @@ -174,6 +176,19 @@ class UpdateUserStatusRequest(BaseModel): isActive: bool +class VideoProgressPayload(BaseModel): + currentTime: float = 0 + activeLineIndex: int = 0 + practicedLineIndexes: list[int] = Field(default_factory=list) + difficultLineIndexes: list[int] = Field(default_factory=list) + updatedAt: str = "" + + +class LearningStateRequest(BaseModel): + favorites: list[str] = Field(default_factory=list) + progress: dict[str, VideoProgressPayload] = Field(default_factory=dict) + + @app.on_event("startup") def on_startup() -> None: initialize_database() @@ -321,6 +336,30 @@ def api_auth_session(session: dict[str, object] = Depends(require_session)) -> d return {"ok": True, "user": session} +def require_user_id(session: dict[str, object]) -> int: + user_id = session.get("id") + if not isinstance(user_id, int) or user_id <= 0: + raise HTTPException(status_code=403, detail="闇€瑕佹櫘閫氱敤鎴风櫥褰曘€?") + return user_id + + +@app.get("/api/me/progress") +def api_get_my_progress(session: dict[str, object] = Depends(require_session)) -> dict[str, object]: + return get_user_learning_state(require_user_id(session)) + + +@app.put("/api/me/progress") +def api_save_my_progress( + request: LearningStateRequest, + session: dict[str, object] = Depends(require_session), +) -> dict[str, object]: + return save_user_learning_state( + require_user_id(session), + favorites=request.favorites, + progress={video_id: payload.dict() for video_id, payload in request.progress.items()}, + ) + + def require_admin( credentials: HTTPBasicCredentials | None = Depends(admin_security), bearer: HTTPAuthorizationCredentials | None = Depends(bearer_security), diff --git a/home.js b/home.js index 8d0b61f..58cab3d 100644 --- a/home.js +++ b/home.js @@ -36,6 +36,7 @@ async function initializeHome() { try { videos = await apiRequest("/api/videos"); + await syncLearningProgressFromBackend(); renderHome(); } catch (error) { els.status.textContent = error.message || "素材加载失败。"; @@ -44,6 +45,9 @@ async function initializeHome() { } async function apiRequest(path, options = {}) { + if (window.SpeakingAuth) { + return window.SpeakingAuth.apiRequest(path, options); + } const response = await fetch(path, options); if (!response.ok) { let message = "请求失败,请重试。"; @@ -404,6 +408,7 @@ function toggleFavorite(videoId) { user.favorites = [...favorites]; saveState(); + scheduleProgressSync(); renderHome(); } @@ -504,3 +509,27 @@ function loadState() { function saveState() { localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); } + +async function syncLearningProgressFromBackend() { + if (!window.SpeakingProgressSync) return; + try { + await window.SpeakingProgressSync.syncLearningState({ + user: getCurrentUser(), + apiRequest, + saveState, + }); + } catch (error) { + console.warn("Learning progress sync failed", error); + } +} + +function scheduleProgressSync() { + if (!window.SpeakingProgressSync) return; + const queue = window.SpeakingProgressSync.createProgressSyncQueue({ + getUser: getCurrentUser, + apiRequest, + saveState, + delay: 300, + }); + queue.schedule(); +} diff --git a/index.html b/index.html index 8360456..ba2dd65 100644 --- a/index.html +++ b/index.html @@ -49,6 +49,7 @@ + diff --git a/progress-sync.js b/progress-sync.js new file mode 100644 index 0000000..f011c8c --- /dev/null +++ b/progress-sync.js @@ -0,0 +1,167 @@ +(function () { + const IS_BROWSER = typeof window !== "undefined"; + + function normalizeIndexList(value) { + if (!Array.isArray(value)) return []; + return [...new Set(value.map(Number).filter((index) => Number.isInteger(index) && index >= 0))] + .sort((a, b) => a - b); + } + + function normalizeProgress(progress = {}) { + return { + currentTime: Number(progress.currentTime) || 0, + activeLineIndex: Number.isInteger(progress.activeLineIndex) && progress.activeLineIndex >= 0 + ? progress.activeLineIndex + : 0, + practicedLineIndexes: normalizeIndexList(progress.practicedLineIndexes), + difficultLineIndexes: normalizeIndexList(progress.difficultLineIndexes), + updatedAt: String(progress.updatedAt || ""), + }; + } + + function normalizeRemoteLearningState(payload = {}) { + const progress = {}; + Object.entries(payload.progress || {}).forEach(([videoId, item]) => { + progress[String(videoId)] = normalizeProgress(item); + }); + return { + favorites: normalizeIdList(payload.favorites), + progress, + }; + } + + function normalizeIdList(value) { + if (!Array.isArray(value)) return []; + return [...new Set(value.map((item) => String(item)).filter(Boolean))] + .sort((a, b) => Number(a) - Number(b)); + } + + function mergeProgress(localProgress = {}, remoteProgress = {}) { + const merged = {}; + const videoIds = new Set([ + ...Object.keys(localProgress || {}), + ...Object.keys(remoteProgress || {}), + ]); + + videoIds.forEach((videoId) => { + const local = normalizeProgress(localProgress[videoId]); + const remote = normalizeProgress(remoteProgress[videoId]); + const localTime = Date.parse(local.updatedAt || "") || 0; + const remoteTime = Date.parse(remote.updatedAt || "") || 0; + const newest = remoteTime >= localTime ? remote : local; + merged[String(videoId)] = { + ...newest, + practicedLineIndexes: normalizeIndexList([ + ...local.practicedLineIndexes, + ...remote.practicedLineIndexes, + ]), + difficultLineIndexes: normalizeIndexList([ + ...local.difficultLineIndexes, + ...remote.difficultLineIndexes, + ]), + }; + }); + + return merged; + } + + function mergeLearningState(localUser, remoteState) { + const remote = normalizeRemoteLearningState(remoteState); + return { + favorites: normalizeIdList([...(localUser?.favorites || []), ...remote.favorites]), + progress: mergeProgress(localUser?.progress || {}, remote.progress), + }; + } + + function applyLearningStateToUser(user, learningState) { + if (!user) return null; + const normalized = normalizeRemoteLearningState(learningState); + user.favorites = normalized.favorites; + user.progress = normalized.progress; + return user; + } + + function buildLearningStatePayload(user) { + return { + favorites: normalizeIdList(user?.favorites || []), + progress: normalizeRemoteLearningState({ progress: user?.progress || {} }).progress, + }; + } + + async function fetchRemoteLearningState(apiRequest) { + if (!apiRequest) return { favorites: [], progress: {} }; + return normalizeRemoteLearningState(await apiRequest("/api/me/progress")); + } + + async function saveRemoteLearningState(apiRequest, user) { + if (!apiRequest || !user) return { favorites: [], progress: {} }; + return normalizeRemoteLearningState(await apiRequest("/api/me/progress", { + method: "PUT", + body: JSON.stringify(buildLearningStatePayload(user)), + })); + } + + async function syncLearningState({ user, apiRequest, saveState }) { + if (!user || !apiRequest) return null; + const remote = await fetchRemoteLearningState(apiRequest); + const merged = mergeLearningState(user, remote); + applyLearningStateToUser(user, merged); + saveState?.(); + const saved = await saveRemoteLearningState(apiRequest, user); + applyLearningStateToUser(user, mergeLearningState(user, saved)); + saveState?.(); + return saved; + } + + function createProgressSyncQueue({ getUser, apiRequest, saveState, delay = 800 }) { + let timer = null; + let inFlight = null; + + async function flush() { + if (timer) { + clearTimeout(timer); + timer = null; + } + const user = getUser?.(); + if (!user || !apiRequest) return null; + inFlight = saveRemoteLearningState(apiRequest, user) + .then((saved) => { + applyLearningStateToUser(user, mergeLearningState(user, saved)); + saveState?.(); + return saved; + }) + .catch(() => null) + .finally(() => { + inFlight = null; + }); + return inFlight; + } + + function schedule() { + if (timer) clearTimeout(timer); + timer = setTimeout(flush, delay); + } + + return { schedule, flush, get inFlight() { return inFlight; } }; + } + + const api = { + applyLearningStateToUser, + buildLearningStatePayload, + createProgressSyncQueue, + fetchRemoteLearningState, + mergeLearningState, + normalizeProgress, + normalizeRemoteLearningState, + saveRemoteLearningState, + syncLearningState, + }; + + if (IS_BROWSER) { + window.SpeakingProgressSync = api; + } + + if (typeof module !== "undefined" && module.exports) { + module.exports = api; + } +})(); diff --git a/study.html b/study.html index c42c7a7..aa3852d 100644 --- a/study.html +++ b/study.html @@ -97,6 +97,7 @@ + diff --git a/tests/admin-activation-code-copy.test.mjs b/tests/admin-activation-code-copy.test.mjs new file mode 100644 index 0000000..6ed4e0c --- /dev/null +++ b/tests/admin-activation-code-copy.test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert/strict"; +import adminHelpers from "../admin.js"; + +assert.equal( + adminHelpers.getActivationCodeCopyFallbackMessage("SL-ABC123"), + "复制失败,请手动复制:SL-ABC123", +); + +assert.equal( + adminHelpers.getActivationCodeCopiedLabel(), + "已复制", +); diff --git a/tests/admin-ai-state.test.mjs b/tests/admin-ai-state.test.mjs index dd2a2bb..b859c9b 100644 --- a/tests/admin-ai-state.test.mjs +++ b/tests/admin-ai-state.test.mjs @@ -4,9 +4,9 @@ import adminHelpers from "../admin.js"; const { getAiSubtitleButtonState, getLocalWhisperButtonState, - getStoredAdminCredentials, + getStoredAdminToken, pickVideoAfterSave, - setStoredAdminCredentials, + setStoredAdminToken, shouldConfirmSubtitleOverwrite, } = adminHelpers; @@ -57,9 +57,7 @@ const fakeSessionStorage = { removeItem: (key) => memoryStorage.delete(key), }; -assert.equal(getStoredAdminCredentials(fakeSessionStorage), null); -setStoredAdminCredentials(fakeSessionStorage, "owner", "secret"); -assert.deepEqual(getStoredAdminCredentials(fakeSessionStorage), { - username: "owner", - password: "secret", -}); +assert.equal(getStoredAdminToken(fakeSessionStorage), ""); +setStoredAdminToken(fakeSessionStorage, "admin-token-value"); +assert.equal(getStoredAdminToken(fakeSessionStorage), "admin-token-value"); +assert.equal([...memoryStorage.values()].some((value) => String(value).includes("secret")), false); diff --git a/tests/auth_helpers_test.py b/tests/auth_helpers_test.py index 84577eb..cde6872 100644 --- a/tests/auth_helpers_test.py +++ b/tests/auth_helpers_test.py @@ -52,8 +52,7 @@ def test_activation_code_registers_user_once(): assert user["username"] == "student" codes = db.list_activation_codes() - assert codes[0]["status"] == "used" - assert codes[0]["usedByUsername"] == "student" + assert codes == [] try: db.register_user_with_activation( diff --git a/tests/auth_routes_test.py b/tests/auth_routes_test.py index 1fd374b..658ce0b 100644 --- a/tests/auth_routes_test.py +++ b/tests/auth_routes_test.py @@ -85,6 +85,7 @@ def test_activation_registration_login_and_reuse_rejection(monkeypatch): )) assert registered["user"]["username"] == "student" assert registered["user"]["role"] == "user" + assert main.api_admin_activation_codes(admin=admin) == [] login = main.api_auth_login(main.LoginRequest(username="student", password="secret123")) session = main.api_auth_session(main.require_session( diff --git a/tests/learning_progress_routes_test.py b/tests/learning_progress_routes_test.py new file mode 100644 index 0000000..b884f4c --- /dev/null +++ b/tests/learning_progress_routes_test.py @@ -0,0 +1,155 @@ +import sys +import tempfile +from pathlib import Path + +from fastapi.security import HTTPAuthorizationCredentials + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +from backend import db, main +from backend.auth import hash_password + + +class EnvPatch: + def __init__(self): + self.attributes = [] + + def setattr(self, target, name, value): + self.attributes.append((target, name, getattr(target, name))) + setattr(target, name, value) + + def restore(self): + while self.attributes: + target, name, original = self.attributes.pop() + setattr(target, name, original) + + +class TempDatabase: + def __enter__(self): + self.temp_dir = tempfile.TemporaryDirectory(ignore_cleanup_errors=True) + self.original = db.DATABASE_PATH + db.DATABASE_PATH = Path(self.temp_dir.name) / "test.sqlite" + db.initialize_database() + return db.DATABASE_PATH + + def __exit__(self, exc_type, exc, tb): + db.DATABASE_PATH = self.original + self.temp_dir.cleanup() + + +def configure_auth(monkeypatch): + monkeypatch.setattr(main, "get_config_value", lambda key, default="": { + "ADMIN_USERNAME": "admin", + "ADMIN_PASSWORD": "admin123", + "AUTH_SECRET": "test-secret", + }.get(key, default)) + + +def create_student_session(): + user = db.register_user_with_activation( + username="student", + password_hash=hash_password("secret123"), + activation_code="SL-ABC123-DEF456-GHI789", + ) + login = main.api_auth_login(main.LoginRequest(username="student", password="secret123")) + return main.require_session( + HTTPAuthorizationCredentials(scheme="Bearer", credentials=login["token"]) + ), user + + +def create_video_record(): + return db.create_video( + title="Lesson One", + speaker="Teacher", + description="", + tags=["口语"], + video_url="https://example.com/lesson-one.mp4", + subtitles=[], + ) + + +def test_learning_progress_round_trips_for_logged_in_user(monkeypatch): + configure_auth(monkeypatch) + + with TempDatabase(): + db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin") + session, _user = create_student_session() + video = create_video_record() + + saved = main.api_save_my_progress( + main.LearningStateRequest( + favorites=[str(video["id"])], + progress={ + str(video["id"]): main.VideoProgressPayload( + currentTime=42.6, + activeLineIndex=3, + practicedLineIndexes=[0, 2, 2], + difficultLineIndexes=[1], + updatedAt="2026-06-14T10:00:00.000Z", + ) + }, + ), + session=session, + ) + loaded = main.api_get_my_progress(session=session) + + assert saved == loaded + assert loaded["favorites"] == [str(video["id"])] + progress = loaded["progress"][str(video["id"])] + assert progress["currentTime"] == 42.6 + assert progress["activeLineIndex"] == 3 + assert progress["practicedLineIndexes"] == [0, 2] + assert progress["difficultLineIndexes"] == [1] + + +def test_learning_progress_save_replaces_removed_favorite_and_merges_progress(monkeypatch): + configure_auth(monkeypatch) + + with TempDatabase(): + db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin") + session, _user = create_student_session() + video = create_video_record() + + main.api_save_my_progress( + main.LearningStateRequest( + favorites=[str(video["id"])], + progress={ + str(video["id"]): main.VideoProgressPayload( + currentTime=10, + practicedLineIndexes=[0], + difficultLineIndexes=[2], + ) + }, + ), + session=session, + ) + loaded = main.api_save_my_progress( + main.LearningStateRequest( + favorites=[], + progress={ + str(video["id"]): main.VideoProgressPayload( + currentTime=12, + practicedLineIndexes=[0, 1], + difficultLineIndexes=[], + ) + }, + ), + session=session, + ) + + assert loaded["favorites"] == [] + assert loaded["progress"][str(video["id"])]["currentTime"] == 12 + assert loaded["progress"][str(video["id"])]["practicedLineIndexes"] == [0, 1] + assert loaded["progress"][str(video["id"])]["difficultLineIndexes"] == [] + + +if __name__ == "__main__": + patch = EnvPatch() + try: + configure_auth(patch) + test_learning_progress_round_trips_for_logged_in_user(patch) + patch.restore() + configure_auth(patch) + test_learning_progress_save_replaces_removed_favorite_and_merges_progress(patch) + finally: + patch.restore() diff --git a/tests/progress-sync-helpers.test.mjs b/tests/progress-sync-helpers.test.mjs new file mode 100644 index 0000000..95bddc2 --- /dev/null +++ b/tests/progress-sync-helpers.test.mjs @@ -0,0 +1,55 @@ +import assert from "node:assert/strict"; +import progressSync from "../progress-sync.js"; + +const { + buildLearningStatePayload, + mergeLearningState, + normalizeRemoteLearningState, +} = progressSync; + +const localUser = { + favorites: ["1"], + progress: { + "1": { + currentTime: 10, + activeLineIndex: 1, + practicedLineIndexes: [0], + difficultLineIndexes: [2], + updatedAt: "2026-06-14T08:00:00.000Z", + }, + }, +}; + +const remote = normalizeRemoteLearningState({ + favorites: ["2"], + progress: { + "1": { + currentTime: 12, + activeLineIndex: 2, + practicedLineIndexes: [1], + difficultLineIndexes: [3], + updatedAt: "2026-06-14T09:00:00.000Z", + }, + "2": { + currentTime: 4, + activeLineIndex: 0, + practicedLineIndexes: [], + difficultLineIndexes: [0], + }, + }, +}); + +assert.deepEqual(remote.favorites, ["2"]); +assert.deepEqual(remote.progress["1"].practicedLineIndexes, [1]); + +const merged = mergeLearningState(localUser, remote); +assert.deepEqual(merged.favorites, ["1", "2"]); +assert.equal(merged.progress["1"].currentTime, 12); +assert.equal(merged.progress["1"].activeLineIndex, 2); +assert.deepEqual(merged.progress["1"].practicedLineIndexes, [0, 1]); +assert.deepEqual(merged.progress["1"].difficultLineIndexes, [2, 3]); +assert.deepEqual(merged.progress["2"].difficultLineIndexes, [0]); + +const payload = buildLearningStatePayload(merged); +assert.deepEqual(payload.favorites, ["1", "2"]); +assert.deepEqual(payload.progress["1"].practicedLineIndexes, [0, 1]);