-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmain.js
More file actions
1763 lines (1551 loc) · 51.1 KB
/
main.js
File metadata and controls
1763 lines (1551 loc) · 51.1 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, globalShortcut, Notification, powerSaveBlocker, dialog, shell } = require('electron/main');
const path = require('node:path');
const {ipcMain} = require('electron')
const http = require('http');
const https = require('https');
const xml = require("xml2js");
const net = require('net');
const WebSocket = require('ws');
const fs = require('fs');
const forge = require('node-forge');
const httpolyglot = require('httpolyglot');
// In some cases we need to make the WLgate window resizable (for example for tiling window managers)
// Default: false
const resizable = process.env.WLGATE_RESIZABLE === 'true' || false;
const sleepable = process.env.WLGATE_SLEEP === 'true' || false;
const gotTheLock = app.requestSingleInstanceLock();
let powerSaveBlockerId;
let s_mainWindow;
let certInstallWindow;
let pendingCertInstall = false; // Track if cert install needs to be shown
let msgbacklog=[];
let qsyServer; // Dual-mode HTTP/HTTPS server for QSY
let currentCAT=null;
var WServer;
let wsServer;
let wsClients = new Set();
let wssServer; // Secure WebSocket server
let wssClients = new Set(); // Secure WebSocket clients
let wssHttpsServer; // HTTPS server for secure WebSocket
let isShuttingDown = false;
let activeConnections = new Set(); // Track active TCP connections
let activeHttpRequests = new Set(); // Track active HTTP requests for cancellation
// Certificate paths for HTTPS server
let certPaths = {
key: null,
cert: null
};
const DemoAdif='<call:5>DJ7NT <gridsquare:4>JO30 <mode:3>FT8 <rst_sent:3>-15 <rst_rcvd:2>33 <qso_date:8>20240110 <time_on:6>051855 <qso_date_off:8>20240110 <time_off:6>051855 <band:3>40m <freq:8>7.155783 <station_callsign:5>TE1ST <my_gridsquare:6>JO30OO <eor>';
if (require('electron-squirrel-startup')) app.quit();
const udp = require('dgram');
let q={};
let defaultcfg = {
wavelog_url: "https://log.jo30.de/index.php",
wavelog_key: "mykey",
wavelog_id: "0",
wavelog_radioname: 'WLGate',
wavelog_pmode: true,
flrig_host: '127.0.0.1',
flrig_port: '12345',
flrig_ena: false,
hamlib_host: '127.0.0.1',
hamlib_port: '4532',
hamlib_ena: false,
ignore_pwr: false,
}
const storage = require('electron-json-storage');
// =============================================================================
// Simple Update Checker
// =============================================================================
// Get repository info from package.json
function getRepoInfo() {
try {
const pkg = require('./package.json');
if (pkg.repository && pkg.repository.url) {
const match = pkg.repository.url.match(/github\.com[/:]([^/]+)\/([^/]+)/);
if (match) {
return { owner: match[1], repo: match[2].replace('.git', '') };
}
}
} catch (e) {
console.log('Could not read repository info:', e.message);
}
// Fallback to defaults
return { owner: 'wavelog', repo: 'WaveLogGate' };
}
// Compare two version strings (returns true if v2 > v1)
function isNewerVersion(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 (p2 > p1) return true;
if (p2 < p1) return false;
}
return false;
}
// Check for updates via GitHub API
function checkForUpdates() {
if (!app.isPackaged) {
console.log('Skipping update check (development mode)');
return;
}
const repoInfo = getRepoInfo();
const currentVersion = app.getVersion();
console.log(`Checking for updates (current: ${currentVersion})...`);
const options = {
hostname: 'api.github.com',
path: `/repos/${repoInfo.owner}/${repoInfo.repo}/releases/latest`,
headers: {
'User-Agent': 'WaveLogGate'
}
};
https.get(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const release = JSON.parse(data);
const latestVersion = release.tag_name.replace(/^v/, '');
console.log(`Latest version: ${latestVersion}`);
if (isNewerVersion(currentVersion, latestVersion)) {
console.log(`Update available: ${latestVersion}`);
showUpdateNotification(latestVersion, release.html_url);
} else {
console.log('Already up to date');
}
} catch (e) {
console.error('Error parsing release info:', e.message);
}
});
}).on('error', (err) => {
console.error('Error checking for updates:', err.message);
});
}
// Show notification about available update
function showUpdateNotification(version, releaseUrl) {
// On Windows, use dialog because notification clicks don't work reliably
if (process.platform === 'win32') {
dialog.showMessageBox({
type: 'info',
title: 'WaveLogGate Update Available',
message: `A new version is available!`,
detail: `Version ${version} is ready to download. You are currently running v${app.getVersion()}.`,
buttons: ['Go to Download', 'Later'],
defaultId: 0,
cancelId: 1
}).then(result => {
if (result.response === 0) {
console.log('Opening download page:', releaseUrl);
shell.openExternal(releaseUrl);
}
});
return;
}
// On macOS/Linux, use native notification (click works on macOS)
if (Notification.isSupported()) {
const notification = new Notification({
title: 'WaveLogGate Update Available',
body: `Version ${version} is available. Click to download.`,
icon: path.join(__dirname, 'icon.png'),
silent: false
});
notification.once('click', () => {
console.log('Notification clicked, opening:', releaseUrl);
shell.openExternal(releaseUrl);
});
notification.show();
} else {
// Fallback: log to console
console.log(`Update available: ${version} - Download from: ${releaseUrl}`);
}
}
app.disableHardwareAcceleration();
function createWindow () {
const mainWindow = new BrowserWindow({
width: 430,
height: 250,
resizable: resizable, // Default: false, can be overwritten with WLGATE_RESIZABLE
autoHideMenuBar: app.isPackaged,
webPreferences: {
contextIsolation: false,
backgroundThrottling: false,
nodeIntegration: true,
devTools: !app.isPackaged,
enableRemoteModule: true,
preload: path.join(__dirname, 'preload.js')
}
});
if (app.isPackaged) {
mainWindow.setMenu(null);
}
mainWindow.loadFile('index.html')
mainWindow.setTitle(require('./package.json').name + " V" + require('./package.json').version);
return mainWindow;
}
ipcMain.on("set_config", async (event,arg) => {
defaultcfg=arg;
storage.set('basic', defaultcfg, function(e) {
if (e) throw e;
});
event.returnValue=defaultcfg;
});
ipcMain.on("resize", async (event,arg) => {
const newsize=arg;
s_mainWindow.setContentSize(newsize.width,newsize.height,newsize.ani);
s_mainWindow.setSize(newsize.width,newsize.height,newsize.ani);
event.returnValue=true;
});
ipcMain.on("get_config", async (event, arg) => {
let storedcfg = storage.getSync('basic');
let realcfg={};
if (!(storedcfg.wavelog_url) && !(storedcfg.profiles)) { storedcfg=defaultcfg; } // Old config not present, add default-cfg
if (!(storedcfg.profiles)) { // Old Config without array? Convert it
(realcfg.profiles = realcfg.profiles || []).push(storedcfg);
realcfg.profiles.push(defaultcfg);
realcfg.profile=(storedcfg.profile ?? 0);
} else {
realcfg=storedcfg;
}
// Migration: Add version and profileNames for dynamic profile system
if (!realcfg.version || realcfg.version < 2) {
realcfg.version = 2;
if (!realcfg.profileNames) {
realcfg.profileNames = realcfg.profiles.map((_, i) => `Profile ${i + 1}`);
}
storage.set('basic', realcfg, function(e) {
if (e) throw e;
});
}
if ((arg ?? '') !== '') {
realcfg.profile=arg;
}
defaultcfg=realcfg;
storage.set('basic', realcfg, function(e) { // Store one time
if (e) throw e;
});
event.returnValue = realcfg;
});
ipcMain.on("setCAT", async (event,arg) => {
settrx(arg);
event.returnValue=true;
});
ipcMain.on("quit", async (event,arg) => {
console.log('Quit requested from renderer');
shutdownApplication();
app.quit();
event.returnValue=true;
});
ipcMain.on("radio_status_update", async (event,arg) => {
// Broadcast radio status updates from renderer to WebSocket clients
broadcastRadioStatus(arg);
event.returnValue=true;
});
ipcMain.on("get_ca_cert", async (event) => {
// Return the CA certificate for display/installation
const caCert = getCaCertificate();
event.returnValue = caCert;
});
ipcMain.on("install_ca_cert", async (event) => {
// Attempt to install the CA certificate
const result = await installCertificate();
event.returnValue = result;
});
ipcMain.on("get_cert_info", async (event) => {
// Return certificate installation info for the UI
const userDataPath = app.getPath('userData');
const certPath = path.join(userDataPath, 'certs', 'server.crt');
event.returnValue = {
certPath: certPath,
platform: process.platform,
hasCert: fs.existsSync(certPath)
};
});
ipcMain.on("close_cert_install_window", async () => {
if (certInstallWindow && !certInstallWindow.isDestroyed()) {
certInstallWindow.close();
}
});
ipcMain.on("check_for_updates", async (event) => {
// Manual update check triggered from renderer
checkForUpdates();
event.returnValue = true;
});
// Dynamic Profile System IPC Handlers
ipcMain.on("create_profile", async (event, name) => {
let data = storage.getSync('basic');
const newProfile = {
wavelog_url: data.profiles[data.profile || 0].wavelog_url || '',
wavelog_key: data.profiles[data.profile || 0].wavelog_key || '',
wavelog_id: data.profiles[data.profile || 0].wavelog_id || '0',
wavelog_radioname: 'WLGate',
wavelog_pmode: true,
flrig_host: '127.0.0.1',
flrig_port: '12345',
flrig_ena: false,
hamlib_host: '127.0.0.1',
hamlib_port: '4532',
hamlib_ena: false,
ignore_pwr: false
};
data.profiles.push(newProfile);
data.profileNames.push(name || `Profile ${data.profiles.length}`);
storage.setSync('basic', data);
event.returnValue = { success: true, index: data.profiles.length - 1 };
});
ipcMain.on("delete_profile", async (event, index) => {
let data = storage.getSync('basic');
// Prevent deleting if only 2 profiles remain
if (data.profiles.length <= 2) {
event.returnValue = { success: false, error: 'Minimum 2 profiles required' };
return;
}
// Prevent deleting active profile
if ((data.profile || 0) === index) {
event.returnValue = { success: false, error: 'Cannot delete active profile' };
return;
}
data.profiles.splice(index, 1);
data.profileNames.splice(index, 1);
// Adjust active index if needed
if ((data.profile || 0) > index) {
data.profile = (data.profile || 0) - 1;
}
storage.setSync('basic', data);
event.returnValue = { success: true };
});
ipcMain.on("rename_profile", async (event, index, newName) => {
let data = storage.getSync('basic');
data.profileNames[index] = newName;
storage.setSync('basic', data);
event.returnValue = { success: true };
});
ipcMain.on("switch_profile", async (event, index) => {
let data = storage.getSync('basic');
data.profile = index;
storage.setSync('basic', data);
event.returnValue = { success: true };
});
function cleanupConnections() {
console.log('Cleaning up active TCP connections...');
// Close all tracked TCP connections
activeConnections.forEach(connection => {
try {
if (connection && !connection.destroyed) {
connection.destroy();
console.log('Closed TCP connection');
}
} catch (error) {
console.error('Error closing TCP connection:', error);
}
});
// Clear the connections set
activeConnections.clear();
console.log('All TCP connections cleaned up');
// Abort all in-flight HTTP requests
activeHttpRequests.forEach(request => {
try {
request.abort();
console.log('Aborted HTTP request');
} catch (error) {
console.error('Error aborting HTTP request:', error);
}
});
// Clear the HTTP requests set
activeHttpRequests.clear();
console.log('All HTTP requests aborted');
}
function shutdownApplication() {
if (isShuttingDown) {
console.log('Shutdown already in progress, ignoring duplicate request');
return;
}
isShuttingDown = true;
console.log('Initiating application shutdown...');
try {
// Signal renderer to clear timers and connections
if (s_mainWindow && !s_mainWindow.isDestroyed()) {
console.log('Sending cleanup signal to renderer...');
s_mainWindow.webContents.send('cleanup');
}
// Clean up TCP connections
cleanupConnections();
// Close all servers
if (WServer) {
console.log('Closing UDP server...');
try {
WServer.close();
} catch (e) {
console.error('Error closing UDP server:', e);
}
WServer = null;
}
if (qsyServer) {
console.log('Closing QSY server...');
try {
qsyServer.close();
} catch (e) {
console.error('Error closing QSY server:', e);
}
qsyServer = null;
}
if (wsServer) {
console.log('Closing WebSocket server and clients...');
// Close all WebSocket client connections with explicit termination
wsClients.forEach(client => {
try {
if (client.readyState === WebSocket.OPEN || client.readyState === WebSocket.CONNECTING) {
client.close(1001, 'Server shutting down');
}
} catch (e) {
// Client may already be closed, try terminate
try {
client.terminate();
} catch (terminateError) {
// Ignore, client is gone
}
}
});
wsClients.clear();
try {
wsServer.close();
} catch (e) {
console.error('Error closing WebSocket server:', e);
}
// wsServer will be set to null by the 'close' event handler
}
if (wssServer) {
console.log('Closing Secure WebSocket server and clients...');
// Close all Secure WebSocket client connections with explicit termination
wssClients.forEach(client => {
try {
if (client.readyState === WebSocket.OPEN || client.readyState === WebSocket.CONNECTING) {
client.close(1001, 'Server shutting down');
}
} catch (e) {
// Client may already be closed, try terminate
try {
client.terminate();
} catch (terminateError) {
// Ignore, client is gone
}
}
});
wssClients.clear();
try {
wssServer.close();
} catch (e) {
console.error('Error closing Secure WebSocket server:', e);
}
// wssServer will be set to null by the 'close' event handler
}
if (wssHttpsServer) {
console.log('Closing HTTPS server...');
try {
wssHttpsServer.close();
} catch (e) {
console.error('Error closing HTTPS server:', e);
}
// wssHttpsServer will be set to null by the 'close' event handler
}
} catch (error) {
console.error('Error during server shutdown:', error);
}
}
function show_noti(arg) {
if (Notification.isSupported()) {
try {
const notification = new Notification({
title: 'Wavelog',
body: arg
});
notification.show();
} catch(e) {
console.log("No notification possible on this system / ignoring");
}
} else {
console.log("Notifications are not supported on this platform");
}
}
ipcMain.on("test", async (event,arg) => {
let result={};
let plain;
try {
plain=await send2wavelog(arg,DemoAdif, true);
} catch (e) {
plain=e;
console.log(plain);
} finally {
try {
result.payload=JSON.parse(plain.resString);
} catch (ee) {
result.payload=plain.resString;
} finally {
result.statusCode=plain.statusCode;
event.returnValue=result;
}
}
});
app.on('before-quit', () => {
console.log('before-quit event triggered');
shutdownApplication();
});
process.on('SIGINT', () => {
console.log('SIGINT received, initiating shutdown...');
shutdownApplication();
process.exit(0);
});
app.on('will-quit', () => {
try {
if (!sleepable && powerSaveBlockerId !== undefined) {
powerSaveBlocker.stop(powerSaveBlockerId);
}
} catch(e) {
console.log(e);
}
});
if (!gotTheLock) {
// Another instance is running - signal it to quit and relaunch
console.log('Another instance is running, requesting it to quit...');
// Wait for the old instance to quit, then relaunch
setTimeout(() => {
app.relaunch();
app.exit(0);
}, 1000);
} else {
// Handle second instance trying to start - quit to let new instance take over
app.on('second-instance', (event, commandLine, workingDirectory) => {
console.log('Second instance detected, quitting to let new instance take over...');
app.quit();
});
startserver();
app.whenReady().then(() => {
if (!sleepable) {
powerSaveBlockerId = powerSaveBlocker.start('prevent-app-suspension');
}
s_mainWindow=createWindow();
globalShortcut.register('Control+Shift+I', () => { return false; });
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
});
s_mainWindow.webContents.once('dom-ready', function() {
if (msgbacklog.length>0) {
s_mainWindow.webContents.send('updateMsg',msgbacklog.pop());
}
// Check for updates on startup
checkForUpdates();
});
// Show certificate install window if it was pending (before main window was ready)
if (pendingCertInstall) {
// Small delay to ensure main window is fully visible
setTimeout(() => {
showCertInstallWindow();
}, 500);
}
});
}
app.on('window-all-closed', function () {
console.log('All windows closed, initiating shutdown...');
if (!isShuttingDown) {
shutdownApplication();
}
if (process.platform !== 'darwin') app.quit();
else app.quit();
})
function normalizeTxPwr(adifdata) {
return adifdata.replace(/<TX_PWR:(\d+)>([^<]+)/gi, (match, length, value) => {
const cleanValue = value.trim().toLowerCase();
const numMatch = cleanValue.match(/^(\d+(?:\.\d+)?)/);
if (!numMatch) return match; // not a valid number, return original match
let watts = parseFloat(numMatch[1]);
// get the unit if present
if (cleanValue.includes('kw')) {
watts *= 1000;
} else if (cleanValue.includes('mw')) {
watts *= 0.001;
}
// if it's just 'w' we assume it's already in watts
// would be equal to
// } else if (cleanValue.includes('w')) {
// watts *= 1;
// }
// get the new length and return the new TX_PWR tag
const newValue = watts.toString();
return `<TX_PWR:${newValue.length}>${newValue}`;
});
}
function normalizeKIndex(adifdata) {
return adifdata.replace(/<K_INDEX:(\d+)>([^<]+)/gi, (match, length, value) => {
const numValue = parseFloat(value.trim());
if (isNaN(numValue)) return ''; // Remove if not a number
// Round to nearest integer and clamp to 0-9 range
let kIndex = Math.round(numValue);
if (kIndex < 0) kIndex = 0;
if (kIndex > 9) kIndex = 9;
return `<K_INDEX:${kIndex.toString().length}>${kIndex}`;
});
}
function manipulateAdifData(adifdata) {
adifdata = normalizeTxPwr(adifdata);
adifdata = normalizeKIndex(adifdata);
// add more manipulation if necessary here
// ...
return adifdata;
}
function parseADIF(adifdata) {
const { ADIF } = require("tcadif");
const normalizedData = manipulateAdifData(adifdata);
const adiReader = ADIF.parse(normalizedData);
return adiReader.toObject();
}
function writeADIF(adifObject) {
const { ADIF } = require("tcadif");
const adiWriter = new ADIF(adifObject);
return adiWriter;
}
function freqToBand(freq_mz) {
const f = parseFloat(freq_mz);
if (isNaN(f)) return null;
const bandMap = require('tcadif/lib/enums/Band');
for (const [band, { lowerFreq, upperFreq }] of Object.entries(bandMap))
if (f >= parseFloat(lowerFreq) && f <= parseFloat(upperFreq))
return band;
return null;
}
function send2wavelog(o_cfg,adif, dryrun = false) {
let clpayload={};
clpayload.key=o_cfg.wavelog_key.trim();
clpayload.station_profile_id=o_cfg.wavelog_id.trim();
clpayload.type='adif';
clpayload.string=adif;
const postData=JSON.stringify(clpayload);
let httpmod='http';
if (o_cfg.wavelog_url.toLowerCase().startsWith('https')) {
httpmod='https';
}
const https = require(httpmod);
const options = {
method: 'POST',
timeout: 5000,
rejectUnauthorized: false,
headers: {
'Content-Type': 'application/json',
'User-Agent': 'SW2WL_v' + app.getVersion(),
'Content-Length': postData.length
}
};
return new Promise((resolve, reject) => {
let rej=false;
let result={};
let url=o_cfg.wavelog_url + '/api/qso';
if (dryrun) { url+='/true'; }
const req = https.request(url,options, (res) => {
result.statusCode=res.statusCode;
if (res.statusCode < 200 || res.statusCode > 299) {
rej=true;
}
const body = [];
res.on('data', (chunk) => body.push(chunk));
res.on('end', () => {
// Remove request from tracking when completed
activeHttpRequests.delete(req);
let resString = Buffer.concat(body).toString();
if (rej) {
if (resString.indexOf('html>')>0) {
resString='{"status":"failed","reason":"wrong URL"}';
}
result.resString=resString;
reject(result);
} else {
result.resString=resString;
resolve(result);
}
})
})
req.on('error', (err) => {
// Remove request from tracking on error
activeHttpRequests.delete(req);
rej=true;
req.destroy();
result.resString='{"status":"failed","reason":"internet problem"}';
reject(result);
})
req.on('timeout', (err) => {
// Remove request from tracking on timeout
activeHttpRequests.delete(req);
rej=true;
req.destroy();
result.resString='{"status":"failed","reason":"timeout"}';
reject(result);
})
// Track the HTTP request for cleanup
activeHttpRequests.add(req);
req.write(postData);
req.end();
});
}
const ports = [2333]; // Liste der Ports, an die Sie binden möchten
ports.forEach(port => {
WServer = udp.createSocket('udp4');
WServer.on('error', function(err) {
tomsg('Some other Tool blocks Port '+port+'. Stop it, and restart this');
});
WServer.on('message',async function(msg,info){
let parsedXML={};
let adobject={};
if (msg.toString().includes("xml")) { // detect if incoming String is XML
try {
xml.parseString(msg.toString(), function (err,dat) {
parsedXML=dat;
});
let qsodatum = new Date(Date.parse(parsedXML.contactinfo.timestamp[0]+"Z")); // Added Z to make it UTC
const qsodat=fmt(qsodatum);
if (parsedXML.contactinfo.mode[0] == 'USB' || parsedXML.contactinfo.mode[0] == 'LSB') { // TCADIF lib is not capable of using USB/LSB
parsedXML.contactinfo.mode[0]='SSB';
}
adobject = { qsos: [
{
CALL: parsedXML.contactinfo.call[0],
MODE: parsedXML.contactinfo.mode[0],
QSO_DATE_OFF: qsodat.d,
QSO_DATE: qsodat.d,
TIME_OFF: qsodat.t,
TIME_ON: qsodat.t,
RST_RCVD: parsedXML.contactinfo.rcv[0],
RST_SENT: parsedXML.contactinfo.snt[0],
FREQ: ((1*parseInt(parsedXML.contactinfo.txfreq[0]))/100000).toString(),
FREQ_RX: ((1*parseInt(parsedXML.contactinfo.rxfreq[0]))/100000).toString(),
OPERATOR: parsedXML.contactinfo.operator[0],
COMMENT: parsedXML.contactinfo.comment[0],
POWER: parsedXML.contactinfo.power[0],
STX: parsedXML.contactinfo.sntnr[0],
RTX: parsedXML.contactinfo.rcvnr[0],
MYCALL: parsedXML.contactinfo.mycall[0],
GRIDSQUARE: parsedXML.contactinfo.gridsquare[0],
STATION_CALLSIGN: parsedXML.contactinfo.mycall[0]
} ]};
let band = freqToBand(adobject.qsos[0].FREQ);
if (band) adobject.qsos[0].BAND = band;
} catch (e) {}
} else {
try {
adobject=parseADIF(msg.toString());
} catch(e) {
tomsg('<div class="alert alert-danger" role="alert">Received broken ADIF</div>');
return;
}
}
let plainret='';
if (adobject.qsos.length>0) {
let x={};
try {
const outadif=writeADIF(adobject);
plainret=await send2wavelog(defaultcfg.profiles[defaultcfg.profile ?? 0],outadif.stringify());
x.state=plainret.statusCode;
x.payload = JSON.parse(plainret.resString);
} catch(e) {
try {
x.payload=JSON.parse(e.resString);
} catch (ee) {
x.state=e.statusCode;
x.payload={};
x.payload.string=e.resString;
x.payload.status='bug';
} finally {
x.payload.status='bug';
}
}
if (x.payload.status == 'created') {
adobject.created=true;
show_noti("QSO added: "+adobject.qsos[0].CALL);
} else {
adobject.created=false;
console.log(x);
adobject.fail=x;
if (x.payload.messages) {
adobject.fail.payload.reason=x.payload.messages.join();
}
show_noti("QSO NOT added: "+adobject.qsos[0].CALL);
}
s_mainWindow.webContents.send('updateTX', adobject);
tomsg('');
} else {
tomsg('<div class="alert alert-danger" role="alert">No ADIF detected. WSJT-X: Use ONLY Secondary UDP-Server</div>');
}
});
WServer.bind(port);
});
function tomsg(msg) {
try {
s_mainWindow.webContents.send('updateMsg',msg);
} catch(e) {
msgbacklog.push(msg);
}
}
// Generate or load self-signed certificate for HTTPS server
function setupCertificates() {
const userDataPath = app.getPath('userData');
const certDir = path.join(userDataPath, 'certs');
// Check if certificates already exist
const keyPath = path.join(certDir, 'server.key');
const certPath = path.join(certDir, 'server.crt');
if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {
// Load existing certificates
certPaths = {
key: fs.readFileSync(keyPath),
cert: fs.readFileSync(certPath)
};
console.log('Using existing SSL certificates');
return { success: true, newlyGenerated: false };
}
// Generate new certificates
try {
// Create cert directory if it doesn't exist
if (!fs.existsSync(certDir)) {
fs.mkdirSync(certDir, { recursive: true });
}
// Generate RSA key pair
const keys = forge.pki.rsa.generateKeyPair(2048);
// Create certificate
const cert = forge.pki.createCertificate();
cert.publicKey = keys.publicKey;
cert.serialNumber = '01';
cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date();
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 10); // 10 years
// Set subject and issuer (self-signed)
const attrs = [{
name: 'commonName',
value: '127.0.0.1'
}];
cert.setSubject(attrs);
cert.setIssuer(attrs);
// Add extensions including SANs
cert.setExtensions([{
name: 'basicConstraints',
cA: false
}, {
name: 'keyUsage',
digitalSignature: true,
keyEncipherment: true
}, {
name: 'extKeyUsage',
serverAuth: true,
clientAuth: true
}, {
name: 'subjectAltName',
altNames: [{
type: 7, // IP address
ip: '127.0.0.1'
}, {
type: 2, // DNS name
value: 'localhost'
}, {
type: 7, // IPv6 address
ip: '::1'
}]
}]);
// Self-sign the certificate
cert.sign(keys.privateKey, forge.md.sha256.create());
// Convert to PEM format
const certPem = forge.pki.certificateToPem(cert);
const keyPem = forge.pki.privateKeyToPem(keys.privateKey);
// Save certificates
fs.writeFileSync(keyPath, keyPem);
fs.writeFileSync(certPath, certPem);
certPaths = {
key: keyPem,
cert: certPem
};
console.log('Generated new SSL certificates');
return { success: true, newlyGenerated: true };
} catch (error) {
console.error('Failed to generate certificates:', error);
tomsg('Warning: Failed to generate SSL certificates. HTTPS server will not be available.');
return { success: false, newlyGenerated: false };
}
}
// Get certificate for user installation
function getCaCertificate() {
const userDataPath = app.getPath('userData');
const certPath = path.join(userDataPath, 'certs', 'server.crt');
if (fs.existsSync(certPath)) {