Skip to content

PRINTFILM: AI short-video marketing and AI short-drama creation platform

配置

增瑞 田3ea9e15178d8
diff --git a/backend/app/marketplace/drama_publish.py b/backend/app/marketplace/drama_publish.py
index 14aec29..1157e67 100644
--- a/backend/app/marketplace/drama_publish.py
+++ b/backend/app/marketplace/drama_publish.py
@@ -21,6 +21,11 @@ ACTIVE = ("pending", "leased", "running", "awaiting_poll", "awaiting_review")
BUSY = ("queued", "running", "generating", "pending", "leased")
+def terminal_source_task(item) -> bool:
+ return bool(item and item.status == "failed" and any(code in (item.error or "") for code in (
+ "SOURCE_CHANGED", "TARGET_CHANGED", "SOURCE_INCOMPATIBLE", "重新选择分集")))
+
+
def digest(value) -> str:
return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False, default=str).encode()).hexdigest()
@@ -128,7 +133,7 @@ async def publish_context(project_id: int, db: DB, user: Actor):
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 (
+ reusable = bool(handoff and not terminal_source_task(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)))
@@ -241,7 +246,7 @@ async def publish_selected(project_id: int, body: DramaPublishInput, db, user):
.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
+ previous_matches = bool(previous and not terminal_source_task(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)))
diff --git a/backend/app/marketplace/series.py b/backend/app/marketplace/series.py
index ddeb089..a88d1c1 100644
--- a/backend/app/marketplace/series.py
+++ b/backend/app/marketplace/series.py
@@ -245,8 +245,15 @@ async def update_episode(series_id: int, episode_id: int, body: EpisodeUpdate, d
await asset_owned_for_draft(db, body.asset_id, user)
if body.cover_asset_id:
await asset_owned(db, body.cover_asset_id, user, ("image",))
+ asset_changed = body.asset_id != item.asset_id
for key, value in body.model_dump(exclude={"version"}).items():
setattr(item, key, value)
+ if asset_changed:
+ # A manually replaced video no longer represents the frozen imported
+ # source. Keep historical tasks/publications, but detach the live mapping.
+ item.source_type, item.source_snapshot = "upload", {}
+ item.preview_status, item.preview_key, item.preview_attempts = "none", None, 0
+ item.playback_status, item.playback_manifest_key, item.playback_attempts = "none", None, 0
item.version += 1
item.audit_status, item.listed, item.reason = "draft", False, ""
series.version += 1
diff --git a/backend/tests/test_marketplace_drama_publish.py b/backend/tests/test_marketplace_drama_publish.py
index 3bfd0f8..4ece813 100644
--- a/backend/tests/test_marketplace_drama_publish.py
+++ b/backend/tests/test_marketplace_drama_publish.py
@@ -317,6 +317,25 @@ async def test_source_file_change_is_detected_before_worker_binding(drama_publis
assert existing.target.asset_id is None
+async def test_terminal_same_source_can_be_explicitly_resynced(drama_publish_ctx):
+ """源恢复原状后仍能重新确认,不永远复用终止的旧任务。"""
+ ctx = drama_publish_ctx
+ existing = await published(ctx)
+ existing.task.status = "failed"
+ existing.task.error = "MARKETPLACE_SOURCE_CHANGED:源分集曾在同步时重新生成"
+ await ctx.db.commit()
+ context = (await ctx.client.get(f"/api/marketplace/printfilm/dramas/{existing.project.id}/publish-context")).json()
+ target = next(row for row in context["series"] if row["id"] == existing.series.id)
+ assert target["imports"][0]["requires_update"] is True
+ 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 response.json()["handoffs"][0]["id"] != existing.task.id
+ assert response.json()["handoffs"][0]["status"] == "pending"
+ assert await ctx.db.scalar(select(func.count()).select_from(SeriesEpisode)) == 1
+
+
@pytest.mark.parametrize("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):
"""实际执行领取/阶段/终态;仅替换远端存储与媒体制作,不伪造任务状态。"""
diff --git a/backend/tests/test_marketplace_publication_access.py b/backend/tests/test_marketplace_publication_access.py
index a86bd42..4c5cbb7 100644
--- a/backend/tests/test_marketplace_publication_access.py
+++ b/backend/tests/test_marketplace_publication_access.py
@@ -16,7 +16,7 @@ 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,
+ Asset, Authorization, ContentOrder, Entitlement, EpisodePreview, Event, Handoff, MarketBase, Publication,
RevenueConfig, RevenueLedger, Rights, Series, SeriesEpisode, Work, WorkPreview,
)
from conftest import _ensure_test_database, _resolve_test_database_url
@@ -375,3 +375,47 @@ async def test_work_submission_freezes_default_share_and_never_rewrites_approved
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 == 2100
+
+
+async def test_replacing_imported_printfilm_video_detaches_source_and_reuses_account_authorization(publication_ctx):
+ from app.marketplace.authorization import VERSION
+
+ ctx = publication_ctx
+ content = await make_publication(ctx)
+ ctx.user = ctx.owner
+ old_handoff = Handoff(owner_id=ctx.owner.id, idempotency_key=uuid.uuid4().hex,
+ source_kind="drama_episode", source_id=123, source_version="original-source-version",
+ target_kind="series_episode", target_id=content.item.id, series_id=content.series.id,
+ asset_id=content.asset.id, status="ready")
+ new_video = Asset(owner_id=ctx.owner.id, kind="video", filename="replacement.mp4", content_type="video/mp4",
+ size_bytes=200, object_key="marketplace/manual/replacement.mp4", status="ready")
+ cover = Asset(owner_id=ctx.owner.id, kind="image", filename="cover.png", content_type="image/png",
+ size_bytes=10, object_key="marketplace/manual/cover.png", status="ready")
+ authorization = Authorization(owner_id=ctx.owner.id, template_version=VERSION, signer_name="测试签署人",
+ body="test authorization", body_hash="a" * 64, letter_key="marketplace/auth/letter.png",
+ signature_key="marketplace/auth/signature.png", client_ip="127.0.0.1", user_agent="test")
+ ctx.db.add_all([old_handoff, new_video, cover, authorization, RevenueConfig(id=1, platform_share_bps=2100)])
+ await ctx.db.flush()
+ content.item.source, content.item.source_type = "printfilm", "drama_import"
+ content.item.source_snapshot = {"source_kind": "drama_episode", "drama_episode_id": 123,
+ "last_handoff_id": old_handoff.id, "imported_source_version": "original-source-version"}
+ content.item.preview_status, content.item.preview_key = "done", "marketplace/old/preview.mp4"
+ content.item.playback_status, content.item.playback_manifest_key = "done", "marketplace/hls/old/index.m3u8"
+ await ctx.db.flush()
+ response = await ctx.client.patch(f"/api/marketplace/series/{content.series.id}/episodes/{content.item.id}", json={
+ "episode_no": 1, "title": "替换后的PrintFilm视频", "version": 1, "source": "printfilm",
+ "asset_id": new_video.id, "cover_asset_id": cover.id, "unlock_price_fen": 999})
+ assert response.status_code == 200, response.text
+ assert content.item.source_type == "upload" and content.item.source_snapshot == {}
+ assert content.item.preview_status == "none" and content.item.preview_key is None
+ assert content.item.playback_status == "none" and content.item.playback_manifest_key is None
+ assert old_handoff.status == "ready" and old_handoff.asset_id == content.asset.id
+ response = await ctx.client.post(f"/api/marketplace/series/{content.series.id}/submit", json={"version": content.series.version})
+ assert response.status_code == 200, response.text
+ proof = (await ctx.db.execute(select(Rights).where(Rights.asset_id == new_video.id))).scalar_one()
+ assert proof.details["source"] == "printfilm" and proof.details["authorization_id"] == str(authorization.id)
+ assert proof.details["authorization_version"] == VERSION and not proof.certificate_asset_id
+ assert proof.basic_status == "pending" and proof.full_status == "pending"
+ assert content.publication.asset_id == content.asset.id and content.publication.version == 1
+ assert content.publication.share_bps == 2345 and content.publication.audit_status == "approved"
+ assert content.publication.playback_manifest_key == "marketplace/hls/old/index.m3u8"
diff --git a/frontend/src/features/marketplace/api.ts b/frontend/src/features/marketplace/api.ts
index cb829bb..b1ec4e8 100644
--- a/frontend/src/features/marketplace/api.ts
+++ b/frontend/src/features/marketplace/api.ts
@@ -74,10 +74,28 @@ export async function media(kind: string, id: number, purpose: string) {
return (await request<{ url: string }>(`/media/${kind}/${id}/${purpose}`)).url
}
+// 续传键只用本地指纹。HTTPS 用 SHA-256;HTTP 页面没有 crypto.subtle,改用同一段字节的纯计算。
+async function sampleDigest(sample: ArrayBuffer): Promise<string> {
+ const subtle = globalThis.crypto?.subtle
+ if (subtle) {
+ const hash = await subtle.digest('SHA-256', sample)
+ return Array.from(new Uint8Array(hash), value => value.toString(16).padStart(2, '0')).join('')
+ }
+ const bytes = new Uint8Array(sample)
+ let high = 0x811c9dc5
+ let low = 0x01000193
+ for (let index = 0; index < bytes.length; index++) {
+ high = Math.imul(high ^ bytes[index], 0x01000193)
+ low = Math.imul(low ^ bytes[bytes.length - 1 - index], 0x01000193)
+ }
+ const hex = (value: number) => (value >>> 0).toString(16).padStart(8, '0')
+ return hex(high) + hex(low)
+}
+
// 保留用户选择的文件;使用首尾片段指纹区分续传,不读取整段视频。
export async function upload(file: File, kind: string, progress: (percent: number) => void, signal?: AbortSignal): Promise<number> {
const sample = await new Blob([file.slice(0, 65536), file.slice(-65536)]).arrayBuffer()
- const digest = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', sample)), value => value.toString(16).padStart(2, '0')).join('')
+ const digest = await sampleDigest(sample)
const key = `marketplace-upload:${file.name}:${file.size}:${file.lastModified}:${digest}`
type Session = { id: number; asset_id: number; state: string; part_size: number; uploaded_parts: number[]; expires_at: string }
let session: Session | undefined