Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
604 lines (524 loc) · 22.6 KB
/
Copy pathserver.js
File metadata and controls
604 lines (524 loc) · 22.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
process.on('unhandledRejection', (reason) => console.error('Unhandled rejection:', reason));
// Resuming after an uncaught exception risks running with corrupted state (Node's own
// guidance) — exit so start.sh's normal restart path (or manual re-run) can recover,
// instead of silently limping along like the missing handler used to allow.
process.on('uncaughtException', (err) => {
console.error('Uncaught exception:', err);
process.exit(1);
});
require('dotenv').config();
if (!process.env.ANTHROPIC_API_KEY) {
console.warn('⚠ ANTHROPIC_API_KEY not set — the Translate feature will return errors until you add it to .env');
}
const express = require('express');
const { Client, LocalAuth, MessageMedia } = require('whatsapp-web.js');
const qrcode = require('qrcode');
const path = require('path');
const fs = require('fs');
const { exec } = require('child_process');
const crypto = require('crypto');
const multer = require('multer');
const { translateBatch } = require('./lib/translator');
const { createCache } = require('./lib/translationCache');
const UPLOADS_DIR = path.join(__dirname, 'uploads');
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
const DOWNLOADS_DIR = path.join(__dirname, 'downloads');
fs.mkdirSync(DOWNLOADS_DIR, { recursive: true });
const storage = multer.diskStorage({
destination: UPLOADS_DIR,
filename: (_req, file, cb) => cb(null, `${crypto.randomUUID()}-${file.originalname}`),
});
const upload = multer({ storage, limits: { fileSize: 64 * 1024 * 1024 } });
const app = express();
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
// ── State ──────────────────────────────────────────────────────────────────
let waStatus = 'initializing'; // 'initializing' | 'qr' | 'loading' | 'connected' | 'disconnected'
let qrDataUrl = null;
let contacts = [];
let scheduledMessages = []; // { id, contactId, contactName, message, sendAt, status, timer }
let shutdownTimer = null;
let shutdownAt = null;
let anySentThisSession = false; // guards auto-shutdown from firing on a bare restart
const QUEUE_FILE = path.join(__dirname, 'queue.json');
const CONTACTS_FILE = path.join(__dirname, 'contacts.json');
const TRANSLATE_GROUPS_FILE = path.join(__dirname, 'translate-groups.json');
const translationCache = createCache(path.join(__dirname, 'translations'));
function loadTranslateGroups() {
try {
if (fs.existsSync(TRANSLATE_GROUPS_FILE)) {
return JSON.parse(fs.readFileSync(TRANSLATE_GROUPS_FILE, 'utf8'));
}
} catch (e) {
console.error('Failed to load translate groups:', e.message);
}
return [];
}
function saveTranslateGroups(groups) {
try {
fs.writeFileSync(TRANSLATE_GROUPS_FILE, JSON.stringify(groups, null, 2));
} catch (e) {
console.error('Failed to save translate groups:', e.message);
}
}
// WhatsApp now addresses group senders by LID, which doesn't match the contact
// cache (@c.us). Map LID → phone number once per author and remember it.
const lidPnCache = new Map(); // '<id>@lid' -> '<number>@c.us' | null
async function resolveLidAuthors(msgs) {
const authorIds = [...new Set(msgs.filter((m) => !m.fromMe).map((m) => m.author || m.from))];
const unknown = authorIds.filter((id) => id && id.endsWith('@lid') && !lidPnCache.has(id));
if (!unknown.length) return;
try {
const mapped = await client.getContactLidAndPhone(unknown);
for (const r of mapped) if (r.lid) lidPnCache.set(r.lid, r.pn || null);
} catch (e) {
console.error('LID→phone resolution failed:', e.message);
}
}
// Resolve a group message's author to a display name via the contact cache.
function resolveSenderName(msg) {
if (msg.fromMe) return 'You';
const authorId = msg.author || msg.from;
const candidateIds = [authorId, lidPnCache.get(authorId)].filter(Boolean);
for (const id of candidateIds) {
const contact = contacts.find((c) => (c.id?._serialized ?? c.id) === id);
if (contact && (contact.name || contact.pushname)) return contact.name || contact.pushname;
}
if (msg._data && msg._data.notifyName) return msg._data.notifyName; // sender's push name
const pn = lidPnCache.get(authorId);
return String(pn || authorId).split('@')[0];
}
// ── Contact cache ──────────────────────────────────────────────────────────
function saveContactsCache() {
try {
const serialisable = contacts.map((c) => ({
id: c.id?._serialized ?? c.id,
name: c.name || c.pushname || '',
number: c.number || '',
isGroup: !!c.isGroup,
}));
fs.writeFileSync(CONTACTS_FILE, JSON.stringify(serialisable, null, 2));
} catch (e) {
console.error('Failed to save contacts cache:', e.message);
}
}
function loadContactsCache() {
try {
if (!fs.existsSync(CONTACTS_FILE)) return;
const cached = JSON.parse(fs.readFileSync(CONTACTS_FILE, 'utf8'));
if (!cached.length) return;
// Use cached entries as stand-ins until real objects arrive from WhatsApp.
contacts = cached.map((c) => ({
id: { _serialized: c.id },
name: c.name,
number: c.number,
isGroup: c.isGroup,
_fromCache: true,
}));
console.log(`Loaded ${cached.length} contacts from local cache`);
} catch (e) {
console.error('Failed to load contacts cache:', e.message);
}
}
// ── Queue persistence ──────────────────────────────────────────────────────
// Only pending messages are persisted — sent/failed/missed are ephemeral.
function saveQueue() {
try {
const pending = scheduledMessages
.filter((m) => m.status === 'pending')
.map(({ timer, ...m }) => m);
fs.writeFileSync(QUEUE_FILE, JSON.stringify(pending, null, 2));
} catch (e) {
console.error('Failed to save queue:', e.message);
}
}
// Called once at startup so the UI can show queued messages before WA connects.
function loadQueue() {
try {
if (!fs.existsSync(QUEUE_FILE)) return;
const raw = JSON.parse(fs.readFileSync(QUEUE_FILE, 'utf8'));
// All items in the file are pending; timers are armed later in rescheduleFromQueue.
scheduledMessages = raw.map((m) => ({ ...m, status: 'pending', timer: null }));
console.log(`Loaded ${scheduledMessages.length} pending message(s) from queue`);
} catch (e) {
console.error('Failed to load queue:', e.message);
}
}
// Arms the send timer for a single pending message.
function armTimer(msg) {
const delay = msg.sendAt - Date.now();
msg.timer = setTimeout(async () => {
if (msg.status !== 'pending') return;
try {
if (msg.filePath) {
const media = MessageMedia.fromFilePath(msg.filePath);
await client.sendMessage(msg.contactId, media, msg.message ? { caption: msg.message } : {});
} else {
await client.sendMessage(msg.contactId, msg.message);
}
msg.status = 'sent';
msg.sentAt = Date.now();
anySentThisSession = true;
console.log(`✓ Sent to ${msg.contactName}`);
} catch (err) {
msg.status = 'failed';
msg.error = err.message;
anySentThisSession = true; // failed attempts still count for shutdown logic
console.error(`✗ Failed to send to ${msg.contactName}:`, err.message);
}
if (msg.filePath) {
fs.unlink(msg.filePath, () => {});
msg.filePath = null;
}
saveQueue();
checkAutoShutdown();
}, delay);
}
// Called when WA becomes ready — re-arms surviving messages or marks them missed.
function rescheduleFromQueue() {
const now = Date.now();
let missed = 0;
scheduledMessages.forEach((msg) => {
if (msg.status !== 'pending') return;
if (msg.sendAt <= now) {
msg.status = 'missed';
if (msg.filePath) {
fs.unlink(msg.filePath, () => {});
msg.filePath = null;
}
anySentThisSession = true; // missed messages are resolved (if unhappily) — count for shutdown logic
missed++;
} else {
armTimer(msg);
}
});
if (missed) {
console.log(`⚠ ${missed} message(s) missed their window while the server was down`);
saveQueue(); // removes missed ones from disk
}
}
// ── WhatsApp Client ────────────────────────────────────────────────────────
const client = new Client({
authStrategy: new LocalAuth({ dataPath: '.wwebjs_auth' }),
puppeteer: {
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
},
});
client.on('qr', async (qr) => {
waStatus = 'qr';
qrDataUrl = await qrcode.toDataURL(qr);
// A fresh QR means a real (re)connection attempt is underway — cancel any shutdown
// armed by an earlier 'disconnected' (e.g. LOGOUT, which whatsapp-web.js can recover
// from in-process via a fresh QR scan, without restarting this server).
cancelAutoShutdown();
console.log('QR code ready — open http://localhost:3000 to scan');
});
client.on('loading_screen', (percent, message) => {
// whatsapp-web.js keeps emitting this in the background after the initial 'ready'
// fires (which only happens once per session) — pure noise unrelated to any real
// state change, so don't let it regress an already-settled status. A genuine
// reconnect moves waStatus off 'connected'/'disconnected' via 'authenticated' first,
// so this still tracks real loading progress when one is actually happening.
if (waStatus !== 'connected' && waStatus !== 'disconnected') waStatus = 'loading';
console.log(`Loading: ${percent}% — ${message}`);
});
client.on('authenticated', () => {
waStatus = 'loading';
// Unlike loading_screen, 'authenticated' only fires on a real (re)authentication —
// cancel any shutdown armed by an earlier 'disconnected' so a recovered session
// (e.g. re-scanning after a LOGOUT) doesn't get killed out from under the user.
cancelAutoShutdown();
console.log('Authenticated');
});
client.on('auth_failure', (msg) => {
waStatus = 'disconnected';
console.error('Auth failure:', msg);
});
let contactRefreshTimer = null;
async function refreshContacts(label = 'Refreshed') {
try {
const [allContacts, allChats] = await Promise.all([
client.getContacts(),
client.getChats(),
]);
const individuals = allContacts
.filter((c) => c.isMyContact && !c.isGroup && c.id && c.id.server === 'c.us')
.filter((c) => c.name || c.pushname || c.number);
const groups = allChats
.filter((c) => c.isGroup && c.name);
contacts = [...individuals, ...groups].sort((a, b) => {
const nameA = (a.name || a.pushname || '').toLowerCase();
const nameB = (b.name || b.pushname || '').toLowerCase();
return nameA.localeCompare(nameB);
});
console.log(`${label} ${individuals.length} contacts and ${groups.length} groups`);
saveContactsCache();
} catch (err) {
console.error('Error loading contacts/groups:', err);
}
}
client.on('ready', async () => {
waStatus = 'connected';
qrDataUrl = null;
console.log('WhatsApp client ready');
await refreshContacts('Loaded');
rescheduleFromQueue();
checkAutoShutdown(); // nothing pending right after connecting? start the idle countdown
// Periodically re-sync contacts (catches new contacts added after initial link)
if (contactRefreshTimer) clearInterval(contactRefreshTimer);
contactRefreshTimer = setInterval(() => refreshContacts('Refreshed'), 2 * 60 * 1000);
});
client.on('disconnected', (reason) => {
waStatus = 'disconnected';
console.log('Disconnected:', reason);
// Most disconnect reasons are unrecoverable without restarting this process, so stop
// the contact-refresh loop (it would otherwise spin forever calling into a detached
// Puppeteer frame) and shut down shortly, regardless of any messages still pending —
// they can't be delivered on a dead session anyway. LOGOUT is the exception:
// whatsapp-web.js can recover in-process via a fresh QR scan, in which case the 'qr'
// and 'authenticated' handlers above cancel this shutdown before it fires.
if (contactRefreshTimer) clearInterval(contactRefreshTimer);
if (shutdownTimer) clearTimeout(shutdownTimer);
console.log('Session lost — shutting down in 1 minute');
shutdownAt = Date.now() + 60 * 1000;
shutdownTimer = setTimeout(performShutdown, 60 * 1000);
});
// ── Shutdown helpers ───────────────────────────────────────────────────────
function checkAutoShutdown() {
const hasPending = scheduledMessages.some((m) => m.status === 'pending');
if (hasPending || shutdownTimer) return;
// Just delivered the last scheduled message this session — short grace period
// (covers polling clients briefly checking status). Otherwise nothing was ever
// pending/sent (idle since startup, or the queue was already empty) — give it a
// longer window in case something gets scheduled shortly after connecting.
const delay = anySentThisSession ? 2 * 60 * 1000 : 30 * 60 * 1000;
const label = anySentThisSession ? 'All messages resolved' : 'No scheduled messages';
console.log(`${label} — auto-shutdown in ${delay / 60000} minutes`);
shutdownAt = Date.now() + delay;
shutdownTimer = setTimeout(performShutdown, delay);
}
function cancelAutoShutdown() {
if (shutdownTimer) {
clearTimeout(shutdownTimer);
shutdownTimer = null;
shutdownAt = null;
console.log('Auto-shutdown cancelled');
}
}
async function performShutdown() {
console.log('Shutting down…');
if (contactRefreshTimer) clearInterval(contactRefreshTimer);
try {
await Promise.race([
client.destroy(),
new Promise(resolve => setTimeout(resolve, 4000)),
]);
} catch (_) { /* ignore */ }
process.exit(0);
}
// Clean exit on SIGUSR1 (sent by ./start.sh restart) or SIGINT (Ctrl+C on direct node run).
// SIGTERM is intentionally NOT caught — macOS Terminal sends it when closing a tab,
// and nohup only blocks SIGHUP. The queue is persisted so no messages are lost on a
// hard kill; the OS will clean up the Puppeteer/Chrome child process automatically.
process.on('SIGUSR1', performShutdown);
process.on('SIGINT', performShutdown);
// ── API Routes ─────────────────────────────────────────────────────────────
app.get('/api/status', (_req, res) => {
res.json({ wa: waStatus, qr: qrDataUrl, contactsLoaded: contacts.length > 0, shutdownAt });
});
app.get('/api/contacts', (req, res) => {
const q = (req.query.q || '').toLowerCase().trim();
const pool = q
? contacts.filter(
(c) =>
(c.name && c.name.toLowerCase().includes(q)) ||
(c.pushname && c.pushname.toLowerCase().includes(q)) ||
(c.number && c.number.includes(q))
)
: contacts;
res.json(
pool.slice(0, 50).map((c) => ({
id: c.id._serialized,
name: c.name || c.pushname || c.number,
number: c.number || null,
isGroup: !!c.isGroup,
}))
);
});
app.post('/api/download-images', async (req, res) => {
const { contactId, contactName } = req.body;
if (!contactId) return res.status(400).json({ error: 'Missing contactId' });
if (waStatus !== 'connected') return res.status(400).json({ error: 'WhatsApp not connected' });
try {
const chat = await client.getChatById(contactId);
const messages = await chat.fetchMessages({ limit: 100000 });
const imageMessages = messages.filter((m) => m.hasMedia && m.type === 'image');
const documentMessages = messages.filter((m) => m.hasMedia && m.type === 'document');
const safeName = (contactName || 'chat').toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
const folder = path.join(DOWNLOADS_DIR, `${safeName || 'chat'}-${Date.now()}`);
const documentsFolder = path.join(folder, 'documents');
fs.mkdirSync(folder, { recursive: true });
fs.mkdirSync(documentsFolder, { recursive: true });
let savedImages = 0;
for (const msg of imageMessages) {
try {
const media = await msg.downloadMedia();
if (!media) continue;
const ext = (media.mimetype.split('/')[1] || 'jpg').split(';')[0];
fs.writeFileSync(path.join(folder, `${msg.timestamp}-${msg.id.id}.${ext}`), Buffer.from(media.data, 'base64'));
savedImages++;
} catch (e) {
console.error('Failed to download an image:', e.message);
}
}
let savedDocuments = 0;
for (const msg of documentMessages) {
try {
const media = await msg.downloadMedia();
if (!media) continue;
const ext = (media.filename && path.extname(media.filename)) || `.${(media.mimetype.split('/')[1] || 'bin').split(';')[0]}`;
const baseName = media.filename ? path.basename(media.filename, path.extname(media.filename)) : msg.id.id;
fs.writeFileSync(path.join(documentsFolder, `${msg.timestamp}-${baseName}${ext}`), Buffer.from(media.data, 'base64'));
savedDocuments++;
} catch (e) {
console.error('Failed to download a document:', e.message);
}
}
console.log(`Downloaded ${savedImages} image(s) and ${savedDocuments} document(s) from ${contactName || contactId} to ${folder}`);
res.json({ success: true, count: savedImages, documentCount: savedDocuments, folder, documentsFolder });
} catch (err) {
console.error('Error downloading images:', err);
res.status(500).json({ error: err.message || 'Failed to download images' });
}
});
app.get('/api/translate/groups', (_req, res) => {
res.json(loadTranslateGroups());
});
app.post('/api/translate/groups', (req, res) => {
const { groups } = req.body;
if (!Array.isArray(groups) || groups.some((g) => !g.id || !g.name)) {
return res.status(400).json({ error: 'groups must be an array of {id, name}' });
}
saveTranslateGroups(groups.map(({ id, name }) => ({ id, name })));
res.json({ success: true });
});
app.get('/api/translate/messages', async (req, res) => {
const { groupId } = req.query;
const limit = Math.min(Number(req.query.limit) || 50, 1000);
if (!groupId) return res.status(400).json({ error: 'Missing groupId' });
if (waStatus !== 'connected') return res.status(400).json({ error: 'WhatsApp not connected' });
cancelAutoShutdown(); // user is actively reading — don't exit under them
try {
const chat = await client.getChatById(groupId);
const fetched = await chat.fetchMessages({ limit });
await resolveLidAuthors(fetched);
const items = fetched.map((msg) => ({
id: msg.id.id,
senderName: resolveSenderName(msg),
timestamp: msg.timestamp * 1000,
type: msg.type, // 'chat' for text; 'image', 'ptt', 'document', 'sticker', ... for media
fromMe: !!msg.fromMe,
body: msg.body || '', // for media messages this is the caption
}));
const toTranslate = items.filter(
(m) => m.body.trim() && !translationCache.get(groupId, m.id)
);
let translationError = null;
if (toTranslate.length > 0) {
try {
const results = await translateBatch(
toTranslate.map(({ id, body }) => ({ id, text: body }))
);
const entries = {};
for (const [id, r] of Object.entries(results)) {
if (r) entries[id] = r; // skipped ids stay uncached and retry next fetch
}
translationCache.setMany(groupId, entries);
} catch (err) {
console.error('Translation failed:', err.message);
translationError = err.message;
}
}
const messages = items
.map((m) => {
const cached = m.body.trim() ? translationCache.get(groupId, m.id) : null;
return {
...m,
lang: cached ? cached.lang : null,
translation: cached ? cached.translation : null,
translated: !!cached,
};
})
.sort((a, b) => a.timestamp - b.timestamp);
res.json({ messages, translationError });
} catch (err) {
console.error('Error fetching translate feed:', err);
res.status(500).json({ error: err.message || 'Failed to fetch messages' });
}
});
app.get('/api/scheduled', (_req, res) => {
res.json(scheduledMessages.map(({ timer, ...m }) => m));
});
app.post('/api/schedule', upload.single('file'), (req, res) => {
const { contactId, contactName, message, sendAt } = req.body;
const hasMessage = message && message.trim();
if (!contactId || !sendAt) {
return res.status(400).json({ error: 'Missing required fields' });
}
if (!hasMessage && !req.file) {
return res.status(400).json({ error: 'Provide a message or attach a file' });
}
const sendTime = Number(sendAt);
if (sendTime - Date.now() <= 0) {
return res.status(400).json({ error: 'sendAt must be in the future' });
}
if (waStatus !== 'connected') {
return res.status(400).json({ error: 'WhatsApp not connected' });
}
cancelAutoShutdown();
const id = crypto.randomUUID();
const msg = {
id,
contactId,
contactName,
message: hasMessage ? message.trim() : '',
sendAt: sendTime,
status: 'pending',
timer: null,
filePath: req.file ? req.file.path : null,
fileName: req.file ? req.file.originalname : null,
};
scheduledMessages.push(msg);
armTimer(msg);
saveQueue();
res.json({ id, contactId, contactName, message: msg.message, sendAt: sendTime, status: 'pending', fileName: msg.fileName });
});
app.delete('/api/schedule/:id', (req, res) => {
const { id } = req.params;
const idx = scheduledMessages.findIndex((m) => m.id === id);
if (idx === -1) return res.status(404).json({ error: 'Message not found' });
const msg = scheduledMessages[idx];
if (msg.status === 'pending' && msg.timer) clearTimeout(msg.timer);
if (msg.filePath) fs.unlink(msg.filePath, () => {});
scheduledMessages.splice(idx, 1);
saveQueue();
res.json({ success: true });
});
app.post('/api/shutdown', (_req, res) => {
res.json({ success: true });
setTimeout(performShutdown, 500);
});
app.post('/api/cancel-shutdown', (_req, res) => {
cancelAutoShutdown();
res.json({ success: true });
});
// ── Start ──────────────────────────────────────────────────────────────────
loadQueue(); // show queued messages in UI immediately, before WA finishes connecting
loadContactsCache(); // pre-populate contacts from last session so search works instantly
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
exec(`open http://localhost:${PORT}`);
client.initialize();
});