levix-bot 4.4.0 → 4.6.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.
@@ -1,4 +1,5 @@
1
1
  const { tr } = require("../utils/i18n.cjs");
2
+ const { isolate } = require("../utils/bidi.cjs");
2
3
  const ownerModule = require("../stickers/owner.cjs");
3
4
  const library = require("../stickers/library.cjs");
4
5
  const { commandHint, countLabel, errorText } = require("../utils/stickerBot.cjs");
@@ -29,7 +30,9 @@ module.exports = {
29
30
  `لا توجد حزم بعد. رد على وسائط بالأمر ${commandHint("pack", "<الاسم>")} لإنشاء حزمة. المكتبة: ${countLabel(total)}.`,
30
31
  ),
31
32
  });
32
- const lines = packs.slice(0, 30).map((pack) => `${pack.name} — ${countLabel(pack.count)}`);
33
+ const lines = packs
34
+ .slice(0, 30)
35
+ .map((pack) => `${isolate(pack.name)} — ${countLabel(pack.count)}`);
33
36
  if (packs.length > 30)
34
37
  lines.push(
35
38
  tr(
@@ -1,92 +1,299 @@
1
- // file: /commands/shortlink.js
1
+ // file: /commands/shortlink.cjs
2
+ //
3
+ // Shortens links with is.gd and falls back to v.gd (the same API on a second
4
+ // host) when the first is unreachable or rate-limits.
5
+ //
6
+ // The link may sit anywhere in the arguments — with or without a scheme, with
7
+ // the punctuation people wrap around it — or, when the arguments carry none,
8
+ // in the message the command is replying to. Up to MAX_LINKS links are
9
+ // shortened and answered in the one status message.
2
10
 
3
11
  const axios = require("axios");
4
12
  const logger = require("../utils/logger.cjs");
5
13
  const { createStatus } = require("../utils/statusMessage.cjs");
6
14
  const { tr } = require("../utils/i18n.cjs");
15
+ const { visibleText, quotedOf } = require("../utils/messageContent.cjs");
7
16
 
8
- // A simple regex to validate if the input is a URL
9
- const urlRegex = new RegExp(/^(https?:\/\/[^\s/$.?#].[^\s]*)$/i);
17
+ // The one HTTP GET the command performs. Exposed so tests can stub the network.
18
+ const http = {
19
+ get: (url, options) => axios.get(url, options),
20
+ };
21
+
22
+ const HTTP_TIMEOUT_MS = 10_000;
23
+ const MAX_LINKS = 5;
24
+
25
+ // is.gd first; v.gd is the fallback — they speak the same API.
26
+ const SHORTENERS = ["is.gd", "v.gd"];
27
+
28
+ // WhatsApp users wrap links in punctuation the API rejects (`see here: x.com).`).
29
+ const LEADING_PUNCTUATION = /^[([{'"]+/;
30
+ const TRAILING_PUNCTUATION = /[)\]}>.,!?;:'"،؛]+$/;
31
+
32
+ // A URL with a scheme, or a bare/`www.` domain. Labels may be any script
33
+ // (\p{L}/\p{N}); the TLD is either two or more letters or a punycode label
34
+ // (`xn--…`) — so "notalink", "1.2.3" and emails are still not links. Unicode
35
+ // domains are punycoded later by `new URL()`.
36
+ const URL_PATTERN =
37
+ /(?<![\p{L}\p{N}@.-])(?:(?:https?:\/\/|www\.)[^\s<>"'`]+|(?:[\p{L}\p{N}](?:[\p{L}\p{N}-]*[\p{L}\p{N}])?\.)+(?:[\p{L}]{2,}|xn--[a-z0-9-]+)(?:\/[^\s<>"'`]*)?)/giu;
38
+
39
+ // The same domain at the start of a candidate, before we add `https://`.
40
+ const BARE_DOMAIN =
41
+ /^(?:[\p{L}\p{N}](?:[\p{L}\p{N}-]*[\p{L}\p{N}])?\.)+(?:[\p{L}]{2,}|xn--[a-z0-9-]+)(?::\d+)?(?:\/|$)/iu;
42
+
43
+ // is.gd's error codes -> the short bilingual reason we show the user.
44
+ const ERROR_REASONS = {
45
+ 1: "invalid", // bad or blocked URL
46
+ 2: "unknown", // a custom-url problem; we never ask for a custom URL
47
+ 3: "rate", // rate limited
48
+ 4: "unreachable", // the service itself failed
49
+ };
50
+
51
+ /** Is `url` an https URL on `host` (or a subdomain of it)? */
52
+ function onHost(url, host) {
53
+ try {
54
+ const parsed = new URL(url);
55
+ if (parsed.protocol !== "https:") return false;
56
+ return parsed.hostname === host || parsed.hostname.endsWith(`.${host}`);
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+
62
+ /** Turn one candidate into a clean https URL, or null when it isn't one. */
63
+ function normaliseUrl(raw) {
64
+ if (raw === null || raw === undefined) return null;
65
+ const trimmed = String(raw)
66
+ .trim()
67
+ .replace(LEADING_PUNCTUATION, "")
68
+ .replace(TRAILING_PUNCTUATION, "");
69
+ if (!trimmed) return null;
70
+
71
+ let candidate = trimmed;
72
+ if (/^www\./i.test(candidate)) {
73
+ candidate = `https://${candidate}`;
74
+ } else if (!/^https?:\/\//i.test(candidate)) {
75
+ // A bare domain must look like name.tld[/path] before we trust it.
76
+ if (!BARE_DOMAIN.test(candidate)) return null;
77
+ candidate = `https://${candidate}`;
78
+ }
79
+
80
+ try {
81
+ const parsed = new URL(candidate);
82
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
83
+ // `hostname` is punycode here, so the TLD is Latin letters or `xn--…`.
84
+ if (!/^[a-z0-9.-]+\.(?:[a-z]{2,}|xn--[a-z0-9-]+)$/i.test(parsed.hostname)) return null;
85
+ return parsed.href;
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+
91
+ /** Every distinct usable link in `text`, in order, capped at `limit`. */
92
+ function extractUrls(text, limit = MAX_LINKS) {
93
+ const found = [];
94
+ const seen = new Set();
95
+ for (const match of String(text || "").match(URL_PATTERN) || []) {
96
+ const url = normaliseUrl(match);
97
+ if (!url || seen.has(url)) continue;
98
+ seen.add(url);
99
+ found.push(url);
100
+ if (found.length >= limit) break;
101
+ }
102
+ return found;
103
+ }
104
+
105
+ /** Read one shortener response into { ok: true, url } or { ok: false, reason }. */
106
+ function parseResponse(data, host) {
107
+ let payload = data;
108
+
109
+ if (typeof payload === "string") {
110
+ const text = payload.trim();
111
+ try {
112
+ payload = JSON.parse(text);
113
+ } catch {
114
+ // Not JSON: a bare short URL is still usable, anything else is a failure.
115
+ const direct = normaliseUrl(text);
116
+ return direct && onHost(direct, host)
117
+ ? { ok: true, url: direct }
118
+ : { ok: false, reason: "unreachable" };
119
+ }
120
+ }
121
+
122
+ if (payload && typeof payload === "object") {
123
+ if (typeof payload.shorturl === "string" && payload.shorturl) {
124
+ const short = normaliseUrl(payload.shorturl);
125
+ return short && onHost(short, host)
126
+ ? { ok: true, url: short }
127
+ : { ok: false, reason: "unreachable" };
128
+ }
129
+ if (typeof payload.errorcode === "number") {
130
+ return { ok: false, reason: ERROR_REASONS[payload.errorcode] || "unknown" };
131
+ }
132
+ }
133
+
134
+ return { ok: false, reason: "unreachable" };
135
+ }
136
+
137
+ function apiUrl(host, longUrl) {
138
+ return `https://${host}/create.php?format=json&url=${encodeURIComponent(longUrl)}`;
139
+ }
140
+
141
+ /**
142
+ * Shorten one link, trying each shortener in turn. A rejection (invalid or
143
+ * blocked URL) is final; an unreachable or rate-limited host falls through to
144
+ * the next one.
145
+ */
146
+ async function shortenUrl(longUrl, get = http.get) {
147
+ let reason = "unreachable";
148
+
149
+ for (const host of SHORTENERS) {
150
+ try {
151
+ const response = await get(apiUrl(host, longUrl), {
152
+ timeout: HTTP_TIMEOUT_MS,
153
+ headers: { Accept: "application/json" },
154
+ });
155
+ const parsed = parseResponse(response?.data, host);
156
+ if (parsed.ok) return parsed;
157
+ reason = parsed.reason;
158
+ if (parsed.reason === "invalid") return parsed;
159
+ } catch (error) {
160
+ const status = error?.response?.status;
161
+ if (status === 429) {
162
+ reason = "rate";
163
+ } else if (error?.response?.data) {
164
+ const parsed = parseResponse(error.response.data, host);
165
+ reason = parsed.ok ? "unreachable" : parsed.reason;
166
+ } else {
167
+ reason = "unreachable";
168
+ }
169
+ }
170
+ }
171
+
172
+ return { ok: false, reason };
173
+ }
174
+
175
+ /** One short bilingual line explaining why a link could not be shortened. */
176
+ function failureText(reason) {
177
+ switch (reason) {
178
+ case "invalid":
179
+ return tr(
180
+ "the service rejected the link (invalid or blocked)",
181
+ "الخدمة رفضت الرابط (غير صالح أو محظور)",
182
+ );
183
+ case "rate":
184
+ return tr(
185
+ "the service is rate-limiting, try again later",
186
+ "الخدمة تحدّ من الطلبات، جرّب لاحقًا",
187
+ );
188
+ case "unreachable":
189
+ return tr("the service is unreachable right now", "تعذّر الوصول إلى الخدمة حاليًا");
190
+ default:
191
+ return tr("an unknown error happened", "حدث خطأ غير معروف");
192
+ }
193
+ }
194
+
195
+ /** Turn every result into the single reply that lands in the status message. */
196
+ function renderResults(results) {
197
+ const ok = results.filter((result) => result.ok);
198
+
199
+ if (!ok.length) {
200
+ const reason = results[results.length - 1].reason;
201
+ if (results.length === 1) {
202
+ return tr(
203
+ `❌ *Couldn't shorten the link*\n\n${failureText(reason)}`,
204
+ `❌ *تعذّر اختصار الرابط*\n\n${failureText(reason)}`,
205
+ );
206
+ }
207
+ const failed = results.map((r) => `• ${r.url} — ${failureText(r.reason)}`).join("\n");
208
+ return tr(
209
+ `❌ *Couldn't shorten any of the links*\n\n${failed}`,
210
+ `❌ *تعذّر اختصار أي من الروابط*\n\n${failed}`,
211
+ );
212
+ }
213
+
214
+ const heading =
215
+ results.length === 1
216
+ ? tr("✅ Link shortened!", "✅ تم اختصار الرابط!")
217
+ : tr(`✅ Links shortened (${ok.length})!`, `✅ تم اختصار الروابط (${ok.length})!`);
218
+
219
+ const body = results
220
+ .map((r) => (r.ok ? `🔗 ${r.url}` : `❌ ${r.url} — ${failureText(r.reason)}`))
221
+ .join("\n");
222
+
223
+ return `${heading}\n\n${body}`;
224
+ }
225
+
226
+ async function shortenMany(urls) {
227
+ const results = [];
228
+ for (const url of urls) {
229
+ results.push({ url, ...(await shortenUrl(url)) });
230
+ }
231
+ return results;
232
+ }
233
+
234
+ function sendUsage(sock, chatId) {
235
+ return sock.sendMessage(chatId, {
236
+ text: tr(
237
+ "Send the link you want to shorten, or reply to a message containing one.\n\n*Example:*\n`!shortlink https://github.com/WhiskeySockets/Baileys`",
238
+ "أرسل الرابط الذي تريد اختصاره، أو اعمل رد على رسالة تحتوي رابطًا.\n\n*مثال:*\n`!shortlink https://github.com/WhiskeySockets/Baileys`",
239
+ ),
240
+ });
241
+ }
242
+
243
+ function sendInvalid(sock, chatId) {
244
+ return sock.sendMessage(chatId, {
245
+ text: tr(
246
+ "I couldn't find a valid link. Send a URL like `https://example.com`, or reply to a message with one.",
247
+ "لم أجد رابطًا صالحًا. أرسل رابطًا مثل `https://example.com`، أو اعمل رد على رسالة تحتوي عليه.",
248
+ ),
249
+ });
250
+ }
10
251
 
11
252
  module.exports = {
12
253
  name: "shortlink",
13
254
  description: {
14
- en: "Shortens a long URL with the is.gd service.",
15
- ar: "يختصر رابطًا طويلًا باستخدام خدمة is.gd.",
255
+ en: "Shortens up to 5 links with is.gd, falling back to v.gd. Reads a URL from the command or a replied message.",
256
+ ar: "يختصر حتى 5 روابط باستخدام is.gd مع التحويل إلى v.gd عند الحاجة، من الأمر أو من رسالة موجّه لها الرد.",
16
257
  },
17
258
  usage: {
18
- en: "shortlink <url>",
19
- ar: "shortlink <الرابط>",
259
+ en: "shortlink <url> | reply to a message containing a link",
260
+ ar: "shortlink <الرابط> | اعمل رد على رسالة تحتوي رابطًا",
20
261
  },
21
- chat: "all", // This command can be used anywhere
262
+ chat: "all",
22
263
  neutralArgs: true, // a URL is not a language
23
264
 
24
265
  async execute(sock, msg, args) {
25
- // 1. Check if the user provided any arguments
26
- if (!args || args.length === 0) {
27
- return await sock.sendMessage(msg.key.remoteJid, {
28
- text: tr(
29
- "Send the link you want to shorten.\n\n*Example:*\n`!shortlink https://github.com/WhiskeySockets/Baileys`",
30
- "يرجى إرسال الرابط الذي تريد اختصاره.\n\n*مثال:*\n`!shortlink https://github.com/WhiskeySockets/Baileys`",
31
- ),
32
- });
33
- }
266
+ const chatId = msg.key.remoteJid;
267
+ const argText = (args || []).join(" ").trim();
268
+ const quoted = quotedOf(msg);
269
+ const quotedText = quoted ? visibleText(quoted) : "";
34
270
 
35
- const longUrl = args[0];
271
+ let urls = extractUrls(argText);
272
+ if (!urls.length && quotedText) urls = extractUrls(quotedText);
36
273
 
37
- // 2. Validate if the provided argument is a valid URL
38
- if (!urlRegex.test(longUrl)) {
39
- return await sock.sendMessage(msg.key.remoteJid, {
40
- text: tr(
41
- "That link isn't valid. Make sure it starts with `http://` or `https://`.",
42
- "الرابط الذي أرسلته غير صالح. يرجى التأكد من أنه يبدأ بـ `http://` أو `https://`.",
43
- ),
44
- });
274
+ if (!urls.length) {
275
+ if (!argText && !quotedText) return sendUsage(sock, chatId);
276
+ return sendInvalid(sock, chatId);
45
277
  }
46
278
 
47
- // 3. Define the API endpoint for is.gd
48
- // We use `encodeURIComponent` to ensure the URL is properly formatted for the API request
49
- const API_URL = `https://is.gd/create.php?format=simple&url=${encodeURIComponent(longUrl)}`;
50
-
51
- // One message: "shortening..." becomes the short link itself.
52
- const status = await createStatus(
53
- sock,
54
- msg.key.remoteJid,
55
- tr("🔗 Shortening...", "🔗 بختصر الرابط..."),
56
- {
57
- replyTo: msg,
58
- },
59
- );
279
+ // One message: "shortening..." becomes the short link(s) or the reason.
280
+ const status = await createStatus(sock, chatId, tr("🔗 Shortening...", "🔗 بختصر الرابط..."), {
281
+ replyTo: msg,
282
+ });
60
283
 
61
284
  try {
62
- // 4. Make the GET request to the API
63
- const response = await axios.get(API_URL);
64
-
65
- // 5. The API returns the shortened URL as plain text in the response body
66
- const shortUrl = response.data;
67
-
68
- const reply = tr(
69
- `✅ Link shortened!\n\n🔗 *Short link:*\n${shortUrl}`,
70
- `✅ تم اختصار الرابط بنجاح!\n\n` + `🔗 *الرابط المختصر:*\n${shortUrl}`,
71
- );
72
-
73
- await status.finish(reply);
285
+ const results = await shortenMany(urls);
286
+ await status.finish(renderResults(results));
74
287
  } catch (error) {
75
- logger.error(
76
- error.response ? error.response.data : error.message,
77
- "[Error] in !shortlink command:",
78
- );
79
-
80
- // The API returns a plain text error message if something goes wrong
81
- const errorMessage = error.response
82
- ? error.response.data
83
- : tr("Something unexpected went wrong.", "حدث خطأ غير متوقع.");
84
-
85
- await sock.sendMessage(msg.key.remoteJid, {
86
- text:
87
- tr(`*Sorry, something went wrong:*\n\n`, `*عذرًا، حدث خطأ:*\n\n`) +
88
- `\`\`\`${errorMessage}\`\`\``,
89
- });
288
+ logger.error({ err: error, command: "shortlink" }, "[Error] in !shortlink command");
289
+ await status.fail(error, tr("Couldn't shorten the link", "تعذّر اختصار الرابط"));
90
290
  }
91
291
  },
292
+
293
+ // Pure helpers and the HTTP seam, kept for tests.
294
+ http,
295
+ extractUrls,
296
+ normaliseUrl,
297
+ parseResponse,
298
+ shortenUrl,
92
299
  };
@@ -1,4 +1,5 @@
1
1
  const { tr } = require("../utils/i18n.cjs");
2
+ const { isolate } = require("../utils/bidi.cjs");
2
3
  const { BOT_PAGE_SIZE } = require("../stickers/limits.cjs");
3
4
  const { StickerError } = require("../stickers/errors.cjs");
4
5
  const ownerModule = require("../stickers/owner.cjs");
@@ -13,21 +14,26 @@ const {
13
14
  function parse(args) {
14
15
  const parts = [...args];
15
16
  let page = 1;
16
- if (/^[1-9]\d*$/.test(parts.at(-1) || "")) page = Number(parts.pop());
17
+ let pageExplicit = false;
18
+ if (/^[1-9]\d*$/.test(parts.at(-1) || "")) {
19
+ page = Number(parts.pop());
20
+ pageExplicit = true;
21
+ }
17
22
  if (!Number.isSafeInteger(page) || page > 1_000_000) throw new StickerError("INVALID_OPTIONS");
18
23
  const first = parts.shift()?.toLowerCase();
19
24
  if (!first || first === "recent" || first === "الأحدث") {
20
25
  if (parts.length) throw new StickerError("INVALID_OPTIONS");
21
- return { mode: "recent", page };
26
+ return { mode: "recent", page, pageExplicit };
22
27
  }
23
28
  if (first === "favorites" || first === "المفضلة") {
24
29
  if (parts.length) throw new StickerError("INVALID_OPTIONS");
25
- return { mode: "favorites", page };
30
+ return { mode: "favorites", page, pageExplicit };
26
31
  }
27
32
  if (first === "pack" || first === "حزمة") {
28
33
  const name = parts.join(" ").trim();
29
34
  if (!name) throw new StickerError("INVALID_NAME");
30
- return { mode: "pack", name, page };
35
+ const fullName = pageExplicit ? `${name} ${page}` : name;
36
+ return { mode: "pack", name, fullName, page, pageExplicit };
31
37
  }
32
38
  throw new StickerError("INVALID_OPTIONS");
33
39
  }
@@ -54,20 +60,32 @@ module.exports = {
54
60
  });
55
61
  try {
56
62
  const selected = parse(args);
57
- const query = { limit: BOT_PAGE_SIZE, offset: (selected.page - 1) * BOT_PAGE_SIZE };
63
+ const query = { limit: BOT_PAGE_SIZE };
58
64
  let label = tr("Recent stickers", "الملصقات الحديثة");
59
65
  if (selected.mode === "favorites") {
60
66
  query.filter = "favorites";
61
67
  label = tr("Favorite stickers", "الملصقات المفضلة");
62
68
  } 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 });
69
+ // A trailing number is a page unless the whole text names an existing
70
+ // pack (a pack can itself end in a number: "عيد 2").
71
+ let name = selected.name;
72
+ if (selected.pageExplicit) {
73
+ const asName = library.findPackByName(who, selected.fullName);
74
+ if (asName) {
75
+ name = selected.fullName;
76
+ selected.page = 1;
77
+ }
78
+ }
79
+ const pack = library.findPackByName(who, name);
80
+ if (!pack) throw new StickerError("PACK_NOT_FOUND", { name });
65
81
  query.pack = pack.id;
66
- label = pack.name;
82
+ selected.name = pack.name;
83
+ label = isolate(pack.name);
67
84
  } else {
68
85
  query.filter = "all";
69
86
  query.sort = "recent";
70
87
  }
88
+ query.offset = (selected.page - 1) * BOT_PAGE_SIZE;
71
89
  const { items, total } = library.listStickers(who, query);
72
90
  if (!total)
73
91
  return sock.sendMessage(jid, {
@@ -53,6 +53,7 @@ const COMMAND_PERMISSIONS = Object.freeze({
53
53
  digit: "MEMBERS",
54
54
  block: "OWNER_ONLY",
55
55
  unblock: "OWNER_ONLY",
56
+ autodelete: "OWNER_ONLY",
56
57
  send: "MEMBERS",
57
58
  sticker: "MEMBERS",
58
59
  toimage: "MEMBERS",
@@ -471,6 +471,16 @@ const SETTINGS = [
471
471
  label: "Forward counters kept (days)",
472
472
  hint: "How long the !score counters survive. They gain a row per forwarded message.",
473
473
  },
474
+ {
475
+ key: "auto_delete_keep_days",
476
+ type: "int",
477
+ default: 30,
478
+ min: 1,
479
+ max: 365,
480
+ group: "server",
481
+ label: "Auto-delete copies kept (days)",
482
+ hint: "How long opt-in copies of auto-deleted messages (text/caption only) survive.",
483
+ },
474
484
  ];
475
485
 
476
486
  const BY_KEY = new Map(SETTINGS.map((definition) => [definition.key, definition]));
@@ -49,8 +49,10 @@
49
49
  import { DisconnectReason } from "@whiskeysockets/baileys";
50
50
  import { createRequire } from "module";
51
51
  import { RETRY_SCHEDULE_MS } from "../config/constants.js";
52
+ import { bootstrapAdmins, bootstrapOwners } from "../utils/permissions.esm.js";
52
53
  import {
53
54
  clearAuthState,
55
+ clearAutoDeleteOnUnlink,
54
56
  clearWhatsAppDirectory,
55
57
  deleteAllChatHistories,
56
58
  deleteQrCode,
@@ -58,7 +60,6 @@ import {
58
60
  pauseAllSchedules,
59
61
  saveQrCode,
60
62
  } from "../utils/storage.esm.js";
61
- import { bootstrapAdmins, bootstrapOwners } from "../utils/permissions.esm.js";
62
63
  import { classifyDisconnect, handleConnectionOpen } from "./connection.js";
63
64
  import { setupEventListeners } from "./events.js";
64
65
  import {
@@ -100,6 +101,13 @@ function clearAccountScopedState() {
100
101
  try {
101
102
  groupMetadataCache.flushAll();
102
103
  } catch {}
104
+ try {
105
+ // Copies of deleted messages and the counters are account-derived; the
106
+ // rules themselves are operator configuration and stay.
107
+ clearAutoDeleteOnUnlink();
108
+ } catch (error) {
109
+ logger.warn({ err: error }, "[Session] failed to clear auto-delete copies after unlink");
110
+ }
103
111
  }
104
112
 
105
113
  // Baileys' `end()` awaits `ws.close()`, which waits for the socket's own
package/src/db/db.cjs CHANGED
@@ -574,6 +574,51 @@ const MIGRATIONS = [
574
574
  repoint(originals, id);
575
575
  }
576
576
  },
577
+ // v6 — scheduled messages can carry one media file. The bytes live in
578
+ // <data>/media/schedules/<job id>; this column holds the metadata the
579
+ // delivery needs (kind, MIME type, file name).
580
+ (database) => {
581
+ database.exec(`ALTER TABLE schedules ADD COLUMN media TEXT;`);
582
+ },
583
+ // v8 — keyword auto-delete rules, plus an opt-in log of text/caption copies
584
+ // of messages a rule actually deleted (never media bytes).
585
+ (database) => {
586
+ database.exec(`
587
+ CREATE TABLE auto_delete_rules (
588
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
589
+ name TEXT,
590
+ enabled INTEGER NOT NULL DEFAULT 1,
591
+ keywords TEXT NOT NULL,
592
+ match_mode TEXT NOT NULL CHECK (match_mode IN ('contains','word','exact')),
593
+ chat_scope TEXT NOT NULL CHECK (chat_scope IN ('all','groups','private')),
594
+ senders_mode TEXT NOT NULL CHECK (senders_mode IN ('everyone','selected')),
595
+ senders_list TEXT NOT NULL DEFAULT '[]',
596
+ include_own INTEGER NOT NULL DEFAULT 0,
597
+ for_everyone INTEGER NOT NULL DEFAULT 1,
598
+ keep_copy INTEGER NOT NULL DEFAULT 0,
599
+ deleted_count INTEGER NOT NULL DEFAULT 0,
600
+ last_deleted_at INTEGER,
601
+ created_at INTEGER NOT NULL,
602
+ updated_at INTEGER NOT NULL
603
+ );
604
+ CREATE INDEX idx_auto_delete_rules_enabled
605
+ ON auto_delete_rules (enabled, id);
606
+
607
+ CREATE TABLE auto_delete_log (
608
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
609
+ rule_id INTEGER NOT NULL,
610
+ chat_jid TEXT NOT NULL,
611
+ sender TEXT,
612
+ text TEXT,
613
+ media_type TEXT,
614
+ mode TEXT NOT NULL,
615
+ created_at INTEGER NOT NULL,
616
+ FOREIGN KEY (rule_id) REFERENCES auto_delete_rules (id) ON DELETE CASCADE
617
+ );
618
+ CREATE INDEX idx_auto_delete_log_created ON auto_delete_log (created_at);
619
+ CREATE INDEX idx_auto_delete_log_rule ON auto_delete_log (rule_id, created_at);
620
+ `);
621
+ },
577
622
  ];
578
623
 
579
624
  function migrate(database, migrations = MIGRATIONS) {
@@ -643,6 +688,24 @@ function sweepExpired() {
643
688
  } catch (err) {
644
689
  logger.error({ err }, "[DB] sweep failed");
645
690
  }
691
+ try {
692
+ let days = 30;
693
+ try {
694
+ days = require("../config/settings.cjs").get("auto_delete_keep_days");
695
+ } catch {
696
+ days = 30;
697
+ }
698
+ const cutoff = Date.now() - Number(days || 30) * 24 * 60 * 60 * 1000;
699
+ const { changes } = q("DELETE FROM auto_delete_log WHERE created_at < ?").run(cutoff);
700
+ if (changes) logger.debug(`[DB] Swept ${changes} expired auto-delete copies`);
701
+ q(
702
+ `DELETE FROM auto_delete_log WHERE id NOT IN (
703
+ SELECT id FROM auto_delete_log ORDER BY created_at DESC, id DESC LIMIT 5000
704
+ )`,
705
+ ).run();
706
+ } catch (err) {
707
+ logger.error({ err }, "[DB] auto-delete log sweep failed");
708
+ }
646
709
  }
647
710
 
648
711
  /** Flush the WAL into the main file — called on shutdown and after a backup. */