Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4c4d6eb4b | ||
|
|
bef5e764a0 | ||
|
|
0c12ce5f33 | ||
|
|
0cf6f62e23 | ||
|
|
64e7cc5d8b | ||
|
|
67dcea21d0 | ||
|
|
cd29764963 | ||
|
|
a38fc638ee | ||
|
|
15ac501843 | ||
|
|
51c8c82e1d | ||
|
|
22831540ef | ||
|
|
468415066e | ||
|
|
b024743cd8 | ||
|
|
c18a5d4c2d |
No files matched your search
+1
-1
@@ -4,7 +4,7 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Speaking Lab 后台管理</title>
|
||||
<link rel="stylesheet" href="./styles.css?v=20260605-auth">
|
||||
<link rel="stylesheet" href="./styles.css?v=20260609-typography">
|
||||
</head>
|
||||
<body class="admin-page">
|
||||
<header class="topbar admin-topbar">
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -32,6 +32,15 @@
|
||||
return `./login.html?next=${encodeURIComponent(current)}`;
|
||||
}
|
||||
|
||||
function isUnauthorizedStatus(status) {
|
||||
return Number(status) === 401;
|
||||
}
|
||||
|
||||
function redirectToLogin() {
|
||||
clearSession();
|
||||
window.location.href = getLoginUrl();
|
||||
}
|
||||
|
||||
async function apiRequest(path, options = {}) {
|
||||
const headers = new Headers(options.headers || {});
|
||||
if (options.body && !(options.body instanceof FormData) && !headers.has("Content-Type")) {
|
||||
@@ -49,6 +58,9 @@
|
||||
} catch {
|
||||
message = response.statusText || message;
|
||||
}
|
||||
if (isUnauthorizedStatus(response.status)) {
|
||||
redirectToLogin();
|
||||
}
|
||||
throw new Error(message);
|
||||
}
|
||||
return response.json();
|
||||
@@ -106,6 +118,7 @@
|
||||
getLoginUrl,
|
||||
getStoredUser,
|
||||
getToken,
|
||||
isUnauthorizedStatus,
|
||||
login,
|
||||
logout,
|
||||
register,
|
||||
@@ -119,6 +132,7 @@
|
||||
getLoginUrlForPath(path) {
|
||||
return `./login.html?next=${encodeURIComponent(path)}`;
|
||||
},
|
||||
isUnauthorizedStatus,
|
||||
shouldShowAdminEntry(user) {
|
||||
return user?.role === "admin";
|
||||
},
|
||||
|
||||
+179
-5
@@ -91,6 +91,14 @@ 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")
|
||||
if "session_token" not in user_columns:
|
||||
connection.execute("ALTER TABLE users ADD COLUMN session_token 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 (
|
||||
@@ -108,6 +116,12 @@ def initialize_database() -> None:
|
||||
ON activation_codes (status);
|
||||
"""
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
DELETE FROM activation_codes
|
||||
WHERE status != 'unused'
|
||||
"""
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
DELETE FROM subtitles
|
||||
@@ -136,6 +150,7 @@ def row_to_user(row: sqlite3.Row) -> dict[str, object]:
|
||||
"createdAt": row["created_at"],
|
||||
"updatedAt": row["updated_at"],
|
||||
"lastLoginAt": row["last_login_at"] or "",
|
||||
"sessionToken": row["session_token"] or "",
|
||||
}
|
||||
|
||||
|
||||
@@ -219,6 +234,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(
|
||||
@@ -232,6 +394,20 @@ def mark_user_login(user_id: int) -> None:
|
||||
)
|
||||
|
||||
|
||||
def rotate_user_session_token(user_id: int, session_token: str) -> None:
|
||||
with get_connection() as connection:
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE users
|
||||
SET session_token = ?,
|
||||
last_login_at = CURRENT_TIMESTAMP,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
""",
|
||||
(session_token, user_id),
|
||||
)
|
||||
|
||||
|
||||
def register_user_with_activation(*, username: str, password_hash: str, activation_code: str) -> dict[str, object]:
|
||||
clean_username = repair_mojibake_text(username)
|
||||
clean_code = activation_code.strip().upper()
|
||||
@@ -264,13 +440,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)
|
||||
@@ -314,6 +487,7 @@ def list_activation_codes() -> list[dict[str, object]]:
|
||||
SELECT activation_codes.*, users.email AS used_by_username
|
||||
FROM activation_codes
|
||||
LEFT JOIN users ON users.id = activation_codes.used_by_user_id
|
||||
WHERE activation_codes.status = 'unused'
|
||||
ORDER BY activation_codes.created_at DESC, activation_codes.id DESC
|
||||
"""
|
||||
).fetchall()
|
||||
|
||||
+49
-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,8 @@ from .db import (
|
||||
mark_user_login,
|
||||
parse_tags,
|
||||
register_user_with_activation,
|
||||
rotate_user_session_token,
|
||||
save_user_learning_state,
|
||||
table_names,
|
||||
get_video,
|
||||
update_user_active,
|
||||
@@ -174,6 +177,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()
|
||||
@@ -222,11 +238,15 @@ def build_user_response(username: str, role: str, user_id: int | None = None) ->
|
||||
|
||||
|
||||
def create_session_payload(username: str, role: str, user_id: int | None = None) -> dict[str, object]:
|
||||
session_token = secrets.token_urlsafe(32) if user_id else ""
|
||||
if user_id:
|
||||
rotate_user_session_token(user_id, session_token)
|
||||
token = create_auth_token(
|
||||
{
|
||||
"username": username,
|
||||
"role": role,
|
||||
"userId": user_id,
|
||||
"sessionToken": session_token,
|
||||
},
|
||||
get_token_secret(),
|
||||
)
|
||||
@@ -247,11 +267,15 @@ def validate_bearer_session(token: str) -> dict[str, object] | None:
|
||||
return build_user_response(username, "admin", None)
|
||||
|
||||
user_id = int(payload.get("userId") or 0)
|
||||
session_token = str(payload.get("sessionToken") or "")
|
||||
user = get_user_by_id(user_id) if user_id else None
|
||||
if not user or not user["isActive"]:
|
||||
return None
|
||||
if user["username"] != username:
|
||||
return None
|
||||
current_session_token = str(user.get("sessionToken") or "")
|
||||
if current_session_token and current_session_token != session_token:
|
||||
return None
|
||||
return build_user_response(str(user["username"]), str(user["role"]), int(user["id"]))
|
||||
|
||||
|
||||
@@ -321,6 +345,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),
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
# Speaking Lab Button Chip Style Refresh Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Refresh Speaking Lab buttons and chips into a TEco-inspired flat, refined style using CSS only.
|
||||
|
||||
**Architecture:** Keep all HTML, class names, IDs, and JavaScript behavior unchanged. Update `styles.css` by introducing shared button tokens in `:root`, then overriding existing button, chip, secondary, danger, and primary action selectors with consistent states. Verify through syntax checks and browser inspection on home, study, admin, and login pages.
|
||||
|
||||
**Tech Stack:** Plain HTML/CSS/JavaScript, existing FastAPI static server, in-app browser verification.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Button Token Foundation
|
||||
|
||||
**Files:**
|
||||
- Modify: `styles.css`
|
||||
|
||||
- [ ] **Step 1: Add shared button tokens to `:root`**
|
||||
|
||||
Insert these variables inside the existing `:root` block after `--danger`:
|
||||
|
||||
```css
|
||||
--control-surface: #f1eee7;
|
||||
--control-surface-hover: #e8e1d6;
|
||||
--control-surface-active: #ddd4c7;
|
||||
--control-border: rgba(67, 56, 45, 0.10);
|
||||
--control-ink: #33413c;
|
||||
--control-muted: #746b60;
|
||||
--primary-solid: #2f4b45;
|
||||
--primary-solid-hover: #263f3a;
|
||||
--primary-solid-active: #203631;
|
||||
--primary-soft-shadow: 0 10px 22px rgba(47, 75, 69, 0.16);
|
||||
--danger-soft: #fdecec;
|
||||
--danger-soft-hover: #f9dddd;
|
||||
--danger-ink: #9f2f35;
|
||||
--focus-ring: 0 0 0 3px rgba(47, 125, 99, 0.18);
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run a quick CSS selector scan**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
rg -n "--control-surface|--primary-solid|--danger-soft|--focus-ring" styles.css
|
||||
```
|
||||
|
||||
Expected: each token appears in `:root`.
|
||||
|
||||
- [ ] **Step 3: Commit token foundation**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
git add styles.css
|
||||
git commit -m "style: add button style tokens"
|
||||
```
|
||||
|
||||
### Task 2: Chips and Secondary Actions
|
||||
|
||||
**Files:**
|
||||
- Modify: `styles.css`
|
||||
|
||||
- [ ] **Step 1: Replace the existing `.chip` block**
|
||||
|
||||
Replace the current `.chip`, `.chip:hover`, and `.chip.active` rules with:
|
||||
|
||||
```css
|
||||
.chip {
|
||||
min-height: 32px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 999px;
|
||||
padding: 0 15px;
|
||||
color: var(--control-ink);
|
||||
background: var(--control-surface);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.54);
|
||||
font-size: 12px;
|
||||
font-weight: 750;
|
||||
white-space: nowrap;
|
||||
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.chip:hover {
|
||||
border-color: var(--control-border);
|
||||
background: var(--control-surface-hover);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.58), 0 8px 18px rgba(47, 64, 57, 0.09);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.chip.active {
|
||||
color: #fffdf8;
|
||||
border-color: var(--primary-solid);
|
||||
background: var(--primary-solid);
|
||||
box-shadow: var(--primary-soft-shadow);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Replace `.primary-link, .secondary-action` and `.secondary-action:hover` area**
|
||||
|
||||
Update the existing `.primary-link, .secondary-action`, `.primary-link`, `.primary-link:hover`, and `.secondary-action:hover` rules near the admin styles so secondary actions use:
|
||||
|
||||
```css
|
||||
.secondary-action {
|
||||
min-height: 34px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 10px;
|
||||
padding: 0 12px;
|
||||
color: var(--control-muted);
|
||||
background: rgba(241, 238, 231, 0.88);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.52);
|
||||
font-size: 13px;
|
||||
font-weight: 750;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.secondary-action:hover {
|
||||
color: var(--control-ink);
|
||||
border-color: var(--control-border);
|
||||
background: var(--control-surface-hover);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.58), 0 8px 18px rgba(47, 64, 57, 0.08);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.secondary-action:active {
|
||||
background: var(--control-surface-active);
|
||||
box-shadow: inset 0 1px 2px rgba(47, 64, 57, 0.12);
|
||||
transform: translateY(0);
|
||||
}
|
||||
```
|
||||
|
||||
Keep any more specific layout rules, such as `.admin-video-actions .secondary-action` widths, after this block.
|
||||
|
||||
- [ ] **Step 3: Add focus-visible support**
|
||||
|
||||
Near the button state rules, add:
|
||||
|
||||
```css
|
||||
.chip:focus-visible,
|
||||
.secondary-action:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: var(--focus-ring);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify selectors**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
rg -n "\\.chip|\\.secondary-action|focus-visible" styles.css
|
||||
```
|
||||
|
||||
Expected: the new chip and secondary-action rules are present once as the main definitions, with responsive/layout overrides preserved.
|
||||
|
||||
- [ ] **Step 5: Commit chips and secondary actions**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
git add styles.css
|
||||
git commit -m "style: refresh chips and secondary buttons"
|
||||
```
|
||||
|
||||
### Task 3: Danger and Primary Actions
|
||||
|
||||
**Files:**
|
||||
- Modify: `styles.css`
|
||||
|
||||
- [ ] **Step 1: Replace `.danger-action` rules**
|
||||
|
||||
Replace `.danger-action` and `.danger-action:hover` with:
|
||||
|
||||
```css
|
||||
.danger-action {
|
||||
min-height: 34px;
|
||||
border: 1px solid rgba(159, 47, 53, 0.10);
|
||||
border-radius: 10px;
|
||||
padding: 0 12px;
|
||||
color: var(--danger-ink);
|
||||
background: var(--danger-soft);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.55);
|
||||
font-size: 13px;
|
||||
font-weight: 800;
|
||||
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.danger-action:hover {
|
||||
border-color: rgba(159, 47, 53, 0.16);
|
||||
color: #84262c;
|
||||
background: var(--danger-soft-hover);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.58), 0 8px 18px rgba(159, 47, 53, 0.08);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.danger-action:active {
|
||||
background: #f4cccc;
|
||||
box-shadow: inset 0 1px 2px rgba(159, 47, 53, 0.14);
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.danger-action:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px rgba(159, 47, 53, 0.14);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Consolidate primary action selectors**
|
||||
|
||||
Add this block after the global button disabled rules and before inputs:
|
||||
|
||||
```css
|
||||
.primary-link,
|
||||
#adminSubmitBtn,
|
||||
.auth-form button[type="submit"],
|
||||
.login-form button,
|
||||
.admin-form button[type="submit"],
|
||||
.activation-code-form button[type="submit"],
|
||||
.practice-answer-row button {
|
||||
border-color: var(--primary-solid);
|
||||
color: #fffdf8;
|
||||
background: var(--primary-solid);
|
||||
box-shadow: var(--primary-soft-shadow);
|
||||
font-weight: 800;
|
||||
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.primary-link:hover,
|
||||
#adminSubmitBtn:hover,
|
||||
.auth-form button[type="submit"]:hover,
|
||||
.login-form button:hover,
|
||||
.admin-form button[type="submit"]:hover,
|
||||
.activation-code-form button[type="submit"]:hover,
|
||||
.practice-answer-row button:hover {
|
||||
border-color: var(--primary-solid-hover);
|
||||
color: #fffdf8;
|
||||
background: var(--primary-solid-hover);
|
||||
box-shadow: 0 12px 26px rgba(47, 75, 69, 0.20);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.primary-link:active,
|
||||
#adminSubmitBtn:active,
|
||||
.auth-form button[type="submit"]:active,
|
||||
.login-form button:active,
|
||||
.admin-form button[type="submit"]:active,
|
||||
.activation-code-form button[type="submit"]:active,
|
||||
.practice-answer-row button:active {
|
||||
border-color: var(--primary-solid-active);
|
||||
background: var(--primary-solid-active);
|
||||
box-shadow: 0 6px 14px rgba(47, 75, 69, 0.14);
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.primary-link:focus-visible,
|
||||
#adminSubmitBtn:focus-visible,
|
||||
.auth-form button[type="submit"]:focus-visible,
|
||||
.login-form button:focus-visible,
|
||||
.admin-form button[type="submit"]:focus-visible,
|
||||
.activation-code-form button[type="submit"]:focus-visible,
|
||||
.practice-answer-row button:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: var(--primary-soft-shadow), var(--focus-ring);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Keep disabled state readable**
|
||||
|
||||
After the primary block, add:
|
||||
|
||||
```css
|
||||
.primary-link:disabled,
|
||||
#adminSubmitBtn:disabled,
|
||||
.auth-form button[type="submit"]:disabled,
|
||||
.login-form button:disabled,
|
||||
.admin-form button[type="submit"]:disabled,
|
||||
.activation-code-form button[type="submit"]:disabled,
|
||||
.practice-answer-row button:disabled {
|
||||
border-color: #d8d2c8;
|
||||
color: #9b9388;
|
||||
background: #e8e2d8;
|
||||
box-shadow: none;
|
||||
transform: none;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Remove or neutralize conflicting older primary blocks**
|
||||
|
||||
Ensure these older rules do not override the new primary system with old teal/navy colors:
|
||||
|
||||
```css
|
||||
.login-form button,
|
||||
.admin-form button[type="submit"] {
|
||||
color: #fff;
|
||||
background: var(--brand);
|
||||
border-color: var(--brand);
|
||||
}
|
||||
```
|
||||
|
||||
and:
|
||||
|
||||
```css
|
||||
.practice-answer-row button {
|
||||
color: #ffffff;
|
||||
border-color: var(--brand);
|
||||
background: var(--brand);
|
||||
font-weight: 800;
|
||||
}
|
||||
```
|
||||
|
||||
Either remove those declarations or update them to match the new variables.
|
||||
|
||||
- [ ] **Step 5: Verify selector conflicts**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
rg -n "var\\(--brand\\)|var\\(--accent\\)|#111827|#0f172a|\\.danger-action|\\.primary-link|#adminSubmitBtn|practice-answer-row button" styles.css
|
||||
```
|
||||
|
||||
Expected: old brand/accent rules may remain for non-button surfaces, but primary/danger action definitions should use the new variables.
|
||||
|
||||
- [ ] **Step 6: Commit danger and primary actions**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
git add styles.css
|
||||
git commit -m "style: refresh primary and danger buttons"
|
||||
```
|
||||
|
||||
### Task 4: Browser Verification and Final Polish
|
||||
|
||||
**Files:**
|
||||
- Modify if needed: `styles.css`
|
||||
|
||||
- [ ] **Step 1: Run static checks**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check app.js
|
||||
node --check home.js
|
||||
node --check admin.js
|
||||
node --check login.js
|
||||
```
|
||||
|
||||
Expected: all commands exit with code 0.
|
||||
|
||||
- [ ] **Step 2: Start the local server**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -m uvicorn backend.main:app --host 127.0.0.1 --port 8000
|
||||
```
|
||||
|
||||
Expected: server starts and serves the app at `http://127.0.0.1:8000`.
|
||||
|
||||
- [ ] **Step 3: Inspect desktop views**
|
||||
|
||||
Open these pages in the browser:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:8000/index.html
|
||||
http://127.0.0.1:8000/study.html
|
||||
http://127.0.0.1:8000/admin.html
|
||||
http://127.0.0.1:8000/login.html
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
- chips are compact capsules;
|
||||
- secondary buttons are quiet and refined;
|
||||
- danger buttons are soft rose, not bright red;
|
||||
- primary buttons use deep green solid styling;
|
||||
- no button text overflows or overlaps.
|
||||
|
||||
- [ ] **Step 4: Inspect mobile-width views**
|
||||
|
||||
Use a viewport around `390x844` and revisit home, study, admin, and login.
|
||||
|
||||
Expected: wrapping still works, buttons remain tappable, and no text escapes the control bounds.
|
||||
|
||||
- [ ] **Step 5: Apply final CSS polish if needed**
|
||||
|
||||
If browser inspection reveals a problem, make only targeted CSS edits. Example fixes:
|
||||
|
||||
```css
|
||||
.admin-video-actions .secondary-action,
|
||||
.danger-action {
|
||||
min-width: 70px;
|
||||
}
|
||||
|
||||
.chip {
|
||||
line-height: 1;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Run final checks**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check app.js
|
||||
node --check home.js
|
||||
node --check admin.js
|
||||
node --check login.js
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Expected: all checks pass, and `git diff --check` reports no whitespace errors.
|
||||
|
||||
- [ ] **Step 7: Commit final polish**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
git add styles.css
|
||||
git commit -m "style: polish button responsive states"
|
||||
```
|
||||
|
||||
If no final polish was needed after Task 3, skip this commit.
|
||||
@@ -0,0 +1,117 @@
|
||||
# Speaking Lab Button and Chip Style Refresh Design
|
||||
|
||||
## Goal
|
||||
|
||||
Refresh all Speaking Lab buttons and chips into a flatter, more refined style inspired by the saved TEco Lab reference page while preserving the current HTML structure and class names.
|
||||
|
||||
This is a CSS-only visual refactor unless implementation discovers a narrow accessibility issue that cannot be solved with CSS. Existing behavior, event wiring, IDs, and class names must remain unchanged.
|
||||
|
||||
## Reference Interpretation
|
||||
|
||||
The TEco Lab reference uses compact controls with:
|
||||
|
||||
- rounded-full chips and rounded-lg buttons;
|
||||
- small, dense typography around 12px to 14px;
|
||||
- low-contrast neutral backgrounds for inactive controls;
|
||||
- solid dark/highlight backgrounds only for active or primary controls;
|
||||
- minimal borders, soft inset or low shadow texture, and smooth hover/active feedback.
|
||||
|
||||
Speaking Lab should adapt those ideas to its Study Notebook direction: warm paper surfaces, deep green primary actions, subdued neutrals, and soft warning colors.
|
||||
|
||||
## Scope
|
||||
|
||||
Update `styles.css` for these existing selectors and related states:
|
||||
|
||||
- `.chip` and `.chip.active`;
|
||||
- `.secondary-action`;
|
||||
- `.danger-action`;
|
||||
- `.primary-link`;
|
||||
- `#adminSubmitBtn`;
|
||||
- primary form buttons such as `.auth-form button[type="submit"]`, `.admin-form button[type="submit"]`, `.activation-code-form button[type="submit"]`, and `.practice-answer-row button`;
|
||||
- relevant disabled, hover, active, and focus-visible states.
|
||||
|
||||
Do not rename selectors, add new required HTML, or change JavaScript behavior.
|
||||
|
||||
## Visual Rules
|
||||
|
||||
### Chips
|
||||
|
||||
`.chip` should become a compact capsule:
|
||||
|
||||
- pill radius;
|
||||
- 12px font size;
|
||||
- medium-bold weight;
|
||||
- horizontal padding that supports short Chinese labels without crowding;
|
||||
- inactive background in warm light neutral;
|
||||
- no hard border in the default state;
|
||||
- hover background slightly darker with subtle elevation;
|
||||
- `.active` background deep green or dark ink, white text, and a low shadow.
|
||||
|
||||
### Secondary Actions
|
||||
|
||||
`.secondary-action` should be quiet and tactile:
|
||||
|
||||
- no heavy border;
|
||||
- light warm neutral or translucent white background;
|
||||
- muted text color;
|
||||
- rounded-lg or small pill shape depending on existing dimensions;
|
||||
- hover smoothly darkens the surface and text;
|
||||
- active state gently presses down;
|
||||
- disabled state is visibly inactive without looking broken.
|
||||
|
||||
This should cover admin entry, logout, cancel edit, refresh, edit, copy, and other secondary operations that use this class or existing secondary-action variants.
|
||||
|
||||
### Danger Actions
|
||||
|
||||
`.danger-action` should be soft warning, not pure red:
|
||||
|
||||
- pale rose background;
|
||||
- dark rose text;
|
||||
- transparent or rose-tinted border;
|
||||
- hover deepens the rose background and text slightly;
|
||||
- active state presses down;
|
||||
- disabled state uses muted rose/neutral colors.
|
||||
|
||||
### Primary Actions
|
||||
|
||||
`#adminSubmitBtn`, `.primary-link`, login submit, activation-code submit, AI primary action, and practice check buttons should share a clear primary treatment:
|
||||
|
||||
- solid deep green background;
|
||||
- white or warm-white text;
|
||||
- minimal border matching the background;
|
||||
- rounded pill or 10px radius based on control context;
|
||||
- subtle shadow/elevation;
|
||||
- hover slightly lightens or darkens while lifting by 1px;
|
||||
- active removes the lift and compresses visually;
|
||||
- focus-visible ring uses a soft green halo.
|
||||
|
||||
## Compatibility
|
||||
|
||||
The changes must not break:
|
||||
|
||||
- home category filters and material cards;
|
||||
- study mode tabs and recording/sentence controls;
|
||||
- login/register form controls;
|
||||
- admin create/edit form buttons;
|
||||
- admin video/user/activation-code action rows;
|
||||
- disabled buttons and hidden states.
|
||||
|
||||
Existing responsive rules should keep working. If a button currently becomes full-width or wraps on small screens, preserve that behavior.
|
||||
|
||||
## Testing
|
||||
|
||||
Verification should include:
|
||||
|
||||
- syntax sanity via existing JS checks if implementation touches no JS;
|
||||
- browser visual checks for home, study, admin, and login pages;
|
||||
- at least one desktop viewport and one mobile-width viewport;
|
||||
- confirm hover/active/focus/disabled states are not visually broken where practical;
|
||||
- confirm no text overflows inside buttons or chips.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No page structure redesign in this task.
|
||||
- No new icon system in this task.
|
||||
- No JavaScript behavior changes.
|
||||
- No changes to backend or data model.
|
||||
- No full Study Notebook layout implementation beyond button and chip styling.
|
||||
@@ -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 = "请求失败,请重试。";
|
||||
@@ -250,7 +254,8 @@ function createVideoCard(video) {
|
||||
statValues[2].textContent = `${difficultCount}`;
|
||||
|
||||
const favorite = card.querySelector(".home-favorite");
|
||||
favorite.textContent = isFavorite ? "已收藏" : "收藏";
|
||||
favorite.textContent = isFavorite ? "♥" : "♡";
|
||||
favorite.setAttribute("aria-label", isFavorite ? "取消收藏素材" : "收藏素材");
|
||||
favorite.classList.toggle("active", isFavorite);
|
||||
favorite.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
@@ -403,6 +408,7 @@ function toggleFavorite(videoId) {
|
||||
|
||||
user.favorites = [...favorites];
|
||||
saveState();
|
||||
scheduleProgressSync();
|
||||
renderHome();
|
||||
}
|
||||
|
||||
@@ -503,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();
|
||||
}
|
||||
+3
-3
@@ -4,7 +4,7 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Speaking Lab</title>
|
||||
<link rel="stylesheet" href="./styles.css?v=20260605-auth">
|
||||
<link rel="stylesheet" href="./styles.css?v=20260609-typography">
|
||||
</head>
|
||||
<body class="home-page">
|
||||
<header class="topbar home-topbar">
|
||||
@@ -40,7 +40,6 @@
|
||||
<h2>素材库</h2>
|
||||
<p>搜索素材,按分类和学习状态继续练习。</p>
|
||||
</div>
|
||||
<a class="primary-link" href="./study.html">进入学习页</a>
|
||||
</div>
|
||||
|
||||
<div id="homeCategoryFilters" class="home-categories"></div>
|
||||
@@ -50,6 +49,7 @@
|
||||
</main>
|
||||
|
||||
<script src="./auth.js?v=20260605-auth"></script>
|
||||
<script src="./home.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>
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>登录 Speaking Lab</title>
|
||||
<link rel="stylesheet" href="./styles.css?v=20260605-auth">
|
||||
<link rel="stylesheet" href="./styles.css?v=20260609-typography">
|
||||
</head>
|
||||
<body class="auth-page">
|
||||
<main class="auth-shell">
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
})();
|
||||
+3
-2
@@ -4,7 +4,7 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Speaking Lab 学习页</title>
|
||||
<link rel="stylesheet" href="./styles.css?v=20260605-auth">
|
||||
<link rel="stylesheet" href="./styles.css?v=20260712-study-controls">
|
||||
</head>
|
||||
<body>
|
||||
<header class="topbar">
|
||||
@@ -26,7 +26,7 @@
|
||||
<section class="left-stage">
|
||||
<section class="video-panel">
|
||||
<div class="video-frame">
|
||||
<video id="video" controls preload="metadata" crossorigin="anonymous"></video>
|
||||
<video id="video" controls preload="metadata" crossorigin="anonymous" playsinline webkit-playsinline></video>
|
||||
<div id="emptyVideo" class="empty-video">
|
||||
<strong>选择一个视频</strong>
|
||||
<span>从首页选择素材后开始练习。</span>
|
||||
@@ -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>
|
||||
+368
-156
@@ -11,7 +11,22 @@
|
||||
--brand-soft: #e4f5f1;
|
||||
--gold: #c98a12;
|
||||
--danger: #b42318;
|
||||
--control-surface: #f1eee7;
|
||||
--control-surface-hover: #e8e1d6;
|
||||
--control-surface-active: #ddd4c7;
|
||||
--control-border: rgba(67, 56, 45, 0.10);
|
||||
--control-ink: #33413c;
|
||||
--control-muted: #746b60;
|
||||
--primary-solid: #2f4b45;
|
||||
--primary-solid-hover: #263f3a;
|
||||
--primary-solid-active: #203631;
|
||||
--primary-soft-shadow: 0 10px 22px rgba(47, 75, 69, 0.16);
|
||||
--danger-soft: #fdecec;
|
||||
--danger-soft-hover: #f9dddd;
|
||||
--danger-ink: #9f2f35;
|
||||
--focus-ring: 0 0 0 3px rgba(47, 125, 99, 0.18);
|
||||
--shadow: 0 12px 30px rgba(25, 37, 59, 0.08);
|
||||
--font-sans: Inter, "Noto Sans SC", "Microsoft YaHei UI", "PingFang SC", "Hiragino Sans GB", "Segoe UI", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
|
||||
}
|
||||
|
||||
* {
|
||||
@@ -27,7 +42,11 @@ body {
|
||||
min-height: 100vh;
|
||||
background: var(--bg);
|
||||
color: var(--ink);
|
||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
font-family: var(--font-sans);
|
||||
line-height: 1.5;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
.auth-page {
|
||||
@@ -67,8 +86,9 @@ body {
|
||||
.auth-heading h1 {
|
||||
margin: 0;
|
||||
font-size: 28px;
|
||||
font-weight: 700;
|
||||
font-weight: 760;
|
||||
letter-spacing: 0;
|
||||
line-height: 1.18;
|
||||
}
|
||||
|
||||
.auth-heading p {
|
||||
@@ -86,7 +106,7 @@ body {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
font-weight: 680;
|
||||
}
|
||||
|
||||
.auth-form input {
|
||||
@@ -103,15 +123,6 @@ body {
|
||||
margin-top: 4px;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
color: #ffffff;
|
||||
background: #111827;
|
||||
font-weight: 700;
|
||||
box-shadow: 0 10px 22px rgba(17, 24, 39, 0.18);
|
||||
}
|
||||
|
||||
.auth-form button[type="submit"]:hover {
|
||||
background: #0f172a;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.auth-message {
|
||||
@@ -187,6 +198,78 @@ button:disabled {
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.primary-link,
|
||||
#adminSubmitBtn,
|
||||
#processAiSubtitlesBtn,
|
||||
.auth-form button[type="submit"],
|
||||
.login-form button,
|
||||
.admin-form button[type="submit"],
|
||||
.activation-code-form button[type="submit"],
|
||||
.practice-answer-row button {
|
||||
border-color: var(--primary-solid);
|
||||
color: #fffdf8;
|
||||
background: var(--primary-solid);
|
||||
box-shadow: var(--primary-soft-shadow);
|
||||
font-weight: 800;
|
||||
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.primary-link:hover,
|
||||
#adminSubmitBtn:hover,
|
||||
#processAiSubtitlesBtn:hover,
|
||||
.auth-form button[type="submit"]:hover,
|
||||
.login-form button:hover,
|
||||
.admin-form button[type="submit"]:hover,
|
||||
.activation-code-form button[type="submit"]:hover,
|
||||
.practice-answer-row button:hover {
|
||||
border-color: var(--primary-solid-hover);
|
||||
color: #fffdf8;
|
||||
background: var(--primary-solid-hover);
|
||||
box-shadow: 0 12px 26px rgba(47, 75, 69, 0.20);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.primary-link:active,
|
||||
#adminSubmitBtn:active,
|
||||
#processAiSubtitlesBtn:active,
|
||||
.auth-form button[type="submit"]:active,
|
||||
.login-form button:active,
|
||||
.admin-form button[type="submit"]:active,
|
||||
.activation-code-form button[type="submit"]:active,
|
||||
.practice-answer-row button:active {
|
||||
border-color: var(--primary-solid-active);
|
||||
background: var(--primary-solid-active);
|
||||
box-shadow: 0 6px 14px rgba(47, 75, 69, 0.14);
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.primary-link:focus-visible,
|
||||
#adminSubmitBtn:focus-visible,
|
||||
#processAiSubtitlesBtn:focus-visible,
|
||||
.auth-form button[type="submit"]:focus-visible,
|
||||
.login-form button:focus-visible,
|
||||
.admin-form button[type="submit"]:focus-visible,
|
||||
.activation-code-form button[type="submit"]:focus-visible,
|
||||
.practice-answer-row button:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: var(--primary-soft-shadow), var(--focus-ring);
|
||||
}
|
||||
|
||||
.primary-link:disabled,
|
||||
#adminSubmitBtn:disabled,
|
||||
#processAiSubtitlesBtn:disabled,
|
||||
.auth-form button[type="submit"]:disabled,
|
||||
.login-form button:disabled,
|
||||
.admin-form button[type="submit"]:disabled,
|
||||
.activation-code-form button[type="submit"]:disabled,
|
||||
.practice-answer-row button:disabled {
|
||||
border-color: #d8d2c8;
|
||||
color: #9b9388;
|
||||
background: #e8e2d8;
|
||||
box-shadow: none;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
@@ -257,7 +340,9 @@ textarea:focus {
|
||||
.brand h1 {
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
font-weight: 760;
|
||||
line-height: 1.1;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.top-actions {
|
||||
@@ -285,28 +370,31 @@ textarea:focus {
|
||||
}
|
||||
|
||||
.chip {
|
||||
min-height: 34px;
|
||||
border-color: transparent;
|
||||
border-radius: 20px;
|
||||
padding: 0 14px;
|
||||
color: #27364a;
|
||||
background: #eef2f7;
|
||||
min-height: 32px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 999px;
|
||||
padding: 0 15px;
|
||||
color: var(--control-ink);
|
||||
background: var(--control-surface);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.54);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
font-weight: 750;
|
||||
white-space: nowrap;
|
||||
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease;
|
||||
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.chip:hover {
|
||||
border-color: #cbd5e1;
|
||||
background: #f8fafc;
|
||||
box-shadow: 0 6px 16px rgba(15, 39, 66, 0.08);
|
||||
border-color: var(--control-border);
|
||||
background: var(--control-surface-hover);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.58), 0 8px 18px rgba(47, 64, 57, 0.09);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.chip.active {
|
||||
color: #fff;
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: #fffdf8;
|
||||
border-color: var(--primary-solid);
|
||||
background: var(--primary-solid);
|
||||
box-shadow: var(--primary-soft-shadow);
|
||||
}
|
||||
|
||||
.login-form,
|
||||
@@ -319,13 +407,6 @@ textarea:focus {
|
||||
width: 150px;
|
||||
}
|
||||
|
||||
.login-form button,
|
||||
.admin-form button[type="submit"] {
|
||||
color: #fff;
|
||||
background: var(--brand);
|
||||
border-color: var(--brand);
|
||||
}
|
||||
|
||||
.user-menu {
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
@@ -449,12 +530,12 @@ textarea:focus {
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
display: grid;
|
||||
grid-template-rows: minmax(520px, 1fr) auto auto;
|
||||
grid-template-rows: minmax(360px, 1fr) auto auto;
|
||||
}
|
||||
|
||||
.video-frame {
|
||||
position: relative;
|
||||
min-height: 520px;
|
||||
min-height: 360px;
|
||||
background: #0b1220;
|
||||
}
|
||||
|
||||
@@ -517,29 +598,40 @@ video {
|
||||
.tool-row button {
|
||||
min-width: 54px;
|
||||
min-height: 38px;
|
||||
border-radius: 10px;
|
||||
border-color: #d8e2ec;
|
||||
background: #f8fafc;
|
||||
font-weight: 650;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 999px;
|
||||
color: var(--control-muted);
|
||||
background: rgba(241, 238, 231, 0.88);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.52);
|
||||
font-weight: 750;
|
||||
white-space: nowrap;
|
||||
transition: background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
|
||||
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.tool-row button:disabled {
|
||||
border-color: #e2e8f0;
|
||||
color: #98a2b3;
|
||||
background: #f1f5f9;
|
||||
border-color: transparent;
|
||||
color: #9b9388;
|
||||
background: #e8e2d8;
|
||||
box-shadow: none;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.tool-row button:hover {
|
||||
border-color: #b9dcd5;
|
||||
background: var(--brand-soft);
|
||||
box-shadow: 0 8px 20px rgba(15, 118, 110, 0.1);
|
||||
border-color: var(--control-border);
|
||||
color: var(--control-ink);
|
||||
background: var(--control-surface-hover);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.58), 0 8px 18px rgba(47, 64, 57, 0.08);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.tool-row button:disabled:hover {
|
||||
border-color: transparent;
|
||||
color: #9b9388;
|
||||
background: #e8e2d8;
|
||||
box-shadow: none;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.right-practice-view {
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
@@ -549,28 +641,35 @@ video {
|
||||
|
||||
.practice-mode-bar {
|
||||
flex-wrap: wrap;
|
||||
gap: 5px;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.practice-mode-bar .tab {
|
||||
min-height: 32px;
|
||||
min-height: 34px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 999px;
|
||||
padding: 0 13px;
|
||||
color: #344054;
|
||||
background: #eef4f6;
|
||||
font-weight: 750;
|
||||
padding: 0 16px;
|
||||
color: var(--control-muted);
|
||||
background: rgba(241, 238, 231, 0.88);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.52);
|
||||
font-size: 13px;
|
||||
font-weight: 800;
|
||||
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.practice-mode-bar .tab:hover {
|
||||
border-color: #b9dcd5;
|
||||
background: var(--brand-soft);
|
||||
border-color: var(--control-border);
|
||||
color: var(--control-ink);
|
||||
background: var(--control-surface-hover);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.58), 0 8px 18px rgba(47, 64, 57, 0.08);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.practice-mode-bar .tab.active {
|
||||
color: #fff;
|
||||
border-color: var(--accent);
|
||||
background: var(--accent);
|
||||
color: #fffdf8;
|
||||
border-color: var(--primary-solid);
|
||||
background: var(--primary-solid);
|
||||
box-shadow: var(--primary-soft-shadow);
|
||||
}
|
||||
|
||||
.practice-body {
|
||||
@@ -636,21 +735,6 @@ video {
|
||||
min-width: 76px;
|
||||
min-height: 42px;
|
||||
align-self: start;
|
||||
color: #ffffff;
|
||||
border-color: var(--brand);
|
||||
background: var(--brand);
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.practice-answer-row button:hover {
|
||||
border-color: #0d625c;
|
||||
background: #0d625c;
|
||||
}
|
||||
|
||||
.practice-answer-row button:disabled {
|
||||
color: #98a2b3;
|
||||
border-color: #d8e2ec;
|
||||
background: #e8eef5;
|
||||
}
|
||||
|
||||
.practice-feedback {
|
||||
@@ -678,47 +762,48 @@ video {
|
||||
|
||||
.sentence-controls button {
|
||||
min-width: 76px;
|
||||
color: #0f2742;
|
||||
border-color: #c8d7e6;
|
||||
background: #ffffff;
|
||||
font-size: 15px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.sentence-controls #replayBtn {
|
||||
color: #fff;
|
||||
border-color: var(--accent);
|
||||
background: var(--accent);
|
||||
color: #fffdf8;
|
||||
border-color: var(--primary-solid);
|
||||
background: var(--primary-solid);
|
||||
box-shadow: var(--primary-soft-shadow);
|
||||
}
|
||||
|
||||
.sentence-controls #replayBtn:hover {
|
||||
border-color: #1e3a5f;
|
||||
background: #1e3a5f;
|
||||
box-shadow: 0 10px 24px rgba(15, 39, 66, 0.2);
|
||||
border-color: var(--primary-solid-hover);
|
||||
background: var(--primary-solid-hover);
|
||||
box-shadow: 0 12px 26px rgba(47, 75, 69, 0.20);
|
||||
}
|
||||
|
||||
.sentence-controls #replayBtn:disabled {
|
||||
border-color: #d8e2ec;
|
||||
color: #98a2b3;
|
||||
background: #e8eef5;
|
||||
border-color: #d8d2c8;
|
||||
color: #9b9388;
|
||||
background: #e8e2d8;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.study-side-actions .toggle {
|
||||
min-height: 42px;
|
||||
padding: 0 14px;
|
||||
border: 1px solid #c8d7e6;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 999px;
|
||||
color: #0f2742;
|
||||
background: #f8fafc;
|
||||
color: var(--control-muted);
|
||||
background: rgba(241, 238, 231, 0.88);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.52);
|
||||
font-size: 14px;
|
||||
font-weight: 800;
|
||||
transition: background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
|
||||
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.study-side-actions .toggle:hover {
|
||||
border-color: #b9dcd5;
|
||||
background: var(--brand-soft);
|
||||
box-shadow: 0 8px 20px rgba(15, 118, 110, 0.1);
|
||||
border-color: var(--control-border);
|
||||
color: var(--control-ink);
|
||||
background: var(--control-surface-hover);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.58), 0 8px 18px rgba(47, 64, 57, 0.08);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
@@ -729,8 +814,6 @@ video {
|
||||
|
||||
.study-side-actions #favoriteBtn {
|
||||
min-width: 68px;
|
||||
color: #0f2742;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.subtitle-card {
|
||||
@@ -907,8 +990,9 @@ video {
|
||||
}
|
||||
|
||||
.line-button.is-practiced {
|
||||
background: #f7fdf9;
|
||||
border-color: #ccebdd;
|
||||
background: #ecfdf3;
|
||||
border-color: #86efac;
|
||||
box-shadow: inset 3px 0 0 #16a34a;
|
||||
}
|
||||
|
||||
.line-button.is-difficult {
|
||||
@@ -916,10 +1000,24 @@ video {
|
||||
box-shadow: inset 3px 0 0 var(--gold);
|
||||
}
|
||||
|
||||
.line-button.is-practiced.is-difficult {
|
||||
background: #fff7e6;
|
||||
border-color: #f4c86a;
|
||||
box-shadow:
|
||||
inset 3px 0 0 var(--gold),
|
||||
inset 7px 0 0 #16a34a;
|
||||
}
|
||||
|
||||
.line-button.active.is-difficult {
|
||||
box-shadow: inset 3px 0 0 var(--gold);
|
||||
}
|
||||
|
||||
.line-button.active.is-practiced.is-difficult {
|
||||
box-shadow:
|
||||
inset 3px 0 0 var(--gold),
|
||||
inset 7px 0 0 #16a34a;
|
||||
}
|
||||
|
||||
.line-time {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
@@ -949,22 +1047,36 @@ video {
|
||||
|
||||
.line-status-button {
|
||||
min-height: 26px;
|
||||
padding: 0 7px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 999px;
|
||||
padding: 0 9px;
|
||||
color: var(--control-muted);
|
||||
background: rgba(241, 238, 231, 0.74);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.50);
|
||||
font-size: 12px;
|
||||
font-weight: 750;
|
||||
white-space: nowrap;
|
||||
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.line-status-button:hover {
|
||||
border-color: var(--control-border);
|
||||
color: var(--control-ink);
|
||||
background: var(--control-surface-hover);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.58), 0 6px 14px rgba(47, 64, 57, 0.07);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.line-status-button.practiced.active {
|
||||
color: #047857;
|
||||
border-color: #9bd8c0;
|
||||
background: #ecfdf5;
|
||||
color: #475467;
|
||||
border-color: #d8dee8;
|
||||
background: #eef2f6;
|
||||
}
|
||||
|
||||
.line-status-button.difficult.active {
|
||||
color: #92400e;
|
||||
border-color: #f5c56f;
|
||||
background: #fffbeb;
|
||||
color: var(--danger-ink);
|
||||
border-color: rgba(159, 47, 53, 0.10);
|
||||
background: var(--danger-soft);
|
||||
}
|
||||
|
||||
.line-primary mark,
|
||||
@@ -1029,12 +1141,6 @@ video {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.admin-form .secondary-action {
|
||||
color: var(--ink);
|
||||
background: #fff;
|
||||
border-color: var(--line);
|
||||
}
|
||||
|
||||
.admin-page {
|
||||
min-height: 100vh;
|
||||
background: #f8fafc;
|
||||
@@ -1348,62 +1454,111 @@ video {
|
||||
}
|
||||
|
||||
.danger-action {
|
||||
border-color: #fecdd3;
|
||||
border-radius: 8px;
|
||||
color: #be123c;
|
||||
background: #fff1f2;
|
||||
white-space: nowrap;
|
||||
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease;
|
||||
min-height: 34px;
|
||||
border: 1px solid rgba(159, 47, 53, 0.10);
|
||||
border-radius: 10px;
|
||||
padding: 0 12px;
|
||||
color: var(--danger-ink);
|
||||
background: var(--danger-soft);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.55);
|
||||
font-size: 13px;
|
||||
font-weight: 800;
|
||||
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.danger-action:hover {
|
||||
border-color: #fb7185;
|
||||
color: #9f1239;
|
||||
background: #ffe4e6;
|
||||
box-shadow: 0 8px 18px rgba(190, 18, 60, 0.1);
|
||||
border-color: rgba(159, 47, 53, 0.16);
|
||||
color: #84262c;
|
||||
background: var(--danger-soft-hover);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.58), 0 8px 18px rgba(159, 47, 53, 0.08);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.primary-link,
|
||||
.secondary-action {
|
||||
.danger-action:active {
|
||||
background: #f4cccc;
|
||||
box-shadow: inset 0 1px 2px rgba(159, 47, 53, 0.14);
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.danger-action:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px rgba(159, 47, 53, 0.14);
|
||||
}
|
||||
|
||||
.danger-action:disabled {
|
||||
border-color: rgba(159, 47, 53, 0.08);
|
||||
color: #aa8e8f;
|
||||
background: #f2e4e2;
|
||||
box-shadow: none;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.secondary-action,
|
||||
.user-menu button {
|
||||
min-height: 34px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 10px;
|
||||
padding: 0 12px;
|
||||
color: var(--control-muted);
|
||||
background: rgba(241, 238, 231, 0.88);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.52);
|
||||
font-size: 13px;
|
||||
font-weight: 750;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.secondary-action:hover,
|
||||
.user-menu button:hover {
|
||||
color: var(--control-ink);
|
||||
border-color: var(--control-border);
|
||||
background: var(--control-surface-hover);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.58), 0 8px 18px rgba(47, 64, 57, 0.08);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.secondary-action:active,
|
||||
.user-menu button:active {
|
||||
background: var(--control-surface-active);
|
||||
box-shadow: inset 0 1px 2px rgba(47, 64, 57, 0.12);
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.secondary-action:disabled,
|
||||
.secondary-action:disabled:hover,
|
||||
.user-menu button:disabled,
|
||||
.user-menu button:disabled:hover {
|
||||
border-color: transparent;
|
||||
color: #9b9388;
|
||||
background: #e8e2d8;
|
||||
box-shadow: none;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.chip:focus-visible,
|
||||
.secondary-action:focus-visible,
|
||||
.user-menu button:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: var(--focus-ring);
|
||||
}
|
||||
|
||||
.primary-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 36px;
|
||||
border: 1px solid #dbe4ee;
|
||||
border: 1px solid var(--primary-solid);
|
||||
border-radius: 8px;
|
||||
padding: 0 12px;
|
||||
color: var(--ink);
|
||||
background: #fff;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.admin-video-actions .secondary-action,
|
||||
.admin-form .secondary-action {
|
||||
color: #1f3b57;
|
||||
border-color: #dbe4ee;
|
||||
background: #f8fafc;
|
||||
box-shadow: 0 6px 16px rgba(15, 23, 42, 0.04);
|
||||
}
|
||||
|
||||
.primary-link {
|
||||
color: #fff;
|
||||
background: var(--brand);
|
||||
border-color: var(--brand);
|
||||
}
|
||||
|
||||
.primary-link:hover {
|
||||
color: #fff;
|
||||
background: #0d625c;
|
||||
border-color: #0d625c;
|
||||
}
|
||||
|
||||
.secondary-action:hover {
|
||||
border-color: #b8c7d9;
|
||||
background: #f1f5f9;
|
||||
}
|
||||
|
||||
.home-page {
|
||||
min-height: 100vh;
|
||||
background: #f8fafc;
|
||||
@@ -1467,6 +1622,7 @@ video {
|
||||
.home-plan-card strong {
|
||||
color: #0f2742;
|
||||
font-size: 22px;
|
||||
font-weight: 760;
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
@@ -1519,12 +1675,13 @@ video {
|
||||
}
|
||||
|
||||
.home-metric-label {
|
||||
font-weight: 800;
|
||||
font-weight: 720;
|
||||
}
|
||||
|
||||
.home-metric strong {
|
||||
color: #0f2742;
|
||||
font-size: 28px;
|
||||
font-weight: 760;
|
||||
line-height: 1;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
@@ -1580,6 +1737,8 @@ video {
|
||||
.home-heading h2 {
|
||||
margin: 0;
|
||||
font-size: 24px;
|
||||
font-weight: 760;
|
||||
line-height: 1.22;
|
||||
}
|
||||
|
||||
.home-heading p {
|
||||
@@ -1674,11 +1833,15 @@ video {
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
z-index: 2;
|
||||
min-height: 28px;
|
||||
min-width: 44px;
|
||||
min-height: 44px;
|
||||
border-color: rgba(255, 255, 255, 0.38);
|
||||
border-radius: 999px;
|
||||
padding: 0;
|
||||
color: #fff;
|
||||
background: rgba(17, 24, 39, 0.3);
|
||||
font-size: 12px;
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.home-favorite:hover,
|
||||
@@ -1742,8 +1905,8 @@ video {
|
||||
margin: 0;
|
||||
color: #1a202c;
|
||||
font-size: 18px;
|
||||
font-weight: 850;
|
||||
line-height: 1.42;
|
||||
font-weight: 760;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.home-card-meta,
|
||||
@@ -1800,7 +1963,7 @@ video {
|
||||
|
||||
.home-card-stats dd {
|
||||
color: #1a202c;
|
||||
font-weight: 800;
|
||||
font-weight: 760;
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -1915,6 +2078,49 @@ video {
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.home-topbar {
|
||||
position: static;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: 10px;
|
||||
height: auto;
|
||||
padding: 12px 14px;
|
||||
}
|
||||
|
||||
.home-topbar .brand {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.home-topbar .top-actions {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.home-topbar .home-search {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.home-topbar .secondary-action {
|
||||
justify-self: start;
|
||||
width: auto;
|
||||
min-width: 58px;
|
||||
}
|
||||
|
||||
.home-topbar .user-menu {
|
||||
justify-content: flex-end;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.home-topbar #homeUserLabel {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.home-shell {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 20px;
|
||||
@@ -1926,7 +2132,13 @@ video {
|
||||
}
|
||||
|
||||
.home-metrics {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
grid-template-columns: 1fr;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.home-metric {
|
||||
min-height: 70px;
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.home-heading {
|
||||
|
||||
@@ -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);
|
||||
@@ -1,9 +1,11 @@
|
||||
import assert from "node:assert/strict";
|
||||
import authHelpers from "../auth.js";
|
||||
|
||||
const { getLoginUrlForPath, shouldShowAdminEntry } = authHelpers;
|
||||
const { getLoginUrlForPath, isUnauthorizedStatus, shouldShowAdminEntry } = authHelpers;
|
||||
|
||||
assert.equal(getLoginUrlForPath("/study.html?video=2"), "./login.html?next=%2Fstudy.html%3Fvideo%3D2");
|
||||
assert.equal(isUnauthorizedStatus(401), true);
|
||||
assert.equal(isUnauthorizedStatus(403), false);
|
||||
assert.equal(shouldShowAdminEntry({ role: "admin" }), true);
|
||||
assert.equal(shouldShowAdminEntry({ role: "user" }), false);
|
||||
assert.equal(shouldShowAdminEntry(null), 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(
|
||||
@@ -67,7 +66,40 @@ def test_activation_code_registers_user_once():
|
||||
raise AssertionError("used activation code should not register another user")
|
||||
|
||||
|
||||
def test_initialize_database_removes_legacy_used_activation_codes():
|
||||
with TempDatabase():
|
||||
with db.get_connection() as connection:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO users (email, password_hash, display_name)
|
||||
VALUES ('legacy-user', 'hash', 'legacy-user')
|
||||
"""
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO activation_codes (
|
||||
code, created_by, used_by_user_id, used_at, status
|
||||
)
|
||||
VALUES ('SL-USED12-USED34-USED56', 'admin', ?, CURRENT_TIMESTAMP, 'used')
|
||||
""",
|
||||
(int(cursor.lastrowid),),
|
||||
)
|
||||
|
||||
with db.get_connection() as connection:
|
||||
count = connection.execute(
|
||||
"SELECT COUNT(*) AS count FROM activation_codes WHERE status = 'used'"
|
||||
).fetchone()["count"]
|
||||
assert count == 1
|
||||
|
||||
db.initialize_database()
|
||||
|
||||
with db.get_connection() as connection:
|
||||
count = connection.execute("SELECT COUNT(*) AS count FROM activation_codes").fetchone()["count"]
|
||||
assert count == 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_password_hash_roundtrip()
|
||||
test_auth_token_roundtrip_and_tamper_rejection()
|
||||
test_activation_code_registers_user_once()
|
||||
test_initialize_database_removes_legacy_used_activation_codes()
|
||||
@@ -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(
|
||||
@@ -104,6 +105,66 @@ def test_activation_registration_login_and_reuse_rejection(monkeypatch):
|
||||
raise AssertionError("used activation code should be rejected")
|
||||
|
||||
|
||||
def test_new_user_login_invalidates_previous_bearer_token(monkeypatch):
|
||||
configure_admin(monkeypatch)
|
||||
|
||||
with TempDatabase():
|
||||
db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin")
|
||||
main.api_auth_register(main.RegisterRequest(
|
||||
activationCode="SL-ABC123-DEF456-GHI789",
|
||||
username="student",
|
||||
password="secret123",
|
||||
))
|
||||
|
||||
first_login = main.api_auth_login(main.LoginRequest(username="student", password="secret123"))
|
||||
first_bearer = HTTPAuthorizationCredentials(scheme="Bearer", credentials=first_login["token"])
|
||||
assert main.api_auth_session(main.require_session(first_bearer))["user"]["username"] == "student"
|
||||
|
||||
second_login = main.api_auth_login(main.LoginRequest(username="student", password="secret123"))
|
||||
second_bearer = HTTPAuthorizationCredentials(scheme="Bearer", credentials=second_login["token"])
|
||||
assert main.api_auth_session(main.require_session(second_bearer))["user"]["username"] == "student"
|
||||
|
||||
try:
|
||||
main.require_session(first_bearer)
|
||||
except HTTPException as error:
|
||||
assert error.status_code == 401
|
||||
else:
|
||||
raise AssertionError("old bearer token should be invalid after a newer login")
|
||||
|
||||
|
||||
def test_legacy_bearer_token_works_until_user_logs_in_again(monkeypatch):
|
||||
configure_admin(monkeypatch)
|
||||
|
||||
with TempDatabase():
|
||||
db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin")
|
||||
registered = main.api_auth_register(main.RegisterRequest(
|
||||
activationCode="SL-ABC123-DEF456-GHI789",
|
||||
username="student",
|
||||
password="secret123",
|
||||
))
|
||||
legacy_token = main.create_auth_token(
|
||||
{"username": "student", "role": "user", "userId": registered["user"]["id"]},
|
||||
main.get_token_secret(),
|
||||
)
|
||||
with db.get_connection() as connection:
|
||||
connection.execute(
|
||||
"UPDATE users SET session_token = NULL WHERE id = ?",
|
||||
(registered["user"]["id"],),
|
||||
)
|
||||
|
||||
legacy_bearer = HTTPAuthorizationCredentials(scheme="Bearer", credentials=legacy_token)
|
||||
assert main.api_auth_session(main.require_session(legacy_bearer))["user"]["username"] == "student"
|
||||
|
||||
main.api_auth_login(main.LoginRequest(username="student", password="secret123"))
|
||||
|
||||
try:
|
||||
main.require_session(legacy_bearer)
|
||||
except HTTPException as error:
|
||||
assert error.status_code == 401
|
||||
else:
|
||||
raise AssertionError("legacy token should expire after the account logs in again")
|
||||
|
||||
|
||||
def test_normal_user_cannot_use_admin_dependency(monkeypatch):
|
||||
configure_admin(monkeypatch)
|
||||
|
||||
@@ -136,6 +197,12 @@ if __name__ == "__main__":
|
||||
test_activation_registration_login_and_reuse_rejection(patch)
|
||||
patch.restore()
|
||||
configure_admin(patch)
|
||||
test_new_user_login_invalidates_previous_bearer_token(patch)
|
||||
patch.restore()
|
||||
configure_admin(patch)
|
||||
test_legacy_bearer_token_works_until_user_logs_in_again(patch)
|
||||
patch.restore()
|
||||
configure_admin(patch)
|
||||
test_normal_user_cannot_use_admin_dependency(patch)
|
||||
finally:
|
||||
patch.restore()
|
||||
@@ -0,0 +1,12 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const html = readFileSync(join(__dirname, "..", "index.html"), "utf8");
|
||||
|
||||
assert.equal(
|
||||
html.includes('<a class="primary-link" href="./study.html">进入学习页</a>'),
|
||||
false,
|
||||
);
|
||||
@@ -0,0 +1,31 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const css = readFileSync(join(__dirname, "..", "styles.css"), "utf8");
|
||||
|
||||
assert.match(
|
||||
css,
|
||||
/@media\s*\(max-width:\s*720px\)[\s\S]*\.home-topbar\s*\{[\s\S]*position:\s*static;/,
|
||||
"mobile home topbar should not remain sticky and tall above the content",
|
||||
);
|
||||
|
||||
assert.match(
|
||||
css,
|
||||
/@media\s*\(max-width:\s*720px\)[\s\S]*\.home-topbar\s+\.top-actions\s*\{[\s\S]*display:\s*grid;[\s\S]*grid-template-columns:\s*minmax\(0,\s*1fr\)\s+auto;/,
|
||||
"mobile top actions should keep search and account controls compact",
|
||||
);
|
||||
|
||||
assert.match(
|
||||
css,
|
||||
/@media\s*\(max-width:\s*720px\)[\s\S]*\.home-metrics\s*\{[\s\S]*grid-template-columns:\s*1fr;/,
|
||||
"mobile dashboard metrics should use one readable column",
|
||||
);
|
||||
|
||||
assert.match(
|
||||
css,
|
||||
/\.home-favorite\s*\{[\s\S]*min-width:\s*44px;[\s\S]*min-height:\s*44px;/,
|
||||
"favorite buttons should meet mobile touch target sizing",
|
||||
);
|
||||
@@ -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]);
|
||||
@@ -0,0 +1,25 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const css = readFileSync(join(__dirname, "..", "styles.css"), "utf8");
|
||||
|
||||
assert.match(
|
||||
css,
|
||||
/\.line-button\.is-practiced\s*\{[\s\S]*background:\s*#ecfdf3;[\s\S]*border-color:\s*#86efac;[\s\S]*box-shadow:\s*inset 3px 0 0 #16a34a;/,
|
||||
"practiced transcript rows should use a clear green row highlight",
|
||||
);
|
||||
|
||||
assert.match(
|
||||
css,
|
||||
/\.line-button\.is-difficult\s*\{[\s\S]*background:\s*#fffaf0;[\s\S]*box-shadow:\s*inset 3px 0 0 var\(--gold\);/,
|
||||
"difficult transcript rows should keep the existing gold row highlight",
|
||||
);
|
||||
|
||||
assert.doesNotMatch(
|
||||
css,
|
||||
/\.line-status-button\.practiced\.active\s*\{[\s\S]*#16a34a/,
|
||||
"the stronger practiced color should belong to the transcript row, not the status button",
|
||||
);
|
||||
@@ -0,0 +1,31 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const css = readFileSync(join(__dirname, "..", "styles.css"), "utf8");
|
||||
|
||||
assert.match(
|
||||
css,
|
||||
/--font-sans:\s*Inter,\s*"Noto Sans SC",\s*"Microsoft YaHei UI",\s*"PingFang SC"/,
|
||||
"global font stack should pair polished Latin and Chinese UI fonts",
|
||||
);
|
||||
|
||||
assert.match(
|
||||
css,
|
||||
/body\s*\{[\s\S]*font-family:\s*var\(--font-sans\);[\s\S]*line-height:\s*1\.5;[\s\S]*text-rendering:\s*optimizeLegibility;[\s\S]*-webkit-font-smoothing:\s*antialiased;/,
|
||||
"body should use the shared font stack with improved rendering",
|
||||
);
|
||||
|
||||
assert.match(
|
||||
css,
|
||||
/\.brand h1\s*\{[\s\S]*font-weight:\s*760;[\s\S]*letter-spacing:\s*0;/,
|
||||
"brand title should use a refined strong weight",
|
||||
);
|
||||
|
||||
assert.match(
|
||||
css,
|
||||
/\.home-card-body h3\s*\{[\s\S]*font-weight:\s*760;[\s\S]*line-height:\s*1\.35;/,
|
||||
"home card titles should be less heavy and easier to scan",
|
||||
);
|
||||
Reference in new issue
Block a user