This commit is contained in:
1 parent
67dcea21d0
commit
64e7cc5d8b
14 files changed
+689
-50
No files matched your search
+155
-5
@@ -91,6 +91,12 @@ def initialize_database() -> None:
|
||||
connection.execute("ALTER TABLE users ADD COLUMN is_active INTEGER NOT NULL DEFAULT 1")
|
||||
if "last_login_at" not in user_columns:
|
||||
connection.execute("ALTER TABLE users ADD COLUMN last_login_at TEXT")
|
||||
interaction_columns = {
|
||||
row["name"]
|
||||
for row in connection.execute("PRAGMA table_info(user_interactions)").fetchall()
|
||||
}
|
||||
if "payload_json" not in interaction_columns:
|
||||
connection.execute("ALTER TABLE user_interactions ADD COLUMN payload_json TEXT")
|
||||
connection.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS activation_codes (
|
||||
@@ -219,6 +225,153 @@ def update_user_active(user_id: int, is_active: bool) -> dict[str, object] | Non
|
||||
return get_user_by_id(user_id)
|
||||
|
||||
|
||||
def normalize_interaction_indexes(value: object) -> list[int]:
|
||||
if not isinstance(value, list):
|
||||
return []
|
||||
indexes = {
|
||||
int(item)
|
||||
for item in value
|
||||
if isinstance(item, int) or (isinstance(item, str) and item.isdigit())
|
||||
}
|
||||
return sorted(index for index in indexes if index >= 0)
|
||||
|
||||
|
||||
def normalize_progress_payload(payload: dict[str, object] | None, current_time_ms: int | None = None) -> dict[str, object]:
|
||||
payload = payload if isinstance(payload, dict) else {}
|
||||
current_time = payload.get("currentTime")
|
||||
if not isinstance(current_time, (int, float)):
|
||||
current_time = (current_time_ms or 0) / 1000
|
||||
active_line_index = payload.get("activeLineIndex")
|
||||
if not isinstance(active_line_index, int) or active_line_index < 0:
|
||||
active_line_index = 0
|
||||
return {
|
||||
"currentTime": float(current_time or 0),
|
||||
"activeLineIndex": active_line_index,
|
||||
"practicedLineIndexes": normalize_interaction_indexes(payload.get("practicedLineIndexes")),
|
||||
"difficultLineIndexes": normalize_interaction_indexes(payload.get("difficultLineIndexes")),
|
||||
"updatedAt": str(payload.get("updatedAt") or ""),
|
||||
}
|
||||
|
||||
|
||||
def get_existing_video_ids(connection: sqlite3.Connection) -> set[int]:
|
||||
rows = connection.execute("SELECT id FROM videos").fetchall()
|
||||
return {int(row["id"]) for row in rows}
|
||||
|
||||
|
||||
def parse_interaction_video_id(video_id: str | int) -> int | None:
|
||||
try:
|
||||
parsed = int(video_id)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return parsed if parsed > 0 else None
|
||||
|
||||
|
||||
def get_user_learning_state(user_id: int) -> dict[str, object]:
|
||||
with get_connection() as connection:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT video_id, interaction_type, current_time_ms, payload_json, updated_at
|
||||
FROM user_interactions
|
||||
WHERE user_id = ?
|
||||
AND interaction_type IN ('favorite', 'progress')
|
||||
ORDER BY video_id ASC
|
||||
""",
|
||||
(user_id,),
|
||||
).fetchall()
|
||||
|
||||
favorites: list[str] = []
|
||||
progress: dict[str, dict[str, object]] = {}
|
||||
for row in rows:
|
||||
video_id = str(row["video_id"])
|
||||
if row["interaction_type"] == "favorite":
|
||||
favorites.append(video_id)
|
||||
continue
|
||||
|
||||
try:
|
||||
payload = json.loads(row["payload_json"] or "{}")
|
||||
except json.JSONDecodeError:
|
||||
payload = {}
|
||||
normalized = normalize_progress_payload(payload, row["current_time_ms"])
|
||||
if not normalized["updatedAt"]:
|
||||
normalized["updatedAt"] = row["updated_at"] or ""
|
||||
progress[video_id] = normalized
|
||||
|
||||
return {
|
||||
"favorites": sorted(set(favorites), key=lambda item: int(item)),
|
||||
"progress": progress,
|
||||
}
|
||||
|
||||
|
||||
def save_user_learning_state(
|
||||
user_id: int,
|
||||
*,
|
||||
favorites: list[str],
|
||||
progress: dict[str, dict[str, object]],
|
||||
) -> dict[str, object]:
|
||||
with get_connection() as connection:
|
||||
existing_video_ids = get_existing_video_ids(connection)
|
||||
favorite_ids = [
|
||||
parsed
|
||||
for item in favorites
|
||||
if (parsed := parse_interaction_video_id(item)) in existing_video_ids
|
||||
]
|
||||
progress_items = {
|
||||
parsed: normalize_progress_payload(payload)
|
||||
for item, payload in progress.items()
|
||||
if (parsed := parse_interaction_video_id(item)) in existing_video_ids
|
||||
}
|
||||
|
||||
connection.execute(
|
||||
"""
|
||||
DELETE FROM user_interactions
|
||||
WHERE user_id = ?
|
||||
AND interaction_type = 'favorite'
|
||||
""",
|
||||
(user_id,),
|
||||
)
|
||||
for video_id in sorted(set(favorite_ids)):
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO user_interactions (user_id, video_id, interaction_type)
|
||||
VALUES (?, ?, 'favorite')
|
||||
ON CONFLICT(user_id, video_id, interaction_type) DO UPDATE SET
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
""",
|
||||
(user_id, video_id),
|
||||
)
|
||||
|
||||
connection.execute(
|
||||
"""
|
||||
DELETE FROM user_interactions
|
||||
WHERE user_id = ?
|
||||
AND interaction_type = 'progress'
|
||||
""",
|
||||
(user_id,),
|
||||
)
|
||||
for video_id, payload in progress_items.items():
|
||||
current_time_ms = int(round(float(payload["currentTime"]) * 1000))
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO user_interactions (
|
||||
user_id, video_id, interaction_type, current_time_ms, payload_json
|
||||
)
|
||||
VALUES (?, ?, 'progress', ?, ?)
|
||||
ON CONFLICT(user_id, video_id, interaction_type) DO UPDATE SET
|
||||
current_time_ms = excluded.current_time_ms,
|
||||
payload_json = excluded.payload_json,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
""",
|
||||
(
|
||||
user_id,
|
||||
video_id,
|
||||
current_time_ms,
|
||||
json.dumps(payload, ensure_ascii=False),
|
||||
),
|
||||
)
|
||||
|
||||
return get_user_learning_state(user_id)
|
||||
|
||||
|
||||
def mark_user_login(user_id: int) -> None:
|
||||
with get_connection() as connection:
|
||||
connection.execute(
|
||||
@@ -264,13 +417,10 @@ def register_user_with_activation(*, username: str, password_hash: str, activati
|
||||
user_id = int(cursor.lastrowid)
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE activation_codes
|
||||
SET status = 'used',
|
||||
used_by_user_id = ?,
|
||||
used_at = CURRENT_TIMESTAMP
|
||||
DELETE FROM activation_codes
|
||||
WHERE id = ?
|
||||
""",
|
||||
(user_id, code_row["id"]),
|
||||
(code_row["id"],),
|
||||
)
|
||||
|
||||
user = get_user_by_id(user_id)
|
||||
|
||||
+40
-1
@@ -4,7 +4,7 @@ from urllib.parse import urlparse
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import Depends, FastAPI, File, Form, HTTPException, UploadFile
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, Field
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBasic, HTTPBasicCredentials, HTTPBearer
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
@@ -26,6 +26,7 @@ from .db import (
|
||||
delete_unused_activation_code,
|
||||
get_user_auth_record,
|
||||
get_user_by_id,
|
||||
get_user_learning_state,
|
||||
initialize_database,
|
||||
list_activation_codes,
|
||||
list_users,
|
||||
@@ -33,6 +34,7 @@ from .db import (
|
||||
mark_user_login,
|
||||
parse_tags,
|
||||
register_user_with_activation,
|
||||
save_user_learning_state,
|
||||
table_names,
|
||||
get_video,
|
||||
update_user_active,
|
||||
@@ -174,6 +176,19 @@ class UpdateUserStatusRequest(BaseModel):
|
||||
isActive: bool
|
||||
|
||||
|
||||
class VideoProgressPayload(BaseModel):
|
||||
currentTime: float = 0
|
||||
activeLineIndex: int = 0
|
||||
practicedLineIndexes: list[int] = Field(default_factory=list)
|
||||
difficultLineIndexes: list[int] = Field(default_factory=list)
|
||||
updatedAt: str = ""
|
||||
|
||||
|
||||
class LearningStateRequest(BaseModel):
|
||||
favorites: list[str] = Field(default_factory=list)
|
||||
progress: dict[str, VideoProgressPayload] = Field(default_factory=dict)
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
def on_startup() -> None:
|
||||
initialize_database()
|
||||
@@ -321,6 +336,30 @@ def api_auth_session(session: dict[str, object] = Depends(require_session)) -> d
|
||||
return {"ok": True, "user": session}
|
||||
|
||||
|
||||
def require_user_id(session: dict[str, object]) -> int:
|
||||
user_id = session.get("id")
|
||||
if not isinstance(user_id, int) or user_id <= 0:
|
||||
raise HTTPException(status_code=403, detail="闇€瑕佹櫘閫氱敤鎴风櫥褰曘€?")
|
||||
return user_id
|
||||
|
||||
|
||||
@app.get("/api/me/progress")
|
||||
def api_get_my_progress(session: dict[str, object] = Depends(require_session)) -> dict[str, object]:
|
||||
return get_user_learning_state(require_user_id(session))
|
||||
|
||||
|
||||
@app.put("/api/me/progress")
|
||||
def api_save_my_progress(
|
||||
request: LearningStateRequest,
|
||||
session: dict[str, object] = Depends(require_session),
|
||||
) -> dict[str, object]:
|
||||
return save_user_learning_state(
|
||||
require_user_id(session),
|
||||
favorites=request.favorites,
|
||||
progress={video_id: payload.dict() for video_id, payload in request.progress.items()},
|
||||
)
|
||||
|
||||
|
||||
def require_admin(
|
||||
credentials: HTTPBasicCredentials | None = Depends(admin_security),
|
||||
bearer: HTTPAuthorizationCredentials | None = Depends(bearer_security),
|
||||
|
||||
Reference in new issue
Block a user