-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathwebserver.js
More file actions
1807 lines (1563 loc) · 63.4 KB
/
webserver.js
File metadata and controls
1807 lines (1563 loc) · 63.4 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
// webserver.js - Web interface for viewing and managing calls with optional authentication
require('dotenv').config();
const AWS = require('aws-sdk'); // Add AWS SDK
const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const path = require('path');
const http = require('http');
const socketIo = require('socket.io');
const crypto = require('crypto');
const fetch = require('node-fetch');
const fs = require('fs');
const logsDir = path.join(__dirname, 'logs');
if (!fs.existsSync(logsDir)) {
fs.mkdirSync(logsDir, { recursive: true });
}
// Environment variables
const {
WEBSERVER_PORT,
WEBSERVER_PASSWORD,
PUBLIC_DOMAIN,
TIMEZONE,
ENABLE_AUTH, // New environment variable for toggling authentication
SESSION_DURATION_DAYS = "7", // Default 7 days if not specified
MAX_SESSIONS_PER_USER = "5", // Default 5 sessions if not specified
GOOGLE_MAPS_API_KEY = null,
// --- NEW: Geocoding API Keys ---
LOCATIONIQ_API_KEY = null,
// --- NEW: Storage Env Vars ---
STORAGE_MODE = 'local', // Default to local if not set
S3_ENDPOINT,
S3_BUCKET_NAME,
S3_ACCESS_KEY_ID,
S3_SECRET_ACCESS_KEY,
// --- NEW: AI Provider Env Vars ---
AI_PROVIDER = 'ollama', // Can be 'ollama' or 'openai'
OPENAI_API_KEY,
OPENAI_MODEL = 'gpt-4o-mini', // A good, fast, and cheap model for this task
OLLAMA_URL = 'http://localhost:11434',
OLLAMA_MODEL = 'llama3.1:8b'
} = process.env;
// Validate required environment variables
const requiredVars = ['WEBSERVER_PORT', 'PUBLIC_DOMAIN'];
const missingVars = requiredVars.filter(varName => !process.env[varName]);
if (missingVars.length > 0) {
console.error(`ERROR: Missing required environment variables: ${missingVars.join(', ')}`);
process.exit(1);
}
// Check for at least one geocoding API key
if (!GOOGLE_MAPS_API_KEY && !LOCATIONIQ_API_KEY) {
console.error('ERROR: At least one geocoding API key is required (GOOGLE_MAPS_API_KEY or LOCATIONIQ_API_KEY)');
process.exit(1);
}
// Log geocoding API availability
if (GOOGLE_MAPS_API_KEY) {
console.log('[Webserver] Google Maps API key found - Google Places autocomplete will be available');
} else {
console.log('[Webserver] Google Maps API key not found - Google Places autocomplete will be disabled');
}
if (LOCATIONIQ_API_KEY) {
console.log('[Webserver] LocationIQ API key found - LocationIQ autocomplete will be available');
} else {
console.log('[Webserver] LocationIQ API key not found - LocationIQ autocomplete will be disabled');
}
// Add endpoint to serve Google API key
const app = express();
app.use(express.json()); // Add this line to parse JSON bodies
app.get('/api/config/google-api-key', (req, res) => {
res.json({ apiKey: GOOGLE_MAPS_API_KEY });
});
// Add endpoint to serve LocationIQ API key
app.get('/api/config/locationiq-api-key', (req, res) => {
res.json({ apiKey: LOCATIONIQ_API_KEY });
});
// Add endpoint to serve all geocoding configuration
app.get('/api/config/geocoding', (req, res) => {
res.json({
google: {
available: !!GOOGLE_MAPS_API_KEY,
apiKey: GOOGLE_MAPS_API_KEY
},
locationiq: {
available: !!LOCATIONIQ_API_KEY,
apiKey: LOCATIONIQ_API_KEY
}
});
});
// Add endpoint to check if current user is admin
app.get('/api/auth/is-admin', async (req, res) => {
if (!authEnabled) {
return res.json({ isAdmin: false, authEnabled: false });
}
const authHeader = req.headers['authorization'];
const adminStatus = await isAdminUser(authHeader);
res.json({ isAdmin: adminStatus, authEnabled: true });
});
// Test endpoint to verify server is working
app.get('/api/test', (req, res) => {
res.json({ message: 'Server is working', timestamp: Date.now() });
});
// --- NEW: S3 Client Setup ---
let s3 = null;
if (STORAGE_MODE === 's3') {
if (!S3_ENDPOINT || !S3_BUCKET_NAME || !S3_ACCESS_KEY_ID || !S3_SECRET_ACCESS_KEY) {
console.error('FATAL: STORAGE_MODE is s3, but required S3 environment variables are missing! Check webserver .env');
process.exit(1); // Exit if S3 config is incomplete
}
AWS.config.update({
accessKeyId: S3_ACCESS_KEY_ID,
secretAccessKey: S3_SECRET_ACCESS_KEY,
endpoint: S3_ENDPOINT,
s3ForcePathStyle: true, // Necessary for MinIO/non-AWS S3
signatureVersion: 'v4'
});
s3 = new AWS.S3();
console.log(`[Webserver] Storage mode set to S3. Endpoint: ${S3_ENDPOINT}, Bucket: ${S3_BUCKET_NAME}`);
} else {
console.log('[Webserver] Storage mode set to local.');
}
// Authentication is enabled if ENABLE_AUTH=true
const authEnabled = ENABLE_AUTH?.toLowerCase() === 'true';
// Session configuration (used only if auth is enabled)
const SESSION_DURATION = parseInt(SESSION_DURATION_DAYS, 10) * 24 * 60 * 60 * 1000; // Convert days to milliseconds
const MAX_SESSIONS = parseInt(MAX_SESSIONS_PER_USER, 10);
const SESSION_CLEANUP_INTERVAL = 60 * 60 * 1000; // Cleanup every hour
// Express app setup
const server = http.createServer(app);
const io = socketIo(server);
// Database setup
const db = new sqlite3.Database('./botdata.db', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error('Error opening database', err.message);
} else {
console.log('Connected to the SQLite database.');
}
});
db.run(`ALTER TABLE transcriptions ADD COLUMN category TEXT`, err => {
// Ignore error if column already exists
if (!err || err.message.includes('duplicate column name')) {
console.log('Category column exists or was created successfully');
}
});
// Create authentication tables if authentication is enabled
if (authEnabled) {
db.serialize(() => {
// Users table
db.run(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
salt TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
// Sessions table
db.run(`
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
token TEXT UNIQUE NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
expires_at DATETIME NOT NULL,
last_activity DATETIME DEFAULT CURRENT_TIMESTAMP,
ip_address TEXT,
user_agent TEXT,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
`);
});
}
// Helper Functions for Authentication
function hashPassword(password, salt) {
return crypto
.pbkdf2Sync(password, salt, 10000, 64, 'sha512')
.toString('hex');
}
function generateSessionToken() {
return crypto.randomBytes(32).toString('hex');
}
// Session Management Functions
async function createSession(userId, req) {
const token = generateSessionToken();
const expiresAt = new Date(Date.now() + SESSION_DURATION);
const ipAddress = req.ip;
const userAgent = req.get('user-agent');
return new Promise((resolve, reject) => {
db.run(
`INSERT INTO sessions (user_id, token, expires_at, ip_address, user_agent)
VALUES (?, ?, datetime(?), ?, ?)`,
[userId, token, expiresAt.toISOString(), ipAddress, userAgent],
function(err) {
if (err) reject(err);
else resolve({ token, expiresAt });
}
);
});
}
async function validateSession(token) {
return new Promise((resolve, reject) => {
db.get(
`SELECT * FROM sessions
WHERE token = ? AND expires_at > datetime('now')`,
[token],
(err, session) => {
if (err) reject(err);
else resolve(session);
}
);
});
}
async function generateShortSummary(transcript) {
try {
// Original list of categories for the AI
const categories = [
'Medical Emergency', 'Injured Person', 'Disturbance', 'Vehicle Collision',
'Burglary', 'Assault', 'Structure Fire', 'Missing Person', 'Medical Call',
'Building Fire', 'Stolen Vehicle', 'Service Call', 'Vehicle Stop',
'Unconscious Person', 'Reckless Driver', 'Person With A Gun',
'Altered Level of Consciousness', 'Breathing Problems', 'Fight',
'Carbon Monoxide', 'Abduction', 'Passed Out Person', 'Hazmat',
'Fire Alarm', 'Traffic Hazard', 'Intoxicated Person', 'Mvc', // Note: Mvc is often redundant with Vehicle Collision
'Animal Bite',
'Assist'
];
// This prompt works well for both Ollama and OpenAI's chat models
const commonPrompt = `
You are an expert emergency service dispatcher categorizing radio transmissions.
Analyze the following first responder radio transmission and categorize it into EXACTLY ONE of the categories listed below.
Choose the category that best fits the main subject of the transmission.
Focus on the primary reason for the dispatch if multiple events are mentioned.
**PRIORITIZATION:**
- If a clear event type (like Vehicle Collision, Fire, Assault, Medical Emergency, etc.) is mentioned, **use that category even if the dispatcher says "no details"** or the information is minimal. do not add stars around your output such as "**GAS LEAK**".
- Use the 'Other' category ONLY if the transmission primarily contains just location/unit information OR if no specific event type from the list is mentioned at all.
It is CRUCIAL that your response is ONLY one of the category names from this list and nothing else.
Categories:
${categories.map(cat => `- ${cat}`).join('\n')}
- Other
Transmission: "${transcript}"
Category:`;
let category = 'OTHER'; // Default value
const controller = new AbortController();
const timeoutId = setTimeout(() => {
console.warn(`[Webserver] AI request timed out after 10 seconds during categorization.`);
controller.abort();
}, 10000); // 10-second timeout
// --- AI Provider Logic ---
if (AI_PROVIDER.toLowerCase() === 'openai') {
if (!OPENAI_API_KEY) {
console.error('[Webserver] FATAL: AI_PROVIDER is set to openai, but OPENAI_API_KEY is not configured!');
return 'OTHER'; // Fallback if key is missing
}
console.log(`[Webserver] Categorizing with OpenAI model: ${OPENAI_MODEL}`);
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${OPENAI_API_KEY}`
},
body: JSON.stringify({
model: OPENAI_MODEL,
messages: [{ role: 'user', content: commonPrompt }],
temperature: 0.2, // Lower temp for more deterministic category
max_tokens: 20 // A category name is short
}),
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
const errorText = await response.text();
console.error(`[Webserver] OpenAI API error! status: ${response.status}, transcript: ${transcript}, details: ${errorText}`);
throw new Error(`OpenAI API error! status: ${response.status}`);
}
const result = await response.json();
if (result.choices && result.choices.length > 0 && result.choices[0].message) {
category = result.choices[0].message.content.trim();
}
} else { // Default to Ollama
console.log(`[Webserver] Categorizing with Ollama model: ${OLLAMA_MODEL}`);
const response = await fetch(`${OLLAMA_URL}/api/generate`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
model: OLLAMA_MODEL,
prompt: commonPrompt, // The prompt is compatible
stream: false,
options: {
temperature: 0.3
}
}),
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
console.error(`[Webserver] Ollama API error! status: ${response.status} for transcript: ${transcript}`);
throw new Error(`Ollama API error! status: ${response.status}`);
}
const result = await response.json();
category = result.response.trim();
}
// --- End AI Provider Logic ---
// The existing post-processing logic is generic enough to work for both
const thinkBlockRegex = /<think>[\s\S]*?<\/think>\s*/;
category = category.replace(thinkBlockRegex, '').trim().toUpperCase();
// Validate the AI's response against the known categories (including OTHER)
const validCategoriesUppercase = categories.map(cat => cat.toUpperCase());
validCategoriesUppercase.push('OTHER');
if (!validCategoriesUppercase.includes(category)) {
console.warn(`[Webserver] AI returned an unexpected or invalid category: "${category}". Defaulting to OTHER for transcript: "${transcript}"`);
category = 'OTHER';
}
return category;
} catch (error) {
console.error(`[Webserver] Error categorizing call: "${transcript}". Error: ${error.message}`);
if (error.name === 'AbortError') {
console.error(`[Webserver] AI request timed out during categorization: ${error.message}`);
}
return 'OTHER'; // Fallback to 'OTHER' in case of any errors
}
}
function cleanupExpiredSessions() {
if (authEnabled) {
db.run('DELETE FROM sessions WHERE expires_at <= datetime("now")', [], (err) => {
if (err) {
console.error('Error cleaning up expired sessions:', err);
} else {
console.log('Expired sessions cleaned up');
}
});
}
}
// Start session cleanup interval if auth enabled
if (authEnabled) {
setInterval(cleanupExpiredSessions, SESSION_CLEANUP_INTERVAL);
}
// Authentication Middleware - only applied when authentication is enabled
const basicAuth = async (req, res, next) => {
// Skip authentication if disabled in .env
if (!authEnabled) {
return next();
}
try {
const authHeader = req.headers['authorization'];
if (!authHeader) {
res.set('WWW-Authenticate', 'Basic realm="Protected Area"');
return res.status(401).send('Authentication required.');
}
// Check if it's a Bearer token (session-based auth)
if (authHeader.startsWith('Bearer ')) {
const token = authHeader.split(' ')[1];
if (!token) {
return res.status(401).send('Invalid Bearer token format.');
}
// Validate the session token
const session = await validateSession(token);
if (!session) {
return res.status(401).send('Invalid or expired session token.');
}
// Get the user from the session
const user = await new Promise((resolve, reject) => {
db.get('SELECT id, username FROM users WHERE id = ?', [session.user_id], (err, row) => {
if (err) reject(err);
else resolve(row);
});
});
if (!user) {
return res.status(401).send('User not found for session.');
}
// Set user info in request for downstream use
req.user = { id: user.id, username: user.username };
req.session = session;
return next();
}
// Check if it's Basic auth (username:password)
if (authHeader.startsWith('Basic ')) {
const base64Credentials = authHeader.split(' ')[1];
if (!base64Credentials) {
res.set('WWW-Authenticate', 'Basic realm="Protected Area"');
return res.status(401).send('Invalid authentication format.');
}
const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
const [username, password] = credentials.split(':');
// Check credentials against database
db.get(
'SELECT id, password_hash, salt FROM users WHERE username = ?',
[username],
async (err, user) => {
if (err) {
console.error('Database error during authentication:', err);
return res.status(500).send('Internal server error.');
}
if (!user) {
res.set('WWW-Authenticate', 'Basic realm="Protected Area"');
return res.status(401).send('Invalid credentials.');
}
const hashedPassword = hashPassword(password, user.salt);
if (hashedPassword === user.password_hash) {
// Get all active sessions for user, ordered by creation date
db.all(
`SELECT id, created_at, expires_at
FROM sessions
WHERE user_id = ? AND expires_at > datetime('now')
ORDER BY created_at ASC`,
[user.id],
async (err, sessions) => {
if (err) {
return res.status(500).send('Internal server error.');
}
// If at session limit, remove oldest session
if (sessions.length >= MAX_SESSIONS) {
db.run(
'DELETE FROM sessions WHERE id = ?',
[sessions[0].id],
async (err) => {
if (err) {
console.error('Error removing oldest session:', err);
return res.status(500).send('Internal server error.');
}
console.log(`Removed oldest session for user ${username}`);
try {
const session = await createSession(user.id, req);
req.user = { id: user.id, username };
req.session = session;
next();
} catch (err) {
console.error('Error creating session:', err);
return res.status(500).send('Internal server error.');
}
}
);
} else {
try {
const session = await createSession(user.id, req);
req.user = { id: user.id, username };
req.session = session;
next();
} catch (err) {
console.error('Error creating session:', err);
return res.status(500).send('Internal server error.');
}
}
}
);
} else {
res.set('WWW-Authenticate', 'Basic realm="Protected Area"');
return res.status(401).send('Invalid credentials.');
}
}
);
} else {
return res.status(401).send('Unsupported authentication method. Use Basic or Bearer.');
}
} catch (err) {
console.error('Authentication error:', err);
return res.status(500).send('Internal server error.');
}
};
// Admin Authentication Middleware
const adminAuth = (req, res, next) => {
// Skip authentication if disabled in .env
if (!authEnabled) {
return next();
}
const authHeader = req.headers['authorization'];
if (!authHeader) {
return res.status(401).send('Admin authentication required.');
}
const base64Credentials = authHeader.split(' ')[1];
const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
const [username, password] = credentials.split(':');
if (username === 'admin' && password === WEBSERVER_PASSWORD) {
next();
} else {
return res.status(401).send('Invalid admin credentials.');
}
};
// Helper function to check if user is admin
async function isAdminUser(authHeader) {
if (!authEnabled || !authHeader) {
return false;
}
try {
// Check if it's a Bearer token (session-based auth)
if (authHeader.startsWith('Bearer ')) {
const token = authHeader.split(' ')[1];
if (!token) {
return false;
}
// Validate the session token
const session = await validateSession(token);
if (!session) {
return false;
}
// Get the user from the session
const user = await new Promise((resolve, reject) => {
db.get('SELECT username FROM users WHERE id = ?', [session.user_id], (err, row) => {
if (err) reject(err);
else resolve(row);
});
});
// Check if the user is admin
return user && user.username === 'admin';
}
// Check if it's Basic auth (username:password)
if (authHeader.startsWith('Basic ')) {
const base64Credentials = authHeader.split(' ')[1];
if (!base64Credentials) {
return false;
}
const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
const [username, password] = credentials.split(':');
return username === 'admin' && password === WEBSERVER_PASSWORD;
}
return false;
} catch (error) {
console.error('Error in isAdminUser:', error);
return false;
}
}
// --- NEW HELPER FUNCTION ---
// Store the last purge operation details for undo functionality
let lastPurgeDetails = null;
// Function to store original coordinates before purging
async function storeOriginalCoordinates(talkgroupIds, categories, timeRangeStart, timeRangeEnd) {
return new Promise((resolve, reject) => {
// Build the WHERE clause to get calls that will be purged
let whereConditions = ['lat IS NOT NULL AND lon IS NOT NULL'];
let params = [];
// If no talkgroups selected, it means "all talkgroups" (no filter applied)
if (talkgroupIds && talkgroupIds.length > 0) {
whereConditions.push(`talk_group_id IN (${talkgroupIds.map(() => '?').join(',')})`);
params.push(...talkgroupIds);
}
// If no talkgroups selected, don't add any filter - this means "all talkgroups"
if (categories && categories.length > 0) {
whereConditions.push(`UPPER(category) IN (${categories.map(() => 'UPPER(?)').join(',')})`);
params.push(...categories);
}
whereConditions.push('timestamp BETWEEN ? AND ?');
params.push(timeRangeStart, timeRangeEnd);
const whereClause = whereConditions.join(' AND ');
const selectQuery = `SELECT id, lat, lon FROM transcriptions WHERE ${whereClause}`;
db.all(selectQuery, params, (err, rows) => {
if (err) {
reject(err);
} else {
resolve(rows);
}
});
});
}
async function serveAudioFromDb(res, transcriptionId) {
console.log(`[Audio DB] Serving audio for ID ${transcriptionId} from database blob.`);
try {
const audioRow = await new Promise((resolve, reject) => {
db.get('SELECT audio_data FROM audio_files WHERE transcription_id = ?', [transcriptionId], (err, row) => {
if (err) reject(err);
else resolve(row);
});
});
if (audioRow && audioRow.audio_data) {
const pathRow = await new Promise((resolve, reject) => {
db.get('SELECT audio_file_path FROM transcriptions WHERE id = ?', [transcriptionId], (err, row) => {
if (err) reject(err); else resolve(row);
});
});
const filePath = pathRow ? pathRow.audio_file_path : '';
const extension = path.extname(filePath).toLowerCase();
const contentType = extension === '.m4a' ? 'audio/mp4' : 'audio/mpeg';
res.setHeader('Content-Type', contentType);
res.send(audioRow.audio_data);
} else {
console.error(`[Audio DB] Audio data not found in DB for ID: ${transcriptionId}`);
if (!res.headersSent) {
res.status(404).send('Audio not found in any storage location.');
}
}
} catch (dbErr) {
console.error(`[Audio DB] DB error for ID ${transcriptionId}:`, dbErr);
if (!res.headersSent) {
res.status(500).send('Internal Server Error during DB fallback.');
}
}
}
// Public Routes (No Auth Required)
app.get('/audio/:id', async (req, res) => {
const transcriptionId = req.params.id;
try {
const transcriptionRow = await new Promise((resolve, reject) => {
db.get('SELECT audio_file_path FROM transcriptions WHERE id = ?', [transcriptionId], (err, row) => {
if (err) reject(err);
else resolve(row);
});
});
if (transcriptionRow && transcriptionRow.audio_file_path) {
const audioStoragePath = transcriptionRow.audio_file_path;
const extension = path.extname(audioStoragePath).toLowerCase();
const contentType = extension === '.m4a' ? 'audio/mp4' : 'audio/mpeg';
if (STORAGE_MODE === 's3') {
const params = { Bucket: S3_BUCKET_NAME, Key: audioStoragePath };
const s3Stream = s3.getObject(params).createReadStream();
s3Stream.on('error', (s3Err) => {
console.warn(`[Audio S3] S3 stream error for key ${audioStoragePath}: ${s3Err.code}. Falling back to DB.`);
serveAudioFromDb(res, transcriptionId);
});
res.setHeader('Content-Type', contentType);
s3Stream.pipe(res);
return;
} else { // Local storage
const localPath = path.join(__dirname, 'audio', audioStoragePath);
if (fs.existsSync(localPath)) {
res.setHeader('Content-Type', contentType);
fs.createReadStream(localPath).pipe(res);
return;
} else {
console.warn(`[Audio Local] File not found at ${localPath}. Falling back to DB.`);
}
}
}
// Fallback to serving from the database blob if file not found or path missing.
serveAudioFromDb(res, transcriptionId);
} catch (dbErr) {
console.error('[Audio Request] Database error:', dbErr);
return res.status(500).send('Internal Server Error');
}
});
// Apply authentication middleware to protected routes if auth is enabled
app.use(basicAuth);
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
// Session Management Routes (Only relevant when auth is enabled)
app.get('/api/sessions/current', (req, res) => {
if (authEnabled) {
res.json({
session: req.session || null,
user: req.user || null
});
} else {
res.json({
session: { token: 'anonymous-session' },
user: { username: 'anonymous' }
});
}
});
app.get('/api/sessions', adminAuth, (req, res) => {
if (!authEnabled) {
return res.json([]);
}
const userId = req.query.userId;
let query = `
SELECT s.*, u.username, s.ip_address, s.user_agent
FROM sessions s
JOIN users u ON s.user_id = u.id
WHERE s.expires_at > datetime('now')
`;
const params = [];
if (userId && userId !== 'all') {
query += ' AND s.user_id = ?';
params.push(userId);
}
query += ' ORDER BY s.created_at DESC';
db.all(query, params, (err, sessions) => {
if (err) {
console.error('Error fetching sessions:', err);
return res.status(500).json({ error: 'Internal server error' });
}
res.json(sessions);
});
});
app.delete('/api/sessions/:token', adminAuth, (req, res) => {
if (!authEnabled) {
return res.json({ message: 'Authentication is disabled' });
}
db.run(
'DELETE FROM sessions WHERE token = ?',
[req.params.token],
function(err) {
if (err) {
console.error('Error deleting session:', err);
return res.status(500).json({ error: 'Internal server error' });
}
res.json({ message: 'Session terminated successfully' });
}
);
});
app.get('/api/sessions/me', (req, res) => {
if (!authEnabled) {
return res.json([]);
}
db.all(
`SELECT id, created_at, expires_at, ip_address, user_agent
FROM sessions
WHERE user_id = ? AND expires_at > datetime('now')
ORDER BY created_at DESC`,
[req.user.id],
(err, sessions) => {
if (err) {
console.error('Error fetching user sessions:', err);
return res.status(500).json({ error: 'Internal server error' });
}
res.json(sessions);
}
);
});
// User Management Routes (Admin Only when auth is enabled)
app.post('/api/users', adminAuth, async (req, res) => {
if (!authEnabled) {
return res.status(400).json({ error: 'Authentication is disabled' });
}
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ error: 'Username and password required.' });
}
const salt = crypto.randomBytes(16).toString('hex');
const passwordHash = hashPassword(password, salt);
try {
const result = await new Promise((resolve, reject) => {
db.run(
'INSERT INTO users (username, password_hash, salt) VALUES (?, ?, ?)',
[username, passwordHash, salt],
function(err) {
if (err) reject(err);
else resolve(this.lastID);
}
);
});
res.status(201).json({
message: 'User created successfully',
userId: result
});
} catch (err) {
if (err.message.includes('UNIQUE constraint failed')) {
res.status(409).json({ error: 'Username already exists.' });
} else {
console.error('Error creating user:', err);
res.status(500).json({ error: 'Internal server error.' });
}
}
});
app.get('/api/users', adminAuth, (req, res) => {
if (!authEnabled) {
return res.json([]);
}
db.all(
`SELECT u.id, u.username, u.created_at,
COUNT(s.id) as active_sessions
FROM users u
LEFT JOIN sessions s ON u.id = s.user_id
AND s.expires_at > datetime('now')
GROUP BY u.id
ORDER BY u.created_at DESC`,
[],
(err, users) => {
if (err) {
console.error('Error fetching users:', err);
return res.status(500).json({ error: 'Internal server error.' });
}
res.json(users);
}
);
});
app.delete('/api/users/:id', adminAuth, (req, res) => {
if (!authEnabled) {
return res.status(400).json({ error: 'Authentication is disabled' });
}
const userId = parseInt(req.params.id, 10);
if (isNaN(userId)) {
return res.status(400).json({ error: 'Invalid user ID.' });
}
db.run('DELETE FROM users WHERE id = ?', [userId], function(err) {
if (err) {
console.error('Error deleting user:', err);
return res.status(500).json({ error: 'Internal server error.' });
}
res.json({ message: 'User deleted successfully.' });
});
});
// API Routes for call data
app.get('/api/calls', (req, res) => {
const hours = parseInt(req.query.hours) || 12;
// Convert hours to a Unix timestamp (seconds) for the WHERE clause
const sinceTimestampUnix = Math.floor((Date.now() - hours * 60 * 60 * 1000) / 1000);
console.log(`Fetching calls since Unix timestamp: ${sinceTimestampUnix} (${hours} hours ago)`);
db.all(
`
SELECT t.*, tg.alpha_tag AS talk_group_name, tg.tag AS talk_group_tag
FROM transcriptions t
LEFT JOIN talk_groups tg ON t.talk_group_id = tg.id
WHERE t.timestamp >= ? AND t.lat IS NOT NULL AND t.lon IS NOT NULL
ORDER BY t.timestamp DESC
`,
[sinceTimestampUnix], // Use Unix timestamp for the query
(err, rows) => {
if (err) {
console.error('Error fetching calls:', err);
res.status(500).json({ error: err.message });
return;
}
console.log(`Returning ${rows.length} calls`);
// Timestamps are now already Unix seconds from the DB
if (rows.length > 0) {
console.log(`Oldest call in result (Unix ts): ${rows[rows.length - 1].timestamp}`);
console.log(`Newest call in result (Unix ts): ${rows[0].timestamp}`);
}
res.json(rows); // Send rows directly as timestamps are already numeric
}
);
});
app.delete('/api/markers/:id', (req, res) => {
const markerId = parseInt(req.params.id, 10);
if (isNaN(markerId)) {
return res.status(400).json({ error: 'Invalid marker ID' });
}
db.run(
'DELETE FROM transcriptions WHERE id = ?',
[markerId],
function(err) {
if (err) {
console.error('Error deleting marker:', err);
return res.status(500).json({ error: 'Internal server error' });
}
res.json({ message: 'Marker deleted successfully' });
}
);
});
app.put('/api/markers/:id/location', (req, res) => {
const markerId = parseInt(req.params.id);
const { lat, lon } = req.body;
if (isNaN(markerId) || typeof lat !== 'number' || typeof lon !== 'number') {
return res.status(400).json({ error: 'Invalid parameters' });
}
db.run(
'UPDATE transcriptions SET lat = ?, lon = ? WHERE id = ?',
[lat, lon, markerId],
function(err) {
if (err) {
console.error('Error updating marker location:', err);
return res.status(500).json({ error: 'Internal server error' });
}
res.json({ success: true });
}
);
});
app.get('/api/additional-transcriptions/:callId', (req, res) => {
const callId = parseInt(req.params.callId, 10);
const skip = parseInt(req.query.skip, 10) || 0;
if (isNaN(callId)) {
return res.status(400).send('Invalid call ID.');
}
db.get(
'SELECT talk_group_id FROM transcriptions WHERE id = ?',
[callId],
(err, row) => {
if (err) {
console.error('Error fetching talk group ID:', err);
return res.status(500).json({ error: 'Internal Server Error' });
}
if (!row) {
return res.status(404).json({ error: 'Call not found' });
}
const talkGroupId = row.talk_group_id;
db.all(