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.
- package/README.md +1 -0
- package/package.json +1 -1
- package/public/dashboard/assets/index-5P8GnKLg.css +2 -0
- package/public/dashboard/assets/index-DXzno3X6.js +515 -0
- package/public/dashboard/index.html +2 -2
- package/public/dashboard.css +32 -0
- package/src/bootstrap/panel.js +16 -4
- package/src/commands/pack.cjs +159 -0
- package/src/commands/packs.cjs +47 -0
- package/src/commands/send.cjs +1 -18
- package/src/commands/sticker.cjs +77 -232
- package/src/commands/stickers.cjs +100 -0
- package/src/commands/toimage.cjs +88 -0
- package/src/config/defaults.cjs +5 -0
- package/src/config/settings.cjs +10 -0
- package/src/core/events.js +15 -1
- package/src/core/session.js +7 -0
- package/src/db/db.cjs +381 -0
- package/src/db/store.cjs +729 -21
- package/src/handlers/command.handler.js +4 -0
- package/src/routes/dashboard.api.esm.js +43 -10
- package/src/routes/stickers.api.esm.js +570 -0
- package/src/stickers/errors.cjs +239 -0
- package/src/stickers/ffmpeg.cjs +133 -0
- package/src/stickers/jobs.cjs +183 -0
- package/src/stickers/library.cjs +712 -0
- package/src/stickers/limits.cjs +60 -0
- package/src/stickers/media.cjs +748 -0
- package/src/stickers/options.cjs +128 -0
- package/src/stickers/owner.cjs +103 -0
- package/src/stickers/studio.cjs +473 -0
- package/src/stickers/uploads.cjs +263 -0
- package/src/stickers/webp.cjs +231 -0
- package/src/stickers/zip.cjs +107 -0
- package/src/utils/messageContent.cjs +30 -4
- package/src/utils/recurrence.cjs +189 -30
- package/src/utils/stickerBot.cjs +84 -0
- package/src/utils/storage.cjs +3 -0
- package/src/utils/storage.esm.js +3 -0
- package/views/login.ejs +39 -3
- package/views/setup.ejs +21 -0
- package/public/dashboard/assets/index-B6RhYFIy.js +0 -446
- package/public/dashboard/assets/index-vEwOcxiH.css +0 -2
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
const { tr } = require("../utils/i18n.cjs");
|
|
2
|
+
const { BOT_PAGE_SIZE } = require("../stickers/limits.cjs");
|
|
3
|
+
const { StickerError } = require("../stickers/errors.cjs");
|
|
4
|
+
const ownerModule = require("../stickers/owner.cjs");
|
|
5
|
+
const library = require("../stickers/library.cjs");
|
|
6
|
+
const {
|
|
7
|
+
sendLibrarySticker,
|
|
8
|
+
commandHint,
|
|
9
|
+
countLabel,
|
|
10
|
+
errorText,
|
|
11
|
+
} = require("../utils/stickerBot.cjs");
|
|
12
|
+
|
|
13
|
+
function parse(args) {
|
|
14
|
+
const parts = [...args];
|
|
15
|
+
let page = 1;
|
|
16
|
+
if (/^[1-9]\d*$/.test(parts.at(-1) || "")) page = Number(parts.pop());
|
|
17
|
+
if (!Number.isSafeInteger(page) || page > 1_000_000) throw new StickerError("INVALID_OPTIONS");
|
|
18
|
+
const first = parts.shift()?.toLowerCase();
|
|
19
|
+
if (!first || first === "recent" || first === "الأحدث") {
|
|
20
|
+
if (parts.length) throw new StickerError("INVALID_OPTIONS");
|
|
21
|
+
return { mode: "recent", page };
|
|
22
|
+
}
|
|
23
|
+
if (first === "favorites" || first === "المفضلة") {
|
|
24
|
+
if (parts.length) throw new StickerError("INVALID_OPTIONS");
|
|
25
|
+
return { mode: "favorites", page };
|
|
26
|
+
}
|
|
27
|
+
if (first === "pack" || first === "حزمة") {
|
|
28
|
+
const name = parts.join(" ").trim();
|
|
29
|
+
if (!name) throw new StickerError("INVALID_NAME");
|
|
30
|
+
return { mode: "pack", name, page };
|
|
31
|
+
}
|
|
32
|
+
throw new StickerError("INVALID_OPTIONS");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
module.exports = {
|
|
36
|
+
name: "stickers",
|
|
37
|
+
aliases: ["ملصقاتي"],
|
|
38
|
+
description: {
|
|
39
|
+
en: "Browse your recent, favorite or packed stickers.",
|
|
40
|
+
ar: "يعرض ملصقاتك الحديثة أو المفضلة أو الموجودة في حزمة.",
|
|
41
|
+
},
|
|
42
|
+
usage: {
|
|
43
|
+
en: "stickers [page]\nstickers recent [page]\nstickers favorites [page]\nstickers pack <name> [page]",
|
|
44
|
+
ar: "stickers [الصفحة]\nstickers الأحدث [الصفحة]\nstickers المفضلة [الصفحة]\nstickers حزمة <الاسم> [الصفحة]",
|
|
45
|
+
},
|
|
46
|
+
keywords: ["recent", "الأحدث", "favorites", "المفضلة", "pack", "حزمة"],
|
|
47
|
+
chat: "all",
|
|
48
|
+
async execute(sock, msg, args = []) {
|
|
49
|
+
const jid = msg.key.remoteJid;
|
|
50
|
+
const who = await ownerModule.forMessage(msg, sock);
|
|
51
|
+
if (!who.key)
|
|
52
|
+
return sock.sendMessage(jid, {
|
|
53
|
+
text: tr("I couldn't identify the sender.", "تعذّر تحديد هوية المرسل."),
|
|
54
|
+
});
|
|
55
|
+
try {
|
|
56
|
+
const selected = parse(args);
|
|
57
|
+
const query = { limit: BOT_PAGE_SIZE, offset: (selected.page - 1) * BOT_PAGE_SIZE };
|
|
58
|
+
let label = tr("Recent stickers", "الملصقات الحديثة");
|
|
59
|
+
if (selected.mode === "favorites") {
|
|
60
|
+
query.filter = "favorites";
|
|
61
|
+
label = tr("Favorite stickers", "الملصقات المفضلة");
|
|
62
|
+
} else if (selected.mode === "pack") {
|
|
63
|
+
const pack = library.findPackByName(who, selected.name);
|
|
64
|
+
if (!pack) throw new StickerError("PACK_NOT_FOUND", { name: selected.name });
|
|
65
|
+
query.pack = pack.id;
|
|
66
|
+
label = pack.name;
|
|
67
|
+
} else {
|
|
68
|
+
query.filter = "all";
|
|
69
|
+
query.sort = "recent";
|
|
70
|
+
}
|
|
71
|
+
const { items, total } = library.listStickers(who, query);
|
|
72
|
+
if (!total)
|
|
73
|
+
return sock.sendMessage(jid, {
|
|
74
|
+
text: tr(
|
|
75
|
+
`No stickers here yet. Reply to media with ${commandHint("sticker")} or ${commandHint("pack", "<name>")} to save one.`,
|
|
76
|
+
`لا توجد ملصقات هنا بعد. رد على وسائط بالأمر ${commandHint("sticker")} أو ${commandHint("pack", "<الاسم>")} لحفظ ملصق.`,
|
|
77
|
+
),
|
|
78
|
+
});
|
|
79
|
+
const pages = Math.ceil(total / BOT_PAGE_SIZE);
|
|
80
|
+
if (selected.page > pages) throw new StickerError("INVALID_OPTIONS");
|
|
81
|
+
const next =
|
|
82
|
+
selected.page < pages
|
|
83
|
+
? selected.mode === "pack"
|
|
84
|
+
? commandHint("stickers", `pack ${selected.name} ${selected.page + 1}`)
|
|
85
|
+
: selected.mode === "favorites"
|
|
86
|
+
? commandHint("stickers", `favorites ${selected.page + 1}`)
|
|
87
|
+
: commandHint("stickers", String(selected.page + 1))
|
|
88
|
+
: null;
|
|
89
|
+
await sock.sendMessage(jid, {
|
|
90
|
+
text: tr(
|
|
91
|
+
`${label} — ${countLabel(total)} · page ${selected.page}/${pages}${next ? ` · ${next} for more` : ""}`,
|
|
92
|
+
`${label} — ${countLabel(total)} · الصفحة ${selected.page}/${pages}${next ? ` · ${next} للمزيد` : ""}`,
|
|
93
|
+
),
|
|
94
|
+
});
|
|
95
|
+
for (const sticker of items) await sendLibrarySticker(sock, jid, who, sticker);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
await sock.sendMessage(jid, { text: errorText(error) });
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
const { tr } = require("../utils/i18n.cjs");
|
|
2
|
+
const { createStatus } = require("../utils/statusMessage.cjs");
|
|
3
|
+
const { targetOf, downloadTarget, commandHint, errorText } = require("../utils/stickerBot.cjs");
|
|
4
|
+
const media = require("../stickers/media.cjs");
|
|
5
|
+
const jobs = require("../stickers/jobs.cjs");
|
|
6
|
+
|
|
7
|
+
module.exports = {
|
|
8
|
+
name: "toimage",
|
|
9
|
+
aliases: ["toimg", "صورة"],
|
|
10
|
+
description: {
|
|
11
|
+
en: "Turn a replied sticker into a PNG or animated video.",
|
|
12
|
+
ar: "يحوّل الملصق المردود عليه إلى صورة PNG أو فيديو متحرك.",
|
|
13
|
+
},
|
|
14
|
+
usage: {
|
|
15
|
+
en: "toimage (reply to a sticker)\ntoimage doc (reply to a sticker)\ntoimage gif (reply to an animated sticker)",
|
|
16
|
+
ar: "toimage (رد على ملصق)\ntoimage ملف (رد على ملصق)\ntoimage متحرك (رد على ملصق متحرك)",
|
|
17
|
+
},
|
|
18
|
+
keywords: ["doc", "ملف", "gif", "متحرك"],
|
|
19
|
+
chat: "all",
|
|
20
|
+
async execute(sock, msg, args = []) {
|
|
21
|
+
const jid = msg.key.remoteJid;
|
|
22
|
+
const target = targetOf(msg, { quotedOnly: true });
|
|
23
|
+
if (target?.type !== "sticker") {
|
|
24
|
+
return sock.sendMessage(jid, {
|
|
25
|
+
text: tr(
|
|
26
|
+
`Reply to a sticker with ${commandHint("toimage", "[doc|gif]")}.`,
|
|
27
|
+
`رد على ملصق بالأمر ${commandHint("toimage", "[ملف|متحرك]")}.`,
|
|
28
|
+
),
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
let status;
|
|
32
|
+
try {
|
|
33
|
+
const buffer = await downloadTarget(target);
|
|
34
|
+
const wantsGif = args.some((arg) => ["gif", "متحرك"].includes(String(arg).toLowerCase()));
|
|
35
|
+
const staticGif = wantsGif && !media.describeWebp(buffer).animated;
|
|
36
|
+
const mode =
|
|
37
|
+
wantsGif && !staticGif
|
|
38
|
+
? "gif"
|
|
39
|
+
: args.some((arg) => ["doc", "ملف"].includes(String(arg).toLowerCase()))
|
|
40
|
+
? "doc"
|
|
41
|
+
: "png";
|
|
42
|
+
status = await createStatus(
|
|
43
|
+
sock,
|
|
44
|
+
jid,
|
|
45
|
+
tr("🎨 Converting sticker...", "🎨 جارٍ تحويل الملصق..."),
|
|
46
|
+
{ replyTo: msg },
|
|
47
|
+
);
|
|
48
|
+
const job = jobs.submit(
|
|
49
|
+
({ signal }) =>
|
|
50
|
+
mode === "gif" ? media.toMp4(buffer, { signal }) : media.toPng(buffer, { signal }),
|
|
51
|
+
{ kind: "export" },
|
|
52
|
+
);
|
|
53
|
+
const result = await job.promise;
|
|
54
|
+
const caption = staticGif
|
|
55
|
+
? tr(
|
|
56
|
+
"This sticker is not animated, so I sent a PNG.",
|
|
57
|
+
"هذا الملصق غير متحرك، لذا أرسلت صورة PNG.",
|
|
58
|
+
)
|
|
59
|
+
: result.animated
|
|
60
|
+
? tr(
|
|
61
|
+
`First frame of an animated sticker. Use ${commandHint("toimage", "gif")} for the animation.`,
|
|
62
|
+
`الإطار الأول من ملصق متحرك. استخدم ${commandHint("toimage", "متحرك")} للحصول على الحركة.`,
|
|
63
|
+
)
|
|
64
|
+
: undefined;
|
|
65
|
+
if (mode === "gif") {
|
|
66
|
+
await sock.sendMessage(jid, { video: result, mimetype: "video/mp4", gifPlayback: true });
|
|
67
|
+
} else if (mode === "doc") {
|
|
68
|
+
await sock.sendMessage(jid, {
|
|
69
|
+
document: result.buffer,
|
|
70
|
+
mimetype: "image/png",
|
|
71
|
+
fileName: "sticker.png",
|
|
72
|
+
caption,
|
|
73
|
+
});
|
|
74
|
+
} else {
|
|
75
|
+
await sock.sendMessage(jid, {
|
|
76
|
+
image: result.buffer,
|
|
77
|
+
mimetype: "image/png",
|
|
78
|
+
caption,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
await status.remove();
|
|
82
|
+
} catch (error) {
|
|
83
|
+
const line = errorText(error);
|
|
84
|
+
if (status) await status.finish(line);
|
|
85
|
+
else await sock.sendMessage(jid, { text: line });
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
};
|
package/src/config/defaults.cjs
CHANGED
|
@@ -54,6 +54,11 @@ const COMMAND_PERMISSIONS = Object.freeze({
|
|
|
54
54
|
block: "OWNER_ONLY",
|
|
55
55
|
unblock: "OWNER_ONLY",
|
|
56
56
|
send: "MEMBERS",
|
|
57
|
+
sticker: "MEMBERS",
|
|
58
|
+
toimage: "MEMBERS",
|
|
59
|
+
pack: "MEMBERS",
|
|
60
|
+
packs: "MEMBERS",
|
|
61
|
+
stickers: "MEMBERS",
|
|
57
62
|
group: {
|
|
58
63
|
default_permission: "ADMINS_OWNER",
|
|
59
64
|
sub_commands: {
|
package/src/config/settings.cjs
CHANGED
|
@@ -345,6 +345,16 @@ const SETTINGS = [
|
|
|
345
345
|
label: "ffmpeg path",
|
|
346
346
|
hint: "Only if the bundled ffmpeg-static binary can't run on this machine.",
|
|
347
347
|
},
|
|
348
|
+
{
|
|
349
|
+
key: "sticker_library_limit",
|
|
350
|
+
type: "int",
|
|
351
|
+
default: 1000,
|
|
352
|
+
min: 1,
|
|
353
|
+
max: 100000,
|
|
354
|
+
group: "media",
|
|
355
|
+
label: "Sticker library size",
|
|
356
|
+
hint: "How many stickers one person can keep in Sticker Studio. Read on every save, so a change applies without a restart. A full library refuses new stickers until some are deleted.",
|
|
357
|
+
},
|
|
348
358
|
|
|
349
359
|
// --- WhatsApp proxy ----------------------------------------------------
|
|
350
360
|
//
|
package/src/core/events.js
CHANGED
|
@@ -4,7 +4,11 @@ import {
|
|
|
4
4
|
handleGroupParticipantsUpdate,
|
|
5
5
|
} from "../handlers/group.handler.js";
|
|
6
6
|
import { handleIncomingMessage } from "../handlers/message.handler.js";
|
|
7
|
-
import {
|
|
7
|
+
import {
|
|
8
|
+
applyContactRecord,
|
|
9
|
+
storeLidPnMappings,
|
|
10
|
+
upsertGroupDirectory,
|
|
11
|
+
} from "../utils/storage.esm.js";
|
|
8
12
|
import { groupMetadataCache } from "./socket.js";
|
|
9
13
|
|
|
10
14
|
const require = createRequire(import.meta.url);
|
|
@@ -62,6 +66,16 @@ export function setupEventListeners(
|
|
|
62
66
|
// Save credentials
|
|
63
67
|
if (saveCreds) sock.ev.on("creds.update", saveCreds);
|
|
64
68
|
|
|
69
|
+
// Address-book names (`name`) and push names (`notify`) from the linked phone.
|
|
70
|
+
// No history sync — these events are the live contact list WhatsApp already
|
|
71
|
+
// pushes. persist `name` as saved_name; never treat `notify` as a saved name.
|
|
72
|
+
const persistContacts = (contacts) => {
|
|
73
|
+
const list = Array.isArray(contacts) ? contacts : contacts ? [contacts] : [];
|
|
74
|
+
for (const contact of list) applyContactRecord(contact);
|
|
75
|
+
};
|
|
76
|
+
sock.ev.on("contacts.upsert", contained("contacts.upsert", persistContacts));
|
|
77
|
+
sock.ev.on("contacts.update", contained("contacts.update", persistContacts));
|
|
78
|
+
|
|
65
79
|
// V7: LID mapping updates
|
|
66
80
|
sock.ev.on("lid-mapping.update", (updates) => {
|
|
67
81
|
logger.info(`[LID] Received ${Object.keys(updates).length} LID mapping updates`);
|
package/src/core/session.js
CHANGED
|
@@ -90,6 +90,13 @@ function clearAccountScopedState() {
|
|
|
90
90
|
} catch (error) {
|
|
91
91
|
logger.warn({ err: error }, "[Session] failed to clear AI context buffers after unlink");
|
|
92
92
|
}
|
|
93
|
+
try {
|
|
94
|
+
// Same boundary as the memory wipe above: the next phone that pairs must
|
|
95
|
+
// not inherit this account's stickers, packs, or files.
|
|
96
|
+
require("../stickers/library.cjs").clearAll();
|
|
97
|
+
} catch (error) {
|
|
98
|
+
logger.warn({ err: error }, "[Session] failed to clear the sticker library after unlink");
|
|
99
|
+
}
|
|
93
100
|
try {
|
|
94
101
|
groupMetadataCache.flushAll();
|
|
95
102
|
} catch {}
|
package/src/db/db.cjs
CHANGED
|
@@ -193,6 +193,387 @@ const MIGRATIONS = [
|
|
|
193
193
|
);
|
|
194
194
|
`);
|
|
195
195
|
},
|
|
196
|
+
// v4 — address-book name from the linked phone (Baileys `contact.name`),
|
|
197
|
+
// distinct from the push name in display_name. Cleared with user_metadata
|
|
198
|
+
// on unlink.
|
|
199
|
+
(database) => {
|
|
200
|
+
database.exec(`
|
|
201
|
+
ALTER TABLE user_metadata ADD COLUMN saved_name TEXT;
|
|
202
|
+
`);
|
|
203
|
+
},
|
|
204
|
+
// v5 — Sticker Studio. One row per sticker per owner; the WebP itself lives
|
|
205
|
+
// outside the database, content-addressed by sha256, and is deleted only
|
|
206
|
+
// when no row (any owner) still points at it. Pack items cascade so a
|
|
207
|
+
// deleted sticker or pack cannot leave a dangling membership. Wiped on
|
|
208
|
+
// unlink with the rest of the account.
|
|
209
|
+
(database) => {
|
|
210
|
+
database.exec(`
|
|
211
|
+
CREATE TABLE IF NOT EXISTS stickers (
|
|
212
|
+
id TEXT PRIMARY KEY,
|
|
213
|
+
owner TEXT NOT NULL,
|
|
214
|
+
sha256 TEXT NOT NULL,
|
|
215
|
+
name TEXT NOT NULL DEFAULT '',
|
|
216
|
+
animated INTEGER NOT NULL DEFAULT 0,
|
|
217
|
+
width INTEGER,
|
|
218
|
+
height INTEGER,
|
|
219
|
+
duration_ms INTEGER,
|
|
220
|
+
file_size INTEGER NOT NULL,
|
|
221
|
+
source TEXT NOT NULL,
|
|
222
|
+
source_mime TEXT,
|
|
223
|
+
is_favorite INTEGER NOT NULL DEFAULT 0,
|
|
224
|
+
created_at INTEGER NOT NULL,
|
|
225
|
+
updated_at INTEGER NOT NULL,
|
|
226
|
+
last_used_at INTEGER,
|
|
227
|
+
UNIQUE (owner, sha256)
|
|
228
|
+
);
|
|
229
|
+
CREATE INDEX IF NOT EXISTS idx_stickers_owner_created
|
|
230
|
+
ON stickers (owner, created_at);
|
|
231
|
+
CREATE INDEX IF NOT EXISTS idx_stickers_owner_name
|
|
232
|
+
ON stickers (owner, name);
|
|
233
|
+
CREATE INDEX IF NOT EXISTS idx_stickers_sha
|
|
234
|
+
ON stickers (sha256);
|
|
235
|
+
|
|
236
|
+
CREATE TABLE IF NOT EXISTS sticker_packs (
|
|
237
|
+
id TEXT PRIMARY KEY,
|
|
238
|
+
owner TEXT NOT NULL,
|
|
239
|
+
name TEXT NOT NULL,
|
|
240
|
+
name_key TEXT NOT NULL,
|
|
241
|
+
created_at INTEGER NOT NULL,
|
|
242
|
+
updated_at INTEGER NOT NULL,
|
|
243
|
+
UNIQUE (owner, name_key)
|
|
244
|
+
);
|
|
245
|
+
CREATE INDEX IF NOT EXISTS idx_sticker_packs_owner
|
|
246
|
+
ON sticker_packs (owner, name_key);
|
|
247
|
+
|
|
248
|
+
CREATE TABLE IF NOT EXISTS sticker_pack_items (
|
|
249
|
+
pack_id TEXT NOT NULL,
|
|
250
|
+
sticker_id TEXT NOT NULL,
|
|
251
|
+
position INTEGER NOT NULL,
|
|
252
|
+
added_at INTEGER NOT NULL,
|
|
253
|
+
PRIMARY KEY (pack_id, sticker_id),
|
|
254
|
+
FOREIGN KEY (pack_id) REFERENCES sticker_packs (id) ON DELETE CASCADE,
|
|
255
|
+
FOREIGN KEY (sticker_id) REFERENCES stickers (id) ON DELETE CASCADE
|
|
256
|
+
);
|
|
257
|
+
CREATE INDEX IF NOT EXISTS idx_sticker_pack_items_sticker
|
|
258
|
+
ON sticker_pack_items (sticker_id);
|
|
259
|
+
CREATE INDEX IF NOT EXISTS idx_sticker_pack_items_order
|
|
260
|
+
ON sticker_pack_items (pack_id, position);
|
|
261
|
+
`);
|
|
262
|
+
},
|
|
263
|
+
// v6 — a sticker library belongs to sticker_owners.id, never a phone JID.
|
|
264
|
+
// A legacy phone key is attached to a LID only when lid_mapping holds exactly
|
|
265
|
+
// one normalized LID for that number. Zero or several stay unbound: the rows
|
|
266
|
+
// are kept and no sender can open them. Keys that resolve to the same LID
|
|
267
|
+
// are merged here. This step is frozen: it inlines its own JID normalization
|
|
268
|
+
// and does not import the application.
|
|
269
|
+
(database) => {
|
|
270
|
+
const crypto = require("node:crypto");
|
|
271
|
+
|
|
272
|
+
database.exec(`
|
|
273
|
+
CREATE TABLE sticker_owners (
|
|
274
|
+
id TEXT PRIMARY KEY,
|
|
275
|
+
kind TEXT NOT NULL CHECK (kind IN ('self','user')),
|
|
276
|
+
account TEXT UNIQUE,
|
|
277
|
+
legacy_key TEXT,
|
|
278
|
+
created_at INTEGER NOT NULL
|
|
279
|
+
);
|
|
280
|
+
CREATE UNIQUE INDEX idx_sticker_owners_self
|
|
281
|
+
ON sticker_owners (kind) WHERE kind = 'self';
|
|
282
|
+
`);
|
|
283
|
+
|
|
284
|
+
// Frozen copy of normalizeJid. A shipped migration cannot follow later edits.
|
|
285
|
+
const normalizeJid = (jid) => {
|
|
286
|
+
if (!jid) return jid;
|
|
287
|
+
const text = String(jid);
|
|
288
|
+
if (text.includes("@lid")) {
|
|
289
|
+
if (text.includes(":")) return `${text.split(":")[0]}@lid`;
|
|
290
|
+
return text;
|
|
291
|
+
}
|
|
292
|
+
if (text.includes(":")) return `${text.split(":")[0]}@${text.split("@")[1]}`;
|
|
293
|
+
return text;
|
|
294
|
+
};
|
|
295
|
+
const isLid = (jid) => typeof jid === "string" && jid.includes("@lid");
|
|
296
|
+
const isPn = (jid) => typeof jid === "string" && jid.includes("@s.whatsapp.net");
|
|
297
|
+
|
|
298
|
+
const run = (sql, ...params) => database.prepare(sql).run(...params);
|
|
299
|
+
const all = (sql, ...params) => database.prepare(sql).all(...params);
|
|
300
|
+
|
|
301
|
+
// Same row set as store.getLidsForPn, then distinct normalized LIDs.
|
|
302
|
+
const lidsForPn = (pn) => {
|
|
303
|
+
if (!pn) return [];
|
|
304
|
+
const found = new Set();
|
|
305
|
+
const consider = (rows) => {
|
|
306
|
+
for (const row of rows) {
|
|
307
|
+
if (!row?.lid || !row?.pn) continue;
|
|
308
|
+
if (normalizeJid(row.pn) !== pn && row.pn !== pn) continue;
|
|
309
|
+
const lid = normalizeJid(row.lid);
|
|
310
|
+
if (isLid(lid)) found.add(lid);
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
consider(all("SELECT lid, pn FROM lid_mapping WHERE pn = ?", pn));
|
|
314
|
+
if (!String(pn).includes(":")) {
|
|
315
|
+
const at = String(pn).lastIndexOf("@");
|
|
316
|
+
if (at > 0) {
|
|
317
|
+
const user = String(pn).slice(0, at);
|
|
318
|
+
consider(
|
|
319
|
+
all("SELECT lid, pn FROM lid_mapping WHERE pn >= ? AND pn < ?", `${user}:`, `${user};`),
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return [...found];
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
const classify = (legacy) => {
|
|
327
|
+
if (legacy === "self") {
|
|
328
|
+
return {
|
|
329
|
+
bucket: "self",
|
|
330
|
+
kind: "self",
|
|
331
|
+
account: null,
|
|
332
|
+
legacyKey: "self",
|
|
333
|
+
normalized: "self",
|
|
334
|
+
original: legacy,
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
const norm = normalizeJid(legacy);
|
|
338
|
+
if (isLid(norm)) {
|
|
339
|
+
return {
|
|
340
|
+
bucket: `account:${norm}`,
|
|
341
|
+
kind: "user",
|
|
342
|
+
account: norm,
|
|
343
|
+
legacyKey: norm,
|
|
344
|
+
normalized: norm,
|
|
345
|
+
original: legacy,
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
if (isPn(norm)) {
|
|
349
|
+
const lids = lidsForPn(norm);
|
|
350
|
+
if (lids.length === 1) {
|
|
351
|
+
return {
|
|
352
|
+
bucket: `account:${lids[0]}`,
|
|
353
|
+
kind: "user",
|
|
354
|
+
account: lids[0],
|
|
355
|
+
legacyKey: norm,
|
|
356
|
+
normalized: norm,
|
|
357
|
+
original: legacy,
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
return {
|
|
361
|
+
bucket: `unbound-pn:${norm}`,
|
|
362
|
+
kind: "user",
|
|
363
|
+
account: null,
|
|
364
|
+
legacyKey: norm,
|
|
365
|
+
normalized: norm,
|
|
366
|
+
original: legacy,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
return {
|
|
370
|
+
bucket: `raw:${legacy}`,
|
|
371
|
+
kind: "user",
|
|
372
|
+
account: null,
|
|
373
|
+
legacyKey: legacy,
|
|
374
|
+
normalized: norm,
|
|
375
|
+
original: legacy,
|
|
376
|
+
};
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
const legacyOwners = all(
|
|
380
|
+
`SELECT owner FROM stickers
|
|
381
|
+
UNION
|
|
382
|
+
SELECT owner FROM sticker_packs`,
|
|
383
|
+
);
|
|
384
|
+
if (!legacyOwners.length) return;
|
|
385
|
+
|
|
386
|
+
const groups = new Map();
|
|
387
|
+
for (const row of legacyOwners) {
|
|
388
|
+
const info = classify(row.owner);
|
|
389
|
+
const group = groups.get(info.bucket);
|
|
390
|
+
if (group) group.entries.push(info);
|
|
391
|
+
else groups.set(info.bucket, { kind: info.kind, account: info.account, entries: [info] });
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
const usedIds = new Set();
|
|
395
|
+
const newId = () => {
|
|
396
|
+
for (;;) {
|
|
397
|
+
const id = crypto.randomBytes(8).toString("hex");
|
|
398
|
+
if (!usedIds.has(id)) {
|
|
399
|
+
usedIds.add(id);
|
|
400
|
+
return id;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
};
|
|
404
|
+
const now = Date.now();
|
|
405
|
+
|
|
406
|
+
const renumberPack = (packId) => {
|
|
407
|
+
const items = all(
|
|
408
|
+
`SELECT sticker_id FROM sticker_pack_items
|
|
409
|
+
WHERE pack_id = ?
|
|
410
|
+
ORDER BY position ASC, added_at ASC, sticker_id ASC`,
|
|
411
|
+
packId,
|
|
412
|
+
);
|
|
413
|
+
for (let index = 0; index < items.length; index += 1) {
|
|
414
|
+
run(
|
|
415
|
+
"UPDATE sticker_pack_items SET position = ? WHERE pack_id = ? AND sticker_id = ?",
|
|
416
|
+
index,
|
|
417
|
+
packId,
|
|
418
|
+
items[index].sticker_id,
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
|
|
423
|
+
const retargetItems = (fromStickerId, toStickerId) => {
|
|
424
|
+
const items = all(
|
|
425
|
+
"SELECT pack_id FROM sticker_pack_items WHERE sticker_id = ?",
|
|
426
|
+
fromStickerId,
|
|
427
|
+
);
|
|
428
|
+
for (const item of items) {
|
|
429
|
+
const exists = database
|
|
430
|
+
.prepare("SELECT 1 AS x FROM sticker_pack_items WHERE pack_id = ? AND sticker_id = ?")
|
|
431
|
+
.get(item.pack_id, toStickerId);
|
|
432
|
+
if (exists) {
|
|
433
|
+
run(
|
|
434
|
+
"DELETE FROM sticker_pack_items WHERE pack_id = ? AND sticker_id = ?",
|
|
435
|
+
item.pack_id,
|
|
436
|
+
fromStickerId,
|
|
437
|
+
);
|
|
438
|
+
} else {
|
|
439
|
+
run(
|
|
440
|
+
"UPDATE sticker_pack_items SET sticker_id = ? WHERE pack_id = ? AND sticker_id = ?",
|
|
441
|
+
toStickerId,
|
|
442
|
+
item.pack_id,
|
|
443
|
+
fromStickerId,
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
renumberPack(item.pack_id);
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
const appendPack = (fromPackId, toPackId) => {
|
|
451
|
+
const items = all(
|
|
452
|
+
`SELECT sticker_id FROM sticker_pack_items
|
|
453
|
+
WHERE pack_id = ?
|
|
454
|
+
ORDER BY position ASC, added_at ASC`,
|
|
455
|
+
fromPackId,
|
|
456
|
+
);
|
|
457
|
+
for (const item of items) {
|
|
458
|
+
const exists = database
|
|
459
|
+
.prepare("SELECT 1 AS x FROM sticker_pack_items WHERE pack_id = ? AND sticker_id = ?")
|
|
460
|
+
.get(toPackId, item.sticker_id);
|
|
461
|
+
if (exists) continue;
|
|
462
|
+
const count = database
|
|
463
|
+
.prepare("SELECT COUNT(*) AS n FROM sticker_pack_items WHERE pack_id = ?")
|
|
464
|
+
.get(toPackId).n;
|
|
465
|
+
run(
|
|
466
|
+
`INSERT INTO sticker_pack_items (pack_id, sticker_id, position, added_at)
|
|
467
|
+
VALUES (?, ?, ?, ?)`,
|
|
468
|
+
toPackId,
|
|
469
|
+
item.sticker_id,
|
|
470
|
+
count,
|
|
471
|
+
now,
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
const placeholders = (values) => values.map(() => "?").join(", ");
|
|
477
|
+
|
|
478
|
+
const mergeStickers = (legacyKeys) => {
|
|
479
|
+
if (legacyKeys.length < 2) return;
|
|
480
|
+
const marks = placeholders(legacyKeys);
|
|
481
|
+
const rows = all(`SELECT * FROM stickers WHERE owner IN (${marks})`, ...legacyKeys);
|
|
482
|
+
const bySha = new Map();
|
|
483
|
+
for (const row of rows) {
|
|
484
|
+
const group = bySha.get(row.sha256);
|
|
485
|
+
if (group) group.push(row);
|
|
486
|
+
else bySha.set(row.sha256, [row]);
|
|
487
|
+
}
|
|
488
|
+
for (const group of bySha.values()) {
|
|
489
|
+
if (group.length < 2) continue;
|
|
490
|
+
group.sort(
|
|
491
|
+
(a, b) => a.created_at - b.created_at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0),
|
|
492
|
+
);
|
|
493
|
+
const keep = group[0];
|
|
494
|
+
let name = keep.name;
|
|
495
|
+
let favorite = keep.is_favorite;
|
|
496
|
+
let lastUsed = keep.last_used_at;
|
|
497
|
+
let created = keep.created_at;
|
|
498
|
+
for (const extra of group.slice(1)) {
|
|
499
|
+
if (!name && extra.name) name = extra.name;
|
|
500
|
+
if (extra.is_favorite) favorite = 1;
|
|
501
|
+
if (extra.last_used_at != null && (lastUsed == null || extra.last_used_at > lastUsed)) {
|
|
502
|
+
lastUsed = extra.last_used_at;
|
|
503
|
+
}
|
|
504
|
+
if (extra.created_at < created) created = extra.created_at;
|
|
505
|
+
retargetItems(extra.id, keep.id);
|
|
506
|
+
run("DELETE FROM stickers WHERE id = ?", extra.id);
|
|
507
|
+
}
|
|
508
|
+
run(
|
|
509
|
+
`UPDATE stickers
|
|
510
|
+
SET name = ?, is_favorite = ?, last_used_at = ?, created_at = ?
|
|
511
|
+
WHERE id = ?`,
|
|
512
|
+
name,
|
|
513
|
+
favorite,
|
|
514
|
+
lastUsed,
|
|
515
|
+
created,
|
|
516
|
+
keep.id,
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
};
|
|
520
|
+
|
|
521
|
+
const mergePacks = (legacyKeys) => {
|
|
522
|
+
if (legacyKeys.length < 2) return;
|
|
523
|
+
const marks = placeholders(legacyKeys);
|
|
524
|
+
const packs = all(`SELECT * FROM sticker_packs WHERE owner IN (${marks})`, ...legacyKeys);
|
|
525
|
+
const byName = new Map();
|
|
526
|
+
for (const pack of packs) {
|
|
527
|
+
const group = byName.get(pack.name_key);
|
|
528
|
+
if (group) group.push(pack);
|
|
529
|
+
else byName.set(pack.name_key, [pack]);
|
|
530
|
+
}
|
|
531
|
+
for (const group of byName.values()) {
|
|
532
|
+
if (group.length < 2) continue;
|
|
533
|
+
group.sort(
|
|
534
|
+
(a, b) => a.created_at - b.created_at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0),
|
|
535
|
+
);
|
|
536
|
+
const keep = group[0];
|
|
537
|
+
for (const extra of group.slice(1)) {
|
|
538
|
+
appendPack(extra.id, keep.id);
|
|
539
|
+
run("DELETE FROM sticker_pack_items WHERE pack_id = ?", extra.id);
|
|
540
|
+
run("DELETE FROM sticker_packs WHERE id = ?", extra.id);
|
|
541
|
+
renumberPack(keep.id);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
|
|
546
|
+
const repoint = (legacyKeys, ownerId) => {
|
|
547
|
+
const marks = placeholders(legacyKeys);
|
|
548
|
+
run(`UPDATE stickers SET owner = ? WHERE owner IN (${marks})`, ownerId, ...legacyKeys);
|
|
549
|
+
run(`UPDATE sticker_packs SET owner = ? WHERE owner IN (${marks})`, ownerId, ...legacyKeys);
|
|
550
|
+
};
|
|
551
|
+
|
|
552
|
+
for (const group of groups.values()) {
|
|
553
|
+
// Stickers still carry the v5 owner string. Merge and repoint those,
|
|
554
|
+
// and only then give the survivor the new id.
|
|
555
|
+
const originals = [...new Set(group.entries.map((entry) => entry.original))];
|
|
556
|
+
const accountMatch = group.account
|
|
557
|
+
? group.entries.find((entry) => entry.normalized === group.account)
|
|
558
|
+
: null;
|
|
559
|
+
const legacyKey = accountMatch
|
|
560
|
+
? accountMatch.legacyKey
|
|
561
|
+
: group.entries.map((entry) => entry.legacyKey).sort()[0];
|
|
562
|
+
const id = newId();
|
|
563
|
+
run(
|
|
564
|
+
`INSERT INTO sticker_owners (id, kind, account, legacy_key, created_at)
|
|
565
|
+
VALUES (?, ?, ?, ?, ?)`,
|
|
566
|
+
id,
|
|
567
|
+
group.kind,
|
|
568
|
+
group.account,
|
|
569
|
+
legacyKey,
|
|
570
|
+
now,
|
|
571
|
+
);
|
|
572
|
+
mergeStickers(originals);
|
|
573
|
+
mergePacks(originals);
|
|
574
|
+
repoint(originals, id);
|
|
575
|
+
}
|
|
576
|
+
},
|
|
196
577
|
];
|
|
197
578
|
|
|
198
579
|
function migrate(database, migrations = MIGRATIONS) {
|