This commit is contained in:
1 parent
67dcea21d0
commit
64e7cc5d8b
14 files changed
+689
-50
No files matched your search
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
+155
-5
@@ -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)
|
||||
|
||||
+40
-1
@@ -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),
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -49,6 +49,7 @@
|
||||
</main>
|
||||
|
||||
<script src="./auth.js?v=20260605-auth"></script>
|
||||
<script src="./progress-sync.js?v=20260615-progress-sync"></script>
|
||||
<script src="./home.js?v=20260609-home-mobile"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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;
|
||||
}
|
||||
})();
|
||||
@@ -97,6 +97,7 @@
|
||||
</main>
|
||||
|
||||
<script src="./auth.js?v=20260605-auth"></script>
|
||||
<script src="./progress-sync.js?v=20260615-progress-sync"></script>
|
||||
<script src="./app.js?v=20260605-auth"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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(),
|
||||
"已复制",
|
||||
);
|
||||
@@ -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);
|
||||
@@ -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(
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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()
|
||||
@@ -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]);
|
||||
Reference in new issue
Block a user