PRINTFILM: AI short-video marketing and AI short-drama creation platform
配置
增瑞 田6a9dba5065f5
diff --git a/admin/src/api/types/settings.ts b/admin/src/api/types/settings.tsindex 928131a..58c580c 100644--- a/admin/src/api/types/settings.ts+++ b/admin/src/api/types/settings.ts@@ -95,6 +95,7 @@ export type AdminModelSettings = {public_base_url: string;ffmpeg_path: string;ffprobe_path: string;+ marketplace_enabled: boolean;source: string;updated_at?: string | null;readiness: ModelCapabilityReadiness[];diff --git a/admin/src/components/settings/SiteSettingsPanel.tsx b/admin/src/components/settings/SiteSettingsPanel.tsxindex 6abb782..8a3500c 100644--- a/admin/src/components/settings/SiteSettingsPanel.tsx+++ b/admin/src/components/settings/SiteSettingsPanel.tsx@@ -5,6 +5,7 @@ import {SettingsStatusBar,SettingsTabShell,} from "@/components/settings/SettingsPanel";+import { Switch } from "@/components/ui/switch";import { useAdminModelSettings } from "@/hooks/useAdminModelSettings";/** 站点公网地址与媒体工具路径 */@@ -18,6 +19,7 @@ export function SiteSettingsPanel() {public_base_url: form.public_base_url,ffmpeg_path: form.ffmpeg_path,ffprobe_path: form.ffprobe_path,+ marketplace_enabled: form.marketplace_enabled,},"站点配置已保存",);@@ -57,6 +59,13 @@ export function SiteSettingsPanel() {readyText: form.ffprobe_path || "已配置",pendingText: "使用默认 PATH",},+ {+ id: "marketplace",+ label: "数字资产市场",+ ready: form.marketplace_enabled,+ readyText: "已启用",+ pendingText: "未启用",+ },]}/>@@ -108,6 +117,23 @@ export function SiteSettingsPanel() {</LabeledControl></div></SettingsPanel>++ <SettingsPanel+ className="settings-panel--compact"+ title="3. 数字资产市场"+ description="线上没有环境文件时,在这里打开入口"+ >+ <div className="settings-toggle-row">+ <div>+ <strong>启用数字资产市场</strong>+ <span>保存后用户端出现「数字资产市场」,管理端「业务」出现「数字资产平台运营」。上传仍使用「存储 OSS」。</span>+ </div>+ <Switch+ checked={form.marketplace_enabled}+ onCheckedChange={(value) => patchField("marketplace_enabled", value)}+ />+ </div>+ </SettingsPanel></div></SettingsTabShell>);diff --git a/backend/.env.marketplace.example b/backend/.env.marketplace.exampleindex fba50fe..0c5fc2e 100644--- a/backend/.env.marketplace.example+++ b/backend/.env.marketplace.example@@ -1,4 +1,5 @@# 下游默认关闭。仅作配置说明,不包含真实凭证,也不改变上游 OSS_*。+# 线上没有这份文件时,在管理端「系统设置 → 站点工具」打开。保存后以数据库为准。MARKETPLACE_ENABLED=false# OSS 共用后台「系统设置 → 存储 OSS」配置,无需 MARKETPLACE_OSS_*。# 数字资产市场固定使用 marketplace/;原业务 OSS_FOLDER 保持原意。diff --git a/backend/app/config.py b/backend/app/config.pyindex 1c75a32..5e8a150 100644--- a/backend/app/config.py+++ b/backend/app/config.py@@ -153,6 +153,8 @@ class Settings(BaseSettings):public_base_url: str = "http://127.0.0.1:8000"ffmpeg_path: str = "ffmpeg"ffprobe_path: str = "ffprobe"+ # 数字资产市场。环境变量 MARKETPLACE_ENABLED;管理端保存后以数据库为准。+ marketplace_enabled: bool = Falsetos_endpoint: str = ""tos_bucket: str = ""diff --git a/backend/app/main.py b/backend/app/main.pyindex 003e7ee..1c0670d 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -131,9 +131,11 @@ async def on_startup() -> None:except Exception: # noqa: BLE001passawait start_task_runtime()- from app.marketplace.config import get_marketplace_settings- if get_marketplace_settings().enabled:- # 市场启动回调早于本函数里的补列,免费内容下架必须等列补齐后再查系列表。+ from app.marketplace.bootstrap import apply_marketplace_switch+ from app.marketplace.config import is_marketplace_enabled+ # 补列完成后再按系统设置建市场表并启动 Worker。关闭时不建表。+ await apply_marketplace_switch()+ if is_marketplace_enabled():from app.marketplace.previews import withdraw_unwatermarked_publicasync with AsyncSessionLocal() as db:await withdraw_unwatermarked_public(db)@@ -145,6 +147,8 @@ async def on_shutdown() -> None:"""Release Postgres pool on uvicorn worker exit."""from app.database import dispose_engine+ from app.marketplace.runtime import stop_marketplace_runtime+ await stop_marketplace_runtime()await stop_task_runtime()await dispose_engine()diff --git a/backend/app/marketplace/api.py b/backend/app/marketplace/api.pyindex 8998fd7..88e7077 100644--- a/backend/app/marketplace/api.py+++ b/backend/app/marketplace/api.py@@ -5,7 +5,7 @@ from sqlalchemy import func, literal, select, union_allfrom app.models import Userfrom .dependencies import Actor, DB, Visitorfrom .previews import prepare_preview, preview_ready, requires_preview-from .models import Asset, PlaybackJob, Publication, Recruit, RegistrationCase, RevenueConfig, Rights, Series, Submission, Work+from .models import Asset, Handoff, PlaybackJob, Publication, Recruit, RegistrationCase, RevenueConfig, Rights, Series, SeriesEpisode, Submission, Workfrom .schemas import CaseInput, RecruitInput, RecruitUpdate, RightsInput, Version, WorkInput, WorkUpdatefrom .service import (asset_owned, asset_owned_for_draft, check_version, data, ensure_kept, event, fail, get_target, is_public_work, now,notify, owned, page, public_recruit_filters, public_work_filters, recruit_data,@@ -14,6 +14,23 @@ from .service import (asset_owned, asset_owned_for_draft, check_version, data, erouter = APIRouter()+async def _pause_work_sales(db, work_id: int) -> None:+ publications = list((await db.execute(select(Publication).where(+ Publication.content_type == "work", Publication.content_id == work_id,+ ).with_for_update())).scalars().all())+ for publication in publications:+ publication.listed = False+++async def _ensure_work_idle(db, work_id: int) -> None:+ active = (await db.execute(select(Handoff.id).where(+ Handoff.target_kind == "work", Handoff.target_id == work_id,+ Handoff.status.in_(("pending", "running")),+ ).limit(1))).scalar_one_or_none()+ if active:+ fail("MARKETPLACE_SYNC_IN_PROGRESS", 409)++@router.get("/categories", response_model=dict)async def get_categories(db: DB):from .categories import category_config@@ -105,6 +122,7 @@ async def update_work(work_id: int, body: WorkUpdate, db: DB, user: Actor):item = await owned(db, Work, work_id, user)ensure_kept(item)check_version(item, body.version)+ await _ensure_work_idle(db, item.id)from .categories import validate_categoryawait validate_category(db, body.category, item.category)if body.asset_id:@@ -123,6 +141,7 @@ async def update_work(work_id: int, body: WorkUpdate, db: DB, user: Actor):setattr(item, key, value)item.version += 1item.audit_status, item.listed, item.reason = "draft", False, ""+ await _pause_work_sales(db, item.id)event(db, user.id, "work", item.id, "updated", version=item.version)await db.commit()return await work_data(db, item, True)@@ -134,8 +153,11 @@ async def submit_work(work_id: int, body: Version, db: DB, user: Actor):item = await owned(db, Work, work_id, user)ensure_kept(item)check_version(item, body.version)+ await _ensure_work_idle(db, item.id)if item.blocked:fail("作品已被管理员封禁")+ if item.audit_status in ("pending", "processing", "approved"):+ return await work_data(db, item, True)await asset_owned(db, item.asset_id or 0, user)rights = await rights_for(db, item.asset_id, lock=True)if not item.license_scope.strip():@@ -155,6 +177,7 @@ async def submit_work(work_id: int, body: Version, db: DB, user: Actor):item.audit_status, item.listed, item.reason = "processing", False, "正在生成试看播放文件"else:item.audit_status, item.listed, item.reason = "pending", False, ""+ config = Noneif item.sale_type == "platform_unlock":config = await db.get(RevenueConfig, 1)if not config or not config.enabled:@@ -162,13 +185,17 @@ async def submit_work(work_id: int, body: Version, db: DB, user: Actor):if item.unlock_price_fen <= 0:fail("平台投放作品必须设置解锁价", 409)if item.audit_status in ("pending", "processing"):+ await _pause_work_sales(db, item.id)publication = (await db.execute(select(Publication).where(Publication.content_type == "work", Publication.content_id == item.id,Publication.version == item.version).with_for_update())).scalar_one_or_none()+ if publication and publication.audit_status == "approved":+ item.version += 1+ publication = Nonevalues = dict(owner_id=user.id, version=item.version, asset_id=item.asset_id,cover_asset_id=item.cover_asset_id, sale_type=item.sale_type,copyright_price_fen=item.price_fen, unlock_price_fen=item.unlock_price_fen,- share_bps=item.share_bps, rights_snapshot={"details": rights.details,+ share_bps=item.share_bps if item.share_bps is not None else (config.platform_share_bps if config else None), rights_snapshot={"details": rights.details,"certificate_asset_id": rights.certificate_asset_id, "evidence_ids": rights.evidence_ids},audit_status=item.audit_status if item.audit_status == "pending" else "draft",preview_status=("done" if watermark_ready else "pending") if requires_preview(item.sale_type) else "none",@@ -229,6 +256,7 @@ async def listing(work_id: int, body: Version, db: DB, user: Actor, listed: boolif not publication or publication.playback_status != "done":fail("平台播放版本尚未就绪,请稍后再上架", 409)item.listed = listed+ await _pause_work_sales(db, item.id)publication = (await db.execute(select(Publication).where(Publication.content_type == "work", Publication.content_id == item.id, Publication.version == item.version).with_for_update())).scalar_one_or_none()if publication:publication.listed = listed and publication.audit_status == "approved" and (item.sale_type != "platform_unlock" or publication.playback_status == "done")@@ -297,8 +325,23 @@ async def save_rights(asset_id: int, body: RightsInput, db: DB, user: Actor):item.basic_status, item.full_status = "draft", "draft"related = (await db.execute(select(Work).where(Work.asset_id == asset_id).with_for_update())).scalars().all()for work in related:+ await _ensure_work_idle(db, work.id)work.audit_status, work.listed = "draft", Falsework.version += 1+ await _pause_work_sales(db, work.id)+ related_episodes = list((await db.execute(select(SeriesEpisode).where(+ SeriesEpisode.asset_id == asset_id).with_for_update())).scalars().all())+ if related_episodes:+ from .series import ensure_series_idle, pause_series_sales+ for episode in related_episodes:+ episode.version += 1+ episode.audit_status, episode.listed = "draft", False+ for series_id in sorted({episode.series_id for episode in related_episodes}):+ series = (await db.execute(select(Series).where(Series.id == series_id).with_for_update())).scalar_one()+ await ensure_series_idle(db, series.id)+ series.version += 1+ series.audit_status, series.listed = "draft", False+ await pause_series_sales(db, series)await db.flush()event(db, user.id, "rights", item.id, "updated", version=item.version)await db.commit()diff --git a/backend/app/marketplace/bootstrap.py b/backend/app/marketplace/bootstrap.pyindex bf3f671..362389a 100644--- a/backend/app/marketplace/bootstrap.py+++ b/backend/app/marketplace/bootstrap.py@@ -1,40 +1,36 @@"""唯一的原项目接入点:能力发现、路由挂载和独立表初始化。"""from fastapi import Depends, FastAPI-from .config import get_marketplace_settings+from .config import is_marketplace_enableddef install(app: FastAPI) -> None:- """默认不加载模型、路由、后台进程;能力发现可用于隐藏菜单。"""+ """始终挂上路由。关闭时业务接口返回未启用,能力接口仍可给菜单判断。"""@app.get("/api/marketplace/capabilities", tags=["下游能力"], response_model=dict)async def capabilities():"""仅报告配置状态,不将配置完整误报为 OSS 联调通过。"""from .storage import configured- enabled = get_marketplace_settings().enabled+ enabled = is_marketplace_enabled()from app.config import get_settingssettings = get_settings()return {"enabled": enabled, "storage_configured": enabled and configured(), "payments": enabled and bool(settings.epay_pid and settings.epay_key and settings.epay_api_url)}- if not get_marketplace_settings().enabled:- return- from . import admin, api, authorization, media, uploads, workspace, series, commerce, handoff+ from . import admin, api, authorization, media, uploads, workspace, series, commerce, handoff, drama_publishfrom .dependencies import enabled- from .models import MarketBase- from app.database import engine- for router in (api.router, uploads.router, workspace.router, media.router, authorization.router, series.router, commerce.router, handoff.router):+ for router in (api.router, uploads.router, workspace.router, media.router, authorization.router, series.router, commerce.router, handoff.router, drama_publish.router):app.include_router(router, prefix="/api/marketplace", dependencies=[Depends(enabled)], tags=["下游作品与招募"])app.include_router(admin.router, prefix="/api/admin/marketplace", dependencies=[Depends(enabled)], tags=["下游运营"])- @app.on_event("startup")- async def initialize_marketplace():- """只创建独立 metadata 中的新表,不迁移原业务数据。"""- async with engine.begin() as conn:- await conn.run_sync(MarketBase.metadata.create_all)- from .runtime import start_marketplace_runtime- await start_marketplace_runtime()- @app.on_event("shutdown")- async def shutdown_marketplace():- from .runtime import stop_marketplace_runtime+async def apply_marketplace_switch() -> None:+ """打开时创建市场表并启动 Worker;关闭时只停 Worker,不删表和文件。"""+ from .runtime import start_marketplace_runtime, stop_marketplace_runtime+ if not is_marketplace_enabled():await stop_marketplace_runtime()+ return+ from app.database import engine+ from .models import MarketBase+ async with engine.begin() as conn:+ await conn.run_sync(MarketBase.metadata.create_all)+ await start_marketplace_runtime()diff --git a/backend/app/marketplace/commerce.py b/backend/app/marketplace/commerce.pyindex 792ee23..ff38035 100644--- a/backend/app/marketplace/commerce.py+++ b/backend/app/marketplace/commerce.py@@ -4,18 +4,21 @@ from __future__ import annotationsimport timeimport uuidfrom datetime import datetime, timezone+from decimal import Decimal, InvalidOperationfrom fastapi import APIRouter, Query, Requestfrom fastapi.responses import PlainTextResponsefrom sqlalchemy import func, select+from sqlalchemy.dialects.postgresql import insertfrom app.config import get_settings+from app.models import Userfrom app.services import epayfrom . import storagefrom .dependencies import Actor, DB, Visitor, storage_ready-from .models import Asset, ContentOrder, Entitlement, Publication, RevenueConfig, RevenueLedger, SeriesEpisode, Work+from .models import Asset, ContentOrder, Entitlement, Publication, RevenueConfig, RevenueLedger, Rights, Series, SeriesEpisode, Workfrom .schemas import ContentOrderInput-from .service import data, fail, now+from .service import data, event, fail, now, rights_validrouter = APIRouter()@@ -30,7 +33,76 @@ def _payment_ready() -> bool:def _publication_public(item: Publication) -> bool:- return bool(item.audit_status == "approved" and item.listed and item.sale_type == "platform_unlock" and item.unlock_price_fen > 0 and item.playback_manifest_key)+ return bool(item.audit_status == "approved" and item.listed and item.sale_type == "platform_unlock" and item.unlock_price_fen > 0 and item.playback_status == "done" and item.playback_manifest_key)+++async def _publication_restriction(db: DB, publication: Publication) -> str:+ """购买后的播放保留旧快照,但实时执行封禁与该版本资产的权属限制。"""+ owner = await db.get(User, publication.owner_id)+ if not owner:+ return "作者账号不可用"+ # 账号模型当前没有封禁字段;不引入或修改原用户表。+ if publication.content_type == "work":+ item = await db.get(Work, publication.content_id)+ if not item or item.owner_id != publication.owner_id:+ return "作品不可用"+ if item.blocked:+ return "作品已被限制播放"+ elif publication.content_type == "series_episode":+ item = await db.get(SeriesEpisode, publication.content_id)+ series = await db.get(Series, item.series_id) if item else None+ if not item or not series or item.owner_id != publication.owner_id or series.owner_id != publication.owner_id:+ return "分集不可用"+ if item.blocked or series.blocked:+ return "系列或分集已被限制播放"+ else:+ return "不支持的发布内容"+ rights = (await db.execute(select(Rights).where(Rights.asset_id == publication.asset_id))).scalar_one_or_none()+ if not rights or rights.owner_id != publication.owner_id or rights.blocked or (rights.valid_until and rights.valid_until <= now()):+ return "该发布版本的权属已受限制"+ return ""+++async def _current_sale(db: DB, publication: Publication) -> bool:+ """Publication.listed 只是快照标记,不能代替父内容当前可售状态。"""+ if not _publication_public(publication) or await _publication_restriction(db, publication):+ return False+ if publication.share_bps is None or not 0 <= publication.share_bps <= 10000:+ return False+ if publication.content_type == "work":+ item = await db.get(Work, publication.content_id)+ parent = item+ else:+ item = await db.get(SeriesEpisode, publication.content_id)+ parent = await db.get(Series, item.series_id)+ if (item.version != publication.version or item.asset_id != publication.asset_id+ or item.audit_status != "approved" or not item.listed+ or parent.audit_status != "approved" or not parent.listed+ or parent.deleted_at or parent.sale_type != "platform_unlock"):+ return False+ asset = await db.get(Asset, publication.asset_id)+ rights = (await db.execute(select(Rights).where(Rights.asset_id == publication.asset_id))).scalar_one_or_none()+ return bool(asset and asset.owner_id == publication.owner_id and asset.status == "ready" and rights_valid(rights, full=True))+++async def _publication_playback(db: DB, user: User, publication: Publication) -> dict:+ entitlement = (await db.execute(select(Entitlement).where(+ Entitlement.user_id == user.id, Entitlement.publication_id == publication.id,+ Entitlement.active.is_(True)))).scalar_one_or_none()+ if not entitlement:+ fail("MARKETPLACE_ENTITLEMENT_REQUIRED", 403)+ restriction = await _publication_restriction(db, publication)+ if restriction:+ fail(restriction, 403)+ if publication.sale_type != "platform_unlock" or publication.audit_status != "approved":+ fail("该发布版本不可播放", 403)+ asset = await db.get(Asset, publication.asset_id)+ if not asset or asset.owner_id != publication.owner_id or asset.status != "ready" or publication.playback_status != "done" or not publication.playback_manifest_key:+ fail("MARKETPLACE_EPISODE_NOT_READY", 409)+ await storage_ready()+ manifest = await _signed_hls_manifest(publication)+ from .config import get_marketplace_settings+ return {"publication_id": publication.id, "manifest": manifest, "kind": "hls", "expires_in": get_marketplace_settings().signed_url_seconds}async def _signed_hls_manifest(publication: Publication) -> str:@@ -80,7 +152,7 @@ async def platform_episode(episode_id: int, db: DB, user: Visitor):Publication.version == episode.version, Publication.audit_status == "approved",Publication.listed.is_(True), Publication.sale_type == "platform_unlock",))).scalar_one_or_none()- if not publication or publication.sale_type != "platform_unlock":+ if not publication or not await _current_sale(db, publication):fail("分集尚未公开", 404)entitled = bool(user and (await db.execute(select(Entitlement.id).where(Entitlement.user_id == user.id, Entitlement.publication_id == publication.id, Entitlement.active.is_(True)))).scalar_one_or_none())return {**data(publication, "id", "content_type", "content_id", "version", "sale_type", "copyright_price_fen", "unlock_price_fen", "created_at"), "entitled": entitled, "playback_ready": bool(publication.playback_manifest_key)}@@ -96,7 +168,7 @@ async def platform_work(work_id: int, db: DB, user: Visitor):Publication.content_type == "work", Publication.content_id == work.id,Publication.version == work.version, Publication.audit_status == "approved",Publication.listed.is_(True), Publication.sale_type == "platform_unlock"))).scalar_one_or_none()- if not publication or publication.sale_type != "platform_unlock":+ if not publication or not await _current_sale(db, publication):fail("作品尚未公开", 404)entitled = bool(user and (await db.execute(select(Entitlement.id).where(Entitlement.user_id == user.id, Entitlement.publication_id == publication.id,@@ -108,20 +180,33 @@ async def platform_work(work_id: int, db: DB, user: Visitor):async def create_content_order(body: ContentOrderInput, request: Request, db: DB, user: Actor):if not _payment_ready():fail("MARKETPLACE_PAYMENT_UNAVAILABLE", 503)- publication = await db.get(Publication, body.publication_id)- if not publication or not _publication_public(publication):+ prior = (await db.execute(select(ContentOrder).where(ContentOrder.idempotency_key == body.idempotency_key).with_for_update())).scalar_one_or_none()+ if prior:+ if prior.user_id != user.id or prior.publication_id != body.publication_id or prior.pay_type != body.pay_type:+ fail("幂等键与原请求不一致", 409)+ return {"out_trade_no": prior.out_trade_no, "status": prior.status, "amount_fen": prior.amount_fen}+ publication = (await db.execute(select(Publication).where(Publication.id == body.publication_id).with_for_update())).scalar_one_or_none()+ if not publication:fail("内容尚未开放购买", 409)existing = (await db.execute(select(Entitlement).where(Entitlement.user_id == user.id, Entitlement.publication_id == publication.id, Entitlement.active.is_(True)))).scalar_one_or_none()if existing:return {"entitled": True, "publication_id": publication.id, "status": "paid"}- prior = (await db.execute(select(ContentOrder).where(ContentOrder.idempotency_key == body.idempotency_key).with_for_update())).scalar_one_or_none()- if prior:- if prior.user_id != user.id:- fail("幂等键已被其他账号使用", 409)- return {"out_trade_no": prior.out_trade_no, "status": prior.status, "amount_fen": prior.amount_fen}+ if not await _current_sale(db, publication):+ fail("内容尚未开放购买", 409)out_trade_no = f"MKT{int(time.time())}{user.id:04d}{uuid.uuid4().hex[:10]}"- order = ContentOrder(out_trade_no=out_trade_no, user_id=user.id, publication_id=publication.id, episode_id=publication.content_id if publication.content_type == "series_episode" else None, amount_fen=int(publication.unlock_price_fen), pay_type=body.pay_type, idempotency_key=body.idempotency_key)- db.add(order)+ inserted = await db.execute(insert(ContentOrder).values(+ out_trade_no=out_trade_no, user_id=user.id, publication_id=publication.id,+ episode_id=publication.content_id if publication.content_type == "series_episode" else None,+ amount_fen=int(publication.unlock_price_fen), pay_type=body.pay_type,+ idempotency_key=body.idempotency_key,+ ).on_conflict_do_nothing(index_elements=[ContentOrder.idempotency_key]).returning(ContentOrder.id))+ order_id = inserted.scalar_one_or_none()+ if order_id is None:+ prior = (await db.execute(select(ContentOrder).where(ContentOrder.idempotency_key == body.idempotency_key))).scalar_one()+ if prior.user_id != user.id or prior.publication_id != publication.id or prior.pay_type != body.pay_type:+ fail("幂等键与原请求不一致", 409)+ return {"out_trade_no": prior.out_trade_no, "status": prior.status, "amount_fen": prior.amount_fen}+ order = await db.get(ContentOrder, order_id)await db.commit()try:notify_url = f"{get_settings().public_base_url.rstrip('/')}/api/marketplace/payments/epay/notify"@@ -161,24 +246,7 @@ async def episode_playback(episode_id: int, db: DB, user: Actor):))).scalar_one_or_none()if not publication or publication.sale_type != "platform_unlock":fail("分集尚未公开", 404)- # Playback always goes through the configured private bucket. Keep this- # explicit because the route opts out of the router dependency list so the- # entitlement check can return a precise 403 first.- await storage_ready()- if publication.sale_type == "platform_unlock":- entitlement = (await db.execute(select(Entitlement).where(Entitlement.user_id == user.id, Entitlement.publication_id == publication.id, Entitlement.active.is_(True)))).scalar_one_or_none()- if not entitlement:- fail("MARKETPLACE_ENTITLEMENT_REQUIRED", 403)- if not publication.playback_manifest_key:- fail("MARKETPLACE_EPISODE_NOT_READY", 409)- manifest = await _signed_hls_manifest(publication)- # 返回重写后的清单文本和过期时间;客户端应创建 Blob URL 播放,分片签名与清单同周期。- return {"manifest": manifest, "kind": "hls", "expires_in": 300}- asset = await db.get(Asset, publication.asset_id)- if not asset or asset.status != "ready":- fail("媒体尚未就绪", 409)- url = await __import__("asyncio").to_thread(storage.signed, asset.object_key, asset.content_type)- return {"url": url, "kind": "original", "expires_in": 300}+ return await _publication_playback(db, user, publication)@router.get("/platform/works/{work_id}/playback", response_model=dict, dependencies=[])@@ -192,22 +260,16 @@ async def work_playback(work_id: int, db: DB, user: Actor):Publication.listed.is_(True), Publication.sale_type == "platform_unlock"))).scalar_one_or_none()if not publication or publication.sale_type != "platform_unlock":fail("作品尚未公开", 404)- # Same storage boundary as episode playback; no local/static fallback is- # allowed for marketplace media.- await storage_ready()- if publication.sale_type == "platform_unlock":- entitlement = (await db.execute(select(Entitlement).where(- Entitlement.user_id == user.id, Entitlement.publication_id == publication.id,- Entitlement.active.is_(True)))).scalar_one_or_none()- if not entitlement:- fail("MARKETPLACE_ENTITLEMENT_REQUIRED", 403)- manifest = await _signed_hls_manifest(publication)- return {"manifest": manifest, "kind": "hls", "expires_in": 300}- asset = await db.get(Asset, publication.asset_id)- if not asset or asset.status != "ready":- fail("媒体尚未就绪", 409)- url = await __import__("asyncio").to_thread(storage.signed, asset.object_key, asset.content_type)- return {"url": url, "kind": "original", "expires_in": 300}+ return await _publication_playback(db, user, publication)++[email protected]("/platform/publications/{publication_id}/playback", response_model=dict)+async def publication_playback(publication_id: int, db: DB, user: Actor):+ """从永久权益打开购买时版本;作者编辑、主动下架不撤销已购在线播放。"""+ publication = await db.get(Publication, publication_id)+ if not publication:+ fail("发布版本不存在", 404)+ return await _publication_playback(db, user, publication)def _notify_success(params: dict[str, str]) -> bool:@@ -216,6 +278,8 @@ def _notify_success(params: dict[str, str]) -> bool:@router.api_route("/payments/epay/notify", methods=["GET", "POST"])async def epay_notify(request: Request, db: DB) -> PlainTextResponse:+ if not _payment_ready():+ return PlainTextResponse("fail", status_code=503)if request.method == "POST":form = await request.form()params = {key: str(value) for key, value in form.items()}@@ -230,16 +294,29 @@ async def epay_notify(request: Request, db: DB) -> PlainTextResponse:if not order:return PlainTextResponse("fail", status_code=404)try:- paid_fen = int(round(float(params.get("money") or 0) * 100))- except ValueError:- paid_fen = order.amount_fen+ amount = Decimal(str(params.get("money") or "")) * 100+ if not amount.is_finite() or amount != amount.to_integral_value():+ raise ValueError("invalid amount")+ paid_fen = int(amount)+ except (ValueError, InvalidOperation):+ return PlainTextResponse("fail", status_code=400)if paid_fen != order.amount_fen:return PlainTextResponse("fail", status_code=400)if order.status == "paid":return PlainTextResponse("success")- publication = await db.get(Publication, order.publication_id)- if not publication or not _publication_public(publication):- return PlainTextResponse("fail", status_code=409)+ # Serialize callbacks for the same publication as well as the order. Two+ # different checkout attempts must not race the unique permanent entitlement.+ publication = (await db.execute(select(Publication).where(+ Publication.id == order.publication_id).with_for_update())).scalar_one_or_none()+ if not publication:+ return PlainTextResponse("fail", status_code=404)+ # A verified payment belongs to its frozen order, even if the author has+ # since edited/unlisted the content or an operator has blocked playback.+ order.status, order.trade_no, order.paid_at = "paid", str(params.get("trade_no") or params.get("transaction_id") or "") or None, datetime.now(timezone.utc)+ restriction = await _publication_restriction(db, publication)+ if restriction or publication.audit_status != "approved":+ event(db, order.user_id, "content_order", order.id, "paid_restricted_review",+ restriction or "付款时发布版本已受审核限制", publication.version)# Two checkout attempts can race before the first callback creates the# entitlement. The unique entitlement is the idempotency boundary for a# user's permanent access; acknowledge the later payment without creating@@ -247,19 +324,25 @@ async def epay_notify(request: Request, db: DB) -> PlainTextResponse:existing_entitlement = (await db.execute(select(Entitlement).where(Entitlement.user_id == order.user_id,Entitlement.publication_id == publication.id,- Entitlement.active.is_(True),).with_for_update())).scalar_one_or_none()if existing_entitlement:- order.status, order.trade_no, order.paid_at = "paid", str(params.get("trade_no") or params.get("transaction_id") or "") or None, datetime.now(timezone.utc)+ event(db, order.user_id, "content_order", order.id, "duplicate_purchase_paid",+ "同一发布版本已有权益,本次付款已确认,需人工核对重复收款;不重复计创作者收益", publication.version)await db.commit()return PlainTextResponse("success")- order.status, order.trade_no, order.paid_at = "paid", str(params.get("trade_no") or params.get("transaction_id") or "") or None, datetime.now(timezone.utc)entitlement = Entitlement(user_id=order.user_id, publication_id=publication.id, episode_id=order.episode_id, order_id=order.id)db.add(entitlement)- config = await db.get(RevenueConfig, 1)- share = publication.share_bps if publication.share_bps is not None else (config.platform_share_bps if config else None)+ share = publication.share_bpsif share is None:- return PlainTextResponse("fail", status_code=409)+ # Legacy checkout records may predate frozen revenue shares. Confirm+ # the cash receipt without inventing an allocation if no config exists.+ config = await db.get(RevenueConfig, 1)+ share = config.platform_share_bps if config else None+ event(db, order.user_id, "content_order", order.id, "paid_legacy_share_review",+ "历史发布版本没有冻结分成;已确认付款及权益,需要人工核对分成", publication.version)+ if share is None or not 0 <= int(share) <= 10000:+ await db.commit()+ return PlainTextResponse("success")platform_fen = order.amount_fen * int(share) // 10000ledger = RevenueLedger(order_id=order.id, publication_id=publication.id, owner_id=publication.owner_id, gross_fen=order.amount_fen, platform_fen=platform_fen, creator_fen=order.amount_fen - platform_fen, share_bps=int(share))db.add(ledger)diff --git a/backend/app/marketplace/config.py b/backend/app/marketplace/config.pyindex 6c0be42..03fc313 100644--- a/backend/app/marketplace/config.py+++ b/backend/app/marketplace/config.py@@ -28,3 +28,9 @@ class MarketplaceSettings(BaseSettings):def get_marketplace_settings() -> MarketplaceSettings:"""缓存独立配置;生产使用环境变量,本地可保持为空。"""return MarketplaceSettings()+++def is_marketplace_enabled() -> bool:+ """菜单和接口以系统设置里的开关为准;还没保存过时回落到 MARKETPLACE_ENABLED。"""+ from app.config import get_settings+ return bool(get_settings().marketplace_enabled)diff --git a/backend/app/marketplace/dependencies.py b/backend/app/marketplace/dependencies.pyindex 4a52fc5..b1907c0 100644--- a/backend/app/marketplace/dependencies.py+++ b/backend/app/marketplace/dependencies.py@@ -9,7 +9,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.database import get_dbfrom app.deps import get_current_admin, get_current_user, security, _user_from_bearerfrom app.models import User-from .config import get_marketplace_settings+from .config import is_marketplace_enabledfrom . import storageDB = Annotated[AsyncSession, Depends(get_db)]@@ -19,7 +19,7 @@ Admin = Annotated[User, Depends(get_current_admin)]def enabled() -> None:"""关闭时不允许通过直接 URL 进入下游接口。"""- if not get_marketplace_settings().enabled:+ if not is_marketplace_enabled():raise HTTPException(404, "下游业务未启用")diff --git a/backend/app/marketplace/drama_media.py b/backend/app/marketplace/drama_media.pynew file mode 100644index 0000000..0cb1b0f--- /dev/null+++ b/backend/app/marketplace/drama_media.py@@ -0,0 +1,349 @@+"""只读漫剧来源,独立制作市场成片;不调用原漫剧合成或公开发布函数。"""+from __future__ import annotations++import asyncio+from fractions import Fraction+import hashlib+import json+import math+from pathlib import Path+import tempfile+from urllib.parse import unquote, urlparse++from app.config import get_settings+from app.services.storage import STATIC_ROOT+from . import storage+from .config import get_marketplace_settings+from .worker import cache_root, command, fingerprint++_FORMATS = "mov,mp4,matroska,webm"+_VIDEO_FIELDS = ("codec_name", "profile", "level", "codec_tag_string", "width", "height", "pix_fmt",+ "sample_aspect_ratio", "r_frame_rate", "avg_frame_rate", "time_base", "field_order",+ "color_range", "color_space", "color_transfer", "color_primaries", "extradata")+_AUDIO_FIELDS = ("codec_name", "profile", "codec_tag_string", "sample_rate", "channels", "channel_layout",+ "sample_fmt", "time_base", "extradata")+++def _error(code: str, message: str) -> ValueError:+ return ValueError(f"MARKETPLACE_{code}:{message}")+++def _local_source(locator: str) -> Path | None:+ """仅解释本站 static URL 或 static 根内的绝对路径,不根据任意远程路径猜本地文件。"""+ text = locator.strip()+ raw = ""+ if text.startswith("/static/"):+ raw = unquote(text[len("/static/"):].split("?", 1)[0])+ elif text.startswith(("http://", "https://")):+ parsed, base = urlparse(text), urlparse(get_settings().public_base_url.rstrip("/"))+ prefix = base.path.rstrip("/") + "/static/"+ if parsed.scheme == base.scheme and parsed.netloc == base.netloc and parsed.path.startswith(prefix):+ raw = unquote(parsed.path[len(prefix):])+ else:+ return None+ else:+ candidate = Path(text)+ if not candidate.is_absolute():+ return None+ path = candidate.resolve()+ try:+ path.relative_to(STATIC_ROOT.resolve())+ except ValueError as exc:+ raise _error("SOURCE_NOT_READY", "不允许读取项目媒体目录之外的文件") from exc+ return path+ if not raw or "\\" in raw or ".." in Path(raw).parts:+ raise _error("SOURCE_NOT_READY", "源视频路径无效")+ path = (STATIC_ROOT / raw).resolve()+ try:+ path.relative_to(STATIC_ROOT.resolve())+ except ValueError as exc:+ raise _error("SOURCE_NOT_READY", "源视频路径超出项目媒体目录") from exc+ return path+++def _source_key(locator: str) -> str:+ """只接受配置桶、明确配置的 CDN 基址或上游 generated 对象键。"""+ settings = get_settings()+ folder = settings.oss_folder.strip().strip("/") or "kepu"+ prefix = folder + "/generated/"+ text = locator.strip()+ if text.startswith(("http://", "https://")):+ parsed = urlparse(text)+ if parsed.username or parsed.password or parsed.fragment:+ raise _error("SOURCE_NOT_READY", "源视频地址无效")+ endpoint = urlparse(settings.oss_endpoint if "://" in settings.oss_endpoint else "https://" + settings.oss_endpoint)+ endpoint_host = (endpoint.hostname or "").lower()+ hosts = {f"{settings.oss_bucket}.{endpoint_host}"}+ if "-internal" in endpoint_host:+ hosts.add(f"{settings.oss_bucket}.{endpoint_host.replace('-internal', '')}")+ public = urlparse(settings.oss_public_base.rstrip("/")) if settings.oss_public_base else None+ if public and parsed.scheme == public.scheme and parsed.netloc == public.netloc:+ base_path = public.path.rstrip("/") + "/"+ if not parsed.path.startswith(base_path):+ raise _error("SOURCE_NOT_READY", "源视频不属于配置的媒体目录")+ key = unquote(parsed.path[len(base_path):])+ elif parsed.scheme == "https" and parsed.hostname in hosts and parsed.port in (None, 443):+ key = unquote(parsed.path.lstrip("/"))+ else:+ raise _error("SOURCE_NOT_READY", "源视频不属于配置的 OSS 桶")+ else:+ key = text+ if not settings.oss_bucket or not key.startswith(prefix) or "\\" in key or ".." in key.split("/") or "?" in key or "#" in key:+ raise _error("SOURCE_NOT_READY", "源视频不属于上游生成目录")+ return key+++def _stat_stamp(path: Path) -> dict:+ if not path.is_file():+ raise _error("SOURCE_NOT_READY", "源视频文件不存在")+ stat = path.stat()+ return {"size_bytes": stat.st_size, "mtime_ns": stat.st_mtime_ns, "file_id": f"{stat.st_dev}:{stat.st_ino}"}+++def source_stamp(locator: str) -> dict:+ """冻结源文件版本,结果仅保存在服务端,不向浏览器暴露文件路径或对象键。"""+ text = (locator or "").strip()+ if not text:+ raise _error("SOURCE_NOT_READY", "分镜视频尚未生成")+ local = _local_source(text)+ if local is not None:+ before = _stat_stamp(local)+ digest = fingerprint(local)+ if before != _stat_stamp(local):+ raise _error("SOURCE_CHANGED", "源视频正在更新,请稍后重新选择")+ result = {"kind": "local", "locator": str(local), **before, "fingerprint": digest}+ else:+ key = _source_key(text)+ result = {"kind": "oss", "locator": key, "key": key, **storage.source_metadata(key)}+ if not 0 < result["size_bytes"] <= get_marketplace_settings().max_video_bytes:+ raise _error("SOURCE_NOT_READY", "源视频为空或超过市场视频大小限制")+ return result+++def stamp_version(stamp: dict) -> str:+ """签名 URL 过期时间不参与版本;只散列安全解析后的地址和文件身份。"""+ payload = {key: stamp.get(key) for key in ("kind", "locator", "key", "size_bytes", "mtime_ns", "file_id", "etag", "fingerprint")}+ return hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()).hexdigest()+++async def _thread(function, *args):+ """取消任务时先等待本地文件操作结束,再清理临时目录。"""+ task = asyncio.create_task(asyncio.to_thread(function, *args))+ try:+ return await asyncio.shield(task)+ except asyncio.CancelledError:+ await asyncio.gather(task, return_exceptions=True)+ raise+++def _copy_source(clip: dict, output: Path) -> None:+ expected = clip.get("stamp") or {}+ current = source_stamp(str(clip.get("locator") or ""))+ if stamp_version(current) != stamp_version(expected):+ raise _error("SOURCE_CHANGED", "源视频已更新,请重新选择分集")+ if current["kind"] == "local":+ digest = hashlib.sha256()+ with Path(current["locator"]).open("rb") as source, output.open("wb") as target:+ for chunk in iter(lambda: source.read(1024 * 1024), b""):+ target.write(chunk)+ digest.update(chunk)+ if digest.hexdigest() != current["fingerprint"]:+ raise _error("SOURCE_CHANGED", "复制过程中源视频发生变化")+ else:+ storage.download_version(current["key"], output, current["etag"])+ after = source_stamp(str(clip["locator"]))+ if stamp_version(after) != stamp_version(expected) or output.stat().st_size != expected["size_bytes"]:+ raise _error("SOURCE_CHANGED", "复制过程中源视频发生变化")+++async def _probe(path: Path) -> dict:+ settings = get_settings()+ try:+ probe = json.loads(await command(settings.ffprobe_path, "-v", "error", "-protocol_whitelist", "file,pipe",+ "-format_whitelist", _FORMATS, "-show_streams", "-show_format", "-show_data", "-of", "json", str(path), timeout=60))+ video = next(stream for stream in probe.get("streams", []) if stream.get("codec_type") == "video" and not stream.get("disposition", {}).get("attached_pic"))+ duration = float(probe.get("format", {}).get("duration", 0))+ width, height = int(video["width"]), int(video["height"])+ if width < 2 or height < 2 or width * height > 50_000_000 or not math.isfinite(duration) or duration <= 0:+ raise ValueError("invalid media")+ audio = next((stream for stream in probe.get("streams", []) if stream.get("codec_type") == "audio"), None)+ return {"video": video, "audio": audio, "duration": duration, "width": width, "height": height}+ except (ValueError, KeyError, StopIteration) as exc:+ raise _error("SOURCE_NOT_READY", "分镜视频无法解析或尺寸无效") from exc+++def _signature(info: dict) -> tuple:+ video, audio = info["video"], info["audio"]+ return (tuple(video.get(key) for key in _VIDEO_FIELDS), tuple(audio.get(key) for key in _AUDIO_FIELDS) if audio else None,+ video.get("side_data_list", []), video.get("tags", {}).get("rotate"))+++def _dimensions(info: dict) -> tuple[int, int]:+ video = info["video"]+ rotation = float(video.get("tags", {}).get("rotate") or 0)+ for side in video.get("side_data_list", []):+ if "rotation" in side:+ rotation = float(side["rotation"])+ width, height = info["width"], info["height"]+ if round(rotation) % 180:+ width, height = height, width+ sar = video.get("sample_aspect_ratio") or "1:1"+ try:+ pixel_ratio = float(Fraction(sar.replace(":", "/"))) if sar not in ("N/A", "0:1") else 1.0+ except (ValueError, ZeroDivisionError):+ pixel_ratio = 1.0+ # 扩大显示尺寸以消除非方形像素,绝不缩小来源像素。+ if pixel_ratio > 1:+ width = math.ceil(width * pixel_ratio)+ elif 0 < pixel_ratio < 1:+ height = math.ceil(height / pixel_ratio)+ return width, height+++async def _concat(paths: list[Path], output: Path, timeout: float) -> None:+ listing = output.with_suffix(".txt")+ listing.write_text("\n".join(f"file '{path.name}'" for path in paths), encoding="utf-8")+ await command(get_settings().ffmpeg_path, "-y", "-v", "error", "-protocol_whitelist", "file,pipe", "-f", "concat",+ "-safe", "1", "-i", str(listing), "-map", "0:v:0", "-map", "0:a:0?", "-sn", "-dn", "-c", "copy",+ "-movflags", "+faststart", str(output), timeout=timeout)+++async def _encode(paths: list[Path], infos: list[dict], output: Path, timeout: float) -> None:+ sizes = [_dimensions(info) for info in infos]+ ratio = sizes[0][0] / sizes[0][1]+ if any(abs(width / height / ratio - 1) > 0.005 for width, height in sizes):+ raise _error("SOURCE_INCOMPATIBLE", "分镜画幅比例不一致,请先统一画幅后发布")+ width = math.ceil(max(size[0] for size in sizes) / 2) * 2+ height = math.ceil(max(size[1] for size in sizes) / 2) * 2+ if width * height > 50_000_000:+ raise _error("SOURCE_INCOMPATIBLE", "合成画面尺寸超出限制")+ fps = Fraction(1, 1)+ for info in infos:+ try:+ value = Fraction(info["video"].get("avg_frame_rate") or info["video"].get("r_frame_rate") or "30")+ except (ValueError, ZeroDivisionError):+ value = Fraction(30, 1)+ fps = max(fps, value)+ if fps > 240:+ raise _error("SOURCE_INCOMPATIBLE", "分镜帧率超出支持范围")+ audio = any(info["audio"] for info in infos)+ normalized = []+ for index, (source, info) in enumerate(zip(paths, infos)):+ dest = output.parent / f"normalized-{index:04d}.mp4"+ args = [get_settings().ffmpeg_path, "-y", "-v", "error", "-protocol_whitelist", "file,pipe",+ "-format_whitelist", _FORMATS, "-i", str(source)]+ if audio and not info["audio"]:+ args += ["-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo"]+ args += ["-map", "0:v:0"]+ if audio:+ args += ["-map", "0:a:0" if info["audio"] else "1:a:0", "-af",+ f"aresample=48000:async=1:first_pts=0,apad,atrim=duration={info['duration']}",+ "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2"]+ # 同画幅因像素取整略有差异时补边,避免把人物画面拉伸。+ args += ["-sn", "-dn", "-t", str(info["duration"]), "-vf",+ f"scale={width}:{height}:force_original_aspect_ratio=decrease:flags=lanczos,"+ f"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setsar=1,setpts=PTS-STARTPTS", "-r", str(fps),+ "-c:v", "libx264", "-preset", "fast", "-crf", "18", "-pix_fmt", "yuv420p",+ "-threads", "2", "-video_track_timescale", "90000", "-movflags", "+faststart", str(dest)]+ await command(*args, timeout=timeout)+ normalized.append(dest)+ await _concat(normalized, output, timeout)+++async def prepare_drama_video(snapshot: dict, dest_key: str, progress=None) -> dict:+ """制作全部分镜的独立成片,上传成功后才返回可绑定的媒体元数据。"""+ if snapshot.get("schema_version") != 2 or not snapshot.get("clips"):+ raise _error("SOURCE_NOT_READY", "漫剧来源快照无效,请重新选择分集")+ if not dest_key.startswith("marketplace/") or ".." in dest_key.split("/") or "\\" in dest_key:+ raise _error("SOURCE_NOT_READY", "市场目标目录无效")+ clips = list(snapshot["clips"])+ if clips != sorted(clips, key=lambda clip: (clip["sort_order"], clip["id"])) or len({clip["id"] for clip in clips}) != len(clips):+ raise _error("SOURCE_NOT_READY", "分镜顺序快照无效")+ settings = get_marketplace_settings()+ if sum(int((clip.get("stamp") or {}).get("size_bytes", 0)) for clip in clips) > settings.max_video_bytes:+ raise _error("SOURCE_NOT_READY", "整集视频超过市场视频大小限制")+ async def phase(value):+ if progress:+ await progress(value)+ with tempfile.TemporaryDirectory(prefix="job-", dir=cache_root()) as directory:+ root = Path(directory)+ await phase("copying")+ sources, infos = [], []+ for index, clip in enumerate(clips):+ source = root / f"source-{index:04d}.mp4"+ await _thread(_copy_source, clip, source)+ sources.append(source)+ infos.append(await _probe(source))+ total = sum(info["duration"] for info in infos)+ if total > settings.max_duration_seconds:+ raise _error("SOURCE_NOT_READY", "整集视频超过市场视频时长限制")+ output = root / "episode.mp4"+ timeout = min(7200, max(120, total * 8 + 60))+ await phase("composing")+ if len(sources) == 1:+ # 单镜头只重新封装,不重新编码或降低画质。+ try:+ await command(get_settings().ffmpeg_path, "-y", "-v", "error", "-protocol_whitelist", "file,pipe",+ "-format_whitelist", _FORMATS, "-i", str(sources[0]), "-map", "0:v:0", "-map", "0:a:0?",+ "-sn", "-dn", "-c", "copy", "-movflags", "+faststart", str(output), timeout=timeout)+ except ValueError as exc:+ raise _error("SOURCE_INCOMPATIBLE", "分镜编码无法无损封装为市场视频") from exc+ else:+ dimensions = [_dimensions(info) for info in infos]+ ratio = dimensions[0][0] / dimensions[0][1]+ if any(abs(width / height / ratio - 1) > 0.005 for width, height in dimensions):+ raise _error("SOURCE_INCOMPATIBLE", "分镜画幅比例不一致,请先统一画幅后发布")+ compatible = all(_signature(info) == _signature(infos[0]) for info in infos[1:])+ copied = False+ if compatible:+ try:+ await _concat(sources, output, timeout)+ combined = await _probe(output)+ copied = abs(combined["duration"] - total) <= max(0.25, total * 0.002)+ except ValueError:+ copied = False+ if not copied:+ await _encode(sources, infos, output, timeout)+ await phase("validating")+ result = await _probe(output)+ if abs(result["duration"] - total) > max(0.25, total * 0.002):+ raise _error("SOURCE_INCOMPATIBLE", "整集合成时长与分镜总时长不一致")+ size = output.stat().st_size+ if not 0 < size <= settings.max_video_bytes:+ raise _error("SOURCE_NOT_READY", "完整成片超过市场视频大小限制")+ if result["duration"] > settings.max_duration_seconds:+ raise _error("SOURCE_NOT_READY", "完整成片超过市场视频时长限制")+ digest = await _thread(fingerprint, output)+ await _thread(storage.upload, dest_key, output, "video/mp4")+ return {"size_bytes": size, "content_type": "video/mp4", "fingerprint": digest, "duration_seconds": result["duration"],+ "width": result["width"], "height": result["height"]}+++async def prepare_drama_cover(locator: str, dest_key: str, stamp: dict | None = None) -> dict:+ """安全复制可选封面,重编码为 PNG;失败由调用方提示用户补充封面。"""+ if not dest_key.startswith("marketplace/") or ".." in dest_key.split("/") or "\\" in dest_key:+ raise _error("SOURCE_NOT_READY", "市场封面目标目录无效")+ expected = stamp if stamp is not None else await _thread(source_stamp, locator)+ if not 0 < int(expected.get("size_bytes", 0)) <= get_marketplace_settings().max_document_bytes:+ raise _error("SOURCE_NOT_READY", "封面为空或超过图片大小限制")+ with tempfile.TemporaryDirectory(prefix="job-", dir=cache_root()) as directory:+ root = Path(directory)+ source, output = root / "cover-source", root / "cover.png"+ await _thread(_copy_source, {"locator": locator, "stamp": expected}, source)+ try:+ probe = json.loads(await command(get_settings().ffprobe_path, "-v", "error", "-protocol_whitelist", "file,pipe",+ "-format_whitelist", "png_pipe,jpeg_pipe,webp_pipe,image2", "-show_streams", "-of", "json", str(source), timeout=60))+ image = next(stream for stream in probe.get("streams", []) if stream.get("codec_type") == "video")+ width, height = int(image["width"]), int(image["height"])+ if image.get("codec_name") not in ("png", "mjpeg", "webp") or min(width, height) < 2 or width * height > 50_000_000:+ raise ValueError("invalid image")+ await command(get_settings().ffmpeg_path, "-y", "-v", "error", "-protocol_whitelist", "file,pipe",+ "-format_whitelist", "png_pipe,jpeg_pipe,webp_pipe,image2", "-i", str(source), "-frames:v", "1", str(output), timeout=60)+ except (ValueError, KeyError, StopIteration) as exc:+ raise _error("SOURCE_NOT_READY", "源封面不是有效的 PNG、JPG 或 WebP 图片,请重新上传封面") from exc+ size = output.stat().st_size+ if not 0 < size <= get_marketplace_settings().max_document_bytes:+ raise _error("SOURCE_NOT_READY", "处理后的封面超过图片大小限制")+ digest = await _thread(fingerprint, output)+ await _thread(storage.upload, dest_key, output, "image/png")+ return {"size_bytes": size, "content_type": "image/png", "fingerprint": digest, "width": width, "height": height}diff --git a/backend/app/marketplace/drama_publish.py b/backend/app/marketplace/drama_publish.pynew file mode 100644index 0000000..14aec29--- /dev/null+++ b/backend/app/marketplace/drama_publish.py@@ -0,0 +1,312 @@+"""漫剧整集到市场的显式快照发布。只读原漫剧,写入独立市场表。"""+from __future__ import annotations++import asyncio+import hashlib+import json++from fastapi import APIRouter, HTTPException+from sqlalchemy import func, or_, select, text, update++from app.models_drama import DramaEpisode, DramaEpisodeFragment, DramaProject+from app.models_tasks import TaskRun+from .authorization import current as current_authorization+from .dependencies import Actor, DB, storage_ready+from .models import DramaPublishBatch, Handoff, Publication, Rights, Series, SeriesEpisode+from .schemas import DramaPublishEpisode, DramaPublishInput+from .service import ensure_kept, fail++router = APIRouter()+ACTIVE = ("pending", "leased", "running", "awaiting_poll", "awaiting_review")+BUSY = ("queued", "running", "generating", "pending", "leased")+++def digest(value) -> str:+ return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False, default=str).encode()).hexdigest()+++def episode_number(episode) -> int:+ try:+ return max(0, int((episode.params or {}).get("episodeNumber") or 0))+ except (ValueError, TypeError):+ return 0+++async def owned_project(db, owner_id: int, project_id: int):+ project = await db.get(DramaProject, project_id)+ if not project or project.user_id != owner_id:+ fail("漫剧项目不存在或无权访问", 404)+ return project+++async def episode_snapshot(db, owner_id: int, project_id: int, episode_id: int) -> dict:+ """服务端保存有序分镜与实际文件身份,不接受客户端传入视频地址。"""+ from .drama_media import source_stamp, stamp_version++ project = await owned_project(db, owner_id, project_id)+ episode = await db.get(DramaEpisode, episode_id)+ if not episode or episode.project_id != project.id:+ fail("存在不属于该漫剧项目的分集", 404)+ fragments = list((await db.execute(select(DramaEpisodeFragment).where(+ DramaEpisodeFragment.episode_id == episode.id+ ).order_by(DramaEpisodeFragment.sort_order, DramaEpisodeFragment.id))).scalars().all())+ active = (await db.execute(select(TaskRun.id).where(+ TaskRun.domain == "drama", TaskRun.task_type.in_(("fragment_video", "fragment_plan")),+ TaskRun.status.in_(ACTIVE),+ or_(TaskRun.episode_id == episode.id, TaskRun.fragment_id.in_([f.id for f in fragments])),+ ).limit(1))).scalar_one_or_none()+ if active or (episode.params or {}).get("fragment_plan_status") in BUSY:+ fail("MARKETPLACE_SOURCE_NOT_READY:分集正在生成视频或重新分镜,请完成后再发布", 409)+ if not fragments or any(not (fragment.video or "").strip() for fragment in fragments):+ fail("MARKETPLACE_SOURCE_NOT_READY:请先完成这一集的全部分镜视频", 409)+ clips = []+ for fragment in fragments:+ params = fragment.params or {}+ generation = params.get("generation") or params.get("video_gen") or params.get("video_generation") or {}+ if (isinstance(generation, dict) and generation.get("status") in BUSY) or params.get("video_status") in BUSY:+ fail("MARKETPLACE_SOURCE_NOT_READY:分镜视频仍在生成中", 409)+ locator = fragment.video.strip()+ try:+ stamp = await asyncio.to_thread(source_stamp, locator)+ except HTTPException:+ raise+ except (ValueError, OSError) as exc:+ fail(str(exc) if str(exc).startswith("MARKETPLACE_") else "MARKETPLACE_SOURCE_NOT_READY:源视频不可用", 409)+ clips.append({"id": fragment.id, "sort_order": fragment.sort_order, "locator": locator,+ "stamp": stamp, "updated_at": fragment.updated_at.isoformat(),+ "cover": fragment.cover or ""})+ snapshot = {"schema_version": 2, "drama_project_id": project.id, "drama_episode_id": episode.id,+ "episode_number": episode_number(episode), "title": episode.name,+ "episode_updated_at": episode.updated_at.isoformat(), "clips": clips,+ "cover_locator": next((clip["cover"] for clip in clips if clip["cover"]), "")}+ snapshot["cover_stamp"] = None+ if snapshot["cover_locator"]:+ try:+ snapshot["cover_stamp"] = await asyncio.to_thread(source_stamp, snapshot["cover_locator"])+ except (HTTPException, ValueError, OSError):+ # A missing cover never selects an unrelated material. The editor asks for one.+ snapshot["cover_locator"] = ""+ snapshot["source_version"] = digest({"episode": episode.id, "title": episode.name,+ "episode_number": snapshot["episode_number"], "updated_at": snapshot["episode_updated_at"],+ "cover_stamp": stamp_version(snapshot["cover_stamp"]) if snapshot["cover_stamp"] else None,+ "clips": [{"id": clip["id"], "sort_order": clip["sort_order"], "updated_at": clip["updated_at"],+ "stamp": stamp_version(clip["stamp"]), "cover": clip["cover"]} for clip in clips]})+ return snapshot+++async def episode_context(db, owner_id: int, project_id: int, episode) -> dict:+ fragments = list((await db.execute(select(DramaEpisodeFragment).where(DramaEpisodeFragment.episode_id == episode.id))).scalars().all())+ result = {"id": episode.id, "name": episode.name, "episode_number": episode_number(episode),+ "fragment_count": len(fragments), "completed_count": sum(bool((f.video or "").strip()) for f in fragments),+ "ready": False, "reason": "", "source_version": ""}+ try:+ snapshot = await episode_snapshot(db, owner_id, project_id, episode.id)+ result.update(ready=True, source_version=snapshot["source_version"])+ except HTTPException as exc:+ result["reason"] = str(exc.detail)+ return result++[email protected]("/printfilm/dramas/{project_id}/publish-context", response_model=dict)+async def publish_context(project_id: int, db: DB, user: Actor):+ from .storage import configured+ project = await owned_project(db, user.id, project_id)+ episodes = list((await db.execute(select(DramaEpisode).where(DramaEpisode.project_id == project.id))).scalars().all())+ episodes.sort(key=lambda row: (episode_number(row), row.id))+ targets = list((await db.execute(select(Series).where(Series.owner_id == user.id,+ Series.deleted_at.is_(None), Series.blocked.is_(False)).order_by(Series.id.desc()))).scalars().all())+ series_items = []+ for target in targets:+ imported = list((await db.execute(select(SeriesEpisode).where(SeriesEpisode.series_id == target.id))).scalars().all())+ mappings = []+ for episode in imported:+ mapping = episode.source_snapshot or {}+ if mapping.get("source_kind") != "drama_episode":+ continue+ handoff_id = mapping.get("pending_handoff_id") or mapping.get("last_handoff_id")+ handoff = await db.get(Handoff, handoff_id) if handoff_id else (await db.execute(select(Handoff).where(+ Handoff.target_kind == "series_episode", Handoff.target_id == episode.id,+ Handoff.source_kind == "drama_episode").order_by(Handoff.id.desc()).limit(1))).scalar_one_or_none()+ frozen = (handoff.source_snapshot or {}) if handoff else {}+ reusable = bool(handoff and frozen.get("schema_version") == 2 and (+ (handoff.status == "ready" and handoff.asset_id == episode.asset_id and mapping.get("last_handoff_id") == handoff.id)+ or (handoff.status in ("pending", "running", "failed") and mapping.get("pending_handoff_id") == handoff.id+ and frozen.get("target_version") == episode.version and frozen.get("original_asset_id") == episode.asset_id)))+ mappings.append({"source_episode_id": mapping.get("drama_episode_id") or mapping.get("source_id"),+ "episode_id": episode.id, "source_version": handoff.source_version if handoff else mapping.get("imported_source_version", ""),+ "status": handoff.status if handoff else "legacy", "handoff_id": handoff.id if handoff else None,+ "requires_update": not reusable})+ series_items.append({"id": target.id, "title": target.title, "version": target.version,+ "series_version": target.version, "listed": target.listed,+ "audit_status": target.audit_status, "imports": mappings})+ return {"project": {"id": project.id, "title": project.title, "description": project.description or ""},+ "episodes": [await episode_context(db, user.id, project.id, episode) for episode in episodes],+ "series": series_items, "authorization_ready": bool(await current_authorization(db, user.id)),+ "storage_configured": configured()}+++async def pause_sales(db, series):+ ids = select(SeriesEpisode.id).where(SeriesEpisode.series_id == series.id)+ await db.execute(update(Publication).where(Publication.content_type == "series_episode", Publication.content_id.in_(ids)).values(listed=False))+ await db.execute(update(SeriesEpisode).where(SeriesEpisode.series_id == series.id).values(listed=False))+ series.audit_status, series.listed, series.reason = "draft", False, ""+++async def ensure_import_rights(db, episode):+ """PrintFilm 分集统一关联账号授权;材料关联绝不等于审核通过。"""+ if episode.source != "printfilm" or not episode.asset_id:+ return+ mapping = episode.source_snapshot or {}+ if episode.source_type == "drama_import":+ if not mapping.get("last_handoff_id"):+ return+ handoff = await db.get(Handoff, mapping["last_handoff_id"])+ if not handoff or handoff.status != "ready" or handoff.asset_id != episode.asset_id or handoff.owner_id != episode.owner_id:+ return+ authorization = await current_authorization(db, episode.owner_id)+ if not authorization:+ return+ rights = (await db.execute(select(Rights).where(Rights.asset_id == episode.asset_id).with_for_update())).scalar_one_or_none()+ if rights and (rights.blocked or str(rights.details.get("authorization_id")) == str(authorization.id)):+ return+ values = {"source": "printfilm", "authorization_id": str(authorization.id),+ "authorization_version": authorization.template_version, "scope": "数字资产市场展示、撮合及经审核的平台投放"}+ if rights is None:+ db.add(Rights(owner_id=episode.owner_id, asset_id=episode.asset_id, details=values))+ else:+ rights.details = values+ rights.version += 1+ rights.basic_status = rights.full_status = "draft"+++async def batch_result(db, batch):+ from .handoff import _view+ from .series import _episode_data+ episodes = [await db.get(SeriesEpisode, item_id) for item_id in batch.episode_ids]+ tasks = [await db.get(Handoff, item_id) for item_id in batch.handoff_ids]+ return {"series_id": batch.series_id, "items": [await _episode_data(db, item, private=True) for item in episodes if item],+ "handoffs": [await _view(db, item) for item in tasks if item]}+++async def publish_selected(project_id: int, body: DramaPublishInput, db, user):+ from .handoff import _category+ # A transaction lock serializes retries even when creating a brand new series.+ # It doesn't update any upstream user or drama record.+ request_hash = digest({"project_id": project_id, **body.model_dump(exclude={"idempotency_key"})})+ lock_id = int(digest([user.id, body.idempotency_key])[:16], 16)+ if lock_id >= 2**63:+ lock_id -= 2**64+ await db.execute(text("SELECT pg_advisory_xact_lock(:key)"), {"key": lock_id})+ existing = (await db.execute(select(DramaPublishBatch).where(DramaPublishBatch.owner_id == user.id,+ DramaPublishBatch.idempotency_key == body.idempotency_key))).scalar_one_or_none()+ if existing:+ if existing.request_hash != request_hash:+ fail("MARKETPLACE_TARGET_CHANGED:此请求编号已用于其他发布内容", 409)+ return await batch_result(db, existing)+ await storage_ready() # Must precede all series/episode/task writes.+ project = await owned_project(db, user.id, project_id)+ snapshots = []+ for selected in body.episodes:+ snapshot = await episode_snapshot(db, user.id, project.id, selected.episode_id)+ if selected.source_version != snapshot["source_version"]:+ fail("MARKETPLACE_SOURCE_CHANGED:分集内容已变化,请刷新并重新选择", 409)+ snapshots.append((snapshot, selected.update))+ snapshots.sort(key=lambda entry: (entry[0]["episode_number"], entry[0]["drama_episode_id"]))+ if body.series_id:+ series = (await db.execute(select(Series).where(Series.id == body.series_id).with_for_update())).scalar_one_or_none()+ if not series or series.owner_id != user.id:+ fail("系列不存在或无权访问", 404)+ ensure_kept(series)+ if series.blocked:+ fail("MARKETPLACE_TARGET_CHANGED:系列已封禁", 409)+ stale_target = body.series_version is not None and series.version != body.series_version+ else:+ series = Series(owner_id=user.id, title=(body.title or project.title or "未命名短剧")[:200],+ description=(project.description or "")[:5000], category=await _category(db, "短剧"), sale_type="copyright_contact")+ db.add(series)+ await db.flush()+ stale_target = False+ episodes = list((await db.execute(select(SeriesEpisode).where(SeriesEpisode.series_id == series.id)+ .order_by(SeriesEpisode.episode_no).with_for_update())).scalars().all())+ next_no = max((episode.episode_no for episode in episodes), default=0) + 1+ targets, tasks = [], []+ changed = False+ for snapshot, confirmed_update in snapshots:+ source_id = snapshot["drama_episode_id"]+ target = next((row for row in episodes if (row.source_snapshot or {}).get("source_kind") == "drama_episode"+ and ((row.source_snapshot or {}).get("drama_episode_id") or (row.source_snapshot or {}).get("source_id")) == source_id), None)+ previous = (await db.execute(select(Handoff).where(Handoff.owner_id == user.id,+ Handoff.series_id == series.id, Handoff.target_id == target.id,+ Handoff.source_kind == "drama_episode", Handoff.source_id == source_id)+ .order_by(Handoff.id.desc()).limit(1))).scalar_one_or_none() if target else None+ previous_snapshot = previous.source_snapshot or {} if previous else {}+ mapping = target.source_snapshot or {} if target else {}+ previous_matches = bool(previous and ((previous.status == "ready" and previous.asset_id == target.asset_id+ and mapping.get("last_handoff_id") == previous.id)+ or (previous.status in ("pending", "running", "failed") and previous_snapshot.get("target_version") == target.version+ and previous_snapshot.get("original_asset_id") == target.asset_id and mapping.get("pending_handoff_id") == previous.id)))+ if previous_matches and previous.source_version == snapshot["source_version"] and previous_snapshot.get("schema_version") == 2:+ targets.append(target)+ tasks.append(previous)+ continue+ if target and not confirmed_update:+ fail("MARKETPLACE_SOURCE_CHANGED:发现新版本或旧版导入记录,请明确确认更新", 409)+ if target and target.blocked:+ fail("MARKETPLACE_TARGET_CHANGED:该分集已封禁", 409)+ if stale_target:+ fail("MARKETPLACE_TARGET_CHANGED:市场系列已修改,请刷新后重试", 409)+ if previous and previous.status in ("pending", "running"):+ previous.status, previous.error = "failed", "MARKETPLACE_TARGET_CHANGED:已有新的同步任务,请查看最新进度"+ previous.lease_token, previous.lease_until = None, None+ if target:+ target.version += 1+ target.audit_status, target.listed, target.reason = "draft", False, ""+ target.preview_status, target.playback_status = "none", "none"+ else:+ target = SeriesEpisode(series_id=series.id, owner_id=user.id, episode_no=next_no,+ title=(snapshot["title"] or f"第{next_no}集")[:200], source="printfilm", source_type="drama_import")+ next_no += 1+ db.add(target)+ await db.flush()+ episodes.append(target)+ # A new request can supersede a prior failed/running task, never its output.+ task = Handoff(owner_id=user.id, idempotency_key=digest(["drama", series.id, target.id, target.version, body.idempotency_key]),+ source_kind="drama_episode", source_id=source_id, source_version=snapshot["source_version"],+ target_kind="series_episode", target_id=target.id, series_id=series.id, status="pending",+ source_snapshot={**snapshot, "phase": "queued", "target_version": target.version,+ "original_asset_id": target.asset_id})+ db.add(task)+ await db.flush()+ target.source = "printfilm"+ target.source_snapshot = {"source_kind": "drama_episode", "source_id": source_id,+ "drama_project_id": project.id, "drama_episode_id": source_id, "source_title": snapshot["title"],+ "source_episode_number": snapshot["episode_number"], "pending_handoff_id": task.id,+ "last_handoff_id": (target.source_snapshot or {}).get("last_handoff_id"),+ "imported_source_version": (target.source_snapshot or {}).get("imported_source_version", "")}+ targets.append(target)+ tasks.append(task)+ changed = True+ if changed:+ series.version += 1+ await pause_sales(db, series)+ batch = DramaPublishBatch(owner_id=user.id, idempotency_key=body.idempotency_key,+ request_hash=request_hash, series_id=series.id, episode_ids=[row.id for row in targets], handoff_ids=[row.id for row in tasks])+ db.add(batch)+ await db.commit()+ return await batch_result(db, batch)++[email protected]("/printfilm/dramas/{project_id}/publish", response_model=dict)+async def publish(project_id: int, body: DramaPublishInput, db: DB, user: Actor):+ return await publish_selected(project_id, body, db, user)+++async def legacy_import(series_id: int, body, db, user):+ """兼容旧 URL;依然验证整集,绝不选择最后一个镜头。"""+ await storage_ready()+ snapshots = [await episode_snapshot(db, user.id, body.drama_project_id, episode_id) for episode_id in dict.fromkeys(body.episode_ids)]+ key = body.idempotency_key.strip() or digest(["legacy", series_id, [(s["drama_episode_id"], s["source_version"]) for s in snapshots]])+ payload = DramaPublishInput(series_id=series_id, idempotency_key=key,+ episodes=[DramaPublishEpisode(episode_id=s["drama_episode_id"], source_version=s["source_version"],+ update=s["drama_episode_id"] in body.update_episode_ids) for s in snapshots])+ return await publish_selected(body.drama_project_id, payload, db, user)diff --git a/backend/app/marketplace/handoff.py b/backend/app/marketplace/handoff.pyindex 3dbeac5..29e09a5 100644--- a/backend/app/marketplace/handoff.py+++ b/backend/app/marketplace/handoff.py@@ -141,7 +141,12 @@ async def _view(db, item: Handoff) -> dict:else:label = "正在同步"payload = data(item, "id", "status", "target_kind", "target_id", "series_id", "asset_id", "attempts", "created_at")- payload.update(label=label, authorization_ready=ready, error=item.error if item.status == "failed" else "",+ phase = (item.source_snapshot or {}).get("phase", "queued")+ phases = {"queued": "排队", "copying": "同步素材", "composing": "拼接整集", "validating": "校验", "ready": "已就绪", "failed": "同步失败"}+ payload.update(label=label, phase=item.status if item.status in ("ready", "failed") else phase,+ phase_label=phases.get(item.status if item.status in ("ready", "failed") else phase, "正在同步"),+ retryable=not any(code in (item.error or "") for code in ("SOURCE_CHANGED", "TARGET_CHANGED", "SOURCE_INCOMPATIBLE", "重新选择分集")),+ authorization_ready=ready, error=item.error if item.status == "failed" else "",work_id=item.target_id if item.target_kind == "work" else None,episode_id=item.target_id if item.target_kind == "series_episode" else None)return payload@@ -181,20 +186,6 @@ async def _project_source(db, user_id: int, project_id: int) -> tuple[Project, sreturn project, locator-async def _drama_source(db, user_id: int, drama_project_id: int, episode_id: int) -> tuple[DramaProject, DramaEpisode, DramaEpisodeFragment, str]:- project = (await db.execute(select(DramaProject).where(DramaProject.id == drama_project_id, DramaProject.user_id == user_id))).scalar_one_or_none()- if not project:- fail("漫剧项目不存在或无权访问", 404)- episode = (await db.execute(select(DramaEpisode).where(DramaEpisode.id == episode_id, DramaEpisode.project_id == project.id))).scalar_one_or_none()- if not episode:- fail("存在不属于该漫剧项目的分集", 404)- fragments = list((await db.execute(select(DramaEpisodeFragment).where(DramaEpisodeFragment.episode_id == episode.id).order_by(DramaEpisodeFragment.sort_order.desc(), DramaEpisodeFragment.id.desc()))).scalars().all())- fragment = next((item for item in fragments if (item.video or "").strip()), None)- if not fragment:- fail("所选分集没有可导入的成片,请先完成分集合成", 409)- return project, episode, fragment, fragment.video.strip()--async def _next_no(db, series_id: int) -> int:current = (await db.execute(select(func.max(SeriesEpisode.episode_no)).where(SeriesEpisode.series_id == series_id))).scalar_one()return int(current or 0) + 1@@ -246,6 +237,9 @@ async def work_from_printfilm(body: PrintfilmWorkInput, db: DB, user: Actor):async def enqueue_series_import(series_id: int, body: PrintfilmEpisodeInput, db, user) -> dict:"""把选中的漫剧分集或一部科普成片登记为短剧分集,实际复制交给 Worker。"""await storage_ready()+ if not body.project_id:+ from .drama_publish import legacy_import+ return await legacy_import(series_id, body, db, user)from .series import _episode_data, _seriesseries = await _series(db, series_id, user, lock=True)@@ -258,11 +252,6 @@ async def enqueue_series_import(series_id: int, body: PrintfilmEpisodeInput, db,project, locator = await _project_source(db, user.id, body.project_id)version = _version(project.updated_at.isoformat(), locator)jobs.append((_item_key(body.idempotency_key.strip(), f"series{series.id}:project_final", project.id, version), "project_final", project.id, version, locator, (project.cover_url or "").strip(), _clip(project.title or "第1集", 200) or "第1集"))- else:- for episode_id in dict.fromkeys(body.episode_ids):- _project, episode, fragment, locator = await _drama_source(db, user.id, body.drama_project_id or 0, episode_id)- version = _version(f"{fragment.id}:{fragment.updated_at.isoformat()}", locator)- jobs.append((_item_key(body.idempotency_key.strip(), f"series{series.id}:drama_episode", episode.id, version), "drama_episode", episode.id, version, locator, (fragment.cover or "").strip(), _clip(episode.name or "", 200) or f"分集{episode.id}"))created: list[SeriesEpisode] = []records: list[Handoff] = []added = False@@ -336,6 +325,9 @@ async def retry_handoff(handoff_id: int, db: DB, user: Actor):item = await _owned_handoff(db, handoff_id, user)if item.status != "failed":return await _view(db, item)+ if item.source_kind == "drama_episode":+ await _validate_drama_source(db, item)+ await _drama_target(db, item)item.status, item.error, item.attempts = "pending", "", 0item.lease_token, item.lease_until = None, Noneawait db.commit()@@ -377,7 +369,8 @@ async def _fail(handoff_id: int, token: str, message: str) -> None:item = (await db.execute(select(Handoff).where(Handoff.id == handoff_id, Handoff.lease_token == token).with_for_update())).scalar_one_or_none()if not item:return- terminal = item.attempts >= get_marketplace_settings().worker_max_attempts+ terminal = item.attempts >= get_marketplace_settings().worker_max_attempts or any(+ code in message for code in ("MARKETPLACE_SOURCE_CHANGED", "MARKETPLACE_TARGET_CHANGED", "MARKETPLACE_SOURCE_INCOMPATIBLE", "重新选择分集"))item.status = "failed" if terminal else "pending"item.error = message[:500]item.lease_token, item.lease_until = None, None@@ -412,6 +405,10 @@ async def _copy(handoff_id: int, token: str) -> None:item = (await db.execute(select(Handoff).where(Handoff.id == handoff_id, Handoff.lease_token == token))).scalar_one_or_none()if not item:return+ if item.source_kind == "drama_episode":+ # Legacy tasks were snapshots of only the final shot; never run them as full episodes.+ await _copy_drama(handoff_id, token)+ returnsnapshot = dict(item.source_snapshot or {})owner_id, target_kind, target_id = item.owner_id, item.target_kind, item.target_idif item.asset_id:@@ -495,6 +492,18 @@ async def _bind(db, item: Handoff, asset_id: int, cover_id: int | None) -> None:if cover_id and not work.cover_asset_id:work.cover_asset_id = cover_idreturn+ if item.source_kind == "drama_episode":+ episode = await _drama_target(db, item)+ episode.asset_id = asset_id+ if cover_id and not episode.cover_asset_id:+ episode.cover_asset_id = cover_id+ episode.source_snapshot = {**(episode.source_snapshot or {}), "pending_handoff_id": None,+ "last_handoff_id": item.id, "imported_source_version": item.source_version}+ from .drama_publish import ensure_import_rights+ # Set ready only for the authorization helper; the transaction is atomic.+ item.status = "ready"+ await ensure_import_rights(db, episode)+ returnepisode = await db.get(SeriesEpisode, item.target_id)if episode and episode.owner_id == item.owner_id:episode.asset_id = asset_id@@ -502,6 +511,116 @@ async def _bind(db, item: Handoff, asset_id: int, cover_id: int | None) -> None:episode.cover_asset_id = cover_id+async def _drama_target(db, item):+ from .models import Series+ series = (await db.execute(select(Series).where(Series.id == item.series_id).with_for_update())).scalar_one_or_none()+ episode = (await db.execute(select(SeriesEpisode).where(SeriesEpisode.id == item.target_id).with_for_update())).scalar_one_or_none()+ snapshot = item.source_snapshot or {}+ if (not series or series.owner_id != item.owner_id or series.deleted_at or series.blocked or not episode+ or episode.series_id != series.id or episode.owner_id != item.owner_id or episode.blocked+ or episode.version != snapshot.get("target_version")+ or episode.asset_id != snapshot.get("original_asset_id")+ or (episode.source_snapshot or {}).get("pending_handoff_id") != item.id):+ fail("MARKETPLACE_TARGET_CHANGED:市场分集已修改、删除或有新的同步任务,请重新选择", 409)+ return episode+++async def _validate_drama_source(db, item):+ from .drama_publish import episode_snapshot+ snapshot = item.source_snapshot or {}+ if snapshot.get("schema_version") != 2:+ fail("MARKETPLACE_SOURCE_CHANGED:旧导入未包含完整分镜,请重新选择分集并确认更新", 409)+ try:+ current = await episode_snapshot(db, item.owner_id, snapshot["drama_project_id"], item.source_id)+ except HTTPException as exc:+ if exc.status_code == 503:+ raise+ fail("MARKETPLACE_SOURCE_CHANGED:源分集已变化或正在重新生成,请重新选择分集", 409)+ if current["source_version"] != item.source_version:+ fail("MARKETPLACE_SOURCE_CHANGED:源分集已更新,请重新选择分集", 409)+++async def _phase(handoff_id, token, phase):+ async with AsyncSessionLocal() as db:+ item = (await db.execute(select(Handoff).where(Handoff.id == handoff_id,+ Handoff.lease_token == token, Handoff.status == "running").with_for_update())).scalar_one_or_none()+ if not item:+ raise RuntimeError("同步任务租约已丢失")+ item.source_snapshot = {**(item.source_snapshot or {}), "phase": phase}+ await db.commit()+++async def _copy_drama(handoff_id, token):+ """完整视频成功写入私有 OSS 且源/目标仍有效,才一次性绑定新资产。"""+ async with AsyncSessionLocal() as db:+ item = (await db.execute(select(Handoff).where(Handoff.id == handoff_id, Handoff.lease_token == token))).scalar_one_or_none()+ if not item:+ return+ await _validate_drama_source(db, item)+ await _drama_target(db, item)+ snapshot, owner_id, target_id = dict(item.source_snapshot), item.owner_id, item.target_id+ folder = f"marketplace/series/u{owner_id}/{target_id}"+ dest = f"{folder}/{uuid.uuid4().hex}.mp4"+ cover_key = f"{folder}/cover-{uuid.uuid4().hex}.png"+ bound = False+ try:+ bound = await _finish_drama_copy(handoff_id, token, snapshot, owner_id, dest, cover_key)+ finally:+ if not bound:+ from .storage import discard_generated+ try:+ # A database commit error can have an uncertain outcome. Never+ # remove an object unless a fresh read confirms it is unbound.+ async with AsyncSessionLocal() as db:+ referenced = set((await db.execute(select(Asset.object_key).where(Asset.object_key.in_((dest, cover_key))))).scalars().all())+ for key in (dest, cover_key):+ if key in referenced:+ continue+ await asyncio.to_thread(discard_generated, key)+ except Exception:+ logger.warning("未绑定的市场同步对象清理失败,任务 %s", handoff_id)+++async def _finish_drama_copy(handoff_id, token, snapshot, owner_id, dest, cover_key):+ from .drama_media import prepare_drama_video, prepare_drama_cover+ result = await prepare_drama_video(snapshot, dest, lambda phase: _phase(handoff_id, token, phase))+ cover = None+ if snapshot.get("cover_locator"):+ try:+ cover = {**await prepare_drama_cover(snapshot["cover_locator"], cover_key, snapshot.get("cover_stamp")), "object_key": cover_key}+ except (ValueError, HTTPException, OSError):+ logger.info("漫剧来源封面不可用,保留为待上传封面")+ async with AsyncSessionLocal() as db:+ # Queue/update locks series -> episode -> handoff; use the same order.+ candidate = await db.get(Handoff, handoff_id)+ if not candidate:+ return False+ await _drama_target(db, candidate)+ item = (await db.execute(select(Handoff).where(Handoff.id == handoff_id,+ Handoff.lease_token == token, Handoff.status == "running").with_for_update())).scalar_one_or_none()+ if not item:+ return False+ await _validate_drama_source(db, item)+ await _drama_target(db, item)+ asset = Asset(owner_id=owner_id, kind="video", filename=f"{snapshot['title'][:180]}.mp4", object_key=dest,+ status="ready", **{key: result[key] for key in ("size_bytes", "content_type", "fingerprint", "duration_seconds")})+ db.add(asset)+ await db.flush()+ item.asset_id, item.source_fingerprint = asset.id, asset.fingerprint+ cover_id = None+ if cover:+ cover_asset = Asset(owner_id=owner_id, kind="image", filename="cover" + Path(cover["object_key"]).suffix,+ status="ready", **{key: cover[key] for key in ("object_key", "size_bytes", "content_type")})+ db.add(cover_asset)+ await db.flush()+ cover_id = cover_asset.id+ await _bind(db, item, asset.id, cover_id)+ item.status, item.error, item.lease_token, item.lease_until = "ready", "", None, None+ item.source_snapshot = {**item.source_snapshot, "phase": "ready"}+ await db.commit()+ return True++async def run_handoff_once() -> bool:"""领取一条转存。没有待处理记录时返回 False。"""claimed = await _claim()@@ -509,12 +628,18 @@ async def run_handoff_once() -> bool:return Falsehandoff_id, token = claimedpulse = asyncio.create_task(_heartbeat(handoff_id, token))+ copy = asyncio.create_task(_copy(handoff_id, token))try:- await _copy(handoff_id, token)+ done, _ = await asyncio.wait({pulse, copy}, return_when=asyncio.FIRST_COMPLETED)+ for task in done:+ await task+ except (ValueError, HTTPException) as exc:+ await _fail(handoff_id, token, str(exc.detail) if isinstance(exc, HTTPException) else str(exc))except Exception:logger.exception("marketplace handoff %s failed", handoff_id)await _fail(handoff_id, token, "复制成片失败,请稍后重试")finally:pulse.cancel()- await asyncio.gather(pulse, return_exceptions=True)+ copy.cancel()+ await asyncio.gather(pulse, copy, return_exceptions=True)return Truediff --git a/backend/app/marketplace/models.py b/backend/app/marketplace/models.pyindex f78e8ba..b4f32e7 100644--- a/backend/app/marketplace/models.py+++ b/backend/app/marketplace/models.py@@ -175,6 +175,18 @@ class Handoff(Record, MarketBase):source_snapshot: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict)+class DramaPublishBatch(Record, MarketBase):+ """一次明确的漫剧发布请求;原子创建系列,重试不能产生空壳或重复系列。"""+ __tablename__ = "marketplace_drama_publish_batches"+ __table_args__ = (UniqueConstraint("owner_id", "idempotency_key"),)+ owner_id: Mapped[int] = mapped_column(Integer, index=True)+ idempotency_key: Mapped[str] = mapped_column(String(120))+ request_hash: Mapped[str] = mapped_column(String(64))+ series_id: Mapped[int] = mapped_column(ForeignKey("marketplace_series.id"))+ episode_ids: Mapped[list[int]] = mapped_column(JSON, default=list)+ handoff_ids: Mapped[list[int]] = mapped_column(JSON, default=list)++class WorkPreview(Record, MarketBase):"""作品专用试看任务,不复用投稿审片或旧资产预览。"""__tablename__ = "marketplace_work_previews"diff --git a/backend/app/marketplace/runtime.py b/backend/app/marketplace/runtime.pyindex 05b6293..8300341 100644--- a/backend/app/marketplace/runtime.py+++ b/backend/app/marketplace/runtime.py@@ -2,7 +2,7 @@import asyncioimport logging-from .config import get_marketplace_settings+from .config import is_marketplace_enabledfrom .worker import run_looplogger = logging.getLogger(__name__)@@ -24,7 +24,7 @@ async def _supervise():async def start_marketplace_runtime():global _watchdog- if not get_marketplace_settings().enabled:+ if not is_marketplace_enabled():returnif _watchdog is not None and not _watchdog.done():returndiff --git a/backend/app/marketplace/schemas.py b/backend/app/marketplace/schemas.pyindex 285edf8..a0ec41c 100644--- a/backend/app/marketplace/schemas.py+++ b/backend/app/marketplace/schemas.py@@ -215,6 +215,7 @@ class PrintfilmEpisodeInput(Input):episode_ids: list[int] = Field(default_factory=list, max_length=100)project_id: int | None = Field(default=None, gt=0)idempotency_key: str = Field(default="", max_length=80)+ update_episode_ids: list[int] = Field(default_factory=list, max_length=100)@model_validator(mode="after")def choose_source(self):@@ -227,6 +228,26 @@ class PrintfilmEpisodeInput(Input):return self+class DramaPublishEpisode(Input):+ episode_id: int = Field(gt=0)+ source_version: str = Field(min_length=1, max_length=80)+ update: bool = False+++class DramaPublishInput(Input):+ episodes: list[DramaPublishEpisode] = Field(min_length=1, max_length=100)+ series_id: int | None = Field(default=None, gt=0)+ series_version: int | None = Field(default=None, ge=1)+ title: str | None = Field(default=None, min_length=1, max_length=200)+ idempotency_key: str = Field(min_length=8, max_length=120)++ @model_validator(mode="after")+ def distinct_episodes(self):+ if len({item.episode_id for item in self.episodes}) != len(self.episodes):+ raise ValueError("不能重复选择同一分集")+ return self++class RevenueConfigInput(Input):version: int = Field(ge=0)platform_share_bps: int = Field(ge=0, le=10000)diff --git a/backend/app/marketplace/series.py b/backend/app/marketplace/series.pyindex 2964557..ddeb089 100644--- a/backend/app/marketplace/series.py+++ b/backend/app/marketplace/series.py@@ -4,20 +4,61 @@"""from __future__ import annotations-from pathlib import Path-from fastapi import APIRouter, Queryfrom sqlalchemy import and_, not_, or_, select-from app.models_drama import DramaEpisode, DramaEpisodeFragment, DramaProject+from app.models_drama import DramaProjectfrom .dependencies import Actor, DB, Visitor, storage_ready-from .models import Asset, EpisodePreview, PlaybackJob, Publication, RevenueConfig, Rights, Series, SeriesEpisode+from .models import Asset, ContentOrder, Entitlement, EpisodePreview, Handoff, PlaybackJob, Publication, RevenueConfig, Rights, Series, SeriesEpisodefrom .schemas import EpisodeInput, EpisodeUpdate, ImportEpisodesInput, SeriesInput, SeriesUpdate, Versionfrom .service import asset_owned, asset_owned_for_draft, check_version, data, event, fail, now, notify, owned, page, validate_rightsrouter = APIRouter()+async def ensure_series_idle(db, series_id: int, *, submitting: bool = False) -> None:+ active = (await db.execute(select(Handoff.id).where(+ Handoff.series_id == series_id, Handoff.status.in_(("pending", "running"))+ ).limit(1))).scalar_one_or_none()+ if active:+ fail("MARKETPLACE_SYNC_IN_PROGRESS", 409)+ if submitting:+ latest = await _latest_series_handoffs(db, series_id)+ if any(item.status == "failed" for item in latest):+ fail("MARKETPLACE_EPISODE_NOT_READY", 409)+++async def _latest_series_handoffs(db, series_id: int) -> list[Handoff]:+ handoffs = list((await db.execute(select(Handoff).where(+ Handoff.series_id == series_id, Handoff.target_kind == "series_episode",+ Handoff.target_id.in_(select(SeriesEpisode.id).where(SeriesEpisode.series_id == series_id)),+ ).order_by(Handoff.id.desc()))).scalars().all())+ latest = {}+ for handoff in handoffs:+ latest.setdefault(handoff.target_id, handoff)+ return list(latest.values())+++async def pause_series_sales(db, series: Series, *, bump_episode_versions: bool = False) -> list[SeriesEpisode]:+ """保留旧媒体及购买快照,仅关闭销售;系列资料更新时产生新的逐集版本。"""+ episodes = list((await db.execute(select(SeriesEpisode).where(+ SeriesEpisode.series_id == series.id).with_for_update())).scalars().all())+ series.listed = False+ for episode in episodes:+ episode.listed = False+ if bump_episode_versions:+ episode.version += 1+ episode.audit_status, episode.reason = "draft", ""+ if episodes:+ publications = list((await db.execute(select(Publication).where(+ Publication.content_type == "series_episode",+ Publication.content_id.in_([item.id for item in episodes]),+ ).with_for_update())).scalars().all())+ for publication in publications:+ publication.listed = False+ return episodes++def _sale_type(value: str, copyright_price: int) -> str:# 收费类型由用户明确选择;参考价为0仍可以先联系客服询价。return value@@ -61,6 +102,13 @@ async def _series_data(db, item: Series, *, private: bool = False) -> dict:result["episodes"] = [await _episode_data(db, episode, private=private) for episode in episodes]if private:result.update(data(item, "owner_id", "version", "audit_status", "listed", "blocked", "reason", "share_bps"))+ from .authorization import current, summary+ from .handoff import _view+ authorization = await current(db, item.owner_id)+ handoffs = await _latest_series_handoffs(db, item.id)+ result.update(authorization_ready=bool(authorization), authorization=summary(authorization),+ sync_in_progress=any(handoff.status in ("pending", "running") for handoff in handoffs),+ pending_handoffs=[await _view(db, handoff) for handoff in handoffs])return result@@ -97,41 +145,12 @@ async def list_series(db: DB, q: str = Query("", max_length=100), category: str@router.get("/series/import-sources", response_model=dict)async def import_sources(db: DB, user: Actor):"""列出当前用户可明确选择导入的漫剧项目和已生成分集。"""- from app.services import oss as upstream_oss- from app.services import storage as upstream_storage+ from .drama_publish import publish_contextprojects = list((await db.execute(select(DramaProject).where(DramaProject.user_id == user.id).order_by(DramaProject.id.desc()))).scalars().all())result = []for project in projects:- episodes = list((await db.execute(select(DramaEpisode).where(DramaEpisode.project_id == project.id).order_by(DramaEpisode.id))).scalars().all())- episode_items = []- for episode in episodes:- fragments = list((await db.execute(select(DramaEpisodeFragment).where(DramaEpisodeFragment.episode_id == episode.id).order_by(DramaEpisodeFragment.sort_order.desc()))).scalars().all())- ready = False- for fragment in fragments:- raw_video = (fragment.video or "").strip()- if not raw_video:- continue- local = upstream_storage.local_path_from_url(raw_video)- if not local:- candidate = Path(raw_video)- if candidate.is_absolute() and candidate.is_file():- try:- relative = candidate.resolve().relative_to(upstream_storage.STATIC_ROOT.resolve())- local = upstream_storage.STATIC_ROOT / relative- except ValueError:- local = None- if (local and local.is_file()) or raw_video.startswith(("http://", "https://")):- ready = True- break- # Object-key rows can be checked during import through the- # existing shared OSS client. Do not issue a network HEAD for- # every list request; a missing object returns SOURCE_NOT_READY- # when the user explicitly imports it.- if upstream_oss.oss_enabled() and not raw_video.startswith("/static/"):- ready = True- break- episode_items.append({"id": episode.id, "name": episode.name, "ready": ready})- result.append({"id": project.id, "title": project.title, "episodes": episode_items})+ context = await publish_context(project.id, db, user)+ result.append({"id": project.id, "title": project.title, "episodes": context["episodes"]})return {"items": result}@@ -170,6 +189,7 @@ async def update_series(series_id: int, body: SeriesUpdate, db: DB, user: Actor)from .service import ensure_keptensure_kept(item)check_version(item, body.version)+ await ensure_series_idle(db, item.id)from .categories import validate_categoryawait validate_category(db, body.category, item.category)if body.cover_asset_id:@@ -182,7 +202,7 @@ async def update_series(series_id: int, body: SeriesUpdate, db: DB, user: Actor)setattr(item, key, value)item.version += 1item.audit_status, item.listed, item.reason = "draft", False, ""- await db.execute(select(SeriesEpisode).where(SeriesEpisode.series_id == item.id).with_for_update())+ await pause_series_sales(db, item, bump_episode_versions=True)await db.commit()return await _series_data(db, item, private=True)@@ -190,6 +210,9 @@ async def update_series(series_id: int, body: SeriesUpdate, db: DB, user: Actor)@router.post("/series/{series_id}/episodes", response_model=dict)async def create_episode(series_id: int, body: EpisodeInput, db: DB, user: Actor):series = await _series(db, series_id, user, lock=True)+ from .service import ensure_kept+ ensure_kept(series)+ await ensure_series_idle(db, series.id)duplicate = (await db.execute(select(SeriesEpisode.id).where(SeriesEpisode.series_id == series.id, SeriesEpisode.episode_no == body.episode_no))).scalar_one_or_none()if duplicate:fail("该集数已经存在", 409)@@ -203,6 +226,7 @@ async def create_episode(series_id: int, body: EpisodeInput, db: DB, user: Actordb.add(item)series.version += 1series.audit_status, series.listed = "draft", False+ await pause_series_sales(db, series)await db.commit()return await _episode_data(db, item, private=True)@@ -210,6 +234,9 @@ async def create_episode(series_id: int, body: EpisodeInput, db: DB, user: Actor@router.patch("/series/{series_id}/episodes/{episode_id}", response_model=dict)async def update_episode(series_id: int, episode_id: int, body: EpisodeUpdate, db: DB, user: Actor):series = await _series(db, series_id, user, lock=True)+ from .service import ensure_kept+ ensure_kept(series)+ await ensure_series_idle(db, series.id)item = await _episode(db, episode_id, user, lock=True)if item.series_id != series.id:fail("分集不属于该系列", 404)@@ -224,6 +251,7 @@ async def update_episode(series_id: int, episode_id: int, body: EpisodeUpdate, ditem.audit_status, item.listed, item.reason = "draft", False, ""series.version += 1series.audit_status, series.listed = "draft", False+ await pause_series_sales(db, series)await db.commit()return await _episode_data(db, item, private=True)@@ -231,9 +259,17 @@ async def update_episode(series_id: int, episode_id: int, body: EpisodeUpdate, d@router.delete("/series/{series_id}/episodes/{episode_id}", response_model=dict)async def delete_episode(series_id: int, episode_id: int, db: DB, user: Actor):series = await _series(db, series_id, user, lock=True)+ from .service import ensure_kept+ ensure_kept(series)+ await ensure_series_idle(db, series.id)item = await _episode(db, episode_id, user, lock=True)if item.series_id != series.id:fail("分集不属于该系列", 404)+ has_order = (await db.execute(select(ContentOrder.id).where(ContentOrder.episode_id == item.id).limit(1))).scalar_one_or_none()+ has_entitlement = (await db.execute(select(Entitlement.id).where(Entitlement.episode_id == item.id).limit(1))).scalar_one_or_none()+ if has_order or has_entitlement:+ fail("该分集已有订单或购买权益,不能删除;请下架系列并保留记录", 409)+ await pause_series_sales(db, series)await db.delete(item)series.version += 1series.audit_status, series.listed = "draft", False@@ -267,8 +303,11 @@ async def submit_series(series_id: int, body: Version, db: DB, user: Actor):from .service import ensure_keptensure_kept(series)check_version(series, body.version)+ await ensure_series_idle(db, series.id, submitting=True)if series.blocked:fail("系列已被管理员封禁")+ if series.audit_status in ("pending", "processing", "approved"):+ return await _series_data(db, series, private=True)episodes = list((await db.execute(select(SeriesEpisode).where(SeriesEpisode.series_id == series.id).order_by(SeriesEpisode.episode_no).with_for_update())).scalars().all())if not episodes:fail("至少添加一集后才能提交审核")@@ -284,18 +323,34 @@ async def submit_series(series_id: int, body: Version, db: DB, user: Actor):await storage_ready()from .previews import is_watermark_keypending_preview = False+ await pause_series_sales(db, series)for episode in episodes:+ if episode.blocked:+ fail(f"第{episode.episode_no}集已被限制发布", 409)asset = await asset_owned(db, episode.asset_id or 0, user)if not episode.cover_asset_id and not series.cover_asset_id:fail(f"第{episode.episode_no}集缺少封面,请上传分集封面或系列封面", 409)+ if episode.source == "printfilm":+ from .drama_publish import ensure_import_rights+ await ensure_import_rights(db, episode)rights = (await db.execute(select(Rights).where(Rights.asset_id == asset.id).with_for_update())).scalar_one_or_none()if not rights or rights.blocked:fail("请完成每集版权信息后再提交", 409)if rights.details.get("source") != episode.source:fail(f"第{episode.episode_no}集版权来源与分集来源不匹配", 409)validate_rights(rights.details, full=True, certificate=bool(rights.certificate_asset_id))+ if rights.valid_until and rights.valid_until <= now():+ fail(f"第{episode.episode_no}集版权授权已过期", 409)if series.sale_type == "platform_unlock" and episode.unlock_price_fen <= 0:fail(f"第{episode.episode_no}集必须设置解锁价")+ publication = (await db.execute(select(Publication).where(+ Publication.content_type == "series_episode", Publication.content_id == episode.id,+ Publication.version == episode.version).with_for_update())).scalar_one_or_none()+ if publication and publication.audit_status == "approved":+ # The series may be re-reviewed because another episode changed.+ # Never reset an approved version's media, financial or rights snapshot.+ episode.version += 1+ publication = None# 同一原片已有水印就沿用,改免费集数或收费类型不重新转码。done = (await db.execute(select(EpisodePreview).where(EpisodePreview.episode_id == episode.id, EpisodePreview.asset_id == asset.id,@@ -319,13 +374,12 @@ async def submit_series(series_id: int, body: Version, db: DB, user: Actor):preview.lease_token, preview.lease_until = None, Nonepreview_status = "done" if preview.status == "done" and is_watermark_key(preview.object_key) else "pending"pending_preview = pending_preview or preview_status != "done"- publication = (await db.execute(select(Publication).where(- Publication.content_type == "series_episode", Publication.content_id == episode.id,- Publication.version == episode.version).with_for_update())).scalar_one_or_none()+ share = episode.share_bps if episode.share_bps is not None else (+ series.share_bps if series.share_bps is not None else (config.platform_share_bps if config else None))values = dict(owner_id=user.id, version=episode.version, asset_id=asset.id,cover_asset_id=episode.cover_asset_id or series.cover_asset_id, sale_type=series.sale_type,copyright_price_fen=episode.copyright_price_fen or series.copyright_price_fen,- unlock_price_fen=episode.unlock_price_fen, share_bps=episode.share_bps,+ unlock_price_fen=episode.unlock_price_fen, share_bps=share,rights_snapshot={"details": rights.details, "certificate_asset_id": rights.certificate_asset_id,"evidence_ids": rights.evidence_ids}, audit_status="pending", listed=False,preview_status=preview_status, playback_status="done" if series.sale_type != "platform_unlock" else "pending")diff --git a/backend/app/marketplace/storage.py b/backend/app/marketplace/storage.pyindex 7ac0842..5fdbc02 100644--- a/backend/app/marketplace/storage.py+++ b/backend/app/marketplace/storage.py@@ -161,6 +161,45 @@ def copy_private(source_key: str, dest_key: str, content_type: str) -> int:return int(client.head_object(dest_key).content_length)+@transport+def discard_generated(key: str) -> None:+ """只清理本次同步生成且未绑定的精确 UUID 对象,绝不删除上游媒体。"""+ import re+ if not re.fullmatch(r"marketplace/series/u\d+/\d+/(?:cover-)?[0-9a-f]{32}\.(?:mp4|png)", key):+ raise ValueError("拒绝清理非市场同步对象")+ bucket().delete_object(key)+++def source_metadata(key: str) -> dict:+ """读取上游对象版本;只供服务端的漫剧快照使用。"""+ try:+ result = bucket().head_object(key)+ etag = str(result.etag or "").strip('"')+ if not etag:+ raise ValueError("MARKETPLACE_SOURCE_NOT_READY:源视频没有可校验的版本")+ return {"etag": etag, "size_bytes": int(result.content_length)}+ except (HTTPException, ValueError):+ raise+ except Exception as exc:+ if getattr(exc, "status", None) == 404:+ raise ValueError("MARKETPLACE_SOURCE_NOT_READY:源视频不存在") from exc+ raise unavailable() from exc+++def download_version(key: str, path: Path, etag: str) -> None:+ """按冻结的 ETag 下载;上游覆盖同名视频时明确终止旧快照。"""+ try:+ bucket().get_object_to_file(key, str(path), headers={"If-Match": etag})+ except HTTPException:+ raise+ except Exception as exc:+ if getattr(exc, "status", None) == 412:+ raise ValueError("MARKETPLACE_SOURCE_CHANGED:源视频已更新,请重新选择") from exc+ if getattr(exc, "status", None) == 404:+ raise ValueError("MARKETPLACE_SOURCE_NOT_READY:源视频不存在") from exc+ raise unavailable() from exc++@transportdef signed(key: str, content_type: str = "application/octet-stream") -> str:"""使用上传时的对象 Content-Type;不覆盖响应头,避免 OSS 拒绝预览。"""diff --git a/backend/app/marketplace/worker.py b/backend/app/marketplace/worker.pyindex 2ab2520..f60f7ae 100644--- a/backend/app/marketplace/worker.py+++ b/backend/app/marketplace/worker.py@@ -17,7 +17,7 @@ from sqlalchemy import and_, or_, select, updatefrom app.config import get_settingsfrom app.database import AsyncSessionLocal, enginefrom . import storage-from .config import get_marketplace_settings+from .config import get_marketplace_settings, is_marketplace_enabledfrom .models import Asset, MarketBase, MediaJob, PlaybackJob, Publication, Recruit, Series, SeriesEpisode, Upload, Workfrom .service import now, notify@@ -376,7 +376,7 @@ async def run_loop(*, standalone: bool = False) -> None:try:if standalone:await refresh_storage_settings()- if get_marketplace_settings().enabled and storage.configured():+ if is_marketplace_enabled() and storage.configured():# 所有后端进程/手动命令共享一把事务锁,市场媒体总并发保持为1。async with engine.begin() as connection:acquired = await connection.scalar(text("SELECT pg_try_advisory_xact_lock(18427, 73102)"))@@ -400,7 +400,7 @@ async def run_loop(*, standalone: bool = False) -> None:async def main() -> None:"""保留手动命令兼容;日常开发由后端生命周期自动托管。"""- if not get_marketplace_settings().enabled:+ if not is_marketplace_enabled():logger.info("下游模块未启用,Worker 不启动")returnasync with engine.begin() as conn:diff --git a/backend/app/schemas_settings.py b/backend/app/schemas_settings.pyindex c1928d5..8e2144a 100644--- a/backend/app/schemas_settings.py+++ b/backend/app/schemas_settings.py@@ -126,6 +126,7 @@ class AdminModelSettingsOut(BaseModel):public_base_url: str = ""ffmpeg_path: str = "ffmpeg"ffprobe_path: str = "ffprobe"+ marketplace_enabled: bool = Falsesource: str = "env"updated_at: datetime | None = None@@ -233,6 +234,7 @@ class AdminModelSettingsPatch(BaseModel):public_base_url: str | None = Noneffmpeg_path: str | None = Noneffprobe_path: str | None = None+ marketplace_enabled: bool | None = Noneclass AdminModelSettingsSaveOut(BaseModel):@@ -336,6 +338,7 @@ def model_config_field_names() -> tuple[str, ...]:"public_base_url","ffmpeg_path","ffprobe_path",+ "marketplace_enabled",)diff --git a/backend/app/services/model_settings.py b/backend/app/services/model_settings.pyindex 2cef94e..04e1408 100644--- a/backend/app/services/model_settings.py+++ b/backend/app/services/model_settings.py@@ -653,6 +653,9 @@ async def patch_admin_model_settings(app_row.config_json = configawait db.commit()await load_model_settings_cache(db)+ if "marketplace_enabled" in applied:+ from app.marketplace.bootstrap import apply_marketplace_switch+ await apply_marketplace_switch()channels, logical_models, defaults, flat, app_row = await _compose_runtime_state(db)admin_channels = await _load_channels(db, runtime=False)return _to_admin_flat_out(flat, source="db", updated_at=app_row.updated_at, channels=admin_channels, logical_models=logical_models, defaults=defaults), applieddiff --git a/backend/tests/test_marketplace.py b/backend/tests/test_marketplace.pyindex 06e1933..0d87a91 100644--- a/backend/tests/test_marketplace.py+++ b/backend/tests/test_marketplace.py@@ -14,6 +14,7 @@ from app.deps import get_current_userfrom app.models import Userfrom app.marketplace import storagefrom app.marketplace.bootstrap import install+from app.config import get_settingsfrom app.marketplace.config import get_marketplace_settingsfrom app.marketplace.dependencies import optional_userfrom app.marketplace.models import Asset, MarketBase, MediaJob, Recruit, Rights, Submission, Support, Work@@ -104,6 +105,16 @@ async def test_recruit_public_detail_contact_flags_and_management_privacy(ctx):async def test_paid_preview_submit_dedup_retry_and_free_transition(ctx, monkeypatch):+ from contextlib import asynccontextmanager+ from app.marketplace import preview_worker++ @asynccontextmanager+ async def session():+ yield ctx.db++ async def render(_snapshot):+ return 'marketplace/work-previews-hq/test-secure.mp4'+fake_oss(monkeypatch)video = await asset(ctx)await rights(ctx, video, full=True)@@ -124,14 +135,20 @@ async def test_paid_preview_submit_dedup_retry_and_free_transition(ctx, monkeypaawait ctx.db.flush()assert (await ctx.client.post(path + '/submit', json={'version': 1})).status_code == 200assert job.status == 'pending' and job.attempts == 0- job.status, job.object_key = 'done', 'marketplace/work-previews-hq/test-secure.mp4'- await ctx.db.flush()+ # 由 Worker 同时完成任务和作品状态转换;重复 submit 不负责推进后台任务。+ monkeypatch.setattr(preview_worker, 'AsyncSessionLocal', session)+ monkeypatch.setattr(preview_worker, 'render_preview', render)+ assert await preview_worker.run_preview_once()+ assert job.status == 'done' and record.audit_status == 'pending'assert (await ctx.client.post(path + '/submit', json={'version': 1})).json()['audit_status'] == 'pending'changed = await ctx.client.put(path, json={**work_body(video), 'price_fen': 0, 'version': 1})assert changed.status_code == 200 and not changed.json()['listed']result = await ctx.client.post(path + '/submit', json={'version': changed.json()['version']})assert result.json()['audit_status'] == 'pending'assert result.json()['preview_status'] == 'done'+ assert result.json()['sale_type'] == 'free'+ assert list((await ctx.db.execute(select(WorkPreview))).scalars()) == [job]+ assert job.object_key == 'marketplace/work-previews-hq/test-secure.mp4'async def test_paid_preview_media_never_leaks_original(ctx, monkeypatch):@@ -280,6 +297,7 @@ async def ctx(db_session, monkeypatch):connection = await db_session.connection()await connection.run_sync(MarketBase.metadata.create_all)settings = get_marketplace_settings()+ monkeypatch.setattr(get_settings(), "marketplace_enabled", True)monkeypatch.setattr(settings, "enabled", True)monkeypatch.setattr(storage.get_settings(), "oss_enabled", False)users = []@@ -528,8 +546,8 @@ def test_metadata_does_not_join_original_tables():async def test_disabled_only_exposes_capabilities(monkeypatch):- """关闭时没有业务路由,不需要 DB 和 Worker。"""- monkeypatch.setattr(get_marketplace_settings(), "enabled", False)+ """关闭时业务接口不可用,能力接口仍可读取开关。"""+ monkeypatch.setattr(get_settings(), "marketplace_enabled", False)app = FastAPI()install(app)async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:@@ -883,7 +901,7 @@ async def test_worker_reads_shared_config_without_writing(monkeypatch):async def test_disabled_worker_does_not_touch_oss_or_db(monkeypatch):"""默认关闭时独立 Worker 命令直接退出。"""from app.marketplace import worker- monkeypatch.setattr(get_marketplace_settings(), "enabled", False)+ monkeypatch.setattr(get_settings(), "marketplace_enabled", False)monkeypatch.setattr(storage, "bucket", lambda: pytest.fail("不应访问OSS"))await worker.main()@@ -975,7 +993,7 @@ async def test_worker_recovers_expired_lease(ctx, monkeypatch):async def test_real_ffmpeg_processing_with_oss_transport_stub(monkeypatch, tmp_path):- """真实FFmpeg验证短预览和完整审片;只替换OSS传输,不计为云端联调。"""+ """上传阶段仅验证完整原片;试看由提交阶段的独立任务生成,不计为云端联调。"""import jsonimport shutilfrom app.config import get_settings@@ -999,15 +1017,14 @@ async def test_real_ffmpeg_processing_with_oss_transport_stub(monkeypatch, tmp_pmonkeypatch.setattr(storage, "upload", upload)result = await worker.process_asset({"id": 999, "filename": "source.mp4", "object_key": "unit-test", "kind": "video", "size_bytes": source.stat().st_size, "content_type": "video/mp4"})assert result["duration_seconds"] == 31- assert len(result["fingerprint"]) == 64- for field, maximum in (("preview_key", 30.1), ("review_key", 31.1)):- probe = json.loads(await worker.command(settings.ffprobe_path, "-v", "error", "-show_format", "-show_streams", "-of", "json", str(results[result[field]])))- duration = float(probe["format"]["duration"])- assert duration <= maximum- assert duration >= maximum - 0.2- stream = probe["streams"][0]- assert stream["height"] <= 720 and stream["codec_name"] == "h264"- assert results[result["cover_key"]].is_file()+ assert result["fingerprint"] == worker.fingerprint(source)+ assert set(result) == {"duration_seconds", "fingerprint"}+ assert results == {} # 不为每次上传额外制作试看、审片或自动封面。+ probe = json.loads(await worker.command(settings.ffprobe_path, "-v", "error", "-show_format", "-show_streams", "-of", "json", str(source)))+ assert float(probe["format"]["duration"]) == 31+ stream = probe["streams"][0]+ assert (stream["width"], stream["height"]) == (320, 180)+ assert stream["codec_name"] == "h264"@pytest.mark.parametrize("extension", ["png", "jpg", "webp"])diff --git a/backend/tests/test_marketplace_drama_concurrency.py b/backend/tests/test_marketplace_drama_concurrency.pynew file mode 100644index 0000000..c508a21--- /dev/null+++ b/backend/tests/test_marketplace_drama_concurrency.py@@ -0,0 +1,189 @@+"""真实并发发布:两个独立 HTTP 请求/数据库事务,验证 PG 锁和提交可见性。"""+import asyncio+import re+from types import SimpleNamespace+import uuid++from fastapi import FastAPI+import httpx+import pytest_asyncio+from sqlalchemy import func, select, text+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++from app.config import get_settings+from app.database import Base, get_db+from app.deps import get_current_user+from app.models import Project, Shot, Template, User+from app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, DramaProject, DramaScript+from app.models_tasks import TaskRun+from app.marketplace import drama_media, drama_publish, storage+from app.marketplace.models import DramaPublishBatch, Handoff, MarketBase, Series, SeriesEpisode+from conftest import _ensure_test_database, _resolve_test_database_url+++@pytest_asyncio.fixture+async def concurrent_publish_ctx(monkeypatch):+ """独立测试库内提交随机 schema,finally 仅删除本用例拥有的 schema。"""+ url, name = _resolve_test_database_url(get_settings().database_url)+ await _ensure_test_database(url, name)+ base_engine = create_async_engine(url, pool_size=5)+ schema = f"drama_concurrency_test_{uuid.uuid4().hex}"+ assert re.fullmatch(r"drama_concurrency_test_[0-9a-f]{32}", schema)+ engine = base_engine.execution_options(schema_translate_map={None: schema})+ sessions = async_sessionmaker(engine, expire_on_commit=False)+ state = SimpleNamespace(engine=engine, sessions=sessions, request_pids=[])+ try:+ async with base_engine.begin() as connection:+ await connection.execute(text(f'CREATE SCHEMA "{schema}"'))+ async with engine.begin() as connection:+ tables = [item.__table__ for item in (+ User, Template, Project, Shot, DramaProject, DramaScript,+ DramaAsset, DramaEpisode, DramaEpisodeFragment, TaskRun,+ )]+ await connection.run_sync(lambda sync: Base.metadata.create_all(sync, tables=tables))+ await connection.run_sync(MarketBase.metadata.create_all)+ async with sessions() as db:+ owner = User(email="[email protected]", hashed_password="unused")+ db.add(owner)+ await db.flush()+ project = DramaProject(user_id=owner.id, title="并发整集发布", description="独立来源快照")+ db.add(project)+ await db.flush()+ episode = DramaEpisode(project_id=project.id, name="第1集", params={"episodeNumber": 1})+ db.add(episode)+ await db.flush()+ for order in range(3):+ db.add(DramaEpisodeFragment(episode_id=episode.id, sort_order=order,+ video=f"/static/test/concurrent-shot-{order}.mp4"))+ await db.commit()+ state.owner_id, state.project_id, state.episode_id = owner.id, project.id, episode.id++ async def db_override():+ # No shared outer transaction or savepoint: each HTTP request must+ # really commit, release PG locks and expose rows to the other.+ async with sessions() as db:+ state.request_pids.append(await db.scalar(text("SELECT pg_backend_pid()")))+ try:+ yield db+ except BaseException:+ await db.rollback()+ raise++ async def actor_override():+ return SimpleNamespace(id=state.owner_id, role="user")++ monkeypatch.setattr(storage, "bucket", lambda: object())+ monkeypatch.setattr(storage, "configured", lambda: True)+ monkeypatch.setattr(drama_media, "source_stamp", lambda locator: {+ "kind": "local", "locator": locator, "size_bytes": 100,+ "file_id": "stable-source", "mtime_ns": 1, "fingerprint": "test-source",+ })+ async with sessions() as db:+ snapshot = await drama_publish.episode_snapshot(db, state.owner_id, state.project_id, state.episode_id)+ state.source_version = snapshot["source_version"]+ app = FastAPI()+ app.include_router(drama_publish.router, prefix="/api/marketplace")+ app.dependency_overrides[get_db] = db_override+ app.dependency_overrides[get_current_user] = actor_override+ async with (+ httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://first") as first,+ httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://second") as second,+ ):+ state.clients = (first, second)+ yield state+ finally:+ # The generated identifier is checked again at the destructive boundary.+ # No shared/public schema or pre-existing test tables are touched.+ assert re.fullmatch(r"drama_concurrency_test_[0-9a-f]{32}", schema)+ async with base_engine.begin() as connection:+ await connection.execute(text(f'DROP SCHEMA IF EXISTS "{schema}" CASCADE'))+ await base_engine.dispose()+++def payload(ctx, key, *, series_id=None, series_version=None):+ return {"episodes": [{"episode_id": ctx.episode_id, "source_version": ctx.source_version}],+ "idempotency_key": key, "series_id": series_id, "series_version": series_version}+++async def wait_for_two_database_waiters(ctx):+ """不依赖调度运气:确认两个不同 PG 连接实际争用锁后才放行。"""+ async with asyncio.timeout(10):+ async with ctx.engine.connect() as observer:+ while True:+ if len(ctx.request_pids) == 2:+ first, second = ctx.request_pids+ assert first != second, "必须使用两个独立数据库连接"+ waiting = set((await observer.execute(text(+ "SELECT DISTINCT pid FROM pg_locks WHERE pid IN (:first, :second) AND NOT granted"+ ), {"first": first, "second": second})).scalars().all())+ if waiting == {first, second}:+ return+ await asyncio.sleep(0.01)+++async def race_requests(ctx, bodies, *, guard_key=None, guard_series_id=None):+ """第三个事务先持锁,让两个请求确定重叠;释放后使用真实提交顺序。"""+ tasks = []+ async with ctx.sessions() as guard:+ try:+ if guard_key is not None:+ lock_id = int(drama_publish.digest([ctx.owner_id, guard_key])[:16], 16)+ if lock_id >= 2**63:+ lock_id -= 2**64+ await guard.execute(text("SELECT pg_advisory_xact_lock(:key)"), {"key": lock_id})+ else:+ await guard.execute(select(Series).where(Series.id == guard_series_id).with_for_update())+ path = f"/api/marketplace/printfilm/dramas/{ctx.project_id}/publish"+ tasks = [asyncio.create_task(client.post(path, json=body)) for client, body in zip(ctx.clients, bodies)]+ await wait_for_two_database_waiters(ctx)+ assert not any(task.done() for task in tasks)+ await guard.commit()+ return await asyncio.wait_for(asyncio.gather(*tasks), timeout=10)+ finally:+ await guard.rollback()+ for task in tasks:+ if not task.done():+ task.cancel()+ if tasks:+ await asyncio.gather(*tasks, return_exceptions=True)+++async def test_concurrent_same_key_new_series_creates_one_batch_episode_and_handoff(concurrent_publish_ctx):+ ctx = concurrent_publish_ctx+ key = uuid.uuid4().hex+ body = payload(ctx, key)+ responses = await race_requests(ctx, (body, body), guard_key=key)+ assert [response.status_code for response in responses] == [200, 200], [response.text for response in responses]+ assert responses[0].json() == responses[1].json()+ async with ctx.sessions() as db:+ for model in (Series, DramaPublishBatch, SeriesEpisode, Handoff):+ assert await db.scalar(select(func.count()).select_from(model)) == 1+ target = (await db.execute(select(SeriesEpisode))).scalar_one()+ handoff = (await db.execute(select(Handoff))).scalar_one()+ batch = (await db.execute(select(DramaPublishBatch))).scalar_one()+ assert batch.episode_ids == [target.id] and batch.handoff_ids == [handoff.id]+ assert handoff.target_id == target.id and handoff.status == "pending"+ assert [clip["sort_order"] for clip in handoff.source_snapshot["clips"]] == [0, 1, 2]+++async def test_concurrent_different_keys_same_target_source_version_never_duplicates_episode(concurrent_publish_ctx):+ ctx = concurrent_publish_ctx+ async with ctx.sessions() as db:+ target = Series(owner_id=ctx.owner_id, title="已有系列", description="保留已有简介")+ db.add(target)+ await db.commit()+ series_id, version = target.id, target.version+ bodies = [payload(ctx, uuid.uuid4().hex, series_id=series_id, series_version=version) for _ in range(2)]+ responses = await race_requests(ctx, bodies, guard_series_id=series_id)+ statuses = [response.status_code for response in responses]+ assert 200 in statuses and all(status in (200, 409) for status in statuses), [response.text for response in responses]+ successes = [response.json() for response in responses if response.status_code == 200]+ assert len({item["items"][0]["id"] for item in successes}) == 1+ assert len({item["handoffs"][0]["id"] for item in successes}) == 1+ async with ctx.sessions() as db:+ for model in (Series, SeriesEpisode, Handoff):+ assert await db.scalar(select(func.count()).select_from(model)) == 1+ assert await db.scalar(select(func.count()).select_from(DramaPublishBatch)) == len(successes)+ target = await db.get(Series, series_id)+ assert target.title == "已有系列" and target.description == "保留已有简介"+ assert target.version == version + 1diff --git a/backend/tests/test_marketplace_drama_media.py b/backend/tests/test_marketplace_drama_media.pynew file mode 100644index 0000000..b2a4fb1--- /dev/null+++ b/backend/tests/test_marketplace_drama_media.py@@ -0,0 +1,216 @@+"""真实 FFmpeg 校验整集顺序、音频与画质;OSS 只使用测试文件替身。"""+import os+from pathlib import Path+import shutil+import struct+from types import SimpleNamespace++import pytest++from app.marketplace import drama_media as media+++def local_media(tmp_path, monkeypatch):+ static = tmp_path / "static"+ static.mkdir()+ cache = tmp_path / "private-cache"+ cache.mkdir()+ monkeypatch.setattr(media, "STATIC_ROOT", static)+ monkeypatch.setattr(media, "cache_root", lambda: cache)+ paths = list(Path("C:/soft/ffmpeg").glob("*/bin/ffmpeg.exe"))+ ffmpeg = shutil.which("ffmpeg") or (str(paths[0]) if paths else "ffmpeg")+ ffprobe = str(Path(ffmpeg).with_name("ffprobe.exe" if ffmpeg.endswith(".exe") else "ffprobe"))+ settings = SimpleNamespace(public_base_url="http://localhost:8000", oss_folder="kepu", oss_bucket="test-bucket",+ oss_endpoint="oss-cn-hangzhou.aliyuncs.com", oss_public_base="https://media.example.test/assets",+ ffmpeg_path=ffmpeg, ffprobe_path=ffprobe)+ monkeypatch.setattr(media, "get_settings", lambda: settings)+ uploaded = tmp_path / "uploaded.mp4"+ def upload(key, source, content_type):+ assert key.startswith("marketplace/")+ assert content_type == "video/mp4"+ assert cache in source.parents+ shutil.copyfile(source, uploaded)+ monkeypatch.setattr(media.storage, "upload", upload)+ return static, cache, uploaded, settings+++def test_local_stamp_and_version_changes_when_same_length_file_changes(local_media):+ static, _cache, _uploaded, _settings = local_media+ source = static / "demo.mp4"+ source.write_bytes(b"first")+ before = media.source_stamp("/static/demo.mp4")+ old_stat = source.stat()+ source.write_bytes(b"other")+ os.utime(source, ns=(old_stat.st_atime_ns, old_stat.st_mtime_ns))+ after = media.source_stamp("/static/demo.mp4")+ assert before["size_bytes"] == after["size_bytes"]+ assert before["mtime_ns"] == after["mtime_ns"]+ assert media.stamp_version(before) != media.stamp_version(after)++[email protected]("locator", ["/static/../secret.mp4", "https://evil.test/kepu/generated/p1/video.mp4",+ "https://test-bucket.oss-cn-hangzhou.aliyuncs.com.evil.test/kepu/generated/a.mp4", "kepu/secrets/a.mp4",+ "marketplace/works/1/a.mp4", "https://media.example.test/not-assets/kepu/generated/a.mp4"])+def test_source_locator_rejects_untrusted_paths(local_media, locator):+ with pytest.raises(ValueError, match="MARKETPLACE_SOURCE_NOT_READY"):+ media.source_stamp(locator)+++def test_absolute_file_outside_static_is_rejected(local_media, tmp_path):+ outside = tmp_path / "outside.mp4"+ outside.write_bytes(b"not permitted")+ with pytest.raises(ValueError, match="MARKETPLACE_SOURCE_NOT_READY"):+ media.source_stamp(str(outside))+++def test_oss_stamp_ignores_temporary_signed_query(local_media, monkeypatch):+ monkeypatch.setattr(media.storage, "source_metadata", lambda key: {"etag": "ABCDEF", "size_bytes": 50})+ first = media.source_stamp("https://test-bucket.oss-cn-hangzhou.aliyuncs.com/kepu/generated/p1/a.mp4?Expires=1")+ second = media.source_stamp("https://test-bucket.oss-cn-hangzhou.aliyuncs.com/kepu/generated/p1/a.mp4?Expires=2")+ assert first["key"] == "kepu/generated/p1/a.mp4"+ assert media.stamp_version(first) == media.stamp_version(second)+ cdn = media.source_stamp("https://media.example.test/assets/kepu/generated/p1/a.mp4?signature=hidden")+ assert media.stamp_version(first) == media.stamp_version(cdn)+++async def test_source_change_is_rejected_before_upload(local_media):+ static, cache, uploaded, _settings = local_media+ source = static / "demo.mp4"+ source.write_bytes(b"first")+ stamp = media.source_stamp("/static/demo.mp4")+ source.write_bytes(b"new source")+ snapshot = {"schema_version": 2, "clips": [{"id": 1, "sort_order": 0, "locator": "/static/demo.mp4", "stamp": stamp}]}+ with pytest.raises(ValueError, match="MARKETPLACE_SOURCE_CHANGED"):+ await media.prepare_drama_video(snapshot, "marketplace/test/episode.mp4")+ assert not uploaded.exists()+ assert not list(cache.iterdir())+++async def _clip(settings, path, color, size="160x90", duration=0.6, audio=False):+ if not Path(settings.ffmpeg_path).is_file() and not shutil.which(settings.ffmpeg_path):+ pytest.skip("FFmpeg is not available")+ args = [settings.ffmpeg_path, "-y", "-v", "error", "-f", "lavfi", "-i", f"color=c={color}:s={size}:r=10:d={duration}"]+ if audio:+ args += ["-f", "lavfi", "-i", f"sine=frequency=1000:sample_rate=48000:duration={duration}", "-c:a", "aac", "-ar", "48000", "-ac", "2"]+ else:+ args += ["-an"]+ await media.command(*args, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-r", "10", "-g", "10", "-crf", "18",+ "-video_track_timescale", "90000", "-t", str(duration), str(path), timeout=30)+++def _snapshot(static, paths):+ return {"schema_version": 2, "clips": [{"id": i + 1, "sort_order": i,+ "locator": "/static/" + path.relative_to(static).as_posix(),+ "stamp": media.source_stamp("/static/" + path.relative_to(static).as_posix())} for i, path in enumerate(paths)]}+++async def _pixel(settings, path, time):+ raw = await media.command(settings.ffmpeg_path, "-v", "error", "-ss", str(time), "-i", str(path),+ "-vf", "scale=1:1", "-frames:v", "1", "-pix_fmt", "rgb24", "-f", "rawvideo", "-", timeout=30)+ return tuple(raw[:3])+++async def test_three_color_full_episode_preserves_order_and_duration(local_media, monkeypatch):+ static, cache, uploaded, settings = local_media+ paths = [static / f"clip-{i}.mp4" for i in range(3)]+ for path, color, duration in zip(paths, ("red", "lime", "blue"), (0.6, 0.7, 0.8)):+ await _clip(settings, path, color, duration=duration)+ async def forbidden(*_args):+ raise AssertionError("compatible clips must use lossless concatenation")+ monkeypatch.setattr(media, "_encode", forbidden)+ phases = []+ async def progress(phase):+ phases.append(phase)+ result = await media.prepare_drama_video(_snapshot(static, paths), "marketplace/test/full.mp4", progress)+ assert result["duration_seconds"] == pytest.approx(2.1, abs=0.15)+ assert result["fingerprint"] == media.fingerprint(uploaded)+ assert result["size_bytes"] == uploaded.stat().st_size+ assert phases == ["copying", "composing", "validating"]+ for index, time in enumerate((0.2, 0.9, 1.7)):+ pixel = await _pixel(settings, uploaded, time)+ assert pixel[index] > 180 and all(value < 60 for other, value in enumerate(pixel) if other != index)+ assert not list(cache.iterdir())+++async def test_mixed_sizes_and_audio_use_highest_source_resolution(local_media):+ static, cache, uploaded, settings = local_media+ paths = [static / f"clip-{i}.mp4" for i in range(3)]+ for path, color, size, duration, audio in zip(paths, ("red", "lime", "blue"), ("160x90", "320x180", "160x90"),+ (0.6, 0.7, 0.8), (False, True, False)):+ await _clip(settings, path, color, size=size, duration=duration, audio=audio)+ result = await media.prepare_drama_video(_snapshot(static, paths), "marketplace/test/full.mp4")+ info = await media._probe(uploaded)+ assert (info["width"], info["height"]) == (320, 180)+ assert info["audio"]+ assert result["duration_seconds"] == pytest.approx(2.1, abs=0.15)+ for index, time in enumerate((0.2, 0.9, 1.7)):+ pixel = await _pixel(settings, uploaded, time)+ assert pixel[index] > 180 and all(value < 60 for other, value in enumerate(pixel) if other != index)+ volumes = []+ for time in (0.2, 0.9, 1.7):+ raw = await media.command(settings.ffmpeg_path, "-v", "error", "-ss", str(time), "-i", str(uploaded),+ "-t", "0.1", "-vn", "-ac", "1", "-f", "f32le", "-", timeout=30)+ samples = struct.unpack("<" + "f" * (len(raw) // 4), raw)+ volumes.append(max(abs(value) for value in samples))+ assert volumes[1] > 0.05+ assert volumes[0] < 0.005 and volumes[2] < 0.005+ assert not list(cache.iterdir())+++async def test_single_clip_is_not_reencoded(local_media, monkeypatch):+ static, _cache, uploaded, settings = local_media+ source = static / "single.mp4"+ await _clip(settings, source, "red", size="320x180")+ async def forbidden(*_args):+ raise AssertionError("single clip must not be encoded")+ monkeypatch.setattr(media, "_encode", forbidden)+ await media.prepare_drama_video(_snapshot(static, [source]), "marketplace/test/single.mp4")+ before, after = await media._probe(source), await media._probe(uploaded)+ assert before["video"]["extradata"] == after["video"]["extradata"]+ assert (after["width"], after["height"]) == (320, 180)+++async def test_different_aspect_ratios_fail_without_upload(local_media):+ static, cache, uploaded, settings = local_media+ paths = [static / "portrait.mp4", static / "landscape.mp4"]+ await _clip(settings, paths[0], "red", size="90x160")+ await _clip(settings, paths[1], "blue", size="160x90")+ with pytest.raises(ValueError, match="MARKETPLACE_SOURCE_INCOMPATIBLE"):+ await media.prepare_drama_video(_snapshot(static, paths), "marketplace/test/invalid.mp4")+ assert not uploaded.exists()+ assert not list(cache.iterdir())+++async def test_cover_uses_private_copy_and_validates_image(local_media, monkeypatch):+ static, cache, _uploaded, settings = local_media+ source = static / "cover.png"+ await media.command(settings.ffmpeg_path, "-y", "-v", "error", "-f", "lavfi", "-i", "color=c=blue:s=120x80",+ "-frames:v", "1", str(source), timeout=30)+ captured = {}+ def upload(key, path, content_type):+ captured.update(key=key, content_type=content_type, size=path.stat().st_size)+ assert cache in path.parents+ monkeypatch.setattr(media.storage, "upload", upload)+ stamp = media.source_stamp("/static/cover.png")+ result = await media.prepare_drama_cover("/static/cover.png", "marketplace/test/cover.png", stamp)+ assert (result["width"], result["height"]) == (120, 80)+ assert captured["content_type"] == "image/png"+ assert captured["size"] == result["size_bytes"]+ assert not list(cache.iterdir())+++async def test_invalid_cover_does_not_upload(local_media):+ static, cache, uploaded, _settings = local_media+ (static / "fake.png").write_text("not an image", encoding="utf-8")+ with pytest.raises(ValueError, match="MARKETPLACE_SOURCE_NOT_READY"):+ await media.prepare_drama_cover("/static/fake.png", "marketplace/test/cover.png")+ assert not uploaded.exists()+ assert not list(cache.iterdir())diff --git a/backend/tests/test_marketplace_drama_publish.py b/backend/tests/test_marketplace_drama_publish.pynew file mode 100644index 0000000..3bfd0f8--- /dev/null+++ b/backend/tests/test_marketplace_drama_publish.py@@ -0,0 +1,380 @@+"""漫剧到市场的整集发布:隔离测试库/schema,文件存储仅使用测试替身。"""+from types import SimpleNamespace+from contextlib import asynccontextmanager+from datetime import timedelta+import uuid++from fastapi import FastAPI, HTTPException+import httpx+import pytest+import pytest_asyncio+from sqlalchemy import func, select, text+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine++from app.config import get_settings+from app.database import Base, get_db+from app.deps import get_current_user+from app.models import Project, Shot, Template, User+from app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, DramaProject, DramaScript+from app.models_tasks import TaskRun+from app.marketplace import drama_media, drama_publish, handoff, storage+from app.marketplace.authorization import VERSION+from app.marketplace.models import Asset, Authorization, DramaPublishBatch, Handoff, MarketBase, Publication, Rights, Series, SeriesEpisode+from app.marketplace.service import now+from conftest import _ensure_test_database, _resolve_test_database_url+++@pytest_asyncio.fixture+async def drama_publish_ctx(monkeypatch):+ url, name = _resolve_test_database_url(get_settings().database_url)+ await _ensure_test_database(url, name)+ engine = create_async_engine(url)+ async with engine.connect() as connection:+ outer = await connection.begin()+ schema = f"drama_publish_test_{uuid.uuid4().hex}"+ await connection.execute(text(f'CREATE SCHEMA "{schema}"'))+ connection = await connection.execution_options(schema_translate_map={None: schema})+ tables = [item.__table__ for item in (User, Template, Project, Shot, DramaProject, DramaScript, DramaAsset, DramaEpisode, DramaEpisodeFragment, TaskRun)]+ await connection.run_sync(lambda sync: Base.metadata.create_all(sync, tables=tables))+ await connection.run_sync(MarketBase.metadata.create_all)+ db = AsyncSession(bind=connection, expire_on_commit=False, join_transaction_mode="create_savepoint")+ owner = User(email="[email protected]", hashed_password="unused")+ other = User(email="[email protected]", hashed_password="unused")+ db.add_all([owner, other])+ await db.commit()+ ctx = SimpleNamespace(db=db, owner=owner, other=other, user=owner, source_revision=1)++ async def db_override():+ try:+ yield db+ except Exception:+ await db.rollback()+ await db.refresh(owner)+ await db.refresh(other)+ raise++ async def actor_override():+ return ctx.user++ def source_stamp(locator):+ return {"kind": "local", "locator": locator, "size_bytes": 100, "file_id": "source-file", "mtime_ns": ctx.source_revision, "fingerprint": f"revision-{ctx.source_revision}"}++ app = FastAPI()+ app.include_router(drama_publish.router, prefix="/api/marketplace")+ app.include_router(handoff.router, prefix="/api/marketplace")+ app.dependency_overrides[get_db] = db_override+ app.dependency_overrides[get_current_user] = actor_override+ monkeypatch.setattr(storage, "bucket", lambda: object())+ monkeypatch.setattr(storage, "configured", lambda: True)+ monkeypatch.setattr(drama_media, "source_stamp", source_stamp)+ try:+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:+ ctx.client = client+ yield ctx+ finally:+ await db.close()+ await outer.rollback()+ await engine.dispose()+++async def source(ctx, *, owner=None, episodes=1, fragments=3):+ project = DramaProject(user_id=(owner or ctx.owner).id, title="完整漫剧", description="导入后的独立介绍")+ ctx.db.add(project)+ await ctx.db.flush()+ items, clips = [], []+ for number in range(1, episodes + 1):+ episode = DramaEpisode(project_id=project.id, name=f"原第{number}集", params={"episodeNumber": number})+ ctx.db.add(episode)+ await ctx.db.flush()+ for index in range(fragments):+ # 故意逆序创建,用排序断言防止只导入最后一镜。+ order = fragments - index - 1+ clip = DramaEpisodeFragment(episode_id=episode.id, sort_order=order, video=f"/static/test/episode-{number}-shot-{order}.mp4", cover=f"/static/test/cover-{number}.png")+ ctx.db.add(clip)+ clips.append(clip)+ items.append(episode)+ await ctx.db.commit()+ return project, items, clips+++async def publish_payload(ctx, project, episodes, *, key=None, series=None, update=False):+ snapshot = [await drama_publish.episode_snapshot(ctx.db, ctx.owner.id, project.id, episode.id) for episode in episodes]+ return {"episodes": [{"episode_id": item["drama_episode_id"], "source_version": item["source_version"], "update": update} for item in snapshot],+ "series_id": series.id if series else None, "series_version": series.version if series else None, "idempotency_key": key or uuid.uuid4().hex}+++async def post_publish(ctx, project, payload):+ return await ctx.client.post(f"/api/marketplace/printfilm/dramas/{project.id}/publish", json=payload)+++async def published(ctx):+ project, episodes, clips = await source(ctx)+ response = await post_publish(ctx, project, await publish_payload(ctx, project, episodes))+ assert response.status_code == 200, response.text+ body = response.json()+ task = await ctx.db.get(Handoff, body["handoffs"][0]["id"])+ target = await ctx.db.get(SeriesEpisode, body["items"][0]["id"])+ series = await ctx.db.get(Series, body["series_id"])+ return SimpleNamespace(project=project, episodes=episodes, clips=clips, task=task, target=target, series=series)+++async def test_context_shows_complete_counts_and_all_owned_target_series(drama_publish_ctx):+ ctx = drama_publish_ctx+ project, episodes, clips = await source(ctx, episodes=2)+ clips[0].video = ""+ own = Series(owner_id=ctx.owner.id, title="我的其他系列")+ foreign = Series(owner_id=ctx.other.id, title="其他人的系列")+ ctx.db.add_all([own, foreign])+ await ctx.db.commit()+ response = await ctx.client.get(f"/api/marketplace/printfilm/dramas/{project.id}/publish-context")+ assert response.status_code == 200, response.text+ body = response.json()+ assert body["project"]["description"] == project.description+ assert body["episodes"][0]["fragment_count"] == 3 and body["episodes"][0]["completed_count"] == 2+ assert body["episodes"][0]["ready"] is False and "SOURCE_NOT_READY" in body["episodes"][0]["reason"]+ assert body["episodes"][1]["ready"] is True+ assert [item["id"] for item in body["series"]] == [own.id]+ assert body["storage_configured"] is True and body["authorization_ready"] is False+ assert "/static/" not in response.text++[email protected]("case", ["foreign_project", "foreign_episode", "foreign_target"])+async def test_publish_rejects_cross_account_sources_and_targets(drama_publish_ctx, case):+ ctx = drama_publish_ctx+ project, episodes, _ = await source(ctx)+ payload = await publish_payload(ctx, project, episodes)+ if case == "foreign_project":+ ctx.user = ctx.other+ elif case == "foreign_episode":+ other_project, other_episodes, _ = await source(ctx, owner=ctx.other)+ payload["episodes"][0]["episode_id"] = other_episodes[0].id+ else:+ target = Series(owner_id=ctx.other.id, title="其他系列")+ ctx.db.add(target)+ await ctx.db.commit()+ payload["series_id"] = target.id+ payload["series_version"] = target.version+ response = await post_publish(ctx, project, payload)+ assert response.status_code == 404, response.text+ assert await ctx.db.scalar(select(func.count()).select_from(Handoff)) == 0+ assert await ctx.db.scalar(select(func.count()).select_from(DramaPublishBatch)) == 0++[email protected]("case", ["missing_shot", "task_video", "task_plan", "episode_plan", "shot_video"])+async def test_incomplete_or_generating_episode_creates_no_market_draft(drama_publish_ctx, case):+ ctx = drama_publish_ctx+ project, episodes, clips = await source(ctx)+ payload = await publish_payload(ctx, project, episodes)+ if case == "missing_shot":+ clips[0].video = ""+ elif case.startswith("task_"):+ ctx.db.add(TaskRun(domain="drama", task_type="fragment_video" if case == "task_video" else "fragment_plan", status="running", requested_by=ctx.owner.id,+ episode_id=episodes[0].id, drama_project_id=project.id, fragment_id=clips[0].id))+ elif case == "episode_plan":+ episodes[0].params = {"episodeNumber": 1, "fragment_plan_status": "running"}+ else:+ clips[0].params = {"video_gen": {"status": "running"}}+ await ctx.db.commit()+ response = await post_publish(ctx, project, payload)+ assert response.status_code == 409 and "MARKETPLACE_SOURCE_NOT_READY" in response.text+ assert await ctx.db.scalar(select(func.count()).select_from(Series)) == 0+ assert await ctx.db.scalar(select(func.count()).select_from(Handoff)) == 0+++async def test_storage_unavailable_never_creates_empty_series(drama_publish_ctx, monkeypatch):+ ctx = drama_publish_ctx+ project, episodes, _ = await source(ctx)+ payload = await publish_payload(ctx, project, episodes)++ def unavailable():+ raise HTTPException(503, {"code": "MARKETPLACE_STORAGE_UNAVAILABLE", "message": "文件服务暂未配置"})++ monkeypatch.setattr(storage, "bucket", unavailable)+ response = await post_publish(ctx, project, payload)+ assert response.status_code == 503 and "MARKETPLACE_STORAGE_UNAVAILABLE" in response.text+ assert await ctx.db.scalar(select(func.count()).select_from(Series)) == 0+++async def test_atomic_publish_is_idempotent_orders_all_clips_and_keeps_upstream(drama_publish_ctx):+ ctx = drama_publish_ctx+ project, episodes, clips = await source(ctx, episodes=2)+ payload = await publish_payload(ctx, project, list(reversed(episodes)))+ response = await post_publish(ctx, project, payload)+ assert response.status_code == 200, response.text+ result = response.json()+ again = await post_publish(ctx, project, payload)+ assert again.status_code == 200 and again.json() == result+ assert await ctx.db.scalar(select(func.count()).select_from(Series)) == 1+ assert await ctx.db.scalar(select(func.count()).select_from(SeriesEpisode)) == 2+ assert await ctx.db.scalar(select(func.count()).select_from(Handoff)) == 2+ target = await ctx.db.get(Series, result["series_id"])+ assert target.title == project.title and target.description == project.description+ for index, item in enumerate(result["items"]):+ assert item["episode_no"] == index + 1 and item["title"] == episodes[index].name+ task = await ctx.db.get(Handoff, result["handoffs"][index]["id"])+ assert [clip["sort_order"] for clip in task.source_snapshot["clips"]] == [0, 1, 2]+ assert len(task.source_snapshot["clips"]) == 3+ assert all(clip.video.startswith("/static/test/") for clip in clips)+ payload["title"] = "另一次不同发布"+ conflict = await post_publish(ctx, project, payload)+ assert conflict.status_code == 409+++async def test_same_source_version_in_same_target_reuses_episode_across_batches(drama_publish_ctx):+ ctx = drama_publish_ctx+ existing = await published(ctx)+ response = await post_publish(ctx, existing.project, await publish_payload(ctx, existing.project, existing.episodes, series=existing.series))+ assert response.status_code == 200, response.text+ assert response.json()["items"][0]["id"] == existing.target.id+ assert response.json()["handoffs"][0]["id"] == existing.task.id+ assert await ctx.db.scalar(select(func.count()).select_from(SeriesEpisode)) == 1+ assert await ctx.db.scalar(select(func.count()).select_from(Handoff)) == 1+++async def test_changed_source_requires_confirmation_and_preserves_old_publication_asset(drama_publish_ctx):+ ctx = drama_publish_ctx+ existing = await published(ctx)+ old_asset = Asset(owner_id=ctx.owner.id, kind="video", filename="old.mp4", content_type="video/mp4", size_bytes=100, object_key="marketplace/old.mp4", status="ready")+ ctx.db.add(old_asset)+ await ctx.db.flush()+ existing.target.asset_id, existing.target.audit_status, existing.target.listed = old_asset.id, "approved", True+ existing.target.source_snapshot = {**existing.target.source_snapshot, "pending_handoff_id": None, "last_handoff_id": existing.task.id}+ existing.task.status, existing.task.asset_id = "ready", old_asset.id+ existing.series.audit_status, existing.series.listed = "approved", True+ publication = Publication(content_type="series_episode", content_id=existing.target.id, owner_id=ctx.owner.id, version=existing.target.version,+ asset_id=old_asset.id, sale_type="copyright_contact", audit_status="approved", listed=True)+ ctx.db.add(publication)+ await ctx.db.commit()+ ctx.source_revision = 2+ payload = await publish_payload(ctx, existing.project, existing.episodes, series=existing.series)+ response = await post_publish(ctx, existing.project, payload)+ assert response.status_code == 409 and "SOURCE_CHANGED" in response.text+ # Failed request rolls back the savepoint; fetch state again before a new request.+ await ctx.db.refresh(existing.series)+ await ctx.db.refresh(existing.target)+ await ctx.db.refresh(publication)+ await ctx.db.refresh(existing.project)+ await ctx.db.refresh(old_asset)+ for episode in existing.episodes:+ await ctx.db.refresh(episode)+ payload = await publish_payload(ctx, existing.project, existing.episodes, series=existing.series, update=True)+ response = await post_publish(ctx, existing.project, payload)+ assert response.status_code == 200, response.text+ assert response.json()["items"][0]["id"] == existing.target.id+ assert existing.target.asset_id == old_asset.id and publication.asset_id == old_asset.id+ assert existing.series.listed is False and existing.series.audit_status == "draft"+ assert existing.target.listed is False and publication.listed is False+ assert await ctx.db.scalar(select(func.count()).select_from(Handoff)) == 2++[email protected]("case", ["version", "asset", "new_task", "blocked", "deleted_series"])+async def test_fenced_bind_never_overwrites_modified_deleted_or_superseded_target(drama_publish_ctx, case):+ ctx = drama_publish_ctx+ existing = await published(ctx)+ candidate = Asset(owner_id=ctx.owner.id, kind="video", filename="new.mp4", content_type="video/mp4", size_bytes=100, object_key=f"marketplace/{uuid.uuid4().hex}.mp4", status="ready")+ ctx.db.add(candidate)+ await ctx.db.flush()+ if case == "version":+ existing.target.version += 1+ elif case == "asset":+ existing.target.asset_id = candidate.id+ elif case == "new_task":+ existing.target.source_snapshot = {**existing.target.source_snapshot, "pending_handoff_id": existing.task.id + 1}+ elif case == "blocked":+ existing.target.blocked = True+ else:+ existing.series.deleted_at = now()+ before = existing.target.asset_id+ await ctx.db.flush()+ with pytest.raises(HTTPException, match="MARKETPLACE_TARGET_CHANGED"):+ await handoff._bind(ctx.db, existing.task, candidate.id, None)+ assert existing.target.asset_id == before+++async def test_successful_bind_auto_attaches_authorization_without_approving_rights(drama_publish_ctx):+ ctx = drama_publish_ctx+ existing = await published(ctx)+ ctx.db.add(Authorization(owner_id=ctx.owner.id, template_version=VERSION, signer_name="测试用户", body="terms", body_hash="0"*64,+ letter_key="marketplace/letter.png", signature_key="marketplace/signature.png", client_ip="127.0.0.1", user_agent="test"))+ candidate = Asset(owner_id=ctx.owner.id, kind="video", filename="new.mp4", content_type="video/mp4", size_bytes=100, object_key="marketplace/new.mp4", status="ready")+ ctx.db.add(candidate)+ await ctx.db.flush()+ existing.task.asset_id = candidate.id+ await handoff._bind(ctx.db, existing.task, candidate.id, None)+ await ctx.db.flush()+ proof = (await ctx.db.execute(select(Rights).where(Rights.asset_id == candidate.id))).scalar_one()+ assert existing.target.asset_id == candidate.id and existing.task.status == "ready"+ assert proof.details["source"] == "printfilm" and int(proof.details["authorization_id"]) > 0+ assert proof.basic_status != "approved" and proof.full_status != "approved"+++async def test_source_file_change_is_detected_before_worker_binding(drama_publish_ctx):+ ctx = drama_publish_ctx+ existing = await published(ctx)+ ctx.source_revision += 1+ with pytest.raises(HTTPException, match="MARKETPLACE_SOURCE_CHANGED"):+ await handoff._validate_drama_source(ctx.db, existing.task)+ assert existing.target.asset_id is None++[email protected]("case", ["success", "source_changed", "target_changed", "lease_stolen", "resume_expired_lease"])+async def test_worker_recovery_and_final_binding_guards(drama_publish_ctx, monkeypatch, case):+ """实际执行领取/阶段/终态;仅替换远端存储与媒体制作,不伪造任务状态。"""+ ctx = drama_publish_ctx+ existing = await published(ctx)+ discarded, produced, phases = [], [], []+ original_phase = handoff._phase++ @asynccontextmanager+ async def sessions():+ # 每个 worker 阶段顺序使用同一测试连接,保持随机 schema 和外层回滚。+ yield ctx.db++ async def phase(handoff_id, token, value):+ phases.append(value)+ return await original_phase(handoff_id, token, value)++ async def prepare_video(snapshot, destination, on_phase):+ assert [item["sort_order"] for item in snapshot["clips"]] == [0, 1, 2]+ produced.append(destination)+ for value in ("copying", "composing", "validating"):+ await on_phase(value)+ if case == "source_changed":+ ctx.source_revision += 1+ elif case == "target_changed":+ existing.target.version += 1+ await ctx.db.commit()+ elif case == "lease_stolen":+ existing.task.lease_token = "other-worker"+ await ctx.db.commit()+ return {"size_bytes": 100, "content_type": "video/mp4", "fingerprint": "f"*64, "duration_seconds": 9.0}++ async def prepare_cover(_locator, destination, _stamp=None):+ produced.append(destination)+ return {"size_bytes": 10, "content_type": "image/png"}++ monkeypatch.setattr(handoff, "AsyncSessionLocal", sessions)+ monkeypatch.setattr(handoff, "_phase", phase)+ monkeypatch.setattr(drama_media, "prepare_drama_video", prepare_video)+ monkeypatch.setattr(drama_media, "prepare_drama_cover", prepare_cover)+ monkeypatch.setattr(storage, "discard_generated", discarded.append)+ if case == "resume_expired_lease":+ existing.task.status, existing.task.lease_token = "running", "dead-worker"+ existing.task.lease_until = now() - timedelta(seconds=1)+ await ctx.db.commit()+ assert await handoff.run_handoff_once() is True+ assert phases == ["copying", "composing", "validating"]+ if case in ("success", "resume_expired_lease"):+ assert existing.task.status == "ready" and existing.target.asset_id is not None+ assert existing.task.lease_token is None and existing.task.lease_until is None+ assert existing.target.cover_asset_id is not None+ assert await ctx.db.scalar(select(func.count()).select_from(Asset)) == 2+ assert discarded == []+ else:+ assert existing.target.asset_id is None and existing.target.cover_asset_id is None+ assert await ctx.db.scalar(select(func.count()).select_from(Asset)) == 0+ assert sorted(discarded) == sorted(produced)+ if case == "lease_stolen":+ assert existing.task.lease_token == "other-worker" # 旧 worker 不得改新租约。+ else:+ assert existing.task.status == "failed" and ("SOURCE_CHANGED" if case == "source_changed" else "TARGET_CHANGED") in existing.task.errordiff --git a/backend/tests/test_marketplace_publication_access.py b/backend/tests/test_marketplace_publication_access.pynew file mode 100644index 0000000..a86bd42--- /dev/null+++ b/backend/tests/test_marketplace_publication_access.py@@ -0,0 +1,377 @@+"""发布版本永久权益与付款回调:独立测试库、随机 schema、事务回滚。"""+from types import SimpleNamespace+import uuid++from fastapi import FastAPI+import httpx+import pytest+import pytest_asyncio+from sqlalchemy import func, select, text+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine++from app.config import get_settings+from app.database import get_db+from app.deps import get_current_user+from app.models import User+from app.marketplace import api, commerce, series as series_api, storage+from app.marketplace.dependencies import optional_user+from app.marketplace.models import (+ Asset, ContentOrder, Entitlement, EpisodePreview, Event, Handoff, MarketBase, Publication,+ RevenueConfig, RevenueLedger, Rights, Series, SeriesEpisode, Work, WorkPreview,+)+from conftest import _ensure_test_database, _resolve_test_database_url+++@pytest_asyncio.fixture+async def publication_ctx(monkeypatch):+ """完全隔离于已有 _test 表;commit 只提交 savepoint,最终回滚 schema。"""+ url, name = _resolve_test_database_url(get_settings().database_url)+ await _ensure_test_database(url, name)+ engine = create_async_engine(url)+ async with engine.connect() as connection:+ outer = await connection.begin()+ schema = f"publication_test_{uuid.uuid4().hex}"+ await connection.execute(text(f'CREATE SCHEMA "{schema}"'))+ connection = await connection.execution_options(schema_translate_map={None: schema})+ await connection.run_sync(lambda sync: User.__table__.create(sync))+ await connection.run_sync(MarketBase.metadata.create_all)+ db = AsyncSession(bind=connection, expire_on_commit=False, join_transaction_mode="create_savepoint")+ owner = User(email="[email protected]", hashed_password="unused")+ buyer = User(email="[email protected]", hashed_password="unused")+ db.add_all([owner, buyer])+ await db.flush()+ state = SimpleNamespace(db=db, owner=owner, buyer=buyer, user=buyer, signed=[], manifests=[])++ async def session_override():+ yield db++ async def user_override():+ return state.user++ app = FastAPI()+ app.include_router(commerce.router, prefix="/api/marketplace")+ app.include_router(series_api.router, prefix="/api/marketplace")+ app.include_router(api.router, prefix="/api/marketplace")+ app.dependency_overrides[get_db] = session_override+ app.dependency_overrides[get_current_user] = user_override+ app.dependency_overrides[optional_user] = user_override+ monkeypatch.setattr(commerce, "_payment_ready", lambda: True)+ monkeypatch.setattr(commerce.epay, "verify", lambda _params: True)+ monkeypatch.setattr(storage, "bucket", lambda: object())++ def read_manifest(key):+ state.manifests.append(key)+ return b"#EXTM3U\n#EXTINF:5,\nsegment-000.ts\n#EXT-X-ENDLIST\n"++ def sign(key, content_type):+ state.signed.append(key)+ return f"https://private.invalid/{key}?expires=300"++ monkeypatch.setattr(storage, "read", read_manifest)+ monkeypatch.setattr(storage, "signed", sign)+ try:+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:+ state.client = client+ yield state+ finally:+ await db.close()+ await outer.rollback()+ await engine.dispose()+++async def make_publication(ctx, *, episode=True):+ asset = Asset(owner_id=ctx.owner.id, kind="video", filename="original.mp4", content_type="video/mp4",+ size_bytes=100, object_key=f"marketplace/originals/{uuid.uuid4().hex}.mp4", status="ready")+ ctx.db.add(asset)+ await ctx.db.flush()+ proof = Rights(owner_id=ctx.owner.id, asset_id=asset.id, basic_status="approved", full_status="approved",+ certificate_asset_id=asset.id, details={"source": "external"})+ ctx.db.add(proof)+ series = None+ if episode:+ series = Series(owner_id=ctx.owner.id, title="series", sale_type="platform_unlock", audit_status="approved", listed=True)+ ctx.db.add(series)+ await ctx.db.flush()+ item = SeriesEpisode(owner_id=ctx.owner.id, series_id=series.id, episode_no=1, title="episode",+ asset_id=asset.id, unlock_price_fen=999, audit_status="approved", listed=True)+ else:+ item = Work(owner_id=ctx.owner.id, title="work", sale_type="platform_unlock", asset_id=asset.id,+ price_fen=1000, unlock_price_fen=999, audit_status="approved", listed=True)+ ctx.db.add(item)+ await ctx.db.flush()+ publication = Publication(content_type="series_episode" if episode else "work", content_id=item.id,+ owner_id=ctx.owner.id, version=1, asset_id=asset.id, sale_type="platform_unlock",+ unlock_price_fen=999, share_bps=2345, audit_status="approved", listed=True,+ playback_status="done", playback_manifest_key="marketplace/hls/old/index.m3u8")+ ctx.db.add(publication)+ await ctx.db.flush()+ return SimpleNamespace(asset=asset, proof=proof, item=item, series=series, publication=publication)+++async def grant(ctx, content):+ entitlement = Entitlement(user_id=ctx.buyer.id, publication_id=content.publication.id,+ episode_id=content.item.id if content.series else None)+ ctx.db.add(entitlement)+ await ctx.db.flush()+ return entitlement+++async def pending_order(ctx, content, *, key=None):+ order = ContentOrder(out_trade_no=f"MKT-{uuid.uuid4().hex}", user_id=ctx.buyer.id,+ publication_id=content.publication.id, episode_id=content.item.id if content.series else None,+ amount_fen=999, pay_type="alipay", idempotency_key=key or uuid.uuid4().hex)+ ctx.db.add(order)+ await ctx.db.flush()+ return order+++def payment_params(order, money="9.99"):+ return {"out_trade_no": order.out_trade_no, "money": money, "trade_status": "TRADE_SUCCESS", "trade_no": "gateway-123"}++[email protected]("episode", [True, False])+async def test_owned_old_publication_plays_original_purchased_hls_after_edit(publication_ctx, episode):+ ctx = publication_ctx+ content = await make_publication(ctx, episode=episode)+ await grant(ctx, content)+ content.item.version = 2+ content.item.audit_status = "draft"+ content.item.listed = False+ content.publication.listed = False+ if content.series:+ content.series.audit_status, content.series.listed = "draft", False+ await ctx.db.flush()+ response = await ctx.client.get(f"/api/marketplace/platform/publications/{content.publication.id}/playback")+ assert response.status_code == 200, response.text+ assert response.json()["kind"] == "hls" and "url" not in response.json()+ assert ctx.manifests == ["marketplace/hls/old/index.m3u8"]+ assert ctx.signed == ["marketplace/hls/old/segment-000.ts"]+ assert content.asset.object_key not in response.text++[email protected]("restriction", ["episode", "series", "rights", "inactive", "missing"])+async def test_old_publication_enforces_live_restrictions_before_signing(publication_ctx, restriction):+ ctx = publication_ctx+ content = await make_publication(ctx)+ entitlement = await grant(ctx, content) if restriction != "missing" else None+ if restriction == "episode":+ content.item.blocked = True+ elif restriction == "series":+ content.series.blocked = True+ elif restriction == "rights":+ content.proof.blocked = True+ elif restriction == "inactive":+ entitlement.active = False+ await ctx.db.flush()+ response = await ctx.client.get(f"/api/marketplace/platform/publications/{content.publication.id}/playback")+ assert response.status_code == 403+ assert ctx.signed == [] and ctx.manifests == []++[email protected]("change", ["version", "draft", "unlisted", "series_draft", "series_unlisted", "blocked", "rights"])+async def test_new_order_cannot_buy_stale_or_hidden_publication(publication_ctx, change):+ ctx = publication_ctx+ content = await make_publication(ctx)+ if change == "version":+ content.item.version = 2+ elif change == "draft":+ content.item.audit_status = "draft"+ elif change == "unlisted":+ content.item.listed = False+ elif change == "series_draft":+ content.series.audit_status = "draft"+ elif change == "series_unlisted":+ content.series.listed = False+ elif change == "blocked":+ content.series.blocked = True+ else:+ content.proof.blocked = True+ await ctx.db.flush()+ response = await ctx.client.post("/api/marketplace/content-orders", json={+ "publication_id": content.publication.id, "pay_type": "alipay", "idempotency_key": uuid.uuid4().hex})+ assert response.status_code == 409, response.text+ assert await ctx.db.scalar(select(func.count()).select_from(ContentOrder)) == 0+++async def test_pending_payment_survives_update_and_duplicate_notification(publication_ctx):+ ctx = publication_ctx+ content = await make_publication(ctx)+ order = await pending_order(ctx, content)+ ctx.db.add(RevenueConfig(id=1, platform_share_bps=9999))+ content.item.version, content.item.listed, content.item.audit_status = 2, False, "draft"+ content.series.listed, content.series.audit_status = False, "draft"+ content.publication.listed = False+ await ctx.db.flush()+ for _ in range(2):+ response = await ctx.client.get("/api/marketplace/payments/epay/notify", params=payment_params(order))+ assert response.status_code == 200 and response.text == "success"+ assert order.status == "paid"+ entitlement = (await ctx.db.execute(select(Entitlement))).scalar_one()+ ledger = (await ctx.db.execute(select(RevenueLedger))).scalar_one()+ assert entitlement.publication_id == content.publication.id and entitlement.active+ assert ledger.gross_fen == 999 and ledger.share_bps == 2345+ assert ledger.platform_fen == 234 and ledger.creator_fen == 765+++async def test_payment_while_blocked_is_recorded_and_playback_remains_blocked(publication_ctx):+ ctx = publication_ctx+ content = await make_publication(ctx)+ order = await pending_order(ctx, content)+ content.proof.blocked = True+ await ctx.db.flush()+ response = await ctx.client.get("/api/marketplace/payments/epay/notify", params=payment_params(order))+ assert response.status_code == 200 and response.text == "success"+ assert order.status == "paid"+ assert await ctx.db.scalar(select(func.count()).select_from(RevenueLedger)) == 1+ assert await ctx.db.scalar(select(func.count()).select_from(Event).where(Event.action == "paid_restricted_review")) == 1+ response = await ctx.client.get(f"/api/marketplace/platform/publications/{content.publication.id}/playback")+ assert response.status_code == 403 and ctx.signed == []+++async def test_second_checkout_payment_does_not_duplicate_entitlement_or_income(publication_ctx):+ ctx = publication_ctx+ content = await make_publication(ctx)+ for _ in range(2):+ order = await pending_order(ctx, content)+ response = await ctx.client.get("/api/marketplace/payments/epay/notify", params=payment_params(order))+ assert response.text == "success"+ assert await ctx.db.scalar(select(func.count()).select_from(Entitlement)) == 1+ assert await ctx.db.scalar(select(func.count()).select_from(RevenueLedger)) == 1+ assert await ctx.db.scalar(select(func.count()).select_from(ContentOrder).where(ContentOrder.status == "paid")) == 2+ assert await ctx.db.scalar(select(func.count()).select_from(Event).where(Event.action == "duplicate_purchase_paid")) == 1++[email protected]("money", ["invalid", "", "9.991", "9.98", "NaN", "Infinity"])+async def test_invalid_payment_amount_never_creates_access(publication_ctx, money):+ ctx = publication_ctx+ content = await make_publication(ctx)+ order = await pending_order(ctx, content)+ response = await ctx.client.get("/api/marketplace/payments/epay/notify", params=payment_params(order, money))+ assert response.status_code == 400+ assert order.status == "pending"+ assert await ctx.db.scalar(select(func.count()).select_from(Entitlement)) == 0+++async def test_retry_idempotency_key_is_bound_to_original_request(publication_ctx):+ ctx = publication_ctx+ content = await make_publication(ctx)+ original = await pending_order(ctx, content)+ other = await make_publication(ctx, episode=False)+ response = await ctx.client.post("/api/marketplace/content-orders", json={+ "publication_id": other.publication.id, "pay_type": "alipay", "idempotency_key": original.idempotency_key})+ assert response.status_code == 409+ content.publication.listed = False+ await ctx.db.flush()+ response = await ctx.client.post("/api/marketplace/content-orders", json={+ "publication_id": content.publication.id, "pay_type": "alipay", "idempotency_key": original.idempotency_key})+ assert response.status_code == 200 and response.json()["out_trade_no"] == original.out_trade_no+++async def test_new_order_freezes_amount_and_idempotent_retry_uses_same_order(publication_ctx, monkeypatch):+ ctx = publication_ctx+ content = await make_publication(ctx)+ calls = []++ async def payment(**kwargs):+ calls.append(kwargs)+ return {"payurl": "https://payment.invalid/checkout"}++ monkeypatch.setattr(commerce.epay, "create_mapi_payment", payment)+ monkeypatch.setattr(commerce.epay, "build_submit_fields", lambda **kwargs: {})+ monkeypatch.setattr(commerce.epay, "submit_url", lambda _fields: "https://payment.invalid/submit")+ body = {"publication_id": content.publication.id, "pay_type": "alipay", "idempotency_key": uuid.uuid4().hex}+ first = await ctx.client.post("/api/marketplace/content-orders", json=body)+ assert first.status_code == 200, first.text+ second = await ctx.client.post("/api/marketplace/content-orders", json=body)+ assert second.status_code == 200 and second.json()["out_trade_no"] == first.json()["out_trade_no"]+ assert len(calls) == 1 and calls[0]["money_yuan"] == "9.99"+ assert await ctx.db.scalar(select(func.count()).select_from(ContentOrder)) == 1+++async def test_series_metadata_edit_creates_new_episode_version_and_preserves_purchase(publication_ctx):+ ctx = publication_ctx+ content = await make_publication(ctx)+ await grant(ctx, content)+ ctx.user = ctx.owner+ response = await ctx.client.patch(f"/api/marketplace/series/{content.series.id}", json={+ "title": "new title", "version": content.series.version, "sale_type": "platform_unlock", "share_bps": 4500})+ assert response.status_code == 200, response.text+ assert response.json()["episodes"][0]["version"] == 2+ assert content.item.version == 2 and content.series.audit_status == "draft"+ assert not content.item.listed and not content.publication.listed+ assert content.publication.version == 1 and content.publication.share_bps == 2345+ assert content.publication.playback_manifest_key == "marketplace/hls/old/index.m3u8"+ ctx.user = ctx.buyer+ assert (await ctx.client.get(f"/api/marketplace/platform/publications/{content.publication.id}/playback")).status_code == 200++[email protected]("state", ["pending", "running", "failed"])+async def test_sync_state_blocks_submission_and_is_exposed_in_editor(publication_ctx, state):+ ctx = publication_ctx+ content = await make_publication(ctx)+ ctx.user = ctx.owner+ content.series.audit_status = "draft"+ ctx.db.add(Handoff(owner_id=ctx.owner.id, idempotency_key=uuid.uuid4().hex, source_kind="drama_episode",+ source_id=99, target_kind="series_episode", target_id=content.item.id,+ series_id=content.series.id, status=state, error="copy failed" if state == "failed" else ""))+ await ctx.db.flush()+ detail = await ctx.client.get(f"/api/marketplace/series/{content.series.id}")+ assert detail.status_code == 200, detail.text+ assert detail.json()["sync_in_progress"] == (state != "failed")+ assert detail.json()["pending_handoffs"][0]["status"] == state+ response = await ctx.client.post(f"/api/marketplace/series/{content.series.id}/submit", json={"version": 1})+ assert response.status_code == 409+ assert response.json()["detail"] == ("MARKETPLACE_EPISODE_NOT_READY" if state == "failed" else "MARKETPLACE_SYNC_IN_PROGRESS")+++async def test_episode_with_pending_order_cannot_be_deleted(publication_ctx):+ ctx = publication_ctx+ content = await make_publication(ctx)+ await pending_order(ctx, content)+ ctx.user = ctx.owner+ response = await ctx.client.delete(f"/api/marketplace/series/{content.series.id}/episodes/{content.item.id}")+ assert response.status_code == 409 and "订单或购买权益" in response.json()["detail"]+ assert await ctx.db.get(SeriesEpisode, content.item.id) is not None++[email protected]("override, expected", [(None, 2100), (0, 0), (3500, 3500)])+async def test_series_submission_freezes_effective_revenue_share(publication_ctx, override, expected):+ ctx = publication_ctx+ content = await make_publication(ctx)+ ctx.user = ctx.owner+ content.series.audit_status = "draft"+ content.item.share_bps = override+ content.proof.details = {"source": "external", "certificate_number": "CP-123", "dispute_ack": True}+ cover = Asset(owner_id=ctx.owner.id, kind="image", filename="cover.png", content_type="image/png",+ size_bytes=10, object_key="marketplace/covers/test.png", status="ready")+ ctx.db.add_all([cover, RevenueConfig(id=1, platform_share_bps=2100)])+ await ctx.db.flush()+ content.item.cover_asset_id = cover.id+ ctx.db.add(EpisodePreview(episode_id=content.item.id, asset_id=content.asset.id, version=1,+ status="done", object_key="marketplace/series-previews-hq/test.mp4"))+ await ctx.db.flush()+ response = await ctx.client.post(f"/api/marketplace/series/{content.series.id}/submit", json={"version": 1})+ assert response.status_code == 200, response.text+ publications = list((await ctx.db.execute(select(Publication).order_by(Publication.version))).scalars().all())+ assert len(publications) == 2 and publications[1].version == 2+ assert publications[0].share_bps == 2345 and publications[0].playback_manifest_key+ assert publications[1].share_bps == expected+ assert not publications[0].listed and not publications[1].listed+++async def test_work_submission_freezes_default_share_and_never_rewrites_approved_snapshot(publication_ctx):+ ctx = publication_ctx+ content = await make_publication(ctx, episode=False)+ ctx.user = ctx.owner+ content.item.audit_status, content.item.source, content.item.license_scope = "draft", "external", "商业展示"+ content.proof.details = {"source": "external", "certificate_number": "CP-123", "dispute_ack": True}+ ctx.db.add_all([RevenueConfig(id=1, platform_share_bps=2100), WorkPreview(+ work_id=content.item.id, asset_id=content.asset.id, version=1,+ status="done", object_key="marketplace/work-previews-hq/test.mp4")])+ await ctx.db.flush()+ response = await ctx.client.post(f"/api/marketplace/works/{content.item.id}/submit", json={"version": 1})+ assert response.status_code == 200, response.text+ publications = list((await ctx.db.execute(select(Publication).order_by(Publication.version))).scalars().all())+ assert len(publications) == 2 and publications[1].version == 2+ assert publications[0].share_bps == 2345 and publications[0].playback_manifest_key+ assert publications[1].share_bps == 2100diff --git a/backend/tests/test_marketplace_runtime.py b/backend/tests/test_marketplace_runtime.pyindex 4f123ce..1f612bc 100644--- a/backend/tests/test_marketplace_runtime.py+++ b/backend/tests/test_marketplace_runtime.py@@ -5,7 +5,7 @@ import sysimport pytestfrom app.marketplace import runtime-from app.marketplace.config import get_marketplace_settings+from app.config import get_settingsdef test_media_tools_fall_back_to_environment_paths(monkeypatch, tmp_path):@@ -53,13 +53,13 @@ async def test_media_thread_command_timeout_and_cancellation(monkeypatch):async def test_market_runtime_disabled_does_not_start(monkeypatch):- monkeypatch.setattr(get_marketplace_settings(), "enabled", False)+ monkeypatch.setattr(get_settings(), "marketplace_enabled", False)await runtime.start_marketplace_runtime()assert runtime._watchdog is None and runtime._worker is Noneasync def test_market_runtime_idempotent_and_clean_shutdown(monkeypatch):- monkeypatch.setattr(get_marketplace_settings(), "enabled", True)+ monkeypatch.setattr(get_settings(), "marketplace_enabled", True)started, stopped = asyncio.Event(), asyncio.Event()async def loop():started.set()@@ -83,7 +83,7 @@ async def test_market_runtime_idempotent_and_clean_shutdown(monkeypatch):@pytest.mark.parametrize("cancelled", [False, True])async def test_market_runtime_recovers_failed_or_cancelled_loop(monkeypatch, cancelled):- monkeypatch.setattr(get_marketplace_settings(), "enabled", True)+ monkeypatch.setattr(get_settings(), "marketplace_enabled", True)started, restarted = asyncio.Event(), asyncio.Event()calls = 0async def loop():diff --git a/docs/MARKETPLACE.md b/docs/MARKETPLACE.mdindex 25dc486..968b5ef 100644--- a/docs/MARKETPLACE.md+++ b/docs/MARKETPLACE.md@@ -72,7 +72,7 @@ cd C:\code\printfilm\backend- 管理端 `/marketplace`:下游审核、登记、投诉、任务与客服配置,区别于原 `/works`。- API `/api/marketplace/*`、`/api/admin/marketplace/*`。-模块默认关闭,关闭时业务路由不挂载、菜单隐藏、新表不初始化,不启动 Worker。`GET /api/marketplace/capabilities` 始终可用,只返回开关与配置完整性,**不代表真实 OSS 已验收**。+模块默认关闭。路由始终挂载,关闭时业务接口返回未启用,菜单隐藏,不建新表,不启动 Worker。`GET /api/marketplace/capabilities` 始终可用,只返回开关与配置完整性,**不代表真实 OSS 已验收**。线上在管理端「系统设置 → 站点工具」打开「启用数字资产市场」并保存,写入 `app_settings`,不必准备 `backend/.env`,也不必为了出现菜单而重启。库里保存过该开关后以数据库为准。下游使用独立 SQLAlchemy metadata,启动时创建 `marketplace_` 表,不修改或迁移原表。用户 ID 复用现有身份。PrintFilm 成片可以按项目或分集编号异步复制进市场;没有走这条路径的作品仍由用户自行上传。复制完成后的草稿不自动过审。@@ -88,11 +88,11 @@ cd C:\code\printfilm\backend.\.venv\Scripts\python.exe -m uvicorn app.main:app --host 127.0.0.1 --port 8000```-先停止原先占用8000端口的后端。前端及管理端仍按项目原命令启动,刷新后会显示新菜单。若使用 VS Code F5,可在调试终端的环境或本地 `.env` 设置开关,重启后端。代码默认值仍为 false。+先停止原先占用8000端口的后端。前端及管理端仍按项目原命令启动,刷新后会显示新菜单。若使用 VS Code F5,可在调试终端的环境或本地 `.env` 设置开关,重启后端。代码默认值仍为 false。已在系统设置里保存过开关时,以数据库中的值为准,改 `.env` 不会盖过它。无 OSS 时支持文字作品草稿和无附件需求的创建、修改、内容审核、招募公开浏览。上传、材料、媒体签名返回503,`detail.code=MARKETPLACE_STORAGE_UNAVAILABLE`,不会回退本地存储、返回 `/static`,也不会产生假就绪视频。-停用时设置 `MARKETPLACE_ENABLED=false` 并重启后端,独立 Worker 一并停止。停用不会删除已经存在的新表或 OSS 对象。+停用时在「系统设置 → 站点工具」关闭开关并保存,或在尚未写入数据库前把 `MARKETPLACE_ENABLED=false` 后重启。Worker 会停止。停用不会删除已经存在的新表或 OSS 对象。## 共用 OSS、独立目录与媒体进程@@ -197,3 +197,19 @@ cd C:\code\printfilm\backend### 招募公开详情与作者管理分离(2026-10-21)招募广场 /marketplace/recruits/:id 始终显示招募内容与联系客服接单入口,不因当前账号是作者/管理员而切换管理界面;编辑、提交审核及关闭在 /marketplace/recruits/:id/manage 展示,由“我的发布 → 查看与管理”或保存招募草稿后进入。本人看到管理招募链接,创作者登录后联系客服;关闭/到期停止新接单咨询。详情不请求私密投稿列表,不提供视频投稿和独立公开评论系统。++### 漫剧完整分集直接发布(2026-10-24)++漫剧列表卡片菜单「发布到数字资产市场」、分集编辑页和市场编辑页使用同一个发布弹窗。选择当前项目的完整分集,新建或选择本人市场系列后同步并进入 `/marketplace/series/{id}/edit`。新系列带入项目名称和简介;已有系列保留介绍、封面及收费配置,按原集数排序后从下一集接续编号。没有可用封面时需补充上传。++- `GET /api/marketplace/printfilm/dramas/{project_id}/publish-context`:完整度、不可发布原因、源版本、本人目标系列和既有同步关系,不返回来源地址或对象键。+- `POST /api/marketplace/printfilm/dramas/{project_id}/publish`:提交选中编号、源版本、新建/已有目标、明确确认的更新及幂等键。独立 `marketplace_drama_publish_batches` 记录原子批次;同一账号的同一幂等键不能创建第二个系列。旧的分集导入 URL 也使用相同的整集逻辑。+- 原漫剧仅供读取。缺失任一分镜、视频生成或重新分镜尚未结束、跨账号选择均阻止发布。按 `(sort_order,id)` 冻结完整分镜清单、源文件指纹/ETag、标题、封面及源集号;不再把最后一个分镜当整集。+- 使用原有市场 Worker 及看门狗,不增加进程。阶段为排队、同步素材、拼接整集、校验、就绪/失败;兼容编码优先无损封装,不兼容时按最高来源画幅使用高质量编码,比例不一致直接阻断。非公开临时目录只作缓存,视频写入私有 OSS `marketplace/series/` 并校验后才绑定。+- 同步期间可以填写表单,保存与提交暂时禁用;失败提供原因和重试,源变化或目标冲突要求重新选择并确认。租约丢失会取消处理;过期租约由同一个 Worker 恢复。源或目标已变化的旧任务不能回填新结果,未成功前保留旧资产。+- PrintFilm 分集统一引用账号当前有效授权函,可先同步及保存草稿,再签署一次并提交。自动关联只表示材料齐备;内容和版权仍由管理员一起审核,不自动批准。+- 明确更新使系列退回草稿并关闭所有历史发布版本的新销售;旧发布快照、HLS、价格及永久权益保留。已有买家通过 `GET /api/marketplace/platform/publications/{publication_id}/playback` 播放购买时版本,每次仍鉴权并检查封禁/权属限制。在途有效付款回调按冻结版本与金额确认,不因作者编辑或下架丢失权益。分成在提交时按单集、系列、后台默认优先顺序冻结。++新增独立表随启用后的后端启动创建,不修改 `drama_*` 或原生成、下载、AI 计费任务。部署更新后需重启后端以加载接口和创建该表。没有真实 OSS 配置时发布返回 `503 MARKETPLACE_STORAGE_UNAVAILABLE`,不创建空系列,不提供本地媒体回退。++专项回归文件:`tests/test_marketplace_drama_publish.py`、`tests/test_marketplace_drama_media.py`、`tests/test_marketplace_publication_access.py`,覆盖整集顺序和时长、权限、状态、防重、版本回填、租约恢复、旧权益和付款幂等。媒体测试使用真实 FFmpeg、OSS 使用传输测试替身;仍须在真实 OSS 环境单独验证复制、合成上传、私有播放及部署重启,不能将替身结果视为云端验收通过。diff --git a/frontend/src/features/marketplace/AssetPicker.tsx b/frontend/src/features/marketplace/AssetPicker.tsxindex 50fa37b..7c07699 100644--- a/frontend/src/features/marketplace/AssetPicker.tsx+++ b/frontend/src/features/marketplace/AssetPicker.tsx@@ -3,8 +3,8 @@ import { request, upload } from './api'import { CheckCircle2, UploadCloud } from 'lucide-react'import AssetPreview, { PreviewContent } from './AssetPreview'-// 上传状态与“处理就绪”分开显示,只允许绑定 ready 文件。-export default function AssetPicker({ kind, value, onChange, title = '选择或上传文件', required = false }: { kind: 'video' | 'document' | 'image'; value: number | null; onChange: (id: number) => void; title?: string; required?: boolean }) {+// 上传状态与“处理就绪”分开显示,只允许绑定 ready 文件。locked 时不提供手动选择。+export default function AssetPicker({ kind, value, onChange, title = '选择或上传文件', required = false, locked = false, lockUntilPreview = false }: { kind: 'video' | 'document' | 'image'; value: number | null; onChange: (id: number) => void; title?: string; required?: boolean; locked?: boolean; lockUntilPreview?: boolean }) {/* 仅上传并绑定当前文件,不加载历史文件列表。 */@@ -16,6 +16,9 @@ export default function AssetPicker({ kind, value, onChange, title = '选择或const [localFile, setLocalFile] = useState<File | null>(null)const [localAssetId, setLocalAssetId] = useState<number | null>(null)const [localUrl, setLocalUrl] = useState('')+ const [previewReady, setPreviewReady] = useState(false)+ useEffect(() => { setPreviewReady(false) }, [value])+ const waitingPreview = locked || (lockUntilPreview && (!value || !previewReady))useEffect(() => {if (!localFile) { setLocalUrl(''); return }const url = URL.createObjectURL(localFile); setLocalUrl(url)@@ -49,10 +52,10 @@ export default function AssetPicker({ kind, value, onChange, title = '选择或finally { controller.current = null }}return <fieldset><legend>{title}{required && <span className="pf-req-mark">必填</span>}</legend>- <label className="pf-market-upload-zone"><UploadCloud size={28} strokeWidth={1.4} /><strong>点击选择{kind === 'video' ? '视频' : kind === 'image' ? '图片' : '文件'}</strong><span>{kind === 'video' ? 'MP4 / MOV / WebM · 最大500MB · 最长30分钟' : kind === 'image' ? 'PNG / JPG / WebP · 最大20MB' : 'PDF / PNG / JPG / WebP · 最大20MB'}</span><input aria-label={`上传${title}`} type="file" disabled={progress !== null} accept={kind === 'video' ? '.mp4,.mov,.webm' : kind === 'image' ? '.png,.jpg,.jpeg,.webp' : '.pdf,.png,.jpg,.jpeg,.webp'} onChange={e => { void choose(e.target.files?.[0]); e.target.value = '' }} /></label>- {progress !== null && <div className="pf-market-upload-progress" role="status"><p>{pending ? '上传完成,正在处理媒体。可稍后到我的文件查看。' : `上传 ${progress}%`}</p><progress value={progress} max={100} aria-label="上传进度" /></div>}- {progress !== null && !pending && <button type="button" onClick={() => controller.current?.abort()}>取消上传</button>}+ {waitingPreview ? <p className="pf-market-notice" role="status">加载预览中</p> : <label className="pf-market-upload-zone"><UploadCloud size={28} strokeWidth={1.4} /><strong>点击选择{kind === 'video' ? '视频' : kind === 'image' ? '图片' : '文件'}</strong><span>{kind === 'video' ? 'MP4 / MOV / WebM · 最大500MB · 最长30分钟' : kind === 'image' ? 'PNG / JPG / WebP · 最大20MB' : 'PDF / PNG / JPG / WebP · 最大20MB'}</span><input aria-label={`上传${title}`} type="file" disabled={progress !== null} accept={kind === 'video' ? '.mp4,.mov,.webm' : kind === 'image' ? '.png,.jpg,.jpeg,.webp' : '.pdf,.png,.jpg,.jpeg,.webp'} onChange={e => { void choose(e.target.files?.[0]); e.target.value = '' }} /></label>}+ {!waitingPreview && progress !== null && <div className="pf-market-upload-progress" role="status"><p>{pending ? '上传完成,正在处理媒体。可稍后到我的文件查看。' : `上传 ${progress}%`}</p><progress value={progress} max={100} aria-label="上传进度" /></div>}+ {!waitingPreview && progress !== null && !pending && <button type="button" onClick={() => controller.current?.abort()}>取消上传</button>}{localFile && localUrl && <div><p>本地预览:{localFile.name} · {(localFile.size / 1024 / 1024).toFixed(2)} MB</p><p>仅供检查所选文件,不代表已上传或审核通过。</p><PreviewContent key={localUrl} url={localUrl} filename={localFile.name} video={kind === 'video'} /><button type="button" onClick={() => setLocalFile(null)}>关闭本地预览</button></div>}- {value && <><p className="pf-market-upload-selection"><CheckCircle2 size={14} /> 已绑定文件 #{value}(新文件处理就绪后才会替换)</p><AssetPreview key={value} id={value} hideMedia={Boolean(localFile)} onReady={id => { if (id === localAssetId) { setLocalFile(null); setLocalAssetId(null) } }} /></>}{error && <p role="alert">{error}</p>}</fieldset>+ {value && <><p className="pf-market-upload-selection" hidden={waitingPreview}><CheckCircle2 size={14} /> 已绑定文件 #{value}(新文件处理就绪后才会替换)</p><AssetPreview key={value} id={value} hideMedia={Boolean(localFile)} onReady={id => { if (id === localAssetId) { setLocalFile(null); setLocalAssetId(null) } }} onMediaReady={() => setPreviewReady(true)} /></>}{error && <p role="alert">{error}</p>}</fieldset>}diff --git a/frontend/src/features/marketplace/AssetPreview.tsx b/frontend/src/features/marketplace/AssetPreview.tsxindex fc88d4d..b72adbf 100644--- a/frontend/src/features/marketplace/AssetPreview.tsx+++ b/frontend/src/features/marketplace/AssetPreview.tsx@@ -12,7 +12,7 @@ export function PreviewContent({ url, filename, video = false, onReady, onFailur</div>}-export default function AssetPreview({ id, onReady, hideMedia = false }: { id: number; onReady?: (id: number) => void; hideMedia?: boolean }) {+export default function AssetPreview({ id, onReady, onMediaReady, hideMedia = false }: { id: number; onReady?: (id: number) => void; onMediaReady?: (id: number) => void; hideMedia?: boolean }) {const [asset, setAsset] = useState<Row | null>(null)const [url, setUrl] = useState('')const [error, setError] = useState('')@@ -33,7 +33,7 @@ export default function AssetPreview({ id, onReady, hideMedia = false }: { id: n// temporary local preview closes without another manual click.onReady?.(id)}- }+ } else if (item.status === 'failed') onMediaReady?.(id)} catch (e) { if (active) setError((e as Error).message) }}void load()@@ -45,7 +45,7 @@ export default function AssetPreview({ id, onReady, hideMedia = false }: { id: nreturn () => window.clearTimeout(timer)}, [asset])return <div className="pf-market-asset-preview"><p>{asset?.filename || `文件 #${id}`} · {labels[asset?.status || ''] || '正在读取'}</p>- {url && <div hidden={hideMedia}><PreviewContent key={url} url={url} filename={asset?.filename || ''} video={asset?.kind === 'video'} onReady={() => onReady?.(id)} onFailure={() => { if (hideMedia) setError('云端预览加载失败,已保留本地预览,可刷新预览链接重试。') }} /></div>}+ {url && <div hidden={hideMedia}><PreviewContent key={url} url={url} filename={asset?.filename || ''} video={asset?.kind === 'video'} onReady={() => { onReady?.(id); onMediaReady?.(id) }} onFailure={() => { onMediaReady?.(id); if (hideMedia) setError('云端预览加载失败,已保留本地预览,可刷新预览链接重试。') }} /></div>}{asset?.status === 'processing' && <p>文件已上传,正在生成兼容浏览器的预览,请稍后刷新。</p>}{asset?.error && <p role="alert">{asset.error}</p>}{error && <p role="alert">{error}</p>}<button type="button" onClick={() => setRevision(v => v + 1)}>刷新预览链接</button>diff --git a/frontend/src/features/marketplace/DramaPublishModal.tsx b/frontend/src/features/marketplace/DramaPublishModal.tsxnew file mode 100644index 0000000..0ea3bc7--- /dev/null+++ b/frontend/src/features/marketplace/DramaPublishModal.tsx@@ -0,0 +1,84 @@+import { useEffect, useRef, useState } from 'react'+import { useNavigate } from 'react-router-dom'+import { CheckCircle2, Film, Loader2 } from 'lucide-react'+import Modal from '../../components/ui/Modal'+import Button from '../../components/ui/Button'+import { request } from './api'+import { publishSelection, sourceRelation, type DramaPublishContext, type DramaPublishResult } from './dramaPublishing'+import './dramaPublishing.css'++type Props = {+ projectId: number; initialEpisodeId?: number; targetSeriesId?: number+ onClose: () => void; onPublished?: (result: DramaPublishResult) => void+}++// 漫剧卡片、分集预览和市场编辑页共用同一发布流程,只提交服务端校验过的编号与版本。+export default function DramaPublishModal({ projectId, initialEpisodeId, targetSeriesId, onClose, onPublished }: Props) {+ const navigate = useNavigate()+ const [context, setContext] = useState<DramaPublishContext | null>(null)+ const [selected, setSelected] = useState<number[]>([])+ const [updates, setUpdates] = useState<number[]>([])+ const [targetId, setTargetId] = useState(targetSeriesId ? String(targetSeriesId) : 'new')+ const [title, setTitle] = useState('')+ const [busy, setBusy] = useState(false)+ const [loading, setLoading] = useState(true)+ const [error, setError] = useState('')+ const [reload, setReload] = useState(0)+ const requestKey = useRef({ signature: '', key: '' })+ const submitting = useRef(false)+ useEffect(() => {+ let active = true+ setLoading(true); setError('')+ request<DramaPublishContext>(`/printfilm/dramas/${projectId}/publish-context`).then(value => {+ if (!active) return+ setContext(value)+ setTitle(current => current || value.project.title)+ setSelected(current => current.length ? current.filter(id => value.episodes.some(item => item.id === id && item.ready)) : initialEpisodeId && value.episodes.some(item => item.id === initialEpisodeId && item.ready) ? [initialEpisodeId] : [])+ setUpdates([])+ }).catch(err => { if (active) setError((err as Error).message) }).finally(() => { if (active) setLoading(false) })+ return () => { active = false }+ }, [projectId, initialEpisodeId, reload])+ const target = context?.series.find(item => String(item.id) === targetId)+ const changed = context?.episodes.filter(item => selected.includes(item.id) && sourceRelation(item, target).changed) || []+ const missingUpdates = changed.some(item => !updates.includes(item.id))+ const storageReady = context?.storage_configured === true+ async function publish() {+ if (!context || !storageReady || submitting.current || !selected.length) return+ submitting.current = true; setBusy(true); setError('')+ try {+ if (targetId !== 'new' && !target) throw new Error('目标系列已变化,请刷新后重新选择')+ const episodes = publishSelection(context, selected, updates, target)+ const payload = { episodes, series_id: target?.id ?? null, ...(target ? { series_version: target.version } : { title: title.trim() || context.project.title }) }+ const signature = JSON.stringify(payload)+ // 网络超时后保留同一个幂等键;只有用户改变发布内容才创建新批次。+ if (requestKey.current.signature !== signature) requestKey.current = { signature, key: crypto.randomUUID() }+ const result = await request<DramaPublishResult>(`/printfilm/dramas/${projectId}/publish`, 'POST', { ...payload, idempotency_key: requestKey.current.key })+ if (onPublished) onPublished(result)+ else navigate(`/marketplace/series/${result.series_id}/edit`)+ onClose()+ } catch (err) { setError((err as Error).message) }+ finally { submitting.current = false; setBusy(false) }+ }+ return <Modal open title="发布到数字资产市场" size="lg" className="pf-drama-publish" onClose={onClose} dismissible={!busy} footer={<>+ <Button type="button" variant="ghost" disabled={busy} onClick={onClose}>取消</Button>+ <Button type="button" variant="lime" disabled={loading || busy || !storageReady || !selected.length || missingUpdates || (targetId !== 'new' && !target)} onClick={() => void publish()}>{busy ? <><Loader2 size={16} className="pf-drama-publish-spin" />正在创建同步任务…</> : '同步并继续编辑'}</Button>+ </>}>+ <p className="pf-drama-publish-intro">选中的完整分集会同步到市场独立保存。随后补充封面、价格与授权,提交管理员审核。</p>+ {loading ? <p role="status">正在检查分集和市场状态…</p> : context ? <>+ {!storageReady && <p className="pf-drama-publish-warning" role="alert">文件服务暂未配置,暂时无法同步视频。请联系管理员完成文件服务配置后重试。</p>}+ <div className="pf-drama-publish-project"><Film size={20} /><div><strong>{context.project.title}</strong><span>{context.episodes.length} 集 · 仅完整生成的分集可发布</span></div></div>+ <div className="pf-drama-publish-episodes" aria-label="选择发布分集">{context.episodes.map(episode => {+ const relation = sourceRelation(episode, target)+ return <div key={episode.id} className={`pf-drama-publish-episode${!episode.ready ? ' is-disabled' : ''}`}>+ <label><input type="checkbox" disabled={busy || !episode.ready || !storageReady} checked={selected.includes(episode.id)} onChange={event => { setSelected(value => event.target.checked ? [...value, episode.id] : value.filter(id => id !== episode.id)); setUpdates(value => value.filter(id => id !== episode.id)) }} /><span><strong>第 {episode.episode_number} 集 · {episode.name}</strong><small>{episode.completed_count}/{episode.fragment_count} 镜已完成{!episode.ready ? ` · ${episode.reason || '成片未就绪'}` : relation.existing ? relation.changed ? ' · 发现新版本' : ' · 已同步,此版本将直接复用' : ''}</small></span></label>+ {relation.changed && selected.includes(episode.id) && <label className="pf-drama-publish-update"><input type="checkbox" disabled={busy} checked={updates.includes(episode.id)} onChange={event => setUpdates(value => event.target.checked ? [...value, episode.id] : value.filter(id => id !== episode.id))} />确认更新为新的完整分集</label>}+ </div>+ })}{context.episodes.length === 0 && <p>这个项目还没有分集。</p>}</div>+ <label className="pf-drama-publish-field">发布到<select disabled={busy || Boolean(targetSeriesId)} value={targetId} onChange={event => { setTargetId(event.target.value); setUpdates([]) }}><option value="new">新建市场短剧</option>{context.series.map(item => <option key={item.id} value={item.id}>{item.title}{item.listed ? '(已上架)' : ''}</option>)}</select></label>+ {targetId === 'new' ? <label className="pf-drama-publish-field">市场短剧名称<input value={title} disabled={busy} maxLength={200} onChange={event => setTitle(event.target.value)} placeholder={context.project.title} /></label> : <p className="pf-drama-publish-hint">保留已有系列的介绍、封面和收费设置;新分集接续目标系列集号。</p>}+ {(changed.length > 0 || (target && (target.listed || target.audit_status === 'approved' || target.audit_status === 'pending'))) && <p className="pf-drama-publish-warning">同步更新或追加分集后,系列将退回草稿并暂停公开销售,需要重新提交审核。历史买家仍可播放已购买版本。</p>}+ <p className="pf-drama-publish-hint"><CheckCircle2 size={15} />{context.authorization_ready ? '当前授权函有效,同步后自动关联,无需逐集签署。' : '可先同步并保存草稿,提交系列审核前统一签署一次 PrintFilm 授权函。'}</p>+ </> : null}+ {error && <div className="pf-drama-publish-error" role="alert"><p>{error}</p><button type="button" disabled={busy || loading} onClick={() => setReload(value => value + 1)}>刷新分集状态</button></div>}+ </Modal>+}diff --git a/frontend/src/features/marketplace/FromPrintfilm.tsx b/frontend/src/features/marketplace/FromPrintfilm.tsxindex d57ad8e..a232011 100644--- a/frontend/src/features/marketplace/FromPrintfilm.tsx+++ b/frontend/src/features/marketplace/FromPrintfilm.tsx@@ -3,6 +3,7 @@ import { useNavigate, useSearchParams } from 'react-router-dom'import { request, type Handoff } from './api'import { PageHeading } from './ui'import Button from '../../components/ui/Button'+import DramaPublishModal from './DramaPublishModal'type ProjectSource = { id: number; title: string; updated_at: string; has_cover: boolean; status: string }type DramaSource = { id: number; title: string; episodes: { id: number; name: string; ready: boolean }[] }@@ -19,7 +20,7 @@ export default function FromPrintfilm() {const [dramas, setDramas] = useState<DramaSource[]>([])const [series, setSeries] = useState<SeriesOption[]>([])const [dramaId, setDramaId] = useState(focusDrama ? String(focusDrama) : '')- const [selected, setSelected] = useState<number[]>(focusEpisode ? [focusEpisode] : [])+ const [dramaPublishOpen, setDramaPublishOpen] = useState(Boolean(focusDrama))const [seriesId, setSeriesId] = useState('')const [error, setError] = useState('')const [busy, setBusy] = useState(false)@@ -75,19 +76,6 @@ export default function FromPrintfilm() {} catch (err) { setError((err as Error).message) } finally { setBusy(false) }}- async function addEpisodes() {- if (!drama || !selected.length) return- setBusy(true); setError('')- try {- const target = await ensureSeries(drama.title)- await request(`/series/${target}/episodes/import-printfilm`, 'POST', {- drama_project_id: drama.id,- episode_ids: selected,- })- navigate(`/marketplace/series/${target}/edit`)- } catch (err) { setError((err as Error).message) } finally { setBusy(false) }- }-if (loading) return <p role="status">正在读取已生成的成片…</p>return <><PageHeading title="发布到数字资产市场" description="选择 PrintFilm 已经生成的成片。文件由服务器复制到市场,草稿仍要补充授权并提交审核。" back="/marketplace/works/new" />@@ -109,10 +97,10 @@ export default function FromPrintfilm() {<h2>漫剧分集</h2><p className="pf-market-notice">只导入勾选的分集。同步完成后,在短剧编辑页补充封面、价格和授权函,再提交审核。</p>{dramas.length === 0 ? <p>还没有可导入的漫剧分集。</p> : <>- <label>漫剧项目<select value={dramaId} onChange={event => { setDramaId(event.target.value); setSelected([]) }}>{dramas.map(item => <option key={item.id} value={item.id}>{item.title}</option>)}</select></label>- {drama?.episodes.map(episode => <label key={episode.id} className="block"><input type="checkbox" disabled={!episode.ready} checked={selected.includes(episode.id)} onChange={event => setSelected(value => event.target.checked ? [...value, episode.id] : value.filter(item => item !== episode.id))} /> {episode.name}{episode.ready ? '' : '(成片未就绪)'}</label>)}- <button type="button" disabled={busy || !seriesId || !selected.length} onClick={() => void addEpisodes()}>导入到短剧系列</button>+ <label>漫剧项目<select value={dramaId} onChange={event => setDramaId(event.target.value)}>{dramas.map(item => <option key={item.id} value={item.id}>{item.title}</option>)}</select></label>+ <button type="button" disabled={busy || !drama} onClick={() => setDramaPublishOpen(true)}>选择完整分集并发布</button></>}</section>+ {dramaPublishOpen && drama && <DramaPublishModal projectId={drama.id} initialEpisodeId={focusEpisode || undefined} onClose={() => setDramaPublishOpen(false)} />}</>}diff --git a/frontend/src/features/marketplace/SeriesEditor.tsx b/frontend/src/features/marketplace/SeriesEditor.tsxindex 9b6ed22..8ca20b1 100644--- a/frontend/src/features/marketplace/SeriesEditor.tsx+++ b/frontend/src/features/marketplace/SeriesEditor.tsx@@ -1,4 +1,4 @@-import { useEffect, useState, type FormEvent } from 'react'+import { useEffect, useRef, useState, type FormEvent } from 'react'import { useNavigate, useParams } from 'react-router-dom'import { ChevronDown, ChevronRight } from 'lucide-react'import AssetPicker from './AssetPicker'@@ -7,13 +7,16 @@ import { FormSection, PageHeading, PublishGuide } from './ui'import Button from '../../components/ui/Button'import { useCategories } from './useCategories'import { dialog } from '../../lib/dialog'+import AuthorizationPanel from './AuthorizationPanel'+import DramaPublishModal from './DramaPublishModal'+import { handoffLabel, isHandoffActive, latestEpisodeHandoffs, mergeSyncedEpisodes } from './dramaPublishing'type EpisodeDraft = { id?: number; version?: number; episode_no: number; title: string; description?: string; asset_id: number | null; cover_asset_id: number | null; copyright_price_fen: number; unlock_price_fen: number; share_bps?: number | null; source?: 'printfilm' | 'external' | 'original' | 'ai' | 'authorized' }-type SeriesDraft = { id: number; version: number; title: string; description: string; category: string; tags: string[]; cover_asset_id?: number | null; sale_type: 'free' | 'copyright_contact' | 'platform_unlock'; copyright_price_fen: number; free_episode_count?: number; audit_status?: string; listed?: boolean; episodes: EpisodeDraft[] }+type SeriesDraft = { id: number; version: number; title: string; description: string; category: string; tags: string[]; cover_asset_id?: number | null; sale_type: 'free' | 'copyright_contact' | 'platform_unlock'; copyright_price_fen: number; free_episode_count?: number; audit_status?: string; listed?: boolean; episodes: EpisodeDraft[]; authorization_ready?: boolean; sync_in_progress?: boolean; pending_handoffs?: Handoff[] }type ImportSource = { id: number; title: string; episodes: { id: number; name: string; ready: boolean }[] }-function EpisodePanel({ episode, count, free, open, saleType, seriesId, busy, videoLabel, toggle, update, remove, goRights }: {- episode: EpisodeDraft; count: number; free: boolean; open: boolean; saleType: SeriesDraft['sale_type']; seriesId?: string; busy: boolean; videoLabel: string+function EpisodePanel({ episode, count, free, open, saleType, seriesId, busy, videoLabel, videoLocked, lockVideoUntilPreview, toggle, update, remove, goRights }: {+ episode: EpisodeDraft; count: number; free: boolean; open: boolean; saleType: SeriesDraft['sale_type']; seriesId?: string; busy: boolean; videoLabel: string; videoLocked: boolean; lockVideoUntilPreview: booleantoggle: () => void; update: (patch: Partial<EpisodeDraft>) => void; remove: () => void; goRights: () => void}) {return <article className={`pf-episode-fold${open ? ' is-open' : ''}`}>@@ -24,11 +27,11 @@ function EpisodePanel({ episode, count, free, open, saleType, seriesId, busy, vi{open && <div className="pf-episode-fold-body"><label>集标题<span className="pf-req-mark">必填</span><input required value={episode.title} onChange={event => update({ title: event.target.value })} /></label><label>分集简介<textarea value={episode.description || ''} maxLength={5000} onChange={event => update({ description: event.target.value })} placeholder="介绍这一集的内容" /></label>- <label>内容来源<select value={episode.source || 'external'} onChange={event => update({ source: event.target.value as EpisodeDraft['source'] })}><option value="printfilm">PrintFilm 生成</option><option value="external">其他平台生成</option></select></label>- <AssetPicker kind="video" value={episode.asset_id} onChange={asset_id => update({ asset_id })} title="分集视频" required />+ <label>内容来源<select disabled={videoLocked} value={episode.source || 'external'} onChange={event => update({ source: event.target.value as EpisodeDraft['source'] })}><option value="printfilm">PrintFilm 生成</option><option value="external">其他平台生成</option></select></label>+ <AssetPicker kind="video" value={episode.asset_id} onChange={asset_id => update({ asset_id })} title="分集视频" required locked={videoLocked} lockUntilPreview={lockVideoUntilPreview} /><AssetPicker kind="image" required value={episode.cover_asset_id} onChange={cover_asset_id => update({ cover_asset_id })} title="分集封面(可使用系列封面)" />{saleType !== 'free' && <label>本集版权参考价(元)<input type="number" min="0" step="0.01" value={(episode.copyright_price_fen / 100) || ''} onChange={event => update({ copyright_price_fen: Math.round(Number(event.target.value || 0) * 100) })} /></label>}- {episode.asset_id && (seriesId ? <button type="button" onClick={goRights}>填写第 {episode.episode_no} 集权属材料</button> : <p>请先保存草稿,再填写这一集的权属材料。保存后会回到这个页面。</p>)}+ {episode.source === 'printfilm' ? <p className="pf-market-notice">PrintFilm 生成:本系列统一引用账号授权函,无需逐集签署或上传证书。</p> : episode.asset_id && (seriesId ? <button type="button" disabled={busy} onClick={goRights}>填写第 {episode.episode_no} 集权属材料</button> : <p>请先保存草稿,再填写这一集的权属材料。保存后会回到这个页面。</p>)}{saleType === 'platform_unlock' && <><label>解锁价(元)<input type="number" min="0.01" step="0.01" value={(episode.unlock_price_fen / 100) || ''} onChange={event => update({ unlock_price_fen: Math.round(Number(event.target.value || 0) * 100) })} /></label><label>本集平台分成(万分比,可留空使用后台默认)<input type="number" min="0" max="10000" step="1" value={episode.share_bps ?? ''} onChange={event => update({ share_bps: event.target.value === '' ? null : Number(event.target.value) })} placeholder="例如 2000" /></label></>}{count > 1 && <button type="button" disabled={busy} onClick={remove}>删除本集</button>}</div>}@@ -45,14 +48,33 @@ export default function SeriesEditor() {const [coverId, setCoverId] = useState<number | null>(null)const [episodes, setEpisodes] = useState<EpisodeDraft[]>([])const [removedEpisodeIds, setRemovedEpisodeIds] = useState<number[]>([])- const [sources, setSources] = useState<ImportSource[]>([]); const [sourceId, setSourceId] = useState(''); const [selected, setSelected] = useState<number[]>([])+ const [sources, setSources] = useState<ImportSource[]>([]); const [sourceId, setSourceId] = useState('')+ const [importOpen, setImportOpen] = useState(false)const [handoffs, setHandoffs] = useState<Handoff[]>([])+ const [handoffsLoaded, setHandoffsLoaded] = useState(!id)+ const [handoffError, setHandoffError] = useState('')+ const [dirty, setDirty] = useState(false)+ const [message, setMessage] = useState('')+ const savedEpisodes = useRef<EpisodeDraft[]>([])const [poll, setPoll] = useState(0)const [busy, setBusy] = useState(false); const [error, setError] = useState('')const [expanded, setExpanded] = useState<Set<number>>(() => new Set([0]))+ const episodeHandoffs = latestEpisodeHandoffs(handoffs)+ const hasSyncFailure = episodeHandoffs.some(item => item.status === 'failed')+ const syncing = Boolean(series?.sync_in_progress) || episodeHandoffs.some(isHandoffActive)+ const syncBlocked = syncing || Boolean(id && !handoffsLoaded)+ function acceptSaved(value: SeriesDraft) {+ setSeries(value); setSaleType(value.sale_type); setFreeEpisodeCount(value.free_episode_count || 0); setCategory(value.category || '其他'); setCoverId(value.cover_asset_id ?? null)+ const normalized = value.episodes.map(item => ({ ...item, asset_id: item.asset_id ?? null, cover_asset_id: item.cover_asset_id ?? null }))+ setEpisodes(normalized); savedEpisodes.current = normalized; setRemovedEpisodeIds([]); setDirty(false)+ if (value.pending_handoffs) setHandoffs(current => [...value.pending_handoffs!, ...current.filter(item => !value.pending_handoffs!.some(pending => pending.id === item.id))])+ }useEffect(() => {if (!id) { setEpisodes([{ episode_no: 1, title: '第1集', asset_id: null, cover_asset_id: null, copyright_price_fen: 0, unlock_price_fen: 0 }]); return }- request<SeriesDraft>(`/series/${id}`).then(value => { setSeries(value); setSaleType(value.sale_type); setFreeEpisodeCount(value.free_episode_count || 0); setCategory(value.category || '其他'); setCoverId(value.cover_asset_id ?? null); setEpisodes(value.episodes.map(item => ({ ...item, asset_id: item.asset_id ?? null, cover_asset_id: item.cover_asset_id ?? null }))) }).catch(e => setError(e.message))+ let active = true+ setHandoffsLoaded(false)+ request<SeriesDraft>(`/series/${id}`).then(value => { if (active) acceptSaved(value) }).catch(e => { if (active) setError(e.message) })+ return () => { active = false }}, [id])useEffect(() => { if (id) request<{ items: ImportSource[] }>('/series/import-sources').then(value => setSources(value.items)).catch(() => {}) }, [id])useEffect(() => {@@ -64,29 +86,41 @@ export default function SeriesEditor() {const value = await request<{ items: Handoff[] }>(`/handoffs?series_id=${id}`)if (stop) returnconst items = value.items+ let activeSync = latestEpisodeHandoffs(items).some(isHandoffActive)setHandoffs(items)- if (items.some(item => item.status === 'ready')) {+ setHandoffsLoaded(true); setHandoffError('')+ if (items.length) {const fresh = await request<SeriesDraft>(`/series/${id}`)if (stop) return- setEpisodes(current => current.map(episode => {- const remote = fresh.episodes.find(item => item.id === episode.id)- if (!remote || (remote.asset_id === episode.asset_id && remote.cover_asset_id === episode.cover_asset_id)) return episode- return { ...episode, asset_id: remote.asset_id ?? episode.asset_id, cover_asset_id: remote.cover_asset_id ?? episode.cover_asset_id, version: remote.version ?? episode.version }- }))+ activeSync = activeSync || Boolean(fresh.sync_in_progress)+ if (fresh.pending_handoffs?.length) setHandoffs([...fresh.pending_handoffs, ...items.filter(item => !fresh.pending_handoffs!.some(pending => pending.id === item.id))])+ const previous = savedEpisodes.current+ setEpisodes(current => mergeSyncedEpisodes(current, fresh.episodes, previous))+ savedEpisodes.current = fresh.episodes+ // Worker 也会推进父系列版本;仅合并状态,保留用户正在填写的标题、价格与封面。+ setSeries(current => current ? { ...current, version: fresh.version, audit_status: fresh.audit_status, listed: fresh.listed, authorization_ready: fresh.authorization_ready, sync_in_progress: fresh.sync_in_progress } : fresh)}- if (items.some(item => item.status === 'pending' || item.status === 'running')) timer = window.setTimeout(() => setPoll(value => value + 1), 3000)- } catch { /* 进度查询失败时保留当前编辑内容 */ }+ if (activeSync) timer = window.setTimeout(() => setPoll(value => value + 1), 3000)+ } catch { if (!stop) { setHandoffError('同步进度暂时无法读取,正在重试。当前填写的内容已保留。'); timer = window.setTimeout(() => setPoll(value => value + 1), 5000) } }}void tick()return () => { stop = true; window.clearTimeout(timer) }}, [id, poll])+ const syncingEpisodes = episodeHandoffs.filter(isHandoffActive).map(item => item.episode_id).join(',')+ const episodeIdList = episodes.map(item => item.id ?? 0).join(',')+ useEffect(() => {+ if (!syncingEpisodes) return+ const syncing = new Set(syncingEpisodes.split(',').map(Number))+ const indexes = episodeIdList.split(',').flatMap((value, index) => syncing.has(Number(value)) ? [index] : [])+ if (indexes.length) setExpanded(new Set(indexes))+ }, [syncingEpisodes, episodeIdList])useEffect(() => { if (!id && !category && categories.length) setCategory(categories.includes('其他') ? '其他' : categories[0]) }, [id, category, categories])- function update(index: number, patch: Partial<EpisodeDraft>) { setEpisodes(value => value.map((item, itemIndex) => itemIndex === index ? { ...item, ...patch } : item)) }+ function update(index: number, patch: Partial<EpisodeDraft>) { setDirty(true); setEpisodes(value => value.map((item, itemIndex) => itemIndex === index ? { ...item, ...patch } : item)) }function episodeBody(episode: EpisodeDraft) {return { episode_no: episode.episode_no, title: episode.title, description: episode.description || '', asset_id: episode.asset_id, cover_asset_id: episode.cover_asset_id, copyright_price_fen: episode.copyright_price_fen || 0, unlock_price_fen: episode.unlock_price_fen || 0, share_bps: episode.share_bps ?? null, source: episode.source || 'external' }}async function save(event: FormEvent<HTMLFormElement>) {- event.preventDefault(); setBusy(true); setError(''); if (handoffs.some(item => item.status === 'pending' || item.status === 'running')) { setBusy(false); setError('成片正在同步,同步完成后再保存'); return } const missing = episodes.findIndex(item => !item.title.trim()); if (missing >= 0) { setExpanded(new Set([missing])); setBusy(false); setError(`第 ${missing + 1} 集标题未填写`); return } const form = new FormData(event.currentTarget)+ event.preventDefault(); setBusy(true); setError(''); setMessage(''); if (syncBlocked || hasSyncFailure) { setBusy(false); setError('请等待同步完成或重试失败任务后再保存,当前输入会保留'); return } const missing = episodes.findIndex(item => !item.title.trim()); if (missing >= 0) { setExpanded(new Set([missing])); setBusy(false); setError(`第 ${missing + 1} 集标题未填写`); return } const form = new FormData(event.currentTarget)try {const payload = { title: form.get('title'), description: form.get('description'), category: category || '其他', tags: String(form.get('tags') || '').split(/[,,]/).map(value => value.trim()).filter(Boolean), sale_type: saleType, copyright_price_fen: Math.round(Number(form.get('copyright_price') || 0) * 100), free_episode_count: freeEpisodeCount, cover_asset_id: coverId, ...(id ? { version: series?.version } : {}) }const saved = await request<SeriesDraft>(id ? `/series/${id}` : '/series', id ? 'PATCH' : 'POST', payload)@@ -95,24 +129,34 @@ export default function SeriesEditor() {// 先删除再改编号,避免同一系列的集数唯一约束冲突。只提交可编辑字段。for (const episodeId of removedEpisodeIds) await request(`/series/${id}/episodes/${episodeId}`, 'DELETE')for (const episode of episodes) {- if (episode.id) await request(`/series/${id}/episodes/${episode.id}`, 'PATCH', { ...episodeBody(episode), version: episode.version })+ if (episode.id) await request(`/series/${id}/episodes/${episode.id}`, 'PATCH', { ...episodeBody(episode), version: saved.episodes.find(remote => remote.id === episode.id)?.version ?? episode.version })else await request(`/series/${id}/episodes`, 'POST', episodeBody(episode))}}if (!id) navigate(`/marketplace/series/${saved.id}/edit`)- else { const fresh = await request<SeriesDraft>(`/series/${saved.id}`); setSeries(fresh); setSaleType(fresh.sale_type); setFreeEpisodeCount(fresh.free_episode_count || 0); setCategory(fresh.category || '其他'); setCoverId(fresh.cover_asset_id ?? null); setEpisodes(fresh.episodes.map(item => ({ ...item, asset_id: item.asset_id ?? null, cover_asset_id: item.cover_asset_id ?? null }))); setRemovedEpisodeIds([]) }- } catch (err) { setError((err as Error).message) } finally { setBusy(false) }+ else { acceptSaved(await request<SeriesDraft>(`/series/${saved.id}`)); setMessage('系列草稿已保存。') }+ } catch (err) {+ setError((err as Error).message)+ // 分集逐条保存失败时,刷新已推进的版本,但保留未保存输入供用户重试。+ if (id) try {+ const fresh = await request<SeriesDraft>(`/series/${id}`)+ setSeries(current => current ? { ...current, version: fresh.version, audit_status: fresh.audit_status, listed: fresh.listed } : fresh)+ setEpisodes(current => current.map(episode => ({ ...episode, version: fresh.episodes.find(remote => remote.id === episode.id)?.version ?? episode.version })))+ } catch { /* 保留原始保存错误 */ }+ } finally { setBusy(false) }}- async function importEpisodes() {- if (!id || !sourceId || !selected.length) return+ async function retryHandoff(handoff: Handoff) {setBusy(true); setError('')- try { const result = await request<{ items: EpisodeDraft[]; handoffs: Handoff[] }>(`/series/${id}/episodes/import-printfilm`, 'POST', { drama_project_id: Number(sourceId), episode_ids: selected }); setEpisodes(value => [...value, ...result.items]); setHandoffs(value => [...result.handoffs, ...value]); setSelected([]); setExpanded(new Set(result.items.map((_, index) => episodes.length + index))); setPoll(value => value + 1) }- catch (err) { setError((err as Error).message) } finally { setBusy(false) }+ try {+ const next = await request<Handoff>(`/handoffs/${handoff.id}/retry`, 'POST')+ setHandoffs(value => value.map(row => row.id === next.id ? next : row)); setPoll(value => value + 1)+ } catch (err) { setError((err as Error).message) } finally { setBusy(false) }}async function submit() {if (!id || !series) return+ if (syncBlocked || dirty || episodeHandoffs.some(item => item.status === 'failed')) { setError('请等待同步完成、处理失败任务并保存修改后,再提交审核'); return }setBusy(true); setError('')- try { const updated = await request<SeriesDraft>(`/series/${id}/submit`, 'POST', { version: series.version }); setSeries(updated); setEpisodes(updated.episodes); setError('系列已提交,等待管理员在同一次内容审核中核验版权和内容。') }+ try { const updated = await request<SeriesDraft>(`/series/${id}/submit`, 'POST', { version: series.version }); acceptSaved(updated); setMessage('系列已提交,等待管理员在同一次内容审核中核验版权和内容。') }catch (err) { setError((err as Error).message) } finally { setBusy(false) }}async function removeSeries() {@@ -127,16 +171,65 @@ export default function SeriesEditor() {setBusy(true); setError('')try {const updated = await request<SeriesDraft>(`/series/${id}/listing?listed=${!series.listed}`, 'POST', { version: series.version })- setSeries(updated); setEpisodes(updated.episodes); setError(updated.listed ? '系列已上架到作品广场。' : '系列已下架,历史审核记录仍保留。')+ setSeries(updated); setEpisodes(updated.episodes); setMessage(updated.listed ? '系列已上架到作品广场。' : '系列已下架,历史审核记录仍保留。')} catch (err) { setError((err as Error).message) } finally { setBusy(false) }}const current = seriesif (id && !series && !error) return <p role="status">正在加载系列…</p>- return <><PageHeading title={id ? '编辑短剧' : '发布短剧'} description="短剧和单条视频一样出现在作品广场。在这一页添加分集,版权规则与单视频相同。" back="/marketplace" /><div className="pf-market-editor-layout"><form className="pf-market-editor-main pf-market-form" onSubmit={save}>- <FormSection step="01" title="系列信息" description="先建立系列,再逐集上传或导入成片。"><label>系列标题<span className="pf-req-mark">必填</span><input name="title" required maxLength={200} placeholder="例如:城市里的光" defaultValue={current?.title} /></label><label>简介<textarea name="description" maxLength={5000} defaultValue={current?.description} placeholder="介绍整部短剧的主题和内容" /></label><div className="pf-market-field-row"><label>分类<span className="pf-req-mark">必填</span><select name="category" required value={category || current?.category || ''} onChange={event => setCategory(event.target.value)} disabled={!categories.length}><option value="" disabled>请选择系列分类</option>{current?.category && !categories.includes(current.category) && <option value={current.category}>{current.category}(历史分类)</option>}{categories.map(name => <option key={name} value={name}>{name}</option>)}</select>{categoryError && <span role="alert">{categoryError}</span>}</label><label>标签<input name="tags" defaultValue={current?.tags?.join(',')} placeholder="都市,短剧" /></label></div><AssetPicker kind="image" value={coverId} onChange={setCoverId} title="系列封面(与分集封面至少上传一处)" /></FormSection>+ return <><PageHeading title={id ? '编辑短剧' : '发布短剧'} description="短剧和单条视频一样出现在作品广场。在这一页添加分集,版权规则与单视频相同。" back="/marketplace" /><div className="pf-market-editor-layout"><form className="pf-market-editor-main pf-market-form" onSubmit={save} onChangeCapture={event => { if (!(event.target as HTMLElement).closest('.pf-market-authorization, [data-market-transient]')) setDirty(true) }}>+ <FormSection step="01" title="系列信息" description="先建立系列,再逐集上传或导入成片。"><label>系列标题<span className="pf-req-mark">必填</span><input name="title" required maxLength={200} placeholder="例如:城市里的光" defaultValue={current?.title} /></label><label>简介<textarea name="description" maxLength={5000} defaultValue={current?.description} placeholder="介绍整部短剧的主题和内容" /></label><div className="pf-market-field-row"><label>分类<span className="pf-req-mark">必填</span><select name="category" required value={category || current?.category || ''} onChange={event => setCategory(event.target.value)} disabled={!categories.length}><option value="" disabled>请选择系列分类</option>{current?.category && !categories.includes(current.category) && <option value={current.category}>{current.category}(历史分类)</option>}{categories.map(name => <option key={name} value={name}>{name}</option>)}</select>{categoryError && <span role="alert">{categoryError}</span>}</label><label>标签<input name="tags" defaultValue={current?.tags?.join(',')} placeholder="都市,短剧" /></label></div><AssetPicker kind="image" value={coverId} onChange={value => { setCoverId(value); setDirty(true) }} title="系列封面(与分集封面至少上传一处)" /></FormSection><FormSection step="02" title="收益方式" description="平台投放收益需要管理员先配置默认分成比例。"><select value={saleType} onChange={event => setSaleType(event.target.value as typeof saleType)}><option value="free">免费公开</option><option value="copyright_contact">联系客服购买版权</option><option value="platform_unlock">平台投放收益(每集独立解锁)</option></select><label>版权参考价(元)<input name="copyright_price" type="number" min="0" step="0.01" defaultValue={current?.copyright_price_fen ? current.copyright_price_fen / 100 : ''} /></label><label>免费集数<span className="pf-req-mark">前几集免费</span><input type="number" min="0" max="10000" step="1" value={freeEpisodeCount} onChange={event => setFreeEpisodeCount(Math.max(0, Number(event.target.value) || 0))} /></label><p className="pf-market-notice">免费集播放原片,不生成水印。选择“免费公开”时全部分集免费;其他收费类型可将前几集设为免费,其余分集按收费方式观看。只改集数或收费类型、不重新上传视频时,不会重新处理成片。</p></FormSection>- <FormSection step="03" title="分集内容" description="每集一个视频和封面。点标题展开这一集,收起后内容仍会保存。"><div className="pf-episode-tools"><button type="button" onClick={() => setExpanded(new Set(episodes.map((_, index) => index)))}>展开全部</button><button type="button" onClick={() => setExpanded(new Set())}>收起全部</button><span>共 {episodes.length} 集</span></div><div className="pf-market-episodes">{episodes.map((episode, index) => { const handoff = handoffs.find(item => item.episode_id === episode.id); const videoLabel = handoff && handoff.status !== 'ready' ? handoff.label : (episode.asset_id ? '视频已上传' : '缺视频'); return <EpisodePanel key={episode.id ?? `new-${index}`} episode={episode} count={episodes.length} free={saleType === 'free' || index < freeEpisodeCount} open={expanded.has(index)} saleType={saleType} seriesId={id} busy={busy} videoLabel={videoLabel} toggle={() => setExpanded(value => { const next = new Set(value); if (next.has(index)) next.delete(index); else next.add(index); return next })} update={patch => update(index, patch)} remove={() => { if (episode.id) setRemovedEpisodeIds(value => [...value, episode.id as number]); setEpisodes(value => value.filter((_, itemIndex) => itemIndex !== index).map((item, itemIndex) => ({ ...item, episode_no: itemIndex + 1 }))); setExpanded(new Set([Math.max(0, index - 1)])) }} goRights={() => navigate(`/marketplace/assets/${episode.asset_id}/rights?source=${episode.source || 'external'}&return=${encodeURIComponent(`/marketplace/series/${id}/edit`)}`)} /> })}</div><button type="button" onClick={() => { setEpisodes(value => [...value, { episode_no: value.length + 1, title: `第${value.length + 1}集`, asset_id: null, cover_asset_id: null, copyright_price_fen: 0, unlock_price_fen: 0, source: 'external' }]); setExpanded(new Set([episodes.length])) }}>+ 添加下一集</button></FormSection>- {id && <FormSection step="04" title="从我的 PrintFilm 漫剧导入" description="只导入勾选的分集。服务器复制到市场后,这里会显示正在同步、已就绪或复制失败可重试。"><select value={sourceId} onChange={event => { setSourceId(event.target.value); setSelected([]) }}><option value="">选择漫剧项目</option>{sources.map(source => <option key={source.id} value={source.id}>{source.title}</option>)}</select>{sources.find(source => String(source.id) === sourceId)?.episodes.map(episode => <label key={episode.id} className="block"><input type="checkbox" disabled={!episode.ready} checked={selected.includes(episode.id)} onChange={event => setSelected(value => event.target.checked ? [...value, episode.id] : value.filter(item => item !== episode.id))} /> {episode.name} {episode.ready ? '' : '(成片未就绪)'}</label>)}<button type="button" disabled={busy || !sourceId || !selected.length} onClick={() => void importEpisodes()}>导入选中分集</button>{handoffs.filter(item => item.status !== 'ready').map(item => <p key={item.id} role={item.status === 'failed' ? 'alert' : 'status'}>{item.label}{item.error ? `:${item.error}` : ''}{item.status === 'failed' ? <button type="button" onClick={() => void request<Handoff>(`/handoffs/${item.id}/retry`, 'POST').then(next => { setHandoffs(value => value.map(row => row.id === next.id ? next : row)); setPoll(value => value + 1) })}>重试复制</button> : null}{item.status === 'ready' && !item.authorization_ready ? <button type="button" onClick={() => navigate('/marketplace/authorization')}>去签署授权函</button> : null}</p>)}</FormSection>}- {error && <p role={error.includes('已') ? 'status' : 'alert'}>{error}</p>}<div className="pf-market-form-actions"><Button variant="lime" type="submit" disabled={busy || !categories.length || !category}>{busy ? '保存中…' : '保存系列草稿'}</Button>{id && (series?.audit_status === 'draft' || series?.audit_status === 'preview_failed') && <button type="button" disabled={busy} onClick={() => void submit()}>{series?.audit_status === 'preview_failed' ? '重试生成水印并提交' : '提交系列审核'}</button>}{id && series?.audit_status === 'processing' && <p role="status">正在生成水印播放文件,完成后自动进入待审核。</p>}{id && series?.audit_status === 'approved' && <button type="button" disabled={busy} onClick={() => void toggleListing()}>{series.listed ? '下架系列' : '上架到作品广场'}</button>}{id && <button type="button" disabled={busy} onClick={() => void removeSeries()}>删除短剧</button>}</div>- </form><PublishGuide /></div></>+ <FormSection step="03" title="分集内容" description="每集一个完整视频和封面。同步期间可以填写信息,完成后再保存。">+ <div className="pf-episode-tools"><button type="button" onClick={() => setExpanded(new Set(episodes.map((_, index) => index)))}>展开全部</button><button type="button" onClick={() => setExpanded(new Set())}>收起全部</button><span>共 {episodes.length} 集</span></div>+ {syncBlocked && <p className="pf-market-notice" role="status">{syncing ? '成片正在后台同步,可先填写标题与价格。同步完成后即可保存和提交;关闭页面不影响任务。' : '正在确认同步状态…'}</p>}+ {hasSyncFailure && <p className="pf-market-notice" role="alert">部分成片同步失败。当前输入已保留,请先重试同步或重新选择源版本,完成后再保存。</p>}+ {handoffError && <p role="alert">{handoffError}</p>}+ <div className="pf-market-episodes">{episodes.map((episode, index) => {+ const handoff = episodeHandoffs.find(item => item.episode_id === episode.id)+ const syncingVideo = Boolean(handoff && isHandoffActive(handoff))+ const fromPrintfilm = episode.source === 'printfilm'+ const videoLabel = handoff ? handoffLabel(handoff) : episode.asset_id ? '视频已就绪' : '缺视频'+ return <div key={episode.id ?? `new-${index}`}>+ <EpisodePanel episode={episode} count={episodes.length} free={saleType === 'free' || index < freeEpisodeCount} open={expanded.has(index)} saleType={saleType} seriesId={id} busy={busy || syncBlocked || hasSyncFailure} videoLabel={videoLabel} videoLocked={syncingVideo || (fromPrintfilm && !episode.asset_id)} lockVideoUntilPreview={fromPrintfilm}+ toggle={() => setExpanded(value => { const next = new Set(value); if (next.has(index)) next.delete(index); else next.add(index); return next })}+ update={patch => update(index, patch)}+ remove={() => { setDirty(true); if (episode.id) setRemovedEpisodeIds(value => [...value, episode.id as number]); setEpisodes(value => value.filter((_, itemIndex) => itemIndex !== index).map((item, itemIndex) => ({ ...item, episode_no: itemIndex + 1 }))); setExpanded(new Set([Math.max(0, index - 1)])) }}+ goRights={() => { if (dirty) { setError('请先保存草稿,再填写外部作品的权属材料'); return } navigate(`/marketplace/assets/${episode.asset_id}/rights?source=${episode.source || 'external'}&return=${encodeURIComponent(`/marketplace/series/${id}/edit`)}`) }} />+ {handoff && handoff.status !== 'ready' && <p className="pf-market-notice" role={handoff.status === 'failed' ? 'alert' : 'status'}>第 {episode.episode_no} 集 · {handoffLabel(handoff)}{handoff.error ? `:${handoff.error}` : ''}+ {handoff.status === 'failed' && handoff.retryable !== false && <button type="button" disabled={busy} onClick={() => void retryHandoff(handoff)}>重试同步</button>}+ {handoff.status === 'failed' && handoff.retryable === false && <span>请在下方重新选择漫剧分集,确认最新源版本后同步。</span>}+ </p>}+ </div>+ })}</div>+ <button type="button" disabled={busy || syncBlocked || hasSyncFailure} onClick={() => { setDirty(true); setEpisodes(value => [...value, { episode_no: value.length + 1, title: `第${value.length + 1}集`, asset_id: null, cover_asset_id: null, copyright_price_fen: 0, unlock_price_fen: 0, source: 'external' }]); setExpanded(new Set([episodes.length])) }}>+ 添加下一集</button>+ </FormSection>+ {id && <FormSection step="04" title="从我的 PrintFilm 漫剧导入" description="选择项目后,在同一个发布弹窗里选择完整分集;新源版本必须明确确认后才能更新。">+ <select data-market-transient value={sourceId} disabled={busy || syncBlocked} onChange={event => setSourceId(event.target.value)}><option value="">选择漫剧项目</option>{sources.map(source => <option key={source.id} value={source.id}>{source.title}</option>)}</select>+ <button type="button" disabled={busy || syncBlocked || !sourceId || (dirty && !hasSyncFailure)} onClick={() => setImportOpen(true)}>选择分集并同步到此系列</button>+ {dirty && !hasSyncFailure && <p className="pf-market-notice">请先保存当前修改,再导入分集。</p>}+ </FormSection>}+ {episodes.some(item => item.source === 'printfilm') && <FormSection step="05" title="PrintFilm 授权确认" description="同一账号按当前条款签署一次,提交系列审核时自动关联全部 PrintFilm 分集。">+ <AuthorizationPanel onSigned={() => { setSeries(value => value ? { ...value, authorization_ready: true } : value); setMessage('授权函已签署,提交审核时将自动关联本系列的 PrintFilm 分集。') }} />+ </FormSection>}+ {error && <p role="alert">{error}</p>}{message && <p role="status">{message}</p>}+ <div className="pf-market-form-actions">+ <Button variant="lime" type="submit" disabled={busy || syncBlocked || hasSyncFailure || !categories.length || !category}>{busy ? '处理中…' : '保存系列草稿'}</Button>+ {id && (series?.audit_status === 'draft' || series?.audit_status === 'rejected' || series?.audit_status === 'preview_failed') && <button type="button" disabled={busy || syncBlocked || dirty || episodeHandoffs.some(item => item.status === 'failed') || (episodes.some(item => item.source === 'printfilm') && series.authorization_ready === false)} onClick={() => void submit()}>{series?.audit_status === 'preview_failed' ? '重试生成水印并提交' : '提交系列审核'}</button>}+ {id && dirty && <p role="status">有未保存修改,请先保存草稿再提交审核。</p>}+ {id && series?.audit_status === 'processing' && <p role="status">正在生成水印播放文件,完成后自动进入待审核。</p>}+ {id && series?.audit_status === 'approved' && <button type="button" disabled={busy || syncBlocked || dirty} onClick={() => void toggleListing()}>{series.listed ? '下架系列' : '上架到作品广场'}</button>}+ {id && <button type="button" disabled={busy || syncBlocked} onClick={() => void removeSeries()}>删除短剧</button>}+ </div>+ </form><PublishGuide /></div>+ {importOpen && id && sourceId && <DramaPublishModal projectId={Number(sourceId)} targetSeriesId={Number(id)} onClose={() => setImportOpen(false)} onPublished={() => {+ setBusy(true)+ request<SeriesDraft>(`/series/${id}`).then(fresh => {+ const previous = savedEpisodes.current+ setEpisodes(current => [...mergeSyncedEpisodes(current, fresh.episodes, previous), ...fresh.episodes.filter(item => !current.some(local => local.id === item.id))])+ savedEpisodes.current = fresh.episodes+ setSeries(current => current ? { ...current, version: fresh.version, audit_status: fresh.audit_status, listed: fresh.listed, sync_in_progress: fresh.sync_in_progress } : fresh)+ setPoll(value => value + 1); setExpanded(new Set(fresh.episodes.map((_, index) => index))); setMessage('同步任务已创建,完成后会自动填入完整视频。当前填写的内容已保留。')+ }).catch(err => setError((err as Error).message)).finally(() => setBusy(false))+ }} />}+ </>}diff --git a/frontend/src/features/marketplace/api.ts b/frontend/src/features/marketplace/api.tsindex 149f3e8..cb829bb 100644--- a/frontend/src/features/marketplace/api.ts+++ b/frontend/src/features/marketplace/api.ts@@ -21,6 +21,7 @@ export type Handoff = {id: number; status: string; label: string; error: string; authorization_ready: booleantarget_kind: string; target_id: number; work_id: number | null; episode_id: number | nullseries_id: number | null; asset_id: number | null+ phase?: string; error_code?: string | null; retryable?: boolean; target_version?: number}export type RightsRecord = {id?: number; asset_id: number; version: number; details?: Record<string, string>;diff --git a/frontend/src/features/marketplace/dramaPublishing.css b/frontend/src/features/marketplace/dramaPublishing.cssnew file mode 100644index 0000000..2c10ad4--- /dev/null+++ b/frontend/src/features/marketplace/dramaPublishing.css@@ -0,0 +1,24 @@+.pf-drama-publish { color:var(--pf-ink); }+.drama-project-row-menu.has-publish { min-width:184px; white-space:nowrap; }+.pf-drama-publish-intro { margin:0 0 20px; color:var(--pf-muted); font-size:13px; line-height:1.8; }+.pf-drama-publish-project { display:flex; align-items:center; gap:12px; padding-bottom:18px; }+.pf-drama-publish-project svg { color:var(--pf-ink); }+.pf-drama-publish-project div { display:grid; gap:5px; }+.pf-drama-publish-project span,.pf-drama-publish-episode small { color:var(--pf-muted); font-size:12px; }+.pf-drama-publish-episodes { display:grid; gap:8px; max-height:300px; overflow:auto; margin:0 0 20px; }+.pf-drama-publish-episode { padding:14px; border:1px solid var(--pf-line); border-radius:12px; background:var(--pf-bg); }+.pf-drama-publish-episode>label { display:flex; align-items:center; gap:12px; cursor:pointer; }+.pf-drama-publish-episode input { width:16px; height:16px; flex:0 0 auto; accent-color:var(--pf-ink); }+.pf-drama-publish-episode span { display:grid; gap:6px; }+.pf-drama-publish-episode strong { font-size:14px; }+.pf-drama-publish-episode.is-disabled { opacity:.6; }+.pf-drama-publish-episode label.pf-drama-publish-update { margin:12px 0 0 28px; font-size:12px; color:#946323; }+.pf-drama-publish-field { display:grid; gap:8px; font-size:13px; margin:16px 0; }+.pf-drama-publish-field input,.pf-drama-publish-field select { width:100%; min-height:42px; border:1px solid var(--pf-line); border-radius:10px; padding:9px 12px; background:var(--pf-bg); color:var(--pf-ink); font:inherit; }+.pf-drama-publish-warning { border:1px solid #dfbd7470; border-radius:10px; padding:12px 14px; color:#946323; background:#dfbd7412; font-size:12px; line-height:1.8; }+.pf-drama-publish-hint { display:flex; align-items:flex-start; gap:7px; font-size:12px; color:var(--pf-muted); line-height:1.8; }+.pf-drama-publish-hint svg { flex:0 0 auto; margin-top:3px; }+.pf-drama-publish-error { font-size:13px; color:var(--pf-error,#c3473a); }+.pf-drama-publish-error button { color:inherit; text-decoration:underline; border:0; background:none; cursor:pointer; }+.pf-drama-publish-spin { animation:pf-drama-publish-spin 1s linear infinite; }+@keyframes pf-drama-publish-spin { to { transform:rotate(360deg); } }diff --git a/frontend/src/features/marketplace/dramaPublishing.ts b/frontend/src/features/marketplace/dramaPublishing.tsnew file mode 100644index 0000000..1aa43f4--- /dev/null+++ b/frontend/src/features/marketplace/dramaPublishing.ts@@ -0,0 +1,66 @@+import type { Handoff } from './api'++export type PublishEpisode = {+ id: number; name: string; episode_number: number; fragment_count: number; completed_count: number+ ready: boolean; reason?: string | null; source_version: string+}+export type ImportedEpisode = {+ source_episode_id: number; episode_id: number; source_version: string; status: string; handoff_id?: number | null; requires_update?: boolean+}+export type PublishSeries = {+ id: number; title: string; version: number; listed?: boolean; audit_status?: string; imports: ImportedEpisode[]+}+export type DramaPublishContext = {+ project: { id: number; title: string; description?: string }+ episodes: PublishEpisode[]; series: PublishSeries[]; authorization_ready: boolean; storage_configured: boolean+}+export type DramaPublishResult = { series_id: number; items: { id: number }[]; handoffs: Handoff[] }++export function sourceRelation(episode: PublishEpisode, target?: PublishSeries) {+ const existing = target?.imports.find(item => item.source_episode_id === episode.id)+ return { existing, changed: Boolean(existing && (existing.requires_update || existing.status === 'legacy' || existing.source_version !== episode.source_version)) }+}++export function publishSelection(context: DramaPublishContext, selected: number[], updates: number[], target?: PublishSeries) {+ return context.episodes.filter(item => selected.includes(item.id)).sort((a, b) => a.episode_number - b.episode_number).map(episode => {+ if (!episode.ready) throw new Error(`${episode.name}:${episode.reason || '分集尚未全部生成完成'}`)+ const { changed } = sourceRelation(episode, target)+ if (changed && !updates.includes(episode.id)) throw new Error(`请确认更新「${episode.name}」的新版本`)+ return { episode_id: episode.id, source_version: episode.source_version, update: changed }+ })+}++const phaseLabels: Record<string, string> = {+ queued: '排队中', pending: '排队中', syncing: '同步素材', downloading: '同步素材', copying: '同步素材',+ composing: '拼接整集', concatenating: '拼接整集', validating: '校验视频', ready: '已就绪', failed: '同步失败',+}+export function handoffLabel(handoff: Handoff) {+ return phaseLabels[handoff.phase || ''] || handoff.label || phaseLabels[handoff.status] || '同步中'+}+export function isHandoffActive(handoff: Pick<Handoff, 'status'>) {+ return handoff.status === 'pending' || handoff.status === 'running'+}+// 一个分集可能保留多个历史任务;只展示最新任务,避免旧任务覆盖新状态。+export function latestEpisodeHandoffs(items: Handoff[]) {+ const latest = new Map<number, Handoff>()+ for (const item of items) {+ if (item.episode_id && (!latest.has(item.episode_id) || latest.get(item.episode_id)!.id < item.id)) latest.set(item.episode_id, item)+ }+ return [...latest.values()]+}++type SyncEpisode = { id?: number; version?: number; asset_id: number | null; cover_asset_id: number | null; source?: string }+// 只回填同步产物和版本;封面被用户编辑过时保留本地选择,标题和价格始终保留。+export function mergeSyncedEpisodes<T extends SyncEpisode>(current: T[], remote: T[], previous: T[]) {+ return current.map(episode => {+ const fresh = remote.find(item => item.id === episode.id)+ if (!episode.id || !fresh) return episode+ const before = previous.find(item => item.id === episode.id)+ return {+ ...episode, version: fresh.version,+ asset_id: before && before.asset_id !== episode.asset_id ? episode.asset_id : fresh.asset_id,+ cover_asset_id: before && before.cover_asset_id !== episode.cover_asset_id ? episode.cover_asset_id : fresh.cover_asset_id,+ source: before && before.source !== episode.source ? episode.source : fresh.source,+ }+ })+}diff --git a/frontend/src/features/marketplace/marketplace.css b/frontend/src/features/marketplace/marketplace.cssindex 6e84f3a..a99c2e5 100644--- a/frontend/src/features/marketplace/marketplace.css+++ b/frontend/src/features/marketplace/marketplace.css@@ -237,6 +237,7 @@ body:has(.pf-market-shell) .pf-wx-fab-root { display:none; }.pf-episode-fold-head span { display:inline-flex; align-items:center; gap:8px; font-weight:650; }.pf-episode-fold-head em { font-style:normal; color:var(--pf-muted); font-size:12px; }.pf-episode-fold-body { display:grid; gap:12px; padding:0 14px 14px; }+.pf-episode-fold-body .pf-market-notice { margin:0 !important; }.pf-market-kind-choice { display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:16px; }.pf-market-kind-choice button { text-align:left; border:1px solid var(--pf-line); background:var(--pf-card); border-radius:16px; padding:22px; display:flex; flex-direction:column; gap:8px; cursor:pointer; }.pf-market-kind-choice strong { font-size:18px; }diff --git a/frontend/src/pages/drama/DramaListPage.tsx b/frontend/src/pages/drama/DramaListPage.tsxindex 64f1f11..ca29872 100644--- a/frontend/src/pages/drama/DramaListPage.tsx+++ b/frontend/src/pages/drama/DramaListPage.tsx@@ -28,6 +28,8 @@ import { useI18n } from '../../i18n'import { DramaEpisodeCountPopover } from './DramaEpisodeCountPopover'import { DramaImageStyleModal } from './DramaImageStyleModal'import { DramaProjectCardMenu } from './DramaProjectCardMenu'+import DramaPublishModal from '../../features/marketplace/DramaPublishModal'+import { useMarketplace } from '../../features/marketplace/hooks'import './drama.css'const CREATIVE_MIN_LENGTH = 20@@ -68,6 +70,8 @@ export default function DramaListPage() {// 渲染 Agent 首页内容function DramaListInner() {const navigate = useNavigate()+ const { capabilities } = useMarketplace()+ const [publishProjectId, setPublishProjectId] = useState<number | null>(null)const { t, m } = useI18n()const filterOptions = useMemo<PillOption<ProjectFilter>[]>(() =>@@ -502,6 +506,7 @@ function DramaListInner() {<DramaProjectCardMenuonRename={() => void handleRename(item)}onDelete={() => void handleDeleteOne(item)}+ onPublish={capabilities?.enabled ? () => setPublishProjectId(item.id) : undefined}/></div><p className="pf-drama-card-meta">{formatDramaCardMeta(item)}</p>@@ -541,6 +546,7 @@ function DramaListInner() {</div>) : null}</div>+ {publishProjectId && capabilities?.enabled && <DramaPublishModal projectId={publishProjectId} onClose={() => setPublishProjectId(null)} />}</AppShell>)}diff --git a/frontend/src/pages/drama/DramaProjectCardMenu.tsx b/frontend/src/pages/drama/DramaProjectCardMenu.tsxindex 03577c4..325feba 100644--- a/frontend/src/pages/drama/DramaProjectCardMenu.tsx+++ b/frontend/src/pages/drama/DramaProjectCardMenu.tsx@@ -6,13 +6,14 @@ import { MoreHorizontal } from 'lucide-react'type Props = {onRename: () => voidonDelete: () => void+ onPublish?: () => void}// 鼠标离开后延迟收起,避免滑向菜单项时被立刻关掉const HIDE_DELAY_MS = 120// 渲染项目卡片重命名 / 删除菜单-export function DramaProjectCardMenu({ onRename, onDelete }: Props) {+export function DramaProjectCardMenu({ onRename, onDelete, onPublish }: Props) {/** open 菜单是否展开* rootRef 用于点外部关闭@@ -100,7 +101,11 @@ export function DramaProjectCardMenu({ onRename, onDelete }: Props) {<MoreHorizontal size={16} strokeWidth={1.8} /></button>{open ? (- <div className="drama-project-row-menu" role="menu">+ <div className={`drama-project-row-menu${onPublish ? ' has-publish' : ''}`} role="menu">+ {onPublish && <button type="button" role="menuitem"+ onPointerDown={event => { event.preventDefault(); event.stopPropagation(); closeThenRun(onPublish) }}+ onClick={event => { event.stopPropagation(); if (!ignoreToggleRef.current) closeThenRun(onPublish) }}+ >发布到数字资产市场</button>}<buttontype="button"role="menuitem"diff --git a/frontend/src/pages/drama/EpisodeEditSidePane.tsx b/frontend/src/pages/drama/EpisodeEditSidePane.tsxindex 37c0b8a..4ff1971 100644--- a/frontend/src/pages/drama/EpisodeEditSidePane.tsx+++ b/frontend/src/pages/drama/EpisodeEditSidePane.tsx@@ -1,7 +1,8 @@/** 分集编辑右侧:分段视频预览 + 入口打开全屏分镜画布 */import { useState } from 'react'import { Download, Loader2 } from 'lucide-react'-import { useNavigate } from 'react-router-dom'+import DramaPublishModal from '../../features/marketplace/DramaPublishModal'+import { useMarketplace } from '../../features/marketplace/hooks'import type { DramaFragment } from '../../api/drama'import { DramaSubtitleBoard } from '../../components/drama/DramaSubtitleBoard'import { DramaFragmentSegmentedVideoPlayer } from '../../components/drama/DramaFragmentSegmentedVideoPlayer'@@ -65,7 +66,8 @@ export function EpisodeEditSidePane({* composeProgress 拉取/拼接进度* composeError 失败原因*/- const navigate = useNavigate()+ const { capabilities } = useMarketplace()+ const [publishOpen, setPublishOpen] = useState(false)const [composeBusy, setComposeBusy] = useState(false)const [composeProgress, setComposeProgress] = useState<EpisodeComposeProgress | null>(null)const [composeError, setComposeError] = useState('')@@ -128,11 +130,11 @@ export function EpisodeEditSidePane({)}{composeProgressLabel(composeProgress, composeBusy)}</button>- {projectId && episodeId && fragments.some(item => item.video) ? (+ {capabilities?.enabled && projectId && episodeId ? (<buttontype="button"className="drama-ep-compose-btn drama-ep-compose-btn--header"- onClick={() => navigate(`/marketplace/from-printfilm?drama=${projectId}&episode=${episodeId}`)}+ onClick={() => setPublishOpen(true)}>发布到数字资产市场</button>@@ -184,6 +186,7 @@ export function EpisodeEditSidePane({/></>)}+ {publishOpen && capabilities?.enabled && projectId && <DramaPublishModal projectId={Number(projectId)} initialEpisodeId={episodeId} onClose={() => setPublishOpen(false)} />}</aside>)}diff --git a/frontend/tests/dramaPublishing.test.mjs b/frontend/tests/dramaPublishing.test.mjsnew file mode 100644index 0000000..33d9025--- /dev/null+++ b/frontend/tests/dramaPublishing.test.mjs@@ -0,0 +1,56 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { latestEpisodeHandoffs, mergeSyncedEpisodes, publishSelection, sourceRelation } from '../src/features/marketplace/dramaPublishing.ts'++const episode = (id, episode_number, source_version = 'v1') => ({ id, name: `第${episode_number}集`, episode_number, source_version, ready: true, fragment_count: 3, completed_count: 3 })++test('按原集数发布,不能将不完整分集混入批次', () => {+ const context = { episodes: [episode(8, 2), episode(4, 1)] }+ assert.deepEqual(publishSelection(context, [8, 4], []), [+ { episode_id: 4, source_version: 'v1', update: false },+ { episode_id: 8, source_version: 'v1', update: false },+ ])+ context.episodes[0] = { ...context.episodes[0], ready: false, reason: '第3镜未生成' }+ assert.throws(() => publishSelection(context, [8, 4], []), /第3镜未生成/)+})++test('同一目标的同版本直接复用,新源版本必须明确确认', () => {+ const target = { imports: [{ source_episode_id: 4, episode_id: 10, source_version: 'v1' }] }+ const context = { episodes: [episode(4, 1)] }+ assert.equal(sourceRelation(context.episodes[0], target).changed, false)+ assert.equal(publishSelection(context, [4], [], target)[0].update, false)+ context.episodes[0].source_version = 'v2'+ assert.throws(() => publishSelection(context, [4], [], target), /请确认更新/)+ assert.deepEqual(publishSelection(context, [4], [4], target), [{ episode_id: 4, source_version: 'v2', update: true }])+ // 原片没变但目标已修改/遗留导入时,同样要求重新确认,不能返回失效任务。+ target.imports[0].source_version = 'v2'+ target.imports[0].requires_update = true+ assert.throws(() => publishSelection(context, [4], [], target), /请确认更新/)+ assert.equal(publishSelection(context, [4], [4], target)[0].update, true)+})++test('每集只采用最新同步任务,旧版成功不能盖掉新版失败或运行状态', () => {+ const items = [+ { id: 5, episode_id: 1, status: 'ready' },+ { id: 9, episode_id: 1, status: 'failed' },+ { id: 8, episode_id: 2, status: 'running' },+ { id: 6, episode_id: 2, status: 'ready' },+ { id: 10, episode_id: null, status: 'ready' },+ ]+ assert.deepEqual(latestEpisodeHandoffs(items).map(item => [item.id, item.status]), [[9, 'failed'], [8, 'running']])+})++test('同步完成回填视频及最新版本,保留本地标题、价格和新选封面', () => {+ const previous = [{ id: 1, version: 1, title: '导入标题', asset_id: null, cover_asset_id: null, source: 'printfilm', unlock_price_fen: 0 }]+ const current = [{ ...previous[0], title: '编辑中的标题', cover_asset_id: 20, unlock_price_fen: 1800 }]+ const remote = [{ ...previous[0], version: 3, asset_id: 30, cover_asset_id: 31, unlock_price_fen: 0 }]+ const merged = mergeSyncedEpisodes(current, remote, previous)+ assert.deepEqual(merged, [{ ...current[0], version: 3, asset_id: 30 }])+})++test('后台第二次回填仍保留用户选择的封面和手动视频,新添分集不会被轮询删掉', () => {+ const previous = [{ id: 1, version: 3, asset_id: 30, cover_asset_id: 31, source: 'printfilm' }]+ const current = [{ ...previous[0], asset_id: 41, cover_asset_id: 42 }, { asset_id: null, cover_asset_id: null, title: '新添分集' }]+ const remote = [{ ...previous[0], version: 4, asset_id: 50, cover_asset_id: 51 }]+ assert.deepEqual(mergeSyncedEpisodes(current, remote, previous), [{ ...current[0], version: 4 }, current[1]])+})