317 lines
16 KiB
Python
317 lines
16 KiB
Python
import asyncio
|
||
import hashlib
|
||
import os
|
||
from pathlib import Path
|
||
import re
|
||
import shutil
|
||
import stat
|
||
from urllib.parse import quote
|
||
from fastapi import APIRouter, Depends, File, Form, Request, Response, UploadFile
|
||
from fastapi.responses import StreamingResponse
|
||
from pydantic import BaseModel, Field
|
||
from sqlalchemy import delete, func, select
|
||
from starlette.background import BackgroundTask
|
||
from .auth import Actor, csrf_actor, current_actor
|
||
from .dto import asset_dto
|
||
from .errors import fail
|
||
from .events import emit_asset, emit_job
|
||
from .models import Asset, Job, JobAsset, new_id, utcnow
|
||
|
||
router = APIRouter(prefix="/assets", tags=["assets"])
|
||
|
||
|
||
def confined(root, value, *, exists=False):
|
||
root = Path(root).resolve()
|
||
path = Path(value)
|
||
path = (path if path.is_absolute() else root / path).resolve(strict=exists)
|
||
if not path.is_relative_to(root):
|
||
raise ValueError("File is outside its permitted directory")
|
||
return path
|
||
|
||
|
||
def safe_file(root, value):
|
||
path = confined(root, value, exists=True)
|
||
fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
|
||
try:
|
||
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
||
raise ValueError("Regular file required")
|
||
if os.name == "posix":
|
||
confined(root, os.readlink(f"/proc/self/fd/{fd}"), exists=True)
|
||
return os.fdopen(fd, "rb")
|
||
except BaseException:
|
||
os.close(fd)
|
||
raise
|
||
|
||
|
||
async def owned_asset(session, asset_id, owner_id, *, include_deleted=False):
|
||
query = select(Asset).where(Asset.id == asset_id, Asset.owner_id == owner_id, Asset.ready.is_(True))
|
||
if not include_deleted:
|
||
query = query.where(Asset.deleted_at.is_(None))
|
||
asset = await session.scalar(query.with_for_update())
|
||
if asset is None:
|
||
fail(404, "asset_not_found", "素材不存在")
|
||
return asset
|
||
|
||
|
||
async def touch_source_job(session, asset):
|
||
if asset.source_job_id:
|
||
source = await session.scalar(select(Job).where(Job.id == asset.source_job_id, Job.owner_id == asset.owner_id))
|
||
if source is not None:
|
||
await emit_job(session, source)
|
||
|
||
|
||
async def build_asset(settings, owner_id, asset_id, path, name, **fields):
|
||
from .media import inspect_media, make_thumbnail
|
||
path = confined(settings.asset_root, path, exists=True)
|
||
metadata = await inspect_media(path, settings)
|
||
def hash_file():
|
||
digest = hashlib.sha256()
|
||
with safe_file(settings.asset_root, path) as source:
|
||
while chunk := source.read(1024 * 1024):
|
||
digest.update(chunk)
|
||
return digest.hexdigest()
|
||
digest = await asyncio.to_thread(hash_file)
|
||
thumbnail = await make_thumbnail(path, path.with_name("thumbnail.jpg"), settings)
|
||
return Asset(id=asset_id, owner_id=owner_id, name=name[:255],
|
||
storage_key=path.relative_to(settings.asset_root).as_posix(),
|
||
thumbnail_key=Path(thumbnail).relative_to(settings.asset_root).as_posix() if thumbnail else None,
|
||
kind=metadata["kind"], mime_type=metadata["mime_type"], size_bytes=path.stat().st_size,
|
||
sha256=digest, width=metadata.get("width"), height=metadata.get("height"),
|
||
duration_seconds=metadata.get("duration_seconds"), tags=[], favorite=False, **fields)
|
||
|
||
|
||
async def import_output(db, settings, job, source, index, *, execution_fence=None):
|
||
async with db.session() as session:
|
||
existing = await session.scalar(select(Asset).where(Asset.source_job_id == job.id,
|
||
Asset.source_output_index == index))
|
||
if existing:
|
||
if execution_fence:
|
||
from .v2_models import AssetReference
|
||
binding=await session.scalar(select(AssetReference.id).where(AssetReference.asset_id==existing.id,AssetReference.ref_kind=="execution",AssetReference.ref_id==execution_fence["execution_id"]))
|
||
if not binding:raise ValueError("Output belongs to a different execution")
|
||
from .artifacts import digest_file
|
||
path=confined(settings.asset_root,existing.storage_key,exists=True)
|
||
with safe_file(settings.asset_root,path):pass
|
||
if path.stat().st_size!=existing.size_bytes or digest_file(path)!=existing.sha256:
|
||
raise ValueError("Imported artifact is missing or corrupt")
|
||
return existing
|
||
asset_id = new_id()
|
||
source = confined(settings.job_work_root, source, exists=True)
|
||
if source.stat().st_size>settings.max_output_bytes:
|
||
raise ValueError("Output exceeds reserved asset limit; retained for operator reconciliation")
|
||
if job.run_id and job.step_key != "compose" and job.task_type == "video.generate":
|
||
from .media import inspect_video_track
|
||
track=await inspect_video_track(source,settings)
|
||
if track["frames"]<120 or track["fps"]!=24 or (track["width"],track["height"])!=(job.parameters.get("upscale_width"),job.parameters.get("upscale_height")):
|
||
raise ValueError("Workflow shot does not meet frozen decoded video specification")
|
||
directory = confined(settings.asset_root, Path(job.owner_id) / asset_id)
|
||
directory.mkdir(parents=True)
|
||
suffix = source.suffix.lower() if re.fullmatch(r"\.[a-z0-9]{1,10}", source.suffix.lower()) else ".bin"
|
||
destination = directory / ("original" + suffix)
|
||
def copy():
|
||
with safe_file(settings.job_work_root, source) as src, destination.open("xb") as dst:
|
||
shutil.copyfileobj(src, dst, 1024 * 1024)
|
||
try:
|
||
await asyncio.to_thread(copy)
|
||
asset = await build_asset(settings, job.owner_id, asset_id, destination, source.name,
|
||
origin="generated", source_job_id=job.id, source_upstream_id=job.upstream_id,
|
||
source_output_index=index, ready=False)
|
||
async with db.session() as session:
|
||
if execution_fence:
|
||
from .executions import gpu_publication_matches
|
||
current=await session.get(Job,job.id)
|
||
if not await gpu_publication_matches(session,current,execution_fence):raise ValueError("Stale GPU result import")
|
||
from .quotas import enforce_owner_asset_budget
|
||
await enforce_owner_asset_budget(session,settings,job.owner_id,asset.size_bytes)
|
||
session.add(asset)
|
||
await session.flush()
|
||
if execution_fence:
|
||
from .v2_models import AssetReference
|
||
session.add(AssetReference(owner_id=job.owner_id,asset_id=asset.id,ref_kind="execution",ref_id=execution_fence["execution_id"]))
|
||
await session.commit()
|
||
return asset
|
||
except BaseException:
|
||
# Commit may have succeeded despite lost ACK; retain for reconciliation.
|
||
raise
|
||
|
||
|
||
@router.post("", status_code=201)
|
||
async def upload(request: Request, file: UploadFile = File(), name: str | None = Form(default=None),
|
||
actor: Actor = Depends(csrf_actor)):
|
||
settings = request.app.state.settings
|
||
from .maintenance import require_writable
|
||
from .quotas import check_storage_budget
|
||
require_writable(settings)
|
||
async with request.app.state.db.session() as session:
|
||
await check_storage_budget(session,settings,actor.id,min(max(0,int(request.headers.get("content-length","0"))) if request.headers.get("content-length","0").isdigit() else settings.max_upload_bytes,settings.max_upload_bytes))
|
||
asset_id = new_id()
|
||
directory = confined(settings.asset_root, Path(actor.id) / asset_id)
|
||
directory.mkdir(parents=True)
|
||
original_name = (file.filename or "素材").replace("\\", "/").rsplit("/", 1)[-1]
|
||
suffix = Path(original_name).suffix.lower()
|
||
if not re.fullmatch(r"\.[a-z0-9]{1,10}", suffix):
|
||
suffix = ".bin"
|
||
path, size = directory / ("original" + suffix), 0
|
||
commit_started = False
|
||
try:
|
||
with path.open("xb") as output:
|
||
while chunk := await file.read(1024 * 1024):
|
||
size += len(chunk)
|
||
if size > settings.max_upload_bytes:
|
||
fail(413, "upload_too_large", "文件超过上传大小限制")
|
||
output.write(chunk)
|
||
if not size:
|
||
fail(422, "empty_upload", "文件不能为空")
|
||
asset = await build_asset(settings, actor.id, asset_id, path, name or original_name or "素材", origin="upload")
|
||
if asset.kind not in {"image", "video", "audio"}:
|
||
fail(422, "unsupported_upload", "上传仅支持图片、视频或音频")
|
||
async with request.app.state.db.session() as session:
|
||
from .quotas import enforce_owner_asset_budget
|
||
await enforce_owner_asset_budget(session,settings,actor.id,asset.size_bytes)
|
||
session.add(asset)
|
||
await session.flush()
|
||
commit_started = True
|
||
emit_asset(session, actor.id, "asset.created", {"asset": asset_dto(asset)})
|
||
await session.commit()
|
||
return asset_dto(asset)
|
||
except BaseException as exc:
|
||
if not commit_started:
|
||
shutil.rmtree(directory, ignore_errors=True)
|
||
if hasattr(exc, "code") and hasattr(exc, "message"):
|
||
fail(422, exc.code, exc.message)
|
||
raise
|
||
finally:
|
||
await file.close()
|
||
|
||
|
||
@router.get("")
|
||
async def list_assets(request: Request, page: int = 1, page_size: int = 24, kind: str = "", q: str = "", tag: str = "", favorite: bool | None = None, origin: str = "",
|
||
actor: Actor = Depends(current_actor)):
|
||
if page < 1 or not 1 <= page_size <= 100:
|
||
fail(422, "invalid_page", "分页参数无效")
|
||
async with request.app.state.db.session() as session:
|
||
query = select(Asset).where(Asset.owner_id == actor.id, Asset.deleted_at.is_(None), Asset.ready.is_(True))
|
||
if kind:
|
||
query = query.where(Asset.kind == kind)
|
||
if q:
|
||
query = query.where(Asset.name.contains(q[:255], autoescape=True))
|
||
from .v2_models import AssetTag
|
||
if favorite is not None:query=query.where(Asset.favorite==favorite)
|
||
if origin:query=query.where(Asset.origin==origin)
|
||
if tag:query=query.where(Asset.id.in_(select(AssetTag.asset_id).where(AssetTag.owner_id==actor.id,AssetTag.tag==tag)))
|
||
total=await session.scalar(select(func.count()).select_from(query.subquery()))
|
||
rows=(await session.scalars(query.order_by(Asset.created_at.desc(),Asset.id.desc()).offset((page-1)*page_size).limit(page_size))).all()
|
||
return {"items":[asset_dto(a) for a in rows],"total":total,"page":page,"page_size":page_size}
|
||
|
||
|
||
|
||
@router.get("/{asset_id}")
|
||
async def get_asset(asset_id: str, request: Request, actor: Actor = Depends(current_actor)):
|
||
async with request.app.state.db.session() as session:
|
||
return asset_dto(await owned_asset(session, asset_id, actor.id))
|
||
|
||
|
||
class AssetPatch(BaseModel):
|
||
name: str | None = Field(default=None, min_length=1, max_length=255)
|
||
tags: list[str] | None = Field(default=None, max_length=30)
|
||
favorite: bool | None = None
|
||
|
||
|
||
@router.patch("/{asset_id}")
|
||
async def patch_asset(asset_id: str, body: AssetPatch, request: Request, actor: Actor = Depends(csrf_actor)):
|
||
async with request.app.state.db.session() as session:
|
||
asset = await owned_asset(session, asset_id, actor.id)
|
||
if body.name is not None:
|
||
asset.name = body.name.strip() or asset.name
|
||
if body.tags is not None:
|
||
if any(not tag.strip() or len(tag) > 64 for tag in body.tags):
|
||
fail(422, "invalid_tag", "标签须为 1–64 个字符")
|
||
asset.tags = list(dict.fromkeys(tag.strip() for tag in body.tags))
|
||
from .v2_models import AssetTag
|
||
await session.execute(delete(AssetTag).where(AssetTag.asset_id==asset.id))
|
||
session.add_all(AssetTag(owner_id=actor.id,asset_id=asset.id,tag=tag) for tag in asset.tags)
|
||
if body.favorite is not None:
|
||
asset.favorite = body.favorite
|
||
emit_asset(session, actor.id, "asset.updated", {"asset": asset_dto(asset)})
|
||
await touch_source_job(session, asset)
|
||
await session.commit()
|
||
return asset_dto(asset)
|
||
|
||
|
||
@router.delete("/{asset_id}", status_code=204)
|
||
async def delete_asset(asset_id: str, request: Request, actor: Actor = Depends(csrf_actor)):
|
||
async with request.app.state.db.session() as session:
|
||
asset = await owned_asset(session, asset_id, actor.id)
|
||
from .v2_models import AssetReference
|
||
ref = await session.scalar(select(AssetReference.id).where(AssetReference.asset_id==asset_id,AssetReference.ref_kind!="execution").limit(1))
|
||
if ref:
|
||
fail(409,"asset_in_use","Asset is referenced by a workflow")
|
||
asset.deleted_at = utcnow()
|
||
referenced = await session.scalar(select(JobAsset.job_id).where(JobAsset.asset_id == asset_id).limit(1))
|
||
storage = asset.storage_key
|
||
emit_asset(session, actor.id, "asset.deleted", {"id": asset.id})
|
||
await touch_source_job(session, asset)
|
||
await session.commit()
|
||
# Physical deletion is exclusively handled by the dry-run-first retention service.
|
||
return Response(status_code=204)
|
||
|
||
|
||
def file_response(settings, asset, key, range_header, download):
|
||
try:
|
||
handle = safe_file(settings.asset_root, key)
|
||
except (ValueError, OSError):
|
||
fail(404, "file_unavailable", "素材文件不可用")
|
||
size = os.fstat(handle.fileno()).st_size
|
||
start, end, code = 0, size - 1, 200
|
||
if range_header:
|
||
match = re.fullmatch(r"bytes=(\d*)-(\d*)", range_header.strip())
|
||
try:
|
||
if not match or not any(match.groups()):
|
||
raise ValueError
|
||
a, b = match.groups()
|
||
if a:
|
||
start, end = int(a), min(int(b), size - 1) if b else size - 1
|
||
else:
|
||
start, end = max(0, size - int(b)), size - 1
|
||
if start > end or start >= size or start < 0:
|
||
raise ValueError
|
||
code = 206
|
||
except ValueError:
|
||
handle.close()
|
||
return Response(status_code=416, headers={"Content-Range": f"bytes */{size}"})
|
||
handle.seek(start)
|
||
def chunks():
|
||
remaining = end - start + 1
|
||
try:
|
||
while remaining > 0:
|
||
data = handle.read(min(1024 * 1024, remaining))
|
||
if not data:
|
||
break
|
||
remaining -= len(data)
|
||
yield data
|
||
finally:
|
||
handle.close()
|
||
headers = {"Accept-Ranges": "bytes", "Content-Length": str(max(0, end - start + 1)),
|
||
"X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store",
|
||
"Content-Disposition": ("attachment" if download else "inline") + "; filename*=UTF-8''" + quote(asset.name, safe="")}
|
||
if code == 206:
|
||
headers["Content-Range"] = f"bytes {start}-{end}/{size}"
|
||
return StreamingResponse(chunks(), status_code=code, media_type="image/jpeg" if key != asset.storage_key else asset.mime_type,
|
||
headers=headers, background=BackgroundTask(handle.close))
|
||
|
||
|
||
@router.get("/{asset_id}/content")
|
||
async def content(asset_id: str, request: Request, download: bool = False, actor: Actor = Depends(current_actor)):
|
||
async with request.app.state.db.session() as session:
|
||
asset = await owned_asset(session, asset_id, actor.id)
|
||
return file_response(request.app.state.settings, asset, asset.storage_key, request.headers.get("range"), download)
|
||
|
||
|
||
@router.get("/{asset_id}/thumbnail")
|
||
async def thumbnail(asset_id: str, request: Request, actor: Actor = Depends(current_actor)):
|
||
async with request.app.state.db.session() as session:
|
||
asset = await owned_asset(session, asset_id, actor.id)
|
||
if not asset.thumbnail_key and asset.kind != "image":
|
||
fail(404, "thumbnail_unavailable", "预览图暂不可用")
|
||
return file_response(request.app.state.settings, asset, asset.thumbnail_key or asset.storage_key, None, False)
|