forked from accius/openhamclock
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
6500 lines (5681 loc) · 227 KB
/
server.js
File metadata and controls
6500 lines (5681 loc) · 227 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
/**
* OpenHamClock Server
*
* Express server that:
* 1. Serves the static web application
* 2. Proxies API requests to avoid CORS issues
* 3. Provides hybrid HF propagation predictions (ITURHFProp + real-time ionosonde)
* 4. Provides WebSocket support for future real-time features
*
* Configuration:
* - Copy .env.example to .env and customize
* - Environment variables override .env file
*
* Usage:
* node server.js
* PORT=8080 node server.js
*/
const express = require('express');
const cors = require('cors');
const compression = require('compression');
const path = require('path');
const fetch = require('node-fetch');
const net = require('net');
const dgram = require('dgram');
const fs = require('fs');
const { execFile, spawn } = require('child_process');
// Read version from package.json as single source of truth
const APP_VERSION = (() => {
try {
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
return pkg.version || '0.0.0';
} catch { return '0.0.0'; }
})();
// Auto-create .env from .env.example on first run
const envPath = path.join(__dirname, '.env');
const envExamplePath = path.join(__dirname, '.env.example');
if (!fs.existsSync(envPath) && fs.existsSync(envExamplePath)) {
fs.copyFileSync(envExamplePath, envPath);
console.log('[Config] Created .env from .env.example');
console.log('[Config] ⚠️ Please edit .env with your callsign and locator, then restart');
}
// Load .env file if it exists
if (fs.existsSync(envPath)) {
const envContent = fs.readFileSync(envPath, 'utf8');
envContent.split('\n').forEach(line => {
const trimmed = line.trim();
if (trimmed && !trimmed.startsWith('#')) {
const [key, ...valueParts] = trimmed.split('=');
const value = valueParts.join('=');
if (key && value !== undefined && !process.env[key]) {
process.env[key] = value;
}
}
});
console.log('[Config] Loaded configuration from .env file');
}
const app = express();
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0';
// ============================================
// CONFIGURATION FROM ENVIRONMENT
// ============================================
// Convert Maidenhead grid locator to lat/lon
function gridToLatLon(grid) {
if (!grid || grid.length < 4) return null;
grid = grid.toUpperCase();
const lon = (grid.charCodeAt(0) - 65) * 20 - 180;
const lat = (grid.charCodeAt(1) - 65) * 10 - 90;
const lon2 = parseInt(grid[2]) * 2;
const lat2 = parseInt(grid[3]);
let longitude = lon + lon2 + 1; // Center of grid
let latitude = lat + lat2 + 0.5;
// 6-character grid for more precision
if (grid.length >= 6) {
const lon3 = (grid.charCodeAt(4) - 65) * (2/24);
const lat3 = (grid.charCodeAt(5) - 65) * (1/24);
longitude = lon + lon2 + lon3 + (1/24);
latitude = lat + lat2 + lat3 + (0.5/24);
}
return { latitude, longitude };
}
// Get locator from env (support both LOCATOR and GRID_SQUARE)
const locator = process.env.LOCATOR || process.env.GRID_SQUARE || '';
// Also load config.json if it exists (for user preferences)
let jsonConfig = {};
const configJsonPath = path.join(__dirname, 'config.json');
if (fs.existsSync(configJsonPath)) {
try {
jsonConfig = JSON.parse(fs.readFileSync(configJsonPath, 'utf8'));
console.log('[Config] Loaded user preferences from config.json');
} catch (e) {
console.error('[Config] Error parsing config.json:', e.message);
}
}
// Calculate lat/lon from locator if not explicitly set
let stationLat = parseFloat(process.env.LATITUDE);
let stationLon = parseFloat(process.env.LONGITUDE);
if ((!stationLat || !stationLon) && locator) {
const coords = gridToLatLon(locator);
if (coords) {
stationLat = stationLat || coords.latitude;
stationLon = stationLon || coords.longitude;
}
}
// Fallback to config.json location if no env
if (!stationLat && jsonConfig.location?.lat) stationLat = jsonConfig.location.lat;
if (!stationLon && jsonConfig.location?.lon) stationLon = jsonConfig.location.lon;
const CONFIG = {
// Station info (env takes precedence over config.json)
callsign: process.env.CALLSIGN || jsonConfig.callsign || 'N0CALL',
gridSquare: locator || jsonConfig.locator || '',
latitude: stationLat || 40.7128,
longitude: stationLon || -74.0060,
// Display preferences
units: process.env.UNITS || jsonConfig.units || 'imperial',
timeFormat: process.env.TIME_FORMAT || jsonConfig.timeFormat || '12',
theme: process.env.THEME || jsonConfig.theme || 'dark',
layout: process.env.LAYOUT || jsonConfig.layout || 'modern',
// DX target
dxLatitude: parseFloat(process.env.DX_LATITUDE) || jsonConfig.defaultDX?.lat || 51.5074,
dxLongitude: parseFloat(process.env.DX_LONGITUDE) || jsonConfig.defaultDX?.lon || -0.1278,
// Feature toggles
showSatellites: process.env.SHOW_SATELLITES !== 'false' && jsonConfig.features?.showSatellites !== false,
showPota: process.env.SHOW_POTA !== 'false' && jsonConfig.features?.showPOTA !== false,
showDxPaths: process.env.SHOW_DX_PATHS !== 'false' && jsonConfig.features?.showDXPaths !== false,
showDxWeather: process.env.SHOW_DX_WEATHER !== 'false' && jsonConfig.features?.showDXWeather !== false,
classicAnalogClock: process.env.CLASSIC_ANALOG_CLOCK === 'true' || jsonConfig.features?.classicAnalogClock === true,
showContests: jsonConfig.features?.showContests !== false,
showDXpeditions: jsonConfig.features?.showDXpeditions !== false,
// DX Cluster settings
spotRetentionMinutes: parseInt(process.env.SPOT_RETENTION_MINUTES) || jsonConfig.dxCluster?.spotRetentionMinutes || 30,
dxClusterSource: process.env.DX_CLUSTER_SOURCE || jsonConfig.dxCluster?.source || 'auto',
// API keys (don't expose to frontend)
_openWeatherApiKey: process.env.OPENWEATHER_API_KEY || '',
_qrzUsername: process.env.QRZ_USERNAME || '',
_qrzPassword: process.env.QRZ_PASSWORD || ''
};
// Check if required config is missing
const configMissing = CONFIG.callsign === 'N0CALL' || !CONFIG.gridSquare;
if (configMissing) {
console.log('[Config] ⚠️ Station configuration incomplete!');
console.log('[Config] Copy .env.example to .env OR config.example.json to config.json');
console.log('[Config] Set your CALLSIGN and LOCATOR/grid square');
console.log('[Config] Settings popup will appear in browser');
}
// ITURHFProp service URL (optional - enables hybrid mode)
// Must be a full URL like https://iturhfprop.example.com
const ITURHFPROP_URL = process.env.ITURHFPROP_URL && process.env.ITURHFPROP_URL.trim().startsWith('http')
? process.env.ITURHFPROP_URL.trim()
: null;
// Log configuration
console.log(`[Config] Station: ${CONFIG.callsign} @ ${CONFIG.gridSquare || 'No grid'}`);
console.log(`[Config] Location: ${CONFIG.latitude.toFixed(4)}, ${CONFIG.longitude.toFixed(4)}`);
console.log(`[Config] Units: ${CONFIG.units}, Time: ${CONFIG.timeFormat}h`);
if (ITURHFPROP_URL) {
console.log(`[Propagation] Hybrid mode enabled - ITURHFProp service: ${ITURHFPROP_URL}`);
} else {
console.log('[Propagation] Standalone mode - using built-in calculations');
}
// Middleware
app.use(cors());
app.use(express.json());
// GZIP compression - reduces response sizes by 70-90%
// This is critical for reducing bandwidth/egress costs
app.use(compression({
level: 6, // Balanced compression level (1-9)
threshold: 1024, // Only compress responses > 1KB
filter: (req, res) => {
// Compress everything except already-compressed formats
if (req.headers['x-no-compression']) return false;
return compression.filter(req, res);
}
}));
// API response caching middleware
// Sets Cache-Control headers based on endpoint to reduce client polling
app.use('/api', (req, res, next) => {
// Determine cache duration based on endpoint
let cacheDuration = 30; // Default: 30 seconds
const path = req.path.toLowerCase();
if (path.includes('/satellites/tle')) {
cacheDuration = 3600; // 1 hour (TLE data is static)
} else if (path.includes('/contests') || path.includes('/dxpeditions')) {
cacheDuration = 1800; // 30 minutes (contests/expeditions change slowly)
} else if (path.includes('/solar-indices') || path.includes('/noaa')) {
cacheDuration = 300; // 5 minutes (space weather updates every 5 min)
} else if (path.includes('/propagation')) {
cacheDuration = 600; // 10 minutes
} else if (path.includes('/pota') || path.includes('/sota')) {
cacheDuration = 120; // 2 minutes
} else if (path.includes('/pskreporter')) {
cacheDuration = 300; // 5 minutes (PSKReporter rate limits aggressively)
} else if (path.includes('/dxcluster') || path.includes('/myspots')) {
cacheDuration = 30; // 30 seconds (DX spots need to be relatively fresh)
} else if (path.includes('/config')) {
cacheDuration = 3600; // 1 hour (config rarely changes)
}
res.setHeader('Cache-Control', `public, max-age=${cacheDuration}`);
res.setHeader('Vary', 'Accept-Encoding');
next();
});
// ============================================
// LOGGING SYSTEM
// ============================================
// LOG_LEVEL: 'debug' = verbose, 'info' = normal, 'warn' = warnings+errors, 'error' = errors only
const LOG_LEVEL = (process.env.LOG_LEVEL || 'warn').toLowerCase();
const LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
const currentLogLevel = LOG_LEVELS[LOG_LEVEL] ?? LOG_LEVELS.warn;
function logDebug(...args) {
if (currentLogLevel <= LOG_LEVELS.debug) console.log(...args);
}
function logInfo(...args) {
if (currentLogLevel <= LOG_LEVELS.info) console.log(...args);
}
function logWarn(...args) {
if (currentLogLevel <= LOG_LEVELS.warn) console.warn(...args);
}
// Rate-limited error logging - prevents log spam when services are down
const errorLogState = {};
const ERROR_LOG_INTERVAL = 5 * 60 * 1000; // Only log same error once per 5 minutes
function logErrorOnce(category, message) {
const key = `${category}:${message}`;
const now = Date.now();
const lastLogged = errorLogState[key] || 0;
if (now - lastLogged >= ERROR_LOG_INTERVAL) {
errorLogState[key] = now;
console.error(`[${category}] ${message}`);
return true;
}
return false;
}
// ============================================
// VISITOR TRACKING (PERSISTENT)
// ============================================
// Persistent visitor tracking that survives server restarts and deployments
// Uses file-based storage - configure STATS_FILE env var for Railway volumes
// Default: ./data/stats.json (local) or /data/stats.json (Railway volume)
// Determine best location for stats file with write permission check
function getStatsFilePath() {
// If explicitly set via env var, use that
if (process.env.STATS_FILE) {
console.log(`[Stats] Using STATS_FILE env: ${process.env.STATS_FILE}`);
return process.env.STATS_FILE;
}
// List of paths to try in order of preference
const pathsToTry = [
'/data/stats.json', // Railway volume
path.join(__dirname, 'data', 'stats.json'), // Local ./data subdirectory
'/tmp/openhamclock-stats.json' // Temp (won't survive restarts but better than nothing)
];
for (const statsPath of pathsToTry) {
try {
const dir = path.dirname(statsPath);
// Create directory if it doesn't exist
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
// Test write permission
const testFile = path.join(dir, '.write-test-' + Date.now());
fs.writeFileSync(testFile, 'test');
fs.unlinkSync(testFile);
console.log(`[Stats] ✓ Using: ${statsPath}`);
return statsPath;
} catch (err) {
console.log(`[Stats] ✗ ${statsPath}: ${err.code || err.message}`);
}
}
// No writable path found
console.log('[Stats] ⚠ No writable storage - stats will be memory-only');
return null;
}
const STATS_FILE = getStatsFilePath();
const STATS_SAVE_INTERVAL = 60000; // Save every 60 seconds
// Load persistent stats from disk
function loadVisitorStats() {
const defaults = {
today: new Date().toISOString().slice(0, 10),
uniqueIPsToday: [],
totalRequestsToday: 0,
allTimeVisitors: 0,
allTimeRequests: 0,
allTimeUniqueIPs: [],
serverFirstStarted: new Date().toISOString(),
lastDeployment: new Date().toISOString(),
deploymentCount: 1,
history: [],
lastSaved: null
};
// No stats file configured - memory only mode
if (!STATS_FILE) {
console.log('[Stats] Running in memory-only mode');
return defaults;
}
try {
if (fs.existsSync(STATS_FILE)) {
const data = JSON.parse(fs.readFileSync(STATS_FILE, 'utf8'));
console.log(`[Stats] Loaded from ${STATS_FILE}`);
console.log(`[Stats] 📊 All-time: ${data.allTimeVisitors || 0} unique visitors, ${data.allTimeRequests || 0} requests`);
console.log(`[Stats] 📅 History: ${(data.history || []).length} days tracked`);
console.log(`[Stats] 🚀 Deployment #${(data.deploymentCount || 0) + 1} (first: ${data.serverFirstStarted || 'unknown'})`);
return {
today: new Date().toISOString().slice(0, 10),
uniqueIPsToday: data.today === new Date().toISOString().slice(0, 10) ? (data.uniqueIPsToday || []) : [],
totalRequestsToday: data.today === new Date().toISOString().slice(0, 10) ? (data.totalRequestsToday || 0) : 0,
allTimeVisitors: data.allTimeVisitors || 0,
allTimeRequests: data.allTimeRequests || 0,
allTimeUniqueIPs: data.allTimeUniqueIPs || [],
serverFirstStarted: data.serverFirstStarted || defaults.serverFirstStarted,
lastDeployment: new Date().toISOString(),
deploymentCount: (data.deploymentCount || 0) + 1,
history: data.history || [],
lastSaved: data.lastSaved
};
}
} catch (err) {
console.error('[Stats] Failed to load:', err.message);
}
console.log('[Stats] Starting fresh (no existing stats file)');
return defaults;
}
// Save stats to disk
let saveErrorCount = 0;
function saveVisitorStats() {
// No stats file configured - memory only mode
if (!STATS_FILE) {
return;
}
try {
const dir = path.dirname(STATS_FILE);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
const data = {
...visitorStats,
lastSaved: new Date().toISOString()
};
fs.writeFileSync(STATS_FILE, JSON.stringify(data, null, 2));
visitorStats.lastSaved = data.lastSaved; // Update in-memory too
saveErrorCount = 0; // Reset on success
// Only log occasionally to avoid spam
if (Math.random() < 0.1) {
console.log(`[Stats] Saved - ${visitorStats.allTimeVisitors} all-time visitors, ${visitorStats.uniqueIPsToday.length} today`);
}
} catch (err) {
saveErrorCount++;
// Only log first error and then every 10th to avoid spam
if (saveErrorCount === 1 || saveErrorCount % 10 === 0) {
console.error(`[Stats] Failed to save (attempt #${saveErrorCount}):`, err.message);
if (saveErrorCount === 1) {
console.error('[Stats] Stats will be kept in memory but won\'t persist across restarts');
}
}
}
}
// Initialize stats
const visitorStats = loadVisitorStats();
// Convert today's IPs to a Set for fast lookup
const todayIPSet = new Set(visitorStats.uniqueIPsToday);
const allTimeIPSet = new Set(visitorStats.allTimeUniqueIPs);
// Save immediately on startup to confirm persistence is working
if (STATS_FILE) {
saveVisitorStats();
console.log('[Stats] Initial save complete - persistence confirmed');
}
// Periodic save
setInterval(saveVisitorStats, STATS_SAVE_INTERVAL);
// Save on shutdown
function gracefulShutdown(signal) {
console.log(`[Stats] Received ${signal}, saving before shutdown...`);
saveVisitorStats();
process.exit(0);
}
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
function rolloverVisitorStats() {
const now = new Date().toISOString().slice(0, 10);
if (now !== visitorStats.today) {
// Save yesterday's stats to history
if (visitorStats.uniqueIPsToday.length > 0 || visitorStats.totalRequestsToday > 0) {
visitorStats.history.push({
date: visitorStats.today,
uniqueVisitors: visitorStats.uniqueIPsToday.length,
totalRequests: visitorStats.totalRequestsToday
});
}
// Keep only last 90 days
if (visitorStats.history.length > 90) {
visitorStats.history = visitorStats.history.slice(-90);
}
const avg = visitorStats.history.length > 0
? Math.round(visitorStats.history.reduce((sum, d) => sum + d.uniqueVisitors, 0) / visitorStats.history.length)
: 0;
console.log(`[Stats] Daily rollover for ${visitorStats.today}: ${visitorStats.uniqueIPsToday.length} unique, ${visitorStats.totalRequestsToday} requests | All-time: ${visitorStats.allTimeVisitors} visitors | ${visitorStats.history.length}-day avg: ${avg}/day`);
// Reset daily counters
visitorStats.today = now;
visitorStats.uniqueIPsToday = [];
visitorStats.totalRequestsToday = 0;
todayIPSet.clear();
// Save after rollover
saveVisitorStats();
}
}
// Visitor tracking middleware
app.use((req, res, next) => {
rolloverVisitorStats();
// Only count meaningful "visits" — initial page load or config fetch
const countableRoutes = ['/', '/index.html', '/api/config'];
if (countableRoutes.includes(req.path)) {
const ip = req.headers['x-forwarded-for']?.split(',')[0]?.trim() || req.ip || req.connection?.remoteAddress || 'unknown';
// Track today's visitors
const isNewToday = !todayIPSet.has(ip);
if (isNewToday) {
todayIPSet.add(ip);
visitorStats.uniqueIPsToday.push(ip);
}
visitorStats.totalRequestsToday++;
visitorStats.allTimeRequests++;
// Track all-time unique visitors
const isNewAllTime = !allTimeIPSet.has(ip);
if (isNewAllTime) {
allTimeIPSet.add(ip);
visitorStats.allTimeUniqueIPs.push(ip);
visitorStats.allTimeVisitors++;
logInfo(`[Stats] New visitor (#${visitorStats.uniqueIPsToday.length} today, #${visitorStats.allTimeVisitors} all-time) from ${ip.replace(/\d+$/, 'x')}`);
}
}
next();
});
// Log visitor count every hour
setInterval(() => {
rolloverVisitorStats();
if (visitorStats.uniqueIPsToday.length > 0 || visitorStats.allTimeVisitors > 0) {
const avg = visitorStats.history.length > 0
? Math.round(visitorStats.history.reduce((sum, d) => sum + d.uniqueVisitors, 0) / visitorStats.history.length)
: visitorStats.uniqueIPsToday.length;
console.log(`[Stats] Hourly: ${visitorStats.uniqueIPsToday.length} unique today, ${visitorStats.totalRequestsToday} requests | All-time: ${visitorStats.allTimeVisitors} visitors | Avg: ${avg}/day`);
}
}, 60 * 60 * 1000);
// ============================================
// AUTO UPDATE (GIT)
// ============================================
const AUTO_UPDATE_ENABLED = process.env.AUTO_UPDATE_ENABLED === 'true';
const AUTO_UPDATE_INTERVAL_MINUTES = parseInt(process.env.AUTO_UPDATE_INTERVAL_MINUTES || '60');
const AUTO_UPDATE_ON_START = process.env.AUTO_UPDATE_ON_START === 'true';
const AUTO_UPDATE_EXIT_AFTER = process.env.AUTO_UPDATE_EXIT_AFTER !== 'false';
const autoUpdateState = {
inProgress: false,
lastCheck: 0,
lastResult: ''
};
function execFilePromise(cmd, args, options = {}) {
return new Promise((resolve, reject) => {
execFile(cmd, args, options, (err, stdout, stderr) => {
if (err) {
err.stdout = stdout;
err.stderr = stderr;
return reject(err);
}
resolve({ stdout, stderr });
});
});
}
async function hasGitUpdates() {
await execFilePromise('git', ['fetch', 'origin'], { cwd: __dirname });
const local = (await execFilePromise('git', ['rev-parse', 'HEAD'], { cwd: __dirname })).stdout.trim();
let remote = '';
try {
remote = (await execFilePromise('git', ['rev-parse', 'origin/main'], { cwd: __dirname })).stdout.trim();
} catch {
remote = (await execFilePromise('git', ['rev-parse', 'origin/master'], { cwd: __dirname })).stdout.trim();
}
return { updateAvailable: local !== remote, local, remote };
}
async function hasDirtyWorkingTree() {
const status = await execFilePromise('git', ['status', '--porcelain'], { cwd: __dirname });
return status.stdout.trim().length > 0;
}
function runUpdateScript() {
return new Promise((resolve, reject) => {
const scriptPath = path.join(__dirname, 'scripts', 'update.sh');
const child = spawn('bash', [scriptPath, '--auto'], {
cwd: __dirname,
stdio: 'inherit'
});
child.on('exit', (code) => {
if (code === 0) return resolve();
reject(new Error(`update.sh exited with code ${code}`));
});
});
}
async function autoUpdateTick(trigger = 'interval', force = false) {
if ((!AUTO_UPDATE_ENABLED && !force) || autoUpdateState.inProgress) return;
autoUpdateState.inProgress = true;
autoUpdateState.lastCheck = Date.now();
try {
if (!fs.existsSync(path.join(__dirname, '.git'))) {
autoUpdateState.lastResult = 'not-git';
logWarn('[Auto Update] Skipped - not a git repository');
return;
}
try {
await execFilePromise('git', ['--version']);
} catch {
autoUpdateState.lastResult = 'no-git';
logWarn('[Auto Update] Skipped - git not installed');
return;
}
if (await hasDirtyWorkingTree()) {
autoUpdateState.lastResult = 'dirty';
logWarn('[Auto Update] Skipped - local changes detected');
return;
}
const { updateAvailable } = await hasGitUpdates();
if (!updateAvailable) {
autoUpdateState.lastResult = 'up-to-date';
logInfo(`[Auto Update] Up to date (${trigger})`);
return;
}
autoUpdateState.lastResult = 'updating';
logInfo('[Auto Update] Updates available - running update script');
await runUpdateScript();
autoUpdateState.lastResult = 'updated';
logInfo('[Auto Update] Update complete');
if (AUTO_UPDATE_EXIT_AFTER) {
logInfo('[Auto Update] Exiting to allow restart');
process.exit(0);
}
} catch (err) {
autoUpdateState.lastResult = 'error';
logErrorOnce('Auto Update', err.message);
} finally {
autoUpdateState.inProgress = false;
}
}
function startAutoUpdateScheduler() {
if (!AUTO_UPDATE_ENABLED) return;
const intervalMinutes = Number.isFinite(AUTO_UPDATE_INTERVAL_MINUTES) && AUTO_UPDATE_INTERVAL_MINUTES > 0
? AUTO_UPDATE_INTERVAL_MINUTES
: 60;
const intervalMs = Math.max(5, intervalMinutes) * 60 * 1000;
logInfo(`[Auto Update] Enabled - every ${intervalMinutes} minutes`);
if (AUTO_UPDATE_ON_START) {
setTimeout(() => autoUpdateTick('startup'), 30000);
}
setInterval(() => autoUpdateTick('interval'), intervalMs);
}
// Serve static files
// dist/ contains the built React app (from npm run build)
// public/ contains the fallback page if build hasn't run
const distDir = path.join(__dirname, 'dist');
const publicDir = path.join(__dirname, 'public');
// Check if dist/ exists (has index.html from build)
const distExists = fs.existsSync(path.join(distDir, 'index.html'));
// Static file caching options
const staticOptions = {
maxAge: '1d', // Cache static files for 1 day
etag: true,
lastModified: true
};
// Long-term caching for hashed assets (Vite adds hash to filenames)
const assetOptions = {
maxAge: '1y', // Cache hashed assets for 1 year
immutable: true
};
if (distExists) {
// Serve built React app from dist/
// Hashed assets (with content hash in filename) can be cached forever
app.use('/assets', express.static(path.join(distDir, 'assets'), assetOptions));
app.use(express.static(distDir, staticOptions));
console.log('[Server] Serving React app from dist/');
} else {
// No build found - serve placeholder from public/
console.log('[Server] ⚠️ No build found! Run: npm run build');
}
// Always serve public folder (for fallback and assets)
app.use(express.static(publicDir, staticOptions));
// ============================================
// API PROXY ENDPOINTS
// ============================================
// Centralized cache for NOAA data (5-minute cache)
const noaaCache = {
flux: { data: null, timestamp: 0 },
kindex: { data: null, timestamp: 0 },
sunspots: { data: null, timestamp: 0 },
xray: { data: null, timestamp: 0 },
aurora: { data: null, timestamp: 0 },
solarIndices: { data: null, timestamp: 0 }
};
const NOAA_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
// NOAA Space Weather - Solar Flux
app.get('/api/noaa/flux', async (req, res) => {
try {
if (noaaCache.flux.data && (Date.now() - noaaCache.flux.timestamp) < NOAA_CACHE_TTL) {
return res.json(noaaCache.flux.data);
}
const response = await fetch('https://services.swpc.noaa.gov/json/f107_cm_flux.json');
const data = await response.json();
noaaCache.flux = { data, timestamp: Date.now() };
res.json(data);
} catch (error) {
logErrorOnce('NOAA Flux', error.message);
if (noaaCache.flux.data) return res.json(noaaCache.flux.data);
res.status(500).json({ error: 'Failed to fetch solar flux data' });
}
});
// NOAA Space Weather - K-Index
app.get('/api/noaa/kindex', async (req, res) => {
try {
if (noaaCache.kindex.data && (Date.now() - noaaCache.kindex.timestamp) < NOAA_CACHE_TTL) {
return res.json(noaaCache.kindex.data);
}
const response = await fetch('https://services.swpc.noaa.gov/products/noaa-planetary-k-index.json');
const data = await response.json();
noaaCache.kindex = { data, timestamp: Date.now() };
res.json(data);
} catch (error) {
logErrorOnce('NOAA K-Index', error.message);
if (noaaCache.kindex.data) return res.json(noaaCache.kindex.data);
res.status(500).json({ error: 'Failed to fetch K-index data' });
}
});
// NOAA Space Weather - Sunspots
app.get('/api/noaa/sunspots', async (req, res) => {
try {
if (noaaCache.sunspots.data && (Date.now() - noaaCache.sunspots.timestamp) < NOAA_CACHE_TTL) {
return res.json(noaaCache.sunspots.data);
}
const response = await fetch('https://services.swpc.noaa.gov/json/solar-cycle/observed-solar-cycle-indices.json');
const data = await response.json();
noaaCache.sunspots = { data, timestamp: Date.now() };
res.json(data);
} catch (error) {
logErrorOnce('NOAA Sunspots', error.message);
if (noaaCache.sunspots.data) return res.json(noaaCache.sunspots.data);
res.status(500).json({ error: 'Failed to fetch sunspot data' });
}
});
// Solar Indices with History and Kp Forecast
app.get('/api/solar-indices', async (req, res) => {
try {
// Check cache first
if (noaaCache.solarIndices.data && (Date.now() - noaaCache.solarIndices.timestamp) < NOAA_CACHE_TTL) {
return res.json(noaaCache.solarIndices.data);
}
const [fluxRes, kIndexRes, kForecastRes, sunspotRes] = await Promise.allSettled([
fetch('https://services.swpc.noaa.gov/json/f107_cm_flux.json'),
fetch('https://services.swpc.noaa.gov/products/noaa-planetary-k-index.json'),
fetch('https://services.swpc.noaa.gov/products/noaa-planetary-k-index-forecast.json'),
fetch('https://services.swpc.noaa.gov/json/solar-cycle/observed-solar-cycle-indices.json')
]);
const result = {
sfi: { current: null, history: [] },
kp: { current: null, history: [], forecast: [] },
ssn: { current: null, history: [] },
timestamp: new Date().toISOString()
};
// Process SFI data (last 30 days)
if (fluxRes.status === 'fulfilled' && fluxRes.value.ok) {
const data = await fluxRes.value.json();
if (data?.length) {
// Get last 30 entries
const recent = data.slice(-30);
result.sfi.history = recent.map(d => ({
date: d.time_tag || d.date,
value: Math.round(d.flux || d.value || 0)
}));
result.sfi.current = result.sfi.history[result.sfi.history.length - 1]?.value || null;
}
}
// Process Kp history (last 3 days, data comes in 3-hour intervals)
if (kIndexRes.status === 'fulfilled' && kIndexRes.value.ok) {
const data = await kIndexRes.value.json();
if (data?.length > 1) {
// Skip header row, get last 24 entries (3 days)
const recent = data.slice(1).slice(-24);
result.kp.history = recent.map(d => ({
time: d[0],
value: parseFloat(d[1]) || 0
}));
result.kp.current = result.kp.history[result.kp.history.length - 1]?.value || null;
}
}
// Process Kp forecast
if (kForecastRes.status === 'fulfilled' && kForecastRes.value.ok) {
const data = await kForecastRes.value.json();
if (data?.length > 1) {
// Skip header row
result.kp.forecast = data.slice(1).map(d => ({
time: d[0],
value: parseFloat(d[1]) || 0
}));
}
}
// Process Sunspot data (last 12 months)
if (sunspotRes.status === 'fulfilled' && sunspotRes.value.ok) {
const data = await sunspotRes.value.json();
if (data?.length) {
// Get last 12 entries (monthly data)
const recent = data.slice(-12);
result.ssn.history = recent.map(d => ({
date: `${d['time-tag'] || d.time_tag || ''}`,
value: Math.round(d.ssn || 0)
}));
result.ssn.current = result.ssn.history[result.ssn.history.length - 1]?.value || null;
}
}
// Cache the result
noaaCache.solarIndices = { data: result, timestamp: Date.now() };
res.json(result);
} catch (error) {
logErrorOnce('Solar Indices', error.message);
// Return stale cache on error
if (noaaCache.solarIndices.data) return res.json(noaaCache.solarIndices.data);
res.status(500).json({ error: 'Failed to fetch solar indices' });
}
});
// DXpedition Calendar - fetches from NG3K ADXO plain text version
let dxpeditionCache = { data: null, timestamp: 0, maxAge: 30 * 60 * 1000 }; // 30 min cache
app.get('/api/dxpeditions', async (req, res) => {
try {
const now = Date.now();
logDebug('[DXpeditions] API called');
// Return cached data if fresh
if (dxpeditionCache.data && (now - dxpeditionCache.timestamp) < dxpeditionCache.maxAge) {
logDebug('[DXpeditions] Returning cached data:', dxpeditionCache.data.dxpeditions?.length, 'entries');
return res.json(dxpeditionCache.data);
}
// Fetch NG3K ADXO plain text version
logDebug('[DXpeditions] Fetching from NG3K...');
const response = await fetch('https://www.ng3k.com/Misc/adxoplain.html');
if (!response.ok) {
logDebug('[DXpeditions] NG3K fetch failed:', response.status);
throw new Error('Failed to fetch NG3K: ' + response.status);
}
let text = await response.text();
logDebug('[DXpeditions] Received', text.length, 'bytes raw');
// Strip HTML tags and decode entities - the "plain" page is actually HTML!
text = text
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '') // Remove scripts
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '') // Remove styles
.replace(/<br\s*\/?>/gi, '\n') // Convert br to newlines
.replace(/<[^>]+>/g, ' ') // Remove all HTML tags
.replace(/ /g, ' ')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/\s+/g, ' ') // Normalize whitespace
.trim();
logDebug('[DXpeditions] Cleaned text length:', text.length);
logDebug('[DXpeditions] First 500 chars:', text.substring(0, 500));
const dxpeditions = [];
// Each entry starts with a date pattern like "Jan 1-Feb 16, 2026 DXCC:"
// Split on date patterns that are followed by DXCC
const entryPattern = /((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+\d{1,2}[^D]*?DXCC:[^·]+?)(?=(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+\d{1,2}|$)/gi;
const entries = text.match(entryPattern) || [];
logDebug('[DXpeditions] Found', entries.length, 'potential entries');
// Log first 3 entries for debugging
entries.slice(0, 3).forEach((e, i) => {
logDebug(`[DXpeditions] Entry ${i}:`, e.substring(0, 150));
});
for (const entry of entries) {
if (!entry.trim()) continue;
// Skip header/footer/legend content
if (entry.includes('ADXB=') || entry.includes('OPDX=') || entry.includes('425DX=') ||
entry.includes('Last updated') || entry.includes('Copyright') ||
entry.includes('Expired Announcements') || entry.includes('Table Version') ||
entry.includes('About ADXO') || entry.includes('Search ADXO') ||
entry.includes('GazDX=') || entry.includes('LNDX=') || entry.includes('TDDX=') ||
entry.includes('DXW.Net=') || entry.includes('DXMB=')) continue;
// Try multiple parsing strategies
let callsign = null;
let entity = null;
let qsl = null;
let info = null;
let dateStr = null;
// Strategy 1: "DXCC: xxx Callsign: xxx" format
const dxccMatch = entry.match(/DXCC:\s*([^C\n]+?)(?=Callsign:|QSL:|Source:|Info:|$)/i);
const callMatch = entry.match(/Callsign:\s*([A-Z0-9\/]+)/i);
if (callMatch && dxccMatch) {
callsign = callMatch[1].trim().toUpperCase();
entity = dxccMatch[1].trim();
}
// Strategy 2: Look for callsign patterns directly (like "3Y0K" or "VP8/G3ABC")
if (!callsign) {
const directCallMatch = entry.match(/\b([A-Z]{1,2}\d[A-Z0-9]*[A-Z](?:\/[A-Z0-9]+)?)\b/);
if (directCallMatch) {
callsign = directCallMatch[1];
}
}
// Strategy 3: Parse "Entity - Callsign" or similar patterns
if (!callsign) {
const altMatch = entry.match(/([A-Za-z\s&]+?)\s*[-–:]\s*([A-Z]{1,2}\d[A-Z0-9]*)/);
if (altMatch) {
entity = altMatch[1].trim();
callsign = altMatch[2].trim();
}
}
// Extract other fields
const qslMatch = entry.match(/QSL:\s*([A-Za-z0-9]+)/i);
const infoMatch = entry.match(/Info:\s*(.+)/i);
// Date is at the start of entry: "Jan 1-Feb 16, 2026"
const dateMatch = entry.match(/^([A-Za-z]{3}\s+\d{1,2}[^D]*?)(?=DXCC:)/i);
qsl = qslMatch ? qslMatch[1].trim() : '';
info = infoMatch ? infoMatch[1].trim() : '';
dateStr = dateMatch ? dateMatch[1].trim() : '';
// Skip if we couldn't find a callsign
if (!callsign || callsign.length < 3) continue;
// Skip obviously wrong matches
if (/^(DXCC|QSL|INFO|SOURCE|THE|AND|FOR)$/i.test(callsign)) continue;
// Log first few successful parses
if (dxpeditions.length < 3) {
logDebug(`[DXpeditions] Parsed: ${callsign} - ${entity} - ${dateStr}`);
}
// Try to extract entity from context if not found
if (!entity && info) {
// Look for "from Entity" or "fm Entity" patterns
const fromMatch = info.match(/(?:from|fm)\s+([A-Za-z\s]+?)(?:;|,|$)/i);
if (fromMatch) entity = fromMatch[1].trim();
}
// Parse dates
let startDate = null;
let endDate = null;
let isActive = false;
let isUpcoming = false;
if (dateStr) {
const monthNames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
const datePattern = /([A-Za-z]{3})\s+(\d{1,2})(?:,?\s*(\d{4}))?(?:\s*[-–]\s*([A-Za-z]{3})?\s*(\d{1,2})(?:,?\s*(\d{4}))?)?/i;
const dateParsed = dateStr.match(datePattern);
if (dateParsed) {
const currentYear = new Date().getFullYear();
const startMonth = monthNames.indexOf(dateParsed[1].toLowerCase());
const startDay = parseInt(dateParsed[2]);
const startYear = dateParsed[3] ? parseInt(dateParsed[3]) : currentYear;
const endMonthStr = dateParsed[4] || dateParsed[1];
const endMonth = monthNames.indexOf(endMonthStr.toLowerCase());
const endDay = parseInt(dateParsed[5]) || startDay + 14;
const endYear = dateParsed[6] ? parseInt(dateParsed[6]) : startYear;
if (startMonth >= 0) {
startDate = new Date(startYear, startMonth, startDay);
endDate = new Date(endYear, endMonth >= 0 ? endMonth : startMonth, endDay);
if (endDate < startDate && !dateParsed[6]) {
endDate.setFullYear(endYear + 1);
}
const today = new Date();
today.setHours(0, 0, 0, 0);
isActive = startDate <= today && endDate >= today;
isUpcoming = startDate > today;
}
}
}
// Extract bands and modes
const bandsMatch = entry.match(/(\d+(?:-\d+)?m)/g);
const bands = bandsMatch ? [...new Set(bandsMatch)].join(' ') : '';
const modesMatch = entry.match(/\b(CW|SSB|FT8|FT4|RTTY|PSK|FM|AM|DIGI)\b/gi);
const modes = modesMatch ? [...new Set(modesMatch.map(m => m.toUpperCase()))].join(' ') : '';
dxpeditions.push({
callsign,
entity: entity || 'Unknown',