# 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()`:
```python
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:
```python
delete_video,
```
- [ ] **Step 3: Add safe upload path resolution in `backend/main.py`**
Add this helper after `cleanup_saved_files()`:
```python
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()`:
```python
@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:
```powershell
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:
```html
素材0
```
with:
```html
素材
0
```
- [ ] **Step 2: Remove embedded admin dock**
Delete the entire `` block from `index.html`.
- [ ] **Step 3: Update element references in `app.js`**
In the `els` object:
Add:
```javascript
adminEntryBtn: document.querySelector("#adminEntryBtn"),
```
Remove these entries:
```javascript
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:
```javascript
els.adminForm.addEventListener("submit", addVideoFromAdmin);
els.updateCurrentBtn.addEventListener("click", updateCurrentVideoInfo);
```
Add:
```javascript
els.adminEntryBtn.addEventListener("click", () => {
window.location.href = "admin.html";
});
```
- [ ] **Step 5: Replace `renderAdminAccess()` in `app.js`**
Replace the existing function with:
```javascript
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:
```javascript
async function addVideoFromAdmin(event) { ... }
function fillAdminForm(video) { ... }
function updateCurrentVideoInfo() { ... }
```
Remove the call to `fillAdminForm(video);` from `selectVideo()`.
- [ ] **Step 7: Run frontend syntax check**
Run:
```powershell
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:
```html
Speaking Lab 后台管理