levix-bot 4.3.0 → 4.4.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/README.md +1 -0
- package/package.json +1 -1
- package/public/dashboard/assets/index-5P8GnKLg.css +2 -0
- package/public/dashboard/assets/index-DXzno3X6.js +515 -0
- package/public/dashboard/index.html +2 -2
- package/public/dashboard.css +32 -0
- package/src/bootstrap/panel.js +16 -4
- package/src/commands/autoschedule.cjs +1 -1
- package/src/commands/blacklist.cjs +1 -1
- package/src/commands/calc.cjs +9 -9
- package/src/commands/gemini.cjs +26 -26
- package/src/commands/group/add.cjs +2 -2
- package/src/commands/group/demote.cjs +2 -2
- package/src/commands/group/members.cjs +2 -2
- package/src/commands/group/rules.cjs +1 -1
- package/src/commands/group/setname.cjs +3 -3
- package/src/commands/group/setpp.cjs +3 -3
- package/src/commands/group/setrules.cjs +1 -1
- package/src/commands/group/tagadmins.cjs +1 -1
- package/src/commands/group.cjs +1 -1
- package/src/commands/lang.cjs +3 -3
- package/src/commands/listschedules.cjs +1 -1
- package/src/commands/loop.cjs +3 -3
- package/src/commands/memory.cjs +18 -18
- package/src/commands/notes.cjs +1 -1
- package/src/commands/pack.cjs +159 -0
- package/src/commands/packs.cjs +47 -0
- package/src/commands/perm.cjs +2 -2
- package/src/commands/poll.cjs +3 -3
- package/src/commands/rand.cjs +2 -2
- package/src/commands/restart.cjs +4 -4
- package/src/commands/schedule.cjs +1 -1
- package/src/commands/send.cjs +3 -20
- package/src/commands/status.cjs +2 -2
- package/src/commands/sticker.cjs +77 -232
- package/src/commands/stickers.cjs +100 -0
- package/src/commands/stopbot.cjs +5 -5
- package/src/commands/stt.cjs +1 -1
- package/src/commands/toimage.cjs +88 -0
- package/src/commands/tts.cjs +2 -2
- package/src/config/defaults.cjs +5 -0
- package/src/config/settings.cjs +10 -0
- package/src/core/events.js +15 -1
- package/src/core/session.js +7 -0
- package/src/db/db.cjs +381 -0
- package/src/db/store.cjs +729 -21
- package/src/handlers/command.handler.js +5 -1
- package/src/panel/password-reset.cjs +1 -1
- package/src/routes/dashboard.api.esm.js +43 -10
- package/src/routes/stickers.api.esm.js +570 -0
- package/src/services/aiAgent.cjs +2 -2
- package/src/services/aiProviders.cjs +1 -1
- package/src/services/aiTools.cjs +27 -27
- package/src/stickers/errors.cjs +239 -0
- package/src/stickers/ffmpeg.cjs +133 -0
- package/src/stickers/jobs.cjs +183 -0
- package/src/stickers/library.cjs +712 -0
- package/src/stickers/limits.cjs +60 -0
- package/src/stickers/media.cjs +748 -0
- package/src/stickers/options.cjs +128 -0
- package/src/stickers/owner.cjs +103 -0
- package/src/stickers/studio.cjs +473 -0
- package/src/stickers/uploads.cjs +263 -0
- package/src/stickers/webp.cjs +231 -0
- package/src/stickers/zip.cjs +107 -0
- package/src/utils/memory.cjs +7 -7
- package/src/utils/messageContent.cjs +30 -4
- package/src/utils/recurrence.cjs +189 -30
- package/src/utils/stickerBot.cjs +84 -0
- package/src/utils/storage.cjs +3 -0
- package/src/utils/storage.esm.js +3 -0
- package/views/login.ejs +39 -3
- package/views/setup.ejs +21 -0
- package/public/dashboard/assets/index-BCXZoPGP.js +0 -446
- package/public/dashboard/assets/index-LvfJ8ybs.css +0 -2
|
@@ -0,0 +1,748 @@
|
|
|
1
|
+
// One converter for panel and bot stickers. A bounded quality ladder keeps
|
|
2
|
+
// WhatsApp files small without needlessly warning about moderate compression.
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const path = require("node:path");
|
|
5
|
+
const { randomUUID } = require("node:crypto");
|
|
6
|
+
const { Readable } = require("node:stream");
|
|
7
|
+
const { setImmediate: nextTick } = require("node:timers/promises");
|
|
8
|
+
const { ensureDataDir } = require("../config/paths.cjs");
|
|
9
|
+
const { ffmpegPath, readImageMeta } = require("../utils/thumbnail.cjs");
|
|
10
|
+
const { StickerError } = require("./errors.cjs");
|
|
11
|
+
const L = require("./limits.cjs");
|
|
12
|
+
const { normalizeOptions, placement } = require("./options.cjs");
|
|
13
|
+
const webp = require("./webp.cjs");
|
|
14
|
+
const ffmpeg = require("./ffmpeg.cjs");
|
|
15
|
+
|
|
16
|
+
const PNG = Buffer.from("89504e470d0a1a0a", "hex");
|
|
17
|
+
const DEMUX = {
|
|
18
|
+
"image/png": "png_pipe",
|
|
19
|
+
"image/jpeg": "jpeg_pipe",
|
|
20
|
+
"image/gif": "gif",
|
|
21
|
+
"image/webp": "webp_pipe",
|
|
22
|
+
"video/mp4": "mov",
|
|
23
|
+
"video/quicktime": "mov",
|
|
24
|
+
"video/3gpp": "mov",
|
|
25
|
+
"video/webm": "matroska",
|
|
26
|
+
};
|
|
27
|
+
let cachedCapabilities;
|
|
28
|
+
let cachedFfmpegPath;
|
|
29
|
+
|
|
30
|
+
function sniff(buffer) {
|
|
31
|
+
if (!Buffer.isBuffer(buffer)) return null;
|
|
32
|
+
if (
|
|
33
|
+
buffer.length >= 24 &&
|
|
34
|
+
buffer.subarray(0, 8).equals(PNG) &&
|
|
35
|
+
buffer.toString("ascii", 12, 16) === "IHDR"
|
|
36
|
+
)
|
|
37
|
+
return { kind: "image", mime: "image/png", ext: "png" };
|
|
38
|
+
if (buffer.length >= 4 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff)
|
|
39
|
+
return { kind: "image", mime: "image/jpeg", ext: "jpg" };
|
|
40
|
+
if (buffer.length >= 10 && ["GIF87a", "GIF89a"].includes(buffer.toString("ascii", 0, 6)))
|
|
41
|
+
return { kind: "gif", mime: "image/gif", ext: "gif" };
|
|
42
|
+
if (
|
|
43
|
+
buffer.length >= 20 &&
|
|
44
|
+
buffer.toString("ascii", 0, 4) === "RIFF" &&
|
|
45
|
+
buffer.toString("ascii", 8, 12) === "WEBP"
|
|
46
|
+
)
|
|
47
|
+
return { kind: "webp", mime: "image/webp", ext: "webp" };
|
|
48
|
+
if (buffer.length >= 12 && buffer.toString("ascii", 4, 8) === "ftyp") {
|
|
49
|
+
const brands = buffer.toString("ascii", 8, Math.min(buffer.length, 32));
|
|
50
|
+
if (/^(qt {2})/.test(brands)) return { kind: "video", mime: "video/quicktime", ext: "mov" };
|
|
51
|
+
if (/^(3g[ep6789])/.test(brands)) return { kind: "video", mime: "video/3gpp", ext: "3gp" };
|
|
52
|
+
if (/^(isom|iso[23456]|mp4[12]|mp41|avc1|M4V |MSNV|dash)/.test(brands))
|
|
53
|
+
return { kind: "video", mime: "video/mp4", ext: "mp4" };
|
|
54
|
+
}
|
|
55
|
+
if (
|
|
56
|
+
buffer.length >= 16 &&
|
|
57
|
+
buffer.subarray(0, 4).equals(Buffer.from("1a45dfa3", "hex")) &&
|
|
58
|
+
/(?:webm|matroska)/i.test(buffer.toString("latin1", 0, Math.min(256, buffer.length)))
|
|
59
|
+
)
|
|
60
|
+
return { kind: "video", mime: "video/webm", ext: "webm" };
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function sourceArgs(sniffed, input) {
|
|
65
|
+
const demux = DEMUX[sniffed?.mime];
|
|
66
|
+
if (!demux) throw new StickerError("UNSUPPORTED_TYPE");
|
|
67
|
+
return ["-f", demux, "-protocol_whitelist", "file,pipe", "-i", input];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function dimensions(width, height) {
|
|
71
|
+
if (!width || !height) throw new StickerError("CORRUPT");
|
|
72
|
+
if (width > L.MAX_INPUT_SIDE || height > L.MAX_INPUT_SIDE || width * height > L.MAX_INPUT_PIXELS)
|
|
73
|
+
throw new StickerError("DIMENSIONS_TOO_LARGE", { limit: L.MAX_INPUT_SIDE });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function gifInfo(b) {
|
|
77
|
+
if (b.length < 13) throw new StickerError("CORRUPT");
|
|
78
|
+
let at = 13;
|
|
79
|
+
let frames = 0;
|
|
80
|
+
let durationMs = 0;
|
|
81
|
+
let delay = 100;
|
|
82
|
+
if (b[10] & 0x80) at += 3 * 2 ** ((b[10] & 7) + 1);
|
|
83
|
+
while (at < b.length) {
|
|
84
|
+
const type = b[at++];
|
|
85
|
+
if (type === 0x3b) break;
|
|
86
|
+
if (type === 0x21) {
|
|
87
|
+
const label = b[at++];
|
|
88
|
+
if (label === 0xf9 && b[at] === 4 && at + 5 < b.length)
|
|
89
|
+
delay = Math.max(20, b.readUInt16LE(at + 2) * 10);
|
|
90
|
+
while (at < b.length) {
|
|
91
|
+
const len = b[at++];
|
|
92
|
+
if (!len) break;
|
|
93
|
+
at += len;
|
|
94
|
+
}
|
|
95
|
+
} else if (type === 0x2c) {
|
|
96
|
+
if (at + 9 > b.length) throw new StickerError("CORRUPT");
|
|
97
|
+
const packed = b[at + 8];
|
|
98
|
+
at += 9;
|
|
99
|
+
if (packed & 0x80) at += 3 * 2 ** ((packed & 7) + 1);
|
|
100
|
+
at++;
|
|
101
|
+
while (at < b.length) {
|
|
102
|
+
const len = b[at++];
|
|
103
|
+
if (!len) break;
|
|
104
|
+
at += len;
|
|
105
|
+
}
|
|
106
|
+
frames++;
|
|
107
|
+
durationMs += delay;
|
|
108
|
+
delay = 100;
|
|
109
|
+
} else throw new StickerError("CORRUPT");
|
|
110
|
+
}
|
|
111
|
+
if (at > b.length || !frames) throw new StickerError("CORRUPT");
|
|
112
|
+
return { frames, durationMs };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function inspect(filePath, sniffed, maxSourceSeconds = L.VIDEO_MAX_SOURCE_SECONDS, signal) {
|
|
116
|
+
if (!sniffed || !DEMUX[sniffed.mime]) throw new StickerError("UNSUPPORTED_TYPE");
|
|
117
|
+
let b = null;
|
|
118
|
+
if (sniffed.kind !== "video") {
|
|
119
|
+
try {
|
|
120
|
+
const size = (await fs.promises.stat(filePath)).size;
|
|
121
|
+
if (size > L.UPLOAD_MAX_BYTES)
|
|
122
|
+
throw new StickerError("TOO_LARGE", { limitBytes: L.UPLOAD_MAX_BYTES });
|
|
123
|
+
b = await fs.promises.readFile(filePath, { signal });
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (error instanceof StickerError) throw error;
|
|
126
|
+
if (signal?.aborted) throw new StickerError("TIMEOUT", {}, { cause: error });
|
|
127
|
+
throw new StickerError("CORRUPT", {}, { cause: error });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
let width;
|
|
131
|
+
let height;
|
|
132
|
+
let durationMs = 0;
|
|
133
|
+
let frames = null;
|
|
134
|
+
let animated = false;
|
|
135
|
+
if (sniffed.kind === "webp") {
|
|
136
|
+
const meta = webp.parse(b);
|
|
137
|
+
({ width, height, durationMs, animated } = meta);
|
|
138
|
+
frames = meta.animated ? meta.frames.length : 1;
|
|
139
|
+
enforceAnimatedWebp(meta);
|
|
140
|
+
} else if (sniffed.kind === "video") {
|
|
141
|
+
let stderr;
|
|
142
|
+
try {
|
|
143
|
+
({ stderr } = await ffmpeg.run(
|
|
144
|
+
[...sourceArgs(sniffed, filePath), "-frames:v", "0", "-f", "image2pipe", "pipe:1"],
|
|
145
|
+
{ probe: true, maxOutputBytes: 1024, signal },
|
|
146
|
+
));
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (error.code === "TIMEOUT") throw error;
|
|
149
|
+
stderr = String(error.cause || "");
|
|
150
|
+
}
|
|
151
|
+
const d = /Stream #\d+:\d+[^\n]*Video:[^\n]*?,\s*(\d{1,5})x(\d{1,5})(?=\s|,)/.exec(stderr);
|
|
152
|
+
const t = /Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/.exec(stderr);
|
|
153
|
+
if (!d || !t) throw new StickerError("CORRUPT");
|
|
154
|
+
width = Number(d[1]);
|
|
155
|
+
height = Number(d[2]);
|
|
156
|
+
durationMs = Math.round((Number(t[1]) * 3600 + Number(t[2]) * 60 + Number(t[3])) * 1000);
|
|
157
|
+
animated = true;
|
|
158
|
+
} else {
|
|
159
|
+
const meta = readImageMeta(b);
|
|
160
|
+
width = meta?.width;
|
|
161
|
+
height = meta?.height;
|
|
162
|
+
if (sniffed.kind === "gif") {
|
|
163
|
+
const g = gifInfo(b);
|
|
164
|
+
frames = g.frames;
|
|
165
|
+
durationMs = g.durationMs;
|
|
166
|
+
animated = frames > 1;
|
|
167
|
+
// Reject oversized canvas headers before asking FFmpeg to parse the GIF.
|
|
168
|
+
dimensions(width, height);
|
|
169
|
+
let stderr;
|
|
170
|
+
try {
|
|
171
|
+
({ stderr } = await ffmpeg.run(
|
|
172
|
+
[...sourceArgs(sniffed, filePath), "-frames:v", "0", "-f", "image2pipe", "pipe:1"],
|
|
173
|
+
{ probe: true, maxOutputBytes: 1024, signal },
|
|
174
|
+
));
|
|
175
|
+
} catch (error) {
|
|
176
|
+
if (error.code === "TIMEOUT") throw error;
|
|
177
|
+
throw new StickerError("CORRUPT", {}, { cause: error });
|
|
178
|
+
}
|
|
179
|
+
const stream = /Stream #\d+:\d+[^\n]*Video:[^\n]*?,\s*(\d{1,5})x(\d{1,5})(?=\s|,)/.exec(
|
|
180
|
+
stderr,
|
|
181
|
+
);
|
|
182
|
+
if (!stream || Number(stream[1]) !== width || Number(stream[2]) !== height)
|
|
183
|
+
throw new StickerError("CORRUPT");
|
|
184
|
+
const time = /Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/.exec(stderr);
|
|
185
|
+
if (time)
|
|
186
|
+
durationMs = Math.round(
|
|
187
|
+
(Number(time[1]) * 3600 + Number(time[2]) * 60 + Number(time[3])) * 1000,
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
dimensions(width, height);
|
|
192
|
+
if (durationMs > maxSourceSeconds * 1000)
|
|
193
|
+
throw new StickerError("VIDEO_TOO_LONG", { limitSeconds: maxSourceSeconds });
|
|
194
|
+
return { kind: sniffed.kind, mime: sniffed.mime, width, height, durationMs, animated, frames };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function validateOverlay(buffer) {
|
|
198
|
+
if (buffer === undefined) return;
|
|
199
|
+
if (
|
|
200
|
+
!Buffer.isBuffer(buffer) ||
|
|
201
|
+
buffer.length > 2 * 1024 * 1024 ||
|
|
202
|
+
buffer.length < 24 ||
|
|
203
|
+
!buffer.subarray(0, 8).equals(PNG) ||
|
|
204
|
+
buffer.toString("ascii", 12, 16) !== "IHDR" ||
|
|
205
|
+
buffer.readUInt32BE(16) !== L.CANVAS ||
|
|
206
|
+
buffer.readUInt32BE(20) !== L.CANVAS
|
|
207
|
+
)
|
|
208
|
+
throw new StickerError("INVALID_OPTIONS", { field: "overlay" });
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Map the canvas window back into the rotated source before scaling. Lanczos
|
|
212
|
+
// needs a few source pixels outside the visible area, bounded by the maximum
|
|
213
|
+
// intermediate size even when a one-pixel edge is zoomed to the whole canvas.
|
|
214
|
+
function visibleSource(width, height, options, placed) {
|
|
215
|
+
const quarter = options.rotate === 90 || options.rotate === 270;
|
|
216
|
+
const sourceWidth = quarter ? height : width;
|
|
217
|
+
const sourceHeight = quarter ? width : height;
|
|
218
|
+
const cap = Math.floor(Math.min(L.CANVAS * 4, L.CANVAS * options.zoom + L.CANVAS / 2));
|
|
219
|
+
function axis(sourceSize, scaledSize, offset) {
|
|
220
|
+
const scale = scaledSize / sourceSize;
|
|
221
|
+
const first = Math.max(0, -offset);
|
|
222
|
+
const last = Math.min(L.CANVAS, offset + scaledSize) - offset;
|
|
223
|
+
const margin = Math.min(3, Math.floor((cap - L.CANVAS) / (2 * scale)));
|
|
224
|
+
const start = Math.max(0, Math.floor(first / scale) - margin);
|
|
225
|
+
const end = Math.min(sourceSize, Math.ceil(last / scale) + margin);
|
|
226
|
+
const natural =
|
|
227
|
+
start === 0 && end === sourceSize
|
|
228
|
+
? scaledSize
|
|
229
|
+
: Math.max(1, Math.round((end - start) * scale));
|
|
230
|
+
const bounded = Math.min(cap, natural);
|
|
231
|
+
const oldVisibleStart = first - start * scale;
|
|
232
|
+
const visibleFraction =
|
|
233
|
+
natural > L.CANVAS ? Math.max(0, Math.min(1, oldVisibleStart / (natural - L.CANVAS))) : 0;
|
|
234
|
+
return {
|
|
235
|
+
start,
|
|
236
|
+
size: Math.max(1, end - start),
|
|
237
|
+
scaled: bounded,
|
|
238
|
+
offset:
|
|
239
|
+
natural > cap
|
|
240
|
+
? -Math.round(visibleFraction * (bounded - L.CANVAS))
|
|
241
|
+
: offset + Math.round(start * scale),
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
const x = axis(sourceWidth, placed.width, placed.x);
|
|
245
|
+
const y = axis(sourceHeight, placed.height, placed.y);
|
|
246
|
+
return {
|
|
247
|
+
x: x.start,
|
|
248
|
+
y: y.start,
|
|
249
|
+
width: x.size,
|
|
250
|
+
height: y.size,
|
|
251
|
+
scaledWidth: x.scaled,
|
|
252
|
+
scaledHeight: y.scaled,
|
|
253
|
+
overlayX: x.offset,
|
|
254
|
+
overlayY: y.offset,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function filterGraph(
|
|
259
|
+
width,
|
|
260
|
+
height,
|
|
261
|
+
options,
|
|
262
|
+
{ overlay = false, fps = L.ANIMATED_FPS, keyColor = "0x000000" } = {},
|
|
263
|
+
) {
|
|
264
|
+
const o = normalizeOptions(options);
|
|
265
|
+
const p = placement(width, height, o);
|
|
266
|
+
const visible = visibleSource(width, height, o, p);
|
|
267
|
+
// placement() is the same 512-canvas geometry the panel preview uses.
|
|
268
|
+
const stages = ["[0:v]format=rgba"];
|
|
269
|
+
if (o.removeBackground) stages.push(`colorkey=${keyColor}:${o.removeBackground.tolerance}:0.05`);
|
|
270
|
+
if (o.rotate === 90) stages.push("transpose=clock");
|
|
271
|
+
else if (o.rotate === 270) stages.push("transpose=cclock");
|
|
272
|
+
else if (o.rotate === 180) stages.push("hflip,vflip");
|
|
273
|
+
stages.push(`crop=${visible.width}:${visible.height}:${visible.x}:${visible.y}`);
|
|
274
|
+
stages.push(`scale=${visible.scaledWidth}:${visible.scaledHeight}:flags=lanczos`);
|
|
275
|
+
const color = o.background === "transparent" ? "black@0.0" : `0x${o.background.slice(1)}`;
|
|
276
|
+
const parts = [
|
|
277
|
+
`${stages.join(",")}[scaled]`,
|
|
278
|
+
`color=c=${color}:s=512x512:r=${fps},format=rgba[bg]`,
|
|
279
|
+
`[bg][scaled]overlay=${visible.overlayX}:${visible.overlayY}:shortest=1:format=auto[base]`,
|
|
280
|
+
];
|
|
281
|
+
// The PNG is one frame; repeat it while the already bounded base stream runs.
|
|
282
|
+
if (overlay) parts.push("[base][1:v]overlay=0:0:eof_action=repeat:format=auto[out]");
|
|
283
|
+
else parts.push("[base]format=rgba[out]");
|
|
284
|
+
return { graph: parts.join(";"), placement: p, visible };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
async function capabilities() {
|
|
288
|
+
const binary = ffmpegPath();
|
|
289
|
+
if (cachedCapabilities && cachedFfmpegPath === binary) return cachedCapabilities;
|
|
290
|
+
let listing = "";
|
|
291
|
+
try {
|
|
292
|
+
listing = (
|
|
293
|
+
await ffmpeg.run(["-encoders"], { probe: true, maxOutputBytes: 1024 * 1024 })
|
|
294
|
+
).buffer.toString();
|
|
295
|
+
} catch {
|
|
296
|
+
/* missing binary */
|
|
297
|
+
}
|
|
298
|
+
const has = (name) => new RegExp(`\\b${name}\\b`).test(listing);
|
|
299
|
+
cachedFfmpegPath = binary;
|
|
300
|
+
cachedCapabilities = {
|
|
301
|
+
webp: has("libwebp"),
|
|
302
|
+
animated: has("libwebp_anim"),
|
|
303
|
+
gif: has("gif"),
|
|
304
|
+
mp4: has("mpeg4") || has("libx264"),
|
|
305
|
+
backgroundRemoval: ["plain"],
|
|
306
|
+
};
|
|
307
|
+
return cachedCapabilities;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function tempPath(ext) {
|
|
311
|
+
return path.join(ensureDataDir("tmp", "stickers"), `${randomUUID()}.${ext}`);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function sweepTemp(maxAgeMs) {
|
|
315
|
+
const dir = ensureDataDir("tmp", "stickers");
|
|
316
|
+
const now = Date.now();
|
|
317
|
+
for (const name of await fs.promises.readdir(dir)) {
|
|
318
|
+
const file = path.join(dir, name);
|
|
319
|
+
try {
|
|
320
|
+
if (now - (await fs.promises.stat(file)).mtimeMs > maxAgeMs)
|
|
321
|
+
await fs.promises.rm(file, { force: true });
|
|
322
|
+
} catch {
|
|
323
|
+
/* another job removed it */
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function describeWebp(buffer) {
|
|
329
|
+
const m = webp.parse(buffer);
|
|
330
|
+
enforceAnimatedWebp(m);
|
|
331
|
+
return {
|
|
332
|
+
width: m.width,
|
|
333
|
+
height: m.height,
|
|
334
|
+
animated: m.animated,
|
|
335
|
+
durationMs: m.durationMs,
|
|
336
|
+
frames: m.animated ? m.frames.length : 1,
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function enforceAnimatedWebp(meta) {
|
|
341
|
+
if (!meta.animated) return;
|
|
342
|
+
if (meta.width > L.EXISTING_MAX_SIDE || meta.height > L.EXISTING_MAX_SIDE) {
|
|
343
|
+
throw new StickerError("DIMENSIONS_TOO_LARGE", { limit: L.EXISTING_MAX_SIDE });
|
|
344
|
+
}
|
|
345
|
+
if (meta.frames.length > L.ANIMATED_MAX_FRAMES) {
|
|
346
|
+
throw new StickerError("TOO_LARGE", { limitFrames: L.ANIMATED_MAX_FRAMES });
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function withStickerMetadata(buffer, data) {
|
|
351
|
+
return webp.metadata(buffer, data);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function canonicalWebp(buffer) {
|
|
355
|
+
return webp.canonical(buffer);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function paint(canvas, pixels, frame, canvasWidth) {
|
|
359
|
+
const { x, y, width, height, blend } = frame;
|
|
360
|
+
for (let row = 0; row < height; row++) {
|
|
361
|
+
for (let col = 0; col < width; col++) {
|
|
362
|
+
const src = (row * width + col) * 4;
|
|
363
|
+
const dst = ((y + row) * canvasWidth + x + col) * 4;
|
|
364
|
+
const a = pixels[src + 3] / 255;
|
|
365
|
+
if (!blend || a === 1) {
|
|
366
|
+
pixels.copy(canvas, dst, src, src + 4);
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
if (a === 0) continue;
|
|
370
|
+
const da = canvas[dst + 3] / 255;
|
|
371
|
+
const out = a + da * (1 - a);
|
|
372
|
+
for (let c = 0; c < 3; c++) {
|
|
373
|
+
canvas[dst + c] = Math.round((pixels[src + c] * a + canvas[dst + c] * da * (1 - a)) / out);
|
|
374
|
+
}
|
|
375
|
+
canvas[dst + 3] = Math.round(out * 255);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function clearFrame(canvas, frame, canvasWidth) {
|
|
381
|
+
for (let row = 0; row < frame.height; row++) {
|
|
382
|
+
canvas.fill(
|
|
383
|
+
0,
|
|
384
|
+
((frame.y + row) * canvasWidth + frame.x) * 4,
|
|
385
|
+
((frame.y + row) * canvasWidth + frame.x + frame.width) * 4,
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
async function* webpFrames(buffer, { fps = L.ANIMATED_FPS, trim = null, signal } = {}) {
|
|
391
|
+
const meta = webp.parse(buffer);
|
|
392
|
+
enforceAnimatedWebp(meta);
|
|
393
|
+
if (!meta.animated) throw new StickerError("INVALID_OPTIONS");
|
|
394
|
+
const frames = meta.frames;
|
|
395
|
+
const canvas = Buffer.alloc(meta.width * meta.height * 4);
|
|
396
|
+
const start = (trim?.start || 0) * 1000;
|
|
397
|
+
const end = Math.min(meta.durationMs, start + (trim?.duration || L.STICKER_MAX_SECONDS) * 1000);
|
|
398
|
+
let cursor = 0;
|
|
399
|
+
let prior = null;
|
|
400
|
+
let elapsed = 0;
|
|
401
|
+
for (let t = start; t < end; t += 1000 / fps) {
|
|
402
|
+
if (signal?.aborted) throw new StickerError("TIMEOUT");
|
|
403
|
+
while (cursor < frames.length && elapsed <= t) {
|
|
404
|
+
// Disposal clears the previous rectangle before the next frame blends.
|
|
405
|
+
if (prior?.dispose) clearFrame(canvas, prior, meta.width);
|
|
406
|
+
const frame = frames[cursor];
|
|
407
|
+
const standalone = webp.extractFrame(buffer, cursor);
|
|
408
|
+
const decoded = await ffmpeg.run(
|
|
409
|
+
[
|
|
410
|
+
...sourceArgs({ mime: "image/webp" }, "pipe:0"),
|
|
411
|
+
"-frames:v",
|
|
412
|
+
"1",
|
|
413
|
+
"-pix_fmt",
|
|
414
|
+
"rgba",
|
|
415
|
+
"-f",
|
|
416
|
+
"rawvideo",
|
|
417
|
+
"pipe:1",
|
|
418
|
+
],
|
|
419
|
+
{ input: standalone, signal, maxOutputBytes: frame.width * frame.height * 4 + 1024 },
|
|
420
|
+
);
|
|
421
|
+
if (decoded.buffer.length !== frame.width * frame.height * 4)
|
|
422
|
+
throw new StickerError("CORRUPT");
|
|
423
|
+
paint(canvas, decoded.buffer, frame, meta.width);
|
|
424
|
+
prior = frame;
|
|
425
|
+
elapsed += Math.max(1, frame.durationMs);
|
|
426
|
+
cursor++;
|
|
427
|
+
await nextTick();
|
|
428
|
+
}
|
|
429
|
+
yield Buffer.from(canvas);
|
|
430
|
+
await nextTick();
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
async function renderAnimatedWebp(buffer, output, { signal, fps = L.ANIMATED_FPS, trim } = {}) {
|
|
435
|
+
const meta = webp.parse(buffer);
|
|
436
|
+
enforceAnimatedWebp(meta);
|
|
437
|
+
const frames = Readable.from(webpFrames(buffer, { signal, fps, trim }));
|
|
438
|
+
return ffmpeg.run(
|
|
439
|
+
[
|
|
440
|
+
"-f",
|
|
441
|
+
"rawvideo",
|
|
442
|
+
"-pixel_format",
|
|
443
|
+
"rgba",
|
|
444
|
+
"-video_size",
|
|
445
|
+
`${meta.width}x${meta.height}`,
|
|
446
|
+
"-framerate",
|
|
447
|
+
String(fps),
|
|
448
|
+
"-protocol_whitelist",
|
|
449
|
+
"file,pipe",
|
|
450
|
+
"-i",
|
|
451
|
+
"pipe:0",
|
|
452
|
+
...output,
|
|
453
|
+
],
|
|
454
|
+
{ input: frames, signal, maxOutputBytes: 32 * 1024 * 1024 },
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
async function sampleCorner(inputPath, sniffed, raw, signal) {
|
|
459
|
+
let result;
|
|
460
|
+
if (raw) {
|
|
461
|
+
result = await renderAnimatedWebp(
|
|
462
|
+
raw,
|
|
463
|
+
["-frames:v", "1", "-vf", "crop=1:1:0:0,format=rgb24", "-f", "rawvideo", "pipe:1"],
|
|
464
|
+
{ signal, fps: 1 },
|
|
465
|
+
);
|
|
466
|
+
} else {
|
|
467
|
+
result = await ffmpeg.run(
|
|
468
|
+
[
|
|
469
|
+
...sourceArgs(sniffed, inputPath),
|
|
470
|
+
"-frames:v",
|
|
471
|
+
"1",
|
|
472
|
+
"-vf",
|
|
473
|
+
"crop=1:1:0:0,format=rgb24",
|
|
474
|
+
"-f",
|
|
475
|
+
"rawvideo",
|
|
476
|
+
"pipe:1",
|
|
477
|
+
],
|
|
478
|
+
{ signal, maxOutputBytes: 16 },
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
if (result.buffer.length < 3) throw new StickerError("CORRUPT");
|
|
482
|
+
return `0x${result.buffer.subarray(0, 3).toString("hex")}`;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
async function createSticker({
|
|
486
|
+
inputPath,
|
|
487
|
+
sniffed,
|
|
488
|
+
options,
|
|
489
|
+
overlayPng,
|
|
490
|
+
maxSourceSeconds = L.VIDEO_MAX_SOURCE_SECONDS,
|
|
491
|
+
signal,
|
|
492
|
+
onProgress,
|
|
493
|
+
_maxBytes = L.STICKER_MAX_BYTES,
|
|
494
|
+
_targetBytes,
|
|
495
|
+
_qualitySteps,
|
|
496
|
+
}) {
|
|
497
|
+
const cap = await capabilities();
|
|
498
|
+
if (!cap.webp) throw new StickerError("ENCODER_MISSING");
|
|
499
|
+
validateOverlay(overlayPng);
|
|
500
|
+
onProgress?.("probing", 0);
|
|
501
|
+
const info = await inspect(inputPath, sniffed, maxSourceSeconds, signal);
|
|
502
|
+
const o = normalizeOptions(options);
|
|
503
|
+
const animated = info.animated;
|
|
504
|
+
if (animated && !cap.animated) throw new StickerError("ENCODER_MISSING");
|
|
505
|
+
const durationMs = animated
|
|
506
|
+
? Math.min(
|
|
507
|
+
info.durationMs - (o.trim?.start || 0) * 1000,
|
|
508
|
+
(o.trim?.duration || L.STICKER_MAX_SECONDS) * 1000,
|
|
509
|
+
)
|
|
510
|
+
: 0;
|
|
511
|
+
if (animated && durationMs <= 0) throw new StickerError("INVALID_OPTIONS", { field: "trim" });
|
|
512
|
+
let raw = null;
|
|
513
|
+
if (sniffed.kind === "webp" && animated) {
|
|
514
|
+
try {
|
|
515
|
+
raw = await fs.promises.readFile(inputPath, { signal });
|
|
516
|
+
} catch (error) {
|
|
517
|
+
if (signal?.aborted) throw new StickerError("TIMEOUT", {}, { cause: error });
|
|
518
|
+
throw new StickerError("CORRUPT", {}, { cause: error });
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
const temp = [];
|
|
522
|
+
try {
|
|
523
|
+
let overlayPath;
|
|
524
|
+
if (overlayPng) {
|
|
525
|
+
overlayPath = tempPath("png");
|
|
526
|
+
temp.push(overlayPath);
|
|
527
|
+
await fs.promises.writeFile(overlayPath, overlayPng);
|
|
528
|
+
}
|
|
529
|
+
let best = null;
|
|
530
|
+
let reduced = false;
|
|
531
|
+
let bestQuality = null;
|
|
532
|
+
let bestFps = null;
|
|
533
|
+
const keyColor = o.removeBackground
|
|
534
|
+
? await sampleCorner(inputPath, sniffed, raw, signal)
|
|
535
|
+
: "0x000000";
|
|
536
|
+
// Moderate compression is routine; warn only below the visible-quality thresholds.
|
|
537
|
+
const steps =
|
|
538
|
+
_qualitySteps ??
|
|
539
|
+
(animated
|
|
540
|
+
? [
|
|
541
|
+
[90, 15],
|
|
542
|
+
[75, 15],
|
|
543
|
+
[60, 12],
|
|
544
|
+
[45, 10],
|
|
545
|
+
[30, 8],
|
|
546
|
+
]
|
|
547
|
+
: [
|
|
548
|
+
[95, 1],
|
|
549
|
+
[80, 1],
|
|
550
|
+
[65, 1],
|
|
551
|
+
[45, 1],
|
|
552
|
+
[25, 1],
|
|
553
|
+
]);
|
|
554
|
+
for (let step = 0; step < steps.length; step++) {
|
|
555
|
+
if (signal?.aborted) throw new StickerError("TIMEOUT");
|
|
556
|
+
const [quality, fps] = steps[step];
|
|
557
|
+
onProgress?.("decoding", step / steps.length);
|
|
558
|
+
const inputDims = [info.width, info.height];
|
|
559
|
+
const { graph } = filterGraph(...inputDims, o, { overlay: !!overlayPath, fps, keyColor });
|
|
560
|
+
const args = [];
|
|
561
|
+
if (!raw && o.trim?.start) args.push("-ss", String(o.trim.start));
|
|
562
|
+
if (!raw) args.push(...sourceArgs(sniffed, inputPath));
|
|
563
|
+
if (overlayPath) args.push(...sourceArgs({ mime: "image/png" }, overlayPath));
|
|
564
|
+
args.push("-filter_complex", graph, "-map", "[out]");
|
|
565
|
+
if (animated) {
|
|
566
|
+
args.push(
|
|
567
|
+
"-t",
|
|
568
|
+
String(Math.min(durationMs / 1000, L.STICKER_MAX_SECONDS)),
|
|
569
|
+
"-r",
|
|
570
|
+
String(fps),
|
|
571
|
+
"-an",
|
|
572
|
+
"-c:v",
|
|
573
|
+
"libwebp_anim",
|
|
574
|
+
"-quality",
|
|
575
|
+
String(quality),
|
|
576
|
+
"-loop",
|
|
577
|
+
"0",
|
|
578
|
+
);
|
|
579
|
+
} else {
|
|
580
|
+
args.push("-frames:v", "1", "-c:v", "libwebp", "-quality", String(quality));
|
|
581
|
+
}
|
|
582
|
+
args.push("-f", "webp", "pipe:1");
|
|
583
|
+
onProgress?.("encoding", step / steps.length);
|
|
584
|
+
const encoded = raw
|
|
585
|
+
? await renderAnimatedWebp(raw, args, { signal, fps, trim: o.trim })
|
|
586
|
+
: await ffmpeg.run(args, { signal, maxOutputBytes: 16 * 1024 * 1024 });
|
|
587
|
+
const bytes = encoded.buffer;
|
|
588
|
+
onProgress?.("optimizing", (step + 1) / steps.length);
|
|
589
|
+
if (!best || bytes.length < best.length) {
|
|
590
|
+
best = bytes;
|
|
591
|
+
bestQuality = quality;
|
|
592
|
+
bestFps = fps;
|
|
593
|
+
}
|
|
594
|
+
if (
|
|
595
|
+
bytes.length <=
|
|
596
|
+
(_targetBytes ?? (animated ? L.ANIMATED_TARGET_BYTES : L.STATIC_TARGET_BYTES))
|
|
597
|
+
) {
|
|
598
|
+
best = bytes;
|
|
599
|
+
bestQuality = quality;
|
|
600
|
+
bestFps = fps;
|
|
601
|
+
break;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
reduced = animated ? bestQuality < 60 || bestFps < L.ANIMATED_FPS : bestQuality < 65;
|
|
605
|
+
if (!best || best.length > Math.min(_maxBytes, L.STICKER_MAX_BYTES))
|
|
606
|
+
throw new StickerError("OUTPUT_TOO_LARGE");
|
|
607
|
+
return {
|
|
608
|
+
buffer: best,
|
|
609
|
+
width: L.CANVAS,
|
|
610
|
+
height: L.CANVAS,
|
|
611
|
+
animated,
|
|
612
|
+
durationMs,
|
|
613
|
+
sourceMime: sniffed.mime,
|
|
614
|
+
qualityReduced: reduced,
|
|
615
|
+
};
|
|
616
|
+
} finally {
|
|
617
|
+
await Promise.all(temp.map((file) => fs.promises.rm(file, { force: true })));
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
async function toPng(buffer, { signal } = {}) {
|
|
622
|
+
const meta = webp.parse(buffer);
|
|
623
|
+
let result;
|
|
624
|
+
if (meta.animated) {
|
|
625
|
+
result = await renderAnimatedWebp(
|
|
626
|
+
buffer,
|
|
627
|
+
["-frames:v", "1", "-c:v", "png", "-f", "image2pipe", "pipe:1"],
|
|
628
|
+
{ signal, fps: 1, trim: { start: 0, duration: 1 } },
|
|
629
|
+
);
|
|
630
|
+
} else {
|
|
631
|
+
result = await ffmpeg.run(
|
|
632
|
+
[
|
|
633
|
+
...sourceArgs({ mime: "image/webp" }, "pipe:0"),
|
|
634
|
+
"-frames:v",
|
|
635
|
+
"1",
|
|
636
|
+
"-c:v",
|
|
637
|
+
"png",
|
|
638
|
+
"-f",
|
|
639
|
+
"image2pipe",
|
|
640
|
+
"pipe:1",
|
|
641
|
+
],
|
|
642
|
+
{ input: buffer, signal },
|
|
643
|
+
);
|
|
644
|
+
}
|
|
645
|
+
return { buffer: result.buffer, animated: meta.animated };
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
async function toGif(buffer, { signal } = {}) {
|
|
649
|
+
const meta = webp.parse(buffer);
|
|
650
|
+
if (!meta.animated) throw new StickerError("INVALID_OPTIONS", { field: "format" });
|
|
651
|
+
return (
|
|
652
|
+
await renderAnimatedWebp(
|
|
653
|
+
buffer,
|
|
654
|
+
[
|
|
655
|
+
"-t",
|
|
656
|
+
String(Math.min(10, meta.durationMs / 1000)),
|
|
657
|
+
"-filter_complex",
|
|
658
|
+
"[0:v]split[image][colors];[colors]palettegen=reserve_transparent=1:stats_mode=full[palette];[image][palette]paletteuse=alpha_threshold=128[out]",
|
|
659
|
+
"-map",
|
|
660
|
+
"[out]",
|
|
661
|
+
"-c:v",
|
|
662
|
+
"gif",
|
|
663
|
+
"-f",
|
|
664
|
+
"gif",
|
|
665
|
+
"pipe:1",
|
|
666
|
+
],
|
|
667
|
+
{ signal },
|
|
668
|
+
)
|
|
669
|
+
).buffer;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
async function toMp4(buffer, { signal } = {}) {
|
|
673
|
+
const meta = webp.parse(buffer);
|
|
674
|
+
if (!meta.animated) throw new StickerError("INVALID_OPTIONS", { field: "format" });
|
|
675
|
+
const videoWidth = Math.ceil(meta.width / 2) * 2;
|
|
676
|
+
const videoHeight = Math.ceil(meta.height / 2) * 2;
|
|
677
|
+
const file = tempPath("mp4");
|
|
678
|
+
try {
|
|
679
|
+
for (const encoder of ["libx264", "mpeg4"]) {
|
|
680
|
+
try {
|
|
681
|
+
await renderAnimatedWebp(
|
|
682
|
+
buffer,
|
|
683
|
+
[
|
|
684
|
+
"-t",
|
|
685
|
+
String(Math.min(10, meta.durationMs / 1000)),
|
|
686
|
+
"-filter_complex",
|
|
687
|
+
`color=c=white:s=${videoWidth}x${videoHeight}:r=15[white];[white][0:v]overlay=0:0:shortest=1:format=auto,format=yuv420p[out]`,
|
|
688
|
+
"-map",
|
|
689
|
+
"[out]",
|
|
690
|
+
"-c:v",
|
|
691
|
+
encoder,
|
|
692
|
+
"-movflags",
|
|
693
|
+
"+faststart",
|
|
694
|
+
"-f",
|
|
695
|
+
"mp4",
|
|
696
|
+
"-y",
|
|
697
|
+
file,
|
|
698
|
+
],
|
|
699
|
+
{ signal, fps: L.ANIMATED_FPS },
|
|
700
|
+
);
|
|
701
|
+
return await fs.promises.readFile(file);
|
|
702
|
+
} catch (error) {
|
|
703
|
+
if (encoder === "mpeg4" || error.code === "TIMEOUT") throw error;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
} finally {
|
|
707
|
+
await fs.promises.rm(file, { force: true });
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
async function makeThumbnail(buffer, { signal } = {}) {
|
|
712
|
+
const png = await toPng(buffer, { signal });
|
|
713
|
+
return (
|
|
714
|
+
await ffmpeg.run(
|
|
715
|
+
[
|
|
716
|
+
...sourceArgs({ mime: "image/png" }, "pipe:0"),
|
|
717
|
+
"-vf",
|
|
718
|
+
`scale=${L.THUMB_SIZE}:${L.THUMB_SIZE}:force_original_aspect_ratio=decrease,pad=${L.THUMB_SIZE}:${L.THUMB_SIZE}:(ow-iw)/2:(oh-ih)/2:color=0x00000000`,
|
|
719
|
+
"-frames:v",
|
|
720
|
+
"1",
|
|
721
|
+
"-c:v",
|
|
722
|
+
"libwebp",
|
|
723
|
+
"-f",
|
|
724
|
+
"webp",
|
|
725
|
+
"pipe:1",
|
|
726
|
+
],
|
|
727
|
+
{ input: png.buffer, signal },
|
|
728
|
+
)
|
|
729
|
+
).buffer;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
module.exports = {
|
|
733
|
+
sniff,
|
|
734
|
+
inspect,
|
|
735
|
+
createSticker,
|
|
736
|
+
toPng,
|
|
737
|
+
toGif,
|
|
738
|
+
toMp4,
|
|
739
|
+
makeThumbnail,
|
|
740
|
+
describeWebp,
|
|
741
|
+
withStickerMetadata,
|
|
742
|
+
canonicalWebp,
|
|
743
|
+
capabilities,
|
|
744
|
+
sweepTemp,
|
|
745
|
+
filterGraph,
|
|
746
|
+
validateOverlay,
|
|
747
|
+
compositeWebpFrames: webpFrames,
|
|
748
|
+
};
|