-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfile-loading-manager.js
More file actions
1187 lines (964 loc) · 39.5 KB
/
file-loading-manager.js
File metadata and controls
1187 lines (964 loc) · 39.5 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
/* ============================================
Mobile-Optimized File Loading Manager v3.0
Key Optimizations:
- Progressive loading (show tracks immediately, load details later)
- IndexedDB persistent cache with compression
- Web Worker integration for heavy tasks
- Mobile-specific concurrency and memory limits
- Lazy metadata extraction on-demand
- Background processing with requestIdleCallback
- Optimized image handling for mobile
- Smart prefetching and prioritization
- Memory-efficient streaming
============================================ */
class EnhancedFileLoadingManager {
constructor(debugLog, options = {}) {
this.debugLog = debugLog;
// Detect mobile for optimizations
this.isMobile = this._detectMobile();
this.isLowMemory = this._detectLowMemory();
// Dependencies
this.metadataParser = null;
this.vttParser = null;
this.analysisParser = null;
this.customMetadataStore = null;
this.analyzer = null;
this.workerManager = null;
this.imageOptimizer = null;
// Mobile-optimized configuration
this.config = {
supportedAudioFormats: options.supportedAudioFormats || [
'mp3', 'wav', 'ogg', 'm4a', 'flac', 'aac', 'wma', 'opus', 'webm'
],
// Mobile: reduce concurrency, desktop: allow more
maxConcurrent: this.isMobile ? 2 : (options.maxConcurrent || 3),
retryAttempts: options.retryAttempts || 2,
retryDelay: options.retryDelay || 1000,
fuzzyMatchThreshold: options.fuzzyMatchThreshold || 0.8,
// Mobile: smaller chunks
chunkSize: this.isMobile ? 3 : (options.chunkSize || 5),
enableCaching: false, // Force disabled as per user request
maxCacheAge: options.maxCacheAge || 7 * 24 * 60 * 60 * 1000, // 7 days
// Progressive loading
progressiveMode: this.isMobile ? true : (options.progressiveMode || false),
// Background processing
useIdleCallback: this.isMobile ? true : (options.useIdleCallback !== false),
// Mobile memory limits
maxMemoryMB: this.isMobile ? 50 : 200,
// Lazy metadata extraction
lazyMetadata: this.isMobile ? true : (options.lazyMetadata || false)
};
// State management
this.state = {
isLoading: false,
isPaused: false,
currentOperation: null,
processedFiles: 0,
totalFiles: 0,
errors: [],
warnings: [],
memoryUsage: 0
};
// Callbacks
this.callbacks = {
onLoadStart: null,
onLoadProgress: null,
onLoadComplete: null,
onLoadError: null,
onFileProcessed: null,
onChunkComplete: null,
onProgressiveUpdate: null
};
// In-memory cache (small, for current session)
this.memoryCache = new Map();
// IndexedDB cache (persistent, larger)
this.dbCache = null;
this.initializeDB();
// Background task queue
this.backgroundQueue = [];
this.isProcessingBackground = false;
// Prefetch queue
this.prefetchQueue = [];
this.debugLog(`📱 Mobile-optimized loader: ${this.isMobile ? 'MOBILE' : 'DESKTOP'} mode`, 'info');
}
// ========== MOBILE DETECTION ==========
_detectMobile() {
const ua = navigator.userAgent.toLowerCase();
const isMobile = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(ua);
const isSmallScreen = window.innerWidth <= 768;
const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
return isMobile || (isSmallScreen && isTouchDevice);
}
_detectLowMemory() {
// Check if device has limited memory
if (navigator.deviceMemory) {
return navigator.deviceMemory < 4; // Less than 4GB
}
return this.isMobile; // Assume mobile is low memory
}
// ========== INDEXEDDB CACHE ==========
async initializeDB() {
try {
this.dbCache = await this._openDB('MusicPlayerCache', 1);
// Clean old entries on startup
await this._cleanExpiredCache();
this.debugLog('💾 IndexedDB cache initialized', 'success');
} catch (err) {
this.debugLog(`⚠️ IndexedDB unavailable: ${err.message}`, 'warning');
this.dbCache = null;
}
}
_openDB(name, version) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(name, version);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains('fileCache')) {
const store = db.createObjectStore('fileCache', { keyPath: 'id' });
store.createIndex('timestamp', 'timestamp', { unique: false });
store.createIndex('fileName', 'fileName', { unique: false });
}
};
});
}
async _getCachedData(cacheKey) {
// Caching disabled as per user request to ensure fresh metadata on every load
return null;
}
async _setCachedData(cacheKey, data, metadata = {}) {
// Caching disabled as per user request
return;
}
async _cleanExpiredCache() {
if (!this.dbCache) return;
try {
const tx = this.dbCache.transaction('fileCache', 'readwrite');
const store = tx.objectStore('fileCache');
const index = store.index('timestamp');
const cutoffTime = Date.now() - this.config.maxCacheAge;
const range = IDBKeyRange.upperBound(cutoffTime);
const request = index.openCursor(range);
let deletedCount = 0;
request.onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
cursor.delete();
deletedCount++;
cursor.continue();
}
};
await new Promise((resolve) => {
tx.oncomplete = () => {
if (deletedCount > 0) {
this.debugLog(`🗑️ Cleaned ${deletedCount} expired cache entries`, 'info');
}
resolve();
};
});
} catch (err) {
this.debugLog(`Cache cleanup error: ${err.message}`, 'error');
}
}
// ========== INITIALIZATION ==========
init(dependencies) {
this.metadataParser = dependencies.metadataParser;
this.vttParser = dependencies.vttParser;
this.analysisParser = dependencies.analysisParser;
this.customMetadataStore = dependencies.customMetadataStore;
this.analyzer = dependencies.analyzer;
this.workerManager = dependencies.workerManager || window.workerManager;
this.imageOptimizer = dependencies.imageOptimizer || window.imageOptimizer;
this.debugLog('✅ Mobile-Optimized File Loading Manager v3.0 initialized', 'success');
}
setCallbacks(callbacks) {
Object.assign(this.callbacks, callbacks);
}
// ========== MAIN LOADING METHODS ==========
async loadFromFolderHandle(handle) {
this.debugLog(`📂 Scanning folder: ${handle.name}...`, 'info');
const files = [];
try {
for await (const entry of handle.values()) {
if (entry.kind === 'file') {
const file = await entry.getFile();
files.push(file);
}
}
this.debugLog(`✅ 📁 Found ${files.length} files`, 'success');
return await this.loadFiles(files);
} catch (err) {
this.debugLog(`❌ Folder scan failed: ${err.message}`, 'error');
throw err;
}
}
async loadFiles(files) {
if (!files || files.length === 0) {
this.debugLog('No files provided', 'warning');
return { success: false, playlist: [], errors: [] };
}
if (this.state.isLoading) {
this.debugLog('⚠️ Loading already in progress', 'warning');
return { success: false, error: 'Loading already in progress' };
}
this.state.isLoading = true;
this.state.processedFiles = 0;
this.state.totalFiles = files.length;
this.state.errors = [];
this.state.warnings = [];
const startTime = Date.now();
this.debugLog(`=== ${this.isMobile ? '📱 MOBILE' : '💻 DESKTOP'} Loading: ${files.length} files ===`);
try {
this._notifyCallback('onLoadStart', files.length);
// Step 1: Quick categorization (no await)
const categorized = this._categorizeFiles(files);
this.debugLog(
`📂 Categorized: ${categorized.audio.length} audio, ` +
`${categorized.vtt.length} VTT, ${categorized.analysis.length} analysis`
);
// Step 2: Build file map (fast, no I/O)
const fileMap = this._buildFileMatchMap(categorized);
// Step 3: PROGRESSIVE MODE - Create minimal entries immediately
let playlist;
if (this.config.progressiveMode) {
playlist = await this._progressiveLoad(categorized, fileMap, startTime);
} else {
// Standard mode - load everything upfront
playlist = await this._standardLoad(categorized, fileMap);
}
const loadTime = Date.now() - startTime;
this.debugLog(
`✅ Loading complete in ${(loadTime / 1000).toFixed(2)}s: ` +
`${playlist.length} tracks | ${this.state.errors.length} errors`,
'success'
);
this._notifyCallback('onLoadComplete', playlist);
const stats = this._generateStats(categorized, playlist);
return {
success: true,
playlist: playlist,
stats: stats,
loadTime: loadTime,
errors: this.state.errors,
warnings: this.state.warnings
};
} catch (error) {
this.debugLog(`❌ Fatal loading error: ${error.message}`, 'error');
this._notifyCallback('onLoadError', error);
return {
success: false,
playlist: [],
error: error.message,
errors: this.state.errors
};
} finally {
this.state.isLoading = false;
}
}
// ========== PROGRESSIVE LOADING (MOBILE OPTIMIZATION) ==========
async _progressiveLoad(categorized, fileMap, startTime) {
this.debugLog('⚡ PROGRESSIVE MODE: Creating minimal entries', 'info');
// Phase 1: Create minimal playlist entries IMMEDIATELY (< 100ms)
const minimalPlaylist = categorized.audio.map((audioFile, index) => {
const baseName = this._getBaseName(audioFile.name);
const matches = this._findMatchingFiles(baseName, fileMap);
return {
audioURL: URL.createObjectURL(audioFile),
fileName: audioFile.name,
fileSize: audioFile.size,
vtt: matches.vtt || null,
metadata: {
title: baseName,
artist: 'Loading...',
album: 'Unknown Album',
image: null,
hasMetadata: false,
isLoading: true
},
duration: 0,
analysis: null,
hasDeepAnalysis: false,
loadedAt: Date.now(),
_needsProcessing: true,
_audioFile: audioFile,
file: audioFile, // Store File object for buffer manager
_matches: matches
};
});
const quickLoadTime = Date.now() - startTime;
this.debugLog(`⚡ Phase 1 complete in ${quickLoadTime}ms - Playlist ready!`, 'success');
// Notify UI immediately with minimal playlist
this._notifyCallback('onProgressiveUpdate', {
phase: 1,
playlist: minimalPlaylist,
message: 'Playlist ready - Loading details...'
});
// Phase 2: Load metadata in background (prioritized)
this._scheduleBackgroundProcessing(minimalPlaylist, categorized);
return minimalPlaylist;
}
async _scheduleBackgroundProcessing(playlist, categorized) {
// Priority 1: Current track + next 2 tracks (load immediately)
const priorityTracks = playlist.slice(0, 3);
// Priority 2: Rest of tracks (background)
const backgroundTracks = playlist.slice(3);
// Process priority tracks first
for (let i = 0; i < priorityTracks.length; i++) {
const track = priorityTracks[i];
await this._enrichTrackMetadata(track, i, playlist.length);
this._notifyCallback('onProgressiveUpdate', {
phase: 2,
priority: true,
trackIndex: i,
playlist: playlist
});
}
// Process remaining tracks in background
this._processBackgroundQueue(backgroundTracks, 3, playlist);
}
_processBackgroundQueue(tracks, offset, fullPlaylist) {
if (this.isProcessingBackground) return;
this.isProcessingBackground = true;
let currentIndex = 0;
const processNext = async () => {
if (currentIndex >= tracks.length) {
this.isProcessingBackground = false;
this.debugLog('✅ Background processing complete', 'success');
this._notifyCallback('onProgressiveUpdate', {
phase: 3,
complete: true,
playlist: fullPlaylist
});
return;
}
const track = tracks[currentIndex];
const globalIndex = offset + currentIndex;
try {
await this._enrichTrackMetadata(track, globalIndex, fullPlaylist.length);
this._notifyCallback('onProgressiveUpdate', {
phase: 2,
priority: false,
trackIndex: globalIndex,
playlist: fullPlaylist,
progress: Math.round(((currentIndex + 1) / tracks.length) * 100)
});
} catch (err) {
this.debugLog(`Background processing error: ${err.message}`, 'error');
}
currentIndex++;
// Use requestIdleCallback for non-blocking processing
if (this.config.useIdleCallback && 'requestIdleCallback' in window) {
requestIdleCallback(() => processNext(), { timeout: 2000 });
} else {
setTimeout(processNext, 50);
}
};
processNext();
}
async _enrichTrackMetadata(track, index, total) {
if (!track._needsProcessing) return;
const cacheKey = this._getCacheKey(track._audioFile);
// Check cache
const cached = await this._getCachedData(cacheKey);
if (cached) {
Object.assign(track, {
metadata: cached.metadata,
duration: cached.duration,
analysis: cached.analysis,
hasDeepAnalysis: cached.hasDeepAnalysis
});
delete track._needsProcessing;
delete track._audioFile;
delete track._matches;
return;
}
// Extract metadata
try {
const metadata = await this._extractMetadata(track._audioFile);
track.metadata = metadata;
// Get duration
const duration = await this._getAudioDuration(track._audioFile);
track.duration = duration;
// Parse analysis if available
if (track._matches.analysis) {
track.analysis = await this._parseAnalysisFile(
track._matches.analysis,
track.fileName
);
track.hasDeepAnalysis = !!track.analysis;
} else if (this.analyzer) {
track.analysis = this.analyzer.analysisCache.get(track.fileName);
}
// Cache the enriched data
await this._setCachedData(cacheKey, {
metadata: track.metadata,
duration: track.duration,
analysis: track.analysis,
hasDeepAnalysis: track.hasDeepAnalysis
}, {
fileName: track.fileName,
size: track.fileSize
});
delete track._needsProcessing;
delete track._audioFile;
delete track._matches;
} catch (err) {
this.debugLog(`Metadata extraction failed: ${track.fileName}`, 'error');
track.metadata.artist = 'Unknown Artist';
track.metadata.isLoading = false;
}
this._updateProgress(index + 1, total, track.fileName, !!cached);
}
// ========== STANDARD LOADING ==========
async _standardLoad(categorized, fileMap) {
const playlist = [];
const chunks = this._chunkArray(categorized.audio, this.config.chunkSize);
this.debugLog(`⚡ Processing ${categorized.audio.length} files in ${chunks.length} chunks`);
for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
const chunk = chunks[chunkIndex];
const chunkResults = await this._processConcurrent(
chunk,
async (audioFile, index) => {
const globalIndex = chunkIndex * this.config.chunkSize + index;
return await this._processAudioFileWithRetry(
audioFile,
fileMap,
globalIndex,
categorized.audio.length
);
},
this.config.maxConcurrent
);
for (const result of chunkResults) {
if (result.success) {
playlist.push(result.data);
}
}
this._notifyCallback('onChunkComplete', {
chunk: chunkIndex + 1,
total: chunks.length,
processed: (chunkIndex + 1) * this.config.chunkSize,
playlist: playlist
});
}
return this._postProcessPlaylist(playlist);
}
// ========== FILE CATEGORIZATION ==========
_categorizeFiles(files) {
const categorized = {
audio: [],
vtt: [],
analysis: [],
unknown: []
};
for (const file of files) {
const category = this._categorizeFile(file);
categorized[category].push(file);
if (category === 'unknown') {
this.state.warnings.push({
file: file.name,
message: 'Unknown file type'
});
}
}
return categorized;
}
_categorizeFile(file) {
const nameLower = file.name.toLowerCase();
const extension = nameLower.split('.').pop();
if (file.type.startsWith('audio/') ||
this.config.supportedAudioFormats.includes(extension)) {
return 'audio';
}
if (extension === 'vtt' || file.type === 'text/vtt') {
return 'vtt';
}
if (extension === 'txt' || file.type === 'text/plain') {
return 'analysis';
}
return 'unknown';
}
// ========== SMART FILE MATCHING ==========
_buildFileMatchMap(categorized) {
const map = {
byBaseName: new Map(),
vttFiles: categorized.vtt,
analysisFiles: categorized.analysis
};
const allFiles = [...categorized.vtt, ...categorized.analysis];
for (const file of allFiles) {
const baseName = this._getBaseName(file.name);
if (!map.byBaseName.has(baseName)) {
map.byBaseName.set(baseName, []);
}
map.byBaseName.get(baseName).push(file);
}
return map;
}
_getBaseName(filename) {
return filename
.split('.').slice(0, -1).join('.')
.toLowerCase()
.trim();
}
_findMatchingFiles(audioBaseName, fileMap) {
const matches = {
vtt: null,
analysis: null
};
// Try exact match first
const exactMatches = fileMap.byBaseName.get(audioBaseName) || [];
for (const file of exactMatches) {
const ext = file.name.toLowerCase().split('.').pop();
if (ext === 'vtt' && !matches.vtt) {
matches.vtt = file;
} else if (ext === 'txt' && !matches.analysis) {
matches.analysis = file;
}
}
// Fuzzy matching only if necessary
if (!matches.vtt) {
matches.vtt = this._fuzzyMatch(audioBaseName, fileMap.vttFiles);
}
if (!matches.analysis) {
matches.analysis = this._fuzzyMatch(audioBaseName, fileMap.analysisFiles);
}
return matches;
}
_fuzzyMatch(baseName, files) {
let bestMatch = null;
let bestScore = 0;
for (const file of files) {
const fileBaseName = this._getBaseName(file.name);
const score = this._calculateSimilarity(baseName, fileBaseName);
if (score > bestScore && score >= this.config.fuzzyMatchThreshold) {
bestScore = score;
bestMatch = file;
}
}
return bestMatch;
}
_calculateSimilarity(str1, str2) {
const longer = str1.length > str2.length ? str1 : str2;
const shorter = str1.length > str2.length ? str2 : str1;
if (longer.length === 0) return 1.0;
const editDistance = this._levenshteinDistance(longer, shorter);
return (longer.length - editDistance) / longer.length;
}
_levenshteinDistance(str1, str2) {
const matrix = [];
for (let i = 0; i <= str2.length; i++) {
matrix[i] = [i];
}
for (let j = 0; j <= str1.length; j++) {
matrix[0][j] = j;
}
for (let i = 1; i <= str2.length; i++) {
for (let j = 1; j <= str1.length; j++) {
if (str2.charAt(i - 1) === str1.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(
matrix[i - 1][j - 1] + 1,
matrix[i][j - 1] + 1,
matrix[i - 1][j] + 1
);
}
}
}
return matrix[str2.length][str1.length];
}
// ========== PARALLEL PROCESSING ==========
async _processConcurrent(items, processor, concurrency) {
const results = [];
const executing = [];
for (let i = 0; i < items.length; i++) {
const promise = processor(items[i], i).then(result => {
executing.splice(executing.indexOf(promise), 1);
return result;
});
results.push(promise);
executing.push(promise);
if (executing.length >= concurrency) {
await Promise.race(executing);
}
}
return await Promise.all(results);
}
_chunkArray(array, chunkSize) {
const chunks = [];
for (let i = 0; i < array.length; i += chunkSize) {
chunks.push(array.slice(i, i + chunkSize));
}
return chunks;
}
// ========== FILE PROCESSING ==========
async _processAudioFileWithRetry(audioFile, fileMap, index, total) {
let lastError = null;
for (let attempt = 0; attempt <= this.config.retryAttempts; attempt++) {
try {
if (attempt > 0) {
await this._delay(this.config.retryDelay * attempt);
}
const result = await this._processAudioFile(audioFile, fileMap, index, total);
return { success: true, data: result };
} catch (error) {
lastError = error;
}
}
this.state.errors.push({
file: audioFile.name,
error: lastError.message
});
return { success: false, error: lastError };
}
async _processAudioFile(audioFile, fileMap, index, total) {
const baseName = this._getBaseName(audioFile.name);
const cacheKey = this._getCacheKey(audioFile);
// Check cache
const cached = await this._getCachedData(cacheKey);
if (cached && !this.config.forceRefresh) {
this._updateProgress(index + 1, total, audioFile.name, true);
return {
...cached,
audioURL: URL.createObjectURL(audioFile),
loadedAt: Date.now()
};
}
// Find matching files
const matches = this._findMatchingFiles(baseName, fileMap);
// Parse analysis
let parsedAnalysis = null;
if (matches.analysis) {
parsedAnalysis = await this._parseAnalysisFile(matches.analysis, audioFile.name);
}
// Extract metadata
const metadata = await this._extractMetadata(audioFile);
// Get duration
const duration = await this._getAudioDuration(audioFile);
// Create blob URL
const audioURL = URL.createObjectURL(audioFile);
// Check cached analysis
const finalAnalysis = parsedAnalysis ||
(this.analyzer ? this.analyzer.analysisCache.get(audioFile.name) : null);
// Build entry
const entry = {
audioURL: audioURL,
fileName: audioFile.name,
fileSize: audioFile.size,
file: audioFile, // Store File object for buffer manager
vtt: matches.vtt || null,
metadata: metadata,
duration: duration,
analysis: finalAnalysis,
hasDeepAnalysis: !!parsedAnalysis,
loadedAt: Date.now()
};
// Cache for future
await this._setCachedData(cacheKey, {
fileName: entry.fileName,
fileSize: entry.fileSize,
vtt: entry.vtt,
metadata: entry.metadata,
duration: entry.duration,
analysis: entry.analysis,
hasDeepAnalysis: entry.hasDeepAnalysis
}, {
fileName: audioFile.name,
size: audioFile.size
});
this._updateProgress(index + 1, total, audioFile.name, false);
this._notifyCallback('onFileProcessed', entry);
return entry;
}
_getCacheKey(file) {
return `${file.name}_${file.size}_${file.lastModified || 0}`;
}
async _parseAnalysisFile(analysisFile, audioFileName) {
if (!this.analysisParser) return null;
try {
const analysisText = await analysisFile.text();
const parsed = this.analysisParser.parseAnalysisText(analysisText);
if (this.analysisParser.isValidAnalysis(parsed)) {
return parsed;
}
} catch (err) {
this.state.errors.push({
file: analysisFile.name,
error: `Analysis parse failed: ${err.message}`
});
}
return null;
}
async _extractMetadata(audioFile) {
if (!this.metadataParser) {
return this._createDefaultMetadata(audioFile);
}
let metadata = await this.metadataParser.extractMetadata(audioFile);
// Check custom metadata
if (this.customMetadataStore) {
const customMeta = this.customMetadataStore.get(audioFile.name, audioFile.size);
if (customMeta) {
metadata = {
...metadata,
...customMeta,
hasMetadata: true,
isCustom: true
};
}
}
// Optimize image if available
if (metadata.image && this.imageOptimizer) {
try {
metadata.optimizedImage = await this.imageOptimizer.optimizeImage(
metadata.image,
'thumbnail'
);
} catch (err) {
this.debugLog(`Image optimization failed for ${audioFile.name}`, 'warning');
}
}
return metadata;
}
_createDefaultMetadata(audioFile) {
return {
title: audioFile.name.split('.')[0],
artist: 'Unknown Artist',
album: 'Unknown Album',
image: null,
hasMetadata: false
};
}
async _getAudioDuration(audioFile) {
const tempAudio = new Audio();
const blobURL = URL.createObjectURL(audioFile);
tempAudio.src = blobURL;
return new Promise((resolve) => {
const timeout = setTimeout(() => {
resolve(0);
URL.revokeObjectURL(blobURL);
}, 3000); // Shorter timeout for mobile
tempAudio.addEventListener('loadedmetadata', () => {
clearTimeout(timeout);
const duration = tempAudio.duration;
URL.revokeObjectURL(blobURL);
resolve(duration || 0);
}, { once: true });
tempAudio.addEventListener('error', () => {
clearTimeout(timeout);
URL.revokeObjectURL(blobURL);
resolve(0);
}, { once: true });
});
}
// ========== POST-PROCESSING ==========
async _postProcessPlaylist(playlist) {
// Sort by file name
playlist.sort((a, b) => a.fileName.localeCompare(b.fileName));
// Remove duplicates
const seen = new Set();
const deduplicated = playlist.filter(track => {
const key = `${track.fileName}_${track.fileSize}`;
if (seen.has(key)) {
URL.revokeObjectURL(track.audioURL);
return false;
}
seen.add(key);
return true;
});
return deduplicated;
}
// ========== FOLDER LOADING ==========
async loadFromFolderHandle(folderHandle) {
this.debugLog('📂 Scanning folder...', 'info');
const files = [];
try {
// Check if folderHandle is actually a FileList (fallback for mobile)
if (folderHandle instanceof FileList || Array.isArray(folderHandle)) {
this.debugLog('📱 Using file list fallback for mobile folder loading', 'info');
return await this.loadFiles(Array.from(folderHandle));
}
// Standard File System Access API
for await (const entry of folderHandle.values()) {
if (entry.kind === 'file') {
try {
const file = await entry.getFile();
files.push(file);
} catch (err) {
this.debugLog(`⚠️ Couldn't access: ${entry.name}`, 'warning');
}
}
}
if (files.length === 0) {
throw new Error('No files found in folder');
}
this.debugLog(`📁 Found ${files.length} files`, 'success');
return await this.loadFiles(files);
} catch (error) {
this.debugLog(`Error scanning folder: ${error.message}`, 'error');
// If it failed and we're on mobile, try to trigger the fallback
if (this.isMobile) {
this.debugLog('🔄 Attempting mobile fallback...', 'warning');
return this.triggerMobileFolderFallback();
}
throw error;
}
}
triggerMobileFolderFallback() {
return new Promise((resolve) => {
let input = document.getElementById('mobile-folder-fallback');
if (!input) {