import os from pathlib import Path from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from app.database import get_db from app.models import Library, MediaItem from app.schemas import LibraryCreate, LibraryOut, BrowseResult, BrowseEntry from app.services import scanner, watcher as watcher_service router = APIRouter(prefix="/libraries", tags=["libraries"]) @router.get("", response_model=list[LibraryOut]) async def list_libraries(db: AsyncSession = Depends(get_db)): result = await db.execute(select(Library)) return result.scalars().all() @router.post("", response_model=LibraryOut, status_code=201) async def create_library(body: LibraryCreate, db: AsyncSession = Depends(get_db)): path = Path(body.path) if not path.is_dir(): raise HTTPException(400, f"Path does not exist or is not a directory: {body.path}") existing = await db.execute(select(Library).where(Library.path == str(path))) if existing.scalars().first(): raise HTTPException(409, "A library with this path already exists") lib = Library(name=body.name, path=str(path)) db.add(lib) await db.flush() await db.refresh(lib) lib_id = lib.id lib_path = lib.path await db.commit() await scanner.scan_library(lib_id, lib_path, db) watcher_service.start_watcher(lib_id, lib_path) async with db.begin(): pass result = await db.execute(select(Library).where(Library.id == lib_id)) return result.scalars().first() @router.delete("/{library_id}", status_code=204) async def delete_library(library_id: int, db: AsyncSession = Depends(get_db)): result = await db.execute(select(Library).where(Library.id == library_id)) lib = result.scalars().first() if not lib: raise HTTPException(404, "Library not found") watcher_service.stop_watcher(library_id) await db.delete(lib) await db.commit() @router.get("/{library_id}/browse", response_model=BrowseResult) async def browse_library(library_id: int, path: str = "", db: AsyncSession = Depends(get_db)): result = await db.execute(select(Library).where(Library.id == library_id)) lib = result.scalars().first() if not lib: raise HTTPException(404, "Library not found") root = Path(lib.path) target = (root / path).resolve() # Path traversal guard if not str(target).startswith(str(root)): raise HTTPException(400, "Invalid path") if not target.is_dir(): raise HTTPException(404, "Directory not found") # Load all media items in this directory (non-recursive) rel_prefix = path.strip("/") items_result = await db.execute( select(MediaItem).where( MediaItem.library_id == library_id, MediaItem.missing == False, # noqa: E712 ) ) db_items: dict[str, MediaItem] = {} for item in items_result.scalars().all(): db_items[item.rel_path] = item entries: list[BrowseEntry] = [] for entry in sorted(target.iterdir(), key=lambda e: (e.is_file(), e.name.lower())): rel_entry = str(entry.relative_to(root)) if entry.is_dir(): entries.append(BrowseEntry(name=entry.name, type="dir", rel_path=rel_entry)) elif entry.is_file() and rel_entry in db_items: item = db_items[rel_entry] entries.append(BrowseEntry( name=entry.name, type=item.media_type, rel_path=rel_entry, media_item_id=item.id, )) return BrowseResult(path=path, entries=entries)