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
package/src/db/store.cjs CHANGED
@@ -14,8 +14,11 @@
14
14
  // handlers need the *same* singleton, and only a CJS module can be required
15
15
  // synchronously from both sides.
16
16
 
17
+ const crypto = require("node:crypto");
18
+
17
19
  const logger = require("../utils/logger.cjs");
18
- const { q, parseJson, sweepExpired, checkpoint, DB_PATH } = require("./db.cjs");
20
+ const normalizeJid = require("../utils/normalizeJid.cjs");
21
+ const { db, q, parseJson, sweepExpired, checkpoint, DB_PATH } = require("./db.cjs");
19
22
 
20
23
  const DAY_MS = 24 * 60 * 60 * 1000;
21
24
  const DEFAULT_FORWARD_TTL_DAYS = 30;
@@ -55,6 +58,13 @@ function migrateSecretsAtRest() {
55
58
 
56
59
  async function initStore() {
57
60
  sweepExpired();
61
+ try {
62
+ // Stale sticker uploads and half-finished conversions from a crash.
63
+ // The timer lives in uploads.cjs; this is the boot pass.
64
+ require("../stickers/uploads.cjs").sweepStale();
65
+ } catch (err) {
66
+ logger.error({ err }, "[Store] sticker temp sweep failed");
67
+ }
58
68
  try {
59
69
  migrateSecretsAtRest();
60
70
  } catch (err) {
@@ -164,9 +174,9 @@ function countGroups() {
164
174
 
165
175
  function upsertGroupDirectory(groupId, { subject = null, participantCount = null } = {}) {
166
176
  if (!groupId) return;
167
- const existing = q("SELECT subject, participant_count FROM group_directory WHERE group_id = ?").get(
168
- groupId,
169
- );
177
+ const existing = q(
178
+ "SELECT subject, participant_count FROM group_directory WHERE group_id = ?",
179
+ ).get(groupId);
170
180
  q(
171
181
  `INSERT INTO group_directory (group_id, subject, participant_count, updated_at)
172
182
  VALUES (?, ?, ?, ?)
@@ -183,9 +193,9 @@ function upsertGroupDirectory(groupId, { subject = null, participantCount = null
183
193
  }
184
194
 
185
195
  function getGroupDirectory(groupId) {
186
- return q("SELECT group_id, subject, participant_count, updated_at FROM group_directory WHERE group_id = ?").get(
187
- groupId,
188
- );
196
+ return q(
197
+ "SELECT group_id, subject, participant_count, updated_at FROM group_directory WHERE group_id = ?",
198
+ ).get(groupId);
189
199
  }
190
200
 
191
201
  function getAllGroupDirectory() {
@@ -373,6 +383,33 @@ function getLidForPn(pn) {
373
383
  return row ? row.lid : null;
374
384
  }
375
385
 
386
+ // Every LID stored for this phone. Writers persist the pn they are given
387
+ // (storeLidPnMapping); a device suffix is the only form normalizeJid folds
388
+ // onto the same number, so the lookup is an index read of that pn plus the
389
+ // `user:` prefix, not a scan of the table.
390
+ function getLidsForPn(pn) {
391
+ if (!pn) return [];
392
+ const found = new Map();
393
+ const consider = (rows) => {
394
+ for (const row of rows) {
395
+ if (!row?.lid || !row?.pn || found.has(row.lid)) continue;
396
+ if (normalizeJid(row.pn) !== pn && row.pn !== pn) continue;
397
+ found.set(row.lid, row.lid);
398
+ }
399
+ };
400
+ consider(q("SELECT lid, pn FROM lid_mapping WHERE pn = ?").all(pn));
401
+ if (!String(pn).includes(":")) {
402
+ const at = String(pn).lastIndexOf("@");
403
+ if (at > 0) {
404
+ const user = String(pn).slice(0, at);
405
+ consider(
406
+ q("SELECT lid, pn FROM lid_mapping WHERE pn >= ? AND pn < ?").all(`${user}:`, `${user};`),
407
+ );
408
+ }
409
+ }
410
+ return [...found.keys()];
411
+ }
412
+
376
413
  function getLidsForPns(pns) {
377
414
  const map = new Map();
378
415
  if (!pns?.length) return map;
@@ -411,9 +448,81 @@ function rowToUser(row) {
411
448
  firstSeen: row.first_seen,
412
449
  lastSeen: row.last_seen,
413
450
  displayName: row.display_name ?? null,
451
+ savedName: row.saved_name ?? null,
414
452
  };
415
453
  }
416
454
 
455
+ function isLidJid(value) {
456
+ return String(value || "").includes("@lid");
457
+ }
458
+
459
+ function isGroupJid(value) {
460
+ return String(value || "").endsWith("@g.us");
461
+ }
462
+
463
+ function asLidJid(value) {
464
+ if (!value) return null;
465
+ const raw = String(value).trim();
466
+ if (!raw) return null;
467
+ const local = raw.split(":")[0].split("@")[0];
468
+ if (!local) return null;
469
+ if (raw.includes("@lid") || (!raw.includes("@") && !/^\d{8,15}$/.test(local))) {
470
+ return `${local}@lid`;
471
+ }
472
+ return null;
473
+ }
474
+
475
+ function asPnJid(value) {
476
+ const phone = digitsOf(value);
477
+ if (!phone || phone.length < 8 || phone.length > 15) return null;
478
+ return `${phone}@s.whatsapp.net`;
479
+ }
480
+
481
+ function personName(value) {
482
+ const text = String(value || "").trim();
483
+ if (!text || text.includes("@")) return null;
484
+ return text.slice(0, 128);
485
+ }
486
+
487
+ function lidLocalPart(value) {
488
+ if (!isLidJid(value)) return null;
489
+ return String(value).split("@")[0].split(":")[0];
490
+ }
491
+
492
+ /**
493
+ * Find the existing user_metadata row for a person named by any mix of JID,
494
+ * LID and phone, including the lid_mapping table, so a LID and a phone JID
495
+ * of the same person land on one record.
496
+ */
497
+ function resolveExistingUser(userData) {
498
+ const candidates = [];
499
+ const add = (value) => {
500
+ if (value && !candidates.includes(value)) candidates.push(value);
501
+ };
502
+ add(userData?.jid);
503
+ add(userData?.lid);
504
+ add(userData?.phone);
505
+ if (userData?.jid) {
506
+ add(getPnForLid(userData.jid));
507
+ add(getLidForPn(userData.jid));
508
+ if (!isLidJid(userData.jid)) add(asPnJid(userData.jid));
509
+ }
510
+ if (userData?.lid) {
511
+ add(getPnForLid(userData.lid));
512
+ add(asLidJid(userData.lid));
513
+ }
514
+ if (userData?.phone) {
515
+ const pnJid = asPnJid(userData.phone);
516
+ add(pnJid);
517
+ if (pnJid) add(getLidForPn(pnJid));
518
+ }
519
+ for (const identifier of candidates) {
520
+ const found = getUserMetadata(identifier);
521
+ if (found) return found;
522
+ }
523
+ return null;
524
+ }
525
+
417
526
  function userRow(jid) {
418
527
  return q("SELECT * FROM user_metadata WHERE user_jid = ?").get(jid);
419
528
  }
@@ -427,37 +536,53 @@ function userRow(jid) {
427
536
  * next message. Same story for `lid` / `phone` / `displayName`: a missing
428
537
  * field keeps whatever we already knew instead of nulling it out.
429
538
  *
430
- * @param {object} userData - { jid, lid?, phone?, isOwner?, isAdmin?, displayName? }
539
+ * @param {object} userData - { jid, lid?, phone?, isOwner?, isAdmin?, displayName?, savedName? }
431
540
  */
432
541
  function saveUserMetadata(userData) {
433
542
  if (!userData?.jid) return;
434
543
  const now = Date.now();
435
- const existing = userRow(userData.jid);
544
+ const resolved = resolveExistingUser(userData);
545
+ const jid =
546
+ resolved?.jid ||
547
+ (isLidJid(userData.jid) ? userData.jid : asPnJid(userData.jid) || userData.jid);
548
+ const existing = userRow(jid) || (resolved ? userRow(resolved.jid) : null);
549
+
550
+ let phone = userData.phone || existing?.phone_number || null;
551
+ const lidDigits = lidLocalPart(userData.jid);
552
+ if (phone && lidDigits && String(phone).replace(/\D/g, "") === lidDigits) {
553
+ phone = existing?.phone_number || null;
554
+ }
555
+ if (phone && isLidJid(phone)) phone = existing?.phone_number || null;
556
+
557
+ const incomingSaved = personName(userData.savedName);
558
+ const incomingPush = personName(userData.displayName);
436
559
 
437
560
  const row = {
438
- user_jid: userData.jid,
439
- user_lid: userData.lid || existing?.user_lid || null,
440
- phone_number: userData.phone || existing?.phone_number || null,
561
+ user_jid: jid,
562
+ user_lid: userData.lid || existing?.user_lid || (isLidJid(userData.jid) ? userData.jid : null),
563
+ phone_number: phone,
441
564
  is_owner:
442
565
  userData.isOwner === undefined ? (existing?.is_owner === 1 ? 1 : 0) : bool(userData.isOwner),
443
566
  is_admin:
444
567
  userData.isAdmin === undefined ? (existing?.is_admin === 1 ? 1 : 0) : bool(userData.isAdmin),
445
568
  first_seen: existing?.first_seen ?? now,
446
569
  last_seen: now,
447
- display_name: userData.displayName || existing?.display_name || null,
570
+ display_name: incomingPush || existing?.display_name || null,
571
+ saved_name: incomingSaved || existing?.saved_name || null,
448
572
  };
449
573
 
450
574
  q(
451
575
  `INSERT INTO user_metadata
452
- (user_jid, user_lid, phone_number, is_owner, is_admin, first_seen, last_seen, display_name)
453
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
576
+ (user_jid, user_lid, phone_number, is_owner, is_admin, first_seen, last_seen, display_name, saved_name)
577
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
454
578
  ON CONFLICT(user_jid) DO UPDATE SET
455
579
  user_lid = excluded.user_lid,
456
580
  phone_number = excluded.phone_number,
457
581
  is_owner = excluded.is_owner,
458
582
  is_admin = excluded.is_admin,
459
583
  last_seen = excluded.last_seen,
460
- display_name = excluded.display_name`,
584
+ display_name = excluded.display_name,
585
+ saved_name = excluded.saved_name`,
461
586
  ).run(
462
587
  row.user_jid,
463
588
  row.user_lid,
@@ -467,9 +592,72 @@ function saveUserMetadata(userData) {
467
592
  row.first_seen,
468
593
  row.last_seen,
469
594
  row.display_name,
595
+ row.saved_name,
470
596
  );
471
597
  }
472
598
 
599
+ /**
600
+ * Store an address-book name for a number only when none is saved yet.
601
+ * Used when the panel creates a schedule from a picked phone-book contact.
602
+ */
603
+ function rememberSavedName(identifier, name) {
604
+ const savedName = personName(name);
605
+ if (!identifier || !savedName) return null;
606
+ const existing = getUserMetadata(identifier);
607
+ if (existing?.savedName) return existing;
608
+ let jid = existing?.jid;
609
+ if (!jid) {
610
+ if (String(identifier).includes("@")) jid = identifier;
611
+ else {
612
+ const phone = digitsOf(identifier);
613
+ jid = phone ? `${phone}@s.whatsapp.net` : identifier;
614
+ }
615
+ }
616
+ saveUserMetadata({
617
+ jid,
618
+ lid: existing?.lid || (isLidJid(identifier) ? identifier : null),
619
+ phone: existing?.phone || digitsOf(identifier),
620
+ savedName,
621
+ });
622
+ return getUserMetadata(jid);
623
+ }
624
+
625
+ function isIgnoredContactId(id) {
626
+ const value = String(id || "");
627
+ if (!value) return true;
628
+ if (value.endsWith("@g.us")) return true;
629
+ if (value.includes("@broadcast") || value.includes("@newsletter")) return true;
630
+ if (value === "status@broadcast") return true;
631
+ return false;
632
+ }
633
+
634
+ /**
635
+ * Persist a Baileys v7 contact record from `contacts.upsert` / `contacts.update`.
636
+ * `name` is the address-book name; `notify` is the push name. Never writes a
637
+ * push name into saved_name.
638
+ */
639
+ function applyContactRecord(contact) {
640
+ if (!contact?.id || isIgnoredContactId(contact.id) || isGroupJid(contact.id)) return;
641
+
642
+ const id = String(contact.id);
643
+ const lid = asLidJid(contact.lid) || (isLidJid(id) ? asLidJid(id) : null);
644
+ const pnJid = asPnJid(contact.phoneNumber) || (!isLidJid(id) ? asPnJid(id) : null);
645
+ if (lid && pnJid) storeLidPnMapping(lid, pnJid);
646
+
647
+ const jid = pnJid || lid || id;
648
+ if (isIgnoredContactId(jid)) return;
649
+
650
+ const savedName = personName(contact.name);
651
+ const pushName = personName(contact.notify) || personName(contact.verifiedName);
652
+ saveUserMetadata({
653
+ jid,
654
+ lid,
655
+ phone: pnJid ? digitsOf(pnJid) : null,
656
+ ...(savedName ? { savedName } : {}),
657
+ ...(pushName ? { displayName: pushName } : {}),
658
+ });
659
+ }
660
+
473
661
  /**
474
662
  * Get user metadata by JID, LID, or bare phone number. Four steps, in order:
475
663
  * exact JID, then LID, then phone, then a digits-only match against either
@@ -881,6 +1069,7 @@ function resolveUserPhone(jid) {
881
1069
  const digits = String(pn).split("@")[0].replace(/\D/g, "");
882
1070
  if (digits) return digits;
883
1071
  }
1072
+ if (raw.includes("@lid")) return null;
884
1073
  }
885
1074
  if (/^\d{8,15}$/.test(local)) return local;
886
1075
  return null;
@@ -888,30 +1077,516 @@ function resolveUserPhone(jid) {
888
1077
 
889
1078
  function describePeer(jid) {
890
1079
  const id = String(jid || "");
891
- if (!id) return { jid: "", kind: "unknown", label: "", phone: null, memberCount: null };
1080
+ if (!id) {
1081
+ return {
1082
+ jid: "",
1083
+ kind: "unknown",
1084
+ label: "",
1085
+ phone: null,
1086
+ savedName: null,
1087
+ pushName: null,
1088
+ memberCount: null,
1089
+ };
1090
+ }
892
1091
  if (id.endsWith("@g.us")) {
893
1092
  const dir = getGroupDirectory(id);
894
- const label = dir?.subject || null;
1093
+ const label = personName(dir?.subject) || "Group";
895
1094
  return {
896
1095
  jid: id,
897
1096
  kind: "group",
898
- label: label || "Group",
1097
+ label,
899
1098
  phone: null,
1099
+ savedName: null,
1100
+ pushName: null,
900
1101
  memberCount: dir?.participant_count ?? null,
901
1102
  };
902
1103
  }
903
1104
  const phone = resolveUserPhone(id);
904
1105
  const meta = getUserMetadata(id);
905
- const label = meta?.displayName || (phone ? `+${phone}` : id.split("@")[0]);
1106
+ const savedName = personName(meta?.savedName);
1107
+ const pushName = personName(meta?.displayName);
1108
+ const phoneLabel = phone ? `+${phone}` : null;
1109
+ const label = savedName || pushName || phoneLabel || "Contact";
906
1110
  return {
907
1111
  jid: id,
908
1112
  kind: "contact",
909
1113
  label,
910
- phone: phone ? `+${phone}` : null,
1114
+ phone: phoneLabel,
1115
+ savedName,
1116
+ pushName,
911
1117
  memberCount: null,
912
1118
  };
913
1119
  }
914
1120
 
1121
+ // ===================================================================
1122
+ // --- Sticker Studio ---
1123
+ // ===================================================================
1124
+ //
1125
+ // Every statement the library uses lives here. Multi-row changes run inside
1126
+ // withImmediateTransaction so a crash cannot leave a pack half-merged or a
1127
+ // sticker deleted while its pack positions still have a hole. The WebP files
1128
+ // themselves are not in SQLite — the library writes them beside the row, on
1129
+ // the same thread, with no await in between.
1130
+
1131
+ function withImmediateTransaction(fn) {
1132
+ db.exec("BEGIN IMMEDIATE");
1133
+ try {
1134
+ const result = fn();
1135
+ db.exec("COMMIT");
1136
+ return result;
1137
+ } catch (error) {
1138
+ try {
1139
+ db.exec("ROLLBACK");
1140
+ } catch {
1141
+ // The statement that failed may already have rolled the transaction back.
1142
+ }
1143
+ throw error;
1144
+ }
1145
+ }
1146
+
1147
+ function sqlIn(values) {
1148
+ return values.map(() => "?").join(", ");
1149
+ }
1150
+
1151
+ function newStickerOwnerId() {
1152
+ return crypto.randomBytes(8).toString("hex");
1153
+ }
1154
+
1155
+ function stickerOwnerInsert(id, kind, account) {
1156
+ q(
1157
+ `INSERT INTO sticker_owners (id, kind, account, legacy_key, created_at)
1158
+ VALUES (?, ?, ?, NULL, ?)`,
1159
+ ).run(id, kind, account, Date.now());
1160
+ }
1161
+
1162
+ /**
1163
+ * The panel library. `pairedAccount` is the linked account's normalized LID,
1164
+ * or its normalized phone JID when the credentials carry no lid, or null when
1165
+ * nothing is paired. One IMMEDIATE transaction when a row has to change; a
1166
+ * plain read when it does not.
1167
+ *
1168
+ * The partial unique index allows one `self` row, so an old self is demoted
1169
+ * before another row is promoted. A missing self whose account is already
1170
+ * taken promotes that row: a second insert would violate UNIQUE(account).
1171
+ *
1172
+ * `pairedPhone` is set only when the account is a LID: the same pairing's
1173
+ * phone JID. A self row still bound to it was bound before the credentials
1174
+ * carried a lid, so it moves onto the LID. A stray row already holding that
1175
+ * LID loses its account; it is kept, unreachable, and the panel keeps the
1176
+ * library it had.
1177
+ * @param {string|null} pairedAccount
1178
+ * @param {string|null} [pairedPhone]
1179
+ * @returns {{ key: string }}
1180
+ */
1181
+ function stickerOwnerReconcileSelf(pairedAccount, pairedPhone = null) {
1182
+ const account = pairedAccount || null;
1183
+ const self = q("SELECT id, account FROM sticker_owners WHERE kind = 'self'").get();
1184
+ if (self && (account == null || self.account === account)) return { key: self.id };
1185
+
1186
+ return withImmediateTransaction(() => {
1187
+ const current = q("SELECT id, account FROM sticker_owners WHERE kind = 'self'").get() || null;
1188
+ if (current && (account == null || current.account === account)) return { key: current.id };
1189
+
1190
+ if (current && account && pairedPhone && current.account === pairedPhone) {
1191
+ q("UPDATE sticker_owners SET account = NULL WHERE account = ? AND id <> ?").run(
1192
+ account,
1193
+ current.id,
1194
+ );
1195
+ q("UPDATE sticker_owners SET account = ? WHERE id = ?").run(account, current.id);
1196
+ return { key: current.id };
1197
+ }
1198
+
1199
+ if (!current) {
1200
+ if (account) {
1201
+ const existing = q("SELECT id FROM sticker_owners WHERE account = ?").get(account);
1202
+ if (existing) {
1203
+ q("UPDATE sticker_owners SET kind = 'self' WHERE id = ?").run(existing.id);
1204
+ return { key: existing.id };
1205
+ }
1206
+ }
1207
+ const id = newStickerOwnerId();
1208
+ stickerOwnerInsert(id, "self", account);
1209
+ return { key: id };
1210
+ }
1211
+
1212
+ if (current.account == null) {
1213
+ const existing = account
1214
+ ? q("SELECT id FROM sticker_owners WHERE account = ?").get(account)
1215
+ : null;
1216
+ if (!existing) {
1217
+ q("UPDATE sticker_owners SET account = ? WHERE id = ?").run(account, current.id);
1218
+ return { key: current.id };
1219
+ }
1220
+ q("UPDATE sticker_owners SET kind = 'user', account = NULL WHERE id = ?").run(current.id);
1221
+ q("UPDATE sticker_owners SET kind = 'self' WHERE id = ?").run(existing.id);
1222
+ return { key: existing.id };
1223
+ }
1224
+
1225
+ // Bound to A, and the paired account is a different B. A keeps the old
1226
+ // library. B must not see it.
1227
+ q("UPDATE sticker_owners SET kind = 'user' WHERE id = ?").run(current.id);
1228
+ const existing = q("SELECT id FROM sticker_owners WHERE account = ?").get(account);
1229
+ if (existing) {
1230
+ q("UPDATE sticker_owners SET kind = 'self' WHERE id = ?").run(existing.id);
1231
+ return { key: existing.id };
1232
+ }
1233
+ const id = newStickerOwnerId();
1234
+ stickerOwnerInsert(id, "self", account);
1235
+ return { key: id };
1236
+ });
1237
+ }
1238
+
1239
+ /** The row whose account is this LID, created on first use. May be `self`. */
1240
+ function stickerOwnerEnsure(account) {
1241
+ if (!account) return { key: null };
1242
+ const existing = q("SELECT id FROM sticker_owners WHERE account = ?").get(account);
1243
+ if (existing) return { key: existing.id };
1244
+ const id = newStickerOwnerId();
1245
+ q(
1246
+ `INSERT INTO sticker_owners (id, kind, account, legacy_key, created_at)
1247
+ VALUES (?, 'user', ?, NULL, ?)
1248
+ ON CONFLICT(account) DO NOTHING`,
1249
+ ).run(id, account, Date.now());
1250
+ const row = q("SELECT id FROM sticker_owners WHERE account = ?").get(account);
1251
+ if (!row) throw new Error("sticker owner was not created");
1252
+ return { key: row.id };
1253
+ }
1254
+
1255
+ function stickerCount(owner) {
1256
+ if (!owner) return 0;
1257
+ return q("SELECT COUNT(*) AS n FROM stickers WHERE owner = ?").get(owner).n;
1258
+ }
1259
+
1260
+ function stickerFindBySha(owner, sha) {
1261
+ if (!owner) return null;
1262
+ return q("SELECT * FROM stickers WHERE sha256 = ? AND owner = ?").get(sha, owner) || null;
1263
+ }
1264
+
1265
+ function stickerGet(owner, id) {
1266
+ if (!owner) return null;
1267
+ return q("SELECT * FROM stickers WHERE id = ? AND owner = ?").get(id, owner) || null;
1268
+ }
1269
+
1270
+ function stickerInsert(row) {
1271
+ q(
1272
+ `INSERT INTO stickers (
1273
+ id, owner, sha256, name, animated, width, height, duration_ms, file_size,
1274
+ source, source_mime, is_favorite, created_at, updated_at, last_used_at
1275
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1276
+ ).run(
1277
+ row.id,
1278
+ row.owner,
1279
+ row.sha256,
1280
+ row.name,
1281
+ row.animated ? 1 : 0,
1282
+ row.width,
1283
+ row.height,
1284
+ row.durationMs,
1285
+ row.fileSize,
1286
+ row.source,
1287
+ row.sourceMime,
1288
+ row.favorite ? 1 : 0,
1289
+ row.createdAt,
1290
+ row.updatedAt,
1291
+ row.lastUsedAt,
1292
+ );
1293
+ }
1294
+
1295
+ function stickerUpdate(id, fields) {
1296
+ const sets = [];
1297
+ const params = [];
1298
+ if (fields.name !== undefined) {
1299
+ sets.push("name = ?");
1300
+ params.push(fields.name);
1301
+ }
1302
+ if (fields.isFavorite !== undefined) {
1303
+ sets.push("is_favorite = ?");
1304
+ params.push(fields.isFavorite ? 1 : 0);
1305
+ }
1306
+ if (fields.updatedAt !== undefined) {
1307
+ sets.push("updated_at = ?");
1308
+ params.push(fields.updatedAt);
1309
+ }
1310
+ if (fields.lastUsedAt !== undefined) {
1311
+ sets.push("last_used_at = ?");
1312
+ params.push(fields.lastUsedAt);
1313
+ }
1314
+ if (!sets.length) return;
1315
+ params.push(id);
1316
+ q(`UPDATE stickers SET ${sets.join(", ")} WHERE id = ?`).run(...params);
1317
+ }
1318
+
1319
+ function stickerDelete(id) {
1320
+ q("DELETE FROM stickers WHERE id = ?").run(id);
1321
+ }
1322
+
1323
+ function stickerShaCount(sha) {
1324
+ return q("SELECT COUNT(*) AS n FROM stickers WHERE sha256 = ?").get(sha).n;
1325
+ }
1326
+
1327
+ const STICKER_SORTS = {
1328
+ newest: "s.created_at DESC, s.id DESC",
1329
+ oldest: "s.created_at ASC, s.id ASC",
1330
+ name: "s.name COLLATE NOCASE ASC, s.id ASC",
1331
+ recent: "COALESCE(s.last_used_at, s.created_at) DESC, s.id DESC",
1332
+ };
1333
+
1334
+ function stickerQuery(owner, filter) {
1335
+ if (!owner) return { rows: [], total: 0 };
1336
+ const clauses = ["s.owner = ?"];
1337
+ const params = [owner];
1338
+
1339
+ const text = String(filter.q || "")
1340
+ .trim()
1341
+ .toLowerCase();
1342
+ if (text) {
1343
+ const escaped = text.replace(/[\\%_]/g, (ch) => `\\${ch}`);
1344
+ clauses.push("LOWER(s.name) LIKE ? ESCAPE '\\'");
1345
+ params.push(`%${escaped}%`);
1346
+ }
1347
+ if (filter.filter === "favorites") clauses.push("s.is_favorite = 1");
1348
+ if (filter.filter === "animated") clauses.push("s.animated = 1");
1349
+ if (filter.filter === "static") clauses.push("s.animated = 0");
1350
+ if (filter.filter === "recent") {
1351
+ clauses.push("COALESCE(s.last_used_at, s.created_at) >= ?");
1352
+ params.push(Date.now() - 30 * 24 * 60 * 60 * 1000);
1353
+ }
1354
+ if (filter.pack === "none") {
1355
+ clauses.push(
1356
+ `NOT EXISTS (
1357
+ SELECT 1 FROM sticker_pack_items i
1358
+ JOIN sticker_packs p ON p.id = i.pack_id
1359
+ WHERE i.sticker_id = s.id AND p.owner = ?
1360
+ )`,
1361
+ );
1362
+ params.push(owner);
1363
+ } else if (filter.pack) {
1364
+ clauses.push(
1365
+ `EXISTS (
1366
+ SELECT 1 FROM sticker_pack_items i
1367
+ JOIN sticker_packs p ON p.id = i.pack_id
1368
+ WHERE i.sticker_id = s.id AND i.pack_id = ? AND p.owner = ?
1369
+ )`,
1370
+ );
1371
+ params.push(filter.pack, owner);
1372
+ }
1373
+
1374
+ const where = clauses.join(" AND ");
1375
+ const total = q(`SELECT COUNT(*) AS n FROM stickers s WHERE ${where}`).get(...params).n;
1376
+ const sort =
1377
+ filter.filter === "recent"
1378
+ ? STICKER_SORTS.recent
1379
+ : STICKER_SORTS[filter.sort] || STICKER_SORTS.newest;
1380
+ const limit = Math.min(200, Math.max(1, Number(filter.limit) || 60));
1381
+ const offset = Math.max(0, Number(filter.offset) || 0);
1382
+ const rows = q(`SELECT s.* FROM stickers s WHERE ${where} ORDER BY ${sort} LIMIT ? OFFSET ?`).all(
1383
+ ...params,
1384
+ limit,
1385
+ offset,
1386
+ );
1387
+ return { rows, total };
1388
+ }
1389
+
1390
+ function stickerPackMembership(owner, stickerIds) {
1391
+ const map = new Map();
1392
+ if (!owner || !stickerIds.length) return map;
1393
+ const rows = q(
1394
+ `SELECT i.sticker_id, i.pack_id
1395
+ FROM sticker_pack_items i
1396
+ JOIN sticker_packs p ON p.id = i.pack_id
1397
+ WHERE i.sticker_id IN (${sqlIn(stickerIds)}) AND p.owner = ?
1398
+ ORDER BY i.added_at ASC, i.pack_id ASC`,
1399
+ ).all(...stickerIds, owner);
1400
+ for (const row of rows) {
1401
+ const list = map.get(row.sticker_id);
1402
+ if (list) list.push(row.pack_id);
1403
+ else map.set(row.sticker_id, [row.pack_id]);
1404
+ }
1405
+ return map;
1406
+ }
1407
+
1408
+ function stickerPacksUsing(owner, stickerId) {
1409
+ if (!owner) return [];
1410
+ return q(
1411
+ `SELECT p.id, p.name
1412
+ FROM sticker_pack_items i
1413
+ JOIN sticker_packs p ON p.id = i.pack_id
1414
+ WHERE i.sticker_id = ? AND p.owner = ?
1415
+ ORDER BY LOWER(p.name) ASC, p.id ASC`,
1416
+ ).all(stickerId, owner);
1417
+ }
1418
+
1419
+ function stickerPackIdsOf(stickerId) {
1420
+ return q("SELECT pack_id FROM sticker_pack_items WHERE sticker_id = ?").all(stickerId);
1421
+ }
1422
+
1423
+ function stickerClearAll() {
1424
+ return withImmediateTransaction(() => {
1425
+ const shas = q("SELECT DISTINCT sha256 FROM stickers")
1426
+ .all()
1427
+ .map((row) => row.sha256);
1428
+ q("DELETE FROM stickers").run();
1429
+ q("DELETE FROM sticker_packs").run();
1430
+ q("DELETE FROM sticker_owners").run();
1431
+ return shas;
1432
+ });
1433
+ }
1434
+
1435
+ function stickerPackCount(owner) {
1436
+ if (!owner) return 0;
1437
+ return q("SELECT COUNT(*) AS n FROM sticker_packs WHERE owner = ?").get(owner).n;
1438
+ }
1439
+
1440
+ function stickerPackList(owner) {
1441
+ if (!owner) return [];
1442
+ return q(
1443
+ `SELECT p.*,
1444
+ (SELECT COUNT(*) FROM sticker_pack_items i WHERE i.pack_id = p.id) AS item_count,
1445
+ (SELECT i.sticker_id FROM sticker_pack_items i
1446
+ WHERE i.pack_id = p.id ORDER BY i.position ASC, i.added_at ASC LIMIT 1) AS cover_id,
1447
+ (SELECT s.sha256 FROM sticker_pack_items i
1448
+ JOIN stickers s ON s.id = i.sticker_id
1449
+ WHERE i.pack_id = p.id ORDER BY i.position ASC, i.added_at ASC LIMIT 1) AS cover_sha
1450
+ FROM sticker_packs p
1451
+ WHERE p.owner = ?
1452
+ ORDER BY p.name COLLATE NOCASE ASC, p.id ASC`,
1453
+ ).all(owner);
1454
+ }
1455
+
1456
+ function stickerPackGet(owner, id) {
1457
+ if (!owner) return null;
1458
+ return (
1459
+ q(
1460
+ `SELECT p.*,
1461
+ (SELECT COUNT(*) FROM sticker_pack_items i WHERE i.pack_id = p.id) AS item_count,
1462
+ (SELECT i.sticker_id FROM sticker_pack_items i
1463
+ WHERE i.pack_id = p.id ORDER BY i.position ASC, i.added_at ASC LIMIT 1) AS cover_id,
1464
+ (SELECT s.sha256 FROM sticker_pack_items i
1465
+ JOIN stickers s ON s.id = i.sticker_id
1466
+ WHERE i.pack_id = p.id ORDER BY i.position ASC, i.added_at ASC LIMIT 1) AS cover_sha
1467
+ FROM sticker_packs p
1468
+ WHERE p.id = ? AND p.owner = ?`,
1469
+ ).get(id, owner) || null
1470
+ );
1471
+ }
1472
+
1473
+ function stickerPackByKey(owner, nameKey) {
1474
+ if (!owner) return null;
1475
+ return (
1476
+ q(
1477
+ `SELECT p.*,
1478
+ (SELECT COUNT(*) FROM sticker_pack_items i WHERE i.pack_id = p.id) AS item_count,
1479
+ (SELECT i.sticker_id FROM sticker_pack_items i
1480
+ WHERE i.pack_id = p.id ORDER BY i.position ASC, i.added_at ASC LIMIT 1) AS cover_id,
1481
+ (SELECT s.sha256 FROM sticker_pack_items i
1482
+ JOIN stickers s ON s.id = i.sticker_id
1483
+ WHERE i.pack_id = p.id ORDER BY i.position ASC, i.added_at ASC LIMIT 1) AS cover_sha
1484
+ FROM sticker_packs p
1485
+ WHERE p.name_key = ? AND p.owner = ?`,
1486
+ ).get(nameKey, owner) || null
1487
+ );
1488
+ }
1489
+
1490
+ function stickerPackInsert(row) {
1491
+ q(
1492
+ `INSERT INTO sticker_packs (id, owner, name, name_key, created_at, updated_at)
1493
+ VALUES (?, ?, ?, ?, ?, ?)`,
1494
+ ).run(row.id, row.owner, row.name, row.nameKey, row.createdAt, row.updatedAt);
1495
+ }
1496
+
1497
+ function stickerPackRename(id, name, nameKey, updatedAt) {
1498
+ q("UPDATE sticker_packs SET name = ?, name_key = ?, updated_at = ? WHERE id = ?").run(
1499
+ name,
1500
+ nameKey,
1501
+ updatedAt,
1502
+ id,
1503
+ );
1504
+ }
1505
+
1506
+ function stickerPackDelete(id) {
1507
+ q("DELETE FROM sticker_packs WHERE id = ?").run(id);
1508
+ }
1509
+
1510
+ function stickerPackItems(packId) {
1511
+ return q(
1512
+ `SELECT s.* FROM sticker_pack_items i
1513
+ JOIN stickers s ON s.id = i.sticker_id
1514
+ WHERE i.pack_id = ?
1515
+ ORDER BY i.position ASC, i.added_at ASC, s.id ASC`,
1516
+ ).all(packId);
1517
+ }
1518
+
1519
+ function stickerPackAdd(packId, stickerId, now) {
1520
+ const exists = q(
1521
+ "SELECT 1 AS x FROM sticker_pack_items WHERE pack_id = ? AND sticker_id = ?",
1522
+ ).get(packId, stickerId);
1523
+ if (exists) return false;
1524
+ const count = q("SELECT COUNT(*) AS n FROM sticker_pack_items WHERE pack_id = ?").get(packId).n;
1525
+ q(
1526
+ `INSERT INTO sticker_pack_items (pack_id, sticker_id, position, added_at)
1527
+ VALUES (?, ?, ?, ?)`,
1528
+ ).run(packId, stickerId, count, now);
1529
+ return true;
1530
+ }
1531
+
1532
+ function stickerPackRemoveItem(packId, stickerId) {
1533
+ const result = q("DELETE FROM sticker_pack_items WHERE pack_id = ? AND sticker_id = ?").run(
1534
+ packId,
1535
+ stickerId,
1536
+ );
1537
+ if (result.changes) stickerPackRenumber(packId);
1538
+ return result.changes > 0;
1539
+ }
1540
+
1541
+ function stickerPackRenumber(packId) {
1542
+ const rows = q(
1543
+ `SELECT sticker_id FROM sticker_pack_items
1544
+ WHERE pack_id = ?
1545
+ ORDER BY position ASC, added_at ASC, sticker_id ASC`,
1546
+ ).all(packId);
1547
+ for (let index = 0; index < rows.length; index += 1) {
1548
+ q("UPDATE sticker_pack_items SET position = ? WHERE pack_id = ? AND sticker_id = ?").run(
1549
+ index,
1550
+ packId,
1551
+ rows[index].sticker_id,
1552
+ );
1553
+ }
1554
+ }
1555
+
1556
+ function stickerPackReorder(packId, ids) {
1557
+ const current = q(
1558
+ "SELECT sticker_id FROM sticker_pack_items WHERE pack_id = ? ORDER BY position ASC, added_at ASC",
1559
+ )
1560
+ .all(packId)
1561
+ .map((row) => row.sticker_id);
1562
+ if (current.length !== ids.length || new Set(ids).size !== ids.length) return false;
1563
+ const have = new Set(current);
1564
+ if (ids.some((id) => !have.has(id))) return false;
1565
+ for (let index = 0; index < ids.length; index += 1) {
1566
+ q("UPDATE sticker_pack_items SET position = ? WHERE pack_id = ? AND sticker_id = ?").run(
1567
+ index,
1568
+ packId,
1569
+ ids[index],
1570
+ );
1571
+ }
1572
+ return true;
1573
+ }
1574
+
1575
+ function stickerPackExclusive(packId) {
1576
+ return q(
1577
+ `SELECT i.sticker_id AS id, s.sha256 AS sha256
1578
+ FROM sticker_pack_items i
1579
+ JOIN stickers s ON s.id = i.sticker_id
1580
+ WHERE i.pack_id = ?
1581
+ AND (SELECT COUNT(*) FROM sticker_pack_items j WHERE j.sticker_id = i.sticker_id) = 1
1582
+ ORDER BY i.position ASC`,
1583
+ ).all(packId);
1584
+ }
1585
+
1586
+ function stickerPackItemCount(packId) {
1587
+ return q("SELECT COUNT(*) AS n FROM sticker_pack_items WHERE pack_id = ?").get(packId).n;
1588
+ }
1589
+
915
1590
  module.exports = {
916
1591
  // Lifecycle
917
1592
  initStore,
@@ -961,11 +1636,14 @@ module.exports = {
961
1636
  storeLidPnMapping,
962
1637
  storeLidPnMappings,
963
1638
  getLidForPn,
1639
+ getLidsForPn,
964
1640
  getLidsForPns,
965
1641
  getPnForLid,
966
1642
  getAllLidMappings,
967
1643
  // User metadata & roles
968
1644
  saveUserMetadata,
1645
+ rememberSavedName,
1646
+ applyContactRecord,
969
1647
  getUserMetadata,
970
1648
  isUserOwner,
971
1649
  isUserBotAdmin,
@@ -1012,4 +1690,34 @@ module.exports = {
1012
1690
  resolveUserPhone,
1013
1691
  describePeer,
1014
1692
  migrateSecretsAtRest,
1693
+ // Sticker Studio
1694
+ withImmediateTransaction,
1695
+ stickerOwnerReconcileSelf,
1696
+ stickerOwnerEnsure,
1697
+ stickerCount,
1698
+ stickerFindBySha,
1699
+ stickerGet,
1700
+ stickerInsert,
1701
+ stickerUpdate,
1702
+ stickerDelete,
1703
+ stickerShaCount,
1704
+ stickerQuery,
1705
+ stickerPackMembership,
1706
+ stickerPacksUsing,
1707
+ stickerPackIdsOf,
1708
+ stickerClearAll,
1709
+ stickerPackCount,
1710
+ stickerPackList,
1711
+ stickerPackGet,
1712
+ stickerPackByKey,
1713
+ stickerPackInsert,
1714
+ stickerPackRename,
1715
+ stickerPackDelete,
1716
+ stickerPackItems,
1717
+ stickerPackAdd,
1718
+ stickerPackRemoveItem,
1719
+ stickerPackRenumber,
1720
+ stickerPackReorder,
1721
+ stickerPackExclusive,
1722
+ stickerPackItemCount,
1015
1723
  };