@napuketto/adapter 0.19.0 → 0.21.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/gray-tip-D0SfHr7q.mjs +917 -0
- package/dist/{index-PWs-cVWe.d.mts → index-Cwq1NPKE.d.mts} +14 -2
- package/dist/{index-D93z0TYf.d.mts → index-DAoLsewN.d.mts} +20 -2
- package/dist/{index-C-pAiIuG.d.mts → index-DsGLfZOl.d.mts} +14 -2
- package/dist/index.d.mts +13 -4
- package/dist/index.mjs +3 -3
- package/dist/{media-cache-C_0C9eCV.d.mts → media-cache-BaTQ_l_b.d.mts} +18 -1
- package/dist/milky/index.d.mts +1 -1
- package/dist/milky/index.mjs +1 -1
- package/dist/{milky-DTlPFEhN.mjs → milky-v3TqHlCp.mjs} +31 -41
- package/dist/onebot11/index.d.mts +1 -1
- package/dist/onebot11/index.mjs +1 -1
- package/dist/{onebot11-Bq0f2Tky.mjs → onebot11-CZUzbgSG.mjs} +66 -84
- package/dist/satori/index.d.mts +1 -1
- package/dist/satori/index.mjs +1 -1
- package/dist/{satori-VkOP24Vc.mjs → satori-Cna8fauQ.mjs} +63 -46
- package/package.json +2 -2
- package/dist/gray-tip-BL1rhwZK.mjs +0 -617
|
@@ -0,0 +1,917 @@
|
|
|
1
|
+
import { errorMessage, kernelError } from "@napuketto/kernel";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { constants, createWriteStream } from "node:fs";
|
|
5
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
|
+
import { copyFile, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, unlink, writeFile } from "node:fs/promises";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { basename, dirname, extname, isAbsolute, join, resolve, sep } from "node:path";
|
|
9
|
+
import { downloadPublicUrl, downloadUrl, encodePcmToSilk, extractVideoFrame, getVideoInfo } from "@napuketto/media";
|
|
10
|
+
import { pipeline } from "node:stream/promises";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
// src/internal/infra/media-cache.ts
|
|
13
|
+
const CACHE_DIR = ".napuketto-media-v1";
|
|
14
|
+
const ENTRY_RE = /^entry-(\d+)-[\da-f-]{36}$/;
|
|
15
|
+
const EXTENSION_RE$1 = /^\.[a-zA-Z0-9]+$/;
|
|
16
|
+
const OWNED_FILE_RE = /^(?:media\.[a-zA-Z0-9]+(?:\.part-\d+-[\da-f-]{36})?|\.napuketto-[\da-f]{16}\.pcm|\.owner-next-[\da-f-]{36}\.json|\.lease-\d+-[\da-f-]{36})$/;
|
|
17
|
+
const PATH_SEPARATOR_RE$1 = /[\\/]/;
|
|
18
|
+
const STAGED_NAME_INVALID_RE = /[\\/:]/;
|
|
19
|
+
const CACHE_COMPONENT_RE = /^\.napuketto-media-v[12](?:-[\da-f]+)?$/i;
|
|
20
|
+
const CACHE_FILE_RE = /^media\.[a-zA-Z0-9]+$/;
|
|
21
|
+
const COLLECT_RE = /^\.collect-(\d+)-[\da-f-]{36}$/;
|
|
22
|
+
const STAGED_DIR = "input";
|
|
23
|
+
const LEASE_RE = /^\.lease-(\d+)-[\da-f-]{36}$/;
|
|
24
|
+
const VIDEO_DIR_RE = /^\.napuketto-video-[a-zA-Z0-9]{6}$/;
|
|
25
|
+
const DAY = 864e5;
|
|
26
|
+
const META = ".owner.json";
|
|
27
|
+
const uid = process.getuid?.();
|
|
28
|
+
const MEDIA_TEMP_ROOT = join(tmpdir(), uid === void 0 ? "napuketto-adapter-media" : `napuketto-adapter-media-${uid}`);
|
|
29
|
+
const cacheOwnerSchema = z.object({
|
|
30
|
+
version: z.literal(1),
|
|
31
|
+
lifetime: z.enum(["temporary", "reference"]),
|
|
32
|
+
expires: z.number(),
|
|
33
|
+
file: z.string().regex(CACHE_FILE_RE).optional(),
|
|
34
|
+
inputName: z.string().refine(isStagedName).optional()
|
|
35
|
+
});
|
|
36
|
+
const locks = /* @__PURE__ */ new Map();
|
|
37
|
+
const active = /* @__PURE__ */ new Map();
|
|
38
|
+
const scopes = new AsyncLocalStorage();
|
|
39
|
+
async function locked(root, task) {
|
|
40
|
+
const prior = locks.get(root) ?? Promise.resolve();
|
|
41
|
+
let release = () => void 0;
|
|
42
|
+
const next = new Promise((done) => {
|
|
43
|
+
release = done;
|
|
44
|
+
});
|
|
45
|
+
locks.set(root, next);
|
|
46
|
+
await prior;
|
|
47
|
+
try {
|
|
48
|
+
return await task();
|
|
49
|
+
} finally {
|
|
50
|
+
release();
|
|
51
|
+
if (locks.get(root) === next) locks.delete(root);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function pin(dir) {
|
|
55
|
+
active.set(dir, (active.get(dir) ?? 0) + 1);
|
|
56
|
+
}
|
|
57
|
+
function unpin(dir) {
|
|
58
|
+
const count = active.get(dir) ?? 0;
|
|
59
|
+
if (count <= 1) active.delete(dir);
|
|
60
|
+
else active.set(dir, count - 1);
|
|
61
|
+
}
|
|
62
|
+
function missing(err) {
|
|
63
|
+
return err instanceof Error && "code" in err && err.code === "ENOENT";
|
|
64
|
+
}
|
|
65
|
+
function alive(pid) {
|
|
66
|
+
try {
|
|
67
|
+
process.kill(pid, 0);
|
|
68
|
+
return true;
|
|
69
|
+
} catch (err) {
|
|
70
|
+
return !(err instanceof Error && "code" in err && err.code === "ESRCH");
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function hasLiveClaim(name, pattern) {
|
|
74
|
+
const match = pattern.exec(name);
|
|
75
|
+
return match !== null && alive(Number(match[1]));
|
|
76
|
+
}
|
|
77
|
+
function hasLiveLease(files) {
|
|
78
|
+
return files.some((name) => hasLiveClaim(name, LEASE_RE));
|
|
79
|
+
}
|
|
80
|
+
/** Staged copies keep their basename for native file uploads. */
|
|
81
|
+
function isStagedName(name) {
|
|
82
|
+
return name !== "" && name !== "." && name !== ".." && !STAGED_NAME_INVALID_RE.test(name);
|
|
83
|
+
}
|
|
84
|
+
function isMediaCachePath(path) {
|
|
85
|
+
return path.split(PATH_SEPARATOR_RE$1).some((part) => CACHE_COMPONENT_RE.test(part));
|
|
86
|
+
}
|
|
87
|
+
async function readOwner(dir) {
|
|
88
|
+
const marker = join(dir, META);
|
|
89
|
+
const info = await lstat(marker);
|
|
90
|
+
if (!info.isFile() || info.nlink !== 1) return void 0;
|
|
91
|
+
return cacheOwnerSchema.safeParse(JSON.parse(await readFile(marker, "utf8"))).data;
|
|
92
|
+
}
|
|
93
|
+
/** Private adapter cache. Only its marked, flat entries are candidates for deletion. */
|
|
94
|
+
var MediaCache = class MediaCache {
|
|
95
|
+
roots = /* @__PURE__ */ new Set();
|
|
96
|
+
cacheName;
|
|
97
|
+
timer;
|
|
98
|
+
starting;
|
|
99
|
+
generation = 0;
|
|
100
|
+
ttl;
|
|
101
|
+
orphanTtl;
|
|
102
|
+
maxBytes;
|
|
103
|
+
now;
|
|
104
|
+
options;
|
|
105
|
+
constructor(options = {}) {
|
|
106
|
+
this.options = options;
|
|
107
|
+
const owner = options.owner;
|
|
108
|
+
const key = owner === void 0 ? void 0 : createHash("sha256").update(JSON.stringify(owner)).digest("hex").slice(0, 32);
|
|
109
|
+
this.cacheName = key === void 0 ? CACHE_DIR : `.napuketto-media-v2-${key}`;
|
|
110
|
+
this.roots.add(resolve(MEDIA_TEMP_ROOT, this.cacheName));
|
|
111
|
+
if (options.root) this.roots.add(resolve(options.root, this.cacheName));
|
|
112
|
+
this.ttl = options.ttlMs ?? DAY;
|
|
113
|
+
this.orphanTtl = options.orphanTtlMs ?? 36e5;
|
|
114
|
+
this.maxBytes = options.maxBytes ?? 536870912;
|
|
115
|
+
this.now = options.now ?? Date.now;
|
|
116
|
+
}
|
|
117
|
+
async start() {
|
|
118
|
+
if (this.timer !== void 0) return;
|
|
119
|
+
if (this.starting !== void 0) return await this.starting;
|
|
120
|
+
const generation = ++this.generation;
|
|
121
|
+
this.starting = this.sweep().then(() => {
|
|
122
|
+
if (generation !== this.generation) return;
|
|
123
|
+
this.timer = setInterval(() => {
|
|
124
|
+
this.sweep().catch((err) => {
|
|
125
|
+
this.options.logger?.warn({ error: errorMessage(err) }, "媒体缓存清理失败");
|
|
126
|
+
});
|
|
127
|
+
}, 6e4);
|
|
128
|
+
this.timer.unref();
|
|
129
|
+
});
|
|
130
|
+
try {
|
|
131
|
+
await this.starting;
|
|
132
|
+
} finally {
|
|
133
|
+
this.starting = void 0;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
stop() {
|
|
137
|
+
this.generation++;
|
|
138
|
+
if (this.timer !== void 0) clearInterval(this.timer);
|
|
139
|
+
this.timer = void 0;
|
|
140
|
+
}
|
|
141
|
+
/** Nested action helpers reuse the lease until the outer action finishes. */
|
|
142
|
+
async run(task) {
|
|
143
|
+
if (scopes.getStore()?.cache === this) return await task();
|
|
144
|
+
const scope = {
|
|
145
|
+
cache: this,
|
|
146
|
+
owned: /* @__PURE__ */ new Map(),
|
|
147
|
+
pinned: /* @__PURE__ */ new Map(),
|
|
148
|
+
failed: false
|
|
149
|
+
};
|
|
150
|
+
return await scopes.run(scope, async () => {
|
|
151
|
+
let result;
|
|
152
|
+
try {
|
|
153
|
+
result = await task();
|
|
154
|
+
} catch (err) {
|
|
155
|
+
await this.finish(scope, false).catch((cleanup) => {
|
|
156
|
+
this.options.logger?.warn({ error: errorMessage(cleanup) }, "媒体动作失败后的清理失败");
|
|
157
|
+
});
|
|
158
|
+
throw err;
|
|
159
|
+
}
|
|
160
|
+
await this.finish(scope, !scope.failed);
|
|
161
|
+
return result;
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
async finish(scope, success) {
|
|
165
|
+
const cleaned = await Promise.allSettled([...scope.owned].map(([dir, { lifetime, file }]) => locked(dirname(dir), async () => {
|
|
166
|
+
if (success && lifetime === "reference") await this.mark(dir, "reference", this.now() + this.ttl, { file });
|
|
167
|
+
else await this.remove(dir);
|
|
168
|
+
})));
|
|
169
|
+
const released = await Promise.allSettled([...scope.pinned].map(([dir, { lease }]) => locked(dirname(dir), async () => {
|
|
170
|
+
try {
|
|
171
|
+
await this.checkRoot(dirname(dir));
|
|
172
|
+
if ((await lstat(dir)).isSymbolicLink() || await realpath(dir) !== dir) throw kernelError("媒体缓存租约边界已改变", "INVALID_STATE");
|
|
173
|
+
await unlink(join(dir, lease));
|
|
174
|
+
} finally {
|
|
175
|
+
unpin(dir);
|
|
176
|
+
}
|
|
177
|
+
})));
|
|
178
|
+
for (const dir of scope.owned.keys()) unpin(dir);
|
|
179
|
+
const failure = [...cleaned, ...released].find((result) => result.status === "rejected");
|
|
180
|
+
if (failure?.status === "rejected") throw failure.reason;
|
|
181
|
+
}
|
|
182
|
+
/** Allocate before any download/write. Writer may return a renamed output in the same entry. */
|
|
183
|
+
async create(base, extension, writer, lifetime = "temporary", inputName) {
|
|
184
|
+
if (!EXTENSION_RE$1.test(extension)) throw kernelError("非法媒体缓存扩展名", "INVALID_PARAM");
|
|
185
|
+
if (inputName !== void 0 && (!isStagedName(inputName) || lifetime !== "temporary")) throw kernelError("非法媒体副本文件名", "INVALID_PARAM");
|
|
186
|
+
await mkdir(resolve(base), {
|
|
187
|
+
recursive: true,
|
|
188
|
+
mode: 448
|
|
189
|
+
});
|
|
190
|
+
const baseDir = await realpath(resolve(base));
|
|
191
|
+
await this.checkDirectory(baseDir);
|
|
192
|
+
const root = join(baseDir, this.cacheName);
|
|
193
|
+
this.roots.add(root);
|
|
194
|
+
const dir = await this.allocate(root, inputName);
|
|
195
|
+
const scope = scopes.getStore();
|
|
196
|
+
try {
|
|
197
|
+
const output = await this.writeEntry(dir, extension, writer, inputName);
|
|
198
|
+
await locked(root, async () => {
|
|
199
|
+
if (await this.collect(root) > this.maxBytes) throw kernelError("媒体缓存容量已满(引用期限或使用中租约保护)", "INVALID_STATE");
|
|
200
|
+
if (scope === void 0 && inputName === void 0) await this.mark(dir, "reference", this.now() + this.ttl, { file: basename(output) });
|
|
201
|
+
});
|
|
202
|
+
if (scope !== void 0) scope.owned.set(dir, {
|
|
203
|
+
lifetime,
|
|
204
|
+
file: basename(output)
|
|
205
|
+
});
|
|
206
|
+
else unpin(dir);
|
|
207
|
+
return output;
|
|
208
|
+
} catch (err) {
|
|
209
|
+
try {
|
|
210
|
+
await locked(root, () => this.remove(dir));
|
|
211
|
+
} finally {
|
|
212
|
+
unpin(dir);
|
|
213
|
+
}
|
|
214
|
+
throw err;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
async allocate(root, inputName) {
|
|
218
|
+
return await locked(root, async () => {
|
|
219
|
+
await mkdir(root, {
|
|
220
|
+
recursive: true,
|
|
221
|
+
mode: 448
|
|
222
|
+
});
|
|
223
|
+
await this.checkRoot(root);
|
|
224
|
+
await this.collect(root);
|
|
225
|
+
for (let attempt = 0; attempt < 8; attempt++) {
|
|
226
|
+
const candidate = join(root, `entry-${process.pid}-${randomUUID()}`);
|
|
227
|
+
try {
|
|
228
|
+
await mkdir(candidate, { mode: 448 });
|
|
229
|
+
} catch (err) {
|
|
230
|
+
if (err instanceof Error && "code" in err && err.code === "EEXIST") continue;
|
|
231
|
+
throw err;
|
|
232
|
+
}
|
|
233
|
+
pin(candidate);
|
|
234
|
+
try {
|
|
235
|
+
await this.mark(candidate, "temporary", this.now() + this.orphanTtl, { inputName });
|
|
236
|
+
} catch (err) {
|
|
237
|
+
unpin(candidate);
|
|
238
|
+
await rmdir(candidate);
|
|
239
|
+
throw err;
|
|
240
|
+
}
|
|
241
|
+
return candidate;
|
|
242
|
+
}
|
|
243
|
+
throw kernelError("媒体缓存命名冲突", "INVALID_STATE");
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
async writeEntry(dir, extension, writer, inputName) {
|
|
247
|
+
const path = inputName === void 0 ? join(dir, `media${extension}`) : join(dir, STAGED_DIR, inputName);
|
|
248
|
+
if (inputName !== void 0) await mkdir(dirname(path), { mode: 448 });
|
|
249
|
+
const output = await writer(path) ?? path;
|
|
250
|
+
const info = await lstat(output);
|
|
251
|
+
if (!(inputName === void 0 ? dirname(resolve(output)) === dir && CACHE_FILE_RE.test(basename(output)) : output === path) || !info.isFile()) throw kernelError("媒体缓存输出超出受控目录", "INVALID_STATE");
|
|
252
|
+
return output;
|
|
253
|
+
}
|
|
254
|
+
async sweep() {
|
|
255
|
+
for (const configuredRoot of this.roots) {
|
|
256
|
+
let root;
|
|
257
|
+
try {
|
|
258
|
+
root = join(await realpath(dirname(configuredRoot)), this.cacheName);
|
|
259
|
+
} catch (err) {
|
|
260
|
+
if (missing(err)) continue;
|
|
261
|
+
throw err;
|
|
262
|
+
}
|
|
263
|
+
await locked(root, async () => {
|
|
264
|
+
try {
|
|
265
|
+
await this.checkRoot(root);
|
|
266
|
+
} catch (err) {
|
|
267
|
+
if (missing(err)) return;
|
|
268
|
+
throw err;
|
|
269
|
+
}
|
|
270
|
+
await this.collect(root);
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
async checkRoot(root) {
|
|
275
|
+
if (basename(root) === this.cacheName) await this.checkDirectory(dirname(root));
|
|
276
|
+
await this.checkDirectory(root);
|
|
277
|
+
}
|
|
278
|
+
async checkDirectory(root) {
|
|
279
|
+
const info = await lstat(root);
|
|
280
|
+
if (!info.isDirectory() || info.isSymbolicLink() || uid !== void 0 && (info.uid !== uid || (info.mode & 18) !== 0) || await realpath(root) !== root) throw kernelError("媒体缓存目录归属或边界无效", "INVALID_STATE");
|
|
281
|
+
}
|
|
282
|
+
async leaseReference(scope, path) {
|
|
283
|
+
const dir = dirname(path);
|
|
284
|
+
const root = dirname(dir);
|
|
285
|
+
if (basename(root) !== this.cacheName || !ENTRY_RE.test(basename(dir)) || !CACHE_FILE_RE.test(basename(path)) || !await this.ownsRoot(root)) throw kernelError("媒体缓存引用归属无效", "INVALID_PARAM");
|
|
286
|
+
await locked(root, async () => {
|
|
287
|
+
const pinned = scope.pinned.get(dir);
|
|
288
|
+
if (pinned !== void 0) {
|
|
289
|
+
if (pinned.path !== path) throw kernelError("媒体缓存文件不匹配", "INVALID_PARAM");
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
await this.checkRoot(root);
|
|
293
|
+
if (await realpath(dir) !== dir || !(await lstat(dir)).isDirectory()) throw kernelError("媒体缓存引用边界无效", "INVALID_PARAM");
|
|
294
|
+
const lease = `.lease-${process.pid}-${randomUUID()}`;
|
|
295
|
+
const leasePath = join(dir, lease);
|
|
296
|
+
await writeFile(leasePath, "", {
|
|
297
|
+
flag: "wx",
|
|
298
|
+
mode: 384
|
|
299
|
+
});
|
|
300
|
+
try {
|
|
301
|
+
await this.checkReference(dir, path);
|
|
302
|
+
pin(dir);
|
|
303
|
+
scope.pinned.set(dir, {
|
|
304
|
+
lease,
|
|
305
|
+
path
|
|
306
|
+
});
|
|
307
|
+
} catch (err) {
|
|
308
|
+
await unlink(leasePath).catch((cleanup) => {
|
|
309
|
+
if (!missing(cleanup)) throw cleanup;
|
|
310
|
+
});
|
|
311
|
+
throw err;
|
|
312
|
+
}
|
|
313
|
+
});
|
|
314
|
+
return path;
|
|
315
|
+
}
|
|
316
|
+
async checkReference(dir, path) {
|
|
317
|
+
const files = await readdir(dir);
|
|
318
|
+
const owner = await readOwner(dir);
|
|
319
|
+
const info = await lstat(path);
|
|
320
|
+
if (owner?.lifetime !== "reference" || owner.expires <= this.now() || owner.file !== basename(path) || files.some((name) => hasLiveClaim(name, COLLECT_RE)) || !info.isFile() || info.nlink !== 1 || await realpath(path) !== path) throw kernelError("媒体缓存引用无效或已过期", "INVALID_PARAM");
|
|
321
|
+
}
|
|
322
|
+
async ownsRoot(root) {
|
|
323
|
+
for (const configuredRoot of this.roots) try {
|
|
324
|
+
if (join(await realpath(dirname(configuredRoot)), this.cacheName) === root) return true;
|
|
325
|
+
} catch (err) {
|
|
326
|
+
if (!missing(err)) throw err;
|
|
327
|
+
}
|
|
328
|
+
return false;
|
|
329
|
+
}
|
|
330
|
+
static async leasePath(path) {
|
|
331
|
+
const scope = scopes.getStore();
|
|
332
|
+
if (scope === void 0 || !isAbsolute(path)) throw kernelError("媒体缓存引用缺少账号作用域或绝对路径", "INVALID_PARAM");
|
|
333
|
+
try {
|
|
334
|
+
return await scope.cache.leaseReference(scope, resolve(path));
|
|
335
|
+
} catch (err) {
|
|
336
|
+
if (!missing(err)) throw err;
|
|
337
|
+
throw kernelError("媒体缓存引用不存在", "INVALID_PARAM");
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
static async leaseInternal(base, account, entry, file) {
|
|
341
|
+
const cache = scopes.getStore()?.cache;
|
|
342
|
+
if (cache === void 0 || !ENTRY_RE.test(entry) || !CACHE_FILE_RE.test(file)) throw kernelError("内部媒体引用无效", "INVALID_PARAM");
|
|
343
|
+
const owner = cache.options.owner;
|
|
344
|
+
if (owner?.protocol !== "satori" || owner.account !== account) throw kernelError("内部媒体引用归属无效", "INVALID_PARAM");
|
|
345
|
+
try {
|
|
346
|
+
return await MediaCache.leasePath(join(await realpath(base), cache.cacheName, entry, file));
|
|
347
|
+
} catch (err) {
|
|
348
|
+
if (!missing(err)) throw err;
|
|
349
|
+
throw kernelError("内部媒体引用不存在", "INVALID_PARAM");
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
async mark(dir, lifetime, expires, details = {}) {
|
|
353
|
+
await this.checkRoot(dirname(dir));
|
|
354
|
+
const info = await lstat(dir);
|
|
355
|
+
if (!info.isDirectory() || info.isSymbolicLink() || await realpath(dir) !== dir) throw kernelError("媒体缓存条目边界无效", "INVALID_STATE");
|
|
356
|
+
const metadata = join(dir, META);
|
|
357
|
+
const next = join(dir, `.owner-next-${randomUUID()}.json`);
|
|
358
|
+
try {
|
|
359
|
+
await writeFile(next, JSON.stringify({
|
|
360
|
+
version: 1,
|
|
361
|
+
lifetime,
|
|
362
|
+
expires,
|
|
363
|
+
...details
|
|
364
|
+
}), { flag: "wx" });
|
|
365
|
+
await rename(next, metadata);
|
|
366
|
+
} finally {
|
|
367
|
+
await unlink(next).catch((err) => {
|
|
368
|
+
if (!missing(err)) throw err;
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
async inspect(dir) {
|
|
373
|
+
const match = ENTRY_RE.exec(basename(dir));
|
|
374
|
+
if (match === null) return void 0;
|
|
375
|
+
const info = await lstat(dir);
|
|
376
|
+
if (!info.isDirectory() || info.isSymbolicLink()) return void 0;
|
|
377
|
+
const files = await readdir(dir);
|
|
378
|
+
if (!files.includes(META)) return void 0;
|
|
379
|
+
const parsed = await readOwner(dir);
|
|
380
|
+
if (parsed === void 0) return void 0;
|
|
381
|
+
const summary = await this.summarize(dir, files, parsed.inputName);
|
|
382
|
+
if (summary === void 0) return void 0;
|
|
383
|
+
const pid = Number(match[1]);
|
|
384
|
+
return {
|
|
385
|
+
dir,
|
|
386
|
+
owner: parsed,
|
|
387
|
+
bytes: summary.bytes,
|
|
388
|
+
files: summary.files,
|
|
389
|
+
directories: summary.directories,
|
|
390
|
+
foreignLive: pid !== process.pid && alive(pid) || hasLiveLease(files),
|
|
391
|
+
removable: summary.removable
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
async summarize(dir, files, inputName) {
|
|
395
|
+
const out = {
|
|
396
|
+
bytes: 0,
|
|
397
|
+
removable: true,
|
|
398
|
+
files: [],
|
|
399
|
+
directories: []
|
|
400
|
+
};
|
|
401
|
+
for (const file of files) {
|
|
402
|
+
const item = await this.summarizeFile(dir, file, inputName);
|
|
403
|
+
if (item === void 0) return void 0;
|
|
404
|
+
out.bytes += item.bytes;
|
|
405
|
+
out.removable &&= item.removable;
|
|
406
|
+
out.files.push(...item.files);
|
|
407
|
+
out.directories.push(...item.directories);
|
|
408
|
+
}
|
|
409
|
+
return out;
|
|
410
|
+
}
|
|
411
|
+
async summarizeFile(dir, file, inputName) {
|
|
412
|
+
const path = join(dir, file);
|
|
413
|
+
const stat = await lstat(path);
|
|
414
|
+
const stagedName = file === STAGED_DIR ? inputName : void 0;
|
|
415
|
+
if (stat.isDirectory() && (stagedName !== void 0 || VIDEO_DIR_RE.test(file))) return await this.summarizeDirectory(path, file, stagedName);
|
|
416
|
+
const regular = stat.isFile();
|
|
417
|
+
if (file === META && !regular) return void 0;
|
|
418
|
+
return {
|
|
419
|
+
bytes: file === META ? 0 : regular ? stat.size : Number.POSITIVE_INFINITY,
|
|
420
|
+
removable: regular && (file === META || OWNED_FILE_RE.test(file) || COLLECT_RE.test(file)),
|
|
421
|
+
files: [file],
|
|
422
|
+
directories: []
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
async summarizeDirectory(path, file, stagedName) {
|
|
426
|
+
const nested = stagedName === void 0 ? await this.videoOutput(path) : await this.stagedOutput(path, stagedName);
|
|
427
|
+
return nested === void 0 ? {
|
|
428
|
+
bytes: Number.POSITIVE_INFINITY,
|
|
429
|
+
removable: false,
|
|
430
|
+
files: [],
|
|
431
|
+
directories: []
|
|
432
|
+
} : {
|
|
433
|
+
bytes: nested.bytes,
|
|
434
|
+
removable: true,
|
|
435
|
+
files: nested.files.map((name) => join(file, name)),
|
|
436
|
+
directories: [...nested.directories.map((name) => join(file, name)), file]
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
async stagedOutput(dir, inputName) {
|
|
440
|
+
if (await realpath(dir) !== dir) return void 0;
|
|
441
|
+
const out = {
|
|
442
|
+
bytes: 0,
|
|
443
|
+
removable: true,
|
|
444
|
+
files: [],
|
|
445
|
+
directories: []
|
|
446
|
+
};
|
|
447
|
+
for (const name of await readdir(dir)) {
|
|
448
|
+
const path = join(dir, name);
|
|
449
|
+
if (name === inputName) {
|
|
450
|
+
const info = await lstat(path);
|
|
451
|
+
if (!info.isFile() || info.nlink !== 1) return void 0;
|
|
452
|
+
out.bytes += info.size;
|
|
453
|
+
out.files.push(name);
|
|
454
|
+
} else {
|
|
455
|
+
if (!VIDEO_DIR_RE.test(name)) return void 0;
|
|
456
|
+
const video = await this.videoOutput(path);
|
|
457
|
+
if (video === void 0) return void 0;
|
|
458
|
+
out.bytes += video.bytes;
|
|
459
|
+
out.files.push(...video.files.map((file) => join(name, file)));
|
|
460
|
+
out.directories.push(name);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return out;
|
|
464
|
+
}
|
|
465
|
+
async videoOutput(dir) {
|
|
466
|
+
if (await realpath(dir) !== dir || !(await lstat(dir)).isDirectory()) return void 0;
|
|
467
|
+
const files = await readdir(dir);
|
|
468
|
+
const [file] = files;
|
|
469
|
+
if (file === void 0) return {
|
|
470
|
+
bytes: 0,
|
|
471
|
+
files,
|
|
472
|
+
directories: [],
|
|
473
|
+
removable: true
|
|
474
|
+
};
|
|
475
|
+
if (files.length !== 1 || file !== "output.mp4") return void 0;
|
|
476
|
+
const info = await lstat(join(dir, file));
|
|
477
|
+
return info.isFile() && !info.isSymbolicLink() ? {
|
|
478
|
+
bytes: info.size,
|
|
479
|
+
files,
|
|
480
|
+
directories: [],
|
|
481
|
+
removable: true
|
|
482
|
+
} : void 0;
|
|
483
|
+
}
|
|
484
|
+
async collect(root) {
|
|
485
|
+
let total = 0;
|
|
486
|
+
for (const name of await readdir(root)) {
|
|
487
|
+
const dir = join(root, name);
|
|
488
|
+
let entry;
|
|
489
|
+
try {
|
|
490
|
+
entry = await this.inspect(dir);
|
|
491
|
+
} catch (err) {
|
|
492
|
+
if (missing(err) || err instanceof SyntaxError) continue;
|
|
493
|
+
throw err;
|
|
494
|
+
}
|
|
495
|
+
if (entry === void 0) continue;
|
|
496
|
+
if (this.canCollect(entry)) await this.remove(dir).catch((err) => {
|
|
497
|
+
if (!missing(err)) throw err;
|
|
498
|
+
});
|
|
499
|
+
else total += entry.bytes;
|
|
500
|
+
}
|
|
501
|
+
return total;
|
|
502
|
+
}
|
|
503
|
+
canCollect(entry) {
|
|
504
|
+
return entry.removable && !active.has(entry.dir) && !entry.foreignLive && entry.owner.expires <= this.now();
|
|
505
|
+
}
|
|
506
|
+
async remove(dir) {
|
|
507
|
+
await this.checkRoot(dirname(dir));
|
|
508
|
+
if (await realpath(dir) !== dir || !(await lstat(dir)).isDirectory()) return;
|
|
509
|
+
const claim = `.collect-${process.pid}-${randomUUID()}`;
|
|
510
|
+
const marker = join(dir, claim);
|
|
511
|
+
await writeFile(marker, "", {
|
|
512
|
+
flag: "wx",
|
|
513
|
+
mode: 384
|
|
514
|
+
});
|
|
515
|
+
try {
|
|
516
|
+
const entry = await this.inspect(dir);
|
|
517
|
+
if (entry === void 0 || !entry.removable || hasLiveLease(entry.files) || entry.files.some((name) => name !== claim && hasLiveClaim(name, COLLECT_RE))) return;
|
|
518
|
+
await this.removeContents(entry, claim);
|
|
519
|
+
} finally {
|
|
520
|
+
await unlink(marker).catch((err) => {
|
|
521
|
+
if (!missing(err)) throw err;
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
await rmdir(dir).catch((err) => {
|
|
525
|
+
if (!missing(err) && !(err instanceof Error && "code" in err && err.code === "ENOTEMPTY")) throw err;
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
async removeContents(entry, claim) {
|
|
529
|
+
const { dir } = entry;
|
|
530
|
+
for (const file of entry.files.filter((name) => name !== META && name !== claim)) {
|
|
531
|
+
await this.checkRoot(dirname(dir));
|
|
532
|
+
if (await realpath(dir) !== dir || (await lstat(dir)).isSymbolicLink()) throw kernelError("媒体缓存条目边界已改变", "INVALID_STATE");
|
|
533
|
+
const path = join(dir, file);
|
|
534
|
+
if (await realpath(dirname(path)) !== dirname(path)) return;
|
|
535
|
+
const info = await lstat(path);
|
|
536
|
+
if (!info.isFile() || info.isSymbolicLink()) return;
|
|
537
|
+
await unlink(path);
|
|
538
|
+
}
|
|
539
|
+
for (const name of entry.directories) await rmdir(join(dir, name));
|
|
540
|
+
await unlink(join(dir, META));
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
/** Action factories also work independently of an adapter/registry. */
|
|
544
|
+
async function withMediaScope(task) {
|
|
545
|
+
const scope = scopes.getStore();
|
|
546
|
+
if (scope === void 0) return await new MediaCache().run(task);
|
|
547
|
+
try {
|
|
548
|
+
return await task();
|
|
549
|
+
} catch (err) {
|
|
550
|
+
scope.failed = true;
|
|
551
|
+
throw err;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
async function cacheMediaFile(root, extension, writer, lifetime = "temporary", inputName) {
|
|
555
|
+
return await (scopes.getStore()?.cache ?? new MediaCache()).create(root, extension, writer, lifetime, inputName);
|
|
556
|
+
}
|
|
557
|
+
/** Lease a reference explicitly supplied by a caller. No temporary files are eligible. */
|
|
558
|
+
const leaseMediaReference = MediaCache.leasePath;
|
|
559
|
+
/** Only the current Satori account can consume its internal IDs. */
|
|
560
|
+
const leaseInternalMedia = MediaCache.leaseInternal;
|
|
561
|
+
// src/internal/infra/local-media.ts
|
|
562
|
+
const MAX_FILE_BYTES = 536870912;
|
|
563
|
+
const WINDOWS = process.platform === "win32";
|
|
564
|
+
const DEVICE_RE = /^(?:con|prn|aux|nul|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i;
|
|
565
|
+
const DRIVE_PATH_RE = /^[a-z]:[\\/]/i;
|
|
566
|
+
const NETWORK_PATH_RE = /^[\\/]{2}/;
|
|
567
|
+
const PATH_SEPARATOR_RE = /[\\/]/;
|
|
568
|
+
const WINDOWS_INVALID_NAME_RE = /[<>:"|?*]|[ .]$/;
|
|
569
|
+
const FILE_SCHEME_RE = /^file:/i;
|
|
570
|
+
const FILE_URI_RE = /^file:\/\//i;
|
|
571
|
+
const EXTENSION_RE = /\.[a-z0-9]+$/i;
|
|
572
|
+
const URI_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
|
|
573
|
+
function denied() {
|
|
574
|
+
return kernelError("本地媒体路径未授权或文件不可用", "INVALID_PARAM");
|
|
575
|
+
}
|
|
576
|
+
function validateWindowsPath(path) {
|
|
577
|
+
if (isAbsolute(path) && !DRIVE_PATH_RE.test(path)) throw denied();
|
|
578
|
+
const components = path.replace(DRIVE_PATH_RE, "").split(PATH_SEPARATOR_RE);
|
|
579
|
+
for (const part of components) {
|
|
580
|
+
if (part === "." || part === "..") continue;
|
|
581
|
+
if (WINDOWS_INVALID_NAME_RE.test(part) || DEVICE_RE.test(part)) throw denied();
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
function validatePath(path) {
|
|
585
|
+
if (path === "" || path.includes("\0") || NETWORK_PATH_RE.test(path)) throw denied();
|
|
586
|
+
if (URI_SCHEME_RE.test(path) && !(WINDOWS && DRIVE_PATH_RE.test(path))) throw denied();
|
|
587
|
+
if (WINDOWS) validateWindowsPath(path);
|
|
588
|
+
return path;
|
|
589
|
+
}
|
|
590
|
+
function decodeLocalPath(input) {
|
|
591
|
+
if (!FILE_SCHEME_RE.test(input)) return validatePath(input);
|
|
592
|
+
try {
|
|
593
|
+
if (!FILE_URI_RE.test(input)) throw denied();
|
|
594
|
+
const url = new URL(input);
|
|
595
|
+
if (url.search || url.hash || url.hostname !== "") throw denied();
|
|
596
|
+
return validatePath(fileURLToPath(url));
|
|
597
|
+
} catch {
|
|
598
|
+
throw denied();
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
/** Resolve configuration relative to the trusted host base, never to a request path. */
|
|
602
|
+
function bindLocalMediaRoots(base, configured) {
|
|
603
|
+
const anchor = resolve(base ?? ".");
|
|
604
|
+
return () => (configured?.() ?? []).map((root) => resolve(anchor, validatePath(root)));
|
|
605
|
+
}
|
|
606
|
+
function within(root, path) {
|
|
607
|
+
return path.startsWith(root.endsWith(sep) ? root : root + sep) && path !== root;
|
|
608
|
+
}
|
|
609
|
+
function unavailable(err) {
|
|
610
|
+
return err instanceof Error && "code" in err && [
|
|
611
|
+
"ENOENT",
|
|
612
|
+
"ENOTDIR",
|
|
613
|
+
"EACCES",
|
|
614
|
+
"EPERM",
|
|
615
|
+
"ELOOP"
|
|
616
|
+
].includes(String(err.code));
|
|
617
|
+
}
|
|
618
|
+
function sameFile(a, b) {
|
|
619
|
+
return a.isFile() && b.isFile() && a.dev === b.dev && a.ino === b.ino && a.ino !== 0n;
|
|
620
|
+
}
|
|
621
|
+
function withinInputRoot(root, path) {
|
|
622
|
+
return WINDOWS ? within(root.toLowerCase(), path.toLowerCase()) : within(root, path);
|
|
623
|
+
}
|
|
624
|
+
async function findCandidate(input, configuredRoot) {
|
|
625
|
+
try {
|
|
626
|
+
const root = validatePath(await realpath(configuredRoot));
|
|
627
|
+
const candidate = resolve(root, input);
|
|
628
|
+
if (!withinInputRoot(root, candidate) && !withinInputRoot(configuredRoot, candidate)) return void 0;
|
|
629
|
+
const path = validatePath(await realpath(candidate));
|
|
630
|
+
if (!within(root, path) || isMediaCachePath(path)) throw denied();
|
|
631
|
+
const before = await lstat(path, { bigint: true });
|
|
632
|
+
if (!before.isFile() || before.nlink !== 1n) throw denied();
|
|
633
|
+
return {
|
|
634
|
+
root,
|
|
635
|
+
path,
|
|
636
|
+
before
|
|
637
|
+
};
|
|
638
|
+
} catch (err) {
|
|
639
|
+
if (unavailable(err)) return void 0;
|
|
640
|
+
throw err;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
async function selectCandidate(input, roots) {
|
|
644
|
+
const matches = /* @__PURE__ */ new Map();
|
|
645
|
+
for (const root of roots) {
|
|
646
|
+
const candidate = await findCandidate(input, resolve(root));
|
|
647
|
+
if (candidate !== void 0) matches.set(candidate.path, candidate);
|
|
648
|
+
}
|
|
649
|
+
if (matches.size !== 1) throw denied();
|
|
650
|
+
const [match] = matches.values();
|
|
651
|
+
if (match === void 0) throw denied();
|
|
652
|
+
return match;
|
|
653
|
+
}
|
|
654
|
+
async function verifyOpenFile(candidate, file) {
|
|
655
|
+
const { root, path, before } = candidate;
|
|
656
|
+
const opened = await file.stat({ bigint: true });
|
|
657
|
+
if (!sameFile(before, opened) || opened.nlink !== 1n || opened.size > MAX_FILE_BYTES) throw denied();
|
|
658
|
+
const actual = process.platform === "linux" ? await readlink(`/proc/self/fd/${file.fd}`) : await realpath(path);
|
|
659
|
+
if (actual !== path || !within(root, actual)) throw denied();
|
|
660
|
+
const after = await lstat(actual, { bigint: true });
|
|
661
|
+
if (!sameFile(after, opened) || after.nlink !== 1n) throw denied();
|
|
662
|
+
return Number(opened.size);
|
|
663
|
+
}
|
|
664
|
+
async function writeSnapshot(file, path, size) {
|
|
665
|
+
if (size === 0) {
|
|
666
|
+
await writeFile(path, "", {
|
|
667
|
+
flag: "wx",
|
|
668
|
+
mode: 384
|
|
669
|
+
});
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
const output = createWriteStream(path, {
|
|
673
|
+
flags: "wx",
|
|
674
|
+
mode: 384
|
|
675
|
+
});
|
|
676
|
+
await pipeline(file.createReadStream({
|
|
677
|
+
autoClose: false,
|
|
678
|
+
start: 0,
|
|
679
|
+
end: size - 1
|
|
680
|
+
}), output);
|
|
681
|
+
if (output.bytesWritten !== size) throw denied();
|
|
682
|
+
}
|
|
683
|
+
async function snapshot(candidate, cacheDir, lifetime) {
|
|
684
|
+
const linuxFlags = constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK;
|
|
685
|
+
const file = await open(candidate.path, WINDOWS ? "r" : linuxFlags);
|
|
686
|
+
try {
|
|
687
|
+
const size = await verifyOpenFile(candidate, file);
|
|
688
|
+
const name = basename(candidate.path);
|
|
689
|
+
return await cacheMediaFile(cacheDir, EXTENSION_RE.exec(name)?.[0] ?? ".bin", (path) => writeSnapshot(file, path, size), lifetime, lifetime === "temporary" ? name : void 0);
|
|
690
|
+
} finally {
|
|
691
|
+
await file.close();
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
/** The result is safe to hand to consumers that reopen a path, including native APIs. */
|
|
695
|
+
async function resolveLocalMedia(input, roots = []) {
|
|
696
|
+
const path = decodeLocalPath(input);
|
|
697
|
+
if (isMediaCachePath(path)) return await leaseMediaReference(path);
|
|
698
|
+
try {
|
|
699
|
+
return await snapshot(await selectCandidate(path, roots), MEDIA_TEMP_ROOT, "temporary");
|
|
700
|
+
} catch (err) {
|
|
701
|
+
if (unavailable(err)) throw denied();
|
|
702
|
+
throw err;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
/** QQ sources come from a current-account message/API response, never from RPC path fields. */
|
|
706
|
+
async function exportQqMedia(source, qqRoot, cacheDir) {
|
|
707
|
+
if (!source || !qqRoot) return void 0;
|
|
708
|
+
try {
|
|
709
|
+
const candidate = await findCandidate(validatePath(source.replaceAll("\\", sep)), resolve(qqRoot));
|
|
710
|
+
if (candidate === void 0) return void 0;
|
|
711
|
+
return await snapshot(candidate, cacheDir || MEDIA_TEMP_ROOT, "reference");
|
|
712
|
+
} catch (err) {
|
|
713
|
+
if (unavailable(err) || err instanceof Error && "code" in err && err.code === "INVALID_PARAM") return;
|
|
714
|
+
throw err;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
// src/internal/qq/media.ts
|
|
718
|
+
/**
|
|
719
|
+
* adapter core 媒体辅助:语音归一化 + 视频缩略图(media 严格解耦的协议层落点)
|
|
720
|
+
*
|
|
721
|
+
* 协议层(onebot11 / satori)发送媒体前统一走这里:
|
|
722
|
+
* - `ensureSilk`:非 silk 音频转 QQ 语音格式(silk v3);
|
|
723
|
+
* - `prepareVideoElements`:视频缺缩略图/时长/尺寸时,用 ffmpeg 抽首帧并探测元数据。
|
|
724
|
+
* 都依赖 @napuketto/media,只发生在 adapter 层;kernel 不 import media(红线),
|
|
725
|
+
* 只接收「文件齐全」的 canonical 元素。
|
|
726
|
+
*/
|
|
727
|
+
const MEDIA_EXTENSION_RE = /^\.[a-zA-Z0-9]+$/;
|
|
728
|
+
const MAX_AUDIO_COPY_BYTES = 33554432;
|
|
729
|
+
/** 协议动作默认走公网下载,兼容模式由受信任的装配方显式启用。 */
|
|
730
|
+
function mediaDownloader(policy) {
|
|
731
|
+
return policy === "compat" ? downloadUrl : downloadPublicUrl;
|
|
732
|
+
}
|
|
733
|
+
/** 转换有上传语义的下载失败,保留既有 SEND_FAILED 信封。 */
|
|
734
|
+
async function downloadProtocolMedia(url, filePath, options = {}) {
|
|
735
|
+
try {
|
|
736
|
+
await mediaDownloader(options.outboundPolicy)(url, filePath, { headers: options.headers });
|
|
737
|
+
} catch (err) {
|
|
738
|
+
throw kernelError(`${options.errorLabel ?? "下载失败"}: ${errorMessage(err)}`, "SEND_FAILED", { cause: err });
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
/** 读文件头 8 字节(判断 silk 魔数)。 */
|
|
742
|
+
async function readFileHead(path) {
|
|
743
|
+
const handle = await open(path, "r");
|
|
744
|
+
try {
|
|
745
|
+
const buf = Buffer.alloc(8);
|
|
746
|
+
await handle.read(buf, 0, 8, 0);
|
|
747
|
+
return buf.toString("utf8");
|
|
748
|
+
} finally {
|
|
749
|
+
await handle.close();
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* 语音转码:非 silk 输入(任意音频格式,经 @napuketto/media 归一化)转 silk。
|
|
754
|
+
* 已是 silk(#!SILK_V3 头)原样返回;转码失败原样返回(由 kernel 发送时兜底),
|
|
755
|
+
* 可选 logger 记录降级上下文。
|
|
756
|
+
*/
|
|
757
|
+
async function ensureSilk(path, logger) {
|
|
758
|
+
try {
|
|
759
|
+
const info = await stat(path);
|
|
760
|
+
if (!info.isFile() || info.size > MAX_AUDIO_COPY_BYTES) throw kernelError("语音复制输入必须是 32MiB 以内的普通文件", "INVALID_PARAM");
|
|
761
|
+
if ((await readFileHead(path)).startsWith("#!SILK")) return path;
|
|
762
|
+
const ext = extname(path);
|
|
763
|
+
return await cacheMediaFile(MEDIA_TEMP_ROOT, MEDIA_EXTENSION_RE.test(ext) ? ext : ".bin", async (copy) => {
|
|
764
|
+
await copyFile(path, copy);
|
|
765
|
+
return await encodePcmToSilk(copy);
|
|
766
|
+
});
|
|
767
|
+
} catch (err) {
|
|
768
|
+
logger?.warn({
|
|
769
|
+
path,
|
|
770
|
+
error: errorMessage(err)
|
|
771
|
+
}, "语音 silk 转码失败,原样透传");
|
|
772
|
+
return path;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
/** 是否是需要补缩略图的视频元素。 */
|
|
776
|
+
function needsVideoThumb(el) {
|
|
777
|
+
return el.type === "video" && (el.thumbPath === void 0 || el.thumbPath === "");
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* 视频元素补「首帧缩略图 + 时长 + 尺寸」(QQ 视频消息发送契约)。
|
|
781
|
+
*
|
|
782
|
+
* 为什么必须补:kernel 的 `prepareVideoElement` 只有在 `thumbPath` 存在时才写
|
|
783
|
+
* `thumbMd5 / thumbSize / thumbPath(Map)`,缺失时 native 传输找不到缩略图,
|
|
784
|
+
* `sendMsg` 只回 `sendStatus=0`(无错误信息);`fileTime`(秒)也取自
|
|
785
|
+
* `durationSec`,缺省 0。Linux 原生宿主实测:只给 `file` 的 OB11 `video` 段
|
|
786
|
+
* 必然失败,补上首帧后成功。
|
|
787
|
+
*
|
|
788
|
+
* 缩略图写在系统临时目录(发送时 kernel 会 copyFile 进 QQ 数据目录),
|
|
789
|
+
* 由 `cleanup` 统一删除——不污染用户文件目录。
|
|
790
|
+
*
|
|
791
|
+
* 依赖系统 ffmpeg / ffprobe(@napuketto/media);缺失或抽帧失败时抛
|
|
792
|
+
* `MediaError`,由协议动作层映射成可读错误,而不是让 native 回 `sendStatus=0`。
|
|
793
|
+
*/
|
|
794
|
+
async function prepareVideoElements(elements) {
|
|
795
|
+
if (!elements.some(needsVideoThumb)) return {
|
|
796
|
+
elements: [...elements],
|
|
797
|
+
cleanup: async () => void 0
|
|
798
|
+
};
|
|
799
|
+
const dir = await mkdtemp(join(tmpdir(), "napuketto-video-thumb-"));
|
|
800
|
+
const cleanup = async () => {
|
|
801
|
+
await rm(dir, {
|
|
802
|
+
recursive: true,
|
|
803
|
+
force: true
|
|
804
|
+
});
|
|
805
|
+
};
|
|
806
|
+
try {
|
|
807
|
+
const out = [];
|
|
808
|
+
let index = 0;
|
|
809
|
+
for (const el of elements) {
|
|
810
|
+
if (!needsVideoThumb(el)) {
|
|
811
|
+
out.push(el);
|
|
812
|
+
continue;
|
|
813
|
+
}
|
|
814
|
+
index += 1;
|
|
815
|
+
const thumbPath = join(dir, `thumb-${index}.png`);
|
|
816
|
+
const info = await getVideoInfo(el.path);
|
|
817
|
+
await extractVideoFrame(el.path, thumbPath);
|
|
818
|
+
out.push({
|
|
819
|
+
...el,
|
|
820
|
+
thumbPath,
|
|
821
|
+
width: el.width ?? info.width,
|
|
822
|
+
height: el.height ?? info.height,
|
|
823
|
+
durationSec: el.durationSec ?? Math.max(1, Math.round(info.durationMs / 1e3))
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
return {
|
|
827
|
+
elements: out,
|
|
828
|
+
cleanup
|
|
829
|
+
};
|
|
830
|
+
} catch (err) {
|
|
831
|
+
await cleanup();
|
|
832
|
+
throw err;
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
// src/internal/infra/media-config.ts
|
|
836
|
+
const protocolMediaSchema = z.object({
|
|
837
|
+
localMediaRoots: z.array(z.string().min(1)).optional(),
|
|
838
|
+
outboundPolicy: z.enum(["public-only", "compat"]).optional()
|
|
839
|
+
});
|
|
840
|
+
// src/internal/infra/log.ts
|
|
841
|
+
/**
|
|
842
|
+
* raw 日志截断与最小 logger 面(协议 adapter 校准日志共用,自
|
|
843
|
+
* onebot11/milky adapter.ts 顶部内联工具收拢)。
|
|
844
|
+
*
|
|
845
|
+
* info/warn 级 raw 字段对运行状态无信息量(输出内容治理):
|
|
846
|
+
* hex/base64/JSON 原文保留前缀定位 + 缺省长度标注;完整值仅在 debug 级
|
|
847
|
+
* 与日志文件中出现。两种截断口径刻意并存——OB11 校准日志带缺省长度标注,
|
|
848
|
+
* Milky 长文本校准日志用固定切片(无标注)。
|
|
849
|
+
*/
|
|
850
|
+
/** info/warn 级截断缺省上限(OB11 口径)。 */
|
|
851
|
+
const RAW_INFO_LIMIT = 64;
|
|
852
|
+
/** 长文本截断缺省上限(debug / raw 校准日志防刷屏)。 */
|
|
853
|
+
const RAW_DEBUG_LIMIT = 2e3;
|
|
854
|
+
/**
|
|
855
|
+
* raw 字段截断:超限截断 + 缺省长度标注(…(+N))。
|
|
856
|
+
* OB11 校准日志(warn 级 64 缺省)口径。
|
|
857
|
+
*/
|
|
858
|
+
function truncRaw(value, keep = RAW_INFO_LIMIT) {
|
|
859
|
+
if (value === void 0) return "";
|
|
860
|
+
return value.length <= keep ? value : `${value.slice(0, keep)}…(+${value.length - keep})`;
|
|
861
|
+
}
|
|
862
|
+
/** 长文本截断:固定上限切片(Milky 校准日志 2000 缺省口径,无长度标注)。 */
|
|
863
|
+
function sliceRaw(value, max = RAW_DEBUG_LIMIT) {
|
|
864
|
+
return value === void 0 ? "" : value.slice(0, max);
|
|
865
|
+
}
|
|
866
|
+
/**
|
|
867
|
+
* 事件链翻译失败留痕(收链路异步 .catch 统一出口:单条/整批丢弃,warn 留痕
|
|
868
|
+
* 不打断订阅;err 规范化为 message 串)。
|
|
869
|
+
*/
|
|
870
|
+
function logEventFailure(logger, msg, err) {
|
|
871
|
+
logger?.warn({ err: errorMessage(err) }, msg);
|
|
872
|
+
}
|
|
873
|
+
// src/internal/qq/gray-tip.ts
|
|
874
|
+
/**
|
|
875
|
+
* 消息是否含 grayTip 元素(OB11 / Milky 收链路分流判据,收拢)。
|
|
876
|
+
* `!= null` 空值判定:Linux 原生宿主把未命中的变体字段显式置 null,
|
|
877
|
+
* `!== undefined` 会把普通消息误判成 grayTip 消息(见 OB11 hasFileElement 注)。
|
|
878
|
+
*/
|
|
879
|
+
function hasGrayTip(msg) {
|
|
880
|
+
return msg.elements.some((el) => el.grayTipElement != null);
|
|
881
|
+
}
|
|
882
|
+
/** 非空 uid 才加入集合(Linux 原生对象未命中的字段是显式 null,不只 undefined)。 */
|
|
883
|
+
function collectUids(uids, ...candidates) {
|
|
884
|
+
for (const uid of candidates) if (uid != null && uid !== "") uids.add(uid);
|
|
885
|
+
}
|
|
886
|
+
/** 收集 grayTip 涉及的 uid(批量 uidToUin 用)。 */
|
|
887
|
+
function collectGrayTipUids(msg) {
|
|
888
|
+
const uids = /* @__PURE__ */ new Set();
|
|
889
|
+
for (const el of msg.elements) {
|
|
890
|
+
const g = el.grayTipElement;
|
|
891
|
+
if (g == null) continue;
|
|
892
|
+
collectUids(uids, g.revokeElement?.operatorUid, g.aioOpGrayTipElement?.peerUid);
|
|
893
|
+
const grp = g.groupElement;
|
|
894
|
+
if (grp == null) continue;
|
|
895
|
+
collectUids(uids, grp.memberUid, grp.adminUid, grp.shutUp?.admin?.uid, grp.shutUp?.member?.uid);
|
|
896
|
+
}
|
|
897
|
+
return [...uids];
|
|
898
|
+
}
|
|
899
|
+
/**
|
|
900
|
+
* 第一条「已挂载但不可翻译」的 grayTip 元素(校准日志入口)。
|
|
901
|
+
* 与 OB11 / Milky notice 翻译共用:翻译函数返回 null 时用本函数定位元素打 raw
|
|
902
|
+
* 日志,两协议的日志口径一致(跳过 REVOKE——撤回翻译独立成事件)。
|
|
903
|
+
*/
|
|
904
|
+
function firstUntranslatedGrayTip(msg) {
|
|
905
|
+
for (const el of msg.elements) {
|
|
906
|
+
const g = el.grayTipElement;
|
|
907
|
+
if (g != null && g.revokeElement == null) return g;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
/**
|
|
911
|
+
* 撤回 grayTip 元素(非撤回消息返回 undefined;Milky 收链路 notice/召回
|
|
912
|
+
* 分流判据,自 milky adapter.ts 收拢)。
|
|
913
|
+
*/
|
|
914
|
+
function findRevokeElement(msg) {
|
|
915
|
+
return msg.elements.find((el) => el.grayTipElement?.revokeElement != null)?.grayTipElement?.revokeElement ?? void 0;
|
|
916
|
+
}
|
|
917
|
+
export { cacheMediaFile as _, logEventFailure as a, protocolMediaSchema as c, mediaDownloader as d, prepareVideoElements as f, MediaCache as g, resolveLocalMedia as h, hasGrayTip as i, downloadProtocolMedia as l, exportQqMedia as m, findRevokeElement as n, sliceRaw as o, bindLocalMediaRoots as p, firstUntranslatedGrayTip as r, truncRaw as s, collectGrayTipUids as t, ensureSilk as u, leaseInternalMedia as v, withMediaScope as y };
|