PRINTFILM: AI short-video marketing and AI short-drama creation platform
fix
增瑞 田aa1b1dd7a4f0
diff --git a/admin/src/features/marketplace/MarketplaceAdmin.tsx b/admin/src/features/marketplace/MarketplaceAdmin.tsxindex f7718e1..09d53ac 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, letterFile, useMarketplaceStatus, type Item, type Listing } from './api'+import { request, assetFile, assetUrl, letterFile, useMarketplaceStatus, type Item, type Listing } from './api'import { fieldStatusLabel, recordDetailsTitle, recordStatus, statusLabel, statusOptions } from './presentation'import { PaginationBar } from '@/components/PaginationBar'import { AdminModal } from '@/components/admin/AdminModal'@@ -25,8 +25,20 @@ function Summary({ item, kind }: { item: Item; kind: string }) {// 直接从服务端签名,不将原始 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 className="market-ops-file"><button type="button" onClick={async () => { try { setUrl(await assetUrl(id, purpose)); setError('') } catch (e) { setError((e as Error).message) } }}>{label}</button>{url && (video ? <video src={url} controls className="my-3 max-h-[500px] w-full" /> : <a href={url} target="_blank" rel="noreferrer">打开文件</a>)}{error && <p role="alert">{error}</p>}</div>+ const [url, setUrl] = useState('')+ const [preview, setPreview] = useState<{ url: string; image: boolean; pdf: boolean } | null>(null)+ const [error, setError] = useState('')+ useEffect(() => () => { if (preview) URL.revokeObjectURL(preview.url) }, [preview])+ async function open() {+ try {+ if (video) { setUrl(await assetUrl(id, purpose)); setError(''); return }+ const blob = await assetFile(id, purpose)+ const type = blob.type+ setPreview(current => { if (current) URL.revokeObjectURL(current.url); return { url: URL.createObjectURL(blob), image: type.startsWith('image/'), pdf: type.includes('pdf') } })+ setError('')+ } catch (e) { setError((e as Error).message) }+ }+ return <div className="market-ops-file"><button type="button" onClick={() => { void open() }}>{label}</button>{url && video && <video src={url} controls className="my-3 max-h-[500px] w-full" />}{preview?.image && <img src={preview.url} alt={label} />}{preview?.pdf && <iframe className="market-ops-file-frame" src={preview.url} title={label} />}{preview && !preview.image && !preview.pdf && <p>这个文件暂时不能在页面里预览。</p>}{error && <p role="alert">{error}</p>}</div>}function WorkPreviewLink({ id }: { id: number }) {diff --git a/admin/src/features/marketplace/api.ts b/admin/src/features/marketplace/api.tsindex 3c9e4b1..a221a32 100644--- a/admin/src/features/marketplace/api.ts+++ b/admin/src/features/marketplace/api.ts@@ -56,3 +56,15 @@ export function useMarketplaceEnabled() {export async function assetUrl(id: number, purpose = 'original') {return (await request<{ url: string }>(`/api/marketplace/media/asset/${id}/${purpose}`)).url}++/** 管理端在页面内预览图片或 PDF,不把 OSS 地址交给浏览器下载。 */+export async function assetFile(id: number, purpose = 'original'): Promise<Blob> {+ const response = await fetch(`/api/marketplace/media/asset/${id}/inline?purpose=${encodeURIComponent(purpose)}`, { headers: { Authorization: `Bearer ${getToken() ?? ''}` } })+ if (!response.ok) {+ const value = await response.json().catch(() => ({}))+ throw new Error(typeof value.detail === 'string' ? value.detail : '文件暂时无法预览')+ }+ const type = response.headers.get('content-type') || 'application/octet-stream'+ const blob = await response.blob()+ return blob.type ? blob : new Blob([blob], { type })+}diff --git a/admin/src/features/marketplace/marketplace-admin.css b/admin/src/features/marketplace/marketplace-admin.cssindex 60f94eb..32b0e17 100644--- a/admin/src/features/marketplace/marketplace-admin.css+++ b/admin/src/features/marketplace/marketplace-admin.css@@ -52,7 +52,8 @@.market-ops-stage { display:flex; flex-direction:column; gap:16px; }.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-file video,.market-ops-file img { flex-basis:100%; width:100%; max-height:70vh; object-fit:contain; background:#111714; }+.market-ops-file-frame { flex-basis:100%; width:100%; height:70vh; min-height:420px; border:0; background:#fff; }.market-ops-letter-modal { background:linear-gradient(145deg,#ffffff 0%,#f6faf6 100%) !important; }.market-ops-letter-modal .admin-modal-header { background:linear-gradient(135deg,#f1f8f2 0%,#ffffff 78%); border-bottom:1px solid #dfeae1; }.market-ops-letter-modal-body { min-height:0; padding:18px 22px 20px !important; background:#f5f8f4; }diff --git a/backend/app/marketplace/media.py b/backend/app/marketplace/media.pyindex 9c7fa0b..f683526 100644--- a/backend/app/marketplace/media.py+++ b/backend/app/marketplace/media.py@@ -2,6 +2,7 @@import asynciofrom fastapi import APIRouter, Depends+from fastapi.responses import Responsefrom sqlalchemy import selectfrom . import storage@@ -13,6 +14,54 @@ from .service import event, fail, is_public_work, recruit_open, rights_for, righrouter = APIRouter()+def _inline_type(payload: bytes, declared: str) -> str:+ """上传时类型不准时,按文件头判断,保证图片和 PDF 能在页面里打开。"""+ if declared and declared != "application/octet-stream":+ return declared+ if payload.startswith(b"%PDF"):+ return "application/pdf"+ if payload.startswith(b"\x89PNG"):+ return "image/png"+ if payload.startswith(b"\xff\xd8"):+ return "image/jpeg"+ if payload.startswith(b"GIF8"):+ return "image/gif"+ if payload.startswith(b"RIFF") and b"WEBP" in payload[:16]:+ return "image/webp"+ return declared or "application/octet-stream"++[email protected]("/media/asset/{record_id}/inline", dependencies=[Depends(storage_ready)])+async def asset_inline(record_id: int, db: DB, user: Visitor, purpose: str = "original"):+ """把已审核通过的文件以 inline 流返回,避免浏览器把预览当成下载。"""+ asset = await db.get(Asset, record_id)+ admin = bool(user and user.role == "admin")+ if not asset or not user or (not admin and asset.owner_id != user.id):+ fail("文件不存在或无权访问", 404)+ if asset.status != "ready":+ fail("媒体尚未就绪", 409)+ if purpose not in ("original", "preview", "review", "cover"):+ fail("媒体用途无效")+ key, content_type = None, asset.content_type or ""+ 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 content_type+ elif purpose == "cover":+ key = asset.cover_key or asset.object_key+ content_type = "image/jpeg" if asset.kind == "video" else ("image/png" if asset.cover_key else content_type)+ else:+ key = getattr(asset, f"{purpose}_key", None)+ if not key:+ fail("该预览尚未生成", 409)+ payload = await asyncio.to_thread(storage.read, key)+ event(db, user.id, "asset", asset.id, "preview_" + purpose)+ await db.commit()+ return Response(content=payload, media_type=_inline_type(payload, content_type), headers={+ "Content-Disposition": "inline", "Cache-Control": "private, no-store",+ })++@router.get("/media/{kind}/{record_id}/{purpose}",response_model=dict,