-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.php
More file actions
727 lines (623 loc) · 24.1 KB
/
api.php
File metadata and controls
727 lines (623 loc) · 24.1 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
<?php
/**
* MelodyHub - Audio Player API
*
* Backend API for the MelodyHub audio player web application.
* Handles directory listing, audio file streaming, cover art serving,
* and playlist loading with security checks.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Audio Player API
*
* This script provides backend functionality for the audio player web application.
* It handles directory listing, audio file streaming, cover art serving, and playlist loading.
*
* Endpoints:
* - ?action=list&path=[path] - List directory contents
* - ?action=play&file=[file] - Stream an audio file
* - ?action=cover&file=[file] - Serve a cover art image
* - ?action=loadPlaylist&path=[file] - Load a playlist file
*/
// Include configuration file
require_once 'config.php';
// Get the requested action
$action = $_GET['action'] ?? '';
// Route to appropriate function based on action
switch ($action) {
case 'list':
header('Content-Type: application/json');
listDirectory();
break;
case 'play':
playAudio();
break;
case 'cover':
serveCoverArt();
break;
case 'loadPlaylist':
header('Content-Type: application/json');
loadPlaylist();
break;
case 'getDirectoryFiles':
header('Content-Type: application/json');
getDirectoryFiles();
break;
default:
header('Content-Type: application/json');
echo json_encode(['error' => 'Invalid action']);
break;
}
/**
* List directory contents
*
* This function returns a JSON array of files and directories in the specified path.
* It includes security checks to prevent directory traversal attacks.
*
* @return void Outputs JSON response with file listing
*/
function listDirectory() {
global $basePath;
// Get the requested path, default to empty string
$path = $_GET['path'] ?? '';
// Security check to prevent directory traversal
// realpath() resolves symbolic links and returns absolute path
// strpos() ensures the resolved path is within the base path
$fullPath = realpath($basePath . '/' . $path);
$realBasePath = realpath($basePath);
// Additional security checks
if (!$fullPath || !$realBasePath || strpos($fullPath, $realBasePath) !== 0) {
echo json_encode(['error' => 'Invalid path']);
return;
}
// Ensure we're still within the base path after normalization
$normalizedPath = str_replace('\\', '/', substr($fullPath, strlen($realBasePath)));
if (preg_match('/\.\.(\/|\\\\|$)/', $normalizedPath)) {
echo json_encode(['error' => 'Invalid path']);
return;
}
// Check if the path is actually a directory
if (!is_dir($fullPath)) {
echo json_encode(['error' => 'Directory not found']);
return;
}
// Initialize files array
$files = [];
// Get directory contents
$items = scandir($fullPath);
// Initialize files array
$files = [];
$coverArt = null; // Cover art for current directory files
// Process each item in the directory
foreach ($items as $item) {
// Skip current and parent directory references
if ($item === '.' || $item === '..') continue;
// Build full path and relative path
$itemPath = $fullPath . '/' . $item;
$relativePath = $path ? $path . '/' . $item : $item;
// Check if item is a directory
if (is_dir($itemPath)) {
// For directories, check if they contain audio files and look for cover art
$dirCoverArt = findCoverArtInDirectory($itemPath);
if ($dirCoverArt) {
// Convert to relative path
$dirCoverArt = substr($dirCoverArt, strlen(realpath($basePath)) + 1);
}
$files[] = [
'name' => $item,
'type' => 'directory',
'path' => $relativePath,
'coverArt' => $dirCoverArt
];
} else {
// For files, extract extension for type identification
$extension = strtolower(pathinfo($item, PATHINFO_EXTENSION));
// Define supported audio extensions
$audioExtensions = ['mp3', 'wav', 'ogg', 'flac', 'm4a', 'aac'];
// Define supported image extensions for cover art
$imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
// Check for cover art files
if (in_array($extension, $imageExtensions) && isCoverArt($item)) {
// Store the first cover art found
if ($coverArt === null) {
$coverArt = $relativePath;
}
}
// Only include audio files and playlist files
else if (in_array($extension, $audioExtensions) || in_array($extension, ['m3u', 'm3u8', 'pls'])) {
$files[] = [
'name' => $item,
'type' => 'file',
'extension' => $extension,
'path' => $relativePath
];
}
}
}
// Add cover art to each file entry if found
if ($coverArt !== null) {
foreach ($files as &$file) {
// Only add cover art to file entries, not directories (they already have their own)
if ($file['type'] !== 'directory') {
$file['coverArt'] = $coverArt;
}
}
$response = ['files' => $files, 'coverArt' => $coverArt];
} else {
$response = ['files' => $files];
}
// Sort items: directories first, then files, both alphabetically
usort($files, function($a, $b) {
// If both items are the same type, sort by name
if ($a['type'] === $b['type']) {
return strcmp($a['name'], $b['name']);
}
// Directories come before files
return $a['type'] === 'directory' ? -1 : 1;
});
// Return JSON response with file list
echo json_encode($response);
}
/**
* Stream an audio file
*
* This function streams an audio file to the client with appropriate headers.
* It includes security checks to prevent unauthorized file access.
*
* @return void Streams audio file content or returns 404 error
*/
function playAudio() {
global $basePath;
// Get the requested file path
$file = $_GET['file'] ?? '';
// Security check to prevent directory traversal
$fullPath = realpath($basePath . '/' . $file);
$realBasePath = realpath($basePath);
// Additional security checks
if (!$fullPath || !$realBasePath || strpos($fullPath, $realBasePath) !== 0) {
http_response_code(404);
echo 'File not found';
return;
}
// Ensure we're still within the base path after normalization
$normalizedPath = str_replace('\\', '/', substr($fullPath, strlen($realBasePath)));
if (preg_match('/\.\.(\/|\\\\|$)/', $normalizedPath)) {
http_response_code(404);
echo 'File not found';
return;
}
// Check if file exists
if (!file_exists($fullPath)) {
http_response_code(404);
echo 'File not found';
return;
}
// Determine content type based on file extension
$extension = strtolower(pathinfo($fullPath, PATHINFO_EXTENSION));
$mimeTypes = [
'mp3' => 'audio/mpeg',
'wav' => 'audio/wav',
'ogg' => 'audio/ogg',
'flac' => 'audio/flac',
'm4a' => 'audio/mp4',
'aac' => 'audio/aac'
];
// Default to MP3 if extension not found
$contentType = $mimeTypes[$extension] ?? 'audio/mpeg';
// Set appropriate headers for audio streaming
header('Content-Type: ' . $contentType);
header('Content-Length: ' . filesize($fullPath));
header('Accept-Ranges: bytes');
// Stream the file content to the client
readfile($fullPath);
exit;
}
/**
* Serve a cover art image
*
* This function serves cover art images with appropriate headers.
* It includes security checks to prevent unauthorized file access.
*
* @return void Streams image file content or returns 404 error
*/
function serveCoverArt() {
global $basePath;
// Get the requested file path
$file = $_GET['file'] ?? '';
// Security check to prevent directory traversal
$fullPath = realpath($basePath . '/' . $file);
$realBasePath = realpath($basePath);
// Additional security checks
if (!$fullPath || !$realBasePath || strpos($fullPath, $realBasePath) !== 0) {
http_response_code(404);
echo 'File not found';
return;
}
// Ensure we're still within the base path after normalization
$normalizedPath = str_replace('\\', '/', substr($fullPath, strlen($realBasePath)));
if (preg_match('/\.\.(\/|\\\\|$)/', $normalizedPath)) {
http_response_code(404);
echo 'File not found';
return;
}
// Check if file exists
if (!file_exists($fullPath)) {
http_response_code(404);
echo 'File not found';
return;
}
// Determine content type based on file extension
$extension = strtolower(pathinfo($fullPath, PATHINFO_EXTENSION));
$mimeTypes = [
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'bmp' => 'image/bmp'
];
// Default to JPEG if extension not found
$contentType = $mimeTypes[$extension] ?? 'image/jpeg';
// Set appropriate headers for image serving
header('Content-Type: ' . $contentType);
header('Content-Length: ' . filesize($fullPath));
// Stream the file content to the client
readfile($fullPath);
exit;
}
/**
* Get all audio files from a directory recursively
*
* This function returns a JSON array of all audio files in the specified directory
* and its subdirectories.
*
* @return void Outputs JSON response with file listing
*/
function getDirectoryFiles() {
global $basePath;
// Get the requested path, default to empty string
$path = $_GET['path'] ?? '';
// Security check to prevent directory traversal
$fullPath = realpath($basePath . '/' . $path);
$realBasePath = realpath($basePath);
// Additional security checks
if (!$fullPath || !$realBasePath || strpos($fullPath, $realBasePath) !== 0) {
echo json_encode(['error' => 'Invalid path']);
return;
}
// Ensure we're still within the base path after normalization
$normalizedPath = str_replace('\\', '/', substr($fullPath, strlen($realBasePath)));
if (preg_match('/\.\.(\/|\\\\|$)/', $normalizedPath)) {
echo json_encode(['error' => 'Invalid path']);
return;
}
// Check if the path is actually a directory
if (!is_dir($fullPath)) {
echo json_encode(['error' => 'Directory not found']);
return;
}
// Initialize files array
$files = [];
// Define supported audio extensions
$audioExtensions = ['mp3', 'wav', 'ogg', 'flac', 'm4a', 'aac'];
// Create recursive iterator to get all files
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($fullPath, RecursiveDirectoryIterator::SKIP_DOTS)
);
// Process each file
foreach ($iterator as $file) {
if ($file->isFile()) {
$extension = strtolower($file->getExtension());
// Only include audio files
if (in_array($extension, $audioExtensions)) {
// Get relative path from base path
$relativePath = substr($file->getPathname(), strlen(realpath($basePath)) + 1);
$dirPath = dirname($relativePath);
// Find cover art for this file's directory
$coverArt = findCoverArtInDirectory(dirname($file->getPathname()));
if ($coverArt) {
// Convert to relative path
$coverArt = substr($coverArt, strlen(realpath($basePath)) + 1);
}
$files[] = [
'name' => $file->getFilename(),
'path' => $relativePath,
'extension' => $extension,
'coverArt' => $coverArt
];
}
}
}
// Sort files alphabetically by path
usort($files, function($a, $b) {
return strcmp($a['path'], $b['path']);
});
// Return JSON response with file list
echo json_encode(['files' => $files]);
}
/**
* Load and parse a playlist file
*
* This function loads and parses playlist files (M3U, M3U8, PLS) and returns
* a JSON array of the contained audio files.
*
* @return void Outputs JSON response with playlist contents
*/
function loadPlaylist() {
global $basePath;
// Get the requested playlist file path
$file = $_GET['path'] ?? '';
// Security check to prevent directory traversal
$fullPath = realpath($basePath . '/' . $file);
$realBasePath = realpath($basePath);
// Additional security checks
if (!$fullPath || !$realBasePath || strpos($fullPath, $realBasePath) !== 0) {
echo json_encode(['error' => 'Invalid path']);
return;
}
// Ensure we're still within the base path after normalization
$normalizedPath = str_replace('\\', '/', substr($fullPath, strlen($realBasePath)));
if (preg_match('/\.\.(\/|\\\\|$)/', $normalizedPath)) {
echo json_encode(['error' => 'Invalid path']);
return;
}
// Check if playlist file exists
if (!file_exists($fullPath)) {
echo json_encode(['error' => 'Playlist not found']);
return;
}
// Get file extension to determine parsing method
$extension = strtolower(pathinfo($fullPath, PATHINFO_EXTENSION));
// Initialize array to hold playlist entries
$files = [];
// Find cover art in the same directory as the playlist
$coverArt = findCoverArtInDirectory(dirname($fullPath));
if ($coverArt) {
// Convert to relative path
$coverArt = substr($coverArt, strlen(realpath($basePath)) + 1);
}
// Parse M3U/M3U8 playlist files
if ($extension === 'm3u' || $extension === 'm3u8') {
// Read entire file content
$content = file_get_contents($fullPath);
// Split content into lines
$lines = explode("\n", $content);
// Process each line
foreach ($lines as $line) {
// Trim whitespace and skip empty lines or comments
$line = trim($line);
if ($line && strpos($line, '#') !== 0) {
// Resolve relative paths based on playlist location
$filePath = dirname($file) . '/' . $line;
$files[] = [
'path' => $filePath,
'title' => basename($line),
'coverArt' => $coverArt
];
}
}
}
// Parse PLS playlist files
elseif ($extension === 'pls') {
// Read entire file content
$content = file_get_contents($fullPath);
// Split content into lines
$lines = explode("\n", $content);
// Process each line
foreach ($lines as $line) {
// Match PLS file entries (File1=path, File2=path, etc.)
if (preg_match('/^File\d+=(.+)$/', $line, $matches)) {
// Sanitize the file path to prevent directory traversal
$playlistEntry = $matches[1];
// Prevent directory traversal in playlist entries
if (strpos($playlistEntry, '..') !== false) {
continue; // Skip this entry
}
// Resolve relative paths based on playlist location
$filePath = dirname($file) . '/' . $playlistEntry;
$files[] = [
'path' => $filePath,
'title' => basename($playlistEntry),
'coverArt' => $coverArt
];
}
}
}
// Unsupported playlist format
else {
echo json_encode(['error' => 'Unsupported playlist format']);
return;
}
// Return JSON response with playlist contents
echo json_encode(['files' => $files]);
}
/**
* Check if a file is a cover art file
*
* This function determines if a file is likely to be a cover art image
* by checking if its name (without extension) contains common cover art keywords.
*
* @param string $filename The name of the file to check
* @return bool True if the file is identified as cover art, false otherwise
*
* The function performs a case-insensitive check against common cover art
* naming conventions like 'cover', 'folder', 'album', 'front', 'artwork'.
*
* Example:
* - isCoverArt('Cover.jpg') returns true
* - isCoverArt('folder.png') returns true
* - isCoverArt('song.mp3') returns false
*/
function isCoverArt($filename) {
$filename = strtolower($filename);
$coverNames = ['cover', 'folder', 'album', 'front', 'artwork'];
$extension = pathinfo($filename, PATHINFO_EXTENSION);
// Remove extension for name checking
$nameWithoutExt = pathinfo($filename, PATHINFO_FILENAME);
// Check if filename matches common cover art names
foreach ($coverNames as $coverName) {
if (strpos($nameWithoutExt, $coverName) !== false) {
return true;
}
}
return false;
}
/**
* Find cover art in a directory
*
* This function searches for cover art images in a directory using a prioritized approach:
* 1. First looks for images with common cover art names (cover, folder, album, etc.)
* 2. If none found, looks for any image file as a fallback
* 3. If still none found, checks first-level subdirectories
*
* @param string $directoryPath The absolute path to the directory to search
* @return string|null The absolute path to the found cover art, or null if none found
*
* The search prioritizes files with specific names over generic image files,
* and follows a hierarchy of common cover art naming conventions.
*/
function findCoverArtInDirectory($directoryPath) {
$coverNames = ['cover', 'folder', 'album', 'front', 'artwork'];
$imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
// Check if directory exists
if (!is_dir($directoryPath)) {
return null;
}
// Get directory contents
$items = scandir($directoryPath);
// Arrays to store potential cover art files
$namedCoverArts = [];
$anyImageFiles = [];
// Look for cover art files in the main directory
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$itemPath = $directoryPath . '/' . $item;
if (is_file($itemPath)) {
$extension = strtolower(pathinfo($item, PATHINFO_EXTENSION));
// Check if it's an image file
if (in_array($extension, $imageExtensions)) {
// Check if it matches cover art naming
if (isCoverArt($item)) {
$namedCoverArts[] = $itemPath;
} else {
// Store any image file as fallback
$anyImageFiles[] = $itemPath;
}
}
}
}
// Return named cover art first (prioritized by common names)
if (!empty($namedCoverArts)) {
// Sort by priority of cover art names
usort($namedCoverArts, function($a, $b) use ($coverNames) {
$nameA = strtolower(pathinfo($a, PATHINFO_FILENAME));
$nameB = strtolower(pathinfo($b, PATHINFO_FILENAME));
foreach ($coverNames as $priority => $coverName) {
if (strpos($nameA, $coverName) !== false && strpos($nameB, $coverName) === false) {
return -1;
}
if (strpos($nameB, $coverName) !== false && strpos($nameA, $coverName) === false) {
return 1;
}
}
return 0;
});
return $namedCoverArts[0];
}
// If no specific cover art found, return first image file found
if (!empty($anyImageFiles)) {
return $anyImageFiles[0];
}
// If no cover art found in main directory, check first-level subdirectories
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$itemPath = $directoryPath . '/' . $item;
if (is_dir($itemPath)) {
// Recursively check subdirectory for cover art
$subdirCoverArt = findCoverArtInSubdirectory($itemPath, $coverNames, $imageExtensions);
if ($subdirCoverArt !== null) {
return $subdirCoverArt;
}
}
}
return null;
}
/**
* Find cover art in a subdirectory (first level only)
*
* This function searches for cover art in a subdirectory using the same
* prioritization logic as findCoverArtInDirectory, but only checks one
* level deep (the specified subdirectory).
*
* @param string $directoryPath The absolute path to the subdirectory to search
* @param array $coverNames List of common cover art naming conventions
* @param array $imageExtensions List of supported image file extensions
* @return string|null The absolute path to the found cover art, or null if none found
*
* This is a helper function used by findCoverArtInDirectory to search
* within subdirectories when no cover art is found in the main directory.
*/
function findCoverArtInSubdirectory($directoryPath, $coverNames, $imageExtensions) {
// Check if directory exists
if (!is_dir($directoryPath)) {
return null;
}
// Get directory contents
$items = scandir($directoryPath);
// Arrays to store potential cover art files
$namedCoverArts = [];
$anyImageFiles = [];
// Look for cover art files
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$itemPath = $directoryPath . '/' . $item;
if (is_file($itemPath)) {
$extension = strtolower(pathinfo($item, PATHINFO_EXTENSION));
// Check if it's an image file
if (in_array($extension, $imageExtensions)) {
// Check if it matches cover art naming
if (isCoverArt($item)) {
$namedCoverArts[] = $itemPath;
} else {
// Store any image file as fallback
$anyImageFiles[] = $itemPath;
}
}
}
}
// Return named cover art first (prioritized by common names)
if (!empty($namedCoverArts)) {
// Sort by priority of cover art names
usort($namedCoverArts, function($a, $b) use ($coverNames) {
$nameA = strtolower(pathinfo($a, PATHINFO_FILENAME));
$nameB = strtolower(pathinfo($b, PATHINFO_FILENAME));
foreach ($coverNames as $priority => $coverName) {
if (strpos($nameA, $coverName) !== false && strpos($nameB, $coverName) === false) {
return -1;
}
if (strpos($nameB, $coverName) !== false && strpos($nameA, $coverName) === false) {
return 1;
}
}
return 0;
});
return $namedCoverArts[0];
}
// If no specific cover art found, return first image file found
if (!empty($anyImageFiles)) {
return $anyImageFiles[0];
}
return null;
}
?>