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.
Files changed (75) 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/autoschedule.cjs +1 -1
  9. package/src/commands/blacklist.cjs +1 -1
  10. package/src/commands/calc.cjs +9 -9
  11. package/src/commands/gemini.cjs +26 -26
  12. package/src/commands/group/add.cjs +2 -2
  13. package/src/commands/group/demote.cjs +2 -2
  14. package/src/commands/group/members.cjs +2 -2
  15. package/src/commands/group/rules.cjs +1 -1
  16. package/src/commands/group/setname.cjs +3 -3
  17. package/src/commands/group/setpp.cjs +3 -3
  18. package/src/commands/group/setrules.cjs +1 -1
  19. package/src/commands/group/tagadmins.cjs +1 -1
  20. package/src/commands/group.cjs +1 -1
  21. package/src/commands/lang.cjs +3 -3
  22. package/src/commands/listschedules.cjs +1 -1
  23. package/src/commands/loop.cjs +3 -3
  24. package/src/commands/memory.cjs +18 -18
  25. package/src/commands/notes.cjs +1 -1
  26. package/src/commands/pack.cjs +159 -0
  27. package/src/commands/packs.cjs +47 -0
  28. package/src/commands/perm.cjs +2 -2
  29. package/src/commands/poll.cjs +3 -3
  30. package/src/commands/rand.cjs +2 -2
  31. package/src/commands/restart.cjs +4 -4
  32. package/src/commands/schedule.cjs +1 -1
  33. package/src/commands/send.cjs +3 -20
  34. package/src/commands/status.cjs +2 -2
  35. package/src/commands/sticker.cjs +77 -232
  36. package/src/commands/stickers.cjs +100 -0
  37. package/src/commands/stopbot.cjs +5 -5
  38. package/src/commands/stt.cjs +1 -1
  39. package/src/commands/toimage.cjs +88 -0
  40. package/src/commands/tts.cjs +2 -2
  41. package/src/config/defaults.cjs +5 -0
  42. package/src/config/settings.cjs +10 -0
  43. package/src/core/events.js +15 -1
  44. package/src/core/session.js +7 -0
  45. package/src/db/db.cjs +381 -0
  46. package/src/db/store.cjs +729 -21
  47. package/src/handlers/command.handler.js +5 -1
  48. package/src/panel/password-reset.cjs +1 -1
  49. package/src/routes/dashboard.api.esm.js +43 -10
  50. package/src/routes/stickers.api.esm.js +570 -0
  51. package/src/services/aiAgent.cjs +2 -2
  52. package/src/services/aiProviders.cjs +1 -1
  53. package/src/services/aiTools.cjs +27 -27
  54. package/src/stickers/errors.cjs +239 -0
  55. package/src/stickers/ffmpeg.cjs +133 -0
  56. package/src/stickers/jobs.cjs +183 -0
  57. package/src/stickers/library.cjs +712 -0
  58. package/src/stickers/limits.cjs +60 -0
  59. package/src/stickers/media.cjs +748 -0
  60. package/src/stickers/options.cjs +128 -0
  61. package/src/stickers/owner.cjs +103 -0
  62. package/src/stickers/studio.cjs +473 -0
  63. package/src/stickers/uploads.cjs +263 -0
  64. package/src/stickers/webp.cjs +231 -0
  65. package/src/stickers/zip.cjs +107 -0
  66. package/src/utils/memory.cjs +7 -7
  67. package/src/utils/messageContent.cjs +30 -4
  68. package/src/utils/recurrence.cjs +189 -30
  69. package/src/utils/stickerBot.cjs +84 -0
  70. package/src/utils/storage.cjs +3 -0
  71. package/src/utils/storage.esm.js +3 -0
  72. package/views/login.ejs +39 -3
  73. package/views/setup.ejs +21 -0
  74. package/public/dashboard/assets/index-BCXZoPGP.js +0 -446
  75. package/public/dashboard/assets/index-LvfJ8ybs.css +0 -2
@@ -0,0 +1,128 @@
1
+ // Sticker edit options: the one schema the panel editor, the API, the bot and
2
+ // the converter agree on, and the placement formula the editor preview and the
3
+ // FFmpeg filter graph both implement — so what the preview shows is what gets
4
+ // encoded.
5
+ //
6
+ // fit "contain" (whole picture, padded) | "cover" (fills, cropped)
7
+ // zoom 1..4, on top of the fit
8
+ // panX, panY -1..1; positive moves the picture right / down
9
+ // rotate 0 | 90 | 180 | 270, clockwise, applied before the fit
10
+ // background "transparent" | "#rrggbb" — what shows around/behind it
11
+ // removeBackground null | { mode: "plain", tolerance: 0.02..0.6 }
12
+ // keys out the colour of the top-left pixel (flat backdrops)
13
+ // trim null | { start: s >= 0, duration: 0.5..STICKER_MAX_SECONDS }
14
+ // video and GIF only
15
+
16
+ const { StickerError } = require("./errors.cjs");
17
+ const { CANVAS, STICKER_MAX_SECONDS, VIDEO_MAX_SOURCE_SECONDS } = require("./limits.cjs");
18
+
19
+ const DEFAULTS = Object.freeze({
20
+ fit: "contain",
21
+ zoom: 1,
22
+ panX: 0,
23
+ panY: 0,
24
+ rotate: 0,
25
+ background: "transparent",
26
+ removeBackground: null,
27
+ trim: null,
28
+ });
29
+
30
+ const FITS = new Set(["contain", "cover"]);
31
+ const ROTATIONS = new Set([0, 90, 180, 270]);
32
+ const HEX = /^#[0-9a-f]{6}$/;
33
+
34
+ function invalid(field) {
35
+ return new StickerError("INVALID_OPTIONS", { field });
36
+ }
37
+
38
+ function number(value, field, min, max) {
39
+ const n = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
40
+ if (typeof n !== "number" || !Number.isFinite(n) || n < min || n > max) throw invalid(field);
41
+ return n;
42
+ }
43
+
44
+ /**
45
+ * Validate and fill in edit options. Unknown keys are dropped; a bad value is
46
+ * an INVALID_OPTIONS error naming the field, never silently replaced.
47
+ * @param {object|null|undefined} raw
48
+ * @returns {typeof DEFAULTS}
49
+ */
50
+ function normalizeOptions(raw) {
51
+ if (raw == null) return { ...DEFAULTS };
52
+ if (typeof raw !== "object" || Array.isArray(raw)) throw invalid("options");
53
+ const out = { ...DEFAULTS };
54
+
55
+ if (raw.fit !== undefined) {
56
+ if (!FITS.has(raw.fit)) throw invalid("fit");
57
+ out.fit = raw.fit;
58
+ }
59
+ if (raw.zoom !== undefined) out.zoom = number(raw.zoom, "zoom", 1, 4);
60
+ if (raw.panX !== undefined) out.panX = number(raw.panX, "panX", -1, 1);
61
+ if (raw.panY !== undefined) out.panY = number(raw.panY, "panY", -1, 1);
62
+ if (raw.rotate !== undefined) {
63
+ const r = number(raw.rotate, "rotate", 0, 270);
64
+ if (!ROTATIONS.has(r)) throw invalid("rotate");
65
+ out.rotate = r;
66
+ }
67
+ if (raw.background !== undefined) {
68
+ const bg = String(raw.background).toLowerCase();
69
+ if (bg !== "transparent" && !HEX.test(bg)) throw invalid("background");
70
+ out.background = bg;
71
+ }
72
+ if (raw.removeBackground != null) {
73
+ const rb = raw.removeBackground;
74
+ if (typeof rb !== "object" || rb.mode !== "plain") throw invalid("removeBackground");
75
+ out.removeBackground = {
76
+ mode: "plain",
77
+ tolerance:
78
+ rb.tolerance === undefined ? 0.15 : number(rb.tolerance, "removeBackground", 0.02, 0.6),
79
+ };
80
+ }
81
+ if (raw.trim != null) {
82
+ if (typeof raw.trim !== "object") throw invalid("trim");
83
+ out.trim = {
84
+ start: number(raw.trim.start ?? 0, "trim", 0, VIDEO_MAX_SOURCE_SECONDS),
85
+ duration: number(raw.trim.duration ?? STICKER_MAX_SECONDS, "trim", 0.5, STICKER_MAX_SECONDS),
86
+ };
87
+ }
88
+ return out;
89
+ }
90
+
91
+ /** True when the options change nothing — a WebP that already fits can be kept as is. */
92
+ function isDefaultOptions(options) {
93
+ const o = normalizeOptions(options);
94
+ return (
95
+ o.fit === "contain" &&
96
+ o.zoom === 1 &&
97
+ o.panX === 0 &&
98
+ o.panY === 0 &&
99
+ o.rotate === 0 &&
100
+ o.background === "transparent" &&
101
+ o.removeBackground === null &&
102
+ o.trim === null
103
+ );
104
+ }
105
+
106
+ /**
107
+ * Where the (rotated) source lands on the CANVAS×CANVAS sticker.
108
+ * @param {number} width source width before rotation
109
+ * @param {number} height source height before rotation
110
+ * @param {typeof DEFAULTS} options normalized options
111
+ * @returns {{ width: number, height: number, x: number, y: number }}
112
+ * the scaled picture's size and its top-left corner; x/y may be negative
113
+ * (the picture overhangs and is cropped)
114
+ */
115
+ function placement(width, height, options) {
116
+ const quarter = options.rotate === 90 || options.rotate === 270;
117
+ const w = quarter ? height : width;
118
+ const h = quarter ? width : height;
119
+ const base = options.fit === "cover" ? CANVAS / Math.min(w, h) : CANVAS / Math.max(w, h);
120
+ const scale = base * options.zoom;
121
+ const W = Math.max(1, Math.round(w * scale));
122
+ const H = Math.max(1, Math.round(h * scale));
123
+ const x = Math.round((CANVAS - W) / 2 + (options.panX * Math.abs(CANVAS - W)) / 2);
124
+ const y = Math.round((CANVAS - H) / 2 + (options.panY * Math.abs(CANVAS - H)) / 2);
125
+ return { width: W, height: H, x, y };
126
+ }
127
+
128
+ module.exports = { DEFAULTS, normalizeOptions, isDefaultOptions, placement };
@@ -0,0 +1,103 @@
1
+ // Who a sticker belongs to.
2
+ //
3
+ // A library is a row in sticker_owners. stickers.owner and sticker_packs.owner
4
+ // hold that row's id, a random 16 hex character string. The id is opaque to
5
+ // the library. This module is the only place that turns a WhatsApp identity
6
+ // into one.
7
+ //
8
+ // `self` is the panel and the linked account. Its account is the paired
9
+ // creds.me.lid, normalized, or creds.me.id only when the credentials carry no
10
+ // lid. Everyone else is a `user` row whose account is the sender's normalized
11
+ // LID (`<digits>@lid`, no device suffix). The LID is the one on the message.
12
+ // A message that has only a phone JID asks Baileys for the current mapping of
13
+ // that number. Levix's lid_mapping table is history and is not consulted: a
14
+ // recycled phone number has a new LID, so it does not inherit the previous
15
+ // holder's library. No LID means the sender is not identified.
16
+
17
+ const store = require("../db/store.cjs");
18
+ const { getSenderCandidates } = require("../utils/permissions.esm.js");
19
+ const normalizeJidModule = require("../utils/normalizeJid.esm.js");
20
+
21
+ const normalizeJid = normalizeJidModule.default;
22
+ const { isLidJid, isPnJid } = normalizeJidModule;
23
+
24
+ const LID_LOOKUP_MS = 5000;
25
+
26
+ function normalizedLid(value) {
27
+ const norm = normalizeJid(value);
28
+ return isLidJid(norm) ? norm : null;
29
+ }
30
+
31
+ function normalizedPn(value) {
32
+ const norm = normalizeJid(value);
33
+ return isPnJid(norm) ? norm : null;
34
+ }
35
+
36
+ function readCreds() {
37
+ if (!store.isPairedSession()) return null;
38
+ try {
39
+ const creds = JSON.parse(store.authRead("creds") || "");
40
+ return creds && typeof creds === "object" ? creds : null;
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ function forPanel() {
47
+ const me = readCreds()?.me;
48
+ const lid = me?.lid ? normalizedLid(me.lid) : null;
49
+ const phone = normalizedPn(me?.id);
50
+ // A session paired before its credentials carried a lid bound the panel to
51
+ // its phone. When Baileys later fills in me.lid, that is the same pairing,
52
+ // so the panel library moves onto the LID instead of being left behind.
53
+ return store.stickerOwnerReconcileSelf(lid || phone || null, lid ? phone : null);
54
+ }
55
+
56
+ function firstOf(ids, normalize) {
57
+ for (const id of ids) {
58
+ const norm = normalize(id);
59
+ if (norm) return norm;
60
+ }
61
+ return null;
62
+ }
63
+
64
+ function lookupLid(sock, pn) {
65
+ const mapping = sock?.signalRepository?.lidMapping;
66
+ const getLIDForPN = mapping?.getLIDForPN;
67
+ if (typeof getLIDForPN !== "function") return Promise.resolve(null);
68
+ let timer;
69
+ const timeout = new Promise((resolve) => {
70
+ timer = setTimeout(() => resolve(null), LID_LOOKUP_MS);
71
+ });
72
+ const lookup = Promise.resolve()
73
+ .then(() => getLIDForPN.call(mapping, pn))
74
+ .then((value) => normalizedLid(value))
75
+ .catch(() => null);
76
+ return Promise.race([lookup, timeout]).finally(() => clearTimeout(timer));
77
+ }
78
+
79
+ /**
80
+ * @param {object} msg a Baileys message
81
+ * @param {object} [sock] the socket, for the current phone-to-LID mapping
82
+ * @returns {Promise<{ key: string|null }>}
83
+ */
84
+ async function forMessage(msg, sock) {
85
+ if (msg?.key?.fromMe) return forPanel();
86
+
87
+ const messageIds = getSenderCandidates(msg, sock);
88
+ let lid = firstOf(messageIds, normalizedLid);
89
+ const phone = firstOf(messageIds, normalizedPn);
90
+ if (!lid && phone) lid = await lookupLid(sock, phone);
91
+
92
+ const creds = readCreds();
93
+ const pairedLid = creds?.me?.lid ? normalizedLid(creds.me.lid) : null;
94
+ if (lid && pairedLid && lid === pairedLid) return forPanel();
95
+ if (!creds?.me?.lid && phone) {
96
+ const pairedPn = normalizedPn(creds?.me?.id);
97
+ if (pairedPn && phone === pairedPn) return forPanel();
98
+ }
99
+ if (!lid) return { key: null };
100
+ return store.stickerOwnerEnsure(lid);
101
+ }
102
+
103
+ module.exports = { forPanel, forMessage };
@@ -0,0 +1,473 @@
1
+ // The glue between an upload (or a WhatsApp buffer) and the library.
2
+ //
3
+ // media.cjs and jobs.cjs are required only when a call needs them. Tests pass
4
+ // fakes that honour the same signatures. Every conversion goes through the job
5
+ // queue, so a burst of export requests cannot start unbounded FFmpeg processes.
6
+ // An upload is converted from its own file (the panel retries that same id).
7
+ // Only a buffer — the bot — is copied to a work file, and only when the bytes
8
+ // cannot be kept as they are.
9
+
10
+ const crypto = require("node:crypto");
11
+ const fs = require("node:fs");
12
+ const path = require("node:path");
13
+
14
+ const brand = require("../config/brand.cjs");
15
+ const { ensureDataDir } = require("../config/paths.cjs");
16
+ const logger = require("../utils/logger.cjs");
17
+ const { StickerError } = require("./errors.cjs");
18
+ const { EXISTING_MAX_SIDE, STICKER_MAX_BYTES, VIDEO_MAX_SOURCE_SECONDS } = require("./limits.cjs");
19
+ const { isDefaultOptions, normalizeOptions } = require("./options.cjs");
20
+ const { zipStore } = require("./zip.cjs");
21
+
22
+ const SOURCES = new Set(["BOT_COMMAND", "PANEL_UPLOAD", "WHATSAPP_STICKER", "MEDIA_HUB"]);
23
+ const ID_RE = /^[0-9a-f]{16}$/;
24
+ const JOB_MAP_MAX = 1000;
25
+ const SNIFF_BYTES = 512;
26
+
27
+ function extOf(sniffed) {
28
+ const ext = String(sniffed?.ext || "bin").replace(/[^a-z0-9]/gi, "");
29
+ return ext || "bin";
30
+ }
31
+
32
+ function fitsKeep(sniffed, options, overlay, byteLength) {
33
+ // An overlay is drawn over the whole sticker, so the bytes cannot be kept.
34
+ return (
35
+ sniffed?.kind === "webp" &&
36
+ !overlay?.length &&
37
+ isDefaultOptions(options) &&
38
+ byteLength > 0 &&
39
+ byteLength <= STICKER_MAX_BYTES
40
+ );
41
+ }
42
+
43
+ function acceptableWebp(buffer, media) {
44
+ try {
45
+ const info = media.describeWebp(buffer);
46
+ return (
47
+ info.width >= 1 &&
48
+ info.height >= 1 &&
49
+ info.width <= EXISTING_MAX_SIDE &&
50
+ info.height <= EXISTING_MAX_SIDE
51
+ );
52
+ } catch {
53
+ return false;
54
+ }
55
+ }
56
+
57
+ function sniffHeader(file, media) {
58
+ const fd = fs.openSync(file, "r");
59
+ try {
60
+ const buf = Buffer.alloc(SNIFF_BYTES);
61
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
62
+ if (n <= 0) return null;
63
+ return media.sniff(buf.subarray(0, n));
64
+ } finally {
65
+ fs.closeSync(fd);
66
+ }
67
+ }
68
+
69
+ function writeWorkFile(buffer, sniffed) {
70
+ const dir = ensureDataDir("tmp", "stickers");
71
+ const temp = path.join(dir, `work-${crypto.randomBytes(8).toString("hex")}.${extOf(sniffed)}`);
72
+ try {
73
+ fs.writeFileSync(temp, buffer);
74
+ } catch (error) {
75
+ fs.rmSync(temp, { force: true });
76
+ if (error?.code === "EACCES" || error?.code === "ENOSPC" || error?.code === "EROFS") {
77
+ throw new StickerError("STORAGE_UNAVAILABLE", {}, { cause: error });
78
+ }
79
+ throw error;
80
+ }
81
+ return temp;
82
+ }
83
+
84
+ function dropWorkFile(file) {
85
+ if (!file) return;
86
+ try {
87
+ fs.rmSync(file, { force: true });
88
+ } catch {
89
+ // The job already failed. A leftover work file is swept with the temp dir.
90
+ }
91
+ }
92
+
93
+ function createStudio({ media, jobs, library, uploads } = {}) {
94
+ const jobOwners = new Map();
95
+
96
+ const useMedia = () => media || require("./media.cjs");
97
+ const useJobs = () => jobs || require("./jobs.cjs");
98
+ const useLibrary = () => library || require("./library.cjs");
99
+ const useUploads = () => uploads || require("./uploads.cjs");
100
+
101
+ function remember(id, owner) {
102
+ if (jobOwners.size >= JOB_MAP_MAX) {
103
+ const oldest = jobOwners.keys().next().value;
104
+ jobOwners.delete(oldest);
105
+ }
106
+ jobOwners.set(id, owner.key);
107
+ }
108
+
109
+ function owns(owner, id) {
110
+ const key = jobOwners.get(id);
111
+ return Boolean(key && owner?.key && key === owner.key);
112
+ }
113
+
114
+ function assertPack(owner, packId) {
115
+ if (packId == null) return;
116
+ if (typeof packId !== "string" || !ID_RE.test(packId)) {
117
+ throw new StickerError("INVALID_OPTIONS", { field: "packId" });
118
+ }
119
+ try {
120
+ useLibrary().getPack(owner, packId);
121
+ } catch (error) {
122
+ if (error instanceof StickerError && error.code === "NOT_FOUND") {
123
+ throw new StickerError("PACK_NOT_FOUND");
124
+ }
125
+ throw error;
126
+ }
127
+ }
128
+
129
+ function prepareBuffer({ buffer, options, overlayPng }) {
130
+ if (!Buffer.isBuffer(buffer) || buffer.length === 0) throw new StickerError("NO_MEDIA");
131
+ const med = useMedia();
132
+ const sniffed = med.sniff(buffer);
133
+ if (!sniffed) throw new StickerError("UNSUPPORTED_TYPE");
134
+ const opts = normalizeOptions(options);
135
+ const keep = fitsKeep(sniffed, opts, overlayPng, buffer.length) && acceptableWebp(buffer, med);
136
+ const keepBuffer = keep ? buffer : null;
137
+ const inputPath = keepBuffer ? null : writeWorkFile(buffer, sniffed);
138
+ return { sniffed, opts, keepBuffer, inputPath };
139
+ }
140
+
141
+ async function produce({
142
+ med,
143
+ sniffed,
144
+ keepBuffer,
145
+ inputPath,
146
+ opts,
147
+ overlayPng,
148
+ maxSourceSeconds,
149
+ signal,
150
+ progress,
151
+ }) {
152
+ if (!keepBuffer) {
153
+ return med.createSticker({
154
+ inputPath,
155
+ sniffed,
156
+ options: opts,
157
+ overlayPng,
158
+ maxSourceSeconds,
159
+ signal,
160
+ onProgress: progress,
161
+ });
162
+ }
163
+ progress("encoding", 1);
164
+ const described = med.describeWebp(keepBuffer);
165
+ return {
166
+ buffer: keepBuffer,
167
+ width: described.width,
168
+ height: described.height,
169
+ animated: !!described.animated,
170
+ durationMs: described.durationMs ?? 0,
171
+ sourceMime: sniffed.mime,
172
+ qualityReduced: false,
173
+ };
174
+ }
175
+
176
+ function runCreate({
177
+ owner,
178
+ inputPath,
179
+ sniffed,
180
+ keepBuffer,
181
+ options,
182
+ overlayPng,
183
+ source,
184
+ packId,
185
+ name,
186
+ maxSourceSeconds,
187
+ removeInput,
188
+ }) {
189
+ const med = useMedia();
190
+ const lib = useLibrary();
191
+ if (!sniffed) throw new StickerError("UNSUPPORTED_TYPE");
192
+ if (!keepBuffer && !inputPath) throw new StickerError("NO_MEDIA");
193
+ const opts = normalizeOptions(options);
194
+ const src = source || "PANEL_UPLOAD";
195
+ if (!SOURCES.has(src)) throw new StickerError("INVALID_OPTIONS", { field: "source" });
196
+ assertPack(owner, packId);
197
+ const epoch = lib.epoch?.();
198
+
199
+ let submitted;
200
+ try {
201
+ submitted = useJobs().submit(
202
+ async ({ signal, progress }) => {
203
+ try {
204
+ const produced = await produce({
205
+ med,
206
+ sniffed,
207
+ keepBuffer,
208
+ inputPath,
209
+ opts,
210
+ overlayPng,
211
+ maxSourceSeconds,
212
+ signal,
213
+ progress,
214
+ });
215
+ const thumb = await med.makeThumbnail(produced.buffer, { signal });
216
+ const saved = lib.saveSticker(owner, {
217
+ buffer: produced.buffer,
218
+ thumbBuffer: thumb,
219
+ width: produced.width,
220
+ height: produced.height,
221
+ animated: !!produced.animated,
222
+ durationMs: produced.durationMs,
223
+ sourceMime: produced.sourceMime || sniffed.mime,
224
+ source: src,
225
+ name,
226
+ epoch,
227
+ });
228
+ if (packId) lib.addToPack(owner, packId, [saved.sticker.id], { epoch });
229
+ const sticker = lib.getSticker(owner, saved.sticker.id);
230
+ return {
231
+ sticker,
232
+ created: saved.created,
233
+ qualityReduced: !!produced.qualityReduced,
234
+ };
235
+ } finally {
236
+ if (removeInput) dropWorkFile(inputPath);
237
+ }
238
+ },
239
+ { kind: "create" },
240
+ );
241
+ } catch (error) {
242
+ if (removeInput) dropWorkFile(inputPath);
243
+ throw error;
244
+ }
245
+
246
+ remember(submitted.id, owner);
247
+ // The route returns 202 and does not await this. The handler keeps the
248
+ // rejection from becoming an unhandled rejection; callers can still await.
249
+ submitted.promise.catch((error) => {
250
+ if (removeInput) dropWorkFile(inputPath);
251
+ logger.warn({ err: error, jobId: submitted.id }, "[Stickers] create job failed");
252
+ });
253
+ return { jobId: submitted.id, promise: submitted.promise };
254
+ }
255
+
256
+ function createFromBuffer(input = {}) {
257
+ // Reject an inaccessible pack before creating a temporary work file.
258
+ assertPack(input.owner, input.packId);
259
+ const { sniffed, opts, keepBuffer, inputPath } = prepareBuffer(input);
260
+ return runCreate({
261
+ owner: input.owner,
262
+ inputPath,
263
+ sniffed,
264
+ keepBuffer,
265
+ options: opts,
266
+ overlayPng: input.overlayPng,
267
+ source: input.source,
268
+ packId: input.packId,
269
+ name: input.name,
270
+ maxSourceSeconds: input.maxSourceSeconds,
271
+ removeInput: inputPath != null,
272
+ });
273
+ }
274
+
275
+ async function convertBuffer({ buffer, options, maxSourceSeconds }) {
276
+ const { sniffed, opts, keepBuffer, inputPath } = prepareBuffer({ buffer, options });
277
+ let submitted;
278
+ try {
279
+ submitted = useJobs().submit(
280
+ async ({ signal, progress }) => {
281
+ try {
282
+ const result = await produce({
283
+ med: useMedia(),
284
+ sniffed,
285
+ keepBuffer,
286
+ inputPath,
287
+ opts,
288
+ maxSourceSeconds,
289
+ signal,
290
+ progress,
291
+ });
292
+ return result.buffer;
293
+ } finally {
294
+ dropWorkFile(inputPath);
295
+ }
296
+ },
297
+ { kind: "create" },
298
+ );
299
+ } catch (error) {
300
+ dropWorkFile(inputPath);
301
+ throw error;
302
+ }
303
+ return submitted.promise.finally(() => dropWorkFile(inputPath));
304
+ }
305
+
306
+ function createFromUpload({ owner, uploadId, options, overlayPng, source, packId, name }) {
307
+ const record = useUploads().get(owner, uploadId);
308
+ if (!record) throw new StickerError("NOT_FOUND");
309
+ const med = useMedia();
310
+ let sniffed;
311
+ try {
312
+ sniffed = sniffHeader(record.path, med);
313
+ } catch (error) {
314
+ logger.error({ err: error }, "[Stickers] upload file disappeared");
315
+ throw new StickerError("NOT_FOUND");
316
+ }
317
+ if (!sniffed) throw new StickerError("UNSUPPORTED_TYPE");
318
+ const opts = normalizeOptions(options);
319
+ let keepBuffer = null;
320
+ // Only a small WebP is worth reading. A video or a large image stays on
321
+ // disk and is converted from that path; the job must not delete it,
322
+ // because "Try again" submits the same upload id.
323
+ if (fitsKeep(sniffed, opts, overlayPng, record.size)) {
324
+ let bytes;
325
+ try {
326
+ bytes = fs.readFileSync(record.path);
327
+ } catch (error) {
328
+ logger.error({ err: error }, "[Stickers] upload file disappeared");
329
+ throw new StickerError("NOT_FOUND");
330
+ }
331
+ if (bytes.length <= STICKER_MAX_BYTES && acceptableWebp(bytes, med)) keepBuffer = bytes;
332
+ }
333
+ return runCreate({
334
+ owner,
335
+ inputPath: record.path,
336
+ sniffed,
337
+ keepBuffer,
338
+ options: opts,
339
+ overlayPng,
340
+ source: source || "PANEL_UPLOAD",
341
+ packId,
342
+ name: name == null ? record.filename : name,
343
+ maxSourceSeconds: VIDEO_MAX_SOURCE_SECONDS,
344
+ removeInput: false,
345
+ });
346
+ }
347
+
348
+ // Export jobs are awaited by the request that queued them, so they are not
349
+ // remembered. Remembering them would push create jobs out of the owner map.
350
+ function queueExport(run) {
351
+ const submitted = useJobs().submit(run, { kind: "export" });
352
+ submitted.promise.catch((error) => {
353
+ logger.warn({ err: error, jobId: submitted.id }, "[Stickers] export job failed");
354
+ });
355
+ return submitted.promise;
356
+ }
357
+
358
+ async function exportImage(owner, stickerId, format) {
359
+ const lib = useLibrary();
360
+ const sticker = lib.getSticker(owner, stickerId);
361
+ if (format === "webp") {
362
+ return {
363
+ buffer: lib.readStickerFile(owner, stickerId),
364
+ mime: "image/webp",
365
+ fileName: lib.fileNameFor(sticker, "webp"),
366
+ animated: sticker.animated,
367
+ };
368
+ }
369
+ if (format !== "png" && format !== "gif") {
370
+ throw new StickerError("INVALID_OPTIONS", { field: "format" });
371
+ }
372
+ // A static gif is rejected before it takes a queue slot.
373
+ if (format === "gif" && !sticker.animated) {
374
+ throw new StickerError("INVALID_OPTIONS", { field: "format" });
375
+ }
376
+ return queueExport(async ({ signal }) => {
377
+ const webp = lib.readStickerFile(owner, stickerId);
378
+ if (format === "png") {
379
+ const png = await useMedia().toPng(webp, { signal });
380
+ return {
381
+ buffer: png.buffer,
382
+ mime: "image/png",
383
+ fileName: lib.fileNameFor(sticker, "png"),
384
+ animated: !!png.animated,
385
+ };
386
+ }
387
+ const gif = await useMedia().toGif(webp, { signal });
388
+ return {
389
+ buffer: gif,
390
+ mime: "image/gif",
391
+ fileName: lib.fileNameFor(sticker, "gif"),
392
+ animated: true,
393
+ };
394
+ });
395
+ }
396
+
397
+ async function exportZip(owner, ids, format) {
398
+ if (format !== "webp" && format !== "png") {
399
+ throw new StickerError("INVALID_OPTIONS", { field: "format" });
400
+ }
401
+ const lib = useLibrary();
402
+ // Resolve every id before taking a slot, so a missing sticker is a 404
403
+ // and not a queued conversion.
404
+ const stickers = ids.map((id) => lib.getSticker(owner, id));
405
+ if (format === "webp") {
406
+ return zipStore(
407
+ stickers.map((sticker) => ({
408
+ name: lib.fileNameFor(sticker, "webp"),
409
+ data: lib.readStickerFile(owner, sticker.id),
410
+ })),
411
+ );
412
+ }
413
+ return queueExport(async ({ signal, progress }) => {
414
+ const entries = [];
415
+ for (let i = 0; i < stickers.length; i++) {
416
+ const sticker = stickers[i];
417
+ const png = await useMedia().toPng(lib.readStickerFile(owner, sticker.id), { signal });
418
+ entries.push({ name: lib.fileNameFor(sticker, "png"), data: png.buffer });
419
+ progress("encoding", (i + 1) / stickers.length);
420
+ }
421
+ return zipStore(entries);
422
+ });
423
+ }
424
+
425
+ function firstPackName(owner, sticker) {
426
+ const packId = sticker.packIds?.[0];
427
+ if (!packId) return null;
428
+ try {
429
+ return useLibrary().getPack(owner, packId).pack.name;
430
+ } catch {
431
+ return null;
432
+ }
433
+ }
434
+
435
+ async function sendStickers(owner, ids, jid, sock) {
436
+ if (!sock) throw new StickerError("NOT_CONNECTED");
437
+ const lib = useLibrary();
438
+ const med = useMedia();
439
+ const stickers = [];
440
+ for (const id of ids) stickers.push(lib.getSticker(owner, id));
441
+ for (const sticker of stickers) {
442
+ const raw = lib.readStickerFile(owner, sticker.id);
443
+ const packed = med.withStickerMetadata(raw, {
444
+ packName: firstPackName(owner, sticker) || "Levix",
445
+ publisher: brand.name,
446
+ });
447
+ await sock.sendMessage(jid, { sticker: packed });
448
+ }
449
+ lib.touch(
450
+ owner,
451
+ stickers.map((sticker) => sticker.id),
452
+ );
453
+ return { sent: stickers.length };
454
+ }
455
+
456
+ function getJob(owner, jobId) {
457
+ if (!owns(owner, jobId)) return null;
458
+ const job = useJobs().get(jobId);
459
+ return job || null;
460
+ }
461
+
462
+ return {
463
+ createFromBuffer,
464
+ convertBuffer,
465
+ createFromUpload,
466
+ exportImage,
467
+ exportZip,
468
+ sendStickers,
469
+ getJob,
470
+ };
471
+ }
472
+
473
+ module.exports = Object.assign(createStudio(), { createStudio });