-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
602 lines (514 loc) · 20.9 KB
/
server.js
File metadata and controls
602 lines (514 loc) · 20.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
const express = require('express');
const fs = require('fs').promises;
const fsSync = require('fs');
const path = require('path');
const cors = require('cors');
const multer = require('multer');
const app = express();
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0';
// CRITICAL: Set proper MIME types for WASM files
express.static.mime.types['wasm'] = 'application/wasm';
express.static.mime.types['mem'] = 'application/octet-stream';
// Middleware
app.use(cors());
// IMPORTANT: Serve static files with proper headers for WASM
app.use('/js', express.static(path.join(__dirname, 'public', 'js'), {
setHeaders: (res, filepath) => {
if (filepath.endsWith('.mem')) {
res.set('Content-Type', 'application/octet-stream');
} else if (filepath.endsWith('.wasm')) {
res.set('Content-Type', 'application/wasm');
} else if (filepath.endsWith('.js')) {
res.set('Content-Type', 'application/javascript');
}
// Allow WASM compilation
res.set('Cross-Origin-Embedder-Policy', 'require-corp');
res.set('Cross-Origin-Opener-Policy', 'same-origin');
}
}));
// Serve other static files
app.use(express.static('public'));
app.use(express.json());
// Enhanced logging with better error handling
const log = async (message, level = 'INFO') => {
const timestamp = new Date().toISOString();
const logMessage = `[${timestamp}] ${level}: ${message}`;
console.log(logMessage);
try {
const logsDir = path.join(__dirname, 'logs');
if (!fsSync.existsSync(logsDir)) {
await fs.mkdir(logsDir, { recursive: true });
}
await fs.appendFile(path.join(logsDir, 'app.log'), logMessage + '\n');
} catch (err) {
if (level === 'ERROR') {
console.error(`⚠️ Log write failed (${err.code}): Check directory permissions for /app/logs/`);
}
}
};
// Initialize directories
const initDirectories = async () => {
const dirs = [
path.join(__dirname, 'public', 'music'),
path.join(__dirname, 'public', 'soundfonts'),
path.join(__dirname, 'public', 'js'),
path.join(__dirname, 'public', 'css'),
path.join(__dirname, 'logs')
];
for (const dir of dirs) {
try {
if (!fsSync.existsSync(dir)) {
await fs.mkdir(dir, { recursive: true });
await log(`Created directory: ${dir}`);
}
} catch (error) {
await log(`Failed to create directory ${dir}: ${error.message}`, 'ERROR');
}
}
};
// API endpoint to list music files with better error handling
app.get('/api/music-files', async (req, res) => {
try {
const musicDir = path.join(__dirname, 'public', 'music');
if (!fsSync.existsSync(musicDir)) {
await log('Music directory does not exist, creating it...', 'WARN');
await fs.mkdir(musicDir, { recursive: true });
return res.json([]);
}
const files = await fs.readdir(musicDir);
const allowedExtensions = ['.mod', '.xm', '.it', '.s3m', '.mid', '.midi', '.sf2'];
const musicFiles = [];
for (const file of files) {
const ext = path.extname(file).toLowerCase();
if (allowedExtensions.includes(ext)) {
try {
const filePath = path.join(musicDir, file);
const stats = await fs.stat(filePath);
musicFiles.push({
filename: file,
size: stats.size,
modified: stats.mtime,
type: ['.mod', '.xm', '.it', '.s3m'].includes(ext) ? 'tracker' :
ext === '.sf2' ? 'soundfont' : 'midi',
displaySize: formatFileSize(stats.size)
});
} catch (statError) {
if (statError.code === 'EACCES') {
await log(`Permission denied accessing ${file}. Check file permissions.`, 'WARN');
musicFiles.push({
filename: file,
size: 0,
modified: new Date(),
type: ['.mod', '.xm', '.it', '.s3m'].includes(ext) ? 'tracker' :
ext === '.sf2' ? 'soundfont' : 'midi',
displaySize: 'Permission denied',
error: 'EACCES'
});
} else {
await log(`Error getting stats for ${file}: ${statError.message}`, 'WARN');
}
}
}
}
musicFiles.sort((a, b) => a.filename.localeCompare(b.filename));
await log(`Found ${musicFiles.length} music files`);
res.json(musicFiles);
} catch (error) {
await log(`Error scanning music directory: ${error.message}`, 'ERROR');
res.status(500).json({ error: 'Unable to scan music directory' });
}
});
// API endpoint to check WASM support
app.get('/api/wasm-check', async (req, res) => {
try {
const jsDir = path.join(__dirname, 'public', 'js');
const wasmFiles = {
'libopenmpt.js': false,
'libopenmpt.js.mem': false,
'libopenmpt.wasm': false,
'libfluidsynth-2.3.0.js': false,
'libfluidsynth-2.3.0.wasm': false
};
for (const file of Object.keys(wasmFiles)) {
if (fsSync.existsSync(path.join(jsDir, file))) {
wasmFiles[file] = true;
const stats = await fs.stat(path.join(jsDir, file));
wasmFiles[file] = { exists: true, size: stats.size };
}
}
res.json({
wasmSupported: true,
files: wasmFiles,
headers: {
'Cross-Origin-Embedder-Policy': res.get('Cross-Origin-Embedder-Policy'),
'Cross-Origin-Opener-Policy': res.get('Cross-Origin-Opener-Policy')
}
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// API endpoint to get file info
app.get('/api/file-info/:filename', async (req, res) => {
try {
const filename = req.params.filename;
const filePath = path.join(__dirname, 'public', 'music', filename);
if (!fsSync.existsSync(filePath)) {
return res.status(404).json({ error: 'File not found' });
}
const stats = await fs.stat(filePath);
const ext = path.extname(filename).toLowerCase();
res.json({
filename,
size: stats.size,
displaySize: formatFileSize(stats.size),
modified: stats.mtime,
type: ['.mod', '.xm', '.it', '.s3m'].includes(ext) ? 'tracker' :
ext === '.sf2' ? 'soundfont' : 'midi'
});
} catch (error) {
await log(`Error getting file info: ${error.message}`, 'ERROR');
res.status(500).json({ error: 'Unable to get file info' });
}
});
// API endpoint to list soundfonts
app.get('/api/soundfonts', async (req, res) => {
try {
const soundfontsDir = path.join(__dirname, 'public', 'soundfonts');
if (!fsSync.existsSync(soundfontsDir)) {
return res.json([]);
}
const files = await fs.readdir(soundfontsDir);
const soundfonts = [];
for (const file of files) {
if (path.extname(file).toLowerCase() === '.sf2') {
try {
const filePath = path.join(soundfontsDir, file);
const stats = await fs.stat(filePath);
soundfonts.push({
filename: file,
size: stats.size,
displaySize: formatFileSize(stats.size),
modified: stats.mtime
});
} catch (statError) {
await log(`Error getting stats for ${file}: ${statError.message}`, 'WARN');
}
}
}
res.json(soundfonts);
} catch (error) {
await log(`Error listing soundfonts: ${error.message}`, 'ERROR');
res.status(500).json({ error: 'Unable to list soundfonts' });
}
});
// Upload configuration
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const ext = path.extname(file.originalname).toLowerCase();
let destDir;
if (ext === '.sf2') {
destDir = path.join(__dirname, 'public', 'soundfonts');
} else {
destDir = path.join(__dirname, 'public', 'music');
}
if (!fsSync.existsSync(destDir)) {
fsSync.mkdirSync(destDir, { recursive: true });
}
cb(null, destDir);
},
filename: (req, file, cb) => {
const sanitized = file.originalname.replace(/[^a-zA-Z0-9.-]/g, '_');
cb(null, sanitized);
}
});
const upload = multer({
storage,
fileFilter: (req, file, cb) => {
const allowedExtensions = ['.mod', '.xm', '.it', '.s3m', '.mid', '.midi', '.sf2'];
const ext = path.extname(file.originalname).toLowerCase();
cb(null, allowedExtensions.includes(ext));
},
limits: { fileSize: 200 * 1024 * 1024 }
});
app.post('/api/upload', upload.single('musicFile'), async (req, res) => {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded or invalid format' });
}
const fileType = path.extname(req.file.filename).toLowerCase() === '.sf2' ? 'soundfont' : 'music';
await log(`File uploaded: ${req.file.filename} (${formatFileSize(req.file.size)}) - Type: ${fileType}`);
res.json({
message: 'File uploaded successfully',
filename: req.file.filename,
size: req.file.size,
displaySize: formatFileSize(req.file.size),
type: fileType
});
});
// Delete file endpoint
app.delete('/api/delete/:filename', async (req, res) => {
try {
const filename = req.params.filename;
const ext = path.extname(filename).toLowerCase();
let filePath;
if (ext === '.sf2') {
filePath = path.join(__dirname, 'public', 'soundfonts', filename);
} else {
filePath = path.join(__dirname, 'public', 'music', filename);
}
if (!fsSync.existsSync(filePath)) {
return res.status(404).json({ error: 'File not found' });
}
await fs.unlink(filePath);
await log(`File deleted: ${filename}`);
res.json({ message: 'File deleted successfully' });
} catch (error) {
await log(`Error deleting file: ${error.message}`, 'ERROR');
res.status(500).json({ error: 'Unable to delete file' });
}
});
// SoundFont management endpoint
app.post('/api/set-default-soundfont/:filename', async (req, res) => {
try {
const filename = req.params.filename;
const soundfontPath = path.join(__dirname, 'public', 'soundfonts', filename);
if (!fsSync.existsSync(soundfontPath)) {
return res.status(404).json({ error: 'SoundFont not found' });
}
const defaultPath = path.join(__dirname, 'public', 'soundfonts', 'default.sf2');
if (fsSync.existsSync(defaultPath)) {
await fs.unlink(defaultPath);
}
await fs.copyFile(soundfontPath, defaultPath);
await log(`Default SoundFont set to: ${filename}`);
res.json({ message: `Default SoundFont set to ${filename}` });
} catch (error) {
await log(`Error setting default SoundFont: ${error.message}`, 'ERROR');
res.status(500).json({ error: 'Unable to set default SoundFont' });
}
});
// Serve main page with proper CORS headers for WASM
app.get('/', (req, res) => {
res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp');
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Health check endpoint
app.get('/health', async (req, res) => {
try {
const musicDir = path.join(__dirname, 'public', 'music');
const soundfontsDir = path.join(__dirname, 'public', 'soundfonts');
const jsDir = path.join(__dirname, 'public', 'js');
const musicDirExists = fsSync.existsSync(musicDir);
const soundfontsDirExists = fsSync.existsSync(soundfontsDir);
const jsDirExists = fsSync.existsSync(jsDir);
let musicFileCount = 0;
let soundfontCount = 0;
let jsFileCount = 0;
if (musicDirExists) {
try {
const musicFiles = await fs.readdir(musicDir);
musicFileCount = musicFiles.filter(f =>
['.mod', '.xm', '.it', '.s3m', '.mid', '.midi'].includes(path.extname(f).toLowerCase())
).length;
} catch (err) {
await log(`Error counting music files: ${err.message}`, 'WARN');
}
}
if (soundfontsDirExists) {
try {
const sfFiles = await fs.readdir(soundfontsDir);
soundfontCount = sfFiles.filter(f => f.endsWith('.sf2')).length;
} catch (err) {
await log(`Error counting soundfont files: ${err.message}`, 'WARN');
}
}
if (jsDirExists) {
try {
const jsFiles = await fs.readdir(jsDir);
jsFileCount = jsFiles.length;
} catch (err) {
await log(`Error counting JS files: ${err.message}`, 'WARN');
}
}
// Check for critical JS and WASM files
const criticalFiles = [
'fallback-audio-engine.js',
'libopenmpt.js',
'libopenmpt.js.mem',
'chiptune2.js'
];
const missingFiles = [];
for (const file of criticalFiles) {
if (!fsSync.existsSync(path.join(jsDir, file))) {
missingFiles.push(file);
}
}
const isHealthy = musicDirExists && soundfontsDirExists && jsDirExists && missingFiles.length === 0;
const healthData = {
status: isHealthy ? 'healthy' : 'degraded',
timestamp: new Date().toISOString(),
uptime: Math.floor(process.uptime()),
host: HOST,
port: PORT,
directories: {
music: musicDirExists,
soundfonts: soundfontsDirExists,
javascript: jsDirExists
},
counts: {
musicFiles: musicFileCount,
soundfonts: soundfontCount,
jsFiles: jsFileCount
},
missingCriticalFiles: missingFiles,
version: '2.3.0',
engines: {
openmpt: missingFiles.includes('libopenmpt.js') ? 'missing' : 'available',
audioWorklet: missingFiles.includes('fallback-audio-engine.js') ? 'missing' : 'available'
}
};
res.status(isHealthy ? 200 : 503).json(healthData);
} catch (error) {
await log(`Health check error: ${error.message}`, 'ERROR');
res.status(503).json({
status: 'unhealthy',
error: error.message,
timestamp: new Date().toISOString()
});
}
});
// System info endpoint
app.get('/api/system-info', async (req, res) => {
const musicDir = path.join(__dirname, 'public', 'music');
const soundfontsDir = path.join(__dirname, 'public', 'soundfonts');
const musicStats = fsSync.existsSync(musicDir) ? await fs.readdir(musicDir) : [];
const soundfontStats = fsSync.existsSync(soundfontsDir) ?
(await fs.readdir(soundfontsDir)).filter(f => f.endsWith('.sf2')) : [];
res.json({
uptime: Math.floor(process.uptime()),
memory: process.memoryUsage(),
platform: process.platform,
nodeVersion: process.version,
host: HOST,
port: PORT,
totalMusicFiles: musicStats.length,
totalSoundfonts: soundfontStats.length,
musicDiskUsage: await getDiskUsage(musicDir),
soundfontsDiskUsage: await getDiskUsage(soundfontsDir),
audioEngines: {
openmpt: {
status: 'available',
formats: ['.mod', '.xm', '.it', '.s3m']
},
fluidsynth: {
status: soundfontStats.length > 0 ? 'available' : 'no_soundfonts',
formats: ['.mid', '.midi'],
soundfonts: soundfontStats.length
}
}
});
});
// Error handling middleware
app.use((err, req, res, next) => {
log(`Server error: ${err.message}`, 'ERROR');
res.status(500).json({ error: 'Internal server error' });
});
// 404 handler
app.use((req, res) => {
log(`404 - ${req.method} ${req.url}`, 'WARN');
res.status(404).json({ error: 'Not found' });
});
// Utility functions
function formatFileSize(bytes) {
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
if (bytes === 0) return '0 Bytes';
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
}
async function getDiskUsage(dir) {
try {
if (!fsSync.existsSync(dir)) return { totalSize: 0, fileCount: 0 };
const files = await fs.readdir(dir);
let totalSize = 0;
for (const file of files) {
try {
const filePath = path.join(dir, file);
const stats = await fs.stat(filePath);
totalSize += stats.size;
} catch (error) {
// Skip files we can't read
}
}
return {
totalSize: totalSize,
displaySize: formatFileSize(totalSize),
fileCount: files.length
};
} catch (error) {
return { totalSize: 0, fileCount: 0, error: error.message };
}
}
// Server startup with proper initialization
const startServer = async () => {
try {
await initDirectories();
await log('🎵 Initializing Fusion Music Player Server v2.0...');
const server = app.listen(PORT, HOST, async () => {
await log(`🌐 Server running on ${HOST}:${PORT}`);
await log(`🐳 Docker mode: ${process.env.NODE_ENV === 'production' ? 'YES' : 'NO'}`);
await log(`🔗 Access URLs:`);
await log(` Local: http://localhost:${PORT}`);
await log(` Network: http://${HOST}:${PORT}`);
await log(`📦 WASM Support: Enabled with proper MIME types`);
// Log initial file counts
try {
const musicDir = path.join(__dirname, 'public', 'music');
const soundfontsDir = path.join(__dirname, 'public', 'soundfonts');
if (fsSync.existsSync(musicDir)) {
const musicFiles = await fs.readdir(musicDir);
await log(`💿 Found ${musicFiles.length} files in music directory`);
}
if (fsSync.existsSync(soundfontsDir)) {
const soundfontFiles = await fs.readdir(soundfontsDir);
const sf2Files = soundfontFiles.filter(f => f.endsWith('.sf2'));
await log(`🎼 Found ${sf2Files.length} SoundFont files`);
}
} catch (error) {
await log(`Error during initial scan: ${error.message}`, 'ERROR');
}
});
// Handle server errors
server.on('error', async (err) => {
if (err.code === 'EADDRINUSE') {
await log(`❌ Port ${PORT} is already in use`, 'ERROR');
process.exit(1);
} else {
await log(`❌ Server error: ${err.message}`, 'ERROR');
throw err;
}
});
} catch (error) {
await log(`Failed to start server: ${error.message}`, 'ERROR');
process.exit(1);
}
};
// Graceful shutdown
const gracefulShutdown = async (signal) => {
await log(`🛑 Received ${signal}, shutting down gracefully`);
process.exit(0);
};
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
// Handle uncaught exceptions
process.on('uncaughtException', async (err) => {
await log(`Uncaught Exception: ${err.message}`, 'ERROR');
console.error(err.stack);
process.exit(1);
});
process.on('unhandledRejection', async (reason, promise) => {
await log(`Unhandled Rejection at: ${promise} reason: ${reason}`, 'ERROR');
});
// Start the server
startServer();