-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2144 lines (1854 loc) · 97.5 KB
/
script.js
File metadata and controls
2144 lines (1854 loc) · 97.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
// DUDU Archive - Main JavaScript
// Badge base URL
const BADGE_URL = 'https://dudux.lol/badges/';
// Media Proxy URL (hides R2 links)
const MEDIA_URL = window.location.origin;
// State
let filteredFiles = [];
let currentPage = 1;
const perPage = 30;
let currentFilter = 'all';
let searchQuery = '';
let currentYear = 'all';
let currentSort = 'date'; // 'date', 'name', 'size'
let currentMediaInfo = null;
let currentFileId = null;
let currentFileName = null;
let currentView = 'normal';
let listViewMode = localStorage.getItem('viewMode') || 'list'; // 'list' or 'grid'
let movieInfoCache = {};
let watchInfoCache = {};
let subtitlesCache = {};
let availableYears = [];
let searchSuggestions = [];
// Folder navigation state
let currentFolderId = null;
let folderPath = [];
// File types
const fileTypes = {
video: ['mp4', 'mkv', 'avi', 'mov', 'webm', 'flv', 'wmv', 'm4v', 'ts'],
audio: ['mp3', 'flac', 'wav', 'm4a', 'ogg', 'aac', 'wma', 'opus'],
archive: ['zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'iso'],
};
// ISO 639-1 language code to full name map
const langNames = {
'en': 'English', 'hi': 'Hindi', 'es': 'Spanish', 'fr': 'French', 'de': 'German',
'it': 'Italian', 'pt': 'Portuguese', 'ru': 'Russian', 'ja': 'Japanese', 'ko': 'Korean',
'zh': 'Chinese', 'ar': 'Arabic', 'tr': 'Turkish', 'pl': 'Polish', 'nl': 'Dutch',
'sv': 'Swedish', 'da': 'Danish', 'no': 'Norwegian', 'fi': 'Finnish', 'el': 'Greek',
'cs': 'Czech', 'ro': 'Romanian', 'hu': 'Hungarian', 'th': 'Thai', 'id': 'Indonesian',
'ms': 'Malay', 'vi': 'Vietnamese', 'uk': 'Ukrainian', 'bg': 'Bulgarian', 'hr': 'Croatian',
'sr': 'Serbian', 'sk': 'Slovak', 'sl': 'Slovenian', 'lt': 'Lithuanian', 'lv': 'Latvian',
'et': 'Estonian', 'he': 'Hebrew', 'fa': 'Persian', 'bn': 'Bengali', 'ta': 'Tamil',
'te': 'Telugu', 'ml': 'Malayalam', 'kn': 'Kannada', 'mr': 'Marathi', 'gu': 'Gujarati',
'pa': 'Punjabi', 'ur': 'Urdu', 'ne': 'Nepali', 'si': 'Sinhala', 'my': 'Burmese',
'km': 'Khmer', 'lo': 'Lao', 'ka': 'Georgian', 'am': 'Amharic', 'sw': 'Swahili',
'af': 'Afrikaans', 'sq': 'Albanian', 'eu': 'Basque', 'ca': 'Catalan', 'gl': 'Galician',
'is': 'Icelandic', 'mk': 'Macedonian', 'mt': 'Maltese', 'cy': 'Welsh', 'ga': 'Irish',
'la': 'Latin', 'und': 'Undefined'
};
// Resolve language code to full name
function getLangName(code) {
if (!code) return null;
const lower = code.toLowerCase().trim();
return langNames[lower] || code;
}
// ========== FILENAME PARSER ==========
// Parse scene-style filename into structured data
function parseFilename(filename) {
const ext = filename.split('.').pop().toLowerCase();
const nameWithoutExt = filename.replace(/\.[^.]+$/, '');
// Replace dots/underscores with spaces for parsing
let clean = nameWithoutExt.replace(/[\._]/g, ' ');
// Extract season/episode (S01E01, S01 E01, 1x01, etc.)
let season = null, episode = null, episodeTitle = null;
const seMatch = clean.match(/\bS(\d{1,2})\s*[-]?\s*E(\d{1,2})\b/i) ||
clean.match(/\bSeason\s*(\d{1,2})\s*Episode\s*(\d{1,2})\b/i) ||
clean.match(/\b(\d{1,2})x(\d{1,2})\b/);
if (seMatch) {
season = parseInt(seMatch[1]);
episode = parseInt(seMatch[2]);
// Extract episode title (text between S01E01 and quality)
const afterSE = clean.substring(clean.indexOf(seMatch[0]) + seMatch[0].length);
const qualityMatch = afterSE.match(/\b(2160p|1080p|720p|480p|4K|UHD|HD|WEB|HDTV|BluRay|BRRip|DVDRip|AMZN|NF|DSNP|ATV|HMAX|ATVP)/i);
if (qualityMatch) {
episodeTitle = afterSE.substring(0, afterSE.indexOf(qualityMatch[0])).trim();
} else {
episodeTitle = afterSE.trim();
}
if (episodeTitle) episodeTitle = episodeTitle.replace(/^\s*[-]\s*/, '').trim();
}
// Extract year
const yearMatch = clean.match(/\b(19\d{2}|20[0-9]{2})\b/);
const year = yearMatch ? parseInt(yearMatch[1]) : null;
// Extract resolution
const resMatch = clean.match(/\b(2160p|1080p|720p|480p|4K|UHD)\b/i);
const resolution = resMatch ? resMatch[1].toUpperCase() : null;
// Extract quality/source
const sourceMatch = clean.match(/\b(WEB[-]?DL|WEBRip|BluRay|BRRip|HDRip|DVDRip|HDTV|CAM|TS|HC|Remux)\b/i);
const source = sourceMatch ? sourceMatch[1] : null;
// Extract release group (usually at end after dash)
const groupMatch = nameWithoutExt.match(/[-]([A-Za-z0-9]+)$/);
const group = groupMatch ? groupMatch[1] : null;
// Extract codec
const codecMatch = clean.match(/\b(H\.?265|H\.?264|HEVC|x265|x264|AV1|VP9|XviD)\b/i);
const codec = codecMatch ? codecMatch[1].replace('.', '') : null;
// Extract title (everything before year or season)
let title = clean;
if (yearMatch) {
title = clean.substring(0, clean.indexOf(yearMatch[0])).trim();
} else if (seMatch) {
title = clean.substring(0, clean.indexOf(seMatch[0])).trim();
} else if (resMatch) {
title = clean.substring(0, clean.indexOf(resMatch[0])).trim();
}
// Clean up title
title = title.replace(/\s+/g, ' ').trim();
return {
title,
year,
season,
episode,
episodeTitle: episodeTitle || null,
resolution,
source,
codec,
group,
ext: ext.toUpperCase(),
original: filename
};
}
// Format parsed filename to clean display
function formatFilename(parsed) {
let formatted = parsed.title;
if (parsed.year) {
formatted += ` ${parsed.year}`;
}
if (parsed.season !== null && parsed.episode !== null) {
formatted += ` S${String(parsed.season).padStart(2, '0')}E${String(parsed.episode).padStart(2, '0')}`;
if (parsed.episodeTitle) {
formatted += ` ${parsed.episodeTitle}`;
}
}
if (parsed.resolution) {
formatted += ` ${parsed.resolution}`;
}
formatted += `.${parsed.ext.toLowerCase()}`;
return formatted;
}
// Get series ID for grouping (title + year for finding related episodes)
function getSeriesKey(parsed) {
return `${parsed.title.toLowerCase().replace(/[^a-z0-9]/g, '')}${parsed.year || ''}`;
}
// Find related files (same series, other resolutions/episodes)
function findRelatedFiles(filename, allFiles) {
const parsed = parseFilename(filename);
const seriesKey = getSeriesKey(parsed);
const related = {
otherResolutions: [],
otherEpisodes: [],
current: parsed
};
for (const file of allFiles) {
if (file.name === filename) continue;
const fileParsed = parseFilename(file.name);
const fileSeriesKey = getSeriesKey(fileParsed);
// Check if same series
if (fileSeriesKey === seriesKey) {
// Same episode, different resolution
if (parsed.season === fileParsed.season &&
parsed.episode === fileParsed.episode &&
parsed.resolution !== fileParsed.resolution) {
related.otherResolutions.push({
...file,
parsed: fileParsed
});
}
// Different episode
else if (parsed.season !== fileParsed.season ||
parsed.episode !== fileParsed.episode) {
related.otherEpisodes.push({
...file,
parsed: fileParsed
});
}
}
// For movies (no season/episode), check same title different resolution
else if (!parsed.season && !fileParsed.season) {
const titleMatch = parsed.title.toLowerCase().replace(/[^a-z0-9]/g, '') ===
fileParsed.title.toLowerCase().replace(/[^a-z0-9]/g, '');
if (titleMatch && parsed.resolution !== fileParsed.resolution) {
related.otherResolutions.push({
...file,
parsed: fileParsed
});
}
}
}
// Sort episodes by season then episode
related.otherEpisodes.sort((a, b) => {
if (a.parsed.season !== b.parsed.season) return (a.parsed.season || 0) - (b.parsed.season || 0);
return (a.parsed.episode || 0) - (b.parsed.episode || 0);
});
// Sort resolutions by quality (4K > 1080p > 720p > 480p)
const resOrder = { '2160P': 4, '4K': 4, 'UHD': 4, '1080P': 3, '720P': 2, '480P': 1 };
related.otherResolutions.sort((a, b) =>
(resOrder[b.parsed.resolution] || 0) - (resOrder[a.parsed.resolution] || 0)
);
return related;
}
// Utility functions
const getFileType = fn => {
const ext = fn.split('.').pop().toLowerCase();
for (const [t, exts] of Object.entries(fileTypes)) if (exts.includes(ext)) return t;
return 'other';
};
const getExt = fn => fn.split('.').pop().toUpperCase().slice(0, 4);
const formatBytes = b => {
if (!b) return '0 B';
const k = 1024, s = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(b) / Math.log(k));
return (b / Math.pow(k, i)).toFixed(i > 1 ? 1 : 0) + ' ' + s[i];
};
const esc = str => { const d = document.createElement('div'); d.textContent = str; return d.innerHTML; };
// Extract year from filename
function extractYear(filename) {
const match = filename.match(/\b(19\d{2}|20[0-9]{2})\b/);
return match ? match[1] : null;
}
// Initialize with files from PHP
function initFiles(files) {
// Add year and isFolder to each file
window.allFiles = files.map(f => ({
...f,
year: extractYear(f.name),
isFolder: f.isFolder || f.mimeType === 'application/vnd.google-apps.folder' || false
}));
// Extract unique years for filter
const years = new Set();
window.allFiles.forEach(f => { if (f.year) years.add(f.year); });
availableYears = Array.from(years).sort((a, b) => b - a);
// Populate year dropdown
const yearSelect = document.getElementById('yearFilter');
if (yearSelect) {
yearSelect.innerHTML = '<option value="all">All Years</option>' +
availableYears.map(y => `<option value="${y}">${y}</option>`).join('');
}
// Generate search suggestions (2 random unique movie titles)
generateSearchSuggestions();
// Apply saved view mode
applyViewMode();
// Update breadcrumbs
renderBreadcrumbs();
filteredFiles = window.allFiles;
document.getElementById('totalCount').textContent = files.length;
const countEl = document.getElementById('filteredCount');
if (countEl) countEl.textContent = filteredFiles.length;
renderFiles();
renderPagination();
}
// Generate 2 random movie/series titles for search suggestions
function generateSearchSuggestions() {
const uniqueTitles = new Set();
const videoFiles = window.allFiles.filter(f => fileTypes.video.includes(f.name.split('.').pop().toLowerCase()));
// Get unique titles
for (const file of videoFiles) {
const parsed = parseFilename(file.name);
if (parsed.title && parsed.title.length > 2) {
uniqueTitles.add(parsed.title);
}
}
// Convert to array and shuffle
const titlesArray = Array.from(uniqueTitles);
const shuffled = titlesArray.sort(() => Math.random() - 0.5);
// Take 2 random titles
searchSuggestions = shuffled.slice(0, 2);
// Render suggestions
renderSearchSuggestions();
}
// Render search suggestions below search box
function renderSearchSuggestions() {
const container = document.getElementById('searchSuggestions');
if (!container || searchSuggestions.length === 0) return;
container.innerHTML = `
<span class="suggest-label">Try:</span>
${searchSuggestions.map(s => `<button class="suggest-tag" onclick="applySuggestion('${esc(s).replace(/'/g, "\\'")}')">${esc(s)}</button>`).join('')}
<button class="suggest-refresh" onclick="generateSearchSuggestions()" title="New suggestions">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M23 4v6h-6"/><path d="M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
</button>
`;
}
// Apply a search suggestion
function applySuggestion(title) {
const searchInput = document.getElementById('searchInput');
if (searchInput) {
searchInput.value = title;
handleSearch();
}
}
// Toggle between list and grid view
function toggleViewMode() {
listViewMode = listViewMode === 'list' ? 'grid' : 'list';
localStorage.setItem('viewMode', listViewMode);
applyViewMode();
renderFiles();
}
// Apply the current view mode to UI
function applyViewMode() {
const fileList = document.getElementById('fileList');
const listBtn = document.getElementById('viewListBtn');
const gridBtn = document.getElementById('viewGridBtn');
if (fileList) {
fileList.classList.toggle('grid-view', listViewMode === 'grid');
fileList.classList.toggle('list-view', listViewMode === 'list');
}
if (listBtn) listBtn.classList.toggle('active', listViewMode === 'list');
if (gridBtn) gridBtn.classList.toggle('active', listViewMode === 'grid');
}
// Set specific view mode
function setViewMode(mode) {
listViewMode = mode;
localStorage.setItem('viewMode', listViewMode);
applyViewMode();
renderFiles();
}
// Filter and search
function handleSearch() {
searchQuery = document.getElementById('searchInput').value.toLowerCase();
updateClearButton();
applyFilters();
}
// Clear search
function clearSearch() {
const searchInput = document.getElementById('searchInput');
if (searchInput) {
searchInput.value = '';
searchQuery = '';
updateClearButton();
applyFilters();
searchInput.focus();
}
}
// Show/hide clear button based on input
function updateClearButton() {
const clearBtn = document.getElementById('searchClear');
const searchInput = document.getElementById('searchInput');
if (clearBtn && searchInput) {
clearBtn.classList.toggle('visible', searchInput.value.length > 0);
}
}
function setFilter(f) {
currentFilter = f;
document.querySelectorAll('.filter-btn, .chip[data-filter], .f-btn[data-filter], .filter-group button[data-filter]').forEach(b => b.classList.toggle('active', b.dataset.filter === f));
applyFilters();
}
function setYear(y) {
currentYear = y;
applyFilters();
}
function setSort(s) {
currentSort = s;
document.querySelectorAll('.sort-btn, .pill[data-sort], .s-btn[data-sort], .sort-group button[data-sort]').forEach(b => b.classList.toggle('active', b.dataset.sort === s));
applyFilters();
}
// Smart search - handles queries like "school spirits s03e03", "avatar 2009 1080p", etc.
function smartSearch(filename, query) {
if (!query) return true;
const normalizedName = filename.toLowerCase().replace(/[\._-]/g, ' ').replace(/\s+/g, ' ');
const normalizedQuery = query.toLowerCase().replace(/[\._-]/g, ' ').replace(/\s+/g, ' ').trim();
// Parse the search query
const queryParts = normalizedQuery.split(' ').filter(p => p.length > 0);
// Check if ALL parts of the query are found in the filename
let allPartsFound = true;
for (const part of queryParts) {
// Allow partial matching for parts longer than 2 chars
if (part.length > 2) {
if (!normalizedName.includes(part)) {
allPartsFound = false;
break;
}
} else {
// For short parts (like "s3" or "e5"), require word boundary match
const regex = new RegExp(`\\b${part}\\b|\\b${part}|${part}\\b`, 'i');
if (!regex.test(normalizedName)) {
allPartsFound = false;
break;
}
}
}
if (allPartsFound) return true;
// Also try matching against parsed filename
const parsed = parseFilename(filename);
const searchableText = [
parsed.title,
parsed.year,
parsed.season ? `s${parsed.season}` : '',
parsed.season ? `s${String(parsed.season).padStart(2, '0')}` : '',
parsed.episode ? `e${parsed.episode}` : '',
parsed.episode ? `e${String(parsed.episode).padStart(2, '0')}` : '',
parsed.episodeTitle,
parsed.resolution,
parsed.source,
parsed.codec,
parsed.group
].filter(Boolean).join(' ').toLowerCase();
for (const part of queryParts) {
if (!searchableText.includes(part)) return false;
}
return true;
}
function applyFilters() {
filteredFiles = window.allFiles.filter(f => {
// Folder filter
if (currentFilter === 'folder' && !f.isFolder) return false;
if (currentFilter !== 'all' && currentFilter !== 'folder') {
if (f.isFolder) return false; // Hide folders when filtering by specific type
const t = getFileType(f.name);
if (t !== currentFilter) return false;
}
// Year filter
if (currentYear !== 'all' && f.year !== currentYear) return false;
// Smart search
if (searchQuery && !smartSearch(f.name, searchQuery)) return false;
return true;
});
// Sort (folders always first)
const folderFirst = (a, b) => {
if (a.isFolder && !b.isFolder) return -1;
if (!a.isFolder && b.isFolder) return 1;
return 0;
};
if (currentSort === 'name') {
filteredFiles.sort((a, b) => {
const ff = folderFirst(a, b);
if (ff !== 0) return ff;
if (a.isFolder || b.isFolder) return a.name.localeCompare(b.name);
const pa = parseFilename(a.name);
const pb = parseFilename(b.name);
const titleCompare = pa.title.localeCompare(pb.title);
if (titleCompare !== 0) return titleCompare;
if (pa.season !== pb.season) return (pa.season || 0) - (pb.season || 0);
if (pa.episode !== pb.episode) return (pa.episode || 0) - (pb.episode || 0);
return 0;
});
} else if (currentSort === 'size') {
filteredFiles.sort((a, b) => {
const ff = folderFirst(a, b);
if (ff !== 0) return ff;
return b.size - a.size;
});
} else if (currentSort === 'year') {
filteredFiles.sort((a, b) => {
const ff = folderFirst(a, b);
if (ff !== 0) return ff;
return (b.year || '0') - (a.year || '0');
});
} else {
filteredFiles.sort((a, b) => {
const ff = folderFirst(a, b);
if (ff !== 0) return ff;
return b.time - a.time;
});
}
currentPage = 1;
renderFiles();
renderPagination();
// Update count
const countEl = document.getElementById('filteredCount');
if (countEl) countEl.textContent = filteredFiles.length;
}
// Render file list (supports list and grid views)
function renderFiles() {
const start = (currentPage - 1) * perPage;
const pf = filteredFiles.slice(start, start + perPage);
const fileList = document.getElementById('fileList');
if (!pf.length) {
fileList.innerHTML = `<div class="empty"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><polyline points="13 2 13 9 20 9"/></svg><h3>No files found</h3></div>`;
return;
}
// Ensure view mode class is applied
fileList.classList.toggle('grid-view', listViewMode === 'grid');
fileList.classList.toggle('list-view', listViewMode === 'list');
fileList.innerHTML = pf.map(f => {
// Render folder items
if (f.isFolder) {
const safeName = esc(f.name).replace(/'/g, "\\'");
if (listViewMode === 'grid') {
return `
<article class="file-card folder-card" onclick="openFolder('${f.id}','${safeName}')">
<div class="card-header"><div class="card-ext">FOLDER</div></div>
<div class="card-body">
<div class="card-title" title="${esc(f.name)}">${esc(f.name)}</div>
<div class="card-tags"><span class="card-tag">Folder</span></div>
</div>
<div class="card-footer">
<span class="card-size">Folder</span>
<div class="card-actions">
<button class="card-btn" title="Open">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"/></svg>
</button>
</div>
</div>
</article>`;
}
return `
<article class="file-item" onclick="openFolder('${f.id}','${safeName}')">
<div class="file-row">
<div class="file-icon folder">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
</svg>
</div>
<div class="file-content">
<div class="file-name">${esc(f.name)}</div>
<div class="file-info">
<span class="file-badge">Folder</span>
</div>
</div>
<div class="file-btns">
<button class="file-btn" title="Open">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"/></svg>
</button>
</div>
</div>
</article>`;
}
const ftype = getFileType(f.name);
const isVideo = ftype === 'video';
const showInfo = isVideo || ftype === 'audio';
const safeName = esc(f.name).replace(/'/g, "\\'");
// Parse and format filename for display
const parsed = parseFilename(f.name);
const displayName = formatFilename(parsed);
// Build tags from parsed data
let tags = [];
if (parsed.resolution) tags.push(`<span class="file-tag res">${parsed.resolution}</span>`);
if (parsed.source) tags.push(`<span class="file-tag source">${parsed.source}</span>`);
if (parsed.codec) tags.push(`<span class="file-tag codec">${parsed.codec}</span>`);
if (parsed.group) tags.push(`<span class="file-tag group">${parsed.group}</span>`);
// Grid view layout
if (listViewMode === 'grid') {
return `
<article class="file-card" onclick="openInfo('${f.id}','${safeName}',${f.size})">
<div class="card-header">
<div class="card-ext">${getExt(f.name)}</div>
${parsed.resolution ? `<div class="card-res">${parsed.resolution}</div>` : ''}
</div>
<div class="card-body">
<div class="card-title" title="${esc(f.name)}">${esc(f.name)}</div>
${parsed.season !== null ? `<div class="card-episode">S${String(parsed.season).padStart(2, '0')}E${String(parsed.episode).padStart(2, '0')}</div>` : ''}
${parsed.year ? `<div class="card-year">${parsed.year}</div>` : ''}
<div class="card-tags">
${parsed.source ? `<span class="card-tag">${parsed.source}</span>` : ''}
${parsed.codec ? `<span class="card-tag">${parsed.codec}</span>` : ''}
${parsed.group ? `<span class="card-tag group">${parsed.group}</span>` : ''}
</div>
</div>
<div class="card-footer">
<span class="card-size">${formatBytes(f.size)}</span>
<div class="card-actions">
${isVideo ? `<button class="card-btn" onclick="event.stopPropagation();togglePlay(event, '${f.id}', '${safeName}')" title="Play">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
</button>` : ''}
${showInfo ? `<button class="card-btn" onclick="event.stopPropagation();openInfo('${f.id}','${safeName}',${f.size})" title="Info">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>
</button>` : ''}
<a href="${MEDIA_URL}/d/${f.id}/${encodeURIComponent(f.name)}" class="card-btn" onclick="event.stopPropagation()" title="Download">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
</a>
</div>
</div>
${isVideo ? `<div class="play-dropdown card-dropdown" id="play-${f.id}">
<a href="#" onclick="event.stopPropagation();playInBrowser('${f.id}','${safeName}');return false;" class="play-browser-option">▶ Play in Browser</a>
<div class="divider"></div>
<div class="section-label">Desktop</div>
<a href="#" onclick="event.stopPropagation();playIn('vlc-desktop','${f.id}','${safeName}');return false;">VLC Desktop</a>
<a href="#" onclick="event.stopPropagation();playIn('potplayer','${f.id}','${safeName}');return false;">PotPlayer</a>
<a href="#" onclick="event.stopPropagation();playIn('iina','${f.id}','${safeName}');return false;">IINA (Mac)</a>
<div class="divider"></div>
<div class="section-label">Mobile</div>
<a href="#" onclick="event.stopPropagation();playIn('vlc-mobile','${f.id}','${safeName}');return false;">VLC Mobile</a>
<a href="#" onclick="event.stopPropagation();playIn('nplayer','${f.id}','${safeName}');return false;">nPlayer</a>
<a href="#" onclick="event.stopPropagation();playIn('mx-free','${f.id}','${safeName}');return false;">MX Player</a>
<div class="divider"></div>
<a href="#" onclick="event.stopPropagation();copyStreamLink('${f.id}');return false;" class="copy-link-option">Copy Stream Link</a>
</div>` : ''}
</article>`;
}
// List view layout (default) - Modern Design
return `
<article class="file-item" onclick="openInfo('${f.id}','${safeName}',${f.size})">
<div class="file-row">
<div class="file-icon ${ftype}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
${isVideo ? '<polygon points="5 3 19 12 5 21 5 3"/>' : '<path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><polyline points="13 2 13 9 20 9"/>'}
</svg>
</div>
<div class="file-content">
<div class="file-name" title="${esc(f.name)}">${esc(f.name)}</div>
<div class="file-info">
${parsed.resolution ? `<span class="file-badge res">${parsed.resolution}</span>` : ''}
${parsed.source ? `<span class="file-badge">${parsed.source}</span>` : ''}
${parsed.codec ? `<span class="file-badge">${parsed.codec}</span>` : ''}
<span class="file-size">${formatBytes(f.size)}</span>
</div>
</div>
<div class="file-btns">
${isVideo ? `<div class="play-wrapper">
<button class="file-btn play" onclick="event.stopPropagation();togglePlay(event, '${f.id}', '${safeName}')" title="Play">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
</button>
<div class="play-dropdown" id="play-${f.id}">
<a href="#" onclick="playInBrowser('${f.id}','${safeName}');return false;" class="play-browser-option">▶ Play in Browser</a>
<div class="divider"></div>
<div class="section-label">Desktop</div>
<a href="#" onclick="playIn('vlc-desktop','${f.id}','${safeName}');return false;">VLC Desktop</a>
<a href="#" onclick="playIn('potplayer','${f.id}','${safeName}');return false;">PotPlayer</a>
<a href="#" onclick="playIn('iina','${f.id}','${safeName}');return false;">IINA (Mac)</a>
<a href="#" onclick="playIn('mpv','${f.id}','${safeName}');return false;">mpv</a>
<div class="divider"></div>
<div class="section-label">Mobile</div>
<a href="#" onclick="playIn('vlc-mobile','${f.id}','${safeName}');return false;">VLC Mobile</a>
<a href="#" onclick="playIn('nplayer','${f.id}','${safeName}');return false;">nPlayer</a>
<a href="#" onclick="playIn('mx-free','${f.id}','${safeName}');return false;">MX Player</a>
<div class="divider"></div>
<a href="#" onclick="copyStreamLink('${f.id}');return false;" class="copy-link-option">Copy Stream Link</a>
</div>
</div>` : ''}
${showInfo ? `<button class="file-btn info" onclick="event.stopPropagation();openInfo('${f.id}','${safeName}',${f.size})" title="Info">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>
</button>` : ''}
<a href="${MEDIA_URL}/d/${f.id}/${encodeURIComponent(f.name)}" class="file-btn download" onclick="event.stopPropagation()" title="Download">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
</a>
</div>
</div>
</article>`;
}).join('');
}
// Pagination
function renderPagination() {
const total = Math.ceil(filteredFiles.length / perPage);
if (total <= 1) { document.getElementById('pagination').innerHTML = ''; return; }
let html = `<button class="page-btn" onclick="goToPage(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''}><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 18 9 12 15 6"/></svg></button>`;
let start = Math.max(1, currentPage - 2), end = Math.min(total, start + 4);
if (end - start < 4) start = Math.max(1, end - 4);
for (let i = start; i <= end; i++) html += `<button class="page-btn ${i === currentPage ? 'active' : ''}" onclick="goToPage(${i})">${i}</button>`;
html += `<button class="page-btn" onclick="goToPage(${currentPage + 1})" ${currentPage === total ? 'disabled' : ''}><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"/></svg></button>`;
document.getElementById('pagination').innerHTML = html;
}
function goToPage(p) {
const total = Math.ceil(filteredFiles.length / perPage);
if (p < 1 || p > total) return;
currentPage = p;
renderFiles();
renderPagination();
window.scrollTo({ top: 150, behavior: 'smooth' });
}
// Modal functions
let infoRetryCount = 0;
const MAX_RETRIES = 5;
async function openInfo(id, name, size, isRetry = false) {
currentFileId = id;
currentFileName = name;
currentView = 'normal';
if (!isRetry) {
infoRetryCount = 0;
document.getElementById('modal').classList.add('open');
document.body.style.overflow = 'hidden';
}
document.getElementById('modalContent').innerHTML = `<div class="loading"><div class="spinner"></div><p>Analyzing...</p></div>`;
try {
// Primary: Use server-side MediaInfo API (fast)
let result = null;
let filename = name;
let filesize = size;
try {
const res = await fetch('/api/mediainfo?id=' + id);
const data = await res.json();
if (data.success && data.mediainfo && data.mediainfo.media && data.mediainfo.media.track) {
result = data.mediainfo;
filename = data.filename || name;
filesize = data.filesize || size;
}
} catch (apiErr) {
console.warn('Server-side MediaInfo failed, falling back to client-side:', apiErr.message);
}
// Fallback: Use client-side WASM analysis
if (!result) {
const infoRes = await fetch('/api/info?id=' + id);
const infoData = await infoRes.json();
if (!infoData.success || !infoData.streamUrl) throw new Error('Failed to get stream URL');
const streamUrl = infoData.streamUrl;
filename = infoData.filename || name;
filesize = infoData.filesize || size;
const MediaInfoFactory = window.MediaInfoFactory || window.MediaInfo;
if (!MediaInfoFactory) throw new Error('MediaInfo library not loaded');
const MI = await MediaInfoFactory({ format: 'object' });
const getChunk = async (chunkSize, offset) => {
const response = await fetch(streamUrl, {
headers: { Range: `bytes=${offset}-${offset + chunkSize - 1}` }
});
return new Uint8Array(await response.arrayBuffer());
};
result = await MI.analyzeData(filesize, getChunk);
}
currentMediaInfo = convertMediaInfoResult(result, filename, filesize);
renderModal();
} catch (e) {
document.getElementById('modalContent').innerHTML = `
<div class="loading">
<p style="color:#f87171;margin-bottom:15px;">Analysis failed</p>
<p style="font-size:13px;color:#888;margin-bottom:15px;">${e.message}</p>
<button onclick="openInfo('${id}', '${name.replace(/'/g, "\\'")}', ${size})" style="padding:10px 24px;background:#222;border:1px solid #333;border-radius:6px;color:#fff;cursor:pointer;font-size:13px;">Try Again</button>
</div>`;
}
}
function convertMediaInfoResult(result, filename, fileSize) {
const data = { filename, filesize: fileSize, tracks: [] };
let tracks = [];
if (result && result.media && result.media.track) {
tracks = Array.isArray(result.media.track) ? result.media.track : [result.media.track];
}
if (!tracks.length) return data;
for (const track of tracks) {
const type = track['@type'] || 'Unknown';
const props = {};
for (const [key, value] of Object.entries(track)) {
if (key === '@type') continue;
if (value === undefined || value === null || value === '') continue;
if (key === 'extra' && typeof value === 'object') {
for (const [ek, ev] of Object.entries(value)) {
if (ev === undefined || ev === null || ev === '') continue;
const formattedKey = ek.replace(/_/g, ' ').replace(/([a-z])([A-Z])/g, '$1 $2');
props[formattedKey.charAt(0).toUpperCase() + formattedKey.slice(1)] = String(ev);
}
continue;
}
let formattedKey = key.replace(/_/g, ' ').replace(/([a-z])([A-Z])/g, '$1 $2');
formattedKey = formattedKey.charAt(0).toUpperCase() + formattedKey.slice(1);
let formattedValue = value;
if (Array.isArray(value)) {
formattedValue = value.join(', ');
} else if (typeof value === 'object') {
formattedValue = JSON.stringify(value);
} else {
formattedValue = String(value);
}
props[formattedKey] = formattedValue;
}
data.tracks.push({ type, properties: props });
}
return data;
}
function closeModal() {
document.getElementById('modal').classList.remove('open');
document.body.style.overflow = '';
}
// View switching
function setView(v) {
currentView = v;
document.querySelectorAll('.view-pill').forEach(b => b.classList.toggle('active', b.dataset.view === v));
document.querySelector('.normal-view')?.classList.toggle('hidden', v !== 'normal');
document.querySelector('.text-view')?.classList.toggle('active', v === 'text');
document.querySelector('.movie-view')?.classList.toggle('active', v === 'movie');
document.querySelector('.movie-view')?.classList.toggle('hidden', v !== 'movie');
document.querySelector('.related-view')?.classList.toggle('active', v === 'related');
document.querySelector('.related-view')?.classList.toggle('hidden', v !== 'related');
document.querySelector('.watch-view')?.classList.toggle('active', v === 'watch');
document.querySelector('.watch-view')?.classList.toggle('hidden', v !== 'watch');
document.querySelector('.subs-view')?.classList.toggle('active', v === 'subs');
document.querySelector('.subs-view')?.classList.toggle('hidden', v !== 'subs');
if (v === 'movie' && currentFileName) loadMovieInfo(currentFileName);
if (v === 'watch' && currentFileName) loadWatchInfo(currentFileName);
if (v === 'subs' && currentFileName) loadSubtitles(currentFileName);
}
// Movie info loading (TMDB only)
async function loadMovieInfo(filename) {
const movieView = document.querySelector('.movie-view');
if (!movieView) return;
if (movieInfoCache[filename]) {
renderMovieInfo(movieInfoCache[filename]);
return;
}
movieView.innerHTML = `<div class="movie-loading"><div class="spinner"></div><p style="margin-top: 16px; color: #666;">Loading...</p></div>`;
try {
const res = await fetch('/api/movie?filename=' + encodeURIComponent(filename));
const data = await res.json();
movieInfoCache[filename] = data;
renderMovieInfo(data);
} catch (err) {
movieView.innerHTML = `<div class="movie-not-found"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg><h3>Error loading movie info</h3><p>${err.message}</p></div>`;
}
}
function renderMovieInfo(data) {
const movieView = document.querySelector('.movie-view');
if (!movieView) return;
if (!data.success) {
movieView.innerHTML = `<div class="movie-not-found"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="12" r="10"/><path d="M8 15h8M9 9h.01M15 9h.01"/></svg><h3>Movie not found</h3><p>"${data.parsed?.title || 'Unknown'}"${data.parsed?.year ? ` (${data.parsed.year})` : ''}</p></div>`;
return;
}
const typeLabel = data.type === 'show' ? 'TV Series' : 'Movie';
const runtimeStr = data.runtime ? `${Math.floor(data.runtime / 60)}h ${data.runtime % 60}m` : '';
const ratingStr = data.rating ? `★ ${data.rating.toFixed(1)}` : '';
const votesStr = data.voteCount ? `(${data.voteCount.toLocaleString()})` : '';
// Format budget/revenue
const fmtMoney = (n) => n > 0 ? '$' + (n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n.toLocaleString()) : '';
// Hero section
let html = `<div class="movie-hero">
<div class="movie-poster">
${data.poster ? `<img src="${data.poster}" alt="${data.title}" loading="lazy">` : `<div class="movie-poster-placeholder">?</div>`}
</div>
<h2 class="movie-title">${data.title}</h2>
${data.originalTitle ? `<div class="movie-original-title">${data.originalTitle}</div>` : ''}
${data.tagline ? `<div class="movie-tagline">"${data.tagline}"</div>` : ''}
<div class="movie-meta">
${ratingStr ? `<span class="movie-tag rating">${ratingStr} ${votesStr}</span>` : ''}
${data.year ? `<span class="movie-tag">${data.year}</span>` : ''}
${runtimeStr ? `<span class="movie-tag">${runtimeStr}</span>` : ''}
${data.certification ? `<span class="movie-tag">${data.certification}</span>` : ''}
<span class="movie-tag rated">${typeLabel}</span>
${data.seasons ? `<span class="movie-tag">${data.seasons} Season${data.seasons > 1 ? 's' : ''}</span>` : ''}
</div>
${data.genres?.length ? `<div class="movie-genre">${data.genres.join(' • ')}</div>` : ''}
${data.overview ? `<div class="movie-plot">${data.overview}</div>` : ''}
${buildRatingsHtml(data)}
</div>`;
// Details grid
let detailItems = '';
if (data.directors?.length) detailItems += `<div class="movie-detail-item"><span class="movie-detail-label">Director</span><span class="movie-detail-value">${data.directors.join(', ')}</span></div>`;
if (data.writers?.length) detailItems += `<div class="movie-detail-item"><span class="movie-detail-label">Writer</span><span class="movie-detail-value">${data.writers.join(', ')}</span></div>`;
if (data.languages?.length) detailItems += `<div class="movie-detail-item"><span class="movie-detail-label">Language</span><span class="movie-detail-value">${data.languages.join(', ')}</span></div>`;
if (data.countries?.length) detailItems += `<div class="movie-detail-item"><span class="movie-detail-label">Country</span><span class="movie-detail-value">${data.countries.join(', ')}</span></div>`;
if (data.releaseDate) detailItems += `<div class="movie-detail-item"><span class="movie-detail-label">Released</span><span class="movie-detail-value">${data.releaseDate}</span></div>`;
if (data.status) detailItems += `<div class="movie-detail-item"><span class="movie-detail-label">Status</span><span class="movie-detail-value">${data.status}</span></div>`;
if (fmtMoney(data.budget)) detailItems += `<div class="movie-detail-item"><span class="movie-detail-label">Budget</span><span class="movie-detail-value">${fmtMoney(data.budget)}</span></div>`;
if (fmtMoney(data.revenue)) detailItems += `<div class="movie-detail-item"><span class="movie-detail-label">Revenue</span><span class="movie-detail-value">${fmtMoney(data.revenue)}</span></div>`;
if (data.companies?.length) detailItems += `<div class="movie-detail-item"><span class="movie-detail-label">Production</span><span class="movie-detail-value">${data.companies.join(', ')}</span></div>`;
if (detailItems) html += `<div class="movie-details"><div class="movie-detail-grid">${detailItems}</div></div>`;
// Cast with photos
if (data.cast?.length > 0) {
html += `<div class="movie-cast-photos"><div class="movie-section-title">Cast</div><div class="cast-grid">${data.cast.map(c => `<div class="cast-item"><div class="cast-photo">${c.photo ? `<img src="${c.photo}" alt="${c.name}" loading="lazy">` : `<div class="cast-photo-placeholder">?</div>`}</div><div class="cast-name">${c.name}</div><div class="cast-character">${c.character || ''}</div></div>`).join('')}</div></div>`;
}
// Images
if (data.images?.length > 0) {
html += `<div class="movie-photos"><div class="movie-section-title">Photos</div><div class="photos-carousel">${data.images.map(img => `<div class="photo-item ${img.type}" onclick="openPhotoLightbox('${img.url_full}')"><img src="${img.url}" alt="Photo" loading="lazy"></div>`).join('')}</div></div>`;
}
// Videos
if (data.videos?.length > 0) {
html += `<div class="movie-videos"><div class="movie-section-title">Videos</div><div class="videos-grid">${data.videos.map(v => `<div class="video-item" onclick="openVideoModal('${v.embed}')"><div class="video-thumb"><img src="${v.thumbnail}" alt="${v.name}" loading="lazy"><div class="video-play-icon">▶</div></div><div class="video-title">${v.name}</div><div class="video-type">${v.type}</div></div>`).join('')}</div></div>`;
}
// Reviews
if (data.reviews?.length > 0) {
html += `<div class="movie-reviews"><div class="movie-section-title">Reviews</div><div class="reviews-list">${data.reviews.map((r, idx) => `<div class="review-item"><div class="review-header"><div class="review-avatar">${r.avatar ? `<img src="${r.avatar}" alt="${r.author}">` : `<div class="review-avatar-placeholder">?</div>`}</div><div class="review-author"><div class="review-author-name">${r.author}</div>${r.rating ? `<div class="review-rating"><span class="star">★</span> ${r.rating}/10</div>` : ''}${r.created ? `<div class="review-date">${r.created}</div>` : ''}</div></div><div class="review-content" id="review-${idx}">${escapeHtml(r.content.substring(0, 500))}${r.content.length > 500 ? '...' : ''}</div>${r.content.length > 300 ? `<div class="review-expand" onclick="toggleReview(${idx}, this)">Read more</div>` : ''}</div>`).join('')}</div></div>`;
}
movieView.innerHTML = html;
}
function buildRatingsHtml(data) {
let items = '';
if (data.omdbRatings && data.omdbRatings.length > 0) {
items = data.omdbRatings.map(r => {
let icon = '', source = r.Source;
if (r.Source.includes('Internet Movie Database')) {
icon = `<img src="badges/imdb.png" alt="IMDb" class="rating-logo">`;
source = 'IMDb';
}
else if (r.Source.includes('Rotten Tomatoes')) {
icon = `<img src="badges/rottentomatoes.png" alt="Rotten Tomatoes" class="rating-logo">`;
source = 'Rotten';
}
else if (r.Source.includes('Metacritic')) {
icon = `<img src="badges/metacritic.png" alt="Metacritic" class="rating-logo">`;
source = 'Meta';
}
return `<div class="movie-rating-item"><div class="rating-icon">${icon}</div><div class="rating-source">${source}</div><div class="rating-value">${r.Value}</div></div>`;
}).join('');
} else if (data.imdbRating) {