-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
3225 lines (2830 loc) · 111 KB
/
main.js
File metadata and controls
3225 lines (2830 loc) · 111 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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { app, BrowserWindow, ipcMain, Notification, shell, dialog, nativeImage } = require('electron');
const path = require('path');
const fs = require('fs');
const https = require('https');
const http = require('http');
const crypto = require('crypto');
const url = require('url');
const { execSync, spawn } = require('child_process');
const Store = require('electron-store');
const imapSimple = require('imap-simple');
const { simpleParser } = require('mailparser');
const nodemailer = require('nodemailer');
const fetch = require('node-fetch');
// ============ EIO FIX (v5.0.6) ============
// When launched without a terminal (desktop icon, autostart), stdout/stderr are
// closed. Any console.log() call then throws "Error: write EIO" which Electron
// catches as an uncaught exception and shows a native error dialog.
// Fix: wrap all console methods to silently swallow EIO write errors.
['log', 'warn', 'error', 'info', 'debug'].forEach((method) => {
const original = console[method].bind(console);
console[method] = (...args) => {
try {
original(...args);
} catch (e) {
if (e.code !== 'EIO') throw e;
// EIO = broken pipe / no terminal — silently ignore
}
};
});
// ============ SANDBOX FIX (v3.0.9) ============
// Required for AppImage on Ubuntu/GNOME where FUSE sandbox is not available
// Must be called before app.whenReady()
app.commandLine.appendSwitch('no-sandbox');
// ============ GPU/OPENGL FIX (v1.5.2) ============
// Completely disable GPU/OpenGL to prevent "GetVSyncParametersIfAvailable() failed" errors
// This MUST be called before app.whenReady() - it's the most reliable fix
app.disableHardwareAcceleration();
// Additional command line flags for complete GPU suppression
app.commandLine.appendSwitch('disable-gpu');
app.commandLine.appendSwitch('disable-gpu-compositing');
app.commandLine.appendSwitch('disable-gpu-vsync');
app.commandLine.appendSwitch('disable-frame-rate-limit');
app.commandLine.appendSwitch('disable-gpu-sandbox');
app.commandLine.appendSwitch('disable-features', 'VizDisplayCompositor');
app.commandLine.appendSwitch('use-gl', 'swiftshader');
app.commandLine.appendSwitch('enable-features', 'VaapiVideoDecoder');
// Fix for /dev/shm ESRCH error on ARM64/Kali Linux:
// Use /tmp for shared memory instead of /dev/shm
app.commandLine.appendSwitch('disable-dev-shm-usage');
// Suppress GPU-related logging
app.commandLine.appendSwitch('disable-logging');
app.commandLine.appendSwitch('log-level', '3'); // Only fatal errors
// App Version - read from package.json
const APP_VERSION = require('./package.json').version;
const GITHUB_REPO = 'Zenovs/coremail';
// Verschlüsselte Speicherung
// v4.5.6: Benutzerspezifischer Key statt hardcodiertem String.
// Der Key wird aus dem Home-Verzeichnis des Users abgeleitet — damit ist er
// pro Benutzer und Maschine einzigartig und steht nicht im Quellcode.
// Migrations-Logik: Falls die Config noch mit dem alten Key verschlüsselt ist,
// wird sie automatisch auf den neuen Key migriert.
const os = require('os');
const LEGACY_ENCRYPTION_KEY = 'coremail-secure-key-v1';
const deriveEncryptionKey = () =>
crypto.createHash('sha256')
.update(os.homedir() + '-coremail-v2')
.digest('hex');
let store;
try {
store = new Store({ encryptionKey: deriveEncryptionKey(), name: 'coremail-config' });
// Lese-Test: prüft ob der Key korrekt ist
store.get('accounts', []);
} catch (_) {
// Config wurde mit altem Key verschlüsselt → migrieren
try {
const legacyStore = new Store({ encryptionKey: LEGACY_ENCRYPTION_KEY, name: 'coremail-config' });
const legacyData = legacyStore.store; // Gesamten Inhalt lesen
// Neu verschlüsseln mit dem benutzerspezifischen Key
store = new Store({ encryptionKey: deriveEncryptionKey(), name: 'coremail-config' });
store.store = legacyData;
console.log('[Store] Migration von Legacy-Key auf benutzerspezifischen Key erfolgreich.');
} catch (migErr) {
// Migration fehlgeschlagen — Konfigurationsdatei löschen und neu erstellen
console.error('[Store] Migrationsfehler, Konfiguration wird zurückgesetzt:', migErr.message);
try {
const configPath = require('path').join(require('os').homedir(), '.config', 'coremail-desktop', 'coremail-config.json');
if (require('fs').existsSync(configPath)) {
require('fs').unlinkSync(configPath);
console.log('[Store] Konfigurationsdatei gelöscht, neuer Store wird erstellt.');
}
} catch (delErr) {
console.error('[Store] Fehler beim Löschen der Konfigurationsdatei:', delErr.message);
}
store = new Store({ encryptionKey: deriveEncryptionKey(), name: 'coremail-config' });
}
}
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 1000,
minHeight: 700,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
},
backgroundColor: '#0a0a0a',
icon: getIconPath(),
title: 'CoreMail Desktop'
});
const isDev = process.env.NODE_ENV === 'development';
// Debug logging for loading issues (v2.4.1)
mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
console.error(`[CoreMail] Failed to load: ${errorCode} - ${errorDescription}`);
console.error(`[CoreMail] URL: ${validatedURL}`);
});
mainWindow.webContents.on('did-finish-load', () => {
console.log('[CoreMail] Page loaded successfully');
});
// Handle render process crashes (v2.4.1)
mainWindow.webContents.on('render-process-gone', (event, details) => {
console.error('[CoreMail] Render process gone:', details.reason);
// Attempt to reload
if (details.reason !== 'killed') {
setTimeout(() => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.reload();
}
}, 1000);
}
});
mainWindow.webContents.on('unresponsive', () => {
console.error('[CoreMail] Window became unresponsive');
});
mainWindow.webContents.on('responsive', () => {
console.log('[CoreMail] Window is responsive again');
});
if (isDev) {
mainWindow.loadURL('http://localhost:3000');
mainWindow.webContents.openDevTools();
} else {
// Production: Load from build directory (v2.4.1 - improved path handling)
const indexPath = path.join(__dirname, 'build', 'index.html');
console.log('[CoreMail] Loading production build from:', indexPath);
// Check if file exists
if (fs.existsSync(indexPath)) {
mainWindow.loadFile(indexPath).catch(err => {
console.error('[CoreMail] Error loading index.html:', err);
});
} else {
console.error('[CoreMail] index.html not found at:', indexPath);
// Show error in window
mainWindow.loadURL(`data:text/html,<h1>Error: Build not found</h1><p>Please run 'npm run build' first.</p>`);
}
}
mainWindow.on('closed', () => {
mainWindow = null;
});
// Context menu für Kopieren/Einfügen in der gesamten App
mainWindow.webContents.on('context-menu', (e, params) => {
const { Menu, MenuItem } = require('electron');
const menu = new Menu();
if (params.selectionText) {
menu.append(new MenuItem({ label: 'Kopieren', role: 'copy' }));
}
if (params.isEditable) {
menu.append(new MenuItem({ label: 'Ausschneiden', role: 'cut' }));
menu.append(new MenuItem({ label: 'Einfügen', role: 'paste' }));
menu.append(new MenuItem({ label: 'Alles auswählen', role: 'selectAll' }));
}
if (params.linkURL) {
const safeUrl = params.linkURL;
const isSafeUrl = safeUrl.startsWith('https://') || safeUrl.startsWith('http://') || safeUrl.startsWith('mailto:');
if (isSafeUrl) {
menu.append(new MenuItem({ label: 'Link öffnen', click: () => shell.openExternal(safeUrl) }));
}
menu.append(new MenuItem({ label: 'Link kopieren', click: () => require('electron').clipboard.writeText(params.linkURL) }));
}
if (menu.items.length > 0) menu.popup();
});
// Auto-Update Check on startup if enabled
const settings = store.get('appSettings', {});
if (settings.autoCheckUpdates !== false) {
setTimeout(() => {
checkForUpdates(true); // Silent check
}, 5000);
}
}
// ============ AUTO-START OLLAMA (v1.7.1) ============
async function autoStartOllama() {
// Only try to start if Ollama is installed
if (!isOllamaInstalled()) {
console.log('[Ollama] Not installed, skipping auto-start');
return;
}
// Check if already running
if (await isOllamaRunning()) {
console.log('[Ollama] Already running');
return;
}
console.log('[Ollama] Installed but not running, starting automatically...');
// Try systemctl first (silent)
try {
execSync('systemctl --user start ollama 2>/dev/null', { stdio: 'ignore' });
await new Promise(resolve => setTimeout(resolve, 1000));
if (await isOllamaRunning()) {
console.log('[Ollama] Started via systemctl');
return;
}
} catch {
// Ignore systemctl errors
}
// Fallback: start ollama serve in background
try {
const ollamaProcess = spawn('ollama', ['serve'], {
detached: true,
stdio: 'ignore'
});
ollamaProcess.unref();
console.log('[Ollama] Started via ollama serve');
} catch (err) {
console.log('[Ollama] Could not auto-start:', err.message);
}
}
// v5.0.8: Set app identity before window creation so Linux WM_CLASS matches
// the StartupWMClass in the .desktop file → taskbar shows the correct icon
app.setName('coremail-desktop');
app.setAppUserModelId('com.coremail.desktop');
app.whenReady().then(async () => {
createWindow();
// Auto-start Ollama in background (non-blocking)
setTimeout(() => autoStartOllama(), 2000);
// Sync system launcher icons in background (non-blocking)
setTimeout(() => syncSystemIcons(), 3000);
// Logbuch: App-Start protokollieren
addLogEntry('app_start', `CoreMail v${APP_VERSION} gestartet`, `Plattform: ${process.platform}`);
// Zeitversetzt senden: alle 30s prüfen
const scheduledEmailInterval = setInterval(() => processScheduledEmails(), 30000);
app.on('before-quit', () => clearInterval(scheduledEmailInterval));
});
// v3.0.3: Refresh Linux system launcher icons from GitHub so the correct icon
// appears in the app drawer after an in-app update (no re-install needed).
function syncSystemIcons() {
if (process.platform !== 'linux') return;
try {
const { execFile } = require('child_process');
const os = require('os');
const home = os.homedir();
const ICON_BASE = 'https://raw.githubusercontent.com/Zenovs/coremail/initial-code/public/icons';
const SIZES = [16, 32, 64, 128, 256, 512];
const APP_VERSION = app.getVersion();
const versionKey = `iconsVersion`;
const storedVersion = store.get(versionKey, '0');
// Only update if app version changed (avoids unnecessary network requests)
if (storedVersion === APP_VERSION) return;
const downloadFile = (url, dest) => new Promise((resolve) => {
const file = fs.createWriteStream(dest);
https.get(url, (res) => {
res.pipe(file);
file.on('finish', () => { file.close(); resolve(); });
}).on('error', () => { file.close(); resolve(); });
});
(async () => {
try {
for (const sz of SIZES) {
const dir = path.join(home, `.local/share/icons/hicolor/${sz}x${sz}/apps`);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
await downloadFile(`${ICON_BASE}/icon-${sz}.png`, path.join(dir, 'coremail.png'));
}
// pixmaps (used as absolute icon path in .desktop file)
const pixDir = path.join(home, '.local/share/pixmaps');
if (!fs.existsSync(pixDir)) fs.mkdirSync(pixDir, { recursive: true });
const pixIconPath = path.join(pixDir, 'coremail.png');
await downloadFile(`${ICON_BASE}/icon-256.png`, pixIconPath);
// Rewrite .desktop file — always create/update after version change
const desktopDir = path.join(home, '.local/share/applications');
if (!fs.existsSync(desktopDir)) fs.mkdirSync(desktopDir, { recursive: true });
const desktopFile = path.join(desktopDir, 'coremail.desktop');
const appImagePath = path.join(home, '.local/bin/coremail-desktop');
const desktopContent = [
'[Desktop Entry]',
'Version=1.0',
'Type=Application',
'Name=CoreMail Desktop',
'Comment=E-Mail Client für Linux',
// --no-sandbox is required on GNOME/Ubuntu without user namespaces
`Exec=env APPIMAGE_EXTRACT_AND_RUN=1 ${appImagePath} --no-sandbox`,
`Icon=${pixIconPath}`,
'Terminal=false',
'Categories=Network;Email;Office;',
'StartupNotify=true',
'StartupWMClass=coremail-desktop',
'Keywords=email;mail;imap;smtp;',
''
].join('\n');
fs.writeFileSync(desktopFile, desktopContent);
try { fs.chmodSync(desktopFile, 0o755); } catch (_) {}
// Refresh caches
execFile('gtk-update-icon-cache', ['-f', path.join(home, '.local/share/icons/hicolor')], () => {});
execFile('update-desktop-database', [path.join(home, '.local/share/applications')], () => {});
store.set(versionKey, APP_VERSION);
console.log('[Icons] System launcher icons updated to v' + APP_VERSION);
} catch (e) {
console.warn('[Icons] Could not update system icons:', e.message);
}
})();
} catch (e) {
console.warn('[Icons] syncSystemIcons error:', e.message);
}
}
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// ============ HELPER FUNCTIONS ============
function getAccountById(accountId) {
const accounts = store.get('accounts', []);
return accounts.find(acc => acc.id === accountId);
}
// v2.0.0: IMAP-Konfiguration für ein Konto erstellen
function getImapConfigForAccount(account) {
return {
imap: {
user: account.imap.username,
password: account.imap.password,
host: account.imap.host,
port: parseInt(account.imap.port) || 993,
tls: account.imap.tls !== false,
authTimeout: 15000,
connTimeout: 30000,
tlsOptions: { rejectUnauthorized: false }
}
};
}
// ── IMAP Connection Pool ────────────────────────────────────────────────────
// Keeps one live IMAP connection per account, reconnects transparently on error.
// Avoids the TCP handshake + TLS + auth overhead (typically 1–3s) on every fetch.
const imapPool = new Map(); // accountId → { connection, busy }
const IMAP_IDLE_TTL = 5 * 60 * 1000; // close connections idle for > 5 minutes
setInterval(() => {
const now = Date.now();
for (const [id, entry] of imapPool) {
if (!entry.busy && (now - entry.lastUsed) > IMAP_IDLE_TTL) {
try { entry.connection.end(); } catch (_) {}
imapPool.delete(id);
console.log(`[IMAPPool] Closed idle connection for ${id}`);
}
}
}, 60_000);
async function getPooledImapConnection(account) {
const entry = imapPool.get(account.id);
if (entry && !entry.busy) {
// Verify the connection is still alive via a lightweight STATUS check
try {
entry.busy = true;
entry.lastUsed = Date.now();
return entry.connection;
} catch (_) {
imapPool.delete(account.id);
}
}
// Create a new connection
const config = getImapConfigForAccount(account);
const connection = await imapSimple.connect(config);
imapPool.set(account.id, { connection, busy: true, lastUsed: Date.now() });
return connection;
}
function releaseImapConnection(accountId, destroy = false) {
const entry = imapPool.get(accountId);
if (!entry) return;
if (destroy) {
try { entry.connection.end(); } catch (_) {}
imapPool.delete(accountId);
} else {
entry.busy = false;
entry.lastUsed = Date.now();
}
}
// Clean up all pooled connections on quit
app.on('before-quit', () => {
for (const [, entry] of imapPool) {
try { entry.connection.end(); } catch (_) {}
}
imapPool.clear();
});
// v2.8.4: Find the Sent folder by \Sent attribute or common names
async function findSentFolderName(connection) {
try {
const boxes = await connection.getBoxes();
const COMMON_SENT = ['Sent', 'Sent Items', 'Sent Mail', '[Gmail]/Sent Mail',
'INBOX.Sent', 'Gesendet', 'INBOX.Gesendet', 'Gesendete Elemente'];
const search = (boxes, prefix) => {
for (const [name, box] of Object.entries(boxes)) {
const sep = box.delimiter || '/';
const fullName = prefix ? `${prefix}${sep}${name}` : name;
if (box.attribs && (box.attribs.includes('\\Sent') || box.attribs.includes('\\sent')))
return fullName;
if (box.children) {
const found = search(box.children, fullName);
if (found) return found;
}
}
return null;
};
const byAttrib = search(boxes, '');
if (byAttrib) return byAttrib;
// Collect all folder names and try common patterns
const allNames = [];
const collect = (boxes, prefix) => {
for (const [name, box] of Object.entries(boxes)) {
const sep = box.delimiter || '/';
const fullName = prefix ? `${prefix}${sep}${name}` : name;
allNames.push(fullName);
if (box.children) collect(box.children, fullName);
}
};
collect(boxes, '');
for (const common of COMMON_SENT) {
const found = allNames.find(n => n.toLowerCase() === common.toLowerCase());
if (found) return found;
}
return null;
} catch (e) {
console.error('[Sent] findSentFolderName error:', e);
return null;
}
}
// v2.1.0: SMTP-Transporter für ein Konto erstellen (mit Anzeigename-Unterstützung)
function getSmtpTransporterForAccount(account) {
const smtp = account.smtp;
const port = parseInt(smtp.port) || 587;
// Auto-detect secure mode: port 465 = implicit TLS, 587/25 = STARTTLS
// If smtp.secure is explicitly set, respect it; otherwise derive from port.
let secure;
if (smtp.secure !== undefined && smtp.secure !== null) {
secure = smtp.secure !== false;
} else {
secure = port === 465;
}
const transporter = nodemailer.createTransport({
host: smtp.host,
port,
secure,
auth: {
user: smtp.username,
pass: smtp.password
},
tls: { rejectUnauthorized: false }, // accept self-signed certs
connectionTimeout: 15000, // 15s to connect
greetingTimeout: 10000, // 10s for SMTP greeting
socketTimeout: 30000, // 30s per socket operation
});
const email = smtp.fromEmail || smtp.username;
const displayName = account.displayName ? account.displayName.replace(/["\\\r\n]/g, '') : '';
const fromEmail = displayName ? `"${displayName}" <${email}>` : email;
return { transporter, fromEmail };
}
// v2.3.0: Improved icon path resolution
function getIconPath() {
if (app.isPackaged) {
// Try multiple locations for packaged app
const locations = [
path.join(process.resourcesPath, 'icon.png'),
path.join(process.resourcesPath, 'app.asar', 'assets', 'icon.png'),
path.join(__dirname, 'assets', 'icon.png')
];
for (const loc of locations) {
if (fs.existsSync(loc)) {
return loc;
}
}
}
return path.join(__dirname, 'assets', 'icon.png');
}
// v2.3.0: Get notification icon (transparent background)
function getNotificationIconPath() {
const iconName = 'notification.png';
if (app.isPackaged) {
const locations = [
path.join(process.resourcesPath, iconName),
path.join(process.resourcesPath, 'app.asar', 'assets', iconName),
path.join(__dirname, 'assets', iconName)
];
for (const loc of locations) {
if (fs.existsSync(loc)) {
return loc;
}
}
}
const devPath = path.join(__dirname, 'assets', iconName);
if (fs.existsSync(devPath)) {
return devPath;
}
// Fallback to regular icon if notification icon not found
return getIconPath();
}
// ============ UPDATE FUNCTIONS ============
async function checkForUpdates(silent = false) {
// 15-second hard timeout — raw https.get has no timeout and hangs indefinitely
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 15000);
try {
const resp = await fetch(`https://api.github.com/repos/${GITHUB_REPO}/releases/latest`, {
headers: { 'User-Agent': 'CoreMail-Desktop', 'Accept': 'application/vnd.github.v3+json' },
signal: controller.signal
});
clearTimeout(timer);
if (!resp.ok) throw new Error(`GitHub API HTTP ${resp.status}`);
const release = await resp.json();
const latestVersion = release.tag_name?.replace('v', '') || '';
const archSuffix = process.arch === 'arm64' ? 'arm64' : 'x86_64';
const appImageAsset = (release.assets || []).find(a =>
a.name?.toLowerCase().endsWith('.appimage') &&
a.name.toLowerCase().includes(archSuffix.toLowerCase()) &&
a.browser_download_url
);
const hasUpdate = compareVersions(latestVersion, APP_VERSION) > 0 && !!appImageAsset;
const downloadUrl = appImageAsset?.browser_download_url || null;
if (hasUpdate && !silent && mainWindow) {
mainWindow.webContents.send('update:available', { version: latestVersion, notes: release.body || '', downloadUrl });
}
return { success: true, currentVersion: APP_VERSION, latestVersion, hasUpdate, releaseNotes: release.body || '', downloadUrl, publishedAt: release.published_at };
} catch (e) {
clearTimeout(timer);
const msg = e.name === 'AbortError' ? 'Timeout — GitHub API nicht erreichbar (>15s)' : e.message;
return { success: false, error: msg, currentVersion: APP_VERSION };
}
}
function compareVersions(v1, v2) {
const parts1 = v1.split('.').map(Number);
const parts2 = v2.split('.').map(Number);
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const p1 = parts1[i] || 0;
const p2 = parts2[i] || 0;
if (p1 > p2) return 1;
if (p1 < p2) return -1;
}
return 0;
}
async function downloadUpdate(downloadUrl) {
const downloadDir = app.getPath('downloads');
const filename = 'CoreMail-Desktop-update.AppImage';
const filePath = path.join(downloadDir, filename);
// Remove existing partial download
try { if (fs.existsSync(filePath)) fs.unlinkSync(filePath); } catch (e) {}
// 10-minute hard timeout for the whole download (node-fetch follows redirects automatically)
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 10 * 60 * 1000);
let fileStream;
try {
const resp = await fetch(downloadUrl, {
headers: { 'User-Agent': 'CoreMail-Desktop', 'Accept': 'application/octet-stream' },
signal: controller.signal
// node-fetch v2 follows redirects automatically (default: redirect='follow')
});
if (!resp.ok) throw new Error(`HTTP-Fehler: ${resp.status}`);
const totalSize = parseInt(resp.headers.get('content-length') || '0', 10);
const hasValidSize = totalSize > 0;
let downloadedSize = 0;
fileStream = fs.createWriteStream(filePath);
// Stream body to file with progress reporting
await new Promise((resolve, reject) => {
resp.body.on('data', (chunk) => {
downloadedSize += chunk.length;
const progress = hasValidSize
? Math.round((downloadedSize / totalSize) * 100)
: Math.min(99, Math.round(downloadedSize / (1024 * 1024)));
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('update:progress', {
progress, downloaded: downloadedSize,
total: hasValidSize ? totalSize : downloadedSize, hasValidSize
});
}
});
resp.body.on('error', reject);
fileStream.on('error', reject);
fileStream.on('finish', resolve);
resp.body.pipe(fileStream);
});
clearTimeout(timer);
const stats = fs.statSync(filePath);
if (stats.size < 1024 * 1024) { // AppImage must be at least 1 MB
fs.unlinkSync(filePath);
throw new Error('Download unvollständig — Datei zu klein');
}
fs.chmodSync(filePath, 0o755);
console.log('[Update] Download abgeschlossen:', filePath, 'Grösse:', stats.size);
return { success: true, filePath, size: stats.size };
} catch (e) {
clearTimeout(timer);
try { fileStream?.close?.(); } catch {}
try { if (fs.existsSync(filePath)) fs.unlinkSync(filePath); } catch {}
const msg = e.name === 'AbortError' ? 'Download-Timeout (10 Minuten überschritten)' : e.message;
console.error('[Update] Download-Fehler:', msg);
return { success: false, error: msg };
}
}
// ============ NOTIFICATION FUNCTIONS ============
// v2.3.0: Updated to use notification icon with transparent background
function showNotification(title, body, onClick = null) {
if (!Notification.isSupported()) {
console.log('Notifications not supported');
return;
}
const notification = new Notification({
title,
body,
icon: getNotificationIconPath(),
silent: store.get('appSettings.notificationSound', true) === false
});
if (onClick) {
notification.on('click', onClick);
}
notification.show();
return notification;
}
function updateBadgeCount(count) {
if (process.platform === 'linux') {
// Linux uses Unity/GNOME launcher API
if (app.setBadgeCount) {
app.setBadgeCount(count);
}
}
}
// ============ OLLAMA INSTALLATION (v1.6.0) ============
// Check if Ollama is installed
function isOllamaInstalled() {
try {
execSync('which ollama', { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
// Check if Ollama is running
async function isOllamaRunning() {
return new Promise((resolve) => {
http.get('http://localhost:11434/api/tags', { timeout: 2000 }, (res) => {
resolve(res.statusCode === 200);
}).on('error', () => resolve(false));
});
}
// Install Ollama
async function installOllama(progressCallback) {
return new Promise((resolve, reject) => {
progressCallback({ step: 'checking', message: 'Prüfe Systemvoraussetzungen...' });
// Check if curl is available
try {
execSync('which curl', { stdio: 'ignore' });
} catch {
reject(new Error('curl ist nicht installiert. Bitte installiere curl zuerst.'));
return;
}
progressCallback({ step: 'downloading', message: 'Lade Ollama herunter...' });
// Download and install Ollama
const installProcess = spawn('sh', ['-c', 'curl -fsSL https://ollama.com/install.sh | sh'], {
stdio: ['ignore', 'pipe', 'pipe']
});
let output = '';
let errorOutput = '';
installProcess.stdout.on('data', (data) => {
output += data.toString();
progressCallback({ step: 'installing', message: 'Installiere Ollama...', detail: data.toString().trim() });
});
installProcess.stderr.on('data', (data) => {
errorOutput += data.toString();
});
installProcess.on('close', (code) => {
if (code === 0 && isOllamaInstalled()) {
progressCallback({ step: 'installed', message: 'Ollama erfolgreich installiert!' });
resolve({ success: true });
} else {
reject(new Error(errorOutput || 'Installation fehlgeschlagen. Code: ' + code));
}
});
installProcess.on('error', (err) => {
reject(new Error('Installation konnte nicht gestartet werden: ' + err.message));
});
});
}
// Start Ollama service
async function startOllamaService(progressCallback) {
progressCallback({ step: 'starting', message: 'Starte Ollama-Dienst...' });
return new Promise((resolve, reject) => {
// First try systemctl
try {
execSync('systemctl --user start ollama 2>/dev/null || true', { stdio: 'ignore' });
} catch {
// Ignore systemctl errors
}
// Wait a moment for systemctl
setTimeout(async () => {
if (await isOllamaRunning()) {
resolve({ success: true });
return;
}
// Fallback: start ollama serve in background
const ollamaProcess = spawn('ollama', ['serve'], {
detached: true,
stdio: 'ignore'
});
ollamaProcess.unref();
// Wait for service to start
let attempts = 0;
const checkInterval = setInterval(async () => {
attempts++;
try {
if (await isOllamaRunning()) {
clearInterval(checkInterval);
progressCallback({ step: 'running', message: 'Ollama-Dienst läuft!' });
resolve({ success: true });
} else if (attempts > 15) {
clearInterval(checkInterval);
reject(new Error('Ollama-Dienst konnte nicht gestartet werden. Versuche: ollama serve'));
}
} catch (err) {
clearInterval(checkInterval);
reject(err);
}
}, 1000);
}, 1000);
});
}
// Download the default model
async function downloadOllamaModel(modelName, progressCallback) {
progressCallback({ step: 'model_download', message: `Lade KI-Modell "${modelName}" herunter...`, progress: 0 });
return new Promise((resolve, reject) => {
const pullProcess = spawn('ollama', ['pull', modelName], {
stdio: ['ignore', 'pipe', 'pipe']
});
pullProcess.stdout.on('data', (data) => {
const output = data.toString();
// Try to parse progress from output
const match = output.match(/(\d+)%/);
if (match) {
progressCallback({
step: 'model_download',
message: `Lade KI-Modell "${modelName}" herunter...`,
progress: parseInt(match[1]),
detail: output.trim()
});
}
});
pullProcess.stderr.on('data', (data) => {
const output = data.toString();
if (output.includes('pulling')) {
progressCallback({ step: 'model_download', message: 'Lade Modelldateien...', detail: output.trim() });
}
});
pullProcess.on('close', (code) => {
if (code === 0) {
progressCallback({ step: 'model_ready', message: `Modell "${modelName}" bereit!`, progress: 100 });
resolve({ success: true });
} else {
reject(new Error('Modell konnte nicht heruntergeladen werden.'));
}
});
pullProcess.on('error', (err) => {
reject(new Error('Modell-Download fehlgeschlagen: ' + err.message));
});
});
}
// ============ IPC HANDLERS ============
// === THEME ICON MANAGEMENT (v2.2.0) ===
const THEME_ICONS = {
dark: 'dark.png',
light: 'light.png',
minimal: 'minimal.png',
morphismus: 'morphismus.png',
glas: 'glas.png',
retro: 'retro.png',
foundations: 'foundations.png',
nerd: 'dark.png',
colorful: 'dark.png',
indie: 'dark.png'
};
// v2.3.0: Fixed icon path resolution for packaged apps
function getIconPathForTheme(themeName) {
const iconFile = THEME_ICONS[themeName] || THEME_ICONS['dark'];
if (app.isPackaged) {
// In packaged app, icons are in resources/build/icons/themes/
const resourcePath = path.join(process.resourcesPath, 'app.asar', 'build', 'icons', 'themes', iconFile);
if (fs.existsSync(resourcePath)) {
return resourcePath;
}
// Fallback: try without asar
const fallbackPath = path.join(process.resourcesPath, 'build', 'icons', 'themes', iconFile);
if (fs.existsSync(fallbackPath)) {
return fallbackPath;
}
// Last fallback: try __dirname (unpacked)
return path.join(__dirname, 'build', 'icons', 'themes', iconFile);
} else {
// Development mode
return path.join(__dirname, 'public', 'icons', 'themes', iconFile);
}
}
function updateWindowIcon(themeName) {
if (!mainWindow) return false;
const iconPath = getIconPathForTheme(themeName);
try {
// Use nativeImage.createFromPath to safely load icon (supports asar paths)
const icon = nativeImage.createFromPath(iconPath);
if (icon.isEmpty()) {
console.warn(`[Theme] Icon is empty or not found: ${iconPath}`);
return false;
}
mainWindow.setIcon(icon);
console.log(`[Theme] Icon updated to: ${themeName}`);
return true;
} catch (error) {
console.error(`[Theme] Failed to set icon: ${error.message}`);
return false;
}
}
ipcMain.handle('theme:setIcon', async (event, themeName) => {
try {
const success = updateWindowIcon(themeName);
return { success, theme: themeName };
} catch (error) {
console.error('[Theme] IPC handler error:', error.message);
return { success: false, error: error.message };
}
});
ipcMain.handle('theme:getAvailableIcons', async () => {
return Object.keys(THEME_ICONS);
});
// === APP INFO ===
ipcMain.handle('app:getVersion', () => APP_VERSION);
ipcMain.handle('app:openExternal', async (event, url) => {
if (url && (url.startsWith('https://') || url.startsWith('http://') || url.startsWith('mailto:'))) {
await shell.openExternal(url);
}
});
ipcMain.handle('app:openDevTools', () => {
if (mainWindow) mainWindow.webContents.openDevTools();
});
ipcMain.handle('app:getSettings', () => {
return store.get('appSettings', {
autoCheckUpdates: true,
notificationsEnabled: true,
notificationSound: true,
downloadPath: app.getPath('downloads')
});
});
ipcMain.handle('app:saveSettings', async (event, settings) => {
store.set('appSettings', settings);
return { success: true };
});
// === UPDATE ===
ipcMain.handle('update:check', async () => {
return await checkForUpdates(false);
});
ipcMain.handle('update:download', async (event, downloadUrl) => {
try {
const result = await downloadUpdate(downloadUrl);
return result;
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle('update:install', async (event, filePath) => {
try {
// Verify file exists