levix-bot 4.4.0 → 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.
- package/README.md +3 -2
- package/package.json +1 -1
- package/public/dashboard/assets/index-COI8zgqa.css +2 -0
- package/public/dashboard/assets/index-IZMBuNAZ.js +505 -0
- package/public/dashboard/index.html +2 -2
- package/scheduler.cjs +66 -7
- package/src/db/db.cjs +6 -0
- package/src/db/store.cjs +17 -3
- package/src/panel/feedback.cjs +43 -14
- package/src/routes/dashboard.api.esm.js +134 -15
- package/src/services/llmDiscovery.cjs +32 -10
- package/src/utils/multipart.esm.js +81 -0
- package/public/dashboard/assets/index-5P8GnKLg.css +0 -2
- package/public/dashboard/assets/index-DXzno3X6.js +0 -515
|
@@ -10,8 +10,8 @@
|
|
|
10
10
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
11
11
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
|
12
12
|
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&family=Tajawal:wght@400;500;700;800&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />
|
|
13
|
-
<script type="module" crossorigin src="/dashboard/assets/index-
|
|
14
|
-
<link rel="stylesheet" crossorigin href="/dashboard/assets/index-
|
|
13
|
+
<script type="module" crossorigin src="/dashboard/assets/index-IZMBuNAZ.js"></script>
|
|
14
|
+
<link rel="stylesheet" crossorigin href="/dashboard/assets/index-COI8zgqa.css">
|
|
15
15
|
</head>
|
|
16
16
|
<body>
|
|
17
17
|
<div id="root"></div>
|
package/scheduler.cjs
CHANGED
|
@@ -17,6 +17,24 @@ const { detectLang, withLang, tr } = require("./src/utils/i18n.cjs");
|
|
|
17
17
|
const RETENTION_MS = 1000 * 60 * 60 * 24 * 3;
|
|
18
18
|
const cacheCleanupCron = "0 */6 * * *"; // every 6 hours
|
|
19
19
|
|
|
20
|
+
// A scheduled message can carry one media file. The bytes live under
|
|
21
|
+
// <data>/media/schedules/<job id> — a subfolder, which the retention sweep
|
|
22
|
+
// skips (it only unlinks files) — and are deleted with the job, not by age.
|
|
23
|
+
const SCHEDULE_MEDIA_MAX_BYTES = 20 * 1024 * 1024;
|
|
24
|
+
|
|
25
|
+
function scheduleMediaPath(jobId) {
|
|
26
|
+
// basename so a hand-crafted job id can never climb out of the folder
|
|
27
|
+
return path.join(ensureDataDir("media"), "schedules", path.basename(String(jobId)));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function removeScheduleMedia(jobId) {
|
|
31
|
+
try {
|
|
32
|
+
fs.rmSync(scheduleMediaPath(jobId), { force: true });
|
|
33
|
+
} catch (err) {
|
|
34
|
+
logger.warn({ err, jobId }, "[Scheduler] failed to remove scheduled media");
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
20
38
|
function getScheduledJobs() {
|
|
21
39
|
try {
|
|
22
40
|
return storage.getSchedules();
|
|
@@ -151,6 +169,42 @@ function recordDelivery(jobId, status, runAt, error = null) {
|
|
|
151
169
|
}
|
|
152
170
|
}
|
|
153
171
|
|
|
172
|
+
/**
|
|
173
|
+
* What sendMessage receives for one job, in order: the text, or the stored
|
|
174
|
+
* media with the text as its caption. Audio and stickers take no caption, so
|
|
175
|
+
* their text follows as a message of its own instead of being dropped. Runs
|
|
176
|
+
* inside withLang() so tr() picks the right header.
|
|
177
|
+
*/
|
|
178
|
+
function buildScheduledPayloads(job) {
|
|
179
|
+
const header = tr("*Scheduled message 🗓️*", "*رسالة مجدولة 🗓️*");
|
|
180
|
+
const text = job.message ? `${header}\n\n${job.message}` : header;
|
|
181
|
+
if (!job.media) return [{ text }];
|
|
182
|
+
|
|
183
|
+
const buffer = fs.readFileSync(scheduleMediaPath(job.id));
|
|
184
|
+
const mimetype = job.media.mimeType || "application/octet-stream";
|
|
185
|
+
const caption = job.message ? text : undefined;
|
|
186
|
+
const followUp = job.message ? [{ text }] : [];
|
|
187
|
+
switch (job.media.kind) {
|
|
188
|
+
case "image":
|
|
189
|
+
return [{ image: buffer, mimetype, caption }];
|
|
190
|
+
case "video":
|
|
191
|
+
return [{ video: buffer, mimetype, caption }];
|
|
192
|
+
case "audio":
|
|
193
|
+
return [{ audio: buffer, mimetype, ptt: false }, ...followUp];
|
|
194
|
+
case "sticker":
|
|
195
|
+
return [{ sticker: buffer }, ...followUp];
|
|
196
|
+
default:
|
|
197
|
+
return [
|
|
198
|
+
{
|
|
199
|
+
document: buffer,
|
|
200
|
+
mimetype,
|
|
201
|
+
fileName: job.media.fileName || undefined,
|
|
202
|
+
caption,
|
|
203
|
+
},
|
|
204
|
+
];
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
154
208
|
async function deliverScheduledJob(sock, job) {
|
|
155
209
|
if (deliveriesInFlight.has(job.id)) {
|
|
156
210
|
logger.warn(`[Scheduler] Job ${job.id} is already being delivered — skipping overlap`);
|
|
@@ -161,13 +215,12 @@ async function deliverScheduledJob(sock, job) {
|
|
|
161
215
|
const runAt = Date.now();
|
|
162
216
|
|
|
163
217
|
try {
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
});
|
|
218
|
+
// No message is being answered here, so the header follows the scheduled
|
|
219
|
+
// text itself (in "auto"), or the bot's language.
|
|
220
|
+
const payloads = withLang(detectLang(job.message || " "), () => buildScheduledPayloads(job));
|
|
221
|
+
for (const payload of payloads) {
|
|
222
|
+
await sock.sendMessage(job.targetJid, payload);
|
|
223
|
+
}
|
|
171
224
|
recordDelivery(job.id, "sent", runAt);
|
|
172
225
|
logger.info(`[Scheduler] Executed job ${job.id} -> ${job.targetJid}`);
|
|
173
226
|
return { ok: true, reason: "sent" };
|
|
@@ -193,6 +246,9 @@ async function executeScheduledJob(sock, job) {
|
|
|
193
246
|
"[Scheduler] failed to record one-off schedule status",
|
|
194
247
|
);
|
|
195
248
|
}
|
|
249
|
+
// A sent one-off never fires again, so its media copy is dead weight —
|
|
250
|
+
// but a failed one stays retryable and keeps its file.
|
|
251
|
+
if (result.ok) removeScheduleMedia(job.id);
|
|
196
252
|
}
|
|
197
253
|
|
|
198
254
|
return result;
|
|
@@ -264,6 +320,7 @@ async function retryScheduledJob(sock, jobId) {
|
|
|
264
320
|
function deleteScheduledJob(jobId) {
|
|
265
321
|
stopTask(jobId);
|
|
266
322
|
storage.deleteSchedule(jobId);
|
|
323
|
+
removeScheduleMedia(jobId);
|
|
267
324
|
logger.info(`[Scheduler] Deleted job ${jobId}.`);
|
|
268
325
|
return true;
|
|
269
326
|
}
|
|
@@ -286,6 +343,7 @@ function scheduleJobNow(job) {
|
|
|
286
343
|
}
|
|
287
344
|
|
|
288
345
|
module.exports = {
|
|
346
|
+
SCHEDULE_MEDIA_MAX_BYTES,
|
|
289
347
|
initializeScheduledJobs,
|
|
290
348
|
stopAllScheduledJobs,
|
|
291
349
|
scheduleNewJob,
|
|
@@ -294,5 +352,6 @@ module.exports = {
|
|
|
294
352
|
getScheduledJobs,
|
|
295
353
|
saveScheduledJob,
|
|
296
354
|
deleteScheduledJob,
|
|
355
|
+
scheduleMediaPath,
|
|
297
356
|
updateJobStatus,
|
|
298
357
|
};
|
package/src/db/db.cjs
CHANGED
|
@@ -574,6 +574,12 @@ 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
|
+
},
|
|
577
583
|
];
|
|
578
584
|
|
|
579
585
|
function migrate(database, migrations = MIGRATIONS) {
|
package/src/db/store.cjs
CHANGED
|
@@ -861,6 +861,17 @@ function countDebts(settled = false) {
|
|
|
861
861
|
// A job is `{ id, type, targetJid, message, cronString?, date?, status,
|
|
862
862
|
// creatorJid, lastRunAt?, lastDeliveryStatus?, lastError? }`.
|
|
863
863
|
|
|
864
|
+
/** The `media` column holds a small JSON object, or NULL for a text job. */
|
|
865
|
+
function parseMediaColumn(value) {
|
|
866
|
+
if (!value) return undefined;
|
|
867
|
+
try {
|
|
868
|
+
const parsed = JSON.parse(value);
|
|
869
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
|
|
870
|
+
} catch {
|
|
871
|
+
return undefined;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
|
|
864
875
|
function scheduleRow(row) {
|
|
865
876
|
if (!row) return null;
|
|
866
877
|
return {
|
|
@@ -876,6 +887,7 @@ function scheduleRow(row) {
|
|
|
876
887
|
lastRunAt: row.last_run_at ?? null,
|
|
877
888
|
lastDeliveryStatus: row.last_delivery_status ?? null,
|
|
878
889
|
lastError: row.last_error ?? null,
|
|
890
|
+
media: parseMediaColumn(row.media),
|
|
879
891
|
};
|
|
880
892
|
}
|
|
881
893
|
|
|
@@ -891,8 +903,8 @@ function saveSchedule(job) {
|
|
|
891
903
|
q(
|
|
892
904
|
`INSERT INTO schedules
|
|
893
905
|
(id, type, target_jid, message, cron_string, date, status, creator_jid,
|
|
894
|
-
created_at, last_run_at, last_delivery_status, last_error)
|
|
895
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
906
|
+
created_at, last_run_at, last_delivery_status, last_error, media)
|
|
907
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
896
908
|
ON CONFLICT(id) DO UPDATE SET
|
|
897
909
|
type = excluded.type,
|
|
898
910
|
target_jid = excluded.target_jid,
|
|
@@ -903,7 +915,8 @@ function saveSchedule(job) {
|
|
|
903
915
|
creator_jid = excluded.creator_jid,
|
|
904
916
|
last_run_at = excluded.last_run_at,
|
|
905
917
|
last_delivery_status = excluded.last_delivery_status,
|
|
906
|
-
last_error = excluded.last_error
|
|
918
|
+
last_error = excluded.last_error,
|
|
919
|
+
media = excluded.media`,
|
|
907
920
|
).run(
|
|
908
921
|
String(job.id),
|
|
909
922
|
job.type,
|
|
@@ -917,6 +930,7 @@ function saveSchedule(job) {
|
|
|
917
930
|
job.lastRunAt ?? null,
|
|
918
931
|
job.lastDeliveryStatus ?? null,
|
|
919
932
|
job.lastError ?? null,
|
|
933
|
+
job.media ? JSON.stringify(job.media) : null,
|
|
920
934
|
);
|
|
921
935
|
return getSchedule(job.id);
|
|
922
936
|
}
|
package/src/panel/feedback.cjs
CHANGED
|
@@ -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
|
|
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
|
-
|
|
171
|
-
|
|
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,
|
|
@@ -38,8 +38,11 @@ import {
|
|
|
38
38
|
getRecentDebts,
|
|
39
39
|
getSchedules,
|
|
40
40
|
rememberSavedName,
|
|
41
|
+
resolveUserPhone,
|
|
41
42
|
saveGroupSettings,
|
|
42
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";
|
|
43
46
|
|
|
44
47
|
const require = createRequire(import.meta.url);
|
|
45
48
|
const logger = require("../utils/logger.cjs");
|
|
@@ -50,6 +53,7 @@ const secrets = require("../config/secrets.cjs");
|
|
|
50
53
|
const { clientAddress } = require("../utils/requestOrigin.cjs");
|
|
51
54
|
const { blockedFor, recordFailure, clearAttempts } = require("../panel/login-throttle.cjs");
|
|
52
55
|
const {
|
|
56
|
+
ATTACHMENT_MAX: FEEDBACK_ATTACHMENT_MAX,
|
|
53
57
|
TOPICS: FEEDBACK_TOPICS,
|
|
54
58
|
MESSAGE_MAX: FEEDBACK_MESSAGE_MAX,
|
|
55
59
|
MESSAGE_MIN: FEEDBACK_MESSAGE_MIN,
|
|
@@ -62,8 +66,10 @@ const { stampPanelSession } = require("../panel/session-auth.cjs");
|
|
|
62
66
|
const { DATA_DIR } = require("../config/paths.cjs");
|
|
63
67
|
const { PERSONA_FILE, activeProviderKeySetting } = require("../services/aiAgent.cjs");
|
|
64
68
|
const {
|
|
69
|
+
SCHEDULE_MEDIA_MAX_BYTES,
|
|
65
70
|
deleteScheduledJob,
|
|
66
71
|
retryScheduledJob,
|
|
72
|
+
scheduleMediaPath,
|
|
67
73
|
scheduleNewJob,
|
|
68
74
|
saveScheduledJob,
|
|
69
75
|
} = require("../../scheduler.cjs");
|
|
@@ -412,6 +418,7 @@ router.post(
|
|
|
412
418
|
apiKey,
|
|
413
419
|
baseUrl,
|
|
414
420
|
refresh = false,
|
|
421
|
+
cacheOnly = false,
|
|
415
422
|
} = req.body || {};
|
|
416
423
|
|
|
417
424
|
const provKey = String(provider || "gemini").toLowerCase();
|
|
@@ -438,6 +445,7 @@ router.post(
|
|
|
438
445
|
apiKey: effectiveKey,
|
|
439
446
|
baseUrl: effectiveBaseUrl,
|
|
440
447
|
refresh: Boolean(refresh),
|
|
448
|
+
cacheOnly: Boolean(cacheOnly),
|
|
441
449
|
});
|
|
442
450
|
|
|
443
451
|
return res.json(result);
|
|
@@ -1008,16 +1016,22 @@ router.get("/recipients", (req, res) => {
|
|
|
1008
1016
|
const users = getAllUsers() || [];
|
|
1009
1017
|
users.sort((a, b) => (b.lastSeen || 0) - (a.lastSeen || 0));
|
|
1010
1018
|
for (const u of users.slice(0, 80)) {
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
const
|
|
1014
|
-
const personKey = peer.phone || u.lid || 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;
|
|
1015
1022
|
if (seen.has(personKey)) continue;
|
|
1016
|
-
|
|
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);
|
|
1017
1031
|
seen.add(personKey);
|
|
1018
1032
|
if (u.lid) seen.add(u.lid);
|
|
1019
1033
|
recipients.push({
|
|
1020
|
-
id
|
|
1034
|
+
id,
|
|
1021
1035
|
name: peer.label,
|
|
1022
1036
|
phone: peer.phone,
|
|
1023
1037
|
savedName: peer.savedName ?? null,
|
|
@@ -1032,6 +1046,32 @@ router.get("/recipients", (req, res) => {
|
|
|
1032
1046
|
}
|
|
1033
1047
|
});
|
|
1034
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
|
+
|
|
1035
1075
|
router.post(
|
|
1036
1076
|
"/schedules",
|
|
1037
1077
|
asyncRoute(async (req, res) => {
|
|
@@ -1040,18 +1080,57 @@ router.post(
|
|
|
1040
1080
|
return badRequest(res, "Maximum 3 scheduled messages reached");
|
|
1041
1081
|
}
|
|
1042
1082
|
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
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");
|
|
1047
1115
|
}
|
|
1048
1116
|
|
|
1049
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
|
+
|
|
1050
1129
|
const job = {
|
|
1051
1130
|
id,
|
|
1052
1131
|
type: type === "once" ? "once" : "recurring",
|
|
1053
|
-
targetJid:
|
|
1054
|
-
message: String(message).trim(),
|
|
1132
|
+
targetJid: target,
|
|
1133
|
+
message: String(message ?? "").trim(),
|
|
1055
1134
|
creatorJid: "dashboard@levix",
|
|
1056
1135
|
status: "active",
|
|
1057
1136
|
};
|
|
@@ -1079,7 +1158,20 @@ router.post(
|
|
|
1079
1158
|
job.date = new Date(timeMs).toISOString();
|
|
1080
1159
|
}
|
|
1081
1160
|
|
|
1082
|
-
|
|
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")) {
|
|
1083
1175
|
rememberSavedName(job.targetJid, targetName);
|
|
1084
1176
|
}
|
|
1085
1177
|
|
|
@@ -1210,6 +1302,7 @@ router.get("/feedback/meta", (req, res) => {
|
|
|
1210
1302
|
topics: FEEDBACK_TOPICS,
|
|
1211
1303
|
messageMin: FEEDBACK_MESSAGE_MIN,
|
|
1212
1304
|
messageMax: FEEDBACK_MESSAGE_MAX,
|
|
1305
|
+
attachmentMax: FEEDBACK_ATTACHMENT_MAX,
|
|
1213
1306
|
// Shown next to the form so the operator can see what travels with it.
|
|
1214
1307
|
runtime: { version: runtime.version, platform: runtime.platform },
|
|
1215
1308
|
});
|
|
@@ -1217,10 +1310,36 @@ router.get("/feedback/meta", (req, res) => {
|
|
|
1217
1310
|
|
|
1218
1311
|
// Leaves this machine only when the operator presses Send, and carries nothing
|
|
1219
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.
|
|
1220
1315
|
router.post(
|
|
1221
1316
|
"/feedback",
|
|
1222
1317
|
asyncRoute(async (req, res) => {
|
|
1223
|
-
|
|
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);
|
|
1224
1343
|
if (!parsed.ok) return badRequest(res, parsed.error);
|
|
1225
1344
|
|
|
1226
1345
|
const retryAfter = feedbackRetryAfter();
|
|
@@ -1232,7 +1351,7 @@ router.post(
|
|
|
1232
1351
|
});
|
|
1233
1352
|
}
|
|
1234
1353
|
|
|
1235
|
-
const result = await submitFeedback(parsed.value);
|
|
1354
|
+
const result = await submitFeedback(parsed.value, attachment);
|
|
1236
1355
|
if (!result.ok) {
|
|
1237
1356
|
return res.status(result.status).json({ success: false, error: result.error });
|
|
1238
1357
|
}
|
|
@@ -49,11 +49,15 @@ async function requestJson(url, { headers, timeoutMs = REQUEST_TIMEOUT_MS } = {}
|
|
|
49
49
|
const controller = new AbortController();
|
|
50
50
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
51
51
|
try {
|
|
52
|
-
const resp = await safeProviderFetch(
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
52
|
+
const resp = await safeProviderFetch(
|
|
53
|
+
url,
|
|
54
|
+
{
|
|
55
|
+
method: "GET",
|
|
56
|
+
headers: { Accept: "application/json", ...headers },
|
|
57
|
+
signal: controller.signal,
|
|
58
|
+
},
|
|
59
|
+
{ allowLoopback: true },
|
|
60
|
+
);
|
|
57
61
|
return resp;
|
|
58
62
|
} catch (err) {
|
|
59
63
|
if (err && err.name === "AbortError") {
|
|
@@ -306,10 +310,9 @@ class GeminiDiscoveryAdapter extends BaseDiscoveryAdapter {
|
|
|
306
310
|
|
|
307
311
|
async discover({ apiKey, baseUrl = "https://generativelanguage.googleapis.com" }) {
|
|
308
312
|
const key = this.validateCredentials(apiKey);
|
|
309
|
-
const rootUrl = assertProviderBaseUrl(
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
);
|
|
313
|
+
const rootUrl = assertProviderBaseUrl(baseUrl || "https://generativelanguage.googleapis.com", {
|
|
314
|
+
allowLoopback: true,
|
|
315
|
+
});
|
|
313
316
|
|
|
314
317
|
const rawList = [];
|
|
315
318
|
let pageToken = "";
|
|
@@ -386,7 +389,13 @@ async function discoverProviderModels(optionsOrProvider = "gemini", maybeOptions
|
|
|
386
389
|
options = optionsOrProvider;
|
|
387
390
|
}
|
|
388
391
|
|
|
389
|
-
const {
|
|
392
|
+
const {
|
|
393
|
+
provider = "gemini",
|
|
394
|
+
apiKey = "",
|
|
395
|
+
baseUrl = "",
|
|
396
|
+
refresh = false,
|
|
397
|
+
cacheOnly = false,
|
|
398
|
+
} = options;
|
|
390
399
|
const provKey = String(provider || "gemini").toLowerCase();
|
|
391
400
|
const adapter = ADAPTERS[provKey];
|
|
392
401
|
|
|
@@ -430,6 +439,19 @@ async function discoverProviderModels(optionsOrProvider = "gemini", maybeOptions
|
|
|
430
439
|
}
|
|
431
440
|
}
|
|
432
441
|
|
|
442
|
+
// Opening the panel must not spend a request on the operator's key: with
|
|
443
|
+
// nothing cached it gets the recommended list, and Refresh goes live.
|
|
444
|
+
if (cacheOnly && !refresh) {
|
|
445
|
+
return {
|
|
446
|
+
success: true,
|
|
447
|
+
live: false,
|
|
448
|
+
requiresApiKey: false,
|
|
449
|
+
fallback: true,
|
|
450
|
+
provider: provKey,
|
|
451
|
+
models: getSeedModels(provKey),
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
|
|
433
455
|
try {
|
|
434
456
|
const liveModels = await adapter.discover({
|
|
435
457
|
apiKey: cleanKey,
|