levix-bot 4.3.1 → 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.
Files changed (43) hide show
  1. package/README.md +1 -0
  2. package/package.json +1 -1
  3. package/public/dashboard/assets/index-5P8GnKLg.css +2 -0
  4. package/public/dashboard/assets/index-DXzno3X6.js +515 -0
  5. package/public/dashboard/index.html +2 -2
  6. package/public/dashboard.css +32 -0
  7. package/src/bootstrap/panel.js +16 -4
  8. package/src/commands/pack.cjs +159 -0
  9. package/src/commands/packs.cjs +47 -0
  10. package/src/commands/send.cjs +1 -18
  11. package/src/commands/sticker.cjs +77 -232
  12. package/src/commands/stickers.cjs +100 -0
  13. package/src/commands/toimage.cjs +88 -0
  14. package/src/config/defaults.cjs +5 -0
  15. package/src/config/settings.cjs +10 -0
  16. package/src/core/events.js +15 -1
  17. package/src/core/session.js +7 -0
  18. package/src/db/db.cjs +381 -0
  19. package/src/db/store.cjs +729 -21
  20. package/src/handlers/command.handler.js +4 -0
  21. package/src/routes/dashboard.api.esm.js +43 -10
  22. package/src/routes/stickers.api.esm.js +570 -0
  23. package/src/stickers/errors.cjs +239 -0
  24. package/src/stickers/ffmpeg.cjs +133 -0
  25. package/src/stickers/jobs.cjs +183 -0
  26. package/src/stickers/library.cjs +712 -0
  27. package/src/stickers/limits.cjs +60 -0
  28. package/src/stickers/media.cjs +748 -0
  29. package/src/stickers/options.cjs +128 -0
  30. package/src/stickers/owner.cjs +103 -0
  31. package/src/stickers/studio.cjs +473 -0
  32. package/src/stickers/uploads.cjs +263 -0
  33. package/src/stickers/webp.cjs +231 -0
  34. package/src/stickers/zip.cjs +107 -0
  35. package/src/utils/messageContent.cjs +30 -4
  36. package/src/utils/recurrence.cjs +189 -30
  37. package/src/utils/stickerBot.cjs +84 -0
  38. package/src/utils/storage.cjs +3 -0
  39. package/src/utils/storage.esm.js +3 -0
  40. package/views/login.ejs +39 -3
  41. package/views/setup.ejs +21 -0
  42. package/public/dashboard/assets/index-B6RhYFIy.js +0 -446
  43. package/public/dashboard/assets/index-vEwOcxiH.css +0 -2
@@ -0,0 +1,263 @@
1
+ // Panel uploads land as raw bytes in <data>/tmp/stickers and stay there until
2
+ // a conversion job reads them or the TTL sweep deletes them. The size cap is
3
+ // applied to each chunk before it is written, so a huge body never becomes a
4
+ // finished file that we then reject.
5
+ //
6
+ // media.cjs is required only when a file is accepted. It is written by the
7
+ // media agent and is not present in every worktree; boot only needs sweepStale.
8
+
9
+ const crypto = require("node:crypto");
10
+ const fs = require("node:fs");
11
+ const path = require("node:path");
12
+
13
+ const { dataPath, ensureDataDir } = require("../config/paths.cjs");
14
+ const logger = require("../utils/logger.cjs");
15
+ const { StickerError } = require("./errors.cjs");
16
+ const { UPLOAD_MAX_BYTES, UPLOAD_TTL_MS } = require("./limits.cjs");
17
+
18
+ const SWEEP_MS = 15 * 60 * 1000;
19
+ const SNIFF_BYTES = 512;
20
+
21
+ /** @type {Map<string, object>} */
22
+ const uploads = new Map();
23
+ let mediaOverride = null;
24
+
25
+ function tmpDir() {
26
+ return ensureDataDir("tmp", "stickers");
27
+ }
28
+
29
+ function loadMedia(explicit) {
30
+ if (explicit) return explicit;
31
+ if (mediaOverride) return mediaOverride;
32
+ return require("./media.cjs");
33
+ }
34
+
35
+ function setMedia(mod) {
36
+ mediaOverride = mod || null;
37
+ }
38
+
39
+ function storageError(error) {
40
+ if (error?.code === "EACCES" || error?.code === "ENOSPC" || error?.code === "EROFS") {
41
+ return new StickerError("STORAGE_UNAVAILABLE", {}, { cause: error });
42
+ }
43
+ return error;
44
+ }
45
+
46
+ function safeName(filename) {
47
+ if (!filename) return "";
48
+ const text = String(filename)
49
+ .replace(/\p{Cc}/gu, "")
50
+ .trim();
51
+ return [...text].slice(0, 120).join("");
52
+ }
53
+
54
+ function publicRecord(record) {
55
+ return {
56
+ uploadId: record.id,
57
+ kind: record.kind,
58
+ mime: record.mime,
59
+ width: record.width,
60
+ height: record.height,
61
+ durationMs: record.durationMs,
62
+ animated: !!record.animated,
63
+ size: record.size,
64
+ };
65
+ }
66
+
67
+ function sameOwner(record, owner) {
68
+ return Boolean(owner?.key) && record.ownerKey === owner.key;
69
+ }
70
+
71
+ function sweepStale(now = Date.now()) {
72
+ const dir = dataPath("tmp", "stickers");
73
+ let names = [];
74
+ try {
75
+ names = fs.readdirSync(dir);
76
+ } catch {
77
+ names = [];
78
+ }
79
+ for (const name of names) {
80
+ const file = path.join(dir, name);
81
+ let stat;
82
+ try {
83
+ stat = fs.statSync(file);
84
+ } catch {
85
+ continue;
86
+ }
87
+ if (!stat.isFile()) continue;
88
+ if (now - stat.mtimeMs < UPLOAD_TTL_MS) continue;
89
+ try {
90
+ fs.rmSync(file, { force: true });
91
+ } catch (error) {
92
+ logger.warn({ err: error }, "[Stickers] failed to sweep a stale temp file");
93
+ }
94
+ }
95
+ for (const [id, record] of uploads) {
96
+ if (now - record.createdAt >= UPLOAD_TTL_MS || !fs.existsSync(record.path)) {
97
+ uploads.delete(id);
98
+ try {
99
+ fs.rmSync(record.path, { force: true });
100
+ } catch {
101
+ // Already gone, or busy. The next sweep tries again.
102
+ }
103
+ }
104
+ }
105
+ }
106
+
107
+ function discardAll() {
108
+ for (const record of uploads.values()) {
109
+ try {
110
+ fs.rmSync(record.path, { force: true });
111
+ } catch {
112
+ // Unlink must still forget the id.
113
+ }
114
+ }
115
+ uploads.clear();
116
+ try {
117
+ fs.rmSync(dataPath("tmp", "stickers"), { recursive: true, force: true });
118
+ } catch (error) {
119
+ logger.warn({ err: error }, "[Stickers] failed to remove the sticker temp directory");
120
+ }
121
+ }
122
+
123
+ function sniffFile(file, media) {
124
+ const fd = fs.openSync(file, "r");
125
+ try {
126
+ const buf = Buffer.alloc(SNIFF_BYTES);
127
+ const n = fs.readSync(fd, buf, 0, SNIFF_BYTES, 0);
128
+ return media.sniff(buf.subarray(0, n));
129
+ } finally {
130
+ fs.closeSync(fd);
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Stream `stream` to disk for `owner`. Resolves the public record (no path).
136
+ * @param {{ key: string }} owner
137
+ * @param {import("node:stream").Readable} stream
138
+ */
139
+ function acceptStream(owner, stream, { filename, media } = {}) {
140
+ if (!owner?.key) return Promise.reject(new StickerError("INVALID_OPTIONS", { field: "owner" }));
141
+ const declared = Number(stream.headers?.["content-length"]);
142
+ if (Number.isFinite(declared) && declared > UPLOAD_MAX_BYTES) {
143
+ return Promise.reject(new StickerError("TOO_LARGE", { limitBytes: UPLOAD_MAX_BYTES }));
144
+ }
145
+ const med = loadMedia(media);
146
+ const id = crypto.randomBytes(16).toString("hex");
147
+ const file = path.join(tmpDir(), `upload-${id}`);
148
+ return new Promise((resolve, reject) => {
149
+ let size = 0;
150
+ let settled = false;
151
+ let ended = false;
152
+ const out = fs.createWriteStream(file);
153
+ const fail = (error) => {
154
+ if (settled) return;
155
+ settled = true;
156
+ stream.pause();
157
+ stream.removeAllListeners("data");
158
+ stream.removeAllListeners("end");
159
+ stream.removeAllListeners("error");
160
+ stream.removeAllListeners("aborted");
161
+ stream.removeAllListeners("close");
162
+ const cleanup = () => fs.rm(file, { force: true }, () => reject(error));
163
+ if (out.closed) cleanup();
164
+ else {
165
+ out.once("close", cleanup);
166
+ out.destroy();
167
+ }
168
+ };
169
+
170
+ stream.on("data", (chunk) => {
171
+ if (settled) return;
172
+ if (size + chunk.length > UPLOAD_MAX_BYTES) {
173
+ stream.pause();
174
+ fail(new StickerError("TOO_LARGE", { limitBytes: UPLOAD_MAX_BYTES }));
175
+ return;
176
+ }
177
+ size += chunk.length;
178
+ if (!out.write(chunk)) stream.pause();
179
+ });
180
+ out.on("drain", () => {
181
+ if (!settled) stream.resume();
182
+ });
183
+ stream.on("error", (error) => fail(error));
184
+ stream.on("aborted", () => fail(new StickerError("CANCELLED")));
185
+ stream.on("close", () => {
186
+ if (!ended) fail(new StickerError("CANCELLED"));
187
+ });
188
+ out.on("error", (error) => fail(storageError(error)));
189
+ stream.on("end", () => {
190
+ ended = true;
191
+ if (settled) return;
192
+ out.end(() => {
193
+ if (settled) return;
194
+ if (size === 0) {
195
+ fail(new StickerError("NO_MEDIA"));
196
+ return;
197
+ }
198
+ let sniffed;
199
+ try {
200
+ sniffed = sniffFile(file, med);
201
+ } catch (error) {
202
+ fail(error);
203
+ return;
204
+ }
205
+ if (!sniffed) {
206
+ fail(new StickerError("UNSUPPORTED_TYPE"));
207
+ return;
208
+ }
209
+ Promise.resolve(med.inspect(file, sniffed))
210
+ .then((info) => {
211
+ if (settled) return;
212
+ settled = true;
213
+ const record = {
214
+ id,
215
+ ownerKey: owner.key,
216
+ path: file,
217
+ filename: safeName(filename),
218
+ kind: info.kind,
219
+ mime: info.mime,
220
+ width: info.width ?? null,
221
+ height: info.height ?? null,
222
+ durationMs: info.durationMs ?? null,
223
+ animated: !!info.animated,
224
+ size,
225
+ createdAt: Date.now(),
226
+ };
227
+ uploads.set(id, record);
228
+ resolve(publicRecord(record));
229
+ })
230
+ .catch((error) => fail(error));
231
+ });
232
+ });
233
+ });
234
+ }
235
+
236
+ /** The stored upload, or null when it is missing, expired, or not this owner's. */
237
+ function get(owner, id) {
238
+ const record = uploads.get(id);
239
+ if (!record || !sameOwner(record, owner)) return null;
240
+ if (!fs.existsSync(record.path)) {
241
+ uploads.delete(id);
242
+ return null;
243
+ }
244
+ return record;
245
+ }
246
+
247
+ sweepStale();
248
+ const sweepTimer = setInterval(() => {
249
+ try {
250
+ sweepStale();
251
+ } catch (error) {
252
+ logger.warn({ err: error }, "[Stickers] upload sweep failed");
253
+ }
254
+ }, SWEEP_MS);
255
+ sweepTimer.unref();
256
+
257
+ module.exports = {
258
+ acceptStream,
259
+ get,
260
+ sweepStale,
261
+ discardAll,
262
+ setMedia,
263
+ };
@@ -0,0 +1,231 @@
1
+ // RIFF/WebP parsing and metadata stay in Buffer code. FFmpeg 7 skips ANMF,
2
+ // so the converter extracts each animated frame as a static WebP for decoding.
3
+ const { createHash } = require("node:crypto");
4
+ const { StickerError } = require("./errors.cjs");
5
+ const { ANIMATED_MAX_FRAMES } = require("./limits.cjs");
6
+ const MAX_CHUNKS = ANIMATED_MAX_FRAMES + 32;
7
+ const MAX_FRAME_PARTS = 8;
8
+
9
+ function corrupt() {
10
+ throw new StickerError("CORRUPT");
11
+ }
12
+
13
+ function chunk(type, payload) {
14
+ const out = Buffer.alloc(8 + payload.length + (payload.length & 1));
15
+ out.write(type, 0, 4, "ascii");
16
+ out.writeUInt32LE(payload.length, 4);
17
+ payload.copy(out, 8);
18
+ return out;
19
+ }
20
+
21
+ function riff(chunks) {
22
+ const size = chunks.reduce((n, item) => n + item.length, 4);
23
+ const out = Buffer.alloc(8);
24
+ out.write("RIFF", 0);
25
+ out.writeUInt32LE(size, 4);
26
+ return Buffer.concat([out, Buffer.from("WEBP"), ...chunks]);
27
+ }
28
+
29
+ function parse(buffer) {
30
+ const riffEnd = Buffer.isBuffer(buffer) && buffer.length >= 8 ? buffer.readUInt32LE(4) + 8 : 0;
31
+ if (
32
+ !Buffer.isBuffer(buffer) ||
33
+ buffer.length < 20 ||
34
+ buffer.toString("ascii", 0, 4) !== "RIFF" ||
35
+ buffer.toString("ascii", 8, 12) !== "WEBP" ||
36
+ riffEnd < 20 ||
37
+ riffEnd > buffer.length
38
+ ) {
39
+ corrupt();
40
+ }
41
+ const chunks = [];
42
+ for (let at = 12; at < riffEnd; ) {
43
+ if (chunks.length >= MAX_CHUNKS) corrupt();
44
+ if (at + 8 > riffEnd) corrupt();
45
+ const type = buffer.toString("ascii", at, at + 4);
46
+ const len = buffer.readUInt32LE(at + 4);
47
+ const end = at + 8 + len;
48
+ if (end > riffEnd || end + (len & 1) > riffEnd) corrupt();
49
+ chunks.push({
50
+ type,
51
+ data: buffer.subarray(at + 8, end),
52
+ raw: buffer.subarray(at, end + (len & 1)),
53
+ });
54
+ at = end + (len & 1);
55
+ }
56
+ let width = 0;
57
+ let height = 0;
58
+ let alpha = false;
59
+ let animated = false;
60
+ let loopCount = 0;
61
+ const frames = [];
62
+ const first = chunks[0];
63
+ if (!first) corrupt();
64
+ if (first.type === "VP8X") {
65
+ if (first.data.length !== 10) corrupt();
66
+ // VP8X stores alpha in bit 4 and animation in bit 1.
67
+ const flags = first.data[0];
68
+ alpha = !!(flags & 0x10);
69
+ animated = !!(flags & 0x02);
70
+ width = first.data.readUIntLE(4, 3) + 1;
71
+ height = first.data.readUIntLE(7, 3) + 1;
72
+ } else if (first.type === "VP8 ") {
73
+ if (
74
+ first.data.length < 10 ||
75
+ first.data[3] !== 0x9d ||
76
+ first.data[4] !== 0x01 ||
77
+ first.data[5] !== 0x2a
78
+ ) {
79
+ corrupt();
80
+ }
81
+ width = first.data.readUInt16LE(6) & 0x3fff;
82
+ height = first.data.readUInt16LE(8) & 0x3fff;
83
+ } else if (first.type === "VP8L") {
84
+ if (first.data.length < 5 || first.data[0] !== 0x2f) corrupt();
85
+ const bits = first.data.readUInt32LE(1);
86
+ width = (bits & 0x3fff) + 1;
87
+ height = ((bits >>> 14) & 0x3fff) + 1;
88
+ alpha = !!(bits & 0x10000000);
89
+ } else corrupt();
90
+ if (!width || !height) corrupt();
91
+ const anim = chunks.find((c) => c.type === "ANIM");
92
+ if (animated) {
93
+ if (anim?.data.length !== 6) corrupt();
94
+ loopCount = anim.data.readUInt16LE(4);
95
+ for (const c of chunks.filter((item) => item.type === "ANMF")) {
96
+ const d = c.data;
97
+ if (d.length < 24) corrupt();
98
+ // ANMF positions are half-pixel units; width and height are minus one.
99
+ const x = d.readUIntLE(0, 3) * 2;
100
+ const y = d.readUIntLE(3, 3) * 2;
101
+ const w = d.readUIntLE(6, 3) + 1;
102
+ const h = d.readUIntLE(9, 3) + 1;
103
+ if (x + w > width || y + h > height) corrupt();
104
+ const parts = [];
105
+ for (let at = 16; at < d.length; ) {
106
+ if (parts.length >= MAX_FRAME_PARTS) corrupt();
107
+ if (at + 8 > d.length) corrupt();
108
+ const len = d.readUInt32LE(at + 4);
109
+ const end = at + 8 + len;
110
+ if (end + (len & 1) > d.length) corrupt();
111
+ parts.push({ type: d.toString("ascii", at, at + 4), raw: d.subarray(at, end + (len & 1)) });
112
+ at = end + (len & 1);
113
+ }
114
+ if (!parts.some((p) => p.type === "VP8 " || p.type === "VP8L")) corrupt();
115
+ frames.push({
116
+ x,
117
+ y,
118
+ width: w,
119
+ height: h,
120
+ durationMs: d.readUIntLE(12, 3),
121
+ blend: !(d[15] & 2),
122
+ dispose: !!(d[15] & 1),
123
+ parts,
124
+ });
125
+ }
126
+ if (!frames.length) corrupt();
127
+ } else if (!chunks.some((c) => c.type === "VP8 " || c.type === "VP8L")) corrupt();
128
+ return {
129
+ width,
130
+ height,
131
+ alpha,
132
+ animated,
133
+ loopCount,
134
+ frames,
135
+ chunks,
136
+ durationMs: frames.reduce((n, f) => n + f.durationMs, 0),
137
+ };
138
+ }
139
+
140
+ function extractFrame(buffer, index) {
141
+ const meta = parse(buffer);
142
+ const frame = meta.frames[index];
143
+ if (!frame) corrupt();
144
+ const payload = Buffer.alloc(10);
145
+ payload[0] = frame.parts.some((p) => p.type === "ALPH" || p.type === "VP8L") ? 0x10 : 0;
146
+ payload.writeUIntLE(frame.width - 1, 4, 3);
147
+ payload.writeUIntLE(frame.height - 1, 7, 3);
148
+ return riff([chunk("VP8X", payload), ...frame.parts.map((p) => p.raw)]);
149
+ }
150
+
151
+ // Pack metadata belongs to the send, not the saved content. Rebuild the RIFF
152
+ // after dropping both metadata chunks, including the extension flags that
153
+ // announce them. A simple image tagged for WhatsApp becomes simple again.
154
+ function canonical(buffer) {
155
+ const meta = parse(buffer);
156
+ const remaining = meta.chunks.filter((item) => item.type !== "EXIF" && item.type !== "XMP ");
157
+ if (remaining[0]?.type !== "VP8X") return riff(remaining.map((item) => item.raw));
158
+ const needsExtended = remaining.some((item) =>
159
+ ["ALPH", "ANIM", "ANMF", "ICCP"].includes(item.type),
160
+ );
161
+ const payload = Buffer.from(remaining[0].data);
162
+ payload[0] &= ~0x0c; // EXIF (0x08), XMP (0x04)
163
+ const body = remaining.slice(1).map((item) => item.raw);
164
+ return riff(needsExtended ? [chunk("VP8X", payload), ...body] : body);
165
+ }
166
+
167
+ function metadata(buffer, { packId, packName, publisher, emojis = [] }) {
168
+ const meta = parse(buffer);
169
+ const id =
170
+ packId ??
171
+ createHash("sha256")
172
+ .update(JSON.stringify([packName, publisher]))
173
+ .digest("hex")
174
+ .slice(0, 32);
175
+ const json = Buffer.from(
176
+ JSON.stringify({
177
+ "sticker-pack-id": id,
178
+ "sticker-pack-name": packName,
179
+ "sticker-pack-publisher": publisher,
180
+ emojis,
181
+ }),
182
+ "utf8",
183
+ );
184
+ const tiff = Buffer.alloc(8 + 2 + 12 + 4 + json.length);
185
+ tiff.write("II", 0);
186
+ tiff.writeUInt16LE(42, 2);
187
+ tiff.writeUInt32LE(8, 4);
188
+ tiff.writeUInt16LE(1, 8);
189
+ tiff.writeUInt16LE(0x5741, 10);
190
+ tiff.writeUInt16LE(7, 12);
191
+ tiff.writeUInt32LE(json.length, 14);
192
+ tiff.writeUInt32LE(26, 18);
193
+ json.copy(tiff, 26);
194
+ const source = meta.chunks.filter((c) => c.type !== "EXIF");
195
+ const first = source[0];
196
+ const vp8x = Buffer.alloc(10);
197
+ if (first.type === "VP8X") first.data.copy(vp8x);
198
+ vp8x[0] |= 0x08;
199
+ if (meta.alpha) vp8x[0] |= 0x10;
200
+ if (meta.animated) vp8x[0] |= 0x02;
201
+ vp8x.writeUIntLE(meta.width - 1, 4, 3);
202
+ vp8x.writeUIntLE(meta.height - 1, 7, 3);
203
+ const rest = source.slice(first.type === "VP8X" ? 1 : 0).map((c) => c.raw);
204
+ const xmp = rest.findIndex((c) => c.toString("ascii", 0, 4) === "XMP ");
205
+ rest.splice(xmp < 0 ? rest.length : xmp, 0, chunk("EXIF", tiff));
206
+ return riff([chunk("VP8X", vp8x), ...rest]);
207
+ }
208
+
209
+ function readMetadata(buffer) {
210
+ const exif = parse(buffer).chunks.find((c) => c.type === "EXIF")?.data;
211
+ if (
212
+ !exif ||
213
+ exif.length < 26 ||
214
+ exif.toString("ascii", 0, 2) !== "II" ||
215
+ exif.readUInt16LE(8) !== 1 ||
216
+ exif.readUInt16LE(10) !== 0x5741 ||
217
+ exif.readUInt16LE(12) !== 7
218
+ ) {
219
+ return null;
220
+ }
221
+ const len = exif.readUInt32LE(14);
222
+ const offset = exif.readUInt32LE(18);
223
+ if (offset + len > exif.length) corrupt();
224
+ try {
225
+ return JSON.parse(exif.toString("utf8", offset, offset + len));
226
+ } catch {
227
+ corrupt();
228
+ }
229
+ }
230
+
231
+ module.exports = { parse, extractFrame, metadata, readMetadata, canonical };
@@ -0,0 +1,107 @@
1
+ // A store-only ZIP (method 0). The sticker export is a handful of already
2
+ // compressed WebP/PNG files, so deflate would cost CPU and save nothing.
3
+ // Node 24's zlib.crc32 is the checksum; names are flagged UTF-8 so an Arabic
4
+ // sticker name round-trips.
5
+
6
+ const zlib = require("node:zlib");
7
+
8
+ function dosDateTime(date) {
9
+ const when = date instanceof Date ? date : new Date();
10
+ const year = Math.max(1980, when.getFullYear());
11
+ const dosTime =
12
+ (when.getHours() << 11) | (when.getMinutes() << 5) | Math.floor(when.getSeconds() / 2);
13
+ const dosDate = ((year - 1980) << 9) | ((when.getMonth() + 1) << 5) | when.getDate();
14
+ return { dosTime, dosDate };
15
+ }
16
+
17
+ function uniqueName(name, used) {
18
+ const leaf = String(name || "sticker")
19
+ .replace(/\\/g, "/")
20
+ .split("/")
21
+ .pop();
22
+ let base = leaf.replace(/\p{Cc}/gu, "").replace(/^\.+/, "");
23
+ if (!base) base = "sticker";
24
+ if ([...base].length > 180) base = [...base].slice(0, 180).join("");
25
+ if (!used.has(base)) {
26
+ used.add(base);
27
+ return base;
28
+ }
29
+ const dot = base.lastIndexOf(".");
30
+ const stem = dot > 0 ? base.slice(0, dot) : base;
31
+ const ext = dot > 0 ? base.slice(dot) : "";
32
+ let n = 2;
33
+ while (used.has(`${stem}-${n}${ext}`)) n += 1;
34
+ const next = `${stem}-${n}${ext}`;
35
+ used.add(next);
36
+ return next;
37
+ }
38
+
39
+ /**
40
+ * @param {{ name: string, data: Buffer }[]} entries
41
+ * @param {Date} [now]
42
+ * @returns {Buffer}
43
+ */
44
+ function zipStore(entries, now = new Date()) {
45
+ const { dosTime, dosDate } = dosDateTime(now);
46
+ const parts = [];
47
+ const centrals = [];
48
+ const used = new Set();
49
+ let offset = 0;
50
+
51
+ for (const entry of entries) {
52
+ const name = Buffer.from(uniqueName(entry.name, used), "utf8");
53
+ const data = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data || "");
54
+ const crc = zlib.crc32(data) >>> 0;
55
+
56
+ const local = Buffer.alloc(30 + name.length);
57
+ local.writeUInt32LE(0x04034b50, 0);
58
+ local.writeUInt16LE(20, 4);
59
+ local.writeUInt16LE(0x0800, 6);
60
+ local.writeUInt16LE(0, 8);
61
+ local.writeUInt16LE(dosTime, 10);
62
+ local.writeUInt16LE(dosDate, 12);
63
+ local.writeUInt32LE(crc, 14);
64
+ local.writeUInt32LE(data.length, 18);
65
+ local.writeUInt32LE(data.length, 22);
66
+ local.writeUInt16LE(name.length, 26);
67
+ local.writeUInt16LE(0, 28);
68
+ name.copy(local, 30);
69
+ parts.push(local, data);
70
+
71
+ const central = Buffer.alloc(46 + name.length);
72
+ central.writeUInt32LE(0x02014b50, 0);
73
+ central.writeUInt16LE(20, 4);
74
+ central.writeUInt16LE(20, 6);
75
+ central.writeUInt16LE(0x0800, 8);
76
+ central.writeUInt16LE(0, 10);
77
+ central.writeUInt16LE(dosTime, 12);
78
+ central.writeUInt16LE(dosDate, 14);
79
+ central.writeUInt32LE(crc, 16);
80
+ central.writeUInt32LE(data.length, 20);
81
+ central.writeUInt32LE(data.length, 24);
82
+ central.writeUInt16LE(name.length, 28);
83
+ central.writeUInt16LE(0, 30);
84
+ central.writeUInt16LE(0, 32);
85
+ central.writeUInt16LE(0, 34);
86
+ central.writeUInt16LE(0, 36);
87
+ central.writeUInt32LE(0, 38);
88
+ central.writeUInt32LE(offset, 42);
89
+ name.copy(central, 46);
90
+ centrals.push(central);
91
+ offset += local.length + data.length;
92
+ }
93
+
94
+ const centralDir = centrals.length ? Buffer.concat(centrals) : Buffer.alloc(0);
95
+ const eocd = Buffer.alloc(22);
96
+ eocd.writeUInt32LE(0x06054b50, 0);
97
+ eocd.writeUInt16LE(0, 4);
98
+ eocd.writeUInt16LE(0, 6);
99
+ eocd.writeUInt16LE(entries.length, 8);
100
+ eocd.writeUInt16LE(entries.length, 10);
101
+ eocd.writeUInt32LE(centralDir.length, 12);
102
+ eocd.writeUInt32LE(offset, 16);
103
+ eocd.writeUInt16LE(0, 20);
104
+ return Buffer.concat([...parts, centralDir, eocd]);
105
+ }
106
+
107
+ module.exports = { zipStore };
@@ -6,9 +6,11 @@ function unwrapMessage(message) {
6
6
  for (let i = 0; i < 6; i++) {
7
7
  if (inner.viewOnceMessage?.message) inner = inner.viewOnceMessage.message;
8
8
  else if (inner.viewOnceMessageV2?.message) inner = inner.viewOnceMessageV2.message;
9
- else if (inner.viewOnceMessageV2Extension?.message) inner = inner.viewOnceMessageV2Extension.message;
9
+ else if (inner.viewOnceMessageV2Extension?.message)
10
+ inner = inner.viewOnceMessageV2Extension.message;
10
11
  else if (inner.ephemeralMessage?.message) inner = inner.ephemeralMessage.message;
11
- else if (inner.documentWithCaptionMessage?.message) inner = inner.documentWithCaptionMessage.message;
12
+ else if (inner.documentWithCaptionMessage?.message)
13
+ inner = inner.documentWithCaptionMessage.message;
12
14
  else if (inner.editedMessage?.message) inner = inner.editedMessage.message;
13
15
  else break;
14
16
  }
@@ -27,7 +29,13 @@ function visibleText(message) {
27
29
  );
28
30
  }
29
31
 
30
- const MEDIA_KEYS = ["imageMessage", "videoMessage", "stickerMessage", "audioMessage", "documentMessage"];
32
+ const MEDIA_KEYS = [
33
+ "imageMessage",
34
+ "videoMessage",
35
+ "stickerMessage",
36
+ "audioMessage",
37
+ "documentMessage",
38
+ ];
31
39
 
32
40
  function mediaType(message) {
33
41
  const inner = unwrapMessage(message);
@@ -37,4 +45,22 @@ function mediaType(message) {
37
45
  return "";
38
46
  }
39
47
 
40
- module.exports = { unwrapMessage, visibleText, mediaType };
48
+ function pickMedia(message) {
49
+ const inner = unwrapMessage(message);
50
+ for (const type of ["sticker", "image", "video", "audio", "document"]) {
51
+ const media = inner[`${type}Message`];
52
+ if (media) return { media, type };
53
+ }
54
+ return null;
55
+ }
56
+
57
+ function quotedOf(msg) {
58
+ const inner = unwrapMessage(msg?.message);
59
+ for (const key of ["extendedTextMessage", "imageMessage", "videoMessage", "documentMessage"]) {
60
+ const quoted = inner[key]?.contextInfo?.quotedMessage;
61
+ if (quoted) return quoted;
62
+ }
63
+ return null;
64
+ }
65
+
66
+ module.exports = { unwrapMessage, visibleText, mediaType, pickMedia, quotedOf };