import { del, get, http, post, put, type JavaApiResponse, unwrapJavaResponse, } from "./http.ts"; import { getTaskProgressCacheTtlMs, getTaskProgressTimeoutMs } from "../task-progress-config.ts"; import { createTaskProgressRequestCache } from "../task-progress-request-cache.ts"; export * from "./types/modules/dedupe.ts"; export * from "./types/modules/split.ts"; export * from "./types/modules/convert.ts"; export * from "./types/modules/publish.ts"; export * from "./types/modules/similar-asin.ts"; export * from "./types/modules/appearance-patent.ts"; export * from "./types/modules/delete-brand.ts"; export * from "./types/modules/price-track.ts"; export * from "./types/modules/shop-match.ts"; export * from "./types/modules/query-asin.ts"; export * from "./types/modules/withdraw.ts"; export * from "./types/modules/collect-data.ts"; import type { ProductRiskCandidateVo, ProductRiskDashboardVo, ProductRiskMatchShopsVo, ProductRiskShopQueueItem, } from "./types/modules/shop-match.ts"; import type { QueryAsinCandidateVo, QueryAsinDashboardVo, } from "./types/modules/query-asin.ts"; const JAVA_API_PREFIX = "/newApi/api"; interface TaskProgressBatchOptions { force?: boolean; } /** 进度批量接口的响应缓存与并发合并:TTL 过期、有界条目、in-flight 去重 */ const taskProgressResponseCache = createTaskProgressRequestCache({ ttlMs: () => getTaskProgressCacheTtlMs(), maxEntries: 100, maxInflight: 16, }); function getCurrentUserId() { const raw = typeof window === "undefined" ? "" : window.localStorage.getItem("uid") || ""; const value = Number(raw); if (!Number.isFinite(value) || value <= 0) { throw new Error("未获取到用户ID"); } return value; } function normalizeTaskIds(taskIds: number[]) { return Array.from( new Set( (taskIds || []) .map((taskId) => Number(taskId)) .filter((taskId) => Number.isFinite(taskId) && taskId > 0), ), ).sort((left, right) => left - right); } function buildTaskProgressRequestKey(path: string, taskIds: number[]) { return `${path}::${taskIds.join(",")}`; } async function postTaskProgressBatch( path: string, taskIds: number[], options: TaskProgressBatchOptions = {}, ) { const normalizedTaskIds = normalizeTaskIds(taskIds); if (!normalizedTaskIds.length) { return { items: [], missingTaskIds: [] } as T; } const cacheKey = buildTaskProgressRequestKey(path, normalizedTaskIds); const cached = taskProgressResponseCache.get(cacheKey); if (!options.force && cached !== undefined) { return cached as T; } const inflight = taskProgressResponseCache.getInflight(cacheKey); if (!options.force && inflight) { return (await inflight) as T; } const requestPromise = unwrapJavaResponse( post, { taskIds: number[] }>(path, { taskIds: normalizedTaskIds }, { timeout: getTaskProgressTimeoutMs(), }), ) .then((data) => { taskProgressResponseCache.set(cacheKey, data); return data; }) .finally(() => { taskProgressResponseCache.endInflight(cacheKey); }); taskProgressResponseCache.startInflight(cacheKey, requestPromise); return requestPromise; } export interface UploadedFileRef { fileKey: string; originalFilename?: string; relativePath?: string; } export interface UploadFileVo { fileKey: string; originalFilename: string; localPath: string; size: number; relativePath?: string; objectKey?: string; url?: string; mediaType?: "image" | "video" | "audio" | "file" | string; } export interface UploadTempFileOptions { relativePath?: string; uploadToOss?: boolean; moduleType?: string; } export async function uploadTempFileToJava( file: File, relativePathOrOptions?: string | UploadTempFileOptions, ) { const options = typeof relativePathOrOptions === 'string' ? { relativePath: relativePathOrOptions } : relativePathOrOptions || {} const formData = new FormData() formData.append('file', file) if (options.relativePath) { formData.append('relativePath', options.relativePath) } if (options.uploadToOss) { formData.append('uploadToOss', 'true') } if (options.moduleType) { formData.append('moduleType', options.moduleType) } const response = await http.post>( `${JAVA_API_PREFIX}/files/upload`, formData, { headers: { 'Content-Type': 'multipart/form-data', }, timeout: 120000, }, ) return response.data } // ========== 视频复刻 / 图生视频 ========== export interface ImageVideoDouyinCopyVo { recognizedContent?: string; scriptDraft?: string; executeId?: string; debugUrl?: string; } export interface ImageVideoDouyinCopyPayload { url: string; api_key?: string; t8_key?: string; duration?: number; proc_info?: { type: string; name: string; proc_image: string[]; properties: string; }; } export interface ImageVideoSecretStatusVo { userId?: number; configured?: boolean; valid?: boolean; expired?: boolean; hasCopyApiKey?: boolean; hasT8Key?: boolean; hasT8VideoKey?: boolean; hasVoiceApiKey?: boolean; hasVoiceGroupId?: boolean; copyApiKeyMasked?: string; t8KeyMasked?: string; t8VideoKeyMasked?: string; voiceApiKeyMasked?: string; voiceGroupIdMasked?: string; expireDays?: number; expiresAt?: string; } export interface ImageVideoSecretSavePayload { copyApiKey?: string; t8Key?: string; t8VideoKey?: string; voiceApiKey?: string; voiceGroupId?: string; expireDays: number; } export interface ImageVideoWorkflowParameters { api_key_info: { t8star_key: string; t8_video_key: string; ai_conductor_key: string; }; bg_info: { type: number; prompt: string; bg_image: string; }; face_info: { type: number; model_figure: string; model_image: string[]; }; proc_info: { type: string; name: string; proc_image: string[]; properties: string; }; text_info: { type: number; language: string; text: string; file_url: string; }; audio_info: { audio_url: string; type: number; bgm_url: string; mode: number; voice_name: string; }; video_info: { video_url: string; share_url: string; ref_video_mode: string; mode: string; draft: boolean; model: string; prompt: string; ratio: string; resolution: string; duration: number; }; } export interface ImageVideoWorkflowResponse { code?: number; msg?: string; data?: string; execute_id?: string; debug_url?: string; [key: string]: unknown; } export type ImageVideoAsyncTaskStatus = 'PENDING' | 'RUNNING' | 'WAITING' | 'POLLING' | 'SUCCESS' | 'FAILED' export interface ImageVideoAsyncTaskVo { taskId: number; taskType: string; status: ImageVideoAsyncTaskStatus; cozeExecuteId?: string; cozeStatus?: string; debugUrl?: string; result?: unknown; errorMessage?: string; submittedAt?: string; completedAt?: string; } export interface ImageVideoMediaUploadVo { url: string; objectKey: string; originalFilename: string; mediaType: "image" | "video" | "audio" | string; } export interface ImageVideoVoiceWorkflowResponse { code?: number; msg?: string; data?: unknown; execute_id?: string; debug_url?: string; [key: string]: unknown; } export interface ImageVideoWorkflowRunRequest { userId: number; parameters: ImageVideoWorkflowParameters; } export interface ImageVideoWorkflowResultRequest { userId: number; executeId: string; } export function getImageVideoSecretStatus() { return unwrapJavaResponse( get>( `${JAVA_API_PREFIX}/image-video/secrets`, { params: { user_id: getCurrentUserId() } }, ), ); } export function saveImageVideoSecrets(payload: ImageVideoSecretSavePayload) { return unwrapJavaResponse( put, ImageVideoSecretSavePayload & { userId: number }>( `${JAVA_API_PREFIX}/image-video/secrets`, { ...payload, userId: getCurrentUserId() }, ), ); } export function runImageVideoDouyinCopy(payload: ImageVideoDouyinCopyPayload) { return unwrapJavaResponse( post, ImageVideoDouyinCopyPayload & { userId: number }>( `${JAVA_API_PREFIX}/image-video/douyin-copy`, { userId: getCurrentUserId(), ...payload }, ), ); } export function runImageVideoWorkflow(parameters: ImageVideoWorkflowParameters) { return unwrapJavaResponse( post, ImageVideoWorkflowRunRequest>( `${JAVA_API_PREFIX}/image-video/workflow/run`, { userId: getCurrentUserId(), parameters }, ), ); } export function getImageVideoWorkflowResult(executeId: string) { return unwrapJavaResponse( post, ImageVideoWorkflowResultRequest>( `${JAVA_API_PREFIX}/image-video/workflow/result`, { userId: getCurrentUserId(), executeId }, ), ); } export function getImageVideoAsyncTask(taskId: number) { return unwrapJavaResponse( get>( `${JAVA_API_PREFIX}/image-video/tasks/${taskId}`, { params: { user_id: getCurrentUserId() } }, ), ); } export async function uploadImageVideoMedia(file: File) { const response = await uploadTempFileToJava(file, { uploadToOss: true, moduleType: "IMAGE_VIDEO", }); if (!response.success) { throw new Error(response.message || "请求失败"); } const data = response.data; if (!data?.url || !data.objectKey) { throw new Error("OSS 上传未返回有效 URL"); } return { url: data.url, objectKey: data.objectKey, originalFilename: data.originalFilename || file.name, mediaType: data.mediaType || resolveImageVideoMediaType(file), } as ImageVideoMediaUploadVo; } function resolveImageVideoMediaType(file: File) { const type = (file.type || "").toLowerCase(); const name = (file.name || "").toLowerCase(); if (type.startsWith("image/") || /\.(png|jpe?g|webp|gif|bmp|svg)$/.test(name)) return "image"; if (type.startsWith("video/") || /\.(mp4|mov|webm|m4v|ogg|avi|mkv)$/.test(name)) return "video"; if (type.startsWith("audio/") || /\.(mp3|wav|m4a|aac|flac)$/.test(name)) return "audio"; return "file"; } export function listImageVideoVoices(name = "") { return unwrapJavaResponse( post, { userId: number; name: string }>( `${JAVA_API_PREFIX}/image-video/voice/list`, { userId: getCurrentUserId(), name }, ), ); } export function deleteImageVideoVoice(voiceId: string) { return unwrapJavaResponse( post, { userId: number; voiceId: string }>( `${JAVA_API_PREFIX}/image-video/voice/delete`, { userId: getCurrentUserId(), voiceId }, ), ); } export function cloneImageVideoVoice(payload: { name?: string; audioUrl?: string; videoUrl?: string }) { return unwrapJavaResponse( post, { userId: number; name?: string; audioUrl?: string; videoUrl?: string }>( `${JAVA_API_PREFIX}/image-video/voice/clone`, { userId: getCurrentUserId(), ...payload }, ), ); } export function synthesizeImageVideoVoice(payload: { text: string; voiceId: string }) { return unwrapJavaResponse( post, { userId: number; text: string; voiceId: string }>( `${JAVA_API_PREFIX}/image-video/voice/synthesis`, { userId: getCurrentUserId(), ...payload }, ), ); } export function getJavaDownloadUrl(path: string) { let raw = path.startsWith("http://") || path.startsWith("https://") ? path : `${JAVA_API_PREFIX}${path}`; // pywebview 的 save_file_from_url_new 需要完整且带 schema 的 URL if ( !raw.startsWith("http://") && !raw.startsWith("https://") && typeof window !== "undefined" ) { raw = `${window.location.origin}${raw}`; } const separator = raw.includes("?") ? "&" : "?"; return `${raw}${separator}user_id=${encodeURIComponent(String(getCurrentUserId()))}`; } export { JAVA_API_PREFIX, http };