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)
|
||||
|
||||
Reference in new issue
Block a user