Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
613 lines (525 loc) · 24.8 KB
/
Copy pathserver.js
File metadata and controls
613 lines (525 loc) · 24.8 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
const express = require('express');
const { Readable } = require('stream');
const path = require('path');
const {
fetchSearchPage,
parseSearchResults,
fetchDownload,
fetchBookDetails,
fetchCover,
getMirror,
getMirrorStatus,
setMirror,
setProxy,
getProxyStatus,
MIRRORS,
LIBGEN_BASE,
} = require('./src/scraper');
const {
rootCatalog,
openSearchDescription,
searchResultsFeed,
libraryFeed,
bookFormatsFeed,
OPDS_MIME,
OPDS_ACQ_MIME,
SEARCH_MIME,
} = require('./src/opds');
const lib = require('./src/library');
const auth = require('./src/auth');
const app = express();
const PORT = process.env.PORT || 3000;
const BASE_URL = (process.env.BASE_URL || `http://localhost:${PORT}`).replace(/\/+$/, '');
/** Map DB book row to frontend-friendly shape */
function mapBook(b) {
if (!b) return b;
b.coverUrl = b.cover_url || b.coverUrl || '';
return b;
}
// ─── Middleware ───────────────────────────────────────────────
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use((req, _res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next();
});
// ─── Health check / API info ──────────────────────────────────
app.get('/api/info', (_req, res) => {
const stats = lib.getStats();
res.json({
name: 'Readest LibGen OPDS Bridge',
version: '4.0.0',
source: 'Library Genesis (libgen.li) — no download limits!',
frontend: `${BASE_URL}/`,
opds: `${BASE_URL}/opds`,
dashboard: `${BASE_URL}/dashboard`,
api: {
search: `${BASE_URL}/api/search?q={query}`,
library: `${BASE_URL}/api/library`,
details: `${BASE_URL}/api/book/{bookId}/details`,
proxy: `${BASE_URL}/api/proxy`,
stats: `${BASE_URL}/api/stats`,
},
stats: {
books_tracked: stats.totalBooks,
total_downloads: stats.totalDownloads,
total_searches: stats.totalSearches,
},
});
});
// ═══════════════════════════════════════════════════════════════
// OPDS FEEDS
// ═══════════════════════════════════════════════════════════════
// ─── OPDS Root Catalog ────────────────────────────────────────
app.get('/opds', (_req, res) => {
res.set('Content-Type', OPDS_MIME);
res.send(rootCatalog(BASE_URL));
});
// ─── OpenSearch Description ───────────────────────────────────
app.get('/opds/opensearch.xml', (_req, res) => {
res.set('Content-Type', SEARCH_MIME);
res.send(openSearchDescription(BASE_URL));
});
// ─── Search ───────────────────────────────────────────────────
app.get('/opds/search', async (req, res) => {
const query = req.query.q || req.query.query || '';
const page = parseInt(req.query.page, 10) || 1;
if (!query.trim()) {
res.set('Content-Type', OPDS_ACQ_MIME);
return res.send(
searchResultsFeed({ baseUrl: BASE_URL, query: '', books: [], page: 1 })
);
}
try {
console.log(`[Search] query="${query}" page=${page}`);
const html = await fetchSearchPage(query, page);
const { books, totalPages } = parseSearchResults(html);
console.log(`[Search] Found ${books.length} results (page ${page}/${totalPages})`);
// Log search & cache books in DB
lib.logSearch(query, books.length);
for (const book of books) {
lib.upsertBook(book);
}
res.set('Content-Type', OPDS_ACQ_MIME);
res.send(searchResultsFeed({ baseUrl: BASE_URL, query, books, page, totalPages }));
} catch (err) {
console.error('[Search Error]', err.message);
res.status(502).set('Content-Type', 'text/plain').send(`Search failed: ${err.message}`);
}
});
// ─── Book Details (OPDS) ──────────────────────────────────────
app.get('/opds/book/:bookId/details', async (req, res) => {
const { bookId } = req.params;
try {
let book = lib.getBook(bookId);
if (!book) {
book = { id: bookId, title: 'Book ' + bookId, author: '', extension: '', filesize: '', download: '' };
}
res.set('Content-Type', OPDS_ACQ_MIME);
res.send(searchResultsFeed({ baseUrl: BASE_URL, query: book.title, books: [book], page: 1 }));
} catch (err) {
console.error('[Details Error]', err.message);
res.status(502).send(`Details fetch failed: ${err.message}`);
}
});
// ─── Library Feeds ────────────────────────────────────────────
app.get('/opds/library', (_req, res) => {
const books = lib.getLibraryBooks(null, 100, 0);
res.set('Content-Type', OPDS_ACQ_MIME);
res.send(libraryFeed({ baseUrl: BASE_URL, title: 'My Library', id: 'all', books, status: null }));
});
app.get('/opds/library/downloads', (_req, res) => {
const history = lib.getDownloadHistory(100, 0);
// Map download history to a book-like structure
const books = history.map((h) => {
const cached = lib.getBook(h.book_id);
return cached || {
id: h.book_id,
title: h.title,
author: h.author,
extension: h.extension,
filesize: h.filesize,
download: h.dl_path,
coverUrl: '',
publisher: '',
language: '',
year: '',
rating: '',
};
});
res.set('Content-Type', OPDS_ACQ_MIME);
res.send(libraryFeed({ baseUrl: BASE_URL, title: 'Download History', id: 'downloads', books, status: 'downloads' }));
});
app.get('/opds/library/:status', (req, res) => {
const { status } = req.params;
const validStatuses = ['downloaded', 'reading', 'finished', 'want-to-read', 'favorite'];
if (!validStatuses.includes(status)) {
return res.status(400).send('Invalid status');
}
const titleMap = {
downloaded: 'Downloaded Books',
reading: 'Currently Reading',
finished: 'Finished Books',
'want-to-read': 'Want to Read',
favorite: 'Favorites',
};
const books = lib.getLibraryBooks(status, 100, 0);
res.set('Content-Type', OPDS_ACQ_MIME);
res.send(libraryFeed({ baseUrl: BASE_URL, title: titleMap[status], id: status, books, status }));
});
// ─── Download Proxy ───────────────────────────────────────────
app.get('/libgen/dl/:md5', async (req, res) => {
const md5 = req.params.md5;
const ext = req.query.ext || 'epub';
const bookId = req.query.id || md5;
try {
console.log(`[Download] md5=${md5} (book: ${bookId})`);
// Log download in history
const book = lib.getBook(bookId);
if (book) {
lib.logDownload({ ...book, download: `/libgen/dl/${md5}` });
lib.addToLibrary(bookId, 'downloaded');
} else {
lib.logDownload({ id: bookId, title: 'Unknown', dl_path: `/libgen/dl/${md5}`, extension: ext });
}
const upstream = await fetchDownload(md5);
if (upstream.error) {
console.error(`[Download Error] ${upstream.error}`);
return res.status(502).json({ error: upstream.error });
}
const response = upstream.response;
// Forward content headers
const contentType = response.headers.get('content-type');
const contentDisp = response.headers.get('content-disposition');
const contentLen = response.headers.get('content-length');
if (contentType) res.set('Content-Type', contentType);
if (contentDisp) {
res.set('Content-Disposition', contentDisp);
} else {
res.set('Content-Disposition', `attachment; filename="book.${ext}"`);
}
if (contentLen) res.set('Content-Length', contentLen);
auth.trackDownload();
const readable = Readable.fromWeb(response.body);
readable.pipe(res);
readable.on('error', (err) => {
console.error('[Download Stream Error]', err.message);
if (!res.headersSent) res.status(500).end();
});
} catch (err) {
console.error('[Download Error]', err.message);
res.status(502).send(`Download failed: ${err.message}`);
}
});
// ─── Cover Image Proxy ───────────────────────────────────────
app.get('/opds/cover', async (req, res) => {
const coverUrl = req.query.url;
if (!coverUrl) return res.status(400).send('Missing cover url');
try {
const upstream = await fetchCover(coverUrl);
const contentType = upstream.headers.get('content-type') || 'image/jpeg';
res.set('Content-Type', contentType);
res.set('Cache-Control', 'public, max-age=86400');
const readable = Readable.fromWeb(upstream.body);
readable.pipe(res);
} catch (err) {
console.error('[Cover Error]', err.message);
res.status(502).send('Cover fetch failed');
}
});
// ═══════════════════════════════════════════════════════════════
// JSON SEARCH API (for frontend)
// ═══════════════════════════════════════════════════════════════
app.get('/api/search', async (req, res) => {
const query = req.query.q || '';
const page = parseInt(req.query.page, 10) || 1;
if (!query.trim()) return res.json({ books: [], page: 1 });
try {
console.log(`[API Search] query="${query}" page=${page}`);
const html = await fetchSearchPage(query, page);
const { books, totalPages } = parseSearchResults(html);
lib.logSearch(query, books.length);
for (const book of books) lib.upsertBook(book);
res.json({ books, page, totalPages, count: books.length });
} catch (err) {
console.error('[API Search Error]', err.message);
res.status(502).json({ error: err.message, books: [] });
}
});
// ─── Book Lookup ──────────────────────────────────────────────
app.get('/api/book/:bookId', (req, res) => {
const book = lib.getBook(req.params.bookId);
if (!book) return res.status(404).json({ error: 'Book not found' });
// Map DB column name to frontend-expected key
book.coverUrl = book.cover_url || '';
res.json(book);
});
// ─── Library Status for a Book ────────────────────────────────
app.get('/api/library/status/:bookId', (req, res) => {
try {
const statuses = lib.getBookStatuses ? lib.getBookStatuses(req.params.bookId) : [];
res.json({ bookId: req.params.bookId, statuses });
} catch {
res.json({ bookId: req.params.bookId, statuses: [] });
}
});
// ═══════════════════════════════════════════════════════════════
// MIRROR & PROXY API
// ═══════════════════════════════════════════════════════════════
app.get('/api/mirrors', (_req, res) => {
res.json({ mirrors: getMirrorStatus(), current: getMirror() });
});
app.post('/api/mirrors', (req, res) => {
const { url } = req.body;
if (!url) return res.status(400).json({ error: 'url required' });
setMirror(url);
res.json({ success: true, current: getMirror(), mirrors: getMirrorStatus() });
});
app.get('/api/proxy', (_req, res) => {
res.json(getProxyStatus());
});
app.post('/api/proxy', async (req, res) => {
const { url } = req.body;
const result = await setProxy(url || '');
res.json(result);
});
// ═══════════════════════════════════════════════════════════════
// STATUS API (LibGen needs no auth)
// ═══════════════════════════════════════════════════════════════
app.get('/api/auth/status', (_req, res) => {
res.json(auth.getStatus());
});
// ═══════════════════════════════════════════════════════════════
// REST API (for dashboard & programmatic use)
// ═══════════════════════════════════════════════════════════════
// ─── Get all formats for a book ───────────────────────────────
app.get('/api/book/:bookId/details', async (req, res) => {
try {
const details = await fetchBookDetails(req.params.bookId);
res.json({ success: true, ...details });
} catch (err) {
res.status(502).json({ success: false, error: err.message });
}
});
// ─── Library API ──────────────────────────────────────────────
app.get('/api/library', (req, res) => {
const status = req.query.status || null;
const limit = parseInt(req.query.limit, 10) || 50;
const offset = parseInt(req.query.offset, 10) || 0;
const books = lib.getLibraryBooks(status, limit, offset).map(mapBook);
const count = lib.getLibraryCount(status);
res.json({ books, total: count });
});
app.post('/api/library/add', (req, res) => {
const { bookId, status } = req.body;
if (!bookId) return res.status(400).json({ error: 'bookId required' });
const validStatuses = ['downloaded', 'reading', 'finished', 'want-to-read', 'favorite'];
const s = validStatuses.includes(status) ? status : 'downloaded';
lib.addToLibrary(bookId, s);
res.json({ success: true, bookId, status: s });
});
app.post('/api/library/remove', (req, res) => {
const { bookId, status } = req.body;
if (!bookId || !status) return res.status(400).json({ error: 'bookId and status required' });
lib.removeFromLibrary(bookId, status);
res.json({ success: true });
});
app.post('/api/library/progress', (req, res) => {
const { bookId, progress } = req.body;
if (!bookId || progress === undefined) return res.status(400).json({ error: 'bookId and progress required' });
lib.updateProgress(bookId, parseFloat(progress));
res.json({ success: true, bookId, progress });
});
// ─── Stats & History API ──────────────────────────────────────
app.get('/api/stats', (_req, res) => {
res.json(lib.getStats());
});
app.get('/api/history/downloads', (req, res) => {
const limit = parseInt(req.query.limit, 10) || 50;
const offset = parseInt(req.query.offset, 10) || 0;
res.json({ downloads: lib.getDownloadHistory(limit, offset), total: lib.getDownloadCount() });
});
app.get('/api/history/searches', (req, res) => {
const limit = parseInt(req.query.limit, 10) || 20;
res.json({ searches: lib.getRecentSearches(limit) });
});
// ═══════════════════════════════════════════════════════════════
// WEB DASHBOARD
// ═══════════════════════════════════════════════════════════════
app.get('/dashboard', (_req, res) => {
const stats = lib.getStats();
const recentSearches = lib.getRecentSearches(10);
const statusBadge = (s) => {
const colors = { downloaded: '#3b82f6', reading: '#f59e0b', finished: '#10b981', 'want-to-read': '#8b5cf6', favorite: '#ef4444' };
return `<span style="background:${colors[s] || '#6b7280'};color:#fff;padding:2px 8px;border-radius:12px;font-size:12px">${s}</span>`;
};
const libraryRows = lib.getLibraryBooks(null, 20, 0).map((b) => `
<tr>
<td>${b.title}</td>
<td>${b.author}</td>
<td>${(b.extension || '').toUpperCase()}</td>
<td>${statusBadge(b.lib_status)}</td>
<td>${b.progress > 0 ? Math.round(b.progress * 100) + '%' : '-'}</td>
<td>${b.lib_added_at || ''}</td>
</tr>
`).join('');
const downloadRows = stats.recentDownloads.map((d) => `
<tr>
<td>${d.title}</td>
<td>${d.author}</td>
<td>${(d.extension || '').toUpperCase()}</td>
<td>${d.filesize}</td>
<td>${d.downloaded_at}</td>
</tr>
`).join('');
const searchRows = recentSearches.map((s) => `
<tr>
<td><a href="/opds/search?q=${encodeURIComponent(s.query)}">${s.query}</a></td>
<td>${s.results}</td>
<td>${s.times}</td>
<td>${s.last_searched}</td>
</tr>
`).join('');
const statusCounts = {};
for (const s of stats.libraryByStatus) statusCounts[s.status] = s.count;
res.send(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LibGen OPDS Dashboard</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #0f172a; color: #e2e8f0; min-height: 100vh; }
.container { max-width: 1200px; margin: 0 auto; padding: 20px; }
h1 { font-size: 28px; margin-bottom: 8px; color: #f1f5f9; }
.subtitle { color: #94a3b8; margin-bottom: 30px; }
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 16px; margin-bottom: 30px; }
.stat-card { background: #1e293b; border-radius: 12px; padding: 20px; text-align: center; border: 1px solid #334155; }
.stat-card .number { font-size: 36px; font-weight: 700; color: #38bdf8; }
.stat-card .label { font-size: 13px; color: #94a3b8; margin-top: 4px; }
.opds-url { background: #1e293b; border: 1px solid #334155; border-radius: 8px; padding: 16px; margin-bottom: 30px; display: flex; align-items: center; gap: 12px; }
.opds-url code { flex: 1; color: #38bdf8; font-size: 15px; word-break: break-all; }
.opds-url button { background: #3b82f6; color: #fff; border: none; padding: 8px 16px; border-radius: 6px; cursor: pointer; font-size: 13px; }
.opds-url button:hover { background: #2563eb; }
.section { background: #1e293b; border-radius: 12px; padding: 20px; margin-bottom: 24px; border: 1px solid #334155; }
.section h2 { font-size: 18px; margin-bottom: 16px; color: #f1f5f9; }
table { width: 100%; border-collapse: collapse; }
th { text-align: left; padding: 10px 12px; border-bottom: 2px solid #334155; color: #94a3b8; font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em; }
td { padding: 10px 12px; border-bottom: 1px solid #1e293b; font-size: 14px; }
tr:hover td { background: #334155; }
a { color: #38bdf8; text-decoration: none; }
a:hover { text-decoration: underline; }
.search-box { display: flex; gap: 8px; margin-bottom: 20px; }
.search-box input { flex: 1; padding: 10px 16px; border-radius: 8px; border: 1px solid #334155; background: #0f172a; color: #e2e8f0; font-size: 15px; }
.search-box button { background: #3b82f6; color: #fff; border: none; padding: 10px 24px; border-radius: 8px; cursor: pointer; font-size: 15px; }
.empty { color: #64748b; text-align: center; padding: 40px; }
</style>
</head>
<body>
<div class="container">
<h1>LibGen OPDS Bridge</h1>
<p class="subtitle">Your personal bridge between Readest and Library Genesis — unlimited downloads!</p>
<div class="opds-url">
<span style="color:#94a3b8">OPDS Feed:</span>
<code id="opdsUrl">${BASE_URL}/opds</code>
<button onclick="navigator.clipboard.writeText(document.getElementById('opdsUrl').textContent)">Copy</button>
</div>
<div class="section" style="border-color:#10b981">
<h2>Source: Library Genesis <span style="color:#10b981">● No Limits</span></h2>
<p style="color:#94a3b8">Downloads: ${auth.getDownloadCount()} today — no authentication required, no rate limits!</p>
</div>
<div class="stats-grid">
<div class="stat-card">
<div class="number">${stats.totalBooks}</div>
<div class="label">Books Tracked</div>
</div>
<div class="stat-card">
<div class="number">${stats.totalDownloads}</div>
<div class="label">Downloads</div>
</div>
<div class="stat-card">
<div class="number">${stats.totalSearches}</div>
<div class="label">Searches</div>
</div>
<div class="stat-card">
<div class="number">${statusCounts['favorite'] || 0}</div>
<div class="label">Favorites</div>
</div>
<div class="stat-card">
<div class="number">${statusCounts['reading'] || 0}</div>
<div class="label">Reading</div>
</div>
<div class="stat-card">
<div class="number">${statusCounts['finished'] || 0}</div>
<div class="label">Finished</div>
</div>
</div>
<div class="section">
<h2>Quick Search</h2>
<form class="search-box" action="/opds/search" method="get">
<input name="q" placeholder="Search for books..." autocomplete="off" />
<button type="submit">Search</button>
</form>
</div>
<div class="section">
<h2>Recent Searches</h2>
${searchRows ? `
<table>
<thead><tr><th>Query</th><th>Results</th><th>Times</th><th>Last Searched</th></tr></thead>
<tbody>${searchRows}</tbody>
</table>` : '<p class="empty">No searches yet. Search for a book to get started!</p>'}
</div>
<div class="section">
<h2>Library</h2>
${libraryRows ? `
<table>
<thead><tr><th>Title</th><th>Author</th><th>Format</th><th>Status</th><th>Progress</th><th>Added</th></tr></thead>
<tbody>${libraryRows}</tbody>
</table>` : '<p class="empty">Your library is empty. Download some books to see them here!</p>'}
</div>
<div class="section">
<h2>Recent Downloads</h2>
${downloadRows ? `
<table>
<thead><tr><th>Title</th><th>Author</th><th>Format</th><th>Size</th><th>Downloaded</th></tr></thead>
<tbody>${downloadRows}</tbody>
</table>` : '<p class="empty">No downloads yet.</p>'}
</div>
<div class="section" style="text-align:center;color:#64748b;font-size:13px;border:none;background:none">
<p>
<a href="/opds">OPDS Feed</a> ·
<a href="/api/stats">API Stats</a> ·
<a href="/api/library">Library API</a> ·
<a href="/api/history/downloads">Downloads API</a> ·
<a href="/api/history/searches">Searches API</a>
</p>
</div>
</div>
</body>
</html>`);
});
// ─── Start Server ─────────────────────────────────────────────
app.listen(PORT, () => {
console.log(`
╔══════════════════════════════════════════════════════════════╗
║ Readest LibGen OPDS Bridge v4.0 ║
╠══════════════════════════════════════════════════════════════╣
║ ║
║ Server: http://localhost:${String(PORT).padEnd(27)} ║
║ Frontend: ${(BASE_URL + '/').padEnd(43)} ║
║ OPDS Feed: ${(BASE_URL + '/opds').padEnd(43)} ║
║ Dashboard: ${(BASE_URL + '/dashboard').padEnd(43)} ║
║ ║
║ Features: ║
║ - Web frontend (search, library, downloads, settings) ║
║ - Multi-format downloads (epub, pdf, mobi, azw3...) ║
║ - Library Genesis — NO download limits! ║
║ - Proxy support for restricted regions ║
║ - Personal library tracking ║
║ - Download & search history ║
║ - OPDS feed for e-reader apps ║
║ ║
╚══════════════════════════════════════════════════════════════╝
`);
});