import hashlib from pathlib import Path import re import shutil from sqlalchemy import func, select, update from app.adapters.storage import confined, file_thread, safe_file from app.services.assets import owned_asset from app.core.security import Actor from app.services.snapshots import asset_dto, iso from app.core.errors import fail from app.services.events import emit_asset from app.models import Asset, User, new_id from app.models import AssetReference, AssetTag, SharedAsset, Submission from app.schemas.shared_assets import EmptyPayload "Authenticated publication snapshots and independent private imports." 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 # 发布与导入各自复制独立字节和 ID;删除原素材或撤回发布不得破坏他人的私有副本。 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("\\.[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 file_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): 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 app.services.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 []) ) async def publish_asset( asset_id: str, runtime, body: EmptyPayload | None = None, idempotency_key: str | None = None, actor: Actor = None, ): from app.core.maintenance import require_writable from app.services.submissions import accept_submission settings = runtime.settings require_writable(settings) directory, commit_started = (None, False) try: async with runtime.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: if directory is not None and (not commit_started): shutil.rmtree(directory, ignore_errors=True) raise async def list_shared_assets( runtime, q: str = "", kind: str = "", tag: str = "", mine: bool = False, page: int = 1, page_size: int = 24, actor: Actor = None, ): if page < 1 or not 1 <= page_size <= 100: fail(422, "invalid_page", "分页参数无效") async with runtime.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, } async def get_shared_asset(shared_id: str, runtime, actor: Actor = None): async with runtime.db.session() as session: return shared_dto(*await available_shared(session, shared_id), actor) async def import_shared_asset( shared_id: str, runtime, body=None, idempotency_key: str | None = None, actor: Actor = None, ): from app.core.maintenance import require_writable from app.services.submissions import accept_submission folder_id = getattr(body, "folder_id", None) settings = runtime.settings require_writable(settings) directory, commit_started = (None, False) try: async with runtime.db.session() as session: from app.services.folders import owned_folder, assign_asset_folders record = ( await accept_submission( session, actor.id, "shared.import", idempotency_key, 2, { "shared_asset_id": shared_id, **({"folder_id": folder_id} if folder_id else {}), }, ) 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) if folder_id: # 已完成的幂等请求先恢复素材;仅首次导入校验目标,目录删除不使成功结果失效。 # 先只校验权限;copy_budget 锁用户后,成员绑定再锁目录,保持用户→目录锁序。 await owned_folder(session, folder_id, actor.id) _, 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() await assign_asset_folders(session, asset, [folder_id] if folder_id else []) 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 async def withdraw_shared_asset(shared_id: str, runtime, actor: Actor = None): async with runtime.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", "共享素材不存在") from app.services.asset_deletion import remove_asset snapshot = await session.get(Asset, publication.asset_id) if snapshot is None or snapshot.library_scope != "shared" or snapshot.owner_id != actor.id: fail(409, "invalid_shared_snapshot", "共享素材存储记录异常,无法安全删除") await remove_asset(session, runtime.settings, snapshot, publication=publication) 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 None