""" 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}