cmvr-visual/backend/app/shared_assets.py

278 lines
14 KiB
Python

"""Authenticated publication snapshots and independent private imports."""
import asyncio
import hashlib
from pathlib import Path
import re
import shutil
from fastapi import APIRouter, Body, Depends, Header, Request, Response
from pydantic import BaseModel, ConfigDict
from sqlalchemy import delete, func, select, update
from .assets import confined, file_response, owned_asset, safe_file
from .auth import Actor, csrf_actor, current_actor
from .dto import asset_dto, iso
from .errors import fail
from .events import emit_asset
from .models import Asset, User, new_id, utcnow
from .v2_models import AssetReference, AssetTag, SharedAsset, Submission
router = APIRouter(prefix="/shared-assets", tags=["shared-assets"])
publish_router = APIRouter(prefix="/assets", tags=["shared-assets"])
class EmptyPayload(BaseModel):
model_config = ConfigDict(extra="forbid")
def shared_dto(publication, asset, publisher, actor):
base = f"/api/shared-assets/{publication.id}"
return {
"id": publication.id, "name": asset.name, "kind": asset.kind,
"mime_type": asset.mime_type, "size_bytes": asset.size_bytes,
"width": asset.width, "height": asset.height,
"duration_seconds": asset.duration_seconds, "tags": asset.tags or [],
"created_at": iso(publication.created_at), "publisher_id": publisher.id,
"publisher_name": publisher.display_name or publisher.username,
"is_owner": publication.publisher_id == actor.id, "version": publication.version,
"preview_url": base + "/content",
"thumbnail_url": base + "/thumbnail" if asset.kind in {"image", "video"} else None,
"download_url": base + "/content?download=1",
}
def shared_query():
return (select(SharedAsset, Asset, User)
.join(Asset, Asset.id == SharedAsset.asset_id)
.join(User, User.id == SharedAsset.publisher_id)
.where(SharedAsset.withdrawn_at.is_(None), Asset.deleted_at.is_(None),
Asset.ready.is_(True), Asset.library_scope == "shared"))
async def available_shared(session, shared_id):
row = (await session.execute(shared_query().where(SharedAsset.id == shared_id).with_for_update())).first()
if row is None:
fail(404, "shared_asset_not_found", "共享素材不存在或已撤回")
return row
async def copy_asset(settings, source, owner_id, *, scope):
"""Copy verified regular files into a fresh directory; never link source bytes."""
asset_id = new_id()
directory = confined(settings.asset_root, Path(owner_id) / asset_id)
directory.mkdir(parents=True)
def copy_files():
suffix = Path(source.storage_key).suffix.lower()
if not re.fullmatch(r"\.[a-z0-9]{1,10}", suffix):
suffix = ".bin"
destination = directory / ("original" + suffix)
digest, size = hashlib.sha256(), 0
with safe_file(settings.asset_root, source.storage_key) as src, destination.open("xb") as dst:
while chunk := src.read(1024 * 1024):
size += len(chunk)
if size > source.size_bytes:
raise ValueError("Source size changed")
digest.update(chunk)
dst.write(chunk)
if size != source.size_bytes or digest.hexdigest() != source.sha256:
raise ValueError("Source integrity check failed")
thumbnail = None
if source.thumbnail_key:
thumbnail = directory / "thumbnail.jpg"
with safe_file(settings.asset_root, source.thumbnail_key) as src, thumbnail.open("xb") as dst:
shutil.copyfileobj(src, dst, 1024 * 1024)
return destination, thumbnail
try:
path, thumbnail = await asyncio.to_thread(copy_files)
asset = Asset(
id=asset_id, owner_id=owner_id, name=source.name, library_scope=scope,
storage_key=path.relative_to(settings.asset_root).as_posix(),
thumbnail_key=thumbnail.relative_to(settings.asset_root).as_posix() if thumbnail else None,
kind=source.kind, mime_type=source.mime_type, size_bytes=source.size_bytes,
sha256=source.sha256, width=source.width, height=source.height,
duration_seconds=source.duration_seconds, tags=list(source.tags or []), favorite=False,
origin="shared", ready=True, source_job_id=None, source_upstream_id=None,
source_output_index=None,
)
return asset, directory
except BaseException as exc:
shutil.rmtree(directory, ignore_errors=True)
if isinstance(exc, (OSError, ValueError)):
fail(404, "file_unavailable", "素材文件不可用")
raise
async def copy_budget(session, settings, owner_id, size_bytes):
# Match upload accounting, including retained soft-deleted files. Publication
# copies charge the publisher; private imports charge the importing user.
owner = await session.scalar(select(User).where(User.id == owner_id).with_for_update())
if owner is None or owner.disabled:
fail(403, "owner_disabled", "用户不可用")
from .quotas import check_storage_budget
await check_storage_budget(session, settings, owner_id, size_bytes)
def add_tags(session, asset):
session.add_all(AssetTag(owner_id=asset.owner_id, asset_id=asset.id, tag=tag) for tag in (asset.tags or []))
@publish_router.post("/{asset_id}/publish", status_code=201)
async def publish_asset(asset_id: str, request: Request, body: EmptyPayload | None = Body(default=None),
idempotency_key: str | None = Header(default=None), actor: Actor = Depends(csrf_actor)):
from .maintenance import require_writable
from .submissions import accept_submission
settings = request.app.state.settings
require_writable(settings)
directory, commit_started = None, False
try:
# This deployment serializes DB units. Keep source verification, copying,
# publication, and references in the same unit to exclude withdrawal/GC.
async with request.app.state.db.session() as session:
record = (await accept_submission(session, actor.id, "assets.publish", idempotency_key,
2, {"asset_id": asset_id})) if idempotency_key is not None else None
if record and record.resource_json.get("shared_asset_id"):
row = (await session.execute(shared_query().where(
SharedAsset.id == record.resource_json["shared_asset_id"], SharedAsset.publisher_id == actor.id))).first()
if row is None:
fail(410, "resource_purged", "共享发布已撤回")
return shared_dto(*row, actor)
source = await owned_asset(session, asset_id, actor.id)
row = (await session.execute(shared_query().where(
SharedAsset.source_asset_id == source.id, SharedAsset.publisher_id == actor.id))).first()
if row:
publication, snapshot, publisher = row
else:
await copy_budget(session, settings, actor.id, source.size_bytes)
snapshot, directory = await copy_asset(settings, source, actor.id, scope="shared")
session.add(snapshot)
await session.flush()
add_tags(session, snapshot)
publication = SharedAsset(id=new_id(), publisher_id=actor.id, asset_id=snapshot.id,
source_asset_id=source.id, version=1)
session.add(publication)
await session.flush()
session.add(AssetReference(owner_id=actor.id, asset_id=snapshot.id,
ref_kind="shared", ref_id=publication.id))
publisher = await session.get(User, actor.id)
if record:
record.resource_json = {"shared_asset_id": publication.id}
commit_started = True
await session.commit()
return shared_dto(publication, snapshot, publisher, actor)
except BaseException:
# A lost commit ACK can leave a durable publication. Retain files in that
# case for reconciliation, as the normal upload/import pipeline does.
if directory is not None and not commit_started:
shutil.rmtree(directory, ignore_errors=True)
raise
@router.get("")
async def list_shared_assets(request: Request, q: str = "", kind: str = "", tag: str = "", mine: bool = False,
page: int = 1, page_size: int = 24, 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 = shared_query()
if q:
query = query.where(Asset.name.contains(q[:255], autoescape=True))
if kind:
query = query.where(Asset.kind == kind)
if tag:
query = query.where(Asset.id.in_(select(AssetTag.asset_id).where(AssetTag.tag == tag)))
if mine:
query = query.where(SharedAsset.publisher_id == actor.id)
total = await session.scalar(select(func.count()).select_from(query.subquery()))
rows = (await session.execute(query.order_by(SharedAsset.created_at.desc(), SharedAsset.id.desc())
.offset((page - 1) * page_size).limit(page_size))).all()
return {"items": [shared_dto(*row, actor) for row in rows], "total": total,
"page": page, "page_size": page_size}
@router.get("/{shared_id}")
async def get_shared_asset(shared_id: str, request: Request, actor: Actor = Depends(current_actor)):
async with request.app.state.db.session() as session:
return shared_dto(*(await available_shared(session, shared_id)), actor)
@router.get("/{shared_id}/content")
async def shared_content(shared_id: str, request: Request, download: bool = False,
actor: Actor = Depends(current_actor)):
async with request.app.state.db.session() as session:
_, asset, _ = await available_shared(session, shared_id)
return file_response(request.app.state.settings, asset, asset.storage_key, request.headers.get("range"), download)
@router.get("/{shared_id}/thumbnail")
async def shared_thumbnail(shared_id: str, request: Request, actor: Actor = Depends(current_actor)):
async with request.app.state.db.session() as session:
_, asset, _ = await available_shared(session, shared_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)
@router.post("/{shared_id}/import", status_code=201)
async def import_shared_asset(shared_id: str, request: Request, body: EmptyPayload | None = Body(default=None),
idempotency_key: str | None = Header(default=None), actor: Actor = Depends(csrf_actor)):
from .maintenance import require_writable
from .submissions import accept_submission
settings = request.app.state.settings
require_writable(settings)
directory, commit_started = None, False
try:
async with request.app.state.db.session() as session:
record = (await accept_submission(session, actor.id, "shared.import", idempotency_key,
2, {"shared_asset_id": shared_id})) if idempotency_key is not None else None
if record and record.resource_json.get("asset_id"):
existing = await session.scalar(select(Asset).where(
Asset.id == record.resource_json["asset_id"], Asset.owner_id == actor.id,
Asset.library_scope == "private", Asset.ready.is_(True), Asset.deleted_at.is_(None)))
if existing is None:
fail(410, "resource_purged", "导入素材已删除")
return asset_dto(existing)
_, source, _ = await available_shared(session, shared_id)
await copy_budget(session, settings, actor.id, source.size_bytes)
asset, directory = await copy_asset(settings, source, actor.id, scope="private")
session.add(asset)
await session.flush()
add_tags(session, asset)
if record:
record.resource_json = {"asset_id": asset.id}
emit_asset(session, actor.id, "asset.created", {"asset": asset_dto(asset)})
commit_started = True
await session.commit()
return asset_dto(asset)
except BaseException:
if directory is not None and not commit_started:
shutil.rmtree(directory, ignore_errors=True)
raise
@router.delete("/{shared_id}", status_code=204)
async def withdraw_shared_asset(shared_id: str, request: Request, actor: Actor = Depends(csrf_actor)):
async with request.app.state.db.session() as session:
publication = await session.scalar(select(SharedAsset).where(
SharedAsset.id == shared_id, SharedAsset.publisher_id == actor.id).with_for_update())
if publication is None:
fail(404, "shared_asset_not_found", "共享素材不存在")
if publication.withdrawn_at is None:
publication.withdrawn_at = utcnow()
publication.version += 1
snapshot = await session.get(Asset, publication.asset_id)
if snapshot is not None:
snapshot.deleted_at = publication.withdrawn_at
await session.execute(delete(AssetReference).where(
AssetReference.asset_id == publication.asset_id,
AssetReference.ref_kind == "shared", AssetReference.ref_id == publication.id))
# Imported private copies have their own asset_id result. Keep their
# recovery records even when the importer is also the publisher.
await session.execute(update(Submission).where(
Submission.owner_id == actor.id, Submission.status != "purged",
Submission.resource_json["shared_asset_id"].as_string() == publication.id).values(status="purged"))
await session.commit()
return Response(status_code=204)