From f7859783d3fb442b0f3fc571ce197f91aeea0a90 Mon Sep 17 00:00:00 2001 From: Drobysh Date: Sat, 26 Sep 2026 16:46:29 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=84=20Lectures:=20backend=20=D0=B4?= =?UTF-8?q?=D0=BB=D1=8F=20=D1=80=D0=B0=D0=B7=D0=B4=D0=B5=D0=BB=D0=B0=20?= =?UTF-8?q?=C2=AB=D0=9E=D0=B1=D1=83=D1=87=D0=B5=D0=BD=D0=B8=D0=B5=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Новое: - Таблица lectures (PDF/HTML, привязка к уровню, скачивание) - routers/lectures.py — 6 эндпоинтов: - GET /learning/lectures?level=A1 — список - GET /learning/lecture/{id} — метаданные - GET /learning/lecture/{id}/download — скачать файл - POST /admin/lectures/upload — загрузить (multipart) - PUT /admin/lectures/{id} — редактировать - DELETE /admin/lectures/{id} — удалить - Регистрация роутера в main.py - Миграция в database.py::init_db() Проверено: GET /learning/lectures → 200, {level:A1, lectures:[]} --- database.py | 30 ++++ main.py | 2 + routers/lectures.py | 338 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 370 insertions(+) create mode 100644 routers/lectures.py diff --git a/database.py b/database.py index c9ebb77..1010d22 100644 --- a/database.py +++ b/database.py @@ -830,6 +830,36 @@ async def init_db(): ) """) + # ============ lectures — лекции (архивы) ============ + await conn.execute(""" + CREATE TABLE IF NOT EXISTS lectures ( + id BIGSERIAL PRIMARY KEY, + level_code VARCHAR(10) NOT NULL, + title_pl TEXT NOT NULL, + title_ru TEXT, + title_uk TEXT, + title_en TEXT, + description_pl TEXT, + description_ru TEXT, + description_uk TEXT, + description_en TEXT, + file_path TEXT NOT NULL, + file_type VARCHAR(20) NOT NULL, + file_size_bytes INT, + order_number INT NOT NULL DEFAULT 0, + is_active BOOLEAN DEFAULT TRUE, + created_at TIMESTAMP DEFAULT NOW(), + edited_at TIMESTAMP + ) + """) + + await conn.execute(""" + CREATE INDEX IF NOT EXISTS idx_lectures_level + ON lectures(level_code, order_number) + """) + + logger.info("Table lectures initialized") + # ============ daily_phrases — фраза дня ============ await conn.execute(""" CREATE TABLE IF NOT EXISTS daily_phrases ( diff --git a/main.py b/main.py index b7efe3e..7cf1d94 100644 --- a/main.py +++ b/main.py @@ -14,6 +14,7 @@ from fastapi.staticfiles import StaticFiles from config import FRONTEND_ORIGIN, UPLOADS_DIR, CF_IPS from database import init_db from routers import users, game, hints, leaderboard, sentences, achievements, wordquiz, bubblewords, pronunciation, assistant, learning, tts, typing, teacher, support, admin, feed, admin_content +from routers import lectures from routers.sentences import init_sentences from routers.achievements import init_achievements from routers.learning_data import init_learning_data @@ -359,6 +360,7 @@ app.include_router(support.router) app.include_router(admin.router) app.include_router(feed.router) app.include_router(admin_content.router) +app.include_router(lectures.router) # ============ Базовые эндпоинты ============ diff --git a/routers/lectures.py b/routers/lectures.py new file mode 100644 index 0000000..fb3f149 --- /dev/null +++ b/routers/lectures.py @@ -0,0 +1,338 @@ +""" +Lectures Router — лекции (архивы) для раздела «Обучение». + +Лекции — это файлы (PDF, HTML, DOCX), которые: +- Привязаны к уровню языка (A1, A2, ...). +- Видны только для выбранного уровня. +- Можно открыть (PDF viewer / HTML render). +- Можно скачать (PDF). + +Публичные эндпоинты: +- GET /learning/lectures?level=A1 — список лекций уровня +- GET /learning/lecture/{id} — метаданные лекции +- GET /learning/lecture/{id}/download — скачать файл + +Админские эндпоинты: +- POST /admin/lectures/upload — загрузить файл (multipart) +- PUT /admin/lectures/{id} — редактировать метаданные +- DELETE /admin/lectures/{id} — удалить +""" +import logging +import uuid +from pathlib import Path +from typing import Optional + +from fastapi import APIRouter, Request, HTTPException, UploadFile, File, Form +from fastapi.responses import FileResponse + +from auth import require_auth +from database import get_pool +from config import ADMIN_IDS, UPLOADS_DIR + +logger = logging.getLogger(__name__) + +router = APIRouter(tags=["lectures"]) + +LEVELS = ["A1", "A2", "B1", "B2", "C1", "C2"] +ALLOWED_FILE_TYPES = {"pdf", "html", "docx", "txt", "md"} +MAX_FILE_SIZE_BYTES = 20 * 1024 * 1024 # 20 MB + + +def _require_admin(telegram_id: int) -> None: + if telegram_id not in ADMIN_IDS: + raise HTTPException(403, "Access denied") + + +def _ext_from_filename(filename: str) -> str: + """Возвращает расширение файла в нижнем регистре без точки.""" + return filename.rsplit(".", 1)[-1].lower() if "." in filename else "" + + +# ============ ПУБЛИЧНЫЕ ============ + +@router.get("/learning/lectures") +async def get_lectures(request: Request, level: Optional[str] = None): + """Список лекций для выбранного уровня. + + Если level не передан — берём из current_level пользователя. + """ + telegram_id, _ = await require_auth(request) + + pool = await get_pool() + async with pool.acquire() as conn: + # Если level не передан — из профиля пользователя + if not level or level not in LEVELS: + level = await conn.fetchval( + "SELECT current_level FROM users WHERE telegram_id = $1", + telegram_id, + ) or "A1" + if level not in LEVELS: + level = "A1" + + rows = await conn.fetch(""" + SELECT id, level_code, title_pl, title_ru, title_uk, title_en, + description_pl, description_ru, description_uk, description_en, + file_type, file_size_bytes, order_number + FROM lectures + WHERE level_code = $1 AND is_active = TRUE + ORDER BY order_number ASC, id ASC + """, level) + + return { + "level": level, + "lectures": [ + { + "id": r["id"], + "title_pl": r["title_pl"], + "title_ru": r["title_ru"], + "title_uk": r["title_uk"], + "title_en": r["title_en"], + "description_pl": r["description_pl"] or "", + "description_ru": r["description_ru"] or "", + "description_uk": r["description_uk"] or "", + "description_en": r["description_en"] or "", + "file_type": r["file_type"], + "file_size_kb": round((r["file_size_bytes"] or 0) / 1024, 1), + "order_number": r["order_number"], + } + for r in rows + ], + } + + +@router.get("/learning/lecture/{lecture_id}") +async def get_lecture(request: Request, lecture_id: int): + """Метаданные одной лекции.""" + telegram_id, _ = await require_auth(request) + + pool = await get_pool() + async with pool.acquire() as conn: + row = await conn.fetchrow(""" + SELECT id, level_code, title_pl, title_ru, title_uk, title_en, + description_pl, description_ru, description_uk, description_en, + file_path, file_type, file_size_bytes, order_number + FROM lectures + WHERE id = $1 AND is_active = TRUE + """, lecture_id) + + if not row: + raise HTTPException(404, "Lecture not found") + + return { + "id": row["id"], + "level_code": row["level_code"], + "title_pl": row["title_pl"], + "title_ru": row["title_ru"], + "title_uk": row["title_uk"], + "title_en": row["title_en"], + "description_pl": row["description_pl"] or "", + "description_ru": row["description_ru"] or "", + "description_uk": row["description_uk"] or "", + "description_en": row["description_en"] or "", + "file_type": row["file_type"], + "file_size_kb": round((row["file_size_bytes"] or 0) / 1024, 1), + "file_url": row["file_path"], # "/uploads/lectures/..." + "order_number": row["order_number"], + } + + +@router.get("/learning/lecture/{lecture_id}/download") +async def download_lecture(request: Request, lecture_id: int): + """Скачать файл лекции.""" + await require_auth(request) + + pool = await get_pool() + async with pool.acquire() as conn: + row = await conn.fetchrow(""" + SELECT file_path, file_type, title_pl + FROM lectures + WHERE id = $1 AND is_active = TRUE + """, lecture_id) + + if not row: + raise HTTPException(404, "Lecture not found") + + # file_path = "/uploads/lectures/xxx.pdf" + # На диске: UPLOADS_DIR / "lectures" / "xxx.pdf" + rel_path = row["file_path"].replace("/uploads/", "", 1).lstrip("/") + abs_path = Path(UPLOADS_DIR) / rel_path + + if not abs_path.exists(): + raise HTTPException(404, "File not found on disk") + + # Формируем имя для скачивания + ext = row["file_type"] + safe_title = (row["title_pl"] or "lecture").replace(" ", "_")[:50] + download_name = f"{safe_title}.{ext}" + + return FileResponse( + path=str(abs_path), + filename=download_name, + media_type="application/octet-stream", + ) + + +# ============ АДМИНСКИЕ ============ + +@router.post("/admin/lectures/upload") +async def admin_upload_lecture( + request: Request, + level_code: str = Form(...), + title_pl: str = Form(...), + title_ru: str = Form(""), + title_uk: str = Form(""), + title_en: str = Form(""), + description_pl: str = Form(""), + description_ru: str = Form(""), + description_uk: str = Form(""), + description_en: str = Form(""), + order_number: int = Form(0), + file: UploadFile = File(...), +): + """Загрузить лекцию (файл + метаданные).""" + telegram_id, _ = await require_auth(request) + _require_admin(telegram_id) + + if level_code not in LEVELS: + raise HTTPException(400, f"Invalid level_code: {level_code}") + + if not title_pl.strip(): + raise HTTPException(400, "title_pl is required") + + # Проверяем расширение + ext = _ext_from_filename(file.filename or "") + if ext not in ALLOWED_FILE_TYPES: + raise HTTPException( + 400, + f"Invalid file type: {ext}. Allowed: {sorted(ALLOWED_FILE_TYPES)}", + ) + + # Читаем файл + content = await file.read() + if len(content) == 0: + raise HTTPException(400, "Empty file") + + if len(content) > MAX_FILE_SIZE_BYTES: + raise HTTPException( + 400, + f"File too large: {len(content)} bytes. Max: {MAX_FILE_SIZE_BYTES}", + ) + + # Сохраняем на диск + lectures_dir = Path(UPLOADS_DIR) / "lectures" + lectures_dir.mkdir(parents=True, exist_ok=True) + + filename = f"{level_code}_{uuid.uuid4().hex[:12]}.{ext}" + file_path_disk = lectures_dir / filename + file_path_disk.write_bytes(content) + + public_path = f"/uploads/lectures/{filename}" + + pool = await get_pool() + async with pool.acquire() as conn: + row = await conn.fetchrow(""" + INSERT INTO lectures + (level_code, title_pl, title_ru, title_uk, title_en, + description_pl, description_ru, description_uk, description_en, + file_path, file_type, file_size_bytes, order_number, is_active) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, TRUE) + RETURNING id + """, + level_code, + title_pl.strip(), + title_ru.strip() or None, + title_uk.strip() or None, + title_en.strip() or None, + description_pl.strip() or None, + description_ru.strip() or None, + description_uk.strip() or None, + description_en.strip() or None, + public_path, + ext, + len(content), + order_number, + ) + + logger.info(f"Lecture uploaded: #{row['id']} by admin {telegram_id}") + + return {"status": "ok", "lecture_id": row["id"]} + + +@router.put("/admin/lectures/{lecture_id}") +async def admin_update_lecture(request: Request, lecture_id: int): + """Обновить метаданные лекции (без замены файла).""" + telegram_id, _ = await require_auth(request) + _require_admin(telegram_id) + + body = await request.json() + + pool = await get_pool() + async with pool.acquire() as conn: + existing = await conn.fetchrow( + "SELECT id FROM lectures WHERE id = $1", lecture_id + ) + if not existing: + raise HTTPException(404, "Lecture not found") + + # Обновляем только переданные поля + await conn.execute(""" + UPDATE lectures + SET title_pl = COALESCE($1, title_pl), + title_ru = COALESCE($2, title_ru), + title_uk = COALESCE($3, title_uk), + title_en = COALESCE($4, title_en), + description_pl = COALESCE($5, description_pl), + description_ru = COALESCE($6, description_ru), + description_uk = COALESCE($7, description_uk), + description_en = COALESCE($8, description_en), + order_number = COALESCE($9, order_number), + is_active = COALESCE($10, is_active), + edited_at = NOW() + WHERE id = $11 + """, + body.get("title_pl"), + body.get("title_ru"), + body.get("title_uk"), + body.get("title_en"), + body.get("description_pl"), + body.get("description_ru"), + body.get("description_uk"), + body.get("description_en"), + body.get("order_number"), + body.get("is_active"), + lecture_id, + ) + + logger.info(f"Lecture #{lecture_id} updated by admin {telegram_id}") + + return {"status": "ok", "lecture_id": lecture_id} + + +@router.delete("/admin/lectures/{lecture_id}") +async def admin_delete_lecture(request: Request, lecture_id: int): + """Удалить лекцию (файл + запись).""" + telegram_id, _ = await require_auth(request) + _require_admin(telegram_id) + + pool = await get_pool() + async with pool.acquire() as conn: + row = await conn.fetchrow( + "SELECT file_path FROM lectures WHERE id = $1", lecture_id + ) + if not row: + raise HTTPException(404, "Lecture not found") + + await conn.execute("DELETE FROM lectures WHERE id = $1", lecture_id) + + # Удаляем файл с диска + rel_path = row["file_path"].replace("/uploads/", "", 1).lstrip("/") + abs_path = Path(UPLOADS_DIR) / rel_path + try: + if abs_path.exists(): + abs_path.unlink() + except Exception as e: + logger.error(f"Failed to delete lecture file {abs_path}: {e}") + + logger.info(f"Lecture #{lecture_id} deleted by admin {telegram_id}") + + return {"status": "ok", "lecture_id": lecture_id} \ No newline at end of file