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 @@
+