-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapp.js
More file actions
2432 lines (2093 loc) · 90.3 KB
/
app.js
File metadata and controls
2432 lines (2093 loc) · 90.3 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
"use strict";
// ================================================================
// Module Imports
// ================================================================
const POTASpots = require('./modules/pota');
const SOTASpots = require('./modules/sota');
const RBNManager = require('./modules/rbn');
const ModeClassifier = require('./modules/modeclassifier');
const Enrichment = require('./modules/enrichment');
const Persistence = require('./modules/persistence');
const Analytics = require('./modules/analytics');
const Clusters = require('./modules/clusters');
const APIv1 = require('./modules/apiv1');
const APIv2 = require('./modules/apiv2');
const Metrics = require('./modules/metrics');
const RateLimiter = require('./modules/rate-limiter');
const { toUcWord, qrg2band, getFreshestSpot, getOldestSpot, normalizeFrequency, parseSkimmerMessage } = require('./lib/utils');
const express = require("express");
const app = express();
const path = require("path");
const cors = require('cors');
const morgan = require('morgan');
const WebSocket = require('ws');
const { Server } = require("socket.io");
const fs = require('fs');
const os = require('os');
// Load version from package.json
const packageJson = require('./package.json');
const APP_VERSION = packageJson.version;
// Prefer global fetch if available (Node 18+), otherwise fall back to node-fetch
const fetch = (global.fetch ? global.fetch : require('node-fetch'));
if (!global.fetch) { global.fetch = fetch; }
// ================================================================
// Global Variables (must be declared before use)
// ================================================================
// Spot cache and indexes
let spots = [];
let httpServer = null; // HTTP server instance for graceful shutdown
const bandIndex = new Map(); // Map<band, Set<spot>>
const frequencyIndex = new Map(); // Map<frequency, spot>
const sourceIndex = new Map(); // Map<source, Set<spot>>
const spotKeyIndex = new Map(); // Map<spotKey, spot> for O(1) duplicate detection
// Statistics indexes (for O(1) /stats endpoint)
const modeTypeStats = { phone: 0, digi: 0, cw: 0, unknown: 0 };
const continentStats = {}; // DX continent breakdown
const continentDeStats = {}; // DE (spotter) continent breakdown
let rbnSpotCount = 0; // Track RBN spots for early exit in cleanup
// WebSocket and Cluster Manager (initialized later)
const wsClients = new Set();
let wss = null; // Will be initialized in startWebSocket()
let io = null; // Will be initialized in startWebSocket()
let clusterManager = null; // Will be initialized after config is loaded
// ================================================================
// Configuration Loading
// ================================================================
// Load .env file first (if exists), then fallback to config.js
require('dotenv').config();
let config = {};
// Check if running from environment variables (.env or Docker)
if (process.env.WEBPORT !== undefined || process.env.MODE !== undefined) {
// Load configuration from environment variables
config = {
mode: process.env.MODE || 'native',
webport: parseInt(process.env.WEBPORT) || 3000,
baseUrl: process.env.BASEURL || '',
maxcache: parseInt(process.env.MAXCACHE) || 200,
spotMaxAge: parseInt(process.env.SPOT_MAX_AGE) || 120, // minutes
// Parse cluster configuration
clusters: JSON.parse(process.env.CLUSTERS || '[]'),
// DXCC lookup
dxcc_lookup_wavelog_url: process.env.WAVELOG_URL,
dxcc_lookup_wavelog_key: process.env.WAVELOG_KEY,
maxConcurrentDxcc: parseInt(process.env.MAX_CONCURRENT_DXCC) || 2, // PHP worker limit
dxccCacheMaxSize: parseInt(process.env.DXCC_CACHE_MAX_SIZE) || 5000, // Max DXCC cache entries
// Module configurations
clusterEnabled: process.env.CLUSTER_ENABLED !== 'false',
// POTA configuration
includepotaspots: process.env.POTA_ENABLED === 'true',
potapollinterval: parseInt(process.env.POTA_POLLING_INTERVAL) || 120,
// SOTA configuration
includesotaspots: process.env.SOTA_ENABLED === 'true',
sotapollinterval: parseInt(process.env.SOTA_POLLING_INTERVAL) || 120,
// RBN configuration
rbnEnabled: process.env.RBN_ENABLED === 'true',
rbnCallsign: process.env.RBN_CALLSIGN || 'N0CALL',
rbnSpotTimeout: parseInt(process.env.RBN_SPOT_TIMEOUT) || 5, // minutes
rbnCwRttyEnabled: process.env.RBN_CW_RTTY_ENABLED !== 'false', // default true
rbnFt8Enabled: process.env.RBN_FT8_ENABLED === 'true', // default false
// Enrichment configuration
enrichmentEnabled: process.env.ENRICHMENT_ENABLED !== 'false',
// Mode Classifier configuration
modeClassifierEnabled: process.env.MODE_CLASSIFIER_ENABLED !== 'false',
// Analytics configuration
analyticsEnabled: process.env.ANALYTICS_ENABLED !== 'false',
// API v1 and v2 configuration
apiv1Enabled: process.env.API_V1_ENABLED !== 'false',
apiv2Enabled: process.env.API_V2_ENABLED !== 'false',
apiv2Key: process.env.API_V2_KEY || '',
apiSpotLimit: parseInt(process.env.API_SPOT_LIMIT) || 200,
// WebSocket configuration
websocketEnabled: process.env.WEBSOCKET_ENABLED !== 'false',
// Live page configuration
livePageEnabled: process.env.LIVE_PAGE_ENABLED !== 'false',
livePagePassword: process.env.LIVE_PAGE_PASSWORD || '',
// Logging configuration
fileLoggingEnabled: process.env.FILE_LOGGING_ENABLED !== 'false',
logRetentionDays: parseInt(process.env.LOG_RETENTION_DAYS) || 3,
// Persistence configuration
persistenceEnabled: process.env.PERSISTENCE_ENABLED !== 'false',
persistenceInterval: parseInt(process.env.PERSISTENCE_INTERVAL) || 60,
persistencePath: process.env.PERSISTENCE_PATH || path.join(__dirname, 'data', 'spots-cache.json'),
// Proxy configuration
trustProxy: process.env.TRUST_PROXY !== 'false', // Default true for reverse proxy compatibility
// Rate limiter configuration
rateLimiterEnabled: process.env.RATE_LIMITER_ENABLED === 'true',
rateLimiterGeneralMax: parseInt(process.env.RATE_LIMITER_GENERAL_MAX) || 120,
rateLimiterDataMax: parseInt(process.env.RATE_LIMITER_DATA_MAX) || 60,
rateLimiterBanTime: parseInt(process.env.RATE_LIMITER_BAN_TIME) || 60
};
} else {
// Fallback to config.js (legacy support)
try {
config = require("./config.js");
config.mode = config.mode || 'native';
config.clusterEnabled = config.clusterEnabled !== false;
config.enrichmentEnabled = config.enrichmentEnabled !== false;
config.analyticsEnabled = config.analyticsEnabled !== false;
config.apiv1Enabled = config.apiv1Enabled !== false;
config.apiv2Enabled = config.apiv2Enabled !== false;
config.apiv2Key = config.apiv2Key || '';
config.websocketEnabled = config.websocketEnabled !== false;
config.livePageEnabled = config.livePageEnabled !== false;
config.livePagePassword = config.livePagePassword || '';
config.fileLoggingEnabled = config.fileLoggingEnabled !== false;
config.logRetentionDays = config.logRetentionDays || 3;
config.spotMaxAge = config.spotMaxAge || 120;
config.maxConcurrentDxcc = config.maxConcurrentDxcc || 2;
config.persistenceEnabled = config.persistenceEnabled !== false;
config.persistenceInterval = config.persistenceInterval || 60;
config.persistencePath = config.persistencePath || path.join(__dirname, 'data', 'spots-cache.json');
config.trustProxy = config.trustProxy !== false; // Default true
} catch (e) {
console.error('[Core] No .env file or config.js found! Please create one based on .env.sample');
process.exit(1);
}
}
// Ensure clusters array is populated
let clusters = config.clusters || [];
if (clusters.length === 0 && config.dxc) {
// Legacy single cluster support
clusters = [config.dxc];
}
// Validate configuration
function validateConfig() {
const warnings = [];
const errors = [];
// Check clusters
if (!clusters || clusters.length === 0) {
warnings.push('No DX clusters configured - cluster spots will not be available');
}
// Check DXCC lookup
if (!config.dxcc_lookup_wavelog_url || !config.dxcc_lookup_wavelog_key) {
warnings.push('DXCC lookup not configured - spots will not have country information');
}
// Check modules
if (!config.includepotaspots && !config.includesotaspots && (!clusters || clusters.length === 0)) {
errors.push('No data sources enabled (no clusters, POTA, or SOTA)');
}
// Log results
if (errors.length > 0) {
console.error('[Core] Configuration errors:');
errors.forEach(err => console.error(`[Core] ❌ ${err}`));
console.error('[Core] \nPlease fix the errors above and restart the application.');
process.exit(1);
}
if (warnings.length > 0) {
console.warn('[Core] Configuration warnings:');
warnings.forEach(warn => console.warn(`[Core] ⚠️ ${warn}`));
}
}
validateConfig();
// ================================================================
// Logging Setup
// ================================================================
const LOG_DIR = path.join(__dirname, 'logs');
let logStream = null;
let LOG_FILE = null;
let currentLogDate = null;
// Daily filename formatter (global for use in /logs endpoint)
function fmtLogDate(d) {
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const dd = String(d.getDate()).padStart(2, '0');
return `${y}${m}${dd}`;
}
/**
* Rotates the log file if the date has changed
*/
function rotateLogIfNeeded() {
const todayStr = fmtLogDate(new Date());
if (currentLogDate === todayStr) return;
// Close existing stream
if (logStream) {
try { logStream.end(); } catch (_) {}
}
currentLogDate = todayStr;
LOG_FILE = path.join(LOG_DIR, `app-${todayStr}.log`);
logStream = fs.createWriteStream(LOG_FILE, { flags: 'a' });
// Prune old logs on rotation
try {
const files = fs.readdirSync(LOG_DIR);
const cutoff = new Date(Date.now() - config.logRetentionDays * 24 * 60 * 60 * 1000);
files.forEach(f => {
if (!/^app-\d{8}\.log$/.test(f)) return;
const stamp = f.slice(4, 12); // YYYYMMDD
const y = parseInt(stamp.slice(0, 4));
const m = parseInt(stamp.slice(4, 6)) - 1;
const d = parseInt(stamp.slice(6, 8));
const fileDate = new Date(y, m, d);
if (fileDate < cutoff) {
try { fs.unlinkSync(path.join(LOG_DIR, f)); } catch (_) {}
}
});
} catch (_) {}
}
if (config.fileLoggingEnabled) {
try {
fs.mkdirSync(LOG_DIR, { recursive: true });
} catch (_) {}
// Initialize log file
rotateLogIfNeeded();
function stamp(level, args) {
const ts = new Date().toISOString();
const line = `[${ts}] [${level}] ${args.map(a => {
try { return (typeof a === 'string') ? a : JSON.stringify(a); }
catch (_) { return String(a); }
}).join(' ')}${os.EOL}`;
return line;
}
const _log = console.log.bind(console);
const _err = console.error.bind(console);
const _warn = console.warn.bind(console);
console.log = (...args) => { rotateLogIfNeeded(); const line = stamp('INFO', args); try { logStream.write(line); } catch (_) {} _log(...args); };
console.warn = (...args) => { rotateLogIfNeeded(); const line = stamp('WARN', args); try { logStream.write(line); } catch (_) {} _warn(...args); };
console.error = (...args) => { rotateLogIfNeeded(); const line = stamp('ERROR', args); try { logStream.write(line); } catch (_) {} _err(...args); };
}
// Build enabled modules list (all modules in one list)
const enabledModules = [];
// Core API endpoints
if (config.apiv1Enabled !== false) enabledModules.push('API v1');
if (config.apiv2Enabled !== false) enabledModules.push('API v2');
if (config.livePageEnabled) enabledModules.push('Live Page');
if (config.websocketEnabled) enabledModules.push('WebSocket');
// Data source modules
if (config.clusterEnabled) enabledModules.push('DX Clusters');
if (config.includepotaspots) enabledModules.push('POTA');
if (config.includesotaspots) enabledModules.push('SOTA');
if (config.rbnEnabled) enabledModules.push('RBN');
// Support modules
if (config.persistenceEnabled) enabledModules.push('Persistence');
if (config.rateLimiterEnabled) enabledModules.push('Rate Limiter');
enabledModules.push('Metrics'); // Always enabled
if (config.analyticsEnabled) enabledModules.push('Analytics');
if (config.modeClassifierEnabled) enabledModules.push('Mode Classifier');
const moduleList = enabledModules.length > 0 ? enabledModules.join(', ') : 'None';
// Display startup banner
console.log('');
console.log('[Core] ════════════════════════════════════════════════════════════');
console.log('[Core] 🚀 DXClusterAPI Starting');
console.log('[Core] ════════════════════════════════════════════════════════════');
console.log('[Core] PID:', process.pid);
console.log('[Core] Node.js:', process.versions.node);
console.log('[Core] Mode:', config.mode);
console.log('[Core] Modules:', moduleList);
console.log('[Core] DXCC Cache:', config.dxccCacheMaxSize, 'max entries');
if (config.fileLoggingEnabled && logStream) {
console.log('[Core] Log file:', LOG_FILE);
}
console.log('[Core] ════════════════════════════════════════════════════════════');
console.log('');
/**
* Helper function to log messages to file and console
* @param {string} message - Message to log
* @param {string} level - Log level (INFO, WARN, ERROR)
*/
function logToFile(message, level = 'INFO') {
console.log('[Core] ' + message);
}
// ================================================================
// Express Middleware Setup
// ================================================================
morgan.token('remote-addr', function (req, res) {
var ffHeaderValue = req.headers['x-forwarded-for'];
return ffHeaderValue || req.connection.remoteAddress;
});
// Morgan stream for file logging
const morganStream = logStream ? {
write: (message) => {
try {
logStream.write(message.endsWith(os.EOL) ? message : message + os.EOL);
} catch (_) {}
}
} : null;
app.disable('x-powered-by');
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
// Also serve static files under BASEURL
if (config.baseUrl) {
app.use(config.baseUrl, express.static(path.join(__dirname, 'public')));
}
// Trust proxy - required when behind reverse proxy (Passenger, nginx, etc.)
// This allows express-rate-limit to correctly identify users via X-Forwarded-For header
if (config.trustProxy) {
app.set('trust proxy', true);
console.log('[Core] Trust proxy enabled - X-Forwarded-For headers will be respected');
}
// Add API version header to all responses
app.use((req, res, next) => {
res.setHeader('X-API-Version', APP_VERSION);
next();
});
// Skip logging for high-frequency endpoints to reduce noise
morgan.token('skip-logging', (req, res) => {
return (req.url.startsWith(config.baseUrl + '/spots') ||
req.url.startsWith(config.baseUrl + '/health') ||
req.url.startsWith(config.baseUrl + '/logs') ||
req.url.startsWith(config.baseUrl + '/stats') ||
req.url.startsWith(config.baseUrl + '/api/v2/bands') ||
req.url.startsWith(config.baseUrl + '/analytics') ||
req.url.startsWith(config.baseUrl + '/live')) ? 'skip' : null;
});
if (morganStream) {
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" :response-time ms', {
stream: morganStream,
skip: (req, res) => req.url.startsWith(config.baseUrl + '/spots') ||
req.url.startsWith(config.baseUrl + '/health') ||
req.url.startsWith(config.baseUrl + '/logs') ||
req.url.startsWith(config.baseUrl + '/stats') ||
req.url.startsWith(config.baseUrl + '/api/v2/bands') ||
req.url.startsWith(config.baseUrl + '/analytics') ||
req.url.startsWith(config.baseUrl + '/live')
}));
}
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" :response-time ms', {
skip: (req, res) => req.url.startsWith(config.baseUrl + '/spots') ||
req.url.startsWith(config.baseUrl + '/health') ||
req.url.startsWith(config.baseUrl + '/logs') ||
req.url.startsWith(config.baseUrl + '/stats') ||
req.url.startsWith(config.baseUrl + '/api/v2/bands') ||
req.url.startsWith(config.baseUrl + '/analytics') ||
req.url.startsWith(config.baseUrl + '/live')
}));
app.use(cors({ origin: '*' }));
// ================================================================
// DX Cluster Module
// ================================================================
// Initialize clusterManager FIRST, before other modules that depend on it
clusterManager = new Clusters(config.clusterEnabled, clusters);
if (config.clusterEnabled && clusters.length > 0) {
console.log(`[Clusters] Initializing ${clusters.length} DXCluster(s)`);
}
// ================================================================
// Rate Limiting Module
// ================================================================
const rateLimiter = new RateLimiter({
enabled: config.rateLimiterEnabled,
trustProxy: config.trustProxy,
generalMax: config.rateLimiterGeneralMax,
dataMax: config.rateLimiterDataMax,
banTimeMs: config.rateLimiterBanTime * 1000, // Convert seconds to ms
exemptPaths: [config.baseUrl + '/health', config.baseUrl + '/metrics']
});
// Apply general rate limiting to all routes
app.use(rateLimiter.middleware(config.baseUrl));
if (config.rateLimiterEnabled) {
console.log(`[RateLimiter] Initialized - General: ${config.rateLimiterGeneralMax}/min, Data: ${config.rateLimiterDataMax}/min, Ban: ${config.rateLimiterBanTime}s`);
}
// ================================================================
// Metrics Module
// ================================================================
// DXCC cache hit tracking for metrics
let dxccCacheHits = 0;
let dxccCacheMisses = 0;
const metrics = new Metrics({
enabled: true,
getSpotsData: () => spots,
getClusterStatus: () => clusterManager.getStatus(),
getWebSocketClients: () => wsClients ? wsClients.size : 0,
getDxccCacheStats: () => {
// Count failed entries in DXCC cache
let failedCount = 0;
for (const [, entry] of dxccCache.entries()) {
if (entry.failed) failedCount++;
}
const totalLookups = dxccCacheHits + dxccCacheMisses;
return {
size: dxccCache.size,
maxSize: DXCC_CACHE_MAX_SIZE,
failedEntries: failedCount,
hitRatio: totalLookups > 0 ? dxccCacheHits / totalLookups : 0,
spotsMaxSize: config.maxcache
};
},
getResponseCacheStats: () => ({
size: responseCache.size,
maxSize: RESPONSE_CACHE_MAX_SIZE
}),
getModeTypeStats: () => ({ ...modeTypeStats }),
getSourceStats: () => {
const stats = {};
for (const [source, spotSet] of sourceIndex.entries()) {
stats[source] = spotSet.size;
}
return stats;
}
});
// Apply metrics tracking middleware
app.use(metrics.middleware());
console.log('[Metrics] Metrics module initialized');
// ================================================================
// API Analytics Module
// ================================================================
const analytics = new Analytics({
enabled: config.analyticsEnabled,
dataFile: path.join(__dirname, 'data', 'analytics.json'),
saveInterval: 5 * 60 * 1000, // 5 minutes
skipPaths: ['/health', '/info', '/analytics', '/logs', '/metrics', '/live']
});
// Apply analytics tracking middleware
app.use(analytics.middleware());
// ================================================================
// API v1 Module (Legacy)
// ================================================================
const apiv1 = new APIv1(
config,
() => spots,
() => ({ bandIndex, frequencyIndex, sourceIndex })
);
// Mount API v1 router if enabled
if (config.apiv1Enabled) {
app.use(apiv1.createRouter(rateLimiter.getDataLimiter(), responseCacheMiddleware(55 * 1000)));
console.log('[Core] API v1 endpoints enabled with rate limiting and 55-second response cache');
} else {
console.log('[Core] API v1 endpoints disabled');
}
// ================================================================
// API v2 Module
// ================================================================
const apiv2 = new APIv2({
enabled: config.apiv2Enabled,
apiKey: config.apiv2Key,
version: APP_VERSION,
getSpotsData: () => spots,
apiSpotLimit: config.apiSpotLimit
});
// Mount API v2 router if enabled
if (config.apiv2Enabled) {
app.use(config.baseUrl + '/api/v2', apiv2.createRouter(rateLimiter.getDataLimiter(), responseCacheMiddleware(55 * 1000)));
console.log('[Core] API v2 enabled at ' + config.baseUrl + '/api/v2' + (apiv2.getStatus().requiresAuth ? ' (authentication required)' : ' (no authentication)') + ' with rate limiting and 55-second response cache');
} else {
console.log('[Core] API v2 disabled');
}
// ================================================================
// DXCC Lookup Debug Endpoint (for live page debugging tool)
// ================================================================
/**
* GET /api/v2/dxcc/:callsign - Debug endpoint for DXCC lookup
* Performs a DXCC lookup using the configured Wavelog API and returns the result
* This endpoint is for debugging purposes only
*/
app.get(config.baseUrl + '/api/v2/dxcc/:callsign', async (req, res) => {
const callsign = req.params.callsign?.toUpperCase().trim();
if (!callsign) {
return res.status(400).json({
status: 'error',
error: 'Callsign is required',
data: null
});
}
// Validate callsign format
const callsignRegex = /^[A-Z0-9\/\-]{2,20}$/i;
if (!callsignRegex.test(callsign)) {
return res.status(400).json({
status: 'error',
error: 'Invalid callsign format',
data: null
});
}
// Check if DXCC lookup is configured
if (!config.dxcc_lookup_wavelog_url || !config.dxcc_lookup_wavelog_key) {
return res.status(503).json({
status: 'error',
error: 'DXCC lookup not configured (missing WAVELOG_URL or WAVELOG_KEY)',
data: null
});
}
try {
const startTime = Date.now();
const normalizedCall = normalizeCallsign(callsign);
// Check cache first
const cached = dxccCache.get(normalizedCall);
const fromCache = cached && (Date.now() - cached.timestamp < DXCC_CACHE_TTL);
let result;
if (fromCache) {
result = cached.data;
} else {
result = await dxcc_lookup(callsign);
}
const duration = Date.now() - startTime;
// Check if lookup failed
const cacheEntry = dxccCache.get(normalizedCall);
const lookupFailed = cacheEntry?.failed === true;
res.json({
status: lookupFailed ? 'failed' : 'success',
version: APP_VERSION,
timestamp: new Date().toISOString(),
data: {
callsign: callsign,
normalizedCallsign: normalizedCall,
dxcc: result,
lookupServer: config.dxcc_lookup_wavelog_url
},
meta: {
fromCache: fromCache,
cacheAge: fromCache ? Math.round((Date.now() - cached.timestamp) / 1000) : null,
lookupDuration: duration,
failReason: lookupFailed ? cacheEntry.failReason : null
}
});
} catch (error) {
console.error('[DXCC Debug] Lookup error:', error);
res.status(500).json({
status: 'error',
error: error.message,
data: null
});
}
});
/**
* DELETE /api/v2/dxcc/:callsign/cache - Remove a callsign from the DXCC cache
* This allows forcing a fresh lookup from the Wavelog API
*/
app.delete(config.baseUrl + '/api/v2/dxcc/:callsign/cache', (req, res) => {
const callsign = req.params.callsign?.toUpperCase().trim();
if (!callsign) {
return res.status(400).json({
status: 'error',
error: 'Callsign is required',
data: null
});
}
const normalizedCall = normalizeCallsign(callsign);
// Check if entry exists in cache
const existed = dxccCache.has(normalizedCall);
if (existed) {
dxccCache.delete(normalizedCall);
console.log(`[DXCC Debug] Cache entry removed for: ${callsign} (normalized: ${normalizedCall})`);
}
res.json({
status: 'success',
message: existed
? `Cache entry for ${callsign} has been removed`
: `No cache entry found for ${callsign} (nothing to remove)`,
data: {
callsign: callsign,
normalizedCallsign: normalizedCall,
wasInCache: existed
}
});
});
// ================================================================
// Routes
// ================================================================
// API Information function (shared by / and /info)
function getApiInfo() {
const endpoints = {};
// API v1 endpoints (if enabled)
if (config.apiv1Enabled) {
endpoints.v1 = apiv1.getEndpoints();
}
// API v2 endpoints (if enabled)
if (config.apiv2Enabled) {
endpoints.v2 = apiv2.getEndpoints(config.baseUrl);
}
// Common endpoints
endpoints.health = config.baseUrl + '/health';
endpoints.metrics = config.baseUrl + '/metrics';
endpoints.logs = config.baseUrl + '/logs';
if (config.analyticsEnabled) {
endpoints.analytics = config.baseUrl + '/analytics';
}
endpoints.info = config.baseUrl + '/info';
// Only include live page endpoint if enabled
if (config.livePageEnabled) {
endpoints.live = config.baseUrl + '/live';
}
return {
name: 'DXClusterAPI',
version: APP_VERSION,
description: 'Real-time DX Cluster, POTA, and SOTA spot aggregation API',
apis: {
v1: config.apiv1Enabled,
v2: config.apiv2Enabled
},
endpoints: endpoints,
documentation: 'https://github.com/int2001/DXClusterAPI'
};
}
// Root endpoint - API information
app.get(config.baseUrl + '/', (req, res) => {
res.json(getApiInfo());
});
// Info endpoint - Same as root, useful when root is served by web server
app.get(config.baseUrl + '/info', (req, res) => {
res.json(getApiInfo());
});
// Serve live page - only if enabled
if (config.livePageEnabled) {
const livePagePath = path.join(__dirname, 'views', 'live', 'index.html');
// Live page route with authentication
app.get(config.baseUrl + '/live', (req, res) => {
// HTTP Basic Authentication (if password is set)
if (config.livePagePassword) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Basic ')) {
res.setHeader('WWW-Authenticate', 'Basic realm="DXClusterAPI Live Monitor"');
return res.status(401).send('Authentication required');
}
// Decode Basic Auth credentials
const base64Credentials = authHeader.split(' ')[1];
const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
const [username, password] = credentials.split(':');
// Verify password (username is ignored)
if (password !== config.livePagePassword) {
res.setHeader('WWW-Authenticate', 'Basic realm="DXClusterAPI Live Monitor"');
return res.status(401).send('Invalid password');
}
}
// Set no-cache and no-index headers
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, private');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
res.setHeader('X-Robots-Tag', 'noindex, nofollow, noarchive, nosnippet');
// Read HTML file and inject BASEURL for Socket.IO library
let htmlContent = fs.readFileSync(livePagePath, 'utf8');
// Replace hardcoded Socket.IO path with BASEURL-prefixed path
htmlContent = htmlContent.replace(
'src="/js/socket.io.min.js"',
`src="${config.baseUrl}/js/socket.io.min.js"`
);
res.send(htmlContent);
});
console.log('[Core] Live page enabled at ' + config.baseUrl + '/live' +
(config.livePagePassword ? ' (password protected)' : ''));
} else {
console.log('[Core] Live page disabled');
}
/**
* Middleware function to check for LIVE_PAGE_PASSWORD authentication
* @param {object} req - Express request object
* @param {object} res - Express response object
* @param {function} next - Express next function
*/
function checkLivePagePassword(req, res, next) {
// If no password is configured, allow access
if (!config.livePagePassword) {
return next();
}
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Basic ')) {
res.setHeader('WWW-Authenticate', 'Basic realm="DXClusterAPI Analytics"');
return res.status(401).json({ error: 'Authentication required' });
}
// Decode Basic Auth credentials
const base64Credentials = authHeader.split(' ')[1];
const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
const [username, password] = credentials.split(':');
// Verify password (username is ignored)
if (password !== config.livePagePassword) {
res.setHeader('WWW-Authenticate', 'Basic realm="DXClusterAPI Analytics"');
return res.status(401).json({ error: 'Invalid password' });
}
next();
}
// API Analytics endpoint - shows who is using the API (password protected if LIVE_PAGE_PASSWORD is set)
app.get(config.baseUrl + '/analytics', checkLivePagePassword, (req, res) => {
res.json(analytics.getSummary());
});
// -----------------------------------
// DXCluster Spot Handling
// -----------------------------------
/**
* Broadcasts a new spot to all connected Socket.IO clients
*/
function broadcastSpot(spot) {
if (wsClients.size === 0) return;
const message = {
type: 'spot',
data: spot,
timestamp: new Date().toISOString()
};
// Broadcast to all connected Socket.IO clients
io.emit('spot', message);
}
// Hook up cluster spot events to handlespot function
clusterManager.on('spot', async (spot, source) => {
await handlespot(spot, source);
});
// -----------------------------------
// API Endpoints
// -----------------------------------
/**
* GET /stats - Retrieve statistics about the cached spots.
*/
/**
* GET /stats - Retrieve statistics about cached spots.
*/
app.get(config.baseUrl + '/stats', (req, res) => {
// Build source breakdown from sourceIndex (already O(1))
const sources = {};
sourceIndex.forEach((spotSet, sourceName) => {
sources[sourceName] = spotSet.size;
});
// Get mode types and continents from indexes (O(1) - no iteration!)
// These are updated in real-time as spots are added/removed
// Legacy counts (for backward compatibility) - use sourceIndex instead of filter
const potaCount = sourceIndex.get('pota')?.size || 0;
const sotaCount = sourceIndex.get('sota')?.size || 0;
const clusterSpots = spots.length - potaCount - sotaCount;
const stats = {
entries: spots.length,
cluster: clusterSpots,
pota: potaCount,
sota: sotaCount,
sources: sources, // Per-source breakdown
modeTypes: modeTypeStats, // Mode type breakdown (phone/digi/cw) - from index
continents: continentStats, // DX continent breakdown - from index
continents_de: continentDeStats, // DE (spotter) continent breakdown - from index
freshest: getFreshestSpot(spots),
oldest: getOldestSpot(spots)
};
res.json(stats);
});
/**
* GET /health - Health check endpoint for monitoring and load balancers.
*/
app.get(config.baseUrl + '/health', (req, res) => {
const clusterStatus = clusterManager.getStatus();
const mem = process.memoryUsage();
const health = {
status: 'ok',
version: APP_VERSION,
timestamp: new Date().toISOString(),
uptime: process.uptime(),
uptimeFormatted: formatUptime(process.uptime()),
mode: config.mode,
memory: {
heapUsed: Math.round(mem.heapUsed / 1024 / 1024),
heapTotal: Math.round(mem.heapTotal / 1024 / 1024),
rss: Math.round(mem.rss / 1024 / 1024),
external: Math.round(mem.external / 1024 / 1024),
arrayBuffers: Math.round((mem.arrayBuffers || 0) / 1024 / 1024)
},
cache: {
spots: spots.length,
maxcache: config.maxcache,
apiSpotLimit: config.apiSpotLimit,
dxccCache: dxccCache.size,
dxccCacheMaxSize: DXCC_CACHE_MAX_SIZE,
responseCache: responseCache.size,
bandIndex: bandIndex.size,
frequencyIndex: frequencyIndex.size,
sourceIndex: sourceIndex.size,
spotKeyIndex: spotKeyIndex.size,
websocketClients: wsClients.size
},
modules: {
cluster: {
enabled: config.clusterEnabled,
totalClusters: clusterStatus.totalClusters,
activeConnections: clusterStatus.activeConnections
},
pota: config.includepotaspots,
sota: config.includesotaspots,
rbn: config.rbnEnabled ? {
enabled: true,
callsign: config.rbnCallsign,
stats: typeof rbn !== 'undefined' ? rbn.getStats() : null
} : false,
enrichment: config.enrichmentEnabled,
modeClassifier: config.modeClassifierEnabled ? {
enabled: true,
stats: modeClassifier ? modeClassifier.getStats() : null
} : false,
analytics: config.analyticsEnabled,
websocket: config.websocketEnabled,
livePage: {
enabled: config.livePageEnabled,
passwordProtected: config.livePagePassword && config.livePagePassword.length > 0
},
metrics: metrics.getStatus(),
rateLimiter: rateLimiter.getStatus(),
persistence: config.persistenceEnabled ? {
enabled: true,
stats: persistenceController ? persistenceController.getStats() : null
} : false,
apiv1: {
enabled: config.apiv1Enabled
},
apiv2: {
enabled: config.apiv2Enabled,
requiresAuth: config.apiv2Key && config.apiv2Key.length > 0
}
}
};
res.json(health);
});
/**
* GET /metrics - Prometheus metrics endpoint
*/
app.get(config.baseUrl + '/metrics', async (req, res) => {
try {
const metricsData = await metrics.getMetrics();
res.set('Content-Type', metrics.getContentType());
res.end(metricsData);
} catch (error) {
console.error('[Core] Error generating metrics:', error);
res.status(500).json({ error: 'Failed to generate metrics' });
}
});
/**
* GET /logs - Retrieve recent log entries (last 1000 lines)
* Only available when file logging is enabled
*/
app.get(config.baseUrl + '/logs', (req, res) => {
if (!config.fileLoggingEnabled) {
return res.status(503).json({ error: 'File logging is not enabled' });
}
try {
// Ensure log rotation happens so today's log file exists
rotateLogIfNeeded();
const logFile = path.join(LOG_DIR, `app-${fmtLogDate(new Date())}.log`);
if (!fs.existsSync(logFile)) {
return res.json({ logs: [], message: 'No log file found for today' });
}
// Read log file and get last 1000 lines
const logContent = fs.readFileSync(logFile, 'utf8');
const lines = logContent.split('\n').filter(line => line.trim());
const recentLines = lines.slice(-1000);
res.json({
logs: recentLines,
total: lines.length,
showing: recentLines.length,
file: path.basename(logFile)
});
} catch (error) {
console.error('[Core] Error reading log file:', error);
res.status(500).json({ error: 'Failed to read log file' });
}
});
// -----------------------------------
// Server Start
// -----------------------------------
/**
* Initializes Socket.IO server on an existing HTTP server
*/
function initializeWebSocket(server) {
if (!config.websocketEnabled) {