levix-bot 4.3.1 → 4.5.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 (47) hide show
  1. package/README.md +4 -2
  2. package/package.json +1 -1
  3. package/public/dashboard/assets/index-COI8zgqa.css +2 -0
  4. package/public/dashboard/assets/index-IZMBuNAZ.js +505 -0
  5. package/public/dashboard/index.html +2 -2
  6. package/public/dashboard.css +32 -0
  7. package/scheduler.cjs +66 -7
  8. package/src/bootstrap/panel.js +16 -4
  9. package/src/commands/pack.cjs +159 -0
  10. package/src/commands/packs.cjs +47 -0
  11. package/src/commands/send.cjs +1 -18
  12. package/src/commands/sticker.cjs +77 -232
  13. package/src/commands/stickers.cjs +100 -0
  14. package/src/commands/toimage.cjs +88 -0
  15. package/src/config/defaults.cjs +5 -0
  16. package/src/config/settings.cjs +10 -0
  17. package/src/core/events.js +15 -1
  18. package/src/core/session.js +7 -0
  19. package/src/db/db.cjs +387 -0
  20. package/src/db/store.cjs +746 -24
  21. package/src/handlers/command.handler.js +4 -0
  22. package/src/panel/feedback.cjs +43 -14
  23. package/src/routes/dashboard.api.esm.js +172 -20
  24. package/src/routes/stickers.api.esm.js +570 -0
  25. package/src/services/llmDiscovery.cjs +32 -10
  26. package/src/stickers/errors.cjs +239 -0
  27. package/src/stickers/ffmpeg.cjs +133 -0
  28. package/src/stickers/jobs.cjs +183 -0
  29. package/src/stickers/library.cjs +712 -0
  30. package/src/stickers/limits.cjs +60 -0
  31. package/src/stickers/media.cjs +748 -0
  32. package/src/stickers/options.cjs +128 -0
  33. package/src/stickers/owner.cjs +103 -0
  34. package/src/stickers/studio.cjs +473 -0
  35. package/src/stickers/uploads.cjs +263 -0
  36. package/src/stickers/webp.cjs +231 -0
  37. package/src/stickers/zip.cjs +107 -0
  38. package/src/utils/messageContent.cjs +30 -4
  39. package/src/utils/multipart.esm.js +81 -0
  40. package/src/utils/recurrence.cjs +189 -30
  41. package/src/utils/stickerBot.cjs +84 -0
  42. package/src/utils/storage.cjs +3 -0
  43. package/src/utils/storage.esm.js +3 -0
  44. package/views/login.ejs +39 -3
  45. package/views/setup.ejs +21 -0
  46. package/public/dashboard/assets/index-B6RhYFIy.js +0 -446
  47. package/public/dashboard/assets/index-vEwOcxiH.css +0 -2
@@ -49,6 +49,10 @@ const EDIT_IN_PLACE_EXCLUDE = new Set([
49
49
  "loop",
50
50
  "rand",
51
51
  "poll",
52
+ "sticker",
53
+ "toimage",
54
+ "pack",
55
+ "stickers",
52
56
  ]);
53
57
 
54
58
  // Wrap a socket so commands reply nicely:
@@ -14,8 +14,8 @@
14
14
  //
15
15
  // Nothing is sent unless the operator presses Send, and nothing about WhatsApp
16
16
  // — no message, chat, contact, credential or key — is ever attached. What goes
17
- // out is exactly the four fields below plus the runtime facts in
18
- // describeRuntime().
17
+ // out is exactly the four fields below, an optional file the operator picked
18
+ // themselves, and the runtime facts in describeRuntime().
19
19
 
20
20
  const fs = require("node:fs");
21
21
  const logger = require("../utils/logger.cjs");
@@ -29,6 +29,9 @@ const TOPICS = Object.freeze(["bug", "idea", "question", "praise", "other"]);
29
29
  const MESSAGE_MIN = 10;
30
30
  const MESSAGE_MAX = 2000;
31
31
  const CONTACT_MAX = 200;
32
+ // One screenshot or log file rides along as multipart; the receiving end
33
+ // forwards it to Telegram as a document, whose own bot-API cap is 50 MB.
34
+ const ATTACHMENT_MAX = 20 * 1024 * 1024;
32
35
 
33
36
  // One operator, pressing a button. This only exists so a stuck retry loop in a
34
37
  // browser tab cannot turn into a flood the receiving end has to absorb.
@@ -150,32 +153,57 @@ function safeRemoteError(value) {
150
153
  }
151
154
 
152
155
  /**
153
- * Forward one validated submission.
156
+ * Forward one validated submission. An attachment (already size-checked by
157
+ * the route) turns the forward into multipart: the fields travel as a JSON
158
+ * "payload" part and the file as "file", and the endpoint delivers it to
159
+ * Telegram as a document instead of a message.
154
160
  *
155
161
  * @param {{ message: string, topic: string, rating: number|null, contact: string|null }} feedback
162
+ * @param {{ buffer: Buffer, name: string, type: string, size: number } | null} attachment
156
163
  * @returns {Promise<{ ok: true } | { ok: false, status: number, error: string }>}
157
164
  */
158
- async function submitFeedback(feedback) {
165
+ async function submitFeedback(feedback, attachment = null) {
159
166
  const endpoint = process.env.LEVIX_FEEDBACK_URL || DEFAULT_ENDPOINT;
160
167
  const runtime = describeRuntime();
161
168
 
162
169
  recordAttempt();
163
170
 
171
+ const envelope = {
172
+ ...feedback,
173
+ source: "panel",
174
+ app: { version: runtime.version, platform: runtime.platform, locale: runtime.locale },
175
+ };
176
+
164
177
  let response;
165
178
  let data = null;
166
179
  try {
180
+ let body;
181
+ const headers = {
182
+ "User-Agent": `Levix/${runtime.version} (${runtime.platform})`,
183
+ };
184
+ const hasFile =
185
+ attachment && Buffer.isBuffer(attachment.buffer) && attachment.buffer.length > 0;
186
+ if (hasFile) {
187
+ const form = new FormData();
188
+ form.set("payload", JSON.stringify(envelope));
189
+ form.set(
190
+ "file",
191
+ new Blob([attachment.buffer], {
192
+ type: attachment.type || "application/octet-stream",
193
+ }),
194
+ attachment.name || "attachment",
195
+ );
196
+ body = form;
197
+ } else {
198
+ headers["Content-Type"] = "application/json";
199
+ body = JSON.stringify(envelope);
200
+ }
167
201
  response = await fetch(endpoint, {
168
202
  method: "POST",
169
- headers: {
170
- "Content-Type": "application/json",
171
- "User-Agent": `Levix/${runtime.version} (${runtime.platform})`,
172
- },
173
- body: JSON.stringify({
174
- ...feedback,
175
- source: "panel",
176
- app: { version: runtime.version, platform: runtime.platform, locale: runtime.locale },
177
- }),
178
- signal: AbortSignal.timeout(15000),
203
+ headers,
204
+ body,
205
+ // Room for a 20 MB attachment on a slow uplink, not for a hang.
206
+ signal: AbortSignal.timeout(120000),
179
207
  });
180
208
  data = await response.json().catch(() => null);
181
209
  } catch (error) {
@@ -223,6 +251,7 @@ module.exports = {
223
251
  MESSAGE_MIN,
224
252
  MESSAGE_MAX,
225
253
  CONTACT_MAX,
254
+ ATTACHMENT_MAX,
226
255
  validateFeedback,
227
256
  describeRuntime,
228
257
  feedbackRetryAfter,
@@ -37,8 +37,12 @@ import {
37
37
  getGroupSettings,
38
38
  getRecentDebts,
39
39
  getSchedules,
40
+ rememberSavedName,
41
+ resolveUserPhone,
40
42
  saveGroupSettings,
41
43
  } from "../utils/storage.esm.js";
44
+ import normalizeJid, { isLidJid } from "../utils/normalizeJid.esm.js";
45
+ import { fileToBuffer, MultipartError, readMultipartForm } from "../utils/multipart.esm.js";
42
46
 
43
47
  const require = createRequire(import.meta.url);
44
48
  const logger = require("../utils/logger.cjs");
@@ -49,6 +53,7 @@ const secrets = require("../config/secrets.cjs");
49
53
  const { clientAddress } = require("../utils/requestOrigin.cjs");
50
54
  const { blockedFor, recordFailure, clearAttempts } = require("../panel/login-throttle.cjs");
51
55
  const {
56
+ ATTACHMENT_MAX: FEEDBACK_ATTACHMENT_MAX,
52
57
  TOPICS: FEEDBACK_TOPICS,
53
58
  MESSAGE_MAX: FEEDBACK_MESSAGE_MAX,
54
59
  MESSAGE_MIN: FEEDBACK_MESSAGE_MIN,
@@ -61,12 +66,18 @@ const { stampPanelSession } = require("../panel/session-auth.cjs");
61
66
  const { DATA_DIR } = require("../config/paths.cjs");
62
67
  const { PERSONA_FILE, activeProviderKeySetting } = require("../services/aiAgent.cjs");
63
68
  const {
69
+ SCHEDULE_MEDIA_MAX_BYTES,
64
70
  deleteScheduledJob,
65
71
  retryScheduledJob,
72
+ scheduleMediaPath,
66
73
  scheduleNewJob,
67
74
  saveScheduledJob,
68
75
  } = require("../../scheduler.cjs");
69
- const { describeScheduledJob } = require("../utils/recurrence.cjs");
76
+ const {
77
+ describeScheduledJob,
78
+ recurrenceErrorMessage,
79
+ recurrenceToCron,
80
+ } = require("../utils/recurrence.cjs");
70
81
  const { discoverProviderModels, DiscoveryError } = require("../services/llmDiscovery.cjs");
71
82
  const settingsTransfer = require("../services/settingsTransfer.cjs");
72
83
  const cron = require("node-cron");
@@ -407,6 +418,7 @@ router.post(
407
418
  apiKey,
408
419
  baseUrl,
409
420
  refresh = false,
421
+ cacheOnly = false,
410
422
  } = req.body || {};
411
423
 
412
424
  const provKey = String(provider || "gemini").toLowerCase();
@@ -433,6 +445,7 @@ router.post(
433
445
  apiKey: effectiveKey,
434
446
  baseUrl: effectiveBaseUrl,
435
447
  refresh: Boolean(refresh),
448
+ cacheOnly: Boolean(cacheOnly),
436
449
  });
437
450
 
438
451
  return res.json(result);
@@ -960,10 +973,14 @@ function scheduleView(job) {
960
973
  const peer = describePeer(job.targetJid);
961
974
  return {
962
975
  ...job,
963
- when: describeScheduledJob(job, timezone),
976
+ when: describeScheduledJob(job, timezone, "en"),
977
+ whenAr: describeScheduledJob(job, timezone, "ar"),
964
978
  targetLabel: peer.label,
965
979
  targetKind: peer.kind,
966
980
  targetPhone: peer.phone,
981
+ savedName: peer.savedName ?? null,
982
+ pushName: peer.pushName ?? null,
983
+ phone: peer.phone,
967
984
  };
968
985
  }
969
986
 
@@ -986,6 +1003,9 @@ router.get("/recipients", (req, res) => {
986
1003
  name: live?.subject || peer.label,
987
1004
  type: "group",
988
1005
  memberCount: live?.participants?.length ?? peer.memberCount,
1006
+ savedName: null,
1007
+ pushName: null,
1008
+ phone: null,
989
1009
  });
990
1010
  };
991
1011
 
@@ -996,14 +1016,26 @@ router.get("/recipients", (req, res) => {
996
1016
  const users = getAllUsers() || [];
997
1017
  users.sort((a, b) => (b.lastSeen || 0) - (a.lastSeen || 0));
998
1018
  for (const u of users.slice(0, 80)) {
999
- const jid = u.jid;
1000
- if (!jid || seen.has(jid) || String(jid).endsWith("@g.us")) continue;
1001
- seen.add(jid);
1002
- const peer = describePeer(jid);
1019
+ if (!u.jid || seen.has(u.jid) || String(u.jid).endsWith("@g.us")) continue;
1020
+ const peer = describePeer(u.jid);
1021
+ const personKey = peer.phone || u.lid || u.jid;
1022
+ if (seen.has(personKey)) continue;
1023
+ // The phone-number JID wins when one is known: it is the stable
1024
+ // identity to schedule against, and it keeps an @lid row from ever
1025
+ // reaching the picker as a raw id.
1026
+ // peer.phone is the "+<digits>" display label; a JID wants the digits.
1027
+ const digits = peer.phone ? peer.phone.replace(/\D/g, "") : "";
1028
+ const id = digits ? `${digits}@s.whatsapp.net` : u.jid;
1029
+ seen.add(u.jid);
1030
+ seen.add(id);
1031
+ seen.add(personKey);
1032
+ if (u.lid) seen.add(u.lid);
1003
1033
  recipients.push({
1004
- id: jid,
1034
+ id,
1005
1035
  name: peer.label,
1006
1036
  phone: peer.phone,
1037
+ savedName: peer.savedName ?? null,
1038
+ pushName: peer.pushName ?? null,
1007
1039
  type: "contact",
1008
1040
  });
1009
1041
  }
@@ -1014,6 +1046,32 @@ router.get("/recipients", (req, res) => {
1014
1046
  }
1015
1047
  });
1016
1048
 
1049
+ // The formats WhatsApp renders inline. Anything else (SVG, HEIC, MKV, WAV…)
1050
+ // would arrive as a broken image/video/voice bubble, so it goes as a document.
1051
+ const INLINE_IMAGE = new Set(["image/jpeg", "image/png", "image/webp"]);
1052
+ const INLINE_VIDEO = new Set(["video/mp4", "video/3gpp"]);
1053
+ const INLINE_AUDIO = new Set([
1054
+ "audio/mpeg",
1055
+ "audio/mp4",
1056
+ "audio/x-m4a",
1057
+ "audio/aac",
1058
+ "audio/ogg",
1059
+ "audio/opus",
1060
+ "audio/amr",
1061
+ ]);
1062
+
1063
+ /** Which WhatsApp shape an uploaded file is delivered as. */
1064
+ function scheduleMediaKind(mime) {
1065
+ const base = String(mime || "")
1066
+ .split(";")[0]
1067
+ .trim()
1068
+ .toLowerCase();
1069
+ if (INLINE_IMAGE.has(base)) return "image";
1070
+ if (INLINE_VIDEO.has(base)) return "video";
1071
+ if (INLINE_AUDIO.has(base)) return "audio";
1072
+ return "document";
1073
+ }
1074
+
1017
1075
  router.post(
1018
1076
  "/schedules",
1019
1077
  asyncRoute(async (req, res) => {
@@ -1022,26 +1080,76 @@ router.post(
1022
1080
  return badRequest(res, "Maximum 3 scheduled messages reached");
1023
1081
  }
1024
1082
 
1025
- const { targetJid, message, type, cronString, scheduledTime } = req.body || {};
1026
- if (!targetJid || !message) {
1027
- return badRequest(res, "Recipient and message are required");
1083
+ // The panel sends JSON; a scheduled message with media arrives as
1084
+ // multipart/form-data (browser FormData or the Android host bridge), with
1085
+ // the same fields as text parts plus one file part.
1086
+ let body = req.body || {};
1087
+ let file = null;
1088
+ if (
1089
+ String(req.headers["content-type"] || "")
1090
+ .toLowerCase()
1091
+ .startsWith("multipart/form-data")
1092
+ ) {
1093
+ try {
1094
+ const parsed = await readMultipartForm(req, { maxFileSize: SCHEDULE_MEDIA_MAX_BYTES });
1095
+ body = parsed.fields;
1096
+ file = parsed.file;
1097
+ } catch (error) {
1098
+ if (error instanceof MultipartError) return badRequest(res, error.message);
1099
+ throw error;
1100
+ }
1101
+ }
1102
+
1103
+ let recurrence = body.recurrence;
1104
+ if (recurrence && typeof recurrence === "string") {
1105
+ try {
1106
+ recurrence = JSON.parse(recurrence);
1107
+ } catch {
1108
+ recurrence = null;
1109
+ }
1110
+ }
1111
+
1112
+ const { targetJid, message, type, cronString, scheduledTime, targetName } = body;
1113
+ if (!targetJid || (!message && !file)) {
1114
+ return badRequest(res, "Recipient and a message or a file are required");
1028
1115
  }
1029
1116
 
1030
1117
  const id = Date.now().toString();
1118
+
1119
+ // An @lid target is resolved to its phone-number JID while the mapping is
1120
+ // fresh, so delivery and the label never depend on the LID still being
1121
+ // mapped months later. Unresolvable LIDs are kept as they are.
1122
+ // A phone JID never carries the "+" of the display label.
1123
+ let target = normalizeJid(String(targetJid).trim().replace(/^\+/, ""));
1124
+ if (isLidJid(target)) {
1125
+ const phone = resolveUserPhone(target);
1126
+ if (phone) target = `${phone}@s.whatsapp.net`;
1127
+ }
1128
+
1031
1129
  const job = {
1032
1130
  id,
1033
1131
  type: type === "once" ? "once" : "recurring",
1034
- targetJid: String(targetJid).trim(),
1035
- message: String(message).trim(),
1132
+ targetJid: target,
1133
+ message: String(message ?? "").trim(),
1036
1134
  creatorJid: "dashboard@levix",
1037
1135
  status: "active",
1038
1136
  };
1039
1137
 
1040
1138
  if (job.type === "recurring") {
1041
- if (!cronString || !cron.validate(cronString)) {
1042
- return badRequest(res, "Invalid cron expression");
1139
+ if (recurrence && typeof recurrence === "object") {
1140
+ const built = recurrenceToCron(recurrence);
1141
+ if (built.error) return badRequest(res, recurrenceErrorMessage(built.error));
1142
+ if (!cron.validate(built.cronString)) {
1143
+ return badRequest(res, recurrenceErrorMessage("recurrence"));
1144
+ }
1145
+ job.cronString = built.cronString;
1146
+ } else if (cronString && cron.validate(cronString)) {
1147
+ // Raw cron is accepted only for existing callers/tests. The panel
1148
+ // sends a structured `recurrence` object and never a cron string.
1149
+ job.cronString = cronString;
1150
+ } else {
1151
+ return badRequest(res, "Invalid recurrence");
1043
1152
  }
1044
- job.cron = cronString;
1045
1153
  } else {
1046
1154
  const timeMs = Number(scheduledTime);
1047
1155
  if (!timeMs || timeMs <= Date.now()) {
@@ -1050,13 +1158,30 @@ router.post(
1050
1158
  job.date = new Date(timeMs).toISOString();
1051
1159
  }
1052
1160
 
1053
- saveScheduledJob(job);
1161
+ // Written only once the job is known to be valid, so a refused request
1162
+ // never leaves a file behind with no row to delete it.
1163
+ if (file) {
1164
+ const mediaPath = scheduleMediaPath(id);
1165
+ fs.mkdirSync(path.dirname(mediaPath), { recursive: true });
1166
+ fs.writeFileSync(mediaPath, await fileToBuffer(file));
1167
+ job.media = {
1168
+ kind: scheduleMediaKind(file.type),
1169
+ mimeType: file.type || "application/octet-stream",
1170
+ fileName: file.name || null,
1171
+ };
1172
+ }
1173
+
1174
+ if (targetName && !job.targetJid.endsWith("@g.us")) {
1175
+ rememberSavedName(job.targetJid, targetName);
1176
+ }
1177
+
1178
+ const saved = saveScheduledJob(job);
1054
1179
  const sock = currentSocket();
1055
1180
  if (sock) {
1056
- scheduleNewJob(sock, job);
1181
+ scheduleNewJob(sock, saved);
1057
1182
  }
1058
1183
 
1059
- res.json({ success: true, schedule: scheduleView(job) });
1184
+ res.json({ success: true, schedule: scheduleView(saved) });
1060
1185
  }),
1061
1186
  );
1062
1187
 
@@ -1177,6 +1302,7 @@ router.get("/feedback/meta", (req, res) => {
1177
1302
  topics: FEEDBACK_TOPICS,
1178
1303
  messageMin: FEEDBACK_MESSAGE_MIN,
1179
1304
  messageMax: FEEDBACK_MESSAGE_MAX,
1305
+ attachmentMax: FEEDBACK_ATTACHMENT_MAX,
1180
1306
  // Shown next to the form so the operator can see what travels with it.
1181
1307
  runtime: { version: runtime.version, platform: runtime.platform },
1182
1308
  });
@@ -1184,10 +1310,36 @@ router.get("/feedback/meta", (req, res) => {
1184
1310
 
1185
1311
  // Leaves this machine only when the operator presses Send, and carries nothing
1186
1312
  // but the form's own fields plus the version and platform — see feedback.cjs.
1313
+ // An optional attachment (a screenshot, a log) rides along as multipart and is
1314
+ // forwarded to the same endpoint, which delivers it to Telegram as a file.
1187
1315
  router.post(
1188
1316
  "/feedback",
1189
1317
  asyncRoute(async (req, res) => {
1190
- const parsed = validateFeedback(req.body || {});
1318
+ let body = req.body || {};
1319
+ let attachment = null;
1320
+ if (
1321
+ String(req.headers["content-type"] || "")
1322
+ .toLowerCase()
1323
+ .startsWith("multipart/form-data")
1324
+ ) {
1325
+ try {
1326
+ const parsed = await readMultipartForm(req, { maxFileSize: FEEDBACK_ATTACHMENT_MAX });
1327
+ body = parsed.fields;
1328
+ if (parsed.file) {
1329
+ attachment = {
1330
+ buffer: await fileToBuffer(parsed.file),
1331
+ name: parsed.file.name || "attachment",
1332
+ type: parsed.file.type || "application/octet-stream",
1333
+ size: parsed.file.size,
1334
+ };
1335
+ }
1336
+ } catch (error) {
1337
+ if (error instanceof MultipartError) return badRequest(res, error.message);
1338
+ throw error;
1339
+ }
1340
+ }
1341
+
1342
+ const parsed = validateFeedback(body);
1191
1343
  if (!parsed.ok) return badRequest(res, parsed.error);
1192
1344
 
1193
1345
  const retryAfter = feedbackRetryAfter();
@@ -1199,7 +1351,7 @@ router.post(
1199
1351
  });
1200
1352
  }
1201
1353
 
1202
- const result = await submitFeedback(parsed.value);
1354
+ const result = await submitFeedback(parsed.value, attachment);
1203
1355
  if (!result.ok) {
1204
1356
  return res.status(result.status).json({ success: false, error: result.error });
1205
1357
  }