-
Notifications
You must be signed in to change notification settings - Fork 695
Expand file tree
/
Copy pathserver.ts
More file actions
429 lines (362 loc) · 15.2 KB
/
Copy pathserver.ts
File metadata and controls
429 lines (362 loc) · 15.2 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
/**
* Device Activity Tracker - Web Server
*
* HTTP server with Socket.IO for real-time tracking visualization.
* Provides REST API and WebSocket interface for the React frontend.
*
* For educational and research purposes only.
*/
import express from 'express';
import { createServer } from 'http';
import { Server } from 'socket.io';
import cors from 'cors';
import makeWASocket, { DisconnectReason, useMultiFileAuthState } from '@whiskeysockets/baileys';
import { pino } from 'pino';
import { Boom } from '@hapi/boom';
import { WhatsAppTracker, ProbeMethod } from './tracker.js';
import { SignalTracker, getSignalAccounts, checkSignalNumber } from './signal-tracker.js';
// Configuration
const SIGNAL_API_URL = process.env.SIGNAL_API_URL || 'http://localhost:8080';
const app = express();
app.use(cors());
const httpServer = createServer(app);
const io = new Server(httpServer, {
cors: {
origin: "*", // Allow all origins for dev
methods: ["GET", "POST"]
}
});
let sock: any;
let isWhatsAppConnected = false;
let isSignalConnected = false;
let signalAccountNumber: string | null = null;
let globalProbeMethod: ProbeMethod = 'delete'; // Default to delete method
let currentWhatsAppQr: string | null = null; // Store current QR code for new clients
// Platform type for contacts
type Platform = 'whatsapp' | 'signal';
interface TrackerEntry {
tracker: WhatsAppTracker | SignalTracker;
platform: Platform;
}
const trackers: Map<string, TrackerEntry> = new Map(); // JID/Number -> Tracker entry
async function connectToWhatsApp() {
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
sock = makeWASocket({
auth: state,
logger: pino({ level: 'debug' }),
markOnlineOnConnect: true,
printQRInTerminal: false,
});
sock.ev.on('connection.update', async (update: any) => {
const { connection, lastDisconnect, qr } = update;
if (qr) {
console.log('QR Code generated');
currentWhatsAppQr = qr; // Store the QR code
io.emit('qr', qr);
}
if (connection === 'close') {
isWhatsAppConnected = false;
currentWhatsAppQr = null; // Clear QR on close
const shouldReconnect = (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut;
console.log('connection closed, reconnecting ', shouldReconnect);
if (shouldReconnect) {
connectToWhatsApp();
}
} else if (connection === 'open') {
isWhatsAppConnected = true;
currentWhatsAppQr = null; // Clear QR on successful connection
console.log('opened connection');
io.emit('connection-open');
}
});
sock.ev.on('creds.update', saveCreds);
sock.ev.on('messaging-history.set', ({ chats, contacts, messages, isLatest }: any) => {
console.log(`[SESSION] History sync - Chats: ${chats.length}, Contacts: ${contacts.length}, Messages: ${messages.length}, Latest: ${isLatest}`);
});
sock.ev.on('messages.update', (updates: any) => {
for (const update of updates) {
console.log(`[MSG UPDATE] JID: ${update.key.remoteJid}, ID: ${update.key.id}, Status: ${update.update.status}, FromMe: ${update.key.fromMe}`);
}
});
}
connectToWhatsApp();
// Signal linking state
let signalLinkingInProgress = false;
let signalApiAvailable = false;
let currentSignalQrUrl: string | null = null;
// Check Signal API availability
async function checkSignalApiAvailable(): Promise<boolean> {
try {
const response = await fetch(`${SIGNAL_API_URL}/v1/about`, {
signal: AbortSignal.timeout(2000)
});
return response.ok;
} catch {
return false;
}
}
// Check Signal connection status
async function checkSignalConnection() {
try {
const available = await checkSignalApiAvailable();
if (available !== signalApiAvailable) {
signalApiAvailable = available;
console.log(`[SIGNAL] API available: ${available}`);
io.emit('signal-api-status', { available });
}
if (!available) {
if (isSignalConnected) {
isSignalConnected = false;
signalAccountNumber = null;
io.emit('signal-disconnected');
}
return;
}
const accounts = await getSignalAccounts(SIGNAL_API_URL);
if (accounts.length > 0) {
if (!isSignalConnected) {
isSignalConnected = true;
signalAccountNumber = accounts[0];
signalLinkingInProgress = false;
console.log(`[SIGNAL] Connected with account: ${signalAccountNumber}`);
io.emit('signal-connection-open', { number: signalAccountNumber });
}
} else {
if (isSignalConnected) {
isSignalConnected = false;
signalAccountNumber = null;
console.log('[SIGNAL] Disconnected');
io.emit('signal-disconnected');
}
// No accounts - need to link, start QR code process
if (!signalLinkingInProgress) {
startSignalLinking();
}
}
} catch (err) {
console.log('[SIGNAL] Error checking connection:', err);
if (isSignalConnected) {
isSignalConnected = false;
signalAccountNumber = null;
io.emit('signal-disconnected');
}
}
}
// Start Signal device linking - signal-cli-rest-api returns QR as PNG image
async function startSignalLinking() {
if (signalLinkingInProgress || isSignalConnected) return;
signalLinkingInProgress = true;
console.log('[SIGNAL] Starting device linking...');
try {
// Check if the QR endpoint is available
const response = await fetch(`${SIGNAL_API_URL}/v1/qrcodelink?device_name=activity-tracker`);
if (!response.ok) {
console.log('[SIGNAL] Failed to start linking:', response.status);
signalLinkingInProgress = false;
return;
}
// signal-cli-rest-api returns the QR code as a PNG image directly
// Send the URL to the frontend to display as an image
currentSignalQrUrl = `${SIGNAL_API_URL}/v1/qrcodelink?device_name=activity-tracker&t=${Date.now()}`;
console.log('[SIGNAL] Emitting QR image URL:', currentSignalQrUrl);
io.emit('signal-qr-image', currentSignalQrUrl);
// Keep polling to check if linking completed
pollSignalLinkingStatus();
} catch (err) {
console.log('[SIGNAL] Error starting linking:', err);
signalLinkingInProgress = false;
}
}
// Poll to check if Signal linking has completed
async function pollSignalLinkingStatus() {
const checkInterval = setInterval(async () => {
try {
const accounts = await getSignalAccounts(SIGNAL_API_URL);
if (accounts.length > 0) {
// Linking completed!
clearInterval(checkInterval);
signalLinkingInProgress = false;
currentSignalQrUrl = null;
isSignalConnected = true;
signalAccountNumber = accounts[0];
console.log(`[SIGNAL] Linking completed! Account: ${signalAccountNumber}`);
io.emit('signal-connection-open', { number: signalAccountNumber });
}
} catch (err) {
// Keep polling
}
}, 2000);
// Stop polling after 5 minutes
setTimeout(() => {
clearInterval(checkInterval);
signalLinkingInProgress = false;
}, 300000);
}
// Check Signal connection periodically
checkSignalConnection();
setInterval(checkSignalConnection, 5000);
io.on('connection', (socket) => {
console.log('Client connected');
// Send current WhatsApp QR code if available
if (currentWhatsAppQr) {
socket.emit('qr', currentWhatsAppQr);
}
if (isWhatsAppConnected) {
socket.emit('connection-open');
}
if (isSignalConnected && signalAccountNumber) {
socket.emit('signal-connection-open', { number: signalAccountNumber });
}
// Send Signal API availability status
socket.emit('signal-api-status', { available: signalApiAvailable });
// Send current Signal QR code if linking is in progress
if (signalLinkingInProgress && currentSignalQrUrl) {
socket.emit('signal-qr-image', currentSignalQrUrl);
}
// Send current probe method to client
socket.emit('probe-method', globalProbeMethod);
// Send tracked contacts with platform info
const trackedContacts = Array.from(trackers.entries()).map(([id, entry]) => ({
id,
platform: entry.platform
}));
// Handle request to get tracked contacts (for page refresh)
socket.on('get-tracked-contacts', () => {
const trackedContacts = Array.from(trackers.entries()).map(([id, entry]) => ({
id,
platform: entry.platform
}));
socket.emit('tracked-contacts', trackedContacts);
});
// Add contact - supports both WhatsApp and Signal
socket.on('add-contact', async (data: string | { number: string; platform: Platform }) => {
// Support both old format (string) and new format (object)
const { number, platform } = typeof data === 'string'
? { number: data, platform: 'whatsapp' as Platform }
: data;
console.log(`Request to track on ${platform}: ${number}`);
const cleanNumber = number.replace(/\D/g, '');
if (platform === 'signal') {
// Signal tracking
if (!isSignalConnected || !signalAccountNumber) {
socket.emit('error', { message: 'Signal is not connected. Please link Signal first.' });
return;
}
const signalId = `signal:${cleanNumber}`;
if (trackers.has(signalId)) {
socket.emit('error', { jid: signalId, message: 'Already tracking this contact on Signal' });
return;
}
try {
const targetNumber = cleanNumber.startsWith('+') ? cleanNumber : `+${cleanNumber}`;
// Check if number is registered and discoverable on Signal
console.log(`[SIGNAL] Checking if ${targetNumber} is registered...`);
const checkResult = await checkSignalNumber(SIGNAL_API_URL, signalAccountNumber, targetNumber);
if (!checkResult.registered) {
console.log(`[SIGNAL] Number ${targetNumber} is not discoverable: ${checkResult.error}`);
socket.emit('error', {
jid: signalId,
message: checkResult.error || 'Number is not registered on Signal'
});
return;
}
console.log(`[SIGNAL] Number ${targetNumber} is registered, starting tracking...`);
const tracker = new SignalTracker(SIGNAL_API_URL, signalAccountNumber, targetNumber);
trackers.set(signalId, { tracker, platform: 'signal' });
tracker.onUpdate = (updateData) => {
io.emit('tracker-update', {
jid: signalId,
platform: 'signal',
...updateData
});
};
tracker.startTracking();
socket.emit('contact-added', {
jid: signalId,
number: cleanNumber,
platform: 'signal'
});
io.emit('contact-name', { jid: signalId, name: cleanNumber });
} catch (err) {
console.error(err);
socket.emit('error', { message: 'Failed to start Signal tracking' });
}
} else {
// WhatsApp tracking (original logic)
const targetJid = cleanNumber + '@s.whatsapp.net';
if (trackers.has(targetJid)) {
socket.emit('error', { jid: targetJid, message: 'Already tracking this contact' });
return;
}
try {
const results = await sock.onWhatsApp(targetJid);
const result = results?.[0];
if (result?.exists) {
const tracker = new WhatsAppTracker(sock, result.jid);
tracker.setProbeMethod(globalProbeMethod);
trackers.set(result.jid, { tracker, platform: 'whatsapp' });
tracker.onUpdate = (updateData) => {
io.emit('tracker-update', {
jid: result.jid,
platform: 'whatsapp',
...updateData
});
};
tracker.startTracking();
const ppUrl = await tracker.getProfilePicture();
let contactName = cleanNumber;
try {
const contactInfo = await sock.onWhatsApp(result.jid);
if (contactInfo && contactInfo[0]?.notify) {
contactName = contactInfo[0].notify;
}
} catch (err) {
console.log('[NAME] Could not fetch contact name, using number');
}
socket.emit('contact-added', {
jid: result.jid,
number: cleanNumber,
platform: 'whatsapp'
});
io.emit('profile-pic', { jid: result.jid, url: ppUrl });
io.emit('contact-name', { jid: result.jid, name: contactName });
} else {
socket.emit('error', { jid: targetJid, message: 'Number not on WhatsApp' });
}
} catch (err) {
console.error(err);
socket.emit('error', { jid: targetJid, message: 'Verification failed' });
}
}
});
socket.on('remove-contact', (jid: string) => {
console.log(`Request to stop tracking: ${jid}`);
const entry = trackers.get(jid);
if (entry) {
entry.tracker.stopTracking();
trackers.delete(jid);
socket.emit('contact-removed', jid);
}
});
socket.on('set-probe-method', (method: ProbeMethod) => {
console.log(`Request to change probe method to: ${method}`);
if (method !== 'delete' && method !== 'reaction') {
socket.emit('error', { message: 'Invalid probe method' });
return;
}
globalProbeMethod = method;
for (const entry of trackers.values()) {
// Only WhatsApp trackers support the delete method
if (entry.platform === 'whatsapp') {
(entry.tracker as WhatsAppTracker).setProbeMethod(method);
}
// Signal trackers always use reaction method
}
io.emit('probe-method', method);
console.log(`Probe method changed to: ${method}`);
});
});
const PORT = parseInt(process.env.PORT || '3001', 10);
httpServer.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});