-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1704 lines (1453 loc) · 54.5 KB
/
server.js
File metadata and controls
1704 lines (1453 loc) · 54.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
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs-extra');
const mime = require('mime-types');
const chokidar = require('chokidar');
const crypto = require('crypto');
const yauzl = require('yauzl');
const util = require('util');
const { createServer } = require('http');
const { Server } = require('socket.io');
let ZIMReader = null; // Keep for compatibility
let zimLib = null;
let zimAvailable = false;
let zimLoaded = false;
// Load ZIM functionality
const loadZIM = async () => {
if (zimLoaded) return zimAvailable;
try {
zimLib = await import('@openzim/libzim');
if (zimLib.ZIMReader) console.log('ZIMReader available');
if (zimLib.ZIM) console.log('ZIM available');
if (zimLib.Archive) console.log('Archive available');
zimAvailable = true;
return true;
} catch (error) {
console.warn('ZIM functionality unavailable:', error.message);
console.warn('ZIM file support will be disabled');
return false;
} finally {
zimLoaded = true;
}
};
const app = express();
const PORT = process.env.PORT || 3000;
// Configuration
const config = {
storagePath: process.env.STORAGE_PATH || path.join(__dirname, 'storage'),
configPath: process.env.CONFIG_PATH || path.join(__dirname, 'config'),
maxFileSize: process.env.MAX_FILE_SIZE || '10gb',
adminPassword: process.env.ADMIN_PASSWORD || 'admin',
serverName: process.env.SERVER_NAME || 'Nomad Docker Server'
};
// Advanced Indexing System (using function constructor for compatibility)
function MediaIndexer() {
this.indexes = new Map();
this.watchers = new Map();
this.building = new Set();
this.mediaExtensions = {
video: ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.m4v', '.3gp'],
audio: ['.mp3', '.flac', '.wav', '.aac', '.ogg', '.m4a', '.wma'],
image: ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg', '.tiff'],
book: ['.epub', '.pdf', '.mobi', '.azw', '.txt', '.fb2'],
comic: ['.cbz', '.cbr', '.zip'],
archive: ['.zim', '.zip', '.rar', '.7z', '.tar', '.gz'],
playlist: ['.m3u', '.m3u8', '.pls', '.xspf'],
rom: ['.nes', '.sfc', '.smc', '.gba', '.gb', '.gbc', '.n64', '.gen', '.md', '.sms', '.psx', '.ps1', '.iso', '.bin', '.z64', '.v64']
};
}
// Get file signature for change detection
MediaIndexer.prototype.getDirectorySignature = async function(dirPath) {
try {
const items = await fs.readdir(dirPath);
const stats = await Promise.all(
items.map(async function(item) {
try {
const stat = await fs.stat(path.join(dirPath, item));
return item + ':' + stat.mtime.getTime() + ':' + stat.size;
} catch (e) {
return null;
}
})
);
return crypto.createHash('md5').update(stats.filter(Boolean).join('|')).digest('hex');
} catch (e) {
return null;
}
};
// Check if file matches media extensions
MediaIndexer.prototype.isMediaFile = function(filename, category) {
category = category || 'all';
const ext = path.extname(filename).toLowerCase();
if (category === 'all') {
const allExtensions = Object.values(this.mediaExtensions);
return allExtensions.some(function(exts) {
return exts.includes(ext);
});
}
const categoryExts = this.mediaExtensions[category];
return categoryExts && categoryExts.includes(ext) || false;
};
// Build index for a directory with optional recursion for Shows and Music
MediaIndexer.prototype.buildIndex = async function(dirPath, recursive) {
const self = this;
const normalizedPath = path.normalize(dirPath);
if (this.building.has(normalizedPath)) {
throw new Error('INDEX_BUILDING');
}
this.building.add(normalizedPath);
try {
if (!await fs.pathExists(dirPath)) {
throw new Error('Directory not found');
}
const signature = await this.getDirectorySignature(dirPath);
const entries = [];
// Determine if we should scan recursively based on directory name
const dirName = path.basename(dirPath);
const shouldRecurse = recursive || ['Shows', 'Music'].includes(dirName);
if (shouldRecurse) {
// Recursive scan for Shows and Music
const allEntries = await this.buildRecursiveIndex(dirPath);
for (const entry of allEntries) {
entries.push(entry);
}
} else {
// Single level scan
const items = await fs.readdir(dirPath);
for (const item of items) {
try {
const itemPath = path.join(dirPath, item);
const stats = await fs.stat(itemPath);
// Build relative path from storage root
const relativePath = path.relative(settings.mediaDirectory || config.storagePath, itemPath).replace(/\\/g, '/');
entries.push({
n: item, // name
t: stats.isDirectory() ? 'd' : 'f', // type: directory or file
p: '/' + relativePath, // full path from root
sz: stats.size,
mt: Math.floor(stats.mtime.getTime() / 1000),
isDir: stats.isDirectory(),
isMedia: stats.isDirectory() ? false : self.isMediaFile(item)
});
} catch (error) {
console.warn('Error processing ' + item + ':', error.message);
}
}
}
entries.sort(function(a, b) {
if (a.isDir && !b.isDir) return -1;
if (!a.isDir && b.isDir) return 1;
return a.n.localeCompare(b.n, undefined, { numeric: true });
});
const relativeDirPath = path.relative(settings.mediaDirectory || config.storagePath, dirPath).replace(/\\/g, '/');
const header = {
path: '/' + (relativeDirPath || ''),
sig: signature,
count: entries.length,
ts: Math.floor(Date.now() / 1000),
server: 'nomad-docker'
};
const indexData = { header: header, entries: entries, signature: signature };
this.indexes.set(normalizedPath, indexData);
this.setupWatcher(dirPath);
return indexData;
} finally {
this.building.delete(normalizedPath);
}
};
// Setup file watcher for real-time updates
MediaIndexer.prototype.setupWatcher = function(dirPath) {
const self = this;
const normalizedPath = path.normalize(dirPath);
if (this.watchers.has(normalizedPath)) {
this.watchers.get(normalizedPath).close();
}
const watcher = chokidar.watch(dirPath, {
ignoreInitial: true,
depth: 0,
persistent: true,
usePolling: false
});
watcher
.on('add', function() { self.invalidateIndex(normalizedPath); })
.on('unlink', function() { self.invalidateIndex(normalizedPath); })
.on('addDir', function() { self.invalidateIndex(normalizedPath); })
.on('unlinkDir', function() { self.invalidateIndex(normalizedPath); })
.on('change', function() { self.invalidateIndex(normalizedPath); });
this.watchers.set(normalizedPath, watcher);
};
// Invalidate index when directory changes
MediaIndexer.prototype.invalidateIndex = function(dirPath) {
const self = this;
const normalizedPath = path.normalize(dirPath);
this.indexes.delete(normalizedPath);
setTimeout(async function() {
try {
await self.buildIndex(dirPath);
} catch (error) {
console.error('Error rebuilding index for ' + dirPath + ':', error.message);
}
}, 500);
};
// Get index for directory (build if needed)
MediaIndexer.prototype.getIndex = async function(dirPath) {
const normalizedPath = path.normalize(dirPath);
if (this.indexes.has(normalizedPath)) {
const cached = this.indexes.get(normalizedPath);
const currentSig = await this.getDirectorySignature(dirPath);
if (cached.signature === currentSig) {
return cached;
}
}
return await this.buildIndex(dirPath);
};
// Recursively scan directory for NDJSON (needed by some frontends) - FIXED
MediaIndexer.prototype.buildRecursiveIndex = async function(rootPath) {
const self = this;
const allEntries = [];
// Get the category name from the directory being scanned
const mediaDirectory = settings.mediaDirectory || config.storagePath;
const categoryRelativePath = path.relative(mediaDirectory, rootPath).replace(/\\/g, '/');
async function scanDir(dirPath, relativePath) {
try {
const items = await fs.readdir(dirPath);
for (const item of items) {
const itemPath = path.join(dirPath, item);
const stats = await fs.stat(itemPath);
const itemRelativePath = relativePath ? relativePath + '/' + item : item;
// Build full relative path from media root including category
const fullRelativePath = categoryRelativePath ? categoryRelativePath + '/' + itemRelativePath : itemRelativePath;
allEntries.push({
n: item,
t: stats.isDirectory() ? 'd' : 'f',
p: '/' + fullRelativePath,
sz: stats.size,
mt: Math.floor(stats.mtime.getTime() / 1000),
isDir: stats.isDirectory(),
isMedia: stats.isDirectory() ? false : self.isMediaFile(item)
});
// Recurse into subdirectories
if (stats.isDirectory()) {
await scanDir(itemPath, itemRelativePath);
}
}
} catch (error) {
console.warn('Error scanning ' + dirPath + ':', error.message);
}
}
await scanDir(rootPath, '');
return allEntries;
};
// Generate legacy media.json format
MediaIndexer.prototype.generateMediaJson = async function() {
const self = this;
const mediaData = {
movies: [],
shows: [],
music: [],
books: [],
archive: [],
games: []
};
const categories = [
{ key: 'movies', dir: 'Movies', types: ['video'] },
{ key: 'shows', dir: 'Shows', types: ['video'] },
{ key: 'music', dir: 'Music', types: ['audio'] },
{ key: 'books', dir: 'Books', types: ['book'] },
{ key: 'archive', dir: 'Archive', types: ['archive'] },
{ key: 'games', dir: 'Games', types: ['rom'] }
];
const mediaDirectory = settings.mediaDirectory || config.storagePath;
for (const category of categories) {
const categoryPath = path.join(mediaDirectory, category.dir);
if (await fs.pathExists(categoryPath)) {
try {
// Get recursive entries for this category
const entries = await this.buildRecursiveIndex(categoryPath);
for (const entry of entries) {
if (!entry.isDir && this.isMediaFile(entry.n)) {
// Check if this matches the category type
let matches = false;
for (const type of category.types) {
if (this.isMediaFile(entry.n, type)) {
matches = true;
break;
}
}
if (matches) {
mediaData[category.key].push({
name: entry.n,
file: entry.p,
path: entry.p,
size: entry.sz,
mtime: entry.mt * 1000,
type: path.extname(entry.n).substring(1).toLowerCase() || 'file'
});
}
}
}
} catch (error) {
console.warn('Error building media.json for ' + category.dir + ':', error.message);
}
}
}
return mediaData;
};
// Cleanup watchers
MediaIndexer.prototype.cleanup = function() {
for (const watcher of this.watchers.values()) {
watcher.close();
}
this.watchers.clear();
this.indexes.clear();
};
// Comic handling utilities
// Comic handling utilities
const ComicReader = {
pageCache: new Map(), // Cache for extracted pages
infoCache: new Map(), // Cache for comic info
// Check if file is a comic
isComic: function(filename) {
const ext = path.extname(filename).toLowerCase();
return ['.cbz', '.cbr', '.zip'].includes(ext);
},
// Get comic info with caching
getComicInfo: async function(filePath) {
// Check cache first
const cacheKey = filePath + ':info';
if (this.infoCache.has(cacheKey)) {
return this.infoCache.get(cacheKey);
}
return new Promise((resolve, reject) => {
yauzl.open(filePath, { lazyEntries: true }, (err, zipfile) => {
if (err) return reject(err);
const pages = [];
const imageExts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff'];
zipfile.readEntry();
zipfile.on('entry', (entry) => {
if (!entry.fileName.endsWith('/') && !entry.fileName.startsWith('__MACOSX/')) {
const ext = path.extname(entry.fileName).toLowerCase();
if (imageExts.includes(ext)) {
pages.push({
name: entry.fileName,
index: pages.length,
size: entry.uncompressedSize
});
}
}
zipfile.readEntry();
});
zipfile.on('end', () => {
// Sort pages naturally (handles numbers correctly)
pages.sort((a, b) => {
return a.name.localeCompare(b.name, undefined, {
numeric: true,
sensitivity: 'base'
});
});
const info = {
pageCount: pages.length,
pages: pages,
fileName: path.basename(filePath)
};
// Cache the info
this.infoCache.set(cacheKey, info);
resolve(info);
});
zipfile.on('error', reject);
});
});
},
// Extract page with sequential processing
getComicPage: async function(filePath, pageIndex) {
// Check page cache first
const cacheKey = `${filePath}:${pageIndex}`;
if (this.pageCache.has(cacheKey)) {
return this.pageCache.get(cacheKey);
}
// First, get the comic info to know which page we want
const info = await this.getComicInfo(filePath);
if (pageIndex >= info.pages.length || pageIndex < 0) {
throw new Error(`Page ${pageIndex} not found. Comic has ${info.pages.length} pages.`);
}
const targetPageName = info.pages[pageIndex].name;
return new Promise((resolve, reject) => {
yauzl.open(filePath, { lazyEntries: true }, (err, zipfile) => {
if (err) return reject(err);
zipfile.readEntry();
zipfile.on('entry', (entry) => {
if (entry.fileName === targetPageName) {
// Found our target page, extract it immediately
zipfile.openReadStream(entry, (err, readStream) => {
if (err) {
zipfile.close();
return reject(err);
}
const chunks = [];
readStream.on('data', (chunk) => chunks.push(chunk));
readStream.on('end', () => {
zipfile.close();
const buffer = Buffer.concat(chunks);
const mimeType = mime.lookup(entry.fileName) || 'image/jpeg';
const pageData = {
buffer: buffer,
mimeType: mimeType,
fileName: path.basename(entry.fileName)
};
// Cache the page
if (this.pageCache.size < 50) {
this.pageCache.set(cacheKey, pageData);
}
resolve(pageData);
});
readStream.on('error', (err) => {
zipfile.close();
reject(err);
});
});
} else {
zipfile.readEntry();
}
});
zipfile.on('end', () => {
zipfile.close();
reject(new Error('Page not found in archive'));
});
zipfile.on('error', (err) => {
zipfile.close();
reject(err);
});
});
});
},
// Clear cache when needed
clearCache: function() {
this.pageCache.clear();
this.infoCache.clear();
}
};
// ZIM Archive Manager
function ZimManager() {
this.zimFiles = new Map();
this.zimIndex = new Map();
this.initialized = false;
}
ZimManager.prototype.initialize = async function() {
if (this.initialized) return;
const archivePath = path.join(settings.mediaDirectory || config.storagePath, 'Archives');
await fs.ensureDir(archivePath);
try {
const files = await fs.readdir(archivePath);
const zimFiles = files.filter(function(f) { return f.toLowerCase().endsWith('.zim'); });
if (zimFiles.length === 0) {
this.initialized = true;
return;
}
// Wait for ZIM module to load
const isAvailable = await loadZIM();
if (!isAvailable) {
this.initialized = true;
return;
}
for (const zimFile of zimFiles) {
try {
const filePath = path.join(archivePath, zimFile);
const stats = await fs.stat(filePath);
if (stats.size > 0) {
const zimReader = new zimLib.Archive(filePath);
this.zimFiles.set(zimFile, zimReader);
const title = zimReader.getMetadata('Title') || zimFile;
const description = zimReader.getMetadata('Description') || '';
const articleCount = zimReader.articleCount;
// ADD THIS MISSING LINE:
this.zimIndex.set(zimFile, {
filename: zimFile,
title: title,
description: description,
articleCount: articleCount,
path: filePath
});
} else {
}
} catch (error) {
console.warn('⚠️ Failed to load ZIM file ' + zimFile + ':', error.message);
}
}
this.initialized = true;
} catch (error) {
console.error('Error initializing ZIM files:', error);
this.initialized = true;
}
};
ZimManager.prototype.searchArticles = async function(query, limit) {
if (!this.initialized) await this.initialize();
limit = limit || 20;
const results = [];
const searchTerm = query.toLowerCase();
for (const [filename, zimFile] of this.zimFiles.entries()) {
// Always use manual iteration for partial title matching
try {
const titleIterator = zimFile.iterByTitle();
let count = 0;
let totalChecked = 0;
for (const entry of titleIterator) {
totalChecked++;
if (count >= limit) break;
if (totalChecked > 2000) break; // Check more entries but prevent infinite loop
if (entry.title && entry.title.toLowerCase().includes(searchTerm)) {
// Skip redirect entries since they often don't work in truncated ZIM files
if (entry.isRedirect) {
} else {
const resultUrl = entry.path || entry.title;
results.push({
title: entry.title,
url: resultUrl,
filename: filename,
zimTitle: this.zimIndex.get(filename).title
});
count++;
}
}
// Log progress every 500 entries
if (totalChecked % 500 === 0) {
if (entry.title && entry.title.toLowerCase().includes(searchTerm)) {
const resultUrl = entry.path || entry.title;
results.push({
title: entry.title,
url: resultUrl, // Make sure we use a valid URL
filename: filename,
zimTitle: this.zimIndex.get(filename).title
});
count++;
}
}
}
} catch (error) {
console.warn('🔍 ZIM Search Debug: Manual iteration failed:', error.message);
}
}
return results.slice(0, limit);
};
ZimManager.prototype.getArticle = async function(filename, articleUrl) {
if (!this.initialized) await this.initialize();
const zimReader = this.zimFiles.get(filename);
if (!zimReader) {
throw new Error('ZIM file not found: ' + filename);
}
try {
let entry;
// List of possible namespaces to try for images and assets
const possiblePaths = [
articleUrl, // Original path
'I/' + articleUrl, // Image namespace
'A/' + articleUrl, // Article namespace
'-/' + articleUrl, // Other assets namespace
articleUrl.replace(/^_assets_\//, 'I/'), // Convert _assets_ to I/
articleUrl.replace(/^_assets_\//, '-/'), // Convert _assets_ to -/
articleUrl.replace(/^_assets_\//, 'A/'), // Convert _assets_ to A/
];
// Remove duplicates
const uniquePaths = [...new Set(possiblePaths)];
// Try different methods to get the entry
for (const tryPath of uniquePaths) {;
if (zimReader.hasEntryByPath && zimReader.hasEntryByPath(tryPath)) {
entry = zimReader.getEntryByPath(tryPath);
break;
} else if (zimReader.hasEntryByTitle && zimReader.hasEntryByTitle(tryPath)) {
entry = zimReader.getEntryByTitle(tryPath);
break;
}
}
// If still not found, try iterating (last resort)
if (!entry) {
const titleIterator = zimReader.iterByTitle();
let count = 0;
for (const iterEntry of titleIterator) {
count++;
// Stop after checking too many entries to avoid performance issues
if (count > 50000) break;
for (const tryPath of uniquePaths) {
if (iterEntry.path === tryPath || iterEntry.title === tryPath) {
entry = iterEntry;
break;
}
}
if (entry) break;
}
}
if (!entry) {
throw new Error('Entry not found');
}
// Get the content using the correct ZIM library methods
let content, mimeType;
// Check if this is a redirect entry and follow it
if (entry.isRedirect) {
try {
// Try different ways to get the redirect target
let redirectTarget = null;
// Method 1: Try redirectEntry() function
if (typeof entry.redirectEntry === 'function') {
try {
redirectTarget = entry.redirectEntry();
} catch (e) {
}
}
// Method 2: Try getRedirectEntry() function
if (!redirectTarget && typeof entry.getRedirectEntry === 'function') {
try {
redirectTarget = entry.getRedirectEntry();
} catch (e) {
}
}
// Method 3: Check if redirect is an index/number
if (!redirectTarget && typeof entry.redirect !== 'undefined') {
// If redirect is a number, try to get entry by index
if (typeof entry.redirect === 'number') {
try {
redirectTarget = zimReader.getEntryByClusterOrder(entry.redirect);
} catch (e) {
}
}
}
if (redirectTarget) {
// Recursively call getArticle with the redirect target
return await this.getArticle(filename, redirectTarget.path);
} else {
// Try to get content anyway - might be HTML redirect
const item = entry.getItem();
if (item) {
// Continue to content extraction to see if it's an HTML redirect
} else {
throw new Error('Redirect entry has no content and redirect could not be followed: ' + entry.path);
}
}
} catch (redirectError) {
console.error('🔍 ZIM Article Debug: Failed to follow redirect:', redirectError);
throw redirectError;
}
}
try {
const item = entry.getItem();
if (!item) {
throw new Error('No content item found for entry: ' + entry.path);
}
// Get the raw content - it's a Blob object
const rawContent = item.getData();
// Since it's a Blob, try to get data from the item's data property instead
let blobData;
if (typeof item.data !== 'undefined') {
blobData = item.data;
} else if (rawContent && typeof rawContent.data !== 'undefined') {
blobData = rawContent.data;
} else {
// Try different Blob extraction methods
if (rawContent && typeof rawContent.getData === 'function') {
blobData = rawContent.getData();
} else {
blobData = rawContent;
}
}
// Get MIME type FIRST to determine how to handle content
mimeType = item.mimetype || 'text/html';
// Handle binary content (images, etc.) differently from text content
if (mimeType.startsWith('image/') || mimeType.startsWith('audio/') ||
mimeType.startsWith('video/') || mimeType === 'application/octet-stream') {
// For binary content, return raw data WITHOUT converting to string
let binaryData;
if (blobData instanceof Buffer) {
binaryData = blobData;
} else if (blobData instanceof Uint8Array) {
binaryData = Buffer.from(blobData);
} else {
// Try to extract binary data from the item
try {
binaryData = Buffer.from(blobData);
} catch (e) {
console.error('Failed to convert to binary data:', e);
throw new Error('Could not extract binary data from ZIM entry');
}
}
return {
title: entry.title,
content: binaryData,
mimeType: mimeType,
isBinary: true
};
} else {
// Handle text content (HTML, CSS, JS, etc.)
// Convert data to string
if (blobData instanceof Buffer) {
content = blobData.toString('utf8');
} else if (blobData instanceof Uint8Array) {
content = new TextDecoder('utf8').decode(blobData);
} else if (typeof blobData === 'string') {
content = blobData;
} else {
content = String(blobData);
}
// Check if content is an HTML redirect
if (content && content.includes('<meta http-equiv="refresh"')) {
// Extract the redirect URL from meta refresh
const metaRefreshMatch = content.match(/content="\d+;URL='([^']+)'/i);
if (metaRefreshMatch) {
const redirectUrl = metaRefreshMatch[1];
// Clean up the redirect URL (remove ./ prefix, handle fragments)
let cleanUrl = redirectUrl.replace(/^\.\//, '');
const hashIndex = cleanUrl.indexOf('#');
if (hashIndex !== -1) {
cleanUrl = cleanUrl.substring(0, hashIndex); // Remove fragment for now
}
// Try to follow the HTML redirect
if (cleanUrl && cleanUrl !== entry.path) {
return await this.getArticle(filename, cleanUrl);
}
}
}
return {
title: entry.title,
content: content,
mimeType: mimeType,
isBinary: false
};
}
} catch (contentError) {
console.error('🔍 ZIM Article Debug: Content extraction error:', contentError);
throw contentError;
}
} catch (error) {
console.error('🔍 ZIM Article Debug: Error details:', error);
throw new Error('Article not found: ' + articleUrl + ' in ' + filename);
}
};
ZimManager.prototype.getZimList = function() {
const result = [];
for (const value of this.zimIndex.values()) {
result.push(value);
}
return result;
};
// Initialize indexer
const mediaIndexer = new MediaIndexer();
const zimManager = new ZimManager();
// Settings
// Settings
let settings = {
adminPassword: config.adminPassword,
serverName: config.serverName,
autoGenerateMedia: true,
mediaDirectory: config.storagePath,
defaultStoragePath: config.storagePath,
theme: 'dark',
maxFileSize: 100,
cacheDuration: 24,
allowDownloads: true,
allowBulkDownloads: true,
maxConcurrentDownloads: 3,
requireAuth: false,
guestAccess: true,
sessionTimeout: 60,
enableCustomCSS: false,
customCSS: '',
mediaDirectories: {
movies: [path.join(config.storagePath, 'Movies')],
shows: [path.join(config.storagePath, 'Shows')],
music: [path.join(config.storagePath, 'Music')],
books: [path.join(config.storagePath, 'Books')],
games: [path.join(config.storagePath, 'Games')],
gallery: [path.join(config.storagePath, 'Gallery')]
}
};
// Create required directories
const ensureMediaDirs = function() {
const mediaDirectory = settings.mediaDirectory || config.storagePath;
const requiredDirs = [
'Movies', 'Shows', 'Music', 'Books', 'Archive', 'Gallery', 'Files', 'config'
].map(function(dir) { return path.join(mediaDirectory, dir); });
requiredDirs.forEach(function(dir) { fs.ensureDirSync(dir); });
};
ensureMediaDirs();
// Middleware
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
// CORS headers
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Range, Authorization');
if (req.method === 'OPTIONS') return res.sendStatus(200);
next();
});
// Add this BEFORE the express.static middleware (before line 888)
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'frontend', 'menu.html'));
});
app.get('/logo.png', function(req, res) {
res.sendFile(path.join(__dirname, 'frontend', 'Logo.png'));
});
app.get('/Logo.png', function(req, res) {
res.sendFile(path.join(__dirname, 'frontend', 'Logo.png'));
});
// Serve frontend files with proper MIME types
app.use(express.static(path.join(__dirname, 'frontend'), {
setHeaders: function(res, filePath) {
if (filePath.endsWith('.js')) {
res.setHeader('Content-Type', 'application/javascript');
} else if (filePath.endsWith('.css')) {
res.setHeader('Content-Type', 'text/css');
} else if (filePath.endsWith('.wasm')) {
res.setHeader('Content-Type', 'application/wasm');
} else if (filePath.endsWith('.data')) {
res.setHeader('Content-Type', 'application/octet-stream');
}
}
}));
// Serve menu.html as the root page instead of index.html
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'frontend', 'menu.html'));
});
// Serve frontend files with proper MIME types
app.use(express.static(path.join(__dirname, 'frontend'), {
setHeaders: function(res, filePath) {
if (filePath.endsWith('.js')) {
res.setHeader('Content-Type', 'application/javascript');
} else if (filePath.endsWith('.css')) {
res.setHeader('Content-Type', 'text/css');
} else if (filePath.endsWith('.wasm')) {
res.setHeader('Content-Type', 'application/wasm');
} else if (filePath.endsWith('.data')) {
res.setHeader('Content-Type', 'application/octet-stream');
}
}
}));
// File upload configuration
const storage = multer.diskStorage({
destination: function(req, file, cb) {
const category = req.body.category || 'Files';
const mediaDirectory = settings.mediaDirectory || config.storagePath;
const destPath = path.join(mediaDirectory, category);
fs.ensureDirSync(destPath);
cb(null, destPath);
},
filename: function(req, file, cb) {
cb(null, file.originalname);
}
});
const upload = multer({
storage: storage,
limits: { fileSize: parseInt(config.maxFileSize) || 10 * 1024 * 1024 * 1024 }
});
// Utility functions
const sanitizePath = function(filePath) {
return path.normalize(filePath).replace(/^(\.\.[\/\\])+/, '');
};
// ZIM API Routes
app.get('/api/zim/search', async function(req, res) {
try {
const query = req.query.q;
if (!query) {
return res.json([]);
}
const results = await zimManager.searchArticles(query, 20);
res.json(results);
} catch (error) {
console.error('ZIM search error:', error);
res.status(500).json({ error: 'Search failed' });
}
});
// Add alias for frontend compatibility
app.get('/zim-list', async function(req, res) {
try {
await zimManager.initialize();
const zimFiles = Array.from(zimManager.zimIndex.values());
res.json(zimFiles);
} catch (error) {
console.error('ZIM list error:', error);
res.status(500).json({ error: error.message });