forked from ardoviniandrea/ViniPlay
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
5135 lines (4526 loc) · 237 KB
/
Copy pathserver.js
File metadata and controls
5135 lines (4526 loc) · 237 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
// A Node.js server for the VINI PLAY IPTV Player.
// Implements server-side EPG parsing, secure environment variables, and improved logging.
// Load environment variables from .env file
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const { spawn, exec } = require('child_process');
const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const multer = require('multer');
const bodyParser = require('body-parser');
const session = require('express-session');
const bcrypt = require('bcrypt');
const sqlite3 = require('sqlite3').verbose();
const SQLiteStore = require('connect-sqlite3')(session);
const xmlJS = require('xml-js');
const zlib = require('zlib');
const webpush = require('web-push');
const schedule = require('node-schedule');
const disk = require('diskusage');
const si = require('systeminformation'); // NEW: For system health monitoring
//vod processor
const { refreshVodContent, processM3uVod } = require('./vodProcessor');
const XtreamClient = require('./xtreamClient');
// --- NEW: Live Activity Tracking for Redirects ---
const activeRedirectStreams = new Map(); // Tracks live redirect streams for the admin UI
const app = express();
const port = 8998;
const saltRounds = 10;
// Initialize global variables at the top-level scope
let notificationCheckInterval = null;
const sourceRefreshTimers = new Map();
let detectedHardware = { nvidia: null, intel_qsv: null, intel_vaapi: null, radeon_vaapi: null }; // MODIFIED: To store specific Intel GPU info
// Used to validate settings.
const validFFmpegLogLevels = ["debug", "verbose", "info", "warning", "error"];
// --- ENHANCEMENT: For Server-Sent Events (SSE) ---
// This map will store active client connections for real-time updates.
const sseClients = new Map();
// --- CAST: Token-based authentication ---
// Stores short-lived tokens for Chromecast authentication
const activeCastTokens = new Map(); // token -> { userId, streamUrl, expiresAt }
// --- NEW: DVR State ---
const activeDvrJobs = new Map(); // Stores active node-schedule jobs
const runningFFmpegProcesses = new Map(); // Stores PIDs of running ffmpeg recordings
// --- MODIFIED: Active Stream Management ---
// Now maps a unique stream key (URL + UserID) to its process info
const activeStreamProcesses = new Map();
const STREAM_INACTIVITY_TIMEOUT = 30000; // 30 seconds to kill an inactive stream process
// --- Configuration ---
const DATA_DIR = '/data';
const DVR_DIR = '/dvr';
const LOGS_DIR = path.join(DATA_DIR, 'logs'); // NEW: Log management directory
const VAPID_KEYS_PATH = path.join(DATA_DIR, 'vapid.json');
const SOURCES_DIR = path.join(DATA_DIR, 'sources');
const RAW_CACHE_DIR = path.join(SOURCES_DIR, 'raw_cache');
const IMAGE_CACHE_DIR = path.join(DATA_DIR, 'image_cache'); // NEW: VOD poster image cache
const PUBLIC_DIR = path.join(__dirname, 'public');
const DB_PATH = path.join(DATA_DIR, 'viniplay.db');
const LIVE_CHANNELS_M3U_PATH = path.join(DATA_DIR, 'live_channels.m3u'); // Renamed
const LIVE_EPG_JSON_PATH = path.join(DATA_DIR, 'epg.json'); // Renamed
const VOD_MOVIES_JSON_PATH = path.join(DATA_DIR, 'vod_movies.json'); // New
const VOD_SERIES_JSON_PATH = path.join(DATA_DIR, 'vod_series.json'); // New
const SETTINGS_PATH = path.join(DATA_DIR, 'settings.json');
console.log(`[INIT] Application starting. Data directory: ${DATA_DIR}, Public directory: ${PUBLIC_DIR}`);
// --- Automatic VAPID Key Generation ---
let vapidKeys = {};
try {
if (fs.existsSync(VAPID_KEYS_PATH)) {
console.log('[Push] Loading existing VAPID keys...');
vapidKeys = JSON.parse(fs.readFileSync(VAPID_KEYS_PATH, 'utf-8'));
} else {
console.log('[Push] VAPID keys not found. Generating new keys...');
vapidKeys = webpush.generateVAPIDKeys();
fs.writeFileSync(VAPID_KEYS_PATH, JSON.stringify(vapidKeys, null, 2));
console.log('[Push] New VAPID keys generated and saved.');
}
const vapidContactEmail = process.env.VAPID_CONTACT_EMAIL || 'mailto:admin@example.com';
console.log(`[Push] Setting VAPID contact to: ${vapidContactEmail}`);
webpush.setVapidDetails(vapidContactEmail, vapidKeys.publicKey, vapidKeys.privateKey);
} catch (error) {
console.error('[Push] FATAL: Could not load or generate VAPID keys.', error);
}
// Ensure the data and dvr directories exist.
try {
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
if (!fs.existsSync(PUBLIC_DIR)) fs.mkdirSync(PUBLIC_DIR, { recursive: true });
if (!fs.existsSync(SOURCES_DIR)) fs.mkdirSync(SOURCES_DIR, { recursive: true });
if (!fs.existsSync(DVR_DIR)) fs.mkdirSync(DVR_DIR, { recursive: true });
if (!fs.existsSync(RAW_CACHE_DIR)) fs.mkdirSync(RAW_CACHE_DIR, { recursive: true });
if (!fs.existsSync(LOGS_DIR)) fs.mkdirSync(LOGS_DIR, { recursive: true });
if (!fs.existsSync(IMAGE_CACHE_DIR)) fs.mkdirSync(IMAGE_CACHE_DIR, { recursive: true });
console.log(`[INIT] All required directories checked/created.`);
} catch (mkdirError) {
console.error(`[INIT] FATAL: Failed to create necessary directories: ${mkdirError.message}`);
process.exit(1);
}
// --- Database Setup ---
const db = new sqlite3.Database(DB_PATH, (err) => {
if (err) {
console.error("[DB] Error opening database:", err.message);
process.exit(1);
} else {
console.log("[DB] Connected to the SQLite database.");
db.serialize(() => {
db.run(`CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE, password TEXT, isAdmin INTEGER DEFAULT 0, canUseDvr INTEGER DEFAULT 0, allowed_sources TEXT)`, (err) => {
if (err) {
console.error("[DB] Error creating 'users' table:", err.message);
} else {
// DB Migrations for existing tables
db.run("ALTER TABLE users ADD COLUMN canUseDvr INTEGER DEFAULT 0", () => { });
db.run("ALTER TABLE users ADD COLUMN allowed_sources TEXT", () => { });
}
});
db.run(`CREATE TABLE IF NOT EXISTS user_settings (user_id INTEGER NOT NULL, key TEXT NOT NULL, value TEXT, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, PRIMARY KEY (user_id, key))`);
db.run(`CREATE TABLE IF NOT EXISTS multiview_layouts (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, name TEXT NOT NULL, layout_data TEXT NOT NULL, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE)`);
db.run(`CREATE TABLE IF NOT EXISTS notifications (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, channelId TEXT NOT NULL, channelName TEXT NOT NULL, channelLogo TEXT, programTitle TEXT NOT NULL, programDesc TEXT, programStart TEXT NOT NULL, programStop TEXT NOT NULL, notificationTime TEXT NOT NULL, programId TEXT NOT NULL, status TEXT DEFAULT 'pending', triggeredAt TEXT, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE)`);
db.run(`CREATE TABLE IF NOT EXISTS push_subscriptions (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, endpoint TEXT UNIQUE NOT NULL, p256dh TEXT NOT NULL, auth TEXT NOT NULL, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE)`);
db.run(`CREATE TABLE IF NOT EXISTS notification_deliveries (id INTEGER PRIMARY KEY AUTOINCREMENT, notification_id INTEGER NOT NULL, subscription_id INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending', updatedAt TEXT NOT NULL, FOREIGN KEY (notification_id) REFERENCES notifications(id) ON DELETE CASCADE, FOREIGN KEY (subscription_id) REFERENCES push_subscriptions(id) ON DELETE CASCADE)`);
db.run(`CREATE TABLE IF NOT EXISTS dvr_jobs (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, channelId TEXT NOT NULL, channelName TEXT NOT NULL, programTitle TEXT NOT NULL, startTime TEXT NOT NULL, endTime TEXT NOT NULL, status TEXT NOT NULL, ffmpeg_pid INTEGER, filePath TEXT, profileId TEXT, userAgentId TEXT, preBufferMinutes INTEGER, postBufferMinutes INTEGER, errorMessage TEXT, isConflicting INTEGER DEFAULT 0, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE)`);
db.run(`CREATE TABLE IF NOT EXISTS dvr_recordings (id INTEGER PRIMARY KEY AUTOINCREMENT, job_id INTEGER, user_id INTEGER NOT NULL, channelName TEXT NOT NULL, programTitle TEXT NOT NULL, startTime TEXT NOT NULL, durationSeconds INTEGER, fileSizeBytes INTEGER, filePath TEXT UNIQUE NOT NULL, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, FOREIGN KEY (job_id) REFERENCES dvr_jobs(id) ON DELETE SET NULL)`);
// --- NEW: VOD Tables ---
db.run(`CREATE TABLE IF NOT EXISTS movies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
year INTEGER,
description TEXT,
logo TEXT,
tmdb_id TEXT,
imdb_id TEXT,
category_name TEXT,
provider_unique_id TEXT UNIQUE,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
)`, (err) => { if (err) console.error("[DB] Error creating 'movies' table:", err.message); });
db.run(`CREATE TABLE IF NOT EXISTS series (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
year INTEGER,
description TEXT,
logo TEXT,
tmdb_id TEXT,
imdb_id TEXT,
category_name TEXT,
provider_unique_id TEXT UNIQUE,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
)`, (err) => { if (err) console.error("[DB] Error creating 'series' table:", err.message); });
db.run(`CREATE TABLE IF NOT EXISTS episodes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
series_id INTEGER NOT NULL,
season_num INTEGER NOT NULL,
episode_num INTEGER NOT NULL,
name TEXT,
description TEXT,
air_date TEXT,
tmdb_id TEXT,
imdb_id TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (series_id) REFERENCES series(id) ON DELETE CASCADE
)`, (err) => { if (err) console.error("[DB] Error creating 'episodes' table:", err.message); });
db.run(`CREATE TABLE IF NOT EXISTS vod_categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category_id TEXT UNIQUE NOT NULL,
category_name TEXT NOT NULL,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
)`, (err) => { if (err) console.error("[DB] Error creating 'vod_categories' table:", err.message); });
// --- NEW: VOD Relation Tables (Linking Providers to Content) ---
// Note: Assuming 'provider_id' refers to the ID of the M3U source entry in settings
// We'll store the source ID (e.g., 'src-12345678') as TEXT for flexibility
db.run(`CREATE TABLE IF NOT EXISTS provider_movie_relations (
provider_id TEXT NOT NULL,
movie_id INTEGER NOT NULL,
stream_id TEXT NOT NULL,
container_extension TEXT,
last_seen TEXT NOT NULL,
FOREIGN KEY (movie_id) REFERENCES movies(id) ON DELETE CASCADE,
PRIMARY KEY (provider_id, stream_id)
)`, (err) => { if (err) console.error("[DB] Error creating 'provider_movie_relations' table:", err.message); });
db.run(`CREATE TABLE IF NOT EXISTS provider_series_relations (
provider_id TEXT NOT NULL,
series_id INTEGER NOT NULL,
external_series_id TEXT NOT NULL,
last_seen TEXT NOT NULL,
FOREIGN KEY (series_id) REFERENCES series(id) ON DELETE CASCADE,
PRIMARY KEY (provider_id, external_series_id)
)`, (err) => { if (err) console.error("[DB] Error creating 'provider_series_relations' table:", err.message); });
db.run(`CREATE TABLE IF NOT EXISTS provider_episode_relations (
provider_id TEXT NOT NULL,
episode_id INTEGER NOT NULL,
provider_stream_id TEXT NOT NULL, -- The stream ID for the episode from XC
container_extension TEXT,
last_seen TEXT NOT NULL,
FOREIGN KEY (episode_id) REFERENCES episodes(id) ON DELETE CASCADE,
PRIMARY KEY (provider_id, episode_id)
)`, (err) => {
if (err) {
console.error("[DB] Error creating 'provider_episode_relations' table:", err.message);
} else {
// Add new column non-destructively
db.run("ALTER TABLE provider_episode_relations ADD COLUMN container_extension TEXT", () => { });
}
});
// --- END NEW VOD TABLES ---
//-- ENHANCEMENT: Modify stream history table to include more data for the admin panel.
db.run(`CREATE TABLE IF NOT EXISTS stream_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
username TEXT NOT NULL,
channel_id TEXT,
channel_name TEXT,
start_time TEXT NOT NULL,
end_time TEXT,
duration_seconds INTEGER,
status TEXT NOT NULL,
client_ip TEXT,
channel_logo TEXT,
stream_profile_name TEXT
)`, (err) => {
if (!err) {
// Add new columns non-destructively if the table already exists
db.run("ALTER TABLE stream_history ADD COLUMN channel_logo TEXT", () => { });
db.run("ALTER TABLE stream_history ADD COLUMN stream_profile_name TEXT", () => { });
}
});
// --- DVR Job Loading and Scheduling (Moved from main execution flow) ---
console.log('[DVR] Loading and scheduling all pending DVR jobs from database...');
db.run("UPDATE dvr_jobs SET status = 'error', errorMessage = 'Server restarted during recording.' WHERE status = 'recording'", [], (err) => {
if (err) {
console.error('[DVR] Error updating recording jobs status on startup:', err.message);
}
});
db.all("SELECT * FROM dvr_jobs WHERE status = 'scheduled'", [], (err, jobs) => {
if (err) {
console.error('[DVR] Error fetching pending DVR jobs:', err);
return;
}
jobs.forEach(job => {
scheduleDvrJob(job);
});
console.log(`[DVR] Loaded and scheduled ${jobs.length} pending DVR jobs.`);
});
// --- End DVR Job Loading and Scheduling ---
});
}
});
// --- Middleware ---
// 1. Smart Caching for API: Allow cache presence but FORCE revalidation every time.
// 'no-cache' = "Check with server before using cached copy".
app.use('/api', (req, res, next) => {
res.set('Cache-Control', 'private, no-cache, must-revalidate');
next();
});
// 2. Smart Caching for Static Files:
// Allow browser to cache index.html/js, but REQUIRE it to check if they changed (304 Not Modified)
app.use(express.static(PUBLIC_DIR, {
setHeaders: (res, path) => {
if (path.endsWith('index.html') || path.endsWith('.js')) {
res.set('Cache-Control', 'public, no-cache, must-revalidate');
}
}
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const updateAndScheduleSourceRefreshes = () => {
console.log('[SCHEDULER] Updating and scheduling all source refreshes...');
const settings = getSettings();
const allSources = [...(settings.m3uSources || []), ...(settings.epgSources || [])];
const activeUrlSources = new Set();
allSources.forEach(source => {
if (source.type === 'url' && source.isActive && source.refreshHours > 0) {
activeUrlSources.add(source.id);
if (sourceRefreshTimers.has(source.id)) {
clearTimeout(sourceRefreshTimers.get(source.id));
}
console.log(`[SCHEDULER] Scheduling refresh for "${source.name}" (ID: ${source.id}) every ${source.refreshHours} hours.`);
const scheduleNext = () => {
const timeoutId = setTimeout(async () => {
console.log(`[SCHEDULER_RUN] Auto-refresh triggered for "${source.name}".`);
try {
const result = await processAndMergeSources();
if (result.success) {
fs.writeFileSync(SETTINGS_PATH, JSON.stringify(result.updatedSettings, null, 2));
console.log(`[SCHEDULER_RUN] Successfully refreshed and processed sources for "${source.name}".`);
}
} catch (error) {
console.error(`[SCHEDULER_RUN] Auto-refresh for "${source.name}" failed:`, error.message);
}
scheduleNext();
}, source.refreshHours * 3600 * 1000);
sourceRefreshTimers.set(source.id, timeoutId);
};
scheduleNext();
}
});
for (const [sourceId, timeoutId] of sourceRefreshTimers.entries()) {
if (!activeUrlSources.has(sourceId)) {
console.log(`[SCHEDULER] Clearing obsolete refresh timer for source ID: ${sourceId}`);
clearTimeout(timeoutId);
sourceRefreshTimers.delete(sourceId);
}
}
console.log(`[SCHEDULER] Finished scheduling. Active timers: ${sourceRefreshTimers.size}`);
};
function saveSettings(settings) {
try {
fs.writeFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2));
console.log('[SETTINGS] Settings saved successfully.');
updateAndScheduleSourceRefreshes();
} catch (e) {
console.error("[SETTINGS] Error saving settings:", e);
}
}
// --- Session Management ---
let sessionSecret = process.env.SESSION_SECRET;
if (!sessionSecret) {
console.log('[SECURITY] SESSION_SECRET not found in environment. Checking settings.json...');
let settings = getSettings();
if (settings.generatedSessionSecret) {
console.log('[SECURITY] Found existing session secret in settings.json.');
sessionSecret = settings.generatedSessionSecret;
} else {
console.log('[SECURITY] No secret in settings.json. Generating a new one...');
sessionSecret = crypto.randomBytes(64).toString('hex');
settings.generatedSessionSecret = sessionSecret;
saveSettings(settings);
console.log('[SECURITY] New session secret generated and saved to settings.json.');
}
} else {
console.log('[SECURITY] Loaded SESSION_SECRET from environment variable.');
}
if (sessionSecret.includes('replace_this')) {
console.warn('[SECURITY] Using a weak or default SESSION_SECRET. Please replace it.');
}
app.use(
session({
store: new SQLiteStore({ db: 'viniplay.db', dir: DATA_DIR, table: 'sessions' }),
secret: sessionSecret,
resave: false,
saveUninitialized: false,
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000, httpOnly: true, secure: process.env.NODE_ENV === 'production' },
})
);
app.use((req, res, next) => {
// Add client IP to the request object for logging
req.clientIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
if (req.path === '/api/events') {
return next();
}
const user_info = req.session.userId ? `User ID: ${req.session.userId}, Admin: ${req.session.isAdmin}, DVR: ${req.session.canUseDvr}` : 'No session';
console.log(`[HTTP_TRACE] ${req.method} ${req.originalUrl} - IP: ${req.clientIp} - Session: [${user_info}]`);
next();
});
// MODIFIED: requireAuth now checks if the user still exists in the database on every request.
const requireAuth = (req, res, next) => {
if (!req.session || !req.session.userId) {
return res.status(401).json({ error: 'Authentication required.' });
}
db.get("SELECT id FROM users WHERE id = ?", [req.session.userId], (err, user) => {
if (err) {
console.error('[AUTH_MIDDLEWARE] DB error checking user existence:', err);
return res.status(500).json({ error: 'Server error during authentication.' });
}
if (!user) {
console.warn(`[AUTH_MIDDLEWARE] User ID ${req.session.userId} from session not found in DB. Destroying session.`);
req.session.destroy();
res.clearCookie('connect.sid');
return res.status(401).json({ error: 'User account no longer exists. Please log in again.' });
}
// User exists, proceed.
next();
});
};
const requireAdmin = (req, res, next) => {
if (req.session && req.session.isAdmin) return next();
return res.status(403).json({ error: 'Administrator privileges required.' });
};
const requireDvrAccess = (req, res, next) => {
if (req.session && (req.session.canUseDvr || req.session.isAdmin)) return next();
return res.status(403).json({ error: 'DVR access required.' });
};
// *** FIX: DVR Playback Access ***
// Removed `requireDvrAccess` from this route. Now, any authenticated user can access
// the /dvr directory to play back recorded files. The API endpoints for creating
// and managing recordings remain protected by `requireDvrAccess`.
app.use('/dvr', requireAuth, express.static(DVR_DIR));
// --- Helper Functions ---
/**
* NEW: Sends a real-time status update to the client during source processing.
* @param {object} req - The Express request object, used to identify the user.
* @param {string} message - The status message to send.
* @param {string} type - The type of message (e.g., 'info', 'success', 'error').
*/
function sendProcessingStatus(req, message, type = 'info') {
if (req && req.session && req.session.userId) {
sendSseEvent(req.session.userId, 'processing-status', { message, type });
}
}
// --- Database Helper Functions ---
/**
* Promisified version of db.run
* @param {sqlite3.Database} db - The database instance.
* @param {string} sql - The SQL query.
* @param {Array} params - Query parameters.
* @returns {Promise<object>} - { lastID, changes }
*/
const dbRun = (db, sql, params = []) => {
return new Promise((resolve, reject) => {
db.run(sql, params, function (err) {
if (err) return reject(err);
resolve(this);
});
});
};
/**
* Promisified version of db.get
* @param {sqlite3.Database} db - The database instance.
* @param {string} sql - The SQL query.
* @param {Array} params - Query parameters.
* @returns {Promise<object|null>} - The first row found.
*/
const dbGet = (db, sql, params = []) => {
return new Promise((resolve, reject) => {
db.get(sql, params, (err, row) => {
if (err) return reject(err);
resolve(row);
});
});
};
/**
* Promisified version of db.all
* @param {sqlite3.Database} db - The database instance.
* @param {string} sql - The SQL query.
* @param {Array} params - Query parameters.
* @returns {Promise<Array>} - An array of rows.
*/
const dbAll = (db, sql, params = []) => {
return new Promise((resolve, reject) => {
db.all(sql, params, (err, rows) => {
if (err) return reject(err);
resolve(rows);
});
});
};
// --- End Database Helper Functions ---
/**
* NEW: Extracts GPU details from vainfo output.
*/
function extractVainfoGPUDetails(vainfo_stdout) {
const start_tag = "Driver version: ";
const end_tag = "vainfo: Supported profile";
let vainfo_gpu_details = vainfo_stdout.substring(
vainfo_stdout.indexOf(start_tag) + start_tag.length,
vainfo_stdout.lastIndexOf(end_tag) - 1
);
// If we can't find the relevant GPU info section, return all to debug.
// Likely means the output format of vainfo has been changed.
if (vainfo_gpu_details === "") {
vainfo_gpu_details = vainfo_stdout;
} else {
console.log(`[HW] Detected: ${vainfo_gpu_details}`)
}
return vainfo_gpu_details;
}
/**
* NEW: Detects available hardware for transcoding.
*/
async function detectHardwareAcceleration() {
// When a new unhandled GPU is found, add the driver name to the appropriate
// array of gpu drivers for detection.
const vaapi_radeon_gpu_drivers = ["r600_drv_video.so", "radeonsi_drv_video.so"];
const intel_qsv_gpu_drivers = ["iHD_drv_video.so"];
const intel_vaapi_gpu_drivers = ["i965_drv_video.so"];
console.log('[HW] Detecting hardware acceleration capabilities...');
// Detect NVIDIA GPU
exec('nvidia-smi --query-gpu=gpu_name --format=csv,noheader', (err, stdout, stderr) => {
if (err || stderr) {
console.log('[HW] NVIDIA GPU not detected or nvidia-smi failed.');
} else {
const gpuName = stdout.trim();
detectedHardware.nvidia = gpuName;
console.log(`[HW] NVIDIA GPU detected: ${gpuName}`);
}
});
// MODIFIED: Use 'vainfo' for more robust detection of AMD, Intel VA-API
// and QSV GPUs. vainfo gives driver detection info on stderr and full
// detected GPU detail on stdout.
exec('vainfo', (err, stdout, stderr) => {
if (stderr) {
let found = false;
const trimmed_stdout = stdout.trim()
// Intel qsv driver is for modern Intel GPUs (Gen9+) and is preferred for QSV
if (intel_qsv_gpu_drivers.some(substring => stderr.includes(substring))) {
detectedHardware.intel_qsv = extractVainfoGPUDetails(trimmed_stdout);
found = true;
}
// AMD Radeon detection
if (vaapi_radeon_gpu_drivers.some(substring => stderr.includes(substring))) {
detectedHardware.radeon_vaapi = extractVainfoGPUDetails(trimmed_stdout);
found = true;
}
// Intel vaapi driver is for older Intel GPUs (pre-Gen9)
if (intel_vaapi_gpu_drivers.some(substring => stderr.includes(substring))) {
detectedHardware.intel_vaapi = extractVainfoGPUDetails(trimmed_stdout);
found = true;
}
if (!found) {
// Show full vainfo output for info/debug purposes.
console.log("[HW] vainfo did not detect any recognized GPU");
if (stderr) {
console.log(`[HW] vainfo init (stderr): ${stderr.trim()}`);
}
if (stdout) {
console.log(`[HW] vainfo GPU info (stdout): ${stdout.trim()}`);
}
}
}
});
}
// MODIFIED: This function is now mostly for multi-view scenarios.
// Single-user streams are handled more directly.
function cleanupInactiveStreams() {
const now = Date.now();
console.log(`[JANITOR] Running cleanup for inactive streams. Current active processes: ${activeStreamProcesses.size}`);
activeStreamProcesses.forEach((streamInfo, streamKey) => {
if (streamInfo.references <= 0 && (now - streamInfo.lastAccess > STREAM_INACTIVITY_TIMEOUT)) {
console.log(`[JANITOR] Found stale stream process for key: ${streamKey}. Terminating PID: ${streamInfo.process.pid}.`);
try {
// Also update the history entry if it exists
if (streamInfo.historyId) {
const endTime = new Date().toISOString();
const duration = Math.round((new Date(endTime).getTime() - new Date(streamInfo.startTime).getTime()) / 1000);
db.run("UPDATE stream_history SET end_time = ?, duration_seconds = ?, status = 'stopped' WHERE id = ? AND status = 'playing'",
[endTime, duration, streamInfo.historyId]);
}
streamInfo.process.kill('SIGKILL');
activeStreamProcesses.delete(streamKey);
//-- ENHANCEMENT: Notify admins that a stream has ended.
broadcastAdminUpdate();
} catch (e) {
console.warn(`[JANITOR] Error killing stale process for ${streamKey}: ${e.message}`);
activeStreamProcesses.delete(streamKey);
//-- ENHANCEMENT: Notify admins even if the process kill fails, to keep UI in sync.
broadcastAdminUpdate();
}
}
});
}
function sendSseEvent(userId, eventName, data) {
const clients = sseClients.get(userId);
if (clients && clients.length > 0) {
console.log(`[SSE] Sending event '${eventName}' to ${clients.length} client(s) for user ID ${userId}.`);
const message = `event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`;
clients.forEach(client => client.res.write(message));
}
}
//-- ENHANCEMENT: New function to broadcast activity updates to all connected admins.
function broadcastAdminUpdate() {
// Combine transcoded and redirect streams into one list for the live view
const transcodedLive = Array.from(activeStreamProcesses.values()).map(info => ({
streamKey: info.streamKey,
userId: info.userId,
username: info.username,
channelName: info.channelName,
channelLogo: info.channelLogo,
streamProfileName: info.streamProfileName,
startTime: info.startTime,
clientIp: info.clientIp,
isTranscoded: true,
}));
const redirectLive = Array.from(activeRedirectStreams.values()).map(info => ({
// Use historyId for redirect streamKey to ensure it's unique per session
streamKey: `${info.userId}::${info.historyId}`,
userId: info.userId,
username: info.username,
channelName: info.channelName,
channelLogo: info.channelLogo,
streamProfileName: info.streamProfileName,
startTime: info.startTime,
clientIp: info.clientIp,
isTranscoded: false,
}));
const combinedLiveActivity = [...transcodedLive, ...redirectLive];
for (const clients of sseClients.values()) {
clients.forEach(client => {
if (client.isAdmin) {
const message = `event: activity-update\ndata: ${JSON.stringify({ live: combinedLiveActivity })}\n\n`;
client.res.write(message);
}
});
}
console.log(`[SSE_ADMIN] Broadcasted combined activity update (${combinedLiveActivity.length} live streams) to all connected admins.`);
}
// NEW: Broadcasts an event to ALL connected clients, regardless of user.
function broadcastSseToAll(eventName, data) {
const message = `event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`;
let clientCount = 0;
for (const clients of sseClients.values()) {
clients.forEach(client => {
client.res.write(message);
clientCount++;
});
}
console.log(`[SSE_BROADCAST] Broadcasted event '${eventName}' to ${clientCount} total clients.`);
}
function getSettings() {
const defaultSettings = {
m3uSources: [],
epgSources: [],
userAgents: [{ id: `default-ua-1724778434000`, name: 'ViniPlay Default', value: 'VLC/3.0.20 (Linux; x86_64)', isDefault: true }],
streamProfiles: [
{ id: 'redirect', name: 'Redirect (No Transcoding)', command: 'redirect', isDefault: true },
{ id: 'ffmpeg-default', name: 'ffmpeg (Built in)', command: '-user_agent "{userAgent}" -i "{streamUrl}" -c:v libx264 -preset ultrafast -crf 23 -c:a aac -b:a 128k -f mpegts pipe:1', isDefault: false },
{ id: 'ffmpeg-fmp4', name: 'ffmpeg fMP4 (CPU)', command: '-user_agent "{userAgent}" -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5 -i "{streamUrl}" -c:v libx264 -preset ultrafast -c:a aac -b:a 192k -movflags frag_keyframe+empty_moov+default_base_moof -f mp4 pipe:1', isDefault: false },
{ id: 'ffmpeg-fmp4-nvidia', name: 'ffmpeg fMP4 (NVIDIA)', command: '-user_agent "{userAgent}" -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5 -i "{streamUrl}" -c:v h264_nvenc -preset p6 -tune hq -c:a aac -b:a 192k -movflags frag_keyframe+empty_moov+default_base_moof -f mp4 pipe:1', isDefault: false },
{ id: 'ffmpeg-nvidia', name: 'ffmpeg (NVIDIA NVENC)', command: '-user_agent "{userAgent}" -re -i "{streamUrl}" -c:v h264_nvenc -preset p6 -tune hq -c:a copy -f mpegts pipe:1', isDefault: false },
{ id: 'ffmpeg-nvidia-reconnect', name: 'ffmpeg (NVIDIA reconnect)', command: '-user_agent "{userAgent}" -re -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5 -i "{streamUrl}" -c:v h264_nvenc -preset p6 -tune hq -c:a copy -f mpegts pipe:1', isDefault: false },
{ id: 'ffmpeg-intel', name: 'ffmpeg (Intel QSV)', command: '-hwaccel qsv -c:v h264_qsv -i "{streamUrl}" -c:v h264_qsv -preset medium -c:a aac -b:a 128k -f mpegts pipe:1', isDefault: false },
{ id: 'ffmpeg-vaapi', name: 'ffmpeg (VA-API) Intel', command: '-hwaccel vaapi -hwaccel_output_format vaapi -i "{streamUrl}" -vf "format=nv12|vaapi,hwupload" -c:v h264_vaapi -preset medium -c:a aac -b:a 128k -f mpegts pipe:1', isDefault: false },
{ id: 'ffmpeg-vaapi-amd', name: 'ffmpeg (VA-API) Radeon/AMD', command: '-vaapi_device /dev/dri/renderD128 -hwaccel vaapi -hwaccel_output_format vaapi -i "{streamUrl}" -c:v h264_vaapi -c:a aac -b:a 128k -f mpegts pipe:1', isDefault: false }
],
dvr: {
preBufferMinutes: 1,
postBufferMinutes: 2,
maxConcurrentRecordings: 1,
autoDeleteDays: 0,
activeRecordingProfileId: 'dvr-ts-default', // **MODIFIED: Point to the new default profile**
recordingProfiles: [
// The primary default for timeshifting, uses almost no CPU.
{ id: 'dvr-ts-default', name: 'Default TS (Stream Copy, Timeshiftable)', command: '-user_agent "{userAgent}" -i "{streamUrl}" -c copy -f mpegts "{filePath}"', isDefault: true },
// The new GPU-accelerated option for timeshifting.
{ id: 'dvr-ts-nvidia', name: 'NVIDIA NVENC TS (Timeshiftable)', command: '-user_agent "{userAgent}" -i "{streamUrl}" -c:v h264_nvenc -preset p6 -tune hq -c:a copy -f mpegts "{filePath}"', isDefault: false },
{ id: 'dvr-ts-nvidia-reconnect', name: 'NVIDIA NVENC TS reconnect', command: '-user_agent "{userAgent}" -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5 -i "{streamUrl}" -c:v h264_nvenc -preset p6 -tune hq -c:a copy -f mpegts "{filePath}"', isDefault: false },
// Legacy MP4 profiles, no longer default.
{ id: 'dvr-mp4-default', name: 'Legacy MP4 (H.264/AAC)', command: '-user_agent "{userAgent}" -i "{streamUrl}" -c:v libx264 -preset veryfast -crf 23 -c:a aac -b:a 128k -movflags +faststart -f mp4 "{filePath}"', isDefault: false },
{ id: 'dvr-mp4-nvidia', name: 'NVIDIA NVENC MP4 (H.264/AAC)', command: '-user_agent "{userAgent}" -i "{streamUrl}" -c:v h264_nvenc -preset p6 -tune hq -c:a aac -b:a 128k -movflags +faststart -f mp4 "{filePath}"', isDefault: false },
{ id: 'dvr-mp4-intel', name: 'Intel QSV MP4 (H.264/AAC)', command: '-hwaccel qsv -hwaccel_output_format qsv -i "{streamUrl}" -c:v h264_qsv -preset medium -vf scale_qsv=format=nv12 -c:a aac -ac 2 -b:a 128k -movflags +faststart -f mp4 "{filePath}"', isDefault: false },
// NEW: Add this line for VA-API recording
{ id: 'dvr-mp4-vaapi', name: 'VA-API MP4 (H.264/AAC)', command: '-hwaccel vaapi -hwaccel_output_format vaapi -i "{streamUrl}" -vf \'format=nv12,hwupload\' -c:v h264_vaapi -preset medium -c:a aac -b:a 128k -movflags +faststart -f mp4 "{filePath}"', isDefault: false },
{ id: 'dvr-mp4-radeon-vaapi', name: 'Radeon/AMD VA-API MP4 (H.264/AAC)', command: '-vaapi_device /dev/dri/renderD128 -hwaccel vaapi -hwaccel_output_format vaapi -i "{streamUrl}" -c:v h264_vaapi -preset medium -vf scale_vaapi=format=nv12 -c:a aac -ac 2 -b:a 128k -movflags +faststart -f mp4 "{filePath}"', isDefault: false }
]
},
castProfiles: [
{ id: 'cast-default', name: 'Cast Default (CPU)', command: '-user_agent "{userAgent}" -i "{streamUrl}" -c:v libx264 -preset veryfast -crf 23 -c:a aac -b:a 128k -movflags frag_keyframe+empty_moov+default_base_moof -f mp4 pipe:1', isDefault: true },
{ id: 'cast-nvidia', name: 'Cast (NVIDIA NVENC)', command: '-user_agent "{userAgent}" -i "{streamUrl}" -c:v h264_nvenc -preset p6 -tune hq -c:a aac -b:a 128k -movflags frag_keyframe+empty_moov+default_base_moof -f mp4 pipe:1', isDefault: false },
{ id: 'cast-intel', name: 'Cast (Intel QSV)', command: '-hwaccel qsv -c:v h264_qsv -i "{streamUrl}" -c:v h264_qsv -preset medium -c:a aac -b:a 128k -movflags frag_keyframe+empty_moov+default_base_moof -f mp4 pipe:1', isDefault: false },
{ id: 'cast-vaapi', name: 'Cast (VA-API Intel)', command: '-hwaccel vaapi -hwaccel_output_format vaapi -i "{streamUrl}" -vf "format=nv12|vaapi,hwupload" -c:v h264_vaapi -c:a aac -b:a 128k -movflags frag_keyframe+empty_moov+default_base_moof -f mp4 pipe:1', isDefault: false },
{ id: 'cast-vaapi-amd', name: 'Cast (VA-API Radeon/AMD)', command: '-vaapi_device /dev/dri/renderD128 -hwaccel vaapi -hwaccel_output_format vaapi -i "{streamUrl}" -c:v h264_vaapi -c:a aac -b:a 128k -movflags frag_keyframe+empty_moov+default_base_moof -f mp4 pipe:1', isDefault: false }
],
activeCastProfileId: 'cast-default',
activeUserAgentId: `default-ua-1724778434000`,
activeStreamProfileId: 'redirect',
playerLogLevel: 'warning',
dvrLogLevel: 'warning',
searchScope: 'all_channels_unfiltered',
notificationLeadTime: 10,
sourcesLastUpdated: null,
logs: {
maxFiles: 5,
maxFileSizeBytes: 5 * 1024 * 1024, // 5MB
autoDeleteDays: 7
}
};
if (!fs.existsSync(SETTINGS_PATH)) {
console.log('[SETTINGS] settings.json not found, creating default settings.');
fs.writeFileSync(SETTINGS_PATH, JSON.stringify(defaultSettings, null, 2));
return defaultSettings;
}
try {
let settings = JSON.parse(fs.readFileSync(SETTINGS_PATH, 'utf-8'));
// --- SETTINGS MIGRATION LOGIC ---
// This is the correct place to handle/validate newly added settings during startup.
// Otherwise users will potentially have errors when migrating to new viniplay
// versions that expect new settings.
let needsSave = false;
defaultSettings.streamProfiles.forEach(defaultProfile => {
const existingProfile = settings.streamProfiles.find(p => p.id === defaultProfile.id);
if (!existingProfile) {
console.log(`[SETTINGS_MIGRATE] Adding missing stream profile: ${defaultProfile.name}`);
settings.streamProfiles.push(defaultProfile);
needsSave = true;
} else if (existingProfile.isDefault) {
// FINAL FIX: Forcibly update the command of default profiles to ensure users get the latest fixes.
if (existingProfile.command !== defaultProfile.command) {
console.log(`[SETTINGS_MIGRATE] Updating outdated default stream profile command for: ${defaultProfile.name}`);
existingProfile.command = defaultProfile.command;
needsSave = true;
}
}
});
if (!settings.dvr) {
console.log(`[SETTINGS_MIGRATE] Initializing DVR settings block.`);
settings.dvr = defaultSettings.dvr;
needsSave = true;
} else {
defaultSettings.dvr.recordingProfiles.forEach(defaultProfile => {
const existingProfile = settings.dvr.recordingProfiles.find(p => p.id === defaultProfile.id);
if (!existingProfile) {
console.log(`[SETTINGS_MIGRATE] Adding missing DVR recording profile: ${defaultProfile.name}`);
settings.dvr.recordingProfiles.push(defaultProfile);
needsSave = true;
} else if (existingProfile.isDefault) {
// FINAL FIX: Forcibly update the command of default DVR profiles.
if (existingProfile.command !== defaultProfile.command) {
console.log(`[SETTINGS_MIGRATE] Updating outdated default DVR profile command for: ${defaultProfile.name}`);
existingProfile.command = defaultProfile.command;
needsSave = true;
}
}
});
}
// Cast profiles migration
if (!settings.castProfiles) {
console.log(`[SETTINGS_MIGRATE] Initializing Cast profiles block.`);
settings.castProfiles = defaultSettings.castProfiles;
needsSave = true;
} else {
defaultSettings.castProfiles.forEach(defaultProfile => {
const existingProfile = settings.castProfiles.find(p => p.id === defaultProfile.id);
if (!existingProfile) {
console.log(`[SETTINGS_MIGRATE] Adding missing Cast profile: ${defaultProfile.name}`);
settings.castProfiles.push(defaultProfile);
needsSave = true;
} else if (existingProfile.isDefault) {
// Update default cast profile commands
if (existingProfile.command !== defaultProfile.command) {
console.log(`[SETTINGS_MIGRATE] Updating outdated default Cast profile command for: ${defaultProfile.name}`);
existingProfile.command = defaultProfile.command;
needsSave = true;
}
}
});
}
if (!settings.activeCastProfileId) {
console.log(`[SETTINGS_MIGRATE] Initializing missing activeCastProfileId to ${defaultSettings.activeCastProfileId}.`);
settings.activeCastProfileId = defaultSettings.activeCastProfileId;
needsSave = true;
}
if (!settings.playerLogLevel) {
// There is no playerLogLevel setting. Add it with default setting.
console.log(`[SETTINGS_MIGRATE] Initializing missing player Log Level setting to ${defaultSettings.playerLogLevel}.`);
settings.playerLogLevel = defaultSettings.playerLogLevel;
needsSave = true;
} else if (!validFFmpegLogLevels.includes(settings.playerLogLevel)) {
// There is a playerLogLevel setting but the value is not recognized. Set to default.
console.log(`[SETTINGS_MIGRATE_ERROR] player Log Level setting: ${settings.playerLogLevel} is invalid, set to default: ${defaultSettings.playerLogLevel}.`);
settings.playerLogLevel = defaultSettings.playerLogLevel;
needsSave = true;
}
if (!settings.dvrLogLevel) {
// There is no dvrLogLevel setting. Add it with default setting.
console.log(`[SETTINGS_MIGRATE] Initializing missing dvr Log Level setting to ${defaultSettings.dvrLogLevel}.`);
settings.dvrLogLevel = defaultSettings.dvrLogLevel;
needsSave = true;
} else if (!validFFmpegLogLevels.includes(settings.dvrLogLevel)) {
// There is a dvrLogLevel setting but the value is not recognized. Set to default.
console.log(`[SETTINGS_MIGRATE_ERROR] dvr Log Level setting: ${settings.dvrLogLevel} is invalid, set to default: ${defaultSettings.dvrLogLevel}.`);
settings.dvrLogLevel = defaultSettings.dvrLogLevel;
needsSave = true;
}
// NEW: Logs settings migration
if (!settings.logs) {
console.log(`[SETTINGS_MIGRATE] Initializing missing logs settings block.`);
settings.logs = defaultSettings.logs;
needsSave = true;
} else {
// Ensure all log sub-settings exist
if (settings.logs.maxFiles === undefined) {
console.log(`[SETTINGS_MIGRATE] Adding missing logs.maxFiles setting.`);
settings.logs.maxFiles = defaultSettings.logs.maxFiles;
needsSave = true;
}
if (settings.logs.maxFileSizeBytes === undefined) {
console.log(`[SETTINGS_MIGRATE] Adding missing logs.maxFileSizeBytes setting.`);
settings.logs.maxFileSizeBytes = defaultSettings.logs.maxFileSizeBytes;
needsSave = true;
}
if (settings.logs.autoDeleteDays === undefined) {
console.log(`[SETTINGS_MIGRATE] Adding missing logs.autoDeleteDays setting.`);
settings.logs.autoDeleteDays = defaultSettings.logs.autoDeleteDays;
needsSave = true;
}
}
// Check that all expected settings are present and set and if not,
// generate log to highlight missing setting(s) migration code.
if (!settings || typeof settings !== 'object') {
console.log('[SETTINGS_MIGRATE_ERROR] Settings are not valid.');
} else {
let allSettingsValid = true;
for (const key of Object.keys(defaultSettings)) {
if (!(key in settings) || settings[key] === undefined) {
console.log(`[SETTINGS_MIGRATE_ERROR] Expected setting ${key} is missing. server.js:getSettings() needs updating.`);
allSettingsValid = false;
}
}
if (allSettingsValid) {
console.log('[SETTINGS_MIGRATE] Settings are all valid.');
if (needsSave) {
console.log('[SETTINGS_MIGRATE] Saving updated settings file after migration.');
fs.writeFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2));
}
} else {
console.log('[SETTINGS_MIGRATE_ERROR] Settings are not all valid.');
}
}
return settings;
} catch (e) {
console.error("[SETTINGS] Could not parse settings.json, returning default. Error:", e.message);
return defaultSettings;
}
}
// --- LOG ROTATION SYSTEM ---
let currentLogStream = null;
let currentLogFilePath = null;
let currentLogSize = 0;
let cachedLogSettings = {
maxFiles: 5,
maxFileSizeBytes: 5 * 1024 * 1024,
autoDeleteDays: 7
};
/**
* Updates the cached log settings. Call this after settings are changed.
*/
function refreshLogSettings() {
try {
const settings = getSettings();
if (settings.logs) {
cachedLogSettings = settings.logs;
}
} catch (error) {
// Silently fail to avoid recursion
}
}
/**
* Gets the current active log file path.
* @returns {string} Path to the current log file.
*/
function getCurrentLogFilePath() {
if (!currentLogFilePath) {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
currentLogFilePath = path.join(LOGS_DIR, `viniplay-${timestamp}.log`);
}
return currentLogFilePath;
}
/**
* Rotates the log file when size limit is reached.
*/
function rotateLogFile() {
try {
if (currentLogStream) {
currentLogStream.end();
currentLogStream = null;
}
// Create new log file
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
currentLogFilePath = path.join(LOGS_DIR, `viniplay-${timestamp}.log`);
currentLogSize = 0;
// Use original console.log to avoid recursion
const originalLog = console.log.__original || console.log;
originalLog.call(console, `[LOG_ROTATE] Created new log file: ${path.basename(currentLogFilePath)}`);
// Clean up old log files based on maxFiles setting
cleanupOldLogsByCount();
} catch (error) {
// Silently fail to avoid recursion
}
}
/**
* Cleans up old log files based on the maxFiles setting.
*/
function cleanupOldLogsByCount() {
try {
const maxFiles = cachedLogSettings.maxFiles || 5;
const logFiles = fs.readdirSync(LOGS_DIR)
.filter(file => file.startsWith('viniplay-') && file.endsWith('.log'))
.map(file => ({
name: file,
path: path.join(LOGS_DIR, file),
mtime: fs.statSync(path.join(LOGS_DIR, file)).mtime
}))
.sort((a, b) => b.mtime - a.mtime); // Sort by newest first
// Delete files beyond maxFiles limit
if (logFiles.length > maxFiles) {
const filesToDelete = logFiles.slice(maxFiles);
filesToDelete.forEach(file => {
try {
fs.unlinkSync(file.path);
const originalLog = console.log.__original || console.log;
originalLog.call(console, `[LOG_CLEANUP] Deleted old log file: ${file.name}`);
} catch (err) {
// Silently fail
}
});
}
} catch (error) {
// Silently fail to avoid recursion
}
}
/**
* Cleans up log files older than the configured autoDeleteDays.
*/
function cleanupOldLogsByAge() {
try {
const autoDeleteDays = cachedLogSettings.autoDeleteDays || 0;
if (autoDeleteDays === 0) {