PRINTFILM: AI short-video marketing and AI short-drama creation platform
授权函修改
增瑞 田ccb72afca05f
diff --git a/admin/src/features/marketplace/MarketplaceAdmin.tsx b/admin/src/features/marketplace/MarketplaceAdmin.tsxindex d7bc466..668b423 100644--- a/admin/src/features/marketplace/MarketplaceAdmin.tsx+++ b/admin/src/features/marketplace/MarketplaceAdmin.tsx@@ -1,6 +1,6 @@import CategoryForm from './CategoryForm'import { useEffect, useState, type FormEvent } from 'react'-import { request, assetUrl, useMarketplaceEnabled, type Item, type Listing } from './api'+import { request, assetUrl, letterFile, 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'@@ -32,10 +32,29 @@ function WorkPreviewLink({ id }: { id: number }) {return <div className="market-ops-file"><button type="button" 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 [filename, setFilename] = useState('授权函.pdf'); const [error, setError] = useState('')const id = details && typeof details === 'object' && 'authorization_id' in details ? Number(details.authorization_id) : 0+ const [preview, setPreview] = useState<{ url: string; image: boolean } | null>(null)+ const [error, setError] = useState('')+ useEffect(() => {+ if (!id) return+ let active = true+ let objectUrl = ''+ letterFile(id).then(blob => {+ if (!active) return+ objectUrl = URL.createObjectURL(blob)+ setPreview({ url: objectUrl, image: blob.type.startsWith('image/') })+ }).catch(e => { if (active) setError((e as Error).message) })+ return () => { active = false; if (objectUrl) URL.revokeObjectURL(objectUrl) }+ }, [id])if (!id) return null- return <div className="market-ops-file"><button type="button" onClick={async () => { try { const value = await request<{ url: string; filename?: string }>(`/api/marketplace/authorizations/${id}/letter`); setUrl(value.url); setFilename(value.filename || '授权函.pdf'); setError('') } catch (e) { setError((e as Error).message) } }}>查看授权函</button>{url && (filename.endsWith('.pdf') ? <a href={url} target="_blank" rel="noreferrer">下载授权函 PDF</a> : <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 downloadLetter() {+ if (!preview) return+ const link = document.createElement('a')+ link.href = preview.url+ link.download = preview.image ? '授权函.png' : '授权函.pdf'+ link.click()+ }+ return <div className="market-ops-file"><button type="button" onClick={downloadLetter} disabled={!preview}>下载授权函</button>{preview && (preview.image ? <img src={preview.url} alt="已签署授权函" /> : <iframe className="market-ops-letter-frame" src={preview.url} title="授权函预览" />)}{error && <p role="alert">{error}</p>}</div>}function CoverImage({ id }: { id?: number }) {diff --git a/admin/src/features/marketplace/api.ts b/admin/src/features/marketplace/api.tsindex 2a1ff44..eb0387e 100644--- a/admin/src/features/marketplace/api.ts+++ b/admin/src/features/marketplace/api.ts@@ -12,6 +12,21 @@ export async function request<T>(path: string, method = 'GET', body?: unknown):return value as T}+/** 管理端在线打开授权函,不把 OSS 地址交给浏览器直接下载。 */+export async function letterFile(id: number): Promise<Blob> {+ let response: Response+ try {+ response = await fetch(`/api/marketplace/authorizations/${id}/file`, { headers: { Authorization: `Bearer ${getToken() ?? ''}` } })+ } catch {+ throw new Error('授权函暂时无法打开')+ }+ if (!response.ok) {+ const value = await response.json().catch(() => ({}))+ throw new Error(typeof value.detail === 'string' ? value.detail : '授权函暂时无法打开')+ }+ return response.blob()+}+// 管理端菜单也由服务端能力发现控制,不另造前端开关。export function useMarketplaceEnabled() {const [enabled, setEnabled] = useState(false)diff --git a/admin/src/features/marketplace/marketplace-admin.css b/admin/src/features/marketplace/marketplace-admin.cssindex 9793ea9..fe3ee9d 100644--- a/admin/src/features/marketplace/marketplace-admin.css+++ b/admin/src/features/marketplace/marketplace-admin.css@@ -53,6 +53,7 @@.market-ops-back { align-self:flex-start; }.market-ops-file { display:flex; flex-wrap:wrap; gap:8px; align-items:center; }.market-ops-file video,.market-ops-file img { flex-basis:100%; width:100%; }+.market-ops-letter-frame { flex-basis:100%; width:100%; height:72vh; min-height:480px; border:0; background:#fff; border-radius:12px; }.market-ops-file button,.market-ops-file a { align-self:flex-start; border:1px solid #b7d0c2; background:#f3faf6; color:#27624e; text-decoration:none; border-radius:8px; padding:8px 14px; font-size:13px; }.market-ops-stage-layout { display:grid; grid-template-columns:minmax(0,1fr) 340px; gap:22px; align-items:start; }.market-ops-stage-player { min-height:360px; background:#111714; border-radius:16px; overflow:hidden; display:flex; flex-direction:column; color:#d5ddd6; }diff --git a/backend/app/marketplace/authorization.py b/backend/app/marketplace/authorization.pyindex dab03dd..6cccf19 100644--- a/backend/app/marketplace/authorization.py+++ b/backend/app/marketplace/authorization.py@@ -5,9 +5,11 @@ import loggingfrom pathlib import Pathimport tempfilefrom typing import Annotated, Literal+from urllib.parse import quoteimport uuidfrom fastapi import APIRouter, Depends, HTTPException, Request+from fastapi.responses import Responsefrom pydantic import Field, model_validatorfrom sqlalchemy import selectfrom sqlalchemy.exc import IntegrityError@@ -15,21 +17,13 @@ from sqlalchemy.exc import IntegrityErrorfrom . import storagefrom .config import get_marketplace_settings, resolve_cjk_fontfrom .dependencies import Actor, DB, storage_ready+from .letter_template import BODY, NOTICES, TITLE, VERSION, archived_textfrom .models import Authorizationfrom .schemas import Inputfrom .service import data, event, fail, nowlogger = logging.getLogger("marketplace.authorization")-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)]@@ -38,6 +32,9 @@ class SignInput(Input):template_version: str = Field(max_length=60)signer_name: str = Field(min_length=2, max_length=80)accepted_terms: Literal[True]+ adult: Literal[True]+ read_all: Literal[True]+ accept_key: Literal[True]strokes: list[Stroke] = Field(min_length=1, max_length=40)@model_validator(mode="after")@@ -118,7 +115,7 @@ def _write_letter(path: Path, font_name: str, body: SignInput, signed_at: str, odocument.setTitle(TITLE)document.setFont(font_name, size)y = page_height - margin- paragraphs = [TITLE, f"版本:{VERSION}", *BODY.splitlines(), f"签署人:{body.signer_name}", f"账号:{owner_id} 签署时间(UTC):{signed_at}", "手写签名:"]+ paragraphs = [TITLE, f"版本:{VERSION}", *archived_text().splitlines(), f"签署人:{body.signer_name}", f"账号:{owner_id} 签署时间(UTC):{signed_at}", "手写签名:"]for paragraph in paragraphs:for line in _wrap(paragraph, font_name, size, text_width) or [""]:if y < margin + 150:@@ -149,7 +146,7 @@ def _write_letter(path: Path, font_name: str, body: SignInput, signed_at: str, o@router.get("/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))}+ return {"template": {"version": VERSION, "title": TITLE, "notices": list(NOTICES), "body": BODY}, "current": summary(await current(db, user.id))}@router.post("/authorization", response_model=dict, dependencies=[Depends(storage_ready)])@@ -161,8 +158,9 @@ async def sign(body: SignInput, request: Request, db: DB, user: Actor):return summary(existing)signed_at = now()letter_key = await asyncio.to_thread(render_and_store, body, signed_at.isoformat(), user.id)+ text = archived_text()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=letter_key,+ body=text, body_hash=hashlib.sha256(text.encode()).hexdigest(), signature_key=letter_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)@@ -189,3 +187,27 @@ async def letter(record_id: int, db: DB, user: Actor):event(db, user.id, "authorization", item.id, "read")await db.commit()return {"url": url, "expires_in": get_marketplace_settings().signed_url_seconds, "filename": "授权函.pdf" if pdf else "授权函.png"}+++def _disposition(filename: str, download: bool) -> str:+ """预览用 inline,只有明确下载时才用 attachment。"""+ encoded = quote(filename)+ kind = "attachment" if download else "inline"+ ascii_name = "letter.pdf" if filename.endswith(".pdf") else "letter.png"+ return f"{kind}; filename=\"{ascii_name}\"; filename*=UTF-8''{encoded}"++[email protected]("/authorizations/{record_id}/file", dependencies=[Depends(storage_ready)])+async def letter_file(record_id: int, db: DB, user: Actor, download: bool = False):+ """把已签署授权函以文件流返回。默认在线打开,download=true 时才作为附件下载。"""+ item = await db.get(Authorization, record_id)+ if not item or (item.owner_id != user.id and user.role != "admin"):+ fail("授权函不存在或无权查看", 404)+ pdf = item.letter_key.lower().endswith(".pdf")+ payload = await asyncio.to_thread(storage.read, item.letter_key)+ filename = "授权函.pdf" if pdf else "授权函.png"+ event(db, user.id, "authorization", item.id, "download" if download else "preview")+ await db.commit()+ return Response(content=payload, media_type="application/pdf" if pdf else "image/png", headers={+ "Content-Disposition": _disposition(filename, download), "Cache-Control": "private, no-store",+ })diff --git a/backend/app/marketplace/letter_template.py b/backend/app/marketplace/letter_template.pynew file mode 100644index 0000000..71e47f1--- /dev/null+++ b/backend/app/marketplace/letter_template.py@@ -0,0 +1,111 @@+"""PrintFilm 作品授权协议文本。结构参照完整格式合同,交易安排按数字资产市场的客服撮合规则书写。"""++VERSION = "printfilm-marketplace-2026-10-v2"+TITLE = "PRINTFILM 数字资产市场 PrintFilm 生成作品授权使用协议"+NOTICES = (+ "本协议为格式条款。请完整阅读。第7、8、10、11、13、15条加重您的义务或限制您的权利,签署前须单独勾选确认。",+ "屏幕手写签名属于电子签名和数据电文,不等于《电子签名法》规定的可靠电子签名(数字证书)。双方同意其构成书面形式,具有合同效力。",+ "本协议只覆盖您声明为 PrintFilm 生成并提交到数字资产市场的作品,不含其他平台来源作品。",+ "条款更新后须重新签署。未重签的,不得再把新的 PrintFilm 作品提交审核。",+)+BODY = """重要提示:本协议由平台事先拟定,属于《中华人民共和国民法典》所称格式条款。平台已通过单独列举和勾选确认的方式,提请您注意免除或减轻平台责任、加重您责任、限制您主要权利的条款。您勾选并手写签名,即视为已阅读、理解并同意全部条款。++第一条 协议主体与订立方式+1.1 授权方(下称「您」)为在 PRINTFILM 注册并完成登录的用户。签署时应填写与有效身份证件一致的真实姓名,保证已年满十八周岁且具有完全民事行为能力;如为组织用户,签署人保证已获合法授权。+1.2 被授权方(下称「平台」)为 PRINTFILM 数字资产市场的运营方,包括其关联公司以及为履行本协议而必要的技术、存储、审核和客服合作方。+1.3 双方同意以数据电文订立本协议,适用《中华人民共和国民法典》《中华人民共和国电子签名法》。您在账户下阅读本协议、勾选确认并手写签署,构成真实意思表示。本协议、签署记录、签名、账号信息、IP 地址和用户代理,可作为认定权利义务的证据。+1.4 您知悉:屏幕手写签名不是由电子认证服务机构签发的可靠电子签名。双方仍确认该签署具有合同效力。发生争议时,您不得仅以未当面签署纸质合同或未使用数字证书为由,主张本协议不成立或不约束您。++第二条 定义+2.1 「PrintFilm 作品」指您声明来源为 PrintFilm 生成,并提交至数字资产市场的视频及其标题、简介、封面、字幕、音频和相关素材。+2.2 「其他平台作品」须按平台另行要求提交权属证明,不适用本协议的授权范围。+2.3 「使用」包括存储、转码、复制、截取、添加标识、展示、播放、缓存、备份,以及为审核、安全和履行本协议所必要的技术处理。++第三条 授权对象+3.1 本协议覆盖您在有效期内提交的全部 PrintFilm 作品。账号签署一次后,后续同类作品可引用本次存档,无需逐件另签纸质授权函。+3.2 每件作品提交审核时,平台固化当时有效的协议版本,作为该作品的授权依据。您此后重签,不影响已经固化到既有作品上的授权,法律另有规定或双方另有书面约定的除外。+3.3 其他平台作品、未提交成功的文件,不在本协议范围内。++第四条 权利归属与授权性质+4.1 除法律另有规定外,作品的著作权及其他合法权益由权利人享有。本协议是许可使用,不是著作权转让,也不构成劳动、劳务、合伙或职务作品约定。+4.2 您授予平台一项普通、非独占、全球范围内的许可,仅可转许可给履行本协议所必要的服务方。您仍可自行使用作品,或在不损害本协议的前提下另行许可他人。+4.3 发表权、署名权、修改权和保护作品完整权依法不得转让。您同意平台为传播、审核、合规和展示之必要,进行技术性裁剪、转码和添加平台标识。平台不得歪曲、篡改作品原意。+4.4 您保证有权作出本授权。如您不是唯一权利人,您保证已取得其他权利人足以覆盖本协议的许可。++第五条 授权权利清单+就 PrintFilm 作品,您授权平台在本协议目的范围内行使下列权利:+(1)复制权:存储、转码、制作副本和封面;+(2)信息网络传播权:在平台向公众提供,使公众可以在选定的时间和地点获得;+(3)放映权:在平台内播放、演示;+(4)为审核、安全、适配终端所作的必要编辑;+(5)向云存储、内容分发和客服等服务方提供履行本协议所必要的副本或访问能力。+未经您另行书面同意,平台不得把作品用于与本市场展示、审核、安全和客服撮合无关的对外素材销售,也不得把作品单独作为对外提供的生成式人工智能基础模型训练集。平台可为审核、侵权比对和安全风控进行内部分析。++第六条 展示与交易安排+6.1 平台可将作品用于市场展示、审核、投诉处理、安全审计和监管配合。+6.2 作品标价是人民币参考价。具体授权范围、期限、地域、价格、合同、收款和成片交付,由相关方通过平台客服协调后线下确认。+6.3 审核通过、上架或联系客服,都不构成版权转让,也不构成购买、再许可或成交。+6.4 您知悉:在您选择上架期间,公众可按平台当时的播放规则观看作品。您下架后,平台停止新的公开展示;已经发出的短时播放链接在到期后失效。++第七条 权利保证(重点条款)+7.1 您保证并承诺:+(1)作品由您合法创作或合法取得,已获得著作权人、邻接权人、表演者、肖像权人、姓名权人、商标权人及其他必要权利人的授权,授权范围足以覆盖本协议;+(2)如作品全部或部分由人工智能生成或经深度合成,您对提示词、输入素材、参考画面、音色、人脸、商标、音乐、字体和台词均有合法来源,且不存在虚假权利声明;+(3)作品不侵犯任何第三人的著作权、商标权、肖像权、名誉权、隐私权、个人信息权益或其他合法权益;+(4)作品不包含法律、行政法规禁止发布或传输的信息;+(5)本授权不违反您与任何第三方的合同或职务作品安排。+7.2 无论将来如何认定生成式人工智能内容的著作权归属,您均保证平台按本协议使用作品不构成对第三方的侵权,并自行承担由此产生的责任。+7.3 您应按法律及监管要求配合对人工智能生成内容进行标识和核验。++第八条 禁止行为(重点条款)+未经平台书面同意,您不得上传无权授权的内容,规避审核,伪造授权或身份,或利用平台从事违法活动。违反本条的,平台可停止服务、下架作品,并保留追究责任的权利。++第九条 审核、下架与投诉+9.1 平台可以在事前、事中、事后审核作品。审核通过不表示平台确认权利真实或内容合法,也不减轻您的保证责任。+9.2 平台收到投诉、监管要求,或有合理理由认为作品侵权、违法或违约的,可以暂停展示、播放和咨询,并要求您补充材料。+9.3 您应按要求在合理期限内提交权属证明。逾期或证明不足的,平台可以维持下架。+9.4 为履行法定义务,平台可以向监管机关、司法机关提供与案件相关的作品、账号和签署记录。++第十条 赔偿责任(重点条款)+10.1 因您违反保证、无权授权或内容违法,导致第三方向平台、关联方或服务商主张权利、投诉、处罚或提起诉讼的,您应负责处理,并赔偿因此产生的赔偿金、罚款、和解款、律师费和合理支出。+10.2 平台因故意或重大过失造成您损失的,依法承担相应责任。法律规定不得预先免除的责任,任何条款都不得解释为免除。++第十一条 个人信息(重点条款)+11.1 为订立和履行本协议、核验身份、处理争议和配合监管,平台可以处理您的账号、真实姓名、签名、IP 地址和必要的访问记录。处理规则遵循《中华人民共和国个人信息保护法》。+11.2 您保证所填真实姓名准确。平台发现明显不符的,可以要求补充核验,并在完成前限制提交或展示。+11.3 签署记录至少保存至本协议终止后三年,或法律要求的更长期限。++第十二条 电子存证+12.1 平台保存协议版本、全文或其哈希、签署后的协议文件、签署时间、账号、IP 地址和用户代理。+12.2 您应妥善保管账号。在您证明账号被盗用之前,使用该账号完成的签署视为您本人行为。++第十三条 生效、变更与终止(重点条款)+13.1 本协议自您勾选确认并完成手写签署时生效。+13.2 平台更新协议后会更换版本号。新版本生效后,您须重新签署,才能继续提交新的 PrintFilm 作品。未重签不影响已经固化到既有作品上的授权。+13.3 您可以停止提交并下架自己的作品。下架停止新的公开展示,不追溯已经依法留存的签署记录。+13.4 您严重违约、内容违法或平台依法停止服务的,平台可以终止本协议。第7、8、10、11、12、15、16条在终止后继续有效。++第十四条 税费+您因作品获得的收入,应依法申报并缴纳税费。平台依法负有代扣代缴义务的,可以代扣代缴。++第十五条 违约(重点条款)+15.1 一方违约的,守约方可以要求停止违约、采取补救措施,并赔偿因此受到的直接损失。+15.2 因自然灾害、法律法规变化、政府行为或基础云服务故障等不能履行的,根据影响程度部分或全部免除责任,但法律另有规定的除外。+15.3 平台已对重点条款作出提示。您不得仅以未仔细阅读或属于格式条款为由拒绝履行。++第十六条 法律适用与争议解决+16.1 本协议适用中华人民共和国法律,不含冲突规范。+16.2 因本协议发生争议,双方应先协商。协商不成的,任何一方可以向平台运营方住所地有管辖权的人民法院起诉。+16.3 某一条款被认定无效的,不影响其他条款效力。++第十七条 其他+17.1 本协议是双方就 PrintFilm 作品授权的完整约定。平台用户协议、隐私政策与本协议不一致的,授权范围以本协议为准,个人信息处理以隐私政策为准。+17.2 平台未及时行使权利,不构成弃权。+17.3 未经平台书面同意,您不得转让本协议项下义务。+17.4 条款标题只为方便阅读,不影响解释。本协议以中文文本为准。+"""+++def archived_text() -> str:+ """写入 PDF 和存档的完整签署文本,含签署前提示。"""+ return "签署前提示:\n" + "\n".join(NOTICES) + "\n\n" + BODYdiff --git a/backend/tests/test_marketplace.py b/backend/tests/test_marketplace.pyindex ec414f2..6f153b9 100644--- a/backend/tests/test_marketplace.py+++ b/backend/tests/test_marketplace.py@@ -375,6 +375,7 @@ def test_signed_media_url_preserves_oss_object_headers(monkeypatch):def signing_body():from app.marketplace.authorization import VERSIONreturn {"template_version": VERSION, "signer_name": "测试签署人", "accepted_terms": True,+ "adult": True, "read_all": True, "accept_key": True,"strokes": [[[20 + i * 12, 60 + (i % 3) * 20] for i in range(25)]]}@@ -427,11 +428,14 @@ async def test_printfilm_signed_letter_review_and_public_flow(ctx, monkeypatch):from app.marketplace.models import Authorizationfake_oss(monkeypatch)uploaded = []+ stored = {}def capture(key, path, content_type):- assert path.read_bytes().startswith(b"%PDF")+ stored["bytes"] = path.read_bytes()+ assert stored["bytes"].startswith(b"%PDF")assert key.endswith("/letter.pdf") and content_type == "application/pdf"uploaded.append(key)monkeypatch.setattr(storage, "upload", capture)+ monkeypatch.setattr(storage, "read", lambda key: stored["bytes"])video = await asset(ctx)path = f"/api/marketplace/assets/{video.id}/rights"payload = {"version": 0, "details": source_details("printfilm")}@@ -439,6 +443,8 @@ async def test_printfilm_signed_letter_review_and_public_flow(ctx, monkeypatch):signed = await ctx.client.post("/api/marketplace/authorization", json=signing_body())assert signed.status_code == 200, signed.textauthorization_id = signed.json()["id"]+ terms = (await ctx.client.get("/api/marketplace/authorization")).json()["template"]+ assert terms["version"].endswith("v2") and "第七条" in terms["body"] and len(terms["notices"]) == 4assert len(uploaded) == 1assert (await ctx.client.post("/api/marketplace/authorization", json=signing_body())).json()["id"] == authorization_idassert len(uploaded) == 1@@ -465,8 +471,15 @@ async def test_printfilm_signed_letter_review_and_public_flow(ctx, monkeypatch):assert (await ctx.client.get("/api/marketplace/works")).json()["meta"]["total"] == 1ctx.user = ctx.strangerassert (await ctx.client.get(f"/api/marketplace/authorizations/{authorization_id}/letter")).status_code == 404+ assert (await ctx.client.get(f"/api/marketplace/authorizations/{authorization_id}/file")).status_code == 404ctx.user = ctx.adminassert (await ctx.client.get(f"/api/marketplace/authorizations/{authorization_id}/letter")).status_code == 200+ preview = await ctx.client.get(f"/api/marketplace/authorizations/{authorization_id}/file")+ assert preview.status_code == 200 and preview.content.startswith(b"%PDF")+ assert preview.headers["content-type"].startswith("application/pdf")+ assert preview.headers["content-disposition"].startswith("inline")+ download = await ctx.client.get(f"/api/marketplace/authorizations/{authorization_id}/file", params={"download": True})+ assert download.headers["content-disposition"].startswith("attachment")async def test_signature_requires_oss_current_terms_and_real_strokes(ctx, monkeypatch):diff --git a/frontend/src/features/marketplace/AuthorizationPanel.tsx b/frontend/src/features/marketplace/AuthorizationPanel.tsxindex 96ccd16..39ded54 100644--- a/frontend/src/features/marketplace/AuthorizationPanel.tsx+++ b/frontend/src/features/marketplace/AuthorizationPanel.tsx@@ -1,23 +1,38 @@import { useEffect, useRef, useState, type PointerEvent } from 'react'-import { request, date } from './api'-import { PreviewContent } from './AssetPreview'+import { date, letterFile, request } from './api'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 Status = { template: { version: string; title: string; notices: string[]; body: string }; current: Signed | null }type Point = [number, number]+type Preview = { url: string; image: boolean }-// 账号签署一次,服务端合成全文存档;每件视频仍需独立核验。+/** 账号签署一次。条款在页面内阅读,已签署文件默认在线预览,点下载才保存。 */export default function AuthorizationPanel({ onSigned }: { onSigned?: () => void }) {const [status, setStatus] = useState<Status | null>(null)const [error, setError] = useState('')const [busy, setBusy] = useState(false)- const [letter, setLetter] = useState<{ url: string; filename: string } | null>(null)+ const [preview, setPreview] = useState<Preview | null>(null)const [name, setName] = useState('')- const [accepted, setAccepted] = useState(false)+ const [adult, setAdult] = useState(false)+ const [readAll, setReadAll] = useState(false)+ const [acceptKey, setAcceptKey] = useState(false)const canvas = useRef<HTMLCanvasElement>(null)const strokes = useRef<Point[][]>([])const drawing = useRef<number | null>(null)+ const ready = adult && readAll && acceptKey && name.trim().length >= 2useEffect(() => { let active = true; request<Status>('/authorization').then(value => { if (active) setStatus(value) }).catch(e => { if (active) setError(e.message) }); return () => { active = false } }, [])+ useEffect(() => {+ const id = status?.current?.id+ if (!id) return+ let active = true+ let objectUrl = ''+ letterFile(id).then(blob => {+ if (!active) return+ objectUrl = URL.createObjectURL(blob)+ setPreview({ url: objectUrl, image: blob.type.startsWith('image/') })+ }).catch(e => { if (active) setError((e as Error).message) })+ return () => { active = false; if (objectUrl) URL.revokeObjectURL(objectUrl) }+ }, [status?.current?.id])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))]@@ -31,21 +46,45 @@ export default function AuthorizationPanel({ onSigned }: { onSigned?: () => voidif (ctx) { ctx.lineWidth = 3; ctx.lineCap = 'round'; ctx.beginPath(); ctx.moveTo(...previous); ctx.lineTo(...next); ctx.stroke() }stroke.push(next)}+ function downloadLetter() {+ if (!preview) return+ const link = document.createElement('a')+ link.href = preview.url+ link.download = preview.image ? '授权函.png' : '授权函.pdf'+ link.click()+ }async function sign() {- if (!status) return+ if (!status || !ready) returnconst 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) })+ const result = await request<Signed>('/authorization', 'POST', { template_version: status.template.version, signer_name: name.trim(), accepted_terms: true, adult: true, read_all: true, accept_key: true, strokes: valid })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 { const value = await request<{ url: string; filename?: string }>(`/authorizations/${status.current!.id}/letter`); setLetter({ url: value.url, filename: value.filename || '授权函.pdf' }) } catch (e) { setError((e as Error).message) } }}>查看已签授权函</button>{letter && <PreviewContent key={letter.url} url={letter.url} filename={letter.filename} />}</> : <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>}</>}+ return <section className="pf-market-authorization"><h2>PrintFilm 作品授权函</h2><p>按现行条款签署一次,本账号后续 PrintFilm 作品可引用。本函是许可使用,不是著作权转让。</p>+ {status && <>+ <h3>{status.template.title}</h3>+ <p>版本 {status.template.version}</p>+ <ol className="pf-market-letter-notices">{status.template.notices.map(item => <li key={item}>{item}</li>)}</ol>+ <div className="pf-market-letter">{status.template.body}</div>+ {status.current ? <>+ <p className="pf-market-notice">已签署:{status.current.signer_name} · {date(status.current.created_at)}。下面是存档预览,不会自动下载。</p>+ <div className="pf-market-letter-actions"><button type="button" onClick={downloadLetter} disabled={!preview}>下载授权函</button></div>+ {preview && (preview.image ? <img className="pf-market-letter-image" src={preview.url} alt="已签署授权函" /> : <iframe className="pf-market-letter-frame" src={preview.url} title="授权函预览" />)}+ </> : <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; try { e.currentTarget.setPointerCapture(e.pointerId) } catch { /* 当前指针无法捕获时仍记录笔画 */ } 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={adult} disabled={busy} onChange={e => setAdult(e.target.checked)} />我已年满十八周岁,具有完全民事行为能力,所填姓名真实。</label>+ <label><input type="checkbox" checked={readAll} disabled={busy} onChange={e => setReadAll(e.target.checked)} />我已完整阅读本协议全文。</label>+ <label><input type="checkbox" checked={acceptKey} disabled={busy} onChange={e => setAcceptKey(e.target.checked)} />我已特别阅读并同意第7、8、10、11、13、15条。</label>+ <button type="button" disabled={busy || !ready} 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/api.ts b/frontend/src/features/marketplace/api.tsindex e559587..2684aed 100644--- a/frontend/src/features/marketplace/api.ts+++ b/frontend/src/features/marketplace/api.ts@@ -69,6 +69,26 @@ export async function request<T>(path: string, method = 'GET', body?: unknown, sreturn result as T}+/** 已签署授权函的文件流。默认由接口 inline 返回,页面再用本地对象地址预览。 */+export async function letterFile(id: number): Promise<Blob> {+ const token = localStorage.getItem('token')+ let response: Response+ try {+ response = await fetch(`${base}/api/marketplace/authorizations/${id}/file`, {+ headers: token ? { Authorization: `Bearer ${token}` } : {},+ })+ } catch {+ throw new Error('授权函暂时无法打开')+ }+ if (!response.ok) {+ if (response.status === 401) window.location.assign(`/auth?next=${encodeURIComponent(window.location.pathname + window.location.search)}`)+ const result = await response.json().catch(() => ({}))+ const detail = result.detail+ throw new Error(typeof detail === 'string' ? detail : '授权函暂时无法打开')+ }+ return response.blob()+}+// 只在需要观看时申请短时链接,不能把 object_key 放到前端。export async function media(kind: string, id: number, purpose: string) {return (await request<{ url: string }>(`/media/${kind}/${id}/${purpose}`)).urldiff --git a/frontend/src/features/marketplace/marketplace.css b/frontend/src/features/marketplace/marketplace.cssindex 6ff51e9..e6a4703 100644--- a/frontend/src/features/marketplace/marketplace.css+++ b/frontend/src/features/marketplace/marketplace.css@@ -177,8 +177,12 @@ body:has(.pf-market-shell) .pf-wx-fab-root { display:none; }.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-letter-notices { margin: 12px 0 16px; padding-left: 1.2em; line-height: 1.7; }+.pf-market-letter-actions { display: flex; flex-wrap: wrap; gap: 12px; margin: 12px 0; }+.pf-market-letter-frame { width: 100%; height: 72vh; min-height: 480px; border: 1px solid #dedfd8; border-radius: 12px; background: #fff; }+.pf-market-letter-image { width: 100%; max-height: 72vh; object-fit: contain; background: #f5f5f0; border-radius: 12px; }.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; } }+@media (max-width: 600px) { .pf-market-file-preview iframe, .pf-market-letter-frame { height: 70vh; min-height: 360px; } .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; }