Repository navigation
Expand file tree
/
Copy pathsora-api.ts
More file actions
1613 lines (1367 loc) · 48.8 KB
/
Copy pathsora-api.ts
File metadata and controls
1613 lines (1367 loc) · 48.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable no-console */
import { getSystemConfig, getVideoChannels, getVideoChannel } from './db';
import { fetch as undiciFetch, Agent, FormData, type RequestInit as UndiciRequestInit } from 'undici';
import type { VideoChannel } from '@/types';
import { fetchWithRetry } from './http-retry';
import { GENERATION_SUBMIT_TIMEOUT_MS, isTransientError } from './polling-utils';
type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
const LOG_LEVELS: Record<LogLevel, number> = {
debug: 10,
info: 20,
warn: 30,
error: 40,
silent: 50,
};
const SORA_LOG_LEVEL: LogLevel = (() => {
const raw = (process.env.SORA_LOG_LEVEL || '').toLowerCase();
if (raw in LOG_LEVELS) return raw as LogLevel;
return process.env.NODE_ENV === 'production' ? 'info' : 'debug';
})();
const shouldLog = (level: LogLevel) => LOG_LEVELS[level] >= LOG_LEVELS[SORA_LOG_LEVEL];
const logDebug = (...args: unknown[]) => {
if (shouldLog('debug')) console.log(...args);
};
const logInfo = (...args: unknown[]) => {
if (shouldLog('info')) console.log(...args);
};
const logWarn = (...args: unknown[]) => {
if (shouldLog('warn')) console.warn(...args);
};
const logError = (...args: unknown[]) => {
if (shouldLog('error')) console.error(...args);
};
// ========================================
// Sora OpenAI-Style Non-Streaming API
// ========================================
// 解析视频 URL(处理字符串、JSON 字符串数组、数组等格式)
function parseVideoUrl(url: string | string[] | unknown): string {
if (Array.isArray(url)) {
return url.length > 0 ? parseVideoUrl(url[0]) : '';
}
if (typeof url !== 'string') {
return String(url);
}
const trimmed = url.trim();
if (!trimmed) {
return trimmed;
}
const parsedArray = tryParseJsonArray(trimmed);
if (parsedArray) {
return normalizeUrlString(parsedArray);
}
const unwrapped = unwrapEncodedArray(trimmed);
if (unwrapped) {
return normalizeUrlString(unwrapped);
}
if (
(trimmed.startsWith('"') && trimmed.endsWith('"')) ||
(trimmed.startsWith("'") && trimmed.endsWith("'"))
) {
const inner = trimmed.slice(1, -1).trim();
const innerParsed = tryParseJsonArray(inner);
if (innerParsed) {
return normalizeUrlString(innerParsed);
}
const innerUnwrapped = unwrapEncodedArray(inner);
if (innerUnwrapped) {
return normalizeUrlString(innerUnwrapped);
}
}
return trimmed;
}
function tryParseJsonArray(value: string): string | null {
if (!value.startsWith('[')) {
return null;
}
try {
const parsed = JSON.parse(value);
if (Array.isArray(parsed) && parsed.length > 0) {
return String(parsed[0]);
}
} catch {
return null;
}
return null;
}
function unwrapEncodedArray(value: string): string | null {
const trimmed = value.trim();
const lower = trimmed.toLowerCase();
const encodedOpen = '%5b%22';
const encodedClose = '%22%5d';
if (lower.startsWith(encodedOpen) && lower.endsWith(encodedClose)) {
return trimmed.slice(encodedOpen.length, trimmed.length - encodedClose.length);
}
const mixedOpen = '[%22';
const mixedClose = '%22]';
if (lower.startsWith(mixedOpen) && lower.endsWith(mixedClose)) {
return trimmed.slice(mixedOpen.length, trimmed.length - mixedClose.length);
}
return null;
}
function normalizeUrlString(value: string): string {
const trimmed = value.trim();
if (/^https?:%2f%2f/i.test(trimmed)) {
try {
return decodeURIComponent(trimmed);
} catch {
return trimmed;
}
}
return trimmed;
}
// 视频代理 URL 替换(将 videos.openai.com 替换为配置的加速域名)
export async function applyVideoProxy(url: string): Promise<string> {
if (!url) return url;
try {
const config = await getSystemConfig();
if (!config.videoProxyEnabled || !config.videoProxyBaseUrl) {
return url;
}
// 检查是否是 OpenAI 视频 URL
const openaiVideoPattern = /^https:\/\/videos\.openai\.com\//;
if (openaiVideoPattern.test(url)) {
// 确保代理 baseUrl 以 / 结尾
const proxyBase = config.videoProxyBaseUrl.replace(/\/$/, '') + '/';
// 替换域名
const proxiedUrl = url.replace(openaiVideoPattern, proxyBase);
logDebug('[Video Proxy] URL replaced:', { original: url.substring(0, 80), proxied: proxiedUrl.substring(0, 80) });
return proxiedUrl;
}
} catch (e) {
logWarn('[Video Proxy] Failed to apply proxy:', e);
}
return url;
}
const DEFAULT_SORA_BASE_URL = 'http://localhost:8000';
const SORA_REQUEST_TIMEOUT_MS = GENERATION_SUBMIT_TIMEOUT_MS;
type SoraConfig = {
apiKey: string;
baseUrl: string;
channelId?: string;
channelType?: VideoChannel['type'] | 'legacy';
};
let soraChannelCursor = 0;
function isSoraCompatibleChannel(channel: VideoChannel): boolean {
return (channel.type === 'sora' || channel.type === 'apexerapi') && Boolean(channel.apiKey);
}
function pickRoundRobinChannel(channels: VideoChannel[]): VideoChannel {
const index = soraChannelCursor % channels.length;
soraChannelCursor = (soraChannelCursor + 1) % channels.length;
return channels[index];
}
// 获取 Sora 配置(优先从新渠道表读取,回退到旧 system_config)
async function getSoraConfig(options?: {
channelId?: string;
mode?: 'default' | 'round-robin';
}): Promise<SoraConfig> {
if (options?.channelId) {
const channel = await getVideoChannel(options.channelId);
if (channel && isSoraCompatibleChannel(channel)) {
return {
apiKey: channel.apiKey,
baseUrl: channel.baseUrl || DEFAULT_SORA_BASE_URL,
channelId: channel.id,
channelType: channel.type,
};
}
}
const channels = await getVideoChannels(true);
const soraChannels = channels.filter(isSoraCompatibleChannel);
if (soraChannels.length > 0) {
const selected =
options?.mode === 'round-robin'
? pickRoundRobinChannel(soraChannels)
: soraChannels[0];
return {
apiKey: selected.apiKey,
baseUrl: selected.baseUrl || DEFAULT_SORA_BASE_URL,
channelId: selected.id,
channelType: selected.type,
};
}
const config = await getSystemConfig();
return {
apiKey: config.soraApiKey || '',
baseUrl: config.soraBaseUrl || DEFAULT_SORA_BASE_URL,
channelType: 'legacy',
};
}
// 创建自定义 Agent
const soraAgent = new Agent({
bodyTimeout: 0,
headersTimeout: SORA_REQUEST_TIMEOUT_MS,
keepAliveTimeout: SORA_REQUEST_TIMEOUT_MS,
keepAliveMaxTimeout: SORA_REQUEST_TIMEOUT_MS,
pipelining: 0,
connections: 30,
connect: {
timeout: SORA_REQUEST_TIMEOUT_MS,
},
});
// ========================================
// Video Generation API (New Format)
// ========================================
export interface VideoGenerationRequest {
prompt: string;
model?: string;
seconds?: string;
orientation?: 'landscape' | 'portrait';
size?: string; // e.g., '1920x1080', '1080x1920'
style_id?: string;
input_image?: string; // Base64 encoded image
remix_target_id?: string;
metadata?: string; // JSON string for extended params
async_mode?: boolean;
}
// Video Remix request
export interface VideoRemixRequest {
prompt: string;
model?: string;
seconds?: string;
orientation?: 'landscape' | 'portrait';
size?: string;
style_id?: string;
remix_target_id?: string;
async_mode?: boolean;
}
function parseSeconds(value: unknown, fallback = 8): number {
if (value === undefined || value === null) return fallback;
const matched = String(value).match(/(\d+)/);
if (!matched) return fallback;
const parsed = Number.parseInt(matched[1], 10);
if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
return parsed;
}
function normalizeApexerSeconds(...values: unknown[]): string {
const raw = values.find((value) => value !== undefined && value !== null && String(value).trim());
const seconds = parseSeconds(raw, 8);
return String(Math.max(1, Math.min(seconds, 20)));
}
function inferApexerOrientation(request: Pick<VideoGenerationRequest, 'model' | 'orientation' | 'size'>): 'landscape' | 'portrait' {
if (request.orientation === 'portrait' || request.orientation === 'landscape') {
return request.orientation;
}
const model = String(request.model || '').toLowerCase();
if (model.includes('portrait')) return 'portrait';
if (model.includes('landscape')) return 'landscape';
const size = String(request.size || '').toLowerCase();
const matched = size.match(/^(\d+)x(\d+)$/);
if (matched) {
const width = Number.parseInt(matched[1], 10);
const height = Number.parseInt(matched[2], 10);
if (Number.isFinite(width) && Number.isFinite(height) && height > width) {
return 'portrait';
}
}
return 'landscape';
}
function apexerSizeForOrientation(orientation: 'landscape' | 'portrait'): string {
return orientation === 'portrait' ? '720x1280' : '1280x720';
}
function normalizeApexerVideoRequest(request: VideoGenerationRequest): VideoGenerationRequest {
const orientation = inferApexerOrientation(request);
return {
...request,
model: 'sora-2',
seconds: normalizeApexerSeconds(request.seconds, request.model),
orientation,
size: request.size || apexerSizeForOrientation(orientation),
};
}
function shouldUseApexerVideoContract(channelType?: SoraConfig['channelType']): boolean {
return channelType === 'apexerapi' || channelType === 'sora' || channelType === 'legacy';
}
function normalizeApexerImageRequest(request: ImageGenerationRequest): ImageGenerationRequest {
const requestedModel = String(request.model || '').trim().toLowerCase();
const model = !requestedModel || requestedModel.startsWith('sora-image')
? 'gpt-image-2'
: request.model;
let size = request.size;
if (!size || size === '1792x1024') {
size = requestedModel.includes('landscape') ? '1536x1024' : size;
}
if (!size || size === '1024x1792') {
size = requestedModel.includes('portrait') ? '1024x1536' : size;
}
if (!size) {
size = '1024x1024';
}
return {
...request,
model,
size,
};
}
// Helper: check if status indicates completion
function isCompletedStatus(status: VideoTaskStatus): boolean {
return status === 'completed' || status === 'succeeded';
}
// Helper: check if status indicates in progress
function isInProgressStatus(status: VideoTaskStatus): boolean {
return status === 'queued' || status === 'pending' || status === 'in_progress' || status === 'processing';
}
// Video task status (new-api-main compatible)
export type VideoTaskStatus =
| 'queued' // 排队中
| 'pending' // 等待中
| 'in_progress' // 处理中 (new-api-main)
| 'processing' // 处理中 (legacy)
| 'completed' // 成功 (new-api-main)
| 'succeeded' // 成功 (legacy)
| 'failed' // 失败
| 'cancelled'; // 已取消
// New API response format (new-api-main compatible)
export interface VideoTaskResponse {
id: string;
object: string;
model: string;
created_at: number;
completed_at?: number;
expires_at?: number;
status: VideoTaskStatus;
progress: number;
size?: string;
seconds?: string;
quality?: string;
url?: string;
output?: { url?: string };
permalink?: string;
revised_prompt?: string;
remixed_from_video_id?: string | null;
metadata?: Record<string, unknown>;
error?: {
message: string;
type?: string;
code?: string;
} | null;
}
// Legacy response format (for compatibility)
export interface VideoGenerationResponse {
id: string;
object: string;
created: number;
model: string;
data: Array<{
url: string;
permalink?: string;
revised_prompt?: string;
[key: string]: unknown;
}>;
}
export interface VideoGenerationResult extends VideoGenerationResponse {
channelId?: string;
}
// 自适应轮询间隔计算
function getPollingInterval(progress: number, stallCount: number): number {
// 基础间隔根据进度调整
let baseInterval: number;
if (progress < 30) {
baseInterval = 5000; // 0-30%: 5秒
} else if (progress < 70) {
baseInterval = 3000; // 30-70%: 3秒
} else {
baseInterval = 2000; // 70-100%: 2秒
}
// 停滞时增加间隔
if (stallCount > 0) {
baseInterval = Math.min(baseInterval + stallCount * 2000, 10000);
}
return baseInterval;
}
// 查询视频任务状态
export async function getVideoStatus(videoId: string, channelId?: string): Promise<VideoTaskResponse> {
const { apiKey, baseUrl } = await getSoraConfig({ channelId });
if (!apiKey) {
throw new Error('Sora API Key 未配置');
}
const normalizedBaseUrl = baseUrl.replace(/\/$/, '');
const apiUrl = `${normalizedBaseUrl}/v1/videos/${videoId}`;
logDebug('[Sora API v5] Query video status:', apiUrl);
const response = await fetchWithRetry(undiciFetch, apiUrl, () => ({
method: 'GET',
headers: {
Authorization: `Bearer ${apiKey}`,
},
dispatcher: soraAgent,
}));
const rawData = await response.json() as any;
logDebug('[Sora API v5] Status response:', JSON.stringify(rawData).substring(0, 200));
// 处理 NewAPI 包装格式
let data = rawData;
if (rawData?.code && rawData?.message && typeof rawData.message === 'string') {
try {
const parsed = JSON.parse(rawData.message);
if (parsed?.id) {
data = parsed;
if (data.output?.url && !data.url) {
data.url = data.output.url;
}
}
} catch {
// 尝试正则提取
const idMatch = rawData.message.match(/"id"\s*:\s*"([^"]+)"/);
const statusMatch = rawData.message.match(/"status"\s*:\s*"([^"]+)"/);
const progressMatch = rawData.message.match(/"progress"\s*:\s*(\d+)/);
const urlMatch = rawData.message.match(/"url"\s*:\s*"(https?:\/\/[^"]+)"/);
if (!urlMatch) {
// 尝试匹配截断的 URL
const truncatedUrlMatch = rawData.message.match(/"url"\s*:\s*"(https?:\/\/[^"]+)/);
if (truncatedUrlMatch) {
data = {
id: idMatch?.[1] || videoId,
status: statusMatch?.[1] || 'processing',
progress: progressMatch ? parseInt(progressMatch[1]) : 0,
url: truncatedUrlMatch[1],
};
}
} else if (idMatch) {
data = {
id: idMatch[1],
status: statusMatch?.[1] || 'processing',
progress: progressMatch ? parseInt(progressMatch[1]) : 0,
url: urlMatch?.[1],
};
}
}
}
if (!response.ok && !data?.id) {
const errorMessage = data?.error?.message || rawData?.message || '查询视频状态失败';
const rawSnippet = (() => {
try {
return JSON.stringify(rawData).substring(0, 200);
} catch {
return String(rawData).substring(0, 200);
}
})();
logError('[Sora API v5] Get status failed', { status: response.status, error: errorMessage, body: rawSnippet });
throw new Error(errorMessage);
}
// 确保 progress 有默认值
if (typeof data.progress !== 'number') {
data.progress = 0;
}
// 处理 output.url 格式
if (data.output?.url && !data.url) {
data.url = data.output.url;
}
return data as VideoTaskResponse;
}
// 获取视频内容 URL(通过 /content 端点,跟随 302 重定向)
export async function getVideoContentUrl(videoId: string, channelId?: string): Promise<string> {
const { apiKey, baseUrl } = await getSoraConfig({ channelId });
if (!apiKey) {
throw new Error('Sora API Key 未配置');
}
const normalizedBaseUrl = baseUrl.replace(/\/$/, '');
const apiUrl = `${normalizedBaseUrl}/v1/videos/${videoId}/content`;
logDebug('[Sora API v5] Fetch video content:', apiUrl);
// 使用 redirect: 'manual' 来捕获 302 重定向的 Location
const requestInit: UndiciRequestInit = {
method: 'GET',
headers: {
Authorization: `Bearer ${apiKey}`,
},
redirect: 'manual',
dispatcher: soraAgent,
};
const response = await fetchWithRetry(undiciFetch, apiUrl, () => requestInit);
logDebug('[Sora API v5] /content status:', response.status);
// 如果是重定向(301, 302, 307, 308),返回 Location header 中的实际视频 URL
if ([301, 302, 307, 308].includes(response.status)) {
const location = response.headers.get('location');
logDebug('[Sora API v5] /content redirect location:', location?.substring(0, 100));
if (location) {
const rawUrl = parseVideoUrl(location);
return await applyVideoProxy(rawUrl);
}
}
// 如果是 200,可能直接返回了视频内容或 JSON
if (response.status === 200) {
const contentType = response.headers.get('content-type') || '';
// 如果是 JSON,尝试解析获取 URL
if (contentType.includes('application/json')) {
const data = await response.json() as any;
logDebug('[Sora API v5] /content JSON response:', JSON.stringify(data).substring(0, 200));
if (data?.url) {
const rawUrl = parseVideoUrl(data.url);
return await applyVideoProxy(rawUrl);
}
}
}
// 如果是错误响应
if (response.status >= 400) {
const data = await response.json().catch(() => ({})) as any;
const errorMessage = data?.error?.message || `获取视频内容失败: ${response.status}`;
logError('[Sora API v5] /content error response', {
status: response.status,
error: errorMessage,
body: JSON.stringify(data).substring(0, 200),
});
throw new Error(errorMessage);
}
// 兜底:返回 content URL(不推荐,因为需要认证)
logError('[Sora API v5] /content missing redirect; cannot resolve public URL');
throw new Error('无法获取视频直链');
}
// 轮询等待视频完成
async function pollVideoCompletion(
videoId: string,
onProgress?: (progress: number, status: string) => void,
channelId?: string
): Promise<VideoTaskResponse> {
let lastProgress = -1;
let stallCount = 0;
let failedCount = 0;
let consecutiveStatusErrors = 0;
const failedRetryDelayMs = 5000;
const retryableFailedPatterns = ['stale in_progress timeout', 'stale in progress timeout'];
const isRetryableFailedError = (message?: string | null): boolean => {
if (!message) return false;
const lower = message.toLowerCase();
return retryableFailedPatterns.some(pattern => lower.includes(pattern));
};
while (true) {
let status: VideoTaskResponse;
try {
status = await getVideoStatus(videoId, channelId);
consecutiveStatusErrors = 0;
} catch (error) {
if (!isTransientError(error)) {
throw error;
}
consecutiveStatusErrors += 1;
const retryDelayMs = Math.min(5000 * 2 ** (consecutiveStatusErrors - 1), 60000);
logWarn(
`[Sora API v5] Status fetch transient error (${consecutiveStatusErrors}), retrying after ${retryDelayMs}ms`,
error
);
await new Promise(resolve => setTimeout(resolve, retryDelayMs));
continue;
}
if (onProgress) {
onProgress(status.progress, status.status);
}
logDebug(
`[Sora API v5] Video status: ${status.status}, progress: ${status.progress}%, hasUrl: ${!!status.url || !!status.output?.url}`
);
// 统一处理 output.url 格式
if (status.output?.url && !status.url) {
status.url = status.output.url;
}
// 成功状态 (兼容 new-api-main)
if (isCompletedStatus(status.status)) {
// 如果没有 URL,尝试通过 /content 端点获取
if (!status.url) {
try {
logDebug('[Sora API v5] Completed without URL, trying /content');
const contentUrl = await getVideoContentUrl(videoId, channelId);
status.url = contentUrl;
} catch (e) {
logWarn('[Sora API v5] /content fetch failed', e);
}
}
return status;
}
if (status.status === 'failed') {
failedCount += 1;
const errorMessage = status.error?.message || '视频生成失败';
if (!isRetryableFailedError(status.error?.message)) {
logError('[Sora API v5] Video status failed', { videoId, error: errorMessage });
throw new Error(errorMessage);
}
logWarn(
`[Sora API v5] Status failed (${failedCount}), retrying after ${failedRetryDelayMs}ms: ${errorMessage}`
);
await new Promise(resolve => setTimeout(resolve, failedRetryDelayMs));
continue;
} else {
failedCount = 0;
}
// 检测停滞
if (status.progress === lastProgress) {
stallCount++;
} else {
stallCount = 0;
lastProgress = status.progress;
}
// 自适应等待
const interval = getPollingInterval(status.progress, stallCount);
await new Promise(resolve => setTimeout(resolve, interval));
}
}
export async function generateVideo(
request: VideoGenerationRequest,
onProgress?: (progress: number, status: string) => void,
options?: { channelId?: string }
): Promise<VideoGenerationResult> {
const { apiKey, baseUrl, channelId, channelType } = await getSoraConfig({
channelId: options?.channelId,
mode: options?.channelId ? 'default' : 'round-robin',
});
const upstreamRequest = shouldUseApexerVideoContract(channelType)
? normalizeApexerVideoRequest(request)
: request;
if (!apiKey) {
throw new Error('Sora API Key 未配置,请在管理后台「视频渠道」中配置 Sora 渠道');
}
if (!baseUrl) {
throw new Error('Sora Base URL 未配置');
}
const normalizedBaseUrl = baseUrl.replace(/\/$/, '');
const apiUrl = `${normalizedBaseUrl}/v1/videos`;
logInfo('[Sora API] Video generation request:', {
apiUrl,
model: upstreamRequest.model,
prompt: upstreamRequest.prompt?.substring(0, 50),
seconds: upstreamRequest.seconds,
size: upstreamRequest.size,
hasInputImage: !!upstreamRequest.input_image,
});
const buildFormData = () => {
const formData = new FormData();
const prompt = upstreamRequest.prompt || 'Generate video';
formData.append('prompt', prompt);
if (upstreamRequest.model) formData.append('model', upstreamRequest.model);
if (upstreamRequest.seconds) formData.append('seconds', upstreamRequest.seconds);
if (upstreamRequest.size) formData.append('size', upstreamRequest.size);
if (upstreamRequest.orientation) formData.append('orientation', upstreamRequest.orientation);
if (upstreamRequest.style_id) formData.append('style_id', upstreamRequest.style_id);
if (upstreamRequest.remix_target_id) formData.append('remix_target_id', upstreamRequest.remix_target_id);
if (upstreamRequest.input_image) {
const imageBuffer = Buffer.from(upstreamRequest.input_image, 'base64');
const imageBlob = new Blob([imageBuffer], { type: 'image/jpeg' });
formData.append('input_reference', imageBlob, 'input.jpg');
}
return formData;
};
const response = await fetchWithRetry(undiciFetch, apiUrl, () => ({
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
},
body: buildFormData(),
dispatcher: soraAgent,
}));
const rawData = await response.json() as any;
// 版本标记 v4 - 改进 NewAPI 格式解析
logDebug('[Sora API v4] Raw response:', JSON.stringify(rawData));
// 处理 NewAPI 包装格式:{code: "...", message: "{json string}", data: null}
let data = rawData;
if (rawData?.code && rawData?.message && typeof rawData.message === 'string') {
try {
// 尝试解析 message 字段中的 JSON
const parsed = JSON.parse(rawData.message);
if (parsed?.id) {
logDebug('[Sora API v5] Detected NewAPI format, parsed message payload');
// 处理 output.url 格式
if (parsed.output?.url && !parsed.url) {
parsed.url = parsed.output.url;
}
data = parsed;
}
} catch (parseError) {
logDebug('[Sora API v5] Message JSON parse failed:', parseError);
// 尝试用正则提取关键字段
try {
const idMatch = rawData.message.match(/"id"\s*:\s*"([^"]+)"/);
const statusMatch = rawData.message.match(/"status"\s*:\s*"([^"]+)"/);
// 匹配 URL - 支持截断的情况(URL 可能没有闭合引号)
// 先尝试匹配完整 URL,再尝试匹配截断的
let urlMatch = rawData.message.match(/"url"\s*:\s*"(https?:\/\/[^"]+)"/);
if (!urlMatch) {
// 匹配截断的 URL(到字符串末尾)
urlMatch = rawData.message.match(/"url"\s*:\s*"(https?:\/\/[^"]+)/);
}
if (idMatch) {
logDebug('[Sora API v5] Regex fallback parsed fields, urlFound:', !!urlMatch);
data = {
id: idMatch[1],
status: statusMatch ? statusMatch[1] : undefined,
url: urlMatch ? urlMatch[1] : undefined,
};
}
} catch (regexError) {
logDebug('[Sora API v5] Regex fallback failed:', regexError);
}
}
}
logDebug('[Sora API v5] Parsed payload:', {
hasId: !!data?.id,
taskStatus: data?.status,
taskId: data?.id,
progress: data?.progress,
hasUrl: !!data?.url || !!data?.output?.url,
url: (data?.url || data?.output?.url)?.substring(0, 80),
});
// 统一处理 output.url 格式
if (data?.output?.url && !data?.url) {
data.url = data.output.url;
}
// 确保 progress 有默认值
if (data && typeof data.progress !== 'number') {
data.progress = 0;
}
// 检查是否是错误响应(NewAPI 格式的真正错误)
if (!response.ok && !data?.id) {
const errorMessage = data?.error?.message || rawData?.message || data?.error || '视频生成失败';
logError('[Sora API v5] Video generation failed:', errorMessage);
throw new Error(errorMessage);
}
// 检查是否是新格式响应(有 id 和 status 字段,或者有 id 和 url 字段)
if (data?.id && (data?.status || data?.url)) {
const taskResponse = data as VideoTaskResponse;
// 如果已经成功(有 url 或状态为完成)
const isCompleted = isCompletedStatus(taskResponse.status);
if (taskResponse.url || isCompleted) {
if (taskResponse.url) {
const videoUrl = await applyVideoProxy(parseVideoUrl(taskResponse.url));
logInfo('[Sora API v5] Video generation completed:', videoUrl?.substring(0, 80));
return {
id: taskResponse.id,
object: taskResponse.object || 'video',
created: taskResponse.created_at || Date.now(),
model: taskResponse.model || '',
data: [{
url: videoUrl,
permalink: taskResponse.permalink || (taskResponse.metadata as any)?.permalink,
revised_prompt: taskResponse.revised_prompt,
}],
channelId,
};
}
// 状态是完成但没有 URL,尝试轮询获取
if (isCompleted && !taskResponse.url) {
logWarn('[Sora API v5] Completed without URL, retrying via polling...');
}
}
// 如果失败,抛出错误
if (taskResponse.status === 'failed') {
logError('[Sora API v5] Video task failed', {
taskId: taskResponse.id,
error: taskResponse.error?.message || '视频生成失败',
});
throw new Error(taskResponse.error?.message || '视频生成失败');
}
// 如果还在处理中或需要获取 URL,轮询等待
if (isInProgressStatus(taskResponse.status) || (taskResponse.id && !taskResponse.url)) {
logInfo('[Sora API v5] Polling task status...', taskResponse.id);
const finalStatus = await pollVideoCompletion(taskResponse.id, onProgress, channelId);
if (!finalStatus.url) {
logError('[Sora API v5] Video completed without URL', { taskId: finalStatus.id });
throw new Error('视频生成完成但未返回 URL');
}
const videoUrl = await applyVideoProxy(parseVideoUrl(finalStatus.url));
return {
id: finalStatus.id,
object: finalStatus.object || 'video',
created: finalStatus.created_at || Date.now(),
model: finalStatus.model || '',
data: [{
url: videoUrl,
permalink: finalStatus.permalink || (finalStatus.metadata as any)?.permalink,
revised_prompt: finalStatus.revised_prompt,
}],
channelId,
};
}
}
// 旧格式响应(直接返回 data 数组)
if (data?.data && Array.isArray(data.data) && data.data.length > 0 && data.data[0]?.url) {
logInfo('[Sora API] Video generation completed (legacy):', data.data[0].url);
const legacy = data as VideoGenerationResponse;
return { ...legacy, channelId };
}
// 未知格式,抛出错误
logError('[Sora API] Unknown response format:', JSON.stringify(data).substring(0, 200));
throw new Error('视频生成失败:API 返回了未知格式的响应');
}
// 异步创建视频任务(立即返回任务ID)
export async function createVideoTask(request: VideoGenerationRequest): Promise<VideoTaskResponse> {
const { apiKey, baseUrl, channelType } = await getSoraConfig();
const upstreamRequest = shouldUseApexerVideoContract(channelType)
? normalizeApexerVideoRequest(request)
: request;
if (!apiKey) {
throw new Error('Sora API Key 未配置');
}
const normalizedBaseUrl = baseUrl.replace(/\/$/, '');
const apiUrl = `${normalizedBaseUrl}/v1/videos`;
const buildFormData = () => {
const formData = new FormData();
formData.append('prompt', upstreamRequest.prompt || 'Generate video');
formData.append('async_mode', 'true');
if (upstreamRequest.model) formData.append('model', upstreamRequest.model);
if (upstreamRequest.seconds) formData.append('seconds', upstreamRequest.seconds);
if (upstreamRequest.size) formData.append('size', upstreamRequest.size);
if (upstreamRequest.orientation) formData.append('orientation', upstreamRequest.orientation);
if (upstreamRequest.style_id) formData.append('style_id', upstreamRequest.style_id);
if (upstreamRequest.remix_target_id) formData.append('remix_target_id', upstreamRequest.remix_target_id);
if (upstreamRequest.input_image) {
const imageBuffer = Buffer.from(upstreamRequest.input_image, 'base64');
const imageBlob = new Blob([imageBuffer], { type: 'image/jpeg' });
formData.append('input_reference', imageBlob, 'input.jpg');
}
return formData;
};
const response = await fetchWithRetry(undiciFetch, apiUrl, () => ({
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
},
body: buildFormData(),
dispatcher: soraAgent,
}));
const data = await response.json() as any;
6BCE
if (!response.ok) {
throw new Error(data?.error?.message || '创建视频任务失败');
}
return data as VideoTaskResponse;
}
// ========================================
// Video Remix API (new-api compatible)
// POST /v1/videos/{video_id}/remix
// ========================================
export async function remixVideo(
videoId: string,
request: VideoRemixRequest,
onProgress?: (progress: number, status: string) => void
): Promise<VideoGenerationResponse> {
const { apiKey, baseUrl, channelType } = await getSoraConfig();
if (!apiKey) {
throw new Error('Sora API Key 未配置');
}
if (!baseUrl) {
throw new Error('Sora Base URL 未配置');
}
const normalizedBaseUrl = baseUrl.replace(/\/$/, '');
const usesApexerContract = shouldUseApexerVideoContract(channelType);
const upstreamRequest = usesApexerContract
? normalizeApexerVideoRequest({ ...request, remix_target_id: videoId })
: request;
const apiUrl = usesApexerContract
? `${normalizedBaseUrl}/v1/videos`
: `${normalizedBaseUrl}/v1/videos/${encodeURIComponent(videoId)}/remix`;
logInfo('[Sora API] Remix request:', {
apiUrl,
videoId,
prompt: upstreamRequest.prompt?.substring(0, 50),
model: upstreamRequest.model,
});
const response = await fetchWithRetry(undiciFetch, apiUrl, () => ({
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
prompt: upstreamRequest.prompt,
model: upstreamRequest.model,
seconds: upstreamRequest.seconds,
size: upstreamRequest.size,
orientation: upstreamRequest.orientation,
style_id: upstreamRequest.style_id,
remix_target_id: upstreamRequest.remix_target_id,
async_mode: upstreamRequest.async_mode ?? true,
}),
dispatcher: soraAgent,
}));