Files
speaking-practice/docs/superpowers/plans/2026-06-01-speaking-lab-admin-page.md
T
2026-06-03 00:34:42 +08:00

22 KiB
Raw Blame History

Speaking Lab Admin Page 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: Move material management to a dedicated admin page with add and delete support, and show a small study-page admin entry only for local admin users.

Architecture: Keep the current local prototype auth model in localStorage. Add backend deletion helpers and a DELETE /api/videos/{video_id} endpoint, remove embedded admin UI from the study page, and add a separate static admin.html + admin.js page that uses the existing create endpoint plus the new delete endpoint.

Tech Stack: FastAPI, Python sqlite3, vanilla JavaScript, localStorage, local filesystem uploads.


File Structure

  • Modify F:\ooo\speaking-practice-local\backend\db.py: add a helper to collect uploaded file paths and delete a video row.
  • Modify F:\ooo\speaking-practice-local\backend\main.py: add safe uploaded-file deletion and DELETE /api/videos/{video_id}.
  • Modify F:\ooo\speaking-practice-local\index.html: remove embedded admin dock and add a hidden admin button beside the material rail heading.
  • Modify F:\ooo\speaking-practice-local\app.js: remove study-page admin form logic, show/hide the admin button for admins, and navigate to admin.html.
  • Add F:\ooo\speaking-practice-local\admin.html: standalone admin page.
  • Add F:\ooo\speaking-practice-local\admin.js: admin-only local gate, add material, list materials, delete material.
  • Modify F:\ooo\speaking-practice-local\styles.css: add styles for the rail admin button and admin page.
  • Modify F:\ooo\speaking-practice-local\README.md: document the dedicated admin page.

The project is not a git repository. Do not initialize git or commit during implementation.


Task 1: Add Backend Delete Support

Files:

  • Modify: F:\ooo\speaking-practice-local\backend\db.py

  • Modify: F:\ooo\speaking-practice-local\backend\main.py

  • Step 1: Add database helper in backend/db.py

Add this function after get_video():

def delete_video(video_id: int) -> dict[str, object] | None:
    with get_connection() as connection:
        video_row = connection.execute(
            """
            SELECT id, video_url
            FROM videos
            WHERE id = ?
            """,
            (video_id,),
        ).fetchone()
        if video_row is None:
            return None

        subtitle_rows = connection.execute(
            """
            SELECT file_path
            FROM subtitles
            WHERE video_id = ?
            """,
            (video_id,),
        ).fetchall()

        upload_paths = []
        if video_row["video_url"]:
            upload_paths.append(video_row["video_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,))

    return {
        "deletedVideoId": video_id,
        "uploadPaths": upload_paths,
    }
  • Step 2: Import delete_video in backend/main.py

Update the .db import list to include:

    delete_video,
  • Step 3: Add safe upload path resolution in backend/main.py

Add this helper after cleanup_saved_files():

def upload_url_to_path(value: str) -> Path | None:
    if not value.startswith("/uploads/"):
        return None

    relative = value.removeprefix("/uploads/").replace("/", "\\")
    candidate = (UPLOADS_DIR / relative).resolve()
    uploads_root = UPLOADS_DIR.resolve()

    try:
        candidate.relative_to(uploads_root)
    except ValueError:
        return None

    return candidate
  • Step 4: Add delete endpoint in backend/main.py

Add this after api_create_video():

@app.delete("/api/videos/{video_id}")
def api_delete_video(video_id: int) -> dict[str, object]:
    deleted = delete_video(video_id)
    if deleted is None:
        raise HTTPException(status_code=404, detail="视频不存在")

    warnings: list[str] = []
    for upload_url in deleted["uploadPaths"]:
        path = upload_url_to_path(str(upload_url))
        if path is None:
            continue
        try:
            path.unlink(missing_ok=True)
        except OSError:
            warnings.append(f"无法删除文件: {path}")

    return {
        "ok": True,
        "deletedVideoId": deleted["deletedVideoId"],
        "warnings": warnings,
    }
  • Step 5: Run backend checks

Run:

python -m py_compile backend\main.py backend\db.py
python -c "from backend.main import app; print([route.path for route in app.routes if route.path.startswith('/api/videos')])"

Expected:

  • compile command exits with no output
  • output includes /api/videos/{video_id} for both GET and DELETE route registrations

Task 2: Clean Study Page And Add Admin Entry

Files:

  • Modify: F:\ooo\speaking-practice-local\index.html

  • Modify: F:\ooo\speaking-practice-local\app.js

  • Step 1: Add admin button beside material heading

In index.html, replace:

<div class="rail-heading">
  <strong>素材</strong>
  <span id="videoCount">0</span>
</div>

with:

<div class="rail-heading">
  <div class="rail-title">
    <strong>素材</strong>
    <button id="adminEntryBtn" class="icon-button admin-entry" type="button" title="后台管理" hidden>管理</button>
  </div>
  <span id="videoCount">0</span>
</div>
  • Step 2: Remove embedded admin dock

Delete the entire <aside class="admin-dock">...</aside> block from index.html.

  • Step 3: Update element references in app.js

In the els object:

Add:

  adminEntryBtn: document.querySelector("#adminEntryBtn"),

Remove these entries:

  adminForm: document.querySelector("#adminForm"),
  adminTitle: document.querySelector("#adminTitle"),
  adminSpeaker: document.querySelector("#adminSpeaker"),
  adminDescription: document.querySelector("#adminDescription"),
  adminTags: document.querySelector("#adminTags"),
  adminVideoFile: document.querySelector("#adminVideoFile"),
  adminVideoUrl: document.querySelector("#adminVideoUrl"),
  adminSubtitleEn: document.querySelector("#adminSubtitleEn"),
  adminSubtitleZh: document.querySelector("#adminSubtitleZh"),
  updateCurrentBtn: document.querySelector("#updateCurrentBtn"),
  adminStatus: document.querySelector("#adminStatus"),
  • Step 4: Update events in app.js

Remove:

  els.adminForm.addEventListener("submit", addVideoFromAdmin);
  els.updateCurrentBtn.addEventListener("click", updateCurrentVideoInfo);

Add:

  els.adminEntryBtn.addEventListener("click", () => {
    window.location.href = "admin.html";
  });
  • Step 5: Replace renderAdminAccess() in app.js

Replace the existing function with:

function renderAdminAccess() {
  const user = getCurrentUser();
  const isAdmin = user?.role === "admin";
  els.adminEntryBtn.hidden = !isAdmin;
}
  • Step 6: Remove study-page admin functions in app.js

Delete these functions completely:

async function addVideoFromAdmin(event) { ... }
function fillAdminForm(video) { ... }
function updateCurrentVideoInfo() { ... }

Remove the call to fillAdminForm(video); from selectVideo().

  • Step 7: Run frontend syntax check

Run:

node --check app.js

Expected: no output, exit code 0.


Task 3: Add Standalone Admin Page

Files:

  • Add: F:\ooo\speaking-practice-local\admin.html

  • Add: F:\ooo\speaking-practice-local\admin.js

  • Step 1: Create admin.html

Create the file:

<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Speaking Lab 后台管理</title>
    <link rel="stylesheet" href="./styles.css">
  </head>
  <body class="admin-page">
    <header class="admin-topbar">
      <div>
        <h1>后台管理</h1>
        <p id="adminIdentity">请先使用管理员账号登录。</p>
      </div>
      <a class="secondary-action" href="./index.html">返回学习页</a>
    </header>

    <main id="adminLocked" class="admin-locked" hidden>
      <h2>需要管理员账号</h2>
      <p>请返回学习页,使用邮箱包含 admin 的账号登录后再进入后台。</p>
      <a class="primary-link" href="./index.html">去登录</a>
    </main>

    <main id="adminContent" class="admin-shell" hidden>
      <section class="admin-panel">
        <h2>添加素材</h2>
        <form id="adminCreateForm" class="admin-create-form">
          <input id="adminTitle" type="text" placeholder="视频标题" required>
          <input id="adminSpeaker" type="text" placeholder="演讲者 / 片段来源">
          <textarea id="adminDescription" placeholder="简介"></textarea>
          <input id="adminTags" type="text" placeholder="标签,用逗号分隔,如 科技,设计">
          <label class="file-input">
            <span>选择视频文件</span>
            <input id="adminVideoFile" type="file" accept="video/*">
          </label>
          <input id="adminVideoUrl" type="url" placeholder="或填写视频 / HLS 地址">
          <label class="file-input">
            <span>英文字幕 .srt/.vtt</span>
            <input id="adminSubtitleEn" type="file" accept=".srt,.vtt,text/vtt,text/plain">
          </label>
          <label class="file-input">
            <span>中文字幕 .srt/.vtt</span>
            <input id="adminSubtitleZh" type="file" accept=".srt,.vtt,text/vtt,text/plain">
          </label>
          <button type="submit">添加到视频库</button>
        </form>
      </section>

      <section class="admin-panel">
        <div class="admin-list-heading">
          <h2>素材列表</h2>
          <button id="refreshVideosBtn" class="secondary-action" type="button">刷新</button>
        </div>
        <div id="adminMessage" class="admin-message" hidden></div>
        <div id="adminVideoList" class="admin-video-list"></div>
      </section>
    </main>

    <script src="./admin.js"></script>
  </body>
</html>
  • Step 2: Create admin.js

Create the file:

const STORAGE_KEY = "speaking-lab-state-v1";

const els = {
  identity: document.querySelector("#adminIdentity"),
  locked: document.querySelector("#adminLocked"),
  content: document.querySelector("#adminContent"),
  form: document.querySelector("#adminCreateForm"),
  title: document.querySelector("#adminTitle"),
  speaker: document.querySelector("#adminSpeaker"),
  description: document.querySelector("#adminDescription"),
  tags: document.querySelector("#adminTags"),
  videoFile: document.querySelector("#adminVideoFile"),
  videoUrl: document.querySelector("#adminVideoUrl"),
  subtitleEn: document.querySelector("#adminSubtitleEn"),
  subtitleZh: document.querySelector("#adminSubtitleZh"),
  refreshBtn: document.querySelector("#refreshVideosBtn"),
  message: document.querySelector("#adminMessage"),
  videoList: document.querySelector("#adminVideoList"),
};

let videos = [];

initializeAdmin();

function loadState() {
  try {
    const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
    return {
      users: Array.isArray(saved.users) ? saved.users : [],
      currentUserId: saved.currentUserId || null,
    };
  } catch {
    return { users: [], currentUserId: null };
  }
}

function getCurrentUser() {
  const state = loadState();
  return state.users.find((user) => user.id === state.currentUserId) || null;
}

function isAdmin(user) {
  return user?.role === "admin" || user?.email?.includes("admin");
}

async function apiRequest(path, options = {}) {
  const response = await fetch(path, options);
  if (!response.ok) {
    let message = "请求失败,请重试。";
    try {
      const payload = await response.json();
      message = payload.detail || message;
    } catch {
      message = response.statusText || message;
    }
    throw new Error(message);
  }
  return response.json();
}

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.form.addEventListener("submit", addVideo);
  els.refreshBtn.addEventListener("click", loadVideos);
  loadVideos();
}

function showMessage(text, isError = false) {
  els.message.hidden = false;
  els.message.textContent = text;
  els.message.classList.toggle("error", isError);
}

function clearMessage() {
  els.message.hidden = true;
  els.message.textContent = "";
  els.message.classList.remove("error");
}

async function loadVideos() {
  clearMessage();
  try {
    videos = await apiRequest("/api/videos");
    renderVideos();
  } catch (error) {
    showMessage(error.message || "素材加载失败。", true);
  }
}

function renderVideos() {
  els.videoList.innerHTML = "";
  if (!videos.length) {
    els.videoList.innerHTML = `<div class="empty-state">还没有素材。</div>`;
    return;
  }

  const fragment = document.createDocumentFragment();
  videos.forEach((video) => {
    const item = document.createElement("article");
    item.className = "admin-video-item";
    const subtitleCodes = Object.keys(video.subtitles || {});
    item.innerHTML = `
      <div>
        <h3></h3>
        <p class="admin-video-meta"></p>
        <p class="admin-video-subtitles"></p>
      </div>
      <button class="danger-action" type="button">删除</button>
    `;
    item.querySelector("h3").textContent = video.title || "Untitled";
    item.querySelector(".admin-video-meta").textContent = [
      video.speaker || "Unknown",
      Array.isArray(video.tags) ? video.tags.join(" / ") : "未分类",
      video.sourceType === "url" ? "链接" : "本地文件",
    ].join(" · ");
    item.querySelector(".admin-video-subtitles").textContent = subtitleCodes.length
      ? `字幕:${subtitleCodes.join(" / ")}`
      : "字幕:无";
    item.querySelector(".danger-action").addEventListener("click", () => deleteVideo(video));
    fragment.appendChild(item);
  });
  els.videoList.appendChild(fragment);
}

async function addVideo(event) {
  event.preventDefault();
  clearMessage();

  const title = els.title.value.trim();
  if (!title) {
    showMessage("标题不能为空", true);
    return;
  }

  const submitButton = els.form.querySelector('button[type="submit"]');
  const previousText = submitButton.textContent;
  submitButton.disabled = true;
  submitButton.textContent = "正在添加...";

  const formData = new FormData();
  formData.append("title", title);
  formData.append("speaker", els.speaker.value.trim());
  formData.append("description", els.description.value.trim());
  formData.append("tags", els.tags.value.trim());
  formData.append("video_url", els.videoUrl.value.trim());

  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]);

  try {
    await apiRequest("/api/videos", {
      method: "POST",
      body: formData,
    });
    els.form.reset();
    showMessage("素材已添加。");
    await loadVideos();
  } catch (error) {
    showMessage(error.message || "添加素材失败。", true);
  } finally {
    submitButton.disabled = false;
    submitButton.textContent = previousText;
  }
}

async function deleteVideo(video) {
  const confirmed = window.confirm("确定删除这个素材吗?此操作不可恢复。");
  if (!confirmed) return;

  clearMessage();
  try {
    const result = await apiRequest(`/api/videos/${video.id}`, {
      method: "DELETE",
    });
    videos = videos.filter((item) => String(item.id) !== String(video.id));
    renderVideos();
    const warningText = Array.isArray(result.warnings) && result.warnings.length
      ? `素材已删除,但有文件未能删除:${result.warnings.join(";")}`
      : "素材已删除。";
    showMessage(warningText, Boolean(result.warnings?.length));
  } catch (error) {
    showMessage(error.message || "删除素材失败。", true);
  }
}
  • Step 3: Run admin script syntax check

Run:

node --check admin.js

Expected: no output, exit code 0.


Task 4: Add Styles For Admin Entry And Page

Files:

  • Modify: F:\ooo\speaking-practice-local\styles.css

  • Step 1: Add rail admin button styles

Add these styles near the existing rail/list styles:

.rail-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.icon-button.admin-entry {
  border: 1px solid var(--border);
  background: var(--surface);
  color: var(--muted);
  border-radius: 6px;
  padding: 4px 8px;
  font-size: 12px;
  cursor: pointer;
}

.icon-button.admin-entry:hover {
  color: var(--text);
  border-color: var(--accent);
}
  • Step 2: Add admin page styles

Append:

.admin-page {
  min-height: 100vh;
  background: var(--bg);
  color: var(--text);
}

.admin-topbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  padding: 18px 24px;
  border-bottom: 1px solid var(--border);
  background: var(--surface);
}

.admin-topbar h1 {
  margin: 0;
  font-size: 22px;
}

.admin-topbar p {
  margin: 4px 0 0;
  color: var(--muted);
}

.admin-shell {
  display: grid;
  grid-template-columns: minmax(320px, 420px) minmax(0, 1fr);
  gap: 16px;
  padding: 16px 24px 32px;
}

.admin-panel,
.admin-locked {
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 16px;
}

.admin-locked {
  max-width: 520px;
  margin: 48px auto;
}

.admin-create-form {
  display: grid;
  gap: 10px;
}

.admin-create-form input,
.admin-create-form textarea {
  width: 100%;
}

.admin-list-heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.admin-message {
  margin: 12px 0;
  padding: 10px 12px;
  border-radius: 6px;
  background: #ecfdf5;
  color: #047857;
}

.admin-message.error {
  background: #fef2f2;
  color: #b91c1c;
}

.admin-video-list {
  display: grid;
  gap: 10px;
  margin-top: 12px;
}

.admin-video-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 12px;
  background: var(--bg);
}

.admin-video-item h3 {
  margin: 0 0 6px;
  font-size: 16px;
}

.admin-video-meta,
.admin-video-subtitles {
  margin: 0;
  color: var(--muted);
  font-size: 13px;
}

.danger-action {
  border: 1px solid #fecaca;
  background: #fff1f2;
  color: #be123c;
  border-radius: 6px;
  padding: 8px 12px;
  cursor: pointer;
}

.primary-link,
.secondary-action {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-height: 36px;
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 0 12px;
  color: var(--text);
  text-decoration: none;
  background: var(--surface);
}

@media (max-width: 900px) {
  .admin-shell {
    grid-template-columns: 1fr;
    padding: 12px;
  }
}
  • Step 3: Run syntax smoke checks

Run:

node --check app.js
node --check admin.js

Expected: both pass with no output.


Task 5: Document And Verify

Files:

  • Modify: F:\ooo\speaking-practice-local\README.md

  • Step 1: Update README

Add this section:

## Admin Page

Content management is handled on a separate local admin page:

```text
http://127.0.0.1:8000/admin.html
```

In this prototype, an admin is any local user whose email contains `admin`.
After logging in as an admin on the study page, a small `管理` button appears
beside the `素材` heading. The admin page supports adding and deleting
materials. Editing and subtitle replacement are planned for later.
```
  • Step 2: Run static checks

Run:

python -m py_compile backend\main.py backend\db.py
node --check app.js
node --check admin.js

Expected: no output, exit code 0.

  • Step 3: Start the dev server

Run:

python -m uvicorn backend.main:app --reload --host 127.0.0.1 --port 8000

Expected output includes Uvicorn running on http://127.0.0.1:8000.

  • Step 4: Verify backend delete endpoint

Create a temporary URL video through the API, then delete it:

$created = curl.exe -s -X POST http://127.0.0.1:8000/api/videos `
  -F "title=Delete Smoke Test" `
  -F "video_url=https://example.com/delete-smoke.mp4" | ConvertFrom-Json

Invoke-RestMethod -Method Delete "http://127.0.0.1:8000/api/videos/$($created.id)"

Expected delete response:

ok deletedVideoId warnings
-- -------------- --------
True <id>          {}
  • Step 5: Verify pages

Open:

http://127.0.0.1:8000
http://127.0.0.1:8000/admin.html
http://127.0.0.1:8000/docs

Expected:

  • Normal user does not see the 管理 button beside 素材.
  • Admin user sees the 管理 button.
  • admin.html shows locked state when not logged in as admin.
  • admin.html shows add form and material list when logged in as admin.
  • /docs includes DELETE /api/videos/{video_id}.

Self-Review

Spec coverage:

  • Dedicated admin page: Task 3.
  • Admin-only study-page entry: Task 2.
  • Remove embedded admin dock: Task 2.
  • Add material from admin page: Task 3.
  • Delete material from admin page: Tasks 1 and 3.
  • Safe local file deletion: Task 1.
  • Documentation and verification: Task 5.

Placeholder scan:

  • No placeholder markers or unspecified implementation steps.

Type consistency:

  • Backend delete response uses deletedVideoId and warnings.
  • Admin frontend reads video.id, video.sourceType, video.subtitles, and the existing backend list shape.
  • Local admin rule reuses speaking-lab-state-v1.