"""Monteeq Clips — free asset library for editors. Public: GET /assets list (filters, search, sort, pagination) GET /assets/{id} detail (preview URLs only, never file_key) POST /assets/{id}/download auth required; counts the download, returns a short-lived download URL GET /assets/download/{token} streams the private file (local mode) after HMAC token validation; redirects to a presigned URL in s3 mode Admin (existing admin_only check): POST /assets multipart upload (file + optional preview) PATCH /assets/{id} metadata update DELETE /assets/{id} soft delete (is_published = false) """ import mimetypes import os import re import unicodedata import uuid from typing import Optional from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile from fastapi.responses import FileResponse, RedirectResponse from sqlalchemy import func, or_ from sqlalchemy.orm import Session from app.core import config from app.core.asset_tokens import verify_download_token from app.core.dependencies import admin_only, get_current_user from app.core.storage import storage from app.db.session import get_db from app.models.assets import Asset, AssetDownload from app.models.models import User from app.schemas.assets import ( AssetDownloadResponse, AssetListResponse, AssetPublic, AssetUpdate, _norm_category, _norm_preview_type, ) router = APIRouter() # ── Helpers ─────────────────────────────────────────────────────────────────── def _to_public(asset: Asset) -> dict: """Serialise an asset for public responses. NEVER includes file_key.""" preview_url = None if asset.preview_key: try: preview_url = storage.get_url(asset.preview_key) except Exception: preview_url = None created = asset.created_at.isoformat() if asset.created_at else None return { "id": asset.id, "title": asset.title, "description": asset.description, "category": asset.category, "owner_id": asset.owner_id, "preview_url": preview_url, "preview_type": asset.preview_type, "format": asset.format, "size_bytes": asset.size_bytes, "license_note": asset.license_note, "is_free": asset.is_free, "price": asset.price, "download_count": asset.download_count or 0, "created_at": created, } def _get_published_or_404(db: Session, asset_id: int) -> Asset: asset = ( db.query(Asset) .filter(Asset.id == asset_id, Asset.is_published.is_(True)) .first() ) if not asset: raise HTTPException(status_code=404, detail="Asset not found") return asset def _safe_filename(filename: str, default_ext: str = "") -> str: base, ext = os.path.splitext(filename or "") safe = unicodedata.normalize("NFKD", base).encode("ascii", "ignore").decode("ascii") safe = re.sub(r"[^\w\s-]", "", safe).strip().lower() safe = re.sub(r"[-\s]+", "_", safe) or "file" return f"{safe}{ext or default_ext}" def _measure_size(upload: UploadFile) -> int: upload.file.seek(0, os.SEEK_END) size = upload.file.tell() upload.file.seek(0) return size def _check_limits(category: str, upload: UploadFile, max_bytes: int, allowed: set) -> str: ext = os.path.splitext(upload.filename or "")[1].lower() if ext not in allowed: raise HTTPException( status_code=400, detail=f"File type '{ext or '(none)'}' not allowed for this upload. " f"Allowed: {sorted(allowed)}", ) size = _measure_size(upload) if size > max_bytes: raise HTTPException( status_code=413, detail=f"File too large ({size} bytes). Maximum is {max_bytes} bytes.", ) return ext # ── Token download (defined BEFORE /{asset_id} so "download" never collides) ─ @router.get("/download/{token}") def download_by_token(token: str, db: Session = Depends(get_db)): """Validate the HMAC token and serve the private file. Local mode streams the file with Content-Disposition: attachment. S3 mode redirects to a short-lived presigned URL. No login required — the signed token is the credential. """ asset_id = verify_download_token(token) asset = _get_published_or_404(db, asset_id) if storage.mode == "local": try: path = storage._local_private_path(asset.file_key) except ValueError: raise HTTPException(status_code=404, detail="File not found") if not os.path.isfile(path): raise HTTPException(status_code=404, detail="File not found") ext = os.path.splitext(asset.file_key)[1] media_type, _ = mimetypes.guess_type("file" + ext) return FileResponse( path, media_type=media_type or "application/octet-stream", filename=f"asset-{asset.id}{ext}", content_disposition_type="attachment", ) # S3 mode (any S3-compatible endpoint): redirect to a fresh presigned URL. try: url = storage.generate_presigned_download_url( asset.file_key, config.ASSETS_DOWNLOAD_EXPIRES_SECONDS ) except Exception: raise HTTPException(status_code=500, detail="Could not generate download URL") return RedirectResponse(url=url, status_code=302) # ── Public list / detail ────────────────────────────────────────────────────── @router.get("/", response_model=AssetListResponse) def list_assets( category: Optional[str] = None, search: Optional[str] = None, sort: str = "newest", page: int = 1, limit: int = 20, db: Session = Depends(get_db), ): if page < 1: raise HTTPException(status_code=422, detail="page must be >= 1") limit = min(max(limit, 1), 50) if sort not in ("popular", "newest"): raise HTTPException(status_code=422, detail="sort must be 'popular' or 'newest'") if category is not None: try: category = _norm_category(category) except ValueError as e: raise HTTPException(status_code=422, detail=str(e)) query = db.query(Asset).filter(Asset.is_published.is_(True)) if category: query = query.filter(Asset.category == category) if search: like = f"%{search}%" query = query.filter(or_(Asset.title.ilike(like), Asset.description.ilike(like))) total = query.with_entities(func.count(Asset.id)).scalar() or 0 if sort == "popular": query = query.order_by(Asset.download_count.desc(), Asset.id.desc()) else: query = query.order_by(Asset.created_at.desc(), Asset.id.desc()) offset = (page - 1) * limit rows = query.offset(offset).limit(limit).all() return { "items": [_to_public(a) for a in rows], "page": page, "limit": limit, "total": total, "has_more": offset + limit < total, } @router.get("/{asset_id}", response_model=AssetPublic) def get_asset(asset_id: int, db: Session = Depends(get_db)): asset = _get_published_or_404(db, asset_id) return _to_public(asset) # ── Authenticated download ──────────────────────────────────────────────────── @router.post("/{asset_id}/download", response_model=AssetDownloadResponse) def download_asset( asset_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): asset = _get_published_or_404(db, asset_id) # One transaction: record the event + atomically bump the counter. db.add(AssetDownload(user_id=current_user.id, asset_id=asset.id)) ( db.query(Asset) .filter(Asset.id == asset.id) .update({Asset.download_count: Asset.download_count + 1}, synchronize_session=False) ) db.commit() expires = config.ASSETS_DOWNLOAD_EXPIRES_SECONDS try: url = storage.get_asset_download_url(asset.id, asset.file_key, expires) except ValueError as e: raise HTTPException(status_code=500, detail=f"Could not generate download URL: {e}") except Exception: raise HTTPException(status_code=500, detail="Could not generate download URL") return {"download_url": url, "expires_in": expires} # ── Admin ───────────────────────────────────────────────────────────────────── @router.post("/", response_model=AssetPublic) def create_asset( title: str = Form(...), category: str = Form(...), file: UploadFile = File(...), description: Optional[str] = Form(None), preview_type: Optional[str] = Form(None), preview: Optional[UploadFile] = File(None), format: Optional[str] = Form(None), license_note: Optional[str] = Form(None), is_free: bool = Form(True), price: Optional[float] = Form(None), is_published: bool = Form(True), db: Session = Depends(get_db), current_user: User = Depends(admin_only), ): try: category = _norm_category(category) except ValueError as e: raise HTTPException(status_code=422, detail=str(e)) try: preview_type = _norm_preview_type(preview_type) if preview_type else None except ValueError as e: raise HTTPException(status_code=422, detail=str(e)) allowed = config.ASSETS_ALLOWED_EXTENSIONS.get(category, set()) ext = _check_limits(category, file, config.ASSETS_MAX_FILE_BYTES, allowed) file_size = _measure_size(file) preview_key = None if preview and preview.filename: _check_limits( category, preview, config.ASSETS_MAX_PREVIEW_BYTES, config.ASSETS_ALLOWED_PREVIEW_EXTENSIONS, ) task = uuid.uuid4().hex file_key = f"{config.ASSETS_FILE_PREFIX}{task}_{_safe_filename(file.filename)}" try: storage.upload_private_file_obj(file.file, file_key) except Exception: raise HTTPException(status_code=500, detail="Failed to upload file to storage") if preview and preview.filename: preview_key = f"{config.ASSETS_PREVIEW_PREFIX}{task}_{_safe_filename(preview.filename)}" try: storage.upload_file_obj(preview.file, preview_key) except Exception: # Roll back the private file so we don't orphan it. try: if storage.mode == "local": os.remove(storage._local_private_path(file_key)) else: storage.delete_file(file_key) except Exception: pass raise HTTPException(status_code=500, detail="Failed to upload preview to storage") asset = Asset( title=title, description=description, category=category, owner_id=current_user.id, file_key=file_key, preview_key=preview_key, preview_type=preview_type, format=format or ext.lstrip("."), size_bytes=file_size, license_note=license_note, is_free=is_free, price=price, is_published=is_published, ) db.add(asset) db.commit() db.refresh(asset) return _to_public(asset) @router.patch("/{asset_id}", response_model=AssetPublic) def update_asset( asset_id: int, payload: AssetUpdate, db: Session = Depends(get_db), current_user: User = Depends(admin_only), ): asset = db.query(Asset).filter(Asset.id == asset_id).first() if not asset: raise HTTPException(status_code=404, detail="Asset not found") for field, value in payload.model_dump(exclude_none=True).items(): setattr(asset, field, value) db.commit() db.refresh(asset) return _to_public(asset) @router.delete("/{asset_id}") def delete_asset( asset_id: int, db: Session = Depends(get_db), current_user: User = Depends(admin_only), ): asset = db.query(Asset).filter(Asset.id == asset_id).first() if not asset: raise HTTPException(status_code=404, detail="Asset not found") asset.is_published = False db.commit() return {"status": "success", "id": asset_id}