feat: protect admin APIs

This commit is contained in:
TTlaji committed 2026-06-05 00:25:20 +08:00
1 parent 4f027a3728
commit 1e9228e50a
13 files changed
+657 -95

No files matched your search

+2 -5
View File
@@ -6,11 +6,8 @@ TEXT_AI_PROTOCOL=openai
TEXT_AI_BATCH_SIZE=0
TEXT_AI_TIMEOUT_SECONDS=120
ASR_PROVIDER=openai
OPENAI_API_KEY=
OPENAI_BASE_URL=https://api.openai.com
OPENAI_ASR_MODEL=whisper-1
ASR_TIMEOUT_SECONDS=120
ADMIN_USERNAME=admin
ADMIN_PASSWORD=change-me
LOCAL_WHISPER_ENABLED=true
LOCAL_WHISPER_MODEL=small
+1
View File
@@ -1,6 +1,7 @@
backend/speaking_lab.sqlite
uploads/videos/
uploads/subtitles/
uploads/images/
__pycache__/
*.pyc
*.lnk
+13 -4
View File
@@ -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">
<link rel="stylesheet" href="./styles.css?v=20260604-admin-polish">
</head>
<body class="admin-page">
<header class="topbar admin-topbar">
@@ -19,8 +19,13 @@
<main id="adminLocked" class="admin-locked empty-state" hidden>
<h2>需要管理员账号</h2>
<p>请返回学习页,使用管理员账号登录后再进入后台。</p>
<a class="primary-link" href="./index.html">返回登录</a>
<p>请输入 .env 中配置的管理员账号密码。</p>
<form id="adminLoginForm" class="admin-login-form">
<input id="adminUsername" type="text" placeholder="管理员账号" autocomplete="username" required>
<input id="adminPassword" type="password" placeholder="管理员密码" autocomplete="current-password" required>
<button type="submit">登录后台</button>
</form>
<p id="adminLoginMessage" class="admin-message" hidden></p>
</main>
<main id="adminContent" class="admin-shell" hidden>
@@ -34,6 +39,10 @@
<input id="adminSpeaker" type="text" placeholder="演讲者 / 片段来源">
<textarea id="adminDescription" placeholder="简介"></textarea>
<input id="adminTags" type="text" placeholder="标签,用逗号分隔,如 科技,设计">
<label class="file-input" data-default-label="封面图片">
<span>封面图片</span>
<input id="adminCoverFile" type="file" accept="image/*">
</label>
<label class="file-input" data-default-label="选择视频文件">
<span>选择视频文件</span>
<input id="adminVideoFile" type="file" accept="video/*">
@@ -74,6 +83,6 @@
</section>
</main>
<script src="./admin.js"></script>
<script src="./admin.js?v=20260604-admin-polish"></script>
</body>
</html>
+97 -25
View File
@@ -1,10 +1,15 @@
const STORAGE_KEY = "speaking-lab-state-v1";
const ADMIN_CREDENTIALS_KEY = "speaking-lab-admin-credentials-v1";
const IS_BROWSER = typeof document !== "undefined";
const els = {
identity: IS_BROWSER ? document.querySelector("#adminIdentity") : null,
locked: IS_BROWSER ? document.querySelector("#adminLocked") : null,
content: IS_BROWSER ? document.querySelector("#adminContent") : null,
adminLoginForm: IS_BROWSER ? document.querySelector("#adminLoginForm") : null,
adminUsername: IS_BROWSER ? document.querySelector("#adminUsername") : null,
adminPassword: IS_BROWSER ? document.querySelector("#adminPassword") : null,
adminLoginMessage: IS_BROWSER ? document.querySelector("#adminLoginMessage") : null,
formTitle: IS_BROWSER ? document.querySelector("#adminFormTitle") : null,
form: IS_BROWSER ? document.querySelector("#adminCreateForm") : null,
submitBtn: IS_BROWSER ? document.querySelector("#adminSubmitBtn") : null,
@@ -13,6 +18,7 @@ const els = {
speaker: IS_BROWSER ? document.querySelector("#adminSpeaker") : null,
description: IS_BROWSER ? document.querySelector("#adminDescription") : null,
tags: IS_BROWSER ? document.querySelector("#adminTags") : null,
coverFile: IS_BROWSER ? document.querySelector("#adminCoverFile") : null,
videoFile: IS_BROWSER ? document.querySelector("#adminVideoFile") : null,
videoUrl: IS_BROWSER ? document.querySelector("#adminVideoUrl") : null,
subtitleEn: IS_BROWSER ? document.querySelector("#adminSubtitleEn") : null,
@@ -31,6 +37,7 @@ const els = {
let videos = [];
let editingVideo = null;
let editableSubtitles = createEmptySubtitleEditState();
let adminCredentials = IS_BROWSER ? getStoredAdminCredentials(window.sessionStorage) : null;
if (IS_BROWSER) initializeAdmin();
@@ -46,18 +53,8 @@ function loadState() {
}
}
function getCurrentUser() {
const state = loadState();
return state.users.find((user) => user.id === state.currentUserId) || null;
}
function isAdmin(user) {
const email = String(user?.email || "").toLowerCase();
return user?.role === "admin" || email.includes("admin");
}
async function apiRequest(path, options = {}) {
const response = await fetch(path, options);
const response = await fetch(path, withAdminAuth(options));
if (!response.ok) {
let message = "请求失败,请重试。";
try {
@@ -72,18 +69,7 @@ async function apiRequest(path, options = {}) {
}
function initializeAdmin() {
const user = getCurrentUser();
if (!isAdmin(user)) {
els.identity.textContent = "未登录管理员账号";
els.locked.hidden = false;
els.content.hidden = true;
return;
}
els.identity.textContent = `${user.email} · 管理员`;
els.locked.hidden = true;
els.content.hidden = false;
els.adminLoginForm?.addEventListener("submit", loginAdmin);
els.form.addEventListener("submit", addVideo);
els.refreshBtn.addEventListener("click", loadVideos);
els.cancelEditBtn.addEventListener("click", resetFormMode);
@@ -91,10 +77,92 @@ function initializeAdmin() {
els.processAiSubtitlesBtn?.addEventListener("click", processAiSubtitles);
els.generateLocalWhisperSubtitlesBtn?.addEventListener("click", generateLocalWhisperSubtitles);
bindFileInputs();
if (adminCredentials) {
unlockAdmin(adminCredentials.username);
verifyStoredAdminCredentials();
} else {
lockAdmin("请输入管理员账号密码。");
}
}
function lockAdmin(message = "") {
els.identity.textContent = "未登录管理员账号";
els.locked.hidden = false;
els.content.hidden = true;
if (els.adminLoginMessage) {
els.adminLoginMessage.hidden = !message;
els.adminLoginMessage.textContent = message;
els.adminLoginMessage.classList.toggle("error", Boolean(message));
}
}
function unlockAdmin(username) {
els.identity.textContent = `${username} · 管理员`;
els.locked.hidden = true;
els.content.hidden = false;
loadAiStatus();
loadVideos();
}
async function loginAdmin(event) {
event.preventDefault();
const username = els.adminUsername.value.trim();
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);
if (els.adminLoginMessage) els.adminLoginMessage.hidden = true;
els.adminLoginForm.reset();
unlockAdmin(result.username || username);
} catch (error) {
adminCredentials = null;
clearStoredAdminCredentials(window.sessionStorage);
lockAdmin(error.message || "管理员账号或密码错误。");
}
}
async function verifyStoredAdminCredentials() {
try {
const result = await apiRequest("/api/admin/session");
unlockAdmin(result.username || adminCredentials.username);
} catch {
adminCredentials = null;
clearStoredAdminCredentials(window.sessionStorage);
lockAdmin("管理员登录已失效,请重新登录。");
}
}
function withAdminAuth(options = {}) {
if (!adminCredentials) return options;
const headers = new Headers(options.headers || {});
headers.set("Authorization", `Basic ${btoa(`${adminCredentials.username}:${adminCredentials.password}`)}`);
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 setStoredAdminCredentials(storage, username, password) {
storage.setItem(ADMIN_CREDENTIALS_KEY, JSON.stringify({ username, password }));
}
function clearStoredAdminCredentials(storage) {
storage.removeItem(ADMIN_CREDENTIALS_KEY);
}
function getFileInputState(file, defaultLabel) {
if (!file) {
return {
@@ -112,7 +180,7 @@ function getFileInputState(file, defaultLabel) {
}
function bindFileInputs() {
[els.videoFile, els.subtitleEn, els.subtitleZh].forEach((input) => {
[els.coverFile, els.videoFile, els.subtitleEn, els.subtitleZh].forEach((input) => {
const label = input?.closest(".file-input");
if (!label) return;
@@ -134,7 +202,7 @@ function updateFileInputLabel(input) {
}
function resetFileInputs() {
[els.videoFile, els.subtitleEn, els.subtitleZh].forEach((input) => {
[els.coverFile, els.videoFile, els.subtitleEn, els.subtitleZh].forEach((input) => {
if (input) updateFileInputLabel(input);
});
}
@@ -468,6 +536,7 @@ async function addVideo(event) {
formData.append("tags", els.tags.value.trim());
formData.append("video_url", els.videoUrl.value.trim());
if (els.coverFile.files?.[0]) formData.append("cover_file", els.coverFile.files[0]);
if (els.videoFile.files?.[0]) formData.append("video_file", els.videoFile.files[0]);
if (els.subtitleEn.files?.[0]) formData.append("subtitle_en", els.subtitleEn.files[0]);
if (els.subtitleZh.files?.[0]) formData.append("subtitle_zh", els.subtitleZh.files[0]);
@@ -508,6 +577,9 @@ if (typeof module !== "undefined" && module.exports) {
getLocalWhisperButtonState,
shouldConfirmSubtitleOverwrite,
pickVideoAfterSave,
getStoredAdminCredentials,
setStoredAdminCredentials,
clearStoredAdminCredentials,
};
}
+22 -4
View File
@@ -38,6 +38,7 @@ def initialize_database() -> None:
description TEXT,
tags TEXT,
video_url TEXT,
cover_url TEXT,
duration_seconds INTEGER,
status TEXT NOT NULL DEFAULT 'draft',
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
@@ -76,6 +77,12 @@ def initialize_database() -> None:
ON user_interactions (user_id);
"""
)
video_columns = {
row["name"]
for row in connection.execute("PRAGMA table_info(videos)").fetchall()
}
if "cover_url" not in video_columns:
connection.execute("ALTER TABLE videos ADD COLUMN cover_url TEXT")
connection.execute(
"""
DELETE FROM subtitles
@@ -145,6 +152,7 @@ def row_to_video(row: sqlite3.Row, subtitle_rows: list[sqlite3.Row]) -> dict[str
"tags": tags if isinstance(tags, list) and tags else ["未分类"],
"duration": row["duration_seconds"] or 0,
"videoUrl": row["video_url"] or "",
"coverUrl": row["cover_url"] or "",
"sourceType": "url" if str(row["video_url"] or "").startswith(("http://", "https://")) else "local-file",
"subtitles": subtitles,
}
@@ -157,15 +165,16 @@ def create_video(
description: str | None,
tags: list[str],
video_url: str,
cover_url: str = "",
subtitles: list[dict[str, str]],
) -> dict[str, object]:
with get_connection() as connection:
cursor = connection.execute(
"""
INSERT INTO videos (
title, speaker, description, tags, video_url, status
title, speaker, description, tags, video_url, cover_url, status
)
VALUES (?, ?, ?, ?, ?, 'published')
VALUES (?, ?, ?, ?, ?, ?, 'published')
""",
(
title,
@@ -173,6 +182,7 @@ def create_video(
repair_mojibake_text(description or ""),
json.dumps([repair_mojibake_text(tag) for tag in tags], ensure_ascii=False),
repair_mojibake_text(video_url),
repair_mojibake_text(cover_url),
),
)
video_id = int(cursor.lastrowid)
@@ -259,7 +269,7 @@ def delete_video(video_id: int) -> dict[str, object] | None:
with get_connection() as connection:
video_row = connection.execute(
"""
SELECT id, video_url
SELECT id, video_url, cover_url
FROM videos
WHERE id = ?
""",
@@ -280,6 +290,8 @@ def delete_video(video_id: int) -> dict[str, object] | None:
upload_paths = []
if video_row["video_url"]:
upload_paths.append(video_row["video_url"])
if video_row["cover_url"]:
upload_paths.append(video_row["cover_url"])
upload_paths.extend(row["file_path"] for row in subtitle_rows if row["file_path"])
connection.execute("DELETE FROM videos WHERE id = ?", (video_id,))
@@ -298,12 +310,13 @@ def update_video(
description: str | None,
tags: list[str],
video_url: str | None,
cover_url: str | None = None,
subtitles: list[dict[str, str]],
) -> dict[str, object] | None:
with get_connection() as connection:
existing = connection.execute(
"""
SELECT id, video_url
SELECT id, video_url, cover_url
FROM videos
WHERE id = ?
""",
@@ -316,6 +329,9 @@ def update_video(
final_video_url = video_url if video_url is not None else existing["video_url"]
if video_url is not None and existing["video_url"] and existing["video_url"] != video_url:
old_upload_paths.append(existing["video_url"])
final_cover_url = cover_url if cover_url is not None else existing["cover_url"]
if cover_url is not None and existing["cover_url"] and existing["cover_url"] != cover_url:
old_upload_paths.append(existing["cover_url"])
connection.execute(
"""
@@ -325,6 +341,7 @@ def update_video(
description = ?,
tags = ?,
video_url = ?,
cover_url = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
""",
@@ -334,6 +351,7 @@ def update_video(
repair_mojibake_text(description or ""),
json.dumps([repair_mojibake_text(tag) for tag in tags], ensure_ascii=False),
repair_mojibake_text(final_video_url),
repair_mojibake_text(final_cover_url or ""),
video_id,
),
)
+90 -12
View File
@@ -1,12 +1,14 @@
from pathlib import Path
import secrets
from urllib.parse import urlparse
from uuid import uuid4
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi import Depends, FastAPI, File, Form, HTTPException, UploadFile
from fastapi.responses import FileResponse
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.staticfiles import StaticFiles
from .ai_config import get_ai_status, load_local_whisper_config, load_text_ai_config
from .ai_config import get_ai_status, get_config_value, load_local_whisper_config, load_text_ai_config
from .db import (
DATABASE_PATH,
create_video,
@@ -28,12 +30,14 @@ PROJECT_DIR = Path(__file__).resolve().parent.parent
UPLOADS_DIR = PROJECT_DIR / "uploads"
VIDEO_EXTENSIONS = {".mp4", ".webm", ".mov", ".m4v"}
SUBTITLE_EXTENSIONS = {".srt", ".vtt"}
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".gif"}
UPLOAD_CHUNK_SIZE = 1024 * 1024
def ensure_upload_directories() -> None:
UPLOADS_DIR.mkdir(parents=True, exist_ok=True)
(UPLOADS_DIR / "videos").mkdir(parents=True, exist_ok=True)
(UPLOADS_DIR / "images").mkdir(parents=True, exist_ok=True)
(UPLOADS_DIR / "subtitles").mkdir(parents=True, exist_ok=True)
@@ -118,9 +122,18 @@ def cleanup_upload_urls(upload_urls: list[str]) -> list[str]:
return warnings
def save_generated_subtitle_file(content: str, language_code: str) -> str:
subtitles_dir = UPLOADS_DIR / "subtitles"
subtitles_dir.mkdir(parents=True, exist_ok=True)
filename = f"{uuid4().hex}.ai.{language_code}.vtt"
(subtitles_dir / filename).write_text(content, encoding="utf-8")
return f"/uploads/subtitles/{filename}"
ensure_upload_directories()
app = FastAPI(title="Speaking Lab API")
admin_security = HTTPBasic(auto_error=False)
@app.on_event("startup")
@@ -154,14 +167,48 @@ def api_get_video(video_id: int) -> dict[str, object]:
return video
def require_admin(credentials: HTTPBasicCredentials | None = Depends(admin_security)) -> dict[str, str]:
admin_username = get_config_value("ADMIN_USERNAME")
admin_password = get_config_value("ADMIN_PASSWORD")
if not admin_username or not admin_password:
raise HTTPException(
status_code=503,
detail="未配置 ADMIN_USERNAME / ADMIN_PASSWORD,请先在 .env 中填写管理员账号密码。",
)
if credentials is None:
raise HTTPException(
status_code=401,
detail="需要管理员账号密码。",
)
username_ok = secrets.compare_digest(credentials.username, admin_username)
password_ok = secrets.compare_digest(credentials.password, admin_password)
if not username_ok or not password_ok:
raise HTTPException(
status_code=401,
detail="管理员账号或密码错误。",
)
return {"username": admin_username}
@app.get("/api/admin/session")
def api_admin_session(admin: dict[str, str] = Depends(require_admin)) -> dict[str, object]:
return {"ok": True, "username": admin["username"]}
@app.post("/api/videos")
async def api_create_video(
admin: dict[str, str] = Depends(require_admin),
title: str = Form(...),
speaker: str = Form(""),
description: str = Form(""),
tags: str = Form(""),
video_url: str = Form(""),
video_file: UploadFile | None = File(None),
cover_file: UploadFile | None = File(None),
subtitle_en: UploadFile | None = File(None),
subtitle_zh: UploadFile | None = File(None),
) -> dict[str, object]:
@@ -180,6 +227,9 @@ async def api_create_video(
if extension_for_upload(video_file) not in VIDEO_EXTENSIONS:
raise HTTPException(status_code=400, detail="视频文件格式不支持")
if cover_file is not None and extension_for_upload(cover_file) not in IMAGE_EXTENSIONS:
raise HTTPException(status_code=400, detail="封面图片格式不支持")
subtitle_uploads: list[tuple[UploadFile, str, str, str]] = []
for upload, language_code, language_name in (
(subtitle_en, "en", "English"),
@@ -200,6 +250,12 @@ async def api_create_video(
saved_paths.append(UPLOADS_DIR / "videos" / video_filename)
final_video_url = f"/uploads/videos/{video_filename}"
final_cover_url = ""
if cover_file is not None:
cover_filename = await save_binary_upload(cover_file, UPLOADS_DIR / "images")
saved_paths.append(UPLOADS_DIR / "images" / cover_filename)
final_cover_url = f"/uploads/images/{cover_filename}"
subtitles: list[dict[str, str]] = []
for upload, language_code, language_name, extension in subtitle_uploads:
subtitle_filename, subtitle_text = await save_upload(upload, UPLOADS_DIR / "subtitles")
@@ -220,6 +276,7 @@ async def api_create_video(
description=description.strip(),
tags=parse_tags(tags),
video_url=final_video_url,
cover_url=final_cover_url,
subtitles=subtitles,
)
except Exception:
@@ -230,6 +287,7 @@ async def api_create_video(
@app.patch("/api/videos/{video_id}")
async def api_update_video(
video_id: int,
admin: dict[str, str] = Depends(require_admin),
title: str = Form(...),
speaker: str = Form(""),
description: str = Form(""),
@@ -238,6 +296,7 @@ async def api_update_video(
subtitle_en_content: str | None = Form(None),
subtitle_zh_content: str | None = Form(None),
video_file: UploadFile | None = File(None),
cover_file: UploadFile | None = File(None),
subtitle_en: UploadFile | None = File(None),
subtitle_zh: UploadFile | None = File(None),
) -> dict[str, object]:
@@ -259,6 +318,9 @@ async def api_update_video(
if video_file is not None and extension_for_upload(video_file) not in VIDEO_EXTENSIONS:
raise HTTPException(status_code=400, detail="视频文件格式不支持")
if cover_file is not None and extension_for_upload(cover_file) not in IMAGE_EXTENSIONS:
raise HTTPException(status_code=400, detail="封面图片格式不支持")
subtitle_uploads: list[tuple[UploadFile, str, str, str]] = []
for upload, language_code, language_name in (
(subtitle_en, "en", "English"),
@@ -278,6 +340,12 @@ async def api_update_video(
saved_paths.append(UPLOADS_DIR / "videos" / video_filename)
final_video_url = f"/uploads/videos/{video_filename}"
final_cover_url: str | None = None
if cover_file is not None:
cover_filename = await save_binary_upload(cover_file, UPLOADS_DIR / "images")
saved_paths.append(UPLOADS_DIR / "images" / cover_filename)
final_cover_url = f"/uploads/images/{cover_filename}"
subtitles: list[dict[str, str]] = []
for upload, language_code, language_name, extension in subtitle_uploads:
subtitle_filename, subtitle_text = await save_upload(upload, UPLOADS_DIR / "subtitles")
@@ -318,6 +386,7 @@ async def api_update_video(
description=description.strip(),
tags=parse_tags(tags),
video_url=final_video_url,
cover_url=final_cover_url,
subtitles=subtitles,
)
if updated is None:
@@ -339,7 +408,7 @@ async def api_update_video(
@app.delete("/api/videos/{video_id}")
def api_delete_video(video_id: int) -> dict[str, object]:
def api_delete_video(video_id: int, admin: dict[str, str] = Depends(require_admin)) -> dict[str, object]:
deleted = delete_video(video_id)
if deleted is None:
raise HTTPException(status_code=404, detail="视频不存在")
@@ -359,15 +428,26 @@ def api_ai_status() -> dict[str, object]:
@app.post("/api/ai/test")
def api_ai_test() -> dict[str, object]:
def api_ai_test(admin: dict[str, str] = Depends(require_admin)) -> dict[str, object]:
status = get_ai_status()
if not status["configured"]:
raise HTTPException(status_code=400, detail=status["message"])
return {"ok": True, "message": "DeepSeek API 配置已读取,处理字幕时会正式调用。"}
try:
text_ai_config = load_text_ai_config()
client = DeepSeekClient(text_ai_config, timeout_seconds=text_ai_config.timeout_seconds)
client.chat_json(
"请只返回 JSON:{\"ok\":true}",
{"task": "ping", "expected": {"ok": True}},
)
except DeepSeekError as error:
raise HTTPException(status_code=400, detail=str(error)) from error
return {"ok": True, "message": "AI API 连接正常。"}
@app.post("/api/videos/{video_id}/ai/subtitles")
def api_process_video_subtitles(video_id: int) -> dict[str, object]:
def api_process_video_subtitles(video_id: int, admin: dict[str, str] = Depends(require_admin)) -> dict[str, object]:
status = get_ai_status()
if not status["configured"]:
raise HTTPException(status_code=400, detail=status["message"])
@@ -395,19 +475,17 @@ def api_process_video_subtitles(video_id: int) -> dict[str, object]:
except (DeepSeekError, ValueError) as error:
raise HTTPException(status_code=400, detail=str(error)) from error
english_file_path = save_generated_subtitle_file(str(result["subtitle_en_content"]), "en")
upsert_video_subtitle(
video_id,
language_code="en",
language_name="English",
format="vtt",
file_path=str(english_subtitle.get("filePath") or ""),
file_path=english_file_path,
content=str(result["subtitle_en_content"]),
)
chinese_subtitle = subtitles.get("zh", {})
chinese_file_path = ""
if isinstance(chinese_subtitle, dict):
chinese_file_path = str(chinese_subtitle.get("filePath") or "")
chinese_file_path = save_generated_subtitle_file(str(result["subtitle_zh_content"]), "zh")
upsert_video_subtitle(
video_id,
language_code="zh",
@@ -454,7 +532,7 @@ def save_processed_subtitles(video_id: int, subtitles: dict[str, object], result
@app.post("/api/videos/{video_id}/local-whisper/subtitles")
def api_generate_local_whisper_subtitles(video_id: int) -> dict[str, object]:
def api_generate_local_whisper_subtitles(video_id: int, admin: dict[str, str] = Depends(require_admin)) -> dict[str, object]:
video = get_video(video_id)
if video is None:
raise HTTPException(status_code=404, detail="视频不存在")
+39 -1
View File
@@ -104,7 +104,7 @@ function renderCategories() {
function renderDashboard() {
const user = getCurrentUser();
const metrics = calculateDashboardMetrics(user);
els.dashboardUser.textContent = user ? user.email : "登录后记录进度";
renderStudyPlan(metrics, user);
els.metricFilters.innerHTML = "";
getMetricItems(metrics).forEach((item) => {
@@ -128,6 +128,23 @@ function renderDashboard() {
});
}
function renderStudyPlan(metrics, user) {
const practiced = metrics.practicedLines;
const total = metrics.totalLines;
const percent = total ? Math.round((practiced / total) * 100) : 0;
const headline = practiced > 0 ? `已练 ${practiced} 句` : "准备开始";
const plan = user
? total > 0
? `今日计划:精听 10 分钟 · 完成度 ${percent}%`
: "今日计划:先添加一份素材"
: "今日计划:登录后记录学习进度";
els.dashboardUser.innerHTML = `
<strong>${headline}</strong>
<small>${plan}</small>
`;
}
function getMetricItems(metrics) {
return [
{ key: "all", label: "当前素材", value: metrics.total, hint: "持续更新中", icon: "::", tone: "blue" },
@@ -144,6 +161,15 @@ function calculateDashboardMetrics(user) {
const favoriteIds = new Set((user?.favorites || []).map(String));
const favorites = [...favoriteIds].filter((id) => loadedIds.has(id)).length;
const difficult = videos.filter((video) => getVideoProgress(user, video.id).difficultLineIndexes.length > 0).length;
const lineSummary = videos.reduce((summary, video) => {
const totalLines = getDefaultCueCount(video);
const progress = getVideoProgress(user, video.id);
const practiced = progress.practicedLineIndexes.filter((index) => index < totalLines || totalLines === 0).length;
return {
practicedLines: summary.practicedLines + practiced,
totalLines: summary.totalLines + totalLines,
};
}, { practicedLines: 0, totalLines: 0 });
return {
total: videos.length,
@@ -151,6 +177,8 @@ function calculateDashboardMetrics(user) {
unstudied: Math.max(0, videos.length - studied),
favorites,
difficult,
practicedLines: lineSummary.practicedLines,
totalLines: lineSummary.totalLines,
};
}
@@ -178,6 +206,7 @@ function createVideoCard(video) {
card.className = "home-card";
card.innerHTML = `
<div class="home-cover tone-${coverTone}">
<img class="home-cover-image" alt="">
<span class="home-cover-badge"></span>
<button class="home-favorite" type="button" aria-label="收藏素材"></button>
<strong></strong>
@@ -209,6 +238,15 @@ function createVideoCard(video) {
card.querySelector(".home-cover-badge").textContent = tags[0] || "素材";
card.querySelector(".home-cover strong").textContent = getCoverText(video.title);
const cover = card.querySelector(".home-cover");
const coverImage = card.querySelector(".home-cover-image");
const coverUrl = String(video.coverUrl || "").trim();
if (coverUrl) {
cover.classList.add("has-image");
coverImage.src = coverUrl;
coverImage.alt = `${video.title || "Speaking Lab"} 封面`;
}
card.querySelector("h3").textContent = video.title || "Untitled";
card.querySelector(".home-card-meta").textContent = video.speaker || "Unknown";
card.querySelector(".home-card-tags").append(...tags.map(createTagPill));
+7 -4
View File
@@ -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">
<link rel="stylesheet" href="./styles.css?v=20260604-plan-card">
</head>
<body class="home-page">
<header class="topbar home-topbar">
@@ -30,8 +30,11 @@
<main class="home-shell">
<aside class="home-dashboard" aria-label="学习概览">
<div class="home-dashboard-title">
<span>学习概览</span>
<strong id="homeDashboardUser">本地学习</strong>
<span>今日学习</span>
<div id="homeDashboardUser" class="home-plan-card">
<strong>准备开始</strong>
<small>今日计划:精听 10 分钟</small>
</div>
</div>
<div id="homeMetricFilters" class="home-metrics"></div>
</aside>
@@ -51,6 +54,6 @@
</section>
</main>
<script src="./home.js"></script>
<script src="./home.js?v=20260604-plan-card"></script>
</body>
</html>
+142 -40
View File
@@ -715,16 +715,23 @@ video {
}
.file-input {
min-height: 34px;
min-height: 44px;
display: flex;
align-items: center;
justify-content: center;
border: 1px dashed #aeb7c4;
border-radius: 7px;
border: 1px dashed #cbd5e1;
border-radius: 10px;
color: var(--muted);
background: var(--panel-soft);
background: #f8fafc;
cursor: pointer;
padding: 0 10px;
padding: 0 13px;
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease;
}
.file-input:hover {
border-color: #94a3b8;
color: #334155;
background: #f1f5f9;
}
.file-input span {
@@ -735,9 +742,10 @@ video {
}
.file-input.is-selected {
border-color: #5bb9a9;
color: #075e54;
background: var(--brand-soft);
border-color: #3182ce;
color: #1d4f7a;
background: #eff6ff;
box-shadow: 0 0 0 4px rgba(49, 130, 206, 0.1);
}
.file-input input {
@@ -752,7 +760,7 @@ video {
.admin-page {
min-height: 100vh;
background: var(--bg);
background: #f8fafc;
color: var(--ink);
}
@@ -773,21 +781,22 @@ video {
.admin-shell {
display: grid;
grid-template-columns: minmax(320px, 420px) minmax(0, 1fr);
gap: 16px;
padding: 16px 24px 32px;
grid-template-columns: minmax(0, 55fr) minmax(360px, 45fr);
align-items: start;
gap: 28px;
padding: 28px 36px 44px;
}
.admin-panel,
.admin-locked {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 8px;
box-shadow: var(--shadow);
background: #fff;
border: 1px solid #edf2f7;
border-radius: 12px;
box-shadow: 0 22px 55px rgba(15, 23, 42, 0.07);
}
.admin-panel {
padding: 16px;
padding: 24px;
}
.admin-form-heading {
@@ -815,13 +824,40 @@ video {
.admin-page .admin-form {
grid-template-columns: 1fr;
gap: 10px;
gap: 12px;
}
.admin-page .admin-form textarea {
grid-row: auto;
}
.admin-page .admin-form input[type="text"],
.admin-page .admin-form input[type="url"],
.admin-page .admin-form textarea {
border-color: #e2e8f0;
border-radius: 10px;
padding: 11px 13px;
background: #fff;
transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
}
.admin-page .admin-form input[type="text"],
.admin-page .admin-form input[type="url"] {
min-height: 44px;
}
.admin-page .admin-form textarea {
min-height: 104px;
}
.admin-page .admin-form input[type="text"]:focus,
.admin-page .admin-form input[type="url"]:focus,
.admin-page .admin-form textarea:focus {
border-color: #3182ce;
box-shadow: 0 0 0 4px rgba(49, 130, 206, 0.14);
background: #ffffff;
}
.admin-subtitle-editor {
display: grid;
gap: 12px;
@@ -833,12 +869,23 @@ video {
margin: 0;
}
.admin-ai-panel {
display: grid;
gap: 12px;
padding: 16px;
border: 1px solid #ddd6fe;
border-radius: 12px;
background: linear-gradient(135deg, #f5f3ff 0%, #eef2ff 100%);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.78);
}
.admin-ai-panel h3 {
color: #312e81;
font-size: 14px;
}
.admin-ai-panel p {
color: var(--muted);
color: #5b5f7a;
font-size: 13px;
line-height: 1.45;
}
@@ -949,15 +996,15 @@ video {
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
gap: 12px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--panel-soft);
padding: 14px;
border: 1px solid #e2e8f0;
border-radius: 10px;
background: #f8fafc;
}
.admin-video-item.is-editing {
border-color: var(--brand);
background: var(--brand-soft);
border-color: #93c5fd;
background: #eff6ff;
}
.admin-video-item h3 {
@@ -984,17 +1031,19 @@ video {
}
.danger-action {
border-color: #fecaca;
border-radius: 6px;
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;
}
.danger-action:hover {
border-color: #fda4af;
border-color: #fb7185;
color: #9f1239;
background: #ffe4e6;
box-shadow: 0 8px 18px rgba(190, 18, 60, 0.1);
}
.primary-link,
@@ -1003,16 +1052,24 @@ video {
align-items: center;
justify-content: center;
min-height: 36px;
border: 1px solid var(--line);
border-radius: 6px;
border: 1px solid #dbe4ee;
border-radius: 8px;
padding: 0 12px;
color: var(--ink);
background: var(--panel);
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);
@@ -1026,8 +1083,8 @@ video {
}
.secondary-action:hover {
border-color: #b8c0cc;
background: #f9fafb;
border-color: #b8c7d9;
background: #f1f5f9;
}
.home-page {
@@ -1074,7 +1131,8 @@ video {
}
.home-dashboard-title span,
.home-dashboard-title strong {
.home-plan-card strong,
.home-plan-card small {
display: block;
}
@@ -1083,12 +1141,22 @@ video {
font-size: 12px;
}
.home-dashboard-title strong {
margin-top: 4px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 15px;
.home-plan-card {
display: grid;
gap: 6px;
margin-top: 8px;
}
.home-plan-card strong {
color: #0f2742;
font-size: 22px;
line-height: 1.15;
}
.home-plan-card small {
color: #667085;
font-size: 12px;
line-height: 1.45;
}
.home-metrics {
@@ -1259,10 +1327,36 @@ video {
background: #e5eaf1;
}
.home-cover-image {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
opacity: 0;
transition: transform 220ms ease, opacity 160ms ease;
}
.home-cover.has-image::after {
content: "";
position: absolute;
inset: 0;
background: linear-gradient(180deg, rgba(15, 23, 42, 0.18), rgba(15, 23, 42, 0.46));
}
.home-cover.has-image .home-cover-image {
opacity: 1;
}
.home-card:hover .home-cover.has-image .home-cover-image {
transform: scale(1.03);
}
.home-favorite {
position: absolute;
top: 10px;
right: 10px;
z-index: 2;
min-height: 28px;
border-color: rgba(255, 255, 255, 0.38);
color: #fff;
@@ -1298,6 +1392,8 @@ video {
}
.home-cover-badge {
position: relative;
z-index: 2;
width: fit-content;
max-width: calc(100% - 86px);
overflow: hidden;
@@ -1311,10 +1407,16 @@ video {
}
.home-cover strong {
position: relative;
z-index: 2;
font-size: 34px;
line-height: 1;
}
.home-cover.has-image strong {
visibility: hidden;
}
.home-card-body {
padding: 18px;
}
+16
View File
@@ -4,7 +4,9 @@ import adminHelpers from "../admin.js";
const {
getAiSubtitleButtonState,
getLocalWhisperButtonState,
getStoredAdminCredentials,
pickVideoAfterSave,
setStoredAdminCredentials,
shouldConfirmSubtitleOverwrite,
} = adminHelpers;
@@ -47,3 +49,17 @@ assert.equal(shouldConfirmSubtitleOverwrite(null), false);
assert.equal(shouldConfirmSubtitleOverwrite({ subtitles: {} }), false);
assert.equal(shouldConfirmSubtitleOverwrite({ subtitles: { en: { content: "WEBVTT\n\nhello" } } }), true);
assert.equal(shouldConfirmSubtitleOverwrite({ subtitles: { zh: { content: "WEBVTT\n\nhello" } } }), false);
const memoryStorage = new Map();
const fakeSessionStorage = {
getItem: (key) => memoryStorage.get(key) || null,
setItem: (key, value) => memoryStorage.set(key, value),
removeItem: (key) => memoryStorage.delete(key),
};
assert.equal(getStoredAdminCredentials(fakeSessionStorage), null);
setStoredAdminCredentials(fakeSessionStorage, "owner", "secret");
assert.deepEqual(getStoredAdminCredentials(fakeSessionStorage), {
username: "owner",
password: "secret",
});
+5
View File
@@ -19,6 +19,11 @@ function run() {
title: "a-very-long-subtitle-file-name-for-practice.vtt",
isSelected: true,
});
assert.deepEqual(getFileInputState({ name: "lesson-cover.jpg" }, "封面图片"), {
text: "已选:lesson-cover.jpg",
title: "lesson-cover.jpg",
isSelected: true,
});
}
run();
+161
View File
@@ -1,11 +1,15 @@
import sys
import tempfile
from pathlib import Path
from fastapi import HTTPException
from fastapi.security import HTTPBasicCredentials
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend import ai_config, main
from backend.ai_config import DeepSeekConfig
from backend.deepseek_client import DeepSeekError
class EnvPatch:
@@ -60,6 +64,151 @@ def test_ai_test_route_rejects_missing_key(monkeypatch):
raise AssertionError("api_ai_test should reject missing DeepSeek API key")
def test_admin_credentials_require_matching_env_values(monkeypatch):
monkeypatch.setattr(main, "get_config_value", lambda key, default="": {
"ADMIN_USERNAME": "owner",
"ADMIN_PASSWORD": "secret",
}.get(key, default))
result = main.require_admin(HTTPBasicCredentials(username="owner", password="secret"))
assert result["username"] == "owner"
def test_admin_credentials_reject_wrong_password(monkeypatch):
monkeypatch.setattr(main, "get_config_value", lambda key, default="": {
"ADMIN_USERNAME": "owner",
"ADMIN_PASSWORD": "secret",
}.get(key, default))
try:
main.require_admin(HTTPBasicCredentials(username="owner", password="wrong"))
except HTTPException as error:
assert error.status_code == 401
else:
raise AssertionError("wrong admin password should be rejected")
def test_admin_credentials_reject_missing_config(monkeypatch):
monkeypatch.setattr(main, "get_config_value", lambda key, default="": "")
try:
main.require_admin(HTTPBasicCredentials(username="owner", password="secret"))
except HTTPException as error:
assert error.status_code == 503
assert "ADMIN_USERNAME" in error.detail
else:
raise AssertionError("missing admin config should be rejected")
def make_text_config() -> DeepSeekConfig:
return DeepSeekConfig(
api_key="test-key",
base_url="https://api.example.com",
model="demo-model",
audio_model="demo-audio-model",
provider="demo",
protocol="openai",
translation_batch_size=40,
timeout_seconds=120,
)
def test_ai_test_route_calls_model_client(monkeypatch):
calls = []
class FakeClient:
def __init__(self, config, timeout_seconds):
calls.append(("init", config.model, timeout_seconds))
def chat_json(self, system_prompt, user_payload):
calls.append(("chat_json", system_prompt, user_payload))
return {"ok": True}
monkeypatch.setattr(main, "get_ai_status", lambda: {"configured": True})
monkeypatch.setattr(main, "load_text_ai_config", make_text_config)
monkeypatch.setattr(main, "DeepSeekClient", FakeClient)
result = main.api_ai_test()
assert result["ok"] is True
assert calls[0] == ("init", "demo-model", 120)
assert calls[1][0] == "chat_json"
assert calls[1][2]["task"] == "ping"
def test_ai_test_route_reports_model_client_failure(monkeypatch):
class FakeClient:
def __init__(self, config, timeout_seconds):
pass
def chat_json(self, system_prompt, user_payload):
raise DeepSeekError("bad key")
monkeypatch.setattr(main, "get_ai_status", lambda: {"configured": True})
monkeypatch.setattr(main, "load_text_ai_config", make_text_config)
monkeypatch.setattr(main, "DeepSeekClient", FakeClient)
try:
main.api_ai_test()
except HTTPException as error:
assert error.status_code == 400
assert "bad key" in error.detail
else:
raise AssertionError("api_ai_test should report model client failures")
def test_ai_subtitle_route_writes_processed_vtt_files(monkeypatch):
calls = []
with tempfile.TemporaryDirectory() as temp_dir:
uploads_dir = Path(temp_dir) / "uploads"
monkeypatch.setattr(main, "UPLOADS_DIR", uploads_dir)
monkeypatch.setattr(main, "get_ai_status", lambda: {"configured": True})
monkeypatch.setattr(main, "load_text_ai_config", make_text_config)
monkeypatch.setattr(main, "DeepSeekClient", lambda config, timeout_seconds: object())
monkeypatch.setattr(
main,
"get_video",
lambda video_id: {
"id": video_id,
"subtitles": {
"en": {
"content": "WEBVTT\n\n1\n00:00:00.000 --> 00:00:01.000\nHello.",
"filePath": "/uploads/subtitles/original.vtt",
}
},
},
)
monkeypatch.setattr(
main,
"process_subtitles_with_ai",
lambda content, client, batch_size: {
"subtitle_en_content": "WEBVTT\n\n1\n00:00:00.000 --> 00:00:01.000\nHello.\n",
"subtitle_zh_content": "WEBVTT\n\n1\n00:00:00.000 --> 00:00:01.000\n你好。\n",
"report": {"duplicate_count": 0, "empty_count": 0, "translation_count": 1},
},
)
def fake_upsert_video_subtitle(video_id, **kwargs):
calls.append({"video_id": video_id, **kwargs})
monkeypatch.setattr(main, "upsert_video_subtitle", fake_upsert_video_subtitle)
result = main.api_process_video_subtitles(9)
assert result["report"]["translation_count"] == 1
assert len(calls) == 2
assert calls[0]["language_code"] == "en"
assert calls[1]["language_code"] == "zh"
assert calls[0]["file_path"].startswith("/uploads/subtitles/")
assert calls[0]["file_path"].endswith(".ai.en.vtt")
assert calls[1]["file_path"].endswith(".ai.zh.vtt")
assert (uploads_dir / calls[0]["file_path"].removeprefix("/uploads/")).read_text(encoding="utf-8").startswith("WEBVTT")
assert "你好" in (uploads_dir / calls[1]["file_path"].removeprefix("/uploads/")).read_text(encoding="utf-8")
def test_local_whisper_route_generates_only_english_subtitle(monkeypatch):
calls = []
@@ -96,6 +245,18 @@ if __name__ == "__main__":
patch.restore()
test_ai_test_route_rejects_missing_key(patch)
patch.restore()
test_admin_credentials_require_matching_env_values(patch)
patch.restore()
test_admin_credentials_reject_wrong_password(patch)
patch.restore()
test_admin_credentials_reject_missing_config(patch)
patch.restore()
test_ai_test_route_calls_model_client(patch)
patch.restore()
test_ai_test_route_reports_model_client_failure(patch)
patch.restore()
test_ai_subtitle_route_writes_processed_vtt_files(patch)
patch.restore()
test_local_whisper_route_generates_only_english_subtitle(patch)
finally:
patch.restore()
+62
View File
@@ -0,0 +1,62 @@
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend import db
class PatchDbPath:
def __init__(self, path):
self.path = path
self.original = db.DATABASE_PATH
def __enter__(self):
db.DATABASE_PATH = self.path
return self
def __exit__(self, exc_type, exc, tb):
db.DATABASE_PATH = self.original
def test_cover_url_round_trips_and_old_cover_is_cleaned():
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as temp_dir:
database_path = Path(temp_dir) / "speaking_lab.sqlite"
with PatchDbPath(database_path):
db.initialize_database()
created = db.create_video(
title="Cover demo",
speaker="Teacher",
description="",
tags=["口语"],
video_url="/uploads/videos/demo.mp4",
cover_url="/uploads/images/cover-a.jpg",
subtitles=[],
)
assert created["coverUrl"] == "/uploads/images/cover-a.jpg"
assert db.get_video(int(created["id"]))["coverUrl"] == "/uploads/images/cover-a.jpg"
updated = db.update_video(
int(created["id"]),
title="Cover demo updated",
speaker="Teacher",
description="",
tags=["口语"],
video_url=None,
cover_url="/uploads/images/cover-b.jpg",
subtitles=[],
)
assert updated["video"]["coverUrl"] == "/uploads/images/cover-b.jpg"
assert "/uploads/images/cover-a.jpg" in updated["oldUploadPaths"]
deleted = db.delete_video(int(created["id"]))
assert "/uploads/images/cover-b.jpg" in deleted["uploadPaths"]
if __name__ == "__main__":
test_cover_url_round_trips_and_old_cover_is_cleaned()