Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.
TypeScript agent-skillscodex-clideskop-appdubbingimage-generationlocalizationskillsttsvideo-editingvideo-generationvideo-transcriptionvideo-translation
feat(creator): expand video translation sources and prioritize online previews
Joshua Yin Junxieabb6e3bdc75
diff --git a/apps/daemon/src/api/server.ts b/apps/daemon/src/api/server.tsindex a8fb0010..5d8441a2 100644--- a/apps/daemon/src/api/server.ts+++ b/apps/daemon/src/api/server.ts@@ -622,8 +622,10 @@ export async function buildServer(input: BuildServerInput) {}});+ let getCreatorYtDlpRuntime: (() => ReturnType<typeof resolveYtDlpRuntime>) | undefined;const videoMetadataService = input.videoMetadataService ?? createVideoMetadataService({- getProxy: async () => (await creatorServicesConfigStore.read()).proxy.trim()+ getProxy: async () => (await creatorServicesConfigStore.read()).proxy.trim(),+ getYtDlpRuntime: () => getCreatorYtDlpRuntime?.()});const creatorService = input.creatorService ?? createCreatorService({jobsRoot: creatorJobsRoot,@@ -736,7 +738,6 @@ export async function buildServer(input: BuildServerInput) {let creatorFfprobePath: string | undefined;let creatorYtDlpUpdateManager = input.creatorYtDlpUpdateManager;let getYtDlpRuntime: (() => ReturnType<typeof resolveYtDlpRuntime>) | undefined;- let getCreatorYtDlpRuntime: (() => ReturnType<typeof resolveYtDlpRuntime>) | undefined;try {const runtimeManifest = readKrillinRuntimeManifest(creatorRuntimeRoot);let runtimeVerification: ReturnType<typeof startKrillinRuntimeVerification> | undefined;diff --git a/apps/daemon/src/creator/command-dispatcher.ts b/apps/daemon/src/creator/command-dispatcher.tsindex 39a322e6..f5b81c3d 100644--- a/apps/daemon/src/creator/command-dispatcher.ts+++ b/apps/daemon/src/creator/command-dispatcher.ts@@ -1,4 +1,5 @@import { createHash } from 'node:crypto';+import { videoSourceIdentity } from '@opencreator/protocol';import type {CreatorActionResponse,CreatorActor,@@ -296,6 +297,13 @@ function stageRequestProgress(stageId: string,input: Record<string, CreatorJson>): Record<string, CreatorJson> {+ if (job.templateId === 'video-translation' && stageId === 'preview-source-video') {+ const sourceUrl = job.state.sourceUrl;+ if (job.state.sourceType === 'file' || typeof sourceUrl !== 'string' || videoSourceIdentity(sourceUrl) === null) {+ throw new CreatorCommandError('unsupported_source', 'A supported public video URL is required for preview');+ }+ return { previewSourceUrl: sourceUrl };+ }if (job.templateId !== 'video-download'|| job.templateVersion < 2diff --git a/apps/daemon/src/creator/download/executor.ts b/apps/daemon/src/creator/download/executor.tsindex 7779d48c..35547a5b 100644--- a/apps/daemon/src/creator/download/executor.ts+++ b/apps/daemon/src/creator/download/executor.ts@@ -8,7 +8,7 @@ import type {DownloadOption,DownloadProbe} from '@opencreator/protocol';-import { extractDouyinShareUrl, parseBilibiliVideoSource, videoSourceIdentity } from '@opencreator/protocol';+import { extractDouyinShareUrl, normalizeVideoSourceUrl, supportedVideoSourcePlatform, parseBilibiliVideoSource, videoSourceIdentity } from '@opencreator/protocol';import { creatorResultSnapshotForVersion } from '../result-snapshots.js';import type {CreatorExecutor,@@ -50,13 +50,17 @@ type PlaybackOutput = PlaybackCodecs & {const YT_DLP_UTF8_ARGS = ['--encoding', 'utf-8'];+function isPreviewStage(stage: CreatorExecutorInput): boolean {+ return stage.stageRun.stageId === 'prepare-source-video' || stage.stageRun.stageId === 'preview-source-video';+}+export function createDownloadExecutor(input: DownloadExecutorOptions): CreatorExecutor {return {id: 'download',async run(stage) {- if (stage.job.templateId === 'video-translation' && stage.stageRun.stageId === 'prepare-source-video') {+ if (stage.job.templateId === 'video-translation' && isPreviewStage(stage)) {return preparePreviewSource(input, stage);}const url = readSourceUrl(stage);@@ -297,15 +301,19 @@ async function preparePreviewSource(const snapshot = typeof version === 'number'? creatorResultSnapshotForVersion(stage.job, version): undefined;- const sourceUrl = snapshot?.state.sourceUrl;+ const draftPreview = stage.stageRun.stageId === 'preview-source-video';+ const sourceState = draftPreview+ ? { ...stage.job.state, sourceType: 'url', sourceUrl: stage.stageRun.progress.previewSourceUrl ?? null }+ : snapshot?.state;+ const sourceUrl = sourceState?.sourceUrl;const identity = typeof sourceUrl === 'string' ? videoSourceIdentity(sourceUrl) : null;- if (snapshot === undefined || snapshot.state.sourceType === 'file' || typeof sourceUrl !== 'string' || identity === null) {+ if (sourceState === undefined || sourceState.sourceType === 'file' || typeof sourceUrl !== 'string' || identity === null) {throw new CreatorExecutorError('creator_action_input_invalid',- 'A saved YouTube or Bilibili result source is required for preview'+ 'A saved supported public video result source is required for preview');}- const resolvedStage = { ...stage, job: { ...stage.job, state: snapshot.state } };+ const resolvedStage = { ...stage, job: { ...stage.job, state: sourceState } };const candidates = [...stage.job.artifacts].reverse().filter(artifact => {if (artifact.kind !== 'source_video' || artifact.status !== 'completed' || artifact.path === null) return false;const settings = artifact.metadata.settingsSnapshot;@@ -341,7 +349,8 @@ async function preparePreviewSource(videoCodec: output.videoCodec,audioCodec: output.audioCodec,pixelFormat: output.pixelFormat,- settingsSnapshot: snapshot.state,+ settingsSnapshot: sourceState,+ previewOnly: draftPreview,cacheReused: true,playbackCompatible: true,normalizedForPlayback: output.normalizedForPlayback@@ -359,7 +368,7 @@ async function preparePreviewSource(}const bilibili = parseBilibiliVideoSource(sourceUrl);const url = bilibili === null- ? sourceUrl+ ? normalizeVideoSourceUrl(sourceUrl): `https://www.bilibili.com/video/${bilibili.videoId}?p=${bilibili.partIndex ?? 1}`;const proxy = (await input.configStore.read()).proxy.trim();return downloadPlaybackSource(input, url, proxy, resolvedStage);@@ -371,7 +380,7 @@ async function downloadPlaybackSource(proxy: string,stage: CreatorExecutorInput): Promise<CreatorExecutorResult> {- const preview = stage.stageRun.stageId === 'prepare-source-video';+ const preview = isPreviewStage(stage);stage.reportProgress({status: 'running',phase: 'preparing_download',@@ -466,6 +475,7 @@ async function downloadPlaybackSource(source: preview ? 'video-translation-preview' : 'stickman-video',sourceUrl: url,...(preview ? { settingsSnapshot: stage.job.state } : {}),+ ...(stage.stageRun.stageId === 'preview-source-video' ? { previewOnly: true } : {}),videoCodec: output.videoCodec,audioCodec: output.audioCodec,pixelFormat: output.pixelFormat,@@ -806,7 +816,7 @@ async function normalizeVideoForPlayback(stage.reportProgress({status: 'running',phase: 'normalizing_media',- percent: stage.stageRun.stageId === 'prepare-source-video' ? null : 98,+ percent: isPreviewStage(stage) ? null : 98,message: 'Converting video for local playback'});const outputPath = playbackOutputPath(path);@@ -878,7 +888,7 @@ function reportPlaybackConversionProgress(line: string,duration: number | null): void {- if (duration === null || duration <= 0 || stage.stageRun.stageId === 'prepare-source-video') return;+ if (duration === null || duration <= 0 || isPreviewStage(stage)) return;const match = line.match(/^out_time=(\d+):(\d+):([\d.]+)$/);if (match === null) return;const elapsed = (@@ -1292,16 +1302,7 @@ function readSourceUrl(stage: CreatorExecutorInput): string {}function normalizeSourceUrl(value: string): string {- const trimmed = extractDouyinShareUrl(value);- try {- const parsed = new URL(trimmed);- if (isDouyinFeaturedVideoUrl(parsed)) {- return `https://www.douyin.com/video/${parsed.searchParams.get('modal_id')}`;- }- } catch {- return trimmed;- }- return trimmed;+ return normalizeVideoSourceUrl(value);}function mimeTypeFor(path: string): string {@@ -1323,86 +1324,7 @@ function sha256File(path: string): Promise<string> {}function isSupported(value: string): boolean {- try {- const parsed = new URL(value);- const host = parsed.hostname.toLowerCase();- return parsed.protocol === 'https:'- && (- host === 'youtu.be'- || host === 'youtube.com'- || host.endsWith('.youtube.com')- || host === 'b23.tv'- || host === 'bilibili.com'- || host.endsWith('.bilibili.com')- || host === 'x.com'- || host.endsWith('.x.com')- || host === 'twitter.com'- || host.endsWith('.twitter.com')- || isTikTokVideoUrl(parsed)- || isInstagramVideoUrl(parsed)- || isDouyinVideoUrl(parsed)- || isFacebookVideoUrl(parsed)- || isXiaohongshuVideoUrl(parsed)- || isPinterestVideoUrl(parsed)- );- } catch {- return false;- }-}--function isTikTokVideoUrl(url: URL): boolean {- const host = url.hostname.toLowerCase();- if (host === 'vm.tiktok.com' || host === 'vt.tiktok.com') {- return /^\/[\w-]+\/?$/.test(url.pathname);- }- return (host === 'tiktok.com' || host.endsWith('.tiktok.com'))- && /^\/@[^/]+\/video\/\d+\/?$/.test(url.pathname);-}--function isInstagramVideoUrl(url: URL): boolean {- const host = url.hostname.toLowerCase();- return (host === 'instagram.com' || host === 'www.instagram.com')- && /^\/(?:reel|p|tv)\/[\w-]+\/?$/.test(url.pathname);-}--function isDouyinVideoUrl(url: URL): boolean {- const host = url.hostname.toLowerCase();- if (host === 'v.douyin.com') {- return /^\/[\w-]+\/?$/.test(url.pathname);- }- return (host === 'douyin.com' || host === 'www.douyin.com')- && (/^\/video\/\d+\/?$/.test(url.pathname) || isDouyinFeaturedVideoUrl(url));-}--function isDouyinFeaturedVideoUrl(url: URL): boolean {- return (url.hostname === 'douyin.com' || url.hostname === 'www.douyin.com')- && url.pathname === '/jingxuan'- && /^\d+$/.test(url.searchParams.get('modal_id') ?? '');-}--function isFacebookVideoUrl(url: URL): boolean {- const host = url.hostname.toLowerCase();- if (host === 'fb.watch') {- return /^\/[\w-]+\/?$/.test(url.pathname);- }- if (!['facebook.com', 'www.facebook.com', 'm.facebook.com'].includes(host)) {- return false;- }- return /^\/watch\/?$/.test(url.pathname)- ? /^\d+$/.test(url.searchParams.get('v') ?? '')- : /^\/(?:reel\/\d+|videos\/\d+|[^/]+\/videos\/\d+)\/?$/.test(url.pathname);-}--function isXiaohongshuVideoUrl(url: URL): boolean {- const host = url.hostname.toLowerCase();- return (host === 'xiaohongshu.com' || host === 'www.xiaohongshu.com')- && /^\/explore\/[0-9a-f]{24}\/?$/i.test(url.pathname);-}--function isPinterestVideoUrl(url: URL): boolean {- const host = url.hostname.toLowerCase();- return (host === 'pinterest.com' || host === 'www.pinterest.com')- && /^\/pin\/\d+\/?$/.test(url.pathname);+ return supportedVideoSourcePlatform(value) !== null;}function isYoutube(value: string): boolean {diff --git a/apps/daemon/src/creator/krillin/adapter.ts b/apps/daemon/src/creator/krillin/adapter.tsindex d66264b8..c2ea9b51 100644--- a/apps/daemon/src/creator/krillin/adapter.ts+++ b/apps/daemon/src/creator/krillin/adapter.ts@@ -1,5 +1,5 @@import { copyFile, link, lstat, mkdir, realpath, rename, writeFile } from 'node:fs/promises';-import { videoSourceIdentity } from '@opencreator/protocol';+import { normalizeVideoSourceUrl, videoSourceIdentity } from '@opencreator/protocol';import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import type {CreatorArtifact,@@ -221,7 +221,7 @@ export function normalizeKrillinFailure(error: { code?: string; message?: stringexport function buildKrillinStageOptions(input: CreatorExecutorInput): Record<string, unknown> {const state = input.job.state;return compactObject({- sourceUrl: typeof state.sourceUrl === 'string' ? state.sourceUrl : undefined,+ sourceUrl: typeof state.sourceUrl === 'string' ? normalizeVideoSourceUrl(state.sourceUrl) : undefined,originLanguage: normalizeKrillinLanguage(typeof state.sourceLanguage === 'string' ? state.sourceLanguage : undefined),diff --git a/apps/daemon/src/creator/preflight.ts b/apps/daemon/src/creator/preflight.tsindex 8aa1ceeb..f233b27c 100644--- a/apps/daemon/src/creator/preflight.ts+++ b/apps/daemon/src/creator/preflight.ts@@ -115,7 +115,7 @@ export function createCreatorPreflight(input: {if (stage.resultVersionPolicy === 'attach' && inputSnapshot === undefined) {add('blocked', { id: 'input-result-version', title: '请先选择项目版本', message: '准备预览视频需要明确的已保存项目版本。', executionMode: 'local' });}- if (job.templateId === 'video-translation' && (stage.id === 'subtitle' || stage.id === 'prepare-source-video')) {+ if (job.templateId === 'video-translation' && (stage.id === 'subtitle' || stage.id === 'prepare-source-video' || stage.id === 'preview-source-video')) {try {await validateBilibiliSource({ ...job, state: inputState }, input.videoMetadataService);} catch (error) {diff --git a/apps/daemon/src/creator/service.ts b/apps/daemon/src/creator/service.tsindex f4829c2d..347b0192 100644--- a/apps/daemon/src/creator/service.ts+++ b/apps/daemon/src/creator/service.ts@@ -1154,7 +1154,9 @@ export function createCreatorService(input: {if (stage.resultVersionPolicy === 'attach' && parsedInput.inputResultVersion === undefined) {throw new CreatorServiceError('creator_action_input_invalid', 'A result version is required to prepare preview media');}- if (stage.resultVersionPolicy === 'attach' && current.stages.some(run => run.status === 'queued' || run.status === 'running')) {+ if ((stage.resultVersionPolicy === 'attach' || stage.id === 'preview-source-video'+ || current.stages.some(run => run.stageId === 'preview-source-video' && (run.status === 'queued' || run.status === 'running')))+ && current.stages.some(run => run.status === 'queued' || run.status === 'running')) {throw new CreatorServiceError('creator_stage_already_running', 'Wait for the current stage to finish before preparing preview media');}nextState = { ...nextState, currentStage: stageId };diff --git a/apps/daemon/src/creator/templates/video-translation-actions.ts b/apps/daemon/src/creator/templates/video-translation-actions.tsindex c87737e8..24aa0ed8 100644--- a/apps/daemon/src/creator/templates/video-translation-actions.ts+++ b/apps/daemon/src/creator/templates/video-translation-actions.ts@@ -1,5 +1,6 @@import {parseBilibiliVideoSource,+ supportedVideoSourcePlatform,type CreatorJob,type CreatorStageRun,type CreatorTtsProvider@@ -165,20 +166,22 @@ function validateSource(job: CreatorJob): void {}const value = job.state.sourceUrl;if (typeof value !== 'string' || !isSupportedVideoUrl(value)) {- throw new VideoTranslationWorkflowError('unsupported_source', 'Only YouTube and Bilibili public URLs are supported');+ throw new VideoTranslationWorkflowError('unsupported_source', 'Only public YouTube, Bilibili, X, TikTok, Instagram, Douyin, Facebook, Xiaohongshu, and Pinterest video URLs are supported');}}function isSupportedVideoUrl(value: string): boolean {try {- const source = new URL(value);- const host = source.hostname.toLowerCase();- const protocol = source.protocol;- return (protocol === 'http:' || protocol === 'https:')- && (host === 'youtu.be' || host === 'youtube.com' || host.endsWith('.youtube.com')- || host === 'b23.tv' || host === 'bilibili.com' || host.endsWith('.bilibili.com'));+ const source = new URL(value.trim());+ // Existing translation jobs may use HTTP YouTube or Bilibili links.+ if (source.protocol === 'http:') {+ source.protocol = 'https:';+ const platform = supportedVideoSourcePlatform(source.toString());+ return platform === 'youtube' || platform === 'bilibili';+ }+ return supportedVideoSourcePlatform(value) !== null;} catch {- return false;+ return supportedVideoSourcePlatform(value) !== null;}}diff --git a/apps/daemon/src/creator/templates/video-translation.ts b/apps/daemon/src/creator/templates/video-translation.tsindex 946116e2..e4709544 100644--- a/apps/daemon/src/creator/templates/video-translation.ts+++ b/apps/daemon/src/creator/templates/video-translation.ts@@ -121,6 +121,17 @@ function createVideoTranslationTemplateDefinition(version: 1 | 2): CreatorTempla],outputArtifacts: [{ kind: 'source_video', status: 'completed' }, { kind: 'vertical_video', status: 'completed' }]},+ {+ id: 'preview-source-video',+ executor: 'download',+ optional: true,+ resultVersionPolicy: 'none',+ jobCompletionPolicy: 'preserve',+ invalidateDependentArtifacts: false,+ allowedJobStatuses: ['draft', 'needs_input', 'failed', 'completed', 'canceled'],+ inputArtifacts: [],+ outputArtifacts: [{ kind: 'source_video', status: 'completed' }]+ },{id: 'prepare-source-video',executor: 'download',@@ -167,7 +178,7 @@ function createVideoTranslationTemplateDefinition(version: 1 | 2): CreatorTemplainputSchema: jsonRecord,allowedStages: ['subtitle', 'tts', 'render-horizontal', 'render-vertical']}- ].map(action => ({ ...action, allowedStages: [...action.allowedStages, 'prepare-source-video'] })),+ ].map(action => ({ ...action, allowedStages: [...action.allowedStages, 'prepare-source-video', 'preview-source-video'] })),outputs: [{ kind: 'target_subtitle', required: true },{ kind: 'horizontal_video', required: false },@@ -181,7 +192,8 @@ function createVideoTranslationTemplateDefinition(version: 1 | 2): CreatorTempla? '字幕样式只使用完整的 subtitleStyle 结构,不要使用 subtitleFont、subtitleSize、subtitleColor 或任意 ASS 标签。': '历史任务可读取旧字幕样式字段,不要改变其模板版本。','启动执行时使用 availableStageIds 中的 subtitle、tts、render-horizontal 或 render-vertical。',- '字幕已完成但需要视频预览时,使用 prepare-source-video 并明确 inputResultVersion。它仅补齐所选版本的原视频,不重新翻译或创建新版本。'+ '字幕已完成但需要视频预览时,使用 prepare-source-video 并明确 inputResultVersion。它仅补齐所选版本的原视频,不重新翻译或创建新版本。',+ '翻译前预览当前链接使用 preview-source-video,仅下载原视频,不启动翻译或创建结果版本。'].join(' ')};}diff --git a/apps/daemon/src/video-metadata/online-preview.ts b/apps/daemon/src/video-metadata/online-preview.tsnew file mode 100644index 00000000..b3b43d23--- /dev/null+++ b/apps/daemon/src/video-metadata/online-preview.ts@@ -0,0 +1,108 @@+import type { DownloadPlatform, VideoMetadataResponse } from '@opencreator/protocol';+import { spawnCreatorProcess } from '../creator/process-tree.js';+import { withYtDlpProxy } from '../creator/yt-dlp/args.js';+import type { YtDlpRuntime } from '../creator/yt-dlp/runtime.js';++export async function resolveOnlineVideoMetadata(input: {+ url: string;+ platform: DownloadPlatform;+ runtime: YtDlpRuntime;+ proxy: string;+}): Promise<VideoMetadataResponse> {+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 15_000);+ timeout.unref();+ try {+ const payload = await new Promise<unknown>((resolve, reject) => {+ const child = spawnCreatorProcess(input.runtime.executable, [+ ...input.runtime.prefixArgs,+ ...withYtDlpProxy([+ '--encoding', 'utf-8', '--skip-download', '--dump-single-json',+ '--no-playlist', '--no-warnings', '--ignore-no-formats-error',+ '--socket-timeout', '8', '--retries', '0', '--', input.url+ ], input.proxy)+ ], { stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...input.runtime.env } }, controller.signal);+ const chunks: Buffer[] = [];+ let size = 0;+ child.stdout?.on('data', (chunk: Buffer) => {+ size += chunk.length;+ if (size > 4 * 1024 * 1024) {+ controller.abort();+ reject(new Error('Video preview metadata is too large'));+ return;+ }+ chunks.push(chunk);+ });+ // Drain diagnostics without returning extractor output or signed URLs in errors.+ child.stderr?.on('data', () => undefined);+ child.once('error', reject);+ child.once('close', code => {+ if (code !== 0 || controller.signal.aborted) {+ reject(new Error('Online video preview could not be resolved'));+ return;+ }+ try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); }+ catch { reject(new Error('Video preview metadata is invalid')); }+ });+ });+ return parseOnlineVideoMetadata(payload, input.platform);+ } finally {+ clearTimeout(timeout);+ }+}++export function parseOnlineVideoMetadata(payload: unknown, platform: DownloadPlatform): VideoMetadataResponse {+ if (!isRecord(payload)) throw new Error('Video preview metadata is invalid');+ const formats = Array.isArray(payload.formats) ? payload.formats.filter(isRecord) : [];+ const silentSource = payload.acodec === 'none' && !Array.isArray(payload.requested_formats);+ // Native video playback requires a single progressive resource, not separate audio/video tracks or an HLS manifest.+ const playable = [payload, ...formats].filter(format => {+ const protocol = format.protocol;+ return safeMediaUrl(format.url) !== undefined+ && (protocol === undefined || protocol === 'https' || protocol === 'http')+ && format.ext === 'mp4'+ && (typeof format.vcodec === 'string' && /^(?:avc1|h264)/i.test(format.vcodec)+ || format.vcodec == null && dimension(format.width) !== undefined && dimension(format.height) !== undefined)+ && (typeof format.acodec === 'string' && /^(?:mp4a|aac)/i.test(format.acodec)+ || format.acodec == null || format.acodec === 'none' && silentSource)+ && !Array.isArray(format.requested_formats);+ }).sort((left, right) => score(right) - score(left))[0];+ const previewUrl = safeMediaUrl(playable?.url);+ const thumbnailUrl = safeMediaUrl(payload.thumbnail);+ const authorName = boundedText(payload.uploader ?? payload.creator, 160);+ const width = dimension(playable?.width ?? payload.width);+ const height = dimension(playable?.height ?? payload.height);+ return {+ platform,+ title: boundedText(payload.title, 300) ?? boundedText(payload.id, 128) ?? platform,+ ...(previewUrl === undefined ? {} : { previewUrl }),+ ...(thumbnailUrl === undefined ? {} : { thumbnailUrl }),+ ...(authorName === undefined ? {} : { authorName }),+ ...(width === undefined || height === undefined ? {} : { width, height })+ };+}++function score(format: Record<string, unknown>): number {+ const height = dimension(format.height) ?? 0;+ return height <= 1080 ? height : -height;+}++function safeMediaUrl(value: unknown): string | undefined {+ if (typeof value !== 'string' || value.length > 8192) return undefined;+ try {+ const url = new URL(value);+ return url.protocol === 'https:' && !url.username && !url.password ? url.toString() : undefined;+ } catch { return undefined; }+}++function boundedText(value: unknown, maximum: number): string | undefined {+ return typeof value === 'string' && value.trim() ? value.trim().slice(0, maximum) : undefined;+}++function dimension(value: unknown): number | undefined {+ return typeof value === 'number' && Number.isInteger(value) && value > 0 && value <= 16_384 ? value : undefined;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}diff --git a/apps/daemon/src/video-metadata/service.ts b/apps/daemon/src/video-metadata/service.tsindex 1ba30389..620df504 100644--- a/apps/daemon/src/video-metadata/service.ts+++ b/apps/daemon/src/video-metadata/service.ts@@ -1,6 +1,8 @@-import { parseBilibiliVideoSource, type VideoMetadataResponse, type VideoSourcePart } from '@opencreator/protocol';+import { normalizeVideoSourceUrl, supportedVideoSourcePlatform, parseBilibiliVideoSource, type VideoMetadataResponse, type VideoSourcePart } from '@opencreator/protocol';import { request as httpsRequest } from 'node:https';import { HttpsProxyAgent } from 'https-proxy-agent';+import type { YtDlpRuntime } from '../creator/yt-dlp/runtime.js';+import { resolveOnlineVideoMetadata } from './online-preview.js';const METADATA_TIMEOUT_MS = 5_000;@@ -20,10 +22,22 @@ export type VideoMetadataService = {export function createVideoMetadataService(input: {fetchImpl?: typeof fetch;getProxy?(): string | Promise<string>;+ getYtDlpRuntime?(): YtDlpRuntime | undefined;} = {}): VideoMetadataService {const cache = new Map<string, { payload: unknown; expiresAt: number }>();return {async get(value: string): Promise<VideoMetadataResponse> {+ const normalized = normalizeVideoSourceUrl(value);+ const platform = supportedVideoSourcePlatform(normalized);+ if (platform !== null && platform !== 'youtube' && platform !== 'bilibili') {+ const runtime = input.getYtDlpRuntime?.();+ if (runtime === undefined) throw new VideoMetadataError('UPSTREAM_ERROR', 'Online video preview resolver is unavailable');+ try {+ return await resolveOnlineVideoMetadata({ url: normalized, platform, runtime, proxy: await resolveProxy(input.getProxy) });+ } catch {+ throw new VideoMetadataError('UPSTREAM_ERROR', 'Online video preview is unavailable for this source');+ }+ }const source = parseVideoSource(value);const endpoint = createMetadataEndpoint(source);const cached = cache.get(endpoint.href);diff --git a/apps/daemon/test/integration/creator-video-preview.test.ts b/apps/daemon/test/integration/creator-video-preview.test.tsindex 069dde98..ff022d78 100644--- a/apps/daemon/test/integration/creator-video-preview.test.ts+++ b/apps/daemon/test/integration/creator-video-preview.test.ts@@ -9,6 +9,51 @@ import { createCreatorService } from '../../src/creator/service.js';import { createDefaultCreatorTemplateRegistry } from '../../src/creator/templates/registry.js';import { openRuntimeDatabase } from '../../src/storage/database.js';+it('preflights and serves a draft Douyin preview without translation configuration or result versions', async () => {+ const directory = mkdtempSync(join(tmpdir(), 'creator-draft-preview-api-'));+ const db = openRuntimeDatabase(join(directory, 'runtime.sqlite'));+ const repository = createCreatorRepository(db);+ const service = createCreatorService({ repository, templates: createDefaultCreatorTemplateRegistry() });+ const sourceUrl = 'https://v.douyin.com/example/';+ const initial = service.createJob({ projectId: 'preview-project', templateId: 'video-translation', state: { sourceType: 'url', sourceUrl } });+ const server = await buildServer({ db, token: 'secret', dataDir: directory, codexHome: join(directory, 'codex-home'),+ creatorExecutors: [{ id: 'download', async run({ stageRun, workdir, reportProgress }) {+ expect(stageRun.stageId).toBe('preview-source-video');+ expect(stageRun.progress.previewSourceUrl).toBe(sourceUrl);+ reportProgress({ phase: 'downloading', percent: 25, downloadedBytes: 25, totalBytes: 100, message: 'Downloading preview' });+ const path = join(workdir, 'preview.mp4');+ writeFileSync(path, 'draft-preview-video');+ return { outputs: [{ kind: 'source_video', path, status: 'completed', sourceArtifactIds: [],+ metadata: { sourceUrl, settingsSnapshot: { sourceType: 'url', sourceUrl }, previewOnly: true, playbackCompatible: true } }] };+ } }]+ });+ const headers = { authorization: 'Bearer secret' };+ const route = `/creator/jobs/${initial.id}`;+ try {+ const preflight = await server.inject({ method: 'GET', url: `${route}/preflight?stageId=preview-source-video`, headers });+ expect(preflight.statusCode).toBe(200);+ expect(preflight.json().canStart).toBe(true);+ const started = await server.inject({ method: 'POST', url: `${route}/actions`, headers, payload: {+ action: 'run-stage', expectedRevision: initial.revision, idempotencyKey: 'draft-preview', input: { stageId: 'preview-source-video' }+ } });+ expect(started.statusCode).toBe(200);+ await expect.poll(() => repository.getJob(initial.id)!.stages.at(-1)!.status).toBe('succeeded');+ const after = repository.getJob(initial.id)!;+ expect(after.status).toBe('draft');+ expect(after.state.resultVersion).toBeUndefined();+ expect(readCreatorResultSnapshots(after.state.resultSnapshots)).toEqual([]);+ const source = after.artifacts[0]!;+ const content = await server.inject({ method: 'GET', url: `${route}/artifacts/${source.id}/content`, headers });+ expect(content.statusCode).toBe(200);+ expect(content.headers['content-type']).toContain('video/mp4');+ expect(content.body).toBe('draft-preview-video');+ } finally {+ await server.close();+ if (db.open) db.close();+ rmSync(directory, { recursive: true, force: true });+ }+});+it('preflights, cancels, resumes, and serves preview media for a completed historical result without retranslation', async () => {const directory = mkdtempSync(join(tmpdir(), 'creator-video-preview-api-'));const db = openRuntimeDatabase(join(directory, 'runtime.sqlite'));diff --git a/apps/daemon/test/integration/video-metadata-api.test.ts b/apps/daemon/test/integration/video-metadata-api.test.tsindex 87c9b12b..f5025f70 100644--- a/apps/daemon/test/integration/video-metadata-api.test.ts+++ b/apps/daemon/test/integration/video-metadata-api.test.ts@@ -67,6 +67,17 @@ describe('video metadata API', () => {expect(fetchImpl).not.toHaveBeenCalled();});+ it('resolves a Douyin share link into metadata and an online video URL without downloading', async () => {+ const payload = { title: 'Douyin preview', thumbnail: 'https://media.example.com/cover.jpg',+ formats: [{ url: 'https://media.example.com/video.mp4', ext: 'mp4', protocol: 'https', vcodec: 'h264', acodec: 'aac', width: 1080, height: 1920 }] };+ await registerVideoMetadataRoutes(server, createVideoMetadataService({ getProxy: () => '', getYtDlpRuntime: () => ({+ version: 'test', executable: process.execPath, prefixArgs: ['-e', `if(!process.argv.includes('--skip-download'))process.exit(1);process.stdout.write(${JSON.stringify(JSON.stringify(payload))})`, '--'], env: {}+ }) }));+ const response = await server.inject({ method: 'GET', url: `/video-metadata?${new URLSearchParams({ url: 'https://v.douyin.com/example/' })}` });+ expect(response.statusCode).toBe(200);+ expect(response.json()).toMatchObject({ platform: 'douyin', title: 'Douyin preview', previewUrl: 'https://media.example.com/video.mp4', width: 1080, height: 1920 });+ });+it('returns title information for a Bilibili video', async () => {const fetchImpl = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => new Response(JSON.stringify({code: 0,diff --git a/apps/daemon/test/unit/creator-download-executor.test.ts b/apps/daemon/test/unit/creator-download-executor.test.tsindex 74227500..b6e229c0 100644--- a/apps/daemon/test/unit/creator-download-executor.test.ts+++ b/apps/daemon/test/unit/creator-download-executor.test.ts@@ -29,6 +29,38 @@ afterEach(async () => {});describe('creator download executor', () => {+ it('downloads the queued draft source even if the URL changes before execution', async () => {+ const executor = createDownloadExecutor(await fakeBinaries());+ const workdir = join(tempDir, 'draft-preview');+ await mkdir(workdir);+ const sourceUrl = 'https://www.douyin.com/video/7490000000000000001';+ const reportProgress = vi.fn();+ const stage = previewInput({ workdir, sourceUrl, reportProgress });+ stage.stageRun.stageId = 'preview-source-video';+ stage.stageRun.progress = { previewSourceUrl: sourceUrl };+ stage.job.state.resultSnapshots = [];+ const result = await executor.run(stage);+ expect(JSON.parse(await readFile(join(workdir, 'args.json'), 'utf8'))).toContain(sourceUrl);+ expect(result.outputs[0]).toMatchObject({ kind: 'source_video', metadata: {+ previewOnly: true, playbackCompatible: true, settingsSnapshot: { sourceType: 'url', sourceUrl }+ } });+ expect(reportProgress).toHaveBeenCalledWith(expect.objectContaining({ phase: 'downloading', percent: 42 }));+ });+ it.each([+ 'https://x.com/creator/status/123', 'https://www.tiktok.com/@creator/video/123',+ 'https://www.instagram.com/reel/abc123/', 'https://www.douyin.com/video/123',+ 'https://www.facebook.com/watch/?v=123',+ 'https://www.xiaohongshu.com/explore/6a9149f3000000001f01d20a?xsec_token=sample%3D',+ 'https://www.pinterest.com/pin/123/'+ ])('prepares saved translation previews from the added platform: %s', async sourceUrl => {+ const executor = createDownloadExecutor(await fakeBinaries());+ const workdir = join(tempDir, 'preview');+ await mkdir(workdir);+ const result = await executor.run(previewInput({ workdir, sourceUrl }));+ expect(JSON.parse(await readFile(join(workdir, 'args.json'), 'utf8'))).toContain(sourceUrl);+ expect(result.outputs[0]).toMatchObject({ kind: 'source_video', status: 'completed',+ metadata: { playbackCompatible: true, settingsSnapshot: { sourceUrl } } });+ });it('prepares the saved Bilibili part without translating or using the current draft source', async () => {const executor = createDownloadExecutor(await fakeBinaries());const workdir = join(tempDir, 'preview');diff --git a/apps/daemon/test/unit/creator-krillin-adapter-dependency.test.ts b/apps/daemon/test/unit/creator-krillin-adapter-dependency.test.tsindex 07433dc8..8fa2e730 100644--- a/apps/daemon/test/unit/creator-krillin-adapter-dependency.test.ts+++ b/apps/daemon/test/unit/creator-krillin-adapter-dependency.test.ts@@ -33,6 +33,28 @@ afterEach(() => {});describe('KrillinAI configured transcription dependency', () => {+ it.each([+ ['分享视频 https://v.douyin.com/abc123/ 复制打开抖音', 'https://v.douyin.com/abc123/'],+ ['https://www.douyin.com/jingxuan?modal_id=123', 'https://www.douyin.com/video/123'],+ ['https://www.xiaohongshu.com/explore/6a9149f3000000001f01d20a?xsec_token=sample%3D',+ 'https://www.xiaohongshu.com/explore/6a9149f3000000001f01d20a?xsec_token=sample%3D']+ ])('transcribes added translation sources with normalized URLs and preserved tokens: %s', async (sourceUrl, expected) => {+ const fixture = setup();+ const stage = fixture.stage as CreatorExecutorInput;+ stage.job.templateId = 'video-translation';+ stage.job.state.sourceType = 'url';+ stage.job.state.sourceUrl = sourceUrl;+ stage.inputArtifacts = [];+ runKrillinCli.mockImplementation(async input => {+ const subtitle = writeTargetSubtitle(input.jobsRoot);+ return ['source_subtitle', 'target_subtitle', 'vertical_subtitle'].map(kind => ({ ...subtitle, kind }));+ });+ await fixture.executor.run(stage);+ expect(fixture.ensure).toHaveBeenCalledTimes(1);+ expect(runKrillinCli).toHaveBeenCalledTimes(1);+ expect(runKrillinCli.mock.calls[0]?.[0]).toMatchObject({ source: expected, options: { sourceUrl: expected } });+ expect(runKrillinCli.mock.calls[0]?.[0].options.captionSource).not.toBe('platform');+ });it('uses the original YouTube URL without preparing transcription when platform captions succeed', async () => {const fixture = setup();runKrillinCli.mockImplementation(async input => [writeTargetSubtitle(input.jobsRoot)]);diff --git a/apps/daemon/test/unit/creator-video-preview.test.ts b/apps/daemon/test/unit/creator-video-preview.test.tsindex d3354d29..c0ba02c9 100644--- a/apps/daemon/test/unit/creator-video-preview.test.ts+++ b/apps/daemon/test/unit/creator-video-preview.test.ts@@ -50,6 +50,50 @@ function setup(executor: CreatorExecutor, templateVersion = 2) {}describe('video translation preview preparation', () => {+ it.each([1, 2])('previews a draft URL without creating a result or changing job status (template v%s)', async templateVersion => {+ const url = 'https://www.douyin.com/video/7490000000000000001';+ const context = setup({ id: 'download', async run(stage) {+ expect(stage.stageRun.progress.previewSourceUrl).toBe(url);+ const path = join(stage.workdir, 'preview.mp4');+ writeFileSync(path, 'preview');+ return { outputs: [{ kind: 'source_video', path, status: 'completed', sourceArtifactIds: [], metadata: { sourceUrl: url, previewOnly: true } }] };+ } }, templateVersion);+ try {+ const draft = context.service.createJob({ projectId: 'preview-project', templateId: 'video-translation', templateVersion,+ state: { sourceType: 'url', sourceUrl: url } });+ const started = context.dispatcher.dispatch(draft.id, { action: 'run-stage', expectedRevision: draft.revision, idempotencyKey: 'draft-preview',+ input: { stageId: 'preview-source-video' } }, 'user');+ expect(() => context.dispatcher.dispatch(draft.id, { action: 'run-stage', expectedRevision: started.job.revision, idempotencyKey: 'duplicate-preview',+ input: { stageId: 'preview-source-video' } }, 'user')).toThrow();+ expect(() => context.dispatcher.dispatch(draft.id, { action: 'run-stage', expectedRevision: started.job.revision, idempotencyKey: 'translation-during-preview',+ input: { stageId: 'subtitle' } }, 'user')).toThrow();+ expect((await context.runner.runStageRun(started.commandReceipt.stageRunId!)).status).toBe('succeeded');+ const after = context.service.getJob(draft.id)!;+ expect(after.status).toBe('draft');+ expect(after.state.resultVersion).toBeUndefined();+ expect(readCreatorResultSnapshots(after.state.resultSnapshots)).toEqual([]);+ expect(after.artifacts).toHaveLength(1);+ expect(after.artifacts[0]!.metadata.resultVersion).toBeUndefined();+ } finally { await context.close(); }+ });++ it('preserves draft status on preview failure and rejects unsupported sources', async () => {+ const context = setup({ id: 'download', async run() { throw new CreatorExecutorError('network_unavailable', 'Preview download failed'); } });+ try {+ const draft = context.service.createJob({ projectId: 'preview-project', templateId: 'video-translation', templateVersion: 2,+ state: { sourceType: 'url', sourceUrl: 'https://v.douyin.com/example/' } });+ const started = context.dispatcher.dispatch(draft.id, { action: 'run-stage', expectedRevision: draft.revision, idempotencyKey: 'failure-preview',+ input: { stageId: 'preview-source-video' } }, 'user');+ expect((await context.runner.runStageRun(started.commandReceipt.stageRunId!)).status).toBe('failed');+ expect(context.service.getJob(draft.id)!.status).toBe('draft');+ const invalid = context.service.createJob({ projectId: 'preview-project', templateId: 'video-translation', templateVersion: 2,+ state: { sourceType: 'url', sourceUrl: 'https://example.com/video' } });+ expect(() => context.dispatcher.dispatch(invalid.id, { action: 'run-stage', expectedRevision: invalid.revision, idempotencyKey: 'invalid-preview',+ input: { stageId: 'preview-source-video' } }, 'user')).toThrow();+ expect(context.service.getJob(invalid.id)!.revision).toBe(invalid.revision);+ } finally { await context.close(); }+ });+it.each([1, 2])('attaches video to the selected result without creating versions or changing subtitles (template v%s)', async templateVersion => {const context = setup({ id: 'download', async run(stage) {expect(stage.stageRun.progress.inputResultVersion).toBe(1);diff --git a/apps/daemon/test/unit/creator-video-translation-workflow.test.ts b/apps/daemon/test/unit/creator-video-translation-workflow.test.tsindex f2a103ad..6807b9f9 100644--- a/apps/daemon/test/unit/creator-video-translation-workflow.test.ts+++ b/apps/daemon/test/unit/creator-video-translation-workflow.test.ts@@ -90,8 +90,16 @@ describe('video translation workflow', () => {it.each(['https://www.youtube.com/watch?v=xVWS7yHdzCU',- 'https://youtu.be/tAkC-ZdaqWs?si=6LcL-jgzdBaZ1IFD'- ])('accepts the supported YouTube URL form: %s', async sourceUrl => {+ 'https://youtu.be/tAkC-ZdaqWs?si=6LcL-jgzdBaZ1IFD',+ 'https://x.com/creator/status/123',+ 'https://www.tiktok.com/@creator/video/123',+ 'https://www.instagram.com/reel/abc123/',+ '分享视频 https://v.douyin.com/abc123/ 复制打开抖音',+ 'https://www.douyin.com/jingxuan?modal_id=123',+ 'https://www.facebook.com/watch/?v=123',+ 'https://www.xiaohongshu.com/explore/6a9149f3000000001f01d20a?xsec_token=sample%3D',+ 'https://www.pinterest.com/pin/123/'+ ])('accepts the supported public video URL form: %s', async sourceUrl => {const fixture = setup({ sourceUrl });const config = createDefaultCreatorServicesConfig();config.llm.apiKey = 'llm-key';@@ -106,6 +114,17 @@ describe('video translation workflow', () => {fixture.db.close();});+ it.each(['https://www.instagram.com/creator/', 'https://www.pinterest.com/creator/',+ 'https://notxiaohongshu.com/explore/6a9149f3000000001f01d20a'])('rejects unsupported translation sources: %s', async sourceUrl => {+ const fixture = setup({ sourceUrl });+ const workflow = createVideoTranslationWorkflow({ creator: fixture.service, dispatcher: fixture.dispatcher,+ configStore: { read: async () => createDefaultCreatorServicesConfig() } });+ try {+ await expect(workflow.validateStage(fixture.service.getJob(fixture.jobId)!, 'subtitle'))+ .rejects.toMatchObject({ code: 'unsupported_source' });+ } finally { fixture.db.close(); }+ });+it('queues the selected stages in order through the command dispatcher', async () => {const fixture = setup({ dubbing: true, composeVideo: true, videoFormat: 'all' });const config = createDefaultCreatorServicesConfig();diff --git a/apps/daemon/test/unit/video-online-preview.test.ts b/apps/daemon/test/unit/video-online-preview.test.tsnew file mode 100644index 00000000..9704bcfb--- /dev/null+++ b/apps/daemon/test/unit/video-online-preview.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';+import { parseOnlineVideoMetadata, resolveOnlineVideoMetadata } from '../../src/video-metadata/online-preview.js';++const progressive = { url: 'https://media.example.com/video.mp4?token=signed', protocol: 'https', ext: 'mp4', vcodec: 'avc1.64001f', acodec: 'mp4a.40.2', width: 1920, height: 1080 };++describe('online video preview resolution', () => {+ it('chooses a progressive video with audio and excludes HLS, split tracks, incompatible codecs and unsafe URLs', () => {+ const metadata = parseOnlineVideoMetadata({ title: ' Preview title ', uploader: 'Creator', thumbnail: 'https://media.example.com/cover.jpg',+ formats: [+ { ...progressive, height: 2160, url: 'https://media.example.com/4k.mp4' },+ { ...progressive, acodec: 'none', url: 'https://media.example.com/video-only.mp4' },+ { ...progressive, protocol: 'm3u8_native', url: 'https://media.example.com/list.m3u8' },+ { ...progressive, vcodec: 'hevc', url: 'https://media.example.com/hevc.mp4' },+ { ...progressive, url: 'javascript:alert(1)' },+ progressive+ ]+ }, 'douyin');+ expect(metadata).toEqual({ platform: 'douyin', title: 'Preview title', authorName: 'Creator', thumbnailUrl: 'https://media.example.com/cover.jpg',+ previewUrl: progressive.url, width: 1920, height: 1080 });+ });++ it('retains the poster and title when there is no native playback format', () => {+ expect(parseOnlineVideoMetadata({ title: 'Poster only', thumbnail: 'https://media.example.com/cover.jpg', formats: [+ { ...progressive, protocol: 'm3u8_native' }+ ] }, 'pinterest')).toEqual({ platform: 'pinterest', title: 'Poster only', thumbnailUrl: 'https://media.example.com/cover.jpg' });+ });++ it('resolves metadata with skip-download and uses the configured runtime and proxy', async () => {+ const script = `process.stdout.write(JSON.stringify({title:process.argv.slice(1).join(' '),formats:[${JSON.stringify(progressive)}]}))`;+ const result = await resolveOnlineVideoMetadata({ url: 'https://v.douyin.com/example/', platform: 'douyin', proxy: 'http://127.0.0.1:7897',+ runtime: { version: 'test', executable: process.execPath, prefixArgs: ['-e', script, '--'], env: {} } });+ expect(result.previewUrl).toBe(progressive.url);+ expect(result.title).toContain('--skip-download');+ expect(result.title).toContain('--dump-single-json');+ expect(result.title).toContain('--proxy http://127.0.0.1:7897');+ expect(result.title).toContain('https://v.douyin.com/example/');+ });++ it('rejects an extractor failure without exposing its diagnostics', async () => {+ await expect(resolveOnlineVideoMetadata({ url: 'https://v.douyin.com/example/', platform: 'douyin', proxy: '',+ runtime: { version: 'test', executable: process.execPath, prefixArgs: ['-e', 'process.stderr.write("sensitive signed URL");process.exit(1)', '--'], env: {} }+ })).rejects.toThrow('Online video preview could not be resolved');+ });+});diff --git a/apps/web/e2e/fixtures/online-preview.mp4 b/apps/web/e2e/fixtures/online-preview.mp4new file mode 100644index 00000000..bf76ada6Binary files /dev/null and b/apps/web/e2e/fixtures/online-preview.mp4 differdiff --git a/apps/web/e2e/video-translation-sources.spec.ts b/apps/web/e2e/video-translation-sources.spec.tsnew file mode 100644index 00000000..d66a0a99--- /dev/null+++ b/apps/web/e2e/video-translation-sources.spec.ts@@ -0,0 +1,88 @@+import type { CreatorJob } from '@opencreator/protocol';+import { readFileSync } from 'node:fs';+import { expect, test } from './fixtures/runtime.js';++test('视频翻译显示全部下载来源并接受抖音分享文本', async ({ page, runtime }, testInfo) => {+ await page.route('**/video-metadata?*', route => route.fulfill({ json: { platform: 'douyin', title: 'Douyin video' } }));+ const { job } = await runtime.api<{ job: CreatorJob }>('POST', '/creator/jobs', {+ projectId: runtime.projectId,+ templateId: 'video-translation',+ templateVersion: 2,+ state: {},+ creationKey: 'translation-platforms'+ });+ await runtime.openApp(page);+ await page.goto(`${runtime.origin}/#/workbench?tool=video-translation&jobId=${encodeURIComponent(job.id)}`);+ const platforms = page.getByRole('list', { name: '支持的平台' });+ await expect(platforms.locator('li')).toHaveCount(9);+ await expect.poll(() => platforms.locator('img').evaluateAll(images => images.every(image => (+ (image as HTMLImageElement).complete && (image as HTMLImageElement).naturalWidth > 0+ )))).toBe(true);+ const urlField = page.getByRole('textbox', { name: '视频链接' });+ const sourceRow = page.locator('.video-source-platforms-compact');+ const inputBounds = await urlField.locator('..').boundingBox();+ const sourceBounds = await sourceRow.boundingBox();+ expect(inputBounds).not.toBeNull();+ expect(sourceBounds).not.toBeNull();+ expect(sourceBounds!.x).toBeCloseTo(inputBounds!.x, 0);+ expect(sourceBounds!.width).toBeCloseTo(inputBounds!.width, 0);+ expect(sourceBounds!.y).toBeGreaterThan(inputBounds!.y + inputBounds!.height);+ expect(await platforms.locator('img').first().evaluate(image => image.getBoundingClientRect().width)).toBe(20);+ const pinterest = platforms.getByRole('img', { name: 'Pinterest', exact: true });+ await pinterest.hover();+ await expect(platforms.getByRole('tooltip', { name: 'Pinterest', exact: true })).toBeVisible();+ await urlField.hover();+ await expect(platforms.getByRole('tooltip', { name: 'Pinterest', exact: true })).toBeHidden();+ await pinterest.focus();+ await expect(platforms.getByRole('tooltip', { name: 'Pinterest', exact: true })).toBeVisible();+ await pinterest.press('Escape');+ await expect(platforms.getByRole('tooltip', { name: 'Pinterest', exact: true })).toBeHidden();+ await urlField.focus();+ expect(await platforms.evaluate(list => {+ const bounds = list.getBoundingClientRect();+ return [...list.querySelectorAll('li')].every(item => {+ const rect = item.getBoundingClientRect();+ return rect.left >= bounds.left && rect.right <= bounds.right;+ });+ })).toBe(true);+ await page.screenshot({ path: testInfo.outputPath('translation-sources.png'), fullPage: true });+ const url = 'https://v.douyin.com/abc123/';+ await urlField.fill(`分享视频 ${url} 复制打开抖音`);+ await expect(page.getByRole('link', { name: '打开原始链接' })).toHaveAttribute('href', url);+ await expect(page.getByRole('button', { name: '下载并预览' })).toBeEnabled();+ const originalLink = page.getByRole('link', { name: '打开原始链接' });+ const mediaBounds = await page.locator('.video-source-preview-media').boundingBox();+ const originalBounds = await originalLink.boundingBox();+ expect(originalBounds!.y + originalBounds!.height).toBeLessThan(mediaBounds!.y + mediaBounds!.height);+ await expect(page.getByText('此平台暂不支持内嵌预览')).toHaveCount(0);+ await page.screenshot({ path: testInfo.outputPath('translation-source-preview.png'), fullPage: true });+ await page.getByRole('button', { name: '继续', exact: true }).click();+ await expect(page.getByRole('heading', { name: '设置翻译语言' })).toBeVisible();+ await expect.poll(async () => runtime.api<{ job: CreatorJob }>('GET', `/creator/jobs/${job.id}`)+ .then(result => result.job.state.sourceUrl)).toBe(url);+});++test('视频来源优先在线播放且不会启动下载阶段', async ({ page, runtime }, testInfo) => {+ const media = readFileSync(new URL('./fixtures/online-preview.mp4', import.meta.url));+ await page.route('**/video-metadata?*', route => route.fulfill({ json: {+ platform: 'douyin', title: 'Douyin online preview', previewUrl: 'https://media.example.test/preview.mp4', width: 96, height: 160+ } }));+ await page.route('https://media.example.test/preview.mp4', route => route.fulfill({ contentType: 'video/mp4', body: media }));+ const { job } = await runtime.api<{ job: CreatorJob }>('POST', '/creator/jobs', {+ projectId: runtime.projectId, templateId: 'video-translation', templateVersion: 2,+ state: { sourceType: 'url', sourceUrl: 'https://v.douyin.com/online/' }, creationKey: 'translation-online-preview'+ });+ await runtime.openApp(page);+ await page.goto(`${runtime.origin}/#/workbench?tool=video-translation&jobId=${encodeURIComponent(job.id)}`);+ const video = page.getByLabel('在线视频预览');+ await expect(video).toBeVisible();+ await expect.poll(() => video.evaluate(element => (element as HTMLVideoElement).readyState)).toBeGreaterThanOrEqual(2);+ await video.evaluate(element => (element as HTMLVideoElement).play());+ await expect.poll(() => video.evaluate(element => (element as HTMLVideoElement).currentTime)).toBeGreaterThan(0.1);+ await video.evaluate(element => (element as HTMLVideoElement).pause());+ await expect(page.getByRole('button', { name: '下载并预览' })).toHaveCount(0);+ const saved = await runtime.api<{ job: CreatorJob }>('GET', `/creator/jobs/${job.id}`);+ expect(saved.job.stages).toHaveLength(0);+ expect(saved.job.artifacts).toHaveLength(0);+ await page.screenshot({ path: testInfo.outputPath('translation-online-preview.png'), fullPage: true });+});diff --git a/apps/web/public/platforms/pinterest.svg b/apps/web/public/platforms/pinterest.svgnew file mode 100644index 00000000..0efc8f98--- /dev/null+++ b/apps/web/public/platforms/pinterest.svg@@ -0,0 +1,5 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">+ <!-- Pinterest mark from Simple Icons: https://simpleicons.org/?q=pinterest -->+ <circle cx="12" cy="12" r="12" fill="#fff"/>+ <path fill="#e60023" d="M12.017 0C5.396 0 .029 5.367.029 11.987c0 5.079 3.158 9.417 7.618 11.162-.105-.949-.199-2.403.041-3.439.219-.937 1.406-5.957 1.406-5.957s-.359-.72-.359-1.781c0-1.663.967-2.911 2.168-2.911 1.024 0 1.518.769 1.518 1.688 0 1.029-.653 2.567-.992 3.992-.285 1.193.6 2.165 1.775 2.165 2.128 0 3.768-2.245 3.768-5.487 0-2.861-2.063-4.869-5.008-4.869-3.41 0-5.409 2.562-5.409 5.199 0 1.033.394 2.143.889 2.741.099.12.112.225.085.345-.09.375-.293 1.199-.334 1.363-.053.225-.172.271-.401.165-1.495-.69-2.433-2.878-2.433-4.646 0-3.776 2.748-7.252 7.92-7.252 4.158 0 7.392 2.967 7.392 6.923 0 4.135-2.607 7.462-6.233 7.462-1.214 0-2.354-.629-2.758-1.379l-.749 2.848c-.269 1.045-1.004 2.352-1.498 3.146 1.123.345 2.306.535 3.55.535 6.607 0 11.985-5.365 11.985-11.987C23.97 5.39 18.592.026 11.985.026L12.017 0z"/>+</svg>diff --git a/apps/web/src/features/dashboard/DashboardPage.test.tsx b/apps/web/src/features/dashboard/DashboardPage.test.tsxindex dc2d5a84..b24f1006 100644--- a/apps/web/src/features/dashboard/DashboardPage.test.tsx+++ b/apps/web/src/features/dashboard/DashboardPage.test.tsx@@ -813,7 +813,7 @@ describe('DashboardPage', () => {expect(screen.getByRole('heading', { name: 'Drop a video here' })).toBeInTheDocument();expect(screen.getByRole('textbox', { name: 'Video link' })).toHaveAttribute('placeholder',- 'Paste a YouTube URL, youtu.be share link, or Bilibili URL'+ 'Paste a video URL');expect(screen.getByText('No collaboration activity yet')).toBeInTheDocument();expect(screen.getByRole('button', { name: 'Ask Agent to review settings' })).toBeInTheDocument();@@ -969,6 +969,7 @@ describe('DashboardPage', () => {expect(screen.getByRole('heading', { name: '视频翻译配音' })).toBeInTheDocument();expect(screen.getByRole('complementary', { name: 'OpenCreator' })).toBeInTheDocument();expect(screen.getByRole('heading', { name: '拖放视频到这里' })).toBeInTheDocument();+ expect(screen.getByRole('list', { name: '支持的平台' }).querySelectorAll('li')).toHaveLength(9);fireEvent.change(screen.getByRole('textbox', { name: '视频链接' }), {target: { value: 'https://www.youtube.com/watch?v=test' }});diff --git a/apps/web/src/features/dashboard/SupportedVideoSources.tsx b/apps/web/src/features/dashboard/SupportedVideoSources.tsxnew file mode 100644index 00000000..27e3e171--- /dev/null+++ b/apps/web/src/features/dashboard/SupportedVideoSources.tsx@@ -0,0 +1,57 @@+import { useId, useState } from 'react';+import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';++export default function SupportedVideoSources(props: { compact?: boolean }) {+ const l = useLocalizedCopy();+ const tooltipId = useId();+ const [activePlatform, setActivePlatform] = useState<string>();+ return (+ <div className={`video-download-platform-section${props.compact ? ' video-source-platforms-compact' : ''}`}>+ <span>{props.compact ? l('支持平台', 'Supported platforms')+ : l('支持的视频来源(支持单个公开视频链接)', 'Supported video sources (one public video link)')}</span>+ <ul className="video-download-platforms" aria-label={l('支持的平台', 'Supported platforms')}>+ {([+ ['youtube', 'YouTube'], ['bilibili', 'Bilibili'], ['x', 'X'],+ ['tiktok', 'TikTok'], ['instagram', 'Instagram'], ['douyin', l('抖音', 'Douyin')],+ ['facebook', 'Facebook'], ['xiaohongshu', l('小红书', 'Xiaohongshu')], ['pinterest', 'Pinterest']+ ] as const).map(([platform, name]) => (+ <li+ key={platform}+ onMouseEnter={props.compact ? () => setActivePlatform(platform) : undefined}+ onMouseLeave={props.compact ? event => {+ if (!event.currentTarget.contains(document.activeElement)) setActivePlatform(undefined);+ } : undefined}+ >+ {props.compact ? (+ <>+ <span+ className="video-source-platform-mark"+ role="img"+ aria-label={name}+ aria-describedby={`${tooltipId}-${platform}`}+ tabIndex={0}+ onFocus={() => setActivePlatform(platform)}+ onBlur={() => setActivePlatform(undefined)}+ onPointerDown={event => event.currentTarget.focus()}+ onKeyDown={event => {+ if (event.key === 'Escape') setActivePlatform(undefined);+ }}+ >+ <img src={`/platforms/${platform}.${platform === 'pinterest' ? 'svg' : 'png'}`} alt="" width="20" height="20" />+ </span>+ <span id={`${tooltipId}-${platform}`} className="video-source-platform-tooltip" role="tooltip" hidden={activePlatform !== platform}>+ {name}+ </span>+ </>+ ) : (+ <>+ <img src={`/platforms/${platform}.${platform === 'pinterest' ? 'svg' : 'png'}`} alt="" width="32" height="32" />+ <span>{name}</span>+ </>+ )}+ </li>+ ))}+ </ul>+ </div>+ );+}diff --git a/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx b/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsxindex c39e6183..1e25d772 100644--- a/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx+++ b/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx@@ -6,7 +6,7 @@ import type {DownloadOption,DownloadProbe} from '@opencreator/protocol';-import { extractDouyinShareUrl } from '@opencreator/protocol';+import { extractDouyinShareUrl, supportedVideoSourcePlatform } from '@opencreator/protocol';import {AlertCircle,Check,@@ -30,6 +30,7 @@ import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';import NativeSelect from '../../components/forms/NativeSelect.js';import CreatorTaskSummary from './CreatorTaskSummary.js';import CreatorToolShell from './CreatorToolShell.js';+import SupportedVideoSources from './SupportedVideoSources.js';import {createCreatorArtifactObjectUrl,useOptionalCreatorSession@@ -680,21 +681,7 @@ export default function VideoDownloadWorkspace(props: {</h2></div></div>- <div className="video-download-platform-section">- <span>{l('支持的视频来源(支持单个公开视频链接)', 'Supported video sources (one public video link)')}</span>- <ul className="video-download-platforms" aria-label={l('支持的平台', 'Supported platforms')}>- {([- ['youtube', 'YouTube'], ['bilibili', 'Bilibili'], ['x', 'X'],- ['tiktok', 'TikTok'], ['instagram', 'Instagram'], ['douyin', l('抖音', 'Douyin')],- ['facebook', 'Facebook'], ['xiaohongshu', l('小红书', 'Xiaohongshu')], ['pinterest', 'Pinterest']- ] as const).map(([platformName, name]) => (- <li key={platformName}>- <img src={`/platforms/${platformName}.png`} alt="" width="32" height="32" />- <span>{name}</span>- </li>- ))}- </ul>- </div>+ <SupportedVideoSources /><label className="creator-tool-url-input"><Link2 size={17} strokeWidth={1.8} aria-hidden="true" /><input@@ -1574,84 +1561,7 @@ function formatBytes(bytes: number): string {}function isSupportedUrl(value: string): boolean {- try {- const parsed = new URL(value.trim());- const host = parsed.hostname.toLowerCase();- return parsed.protocol === 'https:'- && (- host === 'youtu.be'- || host === 'youtube.com'- || host.endsWith('.youtube.com')- || host === 'b23.tv'- || host === 'bilibili.com'- || host.endsWith('.bilibili.com')- || host === 'x.com'- || host.endsWith('.x.com')- || host === 'twitter.com'- || host.endsWith('.twitter.com')- || isTikTokVideoUrl(parsed)- || isInstagramVideoUrl(parsed)- || isDouyinVideoUrl(parsed)- || isFacebookVideoUrl(parsed)- || isXiaohongshuVideoUrl(parsed)- || isPinterestVideoUrl(parsed)- );- } catch {- return false;- }-}--function isTikTokVideoUrl(url: URL): boolean {- const host = url.hostname.toLowerCase();- if (host === 'vm.tiktok.com' || host === 'vt.tiktok.com') {- return /^\/[\w-]+\/?$/.test(url.pathname);- }- return (host === 'tiktok.com' || host.endsWith('.tiktok.com'))- && /^\/@[^/]+\/video\/\d+\/?$/.test(url.pathname);-}--function isInstagramVideoUrl(url: URL): boolean {- const host = url.hostname.toLowerCase();- return (host === 'instagram.com' || host === 'www.instagram.com')- && /^\/(?:reel|p|tv)\/[\w-]+\/?$/.test(url.pathname);-}--function isDouyinVideoUrl(url: URL): boolean {- const host = url.hostname.toLowerCase();- if (host === 'v.douyin.com') {- return /^\/[\w-]+\/?$/.test(url.pathname);- }- return (host === 'douyin.com' || host === 'www.douyin.com')- && (- /^\/video\/\d+\/?$/.test(url.pathname)- || (url.pathname === '/jingxuan'- && /^\d+$/.test(url.searchParams.get('modal_id') ?? ''))- );-}--function isFacebookVideoUrl(url: URL): boolean {- const host = url.hostname.toLowerCase();- if (host === 'fb.watch') {- return /^\/[\w-]+\/?$/.test(url.pathname);- }- if (!['facebook.com', 'www.facebook.com', 'm.facebook.com'].includes(host)) {- return false;- }- return /^\/watch\/?$/.test(url.pathname)- ? /^\d+$/.test(url.searchParams.get('v') ?? '')- : /^\/(?:reel\/\d+|videos\/\d+|[^/]+\/videos\/\d+)\/?$/.test(url.pathname);-}--function isXiaohongshuVideoUrl(url: URL): boolean {- const host = url.hostname.toLowerCase();- return (host === 'xiaohongshu.com' || host === 'www.xiaohongshu.com')- && /^\/explore\/[0-9a-f]{24}\/?$/i.test(url.pathname);-}--function isPinterestVideoUrl(url: URL): boolean {- const host = url.hostname.toLowerCase();- return (host === 'pinterest.com' || host === 'www.pinterest.com')- && /^\/pin\/\d+\/?$/.test(url.pathname);+ return supportedVideoSourcePlatform(value) !== null;}function platformFor(diff --git a/apps/web/src/features/dashboard/VideoSourceInput.tsx b/apps/web/src/features/dashboard/VideoSourceInput.tsxindex aa1614a3..83443fa6 100644--- a/apps/web/src/features/dashboard/VideoSourceInput.tsx+++ b/apps/web/src/features/dashboard/VideoSourceInput.tsx@@ -3,7 +3,8 @@ import { Link2, UploadCloud } from 'lucide-react';import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';import type { VideoMetadataResponse } from '@opencreator/protocol';import type { VideoMetadataService } from '../../services/video-metadata-service.js';-import VideoSourcePreview from './VideoSourcePreview.js';+import VideoSourcePreview, { type SourcePlaybackPreview } from './VideoSourcePreview.js';+import SupportedVideoSources from './SupportedVideoSources.js';export default function VideoSourceInput(props: {file: File | null;@@ -12,9 +13,11 @@ export default function VideoSourceInput(props: {url: string;hasSource: boolean;invalid?: boolean;+ showSupportedPlatforms?: boolean;metadataService?: VideoMetadataService;metadata?: VideoMetadataResponse;previewEnabled?: boolean;+ playbackPreview?: SourcePlaybackPreview;onFileChange(file: File | null): void;onUrlChange(url: string): void;onClear(): void;@@ -69,6 +72,7 @@ export default function VideoSourceInput(props: {metadataService={props.metadataService}metadata={props.metadata}previewEnabled={props.previewEnabled}+ playbackPreview={props.playbackPreview}onChooseFile={openFilePicker}onClear={props.onClear}onDimensions={props.onDimensions}@@ -100,7 +104,7 @@ export default function VideoSourceInput(props: {type="url"value={props.url}onChange={event => props.onUrlChange(event.target.value)}- placeholder={l(+ placeholder={props.showSupportedPlatforms ? l('粘贴视频链接', 'Paste a video URL') : l('粘贴 YouTube 标准链接、youtu.be 分享链接或 Bilibili 链接','Paste a YouTube URL, youtu.be share link, or Bilibili URL')}@@ -108,6 +112,7 @@ export default function VideoSourceInput(props: {/></div></label>+ {props.showSupportedPlatforms ? <SupportedVideoSources compact /> : null}</>) : null}</section>diff --git a/apps/web/src/features/dashboard/VideoSourcePreview.test.tsx b/apps/web/src/features/dashboard/VideoSourcePreview.test.tsxindex 9ff96e0c..a162418e 100644--- a/apps/web/src/features/dashboard/VideoSourcePreview.test.tsx+++ b/apps/web/src/features/dashboard/VideoSourcePreview.test.tsx@@ -1,4 +1,4 @@-import { fireEvent, render, screen } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { LanguageProvider } from '../../i18n/LanguageProvider.js';import VideoSourcePreview from './VideoSourcePreview.js';@@ -24,6 +24,87 @@ afterEach(() => {});describe('VideoSourcePreview', () => {+ it('offers download when an online video never loads and clears the timeout after playback is ready', async () => {+ vi.useFakeTimers();+ const onPrepare = vi.fn();+ const getVideoMetadata = vi.fn(async () => ({ platform: 'douyin' as const, title: 'Slow source', previewUrl: 'https://media.example.com/slow.mp4' }));+ const view = render(<VideoSourcePreview file={null} sourceType="url" url="https://v.douyin.com/example/" onChooseFile={vi.fn()} onClear={vi.fn()}+ metadataService={{ getVideoMetadata }} playbackPreview={{ pending: false, onPrepare }} />);+ try {+ await act(async () => { await vi.advanceTimersByTimeAsync(250); });+ expect(screen.getByLabelText('在线视频预览')).toBeVisible();+ await act(async () => { await vi.advanceTimersByTimeAsync(15_000); });+ expect(screen.getByRole('button', { name: '下载并预览' })).toBeEnabled();+ expect(onPrepare).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: '重试在线播放' }));+ await act(async () => { await vi.advanceTimersByTimeAsync(250); });+ fireEvent.loadedData(screen.getByLabelText('在线视频预览'));+ await act(async () => { await vi.advanceTimersByTimeAsync(15_000); });+ expect(screen.getByLabelText('在线视频预览')).toBeVisible();+ expect(screen.queryByRole('button', { name: '下载并预览' })).not.toBeInTheDocument();+ } finally { view.unmount(); vi.useRealTimers(); }+ });+ it('previews a Douyin URL online first and exposes download only after playback fails', async () => {+ const onPrepare = vi.fn();+ const getVideoMetadata = vi.fn(async () => ({ platform: 'douyin' as const, title: 'Douyin video', previewUrl: 'https://media.example.com/online.mp4', thumbnailUrl: 'https://media.example.com/cover.jpg' }));+ render(<VideoSourcePreview file={null} sourceType="url" url="https://v.douyin.com/example/" onChooseFile={vi.fn()} onClear={vi.fn()}+ metadataService={{ getVideoMetadata }} playbackPreview={{ pending: false, onPrepare }} />);+ expect(screen.getByRole('status')).toHaveTextContent('正在获取视频预览');+ expect(screen.queryByRole('button', { name: '下载并预览' })).not.toBeInTheDocument();+ const video = await screen.findByLabelText('在线视频预览');+ expect(video).toHaveAttribute('src', 'https://media.example.com/online.mp4');+ expect(video).toHaveAttribute('preload', 'metadata');+ expect(onPrepare).not.toHaveBeenCalled();+ fireEvent.error(video);+ expect(screen.getByText('在线播放暂不可用')).toBeVisible();+ expect(screen.getByRole('button', { name: '下载并预览' })).toBeEnabled();+ fireEvent.click(screen.getByRole('button', { name: '重试在线播放' }));+ expect(screen.queryByRole('button', { name: '下载并预览' })).not.toBeInTheDocument();+ expect(await screen.findByLabelText('在线视频预览')).toBeVisible();+ expect(getVideoMetadata).toHaveBeenCalledTimes(2);+ expect(onPrepare).not.toHaveBeenCalled();+ });++ it('falls back to an explicit download action when online resolution fails', async () => {+ const onPrepare = vi.fn();+ render(<VideoSourcePreview file={null} sourceType="url" url="https://v.douyin.com/example/" onChooseFile={vi.fn()} onClear={vi.fn()}+ metadataService={{ getVideoMetadata: vi.fn(async () => { throw new Error('Login required'); }) }} playbackPreview={{ pending: false, onPrepare }} />);+ expect(await screen.findByRole('button', { name: '下载并预览' })).toBeEnabled();+ expect(onPrepare).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: '下载并预览' }));+ expect(onPrepare).toHaveBeenCalledOnce();+ });++ it('ignores an old online response after switching the source URL', async () => {+ let resolveOld!: (value: { platform: 'douyin'; title: string; previewUrl: string }) => void;+ const getVideoMetadata = vi.fn((url: string) => url.includes('first')+ ? new Promise<{ platform: 'douyin'; title: string; previewUrl: string }>(resolve => { resolveOld = resolve; })+ : Promise.resolve({ platform: 'douyin' as const, title: 'Second video', previewUrl: 'https://media.example.com/second.mp4' }));+ const base = { file: null, sourceType: 'url' as const, onChooseFile: vi.fn(), onClear: vi.fn(), metadataService: { getVideoMetadata } };+ const view = render(<VideoSourcePreview {...base} url="https://v.douyin.com/first/" />);+ await waitFor(() => expect(getVideoMetadata).toHaveBeenCalledOnce());+ view.rerender(<VideoSourcePreview {...base} url="https://v.douyin.com/second/" />);+ expect(await screen.findByLabelText('在线视频预览')).toHaveAttribute('src', 'https://media.example.com/second.mp4');+ resolveOld({ platform: 'douyin', title: 'First video', previewUrl: 'https://media.example.com/first.mp4' });+ await waitFor(() => expect(screen.getByLabelText('在线视频预览')).toHaveAttribute('src', 'https://media.example.com/second.mp4'));+ });+ it('offers downloading for an external source, prevents duplicate requests, and plays the prepared file', () => {+ const onPrepare = vi.fn();+ const base = { file: null, sourceType: 'url' as const, url: 'https://v.douyin.com/example/', onChooseFile: vi.fn(), onClear: vi.fn() };+ const view = render(<VideoSourcePreview {...base} playbackPreview={{ pending: false, onPrepare }} />);+ fireEvent.click(screen.getByRole('button', { name: '下载并预览' }));+ expect(onPrepare).toHaveBeenCalledOnce();+ view.rerender(<VideoSourcePreview {...base} playbackPreview={{ pending: true, onPrepare }} />);+ expect(screen.getByRole('status')).toHaveTextContent('正在准备视频预览');+ expect(screen.getByRole('button', { name: '正在准备…' })).toBeDisabled();+ view.rerender(<VideoSourcePreview {...base} playbackPreview={{ pending: false, error: '此视频需要登录', onPrepare }} />);+ expect(screen.getByRole('alert')).toHaveTextContent('此视频需要登录');+ expect(screen.getByRole('button', { name: '重试视频预览' })).toBeEnabled();+ view.rerender(<VideoSourcePreview {...base} playbackPreview={{ pending: false, src: 'blob:downloaded' }} />);+ expect(screen.getByLabelText('原视频预览')).toHaveAttribute('src', 'blob:downloaded');+ expect(screen.queryByRole('button', { name: '下载并预览' })).not.toBeInTheDocument();+ expect(screen.getByRole('link', { name: '在浏览器中打开原视频' })).toHaveAttribute('href', base.url);+ });it('previews a local file and releases its object URL', () => {const file = new File(['video'], 'local.mp4', { type: 'video/mp4' });const { unmount } = render(diff --git a/apps/web/src/features/dashboard/VideoSourcePreview.tsx b/apps/web/src/features/dashboard/VideoSourcePreview.tsxindex 597ddbbc..60a4e388 100644--- a/apps/web/src/features/dashboard/VideoSourcePreview.tsx+++ b/apps/web/src/features/dashboard/VideoSourcePreview.tsx@@ -1,7 +1,7 @@import { useEffect, useMemo, useState } from 'react';-import { ExternalLink, FileVideo, Link2, Play, RotateCcw, Trash2 } from 'lucide-react';+import { Download, ExternalLink, FileVideo, Link2, LoaderCircle, Play, RotateCcw, Trash2 } from 'lucide-react';import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';-import { parseBilibiliVideoSource, type VideoMetadataResponse } from '@opencreator/protocol';+import { supportedVideoSourcePlatform, parseBilibiliVideoSource, type VideoMetadataResponse } from '@opencreator/protocol';import type { VideoMetadataService } from '../../services/video-metadata-service.js';type VideoSource =@@ -11,6 +11,14 @@ type VideoSource =| { kind: 'link'; url: string; hostname: string; label: string }| { kind: 'invalid'; label: string };+export type SourcePlaybackPreview = {+ src?: string;+ pending: boolean;+ blocked?: boolean;+ error?: string;+ onPrepare?(): void;+};+export function parseVideoSource(value: string): VideoSource {const trimmed = value.trim();@@ -94,13 +102,18 @@ function LocalVideoPreview(props: { file: File; onDimensions?(width: number, hei);}-function PreviewVideo(props: { src: string; label: string; onDimensions?(width: number, height: number): void }) {+function PreviewVideo(props: { src: string; label: string; poster?: string; onReady?(): void; onError?(): void; onDimensions?(width: number, height: number): void }) {const [aspectRatio, setAspectRatio] = useState<string>();return (<videocontrols+ playsInline+ preload="metadata"src={props.src}+ poster={props.poster}+ onError={props.onError}+ onLoadedData={props.onReady}aria-label={props.label}style={aspectRatio ? { aspectRatio } : undefined}onLoadedMetadata={event => {@@ -127,6 +140,7 @@ export default function VideoSourcePreview(props: {metadataService?: VideoMetadataService;metadata?: VideoMetadataResponse;previewEnabled?: boolean;+ playbackPreview?: SourcePlaybackPreview;onDimensions?(width: number, height: number): void;onMetadata?(url: string, metadata: VideoMetadataResponse): void;}) {@@ -135,10 +149,20 @@ export default function VideoSourcePreview(props: {const [fetchedMetadata, setFetchedMetadata] = useState<{ url: string; value: VideoMetadataResponse }>();const metadata = props.metadata ?? (fetchedMetadata?.url === props.url ? fetchedMetadata.value : undefined);const [mediaDimensions, setMediaDimensions] = useState<{ width: number; height: number }>();+ const [onlinePreviewState, setOnlinePreviewState] = useState<{ url: string; pending: boolean }>();+ const [onlinePreviewReload, setOnlinePreviewReload] = useState(0);+ const [failedPlayback, setFailedPlayback] = useState<{ url: string; src: string }>();+ const [readyPlayback, setReadyPlayback] = useState<{ url: string; src: string }>();const source = useMemo(() => parseVideoSource(props.url), [props.url]);const localFile = props.sourceType === 'file' ? props.file : null;const registeredFile = props.sourceType === 'file' ? props.registeredFile : undefined;const isLocal = localFile !== null || registeredFile !== undefined;+ const canResolveOnline = !isLocal && source.kind === 'link'+ && !props.playbackPreview?.src && supportedVideoSourcePlatform(props.url) !== null && props.metadataService !== undefined;+ const onlinePreviewPending = canResolveOnline && !props.playbackPreview?.src && !props.playbackPreview?.pending+ && (onlinePreviewState?.url !== props.url || onlinePreviewState.pending);+ const linkPlaybackSrc = props.playbackPreview?.src ?? metadata?.previewUrl;+ const playbackFailed = failedPlayback?.url === props.url && failedPlayback.src === linkPlaybackSrc;const localizedLabel = source.kind === 'youtube'? l('YouTube 视频', 'YouTube video'): source.kind === 'bilibili'@@ -168,12 +192,41 @@ export default function VideoSourcePreview(props: {useEffect(() => {setShowYouTubePlayer(false);setMediaDimensions(undefined);+ setFailedPlayback(undefined);+ setReadyPlayback(undefined);+ setOnlinePreviewReload(0);}, [props.sourceType, props.url]);useEffect(() => {setMediaDimensions(undefined);}, [localFile]);+ useEffect(() => {+ if (source.kind !== 'link' || !linkPlaybackSrc || props.playbackPreview?.src || playbackFailed+ || readyPlayback?.url === props.url && readyPlayback.src === linkPlaybackSrc) return;+ const timeout = setTimeout(() => setFailedPlayback({ url: props.url, src: linkPlaybackSrc }), 15_000);+ return () => clearTimeout(timeout);+ }, [source.kind, props.url, linkPlaybackSrc, props.playbackPreview?.src, playbackFailed, readyPlayback]);++ useEffect(() => {+ if (!canResolveOnline || props.playbackPreview?.src || props.playbackPreview?.pending) return;+ let active = true;+ setOnlinePreviewState({ url: props.url, pending: true });+ const timeout = setTimeout(() => {+ void props.metadataService!.getVideoMetadata(props.url).then(result => {+ if (!active) return;+ setFailedPlayback(undefined);+ setFetchedMetadata({ url: props.url, value: result });+ props.onMetadata?.(props.url, result);+ setOnlinePreviewState({ url: props.url, pending: false });+ if (result.width !== undefined && result.height !== undefined) updateMediaDimensions(result.width, result.height);+ }).catch(() => {+ if (active) setOnlinePreviewState({ url: props.url, pending: false });+ });+ }, 250);+ return () => { active = false; clearTimeout(timeout); };+ }, [canResolveOnline, props.metadataService, props.url, props.playbackPreview?.src, props.playbackPreview?.pending, onlinePreviewReload]);+function updateMediaDimensions(width: number, height: number) {setMediaDimensions({ width, height });props.onDimensions?.(width, height);@@ -253,11 +306,49 @@ export default function VideoSourcePreview(props: {{!isLocal && source.kind === 'direct' ? (<PreviewVideo key={source.url} src={source.url} label={l('视频链接预览', 'Video link preview')} onDimensions={updateMediaDimensions} />) : null}- {!isLocal && (source.kind === 'link' || source.kind === 'invalid') ? (+ {!isLocal && source.kind === 'link' && linkPlaybackSrc && !playbackFailed ? (+ <PreviewVideo key={linkPlaybackSrc} src={linkPlaybackSrc} poster={metadata?.thumbnailUrl}+ label={props.playbackPreview?.src ? l('原视频预览', 'Source video preview') : l('在线视频预览', 'Online video preview')}+ onReady={() => setReadyPlayback({ url: props.url, src: linkPlaybackSrc })}+ onError={() => setFailedPlayback({ url: props.url, src: linkPlaybackSrc })} onDimensions={updateMediaDimensions} />+ ) : null}+ {!isLocal && ((source.kind === 'link' && (!linkPlaybackSrc || playbackFailed)) || source.kind === 'invalid') ? (<div className="video-source-link-preview">- <span><Link2 size={26} strokeWidth={1.6} aria-hidden="true" /></span>- <strong>{source.kind === 'invalid' ? l('暂时无法预览此链接', 'This link cannot be previewed') : l('此平台暂不支持内嵌预览', 'Embedded preview is not supported for this platform')}</strong>+ {!props.playbackPreview?.pending && !onlinePreviewPending && metadata?.thumbnailUrl ? (+ <img className="video-source-preview-thumbnail" src={metadata.thumbnailUrl} alt={l('视频封面', 'Video poster')} />+ ) : <span>{props.playbackPreview?.pending || onlinePreviewPending ? <LoaderCircle className="video-source-preview-spinner" size={26} aria-hidden="true" /> : <Link2 size={26} strokeWidth={1.6} aria-hidden="true" />}</span>}+ <strong role={props.playbackPreview?.pending || onlinePreviewPending ? 'status' : undefined}>{source.kind === 'invalid'+ ? l('暂时无法预览此链接', 'This link cannot be previewed')+ : onlinePreviewPending+ ? l('正在获取视频预览', 'Loading online video preview')+ : props.playbackPreview?.pending+ ? l('正在准备视频预览', 'Preparing video preview')+ : props.playbackPreview?.error+ ? l('视频预览准备失败', 'Video preview preparation failed')+ : canResolveOnline || playbackFailed+ ? l('在线播放暂不可用', 'Online playback is unavailable')+ : props.playbackPreview?.onPrepare+ ? l('原视频预览', 'Source video preview')+ : l('此平台暂不支持内嵌预览', 'Embedded preview is not supported for this platform')}</strong><p>{sourceDetail}</p>+ {source.kind === 'link' && props.playbackPreview?.error ? <p className="video-source-preview-error" role="alert">{props.playbackPreview.error}</p> : null}+ {source.kind === 'link' && props.playbackPreview?.onPrepare && !onlinePreviewPending ? (+ <button type="button" className="video-source-prepare-preview" disabled={props.playbackPreview.pending || props.playbackPreview.blocked} onClick={props.playbackPreview.onPrepare}>+ <Download size={14} aria-hidden="true" />+ {props.playbackPreview.pending ? l('正在准备…', 'Preparing…') : props.playbackPreview.error ? l('重试视频预览', 'Retry video preview') : l('下载并预览', 'Download and preview')}+ </button>+ ) : null}+ {source.kind === 'link' && canResolveOnline && !onlinePreviewPending && !props.playbackPreview?.pending ? (+ <button type="button" className="video-source-retry-online" title={l('重试在线播放', 'Retry online playback')} aria-label={l('重试在线播放', 'Retry online playback')}+ onClick={() => {+ setFetchedMetadata(undefined);+ setReadyPlayback(undefined);+ setOnlinePreviewState({ url: props.url, pending: true });+ setOnlinePreviewReload(value => value + 1);+ }}>+ <RotateCcw size={15} aria-hidden="true" />+ </button>+ ) : null}{source.kind === 'link' ? (<a href={source.url} target="_blank" rel="noreferrer">{l('打开原始链接', 'Open original link')}@@ -278,7 +369,7 @@ export default function VideoSourcePreview(props: {</span>{!props.readOnly ? (<div className="video-source-preview-actions">- {!isLocal && (source.kind === 'youtube' || source.kind === 'bilibili') ? (+ {!isLocal && (source.kind === 'youtube' || source.kind === 'bilibili' || (source.kind === 'link' && linkPlaybackSrc && !playbackFailed)) ? (<ahref={source.url}target="_blank"diff --git a/apps/web/src/features/dashboard/VideoTranslationWorkspace.control.test.tsx b/apps/web/src/features/dashboard/VideoTranslationWorkspace.control.test.tsxindex 63e03a72..7c327fb7 100644--- a/apps/web/src/features/dashboard/VideoTranslationWorkspace.control.test.tsx+++ b/apps/web/src/features/dashboard/VideoTranslationWorkspace.control.test.tsx@@ -13,6 +13,49 @@ import VideoTranslationWorkspace from './VideoTranslationWorkspace.js';import { LanguageSwitchControls } from '../../test/LanguageSwitchControls.js';describe('VideoTranslationWorkspace task controls', () => {+ it('downloads and previews a draft Douyin source without entering results and clears playback when the source changes', async () => {+ const objectUrlDescriptor = Object.getOwnPropertyDescriptor(URL, 'createObjectURL');+ const revokeDescriptor = Object.getOwnPropertyDescriptor(URL, 'revokeObjectURL');+ const revoke = vi.fn();+ Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: vi.fn(() => 'blob:draft-douyin') });+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: revoke });+ const url = 'https://v.douyin.com/example/';+ let current = job({ status: 'draft', revision: 1, stages: [], state: { sourceUrl: url, currentStep: 0, furthestStep: 0 } });+ const openArtifact = vi.fn(async () => new Response(new Blob(['video'], { type: 'video/mp4' })));+ const applyAction = vi.fn(async (_id: string, request: { action: string; input: Record<string, CreatorJson> }) => {+ if (request.action === 'run-stage') {+ const source = { ...sourceVideoArtifact(1), metadata: { sourceUrl: url, settingsSnapshot: { sourceType: 'url', sourceUrl: url }, previewOnly: true } };+ current = { ...current, revision: current.revision + 1, artifacts: [source] };+ } else {+ current = { ...current, revision: current.revision + 1, state: { ...current.state, ...request.input.patch as object } };+ }+ return { job: current };+ });+ let session: ReturnType<typeof useCreatorSession>;+ function Capture() { session = useCreatorSession(); return null; }+ const view = render(<LanguageProvider initialPreference="zh-CN"><CreatorSessionProvider initialJob={current}+ service={{ applyAction, openArtifact, runAgentTurn: vi.fn(), preflight: vi.fn(async () => ({ canStart: true, ready: [], blocked: [], warning: [] })) } as never}>+ <Capture /><VideoTranslationWorkspace onBack={vi.fn()} /></CreatorSessionProvider></LanguageProvider>);+ try {+ fireEvent.click(screen.getByRole('button', { name: '下载并预览' }));+ expect(await screen.findByLabelText('原视频预览')).toHaveAttribute('src', 'blob:draft-douyin');+ expect(screen.getByRole('region', { name: '视频预览' })).toBeVisible();+ expect(screen.queryByRole('tab', { name: '字幕' })).not.toBeInTheDocument();+ expect(applyAction.mock.calls.filter(([, request]) => request.action === 'run-stage')).toEqual([+ ['job_control', expect.objectContaining({ action: 'run-stage', input: { stageId: 'preview-source-video' } })]+ ]);+ const secondUrl = 'https://v.douyin.com/second/';+ act(() => session!.applyRemoteSnapshot({ ...current, revision: current.revision + 1, state: { ...current.state, sourceUrl: secondUrl } }));+ await waitFor(() => expect(screen.queryByLabelText('原视频预览')).not.toBeInTheDocument());+ expect(screen.getByRole('button', { name: '下载并预览' })).toBeEnabled();+ expect(revoke).toHaveBeenCalledWith('blob:draft-douyin');+ expect(openArtifact).toHaveBeenCalledOnce();+ } finally {+ view.unmount();+ restoreUrlMethod('createObjectURL', objectUrlDescriptor);+ restoreUrlMethod('revokeObjectURL', revokeDescriptor);+ }+ });it('keeps the same playable video and URL across snapshots, diagnostic callback changes, and language switches', async () => {const objectUrlDescriptor = Object.getOwnPropertyDescriptor(URL, 'createObjectURL');const revokeDescriptor = Object.getOwnPropertyDescriptor(URL, 'revokeObjectURL');diff --git a/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx b/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsxindex becdaf7a..064cb3db 100644--- a/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx+++ b/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx@@ -50,6 +50,7 @@ import {import {readCreatorResultSnapshots,parseBilibiliVideoSource,+ normalizeVideoSourceUrl,videoSourceIdentity,type CreatorArtifact,type CreatorJson,@@ -757,6 +758,7 @@ function legacyResultVersionsFromArtifacts(for (const artifact of artifacts) {if (artifact.status !== 'completed'+ || artifact.metadata.previewOnly === true|| (artifact.kind !== 'target_subtitle' && !isVideoArtifactKind(artifact.kind))) continue;const version = artifactResultVersion(artifact);@@ -1897,6 +1899,54 @@ export default function VideoTranslationWorkspace(props: {}, [cancelDialogOpen]);const jobArtifacts = creatorSession?.job.artifacts ?? [];+ const currentSourceIdentity = sourceType === 'url' ? videoSourceIdentity(videoUrl) : null;+ const currentSourcePreviewArtifact = currentSourceIdentity === null ? undefined : [...jobArtifacts].reverse().find(artifact => {+ if (artifact.kind !== 'source_video' || artifact.status !== 'completed') return false;+ const settings = artifact.metadata.settingsSnapshot;+ const url = settings !== null && typeof settings === 'object' && !Array.isArray(settings)+ ? settings.sourceUrl : artifact.metadata.sourceUrl;+ return typeof url === 'string' && videoSourceIdentity(url) === currentSourceIdentity;+ });+ const [draftPreviewRequest, setDraftPreviewRequest] = useState<{ url: string; pending: boolean; error?: string }>();+ const [draftSourcePreview, setDraftSourcePreview] = useState<{ artifactId: string; src?: string; loading: boolean; error?: string }>();+ const [draftPreviewReload, setDraftPreviewReload] = useState(0);+ const currentSourcePreviewArtifactId = currentSourcePreviewArtifact?.id;+ useEffect(() => {+ const { session, localize } = mediaPreviewContextRef.current;+ if (workspacePhase !== 'configure' || currentSourcePreviewArtifactId === undefined || session === null || !canOpenMediaPreview) {+ setDraftSourcePreview(undefined);+ return;+ }+ let canceled = false;+ let objectUrl: string | undefined;+ setDraftSourcePreview({ artifactId: currentSourcePreviewArtifactId, loading: true });+ void createCreatorArtifactObjectUrl(session, currentSourcePreviewArtifactId,+ 'video-translation.load-source-preview', localize('原视频预览加载失败,请重试。', 'Source video preview failed to load. Try again.'))+ .then(src => {+ objectUrl = src;+ if (canceled) { URL.revokeObjectURL(src); return; }+ setDraftSourcePreview({ artifactId: currentSourcePreviewArtifactId, src, loading: false });+ }).catch(() => {+ if (!canceled) setDraftSourcePreview({ artifactId: currentSourcePreviewArtifactId, loading: false, error: 'load' });+ });+ return () => {+ canceled = true;+ if (objectUrl !== undefined) URL.revokeObjectURL(objectUrl);+ };+ }, [workspacePhase, currentSourcePreviewArtifactId, canOpenMediaPreview, mediaPreviewJobId, draftPreviewReload]);+ const currentDraftSourcePreview = draftSourcePreview?.artifactId === currentSourcePreviewArtifactId ? draftSourcePreview : undefined;+ const draftPreviewStage = [...(creatorSession?.job.stages ?? [])].reverse().find(stage =>+ stage.stageId === 'preview-source-video' && stage.progress.previewSourceUrl === videoUrl);+ const draftPreviewPending = (draftPreviewRequest?.url === videoUrl && draftPreviewRequest.pending)+ || draftPreviewStage?.status === 'queued' || draftPreviewStage?.status === 'running' || currentDraftSourcePreview?.loading === true;+ const draftPreviewError = draftPreviewRequest?.url === videoUrl && draftPreviewRequest.error+ ? draftPreviewRequest.error+ : currentDraftSourcePreview?.error+ ? l('原视频预览加载失败,请重试。', 'Source video preview failed to load. Try again.')+ : draftPreviewStage?.status === 'failed'+ ? draftPreviewStage.errorMessage ?? l('视频下载失败,请重试。', 'Video download failed. Try again.')+ : draftPreviewStage?.status === 'canceled' || draftPreviewStage?.status === 'interrupted'+ ? l('视频预览准备已停止,可以重试。', 'Video preview preparation stopped. You can retry.') : undefined;const registeredSourceArtifactId = creatorSession?.state.sourceArtifactId;const registeredSourceArtifact = (typeof registeredSourceArtifactId === 'string'@@ -1950,7 +2000,7 @@ export default function VideoTranslationWorkspace(props: {? localPreviewUrl?.file === videoFile ? localPreviewUrl.url : undefined: artifactPreviewUrl !== undefined && artifactPreviewUrl.artifactId === registeredSourceArtifact?.id? artifactPreviewUrl.url : undefined- : parsedVideoSource.kind === 'direct' ? parsedVideoSource.url : undefined;+ : parsedVideoSource.kind === 'direct' ? parsedVideoSource.url : currentDraftSourcePreview?.src;const previewPosterUrl = sourceType === 'url'? currentUrlMetadata?.thumbnailUrl?? (parsedVideoSource.kind === 'youtube' ? parsedVideoSource.thumbnailUrl : undefined)@@ -2781,6 +2831,23 @@ export default function VideoTranslationWorkspace(props: {}}+ async function prepareDraftSourcePreview() {+ if (creatorSession === null || currentSourceIdentity === null || activeStage !== undefined || draftPreviewPending) return;+ if (currentSourcePreviewArtifact !== undefined) {+ setDraftPreviewReload(value => value + 1);+ return;+ }+ const url = videoUrl;+ creatorSession.clearError();+ setDraftPreviewRequest({ url, pending: true });+ try {+ await creatorSession.applyAction({ action: 'run-stage', input: { stageId: 'preview-source-video' } });+ setDraftPreviewRequest({ url, pending: false });+ } catch (cause) {+ setDraftPreviewRequest({ url, pending: false, error: creatorErrorMessage(cause, l) });+ }+ }+async function cancelTask() {if (creatorSession === null || activeStage === undefined || taskControlPending !== undefined) return;setCancelDialogOpen(false);@@ -3098,6 +3165,7 @@ export default function VideoTranslationWorkspace(props: {{workspacePhase === 'configure' && currentStep === 0 ? (<><VideoSourceInput+ showSupportedPlatformsfile={videoFile}registeredFile={registeredSourceFile}sourceType={sourceType}@@ -3107,9 +3175,16 @@ export default function VideoTranslationWorkspace(props: {metadataService={parsedVideoSource.kind === 'bilibili' ? undefined : props.videoMetadataService}metadata={currentUrlMetadata}previewEnabled={sourceSelectionReady}+ playbackPreview={sourceType === 'url' && parsedVideoSource.kind === 'link' ? {+ src: currentDraftSourcePreview?.src,+ pending: Boolean(draftPreviewPending),+ blocked: activeStage !== undefined,+ error: draftPreviewError,+ onPrepare: creatorSession !== null && currentSourceIdentity !== null ? () => void prepareDraftSourcePreview() : undefined+ } : undefined}onFileChange={chooseVideo}onUrlChange={url => {- setVideoUrl(url);+ setVideoUrl(normalizeVideoSourceUrl(url));setSourceType('url');setVideoFile(null);setSourceDimensions(undefined);@@ -3740,7 +3815,7 @@ function creatorErrorMessage(cause: unknown, l: LocalizeCopy): string {return l('已开启配音,请先配置配音服务。', 'Dubbing is enabled. Configure a TTS service first.');}if (code === 'unsupported_source') {- return l('当前仅支持 YouTube、Bilibili 公共链接或已上传的本地视频。', 'Only public YouTube/Bilibili links or uploaded local videos are supported.');+ return l('请使用 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书、Pinterest 的单个公开视频链接或已上传的本地视频。', 'Use a single public video link from YouTube, Bilibili, X, TikTok, Instagram, Douyin, Facebook, Xiaohongshu, or Pinterest, or an uploaded local video.');}return l('启动翻译失败,请在 Agent 区域查看诊断后重试。', 'Failed to start translation. Review the diagnosis in the Agent panel and retry.');}diff --git a/apps/web/src/features/dashboard/creator-panel-adapters.test.ts b/apps/web/src/features/dashboard/creator-panel-adapters.test.tsindex a8d67efa..137f3c7b 100644--- a/apps/web/src/features/dashboard/creator-panel-adapters.test.ts+++ b/apps/web/src/features/dashboard/creator-panel-adapters.test.ts@@ -22,6 +22,17 @@ describe('shared native image progress', () => {});describe('video translation component progress', () => {+ it('labels draft preview activity and reports real progress without translation claims', () => {+ const running = { ...stage('draft-preview', '', 'running', null, 'preview-source-video'),+ progress: { phase: 'downloading', percent: 40, downloadedBytes: 4 * 1024 ** 2, totalBytes: 10 * 1024 ** 2 } };+ expect(videoTranslationPanelAdapter.stageLabel(running.stageId, zh)).toBe('原视频预览准备');+ expect(videoTranslationPanelAdapter.normalizeActivity(activity('run-stage', { stageId: running.stageId }), zh))+ .toEqual({ label: '开始下载原视频预览', fields: [] });+ expect(videoTranslationPanelAdapter.readStageProgress(running, en)).toMatchObject({ percent: 40, indeterminate: false, message: 'Downloading the source video: 4.0 MiB / 10.0 MiB' });+ expect(videoTranslationPanelAdapter.readStageProgress({ ...running, progress: { phase: 'normalizing_media', percent: 98 } }, zh)).toMatchObject({ percent: null, indeterminate: true });+ expect(videoTranslationPanelAdapter.failedProgressText?.(running, zh)).toContain('可重试');+ expect(videoTranslationPanelAdapter.succeededProgressText?.(running, zh)).toContain('已就绪');+ });it.each(['zh-CN', 'en-US', 'sv-SE'] as const)('localizes dependency and preview preparation with real progress in %s', language => {const localize = createLocalizedCopy(language);const raw = '后台原文:正在准备本地模型';diff --git a/apps/web/src/features/dashboard/creator-panel-adapters.ts b/apps/web/src/features/dashboard/creator-panel-adapters.tsindex e24881cb..c707547d 100644--- a/apps/web/src/features/dashboard/creator-panel-adapters.ts+++ b/apps/web/src/features/dashboard/creator-panel-adapters.ts@@ -73,12 +73,14 @@ const genericAdapter: CreatorPanelAdapter = {export const videoTranslationPanelAdapter: CreatorPanelAdapter = {id: 'video-translation',failedProgressText(stage, l) {+ if (stage.stageId === 'preview-source-video') return l('原视频预览准备失败,可重试', 'Source video preview preparation failed. You can retry.');if (stage.stageId === 'prepare-source-video') return l('原视频准备失败,已有字幕未受影响,可重试', 'Source video preparation failed; subtitles are preserved. You can retry.');return stage.errorCode === 'creator_dependency_prepare_failed'? l('本地转录组件准备失败,可前往组件页查看原因并重试', 'Local transcription preparation failed. View the component page and retry.'): null;},succeededProgressText(stage, localize) {+ if (stage.stageId === 'preview-source-video') return localize('原视频预览已就绪', 'Source video preview ready');return stage.stageId === 'prepare-source-video'? localize('原视频已就绪,已有字幕保持不变', 'Source video ready; existing subtitles are unchanged'): null;@@ -89,7 +91,7 @@ export const videoTranslationPanelAdapter: CreatorPanelAdapter = {),stageLabel(stageId, l) {if (stageId === 'subtitle') return l('字幕翻译', 'Subtitle translation');- if (stageId === 'prepare-source-video') return l('原视频预览准备', 'Source video preview preparation');+ if (stageId === 'prepare-source-video' || stageId === 'preview-source-video') return l('原视频预览准备', 'Source video preview preparation');if (stageId === 'tts') return l('配音生成', 'Dubbing');if (stageId === 'render-horizontal') return l('横屏成片', 'Landscape render');if (stageId === 'render-vertical') return l('竖屏成片', 'Portrait render');@@ -126,6 +128,7 @@ export const videoTranslationPanelAdapter: CreatorPanelAdapter = {normalizeActivity(activity, l) {if (activity.action === 'run-stage') {const stageId = readActivityStageId(activity);+ if (stageId === 'preview-source-video') return { label: l('开始下载原视频预览', 'Started downloading the source video preview'), fields: [] };if (stageId === 'prepare-source-video') return { label: l('开始准备原视频预览,保留已有字幕', 'Started preparing source video preview; existing subtitles are preserved'), fields: [] };return {label: stageId === null@@ -143,10 +146,17 @@ export const videoTranslationPanelAdapter: CreatorPanelAdapter = {},readStageProgress(stage, localize) {const standard = readStandardProgress(stage);- if (stage.stageId === 'prepare-source-video') {+ if (stage.stageId === 'prepare-source-video' || stage.stageId === 'preview-source-video') {const bytes = readFiniteNumber(stage.progress.downloadedBytes) ?? 0;const total = readFiniteNumber(stage.progress.totalBytes);const amount = `${(bytes / 1024 ** 2).toFixed(1)} MiB${total === null ? '' : ` / ${(total / 1024 ** 2).toFixed(1)} MiB`}`;+ if (stage.stageId === 'preview-source-video') return { ...standard,+ showMessage: true,+ percent: standard.phase === 'downloading' || standard.phase === 'completed' ? standard.percent : null,+ indeterminate: standard.phase !== 'completed' && (standard.phase !== 'downloading' || standard.percent === null),+ message: standard.phase === 'downloading'+ ? localize(`正在下载原视频:${amount}`, `Downloading the source video: ${amount}`)+ : localize('正在准备原视频预览', 'Preparing the source video preview') };return { ...standard,showMessage: true,percent: standard.phase === 'downloading' || standard.phase === 'completed' ? standard.percent : null,diff --git a/apps/web/src/features/dashboard/dashboard.css b/apps/web/src/features/dashboard/dashboard.cssindex b881e821..96568294 100644--- a/apps/web/src/features/dashboard/dashboard.css+++ b/apps/web/src/features/dashboard/dashboard.css@@ -1875,6 +1875,79 @@overflow-wrap: anywhere;}+.video-source-platforms-compact {+ width: min(592px, 100%);+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 4px 12px;+ margin: 10px auto 0;+}++.video-source-platforms-compact > span {+ flex-shrink: 0;+ font-weight: 450;+}++.video-source-platforms-compact .video-download-platforms {+ justify-content: flex-start;+ gap: 0;+ margin: 0;+}++.video-source-platforms-compact li {+ position: relative;+ width: 32px;+ height: 32px;+ display: block;+}++.video-source-platform-mark {+ width: 32px;+ height: 32px;+ display: grid;+ place-items: center;+ border-radius: 4px;+}++.video-source-platforms-compact .video-source-platform-mark img {+ width: 20px;+ height: 20px;+}++.video-source-platform-mark:hover,+.video-source-platform-mark:focus-visible {+ background: var(--surface-2);+}++.video-source-platforms-compact li > .video-source-platform-tooltip {+ position: absolute;+ pointer-events: none;+ z-index: 5;+ bottom: calc(100% + 6px);+ left: 50%;+ max-width: none;+ transform: translateX(-50%);+ padding: 5px 8px;+ border: 1px solid var(--border);+ border-radius: 5px;+ background: var(--surface);+ color: var(--text);+ font-size: 12px;+ font-weight: 450;+ line-height: 1.4;+ white-space: nowrap;+ box-shadow: 0 3px 8px rgb(0 0 0 / 12%);+}++@media (pointer: coarse) {+ .video-source-platforms-compact li,+ .video-source-platform-mark {+ width: 44px;+ height: 44px;+ }+}+.creator-tool-panel-heading > small {display: inline-flex;align-items: center;@@ -11520,6 +11593,88 @@text-decoration: none;}+.video-source-prepare-preview {+ min-height: 34px;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ margin-top: 5px;+ padding: 0 12px;+ border: 1px solid rgba(255, 255, 255, 0.3);+ border-radius: 6px;+ background: #f4f4f5;+ color: #18181b;+ font: inherit;+ font-size: 12px;+ cursor: pointer;+}++.video-source-preview-media:has(.video-source-prepare-preview) {+ min-height: 280px;+}++.video-source-preview-media:has(.video-source-preview-error) {+ min-height: 340px;+}++.video-source-preview-media:has(.video-source-preview-thumbnail) {+ min-height: 320px;+}++.video-source-preview-thumbnail {+ width: 160px;+ height: 90px;+ object-fit: contain;+ border-radius: 4px;+}++.video-source-retry-online {+ width: 30px;+ height: 30px;+ display: grid;+ place-items: center;+ border: 1px solid rgba(255, 255, 255, 0.18);+ border-radius: 6px;+ background: transparent;+ color: #f4f4f5;+ cursor: pointer;+}++.video-source-retry-online:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 3px;+}++.video-source-prepare-preview:disabled {+ opacity: 0.55;+ cursor: default;+}++.video-source-prepare-preview:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 3px;+}++.video-source-link-preview .video-source-preview-error {+ max-height: 72px;+ overflow: auto;+ color: #fca5a5;+ white-space: normal;+ overflow-wrap: anywhere;+}++.video-source-preview-spinner {+ animation: video-source-preview-spin 1s linear infinite;+}++@keyframes video-source-preview-spin {+ to { transform: rotate(360deg); }+}++@media (prefers-reduced-motion: reduce) {+ .video-source-preview-spinner { animation: none; }+}+.video-source-preview-footer {min-width: 0;min-height: 0;diff --git a/packages/protocol/src/creator-download.ts b/packages/protocol/src/creator-download.tsindex 38f1194b..ac11c6ad 100644--- a/packages/protocol/src/creator-download.ts+++ b/packages/protocol/src/creator-download.ts@@ -7,6 +7,80 @@ export function extractDouyinShareUrl(value: string): string {return links.length === 1 ? links[0]! : trimmed;}+export function normalizeVideoSourceUrl(value: string): string {+ const trimmed = extractDouyinShareUrl(value);+ try {+ const url = new URL(trimmed);+ if (isDouyinFeaturedVideoUrl(url)) {+ return `https://www.douyin.com/video/${url.searchParams.get('modal_id')}`;+ }+ } catch {+ return trimmed;+ }+ return trimmed;+}++export function supportedVideoSourcePlatform(value: string): DownloadPlatform | null {+ try {+ const url = new URL(normalizeVideoSourceUrl(value));+ if (url.protocol !== 'https:') return null;+ const host = url.hostname.toLowerCase();+ if (host === 'youtu.be' || host === 'youtube.com' || host.endsWith('.youtube.com')) return 'youtube';+ if (host === 'b23.tv' || host === 'bilibili.com' || host.endsWith('.bilibili.com')) return 'bilibili';+ if (host === 'x.com' || host.endsWith('.x.com') || host === 'twitter.com' || host.endsWith('.twitter.com')) return 'x';+ if (isTikTokVideoUrl(url)) return 'tiktok';+ if (isInstagramVideoUrl(url)) return 'instagram';+ if (isDouyinVideoUrl(url)) return 'douyin';+ if (isFacebookVideoUrl(url)) return 'facebook';+ if (isXiaohongshuVideoUrl(url)) return 'xiaohongshu';+ if (isPinterestVideoUrl(url)) return 'pinterest';+ } catch {+ return null;+ }+ return null;+}++function isTikTokVideoUrl(url: URL): boolean {+ const host = url.hostname.toLowerCase();+ if (host === 'vm.tiktok.com' || host === 'vt.tiktok.com') return /^\/[\w-]+\/?$/.test(url.pathname);+ return (host === 'tiktok.com' || host.endsWith('.tiktok.com')) && /^\/@[^/]+\/video\/\d+\/?$/.test(url.pathname);+}++function isInstagramVideoUrl(url: URL): boolean {+ return ['instagram.com', 'www.instagram.com'].includes(url.hostname.toLowerCase())+ && /^\/(?:reel|p|tv)\/[\w-]+\/?$/.test(url.pathname);+}++function isDouyinVideoUrl(url: URL): boolean {+ const host = url.hostname.toLowerCase();+ if (host === 'v.douyin.com') return /^\/[\w-]+\/?$/.test(url.pathname);+ return ['douyin.com', 'www.douyin.com'].includes(host)+ && (/^\/video\/\d+\/?$/.test(url.pathname) || isDouyinFeaturedVideoUrl(url));+}++function isDouyinFeaturedVideoUrl(url: URL): boolean {+ return ['douyin.com', 'www.douyin.com'].includes(url.hostname.toLowerCase())+ && url.pathname === '/jingxuan' && /^\d+$/.test(url.searchParams.get('modal_id') ?? '');+}++function isFacebookVideoUrl(url: URL): boolean {+ const host = url.hostname.toLowerCase();+ if (host === 'fb.watch') return /^\/[\w-]+\/?$/.test(url.pathname);+ if (!['facebook.com', 'www.facebook.com', 'm.facebook.com'].includes(host)) return false;+ return /^\/watch\/?$/.test(url.pathname)+ ? /^\d+$/.test(url.searchParams.get('v') ?? '')+ : /^\/(?:reel\/\d+|videos\/\d+|[^/]+\/videos\/\d+)\/?$/.test(url.pathname);+}++function isXiaohongshuVideoUrl(url: URL): boolean {+ return ['xiaohongshu.com', 'www.xiaohongshu.com'].includes(url.hostname.toLowerCase())+ && /^\/explore\/[0-9a-f]{24}\/?$/i.test(url.pathname);+}++function isPinterestVideoUrl(url: URL): boolean {+ return ['pinterest.com', 'www.pinterest.com'].includes(url.hostname.toLowerCase()) && /^\/pin\/\d+\/?$/.test(url.pathname);+}+export type DownloadMediaType = 'video' | 'audio';export type DownloadContainer = 'mp4' | 'mp3' | 'm4a' | 'webm';diff --git a/packages/protocol/src/video-metadata.ts b/packages/protocol/src/video-metadata.tsindex 36949b9d..6877e8a9 100644--- a/packages/protocol/src/video-metadata.ts+++ b/packages/protocol/src/video-metadata.ts@@ -1,4 +1,6 @@-export type VideoMetadataPlatform = 'youtube' | 'bilibili';+import { normalizeVideoSourceUrl, supportedVideoSourcePlatform, type DownloadPlatform } from './creator-download.js';++export type VideoMetadataPlatform = DownloadPlatform;export type VideoSourcePart = {index: number;@@ -14,6 +16,7 @@ export type VideoMetadataResponse = {title: string;authorName?: string;thumbnailUrl?: string;+ previewUrl?: string;width?: number;height?: number;parts?: VideoSourcePart[];@@ -51,7 +54,7 @@ export function videoSourceIdentity(value: string): string | null {const bilibili = parseBilibiliVideoSource(value);if (bilibili !== null) return `bilibili:${bilibili.videoId}:p${bilibili.partIndex ?? 1}`;try {- const source = new URL(value.trim());+ const source = new URL(normalizeVideoSourceUrl(value));if (source.protocol !== 'http:' && source.protocol !== 'https:') return null;const host = source.hostname.toLowerCase();const videoId = host === 'youtu.be'@@ -59,7 +62,12 @@ export function videoSourceIdentity(value: string): string | null {: host === 'youtube.com' || host.endsWith('.youtube.com')? source.searchParams.get('v') || source.pathname.match(/^\/(?:shorts|embed|live)\/([^/]+)\/?$/)?.[1]: undefined;- return videoId && /^[A-Za-z0-9_-]+$/.test(videoId) ? `youtube:${videoId}` : null;+ if (videoId && /^[A-Za-z0-9_-]+$/.test(videoId)) return `youtube:${videoId}`;+ const platform = supportedVideoSourcePlatform(source.toString());+ if (platform === null || (platform === 'youtube')+ || (platform === 'bilibili' && host !== 'b23.tv')) return null;+ source.hash = '';+ return `${platform}:${source.toString()}`;} catch {return null;}diff --git a/packages/protocol/test/video-source-platforms.test.ts b/packages/protocol/test/video-source-platforms.test.tsnew file mode 100644index 00000000..80aaf407--- /dev/null+++ b/packages/protocol/test/video-source-platforms.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest';+import { normalizeVideoSourceUrl, supportedVideoSourcePlatform } from '../src/creator-download.js';+import { videoSourceIdentity } from '../src/video-metadata.js';++describe('shared public video sources', () => {+ it.each([+ ['youtube', 'https://youtu.be/demo?si=share'],+ ['bilibili', 'https://www.bilibili.com/video/BV18E421w7bf?p=3'],+ ['bilibili', 'https://b23.tv/abc123'],+ ['x', 'https://x.com/creator/status/123'],+ ['x', 'https://twitter.com/creator/status/123'],+ ['tiktok', 'https://www.tiktok.com/@creator/video/123'],+ ['tiktok', 'https://vm.tiktok.com/abc123/'],+ ['instagram', 'https://www.instagram.com/reel/abc123/'],+ ['douyin', 'https://www.douyin.com/video/123'],+ ['douyin', 'https://v.douyin.com/abc123/'],+ ['facebook', 'https://www.facebook.com/watch/?v=123'],+ ['facebook', 'https://fb.watch/abc123/'],+ ['xiaohongshu', 'https://www.xiaohongshu.com/explore/6a9149f3000000001f01d20a?xsec_token=sample%3D'],+ ['pinterest', 'https://www.pinterest.com/pin/123/']+ ])('accepts %s videos and identifies them for saved previews: %s', (platform, url) => {+ expect(supportedVideoSourcePlatform(url)).toBe(platform);+ expect(videoSourceIdentity(url)).not.toBeNull();+ });++ it('normalizes Douyin featured URLs and share text consistently', () => {+ const url = 'https://v.douyin.com/abc123/';+ expect(normalizeVideoSourceUrl(`分享视频 ${url} 复制打开抖音`)).toBe(url);+ expect(supportedVideoSourcePlatform(`分享视频 ${url} 复制打开抖音`)).toBe('douyin');+ expect(videoSourceIdentity(`分享视频 ${url} 复制打开抖音`)).toBe(videoSourceIdentity(url));+ const featured = 'https://www.douyin.com/jingxuan?modal_id=123';+ expect(normalizeVideoSourceUrl(featured)).toBe('https://www.douyin.com/video/123');+ expect(videoSourceIdentity(featured)).toBe(videoSourceIdentity('https://www.douyin.com/video/123'));+ });++ it.each([+ 'https://www.tiktok.com/@creator', 'https://www.instagram.com/creator/',+ 'https://www.douyin.com/user/123', 'https://www.facebook.com/creator/',+ 'https://www.xiaohongshu.com/user/profile/123', 'https://www.pinterest.com/creator/',+ 'https://notpinterest.com/pin/123/', 'https://instagram.com.example.com/reel/abc/',+ 'http://www.instagram.com/reel/abc/', 'file:///tmp/video.mp4', 'not a URL'+ ])('rejects unsupported links: %s', url => {+ expect(supportedVideoSourcePlatform(url)).toBeNull();+ expect(videoSourceIdentity(url)).toBeNull();+ });++ it('preserves signed note parameters and never reuses a different note', () => {+ const url = 'https://www.xiaohongshu.com/explore/6a9149f3000000001f01d20a?xsec_token=sample%3D&xsec_source=pc_feed';+ expect(normalizeVideoSourceUrl(url)).toBe(url);+ expect(videoSourceIdentity(url)).not.toBe(videoSourceIdentity(url.replace('1f01d20a', '1f01d20b')));+ });+});diff --git a/runtime/krillinai/internal/service/link2file.go b/runtime/krillinai/internal/service/link2file.goindex 5d4f3755..28fe36bb 100644--- a/runtime/krillinai/internal/service/link2file.go+++ b/runtime/krillinai/internal/service/link2file.go@@ -9,8 +9,10 @@ import ("krillin-ai/internal/types""krillin-ai/log""krillin-ai/pkg/util"+ "net/url""os""os/exec"+ "regexp""strings""go.uber.org/zap"@@ -22,6 +24,11 @@ func (s Service) linkToFile(ctx context.Context, stepParam *types.SubtitleTaskStoutput []byte)link := stepParam.Link+ source, _ := url.Parse(strings.TrimSpace(link))+ sourceHost := ""+ if source != nil {+ sourceHost = strings.ToLower(source.Hostname())+ }audioPath := fmt.Sprintf("%s/%s", stepParam.TaskBasePath, types.SubtitleTaskAudioFileName)videoPath := fmt.Sprintf("%s/%s", stepParam.TaskBasePath, types.SubtitleTaskVideoFileName)localVideoPath, isLocal := resolveLocalMediaInput(link)@@ -39,7 +46,7 @@ func (s Service) linkToFile(ctx context.Context, stepParam *types.SubtitleTaskStlog.GetLogger().Error("generateAudioSubtitles.linkToFile ffmpeg error", zap.Any("step param", stepParam), zap.String("output", string(output)), zap.Error(err))return fmt.Errorf("generateAudioSubtitles.linkToFile ffmpeg error: %w", err)}- } else if strings.Contains(link, "youtube.com") {+ } else if sourceHost == "youtu.be" || sourceHost == "youtube.com" || strings.HasSuffix(sourceHost, ".youtube.com") {var videoId stringvideoId, err = util.GetYouTubeID(link)if err != nil {@@ -50,6 +57,7 @@ func (s Service) linkToFile(ctx context.Context, stepParam *types.SubtitleTaskStif !stepParam.VttSwitch && !stepParam.SkipAudio {// 使用更灵活的音频格式选择器,避免 HTTP 403 错误。cmdArgs := []string{+ "--no-playlist","-f", "bestaudio[ext=m4a]/bestaudio[ext=mp3]/bestaudio/worst","--extract-audio","--audio-format", "mp3",@@ -71,7 +79,7 @@ func (s Service) linkToFile(ctx context.Context, stepParam *types.SubtitleTaskStreturn fmt.Errorf("linkToFile download audio yt-dlp error: %w: %s", err, compactCommandOutput(output))}}- } else if strings.Contains(link, "bilibili.com") {+ } else if sourceHost == "bilibili.com" || strings.HasSuffix(sourceHost, ".bilibili.com") {normalizedLink, normalizeErr := util.NormalizeBilibiliVideoURL(link)if normalizeErr != nil {return fmt.Errorf("linkToFile error: %w", normalizeErr)@@ -92,9 +100,24 @@ func (s Service) linkToFile(ctx context.Context, stepParam *types.SubtitleTaskStreturn fmt.Errorf("linkToFile download audio yt-dlp error: %w: %s", err, compactCommandOutput(output))}}+ } else if isAdditionalVideoSource(link) {+ if !stepParam.SkipAudio {+ cmdArgs := []string{"--no-playlist", "-f", "bestaudio/best", "--extract-audio", "--audio-format", "mp3", "--audio-quality", "192K", "-o", audioPath, stepParam.Link}+ if config.Conf.App.Proxy != "" {+ cmdArgs = append(cmdArgs, "--proxy", config.Conf.App.Proxy)+ }+ cmdArgs = appendCookiesArgs(cmdArgs, youtubeCookiesPath)+ if storage.FfmpegPath != "ffmpeg" {+ cmdArgs = append(cmdArgs, "--ffmpeg-location", storage.FfmpegPath)+ }+ output, err = storage.YtdlpCommand(cmdArgs...).CombinedOutput()+ if err != nil {+ return fmt.Errorf("linkToFile download audio yt-dlp error: %w: %s", err, compactCommandOutput(output))+ }+ }} else {log.GetLogger().Info("linkToFile.unsupported link type", zap.Any("step param", stepParam))- return errors.New("linkToFile error: unsupported link, only support youtube, bilibili and local file")+ return errors.New("linkToFile error: unsupported public video source")}stepParam.TaskPtr.SetProgress(6)if !stepParam.SkipAudio {@@ -104,6 +127,9 @@ func (s Service) linkToFile(ctx context.Context, stepParam *types.SubtitleTaskStif !isLocal && stepParam.EmbedSubtitleVideoType != "none" {// 需要下载原视频cmdArgs := []string{"--no-playlist", "-f", "bestvideo[height<=1080][ext=mp4]+bestaudio[ext=m4a]/bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/bestvideo[height<=480][ext=mp4]+bestaudio[ext=m4a]", "-o", videoPath, stepParam.Link}+ if isAdditionalVideoSource(stepParam.Link) {+ cmdArgs = []string{"--no-playlist", "-f", "bestvideo[height<=1080]+bestaudio/best[height<=1080]/best", "--merge-output-format", "mp4", "--recode-video", "mp4", "-o", videoPath, stepParam.Link}+ }cmdArgs = appendCookiesArgs(cmdArgs, youtubeCookiesPath)if config.Conf.App.Proxy != "" {cmdArgs = append(cmdArgs, "--proxy", config.Conf.App.Proxy)@@ -125,6 +151,41 @@ func (s Service) linkToFile(ctx context.Context, stepParam *types.SubtitleTaskStreturn nil}+func isAdditionalVideoSource(value string) bool {+ source, err := url.Parse(strings.TrimSpace(value))+ if err != nil || source.Scheme != "https" {+ return false+ }+ host := strings.ToLower(source.Hostname())+ path := source.Path+ match := func(pattern string) bool { return regexp.MustCompile(pattern).MatchString(path) }+ switch {+ case host == "x.com" || strings.HasSuffix(host, ".x.com") || host == "twitter.com" || strings.HasSuffix(host, ".twitter.com"):+ return true+ case host == "vm.tiktok.com" || host == "vt.tiktok.com" || host == "v.douyin.com" || host == "fb.watch":+ return match(`^/[\w-]+/?$`)+ case host == "tiktok.com" || strings.HasSuffix(host, ".tiktok.com"):+ return match(`^/@[^/]+/video/\d+/?$`)+ case host == "instagram.com" || host == "www.instagram.com":+ return match(`^/(?:reel|p|tv)/[\w-]+/?$`)+ case host == "douyin.com" || host == "www.douyin.com":+ return match(`^/video/\d+/?$`)+ case host == "facebook.com" || host == "www.facebook.com" || host == "m.facebook.com":+ if match(`^/watch/?$`) {+ return regexp.MustCompile(`^\d+$`).MatchString(source.Query().Get("v"))+ }+ return match(`^/(?:reel/\d+|videos/\d+|[^/]+/videos/\d+)/?$`)+ case host == "xiaohongshu.com" || host == "www.xiaohongshu.com":+ return match(`(?i)^/explore/[0-9a-f]{24}/?$`)+ case host == "pinterest.com" || host == "www.pinterest.com":+ return match(`^/pin/\d+/?$`)+ case host == "b23.tv":+ return match(`^/[\w-]+/?$`)+ default:+ return false+ }+}+func resolveLocalMediaInput(input string) (string, bool) {value := strings.TrimSpace(input)if strings.HasPrefix(value, "local:") {diff --git a/runtime/krillinai/internal/service/link2file_test.go b/runtime/krillinai/internal/service/link2file_test.goindex a7a296d9..6359860c 100644--- a/runtime/krillinai/internal/service/link2file_test.go+++ b/runtime/krillinai/internal/service/link2file_test.go@@ -77,3 +77,76 @@ func TestResolveLocalMediaInput(t *testing.T) {t.Fatalf("missing input = %q, %v; want empty, false", got, ok)}}++func TestAdditionalPlatformMediaDownloads(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell downloader fixture requires POSIX")+ }+ originalYtdlp, originalPrefix, originalFfmpeg, originalProxy := storage.YtdlpPath, storage.YtdlpPrefixArgs, storage.FfmpegPath, config.Conf.App.Proxy+ t.Cleanup(func() {+ storage.YtdlpPath, storage.YtdlpPrefixArgs, storage.FfmpegPath, config.Conf.App.Proxy = originalYtdlp, originalPrefix, originalFfmpeg, originalProxy+ })+ dir := t.TempDir()+ argsPath := filepath.Join(dir, "arguments")+ downloader := filepath.Join(dir, "yt-dlp")+ t.Setenv("VIDEO_SOURCE_TEST_ARGS", argsPath)+ if err := os.WriteFile(downloader, []byte("#!/bin/sh\nprintf '%s\\n' \"$@\" >> \"$VIDEO_SOURCE_TEST_ARGS\"\n"), 0700); err != nil {+ t.Fatal(err)+ }+ storage.YtdlpPath, storage.YtdlpPrefixArgs, storage.FfmpegPath, config.Conf.App.Proxy = downloader, nil, "/custom/ffmpeg", "http://127.0.0.1:7897"+ for _, link := range []string{+ "https://x.com/creator/status/123",+ "https://www.tiktok.com/@creator/video/123",+ "https://vm.tiktok.com/abc123/",+ "https://www.instagram.com/reel/abc123/",+ "https://www.douyin.com/video/123",+ "https://v.douyin.com/abc123/",+ "https://www.facebook.com/watch/?v=123",+ "https://fb.watch/abc123/",+ "https://www.xiaohongshu.com/explore/6a9149f3000000001f01d20a?xsec_token=sample%3D",+ "https://www.pinterest.com/pin/123/",+ } {+ t.Run(link, func(t *testing.T) {+ for _, mode := range []struct {+ compose string+ skipAudio bool+ commands int+ }{{"none", false, 1}, {"horizontal", false, 2}, {"horizontal", true, 1}} {+ if err := os.WriteFile(argsPath, nil, 0600); err != nil {+ t.Fatal(err)+ }+ step := &types.SubtitleTaskStepParam{Link: link, TaskBasePath: dir, TaskPtr: &types.SubtitleTask{},+ EmbedSubtitleVideoType: mode.compose, SkipAudio: mode.skipAudio}+ if err := (Service{}).linkToFile(context.Background(), step); err != nil {+ t.Fatal(err)+ }+ arguments, err := os.ReadFile(argsPath)+ if err != nil {+ t.Fatal(err)+ }+ args := string(arguments)+ if strings.Count(args, "--no-playlist\n") != mode.commands || strings.Count(args, link+"\n") != mode.commands {+ t.Fatalf("expected %d single-video downloads with source parameters, got %s", mode.commands, args)+ }+ if !strings.Contains(args, "--proxy\nhttp://127.0.0.1:7897\n") || !strings.Contains(args, "--ffmpeg-location\n/custom/ffmpeg\n") {+ t.Fatalf("missing proxy or ffmpeg arguments: %s", args)+ }+ if !mode.skipAudio && (!strings.Contains(args, "bestaudio/best\n") || step.AudioFilePath == "") {+ t.Fatalf("missing audio extraction: %s", args)+ }+ if mode.compose != "none" && !strings.Contains(args, "--recode-video\nmp4\n") {+ t.Fatalf("missing video conversion: %s", args)+ }+ }+ })+ }+}++func TestAdditionalPlatformRejectsUnsupportedSources(t *testing.T) {+ for _, link := range []string{"https://www.instagram.com/creator/", "https://www.pinterest.com/creator/",+ "https://notpinterest.com/pin/123/", "https://instagram.com.example.com/reel/abc/", "http://www.instagram.com/reel/abc/"} {+ if isAdditionalVideoSource(link) {+ t.Fatalf("accepted unsupported source: %s", link)+ }+ }+}