-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1120 lines (985 loc) · 37.2 KB
/
script.js
File metadata and controls
1120 lines (985 loc) · 37.2 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
/**
* MelodyHub - Web-based Audio Player
*
* A responsive web-based audio player that allows browsing local directories,
* managing playlists, and playing audio files with cover art display.
*
* 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/>.
*/
/**
* MelodyHub Audio Player
*
* Main JavaScript application for the audio player.
* Handles UI interactions, playlist management, and audio playback.
*
* Features:
* - Directory browsing with breadcrumb navigation
* - Playlist management with drag-and-drop reordering
* - Audio playback controls (play, pause, next, previous)
* - Progress bar with seeking
* - Volume control
* - Cover art display
* - Playlist import/export
*/
// === LOGGING FUNCTIONS ===
/**
* Log debug messages to console
* @param {...any} args - Arguments to log
*/
function logDebug(...args) {
console.debug('[MelodyHub Debug]', ...args);
}
/**
* Log info messages to console
* @param {...any} args - Arguments to log
*/
function logInfo(...args) {
console.info('[MelodyHub Info]', ...args);
}
/**
* Log warning messages to console
* @param {...any} args - Arguments to log
*/
function logWarning(...args) {
console.warn('[MelodyHub Warning]', ...args);
}
/**
* Log error messages to console
* @param {...any} args - Arguments to log
*/
function logError(...args) {
console.error('[MelodyHub Error]', ...args);
}
// === CONFIGURATION ===
/**
* Supported audio file extensions
* @type {string[]}
*/
const AUDIO_EXTENSIONS = ['mp3', 'wav', 'ogg', 'flac', 'm4a', 'aac'];
/**
* Supported playlist file extensions
* @type {string[]}
*/
const PLAYLIST_EXTENSIONS = ['m3u', 'm3u8', 'pls'];
// === APPLICATION STATE ===
/**
* Application state object that holds all the current state of the player
* @property {string} currentPath - Current directory path being browsed
* @property {Array} playlist - Array of playlist items
* @property {number} currentTrackIndex - Index of currently playing track
* @property {boolean} isPlaying - Whether audio is currently playing
* @property {number} volume - Current volume level (0.0 to 1.0)
*/
const state = {
currentPath: '',
playlist: [],
currentTrackIndex: -1,
isPlaying: false,
volume: 0.5
};
// Shortcut references to state properties for easier access
let currentPath = state.currentPath;
let playlist = state.playlist;
let currentTrackIndex = state.currentTrackIndex;
let isPlaying = state.isPlaying;
/**
* Load playlist and current path from localStorage on page load
* This function restores the user's previous session
*/
function loadFromStorage() {
logDebug('Loading data from localStorage');
const savedPlaylist = localStorage.getItem('audioPlayerPlaylist');
const savedTrackIndex = localStorage.getItem('audioPlayerCurrentTrackIndex');
const savedPath = localStorage.getItem('audioPlayerCurrentPath');
const savedVolume = localStorage.getItem('audioPlayerVolume');
if (savedPlaylist) {
try {
const parsedPlaylist = JSON.parse(savedPlaylist);
if (Array.isArray(parsedPlaylist)) {
state.playlist = parsedPlaylist;
playlist = state.playlist;
logInfo(`Loaded playlist with ${state.playlist.length} items from storage`);
} else {
logWarning('Saved playlist is not an array, initializing empty playlist');
state.playlist = [];
playlist = state.playlist;
}
} catch (e) {
logError('Failed to parse saved playlist:', e);
state.playlist = [];
playlist = state.playlist;
}
}
if (savedTrackIndex !== null) {
const index = parseInt(savedTrackIndex);
if (!isNaN(index) && index >= -1) {
state.currentTrackIndex = index;
currentTrackIndex = state.currentTrackIndex;
logDebug(`Current track index set to ${state.currentTrackIndex}`);
}
}
if (savedPath !== null) {
state.currentPath = savedPath;
currentPath = state.currentPath;
logDebug(`Current path set to ${state.currentPath}`);
}
if (savedVolume !== null) {
const volume = parseFloat(savedVolume);
if (!isNaN(volume) && volume >= 0 && volume <= 1) {
state.volume = volume;
logDebug(`Volume set to ${state.volume}`);
}
}
}
// === DOM ELEMENTS ===
/** @type {HTMLElement} Breadcrumb navigation element */
let breadcrumbEl;
/** @type {HTMLElement} File list container */
let fileListEl;
/** @type {HTMLElement} Playlist items container */
let playlistItemsEl;
/** @type {HTMLAudioElement} Audio player element */
let audioPlayer;
/** @type {HTMLButtonElement} Play button */
let playBtn;
/** @type {HTMLButtonElement} Pause button */
let pauseBtn;
/** @type {HTMLButtonElement} Previous track button */
let prevBtn;
/** @type {HTMLButtonElement} Next track button */
let nextBtn;
/** @type {HTMLElement} Progress bar element */
let progressBar;
/** @type {HTMLElement} Progress container element */
let progressContainer;
/** @type {HTMLElement} Current time display */
let currentTimeEl;
/** @type {HTMLElement} Total time display */
let totalTimeEl;
/** @type {HTMLInputElement} Volume slider */
let volumeSlider;
/** @type {HTMLButtonElement} Import playlist button */
let importBtn;
/** @type {HTMLButtonElement} Export playlist button */
let exportBtn;
/** @type {HTMLButtonElement} Clear playlist button */
let clearBtn;
/** @type {HTMLElement} Notification element */
let notificationEl;
// === INITIALIZATION ===
/**
* Initialize the application when the DOM is loaded
* This is the main entry point of the application
*/
document.addEventListener('DOMContentLoaded', () => {
logInfo('Initializing MelodyHub Audio Player');
// Get DOM elements
breadcrumbEl = document.getElementById('breadcrumb');
fileListEl = document.getElementById('fileList');
playlistItemsEl = document.getElementById('playList');
audioPlayer = document.getElementById('audioPlayer');
playBtn = document.getElementById('playBtn');
pauseBtn = document.getElementById('pauseBtn');
prevBtn = document.getElementById('prevBtn');
nextBtn = document.getElementById('nextBtn');
progressBar = document.getElementById('progressBar');
progressContainer = document.getElementById('progressContainer');
currentTimeEl = document.getElementById('currentTime');
totalTimeEl = document.getElementById('totalTime');
volumeSlider = document.getElementById('volumeSlider');
importBtn = document.getElementById('importBtn');
exportBtn = document.getElementById('exportBtn');
clearBtn = document.getElementById('clearBtn');
notificationEl = document.getElementById('notification');
// Load data from localStorage
loadFromStorage();
// Set volume from state
volumeSlider.value = state.volume;
setVolume();
// Render playlist if it was loaded from storage
if (playlist.length > 0) {
logDebug(`Rendering playlist with ${playlist.length} items`);
renderPlaylist();
}
// Load directory based on saved path or default to root
logDebug(`Loading directory: ${currentPath || 'root'}`);
loadDirectory(currentPath);
setupEventListeners();
// Initialize now playing display
updateNowPlaying();
logInfo('MelodyHub Audio Player initialized successfully');
});
// === EVENT LISTENERS ===
/**
* Set up all event listeners for UI elements
* This function connects user interactions to application functionality
*/
function setupEventListeners() {
playBtn.addEventListener('click', playAudio);
pauseBtn.addEventListener('click', pauseAudio);
prevBtn.addEventListener('click', playPrevious);
nextBtn.addEventListener('click', playNext);
audioPlayer.addEventListener('timeupdate', updateProgress);
audioPlayer.addEventListener('ended', playNext);
progressContainer.addEventListener('click', setProgress);
volumeSlider.addEventListener('input', setVolume);
importBtn.addEventListener('click', importPlaylist);
exportBtn.addEventListener('click', exportPlaylist);
clearBtn.addEventListener('click', clearPlaylist);
// Add event listeners for clear playlist modal
const confirmClearBtn = document.getElementById('confirmClearBtn');
const cancelClearBtn = document.getElementById('cancelClearBtn');
if (confirmClearBtn) {
confirmClearBtn.addEventListener('click', confirmClearPlaylist);
}
if (cancelClearBtn) {
cancelClearBtn.addEventListener('click', cancelClearPlaylist);
}
// Add event listener for the new "Add All" button
const addAllBtn = document.getElementById('addAllBtn');
if (addAllBtn) {
addAllBtn.addEventListener('click', () => {
addDirectoryToPlaylist('.');
});
}
// Set initial volume
setVolume();
}
// === DIRECTORY BROWSING FUNCTIONS ===
/**
* Load and display directory contents
* @param {string} path - Directory path to load
*/
function loadDirectory(path) {
logDebug(`Loading directory: ${path}`);
currentPath = path;
updateBreadcrumb();
// Set aria-busy attribute to indicate loading
if (fileListEl) {
fileListEl.setAttribute('aria-busy', 'true');
}
// Fetch directory contents from API
fetch(`api.php?action=list&path=${encodeURIComponent(path)}`)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
if (data.error) {
logError('API error loading directory:', data.error);
showNotification('Error loading directory: ' + data.error, 'error');
return;
}
logDebug(`Loaded ${data.files.length} items from directory`);
renderFileList(data.files);
})
.catch(error => {
logError('Network error loading directory:', error);
showNotification('Error loading directory: ' + error.message, 'error');
})
.finally(() => {
// Remove aria-busy attribute when loading is complete
if (fileListEl) {
fileListEl.setAttribute('aria-busy', 'false');
}
});
}
/**
* Update breadcrumb navigation based on current path
* This creates a navigable path showing where the user is in the directory structure
*/
function updateBreadcrumb() {
logDebug(`Updating breadcrumb for path: ${currentPath}`);
// Split path into components and filter out empty parts
const paths = currentPath.split('/').filter(p => p);
// Start with home link
let breadcrumbHTML = '<li><a href="#" onclick="loadDirectory(\'\')">Home</a></li>';
// Build path for each component
let current = '';
paths.forEach((path, index) => {
current += (index > 0 ? '/' : '') + path;
// Escape single quotes in path for JavaScript onclick handler
const escapedPath = current.replace(/'/g, "\\'");
breadcrumbHTML += `<li><a href="#" onclick="loadDirectory('${escapedPath}')">${path}</a></li>`;
});
breadcrumbEl.innerHTML = '<ul>' + breadcrumbHTML + '</ul>';
// Save current path to localStorage
state.currentPath = currentPath;
saveToStorage();
}
/**
* Render file list in the directory browser
* @param {Array} files - Array of file objects to render
*/
function renderFileList(files) {
fileListEl.innerHTML = '';
files.forEach(file => {
const li = document.createElement('li');
li.role = "grid";
// Determine icon based on file type and cover art
let iconHTML = '';
if (file.coverArt) {
// Use cover art as icon
iconHTML = `<img src="api.php?action=cover&file=${encodeURIComponent(file.coverArt)}" alt="Cover" class="file-cover-icon">`;
} else {
// Determine icon class based on file type
const iconClass = file.type === 'directory' ? 'folderIcon' :
AUDIO_EXTENSIONS.includes(file.extension) ? 'audioIcon' :
PLAYLIST_EXTENSIONS.includes(file.extension) ? 'playlistIcon' : '';
// Determine icon character based on file type
const icon = file.type === 'directory' ? '📁' :
AUDIO_EXTENSIONS.includes(file.extension) ? '🎵' :
PLAYLIST_EXTENSIONS.includes(file.extension) ? '📝' : '📄';
iconHTML = `<span class="fileIcon ${iconClass}">${icon}</span>`;
}
// Generate HTML for file item
// Escape single quotes in file names for JavaScript onclick handlers
const escapedFileName = file.name.replace(/'/g, "\\'").replace(/"/g, '"');
const fullPath = currentPath ? currentPath + '/' + file.name : file.name;
const escapedFullPath = fullPath.replace(/'/g, "\\'").replace(/"/g, '"');
// Properly escape the path for use in onclick handlers
const jsSafePath = fullPath.replace(/'/g, "\\'").replace(/"/g, """);
// Security check: ensure filename doesn't contain directory traversal sequences
if (file.name.includes('..') || file.name.includes('\\')) {
console.warn('Skipping file with potentially unsafe name:', file.name);
return;
}
li.innerHTML = `
${iconHTML}
<span class="fileName" style="cursor: pointer;" ${file.type === 'directory' ? `onclick="loadDirectory('${escapedFullPath}')" ondblclick="addDirectoryToPlaylist('${jsSafePath}'); event.stopPropagation(); return false;"` : `onclick="handleFileClick('${escapedFileName}', '${file.extension}')" title="Add to playlist"`}>${file.name}</span>
`;
fileListEl.appendChild(li);
});
}
/**
* Handle file name click in the file list
* @param {string} filename - Name of the file
* @param {string} extension - File extension
*/
function handleFileClick(filename, extension) {
// If it's an audio file, add it to playlist
if (AUDIO_EXTENSIONS.includes(extension)) {
addToPlaylist(filename, extension);
}
// If it's a directory, navigate into it
else if (extension === '') { // Directories don't have extensions
const fullPath = currentPath ? currentPath + '/' + filename : filename;
const escapedFullPath = fullPath.replace(/'/g, "\\'");
loadDirectory(escapedFullPath);
}
// If it's a playlist file, add it to playlist
else if (PLAYLIST_EXTENSIONS.includes(extension)) {
addToPlaylist(filename, extension);
}
}
// === PLAYLIST MANAGEMENT FUNCTIONS ===
/**
* Add a file to the playlist
* @param {string} filename - Name of the file to add
* @param {string} extension - File extension
*/
function addToPlaylist(filename, extension) {
logDebug(`Adding file to playlist: ${filename} (${extension})`);
// Check if file is a playlist
if (PLAYLIST_EXTENSIONS.includes(extension)) {
logInfo(`Loading playlist file: ${filename}`);
// Load playlist content from API
fetch(`api.php?action=loadPlaylist&path=${encodeURIComponent(currentPath + '/' + filename)}`)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
if (data.error) {
logError('API error loading playlist:', data.error);
showNotification('Error loading playlist: ' + data.error, 'error');
return;
}
// Add each file in the playlist to our playlist
if (Array.isArray(data.files)) {
data.files.forEach(file => {
state.playlist.push({
title: file.title || file.path.split('/').pop(),
path: file.path,
coverArt: file.coverArt || null
});
});
playlist = state.playlist;
logInfo(`Added ${data.files.length} tracks from playlist`);
renderPlaylist();
showNotification(`Added ${data.files.length} tracks from playlist`);
} else {
logError('Invalid playlist data format');
showNotification('Error: Invalid playlist format', 'error');
}
})
.catch(error => {
logError('Network error loading playlist:', error);
showNotification('Error loading playlist: ' + error.message, 'error');
});
} else {
// Add single audio file to playlist
const fullPath = currentPath ? currentPath + '/' + filename : filename;
// Try to find cover art for this file's directory
fetch(`api.php?action=list&path=${encodeURIComponent(currentPath)}`)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
const coverArt = data.coverArt || null;
state.playlist.push({
title: filename,
path: fullPath,
coverArt: coverArt
});
playlist = state.playlist;
logDebug(`Added audio file to playlist: ${filename}`);
renderPlaylist();
showNotification('Added to playlist: ' + filename);
})
.catch(error => {
// Fallback if we can't get cover art
state.playlist.push({
title: filename,
path: fullPath,
coverArt: null
});
playlist = state.playlist;
logDebug(`Added audio file to playlist: ${filename}`);
renderPlaylist();
showNotification('Added to playlist: ' + filename);
});
}
}
/**
* Add all audio files from a directory to the playlist
* @param {string} dirname - Name of the directory to add
*/
function addDirectoryToPlaylist(dirname) {
// Handle special case for current directory
let fullPath;
if (dirname === '.') {
fullPath = currentPath || '.'; // Current directory
} else {
// dirname is already the full path from the API, no need to concatenate
fullPath = dirname;
}
// Load all audio files from directory recursively
fetch(`api.php?action=getDirectoryFiles&path=${encodeURIComponent(fullPath)}`)
.then(response => response.json())
.then(data => {
if (data.error) {
showNotification('Error: ' + data.error, 'error');
return;
}
// Add each file to our playlist
data.files.forEach(file => {
state.playlist.push({
title: file.name,
path: file.path,
coverArt: file.coverArt || null
});
});
playlist = state.playlist;
renderPlaylist();
showNotification(`Added ${data.files.length} tracks from directory`);
})
.catch(error => {
showNotification('Error loading directory: ' + error.message, 'error');
});
}
/**
* Save playlist and current path to localStorage
* This preserves the user's session between page reloads
*/
function saveToStorage() {
localStorage.setItem('audioPlayerPlaylist', JSON.stringify(state.playlist));
localStorage.setItem('audioPlayerCurrentTrackIndex', state.currentTrackIndex.toString());
localStorage.setItem('audioPlayerCurrentPath', state.currentPath);
localStorage.setItem('audioPlayerVolume', state.volume.toString());
}
/**
* Render the playlist in the UI
* This function updates the visual representation of the playlist
*/
function renderPlaylist() {
// Set aria-busy attribute to indicate loading
if (playlistItemsEl) {
playlistItemsEl.setAttribute('aria-busy', 'true');
}
// Clear the playlist container first
playlistItemsEl.innerHTML = '';
// Update playlist count in header
const playlistCountEl = document.getElementById('playlistCount');
if (playlistCountEl) {
playlistCountEl.textContent = playlist.length;
}
// If playlist is empty, show the empty message
if (playlist.length === 0) {
playlistItemsEl.innerHTML = '<p id="emptyPlaylistMessage">Your playlist is empty. Add some audio files!</p>';
} else {
// Create list item for each playlist entry
playlist.forEach((item, index) => {
const li = document.createElement('li');
li.className = 'playlistItem grid';
li.draggable = true;
li.dataset.index = index;
// Check if this is the currently playing track
const isCurrentTrack = index === currentTrackIndex;
const titleStyle = isCurrentTrack ? 'cursor: pointer; color: #ffeb3b; font-weight: bold;' : 'cursor: pointer;';
// Generate HTML for playlist item
li.innerHTML = `
<span class="itemNumber">${index + 1}.</span>
<span class="playlistTitle" style="${titleStyle}" onclick="playTrack(${index + 1})">${item.title}</span>
`;
// Add drag and drop event listeners
li.addEventListener('dragstart', handleDragStart);
li.addEventListener('dragover', handleDragOver);
li.addEventListener('drop', handleDrop);
li.addEventListener('dragend', handleDragEnd);
playlistItemsEl.appendChild(li);
});
}
updatePlayerControls();
updateNowPlaying(); // Update now playing display with cover art
// Save to localStorage
saveToStorage();
// Remove aria-busy attribute when loading is complete
if (playlistItemsEl) {
playlistItemsEl.setAttribute('aria-busy', 'false');
}
}
/**
* Clear the entire playlist
* This function asks for user confirmation before clearing
*/
function clearPlaylist() {
// Don't do anything if playlist is already empty
if (playlist.length === 0) return;
// Show confirmation modal
const modal = document.getElementById('clearPlaylistModal');
if (modal) {
modal.showModal();
}
}
/**
* Confirm clearing the playlist
* This function is called when the user confirms the clear action
*/
function confirmClearPlaylist() {
state.playlist = [];
playlist = state.playlist;
state.currentTrackIndex = -1;
currentTrackIndex = state.currentTrackIndex;
audioPlayer.src = '';
isPlaying = false;
renderPlaylist();
updatePlayPauseButtons();
showNotification('Playlist cleared');
// Close the modal
const modal = document.getElementById('clearPlaylistModal');
if (modal) {
modal.close();
}
}
/**
* Cancel clearing the playlist
* This function is called when the user cancels the clear action
*/
function cancelClearPlaylist() {
// Close the modal
const modal = document.getElementById('clearPlaylistModal');
if (modal) {
modal.close();
}
}
/**
* Import a playlist from a file
* This function allows users to load M3U, M3U8, or PLS playlist files
*/
function importPlaylist() {
// Create a file input element
const input = document.createElement('input');
input.type = 'file';
input.accept = '.m3u,.m3u8,.pls';
// Handle file selection
input.onchange = e => {
const file = e.target.files[0];
if (!file) return;
// Check file extension
const extension = file.name.split('.').pop().toLowerCase();
if (!PLAYLIST_EXTENSIONS.includes(extension)) {
showNotification('Please select a valid playlist file (M3U, M3U8, or PLS)', 'error');
return;
}
// Additional security check on file name
if (file.name.includes('..') || file.name.includes('\\')) {
showNotification('Invalid file name', 'error');
return;
}
// Read the file content
const reader = new FileReader();
reader.onload = function(e) {
try {
const content = e.target.result;
// Split into lines and filter out empty lines and comments
const lines = content.split('\n').filter(line => line.trim() !== '' && !line.startsWith('#'));
// Add each line as a playlist item
let trackCount = 0;
lines.forEach(line => {
if (line.trim()) {
// Security check: prevent directory traversal in imported playlist entries
const cleanLine = line.trim();
if (cleanLine.includes('..') || cleanLine.includes('\\')) {
console.warn('Skipping potentially unsafe playlist entry:', cleanLine);
return;
}
state.playlist.push({
title: cleanLine.split('/').pop(),
path: cleanLine
});
trackCount++;
}
});
playlist = state.playlist;
renderPlaylist();
showNotification(`Imported ${trackCount} tracks`);
} catch (error) {
showNotification('Error importing playlist: ' + error.message, 'error');
}
};
reader.onerror = function() {
showNotification('Error reading file', 'error');
};
reader.readAsText(file);
};
input.click();
}
/**
* Export the current playlist to a file
* This function creates and downloads an M3U playlist file
*/
function exportPlaylist() {
// Don't export empty playlist
if (playlist.length === 0) {
showNotification('Playlist is empty', 'error');
return;
}
// Create M3U format content
let content = '#EXTM3U\n';
playlist.forEach(item => {
content += `${item.path}\n`;
});
// Create a blob and download link
const blob = new Blob([content], { type: 'audio/x-mpegurl' });
const url = URL.createObjectURL(blob);
// Create temporary anchor element for download
const a = document.createElement('a');
a.href = url;
a.download = 'playlist.m3u';
document.body.appendChild(a);
a.click();
// Clean up temporary elements
setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, 100);
showNotification('Playlist exported');
}
// === DRAG AND DROP FUNCTIONS ===
/** @type {HTMLElement} Element being dragged */
let dragSrcEl = null;
/**
* Handle drag start event
* @param {DragEvent} e - Drag event
*/
function handleDragStart(e) {
dragSrcEl = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', this.innerHTML);
}
/**
* Handle drag over event
* @param {DragEvent} e - Drag event
*/
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault();
}
e.dataTransfer.dropEffect = 'move';
return false;
}
/**
* Handle drop event
* @param {DragEvent} e - Drag event
*/
function handleDrop(e) {
if (e.stopPropagation) {
e.stopPropagation();
}
// Only process if dropping on a different element
if (dragSrcEl !== this) {
const srcIndex = parseInt(dragSrcEl.dataset.index);
const destIndex = parseInt(this.dataset.index);
// Reorder playlist by removing and reinserting item
const item = state.playlist.splice(srcIndex, 1)[0];
state.playlist.splice(destIndex, 0, item);
playlist = state.playlist;
// Update current track index if needed
if (state.currentTrackIndex === srcIndex) {
state.currentTrackIndex = destIndex;
currentTrackIndex = state.currentTrackIndex;
} else if (srcIndex < state.currentTrackIndex && destIndex >= state.currentTrackIndex) {
state.currentTrackIndex--;
currentTrackIndex = state.currentTrackIndex;
} else if (srcIndex > state.currentTrackIndex && destIndex <= state.currentTrackIndex) {
state.currentTrackIndex++;
currentTrackIndex = state.currentTrackIndex;
}
renderPlaylist();
}
return false;
}
/**
* Handle drag end event
* This function cleans up after a drag operation
*/
function handleDragEnd() {
const items = document.querySelectorAll('.playlist-item');
items.forEach(item => {
item.classList.remove('dragging');
});
}
// === AUDIO PLAYER FUNCTIONS ===
/**
* Play the current track or first track if none playing
* This is the main function for starting audio playback
*/
function playAudio() {
// Don't play if playlist is empty
if (playlist.length === 0) {
showNotification('Playlist is empty', 'error');
return;
}
// Start at first track if no track is currently selected
if (currentTrackIndex === -1) {
currentTrackIndex = 0;
state.currentTrackIndex = currentTrackIndex;
}
// Get current track and set audio source
const track = playlist[currentTrackIndex];
audioPlayer.src = `api.php?action=play&file=${encodeURIComponent(track.path)}`;
audioPlayer.play()
.then(() => {
isPlaying = true;
state.isPlaying = isPlaying;
updatePlayPauseButtons();
updateNowPlaying(); // Update now playing display
showNotification('Now playing: ' + track.title);
// Save current state to localStorage
saveToStorage();
})
.catch(error => {
showNotification('Error playing audio: ' + error.message, 'error');
});
}
/**
* Pause audio playback
* This function pauses the currently playing audio
*/
function pauseAudio() {
audioPlayer.pause();
isPlaying = false;
state.isPlaying = isPlaying;
updatePlayPauseButtons();
}
/**
* Play the previous track in the playlist
* This function cycles to the previous track or wraps to the end
*
* The modulo operation ensures that when we're at the first track (index 0),
* we wrap around to the last track in the playlist.
*
* Example:
* - If currentTrackIndex is 0 and playlist has 5 items, next index will be 4
* - If currentTrackIndex is 3 and playlist has 5 items, next index will be 2
*/
function playPrevious() {
if (playlist.length === 0) return;
// Cycle to last track if at beginning
// The expression (a - 1 + length) % length handles negative results correctly
currentTrackIndex = (currentTrackIndex - 1 + playlist.length) % playlist.length;
state.currentTrackIndex = currentTrackIndex;
renderPlaylist(); // Update playlist highlighting
playAudio();
}
/**
* Play a specific track by index (1-based indexing)
* @param {number} oneBasedIndex - 1-based index of the track to play
*/
function playTrack(oneBasedIndex) {
// Convert 1-based index to 0-based index
const index = oneBasedIndex - 1;
if (playlist.length === 0 || index < 0 || index >= playlist.length) return;
currentTrackIndex = index;
state.currentTrackIndex = currentTrackIndex;
renderPlaylist(); // Update playlist highlighting
playAudio();
}
/**
* Play the next track in the playlist
* This function cycles to the next track or wraps to the beginning
*
* The modulo operation ensures that when we reach the end of the playlist,
* we wrap around to the first track (index 0).
*
* Example:
* - If currentTrackIndex is 4 and playlist has 5 items, next index will be 0
* - If currentTrackIndex is 2 and playlist has 5 items, next index will be 3
*/
function playNext() {
if (playlist.length === 0) return;
// Cycle to first track if at end
// The expression (a + 1) % length handles wrapping around to 0
currentTrackIndex = (currentTrackIndex + 1) % playlist.length;
state.currentTrackIndex = currentTrackIndex;
renderPlaylist(); // Update playlist highlighting
playAudio();
}
/**
* Update progress bar during playback
* This function updates the UI with current playback position
*/
function updateProgress() {
const { currentTime, duration } = audioPlayer;
// Don't update if duration is not available
if (isNaN(duration)) return;
// Calculate progress percentage
const progressPercent = (currentTime / duration) * 100;
progressBar.value = `${progressPercent}`;