Skip to content

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

feat: 增加独立的数字资产市场,并从 PrintFilm 成片异步转入草稿。

增瑞 田c2af4770bd04
diff --git a/admin/src/App.tsx b/admin/src/App.tsx
index 4a6cf92..7f92c75 100644
--- a/admin/src/App.tsx
+++ b/admin/src/App.tsx
@@ -19,6 +19,7 @@ import { SettingsPage } from "@/pages/SettingsPage";
import { TemplatesPage } from "@/pages/TemplatesPage";
import { UsersPage } from "@/pages/UsersPage";
import { WorksPage } from "@/pages/WorksPage";
+import MarketplaceAdmin from "@/features/marketplace/MarketplaceAdmin";
// Guard: require JWT + admin role
function RequireAdmin() {
@@ -51,6 +52,7 @@ export default function App() {
<Route path="drama-fragments" element={<DramaFragmentsPage />} />
<Route path="drama-fragments/:fragmentId" element={<DramaFragmentDetailPage />} />
<Route path="works" element={<WorksPage />} />
+ <Route path="marketplace" element={<MarketplaceAdmin />} />
<Route path="templates" element={<TemplatesPage />} />
<Route path="queues" element={<QueuesPage />} />
<Route path="settings" element={<SettingsPage />} />
diff --git a/admin/src/components/layout/AdminLayout.tsx b/admin/src/components/layout/AdminLayout.tsx
index 16fe00c..996d27e 100644
--- a/admin/src/components/layout/AdminLayout.tsx
+++ b/admin/src/components/layout/AdminLayout.tsx
@@ -1,4 +1,5 @@
import { useState } from "react";
+import { useMarketplaceEnabled } from "@/features/marketplace/api";
import { NavLink, Outlet, useLocation, useNavigate } from "react-router-dom";
@@ -143,7 +144,7 @@ const navGroups: NavGroup[] = [
-const titles: Record<string, string> = {
+const titles: Record<string, string> = {"/marketplace": "数字资产平台运营",
"/": "仪表盘",
@@ -193,6 +194,7 @@ function resolveTitle(pathname: string): string {
// Admin shell: dark sidebar + glass top bar
export function AdminLayout() {
+ const marketplaceEnabled = useMarketplaceEnabled();
const navigate = useNavigate();
@@ -260,7 +262,7 @@ export function AdminLayout() {
{!collapsed ? <div className="admin-nav-group-label">{group.label}</div> : null}
- {group.items.map((item) => (
+ {[...group.items, ...(group.label === "业务" && marketplaceEnabled ? [{ to: "/marketplace", label: "数字资产平台运营", icon: FileVideo } satisfies NavItem] : [])].map((item) => (
<NavLink
@@ -409,5 +411,3 @@ export function AdminLayout() {
);
}
-
-
diff --git a/admin/src/components/settings/OssSettingsPanel.tsx b/admin/src/components/settings/OssSettingsPanel.tsx
index 80678c5..93530a8 100644
--- a/admin/src/components/settings/OssSettingsPanel.tsx
+++ b/admin/src/components/settings/OssSettingsPanel.tsx
@@ -87,15 +87,21 @@ export function OssSettingsPanel() {
<SettingsPanel
className="settings-panel--compact"
title="1. 阿里云 OSS"
- description="生成文件先落本地,再异步上传 OSS"
+ description="原有生成业务与数字资产市场共用此处的 Bucket 和凭证"
>
<div className="settings-toggle-row">
<div>
<strong>启用 OSS</strong>
- <span>关闭后仅使用本地静态目录</span>
+ <span>关闭后原生成业务使用本地目录;数字资产市场文件上传与播放不可用</span>
</div>
<Switch checked={form.oss_enabled} onCheckedChange={(v) => patchField("oss_enabled", v)} />
</div>
+ <p className="mt-3 text-sm text-muted-foreground">
+ 数字资产市场固定使用 marketplace/ 目录,不受下方原业务目录设置影响。
+ 市场文件以私有权限上传,通过短时签名访问,不使用公开域名。
+ Bucket 须为私有且不得存在匿名 Allow 策略;此页保存配置不会自动修改 Bucket 权限。
+ “已就绪”仅表示配置完整,实际权限仍需云端验证。
+ </p>
<div className="settings-field-grid mt-3">
<LabeledControl label="Endpoint">
<input
diff --git a/admin/src/features/marketplace/CategoryForm.tsx b/admin/src/features/marketplace/CategoryForm.tsx
new file mode 100644
index 0000000..4138cad
--- /dev/null
+++ b/admin/src/features/marketplace/CategoryForm.tsx
@@ -0,0 +1,34 @@
+import { useEffect, useState, type FormEvent } from 'react'
+import { request } from './api'
+
+type Config = { version: number; names: string[] }
+
+export default function CategoryForm() {
+ const [config, setConfig] = useState<Config | null>(null)
+ const [text, setText] = useState('')
+ const [error, setError] = useState('')
+ const [message, setMessage] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [revision, setRevision] = useState(0)
+ useEffect(() => {
+ let active = true; setError(''); setConfig(null)
+ request<Config>('/api/admin/marketplace/categories').then(value => {
+ if (active) { setConfig(value); setText(value.names.join('\n')) }
+ }).catch(e => { if (active) setError(e.message) })
+ return () => { active = false }
+ }, [revision])
+ async function save(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault()
+ if (!config) return
+ const names = text.split(/\r?\n/).map(name => name.trim()).filter(Boolean)
+ if (!names.length || names.length > 30 || new Set(names).size !== names.length || names.some(name => name.length > 60)) {
+ setError('请填写1至30个不重复的分类,每个名称最多60字。'); return
+ }
+ setBusy(true); setError(''); setMessage('')
+ try {
+ const value = await request<Config>('/api/admin/marketplace/categories', 'PUT', { version: config.version, names })
+ setConfig(value); setText(value.names.join('\n')); setMessage('分类已保存,用户刷新广场及发布页后生效。')
+ } catch (e) { setError((e as Error).message) } finally { setBusy(false) }
+ }
+ return <form className="market-ops-support" onSubmit={save}><h2>作品分类配置</h2><p>发布页分类选项与作品广场分类标签共用此配置。每行一个分类,按行的顺序展示。</p><label>分类名称<textarea required rows={10} maxLength={1830} value={text} disabled={!config || busy} onChange={e => setText(e.target.value)} placeholder="短片&#10;广告&#10;动画" /></label><p>新增一行即可添加,调整行顺序即可排序。移除或改名仅影响后续选择与分类入口,历史作品分类不自动改写;编辑历史作品时可保留原分类。</p><div className="flex gap-3"><button type="submit" disabled={!config || busy}>{busy ? '保存中…' : '保存分类'}</button><button type="button" disabled={busy} onClick={() => { if (window.confirm('重新加载将丢弃未保存修改,继续吗?')) { setMessage(''); setRevision(v => v + 1) } }}>重新加载</button></div>{error && <p role="alert">{error}</p>}{message && <p role="status">{message}</p>}</form>
+}
diff --git a/admin/src/features/marketplace/MarketplaceAdmin.tsx b/admin/src/features/marketplace/MarketplaceAdmin.tsx
new file mode 100644
index 0000000..90f73e1
--- /dev/null
+++ b/admin/src/features/marketplace/MarketplaceAdmin.tsx
@@ -0,0 +1,190 @@
+import CategoryForm from './CategoryForm'
+import { useEffect, useState, type FormEvent } from 'react'
+import { request, assetUrl, useMarketplaceEnabled, type Item, type Listing } from './api'
+import { PaginationBar } from '@/components/PaginationBar'
+import { RefreshCw, Film, ShieldCheck, Users, Flag, CircleAlert, MessageCircle, Inbox } from 'lucide-react'
+import './marketplace-admin.css'
+
+// 独立下游运营工作台;不复用或改变原作品审核页。
+const businessTabs = { works: '作品审核', series: '短剧审核', recruits: '招募审核', reports: '举报处理', support: '客服配置', categories: '作品分类', revenue: '平台分成' }
+const maintenanceTabs = { previews: '作品试看任务', submissions: '历史投稿记录', jobs: '历史媒体任务', orders: '平台订单', entitlements: '永久播放权益', ledger: '收益账本', payouts: '人工打款', events: '操作记录' }
+const tabs = { ...businessTabs, ...maintenanceTabs }
+const statusNames: Record<string, string> = { preview_failed: '试看生成失败', original: '免费原片', missing: '未生成', running: '处理中', done: '已完成', draft: '草稿', pending: '待审核', approved: '已通过', rejected: '已驳回', ready: '已就绪', processing: '处理中', failed: '失败', open: '征集中', closed: '已关闭', expired: '已到期', pending_materials: '待材料', reviewing: '材料核验中', supplement: '待补正', applying: '办理中', certificated: '已取得证书', cancelled: '已取消', to_review: '待看', candidate: '候选', not_selected: '不采用', active: '有效权益', inactive: '已停用', printfilm: 'PrintFilm 生成', external: '其他平台生成', existing: '已有证书', self_service: '自行办理', assisted: '客服协办', free: '免费公开', copyright_contact: '联系客服购买版权', platform_unlock: '平台投放收益' }
+const names: Record<string, string> = { preview_status: '试看状态', preview_error: '试看错误', playback_status: '播放版本', playback_error: '播放错误', work_id: '作品编号', id: '编号', owner_id: '用户编号', user_id: '购买用户编号', asset_id: '媒体编号', publication_id: '发布版本编号', publication_version: '发布版本', episode_id: '分集编号', order_id: '订单编号', content_type: '内容类型', content_id: '内容编号', publication_owner_id: '创作者编号', active: '权益有效', version: '内容版本', title: '标题', description: '说明', price_fen: '参考价(分)', sale_type: '收费类型', copyright_price_fen: '版权参考价(分)', unlock_price_fen: '解锁价(分)', free_episode_count: '前置免费集数', episode_count: '分集数量', platform_share_bps: '平台分成(万分比)', share_bps: '单内容分成(万分比)', gross_fen: '订单金额(分)', platform_fen: '平台收益(分)', creator_fen: '创作者收益(分)', amount_fen: '金额(分)', budget_fen: '预算(分)', quote_fen: '报价(分)', category: '分类', source: '来源', source_type: '来源类型', source_snapshot: '导入来源快照', license_scope: '授权意向', audit_status: '内容审核', basic_status: '基础权属', full_status: '完整权属', reason: '审核原因', listed: '作者上架', blocked: '封禁', author: '作者', holder: '权利人', relationship: '发布人与权利人的关系', acquisition: '权利取得方式', scope: '授权范围', third_party: '第三方授权', institution: '登记机构', certificate_number: '证书号', ai_platform_license: 'AI平台许可', ai_generation_record: '生成记录', human_contribution: '人工贡献', official_reference: '申请编号', route: '办理方式', status: '状态', note: '备注', statement: '举报说明', contact: '联系渠道', resolution: '处理结果', target_type: '对象类型', target_id: '对象编号', requirements: '交付要求', wanted_count: '征集数量', deadline_at: '截止时间', valid_until: '授权截止', fingerprint: '文件指纹', filename: '文件名', selection: '筛选标记', withdrawn: '撤回', action: '操作', actor_id: '操作人', attempts: '尝试次数', error: '错误说明', media_status: '媒体状态', state: '业务状态', tags: '标签', authorization_id: '授权函编号', authorization_version: '授权条款版本', authorization_signer: '签署人' }
+
+// 按可读字段渲染审核材料,原片和证书另经鉴权打开。
+function Summary({ item }: { item: Item }) {
+ const details = typeof item.details === 'object' && item.details !== null ? item.details : {}
+ return <dl className="market-ops-summary">
+ {Object.entries(item).filter(([key, value]) => names[key] && !['basic_status', 'full_status', 'id', 'title', 'audit_status', 'status'].includes(key) && value !== null && value !== '').map(([key, value]) => <div key={key}><dt>{names[key]}</dt><dd>{typeof value === 'boolean' ? value ? '是' : '否' : ['price_fen', 'copyright_price_fen', 'unlock_price_fen', 'budget_fen', 'quote_fen', 'gross_fen', 'platform_fen', 'creator_fen', 'amount_fen'].includes(key) ? `¥${(Number(value) / 100).toFixed(2)}` : Array.isArray(value) ? value.join('、') || '—' : typeof value === 'object' ? JSON.stringify(value) : statusNames[String(value)] || String(value)}</dd></div>)}
+ {Object.entries(details).filter(([, value]) => value !== '' && value !== null && value !== undefined).map(([key, value]) => <div key={key}><dt>{key === 'dispute_ack' ? '版权声明已确认' : names[key] || key}</dt><dd>{typeof value === 'boolean' ? value ? '是' : '否' : statusNames[String(value)] || String(value)}</dd></div>)}
+ </dl>
+}
+
+// 直接从服务端签名,不将原始 OSS key 传到页面。
+function FileLink({ id, label, purpose = 'original', video = false }: { id: number; label: string; purpose?: string; video?: boolean }) {
+ const [url, setUrl] = useState(''); const [error, setError] = useState('')
+ return <div><button type="button" className="underline" onClick={async () => { try { setUrl(await assetUrl(id, purpose)); setError('') } catch (e) { setError((e as Error).message) } }}>{label} #{id}</button>{url && (video ? <video src={url} controls className="my-3 max-h-[500px] w-full" /> : <a className="ml-3 underline" href={url} target="_blank" rel="noreferrer">打开文件(链接5分钟有效)</a>)}{error && <p role="alert">{error}</p>}</div>
+}
+
+function WorkPreviewLink({ id }: { id: number }) {
+ const [url, setUrl] = useState(''); const [error, setError] = useState('')
+ return <div><button type="button" className="underline" onClick={async () => { try { setUrl((await request<{ url: string }>(`/api/marketplace/media/work/${id}/preview`)).url); setError('') } catch (e) { setError((e as Error).message) } }}>查看公众水印试看版</button>{url && <video src={url} controls className="my-3 max-h-[500px] w-full" />}{error && <p role="alert">{error}</p>}</div>
+}
+function AuthorizationLink({ details }: { details: unknown }) {
+ const [url, setUrl] = useState(''); const [error, setError] = useState('')
+ const id = details && typeof details === 'object' && 'authorization_id' in details ? Number(details.authorization_id) : 0
+ if (!id) return null
+ return <div><button type="button" className="underline" onClick={async () => { try { setUrl((await request<{ url: string }>(`/api/marketplace/authorizations/${id}/letter`)).url); setError('') } catch (e) { setError((e as Error).message) } }}>查看已签署 PrintFilm 授权函 #{id}</button>{url && <a href={url} target="_blank" rel="noreferrer"><img src={url} alt="已签署授权函" className="my-3 max-h-[600px] max-w-full object-contain" /></a>}{error && <p role="alert">{error}</p>}</div>
+}
+
+function PayoutStatusForm({ item, onSaved }: { item: Item; onSaved: () => void }) {
+ const [status, setStatus] = useState(String(item.status || 'pending'))
+ const [note, setNote] = useState(String(item.note || ''))
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ async function save(event: FormEvent<HTMLFormElement>) {
+ event.preventDefault(); setBusy(true); setError('')
+ try {
+ await request(`/api/admin/marketplace/payouts/${item.id}`, 'PATCH', { owner_id: Number(item.owner_id), amount_fen: Number(item.amount_fen), status, note })
+ onSaved()
+ } catch (e) { setError((e as Error).message) } finally { setBusy(false) }
+ }
+ return <form className="market-ops-inline-form" onSubmit={save}>
+ <label>打款状态<select value={status} onChange={event => setStatus(event.target.value)} disabled={status === 'paid'}><option value="pending">待结算</option><option value="paid">已打款</option><option value="failed">打款失败</option></select></label>
+ <label>备注<input value={note} maxLength={3000} onChange={event => setNote(event.target.value)} /></label>
+ <button type="submit" disabled={busy || status === String(item.status || '')}>{busy ? '保存中…' : '更新打款记录'}</button>
+ {error && <span role="alert">{error}</span>}
+ </form>
+}
+
+
+// 独立工作台含分页、错误态、敏感材料检查和明确原因输入。
+export default function MarketplaceAdmin() {
+ const enabled = useMarketplaceEnabled()
+ const [kind, setKind] = useState<keyof typeof tabs>('works')
+ const [listing, setListing] = useState<Listing | null>(null)
+ const [overview, setOverview] = useState<Record<string, number>>({})
+ const [page, setPage] = useState(1)
+ const [status, setStatus] = useState('')
+ const [error, setError] = useState('')
+ const [message, setMessage] = useState('')
+ const [loading, setLoading] = useState(false)
+ const [refresh, setRefresh] = useState(0)
+ const [maintenanceOpen, setMaintenanceOpen] = useState(false)
+ const [entitlementUserId, setEntitlementUserId] = useState('')
+ const [entitlementOwnerId, setEntitlementOwnerId] = useState('')
+ function navigateTab(next: keyof typeof tabs, nextStatus = '') {
+ if (next === 'jobs' || next === 'events' || next === 'previews' || next === 'submissions' || next === 'orders' || next === 'entitlements' || next === 'ledger' || next === 'payouts') setMaintenanceOpen(true)
+ setKind(next); setPage(1); setStatus(nextStatus); setListing(null); setError(''); setMessage('')
+ }
+ useEffect(() => {
+ if (!enabled || kind === 'support' || kind === 'categories' || kind === 'revenue') return
+ let active = true; setLoading(true); setError('')
+ const params = new URLSearchParams({ page: String(page), status })
+ if (kind === 'entitlements') { if (entitlementUserId) params.set('user_id', entitlementUserId); if (entitlementOwnerId) params.set('owner_id', entitlementOwnerId) }
+ request<Listing>(`/api/admin/marketplace/records/${kind}?${params}`).then(result => { if (active) setListing(result) }).catch(e => { if (active) setError(e.message) }).finally(() => { if (active) setLoading(false) })
+ request<Record<string, number>>('/api/admin/marketplace/overview').then(value => { if (active) setOverview(value) }).catch(() => {})
+ return () => { active = false }
+ }, [enabled, kind, page, status, refresh, entitlementUserId, entitlementOwnerId])
+ // 统一提交审核意图,后端始终重新核对版本与状态。
+ async function action(path: string, body: unknown) { setError(''); setMessage(''); try { await request(`/api/admin/marketplace${path}`, 'POST', body); setRefresh(v => v + 1); setMessage('操作成功') } catch (e) { setError((e as Error).message) } }
+ // 审核原因和逐项确认来自该记录的表单,不自动勾选。
+ function review(e: FormEvent<HTMLFormElement>, item: Item) {
+ e.preventDefault(); const form = new FormData(e.currentTarget); const submitter = (e.nativeEvent as SubmitEvent).submitter as HTMLButtonElement
+ void action(`/${kind}/${item.id}/review`, { version: item.version, decision: submitter.value, reason: form.get('reason'), checks: form.getAll('checks') })
+ }
+ if (!enabled) return <p>下游业务未启用,或无法读取服务状态。</p>
+ return <div className="market-ops">
+ <header className="market-ops-header"><div><div className="market-ops-eyebrow"><ShieldCheck size={15} /> 运营工作台</div><h1>数字资产平台运营</h1><p>集中处理作品、招募与版权审核,跟进举报及客服咨询。</p></div><button type="button" className="market-ops-refresh" onClick={() => setRefresh(v => v + 1)} disabled={loading}><RefreshCw size={16} className={loading ? 'animate-spin' : ''} />刷新数据</button></header>
+ <div className="market-ops-stats">{([
+ { key: 'works_pending', label: '待审作品', icon: Film, tab: 'works', tone: 'green' },
+ { key: 'recruits_pending', label: '待审招募', icon: Users, tab: 'recruits', tone: 'blue' },
+ { key: 'reports_pending', label: '待处理举报', icon: Flag, tab: 'reports', tone: 'amber' },
+ { key: 'jobs_failed', label: '失败媒体任务', icon: CircleAlert, tab: 'jobs', tone: 'red' },
+ ] as const).map(card => <button type="button" className={`market-ops-stat tone-${card.tone}`} key={card.key} onClick={() => navigateTab(card.tab, card.tab === 'jobs' ? 'failed' : 'pending')}><span className="market-ops-stat-icon"><card.icon size={20} /></span><span><span className="market-ops-stat-label">{card.label}</span><strong>{overview[card.key] ?? '—'}</strong></span><span className="market-ops-stat-arrow">↗</span></button>)}</div>
+ <div className="market-ops-context"><span><MessageCircle size={15} />累计咨询 <strong>{overview.consultations ?? '—'}</strong> 次</span><span>文件容量 <strong>{overview.storage_bytes === undefined ? '—' : `${(overview.storage_bytes / 1024 / 1024).toFixed(1)} MB`}</strong></span><span className="market-ops-context-note">合同、收款与交付由客服线下协调</span></div>
+ <nav className="market-ops-tabs" aria-label="数字资产运营业务">{Object.entries(businessTabs).map(([key, label]) => <button type="button" key={key} aria-current={kind === key ? 'page' : undefined} onClick={() => navigateTab(key as keyof typeof tabs)}>{label}</button>)}<button type="button" aria-expanded={maintenanceOpen} className="market-ops-maintenance-toggle" onClick={() => { if (maintenanceOpen && (kind === 'jobs' || kind === 'events' || kind === 'previews' || kind === 'submissions' || kind === 'orders' || kind === 'entitlements' || kind === 'ledger' || kind === 'payouts')) navigateTab('works'); setMaintenanceOpen(!maintenanceOpen) }}>运行维护 {maintenanceOpen ? '−' : '+'}</button></nav>
+ {maintenanceOpen && <div className="market-ops-maintenance"><div><strong>运行维护</strong><p>查看作品试看任务、订单权益、历史投稿及平台操作记录。招募接单由客服线下对接。</p></div><nav aria-label="运行维护">{Object.entries(maintenanceTabs).map(([key, label]) => <button type="button" key={key} aria-current={kind === key ? 'page' : undefined} onClick={() => navigateTab(key as keyof typeof tabs)}>{label}</button>)}</nav></div>}
+ {kind === 'jobs' && <p className="market-ops-feedback">此处仅保留旧版媒体任务,招募不再创建投稿或审片任务;付费作品的限时水印预览请查看“作品试看任务”。</p>}
+ {error && <p role="alert" className="market-ops-feedback is-error">{error}</p>}{message && <p role="status" className="market-ops-feedback">{message}</p>}
+ {kind === 'support' ? <SupportForm /> : kind === 'categories' ? <CategoryForm /> : kind === 'revenue' ? <RevenueConfigForm /> : <><div className="market-ops-filter"><div><h2>{tabs[kind]}</h2><span>{listing ? `共 ${listing.meta.total} 条记录` : '正在加载记录'}</span></div><select aria-label="状态筛选" className="rounded border bg-background p-2" value={status} onChange={e => { setStatus(e.target.value); setPage(1) }}><option value="">全部状态</option>{kind === 'entitlements' ? <><option value="active">有效权益</option><option value="inactive">已停用</option></> : Object.entries(statusNames).map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select>{kind === 'entitlements' && <div className="market-ops-entitlement-filter"><input aria-label="购买用户编号" type="number" min="1" placeholder="购买用户编号" value={entitlementUserId} onChange={e => { setEntitlementUserId(e.target.value); setPage(1) }} /><input aria-label="创作者编号" type="number" min="1" placeholder="创作者编号" value={entitlementOwnerId} onChange={e => { setEntitlementOwnerId(e.target.value); setPage(1) }} /></div>}<button type="button" onClick={() => setRefresh(v => v + 1)}>刷新</button></div>{kind === 'payouts' && <PayoutCreateForm onSaved={() => setRefresh(v => v + 1)} />}{loading ? <p role="status">正在加载…</p> : listing?.items.map(item => <article className="market-ops-record" key={`${kind}-${item.id}-${refresh}`}><header className="market-ops-record-head"><div><span className="market-ops-record-id">#{item.id} · {tabs[kind]}</span><h3>{String(item.title || item.filename || item.recruit_title || (kind === 'entitlements' ? `用户 #${item.user_id} 的永久权益` : '业务记录'))}</h3></div><span className={`market-ops-badge status-${String(item.audit_status || item.status || item.selection || (kind === 'entitlements' ? (item.active ? 'active' : 'inactive') : 'draft'))}`}>{statusNames[String(item.audit_status || item.status || item.selection || (kind === 'entitlements' ? (item.active ? 'active' : 'inactive') : 'draft'))] || (kind === 'entitlements' ? (item.active ? '有效' : '已停用') : String(item.status || '记录'))}</span></header><details className="market-ops-details" open={kind === 'works' || kind === 'recruits' || kind === 'series' || kind === 'entitlements'}><summary>作品资料与版权信息</summary><Summary item={item} /></details>
+ {kind === 'works' && item.sale_type !== 'free' && <WorkPreviewLink id={Number(item.id)} />}
+ {typeof item.asset_id === 'number' && <FileLink id={item.asset_id} label="视频预览" purpose="original" video />}
+ {kind === 'works' && typeof item.cover_asset_id === 'number' && <FileLink id={item.cover_asset_id} label="作品封面" />}{typeof item.certificate_asset_id === 'number' && <FileLink id={item.certificate_asset_id} label="权属证明/登记证书" />}
+ {Array.isArray(item.evidence_ids) && item.evidence_ids.map(id => <FileLink key={Number(id)} id={Number(id)} label="证明材料" />)}
+ {kind === 'series' && Array.isArray(item.episodes) && <div className="market-ops-episodes"><h4>分集材料</h4>{item.episodes.map((episode: Item) => <section key={episode.id}><strong>第 {String(episode.episode_no)} 集 · {String(episode.title || '')}</strong>{typeof episode.asset_id === 'number' && <FileLink id={episode.asset_id} label="分集视频" purpose="original" video />}{typeof episode.cover_asset_id === 'number' && <FileLink id={episode.cover_asset_id} label="分集封面" />}{typeof episode.certificate_asset_id === 'number' && <FileLink id={episode.certificate_asset_id} label="分集版权证明" />}{Array.isArray(episode.evidence_ids) && episode.evidence_ids.map(value => <FileLink key={Number(value)} id={Number(value)} label="分集证明材料" />)}<AuthorizationLink details={episode.details} /></section>)}</div>}
+ <AuthorizationLink details={item.details} />{kind === 'submissions' && <p>投稿快照:{JSON.stringify(item.snapshot)}</p>}
+ {((kind === 'recruits' || kind === 'series' || kind === 'works') && item.audit_status === 'pending') && <form className="market-ops-review" onSubmit={e => review(e, item)}><h3>审核处理</h3><p>查看内容和版权材料后,给出本次审核结论。</p>{(kind === 'works' || kind === 'series') && <div className="grid gap-3"><section><h3>内容检查</h3><label><input name="checks" value="content" type="checkbox" /> 已检查视频、封面、标题和简介</label></section><section><h3>版权检查</h3><label><input name="checks" value="copyright" type="checkbox" /> 已检查授权函或证书编号、证明材料及版权声明</label></section></div>}<label className="block">审核依据及原因<textarea name="reason" required maxLength={3000} className="block w-full rounded border bg-background p-2" /></label><div className="flex gap-3"><button type="submit" value="approved" className="market-ops-approve">通过该版本</button><button type="submit" value="rejected" className="market-ops-reject">驳回该版本</button></div></form>}
+ {kind === 'reports' && <form onSubmit={e => { e.preventDefault(); const form = new FormData(e.currentTarget); if (window.confirm('确认记录举报处理结果?')) void action(`/reports/${item.id}/resolve`, { resolution: form.get('resolution') }) }}><textarea name="resolution" aria-label="处理结果" required maxLength={3000} className="block w-full rounded border bg-background p-2" /><button type="submit">记录处理结果</button><button type="button" onClick={() => { const reason = window.prompt('临时限制该举报对象的依据和原因'); if (reason) void action(`/block/${item.target_type}/${item.target_id}`, { blocked: true, reason }) }}>临时限制举报对象</button></form>}
+ {kind === 'payouts' && <PayoutStatusForm item={item} onSaved={() => setRefresh(v => v + 1)} />}
+ {['works', 'recruits', 'submissions'].includes(kind) && <button type="button" onClick={() => { const reason = window.prompt(`${item.blocked ? '解除限制' : '限制播放和咨询'}的原因`); if (reason) void action(`/block/${({ works: 'work', recruits: 'recruit', submissions: 'submission' } as Record<string, string>)[kind]}/${item.id}`, { blocked: !item.blocked, reason }) }}>{item.blocked ? '解除限制(不自动上架)' : '封禁/临时下架'}</button>}
+ </article>)}{!loading && !error && listing?.items.length === 0 && <div className="market-ops-empty"><Inbox size={36} /><h3>暂无{tabs[kind]}记录</h3><p>新的业务记录会显示在这里,可切换状态查看。</p></div>}{listing && <PaginationBar page={page} pageSize={listing.meta.page_size} total={listing.meta.total} onPageChange={setPage} />}</>}
+ </div>
+}
+
+// 二维码同样必须走独立 OSS;无配置时清晰报错,不生成假图片。
+function SupportForm() {
+ const [settings, setSettings] = useState<Item | null>(null)
+ const [qr, setQr] = useState<number | null>(null)
+ const [message, setMessage] = useState('')
+ const [busy, setBusy] = useState(false)
+ useEffect(() => { request<Item>('/api/admin/marketplace/support').then(value => { setSettings(value); setQr(typeof value.qr_asset_id === 'number' ? value.qr_asset_id : null) }).catch(e => setMessage(e.message)) }, [])
+ // 小二维码也使用同一分片协议,上传完成后需要 Worker 校验。
+ async function uploadQr(file?: File) {
+ if (!file) return; setBusy(true)
+ try {
+ const session = await request<{ id: number; asset_id: number; part_size: number }>('/api/marketplace/uploads', 'POST', { filename: file.name, size_bytes: file.size, kind: 'qr' })
+ for (let start = 0, number = 1; start < file.size; start += session.part_size, number++) await request(`/api/marketplace/uploads/${session.id}/parts/${number}`, 'PUT', file.slice(start, start + session.part_size))
+ await request(`/api/marketplace/uploads/${session.id}/complete`, 'POST'); setQr(session.asset_id); setMessage('二维码上传完成,请保存客服配置。')
+ } catch (e) { setMessage((e as Error).message) } finally { setBusy(false) }
+ }
+ // 后台保存仍校验二维码属于管理员且状态 ready。
+ async function save(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault(); const form = new FormData(e.currentTarget); setBusy(true)
+ try { await request('/api/admin/marketplace/support', 'PUT', { name: form.get('name'), wechat: form.get('wechat'), hours: form.get('hours'), enabled: form.get('enabled') === 'on', qr_asset_id: qr }); setMessage('客服配置已保存') } catch (e) { setMessage((e as Error).message) } finally { setBusy(false) }
+ }
+ if (!settings) return <p>{message || '正在加载客服配置…'}</p>
+ return <form className="market-ops-support" onSubmit={save}><label className="block">客服名称<input name="name" required maxLength={80} defaultValue={String(settings.name ?? '平台客服')} className="block w-full rounded border bg-background p-2" /></label><label className="block">微信号<input name="wechat" maxLength={100} defaultValue={String(settings.wechat ?? '')} className="block w-full rounded border bg-background p-2" /></label><label className="block">服务时间<input name="hours" maxLength={100} defaultValue={String(settings.hours ?? '')} className="block w-full rounded border bg-background p-2" /></label><label className="block">上传真实客服二维码<input type="file" accept=".png,.jpg,.jpeg,.webp" disabled={busy} onChange={e => uploadQr(e.target.files?.[0])} /></label><p>二维码文件编号:{qr ?? '未设置'}</p>{qr && <FileLink id={qr} label="检查二维码" />}<label className="block"><input name="enabled" type="checkbox" defaultChecked={Boolean(settings.enabled)} /> 启用平台客服</label><button type="submit" disabled={busy}>保存客服配置</button><p role="status">{message}</p></form>
+}
+
+function RevenueConfigForm() {
+ const [value, setValue] = useState<Item | null>(null)
+ const [share, setShare] = useState('')
+ const [enabled, setEnabled] = useState(false)
+ const [message, setMessage] = useState('正在加载平台分成配置…')
+ const [busy, setBusy] = useState(false)
+ useEffect(() => { request<Item>('/api/admin/marketplace/revenue-config').then(item => { setValue(item); setShare(String(item.platform_share_bps ?? '')); setEnabled(Boolean(item.enabled)); setMessage('') }).catch(e => setMessage(e.message)) }, [])
+ async function save(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault(); setBusy(true); setMessage('')
+ try {
+ const bps = Number(share)
+ if (!Number.isInteger(bps) || bps < 0 || bps > 10000) throw new Error('平台分成必须是 0 至 10000 的整数(万分比)')
+ const result = await request<Item>('/api/admin/marketplace/revenue-config', 'PUT', { version: value?.version ?? 0, platform_share_bps: bps, enabled })
+ setValue(result); setMessage('平台分成配置已保存;未配置前不能提交平台投放作品。')
+ } catch (e) { setMessage((e as Error).message) } finally { setBusy(false) }
+ }
+ return <form className="market-ops-support" onSubmit={save}><h2>平台投放收益分成</h2><p>按万分比填写平台抽成,例如 2000 表示平台 20%,创作者自动获得剩余 80%。每个作品可以单独覆盖此默认比例。</p><label className="block">平台分成(万分比)<input type="number" min="0" max="10000" step="1" value={share} onChange={e => setShare(e.target.value)} required className="block w-full rounded border bg-background p-2" /></label><label className="block"><input type="checkbox" checked={enabled} onChange={e => setEnabled(e.target.checked)} /> 启用平台投放收益</label><button type="submit" disabled={busy || !value}>{busy ? '保存中…' : '保存配置'}</button><p role="status">{message}</p></form>
+}
+
+function PayoutCreateForm({ onSaved }: { onSaved: () => void }) {
+ const [message, setMessage] = useState('')
+ const [busy, setBusy] = useState(false)
+ async function save(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault(); setBusy(true); setMessage('')
+ const formElement = e.currentTarget; const form = new FormData(formElement)
+ try {
+ await request('/api/admin/marketplace/payouts', 'POST', { owner_id: Number(form.get('owner_id')), amount_fen: Math.round(Number(form.get('amount')) * 100), status: form.get('status'), note: form.get('note') })
+ formElement.reset(); setMessage('打款记录已保存'); onSaved()
+ } catch (err) { setMessage((err as Error).message) } finally { setBusy(false) }
+ }
+ return <form className="market-ops-support" onSubmit={save}><h3>记录人工打款</h3><div className="pf-market-field-row"><label>创作者用户编号<input name="owner_id" type="number" min="1" required /></label><label>金额(元)<input name="amount" type="number" min="0.01" step="0.01" required /></label></div><label>状态<select name="status" defaultValue="paid"><option value="pending">待结算</option><option value="paid">已打款</option><option value="failed">打款失败</option></select></label><label>备注<textarea name="note" maxLength={3000} /></label><button type="submit" disabled={busy}>{busy ? '保存中…' : '保存打款记录'}</button><p role="status">{message}</p></form>
+}
+
+
+
+
+
+
+
+
diff --git a/admin/src/features/marketplace/api.ts b/admin/src/features/marketplace/api.ts
new file mode 100644
index 0000000..2a1ff44
--- /dev/null
+++ b/admin/src/features/marketplace/api.ts
@@ -0,0 +1,25 @@
+import { useEffect, useState } from 'react'
+import { getToken } from '@/lib/auth'
+
+export type Item = { id: number; version?: number; [key: string]: unknown }
+export type Listing = { items: Item[]; meta: { page: number; page_size: number; total: number } }
+
+// 管理端使用原管理员 token,但下游 API 完全隔离。
+export async function request<T>(path: string, method = 'GET', body?: unknown): Promise<T> {
+ const response = await fetch(path, { method, headers: { Authorization: `Bearer ${getToken() ?? ''}`, ...(body !== undefined ? { 'Content-Type': body instanceof Blob ? 'application/octet-stream' : 'application/json' } : {}) }, body: body === undefined ? undefined : body instanceof Blob ? body : JSON.stringify(body) })
+ const value = await response.json().catch(() => ({}))
+ if (!response.ok) throw new Error(typeof value.detail === 'string' ? value.detail : value.detail?.message || '请求失败,请检查输入与登录状态')
+ return value as T
+}
+
+// 管理端菜单也由服务端能力发现控制,不另造前端开关。
+export function useMarketplaceEnabled() {
+ const [enabled, setEnabled] = useState(false)
+ useEffect(() => { let active = true; request<{ enabled: boolean }>('/api/marketplace/capabilities').then(value => { if (active) setEnabled(value.enabled) }).catch(() => {}); return () => { active = false } }, [])
+ return enabled
+}
+
+// 管理员签名必须走原身份鉴权,不拼接 OSS 地址。
+export async function assetUrl(id: number, purpose = 'original') {
+ return (await request<{ url: string }>(`/api/marketplace/media/asset/${id}/${purpose}`)).url
+}
diff --git a/admin/src/features/marketplace/marketplace-admin.css b/admin/src/features/marketplace/marketplace-admin.css
new file mode 100644
index 0000000..2cb358a
--- /dev/null
+++ b/admin/src/features/marketplace/marketplace-admin.css
@@ -0,0 +1,86 @@
+/* Scoped to the digital asset operations page. */
+.market-ops { --ops-accent:#27624e; --ops-line:#e3e9e5; color:#24332b; display:flex; flex-direction:column; gap:20px; max-width:1480px; margin:0 auto; width:100%; }
+.market-ops-header { display:flex; justify-content:space-between; align-items:center; gap:20px; padding:8px 0; }
+.market-ops-eyebrow { display:flex; gap:7px; align-items:center; color:var(--ops-accent); font-size:12px; font-weight:600; margin-bottom:8px; }
+.market-ops-header h1 { font-size:26px; font-weight:700; letter-spacing:-.6px; margin:0 0 8px; }
+.market-ops-header p,.market-ops-review>p { color:#7b8980; font-size:13px; margin:0; }
+.market-ops button { cursor:pointer; transition:background .15s,border-color .15s; }
+.market-ops button:disabled { opacity:.45; cursor:not-allowed; }
+.market-ops button:focus-visible,.market-ops select:focus-visible,.market-ops textarea:focus-visible { outline:2px solid #559278; outline-offset:3px; }
+.market-ops-refresh { display:inline-flex; align-items:center; justify-content:center; gap:8px; white-space:nowrap; padding:10px 16px; background:white; border:1px solid var(--ops-line); border-radius:9px; font-size:13px; }
+.market-ops-stats { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:16px; }
+.market-ops-stat { display:flex; text-align:left; align-items:center; gap:15px; border:1px solid var(--ops-line); border-radius:12px; background:#fff; padding:21px; min-width:0; box-shadow:0 2px 4px #203d2910; }
+.market-ops-stat:hover { border-color:#90b59f; background:#fcfefc; }
+.market-ops-stat-icon { display:grid; place-items:center; background:#edf6ef; color:#28674e; width:44px; height:44px; border-radius:12px; flex-shrink:0; }
+.market-ops-stat.tone-blue .market-ops-stat-icon { background:#eef3fc; color:#537bb4; }
+.market-ops-stat.tone-amber .market-ops-stat-icon { background:#fff6e8; color:#bb8733; }
+.market-ops-stat.tone-red .market-ops-stat-icon { background:#fff0ee; color:#bd6760; }
+.market-ops-stat-label { display:block; color:#7b8980; font-size:12px; margin-bottom:8px; }
+.market-ops-stat strong { display:block; font-size:28px; line-height:1; font-weight:650; font-variant-numeric:tabular-nums; }
+.market-ops-stat-arrow { margin-left:auto; color:#a3afa7; }
+.market-ops-context { display:flex; align-items:center; flex-wrap:wrap; gap:22px; color:#7b8980; font-size:12px; padding:0 3px; }
+.market-ops-context span { display:inline-flex; align-items:center; gap:7px; }
+.market-ops-context strong { color:#41564a; font-weight:600; }
+.market-ops-context-note { margin-left:auto; }
+.market-ops-tabs { display:flex; overflow-x:auto; gap:4px; border-bottom:1px solid var(--ops-line); padding:0 4px; background:#fff; border-radius:10px 10px 0 0; }
+.market-ops-tabs button { flex-shrink:0; padding:16px 14px; border-bottom:3px solid transparent; color:#7b8980; font-size:13px; }
+.market-ops-tabs button[aria-current="page"] { color:var(--ops-accent); border-color:var(--ops-accent); font-weight:650; background:linear-gradient(transparent,#f3f8f4); }
+.market-ops-filter { display:flex; align-items:center; gap:12px; }
+.market-ops-filter>div { margin-right:auto; display:flex; align-items:center; gap:14px; }
+.market-ops-filter h2 { font-size:16px; font-weight:650; margin:0; }
+.market-ops-filter span { font-size:12px; color:#89948e; }
+.market-ops-filter select { min-width:145px; font-size:13px; border-color:var(--ops-line); }
+.market-ops-filter>button { border:1px solid var(--ops-line); padding:9px 14px; border-radius:7px; background:white; font-size:13px; }
+.market-ops-entitlement-filter { display:flex; gap:8px; }
+.market-ops-entitlement-filter input { width:145px; padding:8px 10px; border:1px solid var(--ops-line); border-radius:7px; font-size:13px; }
+.market-ops-record { background:white; border:1px solid var(--ops-line); border-radius:12px; overflow:hidden; padding:24px; margin-bottom:16px; display:flex; flex-direction:column; gap:18px; }
+.market-ops-record-head { display:flex; align-items:center; justify-content:space-between; gap:20px; padding-bottom:18px; border-bottom:1px solid #eef2ef; }
+.market-ops-record-id { color:#8a988f; font-size:11px; }
+.market-ops-record-head h3 { font-size:17px; font-weight:650; margin:6px 0 0; }
+.market-ops-badge { flex-shrink:0; padding:5px 11px; border-radius:6px; background:#f0f3f1; color:#7a897f; font-size:12px; }
+.market-ops-badge.status-pending { color:#a77524; background:#fff7e6; }
+.market-ops-badge.status-approved,.market-ops-badge.status-ready { color:#377357; background:#ebf5ed; }
+.market-ops-badge.status-rejected,.market-ops-badge.status-failed { color:#b15d55; background:#fcefee; }
+.market-ops-details>summary { font-size:13px; font-weight:600; cursor:pointer; padding:5px 0 12px; }
+.market-ops-summary { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:0 28px; font-size:13px; }
+.market-ops-summary>div { display:grid; grid-template-columns:110px minmax(0,1fr); gap:14px; padding:10px 0; border-bottom:1px solid #f1f4f2; }
+.market-ops-summary dt { color:#89978e; }
+.market-ops-summary dd { margin:0; overflow-wrap:anywhere; white-space:pre-wrap; line-height:1.6; }
+.market-ops-record video { border-radius:8px; background:#18231c; }
+.market-ops-record button.underline { color:var(--ops-accent); font-size:13px; text-underline-offset:4px; }
+.market-ops-review { display:flex; flex-direction:column; gap:16px; background:#f8faf8; padding:22px; border:1px solid #e7eee8; border-radius:10px; }
+.market-ops-review h3 { margin:0; font-size:14px; font-weight:650; }
+.market-ops-review section { padding:14px; background:#fff; border:1px solid var(--ops-line); border-radius:8px; }
+.market-ops-review section h3 { margin-bottom:12px; color:#536e5e; font-size:12px; }
+.market-ops-review label { font-size:13px; color:#617567; }
+.market-ops-review input[type="checkbox"],.market-ops-support input[type="checkbox"] { accent-color:var(--ops-accent); margin-right:7px; }
+.market-ops-review textarea { margin-top:9px; min-height:90px; border-color:#dce5de; font-size:13px; resize:vertical; }
+.market-ops-approve { padding:10px 22px; border-radius:7px; background:var(--ops-accent); color:white; font-size:13px; }
+.market-ops-reject { padding:10px 22px; border-radius:7px; border:1px solid #e5cac6; background:white; color:#a15c54; font-size:13px; }
+.market-ops-approve:hover { background:#1c4b3b; }
+.market-ops-empty { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:12px; min-height:280px; background:#fff; border:1px dashed #dbe5df; border-radius:12px; color:#9aafa0; }
+.market-ops-empty h3 { color:#5d7566; font-size:15px; font-weight:600; }
+.market-ops-empty p { color:#8b9a91; font-size:13px; }
+.market-ops-feedback { background:#edf6ef; color:#356849; border:1px solid #d6e7da; padding:12px 16px; border-radius:8px; font-size:13px; }
+.market-ops-feedback.is-error { background:#fff2ef; color:#a44d43; border-color:#f0d7d2; }
+.market-ops-support { background:white; border:1px solid var(--ops-line); border-radius:12px; padding:28px; display:grid; gap:22px; max-width:860px; }
+.market-ops-support label { font-size:13px; color:#617567; }
+.market-ops-support input:not([type="checkbox"]) { margin-top:8px; padding:11px; border-radius:7px; border:1px solid var(--ops-line); width:100%; }
+.market-ops-support>button[type="submit"] { background:var(--ops-accent); color:#fff; border-radius:7px; padding:11px 20px; justify-self:start; }
+.market-ops-inline-form { display:flex; flex-wrap:wrap; align-items:flex-end; gap:12px; padding:14px; border:1px solid var(--ops-line); border-radius:8px; background:#f8faf8; }
+.market-ops-inline-form label { display:flex; flex-direction:column; gap:6px; color:#617567; font-size:12px; }
+.market-ops-inline-form input,.market-ops-inline-form select { min-width:150px; padding:8px 10px; border:1px solid var(--ops-line); border-radius:6px; background:#fff; font-size:13px; }
+.market-ops-inline-form button { padding:9px 14px; border-radius:7px; background:var(--ops-accent); color:#fff; font-size:13px; }
+.market-ops-inline-form [role="alert"] { color:#a44d43; font-size:12px; }
+@media(min-width:1100px) { .market-ops-review>.grid { grid-template-columns:1fr 1fr; } }
+@media(max-width:900px) { .market-ops-stats { grid-template-columns:repeat(2,minmax(0,1fr)); } .market-ops-summary { grid-template-columns:1fr; } .market-ops-context-note { margin-left:0; } }
+@media(max-width:540px) { .market-ops-header { align-items:flex-start; } .market-ops-header h1 { font-size:21px; } .market-ops-stat { padding:14px; gap:10px; } .market-ops-stat-icon { width:33px; height:33px; } .market-ops-stat strong { font-size:24px; } .market-ops-record { padding:16px; } .market-ops-filter { flex-wrap:wrap; } .market-ops-filter>div { width:100%; } .market-ops-summary>div { grid-template-columns:85px minmax(0,1fr); } .market-ops-review { padding:15px; } }
+.market-ops-tabs .market-ops-maintenance-toggle { margin-left:auto; color:#7c8a82; }
+.market-ops-tabs .market-ops-maintenance-toggle[aria-expanded="true"] { color:var(--ops-accent); background:#f2f7f3; }
+.market-ops-maintenance { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:18px 22px; border:1px solid var(--ops-line); border-radius:10px; background:#f6f8f6; }
+.market-ops-maintenance strong { font-size:13px; font-weight:600; }
+.market-ops-maintenance p { margin:5px 0 0; color:#859389; font-size:12px; }
+.market-ops-maintenance nav { display:flex; gap:8px; }
+.market-ops-maintenance button { padding:9px 15px; border:1px solid var(--ops-line); background:#fff; border-radius:7px; font-size:13px; white-space:nowrap; }
+.market-ops-maintenance button[aria-current="page"] { background:var(--ops-accent); border-color:var(--ops-accent); color:#fff; }
+@media(max-width:600px) { .market-ops-maintenance { flex-direction:column; align-items:flex-start; } }
diff --git a/backend/.env.marketplace.example b/backend/.env.marketplace.example
new file mode 100644
index 0000000..fba50fe
--- /dev/null
+++ b/backend/.env.marketplace.example
@@ -0,0 +1,13 @@
+# 下游默认关闭。仅作配置说明,不包含真实凭证,也不改变上游 OSS_*。
+MARKETPLACE_ENABLED=false
+# OSS 共用后台「系统设置 → 存储 OSS」配置,无需 MARKETPLACE_OSS_*。
+# 数字资产市场固定使用 marketplace/;原业务 OSS_FOLDER 保持原意。
+MARKETPLACE_SIGNED_URL_SECONDS=300
+MARKETPLACE_MAX_VIDEO_BYTES=524288000
+MARKETPLACE_MAX_DOCUMENT_BYTES=20971520
+MARKETPLACE_MAX_DURATION_SECONDS=1800
+MARKETPLACE_PART_SIZE=8388608
+# Windows 本机默认字体;Linux 部署须设置实际安装的中文字体绝对路径。
+MARKETPLACE_WATERMARK_FONT=C:/Windows/Fonts/msyh.ttc
+MARKETPLACE_WORKER_POLL_SECONDS=3
+MARKETPLACE_WORKER_MAX_ATTEMPTS=3
diff --git a/backend/app/main.py b/backend/app/main.py
index 9cd3497..1da1c91 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -93,6 +93,10 @@ app.include_router(v1_router, prefix="/api")
app.include_router(drama_router, prefix="/api")
app.include_router(admin_router, prefix="/api")
+# 下游扩展仅注册独立路由和初始化,不改变原发布、生成及存储逻辑。
+from app.marketplace.bootstrap import install as install_marketplace
+install_marketplace(app)
+
@app.on_event("startup")
async def on_startup() -> None:
@@ -112,6 +116,13 @@ async def on_startup() -> None:
except Exception: # noqa: BLE001
pass
await start_task_runtime()
+ from app.marketplace.config import get_marketplace_settings
+ if get_marketplace_settings().enabled:
+ # 市场启动回调早于本函数里的补列,免费内容下架必须等列补齐后再查系列表。
+ from app.marketplace.previews import withdraw_unwatermarked_public
+ async with AsyncSessionLocal() as db:
+ await withdraw_unwatermarked_public(db)
+ await db.commit()
@app.on_event("shutdown")
@@ -138,6 +149,11 @@ async def _pg_columns(conn, table: str) -> set[str]:
async def _apply_schema_patches() -> None:
"""Lightweight additive migrations(仅 PostgreSQL)。"""
async with engine.begin() as conn:
+ # Local unit tests may use SQLite, while production uses PostgreSQL. The
+ # information_schema queries and ALTER TABLE syntax below are deliberately
+ # PostgreSQL-only; create_all() already handles a fresh SQLite database.
+ if conn.dialect.name != "postgresql":
+ return
scols = await _pg_columns(conn, "shots")
if "segment_script" not in scols:
await conn.execute(text("ALTER TABLE shots ADD COLUMN segment_script TEXT DEFAULT ''"))
@@ -248,6 +264,60 @@ async def _apply_schema_patches() -> None:
await conn.execute(text(f"DROP INDEX IF EXISTS ix_task_runs_{col}"))
await conn.execute(text(f"ALTER TABLE task_runs DROP COLUMN {col}"))
+ # Marketplace additive columns. The marketplace bootstrap creates new tables;
+ # these columns keep existing work drafts compatible with the new sale modes.
+ mcols = await _pg_columns(conn, "marketplace_works")
+ if mcols:
+ if "sale_type" not in mcols:
+ await conn.execute(text("ALTER TABLE marketplace_works ADD COLUMN sale_type VARCHAR(24) DEFAULT 'copyright_contact'"))
+ if "unlock_price_fen" not in mcols:
+ await conn.execute(text("ALTER TABLE marketplace_works ADD COLUMN unlock_price_fen BIGINT DEFAULT 0"))
+ if "share_bps" not in mcols:
+ await conn.execute(text("ALTER TABLE marketplace_works ADD COLUMN share_bps INTEGER"))
+
+ # The marketplace tables are intentionally created from their own metadata,
+ # but create_all() does not alter tables from an earlier deployment. Keep
+ # upgrades additive and idempotent so a server can be restarted against an
+ # existing database without a manual migration step. Defaults make these
+ # additions safe for historical rows; newly written records still use the
+ # ORM defaults and publication snapshots remain immutable.
+ marketplace_columns: dict[str, dict[str, str]] = {
+ "marketplace_series": {
+ "sale_type": "VARCHAR(24) DEFAULT 'copyright_contact'",
+ "copyright_price_fen": "BIGINT DEFAULT 0",
+ "share_bps": "INTEGER",
+ "free_episode_count": "INTEGER NOT NULL DEFAULT 0",
+ },
+ "marketplace_series_episodes": {
+ "source": "VARCHAR(30) NOT NULL DEFAULT 'external'",
+ "preview_status": "VARCHAR(24) DEFAULT 'none'",
+ "preview_key": "VARCHAR(512)",
+ "preview_attempts": "INTEGER DEFAULT 0",
+ "playback_status": "VARCHAR(24) DEFAULT 'none'",
+ "playback_manifest_key": "VARCHAR(512)",
+ "playback_attempts": "INTEGER DEFAULT 0",
+ },
+ "marketplace_publications": {
+ "preview_key": "VARCHAR(512)",
+ "preview_status": "VARCHAR(24) DEFAULT 'pending'",
+ "preview_attempts": "INTEGER DEFAULT 0",
+ "preview_error": "TEXT DEFAULT ''",
+ "playback_manifest_key": "VARCHAR(512)",
+ "playback_status": "VARCHAR(24) DEFAULT 'pending'",
+ "playback_attempts": "INTEGER DEFAULT 0",
+ "playback_error": "TEXT DEFAULT ''",
+ },
+ }
+ for table, additions in marketplace_columns.items():
+ columns = await _pg_columns(conn, table)
+ # A missing table is expected on a first boot before marketplace's
+ # startup handler runs create_all(); simply let that handler create it.
+ if not columns:
+ continue
+ for column, definition in additions.items():
+ if column not in columns:
+ await conn.execute(text(f"ALTER TABLE {table} ADD COLUMN {column} {definition}"))
+
async def bootstrap_admins() -> None:
# Promote matching emails to admin (does not create users)
diff --git a/backend/app/marketplace/__init__.py b/backend/app/marketplace/__init__.py
new file mode 100644
index 0000000..9f23556
--- /dev/null
+++ b/backend/app/marketplace/__init__.py
@@ -0,0 +1 @@
+"""独立下游模块;不接管上游作品、生成任务和存储。"""
diff --git a/backend/app/marketplace/admin.py b/backend/app/marketplace/admin.py
new file mode 100644
index 0000000..d3d25cc
--- /dev/null
+++ b/backend/app/marketplace/admin.py
@@ -0,0 +1,418 @@
+"""下游运营 API;审核只操作独立记录,并强制版本匹配。"""
+from fastapi import APIRouter, Query
+from sqlalchemy import func, select
+
+from .dependencies import Admin, DB
+from .models import Asset, EpisodePreview, Entitlement, Event, MediaJob, Publication, Recruit, RegistrationCase, Report, RevenueConfig, RevenueLedger, Payout, Rights, Series, SeriesEpisode, Submission, Support, Work, WorkPreview
+from .schemas import BlockInput, CaseReview, CategoryInput, PayoutInput, ResolutionInput, ReviewInput, RevenueConfigInput, SupportInput, Version
+from .service import (asset_owned, check_version, data, event, fail, now, notify, page, recruit_data,
+ rights_for, rights_valid, submission_data, validate_rights, work_data)
+
+router = APIRouter()
+
+
[email protected]("/categories", response_model=dict)
+async def get_categories(db: DB, user: Admin):
+ from .categories import category_config
+ return await category_config(db)
+
+
[email protected]("/categories", response_model=dict)
+async def save_categories(body: CategoryInput, db: DB, user: Admin):
+ from sqlalchemy import text
+ from .models import CategoryConfig
+ # 首次保存也串行化,避免两个管理员同时创建配置。
+ await db.execute(text("SELECT pg_advisory_xact_lock(18427, 73103)"))
+ item = await db.get(CategoryConfig, 1, with_for_update=True)
+ if body.version != (item.version if item else 0):
+ fail("分类配置已被修改,请重新加载后保存", 409)
+ if item is None:
+ item = CategoryConfig(id=1, version=0, names=[])
+ db.add(item)
+ item.names, item.version = body.names, item.version + 1
+ event(db, user.id, "categories", 1, "updated", version=item.version)
+ await db.commit()
+ return {"names": item.names, "version": item.version}
+
+
+MODELS = {"works": Work, "rights": Rights, "cases": RegistrationCase, "recruits": Recruit,
+ "submissions": Submission, "reports": Report, "jobs": MediaJob, "events": Event, "previews": WorkPreview,
+ "series": Series, "episodes": SeriesEpisode, "orders": __import__("app.marketplace.models", fromlist=["ContentOrder"]).ContentOrder,
+ "ledger": RevenueLedger, "payouts": Payout, "entitlements": Entitlement}
+
+
[email protected]("/overview", response_model=dict)
+async def overview(db: DB, user: Admin):
+ """运营计数不把咨询、候选或扫码计为成交。"""
+ counts = {}
+ for name, model, condition in (("works_pending", Work, Work.audit_status == "pending"),
+ ("rights_pending", Rights, (Rights.basic_status == "pending") | (Rights.full_status == "pending")),
+ ("recruits_pending", Recruit, Recruit.audit_status == "pending"),
+ ("jobs_failed", MediaJob, MediaJob.status == "failed"),
+ ("reports_pending", Report, Report.status == "pending")):
+ counts[name] = (await db.execute(select(func.count()).select_from(model).where(condition))).scalar_one()
+ counts["storage_bytes"] = (await db.execute(select(func.coalesce(func.sum(Asset.size_bytes), 0)))).scalar_one()
+ counts["consultations"] = (await db.execute(select(func.count()).select_from(Event).where(Event.action == "consultation"))).scalar_one()
+ return counts
+
+
[email protected]("/records/{kind}", response_model=dict)
+async def records(kind: str, db: DB, user: Admin, status: str = "", user_id: int | None = Query(None, ge=1), owner_id: int | None = Query(None, ge=1), page_number: int = Query(1, alias="page", ge=1), page_size: int = Query(20, ge=1, le=100)):
+ """管理员分页工作台;敏感材料在单独鉴权接口读取。"""
+ model = MODELS.get(kind)
+ if not model:
+ fail("记录类型无效", 404)
+ query = select(model)
+ field = getattr(model, "audit_status", None) if kind in ("works", "recruits", "series") else getattr(model, "status", None)
+ if status and field is not None:
+ query = query.where(field == status)
+ if kind == "rights" and status:
+ query = query.where((Rights.basic_status == status) | (Rights.full_status == status))
+ if kind == "rights":
+ # 作品版权随作品统一审核,这里只保留独立投稿的审核记录。
+ query = query.where(~select(Work.id).where(Work.asset_id == Rights.asset_id).exists())
+ if kind == "entitlements":
+ if user_id is not None:
+ query = query.where(Entitlement.user_id == user_id)
+ if status in ("active", "inactive"):
+ query = query.where(Entitlement.active.is_(status == "active"))
+ if owner_id is not None:
+ query = query.join(Publication, Publication.id == Entitlement.publication_id).where(Publication.owner_id == owner_id)
+ rows, meta = await page(db, query.order_by(model.id.desc()), page_number, page_size)
+ items = []
+ for item in rows:
+ if kind == "works":
+ result = await work_data(db, item, True)
+ rights = await rights_for(db, item.asset_id)
+ if rights:
+ result.update(details=rights.details, certificate_asset_id=rights.certificate_asset_id,
+ evidence_ids=rights.evidence_ids)
+ elif kind == "recruits":
+ result = await recruit_data(db, item, True)
+ elif kind == "series":
+ result = data(item, *[column.name for column in model.__table__.columns])
+ episodes = list((await db.execute(select(SeriesEpisode).where(SeriesEpisode.series_id == item.id).order_by(SeriesEpisode.episode_no))).scalars().all())
+ result["episodes"] = []
+ for episode in episodes:
+ rights = (await db.execute(select(Rights).where(Rights.asset_id == episode.asset_id))).scalar_one_or_none() if episode.asset_id else None
+ result["episodes"].append({**data(episode, "id", "episode_no", "title", "description", "asset_id", "cover_asset_id", "source", "source_type", "version", "audit_status", "listed", "preview_status", "playback_status"), **({"details": rights.details, "certificate_asset_id": rights.certificate_asset_id, "evidence_ids": rights.evidence_ids} if rights else {})})
+ elif kind == "submissions":
+ result = await submission_data(db, item, user)
+ elif kind == "entitlements":
+ publication = await db.get(Publication, item.publication_id)
+ result = data(item, "id", "user_id", "publication_id", "episode_id", "order_id", "active", "created_at")
+ if publication:
+ result.update(content_type=publication.content_type, content_id=publication.content_id,
+ publication_version=publication.version, publication_owner_id=publication.owner_id,
+ sale_type=publication.sale_type, unlock_price_fen=publication.unlock_price_fen)
+ else:
+ fields = [column.name for column in model.__table__.columns]
+ result = data(item, *fields)
+ items.append(result)
+ if kind in ("rights", "cases", "reports", "entitlements"):
+ event(db, user.id, kind, 0, "admin_list_read")
+ await db.commit()
+ return {"items": items, "meta": meta}
+
+
[email protected]("/works/{work_id}/review", response_model=dict)
+async def review_work(work_id: int, body: ReviewInput, db: DB, user: Admin):
+ """一次审核同时检查作品内容和版权信息。"""
+ item = await db.get(Work, work_id, with_for_update=True)
+ if not item:
+ fail("作品不存在", 404)
+ check_version(item, body.version)
+ if item.audit_status != "pending":
+ fail("该版本不在待审核状态", 409)
+ rights = await rights_for(db, item.asset_id, lock=True)
+ asset = await db.get(Asset, item.asset_id)
+ if body.decision == "approved":
+ from .previews import preview_ready
+ if item.sale_type != "free" and not await preview_ready(db, item):
+ fail("水印播放文件尚未就绪,不能通过审核", 409)
+ if item.blocked or not asset or asset.status != "ready" or not rights or rights.blocked:
+ fail("版权、媒体或封禁状态不允许通过")
+ if rights.details.get("source") != item.source or (rights.valid_until and rights.valid_until <= now()):
+ fail("版权来源不匹配或已过期")
+ if item.source == "printfilm":
+ from .authorization import current
+ authorization = await current(db, item.owner_id)
+ if not authorization or str(authorization.id) != rights.details.get("authorization_id"):
+ fail("授权函不存在或已更新,请重新提交")
+ if not {"content", "copyright"}.issubset(body.checks):
+ fail("请确认作品内容与版权信息均已检查")
+ validate_rights(rights.details, full=True, certificate=bool(rights.certificate_asset_id))
+ if rights.certificate_asset_id:
+ proof = await db.get(Asset, rights.certificate_asset_id)
+ if not proof or proof.owner_id != item.owner_id or proof.status != "ready":
+ fail("版权证明不存在或未就绪")
+ rights.basic_status = rights.full_status = "approved"
+ 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.audit_status = "approved"
+ publication.listed = False
+ item.audit_status, item.reason, item.listed = body.decision, body.reason, False
+ if body.decision == "rejected" and rights:
+ rights.basic_status = rights.full_status = "rejected"
+ event(db, user.id, "work", item.id, f"review_{body.decision}", body.reason, item.version)
+ notify(db, item.owner_id, f"作品《{item.title}》审核结果:{body.decision};{body.reason}")
+ await db.commit()
+ return {"ok": True}
+
+
[email protected]("/revenue-config", response_model=dict)
+async def get_revenue_config(db: DB, user: Admin):
+ item = await db.get(RevenueConfig, 1)
+ return data(item, "id", "version", "platform_share_bps", "enabled") if item else {"version": 0, "enabled": False}
+
+
[email protected]("/revenue-config", response_model=dict)
+async def save_revenue_config(body: RevenueConfigInput, db: DB, user: Admin):
+ item = await db.get(RevenueConfig, 1, with_for_update=True)
+ current = item.version if item else 0
+ if body.version != current:
+ fail("分成配置已被修改,请刷新后重试", 409)
+ if not item:
+ item = RevenueConfig(id=1, version=0, platform_share_bps=body.platform_share_bps, enabled=body.enabled)
+ db.add(item)
+ else:
+ item.platform_share_bps, item.enabled, item.version = body.platform_share_bps, body.enabled, item.version + 1
+ event(db, user.id, "revenue_config", 1, "updated", version=item.version)
+ await db.commit()
+ return data(item, "id", "version", "platform_share_bps", "enabled")
+
+
[email protected]("/payouts", response_model=dict)
+async def create_payout(body: PayoutInput, db: DB, user: Admin):
+ """记录人工打款;不触发任何自动转账。"""
+ item = Payout(owner_id=body.owner_id, amount_fen=body.amount_fen, status=body.status,
+ note=body.note, paid_at=now() if body.status == "paid" else None,
+ operator_id=user.id if body.status == "paid" else None)
+ db.add(item)
+ await db.flush()
+ event(db, user.id, "payout", item.id, "created", body.note)
+ await db.commit()
+ return data(item, "id", "owner_id", "amount_fen", "status", "note", "paid_at", "operator_id", "created_at")
+
+
[email protected]("/payouts/{payout_id}", response_model=dict)
+async def update_payout(payout_id: int, body: PayoutInput, db: DB, user: Admin):
+ item = await db.get(Payout, payout_id, with_for_update=True)
+ if not item:
+ fail("打款记录不存在", 404)
+ if item.status == "paid" and body.status != "paid":
+ fail("已完成的打款记录不可回退", 409)
+ item.owner_id, item.amount_fen, item.note, item.status = body.owner_id, body.amount_fen, body.note, body.status
+ if body.status == "paid":
+ item.paid_at, item.operator_id = now(), user.id
+ event(db, user.id, "payout", item.id, "updated", body.note)
+ await db.commit()
+ return data(item, "id", "owner_id", "amount_fen", "status", "note", "paid_at", "operator_id", "created_at")
+
+
[email protected]("/series/{series_id}/review", response_model=dict)
+async def review_series(series_id: int, body: ReviewInput, db: DB, user: Admin):
+ series = await db.get(Series, series_id, with_for_update=True)
+ if not series:
+ fail("系列不存在", 404)
+ check_version(series, body.version)
+ if series.audit_status != "pending":
+ fail("该系列不在待审核状态", 409)
+ episodes = list((await db.execute(select(SeriesEpisode).where(SeriesEpisode.series_id == series.id).order_by(SeriesEpisode.episode_no).with_for_update())).scalars().all())
+ if body.decision == "approved":
+ # Series review is the single content + rights decision for all
+ # episodes. Require the same explicit confirmations as a single work;
+ # the separate legacy rights review endpoint is not used for new series.
+ if not {"content", "copyright"}.issubset(body.checks):
+ fail("请确认系列内容与各集版权信息均已检查")
+ if not episodes or [item.episode_no for item in episodes] != list(range(1, len(episodes) + 1)):
+ fail("系列分集必须从1开始连续排列")
+ config = await db.get(RevenueConfig, 1)
+ if series.sale_type == "platform_unlock" and (not config or not config.enabled):
+ fail("MARKETPLACE_REVENUE_CONFIG_REQUIRED", 409)
+ for episode in episodes:
+ asset = await db.get(Asset, episode.asset_id) if episode.asset_id else None
+ rights = (await db.execute(select(Rights).where(Rights.asset_id == episode.asset_id))).scalar_one_or_none() if episode.asset_id else None
+ if not asset or asset.status != "ready" or not rights or rights.blocked:
+ fail(f"第{episode.episode_no}集媒体或权属未就绪")
+ if not episode.cover_asset_id and not series.cover_asset_id:
+ fail(f"第{episode.episode_no}集缺少封面")
+ if rights.details.get("source") != episode.source:
+ fail(f"第{episode.episode_no}集版权来源与分集来源不匹配")
+ validate_rights(rights.details, full=True, certificate=bool(rights.certificate_asset_id))
+ if episode.source == "printfilm":
+ from .authorization import current
+ authorization = await current(db, series.owner_id)
+ if not authorization or str(authorization.id) != rights.details.get("authorization_id"):
+ fail(f"第{episode.episode_no}集 PrintFilm 授权函不存在或已更新")
+ elif episode.source == "external":
+ if not rights.certificate_asset_id or not rights.details.get("certificate_number") or not rights.details.get("dispute_ack"):
+ fail(f"第{episode.episode_no}集缺少版权证书编号、证明材料或纠纷声明")
+ from .previews import is_watermark_key
+ preview = (await db.execute(select(EpisodePreview).where(
+ EpisodePreview.episode_id == episode.id, EpisodePreview.asset_id == episode.asset_id,
+ EpisodePreview.status == "done").order_by(EpisodePreview.id.desc()).limit(1))).scalar_one_or_none()
+ if not preview or not is_watermark_key(preview.object_key):
+ 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 not publication:
+ fail(f"第{episode.episode_no}集缺少发布版本,请让作者重新提交", 409)
+ publication.audit_status, publication.listed = "approved", False
+ rights.basic_status = rights.full_status = "approved"
+ episode.audit_status = "approved"
+ episode.listed = False
+ series.audit_status, series.reason, series.listed = "approved", body.reason, False
+ else:
+ series.audit_status, series.reason = "rejected", body.reason
+ for episode in episodes:
+ episode.audit_status = "rejected"
+ rights = (await db.execute(select(Rights).where(Rights.asset_id == episode.asset_id))).scalar_one_or_none() if episode.asset_id else None
+ if rights:
+ rights.basic_status = rights.full_status = "rejected"
+ event(db, user.id, "series", series.id, f"review_{body.decision}", body.reason, series.version)
+ notify(db, series.owner_id, f"系列《{series.title}》审核结果:{body.decision};{body.reason}")
+ await db.commit()
+ return {"ok": True}
+
+
[email protected]("/rights/{rights_id}/review", response_model=dict)
+async def review_rights(rights_id: int, body: ReviewInput, db: DB, user: Admin, full: bool = False):
+ """必须逐项确认核验结果;证书上传与登记案件办结不能自动放行。"""
+ item = await db.get(Rights, rights_id, with_for_update=True)
+ if not item:
+ fail("权属档案不存在", 404)
+ if (await db.execute(select(Work.id).where(Work.asset_id == item.asset_id).limit(1))).scalar_one_or_none():
+ fail("请在作品统一审核中处理该作品", 409)
+ check_version(item, body.version)
+ if item.basic_status != "pending" and item.full_status != "pending":
+ fail("该版本不在待核验状态", 409)
+ if body.decision == "approved":
+ if item.blocked or (item.valid_until and item.valid_until <= now()):
+ fail("权属已封禁或授权到期")
+ validate_rights(item.details, full=full, certificate=bool(item.certificate_asset_id))
+ source = item.details.get("source")
+ if not item.evidence_ids and source not in ("printfilm", "external"):
+ fail("缺少基础证明材料")
+ if source == "external" and not item.evidence_ids and not item.certificate_asset_id:
+ fail("缺少基础权属证明材料")
+ if source == "printfilm":
+ from .authorization import current
+ authorization = await current(db, item.owner_id)
+ if not authorization or str(authorization.id) != item.details.get("authorization_id"):
+ fail("授权函不存在或版本已更新,请重新关联并提交")
+ checks = {"identity", "ownership", "third_party", "scope"}
+ if full:
+ checks.update({"authorization" if source == "printfilm" else "ownership_proof" if source == "external" else "certificate", "sample_match", "sales_authority"})
+ if source in ("ai", "printfilm", "external"):
+ checks.add("ai_evidence")
+ if not checks.issubset(body.checks):
+ fail("请逐项确认身份、作品匹配、素材、授权范围和证书核验")
+ for document_id in [*item.evidence_ids, *([item.certificate_asset_id] if item.certificate_asset_id else [])]:
+ document = await db.get(Asset, document_id)
+ if not document or document.owner_id != item.owner_id or document.status != "ready":
+ fail("核验材料不存在或未处理完成")
+ item.basic_status = item.full_status = body.decision
+ item.reason = body.reason
+ event(db, user.id, "rights", item.id, f"{'full' if full else 'basic'}_{body.decision}", body.reason + ";核验项:" + ",".join(body.checks), item.version)
+ notify(db, item.owner_id, f"视频 #{item.asset_id} 权属核验结果:{body.decision};{body.reason}")
+ await db.commit()
+ return {"ok": True}
+
+
[email protected]("/recruits/{post_id}/review", response_model=dict)
+async def review_recruit(post_id: int, body: ReviewInput, db: DB, user: Admin):
+ """需求公开审核,过期、关闭、封禁不能被过期审核重新开启。"""
+ item = await db.get(Recruit, post_id, with_for_update=True)
+ if not item:
+ fail("需求不存在", 404)
+ check_version(item, body.version)
+ if item.audit_status != "pending" or item.state in ("closed", "expired"):
+ fail("需求不在待审核状态", 409)
+ if body.decision == "approved" and (item.blocked or item.deadline_at <= now()):
+ fail("需求已到期或被封禁")
+ item.audit_status, item.reason = body.decision, body.reason
+ item.state = "open" if body.decision == "approved" else "draft"
+ event(db, user.id, "recruit", item.id, f"content_{body.decision}", body.reason, item.version)
+ notify(db, item.owner_id, f"需求《{item.title}》审核结果:{body.decision};{body.reason}")
+ await db.commit()
+ return {"ok": True}
+
+
[email protected]("/cases/{case_id}/status", response_model=dict)
+async def case_status(case_id: int, body: CaseReview, db: DB, user: Admin):
+ """办理进度独立于权属审核;录入已取证仍不解锁销售。"""
+ item = await db.get(RegistrationCase, case_id, with_for_update=True)
+ if not item:
+ fail("案件不存在", 404)
+ check_version(item, body.version)
+ if body.status == "certificated":
+ rights = await db.get(Rights, item.rights_id)
+ if not rights.certificate_asset_id or not rights.details.get("certificate_number"):
+ fail("请先由用户补充证书号和证书材料")
+ item.status, item.note = body.status, body.note
+ item.version += 1
+ event(db, user.id, "case", item.id, body.status, body.note, item.version)
+ notify(db, item.owner_id, f"登记案件 #{item.id} 更新:{body.status};{body.note}")
+ await db.commit()
+ return {"ok": True}
+
+
[email protected]("/block/{kind}/{record_id}", response_model=dict)
+async def block(kind: str, record_id: int, body: BlockInput, db: DB, user: Admin):
+ """争议处理可暂停播放和咨询;解除封禁不自动重新上架。"""
+ model = {"work": Work, "rights": Rights, "recruit": Recruit, "submission": Submission}.get(kind)
+ if not model:
+ fail("封禁类型无效")
+ item = await db.get(model, record_id, with_for_update=True)
+ if not item:
+ fail("记录不存在", 404)
+ item.blocked = body.blocked
+ if isinstance(item, Work):
+ item.listed = False
+ item.version += 1
+ if isinstance(item, (Work, Recruit, Rights)):
+ item.reason = body.reason
+ event(db, user.id, kind, item.id, "blocked" if body.blocked else "unblocked", body.reason)
+ notify(db, item.owner_id, f"{kind} #{item.id} {'被限制' if body.blocked else '已解除限制'}:{body.reason}")
+ await db.commit()
+ return {"ok": True}
+
+
[email protected]("/reports/{report_id}/resolve", response_model=dict)
+async def resolve_report(report_id: int, body: ResolutionInput, db: DB, user: Admin):
+ """投诉处理结论留痕,限制内容须使用明确的封禁操作。"""
+ item = await db.get(Report, report_id, with_for_update=True)
+ if not item:
+ fail("举报不存在", 404)
+ item.status, item.resolution = "resolved", body.resolution
+ event(db, user.id, "report", item.id, "resolved", body.resolution)
+ notify(db, item.owner_id, f"举报 #{item.id} 已处理:{body.resolution}")
+ await db.commit()
+ return {"ok": True}
+
+
[email protected]("/support", response_model=dict)
+async def get_support(db: DB, user: Admin):
+ """管理配置不返回 OSS 对象位置。"""
+ item = await db.get(Support, 1)
+ return data(item, "name", "wechat", "hours", "qr_asset_id", "enabled") if item else {"enabled": False}
+
+
[email protected]("/support", response_model=dict)
+async def save_support(body: SupportInput, db: DB, user: Admin):
+ """仅使用已处理完成的真实二维码资产。"""
+ if body.qr_asset_id:
+ await asset_owned(db, body.qr_asset_id, user, ("qr",))
+ if body.enabled and (not body.wechat or not body.qr_asset_id):
+ fail("启用客服必须设置微信号及真实二维码")
+ item = await db.get(Support, 1, with_for_update=True)
+ if not item:
+ item = Support(id=1)
+ db.add(item)
+ for key, value in body.model_dump().items():
+ setattr(item, key, value)
+ event(db, user.id, "support", 1, "updated")
+ await db.commit()
+ return {"ok": True}
diff --git a/backend/app/marketplace/api.py b/backend/app/marketplace/api.py
new file mode 100644
index 0000000..e17b280
--- /dev/null
+++ b/backend/app/marketplace/api.py
@@ -0,0 +1,490 @@
+"""公开目录和作者工作台;只操作 marketplace_ 表。"""
+from fastapi import APIRouter, HTTPException, Query
+from sqlalchemy import func, literal, select, union_all
+
+from app.models import User
+from .dependencies import Actor, DB, Visitor
+from .previews import prepare_preview, preview_ready, requires_preview
+from .models import Asset, PlaybackJob, Publication, Recruit, RegistrationCase, RevenueConfig, Rights, Series, Submission, Work
+from .schemas import CaseInput, RecruitInput, RecruitUpdate, RightsInput, Version, WorkInput, WorkUpdate
+from .service import (asset_owned, asset_owned_for_draft, check_version, data, event, fail, get_target, is_public_work, now,
+ notify, owned, page, public_recruit_filters, public_work_filters, recruit_data,
+ recruit_open, rights_for, rights_valid, submission_data, validate_rights, work_data)
+
+router = APIRouter()
+
+
[email protected]("/categories", response_model=dict)
+async def get_categories(db: DB):
+ from .categories import category_config
+ return await category_config(db)
+
+
+async def catalog_item(db, kind: str, item_id: int) -> dict:
+ """把单视频和短剧收成广场卡片;短剧不展开分集正文。"""
+ if kind == "work":
+ payload = await work_data(db, await db.get(Work, item_id))
+ payload["kind"] = "work"
+ return payload
+ from .series import _series_data
+ series = await db.get(Series, item_id)
+ detail = await _series_data(db, series)
+ owner = await db.get(User, series.owner_id)
+ return {"kind": "series", "id": series.id, "title": series.title, "description": series.description,
+ "category": series.category, "sale_type": series.sale_type, "price_fen": series.copyright_price_fen,
+ "author": owner.nickname if owner else "创作者", "episode_count": detail["episode_count"],
+ "free_episode_count": series.free_episode_count,
+ "cover_asset_id": series.cover_asset_id, "created_at": series.created_at}
+
+
[email protected]("/works", response_model=dict)
+async def works(db: DB, q: str = Query("", max_length=100), category: str = Query("", max_length=60),
+ min_price: int | None = Query(None, ge=0), max_price: int | None = Query(None, ge=0),
+ sort: str = "latest", page_number: int = Query(1, alias="page", ge=1), page_size: int = Query(20, ge=1, le=100)):
+ """单视频和短剧共用作品广场,筛选后再分页。"""
+ from .series import public_series_filters
+ if sort not in {"latest", "price_asc", "price_desc"}:
+ fail("排序参数无效")
+ work_query = select(Work.id.label("item_id"), literal("work").label("kind"), Work.created_at.label("sort_at"),
+ Work.price_fen.label("price")).join(Asset, Asset.id == Work.asset_id).join(Rights, Rights.asset_id == Asset.id).where(*public_work_filters())
+ series_query = select(Series.id.label("item_id"), literal("series").label("kind"), Series.created_at.label("sort_at"),
+ Series.copyright_price_fen.label("price")).where(*public_series_filters())
+ if q:
+ work_query = work_query.where(Work.title.ilike(f"%{q}%"))
+ series_query = series_query.where(Series.title.ilike(f"%{q}%"))
+ if category:
+ work_query = work_query.where(Work.category == category)
+ series_query = series_query.where(Series.category == category)
+ if min_price is not None:
+ work_query = work_query.where(Work.price_fen >= min_price)
+ series_query = series_query.where(Series.copyright_price_fen >= min_price)
+ if max_price is not None:
+ work_query = work_query.where(Work.price_fen <= max_price)
+ series_query = series_query.where(Series.copyright_price_fen <= max_price)
+ combined = union_all(work_query, series_query).subquery()
+ total = (await db.execute(select(func.count()).select_from(combined))).scalar_one()
+ ordering = {"latest": combined.c.sort_at.desc(), "price_asc": combined.c.price.asc(), "price_desc": combined.c.price.desc()}
+ rows = (await db.execute(select(combined).order_by(ordering[sort], combined.c.item_id.desc())
+ .offset((page_number - 1) * page_size).limit(page_size))).all()
+ return {"items": [await catalog_item(db, row.kind, row.item_id) for row in rows],
+ "meta": {"page": page_number, "page_size": page_size, "total": total}}
+
+
[email protected]("/works/{work_id}", response_model=dict)
+async def work_detail(work_id: int, db: DB, user: Visitor):
+ """作者和管理员可看草稿,公众仅可看满足全部条件的作品。"""
+ item = await db.get(Work, work_id)
+ private = bool(item and user and (item.owner_id == user.id or user.role == "admin"))
+ if not item or (not private and not await is_public_work(db, work_id)):
+ fail("作品不存在或未公开", 404)
+ return await work_data(db, item, private)
+
+
[email protected]("/works", response_model=dict)
+async def create_work(body: WorkInput, db: DB, user: Actor):
+ """文字草稿无需 OSS,绑定媒体时只能选择本人的 ready 资产。"""
+ from .categories import validate_category
+ await validate_category(db, body.category)
+ if body.asset_id:
+ 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",))
+ values = body.model_dump()
+ # 兼容旧客户端未发送收费类型且 price_fen=0 的草稿;新客户端明确选择联系客服时保留该类型。
+ if "sale_type" not in body.model_fields_set and values["price_fen"] == 0:
+ values["sale_type"] = "free"
+ item = Work(owner_id=user.id, **values)
+ db.add(item)
+ await db.commit()
+ return await work_data(db, item, True)
+
+
[email protected]("/works/{work_id}", response_model=dict)
+async def update_work(work_id: int, body: WorkUpdate, db: DB, user: Actor):
+ """更新即撤下旧公开内容;权利范围变化重置完整核验。"""
+ item = await owned(db, Work, work_id, user)
+ check_version(item, body.version)
+ from .categories import validate_category
+ await validate_category(db, body.category, item.category)
+ if body.asset_id:
+ 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",))
+ if item.license_scope != body.license_scope or item.source != body.source:
+ rights = await rights_for(db, body.asset_id, lock=True)
+ if rights:
+ rights.full_status = "draft"
+ rights.version += 1
+ values = body.model_dump(exclude={"version"})
+ if "sale_type" not in body.model_fields_set and values["price_fen"] == 0:
+ values["sale_type"] = "free"
+ for key, value in values.items():
+ setattr(item, key, value)
+ item.version += 1
+ item.audit_status, item.listed, item.reason = "draft", False, ""
+ event(db, user.id, "work", item.id, "updated", version=item.version)
+ await db.commit()
+ return await work_data(db, item, True)
+
+
[email protected]("/works/{work_id}/submit", response_model=dict)
+async def submit_work(work_id: int, body: Version, db: DB, user: Actor):
+ """作品资料和版权信息一次提交,进入统一管理员审核。"""
+ item = await owned(db, Work, work_id, user)
+ check_version(item, body.version)
+ if item.blocked:
+ fail("作品已被管理员封禁")
+ 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():
+ fail("请在作品草稿中填写“拟授权用途及限制”后再提交审核")
+ if not rights or rights.blocked or rights.details.get("source") != item.source:
+ fail("请先填写版权信息和授权意向")
+ validate_rights(rights.details, full=True, certificate=bool(rights.certificate_asset_id))
+ if rights.valid_until and rights.valid_until <= now():
+ fail("版权授权已过期")
+ # 免费作品直接播放用户上传的原片,不创建试看/水印任务;收费作品
+ # 才需要由市场 Worker 生成最多 15 秒、最多原片 30% 的试看文件。
+ watermark_ready = await preview_ready(db, item) if requires_preview(item.sale_type) else True
+ if requires_preview(item.sale_type) and not watermark_ready:
+ from .dependencies import storage_ready
+ await storage_ready()
+ await prepare_preview(db, item)
+ item.audit_status, item.listed, item.reason = "processing", False, "正在生成试看播放文件"
+ else:
+ item.audit_status, item.listed, item.reason = "pending", False, ""
+ if item.sale_type == "platform_unlock":
+ config = await db.get(RevenueConfig, 1)
+ if not config or not config.enabled:
+ fail("MARKETPLACE_REVENUE_CONFIG_REQUIRED", 409)
+ if item.unlock_price_fen <= 0:
+ fail("平台投放作品必须设置解锁价", 409)
+ if item.audit_status in ("pending", "processing"):
+ 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()
+ values = 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,
+ "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",
+ playback_status="done" if item.sale_type != "platform_unlock" else "pending")
+ if publication is None:
+ publication = Publication(content_type="work", content_id=item.id, **values)
+ db.add(publication)
+ else:
+ for key, value in values.items():
+ setattr(publication, key, value)
+ # A durable playback job gives the market Worker a lease and restart
+ # recovery point. It is intentionally created only for platform
+ # content; free/contact works never need HLS packaging.
+ if item.sale_type == "platform_unlock":
+ playback_job = (await db.execute(select(PlaybackJob).where(
+ PlaybackJob.publication_id == publication.id
+ ).with_for_update())).scalar_one_or_none() if publication.id else None
+ if playback_job is None:
+ # New publications have no database id until flush; the FK is
+ # populated after the explicit flush below.
+ await db.flush()
+ playback_job = (await db.execute(select(PlaybackJob).where(
+ PlaybackJob.publication_id == publication.id
+ ).with_for_update())).scalar_one_or_none()
+ if playback_job is None:
+ db.add(PlaybackJob(publication_id=publication.id, status="pending"))
+ else:
+ # Re-submitting the same draft version invalidates any prior
+ # package attempt; never leave a done job paired with a pending
+ # publication snapshot.
+ playback_job.status, playback_job.error = "pending", ""
+ playback_job.attempts = 0
+ playback_job.lease_token, playback_job.lease_until = None, None
+ publication.playback_manifest_key = None
+ publication.playback_error = ""
+ rights.basic_status = rights.full_status = "pending"
+ if item.audit_status == "pending":
+ event(db, user.id, "work", item.id, "submitted", version=item.version)
+ await db.commit()
+ return await work_data(db, item, True)
+
+
[email protected]("/works/{work_id}/listing", response_model=dict)
+async def listing(work_id: int, body: Version, db: DB, user: Actor, listed: bool = True):
+ """作者主动上下架,不允许自行解除管理员封禁。"""
+ item = await owned(db, Work, work_id, user)
+ check_version(item, body.version)
+ if listed:
+ if requires_preview(item.sale_type) and not await preview_ready(db, item):
+ fail("水印播放文件尚未生成,请重新提交审核", 409)
+ rights = await rights_for(db, item.asset_id, lock=True)
+ asset = await db.get(Asset, item.asset_id) if item.asset_id else None
+ if item.blocked or item.audit_status != "approved" or not asset or asset.status != "ready" or not rights_valid(rights, full=True) or rights.details.get("source") != item.source:
+ fail("媒体、内容或权属尚未通过,不能上架")
+ if item.sale_type == "platform_unlock":
+ 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 not publication or publication.playback_status != "done":
+ fail("平台播放版本尚未就绪,请稍后再上架", 409)
+ item.listed = listed
+ 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")
+ event(db, user.id, "work", item.id, "listed" if listed else "unlisted", version=item.version)
+ await db.commit()
+ return await work_data(db, item, True)
+
+
[email protected]("/assets/{asset_id}/rights", response_model=dict)
+async def get_rights(asset_id: int, db: DB, user: Actor):
+ """权属材料只允许本人或管理员读取,并保留访问记录。"""
+ await owned(db, Asset, asset_id, user, admin=True)
+ rights = await rights_for(db, asset_id)
+ if not rights:
+ source = (await db.execute(select(Work.source).where(Work.asset_id == asset_id, Work.owner_id == user.id).order_by(Work.id.desc()).limit(1))).scalar_one_or_none()
+ return {"asset_id": asset_id, "version": 0, "details": {"source": source or "external"}}
+ event(db, user.id, "rights", rights.id, "read")
+ await db.commit()
+ return data(rights, "id", "asset_id", "version", "details", "certificate_asset_id", "evidence_ids", "basic_status", "full_status", "valid_until", "blocked", "reason")
+
+
[email protected]("/assets/{asset_id}/rights", response_model=dict)
+async def save_rights(asset_id: int, body: RightsInput, db: DB, user: Actor):
+ """任何材料变动都重置核验结论,绑定不可变视频文件。"""
+ await asset_owned(db, asset_id, user)
+ for document_id in [*body.evidence_ids, *([body.certificate_asset_id] if body.certificate_asset_id else [])]:
+ await asset_owned(db, document_id, user, ("document", "image"))
+ if body.valid_until and body.valid_until <= now():
+ fail("授权截止时间必须晚于当前时间")
+ authorization = None
+ if body.details.source == "printfilm":
+ from .authorization import current
+ authorization = await current(db, user.id)
+ if not authorization:
+ fail("请先签署 PrintFilm 授权函")
+ item = await rights_for(db, asset_id, lock=True)
+ if item:
+ check_version(item, body.version)
+ item.version += 1
+ else:
+ if body.version != 0:
+ fail("权属档案版本无效", 409)
+ item = Rights(asset_id=asset_id, owner_id=user.id, version=1)
+ db.add(item)
+ item.details = body.details.model_dump()
+ if body.details.source == "printfilm":
+ from .authorization import current
+ authorization = await current(db, user.id)
+ if authorization:
+ item.details = {**item.details, "authorization_id": str(authorization.id),
+ "authorization_version": authorization.template_version,
+ "authorization_signer": authorization.signer_name}
+ if not authorization:
+ fail("请先签署 PrintFilm 授权函")
+ item.certificate_asset_id, item.evidence_ids, item.valid_until = body.certificate_asset_id, body.evidence_ids, body.valid_until
+ 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:
+ work.audit_status, work.listed = "draft", False
+ work.version += 1
+ await db.flush()
+ event(db, user.id, "rights", item.id, "updated", version=item.version)
+ await db.commit()
+ return {"id": item.id, "version": item.version}
+
+
[email protected]("/rights/{rights_id}/submit", response_model=dict)
+async def submit_rights(rights_id: int, body: Version, db: DB, user: Actor, full: bool = False):
+ """用户只提交一次版权审核;保留 full 参数兼容旧客户端。"""
+ item = await owned(db, Rights, rights_id, user)
+ if (await db.execute(select(Work.id).where(Work.asset_id == item.asset_id).limit(1))).scalar_one_or_none():
+ fail("请提交作品审核,版权信息将一并提交", 409)
+ check_version(item, body.version)
+ if item.blocked:
+ fail("权属档案处于争议或封禁中")
+ validate_rights(item.details, full=full, certificate=bool(item.certificate_asset_id))
+ if not item.evidence_ids and item.details.get("source") not in ("printfilm", "external"):
+ fail("请上传创作或授权证明材料")
+ if item.details.get("source") == "external" and not item.evidence_ids and not item.certificate_asset_id:
+ fail("请上传基础权属证明;没有证明可先联系客服协办")
+ item.basic_status = item.full_status = "pending"
+ event(db, user.id, "rights", item.id, "submitted", version=item.version)
+ await db.commit()
+ return {"ok": True}
+
+
[email protected]("/rights/{rights_id}/case", response_model=dict)
+async def save_case(rights_id: int, body: CaseInput, db: DB, user: Actor):
+ """申请回执和案件办结从不修改权属核验结论。"""
+ await owned(db, Rights, rights_id, user)
+ item = (await db.execute(select(RegistrationCase).where(RegistrationCase.rights_id == rights_id).with_for_update())).scalar_one_or_none()
+ if item:
+ check_version(item, body.version)
+ item.version += 1
+ item.status = "pending_materials"
+ else:
+ if body.version != 0:
+ fail("案件版本无效", 409)
+ item = RegistrationCase(rights_id=rights_id, owner_id=user.id)
+ db.add(item)
+ item.route, item.official_reference, item.note = body.route, body.official_reference, body.note
+ await db.commit()
+ return data(item, "id", "rights_id", "version", "route", "status", "official_reference", "note")
+
+
[email protected]("/assets/{asset_id}/assistance", response_model=dict)
+async def start_assistance(asset_id: int, db: DB, user: Actor):
+ """无证明即可建协办案;不生成虚假权属信息或审核结论。"""
+ await asset_owned(db, asset_id, user)
+ rights = await rights_for(db, asset_id, lock=True)
+ if rights and rights.details.get("source") == "printfilm":
+ fail("PrintFilm 作品请先签署授权函;更正来源请保存权属档案")
+ if not rights:
+ rights = Rights(asset_id=asset_id, owner_id=user.id, details={"source": "external"})
+ db.add(rights)
+ await db.flush()
+ item = (await db.execute(select(RegistrationCase).where(RegistrationCase.rights_id == rights.id).with_for_update())).scalar_one_or_none()
+ if item and item.route != "assisted":
+ fail("已有其他办理方式,请在案件表单中改为客服协办", 409)
+ if not item:
+ item = RegistrationCase(rights_id=rights.id, owner_id=user.id, route="assisted")
+ db.add(item)
+ await db.flush()
+ event(db, user.id, "case", item.id, "created_assistance")
+ notify(db, user.id, f"权属协办案件 #{item.id} 已建立,请联系客服补充材料")
+ await db.commit()
+ return data(item, "id", "rights_id", "version", "route", "status", "official_reference", "note")
+
+
[email protected]("/rights/{rights_id}/case", response_model=dict)
+async def get_case(rights_id: int, db: DB, user: Actor):
+ """按当前档案读取案件,避免个人案件分页截断导致重复创建。"""
+ await owned(db, Rights, rights_id, user)
+ item = (await db.execute(select(RegistrationCase).where(RegistrationCase.rights_id == rights_id))).scalar_one_or_none()
+ return {"item": data(item, "id", "rights_id", "version", "route", "status", "official_reference", "note") if item else None}
+
+
[email protected]("/recruits", response_model=dict)
+async def recruits(db: DB, q: str = Query("", max_length=100), category: str = Query("", max_length=60),
+ min_budget: int | None = Query(None, ge=0), max_budget: int | None = Query(None, ge=0),
+ sort: str = "latest", page_number: int = Query(1, alias="page", ge=1), page_size: int = Query(20, ge=1, le=100)):
+ """只展示审核通过且仍开放的需求。"""
+ query = select(Recruit).where(*public_recruit_filters())
+ if q:
+ query = query.where(Recruit.title.ilike(f"%{q}%"))
+ if category:
+ query = query.where(Recruit.category == category)
+ if min_budget is not None:
+ query = query.where(Recruit.budget_fen >= min_budget)
+ if max_budget is not None:
+ query = query.where(Recruit.budget_fen <= max_budget)
+ if sort not in ("latest", "deadline"):
+ fail("排序参数无效")
+ records, meta = await page(db, query.order_by(Recruit.deadline_at if sort == "deadline" else Recruit.id.desc(), Recruit.id.desc()), page_number, page_size)
+ return {"items": [await recruit_data(db, item) for item in records], "meta": meta}
+
+
[email protected]("/recruits/{post_id}", response_model=dict)
+async def recruit_detail(post_id: int, db: DB, user: Visitor):
+ """相关投稿人可看已关闭需求,但不能借此看他人的投稿。"""
+ item = await db.get(Recruit, post_id)
+ private = bool(item and user and (user.id == item.owner_id or user.role == "admin"))
+ related = bool(user and (await db.execute(select(Submission.id).where(Submission.recruit_id == post_id, Submission.owner_id == user.id).limit(1))).scalar_one_or_none())
+ if not item or (not private and not related and not recruit_open(item)):
+ fail("需求不存在或未公开", 404)
+ result = await recruit_data(db, item, private)
+ result.update(is_owner=bool(user and user.id == item.owner_id), is_open=recruit_open(item),
+ can_submit=False,
+ can_contact=bool(user and user.id != item.owner_id and recruit_open(item)))
+ return result
+
+
[email protected]("/recruits", response_model=dict)
+async def create_recruit(body: RecruitInput, db: DB, user: Actor):
+ """没有参考图的文字需求不依赖 OSS。"""
+ if body.deadline_at <= now():
+ fail("截止时间必须晚于当前时间")
+ for image in body.image_ids:
+ await asset_owned(db, image, user, ("image",))
+ item = Recruit(owner_id=user.id, **body.model_dump())
+ db.add(item)
+ await db.commit()
+ return await recruit_data(db, item, True)
+
+
[email protected]("/recruits/{post_id}", response_model=dict)
+async def update_recruit(post_id: int, body: RecruitUpdate, db: DB, user: Actor):
+ """曾有投稿后锁定实质条款;其他修改撤下并重新审核。"""
+ item = await owned(db, Recruit, post_id, user)
+ check_version(item, body.version)
+ if item.state in ("closed", "expired"):
+ fail("需求已结束,请重新发布")
+ if body.deadline_at <= now():
+ fail("截止时间必须晚于当前时间")
+ exists = (await db.execute(select(Submission.id).where(Submission.recruit_id == post_id).limit(1))).scalar_one_or_none()
+ locked = ("budget_fen", "wanted_count", "license_scope", "requirements", "deadline_at", "description")
+ if exists and any(getattr(item, field) != getattr(body, field) for field in locked):
+ fail("已有投稿,预算、用途、授权、交付及截止条件已锁定,请关闭后重新发布")
+ for image in body.image_ids:
+ await asset_owned(db, image, user, ("image",))
+ for key, value in body.model_dump(exclude={"version"}).items():
+ setattr(item, key, value)
+ item.version += 1
+ item.audit_status, item.state = "draft", "draft"
+ await db.commit()
+ return await recruit_data(db, item, True)
+
+
[email protected]("/recruits/{post_id}/submit", response_model=dict)
+async def submit_recruit(post_id: int, body: Version, db: DB, user: Actor):
+ """需求审核独立于原项目发布流程。"""
+ item = await owned(db, Recruit, post_id, user)
+ check_version(item, body.version)
+ if item.blocked or item.state in ("closed", "expired") or item.deadline_at <= now():
+ fail("需求已结束或被封禁")
+ item.audit_status = "pending"
+ event(db, user.id, "recruit", item.id, "submitted", version=item.version)
+ await db.commit()
+ return {"ok": True}
+
+
[email protected]("/recruits/{post_id}/close", response_model=dict)
+async def close_recruit(post_id: int, db: DB, user: Actor):
+ """关闭后退出广场并停止创作者的新接单咨询,历史记录保留。"""
+ item = await owned(db, Recruit, post_id, user)
+ item.state = "closed"
+ item.version += 1
+ event(db, user.id, "recruit", item.id, "closed", version=item.version)
+ await db.commit()
+ return {"ok": True}
+
+
[email protected]("/recruits/{post_id}/submissions", response_model=dict, include_in_schema=False)
+async def create_submission(post_id: int, user: Actor):
+ """兼容旧客户端并明确拒绝投稿;不创建媒体任务或修改资产。"""
+ raise HTTPException(410, detail={"code": "MARKETPLACE_SUBMISSIONS_DISABLED",
+ "message": "招募已改为客服撮合,请在招募详情中联系客服接单"})
+
+
[email protected]("/recruits/{post_id}/submissions", response_model=dict)
+async def received_submissions(post_id: int, db: DB, user: Actor, page_number: int = Query(1, alias="page", ge=1), page_size: int = Query(20, ge=1, le=100)):
+ """收到的投稿只有需求方和管理员可列出。"""
+ await owned(db, Recruit, post_id, user, admin=True)
+ records, meta = await page(db, select(Submission).where(Submission.recruit_id == post_id).order_by(Submission.id.desc()), page_number, page_size)
+ return {"items": [await submission_data(db, item, user) for item in records], "meta": meta}
+
+
[email protected]("/submissions/{submission_id}/withdraw", response_model=dict)
+async def withdraw(submission_id: int, db: DB, user: Actor):
+ """撤回即停止新签名,历史留痕不删除。"""
+ item = await owned(db, Submission, submission_id, user)
+ item.withdrawn = True
+ event(db, user.id, "submission", item.id, "withdrawn")
+ await db.commit()
+ return {"ok": True}
+
+
[email protected]("/submissions/{submission_id}/selection", response_model=dict, include_in_schema=False)
+async def select_submission(submission_id: int, user: Actor):
+ """停止线上选稿;历史标记只读保留。"""
+ raise HTTPException(410, detail={"code": "MARKETPLACE_SUBMISSIONS_DISABLED",
+ "message": "招募已改为客服撮合,请联系客服确认合作"})
diff --git a/backend/app/marketplace/authorization.py b/backend/app/marketplace/authorization.py
new file mode 100644
index 0000000..67c7784
--- /dev/null
+++ b/backend/app/marketplace/authorization.py
@@ -0,0 +1,132 @@
+"""本平台作品账号授权;仅作用于下游,不自动转让或授予买家权利。"""
+import asyncio
+import hashlib
+from pathlib import Path
+import tempfile
+from typing import Annotated, Literal
+import uuid
+
+from fastapi import APIRouter, Depends, Request
+from pydantic import Field, model_validator
+from sqlalchemy import select
+from sqlalchemy.exc import IntegrityError
+
+from . import storage
+from .config import get_marketplace_settings
+from .dependencies import Actor, DB, storage_ready
+from .models import Authorization
+from .schemas import Input
+from .service import data, event, fail, now
+
+VERSION = "printfilm-marketplace-2026-10-v1"
+TITLE = "PrintFilm 生成作品展示与撮合授权函"
+BODY = """一、适用作品:本人以本账号提交至数字资产市场并声明为 PrintFilm 生成的作品。本授权函可被本账号后续作品引用,但每件作品的来源、权属、素材及授权范围仍由平台逐件核验。
+二、权属声明:本人为作品权利人或有权代表权利人提交作品,保证提供的生成记录、创作贡献和素材许可真实。音乐、字体、肖像、改编及第三方素材须具有相应使用权;本函不构成著作权登记证书,也不证明作品绝无侵权。
+三、授权范围:本人非独家授权平台在审核通过、本人选择上架期间,存储及处理作品,制作压缩水印预览,在市场展示作品介绍和预览,并协助联系潜在需求方。投稿完整水印审片仅向相应需求方及审核人员开放。
+四、交易边界:本函不转让作品版权,不授予平台或买家自动购买、再许可或原片下载权。具体价格、用途、期限、地域、合同、收款和原片交付由相关方在线下另行确认。选择候选或联系客服不构成成交。
+五、下架与争议:本人可下架作品或撤回投稿以停止新展示和新审片链接。已签发的短时链接最长五分钟后失效。平台收到有初步证据的投诉时可暂停展示、播放和咨询,要求补充材料并保留处置记录。
+六、签署与记录:本人已完整阅读并理解以上内容,自愿以真实姓名及手写签名确认。平台保存条款版本、全文摘要、签署时间、账号、签署图像及必要的访问记录,供授权核验与争议处理使用。条款更新后需重新签署;旧记录留档。"""
+
+Point = tuple[Annotated[float, Field(ge=0, le=800, allow_inf_nan=False)], Annotated[float, Field(ge=0, le=240, allow_inf_nan=False)]]
+Stroke = Annotated[list[Point], Field(min_length=2, max_length=1000)]
+
+
+class SignInput(Input):
+ template_version: str = Field(max_length=60)
+ signer_name: str = Field(min_length=2, max_length=80)
+ accepted_terms: Literal[True]
+ strokes: list[Stroke] = Field(min_length=1, max_length=40)
+
+ @model_validator(mode="after")
+ def handwritten(self):
+ points = [p for stroke in self.strokes for p in stroke]
+ distance = sum(((b[0]-a[0])**2 + (b[1]-a[1])**2)**0.5 for stroke in self.strokes for a, b in zip(stroke, stroke[1:]))
+ if len(points) < 12 or distance < 80 or max(p[0] for p in points)-min(p[0] for p in points) < 20:
+ raise ValueError("请在签名区完整手写签名")
+ return self
+
+
+router = APIRouter()
+
+
+async def current(db, owner_id: int):
+ return (await db.execute(select(Authorization).where(Authorization.owner_id == owner_id, Authorization.template_version == VERSION))).scalar_one_or_none()
+
+
+def summary(item):
+ return data(item, "id", "template_version", "signer_name", "created_at", "body_hash") if item else None
+
+
+def render_and_store(body: SignInput, signed_at: str, owner_id: int) -> tuple[str, str]:
+ """服务端合成全文和签名,先完成私有 OSS 写入再登记签署成功。"""
+ from PIL import Image, ImageDraw, ImageFont
+ font = ImageFont.truetype(get_marketplace_settings().watermark_font, 26)
+ lines = []
+ for paragraph in [TITLE, f"版本:{VERSION}", *BODY.splitlines(), f"签署人:{body.signer_name}", f"账号:{owner_id} 签署时间(UTC):{signed_at}", "手写签名:"]:
+ line = ""
+ for char in paragraph:
+ if font.getlength(line + char) > 1000:
+ lines.append(line)
+ line = ""
+ line += char
+ lines.extend([line, ""])
+ signature = Image.new("RGB", (800, 240), "white")
+ draw = ImageDraw.Draw(signature)
+ for stroke in body.strokes:
+ draw.line(stroke, fill="black", width=3, joint="curve")
+ letter = Image.new("RGB", (1120, 100 + len(lines)*40 + 260), "white")
+ draw = ImageDraw.Draw(letter)
+ for i, line in enumerate(lines):
+ draw.text((60, 50 + i*40), line, font=font, fill="black")
+ letter.paste(signature, (60, 50 + len(lines)*40))
+ prefix = f"marketplace/authorizations/u{owner_id}/{uuid.uuid4().hex}"
+ with tempfile.TemporaryDirectory(prefix="printfilm-authorization-") as folder:
+ for name, image in (("signature", signature), ("letter", letter)):
+ path = Path(folder) / f"{name}.png"
+ image.save(path)
+ storage.upload(f"{prefix}/{name}.png", path, "image/png")
+ return f"{prefix}/signature.png", f"{prefix}/letter.png"
+
+
[email protected]("/authorization", response_model=dict)
+async def status(db: DB, user: Actor):
+ return {"template": {"version": VERSION, "title": TITLE, "body": BODY}, "current": summary(await current(db, user.id))}
+
+
[email protected]("/authorization", response_model=dict, dependencies=[Depends(storage_ready)])
+async def sign(body: SignInput, request: Request, db: DB, user: Actor):
+ if body.template_version != VERSION:
+ fail("授权条款已更新,请刷新后重新阅读并签署", 409)
+ existing = await current(db, user.id)
+ if existing:
+ return summary(existing)
+ signed_at = now()
+ signature_key, letter_key = await asyncio.to_thread(render_and_store, body, signed_at.isoformat(), user.id)
+ item = Authorization(owner_id=user.id, template_version=VERSION, signer_name=body.signer_name,
+ body=BODY, body_hash=hashlib.sha256(BODY.encode()).hexdigest(), signature_key=signature_key,
+ letter_key=letter_key, created_at=signed_at, client_ip=(request.client.host if request.client else "")[:64],
+ user_agent=request.headers.get("user-agent", "")[:512])
+ db.add(item)
+ try:
+ await db.flush()
+ event(db, user.id, "authorization", item.id, "signed", version=1)
+ await db.commit()
+ except IntegrityError:
+ await db.rollback()
+ existing = await current(db, user.id)
+ if existing:
+ return summary(existing)
+ raise
+ return summary(item)
+
+
[email protected]("/authorizations/{record_id}/letter", response_model=dict, dependencies=[Depends(storage_ready)])
+async def letter(record_id: int, db: DB, user: Actor):
+ item = await db.get(Authorization, record_id)
+ if not item or (item.owner_id != user.id and user.role != "admin"):
+ fail("授权函不存在或无权查看", 404)
+ url = await asyncio.to_thread(storage.signed, item.letter_key, "image/png")
+ event(db, user.id, "authorization", item.id, "read")
+ await db.commit()
+ return {"url": url, "expires_in": get_marketplace_settings().signed_url_seconds}
diff --git a/backend/app/marketplace/bootstrap.py b/backend/app/marketplace/bootstrap.py
new file mode 100644
index 0000000..bf3f671
--- /dev/null
+++ b/backend/app/marketplace/bootstrap.py
@@ -0,0 +1,40 @@
+"""唯一的原项目接入点:能力发现、路由挂载和独立表初始化。"""
+from fastapi import Depends, FastAPI
+
+from .config import get_marketplace_settings
+
+
+def 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
+ from app.config import get_settings
+ settings = 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 .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):
+ 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
+ await stop_marketplace_runtime()
diff --git a/backend/app/marketplace/categories.py b/backend/app/marketplace/categories.py
new file mode 100644
index 0000000..d705462
--- /dev/null
+++ b/backend/app/marketplace/categories.py
@@ -0,0 +1,18 @@
+"""作品分类由管理员维护;历史作品的分类文字不批量改写。"""
+from .models import CategoryConfig
+from .service import fail
+
+DEFAULT_CATEGORIES = ["短片", "广告", "动画", "文旅", "科普", "其他"]
+
+
+async def category_config(db):
+ item = await db.get(CategoryConfig, 1)
+ return {"version": item.version, "names": item.names} if item else {"version": 0, "names": DEFAULT_CATEGORIES}
+
+
+async def validate_category(db, name, previous=None):
+ if name == previous:
+ return
+ config = await category_config(db)
+ if name not in config["names"]:
+ fail("该作品分类未启用,请刷新后选择管理员配置的分类")
diff --git a/backend/app/marketplace/commerce.py b/backend/app/marketplace/commerce.py
new file mode 100644
index 0000000..792ee23
--- /dev/null
+++ b/backend/app/marketplace/commerce.py
@@ -0,0 +1,268 @@
+"""市场平台投放订单、永久权益和收益账本。"""
+from __future__ import annotations
+
+import time
+import uuid
+from datetime import datetime, timezone
+
+from fastapi import APIRouter, Query, Request
+from fastapi.responses import PlainTextResponse
+from sqlalchemy import func, select
+
+from app.config import get_settings
+from app.services import epay
+from . import storage
+from .dependencies import Actor, DB, Visitor, storage_ready
+from .models import Asset, ContentOrder, Entitlement, Publication, RevenueConfig, RevenueLedger, SeriesEpisode, Work
+from .schemas import ContentOrderInput
+from .service import data, fail, now
+
+router = APIRouter()
+
+
+def _client_ip(request: Request) -> str:
+ return (request.headers.get("x-forwarded-for") or request.headers.get("x-real-ip") or (request.client.host if request.client else "127.0.0.1")).split(",")[0].strip()
+
+
+def _payment_ready() -> bool:
+ settings = get_settings()
+ return bool(settings.epay_pid and settings.epay_key and settings.epay_api_url)
+
+
+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)
+
+
+async def _signed_hls_manifest(publication: Publication) -> str:
+ """重写私有 HLS 分片为短时签名 URL,避免仅签 manifest 后分片 403。"""
+ if not publication.playback_manifest_key:
+ fail("MARKETPLACE_EPISODE_NOT_READY", 409)
+ raw = await __import__("asyncio").to_thread(storage.read, publication.playback_manifest_key)
+ text = raw.decode("utf-8")
+ prefix = publication.playback_manifest_key.rsplit("/", 1)[0] + "/"
+ rewritten: list[str] = []
+ for line in text.splitlines():
+ value = line.strip()
+ if not value or value.startswith("#") or value.startswith(("http://", "https://")):
+ rewritten.append(line)
+ continue
+ # 只允许 Worker 生成目录中的相对分片,拒绝路径穿越或外部 URI。
+ if value.startswith("/") or ".." in value.split("/"):
+ fail("播放清单无效", 502)
+ key = prefix + value
+ signed = await __import__("asyncio").to_thread(storage.signed, key, "video/mp2t")
+ rewritten.append(signed)
+ return "\n".join(rewritten) + "\n"
+
+
[email protected]("/platform/feed", response_model=dict)
+async def platform_feed(db: DB, page: int = Query(1, ge=1), page_size: int = Query(20, ge=1, le=100)):
+ filters = (
+ Publication.audit_status == "approved",
+ Publication.listed.is_(True),
+ Publication.sale_type == "platform_unlock",
+ Publication.playback_status == "done",
+ Publication.playback_manifest_key.is_not(None),
+ )
+ query = select(Publication).where(*filters).order_by(Publication.id.desc())
+ rows = list((await db.execute(query.offset((page - 1) * page_size).limit(page_size))).scalars().all())
+ total = (await db.execute(select(func.count()).select_from(Publication).where(*filters))).scalar_one()
+ return {"items": [data(row, "id", "content_type", "content_id", "version", "sale_type", "copyright_price_fen", "unlock_price_fen", "share_bps", "created_at") for row in rows], "meta": {"page": page, "page_size": page_size, "total": total}}
+
+
[email protected]("/platform/episodes/{episode_id}", response_model=dict)
+async def platform_episode(episode_id: int, db: DB, user: Visitor):
+ episode = await db.get(SeriesEpisode, episode_id)
+ if not episode:
+ fail("分集不存在", 404)
+ publication = (await db.execute(select(Publication).where(
+ Publication.content_type == "series_episode", Publication.content_id == episode.id,
+ 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":
+ 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)}
+
+
[email protected]("/platform/works/{work_id}", response_model=dict)
+async def platform_work(work_id: int, db: DB, user: Visitor):
+ """单视频平台投放详情;与剧集分集使用相同的发布版本和永久权益模型。"""
+ work = await db.get(Work, work_id)
+ if not work:
+ fail("作品不存在", 404)
+ publication = (await db.execute(select(Publication).where(
+ 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":
+ 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)}
+
+
[email protected]("/content-orders", response_model=dict)
+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):
+ 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}
+ 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)
+ await db.commit()
+ try:
+ notify_url = f"{get_settings().public_base_url.rstrip('/')}/api/marketplace/payments/epay/notify"
+ mapi = await epay.create_mapi_payment(out_trade_no=out_trade_no, name=f"数字资产-{publication.content_id}", money_yuan=epay.money_yuan_from_fen(order.amount_fen), pay_type=body.pay_type, clientip=_client_ip(request), notify_url=notify_url)
+ fields = epay.build_submit_fields(out_trade_no=out_trade_no, name=f"数字资产-{publication.content_id}", money_yuan=epay.money_yuan_from_fen(order.amount_fen), pay_type=body.pay_type, clientip=_client_ip(request), notify_url=notify_url)
+ except ValueError as exc:
+ await db.execute(select(ContentOrder).where(ContentOrder.id == order.id).with_for_update())
+ order.status = "failed"
+ await db.commit()
+ fail(str(exc), 503)
+ return {"out_trade_no": order.out_trade_no, "status": order.status, "amount_fen": order.amount_fen, "pay_type": order.pay_type, "trade_no": mapi.get("trade_no") or "", "qrcode": mapi.get("qrcode") or "", "payurl": mapi.get("payurl") or "", "qr_payload": mapi.get("qr_payload") or "", "pay_mode": mapi.get("pay_mode") or "redirect", "submit_url": epay.submit_url(fields)}
+
+
[email protected]("/content-orders/{out_trade_no}", response_model=dict)
+async def get_content_order(out_trade_no: str, db: DB, user: Actor):
+ order = (await db.execute(select(ContentOrder).where(ContentOrder.out_trade_no == out_trade_no, ContentOrder.user_id == user.id))).scalar_one_or_none()
+ if not order:
+ fail("订单不存在", 404)
+ return data(order, "out_trade_no", "publication_id", "episode_id", "amount_fen", "pay_type", "status", "trade_no", "paid_at", "created_at")
+
+
[email protected]("/entitlements", response_model=dict)
+async def list_entitlements(db: DB, user: Actor):
+ rows = list((await db.execute(select(Entitlement, Publication).join(Publication, Publication.id == Entitlement.publication_id).where(Entitlement.user_id == user.id, Entitlement.active.is_(True)).order_by(Entitlement.id.desc()))).all())
+ return {"items": [{**data(entitlement, "id", "publication_id", "episode_id", "created_at"), **data(publication, "content_type", "content_id", "version", "unlock_price_fen")} for entitlement, publication in rows]}
+
+
[email protected]("/platform/episodes/{episode_id}/playback", response_model=dict, dependencies=[])
+async def episode_playback(episode_id: int, db: DB, user: Actor):
+ episode = await db.get(SeriesEpisode, episode_id)
+ if not episode:
+ fail("分集不存在", 404)
+ publication = (await db.execute(select(Publication).where(
+ Publication.content_type == "series_episode", Publication.content_id == episode.id,
+ 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":
+ 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}
+
+
[email protected]("/platform/works/{work_id}/playback", response_model=dict, dependencies=[])
+async def work_playback(work_id: int, db: DB, user: Actor):
+ work = await db.get(Work, work_id)
+ if not work:
+ fail("作品不存在", 404)
+ publication = (await db.execute(select(Publication).where(
+ 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":
+ 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}
+
+
+def _notify_success(params: dict[str, str]) -> bool:
+ return str(params.get("trade_status") or params.get("status") or "").upper() in {"TRADE_SUCCESS", "SUCCESS", "1"}
+
+
[email protected]_route("/payments/epay/notify", methods=["GET", "POST"])
+async def epay_notify(request: Request, db: DB) -> PlainTextResponse:
+ if request.method == "POST":
+ form = await request.form()
+ params = {key: str(value) for key, value in form.items()}
+ else:
+ params = {key: str(value) for key, value in request.query_params.items()}
+ if not epay.verify(params):
+ return PlainTextResponse("fail", status_code=400)
+ if not _notify_success(params):
+ return PlainTextResponse("success")
+ trade_no = str(params.get("out_trade_no") or "")
+ order = (await db.execute(select(ContentOrder).where(ContentOrder.out_trade_no == trade_no).with_for_update())).scalar_one_or_none()
+ 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
+ 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)
+ # 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
+ # a second entitlement or revenue ledger row.
+ 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)
+ 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)
+ if share is None:
+ return PlainTextResponse("fail", status_code=409)
+ platform_fen = order.amount_fen * int(share) // 10000
+ ledger = 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)
+ await db.commit()
+ return PlainTextResponse("success")
+
diff --git a/backend/app/marketplace/config.py b/backend/app/marketplace/config.py
new file mode 100644
index 0000000..6c0be42
--- /dev/null
+++ b/backend/app/marketplace/config.py
@@ -0,0 +1,30 @@
+"""下游独立配置;未配置 OSS 时禁止存储降级。"""
+from functools import lru_cache
+from pathlib import Path
+
+from pydantic import Field
+from pydantic_settings import BaseSettings, SettingsConfigDict
+
+
+class MarketplaceSettings(BaseSettings):
+ """只读取 MARKETPLACE_ 命名空间,保留上游配置语义。"""
+
+ model_config = SettingsConfigDict(
+ env_prefix="MARKETPLACE_", extra="ignore",
+ env_file=Path(__file__).resolve().parents[2] / ".env", env_file_encoding="utf-8",
+ )
+ enabled: bool = False
+ signed_url_seconds: int = Field(300, ge=30, le=300)
+ max_video_bytes: int = Field(500 * 1024 * 1024, gt=0)
+ max_document_bytes: int = Field(20 * 1024 * 1024, gt=0)
+ max_duration_seconds: int = Field(1800, gt=0)
+ part_size: int = Field(8 * 1024 * 1024, ge=1024 * 1024, le=16 * 1024 * 1024)
+ watermark_font: str = "C:/Windows/Fonts/msyh.ttc"
+ worker_poll_seconds: float = Field(3, ge=1)
+ worker_max_attempts: int = Field(3, ge=1, le=5)
+
+
+@lru_cache
+def get_marketplace_settings() -> MarketplaceSettings:
+ """缓存独立配置;生产使用环境变量,本地可保持为空。"""
+ return MarketplaceSettings()
diff --git a/backend/app/marketplace/dependencies.py b/backend/app/marketplace/dependencies.py
new file mode 100644
index 0000000..4a52fc5
--- /dev/null
+++ b/backend/app/marketplace/dependencies.py
@@ -0,0 +1,36 @@
+"""复用现有身份,只增加下游开关与文件服务依赖。"""
+import asyncio
+from typing import Annotated
+
+from fastapi import Depends, HTTPException
+from fastapi.security import HTTPAuthorizationCredentials
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.database import get_db
+from app.deps import get_current_admin, get_current_user, security, _user_from_bearer
+from app.models import User
+from .config import get_marketplace_settings
+from . import storage
+
+DB = Annotated[AsyncSession, Depends(get_db)]
+Actor = Annotated[User, Depends(get_current_user)]
+Admin = Annotated[User, Depends(get_current_admin)]
+
+
+def enabled() -> None:
+ """关闭时不允许通过直接 URL 进入下游接口。"""
+ if not get_marketplace_settings().enabled:
+ raise HTTPException(404, "下游业务未启用")
+
+
+async def storage_ready() -> None:
+ """在异步请求外核验 OSS,禁止阻塞事件循环。"""
+ await asyncio.to_thread(storage.bucket)
+
+
+async def optional_user(db: DB, creds: Annotated[HTTPAuthorizationCredentials | None, Depends(security)]) -> User | None:
+ """公开详情允许访客,私密访问仍要求有效用户。"""
+ return await _user_from_bearer(db, creds.credentials) if creds else None
+
+
+Visitor = Annotated[User | None, Depends(optional_user)]
diff --git a/backend/app/marketplace/handoff.py b/backend/app/marketplace/handoff.py
new file mode 100644
index 0000000..d930191
--- /dev/null
+++ b/backend/app/marketplace/handoff.py
@@ -0,0 +1,518 @@
+"""把 PrintFilm 成片异步复制到市场前缀。
+
+接口只接受项目或分集编号。视频地址由服务端读取并记在转存记录里,
+复制、指纹和探测由现有市场 Worker 完成,不在请求里下载整段视频。
+"""
+from __future__ import annotations
+
+import asyncio
+from datetime import timedelta
+import hashlib
+import logging
+from pathlib import Path
+from urllib.parse import unquote, urlparse
+import uuid
+
+from fastapi import APIRouter, HTTPException
+from sqlalchemy import and_, func, or_, select, update
+from sqlalchemy.exc import IntegrityError
+
+from app.database import AsyncSessionLocal
+from app.models import Project
+from app.models_drama import DramaEpisode, DramaEpisodeFragment, DramaProject
+from .authorization import current as current_authorization
+from .categories import category_config
+from .config import get_marketplace_settings
+from .dependencies import Actor, DB, storage_ready
+from .models import Asset, Handoff, SeriesEpisode, Work
+from .schemas import PrintfilmEpisodeInput, PrintfilmWorkInput
+from .service import data, fail, notify, now
+
+logger = logging.getLogger("marketplace.handoff")
+router = APIRouter()
+VIDEO_LIMIT = 2 * 1024 * 1024 * 1024
+IMAGE_LIMIT = 20 * 1024 * 1024
+_VIDEO_TYPES = {".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".mkv": "video/x-matroska"}
+_IMAGE_TYPES = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp"}
+
+
+def object_key(locator: str, *, bucket: str, public_base: str, folder: str) -> str | None:
+ """从本站 OSS 地址或对象键取出同桶复制用的 key;本地地址不在这里解析。"""
+ text = (locator or "").strip()
+ if not text or text.startswith("/static/") or text.startswith("marketplace/"):
+ return None
+ if text.startswith(("http://", "https://")):
+ parsed = urlparse(text)
+ path = unquote(parsed.path).lstrip("/")
+ host = parsed.netloc.split("@")[-1]
+ if bucket and host.startswith(f"{bucket}."):
+ return path or None
+ if bucket and path.startswith(f"{bucket}/"):
+ path = path[len(bucket) + 1 :]
+ return path or None
+ base = public_base.rstrip("/")
+ bare = text.split("?", 1)[0]
+ if bare.startswith(base + "/"):
+ return unquote(bare[len(base) + 1 :]) or None
+ marker = f"/{folder.strip('/')}/"
+ index = parsed.path.find(marker)
+ if index >= 0:
+ return unquote(parsed.path[index + 1 :].split("?", 1)[0]) or None
+ return None
+ key = text.split("?", 1)[0].lstrip("/")
+ if not key or key.startswith("marketplace/") or key.startswith("static/"):
+ return None
+ prefix = folder.strip("/")
+ if prefix and not key.startswith(prefix + "/") and "/" not in key:
+ key = f"{prefix}/{key}"
+ return key
+
+
+def _version(marker: str, locator: str) -> str:
+ digest = hashlib.sha256(locator.encode()).hexdigest()[:16]
+ return f"{marker}:{digest}"[:80]
+
+
+def _item_key(prefix: str, source_kind: str, source_id: int, version: str) -> str:
+ raw = f"{prefix}:{source_kind}:{source_id}" if prefix else f"{source_kind}:{source_id}:{version}"
+ return raw if len(raw) <= 120 else hashlib.sha256(raw.encode()).hexdigest()
+
+
+def _suffix(locator: str, default: str) -> str:
+ suffix = Path(locator.split("?", 1)[0]).suffix.lower()
+ if suffix in _VIDEO_TYPES or suffix in _IMAGE_TYPES:
+ return suffix
+ return default
+
+
+def _content_type(suffix: str, default: str) -> str:
+ return _VIDEO_TYPES.get(suffix) or _IMAGE_TYPES.get(suffix) or default
+
+
+def _local_file(locator: str) -> Path | None:
+ """只接受 static 目录内的成片,避免按任意本地路径读取。"""
+ from app.services import storage as upstream
+
+ local = upstream.local_path_from_url(locator)
+ if local and local.is_file():
+ return local
+ candidate = Path(locator)
+ if not candidate.is_absolute() or not candidate.is_file():
+ return None
+ try:
+ relative = candidate.resolve().relative_to(upstream.STATIC_ROOT.resolve())
+ except ValueError:
+ return None
+ resolved = upstream.STATIC_ROOT / relative
+ return resolved if resolved.is_file() else None
+
+
+def place_object(locator: str, dest_key: str, content_type: str, limit: int) -> int:
+ """同桶复制,或由服务器读取本地成片后上传。不向浏览器返回源地址。"""
+ from app.config import get_settings
+ from app.services import oss as upstream_oss
+ from . import storage
+
+ local = _local_file(locator)
+ if local:
+ size = local.stat().st_size
+ if size <= 0 or size > limit:
+ raise ValueError("成片大小无效或超过限制")
+ storage.upload(dest_key, local, content_type)
+ return size
+ settings = get_settings()
+ key = object_key(locator, bucket=settings.oss_bucket, public_base=upstream_oss.public_base(), folder=upstream_oss.folder_prefix())
+ if not key:
+ raise ValueError("成片尚未就绪")
+ size = storage.copy_private(key, dest_key, content_type)
+ if size <= 0 or size > limit:
+ raise ValueError("成片大小无效或超过限制")
+ return size
+
+
+async def _view(db, item: Handoff) -> dict:
+ """给页面的状态。不返回源地址、对象键或指纹原文以外的内部快照。"""
+ authorization = await current_authorization(db, item.owner_id)
+ ready = bool(authorization)
+ if item.status == "failed":
+ label = "复制失败可重试"
+ elif item.status == "ready":
+ label = "已就绪" if ready else "待补充授权"
+ 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 "",
+ 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
+
+
+async def _owned_handoff(db, handoff_id: int, user) -> Handoff:
+ item = await db.get(Handoff, handoff_id)
+ if not item or item.owner_id != user.id:
+ fail("转存记录不存在", 404)
+ return item
+
+
+async def _find(db, owner_id: int, key: str) -> Handoff | None:
+ return (await db.execute(select(Handoff).where(Handoff.owner_id == owner_id, Handoff.idempotency_key == key))).scalar_one_or_none()
+
+
+async def _category(db, preferred: str) -> str:
+ names = (await category_config(db))["names"]
+ if preferred in names:
+ return preferred
+ if "其他" in names:
+ return "其他"
+ return names[0] if names else "其他"
+
+
+def _clip(value: str, limit: int) -> str:
+ return (value or "").strip()[:limit]
+
+
+async def _project_source(db, user_id: int, project_id: int) -> tuple[Project, str]:
+ project = await db.get(Project, project_id)
+ if not project or project.user_id != user_id:
+ fail("成片不存在或无权访问", 404)
+ locator = (project.final_video_url or "").strip()
+ if not locator:
+ fail("成片尚未生成", 409)
+ return 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
+
+
+def _handoff(owner_id: int, key: str, source_kind: str, source_id: int, version: str, target_kind: str, target_id: int, series_id: int | None, locator: str, cover: str, title: str) -> Handoff:
+ return Handoff(owner_id=owner_id, idempotency_key=key, source_kind=source_kind, source_id=source_id, source_version=version,
+ target_kind=target_kind, target_id=target_id, series_id=series_id, status="pending",
+ source_snapshot={"locator": locator, "cover_locator": cover, "title": title})
+
+
[email protected]("/printfilm/sources", response_model=dict)
+async def printfilm_sources(db: DB, user: Actor):
+ """只列出当前用户已经生成成片的科普项目和漫剧分集,不返回视频地址。"""
+ from .series import import_sources
+
+ projects = list((await db.execute(select(Project).where(Project.user_id == user.id, Project.final_video_url.is_not(None), Project.final_video_url != "").order_by(Project.updated_at.desc()).limit(50))).scalars().all())
+ dramas = await import_sources(db, user)
+ return {"projects": [{"id": item.id, "title": item.title, "updated_at": item.updated_at, "has_cover": bool(item.cover_url), "status": item.status} for item in projects], "dramas": dramas["items"]}
+
+
[email protected]("/works/from-printfilm", response_model=dict)
+async def work_from_printfilm(body: PrintfilmWorkInput, db: DB, user: Actor):
+ """把一部科普成片登记为市场草稿。同一成片版本重复点击返回原来的草稿。"""
+ await storage_ready()
+ project, locator = await _project_source(db, user.id, body.project_id)
+ version = _version(project.updated_at.isoformat(), locator)
+ key = _item_key(body.idempotency_key.strip(), "project_final", project.id, version)
+ existing = await _find(db, user.id, key)
+ if existing:
+ return await _view(db, existing)
+ work = Work(owner_id=user.id, title=_clip(project.title or "未命名作品", 200) or "未命名作品", description=_clip(project.source_text or "", 5000),
+ category=await _category(db, "科普"), price_fen=0, sale_type="copyright_contact", source="printfilm", audit_status="draft")
+ db.add(work)
+ await db.flush()
+ db.add(_handoff(user.id, key, "project_final", project.id, version, "work", work.id, None, locator, (project.cover_url or "").strip(), work.title))
+ try:
+ await db.commit()
+ except IntegrityError:
+ await db.rollback()
+ existing = await _find(db, user.id, key)
+ if existing:
+ return await _view(db, existing)
+ raise
+ created = await _find(db, user.id, key)
+ return await _view(db, created)
+
+
+async def enqueue_series_import(series_id: int, body: PrintfilmEpisodeInput, db, user) -> dict:
+ """把选中的漫剧分集或一部科普成片登记为短剧分集,实际复制交给 Worker。"""
+ await storage_ready()
+ from .series import _episode_data, _series
+
+ series = await _series(db, series_id, user, lock=True)
+ if series.owner_id != user.id:
+ fail("只能导入到自己的短剧", 403)
+ jobs: list[tuple[str, str, int, str, str, str, str]] = []
+ if body.project_id:
+ 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
+ for key, source_kind, source_id, version, locator, cover, title in jobs:
+ existing = await _find(db, user.id, key)
+ if existing:
+ if existing.target_kind == "series_episode" and existing.series_id == series.id:
+ episode = await db.get(SeriesEpisode, existing.target_id)
+ if episode:
+ created.append(episode)
+ records.append(existing)
+ continue
+ episode_no = await _next_no(db, series.id)
+ item = SeriesEpisode(series_id=series.id, owner_id=user.id, episode_no=episode_no, title=title or f"第{episode_no}集", source="printfilm", source_type="drama_import",
+ source_snapshot={"source_kind": source_kind, "source_id": source_id, "source_title": title})
+ db.add(item)
+ await db.flush()
+ handoff = _handoff(user.id, key, source_kind, source_id, version, "series_episode", item.id, series.id, locator, cover, item.title)
+ db.add(handoff)
+ created.append(item)
+ records.append(handoff)
+ added = True
+ if added:
+ series.version += 1
+ series.audit_status, series.listed = "draft", False
+ try:
+ await db.commit()
+ except IntegrityError:
+ await db.rollback()
+ records = []
+ created = []
+ for key, *_rest in jobs:
+ existing = await _find(db, user.id, key)
+ if not existing:
+ continue
+ records.append(existing)
+ episode = await db.get(SeriesEpisode, existing.target_id) if existing.target_kind == "series_episode" else None
+ if episode and episode.series_id == series.id:
+ created.append(episode)
+ return {"items": [await _episode_data(db, item, private=True) for item in created], "handoffs": [await _view(db, item) for item in records]}
+
+
[email protected]("/series/{series_id}/episodes/import-printfilm", response_model=dict)
+async def import_printfilm(series_id: int, body: PrintfilmEpisodeInput, db: DB, user: Actor):
+ """明确选中的漫剧分集,或一部科普成片,转成短剧分集草稿。"""
+ return await enqueue_series_import(series_id, body, db, user)
+
+
[email protected]("/handoffs/{handoff_id}", response_model=dict)
+async def get_handoff(handoff_id: int, db: DB, user: Actor):
+ """查看自己的转存进度。"""
+ return await _view(db, await _owned_handoff(db, handoff_id, user))
+
+
[email protected]("/handoffs", response_model=dict)
+async def list_handoffs(db: DB, user: Actor, target_kind: str = "", target_id: int = 0, series_id: int = 0):
+ """按作品、分集或系列查看当前用户的转存进度。"""
+ query = select(Handoff).where(Handoff.owner_id == user.id)
+ if target_kind and target_id:
+ query = query.where(Handoff.target_kind == target_kind, Handoff.target_id == target_id)
+ if series_id:
+ query = query.where(Handoff.series_id == series_id)
+ rows = list((await db.execute(query.order_by(Handoff.id.desc()).limit(50))).scalars().all())
+ return {"items": [await _view(db, item) for item in rows]}
+
+
[email protected]("/handoffs/{handoff_id}/retry", response_model=dict)
+async def retry_handoff(handoff_id: int, db: DB, user: Actor):
+ """失败后重新排队。已复制完成的记录保持不变。"""
+ await storage_ready()
+ item = await _owned_handoff(db, handoff_id, user)
+ if item.status != "failed":
+ return await _view(db, item)
+ item.status, item.error, item.attempts = "pending", "", 0
+ item.lease_token, item.lease_until = None, None
+ await db.commit()
+ return await _view(db, item)
+
+
+async def _claim() -> tuple[int, str] | None:
+ async with AsyncSessionLocal() as db:
+ query = select(Handoff).where(or_(Handoff.status == "pending", and_(Handoff.status == "running", Handoff.lease_until < now()))).order_by(Handoff.id).with_for_update(skip_locked=True).limit(1)
+ item = (await db.execute(query)).scalar_one_or_none()
+ if not item:
+ return None
+ if item.attempts >= get_marketplace_settings().worker_max_attempts:
+ item.status = "failed"
+ item.error = item.error or "复制重试次数已用完,请稍后重试"
+ link = f"/marketplace/works/{item.target_id}/edit?handoff={item.id}" if item.target_kind == "work" else f"/marketplace/series/{item.series_id}/edit"
+ notify(db, item.owner_id, "成片复制失败,可在发布页重试", link)
+ await db.commit()
+ return None
+ item.attempts += 1
+ item.status, item.lease_token, item.lease_until = "running", uuid.uuid4().hex, now() + timedelta(minutes=15)
+ item.error = ""
+ await db.commit()
+ return item.id, item.lease_token
+
+
+async def _heartbeat(handoff_id: int, token: str) -> None:
+ while True:
+ await asyncio.sleep(20)
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(update(Handoff).where(Handoff.id == handoff_id, Handoff.lease_token == token, Handoff.status == "running").values(lease_until=now() + timedelta(minutes=15)))
+ await db.commit()
+ if not result.rowcount:
+ raise RuntimeError("转存任务租约已丢失")
+
+
+async def _fail(handoff_id: int, token: str, message: str) -> None:
+ async with AsyncSessionLocal() as db:
+ 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
+ item.status = "failed" if terminal else "pending"
+ item.error = message[:500]
+ item.lease_token, item.lease_until = None, None
+ if item.asset_id:
+ asset = await db.get(Asset, item.asset_id)
+ if asset and asset.status == "processing":
+ asset.status, asset.error = "failed", message[:500]
+ if terminal:
+ link = f"/marketplace/works/{item.target_id}/edit?handoff={item.id}" if item.target_kind == "work" else f"/marketplace/series/{item.series_id}/edit"
+ notify(db, item.owner_id, "成片复制失败,可在发布页重试", link)
+ await db.commit()
+
+
+async def _store_cover(locator: str, owner_id: int, folder: str) -> tuple[str, int, str] | None:
+ if not locator:
+ return None
+ suffix = _suffix(locator, "")
+ if suffix not in _IMAGE_TYPES:
+ return None
+ key = f"{folder}/cover-{uuid.uuid4().hex}{suffix}"
+ try:
+ size = await asyncio.to_thread(place_object, locator, key, _content_type(suffix, "image/png"), IMAGE_LIMIT)
+ except Exception:
+ logger.info("市场转存封面跳过")
+ return None
+ return key, size, _content_type(suffix, "image/png")
+
+
+async def _copy(handoff_id: int, token: str) -> None:
+ """复制到 marketplace/ 后探测时长和指纹,再把资产标为 ready。"""
+ 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
+ snapshot = dict(item.source_snapshot or {})
+ owner_id, target_kind, target_id = item.owner_id, item.target_kind, item.target_id
+ if item.asset_id:
+ asset = await db.get(Asset, item.asset_id)
+ if asset and asset.status == "ready":
+ await _bind(db, item, asset.id, None)
+ item.status, item.error = "ready", ""
+ item.lease_token, item.lease_until = None, None
+ await db.commit()
+ return
+ if asset and asset.status == "processing":
+ asset.status, asset.error = "failed", "已重新复制"
+ await db.commit()
+ locator = str(snapshot.get("locator") or "")
+ suffix = _suffix(locator, ".mp4")
+ content_type = _content_type(suffix, "video/mp4")
+ folder = f"marketplace/{'works' if target_kind == 'work' else 'series'}/u{owner_id}/{target_id}"
+ dest = f"{folder}/{uuid.uuid4().hex}{suffix}"
+ try:
+ size = await asyncio.to_thread(place_object, locator, dest, content_type, VIDEO_LIMIT)
+ except HTTPException:
+ await _fail(handoff_id, token, "文件服务暂未配置或不可用")
+ return
+ except ValueError as exc:
+ await _fail(handoff_id, token, str(exc))
+ return
+ except Exception:
+ logger.exception("marketplace handoff %s copy failed", handoff_id)
+ await _fail(handoff_id, token, "复制成片失败,请稍后重试")
+ return
+ filename = f"{_clip(str(snapshot.get('title') or 'video'), 80) or 'video'}{suffix}"
+ async with AsyncSessionLocal() as db:
+ 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
+ asset = Asset(owner_id=owner_id, kind="video", filename=filename[:255], content_type=content_type, size_bytes=size, object_key=dest, status="processing")
+ db.add(asset)
+ await db.flush()
+ item.asset_id = asset.id
+ asset_id = asset.id
+ probe = {"id": asset.id, "filename": asset.filename, "object_key": dest, "kind": "video", "size_bytes": size, "content_type": content_type}
+ await db.commit()
+ from .worker import process_asset
+ try:
+ result = await process_asset(probe)
+ except ValueError as exc:
+ await _fail(handoff_id, token, str(exc))
+ return
+ except Exception:
+ logger.exception("marketplace handoff %s probe failed", handoff_id)
+ await _fail(handoff_id, token, "成片无法解析,请确认文件完整后重试")
+ return
+ cover = await _store_cover(str(snapshot.get("cover_locator") or ""), owner_id, folder)
+ async with AsyncSessionLocal() as db:
+ item = (await db.execute(select(Handoff).where(Handoff.id == handoff_id, Handoff.lease_token == token).with_for_update())).scalar_one_or_none()
+ asset = await db.get(Asset, asset_id) if item else None
+ if not item or not asset:
+ return
+ asset.fingerprint = str(result.get("fingerprint") or "")
+ asset.duration_seconds = result.get("duration_seconds")
+ asset.status, asset.error = "ready", ""
+ item.source_fingerprint = asset.fingerprint
+ cover_id = None
+ if cover:
+ cover_asset = Asset(owner_id=owner_id, kind="image", filename=f"cover{Path(cover[0]).suffix}", content_type=cover[2], size_bytes=cover[1], object_key=cover[0], status="ready")
+ db.add(cover_asset)
+ await db.flush()
+ cover_id = cover_asset.id
+ await _bind(db, item, asset.id, cover_id)
+ item.status, item.error = "ready", ""
+ item.lease_token, item.lease_until = None, None
+ await db.commit()
+
+
+async def _bind(db, item: Handoff, asset_id: int, cover_id: int | None) -> None:
+ """把就绪资产挂到草稿上;不改审核状态,也不生成水印。"""
+ if item.target_kind == "work":
+ work = await db.get(Work, item.target_id)
+ if work and work.owner_id == item.owner_id:
+ work.asset_id = asset_id
+ if cover_id and not work.cover_asset_id:
+ work.cover_asset_id = cover_id
+ return
+ episode = await db.get(SeriesEpisode, item.target_id)
+ if episode and episode.owner_id == item.owner_id:
+ episode.asset_id = asset_id
+ if cover_id and not episode.cover_asset_id:
+ episode.cover_asset_id = cover_id
+
+
+async def run_handoff_once() -> bool:
+ """领取一条转存。没有待处理记录时返回 False。"""
+ claimed = await _claim()
+ if not claimed:
+ return False
+ handoff_id, token = claimed
+ pulse = asyncio.create_task(_heartbeat(handoff_id, token))
+ try:
+ await _copy(handoff_id, token)
+ 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)
+ return True
diff --git a/backend/app/marketplace/media.py b/backend/app/marketplace/media.py
new file mode 100644
index 0000000..6ff7180
--- /dev/null
+++ b/backend/app/marketplace/media.py
@@ -0,0 +1,129 @@
+"""按业务上下文签名;不根据调用者提供的 OSS key 发放链接。"""
+import asyncio
+
+from fastapi import APIRouter, Depends
+from sqlalchemy import select
+
+from . import storage
+from .config import get_marketplace_settings
+from .dependencies import DB, Visitor, storage_ready
+from .models import Asset, EpisodePreview, Publication, Recruit, Rights, Series, SeriesEpisode, Submission, Support, Work
+from .service import event, fail, is_public_work, recruit_open, rights_for, rights_valid, submission_rights_match
+
+router = APIRouter()
+
+
[email protected]("/media/{kind}/{record_id}/{purpose}", response_model=dict, dependencies=[Depends(storage_ready)])
+async def media_url(kind: str, record_id: int, purpose: str, db: DB, user: Visitor):
+ """每次签名前鉴权;签名最长5分钟,既有链接不能即时撤回。"""
+ asset, key, content_type = None, None, "video/mp4"
+ admin = bool(user and user.role == "admin")
+ if kind == "work":
+ work = await db.get(Work, record_id)
+ if not work or purpose not in ("preview", "cover"):
+ fail("媒体不存在", 404)
+ owner = bool(user and work.owner_id == user.id)
+ if not admin and (work.blocked or (not owner and not await is_public_work(db, record_id))):
+ fail("作品未公开或已下架", 404)
+ asset = await db.get(Asset, work.asset_id) if work.asset_id else None
+ if purpose == "preview" and asset:
+ # 广场播放只签发水印文件。作者和管理员查看原片走 asset 接口。
+ from .previews import is_watermark_key, preview_for
+ preview = await preview_for(db, work)
+ if not preview or preview.status != "done" or not is_watermark_key(preview.object_key):
+ fail("水印播放文件尚未生成,暂不可播放", 409)
+ key, content_type = preview.object_key, "video/mp4"
+ if purpose == "cover" and work.cover_asset_id:
+ asset = await db.get(Asset, work.cover_asset_id)
+ elif kind == "series_episode":
+ episode = await db.get(SeriesEpisode, record_id)
+ series = await db.get(Series, episode.series_id) if episode else None
+ if not episode or not series or purpose not in ("preview", "cover"):
+ fail("媒体不存在", 404)
+ owner = bool(user and episode.owner_id == user.id)
+ public = bool(series.listed and series.audit_status == "approved" and episode.listed and episode.audit_status == "approved" and not series.blocked and not episode.blocked)
+ if not admin and not owner and not public:
+ fail("媒体未公开或已下架", 404)
+ if purpose == "cover":
+ asset = await db.get(Asset, episode.cover_asset_id or series.cover_asset_id) if (episode.cover_asset_id or series.cover_asset_id) else None
+ else:
+ asset = await db.get(Asset, episode.asset_id) if episode.asset_id else None
+ # Paid episodes never fall back to the original object. A legacy
+ # row may still have preview_status="none"; that must be treated as
+ # not-ready and return 409 below rather than leaking the source.
+ from .previews import is_watermark_key
+ preview = (await db.execute(select(EpisodePreview).where(
+ EpisodePreview.episode_id == episode.id, EpisodePreview.asset_id == episode.asset_id,
+ EpisodePreview.status == "done").order_by(EpisodePreview.id.desc()).limit(1))).scalar_one_or_none()
+ if not preview or not is_watermark_key(preview.object_key):
+ fail("水印播放文件尚未生成,暂不可播放", 409)
+ key, content_type = preview.object_key, "video/mp4"
+ elif kind == "series":
+ series = await db.get(Series, record_id)
+ if not series or purpose != "cover" or not series.cover_asset_id:
+ fail("媒体不存在", 404)
+ owner = bool(user and series.owner_id == user.id)
+ public = bool(series.listed and series.audit_status == "approved" and not series.blocked)
+ if not admin and not owner and not public:
+ fail("媒体未公开或已下架", 404)
+ asset = await db.get(Asset, series.cover_asset_id)
+ elif kind == "submission":
+ item = await db.get(Submission, record_id)
+ post = await db.get(Recruit, item.recruit_id) if item else None
+ if not item or not user or (not admin and user.id not in (item.owner_id, post.owner_id)) or purpose not in ("review", "cover"):
+ fail("投稿不存在或无权访问", 404)
+ rights = await rights_for(db, item.asset_id)
+ if not admin and (item.withdrawn or item.blocked or post.blocked or not rights_valid(rights) or not submission_rights_match(item, rights)):
+ fail("投稿未完成基础核验、材料已变更或已被撤回、封禁", 403)
+ asset = await db.get(Asset, item.asset_id)
+ elif kind == "asset":
+ asset = await db.get(Asset, record_id)
+ if not asset or not user or (not admin and asset.owner_id != user.id):
+ fail("文件不存在或无权访问", 404)
+ if purpose not in ("original", "preview", "review", "cover"):
+ fail("媒体用途无效")
+ if purpose == "original" or (purpose == "preview" and asset.kind == "video"):
+ image = asset.kind != "video" and bool(asset.cover_key)
+ key = asset.cover_key if image else asset.object_key
+ content_type = "image/png" if image else asset.content_type
+ event(db, user.id, "asset", asset.id, "signed_" + purpose)
+ elif kind == "recruit":
+ post = await db.get(Recruit, record_id)
+ if not post or not purpose.startswith("image-"):
+ fail("媒体不存在", 404)
+ private = bool(user and (admin or post.owner_id == user.id))
+ if not private and not recruit_open(post):
+ # 已投稿的人仍可看需求参考资料。
+ related = user and (await db.execute(select(Submission.id).where(Submission.recruit_id == post.id, Submission.owner_id == user.id).limit(1))).scalar_one_or_none()
+ if not related or post.blocked:
+ fail("需求已关闭或不可见", 404)
+ try:
+ index = int(purpose.split("-", 1)[1])
+ if index < 0:
+ raise ValueError
+ asset = await db.get(Asset, post.image_ids[index])
+ except (ValueError, IndexError):
+ fail("参考图片不存在", 404)
+ key, content_type = asset.cover_key or asset.object_key, "image/png" if asset.cover_key else asset.content_type
+ elif kind == "support":
+ support = await db.get(Support, 1)
+ if not user or purpose != "qr" or not support or not support.enabled or not support.qr_asset_id:
+ fail("客服暂不可用或尚未登录", 404)
+ asset = await db.get(Asset, support.qr_asset_id)
+ key, content_type = asset.cover_key or asset.object_key, "image/png" if asset.cover_key else asset.content_type
+ else:
+ fail("媒体类型无效", 404)
+ if not asset or asset.status != "ready":
+ fail("媒体尚未就绪", 409)
+ if purpose == "cover" and asset.kind != "video":
+ key = asset.cover_key or asset.object_key
+ content_type = "image/png" if asset.cover_key else asset.content_type
+ if key is None:
+ key = getattr(asset, f"{purpose}_key", None)
+ if purpose == "cover":
+ content_type = "image/jpeg" if asset.kind == "video" else "image/png"
+ if not key:
+ fail("该预览尚未生成", 409)
+ url = await asyncio.to_thread(storage.signed, key, content_type)
+ await db.commit()
+ return {"url": url, "expires_in": get_marketplace_settings().signed_url_seconds}
diff --git a/backend/app/marketplace/models.py b/backend/app/marketplace/models.py
new file mode 100644
index 0000000..fc604a8
--- /dev/null
+++ b/backend/app/marketplace/models.py
@@ -0,0 +1,394 @@
+"""独立 metadata 和 marketplace_ 表;不对原表做 DDL。"""
+from datetime import datetime
+from typing import Any
+
+from sqlalchemy import BigInteger, Boolean, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, func, text
+from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
+
+
+class MarketBase(DeclarativeBase):
+ """下游专用 metadata;用户 ID 只引用现有身份,不修改原表。"""
+
+
+class Record:
+ """业务记录公共字段;时间由数据库生成。"""
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+
+
+class Authorization(Record, MarketBase):
+ """账号授权函不可变存档;逐件权属档案引用签署记录。"""
+ __tablename__ = "marketplace_authorizations"
+ __table_args__ = (UniqueConstraint("owner_id", "template_version"),)
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ template_version: Mapped[str] = mapped_column(String(60))
+ signer_name: Mapped[str] = mapped_column(String(80))
+ body: Mapped[str] = mapped_column(Text)
+ body_hash: Mapped[str] = mapped_column(String(64))
+ letter_key: Mapped[str] = mapped_column(String(512))
+ signature_key: Mapped[str] = mapped_column(String(512))
+ client_ip: Mapped[str] = mapped_column(String(64))
+ user_agent: Mapped[str] = mapped_column(String(512))
+
+
+class Asset(Record, MarketBase):
+ __tablename__ = "marketplace_assets"
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ kind: Mapped[str] = mapped_column(String(24)) # video / image / document / qr
+ filename: Mapped[str] = mapped_column(String(255))
+ content_type: Mapped[str] = mapped_column(String(100))
+ size_bytes: Mapped[int] = mapped_column(BigInteger)
+ object_key: Mapped[str] = mapped_column(String(512), unique=True)
+ status: Mapped[str] = mapped_column(String(24), default="uploading", index=True)
+ fingerprint: Mapped[str] = mapped_column(String(64), default="")
+ duration_seconds: Mapped[float | None]
+ cover_key: Mapped[str | None] = mapped_column(String(512))
+ preview_key: Mapped[str | None] = mapped_column(String(512))
+ review_key: Mapped[str | None] = mapped_column(String(512))
+ error: Mapped[str] = mapped_column(Text, default="")
+
+
+class Upload(Record, MarketBase):
+ __tablename__ = "marketplace_uploads"
+ asset_id: Mapped[int] = mapped_column(ForeignKey("marketplace_assets.id"), unique=True)
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ remote_id: Mapped[str] = mapped_column(String(512))
+ state: Mapped[str] = mapped_column(String(24), default="uploading")
+ part_size: Mapped[int] = mapped_column(Integer)
+ parts: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict)
+ expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
+
+
+class Rights(Record, MarketBase):
+ __tablename__ = "marketplace_rights"
+ asset_id: Mapped[int] = mapped_column(ForeignKey("marketplace_assets.id"), unique=True)
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ version: Mapped[int] = mapped_column(Integer, default=1)
+ details: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict)
+ basic_status: Mapped[str] = mapped_column(String(24), default="draft")
+ full_status: Mapped[str] = mapped_column(String(24), default="draft")
+ certificate_asset_id: Mapped[int | None] = mapped_column(ForeignKey("marketplace_assets.id"))
+ evidence_ids: Mapped[list[int]] = mapped_column(JSON, default=list)
+ valid_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+ blocked: Mapped[bool] = mapped_column(Boolean, default=False)
+ reason: Mapped[str] = mapped_column(Text, default="")
+
+
+class Work(Record, MarketBase):
+ __tablename__ = "marketplace_works"
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ asset_id: Mapped[int | None] = mapped_column(ForeignKey("marketplace_assets.id"))
+ cover_asset_id: Mapped[int | None] = mapped_column(ForeignKey("marketplace_assets.id"))
+ version: Mapped[int] = mapped_column(Integer, default=1)
+ title: Mapped[str] = mapped_column(String(200))
+ description: Mapped[str] = mapped_column(Text, default="")
+ category: Mapped[str] = mapped_column(String(60), default="其他")
+ tags: Mapped[list[str]] = mapped_column(JSON, default=list)
+ price_fen: Mapped[int] = mapped_column(BigInteger)
+ sale_type: Mapped[str] = mapped_column(String(24), default="copyright_contact", index=True)
+ unlock_price_fen: Mapped[int] = mapped_column(BigInteger, default=0)
+ share_bps: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ source: Mapped[str] = mapped_column(String(30), default="original")
+ license_scope: Mapped[str] = mapped_column(Text, default="")
+ audit_status: Mapped[str] = mapped_column(String(24), default="draft", index=True)
+ listed: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
+ blocked: Mapped[bool] = mapped_column(Boolean, default=False)
+ reason: Mapped[str] = mapped_column(Text, default="")
+
+
+class RegistrationCase(Record, MarketBase):
+ __tablename__ = "marketplace_registration_cases"
+ rights_id: Mapped[int] = mapped_column(ForeignKey("marketplace_rights.id"), unique=True)
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ version: Mapped[int] = mapped_column(Integer, default=1)
+ route: Mapped[str] = mapped_column(String(24))
+ status: Mapped[str] = mapped_column(String(30), default="pending_materials")
+ official_reference: Mapped[str] = mapped_column(String(200), default="")
+ note: Mapped[str] = mapped_column(Text, default="")
+
+
+class Recruit(Record, MarketBase):
+ __tablename__ = "marketplace_recruits"
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ version: Mapped[int] = mapped_column(Integer, default=1)
+ title: Mapped[str] = mapped_column(String(200))
+ description: Mapped[str] = mapped_column(Text)
+ category: Mapped[str] = mapped_column(String(60), default="其他")
+ budget_fen: Mapped[int] = mapped_column(BigInteger)
+ wanted_count: Mapped[int] = mapped_column(Integer)
+ requirements: Mapped[str] = mapped_column(Text)
+ license_scope: Mapped[str] = mapped_column(Text)
+ image_ids: Mapped[list[int]] = mapped_column(JSON, default=list)
+ deadline_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True)
+ audit_status: Mapped[str] = mapped_column(String(24), default="draft")
+ state: Mapped[str] = mapped_column(String(24), default="draft")
+ blocked: Mapped[bool] = mapped_column(Boolean, default=False)
+ reason: Mapped[str] = mapped_column(Text, default="")
+
+
+class Submission(Record, MarketBase):
+ __tablename__ = "marketplace_submissions"
+ recruit_id: Mapped[int] = mapped_column(ForeignKey("marketplace_recruits.id"), index=True)
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ asset_id: Mapped[int] = mapped_column(ForeignKey("marketplace_assets.id"))
+ quote_fen: Mapped[int] = mapped_column(BigInteger)
+ description: Mapped[str] = mapped_column(Text, default="")
+ snapshot: Mapped[dict[str, Any]] = mapped_column(JSON)
+ selection: Mapped[str] = mapped_column(String(24), default="to_review")
+ withdrawn: Mapped[bool] = mapped_column(Boolean, default=False)
+ blocked: Mapped[bool] = mapped_column(Boolean, default=False)
+ __table_args__ = (Index("marketplace_one_active_submission", "recruit_id", "owner_id", unique=True,
+ postgresql_where=text("withdrawn = false")),)
+
+
+class MediaJob(Record, MarketBase):
+ __tablename__ = "marketplace_media_jobs"
+ asset_id: Mapped[int] = mapped_column(ForeignKey("marketplace_assets.id"), unique=True)
+ status: Mapped[str] = mapped_column(String(24), default="pending", index=True)
+ attempts: Mapped[int] = mapped_column(Integer, default=0)
+ lease_token: Mapped[str | None] = mapped_column(String(64))
+ lease_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+ error: Mapped[str] = mapped_column(Text, default="")
+
+
+class Handoff(Record, MarketBase):
+ """PrintFilm 成片转存到市场;同一版本幂等,不改已发布的旧资产。"""
+ __tablename__ = "marketplace_handoffs"
+ __table_args__ = (UniqueConstraint("owner_id", "idempotency_key"),)
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ idempotency_key: Mapped[str] = mapped_column(String(120))
+ source_kind: Mapped[str] = mapped_column(String(24))
+ source_id: Mapped[int] = mapped_column(Integer, index=True)
+ source_version: Mapped[str] = mapped_column(String(80), default="")
+ source_fingerprint: Mapped[str] = mapped_column(String(64), default="")
+ target_kind: Mapped[str] = mapped_column(String(24))
+ target_id: Mapped[int] = mapped_column(Integer, index=True)
+ series_id: Mapped[int | None] = mapped_column(Integer)
+ asset_id: Mapped[int | None] = mapped_column(ForeignKey("marketplace_assets.id"))
+ status: Mapped[str] = mapped_column(String(24), default="pending", index=True)
+ error: Mapped[str] = mapped_column(Text, default="")
+ attempts: Mapped[int] = mapped_column(Integer, default=0)
+ lease_token: Mapped[str | None] = mapped_column(String(64))
+ lease_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+ source_snapshot: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict)
+
+
+class WorkPreview(Record, MarketBase):
+ """作品专用试看任务,不复用投稿审片或旧资产预览。"""
+ __tablename__ = "marketplace_work_previews"
+ __table_args__ = (UniqueConstraint("work_id", "asset_id"),)
+ work_id: Mapped[int] = mapped_column(ForeignKey("marketplace_works.id"))
+ asset_id: Mapped[int] = mapped_column(ForeignKey("marketplace_assets.id"))
+ version: Mapped[int] = mapped_column(Integer)
+ status: Mapped[str] = mapped_column(String(24), default="pending", index=True)
+ attempts: Mapped[int] = mapped_column(Integer, default=0)
+ lease_token: Mapped[str | None] = mapped_column(String(64))
+ lease_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+ object_key: Mapped[str | None] = mapped_column(String(512))
+ error: Mapped[str] = mapped_column(Text, default="")
+
+
+class Series(Record, MarketBase):
+ """市场短剧系列;与原 drama_* 项目保持数据和生命周期隔离。"""
+ __tablename__ = "marketplace_series"
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ version: Mapped[int] = mapped_column(Integer, default=1)
+ title: Mapped[str] = mapped_column(String(200))
+ description: Mapped[str] = mapped_column(Text, default="")
+ category: Mapped[str] = mapped_column(String(60), default="其他")
+ tags: Mapped[list[str]] = mapped_column(JSON, default=list)
+ cover_asset_id: Mapped[int | None] = mapped_column(ForeignKey("marketplace_assets.id"))
+ sale_type: Mapped[str] = mapped_column(String(24), default="copyright_contact", index=True)
+ copyright_price_fen: Mapped[int] = mapped_column(BigInteger, default=0)
+ free_episode_count: Mapped[int] = mapped_column(Integer, default=0)
+ share_bps: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ audit_status: Mapped[str] = mapped_column(String(24), default="draft", index=True)
+ listed: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
+ blocked: Mapped[bool] = mapped_column(Boolean, default=False)
+ reason: Mapped[str] = mapped_column(Text, default="")
+
+
+class SeriesEpisode(Record, MarketBase):
+ """市场剧集分集;每集有独立媒体、价格、权属和购买权益。"""
+ __tablename__ = "marketplace_series_episodes"
+ __table_args__ = (UniqueConstraint("series_id", "episode_no"),)
+ series_id: Mapped[int] = mapped_column(ForeignKey("marketplace_series.id", ondelete="CASCADE"), index=True)
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ episode_no: Mapped[int] = mapped_column(Integer)
+ title: Mapped[str] = mapped_column(String(200))
+ description: Mapped[str] = mapped_column(Text, default="")
+ asset_id: Mapped[int | None] = mapped_column(ForeignKey("marketplace_assets.id"))
+ cover_asset_id: Mapped[int | None] = mapped_column(ForeignKey("marketplace_assets.id"))
+ copyright_price_fen: Mapped[int] = mapped_column(BigInteger, default=0)
+ unlock_price_fen: Mapped[int] = mapped_column(BigInteger, default=0)
+ share_bps: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ source: Mapped[str] = mapped_column(String(30), default="external")
+ source_type: Mapped[str] = mapped_column(String(24), default="upload")
+ source_snapshot: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict)
+ version: Mapped[int] = mapped_column(Integer, default=1)
+ audit_status: Mapped[str] = mapped_column(String(24), default="draft", index=True)
+ listed: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
+ blocked: Mapped[bool] = mapped_column(Boolean, default=False)
+ reason: Mapped[str] = mapped_column(Text, default="")
+ preview_status: Mapped[str] = mapped_column(String(24), default="none", index=True)
+ preview_key: Mapped[str | None] = mapped_column(String(512))
+ preview_attempts: Mapped[int] = mapped_column(Integer, default=0)
+ playback_status: Mapped[str] = mapped_column(String(24), default="none", index=True)
+ playback_manifest_key: Mapped[str | None] = mapped_column(String(512))
+ playback_attempts: Mapped[int] = mapped_column(Integer, default=0)
+
+
+class Publication(Record, MarketBase):
+ """提交审核时的不可变发布快照,订单和播放权益始终绑定此版本。"""
+ __tablename__ = "marketplace_publications"
+ __table_args__ = (UniqueConstraint("content_type", "content_id", "version"),)
+ content_type: Mapped[str] = mapped_column(String(24), index=True)
+ content_id: Mapped[int] = mapped_column(Integer, index=True)
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ version: Mapped[int] = mapped_column(Integer)
+ asset_id: Mapped[int] = mapped_column(ForeignKey("marketplace_assets.id"))
+ cover_asset_id: Mapped[int | None] = mapped_column(ForeignKey("marketplace_assets.id"))
+ sale_type: Mapped[str] = mapped_column(String(24), index=True)
+ copyright_price_fen: Mapped[int] = mapped_column(BigInteger, default=0)
+ unlock_price_fen: Mapped[int] = mapped_column(BigInteger, default=0)
+ share_bps: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ rights_snapshot: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict)
+ preview_key: Mapped[str | None] = mapped_column(String(512))
+ playback_manifest_key: Mapped[str | None] = mapped_column(String(512))
+ preview_status: Mapped[str] = mapped_column(String(24), default="pending", index=True)
+ preview_attempts: Mapped[int] = mapped_column(Integer, default=0)
+ preview_error: Mapped[str] = mapped_column(Text, default="")
+ playback_status: Mapped[str] = mapped_column(String(24), default="pending", index=True)
+ playback_attempts: Mapped[int] = mapped_column(Integer, default=0)
+ playback_error: Mapped[str] = mapped_column(Text, default="")
+ audit_status: Mapped[str] = mapped_column(String(24), default="draft", index=True)
+ listed: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
+ reason: Mapped[str] = mapped_column(Text, default="")
+
+
+class EpisodePreview(Record, MarketBase):
+ __tablename__ = "marketplace_episode_previews"
+ __table_args__ = (UniqueConstraint("episode_id", "asset_id", "version"),)
+ episode_id: Mapped[int] = mapped_column(ForeignKey("marketplace_series_episodes.id", ondelete="CASCADE"), index=True)
+ asset_id: Mapped[int] = mapped_column(ForeignKey("marketplace_assets.id"))
+ version: Mapped[int] = mapped_column(Integer)
+ status: Mapped[str] = mapped_column(String(24), default="pending", index=True)
+ attempts: Mapped[int] = mapped_column(Integer, default=0)
+ lease_token: Mapped[str | None] = mapped_column(String(64))
+ lease_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+ object_key: Mapped[str | None] = mapped_column(String(512))
+ error: Mapped[str] = mapped_column(Text, default="")
+
+
+class PlaybackJob(Record, MarketBase):
+ __tablename__ = "marketplace_playback_jobs"
+ __table_args__ = (UniqueConstraint("publication_id"),)
+ publication_id: Mapped[int] = mapped_column(ForeignKey("marketplace_publications.id", ondelete="CASCADE"), index=True)
+ status: Mapped[str] = mapped_column(String(24), default="pending", index=True)
+ attempts: Mapped[int] = mapped_column(Integer, default=0)
+ lease_token: Mapped[str | None] = mapped_column(String(64))
+ lease_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+ error: Mapped[str] = mapped_column(Text, default="")
+
+
+class RevenueConfig(MarketBase):
+ __tablename__ = "marketplace_revenue_config"
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, default=1)
+ version: Mapped[int] = mapped_column(Integer, default=1)
+ platform_share_bps: Mapped[int] = mapped_column(Integer)
+ enabled: Mapped[bool] = mapped_column(Boolean, default=True)
+
+
+class ContentOrder(Record, MarketBase):
+ __tablename__ = "marketplace_content_orders"
+ __table_args__ = (UniqueConstraint("out_trade_no"),)
+ out_trade_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
+ user_id: Mapped[int] = mapped_column(Integer, index=True)
+ publication_id: Mapped[int] = mapped_column(ForeignKey("marketplace_publications.id"), index=True)
+ episode_id: Mapped[int | None] = mapped_column(ForeignKey("marketplace_series_episodes.id"), index=True)
+ amount_fen: Mapped[int] = mapped_column(BigInteger)
+ pay_type: Mapped[str] = mapped_column(String(16))
+ status: Mapped[str] = mapped_column(String(24), default="pending", index=True)
+ trade_no: Mapped[str | None] = mapped_column(String(128))
+ idempotency_key: Mapped[str] = mapped_column(String(128), unique=True, index=True)
+ paid_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+
+
+class Entitlement(Record, MarketBase):
+ __tablename__ = "marketplace_entitlements"
+ __table_args__ = (UniqueConstraint("user_id", "publication_id"),)
+ user_id: Mapped[int] = mapped_column(Integer, index=True)
+ publication_id: Mapped[int] = mapped_column(ForeignKey("marketplace_publications.id"), index=True)
+ episode_id: Mapped[int | None] = mapped_column(ForeignKey("marketplace_series_episodes.id"), index=True)
+ order_id: Mapped[int | None] = mapped_column(ForeignKey("marketplace_content_orders.id"))
+ active: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
+
+
+class RevenueLedger(Record, MarketBase):
+ __tablename__ = "marketplace_revenue_ledger"
+ order_id: Mapped[int] = mapped_column(ForeignKey("marketplace_content_orders.id"), unique=True)
+ publication_id: Mapped[int] = mapped_column(ForeignKey("marketplace_publications.id"), index=True)
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ gross_fen: Mapped[int] = mapped_column(BigInteger)
+ platform_fen: Mapped[int] = mapped_column(BigInteger)
+ creator_fen: Mapped[int] = mapped_column(BigInteger)
+ share_bps: Mapped[int] = mapped_column(Integer)
+ settlement_status: Mapped[str] = mapped_column(String(24), default="pending", index=True)
+
+
+class Payout(Record, MarketBase):
+ __tablename__ = "marketplace_payouts"
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ amount_fen: Mapped[int] = mapped_column(BigInteger)
+ status: Mapped[str] = mapped_column(String(24), default="pending", index=True)
+ note: Mapped[str] = mapped_column(Text, default="")
+ paid_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+ operator_id: Mapped[int | None] = mapped_column(Integer)
+
+
+class Event(Record, MarketBase):
+ __tablename__ = "marketplace_events"
+ actor_id: Mapped[int] = mapped_column(Integer, index=True)
+ target_type: Mapped[str] = mapped_column(String(30))
+ target_id: Mapped[int] = mapped_column(Integer, index=True)
+ action: Mapped[str] = mapped_column(String(50))
+ version: Mapped[int | None] = mapped_column(Integer)
+ note: Mapped[str] = mapped_column(Text, default="")
+
+
+class Notification(Record, MarketBase):
+ __tablename__ = "marketplace_notifications"
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ message: Mapped[str] = mapped_column(Text)
+ link: Mapped[str] = mapped_column(String(300))
+ read: Mapped[bool] = mapped_column(Boolean, default=False)
+
+
+class Report(Record, MarketBase):
+ __tablename__ = "marketplace_reports"
+ owner_id: Mapped[int] = mapped_column(Integer, index=True)
+ target_type: Mapped[str] = mapped_column(String(30))
+ target_id: Mapped[int] = mapped_column(Integer)
+ statement: Mapped[str] = mapped_column(Text)
+ contact: Mapped[str] = mapped_column(String(200))
+ evidence_ids: Mapped[list[int]] = mapped_column(JSON, default=list)
+ status: Mapped[str] = mapped_column(String(24), default="pending")
+ resolution: Mapped[str] = mapped_column(Text, default="")
+
+
+class CategoryConfig(MarketBase):
+ __tablename__ = "marketplace_category_config"
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ version: Mapped[int] = mapped_column(Integer, default=1)
+ names: Mapped[list[str]] = mapped_column(JSON)
+
+
+class Support(MarketBase):
+ __tablename__ = "marketplace_support"
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, default=1)
+ name: Mapped[str] = mapped_column(String(80), default="平台客服")
+ wechat: Mapped[str] = mapped_column(String(100), default="")
+ hours: Mapped[str] = mapped_column(String(100), default="")
+ qr_asset_id: Mapped[int | None] = mapped_column(ForeignKey("marketplace_assets.id"))
+ enabled: Mapped[bool] = mapped_column(Boolean, default=False)
diff --git a/backend/app/marketplace/preview_worker.py b/backend/app/marketplace/preview_worker.py
new file mode 100644
index 0000000..f83989a
--- /dev/null
+++ b/backend/app/marketplace/preview_worker.py
@@ -0,0 +1,315 @@
+"""作品试看任务由现有独立 Worker 串行执行,不接入上游 AI 调度。"""
+import asyncio
+from datetime import timedelta
+import json
+import logging
+import math
+from pathlib import Path
+import tempfile
+import uuid
+
+from sqlalchemy import and_, or_, select
+
+from app.config import get_settings
+from app.database import AsyncSessionLocal
+from . import storage
+from .config import get_marketplace_settings
+from .models import Asset, EpisodePreview, Publication, Series, SeriesEpisode, Work, WorkPreview
+from .previews import episode_is_free, is_watermark_key, plays_full_watermark, preview_duration
+from .service import event, now, notify
+
+logger = logging.getLogger(__name__)
+
+
+def watermark_text(author_name: str | None) -> str:
+ """水印为平台名、作者显示名和侵权声明。去掉会破坏转码参数的字符。"""
+ raw = (author_name or "").strip() or "创作者"
+ cleaned = "".join(ch for ch in raw if ch.isprintable() and ch not in "\\':%{}[]")
+ cleaned = " ".join(cleaned.split())[:20] or "创作者"
+ return f"PRINTFILM {cleaned} 侵权必究"
+
+
+async def render_preview(snapshot):
+ from .worker import cache_root, command
+ settings, upstream = get_marketplace_settings(), get_settings()
+ with tempfile.TemporaryDirectory(prefix="job-", dir=cache_root()) as directory:
+ root = Path(directory)
+ source = root / ("source" + Path(snapshot["filename"]).suffix.lower())
+ await asyncio.to_thread(storage.download, snapshot["source_key"], source)
+ if source.stat().st_size != snapshot["size_bytes"]:
+ raise ValueError("原片大小不一致")
+ # mp4 是首版上传主格式;保留其他已支持容器,避免 ffprobe 因白名单误拒绝正常文件。
+ formats = "mov,matroska,webm,mp4"
+ probe = json.loads(await command(upstream.ffprobe_path, "-v", "error", "-protocol_whitelist", "file,pipe",
+ "-format_whitelist", formats, "-show_format", "-show_streams", "-of", "json", str(source), timeout=60))
+ videos = [v for v in probe.get("streams", []) if v.get("codec_type") == "video"]
+ if not videos or not 0 < int(videos[0].get("width", 0)) * int(videos[0].get("height", 0)) <= 50_000_000:
+ raise ValueError("无效的视频尺寸")
+ duration = float(probe.get("format", {}).get("duration", 0))
+ full = bool(snapshot.get("full_watermark"))
+ if duration <= 0 or duration > settings.max_duration_seconds:
+ raise ValueError("视频超过时长限制" if duration > settings.max_duration_seconds else "视频时长无效")
+ limit_args: list[str] = []
+ timeout = 600
+ if full:
+ timeout = min(7200, max(600, int(duration * 4) + 120))
+ else:
+ limit = preview_duration(duration)
+ # 为视频帧和 AAC 尾帧预留余量,不能因封装取整超出 30% / 15 秒。
+ limit = math.floor((limit - 0.1) * 30) / 30
+ if limit <= 0:
+ raise ValueError("视频过短,无法生成受限试看")
+ limit_args = ["-t", str(limit)]
+ font = Path(settings.watermark_font)
+ if not font.is_file():
+ raise ValueError("水印字体不可用")
+ escaped_font = str(font.resolve()).replace("\\", "/").replace(":", "\\:").replace("'", "\\'")
+ # 作者名已去掉转码特殊字符;上下两处烧录。
+ content_id = snapshot.get("content_id", snapshot.get("work_id"))
+ watermark = watermark_text(snapshot.get("author_name"))
+ # 不缩放画面;奇数尺寸只补至偶数,兼容 H.264 的 yuv420p。
+ filters = "pad=ceil(iw/2)*2:ceil(ih/2)*2"
+ for x, y in (("(w-tw)/2", "h*0.22"), ("(w-tw)/2", "h*0.72")):
+ filters += (f",drawtext=fontfile='{escaped_font}':text='{watermark}':fontsize=h/30:"
+ f"[email protected]:box=1:[email protected]:x={x}:y={y}")
+ output = root / "preview.mp4"
+ await command(upstream.ffmpeg_path, "-y", "-v", "error", "-protocol_whitelist", "file,pipe",
+ "-format_whitelist", formats, "-i", str(source), *limit_args, "-map", "0:v:0", "-map", "0:a:0?",
+ "-sn", "-dn", "-vf", filters, "-c:v", "libx264", "-preset", "fast", "-crf", "16",
+ "-threads", "2", "-fps_mode", "passthrough", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart",
+ str(output), timeout=timeout)
+ # 每次尝试独立对象,过期进程不能覆盖已签发的文件。
+ # Older callers/tests only supplied work_id; treat those snapshots as
+ # single-video works for backwards compatibility. New series jobs pass
+ # content_type explicitly so their preview is isolated under its own
+ # prefix.
+ content = snapshot.get("content_type", "work")
+ if full:
+ folder = "series-watermarks-full" if content == "series_episode" else "work-watermarks-full"
+ else:
+ folder = "work-previews-hq" if content == "work" else "series-previews-hq"
+ prefix = folder
+ key = f"marketplace/{prefix}/{content_id}/{snapshot['asset_id']}/{uuid.uuid4().hex}.mp4"
+ await asyncio.to_thread(storage.upload, key, output, "video/mp4")
+ return key
+
+
+async def run_preview_once():
+ async with AsyncSessionLocal() as db:
+ job = (await db.execute(select(WorkPreview).where(or_(WorkPreview.status == "pending",
+ and_(WorkPreview.status == "running", WorkPreview.lease_until < now())))
+ .order_by(WorkPreview.id).with_for_update(skip_locked=True).limit(1))).scalar_one_or_none()
+ if not job:
+ return False
+ asset = await db.get(Asset, job.asset_id)
+ work = await db.get(Work, job.work_id)
+ token = uuid.uuid4().hex
+ job.status, job.lease_token, job.lease_until = "running", token, now() + timedelta(minutes=2)
+ job.attempts += 1
+ job_id, work_id = job.id, job.work_id
+ from app.models import User
+ owner = await db.get(User, work.owner_id)
+ snapshot = dict(content_type="work", content_id=work_id, work_id=work_id, owner_id=work.owner_id,
+ author_name=owner.nickname if owner and owner.nickname else "创作者", asset_id=asset.id,
+ filename=asset.filename, source_key=asset.object_key, size_bytes=asset.size_bytes,
+ attempts=job.attempts, full_watermark=plays_full_watermark(work.sale_type, work.price_fen))
+ await db.commit()
+
+ async def heartbeat():
+ from sqlalchemy import update
+ while True:
+ await asyncio.sleep(20)
+ async with AsyncSessionLocal() as db:
+ changed = await db.execute(update(WorkPreview).where(WorkPreview.id == job_id,
+ WorkPreview.lease_token == token, WorkPreview.status == "running")
+ .values(lease_until=now() + timedelta(minutes=2)))
+ await db.commit()
+ if not changed.rowcount:
+ raise RuntimeError("试看任务租约失效")
+
+ key, error = None, ""
+ pulse = asyncio.create_task(heartbeat())
+ async def bounded_render():
+ if snapshot["attempts"] > get_marketplace_settings().worker_max_attempts:
+ raise ValueError("试看任务重试次数已用完")
+ return await render_preview(snapshot)
+ processing = asyncio.create_task(bounded_render())
+ try:
+ done, _ = await asyncio.wait((pulse, processing), return_when=asyncio.FIRST_COMPLETED)
+ if pulse in done:
+ await pulse
+ raise RuntimeError("试看任务心跳中断")
+ key = await processing
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.exception("作品试看生成失败 %s", job_id)
+ error = "试看生成失败,请检查原片、字体及 OSS 配置后重试"
+ finally:
+ pulse.cancel()
+ processing.cancel()
+ await asyncio.gather(pulse, processing, return_exceptions=True)
+ async with AsyncSessionLocal() as db:
+ # 与提交接口统一为先锁作品、后锁任务。
+ work = await db.get(Work, work_id, with_for_update=True)
+ job = (await db.execute(select(WorkPreview).where(WorkPreview.id == job_id,
+ WorkPreview.lease_token == token).with_for_update())).scalar_one_or_none()
+ if not job:
+ return True
+ matching = (work.version == job.version and work.asset_id == job.asset_id
+ and work.audit_status == "processing" and not work.blocked)
+ if key:
+ job.object_key, job.status, job.error = key, "done", ""
+ publications = (await db.execute(select(Publication).where(Publication.content_type == "work", Publication.content_id == work_id, Publication.version == job.version).with_for_update())).scalars().all()
+ for publication in publications:
+ publication.preview_key, publication.preview_status, publication.preview_error = key, "done", ""
+ if matching:
+ work.audit_status, work.reason = "pending", ""
+ event(db, work.owner_id, "work", work.id, "preview_ready", version=work.version)
+ notify(db, work.owner_id, f"作品《{work.title}》水印播放文件已生成,已进入待审核",
+ f"/marketplace/works/{work.id}/manage")
+ elif work and work.audit_status == "approved" and not work.blocked and not work.listed and key.startswith(expected):
+ work.listed = True
+ notify(db, work.owner_id, f"作品《{work.title}》完整水印已生成,已重新出现在作品广场",
+ f"/marketplace/works/{work.id}")
+ else:
+ terminal = job.attempts >= get_marketplace_settings().worker_max_attempts
+ job.status, job.error = "failed" if terminal else "pending", error
+ if matching and terminal:
+ work.audit_status, work.reason = "preview_failed", error
+ publications = (await db.execute(select(Publication).where(Publication.content_type == "work", Publication.content_id == work_id, Publication.version == job.version).with_for_update())).scalars().all()
+ for publication in publications:
+ publication.preview_status, publication.preview_error = ("failed" if terminal else "pending"), error
+ notify(db, work.owner_id, f"作品《{work.title}》试看生成失败,可在发布管理中重试",
+ f"/marketplace/works/{work.id}/manage")
+ job.lease_token, job.lease_until = None, None
+ await db.commit()
+ return True
+
+
+async def _advance_series_review(db, series_id: int) -> None:
+ """全部分集水印完成后,短剧才进入待审核。"""
+ series = await db.get(Series, series_id, with_for_update=True)
+ if not series or series.audit_status != "processing":
+ return
+ episodes = list((await db.execute(select(SeriesEpisode).where(SeriesEpisode.series_id == series.id))).scalars().all())
+ failed = False
+ ready = bool(episodes)
+ for item in episodes:
+ preview = (await db.execute(select(EpisodePreview).where(
+ EpisodePreview.episode_id == item.id, EpisodePreview.asset_id == item.asset_id,
+ ).order_by(EpisodePreview.id.desc()).limit(1))).scalar_one_or_none()
+ if preview and preview.status == "failed":
+ failed = True
+ elif not preview or preview.status != "done" or not is_watermark_key(preview.object_key):
+ ready = False
+ if failed:
+ series.audit_status, series.reason = "preview_failed", "水印播放文件生成失败,请在发布页重试"
+ notify(db, series.owner_id, f"短剧《{series.title}》水印生成失败,可在发布页重试", f"/marketplace/series/{series.id}/edit")
+ elif ready:
+ series.audit_status, series.reason = "pending", ""
+ notify(db, series.owner_id, f"短剧《{series.title}》水印已生成,已进入待审核", f"/marketplace/series/{series.id}/edit")
+
+
+async def release_finished_series_once() -> bool:
+ """水印已经完成、但仍停在生成中的短剧推进到待审核。"""
+ async with AsyncSessionLocal() as db:
+ series_ids = list((await db.execute(select(Series.id).where(Series.audit_status == "processing"))).scalars().all())
+ if not series_ids:
+ return False
+ for series_id in series_ids:
+ await _advance_series_review(db, series_id)
+ await db.commit()
+ return True
+
+
+async def run_episode_preview_once():
+ """为非免费剧集生成限时烧录水印试看,并同步不可变 Publication。"""
+ async with AsyncSessionLocal() as db:
+ job = (await db.execute(select(EpisodePreview).where(
+ or_(EpisodePreview.status == "pending",
+ and_(EpisodePreview.status == "running", EpisodePreview.lease_until < now())))
+ .order_by(EpisodePreview.id).with_for_update(skip_locked=True).limit(1))).scalar_one_or_none()
+ if not job:
+ return False
+ asset = await db.get(Asset, job.asset_id)
+ episode = await db.get(SeriesEpisode, job.episode_id)
+ if not asset or not episode:
+ job.status, job.error = "failed", "分集或媒体不存在"
+ await db.commit()
+ return True
+ token = uuid.uuid4().hex
+ job.status, job.lease_token, job.lease_until = "running", token, now() + timedelta(minutes=2)
+ job.attempts += 1
+ episode.preview_status, episode.preview_attempts = "running", job.attempts
+ job_id, episode_id, version = job.id, episode.id, job.version
+ series = await db.get(Series, episode.series_id)
+ from app.models import User
+ owner = await db.get(User, episode.owner_id)
+ snapshot = dict(content_type="series_episode", content_id=episode_id, owner_id=episode.owner_id,
+ author_name=owner.nickname if owner and owner.nickname else "创作者",
+ asset_id=asset.id, filename=asset.filename, source_key=asset.object_key,
+ size_bytes=asset.size_bytes, attempts=job.attempts,
+ full_watermark=bool(series and episode_is_free(series, episode)))
+ await db.commit()
+
+ async def heartbeat():
+ from sqlalchemy import update
+ while True:
+ await asyncio.sleep(20)
+ async with AsyncSessionLocal() as db:
+ changed = await db.execute(update(EpisodePreview).where(
+ EpisodePreview.id == job_id, EpisodePreview.lease_token == token,
+ EpisodePreview.status == "running").values(lease_until=now() + timedelta(minutes=2)))
+ await db.commit()
+ if not changed.rowcount:
+ raise RuntimeError("剧集试看任务租约失效")
+
+ key, error = None, ""
+ pulse = asyncio.create_task(heartbeat())
+ processing = asyncio.create_task(render_preview(snapshot))
+ try:
+ done, _ = await asyncio.wait((pulse, processing), return_when=asyncio.FIRST_COMPLETED)
+ if pulse in done:
+ await pulse
+ raise RuntimeError("剧集试看任务心跳中断")
+ key = await processing
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.exception("剧集试看生成失败 %s", job_id)
+ error = "试看生成失败,请检查原片、字体及 OSS 配置后重试"
+ finally:
+ pulse.cancel()
+ processing.cancel()
+ await asyncio.gather(pulse, processing, return_exceptions=True)
+
+ async with AsyncSessionLocal() as db:
+ job = (await db.execute(select(EpisodePreview).where(
+ EpisodePreview.id == job_id, EpisodePreview.lease_token == token).with_for_update())).scalar_one_or_none()
+ if not job:
+ return True
+ episode = await db.get(SeriesEpisode, episode_id)
+ series = await db.get(Series, episode.series_id, with_for_update=True) if episode else None
+ episode = await db.get(SeriesEpisode, episode_id, with_for_update=True) if episode else None
+ publications = list((await db.execute(select(Publication).where(
+ Publication.content_type == "series_episode", Publication.content_id == episode_id,
+ Publication.version == version).with_for_update())).scalars().all())
+ if key:
+ job.object_key, job.status, job.error = key, "done", ""
+ if episode:
+ episode.preview_key, episode.preview_status = key, "done"
+ for publication in publications:
+ publication.preview_key, publication.preview_status, publication.preview_error = key, "done", ""
+ else:
+ terminal = job.attempts >= get_marketplace_settings().worker_max_attempts
+ job.status, job.error = ("failed" if terminal else "pending"), error
+ if episode:
+ episode.preview_status = "failed" if terminal else "pending"
+ for publication in publications:
+ publication.preview_status, publication.preview_error = ("failed" if terminal else "pending"), error
+ if episode:
+ await _advance_series_review(db, episode.series_id)
+ job.lease_token, job.lease_until = None, None
+ await db.commit()
+ return True
diff --git a/backend/app/marketplace/previews.py b/backend/app/marketplace/previews.py
new file mode 100644
index 0000000..f427e4b
--- /dev/null
+++ b/backend/app/marketplace/previews.py
@@ -0,0 +1,121 @@
+"""公开播放文件策略;任何失败都不退回无水印原片。"""
+from sqlalchemy import and_, or_, select
+
+from .models import EpisodePreview, Series, SeriesEpisode, Work, WorkPreview
+
+FULL_WORK_PREFIX = "marketplace/work-watermarks-full/"
+CLIP_WORK_PREFIX = "marketplace/work-previews-hq/"
+FULL_EPISODE_PREFIX = "marketplace/series-watermarks-full/"
+CLIP_EPISODE_PREFIX = "marketplace/series-previews-hq/"
+
+
+def is_watermark_key(key: str | None) -> bool:
+ """已生成的水印文件,不论是完整时长还是短试看。"""
+ return bool(key and (key.startswith(FULL_WORK_PREFIX) or key.startswith(CLIP_WORK_PREFIX) or key.startswith(FULL_EPISODE_PREFIX) or key.startswith(CLIP_EPISODE_PREFIX)))
+
+
+def episode_is_free(series, episode) -> bool:
+ """集数不超过创作者设置的免费集数时,该集免费观看。"""
+ return int(getattr(episode, "episode_no", 0) or 0) <= int(getattr(series, "free_episode_count", 0) or 0)
+
+
+def plays_full_watermark(sale_type: str, price_fen: int, *, free_watch: bool = False) -> bool:
+ """只有首次为免费观看生成水印时才做完整时长;已有文件不因改类型重做。"""
+ return bool(free_watch) or sale_type == "free" or (sale_type == "copyright_contact" and int(price_fen or 0) == 0)
+
+
+def requires_preview(sale_type: str) -> bool:
+ """公开播放都要有水印文件,免费内容也不返回原片。"""
+ return True
+
+
+def playback_prefix(sale_type: str, price_fen: int, *, episode: bool = False, free_watch: bool = False) -> str:
+ """新水印任务使用的对象前缀。已完成的文件不按这个前缀作废。"""
+ if plays_full_watermark(sale_type, price_fen, free_watch=free_watch):
+ return FULL_EPISODE_PREFIX if episode else FULL_WORK_PREFIX
+ return CLIP_EPISODE_PREFIX if episode else CLIP_WORK_PREFIX
+
+
+def preview_duration(duration: float) -> float:
+ """付费试看时长:不超过 15 秒,且不超过原片 30%。"""
+ if not 0 < duration < float("inf"):
+ raise ValueError("视频时长无效")
+ return min(15.0, duration * 0.3)
+
+
+async def preview_for(db, work, *, lock=False):
+ """读取与当前原片绑定的水印任务。"""
+ query = select(WorkPreview).where(WorkPreview.work_id == work.id, WorkPreview.asset_id == work.asset_id)
+ if lock:
+ query = query.with_for_update()
+ return (await db.execute(query)).scalar_one_or_none()
+
+
+async def preview_ready(db, work):
+ """同一原片已有水印即可,改收费类型不要求重做。"""
+ item = await preview_for(db, work)
+ return bool(item and item.status == "done" and is_watermark_key(item.object_key))
+
+
+async def prepare_preview(db, work):
+ """同一原片只保留一条水印任务;失败才重试,已完成的不因改类型作废。"""
+ item = await preview_for(db, work, lock=True)
+ if item is None:
+ item = WorkPreview(work_id=work.id, asset_id=work.asset_id, version=work.version)
+ db.add(item)
+ else:
+ item.version = work.version
+ if item.status == "failed":
+ item.status, item.attempts, item.error, item.object_key = "pending", 0, "", None
+ item.lease_token, item.lease_until = None, None
+ return item
+
+
+async def withdraw_unwatermarked_public(db) -> None:
+ """启动时收紧历史收费内容,免费内容始终直接播放原片。
+
+ 旧版本可能把收费内容错误上架但没有试看文件;这些记录需要暂时下架
+ 并重新排队。免费内容不创建任务、不下架。
+ """
+ from .service import notify
+ works = (await db.execute(select(Work).where(
+ Work.listed.is_(True),
+ Work.sale_type != "free",
+ ))).scalars().all()
+ for work in works:
+ if not work.asset_id or await preview_ready(db, work):
+ continue
+ work.listed = False
+ await prepare_preview(db, work)
+ notify(db, work.owner_id, f"作品《{work.title}》已暂时下架。试看文件生成后,可在审核通过后重新上架。",
+ f"/marketplace/works/{work.id}/manage")
+ series_rows = (await db.execute(select(Series).where(
+ Series.listed.is_(True),
+ Series.sale_type != "free",
+ ))).scalars().all()
+ for series in series_rows:
+ episodes = (await db.execute(select(SeriesEpisode).where(SeriesEpisode.series_id == series.id))).scalars().all()
+ prefix = playback_prefix(series.sale_type, series.copyright_price_fen, episode=True)
+ missing = False
+ for episode in episodes:
+ episode.listed = False
+ if not episode.asset_id:
+ missing = True
+ continue
+ item = (await db.execute(select(EpisodePreview).where(
+ EpisodePreview.episode_id == episode.id, EpisodePreview.asset_id == episode.asset_id,
+ EpisodePreview.version == episode.version,
+ ))).scalar_one_or_none()
+ ready = bool(item and item.status == "done" and (item.object_key or "").startswith(prefix))
+ if ready:
+ continue
+ missing = True
+ if item is None:
+ db.add(EpisodePreview(episode_id=episode.id, asset_id=episode.asset_id, version=episode.version))
+ elif item.status != "running":
+ item.status, item.attempts, item.error, item.object_key = "pending", 0, "", None
+ item.lease_token, item.lease_until = None, None
+ if missing:
+ series.listed = False
+ notify(db, series.owner_id, f"短剧《{series.title}》已暂时下架。各集试看文件生成后,可重新上架到作品广场。",
+ f"/marketplace/series/{series.id}/edit")
diff --git a/backend/app/marketplace/runtime.py b/backend/app/marketplace/runtime.py
new file mode 100644
index 0000000..05b6293
--- /dev/null
+++ b/backend/app/marketplace/runtime.py
@@ -0,0 +1,44 @@
+"""市场媒体循环独立托管,沿用主业务随 API 启停和看门狗恢复的方式。"""
+import asyncio
+import logging
+
+from .config import get_marketplace_settings
+from .worker import run_loop
+
+logger = logging.getLogger(__name__)
+_worker: asyncio.Task | None = None
+_watchdog: asyncio.Task | None = None
+
+
+async def _supervise():
+ global _worker
+ while True:
+ if _worker is None or _worker.done():
+ if _worker is not None and not _worker.cancelled():
+ error = _worker.exception()
+ if error:
+ logger.error("市场 Worker 异常退出,自动恢复", exc_info=(type(error), error, error.__traceback__))
+ _worker = asyncio.create_task(run_loop(), name="marketplace-media-worker")
+ await asyncio.sleep(2)
+
+
+async def start_marketplace_runtime():
+ global _watchdog
+ if not get_marketplace_settings().enabled:
+ return
+ if _watchdog is not None and not _watchdog.done():
+ return
+ _watchdog = asyncio.create_task(_supervise(), name="marketplace-worker-watchdog")
+
+
+async def stop_marketplace_runtime():
+ global _worker, _watchdog
+ # 先停看门狗,避免关闭期间把 Worker 再次拉起。
+ if _watchdog is not None:
+ _watchdog.cancel()
+ await asyncio.gather(_watchdog, return_exceptions=True)
+ _watchdog = None
+ if _worker is not None:
+ _worker.cancel()
+ await asyncio.gather(_worker, return_exceptions=True)
+ _worker = None
diff --git a/backend/app/marketplace/schemas.py b/backend/app/marketplace/schemas.py
new file mode 100644
index 0000000..285edf8
--- /dev/null
+++ b/backend/app/marketplace/schemas.py
@@ -0,0 +1,246 @@
+"""下游请求契约;完整更新配合版本号防止审核竞态。"""
+from datetime import datetime
+from typing import Literal
+
+from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, field_validator, model_validator
+
+
+class Input(BaseModel):
+ model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
+
+
+class Version(Input):
+ version: int = Field(ge=1)
+
+
+class WorkInput(Input):
+ title: str = Field(min_length=1, max_length=200)
+ description: str = Field(default="", max_length=5000)
+ category: str = Field(default="其他", min_length=1, max_length=60)
+ tags: list[str] = Field(default_factory=list, max_length=10)
+ price_fen: int = Field(ge=0, le=100_000_000)
+ sale_type: Literal["free", "copyright_contact", "platform_unlock"] = "copyright_contact"
+ unlock_price_fen: int = Field(default=0, ge=0, le=100_000_000)
+ share_bps: int | None = Field(default=None, ge=0, le=10000)
+ asset_id: int | None = Field(default=None, gt=0)
+ cover_asset_id: int | None = Field(default=None, gt=0)
+ source: Literal["printfilm", "external", "original", "ai", "authorized"] = "original"
+ license_scope: str = Field(default="", max_length=3000)
+
+ @field_validator("tags")
+ @classmethod
+ def validate_tags(cls, value: list[str]) -> list[str]:
+ """限制标签长度,避免无界公开字段。"""
+ if any(not tag.strip() or len(tag) > 30 for tag in value):
+ raise ValueError("标签应为1至30字")
+ return list(dict.fromkeys(tag.strip() for tag in value))
+
+ @field_validator("unlock_price_fen")
+ @classmethod
+ def validate_unlock_price(cls, value, info):
+ sale_type = info.data.get("sale_type", "copyright_contact")
+ if sale_type == "platform_unlock" and value <= 0:
+ raise ValueError("平台投放作品必须设置单独的解锁价")
+ if sale_type != "platform_unlock" and value:
+ raise ValueError("只有平台投放作品可以设置解锁价")
+ return value
+
+
+class WorkUpdate(WorkInput, Version):
+ pass
+
+
+class RightsDetails(Input):
+ author: str = Field(default="", max_length=200)
+ holder: str = Field(default="", max_length=200)
+ relationship: str = Field(default="", max_length=1000)
+ acquisition: Literal["original", "transferred", "authorized"] = "original"
+ source: Literal["printfilm", "external", "original", "ai", "authorized"] = "external"
+ scope: str = Field(default="", max_length=3000)
+ third_party: str = Field(default="", max_length=3000)
+ institution: str = Field(default="", max_length=200)
+ certificate_number: str = Field(default="", max_length=200)
+ ai_platform_license: str = Field(default="", max_length=3000)
+ ai_generation_record: str = Field(default="", max_length=3000)
+ human_contribution: str = Field(default="", max_length=3000)
+ dispute_ack: bool = False
+
+
+class RightsInput(Input):
+ version: int = Field(default=0, ge=0)
+ details: RightsDetails
+ certificate_asset_id: int | None = Field(default=None, gt=0)
+ evidence_ids: list[int] = Field(default_factory=list, max_length=20)
+ valid_until: AwareDatetime | None = None
+
+
+class CaseInput(Input):
+ version: int = Field(default=0, ge=0)
+ route: Literal["existing", "self_service", "assisted"]
+ official_reference: str = Field(default="", max_length=200)
+ note: str = Field(default="", max_length=3000)
+
+
+class RecruitInput(Input):
+ title: str = Field(min_length=1, max_length=200)
+ description: str = Field(min_length=1, max_length=5000)
+ category: str = Field(default="其他", min_length=1, max_length=60)
+ budget_fen: int = Field(gt=0, le=100_000_000)
+ wanted_count: int = Field(ge=1, le=10000)
+ requirements: str = Field(min_length=1, max_length=3000)
+ license_scope: str = Field(min_length=1, max_length=3000)
+ image_ids: list[int] = Field(default_factory=list, max_length=6)
+ deadline_at: AwareDatetime
+
+
+class RecruitUpdate(RecruitInput, Version):
+ pass
+
+
+class SubmissionInput(Input):
+ asset_id: int = Field(gt=0)
+ quote_fen: int = Field(gt=0, le=100_000_000)
+ description: str = Field(default="", max_length=3000)
+ rights_accepted: Literal[True]
+
+
+class SelectionInput(Input):
+ selection: Literal["to_review", "candidate", "not_selected"]
+
+
+class UploadInput(Input):
+ filename: str = Field(min_length=1, max_length=255)
+ size_bytes: int = Field(gt=0)
+ kind: Literal["video", "image", "document", "qr"]
+
+
+class ReviewInput(Version):
+ decision: Literal["approved", "rejected"]
+ reason: str = Field(min_length=1, max_length=3000)
+ checks: list[str] = Field(default_factory=list, max_length=12)
+
+
+class BlockInput(Input):
+ blocked: bool
+ reason: str = Field(min_length=1, max_length=3000)
+
+
+class CaseReview(Version):
+ status: Literal["pending_materials", "reviewing", "supplement", "applying", "certificated", "rejected", "cancelled"]
+ note: str = Field(min_length=1, max_length=3000)
+
+
+class SupportInput(Input):
+ name: str = Field(min_length=1, max_length=80)
+ wechat: str = Field(default="", max_length=100)
+ hours: str = Field(default="", max_length=100)
+ qr_asset_id: int | None = Field(default=None, gt=0)
+ enabled: bool = False
+
+
+class CategoryInput(Input):
+ version: int = Field(ge=0)
+ names: list[str] = Field(min_length=1, max_length=30)
+
+ @field_validator("names")
+ @classmethod
+ def validate_names(cls, value):
+ names = [name.strip() for name in value]
+ if any(not name or len(name) > 60 for name in names) or len(set(names)) != len(names):
+ raise ValueError("分类名称须为1至60字,且不能重复")
+ return names
+
+
+class Target(Input):
+ target_type: Literal["work", "recruit", "submission", "series_episode", "case"]
+ target_id: int = Field(gt=0)
+
+
+class ReportInput(Target):
+ statement: str = Field(min_length=10, max_length=5000)
+ contact: str = Field(min_length=1, max_length=200)
+ evidence_ids: list[int] = Field(default_factory=list, max_length=10)
+
+
+class ResolutionInput(Input):
+ resolution: str = Field(min_length=1, max_length=3000)
+
+
+class SeriesInput(Input):
+ title: str = Field(min_length=1, max_length=200)
+ description: str = Field(default="", max_length=5000)
+ category: str = Field(default="其他", min_length=1, max_length=60)
+ tags: list[str] = Field(default_factory=list, max_length=10)
+ cover_asset_id: int | None = Field(default=None, gt=0)
+ sale_type: Literal["free", "copyright_contact", "platform_unlock"] = "copyright_contact"
+ copyright_price_fen: int = Field(default=0, ge=0, le=100_000_000)
+ free_episode_count: int = Field(default=0, ge=0, le=10000)
+ share_bps: int | None = Field(default=None, ge=0, le=10000)
+
+
+class SeriesUpdate(SeriesInput, Version):
+ pass
+
+
+class EpisodeInput(Input):
+ episode_no: int = Field(ge=1, le=10000)
+ title: str = Field(min_length=1, max_length=200)
+ description: str = Field(default="", max_length=5000)
+ asset_id: int | None = Field(default=None, gt=0)
+ cover_asset_id: int | None = Field(default=None, gt=0)
+ copyright_price_fen: int = Field(default=0, ge=0, le=100_000_000)
+ unlock_price_fen: int = Field(default=0, ge=0, le=100_000_000)
+ share_bps: int | None = Field(default=None, ge=0, le=10000)
+ source: Literal["printfilm", "external", "original", "ai", "authorized"] = "external"
+
+
+class EpisodeUpdate(EpisodeInput, Version):
+ pass
+
+
+class ImportEpisodesInput(Input):
+ drama_project_id: int = Field(gt=0)
+ episode_ids: list[int] = Field(min_length=1, max_length=100)
+
+
+class PrintfilmWorkInput(Input):
+ project_id: int = Field(gt=0)
+ source_type: Literal["project_final"] = "project_final"
+ idempotency_key: str = Field(default="", max_length=120)
+
+
+class PrintfilmEpisodeInput(Input):
+ """漫剧分集或一部科普成片,二选一。客户端不能提交视频地址。"""
+ drama_project_id: int | None = Field(default=None, gt=0)
+ 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)
+
+ @model_validator(mode="after")
+ def choose_source(self):
+ has_drama = self.drama_project_id is not None and bool(self.episode_ids)
+ has_project = self.project_id is not None
+ if has_drama == has_project:
+ raise ValueError("请选择漫剧分集或一部科普成片")
+ if any(item <= 0 for item in self.episode_ids):
+ raise ValueError("分集编号无效")
+ return self
+
+
+class RevenueConfigInput(Input):
+ version: int = Field(ge=0)
+ platform_share_bps: int = Field(ge=0, le=10000)
+ enabled: bool = True
+
+
+class ContentOrderInput(Input):
+ publication_id: int = Field(gt=0)
+ pay_type: Literal["alipay", "wxpay"]
+ idempotency_key: str = Field(min_length=8, max_length=128)
+
+
+class PayoutInput(Input):
+ owner_id: int = Field(gt=0)
+ amount_fen: int = Field(gt=0, le=100_000_000_000)
+ status: Literal["pending", "paid", "failed"] = "pending"
+ note: str = Field(default="", max_length=3000)
diff --git a/backend/app/marketplace/series.py b/backend/app/marketplace/series.py
new file mode 100644
index 0000000..d6f6ac9
--- /dev/null
+++ b/backend/app/marketplace/series.py
@@ -0,0 +1,403 @@
+"""短剧系列市场 API。
+
+系列数据只使用 marketplace_ 表;原 drama 项目仅在用户明确导入时读取一次快照。
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+from fastapi import APIRouter, Query
+from sqlalchemy import and_, not_, or_, select
+
+from app.models_drama import DramaEpisode, DramaEpisodeFragment, DramaProject
+from .dependencies import Actor, DB, Visitor, storage_ready
+from .models import Asset, EpisodePreview, PlaybackJob, Publication, RevenueConfig, Rights, Series, SeriesEpisode
+from .schemas import EpisodeInput, EpisodeUpdate, ImportEpisodesInput, SeriesInput, SeriesUpdate, Version
+from .service import asset_owned, asset_owned_for_draft, check_version, data, event, fail, now, notify, owned, page, validate_rights
+
+router = APIRouter()
+
+
+def _sale_type(value: str, copyright_price: int) -> str:
+ # 收费类型由用户明确选择;参考价为0仍可以先联系客服询价。
+ return value
+
+
+async def _series(db, series_id: int, user, *, lock: bool = False) -> Series:
+ query = select(Series).where(Series.id == series_id)
+ if lock:
+ query = query.with_for_update()
+ item = (await db.execute(query)).scalar_one_or_none()
+ if not item or (item.owner_id != user.id and user.role != "admin"):
+ fail("系列不存在或无权访问", 404)
+ return item
+
+
+async def _episode(db, episode_id: int, user, *, lock: bool = False) -> SeriesEpisode:
+ query = select(SeriesEpisode).where(SeriesEpisode.id == episode_id)
+ if lock:
+ query = query.with_for_update()
+ item = (await db.execute(query)).scalar_one_or_none()
+ if not item or (item.owner_id != user.id and user.role != "admin"):
+ fail("分集不存在或无权访问", 404)
+ return item
+
+
+async def _episode_data(db, item: SeriesEpisode, *, private: bool = False) -> dict:
+ asset = await db.get(Asset, item.asset_id) if item.asset_id else None
+ result = data(item, "id", "series_id", "episode_no", "title", "description", "copyright_price_fen", "unlock_price_fen", "share_bps", "source", "source_type", "version", "preview_status", "playback_status", "created_at")
+ result.update(media_status=asset.status if asset else "missing", duration_seconds=asset.duration_seconds if asset else None)
+ if private:
+ result.update(data(item, "owner_id", "asset_id", "cover_asset_id", "audit_status", "listed", "blocked", "reason", "source_snapshot"))
+ rights = (await db.execute(select(Rights).where(Rights.asset_id == item.asset_id))).scalar_one_or_none() if item.asset_id else None
+ result.update(rights_ready=bool(rights and rights.basic_status == "approved" and rights.full_status == "approved"), rights_source=rights.details.get("source") if rights else None)
+ return result
+
+
+async def _series_data(db, item: Series, *, private: bool = False) -> dict:
+ episodes = (await db.execute(select(SeriesEpisode).where(SeriesEpisode.series_id == item.id).order_by(SeriesEpisode.episode_no))).scalars().all()
+ result = data(item, "id", "title", "description", "category", "tags", "cover_asset_id", "sale_type", "copyright_price_fen", "free_episode_count", "created_at")
+ result["episode_count"] = len(episodes)
+ 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"))
+ return result
+
+
+def public_series_filters():
+ """作品广场只展示已上架、且每一集都有水印文件的短剧。改免费集数不要求重做。"""
+ watermarked = or_(
+ EpisodePreview.object_key.startswith("marketplace/series-watermarks-full/"),
+ EpisodePreview.object_key.startswith("marketplace/series-previews-hq/"),
+ )
+ missing = select(SeriesEpisode.id).where(
+ SeriesEpisode.series_id == Series.id,
+ not_(select(EpisodePreview.id).where(
+ EpisodePreview.episode_id == SeriesEpisode.id,
+ EpisodePreview.asset_id == SeriesEpisode.asset_id,
+ EpisodePreview.status == "done",
+ watermarked,
+ ).exists()),
+ ).exists()
+ has_episode = select(SeriesEpisode.id).where(SeriesEpisode.series_id == Series.id).exists()
+ return (Series.listed.is_(True), Series.blocked.is_(False), Series.audit_status == "approved", has_episode, not_(missing))
+
+
[email protected]("/series", response_model=dict)
+async def list_series(db: DB, q: str = Query("", max_length=100), category: str = Query("", max_length=60), page_number: int = Query(1, alias="page", ge=1), page_size: int = Query(20, ge=1, le=100)):
+ query = select(Series).where(*public_series_filters())
+ if q:
+ query = query.where(Series.title.ilike(f"%{q}%"))
+ if category:
+ query = query.where(Series.category == category)
+ records, meta = await page(db, query.order_by(Series.id.desc()), page_number, page_size)
+ return {"items": [await _series_data(db, row) for row in records], "meta": meta}
+
+
[email protected]("/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
+ projects = 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})
+ return {"items": result}
+
+
[email protected]("/series/{series_id}", response_model=dict)
+async def get_series(series_id: int, db: DB, user: Visitor):
+ item = await db.get(Series, series_id)
+ private = bool(item and user and (item.owner_id == user.id or user.role == "admin"))
+ if not item or (not private and item.blocked):
+ fail("系列不存在或未公开", 404)
+ if not private:
+ visible = (await db.execute(select(Series.id).where(Series.id == series_id, *public_series_filters()))).scalar_one_or_none()
+ if not visible:
+ fail("系列不存在或未公开", 404)
+ return await _series_data(db, item, private=private)
+
+
[email protected]("/series", response_model=dict)
+async def create_series(body: SeriesInput, db: DB, user: Actor):
+ from .categories import validate_category
+ await validate_category(db, body.category)
+ if body.cover_asset_id:
+ await asset_owned(db, body.cover_asset_id, user, ("image",))
+ values = body.model_dump()
+ if "sale_type" not in body.model_fields_set and values["copyright_price_fen"] == 0:
+ values["sale_type"] = "free"
+ item = Series(owner_id=user.id, **values)
+ item.sale_type = _sale_type(item.sale_type, item.copyright_price_fen)
+ db.add(item)
+ await db.commit()
+ return await _series_data(db, item, private=True)
+
+
[email protected]("/series/{series_id}", response_model=dict)
+async def update_series(series_id: int, body: SeriesUpdate, db: DB, user: Actor):
+ item = await _series(db, series_id, user, lock=True)
+ check_version(item, body.version)
+ from .categories import validate_category
+ await validate_category(db, body.category, item.category)
+ if body.cover_asset_id:
+ await asset_owned(db, body.cover_asset_id, user, ("image",))
+ values = body.model_dump(exclude={"version"})
+ if "sale_type" not in body.model_fields_set and values["copyright_price_fen"] == 0:
+ values["sale_type"] = "free"
+ values["sale_type"] = _sale_type(values["sale_type"], values["copyright_price_fen"])
+ for key, value in values.items():
+ setattr(item, key, value)
+ item.version += 1
+ item.audit_status, item.listed, item.reason = "draft", False, ""
+ await db.execute(select(SeriesEpisode).where(SeriesEpisode.series_id == item.id).with_for_update())
+ await db.commit()
+ return await _series_data(db, item, private=True)
+
+
[email protected]("/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)
+ 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)
+ if body.asset_id:
+ 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",))
+ item = SeriesEpisode(series_id=series.id, owner_id=user.id, source_type="upload", **body.model_dump())
+ if series.sale_type == "platform_unlock" and item.unlock_price_fen <= 0:
+ fail("平台投放系列必须为每集设置解锁价")
+ db.add(item)
+ series.version += 1
+ series.audit_status, series.listed = "draft", False
+ await db.commit()
+ return await _episode_data(db, item, private=True)
+
+
[email protected]("/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)
+ item = await _episode(db, episode_id, user, lock=True)
+ if item.series_id != series.id:
+ fail("分集不属于该系列", 404)
+ check_version(item, body.version)
+ if body.asset_id:
+ 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",))
+ for key, value in body.model_dump(exclude={"version"}).items():
+ setattr(item, key, value)
+ item.version += 1
+ item.audit_status, item.listed, item.reason = "draft", False, ""
+ series.version += 1
+ series.audit_status, series.listed = "draft", False
+ await db.commit()
+ return await _episode_data(db, item, private=True)
+
+
[email protected]("/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)
+ item = await _episode(db, episode_id, user, lock=True)
+ if item.series_id != series.id:
+ fail("分集不属于该系列", 404)
+ await db.delete(item)
+ series.version += 1
+ series.audit_status, series.listed = "draft", False
+ await db.commit()
+ return {"ok": True}
+
+
[email protected]("/series/{series_id}/episodes/import", response_model=dict)
+async def import_episodes(series_id: int, body: ImportEpisodesInput, db: DB, user: Actor):
+ """只导入用户明确选择的漫剧分集。复制交给市场 Worker,请求本身不等待长视频。"""
+ from .handoff import enqueue_series_import
+ from .schemas import PrintfilmEpisodeInput
+
+ payload = PrintfilmEpisodeInput(drama_project_id=body.drama_project_id, episode_ids=list(body.episode_ids))
+ return await enqueue_series_import(series_id, payload, db, user)
+
+
[email protected]("/series/{series_id}/submit", response_model=dict)
+async def submit_series(series_id: int, body: Version, db: DB, user: Actor):
+ series = await _series(db, series_id, user, lock=True)
+ check_version(series, body.version)
+ if series.blocked:
+ fail("系列已被管理员封禁")
+ 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("至少添加一集后才能提交审核")
+ if [episode.episode_no for episode in episodes] != list(range(1, len(episodes) + 1)):
+ fail("分集编号必须从1开始连续排列")
+ config = await db.get(RevenueConfig, 1)
+ if series.sale_type == "platform_unlock" and (not config or not config.enabled):
+ fail("MARKETPLACE_REVENUE_CONFIG_REQUIRED", 409)
+ # Paid series require a real private bucket because the submission creates
+ # a preview job that will immediately be consumed by the market Worker.
+ # Reject early with the standard 503 instead of leaving a misleading pending
+ # job when OSS is not configured.
+ await storage_ready()
+ from .previews import is_watermark_key
+ pending_preview = False
+ for episode in episodes:
+ 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)
+ 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 series.sale_type == "platform_unlock" and episode.unlock_price_fen <= 0:
+ fail(f"第{episode.episode_no}集必须设置解锁价")
+ # 同一原片已有水印就沿用,改免费集数或收费类型不重新转码。
+ done = (await db.execute(select(EpisodePreview).where(
+ EpisodePreview.episode_id == episode.id, EpisodePreview.asset_id == asset.id,
+ EpisodePreview.status == "done").order_by(EpisodePreview.id.desc()).limit(1))).scalar_one_or_none()
+ preview = (await db.execute(select(EpisodePreview).where(
+ EpisodePreview.episode_id == episode.id, EpisodePreview.asset_id == asset.id,
+ EpisodePreview.version == episode.version).with_for_update())).scalar_one_or_none()
+ if done and is_watermark_key(done.object_key):
+ if preview is None:
+ preview = EpisodePreview(episode_id=episode.id, asset_id=asset.id, version=episode.version, status="done", object_key=done.object_key)
+ db.add(preview)
+ elif preview.id != done.id:
+ preview.status, preview.object_key, preview.error = "done", done.object_key, ""
+ preview_status = "done"
+ else:
+ if preview is None:
+ preview = EpisodePreview(episode_id=episode.id, asset_id=asset.id, version=episode.version)
+ db.add(preview)
+ elif preview.status == "failed":
+ preview.status, preview.attempts, preview.error, preview.object_key = "pending", 0, "", None
+ preview.lease_token, preview.lease_until = None, None
+ preview_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()
+ 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,
+ 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")
+ # Keep the episode's live access gate in sync with its immutable
+ # publication. In particular, a paid episode must be marked pending
+ # immediately so /media cannot fall back to the original while the
+ # watermark job is still running.
+ episode.preview_status = preview_status
+ episode.playback_status = "done" if series.sale_type != "platform_unlock" else "pending"
+ if publication is None:
+ publication = Publication(content_type="series_episode", content_id=episode.id, **values)
+ db.add(publication)
+ else:
+ for key, value in values.items():
+ setattr(publication, key, value)
+ if series.sale_type == "platform_unlock":
+ await db.flush()
+ playback_job = (await db.execute(select(PlaybackJob).where(
+ PlaybackJob.publication_id == publication.id
+ ).with_for_update())).scalar_one_or_none()
+ if playback_job is None:
+ db.add(PlaybackJob(publication_id=publication.id, status="pending"))
+ else:
+ playback_job.status, playback_job.error = "pending", ""
+ playback_job.attempts = 0
+ playback_job.lease_token, playback_job.lease_until = None, None
+ publication.playback_manifest_key = None
+ publication.playback_error = ""
+ episode.audit_status = "pending"
+ episode.listed = False
+ rights.basic_status = rights.full_status = "pending"
+ series.audit_status = "processing" if pending_preview else "pending"
+ series.listed, series.reason = False, "正在生成水印播放文件" if pending_preview else ""
+ event(db, user.id, "series", series.id, "submitted", version=series.version)
+ await db.commit()
+ return await _series_data(db, series, private=True)
+
+
[email protected]("/series/{series_id}/listing", response_model=dict)
+async def listing_series(series_id: int, body: Version, db: DB, user: Actor, listed: bool = True):
+ series = await _series(db, series_id, user, lock=True)
+ check_version(series, body.version)
+ # Lock and snapshot the current episode versions once. Historical
+ # publications are kept for entitlements but must never be relisted when a
+ # newer episode version is approved.
+ episodes = list((await db.execute(
+ select(SeriesEpisode).where(SeriesEpisode.series_id == series.id).with_for_update()
+ )).scalars().all())
+ if listed:
+ if series.blocked or series.audit_status != "approved":
+ fail("系列内容或权属尚未通过,不能上架")
+ if not episodes:
+ fail("系列没有可上架的分集")
+ from .previews import is_watermark_key
+ for episode in episodes:
+ if episode.blocked or episode.audit_status != "approved":
+ fail(f"第{episode.episode_no}集尚未审核通过")
+ preview = (await db.execute(select(EpisodePreview).where(
+ EpisodePreview.episode_id == episode.id, EpisodePreview.asset_id == episode.asset_id,
+ EpisodePreview.status == "done").order_by(EpisodePreview.id.desc()).limit(1))).scalar_one_or_none()
+ if not preview or not is_watermark_key(preview.object_key):
+ fail(f"第{episode.episode_no}集水印播放文件尚未生成", 409)
+ if series.sale_type == "platform_unlock":
+ publication = (await db.execute(select(Publication).where(Publication.content_type == "series_episode", Publication.content_id == episode.id, Publication.version == episode.version))).scalar_one_or_none()
+ if not publication or publication.playback_status != "done":
+ fail(f"第{episode.episode_no}集播放版本尚未就绪", 409)
+ series.listed = listed
+ episode_ids = [episode.id for episode in episodes]
+ publications = []
+ if episode_ids:
+ publications = list((await db.execute(
+ select(Publication).where(
+ Publication.content_type == "series_episode",
+ Publication.content_id.in_(episode_ids),
+ ).with_for_update()
+ )).scalars().all())
+ for publication in publications:
+ is_current = any(
+ episode.id == publication.content_id and episode.version == publication.version
+ for episode in episodes
+ )
+ publication.listed = listed and is_current and publication.audit_status == "approved" and (
+ series.sale_type != "platform_unlock" or publication.playback_status == "done"
+ )
+ for episode in episodes:
+ episode.listed = listed and episode.audit_status == "approved" and not episode.blocked
+ await db.commit()
+ return await _series_data(db, series, private=True)
+
diff --git a/backend/app/marketplace/service.py b/backend/app/marketplace/service.py
new file mode 100644
index 0000000..ee63721
--- /dev/null
+++ b/backend/app/marketplace/service.py
@@ -0,0 +1,255 @@
+"""下游共享业务规则;审核、访问与咨询复用同一就绪判定。"""
+from datetime import datetime, timezone
+import hashlib
+import json
+
+from fastapi import HTTPException
+from sqlalchemy import and_, func, not_, or_, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models import User
+from .models import Asset, Event, Notification, Recruit, RegistrationCase, Rights, Submission, Work, WorkPreview
+
+
+def now() -> datetime:
+ """统一使用 UTC,展示层负责北京时间格式化。"""
+ return datetime.now(timezone.utc)
+
+
+def fail(message: str, status: int = 400) -> None:
+ """抛出可读业务错误。"""
+ raise HTTPException(status, detail=message)
+
+
+def check_version(record, version: int) -> None:
+ """锁定后比较版本,拒绝过期页面提交和旧审核结论。"""
+ if record.version != version:
+ fail("内容已更新,请刷新后重新操作", 409)
+
+
+async def owned(db: AsyncSession, model, record_id: int, user: User, *, admin: bool = False):
+ """锁定独立记录并验证所属用户。"""
+ record = (await db.execute(select(model).where(model.id == record_id).with_for_update())).scalar_one_or_none()
+ if record is None or (record.owner_id != user.id and not (admin and user.role == "admin")):
+ fail("记录不存在或无权访问", 404)
+ return record
+
+
+async def asset_owned(db: AsyncSession, asset_id: int, user: User, kinds: tuple[str, ...] = ("video",)) -> Asset:
+ """只接受本人的已就绪媒体,不接受任意 URL 或上游资源。"""
+ asset = await owned(db, Asset, asset_id, user)
+ if asset.kind not in kinds or asset.status != "ready":
+ fail("文件尚未处理完成或类型不正确")
+ return asset
+
+
+async def asset_owned_for_draft(db: AsyncSession, asset_id: int, user: User, kinds: tuple[str, ...] = ("video",)) -> Asset:
+ """草稿可绑定上传中/处理中媒体;发布前仍由 asset_owned 强制 ready。"""
+ asset = await owned(db, Asset, asset_id, user)
+ if asset.kind not in kinds or asset.status in ("failed", "expired"):
+ fail("文件不存在、已失败或类型不正确")
+ return asset
+
+
+async def rights_for(db: AsyncSession, asset_id: int | None, *, lock: bool = False) -> Rights | None:
+ """读取媒体绑定的权属档案。"""
+ query = select(Rights).where(Rights.asset_id == asset_id)
+ if lock:
+ query = query.with_for_update()
+ return (await db.execute(query)).scalar_one_or_none()
+
+
+def rights_valid(rights: Rights | None, *, full: bool = False) -> bool:
+ """权属过期、封禁或版本更新时,立即停止依赖它的访问。"""
+ if not rights or rights.blocked or (rights.valid_until and rights.valid_until <= now()):
+ return False
+ if rights.basic_status != "approved":
+ return False
+ if rights.details.get("source") == "printfilm" and not full_proof_present(rights):
+ return False
+ return not full or (rights.full_status == "approved" and full_proof_present(rights))
+
+
+def full_proof_present(rights: Rights) -> bool:
+ """本平台绑定现行授权函;外部来源绑定证明文件,旧档案沿用证书规则。"""
+ if rights.details.get("source") == "printfilm":
+ from .authorization import VERSION
+ return bool(rights.details.get("authorization_id") and rights.details.get("authorization_version") == VERSION)
+ return bool(rights.certificate_asset_id)
+
+
+def public_work_filters() -> tuple:
+ """列表与详情使用相同 SQL 条件,价格筛选前即排除不可售作品。"""
+ from .authorization import VERSION
+ proof = or_(and_(Rights.details["source"].as_string() == "printfilm",
+ Rights.details["authorization_id"].as_string().is_not(None),
+ Rights.details["authorization_version"].as_string() == VERSION),
+ and_(Rights.details["source"].as_string() != "printfilm", Rights.certificate_asset_id.is_not(None)))
+ def watermark_exists(prefix: str):
+ return select(WorkPreview.id).where(
+ WorkPreview.work_id == Work.id, WorkPreview.asset_id == Work.asset_id,
+ WorkPreview.status == "done", WorkPreview.object_key.startswith(prefix)).exists()
+
+ return (Work.listed.is_(True), Work.blocked.is_(False), Work.audit_status == "approved",
+ Asset.status == "ready", Rights.basic_status == "approved", Rights.full_status == "approved",
+ # 免费作品可直接上架。标价为 0 的作品和收费作品只要已有水印文件就进入广场。
+ or_(Work.sale_type == "free",
+ watermark_exists("marketplace/work-watermarks-full/"),
+ watermark_exists("marketplace/work-previews-hq/")),
+ proof, Rights.blocked.is_(False),
+ Rights.details["source"].as_string() == Work.source,
+ or_(Rights.valid_until.is_(None), Rights.valid_until > now()))
+
+
+def public_recruit_filters() -> tuple:
+ """招募到期在每次请求时校验,不依赖维护任务及时运行。"""
+ return (Recruit.audit_status == "approved", Recruit.state == "open", Recruit.blocked.is_(False), Recruit.deadline_at > now())
+
+
+async def is_public_work(db: AsyncSession, work_id: int) -> bool:
+ """统一判断作品是否允许公众播放或咨询购买。"""
+ query = select(Work.id).join(Asset, Asset.id == Work.asset_id).join(Rights, Rights.asset_id == Asset.id).where(Work.id == work_id, *public_work_filters())
+ return (await db.execute(query)).scalar_one_or_none() is not None
+
+
+def recruit_open(post: Recruit) -> bool:
+ """投稿写入前实时检查截止、审核和关闭状态。"""
+ return post.state == "open" and post.audit_status == "approved" and not post.blocked and post.deadline_at > now()
+
+
+def event(db: AsyncSession, actor: int, kind: str, target: int, action: str, note: str = "", version: int | None = None) -> None:
+ """保留审核与敏感访问审计,不保存密码或签名 URL。"""
+ db.add(Event(actor_id=actor, target_type=kind, target_id=target, action=action, note=note, version=version))
+
+
+def notify(db: AsyncSession, owner: int, message: str, link: str = "/marketplace/mine") -> None:
+ """站内消息与业务事务一并提交,不依赖 SMTP。"""
+ db.add(Notification(owner_id=owner, message=message, link=link))
+
+
+def data(record, *fields: str) -> dict:
+ """显式字段序列化,禁止把 ORM 整行直接暴露给公众。"""
+ return {field: getattr(record, field) for field in fields}
+
+
+async def work_data(db: AsyncSession, work: Work, private: bool = False) -> dict:
+ """公开资料不包含邮箱、原片位置和权属材料。"""
+ owner = await db.get(User, work.owner_id)
+ asset = await db.get(Asset, work.asset_id) if work.asset_id else None
+ result = data(work, "id", "title", "description", "category", "tags", "price_fen", "sale_type", "unlock_price_fen", "share_bps", "source", "license_scope", "created_at")
+ result.update(author=owner.nickname if owner else "创作者", duration_seconds=asset.duration_seconds if asset else None)
+ if private:
+ from .previews import is_watermark_key, preview_for
+ preview = await preview_for(db, work)
+ usable = bool(preview and (preview.status != "done" or is_watermark_key(preview.object_key)))
+ result["preview_status"] = preview.status if usable else "missing"
+ result["preview_error"] = preview.error if preview else ""
+ result.update(data(work, "owner_id", "asset_id", "cover_asset_id", "version", "audit_status", "listed", "blocked", "reason"))
+ result["media_status"] = asset.status if asset else "missing"
+ rights = await rights_for(db, work.asset_id)
+ result["basic_status"] = rights.basic_status if rights else "missing"
+ result["full_status"] = rights.full_status if rights else "missing"
+ result["rights_ready"] = rights_valid(rights, full=True) and rights.details.get("source") == work.source
+ result["rights_source"] = rights.details.get("source") if rights else None
+ result["rights_complete"] = False
+ if rights and not rights.blocked and rights.details.get("source") == work.source:
+ try:
+ validate_rights(rights.details, full=True, certificate=bool(rights.certificate_asset_id))
+ result["rights_complete"] = True
+ except HTTPException:
+ pass
+ return result
+
+
+async def recruit_data(db: AsyncSession, post: Recruit, private: bool = False) -> dict:
+ """招募公开说明不包含私密投稿。"""
+ owner = await db.get(User, post.owner_id)
+ result = data(post, "id", "title", "description", "category", "budget_fen", "wanted_count", "requirements", "license_scope", "image_ids", "deadline_at", "created_at")
+ result["author"] = owner.nickname if owner else "需求发布者"
+ if private:
+ result.update(data(post, "owner_id", "version", "audit_status", "state", "blocked", "reason"))
+ result["submission_count"] = (await db.execute(select(func.count()).select_from(Submission).where(Submission.recruit_id == post.id))).scalar_one()
+ return result
+
+
+async def submission_data(db: AsyncSession, item: Submission, user: User) -> dict:
+ """仅相关双方可看投稿,签名接口仍再次检查基础核验。"""
+ post = await db.get(Recruit, item.recruit_id)
+ if user.id not in (item.owner_id, post.owner_id) and user.role != "admin":
+ fail("无权访问投稿", 404)
+ rights = await rights_for(db, item.asset_id)
+ result = data(item, "id", "recruit_id", "owner_id", "asset_id", "quote_fen", "description", "snapshot", "selection", "withdrawn", "blocked", "created_at")
+ matching = submission_rights_match(item, rights)
+ result.update(recruit_title=post.title, can_review=matching and not item.withdrawn and not item.blocked and not post.blocked and rights_valid(rights),
+ can_purchase=matching and not item.withdrawn and not item.blocked and not post.blocked and rights_valid(rights, full=True))
+ return result
+
+
+def rights_identity(rights: Rights) -> str:
+ """补交证书不改变投稿;作者、权利人或授权范围变化则必须重新投稿。"""
+ identity = {key: rights.details.get(key, "") for key in ("author", "holder", "relationship", "acquisition", "source", "scope")}
+ return hashlib.sha256(json.dumps(identity, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
+
+
+def submission_rights_match(item: Submission, rights: Rights | None) -> bool:
+ """以稳定权利指纹校验快照,不因补材料版本增加而丢失候选。"""
+ return bool(rights and item.snapshot.get("rights_identity") == rights_identity(rights))
+
+
+async def page(db: AsyncSession, query, page_number: int, page_size: int) -> tuple[list, dict]:
+ """数据库分页,避免全量数据下发再切片。"""
+ total = (await db.execute(select(func.count()).select_from(query.order_by(None).subquery()))).scalar_one()
+ records = list((await db.execute(query.offset((page_number - 1) * page_size).limit(page_size))).scalars().all())
+ return records, {"page": page_number, "page_size": page_size, "total": total}
+
+
+def validate_rights(details: dict, *, full: bool, certificate: bool) -> None:
+ """按来源执行最小必要核验材料,避免让用户重复填写无关信息。"""
+ source = details.get("source")
+ if source == "printfilm":
+ from .authorization import VERSION
+ if not details.get("authorization_id") or details.get("authorization_version") != VERSION:
+ fail("请先签署现行 PrintFilm 授权函,再保存权属档案以关联签署记录")
+ return
+ if source == "external" and full:
+ if not certificate or not str(details.get("certificate_number", "")).strip():
+ fail("请填写版权证书编号并上传截图或照片;没有版权材料可联系客服协办")
+ if not details.get("dispute_ack"):
+ fail("请确认版权纠纷与平台无关")
+ if source not in ("printfilm", "external"):
+ fields = ["author", "holder", "relationship", "acquisition", "scope", "third_party"]
+ if source == "ai":
+ fields.extend(["ai_platform_license", "ai_generation_record", "human_contribution"])
+ if full:
+ fields.extend(["institution", "certificate_number"])
+ if not certificate:
+ fail("请上传版权证书")
+ if any(not str(details.get(key, "")).strip() for key in fields):
+ fail("请补齐版权信息")
+
+
+async def get_target(db: AsyncSession, kind: str, target_id: int, user: User):
+ """咨询和举报共用可访问目标检查,防止凭编号枚举私密投稿。"""
+ from .models import Series, SeriesEpisode
+ model = {"work": Work, "recruit": Recruit, "submission": Submission, "series_episode": SeriesEpisode, "case": RegistrationCase}[kind]
+ record = await db.get(model, target_id)
+ if not record:
+ fail("内容不存在", 404)
+ if user.role == "admin" or record.owner_id == user.id:
+ return record
+ if kind == "work" and await is_public_work(db, target_id):
+ return record
+ if kind == "recruit" and recruit_open(record):
+ return record
+ if kind == "submission":
+ post = await db.get(Recruit, record.recruit_id)
+ if post.owner_id == user.id and not record.withdrawn:
+ return record
+ if kind == "series_episode":
+ series = await db.get(Series, record.series_id)
+ if (series and series.sale_type == "copyright_contact" and series.listed
+ and series.audit_status == "approved" and record.listed
+ and record.audit_status == "approved" and not series.blocked
+ and not record.blocked):
+ return record
+ fail("内容不存在或无权访问", 404)
diff --git a/backend/app/marketplace/storage.py b/backend/app/marketplace/storage.py
new file mode 100644
index 0000000..7ac0842
--- /dev/null
+++ b/backend/app/marketplace/storage.py
@@ -0,0 +1,168 @@
+"""共用后台 OSS 配置,独立私有对象;不复用公开上传函数。"""
+from functools import lru_cache, wraps
+import json
+from pathlib import Path
+import time
+
+from fastapi import HTTPException
+from app.config import get_settings
+
+from .config import get_marketplace_settings
+
+# 已核验客户端及核验时刻;一分钟后重新检查 Bucket 权限。
+_verified_at: float = 0
+_verified_client = None
+
+
+def unavailable() -> HTTPException:
+ """统一文件服务缺失或不可用错误,避免泄漏凭证。"""
+ return HTTPException(503, detail={"code": "MARKETPLACE_STORAGE_UNAVAILABLE", "message": "文件服务暂未配置或不可用"})
+
+
+def configured() -> bool:
+ """仅检查配置完整性,不联网、不修改云资源。"""
+ s = get_settings()
+ return bool(s.oss_enabled and s.oss_endpoint and s.oss_bucket and s.oss_access_key_id and s.oss_access_key_secret)
+
+
+def transport(operation):
+ """云端操作失败统一返回503,不向业务响应暴露SDK或凭证错误。"""
+ @wraps(operation)
+ def guarded(*args, **kwargs):
+ try:
+ return operation(*args, **kwargs)
+ except HTTPException:
+ raise
+ except Exception as exc:
+ raise unavailable() from exc
+ return guarded
+
+
+def _client():
+ """读取后台生效配置;保存或清除凭证后立即切换客户端。"""
+ s = get_settings()
+ if not configured():
+ raise unavailable()
+ return _shared_client(s.oss_endpoint, s.oss_bucket, s.oss_access_key_id, s.oss_access_key_secret)
+
+
+@lru_cache(maxsize=1)
+def _shared_client(endpoint: str, bucket_name: str, key_id: str, key_secret: str):
+ """按完整配置缓存,禁止混用不同配置的凭证和 Bucket。"""
+ import oss2
+ auth = oss2.Auth(key_id, key_secret)
+ endpoint = endpoint if "://" in endpoint else f"https://{endpoint}"
+ if not endpoint.startswith("https://"):
+ raise unavailable()
+ return oss2.Bucket(auth, endpoint, bucket_name, connect_timeout=15)
+
+
+def bucket():
+ """检查私有 ACL 和禁止匿名读取的 Bucket policy,失败关闭。"""
+ global _verified_at, _verified_client
+ try:
+ client = _client()
+ if client is not _verified_client or time.monotonic() - _verified_at > 60:
+ if client.get_bucket_acl().acl != "private":
+ raise unavailable()
+ try:
+ policy = json.loads(client.get_bucket_policy().policy)
+ statements = policy.get("Statement", [])
+ if isinstance(statements, dict):
+ statements = [statements]
+ for statement in statements:
+ if statement.get("Effect", "").lower() != "allow":
+ continue
+ principal = statement.get("Principal", "")
+ # 下游不接受任何匿名授权策略,避免条件或资源规则被误判。
+ if "*" in json.dumps(principal):
+ raise unavailable()
+ except Exception as exc:
+ # Aliyun returns 404/NoSuchBucketPolicy when no optional bucket
+ # policy has ever been created. A private ACL is sufficient for
+ # the marketplace, so treat that absence as an empty policy;
+ # genuine permission/network failures still disable storage.
+ details = getattr(exc, "details", {}) or {}
+ code = str(getattr(exc, "code", "") or details.get("Code", "") or "")
+ if code != "NoSuchBucketPolicy" and "NoSuchBucketPolicy" not in str(exc):
+ raise
+ _verified_at = time.monotonic()
+ _verified_client = client
+ return client
+ except HTTPException:
+ raise
+ except Exception as exc:
+ raise unavailable() from exc
+
+
+@transport
+def initiate(key: str, content_type: str) -> str:
+ """初始化私有 multipart 对象。"""
+ return bucket().init_multipart_upload(key, headers={"Content-Type": content_type, "x-oss-object-acl": "private"}).upload_id
+
+
+@transport
+def part(key: str, remote_id: str, number: int, data: bytes) -> str:
+ """只转发单个受限大小分片。"""
+ return bucket().upload_part(key, remote_id, number, data).etag
+
+
+@transport
+def complete(key: str, remote_id: str, parts: dict) -> None:
+ """按分片序号完成上传;对上传已完成但事务重试的情况保持幂等。"""
+ from oss2.models import PartInfo
+ client = bucket()
+ try:
+ client.complete_multipart_upload(key, remote_id, [PartInfo(int(n), item["etag"]) for n, item in sorted(parts.items(), key=lambda x: int(x[0]))])
+ except Exception as exc:
+ if getattr(exc, "code", "") != "NoSuchUpload" or not client.object_exists(key):
+ raise
+
+
+@transport
+def abort(key: str, remote_id: str) -> None:
+ """清理未完成上传;重复取消不报错。"""
+ try:
+ bucket().abort_multipart_upload(key, remote_id)
+ except Exception as exc:
+ if getattr(exc, "code", "") != "NoSuchUpload":
+ raise
+
+
+@transport
+def head(key: str) -> int:
+ """取得 OSS 真实字节数进行完成校验。"""
+ return int(bucket().head_object(key).content_length)
+
+
+@transport
+def download(key: str, path: Path) -> None:
+ """下载到非公开临时工作目录供检测和 FFmpeg 使用。"""
+ bucket().get_object_to_file(key, str(path))
+
+
+@transport
+def read(key: str) -> bytes:
+ """读取短时播放清单;只允许服务端在鉴权后读取,不向业务返回 OSS 地址。"""
+ return bucket().get_object(key).read()
+
+
+@transport
+def upload(key: str, path: Path, content_type: str) -> None:
+ """处理结果成功写入私有 OSS 后才允许业务置为 ready。"""
+ bucket().put_object_from_file(key, str(path), headers={"Content-Type": content_type, "x-oss-object-acl": "private"})
+
+
+@transport
+def copy_private(source_key: str, dest_key: str, content_type: str) -> int:
+ """同桶复制到市场前缀,不把对象下载到浏览器。"""
+ client = bucket()
+ client.copy_object(client.bucket_name, source_key, dest_key, headers={"Content-Type": content_type, "x-oss-object-acl": "private"})
+ return int(client.head_object(dest_key).content_length)
+
+
+@transport
+def signed(key: str, content_type: str = "application/octet-stream") -> str:
+ """使用上传时的对象 Content-Type;不覆盖响应头,避免 OSS 拒绝预览。"""
+ return bucket().sign_url("GET", key, get_marketplace_settings().signed_url_seconds,
+ slash_safe=True)
diff --git a/backend/app/marketplace/uploads.py b/backend/app/marketplace/uploads.py
new file mode 100644
index 0000000..2a88db0
--- /dev/null
+++ b/backend/app/marketplace/uploads.py
@@ -0,0 +1,146 @@
+"""受限分片转发到私有 OSS;本地不配置时明确拒绝。"""
+import asyncio
+from datetime import timedelta
+import math
+from pathlib import PurePath
+import uuid
+
+from fastapi import APIRouter, Depends, Request
+from sqlalchemy import select
+
+from . import storage
+from .config import get_marketplace_settings
+from .dependencies import Actor, DB, storage_ready
+from .models import Asset, MediaJob, Upload
+from .schemas import UploadInput
+from .service import data, event, fail, now, owned
+
+router = APIRouter()
+# 只允许不能执行脚本的业务文件类型;由 Worker 检查真实文件头。
+VIDEO_TYPES = {".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm"}
+IMAGE_TYPES = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp"}
+
+
[email protected]("/uploads", response_model=dict, dependencies=[Depends(storage_ready)])
+async def initiate_upload(body: UploadInput, db: DB, user: Actor):
+ """上传会话使用共用 Bucket 的市场目录和随机对象名。"""
+ settings = get_marketplace_settings()
+ filename = body.filename.replace("\\", "/").split("/")[-1]
+ extension = PurePath(filename).suffix.lower()
+ allowed = VIDEO_TYPES if body.kind == "video" else {**IMAGE_TYPES, **({".pdf": "application/pdf"} if body.kind == "document" else {})}
+ if extension not in allowed:
+ fail("文件格式不支持")
+ if body.kind == "qr" and user.role != "admin":
+ fail("只有管理员可上传客服二维码", 403)
+ limit = settings.max_video_bytes if body.kind == "video" else settings.max_document_bytes
+ if body.size_bytes > limit:
+ fail("文件超过允许大小", 413)
+ # 同一用户的开放会话上限限制未完成分片资源占用。
+ from sqlalchemy import func
+ active = (await db.execute(select(func.count()).select_from(Upload).where(Upload.owner_id == user.id, Upload.state == "uploading", Upload.expires_at > now()))).scalar_one()
+ if active >= 10:
+ fail("未完成上传过多,请先完成或取消", 429)
+ key = f"marketplace/originals/u{user.id}/{uuid.uuid4().hex}{extension}"
+ remote_id = await asyncio.to_thread(storage.initiate, key, allowed[extension])
+ asset = Asset(owner_id=user.id, kind=body.kind, filename=filename, content_type=allowed[extension], size_bytes=body.size_bytes, object_key=key)
+ db.add(asset)
+ await db.flush()
+ upload = Upload(asset_id=asset.id, owner_id=user.id, remote_id=remote_id, part_size=settings.part_size, expires_at=now() + timedelta(hours=24))
+ db.add(upload)
+ try:
+ await db.commit()
+ except Exception:
+ await asyncio.to_thread(storage.abort, key, remote_id)
+ raise
+ return {**data(upload, "id", "asset_id", "state", "part_size", "expires_at"), "uploaded_parts": []}
+
+
[email protected]("/uploads/{upload_id}", response_model=dict)
+async def upload_status(upload_id: int, db: DB, user: Actor):
+ """客户端恢复相同文件时查询已完成分片,不返回 OSS 凭证。"""
+ item = await owned(db, Upload, upload_id, user)
+ return {**data(item, "id", "asset_id", "state", "part_size", "expires_at"), "uploaded_parts": sorted(int(n) for n in item.parts)}
+
+
[email protected]("/uploads/{upload_id}/parts/{number}", response_model=dict, dependencies=[Depends(storage_ready)])
+async def put_part(upload_id: int, number: int, request: Request, db: DB, user: Actor):
+ """流式读取且最多缓存一个分片;持锁避免 JSON 分片记录丢失。"""
+ item = await owned(db, Upload, upload_id, user)
+ asset = await db.get(Asset, item.asset_id)
+ if item.state != "uploading" or item.expires_at <= now():
+ fail("上传已结束或过期", 409)
+ count = math.ceil(asset.size_bytes / item.part_size)
+ if number < 1 or number > count:
+ fail("分片编号无效")
+ expected = min(item.part_size, asset.size_bytes - (number - 1) * item.part_size)
+ buffer = bytearray()
+ async for chunk in request.stream():
+ if len(buffer) + len(chunk) > expected:
+ fail("分片超过预期大小", 413)
+ buffer.extend(chunk)
+ if len(buffer) != expected:
+ fail("分片字节数不匹配")
+ import hashlib
+ digest = hashlib.sha256(buffer).hexdigest()
+ previous = item.parts.get(str(number))
+ if previous and previous.get("sha256") == digest:
+ return {"ok": True, "number": number}
+ etag = await asyncio.to_thread(storage.part, asset.object_key, item.remote_id, number, bytes(buffer))
+ item.parts = {**item.parts, str(number): {"etag": etag, "sha256": digest}}
+ await db.commit()
+ return {"ok": True, "number": number}
+
+
[email protected]("/uploads/{upload_id}/complete", response_model=dict, dependencies=[Depends(storage_ready)])
+async def finish_upload(upload_id: int, db: DB, user: Actor):
+ """OSS 完成和真实大小校验后创建唯一持久化媒体任务。"""
+ item = await owned(db, Upload, upload_id, user)
+ if item.state == "completed":
+ return {"asset_id": item.asset_id, "state": item.state}
+ asset = await db.get(Asset, item.asset_id)
+ if item.state != "uploading" or item.expires_at <= now():
+ fail("上传已结束或过期", 409)
+ count = math.ceil(asset.size_bytes / item.part_size)
+ if set(item.parts) != {str(i) for i in range(1, count + 1)}:
+ fail("分片不完整")
+ await asyncio.to_thread(storage.complete, asset.object_key, item.remote_id, item.parts)
+ if await asyncio.to_thread(storage.head, asset.object_key) != asset.size_bytes:
+ fail("OSS 文件大小校验失败")
+ # 上传本身完成即就绪;只有招募投稿会在提交时创建媒体审片任务。
+ item.state, asset.status = "completed", "ready"
+ event(db, user.id, "asset", asset.id, "upload_completed")
+ await db.commit()
+ return {"asset_id": asset.id, "state": "completed"}
+
+
[email protected]("/uploads/{upload_id}", response_model=dict, dependencies=[Depends(storage_ready)])
+async def cancel_upload(upload_id: int, db: DB, user: Actor):
+ """取消只中止未完成 multipart,不删除已提交的证据或媒体。"""
+ item = await owned(db, Upload, upload_id, user)
+ if item.state == "completed":
+ fail("上传已完成,不能取消")
+ asset = await db.get(Asset, item.asset_id)
+ await asyncio.to_thread(storage.abort, asset.object_key, item.remote_id)
+ item.state, asset.status = "cancelled", "cancelled"
+ await db.commit()
+ return {"ok": True}
+
+
[email protected]("/assets/{asset_id}", response_model=dict)
+async def asset_status(asset_id: int, db: DB, user: Actor):
+ """文件检测未成功前不允许用于业务,失败不伪装上传完成。"""
+ asset = await owned(db, Asset, asset_id, user, admin=True)
+ return data(asset, "id", "kind", "filename", "status", "duration_seconds", "fingerprint", "error", "created_at")
+
+
[email protected]("/assets/{asset_id}/retry", response_model=dict, dependencies=[Depends(storage_ready)])
+async def retry_asset(asset_id: int, db: DB, user: Actor):
+ """显式重试失败任务,不重复创建媒体记录。"""
+ asset = await owned(db, Asset, asset_id, user, admin=True)
+ job = (await db.execute(select(MediaJob).where(MediaJob.asset_id == asset_id).with_for_update())).scalar_one_or_none()
+ if not job or job.status != "failed":
+ fail("该文件没有可重试的失败任务")
+ job.status, job.attempts, job.error = "pending", 0, ""
+ asset.status, asset.error = "processing", ""
+ await db.commit()
+ return {"ok": True}
diff --git a/backend/app/marketplace/worker.py b/backend/app/marketplace/worker.py
new file mode 100644
index 0000000..2ab2520
--- /dev/null
+++ b/backend/app/marketplace/worker.py
@@ -0,0 +1,416 @@
+"""独立媒体进程:python -m app.marketplace.worker;不修改原任务运行时。"""
+import asyncio
+from datetime import timedelta
+import hashlib
+import json
+import logging
+from pathlib import Path
+import shutil
+import subprocess
+import threading
+import tempfile
+import time
+import uuid
+
+from sqlalchemy import and_, or_, select, update
+
+from app.config import get_settings
+from app.database import AsyncSessionLocal, engine
+from . import storage
+from .config import get_marketplace_settings
+from .models import Asset, MarketBase, MediaJob, PlaybackJob, Publication, Recruit, Series, SeriesEpisode, Upload, Work
+from .service import now, notify
+
+logger = logging.getLogger("marketplace.worker")
+
+
+def cache_root() -> Path:
+ """专用非公开缓存根;不使用上游 static 或生成目录。"""
+ root = Path(tempfile.gettempdir()).resolve() / "printfilm-marketplace-cache"
+ root.mkdir(parents=True, exist_ok=True)
+ return root
+
+
+def clean_stale_cache() -> None:
+ """只删除本模块24小时前的任务缓存;校验绝对路径并拒绝符号链接。"""
+ root = cache_root().resolve()
+ for candidate in root.iterdir():
+ if candidate.is_symlink() or not candidate.name.startswith("job-"):
+ continue
+ resolved = candidate.resolve()
+ if resolved.parent != root or not resolved.is_dir():
+ continue
+ if time.time() - resolved.stat().st_mtime > 86400:
+ shutil.rmtree(resolved)
+
+
+def resolve_tool(executable: str) -> str:
+ """后台默认命令不在 PATH 时,使用本机环境中已配置的实际路径。"""
+ if executable in ("ffmpeg", "ffprobe") and not shutil.which(executable):
+ from app.config import Settings
+ configured = getattr(Settings(), executable + "_path")
+ if configured != executable and (Path(configured).is_file() or shutil.which(configured)):
+ return configured
+ raise ValueError(f"未找到 {executable},请在后台系统设置中配置有效程序路径")
+ return executable
+
+
+async def threaded_command(args, timeout):
+ """Windows Selector 事件循环不支持异步子进程,在线程中执行并支持取消。"""
+ cancelled = threading.Event()
+ def run():
+ process = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
+ deadline = time.monotonic() + timeout
+ try:
+ while True:
+ if cancelled.is_set():
+ raise RuntimeError("媒体命令已取消")
+ if time.monotonic() >= deadline:
+ raise TimeoutError("媒体处理超时")
+ try:
+ output, error = process.communicate(timeout=0.2)
+ break
+ except subprocess.TimeoutExpired:
+ continue
+ if process.returncode:
+ logger.warning("media command failed: %s", error[-1500:].decode("utf-8", errors="replace"))
+ raise ValueError("媒体文件无法解析或转码失败")
+ return output
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.communicate()
+ task = asyncio.create_task(asyncio.to_thread(run))
+ try:
+ return await asyncio.shield(task)
+ except asyncio.CancelledError:
+ cancelled.set()
+ await asyncio.gather(task, return_exceptions=True)
+ raise
+
+
+async def command(*args: str, timeout: float = 3600) -> bytes:
+ """有界子进程,超时或停机时回收 FFmpeg,避免孤儿进程。"""
+ args = (resolve_tool(args[0]), *args[1:])
+ try:
+ process = await asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
+ except NotImplementedError:
+ return await threaded_command(args, timeout)
+ try:
+ output, error = await asyncio.wait_for(process.communicate(), timeout)
+ if process.returncode:
+ logger.warning("media command failed: %s", error[-1500:].decode("utf-8", errors="replace"))
+ raise ValueError("媒体文件无法解析或转码失败")
+ return output
+ finally:
+ if process.returncode is None:
+ process.kill()
+ await process.wait()
+
+
+def fingerprint(path: Path) -> str:
+ """流式计算指纹,不把完整原片读入内存。"""
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+async def process_asset(asset: dict) -> dict:
+ """临时文件仅供检测和转码,所有结果成功上传 OSS 后返回 ready 数据。"""
+ settings, upstream = get_marketplace_settings(), get_settings()
+ with tempfile.TemporaryDirectory(prefix="job-", dir=cache_root()) as directory:
+ root = Path(directory)
+ source = root / ("source" + Path(asset["filename"]).suffix.lower())
+ await asyncio.to_thread(storage.download, asset["object_key"], source)
+ if source.stat().st_size != asset["size_bytes"]:
+ raise ValueError("文件大小与上传记录不一致")
+ result = {"fingerprint": await asyncio.to_thread(fingerprint, source)}
+ if asset["content_type"] == "application/pdf":
+ with source.open("rb") as handle:
+ if handle.read(5) != b"%PDF-":
+ raise ValueError("文件内容不是 PDF")
+ return result
+ # MP4 is the primary upload format. Keep probing independent from
+ # upload filename and accept the three supported video containers.
+ formats = "mov,mp4,matroska,webm" if asset["kind"] == "video" else "png_pipe,jpeg_pipe,webp_pipe"
+ probe = json.loads(await command(upstream.ffprobe_path, "-v", "error", "-protocol_whitelist", "file,pipe", "-format_whitelist", formats, "-show_format", "-show_streams", "-of", "json", str(source), timeout=60))
+ videos = [stream for stream in probe.get("streams", []) if stream.get("codec_type") == "video"]
+ if not videos:
+ raise ValueError("文件不包含有效画面")
+ width, height = int(videos[0].get("width", 0)), int(videos[0].get("height", 0))
+ if width < 2 or height < 2 or width * height > 50_000_000:
+ raise ValueError("画面尺寸不支持")
+ if asset["kind"] != "video":
+ if videos[0].get("codec_name") not in ("png", "mjpeg", "webp"):
+ raise ValueError("图片内容与允许格式不符")
+ # 重新编码图片去除附加内容,签名时只返回处理后的对象。
+ image = root / "image.png"
+ await command(upstream.ffmpeg_path, "-y", "-v", "error", "-protocol_whitelist", "file,pipe", "-format_whitelist", formats, "-i", str(source), "-frames:v", "1", str(image), timeout=60)
+ key = f"marketplace/processed/{asset['id']}/image.png"
+ await asyncio.to_thread(storage.upload, key, image, "image/png")
+ return {**result, "cover_key": key}
+ format_name = probe.get("format", {}).get("format_name", "")
+ if not any(name in format_name.split(",") for name in ("mov", "mp4", "matroska", "webm")):
+ raise ValueError("只支持 MP4、MOV、WebM 视频")
+ duration = float(probe.get("format", {}).get("duration", 0))
+ if not 0 < duration <= settings.max_duration_seconds:
+ raise ValueError("视频时长无效或超过30分钟限制")
+ # Upload processing only validates the source and records metadata.
+ # Free works play the original object, while paid works create their
+ # 15-second/30%-limited watermark in the submission path and platform
+ # HLS is packaged only after approval. Generating previews for every
+ # upload here made free content appear perpetually "processing" and
+ # needlessly changed video quality.
+ return {**result, "duration_seconds": duration}
+
+
+async def heartbeat(job_id: int, token: str) -> None:
+ """租约心跳使多进程不会同时提交一个任务的结果。"""
+ while True:
+ await asyncio.sleep(20)
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(update(MediaJob).where(MediaJob.id == job_id, MediaJob.lease_token == token, MediaJob.status == "running").values(lease_until=now() + timedelta(seconds=90)))
+ await db.commit()
+ if not result.rowcount:
+ raise RuntimeError("媒体任务租约已丢失")
+
+
+async def claim() -> tuple[int, str, dict] | None:
+ """SKIP LOCKED 领取一个任务,恢复进程中断遗留任务。"""
+ async with AsyncSessionLocal() as db:
+ query = select(MediaJob).where(or_(MediaJob.status == "pending", and_(MediaJob.status == "running", MediaJob.lease_until < now()))).order_by(MediaJob.id).with_for_update(skip_locked=True).limit(1)
+ item = (await db.execute(query)).scalar_one_or_none()
+ if not item:
+ return None
+ asset = await db.get(Asset, item.asset_id)
+ if item.attempts >= get_marketplace_settings().worker_max_attempts:
+ item.status, asset.status = "failed", "failed"
+ asset.error = "处理重试次数已用完,请检查文件后重试"
+ notify(db, asset.owner_id, f"文件《{asset.filename}》处理失败,请查看我的作品")
+ await db.commit()
+ return None
+ item.attempts += 1
+ item.status, item.lease_token, item.lease_until = "running", uuid.uuid4().hex, now() + timedelta(seconds=90)
+ snapshot = {key: getattr(asset, key) for key in ("id", "filename", "object_key", "kind", "size_bytes", "content_type")}
+ await db.commit()
+ return item.id, item.lease_token, snapshot
+
+
+async def run_once() -> bool:
+ """执行单任务,结果写入时再次比较租约令牌。"""
+ claimed = await claim()
+ if not claimed:
+ return False
+ job_id, token, asset = claimed
+ pulse = asyncio.create_task(heartbeat(job_id, token))
+ processing = asyncio.create_task(process_asset(asset))
+ result, error = None, ""
+ try:
+ done, _ = await asyncio.wait((pulse, processing), return_when=asyncio.FIRST_COMPLETED)
+ if pulse in done:
+ await pulse
+ raise RuntimeError("媒体心跳意外停止")
+ result = await processing
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.exception("marketplace media job %s failed", job_id)
+ error = "媒体处理失败,请检查文件、字体和文件服务配置后重试"
+ finally:
+ pulse.cancel()
+ processing.cancel()
+ await asyncio.gather(pulse, processing, return_exceptions=True)
+ async with AsyncSessionLocal() as db:
+ job = (await db.execute(select(MediaJob).where(MediaJob.id == job_id, MediaJob.lease_token == token).with_for_update())).scalar_one_or_none()
+ if not job:
+ return True
+ record = await db.get(Asset, asset["id"])
+ if result is not None:
+ for key, value in result.items():
+ setattr(record, key, value)
+ job.status, record.status, record.error = "done", "ready", ""
+ notify(db, record.owner_id, f"文件《{record.filename}》已处理完成")
+ else:
+ terminal = job.attempts >= get_marketplace_settings().worker_max_attempts
+ job.status, record.status = ("failed", "failed") if terminal else ("pending", "processing")
+ job.error, record.error = error, error
+ job.lease_until, job.lease_token = None, None
+ await db.commit()
+ return True
+
+
+async def maintenance() -> None:
+ """清理过期 multipart,并标记到期需求;不删除证据或已提交素材。"""
+ await asyncio.to_thread(clean_stale_cache)
+ async with AsyncSessionLocal() as db:
+ uploads = (await db.execute(select(Upload).where(Upload.state == "uploading", Upload.expires_at < now()).with_for_update(skip_locked=True).limit(10))).scalars().all()
+ for item in uploads:
+ asset = await db.get(Asset, item.asset_id)
+ await asyncio.to_thread(storage.abort, asset.object_key, item.remote_id)
+ item.state, asset.status = "expired", "expired"
+ await db.execute(update(Recruit).where(Recruit.state == "open", Recruit.deadline_at <= now()).values(state="expired"))
+ await db.commit()
+
+
+async def package_publication_once() -> bool:
+ """为已审核的平台投放版本生成同源分辨率 HLS 播放清单。"""
+ async with AsyncSessionLocal() as db:
+ # PlaybackJob owns the lease so a crashed Worker can resume packaging;
+ # Publication retains only the immutable playback result/status. Join
+ # against approved publications to avoid repeatedly claiming jobs for a
+ # draft that is still waiting for admin review.
+ job = (await db.execute(select(PlaybackJob).join(
+ Publication, Publication.id == PlaybackJob.publication_id
+ ).where(
+ PlaybackJob.status.in_(("pending", "running")),
+ Publication.sale_type == "platform_unlock",
+ Publication.audit_status == "approved",
+ Publication.playback_status.in_(("pending", "running")),
+ Publication.playback_manifest_key.is_(None),
+ ).order_by(PlaybackJob.id).with_for_update(skip_locked=True).limit(1))).scalar_one_or_none()
+ if not job:
+ # Backfill a job for platform publications created before the durable
+ # job table was introduced. This remains idempotent under the row
+ # lock and allows existing approved content to recover automatically.
+ publication = (await db.execute(select(Publication).where(
+ Publication.sale_type == "platform_unlock",
+ Publication.audit_status == "approved",
+ Publication.playback_status.in_(("pending", "running")),
+ Publication.playback_manifest_key.is_(None),
+ ~select(PlaybackJob.id).where(PlaybackJob.publication_id == Publication.id).exists(),
+ ).order_by(Publication.id).with_for_update(skip_locked=True).limit(1))).scalar_one_or_none()
+ if not publication:
+ return False
+ job = PlaybackJob(publication_id=publication.id, status="pending")
+ db.add(job)
+ await db.flush()
+ publication = await db.get(Publication, job.publication_id, with_for_update=True)
+ if not publication:
+ job.status, job.error = "failed", "发布版本不存在"
+ await db.commit()
+ return True
+ asset = await db.get(Asset, publication.asset_id)
+ if not asset or asset.status != "ready":
+ job.status, job.error = "failed", "媒体尚未就绪"
+ publication.playback_status, publication.playback_error = "failed", "媒体尚未就绪"
+ await db.commit()
+ return True
+ token = uuid.uuid4().hex
+ job.status, job.attempts = "running", job.attempts + 1
+ job.lease_token, job.lease_until = token, now() + timedelta(seconds=90)
+ publication.playback_status, publication.playback_attempts = "running", publication.playback_attempts + 1
+ publication_id, attempts = publication.id, job.attempts
+ snapshot = {"object_key": asset.object_key, "filename": asset.filename, "size_bytes": asset.size_bytes}
+ await db.commit()
+
+ result_key, error = None, ""
+ try:
+ settings = get_settings()
+ with tempfile.TemporaryDirectory(prefix="job-", dir=cache_root()) as directory:
+ root = Path(directory)
+ source = root / ("source" + Path(snapshot["filename"]).suffix.lower())
+ await asyncio.to_thread(storage.download, snapshot["object_key"], source)
+ if source.stat().st_size != snapshot["size_bytes"]:
+ raise ValueError("原片大小不一致")
+ hls_dir = root / "hls"
+ hls_dir.mkdir()
+ segment_pattern = str(hls_dir / "segment-%05d.ts")
+ playlist = hls_dir / "index.m3u8"
+ try:
+ await command(settings.ffmpeg_path, "-y", "-v", "error", "-i", str(source), "-map", "0:v:0", "-map", "0:a:0?", "-c", "copy", "-f", "hls", "-hls_time", "6", "-hls_playlist_type", "vod", "-hls_segment_filename", segment_pattern, str(playlist), timeout=1800)
+ except Exception:
+ # 只在封装不兼容时重编码,保留原分辨率,不强制降画质或尺寸。
+ await command(settings.ffmpeg_path, "-y", "-v", "error", "-i", str(source), "-map", "0:v:0", "-map", "0:a:0?", "-c:v", "libx264", "-crf", "18", "-preset", "fast", "-c:a", "aac", "-b:a", "192k", "-f", "hls", "-hls_time", "6", "-hls_playlist_type", "vod", "-hls_segment_filename", segment_pattern, str(playlist), timeout=3600)
+ prefix = f"marketplace/hls/{publication_id}/"
+ for file in hls_dir.iterdir():
+ content_type = "application/vnd.apple.mpegurl" if file.suffix == ".m3u8" else "video/mp2t"
+ await asyncio.to_thread(storage.upload, prefix + file.name, file, content_type)
+ result_key = prefix + playlist.name
+ except Exception as exc:
+ logger.exception("publication playback packaging failed id=%s", publication_id)
+ error = "播放版本生成失败,请稍后重试"
+
+ async with AsyncSessionLocal() as db:
+ job = (await db.execute(select(PlaybackJob).where(
+ PlaybackJob.publication_id == publication_id,
+ PlaybackJob.lease_token == token,
+ ).with_for_update())).scalar_one_or_none()
+ publication = await db.get(Publication, publication_id, with_for_update=True)
+ if job and publication:
+ if result_key:
+ publication.playback_manifest_key, publication.playback_status, publication.playback_error = result_key, "done", ""
+ job.status, job.error = "done", ""
+ if publication.content_type == "work":
+ parent = await db.get(Work, publication.content_id)
+ else:
+ episode = await db.get(SeriesEpisode, publication.content_id)
+ parent = await db.get(Series, episode.series_id) if episode else None
+ publication.listed = bool(parent and parent.listed and parent.audit_status == "approved" and not parent.blocked)
+ else:
+ terminal = attempts >= get_marketplace_settings().worker_max_attempts
+ job.status, job.error = ("failed" if terminal else "pending"), error
+ publication.playback_status, publication.playback_error = ("failed" if terminal else "pending"), error
+ job.lease_until, job.lease_token = None, None
+ await db.commit()
+ return True
+
+
+async def refresh_storage_settings() -> None:
+ """只读后台配置;不初始化、修复或回写原模型路由。"""
+ from app.config import reload_settings
+ from app.models_settings import AppSettings
+ from app.services.model_settings import _decrypt_flat_config, _refresh_overlay
+ async with AsyncSessionLocal() as db:
+ row = await db.get(AppSettings, "default")
+ _refresh_overlay({"flat": _decrypt_flat_config(row.config_json if row else {})})
+ reload_settings()
+
+
+async def run_loop(*, standalone: bool = False) -> None:
+ """后端内嵌与独立命令共用循环;不释放共享数据库连接池。"""
+ from sqlalchemy import text
+ while True:
+ try:
+ if standalone:
+ await refresh_storage_settings()
+ if get_marketplace_settings().enabled and storage.configured():
+ # 所有后端进程/手动命令共享一把事务锁,市场媒体总并发保持为1。
+ async with engine.begin() as connection:
+ acquired = await connection.scalar(text("SELECT pg_try_advisory_xact_lock(18427, 73102)"))
+ if acquired:
+ await asyncio.to_thread(storage.bucket)
+ await maintenance()
+ from .preview_worker import release_finished_series_once, run_episode_preview_once, run_preview_once
+ await run_episode_preview_once()
+ await run_preview_once()
+ await release_finished_series_once()
+ from .handoff import run_handoff_once
+ await run_handoff_once()
+ await run_once()
+ await package_publication_once()
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.exception("市场 Worker 本轮失败,将延迟重试")
+ await asyncio.sleep(max(1, get_marketplace_settings().worker_poll_seconds))
+
+
+async def main() -> None:
+ """保留手动命令兼容;日常开发由后端生命周期自动托管。"""
+ if not get_marketplace_settings().enabled:
+ logger.info("下游模块未启用,Worker 不启动")
+ return
+ async with engine.begin() as conn:
+ await conn.run_sync(MarketBase.metadata.create_all)
+ try:
+ await run_loop(standalone=True)
+ finally:
+ await engine.dispose()
+
+
+if __name__ == "__main__":
+ logging.basicConfig(level=logging.INFO)
+ asyncio.run(main())
diff --git a/backend/app/marketplace/workspace.py b/backend/app/marketplace/workspace.py
new file mode 100644
index 0000000..bb22728
--- /dev/null
+++ b/backend/app/marketplace/workspace.py
@@ -0,0 +1,142 @@
+"""个人管理、站内通知、咨询与举报。"""
+from fastapi import APIRouter, Query
+from sqlalchemy import func, literal, select, union_all
+
+from .dependencies import Actor, DB
+from .models import Asset, Notification, Recruit, RegistrationCase, Report, Rights, Series, SeriesEpisode, Submission, Support, Work
+from .schemas import ReportInput, Target
+from .service import asset_owned, data, event, fail, get_target, is_public_work, notify, owned, page, recruit_data, recruit_open, rights_for, rights_valid, submission_data, submission_rights_match, work_data
+
+router = APIRouter()
+
+
+async def owner_works(db, user, page_number: int, page_size: int) -> dict:
+ """我的作品同时包含单视频和短剧,按创建时间分页。"""
+ work_part = select(Work.id.label("item_id"), literal("work").label("kind"), Work.created_at.label("sort_at"), Work.id.label("tie")).where(Work.owner_id == user.id)
+ series_part = select(Series.id.label("item_id"), literal("series").label("kind"), Series.created_at.label("sort_at"), Series.id.label("tie")).where(Series.owner_id == user.id)
+ combined = union_all(work_part, series_part).subquery()
+ total = (await db.execute(select(func.count()).select_from(combined))).scalar_one()
+ rows = (await db.execute(select(combined).order_by(combined.c.sort_at.desc(), combined.c.tie.desc()).offset((page_number - 1) * page_size).limit(page_size))).all()
+ items = []
+ for row in rows:
+ if row.kind == "work":
+ payload = await work_data(db, await db.get(Work, row.item_id), True)
+ payload["kind"] = "work"
+ else:
+ from .series import _series_data
+ series = await db.get(Series, row.item_id)
+ detail = await _series_data(db, series, private=True)
+ payload = {"kind": "series", "id": series.id, "title": series.title, "category": series.category,
+ "sale_type": series.sale_type, "price_fen": series.copyright_price_fen,
+ "episode_count": detail["episode_count"], "cover_asset_id": series.cover_asset_id,
+ "audit_status": series.audit_status, "listed": series.listed, "blocked": series.blocked,
+ "reason": series.reason, "created_at": series.created_at}
+ items.append(payload)
+ return {"items": items, "meta": {"page": page_number, "page_size": page_size, "total": total}}
+
+
[email protected]("/mine/{kind}", response_model=dict)
+async def mine(kind: str, db: DB, user: Actor, page_number: int = Query(1, alias="page", ge=1), page_size: int = Query(20, ge=1, le=100)):
+ """个人数据分页,不能通过请求 owner_id 读取别人数据。"""
+ if kind == "works":
+ return await owner_works(db, user, page_number, page_size)
+ model = {"series": Series, "recruits": Recruit, "submissions": Submission, "cases": RegistrationCase,
+ "assets": Asset, "rights": Rights, "notifications": Notification}.get(kind)
+ if not model:
+ fail("列表类型无效", 404)
+ rows, meta = await page(db, select(model).where(model.owner_id == user.id).order_by(model.id.desc()), page_number, page_size)
+ items = []
+ for item in rows:
+ if isinstance(item, Work):
+ result = await work_data(db, item, True)
+ elif isinstance(item, Series):
+ from .series import _series_data
+ result = await _series_data(db, item, private=True)
+ elif isinstance(item, Recruit):
+ result = await recruit_data(db, item, True)
+ elif isinstance(item, Submission):
+ result = await submission_data(db, item, user)
+ elif isinstance(item, Asset):
+ result = data(item, "id", "kind", "filename", "status", "fingerprint", "duration_seconds", "error", "created_at")
+ else:
+ result = data(item, *[column.name for column in model.__table__.columns])
+ items.append(result)
+ return {"items": items, "meta": meta}
+
+
[email protected]("/notifications/{notification_id}/read", response_model=dict)
+async def read_notification(notification_id: int, db: DB, user: Actor):
+ """标记当前账号的站内通知。"""
+ item = await owned(db, Notification, notification_id, user)
+ item.read = True
+ await db.commit()
+ return {"ok": True}
+
+
[email protected]("/support", response_model=dict)
+async def support(db: DB):
+ """公开客服说明;二维码使用独立短时签名接口。"""
+ item = await db.get(Support, 1)
+ if not item or not item.enabled or not item.qr_asset_id:
+ return {"available": False, "message": "客服暂不可用"}
+ return {"available": True, **data(item, "name", "wechat", "hours")}
+
+
[email protected]("/consultations", response_model=dict)
+async def consult(body: Target, db: DB, user: Actor):
+ """记录咨询而非成交;购买类咨询必须满足完整权属核验。"""
+ item = await get_target(db, body.target_type, body.target_id, user)
+ price, title = None, ""
+ if isinstance(item, Work):
+ if not await is_public_work(db, item.id):
+ fail("作品尚未满足购买咨询条件")
+ price, title = item.price_fen, item.title
+ elif isinstance(item, Submission):
+ post = await db.get(Recruit, item.recruit_id)
+ rights = await rights_for(db, item.asset_id)
+ if user.id != post.owner_id:
+ fail("仅需求方可发起投稿购买咨询", 403)
+ if item.withdrawn or item.blocked or post.blocked or not rights_valid(rights, full=True) or not submission_rights_match(item, rights):
+ fail("投稿尚未完成完整权属核验或已撤回、封禁")
+ price, title = item.quote_fen, f"《{post.title}》投稿 #{item.id}"
+ elif isinstance(item, Recruit):
+ if not recruit_open(item) and user.id != item.owner_id:
+ fail("需求已结束,不能发起新咨询")
+ price, title = item.budget_fen, item.title
+ elif isinstance(item, SeriesEpisode):
+ series = await db.get(Series, item.series_id)
+ if (not series or series.sale_type != "copyright_contact" or not series.listed
+ or series.audit_status != "approved" or not item.listed
+ or item.audit_status != "approved" or series.blocked or item.blocked):
+ fail("该分集尚未开放版权咨询", 409)
+ price = item.copyright_price_fen or series.copyright_price_fen
+ title = f"《{series.title}》第{item.episode_no}集 · {item.title}"
+ else:
+ title = f"版权登记案件 #{item.id}"
+ settings = await db.get(Support, 1)
+ if not settings or not settings.enabled or not settings.qr_asset_id:
+ fail("客服暂不可用", 503)
+ event(db, user.id, body.target_type, item.id, "consultation")
+ await db.commit()
+ notice = ("接单请先联系客服,并提供招募编号。由客服协助确认需求、预算、授权和交付要求,具体合作在线下协商确认。咨询不代表已接单或成交。"
+ if isinstance(item, Recruit) else "请联系客服确认价格、授权范围和交付方式。咨询不代表成交或授权。")
+ return {"reference": f"{body.target_type.upper()}-{item.id}", "title": title, "price_fen": price,
+ "name": settings.name, "wechat": settings.wechat, "hours": settings.hours,
+ "notice": notice}
+
+
[email protected]("/reports", response_model=dict)
+async def report(body: ReportInput, db: DB, user: Actor):
+ """举报证据私有存储,不把投诉人联系方式公开给被举报者。"""
+ await get_target(db, body.target_type, body.target_id, user)
+ if body.target_type == "case":
+ fail("登记案件请联系客服补充说明")
+ for asset_id in body.evidence_ids:
+ await asset_owned(db, asset_id, user, ("document", "image"))
+ item = Report(owner_id=user.id, **body.model_dump())
+ db.add(item)
+ await db.flush()
+ event(db, user.id, "report", item.id, "created")
+ notify(db, user.id, f"举报 #{item.id} 已收到,平台将核查材料")
+ await db.commit()
+ return {"id": item.id}
diff --git a/backend/requirements-marketplace.txt b/backend/requirements-marketplace.txt
new file mode 100644
index 0000000..e190cfb
--- /dev/null
+++ b/backend/requirements-marketplace.txt
@@ -0,0 +1,3 @@
+# 下游授权函图像合成依赖;原项目依赖文件保持独立。
+-r requirements.txt
+Pillow==11.3.0
diff --git a/backend/tests/test_marketplace.py b/backend/tests/test_marketplace.py
new file mode 100644
index 0000000..06e1933
--- /dev/null
+++ b/backend/tests/test_marketplace.py
@@ -0,0 +1,1081 @@
+"""下游集成验收:独立测试库/事务回滚,不触碰业务库或真实 OSS。"""
+from datetime import timedelta
+from types import SimpleNamespace
+import uuid
+
+from fastapi import FastAPI, HTTPException
+import httpx
+import pytest
+import pytest_asyncio
+from sqlalchemy import select
+
+from app.database import Base, get_db
+from app.deps import get_current_user
+from app.models import User
+from app.marketplace import storage
+from app.marketplace.bootstrap import install
+from app.marketplace.config import get_marketplace_settings
+from app.marketplace.dependencies import optional_user
+from app.marketplace.models import Asset, MarketBase, MediaJob, Recruit, Rights, Submission, Support, Work
+from app.marketplace.service import now
+from app.marketplace.models import WorkPreview
+
+
+async def ready_work_preview(ctx, work_id, asset_id, version=1):
+ """已生成试看的测试前置条件,不复用旧资产预览。"""
+ ctx.db.add(WorkPreview(work_id=work_id, asset_id=asset_id, version=version,
+ status="done", object_key="marketplace/work-previews-hq/test-preview.mp4"))
+ await ctx.db.flush()
+
+
+def test_watermark_text_uses_author_name_and_strips_ffmpeg_chars():
+ from app.marketplace.preview_worker import watermark_text
+ assert watermark_text("张三") == "PRINTFILM 张三 侵权必究"
+ assert watermark_text("a:b'c") == "PRINTFILM abc 侵权必究"
+ assert watermark_text("") == "PRINTFILM 创作者 侵权必究"
+
+
[email protected]('duration, expected', [(20, 6), (120, 15), (50, 15)])
+def test_work_preview_duration_policy(duration, expected):
+ from app.marketplace.previews import preview_duration
+ assert preview_duration(duration) == expected
+
+
[email protected]('scope', ['', ' '])
+async def test_submit_missing_license_scope_has_actionable_error(ctx, scope):
+ video = await asset(ctx)
+ await rights(ctx, video, full=True)
+ created = await ctx.client.post('/api/marketplace/works', json={**work_body(video), 'license_scope': scope})
+ assert created.status_code == 200 # Drafts can remain incomplete.
+ response = await ctx.client.post(f"/api/marketplace/works/{created.json()['id']}/submit", json={'version': 1})
+ assert response.status_code == 400
+ assert '拟授权用途及限制' in response.json()['detail']
+ work = await ctx.db.get(Work, created.json()['id'])
+ assert work.audit_status == 'draft' and not work.listed
+
+
+async def test_admin_categories_config_validation_versions_and_historical_works(ctx):
+ public = '/api/marketplace/categories'
+ admin = '/api/admin/marketplace/categories'
+ initial = (await ctx.client.get(public)).json()
+ assert initial['version'] == 0 and '短片' in initial['names']
+ # Existing content is never rewritten when configuration changes.
+ created = (await ctx.client.post('/api/marketplace/works', json=work_body())).json()
+ response = await ctx.client.put(admin, json={'version': 0, 'names': ['广告', '短片']})
+ assert response.status_code == 403
+ ctx.user = ctx.admin
+ for names in ([], ['广告', '广告'], [' '], ['x' * 61]):
+ response = await ctx.client.put(admin, json={'version': 0, 'names': names})
+ assert response.status_code == 422, response.text
+ saved = await ctx.client.put(admin, json={'version': 0, 'names': ['广告', ' 短片 ']})
+ assert saved.status_code == 200, saved.text
+ assert saved.json() == {'version': 1, 'names': ['广告', '短片']}
+ assert (await ctx.client.put(admin, json={'version': 0, 'names': ['科普']})).status_code == 409
+ ctx.user = None
+ assert (await ctx.client.get(public)).json() == saved.json()
+ ctx.user = ctx.owner
+ assert (await ctx.client.post('/api/marketplace/works', json=work_body())).status_code == 400
+ assert (await ctx.client.post('/api/marketplace/works', json={**work_body(), 'category': '广告'})).status_code == 200
+ path = f"/api/marketplace/works/{created['id']}"
+ updated = await ctx.client.put(path, json={**work_body(), 'version': 1})
+ assert updated.status_code == 200 and updated.json()['category'] == '其他'
+
+
+async def test_recruit_public_detail_contact_flags_and_management_privacy(ctx):
+ post = await recruit(ctx)
+ path = f'/api/marketplace/recruits/{post.id}'
+ ctx.user = ctx.buyer
+ owner = (await ctx.client.get(path)).json()
+ assert owner['is_owner'] and owner['is_open'] and not owner['can_submit'] and not owner['can_contact']
+ assert 'version' in owner
+ ctx.user = ctx.owner
+ creator = (await ctx.client.get(path)).json()
+ assert not creator['is_owner'] and creator['is_open'] and not creator['can_submit'] and creator['can_contact']
+ assert 'version' not in creator and 'owner_id' not in creator
+ assert (await ctx.client.get(path + '/submissions')).status_code in (403, 404)
+ ctx.user = None
+ guest = (await ctx.client.get(path)).json()
+ assert guest['is_open'] and not guest['can_submit'] and not guest['is_owner'] and not guest['can_contact']
+ post.state = 'closed'
+ await ctx.db.flush()
+ ctx.user = ctx.buyer
+ closed = (await ctx.client.get(path)).json()
+ assert not closed['is_open'] and not closed['can_submit'] and not closed['can_contact']
+
+
+async def test_paid_preview_submit_dedup_retry_and_free_transition(ctx, monkeypatch):
+ fake_oss(monkeypatch)
+ video = await asset(ctx)
+ await rights(ctx, video, full=True)
+ work = (await ctx.client.post('/api/marketplace/works', json=work_body(video))).json()
+ path = f"/api/marketplace/works/{work['id']}"
+ assert work['preview_status'] == 'missing'
+ assert not list((await ctx.db.execute(select(WorkPreview))).scalars())
+ for _ in range(2):
+ result = await ctx.client.post(path + '/submit', json={'version': 1})
+ assert result.status_code == 200, result.text
+ assert result.json()['audit_status'] == 'processing'
+ jobs = list((await ctx.db.execute(select(WorkPreview))).scalars())
+ assert len(jobs) == 1
+ job = jobs[0]
+ job.status = 'failed'
+ record = await ctx.db.get(Work, work['id'])
+ record.audit_status = 'preview_failed'
+ await ctx.db.flush()
+ assert (await ctx.client.post(path + '/submit', json={'version': 1})).status_code == 200
+ assert job.status == 'pending' and job.attempts == 0
+ job.status, job.object_key = 'done', 'marketplace/work-previews-hq/test-secure.mp4'
+ await ctx.db.flush()
+ 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'
+
+
+async def test_paid_preview_media_never_leaks_original(ctx, monkeypatch):
+ fake_oss(monkeypatch)
+ calls = []
+ monkeypatch.setattr(storage, 'signed', lambda key, mime: calls.append(key) or 'https://test.invalid/media')
+ video = await asset(ctx)
+ await rights(ctx, video, full=True)
+ work = Work(owner_id=ctx.owner.id, **work_body(video), audit_status='approved', listed=True)
+ ctx.db.add(work)
+ await ctx.db.flush()
+ ctx.user = None
+ url = f'/api/marketplace/media/work/{work.id}/preview'
+ assert (await ctx.client.get(url)).status_code == 404
+ assert not calls
+ await ready_work_preview(ctx, work.id, video.id)
+ assert (await ctx.client.get(url)).status_code == 200
+ assert calls == ['marketplace/work-previews-hq/test-preview.mp4']
+ assert (await ctx.client.get(f'/api/marketplace/media/asset/{video.id}/original')).status_code == 404
+ work.price_fen = 0
+ await ctx.db.flush()
+ assert (await ctx.client.get(url)).status_code == 200
+ assert calls[-1] == 'marketplace/work-previews-hq/test-preview.mp4'
+
+
+async def test_free_submit_without_oss_creates_no_preview_and_paid_switch_blocks(ctx):
+ """免费作品也要生成水印,未配置 OSS 时不创建任务、不进入待审核。"""
+ video = await asset(ctx)
+ await rights(ctx, video, full=True)
+ body = {**work_body(video), 'price_fen': 0}
+ created = await ctx.client.post('/api/marketplace/works', json=body)
+ assert created.status_code == 200
+ path = f"/api/marketplace/works/{created.json()['id']}"
+ blocked = await ctx.client.post(path + '/submit', json={'version': 1})
+ assert blocked.status_code == 503
+ assert blocked.json()['detail']['code'] == 'MARKETPLACE_STORAGE_UNAVAILABLE'
+ assert not list((await ctx.db.execute(select(WorkPreview))).scalars())
+ changed = await ctx.client.put(path, json={**body, 'price_fen': 100, '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.status_code == 503
+ assert result.json()['detail']['code'] == 'MARKETPLACE_STORAGE_UNAVAILABLE'
+ assert not list((await ctx.db.execute(select(WorkPreview))).scalars())
+
+
+async def test_preview_replaced_video_does_not_reuse_old_result(ctx, monkeypatch):
+ fake_oss(monkeypatch)
+ video = await asset(ctx)
+ await rights(ctx, video, full=True)
+ created = (await ctx.client.post('/api/marketplace/works', json=work_body(video))).json()
+ await ready_work_preview(ctx, created['id'], video.id)
+ new_video = await asset(ctx)
+ await rights(ctx, new_video, full=True)
+ path = f"/api/marketplace/works/{created['id']}"
+ changed = await ctx.client.put(path, json={**work_body(new_video), 'version': 1})
+ assert changed.json()['preview_status'] == 'missing'
+ submitted = await ctx.client.post(path + '/submit', json={'version': changed.json()['version']})
+ assert submitted.json()['audit_status'] == 'processing'
+ assert len(list((await ctx.db.execute(select(WorkPreview))).scalars())) == 2
+
+
+async def test_preview_worker_terminal_failure_then_user_retry(ctx, monkeypatch):
+ from contextlib import asynccontextmanager
+ from app.marketplace import preview_worker
+ @asynccontextmanager
+ async def session():
+ yield ctx.db
+ async def broken(snapshot):
+ raise ValueError('test transport failure')
+ fake_oss(monkeypatch)
+ video = await asset(ctx)
+ await rights(ctx, video, full=True)
+ created = (await ctx.client.post('/api/marketplace/works', json=work_body(video))).json()
+ path = f"/api/marketplace/works/{created['id']}"
+ await ctx.client.post(path + '/submit', json={'version': 1})
+ monkeypatch.setattr(preview_worker, 'AsyncSessionLocal', session)
+ monkeypatch.setattr(preview_worker, 'render_preview', broken)
+ monkeypatch.setattr(get_marketplace_settings(), 'worker_max_attempts', 1)
+ assert await preview_worker.run_preview_once()
+ work = await ctx.db.get(Work, created['id'])
+ assert work.audit_status == 'preview_failed' and not work.listed
+ assert not await preview_worker.run_preview_once()
+ retried = await ctx.client.post(path + '/submit', json={'version': 1})
+ assert retried.json()['audit_status'] == 'processing'
+
+
[email protected]('stale', [False, True])
+async def test_preview_worker_lease_recovery_and_version(ctx, monkeypatch, stale):
+ 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-worker.mp4'
+ video = await asset(ctx)
+ work = Work(owner_id=ctx.owner.id, **work_body(video), audit_status='processing', version=2 if stale else 1)
+ ctx.db.add(work)
+ await ctx.db.flush()
+ job = WorkPreview(work_id=work.id, asset_id=video.id, version=1, status='running',
+ attempts=1, lease_token='dead', lease_until=now() - timedelta(minutes=1))
+ ctx.db.add(job)
+ await ctx.db.flush()
+ 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 job.attempts == 2
+ assert work.audit_status == ('processing' if stale else 'pending')
+ assert not await preview_worker.run_preview_once()
+
+
[email protected]('seconds, dimensions, fps', [(10, '1920x1080', 24), (60, '320x180', 10)])
+async def test_real_work_preview_limits_and_burned_watermark(monkeypatch, tmp_path, seconds, dimensions, fps):
+ import json
+ import shutil
+ from app.config import get_settings
+ from app.marketplace import worker, preview_worker
+ settings = get_settings()
+ source = tmp_path / 'source.mp4'
+ await worker.command(settings.ffmpeg_path, '-y', '-v', 'error', '-f', 'lavfi', '-i',
+ f'color=c=blue:s={dimensions}:r={fps}', '-f', 'lavfi', '-i', 'sine=frequency=440', '-t', str(seconds),
+ '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', str(source))
+ output = tmp_path / 'result.mp4'
+ keys = []
+ monkeypatch.setattr(storage, 'download', lambda key, dest: shutil.copyfile(source, dest))
+ def upload(key, path, mime):
+ keys.append(key)
+ shutil.copyfile(path, output)
+ monkeypatch.setattr(storage, 'upload', upload)
+ key = await preview_worker.render_preview(dict(work_id=123, owner_id=456, asset_id=789,
+ filename='source.mp4', source_key='test', size_bytes=source.stat().st_size))
+ assert keys == [key] and key.startswith('marketplace/work-previews-hq/123/789/')
+ probe = json.loads(await worker.command(settings.ffprobe_path, '-v', 'error', '-show_format', '-show_streams', '-of', 'json', str(output)))
+ limit = min(15, seconds * .3)
+ assert limit - .3 <= float(probe['format']['duration']) <= limit
+ assert (probe['streams'][0]['width'], probe['streams'][0]['height']) == tuple(map(int, dimensions.split('x')))
+ from fractions import Fraction
+ assert Fraction(probe['streams'][0]['avg_frame_rate']) == fps
+ frame = await worker.command(settings.ffmpeg_path, '-v', 'error', '-i', str(output), '-frames:v', '1', '-f', 'rawvideo', '-pix_fmt', 'rgb24', 'pipe:1')
+ assert sum(1 for r, g in zip(frame[::3], frame[1::3]) if r > 100 and g > 100) > 30
+
+
+@pytest_asyncio.fixture
+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(settings, "enabled", True)
+ monkeypatch.setattr(storage.get_settings(), "oss_enabled", False)
+ users = []
+ for role in ("user", "user", "user", "admin"):
+ user = User(email=f"market-{uuid.uuid4().hex}@test.local", hashed_password="unused", role=role)
+ db_session.add(user)
+ users.append(user)
+ await db_session.flush()
+ state = SimpleNamespace(db=db_session, owner=users[0], buyer=users[1], stranger=users[2], admin=users[3], user=users[0])
+ app = FastAPI()
+ install(app)
+
+ async def session_override():
+ """复用外层回滚事务。"""
+ yield db_session
+
+ async def actor_override():
+ """测试用户切换不创建假业务登录接口。"""
+ if state.user is None:
+ raise HTTPException(401, "未登录")
+ return state.user
+
+ async def visitor_override():
+ """测试公开和私密访问的差异。"""
+ return state.user
+
+ app.dependency_overrides[get_db] = session_override
+ app.dependency_overrides[get_current_user] = actor_override
+ app.dependency_overrides[optional_user] = visitor_override
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
+ state.client = client
+ yield state
+
+
+async def asset(ctx, *, owner=None, kind="video", status="ready"):
+ """仅测试库中构造已处理资产,绝不声称真实 OSS 已联调。"""
+ item = Asset(owner_id=(owner or ctx.owner).id, kind=kind, filename="video.mp4" if kind == "video" else "proof.pdf",
+ content_type="video/mp4" if kind == "video" else "application/pdf", size_bytes=128,
+ object_key=f"test-private/{uuid.uuid4().hex}", status=status, fingerprint="a" * 64,
+ preview_key="test/preview.mp4", review_key="test/review.mp4", cover_key="test/cover.jpg")
+ ctx.db.add(item)
+ await ctx.db.flush()
+ return item
+
+
+async def rights(ctx, media, *, full=False, basic=True):
+ """测试证据与视频同一作者,仅核验模型逻辑。"""
+ certificate = await asset(ctx, kind="document")
+ item = Rights(owner_id=media.owner_id, asset_id=media.id, version=1, certificate_asset_id=certificate.id,
+ evidence_ids=[certificate.id], basic_status="approved" if basic else "pending",
+ full_status="approved" if full else "draft", details={"author": "作者", "holder": "权利人", "relationship": "本人",
+ "acquisition": "original", "source": "original", "scope": "展示及销售", "third_party": "无第三方素材",
+ "institution": "登记机构", "certificate_number": "test-certificate"})
+ ctx.db.add(item)
+ await ctx.db.flush()
+ return item
+
+
+async def recruit(ctx, **changes):
+ """构造未来截止的审核通过需求。"""
+ values = dict(owner_id=ctx.buyer.id, title="测试招募", description="说明", category="其他", budget_fen=10000,
+ wanted_count=2, requirements="10秒横屏视频", license_scope="商业授权意向", deadline_at=now() + timedelta(days=1),
+ state="open", audit_status="approved", version=1)
+ values.update(changes)
+ item = Recruit(**values)
+ ctx.db.add(item)
+ await ctx.db.flush()
+ return item
+
+
+async def historical_submission(ctx, post, video, proof, *, selection="to_review"):
+ """只为旧数据兼容测试构造历史快照,不通过已停用的新投稿接口。"""
+ from app.marketplace.service import rights_identity
+ item = Submission(recruit_id=post.id, owner_id=video.owner_id, asset_id=video.id, quote_fen=1000,
+ selection=selection, snapshot={"fingerprint": video.fingerprint, "filename": video.filename,
+ "rights_version": proof.version, "scope": proof.details.get("scope", ""),
+ "rights_identity": rights_identity(proof), "requirements": post.requirements,
+ "license_scope": post.license_scope, "recruit_version": post.version})
+ ctx.db.add(item)
+ await ctx.db.flush()
+ return item
+
+
+def work_body(media=None):
+ """作品入参不包含原项目 project_id 或远程 URL。"""
+ return {"title": "测试作品", "description": "介绍", "category": "其他", "price_fen": 1000,
+ "asset_id": media.id if media else None, "license_scope": "商业授权意向"}
+
+
+def fake_oss(monkeypatch):
+ """仅测试用替身,不修改任何本地真实配置。"""
+ monkeypatch.setattr(storage, "bucket", lambda: object())
+ monkeypatch.setattr(storage, "signed", lambda key, content_type: "https://private.example.test/signed?expires=300")
+
+
+def test_signed_media_url_preserves_oss_object_headers(monkeypatch):
+ """OSS rejects response-content-type overrides; preserve upload metadata."""
+ calls = []
+ class Client:
+ def sign_url(self, *args, **kwargs):
+ calls.append((args, kwargs))
+ return "https://private.example.test/signed"
+ monkeypatch.setattr(storage, "bucket", lambda: Client())
+ assert storage.signed("marketplace/video.mp4", "video/mp4")
+ args, kwargs = calls[0]
+ assert args[0] == "GET" and 0 < args[2] <= 300
+ assert "response-content-type" not in kwargs.get("params", {})
+
+
+def signing_body():
+ from app.marketplace.authorization import VERSION
+ return {"template_version": VERSION, "signer_name": "测试签署人", "accepted_terms": True,
+ "strokes": [[[20 + i * 12, 60 + (i % 3) * 20] for i in range(25)]]}
+
+
+def source_details(source):
+ return {"source": source, "author": "测试作者", "holder": "测试权利人", "relationship": "本人",
+ "acquisition": "original", "scope": "展示和线下洽谈", "third_party": "无第三方素材",
+ "ai_platform_license": "平台商用许可说明", "ai_generation_record": "对应视频生成记录",
+ "human_contribution": "剪辑和分镜设计", "certificate_number": "copyright-123", "dispute_ack": True}
+
+
+async def test_printfilm_signed_letter_review_and_public_flow(ctx, monkeypatch):
+ """真实渲染签名图,OSS 仅用传输替身;签署不能自动批准作品。"""
+ from PIL import Image
+ from app.marketplace.models import Authorization
+ fake_oss(monkeypatch)
+ uploaded = []
+ def capture(key, path, content_type):
+ with Image.open(path) as image:
+ assert image.format == "PNG" and image.width >= 800
+ assert key.startswith("marketplace/authorizations/") and content_type == "image/png"
+ uploaded.append(key)
+ monkeypatch.setattr(storage, "upload", capture)
+ video = await asset(ctx)
+ path = f"/api/marketplace/assets/{video.id}/rights"
+ payload = {"version": 0, "details": source_details("printfilm")}
+ assert (await ctx.client.put(path, json=payload)).status_code == 400
+ signed = await ctx.client.post("/api/marketplace/authorization", json=signing_body())
+ assert signed.status_code == 200, signed.text
+ authorization_id = signed.json()["id"]
+ assert len(uploaded) == 2
+ assert (await ctx.client.post("/api/marketplace/authorization", json=signing_body())).json()["id"] == authorization_id
+ assert len(uploaded) == 2
+ archive = await ctx.db.get(Authorization, authorization_id)
+ assert archive.signer_name == "测试签署人" and len(archive.body_hash) == 64 and archive.body
+ payload["version"] = 0
+ assert (await ctx.client.put(path, json=payload)).status_code == 200
+ item = (await ctx.client.get(path)).json()
+ assert item["details"]["authorization_id"] == str(authorization_id)
+ assert not item["certificate_asset_id"]
+ assert item["full_status"] == "draft"
+ ctx.user = ctx.owner
+ work = (await ctx.client.post("/api/marketplace/works", json={**work_body(video), "source": "printfilm"})).json()
+ work_path = f"/api/marketplace/works/{work['id']}"
+ await ready_work_preview(ctx, work['id'], video.id)
+ assert (await ctx.client.post(work_path + "/submit", json={"version": 1})).status_code == 200
+ ctx.user = ctx.admin
+ review = f"/api/admin/marketplace/works/{work['id']}/review"
+ assert (await ctx.client.post(review, json={"version": 1, "decision": "approved", "reason": "未确认检查"})).status_code == 400
+ assert (await ctx.client.post(review, json={"version": 1, "decision": "approved", "reason": "内容和版权通过", "checks": ["content", "copyright"]})).status_code == 200
+ ctx.user = ctx.owner
+ assert (await ctx.client.post(work_path + "/listing", json={"version": 1})).status_code == 200
+ ctx.user = None
+ assert (await ctx.client.get("/api/marketplace/works")).json()["meta"]["total"] == 1
+ ctx.user = ctx.stranger
+ assert (await ctx.client.get(f"/api/marketplace/authorizations/{authorization_id}/letter")).status_code == 404
+ ctx.user = ctx.admin
+ assert (await ctx.client.get(f"/api/marketplace/authorizations/{authorization_id}/letter")).status_code == 200
+
+
+async def test_signature_requires_oss_current_terms_and_real_strokes(ctx, monkeypatch):
+ response = await ctx.client.post("/api/marketplace/authorization", json=signing_body())
+ assert response.status_code == 503
+ fake_oss(monkeypatch)
+ for changes in ({"accepted_terms": False}, {"strokes": []}, {"strokes": [[[1, 1], [1, 1]]]}, {"strokes": [[[900, 1], [950, 2]]]}):
+ assert (await ctx.client.post("/api/marketplace/authorization", json={**signing_body(), **changes})).status_code == 422
+ assert (await ctx.client.post("/api/marketplace/authorization", json={**signing_body(), "template_version": "obsolete"})).status_code == 409
+
+
+async def test_external_proof_and_assistance_are_separate(ctx):
+ video = await asset(ctx)
+ start = f"/api/marketplace/assets/{video.id}/assistance"
+ response = await ctx.client.post(start)
+ assert response.status_code == 200, response.text
+ case = response.json()
+ assert case["route"] == "assisted" and case["status"] == "pending_materials"
+ assert (await ctx.client.post(start)).json()["id"] == case["id"]
+ path = f"/api/marketplace/assets/{video.id}/rights"
+ existing = (await ctx.client.get(path)).json()
+ submit = f"/api/marketplace/rights/{existing['id']}/submit?full=true"
+ payload = {"version": 1, "details": source_details("external")}
+ assert (await ctx.client.put(path, json=payload)).status_code == 200
+ assert (await ctx.client.post(submit, json={"version": 2})).status_code == 400
+ # 他人的材料不能绑定为权属证明。
+ stranger_proof = await asset(ctx, owner=ctx.stranger, kind="document")
+ assert (await ctx.client.put(path, json={**payload, "version": 2, "certificate_asset_id": stranger_proof.id})).status_code == 404
+ proof = await asset(ctx, kind="document")
+ assert (await ctx.client.put(path, json={**payload, "version": 2, "certificate_asset_id": proof.id})).status_code == 200
+ assert (await ctx.client.post(submit, json={"version": 3})).status_code == 200
+ ctx.user = ctx.admin
+ review = f"/api/admin/marketplace/rights/{existing['id']}/review?full=true"
+ checks = ["identity", "ownership", "third_party", "scope", "sample_match", "sales_authority", "ai_evidence", "ownership_proof"]
+ assert (await ctx.client.post(review, json={"version": 3, "decision": "approved", "reason": "外部逐件授权证明核实", "checks": checks})).status_code == 200
+ # 协办案件仍是待材料,与权属审核状态分离。
+ ctx.user = ctx.owner
+ assert (await ctx.client.get(f"/api/marketplace/rights/{existing['id']}/case")).json()["item"]["status"] == "pending_materials"
+
+
+async def test_rights_cannot_forge_authorization_snapshot(ctx):
+ video = await asset(ctx)
+ response = await ctx.client.put(f"/api/marketplace/assets/{video.id}/rights", json={"version": 0, "details": {**source_details("printfilm"), "authorization_id": "123"}})
+ assert response.status_code == 422
+
+
+async def test_asset_preview_is_owner_only_and_waits_for_processing(ctx, monkeypatch):
+ fake_oss(monkeypatch)
+ video = await asset(ctx, status="processing")
+ path = f"/api/marketplace/media/asset/{video.id}/preview"
+ assert (await ctx.client.get(path)).status_code == 409
+ video.status = "ready"
+ await ctx.db.flush()
+ assert (await ctx.client.get(path)).status_code == 200
+ ctx.user = ctx.stranger
+ assert (await ctx.client.get(path)).status_code == 404
+
+
+async def test_owner_can_preview_unlisted_draft_but_public_cannot(ctx, monkeypatch):
+ fake_oss(monkeypatch)
+ video = await asset(ctx)
+ ctx.user = ctx.owner
+ work = (await ctx.client.post("/api/marketplace/works", json=work_body(video))).json()
+ path = f"/api/marketplace/media/work/{work['id']}/preview"
+ assert (await ctx.client.get(path)).status_code == 409
+ assert (await ctx.client.get(f"/api/marketplace/media/asset/{video.id}/original")).status_code == 200
+ ctx.user = ctx.stranger
+ assert (await ctx.client.get(path)).status_code == 404
+ ctx.user = None
+ assert (await ctx.client.get(path)).status_code == 404
+
+
+def test_metadata_does_not_join_original_tables():
+ """独立 metadata 不登记 users、works 或 tasks 等原表。"""
+ assert all(name.startswith("marketplace_") for name in MarketBase.metadata.tables)
+ assert not set(MarketBase.metadata.tables).intersection(Base.metadata.tables)
+
+
+async def test_disabled_only_exposes_capabilities(monkeypatch):
+ """关闭时没有业务路由,不需要 DB 和 Worker。"""
+ monkeypatch.setattr(get_marketplace_settings(), "enabled", False)
+ app = FastAPI()
+ install(app)
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
+ assert (await client.get("/api/marketplace/capabilities")).json()["enabled"] is False
+ assert (await client.get("/api/marketplace/works")).status_code == 404
+
+
+async def test_missing_oss_keeps_text_drafts_but_blocks_upload(ctx):
+ """缺配置准确返回503,不产生本地路径或假成功。"""
+ response = await ctx.client.post("/api/marketplace/works", json=work_body())
+ assert response.status_code == 200, response.text
+ response = await ctx.client.post("/api/marketplace/uploads", json={"filename": "x.mp4", "size_bytes": 100, "kind": "video"})
+ assert response.status_code == 503
+ assert response.json()["detail"]["code"] == "MARKETPLACE_STORAGE_UNAVAILABLE"
+ assert (await ctx.db.execute(select(Asset.id))).scalar_one_or_none() is None
+
+
+async def test_work_full_flow_and_version_checks(ctx):
+ """持证、内容、作者上架缺一不可;旧版本不允许修改。"""
+ video = await asset(ctx)
+ proof = await rights(ctx, video, full=False)
+ response = await ctx.client.post("/api/marketplace/works", json=work_body(video))
+ item = response.json()
+ path = f"/api/marketplace/works/{item['id']}"
+ await ready_work_preview(ctx, item['id'], video.id)
+ assert (await ctx.client.post(path + "/submit", json={"version": 1})).status_code == 200
+ proof.full_status = "approved"
+ await ctx.db.flush()
+ assert (await ctx.client.post(path + "/submit", json={"version": 1})).status_code == 200
+ ctx.user = ctx.admin
+ admin_path = f"/api/admin/marketplace/works/{item['id']}/review"
+ response = await ctx.client.post(admin_path, json={"version": 2, "decision": "approved", "reason": "核实"})
+ assert response.status_code == 409
+ assert (await ctx.client.post(admin_path, json={"version": 1, "decision": "approved", "reason": "内容核实", "checks": ["content", "copyright"]})).status_code == 200
+ ctx.user = None
+ assert (await ctx.client.get("/api/marketplace/works")).json()["meta"]["total"] == 0
+ ctx.user = ctx.owner
+ assert (await ctx.client.post(path + "/listing", json={"version": 1})).status_code == 200
+ ctx.user = None
+ public = (await ctx.client.get(path)).json()
+ assert public["title"] == "测试作品"
+ assert not {"object_key", "asset_id", "owner_id", "email", "certificate_asset_id"}.intersection(public)
+ assert (await ctx.client.get("/api/marketplace/works")).json()["meta"]["total"] == 1
+ ctx.user = ctx.owner
+ assert (await ctx.client.put(path, json={**work_body(video), "title": "修改后", "version": 1})).status_code == 200
+ assert (await ctx.client.put(path, json={**work_body(video), "version": 1})).status_code == 409
+ ctx.user = None
+ assert (await ctx.client.get(path)).status_code == 404
+
+
+async def test_zero_price_contact_work_requires_full_watermark(ctx):
+ """价格为 0 的作品必须有完整时长水印才能进入广场,不能播放原片。"""
+ video = await asset(ctx)
+ await rights(ctx, video, full=True)
+ hidden_free = Work(owner_id=ctx.owner.id, **{**work_body(video), "title": "未生成水印", "price_fen": 0, "sale_type": "copyright_contact"}, audit_status="approved", listed=True)
+ hidden_paid = Work(owner_id=ctx.owner.id, **{**work_body(video), "title": "未生成试看", "price_fen": 100, "sale_type": "copyright_contact"}, audit_status="approved", listed=True)
+ shown = Work(owner_id=ctx.owner.id, **{**work_body(video), "title": "免费水印", "price_fen": 0, "sale_type": "copyright_contact"}, audit_status="approved", listed=True)
+ ctx.db.add_all([hidden_free, hidden_paid, shown])
+ await ctx.db.flush()
+ ctx.db.add(WorkPreview(work_id=shown.id, asset_id=video.id, version=1, status="done", object_key="marketplace/work-watermarks-full/test.mp4"))
+ await ctx.db.flush()
+ ctx.user = None
+ titles = [item["title"] for item in (await ctx.client.get("/api/marketplace/works")).json()["items"]]
+ assert "免费水印" in titles
+ assert "未生成水印" not in titles
+ assert "未生成试看" not in titles
+ assert (await ctx.client.get(f"/api/marketplace/works/{shown.id}")).status_code == 200
+ assert (await ctx.client.get(f"/api/marketplace/works/{hidden_free.id}")).status_code == 404
+
+
+async def test_expired_rights_hide_public_work(ctx):
+ """授权过期不依赖维护任务即可撤销公开可见性。"""
+ video = await asset(ctx)
+ proof = await rights(ctx, video, full=True)
+ proof.valid_until = now() - timedelta(seconds=1)
+ ctx.db.add(Work(owner_id=ctx.owner.id, **work_body(video), audit_status="approved", listed=True))
+ await ctx.db.flush()
+ ctx.user = None
+ assert (await ctx.client.get("/api/marketplace/works")).json()["items"] == []
+
+
+async def test_rights_review_requires_certificate_and_checks(ctx):
+ """完整核验不能只点通过,且证书申请回执不足。"""
+ video = await asset(ctx)
+ proof = await rights(ctx, video, full=False)
+ proof.full_status = "pending"
+ ctx.user = ctx.admin
+ path = f"/api/admin/marketplace/rights/{proof.id}/review?full=true"
+ body = {"version": 1, "decision": "approved", "reason": "已逐项核验"}
+ assert (await ctx.client.post(path, json=body)).status_code == 400
+ body["checks"] = ["identity", "ownership", "third_party", "scope", "certificate", "sample_match", "sales_authority"]
+ assert (await ctx.client.post(path, json=body)).status_code == 200
+ assert proof.full_status == "approved"
+ assert (await ctx.client.post(path, json=body)).status_code == 409
+
+
+async def test_case_certificate_does_not_approve_rights(ctx):
+ """案件标记取证不自动批准销售。"""
+ video = await asset(ctx)
+ proof = await rights(ctx, video, full=False)
+ result = await ctx.client.put(f"/api/marketplace/rights/{proof.id}/case", json={"route": "existing"})
+ assert result.status_code == 200, result.text
+ assert (await ctx.client.get(f"/api/marketplace/rights/{proof.id}/case")).json()["item"]["id"] == result.json()["id"]
+ ctx.user = ctx.admin
+ response = await ctx.client.post(f"/api/admin/marketplace/cases/{result.json()['id']}/status", json={"version": 1, "status": "certificated", "note": "已取得证书"})
+ assert response.status_code == 200, response.text
+ assert proof.full_status == "draft"
+
+
+async def test_submissions_are_private_and_withdrawal_revokes_new_links(ctx, monkeypatch):
+ """历史私密审片仍每次鉴权,第三人、未核验和撤回均不能签名。"""
+ fake_oss(monkeypatch)
+ video = await asset(ctx)
+ proof = await rights(ctx, video, basic=False)
+ post = await recruit(ctx)
+ item_id = (await historical_submission(ctx, post, video, proof)).id
+ media_path = f"/api/marketplace/media/submission/{item_id}/review"
+ ctx.user = ctx.buyer
+ assert (await ctx.client.get(media_path)).status_code == 403
+ proof.basic_status = "approved"
+ await ctx.db.flush()
+ assert (await ctx.client.get(media_path)).status_code == 200
+ assert (await ctx.client.get(f"/api/marketplace/media/asset/{video.id}/original")).status_code == 404
+ ctx.user = ctx.stranger
+ assert (await ctx.client.get(media_path)).status_code == 404
+ assert (await ctx.client.get(f"/api/marketplace/recruits/{post.id}/submissions")).status_code == 404
+ ctx.user = ctx.owner
+ assert (await ctx.client.post(f"/api/marketplace/submissions/{item_id}/withdraw")).status_code == 200
+ ctx.user = ctx.buyer
+ assert (await ctx.client.get(media_path)).status_code == 403
+
+
[email protected]("change", ["open", "expired", "closed", "self", "budget", "duplicate"])
+async def test_recruit_submissions_disabled_without_creating_media_jobs(ctx, change):
+ """旧客户端也无法投稿,不能修改资产、追加记录或创建审片任务。"""
+ video = await asset(ctx)
+ proof = await rights(ctx, video)
+ post = await recruit(ctx)
+ if change == "expired": post.deadline_at = now() - timedelta(seconds=1)
+ if change == "closed": post.state = "closed"
+ if change == "self": post.owner_id = ctx.owner.id
+ if change == "duplicate":
+ await historical_submission(ctx, post, video, proof)
+ await ctx.db.flush()
+ before = list((await ctx.db.execute(select(Submission.id))).scalars())
+ jobs_before = list((await ctx.db.execute(select(MediaJob.id))).scalars())
+ path = f"/api/marketplace/recruits/{post.id}/submissions"
+ body = {"asset_id": video.id, "quote_fen": 10001 if change == "budget" else 1000, "rights_accepted": True}
+ response = await ctx.client.post(path, json=body)
+ assert response.status_code == 410
+ assert response.json()['detail']['code'] == 'MARKETPLACE_SUBMISSIONS_DISABLED'
+ assert '联系客服' in response.json()['detail']['message']
+ assert list((await ctx.db.execute(select(Submission.id))).scalars()) == before
+ assert list((await ctx.db.execute(select(MediaJob.id))).scalars()) == jobs_before
+ assert video.status == 'ready'
+
+
+async def test_historical_submission_selection_disabled_and_preserved(ctx):
+ video = await asset(ctx)
+ proof = await rights(ctx, video, full=True)
+ post = await recruit(ctx)
+ item = await historical_submission(ctx, post, video, proof, selection='candidate')
+ path = f'/api/marketplace/submissions/{item.id}/selection'
+ for user in (ctx.owner, ctx.buyer, ctx.admin):
+ ctx.user = user
+ response = await ctx.client.post(path, json={'selection': 'not_selected'})
+ assert response.status_code == 410
+ assert response.json()['detail']['code'] == 'MARKETPLACE_SUBMISSIONS_DISABLED'
+ await ctx.db.refresh(item)
+ assert item.selection == 'candidate'
+ ctx.user = None
+ assert (await ctx.client.post(path, json={'selection': 'candidate'})).status_code == 401
+
+
+async def test_recruit_contact_requires_login_and_real_support_but_no_media(ctx):
+ """接单只有客服撮合,无需上传作品和版权材料;未配置客服不能假成功。"""
+ post = await recruit(ctx)
+ body = {'target_type': 'recruit', 'target_id': post.id}
+ ctx.user = None
+ assert (await ctx.client.post('/api/marketplace/consultations', json=body)).status_code == 401
+ ctx.user = ctx.owner
+ assert (await ctx.client.post('/api/marketplace/consultations', json=body)).status_code == 503
+ qr = await asset(ctx, kind='qr', owner=ctx.admin)
+ ctx.db.add(Support(id=1, enabled=True, qr_asset_id=qr.id, name='测试客服', wechat='test-support'))
+ await ctx.db.flush()
+ response = await ctx.client.post('/api/marketplace/consultations', json=body)
+ assert response.status_code == 200, response.text
+ detail = response.json()
+ assert detail['reference'] == f'RECRUIT-{post.id}'
+ assert detail['title'] == post.title and detail['price_fen'] == post.budget_fen
+ assert '接单请先联系客服' in detail['notice'] and '线下' in detail['notice']
+ assert not (await ctx.db.execute(select(Submission.id))).first()
+ assert not (await ctx.db.execute(select(MediaJob.id))).first()
+
+
[email protected]('change', ['closed', 'expired', 'blocked', 'draft', 'pending'])
+async def test_unavailable_recruit_rejects_new_contact(ctx, change):
+ post = await recruit(ctx)
+ if change in ('closed', 'draft'):
+ post.state = change
+ elif change == 'expired':
+ post.deadline_at = now() - timedelta(seconds=1)
+ elif change == 'blocked':
+ post.blocked = True
+ else:
+ post.audit_status = 'pending'
+ qr = await asset(ctx, kind='qr', owner=ctx.admin)
+ ctx.db.add(Support(id=1, enabled=True, qr_asset_id=qr.id))
+ await ctx.db.flush()
+ response = await ctx.client.post('/api/marketplace/consultations', json={'target_type': 'recruit', 'target_id': post.id})
+ assert response.status_code == 404
+
+
+async def test_changed_submission_rights_scope_cannot_unlock_review(ctx, monkeypatch):
+ """投稿快照不能静默使用已变更的授权范围。"""
+ fake_oss(monkeypatch)
+ video = await asset(ctx)
+ proof = await rights(ctx, video, full=True)
+ post = await recruit(ctx)
+ item_id = (await historical_submission(ctx, post, video, proof)).id
+ proof.version += 1
+ proof.details = {**proof.details, "scope": "改变后的授权范围"}
+ await ctx.db.flush()
+ ctx.user = ctx.buyer
+ response = await ctx.client.get(f"/api/marketplace/recruits/{post.id}/submissions")
+ assert not response.json()["items"][0]["can_review"]
+ assert (await ctx.client.get(f"/api/marketplace/media/submission/{item_id}/review")).status_code == 403
+ assert (await ctx.client.post(f"/api/marketplace/submissions/{item_id}/selection", json={"selection": "candidate"})).status_code == 410
+
+
+async def test_admin_guard_and_file_ownership(ctx):
+ """普通账号无法使用运营接口,也不能挂载他人视频。"""
+ video = await asset(ctx, owner=ctx.buyer)
+ assert (await ctx.client.get("/api/admin/marketplace/records/rights")).status_code == 403
+ assert (await ctx.client.post("/api/marketplace/works", json=work_body(video))).status_code == 404
+ assert (await ctx.client.get(f"/api/marketplace/assets/{video.id}/rights")).status_code == 404
+
+
+async def test_document_image_signs_only_processed_copy(ctx, monkeypatch):
+ """以证明材料类型上传的图片也只能取得重新编码后的对象。"""
+ fake_oss(monkeypatch)
+ document = await asset(ctx, kind="document")
+ document.content_type, document.cover_key = "image/jpeg", "private/processed.png"
+ await ctx.db.flush()
+ requested = []
+ monkeypatch.setattr(storage, "signed", lambda key, content_type: requested.append((key, content_type)) or "https://private.example.test/signed")
+ response = await ctx.client.get(f"/api/marketplace/media/asset/{document.id}/original")
+ assert response.status_code == 200, response.text
+ assert requested == [("private/processed.png", "image/png")]
+
+
+async def test_multipart_limits_and_idempotent_completion(ctx, monkeypatch):
+ """OSS替身验证大小校验、重复完成和唯一任务;不写本地文件。"""
+ fake_oss(monkeypatch)
+ sent = []
+ monkeypatch.setattr(storage, "initiate", lambda *args: "test-remote")
+ monkeypatch.setattr(storage, "part", lambda key, remote, number, blob: sent.append(blob) or "etag")
+ monkeypatch.setattr(storage, "complete", lambda *args: None)
+ monkeypatch.setattr(storage, "head", lambda *args: 4)
+ response = await ctx.client.post("/api/marketplace/uploads", json={"filename": "test.mp4", "size_bytes": 4, "kind": "video"})
+ assert response.status_code == 200, response.text
+ upload_id = response.json()["id"]
+ path = f"/api/marketplace/uploads/{upload_id}"
+ assert (await ctx.client.put(path + "/parts/1", content=b"12345")).status_code == 413
+ assert (await ctx.client.put(path + "/parts/1", content=b"1234")).status_code == 200
+ assert (await ctx.client.put(path + "/parts/1", content=b"1234")).status_code == 200
+ assert sent == [b"1234"]
+ assert (await ctx.client.post(path + "/complete")).status_code == 200
+ assert (await ctx.client.post(path + "/complete")).status_code == 200
+ assert len((await ctx.db.execute(select(MediaJob))).scalars().all()) == 0
+
+
+def test_storage_uses_admin_settings_and_tracks_changes(monkeypatch):
+ """同一 Bucket;后台停用、清除或轮换凭证立即作用于下游。"""
+ shared = SimpleNamespace(oss_enabled=True, oss_endpoint="oss.example.com", oss_bucket="shared",
+ oss_access_key_id="id", oss_access_key_secret="first")
+ monkeypatch.setattr(storage, "get_settings", lambda: shared)
+ calls = []
+ monkeypatch.setattr(storage, "_shared_client", lambda *args: calls.append(args) or args)
+ assert storage.configured()
+ assert storage._client()[1] == "shared"
+ shared.oss_access_key_secret = "rotated"
+ assert storage._client()[-1] == "rotated"
+ assert calls[0][-1] == "first"
+ shared.oss_enabled = False
+ assert not storage.configured()
+ with pytest.raises(HTTPException):
+ storage._client()
+ shared.oss_enabled, shared.oss_access_key_secret = True, ""
+ assert not storage.configured()
+
+
+def test_new_client_rechecks_bucket_permissions(monkeypatch):
+ """轮换配置后不沿用旧 Bucket 的权限检查结果。"""
+ safe = SimpleNamespace(get_bucket_acl=lambda: SimpleNamespace(acl="private"),
+ get_bucket_policy=lambda: SimpleNamespace(policy='{"Statement":[]}'))
+ monkeypatch.setattr(storage, "_client", lambda: safe)
+ monkeypatch.setattr(storage, "_verified_client", None)
+ monkeypatch.setattr(storage, "_verified_at", 0)
+ assert storage.bucket() is safe
+ unsafe = SimpleNamespace(get_bucket_acl=lambda: SimpleNamespace(acl="public-read"))
+ monkeypatch.setattr(storage, "_client", lambda: unsafe)
+ with pytest.raises(HTTPException):
+ storage.bucket()
+
+
+def test_public_bucket_is_rejected(monkeypatch):
+ """私有Bucket不成立时失败关闭,不自动更改ACL。"""
+ monkeypatch.setattr(storage, "_verified_at", 0)
+ monkeypatch.setattr(storage, "_client", lambda: SimpleNamespace(get_bucket_acl=lambda: SimpleNamespace(acl="public-read")))
+ with pytest.raises(HTTPException) as error:
+ storage.bucket()
+ assert error.value.status_code == 503
+
+
+def test_oss_transport_failure_has_stable_error(monkeypatch):
+ """已通过配置检查但云端网络失败也返回固定错误,不暴露SDK细节。"""
+ def fail_upload(*_args):
+ raise ConnectionError("private SDK diagnostic")
+ monkeypatch.setattr(storage, "bucket", lambda: SimpleNamespace(upload_part=fail_upload))
+ with pytest.raises(HTTPException) as error:
+ storage.part("key", "remote", 1, b"test")
+ assert error.value.status_code == 503
+ assert error.value.detail["code"] == "MARKETPLACE_STORAGE_UNAVAILABLE"
+
+
+async def test_worker_reads_shared_config_without_writing(monkeypatch):
+ """独立 Worker 读取后台配置,不调用会回写路由的初始化函数。"""
+ from contextlib import asynccontextmanager
+ from app.marketplace import worker
+ from app.services import model_settings
+ import app.config
+ seen = []
+
+ class ReadOnlySession:
+ async def get(self, model, key):
+ assert key == "default"
+ return SimpleNamespace(config_json={"flat": {"oss_enabled": True, "oss_bucket": "shared"}})
+
+ @asynccontextmanager
+ async def session():
+ yield ReadOnlySession()
+
+ monkeypatch.setattr(worker, "AsyncSessionLocal", session)
+ monkeypatch.setattr(model_settings, "_refresh_overlay", lambda value: seen.append(value))
+ monkeypatch.setattr(app.config, "reload_settings", lambda: seen.append("reload"))
+ await worker.refresh_storage_settings()
+ assert seen == [{"flat": {"oss_enabled": True, "oss_bucket": "shared"}}, "reload"]
+
+
+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(storage, "bucket", lambda: pytest.fail("不应访问OSS"))
+ await worker.main()
+
+
+async def test_supplement_certificate_keeps_submission_candidate(ctx, monkeypatch):
+ """历史候选和相关权限保留,补充材料不丢失旧标记。"""
+ fake_oss(monkeypatch)
+ video = await asset(ctx)
+ proof = await rights(ctx, video, full=False)
+ post = await recruit(ctx)
+ item_id = (await historical_submission(ctx, post, video, proof, selection='candidate')).id
+ ctx.user = ctx.buyer
+ proof.version += 1
+ proof.basic_status = "pending"
+ await ctx.db.flush()
+ assert (await ctx.client.get(f"/api/marketplace/media/submission/{item_id}/review")).status_code == 403
+ proof.basic_status, proof.full_status = "approved", "approved"
+ await ctx.db.flush()
+ listing = (await ctx.client.get(f"/api/marketplace/recruits/{post.id}/submissions")).json()
+ assert listing["items"][0]["selection"] == "candidate"
+ assert listing["items"][0]["can_purchase"]
+
+
+async def test_recruit_terms_locked_after_submission_and_close_preserves_review(ctx, monkeypatch):
+ """历史投稿需求继续保留原实质条件和已授权审片。"""
+ fake_oss(monkeypatch)
+ video = await asset(ctx)
+ proof = await rights(ctx, video)
+ post = await recruit(ctx)
+ item_id = (await historical_submission(ctx, post, video, proof)).id
+ ctx.user = ctx.buyer
+ body = {key: getattr(post, key) for key in ("title", "description", "category", "budget_fen", "wanted_count", "requirements", "license_scope", "image_ids", "version")}
+ body["deadline_at"] = post.deadline_at.isoformat()
+ body["budget_fen"] += 1
+ assert (await ctx.client.put(f"/api/marketplace/recruits/{post.id}", json=body)).status_code == 400
+ assert (await ctx.client.post(f"/api/marketplace/recruits/{post.id}/close")).status_code == 200
+ video.status = "ready"
+ await ctx.db.flush()
+ assert (await ctx.client.get(f"/api/marketplace/media/submission/{item_id}/review")).status_code == 200
+
+
+async def test_report_contact_private_and_admin_block_hides_work(ctx, monkeypatch):
+ """举报不是自动判定;管理员限制后目录与播放同时收紧。"""
+ fake_oss(monkeypatch)
+ video = await asset(ctx)
+ await rights(ctx, video, full=True)
+ item = Work(owner_id=ctx.owner.id, **work_body(video), audit_status="approved", listed=True)
+ ctx.db.add(item)
+ await ctx.db.flush()
+ await ready_work_preview(ctx, item.id, video.id)
+ ctx.user = ctx.buyer
+ response = await ctx.client.post("/api/marketplace/reports", json={"target_type": "work", "target_id": item.id, "statement": "这是需要核查权属的测试说明", "contact": "[email protected]"})
+ assert response.status_code == 200
+ public = (await ctx.client.get(f"/api/marketplace/works/{item.id}")).json()
+ assert "contact" not in public
+ ctx.user = ctx.admin
+ assert (await ctx.client.post(f"/api/admin/marketplace/block/work/{item.id}", json={"blocked": True, "reason": "存在初步证据,临时核查"})).status_code == 200
+ ctx.user = ctx.buyer
+ assert (await ctx.client.get(f"/api/marketplace/works/{item.id}")).status_code == 404
+ assert (await ctx.client.get(f"/api/marketplace/media/work/{item.id}/preview")).status_code == 404
+ ctx.user = ctx.owner
+ assert (await ctx.client.post(f"/api/marketplace/works/{item.id}/listing", json={"version": item.version})).status_code == 400
+
+
+async def test_worker_recovers_expired_lease(ctx, monkeypatch):
+ """模拟崩溃遗留租约,恢复后只发布一个就绪结果。"""
+ from contextlib import asynccontextmanager
+ from app.marketplace import worker
+
+ @asynccontextmanager
+ async def session():
+ """复用回滚事务,测试租约而非生产连接池。"""
+ yield ctx.db
+
+ async def process(_asset):
+ """媒体结果替身不访问任何云服务。"""
+ return {"fingerprint": "b" * 64, "preview_key": "private/preview.mp4", "review_key": "private/review.mp4"}
+
+ video = await asset(ctx, status="processing")
+ job = MediaJob(asset_id=video.id, status="running", attempts=1, lease_token="dead-process", lease_until=now() - timedelta(minutes=1))
+ ctx.db.add(job)
+ await ctx.db.flush()
+ monkeypatch.setattr(worker, "AsyncSessionLocal", session)
+ monkeypatch.setattr(worker, "process_asset", process)
+ assert await worker.run_once()
+ assert job.attempts == 2 and job.status == "done"
+ assert video.status == "ready"
+ assert not await worker.run_once()
+
+
+async def test_real_ffmpeg_processing_with_oss_transport_stub(monkeypatch, tmp_path):
+ """真实FFmpeg验证短预览和完整审片;只替换OSS传输,不计为云端联调。"""
+ import json
+ import shutil
+ from app.config import get_settings
+ from app.marketplace import worker
+ settings = get_settings()
+ source = tmp_path / "source.mp4"
+ await worker.command(settings.ffmpeg_path, "-y", "-v", "error", "-f", "lavfi", "-i", "color=c=blue:s=320x180:r=2", "-t", "31", "-c:v", "libx264", "-pix_fmt", "yuv420p", str(source))
+ results = {}
+
+ def download(_key, destination):
+ """仅读写测试临时目录。"""
+ shutil.copyfile(source, destination)
+
+ def upload(key, path, content_type):
+ """保存传输替身以检测输出内容,不创建业务OSS假对象。"""
+ target = tmp_path / path.name
+ shutil.copyfile(path, target)
+ results[key] = target
+
+ monkeypatch.setattr(storage, "download", download)
+ monkeypatch.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()
+
+
[email protected]("extension", ["png", "jpg", "webp"])
+async def test_real_image_processing_with_oss_transport_stub(monkeypatch, tmp_path, extension):
+ """真实图片检测及重编码覆盖参考图、证书图片和客服二维码。"""
+ import shutil
+ from app.config import get_settings
+ from app.marketplace import worker
+ source = tmp_path / f"source.{extension}"
+ await worker.command(get_settings().ffmpeg_path, "-y", "-v", "error", "-f", "lavfi", "-i", "color=c=blue:s=64x64", "-frames:v", "1", "-threads", "1", str(source))
+ monkeypatch.setattr(storage, "download", lambda _key, path: shutil.copyfile(source, path))
+ output = tmp_path / "processed.png"
+ monkeypatch.setattr(storage, "upload", lambda _key, path, _type: shutil.copyfile(path, output))
+ result = await worker.process_asset({"id": 1000, "filename": source.name, "object_key": "unit-test", "kind": "image", "size_bytes": source.stat().st_size, "content_type": "image/" + extension})
+ assert result["cover_key"].endswith("/image.png")
+ assert output.read_bytes().startswith(b"\x89PNG\r\n\x1a\n")
+
+async def test_unified_external_work_review_and_material_change(ctx):
+ """Minimal copyright input is reviewed with the work; edits revoke old approvals."""
+ video = await asset(ctx)
+ certificate = await asset(ctx, kind="image")
+ work = (await ctx.client.post("/api/marketplace/works", json={**work_body(video), "source": "external"})).json()
+ copyright_path = f"/api/marketplace/assets/{video.id}/rights"
+ payload = {"details": {"source": "external", "certificate_number": "CERT-1", "dispute_ack": True}, "certificate_asset_id": certificate.id}
+ saved = await ctx.client.put(copyright_path, json=payload)
+ assert saved.status_code == 200, saved.text
+ work_path = f"/api/marketplace/works/{work['id']}"
+ version = (await ctx.client.get(work_path)).json()["version"]
+ await ready_work_preview(ctx, work['id'], video.id, version)
+ assert (await ctx.client.post(work_path + "/submit", json={"version": version})).status_code == 200
+ # The old separate copyright submission cannot create a second review.
+ assert (await ctx.client.post(f"/api/marketplace/rights/{saved.json()['id']}/submit", json={"version": 1})).status_code == 409
+ ctx.user = ctx.admin
+ records = (await ctx.client.get("/api/admin/marketplace/records/works")).json()["items"]
+ assert records[0]["details"]["certificate_number"] == "CERT-1"
+ assert records[0]["certificate_asset_id"] == certificate.id
+ review_path = f"/api/admin/marketplace/works/{work['id']}/review"
+ review = {"version": version, "decision": "approved", "reason": "Reviewed both", "checks": ["content", "copyright"]}
+ assert (await ctx.client.post(review_path, json=review)).status_code == 200
+ ctx.user = ctx.owner
+ assert (await ctx.client.post(work_path + "/listing", json={"version": version})).status_code == 200
+ changed = await ctx.client.put(copyright_path, json={**payload, "version": 1})
+ assert changed.status_code == 200, changed.text
+ updated = (await ctx.client.get(work_path)).json()
+ assert updated["audit_status"] == "draft" and not updated["listed"]
+ assert updated["version"] > version
+ ctx.user = ctx.admin
+ assert (await ctx.client.post(review_path, json=review)).status_code == 409
+
+async def test_uploaded_media_preview_uses_original_without_worker(ctx, monkeypatch):
+ """Direct uploads do not have derived previews or covers."""
+ fake_oss(monkeypatch)
+ requested = []
+ monkeypatch.setattr(storage, 'signed', lambda key, content_type: requested.append((key, content_type)) or 'https://private.example.test/signed')
+ video = await asset(ctx)
+ video.preview_key = video.review_key = video.cover_key = None
+ image = await asset(ctx, kind='image')
+ image.cover_key = None
+ image.content_type = 'image/png'
+ await ctx.db.flush()
+ for purpose in ('original', 'preview'):
+ result = await ctx.client.get(f'/api/marketplace/media/asset/{video.id}/{purpose}')
+ assert result.status_code == 200, result.text
+ assert requested[-1] == (video.object_key, 'video/mp4')
+ for purpose in ('original', 'cover'):
+ result = await ctx.client.get(f'/api/marketplace/media/asset/{image.id}/{purpose}')
+ assert result.status_code == 200, result.text
+ assert requested[-1] == (image.object_key, 'image/png')
+ ctx.user = ctx.stranger
+ assert (await ctx.client.get(f'/api/marketplace/media/asset/{video.id}/original')).status_code == 404
+
diff --git a/backend/tests/test_marketplace_handoff.py b/backend/tests/test_marketplace_handoff.py
new file mode 100644
index 0000000..a68fb96
--- /dev/null
+++ b/backend/tests/test_marketplace_handoff.py
@@ -0,0 +1,21 @@
+"""成片转存的纯函数校验,不连接数据库。"""
+from app.marketplace.handoff import object_key
+
+
+def test_object_key_from_same_bucket_url():
+ key = object_key(
+ "https://reelbay-pri.oss-cn-hangzhou.aliyuncs.com/kepu/generated/p1/final.mp4?Expires=1",
+ bucket="reelbay-pri",
+ public_base="https://reelbay-pri.oss-cn-hangzhou.aliyuncs.com",
+ folder="kepu",
+ )
+ assert key == "kepu/generated/p1/final.mp4"
+
+
+def test_object_key_ignores_local_static_and_marketplace_prefix():
+ assert object_key("/static/generated/p1/final.mp4", bucket="b", public_base="https://b.example", folder="kepu") is None
+ assert object_key("marketplace/works/u1/2/a.mp4", bucket="b", public_base="https://b.example", folder="kepu") is None
+
+
+def test_object_key_accepts_raw_object_key():
+ assert object_key("kepu/generated/p8/final.mp4", bucket="b", public_base="https://b.example", folder="kepu") == "kepu/generated/p8/final.mp4"
diff --git a/backend/tests/test_marketplace_runtime.py b/backend/tests/test_marketplace_runtime.py
new file mode 100644
index 0000000..4f123ce
--- /dev/null
+++ b/backend/tests/test_marketplace_runtime.py
@@ -0,0 +1,106 @@
+"""媒体生命周期测试不连接 OSS,不启动真实转码。"""
+import asyncio
+import sys
+
+import pytest
+
+from app.marketplace import runtime
+from app.marketplace.config import get_marketplace_settings
+
+
+def test_media_tools_fall_back_to_environment_paths(monkeypatch, tmp_path):
+ from types import SimpleNamespace
+ from app import config
+ from app.marketplace import worker
+ executable = tmp_path / 'ffprobe.exe'
+ executable.touch()
+ monkeypatch.setattr(worker.shutil, 'which', lambda value: None)
+ monkeypatch.setattr(config, 'Settings', lambda: SimpleNamespace(ffprobe_path=str(executable)))
+ assert worker.resolve_tool('ffprobe') == str(executable)
+ explicit = str(tmp_path / 'custom.exe')
+ assert worker.resolve_tool(explicit) == explicit
+
+
+async def test_media_command_selector_loop_fallback(monkeypatch):
+ from app.marketplace import worker
+ async def unsupported(*args, **kwargs):
+ raise NotImplementedError
+ monkeypatch.setattr(asyncio, 'create_subprocess_exec', unsupported)
+ output = await worker.command(sys.executable, '-c', 'print("selector-compatible")', timeout=10)
+ assert output.strip() == b'selector-compatible'
+
+
+async def test_media_thread_command_timeout_and_cancellation(monkeypatch):
+ from app.marketplace import worker
+ original = worker.subprocess.Popen
+ processes = []
+ def capture(*args, **kwargs):
+ process = original(*args, **kwargs)
+ processes.append(process)
+ return process
+ monkeypatch.setattr(worker.subprocess, 'Popen', capture)
+ args = (sys.executable, '-c', 'import time; time.sleep(10)')
+ with pytest.raises(TimeoutError):
+ await worker.threaded_command(args, .1)
+ assert processes[-1].poll() is not None
+ task = asyncio.create_task(worker.threaded_command(args, 20))
+ while len(processes) < 2:
+ await asyncio.sleep(.01)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert processes[-1].poll() is not None
+
+
+async def test_market_runtime_disabled_does_not_start(monkeypatch):
+ monkeypatch.setattr(get_marketplace_settings(), "enabled", False)
+ await runtime.start_marketplace_runtime()
+ assert runtime._watchdog is None and runtime._worker is None
+
+
+async def test_market_runtime_idempotent_and_clean_shutdown(monkeypatch):
+ monkeypatch.setattr(get_marketplace_settings(), "enabled", True)
+ started, stopped = asyncio.Event(), asyncio.Event()
+ async def loop():
+ started.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ stopped.set()
+ monkeypatch.setattr(runtime, "run_loop", loop)
+ try:
+ await runtime.start_marketplace_runtime()
+ await asyncio.wait_for(started.wait(), 1)
+ original = runtime._worker
+ await runtime.start_marketplace_runtime()
+ assert runtime._worker is original
+ finally:
+ await runtime.stop_marketplace_runtime()
+ assert stopped.is_set()
+ assert runtime._worker is None and runtime._watchdog is None
+ await runtime.stop_marketplace_runtime()
+
+
[email protected]("cancelled", [False, True])
+async def test_market_runtime_recovers_failed_or_cancelled_loop(monkeypatch, cancelled):
+ monkeypatch.setattr(get_marketplace_settings(), "enabled", True)
+ started, restarted = asyncio.Event(), asyncio.Event()
+ calls = 0
+ async def loop():
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ started.set()
+ if cancelled:
+ raise asyncio.CancelledError
+ raise RuntimeError("test unexpected exit")
+ restarted.set()
+ await asyncio.Event().wait()
+ monkeypatch.setattr(runtime, "run_loop", loop)
+ try:
+ await runtime.start_marketplace_runtime()
+ await asyncio.wait_for(started.wait(), 1)
+ await asyncio.wait_for(restarted.wait(), 4)
+ assert calls == 2 and not runtime._worker.done()
+ finally:
+ await runtime.stop_marketplace_runtime()
diff --git a/docs/DIGITAL_ASSET_DEVELOPMENT.md b/docs/DIGITAL_ASSET_DEVELOPMENT.md
new file mode 100644
index 0000000..bf20d7a
--- /dev/null
+++ b/docs/DIGITAL_ASSET_DEVELOPMENT.md
@@ -0,0 +1,249 @@
+# 数字资产市场分期开发说明
+
+本文是数字资产市场的产品与开发边界。Word 版本(含第一期页面截图)见 [数字资产市场分期开发说明.docx](./数字资产市场分期开发说明.docx)。实现细节、配置和历史变更仍以 [MARKETPLACE.md](./MARKETPLACE.md) 为准;本文负责划分两期范围,避免把 Web 版权交易和 App 持续收益混成一次交付。
+
+模块保持独立:数据表使用 `marketplace_` 前缀,接口使用 `/api/marketplace/*` 与 `/api/admin/marketplace/*`。只复用现有登录和管理员身份。不改原创作、生成、计费、任务调度、存储函数和漫剧表。`C:\code\ReelBay` 只作流程参考,不改其代码。
+
+文件继续共用后台「系统设置 → 存储 OSS」里的同一个 Bucket,市场文件固定放在 `marketplace/`。原业务目录保持原样。市场对象保持私有,访问时签发短时链接。OSS 未配置时,上传和依赖文件的发布返回 `503`,错误码 `MARKETPLACE_STORAGE_UNAVAILABLE`,不回退到本地存储,也不返回 `/static` 地址。
+
+## 分期
+
+| | 第一期 | 第二期 |
+|---|---|---|
+| 终端 | 用户端 Web、管理后台 | App 先做持续收益;Web 只补作者配置、系列基础浏览和运营后台 |
+| 业务 | 作品广场、招募广场、版权确认与客服交易 | 平台投放、在线解锁、短剧分集、收益记账和人工打款 |
+| 钱怎么走 | 页面展示参考价,购买和接单都联系客服,线下签约、收款、交付 | 观众在线支付解锁单条或单集;平台与创作者按比例记账,管理员人工打款 |
+| 播放 | 免费作品播完整时长水印;付费版权作品只播水印试看 | 未购买只播试看;已购买获得永久在线播放权益,每次播放重新鉴权 |
+
+第一期可以上线并运营。第二期在第一期作品、权属和 OSS 链路上继续加,不回头改第一期的客服购买规则。
+
+短剧和单视频一起出现在作品广场。平台投放、内容订单、永久权益、收益账本和人工打款仍属于第二期,待真实 OSS、易支付回调和 App 播放端验收。Web 不提供独立观众端付费播放站。
+
+## 第一期:Web 作品广场、招募广场与版权交易
+
+### 入口
+
+用户端顶部只保留一个「数字资产市场」。进入后切换:
+
+- 作品广场 `/marketplace`
+- 招募广场 `/marketplace/recruits`
+- 发布作品 `/marketplace/works/new`
+- 发布招募 `/marketplace/recruits/new`
+- 我的发布 `/marketplace/mine`
+
+管理后台放在侧边栏「业务」分组下,名称是「数字资产平台运营」。日常导航是作品审核、招募审核、举报处理、客服配置、作品分类。媒体任务和操作记录收在默认折叠的「运行维护」里。
+
+广场点进作品,看到的是买家页:视频、介绍、参考价、「联系客服购买」。作者的编辑、提交审核和上下架只从「我的发布 → 查看与管理」进入。招募同理:广场是需求帖和「联系客服接单」,管理页才有编辑、审核和关闭。
+
+### 作品发布
+
+一次发布只绑定一条视频和一个作者上传的封面。发布页不展示历史文件列表,重新上传即替换当前选择。
+
+保存草稿只保存作品资料,不要求签署授权函或上传版权材料,也不生成试看。
+
+收费在第一期只有两种:
+
+- **免费公开**:价格为 0。审核通过并上架后,公众播放完整时长水印,不提供无水印原片。免费不代表可以任意商用。
+- **联系客服购买版权**:填写参考价。参考价大于 0 时,公众只能看水印试看;参考价为 0 时按免费处理,播放完整时长水印。无水印原片不进入公开播放接口。
+
+作品分类由管理员配置,发布页用下拉选择,广场用同一份配置做筛选。初始分类为短片、广告、动画、文旅、科普、其他。移除分类不改历史作品。
+
+提交审核前必须补齐:
+
+- 视频已上传;
+- 封面已上传;
+- 标题、简介、分类、拟授权用途及限制;
+- 下面的版权材料。
+
+按钮旁直接列出缺什么,避免只显示灰色按钮。
+
+### 版权确认
+
+用户只做一次确认,管理员只做一次审核。审核页里可以分成「内容检查」和「版权检查」两个区域,结果只有待审核、已通过、已驳回。
+
+按来源分流:
+
+- **PrintFilm 生成**:阅读并手写签署账号授权函,把当前视频关联到这份签署记录。不要求版权证书、截图或其他权属证明。授权函按账号与条款版本签署,作品仍逐件审核。
+- **其他平台生成**:填写版权证书编号,上传证书截图或照片,勾选「版权纠纷与平台无关」。
+- **没有版权材料**:联系客服线下协办。协办不创建登记案件,不自动通过审核,补齐材料后再提交作品。
+
+不向用户展示基础核验、完整核验、私密核验、自行办理版权登记。修改版权材料后撤回已通过的审核和下架,防止旧审核结果批准新材料。
+
+### 试看
+
+作品在点击「提交审核」时才生成水印播放文件,不在上传或保存草稿时转码。
+
+试看规则:
+
+- 有标价的版权作品时长取 15 秒和原片时长 30% 中的较小值;免费和零元作品保留完整时长;
+- 保留原分辨率和原帧率,使用高保真编码;
+- 水印烧进画面,内容为 PRINTFILM、作者名字和「侵权必究」;
+- 不生成封面,封面以用户上传为准;
+- 生成成功后自动进入待审核,失败可重试;
+- 试看未就绪时,公开接口不回退原片。
+
+免费和零元作品生成完整时长水印,有标价的版权作品生成短试看。收费方式变化后先下架,生成对应水印并重新审核后才能再上架。已经保存出去的无水印原片无法收回。
+
+媒体处理由市场 Worker 完成。它随后端自动启动、停止,异常退出后自动恢复,并发保持 1。它不接入原项目 AI 调度和计费。免费作品的完整时长转码也由它串行处理。
+
+### 作品广场
+
+广场以封面浏览为主:分类、搜索、价格区间、最新和价格排序。卡片展示封面、标题、作者和参考价;免费作品价格显示「免费」。
+
+买家详情:
+
+- 免费作品播放完整时长水印;
+- 付费作品播放水印试看;
+- 「联系客服购买」打开展示真实客服二维码、微信号和服务时间;
+- 可复制作品编号、标题、参考价和链接;
+- 弹窗说明:购买使用授权不等于取得版权。购买著作财产权须另行签订书面转让合同并办理手续,可能产生办理、登记或服务费用,参考价不包含这些费用,费用和承担方先与客服确认。
+
+客服未配置时显示「客服暂不可用」,不用社区入群微信代替。
+
+上传成功且云端预览可播放后,自动关掉本地预览,改显示云端文件。上传失败时保留本地预览。
+
+### 招募广场
+
+招募是需求展示和客服撮合,不接受站内投稿。
+
+需求方填写标题、说明、分类、单条预算、数量、时长、画幅、用途、交付要求、授权意向、截止时间,最多 6 张参考图。管理员审核通过后公开展示。
+
+创作者打开需求帖,登录后点「联系客服接单」。咨询不代表已接单或成交。不上传应征视频,不报价,不审片,不选稿。
+
+关闭、到期、未审核或封禁的需求不再接受新咨询。作者从「我的发布」管理自己的需求。已有历史投稿只留在后台「运行维护」,不恢复投稿入口。
+
+### 第一期验收
+
+- 不配置 AI、支付和邮件,仍能完成上传、草稿、版权确认、一次审核、上架、广场浏览和客服咨询。
+- OSS 未配置时上传被明确阻断。
+- 广场点击作品不会进入作者管理页。
+- 草稿保存不要求授权函或版权证明。
+- PrintFilm 作品签署授权函后可以提交;其他平台作品缺证书编号、截图或勾选时不能提交。
+- 付费作品公众只能拿到试看;免费作品播放完整时长水印,不返回原片。
+- 招募详情没有投稿表单,新投稿接口保持关闭。
+- 原项目登录、生成、计费和漫剧流程不受影响。
+
+## 第二期:App 持续收益
+
+第二期从 App 观众付费解锁开始。Web 第一期的客服版权购买继续保留,不改成自动交易。
+
+### 收费类型
+
+在免费公开、联系客服购买版权之外,增加 **平台投放收益**。三种类型互斥。
+
+| 类型 | 观众看到什么 | 钱怎么结算 |
+|---|---|---|
+| 免费公开 | 完整时长水印 | 无订单 |
+| 联系客服购买版权 | 水印试看,联系客服 | 线下签约收款,不产生平台订单 |
+| 平台投放收益 | 未购买看试看;支付后永久在线播放 | 在线支付,按比例记账,人工打款 |
+
+版权参考价和平台解锁价分开保存。平台投放必须填写大于 0 的解锁价。版权材料仍按第一期规则,在同一次审核里检查。
+
+### 分成
+
+后台先配置统一的创作者分成比例,平台比例由系统用万分比计算。未配置统一比例时,平台投放作品可以存草稿,不能提交审核。
+
+单个作品或单个分集可以覆盖分成比例;留空则使用后台统一配置。订单支付成功时把当时的比例写进账本,之后修改配置不影响已入账订单。
+
+### 短剧
+
+单条短视频作品保持不变,不把历史作品改成剧集。短剧系列和单视频一起出现在作品广场,发布时在同一入口选择「短剧」:
+
+```text
+短剧系列
+ └── 第 1 集
+ └── 第 2 集
+ └── 第 N 集
+```
+
+分集来源:
+
+- 手动上传,每集一个视频、一个封面;
+- 用户明确选择后,从自己的漫剧项目导入已经生成成片的分集。导入时复制到 `marketplace/`,保存项目和分集快照。之后原漫剧修改不影响市场内容,市场也不回写漫剧。
+
+同一系列提交时收费类型保持一致。平台投放按集购买、按集定价、按集分成。购买一集只解锁这一集的当前发布版本。
+
+系列提交时检查:至少一集、集数连续、每集视频和封面就绪、每集版权材料齐全、每集都有对应水印播放文件、投放集已有解锁价和可用分成配置。短剧卡片出现在作品广场,不单独开设短剧页。任意一集不通过,系列不能上架。
+
+### 支付、权益和打款
+
+不使用原 AI 充值钱包,不写入原 `orders` 表。支付通道复用现有易支付适配器里的支付宝和微信能力,订单、权益、账本使用市场自己的表。
+
+观众流程:
+
+1. App 请求解锁订单;
+2. 跳转支付;
+3. 回调校验签名和金额;
+4. 同一笔回调重复到达只入账一次;
+5. 写入永久观看权益;
+6. 写入平台收入和创作者收入,两者之和等于实付金额。
+
+同一用户重复购买同一发布版本时返回已有权益,不重复分账。本期不支持退款,支付成功后不自动撤销权益。
+
+创作者在 App 或后续 Web 查看收益明细。管理员在后台把待结算标记为已打款,并记录金额、时间、渠道、外部流水号、操作人和备注。本期不做自动提现。
+
+支付参数或回调地址未配置时返回 `MARKETPLACE_PAYMENT_UNAVAILABLE`,不伪造支付成功,不提前开放原片。
+
+作品替换视频或变更授权后产生新的发布版本并重新审核。已购买的旧版本继续对应旧播放文件,不自动换成新版本。
+
+### 播放
+
+平台投放内容:
+
+- 未购买只签发试看;
+- 已购买签发短时有效的 HLS 播放清单和分片,不返回原片地址;
+- 播放版本保留原分辨率,不强制压到 720p;
+- 审核通过后再生成完整播放版本,就绪后才进入 App 内容流;
+- 每次播放重新鉴权。
+
+这只能降低直接下载,不能阻止录屏。试看水印和账号权益用于追踪,不承诺无法复制。
+
+文件目录:
+
+```text
+marketplace/works/
+marketplace/series/
+marketplace/previews/
+marketplace/hls/
+marketplace/rights/
+```
+
+仍由同一个市场 Worker 处理试看和播放版本,不新增第二套进程,也不写入原项目任务表。
+
+### App 与 Web 的分工
+
+App 第一批接口:
+
+- 平台内容流和分集详情;
+- 当前用户是否已解锁;
+- 试看或已购播放地址;
+- 创建解锁订单和查询支付结果;
+- 创作者收益明细。
+
+本期不做独立的 Web 短视频播放站,也不向抖音等外部平台自动发布。Web 只保留作者配置解锁价、分成和管理员查看订单、权益、账本、打款。
+
+### 第二期验收
+
+- 未配置分成时,平台投放不能提交。
+- 单集或单作品分成优先于后台默认值。
+- 支付回调重复通知不会产生第二份权益或账本。
+- 未支付用户拿不到完整播放地址。
+- 已支付用户获得永久在线播放权益。
+- 导入漫剧分集不修改原项目。
+- 第一期免费作品、客服版权购买和招募接单保持可用。
+- 原 AI 充值、计费和漫剧生成不受影响。
+
+本地没有真实支付和公网回调时,只验收接口、签名校验和权限边界,不把真实支付记为通过。
+
+## 参考项目
+
+只借鉴状态和边界,不复制代码。AGPL 项目不能搬进本仓库。
+
+- PeerTube:内容公开、审核和播放权限。
+- MediaCMS:媒体资产和后台运营。
+- Owncast:自托管播放状态,它偏直播,不直接当点播付费模型。
+- Video.js、Shaka Player:第二期 App 或后续 Web 播放器,当前不引入依赖。
+- FOSSBilling:订单、账本和人工财务处理。
+- social-auto-upload:以后如果要分发到外部平台,再做独立适配器。
+
+GitHub 上没有一个项目同时覆盖本平台的版权审核、客服版权交易、永久解锁和人工分账,所以两期都做在现有市场模块上,而不是替换原项目。
diff --git a/docs/LOCAL_DEVELOPMENT.md b/docs/LOCAL_DEVELOPMENT.md
new file mode 100644
index 0000000..4a3fbfd
--- /dev/null
+++ b/docs/LOCAL_DEVELOPMENT.md
@@ -0,0 +1,90 @@
+# Windows 本地开发环境
+
+本机项目目录:`C:\code\printfilm`。使用 Python 3.12 虚拟环境、两个 Vite 开发服务器、Docker PostgreSQL 与 Redis。未启用模拟 AI,也未接入真实 AI、支付、OSS 或邮件服务。
+
+## 一键启动与停止
+
+先启动 Docker Desktop,然后在 PowerShell 中运行:
+
+```powershell
+cd C:\code\printfilm
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\.work\local-dev\start.ps1
+```
+
+脚本在后台运行后端和两个前端,后端启用热重载。重复执行会复用本脚本已启动的进程;其他进程占用目标端口时会停止启动并提示,不会自动终止它。
+
+停止本项目三个应用及两个容器:
+
+```powershell
+cd C:\code\printfilm
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\.work\local-dev\stop.ps1
+```
+
+停止脚本按本次保存的 PID 和启动时间核对进程,仅停止本项目的服务树;Docker 数据卷保留。重启电脑后重新启动 Docker Desktop 并运行启动脚本即可。
+
+`.work/local-dev` 是本机辅助目录,已被 Git 忽略,脚本不会随仓库提交到其他电脑。上述 ExecutionPolicy 参数只作用于当前命令,不修改系统全局执行策略。
+
+## 访问入口
+
+- 用户端:http://127.0.0.1:5173
+- 用户注册登录:http://127.0.0.1:5173/auth
+- 管理后台:http://127.0.0.1:5174
+- 接口文档:http://127.0.0.1:8000/docs
+- 健康检查:http://127.0.0.1:8000/api/health
+- PostgreSQL:127.0.0.1:15432,数据库和用户均为 `printfilm`。
+- Redis:127.0.0.1:16379。
+
+管理后台需要管理员身份。先在用户端注册自己的账号,再将注册邮箱写入 `backend/.env` 的 `ADMIN_BOOTSTRAP_EMAILS`,重启后端即可提升权限。没有预置管理员账号;验收临时账号会删除。
+
+## 本机配置与日志
+
+- `backend/.env`:数据库连接、应用随机密钥、媒体工具绝对路径与功能开关。
+- `deploy/.env.prod`:本地 PostgreSQL 用户、随机密码和映射端口。文件名沿用项目现有 Compose 约定,内容用于本地开发。
+- `backend/.venv`:项目独立 Python 环境。
+- `C:\soft\ffmpeg`:FFmpeg essentials 发行包;程序位于版本子目录的 `bin` 下,已配置到后端,无需手动添加 PATH。
+- `.work/local-dev/*.stdout.log`、`*.stderr.log`:各应用日志。
+- `.work/local-dev/processes.json`:本机辅助脚本管理的进程信息。
+- `.work/local-dev/verification.json`:本地验收摘要,不含测试账号密码和访问令牌。
+
+两份环境文件均在 Git 忽略规则内。数据库密码可在本机环境文件中查看,不要提交到版本库或复制到公开日志。现有其他项目容器不属于本项目的启停范围。
+
+## 在 VS Code 中分别启动
+
+如果需要直接观察终端日志,先用停止脚本停掉后台服务,再依次启动:
+
+```powershell
+cd C:\code\printfilm
+docker compose -f deploy/docker-compose.yml --env-file deploy/.env.prod up -d --wait
+```
+
+后端终端:
+
+```powershell
+cd C:\code\printfilm\backend
+.\.venv\Scripts\python.exe -m uvicorn app.main:app --host 127.0.0.1 --port 8000 --reload
+```
+
+用户端终端:
+
+```powershell
+cd C:\code\printfilm\frontend
+npm.cmd run dev -- --host 127.0.0.1 --port 5173 --strictPort
+```
+
+管理端终端:
+
+```powershell
+cd C:\code\printfilm\admin
+npm.cmd run dev -- --host 127.0.0.1 --port 5174 --strictPort
+```
+
+前台启动的应用用各自终端的 Ctrl+C 停止。不要同时使用后台脚本和前台命令抢占同一端口。不需要另开 Celery Worker。数字资产市场启用时,其媒体 Worker 也随后端自动启动、停止和异常恢复,无需单独运行命令;未配置 OSS 时空闲等待。若之前手动开过市场 Worker,请在那个终端按 Ctrl+C 关闭,以后只启动后端即可。
+
+## 验收与外部功能边界
+
+本地验收只访问本机接口,覆盖应用健康、前端入口、注册登录、错误密码、重复注册、数据库与 Redis,以及 FFmpeg 中文字体渲染。验收脚本位于 `.work/local-dev/verify_local.py`,可用后端虚拟环境 Python 重跑。
+
+`ARK_MOCK=false`,AI Key 为空;计费、OSS、SMTP 关闭。未验证真实生成、支付、云上传和发邮件。当前源码部分 AI 路径缺 Key 时会自动回退 mock,这是已有业务行为,本次没有修改,也没有触发这些接口。
+
+前端依赖按各自锁文件安装。更换电脑或清除 node_modules 后,在 `frontend`、`admin` 目录分别执行 `npm.cmd ci`。
+
diff --git a/docs/MARKETPLACE.md b/docs/MARKETPLACE.md
new file mode 100644
index 0000000..57132ed
--- /dev/null
+++ b/docs/MARKETPLACE.md
@@ -0,0 +1,199 @@
+## 当前实现规范:作品广场(单视频与短剧)+ 平台投放(2026-10-23)
+
+本节是当前产品和接口的准则,优先于本文后面的历史记录。市场保留原有单视频作品,新增独立的短剧系列与分集模型;历史作品不会自动迁移。单视频和每个分集都使用不可变发布版本,修改视频、权属材料、收费类型或价格后必须重新提交审核。作品内容与版权信息在同一次管理员审核中完成,不要求用户先做“版权审核”再做“内容审核”。
+
+收费类型只有三种:
+
+- `free`:审核通过并上架后播放完整时长烧录水印,不公开无水印原片。免费不代表可以任意商用,也不承诺防录屏。
+- `copyright_contact`:参考价大于 0 时只展示最多 15 秒且不超过原片 30% 的原分辨率烧录水印试看;参考价为 0 时按免费处理,播放完整时长水印。购买版权通过真实客服线下协商。
+- `platform_unlock`:单视频或单集单独配置解锁价;未购买看试看,支付成功后永久在线播放,不返回原片地址。
+
+平台投放作品必须先由后台配置默认创作者分成比例;作品或分集可以覆盖该比例。没有默认比例时只能保存草稿,提交审核返回 `MARKETPLACE_REVENUE_CONFIG_REQUIRED`。订单、永久权益、收益账本和人工打款使用独立 `marketplace_` 表,不复用原 AI 钱包或订单,不提供退款和自动提现。支付配置缺失返回 `MARKETPLACE_PAYMENT_UNAVAILABLE`。
+
+短剧结构为 `Series → Episode`,和单视频一起出现在作品广场,不再单独开设短剧广场。发布入口有「发布作品」,也可以从 PrintFilm 成片页进入「发布到数字资产市场」。科普成片和明确选中的漫剧分集只提交编号,由市场 Worker 复制到 `marketplace/`;同一成片版本重复点击不会生成第二份草稿,原项目重新生成后用新版本再发布。草稿可以先保存,提交审核前仍要签署账号授权函,管理员一次审核内容和版权,通过后由作者上架。水印不在复制时生成。
+
+版权材料按来源简化:PrintFilm 生成只需关联当前有效的签署授权函;其他平台需要证书编号、证书截图/照片和“版权纠纷与平台无关”确认;没有材料时只能联系客服协办,不创建新的登记案件,也不会自动通过。客服购买版权和招募接单均使用后台维护的真实二维码,不使用虚假或社区微信。
+
+同一个市场 Worker 负责成片复制、上传后媒体校验、水印播放文件和平台 HLS 播放版本,数据库持久化任务、租约和重试,随 API 自动启动并由看门狗恢复;不修改原项目 Worker、AI 调度、计费、漫剧表或存储目录。免费和零元作品生成完整时长水印,有标价的版权作品只生成短试看,平台投放审核通过后才生成同源分辨率 HLS。共用 OSS 但固定使用 `marketplace/` 前缀,OSS 未配置时上传和依赖媒体的接口返回 503 `MARKETPLACE_STORAGE_UNAVAILABLE`,不回退本地文件。已经上架但没有水印的免费内容会在服务启动时下架并排队生成水印。
+
+当前已完成:用户端系列创建/编辑/导入/提交、系列和分集浏览,单视频三种收费类型,管理员系列审核、分成配置、订单/权益查询(支持购买用户和创作者筛选)、收益账本、人工打款和分类配置,市场 Worker 试看/HLS 任务,以及短时签名播放权限。当前仍需真实环境验收:共用 OSS 的分片上传、私有对象与分片签名、FFmpeg/HLS 播放、易支付回调和 App 播放端;本地未配置真实服务时这些接口只能验证错误码和权限边界。
+
+核心接口:系列使用 /api/marketplace/series、/series/{id}/episodes、/series/{id}/episodes/import 和 /series/{id}/submit;平台内容使用 /platform/feed、/platform/episodes/{id}、/platform/works/{id} 及对应 /playback;订单使用 /content-orders、/entitlements 和 /payments/epay/notify。播放接口只返回短时签名清单或原片链接,详情接口不会泄露 OSS 密钥。当前不提供 Web 观众端支付/播放页面,App 应按接口接入。
+## 当前招募规则:联系客服接单(2026-10-21)
+
+招募只提供需求展示与客服撮合:需求方保存草稿 → 提交管理员审核 → 招募广场展示;创作者查看需求 → 登录 → 联系客服接单 → 客服线下协调预算、授权、合同与交付。接单咨询不需要上传视频、报价表单或版权材料,咨询不代表已接单或成交。
+
+详情保留需求说明、预算、数量、交付要求、授权意向、截止时间及最多6张参考图;作者从“我的发布”进入管理。用户端取消“我的投稿”、视频投稿、审片和选稿入口。后台日常只保留招募审核,旧记录移到“运行维护 → 历史投稿记录”,不删除已有数据。
+
+新投稿及选稿接口已停用:`POST /api/marketplace/recruits/{id}/submissions`、`POST /api/marketplace/submissions/{id}/selection` 对已登录调用返回410,`detail.code=MARKETPLACE_SUBMISSIONS_DISABLED`,不修改资产、不创建投稿和审片任务;接口文档不再展示这两个旧入口。详情的旧字段 `can_submit` 固定为false,`can_contact` 表示当前登录创作者可联系开放需求。旧记录读取、撤回和私密文件权限保留兼容,不恢复线上投稿流程。
+
+客服沿用“数字资产平台运营 → 客服配置”中的真实二维码、微信及服务时间,弹窗提供招募编号、标题、预算、当前链接的一键复制。无客服配置返回503;关闭、到期、未审核或封禁需求不接受创作者新咨询。本文下方的历史投稿、审片、选稿说明均以本节为准。
+
+只需重启后端并刷新前端页面,无数据库迁移或历史数据清理。不影响作品发布、作品试看和原项目业务。
+
+## 当前作品试看规则(2026-10-21)
+
+本节替代下文历史版本中关于普通作品转码、免费价格、预览时长及双重审核的说明。市场 Worker 现随后端自动启停,异常退出自动恢复,不需另开终端。
+
+- 发布方式可选择免费(价格为0)或付费。上传、保存草稿不创建水印任务。免费公开播放完整时长水印,不提供无水印原片,也不代表任意商用。
+- 提交作品时一次校验版权信息:PrintFilm 仅关联已签署授权函;其他平台填写证书编号、上传截图/照片并确认版权声明;无材料直接联系客服线下协办,不在作品流程创建登记案件。
+- 提交审核后进入 `processing`,Worker 生成保留原分辨率、原帧率的高保真烧录水印(H.264 CRF16,不保证逐像素无损;奇数尺寸仅补齐偶数)。免费和零元作品为完整时长;有标价的版权作品时长不超过 `min(15秒, 原片时长*30%)`,编码为封装取整预留少量余量。公众播放不回退无水印原片。
+- 水印包含 PRINTFILM、作者名字和「侵权必究」,上下两处烧入画面。不会为普通作品额外生成完整审片或封面;封面由用户上传。
+- 生成成功自动进入 `pending`;管理员查看原片、公众试看及版权材料,一次审核,作者再上架。失败最多自动尝试配置次数,终止后显示 `preview_failed`,作者可点击重试生成并提交。
+- 新增独立表 `marketplace_work_previews`;启动 API/Worker 时通过现有独立 metadata 创建新表,不修改原业务表或现有列。按作品和原片去重,同片修改标题/价格金额复用试看;替换视频创建新任务。结果更新须符合当前作品版本、媒体、付费及提交状态。
+- Worker 单进程串行执行,作品试看使用120秒租约、20秒心跳,进程重启可恢复。每次尝试使用独立 OSS 对象,过期任务不能覆盖新结果。不得启动多个 Worker 来追求并发;当前建议保持一个。
+- 公开媒体接口对付费作品只签发独立试看对象,缺失或失败时拒绝播放,不回退原片和旧版 `Asset.preview_key`。免费转付费先撤下、生成试看并重新审核;已签发原片链接仍最多存活5分钟,已被保存的原片无法收回。
+- 旧版已上架付费作品没有该试看记录时,从公开列表及公开播放中排除。作者需从“我的发布 → 查看与管理”重新提交,生成试看、审核通过后再上架;不自动处理历史文件、不替作者重新上架。
+- 后台“运行维护 → 作品试看任务”查看任务;作品记录可分别打开原片与公众试看。任务数据不包含公开原片下载接口。
+
+部署本次更新只需重启后端(前端开发服务刷新即可)。后端自动启动市场 Worker 及其看门狗,停止或热重载时先取消媒体任务;异常退出后约2秒自动拉起。无OSS配置时空闲等待,不影响原项目。原AI调度器不变。以下手动命令仅保留兼容,不是日常启动步骤:
+
+```powershell
+cd C:\code\printfilm\backend
+.\.venv\Scripts\python.exe -m app.marketplace.worker
+```
+
+测试:52项下游测试通过,涵盖免费/付费、无OSS、原片权限、重复提交、失败重试、替换视频、租约恢复和版本冲突。真实 FFmpeg 配合 OSS 传输替身验证了10秒原片生成不超过3秒、60秒原片生成不超过15秒的可见水印视频。两端构建通过;这些不代表真实 OSS 上传/播放联调已通过。
+
+---
+# 下游作品与招募模块
+
+## 边界与入口
+
+新增模块位于 `backend/app/marketplace`、`frontend/src/features/marketplace`、`admin/src/features/marketplace`。原项目只增加 FastAPI 模块挂载、页面路由和条件菜单,不修改原作品表、生成、计费、任务调度、存储函数或旧接口。ReelBay 只作参考,未修改。
+
+用户端顶部和手机导航统一使用“数字资产市场”一个入口,进入后通过模块内导航访问作品广场、招募广场、发布作品、发布招募及个人业务进度。
+
+界面沿用主站的浅灰背景、白色圆角卡片、黑色文字与荧光绿主操作,复用全局颜色变量和 `Button`。广场提供页头、选中态导航、搜索/分类/价格筛选、作品卡片及真实空态;发布页按文件、介绍、授权分组,配合流程指引;工作台突出状态和记录。样式均限定在市场模块内,桌面和手机使用同一套功能。展示卡片只读取真实接口数据,不内置示例作品或虚构统计。
+
+- 用户端 `/marketplace`:作品广场。
+- 用户端 `/marketplace/recruits`:招募广场。
+- 用户端 `/marketplace/mine`:我的作品、招募、文件、版权信息及站内通知;接单通过招募详情联系客服。
+- 管理端 `/marketplace`:下游审核、登记、投诉、任务与客服配置,区别于原 `/works`。
+- API `/api/marketplace/*`、`/api/admin/marketplace/*`。
+
+模块默认关闭,关闭时业务路由不挂载、菜单隐藏、新表不初始化,不启动 Worker。`GET /api/marketplace/capabilities` 始终可用,只返回开关与配置完整性,**不代表真实 OSS 已验收**。
+
+下游使用独立 SQLAlchemy metadata,启动时创建 `marketplace_` 表,不修改或迁移原表。用户 ID 复用现有身份。PrintFilm 成片可以按项目或分集编号异步复制进市场;没有走这条路径的作品仍由用户自行上传。复制完成后的草稿不自动过审。
+
+## 本地启动与功能开关
+
+当前本机没有配置真实 OSS,也没有填写虚假凭证。OSS 在现有后台统一配置;后台保存或清除凭证后 API 自动生效,内嵌 Worker 读取现有后台配置缓存,兼容独立命令每轮同步配置。配置示例见 `backend/.env.marketplace.example`。配置可放入部署环境变量,或将需要的 `MARKETPLACE_` 配置项加入后端 `.env`,不要覆盖整份原环境文件。
+
+仅查看页面和文字草稿,可以在**启动后端的同一 PowerShell 终端**执行:
+
+```powershell
+$env:MARKETPLACE_ENABLED = 'true'
+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。
+
+无 OSS 时支持文字作品草稿和无附件需求的创建、修改、内容审核、招募公开浏览。上传、材料、媒体签名返回503,`detail.code=MARKETPLACE_STORAGE_UNAVAILABLE`,不会回退本地存储、返回 `/static`,也不会产生假就绪视频。
+
+停用时设置 `MARKETPLACE_ENABLED=false` 并重启后端,独立 Worker 一并停止。停用不会删除已经存在的新表或 OSS 对象。
+
+## 共用 OSS、独立目录与媒体进程
+
+下游直接读取后台「系统设置 → 存储 OSS」的启用状态、Endpoint、Bucket 和凭证,与原业务共用 Bucket。固定使用 `marketplace/` 目录,原业务继续使用原 `OSS_FOLDER`(默认 `kepu/`),请勿将原业务目录设置为 `marketplace/`。无需配置 `MARKETPLACE_OSS_*`,旧的同名环境变量不再生效。所有原片、封面、水印预览、版权材料、参考图、客服二维码使用 OSS 对象标识。模块不创建 Bucket,不改 ACL、CORS、生命周期及上游配置。
+
+客户端会只读检查 Bucket ACL 和 policy,公开 ACL 或匿名 Allow 策略将阻止市场文件使用。目录不是权限边界:共用 Bucket 仍须保持私有,原业务已通过对象 ACL 显式公开的文件继续遵循原上传逻辑;下游始终显式上传为 private,不调用原公开上传函数、不使用公开域名。不会自动改动现有云端权限,实际兼容性待真实 OSS 联调。RAM 权限需要包括共用 Bucket 的 GetBucketAcl/GetBucketPolicy,以及 `marketplace/*` 下文件读取、上传、multipart 初始化/分片/完成/取消权限。没有 Bucket policy 时允许 `NoSuchBucketPolicy`;元数据检查权限不足时失败关闭。部署方需配置文件保留、备份、日志及未完成 multipart 的兜底生命周期。
+
+浏览器播放器通过已鉴权的接口取得短时 GET 链接,不接收 OSS 密钥。默认有效期300秒;下架、撤回后不再签发新链接,旧链接最长5分钟后过期。播放、Range 和二维码图片访问应在真实 Bucket 上验收。原片和证据仅作者或管理员可申请访问,需求方只能获得水印审片。
+
+市场 Worker 已随后端自动启动,不需另开终端。仅在确需独立运行时使用兼容命令:
+
+```powershell
+cd C:\code\printfilm\backend
+.\.venv\Scripts\python.exe -m app.marketplace.worker
+```
+
+Worker 随 API 自动启动和停止,由市场独立看门狗恢复,不接入原 TaskRun、AI 计费或原调度器。通过 PostgreSQL 事务级咨询锁保证多个后端进程或兼容命令之间总媒体并发为1。默认单并发,任务持久化、SKIP LOCKED领取、90秒租约和20秒心跳;最多自动尝试3次,失败可通过作者工作台重试。多进程使用同一租约规则,首版建议只部署一个 Worker。生产需用进程管理器托管并监控失败任务。
+
+视频默认最大500MB、最长30分钟,支持MP4/MOV/WebM。8MB分片转发到OSS,会话24小时,重复同一分片和重复完成保持幂等。重新选择同一文件可以恢复已成功的分片,上传中可取消;取消未获云端确认时显示错误并保留恢复信息。完成后校验OSS真实大小,Worker校验文件内容、指纹和媒体信息。
+
+FFmpeg 在系统临时目录的 `printfilm-marketplace-cache/job-*` 内处理付费试看和平台投放 HLS。版权咨询试看最多 15 秒且不超过原片 30%,保持源分辨率和帧率并烧录水印;平台投放播放版本保持源分辨率,优先无重编码分段。免费作品不生成试看或默认封面,封面由作者上传。临时文件只作缓存,上传到私有 OSS 成功后才标记就绪,任务结束和超时清理。
+
+## 业务操作顺序
+
+### 单视频与短剧
+
+1. 作者上传单视频或创建短剧系列,保存草稿只保存资料,不要求授权材料,也不创建试看任务。
+2. 单视频提交审核时选择免费、联系客服购买版权或平台投放收益;短剧逐集填写收费类型、价格和权属信息。平台投放还必须已有后台默认分成或单项分成。
+3. PrintFilm 生成只关联当前有效授权函;其他平台填写证书编号、证书截图/照片并勾选版权纠纷声明;没有材料只能联系客服协办,不创建新登记案件。
+4. 后端校验媒体、封面、权属和收费信息后,付费内容由同一个市场 Worker 生成试看;管理员在一个审核入口同时检查内容与版权,结果只有待审核、已通过或已驳回。
+5. 审核通过且版本就绪后作者上架。修改视频、权属、收费类型或价格会创建新版本并重新审核;已购买旧版本继续使用旧播放资产。
+
+单视频保留一条视频一张封面;短剧系列要求至少一集、集数连续且每集视频/封面/材料/试看就绪。分集可以手动上传,也可以明确选择本人漫剧项目中已生成的分集导入,导入复制并保存来源快照,不修改原漫剧。
+
+### 权属与客服协办
+
+作品和版权信息只提交一次、管理员只审核一次。不要向用户展示基础核验、完整核验、私密核验或自行办理登记案件。授权函或证书材料修改会使当前版本重新进入待审核;证书编号本身不代表平台保证无侵权。客服协办不自动通过,服务费或登记机构费用按线下通知处理。
+### 招募与客服接单
+
+需求保存草稿、提交审核,通过后公开;最多6张参考图。创作者浏览需求后先联系平台客服,由客服协调合作,不在线上传视频、报价或选稿。
+
+联系客服时提供业务编号、标题、预算和页面链接;具体价格、版权约定、合同及交付在线下确认。未配置真实客服时明确提示不可用,关闭或到期后停止创作者新接单咨询。
+
+历史投稿不删除,原私密权限继续生效;曾有投稿的旧需求继续锁定预算、数量、授权、规格、说明和截止条件,重大变更关闭后重新发布。新需求不创建投稿记录。
+
+### 客服、投诉与原片交付
+
+管理员上传真实二维码、等媒体处理后保存客服配置。没有真实配置时显示不可用,不使用社区微信代替。不创建订单、支付、在线买家下载或授权凭证;客服线下确认合同、收款、原片交付。咨询事件仅用于统计,不能视为扫码或成交证明。
+
+举报需要说明和联系方式,可在页面附带本人证明文件。管理员查看证据后可限制作品、需求、权属或投稿,再记录处理结论并通知用户。举报不自动永久封号。投诉人联系方式、证据不公开。敏感材料的读取和审核保留访问记录。下游页面隐藏原站社区入群浮标,业务咨询只使用后台维护的专用客服。
+
+## 验收与发布边界
+
+```powershell
+cd C:\code\printfilm\backend
+.\.venv\Scripts\python.exe -m pytest tests/test_marketplace.py -q
+```
+
+集成测试复用仓库的隔离测试库与事务回滚机制,OSS传输使用测试替身;测试不存在的材料不进入用户业务环境。FFmpeg 测试覆盖付费试看约束和同源分辨率播放版本,但不是云端验收。
+
+本地检查覆盖关闭开关、无OSS错误、草稿、身份权限、一次内容与权属审核、系列分集连续性和漫剧导入边界、平台分成缺失、订单权益幂等、旧版本冲突、私密试看、到期与撤回、举报限制、分片边界与幂等、媒体租约恢复。两端应运行 `npm.cmd run build`。
+
+已有市场测试覆盖单视频试看、无OSS、权限、重复提交、失败重试、替换视频、租约恢复和版本冲突;系列、平台订单/权益/账本及分成边界应继续补充接口级回归。两个前端构建及市场目录静态检查通过时,仍需使用可用 Python 环境重跑后端测试。独立浏览器使用仅测试会话内的接口替身,不写入业务数据;测试替身不构成真实上传或云端播放验收。
+
+数据库备份需使用整个业务库的 `pg_dump`,不要沿用仅导出原表的白名单;确认备份包含全部 `marketplace_` 表并演练恢复。下游OSS对象、版本和保留策略需单独纳入备份方案,数据库备份不包含OSS文件;本地尚无真实Bucket,因此未设置任何云端策略。首次启用会创建独立表,后续模型变化应为下游单独提供DDL迁移,`create_all`不会修改已有表结构。
+
+正式启用前仍须在真实共用OSS环境验收:RAM和Bucket权限、真实分片续传、断线和重启恢复、私有文件无法匿名读取、签名到期/Range播放、水印视频与材料上传、部署字体、进程守护、数据库/OSS备份和投诉流程。**本机未配置OSS,不把这些项目记为通过,也不声称可以立即上线。**
+
+
+## 来源分流与上传预览补充(2026-10-20)
+
+- 授权签署入口:`/marketplace/authorization`,个人工作台与发布作品页均有入口,权属页内也可直接签署。
+- 独立依赖安装:在 backend 目录执行 `.\.venv\Scripts\python.exe -m pip install -r requirements-marketplace.txt`。Pillow 用于服务端合成中文授权函;沿用 MARKETPLACE_WATERMARK_FONT 字体。原依赖文件和锁文件未改。
+- `marketplace_authorizations` 是新增独立表,启用模块启动时创建。签署存储全文、版本、SHA-256 摘要、姓名、时间、账号及必要访问信息;签名与完整授权函 PNG 存到私有 OSS 的 `marketplace/authorizations/`。全文与签名由服务端合成,不信任客户端合成的协议图片。未写入 OSS 不返回签署成功。
+- 授权函按账号与版本唯一,逐件权属档案只能由服务端关联本人的签署记录。重新保存材料会重置核验,模板更新须重签及重新关联。只有本人和管理员能获取短时授权函链接。
+- 协议采用数字资产市场当前范围:非独家展示、处理和客服撮合;没有自动转让、线上付款、分成或买家下载授权。ReelBay 仅参考流程,不复制它的支付或商业分成条款。
+- 选择文件后支持本地视频、图片和 PDF 预览,明确标注不代表上传成功;切换文件或离开组件释放对象 URL。上传失败仍可查看所选本地文件。已有文件、我的文件及证明材料通过本人鉴权链接预览;处理未完成显示状态,链接过期可刷新。浏览器不支持 MOV 编码时提示等待处理后的 MP4 预览。
+- 修复作者的未上架草稿预览权限:允许本人查看水印预览,其他用户和访客仍不可访问。
+- 本轮验证包括中文授权函真实渲染、完整签署/核验/上架流程、外部证明、无证明协办、越权与未就绪文件限制;浏览器通过手写签名、图片/PDF 本地预览、上传失败和 390px 手机布局检查。云端传输采用测试替身,本轮没有执行真实 OSS 签署上传、视频转码或播放验收。
+
+
+
+### Windows 媒体命令兼容修复(2026-10-21)
+
+后台覆盖配置可能把 FFmpeg 路径设为默认命令 `ffmpeg` / `ffprobe`,但程序不在 PATH。下游执行器在此情况下读取环境配置中的实际安装路径;显式自定义路径不被替换。Windows 的 Uvicorn 热重载使用 Selector 事件循环时,执行器改用可取消、有超时并负责回收子进程的线程方式,不修改原项目事件循环。`NoSuchBucketPolicy` 表示不存在额外 Bucket policy,现有私有 ACL 校验允许该情况,不是试看任务失败的原因。
+
+本轮59项市场与运行时测试通过,并对当前失败作品执行实际转码和私有 OSS 上传重试,任务完成、作品恢复待审核;没有自动通过审核或上架。
+
+
+### 试看保真调整(2026-10-21)
+
+付费作品试看取消720p缩放和固定30帧,保留源画面尺寸和帧时间,改用H.264 CRF16高保真编码与192kbps音频。仅奇数画幅补至偶数以兼容yuv420p,不拉伸或缩小。烧录水印必须重新编码,不能宣称逐像素无损;HDR、色深与色彩管理不在本轮保真验收范围。时长仍不超过15秒/原片30%。新版对象位于 marketplace/work-previews-hq/,旧低清对象不能作为新版任务的就绪结果复用。
+
+59项测试通过,真实测试确认1920x1080、24fps素材生成后尺寸与帧率保持不变。当前作品的旧试看已在原片与内容版本未变的前提下替换为高保真对象,保留审核及上架状态;原片未改动。
+
+### 管理员配置作品分类与版权购买提示(2026-10-21)
+
+后台「业务 → 数字资产平台运营 → 作品分类」配置分类名称,一行一个,按行排序。配置持久化到独立表 marketplace_category_config,初始配置为短片、广告、动画、文旅、科普、其他。新表随后端启动自动创建;管理员保存采用版本校验及事务锁,防止并发覆盖。公开接口 GET /api/marketplace/categories,管理接口 GET/PUT /api/admin/marketplace/categories。发布作品采用下拉选择、广场分类标签读取同一配置,服务端拒绝任意新分类;移除分类不改历史作品,历史编辑可保留原分类。
+
+用户页面将“授权参考价”统一改为“参考价”。作品/投稿购买咨询弹窗增加版权购买须知:使用授权不等同于版权转让,购买著作财产权须签订书面转让合同并按约定办理相关手续,可能产生办理、登记或服务等费用,页面参考价不默认包含这些费用,费用及承担方须先与客服确认。本次不新增支付、订单、自动授权或版权转让接口。
+
+### 招募公开详情与作者管理分离(2026-10-21)
+
+招募广场 /marketplace/recruits/:id 始终显示招募内容与联系客服接单入口,不因当前账号是作者/管理员而切换管理界面;编辑、提交审核及关闭在 /marketplace/recruits/:id/manage 展示,由“我的发布 → 查看与管理”或保存招募草稿后进入。本人看到管理招募链接,创作者登录后联系客服;关闭/到期停止新接单咨询。详情不请求私密投稿列表,不提供视频投稿和独立公开评论系统。
diff --git a/docs/PLACEHOLDER_BACKLOG.md b/docs/PLACEHOLDER_BACKLOG.md
index 6b726f5..6a8d186 100644
--- a/docs/PLACEHOLDER_BACKLOG.md
+++ b/docs/PLACEHOLDER_BACKLOG.md
@@ -1,13 +1,15 @@
# 占位功能与待开发清单
-> 扫描日期:2026-08-07
-> 依据:前端 `ComingSoon` / `disabled` 入口、[`PRINTFILM_UI_ROADMAP.md`](./PRINTFILM_UI_ROADMAP.md)、近期线上流水线问题。
+> 扫描日期:2026-10-23
+> 依据:前端 `ComingSoon` / `disabled` 入口、[`PRINTFILM_UI_ROADMAP.md`](./PRINTFILM_UI_ROADMAP.md)、近期线上流水线问题。
> 状态标记:`待开发` | `部分完成` | `已完成待部署` | `工程债`
---
## 1. 文档与代码入口一览
+2026-10-23:数字资产市场已扩展为单视频 + 短剧剧集 + 平台投放收益。系列/分集管理、一次内容与权属审核、订单/永久权益/收益账本/人工打款接口及市场 Worker 已接入;招募继续仅做客服撮合。真实私有 OSS、易支付回调和 App 播放端仍待配置后验收。该模块不替换原创作与历史作品入口,参见 [MARKETPLACE.md](./MARKETPLACE.md)。
+
| 区域 | 主要文件 |
|------|----------|
| 顶栏 | `frontend/src/components/layout/SiteNav.tsx` |
@@ -159,26 +161,26 @@
### Sprint A — 体验与稳定性(P0)
-1. 部署前端:帮助侧栏 + `effectiveStatus` 状态文案
-2. 流水线:项目级互斥锁 / 队列去重,避免同项目并行双任务
+1. 部署前端:帮助侧栏 + `effectiveStatus` 状态文案
+2. 流水线:项目级互斥锁 / 队列去重,避免同项目并行双任务
3. 续跑失败时保留素材,明确错误提示(勿清空分镜)
### Sprint B — 创作输入与风格(P1)
-1. **C-01** 文章链接抓取 → `source_text`
-2. **C-02** 文档上传解析
-3. **S-04 / S-05** BGM + 字幕样式最小集接入合成
+1. **C-01** 文章链接抓取 → `source_text`
+2. **C-02** 文档上传解析
+3. **S-04 / S-05** BGM + 字幕样式最小集接入合成
### Sprint C — 编辑器与资产(P1)
-1. **E-06** 本地上传替换镜头图
-2. **E-04 / E-05** 增删镜头与调序
-3. **E-03 / Y-04** 编辑器导出与历史页复制分享链接
+1. **E-06** 本地上传替换镜头图
+2. **E-04 / E-05** 增删镜头与调序
+3. **E-03 / Y-04** 编辑器导出与历史页复制分享链接
### Sprint D — 商业化(P1–P2)
-1. **P-01~P-03** 定价与额度
-2. **Y-02** 历史页额度条接真实数据
+1. **P-01~P-03** 定价与额度
+2. **Y-02** 历史页额度条接真实数据
---
diff --git a/docs/PROJECT_ARCHITECTURE.md b/docs/PROJECT_ARCHITECTURE.md
new file mode 100644
index 0000000..a08751d
--- /dev/null
+++ b/docs/PROJECT_ARCHITECTURE.md
@@ -0,0 +1,574 @@
+# PRINTFILM 项目架构与业务全流程
+
+> 基于当前仓库提交 `345495e` 的静态代码扫描,整理日期:2026-10-20。以实现为准核对 README 与 CLAUDE.md;没有启动数据库、真实 AI 调用、支付或线上环境。图中的可选分支依赖运行配置,不代表当前环境已开启。
+
+快速看图:[业务流程总图(SVG)](./images/project-business-flow.svg) · [技术架构总图(SVG)](./images/project-technical-architecture.svg)。两张总图可离线打开;下文另有 15 张 Mermaid 详图,覆盖主流程、分支、时序、状态、数据与部署。
+
+## 1. 先建立整体认识
+
+PRINTFILM 是模板驱动的 AI 影视创作平台。用户购买或自行配置的上游 AI 能力,经由项目的内容编排、资产管理、任务管理和媒体合成,变成可编辑、可重做、可下载的作品。
+
+它有两条主业务:
+
+- **短视频 / 科普(kepu)**:围绕一个 Project 和若干 Shot,按“脚本 → 素材 → 视频 → 合成”分阶段生产。
+- **漫剧(drama)**:围绕剧集项目,管理剧本、分集、角色场景道具资产和分镜,每个分镜可独立生成视频。
+
+另外有工具中心、开放 API 和独立运营后台。它们共用用户、模型网关、用量记录与钱包。架构属于**前后端分离的模块化单体**:两个独立 React 应用,连接同一个 FastAPI 服务和同一个 PostgreSQL;业务模块不是独立微服务。
+
+理解时始终区分三类对象:**业务对象**(项目、镜头、资产)、**执行对象**(TaskRun / 上游任务)、**资金对象**(UsageEvent / 钱包流水)。一段生成成功,不等于整部片完成;上游提交成功,不等于视频已落盘;任务失败,也不一定没有产生收费。
+
+## 2. 全站业务总图
+
+```mermaid
+flowchart TD
+ Visitor[访客] --> Browse[浏览模板 / 工具 / 帮助]
+ Visitor --> Auth[邮箱注册 / 登录]
+ Auth --> User[创作者]
+ User --> Balance{计费是否开启且余额充足}
+ Balance -->|未开启或足够| Choice{选择创作入口}
+ Balance -->|不足| Pay[充值下单 / 易支付]
+ Pay --> Notify[服务端验签并确认支付]
+ Notify --> Wallet[钱包入账]
+ Wallet --> Choice
+ Choice --> K[短视频:主题 + 模板]
+ Choice --> D[漫剧:大纲 / 剧本]
+ Choice --> T[工具中心:单点出图出片]
+ Choice --> A[开放 API:程序调用]
+ K --> KS[脚本 → 人工确认 → 素材 → 确认 → 视频 → 确认]
+ KS --> KC[FFmpeg 合成]
+ KC --> KW[预览 / 下载 / 发布 Work]
+ D --> DS[摘要 / 分集剧本 → 确认单集 → 资产与分镜]
+ DS --> DV[维护参考资产 → 逐镜生成 / 重做]
+ DV --> DC[浏览器拼接;编码不兼容时服务端合成]
+ DC --> DW[分集预览与下载]
+ T --> TW[工具运行记录与素材结果]
+ A --> AW[同步图片结果 / 异步视频任务查询]
+ Admin[运营管理员] --> Manage[用户 / 订单 / 财务 / 模板 / 作品 / 模型 / 任务]
+ Manage -.配置与运营.-> Choice
+ KS -.用量.-> Billing[任务级用量记录与结算]
+ DV -.用量.-> Billing
+ TW -.用量.-> Billing
+ AW -.用量.-> Billing
+```
+
+依据:`frontend/src/App.tsx`、`admin/src/App.tsx`、`backend/app/main.py`、`backend/app/api/projects.py`、`backend/app/api/drama/`、`backend/app/api/tools.py`、`backend/app/api/v1/generation.py`。
+
+## 3. 技术架构总图
+
+```mermaid
+flowchart TB
+ subgraph Clients[访问层]
+ UserWeb[用户端 React 19 / TS / Vite 8\nReact Router / React Flow / 自有 CSS / i18n]
+ AdminWeb[管理端 React / TS / Vite\nTailwind v4 / Radix 组件]
+ SDK[第三方 HTTP 客户端]
+ end
+ subgraph Edge[部署入口]
+ Nginx[Nginx:SPA 静态站点\n反代 /api /static /epay/notify]
+ end
+ subgraph API[同一个 FastAPI 进程]
+ Routes[路由与依赖注入\nJWT / API Key / admin / 对象归属校验]
+ Domain[业务服务\nkepu pipeline / drama / tools / agent]
+ Runtime[进程内 Runtime\nscheduler → executor / poller / watchdog]
+ Bill[计费服务\n估价 / 冻结 / 用量 / 结算 / 对账]
+ Gateway[模型路由与适配\nLLM / Ark 外观 / TokenFree gateway]
+ Files[storage / OSS 后台上传 / FFmpeg 子进程]
+ Inline[请求内执行 / asyncio 后台任务\n部分工具与 ephemeral 路径]
+ end
+ PG[(PostgreSQL 16\n业务 / 任务 / 财务 / 配置)]
+ Redis[(Redis 7\n进度 PubSub / 缓存\n重置密码 / OSS 去重标记)]
+ Disk[(本地 generated 媒体卷)]
+ TF[TokenFree New API\n文字 / 图片 / 视频]
+ Voice[可选配音服务\n火山 TTS / edge-tts 等能力路径]
+ OSS[可选阿里云 OSS]
+ EP[易支付 / SMTP 邮件]
+ UserWeb --> Nginx
+ AdminWeb --> Nginx
+ SDK --> Routes
+ Nginx --> Routes
+ Routes --> Domain
+ Domain --> Runtime
+ Domain --> Inline
+ Domain --> Bill
+ Runtime --> Domain
+ Inline --> Gateway
+ Domain --> Gateway
+ Gateway --> TF
+ Domain --> Voice
+ Domain --> Files
+ Routes --> EP
+ Runtime --> PG
+ Domain --> PG
+ Bill --> PG
+ Domain --> Redis
+ Files --> Redis
+ Files --> Disk
+ Files --> OSS
+```
+
+**边界解释**:AI 模型推理发生在上游;本服务做编排、适配、轮询、素材保存和合成。数据库是任务与资金的持久化事实来源。Redis 不是统一生成任务的 Celery broker;FFmpeg 是本服务调用的本地程序,不是外部转码平台。
+
+## 4. 短视频业务:实际是分阶段确认
+
+### 4.1 从创建到成片
+
+```mermaid
+flowchart TD
+ Start[创建项目:主题 / 文案 / 模板 / 比例 / 风格] --> Mode{pipeline_mode}
+ Mode -->|full| Full[动态视频模式]
+ Mode -->|image_text| Image[静图配音模式]
+ Full --> Script[generate:创建 script 阶段 TaskRun]
+ Image --> Script
+ Script --> LLM[LLM 拆镜,保存 Shots 与提示词]
+ LLM --> Review[暂停:SCRIPT_READY\n用户审核与修改分镜]
+ Review --> Continue[再次 generate:解析当前下一阶段]
+ Continue --> Assets[assets:生成缺失图片\n按音频策略补齐旁白]
+ Assets --> Review2[暂停:素材确认\n可上传图片 / 单镜重绘 / 重做音频]
+ Review2 --> CheckMode{模式与素材是否就绪}
+ CheckMode -->|full 且缺镜头视频| Videos[videos:生成缺失镜头视频]
+ Videos --> Audio{音频策略}
+ Audio -->|默认原生口播| Native[Seedance 视频自带声音]
+ Audio -->|外部配音配置| TTS[使用已有 / 生成的旁白素材]
+ Native --> Review3[暂停:VIDEO_READY\n确认镜头视频 / 可单镜重生]
+ TTS --> Review3
+ CheckMode -->|image_text| Compose[调用专用 compose 接口]
+ Review3 --> Compose
+ Compose --> FF[FFmpeg:画幅 / 音视频 / 字幕与背景音乐配置]
+ FF --> Done[DONE:final_video_url]
+ Done --> Output[预览 / 下载 / 发布到 Work]
+ Assets -->|失败或取消| Recover[保留已有素材与错误状态]
+ Videos -->|失败或取消| Recover
+ FF -->|失败| Recover
+ Recover -->|用户重试| Continue
+ Review -->|restart=true| Reset[删除已有分镜和项目素材]
+ Reset --> Script
+```
+
+**重要约束**:
+
+1. `generate` 首次仅产出脚本;之后每次执行一个计费阶段并暂停。素材齐备后,`generate` 返回“请点击合成成片”,合成走专用接口。
+2. `resolve_kepu_billing_phase()` 是下一阶段的共同判定:无 shots → script;缺图或必需音频 → assets;full 缺视频 → videos;否则 compose。恢复与估价必须遵守同一套规则。
+3. `full` 默认使用 Seedance 原生口播,不能把“所有视频都强制先 TTS”画成必经路径。`image_text` 不生成镜头视频,需要静图和旁白。
+4. 被明确标记为隐私拦截跳过的视频镜头,可以用静图完成合成;就绪不总等于“有 video_url”。
+5. 普通重试复用已有成果;`restart=true` 会删分镜与项目素材,属于重新生产。
+
+源码入口:`api/projects.py:697`(生成)、`:1065`(单镜重绘)、`:1090`(重生视频)、`:1175`(合成)、`:1201`(发布);`services/pipeline.py:396`(编排)、`:674`(脚本)、`:870`(图和音频)、`:1103`(视频)、`:1353`(合成);`services/kepu_stages.py`(就绪规则)。
+
+### 4.2 项目状态和执行状态不是同一状态机
+
+```mermaid
+stateDiagram-v2
+ [*] --> DRAFT
+ DRAFT --> SCRIPTING: 生成脚本
+ SCRIPTING --> SCRIPT_READY: 等待用户确认
+ SCRIPT_READY --> IMAGING: 继续素材阶段
+ IMAGING --> IMAGE_READY: 图片等素材完成
+ IMAGE_READY --> VIDEOING: full 模式继续
+ VIDEOING --> VIDEO_READY: 镜头视频就绪
+ VIDEO_READY --> COMPOSING: 合成
+ IMAGE_READY --> COMPOSING: image_text 且音频就绪
+ COMPOSING --> DONE
+ SCRIPTING --> FAILED
+ IMAGING --> FAILED
+ VIDEOING --> FAILED
+ COMPOSING --> FAILED
+ FAILED --> SCRIPTING: 无分镜时重试
+ FAILED --> IMAGING: 补素材
+ FAILED --> VIDEOING: 补视频
+ FAILED --> COMPOSING: 仅重合成
+ DONE --> [*]
+```
+
+这张图展示主路径。枚举还包含 AUDIOING、AUDITING、REJECTED、CANCELLED,不能仅因枚举存在就认为当前所有生成都会经过审核服务。实际恢复结合素材和下一阶段计算;前端收到的事件阶段(如 ASSETS_READY)也不必与 ProjectStatus 字符串完全相同。
+
+## 5. 漫剧业务:剧本、资产、分集、分镜
+
+### 5.1 内容生产流程
+
+```mermaid
+flowchart TD
+ P[创建 DramaProject] --> Input[输入故事 / 大纲 / 原始剧本]
+ Input --> Summary[script_summary 任务\n生成摘要与分集规划]
+ Summary --> ES[episode_script 任务\n生成 / 修改指定分集剧本]
+ ES --> Confirm[确认某一集剧本\nconfirm_from_script]
+ Confirm --> Seed[增量抽取角色 / 场景 / 道具资产\n创建对应分集及分镜]
+ Seed --> Assets[资产库编辑\n生成 / 上传图片、音色与参考音频]
+ Seed --> EP[分集工作台\n编辑 Fragment 内容、时长、参数]
+ Assets --> Ref[绑定分镜参考资产]
+ EP --> Ref
+ EP --> Plan[可选:AI 重新规划分镜\nfragment_plan]
+ Plan --> Ref
+ Ref --> Generate[选单镜 / 多镜生成\n每个 Fragment 一个 TaskRun]
+ Generate --> Link{开启尾帧衔接}
+ Link -->|否| Parallel[按用户与全站槽位并发 / 排队]
+ Link -->|是| Sequential[按镜序执行\n下一镜等待上一镜尾帧]
+ Parallel --> Up[提交上游 Seedance]
+ Sequential --> Up
+ Up --> Poll[awaiting_poll → 下载 / 尾帧 / 用量 / 结算]
+ Poll --> Version[回写分镜视频与版本\n选择有效视频版本]
+ Version --> Check{对结果满意}
+ Check -->|否| EP
+ Check -->|是| Client[下载各镜,在浏览器检查 MP4 编码兼容性]
+ Client --> Compatible{兼容}
+ Compatible -->|是| Merge[mp4cat 无损拼接为 Blob]
+ Compatible -->|否且有 episodeId| Server[后端 compose\nFFmpeg 统一编码后拼接]
+ Merge --> Export[下载本集视频]
+ Server --> Export
+ P --> Canvas[独立自由画布\n资产节点 / 编辑 / 生成 / 保存]
+ Assets <--> Canvas
+```
+
+**对象层级**:剧项目 → 分集 Episode → 分镜 Fragment → 镜内 Beat(脚本中的 `@duration` 段)。Beat 是镜内节奏描述,不是独立 TaskRun。角色/场景/道具资产在项目范围复用,通过关联表绑定到分集与分镜。
+
+**内容约束**:按 `docs/EPISODE_RULES.md`,一镜通常优先 8–20 秒、硬上限 30 秒;镜内段通常 3–12 秒,具体上游 duration 另有模型约束。开幕镜交代集号、标题与背景;画面/空镜、对白、旁白使用不同 cue,空镜不口播。最终参数还受模型预设和服务端校验约束。
+
+**确认不是纯保存**:`confirm_from_script` 会锁定项目相关状态,增量抽取资产,创建/同步指定集内容,并通过 `run_billed_ephemeral` 记录执行与计费。不能把确认动作当成无成本的前端按钮。
+
+**顺序不是纯展示顺序**:开启尾帧衔接时,分镜任务有 batch_key、batch_index 和 sequential 标记;上一镜失败会使后续依赖镜头停止,避免错误衔接。未开启时仍受并发槽位和预算限制。
+
+**两种画布要分开理解**:`/drama/projects/:projectId/canvas` 是项目自由画布;`.../episodes/:episodeId/canvas` 是分集分镜画布。两者都用到节点编辑,但前者围绕资产创作,后者围绕分集叙事顺序与镜头生产。
+
+依据:`api/drama/agents.py`、`api/drama/episodes.py:280`、`:420`、`:594`、`:852`;`services/drama/jobs.py`、`generation.py`、`fragment_plan.py`、`seed.py`、`build_fragments.py`;`frontend/src/lib/composeEpisodeVideoClient.ts:59`。
+
+### 5.2 一次漫剧视频任务的时序
+
+```mermaid
+sequenceDiagram
+ participant U as 分集前端
+ participant A as episodes API
+ participant DB as PostgreSQL
+ participant S as scheduler / executor
+ participant M as TokenFree
+ participant P as poller
+ U->>A: POST episodes/{id}/generate(fragment_ids)
+ A->>DB: 校验归属、过滤活跃镜头、写 TaskRun / batch / targets
+ A-->>U: 本地 task_ids / batch_key / 排队信息
+ S->>DB: 租约领取可执行任务并冻结估价
+ S->>M: 组装镜头内容、参考图音频与连续性参数并提交
+ M-->>S: provider_task_id
+ S->>DB: awaiting_poll / next_action_at
+ loop 到期轮询直到终态
+ P->>M: 查询 provider_task_id
+ M-->>P: 运行中 / 失败 / 成功
+ end
+ P->>DB: 认领 finalizing 收尾窗口
+ P->>M: 下载结果素材
+ P->>DB: 回写 Fragment / 用量 / TaskRun / 钱包结算
+ U->>A: GET generate_status
+ A->>DB: 聚合本集任务与分镜状态
+ A-->>U: 进度、错误、视频结果
+```
+
+## 6. 统一任务平台与例外路径
+
+### 6.1 运行时
+
+```mermaid
+flowchart LR
+ Request[API 请求] --> Create[create_task\n处理器校验 / 去重 / 估价余额检查]
+ Create --> DB[(TaskRun + steps + targets + events)]
+ DB --> Scheduler[scheduler\n扫描到期任务 / 租约领取\n全站与用户槽位]
+ Scheduler --> Executor[executor\n冻结估价 / billing_scope / handler]
+ Executor --> Sync[本地编排 / 等待完成的 handler]
+ Executor --> Async[提交上游后 awaiting_poll]
+ Async --> Poller[poller\n到期集中查询 / 并发限制]
+ Poller --> Final[素材下载与回写 / 用量 / 结算]
+ Sync --> Final
+ Final --> DB
+ Watch[watchdog 心跳检查] -.软重启循环.-> Scheduler
+ Watch -.软重启循环.-> Poller
+ Reconcile[孤儿回收 / 批次修复\n终态冻结资金对账] --> DB
+```
+
+`main.py` 启动 `start_task_runtime()`,在同一个进程中启动 scheduler、poller 和 watchdog。执行器不需要单独部署;requirements 里的 Celery 不代表运行时正在使用 Celery。
+
+`tasks/handlers.py` 的真实注册变量名是 **`TASK_HANDLERS`**(不是 CLAUDE.md 概括中的 `HANDLERS`)。五个 domain:kepu、drama、api、studio、tools。domain 是分类,不能据此推断所有任务都经过 scheduler。
+
+### 6.2 必须区分的执行方式
+
+- **持久化调度任务**:短视频流水线/单镜重做、漫剧剧本/资产/分镜任务等,通过 `create_task` 进入调度执行。
+- **请求内 ephemeral**:部分 AI 对话、确认、开放 API 生图等,请求中执行业务,TaskRun 用于留痕、上下文计费与结算。注册 `_noop_ephemeral` 不代表功能尚未实现。
+- **ephemeral deferred 视频**:开放 API / 工具视频在请求中提交上游,保存 provider_task_id 后进入等待;poller 和查询接口都具备推进结算的路径。
+- **工具生图特别路径**:`studio_tools._dispatch_tool_image()` 直接 `asyncio.create_task(execute_image_tool_run(...))`,先以 ToolRun 排队,再在后台通过 `run_billed_ephemeral` 生成和计费。源码注释“统一任务平台”不能被理解成 scheduler 已接管其调度和重启恢复。
+- **OSS 后台上传**:也是进程内 `asyncio.create_task`;Redis 存去重标记,不是一个独立持久化上传 Worker 队列。
+
+因此,“离开页面仍继续”通常成立;“所有后台任务进程重启后都自动恢复”则不能一概而论。持久化任务有孤儿回收与重入机制,临时后台协程需要单独评估恢复性。
+
+### 6.3 TaskRun 主状态
+
+```mermaid
+stateDiagram-v2
+ [*] --> pending
+ pending --> leased: scheduler 领取
+ leased --> running: 冻结成功后启动
+ leased --> failed: 预扣或启动失败
+ running --> awaiting_poll: 上游异步提交
+ running --> succeeded: 同步 handler 完成
+ running --> failed: 执行失败
+ awaiting_poll --> succeeded: 素材与计费收尾
+ awaiting_poll --> failed: 上游失败 / 超时
+ running --> pending: 中断后重新排队
+ pending --> cancelled: 取消
+ running --> cancel_requested: 取消请求
+ awaiting_poll --> cancel_requested: 取消请求
+ cancel_requested --> cancelled: 按收尾窗口规则处理
+```
+
+图为主路径,不是枚举的全部组合。`awaiting_review` 也被列为活跃态;`current_step_status`(如 submitting、polling、finalizing)是步骤状态,不能与 TaskRun.status 混用。finalizing 窗口保护下载和记账收尾,防止取消先退款、成果和用量随后落库。
+
+## 7. 工具中心与开放 API
+
+```mermaid
+flowchart TD
+ Entry{入口} -->|用户工具页| Tool[POST /api/tools/run]
+ Entry -->|外部程序| Key[Bearer JWT / API Key\n或 X-Api-Key]
+ Tool --> Type{工具类别}
+ Type -->|t2i / i2i / i2p / ecom| Local[保存 ToolRun\nlocal-id + asyncio 生图]
+ Local --> ImageBill[后台 run_billed_ephemeral\n生成、记用量、结算]
+ ImageBill --> ToolPoll[GET tools/tasks/id\n读归属 ToolRun 与结果]
+ Type -->|t2v / v2v| Deferred[请求内提交视频\nephemeral deferred]
+ Key --> Public{开放 API 类别}
+ Public -->|images/generations| Img[请求内生图并结算\n返回 URL 和本地 TaskRun ID]
+ Public -->|videos/generations 或 seedance/tasks| Deferred
+ Deferred --> UpID[返回上游 provider_task_id]
+ UpID --> Poll[后台 poller / 本人查询接口推进]
+ Poll --> Result[落用量 / 结算 / 返回视频结果]
+```
+
+**ID 语义**:本地 `TaskRun.id` 是执行/计费标识;上游 `provider_task_id` 是 AI 平台标识;工具图片另有 `local-{run_id}`。开放 API 图片返回本地 ID,视频提交返回上游 ID。排查时先确认接口的 ID 语义,不要把它们互换。
+
+**访问控制**:普通业务依赖 `get_current_user`;admin 额外检查 role;对象查询还要限制 user_id。开放 API 的查询校验 TaskRun.requested_by 与 provider_task_id 的对应关系;工具查询校验 ToolRun 归属,不能只凭一个上游任务 ID 代理查询。
+
+## 8. 充值、计费与对账
+
+### 8.1 充值链路
+
+```mermaid
+sequenceDiagram
+ participant U as 用户
+ participant A as Billing API
+ participant DB as 订单与钱包
+ participant E as 易支付
+ U->>A: 创建充值订单
+ A->>DB: 保存 Order
+ A->>E: 创建支付请求
+ E-->>U: 收银台 / 二维码
+ U->>E: 支付
+ E->>A: /epay/notify 经 Nginx 转到 API
+ A->>A: 验签、成功状态、金额核对
+ A->>DB: 锁订单并检查 paid 幂等
+ A->>DB: 订单 paid + credit_topup + WalletLedger
+ A-->>E: success
+ U->>A: 查询订单 / 钱包
+```
+
+生产对外回调使用 `/epay/notify`,由 Nginx 映射到 `/api/billing/epay/notify`。前端支付完成页面不能替代服务端回调入账。
+
+### 8.2 生成费用链路
+
+```mermaid
+flowchart TD
+ Request[生成请求] --> Switch{BILLING_ENABLED}
+ Switch -->|关闭| Skip[任务计费 skipped\n不冻结用户钱包]
+ Switch -->|开启| Estimate[估价:按任务 / 阶段 / 模型参数]
+ Estimate --> Preflight[入队检查余额\n部分路径计入尚未冻结的排队承诺]
+ Preflight -->|不足| Stop[拒绝提交 / 提示充值]
+ Preflight -->|足够| Freeze[执行前锁任务和用户\n余额转冻结 / 写 freeze 流水]
+ Freeze --> Work[执行生成]
+ Work --> Usage[记录 UsageEvent\n优先上游真实额度与用量]
+ Usage --> End[成功 / 失败 / 取消进入结算]
+ End --> Settle[settle_task\n按实多退少补、清冻结、标用量已结算]
+ Settle --> Ledger[WalletLedger + TaskRun billing_status]
+ Ledger --> Reconcile[定时修复终态但仍 frozen 的任务]
+```
+
+钱包单位是**分**,balance_fen 是可用余额,frozen_fen 是冻结金额。预扣本身会减少可用余额,结算不是简单“再扣一次全额”。
+
+优先使用 TokenFree 真实 quota/用量;缺失时走本地估算与定价逻辑,涉及汇率、价格缓存和倍率。任务成功与否不是唯一计费依据:失败或取消时,如果上游已产生有效用量,需要按实际规则结算。不要承诺“一失败就全部退款”。
+
+资金并发通过数据库行锁和任务结算幂等控制;scheduler 还会对“终态 + frozen”遗留任务补偿对账。计费默认关闭不代表上游调用免费,只表示不扣本系统用户钱包。
+
+依据:`services/billing/settlement.py`、`ephemeral.py`、`usage.py`、`pricing.py`、`newapi_bill.py`;`api/billing.py:399`;专题细则见 `docs/BILLING.md`。
+
+## 9. 核心数据关系图
+
+```mermaid
+erDiagram
+ USERS ||--o{ PROJECTS : owns
+ TEMPLATES ||--o{ PROJECTS : configures
+ PROJECTS ||--o{ SHOTS : contains
+ PROJECTS ||--o| WORKS : publishes
+ USERS ||--o{ DRAMA_PROJECTS : owns
+ DRAMA_PROJECTS ||--o| DRAMA_SCRIPTS : has
+ DRAMA_PROJECTS ||--o{ DRAMA_EPISODES : contains
+ DRAMA_PROJECTS ||--o{ DRAMA_ASSETS : owns
+ DRAMA_EPISODES ||--o{ DRAMA_EPISODE_FRAGMENTS : contains
+ DRAMA_ASSETS ||--o{ DRAMA_ASSET_EPISODES : binds
+ DRAMA_EPISODES ||--o{ DRAMA_ASSET_EPISODES : binds
+ DRAMA_EPISODE_FRAGMENTS ||--o{ DRAMA_FRAGMENT_ASSET_REFS : references
+ DRAMA_ASSETS ||--o{ DRAMA_FRAGMENT_ASSET_REFS : reused_by
+ USERS ||--o{ TASK_RUNS : requests
+ TASK_RUNS ||--o{ TASK_STEPS : contains
+ TASK_RUNS ||--o{ TASK_EVENTS : records
+ TASK_RUNS ||--o{ TASK_TARGETS : binds_business_objects
+ USERS ||--o{ USAGE_EVENTS : consumes
+ USERS ||--o{ WALLET_LEDGER : has
+ USERS ||--o{ ORDERS : pays
+ USERS ||--o{ TOOL_RUNS : runs
+ USERS ||--o{ USER_API_KEYS : authorizes
+```
+
+图表示主要业务基数,不声称图中所有逻辑连接都是数据库强外键。TaskRun 还带项目、分集、分镜、资产等上下文字段;UsageEvent 与 TaskRun 对应以支持任务结算。TaskTarget 通过类型与 ID 绑定对象,不应按一个普通单表外键理解。
+
+- `models.py`:用户、模板、短视频项目/镜头、历史 PipelineJob、作品、用量、钱包、订单、工具运行。
+- `models_drama.py`:漫剧项目、项目级单份剧本、资产、分集、分镜、资产关联。
+- `models_tasks.py`:执行、步骤、目标、事件四类表。
+- `models_settings.py`:AppSettings、SystemModelChannelRow,承载运行配置与渠道。
+- `models_api.py`:用户 API Key;`models_agent.py`:导演/提示词 Skill 定义。
+
+漫剧大量扩展信息在 `params` / `content` / `episode_content` JSON 内:任务展示状态、画布、生成参数、版本等字段不能只靠表列名理解,必须同时读服务和前端规范化逻辑。
+
+## 10. 模型配置与媒体生命周期
+
+### 10.1 配置到调用
+
+```mermaid
+flowchart LR
+ Env[环境变量 / .env 初始配置] --> Base[Settings 基础值]
+ Admin[后台设置模型 / 渠道 / Key] --> DB[(app_settings\nsystem_model_channels)]
+ DB --> Cache[model_settings\n加载缓存 / 解密 / 构造 overlay]
+ Base --> Effective[get_settings\n基础值叠加 DB overlay]
+ Cache --> Effective
+ Effective --> Router[逻辑模型路由\n能力 / 绑定 / 优先级 / 权重 / 故障切换]
+ Router --> Gate[tokenfree_gateway\n固定 TokenFree 上游边界]
+ Gate --> Text[llm_client 文字调用]
+ Gate --> Media[ark / tokenfree_image / tokenfree_video]
+ Media --> TF[TokenFree New API]
+ Text --> TF
+```
+
+开源版不是任意上游的通用代理:上游协议与 Base URL 被 TokenFree 网关约束。路由可以选择逻辑模型/渠道绑定,但不意味着可以直接换成任意厂商地址。
+
+DB overlay 优先于 env,因此“改了 .env 但模型没变”可能是后台配置覆盖。Key 加密依赖 secret_key 派生的 Fernet 密钥,备份迁移要保留相应配置。`ARK_MOCK=true` 走 mock,不验证真实模型能力。音频有独立实现与 Key/配置路径,不能把配音 Key 与图片视频 Key 混为一谈。
+
+### 10.2 媒体到用户
+
+```mermaid
+flowchart TD
+ Upstream[上游图片 / 视频结果] --> Download[下载或解码]
+ Upload[用户上传参考素材] --> Local[backend/static/generated]
+ Download --> Local
+ Local --> DB[(数据库保存 URL 与业务引用)]
+ Local --> FFmpeg[FFmpeg 本地读取 / 合成]
+ FFmpeg --> Final[本地 final.mp4 / 分集合成视频]
+ Final --> Public[通过 /static 提供访问]
+ Local --> Policy{开启 OSS 且符合上传策略}
+ Final --> Policy
+ Policy -->|是| Marker[Redis 去重标记]
+ Marker --> Background[进程内后台上传 / 必要时同步发布]
+ Background --> OSS[OSS 公网 URL]
+ OSS --> Backfill[回填相关数据库 URL]
+ Backfill --> View[前端预览 / 上游参考素材访问]
+ Public --> View
+```
+
+本地媒体卷不可随意删除:即使已有 OSS URL,FFmpeg 和恢复判定仍会用本地文件。科普流水线可跳过中间素材 OSS 发布,仅上传最终片;因此“数据库都是远程链接”与“所有素材均已备份到 OSS”都不成立。OSS 队列名称不能掩盖其进程内协程实现;补传脚本位于 `backend/scripts/backfill_oss_media.py`。
+
+## 11. 启动与部署架构
+
+```mermaid
+flowchart TB
+ Compose[Docker Compose] --> PG[postgres:16-alpine\n宿主 15432 → 容器 5432\npgdata 卷]
+ Compose --> R[redis:7-alpine\n宿主 16379 → 容器 6379\nredisdata 卷]
+ PG -->|healthy| API[api 容器 :8000\nFastAPI + Runtime + FFmpeg\ngenerated 媒体卷]
+ R -->|healthy| API
+ API -->|健康检查通过| Web[web 容器 Nginx\n宿主 :8080 → :80]
+ API -->|健康检查通过| Admin[admin-web 容器 Nginx\n宿主 :8081 → :80]
+```
+
+源码构建使用 `docker-compose.full.yml`;根 `docker-compose.yml` 使用预构建镜像;`deploy/docker-compose.yml` 主要用于中间件。不要混淆这三种入口。
+
+开发时为三个应用进程:后端 :8000、用户端 Vite :5173、管理端 Vite :5174。用户端未配置 Vite API proxy,未设 `VITE_API_BASE` 时使用当前主机 :8000;设空字符串表示同源。管理端开发配置代理 `/api` 与 `/static`。
+
+FastAPI 启动顺序:建表 → 增量 schema patch → 载入 DB 模型配置 → seed 模板 → 提权已注册 bootstrap 管理员 → seed Skill → 尝试 OSS CORS 配置 → 启动 Runtime。退出时先停 Runtime,再释放数据库连接池。
+
+数据库不是 Alembic 迁移模式:`init_db/create_all` 加 `main._apply_schema_patches()`。不要认为改 ORM 自动会改已有列。模板 seed 主要补缺,不代表每次启动覆盖后台编辑。bootstrap 管理员只提升已存在的注册用户,不自动创建账号。
+
+## 12. 前端、后台与代码阅读地图
+
+### 12.1 用户端
+
+入口是 `frontend/src/main.tsx` → `App.tsx` → 页面;请求在 `api.ts` 和 `api/`,纯业务转换在 `lib/`,可复用状态逻辑在 `hooks/`。样式是 `styles/printfilm.css` 与 pf-* 语义 class,语言资源在 `i18n/`。
+
+- `/studio/new` → `CreateProjectPage`:建立短视频项目。
+- `/studio/:id/style` → `StyleConfigPage`:风格配置。
+- `/studio/:id` → `StoryboardPage`:分镜、分阶段生成和进度。
+- `/studio/:id/editor` → `EditorPage`:编辑入口。
+- `/drama/projects/:projectId` → `ProjectWorkspacePage`:漫剧剧本/项目工作台。
+- `/drama/projects/:projectId/episodes/:episodeId` → `EpisodeEditPage`:分集与镜头生产。
+- 两种 canvas 路由分别连接项目资产画布和分集分镜画布。
+- `/tools/:toolId` → `ToolDetailPage`:单点工具;`/settings`、`/pricing` 涉及账户、API Key 和钱包相关交互。
+
+短视频前端在运行时轮询项目;后端也提供 `/projects/{id}/events` SSE,Redis/本地队列支持进度广播。**存在 SSE 接口不等于当前页面全部用 SSE**。漫剧的全局队列组件与 `lib/dramaGenQueue.ts` 负责跨页面展示/轮询,服务端任务才是执行事实来源。
+
+### 12.2 管理端
+
+`admin/src/App.tsx` 的 `RequireAdmin` 做前端入口限制;真正权限仍由后端 `get_current_admin` 校验。后台包括用户、订单、财务、短视频项目、漫剧项目/分集/分镜/资产、作品、模板、任务中心与设置。
+
+`/queues` 读取 TaskRun 平台信息,不能理解成 Celery broker 控制台。模型设置影响全部业务,模板影响新项目/分镜的默认风格和生成约束,财务聚合服务负责查看账务与上游消耗。
+
+### 12.3 推荐阅读顺序
+
+1. **入口与边界**:`backend/app/main.py`、`deps.py`、`database.py`、`frontend/src/App.tsx`。
+2. **业务对象**:`models.py`、`models_drama.py`、`models_tasks.py`,对照第 9 节图。
+3. **跑通一条短视频链路**:`api/projects.py:697` → `tasks/service.py` → `tasks/handlers.py:150` → `pipeline.py:396` → `kepu_stages.py`。
+4. **跑通一条漫剧链路**:`api/drama/agents.py` → `episodes.py:280` / `:594` → `drama/jobs.py` → `drama/generation.py` → `tasks/poller.py`。
+5. **理解钱从哪来、到哪去**:`api/billing.py` → `billing/ephemeral.py` / `settlement.py` → `usage.py` / `newapi_bill.py`。
+6. **理解真实上游与结果**:`model_settings.py` → `logical_model_router.py` → `tokenfree_gateway.py` → `ark.py` / `llm_client.py` → `storage.py`。
+7. **回到交互**:`StoryboardPage.tsx`、`EpisodeEditPage.tsx`、`lib/dramaGenQueue.ts`、`lib/composeEpisodeVideoClient.ts`、画布 Store 与 normalize helper。
+
+## 13. 实际排查问题时沿哪条线走
+
+- **点生成没反应**:浏览器请求/错误 → 对象归属和余额 → TaskRun 是否创建 → pending/next_action_at/槽位 → scheduler 心跳 → handler 注册。
+- **一直显示生成中**:区分本地 TaskRun ID 与 provider_task_id → 查看步骤 polling/finalizing → 上游状态 → 下载/本地磁盘 → 业务回写。工具图片先查 ToolRun 和后台协程路径。
+- **某集后面的镜头不执行**:先看是否尾帧串行,再看上一镜结果、尾帧和 sequential 批次状态,不要先提高并发。
+- **素材齐了仍不能下一步**:看 `kepu_stages` 音频文件存在性与静音判定、视频 privacy skip、运行中的侧任务,以及是否需要专用 compose 接口。
+- **扣费不符合预期**:TaskRun phase / 估价 / frozen → UsageEvent 的真实上游值与估算来源 → settle_task → WalletLedger;不要只看订单或前端金额。
+- **改模型不生效**:查 DB overlay、逻辑模型绑定、网关限制、缓存刷新,再查 env。
+- **能预览但合成失败**:先查本地媒体文件、FFmpeg/ffprobe 与编码/画幅;漫剧再区分浏览器 MP4 兼容性与服务端回退。
+
+## 14. 理解架构时需要保留的边界
+
+1. **Web 与后台执行耦合**:API 重启会影响同进程 Runtime 与临时协程;持久化任务有恢复设计,但不能据此宣称所有工作都可无损恢复。
+2. **水平扩容需要重新核对**:调度含数据库租约,但槽位计数、看门狗和部分状态在进程内,启动 schema patch 也有并发影响。不能简单多开 uvicorn worker 就认定实现了全局统一限流和安全扩容。
+3. **外部服务与本地磁盘共同影响成功**:上游成功后仍有下载、尾帧、FFmpeg、OSS 回填和账务收尾,不能仅以 AI 返回成功定义业务成功。
+4. **业务和资金两套状态都要收敛**:TaskRun、Project/Fragment、UsageEvent 和钱包需要对齐;finalizing 和终态冻结对账正是为跨步骤不一致提供保护。
+5. **说明文档有历史痕迹**:Celery 依赖、PipelineJob、函数注释和部分抽象命名保留旧表述。本报告把工具生图、OSS 上传、阶段暂停等按当前代码展开,后续改动应重新核对。
+
+本次交付仅新增说明文档与图稿,不修改业务逻辑。结论来自路由、服务、模型、前端与部署文件交叉核对;没有宣称真实上游、支付、OSS、所有错误分支已通过运行测试。
+
+## 15. 下游数字资产市场架构(2026-10-23)
+
+数字资产市场是挂载在同一 FastAPI 进程里的独立业务模块,不是微服务。用户端和管理端分别通过 `/api/marketplace/*`、`/api/admin/marketplace/*` 访问;仅复用账号、管理员身份和后台 OSS 配置。新增 SQLAlchemy metadata 的表都使用 `marketplace_` 前缀,不能读取或改写原 AI、计费、漫剧任务表。
+
+```mermaid
+flowchart LR
+ Author[作者 Web] --> MarketAPI[市场 API]
+ Buyer[后续 App] --> MarketAPI
+ Admin[运营后台] --> AdminAPI[市场运营 API]
+ MarketAPI --> MarketDB[(marketplace_ 表)]
+ AdminAPI --> MarketDB
+ MarketAPI --> Sign[鉴权/短时签名]
+ Sign --> OSS[(共用 OSS
+marketplace/ 前缀)]
+ MarketDB --> Worker[市场 Worker
+校验/试看/HLS]
+ Worker --> OSS
+ MarketAPI --> Pay[易支付适配器]
+ Pay --> Orders[订单/永久权益/收益账本]
+```
+
+业务对象分为单视频 `Work`、短剧 `Series` 及分集 `SeriesEpisode`。每次提交审核生成 `Publication` 快照,订单和播放权益绑定快照版本,视频、权属、收费类型或价格修改后不会覆盖旧版本。收费类型为免费原片、客服版权试看、平台投放永久解锁;作品与版权信息一次提交、一次管理员审核。短剧导入只在用户明确选择本人漫剧成片后复制到市场 OSS,并保存来源快照,原漫剧后续修改不会回写市场。
+
+市场 Worker 与原项目 Worker 分开使用任务表和租约,但由 API 自动启停和看门狗恢复。免费内容无需转码;付费客服内容生成不超过 15 秒且不超过 30% 的高保真烧录水印试看;平台投放审核通过后生成同源分辨率 HLS。播放每次重新鉴权,付费接口不返回原片对象地址。OSS、支付和 App 播放未配置时只能验证错误码和权限边界,不能把本地替身结果当作线上验收。
+
+阅读市场代码建议按以下顺序:`backend/app/marketplace/models.py`(表与版本)、`schemas.py`(请求约束)、`series.py`/`api.py`(作者流程)、`admin.py`(一次审核与运营)、`preview_worker.py`/`worker.py`(媒体任务)、`commerce.py`(订单/权益/播放)、`storage.py`(私有 OSS 适配),再看 `frontend/src/features/marketplace` 与 `admin/src/features/marketplace` 的页面接线。
\ No newline at end of file
diff --git a/docs/README.md b/docs/README.md
index 349106d..1863a0a 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -4,6 +4,10 @@ PRINTFILM(ai_movie)产品与工程文档。
| 文档 | 说明 |
|------|------|
+| [DIGITAL_ASSET_DEVELOPMENT.md](./DIGITAL_ASSET_DEVELOPMENT.md) | 数字资产市场分期:第一期 Web 广场与版权交易,第二期 App 持续收益;Word 版见同目录 docx |
+| [MARKETPLACE.md](./MARKETPLACE.md) | 单视频 + 短剧剧集数字资产市场、客服招募、版权核验、平台投放收益与私有 OSS:配置、接口、操作流程及验收边界 |
+| [LOCAL_DEVELOPMENT.md](./LOCAL_DEVELOPMENT.md) | 本机 Windows 环境、后台启停脚本、访问地址与日志位置 |
+| [PROJECT_ARCHITECTURE.md](./PROJECT_ARCHITECTURE.md) | 项目深入导读:业务流程、技术架构、任务时序、计费、数据关系、部署与源码阅读地图 |
| [STANDARDS.md](./STANDARDS.md) | **全局规范**(注释、分层、前后端、Git、发布、安全) |
| [BILLING.md](./BILLING.md) | 计费与易支付 |
| [EPISODE_RULES.md](./EPISODE_RULES.md) | **漫剧分集主规范**(开幕/拆镜/脚本/资产/Seedance/门禁/后续清单) |
@@ -25,4 +29,4 @@ PRINTFILM(ai_movie)产品与工程文档。
- 编码与协作先读 [STANDARDS.md](./STANDARDS.md);约定变更时同步更新该文。
- 新增 `ComingSoon` / `disabled` 功能入口时,同步更新 `PLACEHOLDER_BACKLOG.md`;功能上线后勾掉对应条目。
-- 现网发版记录写在本机 `docs/releases/`(不上开源仓库)。
\ No newline at end of file
+- 现网发版记录写在本机 `docs/releases/`(不上开源仓库)。
diff --git a/docs/images/digital-asset-phase1/01-work-gallery.png b/docs/images/digital-asset-phase1/01-work-gallery.png
new file mode 100644
index 0000000..b65c7b0
Binary files /dev/null and b/docs/images/digital-asset-phase1/01-work-gallery.png differ
diff --git a/docs/images/digital-asset-phase1/02-work-buyer.png b/docs/images/digital-asset-phase1/02-work-buyer.png
new file mode 100644
index 0000000..10af354
Binary files /dev/null and b/docs/images/digital-asset-phase1/02-work-buyer.png differ
diff --git a/docs/images/digital-asset-phase1/03-work-contact.png b/docs/images/digital-asset-phase1/03-work-contact.png
new file mode 100644
index 0000000..73f5559
Binary files /dev/null and b/docs/images/digital-asset-phase1/03-work-contact.png differ
diff --git a/docs/images/digital-asset-phase1/04-work-editor.png b/docs/images/digital-asset-phase1/04-work-editor.png
new file mode 100644
index 0000000..e30bafd
Binary files /dev/null and b/docs/images/digital-asset-phase1/04-work-editor.png differ
diff --git a/docs/images/digital-asset-phase1/05-work-manage.png b/docs/images/digital-asset-phase1/05-work-manage.png
new file mode 100644
index 0000000..62a5730
Binary files /dev/null and b/docs/images/digital-asset-phase1/05-work-manage.png differ
diff --git a/docs/images/digital-asset-phase1/06-authorization.png b/docs/images/digital-asset-phase1/06-authorization.png
new file mode 100644
index 0000000..da6a6b3
Binary files /dev/null and b/docs/images/digital-asset-phase1/06-authorization.png differ
diff --git a/docs/images/digital-asset-phase1/07-rights.png b/docs/images/digital-asset-phase1/07-rights.png
new file mode 100644
index 0000000..509d49c
Binary files /dev/null and b/docs/images/digital-asset-phase1/07-rights.png differ
diff --git a/docs/images/digital-asset-phase1/07b-rights-external.png b/docs/images/digital-asset-phase1/07b-rights-external.png
new file mode 100644
index 0000000..048a056
Binary files /dev/null and b/docs/images/digital-asset-phase1/07b-rights-external.png differ
diff --git a/docs/images/digital-asset-phase1/08-recruit-gallery.png b/docs/images/digital-asset-phase1/08-recruit-gallery.png
new file mode 100644
index 0000000..7d52266
Binary files /dev/null and b/docs/images/digital-asset-phase1/08-recruit-gallery.png differ
diff --git a/docs/images/digital-asset-phase1/09-recruit-detail.png b/docs/images/digital-asset-phase1/09-recruit-detail.png
new file mode 100644
index 0000000..951bc3e
Binary files /dev/null and b/docs/images/digital-asset-phase1/09-recruit-detail.png differ
diff --git a/docs/images/digital-asset-phase1/09b-recruit-visitor.png b/docs/images/digital-asset-phase1/09b-recruit-visitor.png
new file mode 100644
index 0000000..a7b77d6
Binary files /dev/null and b/docs/images/digital-asset-phase1/09b-recruit-visitor.png differ
diff --git a/docs/images/digital-asset-phase1/10-recruit-contact.png b/docs/images/digital-asset-phase1/10-recruit-contact.png
new file mode 100644
index 0000000..d0d3d1e
Binary files /dev/null and b/docs/images/digital-asset-phase1/10-recruit-contact.png differ
diff --git a/docs/images/digital-asset-phase1/11-recruit-editor.png b/docs/images/digital-asset-phase1/11-recruit-editor.png
new file mode 100644
index 0000000..6e58871
Binary files /dev/null and b/docs/images/digital-asset-phase1/11-recruit-editor.png differ
diff --git a/docs/images/digital-asset-phase1/12-recruit-manage.png b/docs/images/digital-asset-phase1/12-recruit-manage.png
new file mode 100644
index 0000000..76dfede
Binary files /dev/null and b/docs/images/digital-asset-phase1/12-recruit-manage.png differ
diff --git a/docs/images/digital-asset-phase1/13-workspace.png b/docs/images/digital-asset-phase1/13-workspace.png
new file mode 100644
index 0000000..441c924
Binary files /dev/null and b/docs/images/digital-asset-phase1/13-workspace.png differ
diff --git a/docs/images/digital-asset-phase1/14-admin-works.png b/docs/images/digital-asset-phase1/14-admin-works.png
new file mode 100644
index 0000000..e5a5d17
Binary files /dev/null and b/docs/images/digital-asset-phase1/14-admin-works.png differ
diff --git a/docs/images/digital-asset-phase1/15-admin-recruits.png b/docs/images/digital-asset-phase1/15-admin-recruits.png
new file mode 100644
index 0000000..3238c8e
Binary files /dev/null and b/docs/images/digital-asset-phase1/15-admin-recruits.png differ
diff --git a/docs/images/digital-asset-phase1/16-admin-support.png b/docs/images/digital-asset-phase1/16-admin-support.png
new file mode 100644
index 0000000..1a67683
Binary files /dev/null and b/docs/images/digital-asset-phase1/16-admin-support.png differ
diff --git a/docs/images/digital-asset-phase1/17-admin-categories.png b/docs/images/digital-asset-phase1/17-admin-categories.png
new file mode 100644
index 0000000..787768a
Binary files /dev/null and b/docs/images/digital-asset-phase1/17-admin-categories.png differ
diff --git a/docs/images/digital-asset-phase1/18-admin-maintenance.png b/docs/images/digital-asset-phase1/18-admin-maintenance.png
new file mode 100644
index 0000000..65d6a58
Binary files /dev/null and b/docs/images/digital-asset-phase1/18-admin-maintenance.png differ
diff --git a/docs/images/project-business-flow.svg b/docs/images/project-business-flow.svg
new file mode 100644
index 0000000..7c05d68
--- /dev/null
+++ b/docs/images/project-business-flow.svg
@@ -0,0 +1,83 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="1260" height="1100" viewBox="0 0 1260 1100" role="img" aria-label="PRINTFILM · 业务流程总图">
+<defs><marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10Z" fill="#6b7686"/></marker></defs>
+<style>text{font-family:"Microsoft YaHei","Noto Sans CJK SC",sans-serif;fill:#202d3d}.title{font-size:26px;font-weight:600}.sub{font-size:14px;fill:#586779}.label{font-size:16px;font-weight:600}.body{font-size:14px}.edge{fill:none;stroke:#6b7686;stroke-width:1.5;marker-end:url(#arrow)}.caption{font-size:13px;fill:#586779}</style>
+<rect width="1260" height="1100" fill="#ffffff"/>
+<text class="title" x="36" y="45">PRINTFILM · 业务流程总图</text>
+<text class="sub" x="36" y="73">从创作入口到成果交付;箭头向下为主流程,分阶段确认与串行依赖明确保留。</text>
+<path class="edge" d="M630.0 181 L630.0 205.5 L220.0 205.5 L220.0 230"/>
+<path class="edge" d="M630.0 181 L630.0 205.5 L630.0 205.5 L630.0 230"/>
+<path class="edge" d="M630.0 181 L630.0 205.5 L1040.0 205.5 L1040.0 230"/>
+<path class="edge" d="M220.0 307 L220.0 331.0 L220.0 331.0 L220.0 355"/>
+<path class="edge" d="M220.0 454 L220.0 479.5 L220.0 479.5 L220.0 505"/>
+<path class="edge" d="M220.0 604 L220.0 629.5 L220.0 629.5 L220.0 655"/>
+<text class="caption" x="226.0" y="623.5">full</text>
+<path class="edge" d="M220.0 754 L220.0 779.5 L220.0 779.5 L220.0 805"/>
+<path class="edge" d="M630.0 307 L630.0 331.0 L630.0 331.0 L630.0 355"/>
+<path class="edge" d="M630.0 454 L630.0 479.5 L630.0 479.5 L630.0 505"/>
+<path class="edge" d="M630.0 604 L630.0 629.5 L630.0 629.5 L630.0 655"/>
+<path class="edge" d="M630.0 754 L630.0 779.5 L630.0 779.5 L630.0 805"/>
+<path class="edge" d="M1040.0 307 L1040.0 331.0 L1040.0 331.0 L1040.0 355"/>
+<path class="edge" d="M1040.0 454 L1040.0 479.5 L1040.0 479.5 L1040.0 505"/>
+<path class="edge" d="M1040.0 604 L1040.0 629.5 L1040.0 629.5 L1040.0 655"/>
+<path class="edge" d="M1040.0 754 L1040.0 779.5 L1040.0 779.5 L1040.0 805"/>
+<rect x="450" y="105" width="360" height="76" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="466" y="132">注册 / 登录 / 身份校验</text>
+<text class="body" x="466" y="156">可选充值;开启计费时校验可用余额</text>
+<rect x="40" y="230" width="360" height="77" rx="5" fill="#edf4fa" stroke="#bec9d4"/>
+<text class="label" x="56" y="257">短视频 / 科普</text>
+<text class="body" x="56" y="281">主题 / 文案 + 模板 + 风格与画幅</text>
+<rect x="450" y="230" width="360" height="77" rx="5" fill="#edf4fa" stroke="#bec9d4"/>
+<text class="label" x="466" y="257">AI 漫剧</text>
+<text class="body" x="466" y="281">大纲 / 原始剧本 + 剧项目</text>
+<rect x="860" y="230" width="360" height="77" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="876" y="257">工具中心 / 开放 API</text>
+<text class="body" x="876" y="281">单点生成;不经过完整项目流水线</text>
+<rect x="40" y="355" width="360" height="99" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="56" y="382">脚本拆镜 → 人工确认</text>
+<text class="body" x="56" y="406">保存 Project / Shots</text>
+<text class="body" x="56" y="429">修改提示词、角色风格与旁白</text>
+<rect x="450" y="355" width="360" height="99" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="466" y="382">摘要 → 分集剧本 → 确认单集</text>
+<text class="body" x="466" y="406">增量提取资产、建立分集与分镜</text>
+<text class="body" x="466" y="429">角色 / 场景 / 道具 / 参考音频</text>
+<rect x="860" y="355" width="360" height="99" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="876" y="382">按入口执行</text>
+<text class="body" x="876" y="406">工具图片:ToolRun + 后台协程</text>
+<text class="body" x="876" y="429">API 图片:请求内;视频:异步提交</text>
+<rect x="40" y="505" width="360" height="99" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="56" y="532">素材阶段 → 人工确认</text>
+<text class="body" x="56" y="556">补齐分镜图片和必需旁白</text>
+<text class="body" x="56" y="579">image_text 可直接进入合成</text>
+<rect x="450" y="505" width="360" height="99" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="466" y="532">编辑分镜与绑定参考资产</text>
+<text class="body" x="466" y="556">单镜 / 多镜生成;每镜一个 TaskRun</text>
+<text class="body" x="466" y="579">自由资产画布与分集画布为不同入口</text>
+<rect x="860" y="505" width="360" height="99" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="876" y="532">结果查询与后台推进</text>
+<text class="body" x="876" y="556">图片返回 URL 或 local-id 查询</text>
+<text class="body" x="876" y="579">视频按 provider_task_id 轮询</text>
+<rect x="40" y="655" width="360" height="99" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="56" y="682">full:生成镜头视频 → 确认</text>
+<text class="body" x="56" y="706">默认 Seedance 原生口播</text>
+<text class="body" x="56" y="729">支持单镜重绘、重生与恢复</text>
+<rect x="450" y="655" width="360" height="99" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="466" y="682">排队 / 提交 / 轮询 / 下载</text>
+<text class="body" x="466" y="706">普通并发受全站与用户槽位限制</text>
+<text class="body" x="466" y="729">尾帧衔接开启:按镜序等待前镜完成</text>
+<rect x="860" y="655" width="360" height="99" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="876" y="682">素材结果与历史记录</text>
+<text class="body" x="876" y="706">ToolRun / TaskRun / UsageEvent</text>
+<text class="body" x="876" y="729">任务终态按实际用量结算</text>
+<rect x="40" y="805" width="360" height="99" rx="5" fill="#edf4fa" stroke="#bec9d4"/>
+<text class="label" x="56" y="832">专用 compose → FFmpeg 合成</text>
+<text class="body" x="56" y="856">得到 final_video_url</text>
+<text class="body" x="56" y="879">预览 / 下载 / 发布 Work</text>
+<rect x="450" y="805" width="360" height="99" rx="5" fill="#edf4fa" stroke="#bec9d4"/>
+<text class="label" x="466" y="832">分集视频拼接与下载</text>
+<text class="body" x="466" y="856">浏览器 mp4cat 优先</text>
+<text class="body" x="466" y="879">编码不兼容且有分集 ID:FFmpeg 回退</text>
+<rect x="860" y="805" width="360" height="99" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="876" y="832">共享运营与资金底座</text>
+<text class="body" x="876" y="856">模型配置 / 模板 / 任务中心</text>
+<text class="body" x="876" y="879">充值订单 / 冻结 / 用量 / 结算对账</text>
+<text class="caption" x="36" y="1076">来源:当前仓库 345495e · 2026-10-20 静态核对;完整分支、时序与源码入口见 PROJECT_ARCHITECTURE.md</text></svg>
\ No newline at end of file
diff --git a/docs/images/project-technical-architecture.svg b/docs/images/project-technical-architecture.svg
new file mode 100644
index 0000000..132d3a2
--- /dev/null
+++ b/docs/images/project-technical-architecture.svg
@@ -0,0 +1,67 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="1260" height="960" viewBox="0 0 1260 960" role="img" aria-label="PRINTFILM · 技术架构总图">
+<defs><marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10Z" fill="#6b7686"/></marker></defs>
+<style>text{font-family:"Microsoft YaHei","Noto Sans CJK SC",sans-serif;fill:#202d3d}.title{font-size:26px;font-weight:600}.sub{font-size:14px;fill:#586779}.label{font-size:16px;font-weight:600}.body{font-size:14px}.edge{fill:none;stroke:#6b7686;stroke-width:1.5;marker-end:url(#arrow)}.caption{font-size:13px;fill:#586779}</style>
+<rect width="1260" height="960" fill="#ffffff"/>
+<text class="title" x="36" y="45">PRINTFILM · 技术架构总图</text>
+<text class="sub" x="36" y="73">两个 React 应用 + 一个 FastAPI 模块化单体;业务、执行、资金三套对象相互关联。</text>
+<rect x="40" y="345" width="1180" height="300" rx="8" fill="#f4f6f8"/>
+<text class="caption" x="56" y="369">同一个 API 进程:没有单独 Celery Worker;部分生成与上传直接用后台协程</text>
+<path class="edge" d="M220.0 213 L220.0 231.5 L425.0 231.5 L425.0 250"/>
+<path class="edge" d="M630.0 213 L630.0 231.5 L425.0 231.5 L425.0 250"/>
+<path class="edge" d="M425.0 327 L425.0 351.0 L630.0 351.0 L630.0 375"/>
+<path class="edge" d="M1040.0 213 L1040.0 294.0 L630.0 294.0 L630.0 375"/>
+<path class="edge" d="M630.0 452 L630.0 476.0 L240.0 476.0 L240.0 500"/>
+<path class="edge" d="M630.0 452 L630.0 476.0 L630.0 476.0 L630.0 500"/>
+<path class="edge" d="M630.0 452 L630.0 476.0 L1020.0 476.0 L1020.0 500"/>
+<path class="edge" d="M240.0 604 L240.0 652.0 L175.0 652.0 L175.0 700"/>
+<path class="edge" d="M630.0 604 L630.0 652.0 L175.0 652.0 L175.0 700"/>
+<path class="edge" d="M240.0 604 L240.0 652.0 L480.0 652.0 L480.0 700"/>
+<path class="edge" d="M240.0 604 L240.0 652.0 L785.0 652.0 L785.0 700"/>
+<path class="edge" d="M1020.0 604 L1020.0 652.0 L1090.0 652.0 L1090.0 700"/>
+<rect x="40" y="115" width="360" height="98" rx="5" fill="#edf4fa" stroke="#bec9d4"/>
+<text class="label" x="56" y="142">用户端 frontend</text>
+<text class="body" x="56" y="166">React 19 / TypeScript / Vite 8</text>
+<text class="body" x="56" y="189">短视频 / 漫剧 / 工具 / React Flow</text>
+<rect x="450" y="115" width="360" height="98" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="466" y="142">管理端 admin</text>
+<text class="body" x="466" y="166">React / Tailwind / Radix</text>
+<text class="body" x="466" y="189">用户 / 财务 / 模型 / 模板 / 任务</text>
+<rect x="860" y="115" width="360" height="98" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="876" y="142">外部程序</text>
+<text class="body" x="876" y="166">/api/v1:图片、视频与任务查询</text>
+<text class="body" x="876" y="189">Bearer JWT / API Key / X-Api-Key</text>
+<rect x="245" y="250" width="360" height="77" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="261" y="277">Nginx 入口</text>
+<text class="body" x="261" y="301">SPA;反代 /api、/static、支付通知</text>
+<rect x="450" y="375" width="360" height="77" rx="5" fill="#edf4fa" stroke="#bec9d4"/>
+<text class="label" x="466" y="402">FastAPI 路由与权限</text>
+<text class="body" x="466" y="426">JWT / admin / 对象归属 / 输入校验</text>
+<rect x="70" y="500" width="340" height="104" rx="5" fill="#edf4fa" stroke="#bec9d4"/>
+<text class="label" x="86" y="527">领域服务</text>
+<text class="body" x="86" y="551">kepu 分阶段流水线 / drama 剧集资产</text>
+<text class="body" x="86" y="574">工具 / Skill / 模型路由 / 媒体编排</text>
+<rect x="460" y="500" width="340" height="104" rx="5" fill="#edf4fa" stroke="#bec9d4"/>
+<text class="label" x="476" y="527">进程内任务 Runtime</text>
+<text class="body" x="476" y="551">scheduler → executor / poller</text>
+<text class="body" x="476" y="574">watchdog;持久化任务与恢复</text>
+<rect x="850" y="500" width="340" height="104" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="866" y="527">计费与临时执行路径</text>
+<text class="body" x="866" y="551">估价 → 冻结 → 用量 → 结算</text>
+<text class="body" x="866" y="574">ephemeral / asyncio 后台协程</text>
+<rect x="40" y="700" width="270" height="98" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="56" y="727">PostgreSQL 16</text>
+<text class="body" x="56" y="751">业务 / TaskRun / 财务 / 配置</text>
+<text class="body" x="56" y="774">任务与资金的持久化来源</text>
+<rect x="345" y="700" width="270" height="98" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="361" y="727">Redis 7</text>
+<text class="body" x="361" y="751">进度 PubSub / 重置密码</text>
+<text class="body" x="361" y="774">缓存 / OSS 上传去重标记</text>
+<rect x="650" y="700" width="270" height="98" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="666" y="727">本地媒体 + FFmpeg</text>
+<text class="body" x="666" y="751">generated 持久卷 / 合成</text>
+<text class="body" x="666" y="774">可选 OSS 上传及 URL 回填</text>
+<rect x="955" y="700" width="270" height="98" rx="5" fill="#ffffff" stroke="#bec9d4"/>
+<text class="label" x="971" y="727">外部服务</text>
+<text class="body" x="971" y="751">TokenFree:文字 / 图 / 视频</text>
+<text class="body" x="971" y="774">可选配音 / 易支付 / SMTP</text>
+<text class="caption" x="36" y="936">来源:当前仓库 345495e · 2026-10-20 静态核对;完整分支、时序与源码入口见 PROJECT_ARCHITECTURE.md</text></svg>
\ No newline at end of file
diff --git "a/docs/\346\225\260\345\255\227\350\265\204\344\272\247\345\270\202\345\234\272\345\210\206\346\234\237\345\274\200\345\217\221\350\257\264\346\230\216.docx" "b/docs/\346\225\260\345\255\227\350\265\204\344\272\247\345\270\202\345\234\272\345\210\206\346\234\237\345\274\200\345\217\221\350\257\264\346\230\216.docx"
new file mode 100644
index 0000000..4fe9b3f
Binary files /dev/null and "b/docs/\346\225\260\345\255\227\350\265\204\344\272\247\345\270\202\345\234\272\345\210\206\346\234\237\345\274\200\345\217\221\350\257\264\346\230\216.docx" differ
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 6034ac8..1932829 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,4 +1,5 @@
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'
+import { lazy, Suspense } from 'react'
import DialogHost from './components/ui/DialogHost'
import BillingAlertHost from './components/billing/BillingAlertHost'
import { DramaGenQueuePanel } from './components/drama/DramaGenQueuePanel'
@@ -30,10 +31,14 @@ import EpisodeStoryboardPage from './pages/drama/episodeCanvas/EpisodeStoryboard
import './styles/printfilm.css'
import './App.css'
+// 下游页面按需加载,不将媒体业务接入原工作台。
+const Marketplace = lazy(() => import('./features/marketplace/Marketplace'))
+
export default function App() {
return (
<BrowserRouter>
<Routes>
+ <Route path="/marketplace/*" element={<Suspense fallback={<p>正在加载作品与招募…</p>}><Marketplace /></Suspense>} />
<Route path="/" element={<HomePage />} />
<Route path="/method" element={<MethodPage />} />
<Route path="/auth" element={<AuthPage />} />
diff --git a/frontend/src/components/layout/SiteNav.tsx b/frontend/src/components/layout/SiteNav.tsx
index 52efdfa..b89fbfe 100644
--- a/frontend/src/components/layout/SiteNav.tsx
+++ b/frontend/src/components/layout/SiteNav.tsx
@@ -11,6 +11,7 @@ import { USER_UPDATED_EVENT } from '../../lib/userEvents'
import { GITHUB_REPO_URL } from '../../lib/siteLinks'
import { useI18n } from '../../i18n'
import LanguageSwitch from './LanguageSwitch'
+import { useMarketplace } from '../../features/marketplace/hooks'
export type NavActive = 'home' | 'drama' | 'kepu' | 'tools' | 'assets' | 'pricing' | 'templates' | 'studio' | 'history'
@@ -38,6 +39,7 @@ function normalizeActive(active: NavActive | undefined, pathname: string): NavAc
}
export default function SiteNav({ active }: Props) {
+ const { capabilities: marketplace } = useMarketplace()
const nav = useNavigate()
const location = useLocation()
const { t } = useI18n()
@@ -83,6 +85,7 @@ export default function SiteNav({ active }: Props) {
const centerLinks = (
<>
+ {marketplace?.enabled && <NavLink to="/marketplace">数字资产市场</NavLink>}
<NavLink to="/" end className={() => isActive('home')}>
{t('nav.workbench')}
</NavLink>
diff --git a/frontend/src/features/marketplace/AssetPicker.tsx b/frontend/src/features/marketplace/AssetPicker.tsx
new file mode 100644
index 0000000..50fa37b
--- /dev/null
+++ b/frontend/src/features/marketplace/AssetPicker.tsx
@@ -0,0 +1,58 @@
+import { useEffect, useRef, useState } from 'react'
+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 }) {
+ /* 仅上传并绑定当前文件,不加载历史文件列表。 */
+
+
+ const [error, setError] = useState('')
+ const [progress, setProgress] = useState<number | null>(null)
+
+ const [pending, setPending] = useState<number | null>(null)
+ const controller = useRef<AbortController | null>(null)
+ const [localFile, setLocalFile] = useState<File | null>(null)
+ const [localAssetId, setLocalAssetId] = useState<number | null>(null)
+ const [localUrl, setLocalUrl] = useState('')
+ useEffect(() => {
+ if (!localFile) { setLocalUrl(''); return }
+ const url = URL.createObjectURL(localFile); setLocalUrl(url)
+ return () => URL.revokeObjectURL(url)
+ }, [localFile])
+ useEffect(() => {
+ if (!pending) return
+ let active = true
+ // 独立查询处理状态,离开页面即清理轮询。
+ const check = async () => {
+ try {
+ const asset = await request<{ status: string; error: string }>(`/assets/${pending}`)
+ if (!active) return
+ if (asset.status === 'ready') { onChange(pending); setPending(null); setProgress(null) }
+ if (asset.status === 'failed') { setError(asset.error); setPending(null); setProgress(null) }
+ } catch (e) { if (active) { setError((e as Error).message); setPending(null); setProgress(null) } }
+ }
+ const interval = window.setInterval(check, 5000); void check()
+ return () => { active = false; window.clearInterval(interval) }
+ }, [pending, onChange])
+ // 续传失败保留会话,重新选择同一文件即可继续。
+ async function choose(file?: File) {
+ if (!file) return
+ const allowed = kind === 'video' ? /\.(mp4|mov|webm)$/i : kind === 'image' ? /\.(png|jpe?g|webp)$/i : /\.(pdf|png|jpe?g|webp)$/i
+ if (!allowed.test(file.name) || file.size > (kind === 'video' ? 500 : 20) * 1024 * 1024 || file.size === 0) { setError('文件类型或大小不符合要求'); return }
+ setLocalFile(file); setLocalAssetId(null)
+ setError(''); setProgress(0)
+ controller.current = new AbortController()
+ try { const id = await upload(file, kind, setProgress, controller.current.signal); setLocalAssetId(id); onChange(id); setPending(id) }
+ catch (e) { setError((e as Error).message); setProgress(null) }
+ 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>}
+ {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>
+}
+
diff --git a/frontend/src/features/marketplace/AssetPreview.tsx b/frontend/src/features/marketplace/AssetPreview.tsx
new file mode 100644
index 0000000..fc88d4d
--- /dev/null
+++ b/frontend/src/features/marketplace/AssetPreview.tsx
@@ -0,0 +1,53 @@
+import { useEffect, useState } from 'react'
+import { labels, media, request, type Row } from './api'
+
+// 浏览器原生预览;不把文件或签名链接保存到 localStorage。
+export function PreviewContent({ url, filename, video = false, onReady, onFailure }: { url: string; filename: string; video?: boolean; onReady?: () => void; onFailure?: () => void }) {
+ const [failed, setFailed] = useState(false)
+ function fail() { setFailed(true); onFailure?.() }
+ const pdf = /\.pdf$/i.test(filename)
+ return <div className="pf-market-file-preview">
+ {video ? <video src={url} controls preload="metadata" onLoadedMetadata={onReady} onError={fail} /> : pdf ? <><iframe src={url} title={`PDF预览:${filename}`} onLoad={onReady} /><a href={url} target="_blank" rel="noreferrer">在新窗口查看 PDF</a></> : <img src={url} alt={filename} onLoad={onReady} onError={fail} />}
+ {failed && <p role="alert">{video ? '视频加载失败,请刷新链接重试;也可能是浏览器不支持该视频编码。' : '文件加载失败,请刷新链接重试,或检查文件服务的访问配置。'}</p>}
+ </div>
+}
+
+export default function AssetPreview({ id, onReady, hideMedia = false }: { id: number; onReady?: (id: number) => void; hideMedia?: boolean }) {
+ const [asset, setAsset] = useState<Row | null>(null)
+ const [url, setUrl] = useState('')
+ const [error, setError] = useState('')
+ const [revision, setRevision] = useState(0)
+ useEffect(() => {
+ let active = true; setUrl(''); setError(''); setAsset(null)
+ async function load() {
+ try {
+ const item = await request<Row>(`/assets/${id}`)
+ if (!active) return
+ setAsset(item)
+ if (item.status === 'ready') {
+ const link = await media('asset', id, 'original')
+ if (active) {
+ setUrl(link)
+ // A signed cloud URL means the uploaded asset is ready to replace
+ // the local object URL. Notify the picker immediately so the
+ // temporary local preview closes without another manual click.
+ onReady?.(id)
+ }
+ }
+ } catch (e) { if (active) setError((e as Error).message) }
+ }
+ void load()
+ return () => { active = false }
+ }, [id, revision])
+ useEffect(() => {
+ if (!asset || !['uploading', 'processing'].includes(asset.status || '')) return
+ const timer = window.setTimeout(() => setRevision(value => value + 1), 2000)
+ return () => 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>}
+ {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>
+ </div>
+}
diff --git a/frontend/src/features/marketplace/AuthorizationPanel.tsx b/frontend/src/features/marketplace/AuthorizationPanel.tsx
new file mode 100644
index 0000000..5ded1ad
--- /dev/null
+++ b/frontend/src/features/marketplace/AuthorizationPanel.tsx
@@ -0,0 +1,51 @@
+import { useEffect, useRef, useState, type PointerEvent } from 'react'
+import { request, date } from './api'
+import { PreviewContent } from './AssetPreview'
+
+type Signed = { id: number; signer_name: string; created_at: string; template_version: string }
+type Status = { template: { version: string; title: string; body: string }; current: Signed | null }
+type Point = [number, number]
+
+// 账号签署一次,服务端合成全文存档;每件视频仍需独立核验。
+export default function AuthorizationPanel({ onSigned }: { onSigned?: () => void }) {
+ const [status, setStatus] = useState<Status | null>(null)
+ const [error, setError] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [url, setUrl] = useState('')
+ const [name, setName] = useState('')
+ const [accepted, setAccepted] = useState(false)
+ const canvas = useRef<HTMLCanvasElement>(null)
+ const strokes = useRef<Point[][]>([])
+ const drawing = useRef<number | null>(null)
+ useEffect(() => { let active = true; request<Status>('/authorization').then(value => { if (active) setStatus(value) }).catch(e => { if (active) setError(e.message) }); return () => { active = false } }, [])
+ function point(e: PointerEvent<HTMLCanvasElement>): Point {
+ const rect = e.currentTarget.getBoundingClientRect()
+ return [Math.max(0, Math.min(800, (e.clientX - rect.left) / rect.width * 800)), Math.max(0, Math.min(240, (e.clientY - rect.top) / rect.height * 240))]
+ }
+ function move(e: PointerEvent<HTMLCanvasElement>) {
+ if (drawing.current !== e.pointerId) return
+ const stroke = strokes.current[strokes.current.length - 1]
+ if (stroke.length >= 1000) return
+ const next = point(e), previous = stroke[stroke.length - 1]
+ const ctx = canvas.current?.getContext('2d')
+ if (ctx) { ctx.lineWidth = 3; ctx.lineCap = 'round'; ctx.beginPath(); ctx.moveTo(...previous); ctx.lineTo(...next); ctx.stroke() }
+ stroke.push(next)
+ }
+ async function sign() {
+ if (!status) return
+ const valid = strokes.current.filter(stroke => stroke.length >= 2)
+ if (valid.flat().length < 12) { setError('请在签名区完整手写签名,再确认签署。'); return }
+ setBusy(true); setError('')
+ try {
+ const result = await request<Signed>('/authorization', 'POST', { template_version: status.template.version, signer_name: name, accepted_terms: accepted, strokes: strokes.current.filter(stroke => stroke.length >= 2) })
+ setStatus({ ...status, current: result }); onSigned?.()
+ } catch (e) { setError((e as Error).message) }
+ finally { setBusy(false) }
+ }
+ return <section className="pf-market-authorization"><h2>PrintFilm 作品授权函</h2><p>按现行条款签署一次,本账号后续 PrintFilm 作品可引用。无需另外填写创作记录或上传版权证明。</p>
+ {status && <><details><summary>阅读完整授权函 · {status.template.version}</summary><h3>{status.template.title}</h3><div className="pf-market-letter">{status.template.body}</div></details>
+ {status.current ? <><p className="pf-market-notice">已签署:{status.current.signer_name} · {date(status.current.created_at)}。可用于当前视频的发布审核。</p><button type="button" onClick={async () => { try { setUrl((await request<{ url: string }>(`/authorizations/${status.current!.id}/letter`)).url) } catch (e) { setError((e as Error).message) } }}>查看已签授权函</button>{url && <PreviewContent key={url} url={url} filename="授权函.png" />}</> : <div className="pf-market-fields"><label>签署人真实姓名<input value={name} minLength={2} maxLength={80} onChange={e => setName(e.target.value)} disabled={busy} /></label><p>在下方手写签名(支持鼠标或触屏)</p><canvas aria-label="手写签名区域" ref={canvas} width={800} height={240} className="pf-market-signature" onPointerDown={e => { if (busy || drawing.current !== null || strokes.current.length >= 40) return; e.currentTarget.setPointerCapture(e.pointerId); drawing.current = e.pointerId; strokes.current.push([point(e)]) }} onPointerMove={move} onPointerUp={e => { if (drawing.current === e.pointerId) drawing.current = null }} onPointerCancel={() => { drawing.current = null }} /><button type="button" disabled={busy} onClick={() => { strokes.current = []; canvas.current?.getContext('2d')?.clearRect(0, 0, 800, 240) }}>清除签名</button><label><input type="checkbox" checked={accepted} disabled={busy} onChange={e => setAccepted(e.target.checked)} />我已阅读完整授权函,有权签署并确认以上声明;具体交易仍需另行订立合同。</label><button type="button" disabled={busy || !accepted || name.trim().length < 2} onClick={sign}>{busy ? '正在存档…' : '确认签署并保存授权函'}</button></div>}</>}
+ {!status && !error && <p role="status">正在读取授权条款…</p>}{error && <p role="alert">{error}</p>}
+ </section>
+}
+
diff --git a/frontend/src/features/marketplace/Detail.tsx b/frontend/src/features/marketplace/Detail.tsx
new file mode 100644
index 0000000..9129f8b
--- /dev/null
+++ b/frontend/src/features/marketplace/Detail.tsx
@@ -0,0 +1,72 @@
+import { useEffect, useState } from 'react'
+import { Link, useParams } from 'react-router-dom'
+import { date, labels, money, request, type Row } from './api'
+import { Contact, Media, NeedLogin, ReportForm } from './shared'
+import { PageHeading } from './ui'
+import WorkPublishingSteps from './WorkPublishingSteps'
+
+// 公开详情与作者管理分离,招募统一由客服协调接单。
+export default function Detail({ recruit = false, manage = false }: { recruit?: boolean; manage?: boolean }) {
+ const id = Number(useParams().id)
+ const [item, setItem] = useState<Row | null>(null)
+ const [error, setError] = useState('')
+ const [message, setMessage] = useState('')
+ const [refresh, setRefresh] = useState(0)
+ const [preview, setPreview] = useState(false)
+ useEffect(() => { let active = true; setItem(null); setError(''); request<Row>(`/${recruit ? 'recruits' : 'works'}/${id}`).then(value => { if (active) setItem(value) }).catch(e => { if (active) setError(e.message) }); return () => { active = false } }, [id, recruit, refresh])
+ // 状态操作只发意图;重复和过期版本由后端处理。
+ async function action(path: string, body?: unknown) {
+ setError(''); setMessage('')
+ try { await request(path, 'POST', body); setMessage('操作成功'); setRefresh(v => v + 1) }
+ catch (err) { setError((err as Error).message) }
+ }
+ useEffect(() => { if (!manage || item?.audit_status !== 'processing') return; const timer = window.setInterval(() => setRefresh(v => v + 1), 5000); return () => window.clearInterval(timer) }, [manage, item?.audit_status])
+ if (!item) return <p role={error ? 'alert' : 'status'}>{error || '正在加载…'}</p>
+ const privateView = manage && item.version !== undefined
+ const submitIssues = [
+ !item.asset_id ? '请先上传并保存作品视频。' : item.media_status !== 'ready' ? '作品视频尚未就绪,请检查上传状态。' : '',
+ !item.rights_complete ? '请完成并保存版权信息(PrintFilm 授权函或外部版权证明)。' : '',
+ !item.license_scope?.trim() ? '请在“编辑草稿 → 价格与授权意向”中填写“拟授权用途及限制”。' : '',
+ item.blocked ? '作品已被限制,请联系客服处理。' : '',
+ ].filter(Boolean)
+ const canSubmitWork = submitIssues.length === 0
+ async function refreshProgress() {
+ try { setItem(await request<Row>(`/works/${id}`)) } catch (e) { setError((e as Error).message) }
+ }
+ if (manage && !privateView) return <p role="alert">无权管理此记录,请从广场查看公开详情。</p>
+ // 广场详情面向浏览与购买;作者管理仅从独立管理路由进入。
+ if (!recruit && !manage) return <>
+ <PageHeading title={item.title || '作品详情'} description={`${item.author || '创作者'} · ${item.category || '其他'}`} back="/marketplace" />
+ <div className="pf-market-buyer-layout">
+ <section className="pf-market-buyer-player" aria-label="作品视频预览"><Media kind="work" id={id} purpose="preview" video /></section>
+ <aside className="pf-market-buyer-info"><span className="pf-market-badge">视频作品</span><h2>{item.title}</h2><p>创作者 · {item.author || '创作者'}</p><div className="pf-market-buyer-price"><span>{item.sale_type === 'free' || (item.price_fen === 0 && item.sale_type !== 'platform_unlock') ? '免费公开' : item.sale_type === 'platform_unlock' ? '平台解锁价' : '版权参考价'}</span><strong>{item.sale_type === 'free' || (item.price_fen === 0 && item.sale_type !== 'platform_unlock') ? '免费' : money(item.sale_type === 'platform_unlock' ? item.unlock_price_fen : item.price_fen)}</strong></div>{item.sale_type === 'copyright_contact' && <Contact kind="work" id={id} />}<small>{item.sale_type === 'free' || (item.price_fen === 0 && item.sale_type !== 'platform_unlock') ? '免费作品可看完整时长,播放原片。使用仍须遵守作者授权范围。' : item.sale_type === 'platform_unlock' ? '平台投放内容购买后永久在线播放,支付和播放接口由客户端接入。未购买只能看水印试看。' : '当前为水印试看,最多15秒、不超过原片30%。联系客服确认授权并线下购买原片。'}</small><ReportForm kind="work" id={id} /></aside>
+ </div>
+ <section className="pf-market-detail-section"><h2>作品介绍</h2><p className="pf-market-text">{item.description || '暂未填写详细介绍'}</p><h2>用途及授权意向</h2><p className="pf-market-text">{item.license_scope || '具体授权范围请联系客服确认'}</p><p>作品版权与内容已由平台人工审核,最终授权以线下协议为准。</p></section>
+ </>
+ if (recruit && !manage) return <>
+ <PageHeading title={item.title || '招募详情'} description={`${item.author || '需求发布者'} · ${item.category || '其他'} · ${date(item.created_at)}`} back="/marketplace/recruits" />
+ <div className="pf-market-detail-intro">
+ <div><span className="pf-market-category-tag">创作需求</span><p className="pf-market-text">{item.description || '暂未填写详细介绍'}</p></div>
+ <div className="pf-market-detail-price"><span>单条预算</span><strong>{money(item.budget_fen)}</strong><small>具体合作条件由客服协助线下确认</small></div>
+ </div>
+ <section className="pf-market-detail-section"><h2>需求与交付要求</h2><p>需求数量 {item.wanted_count} 条 · 截止 {date(item.deadline_at)}</p><p className="pf-market-text">{item.requirements}</p><h2>用途及授权意向</h2><p className="pf-market-text">{item.license_scope || '具体授权要求请联系客服确认'}</p>{Boolean(item.image_ids?.length) && <><h2>参考图片</h2>{item.image_ids?.map((image, index) => <Media key={image} kind="recruit" id={id} purpose={`image-${index}`} />)}</>}</section>
+ <section className="pf-market-detail-section"><h2>{item.is_owner ? '你的招募需求' : '想接下这个项目?'}</h2>
+ {item.is_owner ? <p>创作者通过平台客服沟通接单,客服协助你确认合作。<Link to={`/marketplace/recruits/${id}/manage`}>管理我的招募</Link></p> : !item.is_open ? <p className="pf-market-notice">该招募已结束,暂不接受新的接单咨询。</p> : <><p>先联系平台客服,提供这条招募的编号及你的创作意向。客服将协助确认需求、预算、授权和交付安排。</p><div className="pf-market-actions"><NeedLogin><Contact kind="recruit" id={id} /></NeedLogin></div><small>具体合作在线下协商,联系客服不代表已接单或成交。</small></>}
+ </section>
+ <ReportForm kind="recruit" id={id} />
+ </>
+ return <><PageHeading title={item.title || (recruit ? '招募详情' : '作品详情')} description={`${item.author || '创作者'} · ${item.category || '其他'} · ${date(item.created_at)}`} back={manage ? '/marketplace/mine' : recruit ? '/marketplace/recruits' : '/marketplace'} /><div className="pf-market-detail-intro"><div><span className="pf-market-category-tag">{recruit ? '创作需求' : '视频作品'}</span><p className="pf-market-text">{item.description || '暂未填写详细介绍'}</p></div><div className="pf-market-detail-price"><span>{recruit ? '单条预算' : '参考价'}</span><strong>{money(recruit ? item.budget_fen : item.price_fen)}</strong><small>具体合作与授权由客服线下确认</small></div></div><section className="pf-market-detail-section"><h2>用途及授权意向</h2><p className="pf-market-text">{item.license_scope || '请联系发布者补充授权说明'}</p>
+ {recruit ? <><p>征集 {item.wanted_count} 条 · 截止 {date(item.deadline_at)}</p><p className="pf-market-text">{item.requirements}</p>{item.image_ids?.map((_, index) => <Media key={index} kind="recruit" id={id} purpose={`image-${index}`} />)}</> : <><p>作品版权与内容统一审核,最终授权以线下协议为准。</p><button type="button" disabled={privateView && (!item.asset_id || item.media_status !== 'ready')} onClick={() => setPreview(!preview)}>播放/关闭作品预览</button>{preview && <Media kind={privateView ? 'asset' : 'work'} id={privateView ? item.asset_id ?? 0 : id} purpose="preview" video />}</>}
+ </section>{privateView && !recruit && <WorkPublishingSteps item={item} onUpdated={() => { void refreshProgress() }} />}{privateView && <section><h2>发布管理</h2>{!recruit && submitIssues.length > 0 && <div className="pf-market-notice" role="status"><strong>提交前还需完成:</strong><ul>{submitIssues.map(issue => <li key={issue}>{issue}</li>)}</ul><Link to={`/marketplace/works/${id}/edit`}>前往编辑草稿</Link></div>}{item.audit_status === 'processing' && <p role="status">正在生成水印播放文件,完成后自动进入待审核。可以关闭页面,稍后在我的发布中查看。</p>}<p>{recruit ? '招募审核' : '作品审核'}:{labels[item.audit_status ?? ''] || item.audit_status} · {recruit ? labels[item.state ?? ''] : item.listed ? '已上架' : '未上架'}{item.blocked ? ' · 已封禁' : ''}</p><p>{item.reason}</p><div className="pf-market-actions"><Link to={`/marketplace/${recruit ? 'recruits' : 'works'}/${id}/edit`}>编辑草稿</Link><button type="button" disabled={!recruit && (!canSubmitWork || item.audit_status === 'processing' || item.audit_status === 'pending' || item.audit_status === 'approved')} onClick={() => action(`/${recruit ? 'recruits' : 'works'}/${id}/submit`, { version: item.version })}>{item.audit_status === 'processing' ? '正在生成试看视频…' : item.audit_status === 'preview_failed' ? '重试生成试看并提交' : '提交审核'}</button>{recruit ? <button type="button" onClick={() => { if (window.confirm('关闭后将退出招募广场,停止新的接单咨询。确认关闭?')) void action(`/recruits/${id}/close`) }}>关闭招募</button> : <><button type="button" disabled={!item.listed && (!canSubmitWork || item.audit_status !== 'approved')} onClick={() => action(`/works/${id}/listing?listed=${!item.listed}`, { version: item.version })}>{item.listed ? '下架' : '上架'}</button>{item.asset_id && <Link to={`/marketplace/assets/${item.asset_id}/rights?source=${item.source || 'external'}&return=${encodeURIComponent(`/marketplace/works/${id}/edit`)}`}>确认版权信息</Link>}</>}</div></section>}
+ {recruit && <p className="pf-market-notice">审核通过后,创作者通过平台客服沟通接单。具体合作、合同与交付在线下确认。</p>}
+ <div className="pf-market-actions"><Contact kind={recruit ? 'recruit' : 'work'} id={id} label={recruit ? '联系客服' : undefined} /><ReportForm kind={recruit ? 'recruit' : 'work'} id={id} /></div>
+ {message && <p role="status">{message}</p>}{error && <p role="alert">{error}</p>}</>
+}
+
+
+
+
+
+
+
+
diff --git a/frontend/src/features/marketplace/FromPrintfilm.tsx b/frontend/src/features/marketplace/FromPrintfilm.tsx
new file mode 100644
index 0000000..d57ad8e
--- /dev/null
+++ b/frontend/src/features/marketplace/FromPrintfilm.tsx
@@ -0,0 +1,118 @@
+import { useEffect, useMemo, useState } from 'react'
+import { useNavigate, useSearchParams } from 'react-router-dom'
+import { request, type Handoff } from './api'
+import { PageHeading } from './ui'
+import Button from '../../components/ui/Button'
+
+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 }[] }
+type SeriesOption = { id: number; title: string }
+
+// 从 PrintFilm 已生成成片发起转存。页面只提交编号,不提交视频地址。
+export default function FromPrintfilm() {
+ const navigate = useNavigate()
+ const [search] = useSearchParams()
+ const focusProject = Number(search.get('project') || 0)
+ const focusDrama = Number(search.get('drama') || 0)
+ const focusEpisode = Number(search.get('episode') || 0)
+ const [projects, setProjects] = useState<ProjectSource[]>([])
+ 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 [seriesId, setSeriesId] = useState('')
+ const [error, setError] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [loading, setLoading] = useState(true)
+
+ useEffect(() => {
+ let stop = false
+ Promise.all([
+ request<{ projects: ProjectSource[]; dramas: DramaSource[] }>('/printfilm/sources'),
+ request<{ items: SeriesOption[] }>('/mine/series?page_size=100'),
+ ]).then(([sources, mine]) => {
+ if (stop) return
+ setProjects(sources.projects)
+ setDramas(sources.dramas)
+ setSeries(mine.items)
+ setDramaId(current => current || (sources.dramas[0] ? String(sources.dramas[0].id) : ''))
+ }).catch(err => { if (!stop) setError((err as Error).message) }).finally(() => { if (!stop) setLoading(false) })
+ return () => { stop = true }
+ }, [])
+
+ const drama = dramas.find(item => String(item.id) === dramaId)
+ const focused = useMemo(() => projects.find(item => item.id === focusProject), [projects, focusProject])
+
+ async function publishWork(project: ProjectSource) {
+ setBusy(true); setError('')
+ try {
+ const handoff = await request<Handoff>('/works/from-printfilm', 'POST', {
+ project_id: project.id,
+ idempotency_key: `kepu-${project.id}-${project.updated_at}`,
+ })
+ navigate(`/marketplace/works/${handoff.work_id}/edit?handoff=${handoff.id}`)
+ } catch (err) { setError((err as Error).message) } finally { setBusy(false) }
+ }
+
+ async function ensureSeries(title: string) {
+ if (seriesId && seriesId !== 'new') return Number(seriesId)
+ const created = await request<SeriesOption>('/series', 'POST', {
+ title: title || '未命名短剧', category: '其他', sale_type: 'copyright_contact', copyright_price_fen: 0, description: '',
+ })
+ return created.id
+ }
+
+ async function addProject(project: ProjectSource) {
+ setBusy(true); setError('')
+ try {
+ const target = await ensureSeries(project.title)
+ const result = await request<{ handoffs: Handoff[] }>(`/series/${target}/episodes/import-printfilm`, 'POST', {
+ project_id: project.id,
+ idempotency_key: `kepu-${project.id}-${project.updated_at}`,
+ })
+ const handoff = result.handoffs[0]
+ navigate(`/marketplace/series/${target}/edit${handoff ? `?handoff=${handoff.id}` : ''}`)
+ } 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" />
+ {error && <p role="alert">{error}</p>}
+ <section className="pf-market-form">
+ <h2>科普成片</h2>
+ <p className="pf-market-notice">发布为单视频会生成一条草稿。添加到短剧系列会把这部成片作为一集,不改已经发布过的旧版本。</p>
+ <label>添加到短剧<select value={seriesId} onChange={event => setSeriesId(event.target.value)}><option value="">选择已有短剧,或新建</option><option value="new">新建短剧</option>{series.map(item => <option key={item.id} value={item.id}>{item.title}</option>)}</select></label>
+ {projects.length === 0 ? <p>还没有可发布的科普成片。</p> : projects.map(project => <article key={project.id} className="pf-market-handoff">
+ <strong>{project.title}{project.id === focusProject ? ' · 当前成片' : ''}</strong>
+ <div>
+ <Button variant="lime" type="button" disabled={busy} onClick={() => void publishWork(project)}>发布为单视频</Button>
+ <button type="button" disabled={busy || !seriesId} onClick={() => void addProject(project)}>添加到短剧系列</button>
+ </div>
+ </article>)}
+ {focused ? null : focusProject ? <p role="status">这部成片还没有生成完成,暂时不能发布。</p> : null}
+ </section>
+ <section className="pf-market-form">
+ <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>
+ </>}
+ </section>
+ </>
+}
diff --git a/frontend/src/features/marketplace/Gallery.tsx b/frontend/src/features/marketplace/Gallery.tsx
new file mode 100644
index 0000000..b563849
--- /dev/null
+++ b/frontend/src/features/marketplace/Gallery.tsx
@@ -0,0 +1,75 @@
+import { useCategories } from './useCategories'
+import { useEffect, useRef, useState, type FormEvent } from 'react'
+import { Link } from 'react-router-dom'
+import { ArrowUpRight, Check, Clock3, Film, Handshake, Play, Search, ShieldCheck, SlidersHorizontal, UsersRound } from 'lucide-react'
+import Button from '../../components/ui/Button'
+import { date, money, request, type Listing, type Row } from './api'
+import { Media, Pager } from './shared'
+import { EmptyState } from './ui'
+
+function plazaHref(item: Row, recruits: boolean) {
+ if (item.kind === 'series') return `/marketplace/series/${item.id}`
+ return `/marketplace/${recruits ? 'recruits' : 'works'}/${item.id}`
+}
+
+function freeListing(item: Row) {
+ return item.sale_type === 'free' || (item.price_fen === 0 && item.sale_type !== 'platform_unlock')
+}
+
+// 公开广场只展示后端过滤通过的单视频、短剧或需求。
+export default function Gallery({ recruits = false }: { recruits?: boolean }) {
+ /* listing 服务端分页;query 已提交筛选;page 当前页;revision 手动重试;formRef 重置筛选。 */
+ const { names: categories, error: categoryError } = useCategories()
+ const [listing, setListing] = useState<Listing | null>(null)
+ const [query, setQuery] = useState('')
+ const [page, setPage] = useState(1)
+ const [error, setError] = useState('')
+ const [loading, setLoading] = useState(true)
+ const [revision, setRevision] = useState(0)
+ const [category, setCategory] = useState('')
+ const formRef = useRef<HTMLFormElement>(null)
+ useEffect(() => {
+ let active = true; setLoading(true); setError('')
+ request<Listing>(`/${recruits ? 'recruits' : 'works'}?${query}&page=${page}`).then(value => { if (active) setListing(value) }).catch(e => { if (active) setError(e.message) }).finally(() => { if (active) setLoading(false) })
+ return () => { active = false }
+ }, [query, page, recruits, revision])
+ // 筛选提交后从第一页查询,金额转分并由服务端执行分页。
+ function search(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault(); const form = new FormData(e.currentTarget); const params = new URLSearchParams()
+ for (const key of ['q', 'category', 'sort']) if (form.get(key)) params.set(key, String(form.get(key)))
+ for (const [field, key] of [['min', recruits ? 'min_budget' : 'min_price'], ['max', recruits ? 'max_budget' : 'max_price']]) if (form.get(field)) params.set(key, String(Math.round(Number(form.get(field)) * 100)))
+ setPage(1); setQuery(params.toString()); setRevision(value => value + 1)
+ }
+ // 清空条件并恢复最新目录。
+ function reset() { setCategory(''); formRef.current?.reset(); setPage(1); setQuery(''); setRevision(value => value + 1) }
+ const filtered = [...new URLSearchParams(query)].some(([key, value]) => key !== 'sort' && value)
+ return <div className={recruits ? 'pf-market-recruit-gallery' : 'pf-market-discover'}>
+ {!recruits && <header className="pf-discover-heading"><div><span className="pf-market-kicker">创作有价值 · 灵感有回响</span><h1>发现好作品</h1><p>从一帧灵感,到下一次合作。探索创作者的数字影像。</p></div><Button variant="dark" to="/marketplace/works/new" icon>发布作品<ArrowUpRight size={17} /></Button></header>}
+ <section className={`pf-market-hero${recruits ? ' is-recruit' : ''}`}>
+ <div className="pf-market-hero-copy"><span className="pf-market-kicker">{recruits ? '连接需求与创作' : '让创作,继续发生'}</span><h1>{recruits ? <>发现值得投入的<br /><em>下一个创作机会。</em></> : <>让好作品,<br /><em>遇见新的价值。</em></>}</h1><p>{recruits ? '寻找适合你的创作需求,先联系平台客服,开启下一次合作。' : '发现创作者的优质视频,也让你的作品被更多人看见。'}</p><Button variant="dark" to={recruits ? '/marketplace/recruits/new' : '/marketplace/works/new'} icon>{recruits ? '发布我的需求' : '发布我的作品'}<ArrowUpRight size={17} /></Button></div>
+ <div className="pf-market-hero-art" aria-hidden="true"><div className="pf-market-art-orbit" /><div className="pf-market-art-frame pf-market-art-back"><Film size={27} /><span>CREATIVE ASSETS</span></div><div className="pf-market-art-frame pf-market-art-front"><div className="pf-market-art-top"><span>PRINTFILM</span><span>● ● ●</span></div><div className="pf-market-art-play">{recruits ? <UsersRound size={40} strokeWidth={1.3} /> : <Play size={38} strokeWidth={1.2} />}</div><div className="pf-market-art-bottom"><span>{recruits ? '灵感与需求,在此相遇' : '每一份创作,都有新的可能'}</span><ArrowUpRight size={20} /></div></div><span className="pf-market-art-label"><Handshake size={16} />连接创作与合作</span></div>
+ </section>
+ <div className="pf-market-principles"><span><ShieldCheck size={17} />{recruits ? '招募需求人工审核' : '权属材料人工核验'}</span><span><Film size={17} />{recruits ? '意向接单 · 先联系客服' : '按收费类型播放 · 先看再聊'}</span><span><Handshake size={17} />客服撮合 · 线下确认授权</span></div>
+ <section className="pf-market-catalog" aria-labelledby="market-catalog-title">
+ <header className="pf-market-section-heading"><div><h2 id="market-catalog-title">{recruits ? '招募广场' : '作品广场'}</h2><p>{recruits ? '明确的创作需求,寻找合适的合作伙伴。' : '浏览已审核上架的单视频和短剧。'}</p></div><span className="pf-market-count">{loading ? '正在更新' : `${listing?.meta.total ?? 0} ${recruits ? '个需求' : '件作品'}`}</span></header>
+ {!recruits && categoryError && <p role="alert">{categoryError}</p>}<form ref={formRef} className="pf-market-filter-panel" onSubmit={search}>
+ {!recruits && <div className="pf-discover-categories" aria-label="作品分类">{['', ...categories].map(value => <button key={value} type="button" aria-pressed={category === value} onClick={() => { setCategory(value); const params = new URLSearchParams(query); if (value) params.set('category', value); else params.delete('category'); setQuery(params.toString()); setPage(1) }}>{value || '全部作品'}</button>)}</div>}
+ <div className="pf-market-filter-top"><label className="pf-market-search"><Search size={18} aria-hidden /><input name="q" aria-label="关键词" placeholder={recruits ? '搜索需求名称,发现创作机会' : '搜索作品名称,发现更多创意'} maxLength={100} /></label><select name="sort" aria-label="排序"><option value="latest">最新发布</option>{recruits ? <option value="deadline">最近截止</option> : <><option value="price_asc">价格从低到高</option><option value="price_desc">价格从高到低</option></>}</select><Button variant="dark" type="submit"><Search size={16} />搜索</Button></div>
+ <div className="pf-market-filter-bottom"><span className="pf-market-filter-label"><SlidersHorizontal size={15} />筛选</span><label className="pf-market-category"><span>分类</span><input name="category" value={category} onChange={e => setCategory(e.target.value)} aria-label="分类" placeholder="全部分类" list="market-categories" maxLength={60} /><datalist id="market-categories">{(recruits ? ['短片', '广告', '动画', '文旅', '科普', '其他'] : categories).map(value => <option key={value} value={value} />)}</datalist></label><div className="pf-market-price-filter"><span>{recruits ? '单条预算' : '参考价'}</span><input name="min" type="number" min="0" step="0.01" aria-label="最低价" placeholder="¥ 最低" /><span>—</span><input name="max" type="number" min="0" step="0.01" aria-label="最高价" placeholder="¥ 最高" /></div><button type="button" className="pf-market-reset" onClick={reset}>重置筛选</button></div>
+ </form>
+ {error ? <div className="pf-market-error" role="alert"><p>{error}</p><Button variant="outline" onClick={() => setRevision(value => value + 1)}>重新加载</Button></div> : loading ? <div className="pf-market-grid" role="status" aria-label="正在加载作品与需求">{[0, 1, 2].map(item => <div key={item} className="pf-market-skeleton"><div /><span /><span /></div>)}</div> : listing?.items.length ? <div className={`pf-market-grid${recruits ? ' is-recruits' : ''}`}>{listing.items.map(item => {
+ const href = plazaHref(item, recruits)
+ const free = !recruits && freeListing(item)
+ return <article className="pf-market-item" key={`${item.kind || (recruits ? 'recruit' : 'work')}-${item.id}`}>
+ {recruits ? <div className="pf-market-recruit-top"><span className="pf-market-item-icon"><UsersRound size={23} strokeWidth={1.5} /></span><span className="pf-market-badge">征集中</span></div> : <div className="pf-market-item-cover">{item.kind === 'series' && !item.cover_asset_id ? <span className="pf-market-series-mark"><Film size={36} /></span> : <Media kind={item.kind === 'series' ? 'series' : 'work'} id={item.id} purpose="cover" />}<Link className="pf-market-cover-play" to={href} aria-label={`查看作品:${item.title}`}><Play size={16} /></Link></div>}
+ <div className="pf-market-item-body"><span className="pf-market-category-tag">{item.kind === 'series' ? '短剧' : item.category}</span><h3><Link to={href}>{item.title}</Link></h3><p className="pf-market-author"><span>{item.author?.slice(0, 1) || '创'}</span>{item.author || '创作者'}</p>{recruits && <p className="pf-market-item-description">{item.description}</p>}<div className="pf-market-item-price"><div><strong>{free ? '免费' : item.kind === 'series' && item.sale_type === 'platform_unlock' ? '按集解锁' : money(recruits ? item.budget_fen : item.sale_type === 'platform_unlock' ? item.unlock_price_fen : item.price_fen)}</strong>{item.kind === 'series' ? <span>{item.episode_count || 0} 集{item.free_episode_count ? ` · 前${item.free_episode_count}集免费` : ''}</span> : (!free) && <span>{recruits ? '/ 条预算' : item.sale_type === 'platform_unlock' ? '解锁价' : '参考价'}</span>}</div><Link to={href} aria-label={`查看${item.title}详情`}><ArrowUpRight size={20} /></Link></div><div className="pf-market-item-foot">{recruits ? <><Clock3 size={13} /><span>截止 {date(item.deadline_at)} · 征集 {item.wanted_count} 条</span></> : <><Check size={14} /><span>{item.kind === 'series' ? '短剧 · 权属材料已核验' : '权属材料已核验'}</span></>}</div></div>
+ </article>})}</div> : <EmptyState title={filtered ? '暂时没有找到匹配结果' : recruits ? '下一个好项目,从你的需求开始' : '好作品,值得被更多人看见'} description={filtered ? '试试其他关键词,或放宽分类和价格范围。' : recruits ? '当前暂无公开招募。写下你的创作需求,寻找合适的创作者。' : '当前暂无已审核上架的作品。上传你的作品,完成核验后开启展示。'} action={filtered ? undefined : recruits ? '发布第一份需求' : '发布我的作品'} to={recruits ? '/marketplace/recruits/new' : '/marketplace/works/new'}>{filtered && <Button variant="outline" onClick={reset}>清空筛选条件</Button>}</EmptyState>}
+ <Pager listing={listing} page={page} change={setPage} />
+ </section>
+ <p className="pf-market-footnote">{recruits ? '接单请先联系平台客服,具体合作在线下协商。' : '所有标价均为人民币参考价。'}最终价格、授权范围与交付方式由客服协助在线下确认。</p>
+ </div>
+}
+
+
+
+
diff --git a/frontend/src/features/marketplace/Marketplace.tsx b/frontend/src/features/marketplace/Marketplace.tsx
new file mode 100644
index 0000000..56f0bb6
--- /dev/null
+++ b/frontend/src/features/marketplace/Marketplace.tsx
@@ -0,0 +1,38 @@
+import { Navigate, Route, Routes } from 'react-router-dom'
+import AppShell from '../../components/layout/AppShell'
+import { Gate, NeedLogin } from './shared'
+import Gallery from './Gallery'
+import WorkEditor from './WorkEditor'
+import RecruitEditor from './RecruitEditor'
+import Detail from './Detail'
+import Workspace from './Workspace'
+import RightsPage from './RightsPage'
+import AuthorizationPanel from './AuthorizationPanel'
+import SeriesEditor from './SeriesEditor'
+import SeriesDetail from './SeriesDetail'
+import FromPrintfilm from './FromPrintfilm'
+import './marketplace.css'
+
+// 独立下游路由壳;不替换原 studio、作品或个人设置页面。
+export default function Marketplace() {
+ return <div className="pf-market-shell"><AppShell wide><div className="pf-market"><Gate><Routes>
+ <Route index element={<Gallery key="works" />} /><Route path="recruits" element={<Gallery key="recruits" recruits />} />
+ <Route path="series" element={<Navigate to="/marketplace" replace />} />
+ <Route path="series/new" element={<Navigate to="/marketplace/works/new?type=series" replace />} />
+ <Route path="series/:id" element={<SeriesDetail />} />
+ <Route path="works/new" element={<NeedLogin><WorkEditor /></NeedLogin>} />
+ <Route path="from-printfilm" element={<NeedLogin><FromPrintfilm /></NeedLogin>} />
+ <Route path="series/:id/edit" element={<NeedLogin><SeriesEditor /></NeedLogin>} />
+ <Route path="works/:id/edit" element={<NeedLogin><WorkEditor /></NeedLogin>} />
+ <Route path="works/:id" element={<Detail />} />
+ <Route path="works/:id/manage" element={<NeedLogin><Detail manage /></NeedLogin>} />
+ <Route path="recruits/new" element={<NeedLogin><RecruitEditor /></NeedLogin>} />
+ <Route path="recruits/:id/edit" element={<NeedLogin><RecruitEditor /></NeedLogin>} />
+ <Route path="recruits/:id" element={<Detail recruit />} />
+ <Route path="recruits/:id/manage" element={<NeedLogin><Detail recruit manage /></NeedLogin>} />
+ <Route path="mine" element={<NeedLogin><Workspace /></NeedLogin>} />
+ <Route path="authorization" element={<NeedLogin><AuthorizationPanel /></NeedLogin>} />
+ <Route path="assets/:id/rights" element={<NeedLogin><RightsPage /></NeedLogin>} />
+ <Route path="*" element={<p>页面不存在</p>} />
+ </Routes></Gate></div></AppShell></div>
+}
diff --git a/frontend/src/features/marketplace/RecruitEditor.tsx b/frontend/src/features/marketplace/RecruitEditor.tsx
new file mode 100644
index 0000000..c347442
--- /dev/null
+++ b/frontend/src/features/marketplace/RecruitEditor.tsx
@@ -0,0 +1,34 @@
+import { useEffect, useState, type FormEvent } from 'react'
+import { useNavigate, useParams } from 'react-router-dom'
+import AssetPicker from './AssetPicker'
+import { localDate, request, type Row } from './api'
+import { Save } from 'lucide-react'
+import Button from '../../components/ui/Button'
+import { FormSection, PageHeading, PublishGuide } from './ui'
+
+// 需求可以无附件发布;实质条款锁定由服务端最终校验。
+export default function RecruitEditor() {
+ /* item 需求快照;images 参考图;error/busy 保存反馈。 */
+ const { id } = useParams(); const navigate = useNavigate()
+ const [item, setItem] = useState<Row | null>(null)
+ const [images, setImages] = useState<number[]>([])
+ const [error, setError] = useState('')
+ const [busy, setBusy] = useState(false)
+ useEffect(() => { if (id) request<Row>(`/recruits/${id}`).then(value => { setItem(value); setImages(value.image_ids ?? []) }).catch(e => setError(e.message)) }, [id])
+ // 保留服务器版本,避免旧表单覆盖最新需求及审核结果。
+ async function save(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault(); const form = new FormData(e.currentTarget); setBusy(true); setError('')
+ const body = { title: form.get('title'), description: form.get('description'), category: form.get('category'), budget_fen: Math.round(Number(form.get('budget')) * 100), wanted_count: Number(form.get('count')), requirements: form.get('requirements'), license_scope: form.get('license_scope'), deadline_at: new Date(String(form.get('deadline'))).toISOString(), image_ids: images, ...(id ? { version: item?.version } : {}) }
+ try { const result = await request<Row>(id ? `/recruits/${id}` : '/recruits', id ? 'PUT' : 'POST', body); navigate(`/marketplace/recruits/${result.id}/manage`) }
+ catch (err) { setError((err as Error).message) }
+ finally { setBusy(false) }
+ }
+ if (id && !item) return <p role={error ? 'alert' : 'status'}>{error || '正在加载…'}</p>
+ return <><PageHeading title={id ? '编辑招募' : '发布招募'} description="描述创作需求,审核通过后由平台客服协助对接创作者。" back="/marketplace/recruits" />{Boolean(item?.submission_count) && <p className="pf-market-notice">这条需求存在旧版合作记录,为保留原约定,预算、用途、授权、交付和截止条件不可修改。重大变更请关闭后重新发布。</p>}<div className="pf-market-editor-layout"><form className="pf-market-form" onSubmit={save}>
+ <FormSection step="01" title="描述创作需求" description="写清你想做什么,以及作品将用于什么场景。"><label>标题<input name="title" required maxLength={200} placeholder="例如:为城市文旅项目征集一支短片" defaultValue={item?.title} /></label><label>需求说明<textarea name="description" required maxLength={5000} placeholder="介绍项目背景、目标受众与期待的内容方向" defaultValue={item?.description} /></label><label>分类<input name="category" required maxLength={60} defaultValue={item?.category ?? '其他'} /></label></FormSection>
+ <FormSection step="02" title="预算与交付" description="填写预期预算及交付要求,具体合作条件由客服协助线下确认。"><div className="pf-market-field-row"><label>单条预算(元)<input name="budget" required type="number" min="0.01" max="1000000" step="0.01" placeholder="0.00" defaultValue={item?.budget_fen ? item.budget_fen / 100 : ''} /></label><label>征集数量<input name="count" required type="number" min="1" max="10000" defaultValue={item?.wanted_count ?? 1} /></label></div><label>规格和交付要求(时长、画幅、用途等)<textarea name="requirements" required maxLength={3000} placeholder="例如:30秒、16:9横屏、用于品牌宣传;写清交付格式" defaultValue={item?.requirements} /></label><label>授权意向及限制<textarea name="license_scope" required maxLength={3000} placeholder="说明使用渠道、期限、地域与是否需要独家授权" defaultValue={item?.license_scope} /></label><label>截止时间(本机时区)<input name="deadline" type="datetime-local" required defaultValue={localDate(item?.deadline_at ?? new Date(Date.now() + 30 * 86400000).toISOString())} /></label></FormSection>
+ <FormSection step="03" title="参考与确认" description="参考图片为选填,最多6张;没有附件也可以发布需求。">{images.length > 0 && <div className="pf-market-actions">{images.map(image => <button key={image} type="button" onClick={() => setImages(images.filter(i => i !== image))}>移除参考图 #{image}</button>)}</div>}{images.length < 6 && <AssetPicker kind="image" value={null} onChange={image => setImages(previous => [...new Set([...previous, image])].slice(0, 6))} title="添加参考图片(最多6张)" />}<label><input type="checkbox" required />确认有权展示参考材料,理解发布需求及客服咨询不代表已达成合作。</label></FormSection>
+ {error && <p role="alert">{error}</p>}<div className="pf-market-form-actions"><p>先保存草稿,确认内容后提交审核。审核通过后展示在招募广场。</p><Button type="submit" variant="lime" disabled={busy} icon><Save size={17} />{busy ? '保存中…' : '保存草稿'}</Button></div>
+ </form><PublishGuide recruit /></div></>
+}
+
diff --git a/frontend/src/features/marketplace/RightsPage.tsx b/frontend/src/features/marketplace/RightsPage.tsx
new file mode 100644
index 0000000..4d2f7e2
--- /dev/null
+++ b/frontend/src/features/marketplace/RightsPage.tsx
@@ -0,0 +1,57 @@
+import { useEffect, useState, type FormEvent } from 'react'
+import { Link, useParams, useSearchParams } from 'react-router-dom'
+import { request, type RightsRecord } from './api'
+import AssetPicker from './AssetPicker'
+import { PageHeading } from './ui'
+import AuthorizationPanel from './AuthorizationPanel'
+import AssetPreview from './AssetPreview'
+
+function safeDraftReturn(value: string | null) {
+ if (!value) return ''
+ try {
+ const url = new URL(value, window.location.origin)
+ if (url.origin !== window.location.origin || !url.pathname.startsWith('/marketplace/')) return ''
+ return url.pathname + url.search
+ } catch { return '' }
+}
+
+export default function RightsPage({ assetId: suppliedAssetId, sourceHint, embedded = false, onUpdated }: { assetId?: number; sourceHint?: string; embedded?: boolean; onUpdated?: () => void } = {}) {
+ const params = useParams()
+ const assetId = suppliedAssetId ?? Number(params.id)
+ const [query] = useSearchParams()
+ const backTo = safeDraftReturn(query.get('return'))
+ const [source, setSource] = useState('external')
+ const [item, setItem] = useState<RightsRecord | null>(null)
+ const [certificate, setCertificate] = useState<number | null>(null)
+ const [message, setMessage] = useState('')
+ const [error, setError] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [revision, setRevision] = useState(0)
+ const [support, setSupport] = useState<{ available: boolean; name?: string; wechat?: string; hours?: string; message?: string } | null>(null)
+ const [qr, setQr] = useState('')
+ useEffect(() => { let active = true; request<RightsRecord>(`/assets/${assetId}/rights`).then(value => { if (active) { setItem(value); setSource(sourceHint ?? (value.id ? value.details?.source : query.get('source')) ?? 'external'); setCertificate(value.certificate_asset_id ?? null) } }).catch(e => { if (active) setError(e.message) }); return () => { active = false } }, [assetId, revision, query, sourceHint])
+ async function save(e?: FormEvent<HTMLFormElement>) {
+ e?.preventDefault()
+ const form = e ? new FormData(e.currentTarget) : null
+ setBusy(true); setError(''); setMessage('')
+ try {
+ await request(`/assets/${assetId}/rights`, 'PUT', { version: item?.version ?? 0, details: { source, certificate_number: String(form?.get('certificate_number') ?? ''), dispute_ack: form?.get('dispute_ack') === 'on' }, certificate_asset_id: source === 'printfilm' ? null : certificate, evidence_ids: [] })
+ setMessage(backTo ? '版权信息已保存。可以返回草稿页继续编辑或提交审核。' : '版权信息已保存。请回到草稿页点击“提交审核”。')
+ setRevision(v => v + 1); onUpdated?.()
+ } catch (err) { setError((err as Error).message) } finally { setBusy(false) }
+ }
+ async function contact() {
+ setError('')
+ try {
+ const result = await request<{ available: boolean; name?: string; wechat?: string; hours?: string; message?: string }>('/support')
+ setSupport(result)
+ if (result.available) setQr((await request<{ url: string }>('/media/support/1/qr')).url)
+ } catch (err) { setError((err as Error).message) }
+ }
+ if (!item) return <p role={error ? 'alert' : 'status'}>{error || '正在加载版权信息…'}</p>
+ return <>{!embedded && <PageHeading title="确认版权信息" description="版权信息与作品一次提交、一次审核。标有必填的项目需要填完才能保存。" back={backTo || '/marketplace/mine'} backLabel={backTo ? '返回继续编辑草稿' : '返回我的发布'} />}
+ <section className="pf-market-rights-route"><h2>确认作品来源</h2><label>视频生成平台<select value={source} disabled={Boolean(sourceHint)} onChange={e => setSource(e.target.value)}><option value="printfilm">PrintFilm 生成</option><option value="external">其他平台生成</option></select></label><details><summary>查看当前视频</summary><AssetPreview id={assetId} /></details>
+ {source === 'printfilm' ? <><AuthorizationPanel onSigned={() => { void save() }} /><button type="button" disabled={busy} onClick={() => { void save() }}>使用已签署授权函</button><p>只需签署授权函,无需版权证书或其他证明文件。</p></> : <><form className="pf-market-form" key={`${item.version}-${source}`} onSubmit={save}><label>版权证书编号<span className="pf-req-mark">必填</span><input name="certificate_number" required maxLength={200} defaultValue={item.details?.certificate_number} /></label><AssetPicker kind="image" required value={certificate} onChange={setCertificate} title="版权证书截图或照片" /><label><input type="checkbox" name="dispute_ack" required defaultChecked={Boolean(item.details?.dispute_ack)} />我确认材料真实,版权纠纷与平台无关<span className="pf-req-mark">必填</span></label><button type="submit" disabled={busy || !certificate}>保存版权信息</button></form><p>没有版权材料?联系客服线下协办,补齐材料后再提交作品。</p><button type="button" onClick={() => { void contact() }}>联系客服协办</button></>}
+ {support && <div role="status">{support.available ? <><p>{support.name} · {support.wechat} · {support.hours}</p>{qr && <img src={qr} alt="平台客服二维码" style={{ maxWidth: 240 }} />}</> : <p>{support.message || '客服暂不可用'}</p>}</div>}
+ </section>{message && <p role="status">{message}{backTo && <> <Link to={backTo}>返回继续编辑草稿</Link></>}</p>}{error && <p role="alert">{error}</p>}</>
+}
diff --git a/frontend/src/features/marketplace/SeriesDetail.tsx b/frontend/src/features/marketplace/SeriesDetail.tsx
new file mode 100644
index 0000000..d4663e3
--- /dev/null
+++ b/frontend/src/features/marketplace/SeriesDetail.tsx
@@ -0,0 +1,90 @@
+import { useEffect, useState } from 'react'
+import { Link, useParams } from 'react-router-dom'
+import { Lock } from 'lucide-react'
+import { Contact, Media, NeedLogin } from './shared'
+import { money, request, type Row } from './api'
+import { PageHeading } from './ui'
+
+type Episode = Row & { episode_no: number; description?: string }
+type Series = { id: number; title: string; description?: string; category?: string; sale_type: string; copyright_price_fen?: number; free_episode_count?: number; episodes: Episode[] }
+
+const pageSize = 15
+
+function rememberKey(id: number) {
+ return `pf-market-series-${id}`
+}
+
+function isFreeEpisode(series: Series, episodeNo: number) {
+ return series.sale_type === 'free' || episodeNo <= (series.free_episode_count || 0)
+}
+
+// 短剧详情只挂一个播放器,选集格切换当前集。
+export default function SeriesDetail() {
+ const id = Number(useParams().id)
+ const [item, setItem] = useState<Series | null>(null)
+ const [error, setError] = useState('')
+ const [current, setCurrent] = useState(1)
+ const [range, setRange] = useState(0)
+ const [autoPlay, setAutoPlay] = useState(false)
+ useEffect(() => {
+ let active = true
+ request<Series>(`/series/${id}`).then(value => {
+ if (!active) return
+ const saved = Number(sessionStorage.getItem(rememberKey(id)) || 1)
+ const episode = value.episodes.find(entry => entry.episode_no === saved) || value.episodes[0]
+ setItem(value)
+ if (episode) {
+ setCurrent(episode.episode_no)
+ setRange(Math.floor((episode.episode_no - 1) / pageSize))
+ }
+ }).catch(e => { if (active) setError(e.message) })
+ return () => { active = false }
+ }, [id])
+ function select(episodeNo: number, play = true) {
+ setCurrent(episodeNo)
+ setAutoPlay(play)
+ setRange(Math.floor((episodeNo - 1) / pageSize))
+ sessionStorage.setItem(rememberKey(id), String(episodeNo))
+ }
+ if (error) return <p role="alert">{error}</p>
+ if (!item) return <p role="status">正在加载短剧…</p>
+ const episode = item.episodes.find(entry => entry.episode_no === current) || item.episodes[0]
+ if (!episode) return <p>这部短剧还没有可播放的分集。</p>
+ const free = isFreeEpisode(item, episode.episode_no)
+ const index = item.episodes.findIndex(entry => entry.id === episode.id)
+ const previous = item.episodes[index - 1]
+ const next = item.episodes[index + 1]
+ const ranges = Math.ceil(item.episodes.length / pageSize)
+ const visible = item.episodes.filter(entry => Math.floor((entry.episode_no - 1) / pageSize) === range)
+ const price = item.sale_type === 'platform_unlock' ? '按集解锁' : item.copyright_price_fen ? money(item.copyright_price_fen) : '免费'
+ return <>
+ <PageHeading title={item.title} description={`${item.category || '其他'} · 短剧 · ${item.episodes.length} 集`} back="/marketplace" />
+ <section className="pf-series-stage">
+ <Media key={episode.id} kind="series_episode" id={episode.id} purpose="preview" video autoPlay={autoPlay} onEnded={() => { if (next) select(next.episode_no) }} />
+ <div className="pf-series-transport">
+ <button type="button" disabled={!previous} onClick={() => previous && select(previous.episode_no)}>上一集</button>
+ <span>第 {episode.episode_no} 集 · {episode.title}</span>
+ <button type="button" disabled={!next} onClick={() => next && select(next.episode_no)}>下一集</button>
+ </div>
+ </section>
+ <section className="pf-series-meta">
+ <p>{item.sale_type === 'free' || (item.free_episode_count || 0) >= item.episodes.length ? '全部免费,播放原片' : (item.free_episode_count || 0) > 0 ? `前 ${item.free_episode_count} 集免费播放原片,之后 ${price}` : `收费观看 · ${price}`}</p>
+ <p className="pf-market-text">{item.description || '暂无系列简介'}</p>
+ <p>{free ? '本集免费观看,直接播放原片。使用仍须遵守作者授权范围。' : item.sale_type === 'platform_unlock' ? '本集需付费。未购买只能看水印试看,购买后永久在线播放。' : '本集需付费。当前为水印试看,联系客服购买后获取完整成片。'}</p>
+ {!free && item.sale_type === 'copyright_contact' && <NeedLogin><Contact kind="series_episode" id={episode.id} /></NeedLogin>}
+ {!free && item.sale_type === 'platform_unlock' && <small>平台解锁购买和永久播放由 App 接入,当前网页只播放水印试看。</small>}
+ </section>
+ <section className="pf-series-picker" aria-label="选集">
+ {ranges > 1 && <div className="pf-series-ranges">{Array.from({ length: ranges }, (_, group) => {
+ const start = group * pageSize + 1
+ const end = Math.min(item.episodes.length, start + pageSize - 1)
+ return <button key={group} type="button" aria-pressed={group === range} onClick={() => setRange(group)}>{start}–{end}</button>
+ })}</div>}
+ <div className="pf-series-grid">{visible.map(entry => {
+ const locked = !isFreeEpisode(item, entry.episode_no)
+ return <button key={entry.id} type="button" className={entry.episode_no === episode.episode_no ? 'is-current' : ''} aria-current={entry.episode_no === episode.episode_no} onClick={() => select(entry.episode_no)}>{entry.episode_no}{locked && <Lock size={12} aria-label="收费" />}</button>
+ })}</div>
+ </section>
+ <Link to="/marketplace">返回作品广场</Link>
+ </>
+}
diff --git a/frontend/src/features/marketplace/SeriesEditor.tsx b/frontend/src/features/marketplace/SeriesEditor.tsx
new file mode 100644
index 0000000..29c7349
--- /dev/null
+++ b/frontend/src/features/marketplace/SeriesEditor.tsx
@@ -0,0 +1,134 @@
+import { useEffect, useState, type FormEvent } from 'react'
+import { useNavigate, useParams } from 'react-router-dom'
+import { ChevronDown, ChevronRight } from 'lucide-react'
+import AssetPicker from './AssetPicker'
+import { request, type Handoff } from './api'
+import { FormSection, PageHeading, PublishGuide } from './ui'
+import Button from '../../components/ui/Button'
+import { useCategories } from './useCategories'
+
+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 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
+ toggle: () => void; update: (patch: Partial<EpisodeDraft>) => void; remove: () => void; goRights: () => void
+}) {
+ return <article className={`pf-episode-fold${open ? ' is-open' : ''}`}>
+ <button type="button" className="pf-episode-fold-head" aria-expanded={open} onClick={toggle}>
+ <span>{open ? <ChevronDown size={16} /> : <ChevronRight size={16} />}第 {episode.episode_no} 集 · {episode.title || '未命名'}</span>
+ <em>{free ? '免费' : '收费'} · {videoLabel}</em>
+ </button>
+ {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 />
+ <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>)}
+ {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>}
+ </article>
+}
+
+export default function SeriesEditor() {
+ const { id } = useParams(); const navigate = useNavigate()
+ const { names: categories, error: categoryError } = useCategories()
+ const [series, setSeries] = useState<SeriesDraft | null>(null)
+ const [saleType, setSaleType] = useState<'free' | 'copyright_contact' | 'platform_unlock'>('copyright_contact')
+ const [freeEpisodeCount, setFreeEpisodeCount] = useState(0)
+ const [category, setCategory] = useState('')
+ 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 [handoffs, setHandoffs] = useState<Handoff[]>([])
+ const [poll, setPoll] = useState(0)
+ const [busy, setBusy] = useState(false); const [error, setError] = useState('')
+ const [expanded, setExpanded] = useState<Set<number>>(() => new Set([0]))
+ 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))
+ }, [id])
+ useEffect(() => { if (id) request<{ items: ImportSource[] }>('/series/import-sources').then(value => setSources(value.items)).catch(() => {}) }, [id])
+ useEffect(() => {
+ if (!id) return
+ let stop = false
+ let timer = 0
+ async function tick() {
+ try {
+ const value = await request<{ items: Handoff[] }>(`/handoffs?series_id=${id}`)
+ if (stop) return
+ const items = value.items
+ setHandoffs(items)
+ if (items.some(item => item.status === 'ready')) {
+ 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 }
+ }))
+ }
+ if (items.some(item => item.status === 'pending' || item.status === 'running')) timer = window.setTimeout(() => setPoll(value => value + 1), 3000)
+ } catch { /* 进度查询失败时保留当前编辑内容 */ }
+ }
+ void tick()
+ return () => { stop = true; window.clearTimeout(timer) }
+ }, [id, poll])
+ 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 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)
+ 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)
+ if (!id) for (const episode of episodes) await request(`/series/${saved.id}/episodes`, 'POST', episodeBody(episode))
+ else {
+ // 先删除再改编号,避免同一系列的集数唯一约束冲突。只提交可编辑字段。
+ 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 })
+ 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) }
+ }
+ async function importEpisodes() {
+ if (!id || !sourceId || !selected.length) return
+ 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) }
+ }
+ async function submit() {
+ if (!id || !series) return
+ setBusy(true); setError('')
+ try { const updated = await request<SeriesDraft>(`/series/${id}/submit`, 'POST', { version: series.version }); setSeries(updated); setEpisodes(updated.episodes); setError('系列已提交,等待管理员在同一次内容审核中核验版权和内容。') }
+ catch (err) { setError((err as Error).message) } finally { setBusy(false) }
+ }
+ async function toggleListing() {
+ if (!id || !series || series.audit_status !== 'approved') return
+ 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 ? '系列已上架到作品广场。' : '系列已下架,历史审核记录仍保留。')
+ } catch (err) { setError((err as Error).message) } finally { setBusy(false) }
+ }
+ const current = series
+ if (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>
+ <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>}</div>
+ </form><PublishGuide /></div></>
+}
diff --git a/frontend/src/features/marketplace/WorkEditor.tsx b/frontend/src/features/marketplace/WorkEditor.tsx
new file mode 100644
index 0000000..e802cc9
--- /dev/null
+++ b/frontend/src/features/marketplace/WorkEditor.tsx
@@ -0,0 +1,99 @@
+import { useCategories } from './useCategories'
+import { useEffect, useState, type FormEvent } from 'react'
+import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
+import SeriesEditor from './SeriesEditor'
+import AssetPicker from './AssetPicker'
+import { request, type Handoff, type Row } from './api'
+import { Save } from 'lucide-react'
+import Button from '../../components/ui/Button'
+import { FormSection, PageHeading, PublishGuide } from './ui'
+
+
+
+function PublishKindChooser({ choose }: { choose: (kind: 'video' | 'series') => void }) {
+ const navigate = useNavigate()
+ return <>
+ <PageHeading title="发布作品" description="单条视频和短剧都会出现在作品广场。也可以直接选择已经在 PrintFilm 生成的成片。" back="/marketplace" />
+ <div className="pf-market-kind-choice">
+ <button type="button" onClick={() => choose('video')}><strong>单条视频</strong><span>上传一条成片和封面,提交后进入审核。</span></button>
+ <button type="button" onClick={() => choose('series')}><strong>短剧</strong><span>在同一页继续添加分集,每集一个视频和封面。</span></button>
+ <button type="button" onClick={() => navigate('/marketplace/from-printfilm')}><strong>从我的成片选择</strong><span>把 PrintFilm 已生成的科普成片或漫剧分集同步到市场,仍需授权和审核。</span></button>
+ </div>
+ </>
+}
+
+// 发布草稿独立于上游创作项目,未配置文件服务仍可保存文字。
+export default function WorkEditor() {
+ /* item 编辑快照;assetId 视频;coverId 自定义封面;error/busy 保存反馈。 */
+ const { id } = useParams(); const navigate = useNavigate(); const [search] = useSearchParams()
+ const [publishKind, setPublishKind] = useState<'video' | 'series' | ''>(search.get('type') === 'series' ? 'series' : '')
+ const { names: categories, error: categoryError } = useCategories()
+ const [category, setCategory] = useState('')
+ useEffect(() => { if (!id && !category && categories.length) setCategory(categories.includes('其他') ? '其他' : categories[0]) }, [id, category, categories])
+ const [item, setItem] = useState<Row | null>(null)
+ const [assetId, setAssetId] = useState<number | null>(null)
+ const [coverId, setCoverId] = useState<number | null>(null)
+ const [error, setError] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [saleType, setSaleType] = useState<'free' | 'copyright_contact' | 'platform_unlock'>('copyright_contact')
+ const [shareBps, setShareBps] = useState<number | null>(null)
+ const [source, setSource] = useState('external')
+ const [handoff, setHandoff] = useState<Handoff | null>(null)
+ const handoffQuery = search.get('handoff')
+ const syncing = handoff?.status === 'pending' || handoff?.status === 'running'
+ useEffect(() => {
+ if (!id && !handoffQuery) return
+ let stop = false
+ let timer = 0
+ async function tick() {
+ try {
+ const value = handoffQuery
+ ? await request<Handoff>(`/handoffs/${handoffQuery}`)
+ : (await request<{ items: Handoff[] }>(`/handoffs?target_kind=work&target_id=${id}`)).items[0]
+ if (stop || !value) return
+ setHandoff(value)
+ if (value.status === 'ready' && value.work_id) {
+ const work = await request<Row>(`/works/${value.work_id}`)
+ if (stop) return
+ setAssetId(work.asset_id ?? null)
+ setCoverId(work.cover_asset_id ?? null)
+ }
+ if (value.status === 'pending' || value.status === 'running') timer = window.setTimeout(tick, 3000)
+ } catch (err) { if (!stop) setError((err as Error).message) }
+ }
+ void tick()
+ return () => { stop = true; window.clearTimeout(timer) }
+ }, [id, handoffQuery, handoff?.status])
+ useEffect(() => { if (id) request<Row>(`/works/${id}`).then(value => { setItem(value); setCategory(value.category || '其他'); setSaleType((value.sale_type as typeof saleType) || (value.price_fen === 0 ? 'free' : 'copyright_contact')); setShareBps(typeof value.share_bps === 'number' ? value.share_bps : null); setSource(value.source || 'external'); setAssetId(value.asset_id ?? null); setCoverId(value.cover_asset_id ?? null) }).catch(e => setError(e.message)) }, [id])
+ // 完整表单更新携带版本,服务器决定是否重审。
+ async function save(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault(); setBusy(true); setError(''); const form = new FormData(e.currentTarget)
+ const body = { title: form.get('title'), description: form.get('description'), category: form.get('category'), tags: String(form.get('tags')).split(/[,,]/).map(v => v.trim()).filter(Boolean), price_fen: saleType === 'free' ? 0 : Math.round(Number(form.get('price')) * 100), unlock_price_fen: saleType === 'platform_unlock' ? Math.round(Number(form.get('unlock_price')) * 100) : 0, share_bps: saleType === 'platform_unlock' ? shareBps : null, sale_type: saleType, source, license_scope: form.get('license_scope'), asset_id: assetId, cover_asset_id: coverId, ...(id ? { version: item?.version } : {}) }
+ try { const result = await request<Row>(id ? `/works/${id}` : '/works', id ? 'PUT' : 'POST', body); navigate(`/marketplace/works/${result.id}/manage`) }
+ catch (err) { setError((err as Error).message) }
+ finally { setBusy(false) }
+ }
+ if (!id && publishKind === 'series') return <SeriesEditor />
+ if (!id && !publishKind) return <PublishKindChooser choose={setPublishKind} />
+ if (id && !item) return <p role={error ? 'alert' : 'status'}>{error || '正在加载作品…'}</p>
+ return <><PageHeading title={id ? '编辑作品' : '发布作品'} description="为作品建立一份清晰的介绍。资料可以先保存为草稿,提交时一次确认版权并交由管理员审核,通过后再上架。" back="/marketplace" /><div className="pf-market-editor-layout"><div className="pf-market-editor-main"><form className="pf-market-form" onSubmit={save}>
+ <p className="pf-market-notice">先保存作品草稿,提交审核前再统一确认版权信息。</p>
+ {handoff && <p className={handoff.status === 'failed' ? '' : 'pf-market-notice'} role={handoff.status === 'failed' ? 'alert' : 'status'}>{handoff.label}{handoff.error ? `:${handoff.error}` : ''}。{handoff.status === 'ready' && !handoff.authorization_ready ? <button type="button" onClick={() => navigate('/marketplace/authorization')}>去签署授权函</button> : null}{handoff.status === 'failed' ? <button type="button" onClick={() => void request<Handoff>(`/handoffs/${handoff.id}/retry`, 'POST').then(setHandoff).catch(err => setError((err as Error).message))}>重试复制</button> : null}</p>} <FormSection step="01" title="作品文件" description="视频和封面在提交审核前必填。保存草稿可以先只写文字。">
+ <AssetPicker kind="video" required value={assetId} onChange={setAssetId} title="作品视频" /><AssetPicker kind="image" required value={coverId} onChange={setCoverId} title="作品封面" />
+ </FormSection>
+ <FormSection step="02" title="介绍你的作品" description="清晰的标题和简介,帮助感兴趣的人找到你。"><label>标题<span className="pf-req-mark">必填</span><input name="title" required maxLength={200} placeholder="给作品一个简洁、有辨识度的名字" defaultValue={item?.title} /></label><label>简介<textarea name="description" maxLength={5000} placeholder="介绍作品内容、创作想法与适用场景" defaultValue={item?.description} /></label><div className="pf-market-field-row"><label>作品分类<span className="pf-req-mark">必填</span><select name="category" required value={category} onChange={e => setCategory(e.target.value)} disabled={!categories.length}><option value="" disabled>请选择作品分类</option>{category && !categories.includes(category) && <option value={category}>{category}(历史分类)</option>}{categories.map(name => <option key={name} value={name}>{name}</option>)}</select>{categoryError && <span role="alert">{categoryError}</span>}</label><label>内容来源<select name="source" value={source} onChange={e => setSource(e.target.value)}><option value="printfilm">PrintFilm 生成</option><option value="external">其他平台生成</option>{!['printfilm', 'external'].includes(source) && <option value={source}>历史来源:{source}</option>}</select></label></div><label>标签(逗号分隔,最多10个)<input name="tags" placeholder="例如:城市,航拍,生活" defaultValue={item?.tags?.join(',')} /></label></FormSection>
+ <FormSection step="03" title="价格与授权意向" description="标价为人民币参考价,具体授权与交付在线下确认。"><label>收费类型<select value={saleType} onChange={e => { const next = e.target.value as typeof saleType; setSaleType(next); if (next !== 'platform_unlock') setShareBps(null) }}><option value="free">免费公开</option><option value="copyright_contact">联系客服购买版权</option><option value="platform_unlock">平台投放收益</option></select></label>{saleType === 'free' ? <p className="pf-market-notice">免费作品审核通过后公开播放原片,不生成水印试看。免费不代表可任意商用,仍以授权范围为准。</p> : <><p className="pf-market-notice">提交审核时生成试看文件:版权咨询作品最多15秒且不超过原片30%;平台投放收益会生成同源分辨率 HLS 播放版本。原片仅按对应授权或购买权益提供。</p><label>版权参考价(元)<span className="pf-req-mark">有标价时必填</span><input name="price" type="number" min="0" max="1000000" step="0.01" placeholder="0.00" defaultValue={item?.price_fen ? item.price_fen / 100 : ''} /></label>{saleType === 'platform_unlock' && <><label>观众解锁价(元)<span className="pf-req-mark">必填</span><input name="unlock_price" type="number" required min="0.01" max="1000000" step="0.01" defaultValue={item?.unlock_price_fen ? item.unlock_price_fen / 100 : ''} /></label><label>平台分成(万分比,可留空使用后台默认)<input type="number" min="0" max="10000" step="1" value={shareBps ?? ''} onChange={e => setShareBps(e.target.value === '' ? null : Number(e.target.value))} placeholder="例如 2000" /></label></>}</>}<label>拟授权用途及限制<span className="pf-req-mark">提交审核前必填</span><textarea name="license_scope" maxLength={3000} placeholder="请说明允许的用途、范围和期限及禁止事项;保存草稿可暂不填,提交审核前必须补充" defaultValue={item?.license_scope} /></label></FormSection>
+ {error && <p role="alert">{error}</p>}<div className="pf-market-form-actions"><p>{id ? '保存修改后,作品将退出公开展示并重新审核。' : '保存草稿不会公开发布,封面请自行上传。'}</p><Button variant="lime" type="submit" disabled={busy || syncing || !categories.length || !category} icon><Save size={17} />{busy ? '保存中…' : syncing ? '正在同步成片…' : '保存草稿'}</Button></div>
+ </form></div><PublishGuide /></div></>
+}
+
+
+
+
+
+
+
+
+
+
+
diff --git a/frontend/src/features/marketplace/WorkPublishingSteps.tsx b/frontend/src/features/marketplace/WorkPublishingSteps.tsx
new file mode 100644
index 0000000..58aadc3
--- /dev/null
+++ b/frontend/src/features/marketplace/WorkPublishingSteps.tsx
@@ -0,0 +1,26 @@
+import { Link } from 'react-router-dom'
+import { labels, type Row } from './api'
+import RightsPage from './RightsPage'
+import AuthorizationPanel from './AuthorizationPanel'
+
+// 发布步骤始终显示;缺少视频时明确指向第一步,不再隐藏权属入口。
+export default function WorkPublishingSteps({ item, onUpdated }: { item: Row; onUpdated: () => void }) {
+ const mediaReady = Boolean(item.asset_id && item.media_status === 'ready')
+ const internal = item.source === 'printfilm'
+ const sourceKnown = internal || item.source === 'external'
+ const rightsTitle = internal ? '确认版权信息' : sourceKnown ? '上传权属证明 / 客服协办' : '确认生成平台并办理权属'
+ return <section className="pf-market-publishing" id="publishing" aria-label="作品发布流程">
+ <h2>发布步骤</h2><p>按顺序完成文件、授权材料与人工审核,最后由您主动上架。</p>
+ <ol className="pf-market-publish-steps">
+ <li data-complete={mediaReady}><span>01</span><div><h3>上传并绑定视频</h3><p>{mediaReady ? '视频已上传' : item.asset_id ? `媒体${labels[item.media_status || ''] || '尚未就绪'},请检查文件状态` : '尚未绑定视频。请先上传视频。'}</p><Link to={`/marketplace/works/${item.id}/edit`}>{mediaReady ? '修改作品文件' : '去上传 / 绑定视频'}</Link></div></li>
+ <li data-complete={Boolean(item.rights_complete)}><span>02</span><div><h3>{rightsTitle}</h3><p>{internal ? '签署授权函即可,无需其他证明。' : sourceKnown ? '填写证书编号并上传截图或照片;没有版权联系客服协办。' : '请先确认生成平台,再按对应流程处理。'}</p><p>作品审核:{labels[item.audit_status || 'missing']}</p>{item.rights_ready ? <p>作品审核已通过</p> : <p>{mediaReady ? '完成材料后提交管理员审核。' : '请先完成第 01 步上传视频。'}</p>}</div></li>
+ <li data-complete={item.audit_status === 'approved'}><span>03</span><div><h3>提交作品审核</h3><p>作品和版权信息一次提交,管理员一次审核。免费作品审核通过后公开播放原片;版权咨询作品生成最多15秒且不超过原片30%的水印试看;平台投放作品生成同源分辨率播放版本。</p></div></li>
+ <li data-complete={Boolean(item.listed)}><span>04</span><div><h3>确认上架</h3><p>{item.listed ? '已上架' : '媒体、权属和内容均通过后,由您主动上架。'}</p></div></li>
+ </ol>
+ {mediaReady ? <details className="pf-market-inline-rights" open={!item.rights_ready}><summary>{internal ? '签署 / 查看授权函' : '上传 / 补充权属材料,或联系客服协办'}</summary><RightsPage key={`${item.asset_id}-${item.source}`} assetId={item.asset_id!} sourceHint={item.source} embedded onUpdated={onUpdated} /></details> : internal ? <AuthorizationPanel /> : <p className="pf-market-notice">版权信息表单,会在视频绑定且处理就绪后显示。<Link to="/marketplace/authorization">PrintFilm 作品也可先签署账号授权函</Link>。</p>}
+ </section>
+}
+
+
+
+
diff --git a/frontend/src/features/marketplace/Workspace.tsx b/frontend/src/features/marketplace/Workspace.tsx
new file mode 100644
index 0000000..0674c56
--- /dev/null
+++ b/frontend/src/features/marketplace/Workspace.tsx
@@ -0,0 +1,74 @@
+import { useEffect, useState } from 'react'
+import { Link } from 'react-router-dom'
+import { ArrowUpRight, Film, Play, RefreshCw } from 'lucide-react'
+import { date, labels, money, request, type Listing, type Row } from './api'
+import { Media, Pager } from './shared'
+import Button from '../../components/ui/Button'
+import { EmptyState, PageHeading } from './ui'
+import AssetPreview from './AssetPreview'
+
+function mineHref(item: Row) {
+ return item.kind === 'series' ? `/marketplace/series/${item.id}/edit` : `/marketplace/works/${item.id}/manage`
+}
+
+function mineStatus(item: Row) {
+ if (item.blocked) return '已限制'
+ if (item.listed) return '已上架'
+ return labels[item.audit_status || ''] || '草稿'
+}
+
+function freeMine(item: Row) {
+ return item.sale_type === 'free' || ((item.price_fen ?? 0) === 0 && item.sale_type !== 'platform_unlock')
+}
+
+function MineWorks({ listing, loading, page, changePage }: { listing: Listing | null; loading: boolean; page: number; changePage: (value: number) => void }) {
+ return <section className="pf-market-discover pf-market-mine">
+ <header className="pf-discover-heading"><div><span className="pf-market-kicker">单视频与短剧</span><h1>我的作品</h1><p>草稿、审核和已上架的作品都在这里。</p></div><Button variant="dark" to="/marketplace/works/new" icon>发布作品<ArrowUpRight size={17} /></Button></header>
+ {loading ? <div className="pf-market-grid" role="status">{[0, 1, 2].map(item => <div key={item} className="pf-market-skeleton"><div /><span /><span /></div>)}</div> : listing?.items.length ? <div className="pf-market-grid">{listing.items.map(item => {
+ const href = mineHref(item)
+ const free = freeMine(item)
+ return <article className="pf-market-item" key={`${item.kind}-${item.id}`}>
+ <div className="pf-market-item-cover">{item.cover_asset_id ? <Media kind={item.kind === 'series' ? 'series' : 'work'} id={item.id} purpose="cover" /> : <span className="pf-market-series-mark"><Film size={36} /></span>}<Link className="pf-market-cover-play" to={href} aria-label={`管理${item.title}`}><Play size={16} /></Link></div>
+ <div className="pf-market-item-body">
+ <h3><Link to={href}>{item.title}</Link></h3>
+ <p className="pf-market-author"><span>{item.kind === 'series' ? '剧' : '作'}</span>{mineStatus(item)}{item.kind === 'series' ? ` · ${item.episode_count || 0} 集` : ''}</p>
+ <div className="pf-market-item-price"><div><strong>{free ? '免费' : money(item.sale_type === 'platform_unlock' ? item.unlock_price_fen : item.price_fen)}</strong>{!free && <span>{item.sale_type === 'platform_unlock' ? '解锁价' : '参考价'}</span>}</div><Link to={href} aria-label={`管理${item.title}`}><ArrowUpRight size={20} /></Link></div>
+ </div>
+ </article>
+ })}</div> : <EmptyState title="还没有作品" description="单条视频和短剧都会出现在这里。" action="发布我的作品" to="/marketplace/works/new" />}
+ <Pager listing={listing} page={page} change={changePage} />
+ </section>
+}
+
+// 所有列表由后端按当前账号隔离;不与原个人中心数据混合。
+export default function Workspace() {
+ /* kind 工作台分类;listing/page 当前列表;refresh 重新读取;mediaId 当前文件预览。 */
+ const [kind, setKind] = useState('works')
+ const [listing, setListing] = useState<Listing | null>(null)
+ const [page, setPage] = useState(1)
+ const [refresh, setRefresh] = useState(0)
+ const [error, setError] = useState('')
+ const [loading, setLoading] = useState(false)
+ const [mediaId, setMediaId] = useState<number | null>(null)
+ useEffect(() => { let active = true; setLoading(true); setError(''); request<Listing>(`/mine/${kind}?page=${page}`).then(value => { if (active) setListing(value) }).catch(e => { if (active) setError(e.message) }).finally(() => { if (active) setLoading(false) }); return () => { active = false } }, [kind, page, refresh])
+ async function action(path: string) { try { await request(path, 'POST'); setRefresh(v => v + 1) } catch (e) { setError((e as Error).message) } }
+ const tabs = { works: '我的作品', series: '我的短剧', recruits: '我的招募', rights: '版权审核', assets: '我的文件', notifications: '站内通知' }
+ return <><PageHeading title="我的发布与业务进度" description="从作品草稿到合作机会,在这里跟进作品发布与需求审核。招募接单请联系客服。" /><p><Link to="/marketplace/authorization">签署 / 查看 PrintFilm 授权函</Link></p>
+ <div className="pf-market-workspace-toolbar"><nav className="pf-market-tabs" aria-label="个人业务分类">{Object.entries(tabs).map(([key, label]) => <button key={key} type="button" aria-pressed={key === kind} onClick={() => { setKind(key); setPage(1); setMediaId(null) }}>{label}</button>)}</nav><button type="button" onClick={() => setRefresh(v => v + 1)}><RefreshCw size={14} />刷新</button></div>
+ {error && <p role="alert">{error}</p>}
+ {kind === 'works' ? <MineWorks listing={listing} loading={loading} page={page} changePage={setPage} /> : <>
+ {kind === 'series' && <section className="pf-market-discover pf-market-mine"><header className="pf-discover-heading"><div><span className="pf-market-kicker">剧集资产</span><h1>我的短剧</h1><p>查看系列草稿、分集审核和上架状态。</p></div><Button variant="dark" to="/marketplace/works/new?type=series" icon>发布短剧<ArrowUpRight size={17} /></Button></header>{loading ? <div className="pf-market-grid" role="status">{[0, 1, 2].map(item => <div key={item} className="pf-market-skeleton"><div /><span /><span /></div>)}</div> : listing?.items.length ? <div className="pf-market-grid">{listing.items.map(item => { const href = `/marketplace/series/${item.id}/edit`; const free = item.sale_type === 'free'; const price = item.copyright_price_fen ?? item.price_fen; return <article className="pf-market-item" key={`series-${item.id}`}><div className="pf-market-item-cover">{item.cover_asset_id ? <Media kind="series" id={item.id} purpose="cover" /> : <span className="pf-market-series-mark"><Film size={36} /></span>}<Link className="pf-market-cover-play" to={href} aria-label={`管理${item.title}`}><Play size={16} /></Link></div><div className="pf-market-item-body"><h3><Link to={href}>{item.title}</Link></h3><p className="pf-market-author"><span>剧</span>{mineStatus(item)} · {item.episode_count || 0} 集</p><div className="pf-market-item-price"><div><strong>{free ? '免费' : item.sale_type === 'platform_unlock' ? '按集解锁' : money(price)}</strong>{!free && <span>{item.sale_type === 'platform_unlock' ? '分集定价' : '参考价'}</span>}</div><Link to={href} aria-label={`管理${item.title}`}><ArrowUpRight size={20} /></Link></div></div></article> })}</div> : <EmptyState title="还没有短剧" description="创建系列后,可逐集上传或导入漫剧分集。" action="发布短剧" to="/marketplace/works/new?type=series" />}<Pager listing={listing} page={page} change={setPage} /></section>}
+ {kind !== 'series' && <>{loading ? <div className="pf-market-empty" role="status">正在读取你的业务进度…</div> : listing?.items.map(item => <article className="pf-market-workspace-item" key={item.id}>
+ <div className="pf-market-record-head"><h2>{item.title || item.filename || item.recruit_title || item.message || `记录 #${item.id}`}</h2><span className="pf-market-badge">{item.blocked ? '已限制' : item.withdrawn ? '已撤回' : labels[item.audit_status ?? item.status ?? item.state ?? item.selection ?? ''] || (kind === 'notifications' ? item.read ? '已读' : '未读' : '业务记录')}</span></div>
+ <p>{date(item.created_at)} · 编号 #{item.id}</p>
+ {(item.reason || item.note || item.error) && <p className="pf-market-record-note">{item.reason || item.note || item.error}</p>}
+ {kind === 'recruits' && <Link to={`/marketplace/recruits/${item.id}/manage`}>查看与管理</Link>}
+ {kind === 'assets' && <><p>类型:{item.kind} · 指纹:{item.fingerprint || '处理后生成'}</p><button type="button" onClick={() => setMediaId(mediaId === item.id ? null : item.id)}>{mediaId === item.id ? '收起预览' : '查看文件预览'}</button>{mediaId === item.id && <AssetPreview id={item.id} />}{item.status === 'failed' && <button type="button" onClick={() => action(`/assets/${item.id}/retry`)}>重试处理</button>}{item.kind === 'video' && item.status === 'ready' && <Link to={`/marketplace/assets/${item.id}/rights?return=${encodeURIComponent('/marketplace/mine')}`}>查看版权审核</Link>}</>}
+ {kind === 'rights' && <><p>审核状态:{labels[item.full_status ?? '']}</p><Link to={`/marketplace/assets/${item.asset_id}/rights?return=${encodeURIComponent('/marketplace/mine')}`}>查看与补充材料</Link></>}
+ {kind === 'notifications' && <>{item.link && <Link to={item.link}>前往工作台</Link>}<button type="button" disabled={item.read} onClick={() => action(`/notifications/${item.id}/read`)}>{item.read ? '已读' : '标记已读'}</button></>}
+ </article>)}
+ {!loading && !error && listing?.items.length === 0 && <EmptyState title="这里还没有记录" description={kind === 'notifications' ? '发布及审核状态发生变化时,通知会出现在这里。' : '你的需求与合作进展,都会在这里留下记录。'} action={kind === 'recruits' ? '发布招募需求' : undefined} to={kind === 'recruits' ? '/marketplace/recruits/new' : '/marketplace'} />}
+ <Pager listing={listing} page={page} change={setPage} /></>}
+ </>}
+ </>
+}
diff --git a/frontend/src/features/marketplace/api.ts b/frontend/src/features/marketplace/api.ts
new file mode 100644
index 0000000..149f3e8
--- /dev/null
+++ b/frontend/src/features/marketplace/api.ts
@@ -0,0 +1,133 @@
+/** 下游独立客户端;不修改原 api.ts。金额统一以分传输。 */
+export type Row = {
+ id: number; title?: string; description?: string; category?: string; author?: string;
+ price_fen?: number; copyright_price_fen?: number; unlock_price_fen?: number; sale_type?: 'free' | 'copyright_contact' | 'platform_unlock'; share_bps?: number | null; budget_fen?: number; quote_fen?: number; wanted_count?: number;
+ requirements?: string; license_scope?: string; image_ids?: number[]; deadline_at?: string;
+ version?: number; asset_id?: number | null; cover_asset_id?: number | null; source?: string; tags?: string[];
+ audit_status?: string; listed?: boolean; blocked?: boolean; reason?: string; media_status?: string;
+ preview_status?: string; preview_error?: string;
+ basic_status?: string; full_status?: string; owner_id?: number; state?: string; status?: string;
+ rights_complete?: boolean; rights_ready?: boolean; rights_source?: string | null;
+ filename?: string; kind?: string; error?: string; fingerprint?: string; duration_seconds?: number; episode_count?: number; free_episode_count?: number;
+ recruit_id?: number; recruit_title?: string; selection?: string; withdrawn?: boolean;
+ can_review?: boolean; can_purchase?: boolean; submission_count?: number;
+ is_owner?: boolean; is_open?: boolean; can_submit?: boolean; can_contact?: boolean;
+ rights_id?: number; route?: string; official_reference?: string; note?: string;
+ message?: string; link?: string; read?: boolean; created_at?: string;
+}
+export type Listing = { items: Row[]; meta: { page: number; page_size: number; total: number } }
+export type Capabilities = { enabled: boolean; storage_configured: boolean }
+export type Handoff = {
+ id: number; status: string; label: string; error: string; authorization_ready: boolean
+ target_kind: string; target_id: number; work_id: number | null; episode_id: number | null
+ series_id: number | null; asset_id: number | null
+}
+export type RightsRecord = {
+ id?: number; asset_id: number; version: number; details?: Record<string, string>;
+ certificate_asset_id?: number | null; evidence_ids?: number[]; valid_until?: string | null;
+ preview_status?: string; preview_error?: string;
+ basic_status?: string; full_status?: string; reason?: string; blocked?: boolean;
+}
+
+// 使用与用户端相同的 API 域名约定,但隔离请求实现。
+export const base = import.meta.env.VITE_API_BASE ?? `${window.location.protocol}//${window.location.hostname}:8000`
+
+const fieldNames: Record<string, string> = {
+ title: '标题', description: '简介', category: '分类', tags: '标签', price_fen: '版权参考价',
+ copyright_price_fen: '版权参考价', unlock_price_fen: '解锁价', share_bps: '平台分成',
+ license_scope: '拟授权用途及限制', asset_id: '视频', cover_asset_id: '封面', source: '内容来源',
+ certificate_number: '版权证书编号', dispute_ack: '纠纷确认', episode_no: '集数',
+}
+
+function explainValidation(detail: unknown[]) {
+ const lines = detail.map(item => {
+ if (!item || typeof item !== 'object') return ''
+ const row = item as { loc?: unknown[]; msg?: string }
+ const loc = (row.loc ?? []).filter(part => part !== 'body' && part !== 'query').map(part => typeof part === 'number' ? `第 ${part + 1} 项` : fieldNames[String(part)] || String(part))
+ const raw = row.msg || ''
+ const msg = /field required/i.test(raw) ? '这是必填项' : /at least 1 character/i.test(raw) ? '不能为空' : /valid integer|valid number/i.test(raw) ? '请填写数字' : /extra inputs are not permitted/i.test(raw) ? '不能提交' : raw
+ return loc.length ? `${loc.join('的')}:${msg}` : msg
+ }).filter(Boolean)
+ return [...new Set(lines)].join(';') || '请检查表单内容和必填字段'
+}
+
+// 统一解析中文业务错误;不把原项目令牌发给 OSS。
+export async function request<T>(path: string, method = 'GET', body?: unknown, signal?: AbortSignal): Promise<T> {
+ const token = localStorage.getItem('token')
+ const binary = body instanceof Blob
+ const response = await fetch(`${base}/api/marketplace${path}`, {
+ method, signal, headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(body !== undefined ? { 'Content-Type': binary ? 'application/octet-stream' : 'application/json' } : {}) },
+ body: body === undefined ? undefined : binary ? body : JSON.stringify(body),
+ })
+ const result = await response.json().catch(() => ({}))
+ if (!response.ok) {
+ if (response.status === 401) window.location.assign(`/auth?next=${encodeURIComponent(window.location.pathname + window.location.search)}`)
+ const detail = result.detail
+ throw new Error(typeof detail === 'string' ? detail : detail?.message || (Array.isArray(detail) ? explainValidation(detail) : `请求失败(${response.status})`))
+ }
+ return result as T
+}
+
+// 只在需要观看时申请短时链接,不能把 object_key 放到前端。
+export async function media(kind: string, id: number, purpose: string) {
+ return (await request<{ url: string }>(`/media/${kind}/${id}/${purpose}`)).url
+}
+
+// 保留用户选择的文件;使用首尾片段指纹区分续传,不读取整段视频。
+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 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
+ signal?.throwIfAborted()
+ try {
+ const stored = localStorage.getItem(key)
+ if (stored) {
+ try {
+ const candidate = await request<Session>(`/uploads/${stored}`)
+ if (candidate.state === 'uploading' && Date.parse(candidate.expires_at) > Date.now()) session = candidate
+ } catch { localStorage.removeItem(key) }
+ }
+ if (!session) {
+ session = await request<Session>('/uploads', 'POST', { filename: file.name, size_bytes: file.size, kind })
+ localStorage.setItem(key, String(session.id))
+ }
+ const count = Math.ceil(file.size / session.part_size)
+ const uploaded = new Set(session.uploaded_parts)
+ for (let number = 1; number <= count; number++) {
+ if (!uploaded.has(number)) {
+ const part = file.slice((number - 1) * session.part_size, number * session.part_size)
+ let success = false
+ for (let attempt = 0; attempt < 3; attempt++) {
+ try { await request(`/uploads/${session.id}/parts/${number}`, 'PUT', part, signal); success = true; break }
+ catch (error) { if (signal?.aborted || attempt === 2) throw error }
+ }
+ if (success) uploaded.add(number)
+ }
+ progress(Math.floor(uploaded.size / count * 100))
+ }
+ signal?.throwIfAborted()
+ await request(`/uploads/${session.id}/complete`, 'POST', undefined, signal)
+ localStorage.removeItem(key)
+ return session.asset_id
+ } catch (error) {
+ if (signal?.aborted && session) {
+ try { await request(`/uploads/${session.id}`, 'DELETE'); localStorage.removeItem(key) }
+ catch { throw new Error('取消未确认,请到我的文件检查状态;重新选择相同文件可恢复上传。') }
+ throw new Error('已取消上传')
+ }
+ throw error
+ }
+}
+
+// 以分展示人民币,避免浮点金额进入业务接口。
+export const money = (value?: number) => `¥${((value ?? 0) / 100).toFixed(2)}`
+// 北京时间展示,服务端保留 UTC。
+export const date = (value?: string) => value ? new Date(value).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }) : '—'
+// 将UTC转为当前浏览器datetime-local值,避免表单回填时改变时区。
+export function localDate(value: string) { const date = new Date(value); return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16) }
+// 状态不在客户端推断,仅翻译后端结果。
+export const labels: Record<string, string> = { draft: '草稿', preview_failed: '水印生成失败', pending: '待审核', approved: '已通过', rejected: '已驳回', missing: '未提交', ready: '已就绪', processing: '处理中', uploading: '上传中', failed: '失败', open: '征集中', closed: '已关闭', expired: '已到期', to_review: '待看', candidate: '候选', not_selected: '不采用', pending_materials: '待材料', reviewing: '材料核验中', supplement: '待补正', applying: '办理中', certificated: '已取得证书', cancelled: '已取消', existing: '已有证书', self_service: '自行办理', assisted: '客服协办' }
+
+
diff --git a/frontend/src/features/marketplace/hooks.ts b/frontend/src/features/marketplace/hooks.ts
new file mode 100644
index 0000000..143b762
--- /dev/null
+++ b/frontend/src/features/marketplace/hooks.ts
@@ -0,0 +1,14 @@
+import { useEffect, useState } from 'react'
+import { request, type Capabilities } from './api'
+
+// 菜单和页面以服务端开关为准,失败时不展示下游入口。
+export function useMarketplace() {
+ const [capabilities, setCapabilities] = useState<Capabilities | null>(null)
+ const [error, setError] = useState('')
+ useEffect(() => {
+ let active = true
+ request<Capabilities>('/capabilities').then(value => { if (active) setCapabilities(value) }).catch(() => { if (active) setError('无法读取下游业务状态,请稍后重试') })
+ return () => { active = false }
+ }, [])
+ return { capabilities, error }
+}
diff --git a/frontend/src/features/marketplace/marketplace.css b/frontend/src/features/marketplace/marketplace.css
new file mode 100644
index 0000000..92981c2
--- /dev/null
+++ b/frontend/src/features/marketplace/marketplace.css
@@ -0,0 +1,261 @@
+/* 数字资产市场复用主站 tokens;所有布局和控件样式限定在本模块。 */
+.pf-market { max-width:1200px; margin:auto; padding:12px 8px 24px; color:var(--pf-ink); font-size:14px; }
+body:has(.pf-market-shell) .pf-wx-fab-root { display:none; }
+.pf-market h1,.pf-market h2,.pf-market h3,.pf-market p { margin:0; }
+.pf-market h1 { font-size:28px; letter-spacing:-.8px; line-height:1.35; }
+.pf-market h2 { font-size:20px; letter-spacing:-.4px; }
+.pf-market h3 { font-size:16px; }
+.pf-market p { line-height:1.75; overflow-wrap:anywhere; }
+.pf-market svg { flex-shrink:0; }
+.pf-market a { text-decoration:none; }
+.pf-market :where(button:not(.pf-btn),select,input:not([type=checkbox]):not([type=file]),textarea) { border:1px solid var(--pf-line); border-radius:var(--pf-radius-sm); background:var(--pf-card); color:var(--pf-ink); padding:10px 12px; font:inherit; min-width:0; max-width:100%; transition:border-color .16s,box-shadow .16s,background .16s; }
+.pf-market input::placeholder,.pf-market textarea::placeholder { color:#969ca6; }
+.pf-market button:not(.pf-btn) { display:inline-flex; align-items:center; justify-content:center; gap:7px; font-weight:550; cursor:pointer; }
+.pf-market button:not(.pf-btn):hover:not(:disabled) { border-color:#a5b779; background:#f5f8ee; }
+.pf-market button:disabled { opacity:.45; cursor:not-allowed; }
+.pf-market :is(button,a,input,textarea,select):focus-visible { outline:2px solid #6b8d16; outline-offset:3px; }
+.pf-market :is(input,textarea,select):focus { border-color:#91b943; }
+.pf-market .pf-btn { gap:8px; text-decoration:none; white-space:nowrap; }
+.pf-market [role=alert] { color:#a32722; margin:14px 0; }
+.pf-market-top { display:flex; justify-content:space-between; align-items:center; gap:20px; padding:12px 0 26px; }
+.pf-market-brand { display:flex; align-items:center; gap:12px; }
+.pf-market-brand-icon { width:46px; height:46px; display:grid; place-items:center; background:var(--pf-ink); color:var(--pf-lime); border-radius:13px; }
+.pf-market .pf-market-eyebrow { font-size:10px; letter-spacing:1.8px; font-weight:650; color:var(--pf-muted); line-height:1.5; }
+.pf-market .pf-market-title { font-size:23px; letter-spacing:-.5px; font-weight:750; line-height:1.45; }
+.pf-market-publish-actions { display:flex; gap:10px; }
+.pf-market-nav-row { display:flex; justify-content:space-between; gap:20px; align-items:center; border-bottom:1px solid var(--pf-line); margin-bottom:22px; }
+.pf-market-nav { display:flex; gap:30px; }
+.pf-market-nav a { display:flex; align-items:center; gap:8px; padding:0 2px 16px; color:var(--pf-muted); border-bottom:3px solid transparent; margin-bottom:-1px; white-space:nowrap; font-weight:600; }
+.pf-market-nav a:hover { color:var(--pf-ink); }
+.pf-market-nav a.active { color:var(--pf-ink); border-bottom-color:var(--pf-lime); }
+.pf-market-nav-hint { display:flex; align-items:center; gap:7px; font-size:12px; color:var(--pf-muted); padding-bottom:15px; white-space:nowrap; }
+.pf-market-storage-note { display:flex; gap:10px; align-items:center; background:#fff9e9; color:#806222; border:1px solid #eee3c7; border-radius:10px; padding:10px 14px; margin-bottom:22px; font-size:12px; }
+.pf-market-storage-note strong { font-weight:600; margin-right:14px; }
+.pf-market-storage-note p { display:flex; flex-wrap:wrap; gap:1px; }
+.pf-market-hero { position:relative; overflow:hidden; display:grid; grid-template-columns:1.2fr 1fr; min-height:300px; border:1px solid #e0e6d7; border-radius:20px; background:linear-gradient(110deg,#fff 10%,#f3f8e9 65%,#eaf2dc); padding:35px 42px; align-items:center; }
+.pf-market-kicker { display:inline-flex; align-items:center; gap:7px; font-size:12px; font-weight:600; color:#52622e; margin-bottom:14px; }
+.pf-market-kicker::before { content:''; width:6px; height:6px; border-radius:50%; background:#779d28; }
+.pf-market-hero h1 { font-size:36px; font-weight:760; letter-spacing:-1px; line-height:1.4; }
+.pf-market-hero h1 em { font-style:normal; position:relative; background:linear-gradient(transparent 66%,#d7f292 66%,#d7f292 92%,transparent 92%); }
+.pf-market-hero-copy>p { color:var(--pf-muted); font-size:13px; margin:15px 0 23px; max-width:380px; }
+.pf-market-hero-art { width:340px; height:235px; justify-self:center; position:relative; }
+.pf-market-art-orbit { position:absolute; width:260px; height:260px; border:1px solid #c7d6b0; border-radius:50%; left:35px; top:-15px; }
+.pf-market-art-orbit::after { content:''; position:absolute; inset:23px; border:1px dashed #cad8b7; border-radius:50%; }
+.pf-market-art-frame { position:absolute; border-radius:15px; box-shadow:0 18px 35px #27331b14; }
+.pf-market-art-back { display:flex; justify-content:space-between; align-items:flex-start; width:235px; height:162px; right:6px; top:10px; transform:rotate(9deg); background:#d7ecb7; border:1px solid #bed59f; padding:17px; color:#637f3b; }
+.pf-market-art-back>span { font-size:8px; letter-spacing:1px; }
+.pf-market-art-front { width:255px; height:180px; top:40px; left:16px; transform:rotate(-6deg); background:#202723; color:#fff; border:1px solid #3a493d; padding:17px 19px; }
+.pf-market-art-top { display:flex; justify-content:space-between; font-size:8px; letter-spacing:1.8px; color:#adb7ae; }
+.pf-market-art-play { width:64px; height:64px; border:1px solid #b6ff0060; border-radius:50%; display:grid; place-items:center; color:var(--pf-lime); margin:19px auto; background:#b6ff000b; }
+.pf-market-art-bottom { display:flex; align-items:center; justify-content:space-between; color:#d3dbd4; font-size:10px; }
+.pf-market-art-label { position:absolute; bottom:2px; right:0; display:flex; align-items:center; gap:8px; background:#fff; color:#425833; font-size:11px; border-radius:9px; border:1px solid #e0e5d9; box-shadow:0 8px 20px #27331b0c; padding:12px 15px; }
+.pf-market-hero.is-recruit { background:linear-gradient(110deg,#fff 10%,#f2f6ee 65%,#e6eee4); }
+.pf-market-principles { display:flex; justify-content:space-around; flex-wrap:wrap; gap:15px; margin:0 16px 34px; padding:18px 0; border-bottom:1px solid var(--pf-line); color:var(--pf-muted); font-size:12px; }
+.pf-market-principles>span { display:flex; align-items:center; gap:8px; }
+.pf-market-principles svg { color:#6c8053; }
+.pf-market-section-heading { display:flex; justify-content:space-between; align-items:center; gap:18px; margin-bottom:20px; }
+.pf-market-section-heading p { color:var(--pf-muted); font-size:13px; margin-top:5px; }
+.pf-market-count { color:var(--pf-muted); font-size:12px; white-space:nowrap; }
+.pf-market-filter-panel { background:var(--pf-card); border:1px solid var(--pf-line); border-radius:var(--pf-radius); margin-bottom:24px; overflow:hidden; }
+.pf-market-filter-top { display:flex; gap:12px; padding:17px 20px; }
+.pf-market-filter-top select { width:160px; }
+.pf-market-search { display:flex; align-items:center; gap:10px; flex:1; min-width:0; border:1px solid var(--pf-line); border-radius:10px; padding:0 13px; color:var(--pf-muted); background:var(--pf-bg); }
+.pf-market-search:focus-within { border-color:#91b943; }
+.pf-market .pf-market-search input { border:0; background:transparent; width:100%; padding:11px 0; box-shadow:none; outline:none; }
+.pf-market-filter-bottom { display:flex; align-items:center; gap:20px; flex-wrap:wrap; padding:13px 20px; border-top:1px solid var(--pf-line); font-size:12px; }
+.pf-market-filter-label { display:flex; align-items:center; gap:7px; color:var(--pf-muted); }
+.pf-market-category,.pf-market-price-filter { display:flex; align-items:center; gap:9px; }
+.pf-market .pf-market-category input { width:122px; padding:7px 10px; font-size:12px; }
+.pf-market .pf-market-price-filter input { width:100px; padding:7px 10px; font-size:12px; }
+.pf-market .pf-market-reset { border:0; background:transparent; color:var(--pf-muted); padding:6px 0; font-size:12px; margin-left:auto; }
+.pf-market-grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:22px; }
+.pf-market article { background:var(--pf-card); border:1px solid var(--pf-line); border-radius:var(--pf-radius); padding:22px; margin:14px 0; min-width:0; }
+.pf-market article h2 { margin-bottom:8px; }
+.pf-market article>p { color:var(--pf-muted); margin:8px 0; }
+.pf-market article>a { display:inline-flex; gap:6px; margin:6px 14px 6px 0; font-weight:600; }
+.pf-market article>button { margin:5px 8px 5px 0; }
+.pf-market .pf-market-item { padding:0; margin:0; overflow:hidden; transition:box-shadow .2s,transform .2s; }
+.pf-market-item:hover { box-shadow:var(--pf-shadow); transform:translateY(-3px); }
+.pf-market .pf-market-item-cover { display:block; margin:0; aspect-ratio:16/9; background:#edf0eb; position:relative; overflow:hidden; }
+.pf-market-item-cover .pf-market-cover { width:100%; height:100%; object-fit:cover; border-radius:0; margin:0; }
+.pf-market-cover-play { position:absolute; bottom:12px; right:12px; background:#fff; display:grid; place-items:center; width:32px; height:32px; border-radius:50%; }
+.pf-market-item-cover>p { padding:20px; font-size:12px; }
+.pf-market-item-body { padding:20px; }
+.pf-market-category-tag { color:var(--pf-muted); font-size:11px; background:var(--pf-bg); border-radius:5px; padding:3px 7px; }
+.pf-market-item h3 { margin-top:10px; line-height:1.5; overflow-wrap:anywhere; }
+.pf-market .pf-market-author { display:flex; align-items:center; gap:7px; font-size:12px; color:var(--pf-muted); margin:12px 0 20px; }
+.pf-market-author>span { width:24px; height:24px; display:grid; place-items:center; border-radius:50%; background:#eaf0e3; color:#5b6b49; font-size:10px; }
+.pf-market-item-price { display:flex; align-items:center; justify-content:space-between; }
+.pf-market-item-price>div { display:flex; align-items:baseline; gap:7px; flex-wrap:wrap; }
+.pf-market-item-price strong { font-size:23px; font-weight:750; font-variant-numeric:tabular-nums; }
+.pf-market-item-price span { font-size:11px; color:var(--pf-muted); }
+.pf-market-item-price>a { background:var(--pf-bg); width:32px; height:32px; border-radius:50%; display:grid; place-items:center; }
+.pf-market-item-foot { display:flex; align-items:center; gap:5px; margin-top:16px; padding-top:13px; border-top:1px solid var(--pf-line); color:#748260; font-size:11px; }
+.pf-market-recruit-top { padding:20px 20px 0; display:flex; align-items:center; justify-content:space-between; }
+.pf-market-item-icon { width:44px; height:44px; display:grid; place-items:center; border-radius:12px; background:#f0f4e8; color:#687d46; }
+.pf-market-badge { display:inline-flex; align-items:center; border-radius:30px; padding:4px 10px; font-size:11px; font-weight:600; background:var(--pf-lime-soft); color:#4e6424; }
+.pf-market .pf-market-item-description { font-size:12px; color:var(--pf-muted); margin:-4px 0 20px; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; min-height:42px; }
+.pf-market-empty { background:var(--pf-card); border:1px solid var(--pf-line); border-radius:var(--pf-radius); padding:48px 24px; text-align:center; display:flex; flex-direction:column; align-items:center; gap:14px; }
+.pf-market-empty-icon { width:64px; height:64px; border-radius:20px; display:grid; place-items:center; color:#7b8b69; background:linear-gradient(140deg,#f1f5e9,#e9eee3); margin-bottom:3px; box-shadow:0 0 0 8px #f7f9f3; }
+.pf-market-empty h3 { margin-top:9px; font-size:17px; }
+.pf-market-empty p { font-size:13px; color:var(--pf-muted); max-width:420px; }
+.pf-market-empty .pf-btn { margin-top:5px; }
+.pf-market-pagination { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:22px 0; color:var(--pf-muted); font-size:12px; }
+.pf-market-pagination>div { display:flex; align-items:center; gap:14px; }
+.pf-market-pagination button { font-size:12px!important; padding:7px 10px!important; }
+.pf-market .pf-market-footnote { text-align:center; color:var(--pf-muted); font-size:11px; padding:12px 0 0; }
+.pf-market-skeleton { border-radius:14px; padding:15px; border:1px solid var(--pf-line); background:var(--pf-card); }
+.pf-market-skeleton div,.pf-market-skeleton span { display:block; background:var(--pf-bg); border-radius:8px; }
+.pf-market-skeleton div { aspect-ratio:16/9; }.pf-market-skeleton span { width:75%; height:16px; margin-top:16px; }.pf-market-skeleton span:last-child { width:45%; }
+.pf-market-error { background:#fff8f7; padding:30px; border-radius:14px; border:1px solid #f0dad5; text-align:center; }.pf-market-error .pf-btn { margin-top:15px; }
+/* 分组编辑页与作品工作台。 */
+.pf-market-page-heading { margin:30px 0 25px; }.pf-market-page-heading>p { color:var(--pf-muted); margin-top:9px; max-width:760px; }
+.pf-market-back { display:inline-flex; align-items:center; gap:7px; color:var(--pf-muted); font-size:12px; margin-bottom:14px; }
+.pf-market-editor-layout { display:grid; grid-template-columns:minmax(0,1fr) 290px; gap:26px; align-items:start; }
+.pf-market-form { display:grid; gap:20px; min-width:0; max-width:840px; margin:22px 0; }
+.pf-market-editor-layout>.pf-market-form { margin:0; max-width:none; }
+.pf-market-form-section { border:1px solid var(--pf-line); background:var(--pf-card); border-radius:var(--pf-radius); padding:25px; }
+.pf-market-form-section>header { display:flex; gap:12px; align-items:flex-start; margin-bottom:24px; }
+.pf-market-form-section>header>span { display:grid; place-items:center; width:29px; height:29px; background:var(--pf-lime-soft); color:#5d742d; font-size:11px; border-radius:8px; font-weight:700; }
+.pf-market-form-section h2 { font-size:17px; margin:2px 0; }.pf-market-form-section header p { font-size:12px; color:var(--pf-muted); margin-top:5px; }
+.pf-market-fields { display:grid; gap:19px; min-width:0; }
+.pf-market-field-row { display:grid; grid-template-columns:1fr 1fr; gap:18px; min-width:0; }
+.pf-market-form label { display:grid; gap:8px; font-size:13px; font-weight:550; min-width:0; }
+.pf-req-mark { margin-left:8px; color:#b42318; font-size:11px; font-weight:700; }
+.pf-market-form label:has(input[type=checkbox]) { display:flex; align-items:flex-start; font-weight:400; color:var(--pf-muted); line-height:1.7; }
+.pf-market-form :is(input:not([type=checkbox]),select,textarea) { width:100%; }
+.pf-market-form textarea { min-height:110px; resize:vertical; line-height:1.7; }.pf-market input[type=checkbox] { accent-color:#6f9220; margin:5px 5px 0 0; flex-shrink:0; }
+.pf-market-form-actions { display:flex; align-items:center; justify-content:space-between; gap:20px; background:var(--pf-card); padding:20px 24px; border:1px solid var(--pf-line); border-radius:var(--pf-radius); }
+.pf-market-form-actions p { font-size:12px; color:var(--pf-muted); max-width:480px; }.pf-market-form-actions .pf-btn { flex-shrink:0; }
+.pf-market-guide { border:1px solid var(--pf-line); border-radius:var(--pf-radius); padding:24px; background:var(--pf-card); position:sticky; top:85px; }
+.pf-market-guide-heading { display:flex; align-items:center; gap:9px; }.pf-market-guide-heading svg { color:#718a48; }.pf-market-guide-heading h2 { font-size:16px; }
+.pf-market-guide ol { list-style:none; margin:25px 0; padding:0; }.pf-market-guide li { display:flex; gap:12px; position:relative; padding-bottom:24px; }.pf-market-guide li:last-child { padding-bottom:0; }.pf-market-guide li:not(:last-child)::before { content:''; position:absolute; top:27px; bottom:4px; left:12px; width:1px; background:var(--pf-line); }.pf-market-guide li>span { width:26px; height:26px; display:grid; place-items:center; background:var(--pf-bg); color:var(--pf-muted); border-radius:50%; font-size:10px; flex-shrink:0; }.pf-market-guide strong { font-size:12px; font-weight:650; }.pf-market-guide li p { font-size:11px; color:var(--pf-muted); margin-top:4px; }.pf-market-guide-note { border-top:1px solid var(--pf-line); padding-top:18px; }.pf-market-guide-note p { color:var(--pf-muted); font-size:12px; margin-top:7px; }
+.pf-market fieldset { min-width:0; margin:0; padding:18px; border:1px solid var(--pf-line); border-radius:12px; display:grid; gap:12px; }.pf-market legend { font-size:13px; font-weight:600; padding:0 6px; }
+.pf-market-upload-zone { display:flex!important; align-items:center!important; justify-content:center; flex-direction:column; text-align:center; gap:9px!important; border:1px dashed #cbd4bf; border-radius:11px; padding:25px 14px; background:#fafcf7; position:relative; cursor:pointer; }.pf-market-upload-zone:hover { border-color:#8caa53; background:#f5f9ed; }.pf-market-upload-zone svg { color:#788d5c; }.pf-market-upload-zone strong { font-size:13px; }.pf-market-upload-zone span { font-size:11px; color:var(--pf-muted); font-weight:400; }.pf-market-upload-zone input { position:absolute; inset:0; width:100%; height:100%; opacity:0; cursor:pointer; }.pf-market-upload-zone:focus-within { outline:2px solid #6b8d16; outline-offset:2px; }.pf-market-upload-zone:has(input:disabled) { opacity:.55; cursor:not-allowed; }
+.pf-market-existing summary { font-size:12px; color:var(--pf-muted); cursor:pointer; padding:3px 0; }.pf-market-existing select { margin-top:12px; width:100%; }.pf-market-existing .pf-market-actions { margin:10px 0 0; }.pf-market-existing button { font-size:11px!important; padding:5px 9px!important; }.pf-market-upload-selection { font-size:12px; color:#5d742d; }.pf-market-upload-progress { display:grid; gap:7px; font-size:12px; color:var(--pf-muted); }.pf-market-upload-progress progress { width:100%; accent-color:#83aa34; height:5px; }
+.pf-market-actions,.pf-market-tabs { display:flex; flex-wrap:wrap; align-items:center; gap:10px; margin:20px 0; }.pf-market-tabs { padding:6px; background:#ebedf0; border-radius:12px; width:fit-content; max-width:100%; }.pf-market-tabs button { border:0!important; background:transparent!important; font-size:12px!important; padding:9px 14px!important; color:var(--pf-muted)!important; }.pf-market-tabs button[aria-pressed=true] { background:var(--pf-card)!important; color:var(--pf-ink)!important; box-shadow:0 2px 6px #1113180a; }
+.pf-market-workspace-toolbar { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:12px; margin-bottom:20px; }.pf-market-workspace-toolbar .pf-market-tabs { margin:0; }.pf-market-record-head { display:flex; align-items:center; justify-content:space-between; gap:15px; }.pf-market-record-head h2 { font-size:16px; overflow-wrap:anywhere; }.pf-market-record-head .pf-market-badge { flex-shrink:0; }.pf-market-record-note { padding:12px 15px; border-radius:8px; background:var(--pf-bg); }.pf-market-upload-selection { display:flex; align-items:center; gap:6px; }
+.pf-market>h1 { margin:28px 0 15px; }.pf-market>h2 { margin:24px 0 10px; }.pf-market>p { margin:10px 0; }.pf-market>.pf-market-form { background:var(--pf-card); border:1px solid var(--pf-line); padding:26px; border-radius:var(--pf-radius); }.pf-market>section:not([class]) { background:var(--pf-card); border:1px solid var(--pf-line); border-radius:var(--pf-radius); padding:24px; margin:22px 0; }
+.pf-market-detail-intro { display:grid; grid-template-columns:minmax(0,1fr) 280px; border:1px solid var(--pf-line); background:var(--pf-card); border-radius:14px; overflow:hidden; }.pf-market-detail-intro>div { padding:26px; }.pf-market-detail-intro p { margin-top:15px; color:var(--pf-muted); }.pf-market-detail-price { display:flex; flex-direction:column; gap:8px; background:#f2f6e9; border-left:1px solid #e4eadb; }.pf-market-detail-price>span { color:var(--pf-muted); font-size:12px; }.pf-market-detail-price strong { font-size:30px; letter-spacing:-1px; }.pf-market-detail-price small { font-size:11px; color:var(--pf-muted); }.pf-market-detail-section { border:1px solid var(--pf-line); border-radius:14px; background:var(--pf-card); margin:22px 0; padding:25px; }.pf-market-detail-section h2 { margin-bottom:13px; font-size:18px; }.pf-market-detail-section p { color:var(--pf-muted); margin:10px 0 18px; }.pf-market-page-heading h1 { overflow-wrap:anywhere; }
+@media(min-width:1101px) and (max-width:1350px) { .pf-market-shell .pf-nav { grid-template-columns:auto minmax(0,1fr) auto; gap:12px; }.pf-market-shell .pf-nav-center { justify-content:center; gap:14px; font-size:12px; }.pf-market-shell .pf-nav-right { gap:7px; } }
+@media(max-width:640px) { .pf-market-detail-intro { grid-template-columns:1fr; }.pf-market-detail-price { border-left:0; border-top:1px solid #e4eadb; }.pf-market>.pf-market-form { padding:20px 16px; } }
+.pf-market-notice { padding:14px 18px; background:#f3f7eb; color:#526338; border:1px solid #e0e9d1; border-radius:10px; margin:16px 0!important; font-size:12px; }
+.pf-market-video,.pf-market-cover { display:block; width:100%; max-width:800px; max-height:65vh; object-fit:contain; background:#171c19; border-radius:12px; margin:16px 0; }.pf-market-text,.pf-market-copy { white-space:pre-wrap; }
+.pf-market-modal { position:fixed; inset:0; background:#11131888; backdrop-filter:blur(5px); z-index:1000; display:flex; align-items:center; justify-content:center; padding:20px; overflow:auto; }.pf-market-modal section { background:var(--pf-card); border:1px solid var(--pf-line); border-radius:20px; box-shadow:0 24px 80px #0003; padding:28px; max-width:520px; width:100%; max-height:90vh; overflow:auto; }.pf-market-modal h2 { margin:20px 0 12px; }.pf-market-modal p { margin:10px 0; font-size:13px; }.pf-market-modal .pf-market-cover { max-width:240px; margin:20px auto; background:#fff; }.pf-market-copy { background:var(--pf-bg); border:1px solid var(--pf-line); border-radius:10px; padding:14px; }
+@media(max-width:1000px) { .pf-market-hero { padding:30px; }.pf-market-hero h1 { font-size:31px; }.pf-market-hero-art { transform:scale(.85); transform-origin:center; width:310px; }.pf-market-grid { grid-template-columns:repeat(2,minmax(0,1fr)); }.pf-market-editor-layout { grid-template-columns:minmax(0,1fr) 250px; gap:18px; }.pf-market-guide { padding:20px; }.pf-market-nav-hint { display:none; } }
+@media(max-width:760px) { .pf-market-hero { grid-template-columns:1fr; }.pf-market-hero-art { display:none; }.pf-market-editor-layout { grid-template-columns:1fr; }.pf-market-guide { position:static; }.pf-market-filter-bottom { gap:13px; }.pf-market-form-actions { flex-wrap:wrap; }.pf-market-principles { justify-content:flex-start; gap:12px 22px; font-size:11px; }.pf-market-publish-actions .pf-btn { padding:9px 10px; font-size:12px; } }
+@media(max-width:640px) { .pf-market-shell .pf-shell-main { padding:16px 16px 30px; }.pf-market { padding:0; }.pf-market-shell .pf-nav { padding:0 12px; gap:8px; }.pf-market-shell .pf-nav-right { gap:6px; }.pf-market-shell .pf-nav-right>.pf-nav-lang,.pf-market-shell .pf-nav-right>.pf-nav-github,.pf-market-shell .pf-nav-right>.pf-nav-help-btn,.pf-market-shell .pf-nav-right>.pf-btn { display:none; }.pf-market-top { flex-wrap:wrap; padding:8px 0 20px; gap:18px; }.pf-market-brand-icon { width:40px; height:40px; }.pf-market .pf-market-title { font-size:21px; }.pf-market-publish-actions { width:100%; }.pf-market-publish-actions .pf-btn { flex:1; }.pf-market-nav { width:100%; gap:0; justify-content:space-between; }.pf-market-nav a { font-size:12px; gap:6px; padding-bottom:13px; }.pf-market-nav svg { width:15px; }.pf-market-nav-row { margin-bottom:16px; }.pf-market-storage-note { align-items:flex-start; padding:10px 12px; margin-bottom:16px; font-size:11px; }.pf-market-storage-note svg { margin-top:2px; }.pf-market-hero { padding:27px 24px; min-height:0; border-radius:16px; }.pf-market-hero h1 { font-size:30px; }.pf-market-hero-copy>p { font-size:12px; }.pf-market-principles { margin:0 0 25px; padding:15px 4px; gap:10px; flex-direction:column; }.pf-market-section-heading p { font-size:12px; max-width:245px; }.pf-market-count { font-size:11px; }.pf-market-filter-top { padding:12px; gap:9px; flex-wrap:wrap; }.pf-market-search { flex-basis:100%; }.pf-market-filter-top select { flex:1; width:auto; }.pf-market-filter-top>.pf-btn { padding:10px 20px; }.pf-market-filter-bottom { padding:12px; gap:12px; }.pf-market-filter-label { display:none; }.pf-market-category { width:100%; }.pf-market .pf-market-category input { flex:1; width:auto; }.pf-market-price-filter { width:100%; gap:8px; }.pf-market .pf-market-price-filter input { flex:1; width:70px; }.pf-market .pf-market-reset { margin:0; }.pf-market-grid { grid-template-columns:1fr; }.pf-market-empty { padding:38px 20px; }.pf-market-empty p { font-size:12px; }.pf-market-pagination { gap:8px; }.pf-market-pagination>div { gap:9px; }.pf-market-field-row { grid-template-columns:1fr; gap:18px; }.pf-market-form-section { padding:20px 16px; }.pf-market-form-section>header { margin-bottom:20px; }.pf-market-form-actions { padding:18px 16px; }.pf-market-form-actions>.pf-btn { width:100%; }.pf-market-page-heading h1 { font-size:25px; }.pf-market-page-heading p { font-size:12px; }.pf-market-tabs { width:100%; gap:4px; }.pf-market-tabs button { flex:1 0 auto; }.pf-market-modal { padding:14px; }.pf-market-modal section { padding:22px; } }
+@media(prefers-reduced-motion:reduce) { .pf-market * { transition:none!important; } }
+/* 文件预览、授权签署沿用市场卡片与原站色彩。 */
+.pf-market-file-preview { margin: 12px 0; overflow: hidden; border: 1px solid #ddd; border-radius: 12px; background: #f6f6f2; }
+.pf-market-file-preview img, .pf-market-file-preview video { display: block; max-width: 100%; max-height: 480px; margin: 0 auto; object-fit: contain; }
+.pf-market-file-preview iframe { display: block; width: 100%; height: 480px; border: 0; background: white; }
+.pf-market-file-preview p, .pf-market-file-preview a { display: block; margin: 12px; }
+.pf-market-asset-preview { padding: 12px; border: 1px solid #ddd; border-radius: 12px; margin: 12px 0; }
+.pf-market-rights-route, .pf-market-authorization { padding: clamp(16px, 3vw, 28px); border: 1px solid #dedfd8; border-radius: 18px; background: #fff; margin: 20px 0; }
+.pf-market-rights-route h2, .pf-market-authorization h2 { font-size: 20px; margin: 0 0 16px; }
+.pf-market-rights-route select { padding: 10px; border: 1px solid #ccc; border-radius: 8px; max-width: 100%; }
+.pf-market-authorization details { margin: 16px 0; }
+.pf-market-authorization summary { cursor: pointer; font-weight: 600; }
+.pf-market-letter { white-space: pre-wrap; line-height: 1.9; padding: 16px; max-height: 420px; overflow: auto; background: #f5f5f0; border-radius: 10px; }
+.pf-market-signature { display: block; width: 100%; max-width: 800px; aspect-ratio: 10 / 3; border: 1px dashed #888; border-radius: 10px; background: #fff; touch-action: none; }
+@media (max-width: 600px) { .pf-market-file-preview iframe { height: 320px; } .pf-market-rights-route, .pf-market-authorization { padding: 16px; } }
+.pf-market-editor-main { min-width:0; }
+.pf-market-editor-main > .pf-market-form { margin-top:0; max-width:none; }
+.pf-market-editor-rights,.pf-market-publishing { border:1px solid var(--pf-line); border-radius:14px; background:var(--pf-card); padding:24px; margin:22px 0; min-width:0; }
+.pf-market-editor-rights > h2,.pf-market-publishing > h2 { margin-bottom:12px; }
+.pf-market-publish-steps { padding:0; margin:22px 0; display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:12px; list-style:none; }
+.pf-market-publish-steps li { display:flex; align-items:flex-start; gap:10px; padding:16px; background:#f6f7f3; border:1px solid var(--pf-line); border-radius:12px; min-width:0; }
+.pf-market-publish-steps li > span { font-size:12px; font-weight:700; padding:5px; border-radius:6px; background:#e7e9e0; }
+.pf-market-publish-steps li[data-complete=true] > span { background:var(--pf-lime); }
+.pf-market-publish-steps h3 { font-size:14px; margin-bottom:8px; }
+.pf-market-publish-steps p { font-size:12px; color:var(--pf-muted); margin:8px 0; }
+.pf-market-publish-steps a { display:inline-block; color:#496217; text-decoration:underline; margin-top:8px; font-size:13px; }
+.pf-market-inline-rights > summary { font-weight:650; padding:16px; background:#f2f6e9; border-radius:10px; cursor:pointer; }
+.pf-market-inline-rights .pf-market-form { max-width:none; background:var(--pf-card); padding:20px; border:1px solid var(--pf-line); border-radius:12px; }
+@media(max-width:1000px) { .pf-market-publish-steps { grid-template-columns:repeat(2,minmax(0,1fr)); } }
+@media(max-width:600px) { .pf-market-publish-steps { grid-template-columns:1fr; } .pf-market-editor-rights,.pf-market-publishing { padding:16px; } }
+
+/* 作品发现页:以影像为主,沿用 PrintFilm 的浅色与青绿视觉。 */
+.pf-discover-heading { display:flex; align-items:center; justify-content:space-between; gap:24px; padding:25px 0 32px; }
+.pf-discover-heading h1 { font-size:34px; letter-spacing:-1.2px; margin:10px 0; line-height:1.3; }
+.pf-discover-heading p { font-size:13px; color:var(--pf-muted); }
+.pf-market-discover>.pf-market-hero,.pf-market-discover>.pf-market-principles { display:none; }
+.pf-market-discover .pf-market-section-heading { margin-bottom:18px; }
+.pf-market-discover .pf-market-section-heading h2 { font-size:17px; }
+.pf-market-discover .pf-market-section-heading p { display:none; }
+.pf-market-discover .pf-market-filter-panel { background:transparent; border:0; border-radius:0; overflow:visible; margin-bottom:26px; }
+.pf-discover-categories { display:flex; gap:8px; overflow-x:auto; padding:0 0 20px; }
+.pf-market .pf-discover-categories button { white-space:nowrap; border:1px solid transparent; background:transparent; color:var(--pf-muted); padding:9px 20px; border-radius:24px; font-size:13px; cursor:pointer; }
+.pf-market .pf-discover-categories button:hover { background:var(--pf-card); color:var(--pf-ink); }
+.pf-market .pf-discover-categories button[aria-pressed=true] { background:var(--pf-ink); color:var(--pf-lime); }
+.pf-market-discover .pf-market-filter-top { padding:0; }
+.pf-market-discover .pf-market-search { background:var(--pf-card); border-radius:12px; }
+.pf-market-discover .pf-market-filter-bottom { border:0; padding:14px 0 0; gap:14px; }
+.pf-market-discover .pf-market-filter-label { display:none; }
+.pf-market-discover .pf-market-grid { grid-template-columns:repeat(3,minmax(0,1fr)); gap:28px 22px; }
+.pf-market .pf-market-discover .pf-market-item { border:0; background:transparent; border-radius:0; overflow:visible; }
+.pf-market-discover .pf-market-item:hover { box-shadow:none; transform:none; }
+.pf-market .pf-market-discover .pf-market-item-cover { aspect-ratio:4/3; border-radius:16px; isolation:isolate; }
+.pf-market-discover .pf-market-item-cover .pf-market-cover { transition:transform .35s ease; }
+.pf-market-discover .pf-market-item:hover .pf-market-cover { transform:scale(1.035); }
+.pf-market-discover .pf-market-cover-play { inset:0; width:auto; height:auto; border-radius:16px; background:linear-gradient(transparent 45%,#111a224d); color:white; opacity:0; transition:opacity .2s; }
+.pf-market-discover .pf-market-cover-play svg { padding:14px; box-sizing:content-box; border:1px solid #ffffff70; border-radius:50%; background:#11131844; backdrop-filter:blur(8px); }
+.pf-market-discover .pf-market-item:hover .pf-market-cover-play,.pf-market-discover .pf-market-item:focus-within .pf-market-cover-play { opacity:1; }
+.pf-market-discover .pf-market-item-body { padding:13px 2px 0; display:grid; grid-template-columns:minmax(0,1fr) auto; gap:10px; }
+.pf-market-discover .pf-market-category-tag,.pf-market-discover .pf-market-item-foot,.pf-market-discover .pf-market-item-price>a { display:none; }
+.pf-market-discover .pf-market-item h3 { grid-column:1/-1; margin:0; font-size:15px; font-weight:600; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }
+.pf-market .pf-market-discover .pf-market-author { margin:0; min-width:0; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }
+.pf-market-discover .pf-market-author>span { width:22px; height:22px; }
+.pf-market-discover .pf-market-item-price>div { gap:4px; justify-content:flex-end; }
+.pf-market-discover .pf-market-item-price strong { font-size:16px; font-weight:650; }
+.pf-market-discover .pf-market-item-price span { font-size:10px; }
+.pf-market-discover a:focus-visible,.pf-discover-categories button:focus-visible { outline:2px solid #719632; outline-offset:4px; }
+@media(min-width:1400px) { .pf-market-discover .pf-market-grid { grid-template-columns:repeat(4,minmax(0,1fr)); gap:26px 18px; } }
+@media(max-width:1000px) { .pf-market-discover .pf-market-grid { grid-template-columns:repeat(2,minmax(0,1fr)); } }
+@media(max-width:640px) { .pf-discover-heading { padding:15px 0 25px; gap:12px; align-items:flex-start; }.pf-discover-heading h1 { font-size:27px; }.pf-discover-heading p { font-size:12px; max-width:230px; }.pf-discover-heading>.pf-btn { font-size:12px; padding:10px 12px; flex-shrink:0; margin-top:30px; }.pf-discover-categories { gap:4px; padding-bottom:15px; }.pf-market .pf-discover-categories button { padding:8px 15px; }.pf-market-discover .pf-market-grid { gap:22px 12px; }.pf-market-discover .pf-market-item-body { display:flex; flex-wrap:wrap; gap:7px; }.pf-market-discover .pf-market-item h3 { width:100%; font-size:13px; }.pf-market-discover .pf-market-item-price { width:100%; }.pf-market-discover .pf-market-item-cover { border-radius:11px; }.pf-market-discover .pf-market-cover-play { opacity:1; background:transparent; inset:auto 9px 9px auto; }.pf-market-discover .pf-market-cover-play svg { width:12px; height:12px; padding:7px; } }
+@media(max-width:380px) { .pf-market-discover .pf-market-grid { grid-template-columns:1fr; }.pf-discover-heading { flex-wrap:wrap; }.pf-discover-heading>.pf-btn { margin:0; } }
+
+/* 买家作品详情与作者管理明确分离。 */
+.pf-market-buyer-layout { display:grid; grid-template-columns:minmax(0,1fr) 300px; gap:24px; align-items:start; }
+.pf-market-buyer-player { display:grid; align-items:center; min-height:360px; background:#111714; border-radius:16px; overflow:hidden; color:#cbd3cd; }
+.pf-market-buyer-player .pf-market-video { width:100%; max-width:none; max-height:70vh; margin:0; border-radius:0; }
+.pf-market-buyer-player>p { padding:24px; }
+.pf-market-buyer-info { display:flex; flex-direction:column; align-items:flex-start; gap:16px; border:1px solid var(--pf-line); background:var(--pf-card); border-radius:16px; padding:26px; }
+.pf-market-buyer-info h2 { font-size:22px; overflow-wrap:anywhere; }
+.pf-market-buyer-info>p,.pf-market-buyer-info>small { color:var(--pf-muted); font-size:12px; line-height:1.8; }
+.pf-market-buyer-price { display:flex; flex-direction:column; gap:8px; border-top:1px solid var(--pf-line); padding-top:20px; width:100%; }
+.pf-market-buyer-price>span { font-size:12px; color:var(--pf-muted); }
+.pf-market-buyer-price strong { font-size:32px; }
+.pf-market .pf-market-buyer-info>button:first-of-type { width:100%; background:var(--pf-lime); color:var(--pf-ink); border-color:transparent; padding:13px; font-weight:650; }
+@media(max-width:850px) { .pf-market-buyer-layout { grid-template-columns:1fr; }.pf-market-buyer-player { min-height:220px; }.pf-market-buyer-info { padding:22px; } }
+.pf-episode-tools { display:flex; align-items:center; gap:8px; margin-bottom:12px; }
+.pf-episode-tools button { padding:6px 10px; font-size:12px; }
+.pf-episode-tools span { margin-left:auto; color:var(--pf-muted); font-size:12px; }
+.pf-episode-fold { border:1px solid var(--pf-line); border-radius:12px; margin-bottom:10px; background:var(--pf-bg); }
+.pf-episode-fold-head { width:100%; display:flex; align-items:center; justify-content:space-between; gap:12px; padding:12px 14px; border:0; background:transparent; text-align:left; cursor:pointer; }
+.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-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; }
+.pf-market-kind-choice span { color:var(--pf-muted); font-size:13px; line-height:1.7; }
+@media(max-width:640px) { .pf-market-kind-choice { grid-template-columns:1fr; } }
+.pf-market-series-mark { display:grid; place-items:center; width:100%; height:100%; min-height:160px; color:#8ea084; }
+.pf-market-handoff { display:flex; justify-content:space-between; gap:12px; align-items:center; flex-wrap:wrap; padding:12px 0; border-bottom:1px solid var(--pf-line); }
+.pf-market-handoff div { display:flex; gap:8px; flex-wrap:wrap; }
+.pf-market-purchase-notice { padding:15px 17px; margin:16px 0; border:1px solid #e2e8d8; background:#f5f8ee; border-radius:12px; line-height:1.8; }
+.pf-market-purchase-notice strong { font-size:14px; }.pf-market-purchase-notice p { font-size:12px; color:var(--pf-muted); }
+.pf-series-stage { max-width:440px; margin:0 auto 18px; }
+.pf-series-stage .pf-market-video { width:100%; max-width:none; max-height:72vh; margin:0; border-radius:16px; background:#111714; }
+.pf-series-transport { display:flex; align-items:center; justify-content:space-between; gap:8px; margin-top:10px; }
+.pf-series-transport span { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:13px; }
+.pf-series-meta { display:grid; gap:8px; margin-bottom:18px; }
+.pf-series-meta p,.pf-series-meta small { margin:0; color:var(--pf-muted); font-size:13px; line-height:1.7; }
+.pf-series-ranges { display:flex; flex-wrap:wrap; gap:8px; margin-bottom:12px; }
+.pf-series-grid { display:grid; grid-template-columns:repeat(6,minmax(0,1fr)); gap:8px; margin-bottom:18px; }
+.pf-series-grid button { min-height:44px; border-radius:8px; font-weight:650; }
+.pf-series-ranges button[aria-pressed=true],.pf-series-grid button.is-current { background:var(--pf-lime); color:var(--pf-ink); border-color:transparent; }
+@media(min-width:720px) { .pf-series-grid { grid-template-columns:repeat(10,minmax(0,1fr)); } }
+@media(max-width:640px) { .pf-series-stage { max-width:none; } }
diff --git a/frontend/src/features/marketplace/shared.tsx b/frontend/src/features/marketplace/shared.tsx
new file mode 100644
index 0000000..992109e
--- /dev/null
+++ b/frontend/src/features/marketplace/shared.tsx
@@ -0,0 +1,77 @@
+import { useEffect, useState, type ReactNode } from 'react'
+import { NavLink } from 'react-router-dom'
+import { ChevronLeft, ChevronRight, CircleUserRound, Grid2X2, Info, LockKeyhole, Plus, Store, UsersRound } from 'lucide-react'
+import Button from '../../components/ui/Button'
+import { EmptyState } from './ui'
+import { request, media, money, type Listing } from './api'
+import { useMarketplace } from './hooks'
+import AssetPicker from './AssetPicker'
+
+// 提供加载、错误和关闭状态,避免关闭模块仍展示业务表单。
+export function Gate({ children }: { children: ReactNode }) {
+ const { capabilities, error } = useMarketplace()
+ if (error) return <p role="alert">{error}</p>
+ if (!capabilities) return <p role="status">正在读取服务状态…</p>
+ if (!capabilities.enabled) return <p>作品与招募模块尚未启用。</p>
+ return <><MarketNav />{!capabilities.storage_configured && <div className="pf-market-storage-note" role="note"><Info size={17} aria-hidden /><p><strong>文件服务暂未配置</strong><span>可保存文字草稿和无附件需求,上传及媒体发布暂不可用。</span></p></div>}{children}</>
+}
+
+// 登录保持原有登录页与回跳约定。
+export function NeedLogin({ children }: { children: ReactNode }) {
+ if (!localStorage.getItem('token')) return <EmptyState title="登录,开启你的创作机会" description="管理作品、发布需求,与更多创作者建立合作。" action="登录 / 注册" to={`/auth?next=${encodeURIComponent(window.location.pathname + window.location.search)}`} />
+ return children
+}
+
+// 统一下游页内导航,不接管原个人中心逻辑。
+export function MarketNav() {
+ return <><header className="pf-market-top"><div className="pf-market-brand"><span className="pf-market-brand-icon"><Store size={22} strokeWidth={1.7} /></span><div><p className="pf-market-eyebrow">PRINTFILM MARKETPLACE</p><p className="pf-market-title">数字资产市场</p></div></div><div className="pf-market-publish-actions"><Button to="/marketplace/recruits/new" variant="outline" size="sm" icon><Plus size={16} />发布招募</Button><Button to="/marketplace/works/new" variant="lime" size="sm" icon><Plus size={16} />发布作品</Button></div></header><div className="pf-market-nav-row"><nav className="pf-market-nav" aria-label="数字资产市场导航"><NavLink to="/marketplace" end><Grid2X2 size={17} />作品广场</NavLink><NavLink to="/marketplace/recruits" end><UsersRound size={18} />招募广场</NavLink><NavLink to="/marketplace/mine"><CircleUserRound size={17} />我的发布与通知</NavLink></nav><span className="pf-market-nav-hint"><LockKeyhole size={13} />权属核验 · 人工审核</span></div></>
+}
+
+// 列表均请求服务端分页,搜索时由调用方重置页码。
+export function Pager({ listing, page, change }: { listing: Listing | null; page: number; change: (value: number) => void }) {
+ const pages = listing ? Math.max(1, Math.ceil(listing.meta.total / listing.meta.page_size)) : 1
+ return <div className="pf-market-pagination"><span>共 {listing?.meta.total ?? 0} 条</span><div><button type="button" disabled={page <= 1} onClick={() => change(page - 1)}><ChevronLeft size={15} />上一页</button><span>{page} / {pages}</span><button type="button" disabled={!listing || page >= pages} onClick={() => change(page + 1)}>下一页<ChevronRight size={15} /></button></div></div>
+}
+
+// 有权访问后才签名;缩略图无权访问时不显示伪造封面。
+export function Media({ kind, id, purpose, video = false, autoPlay = false, onEnded }: { kind: string; id: number; purpose: string; video?: boolean; autoPlay?: boolean; onEnded?: () => void }) {
+ const [url, setUrl] = useState('')
+ const [error, setError] = useState('')
+ const [reload, setReload] = useState(0)
+ useEffect(() => { let active = true; setUrl(''); setError(''); media(kind, id, purpose).then(value => { if (active) setUrl(value) }).catch(e => { if (active) setError(e.message) }); return () => { active = false } }, [kind, id, purpose, reload])
+ if (error) return <p role="alert">{error}<button type="button" onClick={() => setReload(reload + 1)}>重试</button></p>
+ if (!url) return <p role="status">正在获取媒体…</p>
+ return video ? <video className="pf-market-video" src={url} controls controlsList="nodownload" preload="metadata" autoPlay={autoPlay} onEnded={onEnded} onError={() => setError('视频链接可能已过期,请重试')} /> : <img className="pf-market-cover" src={url} alt="作品或业务附件" onError={() => setError('图片链接可能已过期,请重试')} />
+}
+
+// 购买咨询只展示真实客服;不创建交易或自动授予权益。
+export function Contact({ kind, id, disabled = false, label }: { kind: string; id: number; disabled?: boolean; label?: string }) {
+ const [detail, setDetail] = useState<{ reference: string; title: string; price_fen: number | null; name: string; wechat: string; hours: string; notice: string } | null>(null)
+ const [error, setError] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [copyMessage, setCopyMessage] = useState('')
+ // 用户主动咨询才记录业务意向。
+ async function open() {
+ setBusy(true); setError('')
+ try { setDetail(await request('/consultations', 'POST', { target_type: kind, target_id: id })) }
+ catch (e) { setError((e as Error).message) }
+ finally { setBusy(false) }
+ }
+ // 剪贴板不可用时保留可手动选择的咨询文本。
+ async function copy(text: string) {
+ try { await navigator.clipboard.writeText(text); setCopyMessage('已复制') }
+ catch { setCopyMessage('复制失败,请选中下方文字手动复制') }
+ }
+ const text = detail ? `${detail.reference}|${detail.title}|${detail.price_fen === null ? '' : money(detail.price_fen)}|${window.location.href}` : ''
+ return <><button type="button" disabled={disabled || busy} onClick={open}>{disabled ? '待完成权属核验' : busy ? '正在获取客服…' : label ? label : kind === 'case' ? '联系客服协办' : kind === 'recruit' ? '联系客服接单' : '联系客服购买'}</button>{error && <p role="alert">{error}</p>}{detail && <div className="pf-market-modal" role="dialog" aria-modal="true" aria-label="联系客服" onKeyDown={e => { if (e.key === 'Escape') setDetail(null) }}><section><button type="button" autoFocus onClick={() => setDetail(null)}>关闭</button><h2>{detail.name}</h2><Media kind="support" id={1} purpose="qr" /><p>微信:{detail.wechat} · {detail.hours}</p><p>{detail.notice}</p>{(kind === 'work' || kind === 'submission' || kind === 'series_episode') && <div className="pf-market-purchase-notice"><strong>版权购买须知</strong><p>如需购买作品版权(著作财产权转让),须另行签订书面转让合同,并按约定办理版权转让及相关手续,可能产生转让办理、登记或服务等费用。具体流程、费用项目及承担方请先与客服确认。</p><p>页面参考价不代表已包含上述费用。仅购买使用授权不等于取得作品版权。</p></div>}<p className="pf-market-copy">{text}</p><button type="button" onClick={() => copy(text)}>复制咨询信息</button><p role="status">{copyMessage}</p><p>可在二维码上右键或长按保存图片。</p></section></div>}</>
+}
+
+// 举报证据可后续由平台要求补充,联系方式不公开。
+export function ReportForm({ kind, id }: { kind: string; id: number }) {
+ const [open, setOpen] = useState(false)
+ const [message, setMessage] = useState('')
+ const [evidence, setEvidence] = useState<number[]>([])
+ return <><button type="button" onClick={() => setOpen(!open)}>举报</button>{open && <NeedLogin><form className="pf-market-form" onSubmit={async e => { e.preventDefault(); const form = new FormData(e.currentTarget); try { await request('/reports', 'POST', { target_type: kind, target_id: id, statement: form.get('statement'), contact: form.get('contact'), evidence_ids: evidence }); setMessage('已提交,平台会核查并发送站内通知') } catch (error) { setMessage((error as Error).message) } }}><label>举报说明(至少10字)<textarea name="statement" required minLength={10} maxLength={5000} /></label><label>联系渠道(不会公开)<input name="contact" required maxLength={200} /></label><p>证明材料:{evidence.map(value => <button type="button" key={value} onClick={() => setEvidence(evidence.filter(item => item !== value))}>移除 #{value}</button>)}</p>{evidence.length < 10 && <AssetPicker kind="document" value={null} onChange={value => setEvidence(previous => [...new Set([...previous, value])].slice(0, 10))} title="添加举报证明(可选)" />}<button type="submit">提交举报</button><p role="status">{message}</p></form></NeedLogin>}</>
+}
+
+
diff --git a/frontend/src/features/marketplace/ui.tsx b/frontend/src/features/marketplace/ui.tsx
new file mode 100644
index 0000000..b70447d
--- /dev/null
+++ b/frontend/src/features/marketplace/ui.tsx
@@ -0,0 +1,26 @@
+import type { ReactNode } from 'react'
+import { ArrowLeft, ArrowUpRight, FolderOpen, ShieldCheck } from 'lucide-react'
+import { Link } from 'react-router-dom'
+import Button from '../../components/ui/Button'
+
+// 模块内统一页头,明确当前任务和返回路径。
+export function PageHeading({ title, description, back, backLabel = '返回广场' }: { title: string; description: string; back?: string; backLabel?: string }) {
+ return <header className="pf-market-page-heading">{back && <Link className="pf-market-back" to={back}><ArrowLeft size={15} />{backLabel}</Link>}<h1>{title}</h1><p>{description}</p></header>
+}
+
+// 空数据、空搜索和个人工作台共用真实空态,不填充示例作品。
+export function EmptyState({ title, description, action, to, children }: { title: string; description: string; action?: string; to?: string; children?: ReactNode }) {
+ return <div className="pf-market-empty"><div className="pf-market-empty-icon" aria-hidden><FolderOpen size={30} strokeWidth={1.4} /></div><h3>{title}</h3><p>{description}</p>{action && to && <Button to={to} variant="dark" icon>{action}<ArrowUpRight size={16} /></Button>}{children}</div>
+}
+
+// 发布表单按内容分组,数字仅表示填写顺序。
+export function FormSection({ step, title, description, children }: { step: string; title: string; description?: string; children: ReactNode }) {
+ return <section className="pf-market-form-section"><header><span>{step}</span><div><h2>{title}</h2>{description && <p>{description}</p>}</div></header><div className="pf-market-fields">{children}</div></section>
+}
+
+// 侧栏展示实际发布规则,不把流程说明显示为已完成状态。
+export function PublishGuide({ recruit = false }: { recruit?: boolean }) {
+ const steps = recruit ? [['说明需求', '写清用途、预算和交付要求。'], ['内容审核', '审核通过后进入招募广场。'], ['联系客服', '创作者先联系客服表达接单意向。'], ['线下合作', '客服协调需求、预算、合同及交付。']] : [['上传与介绍', '上传视频,完善作品资料。'], ['权属核验', '本平台签授权函,其他平台交证明,无证明联系客服。'], ['内容审核', '审核通过后,由你主动上架。'], ['客服撮合', '授权、合同与交付在线下确认。']]
+ return <aside className="pf-market-guide"><div className="pf-market-guide-heading"><ShieldCheck size={21} /><h2>{recruit ? '从需求到合作' : '从作品到市场'}</h2></div><ol>{steps.map(([title, description], index) => <li key={title}><span>{String(index + 1).padStart(2, '0')}</span><div><strong>{title}</strong><p>{description}</p></div></li>)}</ol><div className="pf-market-guide-note"><strong>{recruit ? '先明确,再合作' : '让授权更清楚'}</strong><p>{recruit ? '创作者通过平台客服接单。具体合作条件在线下协商确认,咨询不代表已接单或成交。' : '登记证书不能代替素材授权。音乐、字体、肖像等涉及的权利,需要逐项说明。'}</p></div></aside>
+}
+
diff --git a/frontend/src/features/marketplace/useCategories.ts b/frontend/src/features/marketplace/useCategories.ts
new file mode 100644
index 0000000..db7d1bc
--- /dev/null
+++ b/frontend/src/features/marketplace/useCategories.ts
@@ -0,0 +1,14 @@
+import { useEffect, useState } from 'react'
+import { request } from './api'
+
+export function useCategories() {
+ const [names, setNames] = useState<string[]>([])
+ const [error, setError] = useState('')
+ useEffect(() => {
+ let active = true
+ request<{ names: string[] }>('/categories').then(value => { if (active) setNames(value.names) })
+ .catch(e => { if (active) setError(`分类加载失败:${e.message},请刷新重试。`) })
+ return () => { active = false }
+ }, [])
+ return { names, error }
+}
diff --git a/frontend/src/pages/HistoryPage.tsx b/frontend/src/pages/HistoryPage.tsx
index 68f780d..bb3c8da 100644
--- a/frontend/src/pages/HistoryPage.tsx
+++ b/frontend/src/pages/HistoryPage.tsx
@@ -465,6 +465,15 @@ export default function HistoryPage() {
<IconDownload size={14} />
{busyId === p.id ? t('common.downloading') : t('common.download')}
</button>
+ <button
+ type="button"
+ className="pf-btn-text"
+ disabled={!p.final_video_url}
+ onClick={() => nav(`/marketplace/from-printfilm?project=${p.id}`)}
+ >
+ <IconSend size={14} />
+ 发布到市场
+ </button>
<button
type="button"
className="pf-icon-btn danger"
diff --git a/frontend/src/pages/drama/EpisodeEditPage.tsx b/frontend/src/pages/drama/EpisodeEditPage.tsx
index aed0e4b..361618a 100644
--- a/frontend/src/pages/drama/EpisodeEditPage.tsx
+++ b/frontend/src/pages/drama/EpisodeEditPage.tsx
@@ -1727,6 +1727,7 @@ function EpisodeEditInner() {
onPlayingFragmentChange={handlePlayingFragmentChange}
aspectRatio={aspectRatio}
episodeId={episode?.id}
+ projectId={projectId}
episodeName={episode?.name || '本集'}
subtitleMode={subtitleMode}
onOpenStoryboard={openEpisodeStoryboard}
diff --git a/frontend/src/pages/drama/EpisodeEditSidePane.tsx b/frontend/src/pages/drama/EpisodeEditSidePane.tsx
index bd9cd6f..37c0b8a 100644
--- a/frontend/src/pages/drama/EpisodeEditSidePane.tsx
+++ b/frontend/src/pages/drama/EpisodeEditSidePane.tsx
@@ -1,6 +1,7 @@
/** 分集编辑右侧:分段视频预览 + 入口打开全屏分镜画布 */
import { useState } from 'react'
import { Download, Loader2 } from 'lucide-react'
+import { useNavigate } from 'react-router-dom'
import type { DramaFragment } from '../../api/drama'
import { DramaSubtitleBoard } from '../../components/drama/DramaSubtitleBoard'
import { DramaFragmentSegmentedVideoPlayer } from '../../components/drama/DramaFragmentSegmentedVideoPlayer'
@@ -20,6 +21,7 @@ type Props = {
onPlayingFragmentChange: (fragmentId: number) => void
aspectRatio: string
episodeId?: number
+ projectId?: string
episodeName?: string
subtitleMode: DramaSubtitleMode
onOpenStoryboard: () => void
@@ -47,6 +49,7 @@ export function EpisodeEditSidePane({
onPlayingFragmentChange,
aspectRatio,
episodeId,
+ projectId,
episodeName = '本集',
subtitleMode,
onOpenStoryboard,
@@ -62,6 +65,7 @@ export function EpisodeEditSidePane({
* composeProgress 拉取/拼接进度
* composeError 失败原因
*/
+ const navigate = useNavigate()
const [composeBusy, setComposeBusy] = useState(false)
const [composeProgress, setComposeProgress] = useState<EpisodeComposeProgress | null>(null)
const [composeError, setComposeError] = useState('')
@@ -124,6 +128,15 @@ export function EpisodeEditSidePane({
)}
{composeProgressLabel(composeProgress, composeBusy)}
</button>
+ {projectId && episodeId && fragments.some(item => item.video) ? (
+ <button
+ type="button"
+ className="drama-ep-compose-btn drama-ep-compose-btn--header"
+ onClick={() => navigate(`/marketplace/from-printfilm?drama=${projectId}&episode=${episodeId}`)}
+ >
+ 发布到数字资产市场
+ </button>
+ ) : null}
</div>
{composeError ? <p className="drama-ep-compose-error drama-ep-compose-error--header">{composeError}</p> : null}
diff --git a/frontend/src/pages/studio/EditorPage.tsx b/frontend/src/pages/studio/EditorPage.tsx
index c340007..cbade58 100644
--- a/frontend/src/pages/studio/EditorPage.tsx
+++ b/frontend/src/pages/studio/EditorPage.tsx
@@ -253,6 +253,14 @@ export default function EditorPage() {
>
导出视频
</button>
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-sm"
+ disabled={!project.final_video_url}
+ onClick={() => nav(`/marketplace/from-printfilm?project=${project.id}`)}
+ >
+ 发布到数字资产市场
+ </button>
</div>
</div>
diff --git a/frontend/src/pages/studio/StoryboardPage.tsx b/frontend/src/pages/studio/StoryboardPage.tsx
index 7c254f4..3e247b5 100644
--- a/frontend/src/pages/studio/StoryboardPage.tsx
+++ b/frontend/src/pages/studio/StoryboardPage.tsx
@@ -976,9 +976,14 @@ title="用当前镜头重新拼接"
</button>
) : null}
{hasFinal ? (
- <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" onClick={openFinalPreview}>
- 预览成片
- </button>
+ <>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" onClick={openFinalPreview}>
+ 预览成片
+ </button>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" onClick={() => nav(`/marketplace/from-printfilm?project=${project.id}`)}>
+ 发布到数字资产市场
+ </button>
+ </>
) : (
<button
type="button"