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,712 @@
1
+ // The sticker library. Every call takes an owner ({ key }) and treats another
2
+ // owner's ids as missing. `key` is opaque: a sticker_owners id for a WhatsApp
3
+ // sender, or any string a caller passes. Files are content-addressed by the
4
+ // WebP's sha256 under <data>/stickers/<sha[0..2]>/ and are removed only when
5
+ // no row, of any owner, still points at that hash.
6
+ //
7
+ // The write-then-insert and the delete-then-unlink pairs are synchronous, with
8
+ // no await between them, so two requests cannot interleave halfway. A crash
9
+ // after the commit and before the unlink leaves an orphan file; the reverse
10
+ // would leave a row whose bytes are gone.
11
+
12
+ const crypto = require("node:crypto");
13
+ const fs = require("node:fs");
14
+ const path = require("node:path");
15
+
16
+ const { dataPath } = require("../config/paths.cjs");
17
+ const settings = require("../config/settings.cjs");
18
+ const store = require("../db/store.cjs");
19
+ const logger = require("../utils/logger.cjs");
20
+ const { StickerError } = require("./errors.cjs");
21
+ const webp = require("./webp.cjs");
22
+ const {
23
+ PACK_NAME_MAX,
24
+ PACK_SUBCOMMANDS,
25
+ PACKS_MAX_PER_OWNER,
26
+ STICKER_NAME_MAX,
27
+ } = require("./limits.cjs");
28
+
29
+ const SOURCES = new Set(["BOT_COMMAND", "PANEL_UPLOAD", "WHATSAPP_STICKER", "MEDIA_HUB"]);
30
+ const ID_RE = /^[0-9a-f]{16}$/;
31
+ const PACK_NAME_RE = /^[\p{L}\p{N}\p{M} _-]+$/u;
32
+ const SORTS = new Set(["newest", "oldest", "name", "recent"]);
33
+ const FILTERS = new Set(["all", "favorites", "recent", "animated", "static"]);
34
+ const DEFAULT_LIBRARY_LIMIT = 1000;
35
+ const MAX_BATCH = 100_000;
36
+ let epoch = 0;
37
+
38
+ function assertEpoch(captured) {
39
+ if (captured !== undefined && captured !== epoch) throw new StickerError("CANCELLED");
40
+ }
41
+
42
+ const RESERVED_PACK_NAMES = new Set();
43
+ for (const words of Object.values(PACK_SUBCOMMANDS)) {
44
+ for (const word of words) {
45
+ RESERVED_PACK_NAMES.add(
46
+ String(word).normalize("NFKC").replace(/\s+/g, " ").trim().toLowerCase(),
47
+ );
48
+ }
49
+ }
50
+
51
+ function newId() {
52
+ return crypto.randomBytes(8).toString("hex");
53
+ }
54
+
55
+ function libraryLimit() {
56
+ try {
57
+ const value = settings.get("sticker_library_limit");
58
+ if (Number.isFinite(value) && value >= 1) return value;
59
+ } catch {
60
+ // A broken settings read must not refuse every save.
61
+ }
62
+ return DEFAULT_LIBRARY_LIMIT;
63
+ }
64
+
65
+ function canonicalContent(buffer) {
66
+ if (
67
+ buffer.length < 12 ||
68
+ buffer.toString("ascii", 0, 4) !== "RIFF" ||
69
+ buffer.toString("ascii", 8, 12) !== "WEBP"
70
+ )
71
+ return buffer;
72
+ try {
73
+ return webp.canonical(buffer);
74
+ } catch (error) {
75
+ // Old library callers and API fixtures can provide opaque bytes with a
76
+ // WebP-looking header. Keep their existing storage behavior. The studio
77
+ // validates actual WhatsApp media before it reaches this function.
78
+ if (error instanceof StickerError && error.code === "CORRUPT") return buffer;
79
+ throw error;
80
+ }
81
+ }
82
+
83
+ function bind(owner) {
84
+ if (!owner || typeof owner.key !== "string" || !owner.key || owner.key.length > 128) {
85
+ throw new StickerError("INVALID_OPTIONS", { field: "owner" });
86
+ }
87
+ return { key: owner.key };
88
+ }
89
+
90
+ function eachId(ids, field = "ids") {
91
+ if (!Array.isArray(ids) || ids.length > MAX_BATCH) {
92
+ throw new StickerError("INVALID_OPTIONS", { field });
93
+ }
94
+ for (const id of ids) {
95
+ if (typeof id !== "string" || !ID_RE.test(id)) {
96
+ throw new StickerError("INVALID_OPTIONS", { field });
97
+ }
98
+ }
99
+ return ids;
100
+ }
101
+
102
+ function sanitizeStickerName(raw) {
103
+ if (raw == null) return "";
104
+ if (typeof raw !== "string") throw new StickerError("INVALID_OPTIONS", { field: "name" });
105
+ const text = raw.replace(/\p{Cc}/gu, "").trim();
106
+ return [...text].slice(0, STICKER_NAME_MAX).join("");
107
+ }
108
+
109
+ function normalizePackName(raw) {
110
+ if (typeof raw !== "string") throw new StickerError("INVALID_NAME");
111
+ const name = raw.normalize("NFKC").replace(/\s+/g, " ").trim();
112
+ const length = [...name].length;
113
+ if (length < 1 || length > PACK_NAME_MAX || !PACK_NAME_RE.test(name)) {
114
+ throw new StickerError("INVALID_NAME");
115
+ }
116
+ const nameKey = name.toLowerCase();
117
+ if (RESERVED_PACK_NAMES.has(nameKey)) {
118
+ throw new StickerError("INVALID_NAME", { reason: "reserved" });
119
+ }
120
+ return { name, nameKey };
121
+ }
122
+
123
+ function isUnique(error) {
124
+ return /UNIQUE constraint failed/i.test(String(error?.message || ""));
125
+ }
126
+
127
+ function storageError(error) {
128
+ if (error?.code === "EACCES" || error?.code === "ENOSPC" || error?.code === "EROFS") {
129
+ return new StickerError("STORAGE_UNAVAILABLE", {}, { cause: error });
130
+ }
131
+ return error;
132
+ }
133
+
134
+ function bucket(sha) {
135
+ return dataPath("stickers", sha.slice(0, 2));
136
+ }
137
+
138
+ function webpPath(sha) {
139
+ return path.join(bucket(sha), `${sha}.webp`);
140
+ }
141
+
142
+ function thumbPath(sha) {
143
+ return path.join(bucket(sha), `${sha}.thumb.webp`);
144
+ }
145
+
146
+ function writeAtomic(target, buffer) {
147
+ const dir = path.dirname(target);
148
+ const tmp = path.join(
149
+ dir,
150
+ `.${path.basename(target)}.${crypto.randomBytes(6).toString("hex")}.tmp`,
151
+ );
152
+ try {
153
+ // Inside the catch: a read-only stickers directory fails here (EACCES),
154
+ // and that has to become STORAGE_UNAVAILABLE rather than a raw fs error.
155
+ fs.mkdirSync(dir, { recursive: true });
156
+ const fd = fs.openSync(tmp, "w", 0o644);
157
+ try {
158
+ fs.writeSync(fd, buffer);
159
+ fs.fsyncSync(fd);
160
+ } finally {
161
+ fs.closeSync(fd);
162
+ }
163
+ fs.renameSync(tmp, target);
164
+ } catch (error) {
165
+ try {
166
+ fs.rmSync(tmp, { force: true });
167
+ } catch {
168
+ // The original error is the one the caller needs.
169
+ }
170
+ throw storageError(error);
171
+ }
172
+ }
173
+
174
+ function writeIfAbsent(target, buffer) {
175
+ if (fs.existsSync(target)) return;
176
+ writeAtomic(target, buffer);
177
+ }
178
+
179
+ function rmQuiet(file) {
180
+ try {
181
+ fs.rmSync(file, { force: true });
182
+ } catch (error) {
183
+ logger.warn({ err: error }, "[Stickers] failed to remove an unreferenced file");
184
+ }
185
+ }
186
+
187
+ function removeIfOrphan(sha) {
188
+ if (!sha || store.stickerShaCount(sha) > 0) return;
189
+ rmQuiet(webpPath(sha));
190
+ rmQuiet(thumbPath(sha));
191
+ try {
192
+ fs.rmdirSync(bucket(sha));
193
+ } catch {
194
+ // The bucket still holds another hash, or is already gone.
195
+ }
196
+ }
197
+
198
+ function versionOf(sha) {
199
+ return String(sha || "").slice(0, 12);
200
+ }
201
+
202
+ function stickerDto(row, packIds) {
203
+ const version = versionOf(row.sha256);
204
+ return {
205
+ id: row.id,
206
+ name: row.name,
207
+ animated: !!row.animated,
208
+ width: row.width,
209
+ height: row.height,
210
+ durationMs: row.duration_ms,
211
+ fileSize: row.file_size,
212
+ sourceMime: row.source_mime,
213
+ source: row.source,
214
+ favorite: !!row.is_favorite,
215
+ createdAt: row.created_at,
216
+ updatedAt: row.updated_at,
217
+ lastUsedAt: row.last_used_at,
218
+ packIds: packIds || [],
219
+ url: `/dashboard/api/stickers/${row.id}/file?v=${version}`,
220
+ thumbUrl: `/dashboard/api/stickers/${row.id}/thumb?v=${version}`,
221
+ };
222
+ }
223
+
224
+ function packDto(row) {
225
+ const coverUrl =
226
+ row.cover_id && row.cover_sha
227
+ ? `/dashboard/api/stickers/${row.cover_id}/thumb?v=${versionOf(row.cover_sha)}`
228
+ : null;
229
+ return {
230
+ id: row.id,
231
+ name: row.name,
232
+ count: row.item_count,
233
+ coverUrl,
234
+ createdAt: row.created_at,
235
+ updatedAt: row.updated_at,
236
+ };
237
+ }
238
+
239
+ function present(bound, row) {
240
+ if (!row) throw new StickerError("NOT_FOUND");
241
+ const membership = store.stickerPackMembership(bound.key, [row.id]);
242
+ return stickerDto(row, membership.get(row.id) || []);
243
+ }
244
+
245
+ function presentMany(bound, rows) {
246
+ if (!rows.length) return [];
247
+ const membership = store.stickerPackMembership(
248
+ bound.key,
249
+ rows.map((row) => row.id),
250
+ );
251
+ return rows.map((row) => stickerDto(row, membership.get(row.id) || []));
252
+ }
253
+
254
+ function requireStickerRow(bound, id) {
255
+ if (typeof id !== "string" || !ID_RE.test(id)) {
256
+ throw new StickerError("INVALID_OPTIONS", { field: "id" });
257
+ }
258
+ const row = store.stickerGet(bound.key, id);
259
+ if (!row) throw new StickerError("NOT_FOUND");
260
+ return row;
261
+ }
262
+
263
+ function requirePack(bound, id) {
264
+ if (typeof id !== "string" || !ID_RE.test(id)) {
265
+ throw new StickerError("INVALID_OPTIONS", { field: "packId" });
266
+ }
267
+ const pack = store.stickerPackGet(bound.key, id);
268
+ if (!pack) throw new StickerError("NOT_FOUND");
269
+ return pack;
270
+ }
271
+
272
+ function fileNameFor(sticker, ext) {
273
+ const raw = sticker?.name ? String(sticker.name) : sticker.id;
274
+ const cleaned = raw
275
+ .replace(/[\\/:*?"<>|]/g, " ")
276
+ .replace(/\p{Cc}/gu, " ")
277
+ .replace(/\s+/g, " ")
278
+ .trim();
279
+ const base = [...cleaned].slice(0, STICKER_NAME_MAX).join("") || sticker.id;
280
+ return `${base}.${ext}`;
281
+ }
282
+
283
+ function integerOrNull(value) {
284
+ if (value == null || value === "") return null;
285
+ const n = Number(value);
286
+ if (!Number.isFinite(n) || n < 0) return null;
287
+ return Math.round(n);
288
+ }
289
+
290
+ function saveSticker(owner, input) {
291
+ assertEpoch(input?.epoch);
292
+ const bound = bind(owner);
293
+ const sourceBuffer = input?.buffer;
294
+ if (!Buffer.isBuffer(sourceBuffer) || sourceBuffer.length === 0)
295
+ throw new StickerError("NO_MEDIA");
296
+ const buffer = canonicalContent(sourceBuffer);
297
+ if (!SOURCES.has(input.source)) throw new StickerError("INVALID_OPTIONS", { field: "source" });
298
+ const name = sanitizeStickerName(input.name);
299
+ const sha = crypto.createHash("sha256").update(buffer).digest("hex");
300
+ const thumb =
301
+ Buffer.isBuffer(input.thumbBuffer) && input.thumbBuffer.length ? input.thumbBuffer : null;
302
+
303
+ const existing = store.stickerFindBySha(bound.key, sha);
304
+ if (existing) {
305
+ // The row won the race against a deleted file. Put the bytes back, still
306
+ // one copy, and hand the original sticker back.
307
+ writeIfAbsent(webpPath(sha), buffer);
308
+ if (thumb) writeIfAbsent(thumbPath(sha), thumb);
309
+ return {
310
+ sticker: present(bound, store.stickerGet(bound.key, existing.id)),
311
+ created: false,
312
+ };
313
+ }
314
+
315
+ const limit = libraryLimit();
316
+ if (store.stickerCount(bound.key) >= limit) {
317
+ throw new StickerError("LIBRARY_FULL", { limit });
318
+ }
319
+
320
+ const id = newId();
321
+ const now = Date.now();
322
+ try {
323
+ writeIfAbsent(webpPath(sha), buffer);
324
+ if (thumb) writeIfAbsent(thumbPath(sha), thumb);
325
+ store.stickerInsert({
326
+ id,
327
+ owner: bound.key,
328
+ sha256: sha,
329
+ name,
330
+ animated: !!input.animated,
331
+ width: integerOrNull(input.width),
332
+ height: integerOrNull(input.height),
333
+ durationMs: integerOrNull(input.durationMs),
334
+ fileSize: buffer.length,
335
+ source: input.source,
336
+ sourceMime: input.sourceMime == null ? null : String(input.sourceMime),
337
+ favorite: 0,
338
+ createdAt: now,
339
+ updatedAt: now,
340
+ lastUsedAt: null,
341
+ });
342
+ } catch (error) {
343
+ if (isUnique(error)) {
344
+ const raced = store.stickerFindBySha(bound.key, sha);
345
+ if (raced) return { sticker: present(bound, raced), created: false };
346
+ }
347
+ removeIfOrphan(sha);
348
+ throw storageError(error);
349
+ }
350
+ return { sticker: present(bound, store.stickerGet(bound.key, id)), created: true };
351
+ }
352
+
353
+ function hasRoom(owner) {
354
+ const bound = bind(owner);
355
+ return store.stickerCount(bound.key) < libraryLimit();
356
+ }
357
+
358
+ function findStickerByContent(owner, buffer) {
359
+ const bound = bind(owner);
360
+ if (!Buffer.isBuffer(buffer) || !buffer.length) throw new StickerError("NOT_FOUND");
361
+ const sha = crypto.createHash("sha256").update(canonicalContent(buffer)).digest("hex");
362
+ return present(bound, store.stickerFindBySha(bound.key, sha));
363
+ }
364
+
365
+ function getSticker(owner, id) {
366
+ const bound = bind(owner);
367
+ return present(bound, requireStickerRow(bound, id));
368
+ }
369
+
370
+ function readBytes(owner, id, which) {
371
+ const bound = bind(owner);
372
+ const row = requireStickerRow(bound, id);
373
+ const file = which === "thumb" ? thumbPath(row.sha256) : webpPath(row.sha256);
374
+ try {
375
+ return fs.readFileSync(file);
376
+ } catch (error) {
377
+ logger.error({ err: error, stickerId: id }, "[Stickers] library row has no file");
378
+ throw new StickerError("NOT_FOUND");
379
+ }
380
+ }
381
+
382
+ function readStickerFile(owner, id) {
383
+ return readBytes(owner, id, "file");
384
+ }
385
+
386
+ function readThumbnail(owner, id) {
387
+ return readBytes(owner, id, "thumb");
388
+ }
389
+
390
+ function listStickers(owner, query = {}) {
391
+ const bound = bind(owner);
392
+ const sort = query.sort || "newest";
393
+ const filter = query.filter || "all";
394
+ if (!SORTS.has(sort)) throw new StickerError("INVALID_OPTIONS", { field: "sort" });
395
+ if (!FILTERS.has(filter)) throw new StickerError("INVALID_OPTIONS", { field: "filter" });
396
+ const pack = query.pack ?? null;
397
+ if (pack != null && pack !== "none" && (typeof pack !== "string" || !ID_RE.test(pack))) {
398
+ throw new StickerError("INVALID_OPTIONS", { field: "pack" });
399
+ }
400
+ const limit = query.limit == null ? 60 : query.limit;
401
+ const offset = query.offset == null ? 0 : query.offset;
402
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
403
+ throw new StickerError("INVALID_OPTIONS", { field: "limit" });
404
+ }
405
+ if (!Number.isInteger(offset) || offset < 0) {
406
+ throw new StickerError("INVALID_OPTIONS", { field: "offset" });
407
+ }
408
+ const q = query.q == null ? "" : String(query.q);
409
+ if (q.length > 200) throw new StickerError("INVALID_OPTIONS", { field: "q" });
410
+ const { rows, total } = store.stickerQuery(bound.key, {
411
+ q,
412
+ sort,
413
+ filter,
414
+ pack,
415
+ limit,
416
+ offset,
417
+ });
418
+ return { items: presentMany(bound, rows), total };
419
+ }
420
+
421
+ function updateSticker(owner, id, patch = {}) {
422
+ const bound = bind(owner);
423
+ const row = requireStickerRow(bound, id);
424
+ const fields = {};
425
+ if (patch.name !== undefined) fields.name = sanitizeStickerName(patch.name);
426
+ if (patch.favorite !== undefined) {
427
+ if (typeof patch.favorite !== "boolean") {
428
+ throw new StickerError("INVALID_OPTIONS", { field: "favorite" });
429
+ }
430
+ fields.isFavorite = patch.favorite;
431
+ }
432
+ if (Object.keys(fields).length) {
433
+ fields.updatedAt = Date.now();
434
+ store.stickerUpdate(row.id, fields);
435
+ }
436
+ return present(bound, store.stickerGet(bound.key, row.id));
437
+ }
438
+
439
+ function deleteStickers(owner, ids, options = {}) {
440
+ const bound = bind(owner);
441
+ const list = eachId(ids);
442
+ const rows = list.map((id) => requireStickerRow(bound, id));
443
+ if (!options.confirm) {
444
+ for (const row of rows) {
445
+ const packs = store.stickerPacksUsing(bound.key, row.id);
446
+ if (packs.length) throw new StickerError("IN_USE", { packs });
447
+ }
448
+ }
449
+ const shas = store.withImmediateTransaction(() => {
450
+ const touched = new Set();
451
+ for (const row of rows) {
452
+ for (const pack of store.stickerPackIdsOf(row.id)) touched.add(pack.pack_id);
453
+ }
454
+ for (const row of rows) store.stickerDelete(row.id);
455
+ for (const packId of touched) store.stickerPackRenumber(packId);
456
+ return rows.map((row) => row.sha256);
457
+ });
458
+ for (const sha of new Set(shas)) removeIfOrphan(sha);
459
+ return { deleted: rows.map((row) => row.id) };
460
+ }
461
+
462
+ function applyEach(owner, ids, fn) {
463
+ const bound = bind(owner);
464
+ const list = eachId(ids);
465
+ let affected = 0;
466
+ const skipped = [];
467
+ for (const id of list) {
468
+ const row = store.stickerGet(bound.key, id);
469
+ if (!row) {
470
+ skipped.push({ id, code: "NOT_FOUND" });
471
+ continue;
472
+ }
473
+ if (fn(row)) affected += 1;
474
+ }
475
+ return { affected, skipped };
476
+ }
477
+
478
+ function setFavorite(owner, ids, favorite) {
479
+ if (typeof favorite !== "boolean") {
480
+ throw new StickerError("INVALID_OPTIONS", { field: "favorite" });
481
+ }
482
+ const now = Date.now();
483
+ return applyEach(owner, ids, (row) => {
484
+ store.stickerUpdate(row.id, { isFavorite: favorite, updatedAt: now });
485
+ return true;
486
+ });
487
+ }
488
+
489
+ function touch(owner, ids) {
490
+ const now = Date.now();
491
+ return applyEach(owner, ids, (row) => {
492
+ store.stickerUpdate(row.id, { lastUsedAt: now });
493
+ return true;
494
+ });
495
+ }
496
+
497
+ function createPack(owner, name) {
498
+ const bound = bind(owner);
499
+ const parsed = normalizePackName(name);
500
+ if (store.stickerPackByKey(bound.key, parsed.nameKey)) {
501
+ throw new StickerError("PACK_EXISTS", { name: parsed.name });
502
+ }
503
+ if (store.stickerPackCount(bound.key) >= PACKS_MAX_PER_OWNER) {
504
+ throw new StickerError("PACK_LIMIT", { limit: PACKS_MAX_PER_OWNER });
505
+ }
506
+ const now = Date.now();
507
+ const id = newId();
508
+ try {
509
+ store.stickerPackInsert({
510
+ id,
511
+ owner: bound.key,
512
+ name: parsed.name,
513
+ nameKey: parsed.nameKey,
514
+ createdAt: now,
515
+ updatedAt: now,
516
+ });
517
+ } catch (error) {
518
+ if (isUnique(error)) throw new StickerError("PACK_EXISTS", { name: parsed.name });
519
+ throw error;
520
+ }
521
+ return packDto(store.stickerPackGet(bound.key, id));
522
+ }
523
+
524
+ function listPacks(owner) {
525
+ const bound = bind(owner);
526
+ return store.stickerPackList(bound.key).map(packDto);
527
+ }
528
+
529
+ function getPack(owner, id) {
530
+ const bound = bind(owner);
531
+ const pack = requirePack(bound, id);
532
+ const rows = store.stickerPackItems(pack.id);
533
+ return { pack: packDto(pack), items: presentMany(bound, rows) };
534
+ }
535
+
536
+ function updatePack(owner, id, name) {
537
+ const bound = bind(owner);
538
+ const pack = requirePack(bound, id);
539
+ const parsed = normalizePackName(name);
540
+ const other = store.stickerPackByKey(bound.key, parsed.nameKey);
541
+ if (other && other.id !== pack.id) throw new StickerError("PACK_EXISTS", { name: parsed.name });
542
+ store.stickerPackRename(pack.id, parsed.name, parsed.nameKey, Date.now());
543
+ return packDto(store.stickerPackGet(bound.key, pack.id));
544
+ }
545
+
546
+ function deletePack(owner, id, options = {}) {
547
+ const bound = bind(owner);
548
+ const pack = requirePack(bound, id);
549
+ const removed = store.withImmediateTransaction(() => {
550
+ const exclusive = options.deleteStickers ? store.stickerPackExclusive(pack.id) : [];
551
+ store.stickerPackDelete(pack.id);
552
+ for (const item of exclusive) store.stickerDelete(item.id);
553
+ return exclusive;
554
+ });
555
+ for (const item of removed) removeIfOrphan(item.sha256);
556
+ return { deletedPack: pack.id, deletedStickers: removed.map((item) => item.id) };
557
+ }
558
+
559
+ function findPackByName(owner, name) {
560
+ const bound = bind(owner);
561
+ let parsed;
562
+ try {
563
+ parsed = normalizePackName(name);
564
+ } catch (error) {
565
+ if (error instanceof StickerError && error.code === "INVALID_NAME") return null;
566
+ throw error;
567
+ }
568
+ const row = store.stickerPackByKey(bound.key, parsed.nameKey);
569
+ return row ? packDto(row) : null;
570
+ }
571
+
572
+ function membershipResult(bound, packId, ids, mutate) {
573
+ const list = eachId(ids);
574
+ return store.withImmediateTransaction(() => {
575
+ const pack = requirePack(bound, packId);
576
+ let affected = 0;
577
+ const skipped = [];
578
+ const now = Date.now();
579
+ for (const id of list) {
580
+ const sticker = store.stickerGet(bound.key, id);
581
+ if (!sticker) {
582
+ skipped.push({ id, code: "NOT_FOUND" });
583
+ continue;
584
+ }
585
+ if (mutate(pack, sticker, now)) affected += 1;
586
+ }
587
+ return { affected, skipped };
588
+ });
589
+ }
590
+
591
+ function addToPack(owner, packId, ids, options = {}) {
592
+ assertEpoch(options.epoch);
593
+ const bound = bind(owner);
594
+ return membershipResult(bound, packId, ids, (pack, sticker, now) =>
595
+ store.stickerPackAdd(pack.id, sticker.id, now),
596
+ );
597
+ }
598
+
599
+ function removeFromPack(owner, packId, ids) {
600
+ const bound = bind(owner);
601
+ return membershipResult(bound, packId, ids, (pack, sticker) =>
602
+ store.stickerPackRemoveItem(pack.id, sticker.id),
603
+ );
604
+ }
605
+
606
+ function moveToPack(owner, ids, packId, options = {}) {
607
+ const bound = bind(owner);
608
+ const list = eachId(ids);
609
+ const fromPackId = options.fromPackId;
610
+ return store.withImmediateTransaction(() => {
611
+ const pack = requirePack(bound, packId);
612
+ const from = fromPackId == null ? null : requirePack(bound, fromPackId);
613
+ let affected = 0;
614
+ const skipped = [];
615
+ const now = Date.now();
616
+ for (const id of list) {
617
+ const sticker = store.stickerGet(bound.key, id);
618
+ if (!sticker) {
619
+ skipped.push({ id, code: "NOT_FOUND" });
620
+ continue;
621
+ }
622
+ if (from) {
623
+ if (from.id !== pack.id) store.stickerPackRemoveItem(from.id, sticker.id);
624
+ } else {
625
+ for (const membership of store.stickerPackIdsOf(sticker.id)) {
626
+ if (membership.pack_id === pack.id) continue;
627
+ if (!store.stickerPackGet(bound.key, membership.pack_id)) continue;
628
+ store.stickerPackRemoveItem(membership.pack_id, sticker.id);
629
+ }
630
+ }
631
+ store.stickerPackAdd(pack.id, sticker.id, now);
632
+ affected += 1;
633
+ }
634
+ return { affected, skipped };
635
+ });
636
+ }
637
+
638
+ function reorderPack(owner, packId, ids) {
639
+ const bound = bind(owner);
640
+ const list = eachId(ids);
641
+ store.withImmediateTransaction(() => {
642
+ const pack = requirePack(bound, packId);
643
+ if (!store.stickerPackReorder(pack.id, list)) {
644
+ throw new StickerError("INVALID_OPTIONS", { field: "ids" });
645
+ }
646
+ });
647
+ return { ok: true };
648
+ }
649
+
650
+ function mergePacks(owner, sourceId, intoPackId) {
651
+ const bound = bind(owner);
652
+ if (sourceId === intoPackId) throw new StickerError("INVALID_OPTIONS", { field: "intoPackId" });
653
+ const moved = store.withImmediateTransaction(() => {
654
+ const source = requirePack(bound, sourceId);
655
+ const target = requirePack(bound, intoPackId);
656
+ const items = store.stickerPackItems(source.id);
657
+ const now = Date.now();
658
+ let added = 0;
659
+ for (const item of items) {
660
+ if (store.stickerPackAdd(target.id, item.id, now)) added += 1;
661
+ }
662
+ store.stickerPackDelete(source.id);
663
+ store.stickerPackRenumber(target.id);
664
+ return added;
665
+ });
666
+ return { pack: packDto(store.stickerPackGet(bound.key, intoPackId)), moved };
667
+ }
668
+
669
+ function clearAll() {
670
+ require("./jobs.cjs").cancelAll();
671
+ epoch++;
672
+ store.stickerClearAll();
673
+ try {
674
+ fs.rmSync(dataPath("stickers"), { recursive: true, force: true });
675
+ } catch (error) {
676
+ logger.error({ err: error }, "[Stickers] failed to remove sticker files");
677
+ throw new StickerError("STORAGE_UNAVAILABLE", {}, { cause: error });
678
+ }
679
+ try {
680
+ require("./uploads.cjs").discardAll();
681
+ } catch (error) {
682
+ logger.warn({ err: error }, "[Stickers] failed to discard uploads");
683
+ }
684
+ }
685
+
686
+ module.exports = {
687
+ saveSticker,
688
+ hasRoom,
689
+ findStickerByContent,
690
+ getSticker,
691
+ readStickerFile,
692
+ readThumbnail,
693
+ listStickers,
694
+ updateSticker,
695
+ deleteStickers,
696
+ setFavorite,
697
+ touch,
698
+ createPack,
699
+ listPacks,
700
+ getPack,
701
+ updatePack,
702
+ deletePack,
703
+ findPackByName,
704
+ addToPack,
705
+ removeFromPack,
706
+ moveToPack,
707
+ reorderPack,
708
+ mergePacks,
709
+ clearAll,
710
+ epoch: () => epoch,
711
+ fileNameFor,
712
+ };