-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_server.js
More file actions
1621 lines (1383 loc) · 48.9 KB
/
data_server.js
File metadata and controls
1621 lines (1383 loc) · 48.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs-extra');
const MusicDatabase = require('./lib/music_database');
const MusicScanner = require('./lib/music_scanner');
const AppDatabase = require('./lib/app_database');
// Determine the correct root directory for both PKG and normal execution
let ROOT_PATH;
if (process.pkg) {
// Running in PKG - use current working directory (where exe is executed from)
ROOT_PATH = process.cwd();
console.log('[SERVER] 🔧 PKG Mode - Working directory:', ROOT_PATH);
} else {
// Running normally with Node.js - use script directory
ROOT_PATH = __dirname;
console.log('[SERVER] 🔧 Development Mode - Working directory:', ROOT_PATH);
}
// Load configuration
let config = {};
try {
const configPath = path.join(ROOT_PATH, 'config.json');
if (fs.existsSync(configPath)) {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
console.log('[SERVER] 📋 Configuration loaded from config.json');
}
} catch (error) {
console.warn('[SERVER] ⚠️ Failed to load config.json, using defaults:', error.message);
}
const app = express();
const PORT = process.env.PORT || config.server?.dataPort || 3001;
const HOST = config.server?.host || '127.0.0.1';
// Global debugging system
let isDebuggingEnabled = false;
const loggedMessages = new Set();
const logCooldown = new Map();
// Debug function with spam prevention and cooldown
function debugLog(category, ...args) {
if (isDebuggingEnabled) {
const message = `[${category.toUpperCase()}] ${args.join(' ')}`;
const now = Date.now();
if (!logCooldown.has(message) || (now - logCooldown.get(message)) > 5000) {
console.log(`[${category.toUpperCase()}]`, ...args);
logCooldown.set(message, now);
// Cleanup old entries to prevent memory leak
if (logCooldown.size > 100) {
const cutoff = now - 60000;
for (const [msg, timestamp] of logCooldown.entries()) {
if (timestamp < cutoff) {
logCooldown.delete(msg);
}
}
}
}
}
}
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static('public'));
// Initialize database and scanner
let musicDB = null;
let appDB = null;
let musicScanner = null;
// Cache for converted audio files
const conversionCache = new Map();
async function initializeServer() {
try {
debugLog('SERVER', '🎵 Jukebox Data Server starting...');
// Ensure directories exist
await fs.ensureDir(path.join(ROOT_PATH, 'music'));
await fs.ensureDir(path.join(ROOT_PATH, 'data/converted'));
// Initialize database
musicDB = new MusicDatabase(path.join(ROOT_PATH, 'data/music.db'));
await musicDB.init();
await musicDB.createTables();
// Initialize app database (queue, session, settings)
appDB = new AppDatabase(path.join(ROOT_PATH, 'data/app.db'));
await appDB.init();
await appDB.createTables();
// Restore settings cache
await appDB.restoreCache();
// Load debugging setting
isDebuggingEnabled = await appDB.getSetting('admin', 'debuggingEnabled', true);
debugLog('SERVER', `🔧 Debugging ${isDebuggingEnabled ? 'enabled' : 'disabled'}`);
// Initialize scanner
musicScanner = new MusicScanner(path.join(ROOT_PATH, 'music'), musicDB);
await musicScanner.init();
debugLog('SERVER', '✅ Data Server initialized successfully');
// Start initial scan
debugLog('SERVER', '🔍 Starting initial music scan...');
await musicScanner.scanAll();
debugLog('SERVER', '📊 Initial scan completed');
// Start simple token cleanup (daily)
setInterval(async () => {
try {
const deletedCount = await appDB.cleanupExpiredSpotifyTokens();
if (deletedCount > 0) {
debugLog('SERVER', `🧹 Cleaned up ${deletedCount} expired Spotify token(s)`);
}
} catch (error) {
debugLog('SERVER', '❌ Token cleanup failed:', error.message);
}
}, 24 * 60 * 60 * 1000); // Every 24 hours
} catch (error) {
debugLog('SERVER', '❌ Failed to initialize server:', error.message);
console.error('❌ Failed to initialize server:', error);
process.exit(1);
}
}
// API Routes
app.get('/api/tracks', async (req, res) => {
try {
const { artist, album, genre, year, search, limit = 50000, offset = 0 } = req.query;
const tracks = await musicDB.getTracks({
artist,
album,
genre,
year,
search,
limit: parseInt(limit),
offset: parseInt(offset)
});
res.json({
success: true,
data: tracks,
total: tracks.length
});
} catch (error) {
debugLog('SERVER', '❌ Error fetching tracks:', error.message);
console.error('Error fetching tracks:', error);
res.status(500).json({ success: false, error: error.message });
}
});
app.get('/api/tracks/:id', async (req, res) => {
try {
const track = await musicDB.getTrackById(req.params.id);
if (!track) {
return res.status(404).json({ success: false, error: 'Track not found' });
}
res.json({ success: true, data: track });
} catch (error) {
debugLog('SERVER', '❌ Error fetching track:', error.message);
console.error('Error fetching track:', error);
res.status(500).json({ success: false, error: error.message });
}
});
app.get('/api/stream/:id', async (req, res) => {
try {
const track = await musicDB.getTrackById(req.params.id);
if (!track) {
return res.status(404).json({ success: false, error: 'Track not found' });
}
// Handle both relative and absolute paths correctly
let filePath;
if (path.isAbsolute(track.file_path)) {
// If file_path is absolute, check if it exists as-is first
if (await fs.pathExists(track.file_path)) {
filePath = track.file_path;
} else {
// If absolute path doesn't exist, try to make it relative to ROOT_PATH
const relativePath = path.relative(path.dirname(ROOT_PATH), track.file_path);
filePath = path.join(ROOT_PATH, relativePath);
}
} else {
// If file_path is relative, join with ROOT_PATH
filePath = path.join(ROOT_PATH, track.file_path);
}
if (!await fs.pathExists(filePath)) {
return res.status(404).json({ success: false, error: 'Audio file not found', attempted_path: filePath });
}
const fileExtension = path.extname(filePath).toLowerCase();
if (fileExtension !== '.mp3') {
return res.status(415).json({ success: false, error: 'Unsupported media type. Only MP3 files are supported.' });
}
debugLog('STREAM', `🎵 Serving MP3: ${track.title}`);
const stat = await fs.stat(filePath);
const range = req.headers.range;
if (range) {
// Handle range requests for audio seeking
const parts = range.replace(/bytes=/, "").split("-");
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : stat.size - 1;
const chunksize = (end - start) + 1;
res.writeHead(206, {
'Content-Range': `bytes ${start}-${end}/${stat.size}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'audio/mpeg',
'Cache-Control': 'public, max-age=3600',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Range'
});
fs.createReadStream(filePath, { start, end }).pipe(res);
} else {
res.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Range',
'Content-Length': stat.size,
'Accept-Ranges': 'bytes',
'Cache-Control': 'public, max-age=3600'
});
fs.createReadStream(filePath).pipe(res);
}
} catch (error) {
debugLog('SERVER', '❌ Error streaming track:', error.message);
console.error('Error streaming track:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Get cover art
app.get('/api/cover/:id', async (req, res) => {
try {
// Cache headers for browser cache (1 hour)
res.set({
'Cache-Control': 'public, max-age=3600',
'ETag': `"cover-${req.params.id}"`
});
const track = await musicDB.getTrackById(req.params.id);
if (!track || !track.cover_path) {
return res.sendFile(path.join(ROOT_PATH, 'assets/default_cover.png'));
}
const coverPath = path.join(ROOT_PATH, track.cover_path);
if (!await fs.pathExists(coverPath)) {
return res.sendFile(path.join(ROOT_PATH, 'assets/default_cover.png'));
}
res.sendFile(coverPath);
} catch (error) {
debugLog('COVER', '❌ Error fetching cover:', error.message);
console.error('Error fetching cover:', error);
res.sendFile(path.join(ROOT_PATH, 'assets/default_cover.png'));
}
});
// Get album cover by artist and album name
app.get('/api/album-cover/:albumKey', async (req, res) => {
try {
// Cache headers for browser cache (1 hour)
// Clean ETag value - only alphanumeric characters and hyphens
const cleanAlbumKey = req.params.albumKey.replace(/[^a-zA-Z0-9-]/g, '-');
res.set({
'Cache-Control': 'public, max-age=3600',
'ETag': `"album-${cleanAlbumKey}"`
});
debugLog('COVER', `Requesting album cover for: ${req.params.albumKey}`);
let albumKey;
try {
albumKey = decodeURIComponent(req.params.albumKey);
} catch (error) {
debugLog('COVER', `URI decode error for "${req.params.albumKey}": ${error.message}`);
// If decoding fails, use the original parameter
albumKey = req.params.albumKey;
}
const [artist, album] = albumKey.split('||');
debugLog('COVER', `Parsed artist: "${artist}", album: "${album}"`);
if (!artist || !album) {
debugLog('COVER', `Invalid artist/album, returning default cover`);
return res.sendFile(path.join(ROOT_PATH, 'assets/default_cover.png'));
}
// Find any track from this album that has a cover
const trackWithCover = await musicDB.getTrackWithCover(artist, album);
debugLog('COVER', `Found track with cover:`, trackWithCover ? 'Yes' : 'No');
if (!trackWithCover || !trackWithCover.cover_path) {
debugLog('COVER', `No cover found, returning default cover`);
return res.sendFile(path.join(ROOT_PATH, 'assets/default_cover.png'));
}
const coverPath = path.join(ROOT_PATH, trackWithCover.cover_path);
if (!await fs.pathExists(coverPath)) {
debugLog('COVER', `Cover file not found at ${coverPath}, returning default cover`);
return res.sendFile(path.join(ROOT_PATH, 'assets/default_cover.png'));
}
debugLog('COVER', `Serving cover from: ${coverPath}`);
res.sendFile(coverPath);
} catch (error) {
debugLog('COVER', '❌ Error fetching album cover:', error.message);
console.error('Error fetching album cover:', error);
res.sendFile(path.join(ROOT_PATH, 'assets/default_cover.png'));
}
});
// Get artist cover - mosaic of all album covers
app.get('/api/artist-cover/:artistName', async (req, res) => {
try {
// Cache headers for browser cache (1 hour)
// Clean ETag value - only alphanumeric characters and hyphens
const cleanArtistName = req.params.artistName.replace(/[^a-zA-Z0-9-]/g, '-');
res.set({
'Cache-Control': 'public, max-age=3600',
'ETag': `"artist-${cleanArtistName}"`
});
let artistName;
try {
artistName = decodeURIComponent(req.params.artistName);
} catch (error) {
debugLog('COVER', `URI decode error for artist "${req.params.artistName}": ${error.message}`);
// If decoding fails, use the original parameter
artistName = req.params.artistName;
}
debugLog('COVER', `Requesting artist cover for: ${artistName}`);
// Get all album covers for this artist
const albumCovers = await musicDB.getArtistAlbumCovers(artistName);
debugLog('COVER', `Found ${albumCovers.length} album covers for ${artistName}`);
if (albumCovers.length === 0) {
debugLog('COVER', `No covers found, returning default cover`);
return res.sendFile(path.join(ROOT_PATH, 'assets/default_cover.png'));
}
// Create cache directory for artist covers
const artistCoverCacheDir = path.join(ROOT_PATH, 'data/artist-covers');
await fs.ensureDir(artistCoverCacheDir);
// Create a safe filename for the artist
const safeArtistName = artistName.replace(/[^a-z0-9]/gi, '_').toLowerCase();
const artistCoverPath = path.join(artistCoverCacheDir, `${safeArtistName}_mosaic.jpg`);
// Check if cached version exists and is recent
try {
const cacheStats = await fs.stat(artistCoverPath);
const cacheAge = Date.now() - cacheStats.mtime.getTime();
const maxCacheAge = 24 * 60 * 60 * 1000; // 24 hours
if (cacheAge < maxCacheAge) {
debugLog('COVER', `Serving cached artist cover: ${artistCoverPath}`);
return res.sendFile(artistCoverPath);
}
} catch (err) {
// Cache doesn't exist, will create new one
}
debugLog('COVER', `Generating new artist mosaic for: ${artistName}`);
// Import sharp for image processing
const sharp = require('sharp');
// Determine grid size based on number of covers
let gridSize;
if (albumCovers.length === 1) {
gridSize = { cols: 1, rows: 1 };
} else if (albumCovers.length <= 4) {
gridSize = { cols: 2, rows: 2 };
} else if (albumCovers.length <= 9) {
gridSize = { cols: 3, rows: 3 };
} else if (albumCovers.length <= 16) {
gridSize = { cols: 4, rows: 4 };
} else {
gridSize = { cols: 5, rows: 5 };
}
const maxCovers = gridSize.cols * gridSize.rows;
const useCovers = albumCovers.slice(0, maxCovers);
// Cover size in final mosaic
const coverSize = 150;
const mosaicWidth = gridSize.cols * coverSize;
const mosaicHeight = gridSize.rows * coverSize;
// Create mosaic background
const mosaic = sharp({
create: {
width: mosaicWidth,
height: mosaicHeight,
channels: 3,
background: { r: 40, g: 40, b: 40 }
}
}).jpeg({ quality: 85 });
// Prepare cover images
const coverImages = [];
for (let i = 0; i < useCovers.length; i++) {
const cover = useCovers[i];
const coverPath = path.join(ROOT_PATH, cover.cover_path);
try {
// Check if cover file exists
await fs.access(coverPath);
// Resize cover to fit in grid
const resizedCover = await sharp(coverPath)
.resize(coverSize, coverSize, { fit: 'cover' })
.jpeg({ quality: 80 })
.toBuffer();
// Calculate position in grid
const row = Math.floor(i / gridSize.cols);
const col = i % gridSize.cols;
const left = col * coverSize;
const top = row * coverSize;
coverImages.push({
input: resizedCover,
left: left,
top: top
});
} catch (err) {
debugLog('COVER', `⚠️ Could not process cover: ${coverPath} - ${err.message}`);
}
}
// Composite all covers into mosaic
if (coverImages.length > 0) {
const finalMosaic = await mosaic.composite(coverImages).toBuffer();
// Save to cache
await fs.writeFile(artistCoverPath, finalMosaic);
debugLog('COVER', `Created and cached artist mosaic: ${artistCoverPath}`);
// Send the generated mosaic
res.setHeader('Content-Type', 'image/jpeg');
res.setHeader('Cache-Control', 'public, max-age=86400'); // 24 hours cache
res.send(finalMosaic);
} else {
debugLog('COVER', `No valid covers found, returning default`);
res.sendFile(path.join(ROOT_PATH, 'assets/default_cover.png'));
}
} catch (error) {
debugLog('COVER', '❌ Error creating artist cover:', error.message);
console.error('Error creating artist cover:', error);
res.sendFile(path.join(ROOT_PATH, 'assets/default_cover.png'));
}
});
// Get all artists
app.get('/api/artists', async (req, res) => {
try {
const artists = await musicDB.getArtists();
res.json({ success: true, data: artists });
} catch (error) {
debugLog('SERVER', '❌ Error fetching artists:', error.message);
console.error('Error fetching artists:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Get all albums
app.get('/api/albums', async (req, res) => {
try {
const { artist } = req.query;
const albums = await musicDB.getAlbums(artist);
res.json({ success: true, data: albums });
} catch (error) {
debugLog('SERVER', '❌ Error fetching albums:', error.message);
console.error('Error fetching albums:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Get all genres
app.get('/api/genres', async (req, res) => {
try {
const genres = await musicDB.getGenres();
res.json({ success: true, data: genres });
} catch (error) {
debugLog('SERVER', '❌ Error fetching genres:', error.message);
console.error('Error fetching genres:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Manual rescan
app.post('/api/rescan', async (req, res) => {
try {
debugLog('SERVER', '🔄 Manual rescan requested');
await musicScanner.scanAll();
res.json({ success: true, message: 'Rescan completed' });
} catch (error) {
debugLog('SERVER', '❌ Error during rescan:', error.message);
console.error('Error during rescan:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Update track play count
app.post('/api/tracks/:id/play', async (req, res) => {
try {
const trackId = req.params.id;
const track = await musicDB.getTrackById(trackId);
if (!track) {
return res.status(404).json({ success: false, error: 'Track not found' });
}
await musicDB.updateTrackPlayCount(trackId);
debugLog('DATA-API', `📊 Updated play count for: ${track.title} by ${track.artist}`);
res.json({
success: true,
message: 'Play count updated',
trackId: parseInt(trackId)
});
} catch (error) {
debugLog('DATA-API', '❌ Error updating track play count:', error.message);
console.error('Error updating track play count:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Update Spotify track play count
app.post('/api/spotify/:spotify_id/play', async (req, res) => {
try {
let spotifyId = req.params.spotify_id;
const { trackData } = req.body; // Optional track data for auto-adding
// Remove 'spotify_' prefix if present (fix for prefixed IDs)
if (spotifyId.startsWith('spotify_')) {
spotifyId = spotifyId.replace('spotify_', '');
debugLog('SPOTIFY', `Removed spotify_ prefix, using ID: ${spotifyId}`);
}
let track = await musicDB.getSpotifyTrack(spotifyId);
if (!track) {
// If track data is provided, try to add the track automatically
if (trackData && trackData.title && trackData.artist) {
debugLog('SPOTIFY', `Auto-adding Spotify track: ${trackData.title} by ${trackData.artist}`);
const spotifyTrack = {
spotify_id: spotifyId,
title: trackData.title,
artist: trackData.artist,
album: trackData.album || '',
duration_ms: trackData.duration_ms || 0,
preview_url: trackData.preview_url || null,
external_url: trackData.external_url || null,
image_url: trackData.image_url || null,
popularity: trackData.popularity || 0,
added_at: new Date().toISOString()
};
try {
const trackId = await musicDB.addSpotifyTrack(spotifyTrack);
track = await musicDB.getSpotifyTrack(spotifyId);
debugLog('SPOTIFY', `📊 Auto-added Spotify track: ${trackData.title} by ${trackData.artist}`);
} catch (addError) {
debugLog('SPOTIFY', `⚠️ Could not auto-add Spotify track ${spotifyId}: ${addError.message}`);
}
}
if (!track) {
// Track still not found - return success but no action taken
debugLog('SPOTIFY', `Track ${spotifyId} not found in database - skipping play count`);
return res.json({
success: true,
message: 'Spotify track not in database - play count not recorded',
spotifyId: spotifyId,
tracked: false
});
}
}
// Update play count for existing/added track
await musicDB.updateSpotifyTrackPlayCount(spotifyId);
debugLog('SPOTIFY', `📊 Updated Spotify play count for: ${track.title} by ${track.artist}`);
res.json({
success: true,
message: 'Spotify play count updated',
spotifyId: spotifyId,
tracked: true
});
} catch (error) {
console.error('Error updating Spotify track play count:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Get most played tracks
app.get('/api/most-played', async (req, res) => {
try {
const limit = parseInt(req.query.limit) || 10;
const tracks = await musicDB.getMostPlayedTracks(limit);
res.json({
success: true,
data: tracks,
total: tracks.length
});
} catch (error) {
console.error('Error fetching most played tracks:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Get play statistics
app.get('/api/play-stats', async (req, res) => {
try {
const stats = await musicDB.getPlayStats();
res.json({
success: true,
data: stats
});
} catch (error) {
console.error('Error fetching play statistics:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Get play statistics for GEMA reporting (by date range)
app.get('/api/plays', async (req, res) => {
try {
const { start, end } = req.query;
if (!start || !end) {
return res.status(400).json({
success: false,
error: 'Start and end timestamps are required'
});
}
const startTimestamp = parseInt(start);
const endTimestamp = parseInt(end);
if (isNaN(startTimestamp) || isNaN(endTimestamp)) {
return res.status(400).json({
success: false,
error: 'Invalid timestamp format'
});
}
debugLog('REPORTING', `Fetching plays from ${new Date(startTimestamp)} to ${new Date(endTimestamp)}`);
const plays = await musicDB.getPlaysForPeriod(startTimestamp, endTimestamp);
res.json({
success: true,
plays: plays,
count: plays.length,
period: {
start: new Date(startTimestamp).toISOString(),
end: new Date(endTimestamp).toISOString()
}
});
} catch (error) {
console.error('Error fetching plays for period:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Record detailed play history for GEMA reporting
app.post('/api/play-history', async (req, res) => {
try {
const { trackData, source } = req.body;
if (!trackData || !source) {
return res.status(400).json({
success: false,
error: 'Track data and source are required'
});
}
if (!['local', 'spotify'].includes(source)) {
return res.status(400).json({
success: false,
error: 'Source must be either "local" or "spotify"'
});
}
debugLog('REPORTING', `Recording play history: ${trackData.artist} - ${trackData.title} (${source})`);
const result = await musicDB.recordPlayHistory(trackData, source);
res.json({
success: true,
data: result,
message: 'Play history recorded successfully'
});
} catch (error) {
console.error('Error recording play history:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Server stats
app.get('/api/stats', async (req, res) => {
try {
const stats = await musicDB.getStats();
res.json({ success: true, data: stats });
} catch (error) {
console.error('Error fetching stats:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Health check
app.get('/api/health', (req, res) => {
res.json({
success: true,
status: 'healthy',
uptime: process.uptime(),
memory: process.memoryUsage(),
debugging: isDebuggingEnabled
});
});
// Debug configuration endpoint
app.post('/api/debug-config', (req, res) => {
try {
const { enabled } = req.body;
if (typeof enabled === 'boolean') {
isDebuggingEnabled = enabled;
if (enabled) {
console.log('[SERVER] 🐛 DATA SERVER DEBUGGING AKTIVIERT - Debug-Ausgaben werden angezeigt');
debugLog('SERVER', 'Debugging wurde vom Frontend eingeschaltet');
} else {
console.log('[SERVER] 🔇 Normal server mode active, enable debugging in the Jukebox App for debug output.');
}
res.json({ success: true, debugging: isDebuggingEnabled });
} else {
res.status(400).json({ success: false, error: 'Invalid enabled parameter' });
}
} catch (error) {
console.error('Error updating debug config:', error);
res.status(500).json({ success: false, error: error.message });
}
});
app.get('/api/debug-config', (req, res) => {
res.json({ success: true, debugging: isDebuggingEnabled });
});
// Spotify Integration Routes
// Add Spotify track to database
app.post('/api/spotify/add', async (req, res) => {
try {
const {
spotify_id,
name,
artist,
album,
year,
genre,
duration_ms,
image_url,
preview_url,
spotify_uri,
popularity
} = req.body;
// Check if track already exists
const existingTrack = await musicDB.getSpotifyTrack(spotify_id);
if (existingTrack) {
// Check if track was recently added (within last 60 minutes)
const addedDate = new Date(existingTrack.added_date);
const now = new Date();
const timeDifference = now - addedDate;
const oneHourMs = 60 * 60 * 1000; // 60 minutes in milliseconds
if (timeDifference < oneHourMs) {
const remainingMinutes = Math.ceil((oneHourMs - timeDifference) / (60 * 1000));
return res.status(429).json({
success: false,
message: `Track wurde kürzlich hinzugefügt. Bitte warte noch ${remainingMinutes} Minuten.`,
remainingMinutes: remainingMinutes
});
}
return res.json({
success: true,
message: 'Track already in library',
track: existingTrack
});
}
// Add track to database
const trackId = await musicDB.addSpotifyTrack({
spotify_id,
title: name,
artist,
album,
year: parseInt(year) || null,
genre,
duration: Math.floor(duration_ms / 1000),
image_url,
preview_url,
spotify_uri,
popularity: popularity || 0,
added_date: new Date().toISOString()
});
const track = await musicDB.getTrackById(trackId);
debugLog('SPOTIFY', `✅ Added Spotify track: ${artist} - ${name}`);
res.json({
success: true,
message: 'Track added to library',
track
});
} catch (error) {
console.error('Error adding Spotify track:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Get Spotify tracks from database
app.get('/api/spotify/tracks', async (req, res) => {
try {
const { limit = 50, offset = 0, search } = req.query;
const tracks = await musicDB.getSpotifyTracks({
limit: parseInt(limit),
offset: parseInt(offset),
search
});
res.json({
success: true,
tracks,
count: tracks.length
});
} catch (error) {
console.error('Error fetching Spotify tracks:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Remove Spotify track from database
app.delete('/api/spotify/:spotify_id', async (req, res) => {
try {
const { spotify_id } = req.params;
await musicDB.removeSpotifyTrack(spotify_id);
debugLog('SPOTIFY', `🗑️ Removed Spotify track: ${spotify_id}`);
res.json({
success: true,
message: 'Spotify track removed from library'
});
} catch (error) {
console.error('Error removing Spotify track:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Bulk add Spotify tracks (for auto-learning)
app.post('/api/spotify/bulk-add', async (req, res) => {
try {
const { tracks } = req.body;
if (!Array.isArray(tracks)) {
return res.status(400).json({
success: false,
error: 'Tracks must be an array'
});
}
let addedCount = 0;
let skippedCount = 0;
const results = [];
for (const trackData of tracks) {
try {
// Check if track already exists
const existingTrack = await musicDB.getSpotifyTrack(trackData.spotify_id);
if (existingTrack) {
skippedCount++;
continue;
}
// Add track to database
const trackId = await musicDB.addSpotifyTrack({
spotify_id: trackData.spotify_id,
title: trackData.name,
artist: trackData.artist,
album: trackData.album,
year: parseInt(trackData.year) || null,
genre: trackData.genre || 'Unknown',
duration: Math.floor(trackData.duration_ms / 1000),
image_url: trackData.image_url,
preview_url: trackData.preview_url,
spotify_uri: trackData.spotify_uri,
popularity: trackData.popularity || 0,
added_date: new Date().toISOString()
});
addedCount++;
results.push({ trackId, spotify_id: trackData.spotify_id });
} catch (error) {
debugLog('SPOTIFY', `❌ Failed to add track ${trackData.spotify_id}: ${error.message}`);
}
}
debugLog('SPOTIFY', `✅ Bulk added ${addedCount} Spotify tracks, skipped ${skippedCount} existing`);
res.json({
success: true,
message: `Added ${addedCount} tracks, skipped ${skippedCount} existing`,
addedCount,
skippedCount,
results
});
} catch (error) {
console.error('Error bulk adding Spotify tracks:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Clean up orphaned database entries
app.post('/api/cleanup', async (req, res) => {
try {
debugLog('SERVER', '🧹 Starting database cleanup...');
// Get all tracks from database using getTracks method
const tracks = await musicDB.getTracks({ limit: 10000 });
let removedCount = 0;
for (const track of tracks) {
if (track.file_path && !await fs.pathExists(track.file_path)) {
// File doesn't exist, remove from database using ID
await musicDB.removeTrack(track.id);
removedCount++;
debugLog('SERVER', `🗑️ Removed orphaned track: ${track.title} (${track.file_path})`);
}
}
// Clean up empty artists and albums
await musicDB.cleanupOrphans();
debugLog('SERVER', `✅ Cleanup completed: ${removedCount} orphaned tracks removed`);
res.json({
success: true,
message: `Cleanup completed: ${removedCount} orphaned tracks removed`,
removedCount
});
} catch (error) {
console.error('❌ Cleanup failed:', error);
res.status(500).json({
success: false,
error: error.message
});
}
});
// Clear entire database (admin function)
app.post('/api/clear-database', async (req, res) => {
try {
debugLog('SERVER', '🗑️ Starting complete database clear...');
await musicDB.clearDatabase();