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
@@ -49,6 +49,10 @@ const EDIT_IN_PLACE_EXCLUDE = new Set([
49
49
  "loop",
50
50
  "rand",
51
51
  "poll",
52
+ "sticker",
53
+ "toimage",
54
+ "pack",
55
+ "stickers",
52
56
  ]);
53
57
 
54
58
  // Wrap a socket so commands reply nicely:
@@ -37,6 +37,7 @@ import {
37
37
  getGroupSettings,
38
38
  getRecentDebts,
39
39
  getSchedules,
40
+ rememberSavedName,
40
41
  saveGroupSettings,
41
42
  } from "../utils/storage.esm.js";
42
43
 
@@ -66,7 +67,11 @@ const {
66
67
  scheduleNewJob,
67
68
  saveScheduledJob,
68
69
  } = require("../../scheduler.cjs");
69
- const { describeScheduledJob } = require("../utils/recurrence.cjs");
70
+ const {
71
+ describeScheduledJob,
72
+ recurrenceErrorMessage,
73
+ recurrenceToCron,
74
+ } = require("../utils/recurrence.cjs");
70
75
  const { discoverProviderModels, DiscoveryError } = require("../services/llmDiscovery.cjs");
71
76
  const settingsTransfer = require("../services/settingsTransfer.cjs");
72
77
  const cron = require("node-cron");
@@ -960,10 +965,14 @@ function scheduleView(job) {
960
965
  const peer = describePeer(job.targetJid);
961
966
  return {
962
967
  ...job,
963
- when: describeScheduledJob(job, timezone),
968
+ when: describeScheduledJob(job, timezone, "en"),
969
+ whenAr: describeScheduledJob(job, timezone, "ar"),
964
970
  targetLabel: peer.label,
965
971
  targetKind: peer.kind,
966
972
  targetPhone: peer.phone,
973
+ savedName: peer.savedName ?? null,
974
+ pushName: peer.pushName ?? null,
975
+ phone: peer.phone,
967
976
  };
968
977
  }
969
978
 
@@ -986,6 +995,9 @@ router.get("/recipients", (req, res) => {
986
995
  name: live?.subject || peer.label,
987
996
  type: "group",
988
997
  memberCount: live?.participants?.length ?? peer.memberCount,
998
+ savedName: null,
999
+ pushName: null,
1000
+ phone: null,
989
1001
  });
990
1002
  };
991
1003
 
@@ -998,12 +1010,18 @@ router.get("/recipients", (req, res) => {
998
1010
  for (const u of users.slice(0, 80)) {
999
1011
  const jid = u.jid;
1000
1012
  if (!jid || seen.has(jid) || String(jid).endsWith("@g.us")) continue;
1001
- seen.add(jid);
1002
1013
  const peer = describePeer(jid);
1014
+ const personKey = peer.phone || u.lid || jid;
1015
+ if (seen.has(personKey)) continue;
1016
+ seen.add(jid);
1017
+ seen.add(personKey);
1018
+ if (u.lid) seen.add(u.lid);
1003
1019
  recipients.push({
1004
1020
  id: jid,
1005
1021
  name: peer.label,
1006
1022
  phone: peer.phone,
1023
+ savedName: peer.savedName ?? null,
1024
+ pushName: peer.pushName ?? null,
1007
1025
  type: "contact",
1008
1026
  });
1009
1027
  }
@@ -1022,7 +1040,8 @@ router.post(
1022
1040
  return badRequest(res, "Maximum 3 scheduled messages reached");
1023
1041
  }
1024
1042
 
1025
- const { targetJid, message, type, cronString, scheduledTime } = req.body || {};
1043
+ const { targetJid, message, type, cronString, scheduledTime, recurrence, targetName } =
1044
+ req.body || {};
1026
1045
  if (!targetJid || !message) {
1027
1046
  return badRequest(res, "Recipient and message are required");
1028
1047
  }
@@ -1038,10 +1057,20 @@ router.post(
1038
1057
  };
1039
1058
 
1040
1059
  if (job.type === "recurring") {
1041
- if (!cronString || !cron.validate(cronString)) {
1042
- return badRequest(res, "Invalid cron expression");
1060
+ if (recurrence && typeof recurrence === "object") {
1061
+ const built = recurrenceToCron(recurrence);
1062
+ if (built.error) return badRequest(res, recurrenceErrorMessage(built.error));
1063
+ if (!cron.validate(built.cronString)) {
1064
+ return badRequest(res, recurrenceErrorMessage("recurrence"));
1065
+ }
1066
+ job.cronString = built.cronString;
1067
+ } else if (cronString && cron.validate(cronString)) {
1068
+ // Raw cron is accepted only for existing callers/tests. The panel
1069
+ // sends a structured `recurrence` object and never a cron string.
1070
+ job.cronString = cronString;
1071
+ } else {
1072
+ return badRequest(res, "Invalid recurrence");
1043
1073
  }
1044
- job.cron = cronString;
1045
1074
  } else {
1046
1075
  const timeMs = Number(scheduledTime);
1047
1076
  if (!timeMs || timeMs <= Date.now()) {
@@ -1050,13 +1079,17 @@ router.post(
1050
1079
  job.date = new Date(timeMs).toISOString();
1051
1080
  }
1052
1081
 
1053
- saveScheduledJob(job);
1082
+ if (targetName && !String(job.targetJid).endsWith("@g.us")) {
1083
+ rememberSavedName(job.targetJid, targetName);
1084
+ }
1085
+
1086
+ const saved = saveScheduledJob(job);
1054
1087
  const sock = currentSocket();
1055
1088
  if (sock) {
1056
- scheduleNewJob(sock, job);
1089
+ scheduleNewJob(sock, saved);
1057
1090
  }
1058
1091
 
1059
- res.json({ success: true, schedule: scheduleView(job) });
1092
+ res.json({ success: true, schedule: scheduleView(saved) });
1060
1093
  }),
1061
1094
  );
1062
1095
 
@@ -0,0 +1,570 @@
1
+ // Sticker Studio HTTP API. Mounted at /dashboard/api behind the same session
2
+ // check as the rest of the panel. The operator shares the linked account's
3
+ // library (`owner.forPanel()`). Errors are the sticker vocabulary; anything else
4
+ // is logged and answered as INTERNAL, never with the exception text.
5
+ //
6
+ // The upload is not JSON. jsonUnlessStickerUpload skips the dashboard parser
7
+ // for that one path so the route can cap the body while it is still a stream.
8
+
9
+ import { Readable } from "node:stream";
10
+ import { Router } from "express";
11
+ import { createRequire } from "module";
12
+ import normalizeJid from "../utils/normalizeJid.esm.js";
13
+
14
+ const require = createRequire(import.meta.url);
15
+ const logger = require("../utils/logger.cjs");
16
+ const settings = require("../config/settings.cjs");
17
+ const library = require("../stickers/library.cjs");
18
+ const uploads = require("../stickers/uploads.cjs");
19
+ const studioModule = require("../stickers/studio.cjs");
20
+ const owner = require("../stickers/owner.cjs");
21
+ const {
22
+ CODES,
23
+ StickerError,
24
+ httpStatus,
25
+ toResponseBody,
26
+ userMessageIn,
27
+ } = require("../stickers/errors.cjs");
28
+ const {
29
+ CANVAS,
30
+ EXPORT_MAX_IDS,
31
+ MAX_INPUT_SIDE,
32
+ PACKS_MAX_PER_OWNER,
33
+ SEND_MAX_IDS,
34
+ STICKER_MAX_SECONDS,
35
+ UPLOAD_MAX_BYTES,
36
+ VIDEO_MAX_SOURCE_SECONDS,
37
+ } = require("../stickers/limits.cjs");
38
+ const { normalizeOptions } = require("../stickers/options.cjs");
39
+
40
+ const ID_RE = /^[0-9a-f]{16}$/;
41
+ const UPLOAD_ID_RE = /^[0-9a-f]{32}$/;
42
+ const JOB_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
43
+ const JID_RE = /@(s\.whatsapp\.net|g\.us|lid)$/;
44
+ const SORTS = new Set(["newest", "oldest", "name", "recent"]);
45
+ const FILTERS = new Set(["all", "favorites", "recent", "animated", "static"]);
46
+ const ACTIONS = new Set([
47
+ "favorite",
48
+ "unfavorite",
49
+ "delete",
50
+ "addToPack",
51
+ "moveToPack",
52
+ "removeFromPack",
53
+ "touch",
54
+ ]);
55
+ const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
56
+ const OVERLAY_MAX_BYTES = 4 * 1024 * 1024;
57
+
58
+ const router = Router();
59
+ let session = null;
60
+ let studioOverride = null;
61
+ let mediaOverride = null;
62
+
63
+ export function setSession(manager) {
64
+ session = manager;
65
+ }
66
+
67
+ export function setStudio(instance) {
68
+ studioOverride = instance || null;
69
+ }
70
+
71
+ export function setMedia(mod) {
72
+ mediaOverride = mod || null;
73
+ uploads.setMedia(mod || null);
74
+ }
75
+
76
+ function studio() {
77
+ return studioOverride || studioModule;
78
+ }
79
+
80
+ function media() {
81
+ return mediaOverride || require("../stickers/media.cjs");
82
+ }
83
+
84
+ function currentSocket() {
85
+ return session?.socket ?? null;
86
+ }
87
+
88
+ function panelOwner() {
89
+ return owner.forPanel();
90
+ }
91
+
92
+ export function jsonUnlessStickerUpload(jsonParser) {
93
+ return (req, res, next) => {
94
+ const urlPath = (req.originalUrl || "").split("?")[0];
95
+ if (req.method === "POST" && urlPath.endsWith("/stickers/uploads")) return next();
96
+ return jsonParser(req, res, next);
97
+ };
98
+ }
99
+
100
+ function asyncRoute(handler) {
101
+ return (req, res) => {
102
+ Promise.resolve(handler(req, res)).catch((error) => {
103
+ if (res.headersSent) return;
104
+ if (!(error instanceof StickerError)) {
105
+ logger.error({ err: error }, `[Stickers] ${req.method} ${req.path} failed`);
106
+ }
107
+ res.status(httpStatus(error)).json(toResponseBody(error));
108
+ if (error instanceof StickerError && error.code === "TOO_LARGE") {
109
+ res.on("finish", () => req.destroy());
110
+ }
111
+ });
112
+ };
113
+ }
114
+
115
+ function asPackError(error) {
116
+ if (error instanceof StickerError && error.code === "NOT_FOUND") {
117
+ throw new StickerError("PACK_NOT_FOUND");
118
+ }
119
+ throw error;
120
+ }
121
+
122
+ function bodyOf(req) {
123
+ const body = req.body;
124
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
125
+ throw new StickerError("INVALID_OPTIONS", { field: "body" });
126
+ }
127
+ return body;
128
+ }
129
+
130
+ function parseIds(value, max, { field = "ids", allowEmpty = false } = {}) {
131
+ if (!Array.isArray(value) || value.length > max || (!allowEmpty && value.length === 0)) {
132
+ throw new StickerError("INVALID_OPTIONS", { field });
133
+ }
134
+ const ids = [];
135
+ const seen = new Set();
136
+ for (const id of value) {
137
+ if (typeof id !== "string" || !ID_RE.test(id) || seen.has(id)) {
138
+ throw new StickerError("INVALID_OPTIONS", { field });
139
+ }
140
+ seen.add(id);
141
+ ids.push(id);
142
+ }
143
+ return ids;
144
+ }
145
+
146
+ function requireStickerId(id) {
147
+ if (typeof id !== "string" || !ID_RE.test(id)) {
148
+ throw new StickerError("INVALID_OPTIONS", { field: "id" });
149
+ }
150
+ return id;
151
+ }
152
+
153
+ function contentDisposition(fileName) {
154
+ const ascii = fileName.replace(/[^\x20-\x7e]/g, "_").replace(/"/g, "");
155
+ return `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(fileName)}`;
156
+ }
157
+
158
+ function decodeOverlay(value) {
159
+ if (typeof value !== "string" || !value.startsWith("data:image/png;base64,")) {
160
+ throw new StickerError("INVALID_OPTIONS", { field: "overlay" });
161
+ }
162
+ const buffer = Buffer.from(value.slice("data:image/png;base64,".length), "base64");
163
+ if (
164
+ buffer.length < 24 ||
165
+ buffer.length > OVERLAY_MAX_BYTES ||
166
+ !buffer.subarray(0, 8).equals(PNG_SIG)
167
+ ) {
168
+ throw new StickerError("INVALID_OPTIONS", { field: "overlay" });
169
+ }
170
+ if (buffer.toString("ascii", 12, 16) !== "IHDR") {
171
+ throw new StickerError("INVALID_OPTIONS", { field: "overlay" });
172
+ }
173
+ if (buffer.readUInt32BE(16) !== CANVAS || buffer.readUInt32BE(20) !== CANVAS) {
174
+ throw new StickerError("INVALID_OPTIONS", { field: "overlay" });
175
+ }
176
+ return buffer;
177
+ }
178
+
179
+ function jobErrorBody(error) {
180
+ if (!error) return null;
181
+ const code = CODES[error.code] ? error.code : "CONVERSION_FAILED";
182
+ const details = error.details && typeof error.details === "object" ? error.details : {};
183
+ const wrapped = new StickerError(code, details);
184
+ return { code, message: userMessageIn("en", wrapped), ...details };
185
+ }
186
+
187
+ function intQuery(value, fallback, field, min, max) {
188
+ if (value == null || value === "") return fallback;
189
+ if (typeof value !== "string" || !/^\d+$/.test(value)) {
190
+ throw new StickerError("INVALID_OPTIONS", { field });
191
+ }
192
+ const n = Number(value);
193
+ if (n < min || n > max) throw new StickerError("INVALID_OPTIONS", { field });
194
+ return n;
195
+ }
196
+
197
+ router.get(
198
+ "/stickers/capabilities",
199
+ asyncRoute(async (_req, res) => {
200
+ const caps = await media().capabilities();
201
+ res.json({
202
+ webp: !!caps.webp,
203
+ animated: !!caps.animated,
204
+ gif: !!caps.gif,
205
+ mp4: !!caps.mp4,
206
+ backgroundRemoval: Array.isArray(caps.backgroundRemoval) ? caps.backgroundRemoval : [],
207
+ limits: {
208
+ uploadBytes: UPLOAD_MAX_BYTES,
209
+ videoSeconds: VIDEO_MAX_SOURCE_SECONDS,
210
+ stickerSeconds: STICKER_MAX_SECONDS,
211
+ maxSide: MAX_INPUT_SIDE,
212
+ libraryMax: settings.get("sticker_library_limit"),
213
+ packsMax: PACKS_MAX_PER_OWNER,
214
+ },
215
+ });
216
+ }),
217
+ );
218
+
219
+ router.get(
220
+ "/stickers",
221
+ asyncRoute(async (req, res) => {
222
+ const sort = req.query.sort || "newest";
223
+ const filter = req.query.filter || "all";
224
+ if (typeof sort !== "string" || !SORTS.has(sort)) {
225
+ throw new StickerError("INVALID_OPTIONS", { field: "sort" });
226
+ }
227
+ if (typeof filter !== "string" || !FILTERS.has(filter)) {
228
+ throw new StickerError("INVALID_OPTIONS", { field: "filter" });
229
+ }
230
+ const pack = req.query.pack;
231
+ if (pack != null && pack !== "none" && (typeof pack !== "string" || !ID_RE.test(pack))) {
232
+ throw new StickerError("INVALID_OPTIONS", { field: "pack" });
233
+ }
234
+ const q = req.query.q == null ? "" : String(req.query.q);
235
+ res.json(
236
+ library.listStickers(panelOwner(), {
237
+ q,
238
+ sort,
239
+ filter,
240
+ pack: pack ?? null,
241
+ offset: intQuery(req.query.offset, 0, "offset", 0, 1_000_000),
242
+ limit: intQuery(req.query.limit, 60, "limit", 1, 200),
243
+ }),
244
+ );
245
+ }),
246
+ );
247
+
248
+ router.post(
249
+ "/stickers/uploads",
250
+ asyncRoute(async (req, res) => {
251
+ let filename = "";
252
+ const header = req.get("x-filename");
253
+ if (header) {
254
+ try {
255
+ filename = decodeURIComponent(header);
256
+ } catch {
257
+ filename = header;
258
+ }
259
+ }
260
+ const record = await uploads.acceptStream(panelOwner(), req, { filename, media: media() });
261
+ res.status(201).json(record);
262
+ }),
263
+ );
264
+
265
+ // Re-editing a library sticker in the Android host keeps its bytes on the
266
+ // server instead of uploading the WebView's preview Blob through the bridge.
267
+ router.post(
268
+ "/stickers/:id/uploads",
269
+ asyncRoute(async (req, res) => {
270
+ const id = requireStickerId(req.params.id);
271
+ const who = panelOwner();
272
+ const sticker = library.getSticker(who, id);
273
+ const bytes = library.readStickerFile(who, id);
274
+ const record = await uploads.acceptStream(who, Readable.from(bytes), {
275
+ filename: sticker.name,
276
+ media: media(),
277
+ });
278
+ res.status(201).json(record);
279
+ }),
280
+ );
281
+
282
+ router.post(
283
+ "/stickers/jobs",
284
+ asyncRoute(async (req, res) => {
285
+ const body = bodyOf(req);
286
+ if (typeof body.uploadId !== "string" || !UPLOAD_ID_RE.test(body.uploadId)) {
287
+ throw new StickerError("INVALID_OPTIONS", { field: "uploadId" });
288
+ }
289
+ const options = body.options == null ? undefined : normalizeOptions(body.options);
290
+ const overlay = body.overlay == null ? undefined : decodeOverlay(body.overlay);
291
+ if (body.name != null && typeof body.name !== "string") {
292
+ throw new StickerError("INVALID_OPTIONS", { field: "name" });
293
+ }
294
+ if (body.packId != null && (typeof body.packId !== "string" || !ID_RE.test(body.packId))) {
295
+ throw new StickerError("INVALID_OPTIONS", { field: "packId" });
296
+ }
297
+ const source = body.source ?? "PANEL_UPLOAD";
298
+ if (source !== "PANEL_UPLOAD" && source !== "MEDIA_HUB") {
299
+ throw new StickerError("INVALID_OPTIONS", { field: "source" });
300
+ }
301
+ const { jobId } = studio().createFromUpload({
302
+ owner: panelOwner(),
303
+ uploadId: body.uploadId,
304
+ options,
305
+ overlayPng: overlay,
306
+ source,
307
+ packId: body.packId,
308
+ name: body.name,
309
+ });
310
+ res.status(202).json({ jobId });
311
+ }),
312
+ );
313
+
314
+ router.get(
315
+ "/stickers/jobs/:id",
316
+ asyncRoute(async (req, res) => {
317
+ if (!JOB_ID_RE.test(req.params.id)) throw new StickerError("NOT_FOUND");
318
+ const job = studio().getJob(panelOwner(), req.params.id);
319
+ if (!job) throw new StickerError("NOT_FOUND");
320
+ const result = job.result || null;
321
+ res.json({
322
+ id: job.id,
323
+ state: job.state,
324
+ stage: job.stage ?? null,
325
+ progress: job.progress ?? 0,
326
+ error: jobErrorBody(job.error),
327
+ sticker: result?.sticker ?? null,
328
+ created: result ? result.created : null,
329
+ qualityReduced: result ? !!result.qualityReduced : null,
330
+ });
331
+ }),
332
+ );
333
+
334
+ router.post(
335
+ "/stickers/bulk",
336
+ asyncRoute(async (req, res) => {
337
+ const body = bodyOf(req);
338
+ if (!ACTIONS.has(body.action)) throw new StickerError("INVALID_OPTIONS", { field: "action" });
339
+ if (body.confirm !== undefined && typeof body.confirm !== "boolean") {
340
+ throw new StickerError("INVALID_OPTIONS", { field: "confirm" });
341
+ }
342
+ const ids = parseIds(body.ids, EXPORT_MAX_IDS);
343
+ const who = panelOwner();
344
+ if (body.action === "favorite" || body.action === "unfavorite") {
345
+ res.json(library.setFavorite(who, ids, body.action === "favorite"));
346
+ return;
347
+ }
348
+ if (body.action === "touch") {
349
+ res.json(library.touch(who, ids));
350
+ return;
351
+ }
352
+ if (body.action === "delete") {
353
+ let affected = 0;
354
+ const skipped = [];
355
+ for (const id of ids) {
356
+ try {
357
+ const result = library.deleteStickers(who, [id], { confirm: body.confirm === true });
358
+ affected += result.deleted.length;
359
+ } catch (error) {
360
+ if (
361
+ error instanceof StickerError &&
362
+ (error.code === "IN_USE" || error.code === "NOT_FOUND")
363
+ ) {
364
+ skipped.push({ id, code: error.code });
365
+ continue;
366
+ }
367
+ throw error;
368
+ }
369
+ }
370
+ res.json({ affected, skipped });
371
+ return;
372
+ }
373
+ if (typeof body.packId !== "string" || !ID_RE.test(body.packId)) {
374
+ throw new StickerError("INVALID_OPTIONS", { field: "packId" });
375
+ }
376
+ if (
377
+ body.fromPackId != null &&
378
+ (typeof body.fromPackId !== "string" || !ID_RE.test(body.fromPackId))
379
+ ) {
380
+ throw new StickerError("INVALID_OPTIONS", { field: "fromPackId" });
381
+ }
382
+ try {
383
+ if (body.action === "addToPack") res.json(library.addToPack(who, body.packId, ids));
384
+ else if (body.action === "removeFromPack") {
385
+ res.json(library.removeFromPack(who, body.packId, ids));
386
+ } else {
387
+ res.json(library.moveToPack(who, ids, body.packId, { fromPackId: body.fromPackId }));
388
+ }
389
+ } catch (error) {
390
+ asPackError(error);
391
+ }
392
+ }),
393
+ );
394
+
395
+ router.post(
396
+ "/stickers/export",
397
+ asyncRoute(async (req, res) => {
398
+ const body = bodyOf(req);
399
+ if (body.format !== "webp" && body.format !== "png") {
400
+ throw new StickerError("INVALID_OPTIONS", { field: "format" });
401
+ }
402
+ const ids = parseIds(body.ids, EXPORT_MAX_IDS);
403
+ const archive = await studio().exportZip(panelOwner(), ids, body.format);
404
+ res.set("Content-Type", "application/zip");
405
+ res.set("Content-Disposition", contentDisposition("stickers.zip"));
406
+ res.send(archive);
407
+ }),
408
+ );
409
+
410
+ router.post(
411
+ "/stickers/send",
412
+ asyncRoute(async (req, res) => {
413
+ const body = bodyOf(req);
414
+ const ids = parseIds(body.ids, SEND_MAX_IDS);
415
+ const jid = normalizeJid(typeof body.jid === "string" ? body.jid : "");
416
+ if (!jid || !JID_RE.test(jid)) throw new StickerError("INVALID_OPTIONS", { field: "jid" });
417
+ const sock = currentSocket();
418
+ if (!sock) throw new StickerError("NOT_CONNECTED");
419
+ res.json(await studio().sendStickers(panelOwner(), ids, jid, sock));
420
+ }),
421
+ );
422
+
423
+ router.get(
424
+ "/stickers/:id/file",
425
+ asyncRoute(async (req, res) => {
426
+ const buffer = library.readStickerFile(panelOwner(), requireStickerId(req.params.id));
427
+ // Private, and revalidated on every load. Express still answers a matching
428
+ // If-None-Match with 304, so a reload does not resend the bytes.
429
+ res.set("Cache-Control", "private, no-cache");
430
+ res.set("Content-Type", "image/webp");
431
+ res.send(buffer);
432
+ }),
433
+ );
434
+
435
+ router.get(
436
+ "/stickers/:id/thumb",
437
+ asyncRoute(async (req, res) => {
438
+ const buffer = library.readThumbnail(panelOwner(), requireStickerId(req.params.id));
439
+ res.set("Cache-Control", "private, no-cache");
440
+ res.set("Content-Type", "image/webp");
441
+ res.send(buffer);
442
+ }),
443
+ );
444
+
445
+ router.get(
446
+ "/stickers/:id/export",
447
+ asyncRoute(async (req, res) => {
448
+ const format = req.query.format;
449
+ if (format !== "png" && format !== "webp" && format !== "gif") {
450
+ throw new StickerError("INVALID_OPTIONS", { field: "format" });
451
+ }
452
+ const out = await studio().exportImage(panelOwner(), requireStickerId(req.params.id), format);
453
+ res.set("Content-Type", out.mime);
454
+ res.set("Content-Disposition", contentDisposition(out.fileName));
455
+ if (format === "png" && out.animated) res.set("X-Levix-Animated", "1");
456
+ res.send(out.buffer);
457
+ }),
458
+ );
459
+
460
+ router.patch(
461
+ "/stickers/:id",
462
+ asyncRoute(async (req, res) => {
463
+ const body = bodyOf(req);
464
+ const patch = {};
465
+ if (body.name !== undefined) {
466
+ if (typeof body.name !== "string")
467
+ throw new StickerError("INVALID_OPTIONS", { field: "name" });
468
+ patch.name = body.name;
469
+ }
470
+ if (body.favorite !== undefined) {
471
+ if (typeof body.favorite !== "boolean") {
472
+ throw new StickerError("INVALID_OPTIONS", { field: "favorite" });
473
+ }
474
+ patch.favorite = body.favorite;
475
+ }
476
+ res.json(library.updateSticker(panelOwner(), requireStickerId(req.params.id), patch));
477
+ }),
478
+ );
479
+
480
+ router.delete(
481
+ "/stickers/:id",
482
+ asyncRoute(async (req, res) => {
483
+ const confirm = req.query.confirm === "1";
484
+ res.json(library.deleteStickers(panelOwner(), [requireStickerId(req.params.id)], { confirm }));
485
+ }),
486
+ );
487
+
488
+ router.get(
489
+ "/sticker-packs",
490
+ asyncRoute(async (_req, res) => {
491
+ res.json({ packs: library.listPacks(panelOwner()) });
492
+ }),
493
+ );
494
+
495
+ router.post(
496
+ "/sticker-packs",
497
+ asyncRoute(async (req, res) => {
498
+ const body = bodyOf(req);
499
+ if (typeof body.name !== "string") throw new StickerError("INVALID_NAME");
500
+ res.status(201).json(library.createPack(panelOwner(), body.name));
501
+ }),
502
+ );
503
+
504
+ router.get(
505
+ "/sticker-packs/:id",
506
+ asyncRoute(async (req, res) => {
507
+ try {
508
+ res.json(library.getPack(panelOwner(), requireStickerId(req.params.id)));
509
+ } catch (error) {
510
+ asPackError(error);
511
+ }
512
+ }),
513
+ );
514
+
515
+ router.patch(
516
+ "/sticker-packs/:id",
517
+ asyncRoute(async (req, res) => {
518
+ const body = bodyOf(req);
519
+ if (typeof body.name !== "string") throw new StickerError("INVALID_NAME");
520
+ try {
521
+ res.json(library.updatePack(panelOwner(), requireStickerId(req.params.id), body.name));
522
+ } catch (error) {
523
+ asPackError(error);
524
+ }
525
+ }),
526
+ );
527
+
528
+ router.delete(
529
+ "/sticker-packs/:id",
530
+ asyncRoute(async (req, res) => {
531
+ try {
532
+ res.json(
533
+ library.deletePack(panelOwner(), requireStickerId(req.params.id), {
534
+ deleteStickers: req.query.deleteStickers === "1",
535
+ }),
536
+ );
537
+ } catch (error) {
538
+ asPackError(error);
539
+ }
540
+ }),
541
+ );
542
+
543
+ router.put(
544
+ "/sticker-packs/:id/order",
545
+ asyncRoute(async (req, res) => {
546
+ const ids = parseIds(bodyOf(req).ids, 100_000, { allowEmpty: true });
547
+ try {
548
+ res.json(library.reorderPack(panelOwner(), requireStickerId(req.params.id), ids));
549
+ } catch (error) {
550
+ asPackError(error);
551
+ }
552
+ }),
553
+ );
554
+
555
+ router.post(
556
+ "/sticker-packs/:id/merge",
557
+ asyncRoute(async (req, res) => {
558
+ const intoPackId = bodyOf(req).intoPackId;
559
+ if (typeof intoPackId !== "string" || !ID_RE.test(intoPackId)) {
560
+ throw new StickerError("INVALID_OPTIONS", { field: "intoPackId" });
561
+ }
562
+ try {
563
+ res.json(library.mergePacks(panelOwner(), requireStickerId(req.params.id), intoPackId));
564
+ } catch (error) {
565
+ asPackError(error);
566
+ }
567
+ }),
568
+ );
569
+
570
+ export default router;