From 0a6473e5d7e7b2a76973344ffefeeed9d57237c5 Mon Sep 17 00:00:00 2001 From: xiaoxia Date: Sat, 26 Sep 2026 16:12:57 +0800 Subject: [PATCH 1/3] =?UTF-8?q?fix(cover):=20=E6=A8=A1=E6=9D=BF=E7=BC=A9?= =?UTF-8?q?=E7=95=A5=E5=9B=BE=E6=B8=B2=E6=9F=93=20+=20=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E7=94=9F=E6=88=90=E5=B0=81=E9=9D=A2404=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 问题1:模板卡片不显示预览图 - 之前写死渐变色+🖼️emoji,完全没用 thumbnail_url 字段 - 新增 TemplateThumb 子组件:优先渲染 tpl.thumbnail_url(object-fit:cover), 图片加载失败或无URL时回退到按模板id哈希的柔和渐变色占位 - 选中态✓覆盖在图片上层 问题2:自动生成封面 POST /generation/generate-cover 返回404 根因:前端用魔法字符串 "default" 作为 template_id 发给后端,但后端 模板库中不存在 id="default" 的记录,resolve_draft_plan_id 返回404。 修复: 1. 前端 useSharedCover:挂载时拉模板列表,把初始 "default" 占位符自动 解析为第一个系统模板的真实id;用户未选模板时传空串给API层 2. 前端 api/generation/cover.ts:templateId 为空或 "default" 时不传 template_id query 参数(而非传 "default") 3. 后端 generation_cover.py: - template_id Query 改为可选(默认空串) - 移除原来强依赖 get_draft_plan_id(auto_create_default=False) 的 Depends - 在函数体内手动 resolve:空串时 auto_create_default=True 自动兜底到 用户默认模板;非空时走原校验逻辑 4. useBatchCovers:批量一键生成同样不传 "default" 5. Step6CoverSettings:透传原始 selectedTemplateId 给 useBatchCovers 6. 保留 selectedTemplateId==="default" 的UI展示分支("默认模板"文案) 用于首次挂载模板列表加载完成前的过渡态 验证: - tsc --noEmit ✅ - eslint --max-warnings=0 ✅ - prettier ✅ - vite build ✅ - 后端 Python 语法检查 ✅ - 未修改 CI 配置 --- apps/api/app/api/routes/generation_cover.py | 28 +++++- apps/web/src/api/generation/cover.ts | 10 +- .../src/components/cover/useSharedCover.ts | 24 ++++- .../components/Step6CoverSettings.tsx | 2 +- .../cover-settings/CoverSettingsModal.tsx | 71 +++++++++---- .../pages/generate/hooks/useBatchCovers.ts | 99 ++++++++++--------- 6 files changed, 159 insertions(+), 75 deletions(-) diff --git a/apps/api/app/api/routes/generation_cover.py b/apps/api/app/api/routes/generation_cover.py index c147c0f93..55ec9a915 100644 --- a/apps/api/app/api/routes/generation_cover.py +++ b/apps/api/app/api/routes/generation_cover.py @@ -30,7 +30,7 @@ from packages.domain.config_schemas import normalize_plan_config from packages.middleware.points_gate import points_gate from packages.shared.storage import get_shared_storage_service -from .templates_editor.dependencies import get_draft_plan_id, get_editor_services +from .templates_editor.dependencies import get_editor_services logger = logging.getLogger(__name__) router = APIRouter(tags=["Generation"]) @@ -349,8 +349,8 @@ def _is_trusted_media_url(url: str) -> bool: @points_gate("ai_cover") def generate_cover( body: GenerateCoverRequest, - template_id: str = Query(..., description="模板 ID"), - plan_id: str = Depends(get_draft_plan_id), + template_id: str = Query("", description="模板 ID,为空时使用用户默认模板"), + plan_id: str = "", services: tuple[EditTemplateService, EditPlanService] = Depends(get_editor_services), db: Session = Depends(get_db_session), current_user: AuthenticatedUser = Depends(get_current_user), @@ -366,7 +366,27 @@ def generate_cover( MediaKit 的调用方式(strategy / max_frames / 轮询 / 重试 / 降级)不变。 """ - _, plan_svc = services + tpl_svc, plan_svc = services + # template_id 为空时自动创建/获取用户默认模板,保证 ai_frame 无模板也能抽帧 + if not template_id: + from app.api.routes.templates_editor.dependencies import resolve_draft_plan_id + plan_id = resolve_draft_plan_id( + template_id="", + services=services, + current_user=current_user, + db=db, + auto_create_default=True, + ) + else: + # 校验模板存在且可访问(原 Depends 逻辑) + from app.api.routes.templates_editor.dependencies import resolve_draft_plan_id + plan_id = resolve_draft_plan_id( + template_id=template_id, + services=services, + current_user=current_user, + db=db, + auto_create_default=False, + ) plan = plan_svc.get_plan_or_raise(plan_id) # ── upload 类型:直接保存前端上传的封面图片,不需要预览视频 ────── diff --git a/apps/web/src/api/generation/cover.ts b/apps/web/src/api/generation/cover.ts index 7c1d98bf6..948d4b3df 100644 --- a/apps/web/src/api/generation/cover.ts +++ b/apps/web/src/api/generation/cover.ts @@ -51,12 +51,18 @@ export interface GenerateCoverResponse { /** AI 生成封面 — 从最终成片中抽帧(MediaKit 选帧) */ export async function generateCover( - templateId: string, + templateId: string | undefined | null, data: GenerateCoverRequest, ): Promise { + // templateId 为空时不传该参数,让后端使用默认模板配置 + // (前端此前用 "default" 作为占位符,该 id 不存在于后端模板库会 404) + const params: Record = {} + if (templateId && templateId !== "default") { + params.template_id = templateId + } const response = await apiClient.post("/generation/generate-cover", data, { timeout: 300000, - params: { template_id: templateId }, + params, }) return response.data } diff --git a/apps/web/src/components/cover/useSharedCover.ts b/apps/web/src/components/cover/useSharedCover.ts index 4db30d162..574c5bddd 100644 --- a/apps/web/src/components/cover/useSharedCover.ts +++ b/apps/web/src/components/cover/useSharedCover.ts @@ -85,6 +85,13 @@ export function useSharedCover(opts: UseSharedCoverOptions): UseSharedCoverRetur config: t.config, })) setTemplates(list) + // 若当前选中 "default"(初始占位),自动解析为第一个系统模板的真实 id + // ("default" 不是后端真实模板 id,传过去会 404) + setSelectedTemplateId((prev) => { + if (prev !== "default") return prev + const firstSys = list.find((t) => t.is_system) + return firstSys?.id || list[0]?.id || "default" + }) } catch (err) { const axiosErr = err as { response?: { @@ -112,6 +119,11 @@ export function useSharedCover(opts: UseSharedCoverOptions): UseSharedCoverRetur } }, []) + useEffect(() => { + // 挂载时拉一次模板列表,用于把 "default" 占位符解析成真实模板 id + void reloadTemplates() + }, [reloadTemplates]) + useEffect(() => { if (showCoverSettings) { void reloadTemplates() @@ -193,7 +205,12 @@ export function useSharedCover(opts: UseSharedCoverOptions): UseSharedCoverRetur await deleteCoverTemplate(id) setTemplates((prev) => prev.filter((t) => t.id !== id)) if (selectedTemplateId === id) { - setSelectedTemplateId("default") + // 删除后选中第一个系统模板作为兜底,避免 magic string "default" 传后端 404 + setTemplates((prevAfter) => { + const firstSys = prevAfter.find((t) => t.is_system) + setSelectedTemplateId(firstSys?.id || prevAfter[0]?.id || "") + return prevAfter + }) } } catch (err) { const axiosErr = err as { @@ -231,7 +248,8 @@ export function useSharedCover(opts: UseSharedCoverOptions): UseSharedCoverRetur } setGenerating(true) try { - const url = await generateFn(selectedTemplateId || "default") + const tplId = selectedTemplateId && selectedTemplateId !== "default" ? selectedTemplateId : "" + const url = await generateFn(tplId) if (!url) { message.warning("封面生成未返回图片,请重试") } @@ -266,7 +284,7 @@ export function useSharedCover(opts: UseSharedCoverOptions): UseSharedCoverRetur const selectedTemplateName = templates.find((t) => t.id === selectedTemplateId)?.name || - (selectedTemplateId === "default" ? "默认模板" : "自定义") + (selectedTemplateId === "default" || !selectedTemplateId ? "默认模板" : "自定义") return { templates, diff --git a/apps/web/src/pages/generate/components/Step6CoverSettings.tsx b/apps/web/src/pages/generate/components/Step6CoverSettings.tsx index a94c0275e..2a24287ca 100755 --- a/apps/web/src/pages/generate/components/Step6CoverSettings.tsx +++ b/apps/web/src/pages/generate/components/Step6CoverSettings.tsx @@ -186,7 +186,7 @@ const Step6CoverSettings: React.FC = (props) => { * 透传给 useBatchCovers,由其在 generateOne/generateAll 中发给后端。 */ const batchCovers = useBatchCovers({ - selectedTemplate: shared.selectedTemplateId || "default", + selectedTemplate: shared.selectedTemplateId, generatedVideos: props.generatedVideos, titles: batchTitles, titleStyle: { diff --git a/apps/web/src/pages/generate/components/cover-settings/CoverSettingsModal.tsx b/apps/web/src/pages/generate/components/cover-settings/CoverSettingsModal.tsx index 37923b6be..786a5ed5b 100644 --- a/apps/web/src/pages/generate/components/cover-settings/CoverSettingsModal.tsx +++ b/apps/web/src/pages/generate/components/cover-settings/CoverSettingsModal.tsx @@ -1,4 +1,4 @@ -import React from "react" +import React, { useMemo, useState } from "react" import type { CoverTemplate } from "../../types/cover" import Modal from "@/components/ui/Modal" import Button from "@/components/ui/Button" @@ -17,15 +17,58 @@ interface CoverSettingsModalProps { onCreateNew: () => void } -const GRADIENT_MAP: Record = { - default: "linear-gradient(135deg, #e0e0e0, #c0c0c0)", - "bold-red": "linear-gradient(135deg, #ef4444, #b91c1c)", - "elegant-black": "linear-gradient(135deg, #374151, #111827)", - "gradient-blue": "linear-gradient(135deg, #3b82f6, #1d4ed8)", - "gradient-purple": "linear-gradient(135deg, #8b5cf6, #6d28d9)", - "warm-orange": "linear-gradient(135deg, #f97316, #ea580c)", - "fresh-green": "linear-gradient(135deg, #22c55e, #15803d)", - "tech-blue": "linear-gradient(135deg, #06b6d4, #0e7490)", +/** 模板缩略图:优先渲染 thumbnail_url;加载失败/无图时展示占位 */ +const TemplateThumb: React.FC<{ tpl: CoverTemplate; isSelected: boolean }> = ({ + tpl, + isSelected, +}) => { + const [errored, setErrored] = useState(false) + const url = tpl.thumbnail_url && !errored ? tpl.thumbnail_url : "" + // 随机柔和渐变做占位,保证卡片不会灰成一片 + const placeholderBg = useMemo(() => { + const palettes = [ + ["#e0e0e0", "#c0c0c0"], + ["#ef4444", "#b91c1c"], + ["#374151", "#111827"], + ["#3b82f6", "#1d4ed8"], + ["#8b5cf6", "#6d28d9"], + ["#f97316", "#ea580c"], + ["#22c55e", "#15803d"], + ["#06b6d4", "#0e7490"], + ] + let h = 0 + for (const ch of tpl.id || tpl.name || "") h = (h * 31 + ch.charCodeAt(0)) >>> 0 + const [a, b] = palettes[h % palettes.length] + return `linear-gradient(135deg, ${a}, ${b})` + }, [tpl.id, tpl.name]) + + return ( +
+ {isSelected && ✓} + {url ? ( + {tpl.name} setErrored(true)} + style={{ + width: "100%", + height: "100%", + objectFit: "cover", + display: "block", + }} + /> + ) : ( + 🖼️ + )} +
+ ) } const CoverSettingsModal: React.FC = ({ @@ -97,13 +140,7 @@ const CoverSettingsModal: React.FC = ({ className={`xx-cover-template-card${isSelected ? " selected" : ""}`} onClick={() => onSelectTemplate(tpl.id)} > -
- {isSelected && ✓} - 🖼️ -
+
{tpl.name} diff --git a/apps/web/src/pages/generate/hooks/useBatchCovers.ts b/apps/web/src/pages/generate/hooks/useBatchCovers.ts index 859c893c0..80d607a01 100644 --- a/apps/web/src/pages/generate/hooks/useBatchCovers.ts +++ b/apps/web/src/pages/generate/hooks/useBatchCovers.ts @@ -107,54 +107,57 @@ export function useBatchCovers({ addBusy(index) try { const titleText = titles[index] || "" - const response = await generateCover(selectedTemplate || "default", { - generated_video_id: target.id, - video_url: target.file_url || target.download_url || "", - cover_type: "ai_frame", - ...(titleText - ? { - title_config: { - text: titleText, - font: titleStyle.font, - font_size: titleStyle.size, - font_color: titleStyle.color, - position: titleStyle.position, - bold: titleStyle.bold, - italic: titleStyle.italic, - stroke: titleStyle.stroke - ? { - enabled: true, - width: titleStyle.strokeWidth ?? 4, - color: titleStyle.strokeColor ?? "#000000", - } - : { enabled: false }, - shadow: titleStyle.shadow - ? { - enabled: true, - offset_x: titleStyle.shadowOffsetX ?? 2, - offset_y: titleStyle.shadowOffsetY ?? 2, - blur: titleStyle.shadowBlur ?? 4, - color: titleStyle.shadowColor ?? "rgba(0,0,0,0.8)", - } - : { enabled: false }, - line_height: titleStyle.lineHeight ?? 1.2, - margin_top: titleStyle.marginTop ?? 24, - max_chars_per_line: titleStyle.maxCharsPerLine ?? 0, - background: titleStyle.bgEnabled - ? { - enabled: true, - color: titleStyle.bgColor, - padding: titleStyle.bgPadding, - radius: titleStyle.bgRadius, - } - : { enabled: false }, - line_overrides: (titleStyle.lineOverrides ?? []) as Array< - Record - >, - }, - } - : {}), - }) + const response = await generateCover( + selectedTemplate && selectedTemplate !== "default" ? selectedTemplate : undefined, + { + generated_video_id: target.id, + video_url: target.file_url || target.download_url || "", + cover_type: "ai_frame", + ...(titleText + ? { + title_config: { + text: titleText, + font: titleStyle.font, + font_size: titleStyle.size, + font_color: titleStyle.color, + position: titleStyle.position, + bold: titleStyle.bold, + italic: titleStyle.italic, + stroke: titleStyle.stroke + ? { + enabled: true, + width: titleStyle.strokeWidth ?? 4, + color: titleStyle.strokeColor ?? "#000000", + } + : { enabled: false }, + shadow: titleStyle.shadow + ? { + enabled: true, + offset_x: titleStyle.shadowOffsetX ?? 2, + offset_y: titleStyle.shadowOffsetY ?? 2, + blur: titleStyle.shadowBlur ?? 4, + color: titleStyle.shadowColor ?? "rgba(0,0,0,0.8)", + } + : { enabled: false }, + line_height: titleStyle.lineHeight ?? 1.2, + margin_top: titleStyle.marginTop ?? 24, + max_chars_per_line: titleStyle.maxCharsPerLine ?? 0, + background: titleStyle.bgEnabled + ? { + enabled: true, + color: titleStyle.bgColor, + padding: titleStyle.bgPadding, + radius: titleStyle.bgRadius, + } + : { enabled: false }, + line_overrides: (titleStyle.lineOverrides ?? []) as Array< + Record + >, + }, + } + : {}), + }, + ) const url = response.cover?.image_url || response.cover?.thumbnail_url || "" if (url) { patchCover(index, url) -- 2.54.0 From a989670d83ba903cd31f88bf2de29e7e514fa9e0 Mon Sep 17 00:00:00 2001 From: xiaoxia Date: Sat, 26 Sep 2026 18:16:37 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix(cover):=20=E4=BF=AE=E5=A4=8D=20#2053=20?= =?UTF-8?q?=E5=8D=95=E6=B5=8B=E5=A4=B1=E8=B4=A5=20=E2=80=94=20plan=5Fid=20?= =?UTF-8?q?=E7=9B=B4=E6=8E=A5=E8=BF=94=E5=9B=9E=E4=BB=A5=E5=85=BC=E5=AE=B9?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E7=9B=B4=E6=8E=A5=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI 报错 17 个用例失败: ValidationError: GenerateCoverResponse.plan_id Input should be a valid string input_value= 原因:上一版把 plan_id 参数默认值改为 "" 后,在函数体内用 resolve_draft_plan_id 的返回值覆盖了 plan_id。单测直接调用函数时虽然显式传入了 plan_id="plan-x", 但 resolve_draft_plan_id 未被 mock,会把 services=(mock_tpl, mock_plan) 中的 MagicMock 当作 tpl_svc 调用并返回 MagicMock,最终覆盖传入的字符串。 修复:在函数体内加判断 if not plan_id: 才走 resolve_draft_plan_id;单测显式 传入 plan_id 字符串时直接用,HTTP 调用默认空串才触发模板解析。 同时把两处函数内 from-import 提升到模块顶层 import resolve_draft_plan_id, 并在 templates_editor/dependencies.py 新增 get_draft_plan_id_optional 依赖 (供其他端点复用,本次未实际引用但保留供将来使用)。 PR Build API Image 的失败是 CI 基础设施 DNS 解析超时 (xiaoxia-registry.cn-hangzhou.cr.aliyuncs.com i/o timeout), 与代码无关,push 后重试即可。 --- apps/api/app/api/routes/generation_cover.py | 24 +++++++------------ .../routes/templates_editor/dependencies.py | 23 +++++++++++++++++- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/apps/api/app/api/routes/generation_cover.py b/apps/api/app/api/routes/generation_cover.py index 55ec9a915..06fba29eb 100644 --- a/apps/api/app/api/routes/generation_cover.py +++ b/apps/api/app/api/routes/generation_cover.py @@ -30,7 +30,7 @@ from packages.domain.config_schemas import normalize_plan_config from packages.middleware.points_gate import points_gate from packages.shared.storage import get_shared_storage_service -from .templates_editor.dependencies import get_editor_services +from .templates_editor.dependencies import get_editor_services, resolve_draft_plan_id logger = logging.getLogger(__name__) router = APIRouter(tags=["Generation"]) @@ -366,26 +366,18 @@ def generate_cover( MediaKit 的调用方式(strategy / max_frames / 轮询 / 重试 / 降级)不变。 """ - tpl_svc, plan_svc = services - # template_id 为空时自动创建/获取用户默认模板,保证 ai_frame 无模板也能抽帧 - if not template_id: - from app.api.routes.templates_editor.dependencies import resolve_draft_plan_id - plan_id = resolve_draft_plan_id( - template_id="", - services=services, - current_user=current_user, - db=db, - auto_create_default=True, - ) - else: - # 校验模板存在且可访问(原 Depends 逻辑) - from app.api.routes.templates_editor.dependencies import resolve_draft_plan_id + _tpl_svc, plan_svc = services + # 只有显式未传 plan_id(HTTP 调用默认空串)时才按 template_id 解析, + # 以便单测可直接传入 mock 的 plan_id 字符串。 + # 注意:plan_id 不作为公开 query 参数暴露,直接传任意 plan_id 会被 + # get_plan_or_raise 校验,不会造成越权(plan 归属校验在 service 层)。 + if not plan_id: plan_id = resolve_draft_plan_id( template_id=template_id, services=services, current_user=current_user, db=db, - auto_create_default=False, + auto_create_default=(not template_id), ) plan = plan_svc.get_plan_or_raise(plan_id) diff --git a/apps/api/app/api/routes/templates_editor/dependencies.py b/apps/api/app/api/routes/templates_editor/dependencies.py index 1f70dd25f..b6c7014dd 100755 --- a/apps/api/app/api/routes/templates_editor/dependencies.py +++ b/apps/api/app/api/routes/templates_editor/dependencies.py @@ -3,6 +3,7 @@ 核心依赖: - get_editor_services: 获取模板+计划服务 - get_draft_plan_id: Depends 形式的路径依赖(template_id 路径参数必填) +- get_draft_plan_id_optional: Depends 形式的查询依赖(template_id 可为空,自动兜底默认模板) - resolve_draft_plan_id: 纯函数版本,供 clips_standalone 等非路径参数场景复用 (支持空 tid 时自动兜底创建默认模板) """ @@ -16,7 +17,7 @@ from app.auth import AuthenticatedUser, get_current_user from app.dependencies import get_db_session from app.services.edit_plan_service import EditPlanService from app.services.edit_template_service import EditTemplateService -from fastapi import Depends, HTTPException, status +from fastapi import Depends, HTTPException, Query, status from sqlalchemy.orm import Session from packages.adapters.sqlalchemy_impl.template_repository import ( @@ -147,3 +148,23 @@ def get_draft_plan_id( db=db, auto_create_default=False, ) + + +def get_draft_plan_id_optional( + template_id: str = Query("", description="模板 ID,为空时使用用户默认模板"), + services: tuple[EditTemplateService, EditPlanService] = Depends(get_editor_services), + current_user: AuthenticatedUser = Depends(get_current_user), + db: Session = Depends(get_db_session), +) -> str: + """可选 Depends 版本:template_id 为空时自动创建/获取用户默认模板. + + 供 /generation/generate-cover 等「用户没选模板也应可用」的端点复用。 + 返回的 plan_id 一定非空(字符串)。 + """ + return resolve_draft_plan_id( + template_id=template_id, + services=services, + current_user=current_user, + db=db, + auto_create_default=True, + ) -- 2.54.0 From 6becc7beca3e0056ef7e1624db7fbfc3b0638a91 Mon Sep 17 00:00:00 2001 From: xiaoxia Date: Sat, 26 Sep 2026 18:18:40 +0800 Subject: [PATCH 3/3] =?UTF-8?q?revert(backend):=20=E6=92=A4=E5=9B=9E=20#20?= =?UTF-8?q?53=20=E5=90=8E=E7=AB=AF=E6=94=B9=E5=8A=A8=EF=BC=8C=E8=AE=A9?= =?UTF-8?q?=E5=89=8D=E7=AB=AFPR=E5=85=88=E5=90=88=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 按方案1拆分:撤回 generation_cover.py 的 template_id 可选改动和 dependencies.py 的 get_draft_plan_id_optional 新增依赖。PR#2053 现在只包含 前端修复(模板缩略图渲染 + 不传 "default" 魔法字符串 + 真实模板id解析)。 后端改动(让 /generate-cover 支持 template_id 为空自动兜底默认模板)后续 会在独立 PR 中跟进,配合单测更新一起合。 前端已处理的向后兼容: - api/generation/cover.ts: templateId 为空或 'default' 时不传 template_id 参数。当前后端 template_id 是必填 Query,会返回 422 Validation Error, 这比之前传 'default' 返回 404 '模板不存在' 更明确; - useSharedCover 挂载时会自动拉模板列表把 'default' 占位符解析为第一个 系统模板的真实 id,因此绝大多数正常路径(选过模板/默认系统模板)不会 触发空 template_id 分支; - useBatchCovers 同样使用解析后的真实模板 id 或空串,空串情况只发生在 用户删除全部模板后的极端兜底场景,届时用户会看到 422 错误提示需要 新建模板,属于可接受的退化行为。 --- apps/api/app/api/routes/generation_cover.py | 20 ++++------------ .../routes/templates_editor/dependencies.py | 23 +------------------ 2 files changed, 5 insertions(+), 38 deletions(-) diff --git a/apps/api/app/api/routes/generation_cover.py b/apps/api/app/api/routes/generation_cover.py index 06fba29eb..c147c0f93 100644 --- a/apps/api/app/api/routes/generation_cover.py +++ b/apps/api/app/api/routes/generation_cover.py @@ -30,7 +30,7 @@ from packages.domain.config_schemas import normalize_plan_config from packages.middleware.points_gate import points_gate from packages.shared.storage import get_shared_storage_service -from .templates_editor.dependencies import get_editor_services, resolve_draft_plan_id +from .templates_editor.dependencies import get_draft_plan_id, get_editor_services logger = logging.getLogger(__name__) router = APIRouter(tags=["Generation"]) @@ -349,8 +349,8 @@ def _is_trusted_media_url(url: str) -> bool: @points_gate("ai_cover") def generate_cover( body: GenerateCoverRequest, - template_id: str = Query("", description="模板 ID,为空时使用用户默认模板"), - plan_id: str = "", + template_id: str = Query(..., description="模板 ID"), + plan_id: str = Depends(get_draft_plan_id), services: tuple[EditTemplateService, EditPlanService] = Depends(get_editor_services), db: Session = Depends(get_db_session), current_user: AuthenticatedUser = Depends(get_current_user), @@ -366,19 +366,7 @@ def generate_cover( MediaKit 的调用方式(strategy / max_frames / 轮询 / 重试 / 降级)不变。 """ - _tpl_svc, plan_svc = services - # 只有显式未传 plan_id(HTTP 调用默认空串)时才按 template_id 解析, - # 以便单测可直接传入 mock 的 plan_id 字符串。 - # 注意:plan_id 不作为公开 query 参数暴露,直接传任意 plan_id 会被 - # get_plan_or_raise 校验,不会造成越权(plan 归属校验在 service 层)。 - if not plan_id: - plan_id = resolve_draft_plan_id( - template_id=template_id, - services=services, - current_user=current_user, - db=db, - auto_create_default=(not template_id), - ) + _, plan_svc = services plan = plan_svc.get_plan_or_raise(plan_id) # ── upload 类型:直接保存前端上传的封面图片,不需要预览视频 ────── diff --git a/apps/api/app/api/routes/templates_editor/dependencies.py b/apps/api/app/api/routes/templates_editor/dependencies.py index b6c7014dd..1f70dd25f 100755 --- a/apps/api/app/api/routes/templates_editor/dependencies.py +++ b/apps/api/app/api/routes/templates_editor/dependencies.py @@ -3,7 +3,6 @@ 核心依赖: - get_editor_services: 获取模板+计划服务 - get_draft_plan_id: Depends 形式的路径依赖(template_id 路径参数必填) -- get_draft_plan_id_optional: Depends 形式的查询依赖(template_id 可为空,自动兜底默认模板) - resolve_draft_plan_id: 纯函数版本,供 clips_standalone 等非路径参数场景复用 (支持空 tid 时自动兜底创建默认模板) """ @@ -17,7 +16,7 @@ from app.auth import AuthenticatedUser, get_current_user from app.dependencies import get_db_session from app.services.edit_plan_service import EditPlanService from app.services.edit_template_service import EditTemplateService -from fastapi import Depends, HTTPException, Query, status +from fastapi import Depends, HTTPException, status from sqlalchemy.orm import Session from packages.adapters.sqlalchemy_impl.template_repository import ( @@ -148,23 +147,3 @@ def get_draft_plan_id( db=db, auto_create_default=False, ) - - -def get_draft_plan_id_optional( - template_id: str = Query("", description="模板 ID,为空时使用用户默认模板"), - services: tuple[EditTemplateService, EditPlanService] = Depends(get_editor_services), - current_user: AuthenticatedUser = Depends(get_current_user), - db: Session = Depends(get_db_session), -) -> str: - """可选 Depends 版本:template_id 为空时自动创建/获取用户默认模板. - - 供 /generation/generate-cover 等「用户没选模板也应可用」的端点复用。 - 返回的 plan_id 一定非空(字符串)。 - """ - return resolve_draft_plan_id( - template_id=template_id, - services=services, - current_user=current_user, - db=db, - auto_create_default=True, - ) -- 2.54.0