@secret-momo/utils 1.9.0 → 2.0.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/LICENSE +21 -0
- package/README.md +215 -6
- package/dist/date-time.js +23 -0
- package/{lib → dist}/download/aria2.d.ts +5 -4
- package/dist/download/aria2.js +134 -0
- package/{lib → dist}/download/extension.d.ts +1 -0
- package/dist/download/extension.js +96 -0
- package/{lib → dist}/download/index.d.ts +6 -6
- package/dist/download/index.js +94 -0
- package/dist/download/types.js +1 -0
- package/dist/env.d.ts +9 -0
- package/dist/env.js +76 -0
- package/dist/fetch.d.ts +33 -0
- package/dist/fetch.js +174 -0
- package/dist/file.js +14 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +12 -0
- package/{lib → dist}/mihomo/cache.d.ts +2 -2
- package/dist/mihomo/cache.js +6 -0
- package/dist/mihomo/client.d.ts +22 -0
- package/dist/mihomo/client.js +80 -0
- package/{lib → dist}/mihomo/configs.d.ts +2 -2
- package/dist/mihomo/configs.js +13 -0
- package/{lib → dist}/mihomo/connections.d.ts +5 -3
- package/dist/mihomo/connections.js +8 -0
- package/{lib → dist}/mihomo/debug.d.ts +3 -3
- package/dist/mihomo/debug.js +6 -0
- package/{lib → dist}/mihomo/dns.d.ts +2 -2
- package/dist/mihomo/dns.js +5 -0
- package/{lib → dist}/mihomo/groups.d.ts +2 -2
- package/dist/mihomo/groups.js +11 -0
- package/dist/mihomo/index.d.ts +39 -0
- package/dist/mihomo/index.js +40 -0
- package/{lib → dist}/mihomo/logs.d.ts +2 -2
- package/dist/mihomo/logs.js +8 -0
- package/{lib → dist}/mihomo/memory.d.ts +2 -2
- package/dist/mihomo/memory.js +3 -0
- package/{lib → dist}/mihomo/proxies.d.ts +2 -2
- package/dist/mihomo/proxies.js +17 -0
- package/{lib → dist}/mihomo/proxy-providers.d.ts +2 -2
- package/dist/mihomo/proxy-providers.js +15 -0
- package/{lib → dist}/mihomo/rule-providers.d.ts +2 -2
- package/dist/mihomo/rule-providers.js +7 -0
- package/{lib → dist}/mihomo/rules.d.ts +2 -2
- package/dist/mihomo/rules.js +6 -0
- package/{lib → dist}/mihomo/storage.d.ts +2 -2
- package/dist/mihomo/storage.js +9 -0
- package/{lib → dist}/mihomo/traffic.d.ts +2 -2
- package/dist/mihomo/traffic.js +3 -0
- package/{lib → dist}/mihomo/types.d.ts +5 -4
- package/dist/mihomo/types.js +1 -0
- package/{lib → dist}/mihomo/upgrade.d.ts +2 -2
- package/dist/mihomo/upgrade.js +11 -0
- package/{lib → dist}/mihomo/version.d.ts +2 -2
- package/dist/mihomo/version.js +3 -0
- package/{lib → dist}/num.d.ts +2 -0
- package/dist/num.js +19 -0
- package/dist/pino.js +13 -0
- package/dist/public-ip.js +19 -0
- package/dist/sleep.d.ts +3 -0
- package/dist/sleep.js +21 -0
- package/{lib → dist}/url.d.ts +1 -1
- package/dist/url.js +29 -0
- package/{lib → dist}/uuid.d.ts +1 -0
- package/dist/uuid.js +16 -0
- package/package.json +33 -48
- package/lib/date-time.js +0 -1
- package/lib/download/aria2.js +0 -1
- package/lib/download/extension.js +0 -1
- package/lib/download/index.js +0 -1
- package/lib/env.d.ts +0 -9
- package/lib/env.js +0 -1
- package/lib/fetch.d.ts +0 -13
- package/lib/fetch.js +0 -1
- package/lib/file.js +0 -1
- package/lib/index.d.ts +0 -12
- package/lib/index.js +0 -1
- package/lib/mihomo/cache.js +0 -1
- package/lib/mihomo/client.d.ts +0 -25
- package/lib/mihomo/client.js +0 -1
- package/lib/mihomo/configs.js +0 -1
- package/lib/mihomo/connections.js +0 -1
- package/lib/mihomo/debug.js +0 -1
- package/lib/mihomo/dns.js +0 -1
- package/lib/mihomo/groups.js +0 -1
- package/lib/mihomo/index.d.ts +0 -39
- package/lib/mihomo/index.js +0 -1
- package/lib/mihomo/logs.js +0 -1
- package/lib/mihomo/memory.js +0 -1
- package/lib/mihomo/proxies.js +0 -1
- package/lib/mihomo/proxy-providers.js +0 -1
- package/lib/mihomo/rule-providers.js +0 -1
- package/lib/mihomo/rules.js +0 -1
- package/lib/mihomo/storage.js +0 -1
- package/lib/mihomo/traffic.js +0 -1
- package/lib/mihomo/upgrade.js +0 -1
- package/lib/mihomo/version.js +0 -1
- package/lib/num.js +0 -1
- package/lib/pino.js +0 -1
- package/lib/public-ip.js +0 -1
- package/lib/sleep.d.ts +0 -2
- package/lib/sleep.js +0 -1
- package/lib/url.js +0 -1
- package/lib/uuid.js +0 -1
- /package/{lib → dist}/date-time.d.ts +0 -0
- /package/{lib → dist}/download/types.d.ts +0 -0
- /package/{lib → dist}/file.d.ts +0 -0
- /package/{lib → dist}/pino.d.ts +0 -0
- /package/{lib → dist}/public-ip.d.ts +0 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 secretmomo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,13 +1,222 @@
|
|
|
1
|
-
# utils
|
|
1
|
+
# @secret-momo/utils
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
常用工具函数、资源下载和 Mihomo HTTP API 客户端。仅提供 ESM 和 TypeScript 声明,运行环境要求 **Node.js >=26**。
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## 安装与使用
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
```sh
|
|
8
|
+
pnpm add @secret-momo/utils
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { dateToNow, fetchJson, toPercentage, uuidv4 } from '@secret-momo/utils';
|
|
13
|
+
|
|
14
|
+
console.log(dateToNow(), toPercentage(0.1234), uuidv4());
|
|
15
|
+
const data = await fetchJson('https://example.com/api');
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
所有公开 API 均可从 `@secret-momo/utils` 导入。只使用 HTTP 请求或日志工具时,可分别从 `@secret-momo/utils/fetch` 和 `@secret-momo/utils/pino` 导入。
|
|
19
|
+
|
|
20
|
+
## 工具函数
|
|
21
|
+
|
|
22
|
+
数字函数沿用原生 `toFixed` 的二进制浮点舍入行为,不保证十进制中点精确四舍五入;例如 `fixed2(1.005) === 1`、`fixed2(2.675) === 2.67`。
|
|
23
|
+
|
|
24
|
+
`genId(len)` 的长度必须是 0–65536 的整数。`findRepoRoot(from)` 接受相对或绝对目录。`getNodeName()` 首次调用会同步启动 macOS 硬件探测,期间会阻塞事件循环,后续调用复用结果(含探测失败)。`removeQueryParams()` 支持相对地址并保留 fragment。
|
|
25
|
+
|
|
26
|
+
| 分类 | API | 行为 |
|
|
27
|
+
| -------- | --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
|
|
28
|
+
| 日期 | `dateTimeToNow(fmt?)`、`dateToNow(fmt?)`、`yesterdayDate(fmt?)`、`timestampToDate(timestamp, fmt?)` | 使用 dayjs 按本地时区格式化;时间戳单位为毫秒。默认日期格式 `YYYY-MM-DD`,日期时间格式 `YYYY-MM-DD HH:mm:ss`。 |
|
|
29
|
+
| 数字 | `fixed2(n)`、`fixed4(n)`、`toPercentage(n?)` | 四舍五入并返回数字;百分比最多保留两位小数,缺省值显示 `-`,零显示 `0%`。 |
|
|
30
|
+
| 随机标识 | `genId(len?)`、`uuidv4()` | 字母数字随机字符串(默认 10 位),或基于 Web Crypto 的 UUID v4。 |
|
|
31
|
+
| 等待 | `sleep(ms, signal?)`、`sleep_random()` | 支持取消信号,取消时以 `signal.reason` 拒绝;随机等待 750–1249ms。 |
|
|
32
|
+
| 文件 | `fileSize(filePath)` | 返回 `Promise<string>`,按 B、KB、MB、GB、TB 格式化文件大小;读取失败时拒绝。 |
|
|
33
|
+
| 环境 | `findRepoRoot(from)`、`getNodeName()` | 向上寻找最近的 Git、pnpm、Bun 或 workspace 标记;通过 macOS `system_profiler` 读取机型和芯片,命令不可用时返回 `null(null)`。 |
|
|
34
|
+
| 网络 | `getPublicIp()`、`removeQueryParams(url)`、`getRedirectUrl(url)` | 查询 ipify 公网 IP;移除 query 和末尾一个 `/`;读取一跳重定向并解析相对 Location。 |
|
|
35
|
+
| 日志 | `pino`、`logger` | 导出 pino 工厂及默认 info 级别的 pino-pretty logger。包根入口加载时创建默认日志 transport。 |
|
|
36
|
+
|
|
37
|
+
## HTTP 请求
|
|
38
|
+
|
|
39
|
+
`fetch`、`fetchText`、`fetchHtml`、`fetchJson` 接受原生 `fetch` 的 `string | URL | Request` 和可选 `FetchRequestInit`(兼容 `RequestInit`,额外支持 `retry?: boolean`)。分别返回 `Response`、文本、HTML 文本和 `unknown` JSON 值。另导出 `userAgent` 与 `mobileUserAgent`。
|
|
40
|
+
|
|
41
|
+
- 补齐默认 Accept-Language、Referer 和 User-Agent;HTML、JSON 方法再补齐对应场景请求头。保留调用方显式设置的同名请求头。
|
|
42
|
+
- 默认仅自动重试 GET、HEAD、OPTIONS、PUT、DELETE、TRACE。POST、PATCH 等非幂等请求默认不重试;调用方确认服务端支持幂等键或其他去重机制后,可显式设置 `retry: true`。`retry: false` 可完全禁用重试。
|
|
43
|
+
- 最多重试 5 次,共尝试 6 次,退避为 1、2、4、8、16 秒。有错误码时,仅重试已知瞬时网络、连接、DNS 和超时错误。证书错误、HTTP 状态码、响应体读取和 JSON 解析失败不触发重试。
|
|
44
|
+
- 允许重试且使用 Request 自带的 body 时,每次尝试使用新克隆,上传体重放可能增加缓冲内存。禁用重试或通过 `init.body` 覆盖时,直接传递原 Request,遵循原生 fetch 的消费语义。放在 `init.body` 的一次性流始终跳过重试。
|
|
45
|
+
- `init.signal` 优先于 Request 自带的信号;取消信号也会中止退避等待。
|
|
46
|
+
- 重试日志仅记录 URL 的 origin/path、异常名和错误码,不记录 userinfo、query、fragment 或可能携带完整 URL 的原始错误消息。
|
|
47
|
+
|
|
48
|
+
`getPublicIp()` 直接请求 ipify,服务错误、非 IPv4/IPv6 响应或网络错误均向调用方抛出。`getRedirectUrl()` 只对 301、302、303、307、308 读取一跳 Location,返回前取消未使用的响应体。
|
|
49
|
+
|
|
50
|
+
## 下载
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { aria2DownloadVideo, downloadImage, downloadVideo } from '@secret-momo/utils';
|
|
54
|
+
|
|
55
|
+
const image = await downloadImage({
|
|
56
|
+
url: 'https://example.com/image.png',
|
|
57
|
+
dir: './downloads',
|
|
58
|
+
referer: 'https://example.com/',
|
|
59
|
+
});
|
|
60
|
+
if (image.isSuccess) console.log(image.filePath, image.fileSize);
|
|
61
|
+
else console.error(image.error);
|
|
62
|
+
|
|
63
|
+
const videoPath = await downloadVideo({ url: 'https://example.com/video.mp4', dir: './downloads' });
|
|
64
|
+
const video = await aria2DownloadVideo({ url: 'https://example.com/video.mp4', dir: './downloads' });
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
三个方法都接受 `{ url, dir, referer? }`,自动创建目录,以 UUID 命名文件,并按 URL、响应 Content-Type、默认扩展名的顺序决定文件类型。
|
|
68
|
+
|
|
69
|
+
| 方法 | 成功 | 失败 |
|
|
70
|
+
| -------------------- | ----------------------------------------- | -------------------------------------------------------------------------------- |
|
|
71
|
+
| `downloadVideo` | 文件路径字符串 | 记录错误,返回 `null` |
|
|
72
|
+
| `downloadImage` | `{ isSuccess: true, filePath, fileSize }` | `{ isSuccess: false, error }` |
|
|
73
|
+
| `aria2DownloadVideo` | `{ isSuccess: true, filePath, fileSize }` | 下载失败时返回 `{ isSuccess: false, error }`;未安装 aria2c 等安装检查错误会抛出 |
|
|
74
|
+
|
|
75
|
+
`aria2DownloadVideo` 仅接受合法的 HTTP(S) URL。无效地址或其他协议返回 `{ isSuccess: false, error }`,不会启动安装检查、HEAD 请求或下载命令。合法地址先规范化,只有 URL 无法推断视频扩展名时才发 HEAD。调用前需安装 `aria2c`(macOS 可执行 `brew install aria2`)。下载使用 `-x8 -s8 -k1M`,进度输出由子进程直接丢弃,失败日志只记录安全的错误码。失败时清理本次新产生的目标文件和 `.aria2` 控制文件,保留调用前已有的文件。原生下载方法在流写入失败时清理已经打开的部分文件。
|
|
76
|
+
|
|
77
|
+
## Mihomo API
|
|
78
|
+
|
|
79
|
+
这是 mihomo `external-controller` HTTP API 的 TypeScript 封装。它以接口模块组织调用,例如
|
|
80
|
+
`mihomo.proxies.select()`,并会自动处理路径编码、JSON 请求体及
|
|
81
|
+
`Authorization: Bearer <secret>` 认证。
|
|
82
|
+
|
|
83
|
+
接口含义以 [mihomo 官方 API 文档](https://wiki.metacubex.one/api/) 为准。
|
|
84
|
+
|
|
85
|
+
### 创建客户端
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import { createMihomo } from '@secret-momo/utils';
|
|
89
|
+
|
|
90
|
+
const mihomo = createMihomo({
|
|
91
|
+
// mihomo 配置中的 secret;未配置 secret 时可以省略
|
|
92
|
+
secret: 'controller-secret',
|
|
93
|
+
});
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
`baseUrl` 默认为 `http://127.0.0.1:9090`;如 mihomo 的 `external-controller`
|
|
97
|
+
使用其他地址,可显式传入,且可以带或不带末尾 `/`。调用方传入的
|
|
98
|
+
`headers.Authorization` 会覆盖 `secret` 自动生成的认证头;每个方法还可传入
|
|
99
|
+
`signal` 取消请求。
|
|
100
|
+
|
|
101
|
+
直接使用 `MihomoClient` 时,请求路径以 `/` 开头,并保留 `baseUrl` 中的路径前缀。点号导航段和反斜杠会被拒绝。
|
|
8
102
|
|
|
103
|
+
### 常见调用
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
// 版本与运行配置
|
|
107
|
+
const version = await mihomo.version.get();
|
|
108
|
+
const config = await mihomo.configs.get();
|
|
109
|
+
await mihomo.configs.patch({ mode: 'global', 'mixed-port': 7890 });
|
|
110
|
+
await mihomo.configs.reload(undefined, { force: true });
|
|
111
|
+
|
|
112
|
+
// 代理和策略组
|
|
113
|
+
const proxies = await mihomo.proxies.list();
|
|
114
|
+
await mihomo.proxies.select('Proxy', '日本');
|
|
115
|
+
const { delay } = await mihomo.proxies.delay('日本', {
|
|
116
|
+
url: 'https://www.gstatic.com/generate_204',
|
|
117
|
+
timeout: 5_000,
|
|
118
|
+
expected: '204',
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
// DNS、连接与存储
|
|
122
|
+
const dns = await mihomo.dns.query('example.com', 'A');
|
|
123
|
+
const connections = await mihomo.connections.list();
|
|
124
|
+
await mihomo.storage.set('panel-theme', { theme: 'dark' });
|
|
125
|
+
const theme = await mihomo.storage.get<{ theme: string }>('panel-theme');
|
|
9
126
|
```
|
|
10
|
-
|
|
11
|
-
|
|
127
|
+
|
|
128
|
+
### 实时 HTTP 流
|
|
129
|
+
|
|
130
|
+
`/logs`、`/traffic`、`/memory` 在官方文档中同时支持 HTTP 与 WebSocket。本封装的
|
|
131
|
+
`stream()` 方法发起 HTTP GET,并原样返回
|
|
132
|
+
`Response`,由调用方按服务端实际返回格式消费 `response.body`:
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
const response = await mihomo.logs.stream({
|
|
136
|
+
level: 'info',
|
|
137
|
+
structured: true,
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
const reader = response.body?.pipeThrough(new TextDecoderStream()).getReader();
|
|
141
|
+
if (reader) {
|
|
142
|
+
for (;;) {
|
|
143
|
+
const { value, done } = await reader.read();
|
|
144
|
+
if (done) break;
|
|
145
|
+
console.log(value);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
WebSocket 建连不在本封装范围内:浏览器原生 `WebSocket` 无法直接附带文档要求的
|
|
151
|
+
`Authorization` 请求头。如需 WS,请根据运行环境的认证能力自行建立连接。
|
|
152
|
+
|
|
153
|
+
### 模块与方法
|
|
154
|
+
|
|
155
|
+
| 模块 | 方法 | 对应接口与用途 |
|
|
156
|
+
| ---------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------ |
|
|
157
|
+
| `version` | `get()` | `GET /version`,获取版本号和 Meta 标识。 |
|
|
158
|
+
| `cache` | `flushFakeIp()`、`flushDns()` | 清除 fake-ip 或 DNS 缓存。 |
|
|
159
|
+
| `configs` | `get()`、`reload()`、`patch()`、`updateGeo()`、`restart()` | 读取、重载、更新运行配置,更新 GEO 数据库或重启内核。 |
|
|
160
|
+
| `upgrade` | `core()`、`ui()`、`geo()` | 更新内核、external-ui 面板或 GEO 数据库。 |
|
|
161
|
+
| `groups` | `list()`、`get()`、`delay()` | 读取策略组,或测试策略组内成员的延迟。 |
|
|
162
|
+
| `proxies` | `list()`、`get()`、`select()`、`clearFixed()`、`delay()` | 查询代理/策略组、选择节点、清除 fixed 选择或测试延迟。 |
|
|
163
|
+
| `proxyProviders` | `list()`、`get()`、`update()`、`healthcheck()`、`getProxy()`、`healthcheckProxy()` | 管理代理集合并检查集合或集合内节点的健康状态。 |
|
|
164
|
+
| `rules` | `list()`、`setDisabled()` | 查询规则,或按索引临时禁用/启用规则。 |
|
|
165
|
+
| `ruleProviders` | `list()`、`update()` | 查询或更新规则集合。 |
|
|
166
|
+
| `connections` | `list()`、`closeAll()`、`close()` | 查询当前连接,关闭全部或指定连接。 |
|
|
167
|
+
| `dns` | `query()` | 对域名及记录类型执行 DNS 查询。 |
|
|
168
|
+
| `storage` | `get()`、`set()`、`delete()` | 读写或删除指定 key 的 JSON 存储值。 |
|
|
169
|
+
| `logs` | `stream()` | 读取实时日志 HTTP 流,可按级别过滤或选择结构化格式。 |
|
|
170
|
+
| `traffic` | `stream()` | 读取实时上/下行流量 HTTP 流。 |
|
|
171
|
+
| `memory` | `stream()` | 读取实时内存占用 HTTP 流。 |
|
|
172
|
+
| `debug` | `gc()`、`pprofUrl()` | 主动 GC,或取得 pprof 调试页面 URL。 |
|
|
173
|
+
|
|
174
|
+
每个模块方法的 IDE 悬停注释都附有对应的 HTTP 方法、路径、行为和重要参数。
|
|
175
|
+
|
|
176
|
+
`connections.list()` 返回单次 HTTP 快照;`interval` 仅为兼容保留并转发,不会开启 WebSocket 或自动刷新。名称、存储 key 等路径参数不能是独立的 `.` 或 `..`,这些值会抛出 `TypeError`,避免 URL 规范化后请求其他路由。
|
|
177
|
+
|
|
178
|
+
`debug.pprofUrl()` 只生成 URL,不会携带 Authorization 头。直接浏览器访问需满足 controller 的认证要求;启用 secret 时,可创建配置了 secret 的 `MihomoClient` 实例,再调用 `client.response('GET', '/debug/pprof')` 携带认证信息获取响应。
|
|
179
|
+
|
|
180
|
+
### 错误处理
|
|
181
|
+
|
|
182
|
+
任何非 2xx 响应都会抛出 `MihomoHttpError`。错误对象包含原始 `response`
|
|
183
|
+
和已读取的文本 `body`,方便展示 mihomo 的错误信息。读取响应体失败时,`body` 为空字符串,`cause` 保留读取异常:
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
import { MihomoHttpError } from '@secret-momo/utils';
|
|
187
|
+
|
|
188
|
+
try {
|
|
189
|
+
await mihomo.proxies.get('不存在的节点');
|
|
190
|
+
} catch (error) {
|
|
191
|
+
if (error instanceof MihomoHttpError) {
|
|
192
|
+
console.error(error.response.status, error.body);
|
|
193
|
+
}
|
|
12
194
|
}
|
|
13
195
|
```
|
|
196
|
+
|
|
197
|
+
### 类型
|
|
198
|
+
|
|
199
|
+
公共返回类型和选项(如
|
|
200
|
+
`MihomoProxy`、`MihomoConnection`、`MihomoDnsResponse`、`MihomoDelayOptions`)均从包根目录导出:
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
import type { MihomoProxy, MihomoRequestOptions } from '@secret-momo/utils';
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
## 开发与验证
|
|
207
|
+
|
|
208
|
+
在仓库根目录使用统一的 Node.js / pnpm 开发环境,版本和安装步骤见[仓库说明](../../README.md)。
|
|
209
|
+
|
|
210
|
+
```sh
|
|
211
|
+
pnpm --filter @secret-momo/utils typecheck
|
|
212
|
+
pnpm --filter @secret-momo/utils test
|
|
213
|
+
pnpm --filter @secret-momo/utils build
|
|
214
|
+
pnpm --filter @secret-momo/utils test:runtime
|
|
215
|
+
pnpm check
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
Vitest V8 覆盖率统计全部 `src/**/*.ts` 业务源码,包括未被测试导入的文件,仅排除测试和 `.d.ts`。纯类型文件没有可执行语句。全包的语句、分支、函数、行四项均须达到 90%,不足会使测试失败。报告输出到 `coverage/`,包括终端摘要、`index.html`、`lcov.info` 和 `coverage-summary.json`。配置方式见 [Vitest 覆盖率文档](https://vitest.dev/config/coverage)。
|
|
219
|
+
|
|
220
|
+
业务测试通过替身和临时文件覆盖网络、macOS 命令和 aria2,无需真实外网服务或安装 aria2c。`test:runtime` 直接使用构建产物,通过本地 HTTP 服务验证 fetch、Request、流下载、Mihomo 和真实日志 transport。开发、安装、构建和 CI 检查统一使用根目录 `.node-version` 指定的 Node.js 26 版本。
|
|
221
|
+
|
|
222
|
+
当前 `1.9.0` 是与源仓库和 npm latest 对齐的迁移基线(2026-11-22 核实),尚未添加发版 changeset。发布约定、OIDC 和飞书通知配置统一见[仓库说明](../../README.md)。
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import dayjs from 'dayjs';
|
|
2
|
+
export function dateTimeToNow(fmt = 'YYYY-MM-DD HH:mm:ss') {
|
|
3
|
+
return dayjs().format(fmt);
|
|
4
|
+
}
|
|
5
|
+
export function dateToNow(fmt = 'YYYY-MM-DD') {
|
|
6
|
+
return dayjs().format(fmt);
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* 获取昨天日期
|
|
10
|
+
* @param fmt 日期格式
|
|
11
|
+
* @returns 昨天日期(YYYY-MM-DD)
|
|
12
|
+
*/
|
|
13
|
+
export function yesterdayDate(fmt = 'YYYY-MM-DD') {
|
|
14
|
+
return dayjs().subtract(1, 'day').format(fmt);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* 将时间戳转换为日期
|
|
18
|
+
* @param timestamp 时间戳(毫秒)
|
|
19
|
+
* @returns 日期(YYYY-MM-DD)
|
|
20
|
+
*/
|
|
21
|
+
export function timestampToDate(timestamp, fmt = 'YYYY-MM-DD') {
|
|
22
|
+
return dayjs(timestamp).format(fmt);
|
|
23
|
+
}
|
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import type { DownloadOptions, DownloadResult } from './types';
|
|
1
|
+
import type { DownloadOptions, DownloadResult } from './types.js';
|
|
2
2
|
/**
|
|
3
3
|
* 使用 aria2c 下载视频资源到指定目录。
|
|
4
4
|
*
|
|
5
|
+
* 仅接受合法的 HTTP(S) URL,无效地址返回错误结果且不启动外部命令。
|
|
5
6
|
* 下载前会检查本机是否安装 `aria2c`;若不存在会抛出异常,并提示通过
|
|
6
7
|
* `brew install aria2` 安装。下载时使用 `aria2c -x8 -s8 -k1M` 参数;如提供
|
|
7
|
-
* referer
|
|
8
|
+
* referer,则将其用于下载和需要时的 HEAD 探测。仅在 URL 无法推断扩展名时通过 HEAD 查询 `Content-Type`。
|
|
8
9
|
*
|
|
9
10
|
* @param options 下载配置
|
|
10
|
-
* @param options.url 视频资源 URL
|
|
11
|
+
* @param options.url 合法的 HTTP(S) 视频资源 URL
|
|
11
12
|
* @param options.dir 资源保存目录,不存在时会自动创建
|
|
12
13
|
* @param options.referer 可选的请求 Referer
|
|
13
|
-
* @returns
|
|
14
|
+
* @returns 下载成功时返回文件信息,下载过程失败时返回错误结果;缺少 aria2c 时抛出异常
|
|
14
15
|
*/
|
|
15
16
|
export declare function aria2DownloadVideo({ url, dir, referer, }: DownloadOptions): Promise<DownloadResult>;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { once } from 'node:events';
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import { mkdir, rm } from 'node:fs/promises';
|
|
5
|
+
import { basename, join } from 'node:path';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import { uuidv4 } from '../uuid.js';
|
|
8
|
+
import { fetch } from '../fetch.js';
|
|
9
|
+
import { logger } from '../pino.js';
|
|
10
|
+
import { pickVideoExtension, videoExtensionFromUrl } from './extension.js';
|
|
11
|
+
import { fileSize } from '../file.js';
|
|
12
|
+
const execFileAsync = promisify(execFile);
|
|
13
|
+
const aria2DownloadLogger = logger.child({ name: 'aria2DownloadVideo' });
|
|
14
|
+
/**
|
|
15
|
+
* 清理本次下载新产生的文件。
|
|
16
|
+
*
|
|
17
|
+
* aria2 下载失败时可能同时留下未完成的目标文件和用于断点续传的 `.aria2`
|
|
18
|
+
* 控制文件。下载开始前已经存在的同名文件不会被删除,避免误删调用方原有文件。
|
|
19
|
+
*/
|
|
20
|
+
async function cleanupDownloadArtifacts(filePath, preExistingArtifactPaths) {
|
|
21
|
+
// aria2 可能产生的两个中间产物:下载内容本身,以及断点续传控制文件。
|
|
22
|
+
const possibleArtifactPaths = [filePath, `${filePath}.aria2`];
|
|
23
|
+
// 仅清理本次调用新建的路径;下载前就存在的同名文件必须保留。
|
|
24
|
+
const newArtifactPaths = possibleArtifactPaths.filter((artifactPath) => !preExistingArtifactPaths.has(artifactPath));
|
|
25
|
+
const results = await Promise.allSettled(newArtifactPaths.map((artifactPath) => rm(artifactPath, { force: true })));
|
|
26
|
+
const errors = results.flatMap((result) => (result.status === 'rejected' ? [result.reason] : []));
|
|
27
|
+
// 清理错误单独记录,不让它覆盖真正导致下载失败的原始错误。
|
|
28
|
+
if (errors.length > 0) {
|
|
29
|
+
aria2DownloadLogger.error(new AggregateError(errors, '清理 aria2 下载中间产物失败'));
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
async function assertAria2cInstalled() {
|
|
33
|
+
try {
|
|
34
|
+
await execFileAsync('aria2c', ['--version']);
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
const err = error;
|
|
38
|
+
if (err.code === 'ENOENT') {
|
|
39
|
+
throw new Error('未找到 aria2c 命令行工具,请先使用 brew install aria2 安装。', {
|
|
40
|
+
cause: error,
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
async function runDownload(args) {
|
|
47
|
+
// 下载可能持续很久。丢弃进度输出,避免子进程因输出缓冲达到上限而终止。
|
|
48
|
+
const child = spawn('aria2c', args, { stdio: 'ignore' });
|
|
49
|
+
const [code, signal] = (await once(child, 'close'));
|
|
50
|
+
if (code !== 0) {
|
|
51
|
+
throw Object.assign(new Error(`aria2c 下载失败(${signal ?? code})`), { code, signal });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async function fetchVideoContentType(url, referer) {
|
|
55
|
+
try {
|
|
56
|
+
const res = await fetch(url, {
|
|
57
|
+
method: 'HEAD',
|
|
58
|
+
...(referer ? { headers: { Referer: referer } } : {}),
|
|
59
|
+
});
|
|
60
|
+
return res.headers.get('content-type');
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* 使用 aria2c 下载视频资源到指定目录。
|
|
68
|
+
*
|
|
69
|
+
* 仅接受合法的 HTTP(S) URL,无效地址返回错误结果且不启动外部命令。
|
|
70
|
+
* 下载前会检查本机是否安装 `aria2c`;若不存在会抛出异常,并提示通过
|
|
71
|
+
* `brew install aria2` 安装。下载时使用 `aria2c -x8 -s8 -k1M` 参数;如提供
|
|
72
|
+
* referer,则将其用于下载和需要时的 HEAD 探测。仅在 URL 无法推断扩展名时通过 HEAD 查询 `Content-Type`。
|
|
73
|
+
*
|
|
74
|
+
* @param options 下载配置
|
|
75
|
+
* @param options.url 合法的 HTTP(S) 视频资源 URL
|
|
76
|
+
* @param options.dir 资源保存目录,不存在时会自动创建
|
|
77
|
+
* @param options.referer 可选的请求 Referer
|
|
78
|
+
* @returns 下载成功时返回文件信息,下载过程失败时返回错误结果;缺少 aria2c 时抛出异常
|
|
79
|
+
*/
|
|
80
|
+
export async function aria2DownloadVideo({ url, dir, referer, }) {
|
|
81
|
+
try {
|
|
82
|
+
const parsed = new URL(url);
|
|
83
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
84
|
+
throw new TypeError('视频地址必须是合法的 HTTP(S) URL');
|
|
85
|
+
}
|
|
86
|
+
url = parsed.href;
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
return { isSuccess: false, error: error };
|
|
90
|
+
}
|
|
91
|
+
await assertAria2cInstalled();
|
|
92
|
+
let filePath;
|
|
93
|
+
const preExistingArtifactPaths = new Set();
|
|
94
|
+
try {
|
|
95
|
+
await mkdir(dir, { recursive: true });
|
|
96
|
+
const ext = videoExtensionFromUrl(url) ??
|
|
97
|
+
pickVideoExtension(url, await fetchVideoContentType(url, referer));
|
|
98
|
+
filePath = join(dir, `${uuidv4()}.${ext}`);
|
|
99
|
+
// 在启动 aria2c 前记录既有文件,后续失败清理时据此避免误删。
|
|
100
|
+
for (const artifactPath of [filePath, `${filePath}.aria2`]) {
|
|
101
|
+
if (existsSync(artifactPath)) {
|
|
102
|
+
preExistingArtifactPaths.add(artifactPath);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const args = [
|
|
106
|
+
'-x8',
|
|
107
|
+
'-s8',
|
|
108
|
+
'-k1M',
|
|
109
|
+
// 禁止 aria2 自动生成 `.1` 等新文件名,确保失败产物路径可预测、可清理。
|
|
110
|
+
'--auto-file-renaming=false',
|
|
111
|
+
...(referer ? ['--referer', referer] : []),
|
|
112
|
+
'-d',
|
|
113
|
+
dir,
|
|
114
|
+
'-o',
|
|
115
|
+
basename(filePath),
|
|
116
|
+
url,
|
|
117
|
+
];
|
|
118
|
+
await runDownload(args);
|
|
119
|
+
return { isSuccess: true, filePath, fileSize: await fileSize(filePath) };
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
// aria2c 执行或后续文件信息读取失败时,清理本次调用新产生的下载产物。
|
|
123
|
+
if (filePath) {
|
|
124
|
+
await cleanupDownloadArtifacts(filePath, preExistingArtifactPaths);
|
|
125
|
+
}
|
|
126
|
+
// 命令行和错误输出可能包含下载地址、查询参数或 Referer 中的凭据。
|
|
127
|
+
const code = error?.code;
|
|
128
|
+
const safeCode = typeof code === 'number' || (typeof code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(code))
|
|
129
|
+
? code
|
|
130
|
+
: undefined;
|
|
131
|
+
aria2DownloadLogger.error({ code: safeCode }, 'aria2c 下载失败');
|
|
132
|
+
return { isSuccess: false, error: error };
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
const VIDEO_CONTENT_TYPE_TO_EXT = {
|
|
2
|
+
'video/mp4': 'mp4',
|
|
3
|
+
'video/webm': 'webm',
|
|
4
|
+
'video/quicktime': 'mov',
|
|
5
|
+
'video/x-m4v': 'm4v',
|
|
6
|
+
'video/x-matroska': 'mkv',
|
|
7
|
+
'video/x-msvideo': 'avi',
|
|
8
|
+
'video/ogg': 'ogv',
|
|
9
|
+
};
|
|
10
|
+
const IMAGE_CONTENT_TYPE_TO_EXT = {
|
|
11
|
+
'image/jpeg': 'jpg',
|
|
12
|
+
'image/jpg': 'jpg',
|
|
13
|
+
'image/png': 'png',
|
|
14
|
+
'image/gif': 'gif',
|
|
15
|
+
'image/webp': 'webp',
|
|
16
|
+
'image/svg+xml': 'svg',
|
|
17
|
+
'image/bmp': 'bmp',
|
|
18
|
+
'image/x-ms-bmp': 'bmp',
|
|
19
|
+
'image/avif': 'avif',
|
|
20
|
+
'image/x-icon': 'ico',
|
|
21
|
+
};
|
|
22
|
+
const VIDEO_EXTENSIONS = new Set(Object.values(VIDEO_CONTENT_TYPE_TO_EXT));
|
|
23
|
+
const IMAGE_EXTENSIONS = new Set([...Object.values(IMAGE_CONTENT_TYPE_TO_EXT), 'jpeg']);
|
|
24
|
+
/**
|
|
25
|
+
* 从 URL 的 pathname 末段提取扩展名。
|
|
26
|
+
* 仅在扩展名属于 `allowed` 白名单时返回;URL 非法或无匹配时返回 `null`。
|
|
27
|
+
*
|
|
28
|
+
* @param urlString 资源 URL
|
|
29
|
+
* @param allowed 允许的扩展名白名单
|
|
30
|
+
* @returns 小写扩展名,或 `null`
|
|
31
|
+
*/
|
|
32
|
+
function extensionFromUrlPath(urlString, allowed) {
|
|
33
|
+
try {
|
|
34
|
+
const { pathname } = new URL(urlString);
|
|
35
|
+
const base = pathname.split('/').pop() ?? '';
|
|
36
|
+
const m = /\.([a-zA-Z0-9]+)$/.exec(base);
|
|
37
|
+
if (!m?.[1]) {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
const ext = m[1].toLowerCase();
|
|
41
|
+
return allowed.has(ext) ? ext : null;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* 根据 `Content-Type` 响应头推断扩展名。
|
|
49
|
+
* 会忽略 `;` 后的 charset 等参数;无匹配时返回 `null`。
|
|
50
|
+
*
|
|
51
|
+
* @param header `Content-Type` 响应头
|
|
52
|
+
* @param map MIME 类型到扩展名的映射表
|
|
53
|
+
* @returns 扩展名,或 `null`
|
|
54
|
+
*/
|
|
55
|
+
function extensionFromContentType(header, map) {
|
|
56
|
+
if (!header) {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
const type = header.split(';')[0]?.trim().toLowerCase() ?? '';
|
|
60
|
+
return Object.hasOwn(map, type) ? (map[type] ?? null) : null;
|
|
61
|
+
}
|
|
62
|
+
export function videoExtensionFromUrl(url) {
|
|
63
|
+
return extensionFromUrlPath(url, VIDEO_EXTENSIONS);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* 推断视频文件的扩展名,按以下优先级:
|
|
67
|
+
* 1. URL 路径中的视频扩展名
|
|
68
|
+
* 2. `Content-Type` 映射
|
|
69
|
+
* 3. 兜底 `'mp4'`
|
|
70
|
+
* @param url 资源 URL
|
|
71
|
+
* @param contentType `Content-Type` 响应头,可为 `null`
|
|
72
|
+
* @returns 视频扩展名(不含点号)
|
|
73
|
+
*/
|
|
74
|
+
export function pickVideoExtension(url, contentType) {
|
|
75
|
+
return (videoExtensionFromUrl(url) ??
|
|
76
|
+
extensionFromContentType(contentType, VIDEO_CONTENT_TYPE_TO_EXT) ??
|
|
77
|
+
'mp4');
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* 推断图片文件的扩展名,按以下优先级:
|
|
81
|
+
* 1. URL 路径中的图片扩展名(`jpeg` 统一为 `jpg`)
|
|
82
|
+
* 2. `Content-Type` 映射
|
|
83
|
+
* 3. 兜底 `'jpg'`
|
|
84
|
+
*
|
|
85
|
+
* @param url 资源 URL
|
|
86
|
+
* @param contentType `Content-Type` 响应头,可为 `null`
|
|
87
|
+
* @returns 图片扩展名(不含点号)
|
|
88
|
+
*/
|
|
89
|
+
export function pickImageExtension(url, contentType) {
|
|
90
|
+
const fromUrl = extensionFromUrlPath(url, IMAGE_EXTENSIONS);
|
|
91
|
+
if (fromUrl === 'jpeg') {
|
|
92
|
+
return 'jpg';
|
|
93
|
+
}
|
|
94
|
+
const fromCt = extensionFromContentType(contentType, IMAGE_CONTENT_TYPE_TO_EXT);
|
|
95
|
+
return fromUrl ?? fromCt ?? 'jpg';
|
|
96
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { aria2DownloadVideo } from './aria2';
|
|
2
|
-
import type { DownloadOptions, DownloadResult } from './types';
|
|
1
|
+
import { aria2DownloadVideo } from './aria2.js';
|
|
2
|
+
import type { DownloadOptions, DownloadResult } from './types.js';
|
|
3
3
|
export { aria2DownloadVideo };
|
|
4
4
|
/**
|
|
5
5
|
* 下载视频资源到指定目录。
|
|
@@ -12,16 +12,16 @@ export { aria2DownloadVideo };
|
|
|
12
12
|
* @param options.dir 资源保存目录,不存在时会自动创建
|
|
13
13
|
* @returns 下载成功后的文件路径,失败时返回 `null`
|
|
14
14
|
*/
|
|
15
|
-
export declare function downloadVideo({ url, dir }: DownloadOptions): Promise<string | null>;
|
|
15
|
+
export declare function downloadVideo({ url, dir, referer, }: DownloadOptions): Promise<string | null>;
|
|
16
16
|
/**
|
|
17
17
|
* 下载图片资源到指定目录。
|
|
18
18
|
*
|
|
19
19
|
* 会根据 URL 或响应 `Content-Type` 推断图片扩展名,并用 UUID 生成文件名。
|
|
20
|
-
*
|
|
20
|
+
* 下载成功时返回文件信息;下载失败时记录日志并返回错误结果。
|
|
21
21
|
*
|
|
22
22
|
* @param options 下载配置
|
|
23
23
|
* @param options.url 图片资源 URL
|
|
24
24
|
* @param options.dir 资源保存目录,不存在时会自动创建
|
|
25
|
-
* @returns
|
|
25
|
+
* @returns 下载成功时返回文件信息,失败时返回错误结果
|
|
26
26
|
*/
|
|
27
|
-
export declare function downloadImage({ url, dir }: DownloadOptions): Promise<DownloadResult>;
|
|
27
|
+
export declare function downloadImage({ url, dir, referer, }: DownloadOptions): Promise<DownloadResult>;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { createWriteStream } from 'node:fs';
|
|
2
|
+
import { mkdir, rm } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { Readable } from 'node:stream';
|
|
5
|
+
import { pipeline } from 'node:stream/promises';
|
|
6
|
+
import { fetch } from '../fetch.js';
|
|
7
|
+
import { uuidv4 } from '../uuid.js';
|
|
8
|
+
import { pickVideoExtension, pickImageExtension } from './extension.js';
|
|
9
|
+
import { logger } from '../pino.js';
|
|
10
|
+
import { aria2DownloadVideo } from './aria2.js';
|
|
11
|
+
import { fileSize } from '../file.js';
|
|
12
|
+
export { aria2DownloadVideo };
|
|
13
|
+
async function removePartialFile(filePath, name) {
|
|
14
|
+
if (!filePath)
|
|
15
|
+
return;
|
|
16
|
+
try {
|
|
17
|
+
await rm(filePath, { force: true });
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
logger.child({ name, filePath }).error(error, 'Failed to remove partial download');
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* 下载视频资源到指定目录。
|
|
25
|
+
*
|
|
26
|
+
* 会根据 URL 或响应 `Content-Type` 推断视频扩展名,并用 UUID 生成文件名。
|
|
27
|
+
* 下载成功时返回保存后的文件路径;下载失败时记录日志并返回 `null`。
|
|
28
|
+
*
|
|
29
|
+
* @param options 下载配置
|
|
30
|
+
* @param options.url 视频资源 URL
|
|
31
|
+
* @param options.dir 资源保存目录,不存在时会自动创建
|
|
32
|
+
* @returns 下载成功后的文件路径,失败时返回 `null`
|
|
33
|
+
*/
|
|
34
|
+
export async function downloadVideo({ url, dir, referer, }) {
|
|
35
|
+
let partialFilePath;
|
|
36
|
+
try {
|
|
37
|
+
await mkdir(dir, { recursive: true });
|
|
38
|
+
const res = await fetch(url, referer === undefined ? undefined : { headers: { Referer: referer } });
|
|
39
|
+
if (!res.ok) {
|
|
40
|
+
await res.body?.cancel().catch(() => { });
|
|
41
|
+
throw new Error(`Download failed: HTTP ${res.status}`);
|
|
42
|
+
}
|
|
43
|
+
if (!res.body) {
|
|
44
|
+
throw new Error('Response has no body');
|
|
45
|
+
}
|
|
46
|
+
const ext = pickVideoExtension(url, res.headers.get('content-type'));
|
|
47
|
+
const outputPath = join(dir, `${uuidv4()}.${ext}`);
|
|
48
|
+
await pipeline(Readable.fromWeb(res.body), createWriteStream(outputPath).once('open', () => {
|
|
49
|
+
// 仅清理由本次下载实际打开写入的文件。
|
|
50
|
+
partialFilePath = outputPath;
|
|
51
|
+
}));
|
|
52
|
+
return outputPath;
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
logger.child({ name: 'downloadVideo' }).error(error);
|
|
56
|
+
await removePartialFile(partialFilePath, 'downloadVideo');
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* 下载图片资源到指定目录。
|
|
62
|
+
*
|
|
63
|
+
* 会根据 URL 或响应 `Content-Type` 推断图片扩展名,并用 UUID 生成文件名。
|
|
64
|
+
* 下载成功时返回文件信息;下载失败时记录日志并返回错误结果。
|
|
65
|
+
*
|
|
66
|
+
* @param options 下载配置
|
|
67
|
+
* @param options.url 图片资源 URL
|
|
68
|
+
* @param options.dir 资源保存目录,不存在时会自动创建
|
|
69
|
+
* @returns 下载成功时返回文件信息,失败时返回错误结果
|
|
70
|
+
*/
|
|
71
|
+
export async function downloadImage({ url, dir, referer, }) {
|
|
72
|
+
let partialFilePath;
|
|
73
|
+
try {
|
|
74
|
+
await mkdir(dir, { recursive: true });
|
|
75
|
+
const res = await fetch(url, referer === undefined ? undefined : { headers: { Referer: referer } });
|
|
76
|
+
if (!res.ok) {
|
|
77
|
+
await res.body?.cancel().catch(() => { });
|
|
78
|
+
throw new Error(`Download failed: HTTP ${res.status}`);
|
|
79
|
+
}
|
|
80
|
+
if (!res.body)
|
|
81
|
+
throw new Error('Response has no body');
|
|
82
|
+
const ext = pickImageExtension(url, res.headers.get('content-type'));
|
|
83
|
+
const filePath = join(dir, `${uuidv4()}.${ext}`);
|
|
84
|
+
await pipeline(Readable.fromWeb(res.body), createWriteStream(filePath).once('open', () => {
|
|
85
|
+
partialFilePath = filePath;
|
|
86
|
+
}));
|
|
87
|
+
return { isSuccess: true, filePath, fileSize: await fileSize(filePath) };
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
logger.child({ name: 'downloadImage' }).error(error);
|
|
91
|
+
await removePartialFile(partialFilePath, 'downloadImage');
|
|
92
|
+
return { isSuccess: false, error: error };
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|