-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
800 lines (680 loc) · 24.6 KB
/
server.js
File metadata and controls
800 lines (680 loc) · 24.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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs-extra');
const { v4: uuidv4 } = require('uuid');
const cors = require('cors');
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
const PORT = process.env.PORT || 3001;
const IMAPSYNC_LOGS_DIR = '/var/log/imapsync';
const IMAPSYNC_TMP_DIR = '/tmp/imapsync';
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'client/build')));
// Ensure directories exist
fs.ensureDirSync(IMAPSYNC_LOGS_DIR);
fs.ensureDirSync(IMAPSYNC_TMP_DIR);
// Store active sync sessions
const activeSyncs = new Map();
// Store sync status for polling-based updates
const syncStatuses = new Map();
// Store user sessions for log isolation
const userSessions = new Map();
// Socket.IO connection handling
io.on('connection', (socket) => {
console.log('Client connected:', socket.id);
// Initialize user session
const userId = socket.handshake.query.userId || uuidv4();
socket.userId = userId;
if (!userSessions.has(userId)) {
const userLogDir = path.join(IMAPSYNC_LOGS_DIR, 'users', userId);
fs.ensureDirSync(userLogDir);
userSessions.set(userId, {
id: userId,
logDir: userLogDir,
createdAt: new Date(),
lastActivity: new Date()
});
}
// Update last activity
userSessions.get(userId).lastActivity = new Date();
// Send user ID to client
socket.emit('user-session', { userId });
socket.on('start-sync', async (syncConfig) => {
const syncId = uuidv4();
console.log(`Starting sync ${syncId} for client ${socket.id}`);
try {
await startImapSync(socket, syncId, syncConfig);
} catch (error) {
socket.emit('sync-error', {
syncId,
error: error.message,
timestamp: new Date().toISOString()
});
}
});
socket.on('get-logs', async () => {
console.log('Client requested logs for user:', socket.userId);
try {
const logs = await getUserLogFiles(socket.userId);
console.log(`Found ${logs.length} log files for user ${socket.userId}:`, logs.map(l => l.name));
socket.emit('logs-list', logs);
} catch (error) {
console.error('Error fetching logs:', error);
socket.emit('error', { message: 'Failed to fetch logs' });
}
});
socket.on('get-log-content', async (filename) => {
console.log('Received get-log-content request for:', filename, 'user:', socket.userId);
try {
const content = await getUserLogContent(socket.userId, filename);
console.log('Sending log content, size:', content.length, 'chars');
socket.emit('log-content', { filename, content });
} catch (error) {
console.error('Error getting log content:', error);
socket.emit('error', { message: 'Failed to fetch log content' });
}
});
socket.on('delete-log', async (filename) => {
console.log('Received delete-log request for:', filename, 'user:', socket.userId);
try {
await deleteUserLog(socket.userId, filename);
console.log('Log deleted successfully:', filename);
socket.emit('log-deleted', { filename });
// Send updated logs list
const logs = await getUserLogFiles(socket.userId);
socket.emit('logs-list', logs);
} catch (error) {
console.error('Error deleting log:', error);
socket.emit('error', { message: 'Failed to delete log file' });
}
});
socket.on('delete-all-logs', async () => {
console.log('Received delete-all-logs request for user:', socket.userId);
try {
const userSession = userSessions.get(socket.userId);
if (userSession) {
const logs = await getUserLogFiles(socket.userId);
for (const log of logs) {
await deleteUserLog(socket.userId, log.name);
}
console.log(`Deleted ${logs.length} log files for user ${socket.userId}`);
}
socket.emit('logs-list', []);
} catch (error) {
console.error('Error deleting all logs:', error);
socket.emit('error', { message: 'Failed to delete all log files' });
}
});
socket.on('test-event', (data) => {
console.log('Received test-event:', data);
});
socket.on('disconnect', () => {
console.log('Client disconnected:', socket.id);
// Clean up any active syncs for this client
for (const [syncId, syncData] of activeSyncs.entries()) {
if (syncData.socketId === socket.id && syncData.process) {
console.log(`Killing sync ${syncId} due to client disconnect`);
syncData.process.kill('SIGTERM');
activeSyncs.delete(syncId);
}
}
});
});
async function startImapSyncPolling(syncId, config) {
return startImapSyncCore(null, syncId, config);
}
async function startImapSync(socket, syncId, config) {
return startImapSyncCore(socket, syncId, config, socket.userId);
}
async function startImapSyncCore(socket, syncId, config, userId = null) {
const {
host1, port1, user1, password1, ssl1,
host2, port2, user2, password2, ssl2,
dryRun, delete1, automap, gmail1, gmail2
} = config;
// Determine log directory - use user-specific if userId provided
const logDir = userId && userSessions.has(userId)
? userSessions.get(userId).logDir
: IMAPSYNC_LOGS_DIR;
// Build imapsync command
const args = [
'--host1', host1,
'--user1', user1,
'--password1', password1,
'--host2', host2,
'--user2', user2,
'--password2', password2,
'--tmpdir', IMAPSYNC_TMP_DIR,
'--logdir', logDir,
'--log',
'--noreleasecheck'
];
if (port1) args.push('--port1', port1);
if (port2) args.push('--port2', port2);
if (ssl1) args.push('--ssl1');
if (ssl2) args.push('--ssl2');
if (dryRun) args.push('--dry');
if (delete1) args.push('--delete1');
if (automap) args.push('--automap');
if (gmail1) args.push('--gmail1');
if (gmail2) args.push('--gmail2');
console.log('Starting imapsync with args:', args.map(arg =>
arg.includes('password') ? '[MASKED]' : arg
));
const startTime = Date.now();
let stats = {
totalMessages: 0,
transferredMessages: 0,
skippedMessages: 0,
errorMessages: 0,
currentFolder: '',
bytesTransferred: 0,
errors: []
};
// Update sync status
const updateSyncStatus = (status, additionalData = {}) => {
const statusData = {
syncId,
status,
timestamp: new Date().toISOString(),
stats: { ...stats },
elapsed: Date.now() - startTime,
...additionalData
};
syncStatuses.set(syncId, statusData);
return statusData;
};
// Emit initial status
const startedData = updateSyncStatus('running', {
command: args.join(' ').replace(/--password\d+ \S+/g, '--password* [MASKED]')
});
if (socket) {
socket.emit('sync-started', startedData);
}
// Spawn imapsync process
const process = spawn('/usr/local/bin/imapsync', args, {
stdio: ['pipe', 'pipe', 'pipe']
});
// Store process reference
activeSyncs.set(syncId, {
process,
socketId: socket.id,
startTime,
stats
});
// Track last emitted stats to avoid spam
let lastEmittedStats = { transferredMessages: 0, totalMessages: 0, currentFolder: '' };
// Periodic stats emission for progress updates (every 15 seconds)
const statsInterval = setInterval(() => {
if (activeSyncs.has(syncId)) {
console.log(`[PERIODIC-STATS] Total: ${stats.totalMessages}, Transferred: ${stats.transferredMessages}, Skipped: ${stats.skippedMessages}, Current: ${stats.currentFolder}`);
// Update sync status for polling
updateSyncStatus('running');
// Only emit if there's meaningful progress or folder change
const hasProgress = stats.transferredMessages !== lastEmittedStats.transferredMessages ||
stats.totalMessages !== lastEmittedStats.totalMessages ||
stats.currentFolder !== lastEmittedStats.currentFolder;
if (socket && (hasProgress || stats.totalMessages > 0)) {
const progressPercent = stats.totalMessages > 0 ? Math.round((stats.transferredMessages / stats.totalMessages) * 100) : 0;
const progressLine = stats.currentFolder
? `[PERIODIC UPDATE] ${stats.transferredMessages}/${stats.totalMessages} messages (${progressPercent}%) - Processing folder: ${stats.currentFolder}`
: `[PERIODIC UPDATE] ${stats.transferredMessages}/${stats.totalMessages} messages (${progressPercent}%) processed`;
socket.emit('sync-output', {
syncId,
timestamp: new Date().toISOString(),
line: progressLine,
type: 'info',
stats: { ...stats },
elapsed: Date.now() - startTime,
realtime: true
});
lastEmittedStats = { ...stats };
}
} else {
clearInterval(statsInterval);
}
}, 15000);
// Handle stdout
process.stdout.on('data', (data) => {
const output = data.toString();
const lines = output.split('\n').filter(line => line.trim());
lines.forEach(line => {
const parsedData = parseImapSyncOutput(line, stats);
// Debug logging
console.log(`[SYNC-STDOUT] ${line.trim()}`);
if (line.includes('msg') || line.includes('messages') || line.includes('folder')) {
console.log(`[STATS] Total: ${stats.totalMessages}, Transferred: ${stats.transferredMessages}, Skipped: ${stats.skippedMessages}, Current: ${stats.currentFolder}`);
}
// Always emit for real-time updates, especially for message processing
const shouldEmitUpdate = line.includes('msg') ||
line.includes('folder') ||
line.includes('transferred') ||
line.includes('skipped') ||
line.includes('messages');
// Update sync status for important events
if (shouldEmitUpdate) {
updateSyncStatus('running');
}
if (socket) {
const outputData = {
syncId,
timestamp: new Date().toISOString(),
line: line.trim(),
type: getLogType(line),
stats: { ...stats },
elapsed: Date.now() - startTime,
realtime: shouldEmitUpdate // Flag for real-time updates
};
// Debug: Log stats when sending important updates
if (shouldEmitUpdate || line.includes('error') || line.includes('failed')) {
console.log(`[EMIT-STATS] ${line.trim().substring(0, 50)}... -> Stats:`, stats);
}
socket.emit('sync-output', outputData);
}
});
});
// Handle stderr
process.stderr.on('data', (data) => {
const output = data.toString();
const lines = output.split('\n').filter(line => line.trim());
lines.forEach(line => {
// Check if stderr contains progress information
console.log(`[SYNC-STDERR] ${line.trim()}`);
// Parse stderr for progress too (some imapsync versions output to stderr)
parseImapSyncOutput(line, stats);
// Only treat as error if it looks like an actual error
const isActualError = line.toLowerCase().includes('error') ||
line.toLowerCase().includes('failed') ||
line.toLowerCase().includes('can\'t') ||
line.toLowerCase().includes('unable');
if (isActualError) {
stats.errors.push(line.trim());
stats.errorMessages++;
}
if (socket) {
const outputData = {
syncId,
timestamp: new Date().toISOString(),
line: line.trim(),
type: isActualError ? 'error' : 'info',
stats: { ...stats },
elapsed: Date.now() - startTime
};
// Debug: Log stats when sending errors
if (isActualError) {
console.log(`[EMIT-ERROR-STATS] ${line.trim().substring(0, 50)}... -> Stats:`, stats);
}
socket.emit('sync-output', outputData);
}
});
});
// Handle process completion
process.on('close', (code) => {
const elapsed = Date.now() - startTime;
const completedData = updateSyncStatus(code === 0 ? 'completed' : 'error', {
exitCode: code,
success: code === 0
});
if (socket) {
socket.emit('sync-completed', completedData);
}
activeSyncs.delete(syncId);
clearInterval(statsInterval); // Clear the periodic stats interval
console.log(`Sync ${syncId} completed with exit code ${code}`);
});
process.on('error', (error) => {
const errorData = updateSyncStatus('error', {
error: error.message
});
if (socket) {
socket.emit('sync-error', errorData);
}
activeSyncs.delete(syncId);
clearInterval(statsInterval); // Clear the periodic stats interval
console.error(`Sync ${syncId} error:`, error);
});
}
function parseImapSyncOutput(line, stats) {
// Extract folder information
const folderMatch = line.match(/folder \[([^\]]+)\]/);
if (folderMatch) {
stats.currentFolder = folderMatch[1];
}
// Real-time message transfer tracking - prioritize individual message processing
if (line.match(/msg (\d+)\/(\d+)/)) {
const msgMatch = line.match(/msg (\d+)\/(\d+)/);
if (msgMatch) {
const current = parseInt(msgMatch[1]);
const total = parseInt(msgMatch[2]);
// Update transferred count in real-time
stats.transferredMessages = current;
// Update total if we have a better count
if (total > stats.totalMessages) {
stats.totalMessages = total;
}
}
} else if (line.includes('msg ') && !line.includes('skipped') && !line.includes('could not') && !line.includes('Messages')) {
// Count individual message transfers for real-time updates
const msgSingleMatch = line.match(/msg (\d+)/);
if (msgSingleMatch) {
const msgNum = parseInt(msgSingleMatch[1]);
// Always update for real-time progress
if (msgNum >= stats.transferredMessages) {
stats.transferredMessages = msgNum;
}
}
}
// Extract final statistics (most reliable for final counts)
if (line.includes('Messages transferred') && line.includes(':')) {
const transferredMatch = line.match(/Messages transferred\s*:\s*(\d+)/);
if (transferredMatch) {
stats.transferredMessages = parseInt(transferredMatch[1]);
}
}
if (line.includes('Messages skipped') && line.includes(':')) {
const skippedMatch = line.match(/Messages skipped\s*:\s*(\d+)/);
if (skippedMatch) {
stats.skippedMessages = parseInt(skippedMatch[1]);
}
}
// Get total messages from reliable sources
if (line.includes('Host1 Nb messages:') || line.includes('Host2 Nb messages:')) {
const nbMatch = line.match(/Host[12] Nb messages:\s*(\d+)/);
if (nbMatch) {
const count = parseInt(nbMatch[1]);
if (count > stats.totalMessages) {
stats.totalMessages = count; // Use the higher count
}
}
}
// Extract message counts from folder scanning
let messageCountMatch = line.match(/(\d+) messages to sync/);
if (messageCountMatch) {
const count = parseInt(messageCountMatch[1]);
stats.totalMessages += count; // Add to running total
}
// Catch "will sync X messages"
messageCountMatch = line.match(/will sync (\d+) messages/);
if (messageCountMatch) {
const count = parseInt(messageCountMatch[1]);
stats.totalMessages += count; // Add to running total
}
// Real-time message processing patterns (ordered by priority)
const messagePatterns = [
/ETA:.*\s+(\d+)\/(\d+)\s+msgs left/i, // Most reliable: ETA lines
/copied.*(\d+)\/(\d+)\s+msgs left/i, // Individual message copied
/(\d+)\/(\d+)\s+msgs left/i, // Simple msgs left pattern
/Messages transferred\s*:\s*(\d+)/i, // Final transferred count
/Messages skipped\s*:\s*(\d+)/i, // Final skipped count
/Host1: folder \[([^\]]+)\] has (\d+) messages/i,
/Host2: folder \[([^\]]+)\] has (\d+) messages/i,
/msg (\d+)\/(\d+)/i,
/(\d+) messages? in .+ will be synced/i
];
for (const pattern of messagePatterns) {
const match = line.match(pattern);
if (match) {
console.log(`[DEBUG-PARSE] Pattern matched: ${pattern.source}`);
console.log(`[DEBUG-PARSE] Line: ${line}`);
console.log(`[DEBUG-PARSE] Groups: ${JSON.stringify(match)}`);
if (pattern.source.includes('ETA:') || pattern.source.includes('msgs left')) {
// Handle ETA and msgs left patterns - most reliable for real-time progress
const msgsLeft = parseInt(match[1]);
const totalMsgs = parseInt(match[2]);
console.log(`[DEBUG-PARSE] ETA/msgs left: ${totalMsgs} total - ${msgsLeft} left = ${totalMsgs - msgsLeft} transferred`);
stats.totalMessages = totalMsgs;
stats.transferredMessages = totalMsgs - msgsLeft;
} else if (pattern.source.includes('transferred')) {
stats.transferredMessages = parseInt(match[1]);
console.log(`[DEBUG-PARSE] Set transferred to: ${stats.transferredMessages}`);
} else if (pattern.source.includes('skipped')) {
stats.skippedMessages = parseInt(match[1]);
console.log(`[DEBUG-PARSE] Set skipped to: ${stats.skippedMessages}`);
} else if (pattern.source.includes('msg') && match[2]) {
// Handle "msg 1/2" pattern
stats.transferredMessages = parseInt(match[1]);
stats.totalMessages = Math.max(stats.totalMessages, parseInt(match[2]));
console.log(`[DEBUG-PARSE] msg pattern: transferred=${stats.transferredMessages}, total=${stats.totalMessages}`);
}
break;
}
}
// Real-time skipped message tracking
if (line.includes('skipped') || line.includes('SKIP')) {
stats.skippedMessages++;
}
// Better bytes transferred parsing
const bytesPatterns = [
/Total bytes transferred\s*:\s*(\d+)/i,
/transferred (\d+) bytes/i,
/(\d+) bytes transferred/i,
/size (\d+) bytes/i,
/(\d+\.?\d*) (\w+) transferred/i
];
for (const pattern of bytesPatterns) {
const match = line.match(pattern);
if (match) {
let bytes = 0;
if (match[2] && ['KB', 'MB', 'GB'].includes(match[2].toUpperCase())) {
const value = parseFloat(match[1]);
const unit = match[2].toUpperCase();
switch (unit) {
case 'KB': bytes = value * 1024; break;
case 'MB': bytes = value * 1024 * 1024; break;
case 'GB': bytes = value * 1024 * 1024 * 1024; break;
}
} else {
bytes = parseInt(match[1]);
}
if (bytes > stats.bytesTransferred) {
stats.bytesTransferred = bytes;
}
break;
}
}
// Extract progress summaries
const progressMatch = line.match(/(\d+)\/(\d+) messages? \((\d+)%\)/);
if (progressMatch) {
stats.transferredMessages = parseInt(progressMatch[1]);
stats.totalMessages = parseInt(progressMatch[2]);
}
// Extract final statistics
const finalStatsMatch = line.match(/Messages: (\d+) transferred, (\d+) skipped/);
if (finalStatsMatch) {
stats.transferredMessages = parseInt(finalStatsMatch[1]);
stats.skippedMessages = parseInt(finalStatsMatch[2]);
}
return stats;
}
function getLogType(line) {
if (line.includes('ERROR') || line.includes('FAILED')) return 'error';
if (line.includes('WARNING')) return 'warning';
if (line.includes('SUCCESS') || line.includes('OK')) return 'success';
if (line.includes('folder') || line.includes('msg')) return 'info';
return 'default';
}
async function getLogFiles() {
try {
const files = await fs.readdir(IMAPSYNC_LOGS_DIR);
const logFiles = [];
for (const file of files) {
if (file.endsWith('.txt') || file.endsWith('.log')) {
const filePath = path.join(IMAPSYNC_LOGS_DIR, file);
const stats = await fs.stat(filePath);
logFiles.push({
name: file,
size: stats.size,
modified: stats.mtime.toISOString(),
created: stats.birthtime.toISOString()
});
}
}
return logFiles.sort((a, b) => new Date(b.modified) - new Date(a.modified));
} catch (error) {
console.error('Error reading log files:', error);
return [];
}
}
async function getLogContent(filename) {
const filePath = path.join(IMAPSYNC_LOGS_DIR, filename);
// Security check - allow alphanumeric, dots, underscores, dashes, and @ symbols
if (!filename.match(/^[a-zA-Z0-9._@-]+$/)) {
throw new Error('Invalid filename');
}
try {
const content = await fs.readFile(filePath, 'utf8');
return content;
} catch (error) {
throw new Error('File not found or cannot be read');
}
}
// User-specific log functions
async function getUserLogFiles(userId) {
try {
const userSession = userSessions.get(userId);
if (!userSession) {
return [];
}
const userLogDir = userSession.logDir;
if (!await fs.pathExists(userLogDir)) {
return [];
}
const files = await fs.readdir(userLogDir);
const logFiles = [];
for (const file of files) {
if (file.endsWith('.txt') || file.endsWith('.log')) {
const filePath = path.join(userLogDir, file);
const stats = await fs.stat(filePath);
logFiles.push({
name: file,
size: stats.size,
modified: stats.mtime.toISOString(),
created: stats.birthtime.toISOString()
});
}
}
return logFiles.sort((a, b) => new Date(b.modified) - new Date(a.modified));
} catch (error) {
console.error('Error reading user log directory:', error);
return [];
}
}
async function getUserLogContent(userId, filename) {
const userSession = userSessions.get(userId);
if (!userSession) {
throw new Error('User session not found');
}
const filePath = path.join(userSession.logDir, filename);
// Security check - allow alphanumeric, dots, underscores, dashes, and @ symbols
if (!filename.match(/^[a-zA-Z0-9._@-]+$/)) {
throw new Error('Invalid filename');
}
try {
const content = await fs.readFile(filePath, 'utf8');
return content;
} catch (error) {
throw new Error(`Failed to read log file: ${error.message}`);
}
}
async function deleteUserLog(userId, filename) {
const userSession = userSessions.get(userId);
if (!userSession) {
throw new Error('User session not found');
}
const filePath = path.join(userSession.logDir, filename);
// Security check - allow alphanumeric, dots, underscores, dashes, and @ symbols
if (!filename.match(/^[a-zA-Z0-9._@-]+$/)) {
throw new Error('Invalid filename');
}
try {
await fs.unlink(filePath);
console.log(`Deleted log file: ${filePath}`);
} catch (error) {
throw new Error(`Failed to delete log file: ${error.message}`);
}
}
// API Routes
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
app.get('/api/logs', async (req, res) => {
try {
const logs = await getLogFiles();
res.json(logs);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch logs' });
}
});
app.get('/api/logs/:filename', async (req, res) => {
try {
const content = await getLogContent(req.params.filename);
res.type('text/plain').send(content);
} catch (error) {
res.status(404).json({ error: error.message });
}
});
// Get active sync status (for polling)
app.get('/api/sync/status/:syncId', (req, res) => {
const syncId = req.params.syncId;
const syncStatus = syncStatuses.get(syncId);
if (!syncStatus) {
return res.status(404).json({ error: 'Sync not found' });
}
res.json(syncStatus);
});
// Get all active syncs
app.get('/api/sync/active', (req, res) => {
const activeList = Array.from(activeSyncs.entries()).map(([syncId, syncData]) => ({
syncId,
startTime: syncData.startTime,
stats: syncData.stats,
status: syncStatuses.get(syncId)?.status || 'running'
}));
res.json(activeList);
});
// Start sync via REST API (backup to WebSocket)
app.post('/api/sync/start', async (req, res) => {
const syncId = uuidv4();
const config = req.body;
try {
// Store initial status
syncStatuses.set(syncId, {
syncId,
status: 'starting',
timestamp: new Date().toISOString(),
stats: {
totalMessages: 0,
transferredMessages: 0,
skippedMessages: 0,
errorMessages: 0,
currentFolder: 'Initializing...',
bytesTransferred: 0,
errors: []
},
elapsed: 0
});
// Start sync without socket dependency
await startImapSyncPolling(syncId, config);
res.json({ syncId, status: 'started' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Serve React app for all non-API routes
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
server.listen(PORT, '0.0.0.0', () => {
console.log(`ImapSync SPA server running on port ${PORT}`);
});