jimeng-cli 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-2IIK4X7C.js +10228 -0
- package/dist/chunk-2IIK4X7C.js.map +1 -0
- package/dist/cli/index.cjs +6420 -580
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +406 -5
- package/dist/cli/index.js.map +1 -1
- package/dist/mcp/index.cjs +6056 -513
- package/dist/mcp/index.cjs.map +1 -1
- package/dist/mcp/index.js +111 -1
- package/dist/mcp/index.js.map +1 -1
- package/package.json +11 -16
- package/dist/chunk-JZY62VNI.js +0 -4762
- package/dist/chunk-JZY62VNI.js.map +0 -1
package/dist/chunk-JZY62VNI.js
DELETED
|
@@ -1,4762 +0,0 @@
|
|
|
1
|
-
// src/lib/environment.ts
|
|
2
|
-
import path from "path";
|
|
3
|
-
import fs from "fs-extra";
|
|
4
|
-
import minimist from "minimist";
|
|
5
|
-
import _ from "lodash";
|
|
6
|
-
var cmdArgs = minimist(process.argv.slice(2));
|
|
7
|
-
var envVars = process.env;
|
|
8
|
-
var Environment = class {
|
|
9
|
-
/** 命令行参数 */
|
|
10
|
-
cmdArgs;
|
|
11
|
-
/** 环境变量 */
|
|
12
|
-
envVars;
|
|
13
|
-
/** 环境名称 */
|
|
14
|
-
env;
|
|
15
|
-
/** 服务名称 */
|
|
16
|
-
name;
|
|
17
|
-
/** 服务地址 */
|
|
18
|
-
host;
|
|
19
|
-
/** 服务端口 */
|
|
20
|
-
port;
|
|
21
|
-
/** 包参数 */
|
|
22
|
-
package;
|
|
23
|
-
constructor(options = {}) {
|
|
24
|
-
const { cmdArgs: cmdArgs2, envVars: envVars2, package: _package } = options;
|
|
25
|
-
this.cmdArgs = cmdArgs2;
|
|
26
|
-
this.envVars = envVars2;
|
|
27
|
-
this.env = _.defaultTo(cmdArgs2.env || envVars2.SERVER_ENV, "dev");
|
|
28
|
-
this.name = cmdArgs2.name || envVars2.SERVER_NAME || void 0;
|
|
29
|
-
this.host = cmdArgs2.host || envVars2.SERVER_HOST || void 0;
|
|
30
|
-
this.port = Number(cmdArgs2.port || envVars2.SERVER_PORT) ? Number(cmdArgs2.port || envVars2.SERVER_PORT) : void 0;
|
|
31
|
-
this.package = _package;
|
|
32
|
-
}
|
|
33
|
-
};
|
|
34
|
-
var environment_default = new Environment({
|
|
35
|
-
cmdArgs,
|
|
36
|
-
envVars,
|
|
37
|
-
package: JSON.parse(fs.readFileSync(path.join(path.resolve(), "package.json")).toString())
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
// src/lib/configs/service-config.ts
|
|
41
|
-
import path3 from "path";
|
|
42
|
-
import fs3 from "fs-extra";
|
|
43
|
-
import yaml from "yaml";
|
|
44
|
-
import _3 from "lodash";
|
|
45
|
-
|
|
46
|
-
// src/lib/util.ts
|
|
47
|
-
import os from "os";
|
|
48
|
-
import path2 from "path";
|
|
49
|
-
import crypto from "crypto";
|
|
50
|
-
import { Readable, Writable } from "stream";
|
|
51
|
-
import "colors";
|
|
52
|
-
import mime from "mime";
|
|
53
|
-
import axios from "axios";
|
|
54
|
-
import fs2 from "fs-extra";
|
|
55
|
-
import { v4 as uuid } from "uuid";
|
|
56
|
-
import { format as dateFormat } from "date-fns";
|
|
57
|
-
import CRC32 from "crc-32";
|
|
58
|
-
import randomstring from "randomstring";
|
|
59
|
-
import _2 from "lodash";
|
|
60
|
-
import { CronJob } from "cron";
|
|
61
|
-
|
|
62
|
-
// src/lib/http-status-codes.ts
|
|
63
|
-
var http_status_codes_default = {
|
|
64
|
-
CONTINUE: 100,
|
|
65
|
-
//客户端应当继续发送请求。这个临时响应是用来通知客户端它的部分请求已经被服务器接收,且仍未被拒绝。客户端应当继续发送请求的剩余部分,或者如果请求已经完成,忽略这个响应。服务器必须在请求完成后向客户端发送一个最终响应
|
|
66
|
-
SWITCHING_PROTOCOLS: 101,
|
|
67
|
-
//服务器已经理解了客户端的请求,并将通过Upgrade 消息头通知客户端采用不同的协议来完成这个请求。在发送完这个响应最后的空行后,服务器将会切换到在Upgrade 消息头中定义的那些协议。只有在切换新的协议更有好处的时候才应该采取类似措施。例如,切换到新的HTTP 版本比旧版本更有优势,或者切换到一个实时且同步的协议以传送利用此类特性的资源
|
|
68
|
-
PROCESSING: 102,
|
|
69
|
-
//处理将被继续执行
|
|
70
|
-
OK: 200,
|
|
71
|
-
//请求已成功,请求所希望的响应头或数据体将随此响应返回
|
|
72
|
-
CREATED: 201,
|
|
73
|
-
//请求已经被实现,而且有一个新的资源已经依据请求的需要而建立,且其 URI 已经随Location 头信息返回。假如需要的资源无法及时建立的话,应当返回 '202 Accepted'
|
|
74
|
-
ACCEPTED: 202,
|
|
75
|
-
//服务器已接受请求,但尚未处理。正如它可能被拒绝一样,最终该请求可能会也可能不会被执行。在异步操作的场合下,没有比发送这个状态码更方便的做法了。返回202状态码的响应的目的是允许服务器接受其他过程的请求(例如某个每天只执行一次的基于批处理的操作),而不必让客户端一直保持与服务器的连接直到批处理操作全部完成。在接受请求处理并返回202状态码的响应应当在返回的实体中包含一些指示处理当前状态的信息,以及指向处理状态监视器或状态预测的指针,以便用户能够估计操作是否已经完成
|
|
76
|
-
NON_AUTHORITATIVE_INFO: 203,
|
|
77
|
-
//服务器已成功处理了请求,但返回的实体头部元信息不是在原始服务器上有效的确定集合,而是来自本地或者第三方的拷贝。当前的信息可能是原始版本的子集或者超集。例如,包含资源的元数据可能导致原始服务器知道元信息的超级。使用此状态码不是必须的,而且只有在响应不使用此状态码便会返回200 OK的情况下才是合适的
|
|
78
|
-
NO_CONTENT: 204,
|
|
79
|
-
//服务器成功处理了请求,但不需要返回任何实体内容,并且希望返回更新了的元信息。响应可能通过实体头部的形式,返回新的或更新后的元信息。如果存在这些头部信息,则应当与所请求的变量相呼应。如果客户端是浏览器的话,那么用户浏览器应保留发送了该请求的页面,而不产生任何文档视图上的变化,即使按照规范新的或更新后的元信息应当被应用到用户浏览器活动视图中的文档。由于204响应被禁止包含任何消息体,因此它始终以消息头后的第一个空行结尾
|
|
80
|
-
RESET_CONTENT: 205,
|
|
81
|
-
//服务器成功处理了请求,且没有返回任何内容。但是与204响应不同,返回此状态码的响应要求请求者重置文档视图。该响应主要是被用于接受用户输入后,立即重置表单,以便用户能够轻松地开始另一次输入。与204响应一样,该响应也被禁止包含任何消息体,且以消息头后的第一个空行结束
|
|
82
|
-
PARTIAL_CONTENT: 206,
|
|
83
|
-
//服务器已经成功处理了部分 GET 请求。类似于FlashGet或者迅雷这类的HTTP下载工具都是使用此类响应实现断点续传或者将一个大文档分解为多个下载段同时下载。该请求必须包含 Range 头信息来指示客户端希望得到的内容范围,并且可能包含 If-Range 来作为请求条件。响应必须包含如下的头部域:Content-Range 用以指示本次响应中返回的内容的范围;如果是Content-Type为multipart/byteranges的多段下载,则每一段multipart中都应包含Content-Range域用以指示本段的内容范围。假如响应中包含Content-Length,那么它的数值必须匹配它返回的内容范围的真实字节数。Date和ETag或Content-Location,假如同样的请求本应该返回200响应。Expires, Cache-Control,和/或 Vary,假如其值可能与之前相同变量的其他响应对应的值不同的话。假如本响应请求使用了 If-Range 强缓存验证,那么本次响应不应该包含其他实体头;假如本响应的请求使用了 If-Range 弱缓存验证,那么本次响应禁止包含其他实体头;这避免了缓存的实体内容和更新了的实体头信息之间的不一致。否则,本响应就应当包含所有本应该返回200响应中应当返回的所有实体头部域。假如 ETag 或 Latest-Modified 头部不能精确匹配的话,则客户端缓存应禁止将206响应返回的内容与之前任何缓存过的内容组合在一起。任何不支持 Range 以及 Content-Range 头的缓存都禁止缓存206响应返回的内容
|
|
84
|
-
MULTIPLE_STATUS: 207,
|
|
85
|
-
//代表之后的消息体将是一个XML消息,并且可能依照之前子请求数量的不同,包含一系列独立的响应代码
|
|
86
|
-
MULTIPLE_CHOICES: 300,
|
|
87
|
-
//被请求的资源有一系列可供选择的回馈信息,每个都有自己特定的地址和浏览器驱动的商议信息。用户或浏览器能够自行选择一个首选的地址进行重定向。除非这是一个HEAD请求,否则该响应应当包括一个资源特性及地址的列表的实体,以便用户或浏览器从中选择最合适的重定向地址。这个实体的格式由Content-Type定义的格式所决定。浏览器可能根据响应的格式以及浏览器自身能力,自动作出最合适的选择。当然,RFC 2616规范并没有规定这样的自动选择该如何进行。如果服务器本身已经有了首选的回馈选择,那么在Location中应当指明这个回馈的 URI;浏览器可能会将这个 Location 值作为自动重定向的地址。此外,除非额外指定,否则这个响应也是可缓存的
|
|
88
|
-
MOVED_PERMANENTLY: 301,
|
|
89
|
-
//被请求的资源已永久移动到新位置,并且将来任何对此资源的引用都应该使用本响应返回的若干个URI之一。如果可能,拥有链接编辑功能的客户端应当自动把请求的地址修改为从服务器反馈回来的地址。除非额外指定,否则这个响应也是可缓存的。新的永久性的URI应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。如果这不是一个GET或者HEAD请求,因此浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化。注意:对于某些使用 HTTP/1.0 协议的浏览器,当它们发送的POST请求得到了一个301响应的话,接下来的重定向请求将会变成GET方式
|
|
90
|
-
FOUND: 302,
|
|
91
|
-
//请求的资源现在临时从不同的URI响应请求。由于这样的重定向是临时的,客户端应当继续向原有地址发送以后的请求。只有在Cache-Control或Expires中进行了指定的情况下,这个响应才是可缓存的。新的临时性的URI应当在响应的 Location 域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。如果这不是一个GET或者HEAD请求,那么浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化。注意:虽然RFC 1945和RFC 2068规范不允许客户端在重定向时改变请求的方法,但是很多现存的浏览器将302响应视作为303响应,并且使用GET方式访问在Location中规定的URI,而无视原先请求的方法。状态码303和307被添加了进来,用以明确服务器期待客户端进行何种反应
|
|
92
|
-
SEE_OTHER: 303,
|
|
93
|
-
//对应当前请求的响应可以在另一个URI上被找到,而且客户端应当采用 GET 的方式访问那个资源。这个方法的存在主要是为了允许由脚本激活的POST请求输出重定向到一个新的资源。这个新的 URI 不是原始资源的替代引用。同时,303响应禁止被缓存。当然,第二个请求(重定向)可能被缓存。新的 URI 应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。注意:许多 HTTP/1.1 版以前的浏览器不能正确理解303状态。如果需要考虑与这些浏览器之间的互动,302状态码应该可以胜任,因为大多数的浏览器处理302响应时的方式恰恰就是上述规范要求客户端处理303响应时应当做的
|
|
94
|
-
NOT_MODIFIED: 304,
|
|
95
|
-
//如果客户端发送了一个带条件的GET请求且该请求已被允许,而文档的内容(自上次访问以来或者根据请求的条件)并没有改变,则服务器应当返回这个状态码。304响应禁止包含消息体,因此始终以消息头后的第一个空行结尾。该响应必须包含以下的头信息:Date,除非这个服务器没有时钟。假如没有时钟的服务器也遵守这些规则,那么代理服务器以及客户端可以自行将Date字段添加到接收到的响应头中去(正如RFC 2068中规定的一样),缓存机制将会正常工作。ETag或 Content-Location,假如同样的请求本应返回200响应。Expires, Cache-Control,和/或Vary,假如其值可能与之前相同变量的其他响应对应的值不同的话。假如本响应请求使用了强缓存验证,那么本次响应不应该包含其他实体头;否则(例如,某个带条件的 GET 请求使用了弱缓存验证),本次响应禁止包含其他实体头;这避免了缓存了的实体内容和更新了的实体头信息之间的不一致。假如某个304响应指明了当前某个实体没有缓存,那么缓存系统必须忽视这个响应,并且重复发送不包含限制条件的请求。假如接收到一个要求更新某个缓存条目的304响应,那么缓存系统必须更新整个条目以反映所有在响应中被更新的字段的值
|
|
96
|
-
USE_PROXY: 305,
|
|
97
|
-
//被请求的资源必须通过指定的代理才能被访问。Location域中将给出指定的代理所在的URI信息,接收者需要重复发送一个单独的请求,通过这个代理才能访问相应资源。只有原始服务器才能建立305响应。注意:RFC 2068中没有明确305响应是为了重定向一个单独的请求,而且只能被原始服务器建立。忽视这些限制可能导致严重的安全后果
|
|
98
|
-
UNUSED: 306,
|
|
99
|
-
//在最新版的规范中,306状态码已经不再被使用
|
|
100
|
-
TEMPORARY_REDIRECT: 307,
|
|
101
|
-
//请求的资源现在临时从不同的URI 响应请求。由于这样的重定向是临时的,客户端应当继续向原有地址发送以后的请求。只有在Cache-Control或Expires中进行了指定的情况下,这个响应才是可缓存的。新的临时性的URI 应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI 的超链接及简短说明。因为部分浏览器不能识别307响应,因此需要添加上述必要信息以便用户能够理解并向新的 URI 发出访问请求。如果这不是一个GET或者HEAD请求,那么浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化
|
|
102
|
-
BAD_REQUEST: 400,
|
|
103
|
-
//1.语义有误,当前请求无法被服务器理解。除非进行修改,否则客户端不应该重复提交这个请求 2.请求参数有误
|
|
104
|
-
UNAUTHORIZED: 401,
|
|
105
|
-
//当前请求需要用户验证。该响应必须包含一个适用于被请求资源的 WWW-Authenticate 信息头用以询问用户信息。客户端可以重复提交一个包含恰当的 Authorization 头信息的请求。如果当前请求已经包含了 Authorization 证书,那么401响应代表着服务器验证已经拒绝了那些证书。如果401响应包含了与前一个响应相同的身份验证询问,且浏览器已经至少尝试了一次验证,那么浏览器应当向用户展示响应中包含的实体信息,因为这个实体信息中可能包含了相关诊断信息。参见RFC 2617
|
|
106
|
-
PAYMENT_REQUIRED: 402,
|
|
107
|
-
//该状态码是为了将来可能的需求而预留的
|
|
108
|
-
FORBIDDEN: 403,
|
|
109
|
-
//服务器已经理解请求,但是拒绝执行它。与401响应不同的是,身份验证并不能提供任何帮助,而且这个请求也不应该被重复提交。如果这不是一个HEAD请求,而且服务器希望能够讲清楚为何请求不能被执行,那么就应该在实体内描述拒绝的原因。当然服务器也可以返回一个404响应,假如它不希望让客户端获得任何信息
|
|
110
|
-
NOT_FOUND: 404,
|
|
111
|
-
//请求失败,请求所希望得到的资源未被在服务器上发现。没有信息能够告诉用户这个状况到底是暂时的还是永久的。假如服务器知道情况的话,应当使用410状态码来告知旧资源因为某些内部的配置机制问题,已经永久的不可用,而且没有任何可以跳转的地址。404这个状态码被广泛应用于当服务器不想揭示到底为何请求被拒绝或者没有其他适合的响应可用的情况下
|
|
112
|
-
METHOD_NOT_ALLOWED: 405,
|
|
113
|
-
//请求行中指定的请求方法不能被用于请求相应的资源。该响应必须返回一个Allow 头信息用以表示出当前资源能够接受的请求方法的列表。鉴于PUT,DELETE方法会对服务器上的资源进行写操作,因而绝大部分的网页服务器都不支持或者在默认配置下不允许上述请求方法,对于此类请求均会返回405错误
|
|
114
|
-
NO_ACCEPTABLE: 406,
|
|
115
|
-
//请求的资源的内容特性无法满足请求头中的条件,因而无法生成响应实体。除非这是一个 HEAD 请求,否则该响应就应当返回一个包含可以让用户或者浏览器从中选择最合适的实体特性以及地址列表的实体。实体的格式由Content-Type头中定义的媒体类型决定。浏览器可以根据格式及自身能力自行作出最佳选择。但是,规范中并没有定义任何作出此类自动选择的标准
|
|
116
|
-
PROXY_AUTHENTICATION_REQUIRED: 407,
|
|
117
|
-
//与401响应类似,只不过客户端必须在代理服务器上进行身份验证。代理服务器必须返回一个Proxy-Authenticate用以进行身份询问。客户端可以返回一个Proxy-Authorization信息头用以验证。参见RFC 2617
|
|
118
|
-
REQUEST_TIMEOUT: 408,
|
|
119
|
-
//请求超时。客户端没有在服务器预备等待的时间内完成一个请求的发送。客户端可以随时再次提交这一请求而无需进行任何更改
|
|
120
|
-
CONFLICT: 409,
|
|
121
|
-
//由于和被请求的资源的当前状态之间存在冲突,请求无法完成。这个代码只允许用在这样的情况下才能被使用:用户被认为能够解决冲突,并且会重新提交新的请求。该响应应当包含足够的信息以便用户发现冲突的源头。冲突通常发生于对PUT请求的处理中。例如,在采用版本检查的环境下,某次PUT提交的对特定资源的修改请求所附带的版本信息与之前的某个(第三方)请求向冲突,那么此时服务器就应该返回一个409错误,告知用户请求无法完成。此时,响应实体中很可能会包含两个冲突版本之间的差异比较,以便用户重新提交归并以后的新版本
|
|
122
|
-
GONE: 410,
|
|
123
|
-
//被请求的资源在服务器上已经不再可用,而且没有任何已知的转发地址。这样的状况应当被认为是永久性的。如果可能,拥有链接编辑功能的客户端应当在获得用户许可后删除所有指向这个地址的引用。如果服务器不知道或者无法确定这个状况是否是永久的,那么就应该使用404状态码。除非额外说明,否则这个响应是可缓存的。410响应的目的主要是帮助网站管理员维护网站,通知用户该资源已经不再可用,并且服务器拥有者希望所有指向这个资源的远端连接也被删除。这类事件在限时、增值服务中很普遍。同样,410响应也被用于通知客户端在当前服务器站点上,原本属于某个个人的资源已经不再可用。当然,是否需要把所有永久不可用的资源标记为'410 Gone',以及是否需要保持此标记多长时间,完全取决于服务器拥有者
|
|
124
|
-
LENGTH_REQUIRED: 411,
|
|
125
|
-
//服务器拒绝在没有定义Content-Length头的情况下接受请求。在添加了表明请求消息体长度的有效Content-Length头之后,客户端可以再次提交该请求
|
|
126
|
-
PRECONDITION_FAILED: 412,
|
|
127
|
-
//服务器在验证在请求的头字段中给出先决条件时,没能满足其中的一个或多个。这个状态码允许客户端在获取资源时在请求的元信息(请求头字段数据)中设置先决条件,以此避免该请求方法被应用到其希望的内容以外的资源上
|
|
128
|
-
REQUEST_ENTITY_TOO_LARGE: 413,
|
|
129
|
-
//服务器拒绝处理当前请求,因为该请求提交的实体数据大小超过了服务器愿意或者能够处理的范围。此种情况下,服务器可以关闭连接以免客户端继续发送此请求。如果这个状况是临时的,服务器应当返回一个 Retry-After 的响应头,以告知客户端可以在多少时间以后重新尝试
|
|
130
|
-
REQUEST_URI_TOO_LONG: 414,
|
|
131
|
-
//请求的URI长度超过了服务器能够解释的长度,因此服务器拒绝对该请求提供服务。这比较少见,通常的情况包括:本应使用POST方法的表单提交变成了GET方法,导致查询字符串(Query String)过长。重定向URI “黑洞”,例如每次重定向把旧的URI作为新的URI的一部分,导致在若干次重定向后URI超长。客户端正在尝试利用某些服务器中存在的安全漏洞攻击服务器。这类服务器使用固定长度的缓冲读取或操作请求的URI,当GET后的参数超过某个数值后,可能会产生缓冲区溢出,导致任意代码被执行[1]。没有此类漏洞的服务器,应当返回414状态码
|
|
132
|
-
UNSUPPORTED_MEDIA_TYPE: 415,
|
|
133
|
-
//对于当前请求的方法和所请求的资源,请求中提交的实体并不是服务器中所支持的格式,因此请求被拒绝
|
|
134
|
-
REQUESTED_RANGE_NOT_SATISFIABLE: 416,
|
|
135
|
-
//如果请求中包含了Range请求头,并且Range中指定的任何数据范围都与当前资源的可用范围不重合,同时请求中又没有定义If-Range请求头,那么服务器就应当返回416状态码。假如Range使用的是字节范围,那么这种情况就是指请求指定的所有数据范围的首字节位置都超过了当前资源的长度。服务器也应当在返回416状态码的同时,包含一个Content-Range实体头,用以指明当前资源的长度。这个响应也被禁止使用multipart/byteranges作为其 Content-Type
|
|
136
|
-
EXPECTION_FAILED: 417,
|
|
137
|
-
//在请求头Expect中指定的预期内容无法被服务器满足,或者这个服务器是一个代理服务器,它有明显的证据证明在当前路由的下一个节点上,Expect的内容无法被满足
|
|
138
|
-
TOO_MANY_CONNECTIONS: 421,
|
|
139
|
-
//从当前客户端所在的IP地址到服务器的连接数超过了服务器许可的最大范围。通常,这里的IP地址指的是从服务器上看到的客户端地址(比如用户的网关或者代理服务器地址)。在这种情况下,连接数的计算可能涉及到不止一个终端用户
|
|
140
|
-
UNPROCESSABLE_ENTITY: 422,
|
|
141
|
-
//请求格式正确,但是由于含有语义错误,无法响应
|
|
142
|
-
FAILED_DEPENDENCY: 424,
|
|
143
|
-
//由于之前的某个请求发生的错误,导致当前请求失败,例如PROPPATCH
|
|
144
|
-
UNORDERED_COLLECTION: 425,
|
|
145
|
-
//在WebDav Advanced Collections 草案中定义,但是未出现在《WebDAV 顺序集协议》(RFC 3658)中
|
|
146
|
-
UPGRADE_REQUIRED: 426,
|
|
147
|
-
//客户端应当切换到TLS/1.0
|
|
148
|
-
RETRY_WITH: 449,
|
|
149
|
-
//由微软扩展,代表请求应当在执行完适当的操作后进行重试
|
|
150
|
-
INTERNAL_SERVER_ERROR: 500,
|
|
151
|
-
//服务器遇到了一个未曾预料的状况,导致了它无法完成对请求的处理。一般来说,这个问题都会在服务器的程序码出错时出现
|
|
152
|
-
NOT_IMPLEMENTED: 501,
|
|
153
|
-
//服务器不支持当前请求所需要的某个功能。当服务器无法识别请求的方法,并且无法支持其对任何资源的请求
|
|
154
|
-
BAD_GATEWAY: 502,
|
|
155
|
-
//作为网关或者代理工作的服务器尝试执行请求时,从上游服务器接收到无效的响应
|
|
156
|
-
SERVICE_UNAVAILABLE: 503,
|
|
157
|
-
//由于临时的服务器维护或者过载,服务器当前无法处理请求。这个状况是临时的,并且将在一段时间以后恢复。如果能够预计延迟时间,那么响应中可以包含一个 Retry-After 头用以标明这个延迟时间。如果没有给出这个 Retry-After 信息,那么客户端应当以处理500响应的方式处理它。注意:503状态码的存在并不意味着服务器在过载的时候必须使用它。某些服务器只不过是希望拒绝客户端的连接
|
|
158
|
-
GATEWAY_TIMEOUT: 504,
|
|
159
|
-
//作为网关或者代理工作的服务器尝试执行请求时,未能及时从上游服务器(URI标识出的服务器,例如HTTP、FTP、LDAP)或者辅助服务器(例如DNS)收到响应。注意:某些代理服务器在DNS查询超时时会返回400或者500错误
|
|
160
|
-
HTTP_VERSION_NOT_SUPPORTED: 505,
|
|
161
|
-
//服务器不支持,或者拒绝支持在请求中使用的HTTP版本。这暗示着服务器不能或不愿使用与客户端相同的版本。响应中应当包含一个描述了为何版本不被支持以及服务器支持哪些协议的实体
|
|
162
|
-
VARIANT_ALSO_NEGOTIATES: 506,
|
|
163
|
-
//服务器存在内部配置错误:被请求的协商变元资源被配置为在透明内容协商中使用自己,因此在一个协商处理中不是一个合适的重点
|
|
164
|
-
INSUFFICIENT_STORAGE: 507,
|
|
165
|
-
//服务器无法存储完成请求所必须的内容。这个状况被认为是临时的
|
|
166
|
-
BANDWIDTH_LIMIT_EXCEEDED: 509,
|
|
167
|
-
//服务器达到带宽限制。这不是一个官方的状态码,但是仍被广泛使用
|
|
168
|
-
NOT_EXTENDED: 510
|
|
169
|
-
//获取资源所需要的策略并没有没满足
|
|
170
|
-
};
|
|
171
|
-
|
|
172
|
-
// src/lib/util.ts
|
|
173
|
-
var autoIdMap = /* @__PURE__ */ new Map();
|
|
174
|
-
var util = {
|
|
175
|
-
is2DArrays(value) {
|
|
176
|
-
return _2.isArray(value) && (!value[0] || _2.isArray(value[0]) && _2.isArray(value[value.length - 1]));
|
|
177
|
-
},
|
|
178
|
-
uuid: (separator = true) => separator ? uuid() : uuid().replace(/\-/g, ""),
|
|
179
|
-
autoId: (prefix = "") => {
|
|
180
|
-
let index = autoIdMap.get(prefix);
|
|
181
|
-
if (index > 999999) index = 0;
|
|
182
|
-
autoIdMap.set(prefix, (index || 0) + 1);
|
|
183
|
-
return `${prefix}${index || 1}`;
|
|
184
|
-
},
|
|
185
|
-
ignoreJSONParse(value) {
|
|
186
|
-
const result = _2.attempt(() => JSON.parse(value));
|
|
187
|
-
if (_2.isError(result)) return null;
|
|
188
|
-
return result;
|
|
189
|
-
},
|
|
190
|
-
generateRandomString(options) {
|
|
191
|
-
return randomstring.generate(options);
|
|
192
|
-
},
|
|
193
|
-
getResponseContentType(value) {
|
|
194
|
-
return value.headers ? value.headers["content-type"] || value.headers["Content-Type"] : null;
|
|
195
|
-
},
|
|
196
|
-
mimeToExtension(value) {
|
|
197
|
-
let extension = mime.getExtension(value);
|
|
198
|
-
if (extension == "mpga") return "mp3";
|
|
199
|
-
return extension;
|
|
200
|
-
},
|
|
201
|
-
extractURLExtension(value) {
|
|
202
|
-
const extname = path2.extname(new URL(value).pathname);
|
|
203
|
-
return extname.substring(1).toLowerCase();
|
|
204
|
-
},
|
|
205
|
-
createCronJob(cronPatterns, callback) {
|
|
206
|
-
if (!_2.isFunction(callback))
|
|
207
|
-
throw new Error("callback must be an Function");
|
|
208
|
-
return new CronJob(
|
|
209
|
-
cronPatterns,
|
|
210
|
-
() => callback(),
|
|
211
|
-
null,
|
|
212
|
-
false,
|
|
213
|
-
"Asia/Shanghai"
|
|
214
|
-
);
|
|
215
|
-
},
|
|
216
|
-
getDateString(format = "yyyy-MM-dd", date = /* @__PURE__ */ new Date()) {
|
|
217
|
-
return dateFormat(date, format);
|
|
218
|
-
},
|
|
219
|
-
getIPAddressesByIPv4() {
|
|
220
|
-
const interfaces = os.networkInterfaces();
|
|
221
|
-
const addresses = [];
|
|
222
|
-
for (let name in interfaces) {
|
|
223
|
-
const networks = interfaces[name];
|
|
224
|
-
const results = networks.filter(
|
|
225
|
-
(network) => network.family === "IPv4" && network.address !== "127.0.0.1" && !network.internal
|
|
226
|
-
);
|
|
227
|
-
if (results[0] && results[0].address) addresses.push(results[0].address);
|
|
228
|
-
}
|
|
229
|
-
return addresses;
|
|
230
|
-
},
|
|
231
|
-
getMACAddressesByIPv4() {
|
|
232
|
-
const interfaces = os.networkInterfaces();
|
|
233
|
-
const addresses = [];
|
|
234
|
-
for (let name in interfaces) {
|
|
235
|
-
const networks = interfaces[name];
|
|
236
|
-
const results = networks.filter(
|
|
237
|
-
(network) => network.family === "IPv4" && network.address !== "127.0.0.1" && !network.internal
|
|
238
|
-
);
|
|
239
|
-
if (results[0] && results[0].mac) addresses.push(results[0].mac);
|
|
240
|
-
}
|
|
241
|
-
return addresses;
|
|
242
|
-
},
|
|
243
|
-
generateSSEData(event, data, retry) {
|
|
244
|
-
return `event: ${event || "message"}
|
|
245
|
-
data: ${(data || "").replace(/\n/g, "\\n").replace(/\s/g, "\\s")}
|
|
246
|
-
retry: ${retry || 3e3}
|
|
247
|
-
|
|
248
|
-
`;
|
|
249
|
-
},
|
|
250
|
-
buildDataBASE64(type, ext, buffer) {
|
|
251
|
-
return `data:${type}/${ext.replace("jpg", "jpeg")};base64,${buffer.toString(
|
|
252
|
-
"base64"
|
|
253
|
-
)}`;
|
|
254
|
-
},
|
|
255
|
-
isLinux() {
|
|
256
|
-
return os.platform() !== "win32";
|
|
257
|
-
},
|
|
258
|
-
isIPAddress(value) {
|
|
259
|
-
return _2.isString(value) && (/^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/.test(
|
|
260
|
-
value
|
|
261
|
-
) || /\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*/.test(
|
|
262
|
-
value
|
|
263
|
-
));
|
|
264
|
-
},
|
|
265
|
-
isPort(value) {
|
|
266
|
-
return _2.isNumber(value) && value > 0 && value < 65536;
|
|
267
|
-
},
|
|
268
|
-
isReadStream(value) {
|
|
269
|
-
return value && (value instanceof Readable || "readable" in value || value.readable);
|
|
270
|
-
},
|
|
271
|
-
isWriteStream(value) {
|
|
272
|
-
return value && (value instanceof Writable || "writable" in value || value.writable);
|
|
273
|
-
},
|
|
274
|
-
isHttpStatusCode(value) {
|
|
275
|
-
return _2.isNumber(value) && Object.values(http_status_codes_default).includes(value);
|
|
276
|
-
},
|
|
277
|
-
isURL(value) {
|
|
278
|
-
return !_2.isUndefined(value) && /^(http|https)/.test(value);
|
|
279
|
-
},
|
|
280
|
-
isSrc(value) {
|
|
281
|
-
return !_2.isUndefined(value) && /^\/.+\.[0-9a-zA-Z]+(\?.+)?$/.test(value);
|
|
282
|
-
},
|
|
283
|
-
isBASE64(value) {
|
|
284
|
-
return !_2.isUndefined(value) && /^[a-zA-Z0-9\/\+]+(=?)+$/.test(value);
|
|
285
|
-
},
|
|
286
|
-
isBASE64Data(value) {
|
|
287
|
-
return /^data:/.test(value);
|
|
288
|
-
},
|
|
289
|
-
extractBASE64DataFormat(value) {
|
|
290
|
-
const match = value.trim().match(/^data:(.+);base64,/);
|
|
291
|
-
if (!match) return null;
|
|
292
|
-
return match[1];
|
|
293
|
-
},
|
|
294
|
-
removeBASE64DataHeader(value) {
|
|
295
|
-
return value.replace(/^data:(.+);base64,/, "");
|
|
296
|
-
},
|
|
297
|
-
isDataString(value) {
|
|
298
|
-
return /^(base64|json):/.test(value);
|
|
299
|
-
},
|
|
300
|
-
isStringNumber(value) {
|
|
301
|
-
return _2.isFinite(Number(value));
|
|
302
|
-
},
|
|
303
|
-
isUnixTimestamp(value) {
|
|
304
|
-
return /^[0-9]{10}$/.test(`${value}`);
|
|
305
|
-
},
|
|
306
|
-
isTimestamp(value) {
|
|
307
|
-
return /^[0-9]{13}$/.test(`${value}`);
|
|
308
|
-
},
|
|
309
|
-
isEmail(value) {
|
|
310
|
-
return /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(
|
|
311
|
-
value
|
|
312
|
-
);
|
|
313
|
-
},
|
|
314
|
-
isAsyncFunction(value) {
|
|
315
|
-
return Object.prototype.toString.call(value) === "[object AsyncFunction]";
|
|
316
|
-
},
|
|
317
|
-
async isAPNG(filePath) {
|
|
318
|
-
let head;
|
|
319
|
-
const readStream = fs2.createReadStream(filePath, { start: 37, end: 40 });
|
|
320
|
-
const readPromise = new Promise((resolve, reject) => {
|
|
321
|
-
readStream.once("end", resolve);
|
|
322
|
-
readStream.once("error", reject);
|
|
323
|
-
});
|
|
324
|
-
readStream.once("data", (data) => head = data);
|
|
325
|
-
await readPromise;
|
|
326
|
-
return head.compare(Buffer.from([97, 99, 84, 76])) === 0;
|
|
327
|
-
},
|
|
328
|
-
unixTimestamp() {
|
|
329
|
-
return parseInt(`${Date.now() / 1e3}`);
|
|
330
|
-
},
|
|
331
|
-
timestamp() {
|
|
332
|
-
return Date.now();
|
|
333
|
-
},
|
|
334
|
-
urlJoin(...values) {
|
|
335
|
-
let url = "";
|
|
336
|
-
for (let i = 0; i < values.length; i++)
|
|
337
|
-
url += `${i > 0 ? "/" : ""}${values[i].replace(/^\/*/, "").replace(/\/*$/, "")}`;
|
|
338
|
-
return url;
|
|
339
|
-
},
|
|
340
|
-
millisecondsToHmss(milliseconds) {
|
|
341
|
-
if (_2.isString(milliseconds)) return milliseconds;
|
|
342
|
-
milliseconds = parseInt(milliseconds);
|
|
343
|
-
const sec = Math.floor(milliseconds / 1e3);
|
|
344
|
-
const hours = Math.floor(sec / 3600);
|
|
345
|
-
const minutes = Math.floor((sec - hours * 3600) / 60);
|
|
346
|
-
const seconds = sec - hours * 3600 - minutes * 60;
|
|
347
|
-
const ms = milliseconds % 6e4 - seconds * 1e3;
|
|
348
|
-
return `${hours > 9 ? hours : "0" + hours}:${minutes > 9 ? minutes : "0" + minutes}:${seconds > 9 ? seconds : "0" + seconds}.${ms}`;
|
|
349
|
-
},
|
|
350
|
-
millisecondsToTimeString(milliseconds) {
|
|
351
|
-
if (milliseconds < 1e3) return `${milliseconds}ms`;
|
|
352
|
-
if (milliseconds < 6e4)
|
|
353
|
-
return `${parseFloat((milliseconds / 1e3).toFixed(2))}s`;
|
|
354
|
-
return `${Math.floor(milliseconds / 1e3 / 60)}m${Math.floor(
|
|
355
|
-
milliseconds / 1e3 % 60
|
|
356
|
-
)}s`;
|
|
357
|
-
},
|
|
358
|
-
rgbToHex(r, g, b) {
|
|
359
|
-
return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
|
|
360
|
-
},
|
|
361
|
-
hexToRgb(hex) {
|
|
362
|
-
const value = parseInt(hex.replace(/^#/, ""), 16);
|
|
363
|
-
return [value >> 16 & 255, value >> 8 & 255, value & 255];
|
|
364
|
-
},
|
|
365
|
-
md5(value) {
|
|
366
|
-
return crypto.createHash("md5").update(value).digest("hex");
|
|
367
|
-
},
|
|
368
|
-
crc32(value) {
|
|
369
|
-
return _2.isBuffer(value) ? CRC32.buf(value) : CRC32.str(value);
|
|
370
|
-
},
|
|
371
|
-
arrayParse(value) {
|
|
372
|
-
return _2.isArray(value) ? value : [value];
|
|
373
|
-
},
|
|
374
|
-
booleanParse(value) {
|
|
375
|
-
return value === "true" || value === true ? true : false;
|
|
376
|
-
},
|
|
377
|
-
encodeBASE64(value) {
|
|
378
|
-
return Buffer.from(value).toString("base64");
|
|
379
|
-
},
|
|
380
|
-
decodeBASE64(value) {
|
|
381
|
-
return Buffer.from(value, "base64").toString();
|
|
382
|
-
},
|
|
383
|
-
async fetchFileBASE64(url) {
|
|
384
|
-
const result = await axios.get(url, {
|
|
385
|
-
responseType: "arraybuffer"
|
|
386
|
-
});
|
|
387
|
-
return result.data.toString("base64");
|
|
388
|
-
},
|
|
389
|
-
/**
|
|
390
|
-
* 计算 ArrayBuffer 的 CRC32 值
|
|
391
|
-
* @param buffer ArrayBuffer 数据
|
|
392
|
-
* @returns CRC32 十六进制字符串
|
|
393
|
-
*/
|
|
394
|
-
calculateCRC32(buffer) {
|
|
395
|
-
const crcTable = [];
|
|
396
|
-
for (let i = 0; i < 256; i++) {
|
|
397
|
-
let crc2 = i;
|
|
398
|
-
for (let j = 0; j < 8; j++) {
|
|
399
|
-
crc2 = crc2 & 1 ? 3988292384 ^ crc2 >>> 1 : crc2 >>> 1;
|
|
400
|
-
}
|
|
401
|
-
crcTable[i] = crc2;
|
|
402
|
-
}
|
|
403
|
-
let crc = 0 ^ -1;
|
|
404
|
-
const bytes = buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
405
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
406
|
-
crc = crc >>> 8 ^ crcTable[(crc ^ bytes[i]) & 255];
|
|
407
|
-
}
|
|
408
|
-
return ((crc ^ -1) >>> 0).toString(16).padStart(8, "0");
|
|
409
|
-
}
|
|
410
|
-
};
|
|
411
|
-
var util_default = util;
|
|
412
|
-
|
|
413
|
-
// src/lib/configs/service-config.ts
|
|
414
|
-
var CONFIG_PATH = path3.join(path3.resolve(), "configs/", environment_default.env, "/service.yml");
|
|
415
|
-
var ServiceConfig = class _ServiceConfig {
|
|
416
|
-
/** 服务名称 */
|
|
417
|
-
name;
|
|
418
|
-
/** @type {string} 服务绑定主机地址 */
|
|
419
|
-
host;
|
|
420
|
-
/** @type {number} 服务绑定端口 */
|
|
421
|
-
port;
|
|
422
|
-
/** @type {string} 服务路由前缀 */
|
|
423
|
-
urlPrefix;
|
|
424
|
-
/** @type {string} 服务绑定地址(外部访问地址) */
|
|
425
|
-
bindAddress;
|
|
426
|
-
constructor(options) {
|
|
427
|
-
const { name, host, port, urlPrefix, bindAddress } = options || {};
|
|
428
|
-
this.name = _3.defaultTo(name, "jimeng-cli");
|
|
429
|
-
this.host = _3.defaultTo(host, "0.0.0.0");
|
|
430
|
-
this.port = _3.defaultTo(port, 5566);
|
|
431
|
-
this.urlPrefix = _3.defaultTo(urlPrefix, "");
|
|
432
|
-
this.bindAddress = bindAddress;
|
|
433
|
-
}
|
|
434
|
-
get addressHost() {
|
|
435
|
-
if (this.bindAddress) return this.bindAddress;
|
|
436
|
-
const ipAddresses = util_default.getIPAddressesByIPv4();
|
|
437
|
-
for (let ipAddress of ipAddresses) {
|
|
438
|
-
if (ipAddress === this.host)
|
|
439
|
-
return ipAddress;
|
|
440
|
-
}
|
|
441
|
-
return ipAddresses[0] || "127.0.0.1";
|
|
442
|
-
}
|
|
443
|
-
get address() {
|
|
444
|
-
return `${this.addressHost}:${this.port}`;
|
|
445
|
-
}
|
|
446
|
-
get pageDirUrl() {
|
|
447
|
-
return `http://127.0.0.1:${this.port}/page`;
|
|
448
|
-
}
|
|
449
|
-
static load() {
|
|
450
|
-
const external = _3.pickBy(environment_default, (v, k) => ["name", "host", "port"].includes(k) && !_3.isUndefined(v));
|
|
451
|
-
if (!fs3.pathExistsSync(CONFIG_PATH)) return new _ServiceConfig(external);
|
|
452
|
-
const data = yaml.parse(fs3.readFileSync(CONFIG_PATH).toString());
|
|
453
|
-
return new _ServiceConfig({ ...data, ...external });
|
|
454
|
-
}
|
|
455
|
-
};
|
|
456
|
-
var service_config_default = ServiceConfig.load();
|
|
457
|
-
|
|
458
|
-
// src/lib/configs/system-config.ts
|
|
459
|
-
import path4 from "path";
|
|
460
|
-
import fs4 from "fs-extra";
|
|
461
|
-
import yaml2 from "yaml";
|
|
462
|
-
import _4 from "lodash";
|
|
463
|
-
var CONFIG_PATH2 = path4.join(path4.resolve(), "configs/", environment_default.env, "/system.yml");
|
|
464
|
-
var SystemConfig = class _SystemConfig {
|
|
465
|
-
/** 是否开启请求日志 */
|
|
466
|
-
requestLog;
|
|
467
|
-
/** 临时目录路径 */
|
|
468
|
-
tmpDir;
|
|
469
|
-
/** 日志目录路径 */
|
|
470
|
-
logDir;
|
|
471
|
-
/** 日志写入间隔(毫秒) */
|
|
472
|
-
logWriteInterval;
|
|
473
|
-
/** 日志文件有效期(毫秒) */
|
|
474
|
-
logFileExpires;
|
|
475
|
-
/** 临时文件有效期(毫秒) */
|
|
476
|
-
tmpFileExpires;
|
|
477
|
-
/** 请求体配置 */
|
|
478
|
-
requestBody;
|
|
479
|
-
/** 是否调试模式 */
|
|
480
|
-
debug;
|
|
481
|
-
/** 日志级别 */
|
|
482
|
-
log_level;
|
|
483
|
-
constructor(options) {
|
|
484
|
-
const { requestLog, tmpDir, logDir, logWriteInterval, logFileExpires, tmpFileExpires, requestBody, debug, log_level } = options || {};
|
|
485
|
-
this.requestLog = _4.defaultTo(requestLog, false);
|
|
486
|
-
this.tmpDir = _4.defaultTo(tmpDir, "./tmp");
|
|
487
|
-
this.logDir = _4.defaultTo(logDir, "./logs");
|
|
488
|
-
this.logWriteInterval = _4.defaultTo(logWriteInterval, 200);
|
|
489
|
-
this.logFileExpires = _4.defaultTo(logFileExpires, 262656e4);
|
|
490
|
-
this.tmpFileExpires = _4.defaultTo(tmpFileExpires, 864e5);
|
|
491
|
-
this.requestBody = Object.assign(requestBody || {}, {
|
|
492
|
-
enableTypes: ["form", "text", "xml"],
|
|
493
|
-
// 移除 json,由自定义中间件处理
|
|
494
|
-
encoding: "utf-8",
|
|
495
|
-
formLimit: "100mb",
|
|
496
|
-
jsonLimit: "100mb",
|
|
497
|
-
textLimit: "100mb",
|
|
498
|
-
xmlLimit: "100mb",
|
|
499
|
-
formidable: {
|
|
500
|
-
maxFileSize: "100mb"
|
|
501
|
-
},
|
|
502
|
-
multipart: true,
|
|
503
|
-
parsedMethods: ["POST", "PUT", "PATCH"]
|
|
504
|
-
});
|
|
505
|
-
this.debug = _4.defaultTo(debug, true);
|
|
506
|
-
this.log_level = _4.defaultTo(log_level, "info");
|
|
507
|
-
}
|
|
508
|
-
get rootDirPath() {
|
|
509
|
-
return path4.resolve();
|
|
510
|
-
}
|
|
511
|
-
get tmpDirPath() {
|
|
512
|
-
return path4.resolve(this.tmpDir);
|
|
513
|
-
}
|
|
514
|
-
get logDirPath() {
|
|
515
|
-
return path4.resolve(this.logDir);
|
|
516
|
-
}
|
|
517
|
-
static load() {
|
|
518
|
-
if (!fs4.pathExistsSync(CONFIG_PATH2)) return new _SystemConfig();
|
|
519
|
-
const data = yaml2.parse(fs4.readFileSync(CONFIG_PATH2).toString());
|
|
520
|
-
return new _SystemConfig(data);
|
|
521
|
-
}
|
|
522
|
-
};
|
|
523
|
-
var system_config_default = SystemConfig.load();
|
|
524
|
-
|
|
525
|
-
// src/lib/config.ts
|
|
526
|
-
var Config = class {
|
|
527
|
-
/** 服务配置 */
|
|
528
|
-
service = service_config_default;
|
|
529
|
-
/** 系统配置 */
|
|
530
|
-
system = system_config_default;
|
|
531
|
-
};
|
|
532
|
-
var config_default = new Config();
|
|
533
|
-
|
|
534
|
-
// src/lib/logger.ts
|
|
535
|
-
import path5 from "path";
|
|
536
|
-
import _util from "util";
|
|
537
|
-
import "colors";
|
|
538
|
-
import _5 from "lodash";
|
|
539
|
-
import fs5 from "fs-extra";
|
|
540
|
-
import { format as dateFormat2 } from "date-fns";
|
|
541
|
-
var isVercelEnv = process.env.VERCEL;
|
|
542
|
-
var isCliSilentLogs = () => process.env.JIMENG_CLI_SILENT_LOGS === "true";
|
|
543
|
-
var LogWriter = class {
|
|
544
|
-
#buffers = [];
|
|
545
|
-
#timer = null;
|
|
546
|
-
constructor() {
|
|
547
|
-
!isVercelEnv && fs5.ensureDirSync(config_default.system.logDirPath);
|
|
548
|
-
!isVercelEnv && this.work();
|
|
549
|
-
}
|
|
550
|
-
push(content) {
|
|
551
|
-
const buffer = Buffer.from(content);
|
|
552
|
-
this.#buffers.push(buffer);
|
|
553
|
-
}
|
|
554
|
-
writeSync(buffer) {
|
|
555
|
-
!isVercelEnv && fs5.appendFileSync(path5.join(config_default.system.logDirPath, `/${util_default.getDateString()}.log`), buffer);
|
|
556
|
-
}
|
|
557
|
-
async write(buffer) {
|
|
558
|
-
!isVercelEnv && await fs5.appendFile(path5.join(config_default.system.logDirPath, `/${util_default.getDateString()}.log`), buffer);
|
|
559
|
-
}
|
|
560
|
-
flush() {
|
|
561
|
-
if (!this.#buffers.length) return;
|
|
562
|
-
!isVercelEnv && fs5.appendFileSync(path5.join(config_default.system.logDirPath, `/${util_default.getDateString()}.log`), Buffer.concat(this.#buffers));
|
|
563
|
-
this.#buffers = [];
|
|
564
|
-
}
|
|
565
|
-
destroy() {
|
|
566
|
-
if (this.#timer) clearTimeout(this.#timer);
|
|
567
|
-
this.flush();
|
|
568
|
-
}
|
|
569
|
-
scheduleNext() {
|
|
570
|
-
this.#timer = setTimeout(this.work.bind(this), config_default.system.logWriteInterval);
|
|
571
|
-
if (this.#timer && typeof this.#timer.unref === "function") this.#timer.unref();
|
|
572
|
-
}
|
|
573
|
-
work() {
|
|
574
|
-
if (!this.#buffers.length) return this.scheduleNext();
|
|
575
|
-
const buffer = Buffer.concat(this.#buffers);
|
|
576
|
-
this.#buffers = [];
|
|
577
|
-
this.write(buffer).finally(() => this.scheduleNext()).catch((err) => console.error("Log write error:", err));
|
|
578
|
-
}
|
|
579
|
-
};
|
|
580
|
-
var LogText = class {
|
|
581
|
-
/** @type {string} 日志级别 */
|
|
582
|
-
level;
|
|
583
|
-
/** @type {string} 日志文本 */
|
|
584
|
-
text;
|
|
585
|
-
/** @type {string} 日志来源 */
|
|
586
|
-
source;
|
|
587
|
-
/** @type {Date} 日志发生时间 */
|
|
588
|
-
time = /* @__PURE__ */ new Date();
|
|
589
|
-
constructor(level, ...params) {
|
|
590
|
-
this.level = level;
|
|
591
|
-
this.text = _util.format.apply(null, params);
|
|
592
|
-
this.source = this.#getStackTopCodeInfo();
|
|
593
|
-
}
|
|
594
|
-
#getStackTopCodeInfo() {
|
|
595
|
-
const unknownInfo = { name: "unknown", codeLine: 0, codeColumn: 0 };
|
|
596
|
-
const stackArray = new Error().stack.split("\n");
|
|
597
|
-
const text = stackArray[4];
|
|
598
|
-
if (!text)
|
|
599
|
-
return unknownInfo;
|
|
600
|
-
const match = text.match(/at (.+) \((.+)\)/) || text.match(/at (.+)/);
|
|
601
|
-
if (!match || !_5.isString(match[2] || match[1]))
|
|
602
|
-
return unknownInfo;
|
|
603
|
-
const temp = match[2] || match[1];
|
|
604
|
-
const _match = temp.match(/([a-zA-Z0-9_\-\.]+)\:(\d+)\:(\d+)$/);
|
|
605
|
-
if (!_match)
|
|
606
|
-
return unknownInfo;
|
|
607
|
-
const [, scriptPath, codeLine, codeColumn] = _match;
|
|
608
|
-
return {
|
|
609
|
-
name: scriptPath ? scriptPath.replace(/.js$/, "") : "unknown",
|
|
610
|
-
path: scriptPath || null,
|
|
611
|
-
codeLine: parseInt(codeLine || 0),
|
|
612
|
-
codeColumn: parseInt(codeColumn || 0)
|
|
613
|
-
};
|
|
614
|
-
}
|
|
615
|
-
toString() {
|
|
616
|
-
return `[${dateFormat2(this.time, "yyyy-MM-dd HH:mm:ss.SSS")}][${this.level}][${this.source.name}<${this.source.codeLine},${this.source.codeColumn}>] ${this.text}`;
|
|
617
|
-
}
|
|
618
|
-
};
|
|
619
|
-
var Logger = class _Logger {
|
|
620
|
-
/** @type {Object} 系统配置 */
|
|
621
|
-
config = {};
|
|
622
|
-
/** @type {Object} 日志级别映射 */
|
|
623
|
-
static Level = {
|
|
624
|
-
Success: "success",
|
|
625
|
-
Info: "info",
|
|
626
|
-
Log: "log",
|
|
627
|
-
Debug: "debug",
|
|
628
|
-
Warning: "warning",
|
|
629
|
-
Error: "error",
|
|
630
|
-
Fatal: "fatal"
|
|
631
|
-
};
|
|
632
|
-
/** @type {Object} 日志级别文本颜色樱色 */
|
|
633
|
-
static LevelColor = {
|
|
634
|
-
[_Logger.Level.Success]: "green",
|
|
635
|
-
[_Logger.Level.Info]: "brightCyan",
|
|
636
|
-
[_Logger.Level.Debug]: "white",
|
|
637
|
-
[_Logger.Level.Warning]: "brightYellow",
|
|
638
|
-
[_Logger.Level.Error]: "brightRed",
|
|
639
|
-
[_Logger.Level.Fatal]: "red"
|
|
640
|
-
};
|
|
641
|
-
static LevelPriority = {
|
|
642
|
-
[_Logger.Level.Fatal]: 1,
|
|
643
|
-
[_Logger.Level.Error]: 2,
|
|
644
|
-
[_Logger.Level.Warning]: 3,
|
|
645
|
-
[_Logger.Level.Success]: 4,
|
|
646
|
-
[_Logger.Level.Info]: 5,
|
|
647
|
-
[_Logger.Level.Log]: 6,
|
|
648
|
-
[_Logger.Level.Debug]: 7
|
|
649
|
-
};
|
|
650
|
-
#writer;
|
|
651
|
-
constructor() {
|
|
652
|
-
this.#writer = new LogWriter();
|
|
653
|
-
}
|
|
654
|
-
header() {
|
|
655
|
-
this.#writer.writeSync(Buffer.from(`
|
|
656
|
-
|
|
657
|
-
===================== LOG START ${dateFormat2(/* @__PURE__ */ new Date(), "yyyy-MM-dd HH:mm:ss.SSS")} =====================
|
|
658
|
-
|
|
659
|
-
`));
|
|
660
|
-
}
|
|
661
|
-
footer() {
|
|
662
|
-
this.#writer.flush();
|
|
663
|
-
this.#writer.writeSync(Buffer.from(`
|
|
664
|
-
|
|
665
|
-
===================== LOG END ${dateFormat2(/* @__PURE__ */ new Date(), "yyyy-MM-dd HH:mm:ss.SSS")} =====================
|
|
666
|
-
|
|
667
|
-
`));
|
|
668
|
-
}
|
|
669
|
-
#emit(level, consoleMethod, params, options = {}) {
|
|
670
|
-
if (isCliSilentLogs()) return;
|
|
671
|
-
if (options.requireDebug && !config_default.system.debug) return;
|
|
672
|
-
if (!this.#checkLevel(level)) return;
|
|
673
|
-
const content = new LogText(level, ...params).toString();
|
|
674
|
-
consoleMethod(content[_Logger.LevelColor[level]]);
|
|
675
|
-
this.#writer.push(options.trailingNewline === false ? content : content + "\n");
|
|
676
|
-
}
|
|
677
|
-
#checkLevel(level) {
|
|
678
|
-
const currentLevelPriority = _Logger.LevelPriority[config_default.system.log_level] || 99;
|
|
679
|
-
const levelPriority = _Logger.LevelPriority[level];
|
|
680
|
-
return levelPriority <= currentLevelPriority;
|
|
681
|
-
}
|
|
682
|
-
success(...params) {
|
|
683
|
-
this.#emit(_Logger.Level.Success, console.info, params);
|
|
684
|
-
}
|
|
685
|
-
info(...params) {
|
|
686
|
-
this.#emit(_Logger.Level.Info, console.info, params);
|
|
687
|
-
}
|
|
688
|
-
debug(...params) {
|
|
689
|
-
this.#emit(_Logger.Level.Debug, console.debug, params, { requireDebug: true });
|
|
690
|
-
}
|
|
691
|
-
warn(...params) {
|
|
692
|
-
this.#emit(_Logger.Level.Warning, console.warn, params);
|
|
693
|
-
}
|
|
694
|
-
error(...params) {
|
|
695
|
-
this.#emit(_Logger.Level.Error, console.error, params, { trailingNewline: false });
|
|
696
|
-
}
|
|
697
|
-
destroy() {
|
|
698
|
-
this.#writer.destroy();
|
|
699
|
-
}
|
|
700
|
-
};
|
|
701
|
-
var logger_default = new Logger();
|
|
702
|
-
|
|
703
|
-
// src/api/controllers/core.ts
|
|
704
|
-
import net from "net";
|
|
705
|
-
import dns from "dns/promises";
|
|
706
|
-
import _7 from "lodash";
|
|
707
|
-
import mime2 from "mime";
|
|
708
|
-
import axios2 from "axios";
|
|
709
|
-
import { HttpsProxyAgent } from "https-proxy-agent";
|
|
710
|
-
import { SocksProxyAgent } from "socks-proxy-agent";
|
|
711
|
-
|
|
712
|
-
// src/lib/exceptions/Exception.ts
|
|
713
|
-
import assert from "assert";
|
|
714
|
-
import _6 from "lodash";
|
|
715
|
-
var Exception = class extends Error {
|
|
716
|
-
/** 错误码 */
|
|
717
|
-
errcode;
|
|
718
|
-
/** 错误消息 */
|
|
719
|
-
errmsg;
|
|
720
|
-
/** 数据 */
|
|
721
|
-
data;
|
|
722
|
-
/** HTTP状态码 */
|
|
723
|
-
httpStatusCode;
|
|
724
|
-
/**
|
|
725
|
-
* 构造异常
|
|
726
|
-
*
|
|
727
|
-
* @param exception 异常
|
|
728
|
-
* @param _errmsg 异常消息
|
|
729
|
-
*/
|
|
730
|
-
constructor(exception, _errmsg) {
|
|
731
|
-
assert(_6.isArray(exception), "Exception must be Array");
|
|
732
|
-
const [errcode, errmsg] = exception;
|
|
733
|
-
assert(_6.isFinite(errcode), "Exception errcode invalid");
|
|
734
|
-
assert(_6.isString(errmsg), "Exception errmsg invalid");
|
|
735
|
-
super(_errmsg || errmsg);
|
|
736
|
-
this.errcode = errcode;
|
|
737
|
-
this.errmsg = _errmsg || errmsg;
|
|
738
|
-
}
|
|
739
|
-
compare(exception) {
|
|
740
|
-
const [errcode] = exception;
|
|
741
|
-
return this.errcode == errcode;
|
|
742
|
-
}
|
|
743
|
-
setHTTPStatusCode(value) {
|
|
744
|
-
this.httpStatusCode = value;
|
|
745
|
-
return this;
|
|
746
|
-
}
|
|
747
|
-
setData(value) {
|
|
748
|
-
this.data = _6.defaultTo(value, null);
|
|
749
|
-
return this;
|
|
750
|
-
}
|
|
751
|
-
};
|
|
752
|
-
|
|
753
|
-
// src/lib/exceptions/APIException.ts
|
|
754
|
-
var APIException = class extends Exception {
|
|
755
|
-
/**
|
|
756
|
-
* 构造异常
|
|
757
|
-
*
|
|
758
|
-
* @param {[number, string]} exception 异常
|
|
759
|
-
*/
|
|
760
|
-
constructor(exception, errmsg) {
|
|
761
|
-
super(exception, errmsg);
|
|
762
|
-
}
|
|
763
|
-
};
|
|
764
|
-
|
|
765
|
-
// src/api/consts/exceptions.ts
|
|
766
|
-
var exceptions_default = {
|
|
767
|
-
API_TEST: [-9999, "API\u5F02\u5E38\u9519\u8BEF"],
|
|
768
|
-
API_REQUEST_PARAMS_INVALID: [-2e3, "\u8BF7\u6C42\u53C2\u6570\u975E\u6CD5"],
|
|
769
|
-
API_REQUEST_FAILED: [-2001, "\u8BF7\u6C42\u5931\u8D25"],
|
|
770
|
-
API_TOKEN_EXPIRES: [-2002, "Token\u5DF2\u5931\u6548"],
|
|
771
|
-
API_FILE_URL_INVALID: [-2003, "\u8FDC\u7A0B\u6587\u4EF6URL\u975E\u6CD5"],
|
|
772
|
-
API_FILE_EXECEEDS_SIZE: [-2004, "\u8FDC\u7A0B\u6587\u4EF6\u8D85\u51FA\u5927\u5C0F"],
|
|
773
|
-
API_CHAT_STREAM_PUSHING: [-2005, "\u5DF2\u6709\u5BF9\u8BDD\u6D41\u6B63\u5728\u8F93\u51FA"],
|
|
774
|
-
API_CONTENT_FILTERED: [-2006, "\u5185\u5BB9\u7531\u4E8E\u5408\u89C4\u95EE\u9898\u5DF2\u88AB\u963B\u6B62\u751F\u6210"],
|
|
775
|
-
API_IMAGE_GENERATION_FAILED: [-2007, "\u56FE\u50CF\u751F\u6210\u5931\u8D25"],
|
|
776
|
-
API_VIDEO_GENERATION_FAILED: [-2008, "\u89C6\u9891\u751F\u6210\u5931\u8D25"],
|
|
777
|
-
API_IMAGE_GENERATION_INSUFFICIENT_POINTS: [-2009, "\u5373\u68A6\u79EF\u5206\u4E0D\u8DB3"]
|
|
778
|
-
};
|
|
779
|
-
|
|
780
|
-
// src/lib/error-handler.ts
|
|
781
|
-
var JimengErrorHandler = class {
|
|
782
|
-
/**
|
|
783
|
-
* 处理即梦API响应错误
|
|
784
|
-
*/
|
|
785
|
-
static handleApiResponse(response, options = {}) {
|
|
786
|
-
const { ret, errmsg, historyId } = response;
|
|
787
|
-
const { context = "\u5373\u68A6API\u8BF7\u6C42", operation = "\u64CD\u4F5C" } = options;
|
|
788
|
-
logger_default.error(`${context}\u5931\u8D25: ret=${ret}, errmsg=${errmsg}${historyId ? `, historyId=${historyId}` : ""}`);
|
|
789
|
-
switch (ret) {
|
|
790
|
-
case "1015":
|
|
791
|
-
throw new APIException(exceptions_default.API_TOKEN_EXPIRES, `[\u767B\u5F55\u5931\u6548]: ${errmsg}\u3002\u8BF7\u91CD\u65B0\u83B7\u53D6refresh_token\u5E76\u66F4\u65B0\u914D\u7F6E`);
|
|
792
|
-
case "5000":
|
|
793
|
-
throw new APIException(
|
|
794
|
-
exceptions_default.API_IMAGE_GENERATION_INSUFFICIENT_POINTS,
|
|
795
|
-
`[\u79EF\u5206\u4E0D\u8DB3]: ${errmsg}\u3002\u5EFA\u8BAE\uFF1A1)\u5C1D\u8BD5\u4F7F\u75281024x1024\u5206\u8FA8\u7387\uFF0C2)\u68C0\u67E5\u662F\u5426\u9700\u8981\u8D2D\u4E70\u79EF\u5206\uFF0C3)\u786E\u8BA4\u8D26\u6237\u72B6\u6001\u6B63\u5E38`
|
|
796
|
-
);
|
|
797
|
-
case "4001":
|
|
798
|
-
throw new APIException(exceptions_default.API_CONTENT_FILTERED, `[\u5185\u5BB9\u8FDD\u89C4]: ${errmsg}`);
|
|
799
|
-
case "4002":
|
|
800
|
-
throw new APIException(exceptions_default.API_REQUEST_PARAMS_INVALID, `[\u53C2\u6570\u9519\u8BEF]: ${errmsg}`);
|
|
801
|
-
case "5001":
|
|
802
|
-
throw new APIException(exceptions_default.API_IMAGE_GENERATION_FAILED, `[\u751F\u6210\u5931\u8D25]: ${errmsg}`);
|
|
803
|
-
case "5002":
|
|
804
|
-
throw new APIException(exceptions_default.API_VIDEO_GENERATION_FAILED, `[\u89C6\u9891\u751F\u6210\u5931\u8D25]: ${errmsg}`);
|
|
805
|
-
default:
|
|
806
|
-
throw new APIException(exceptions_default.API_REQUEST_FAILED, `[${operation}\u5931\u8D25]: ${errmsg} (\u9519\u8BEF\u7801: ${ret})`);
|
|
807
|
-
}
|
|
808
|
-
}
|
|
809
|
-
/**
|
|
810
|
-
* 处理网络请求错误
|
|
811
|
-
*/
|
|
812
|
-
static handleNetworkError(error, options = {}) {
|
|
813
|
-
var _a, _b;
|
|
814
|
-
const { context = "\u7F51\u7EDC\u8BF7\u6C42", retryCount = 0, maxRetries = 3 } = options;
|
|
815
|
-
logger_default.error(`${context}\u7F51\u7EDC\u9519\u8BEF (\u5C1D\u8BD5 ${retryCount + 1}/${maxRetries + 1}): ${error.message}`);
|
|
816
|
-
if (error.code === "ECONNABORTED") {
|
|
817
|
-
throw new APIException(exceptions_default.API_REQUEST_FAILED, `[\u8BF7\u6C42\u8D85\u65F6]: ${context}\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`);
|
|
818
|
-
}
|
|
819
|
-
if (error.code === "ENOTFOUND") {
|
|
820
|
-
throw new APIException(exceptions_default.API_REQUEST_FAILED, `[\u7F51\u7EDC\u9519\u8BEF]: \u65E0\u6CD5\u8FDE\u63A5\u5230\u5373\u68A6\u670D\u52A1\u5668\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5`);
|
|
821
|
-
}
|
|
822
|
-
if (((_a = error.response) == null ? void 0 : _a.status) >= 500) {
|
|
823
|
-
throw new APIException(exceptions_default.API_REQUEST_FAILED, `[\u670D\u52A1\u5668\u9519\u8BEF]: \u5373\u68A6\u670D\u52A1\u5668\u6682\u65F6\u4E0D\u53EF\u7528 (${error.response.status})`);
|
|
824
|
-
}
|
|
825
|
-
if (((_b = error.response) == null ? void 0 : _b.status) === 429) {
|
|
826
|
-
throw new APIException(exceptions_default.API_REQUEST_FAILED, `[\u8BF7\u6C42\u9891\u7387\u9650\u5236]: \u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`);
|
|
827
|
-
}
|
|
828
|
-
throw new APIException(exceptions_default.API_REQUEST_FAILED, `[${context}\u5931\u8D25]: ${error.message}`);
|
|
829
|
-
}
|
|
830
|
-
/**
|
|
831
|
-
* 处理轮询超时错误
|
|
832
|
-
* @returns 如果有部分结果,返回 void 而不抛出异常
|
|
833
|
-
*/
|
|
834
|
-
static handlePollingTimeout(pollCount, maxPollCount, elapsedTime, status, itemCount, historyId) {
|
|
835
|
-
const message = `\u8F6E\u8BE2\u8D85\u65F6: \u5DF2\u8F6E\u8BE2 ${pollCount} \u6B21\uFF0C\u8017\u65F6 ${elapsedTime} \u79D2\uFF0C\u6700\u7EC8\u72B6\u6001: ${status}\uFF0C\u56FE\u7247\u6570\u91CF: ${itemCount}`;
|
|
836
|
-
logger_default.warn(message + (historyId ? `\uFF0C\u5386\u53F2ID: ${historyId}` : ""));
|
|
837
|
-
if (itemCount === 0) {
|
|
838
|
-
throw new APIException(
|
|
839
|
-
exceptions_default.API_IMAGE_GENERATION_FAILED,
|
|
840
|
-
`\u751F\u6210\u8D85\u65F6\u4E14\u65E0\u7ED3\u679C\uFF0C\u72B6\u6001\u7801: ${status}${historyId ? `\uFF0C\u5386\u53F2ID: ${historyId}` : ""}`
|
|
841
|
-
);
|
|
842
|
-
}
|
|
843
|
-
logger_default.info(`\u8F6E\u8BE2\u8D85\u65F6\u4F46\u5DF2\u83B7\u5F97 ${itemCount} \u5F20\u56FE\u7247\uFF0C\u5C06\u8FD4\u56DE\u73B0\u6709\u7ED3\u679C`);
|
|
844
|
-
}
|
|
845
|
-
/**
|
|
846
|
-
* 处理生成失败错误
|
|
847
|
-
* @param itemCount 已生成的结果数量,如果 > 0 则不抛出异常
|
|
848
|
-
* @returns 如果有部分结果,返回 false 表示不应抛出异常
|
|
849
|
-
*/
|
|
850
|
-
static handleGenerationFailure(status, failCode, historyId, type = "image", itemCount = 0) {
|
|
851
|
-
const typeText = type === "image" ? "\u56FE\u50CF" : "\u89C6\u9891";
|
|
852
|
-
const message = `${typeText}\u751F\u6210\u6700\u7EC8\u5931\u8D25: status=${status}, failCode=${failCode}${historyId ? `, historyId=${historyId}` : ""}, \u5DF2\u751F\u6210\u6570\u91CF=${itemCount}`;
|
|
853
|
-
if (itemCount > 0) {
|
|
854
|
-
logger_default.warn(message);
|
|
855
|
-
logger_default.info(`${typeText}\u751F\u6210\u90E8\u5206\u5931\u8D25\uFF0C\u4F46\u5DF2\u83B7\u5F97 ${itemCount} \u4E2A\u7ED3\u679C\uFF0C\u5C06\u8FD4\u56DE\u73B0\u6709\u7ED3\u679C`);
|
|
856
|
-
return false;
|
|
857
|
-
}
|
|
858
|
-
logger_default.error(message);
|
|
859
|
-
const exception = type === "image" ? exceptions_default.API_IMAGE_GENERATION_FAILED : exceptions_default.API_VIDEO_GENERATION_FAILED;
|
|
860
|
-
throw new APIException(exception, `${typeText}\u751F\u6210\u5931\u8D25\uFF0C\u72B6\u6001\u7801: ${status}${failCode ? `\uFF0C\u9519\u8BEF\u7801: ${failCode}` : ""}`);
|
|
861
|
-
}
|
|
862
|
-
/**
|
|
863
|
-
* 包装重试逻辑的错误处理
|
|
864
|
-
*/
|
|
865
|
-
static async withRetry(operation, options = {}) {
|
|
866
|
-
const {
|
|
867
|
-
maxRetries = 3,
|
|
868
|
-
retryDelay = 5e3,
|
|
869
|
-
context = "\u64CD\u4F5C",
|
|
870
|
-
operation: operationName = "\u8BF7\u6C42"
|
|
871
|
-
} = options;
|
|
872
|
-
let lastError;
|
|
873
|
-
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
874
|
-
try {
|
|
875
|
-
return await operation();
|
|
876
|
-
} catch (error) {
|
|
877
|
-
lastError = error;
|
|
878
|
-
if (error instanceof APIException) {
|
|
879
|
-
throw error;
|
|
880
|
-
}
|
|
881
|
-
if (attempt < maxRetries) {
|
|
882
|
-
logger_default.warn(`${context}\u5931\u8D25 (\u5C1D\u8BD5 ${attempt + 1}/${maxRetries + 1}): ${error.message}`);
|
|
883
|
-
logger_default.info(`${retryDelay / 1e3}\u79D2\u540E\u91CD\u8BD5...`);
|
|
884
|
-
await new Promise((resolve) => setTimeout(resolve, retryDelay));
|
|
885
|
-
}
|
|
886
|
-
}
|
|
887
|
-
}
|
|
888
|
-
this.handleNetworkError(lastError, {
|
|
889
|
-
context,
|
|
890
|
-
retryCount: maxRetries,
|
|
891
|
-
maxRetries,
|
|
892
|
-
operation: operationName
|
|
893
|
-
});
|
|
894
|
-
}
|
|
895
|
-
};
|
|
896
|
-
var handleJimengError = JimengErrorHandler.handleApiResponse;
|
|
897
|
-
var handleNetworkError = JimengErrorHandler.handleNetworkError;
|
|
898
|
-
var handlePollingTimeout = JimengErrorHandler.handlePollingTimeout;
|
|
899
|
-
var handleGenerationFailure = JimengErrorHandler.handleGenerationFailure;
|
|
900
|
-
var withRetry = JimengErrorHandler.withRetry;
|
|
901
|
-
|
|
902
|
-
// src/api/consts/dreamina.ts
|
|
903
|
-
var BASE_URL_DREAMINA_US = "https://dreamina-api.us.capcut.com";
|
|
904
|
-
var BASE_URL_IMAGEX_US = "https://imagex16-normal-us-ttp.capcutapi.us";
|
|
905
|
-
var BASE_URL_DREAMINA_HK = "https://mweb-api-sg.capcut.com";
|
|
906
|
-
var BASE_URL_IMAGEX_HK = "https://imagex-normal-sg.capcutapi.com";
|
|
907
|
-
var WEB_VERSION = "7.5.0";
|
|
908
|
-
var DA_VERSION = "3.3.8";
|
|
909
|
-
|
|
910
|
-
// src/api/consts/common.ts
|
|
911
|
-
var BASE_URL_CN = "https://jimeng.jianying.com";
|
|
912
|
-
var BASE_URL_US_COMMERCE = "https://commerce.us.capcut.com";
|
|
913
|
-
var BASE_URL_HK_COMMERCE = "https://commerce-api-sg.capcut.com";
|
|
914
|
-
var DEFAULT_ASSISTANT_ID_CN = 513695;
|
|
915
|
-
var DEFAULT_ASSISTANT_ID_US = 513641;
|
|
916
|
-
var DEFAULT_ASSISTANT_ID_HK = 513641;
|
|
917
|
-
var DEFAULT_ASSISTANT_ID_JP = 513641;
|
|
918
|
-
var DEFAULT_ASSISTANT_ID_SG = 513641;
|
|
919
|
-
var REGION_CN = "cn";
|
|
920
|
-
var REGION_US = "US";
|
|
921
|
-
var REGION_HK = "HK";
|
|
922
|
-
var REGION_JP = "JP";
|
|
923
|
-
var REGION_SG = "SG";
|
|
924
|
-
var PLATFORM_CODE = "7";
|
|
925
|
-
var VERSION_CODE = "8.4.0";
|
|
926
|
-
var DEFAULT_IMAGE_MODEL = "jimeng-4.5";
|
|
927
|
-
var DEFAULT_IMAGE_MODEL_US = "jimeng-4.5";
|
|
928
|
-
var DEFAULT_VIDEO_MODEL = "jimeng-video-3.5-pro";
|
|
929
|
-
var DRAFT_VERSION = "3.3.8";
|
|
930
|
-
var DRAFT_MIN_VERSION = "3.0.2";
|
|
931
|
-
var DRAFT_VERSION_OMNI = "3.3.9";
|
|
932
|
-
var OMNI_BENEFIT_TYPE = "dreamina_video_seedance_20_video_add";
|
|
933
|
-
var OMNI_BENEFIT_TYPE_FAST = "dreamina_seedance_20_fast_with_video";
|
|
934
|
-
var IMAGE_MODEL_MAP = {
|
|
935
|
-
"jimeng-5.0": "high_aes_general_v50",
|
|
936
|
-
"jimeng-4.6": "high_aes_general_v42",
|
|
937
|
-
"jimeng-4.5": "high_aes_general_v40l",
|
|
938
|
-
"jimeng-4.1": "high_aes_general_v41",
|
|
939
|
-
"jimeng-4.0": "high_aes_general_v40",
|
|
940
|
-
"jimeng-3.1": "high_aes_general_v30l_art_fangzhou:general_v3.0_18b",
|
|
941
|
-
"jimeng-3.0": "high_aes_general_v30l:general_v3.0_18b"
|
|
942
|
-
};
|
|
943
|
-
var IMAGE_MODEL_MAP_US = {
|
|
944
|
-
"jimeng-4.5": "high_aes_general_v40l",
|
|
945
|
-
"jimeng-4.1": "high_aes_general_v41",
|
|
946
|
-
"jimeng-4.0": "high_aes_general_v40",
|
|
947
|
-
"jimeng-3.0": "high_aes_general_v30l:general_v3.0_18b",
|
|
948
|
-
"nanobanana": "external_model_gemini_flash_image_v25",
|
|
949
|
-
"nanobananapro": "dreamina_image_lib_1"
|
|
950
|
-
};
|
|
951
|
-
var IMAGE_MODEL_MAP_ASIA = {
|
|
952
|
-
"jimeng-5.0": "high_aes_general_v50",
|
|
953
|
-
"jimeng-4.6": "high_aes_general_v42",
|
|
954
|
-
"jimeng-4.5": "high_aes_general_v40l",
|
|
955
|
-
"jimeng-4.1": "high_aes_general_v41",
|
|
956
|
-
"jimeng-4.0": "high_aes_general_v40",
|
|
957
|
-
"jimeng-3.0": "high_aes_general_v30l:general_v3.0_18b",
|
|
958
|
-
"nanobanana": "external_model_gemini_flash_image_v25",
|
|
959
|
-
"nanobananapro": "dreamina_image_lib_1"
|
|
960
|
-
};
|
|
961
|
-
var VIDEO_MODEL_MAP = {
|
|
962
|
-
"jimeng-video-seedance-2.0": "dreamina_seedance_40_pro",
|
|
963
|
-
"jimeng-video-seedance-2.0-fast": "dreamina_seedance_40",
|
|
964
|
-
"jimeng-video-3.5-pro": "dreamina_ic_generate_video_model_vgfm_3.5_pro",
|
|
965
|
-
"jimeng-video-3.0-pro": "dreamina_ic_generate_video_model_vgfm_3.0_pro",
|
|
966
|
-
"jimeng-video-3.0": "dreamina_ic_generate_video_model_vgfm_3.0",
|
|
967
|
-
"jimeng-video-3.0-fast": "dreamina_ic_generate_video_model_vgfm_3.0_fast",
|
|
968
|
-
"jimeng-video-2.0": "dreamina_ic_generate_video_model_vgfm_lite",
|
|
969
|
-
"jimeng-video-2.0-pro": "dreamina_ic_generate_video_model_vgfm1.0"
|
|
970
|
-
};
|
|
971
|
-
var VIDEO_MODEL_MAP_US = {
|
|
972
|
-
"jimeng-video-3.5-pro": "dreamina_ic_generate_video_model_vgfm_3.5_pro",
|
|
973
|
-
"jimeng-video-3.0": "dreamina_ic_generate_video_model_vgfm_3.0"
|
|
974
|
-
};
|
|
975
|
-
var VIDEO_MODEL_MAP_ASIA = {
|
|
976
|
-
"jimeng-video-veo3": "dreamina_veo3_generate_video",
|
|
977
|
-
"jimeng-video-veo3.1": "dreamina_veo3.1_generate_video",
|
|
978
|
-
"jimeng-video-sora2": "dreamina_sora2_generate_video",
|
|
979
|
-
"jimeng-video-3.5-pro": "dreamina_ic_generate_video_model_vgfm_3.5_pro",
|
|
980
|
-
"jimeng-video-3.0-pro": "dreamina_ic_generate_video_model_vgfm_3.0_pro",
|
|
981
|
-
"jimeng-video-3.0": "dreamina_ic_generate_video_model_vgfm_3.0",
|
|
982
|
-
"jimeng-video-3.0-fast": "dreamina_ic_generate_video_model_vgfm_3.0_fast",
|
|
983
|
-
"jimeng-video-2.0": "dreamina_ic_generate_video_model_vgfm_lite",
|
|
984
|
-
"jimeng-video-2.0-pro": "dreamina_ic_generate_video_model_vgfm1.0"
|
|
985
|
-
};
|
|
986
|
-
var STATUS_CODE_MAP = {
|
|
987
|
-
20: "PROCESSING",
|
|
988
|
-
10: "SUCCESS",
|
|
989
|
-
30: "FAILED",
|
|
990
|
-
42: "POST_PROCESSING",
|
|
991
|
-
45: "FINALIZING",
|
|
992
|
-
50: "COMPLETED"
|
|
993
|
-
};
|
|
994
|
-
var RETRY_CONFIG = {
|
|
995
|
-
MAX_RETRY_COUNT: 3,
|
|
996
|
-
RETRY_DELAY: 5e3
|
|
997
|
-
};
|
|
998
|
-
var POLLING_CONFIG = {
|
|
999
|
-
MAX_POLL_COUNT: 900,
|
|
1000
|
-
// 最大轮询次数
|
|
1001
|
-
POLL_INTERVAL: 5e3,
|
|
1002
|
-
// 轮询间隔 5 秒
|
|
1003
|
-
STABLE_ROUNDS: 5,
|
|
1004
|
-
// 稳定轮次
|
|
1005
|
-
TIMEOUT_SECONDS: 900
|
|
1006
|
-
// 默认超时 15 分钟
|
|
1007
|
-
};
|
|
1008
|
-
var RESOLUTION_OPTIONS = {
|
|
1009
|
-
"1k": {
|
|
1010
|
-
"1:1": { width: 1024, height: 1024, ratio: 1 },
|
|
1011
|
-
"4:3": { width: 768, height: 1024, ratio: 4 },
|
|
1012
|
-
"3:4": { width: 1024, height: 768, ratio: 2 },
|
|
1013
|
-
"16:9": { width: 1024, height: 576, ratio: 3 },
|
|
1014
|
-
"9:16": { width: 576, height: 1024, ratio: 5 },
|
|
1015
|
-
"3:2": { width: 1024, height: 682, ratio: 7 },
|
|
1016
|
-
"2:3": { width: 682, height: 1024, ratio: 6 },
|
|
1017
|
-
"21:9": { width: 1195, height: 512, ratio: 8 }
|
|
1018
|
-
},
|
|
1019
|
-
"2k": {
|
|
1020
|
-
"1:1": { width: 2048, height: 2048, ratio: 1 },
|
|
1021
|
-
"4:3": { width: 2304, height: 1728, ratio: 4 },
|
|
1022
|
-
"3:4": { width: 1728, height: 2304, ratio: 2 },
|
|
1023
|
-
"16:9": { width: 2560, height: 1440, ratio: 3 },
|
|
1024
|
-
"9:16": { width: 1440, height: 2560, ratio: 5 },
|
|
1025
|
-
"3:2": { width: 2496, height: 1664, ratio: 7 },
|
|
1026
|
-
"2:3": { width: 1664, height: 2496, ratio: 6 },
|
|
1027
|
-
"21:9": { width: 3024, height: 1296, ratio: 8 }
|
|
1028
|
-
},
|
|
1029
|
-
"4k": {
|
|
1030
|
-
"1:1": { width: 4096, height: 4096, ratio: 101 },
|
|
1031
|
-
"4:3": { width: 4608, height: 3456, ratio: 104 },
|
|
1032
|
-
"3:4": { width: 3456, height: 4608, ratio: 102 },
|
|
1033
|
-
"16:9": { width: 5120, height: 2880, ratio: 103 },
|
|
1034
|
-
"9:16": { width: 2880, height: 5120, ratio: 105 },
|
|
1035
|
-
"3:2": { width: 4992, height: 3328, ratio: 107 },
|
|
1036
|
-
"2:3": { width: 3328, height: 4992, ratio: 106 },
|
|
1037
|
-
"21:9": { width: 6048, height: 2592, ratio: 108 }
|
|
1038
|
-
}
|
|
1039
|
-
};
|
|
1040
|
-
var RESOLUTION_OPTIONS_NANOBANANAPRO_4K = {
|
|
1041
|
-
"1:1": { width: 4096, height: 4096, ratio: 1 },
|
|
1042
|
-
"4:3": { width: 4693, height: 3520, ratio: 4 },
|
|
1043
|
-
"3:4": { width: 3520, height: 4693, ratio: 2 },
|
|
1044
|
-
"16:9": { width: 5404, height: 3040, ratio: 3 },
|
|
1045
|
-
"9:16": { width: 3040, height: 5404, ratio: 5 },
|
|
1046
|
-
"3:2": { width: 4992, height: 3328, ratio: 7 },
|
|
1047
|
-
"2:3": { width: 3328, height: 4992, ratio: 6 },
|
|
1048
|
-
"21:9": { width: 6197, height: 2656, ratio: 8 }
|
|
1049
|
-
};
|
|
1050
|
-
|
|
1051
|
-
// src/api/controllers/core.ts
|
|
1052
|
-
var DEVICE_ID = Math.random() * 1e18 + 7e18;
|
|
1053
|
-
var WEB_ID = Math.random() * 1e18 + 7e18;
|
|
1054
|
-
var USER_ID = util_default.uuid(false);
|
|
1055
|
-
var FAKE_HEADERS = {
|
|
1056
|
-
Accept: "application/json, text/plain, */*",
|
|
1057
|
-
"Accept-Encoding": "gzip, deflate, br, zstd",
|
|
1058
|
-
"Accept-language": "zh-CN,zh;q=0.9",
|
|
1059
|
-
"Cache-control": "no-cache",
|
|
1060
|
-
Appvr: VERSION_CODE,
|
|
1061
|
-
Pragma: "no-cache",
|
|
1062
|
-
Priority: "u=1, i",
|
|
1063
|
-
Pf: PLATFORM_CODE,
|
|
1064
|
-
"Sec-Ch-Ua": '"Google Chrome";v="142", "Chromium";v="142", "Not_A Brand";v="99"',
|
|
1065
|
-
"Sec-Ch-Ua-Mobile": "?0",
|
|
1066
|
-
"Sec-Ch-Ua-Platform": '"Windows"',
|
|
1067
|
-
"Sec-Fetch-Dest": "empty",
|
|
1068
|
-
"Sec-Fetch-Mode": "cors",
|
|
1069
|
-
"Sec-Fetch-Site": "same-origin",
|
|
1070
|
-
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36"
|
|
1071
|
-
};
|
|
1072
|
-
var FILE_MAX_SIZE = 100 * 1024 * 1024;
|
|
1073
|
-
function isPrivateOrLocalIp(address) {
|
|
1074
|
-
const normalized = address.toLowerCase().split("%")[0];
|
|
1075
|
-
const ipVersion = net.isIP(normalized);
|
|
1076
|
-
if (ipVersion === 4) {
|
|
1077
|
-
const octets = normalized.split(".").map((part) => Number(part));
|
|
1078
|
-
const [a, b] = octets;
|
|
1079
|
-
if (a === 10) return true;
|
|
1080
|
-
if (a === 127) return true;
|
|
1081
|
-
if (a === 0) return true;
|
|
1082
|
-
if (a === 169 && b === 254) return true;
|
|
1083
|
-
if (a === 172 && b >= 16 && b <= 31) return true;
|
|
1084
|
-
if (a === 192 && b === 168) return true;
|
|
1085
|
-
return false;
|
|
1086
|
-
}
|
|
1087
|
-
if (ipVersion === 6) {
|
|
1088
|
-
if (normalized === "::1" || normalized === "::") return true;
|
|
1089
|
-
if (normalized.startsWith("fc") || normalized.startsWith("fd")) return true;
|
|
1090
|
-
if (normalized.startsWith("fe8") || normalized.startsWith("fe9") || normalized.startsWith("fea") || normalized.startsWith("feb")) return true;
|
|
1091
|
-
if (normalized.startsWith("::ffff:127.")) return true;
|
|
1092
|
-
return false;
|
|
1093
|
-
}
|
|
1094
|
-
return false;
|
|
1095
|
-
}
|
|
1096
|
-
async function assertSafeExternalHttpUrl(fileUrl) {
|
|
1097
|
-
let parsed;
|
|
1098
|
-
try {
|
|
1099
|
-
parsed = new URL(fileUrl);
|
|
1100
|
-
} catch {
|
|
1101
|
-
throw new APIException(exceptions_default.API_FILE_URL_INVALID, `File URL is invalid: ${fileUrl}`);
|
|
1102
|
-
}
|
|
1103
|
-
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
1104
|
-
throw new APIException(exceptions_default.API_FILE_URL_INVALID, `File URL protocol is not supported: ${parsed.protocol}`);
|
|
1105
|
-
}
|
|
1106
|
-
const hostname = parsed.hostname.trim().toLowerCase();
|
|
1107
|
-
if (!hostname) {
|
|
1108
|
-
throw new APIException(exceptions_default.API_FILE_URL_INVALID, "File URL hostname is empty");
|
|
1109
|
-
}
|
|
1110
|
-
if (hostname === "localhost" || hostname.endsWith(".local")) {
|
|
1111
|
-
throw new APIException(exceptions_default.API_FILE_URL_INVALID, `File URL host is not allowed: ${hostname}`);
|
|
1112
|
-
}
|
|
1113
|
-
if (net.isIP(hostname)) {
|
|
1114
|
-
if (isPrivateOrLocalIp(hostname)) {
|
|
1115
|
-
throw new APIException(exceptions_default.API_FILE_URL_INVALID, `File URL host is not allowed: ${hostname}`);
|
|
1116
|
-
}
|
|
1117
|
-
return;
|
|
1118
|
-
}
|
|
1119
|
-
let records;
|
|
1120
|
-
try {
|
|
1121
|
-
records = await dns.lookup(hostname, { all: true, verbatim: true });
|
|
1122
|
-
} catch {
|
|
1123
|
-
throw new APIException(exceptions_default.API_FILE_URL_INVALID, `File URL hostname cannot be resolved: ${hostname}`);
|
|
1124
|
-
}
|
|
1125
|
-
if (!records.length) {
|
|
1126
|
-
throw new APIException(exceptions_default.API_FILE_URL_INVALID, `File URL hostname cannot be resolved: ${hostname}`);
|
|
1127
|
-
}
|
|
1128
|
-
for (const record of records) {
|
|
1129
|
-
if (isPrivateOrLocalIp(record.address)) {
|
|
1130
|
-
throw new APIException(exceptions_default.API_FILE_URL_INVALID, `File URL host is not allowed: ${hostname}`);
|
|
1131
|
-
}
|
|
1132
|
-
}
|
|
1133
|
-
}
|
|
1134
|
-
async function acquireToken(refreshToken) {
|
|
1135
|
-
return refreshToken;
|
|
1136
|
-
}
|
|
1137
|
-
var REGION_PREFIX_PATTERN = /^(us|hk|jp|sg)-/i;
|
|
1138
|
-
function parseRegionCode(value) {
|
|
1139
|
-
if (!_7.isString(value)) return null;
|
|
1140
|
-
const normalized = value.trim().toLowerCase();
|
|
1141
|
-
if (normalized === "cn" || normalized === "us" || normalized === "hk" || normalized === "jp" || normalized === "sg") {
|
|
1142
|
-
return normalized;
|
|
1143
|
-
}
|
|
1144
|
-
return null;
|
|
1145
|
-
}
|
|
1146
|
-
function buildRegionInfo(regionCode) {
|
|
1147
|
-
return {
|
|
1148
|
-
isUS: regionCode === "us",
|
|
1149
|
-
isHK: regionCode === "hk",
|
|
1150
|
-
isJP: regionCode === "jp",
|
|
1151
|
-
isSG: regionCode === "sg",
|
|
1152
|
-
isInternational: regionCode !== "cn",
|
|
1153
|
-
isCN: regionCode === "cn"
|
|
1154
|
-
};
|
|
1155
|
-
}
|
|
1156
|
-
function assertTokenWithoutRegionPrefix(rawToken) {
|
|
1157
|
-
const { token } = parseProxyFromToken(rawToken);
|
|
1158
|
-
if (REGION_PREFIX_PATTERN.test(token.trim())) {
|
|
1159
|
-
throw new APIException(
|
|
1160
|
-
exceptions_default.API_REQUEST_FAILED,
|
|
1161
|
-
"token \u524D\u7F00\u534F\u8BAE\u5DF2\u79FB\u9664\uFF0C\u8BF7\u4F7F\u7528\u7EAF token\uFF0C\u5E76\u901A\u8FC7 token-pool \u7684 region \u5B57\u6BB5\u6216\u8BF7\u6C42\u5934 X-Region \u6307\u5B9A\u533A\u57DF"
|
|
1162
|
-
);
|
|
1163
|
-
}
|
|
1164
|
-
}
|
|
1165
|
-
function parseProxyFromToken(rawToken) {
|
|
1166
|
-
const tokenValue = rawToken.trim();
|
|
1167
|
-
const proxyPattern = /^(https?|socks(?:4|5)?):\/\//i;
|
|
1168
|
-
if (!proxyPattern.test(tokenValue)) return { token: tokenValue, proxyUrl: null };
|
|
1169
|
-
const lastAtIndex = tokenValue.lastIndexOf("@");
|
|
1170
|
-
if (lastAtIndex <= 0 || lastAtIndex === tokenValue.length - 1)
|
|
1171
|
-
return { token: tokenValue, proxyUrl: null };
|
|
1172
|
-
const proxyUrl = tokenValue.slice(0, lastAtIndex);
|
|
1173
|
-
const token = tokenValue.slice(lastAtIndex + 1);
|
|
1174
|
-
if (!proxyUrl || !token) return { token: tokenValue, proxyUrl: null };
|
|
1175
|
-
return { token, proxyUrl };
|
|
1176
|
-
}
|
|
1177
|
-
function getRefererByRegion(regionInfo, cnPath) {
|
|
1178
|
-
const { isInternational } = regionInfo;
|
|
1179
|
-
return isInternational ? "https://dreamina.capcut.com/" : `https://jimeng.jianying.com${cnPath}`;
|
|
1180
|
-
}
|
|
1181
|
-
function getAssistantId(regionInfo) {
|
|
1182
|
-
if (regionInfo.isUS) return DEFAULT_ASSISTANT_ID_US;
|
|
1183
|
-
if (regionInfo.isJP) return DEFAULT_ASSISTANT_ID_JP;
|
|
1184
|
-
if (regionInfo.isSG) return DEFAULT_ASSISTANT_ID_SG;
|
|
1185
|
-
if (regionInfo.isHK) return DEFAULT_ASSISTANT_ID_HK;
|
|
1186
|
-
return DEFAULT_ASSISTANT_ID_CN;
|
|
1187
|
-
}
|
|
1188
|
-
function generateCookie(refreshToken) {
|
|
1189
|
-
const { token: tokenWithRegion } = parseProxyFromToken(refreshToken);
|
|
1190
|
-
assertTokenWithoutRegionPrefix(tokenWithRegion);
|
|
1191
|
-
const token = tokenWithRegion;
|
|
1192
|
-
const sidGuardTtl = 5184e3;
|
|
1193
|
-
const sidGuardIssuedAt = util_default.unixTimestamp();
|
|
1194
|
-
const sidGuardExpireAt = encodeURIComponent(
|
|
1195
|
-
new Date((sidGuardIssuedAt + sidGuardTtl) * 1e3).toUTCString()
|
|
1196
|
-
).replace(/%20/g, "+");
|
|
1197
|
-
return [
|
|
1198
|
-
`_tea_web_id=${WEB_ID}`,
|
|
1199
|
-
`is_staff_user=false`,
|
|
1200
|
-
`sid_guard=${token}%7C${sidGuardIssuedAt}%7C${sidGuardTtl}%7C${sidGuardExpireAt}`,
|
|
1201
|
-
`uid_tt=${USER_ID}`,
|
|
1202
|
-
`uid_tt_ss=${USER_ID}`,
|
|
1203
|
-
`sid_tt=${token}`,
|
|
1204
|
-
`sessionid=${token}`,
|
|
1205
|
-
`sessionid_ss=${token}`
|
|
1206
|
-
].join("; ");
|
|
1207
|
-
}
|
|
1208
|
-
async function getCredit(refreshToken, regionInfo) {
|
|
1209
|
-
const referer = getRefererByRegion(regionInfo, "/ai-tool/image/generate");
|
|
1210
|
-
const {
|
|
1211
|
-
credit: { gift_credit, purchase_credit, vip_credit }
|
|
1212
|
-
} = await request("POST", "/commerce/v1/benefits/user_credit", refreshToken, regionInfo, {
|
|
1213
|
-
data: {},
|
|
1214
|
-
headers: {
|
|
1215
|
-
Referer: referer
|
|
1216
|
-
},
|
|
1217
|
-
noDefaultParams: true
|
|
1218
|
-
});
|
|
1219
|
-
logger_default.info(`
|
|
1220
|
-
\u79EF\u5206\u4FE1\u606F:
|
|
1221
|
-
\u8D60\u9001\u79EF\u5206: ${gift_credit}, \u8D2D\u4E70\u79EF\u5206: ${purchase_credit}, VIP\u79EF\u5206: ${vip_credit}`);
|
|
1222
|
-
return {
|
|
1223
|
-
giftCredit: gift_credit,
|
|
1224
|
-
purchaseCredit: purchase_credit,
|
|
1225
|
-
vipCredit: vip_credit,
|
|
1226
|
-
totalCredit: gift_credit + purchase_credit + vip_credit
|
|
1227
|
-
};
|
|
1228
|
-
}
|
|
1229
|
-
async function receiveCredit(refreshToken, regionInfo) {
|
|
1230
|
-
logger_default.info("\u6B63\u5728\u5C1D\u8BD5\u6536\u53D6\u4ECA\u65E5\u79EF\u5206...");
|
|
1231
|
-
const referer = getRefererByRegion(regionInfo, "/ai-tool/home");
|
|
1232
|
-
const timeZone = regionInfo.isUS ? "America/New_York" : regionInfo.isHK ? "Asia/Hong_Kong" : regionInfo.isJP ? "Asia/Tokyo" : regionInfo.isSG ? "Asia/Singapore" : "Asia/Shanghai";
|
|
1233
|
-
const { receive_quota } = await request("POST", "/commerce/v1/benefits/credit_receive", refreshToken, regionInfo, {
|
|
1234
|
-
data: {
|
|
1235
|
-
time_zone: timeZone
|
|
1236
|
-
},
|
|
1237
|
-
headers: {
|
|
1238
|
-
Referer: referer
|
|
1239
|
-
}
|
|
1240
|
-
});
|
|
1241
|
-
logger_default.info(`\u4ECA\u65E5${receive_quota}\u79EF\u5206\u6536\u53D6\u6210\u529F`);
|
|
1242
|
-
return receive_quota;
|
|
1243
|
-
}
|
|
1244
|
-
async function request(method, uri, refreshToken, regionInfo, options = {}) {
|
|
1245
|
-
const { token: tokenWithRegion, proxyUrl } = parseProxyFromToken(refreshToken);
|
|
1246
|
-
assertTokenWithoutRegionPrefix(tokenWithRegion);
|
|
1247
|
-
const { isUS, isHK, isJP, isSG } = regionInfo;
|
|
1248
|
-
await acquireToken(tokenWithRegion);
|
|
1249
|
-
const deviceTime = util_default.unixTimestamp();
|
|
1250
|
-
const sign = util_default.md5(
|
|
1251
|
-
`9e2c|${uri.slice(-7)}|${PLATFORM_CODE}|${VERSION_CODE}|${deviceTime}||11ac`
|
|
1252
|
-
);
|
|
1253
|
-
let baseUrl;
|
|
1254
|
-
let aid;
|
|
1255
|
-
let region;
|
|
1256
|
-
if (isUS) {
|
|
1257
|
-
if (uri.startsWith("/commerce/")) {
|
|
1258
|
-
baseUrl = BASE_URL_US_COMMERCE;
|
|
1259
|
-
} else {
|
|
1260
|
-
baseUrl = BASE_URL_DREAMINA_US;
|
|
1261
|
-
}
|
|
1262
|
-
aid = DEFAULT_ASSISTANT_ID_US;
|
|
1263
|
-
region = REGION_US;
|
|
1264
|
-
} else if (isHK || isJP || isSG) {
|
|
1265
|
-
if (uri.startsWith("/commerce/")) {
|
|
1266
|
-
baseUrl = BASE_URL_HK_COMMERCE;
|
|
1267
|
-
} else {
|
|
1268
|
-
baseUrl = BASE_URL_DREAMINA_HK;
|
|
1269
|
-
}
|
|
1270
|
-
if (isJP) {
|
|
1271
|
-
aid = DEFAULT_ASSISTANT_ID_JP;
|
|
1272
|
-
region = REGION_JP;
|
|
1273
|
-
} else if (isSG) {
|
|
1274
|
-
aid = DEFAULT_ASSISTANT_ID_SG;
|
|
1275
|
-
region = REGION_SG;
|
|
1276
|
-
} else {
|
|
1277
|
-
aid = DEFAULT_ASSISTANT_ID_HK;
|
|
1278
|
-
region = REGION_HK;
|
|
1279
|
-
}
|
|
1280
|
-
} else {
|
|
1281
|
-
baseUrl = BASE_URL_CN;
|
|
1282
|
-
aid = DEFAULT_ASSISTANT_ID_CN;
|
|
1283
|
-
region = REGION_CN;
|
|
1284
|
-
}
|
|
1285
|
-
const origin = new URL(baseUrl).origin;
|
|
1286
|
-
const fullUrl = `${baseUrl}${uri}`;
|
|
1287
|
-
const requestParams = options.noDefaultParams ? options.params || {} : {
|
|
1288
|
-
aid,
|
|
1289
|
-
device_platform: "web",
|
|
1290
|
-
region,
|
|
1291
|
-
...isUS || isHK || isJP || isSG ? {} : { webId: WEB_ID },
|
|
1292
|
-
da_version: DA_VERSION,
|
|
1293
|
-
os: "windows",
|
|
1294
|
-
web_component_open_flag: 1,
|
|
1295
|
-
web_version: WEB_VERSION,
|
|
1296
|
-
aigc_features: "app_lip_sync",
|
|
1297
|
-
...options.params || {}
|
|
1298
|
-
};
|
|
1299
|
-
const headers = {
|
|
1300
|
-
...FAKE_HEADERS,
|
|
1301
|
-
Origin: origin,
|
|
1302
|
-
Referer: origin,
|
|
1303
|
-
"App-Sdk-Version": "48.0.0",
|
|
1304
|
-
Appid: aid,
|
|
1305
|
-
Cookie: generateCookie(tokenWithRegion),
|
|
1306
|
-
"Device-Time": deviceTime,
|
|
1307
|
-
Lan: isUS ? "en" : isJP ? "ja" : isHK || isSG ? "en" : "zh-Hans",
|
|
1308
|
-
Loc: isUS ? "us" : isJP ? "jp" : isHK ? "hk" : isSG ? "sg" : "cn",
|
|
1309
|
-
Sign: sign,
|
|
1310
|
-
"Sign-Ver": "1",
|
|
1311
|
-
Tdid: "",
|
|
1312
|
-
...options.headers || {}
|
|
1313
|
-
};
|
|
1314
|
-
logger_default.info(`\u53D1\u9001\u8BF7\u6C42: ${method.toUpperCase()} ${fullUrl}`);
|
|
1315
|
-
if (proxyUrl) {
|
|
1316
|
-
const maskedProxyUrl = proxyUrl.replace(/\/\/([^@/]+)@/i, "//***@");
|
|
1317
|
-
logger_default.info(`\u4F7F\u7528\u4EE3\u7406: ${maskedProxyUrl}`);
|
|
1318
|
-
}
|
|
1319
|
-
logger_default.info(`\u8BF7\u6C42\u53C2\u6570: ${JSON.stringify(requestParams)}`);
|
|
1320
|
-
logger_default.info(`\u8BF7\u6C42\u6570\u636E: ${JSON.stringify(options.data || {})}`);
|
|
1321
|
-
const proxyAgent = proxyUrl ? proxyUrl.toLowerCase().startsWith("socks") ? new SocksProxyAgent(proxyUrl) : new HttpsProxyAgent(proxyUrl) : void 0;
|
|
1322
|
-
let retries = 0;
|
|
1323
|
-
const maxRetries = RETRY_CONFIG.MAX_RETRY_COUNT;
|
|
1324
|
-
let lastError = null;
|
|
1325
|
-
while (retries <= maxRetries) {
|
|
1326
|
-
try {
|
|
1327
|
-
if (retries > 0) {
|
|
1328
|
-
logger_default.info(`\u7B2C ${retries} \u6B21\u91CD\u8BD5\u8BF7\u6C42: ${method.toUpperCase()} ${fullUrl}`);
|
|
1329
|
-
await new Promise((resolve) => setTimeout(resolve, RETRY_CONFIG.RETRY_DELAY));
|
|
1330
|
-
}
|
|
1331
|
-
const response = await axios2.request({
|
|
1332
|
-
method,
|
|
1333
|
-
url: fullUrl,
|
|
1334
|
-
params: requestParams,
|
|
1335
|
-
headers,
|
|
1336
|
-
timeout: 45e3,
|
|
1337
|
-
// 增加超时时间到45秒
|
|
1338
|
-
validateStatus: () => true,
|
|
1339
|
-
// 允许任何状态码
|
|
1340
|
-
..._7.omit(options, "params", "headers"),
|
|
1341
|
-
...proxyAgent ? { httpAgent: proxyAgent, httpsAgent: proxyAgent, proxy: false } : {}
|
|
1342
|
-
});
|
|
1343
|
-
logger_default.info(`\u54CD\u5E94\u72B6\u6001: ${response.status} ${response.statusText}`);
|
|
1344
|
-
if (options.responseType == "stream") return response;
|
|
1345
|
-
const responseDataSummary = JSON.stringify(response.data).substring(0, 500) + (JSON.stringify(response.data).length > 500 ? "..." : "");
|
|
1346
|
-
logger_default.info(`\u54CD\u5E94\u6570\u636E\u6458\u8981: ${responseDataSummary}`);
|
|
1347
|
-
if (response.status >= 400) {
|
|
1348
|
-
logger_default.warn(`HTTP\u9519\u8BEF: ${response.status} ${response.statusText}`);
|
|
1349
|
-
if (retries < maxRetries) {
|
|
1350
|
-
retries++;
|
|
1351
|
-
continue;
|
|
1352
|
-
}
|
|
1353
|
-
}
|
|
1354
|
-
return checkResult(response);
|
|
1355
|
-
} catch (error) {
|
|
1356
|
-
lastError = error;
|
|
1357
|
-
logger_default.error(`\u8BF7\u6C42\u5931\u8D25 (\u5C1D\u8BD5 ${retries + 1}/${maxRetries + 1}): ${error.message}`);
|
|
1358
|
-
const retryableErrorCodes = [
|
|
1359
|
-
"ECONNABORTED",
|
|
1360
|
-
"ETIMEDOUT",
|
|
1361
|
-
"ECONNRESET",
|
|
1362
|
-
"ENOTFOUND",
|
|
1363
|
-
"ECONNREFUSED",
|
|
1364
|
-
"EAI_AGAIN",
|
|
1365
|
-
"EPIPE",
|
|
1366
|
-
"ENETUNREACH",
|
|
1367
|
-
"EHOSTUNREACH"
|
|
1368
|
-
];
|
|
1369
|
-
const isRetryableError = retryableErrorCodes.includes(error.code) || error.message.includes("timeout") || error.message.includes("network") || error.message.includes("ECONNRESET") || error.message.includes("socket hang up") || error.message.includes("Proxy connection");
|
|
1370
|
-
if (isRetryableError && retries < maxRetries) {
|
|
1371
|
-
retries++;
|
|
1372
|
-
continue;
|
|
1373
|
-
}
|
|
1374
|
-
break;
|
|
1375
|
-
}
|
|
1376
|
-
}
|
|
1377
|
-
if (lastError) {
|
|
1378
|
-
logger_default.error(`\u8BF7\u6C42\u5931\u8D25\uFF0C\u5DF2\u91CD\u8BD5 ${retries} \u6B21: ${lastError.message}`);
|
|
1379
|
-
if (lastError.response) {
|
|
1380
|
-
logger_default.error(`\u54CD\u5E94\u72B6\u6001: ${lastError.response.status}`);
|
|
1381
|
-
logger_default.error(`\u54CD\u5E94\u6570\u636E: ${JSON.stringify(lastError.response.data)}`);
|
|
1382
|
-
}
|
|
1383
|
-
throw lastError;
|
|
1384
|
-
} else {
|
|
1385
|
-
const error = new Error(`\u8BF7\u6C42\u5931\u8D25\uFF0C\u5DF2\u91CD\u8BD5 ${retries} \u6B21\uFF0C\u4F46\u6CA1\u6709\u5177\u4F53\u9519\u8BEF\u4FE1\u606F`);
|
|
1386
|
-
logger_default.error(error.message);
|
|
1387
|
-
throw error;
|
|
1388
|
-
}
|
|
1389
|
-
}
|
|
1390
|
-
async function checkImageContent(imageUri, refreshToken, regionInfo) {
|
|
1391
|
-
if (regionInfo.isInternational) return;
|
|
1392
|
-
const babiParam = JSON.stringify({
|
|
1393
|
-
scenario: "image_video_generation",
|
|
1394
|
-
feature_key: "aigc_to_image",
|
|
1395
|
-
feature_entrance: "to-generate",
|
|
1396
|
-
feature_entrance_detail: "to-generate-algo_proxy"
|
|
1397
|
-
});
|
|
1398
|
-
logger_default.info(`\u5F00\u59CB\u56FE\u7247\u5185\u5BB9\u5B89\u5168\u68C0\u6D4B: ${imageUri}`);
|
|
1399
|
-
try {
|
|
1400
|
-
await request("post", "/mweb/v1/algo_proxy", refreshToken, regionInfo, {
|
|
1401
|
-
params: {
|
|
1402
|
-
babi_param: babiParam
|
|
1403
|
-
},
|
|
1404
|
-
data: {
|
|
1405
|
-
scene: "image_face_ip",
|
|
1406
|
-
options: { ip_check: true },
|
|
1407
|
-
req_key: "benchmark_test_user_upload_image_input",
|
|
1408
|
-
file_list: [{ file_uri: imageUri }],
|
|
1409
|
-
req_params: {}
|
|
1410
|
-
}
|
|
1411
|
-
});
|
|
1412
|
-
logger_default.info(`\u56FE\u7247\u5185\u5BB9\u5B89\u5168\u68C0\u6D4B\u901A\u8FC7: ${imageUri}`);
|
|
1413
|
-
} catch (error) {
|
|
1414
|
-
const isContentViolation = error.message && (error.message.includes("2003") || error.message.includes("risk not pass") || error.message.includes("detected risk"));
|
|
1415
|
-
if (isContentViolation) {
|
|
1416
|
-
logger_default.error(`\u56FE\u7247\u5185\u5BB9\u5B89\u5168\u68C0\u6D4B\u672A\u901A\u8FC7: ${imageUri}, ${error.message}`);
|
|
1417
|
-
throw new APIException(
|
|
1418
|
-
exceptions_default.API_REQUEST_FAILED,
|
|
1419
|
-
`\u56FE\u7247\u5185\u5BB9\u68C0\u6D4B\u672A\u901A\u8FC7\uFF0C\u8BE5\u56FE\u7247\u53EF\u80FD\u5305\u542B\u8FDD\u89C4\u5185\u5BB9`
|
|
1420
|
-
);
|
|
1421
|
-
}
|
|
1422
|
-
logger_default.warn(`\u56FE\u7247\u5185\u5BB9\u5B89\u5168\u68C0\u6D4B\u670D\u52A1\u5F02\u5E38(\u4E0D\u963B\u585E): ${imageUri}, ${error.message}`);
|
|
1423
|
-
}
|
|
1424
|
-
}
|
|
1425
|
-
function checkResult(result) {
|
|
1426
|
-
const { ret, errmsg, data } = result.data;
|
|
1427
|
-
if (!_7.isFinite(Number(ret))) return result.data;
|
|
1428
|
-
if (ret === "0") return data;
|
|
1429
|
-
JimengErrorHandler.handleApiResponse(result.data, {
|
|
1430
|
-
context: "\u5373\u68A6API\u8BF7\u6C42",
|
|
1431
|
-
operation: "\u8BF7\u6C42"
|
|
1432
|
-
});
|
|
1433
|
-
}
|
|
1434
|
-
async function getTokenLiveStatus(refreshToken, regionInfo) {
|
|
1435
|
-
try {
|
|
1436
|
-
const result = await request(
|
|
1437
|
-
"POST",
|
|
1438
|
-
"/passport/account/info/v2",
|
|
1439
|
-
refreshToken,
|
|
1440
|
-
regionInfo,
|
|
1441
|
-
{
|
|
1442
|
-
params: {
|
|
1443
|
-
account_sdk_source: "web"
|
|
1444
|
-
}
|
|
1445
|
-
}
|
|
1446
|
-
);
|
|
1447
|
-
const resultObj = result && typeof result === "object" ? result : {};
|
|
1448
|
-
const nestedData = resultObj.data && typeof resultObj.data === "object" ? resultObj.data : null;
|
|
1449
|
-
return Boolean(resultObj.user_id || (nestedData == null ? void 0 : nestedData.user_id));
|
|
1450
|
-
} catch {
|
|
1451
|
-
return false;
|
|
1452
|
-
}
|
|
1453
|
-
}
|
|
1454
|
-
|
|
1455
|
-
// src/lib/session-pool.ts
|
|
1456
|
-
import path6 from "path";
|
|
1457
|
-
import fs6 from "fs-extra";
|
|
1458
|
-
import _8 from "lodash";
|
|
1459
|
-
var DYNAMIC_CAPABILITY_TTL_MS = 30 * 60 * 1e3;
|
|
1460
|
-
var TokenPool = class {
|
|
1461
|
-
enabled;
|
|
1462
|
-
filePath;
|
|
1463
|
-
healthCheckIntervalMs;
|
|
1464
|
-
fetchCreditOnCheck;
|
|
1465
|
-
autoDisableEnabled;
|
|
1466
|
-
autoDisableFailures;
|
|
1467
|
-
pickStrategy;
|
|
1468
|
-
entryMap = /* @__PURE__ */ new Map();
|
|
1469
|
-
initialized = false;
|
|
1470
|
-
healthChecking = false;
|
|
1471
|
-
lastHealthCheckAt = 0;
|
|
1472
|
-
healthCheckTimer = null;
|
|
1473
|
-
roundRobinCursor = 0;
|
|
1474
|
-
constructor() {
|
|
1475
|
-
this.enabled = process.env.TOKEN_POOL_ENABLED !== "false";
|
|
1476
|
-
this.filePath = path6.resolve(
|
|
1477
|
-
process.env.TOKEN_POOL_FILE || "configs/token-pool.json"
|
|
1478
|
-
);
|
|
1479
|
-
this.healthCheckIntervalMs = Number(
|
|
1480
|
-
process.env.TOKEN_POOL_HEALTHCHECK_INTERVAL_MS || 10 * 60 * 1e3
|
|
1481
|
-
);
|
|
1482
|
-
this.fetchCreditOnCheck = process.env.TOKEN_POOL_FETCH_CREDIT === "true";
|
|
1483
|
-
this.autoDisableEnabled = process.env.TOKEN_POOL_AUTO_DISABLE !== "false";
|
|
1484
|
-
this.autoDisableFailures = Math.max(
|
|
1485
|
-
1,
|
|
1486
|
-
Number(process.env.TOKEN_POOL_AUTO_DISABLE_FAILURES || 2)
|
|
1487
|
-
);
|
|
1488
|
-
this.pickStrategy = process.env.TOKEN_POOL_STRATEGY === "round_robin" ? "round_robin" : "random";
|
|
1489
|
-
}
|
|
1490
|
-
async init() {
|
|
1491
|
-
if (this.initialized) return;
|
|
1492
|
-
this.initialized = true;
|
|
1493
|
-
if (!this.enabled) {
|
|
1494
|
-
logger_default.info("Token pool disabled by TOKEN_POOL_ENABLED=false");
|
|
1495
|
-
return;
|
|
1496
|
-
}
|
|
1497
|
-
await this.loadFromDisk();
|
|
1498
|
-
this.startHealthCheckLoop();
|
|
1499
|
-
logger_default.info(
|
|
1500
|
-
`Token pool initialized: total=${this.entryMap.size}, file=${this.filePath}`
|
|
1501
|
-
);
|
|
1502
|
-
}
|
|
1503
|
-
getSummary() {
|
|
1504
|
-
const entries = this.getEntries(false);
|
|
1505
|
-
const enabledCount = entries.filter((item) => item.enabled).length;
|
|
1506
|
-
const liveCount = entries.filter((item) => item.enabled && item.live === true).length;
|
|
1507
|
-
const missingRegionCount = entries.filter((item) => !item.region).length;
|
|
1508
|
-
return {
|
|
1509
|
-
enabled: this.enabled,
|
|
1510
|
-
filePath: this.filePath,
|
|
1511
|
-
pickStrategy: this.pickStrategy,
|
|
1512
|
-
healthCheckIntervalMs: this.healthCheckIntervalMs,
|
|
1513
|
-
fetchCreditOnCheck: this.fetchCreditOnCheck,
|
|
1514
|
-
autoDisableEnabled: this.autoDisableEnabled,
|
|
1515
|
-
autoDisableFailures: this.autoDisableFailures,
|
|
1516
|
-
total: entries.length,
|
|
1517
|
-
enabledCount,
|
|
1518
|
-
liveCount,
|
|
1519
|
-
missingRegionCount,
|
|
1520
|
-
lastHealthCheckAt: this.lastHealthCheckAt || null
|
|
1521
|
-
};
|
|
1522
|
-
}
|
|
1523
|
-
getEntries(maskToken = true) {
|
|
1524
|
-
const items = Array.from(this.entryMap.values()).map((item) => ({ ...item }));
|
|
1525
|
-
if (!maskToken) return items;
|
|
1526
|
-
return items.map((item) => ({
|
|
1527
|
-
...item,
|
|
1528
|
-
token: this.maskToken(item.token)
|
|
1529
|
-
}));
|
|
1530
|
-
}
|
|
1531
|
-
getAllTokens(options = {}) {
|
|
1532
|
-
const { onlyEnabled = true, preferLive = true } = options;
|
|
1533
|
-
const entries = this.getEntries(false).filter((item) => {
|
|
1534
|
-
if (onlyEnabled && !item.enabled) return false;
|
|
1535
|
-
if (preferLive && item.live === false) return false;
|
|
1536
|
-
return true;
|
|
1537
|
-
});
|
|
1538
|
-
return entries.map((item) => item.token);
|
|
1539
|
-
}
|
|
1540
|
-
getTokenEntry(token) {
|
|
1541
|
-
const entry = this.entryMap.get(token);
|
|
1542
|
-
return entry ? { ...entry } : null;
|
|
1543
|
-
}
|
|
1544
|
-
pickTokenFromAuthorization(authorization) {
|
|
1545
|
-
return this.pickTokenFromAuthorizationDetailed(authorization).token;
|
|
1546
|
-
}
|
|
1547
|
-
pickTokenFromAuthorizationDetailed(authorization) {
|
|
1548
|
-
if (_8.isString(authorization)) {
|
|
1549
|
-
if (authorization.trim().length === 0) return { token: this.pickToken(), error: null };
|
|
1550
|
-
if (!/^Bearer\s+/i.test(authorization)) {
|
|
1551
|
-
return { token: null, error: "invalid_authorization_format" };
|
|
1552
|
-
}
|
|
1553
|
-
const tokens = authorization.replace(/^Bearer\s+/i, "").split(",").map((token) => token.trim()).filter(Boolean);
|
|
1554
|
-
if (tokens.length === 0) {
|
|
1555
|
-
return { token: null, error: "empty_authorization_tokens" };
|
|
1556
|
-
}
|
|
1557
|
-
return { token: _8.sample(tokens) || null, error: null };
|
|
1558
|
-
}
|
|
1559
|
-
return { token: this.pickToken(), error: null };
|
|
1560
|
-
}
|
|
1561
|
-
pickToken() {
|
|
1562
|
-
if (!this.enabled) return null;
|
|
1563
|
-
const tokens = this.getAllTokens({ onlyEnabled: true, preferLive: true });
|
|
1564
|
-
if (tokens.length === 0) return null;
|
|
1565
|
-
if (this.pickStrategy === "round_robin") {
|
|
1566
|
-
const token = tokens[this.roundRobinCursor % tokens.length];
|
|
1567
|
-
this.roundRobinCursor++;
|
|
1568
|
-
return token;
|
|
1569
|
-
}
|
|
1570
|
-
return _8.sample(tokens) || null;
|
|
1571
|
-
}
|
|
1572
|
-
pickTokenForRequest({
|
|
1573
|
-
authorization,
|
|
1574
|
-
requestedModel,
|
|
1575
|
-
taskType,
|
|
1576
|
-
requiredCapabilityTags = [],
|
|
1577
|
-
xRegion
|
|
1578
|
-
}) {
|
|
1579
|
-
const xRegionCode = parseRegionCode(xRegion);
|
|
1580
|
-
if (_8.isString(xRegion) && xRegion.trim().length > 0 && !xRegionCode) {
|
|
1581
|
-
return { token: null, region: null, error: "unsupported_region", reason: "X-Region \u4EC5\u652F\u6301 cn/us/hk/jp/sg" };
|
|
1582
|
-
}
|
|
1583
|
-
const authParseResult = this.parseAuthorizationTokens(authorization);
|
|
1584
|
-
if (authParseResult.error) {
|
|
1585
|
-
return { token: null, region: null, error: authParseResult.error };
|
|
1586
|
-
}
|
|
1587
|
-
const authTokens = authParseResult.tokens;
|
|
1588
|
-
const candidates = authTokens.length > 0 ? authTokens.map((token) => this.buildCandidateFromAuthToken(token, xRegionCode)) : this.getEntries(false).map((entry) => this.buildCandidateFromPoolEntry(entry));
|
|
1589
|
-
const validCandidates = candidates.filter((item) => Boolean(item));
|
|
1590
|
-
if (validCandidates.length === 0) {
|
|
1591
|
-
return { token: null, region: null, error: "no_matching_token", reason: "\u672A\u627E\u5230\u53EF\u8BC4\u4F30\u7684 token \u5019\u9009\u96C6" };
|
|
1592
|
-
}
|
|
1593
|
-
const prefixedCandidate = validCandidates.find((item) => item.prefixedToken);
|
|
1594
|
-
if (prefixedCandidate) {
|
|
1595
|
-
return {
|
|
1596
|
-
token: null,
|
|
1597
|
-
region: null,
|
|
1598
|
-
error: "prefixed_token_not_supported",
|
|
1599
|
-
reason: `token ${this.maskToken(prefixedCandidate.token)} \u4F7F\u7528\u4E86\u5DF2\u5E9F\u5F03\u7684 region \u524D\u7F00`
|
|
1600
|
-
};
|
|
1601
|
-
}
|
|
1602
|
-
const regionLockedCandidates = validCandidates.filter(
|
|
1603
|
-
(item) => xRegionCode ? item.region === xRegionCode : true
|
|
1604
|
-
);
|
|
1605
|
-
const regionReadyCandidates = regionLockedCandidates.filter((item) => Boolean(item.region));
|
|
1606
|
-
if (regionReadyCandidates.length === 0) {
|
|
1607
|
-
return { token: null, region: null, error: "missing_region", reason: "\u5019\u9009 token \u7F3A\u5C11 region\uFF0C\u6216\u4E0E X-Region \u4E0D\u5339\u914D" };
|
|
1608
|
-
}
|
|
1609
|
-
const matched = regionReadyCandidates.filter(
|
|
1610
|
-
(item) => this.matchesModelAndCapabilities(item, requestedModel, taskType, requiredCapabilityTags)
|
|
1611
|
-
);
|
|
1612
|
-
if (matched.length === 0) {
|
|
1613
|
-
return {
|
|
1614
|
-
token: null,
|
|
1615
|
-
region: xRegionCode || regionReadyCandidates[0].region || null,
|
|
1616
|
-
error: "no_matching_token",
|
|
1617
|
-
reason: `region \u5DF2\u5339\u914D\uFF0C\u4F46\u65E0 token \u652F\u6301\u6A21\u578B ${requestedModel}`
|
|
1618
|
-
};
|
|
1619
|
-
}
|
|
1620
|
-
const selected = this.pickCandidate(matched);
|
|
1621
|
-
return { token: selected.token, region: selected.region, error: null };
|
|
1622
|
-
}
|
|
1623
|
-
async addTokens(rawTokens, options = {}) {
|
|
1624
|
-
var _a, _b;
|
|
1625
|
-
if (!this.enabled) return { added: 0, total: 0 };
|
|
1626
|
-
const normalized = this.normalizeAddTokens(rawTokens, options.defaultRegion);
|
|
1627
|
-
let added = 0;
|
|
1628
|
-
for (const tokenInput of normalized) {
|
|
1629
|
-
const token = tokenInput.token;
|
|
1630
|
-
if (this.entryMap.has(token)) continue;
|
|
1631
|
-
assertTokenWithoutRegionPrefix(token);
|
|
1632
|
-
this.entryMap.set(token, {
|
|
1633
|
-
token,
|
|
1634
|
-
region: tokenInput.region,
|
|
1635
|
-
enabled: tokenInput.enabled !== false,
|
|
1636
|
-
live: void 0,
|
|
1637
|
-
lastCheckedAt: void 0,
|
|
1638
|
-
lastError: void 0,
|
|
1639
|
-
lastCredit: void 0,
|
|
1640
|
-
consecutiveFailures: 0,
|
|
1641
|
-
allowedModels: ((_a = tokenInput.allowedModels) == null ? void 0 : _a.length) ? Array.from(new Set(tokenInput.allowedModels)) : void 0,
|
|
1642
|
-
capabilityTags: ((_b = tokenInput.capabilityTags) == null ? void 0 : _b.length) ? Array.from(new Set(tokenInput.capabilityTags)) : void 0,
|
|
1643
|
-
dynamicCapabilities: void 0
|
|
1644
|
-
});
|
|
1645
|
-
added++;
|
|
1646
|
-
}
|
|
1647
|
-
if (added > 0) {
|
|
1648
|
-
await this.persistToDisk();
|
|
1649
|
-
logger_default.info(`Token pool add tokens: added=${added}, total=${this.entryMap.size}`);
|
|
1650
|
-
}
|
|
1651
|
-
return { added, total: this.entryMap.size };
|
|
1652
|
-
}
|
|
1653
|
-
async removeTokens(rawTokens) {
|
|
1654
|
-
if (!this.enabled) return { removed: 0, total: 0 };
|
|
1655
|
-
const tokens = rawTokens.map((token) => token.trim()).filter(Boolean);
|
|
1656
|
-
let removed = 0;
|
|
1657
|
-
for (const token of tokens) {
|
|
1658
|
-
if (this.entryMap.delete(token)) removed++;
|
|
1659
|
-
}
|
|
1660
|
-
if (removed > 0) {
|
|
1661
|
-
await this.persistToDisk();
|
|
1662
|
-
logger_default.info(`Token pool remove tokens: removed=${removed}, total=${this.entryMap.size}`);
|
|
1663
|
-
}
|
|
1664
|
-
return { removed, total: this.entryMap.size };
|
|
1665
|
-
}
|
|
1666
|
-
async setTokenEnabled(token, enabled) {
|
|
1667
|
-
if (!this.enabled) return false;
|
|
1668
|
-
const item = this.entryMap.get(token);
|
|
1669
|
-
if (!item) return false;
|
|
1670
|
-
item.enabled = enabled;
|
|
1671
|
-
if (!enabled) item.live = false;
|
|
1672
|
-
await this.persistToDisk();
|
|
1673
|
-
return true;
|
|
1674
|
-
}
|
|
1675
|
-
async syncTokenCheckResult(token, live) {
|
|
1676
|
-
if (!this.enabled) return false;
|
|
1677
|
-
const item = this.entryMap.get(token);
|
|
1678
|
-
if (!item) return false;
|
|
1679
|
-
item.lastCheckedAt = Date.now();
|
|
1680
|
-
item.live = live;
|
|
1681
|
-
if (live) {
|
|
1682
|
-
item.enabled = true;
|
|
1683
|
-
item.consecutiveFailures = 0;
|
|
1684
|
-
item.lastError = void 0;
|
|
1685
|
-
} else {
|
|
1686
|
-
item.consecutiveFailures++;
|
|
1687
|
-
item.lastError = "token_not_live";
|
|
1688
|
-
if (this.autoDisableEnabled && item.consecutiveFailures >= this.autoDisableFailures) {
|
|
1689
|
-
item.enabled = false;
|
|
1690
|
-
}
|
|
1691
|
-
}
|
|
1692
|
-
await this.persistToDisk();
|
|
1693
|
-
return true;
|
|
1694
|
-
}
|
|
1695
|
-
async reloadFromDisk() {
|
|
1696
|
-
await this.loadFromDisk();
|
|
1697
|
-
}
|
|
1698
|
-
async runHealthCheck() {
|
|
1699
|
-
if (!this.enabled) return { checked: 0, live: 0, invalid: 0, disabled: 0 };
|
|
1700
|
-
if (this.healthChecking) {
|
|
1701
|
-
return { checked: 0, live: 0, invalid: 0, disabled: 0 };
|
|
1702
|
-
}
|
|
1703
|
-
this.healthChecking = true;
|
|
1704
|
-
const entries = this.getEntries(false).filter((item) => item.enabled);
|
|
1705
|
-
let checked = 0;
|
|
1706
|
-
let live = 0;
|
|
1707
|
-
let invalid = 0;
|
|
1708
|
-
let disabled = 0;
|
|
1709
|
-
try {
|
|
1710
|
-
for (const item of entries) {
|
|
1711
|
-
checked++;
|
|
1712
|
-
const current = this.entryMap.get(item.token);
|
|
1713
|
-
if (!current || !current.enabled) continue;
|
|
1714
|
-
const regionInfo = current.region ? buildRegionInfo(current.region) : null;
|
|
1715
|
-
if (!regionInfo) {
|
|
1716
|
-
current.live = false;
|
|
1717
|
-
current.lastError = "missing_region";
|
|
1718
|
-
current.consecutiveFailures++;
|
|
1719
|
-
invalid++;
|
|
1720
|
-
continue;
|
|
1721
|
-
}
|
|
1722
|
-
current.lastCheckedAt = Date.now();
|
|
1723
|
-
try {
|
|
1724
|
-
const isLive = await getTokenLiveStatus(current.token, regionInfo);
|
|
1725
|
-
current.live = isLive;
|
|
1726
|
-
current.lastError = void 0;
|
|
1727
|
-
if (isLive) {
|
|
1728
|
-
current.consecutiveFailures = 0;
|
|
1729
|
-
live++;
|
|
1730
|
-
await this.refreshDynamicCapabilitiesIfNeeded(current, regionInfo);
|
|
1731
|
-
if (this.fetchCreditOnCheck) {
|
|
1732
|
-
try {
|
|
1733
|
-
const credit = await getCredit(current.token, regionInfo);
|
|
1734
|
-
current.lastCredit = credit.totalCredit;
|
|
1735
|
-
} catch (err) {
|
|
1736
|
-
current.lastError = `credit_check_failed: ${(err == null ? void 0 : err.message) || String(err)}`;
|
|
1737
|
-
}
|
|
1738
|
-
}
|
|
1739
|
-
} else {
|
|
1740
|
-
invalid++;
|
|
1741
|
-
current.consecutiveFailures++;
|
|
1742
|
-
current.lastError = "token_not_live";
|
|
1743
|
-
}
|
|
1744
|
-
} catch (err) {
|
|
1745
|
-
invalid++;
|
|
1746
|
-
current.live = false;
|
|
1747
|
-
current.consecutiveFailures++;
|
|
1748
|
-
current.lastError = (err == null ? void 0 : err.message) || String(err);
|
|
1749
|
-
}
|
|
1750
|
-
if (this.autoDisableEnabled && current.consecutiveFailures >= this.autoDisableFailures) {
|
|
1751
|
-
current.enabled = false;
|
|
1752
|
-
current.live = false;
|
|
1753
|
-
disabled++;
|
|
1754
|
-
}
|
|
1755
|
-
}
|
|
1756
|
-
this.lastHealthCheckAt = Date.now();
|
|
1757
|
-
await this.persistToDisk();
|
|
1758
|
-
logger_default.info(
|
|
1759
|
-
`Token pool health check done: checked=${checked}, live=${live}, invalid=${invalid}, disabled=${disabled}`
|
|
1760
|
-
);
|
|
1761
|
-
return { checked, live, invalid, disabled };
|
|
1762
|
-
} finally {
|
|
1763
|
-
this.healthChecking = false;
|
|
1764
|
-
}
|
|
1765
|
-
}
|
|
1766
|
-
startHealthCheckLoop() {
|
|
1767
|
-
if (!this.enabled || this.healthCheckIntervalMs <= 0) return;
|
|
1768
|
-
if (this.healthCheckTimer) clearInterval(this.healthCheckTimer);
|
|
1769
|
-
this.healthCheckTimer = setInterval(() => {
|
|
1770
|
-
this.runHealthCheck().catch((err) => {
|
|
1771
|
-
logger_default.warn(`Token pool health check failed: ${(err == null ? void 0 : err.message) || String(err)}`);
|
|
1772
|
-
});
|
|
1773
|
-
}, this.healthCheckIntervalMs);
|
|
1774
|
-
if (typeof this.healthCheckTimer.unref === "function") this.healthCheckTimer.unref();
|
|
1775
|
-
}
|
|
1776
|
-
async loadFromDisk() {
|
|
1777
|
-
await fs6.ensureDir(path6.dirname(this.filePath));
|
|
1778
|
-
if (!await fs6.pathExists(this.filePath)) {
|
|
1779
|
-
await this.persistToDisk();
|
|
1780
|
-
return;
|
|
1781
|
-
}
|
|
1782
|
-
let data = null;
|
|
1783
|
-
try {
|
|
1784
|
-
data = await fs6.readJson(this.filePath);
|
|
1785
|
-
} catch (err) {
|
|
1786
|
-
logger_default.warn(`Token pool file parse failed, fallback to empty: ${(err == null ? void 0 : err.message) || String(err)}`);
|
|
1787
|
-
data = null;
|
|
1788
|
-
}
|
|
1789
|
-
const items = Array.isArray(data == null ? void 0 : data.tokens) ? data.tokens : [];
|
|
1790
|
-
const nextMap = /* @__PURE__ */ new Map();
|
|
1791
|
-
for (const raw of items) {
|
|
1792
|
-
const token = String((raw == null ? void 0 : raw.token) || "").trim();
|
|
1793
|
-
if (!token) continue;
|
|
1794
|
-
const parsedRegion = parseRegionCode(raw == null ? void 0 : raw.region);
|
|
1795
|
-
nextMap.set(token, {
|
|
1796
|
-
token,
|
|
1797
|
-
region: parsedRegion || void 0,
|
|
1798
|
-
enabled: raw.enabled !== false,
|
|
1799
|
-
live: _8.isBoolean(raw.live) ? raw.live : void 0,
|
|
1800
|
-
lastCheckedAt: _8.isFinite(Number(raw.lastCheckedAt)) ? Number(raw.lastCheckedAt) : void 0,
|
|
1801
|
-
lastError: _8.isString(raw.lastError) ? raw.lastError : void 0,
|
|
1802
|
-
lastCredit: _8.isFinite(Number(raw.lastCredit)) ? Number(raw.lastCredit) : void 0,
|
|
1803
|
-
consecutiveFailures: Math.max(0, Number(raw.consecutiveFailures) || 0),
|
|
1804
|
-
allowedModels: this.normalizeStringArray(raw.allowedModels),
|
|
1805
|
-
capabilityTags: this.normalizeStringArray(raw.capabilityTags),
|
|
1806
|
-
dynamicCapabilities: this.normalizeDynamicCapabilities(raw.dynamicCapabilities)
|
|
1807
|
-
});
|
|
1808
|
-
}
|
|
1809
|
-
this.entryMap.clear();
|
|
1810
|
-
for (const [token, item] of nextMap.entries()) this.entryMap.set(token, item);
|
|
1811
|
-
}
|
|
1812
|
-
async persistToDisk() {
|
|
1813
|
-
await fs6.ensureDir(path6.dirname(this.filePath));
|
|
1814
|
-
const payload = {
|
|
1815
|
-
updatedAt: Date.now(),
|
|
1816
|
-
tokens: this.getEntries(false)
|
|
1817
|
-
};
|
|
1818
|
-
await fs6.writeJson(this.filePath, payload, { spaces: 2 });
|
|
1819
|
-
}
|
|
1820
|
-
maskToken(token) {
|
|
1821
|
-
if (token.length <= 10) return "***";
|
|
1822
|
-
return `${token.slice(0, 4)}...${token.slice(-4)}`;
|
|
1823
|
-
}
|
|
1824
|
-
parseAuthorizationTokens(authorization) {
|
|
1825
|
-
if (!_8.isString(authorization) || authorization.trim().length === 0) {
|
|
1826
|
-
return { tokens: [], error: null };
|
|
1827
|
-
}
|
|
1828
|
-
if (!/^Bearer\s+/i.test(authorization)) {
|
|
1829
|
-
return { tokens: [], error: "invalid_authorization_format" };
|
|
1830
|
-
}
|
|
1831
|
-
const tokens = authorization.replace(/^Bearer\s+/i, "").split(",").map((token) => token.trim()).filter(Boolean);
|
|
1832
|
-
if (tokens.length === 0) return { tokens: [], error: "empty_authorization_tokens" };
|
|
1833
|
-
return { tokens, error: null };
|
|
1834
|
-
}
|
|
1835
|
-
normalizeAddTokens(rawTokens, defaultRegion) {
|
|
1836
|
-
const normalized = [];
|
|
1837
|
-
for (const item of rawTokens) {
|
|
1838
|
-
if (_8.isString(item)) {
|
|
1839
|
-
const token2 = item.trim();
|
|
1840
|
-
if (!token2) continue;
|
|
1841
|
-
if (!defaultRegion) {
|
|
1842
|
-
throw new Error("\u65B0\u589E token \u5FC5\u987B\u6307\u5B9A region\uFF08\u901A\u8FC7 body.region \u6216 tokens[].region\uFF09");
|
|
1843
|
-
}
|
|
1844
|
-
normalized.push({ token: token2, region: defaultRegion, enabled: true });
|
|
1845
|
-
continue;
|
|
1846
|
-
}
|
|
1847
|
-
if (!item || typeof item !== "object") continue;
|
|
1848
|
-
const token = String(item.token || "").trim();
|
|
1849
|
-
if (!token) continue;
|
|
1850
|
-
const parsedRegion = parseRegionCode(item.region || defaultRegion);
|
|
1851
|
-
if (!parsedRegion) {
|
|
1852
|
-
throw new Error(`token ${this.maskToken(token)} \u7F3A\u5C11\u6709\u6548 region\uFF08\u4EC5\u652F\u6301 cn/us/hk/jp/sg\uFF09`);
|
|
1853
|
-
}
|
|
1854
|
-
normalized.push({
|
|
1855
|
-
token,
|
|
1856
|
-
region: parsedRegion,
|
|
1857
|
-
enabled: item.enabled,
|
|
1858
|
-
allowedModels: this.normalizeStringArray(item.allowedModels),
|
|
1859
|
-
capabilityTags: this.normalizeStringArray(item.capabilityTags)
|
|
1860
|
-
});
|
|
1861
|
-
}
|
|
1862
|
-
return normalized;
|
|
1863
|
-
}
|
|
1864
|
-
normalizeStringArray(value) {
|
|
1865
|
-
if (!Array.isArray(value)) return void 0;
|
|
1866
|
-
const items = value.map((item) => typeof item === "string" ? item.trim() : "").filter(Boolean);
|
|
1867
|
-
return items.length ? Array.from(new Set(items)) : void 0;
|
|
1868
|
-
}
|
|
1869
|
-
normalizeDynamicCapabilities(value) {
|
|
1870
|
-
if (!value || typeof value !== "object") return void 0;
|
|
1871
|
-
const data = value;
|
|
1872
|
-
const dynamic = {
|
|
1873
|
-
imageModels: this.normalizeStringArray(data.imageModels),
|
|
1874
|
-
videoModels: this.normalizeStringArray(data.videoModels),
|
|
1875
|
-
capabilityTags: this.normalizeStringArray(data.capabilityTags),
|
|
1876
|
-
updatedAt: _8.isFinite(Number(data.updatedAt)) ? Number(data.updatedAt) : void 0
|
|
1877
|
-
};
|
|
1878
|
-
if (!dynamic.imageModels && !dynamic.videoModels && !dynamic.capabilityTags && !dynamic.updatedAt) {
|
|
1879
|
-
return void 0;
|
|
1880
|
-
}
|
|
1881
|
-
return dynamic;
|
|
1882
|
-
}
|
|
1883
|
-
buildCandidateFromPoolEntry(entry) {
|
|
1884
|
-
return {
|
|
1885
|
-
token: entry.token,
|
|
1886
|
-
region: entry.region || null,
|
|
1887
|
-
allowedModels: entry.allowedModels,
|
|
1888
|
-
capabilityTags: entry.capabilityTags,
|
|
1889
|
-
dynamicCapabilities: entry.dynamicCapabilities,
|
|
1890
|
-
enabled: entry.enabled,
|
|
1891
|
-
live: entry.live !== false,
|
|
1892
|
-
prefixedToken: this.hasLegacyPrefix(entry.token)
|
|
1893
|
-
};
|
|
1894
|
-
}
|
|
1895
|
-
buildCandidateFromAuthToken(token, xRegion) {
|
|
1896
|
-
const entry = this.entryMap.get(token);
|
|
1897
|
-
if (entry) {
|
|
1898
|
-
return this.buildCandidateFromPoolEntry(entry);
|
|
1899
|
-
}
|
|
1900
|
-
return {
|
|
1901
|
-
token,
|
|
1902
|
-
region: xRegion,
|
|
1903
|
-
allowedModels: void 0,
|
|
1904
|
-
capabilityTags: void 0,
|
|
1905
|
-
dynamicCapabilities: void 0,
|
|
1906
|
-
enabled: true,
|
|
1907
|
-
live: true,
|
|
1908
|
-
prefixedToken: this.hasLegacyPrefix(token)
|
|
1909
|
-
};
|
|
1910
|
-
}
|
|
1911
|
-
hasLegacyPrefix(token) {
|
|
1912
|
-
const normalized = token.trim().toLowerCase();
|
|
1913
|
-
return normalized.startsWith("us-") || normalized.startsWith("hk-") || normalized.startsWith("jp-") || normalized.startsWith("sg-");
|
|
1914
|
-
}
|
|
1915
|
-
pickCandidate(candidates) {
|
|
1916
|
-
if (this.pickStrategy === "round_robin") {
|
|
1917
|
-
const item = candidates[this.roundRobinCursor % candidates.length];
|
|
1918
|
-
this.roundRobinCursor++;
|
|
1919
|
-
return item;
|
|
1920
|
-
}
|
|
1921
|
-
return _8.sample(candidates) || candidates[0];
|
|
1922
|
-
}
|
|
1923
|
-
matchesModelAndCapabilities(candidate, requestedModel, taskType, requiredCapabilityTags) {
|
|
1924
|
-
var _a, _b, _c, _d;
|
|
1925
|
-
if (!candidate.enabled || !candidate.live) return false;
|
|
1926
|
-
if (!candidate.region) return false;
|
|
1927
|
-
if ((_a = candidate.allowedModels) == null ? void 0 : _a.length) {
|
|
1928
|
-
if (!candidate.allowedModels.includes(requestedModel)) return false;
|
|
1929
|
-
} else {
|
|
1930
|
-
const dynamicModels = taskType === "image" ? (_b = candidate.dynamicCapabilities) == null ? void 0 : _b.imageModels : (_c = candidate.dynamicCapabilities) == null ? void 0 : _c.videoModels;
|
|
1931
|
-
if ((dynamicModels == null ? void 0 : dynamicModels.length) && !dynamicModels.includes(requestedModel)) return false;
|
|
1932
|
-
}
|
|
1933
|
-
if (requiredCapabilityTags.length) {
|
|
1934
|
-
const mergedTags = /* @__PURE__ */ new Set([
|
|
1935
|
-
...candidate.capabilityTags || [],
|
|
1936
|
-
...((_d = candidate.dynamicCapabilities) == null ? void 0 : _d.capabilityTags) || []
|
|
1937
|
-
]);
|
|
1938
|
-
for (const tag of requiredCapabilityTags) {
|
|
1939
|
-
if (!mergedTags.has(tag)) return false;
|
|
1940
|
-
}
|
|
1941
|
-
}
|
|
1942
|
-
return true;
|
|
1943
|
-
}
|
|
1944
|
-
async refreshDynamicCapabilitiesIfNeeded(item, regionInfo) {
|
|
1945
|
-
var _a;
|
|
1946
|
-
const lastUpdated = ((_a = item.dynamicCapabilities) == null ? void 0 : _a.updatedAt) || 0;
|
|
1947
|
-
if (Date.now() - lastUpdated < DYNAMIC_CAPABILITY_TTL_MS) return;
|
|
1948
|
-
try {
|
|
1949
|
-
const capabilities = await this.fetchDynamicCapabilities(item.token, regionInfo);
|
|
1950
|
-
item.dynamicCapabilities = {
|
|
1951
|
-
...capabilities,
|
|
1952
|
-
updatedAt: Date.now()
|
|
1953
|
-
};
|
|
1954
|
-
} catch (err) {
|
|
1955
|
-
item.lastError = `dynamic_capability_refresh_failed: ${(err == null ? void 0 : err.message) || String(err)}`;
|
|
1956
|
-
}
|
|
1957
|
-
}
|
|
1958
|
-
async fetchDynamicCapabilities(token, regionInfo) {
|
|
1959
|
-
const regionCode = regionInfo.isUS ? "us" : regionInfo.isHK ? "hk" : regionInfo.isJP ? "jp" : regionInfo.isSG ? "sg" : "cn";
|
|
1960
|
-
const reverseMap = this.getReverseModelMapByRegion(regionCode);
|
|
1961
|
-
const imageConfig = await request("post", "/mweb/v1/get_common_config", token, regionInfo, {
|
|
1962
|
-
data: {},
|
|
1963
|
-
params: { needCache: true, needRefresh: false }
|
|
1964
|
-
});
|
|
1965
|
-
const videoConfig = await request("post", "/mweb/v1/video_generate/get_common_config", token, regionInfo, {
|
|
1966
|
-
data: { scene: "generate_video", params: {} }
|
|
1967
|
-
});
|
|
1968
|
-
const imageReqKeys = Array.isArray(imageConfig == null ? void 0 : imageConfig.model_list) ? imageConfig.model_list.map((item) => typeof (item == null ? void 0 : item.model_req_key) === "string" ? item.model_req_key : "").filter(Boolean) : [];
|
|
1969
|
-
const videoReqKeys = Array.isArray(videoConfig == null ? void 0 : videoConfig.model_list) ? videoConfig.model_list.map((item) => typeof (item == null ? void 0 : item.model_req_key) === "string" ? item.model_req_key : "").filter(Boolean) : [];
|
|
1970
|
-
const imageModels = imageReqKeys.map((key) => reverseMap[key]).filter(Boolean);
|
|
1971
|
-
const videoModels = videoReqKeys.map((key) => reverseMap[key]).filter(Boolean);
|
|
1972
|
-
const capabilityTags = /* @__PURE__ */ new Set();
|
|
1973
|
-
for (const model of videoModels) {
|
|
1974
|
-
if (model.includes("seedance_40")) capabilityTags.add("omni_reference");
|
|
1975
|
-
if (model.includes("veo3")) capabilityTags.add("veo3");
|
|
1976
|
-
if (model.includes("sora2")) capabilityTags.add("sora2");
|
|
1977
|
-
}
|
|
1978
|
-
return {
|
|
1979
|
-
imageModels: imageModels.length ? Array.from(new Set(imageModels)) : void 0,
|
|
1980
|
-
videoModels: videoModels.length ? Array.from(new Set(videoModels)) : void 0,
|
|
1981
|
-
capabilityTags: capabilityTags.size ? Array.from(capabilityTags) : void 0
|
|
1982
|
-
};
|
|
1983
|
-
}
|
|
1984
|
-
getReverseModelMapByRegion(region) {
|
|
1985
|
-
const maps = region === "us" ? [IMAGE_MODEL_MAP_US, VIDEO_MODEL_MAP_US] : region === "hk" || region === "jp" || region === "sg" ? [IMAGE_MODEL_MAP_ASIA, VIDEO_MODEL_MAP_ASIA] : [IMAGE_MODEL_MAP, VIDEO_MODEL_MAP];
|
|
1986
|
-
const reverse = {};
|
|
1987
|
-
for (const map of maps) {
|
|
1988
|
-
for (const [modelId, reqKey] of Object.entries(map)) {
|
|
1989
|
-
reverse[reqKey] = modelId;
|
|
1990
|
-
}
|
|
1991
|
-
}
|
|
1992
|
-
return reverse;
|
|
1993
|
-
}
|
|
1994
|
-
};
|
|
1995
|
-
var session_pool_default = new TokenPool();
|
|
1996
|
-
|
|
1997
|
-
// src/api/controllers/models.ts
|
|
1998
|
-
var CACHE_TTL_MS = 10 * 60 * 1e3;
|
|
1999
|
-
var FALLBACK_TOKEN = "test_token";
|
|
2000
|
-
var modelCache = /* @__PURE__ */ new Map();
|
|
2001
|
-
function mapVideoDescription(id) {
|
|
2002
|
-
if (id.includes("veo3.1")) return "\u5373\u68A6AI\u89C6\u9891\u751F\u6210\u6A21\u578B veo3.1";
|
|
2003
|
-
if (id.includes("veo3")) return "\u5373\u68A6AI\u89C6\u9891\u751F\u6210\u6A21\u578B veo3";
|
|
2004
|
-
if (id.includes("sora2")) return "\u5373\u68A6AI\u89C6\u9891\u751F\u6210\u6A21\u578B sora2";
|
|
2005
|
-
if (id.includes("seedance-2.0-fast")) return "\u5373\u68A6AI\u89C6\u9891\u751F\u6210\u6A21\u578B seedance 2.0-fast";
|
|
2006
|
-
if (id.includes("seedance-2.0")) return "\u5373\u68A6AI\u89C6\u9891\u751F\u6210\u6A21\u578B seedance 2.0";
|
|
2007
|
-
if (id.includes("3.5-pro")) return "\u5373\u68A6AI\u89C6\u9891\u751F\u6210\u6A21\u578B 3.5 \u4E13\u4E1A\u7248";
|
|
2008
|
-
if (id.includes("3.0-fast")) return "\u5373\u68A6AI\u89C6\u9891\u751F\u6210\u6A21\u578B 3.0 \u6781\u901F\u7248";
|
|
2009
|
-
if (id.includes("3.0-pro")) return "\u5373\u68A6AI\u89C6\u9891\u751F\u6210\u6A21\u578B 3.0 \u4E13\u4E1A\u7248";
|
|
2010
|
-
if (id.includes("3.0")) return "\u5373\u68A6AI\u89C6\u9891\u751F\u6210\u6A21\u578B 3.0";
|
|
2011
|
-
if (id.includes("2.0-pro")) return "\u5373\u68A6AI\u89C6\u9891\u751F\u6210\u6A21\u578B 2.0 \u4E13\u4E1A\u7248";
|
|
2012
|
-
if (id.includes("2.0")) return "\u5373\u68A6AI\u89C6\u9891\u751F\u6210\u6A21\u578B 2.0";
|
|
2013
|
-
return void 0;
|
|
2014
|
-
}
|
|
2015
|
-
function mapImageDescription(id) {
|
|
2016
|
-
if (id.includes("5.0")) return "\u5373\u68A6AI\u56FE\u50CF\u6A21\u578B 5.0";
|
|
2017
|
-
if (id.includes("4.6")) return "\u5373\u68A6AI\u56FE\u50CF\u6A21\u578B 4.6";
|
|
2018
|
-
if (id.includes("4.5")) return "\u5373\u68A6AI\u56FE\u50CF\u6A21\u578B 4.5";
|
|
2019
|
-
if (id.includes("4.1")) return "\u5373\u68A6AI\u56FE\u50CF\u6A21\u578B 4.1";
|
|
2020
|
-
if (id.includes("4.0")) return "\u5373\u68A6AI\u56FE\u50CF\u6A21\u578B 4.0";
|
|
2021
|
-
if (id.includes("3.1")) return "\u5373\u68A6AI\u56FE\u50CF\u6A21\u578B 3.1";
|
|
2022
|
-
if (id.includes("3.0")) return "\u5373\u68A6AI\u56FE\u50CF\u6A21\u578B 3.0";
|
|
2023
|
-
return `\u5373\u68A6AI\u56FE\u50CF\u6A21\u578B ${id}`;
|
|
2024
|
-
}
|
|
2025
|
-
function buildModelItem(modelId, meta) {
|
|
2026
|
-
var _a;
|
|
2027
|
-
const modelType = modelId.startsWith("jimeng-video-") ? "video" : "image";
|
|
2028
|
-
const item = {
|
|
2029
|
-
id: modelId,
|
|
2030
|
-
object: "model",
|
|
2031
|
-
owned_by: "jimeng-cli",
|
|
2032
|
-
model_type: modelType
|
|
2033
|
-
};
|
|
2034
|
-
if (meta == null ? void 0 : meta.reqKey) item.model_req_key = meta.reqKey;
|
|
2035
|
-
if (meta == null ? void 0 : meta.modelName) item.model_name = meta.modelName;
|
|
2036
|
-
if ((_a = meta == null ? void 0 : meta.capabilities) == null ? void 0 : _a.length) item.capabilities = Array.from(new Set(meta.capabilities)).sort();
|
|
2037
|
-
if (meta == null ? void 0 : meta.modelTip) {
|
|
2038
|
-
item.description = meta.modelTip;
|
|
2039
|
-
} else if (modelType === "video") {
|
|
2040
|
-
item.description = mapVideoDescription(modelId);
|
|
2041
|
-
} else {
|
|
2042
|
-
item.description = mapImageDescription(modelId);
|
|
2043
|
-
}
|
|
2044
|
-
return item;
|
|
2045
|
-
}
|
|
2046
|
-
function parseFirstToken(authorization) {
|
|
2047
|
-
var _a;
|
|
2048
|
-
if (!authorization || !/^Bearer\s+/i.test(authorization)) return void 0;
|
|
2049
|
-
const raw = authorization.replace(/^Bearer\s+/i, "").trim();
|
|
2050
|
-
if (!raw) return void 0;
|
|
2051
|
-
const first = (_a = raw.split(",")[0]) == null ? void 0 : _a.trim();
|
|
2052
|
-
return first || void 0;
|
|
2053
|
-
}
|
|
2054
|
-
function resolveToken(authorization) {
|
|
2055
|
-
const fromAuth = parseFirstToken(authorization);
|
|
2056
|
-
if (fromAuth) return fromAuth;
|
|
2057
|
-
const fromPool = session_pool_default.getAllTokens({ onlyEnabled: true, preferLive: true })[0];
|
|
2058
|
-
return fromPool || void 0;
|
|
2059
|
-
}
|
|
2060
|
-
function getRegionalMaps(region) {
|
|
2061
|
-
if (region === "us") return [IMAGE_MODEL_MAP_US, VIDEO_MODEL_MAP_US];
|
|
2062
|
-
if (region === "hk" || region === "jp" || region === "sg") return [IMAGE_MODEL_MAP_ASIA, VIDEO_MODEL_MAP_ASIA];
|
|
2063
|
-
if (region === "cn") return [IMAGE_MODEL_MAP, VIDEO_MODEL_MAP];
|
|
2064
|
-
return [IMAGE_MODEL_MAP, IMAGE_MODEL_MAP_US, IMAGE_MODEL_MAP_ASIA, VIDEO_MODEL_MAP, VIDEO_MODEL_MAP_US, VIDEO_MODEL_MAP_ASIA];
|
|
2065
|
-
}
|
|
2066
|
-
function resolveRegion(authorization, xRegion) {
|
|
2067
|
-
var _a;
|
|
2068
|
-
const token = resolveToken(authorization);
|
|
2069
|
-
const parsedXRegion = parseRegionCode(xRegion);
|
|
2070
|
-
if (parsedXRegion) return parsedXRegion;
|
|
2071
|
-
if (token) {
|
|
2072
|
-
assertTokenWithoutRegionPrefix(token);
|
|
2073
|
-
const normalizedToken = parseProxyFromToken(token).token;
|
|
2074
|
-
const poolRegion = (_a = session_pool_default.getTokenEntry(normalizedToken)) == null ? void 0 : _a.region;
|
|
2075
|
-
if (poolRegion) return poolRegion;
|
|
2076
|
-
throw new Error("\u7F3A\u5C11 region\u3002token \u672A\u5728 pool \u4E2D\u6CE8\u518C\u65F6\uFF0C/v1/models \u9700\u8981\u63D0\u4F9B\u8BF7\u6C42\u5934 X-Region");
|
|
2077
|
-
}
|
|
2078
|
-
return "cn";
|
|
2079
|
-
}
|
|
2080
|
-
function buildReverseMap(region) {
|
|
2081
|
-
const reverse = {};
|
|
2082
|
-
for (const map of getRegionalMaps(region)) {
|
|
2083
|
-
for (const [modelId, upstreamKey] of Object.entries(map)) {
|
|
2084
|
-
reverse[upstreamKey] = modelId;
|
|
2085
|
-
}
|
|
2086
|
-
}
|
|
2087
|
-
return reverse;
|
|
2088
|
-
}
|
|
2089
|
-
function buildFallbackModels(region) {
|
|
2090
|
-
const maps = getRegionalMaps(region);
|
|
2091
|
-
const modelIds = Array.from(new Set(maps.flatMap((item) => Object.keys(item)))).sort();
|
|
2092
|
-
return modelIds.map((id) => buildModelItem(id));
|
|
2093
|
-
}
|
|
2094
|
-
function makeCacheKey(region) {
|
|
2095
|
-
return `models|${region}`;
|
|
2096
|
-
}
|
|
2097
|
-
function resolveFetchToken(token) {
|
|
2098
|
-
if (!token) return FALLBACK_TOKEN;
|
|
2099
|
-
const normalizedToken = parseProxyFromToken(token).token;
|
|
2100
|
-
assertTokenWithoutRegionPrefix(normalizedToken);
|
|
2101
|
-
return normalizedToken;
|
|
2102
|
-
}
|
|
2103
|
-
function extractCapabilities(item) {
|
|
2104
|
-
const features = Array.isArray(item.feats) ? item.feats.filter((feature) => typeof feature === "string" && feature.length > 0) : [];
|
|
2105
|
-
const options = Array.isArray(item.options) ? item.options.map(
|
|
2106
|
-
(option) => option && typeof option === "object" && typeof option.key === "string" ? option.key : void 0
|
|
2107
|
-
).filter((key) => typeof key === "string" && key.length > 0) : [];
|
|
2108
|
-
return Array.from(/* @__PURE__ */ new Set([...features, ...options]));
|
|
2109
|
-
}
|
|
2110
|
-
async function fetchConfigModelReqKeys(token, region) {
|
|
2111
|
-
const regionInfo = buildRegionInfo(region);
|
|
2112
|
-
const imageConfig = await request("post", "/mweb/v1/get_common_config", token, regionInfo, {
|
|
2113
|
-
data: {},
|
|
2114
|
-
params: { needCache: true, needRefresh: false }
|
|
2115
|
-
});
|
|
2116
|
-
const videoConfig = await request("post", "/mweb/v1/video_generate/get_common_config", token, regionInfo, {
|
|
2117
|
-
data: { scene: "generate_video", params: {} }
|
|
2118
|
-
});
|
|
2119
|
-
const imageModels = Array.isArray(imageConfig == null ? void 0 : imageConfig.model_list) ? imageConfig.model_list.map((item) => {
|
|
2120
|
-
const reqKey = item == null ? void 0 : item.model_req_key;
|
|
2121
|
-
if (typeof reqKey !== "string" || reqKey.length === 0) return void 0;
|
|
2122
|
-
return {
|
|
2123
|
-
reqKey,
|
|
2124
|
-
modelName: typeof (item == null ? void 0 : item.model_name) === "string" ? item.model_name : void 0,
|
|
2125
|
-
modelTip: typeof (item == null ? void 0 : item.model_tip) === "string" ? item.model_tip : void 0,
|
|
2126
|
-
capabilities: extractCapabilities(item)
|
|
2127
|
-
};
|
|
2128
|
-
}).filter((item) => Boolean(item)) : [];
|
|
2129
|
-
const videoModels = Array.isArray(videoConfig == null ? void 0 : videoConfig.model_list) ? videoConfig.model_list.map((item) => {
|
|
2130
|
-
const reqKey = item == null ? void 0 : item.model_req_key;
|
|
2131
|
-
if (typeof reqKey !== "string" || reqKey.length === 0) return void 0;
|
|
2132
|
-
return {
|
|
2133
|
-
reqKey,
|
|
2134
|
-
modelName: typeof (item == null ? void 0 : item.model_name) === "string" ? item.model_name : void 0,
|
|
2135
|
-
modelTip: typeof (item == null ? void 0 : item.model_tip) === "string" ? item.model_tip : void 0,
|
|
2136
|
-
capabilities: extractCapabilities(item)
|
|
2137
|
-
};
|
|
2138
|
-
}).filter((item) => Boolean(item)) : [];
|
|
2139
|
-
return { imageModels, videoModels };
|
|
2140
|
-
}
|
|
2141
|
-
async function getLiveModels(authorization, xRegion) {
|
|
2142
|
-
const region = resolveRegion(authorization, xRegion);
|
|
2143
|
-
const token = resolveToken(authorization);
|
|
2144
|
-
const effectiveToken = resolveFetchToken(token);
|
|
2145
|
-
const cacheKey = makeCacheKey(region);
|
|
2146
|
-
const cached = modelCache.get(cacheKey);
|
|
2147
|
-
if (cached && cached.expiresAt > Date.now()) {
|
|
2148
|
-
return { source: cached.source, data: cached.data };
|
|
2149
|
-
}
|
|
2150
|
-
try {
|
|
2151
|
-
const reverseMap = buildReverseMap(region);
|
|
2152
|
-
const { imageModels, videoModels } = await fetchConfigModelReqKeys(effectiveToken, region);
|
|
2153
|
-
const upstreamModels = [...imageModels, ...videoModels];
|
|
2154
|
-
const metaByModelId = /* @__PURE__ */ new Map();
|
|
2155
|
-
const mapped = upstreamModels.map((model) => {
|
|
2156
|
-
const modelId = reverseMap[model.reqKey];
|
|
2157
|
-
if (modelId && !metaByModelId.has(modelId)) {
|
|
2158
|
-
metaByModelId.set(modelId, model);
|
|
2159
|
-
}
|
|
2160
|
-
return modelId;
|
|
2161
|
-
}).filter((item) => typeof item === "string" && item.length > 0);
|
|
2162
|
-
const modelIds = Array.from(new Set(mapped)).sort();
|
|
2163
|
-
if (modelIds.length === 0) {
|
|
2164
|
-
throw new Error("model_req_key resolved but none matched local reverse map");
|
|
2165
|
-
}
|
|
2166
|
-
const data = modelIds.map((id) => buildModelItem(id, metaByModelId.get(id)));
|
|
2167
|
-
modelCache.set(cacheKey, {
|
|
2168
|
-
expiresAt: Date.now() + CACHE_TTL_MS,
|
|
2169
|
-
source: "upstream",
|
|
2170
|
-
data
|
|
2171
|
-
});
|
|
2172
|
-
return { source: "upstream", data };
|
|
2173
|
-
} catch {
|
|
2174
|
-
const data = buildFallbackModels(region);
|
|
2175
|
-
modelCache.set(cacheKey, {
|
|
2176
|
-
expiresAt: Date.now() + CACHE_TTL_MS,
|
|
2177
|
-
source: "fallback",
|
|
2178
|
-
data
|
|
2179
|
-
});
|
|
2180
|
-
return { source: "fallback", data };
|
|
2181
|
-
}
|
|
2182
|
-
}
|
|
2183
|
-
|
|
2184
|
-
// src/lib/smart-poller.ts
|
|
2185
|
-
var SmartPoller = class {
|
|
2186
|
-
pollCount = 0;
|
|
2187
|
-
startTime = Date.now();
|
|
2188
|
-
lastItemCount = 0;
|
|
2189
|
-
stableItemCountRounds = 0;
|
|
2190
|
-
options;
|
|
2191
|
-
constructor(options = {}) {
|
|
2192
|
-
this.options = {
|
|
2193
|
-
maxPollCount: options.maxPollCount ?? POLLING_CONFIG.MAX_POLL_COUNT,
|
|
2194
|
-
pollInterval: options.pollInterval ?? POLLING_CONFIG.POLL_INTERVAL,
|
|
2195
|
-
stableRounds: options.stableRounds ?? POLLING_CONFIG.STABLE_ROUNDS,
|
|
2196
|
-
timeoutSeconds: options.timeoutSeconds ?? POLLING_CONFIG.TIMEOUT_SECONDS,
|
|
2197
|
-
expectedItemCount: options.expectedItemCount ?? 4,
|
|
2198
|
-
type: options.type ?? "image"
|
|
2199
|
-
};
|
|
2200
|
-
}
|
|
2201
|
-
/**
|
|
2202
|
-
* 获取状态名称
|
|
2203
|
-
*/
|
|
2204
|
-
getStatusName(status) {
|
|
2205
|
-
return STATUS_CODE_MAP[status] || `UNKNOWN(${status})`;
|
|
2206
|
-
}
|
|
2207
|
-
/**
|
|
2208
|
-
* 根据状态码计算智能轮询间隔
|
|
2209
|
-
*/
|
|
2210
|
-
getSmartInterval(status, itemCount) {
|
|
2211
|
-
const baseInterval = this.options.pollInterval;
|
|
2212
|
-
switch (status) {
|
|
2213
|
-
case 20:
|
|
2214
|
-
return baseInterval;
|
|
2215
|
-
case 42:
|
|
2216
|
-
return baseInterval * 1.2;
|
|
2217
|
-
case 45:
|
|
2218
|
-
return baseInterval * 1.5;
|
|
2219
|
-
case 50:
|
|
2220
|
-
return baseInterval * 0.5;
|
|
2221
|
-
case 10:
|
|
2222
|
-
return 0;
|
|
2223
|
-
case 30:
|
|
2224
|
-
return 0;
|
|
2225
|
-
default:
|
|
2226
|
-
return baseInterval;
|
|
2227
|
-
}
|
|
2228
|
-
}
|
|
2229
|
-
/**
|
|
2230
|
-
* 检查是否应该退出轮询
|
|
2231
|
-
*/
|
|
2232
|
-
shouldExitPolling(pollingStatus) {
|
|
2233
|
-
const { status, itemCount } = pollingStatus;
|
|
2234
|
-
const elapsedTime = Math.round((Date.now() - this.startTime) / 1e3);
|
|
2235
|
-
if (itemCount === this.lastItemCount) {
|
|
2236
|
-
this.stableItemCountRounds++;
|
|
2237
|
-
} else {
|
|
2238
|
-
this.stableItemCountRounds = 0;
|
|
2239
|
-
this.lastItemCount = itemCount;
|
|
2240
|
-
}
|
|
2241
|
-
if (status === 10 || status === 50) {
|
|
2242
|
-
return { shouldExit: true, reason: "\u4EFB\u52A1\u6210\u529F\u5B8C\u6210" };
|
|
2243
|
-
}
|
|
2244
|
-
if (status === 30) {
|
|
2245
|
-
return { shouldExit: true, reason: "\u4EFB\u52A1\u5931\u8D25" };
|
|
2246
|
-
}
|
|
2247
|
-
if (itemCount >= this.options.expectedItemCount && (status === 10 || status === 50)) {
|
|
2248
|
-
return { shouldExit: true, reason: `\u5DF2\u83B7\u5F97\u5B8C\u6574\u7ED3\u679C\u96C6(${itemCount}/${this.options.expectedItemCount})` };
|
|
2249
|
-
}
|
|
2250
|
-
if (this.pollCount >= this.options.maxPollCount) {
|
|
2251
|
-
return { shouldExit: true, reason: "\u8F6E\u8BE2\u6B21\u6570\u8D85\u9650" };
|
|
2252
|
-
}
|
|
2253
|
-
if (elapsedTime >= this.options.timeoutSeconds && itemCount > 0) {
|
|
2254
|
-
return { shouldExit: true, reason: "\u65F6\u95F4\u8D85\u9650\u4F46\u5DF2\u6709\u7ED3\u679C" };
|
|
2255
|
-
}
|
|
2256
|
-
return { shouldExit: false, reason: "" };
|
|
2257
|
-
}
|
|
2258
|
-
/**
|
|
2259
|
-
* 执行单次轮询检查
|
|
2260
|
-
*/
|
|
2261
|
-
async poll(pollFunction, historyId) {
|
|
2262
|
-
var _a, _b, _c, _d, _e;
|
|
2263
|
-
logger_default.info(`\u5F00\u59CB\u667A\u80FD\u8F6E\u8BE2: historyId=${historyId || "N/A"}, \u6700\u5927\u8F6E\u8BE2\u6B21\u6570=${this.options.maxPollCount}, \u671F\u671B\u7ED3\u679C\u6570=${this.options.expectedItemCount}`);
|
|
2264
|
-
let lastData;
|
|
2265
|
-
let lastStatus = { status: 20, itemCount: 0 };
|
|
2266
|
-
while (true) {
|
|
2267
|
-
this.pollCount++;
|
|
2268
|
-
const elapsedTime = Math.round((Date.now() - this.startTime) / 1e3);
|
|
2269
|
-
try {
|
|
2270
|
-
const { status, data } = await pollFunction();
|
|
2271
|
-
lastStatus = status;
|
|
2272
|
-
lastData = data;
|
|
2273
|
-
logger_default.info(`\u8F6E\u8BE2 ${this.pollCount}/${this.options.maxPollCount}: status=${status.status}(${this.getStatusName(status.status)}), failCode=${status.failCode || "none"}, items=${status.itemCount}, elapsed=${elapsedTime}s, finish_time=${status.finishTime || 0}, stable=${this.stableItemCountRounds}/${this.options.stableRounds}`);
|
|
2274
|
-
if (status.itemCount > 0) {
|
|
2275
|
-
logger_default.info(`\u68C0\u6D4B\u5230${this.options.type === "image" ? "\u56FE\u7247" : "\u89C6\u9891"}\u751F\u6210: \u6570\u91CF=${status.itemCount}, \u72B6\u6001=${this.getStatusName(status.status)}`);
|
|
2276
|
-
}
|
|
2277
|
-
const { shouldExit, reason } = this.shouldExitPolling(status);
|
|
2278
|
-
if (shouldExit) {
|
|
2279
|
-
logger_default.info(`\u9000\u51FA\u8F6E\u8BE2: ${reason}, \u6700\u7EC8${this.options.type === "image" ? "\u56FE\u7247" : "\u89C6\u9891"}\u6570\u91CF=${status.itemCount}`);
|
|
2280
|
-
if (status.status === 30) {
|
|
2281
|
-
handleGenerationFailure(status.status, status.failCode, historyId, this.options.type, status.itemCount);
|
|
2282
|
-
}
|
|
2283
|
-
if (reason === "\u8F6E\u8BE2\u6B21\u6570\u8D85\u9650" || reason === "\u65F6\u95F4\u8D85\u9650\u4F46\u5DF2\u6709\u7ED3\u679C") {
|
|
2284
|
-
handlePollingTimeout(
|
|
2285
|
-
this.pollCount,
|
|
2286
|
-
this.options.maxPollCount,
|
|
2287
|
-
elapsedTime,
|
|
2288
|
-
status.status,
|
|
2289
|
-
status.itemCount,
|
|
2290
|
-
historyId
|
|
2291
|
-
);
|
|
2292
|
-
}
|
|
2293
|
-
break;
|
|
2294
|
-
}
|
|
2295
|
-
if (![20, 42, 45, 10, 30, 50].includes(status.status)) {
|
|
2296
|
-
logger_default.warn(`\u68C0\u6D4B\u5230\u672A\u77E5\u72B6\u6001\u7801 ${status.status}(${this.getStatusName(status.status)})\uFF0C\u7EE7\u7EED\u8F6E\u8BE2\u7B49\u5F85\u751F\u6210...`);
|
|
2297
|
-
}
|
|
2298
|
-
if (this.pollCount % 30 === 0) {
|
|
2299
|
-
logger_default.info(`${this.options.type === "image" ? "\u56FE\u50CF" : "\u89C6\u9891"}\u751F\u6210\u8FDB\u5EA6: \u7B2C ${this.pollCount} \u6B21\u8F6E\u8BE2\uFF0C\u72B6\u6001: ${this.getStatusName(status.status)}\uFF0C\u5DF2\u7B49\u5F85 ${elapsedTime} \u79D2...`);
|
|
2300
|
-
}
|
|
2301
|
-
const nextInterval = this.getSmartInterval(status.status, status.itemCount);
|
|
2302
|
-
if (nextInterval > 0) {
|
|
2303
|
-
await new Promise((resolve) => setTimeout(resolve, nextInterval));
|
|
2304
|
-
}
|
|
2305
|
-
} catch (error) {
|
|
2306
|
-
const retryableErrorCodes = [
|
|
2307
|
-
"ECONNABORTED",
|
|
2308
|
-
"ETIMEDOUT",
|
|
2309
|
-
"ECONNRESET",
|
|
2310
|
-
"ENOTFOUND",
|
|
2311
|
-
"ECONNREFUSED",
|
|
2312
|
-
"EAI_AGAIN",
|
|
2313
|
-
"EPIPE",
|
|
2314
|
-
"ENETUNREACH",
|
|
2315
|
-
"EHOSTUNREACH"
|
|
2316
|
-
];
|
|
2317
|
-
const isRetryableError = retryableErrorCodes.includes(error.code) || ((_a = error.message) == null ? void 0 : _a.includes("timeout")) || ((_b = error.message) == null ? void 0 : _b.includes("network")) || ((_c = error.message) == null ? void 0 : _c.includes("ECONNRESET")) || ((_d = error.message) == null ? void 0 : _d.includes("socket hang up")) || ((_e = error.message) == null ? void 0 : _e.includes("Proxy connection"));
|
|
2318
|
-
if (isRetryableError && this.pollCount < this.options.maxPollCount) {
|
|
2319
|
-
logger_default.warn(`\u8F6E\u8BE2\u8FC7\u7A0B\u4E2D\u53D1\u751F\u7F51\u7EDC\u9519\u8BEF (${error.code || error.message})\uFF0C\u7B49\u5F85\u540E\u7EE7\u7EED\u8F6E\u8BE2...`);
|
|
2320
|
-
await new Promise((resolve) => setTimeout(resolve, this.options.pollInterval));
|
|
2321
|
-
continue;
|
|
2322
|
-
}
|
|
2323
|
-
logger_default.error(`\u8F6E\u8BE2\u8FC7\u7A0B\u4E2D\u53D1\u751F\u4E0D\u53EF\u6062\u590D\u7684\u9519\u8BEF: ${error.message}`);
|
|
2324
|
-
throw error;
|
|
2325
|
-
}
|
|
2326
|
-
}
|
|
2327
|
-
const finalElapsedTime = Math.round((Date.now() - this.startTime) / 1e3);
|
|
2328
|
-
const result = {
|
|
2329
|
-
status: lastStatus.status,
|
|
2330
|
-
failCode: lastStatus.failCode,
|
|
2331
|
-
itemCount: lastStatus.itemCount,
|
|
2332
|
-
elapsedTime: finalElapsedTime,
|
|
2333
|
-
pollCount: this.pollCount,
|
|
2334
|
-
exitReason: this.shouldExitPolling(lastStatus).reason
|
|
2335
|
-
};
|
|
2336
|
-
logger_default.info(`${this.options.type === "image" ? "\u56FE\u50CF" : "\u89C6\u9891"}\u751F\u6210\u5B8C\u6210: \u6210\u529F\u751F\u6210 ${lastStatus.itemCount} \u4E2A\u7ED3\u679C\uFF0C\u603B\u8017\u65F6 ${finalElapsedTime} \u79D2\uFF0C\u6700\u7EC8\u72B6\u6001: ${this.getStatusName(lastStatus.status)}`);
|
|
2337
|
-
return { result, data: lastData };
|
|
2338
|
-
}
|
|
2339
|
-
};
|
|
2340
|
-
|
|
2341
|
-
// src/api/controllers/task-common.ts
|
|
2342
|
-
function buildPendingTaskInfo(taskId, type) {
|
|
2343
|
-
return {
|
|
2344
|
-
task_id: taskId,
|
|
2345
|
-
type,
|
|
2346
|
-
status: 20,
|
|
2347
|
-
fail_code: null,
|
|
2348
|
-
created: util_default.unixTimestamp(),
|
|
2349
|
-
data: null
|
|
2350
|
-
};
|
|
2351
|
-
}
|
|
2352
|
-
function buildPollerOptions(waitTimeoutSeconds, pollIntervalMs, defaultTimeoutSeconds, defaultPollIntervalMs, defaultMaxPollCount) {
|
|
2353
|
-
const timeoutSeconds = Number.isFinite(waitTimeoutSeconds) && waitTimeoutSeconds > 0 ? Math.floor(waitTimeoutSeconds) : defaultTimeoutSeconds;
|
|
2354
|
-
const pollInterval = Number.isFinite(pollIntervalMs) && pollIntervalMs > 0 ? Math.floor(pollIntervalMs) : defaultPollIntervalMs;
|
|
2355
|
-
const computedMaxPollCount = Math.max(1, Math.ceil(timeoutSeconds * 1e3 / pollInterval));
|
|
2356
|
-
return {
|
|
2357
|
-
timeoutSeconds,
|
|
2358
|
-
pollInterval,
|
|
2359
|
-
maxPollCount: Math.max(defaultMaxPollCount, computedMaxPollCount)
|
|
2360
|
-
};
|
|
2361
|
-
}
|
|
2362
|
-
|
|
2363
|
-
// src/lib/image-utils.ts
|
|
2364
|
-
function extractImageUrl(item, index) {
|
|
2365
|
-
var _a, _b, _c;
|
|
2366
|
-
const logPrefix = index !== void 0 ? `\u56FE\u7247 ${index + 1}` : "\u56FE\u7247";
|
|
2367
|
-
if ((_c = (_b = (_a = item == null ? void 0 : item.image) == null ? void 0 : _a.large_images) == null ? void 0 : _b[0]) == null ? void 0 : _c.image_url) {
|
|
2368
|
-
let imageUrl = item.image.large_images[0].image_url;
|
|
2369
|
-
imageUrl = imageUrl.replace(/\\u0026/g, "&");
|
|
2370
|
-
logger_default.debug(`${logPrefix}: \u4F7F\u7528 large_images URL`);
|
|
2371
|
-
return imageUrl;
|
|
2372
|
-
}
|
|
2373
|
-
logger_default.warn(`${logPrefix}: \u65E0\u6CD5\u63D0\u53D6URL\uFF0C\u7F3A\u5C11 image.large_images[0].image_url \u5B57\u6BB5\u3002item\u7ED3\u6784: ${JSON.stringify(item, null, 2)}`);
|
|
2374
|
-
return null;
|
|
2375
|
-
}
|
|
2376
|
-
function extractImageUrls(itemList) {
|
|
2377
|
-
return itemList.map((item, index) => extractImageUrl(item, index)).filter((url) => url !== null);
|
|
2378
|
-
}
|
|
2379
|
-
function extractVideoUrl(item) {
|
|
2380
|
-
var _a, _b, _c, _d, _e, _f;
|
|
2381
|
-
if ((_c = (_b = (_a = item == null ? void 0 : item.video) == null ? void 0 : _a.transcoded_video) == null ? void 0 : _b.origin) == null ? void 0 : _c.video_url) {
|
|
2382
|
-
return item.video.transcoded_video.origin.video_url;
|
|
2383
|
-
}
|
|
2384
|
-
if ((_d = item == null ? void 0 : item.video) == null ? void 0 : _d.play_url) {
|
|
2385
|
-
return item.video.play_url;
|
|
2386
|
-
}
|
|
2387
|
-
if ((_e = item == null ? void 0 : item.video) == null ? void 0 : _e.download_url) {
|
|
2388
|
-
return item.video.download_url;
|
|
2389
|
-
}
|
|
2390
|
-
if ((_f = item == null ? void 0 : item.video) == null ? void 0 : _f.url) {
|
|
2391
|
-
return item.video.url;
|
|
2392
|
-
}
|
|
2393
|
-
return null;
|
|
2394
|
-
}
|
|
2395
|
-
async function fetchHighQualityVideoUrl(itemId, refreshToken, regionInfo) {
|
|
2396
|
-
var _a, _b, _c, _d, _e, _f;
|
|
2397
|
-
try {
|
|
2398
|
-
logger_default.info(`\u5C1D\u8BD5\u83B7\u53D6\u9AD8\u8D28\u91CF\u89C6\u9891\u4E0B\u8F7DURL\uFF0Citem_id: ${itemId}`);
|
|
2399
|
-
const result = await request("post", "/mweb/v1/get_local_item_list", refreshToken, regionInfo, {
|
|
2400
|
-
data: {
|
|
2401
|
-
item_id_list: [itemId],
|
|
2402
|
-
pack_item_opt: {
|
|
2403
|
-
scene: 1,
|
|
2404
|
-
need_data_integrity: true
|
|
2405
|
-
},
|
|
2406
|
-
is_for_video_download: true
|
|
2407
|
-
}
|
|
2408
|
-
});
|
|
2409
|
-
const responseStr = JSON.stringify(result);
|
|
2410
|
-
logger_default.info(`get_local_item_list \u54CD\u5E94\u5927\u5C0F: ${responseStr.length} \u5B57\u7B26`);
|
|
2411
|
-
const itemList = result.item_list || result.local_item_list || [];
|
|
2412
|
-
if (itemList.length > 0) {
|
|
2413
|
-
const item = itemList[0];
|
|
2414
|
-
const videoUrl = ((_c = (_b = (_a = item == null ? void 0 : item.video) == null ? void 0 : _a.transcoded_video) == null ? void 0 : _b.origin) == null ? void 0 : _c.video_url) || ((_d = item == null ? void 0 : item.video) == null ? void 0 : _d.download_url) || ((_e = item == null ? void 0 : item.video) == null ? void 0 : _e.play_url) || ((_f = item == null ? void 0 : item.video) == null ? void 0 : _f.url);
|
|
2415
|
-
if (videoUrl) {
|
|
2416
|
-
logger_default.info(`\u4ECEget_local_item_list\u7ED3\u6784\u5316\u5B57\u6BB5\u83B7\u53D6\u5230\u9AD8\u6E05\u89C6\u9891URL: ${videoUrl}`);
|
|
2417
|
-
return videoUrl;
|
|
2418
|
-
}
|
|
2419
|
-
}
|
|
2420
|
-
const hqUrlMatch = responseStr.match(/https:\/\/v[0-9]+-dreamnia\.jimeng\.com\/[^"\s\\]+/);
|
|
2421
|
-
if (hqUrlMatch && hqUrlMatch[0]) {
|
|
2422
|
-
logger_default.info(`\u6B63\u5219\u63D0\u53D6\u5230\u9AD8\u8D28\u91CF\u89C6\u9891URL (dreamnia): ${hqUrlMatch[0]}`);
|
|
2423
|
-
return hqUrlMatch[0];
|
|
2424
|
-
}
|
|
2425
|
-
const jimengUrlMatch = responseStr.match(/https:\/\/v[0-9]+-[^"\\]*\.jimeng\.com\/[^"\s\\]+/);
|
|
2426
|
-
if (jimengUrlMatch && jimengUrlMatch[0]) {
|
|
2427
|
-
logger_default.info(`\u6B63\u5219\u63D0\u53D6\u5230jimeng\u89C6\u9891URL: ${jimengUrlMatch[0]}`);
|
|
2428
|
-
return jimengUrlMatch[0];
|
|
2429
|
-
}
|
|
2430
|
-
const anyVideoUrlMatch = responseStr.match(/https:\/\/v[0-9]+-[^"\\]*\.(vlabvod|jimeng)\.com\/[^"\s\\]+/);
|
|
2431
|
-
if (anyVideoUrlMatch && anyVideoUrlMatch[0]) {
|
|
2432
|
-
logger_default.info(`\u4ECEget_local_item_list\u63D0\u53D6\u5230\u89C6\u9891URL: ${anyVideoUrlMatch[0]}`);
|
|
2433
|
-
return anyVideoUrlMatch[0];
|
|
2434
|
-
}
|
|
2435
|
-
logger_default.warn(`\u672A\u80FD\u4ECEget_local_item_list\u54CD\u5E94\u4E2D\u63D0\u53D6\u5230\u89C6\u9891URL`);
|
|
2436
|
-
return null;
|
|
2437
|
-
} catch (error) {
|
|
2438
|
-
logger_default.warn(`\u83B7\u53D6\u9AD8\u8D28\u91CF\u89C6\u9891\u4E0B\u8F7DURL\u5931\u8D25: ${error.message}`);
|
|
2439
|
-
return null;
|
|
2440
|
-
}
|
|
2441
|
-
}
|
|
2442
|
-
|
|
2443
|
-
// src/api/controllers/tasks.ts
|
|
2444
|
-
var IMAGE_INFO_PAYLOAD = {
|
|
2445
|
-
width: 2048,
|
|
2446
|
-
height: 2048,
|
|
2447
|
-
format: "webp",
|
|
2448
|
-
image_scene_list: [
|
|
2449
|
-
{ scene: "smart_crop", width: 360, height: 360, uniq_key: "smart_crop-w:360-h:360", format: "webp" },
|
|
2450
|
-
{ scene: "smart_crop", width: 480, height: 480, uniq_key: "smart_crop-w:480-h:480", format: "webp" },
|
|
2451
|
-
{ scene: "smart_crop", width: 720, height: 720, uniq_key: "smart_crop-w:720-h:720", format: "webp" },
|
|
2452
|
-
{ scene: "smart_crop", width: 720, height: 480, uniq_key: "smart_crop-w:720-h:480", format: "webp" },
|
|
2453
|
-
{ scene: "normal", width: 2400, height: 2400, uniq_key: "2400", format: "webp" },
|
|
2454
|
-
{ scene: "normal", width: 1080, height: 1080, uniq_key: "1080", format: "webp" },
|
|
2455
|
-
{ scene: "normal", width: 720, height: 720, uniq_key: "720", format: "webp" },
|
|
2456
|
-
{ scene: "normal", width: 480, height: 480, uniq_key: "480", format: "webp" },
|
|
2457
|
-
{ scene: "normal", width: 360, height: 360, uniq_key: "360", format: "webp" }
|
|
2458
|
-
]
|
|
2459
|
-
};
|
|
2460
|
-
function inferTaskType(task, fallback) {
|
|
2461
|
-
var _a;
|
|
2462
|
-
if (fallback) return fallback;
|
|
2463
|
-
const firstItem = (_a = task == null ? void 0 : task.item_list) == null ? void 0 : _a[0];
|
|
2464
|
-
if (firstItem == null ? void 0 : firstItem.video) return "video";
|
|
2465
|
-
return "image";
|
|
2466
|
-
}
|
|
2467
|
-
async function getHistoryTaskById(taskId, refreshToken, regionInfo) {
|
|
2468
|
-
const result = await request("post", "/mweb/v1/get_history_by_ids", refreshToken, regionInfo, {
|
|
2469
|
-
data: {
|
|
2470
|
-
history_ids: [taskId],
|
|
2471
|
-
image_info: IMAGE_INFO_PAYLOAD
|
|
2472
|
-
}
|
|
2473
|
-
});
|
|
2474
|
-
const task = result == null ? void 0 : result[taskId];
|
|
2475
|
-
if (!task) {
|
|
2476
|
-
throw new APIException(exceptions_default.API_REQUEST_FAILED, `\u4EFB\u52A1\u4E0D\u5B58\u5728: ${taskId}`);
|
|
2477
|
-
}
|
|
2478
|
-
return task;
|
|
2479
|
-
}
|
|
2480
|
-
async function buildTaskData(type, task, responseFormat) {
|
|
2481
|
-
const itemList = Array.isArray(task == null ? void 0 : task.item_list) ? task.item_list : [];
|
|
2482
|
-
if (itemList.length === 0) return null;
|
|
2483
|
-
if (type === "image") {
|
|
2484
|
-
const imageUrls = extractImageUrls(itemList);
|
|
2485
|
-
if (imageUrls.length === 0) return null;
|
|
2486
|
-
if (responseFormat === "b64_json") {
|
|
2487
|
-
const encoded = await Promise.all(imageUrls.map((url) => util_default.fetchFileBASE64(url)));
|
|
2488
|
-
return encoded.map((b64) => ({ b64_json: b64 }));
|
|
2489
|
-
}
|
|
2490
|
-
return imageUrls.map((url) => ({ url }));
|
|
2491
|
-
}
|
|
2492
|
-
const videoUrl = extractVideoUrl(itemList[0]);
|
|
2493
|
-
if (!videoUrl) return null;
|
|
2494
|
-
if (responseFormat === "b64_json") {
|
|
2495
|
-
return [{ b64_json: await util_default.fetchFileBASE64(videoUrl) }];
|
|
2496
|
-
}
|
|
2497
|
-
return [{ url: videoUrl }];
|
|
2498
|
-
}
|
|
2499
|
-
async function getTaskResponse(taskId, refreshToken, regionInfo, options = {}) {
|
|
2500
|
-
const task = await getHistoryTaskById(taskId, refreshToken, regionInfo);
|
|
2501
|
-
const type = inferTaskType(task, options.type);
|
|
2502
|
-
const responseFormat = options.responseFormat || "url";
|
|
2503
|
-
return {
|
|
2504
|
-
task_id: taskId,
|
|
2505
|
-
type,
|
|
2506
|
-
status: typeof (task == null ? void 0 : task.status) === "number" ? task.status : 20,
|
|
2507
|
-
fail_code: typeof (task == null ? void 0 : task.fail_code) === "string" ? task.fail_code : null,
|
|
2508
|
-
created: util_default.unixTimestamp(),
|
|
2509
|
-
data: await buildTaskData(type, task, responseFormat)
|
|
2510
|
-
};
|
|
2511
|
-
}
|
|
2512
|
-
async function waitForTaskResponse(taskId, refreshToken, regionInfo, options = {}) {
|
|
2513
|
-
var _a, _b;
|
|
2514
|
-
const responseFormat = options.responseFormat || "url";
|
|
2515
|
-
const defaultTimeoutSeconds = options.type === "video" ? 3600 : 1800;
|
|
2516
|
-
const defaultPollIntervalMs = options.type === "video" ? 2e4 : 1e4;
|
|
2517
|
-
const pollerOptions = buildPollerOptions(
|
|
2518
|
-
options.waitTimeoutSeconds,
|
|
2519
|
-
options.pollIntervalMs,
|
|
2520
|
-
defaultTimeoutSeconds,
|
|
2521
|
-
defaultPollIntervalMs,
|
|
2522
|
-
900
|
|
2523
|
-
);
|
|
2524
|
-
const poller = new SmartPoller({
|
|
2525
|
-
maxPollCount: pollerOptions.maxPollCount,
|
|
2526
|
-
pollInterval: pollerOptions.pollInterval,
|
|
2527
|
-
expectedItemCount: 1,
|
|
2528
|
-
type: options.type || "image",
|
|
2529
|
-
timeoutSeconds: pollerOptions.timeoutSeconds
|
|
2530
|
-
});
|
|
2531
|
-
const { data: taskData } = await poller.poll(async () => {
|
|
2532
|
-
var _a2;
|
|
2533
|
-
const task = await getHistoryTaskById(taskId, refreshToken, regionInfo);
|
|
2534
|
-
const type = inferTaskType(task, options.type);
|
|
2535
|
-
const itemList = Array.isArray(task == null ? void 0 : task.item_list) ? task.item_list : [];
|
|
2536
|
-
const itemCount = itemList.length;
|
|
2537
|
-
return {
|
|
2538
|
-
status: {
|
|
2539
|
-
status: typeof (task == null ? void 0 : task.status) === "number" ? task.status : 20,
|
|
2540
|
-
failCode: typeof (task == null ? void 0 : task.fail_code) === "string" ? task.fail_code : void 0,
|
|
2541
|
-
itemCount,
|
|
2542
|
-
finishTime: ((_a2 = task == null ? void 0 : task.task) == null ? void 0 : _a2.finish_time) || 0,
|
|
2543
|
-
historyId: taskId
|
|
2544
|
-
},
|
|
2545
|
-
data: { task, type }
|
|
2546
|
-
};
|
|
2547
|
-
}, taskId);
|
|
2548
|
-
const finalType = inferTaskType(taskData.task, taskData.type);
|
|
2549
|
-
return {
|
|
2550
|
-
task_id: taskId,
|
|
2551
|
-
type: finalType,
|
|
2552
|
-
status: typeof ((_a = taskData.task) == null ? void 0 : _a.status) === "number" ? taskData.task.status : 20,
|
|
2553
|
-
fail_code: typeof ((_b = taskData.task) == null ? void 0 : _b.fail_code) === "string" ? taskData.task.fail_code : null,
|
|
2554
|
-
created: util_default.unixTimestamp(),
|
|
2555
|
-
data: await buildTaskData(finalType, taskData.task, responseFormat)
|
|
2556
|
-
};
|
|
2557
|
-
}
|
|
2558
|
-
|
|
2559
|
-
// src/lib/image-uploader.ts
|
|
2560
|
-
import crypto3 from "crypto";
|
|
2561
|
-
import axios3 from "axios";
|
|
2562
|
-
|
|
2563
|
-
// src/lib/region-utils.ts
|
|
2564
|
-
var RegionUtils = class {
|
|
2565
|
-
/**
|
|
2566
|
-
* 获取ServiceId
|
|
2567
|
-
*/
|
|
2568
|
-
static getServiceId(regionInfo, providedServiceId) {
|
|
2569
|
-
if (providedServiceId) {
|
|
2570
|
-
return providedServiceId;
|
|
2571
|
-
}
|
|
2572
|
-
if (regionInfo.isUS || regionInfo.isHK || regionInfo.isJP || regionInfo.isSG) {
|
|
2573
|
-
return "wopfjsm1ax";
|
|
2574
|
-
}
|
|
2575
|
-
return "tb4s082cfz";
|
|
2576
|
-
}
|
|
2577
|
-
/**
|
|
2578
|
-
* 获取ImageX URL
|
|
2579
|
-
*/
|
|
2580
|
-
static getImageXUrl(regionInfo) {
|
|
2581
|
-
if (regionInfo.isUS) {
|
|
2582
|
-
return BASE_URL_IMAGEX_US;
|
|
2583
|
-
}
|
|
2584
|
-
if (regionInfo.isHK || regionInfo.isJP || regionInfo.isSG) {
|
|
2585
|
-
return BASE_URL_IMAGEX_HK;
|
|
2586
|
-
}
|
|
2587
|
-
return "https://imagex.bytedanceapi.com";
|
|
2588
|
-
}
|
|
2589
|
-
/**
|
|
2590
|
-
* 获取Origin
|
|
2591
|
-
*/
|
|
2592
|
-
static getOrigin(regionInfo) {
|
|
2593
|
-
if (regionInfo.isUS) {
|
|
2594
|
-
return new URL(BASE_URL_DREAMINA_US).origin;
|
|
2595
|
-
}
|
|
2596
|
-
if (regionInfo.isHK || regionInfo.isJP || regionInfo.isSG) {
|
|
2597
|
-
return new URL(BASE_URL_DREAMINA_HK).origin;
|
|
2598
|
-
}
|
|
2599
|
-
return "https://jimeng.jianying.com";
|
|
2600
|
-
}
|
|
2601
|
-
/**
|
|
2602
|
-
* 获取AWS区域
|
|
2603
|
-
*/
|
|
2604
|
-
static getAWSRegion(regionInfo) {
|
|
2605
|
-
if (regionInfo.isUS) {
|
|
2606
|
-
return "us-east-1";
|
|
2607
|
-
}
|
|
2608
|
-
if (regionInfo.isHK || regionInfo.isJP || regionInfo.isSG) {
|
|
2609
|
-
return "ap-southeast-1";
|
|
2610
|
-
}
|
|
2611
|
-
return "cn-north-1";
|
|
2612
|
-
}
|
|
2613
|
-
/**
|
|
2614
|
-
* 获取Referer路径
|
|
2615
|
-
*/
|
|
2616
|
-
static getRefererPath(regionInfo, path7 = "/ai-tool/generate") {
|
|
2617
|
-
const origin = this.getOrigin(regionInfo);
|
|
2618
|
-
return `${origin}${path7}`;
|
|
2619
|
-
}
|
|
2620
|
-
};
|
|
2621
|
-
|
|
2622
|
-
// src/lib/aws-signature.ts
|
|
2623
|
-
import crypto2 from "crypto";
|
|
2624
|
-
function createSignature(method, url, headers, accessKeyId, secretAccessKey, sessionToken, payload = "", region = "cn-north-1", service = "imagex") {
|
|
2625
|
-
const urlObj = new URL(url);
|
|
2626
|
-
const pathname = urlObj.pathname || "/";
|
|
2627
|
-
const search = urlObj.search;
|
|
2628
|
-
const timestamp = headers["x-amz-date"];
|
|
2629
|
-
const date = timestamp.substr(0, 8);
|
|
2630
|
-
const queryParams = [];
|
|
2631
|
-
const searchParams = new URLSearchParams(search);
|
|
2632
|
-
searchParams.forEach((value, key) => {
|
|
2633
|
-
queryParams.push([key, value]);
|
|
2634
|
-
});
|
|
2635
|
-
queryParams.sort(([a], [b]) => {
|
|
2636
|
-
if (a < b) return -1;
|
|
2637
|
-
if (a > b) return 1;
|
|
2638
|
-
return 0;
|
|
2639
|
-
});
|
|
2640
|
-
const canonicalQueryString = queryParams.map(([key, value]) => `${key}=${value}`).join("&");
|
|
2641
|
-
const headersToSign = {
|
|
2642
|
-
"x-amz-date": timestamp
|
|
2643
|
-
};
|
|
2644
|
-
if (sessionToken) {
|
|
2645
|
-
headersToSign["x-amz-security-token"] = sessionToken;
|
|
2646
|
-
}
|
|
2647
|
-
let payloadHash = crypto2.createHash("sha256").update("").digest("hex");
|
|
2648
|
-
if (method.toUpperCase() === "POST" && payload) {
|
|
2649
|
-
payloadHash = crypto2.createHash("sha256").update(payload, "utf8").digest("hex");
|
|
2650
|
-
headersToSign["x-amz-content-sha256"] = payloadHash;
|
|
2651
|
-
}
|
|
2652
|
-
const signedHeaders = Object.keys(headersToSign).map((key) => key.toLowerCase()).sort().join(";");
|
|
2653
|
-
const canonicalHeaders = Object.keys(headersToSign).sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())).map((key) => `${key.toLowerCase()}:${headersToSign[key].trim()}
|
|
2654
|
-
`).join("");
|
|
2655
|
-
const canonicalRequest = [
|
|
2656
|
-
method.toUpperCase(),
|
|
2657
|
-
pathname,
|
|
2658
|
-
canonicalQueryString,
|
|
2659
|
-
canonicalHeaders,
|
|
2660
|
-
signedHeaders,
|
|
2661
|
-
payloadHash
|
|
2662
|
-
].join("\n");
|
|
2663
|
-
const credentialScope = `${date}/${region}/${service}/aws4_request`;
|
|
2664
|
-
const stringToSign = [
|
|
2665
|
-
"AWS4-HMAC-SHA256",
|
|
2666
|
-
timestamp,
|
|
2667
|
-
credentialScope,
|
|
2668
|
-
crypto2.createHash("sha256").update(canonicalRequest, "utf8").digest("hex")
|
|
2669
|
-
].join("\n");
|
|
2670
|
-
const kDate = crypto2.createHmac("sha256", `AWS4${secretAccessKey}`).update(date).digest();
|
|
2671
|
-
const kRegion = crypto2.createHmac("sha256", kDate).update(region).digest();
|
|
2672
|
-
const kService = crypto2.createHmac("sha256", kRegion).update(service).digest();
|
|
2673
|
-
const kSigning = crypto2.createHmac("sha256", kService).update("aws4_request").digest();
|
|
2674
|
-
const signature = crypto2.createHmac("sha256", kSigning).update(stringToSign).digest("hex");
|
|
2675
|
-
return `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
|
|
2676
|
-
}
|
|
2677
|
-
|
|
2678
|
-
// src/lib/image-uploader.ts
|
|
2679
|
-
async function uploadImageBuffer(imageBuffer, refreshToken, regionInfo) {
|
|
2680
|
-
var _a, _b, _c, _d, _e, _f;
|
|
2681
|
-
try {
|
|
2682
|
-
logger_default.info(`\u5F00\u59CB\u4E0A\u4F20\u56FE\u7247Buffer... (isInternational: ${regionInfo.isInternational})`);
|
|
2683
|
-
const tokenResult = await request("post", "/mweb/v1/get_upload_token", refreshToken, regionInfo, {
|
|
2684
|
-
data: {
|
|
2685
|
-
scene: 2
|
|
2686
|
-
// AIGC 图片上传场景
|
|
2687
|
-
}
|
|
2688
|
-
});
|
|
2689
|
-
const { access_key_id, secret_access_key, session_token } = tokenResult;
|
|
2690
|
-
const service_id = regionInfo.isInternational ? tokenResult.space_name : tokenResult.service_id;
|
|
2691
|
-
if (!access_key_id || !secret_access_key || !session_token) {
|
|
2692
|
-
throw new Error("\u83B7\u53D6\u4E0A\u4F20\u4EE4\u724C\u5931\u8D25");
|
|
2693
|
-
}
|
|
2694
|
-
const actualServiceId = RegionUtils.getServiceId(regionInfo, service_id);
|
|
2695
|
-
logger_default.info(`\u83B7\u53D6\u4E0A\u4F20\u4EE4\u724C\u6210\u529F: service_id=${actualServiceId}`);
|
|
2696
|
-
const fileSize = imageBuffer.byteLength;
|
|
2697
|
-
const crc32 = util_default.calculateCRC32(imageBuffer);
|
|
2698
|
-
logger_default.info(`\u56FE\u7247Buffer: \u5927\u5C0F=${fileSize}\u5B57\u8282, CRC32=${crc32}`);
|
|
2699
|
-
const now = /* @__PURE__ */ new Date();
|
|
2700
|
-
const timestamp = now.toISOString().replace(/[:\-]/g, "").replace(/\.\d{3}Z$/, "Z");
|
|
2701
|
-
const randomStr = Math.random().toString(36).substring(2, 12);
|
|
2702
|
-
const applyUrlHost = RegionUtils.getImageXUrl(regionInfo);
|
|
2703
|
-
const applyUrl = `${applyUrlHost}/?Action=ApplyImageUpload&Version=2018-08-01&ServiceId=${actualServiceId}&FileSize=${fileSize}&s=${randomStr}${regionInfo.isInternational ? "&device_platform=web" : ""}`;
|
|
2704
|
-
const awsRegion = RegionUtils.getAWSRegion(regionInfo);
|
|
2705
|
-
const origin = RegionUtils.getOrigin(regionInfo);
|
|
2706
|
-
const requestHeaders = {
|
|
2707
|
-
"x-amz-date": timestamp,
|
|
2708
|
-
"x-amz-security-token": session_token
|
|
2709
|
-
};
|
|
2710
|
-
const authorization = createSignature("GET", applyUrl, requestHeaders, access_key_id, secret_access_key, session_token, "", awsRegion);
|
|
2711
|
-
logger_default.info(`\u7533\u8BF7\u4E0A\u4F20\u6743\u9650: ${applyUrl}`);
|
|
2712
|
-
let applyResponse;
|
|
2713
|
-
try {
|
|
2714
|
-
applyResponse = await axios3({
|
|
2715
|
-
method: "GET",
|
|
2716
|
-
url: applyUrl,
|
|
2717
|
-
headers: {
|
|
2718
|
-
"accept": "*/*",
|
|
2719
|
-
"accept-language": "zh-CN,zh;q=0.9",
|
|
2720
|
-
"authorization": authorization,
|
|
2721
|
-
"origin": origin,
|
|
2722
|
-
"referer": `${origin}/ai-tool/generate`,
|
|
2723
|
-
"sec-ch-ua": '"Not A(Brand";v="8", "Chromium";v="132", "Google Chrome";v="132"',
|
|
2724
|
-
"sec-ch-ua-mobile": "?0",
|
|
2725
|
-
"sec-ch-ua-platform": '"Windows"',
|
|
2726
|
-
"sec-fetch-dest": "empty",
|
|
2727
|
-
"sec-fetch-mode": "cors",
|
|
2728
|
-
"sec-fetch-site": "cross-site",
|
|
2729
|
-
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36",
|
|
2730
|
-
"x-amz-date": timestamp,
|
|
2731
|
-
"x-amz-security-token": session_token
|
|
2732
|
-
},
|
|
2733
|
-
validateStatus: () => true
|
|
2734
|
-
});
|
|
2735
|
-
} catch (fetchError) {
|
|
2736
|
-
logger_default.error(`Fetch\u8BF7\u6C42\u5931\u8D25\uFF0C\u76EE\u6807URL: ${applyUrl}`);
|
|
2737
|
-
logger_default.error(`\u9519\u8BEF\u8BE6\u60C5: ${fetchError.message}`);
|
|
2738
|
-
throw new Error(`\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25 (${applyUrlHost}): ${fetchError.message}. \u8BF7\u68C0\u67E5: 1) \u7F51\u7EDC\u8FDE\u63A5\u662F\u5426\u6B63\u5E38 2) \u662F\u5426\u9700\u8981\u914D\u7F6E\u4EE3\u7406 3) DNS\u662F\u5426\u80FD\u89E3\u6790\u8BE5\u57DF\u540D`);
|
|
2739
|
-
}
|
|
2740
|
-
if (applyResponse.status < 200 || applyResponse.status >= 300) {
|
|
2741
|
-
const errorText = typeof applyResponse.data === "string" ? applyResponse.data : JSON.stringify(applyResponse.data);
|
|
2742
|
-
throw new Error(`\u7533\u8BF7\u4E0A\u4F20\u6743\u9650\u5931\u8D25: ${applyResponse.status} - ${errorText}`);
|
|
2743
|
-
}
|
|
2744
|
-
const applyResult = applyResponse.data;
|
|
2745
|
-
if ((_a = applyResult == null ? void 0 : applyResult.ResponseMetadata) == null ? void 0 : _a.Error) {
|
|
2746
|
-
throw new Error(`\u7533\u8BF7\u4E0A\u4F20\u6743\u9650\u5931\u8D25: ${JSON.stringify(applyResult.ResponseMetadata.Error)}`);
|
|
2747
|
-
}
|
|
2748
|
-
logger_default.info(`\u7533\u8BF7\u4E0A\u4F20\u6743\u9650\u6210\u529F`);
|
|
2749
|
-
const uploadAddress = (_b = applyResult == null ? void 0 : applyResult.Result) == null ? void 0 : _b.UploadAddress;
|
|
2750
|
-
if (!uploadAddress || !uploadAddress.StoreInfos || !uploadAddress.UploadHosts) {
|
|
2751
|
-
throw new Error(`\u83B7\u53D6\u4E0A\u4F20\u5730\u5740\u5931\u8D25: ${JSON.stringify(applyResult)}`);
|
|
2752
|
-
}
|
|
2753
|
-
const storeInfo = uploadAddress.StoreInfos[0];
|
|
2754
|
-
const uploadHost = uploadAddress.UploadHosts[0];
|
|
2755
|
-
const auth = storeInfo.Auth;
|
|
2756
|
-
const uploadUrl = `https://${uploadHost}/upload/v1/${storeInfo.StoreUri}`;
|
|
2757
|
-
logger_default.info(`\u51C6\u5907\u4E0A\u4F20\u56FE\u7247: uploadUrl=${uploadUrl}`);
|
|
2758
|
-
let uploadResponse;
|
|
2759
|
-
try {
|
|
2760
|
-
uploadResponse = await axios3({
|
|
2761
|
-
method: "POST",
|
|
2762
|
-
url: uploadUrl,
|
|
2763
|
-
headers: {
|
|
2764
|
-
"Accept": "*/*",
|
|
2765
|
-
"Accept-Language": "zh-CN,zh;q=0.9",
|
|
2766
|
-
"Authorization": auth,
|
|
2767
|
-
"Connection": "keep-alive",
|
|
2768
|
-
"Content-CRC32": crc32,
|
|
2769
|
-
"Content-Disposition": 'attachment; filename="undefined"',
|
|
2770
|
-
"Content-Type": "application/octet-stream",
|
|
2771
|
-
"Origin": origin,
|
|
2772
|
-
"Referer": RegionUtils.getRefererPath(regionInfo),
|
|
2773
|
-
"Sec-Fetch-Dest": "empty",
|
|
2774
|
-
"Sec-Fetch-Mode": "cors",
|
|
2775
|
-
"Sec-Fetch-Site": "cross-site",
|
|
2776
|
-
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36"
|
|
2777
|
-
},
|
|
2778
|
-
data: imageBuffer,
|
|
2779
|
-
validateStatus: () => true
|
|
2780
|
-
});
|
|
2781
|
-
} catch (fetchError) {
|
|
2782
|
-
logger_default.error(`\u56FE\u7247\u6587\u4EF6\u4E0A\u4F20fetch\u8BF7\u6C42\u5931\u8D25\uFF0C\u76EE\u6807URL: ${uploadUrl}`);
|
|
2783
|
-
logger_default.error(`\u9519\u8BEF\u8BE6\u60C5: ${fetchError.message}`);
|
|
2784
|
-
throw new Error(`\u56FE\u7247\u4E0A\u4F20\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25 (${uploadHost}): ${fetchError.message}. \u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5`);
|
|
2785
|
-
}
|
|
2786
|
-
if (uploadResponse.status < 200 || uploadResponse.status >= 300) {
|
|
2787
|
-
const errorText = typeof uploadResponse.data === "string" ? uploadResponse.data : JSON.stringify(uploadResponse.data);
|
|
2788
|
-
throw new Error(`\u56FE\u7247\u4E0A\u4F20\u5931\u8D25: ${uploadResponse.status} - ${errorText}`);
|
|
2789
|
-
}
|
|
2790
|
-
logger_default.info(`\u56FE\u7247\u6587\u4EF6\u4E0A\u4F20\u6210\u529F`);
|
|
2791
|
-
const commitUrl = `${applyUrlHost}/?Action=CommitImageUpload&Version=2018-08-01&ServiceId=${actualServiceId}`;
|
|
2792
|
-
const commitTimestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:\-]/g, "").replace(/\.\d{3}Z$/, "Z");
|
|
2793
|
-
const commitPayload = JSON.stringify({
|
|
2794
|
-
SessionKey: uploadAddress.SessionKey
|
|
2795
|
-
});
|
|
2796
|
-
const payloadHash = crypto3.createHash("sha256").update(commitPayload, "utf8").digest("hex");
|
|
2797
|
-
const commitRequestHeaders = {
|
|
2798
|
-
"x-amz-date": commitTimestamp,
|
|
2799
|
-
"x-amz-security-token": session_token,
|
|
2800
|
-
"x-amz-content-sha256": payloadHash
|
|
2801
|
-
};
|
|
2802
|
-
const commitAuthorization = createSignature("POST", commitUrl, commitRequestHeaders, access_key_id, secret_access_key, session_token, commitPayload, awsRegion);
|
|
2803
|
-
let commitResponse;
|
|
2804
|
-
try {
|
|
2805
|
-
commitResponse = await axios3({
|
|
2806
|
-
method: "POST",
|
|
2807
|
-
url: commitUrl,
|
|
2808
|
-
headers: {
|
|
2809
|
-
"accept": "*/*",
|
|
2810
|
-
"accept-language": "zh-CN,zh;q=0.9",
|
|
2811
|
-
"authorization": commitAuthorization,
|
|
2812
|
-
"content-type": "application/json",
|
|
2813
|
-
"origin": origin,
|
|
2814
|
-
"referer": RegionUtils.getRefererPath(regionInfo),
|
|
2815
|
-
"sec-ch-ua": '"Not A(Brand";v="8", "Chromium";v="132", "Google Chrome";v="132"',
|
|
2816
|
-
"sec-ch-ua-mobile": "?0",
|
|
2817
|
-
"sec-ch-ua-platform": '"Windows"',
|
|
2818
|
-
"sec-fetch-dest": "empty",
|
|
2819
|
-
"sec-fetch-mode": "cors",
|
|
2820
|
-
"sec-fetch-site": "cross-site",
|
|
2821
|
-
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36",
|
|
2822
|
-
"x-amz-date": commitTimestamp,
|
|
2823
|
-
"x-amz-security-token": session_token,
|
|
2824
|
-
"x-amz-content-sha256": payloadHash
|
|
2825
|
-
},
|
|
2826
|
-
data: commitPayload,
|
|
2827
|
-
validateStatus: () => true
|
|
2828
|
-
});
|
|
2829
|
-
} catch (fetchError) {
|
|
2830
|
-
logger_default.error(`\u63D0\u4EA4\u4E0A\u4F20fetch\u8BF7\u6C42\u5931\u8D25\uFF0C\u76EE\u6807URL: ${commitUrl}`);
|
|
2831
|
-
logger_default.error(`\u9519\u8BEF\u8BE6\u60C5: ${fetchError.message}`);
|
|
2832
|
-
throw new Error(`\u63D0\u4EA4\u4E0A\u4F20\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25 (${applyUrlHost}): ${fetchError.message}. \u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5`);
|
|
2833
|
-
}
|
|
2834
|
-
if (commitResponse.status < 200 || commitResponse.status >= 300) {
|
|
2835
|
-
const errorText = typeof commitResponse.data === "string" ? commitResponse.data : JSON.stringify(commitResponse.data);
|
|
2836
|
-
throw new Error(`\u63D0\u4EA4\u4E0A\u4F20\u5931\u8D25: ${commitResponse.status} - ${errorText}`);
|
|
2837
|
-
}
|
|
2838
|
-
const commitResult = commitResponse.data;
|
|
2839
|
-
if ((_c = commitResult == null ? void 0 : commitResult.ResponseMetadata) == null ? void 0 : _c.Error) {
|
|
2840
|
-
throw new Error(`\u63D0\u4EA4\u4E0A\u4F20\u5931\u8D25: ${JSON.stringify(commitResult.ResponseMetadata.Error)}`);
|
|
2841
|
-
}
|
|
2842
|
-
if (!((_d = commitResult == null ? void 0 : commitResult.Result) == null ? void 0 : _d.Results) || commitResult.Result.Results.length === 0) {
|
|
2843
|
-
throw new Error(`\u63D0\u4EA4\u4E0A\u4F20\u54CD\u5E94\u7F3A\u5C11\u7ED3\u679C: ${JSON.stringify(commitResult)}`);
|
|
2844
|
-
}
|
|
2845
|
-
const uploadResult = commitResult.Result.Results[0];
|
|
2846
|
-
if (uploadResult.UriStatus !== 2e3) {
|
|
2847
|
-
throw new Error(`\u56FE\u7247\u4E0A\u4F20\u72B6\u6001\u5F02\u5E38: UriStatus=${uploadResult.UriStatus}`);
|
|
2848
|
-
}
|
|
2849
|
-
const fullImageUri = uploadResult.Uri;
|
|
2850
|
-
const pluginResult = (_f = (_e = commitResult.Result) == null ? void 0 : _e.PluginResult) == null ? void 0 : _f[0];
|
|
2851
|
-
const width = (pluginResult == null ? void 0 : pluginResult.ImageWidth) || 0;
|
|
2852
|
-
const height = (pluginResult == null ? void 0 : pluginResult.ImageHeight) || 0;
|
|
2853
|
-
const format = (pluginResult == null ? void 0 : pluginResult.ImageFormat) || "";
|
|
2854
|
-
logger_default.info(`\u56FE\u7247\u4E0A\u4F20\u5B8C\u6210: ${fullImageUri} (${width}x${height}, ${format})`);
|
|
2855
|
-
return { uri: fullImageUri, width, height, format };
|
|
2856
|
-
} catch (error) {
|
|
2857
|
-
logger_default.error(`\u56FE\u7247Buffer\u4E0A\u4F20\u5931\u8D25: ${error.message}`);
|
|
2858
|
-
throw error;
|
|
2859
|
-
}
|
|
2860
|
-
}
|
|
2861
|
-
async function uploadImageFromUrl(imageUrl, refreshToken, regionInfo) {
|
|
2862
|
-
try {
|
|
2863
|
-
logger_default.info(`\u5F00\u59CB\u4ECEURL\u4E0B\u8F7D\u5E76\u4E0A\u4F20\u56FE\u7247: ${imageUrl}`);
|
|
2864
|
-
await assertSafeExternalHttpUrl(imageUrl);
|
|
2865
|
-
const imageResponse = await axios3.get(imageUrl, {
|
|
2866
|
-
responseType: "arraybuffer",
|
|
2867
|
-
maxContentLength: 100 * 1024 * 1024,
|
|
2868
|
-
timeout: 6e4
|
|
2869
|
-
});
|
|
2870
|
-
if (imageResponse.status < 200 || imageResponse.status >= 300) {
|
|
2871
|
-
throw new Error(`\u4E0B\u8F7D\u56FE\u7247\u5931\u8D25: ${imageResponse.status}`);
|
|
2872
|
-
}
|
|
2873
|
-
const imageBuffer = imageResponse.data;
|
|
2874
|
-
return await uploadImageBuffer(imageBuffer, refreshToken, regionInfo);
|
|
2875
|
-
} catch (error) {
|
|
2876
|
-
logger_default.error(`\u4ECEURL\u4E0A\u4F20\u56FE\u7247\u5931\u8D25: ${error.message}`);
|
|
2877
|
-
throw error;
|
|
2878
|
-
}
|
|
2879
|
-
}
|
|
2880
|
-
|
|
2881
|
-
// src/api/builders/payload-builder.ts
|
|
2882
|
-
function getRegionKey(regionInfo) {
|
|
2883
|
-
if (regionInfo.isUS) return "US";
|
|
2884
|
-
if (regionInfo.isHK) return "HK";
|
|
2885
|
-
if (regionInfo.isJP) return "JP";
|
|
2886
|
-
if (regionInfo.isSG) return "SG";
|
|
2887
|
-
return "CN";
|
|
2888
|
-
}
|
|
2889
|
-
function lookupResolution(resolution = "2k", ratio = "1:1", userModel) {
|
|
2890
|
-
if (userModel === "nanobananapro" && resolution === "4k") {
|
|
2891
|
-
const ratioConfig2 = RESOLUTION_OPTIONS_NANOBANANAPRO_4K[ratio];
|
|
2892
|
-
if (!ratioConfig2) {
|
|
2893
|
-
const supportedRatios = Object.keys(RESOLUTION_OPTIONS_NANOBANANAPRO_4K).join(", ");
|
|
2894
|
-
throw new Error(`nanobananapro \u6A21\u578B\u5728 4k \u5206\u8FA8\u7387\u4E0B\uFF0C\u4E0D\u652F\u6301\u7684\u6BD4\u4F8B "${ratio}"\u3002\u652F\u6301\u7684\u6BD4\u4F8B: ${supportedRatios}`);
|
|
2895
|
-
}
|
|
2896
|
-
return {
|
|
2897
|
-
width: ratioConfig2.width,
|
|
2898
|
-
height: ratioConfig2.height,
|
|
2899
|
-
imageRatio: ratioConfig2.ratio,
|
|
2900
|
-
resolutionType: resolution
|
|
2901
|
-
};
|
|
2902
|
-
}
|
|
2903
|
-
const resolutionGroup = RESOLUTION_OPTIONS[resolution];
|
|
2904
|
-
if (!resolutionGroup) {
|
|
2905
|
-
const supportedResolutions = Object.keys(RESOLUTION_OPTIONS).join(", ");
|
|
2906
|
-
throw new Error(`\u4E0D\u652F\u6301\u7684\u5206\u8FA8\u7387 "${resolution}"\u3002\u652F\u6301\u7684\u5206\u8FA8\u7387: ${supportedResolutions}`);
|
|
2907
|
-
}
|
|
2908
|
-
const ratioConfig = resolutionGroup[ratio];
|
|
2909
|
-
if (!ratioConfig) {
|
|
2910
|
-
const supportedRatios = Object.keys(resolutionGroup).join(", ");
|
|
2911
|
-
throw new Error(`\u5728 "${resolution}" \u5206\u8FA8\u7387\u4E0B\uFF0C\u4E0D\u652F\u6301\u7684\u6BD4\u4F8B "${ratio}"\u3002\u652F\u6301\u7684\u6BD4\u4F8B: ${supportedRatios}`);
|
|
2912
|
-
}
|
|
2913
|
-
return {
|
|
2914
|
-
width: ratioConfig.width,
|
|
2915
|
-
height: ratioConfig.height,
|
|
2916
|
-
imageRatio: ratioConfig.ratio,
|
|
2917
|
-
resolutionType: resolution
|
|
2918
|
-
};
|
|
2919
|
-
}
|
|
2920
|
-
function resolveResolution(userModel, regionInfo, resolution = "2k", ratio = "1:1") {
|
|
2921
|
-
const regionKey = getRegionKey(regionInfo);
|
|
2922
|
-
if (regionKey === "CN" && (userModel === "nanobanana" || userModel === "nanobananapro")) {
|
|
2923
|
-
throw new Error(
|
|
2924
|
-
`\u56FD\u5185\u7AD9\u4E0D\u652F\u6301${userModel}\u6A21\u578B,\u8BF7\u4F7F\u7528jimeng\u7CFB\u5217\u6A21\u578B`
|
|
2925
|
-
);
|
|
2926
|
-
}
|
|
2927
|
-
if (userModel === "nanobanana") {
|
|
2928
|
-
if (regionKey === "US") {
|
|
2929
|
-
return {
|
|
2930
|
-
width: 1024,
|
|
2931
|
-
height: 1024,
|
|
2932
|
-
imageRatio: 1,
|
|
2933
|
-
resolutionType: "2k",
|
|
2934
|
-
isForced: true
|
|
2935
|
-
};
|
|
2936
|
-
} else if (regionKey === "HK" || regionKey === "JP" || regionKey === "SG") {
|
|
2937
|
-
const params2 = lookupResolution("1k", ratio, userModel);
|
|
2938
|
-
return {
|
|
2939
|
-
width: params2.width,
|
|
2940
|
-
height: params2.height,
|
|
2941
|
-
imageRatio: params2.imageRatio,
|
|
2942
|
-
resolutionType: "1k",
|
|
2943
|
-
isForced: true
|
|
2944
|
-
};
|
|
2945
|
-
}
|
|
2946
|
-
}
|
|
2947
|
-
const params = lookupResolution(resolution, ratio, userModel);
|
|
2948
|
-
return {
|
|
2949
|
-
...params,
|
|
2950
|
-
isForced: false
|
|
2951
|
-
};
|
|
2952
|
-
}
|
|
2953
|
-
function getBenefitCount(userModel, regionInfo, isMultiImage = false) {
|
|
2954
|
-
if (isMultiImage) return void 0;
|
|
2955
|
-
return 4;
|
|
2956
|
-
}
|
|
2957
|
-
function buildCoreParam(options) {
|
|
2958
|
-
const {
|
|
2959
|
-
userModel,
|
|
2960
|
-
model,
|
|
2961
|
-
prompt,
|
|
2962
|
-
imageCount = 0,
|
|
2963
|
-
negativePrompt,
|
|
2964
|
-
seed,
|
|
2965
|
-
sampleStrength,
|
|
2966
|
-
resolution,
|
|
2967
|
-
intelligentRatio = false,
|
|
2968
|
-
mode = "text2img"
|
|
2969
|
-
} = options;
|
|
2970
|
-
const effectiveIntelligentRatio = ["jimeng-4.0", "jimeng-4.1", "jimeng-4.5", "jimeng-4.6", "jimeng-5.0"].includes(userModel) ? intelligentRatio : false;
|
|
2971
|
-
const promptPrefix = mode === "img2img" ? "#".repeat(imageCount * 2) : "";
|
|
2972
|
-
const coreParam = {
|
|
2973
|
-
type: "",
|
|
2974
|
-
id: util_default.uuid(),
|
|
2975
|
-
model,
|
|
2976
|
-
prompt: `${promptPrefix}${prompt}`,
|
|
2977
|
-
sample_strength: sampleStrength,
|
|
2978
|
-
large_image_info: {
|
|
2979
|
-
type: "",
|
|
2980
|
-
id: util_default.uuid(),
|
|
2981
|
-
min_version: DRAFT_MIN_VERSION,
|
|
2982
|
-
height: resolution.height,
|
|
2983
|
-
width: resolution.width,
|
|
2984
|
-
resolution_type: resolution.resolutionType
|
|
2985
|
-
},
|
|
2986
|
-
intelligent_ratio: effectiveIntelligentRatio
|
|
2987
|
-
};
|
|
2988
|
-
if (mode === "img2img") {
|
|
2989
|
-
coreParam.image_ratio = resolution.imageRatio;
|
|
2990
|
-
} else if (!effectiveIntelligentRatio) {
|
|
2991
|
-
coreParam.image_ratio = resolution.imageRatio;
|
|
2992
|
-
}
|
|
2993
|
-
if (negativePrompt !== void 0) {
|
|
2994
|
-
coreParam.negative_prompt = negativePrompt;
|
|
2995
|
-
}
|
|
2996
|
-
if (seed !== void 0) {
|
|
2997
|
-
coreParam.seed = seed;
|
|
2998
|
-
}
|
|
2999
|
-
return coreParam;
|
|
3000
|
-
}
|
|
3001
|
-
function buildMetricsExtra({
|
|
3002
|
-
userModel,
|
|
3003
|
-
model,
|
|
3004
|
-
regionInfo,
|
|
3005
|
-
submitId,
|
|
3006
|
-
scene,
|
|
3007
|
-
resolutionType,
|
|
3008
|
-
abilityList = [],
|
|
3009
|
-
isMultiImage = false
|
|
3010
|
-
}) {
|
|
3011
|
-
const benefitCount = getBenefitCount(userModel, regionInfo, isMultiImage);
|
|
3012
|
-
const sceneOption = {
|
|
3013
|
-
type: "image",
|
|
3014
|
-
scene,
|
|
3015
|
-
modelReqKey: model,
|
|
3016
|
-
resolutionType,
|
|
3017
|
-
abilityList,
|
|
3018
|
-
reportParams: {
|
|
3019
|
-
enterSource: "generate",
|
|
3020
|
-
vipSource: "generate",
|
|
3021
|
-
extraVipFunctionKey: `${model}-${resolutionType}`,
|
|
3022
|
-
useVipFunctionDetailsReporterHoc: true
|
|
3023
|
-
}
|
|
3024
|
-
};
|
|
3025
|
-
if (benefitCount !== void 0) {
|
|
3026
|
-
sceneOption.benefitCount = benefitCount;
|
|
3027
|
-
}
|
|
3028
|
-
const metrics = {
|
|
3029
|
-
promptSource: "custom",
|
|
3030
|
-
generateCount: 1,
|
|
3031
|
-
enterFrom: "click",
|
|
3032
|
-
sceneOptions: JSON.stringify([sceneOption]),
|
|
3033
|
-
generateId: submitId,
|
|
3034
|
-
isRegenerate: false
|
|
3035
|
-
};
|
|
3036
|
-
if (isMultiImage) {
|
|
3037
|
-
Object.assign(metrics, {
|
|
3038
|
-
templateId: "",
|
|
3039
|
-
templateSource: "",
|
|
3040
|
-
lastRequestId: "",
|
|
3041
|
-
originRequestId: ""
|
|
3042
|
-
});
|
|
3043
|
-
}
|
|
3044
|
-
return JSON.stringify(metrics);
|
|
3045
|
-
}
|
|
3046
|
-
function buildDraftContent({
|
|
3047
|
-
componentId,
|
|
3048
|
-
generateType,
|
|
3049
|
-
coreParam,
|
|
3050
|
-
abilityList,
|
|
3051
|
-
promptPlaceholderInfoList,
|
|
3052
|
-
posteditParam,
|
|
3053
|
-
imageCount = 0
|
|
3054
|
-
}) {
|
|
3055
|
-
const abilities = {
|
|
3056
|
-
type: "",
|
|
3057
|
-
id: util_default.uuid()
|
|
3058
|
-
};
|
|
3059
|
-
const isBlend = generateType === "blend";
|
|
3060
|
-
const draftMinVersion = isBlend ? "3.2.9" : DRAFT_MIN_VERSION;
|
|
3061
|
-
if (generateType === "generate") {
|
|
3062
|
-
abilities.generate = {
|
|
3063
|
-
type: "",
|
|
3064
|
-
id: util_default.uuid(),
|
|
3065
|
-
core_param: coreParam,
|
|
3066
|
-
gen_option: {
|
|
3067
|
-
type: "",
|
|
3068
|
-
id: util_default.uuid(),
|
|
3069
|
-
generate_all: false
|
|
3070
|
-
}
|
|
3071
|
-
};
|
|
3072
|
-
} else {
|
|
3073
|
-
abilities.blend = {
|
|
3074
|
-
type: "",
|
|
3075
|
-
id: util_default.uuid(),
|
|
3076
|
-
...imageCount >= 2 ? { min_version: "3.2.9" } : {},
|
|
3077
|
-
min_features: [],
|
|
3078
|
-
core_param: coreParam,
|
|
3079
|
-
ability_list: abilityList,
|
|
3080
|
-
prompt_placeholder_info_list: promptPlaceholderInfoList,
|
|
3081
|
-
postedit_param: posteditParam
|
|
3082
|
-
};
|
|
3083
|
-
abilities.gen_option = {
|
|
3084
|
-
type: "",
|
|
3085
|
-
id: util_default.uuid(),
|
|
3086
|
-
generate_all: false
|
|
3087
|
-
};
|
|
3088
|
-
}
|
|
3089
|
-
const draftContent = {
|
|
3090
|
-
type: "draft",
|
|
3091
|
-
id: util_default.uuid(),
|
|
3092
|
-
min_version: draftMinVersion,
|
|
3093
|
-
min_features: [],
|
|
3094
|
-
is_from_tsn: true,
|
|
3095
|
-
version: DRAFT_VERSION,
|
|
3096
|
-
main_component_id: componentId,
|
|
3097
|
-
component_list: [
|
|
3098
|
-
{
|
|
3099
|
-
type: "image_base_component",
|
|
3100
|
-
id: componentId,
|
|
3101
|
-
min_version: DRAFT_MIN_VERSION,
|
|
3102
|
-
aigc_mode: "workbench",
|
|
3103
|
-
metadata: {
|
|
3104
|
-
type: "",
|
|
3105
|
-
id: util_default.uuid(),
|
|
3106
|
-
created_platform: 3,
|
|
3107
|
-
created_platform_version: "",
|
|
3108
|
-
created_time_in_ms: Date.now().toString(),
|
|
3109
|
-
created_did: ""
|
|
3110
|
-
},
|
|
3111
|
-
generate_type: generateType,
|
|
3112
|
-
abilities
|
|
3113
|
-
}
|
|
3114
|
-
]
|
|
3115
|
-
};
|
|
3116
|
-
return JSON.stringify(draftContent);
|
|
3117
|
-
}
|
|
3118
|
-
function buildGenerateRequest({
|
|
3119
|
-
model,
|
|
3120
|
-
regionInfo,
|
|
3121
|
-
submitId,
|
|
3122
|
-
draftContent,
|
|
3123
|
-
metricsExtra
|
|
3124
|
-
}) {
|
|
3125
|
-
return {
|
|
3126
|
-
extend: {
|
|
3127
|
-
root_model: model
|
|
3128
|
-
},
|
|
3129
|
-
submit_id: submitId,
|
|
3130
|
-
metrics_extra: metricsExtra,
|
|
3131
|
-
draft_content: draftContent,
|
|
3132
|
-
http_common_info: {
|
|
3133
|
-
aid: getAssistantId(regionInfo)
|
|
3134
|
-
}
|
|
3135
|
-
};
|
|
3136
|
-
}
|
|
3137
|
-
function buildBlendAbilityList(uploadedImageIds, strength) {
|
|
3138
|
-
return uploadedImageIds.map((imageId) => ({
|
|
3139
|
-
type: "",
|
|
3140
|
-
id: util_default.uuid(),
|
|
3141
|
-
name: "byte_edit",
|
|
3142
|
-
image_uri_list: [imageId],
|
|
3143
|
-
image_list: [
|
|
3144
|
-
{
|
|
3145
|
-
type: "image",
|
|
3146
|
-
id: util_default.uuid(),
|
|
3147
|
-
source_from: "upload",
|
|
3148
|
-
platform_type: 1,
|
|
3149
|
-
name: "",
|
|
3150
|
-
image_uri: imageId,
|
|
3151
|
-
width: 0,
|
|
3152
|
-
height: 0,
|
|
3153
|
-
format: "",
|
|
3154
|
-
uri: imageId
|
|
3155
|
-
}
|
|
3156
|
-
],
|
|
3157
|
-
strength
|
|
3158
|
-
}));
|
|
3159
|
-
}
|
|
3160
|
-
function buildPromptPlaceholderList(count) {
|
|
3161
|
-
return Array.from({ length: count }, (_9, index) => ({
|
|
3162
|
-
type: "",
|
|
3163
|
-
id: util_default.uuid(),
|
|
3164
|
-
ability_index: index
|
|
3165
|
-
}));
|
|
3166
|
-
}
|
|
3167
|
-
|
|
3168
|
-
// src/api/controllers/images.ts
|
|
3169
|
-
var DEFAULT_MODEL = DEFAULT_IMAGE_MODEL;
|
|
3170
|
-
var DEFAULT_MODEL_US = DEFAULT_IMAGE_MODEL_US;
|
|
3171
|
-
function getModel(model, regionInfo) {
|
|
3172
|
-
let modelMap;
|
|
3173
|
-
if (regionInfo.isUS) {
|
|
3174
|
-
modelMap = IMAGE_MODEL_MAP_US;
|
|
3175
|
-
} else if (regionInfo.isHK || regionInfo.isJP || regionInfo.isSG) {
|
|
3176
|
-
modelMap = IMAGE_MODEL_MAP_ASIA;
|
|
3177
|
-
} else {
|
|
3178
|
-
modelMap = IMAGE_MODEL_MAP;
|
|
3179
|
-
}
|
|
3180
|
-
const defaultModel = regionInfo.isInternational ? DEFAULT_MODEL_US : DEFAULT_MODEL;
|
|
3181
|
-
if (regionInfo.isInternational && !modelMap[model]) {
|
|
3182
|
-
if (model === DEFAULT_MODEL) {
|
|
3183
|
-
logger_default.info(`\u56FD\u9645\u7AD9\u4E0D\u652F\u6301\u9ED8\u8BA4\u6A21\u578B "${model}"\uFF0C\u56DE\u9000\u5230 "${defaultModel}"`);
|
|
3184
|
-
return { model: modelMap[defaultModel], userModel: defaultModel };
|
|
3185
|
-
}
|
|
3186
|
-
const supportedModels = Object.keys(modelMap).join(", ");
|
|
3187
|
-
throw new Error(`\u56FD\u9645\u7248\u4E0D\u652F\u6301\u6A21\u578B "${model}"\u3002\u652F\u6301\u7684\u6A21\u578B: ${supportedModels}`);
|
|
3188
|
-
}
|
|
3189
|
-
const effectiveUserModel = modelMap[model] ? model : defaultModel;
|
|
3190
|
-
return { model: modelMap[effectiveUserModel], userModel: effectiveUserModel };
|
|
3191
|
-
}
|
|
3192
|
-
function logResolutionInfo(userModel, resolution, regionInfo) {
|
|
3193
|
-
if (!resolution.isForced) return;
|
|
3194
|
-
if (userModel === "nanobanana") {
|
|
3195
|
-
if (regionInfo.isUS) {
|
|
3196
|
-
logger_default.warn("\u7F8E\u533A nanobanana \u6A21\u578B\u56FA\u5B9A\u4F7F\u75281024x1024\u5206\u8FA8\u7387\u548C2k\u7684\u6E05\u6670\u5EA6\uFF0C\u6BD4\u4F8B\u56FA\u5B9A\u4E3A1:1\u3002");
|
|
3197
|
-
} else if (regionInfo.isHK || regionInfo.isJP || regionInfo.isSG) {
|
|
3198
|
-
const regionName = regionInfo.isHK ? "\u9999\u6E2F" : regionInfo.isJP ? "\u65E5\u672C" : "\u65B0\u52A0\u5761";
|
|
3199
|
-
logger_default.warn(`${regionName}\u7AD9 nanobanana \u6A21\u578B\u56FA\u5B9A\u4F7F\u75281k\u6E05\u6670\u5EA6\u3002`);
|
|
3200
|
-
}
|
|
3201
|
-
}
|
|
3202
|
-
}
|
|
3203
|
-
async function generateImageComposition(_model, prompt, images, {
|
|
3204
|
-
ratio = "1:1",
|
|
3205
|
-
resolution = "2k",
|
|
3206
|
-
sampleStrength = 0.5,
|
|
3207
|
-
negativePrompt = "",
|
|
3208
|
-
intelligentRatio = false,
|
|
3209
|
-
wait = true,
|
|
3210
|
-
waitTimeoutSeconds,
|
|
3211
|
-
pollIntervalMs
|
|
3212
|
-
}, refreshToken, regionInfo) {
|
|
3213
|
-
const { model, userModel } = getModel(_model, regionInfo);
|
|
3214
|
-
const resolutionResult = resolveResolution(userModel, regionInfo, resolution, ratio);
|
|
3215
|
-
logResolutionInfo(userModel, resolutionResult, regionInfo);
|
|
3216
|
-
const imageCount = images.length;
|
|
3217
|
-
logger_default.info(`\u4F7F\u7528\u6A21\u578B: ${userModel} \u6620\u5C04\u6A21\u578B: ${model} \u56FE\u751F\u56FE\u529F\u80FD ${imageCount}\u5F20\u56FE\u7247 ${resolutionResult.width}x${resolutionResult.height} \u7CBE\u7EC6\u5EA6: ${sampleStrength}`);
|
|
3218
|
-
try {
|
|
3219
|
-
const { totalCredit } = await getCredit(refreshToken, regionInfo);
|
|
3220
|
-
if (totalCredit <= 0) {
|
|
3221
|
-
logger_default.info("\u79EF\u5206\u4E3A 0\uFF0C\u5C1D\u8BD5\u6536\u53D6\u4ECA\u65E5\u79EF\u5206...");
|
|
3222
|
-
try {
|
|
3223
|
-
await receiveCredit(refreshToken, regionInfo);
|
|
3224
|
-
} catch (receiveError) {
|
|
3225
|
-
logger_default.warn(`\u6536\u53D6\u79EF\u5206\u5931\u8D25: ${receiveError.message}. \u8FD9\u53EF\u80FD\u662F\u56E0\u4E3A: 1) \u4ECA\u65E5\u5DF2\u6536\u53D6\u8FC7\u79EF\u5206, 2) \u8D26\u6237\u53D7\u5230\u98CE\u63A7\u9650\u5236, 3) \u9700\u8981\u5728\u5B98\u7F51\u624B\u52A8\u6536\u53D6\u9996\u6B21\u79EF\u5206`);
|
|
3226
|
-
}
|
|
3227
|
-
}
|
|
3228
|
-
} catch (e) {
|
|
3229
|
-
logger_default.warn(`\u83B7\u53D6\u79EF\u5206\u5931\u8D25\uFF0C\u53EF\u80FD\u662F\u4E0D\u652F\u6301\u7684\u533A\u57DF\u6216token\u5DF2\u5931\u6548: ${e.message}`);
|
|
3230
|
-
}
|
|
3231
|
-
const uploadedImageIds = [];
|
|
3232
|
-
for (let i = 0; i < images.length; i++) {
|
|
3233
|
-
try {
|
|
3234
|
-
const image = images[i];
|
|
3235
|
-
let imageId;
|
|
3236
|
-
if (typeof image === "string") {
|
|
3237
|
-
logger_default.info(`\u6B63\u5728\u5904\u7406\u7B2C ${i + 1}/${imageCount} \u5F20\u56FE\u7247 (URL)...`);
|
|
3238
|
-
imageId = (await uploadImageFromUrl(image, refreshToken, regionInfo)).uri;
|
|
3239
|
-
} else {
|
|
3240
|
-
logger_default.info(`\u6B63\u5728\u5904\u7406\u7B2C ${i + 1}/${imageCount} \u5F20\u56FE\u7247 (Buffer)...`);
|
|
3241
|
-
imageId = (await uploadImageBuffer(image, refreshToken, regionInfo)).uri;
|
|
3242
|
-
}
|
|
3243
|
-
uploadedImageIds.push(imageId);
|
|
3244
|
-
await checkImageContent(imageId, refreshToken, regionInfo);
|
|
3245
|
-
logger_default.info(`\u56FE\u7247 ${i + 1}/${imageCount} \u4E0A\u4F20\u6210\u529F: ${imageId}`);
|
|
3246
|
-
} catch (error) {
|
|
3247
|
-
logger_default.error(`\u56FE\u7247 ${i + 1}/${imageCount} \u4E0A\u4F20\u5931\u8D25: ${error.message}`);
|
|
3248
|
-
throw new APIException(exceptions_default.API_IMAGE_GENERATION_FAILED, `\u56FE\u7247\u4E0A\u4F20\u5931\u8D25: ${error.message}`);
|
|
3249
|
-
}
|
|
3250
|
-
}
|
|
3251
|
-
logger_default.info(`\u6240\u6709\u56FE\u7247\u4E0A\u4F20\u5B8C\u6210\uFF0C\u5F00\u59CB\u56FE\u751F\u56FE: ${uploadedImageIds.join(", ")}`);
|
|
3252
|
-
const componentId = util_default.uuid();
|
|
3253
|
-
const submitId = util_default.uuid();
|
|
3254
|
-
const coreParam = buildCoreParam({
|
|
3255
|
-
userModel,
|
|
3256
|
-
model,
|
|
3257
|
-
prompt,
|
|
3258
|
-
negativePrompt,
|
|
3259
|
-
imageCount,
|
|
3260
|
-
sampleStrength,
|
|
3261
|
-
resolution: resolutionResult,
|
|
3262
|
-
intelligentRatio,
|
|
3263
|
-
mode: "img2img"
|
|
3264
|
-
});
|
|
3265
|
-
const metricsAbilityList = uploadedImageIds.map(() => ({
|
|
3266
|
-
abilityName: "byte_edit",
|
|
3267
|
-
strength: sampleStrength,
|
|
3268
|
-
source: {
|
|
3269
|
-
imageUrl: `blob:https://dreamina.capcut.com/${util_default.uuid()}`
|
|
3270
|
-
}
|
|
3271
|
-
}));
|
|
3272
|
-
const metricsExtra = buildMetricsExtra({
|
|
3273
|
-
userModel,
|
|
3274
|
-
model,
|
|
3275
|
-
regionInfo,
|
|
3276
|
-
submitId,
|
|
3277
|
-
scene: "ImageBasicGenerate",
|
|
3278
|
-
resolutionType: resolutionResult.resolutionType,
|
|
3279
|
-
abilityList: metricsAbilityList
|
|
3280
|
-
});
|
|
3281
|
-
const abilityList = buildBlendAbilityList(uploadedImageIds, sampleStrength);
|
|
3282
|
-
const promptPlaceholderInfoList = buildPromptPlaceholderList(uploadedImageIds.length);
|
|
3283
|
-
const posteditParam = {
|
|
3284
|
-
type: "",
|
|
3285
|
-
id: util_default.uuid(),
|
|
3286
|
-
generate_type: 0
|
|
3287
|
-
};
|
|
3288
|
-
const draftContent = buildDraftContent({
|
|
3289
|
-
componentId,
|
|
3290
|
-
generateType: "blend",
|
|
3291
|
-
coreParam,
|
|
3292
|
-
abilityList,
|
|
3293
|
-
promptPlaceholderInfoList,
|
|
3294
|
-
posteditParam,
|
|
3295
|
-
imageCount
|
|
3296
|
-
});
|
|
3297
|
-
const requestData = buildGenerateRequest({
|
|
3298
|
-
model,
|
|
3299
|
-
regionInfo,
|
|
3300
|
-
submitId,
|
|
3301
|
-
draftContent,
|
|
3302
|
-
metricsExtra
|
|
3303
|
-
});
|
|
3304
|
-
const imageReferer = regionInfo.isCN ? "https://jimeng.jianying.com/ai-tool/generate?type=image" : "https://dreamina.capcut.com/ai-tool/generate?type=image";
|
|
3305
|
-
const { aigc_data } = await request(
|
|
3306
|
-
"post",
|
|
3307
|
-
"/mweb/v1/aigc_draft/generate",
|
|
3308
|
-
refreshToken,
|
|
3309
|
-
regionInfo,
|
|
3310
|
-
{ data: requestData, headers: { Referer: imageReferer } }
|
|
3311
|
-
);
|
|
3312
|
-
const historyId = aigc_data == null ? void 0 : aigc_data.history_record_id;
|
|
3313
|
-
if (!historyId)
|
|
3314
|
-
throw new APIException(exceptions_default.API_IMAGE_GENERATION_FAILED, "\u8BB0\u5F55ID\u4E0D\u5B58\u5728");
|
|
3315
|
-
if (!wait) {
|
|
3316
|
-
logger_default.info(`\u56FE\u751F\u56FE\u4EFB\u52A1\u5DF2\u63D0\u4EA4\uFF08\u5F02\u6B65\u6A21\u5F0F\uFF09\uFF0Chistory_id: ${historyId}`);
|
|
3317
|
-
return buildPendingTaskInfo(historyId, "image");
|
|
3318
|
-
}
|
|
3319
|
-
logger_default.info(`\u56FE\u751F\u56FE\u4EFB\u52A1\u5DF2\u63D0\u4EA4\uFF0Chistory_id: ${historyId}\uFF0C\u7B49\u5F85\u751F\u6210\u5B8C\u6210...`);
|
|
3320
|
-
const pollerOptions = buildPollerOptions(waitTimeoutSeconds, pollIntervalMs, 1800, 1e4, 900);
|
|
3321
|
-
const poller = new SmartPoller({
|
|
3322
|
-
maxPollCount: pollerOptions.maxPollCount,
|
|
3323
|
-
pollInterval: pollerOptions.pollInterval,
|
|
3324
|
-
expectedItemCount: 1,
|
|
3325
|
-
type: "image",
|
|
3326
|
-
timeoutSeconds: pollerOptions.timeoutSeconds
|
|
3327
|
-
});
|
|
3328
|
-
const { result: pollingResult, data: finalTaskInfo } = await poller.poll(async () => {
|
|
3329
|
-
var _a;
|
|
3330
|
-
const response = await request("post", "/mweb/v1/get_history_by_ids", refreshToken, regionInfo, {
|
|
3331
|
-
data: {
|
|
3332
|
-
history_ids: [historyId],
|
|
3333
|
-
image_info: {
|
|
3334
|
-
width: 2048,
|
|
3335
|
-
height: 2048,
|
|
3336
|
-
format: "webp",
|
|
3337
|
-
image_scene_list: [
|
|
3338
|
-
{ scene: "smart_crop", width: 360, height: 360, uniq_key: "smart_crop-w:360-h:360", format: "webp" },
|
|
3339
|
-
{ scene: "smart_crop", width: 480, height: 480, uniq_key: "smart_crop-w:480-h:480", format: "webp" },
|
|
3340
|
-
{ scene: "smart_crop", width: 720, height: 720, uniq_key: "smart_crop-w:720-h:720", format: "webp" },
|
|
3341
|
-
{ scene: "smart_crop", width: 720, height: 480, uniq_key: "smart_crop-w:720-h:480", format: "webp" },
|
|
3342
|
-
{ scene: "normal", width: 2400, height: 2400, uniq_key: "2400", format: "webp" },
|
|
3343
|
-
{ scene: "normal", width: 1080, height: 1080, uniq_key: "1080", format: "webp" },
|
|
3344
|
-
{ scene: "normal", width: 720, height: 720, uniq_key: "720", format: "webp" },
|
|
3345
|
-
{ scene: "normal", width: 480, height: 480, uniq_key: "480", format: "webp" },
|
|
3346
|
-
{ scene: "normal", width: 360, height: 360, uniq_key: "360", format: "webp" }
|
|
3347
|
-
]
|
|
3348
|
-
}
|
|
3349
|
-
}
|
|
3350
|
-
});
|
|
3351
|
-
if (!response[historyId]) {
|
|
3352
|
-
logger_default.error(`\u5386\u53F2\u8BB0\u5F55\u4E0D\u5B58\u5728: historyId=${historyId}`);
|
|
3353
|
-
throw new APIException(exceptions_default.API_IMAGE_GENERATION_FAILED, "\u8BB0\u5F55\u4E0D\u5B58\u5728");
|
|
3354
|
-
}
|
|
3355
|
-
const taskInfo = response[historyId];
|
|
3356
|
-
return {
|
|
3357
|
-
status: {
|
|
3358
|
-
status: taskInfo.status,
|
|
3359
|
-
failCode: taskInfo.fail_code,
|
|
3360
|
-
itemCount: (taskInfo.item_list || []).length,
|
|
3361
|
-
finishTime: ((_a = taskInfo.task) == null ? void 0 : _a.finish_time) || 0,
|
|
3362
|
-
historyId
|
|
3363
|
-
},
|
|
3364
|
-
data: taskInfo
|
|
3365
|
-
};
|
|
3366
|
-
}, historyId);
|
|
3367
|
-
const item_list = finalTaskInfo.item_list || [];
|
|
3368
|
-
const resultImageUrls = extractImageUrls(item_list);
|
|
3369
|
-
if (resultImageUrls.length === 0 && item_list.length > 0) {
|
|
3370
|
-
throw new APIException(exceptions_default.API_IMAGE_GENERATION_FAILED, `\u56FE\u751F\u56FE\u5931\u8D25: item_list\u6709 ${item_list.length} \u4E2A\u9879\u76EE\uFF0C\u4F46\u65E0\u6CD5\u63D0\u53D6\u4EFB\u4F55\u56FE\u7247URL`);
|
|
3371
|
-
}
|
|
3372
|
-
logger_default.info(`\u56FE\u751F\u56FE\u7ED3\u679C: \u6210\u529F\u751F\u6210 ${resultImageUrls.length} \u5F20\u56FE\u7247\uFF0C\u603B\u8017\u65F6 ${pollingResult.elapsedTime} \u79D2\uFF0C\u6700\u7EC8\u72B6\u6001: ${pollingResult.status}`);
|
|
3373
|
-
return resultImageUrls;
|
|
3374
|
-
}
|
|
3375
|
-
async function generateImages(_model, prompt, {
|
|
3376
|
-
ratio = "1:1",
|
|
3377
|
-
resolution = "2k",
|
|
3378
|
-
sampleStrength = 0.5,
|
|
3379
|
-
negativePrompt = "",
|
|
3380
|
-
intelligentRatio = false,
|
|
3381
|
-
wait = true,
|
|
3382
|
-
waitTimeoutSeconds,
|
|
3383
|
-
pollIntervalMs
|
|
3384
|
-
}, refreshToken, regionInfo) {
|
|
3385
|
-
const { model, userModel } = getModel(_model, regionInfo);
|
|
3386
|
-
logger_default.info(`\u4F7F\u7528\u6A21\u578B: ${userModel} \u6620\u5C04\u6A21\u578B: ${model} \u5206\u8FA8\u7387: ${resolution} \u6BD4\u4F8B: ${ratio} \u7CBE\u7EC6\u5EA6: ${sampleStrength} \u667A\u80FD\u6BD4\u4F8B: ${intelligentRatio}`);
|
|
3387
|
-
return await generateImagesInternal(
|
|
3388
|
-
userModel,
|
|
3389
|
-
prompt,
|
|
3390
|
-
{ ratio, resolution, sampleStrength, negativePrompt, intelligentRatio, wait, waitTimeoutSeconds, pollIntervalMs },
|
|
3391
|
-
refreshToken,
|
|
3392
|
-
regionInfo
|
|
3393
|
-
);
|
|
3394
|
-
}
|
|
3395
|
-
async function generateImagesInternal(_model, prompt, {
|
|
3396
|
-
ratio,
|
|
3397
|
-
resolution,
|
|
3398
|
-
sampleStrength = 0.5,
|
|
3399
|
-
negativePrompt = "",
|
|
3400
|
-
intelligentRatio = false,
|
|
3401
|
-
wait = true,
|
|
3402
|
-
waitTimeoutSeconds,
|
|
3403
|
-
pollIntervalMs
|
|
3404
|
-
}, refreshToken, regionInfo) {
|
|
3405
|
-
const { model, userModel } = getModel(_model, regionInfo);
|
|
3406
|
-
const resolutionResult = resolveResolution(userModel, regionInfo, resolution, ratio);
|
|
3407
|
-
logResolutionInfo(userModel, resolutionResult, regionInfo);
|
|
3408
|
-
const { totalCredit, giftCredit, purchaseCredit, vipCredit } = await getCredit(refreshToken, regionInfo);
|
|
3409
|
-
if (totalCredit <= 0) {
|
|
3410
|
-
logger_default.info("\u79EF\u5206\u4E3A 0\uFF0C\u5C1D\u8BD5\u6536\u53D6\u4ECA\u65E5\u79EF\u5206...");
|
|
3411
|
-
try {
|
|
3412
|
-
await receiveCredit(refreshToken, regionInfo);
|
|
3413
|
-
logger_default.info("\u79EF\u5206\u6536\u53D6\u6210\u529F\uFF0C\u7EE7\u7EED\u751F\u6210\u56FE\u7247");
|
|
3414
|
-
} catch (receiveError) {
|
|
3415
|
-
logger_default.warn(`\u6536\u53D6\u79EF\u5206\u5931\u8D25: ${receiveError.message}. \u8FD9\u53EF\u80FD\u662F\u56E0\u4E3A: 1) \u4ECA\u65E5\u5DF2\u6536\u53D6\u8FC7\u79EF\u5206, 2) \u8D26\u6237\u53D7\u5230\u98CE\u63A7\u9650\u5236, 3) \u9700\u8981\u5728\u5B98\u7F51\u624B\u52A8\u6536\u53D6\u9996\u6B21\u79EF\u5206`);
|
|
3416
|
-
throw new APIException(
|
|
3417
|
-
exceptions_default.API_IMAGE_GENERATION_INSUFFICIENT_POINTS,
|
|
3418
|
-
`\u79EF\u5206\u4E0D\u8DB3\u4E14\u65E0\u6CD5\u81EA\u52A8\u6536\u53D6\u3002\u8BF7\u8BBF\u95EE\u5373\u68A6\u5B98\u7F51\u624B\u52A8\u6536\u53D6\u9996\u6B21\u79EF\u5206\uFF0C\u6216\u68C0\u67E5\u8D26\u6237\u72B6\u6001\u3002`
|
|
3419
|
-
);
|
|
3420
|
-
}
|
|
3421
|
-
} else {
|
|
3422
|
-
logger_default.info(`\u5F53\u524D\u79EF\u5206\u72B6\u6001: \u603B\u8BA1=${totalCredit}, \u8D60\u9001=${giftCredit}, \u8D2D\u4E70=${purchaseCredit}, VIP=${vipCredit}`);
|
|
3423
|
-
}
|
|
3424
|
-
const isJimeng4xMultiImage = ["jimeng-4.0", "jimeng-4.1", "jimeng-4.5"].includes(userModel) && (prompt.includes("\u8FDE\u7EED") || prompt.includes("\u7ED8\u672C") || prompt.includes("\u6545\u4E8B") || /\d+张/.test(prompt));
|
|
3425
|
-
if (isJimeng4xMultiImage) {
|
|
3426
|
-
return await generateJimeng4xMultiImages(
|
|
3427
|
-
userModel,
|
|
3428
|
-
prompt,
|
|
3429
|
-
{ ratio, resolution, sampleStrength, negativePrompt, intelligentRatio, wait, waitTimeoutSeconds, pollIntervalMs },
|
|
3430
|
-
refreshToken,
|
|
3431
|
-
regionInfo
|
|
3432
|
-
);
|
|
3433
|
-
}
|
|
3434
|
-
const componentId = util_default.uuid();
|
|
3435
|
-
const submitId = util_default.uuid();
|
|
3436
|
-
const coreParam = buildCoreParam({
|
|
3437
|
-
userModel,
|
|
3438
|
-
model,
|
|
3439
|
-
prompt,
|
|
3440
|
-
negativePrompt,
|
|
3441
|
-
seed: Math.floor(Math.random() * 1e8) + 25e8,
|
|
3442
|
-
sampleStrength,
|
|
3443
|
-
resolution: resolutionResult,
|
|
3444
|
-
intelligentRatio,
|
|
3445
|
-
mode: "text2img"
|
|
3446
|
-
});
|
|
3447
|
-
const metricsExtra = buildMetricsExtra({
|
|
3448
|
-
userModel,
|
|
3449
|
-
model,
|
|
3450
|
-
regionInfo,
|
|
3451
|
-
submitId,
|
|
3452
|
-
scene: "ImageBasicGenerate",
|
|
3453
|
-
resolutionType: resolutionResult.resolutionType,
|
|
3454
|
-
abilityList: []
|
|
3455
|
-
});
|
|
3456
|
-
const draftContent = buildDraftContent({
|
|
3457
|
-
componentId,
|
|
3458
|
-
generateType: "generate",
|
|
3459
|
-
coreParam
|
|
3460
|
-
});
|
|
3461
|
-
const requestData = buildGenerateRequest({
|
|
3462
|
-
model,
|
|
3463
|
-
regionInfo,
|
|
3464
|
-
submitId,
|
|
3465
|
-
draftContent,
|
|
3466
|
-
metricsExtra
|
|
3467
|
-
});
|
|
3468
|
-
const imageReferer = regionInfo.isCN ? "https://jimeng.jianying.com/ai-tool/generate?type=image" : "https://dreamina.capcut.com/ai-tool/generate?type=image";
|
|
3469
|
-
const { aigc_data } = await request(
|
|
3470
|
-
"post",
|
|
3471
|
-
"/mweb/v1/aigc_draft/generate",
|
|
3472
|
-
refreshToken,
|
|
3473
|
-
regionInfo,
|
|
3474
|
-
{ data: requestData, headers: { Referer: imageReferer } }
|
|
3475
|
-
);
|
|
3476
|
-
const historyId = aigc_data == null ? void 0 : aigc_data.history_record_id;
|
|
3477
|
-
if (!historyId)
|
|
3478
|
-
throw new APIException(exceptions_default.API_IMAGE_GENERATION_FAILED, "\u8BB0\u5F55ID\u4E0D\u5B58\u5728");
|
|
3479
|
-
if (!wait) {
|
|
3480
|
-
logger_default.info(`\u56FE\u50CF\u751F\u6210\u4EFB\u52A1\u5DF2\u63D0\u4EA4\uFF08\u5F02\u6B65\u6A21\u5F0F\uFF09\uFF0Chistory_id: ${historyId}`);
|
|
3481
|
-
return buildPendingTaskInfo(historyId, "image");
|
|
3482
|
-
}
|
|
3483
|
-
const pollerOptions = buildPollerOptions(waitTimeoutSeconds, pollIntervalMs, 1800, 1e4, 900);
|
|
3484
|
-
const poller = new SmartPoller({
|
|
3485
|
-
maxPollCount: pollerOptions.maxPollCount,
|
|
3486
|
-
pollInterval: pollerOptions.pollInterval,
|
|
3487
|
-
expectedItemCount: 4,
|
|
3488
|
-
type: "image",
|
|
3489
|
-
timeoutSeconds: pollerOptions.timeoutSeconds
|
|
3490
|
-
});
|
|
3491
|
-
const { result: pollingResult, data: finalTaskInfo } = await poller.poll(async () => {
|
|
3492
|
-
var _a;
|
|
3493
|
-
const response = await request("post", "/mweb/v1/get_history_by_ids", refreshToken, regionInfo, {
|
|
3494
|
-
data: {
|
|
3495
|
-
history_ids: [historyId],
|
|
3496
|
-
image_info: {
|
|
3497
|
-
width: 2048,
|
|
3498
|
-
height: 2048,
|
|
3499
|
-
format: "webp",
|
|
3500
|
-
image_scene_list: [
|
|
3501
|
-
{ scene: "smart_crop", width: 360, height: 360, uniq_key: "smart_crop-w:360-h:360", format: "webp" },
|
|
3502
|
-
{ scene: "smart_crop", width: 480, height: 480, uniq_key: "smart_crop-w:480-h:480", format: "webp" },
|
|
3503
|
-
{ scene: "smart_crop", width: 720, height: 720, uniq_key: "smart_crop-w:720-h:720", format: "webp" },
|
|
3504
|
-
{ scene: "smart_crop", width: 720, height: 480, uniq_key: "smart_crop-w:720-h:480", format: "webp" },
|
|
3505
|
-
{ scene: "smart_crop", width: 360, height: 240, uniq_key: "smart_crop-w:360-h:240", format: "webp" },
|
|
3506
|
-
{ scene: "smart_crop", width: 240, height: 320, uniq_key: "smart_crop-w:240-h:320", format: "webp" },
|
|
3507
|
-
{ scene: "smart_crop", width: 480, height: 640, uniq_key: "smart_crop-w:480-h:640", format: "webp" },
|
|
3508
|
-
{ scene: "normal", width: 2400, height: 2400, uniq_key: "2400", format: "webp" },
|
|
3509
|
-
{ scene: "normal", width: 1080, height: 1080, uniq_key: "1080", format: "webp" },
|
|
3510
|
-
{ scene: "normal", width: 720, height: 720, uniq_key: "720", format: "webp" },
|
|
3511
|
-
{ scene: "normal", width: 480, height: 480, uniq_key: "480", format: "webp" },
|
|
3512
|
-
{ scene: "normal", width: 360, height: 360, uniq_key: "360", format: "webp" }
|
|
3513
|
-
]
|
|
3514
|
-
}
|
|
3515
|
-
}
|
|
3516
|
-
});
|
|
3517
|
-
if (!response[historyId]) {
|
|
3518
|
-
logger_default.error(`\u5386\u53F2\u8BB0\u5F55\u4E0D\u5B58\u5728: historyId=${historyId}`);
|
|
3519
|
-
throw new APIException(exceptions_default.API_IMAGE_GENERATION_FAILED, "\u8BB0\u5F55\u4E0D\u5B58\u5728");
|
|
3520
|
-
}
|
|
3521
|
-
const taskInfo = response[historyId];
|
|
3522
|
-
return {
|
|
3523
|
-
status: {
|
|
3524
|
-
status: taskInfo.status,
|
|
3525
|
-
failCode: taskInfo.fail_code,
|
|
3526
|
-
itemCount: (taskInfo.item_list || []).length,
|
|
3527
|
-
finishTime: ((_a = taskInfo.task) == null ? void 0 : _a.finish_time) || 0,
|
|
3528
|
-
historyId
|
|
3529
|
-
},
|
|
3530
|
-
data: taskInfo
|
|
3531
|
-
};
|
|
3532
|
-
}, historyId);
|
|
3533
|
-
const item_list = finalTaskInfo.item_list || [];
|
|
3534
|
-
const imageUrls = extractImageUrls(item_list);
|
|
3535
|
-
if (imageUrls.length === 0 && item_list.length > 0) {
|
|
3536
|
-
throw new APIException(exceptions_default.API_IMAGE_GENERATION_FAILED, `\u56FE\u50CF\u751F\u6210\u5931\u8D25: item_list\u6709 ${item_list.length} \u4E2A\u9879\u76EE\uFF0C\u4F46\u65E0\u6CD5\u63D0\u53D6\u4EFB\u4F55\u56FE\u7247URL`);
|
|
3537
|
-
}
|
|
3538
|
-
logger_default.info(`\u56FE\u50CF\u751F\u6210\u5B8C\u6210: \u6210\u529F\u751F\u6210 ${imageUrls.length} \u5F20\u56FE\u7247\uFF0C\u603B\u8017\u65F6 ${pollingResult.elapsedTime} \u79D2\uFF0C\u6700\u7EC8\u72B6\u6001: ${pollingResult.status}`);
|
|
3539
|
-
return imageUrls;
|
|
3540
|
-
}
|
|
3541
|
-
async function generateJimeng4xMultiImages(_model, prompt, {
|
|
3542
|
-
ratio = "1:1",
|
|
3543
|
-
resolution = "2k",
|
|
3544
|
-
sampleStrength = 0.5,
|
|
3545
|
-
negativePrompt = "",
|
|
3546
|
-
intelligentRatio = false,
|
|
3547
|
-
wait = true,
|
|
3548
|
-
waitTimeoutSeconds,
|
|
3549
|
-
pollIntervalMs
|
|
3550
|
-
}, refreshToken, regionInfo) {
|
|
3551
|
-
const { model, userModel } = getModel(_model, regionInfo);
|
|
3552
|
-
const resolutionResult = resolveResolution(userModel, regionInfo, resolution, ratio);
|
|
3553
|
-
const targetImageCount = prompt.match(/(\d+)张/) ? parseInt(prompt.match(/(\d+)张/)[1]) : 4;
|
|
3554
|
-
logger_default.info(`\u4F7F\u7528 \u591A\u56FE\u751F\u6210: ${targetImageCount}\u5F20\u56FE\u7247 ${resolutionResult.width}x${resolutionResult.height} \u7CBE\u7EC6\u5EA6: ${sampleStrength}`);
|
|
3555
|
-
const componentId = util_default.uuid();
|
|
3556
|
-
const submitId = util_default.uuid();
|
|
3557
|
-
const coreParam = buildCoreParam({
|
|
3558
|
-
userModel,
|
|
3559
|
-
model,
|
|
3560
|
-
prompt,
|
|
3561
|
-
negativePrompt,
|
|
3562
|
-
seed: Math.floor(Math.random() * 1e8) + 25e8,
|
|
3563
|
-
sampleStrength,
|
|
3564
|
-
resolution: resolutionResult,
|
|
3565
|
-
intelligentRatio,
|
|
3566
|
-
mode: "text2img"
|
|
3567
|
-
});
|
|
3568
|
-
const metricsExtra = buildMetricsExtra({
|
|
3569
|
-
userModel,
|
|
3570
|
-
model,
|
|
3571
|
-
regionInfo,
|
|
3572
|
-
submitId,
|
|
3573
|
-
scene: "ImageMultiGenerate",
|
|
3574
|
-
resolutionType: resolutionResult.resolutionType,
|
|
3575
|
-
abilityList: [],
|
|
3576
|
-
isMultiImage: true
|
|
3577
|
-
});
|
|
3578
|
-
const draftContent = buildDraftContent({
|
|
3579
|
-
componentId,
|
|
3580
|
-
generateType: "generate",
|
|
3581
|
-
coreParam
|
|
3582
|
-
});
|
|
3583
|
-
const requestData = buildGenerateRequest({
|
|
3584
|
-
model,
|
|
3585
|
-
regionInfo,
|
|
3586
|
-
submitId,
|
|
3587
|
-
draftContent,
|
|
3588
|
-
metricsExtra
|
|
3589
|
-
});
|
|
3590
|
-
const imageReferer = regionInfo.isCN ? "https://jimeng.jianying.com/ai-tool/generate?type=image" : "https://dreamina.capcut.com/ai-tool/generate?type=image";
|
|
3591
|
-
const { aigc_data } = await request(
|
|
3592
|
-
"post",
|
|
3593
|
-
"/mweb/v1/aigc_draft/generate",
|
|
3594
|
-
refreshToken,
|
|
3595
|
-
regionInfo,
|
|
3596
|
-
{ data: requestData, headers: { Referer: imageReferer } }
|
|
3597
|
-
);
|
|
3598
|
-
const historyId = aigc_data == null ? void 0 : aigc_data.history_record_id;
|
|
3599
|
-
if (!historyId)
|
|
3600
|
-
throw new APIException(exceptions_default.API_IMAGE_GENERATION_FAILED, "\u8BB0\u5F55ID\u4E0D\u5B58\u5728");
|
|
3601
|
-
if (!wait) {
|
|
3602
|
-
logger_default.info(`\u591A\u56FE\u751F\u6210\u4EFB\u52A1\u5DF2\u63D0\u4EA4\uFF08\u5F02\u6B65\u6A21\u5F0F\uFF09\uFF0Chistory_id: ${historyId}`);
|
|
3603
|
-
return buildPendingTaskInfo(historyId, "image");
|
|
3604
|
-
}
|
|
3605
|
-
logger_default.info(`\u591A\u56FE\u751F\u6210\u4EFB\u52A1\u5DF2\u63D0\u4EA4\uFF0Csubmit_id: ${submitId}, history_id: ${historyId}\uFF0C\u7B49\u5F85\u751F\u6210 ${targetImageCount} \u5F20\u56FE\u7247...`);
|
|
3606
|
-
const pollerOptions = buildPollerOptions(waitTimeoutSeconds, pollIntervalMs, 1800, 1e4, 600);
|
|
3607
|
-
const poller = new SmartPoller({
|
|
3608
|
-
maxPollCount: pollerOptions.maxPollCount,
|
|
3609
|
-
pollInterval: pollerOptions.pollInterval,
|
|
3610
|
-
expectedItemCount: targetImageCount,
|
|
3611
|
-
type: "image",
|
|
3612
|
-
timeoutSeconds: pollerOptions.timeoutSeconds
|
|
3613
|
-
});
|
|
3614
|
-
const { result: pollingResult, data: finalTaskInfo } = await poller.poll(async () => {
|
|
3615
|
-
var _a;
|
|
3616
|
-
const result = await request("post", "/mweb/v1/get_history_by_ids", refreshToken, regionInfo, {
|
|
3617
|
-
data: {
|
|
3618
|
-
history_ids: [historyId],
|
|
3619
|
-
image_info: {
|
|
3620
|
-
width: 2048,
|
|
3621
|
-
height: 2048,
|
|
3622
|
-
format: "webp",
|
|
3623
|
-
image_scene_list: [
|
|
3624
|
-
{ scene: "smart_crop", width: 360, height: 360, uniq_key: "smart_crop-w:360-h:360", format: "webp" },
|
|
3625
|
-
{ scene: "smart_crop", width: 480, height: 480, uniq_key: "smart_crop-w:480-h:480", format: "webp" },
|
|
3626
|
-
{ scene: "smart_crop", width: 720, height: 720, uniq_key: "smart_crop-w:720-h:720", format: "webp" },
|
|
3627
|
-
{ scene: "smart_crop", width: 720, height: 480, uniq_key: "smart_crop-w:720-h:480", format: "webp" },
|
|
3628
|
-
{ scene: "normal", width: 2400, height: 2400, uniq_key: "2400", format: "webp" },
|
|
3629
|
-
{ scene: "normal", width: 1080, height: 1080, uniq_key: "1080", format: "webp" },
|
|
3630
|
-
{ scene: "normal", width: 720, height: 720, uniq_key: "720", format: "webp" },
|
|
3631
|
-
{ scene: "normal", width: 480, height: 480, uniq_key: "480", format: "webp" },
|
|
3632
|
-
{ scene: "normal", width: 360, height: 360, uniq_key: "360", format: "webp" }
|
|
3633
|
-
]
|
|
3634
|
-
}
|
|
3635
|
-
}
|
|
3636
|
-
});
|
|
3637
|
-
if (!result[historyId])
|
|
3638
|
-
throw new APIException(exceptions_default.API_IMAGE_GENERATION_FAILED, "\u8BB0\u5F55\u4E0D\u5B58\u5728");
|
|
3639
|
-
const taskInfo = result[historyId];
|
|
3640
|
-
return {
|
|
3641
|
-
status: {
|
|
3642
|
-
status: taskInfo.status,
|
|
3643
|
-
failCode: taskInfo.fail_code,
|
|
3644
|
-
itemCount: (taskInfo.item_list || []).length,
|
|
3645
|
-
finishTime: ((_a = taskInfo.task) == null ? void 0 : _a.finish_time) || 0,
|
|
3646
|
-
historyId
|
|
3647
|
-
},
|
|
3648
|
-
data: taskInfo
|
|
3649
|
-
};
|
|
3650
|
-
}, historyId);
|
|
3651
|
-
const item_list = finalTaskInfo.item_list || [];
|
|
3652
|
-
const imageUrls = extractImageUrls(item_list);
|
|
3653
|
-
if (imageUrls.length === 0 && item_list.length > 0) {
|
|
3654
|
-
throw new APIException(exceptions_default.API_IMAGE_GENERATION_FAILED, `\u591A\u56FE\u751F\u6210\u5931\u8D25: item_list\u6709 ${item_list.length} \u4E2A\u9879\u76EE\uFF0C\u4F46\u65E0\u6CD5\u63D0\u53D6\u4EFB\u4F55\u56FE\u7247URL`);
|
|
3655
|
-
}
|
|
3656
|
-
logger_default.info(`\u591A\u56FE\u751F\u6210\u7ED3\u679C: \u6210\u529F\u751F\u6210 ${imageUrls.length} \u5F20\u56FE\u7247\uFF0C\u603B\u8017\u65F6 ${pollingResult.elapsedTime} \u79D2\uFF0C\u6700\u7EC8\u72B6\u6001: ${pollingResult.status}`);
|
|
3657
|
-
return imageUrls;
|
|
3658
|
-
}
|
|
3659
|
-
|
|
3660
|
-
// src/api/controllers/videos.ts
|
|
3661
|
-
import fs7 from "fs-extra";
|
|
3662
|
-
import axios5 from "axios";
|
|
3663
|
-
|
|
3664
|
-
// src/lib/video-uploader.ts
|
|
3665
|
-
import crypto4 from "crypto";
|
|
3666
|
-
import axios4 from "axios";
|
|
3667
|
-
async function uploadVideoBuffer(videoBuffer, refreshToken, regionInfo) {
|
|
3668
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
3669
|
-
try {
|
|
3670
|
-
const fileSize = videoBuffer.byteLength;
|
|
3671
|
-
logger_default.info(`\u5F00\u59CB\u4E0A\u4F20\u89C6\u9891Buffer... (size=${fileSize}, isInternational=${regionInfo.isInternational})`);
|
|
3672
|
-
const tokenResult = await request("post", "/mweb/v1/get_upload_token", refreshToken, regionInfo, {
|
|
3673
|
-
data: {
|
|
3674
|
-
scene: 1
|
|
3675
|
-
// VOD 视频上传场景
|
|
3676
|
-
}
|
|
3677
|
-
});
|
|
3678
|
-
const { access_key_id, secret_access_key, session_token, space_name } = tokenResult;
|
|
3679
|
-
if (!access_key_id || !secret_access_key || !session_token) {
|
|
3680
|
-
throw new Error("\u83B7\u53D6\u89C6\u9891\u4E0A\u4F20\u4EE4\u724C\u5931\u8D25");
|
|
3681
|
-
}
|
|
3682
|
-
const spaceName = space_name || "dreamina";
|
|
3683
|
-
logger_default.info(`\u83B7\u53D6\u89C6\u9891\u4E0A\u4F20\u4EE4\u724C\u6210\u529F: spaceName=${spaceName}`);
|
|
3684
|
-
const now = /* @__PURE__ */ new Date();
|
|
3685
|
-
const timestamp = now.toISOString().replace(/[:\-]/g, "").replace(/\.\d{3}Z$/, "Z");
|
|
3686
|
-
const randomStr = Math.random().toString(36).substring(2, 12);
|
|
3687
|
-
const vodHost = "https://vod.bytedanceapi.com";
|
|
3688
|
-
const applyUrl = `${vodHost}/?Action=ApplyUploadInner&Version=2020-11-19&SpaceName=${spaceName}&FileType=video&IsInner=1&FileSize=${fileSize}&s=${randomStr}`;
|
|
3689
|
-
const awsRegion = RegionUtils.getAWSRegion(regionInfo);
|
|
3690
|
-
const origin = RegionUtils.getOrigin(regionInfo);
|
|
3691
|
-
const requestHeaders = {
|
|
3692
|
-
"x-amz-date": timestamp,
|
|
3693
|
-
"x-amz-security-token": session_token
|
|
3694
|
-
};
|
|
3695
|
-
const authorization = createSignature(
|
|
3696
|
-
"GET",
|
|
3697
|
-
applyUrl,
|
|
3698
|
-
requestHeaders,
|
|
3699
|
-
access_key_id,
|
|
3700
|
-
secret_access_key,
|
|
3701
|
-
session_token,
|
|
3702
|
-
"",
|
|
3703
|
-
awsRegion,
|
|
3704
|
-
"vod"
|
|
3705
|
-
);
|
|
3706
|
-
logger_default.info(`\u7533\u8BF7\u89C6\u9891\u4E0A\u4F20\u6743\u9650: ${applyUrl}`);
|
|
3707
|
-
let applyResponse;
|
|
3708
|
-
try {
|
|
3709
|
-
applyResponse = await axios4({
|
|
3710
|
-
method: "GET",
|
|
3711
|
-
url: applyUrl,
|
|
3712
|
-
headers: {
|
|
3713
|
-
"accept": "*/*",
|
|
3714
|
-
"accept-language": "zh-CN,zh;q=0.9",
|
|
3715
|
-
"authorization": authorization,
|
|
3716
|
-
"origin": origin,
|
|
3717
|
-
"referer": RegionUtils.getRefererPath(regionInfo),
|
|
3718
|
-
"sec-ch-ua": '"Not A(Brand";v="8", "Chromium";v="132", "Google Chrome";v="132"',
|
|
3719
|
-
"sec-ch-ua-mobile": "?0",
|
|
3720
|
-
"sec-ch-ua-platform": '"Windows"',
|
|
3721
|
-
"sec-fetch-dest": "empty",
|
|
3722
|
-
"sec-fetch-mode": "cors",
|
|
3723
|
-
"sec-fetch-site": "cross-site",
|
|
3724
|
-
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36",
|
|
3725
|
-
"x-amz-date": timestamp,
|
|
3726
|
-
"x-amz-security-token": session_token
|
|
3727
|
-
},
|
|
3728
|
-
validateStatus: () => true
|
|
3729
|
-
});
|
|
3730
|
-
} catch (fetchError) {
|
|
3731
|
-
logger_default.error(`ApplyUploadInner\u8BF7\u6C42\u5931\u8D25: ${fetchError.message}`);
|
|
3732
|
-
throw new Error(`\u89C6\u9891\u4E0A\u4F20\u7533\u8BF7\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25 (${vodHost}): ${fetchError.message}`);
|
|
3733
|
-
}
|
|
3734
|
-
if (applyResponse.status < 200 || applyResponse.status >= 300) {
|
|
3735
|
-
const errorText = typeof applyResponse.data === "string" ? applyResponse.data : JSON.stringify(applyResponse.data);
|
|
3736
|
-
throw new Error(`\u7533\u8BF7\u89C6\u9891\u4E0A\u4F20\u6743\u9650\u5931\u8D25: ${applyResponse.status} - ${errorText}`);
|
|
3737
|
-
}
|
|
3738
|
-
const applyResult = applyResponse.data;
|
|
3739
|
-
if ((_a = applyResult == null ? void 0 : applyResult.ResponseMetadata) == null ? void 0 : _a.Error) {
|
|
3740
|
-
throw new Error(`\u7533\u8BF7\u89C6\u9891\u4E0A\u4F20\u6743\u9650\u5931\u8D25: ${JSON.stringify(applyResult.ResponseMetadata.Error)}`);
|
|
3741
|
-
}
|
|
3742
|
-
const uploadNodes = (_c = (_b = applyResult == null ? void 0 : applyResult.Result) == null ? void 0 : _b.InnerUploadAddress) == null ? void 0 : _c.UploadNodes;
|
|
3743
|
-
if (!uploadNodes || uploadNodes.length === 0) {
|
|
3744
|
-
throw new Error(`\u83B7\u53D6\u89C6\u9891\u4E0A\u4F20\u8282\u70B9\u5931\u8D25: ${JSON.stringify(applyResult)}`);
|
|
3745
|
-
}
|
|
3746
|
-
const uploadNode = uploadNodes[0];
|
|
3747
|
-
const storeInfo = (_d = uploadNode.StoreInfos) == null ? void 0 : _d[0];
|
|
3748
|
-
if (!storeInfo) {
|
|
3749
|
-
throw new Error(`\u83B7\u53D6\u89C6\u9891\u4E0A\u4F20\u5B58\u50A8\u4FE1\u606F\u5931\u8D25: ${JSON.stringify(uploadNode)}`);
|
|
3750
|
-
}
|
|
3751
|
-
const uploadHost = uploadNode.UploadHost;
|
|
3752
|
-
const storeUri = storeInfo.StoreUri;
|
|
3753
|
-
const auth = storeInfo.Auth;
|
|
3754
|
-
const sessionKey = uploadNode.SessionKey;
|
|
3755
|
-
const vid = uploadNode.Vid;
|
|
3756
|
-
logger_default.info(`\u83B7\u53D6\u89C6\u9891\u4E0A\u4F20\u8282\u70B9\u6210\u529F: host=${uploadHost}, vid=${vid}, type=${uploadNode.Type}`);
|
|
3757
|
-
const uploadUrl = `https://${uploadHost}/upload/v1/${storeUri}`;
|
|
3758
|
-
const crc32 = util_default.calculateCRC32(videoBuffer);
|
|
3759
|
-
logger_default.info(`\u5F00\u59CB\u4E0A\u4F20\u89C6\u9891\u6587\u4EF6: ${uploadUrl}, CRC32=${crc32}`);
|
|
3760
|
-
let uploadResponse;
|
|
3761
|
-
try {
|
|
3762
|
-
uploadResponse = await axios4({
|
|
3763
|
-
method: "POST",
|
|
3764
|
-
url: uploadUrl,
|
|
3765
|
-
headers: {
|
|
3766
|
-
"Accept": "*/*",
|
|
3767
|
-
"Accept-Language": "zh-CN,zh;q=0.9",
|
|
3768
|
-
"Authorization": auth,
|
|
3769
|
-
"Connection": "keep-alive",
|
|
3770
|
-
"Content-CRC32": crc32,
|
|
3771
|
-
"Content-Type": "application/octet-stream",
|
|
3772
|
-
"Origin": origin,
|
|
3773
|
-
"Referer": RegionUtils.getRefererPath(regionInfo),
|
|
3774
|
-
"Sec-Fetch-Dest": "empty",
|
|
3775
|
-
"Sec-Fetch-Mode": "cors",
|
|
3776
|
-
"Sec-Fetch-Site": "cross-site",
|
|
3777
|
-
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36"
|
|
3778
|
-
},
|
|
3779
|
-
data: videoBuffer,
|
|
3780
|
-
maxContentLength: Infinity,
|
|
3781
|
-
maxBodyLength: Infinity,
|
|
3782
|
-
validateStatus: () => true
|
|
3783
|
-
});
|
|
3784
|
-
} catch (fetchError) {
|
|
3785
|
-
logger_default.error(`\u89C6\u9891\u6587\u4EF6\u4E0A\u4F20\u8BF7\u6C42\u5931\u8D25: ${fetchError.message}`);
|
|
3786
|
-
throw new Error(`\u89C6\u9891\u6587\u4EF6\u4E0A\u4F20\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25 (${uploadHost}): ${fetchError.message}`);
|
|
3787
|
-
}
|
|
3788
|
-
if (uploadResponse.status < 200 || uploadResponse.status >= 300) {
|
|
3789
|
-
const errorText = typeof uploadResponse.data === "string" ? uploadResponse.data : JSON.stringify(uploadResponse.data);
|
|
3790
|
-
throw new Error(`\u89C6\u9891\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25: ${uploadResponse.status} - ${errorText}`);
|
|
3791
|
-
}
|
|
3792
|
-
const uploadData = uploadResponse.data;
|
|
3793
|
-
if ((uploadData == null ? void 0 : uploadData.code) !== 2e3) {
|
|
3794
|
-
throw new Error(`\u89C6\u9891\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25: code=${uploadData == null ? void 0 : uploadData.code}, message=${uploadData == null ? void 0 : uploadData.message}`);
|
|
3795
|
-
}
|
|
3796
|
-
logger_default.info(`\u89C6\u9891\u6587\u4EF6\u4E0A\u4F20\u6210\u529F: crc32=${(_e = uploadData.data) == null ? void 0 : _e.crc32}`);
|
|
3797
|
-
const commitUrl = `${vodHost}/?Action=CommitUploadInner&Version=2020-11-19&SpaceName=${spaceName}`;
|
|
3798
|
-
const commitTimestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:\-]/g, "").replace(/\.\d{3}Z$/, "Z");
|
|
3799
|
-
const commitPayload = JSON.stringify({
|
|
3800
|
-
SessionKey: sessionKey,
|
|
3801
|
-
Functions: []
|
|
3802
|
-
});
|
|
3803
|
-
const payloadHash = crypto4.createHash("sha256").update(commitPayload, "utf8").digest("hex");
|
|
3804
|
-
const commitRequestHeaders = {
|
|
3805
|
-
"x-amz-date": commitTimestamp,
|
|
3806
|
-
"x-amz-security-token": session_token,
|
|
3807
|
-
"x-amz-content-sha256": payloadHash
|
|
3808
|
-
};
|
|
3809
|
-
const commitAuthorization = createSignature(
|
|
3810
|
-
"POST",
|
|
3811
|
-
commitUrl,
|
|
3812
|
-
commitRequestHeaders,
|
|
3813
|
-
access_key_id,
|
|
3814
|
-
secret_access_key,
|
|
3815
|
-
session_token,
|
|
3816
|
-
commitPayload,
|
|
3817
|
-
awsRegion,
|
|
3818
|
-
"vod"
|
|
3819
|
-
);
|
|
3820
|
-
logger_default.info(`\u63D0\u4EA4\u89C6\u9891\u4E0A\u4F20\u786E\u8BA4: ${commitUrl}`);
|
|
3821
|
-
let commitResponse;
|
|
3822
|
-
try {
|
|
3823
|
-
commitResponse = await axios4({
|
|
3824
|
-
method: "POST",
|
|
3825
|
-
url: commitUrl,
|
|
3826
|
-
headers: {
|
|
3827
|
-
"accept": "*/*",
|
|
3828
|
-
"accept-language": "zh-CN,zh;q=0.9",
|
|
3829
|
-
"authorization": commitAuthorization,
|
|
3830
|
-
"content-type": "application/json",
|
|
3831
|
-
"origin": origin,
|
|
3832
|
-
"referer": RegionUtils.getRefererPath(regionInfo),
|
|
3833
|
-
"sec-ch-ua": '"Not A(Brand";v="8", "Chromium";v="132", "Google Chrome";v="132"',
|
|
3834
|
-
"sec-ch-ua-mobile": "?0",
|
|
3835
|
-
"sec-ch-ua-platform": '"Windows"',
|
|
3836
|
-
"sec-fetch-dest": "empty",
|
|
3837
|
-
"sec-fetch-mode": "cors",
|
|
3838
|
-
"sec-fetch-site": "cross-site",
|
|
3839
|
-
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36",
|
|
3840
|
-
"x-amz-date": commitTimestamp,
|
|
3841
|
-
"x-amz-security-token": session_token,
|
|
3842
|
-
"x-amz-content-sha256": payloadHash
|
|
3843
|
-
},
|
|
3844
|
-
data: commitPayload,
|
|
3845
|
-
validateStatus: () => true
|
|
3846
|
-
});
|
|
3847
|
-
} catch (fetchError) {
|
|
3848
|
-
logger_default.error(`CommitUploadInner\u8BF7\u6C42\u5931\u8D25: ${fetchError.message}`);
|
|
3849
|
-
throw new Error(`\u63D0\u4EA4\u89C6\u9891\u4E0A\u4F20\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25 (${vodHost}): ${fetchError.message}`);
|
|
3850
|
-
}
|
|
3851
|
-
if (commitResponse.status < 200 || commitResponse.status >= 300) {
|
|
3852
|
-
const errorText = typeof commitResponse.data === "string" ? commitResponse.data : JSON.stringify(commitResponse.data);
|
|
3853
|
-
throw new Error(`\u63D0\u4EA4\u89C6\u9891\u4E0A\u4F20\u5931\u8D25: ${commitResponse.status} - ${errorText}`);
|
|
3854
|
-
}
|
|
3855
|
-
const commitResult = commitResponse.data;
|
|
3856
|
-
if ((_f = commitResult == null ? void 0 : commitResult.ResponseMetadata) == null ? void 0 : _f.Error) {
|
|
3857
|
-
throw new Error(`\u63D0\u4EA4\u89C6\u9891\u4E0A\u4F20\u5931\u8D25: ${JSON.stringify(commitResult.ResponseMetadata.Error)}`);
|
|
3858
|
-
}
|
|
3859
|
-
if (!((_g = commitResult == null ? void 0 : commitResult.Result) == null ? void 0 : _g.Results) || commitResult.Result.Results.length === 0) {
|
|
3860
|
-
throw new Error(`\u63D0\u4EA4\u89C6\u9891\u4E0A\u4F20\u54CD\u5E94\u7F3A\u5C11\u7ED3\u679C: ${JSON.stringify(commitResult)}`);
|
|
3861
|
-
}
|
|
3862
|
-
const result = commitResult.Result.Results[0];
|
|
3863
|
-
const videoMeta = result.VideoMeta;
|
|
3864
|
-
if (!result.Vid) {
|
|
3865
|
-
throw new Error(`\u63D0\u4EA4\u89C6\u9891\u4E0A\u4F20\u54CD\u5E94\u7F3A\u5C11 Vid: ${JSON.stringify(result)}`);
|
|
3866
|
-
}
|
|
3867
|
-
const MAX_VIDEO_DURATION = 15;
|
|
3868
|
-
if ((videoMeta == null ? void 0 : videoMeta.Duration) && videoMeta.Duration > MAX_VIDEO_DURATION) {
|
|
3869
|
-
throw new Error(`\u89C6\u9891\u65F6\u957F ${videoMeta.Duration.toFixed(2)}s \u8D85\u8FC7\u9650\u5236 (\u6700\u5927 ${MAX_VIDEO_DURATION}s)`);
|
|
3870
|
-
}
|
|
3871
|
-
logger_default.info(`\u89C6\u9891\u4E0A\u4F20\u5B8C\u6210: vid=${result.Vid}, ${videoMeta == null ? void 0 : videoMeta.Width}x${videoMeta == null ? void 0 : videoMeta.Height}, ${videoMeta == null ? void 0 : videoMeta.Duration}s, ${videoMeta == null ? void 0 : videoMeta.Format}/${videoMeta == null ? void 0 : videoMeta.Codec}`);
|
|
3872
|
-
return {
|
|
3873
|
-
vid: result.Vid,
|
|
3874
|
-
uri: (videoMeta == null ? void 0 : videoMeta.Uri) || "",
|
|
3875
|
-
videoMeta: {
|
|
3876
|
-
width: (videoMeta == null ? void 0 : videoMeta.Width) || 0,
|
|
3877
|
-
height: (videoMeta == null ? void 0 : videoMeta.Height) || 0,
|
|
3878
|
-
duration: (videoMeta == null ? void 0 : videoMeta.Duration) || 0,
|
|
3879
|
-
bitrate: (videoMeta == null ? void 0 : videoMeta.Bitrate) || 0,
|
|
3880
|
-
format: (videoMeta == null ? void 0 : videoMeta.Format) || "",
|
|
3881
|
-
codec: (videoMeta == null ? void 0 : videoMeta.Codec) || "",
|
|
3882
|
-
size: (videoMeta == null ? void 0 : videoMeta.Size) || 0,
|
|
3883
|
-
md5: (videoMeta == null ? void 0 : videoMeta.Md5) || ""
|
|
3884
|
-
}
|
|
3885
|
-
};
|
|
3886
|
-
} catch (error) {
|
|
3887
|
-
logger_default.error(`\u89C6\u9891Buffer\u4E0A\u4F20\u5931\u8D25: ${error.message}`);
|
|
3888
|
-
throw error;
|
|
3889
|
-
}
|
|
3890
|
-
}
|
|
3891
|
-
async function uploadVideoFromUrl(videoUrl, refreshToken, regionInfo) {
|
|
3892
|
-
try {
|
|
3893
|
-
logger_default.info(`\u5F00\u59CB\u4ECEURL\u4E0B\u8F7D\u5E76\u4E0A\u4F20\u89C6\u9891: ${videoUrl}`);
|
|
3894
|
-
await assertSafeExternalHttpUrl(videoUrl);
|
|
3895
|
-
const videoResponse = await axios4.get(videoUrl, {
|
|
3896
|
-
responseType: "arraybuffer",
|
|
3897
|
-
maxContentLength: 100 * 1024 * 1024,
|
|
3898
|
-
maxBodyLength: 100 * 1024 * 1024,
|
|
3899
|
-
timeout: 6e4
|
|
3900
|
-
});
|
|
3901
|
-
if (videoResponse.status < 200 || videoResponse.status >= 300) {
|
|
3902
|
-
throw new Error(`\u4E0B\u8F7D\u89C6\u9891\u5931\u8D25: ${videoResponse.status}`);
|
|
3903
|
-
}
|
|
3904
|
-
const videoBuffer = videoResponse.data;
|
|
3905
|
-
logger_default.info(`\u89C6\u9891\u4E0B\u8F7D\u5B8C\u6210: ${videoBuffer.byteLength} \u5B57\u8282`);
|
|
3906
|
-
return await uploadVideoBuffer(videoBuffer, refreshToken, regionInfo);
|
|
3907
|
-
} catch (error) {
|
|
3908
|
-
logger_default.error(`\u4ECEURL\u4E0A\u4F20\u89C6\u9891\u5931\u8D25: ${error.message}`);
|
|
3909
|
-
throw error;
|
|
3910
|
-
}
|
|
3911
|
-
}
|
|
3912
|
-
|
|
3913
|
-
// src/api/controllers/videos.ts
|
|
3914
|
-
var DEFAULT_MODEL2 = DEFAULT_VIDEO_MODEL;
|
|
3915
|
-
function getModel2(model, regionInfo) {
|
|
3916
|
-
let modelMap;
|
|
3917
|
-
if (regionInfo.isUS) {
|
|
3918
|
-
modelMap = VIDEO_MODEL_MAP_US;
|
|
3919
|
-
} else if (regionInfo.isHK || regionInfo.isJP || regionInfo.isSG) {
|
|
3920
|
-
modelMap = VIDEO_MODEL_MAP_ASIA;
|
|
3921
|
-
} else {
|
|
3922
|
-
modelMap = VIDEO_MODEL_MAP;
|
|
3923
|
-
}
|
|
3924
|
-
return modelMap[model] || modelMap[DEFAULT_MODEL2] || VIDEO_MODEL_MAP[DEFAULT_MODEL2];
|
|
3925
|
-
}
|
|
3926
|
-
function getVideoBenefitType(model) {
|
|
3927
|
-
if (model.includes("veo3.1")) {
|
|
3928
|
-
return "generate_video_veo3.1";
|
|
3929
|
-
}
|
|
3930
|
-
if (model.includes("veo3")) {
|
|
3931
|
-
return "generate_video_veo3";
|
|
3932
|
-
}
|
|
3933
|
-
if (model.includes("sora2")) {
|
|
3934
|
-
return "generate_video_sora2";
|
|
3935
|
-
}
|
|
3936
|
-
if (model.includes("40_pro")) {
|
|
3937
|
-
return "dreamina_video_seedance_20_pro";
|
|
3938
|
-
}
|
|
3939
|
-
if (model.includes("40")) {
|
|
3940
|
-
return "dreamina_video_seedance_20_fast";
|
|
3941
|
-
}
|
|
3942
|
-
if (model.includes("3.5_pro")) {
|
|
3943
|
-
return "dreamina_video_seedance_15_pro";
|
|
3944
|
-
}
|
|
3945
|
-
if (model.includes("3.5")) {
|
|
3946
|
-
return "dreamina_video_seedance_15";
|
|
3947
|
-
}
|
|
3948
|
-
return "basic_video_operation_vgfm_v_three";
|
|
3949
|
-
}
|
|
3950
|
-
async function uploadImageFromFile(file, refreshToken, regionInfo) {
|
|
3951
|
-
try {
|
|
3952
|
-
logger_default.info(`\u5F00\u59CB\u4ECE\u672C\u5730\u6587\u4EF6\u4E0A\u4F20\u89C6\u9891\u56FE\u7247: ${file.originalFilename} (\u8DEF\u5F84: ${file.filepath})`);
|
|
3953
|
-
const imageBuffer = await fs7.readFile(file.filepath);
|
|
3954
|
-
return await uploadImageBuffer(imageBuffer, refreshToken, regionInfo);
|
|
3955
|
-
} catch (error) {
|
|
3956
|
-
logger_default.error(`\u4ECE\u672C\u5730\u6587\u4EF6\u4E0A\u4F20\u89C6\u9891\u56FE\u7247\u5931\u8D25: ${error.message}`);
|
|
3957
|
-
throw error;
|
|
3958
|
-
}
|
|
3959
|
-
}
|
|
3960
|
-
async function uploadImageFromUrl2(imageUrl, refreshToken, regionInfo) {
|
|
3961
|
-
try {
|
|
3962
|
-
logger_default.info(`\u5F00\u59CB\u4ECEURL\u4E0B\u8F7D\u5E76\u4E0A\u4F20\u89C6\u9891\u56FE\u7247: ${imageUrl}`);
|
|
3963
|
-
await assertSafeExternalHttpUrl(imageUrl);
|
|
3964
|
-
const imageResponse = await axios5.get(imageUrl, {
|
|
3965
|
-
responseType: "arraybuffer",
|
|
3966
|
-
maxContentLength: 100 * 1024 * 1024,
|
|
3967
|
-
timeout: 6e4,
|
|
3968
|
-
proxy: false
|
|
3969
|
-
});
|
|
3970
|
-
if (imageResponse.status < 200 || imageResponse.status >= 300) {
|
|
3971
|
-
throw new Error(`\u4E0B\u8F7D\u56FE\u7247\u5931\u8D25: ${imageResponse.status}`);
|
|
3972
|
-
}
|
|
3973
|
-
const imageBuffer = imageResponse.data;
|
|
3974
|
-
return await uploadImageBuffer(imageBuffer, refreshToken, regionInfo);
|
|
3975
|
-
} catch (error) {
|
|
3976
|
-
logger_default.error(`\u4ECEURL\u4E0A\u4F20\u89C6\u9891\u56FE\u7247\u5931\u8D25: ${error.message}`);
|
|
3977
|
-
throw error;
|
|
3978
|
-
}
|
|
3979
|
-
}
|
|
3980
|
-
function flattenUploadedFiles(files) {
|
|
3981
|
-
if (!files || typeof files !== "object") return [];
|
|
3982
|
-
const flattened = [];
|
|
3983
|
-
for (const value of Object.values(files)) {
|
|
3984
|
-
if (Array.isArray(value)) {
|
|
3985
|
-
for (const file of value) if (file) flattened.push(file);
|
|
3986
|
-
} else if (value) {
|
|
3987
|
-
flattened.push(value);
|
|
3988
|
-
}
|
|
3989
|
-
}
|
|
3990
|
-
return flattened;
|
|
3991
|
-
}
|
|
3992
|
-
function parseOmniPrompt(prompt, materialRegistry) {
|
|
3993
|
-
const refNames = [...materialRegistry.keys()].sort((a, b) => b.length - a.length).map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
3994
|
-
if (refNames.length === 0) {
|
|
3995
|
-
return [{ meta_type: "text", text: prompt }];
|
|
3996
|
-
}
|
|
3997
|
-
const pattern = new RegExp(`@(${refNames.join("|")})`, "g");
|
|
3998
|
-
const meta_list = [];
|
|
3999
|
-
let lastIndex = 0;
|
|
4000
|
-
let match;
|
|
4001
|
-
while ((match = pattern.exec(prompt)) !== null) {
|
|
4002
|
-
if (match.index > lastIndex) {
|
|
4003
|
-
const textSegment = prompt.slice(lastIndex, match.index);
|
|
4004
|
-
if (textSegment) {
|
|
4005
|
-
meta_list.push({ meta_type: "text", text: textSegment });
|
|
4006
|
-
}
|
|
4007
|
-
}
|
|
4008
|
-
const refName = match[1];
|
|
4009
|
-
const entry = materialRegistry.get(refName);
|
|
4010
|
-
if (entry) {
|
|
4011
|
-
meta_list.push({
|
|
4012
|
-
meta_type: entry.type,
|
|
4013
|
-
text: "",
|
|
4014
|
-
material_ref: { material_idx: entry.idx }
|
|
4015
|
-
});
|
|
4016
|
-
}
|
|
4017
|
-
lastIndex = pattern.lastIndex;
|
|
4018
|
-
}
|
|
4019
|
-
if (lastIndex < prompt.length) {
|
|
4020
|
-
meta_list.push({ meta_type: "text", text: prompt.slice(lastIndex) });
|
|
4021
|
-
}
|
|
4022
|
-
if (meta_list.length === 0) {
|
|
4023
|
-
meta_list.push({ meta_type: "text", text: prompt });
|
|
4024
|
-
}
|
|
4025
|
-
return meta_list;
|
|
4026
|
-
}
|
|
4027
|
-
async function generateVideo(_model, prompt, {
|
|
4028
|
-
ratio = "1:1",
|
|
4029
|
-
resolution = "720p",
|
|
4030
|
-
duration = 5,
|
|
4031
|
-
filePaths = [],
|
|
4032
|
-
files = {},
|
|
4033
|
-
httpRequest,
|
|
4034
|
-
functionMode = "first_last_frames",
|
|
4035
|
-
wait = true,
|
|
4036
|
-
waitTimeoutSeconds,
|
|
4037
|
-
pollIntervalMs
|
|
4038
|
-
}, refreshToken, regionInfo) {
|
|
4039
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
|
|
4040
|
-
const { isInternational } = regionInfo;
|
|
4041
|
-
logger_default.info(`\u89C6\u9891\u751F\u6210\u533A\u57DF\u68C0\u6D4B: isInternational=${isInternational}`);
|
|
4042
|
-
const model = getModel2(_model, regionInfo);
|
|
4043
|
-
const isVeo3 = model.includes("veo3");
|
|
4044
|
-
const isSora2 = model.includes("sora2");
|
|
4045
|
-
const is35Pro = model.includes("3.5_pro");
|
|
4046
|
-
const is40Pro = model.includes("40_pro");
|
|
4047
|
-
const is40 = model.includes("40") && !model.includes("40_pro");
|
|
4048
|
-
const supportsResolution = (model.includes("vgfm_3.0") || model.includes("vgfm_3.0_fast")) && !model.includes("_pro");
|
|
4049
|
-
let durationMs;
|
|
4050
|
-
let actualDuration;
|
|
4051
|
-
if (isVeo3) {
|
|
4052
|
-
durationMs = 8e3;
|
|
4053
|
-
actualDuration = 8;
|
|
4054
|
-
} else if (isSora2) {
|
|
4055
|
-
if (duration === 12) {
|
|
4056
|
-
durationMs = 12e3;
|
|
4057
|
-
actualDuration = 12;
|
|
4058
|
-
} else if (duration === 8) {
|
|
4059
|
-
durationMs = 8e3;
|
|
4060
|
-
actualDuration = 8;
|
|
4061
|
-
} else {
|
|
4062
|
-
durationMs = 4e3;
|
|
4063
|
-
actualDuration = 4;
|
|
4064
|
-
}
|
|
4065
|
-
} else if (is40Pro || is40) {
|
|
4066
|
-
actualDuration = Math.max(4, Math.min(15, duration));
|
|
4067
|
-
durationMs = actualDuration * 1e3;
|
|
4068
|
-
} else if (is35Pro) {
|
|
4069
|
-
if (duration === 12) {
|
|
4070
|
-
durationMs = 12e3;
|
|
4071
|
-
actualDuration = 12;
|
|
4072
|
-
} else if (duration === 10) {
|
|
4073
|
-
durationMs = 1e4;
|
|
4074
|
-
actualDuration = 10;
|
|
4075
|
-
} else {
|
|
4076
|
-
durationMs = 5e3;
|
|
4077
|
-
actualDuration = 5;
|
|
4078
|
-
}
|
|
4079
|
-
} else {
|
|
4080
|
-
durationMs = duration === 10 ? 1e4 : 5e3;
|
|
4081
|
-
actualDuration = duration === 10 ? 10 : 5;
|
|
4082
|
-
}
|
|
4083
|
-
logger_default.info(`\u4F7F\u7528\u6A21\u578B: ${_model} \u6620\u5C04\u6A21\u578B: ${model} \u6BD4\u4F8B: ${ratio} \u5206\u8FA8\u7387: ${supportsResolution ? resolution : "\u4E0D\u652F\u6301"} \u65F6\u957F: ${actualDuration}s`);
|
|
4084
|
-
const { totalCredit } = await getCredit(refreshToken, regionInfo);
|
|
4085
|
-
if (totalCredit <= 0) {
|
|
4086
|
-
logger_default.info("\u79EF\u5206\u4E3A 0\uFF0C\u5C1D\u8BD5\u6536\u53D6\u4ECA\u65E5\u79EF\u5206...");
|
|
4087
|
-
try {
|
|
4088
|
-
await receiveCredit(refreshToken, regionInfo);
|
|
4089
|
-
} catch (receiveError) {
|
|
4090
|
-
logger_default.warn(`\u6536\u53D6\u79EF\u5206\u5931\u8D25: ${receiveError.message}. \u8FD9\u53EF\u80FD\u662F\u56E0\u4E3A: 1) \u4ECA\u65E5\u5DF2\u6536\u53D6\u8FC7\u79EF\u5206, 2) \u8D26\u6237\u53D7\u5230\u98CE\u63A7\u9650\u5236, 3) \u9700\u8981\u5728\u5B98\u7F51\u624B\u52A8\u6536\u53D6\u9996\u6B21\u79EF\u5206`);
|
|
4091
|
-
throw new APIException(
|
|
4092
|
-
exceptions_default.API_VIDEO_GENERATION_FAILED,
|
|
4093
|
-
`\u79EF\u5206\u4E0D\u8DB3\u4E14\u65E0\u6CD5\u81EA\u52A8\u6536\u53D6\u3002\u8BF7\u8BBF\u95EE\u5373\u68A6\u5B98\u7F51\u624B\u52A8\u6536\u53D6\u9996\u6B21\u79EF\u5206\uFF0C\u6216\u68C0\u67E5\u8D26\u6237\u72B6\u6001\u3002`
|
|
4094
|
-
);
|
|
4095
|
-
}
|
|
4096
|
-
}
|
|
4097
|
-
const isOmniMode = functionMode === "omni_reference";
|
|
4098
|
-
if (isOmniMode && !is40Pro && !is40) {
|
|
4099
|
-
throw new APIException(
|
|
4100
|
-
exceptions_default.API_REQUEST_FAILED,
|
|
4101
|
-
`omni_reference \u6A21\u5F0F\u4EC5\u652F\u6301 jimeng-video-seedance-2.0 \u548C jimeng-video-seedance-2.0-fast \u6A21\u578B`
|
|
4102
|
-
);
|
|
4103
|
-
}
|
|
4104
|
-
let requestData;
|
|
4105
|
-
if (isOmniMode) {
|
|
4106
|
-
let registerAlias = function(filename, entry) {
|
|
4107
|
-
if (!canonicalKeys.has(filename) && !materialRegistry.has(filename)) {
|
|
4108
|
-
materialRegistry.set(filename, entry);
|
|
4109
|
-
}
|
|
4110
|
-
};
|
|
4111
|
-
logger_default.info(`\u8FDB\u5165 omni_reference \u5168\u80FD\u6A21\u5F0F`);
|
|
4112
|
-
const materialRegistry = /* @__PURE__ */ new Map();
|
|
4113
|
-
let materialIdx = 0;
|
|
4114
|
-
const canonicalKeys = /* @__PURE__ */ new Set();
|
|
4115
|
-
canonicalKeys.add("image_file");
|
|
4116
|
-
canonicalKeys.add("video_file");
|
|
4117
|
-
for (let i = 1; i <= 9; i++) canonicalKeys.add(`image_file_${i}`);
|
|
4118
|
-
for (let i = 1; i <= 3; i++) canonicalKeys.add(`video_file_${i}`);
|
|
4119
|
-
const imageFields = [];
|
|
4120
|
-
const videoFields = [];
|
|
4121
|
-
if (files) {
|
|
4122
|
-
for (const fieldName of Object.keys(files)) {
|
|
4123
|
-
if (fieldName === "image_file" || fieldName.startsWith("image_file_")) imageFields.push(fieldName);
|
|
4124
|
-
else if (fieldName === "video_file" || fieldName.startsWith("video_file_")) videoFields.push(fieldName);
|
|
4125
|
-
}
|
|
4126
|
-
}
|
|
4127
|
-
for (let i = 1; i <= 9; i++) {
|
|
4128
|
-
const fieldName = `image_file_${i}`;
|
|
4129
|
-
if (typeof ((_a = httpRequest == null ? void 0 : httpRequest.body) == null ? void 0 : _a[fieldName]) === "string" && httpRequest.body[fieldName].startsWith("http")) {
|
|
4130
|
-
if (!imageFields.includes(fieldName)) imageFields.push(fieldName);
|
|
4131
|
-
}
|
|
4132
|
-
}
|
|
4133
|
-
for (let i = 1; i <= 3; i++) {
|
|
4134
|
-
const fieldName = `video_file_${i}`;
|
|
4135
|
-
if (typeof ((_b = httpRequest == null ? void 0 : httpRequest.body) == null ? void 0 : _b[fieldName]) === "string" && httpRequest.body[fieldName].startsWith("http")) {
|
|
4136
|
-
if (!videoFields.includes(fieldName)) videoFields.push(fieldName);
|
|
4137
|
-
}
|
|
4138
|
-
}
|
|
4139
|
-
if (typeof ((_c = httpRequest == null ? void 0 : httpRequest.body) == null ? void 0 : _c.image_file) === "string" && httpRequest.body.image_file.startsWith("http")) {
|
|
4140
|
-
if (!imageFields.includes("image_file")) imageFields.push("image_file");
|
|
4141
|
-
}
|
|
4142
|
-
if (typeof ((_d = httpRequest == null ? void 0 : httpRequest.body) == null ? void 0 : _d.video_file) === "string" && httpRequest.body.video_file.startsWith("http")) {
|
|
4143
|
-
if (!videoFields.includes("video_file")) videoFields.push("video_file");
|
|
4144
|
-
}
|
|
4145
|
-
const hasFilePaths = filePaths && filePaths.length > 0;
|
|
4146
|
-
if (imageFields.length === 0 && videoFields.length === 0 && !hasFilePaths) {
|
|
4147
|
-
throw new APIException(
|
|
4148
|
-
exceptions_default.API_REQUEST_FAILED,
|
|
4149
|
-
`omni_reference \u6A21\u5F0F\u9700\u8981\u81F3\u5C11\u4E0A\u4F20\u4E00\u4E2A\u7D20\u6750\u6587\u4EF6 (image_file_*, video_file_*) \u6216\u63D0\u4F9B\u7D20\u6750URL`
|
|
4150
|
-
);
|
|
4151
|
-
}
|
|
4152
|
-
let totalVideoDuration = 0;
|
|
4153
|
-
for (const fieldName of imageFields) {
|
|
4154
|
-
const rawImageFile = files == null ? void 0 : files[fieldName];
|
|
4155
|
-
const imageFile = Array.isArray(rawImageFile) ? rawImageFile[0] : rawImageFile;
|
|
4156
|
-
const imageUrlField = (_e = httpRequest == null ? void 0 : httpRequest.body) == null ? void 0 : _e[fieldName];
|
|
4157
|
-
try {
|
|
4158
|
-
logger_default.info(`[omni] \u4E0A\u4F20 ${fieldName}`);
|
|
4159
|
-
let imgResult;
|
|
4160
|
-
if (Array.isArray(rawImageFile) && rawImageFile.length > 1) {
|
|
4161
|
-
throw new APIException(exceptions_default.API_REQUEST_FAILED, `${fieldName} \u4E0D\u652F\u6301\u91CD\u590D\u4E0A\u4F20\u591A\u4E2A\u6587\u4EF6`);
|
|
4162
|
-
}
|
|
4163
|
-
if (imageFile) {
|
|
4164
|
-
const buf = await fs7.readFile(imageFile.filepath);
|
|
4165
|
-
imgResult = await uploadImageBuffer(buf, refreshToken, regionInfo);
|
|
4166
|
-
await checkImageContent(imgResult.uri, refreshToken, regionInfo);
|
|
4167
|
-
const entry = {
|
|
4168
|
-
idx: materialIdx++,
|
|
4169
|
-
type: "image",
|
|
4170
|
-
fieldName,
|
|
4171
|
-
originalFilename: imageFile.originalFilename,
|
|
4172
|
-
imageUri: imgResult.uri,
|
|
4173
|
-
imageWidth: imgResult.width,
|
|
4174
|
-
imageHeight: imgResult.height,
|
|
4175
|
-
imageFormat: imgResult.format
|
|
4176
|
-
};
|
|
4177
|
-
materialRegistry.set(fieldName, entry);
|
|
4178
|
-
registerAlias(imageFile.originalFilename, entry);
|
|
4179
|
-
logger_default.info(`[omni] ${fieldName} \u4E0A\u4F20\u6210\u529F: ${imgResult.uri} (${imgResult.width}x${imgResult.height})`);
|
|
4180
|
-
} else if (imageUrlField && typeof imageUrlField === "string" && imageUrlField.startsWith("http")) {
|
|
4181
|
-
imgResult = await uploadImageFromUrl2(imageUrlField, refreshToken, regionInfo);
|
|
4182
|
-
await checkImageContent(imgResult.uri, refreshToken, regionInfo);
|
|
4183
|
-
const entry = {
|
|
4184
|
-
idx: materialIdx++,
|
|
4185
|
-
type: "image",
|
|
4186
|
-
fieldName,
|
|
4187
|
-
originalFilename: imageUrlField,
|
|
4188
|
-
imageUri: imgResult.uri,
|
|
4189
|
-
imageWidth: imgResult.width,
|
|
4190
|
-
imageHeight: imgResult.height,
|
|
4191
|
-
imageFormat: imgResult.format
|
|
4192
|
-
};
|
|
4193
|
-
materialRegistry.set(fieldName, entry);
|
|
4194
|
-
logger_default.info(`[omni] ${fieldName} URL\u4E0A\u4F20\u6210\u529F: ${imgResult.uri} (${imgResult.width}x${imgResult.height})`);
|
|
4195
|
-
}
|
|
4196
|
-
} catch (error) {
|
|
4197
|
-
throw new APIException(exceptions_default.API_REQUEST_FAILED, `${fieldName} \u5904\u7406\u5931\u8D25: ${error.message}`);
|
|
4198
|
-
}
|
|
4199
|
-
}
|
|
4200
|
-
if (filePaths && filePaths.length > 0) {
|
|
4201
|
-
let slotIndex = 1;
|
|
4202
|
-
for (const url of filePaths) {
|
|
4203
|
-
while (slotIndex <= 9 && materialRegistry.has(`image_file_${slotIndex}`)) {
|
|
4204
|
-
slotIndex++;
|
|
4205
|
-
}
|
|
4206
|
-
if (slotIndex > 9) break;
|
|
4207
|
-
const fieldName = `image_file_${slotIndex}`;
|
|
4208
|
-
try {
|
|
4209
|
-
logger_default.info(`[omni] \u4ECEURL\u4E0A\u4F20 ${fieldName}: ${url}`);
|
|
4210
|
-
const imgResult = await uploadImageFromUrl2(url, refreshToken, regionInfo);
|
|
4211
|
-
await checkImageContent(imgResult.uri, refreshToken, regionInfo);
|
|
4212
|
-
const entry = {
|
|
4213
|
-
idx: materialIdx++,
|
|
4214
|
-
type: "image",
|
|
4215
|
-
fieldName,
|
|
4216
|
-
originalFilename: url,
|
|
4217
|
-
imageUri: imgResult.uri,
|
|
4218
|
-
imageWidth: imgResult.width,
|
|
4219
|
-
imageHeight: imgResult.height,
|
|
4220
|
-
imageFormat: imgResult.format
|
|
4221
|
-
};
|
|
4222
|
-
materialRegistry.set(fieldName, entry);
|
|
4223
|
-
logger_default.info(`[omni] ${fieldName} URL\u4E0A\u4F20\u6210\u529F: ${imgResult.uri} (${imgResult.width}x${imgResult.height})`);
|
|
4224
|
-
} catch (error) {
|
|
4225
|
-
throw new APIException(exceptions_default.API_REQUEST_FAILED, `${fieldName} URL\u56FE\u7247\u5904\u7406\u5931\u8D25: ${error.message}`);
|
|
4226
|
-
}
|
|
4227
|
-
slotIndex++;
|
|
4228
|
-
}
|
|
4229
|
-
}
|
|
4230
|
-
for (const fieldName of videoFields) {
|
|
4231
|
-
const rawVideoFile = files == null ? void 0 : files[fieldName];
|
|
4232
|
-
const videoFile = Array.isArray(rawVideoFile) ? rawVideoFile[0] : rawVideoFile;
|
|
4233
|
-
const videoUrlField = (_f = httpRequest == null ? void 0 : httpRequest.body) == null ? void 0 : _f[fieldName];
|
|
4234
|
-
try {
|
|
4235
|
-
logger_default.info(`[omni] \u4E0A\u4F20 ${fieldName}`);
|
|
4236
|
-
let vResult;
|
|
4237
|
-
if (Array.isArray(rawVideoFile) && rawVideoFile.length > 1) {
|
|
4238
|
-
throw new APIException(exceptions_default.API_REQUEST_FAILED, `${fieldName} \u4E0D\u652F\u6301\u91CD\u590D\u4E0A\u4F20\u591A\u4E2A\u6587\u4EF6`);
|
|
4239
|
-
}
|
|
4240
|
-
if (videoFile) {
|
|
4241
|
-
const buf = await fs7.readFile(videoFile.filepath);
|
|
4242
|
-
vResult = await uploadVideoBuffer(buf, refreshToken, regionInfo);
|
|
4243
|
-
totalVideoDuration += vResult.videoMeta.duration;
|
|
4244
|
-
const entry = {
|
|
4245
|
-
idx: materialIdx++,
|
|
4246
|
-
type: "video",
|
|
4247
|
-
fieldName,
|
|
4248
|
-
originalFilename: videoFile.originalFilename,
|
|
4249
|
-
videoResult: vResult
|
|
4250
|
-
};
|
|
4251
|
-
materialRegistry.set(fieldName, entry);
|
|
4252
|
-
registerAlias(videoFile.originalFilename, entry);
|
|
4253
|
-
logger_default.info(`[omni] ${fieldName} \u4E0A\u4F20\u6210\u529F: vid=${vResult.vid}, ${vResult.videoMeta.width}x${vResult.videoMeta.height}, ${vResult.videoMeta.duration}s`);
|
|
4254
|
-
} else if (videoUrlField && typeof videoUrlField === "string" && videoUrlField.startsWith("http")) {
|
|
4255
|
-
vResult = await uploadVideoFromUrl(videoUrlField, refreshToken, regionInfo);
|
|
4256
|
-
totalVideoDuration += vResult.videoMeta.duration;
|
|
4257
|
-
const entry = {
|
|
4258
|
-
idx: materialIdx++,
|
|
4259
|
-
type: "video",
|
|
4260
|
-
fieldName,
|
|
4261
|
-
originalFilename: videoUrlField,
|
|
4262
|
-
videoResult: vResult
|
|
4263
|
-
};
|
|
4264
|
-
materialRegistry.set(fieldName, entry);
|
|
4265
|
-
logger_default.info(`[omni] ${fieldName} URL\u4E0A\u4F20\u6210\u529F: vid=${vResult.vid}, ${vResult.videoMeta.width}x${vResult.videoMeta.height}, ${vResult.videoMeta.duration}s`);
|
|
4266
|
-
}
|
|
4267
|
-
} catch (error) {
|
|
4268
|
-
throw new APIException(exceptions_default.API_REQUEST_FAILED, `${fieldName} \u5904\u7406\u5931\u8D25: ${error.message}`);
|
|
4269
|
-
}
|
|
4270
|
-
}
|
|
4271
|
-
const MAX_TOTAL_VIDEO_DURATION = 15;
|
|
4272
|
-
if (!Number.isFinite(totalVideoDuration)) {
|
|
4273
|
-
throw new APIException(
|
|
4274
|
-
exceptions_default.API_REQUEST_FAILED,
|
|
4275
|
-
`\u89C6\u9891\u65F6\u957F\u6570\u636E\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u89C6\u9891\u6587\u4EF6`
|
|
4276
|
-
);
|
|
4277
|
-
}
|
|
4278
|
-
if (totalVideoDuration > MAX_TOTAL_VIDEO_DURATION) {
|
|
4279
|
-
throw new APIException(
|
|
4280
|
-
exceptions_default.API_REQUEST_FAILED,
|
|
4281
|
-
`\u89C6\u9891\u603B\u65F6\u957F ${totalVideoDuration.toFixed(2)}s \u8D85\u8FC7\u9650\u5236 (\u6700\u5927 ${MAX_TOTAL_VIDEO_DURATION}s)`
|
|
4282
|
-
);
|
|
4283
|
-
}
|
|
4284
|
-
logger_default.info(`[omni] \u89C6\u9891\u603B\u65F6\u957F: ${totalVideoDuration.toFixed(2)}s`);
|
|
4285
|
-
const orderedEntries = [...new Map([...materialRegistry].filter(([k, v]) => k === v.fieldName)).values()].sort((a, b) => a.idx - b.idx);
|
|
4286
|
-
const material_list = [];
|
|
4287
|
-
const materialTypes = [];
|
|
4288
|
-
for (const entry of orderedEntries) {
|
|
4289
|
-
if (entry.type === "image") {
|
|
4290
|
-
material_list.push({
|
|
4291
|
-
type: "",
|
|
4292
|
-
id: util_default.uuid(),
|
|
4293
|
-
material_type: "image",
|
|
4294
|
-
image_info: {
|
|
4295
|
-
type: "image",
|
|
4296
|
-
id: util_default.uuid(),
|
|
4297
|
-
source_from: "upload",
|
|
4298
|
-
platform_type: 1,
|
|
4299
|
-
name: "",
|
|
4300
|
-
image_uri: entry.imageUri,
|
|
4301
|
-
width: entry.imageWidth || 0,
|
|
4302
|
-
height: entry.imageHeight || 0,
|
|
4303
|
-
format: entry.imageFormat || "",
|
|
4304
|
-
uri: entry.imageUri
|
|
4305
|
-
}
|
|
4306
|
-
});
|
|
4307
|
-
materialTypes.push(1);
|
|
4308
|
-
} else {
|
|
4309
|
-
const vm = entry.videoResult;
|
|
4310
|
-
material_list.push({
|
|
4311
|
-
type: "",
|
|
4312
|
-
id: util_default.uuid(),
|
|
4313
|
-
material_type: "video",
|
|
4314
|
-
video_info: {
|
|
4315
|
-
type: "video",
|
|
4316
|
-
id: util_default.uuid(),
|
|
4317
|
-
source_from: "upload",
|
|
4318
|
-
name: "",
|
|
4319
|
-
vid: vm.vid,
|
|
4320
|
-
fps: 0,
|
|
4321
|
-
width: vm.videoMeta.width,
|
|
4322
|
-
height: vm.videoMeta.height,
|
|
4323
|
-
duration: Math.round(vm.videoMeta.duration * 1e3)
|
|
4324
|
-
}
|
|
4325
|
-
});
|
|
4326
|
-
materialTypes.push(2);
|
|
4327
|
-
}
|
|
4328
|
-
}
|
|
4329
|
-
const meta_list = parseOmniPrompt(prompt, materialRegistry);
|
|
4330
|
-
logger_default.info(`[omni] material_list: ${material_list.length} \u9879, meta_list: ${meta_list.length} \u9879, materialTypes: [${materialTypes}]`);
|
|
4331
|
-
const componentId = util_default.uuid();
|
|
4332
|
-
const submitId = util_default.uuid();
|
|
4333
|
-
const sceneOption = {
|
|
4334
|
-
type: "video",
|
|
4335
|
-
scene: "BasicVideoGenerateButton",
|
|
4336
|
-
modelReqKey: model,
|
|
4337
|
-
videoDuration: actualDuration,
|
|
4338
|
-
materialTypes,
|
|
4339
|
-
reportParams: {
|
|
4340
|
-
enterSource: "generate",
|
|
4341
|
-
vipSource: "generate",
|
|
4342
|
-
extraVipFunctionKey: model,
|
|
4343
|
-
useVipFunctionDetailsReporterHoc: true
|
|
4344
|
-
}
|
|
4345
|
-
};
|
|
4346
|
-
const metricsExtra = JSON.stringify({
|
|
4347
|
-
position: "page_bottom_box",
|
|
4348
|
-
isDefaultSeed: 1,
|
|
4349
|
-
originSubmitId: submitId,
|
|
4350
|
-
isRegenerate: false,
|
|
4351
|
-
enterFrom: "click",
|
|
4352
|
-
functionMode: "omni_reference",
|
|
4353
|
-
sceneOptions: JSON.stringify([sceneOption])
|
|
4354
|
-
});
|
|
4355
|
-
const omniBenefitType = is40 ? OMNI_BENEFIT_TYPE_FAST : OMNI_BENEFIT_TYPE;
|
|
4356
|
-
requestData = {
|
|
4357
|
-
params: {
|
|
4358
|
-
aigc_features: "app_lip_sync",
|
|
4359
|
-
web_version: "7.5.0",
|
|
4360
|
-
da_version: DRAFT_VERSION_OMNI
|
|
4361
|
-
},
|
|
4362
|
-
data: {
|
|
4363
|
-
extend: {
|
|
4364
|
-
root_model: model,
|
|
4365
|
-
m_video_commerce_info: {
|
|
4366
|
-
benefit_type: omniBenefitType,
|
|
4367
|
-
resource_id: "generate_video",
|
|
4368
|
-
resource_id_type: "str",
|
|
4369
|
-
resource_sub_type: "aigc"
|
|
4370
|
-
},
|
|
4371
|
-
m_video_commerce_info_list: [{
|
|
4372
|
-
benefit_type: omniBenefitType,
|
|
4373
|
-
resource_id: "generate_video",
|
|
4374
|
-
resource_id_type: "str",
|
|
4375
|
-
resource_sub_type: "aigc"
|
|
4376
|
-
}]
|
|
4377
|
-
},
|
|
4378
|
-
submit_id: submitId,
|
|
4379
|
-
metrics_extra: metricsExtra,
|
|
4380
|
-
draft_content: JSON.stringify({
|
|
4381
|
-
type: "draft",
|
|
4382
|
-
id: util_default.uuid(),
|
|
4383
|
-
min_version: DRAFT_VERSION_OMNI,
|
|
4384
|
-
min_features: ["AIGC_Video_UnifiedEdit"],
|
|
4385
|
-
is_from_tsn: true,
|
|
4386
|
-
version: DRAFT_VERSION_OMNI,
|
|
4387
|
-
main_component_id: componentId,
|
|
4388
|
-
component_list: [{
|
|
4389
|
-
type: "video_base_component",
|
|
4390
|
-
id: componentId,
|
|
4391
|
-
min_version: "1.0.0",
|
|
4392
|
-
aigc_mode: "workbench",
|
|
4393
|
-
metadata: {
|
|
4394
|
-
type: "",
|
|
4395
|
-
id: util_default.uuid(),
|
|
4396
|
-
created_platform: 3,
|
|
4397
|
-
created_platform_version: "",
|
|
4398
|
-
created_time_in_ms: Date.now().toString(),
|
|
4399
|
-
created_did: ""
|
|
4400
|
-
},
|
|
4401
|
-
generate_type: "gen_video",
|
|
4402
|
-
abilities: {
|
|
4403
|
-
type: "",
|
|
4404
|
-
id: util_default.uuid(),
|
|
4405
|
-
gen_video: {
|
|
4406
|
-
id: util_default.uuid(),
|
|
4407
|
-
type: "",
|
|
4408
|
-
text_to_video_params: {
|
|
4409
|
-
type: "",
|
|
4410
|
-
id: util_default.uuid(),
|
|
4411
|
-
video_gen_inputs: [{
|
|
4412
|
-
type: "",
|
|
4413
|
-
id: util_default.uuid(),
|
|
4414
|
-
min_version: DRAFT_VERSION_OMNI,
|
|
4415
|
-
prompt: "",
|
|
4416
|
-
video_mode: 2,
|
|
4417
|
-
fps: 24,
|
|
4418
|
-
duration_ms: durationMs,
|
|
4419
|
-
unified_edit_input: {
|
|
4420
|
-
type: "",
|
|
4421
|
-
id: util_default.uuid(),
|
|
4422
|
-
material_list,
|
|
4423
|
-
meta_list
|
|
4424
|
-
},
|
|
4425
|
-
idip_meta_list: []
|
|
4426
|
-
}],
|
|
4427
|
-
video_aspect_ratio: ratio,
|
|
4428
|
-
seed: Math.floor(Math.random() * 4294967296),
|
|
4429
|
-
model_req_key: model,
|
|
4430
|
-
priority: 0
|
|
4431
|
-
},
|
|
4432
|
-
video_task_extra: metricsExtra
|
|
4433
|
-
}
|
|
4434
|
-
},
|
|
4435
|
-
process_type: 1
|
|
4436
|
-
}]
|
|
4437
|
-
}),
|
|
4438
|
-
http_common_info: {
|
|
4439
|
-
aid: getAssistantId(regionInfo)
|
|
4440
|
-
}
|
|
4441
|
-
}
|
|
4442
|
-
};
|
|
4443
|
-
} else {
|
|
4444
|
-
let first_frame_image = void 0;
|
|
4445
|
-
let end_frame_image = void 0;
|
|
4446
|
-
let uploadIDs = [];
|
|
4447
|
-
const uploadedFiles = flattenUploadedFiles(files);
|
|
4448
|
-
if (uploadedFiles && uploadedFiles.length > 0) {
|
|
4449
|
-
logger_default.info(`\u68C0\u6D4B\u5230 ${uploadedFiles.length} \u4E2A\u672C\u5730\u4E0A\u4F20\u6587\u4EF6\uFF0C\u4F18\u5148\u5904\u7406`);
|
|
4450
|
-
for (let i = 0; i < uploadedFiles.length; i++) {
|
|
4451
|
-
const file = uploadedFiles[i];
|
|
4452
|
-
if (!file) continue;
|
|
4453
|
-
try {
|
|
4454
|
-
logger_default.info(`\u5F00\u59CB\u4E0A\u4F20\u7B2C ${i + 1} \u5F20\u672C\u5730\u56FE\u7247: ${file.originalFilename}`);
|
|
4455
|
-
const imgResult = await uploadImageFromFile(file, refreshToken, regionInfo);
|
|
4456
|
-
if (imgResult) {
|
|
4457
|
-
await checkImageContent(imgResult.uri, refreshToken, regionInfo);
|
|
4458
|
-
uploadIDs.push(imgResult.uri);
|
|
4459
|
-
logger_default.info(`\u7B2C ${i + 1} \u5F20\u672C\u5730\u56FE\u7247\u4E0A\u4F20\u6210\u529F: ${imgResult.uri}`);
|
|
4460
|
-
} else {
|
|
4461
|
-
logger_default.error(`\u7B2C ${i + 1} \u5F20\u672C\u5730\u56FE\u7247\u4E0A\u4F20\u5931\u8D25: \u672A\u83B7\u53D6\u5230 image_uri`);
|
|
4462
|
-
}
|
|
4463
|
-
} catch (error) {
|
|
4464
|
-
logger_default.error(`\u7B2C ${i + 1} \u5F20\u672C\u5730\u56FE\u7247\u4E0A\u4F20\u5931\u8D25: ${error.message}`);
|
|
4465
|
-
if (i === 0) {
|
|
4466
|
-
throw new APIException(exceptions_default.API_REQUEST_FAILED, `\u9996\u5E27\u56FE\u7247\u4E0A\u4F20\u5931\u8D25: ${error.message}`);
|
|
4467
|
-
}
|
|
4468
|
-
}
|
|
4469
|
-
}
|
|
4470
|
-
} else if (filePaths && filePaths.length > 0) {
|
|
4471
|
-
logger_default.info(`\u672A\u68C0\u6D4B\u5230\u672C\u5730\u4E0A\u4F20\u6587\u4EF6\uFF0C\u5904\u7406 ${filePaths.length} \u4E2A\u56FE\u7247URL`);
|
|
4472
|
-
for (let i = 0; i < filePaths.length; i++) {
|
|
4473
|
-
const filePath = filePaths[i];
|
|
4474
|
-
if (!filePath) {
|
|
4475
|
-
logger_default.warn(`\u7B2C ${i + 1} \u4E2A\u56FE\u7247URL\u4E3A\u7A7A\uFF0C\u8DF3\u8FC7`);
|
|
4476
|
-
continue;
|
|
4477
|
-
}
|
|
4478
|
-
try {
|
|
4479
|
-
logger_default.info(`\u5F00\u59CB\u4E0A\u4F20\u7B2C ${i + 1} \u4E2AURL\u56FE\u7247: ${filePath}`);
|
|
4480
|
-
const imgResult = await uploadImageFromUrl2(filePath, refreshToken, regionInfo);
|
|
4481
|
-
if (imgResult) {
|
|
4482
|
-
await checkImageContent(imgResult.uri, refreshToken, regionInfo);
|
|
4483
|
-
uploadIDs.push(imgResult.uri);
|
|
4484
|
-
logger_default.info(`\u7B2C ${i + 1} \u4E2AURL\u56FE\u7247\u4E0A\u4F20\u6210\u529F: ${imgResult.uri}`);
|
|
4485
|
-
} else {
|
|
4486
|
-
logger_default.error(`\u7B2C ${i + 1} \u4E2AURL\u56FE\u7247\u4E0A\u4F20\u5931\u8D25: \u672A\u83B7\u53D6\u5230 image_uri`);
|
|
4487
|
-
}
|
|
4488
|
-
} catch (error) {
|
|
4489
|
-
logger_default.error(`\u7B2C ${i + 1} \u4E2AURL\u56FE\u7247\u4E0A\u4F20\u5931\u8D25: ${error.message}`);
|
|
4490
|
-
if (i === 0) {
|
|
4491
|
-
throw new APIException(exceptions_default.API_REQUEST_FAILED, `\u9996\u5E27\u56FE\u7247\u4E0A\u4F20\u5931\u8D25: ${error.message}`);
|
|
4492
|
-
}
|
|
4493
|
-
}
|
|
4494
|
-
}
|
|
4495
|
-
} else {
|
|
4496
|
-
logger_default.info(`\u672A\u63D0\u4F9B\u56FE\u7247\u6587\u4EF6\u6216URL\uFF0C\u5C06\u8FDB\u884C\u7EAF\u6587\u672C\u89C6\u9891\u751F\u6210`);
|
|
4497
|
-
}
|
|
4498
|
-
if (uploadIDs.length > 0) {
|
|
4499
|
-
logger_default.info(`\u56FE\u7247\u4E0A\u4F20\u5B8C\u6210\uFF0C\u5171\u6210\u529F ${uploadIDs.length} \u5F20`);
|
|
4500
|
-
if (uploadIDs[0]) {
|
|
4501
|
-
first_frame_image = {
|
|
4502
|
-
format: "",
|
|
4503
|
-
height: 0,
|
|
4504
|
-
id: util_default.uuid(),
|
|
4505
|
-
image_uri: uploadIDs[0],
|
|
4506
|
-
name: "",
|
|
4507
|
-
platform_type: 1,
|
|
4508
|
-
source_from: "upload",
|
|
4509
|
-
type: "image",
|
|
4510
|
-
uri: uploadIDs[0],
|
|
4511
|
-
width: 0
|
|
4512
|
-
};
|
|
4513
|
-
logger_default.info(`\u8BBE\u7F6E\u9996\u5E27\u56FE\u7247: ${uploadIDs[0]}`);
|
|
4514
|
-
}
|
|
4515
|
-
if (uploadIDs[1]) {
|
|
4516
|
-
end_frame_image = {
|
|
4517
|
-
format: "",
|
|
4518
|
-
height: 0,
|
|
4519
|
-
id: util_default.uuid(),
|
|
4520
|
-
image_uri: uploadIDs[1],
|
|
4521
|
-
name: "",
|
|
4522
|
-
platform_type: 1,
|
|
4523
|
-
source_from: "upload",
|
|
4524
|
-
type: "image",
|
|
4525
|
-
uri: uploadIDs[1],
|
|
4526
|
-
width: 0
|
|
4527
|
-
};
|
|
4528
|
-
logger_default.info(`\u8BBE\u7F6E\u5C3E\u5E27\u56FE\u7247: ${uploadIDs[1]}`);
|
|
4529
|
-
}
|
|
4530
|
-
}
|
|
4531
|
-
const componentId = util_default.uuid();
|
|
4532
|
-
const originSubmitId = util_default.uuid();
|
|
4533
|
-
const flFunctionMode = "first_last_frames";
|
|
4534
|
-
const sceneOption = {
|
|
4535
|
-
type: "video",
|
|
4536
|
-
scene: "BasicVideoGenerateButton",
|
|
4537
|
-
...supportsResolution ? { resolution } : {},
|
|
4538
|
-
modelReqKey: model,
|
|
4539
|
-
videoDuration: actualDuration,
|
|
4540
|
-
reportParams: {
|
|
4541
|
-
enterSource: "generate",
|
|
4542
|
-
vipSource: "generate",
|
|
4543
|
-
extraVipFunctionKey: supportsResolution ? `${model}-${resolution}` : model,
|
|
4544
|
-
useVipFunctionDetailsReporterHoc: true
|
|
4545
|
-
}
|
|
4546
|
-
};
|
|
4547
|
-
const metricsExtra = JSON.stringify({
|
|
4548
|
-
promptSource: "custom",
|
|
4549
|
-
isDefaultSeed: 1,
|
|
4550
|
-
originSubmitId,
|
|
4551
|
-
isRegenerate: false,
|
|
4552
|
-
enterFrom: "click",
|
|
4553
|
-
functionMode: flFunctionMode,
|
|
4554
|
-
sceneOptions: JSON.stringify([sceneOption])
|
|
4555
|
-
});
|
|
4556
|
-
const hasImageInput = uploadIDs.length > 0;
|
|
4557
|
-
if (hasImageInput && ratio !== "1:1") {
|
|
4558
|
-
logger_default.warn(`\u56FE\u751F\u89C6\u9891\u6A21\u5F0F\u4E0B\uFF0Cratio\u53C2\u6570\u5C06\u88AB\u5FFD\u7565\uFF08\u7531\u8F93\u5165\u56FE\u7247\u7684\u5B9E\u9645\u6BD4\u4F8B\u51B3\u5B9A\uFF09\uFF0C\u4F46resolution\u53C2\u6570\u4ECD\u7136\u6709\u6548`);
|
|
4559
|
-
}
|
|
4560
|
-
logger_default.info(`\u89C6\u9891\u751F\u6210\u6A21\u5F0F: ${uploadIDs.length}\u5F20\u56FE\u7247 (\u9996\u5E27: ${!!first_frame_image}, \u5C3E\u5E27: ${!!end_frame_image}), resolution: ${resolution}`);
|
|
4561
|
-
requestData = {
|
|
4562
|
-
params: {
|
|
4563
|
-
aigc_features: "app_lip_sync",
|
|
4564
|
-
web_version: "7.5.0",
|
|
4565
|
-
da_version: DRAFT_VERSION
|
|
4566
|
-
},
|
|
4567
|
-
data: {
|
|
4568
|
-
extend: {
|
|
4569
|
-
root_model: model,
|
|
4570
|
-
m_video_commerce_info: {
|
|
4571
|
-
benefit_type: getVideoBenefitType(model),
|
|
4572
|
-
resource_id: "generate_video",
|
|
4573
|
-
resource_id_type: "str",
|
|
4574
|
-
resource_sub_type: "aigc"
|
|
4575
|
-
},
|
|
4576
|
-
m_video_commerce_info_list: [{
|
|
4577
|
-
benefit_type: getVideoBenefitType(model),
|
|
4578
|
-
resource_id: "generate_video",
|
|
4579
|
-
resource_id_type: "str",
|
|
4580
|
-
resource_sub_type: "aigc"
|
|
4581
|
-
}]
|
|
4582
|
-
},
|
|
4583
|
-
submit_id: util_default.uuid(),
|
|
4584
|
-
metrics_extra: metricsExtra,
|
|
4585
|
-
draft_content: JSON.stringify({
|
|
4586
|
-
type: "draft",
|
|
4587
|
-
id: util_default.uuid(),
|
|
4588
|
-
min_version: "3.0.5",
|
|
4589
|
-
min_features: [],
|
|
4590
|
-
is_from_tsn: true,
|
|
4591
|
-
version: DRAFT_VERSION,
|
|
4592
|
-
main_component_id: componentId,
|
|
4593
|
-
component_list: [{
|
|
4594
|
-
type: "video_base_component",
|
|
4595
|
-
id: componentId,
|
|
4596
|
-
min_version: "1.0.0",
|
|
4597
|
-
aigc_mode: "workbench",
|
|
4598
|
-
metadata: {
|
|
4599
|
-
type: "",
|
|
4600
|
-
id: util_default.uuid(),
|
|
4601
|
-
created_platform: 3,
|
|
4602
|
-
created_platform_version: "",
|
|
4603
|
-
created_time_in_ms: Date.now().toString(),
|
|
4604
|
-
created_did: ""
|
|
4605
|
-
},
|
|
4606
|
-
generate_type: "gen_video",
|
|
4607
|
-
abilities: {
|
|
4608
|
-
type: "",
|
|
4609
|
-
id: util_default.uuid(),
|
|
4610
|
-
gen_video: {
|
|
4611
|
-
id: util_default.uuid(),
|
|
4612
|
-
type: "",
|
|
4613
|
-
text_to_video_params: {
|
|
4614
|
-
type: "",
|
|
4615
|
-
id: util_default.uuid(),
|
|
4616
|
-
video_gen_inputs: [{
|
|
4617
|
-
type: "",
|
|
4618
|
-
id: util_default.uuid(),
|
|
4619
|
-
min_version: "3.0.5",
|
|
4620
|
-
prompt,
|
|
4621
|
-
video_mode: 2,
|
|
4622
|
-
fps: 24,
|
|
4623
|
-
duration_ms: durationMs,
|
|
4624
|
-
...supportsResolution ? { resolution } : {},
|
|
4625
|
-
first_frame_image,
|
|
4626
|
-
end_frame_image,
|
|
4627
|
-
idip_meta_list: []
|
|
4628
|
-
}],
|
|
4629
|
-
video_aspect_ratio: ratio,
|
|
4630
|
-
seed: Math.floor(Math.random() * 4294967296),
|
|
4631
|
-
model_req_key: model,
|
|
4632
|
-
priority: 0
|
|
4633
|
-
},
|
|
4634
|
-
video_task_extra: metricsExtra
|
|
4635
|
-
}
|
|
4636
|
-
},
|
|
4637
|
-
process_type: 1
|
|
4638
|
-
}]
|
|
4639
|
-
}),
|
|
4640
|
-
http_common_info: {
|
|
4641
|
-
aid: getAssistantId(regionInfo)
|
|
4642
|
-
}
|
|
4643
|
-
}
|
|
4644
|
-
};
|
|
4645
|
-
}
|
|
4646
|
-
const videoReferer = regionInfo.isCN ? "https://jimeng.jianying.com/ai-tool/generate?type=video" : "https://dreamina.capcut.com/ai-tool/generate?type=video";
|
|
4647
|
-
const { aigc_data } = await request(
|
|
4648
|
-
"post",
|
|
4649
|
-
"/mweb/v1/aigc_draft/generate",
|
|
4650
|
-
refreshToken,
|
|
4651
|
-
regionInfo,
|
|
4652
|
-
{
|
|
4653
|
-
...requestData,
|
|
4654
|
-
headers: { Referer: videoReferer }
|
|
4655
|
-
}
|
|
4656
|
-
);
|
|
4657
|
-
const historyId = aigc_data.history_record_id;
|
|
4658
|
-
if (!historyId)
|
|
4659
|
-
throw new APIException(exceptions_default.API_VIDEO_GENERATION_FAILED, "\u8BB0\u5F55ID\u4E0D\u5B58\u5728");
|
|
4660
|
-
if (!wait) {
|
|
4661
|
-
logger_default.info(`\u89C6\u9891\u751F\u6210\u4EFB\u52A1\u5DF2\u63D0\u4EA4\uFF08\u5F02\u6B65\u6A21\u5F0F\uFF09\uFF0Chistory_id: ${historyId}`);
|
|
4662
|
-
return buildPendingTaskInfo(historyId, "video");
|
|
4663
|
-
}
|
|
4664
|
-
logger_default.info(`\u89C6\u9891\u751F\u6210\u4EFB\u52A1\u5DF2\u63D0\u4EA4\uFF0Chistory_id: ${historyId}\uFF0C\u7B49\u5F85\u751F\u6210\u5B8C\u6210...`);
|
|
4665
|
-
await new Promise((resolve) => setTimeout(resolve, 5e3));
|
|
4666
|
-
const pollerOptions = buildPollerOptions(waitTimeoutSeconds, pollIntervalMs, 3600, 2e4, 900);
|
|
4667
|
-
const maxPollCount = pollerOptions.maxPollCount;
|
|
4668
|
-
let pollAttempts = 0;
|
|
4669
|
-
const poller = new SmartPoller({
|
|
4670
|
-
maxPollCount,
|
|
4671
|
-
pollInterval: pollerOptions.pollInterval,
|
|
4672
|
-
expectedItemCount: 1,
|
|
4673
|
-
type: "video",
|
|
4674
|
-
timeoutSeconds: pollerOptions.timeoutSeconds
|
|
4675
|
-
});
|
|
4676
|
-
const { result: pollingResult, data: finalHistoryData } = await poller.poll(async () => {
|
|
4677
|
-
var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2, _k2;
|
|
4678
|
-
pollAttempts++;
|
|
4679
|
-
const result = await request("post", "/mweb/v1/get_history_by_ids", refreshToken, regionInfo, {
|
|
4680
|
-
data: {
|
|
4681
|
-
history_ids: [historyId]
|
|
4682
|
-
}
|
|
4683
|
-
});
|
|
4684
|
-
if (!result[historyId]) {
|
|
4685
|
-
logger_default.warn(`API\u672A\u8FD4\u56DE\u5386\u53F2\u8BB0\u5F55 (\u8F6E\u8BE2\u7B2C${pollAttempts}\u6B21)\uFF0ChistoryId: ${historyId}\uFF0C\u7EE7\u7EED\u7B49\u5F85...`);
|
|
4686
|
-
return {
|
|
4687
|
-
status: {
|
|
4688
|
-
status: 20,
|
|
4689
|
-
// PROCESSING
|
|
4690
|
-
itemCount: 0,
|
|
4691
|
-
historyId
|
|
4692
|
-
},
|
|
4693
|
-
data: { status: 20, item_list: [] }
|
|
4694
|
-
};
|
|
4695
|
-
}
|
|
4696
|
-
const historyData = result[historyId];
|
|
4697
|
-
const currentStatus = historyData.status;
|
|
4698
|
-
const currentFailCode = historyData.fail_code;
|
|
4699
|
-
const currentItemList = historyData.item_list || [];
|
|
4700
|
-
const finishTime = ((_a2 = historyData.task) == null ? void 0 : _a2.finish_time) || 0;
|
|
4701
|
-
if (currentItemList.length > 0) {
|
|
4702
|
-
const tempVideoUrl = ((_e2 = (_d2 = (_c2 = (_b2 = currentItemList[0]) == null ? void 0 : _b2.video) == null ? void 0 : _c2.transcoded_video) == null ? void 0 : _d2.origin) == null ? void 0 : _e2.video_url) || ((_g2 = (_f2 = currentItemList[0]) == null ? void 0 : _f2.video) == null ? void 0 : _g2.play_url) || ((_i2 = (_h2 = currentItemList[0]) == null ? void 0 : _h2.video) == null ? void 0 : _i2.download_url) || ((_k2 = (_j2 = currentItemList[0]) == null ? void 0 : _j2.video) == null ? void 0 : _k2.url);
|
|
4703
|
-
if (tempVideoUrl) {
|
|
4704
|
-
logger_default.info(`\u68C0\u6D4B\u5230\u89C6\u9891URL: ${tempVideoUrl}`);
|
|
4705
|
-
}
|
|
4706
|
-
}
|
|
4707
|
-
return {
|
|
4708
|
-
status: {
|
|
4709
|
-
status: currentStatus,
|
|
4710
|
-
failCode: currentFailCode,
|
|
4711
|
-
itemCount: currentItemList.length,
|
|
4712
|
-
finishTime,
|
|
4713
|
-
historyId
|
|
4714
|
-
},
|
|
4715
|
-
data: historyData
|
|
4716
|
-
};
|
|
4717
|
-
}, historyId);
|
|
4718
|
-
const item_list = finalHistoryData.item_list || [];
|
|
4719
|
-
const itemId = ((_g = item_list == null ? void 0 : item_list[0]) == null ? void 0 : _g.item_id) || ((_h = item_list == null ? void 0 : item_list[0]) == null ? void 0 : _h.id) || ((_i = item_list == null ? void 0 : item_list[0]) == null ? void 0 : _i.local_item_id) || ((_k = (_j = item_list == null ? void 0 : item_list[0]) == null ? void 0 : _j.common_attr) == null ? void 0 : _k.id);
|
|
4720
|
-
if (itemId) {
|
|
4721
|
-
try {
|
|
4722
|
-
const hqVideoUrl = await fetchHighQualityVideoUrl(String(itemId), refreshToken, regionInfo);
|
|
4723
|
-
if (hqVideoUrl) {
|
|
4724
|
-
logger_default.info(`\u89C6\u9891\u751F\u6210\u6210\u529F\uFF08\u9AD8\u8D28\u91CF\uFF09\uFF0CURL: ${hqVideoUrl}\uFF0C\u603B\u8017\u65F6: ${pollingResult.elapsedTime}\u79D2`);
|
|
4725
|
-
return hqVideoUrl;
|
|
4726
|
-
}
|
|
4727
|
-
} catch (error) {
|
|
4728
|
-
logger_default.warn(`\u83B7\u53D6\u9AD8\u8D28\u91CF\u89C6\u9891URL\u5931\u8D25\uFF0C\u5C06\u4F7F\u7528\u9884\u89C8URL\u4F5C\u4E3A\u56DE\u9000: ${error.message}`);
|
|
4729
|
-
}
|
|
4730
|
-
} else {
|
|
4731
|
-
logger_default.warn(`\u672A\u80FD\u4ECEitem_list\u4E2D\u63D0\u53D6item_id\uFF0C\u5C06\u4F7F\u7528\u9884\u89C8URL\u3002item_list[0]\u952E: ${(item_list == null ? void 0 : item_list[0]) ? Object.keys(item_list[0]).join(", ") : "\u65E0"}`);
|
|
4732
|
-
}
|
|
4733
|
-
let fallbackVideoUrl = (item_list == null ? void 0 : item_list[0]) ? extractVideoUrl(item_list[0]) : null;
|
|
4734
|
-
if (!fallbackVideoUrl) {
|
|
4735
|
-
logger_default.error(`\u672A\u80FD\u83B7\u53D6\u89C6\u9891URL\uFF0Citem_list: ${JSON.stringify(item_list)}`);
|
|
4736
|
-
throw new APIException(exceptions_default.API_VIDEO_GENERATION_FAILED, "\u672A\u80FD\u83B7\u53D6\u89C6\u9891URL\uFF0C\u8BF7\u7A0D\u540E\u67E5\u770B");
|
|
4737
|
-
}
|
|
4738
|
-
logger_default.info(`\u89C6\u9891\u751F\u6210\u6210\u529F\uFF0CURL: ${fallbackVideoUrl}\uFF0C\u603B\u8017\u65F6: ${pollingResult.elapsedTime}\u79D2`);
|
|
4739
|
-
return fallbackVideoUrl;
|
|
4740
|
-
}
|
|
4741
|
-
|
|
4742
|
-
export {
|
|
4743
|
-
environment_default,
|
|
4744
|
-
util_default,
|
|
4745
|
-
config_default,
|
|
4746
|
-
logger_default,
|
|
4747
|
-
DEFAULT_IMAGE_MODEL,
|
|
4748
|
-
parseRegionCode,
|
|
4749
|
-
buildRegionInfo,
|
|
4750
|
-
getCredit,
|
|
4751
|
-
receiveCredit,
|
|
4752
|
-
getTokenLiveStatus,
|
|
4753
|
-
session_pool_default,
|
|
4754
|
-
getLiveModels,
|
|
4755
|
-
getTaskResponse,
|
|
4756
|
-
waitForTaskResponse,
|
|
4757
|
-
generateImageComposition,
|
|
4758
|
-
generateImages,
|
|
4759
|
-
DEFAULT_MODEL2 as DEFAULT_MODEL,
|
|
4760
|
-
generateVideo
|
|
4761
|
-
};
|
|
4762
|
-
//# sourceMappingURL=chunk-JZY62VNI.js.map
|