File size: 12,686 Bytes
8ad8368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
"""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}