Compare commits
100 Commits
v2.0.0-rc.
...
v2.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 27a4239a4d | |||
| c380d20ef0 | |||
| 39ce24de91 | |||
| f4eb96c4ec | |||
| 6387d4a373 | |||
| c225a9f48d | |||
| 82ddc6d5e9 | |||
| 8296e8d7da | |||
| ba05e08e71 | |||
| 6c9f021e8d | |||
| 5fd2341e8e | |||
| 5b5cedcc98 | |||
| 5401a5e302 | |||
| 4a711accad | |||
| a9fc4b0ece | |||
| e2345aa20a | |||
| 5cf034200e | |||
| 6e51bf8568 | |||
| 4bf23980c2 | |||
| 5fe0e319b9 | |||
| d9c1ba3d27 | |||
| cde09c6ffa | |||
| c65a2e1a5b | |||
| c5a96d59ff | |||
| 148beb6c5a | |||
| 57acf10f38 | |||
| 3fe39bd6df | |||
| 136914ba4a | |||
| 8d4d099c6a | |||
| 40197b6476 | |||
| f72fff982c | |||
| 942cab2f25 | |||
| 5c4f4cf3b6 | |||
| 59fdadd288 | |||
| f5cfa29b64 | |||
| a1d70193fa | |||
| edb8a93395 | |||
| d09c769804 | |||
| 6c3bc4d789 | |||
| 74f6c9bf62 | |||
| 01ae038a8b | |||
| d7ab08c022 | |||
| f612960bd2 | |||
| 7fdd67316d | |||
| a02db95501 | |||
| 58843a8bac | |||
| ba07011800 | |||
| a5757d3bf9 | |||
| 20ea5bee9c | |||
| c9c4cc074c | |||
| 991c58d91d | |||
| e3c366836f | |||
| 1e144c4bad | |||
| 20261159a4 | |||
| 2668bc5e72 | |||
| d07c8de452 | |||
| 7b3c559d03 | |||
| 776079d5c6 | |||
| d801a65602 | |||
| 5e96a89a4b | |||
| 9daa4f1ad8 | |||
| 47433733d0 | |||
| 2afb9742b1 | |||
| a4ff19c3d7 | |||
| 8dc38ec9a7 | |||
| c28948f6e9 | |||
| 48e1939d2a | |||
| 6222e7736f | |||
| 03d8337d89 | |||
| d49f739565 | |||
| 295cab93f3 | |||
| 4bca41f6a2 | |||
| bc74aa8116 | |||
| cc0b0a891e | |||
| 76391f74d2 | |||
| 487e24a20a | |||
| 25ea30f086 | |||
| 6075dcf149 | |||
| dbce12b708 | |||
| 9943c5d010 | |||
| cbacf2ea07 | |||
| 90231f6608 | |||
| a26f03f024 | |||
| 16cf6b3d4f | |||
| 4811c4535a | |||
| d6a99bfeb4 | |||
| b8f560141c | |||
| 2cf475931c | |||
| 41dddef354 | |||
| d54b0bcdef | |||
| c7ed97a452 | |||
| 1ebac7ee15 | |||
| 7490f269b0 | |||
| c7f919fe18 | |||
| 7c85d91b85 | |||
| c11a1eed35 | |||
| 7544f56ba9 | |||
| 1a01d29f19 | |||
| 315c2e911b | |||
| 28ff6ccc68 |
16
.gitignore
vendored
@@ -1,5 +1,11 @@
|
|||||||
node_modules
|
desktop/node_modules
|
||||||
electron
|
desktop/electron
|
||||||
dist
|
desktop/dist
|
||||||
.env
|
desktop/.env
|
||||||
build
|
desktop/build
|
||||||
|
|
||||||
|
docker/node_modules
|
||||||
|
docker/electron
|
||||||
|
docker/dist
|
||||||
|
docker/.env
|
||||||
|
docker/build
|
||||||
|
|||||||
44
README.md
@@ -1,31 +1,55 @@
|
|||||||
# 🎀 WaifuBoard
|
# 🎀 WaifuBoard
|
||||||
|
|
||||||
**Lightweight all-in-one app for boorus, manga and light novels — no sources included, total freedom via extensions.**
|
**Lightweight all-in-one app for boorus, anime, manga and light novels — no sources included, total freedom via extensions.**
|
||||||
|
|
||||||
<img src="public/banner.png" alt="WaifuBoard Hero" width="100%"/>
|
<img src="assets/hero.png" alt="WaifuBoard Hero" width="100%"/>
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
[](https://waifuboard.app)
|
[](https://waifuboard.app)
|
||||||
[](https://git.waifuboard.app/ItsSkaiya/WaifuBoard/releases/latest)
|
[](https://git.waifuboard.app/ItsSkaiya/WaifuBoard/releases/latest)
|
||||||
[](https://git.waifuboard.app/ItsSkaiya/WaifuBoard-Extensions)
|
[](https://git.waifuboard.app/ItsSkaiya/WaifuBoard-Extensions)
|
||||||
|
|
||||||
**[Website](https://waifuboard.app)** • **[Documentation](https://waifuboard.app/docs)** • **[Download Latest](https://git.waifuboard.app/ItsSkaiya/WaifuBoard/releases/latest)** • **[Discord (soon)](#)**
|
**[Website](https://waifuboard.app)** • **[Documentation](https://waifuboard.app/docs)** • **[Download Latest](https://git.waifuboard.app/ItsSkaiya/WaifuBoard/releases/latest)** • **[Discord](https://discord.gg/DAVNf7erRJ)**
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
## 🚀 What is WaifuBoard?
|
|
||||||
|
|
||||||
**A lightweight and privacy-friendly desktop app designed around modular extensions.** WaifuBoard delivers a clean, organized reading experience for boorus, manga, and light novels, powered entirely by community-made sources.
|
|
||||||
|
|
||||||
## ✨ Features
|
## ✨ Features
|
||||||
|
|
||||||
- Lightweight
|
- Lightweight
|
||||||
- Discord Rich Presence
|
- Discord Rich Presence
|
||||||
- Super clean & fast UI
|
- Local lists & anilist integration
|
||||||
- Built-in **Extension Marketplace**
|
- Multi user support
|
||||||
|
- Server version (Coming soon!)
|
||||||
- Fully open-source & community-driven
|
- Fully open-source & community-driven
|
||||||
- Future mobile ports planned
|
|
||||||
|
> ⚠️ **Note**
|
||||||
|
>
|
||||||
|
> Release candidates may contain breaking changes and unresolved bugs.
|
||||||
|
> Expect frequent updates and major changes between versions.
|
||||||
|
|
||||||
|
## 🖼️ Gallery
|
||||||
|
|
||||||
|
### 👥 Multi-User Profiles
|
||||||
|
<img src="assets/users.gif" alt="Multi-user profiles" width="100%"/>
|
||||||
|
|
||||||
|
### 📖 Reader
|
||||||
|
|
||||||
|
#### Manga
|
||||||
|
<img src="assets/manga.png" alt="Manga reader" width="100%"/>
|
||||||
|
|
||||||
|
#### Manhwa
|
||||||
|
<img src="assets/manhwa.png" alt="Manhwa reader" width="100%"/>
|
||||||
|
|
||||||
|
#### Light Novel
|
||||||
|
<img src="assets/novel.gif" alt="Light novel reader" width="100%"/>
|
||||||
|
|
||||||
|
### 📅 Schedule & Tracking
|
||||||
|
<img src="assets/schedule.png" alt="Anime schedule" width="100%"/>
|
||||||
|
|
||||||
|
### 📚 Lists (Local & AniList)
|
||||||
|
<img src="assets/list.gif" alt="Lists and tracking" width="100%"/>
|
||||||
|
|
||||||
|
|
||||||
## 🖥️ Download & Platform Support
|
## 🖥️ Download & Platform Support
|
||||||
|
|
||||||
|
|||||||
BIN
assets/hero.png
Normal file
|
After Width: | Height: | Size: 1.8 MiB |
BIN
assets/list.gif
Normal file
|
After Width: | Height: | Size: 6.2 MiB |
BIN
assets/manga.png
Normal file
|
After Width: | Height: | Size: 756 KiB |
BIN
assets/manhwa.png
Normal file
|
After Width: | Height: | Size: 577 KiB |
BIN
assets/novel.gif
Normal file
|
After Width: | Height: | Size: 1.5 MiB |
BIN
assets/schedule.png
Normal file
|
After Width: | Height: | Size: 227 KiB |
BIN
assets/users.gif
Normal file
|
After Width: | Height: | Size: 5.2 MiB |
5
desktop/.gitignore
vendored
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
node_modules
|
||||||
|
electron
|
||||||
|
dist
|
||||||
|
.env
|
||||||
|
build
|
||||||
229
desktop/loading.html
Normal file
@@ -0,0 +1,229 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Waifuboard</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--color-bg: #09090b;
|
||||||
|
--color-primary: #8b5cf6;
|
||||||
|
--color-text: #ffffff;
|
||||||
|
--color-text-dim: #a1a1aa;
|
||||||
|
}
|
||||||
|
|
||||||
|
* {
|
||||||
|
box-sizing: border-box;
|
||||||
|
user-select: none;
|
||||||
|
-webkit-user-select: none;
|
||||||
|
-ms-user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
background: linear-gradient(135deg, #18181b 0%, var(--color-bg) 100%);
|
||||||
|
color: var(--color-text);
|
||||||
|
font-family: 'Inter', system-ui, -apple-system, sans-serif;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 400px;
|
||||||
|
height: 300px;
|
||||||
|
overflow: hidden;
|
||||||
|
position: relative;
|
||||||
|
border-radius: 16px;
|
||||||
|
-webkit-app-region: drag;
|
||||||
|
}
|
||||||
|
|
||||||
|
body::before {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
border-radius: 16px;
|
||||||
|
box-shadow: 0 0 0 1px rgba(255,255,255,0.05),
|
||||||
|
0 20px 40px rgba(0,0,0,0.6);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
img {
|
||||||
|
-webkit-user-drag: none;
|
||||||
|
user-drag: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bg-particle {
|
||||||
|
position: absolute;
|
||||||
|
background: var(--color-primary);
|
||||||
|
border-radius: 50%;
|
||||||
|
opacity: 0;
|
||||||
|
animation: particleFloat 8s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bg-particle:nth-child(1) {
|
||||||
|
width: 4px;
|
||||||
|
height: 4px;
|
||||||
|
top: 20%;
|
||||||
|
left: 10%;
|
||||||
|
animation-delay: 0s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bg-particle:nth-child(2) {
|
||||||
|
width: 6px;
|
||||||
|
height: 6px;
|
||||||
|
top: 60%;
|
||||||
|
left: 80%;
|
||||||
|
animation-delay: 2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bg-particle:nth-child(3) {
|
||||||
|
width: 3px;
|
||||||
|
height: 3px;
|
||||||
|
top: 40%;
|
||||||
|
left: 20%;
|
||||||
|
animation-delay: 4s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bg-particle:nth-child(4) {
|
||||||
|
width: 5px;
|
||||||
|
height: 5px;
|
||||||
|
top: 70%;
|
||||||
|
left: 70%;
|
||||||
|
animation-delay: 1s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.splash-container {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 28px;
|
||||||
|
width: 100%;
|
||||||
|
animation: fadeIn 0.5s ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-container {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-container.horizontal {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 14px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-icon {
|
||||||
|
width: 50px;
|
||||||
|
height: 50px;
|
||||||
|
object-fit: contain;
|
||||||
|
animation: iconPulse 2s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-name {
|
||||||
|
font-size: 25px;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: -0.02em;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
color: #ffffff;
|
||||||
|
line-height: 1;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.spinner-wrapper {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.spinner {
|
||||||
|
width: 44px;
|
||||||
|
height: 44px;
|
||||||
|
border: 5px solid rgba(139, 92, 246, 0.2);
|
||||||
|
border-top: 5px solid var(--color-primary);
|
||||||
|
border-radius: 50%;
|
||||||
|
animation: spin 1s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading-text {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #a1a1aa;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes fadeIn {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes iconPulse {
|
||||||
|
0%, 100% {
|
||||||
|
transform: scale(1);
|
||||||
|
filter: drop-shadow(0 0 8px rgba(139, 92, 246, 0.4));
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
transform: scale(1.05);
|
||||||
|
filter: drop-shadow(0 0 16px rgba(139, 92, 246, 0.6));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes spin {
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes particleFloat {
|
||||||
|
0% {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(0) scale(0);
|
||||||
|
}
|
||||||
|
25% {
|
||||||
|
opacity: 0.3;
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
opacity: 0.6;
|
||||||
|
transform: translateY(-100px) scale(1);
|
||||||
|
}
|
||||||
|
75% {
|
||||||
|
opacity: 0.3;
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(-200px) scale(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div class="bg-particle"></div>
|
||||||
|
<div class="bg-particle"></div>
|
||||||
|
<div class="bg-particle"></div>
|
||||||
|
<div class="bg-particle"></div>
|
||||||
|
|
||||||
|
<div class="splash-container">
|
||||||
|
<div class="brand-container horizontal">
|
||||||
|
<img src="public/assets/waifuboards.ico" alt="Waifuboard Logo" class="brand-icon">
|
||||||
|
<h1 class="brand-name">Waifuboard</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="spinner-wrapper">
|
||||||
|
<div class="spinner"></div>
|
||||||
|
<span class="loading-text">Loading</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
144
desktop/main.js
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
const { app, BrowserWindow, ipcMain } = require('electron');
|
||||||
|
const { fork } = require('child_process');
|
||||||
|
const path = require('path');
|
||||||
|
const log = require('electron-log');
|
||||||
|
|
||||||
|
const sessionId = new Date().toISOString().replace(/[:.]/g, '-');
|
||||||
|
log.transports.file.resolvePath = () => path.join(app.getPath('userData'), 'logs', `${sessionId}.log`);
|
||||||
|
|
||||||
|
log.transports.file.level = 'info';
|
||||||
|
log.format = '[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}] {text}';
|
||||||
|
|
||||||
|
let win;
|
||||||
|
let backend;
|
||||||
|
const net = require('net');
|
||||||
|
|
||||||
|
function waitForServer(port, host = '127.0.0.1', timeout = 10000) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const start = Date.now();
|
||||||
|
|
||||||
|
const check = () => {
|
||||||
|
const socket = new net.Socket();
|
||||||
|
|
||||||
|
socket
|
||||||
|
.once('connect', () => {
|
||||||
|
socket.destroy();
|
||||||
|
resolve();
|
||||||
|
})
|
||||||
|
.once('error', () => {
|
||||||
|
socket.destroy();
|
||||||
|
if (Date.now() - start > timeout) {
|
||||||
|
reject(new Error('Backend timeout'));
|
||||||
|
} else {
|
||||||
|
setTimeout(check, 200);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.connect(port, host);
|
||||||
|
};
|
||||||
|
|
||||||
|
check();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function startBackend() {
|
||||||
|
backend = fork(path.join(__dirname, 'server.js'), [], {
|
||||||
|
stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
IS_PACKAGED: app.isPackaged ? 'true' : 'false'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
log.info('Starting backend process...');
|
||||||
|
|
||||||
|
backend.stdout.on('data', (data) => {
|
||||||
|
log.info(`[Backend]: ${data.toString().trim()}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
backend.stderr.on('data', (data) => {
|
||||||
|
log.error(`[Backend ERROR]: ${data.toString().trim()}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
backend.on('exit', (code) => {
|
||||||
|
log.warn(`Backend process exited with code: ${code}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let splash;
|
||||||
|
|
||||||
|
function createSplash() {
|
||||||
|
splash = new BrowserWindow({
|
||||||
|
width: 400,
|
||||||
|
height: 300,
|
||||||
|
frame: false,
|
||||||
|
transparent: false,
|
||||||
|
alwaysOnTop: true,
|
||||||
|
resizable: false,
|
||||||
|
hasShadow: false,
|
||||||
|
backgroundColor: '#00000000'
|
||||||
|
});
|
||||||
|
|
||||||
|
splash.loadFile('loading.html');
|
||||||
|
}
|
||||||
|
|
||||||
|
function createWindow() {
|
||||||
|
win = new BrowserWindow({
|
||||||
|
width: 1200,
|
||||||
|
height: 800,
|
||||||
|
frame: false,
|
||||||
|
titleBarStyle: "hidden",
|
||||||
|
webPreferences: {
|
||||||
|
preload: path.join(__dirname, "preload.js"),
|
||||||
|
nodeIntegration: false,
|
||||||
|
contextIsolation: true
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
win.setMenu(null);
|
||||||
|
win.maximize();
|
||||||
|
|
||||||
|
win.loadURL('http://localhost:54322');
|
||||||
|
|
||||||
|
win.on('closed', () => {
|
||||||
|
win = null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ipcMain.on("win:minimize", () => win.minimize());
|
||||||
|
ipcMain.on("win:maximize", () => {
|
||||||
|
if (win.isMaximized()) {
|
||||||
|
win.unmaximize();
|
||||||
|
} else {
|
||||||
|
win.maximize();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ipcMain.on("win:close", () => win.close());
|
||||||
|
|
||||||
|
process.on('uncaughtException', (err) => {
|
||||||
|
log.error('Critical unhandled error in Main:', err);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.whenReady().then(async () => {
|
||||||
|
startBackend();
|
||||||
|
createSplash();
|
||||||
|
try {
|
||||||
|
await waitForServer(54322);
|
||||||
|
createWindow();
|
||||||
|
splash.close();
|
||||||
|
} catch (e) {
|
||||||
|
splash.close();
|
||||||
|
log.error(e);
|
||||||
|
app.quit();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.on('window-all-closed', () => {
|
||||||
|
log.info('Closing all windows...');
|
||||||
|
if (backend) {
|
||||||
|
backend.kill();
|
||||||
|
log.info('Backend process terminated.');
|
||||||
|
}
|
||||||
|
if (process.platform !== 'darwin') {
|
||||||
|
app.quit();
|
||||||
|
}
|
||||||
|
});
|
||||||
834
package-lock.json → desktop/package-lock.json
generated
@@ -4,10 +4,8 @@
|
|||||||
"description": "",
|
"description": "",
|
||||||
"main": "main.js",
|
"main": "main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"start": "tsc && electron .",
|
||||||
"start": "tsc && node server.js",
|
"dist": "tsc && electron-builder"
|
||||||
"electron": "tsc && electron .",
|
|
||||||
"dist": "npm run build && electron-builder"
|
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"author": "",
|
||||||
@@ -15,21 +13,30 @@
|
|||||||
"type": "commonjs",
|
"type": "commonjs",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fastify/static": "^8.3.0",
|
"@fastify/static": "^8.3.0",
|
||||||
"@ryuziii/discord-rpc": "^1.0.1-rc.1",
|
"@fastify/websocket": "^11.2.0",
|
||||||
"bcrypt": "^6.0.0",
|
"@xhayper/discord-rpc": "^1.3.0",
|
||||||
|
"adm-zip": "^0.5.16",
|
||||||
|
"bcryptjs": "^3.0.3",
|
||||||
"bindings": "^1.5.0",
|
"bindings": "^1.5.0",
|
||||||
"cheerio": "^1.1.2",
|
"cheerio": "^1.1.2",
|
||||||
"dotenv": "^17.2.3",
|
"dotenv": "^17.2.3",
|
||||||
|
"electron-log": "^5.4.3",
|
||||||
|
"epub": "^1.3.0",
|
||||||
"fastify": "^5.6.2",
|
"fastify": "^5.6.2",
|
||||||
|
"js-yaml": "^4.1.1",
|
||||||
"jsonwebtoken": "^9.0.3",
|
"jsonwebtoken": "^9.0.3",
|
||||||
"node-addon-api": "^8.5.0",
|
"node-addon-api": "^8.5.0",
|
||||||
|
"node-cron": "^4.2.1",
|
||||||
"playwright-chromium": "^1.57.0",
|
"playwright-chromium": "^1.57.0",
|
||||||
"sqlite3": "^5.1.7"
|
"sqlite3": "^5.1.7",
|
||||||
|
"ws": "^8.18.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/adm-zip": "^0.5.7",
|
||||||
"@types/bcrypt": "^6.0.0",
|
"@types/bcrypt": "^6.0.0",
|
||||||
"@types/jsonwebtoken": "^9.0.10",
|
"@types/jsonwebtoken": "^9.0.10",
|
||||||
"@types/node": "^24.0.0",
|
"@types/node": "^24.0.0",
|
||||||
|
"@types/ws": "^8.18.1",
|
||||||
"electron": "^39.2.5",
|
"electron": "^39.2.5",
|
||||||
"electron-builder": "^26.0.12",
|
"electron-builder": "^26.0.12",
|
||||||
"node-gyp": "^12.1.0",
|
"node-gyp": "^12.1.0",
|
||||||
@@ -47,10 +54,15 @@
|
|||||||
"package.json",
|
"package.json",
|
||||||
"views/**/*",
|
"views/**/*",
|
||||||
"src/scripts/**/*",
|
"src/scripts/**/*",
|
||||||
"public/assets/*"
|
"public/assets/*",
|
||||||
|
"loading.html"
|
||||||
],
|
],
|
||||||
"extraResources": [
|
"extraResources": [
|
||||||
"./.env"
|
{
|
||||||
|
"from": "C:\\Users\\synta\\AppData\\Local\\ms-playwright\\chromium_headless_shell-1200",
|
||||||
|
"to": "playwright/chromium"
|
||||||
|
},
|
||||||
|
".env"
|
||||||
],
|
],
|
||||||
"win": {
|
"win": {
|
||||||
"target": "portable",
|
"target": "portable",
|
||||||
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 123 KiB After Width: | Height: | Size: 123 KiB |
212
desktop/server.js
Normal file
@@ -0,0 +1,212 @@
|
|||||||
|
const fastify = require("fastify")({
|
||||||
|
logger: { level: "error" },
|
||||||
|
});
|
||||||
|
|
||||||
|
const path = require("path");
|
||||||
|
const jwt = require("jsonwebtoken");
|
||||||
|
const cron = require("node-cron");
|
||||||
|
const { initHeadless } = require("./electron/shared/headless");
|
||||||
|
const { initDatabase } = require("./electron/shared/database");
|
||||||
|
const { loadExtensions } = require("./electron/shared/extensions");
|
||||||
|
const { ensureConfigFile } = require("./electron/shared/config");
|
||||||
|
const { init } = require("./electron/api/rpc/rpc.controller");
|
||||||
|
const {refreshTrendingAnime, refreshTopAiringAnime} = require("./electron/api/anime/anime.service");
|
||||||
|
const {refreshPopularBooks, refreshTrendingBooks} = require("./electron/api/books/books.service");
|
||||||
|
|
||||||
|
const dotenv = require("dotenv");
|
||||||
|
const isPackaged = process.env.IS_PACKAGED === "true";
|
||||||
|
const envPath = isPackaged
|
||||||
|
? path.join(process.resourcesPath, ".env")
|
||||||
|
: path.join(__dirname, ".env");
|
||||||
|
|
||||||
|
dotenv.config({ path: envPath, override: false });
|
||||||
|
const viewsRoutes = require("./electron/views/views.routes");
|
||||||
|
const animeRoutes = require("./electron/api/anime/anime.routes");
|
||||||
|
const booksRoutes = require("./electron/api/books/books.routes");
|
||||||
|
const proxyRoutes = require("./electron/api/proxy/proxy.routes");
|
||||||
|
const extensionsRoutes = require("./electron/api/extensions/extensions.routes");
|
||||||
|
const galleryRoutes = require("./electron/api/gallery/gallery.routes");
|
||||||
|
const rpcRoutes = require("./electron/api/rpc/rpc.routes");
|
||||||
|
const userRoutes = require("./electron/api/user/user.routes");
|
||||||
|
const listRoutes = require("./electron/api/list/list.routes");
|
||||||
|
const anilistRoute = require("./electron/api/anilist/anilist");
|
||||||
|
const localRoutes = require("./electron/api/local/local.routes");
|
||||||
|
const configRoutes = require("./electron/api/config/config.routes");
|
||||||
|
const roomRoutes = require("./electron/api/rooms/rooms.routes");
|
||||||
|
const { setupRoomWebSocket } = require("./electron/api/rooms/rooms.websocket");
|
||||||
|
|
||||||
|
const { getConfig } = require('./electron/shared/config');
|
||||||
|
const { values } = getConfig();
|
||||||
|
const jwtSecret = values.server?.jwt_secret;
|
||||||
|
|
||||||
|
fastify.addHook("preHandler", async (request, reply) => {
|
||||||
|
const auth = request.headers.authorization;
|
||||||
|
if (!auth) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const token = auth.replace("Bearer ", "");
|
||||||
|
request.user = jwt.verify(token, jwtSecret);
|
||||||
|
} catch (e) {
|
||||||
|
return reply.code(401).send({ error: "Invalid token" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const roomService = require('./electron/api/rooms/rooms.service');
|
||||||
|
|
||||||
|
fastify.addHook('onRequest', async (req, reply) => {
|
||||||
|
const isTunnel =
|
||||||
|
!!req.headers['cf-connecting-ip'] ||
|
||||||
|
!!req.headers['cf-ray'];
|
||||||
|
|
||||||
|
if (!isTunnel) return;
|
||||||
|
|
||||||
|
if (req.url.startsWith('/public/') ||
|
||||||
|
req.url.startsWith('/views/') ||
|
||||||
|
req.url.startsWith('/src/')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.url.startsWith('/room')) {
|
||||||
|
const urlParams = new URLSearchParams(req.url.split('?')[1]);
|
||||||
|
const roomId = urlParams.get('id');
|
||||||
|
|
||||||
|
if (!roomId) {
|
||||||
|
return reply.code(404).send({ error: 'Room ID required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const room = roomService.getRoom(roomId);
|
||||||
|
if (!room || room.exposed !== true) {
|
||||||
|
return reply.code(404).send({ error: 'Room not found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const wsMatch = req.url.match(/^\/ws\/room\/([a-f0-9]+)/);
|
||||||
|
if (wsMatch) {
|
||||||
|
const roomId = wsMatch[1];
|
||||||
|
const room = roomService.getRoom(roomId);
|
||||||
|
|
||||||
|
if (!room || room.exposed !== true) {
|
||||||
|
return reply.code(404).send({ error: 'Room not found' });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const apiMatch = req.url.match(/^\/api\/rooms\/([a-f0-9]+)/);
|
||||||
|
if (apiMatch) {
|
||||||
|
const roomId = apiMatch[1];
|
||||||
|
const room = roomService.getRoom(roomId);
|
||||||
|
|
||||||
|
if (!room || room.exposed !== true) {
|
||||||
|
return reply.code(404).send({ error: 'Room not found' });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const allowedEndpoints = [
|
||||||
|
'/api/watch/stream',
|
||||||
|
'/api/proxy',
|
||||||
|
'/api/extensions',
|
||||||
|
'/api/search'
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const endpoint of allowedEndpoints) {
|
||||||
|
if (req.url.startsWith(endpoint)) {
|
||||||
|
console.log('[Tunnel] ✓ Allowing utility endpoint:', endpoint);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return reply.code(404).send({ error: 'Not found' });
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.register(require("@fastify/static"), {
|
||||||
|
root: path.join(__dirname, "public"),
|
||||||
|
prefix: "/public/",
|
||||||
|
decorateReply: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.register(require("@fastify/static"), {
|
||||||
|
root: path.join(__dirname, "views"),
|
||||||
|
prefix: "/views/",
|
||||||
|
decorateReply: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.register(require("@fastify/static"), {
|
||||||
|
root: path.join(__dirname, "src", "scripts"),
|
||||||
|
prefix: "/src/scripts/",
|
||||||
|
decorateReply: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.register(viewsRoutes);
|
||||||
|
fastify.register(animeRoutes, { prefix: "/api" });
|
||||||
|
fastify.register(booksRoutes, { prefix: "/api" });
|
||||||
|
fastify.register(proxyRoutes, { prefix: "/api" });
|
||||||
|
fastify.register(extensionsRoutes, { prefix: "/api" });
|
||||||
|
fastify.register(galleryRoutes, { prefix: "/api" });
|
||||||
|
fastify.register(rpcRoutes, { prefix: "/api" });
|
||||||
|
fastify.register(userRoutes, { prefix: "/api" });
|
||||||
|
fastify.register(anilistRoute, { prefix: "/api" });
|
||||||
|
fastify.register(listRoutes, { prefix: "/api" });
|
||||||
|
fastify.register(localRoutes, { prefix: "/api" });
|
||||||
|
fastify.register(configRoutes, { prefix: "/api" });
|
||||||
|
fastify.register(roomRoutes, { prefix: "/api" });
|
||||||
|
|
||||||
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
|
||||||
|
const start = async () => {
|
||||||
|
try {
|
||||||
|
await fastify.register(require('@fastify/websocket'));
|
||||||
|
ensureConfigFile()
|
||||||
|
initDatabase("anilist");
|
||||||
|
initDatabase("favorites");
|
||||||
|
initDatabase("cache");
|
||||||
|
initDatabase("userdata");
|
||||||
|
initDatabase("local_library");
|
||||||
|
init();
|
||||||
|
setupRoomWebSocket(fastify);
|
||||||
|
|
||||||
|
const refreshAll = async () => {
|
||||||
|
await refreshTrendingAnime();
|
||||||
|
await sleep(300);
|
||||||
|
await refreshTopAiringAnime();
|
||||||
|
await sleep(300);
|
||||||
|
await refreshTrendingBooks();
|
||||||
|
await sleep(300);
|
||||||
|
await refreshPopularBooks();
|
||||||
|
};
|
||||||
|
|
||||||
|
const job = cron.schedule("*/30 * * * *", async () => {
|
||||||
|
try {
|
||||||
|
await refreshAll();
|
||||||
|
console.log("cache refreshed");
|
||||||
|
} catch (e) {
|
||||||
|
console.error("refresh failed", e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await loadExtensions();
|
||||||
|
await initHeadless();
|
||||||
|
|
||||||
|
await fastify.listen({ port: 54322, host: "0.0.0.0" });
|
||||||
|
refreshAll().catch(e =>
|
||||||
|
console.error("initial refresh failed", e)
|
||||||
|
);
|
||||||
|
console.log(`Server running at http://localhost:54322`);
|
||||||
|
|
||||||
|
const shutdown = async () => {
|
||||||
|
job.stop();
|
||||||
|
await fastify.close();
|
||||||
|
process.exit(0);
|
||||||
|
};
|
||||||
|
|
||||||
|
process.on("SIGINT", shutdown);
|
||||||
|
process.on("SIGTERM", shutdown);
|
||||||
|
} catch (err) {
|
||||||
|
fastify.log.error(err);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
start();
|
||||||
@@ -2,58 +2,49 @@ import { FastifyInstance } from "fastify";
|
|||||||
import { run } from "../../shared/database";
|
import { run } from "../../shared/database";
|
||||||
|
|
||||||
async function anilist(fastify: FastifyInstance) {
|
async function anilist(fastify: FastifyInstance) {
|
||||||
fastify.get("/anilist", async (request, reply) => {
|
fastify.post("/anilist/store", async (request, reply) => {
|
||||||
try {
|
try {
|
||||||
const { code, state } = request.query as { code?: string; state?: string };
|
const {
|
||||||
|
userId,
|
||||||
|
accessToken,
|
||||||
|
tokenType = "Bearer",
|
||||||
|
expiresIn
|
||||||
|
} = request.body as {
|
||||||
|
userId: number;
|
||||||
|
accessToken: string;
|
||||||
|
tokenType?: string;
|
||||||
|
expiresIn?: number;
|
||||||
|
};
|
||||||
|
|
||||||
if (!code) return reply.status(400).send("No code");
|
if (!userId || !accessToken) {
|
||||||
if (!state) return reply.status(400).send("No user state");
|
return reply.status(400).send({ error: "Faltan datos (User ID o Token)" });
|
||||||
|
|
||||||
const userId = Number(state);
|
|
||||||
if (!userId || isNaN(userId)) {
|
|
||||||
return reply.status(400).send("Invalid user id");
|
|
||||||
}
|
|
||||||
|
|
||||||
const tokenRes = await fetch("https://anilist.co/api/v2/oauth/token", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({
|
|
||||||
grant_type: "authorization_code",
|
|
||||||
client_id: process.env.ANILIST_CLIENT_ID,
|
|
||||||
client_secret: process.env.ANILIST_CLIENT_SECRET,
|
|
||||||
redirect_uri: "http://localhost:54322/api/anilist",
|
|
||||||
code
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
const tokenData = await tokenRes.json();
|
|
||||||
|
|
||||||
if (!tokenData.access_token) {
|
|
||||||
console.error("AniList token error:", tokenData);
|
|
||||||
return reply.status(500).send("Failed to get AniList token");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 1. Verificar que el token es válido consultando a AniList
|
||||||
const userRes = await fetch("https://graphql.anilist.co", {
|
const userRes = await fetch("https://graphql.anilist.co", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
Authorization: `${tokenData.token_type} ${tokenData.access_token}`
|
Authorization: `${tokenType} ${accessToken}`
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
query: `query { Viewer { id } }`
|
query: `query { Viewer { id } }`
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (!userRes.ok) {
|
||||||
|
return reply.status(401).send({ error: "Token de AniList inválido o expirado" });
|
||||||
|
}
|
||||||
|
|
||||||
const userData = await userRes.json();
|
const userData = await userRes.json();
|
||||||
const anilistUserId = userData?.data?.Viewer?.id;
|
const anilistUserId = userData?.data?.Viewer?.id;
|
||||||
|
|
||||||
if (!anilistUserId) {
|
if (!anilistUserId) {
|
||||||
console.error("AniList Viewer error:", userData);
|
return reply.status(500).send({ error: "No se pudo obtener el ID de usuario de AniList" });
|
||||||
return reply.status(500).send("Failed to fetch AniList user");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const expiresAt = new Date(
|
const expiresAt = new Date(
|
||||||
Date.now() + tokenData.expires_in * 1000
|
Date.now() + 365 * 24 * 60 * 60 * 1000
|
||||||
).toISOString();
|
).toISOString();
|
||||||
|
|
||||||
await run(
|
await run(
|
||||||
@@ -71,19 +62,19 @@ async function anilist(fastify: FastifyInstance) {
|
|||||||
[
|
[
|
||||||
userId,
|
userId,
|
||||||
"AniList",
|
"AniList",
|
||||||
tokenData.access_token,
|
accessToken,
|
||||||
tokenData.refresh_token,
|
"", // <- aquí
|
||||||
tokenData.token_type,
|
tokenType,
|
||||||
anilistUserId,
|
anilistUserId,
|
||||||
expiresAt
|
expiresAt
|
||||||
],
|
],
|
||||||
"userdata"
|
"userdata"
|
||||||
);
|
);
|
||||||
|
|
||||||
return reply.redirect("http://localhost:54322/?anilist=success");
|
return reply.send({ ok: true, anilistUserId });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("AniList error:", e);
|
console.error("AniList error:", e);
|
||||||
return reply.redirect("http://localhost:54322/?anilist=error");
|
return reply.status(500).send({ error: "Error interno del servidor al guardar AniList" });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
342
desktop/src/api/anime/anime.controller.ts
Normal file
@@ -0,0 +1,342 @@
|
|||||||
|
import {FastifyReply, FastifyRequest} from 'fastify';
|
||||||
|
import * as animeService from './anime.service';
|
||||||
|
import { setActivity } from '../rpc/rp.service';
|
||||||
|
import { upsertListEntry } from '../list/list.service';
|
||||||
|
import {getExtension} from '../../shared/extensions';
|
||||||
|
import { getConfig as loadConfig } from '../../shared/config';
|
||||||
|
import {Anime, AnimeRequest, SearchRequest, WatchStreamRequest} from '../types';
|
||||||
|
import {spawn} from "node:child_process";
|
||||||
|
import net from 'net';
|
||||||
|
import fs from 'fs';
|
||||||
|
import os from 'os';
|
||||||
|
import path from 'path';
|
||||||
|
import jwt from "jsonwebtoken";
|
||||||
|
|
||||||
|
export async function getAnime(req: AnimeRequest, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const { id } = req.params;
|
||||||
|
const source = req.query.source;
|
||||||
|
|
||||||
|
let anime: Anime | { error: string };
|
||||||
|
if (source === 'anilist') {
|
||||||
|
anime = await animeService.getAnimeById(id);
|
||||||
|
} else {
|
||||||
|
const ext = getExtension(source);
|
||||||
|
anime = await animeService.getAnimeInfoExtension(ext, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
return anime;
|
||||||
|
} catch (err) {
|
||||||
|
return { error: "Database error" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAnimeEpisodes(req: AnimeRequest, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const { id } = req.params;
|
||||||
|
const source = req.query.source || 'anilist';
|
||||||
|
const ext = getExtension(source);
|
||||||
|
|
||||||
|
return await animeService.searchEpisodesInExtension(
|
||||||
|
ext,
|
||||||
|
source,
|
||||||
|
id
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
return { error: "Database error" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getTrending(req: FastifyRequest, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const results = await animeService.getTrendingAnime();
|
||||||
|
return { results };
|
||||||
|
} catch (err) {
|
||||||
|
return { results: [] };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getTopAiring(req: FastifyRequest, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const results = await animeService.getTopAiringAnime();
|
||||||
|
return { results };
|
||||||
|
} catch (err) {
|
||||||
|
return { results: [] };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function search(req: SearchRequest, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const query = req.query.q;
|
||||||
|
const results = await animeService.searchAnimeLocal(query);
|
||||||
|
|
||||||
|
if (results.length > 0) {
|
||||||
|
return { results: results };
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
return { results: [] };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function searchInExtension(req: any, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const extensionName = req.params.extension;
|
||||||
|
const query = req.query.q;
|
||||||
|
|
||||||
|
const ext = getExtension(extensionName);
|
||||||
|
if (!ext) return { results: [] };
|
||||||
|
|
||||||
|
const results = await animeService.searchAnimeInExtension(ext, extensionName, query);
|
||||||
|
return { results };
|
||||||
|
} catch {
|
||||||
|
return { results: [] };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getWatchStream(req: WatchStreamRequest, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const { animeId, episode, server, category, ext, source, extensionAnimeId } = req.query;
|
||||||
|
|
||||||
|
const extension = getExtension(ext);
|
||||||
|
if (!extension) return { error: "Extension not found" };
|
||||||
|
|
||||||
|
return await animeService.getStreamData(
|
||||||
|
extension,
|
||||||
|
episode,
|
||||||
|
animeId,
|
||||||
|
source,
|
||||||
|
server,
|
||||||
|
category,
|
||||||
|
extensionAnimeId
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
const error = err as Error;
|
||||||
|
return { error: error.message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function openInMPV(req: any, reply: any) {
|
||||||
|
try {
|
||||||
|
const { title, video, subtitles = [], chapters = [], animeId, episode, entrySource } = req.body;
|
||||||
|
|
||||||
|
if (!video?.url) return { error: 'Missing video url' };
|
||||||
|
|
||||||
|
const isLocalPath = (p: string) =>
|
||||||
|
p.startsWith('file://') ||
|
||||||
|
p.startsWith('/') ||
|
||||||
|
/^[a-zA-Z]:\\/.test(p);
|
||||||
|
|
||||||
|
const toFileUrl = (p: string) =>
|
||||||
|
p.startsWith('file://')
|
||||||
|
? p
|
||||||
|
: `file://${p.replace(/\\/g, '/')}`;
|
||||||
|
|
||||||
|
const PORT = 54322;
|
||||||
|
const proxyBase = `http://localhost:${PORT}/api/proxy`;
|
||||||
|
const mediaTitle = title || 'Anime';
|
||||||
|
|
||||||
|
const videoUrl = isLocalPath(video.url)
|
||||||
|
? toFileUrl(video.url)
|
||||||
|
: `${proxyBase}?url=${encodeURIComponent(video.url)}` +
|
||||||
|
`&referer=${encodeURIComponent(video.headers?.Referer ?? '')}` +
|
||||||
|
`&origin=${encodeURIComponent(video.headers?.Origin ?? '')}` +
|
||||||
|
`&userAgent=${encodeURIComponent(video.headers?.['User-Agent'] ?? '')}`;
|
||||||
|
|
||||||
|
|
||||||
|
const subsUrls = subtitles.map((s: any) =>
|
||||||
|
isLocalPath(s.src)
|
||||||
|
? toFileUrl(s.src)
|
||||||
|
: `${proxyBase}?url=${encodeURIComponent(s.src)}` +
|
||||||
|
`&referer=${encodeURIComponent(video.headers?.Referer ?? '')}` +
|
||||||
|
`&origin=${encodeURIComponent(video.headers?.Origin ?? '')}` +
|
||||||
|
`&userAgent=${encodeURIComponent(video.headers?.['User-Agent'] ?? '')}`
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
const pipe = `\\\\.\\pipe\\mpv-${Date.now()}`;
|
||||||
|
const { values } = loadConfig();
|
||||||
|
|
||||||
|
const MPV_PATH =
|
||||||
|
values.paths?.mpv || 'mpv';
|
||||||
|
|
||||||
|
let chaptersArg: string[] = [];
|
||||||
|
if (chapters.length) {
|
||||||
|
|
||||||
|
chapters.sort((a: any, b: any) => a.startTime - b.startTime);
|
||||||
|
|
||||||
|
const lines = [';FFMETADATA1'];
|
||||||
|
|
||||||
|
for (let i = 0; i < chapters.length; i++) {
|
||||||
|
const c = chapters[i];
|
||||||
|
|
||||||
|
const start = Math.floor(c.startTime * 1000);
|
||||||
|
const end = Math.floor(c.endTime * 1000);
|
||||||
|
|
||||||
|
const title = (c.type || 'chapter').toUpperCase();
|
||||||
|
|
||||||
|
lines.push(
|
||||||
|
`[CHAPTER]`, `TIMEBASE=1/1000`, `START=${start}`, `END=${end}`, `title=${title}`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (i < chapters.length - 1) {
|
||||||
|
const nextStart = Math.floor(chapters[i + 1].startTime * 1000);
|
||||||
|
|
||||||
|
if (nextStart - end > 1000) {
|
||||||
|
lines.push(
|
||||||
|
`[CHAPTER]`, `TIMEBASE=1/1000`, `START=${end}`, `END=${nextStart}`, `title=Episode`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
lines.push(
|
||||||
|
`[CHAPTER]`, `TIMEBASE=1/1000`, `START=${end}`, `title=Episode`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const chaptersFile = path.join(os.tmpdir(), `mpv-chapters-${Date.now()}.txt`);
|
||||||
|
fs.writeFileSync(chaptersFile, lines.join('\n'));
|
||||||
|
chaptersArg = [`--chapters-file=${chaptersFile}`];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!MPV_PATH) {
|
||||||
|
return { error: 'MPV_NOT_CONFIGURED' };
|
||||||
|
}
|
||||||
|
|
||||||
|
spawn(
|
||||||
|
MPV_PATH,
|
||||||
|
[
|
||||||
|
'--force-window=yes',
|
||||||
|
'--idle=yes',
|
||||||
|
'--keep-open=yes',
|
||||||
|
'--no-terminal',
|
||||||
|
'--hwdec=auto',
|
||||||
|
`--force-media-title=Loading...`,
|
||||||
|
|
||||||
|
`--input-ipc-server=${pipe}`,
|
||||||
|
...chaptersArg
|
||||||
|
],
|
||||||
|
{ stdio: 'ignore', windowsHide: true, detached: true }
|
||||||
|
).unref();
|
||||||
|
|
||||||
|
await new Promise(r => setTimeout(r, 400));
|
||||||
|
const socket = net.connect(pipe);
|
||||||
|
|
||||||
|
let duration = 0;
|
||||||
|
let currentTime = 0;
|
||||||
|
let isPaused = false;
|
||||||
|
let titleChanged = false;
|
||||||
|
let progressUpdated = false;
|
||||||
|
|
||||||
|
const sendRPC = (paused: boolean) => {
|
||||||
|
let startTimestamp = undefined;
|
||||||
|
let endTimestamp = undefined;
|
||||||
|
|
||||||
|
if (!paused && duration > 0) {
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
const elapsed = Math.floor(currentTime);
|
||||||
|
|
||||||
|
startTimestamp = now - elapsed;
|
||||||
|
endTimestamp = startTimestamp + Math.floor(duration);
|
||||||
|
}
|
||||||
|
setActivity({
|
||||||
|
details: mediaTitle,
|
||||||
|
state: `Episode ${episode}`,
|
||||||
|
mode: "watching",
|
||||||
|
paused: paused,
|
||||||
|
startTimestamp: startTimestamp,
|
||||||
|
endTimestamp: endTimestamp
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateProgress = async () => {
|
||||||
|
if (!req.user || progressUpdated) return;
|
||||||
|
try {
|
||||||
|
const userId = req.user.id;
|
||||||
|
await upsertListEntry({
|
||||||
|
user_id: userId,
|
||||||
|
entry_id: animeId,
|
||||||
|
source: entrySource,
|
||||||
|
entry_type: "ANIME",
|
||||||
|
status: "CURRENT",
|
||||||
|
progress: episode
|
||||||
|
});
|
||||||
|
progressUpdated = true;
|
||||||
|
progressUpdated = true;
|
||||||
|
} catch (e) { console.error("[MPV] Progress update failed", e); }
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadingTimeout = setTimeout(() => { if (!socket.destroyed) socket.end(); }, 15000);
|
||||||
|
|
||||||
|
socket.on('data', (data) => {
|
||||||
|
const chunks = data.toString().split('\n');
|
||||||
|
for (const chunk of chunks) {
|
||||||
|
if (!chunk.trim()) continue;
|
||||||
|
try {
|
||||||
|
const json = JSON.parse(chunk);
|
||||||
|
|
||||||
|
if (json.event === 'property-change' && json.name === 'duration' && typeof json.data === 'number') {
|
||||||
|
duration = json.data;
|
||||||
|
if (!titleChanged) {
|
||||||
|
socket.write(JSON.stringify({ command: ['set_property', 'force-media-title', mediaTitle] }) + '\n');
|
||||||
|
|
||||||
|
sendRPC(false);
|
||||||
|
titleChanged = true;
|
||||||
|
clearTimeout(loadingTimeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (json.event === 'property-change' && json.name === 'time-pos' && typeof json.data === 'number') {
|
||||||
|
currentTime = json.data;
|
||||||
|
|
||||||
|
if (duration > 0 && !progressUpdated && (currentTime / duration) >= 0.8) {
|
||||||
|
updateProgress();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (json.event === 'property-change' && json.name === 'pause') {
|
||||||
|
isPaused = json.data === true;
|
||||||
|
sendRPC(isPaused);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if (json.event === 'seek') {
|
||||||
|
|
||||||
|
setTimeout(() => sendRPC(isPaused), 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (json.event === 'end-file' || json.event === 'shutdown') {
|
||||||
|
sendRPC(true);
|
||||||
|
if (!socket.destroyed) socket.destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (err) {}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const commands = [
|
||||||
|
{ command: ['observe_property', 1, 'duration'] },
|
||||||
|
{ command: ['observe_property', 2, 'time-pos'] },
|
||||||
|
{ command: ['observe_property', 3, 'pause'] },
|
||||||
|
{ command: ['loadfile', videoUrl, 'replace'] }
|
||||||
|
];
|
||||||
|
|
||||||
|
commands.forEach(cmd => socket.write(JSON.stringify(cmd) + '\n'));
|
||||||
|
|
||||||
|
subtitles.forEach((s: any, i: number) => {
|
||||||
|
socket.write(JSON.stringify({
|
||||||
|
command: [
|
||||||
|
'sub-add',
|
||||||
|
subsUrls[i],
|
||||||
|
'auto',
|
||||||
|
s.label || 'Subtitle',
|
||||||
|
s.srclang || ''
|
||||||
|
]
|
||||||
|
}) + '\n');
|
||||||
|
});
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
} catch (e) {
|
||||||
|
return { error: (e as Error).message };
|
||||||
|
}
|
||||||
|
}
|
||||||
15
desktop/src/api/anime/anime.routes.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { FastifyInstance } from 'fastify';
|
||||||
|
import * as controller from './anime.controller';
|
||||||
|
|
||||||
|
async function animeRoutes(fastify: FastifyInstance) {
|
||||||
|
fastify.get('/anime/:id', controller.getAnime);
|
||||||
|
fastify.get('/anime/:id/:episodes', controller.getAnimeEpisodes);
|
||||||
|
fastify.get('/trending', controller.getTrending);
|
||||||
|
fastify.get('/top-airing', controller.getTopAiring);
|
||||||
|
fastify.get('/search', controller.search);
|
||||||
|
fastify.get('/search/:extension', controller.searchInExtension);
|
||||||
|
fastify.get('/watch/stream', controller.getWatchStream);
|
||||||
|
fastify.post('/watch/mpv', controller.openInMPV);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default animeRoutes;
|
||||||
@@ -3,7 +3,6 @@ import { queryAll, queryOne } from '../../shared/database';
|
|||||||
import {Anime, Episode, Extension, StreamData} from '../types';
|
import {Anime, Episode, Extension, StreamData} from '../types';
|
||||||
|
|
||||||
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
||||||
const TTL = 60 * 60 * 6;
|
|
||||||
|
|
||||||
const ANILIST_URL = "https://graphql.anilist.co";
|
const ANILIST_URL = "https://graphql.anilist.co";
|
||||||
|
|
||||||
@@ -42,17 +41,21 @@ const MEDIA_FIELDS = `
|
|||||||
siteUrl
|
siteUrl
|
||||||
tags { id name description category rank isGeneralSpoiler isMediaSpoiler isAdult }
|
tags { id name description category rank isGeneralSpoiler isMediaSpoiler isAdult }
|
||||||
relations {
|
relations {
|
||||||
edges {
|
edges {
|
||||||
relationType
|
relationType
|
||||||
node {
|
node {
|
||||||
id
|
id
|
||||||
title { romaji }
|
title { romaji english }
|
||||||
type
|
type
|
||||||
format
|
format
|
||||||
status
|
status
|
||||||
|
coverImage { medium large color }
|
||||||
|
bannerImage
|
||||||
|
season
|
||||||
|
seasonYear
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
studios {
|
studios {
|
||||||
edges {
|
edges {
|
||||||
isMain
|
isMain
|
||||||
@@ -71,14 +74,78 @@ const MEDIA_FIELDS = `
|
|||||||
mediaRecommendation {
|
mediaRecommendation {
|
||||||
id
|
id
|
||||||
title { romaji }
|
title { romaji }
|
||||||
coverImage { medium }
|
coverImage { medium large}
|
||||||
format
|
format
|
||||||
type
|
type
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
characters(perPage: 12, sort: [ROLE, RELEVANCE]) {
|
||||||
|
edges {
|
||||||
|
role
|
||||||
|
node {
|
||||||
|
id
|
||||||
|
name { full native }
|
||||||
|
image { medium large }
|
||||||
|
}
|
||||||
|
voiceActors {
|
||||||
|
id
|
||||||
|
name { full }
|
||||||
|
language
|
||||||
|
image { medium }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
export async function refreshTrendingAnime(): Promise<void> {
|
||||||
|
const query = `
|
||||||
|
query {
|
||||||
|
Page(page: 1, perPage: 10) {
|
||||||
|
media(type: ANIME, sort: TRENDING_DESC) { ${MEDIA_FIELDS} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const data = await fetchAniList(query, {});
|
||||||
|
const list = data?.Page?.media || [];
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
|
await queryOne("DELETE FROM trending");
|
||||||
|
|
||||||
|
let rank = 1;
|
||||||
|
for (const anime of list) {
|
||||||
|
await queryOne(
|
||||||
|
"INSERT INTO trending (rank, id, full_data, updated_at) VALUES (?, ?, ?, ?)",
|
||||||
|
[rank++, anime.id, JSON.stringify(anime), now]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function refreshTopAiringAnime(): Promise<void> {
|
||||||
|
const query = `
|
||||||
|
query {
|
||||||
|
Page(page: 1, perPage: 10) {
|
||||||
|
media(type: ANIME, status: RELEASING, sort: SCORE_DESC) { ${MEDIA_FIELDS} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const data = await fetchAniList(query, {});
|
||||||
|
const list = data?.Page?.media || [];
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
|
await queryOne("DELETE FROM top_airing");
|
||||||
|
|
||||||
|
let rank = 1;
|
||||||
|
for (const anime of list) {
|
||||||
|
await queryOne(
|
||||||
|
"INSERT INTO top_airing (rank, id, full_data, updated_at) VALUES (?, ?, ?, ?)",
|
||||||
|
[rank++, anime.id, JSON.stringify(anime), now]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function fetchAniList(query: string, variables: any) {
|
async function fetchAniList(query: string, variables: any) {
|
||||||
const res = await fetch(ANILIST_URL, {
|
const res = await fetch(ANILIST_URL, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -93,7 +160,19 @@ async function fetchAniList(query: string, variables: any) {
|
|||||||
export async function getAnimeById(id: string | number): Promise<Anime | { error: string }> {
|
export async function getAnimeById(id: string | number): Promise<Anime | { error: string }> {
|
||||||
const row = await queryOne("SELECT full_data FROM anime WHERE id = ?", [id]);
|
const row = await queryOne("SELECT full_data FROM anime WHERE id = ?", [id]);
|
||||||
|
|
||||||
if (row) return JSON.parse(row.full_data);
|
if (row) {
|
||||||
|
const cached = JSON.parse(row.full_data);
|
||||||
|
|
||||||
|
if (cached?.characters?.edges?.length) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
await queryOne(
|
||||||
|
"DELETE FROM anime WHERE id = ?",
|
||||||
|
[id]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
const query = `
|
const query = `
|
||||||
query ($id: Int) {
|
query ($id: Int) {
|
||||||
@@ -119,76 +198,16 @@ export async function getAnimeById(id: string | number): Promise<Anime | { error
|
|||||||
|
|
||||||
export async function getTrendingAnime(): Promise<Anime[]> {
|
export async function getTrendingAnime(): Promise<Anime[]> {
|
||||||
const rows = await queryAll(
|
const rows = await queryAll(
|
||||||
"SELECT full_data, updated_at FROM trending ORDER BY rank ASC LIMIT 10"
|
"SELECT full_data FROM trending ORDER BY rank ASC LIMIT 10"
|
||||||
);
|
);
|
||||||
|
return rows.map((r: { full_data: string; }) => JSON.parse(r.full_data));
|
||||||
if (rows.length) {
|
|
||||||
const expired = (Date.now() / 1000 - rows[0].updated_at) > TTL;
|
|
||||||
if (!expired) {
|
|
||||||
return rows.map((r: { full_data: string }) => JSON.parse(r.full_data));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const query = `
|
|
||||||
query {
|
|
||||||
Page(page: 1, perPage: 10) {
|
|
||||||
media(type: ANIME, sort: TRENDING_DESC) { ${MEDIA_FIELDS} }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
`;
|
|
||||||
|
|
||||||
const data = await fetchAniList(query, {});
|
|
||||||
const list = data?.Page?.media || [];
|
|
||||||
const now = Math.floor(Date.now() / 1000);
|
|
||||||
|
|
||||||
await queryOne("DELETE FROM trending");
|
|
||||||
let rank = 1;
|
|
||||||
|
|
||||||
for (const anime of list) {
|
|
||||||
await queryOne(
|
|
||||||
"INSERT INTO trending (rank, id, full_data, updated_at) VALUES (?, ?, ?, ?)",
|
|
||||||
[rank++, anime.id, JSON.stringify(anime), now]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return list;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getTopAiringAnime(): Promise<Anime[]> {
|
export async function getTopAiringAnime(): Promise<Anime[]> {
|
||||||
const rows = await queryAll(
|
const rows = await queryAll(
|
||||||
"SELECT full_data, updated_at FROM top_airing ORDER BY rank ASC LIMIT 10"
|
"SELECT full_data FROM top_airing ORDER BY rank ASC LIMIT 10"
|
||||||
);
|
);
|
||||||
|
return rows.map((r: { full_data: string; }) => JSON.parse(r.full_data));
|
||||||
if (rows.length) {
|
|
||||||
const expired = (Date.now() / 1000 - rows[0].updated_at) > TTL;
|
|
||||||
if (!expired) {
|
|
||||||
return rows.map((r: { full_data: string }) => JSON.parse(r.full_data));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const query = `
|
|
||||||
query {
|
|
||||||
Page(page: 1, perPage: 10) {
|
|
||||||
media(type: ANIME, status: RELEASING, sort: SCORE_DESC) { ${MEDIA_FIELDS} }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
`;
|
|
||||||
|
|
||||||
const data = await fetchAniList(query, {});
|
|
||||||
const list = data?.Page?.media || [];
|
|
||||||
const now = Math.floor(Date.now() / 1000);
|
|
||||||
|
|
||||||
await queryOne("DELETE FROM top_airing");
|
|
||||||
let rank = 1;
|
|
||||||
|
|
||||||
for (const anime of list) {
|
|
||||||
await queryOne(
|
|
||||||
"INSERT INTO top_airing (rank, id, full_data, updated_at) VALUES (?, ?, ?, ?)",
|
|
||||||
[rank++, anime.id, JSON.stringify(anime), now]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return list;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function searchAnimeLocal(query: string): Promise<Anime[]> {
|
export async function searchAnimeLocal(query: string): Promise<Anime[]> {
|
||||||
@@ -257,7 +276,6 @@ export async function getAnimeInfoExtension(ext: Extension | null, id: string):
|
|||||||
if (!ext) return { error: "not found" };
|
if (!ext) return { error: "not found" };
|
||||||
|
|
||||||
const extName = ext.constructor.name;
|
const extName = ext.constructor.name;
|
||||||
|
|
||||||
const cached = await getCachedExtension(extName, id);
|
const cached = await getCachedExtension(extName, id);
|
||||||
if (cached) {
|
if (cached) {
|
||||||
try {
|
try {
|
||||||
@@ -322,6 +340,7 @@ export async function searchAnimeInExtension(ext: Extension | null, name: string
|
|||||||
averageScore: m.rating || m.score || null,
|
averageScore: m.rating || m.score || null,
|
||||||
format: 'ANIME',
|
format: 'ANIME',
|
||||||
seasonYear: null,
|
seasonYear: null,
|
||||||
|
url: m.url,
|
||||||
isExtensionResult: true,
|
isExtensionResult: true,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
@@ -342,15 +361,36 @@ export async function searchEpisodesInExtension(ext: Extension | null, name: str
|
|||||||
if (cached) {
|
if (cached) {
|
||||||
const isExpired = Date.now() - cached.created_at > CACHE_TTL_MS;
|
const isExpired = Date.now() - cached.created_at > CACHE_TTL_MS;
|
||||||
|
|
||||||
if (!isExpired) {
|
try {
|
||||||
console.log(`[${name}] Episodes cache hit for: ${query}`);
|
const parsed = JSON.parse(cached.result) as {
|
||||||
try {
|
mediaId?: string;
|
||||||
return JSON.parse(cached.result) as Episode[];
|
episodes: Episode[];
|
||||||
} catch (e) {
|
};
|
||||||
console.error(`[${name}] Error parsing cached episodes:`, e);
|
|
||||||
|
if (!isExpired) {
|
||||||
|
console.log(`[${name}] Episodes cache hit for: ${query}`);
|
||||||
|
return parsed.episodes;
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
console.log(`[${name}] Episodes cache expired for: ${query}`);
|
// Si el caché expiró pero tenemos mediaId, refrescamos directamente
|
||||||
|
if (parsed.mediaId && ext.type === "anime-board" && ext.search && typeof ext.findEpisodes === "function") {
|
||||||
|
console.log(`[${name}] Episodes cache expired but mediaId found, refreshing...`);
|
||||||
|
const chapterList = await ext.findEpisodes(parsed.mediaId);
|
||||||
|
|
||||||
|
if (!Array.isArray(chapterList)) return [];
|
||||||
|
|
||||||
|
const result: Episode[] = chapterList.map(ep => ({
|
||||||
|
id: ep.id,
|
||||||
|
number: ep.number,
|
||||||
|
url: ep.url,
|
||||||
|
title: ep.title
|
||||||
|
}));
|
||||||
|
|
||||||
|
await setCache(cacheKey, { mediaId: parsed.mediaId, episodes: result }, CACHE_TTL_MS);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[${name}] Error parsing cached episodes:`, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -368,20 +408,40 @@ export async function searchEpisodesInExtension(ext: Extension | null, name: str
|
|||||||
startDate: { year: 0, month: 0, day: 0 }
|
startDate: { year: 0, month: 0, day: 0 }
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!matches || matches.length === 0) return [];
|
if (!matches || matches.length === 0) return [];
|
||||||
|
|
||||||
const res = matches[0];
|
const normalizedQuery = normalize(query);
|
||||||
|
const scored = matches.map(match => {
|
||||||
|
const normalizedTitle = normalize(match.title);
|
||||||
|
const score = similarity(normalizedQuery, normalizedTitle);
|
||||||
|
|
||||||
|
let bonus = 0;
|
||||||
|
if (normalizedTitle === normalizedQuery) {
|
||||||
|
bonus = 0.5;
|
||||||
|
} else if (normalizedTitle.toLowerCase().includes(normalizedQuery.toLowerCase())) {
|
||||||
|
bonus = 0.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
const finalScore = score + bonus;
|
||||||
|
|
||||||
|
return {
|
||||||
|
match,
|
||||||
|
score: finalScore
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
scored.sort((a, b) => b.score - a.score);
|
||||||
|
const bestMatches = scored.filter(s => s.score > 0.4);
|
||||||
|
|
||||||
|
if (bestMatches.length === 0) return [];
|
||||||
|
const res = bestMatches[0].match;
|
||||||
if (!res?.id) return [];
|
if (!res?.id) return [];
|
||||||
|
|
||||||
mediaId = res.id;
|
mediaId = res.id;
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
mediaId = query;
|
mediaId = query;
|
||||||
}
|
}
|
||||||
|
|
||||||
const chapterList = await ext.findEpisodes(mediaId);
|
const chapterList = await ext.findEpisodes(mediaId);
|
||||||
|
|
||||||
if (!Array.isArray(chapterList)) return [];
|
if (!Array.isArray(chapterList)) return [];
|
||||||
|
|
||||||
const result: Episode[] = chapterList.map(ep => ({
|
const result: Episode[] = chapterList.map(ep => ({
|
||||||
@@ -391,7 +451,8 @@ export async function searchEpisodesInExtension(ext: Extension | null, name: str
|
|||||||
title: ep.title
|
title: ep.title
|
||||||
}));
|
}));
|
||||||
|
|
||||||
await setCache(cacheKey, result, CACHE_TTL_MS);
|
// Cachear tanto el mediaId como los episodios
|
||||||
|
await setCache(cacheKey, { mediaId, episodes: result }, CACHE_TTL_MS);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -402,25 +463,27 @@ export async function searchEpisodesInExtension(ext: Extension | null, name: str
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getStreamData(extension: Extension, episode: string, id: string, source: string, server?: string, category?: string): Promise<StreamData> {
|
export async function getStreamData(extension: Extension, episode: string, id: string, source: string, server?: string, category?: string, extensionAnimeId?: string): Promise<StreamData> {
|
||||||
const providerName = extension.constructor.name;
|
const providerName = extension.constructor.name;
|
||||||
|
|
||||||
const cacheKey = `anime:stream:${providerName}:${id}:${episode}:${server || 'default'}:${category || 'sub'}`;
|
const finalCategory = category ?? "sub";
|
||||||
|
|
||||||
const cached = await getCache(cacheKey);
|
const cacheKey =
|
||||||
|
`anime:stream:${providerName}:${id}:${episode}:${server}:${finalCategory}`;
|
||||||
|
if (!extensionAnimeId) {
|
||||||
|
const cached = await getCache(cacheKey);
|
||||||
|
|
||||||
if (cached) {
|
if (cached) {
|
||||||
const isExpired = Date.now() - cached.created_at > CACHE_TTL_MS;
|
const isExpired = Date.now() - cached.created_at > CACHE_TTL_MS;
|
||||||
|
|
||||||
if (!isExpired) {
|
if (!isExpired) {
|
||||||
console.log(`[${providerName}] Stream data cache hit for episode ${episode}`);
|
console.log(`[${providerName}] Stream data cache hit for episode ${episode}`);
|
||||||
try {
|
try {
|
||||||
return JSON.parse(cached.result) as StreamData;
|
return JSON.parse(cached.result) as StreamData;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(`[${providerName}] Error parsing cached stream data:`, e);
|
console.error(`[${providerName}] Error parsing cached stream data:`, e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
console.log(`[${providerName}] Stream data cache expired for episode ${episode}`);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -428,23 +491,85 @@ export async function getStreamData(extension: Extension, episode: string, id: s
|
|||||||
throw new Error("Extension doesn't support required methods");
|
throw new Error("Extension doesn't support required methods");
|
||||||
}
|
}
|
||||||
let episodes;
|
let episodes;
|
||||||
|
let animeTitle: string | undefined;
|
||||||
|
|
||||||
if (source === "anilist"){
|
if (source === "anilist" && !extensionAnimeId) {
|
||||||
const anime: any = await getAnimeById(id)
|
const anime: any = await getAnimeById(id);
|
||||||
episodes = await searchEpisodesInExtension(extension, extension.constructor.name, anime.title.romaji);
|
episodes = await searchEpisodesInExtension(extension, extension.constructor.name, anime.title.romaji);
|
||||||
|
} else {
|
||||||
|
const targetId = extensionAnimeId ?? id;
|
||||||
|
episodes = await extension.findEpisodes(targetId);
|
||||||
|
|
||||||
|
if (extensionAnimeId) {
|
||||||
|
const anime: any = await getAnimeById(id);
|
||||||
|
animeTitle = anime.title.romaji;
|
||||||
|
|
||||||
|
const episodesCacheKey = `anime:episodes:${providerName}:${animeTitle}`;
|
||||||
|
const episodesResult: Episode[] = episodes.map((ep: any) => ({
|
||||||
|
id: ep.id,
|
||||||
|
number: ep.number,
|
||||||
|
url: ep.url,
|
||||||
|
title: ep.title
|
||||||
|
}));
|
||||||
|
|
||||||
|
await setCache(episodesCacheKey, {
|
||||||
|
mediaId: extensionAnimeId,
|
||||||
|
episodes: episodesResult
|
||||||
|
}, CACHE_TTL_MS);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else{
|
|
||||||
episodes = await extension.findEpisodes(id);
|
const targetEp = episodes.find((e: any) => e.number === parseInt(episode));
|
||||||
}
|
|
||||||
const targetEp = episodes.find(e => e.number === parseInt(episode));
|
|
||||||
|
|
||||||
if (!targetEp) {
|
if (!targetEp) {
|
||||||
throw new Error("Episode not found");
|
throw new Error("Episode not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const serverName = server || "default";
|
const streamData = await extension.findEpisodeServer(targetEp, server, category);
|
||||||
const streamData = await extension.findEpisodeServer(targetEp, serverName);
|
|
||||||
|
|
||||||
await setCache(cacheKey, streamData, CACHE_TTL_MS);
|
await setCache(cacheKey, streamData, CACHE_TTL_MS);
|
||||||
return streamData;
|
return streamData;
|
||||||
|
}
|
||||||
|
|
||||||
|
function similarity(s1: string, s2: string): number {
|
||||||
|
const str1 = normalize(s1);
|
||||||
|
const str2 = normalize(s2);
|
||||||
|
|
||||||
|
const longer = str1.length > str2.length ? str1 : str2;
|
||||||
|
const shorter = str1.length > str2.length ? str2 : str1;
|
||||||
|
|
||||||
|
if (longer.length === 0) return 1.0;
|
||||||
|
|
||||||
|
const editDistance = levenshteinDistance(longer, shorter);
|
||||||
|
return (longer.length - editDistance) / longer.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
function levenshteinDistance(s1: string, s2: string): number {
|
||||||
|
const costs: number[] = [];
|
||||||
|
for (let i = 0; i <= s1.length; i++) {
|
||||||
|
let lastValue = i;
|
||||||
|
for (let j = 0; j <= s2.length; j++) {
|
||||||
|
if (i === 0) {
|
||||||
|
costs[j] = j;
|
||||||
|
} else if (j > 0) {
|
||||||
|
let newValue = costs[j - 1];
|
||||||
|
if (s1.charAt(i - 1) !== s2.charAt(j - 1)) {
|
||||||
|
newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1;
|
||||||
|
}
|
||||||
|
costs[j - 1] = lastValue;
|
||||||
|
lastValue = newValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (i > 0) costs[s2.length] = lastValue;
|
||||||
|
}
|
||||||
|
return costs[s2.length];
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalize(str: string): string {
|
||||||
|
return str
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/'/g, "'") // decodificar entidades HTML
|
||||||
|
.replace(/[^\w\s]/g, ' ') // convertir puntuación a espacios
|
||||||
|
.replace(/\s+/g, ' ') // normalizar espacios
|
||||||
|
.trim();
|
||||||
}
|
}
|
||||||
@@ -87,25 +87,29 @@ export async function getChapters(req: any, reply: FastifyReply) {
|
|||||||
try {
|
try {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const source = req.query.source || 'anilist';
|
const source = req.query.source || 'anilist';
|
||||||
|
const provider = req.query.provider;
|
||||||
|
const extensionBookId = req.query.extensionBookId;
|
||||||
|
|
||||||
const isExternal = source !== 'anilist';
|
const isExternal = source !== 'anilist';
|
||||||
return await booksService.getChaptersForBook(id, isExternal);
|
return await booksService.getChaptersForBook(id, isExternal, provider, extensionBookId);
|
||||||
} catch {
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
return { chapters: [] };
|
return { chapters: [] };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export async function getChapterContent(req: any, reply: FastifyReply) {
|
export async function getChapterContent(req: any, reply: FastifyReply) {
|
||||||
try {
|
try {
|
||||||
const { bookId, chapter, provider } = req.params;
|
const { bookId, chapter, provider } = req.params;
|
||||||
const source = req.query.source || 'anilist';
|
const source = req.query.source || 'anilist';
|
||||||
|
const lang = req.query.lang || 'none';
|
||||||
|
|
||||||
const content = await booksService.getChapterContent(
|
const content = await booksService.getChapterContent(
|
||||||
bookId,
|
bookId,
|
||||||
chapter,
|
chapter,
|
||||||
provider,
|
provider,
|
||||||
source
|
source,
|
||||||
|
lang
|
||||||
);
|
);
|
||||||
|
|
||||||
return reply.send(content);
|
return reply.send(content);
|
||||||
@@ -4,7 +4,6 @@ import { getAllExtensions, getBookExtensionsMap } from '../../shared/extensions'
|
|||||||
import { Book, Extension, ChapterWithProvider, ChapterContent } from '../types';
|
import { Book, Extension, ChapterWithProvider, ChapterContent } from '../types';
|
||||||
|
|
||||||
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
||||||
const TTL = 60 * 60 * 6;
|
|
||||||
const ANILIST_URL = "https://graphql.anilist.co";
|
const ANILIST_URL = "https://graphql.anilist.co";
|
||||||
|
|
||||||
async function fetchAniList(query: string, variables: any) {
|
async function fetchAniList(query: string, variables: any) {
|
||||||
@@ -68,7 +67,19 @@ export async function getBookById(id: string | number): Promise<Book | { error:
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (row) {
|
if (row) {
|
||||||
return JSON.parse(row.full_data);
|
const parsed = JSON.parse(row.full_data);
|
||||||
|
|
||||||
|
const hasRelationImages =
|
||||||
|
parsed?.relations?.edges?.[0]?.node?.coverImage?.large;
|
||||||
|
|
||||||
|
const hasCharacterImages =
|
||||||
|
parsed?.characters?.nodes?.[0]?.image?.large;
|
||||||
|
|
||||||
|
if (hasRelationImages && hasCharacterImages) {
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[Book] Cache outdated for ID ${id}, refetching...`);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -83,8 +94,8 @@ export async function getBookById(id: string | number): Promise<Book | { error:
|
|||||||
trailer { id site thumbnail } updatedAt coverImage { extraLarge large medium color }
|
trailer { id site thumbnail } updatedAt coverImage { extraLarge large medium color }
|
||||||
bannerImage genres synonyms averageScore meanScore popularity isLocked trending favourites
|
bannerImage genres synonyms averageScore meanScore popularity isLocked trending favourites
|
||||||
tags { id name description category rank isGeneralSpoiler isMediaSpoiler isAdult userId }
|
tags { id name description category rank isGeneralSpoiler isMediaSpoiler isAdult userId }
|
||||||
relations { edges { relationType node { id title { romaji } } } }
|
relations { edges { relationType node { id title { romaji } coverImage { large medium } } } }
|
||||||
characters(page: 1, perPage: 10) { nodes { id name { full } } }
|
characters(page: 1, perPage: 10) { nodes { id name { full } image { large medium } } }
|
||||||
studios { nodes { id name isAnimationStudio } }
|
studios { nodes { id name isAnimationStudio } }
|
||||||
isAdult nextAiringEpisode { airingAt timeUntilAiring episode }
|
isAdult nextAiringEpisode { airingAt timeUntilAiring episode }
|
||||||
externalLinks { url site }
|
externalLinks { url site }
|
||||||
@@ -134,25 +145,14 @@ export async function getBookById(id: string | number): Promise<Book | { error:
|
|||||||
return { error: "Book not found" };
|
return { error: "Book not found" };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getTrendingBooks(): Promise<Book[]> {
|
export async function refreshTrendingBooks(): Promise<void> {
|
||||||
const rows = await queryAll(
|
|
||||||
"SELECT full_data, updated_at FROM trending_books ORDER BY rank ASC LIMIT 10"
|
|
||||||
);
|
|
||||||
|
|
||||||
if (rows.length) {
|
|
||||||
const expired = (Date.now() / 1000 - rows[0].updated_at) > TTL;
|
|
||||||
if (!expired) {
|
|
||||||
return rows.map((r: { full_data: string }) => JSON.parse(r.full_data));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const query = `
|
const query = `
|
||||||
query {
|
query {
|
||||||
Page(page: 1, perPage: 10) {
|
Page(page: 1, perPage: 10) {
|
||||||
media(type: MANGA, sort: TRENDING_DESC) { ${MEDIA_FIELDS} }
|
media(type: MANGA, sort: TRENDING_DESC) { ${MEDIA_FIELDS} }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
`;
|
||||||
`;
|
|
||||||
|
|
||||||
const data = await fetchAniList(query, {});
|
const data = await fetchAniList(query, {});
|
||||||
const list = data?.Page?.media || [];
|
const list = data?.Page?.media || [];
|
||||||
@@ -167,30 +167,16 @@ export async function getTrendingBooks(): Promise<Book[]> {
|
|||||||
[rank++, book.id, JSON.stringify(book), now]
|
[rank++, book.id, JSON.stringify(book), now]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return list;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function refreshPopularBooks(): Promise<void> {
|
||||||
export async function getPopularBooks(): Promise<Book[]> {
|
|
||||||
const rows = await queryAll(
|
|
||||||
"SELECT full_data, updated_at FROM popular_books ORDER BY rank ASC LIMIT 10"
|
|
||||||
);
|
|
||||||
|
|
||||||
if (rows.length) {
|
|
||||||
const expired = (Date.now() / 1000 - rows[0].updated_at) > TTL;
|
|
||||||
if (!expired) {
|
|
||||||
return rows.map((r: { full_data: string }) => JSON.parse(r.full_data));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const query = `
|
const query = `
|
||||||
query {
|
query {
|
||||||
Page(page: 1, perPage: 10) {
|
Page(page: 1, perPage: 10) {
|
||||||
media(type: MANGA, sort: POPULARITY_DESC) { ${MEDIA_FIELDS} }
|
media(type: MANGA, sort: POPULARITY_DESC) { ${MEDIA_FIELDS} }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
`;
|
||||||
`;
|
|
||||||
|
|
||||||
const data = await fetchAniList(query, {});
|
const data = await fetchAniList(query, {});
|
||||||
const list = data?.Page?.media || [];
|
const list = data?.Page?.media || [];
|
||||||
@@ -205,10 +191,21 @@ export async function getPopularBooks(): Promise<Book[]> {
|
|||||||
[rank++, book.id, JSON.stringify(book), now]
|
[rank++, book.id, JSON.stringify(book), now]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return list;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getTrendingBooks(): Promise<Book[]> {
|
||||||
|
const rows = await queryAll(
|
||||||
|
"SELECT full_data FROM trending_books ORDER BY rank ASC LIMIT 10"
|
||||||
|
);
|
||||||
|
return rows.map((r: { full_data: string; }) => JSON.parse(r.full_data));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPopularBooks(): Promise<Book[]> {
|
||||||
|
const rows = await queryAll(
|
||||||
|
"SELECT full_data FROM popular_books ORDER BY rank ASC LIMIT 10"
|
||||||
|
);
|
||||||
|
return rows.map((r: { full_data: string; }) => JSON.parse(r.full_data));
|
||||||
|
}
|
||||||
|
|
||||||
export async function searchBooksLocal(query: string): Promise<Book[]> {
|
export async function searchBooksLocal(query: string): Promise<Book[]> {
|
||||||
if (!query || query.length < 2) {
|
if (!query || query.length < 2) {
|
||||||
@@ -329,7 +326,8 @@ export async function searchBooksInExtension(ext: Extension | null, name: string
|
|||||||
averageScore: m.rating || m.score || null,
|
averageScore: m.rating || m.score || null,
|
||||||
format: m.format,
|
format: m.format,
|
||||||
seasonYear: null,
|
seasonYear: null,
|
||||||
isExtensionResult: true
|
isExtensionResult: true,
|
||||||
|
url: m.url,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -364,47 +362,82 @@ async function fetchBookMetadata(id: string): Promise<Book | null> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function searchChaptersInExtension(ext: Extension, name: string, searchTitle: string, search: boolean, origin: string): Promise<ChapterWithProvider[]> {
|
async function searchChaptersInExtension(ext: Extension, name: string, lookupId: string, cacheId: string, search: boolean, origin: string, disableCache = false): Promise<ChapterWithProvider[]> {
|
||||||
const cacheKey = `chapters:${name}:${origin}:${search ? "search" : "id"}:${searchTitle}`;
|
const cacheKey = `chapters:${name}:${origin}:id:${cacheId}`;
|
||||||
const cached = await getCache(cacheKey);
|
if (!disableCache) {
|
||||||
|
const cached = await getCache(cacheKey);
|
||||||
|
|
||||||
if (cached) {
|
if (cached) {
|
||||||
const isExpired = Date.now() - cached.created_at > CACHE_TTL_MS;
|
const isExpired = Date.now() - cached.created_at > CACHE_TTL_MS;
|
||||||
|
|
||||||
if (!isExpired) {
|
|
||||||
console.log(`[${name}] Chapters cache hit for: ${searchTitle}`);
|
|
||||||
try {
|
try {
|
||||||
return JSON.parse(cached.result) as ChapterWithProvider[];
|
const parsed = JSON.parse(cached.result) as {
|
||||||
|
mediaId?: string;
|
||||||
|
chapters: ChapterWithProvider[];
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!isExpired) {
|
||||||
|
console.log(`[${name}] Chapters cache hit for: ${lookupId}`);
|
||||||
|
return parsed.chapters;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parsed.mediaId) {
|
||||||
|
const chaps = await ext.findChapters!(parsed.mediaId);
|
||||||
|
|
||||||
|
const result = chaps.map(ch => ({
|
||||||
|
id: ch.id,
|
||||||
|
number: parseFloat(ch.number.toString()),
|
||||||
|
title: ch.title,
|
||||||
|
date: ch.releaseDate,
|
||||||
|
provider: name,
|
||||||
|
index: ch.index,
|
||||||
|
language: ch.language ?? null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
await setCache(cacheKey, { mediaId: parsed.mediaId, chapters: result }, CACHE_TTL_MS);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(`[${name}] Error parsing cached chapters:`, e);
|
console.error(`[${name}] Error parsing cached chapters:`, e);
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
console.log(`[${name}] Chapters cache expired for: ${searchTitle}`);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log(`[${name}] Searching chapters for: ${searchTitle}`);
|
console.log(`[${name}] Searching chapters for: ${lookupId}`);
|
||||||
|
|
||||||
let mediaId: string;
|
let mediaId: string;
|
||||||
if (search) {
|
if (search) {
|
||||||
const matches = await ext.search!({
|
const matches = await ext.search!({
|
||||||
query: searchTitle,
|
query: lookupId,
|
||||||
media: {
|
media: {
|
||||||
romajiTitle: searchTitle,
|
romajiTitle: lookupId,
|
||||||
englishTitle: searchTitle,
|
englishTitle: lookupId,
|
||||||
startDate: { year: 0, month: 0, day: 0 }
|
startDate: { year: 0, month: 0, day: 0 }
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const best = matches?.[0];
|
if (!matches?.length) return [];
|
||||||
|
|
||||||
if (!best) { return [] }
|
const nq = normalize(lookupId);
|
||||||
|
|
||||||
mediaId = best.id;
|
const scored = matches.map(m => {
|
||||||
|
const nt = normalize(m.title);
|
||||||
|
let score = similarity(nq, nt);
|
||||||
|
|
||||||
|
if (nt === nq || nt.includes(nq)) score += 0.5;
|
||||||
|
|
||||||
|
return { m, score };
|
||||||
|
});
|
||||||
|
|
||||||
|
scored.sort((a, b) => b.score - a.score);
|
||||||
|
|
||||||
|
if (scored[0].score < 0.4) return [];
|
||||||
|
|
||||||
|
mediaId = scored[0].m.id;
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
const match = await ext.getMetadata(searchTitle);
|
const match = await ext.getMetadata(lookupId);
|
||||||
mediaId = match.id;
|
mediaId = match.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -421,10 +454,14 @@ async function searchChaptersInExtension(ext: Extension, name: string, searchTit
|
|||||||
title: ch.title,
|
title: ch.title,
|
||||||
date: ch.releaseDate,
|
date: ch.releaseDate,
|
||||||
provider: name,
|
provider: name,
|
||||||
index: ch.index
|
index: ch.index,
|
||||||
|
language: ch.language ?? null,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
await setCache(cacheKey, result, CACHE_TTL_MS);
|
await setCache(cacheKey, {
|
||||||
|
mediaId,
|
||||||
|
chapters: result
|
||||||
|
}, CACHE_TTL_MS);
|
||||||
return result;
|
return result;
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -434,7 +471,7 @@ async function searchChaptersInExtension(ext: Extension, name: string, searchTit
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getChaptersForBook(id: string, ext: Boolean, onlyProvider?: string): Promise<{ chapters: ChapterWithProvider[] }> {
|
export async function getChaptersForBook(id: string, ext: Boolean, onlyProvider?: string, extensionBookId?: string): Promise<{ chapters: ChapterWithProvider[] }> {
|
||||||
let bookData: Book | null = null;
|
let bookData: Book | null = null;
|
||||||
let searchTitle: string = "";
|
let searchTitle: string = "";
|
||||||
|
|
||||||
@@ -464,11 +501,30 @@ export async function getChaptersForBook(id: string, ext: Boolean, onlyProvider?
|
|||||||
|
|
||||||
for (const [name, ext] of bookExtensions) {
|
for (const [name, ext] of bookExtensions) {
|
||||||
if (onlyProvider && name !== onlyProvider) continue;
|
if (onlyProvider && name !== onlyProvider) continue;
|
||||||
if (name == extension) {
|
if (extensionBookId && name === onlyProvider) {
|
||||||
const chapters = await searchChaptersInExtension(ext, name, id, false, exts);
|
const targetId = extensionBookId ?? id;
|
||||||
|
|
||||||
|
const chapters = await searchChaptersInExtension(
|
||||||
|
ext,
|
||||||
|
name,
|
||||||
|
targetId, // lookup
|
||||||
|
id, // cache siempre con el id normal
|
||||||
|
false,
|
||||||
|
exts,
|
||||||
|
Boolean(extensionBookId)
|
||||||
|
);
|
||||||
|
|
||||||
allChapters.push(...chapters);
|
allChapters.push(...chapters);
|
||||||
} else {
|
} else {
|
||||||
const chapters = await searchChaptersInExtension(ext, name, searchTitle, true, exts);
|
const chapters = await searchChaptersInExtension(
|
||||||
|
ext,
|
||||||
|
name,
|
||||||
|
searchTitle,
|
||||||
|
id, // cache con id normal
|
||||||
|
true,
|
||||||
|
exts
|
||||||
|
);
|
||||||
|
|
||||||
allChapters.push(...chapters);
|
allChapters.push(...chapters);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -478,7 +534,7 @@ export async function getChaptersForBook(id: string, ext: Boolean, onlyProvider?
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getChapterContent(bookId: string, chapterIndex: string, providerName: string, source: string): Promise<ChapterContent> {
|
export async function getChapterContent(bookId: string, chapterId: string, providerName: string, source: string, lang: string): Promise<ChapterContent> {
|
||||||
const extensions = getAllExtensions();
|
const extensions = getAllExtensions();
|
||||||
const ext = extensions.get(providerName);
|
const ext = extensions.get(providerName);
|
||||||
|
|
||||||
@@ -486,14 +542,14 @@ export async function getChapterContent(bookId: string, chapterIndex: string, pr
|
|||||||
throw new Error("Provider not found");
|
throw new Error("Provider not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const contentCacheKey = `content:${providerName}:${source}:${bookId}:${chapterIndex}`;
|
const contentCacheKey = `content:${providerName}:${source}:${lang}:${bookId}:${chapterId}`;
|
||||||
const cachedContent = await getCache(contentCacheKey);
|
const cachedContent = await getCache(contentCacheKey);
|
||||||
|
|
||||||
if (cachedContent) {
|
if (cachedContent) {
|
||||||
const isExpired = Date.now() - cachedContent.created_at > CACHE_TTL_MS;
|
const isExpired = Date.now() - cachedContent.created_at > CACHE_TTL_MS;
|
||||||
|
|
||||||
if (!isExpired) {
|
if (!isExpired) {
|
||||||
console.log(`[${providerName}] Content cache hit for Book ID ${bookId}, Index ${chapterIndex}`);
|
console.log(`[${providerName}] Content cache hit for Book ID ${bookId}, Index ${chapterId}`);
|
||||||
try {
|
try {
|
||||||
return JSON.parse(cachedContent.result) as ChapterContent;
|
return JSON.parse(cachedContent.result) as ChapterContent;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -501,33 +557,14 @@ export async function getChapterContent(bookId: string, chapterIndex: string, pr
|
|||||||
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
console.log(`[${providerName}] Content cache expired for Book ID ${bookId}, Index ${chapterIndex}`);
|
console.log(`[${providerName}] Content cache expired for Book ID ${bookId}, Index ${chapterId}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const isExternal = source !== 'anilist';
|
const selectedChapter: any = {
|
||||||
const chapterList = await getChaptersForBook(bookId, isExternal, providerName);
|
id: chapterId,
|
||||||
|
provider: providerName
|
||||||
if (!chapterList?.chapters || chapterList.chapters.length === 0) {
|
};
|
||||||
throw new Error("Chapters not found");
|
|
||||||
}
|
|
||||||
|
|
||||||
const providerChapters = chapterList.chapters.filter(c => c.provider === providerName);
|
|
||||||
const index = parseInt(chapterIndex, 10);
|
|
||||||
|
|
||||||
if (Number.isNaN(index)) {
|
|
||||||
throw new Error("Invalid chapter index");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!providerChapters[index]) {
|
|
||||||
throw new Error("Chapter index out of range");
|
|
||||||
}
|
|
||||||
|
|
||||||
const selectedChapter = providerChapters[index];
|
|
||||||
|
|
||||||
const chapterId = selectedChapter.id;
|
|
||||||
const chapterTitle = selectedChapter.title || null;
|
|
||||||
const chapterNumber = typeof selectedChapter.number === 'number' ? selectedChapter.number : index;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!ext.findChapterPages) {
|
if (!ext.findChapterPages) {
|
||||||
@@ -537,12 +574,13 @@ export async function getChapterContent(bookId: string, chapterIndex: string, pr
|
|||||||
let contentResult: ChapterContent;
|
let contentResult: ChapterContent;
|
||||||
|
|
||||||
if (ext.mediaType === "manga") {
|
if (ext.mediaType === "manga") {
|
||||||
|
// Usamos el ID directamente
|
||||||
const pages = await ext.findChapterPages(chapterId);
|
const pages = await ext.findChapterPages(chapterId);
|
||||||
contentResult = {
|
contentResult = {
|
||||||
type: "manga",
|
type: "manga",
|
||||||
chapterId,
|
chapterId: selectedChapter.id,
|
||||||
title: chapterTitle,
|
title: selectedChapter.title,
|
||||||
number: chapterNumber,
|
number: selectedChapter.number,
|
||||||
provider: providerName,
|
provider: providerName,
|
||||||
pages
|
pages
|
||||||
};
|
};
|
||||||
@@ -550,9 +588,9 @@ export async function getChapterContent(bookId: string, chapterIndex: string, pr
|
|||||||
const content = await ext.findChapterPages(chapterId);
|
const content = await ext.findChapterPages(chapterId);
|
||||||
contentResult = {
|
contentResult = {
|
||||||
type: "ln",
|
type: "ln",
|
||||||
chapterId,
|
chapterId: selectedChapter.id,
|
||||||
title: chapterTitle,
|
title: selectedChapter.title,
|
||||||
number: chapterNumber,
|
number: selectedChapter.number,
|
||||||
provider: providerName,
|
provider: providerName,
|
||||||
content
|
content
|
||||||
};
|
};
|
||||||
@@ -561,7 +599,6 @@ export async function getChapterContent(bookId: string, chapterIndex: string, pr
|
|||||||
}
|
}
|
||||||
|
|
||||||
await setCache(contentCacheKey, contentResult, CACHE_TTL_MS);
|
await setCache(contentCacheKey, contentResult, CACHE_TTL_MS);
|
||||||
|
|
||||||
return contentResult;
|
return contentResult;
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -569,4 +606,47 @@ export async function getChapterContent(bookId: string, chapterIndex: string, pr
|
|||||||
console.error(`[Chapter] Error loading from ${providerName}:`, error.message);
|
console.error(`[Chapter] Error loading from ${providerName}:`, error.message);
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function similarity(s1: string, s2: string): number {
|
||||||
|
const str1 = normalize(s1);
|
||||||
|
const str2 = normalize(s2);
|
||||||
|
|
||||||
|
const longer = str1.length > str2.length ? str1 : str2;
|
||||||
|
const shorter = str1.length > str2.length ? str2 : str1;
|
||||||
|
|
||||||
|
if (longer.length === 0) return 1.0;
|
||||||
|
|
||||||
|
const editDistance = levenshteinDistance(longer, shorter);
|
||||||
|
return (longer.length - editDistance) / longer.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
function levenshteinDistance(s1: string, s2: string): number {
|
||||||
|
const costs: number[] = [];
|
||||||
|
for (let i = 0; i <= s1.length; i++) {
|
||||||
|
let lastValue = i;
|
||||||
|
for (let j = 0; j <= s2.length; j++) {
|
||||||
|
if (i === 0) {
|
||||||
|
costs[j] = j;
|
||||||
|
} else if (j > 0) {
|
||||||
|
let newValue = costs[j - 1];
|
||||||
|
if (s1.charAt(i - 1) !== s2.charAt(j - 1)) {
|
||||||
|
newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1;
|
||||||
|
}
|
||||||
|
costs[j - 1] = lastValue;
|
||||||
|
lastValue = newValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (i > 0) costs[s2.length] = lastValue;
|
||||||
|
}
|
||||||
|
return costs[s2.length];
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalize(str: string): string {
|
||||||
|
return str
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/'/g, "'") // decodificar entidades HTML
|
||||||
|
.replace(/[^\w\s]/g, ' ') // convertir puntuación a espacios
|
||||||
|
.replace(/\s+/g, ' ') // normalizar espacios
|
||||||
|
.trim();
|
||||||
}
|
}
|
||||||
59
desktop/src/api/config/config.controller.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import { FastifyReply, FastifyRequest } from 'fastify';
|
||||||
|
import { getConfig, setConfig } from '../../shared/config';
|
||||||
|
|
||||||
|
function hideSecrets(values: any) {
|
||||||
|
const copy = structuredClone(values);
|
||||||
|
if (copy.server?.jwt_secret) delete copy.server.jwt_secret;
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getFullConfig(req: FastifyRequest, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const { values, schema } = getConfig();
|
||||||
|
return { values: hideSecrets(values), schema };
|
||||||
|
} catch {
|
||||||
|
return { error: "Error loading config" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getConfigSection(
|
||||||
|
req: FastifyRequest<{ Params: { section: string } }>,
|
||||||
|
reply: FastifyReply
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { section } = req.params;
|
||||||
|
const { values } = getConfig();
|
||||||
|
|
||||||
|
if (values[section] === undefined) {
|
||||||
|
return { error: "Section not found" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { [section]: hideSecrets(values)[section] };
|
||||||
|
} catch {
|
||||||
|
return { error: "Error loading config section" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateConfig(
|
||||||
|
req: FastifyRequest<{ Body: any }>,
|
||||||
|
reply: FastifyReply
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
return setConfig(req.body); // schema nunca se toca
|
||||||
|
} catch {
|
||||||
|
return { error: "Error updating config" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateConfigSection(
|
||||||
|
req: FastifyRequest<{ Params: { section: string }, Body: any }>,
|
||||||
|
reply: FastifyReply
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { section } = req.params;
|
||||||
|
const updatedValues = setConfig({ [section]: req.body });
|
||||||
|
return { [section]: updatedValues[section] };
|
||||||
|
} catch {
|
||||||
|
return { error: "Error updating config section" };
|
||||||
|
}
|
||||||
|
}
|
||||||
11
desktop/src/api/config/config.routes.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { FastifyInstance } from 'fastify';
|
||||||
|
import * as controller from './config.controller';
|
||||||
|
|
||||||
|
async function configRoutes(fastify: FastifyInstance) {
|
||||||
|
fastify.get('/config', controller.getFullConfig);
|
||||||
|
fastify.get('/config/:section', controller.getConfigSection);
|
||||||
|
fastify.post('/config', controller.updateConfig);
|
||||||
|
fastify.post('/config/:section', controller.updateConfigSection);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default configRoutes;
|
||||||
155
desktop/src/api/extensions/extensions.controller.ts
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
import { FastifyReply, FastifyRequest } from 'fastify';
|
||||||
|
import { getExtension, getExtensionsList, getGalleryExtensionsMap, getBookExtensionsMap, getMangaExtensionsMap, getNovelExtensionsMap, getAnimeExtensionsMap, saveExtensionFile, deleteExtensionFile } from '../../shared/extensions';
|
||||||
|
import { ExtensionNameRequest } from '../types';
|
||||||
|
|
||||||
|
const TYPE_MAP: Record<string, string> = {
|
||||||
|
'anime-board': 'anime',
|
||||||
|
'image-board': 'image',
|
||||||
|
'book-board': 'book',
|
||||||
|
};
|
||||||
|
|
||||||
|
function extractProp(source: string, prop: string): string | null {
|
||||||
|
const m = source.match(new RegExp(`this\\.${prop}\\s*=\\s*["']([^"']+)["']`));
|
||||||
|
return m ? m[1] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNewer(remote: string, local?: string | null) {
|
||||||
|
if (!local) return true;
|
||||||
|
return remote !== local;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateExtensions(req: any, reply: FastifyReply) {
|
||||||
|
const updated: string[] = [];
|
||||||
|
|
||||||
|
for (const name of getExtensionsList()) {
|
||||||
|
const ext = getExtension(name);
|
||||||
|
if (!ext) continue;
|
||||||
|
|
||||||
|
const type = ext.type;
|
||||||
|
if (!TYPE_MAP[type]) continue;
|
||||||
|
|
||||||
|
const fileName = ext.__fileName;
|
||||||
|
const remoteUrl = `https://git.waifuboard.app/ItsSkaiya/WaifuBoard-Extensions/raw/branch/main/${TYPE_MAP[type]}/${fileName}`;
|
||||||
|
|
||||||
|
let remoteSrc: string;
|
||||||
|
try {
|
||||||
|
const res = await fetch(remoteUrl);
|
||||||
|
if (!res.ok) continue;
|
||||||
|
remoteSrc = await res.text();
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const remoteVersion = extractProp(remoteSrc, 'version');
|
||||||
|
const localVersion = ext.version ?? null;
|
||||||
|
if (!remoteVersion) continue;
|
||||||
|
|
||||||
|
if (isNewer(remoteVersion, localVersion)) {
|
||||||
|
await saveExtensionFile(fileName, remoteUrl);
|
||||||
|
updated.push(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { updated };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getExtensions(req: FastifyRequest, reply: FastifyReply) {
|
||||||
|
return { extensions: getExtensionsList() };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAnimeExtensions(req: FastifyRequest, reply: FastifyReply) {
|
||||||
|
const animeExtensions = getAnimeExtensionsMap();
|
||||||
|
return { extensions: Array.from(animeExtensions.keys()) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getBookExtensions(req: FastifyRequest, reply: FastifyReply) {
|
||||||
|
const bookExtensions = getBookExtensionsMap();
|
||||||
|
return { extensions: Array.from(bookExtensions.keys()) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getMangaExtensions(req: FastifyRequest, reply: FastifyReply) {
|
||||||
|
const bookExtensions = getMangaExtensionsMap();
|
||||||
|
return { extensions: Array.from(bookExtensions.keys()) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getNovelExtensions(req: FastifyRequest, reply: FastifyReply) {
|
||||||
|
const bookExtensions = getNovelExtensionsMap();
|
||||||
|
return { extensions: Array.from(bookExtensions.keys()) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getGalleryExtensions(req: FastifyRequest, reply: FastifyReply) {
|
||||||
|
const galleryExtensions = getGalleryExtensionsMap();
|
||||||
|
return { extensions: Array.from(galleryExtensions.keys()) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getExtensionSettings(req: ExtensionNameRequest, reply: FastifyReply) {
|
||||||
|
const { name } = req.params;
|
||||||
|
const ext = getExtension(name);
|
||||||
|
|
||||||
|
if (!ext) {
|
||||||
|
return { error: "Extension not found" };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ext.getSettings) {
|
||||||
|
return { episodeServers: ["default"], supportsDub: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
return ext.getSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function installExtension(req: any, reply: FastifyReply) {
|
||||||
|
const { url } = req.body;
|
||||||
|
|
||||||
|
if (!url || typeof url !== 'string' || !url.endsWith('.js')) {
|
||||||
|
return reply.code(400).send({ error: "Invalid extension URL provided" });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const fileName = url.split('/').pop();
|
||||||
|
|
||||||
|
if (!fileName) {
|
||||||
|
return reply.code(400).send({ error: "Could not determine file name from URL" });
|
||||||
|
}
|
||||||
|
|
||||||
|
await saveExtensionFile(fileName, url);
|
||||||
|
|
||||||
|
req.server.log.info(`Extension installed: ${fileName}`);
|
||||||
|
return reply.code(200).send({
|
||||||
|
success: true,
|
||||||
|
message: `Extension ${fileName} installed successfully.`,
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
req.server.log.error(`Failed to install extension from ${url}:`, error);
|
||||||
|
return reply.code(500).send({
|
||||||
|
success: false,
|
||||||
|
error: "Failed to install extension.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function uninstallExtension(req: any, reply: FastifyReply) {
|
||||||
|
const { fileName } = req.body;
|
||||||
|
|
||||||
|
if (!fileName || !fileName.endsWith('.js')) {
|
||||||
|
return reply.code(400).send({ error: "Invalid extension fileName provided" });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
|
await deleteExtensionFile(fileName);
|
||||||
|
|
||||||
|
req.server.log.info(`Extension uninstalled: ${fileName}`);
|
||||||
|
return reply.code(200).send({ success: true, message: `Extension ${fileName} uninstalled successfully.` });
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
if (error.code === 'ENOENT') {
|
||||||
|
return reply.code(200).send({ success: true, message: `Extension ${fileName} already uninstalled (file not found).` });
|
||||||
|
}
|
||||||
|
|
||||||
|
req.server.log.error(`Failed to uninstall extension ${fileName}:`, error);
|
||||||
|
return reply.code(500).send({ success: false, error: `Failed to uninstall extension ${fileName}.` });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,10 @@ import * as controller from './extensions.controller';
|
|||||||
async function extensionsRoutes(fastify: FastifyInstance) {
|
async function extensionsRoutes(fastify: FastifyInstance) {
|
||||||
fastify.get('/extensions', controller.getExtensions);
|
fastify.get('/extensions', controller.getExtensions);
|
||||||
fastify.get('/extensions/anime', controller.getAnimeExtensions);
|
fastify.get('/extensions/anime', controller.getAnimeExtensions);
|
||||||
|
fastify.post('/extensions/update', controller.updateExtensions);
|
||||||
fastify.get('/extensions/book', controller.getBookExtensions);
|
fastify.get('/extensions/book', controller.getBookExtensions);
|
||||||
|
fastify.get('/extensions/manga', controller.getMangaExtensions);
|
||||||
|
fastify.get('/extensions/novel', controller.getNovelExtensions);
|
||||||
fastify.get('/extensions/gallery', controller.getGalleryExtensions);
|
fastify.get('/extensions/gallery', controller.getGalleryExtensions);
|
||||||
fastify.get('/extensions/:name/settings', controller.getExtensionSettings);
|
fastify.get('/extensions/:name/settings', controller.getExtensionSettings);
|
||||||
fastify.post('/extensions/install', controller.installExtension);
|
fastify.post('/extensions/install', controller.installExtension);
|
||||||
565
desktop/src/api/local/download.service.ts
Normal file
@@ -0,0 +1,565 @@
|
|||||||
|
import { getConfig as loadConfig } from '../../shared/config';
|
||||||
|
import { queryOne, queryAll, run } from '../../shared/database';
|
||||||
|
import { getAnimeById } from '../anime/anime.service';
|
||||||
|
import { getBookById } from '../books/books.service';
|
||||||
|
import crypto from 'crypto';
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import AdmZip from 'adm-zip';
|
||||||
|
import { spawn } from 'child_process';
|
||||||
|
const { values } = loadConfig();
|
||||||
|
|
||||||
|
const FFMPEG_PATH = values.paths?.ffmpeg || 'ffmpeg';
|
||||||
|
|
||||||
|
type DownloadStatus = {
|
||||||
|
id: string;
|
||||||
|
type: 'anime' | 'manga' | 'novel';
|
||||||
|
anilistId: number;
|
||||||
|
unitNumber: number;
|
||||||
|
status: 'pending' | 'downloading' | 'completed' | 'failed';
|
||||||
|
progress: number;
|
||||||
|
speed?: string;
|
||||||
|
timeElapsed?: string;
|
||||||
|
error?: string;
|
||||||
|
startedAt: number;
|
||||||
|
completedAt?: number;
|
||||||
|
folderName?: string;
|
||||||
|
fileName?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const activeDownloads = new Map<string, DownloadStatus>();
|
||||||
|
|
||||||
|
export function getActiveDownloads(): DownloadStatus[] {
|
||||||
|
return Array.from(activeDownloads.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDownloadById(id: string): DownloadStatus | undefined {
|
||||||
|
return activeDownloads.get(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateDownloadProgress(id: string, updates: Partial<DownloadStatus>) {
|
||||||
|
const current = activeDownloads.get(id);
|
||||||
|
if (current) {
|
||||||
|
activeDownloads.set(id, { ...current, ...updates });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type AnimeDownloadParams = {
|
||||||
|
anilistId: number;
|
||||||
|
episodeNumber: number;
|
||||||
|
streamUrl: string;
|
||||||
|
headers?: Record<string, string>;
|
||||||
|
quality?: string;
|
||||||
|
subtitles?: Array<{ language: string; url: string }>;
|
||||||
|
chapters?: Array<{ title: string; start_time: number; end_time: number }>;
|
||||||
|
totalDuration?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type BookDownloadParams = {
|
||||||
|
anilistId: number;
|
||||||
|
chapterNumber: number;
|
||||||
|
format: 'manga' | 'novel';
|
||||||
|
content?: string;
|
||||||
|
images?: Array<{ index: number; url: string }>;
|
||||||
|
};
|
||||||
|
|
||||||
|
async function ensureDirectory(dirPath: string) {
|
||||||
|
if (!fs.existsSync(dirPath)) {
|
||||||
|
fs.mkdirSync(dirPath, { recursive: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadFile(url: string, outputPath: string): Promise<void> {
|
||||||
|
const res = await fetch(url);
|
||||||
|
if (!res.ok) throw new Error(`HTTP_${res.status}`);
|
||||||
|
|
||||||
|
await ensureDirectory(path.dirname(outputPath));
|
||||||
|
const buf = Buffer.from(await res.arrayBuffer());
|
||||||
|
fs.writeFileSync(outputPath, buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getOrCreateEntry(
|
||||||
|
anilistId: number,
|
||||||
|
type: 'anime' | 'manga' | 'novels'
|
||||||
|
): Promise<{ id: string; path: string; folderName: string }> {
|
||||||
|
const existing = await queryOne(
|
||||||
|
`SELECT id, path, folder_name FROM local_entries
|
||||||
|
WHERE matched_id = ? AND matched_source = 'anilist' AND type = ?`,
|
||||||
|
[anilistId, type],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
return {
|
||||||
|
id: existing.id,
|
||||||
|
path: existing.path,
|
||||||
|
folderName: existing.folder_name
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const metadata: any = type === 'anime'
|
||||||
|
? await getAnimeById(anilistId)
|
||||||
|
: await getBookById(anilistId);
|
||||||
|
|
||||||
|
if (!metadata) {
|
||||||
|
throw new Error('METADATA_NOT_FOUND');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { values } = loadConfig();
|
||||||
|
const basePath = values.library?.[type];
|
||||||
|
|
||||||
|
if (!basePath) {
|
||||||
|
throw new Error(`NO_LIBRARY_PATH_FOR_${type.toUpperCase()}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const title = metadata.title?.romaji || metadata.title?.english || `ID_${anilistId}`;
|
||||||
|
const safeName = title.replace(/[<>:"/\\|?*]/g, '_');
|
||||||
|
const folderPath = path.join(basePath, safeName);
|
||||||
|
|
||||||
|
await ensureDirectory(folderPath);
|
||||||
|
|
||||||
|
const entryId = crypto
|
||||||
|
.createHash('sha1')
|
||||||
|
.update(`anilist:${type}:${anilistId}`)
|
||||||
|
.digest('hex');
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
await run(
|
||||||
|
`INSERT OR IGNORE INTO local_entries
|
||||||
|
(id, type, path, folder_name, matched_id, matched_source, last_scan)
|
||||||
|
VALUES (?, ?, ?, ?, ?, 'anilist', ?)`,
|
||||||
|
[entryId, type, folderPath, safeName, anilistId, now],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: entryId,
|
||||||
|
path: folderPath,
|
||||||
|
folderName: safeName
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function downloadAnimeEpisode(params: AnimeDownloadParams) {
|
||||||
|
const { anilistId, episodeNumber, streamUrl, subtitles, chapters, totalDuration } = params;
|
||||||
|
|
||||||
|
const entry: any = await getOrCreateEntry(anilistId, 'anime');
|
||||||
|
const fileName = `Episode_${episodeNumber.toString().padStart(2, '0')}.mkv`;
|
||||||
|
|
||||||
|
const downloadId = crypto.randomUUID();
|
||||||
|
activeDownloads.set(downloadId, {
|
||||||
|
id: downloadId,
|
||||||
|
type: 'anime',
|
||||||
|
anilistId,
|
||||||
|
unitNumber: episodeNumber,
|
||||||
|
status: 'pending',
|
||||||
|
progress: 0,
|
||||||
|
startedAt: Date.now(),
|
||||||
|
folderName: entry.folderName,
|
||||||
|
fileName: fileName
|
||||||
|
});
|
||||||
|
|
||||||
|
const exists = await queryOne(
|
||||||
|
`SELECT id FROM local_files WHERE entry_id = ? AND unit_number = ?`,
|
||||||
|
[entry.id, episodeNumber],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (exists) {
|
||||||
|
activeDownloads.delete(downloadId);
|
||||||
|
return { status: 'ALREADY_EXISTS', entry_id: entry.id, episode: episodeNumber };
|
||||||
|
}
|
||||||
|
|
||||||
|
const outputPath = path.join(entry.path, `Episode_${episodeNumber.toString().padStart(2, '0')}.mkv`);
|
||||||
|
const tempDir = path.join(entry.path, '.temp');
|
||||||
|
await ensureDirectory(tempDir);
|
||||||
|
|
||||||
|
try {
|
||||||
|
updateDownloadProgress(downloadId, { status: 'downloading' });
|
||||||
|
|
||||||
|
let videoInput = streamUrl;
|
||||||
|
let audioInputs: string[] = [];
|
||||||
|
|
||||||
|
const isMaster = (params as any).is_master === true;
|
||||||
|
|
||||||
|
if (isMaster) {
|
||||||
|
const variant = (params as any).variant;
|
||||||
|
const audios = (params as any).audio;
|
||||||
|
|
||||||
|
if (!variant || !variant.playlist_url) {
|
||||||
|
throw new Error('VARIANT_REQUIRED_FOR_MASTER');
|
||||||
|
}
|
||||||
|
|
||||||
|
videoInput = variant.playlist_url;
|
||||||
|
|
||||||
|
if (audios && audios.length > 0) {
|
||||||
|
audioInputs = audios.map((a: any) => a.playlist_url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const subFiles: string[] = [];
|
||||||
|
if (subtitles?.length) {
|
||||||
|
for (let i = 0; i < subtitles.length; i++) {
|
||||||
|
const ext = subtitles[i].url.endsWith('.vtt') ? 'vtt' : 'srt';
|
||||||
|
const p = path.join(tempDir, `sub_${i}.${ext}`);
|
||||||
|
await downloadFile(subtitles[i].url, p);
|
||||||
|
subFiles.push(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const args = [
|
||||||
|
'-protocol_whitelist', 'file,http,https,tcp,tls,crypto',
|
||||||
|
'-allowed_extensions', 'ALL',
|
||||||
|
'-f', 'hls',
|
||||||
|
'-extension_picky', '0',
|
||||||
|
'-i', videoInput
|
||||||
|
];
|
||||||
|
|
||||||
|
audioInputs.forEach(audioUrl => {
|
||||||
|
args.push(
|
||||||
|
'-protocol_whitelist', 'file,http,https,tcp,tls,crypto',
|
||||||
|
'-allowed_extensions', 'ALL',
|
||||||
|
'-f', 'hls',
|
||||||
|
'-extension_picky', '0',
|
||||||
|
'-i', audioUrl
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
subFiles.forEach(f => args.push('-i', f));
|
||||||
|
|
||||||
|
let chaptersInputIndex = -1;
|
||||||
|
|
||||||
|
if (chapters?.length) {
|
||||||
|
const meta = path.join(tempDir, 'chapters.txt');
|
||||||
|
const sorted = [...chapters].sort((a, b) => a.start_time - b.start_time);
|
||||||
|
const lines: string[] = [';FFMETADATA1'];
|
||||||
|
|
||||||
|
for (let i = 0; i < sorted.length; i++) {
|
||||||
|
const c = sorted[i];
|
||||||
|
const start = Math.floor(c.start_time * 1000);
|
||||||
|
const end = Math.floor(c.end_time * 1000);
|
||||||
|
const title = (c.title || 'chapter').toUpperCase();
|
||||||
|
|
||||||
|
lines.push(
|
||||||
|
'[CHAPTER]',
|
||||||
|
'TIMEBASE=1/1000',
|
||||||
|
`START=${start}`,
|
||||||
|
`END=${end}`,
|
||||||
|
`title=${title}`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (i < sorted.length - 1) {
|
||||||
|
const nextStart = Math.floor(sorted[i + 1].start_time * 1000);
|
||||||
|
if (nextStart - end > 1000) {
|
||||||
|
lines.push(
|
||||||
|
'[CHAPTER]',
|
||||||
|
'TIMEBASE=1/1000',
|
||||||
|
`START=${end}`,
|
||||||
|
`END=${nextStart}`,
|
||||||
|
'title=Episode'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
lines.push(
|
||||||
|
'[CHAPTER]',
|
||||||
|
'TIMEBASE=1/1000',
|
||||||
|
`START=${end}`,
|
||||||
|
'title=Episode'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.writeFileSync(meta, lines.join('\n'));
|
||||||
|
args.push('-i', meta);
|
||||||
|
chaptersInputIndex = 1 + audioInputs.length + subFiles.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
args.push('-map', '0:v:0');
|
||||||
|
|
||||||
|
if (audioInputs.length > 0) {
|
||||||
|
audioInputs.forEach((_, i) => {
|
||||||
|
args.push('-map', `${i + 1}:a:0`);
|
||||||
|
const audioInfo = (params as any).audio?.[i];
|
||||||
|
if (audioInfo) {
|
||||||
|
const audioStreamIndex = i;
|
||||||
|
if (audioInfo.language) {
|
||||||
|
args.push(`-metadata:s:a:${audioStreamIndex}`, `language=${audioInfo.language}`);
|
||||||
|
}
|
||||||
|
if (audioInfo.name) {
|
||||||
|
args.push(`-metadata:s:a:${audioStreamIndex}`, `title=${audioInfo.name}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
args.push('-map', '0:a:0?');
|
||||||
|
}
|
||||||
|
|
||||||
|
const subtitleStartIndex = 1 + audioInputs.length;
|
||||||
|
subFiles.forEach((_, i) => {
|
||||||
|
args.push('-map', `${subtitleStartIndex + i}:0`);
|
||||||
|
args.push(`-metadata:s:s:${i}`, `language=${subtitles![i].language}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (chaptersInputIndex >= 0) {
|
||||||
|
args.push('-map_metadata', `${chaptersInputIndex}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
args.push('-c:v', 'copy', '-c:a', 'copy');
|
||||||
|
if (subFiles.length) args.push('-c:s', 'srt');
|
||||||
|
args.push('-y', outputPath);
|
||||||
|
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
const ff = spawn(FFMPEG_PATH, args, {
|
||||||
|
windowsHide: true,
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe']
|
||||||
|
});
|
||||||
|
|
||||||
|
ff.stderr.on('data', (data) => {
|
||||||
|
const text = data.toString();
|
||||||
|
const timeMatch = text.match(/time=(\S+)/);
|
||||||
|
const speedMatch = text.match(/speed=(\S+)/);
|
||||||
|
|
||||||
|
if (timeMatch || speedMatch) {
|
||||||
|
const updates: any = {};
|
||||||
|
|
||||||
|
if (timeMatch) updates.timeElapsed = timeMatch[1];
|
||||||
|
if (speedMatch) updates.speed = speedMatch[1];
|
||||||
|
|
||||||
|
if (timeMatch && totalDuration && totalDuration > 0) {
|
||||||
|
const elapsedSeconds = parseFFmpegTime(timeMatch[1]);
|
||||||
|
updates.progress = Math.min(
|
||||||
|
99,
|
||||||
|
Math.round((elapsedSeconds / totalDuration) * 100)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
updateDownloadProgress(downloadId, updates);
|
||||||
|
}
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
ff.on('error', (error) => reject(error));
|
||||||
|
ff.on('close', (code) => {
|
||||||
|
if (code === 0) resolve(true);
|
||||||
|
else reject(new Error(`FFmpeg exited with code ${code}`));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
|
||||||
|
const fileId = crypto.randomUUID();
|
||||||
|
await run(
|
||||||
|
`INSERT INTO local_files (id, entry_id, file_path, unit_number)
|
||||||
|
VALUES (?, ?, ?, ?)`,
|
||||||
|
[fileId, entry.id, outputPath, episodeNumber],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
await run(
|
||||||
|
`UPDATE local_entries SET last_scan = ? WHERE id = ?`,
|
||||||
|
[Date.now(), entry.id],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
updateDownloadProgress(downloadId, {
|
||||||
|
status: 'completed',
|
||||||
|
progress: 100,
|
||||||
|
completedAt: Date.now()
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(() => activeDownloads.delete(downloadId), 30000);
|
||||||
|
|
||||||
|
return {
|
||||||
|
status: 'SUCCESS',
|
||||||
|
download_id: downloadId,
|
||||||
|
entry_id: entry.id,
|
||||||
|
file_id: fileId,
|
||||||
|
episode: episodeNumber,
|
||||||
|
path: outputPath
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (e: any) {
|
||||||
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath);
|
||||||
|
|
||||||
|
updateDownloadProgress(downloadId, {
|
||||||
|
status: 'failed',
|
||||||
|
error: e.message
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(() => activeDownloads.delete(downloadId), 60000);
|
||||||
|
|
||||||
|
const err = new Error('DOWNLOAD_FAILED');
|
||||||
|
(err as any).details = e.message;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function downloadBookChapter(params: BookDownloadParams) {
|
||||||
|
const { anilistId, chapterNumber, format, content, images } = params;
|
||||||
|
|
||||||
|
const type = format === 'manga' ? 'manga' : 'novels';
|
||||||
|
const entry = await getOrCreateEntry(anilistId, type);
|
||||||
|
|
||||||
|
const ext = format === 'manga' ? 'cbz' : 'epub';
|
||||||
|
const fileName = `Chapter_${chapterNumber.toString().padStart(3, '0')}.${ext}`;
|
||||||
|
|
||||||
|
const downloadId = crypto.randomUUID();
|
||||||
|
|
||||||
|
activeDownloads.set(downloadId, {
|
||||||
|
id: downloadId,
|
||||||
|
type: format === 'manga' ? 'manga' : 'novel',
|
||||||
|
anilistId,
|
||||||
|
unitNumber: chapterNumber,
|
||||||
|
status: 'pending',
|
||||||
|
progress: 0,
|
||||||
|
startedAt: Date.now(),
|
||||||
|
folderName: entry.folderName,
|
||||||
|
fileName: fileName
|
||||||
|
});
|
||||||
|
|
||||||
|
const existingFile = await queryOne(
|
||||||
|
`SELECT id FROM local_files WHERE entry_id = ? AND unit_number = ?`,
|
||||||
|
[entry.id, chapterNumber],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (existingFile) {
|
||||||
|
activeDownloads.delete(downloadId);
|
||||||
|
return {
|
||||||
|
status: 'ALREADY_EXISTS',
|
||||||
|
message: `Chapter ${chapterNumber} already exists`,
|
||||||
|
entry_id: entry.id,
|
||||||
|
chapter: chapterNumber
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
updateDownloadProgress(downloadId, { status: 'downloading' });
|
||||||
|
|
||||||
|
let outputPath: string;
|
||||||
|
let fileId: string;
|
||||||
|
|
||||||
|
if (format === 'manga') {
|
||||||
|
const chapterName = `Chapter_${chapterNumber.toString().padStart(3, '0')}.cbz`;
|
||||||
|
outputPath = path.join(entry.path, chapterName);
|
||||||
|
|
||||||
|
const zip = new AdmZip();
|
||||||
|
const sortedImages = images!.sort((a, b) => a.index - b.index);
|
||||||
|
|
||||||
|
for (let i = 0; i < sortedImages.length; i++) {
|
||||||
|
const img = sortedImages[i];
|
||||||
|
const res = await fetch(img.url);
|
||||||
|
if (!res.ok) throw new Error(`HTTP_${res.status}`);
|
||||||
|
const buf = Buffer.from(await res.arrayBuffer());
|
||||||
|
|
||||||
|
const ext = path.extname(new URL(img.url).pathname) || '.jpg';
|
||||||
|
const filename = `${img.index.toString().padStart(4, '0')}${ext}`;
|
||||||
|
zip.addFile(filename, buf);
|
||||||
|
|
||||||
|
updateDownloadProgress(downloadId, {
|
||||||
|
progress: Math.floor((i / sortedImages.length) * 100)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
zip.writeZip(outputPath);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
const chapterName = `Chapter_${chapterNumber.toString().padStart(3, '0')}.epub`;
|
||||||
|
outputPath = path.join(entry.path, chapterName);
|
||||||
|
|
||||||
|
const zip = new AdmZip();
|
||||||
|
zip.addFile('mimetype', Buffer.from('application/epub+zip'), '', 0);
|
||||||
|
|
||||||
|
const containerXml = `<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
|
||||||
|
<rootfiles>
|
||||||
|
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
|
||||||
|
</rootfiles>
|
||||||
|
</container>`;
|
||||||
|
zip.addFile('META-INF/container.xml', Buffer.from(containerXml));
|
||||||
|
|
||||||
|
const contentOpf = `<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="bookid">
|
||||||
|
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||||
|
<dc:title>Chapter ${chapterNumber}</dc:title>
|
||||||
|
<dc:identifier id="bookid">chapter-${anilistId}-${chapterNumber}</dc:identifier>
|
||||||
|
<dc:language>en</dc:language>
|
||||||
|
</metadata>
|
||||||
|
<manifest>
|
||||||
|
<item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/>
|
||||||
|
</manifest>
|
||||||
|
<spine>
|
||||||
|
<itemref idref="chapter"/>
|
||||||
|
</spine>
|
||||||
|
</package>`;
|
||||||
|
zip.addFile('OEBPS/content.opf', Buffer.from(contentOpf));
|
||||||
|
|
||||||
|
const chapterXhtml = `<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||||
|
<head>
|
||||||
|
<title>Chapter ${chapterNumber}</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
${content}
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
zip.addFile('OEBPS/chapter.xhtml', Buffer.from(chapterXhtml));
|
||||||
|
zip.writeZip(outputPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
fileId = crypto.randomUUID();
|
||||||
|
await run(
|
||||||
|
`INSERT INTO local_files (id, entry_id, file_path, unit_number)
|
||||||
|
VALUES (?, ?, ?, ?)`,
|
||||||
|
[fileId, entry.id, outputPath, chapterNumber],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
await run(
|
||||||
|
`UPDATE local_entries SET last_scan = ? WHERE id = ?`,
|
||||||
|
[Date.now(), entry.id],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
updateDownloadProgress(downloadId, {
|
||||||
|
status: 'completed',
|
||||||
|
progress: 100,
|
||||||
|
completedAt: Date.now()
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(() => activeDownloads.delete(downloadId), 30000);
|
||||||
|
|
||||||
|
return {
|
||||||
|
status: 'SUCCESS',
|
||||||
|
download_id: downloadId,
|
||||||
|
entry_id: entry.id,
|
||||||
|
file_id: fileId,
|
||||||
|
chapter: chapterNumber,
|
||||||
|
format,
|
||||||
|
path: outputPath
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error: any) {
|
||||||
|
updateDownloadProgress(downloadId, {
|
||||||
|
status: 'failed',
|
||||||
|
error: error.message
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(() => activeDownloads.delete(downloadId), 60000);
|
||||||
|
|
||||||
|
const err = new Error('DOWNLOAD_FAILED');
|
||||||
|
(err as any).details = error.message;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseFFmpegTime(timeStr: string): number {
|
||||||
|
const parts = timeStr.split(':');
|
||||||
|
if (parts.length < 3) return 0;
|
||||||
|
|
||||||
|
const h = parseFloat(parts[0]) || 0;
|
||||||
|
const m = parseFloat(parts[1]) || 0;
|
||||||
|
const s = parseFloat(parts[2]) || 0;
|
||||||
|
|
||||||
|
return (h * 3600) + (m * 60) + s;
|
||||||
|
}
|
||||||
485
desktop/src/api/local/local.controller.ts
Normal file
@@ -0,0 +1,485 @@
|
|||||||
|
import {FastifyReply, FastifyRequest} from 'fastify';
|
||||||
|
import fs from 'fs';
|
||||||
|
import * as service from './local.service';
|
||||||
|
import * as downloadService from './download.service';
|
||||||
|
import * as streamingService from './streaming.service';
|
||||||
|
|
||||||
|
type ScanQuery = {
|
||||||
|
mode?: 'full' | 'incremental';
|
||||||
|
};
|
||||||
|
|
||||||
|
type Params = {
|
||||||
|
type: 'anime' | 'manga' | 'novels';
|
||||||
|
id?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type MatchBody = {
|
||||||
|
source: 'anilist';
|
||||||
|
matched_id: number | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
type DownloadAnimeBody =
|
||||||
|
| {
|
||||||
|
anilist_id: number;
|
||||||
|
episode_number: number;
|
||||||
|
stream_url: string;
|
||||||
|
is_master?: false;
|
||||||
|
subtitles?: {
|
||||||
|
language: string;
|
||||||
|
url: string;
|
||||||
|
}[];
|
||||||
|
duration?: number;
|
||||||
|
chapters?: {
|
||||||
|
title: string;
|
||||||
|
start_time: number;
|
||||||
|
end_time: number;
|
||||||
|
}[];
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
anilist_id: number;
|
||||||
|
episode_number: number;
|
||||||
|
stream_url: string;
|
||||||
|
duration?: number;
|
||||||
|
is_master: true;
|
||||||
|
variant: {
|
||||||
|
resolution: string;
|
||||||
|
bandwidth?: number;
|
||||||
|
codecs?: string;
|
||||||
|
playlist_url: string;
|
||||||
|
};
|
||||||
|
audio?: {
|
||||||
|
group?: string;
|
||||||
|
language?: string;
|
||||||
|
name?: string;
|
||||||
|
playlist_url: string;
|
||||||
|
}[];
|
||||||
|
subtitles?: {
|
||||||
|
language: string;
|
||||||
|
url: string;
|
||||||
|
}[];
|
||||||
|
chapters?: {
|
||||||
|
title: string;
|
||||||
|
start_time: number;
|
||||||
|
end_time: number;
|
||||||
|
}[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type DownloadBookBody = {
|
||||||
|
anilist_id: number;
|
||||||
|
chapter_number: number;
|
||||||
|
format: 'manga' | 'novel';
|
||||||
|
content?: string;
|
||||||
|
images?: Array<{
|
||||||
|
index: number;
|
||||||
|
url: string;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function scanLibrary(request: FastifyRequest<{ Querystring: ScanQuery }>, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const mode = request.query.mode || 'incremental';
|
||||||
|
return await service.performLibraryScan(mode);
|
||||||
|
} catch (err: any) {
|
||||||
|
if (err.message === 'NO_LIBRARY_CONFIGURED') {
|
||||||
|
return reply.status(400).send({ error: 'NO_LIBRARY_CONFIGURED' });
|
||||||
|
}
|
||||||
|
return reply.status(500).send({ error: 'FAILED_TO_SCAN_LIBRARY' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listEntries(request: FastifyRequest<{ Params: Params }>, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const { type } = request.params;
|
||||||
|
return await service.getEntriesByType(type);
|
||||||
|
} catch {
|
||||||
|
return reply.status(500).send({ error: 'FAILED_TO_LIST_ENTRIES' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getEntry(request: FastifyRequest<{ Params: Params }>, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const { type, id } = request.params as { type: string, id: string };
|
||||||
|
const entry = await service.getEntryDetails(type, id);
|
||||||
|
|
||||||
|
if (!entry) {
|
||||||
|
return reply.status(404).send({ error: 'ENTRY_NOT_FOUND' });
|
||||||
|
}
|
||||||
|
|
||||||
|
return entry;
|
||||||
|
} catch {
|
||||||
|
return reply.status(500).send({ error: 'FAILED_TO_GET_ENTRY' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function streamUnit(request: FastifyRequest, reply: FastifyReply) {
|
||||||
|
const { id, unit } = request.params as any;
|
||||||
|
|
||||||
|
const fileInfo = await service.getFileForStreaming(id, unit);
|
||||||
|
|
||||||
|
if (!fileInfo) {
|
||||||
|
return reply.status(404).send({ error: 'FILE_NOT_FOUND' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { filePath, stat } = fileInfo;
|
||||||
|
const range = request.headers.range;
|
||||||
|
|
||||||
|
if (!range) {
|
||||||
|
reply
|
||||||
|
.header('Content-Length', stat.size)
|
||||||
|
.header('Content-Type', 'video/mp4');
|
||||||
|
return fs.createReadStream(filePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
const parts = range.replace(/bytes=/, '').split('-');
|
||||||
|
const start = Number(parts[0]);
|
||||||
|
const end = parts[1] ? Number(parts[1]) : stat.size - 1;
|
||||||
|
|
||||||
|
if (
|
||||||
|
Number.isNaN(start) ||
|
||||||
|
Number.isNaN(end) ||
|
||||||
|
start < 0 ||
|
||||||
|
start >= stat.size ||
|
||||||
|
end < start ||
|
||||||
|
end >= stat.size
|
||||||
|
) {
|
||||||
|
return reply.status(416).send({ error: 'INVALID_RANGE' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const contentLength = end - start + 1;
|
||||||
|
|
||||||
|
reply
|
||||||
|
.status(206)
|
||||||
|
.header('Content-Range', `bytes ${start}-${end}/${stat.size}`)
|
||||||
|
.header('Accept-Ranges', 'bytes')
|
||||||
|
.header('Content-Length', contentLength)
|
||||||
|
.header('Content-Type', 'video/mp4');
|
||||||
|
|
||||||
|
return fs.createReadStream(filePath, { start, end });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function matchEntry(
|
||||||
|
request: FastifyRequest<{ Body: MatchBody }>,
|
||||||
|
reply: FastifyReply
|
||||||
|
) {
|
||||||
|
const { id, type } = request.params as any;
|
||||||
|
const { source, matched_id } = request.body;
|
||||||
|
|
||||||
|
const result = await service.updateEntryMatch(id, type, source, matched_id);
|
||||||
|
|
||||||
|
if (!result) {
|
||||||
|
return reply.status(404).send({ error: 'ENTRY_NOT_FOUND' });
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUnits(request: FastifyRequest<{ Params: Params }>, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const { id } = request.params as { id: string };
|
||||||
|
const units = await service.getEntryUnits(id);
|
||||||
|
|
||||||
|
if (!units) {
|
||||||
|
return reply.status(404).send({ error: 'ENTRY_NOT_FOUND' });
|
||||||
|
}
|
||||||
|
|
||||||
|
return units;
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error getting units:', err);
|
||||||
|
return reply.status(500).send({ error: 'FAILED_TO_GET_UNITS' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getManifest(request: FastifyRequest, reply: FastifyReply) {
|
||||||
|
const { unitId } = request.params as any;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const manifest = await service.getUnitManifest(unitId);
|
||||||
|
|
||||||
|
if (!manifest) {
|
||||||
|
return reply.status(404).send({ error: 'FILE_NOT_FOUND' });
|
||||||
|
}
|
||||||
|
|
||||||
|
return manifest;
|
||||||
|
} catch (err: any) {
|
||||||
|
if (err.message === 'UNSUPPORTED_FORMAT') {
|
||||||
|
return reply.status(400).send({ error: 'UNSUPPORTED_FORMAT' });
|
||||||
|
}
|
||||||
|
return reply.status(500).send({ error: 'FAILED_TO_GET_MANIFEST' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPage(request: FastifyRequest, reply: FastifyReply) {
|
||||||
|
const { unitId, resId } = request.params as any;
|
||||||
|
|
||||||
|
const resource = await service.getUnitResource(unitId, resId);
|
||||||
|
|
||||||
|
if (!resource) {
|
||||||
|
return reply.status(404).send();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resource.type === 'image') {
|
||||||
|
if (resource.data) {
|
||||||
|
return reply
|
||||||
|
.header('Content-Type', 'image/jpeg')
|
||||||
|
.send(resource.data);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resource.path && resource.size) {
|
||||||
|
reply
|
||||||
|
.header('Content-Length', resource.size)
|
||||||
|
.header('Content-Type', 'image/jpeg');
|
||||||
|
|
||||||
|
return fs.createReadStream(resource.path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resource.type === 'html') {
|
||||||
|
return reply
|
||||||
|
.header('Content-Type', 'text/html; charset=utf-8')
|
||||||
|
.send(resource.data);
|
||||||
|
}
|
||||||
|
|
||||||
|
return reply.status(400).send();
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildProxyUrl(rawUrl: string, headers: Record<string, string>) {
|
||||||
|
const params = new URLSearchParams({ url: rawUrl });
|
||||||
|
|
||||||
|
for (const [key, value] of Object.entries(headers)) {
|
||||||
|
params.set(key.toLowerCase(), value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return `http://localhost:54322/api/proxy?${params.toString()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function downloadAnime(request: FastifyRequest<{ Body: DownloadAnimeBody }>, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const {
|
||||||
|
anilist_id,
|
||||||
|
episode_number,
|
||||||
|
stream_url,
|
||||||
|
duration,
|
||||||
|
is_master,
|
||||||
|
subtitles,
|
||||||
|
chapters
|
||||||
|
} = request.body;
|
||||||
|
|
||||||
|
const clientHeaders = (request.body as any).headers || {};
|
||||||
|
|
||||||
|
if (!anilist_id || !episode_number || !stream_url) {
|
||||||
|
return reply.status(400).send({
|
||||||
|
error: 'MISSING_REQUIRED_FIELDS',
|
||||||
|
required: ['anilist_id', 'episode_number', 'stream_url']
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const proxyUrl = buildProxyUrl(stream_url, clientHeaders);
|
||||||
|
console.log('Stream URL:', proxyUrl);
|
||||||
|
|
||||||
|
const proxiedSubs = subtitles?.map(sub => ({
|
||||||
|
...sub,
|
||||||
|
url: buildProxyUrl(sub.url, clientHeaders)
|
||||||
|
}));
|
||||||
|
|
||||||
|
const downloadParams: any = {
|
||||||
|
anilistId: anilist_id,
|
||||||
|
episodeNumber: episode_number,
|
||||||
|
streamUrl: proxyUrl,
|
||||||
|
subtitles: proxiedSubs,
|
||||||
|
chapters,
|
||||||
|
totalDuration: duration
|
||||||
|
};
|
||||||
|
|
||||||
|
if (is_master === true) {
|
||||||
|
const { variant, audio } = request.body as any;
|
||||||
|
|
||||||
|
if (!variant || !variant.playlist_url) {
|
||||||
|
return reply.status(400).send({
|
||||||
|
error: 'MISSING_VARIANT',
|
||||||
|
message: 'variant with playlist_url is required when is_master is true'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
downloadParams.is_master = true;
|
||||||
|
downloadParams.variant = {
|
||||||
|
...variant,
|
||||||
|
playlist_url: buildProxyUrl(variant.playlist_url, clientHeaders)
|
||||||
|
};
|
||||||
|
|
||||||
|
if (audio && audio.length > 0) {
|
||||||
|
downloadParams.audio = audio.map((a: any) => ({
|
||||||
|
...a,
|
||||||
|
playlist_url: buildProxyUrl(a.playlist_url, clientHeaders)
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Master playlist detected');
|
||||||
|
console.log('Variant:', downloadParams.variant.resolution);
|
||||||
|
console.log('Audio tracks:', downloadParams.audio?.length || 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await downloadService.downloadAnimeEpisode(downloadParams);
|
||||||
|
|
||||||
|
if (result.status === 'ALREADY_EXISTS') {
|
||||||
|
return reply.status(409).send(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error('Error downloading anime:', err);
|
||||||
|
|
||||||
|
if (err.message === 'METADATA_NOT_FOUND') {
|
||||||
|
return reply.status(404).send({ error: 'ANIME_NOT_FOUND_IN_ANILIST' });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (err.message === 'VARIANT_REQUIRED_FOR_MASTER') {
|
||||||
|
return reply.status(400).send({ error: 'VARIANT_REQUIRED_FOR_MASTER' });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (err.message === 'DOWNLOAD_FAILED') {
|
||||||
|
return reply.status(500).send({ error: 'DOWNLOAD_FAILED', details: err.details });
|
||||||
|
}
|
||||||
|
|
||||||
|
return reply.status(500).send({ error: 'FAILED_TO_DOWNLOAD_ANIME' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function downloadBook(request: FastifyRequest<{ Body: DownloadBookBody }>, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const {
|
||||||
|
anilist_id,
|
||||||
|
chapter_number,
|
||||||
|
format,
|
||||||
|
content,
|
||||||
|
images
|
||||||
|
} = request.body;
|
||||||
|
|
||||||
|
if (!anilist_id || !chapter_number || !format) {
|
||||||
|
return reply.status(400).send({
|
||||||
|
error: 'MISSING_REQUIRED_FIELDS',
|
||||||
|
required: ['anilist_id', 'chapter_number', 'format']
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (format === 'novel' && !content) {
|
||||||
|
return reply.status(400).send({
|
||||||
|
error: 'MISSING_CONTENT',
|
||||||
|
message: 'content field is required for novels'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (format === 'manga' && (!images || images.length === 0)) {
|
||||||
|
return reply.status(400).send({
|
||||||
|
error: 'MISSING_IMAGES',
|
||||||
|
message: 'images field is required for manga'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await downloadService.downloadBookChapter({
|
||||||
|
anilistId: anilist_id,
|
||||||
|
chapterNumber: chapter_number,
|
||||||
|
format,
|
||||||
|
content,
|
||||||
|
images
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.status === 'ALREADY_EXISTS') {
|
||||||
|
return reply.status(409).send(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error('Error downloading book:', err);
|
||||||
|
|
||||||
|
if (err.message === 'METADATA_NOT_FOUND') {
|
||||||
|
return reply.status(404).send({ error: 'BOOK_NOT_FOUND_IN_ANILIST' });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (err.message === 'DOWNLOAD_FAILED') {
|
||||||
|
return reply.status(500).send({ error: 'DOWNLOAD_FAILED', details: err.details });
|
||||||
|
}
|
||||||
|
|
||||||
|
return reply.status(500).send({ error: 'FAILED_TO_DOWNLOAD_BOOK' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getDownloadStatus(request: FastifyRequest, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const downloads = downloadService.getActiveDownloads();
|
||||||
|
const streams = streamingService.getActiveStreamsStatus();
|
||||||
|
|
||||||
|
return {
|
||||||
|
downloads: {
|
||||||
|
total: downloads.length,
|
||||||
|
active: downloads.filter(d => d.status === 'downloading').length,
|
||||||
|
completed: downloads.filter(d => d.status === 'completed').length,
|
||||||
|
failed: downloads.filter(d => d.status === 'failed').length,
|
||||||
|
list: downloads
|
||||||
|
},
|
||||||
|
streams: {
|
||||||
|
total: streams.length,
|
||||||
|
active: streams.filter(s => !s.isComplete).length,
|
||||||
|
completed: streams.filter(s => s.isComplete).length,
|
||||||
|
list: streams
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error getting download status:', err);
|
||||||
|
return reply.status(500).send({ error: 'FAILED_TO_GET_DOWNLOAD_STATUS' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAnimeStreamManifest(request: FastifyRequest, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const { type, id, unit } = request.params as any;
|
||||||
|
|
||||||
|
if (type !== 'anime') {
|
||||||
|
return reply.status(400).send({ error: 'ONLY_ANIME_SUPPORTED' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileInfo = await service.getFileForStreaming(id, unit);
|
||||||
|
|
||||||
|
if (!fileInfo) {
|
||||||
|
return reply.status(404).send({ error: 'FILE_NOT_FOUND' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const manifest = await streamingService.getStreamingManifest(fileInfo.filePath);
|
||||||
|
|
||||||
|
if (!manifest) {
|
||||||
|
return reply.status(500).send({ error: 'FAILED_TO_GENERATE_MANIFEST' });
|
||||||
|
}
|
||||||
|
|
||||||
|
return manifest;
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error('Error getting stream manifest:', err);
|
||||||
|
return reply.status(500).send({ error: 'FAILED_TO_GET_STREAM_MANIFEST' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function serveHLSFile(request: FastifyRequest, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const { hash, filename } = request.params as any;
|
||||||
|
|
||||||
|
const file = await streamingService.getHLSFile(hash, filename);
|
||||||
|
|
||||||
|
if (!file) {
|
||||||
|
return reply.status(404).send({ error: 'FILE_NOT_FOUND' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const contentType = filename.endsWith('.m3u8')
|
||||||
|
? 'application/vnd.apple.mpegurl'
|
||||||
|
: filename.endsWith('.vtt')
|
||||||
|
? 'text/vtt'
|
||||||
|
: 'video/mp2t';
|
||||||
|
|
||||||
|
reply
|
||||||
|
.header('Content-Type', contentType)
|
||||||
|
.header('Content-Length', file.stat.size)
|
||||||
|
.header('Access-Control-Allow-Origin', '*');
|
||||||
|
|
||||||
|
return fs.createReadStream(file.path);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error serving HLS file:', err);
|
||||||
|
return reply.status(500).send({ error: 'FAILED_TO_SERVE_HLS_FILE' });
|
||||||
|
}
|
||||||
|
}
|
||||||
22
desktop/src/api/local/local.routes.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { FastifyInstance } from 'fastify';
|
||||||
|
import * as controller from './local.controller';
|
||||||
|
|
||||||
|
async function localRoutes(fastify: FastifyInstance) {
|
||||||
|
fastify.post('/library/scan', controller.scanLibrary);
|
||||||
|
fastify.get('/library/:type', controller.listEntries);
|
||||||
|
fastify.get('/library/:type/:id', controller.getEntry);
|
||||||
|
|
||||||
|
// Streaming básico (legacy)
|
||||||
|
fastify.get('/library/stream/:type/:id/:unit', controller.streamUnit);
|
||||||
|
fastify.post('/library/:type/:id/match', controller.matchEntry);
|
||||||
|
fastify.get('/library/:id/units', controller.getUnits);
|
||||||
|
fastify.get('/library/:unitId/manifest', controller.getManifest);
|
||||||
|
fastify.get('/library/:unitId/resource/:resId', controller.getPage);
|
||||||
|
fastify.post('/library/download/anime', controller.downloadAnime);
|
||||||
|
fastify.post('/library/download/book', controller.downloadBook);
|
||||||
|
fastify.get('/library/downloads/status', controller.getDownloadStatus);
|
||||||
|
fastify.get('/library/stream/:type/:id/:unit/manifest', controller.getAnimeStreamManifest);
|
||||||
|
fastify.get('/library/hls/:hash/:filename', controller.serveHLSFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default localRoutes;
|
||||||
513
desktop/src/api/local/local.service.ts
Normal file
@@ -0,0 +1,513 @@
|
|||||||
|
import { getConfig as loadConfig } from '../../shared/config.js';
|
||||||
|
import { queryOne, queryAll, run } from '../../shared/database.js';
|
||||||
|
import crypto from 'crypto';
|
||||||
|
import fs from "fs";
|
||||||
|
import { PathLike } from "node:fs";
|
||||||
|
import path from "path";
|
||||||
|
import { getAnimeById, searchAnimeLocal } from "../anime/anime.service";
|
||||||
|
import { getBookById, searchBooksAniList } from "../books/books.service";
|
||||||
|
import AdmZip from 'adm-zip';
|
||||||
|
import { getStreamHash, getSubtitleFileStream } from './streaming.service';
|
||||||
|
|
||||||
|
const MANGA_IMAGE_EXTS = ['.jpg', '.jpeg', '.png', '.webp'];
|
||||||
|
const MANGA_ARCHIVES = ['.cbz', '.cbr', '.zip'];
|
||||||
|
const NOVEL_EXTS = ['.epub', '.pdf', '.txt', '.md', '.docx', '.mobi'];
|
||||||
|
|
||||||
|
function normalize(str: string) {
|
||||||
|
return str
|
||||||
|
.toLowerCase()
|
||||||
|
.normalize('NFD')
|
||||||
|
.replace(/[\u0300-\u036f]/g, '')
|
||||||
|
.replace(/[^a-z0-9 ]/g, '')
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function levenshtein(a: string, b: string) {
|
||||||
|
const matrix = Array.from({ length: b.length + 1 }, (_, i) => [i]);
|
||||||
|
|
||||||
|
for (let j = 0; j <= a.length; j++) matrix[0][j] = j;
|
||||||
|
|
||||||
|
for (let i = 1; i <= b.length; i++) {
|
||||||
|
for (let j = 1; j <= a.length; j++) {
|
||||||
|
matrix[i][j] = Math.min(
|
||||||
|
matrix[i - 1][j] + 1,
|
||||||
|
matrix[i][j - 1] + 1,
|
||||||
|
matrix[i - 1][j - 1] + (b[i - 1] === a[j - 1] ? 0 : 1)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return matrix[b.length][a.length];
|
||||||
|
}
|
||||||
|
|
||||||
|
function getTitleVariants(media: any): string[] {
|
||||||
|
const t = media.title || {};
|
||||||
|
return [
|
||||||
|
t.romaji,
|
||||||
|
t.english,
|
||||||
|
t.native,
|
||||||
|
...(media.synonyms || [])
|
||||||
|
].filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
function scoreEntry(query: string, media: any) {
|
||||||
|
const q = normalize(query);
|
||||||
|
let best = Infinity;
|
||||||
|
|
||||||
|
for (const title of getTitleVariants(media)) {
|
||||||
|
const t = normalize(title);
|
||||||
|
|
||||||
|
if (t.includes(q) || q.includes(t)) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
best = Math.min(best, levenshtein(q, t));
|
||||||
|
}
|
||||||
|
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resolveEntryMetadata(entry: any, type: string) {
|
||||||
|
let metadata = null;
|
||||||
|
let matchedId = entry.matched_id;
|
||||||
|
|
||||||
|
if (!matchedId) {
|
||||||
|
const query = entry.folder_name;
|
||||||
|
|
||||||
|
const results = type === 'anime'
|
||||||
|
? await searchAnimeLocal(query)
|
||||||
|
: await searchBooksAniList(query);
|
||||||
|
|
||||||
|
let picked = null;
|
||||||
|
|
||||||
|
let candidates = results;
|
||||||
|
|
||||||
|
if (type !== 'anime' && Array.isArray(results)) {
|
||||||
|
if (entry.type === 'novels') {
|
||||||
|
candidates = results.filter(r => r.format === 'NOVEL');
|
||||||
|
} else if (entry.type === 'manga') {
|
||||||
|
candidates = results.filter(r => r.format !== 'NOVEL');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(candidates) && candidates.length) {
|
||||||
|
const scored = candidates
|
||||||
|
.map(r => ({ r, score: scoreEntry(entry.folder_name, r) }))
|
||||||
|
.sort((a, b) => a.score - b.score);
|
||||||
|
|
||||||
|
// cutoff opcional
|
||||||
|
if (scored[0].score <= 10) {
|
||||||
|
picked = scored[0].r;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (picked?.id) {
|
||||||
|
matchedId = picked.id;
|
||||||
|
|
||||||
|
await run(
|
||||||
|
`UPDATE local_entries
|
||||||
|
SET matched_id = ?, matched_source = 'anilist'
|
||||||
|
WHERE id = ?`,
|
||||||
|
[matchedId, entry.id],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (matchedId) {
|
||||||
|
metadata = type === 'anime'
|
||||||
|
? await getAnimeById(matchedId)
|
||||||
|
: await getBookById(matchedId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: entry.id,
|
||||||
|
type: entry.type,
|
||||||
|
matched: !!matchedId,
|
||||||
|
metadata
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function performLibraryScan(mode: 'full' | 'incremental' = 'incremental') {
|
||||||
|
const { values } = loadConfig();
|
||||||
|
|
||||||
|
if (!values.library) {
|
||||||
|
throw new Error('NO_LIBRARY_CONFIGURED');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mode === 'full') {
|
||||||
|
await run(`DELETE FROM local_files`, [], 'local_library');
|
||||||
|
await run(`DELETE FROM local_entries`, [], 'local_library');
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [type, basePath] of Object.entries(values.library)) {
|
||||||
|
if (!basePath || !fs.existsSync(<PathLike>basePath)) continue;
|
||||||
|
|
||||||
|
const dirs = fs.readdirSync(<string>basePath, { withFileTypes: true }).filter(d => d.isDirectory());
|
||||||
|
|
||||||
|
for (const dir of dirs) {
|
||||||
|
const fullPath = path.join(<string>basePath, dir.name);
|
||||||
|
const id = crypto.createHash('sha1').update(fullPath).digest('hex');
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
const existing = await queryOne(`SELECT id FROM local_entries WHERE id = ?`, [id], 'local_library');
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
await run(`UPDATE local_entries SET last_scan = ? WHERE id = ?`, [now, id], 'local_library');
|
||||||
|
await run(`DELETE FROM local_files WHERE entry_id = ?`, [id], 'local_library');
|
||||||
|
} else {
|
||||||
|
await run(
|
||||||
|
`INSERT INTO local_entries (id, type, path, folder_name, last_scan) VALUES (?, ?, ?, ?, ?)`,
|
||||||
|
[id, type, fullPath, dir.name, now],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const files = fs.readdirSync(fullPath, { withFileTypes: true })
|
||||||
|
.filter(f =>
|
||||||
|
f.isFile() ||
|
||||||
|
(type === 'manga' && f.isDirectory())
|
||||||
|
)
|
||||||
|
.sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
|
||||||
|
let unit = 1;
|
||||||
|
|
||||||
|
for (const file of files) {
|
||||||
|
await run(
|
||||||
|
`INSERT INTO local_files (id, entry_id, file_path, unit_number)
|
||||||
|
VALUES (?, ?, ?, ?)`,
|
||||||
|
[crypto.randomUUID(), id, path.join(fullPath, file.name), unit],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
unit++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { status: 'OK' };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getEntriesByType(type: string) {
|
||||||
|
const sql = `
|
||||||
|
SELECT local_entries.*, COUNT(local_files.id) as file_count
|
||||||
|
FROM local_entries
|
||||||
|
LEFT JOIN local_files ON local_entries.id = local_files.entry_id
|
||||||
|
WHERE local_entries.type = ?
|
||||||
|
GROUP BY local_entries.id
|
||||||
|
`;
|
||||||
|
const entries = await queryAll(sql, [type], 'local_library');
|
||||||
|
return await Promise.all(entries.map(async (entry: any) => {
|
||||||
|
const metadata = await resolveEntryMetadata(entry, type);
|
||||||
|
return {
|
||||||
|
...metadata,
|
||||||
|
path: entry.path,
|
||||||
|
files: entry.file_count
|
||||||
|
};
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getEntryDetails(type: string, id: string) {
|
||||||
|
const entry = await queryOne(
|
||||||
|
`SELECT * FROM local_entries WHERE matched_id = ? AND type = ?`,
|
||||||
|
[Number(id), type],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!entry) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [details, files] = await Promise.all([
|
||||||
|
resolveEntryMetadata(entry, type),
|
||||||
|
queryAll(
|
||||||
|
`SELECT id, file_path, unit_number FROM local_files WHERE entry_id = ? ORDER BY unit_number ASC`,
|
||||||
|
[id],
|
||||||
|
'local_library'
|
||||||
|
)
|
||||||
|
]);
|
||||||
|
|
||||||
|
return { ...details, files };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getFileForStreaming(id: string, unit: string) {
|
||||||
|
const file = await queryOne(
|
||||||
|
`SELECT file_path FROM local_files WHERE entry_id = ? AND unit_number = ?`,
|
||||||
|
[id, unit],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!file || !fs.existsSync(file.file_path)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
filePath: file.file_path,
|
||||||
|
stat: fs.statSync(file.file_path)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateEntryMatch(id: string, type: string, source: string, matchedId: number | null) {
|
||||||
|
const entry = await queryOne(
|
||||||
|
`SELECT id FROM local_entries WHERE id = ? AND type = ?`,
|
||||||
|
[id, type],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!entry) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
await run(
|
||||||
|
`UPDATE local_entries
|
||||||
|
SET matched_source = ?, matched_id = ?
|
||||||
|
WHERE id = ?`,
|
||||||
|
[source, matchedId, id],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
return { status: 'OK', matched: !!matchedId };
|
||||||
|
}
|
||||||
|
|
||||||
|
function isImageFolder(folderPath: string): boolean {
|
||||||
|
if (!fs.existsSync(folderPath)) return false;
|
||||||
|
if (!fs.statSync(folderPath).isDirectory()) return false;
|
||||||
|
|
||||||
|
const files = fs.readdirSync(folderPath);
|
||||||
|
return files.some(f => MANGA_IMAGE_EXTS.includes(path.extname(f).toLowerCase()));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getEntryUnits(id: string) {
|
||||||
|
const entry = await queryOne(
|
||||||
|
`SELECT id, type, matched_id FROM local_entries WHERE matched_id = ?`,
|
||||||
|
[Number(id)],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!entry) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const files = await queryAll(
|
||||||
|
`SELECT id, file_path, unit_number FROM local_files
|
||||||
|
WHERE entry_id = ?
|
||||||
|
ORDER BY unit_number ASC`,
|
||||||
|
[entry.id],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
const units = files
|
||||||
|
.map((file: any) => {
|
||||||
|
const fileExt = path.extname(file.file_path).toLowerCase();
|
||||||
|
const isDir = fs.existsSync(file.file_path) &&
|
||||||
|
fs.statSync(file.file_path).isDirectory();
|
||||||
|
|
||||||
|
if (entry.type === 'manga') {
|
||||||
|
if (MANGA_ARCHIVES.includes(fileExt)) {
|
||||||
|
return {
|
||||||
|
id: file.id,
|
||||||
|
number: file.unit_number,
|
||||||
|
name: path.basename(file.file_path),
|
||||||
|
type: 'chapter',
|
||||||
|
format: fileExt.replace('.', ''),
|
||||||
|
path: file.file_path
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isDir && isImageFolder(file.file_path)) {
|
||||||
|
return {
|
||||||
|
id: file.id,
|
||||||
|
number: file.unit_number,
|
||||||
|
name: path.basename(file.file_path),
|
||||||
|
type: 'chapter',
|
||||||
|
format: 'folder',
|
||||||
|
path: file.file_path
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (entry.type === 'novels') {
|
||||||
|
if (NOVEL_EXTS.includes(fileExt)) {
|
||||||
|
return {
|
||||||
|
id: file.id,
|
||||||
|
number: file.unit_number,
|
||||||
|
name: path.basename(file.file_path),
|
||||||
|
type: 'chapter',
|
||||||
|
format: fileExt.replace('.', ''),
|
||||||
|
path: file.file_path
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (entry.type === 'anime') {
|
||||||
|
return {
|
||||||
|
id: file.id,
|
||||||
|
number: file.unit_number,
|
||||||
|
name: path.basename(file.file_path),
|
||||||
|
type: 'episode',
|
||||||
|
format: fileExt.replace('.', ''),
|
||||||
|
path: file.file_path
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
})
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
return {
|
||||||
|
entry_id: entry.id,
|
||||||
|
matched_id: entry.matched_id,
|
||||||
|
type: entry.type,
|
||||||
|
total: units.length,
|
||||||
|
units
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUnitManifest(unitId: string) {
|
||||||
|
const file = await queryOne(
|
||||||
|
`SELECT file_path FROM local_files WHERE id = ?`,
|
||||||
|
[unitId],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!file || !fs.existsSync(file.file_path)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ext = path.extname(file.file_path).toLowerCase();
|
||||||
|
|
||||||
|
if (['.cbz', '.cbr', '.zip'].includes(ext)) {
|
||||||
|
const zip = new AdmZip(file.file_path);
|
||||||
|
|
||||||
|
const pages = zip.getEntries()
|
||||||
|
.filter(e => !e.isDirectory && /\.(jpg|jpeg|png|webp)$/i.test(e.entryName))
|
||||||
|
.sort((a, b) => a.entryName.localeCompare(b.entryName, undefined, { numeric: true }))
|
||||||
|
.map((_, i) => ({
|
||||||
|
id: i,
|
||||||
|
url: `/api/library/${unitId}/resource/${i}`
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: 'manga',
|
||||||
|
format: 'archive',
|
||||||
|
pages
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fs.statSync(file.file_path).isDirectory()) {
|
||||||
|
const pages = fs.readdirSync(file.file_path)
|
||||||
|
.filter(f => /\.(jpg|jpeg|png|webp)$/i.test(f))
|
||||||
|
.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))
|
||||||
|
.map((_, i) => ({
|
||||||
|
id: i,
|
||||||
|
url: `/api/library/${unitId}/resource/${i}`
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: 'manga',
|
||||||
|
format: 'folder',
|
||||||
|
pages
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ext === '.epub') {
|
||||||
|
return {
|
||||||
|
type: 'ln',
|
||||||
|
format: 'epub',
|
||||||
|
url: `/api/library/${unitId}/resource/epub`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (['.txt', '.md'].includes(ext)) {
|
||||||
|
return {
|
||||||
|
type: 'ln',
|
||||||
|
format: 'text',
|
||||||
|
url: `/api/library/${unitId}/resource/text`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ext === '.pdf') {
|
||||||
|
return {
|
||||||
|
type: 'ln',
|
||||||
|
format: 'pdf',
|
||||||
|
url: `/api/library/${unitId}/resource/pdf`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('UNSUPPORTED_FORMAT');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUnitResource(unitId: string, resId: string) {
|
||||||
|
const file = await queryOne(
|
||||||
|
`SELECT file_path FROM local_files WHERE id = ?`,
|
||||||
|
[unitId],
|
||||||
|
'local_library'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!file) return null;
|
||||||
|
|
||||||
|
const ext = path.extname(file.file_path).toLowerCase();
|
||||||
|
|
||||||
|
if (['.cbz', '.zip', '.cbr'].includes(ext)) {
|
||||||
|
const zip = new AdmZip(file.file_path);
|
||||||
|
const images = zip.getEntries()
|
||||||
|
.filter(e => !e.isDirectory && /\.(jpg|jpeg|png|webp)$/i.test(e.entryName))
|
||||||
|
.sort((a, b) => a.entryName.localeCompare(b.entryName, undefined, { numeric: true }));
|
||||||
|
|
||||||
|
const entry = images[Number(resId)];
|
||||||
|
if (!entry) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: 'image',
|
||||||
|
data: entry.getData()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fs.statSync(file.file_path).isDirectory()) {
|
||||||
|
const images = fs.readdirSync(file.file_path)
|
||||||
|
.filter(f => /\.(jpg|jpeg|png|webp)$/i.test(f))
|
||||||
|
.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
|
||||||
|
|
||||||
|
const img = images[Number(resId)];
|
||||||
|
if (!img) return null;
|
||||||
|
|
||||||
|
const imgPath = path.join(file.file_path, img);
|
||||||
|
const stat = fs.statSync(imgPath);
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: 'image',
|
||||||
|
path: imgPath,
|
||||||
|
size: stat.size
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ext === '.epub') {
|
||||||
|
const html = await parseEpubToHtml(file.file_path);
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: 'html',
|
||||||
|
data: html
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (['.txt', '.md'].includes(ext)) {
|
||||||
|
const text = fs.readFileSync(file.file_path, 'utf8');
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: 'html',
|
||||||
|
data: `<div class="ln-content"><pre>${text}</pre></div>`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function parseEpubToHtml(filePath: string) {
|
||||||
|
const zip = new AdmZip(filePath);
|
||||||
|
const entry = zip.getEntry('OEBPS/chapter.xhtml');
|
||||||
|
if (!entry) throw new Error('CHAPTER_NOT_FOUND');
|
||||||
|
return entry.getData().toString('utf8');
|
||||||
|
}
|
||||||
622
desktop/src/api/local/streaming.service.ts
Normal file
@@ -0,0 +1,622 @@
|
|||||||
|
import { getConfig as loadConfig } from '../../shared/config';
|
||||||
|
import { queryOne } from '../../shared/database';
|
||||||
|
import crypto from 'crypto';
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import { spawn } from 'child_process';
|
||||||
|
|
||||||
|
const { values } = loadConfig();
|
||||||
|
const FFMPEG_PATH = values.paths?.ffmpeg || 'ffmpeg';
|
||||||
|
const FFPROBE_PATH = values.paths?.ffprobe || 'ffprobe';
|
||||||
|
|
||||||
|
const STREAM_TTL = 2 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
type VideoStreamInfo = {
|
||||||
|
index: number;
|
||||||
|
codec: string;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
fps: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type AudioStreamInfo = {
|
||||||
|
index: number;
|
||||||
|
codec: string;
|
||||||
|
language?: string;
|
||||||
|
title?: string;
|
||||||
|
channels: number;
|
||||||
|
sampleRate: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type SubtitleStreamInfo = {
|
||||||
|
index: number;
|
||||||
|
codec: string;
|
||||||
|
language?: string;
|
||||||
|
title?: string;
|
||||||
|
duration: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ChapterInfo = {
|
||||||
|
id: number;
|
||||||
|
start: number;
|
||||||
|
end: number;
|
||||||
|
title: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type MediaInfo = {
|
||||||
|
video: VideoStreamInfo[];
|
||||||
|
audio: AudioStreamInfo[];
|
||||||
|
subtitles: SubtitleStreamInfo[];
|
||||||
|
chapters: ChapterInfo[];
|
||||||
|
duration: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ActiveStream = {
|
||||||
|
hash: string;
|
||||||
|
filePath: string;
|
||||||
|
hlsDir: string;
|
||||||
|
info: MediaInfo;
|
||||||
|
process?: any;
|
||||||
|
startedAt: number;
|
||||||
|
lastAccessed: number;
|
||||||
|
isComplete: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const activeStreams = new Map<string, ActiveStream>();
|
||||||
|
|
||||||
|
setInterval(() => {
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
for (const [hash, stream] of activeStreams.entries()) {
|
||||||
|
const age = now - stream.lastAccessed;
|
||||||
|
|
||||||
|
if (age > STREAM_TTL) {
|
||||||
|
console.log(`🗑️ Limpiando stream antiguo: ${hash}`);
|
||||||
|
|
||||||
|
if (stream.process && !stream.process.killed) {
|
||||||
|
stream.process.kill('SIGKILL');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fs.existsSync(stream.hlsDir)) {
|
||||||
|
fs.rmSync(stream.hlsDir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
activeStreams.delete(hash);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 60 * 1000);
|
||||||
|
|
||||||
|
export function getStreamHash(filePath: string): string {
|
||||||
|
const stat = fs.statSync(filePath);
|
||||||
|
return crypto
|
||||||
|
.createHash('md5')
|
||||||
|
.update(`${filePath}-${stat.mtime.getTime()}`)
|
||||||
|
.digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureHLSDirectory(hash: string): string {
|
||||||
|
const tempDir = path.join(require('os').tmpdir(), 'hls-streams', hash);
|
||||||
|
|
||||||
|
if (!fs.existsSync(tempDir)) {
|
||||||
|
fs.mkdirSync(tempDir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
return tempDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildStreamMap(info: MediaInfo): string {
|
||||||
|
const maps: string[] = [];
|
||||||
|
|
||||||
|
maps.push(`v:0,a:0`);
|
||||||
|
|
||||||
|
return maps.join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeMasterPlaylist(info: MediaInfo, hlsDir: string) {
|
||||||
|
const lines: string[] = ['#EXTM3U'];
|
||||||
|
|
||||||
|
info.audio.forEach((a, i) => {
|
||||||
|
lines.push(
|
||||||
|
`#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="${a.title || `Audio ${i+1}`}",LANGUAGE="${a.language || 'und'}",AUTOSELECT=YES,DEFAULT=${i===0?'YES':'NO'},URI="audio_${i}.m3u8"`
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
info.subtitles.forEach((s, i) => {
|
||||||
|
lines.push(
|
||||||
|
`#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="${s.title || `Sub ${i+1}`}",LANGUAGE="${s.language || 'und'}",AUTOSELECT=YES,DEFAULT=NO,URI="subs_${i}.m3u8"`
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
const v = info.video[0];
|
||||||
|
const bandwidth = v.width * v.height * v.fps * 0.07 | 0;
|
||||||
|
|
||||||
|
lines.push(
|
||||||
|
`#EXT-X-STREAM-INF:BANDWIDTH=${bandwidth},RESOLUTION=${v.width}x${v.height},AUDIO="audio"${info.subtitles.length ? ',SUBTITLES="subs"' : ''}`
|
||||||
|
);
|
||||||
|
lines.push('video.m3u8');
|
||||||
|
|
||||||
|
fs.writeFileSync(path.join(hlsDir, 'master.m3u8'), lines.join('\n'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function startHLSConversion(filePath: string, info: MediaInfo, hash: string): ActiveStream {
|
||||||
|
const hlsDir = ensureHLSDirectory(hash);
|
||||||
|
|
||||||
|
const stream: ActiveStream = {
|
||||||
|
hash,
|
||||||
|
filePath,
|
||||||
|
hlsDir,
|
||||||
|
info,
|
||||||
|
process: null,
|
||||||
|
startedAt: Date.now(),
|
||||||
|
lastAccessed: Date.now(),
|
||||||
|
isComplete: false
|
||||||
|
};
|
||||||
|
|
||||||
|
activeStreams.set(hash, stream);
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
|
||||||
|
await extractSubtitles(filePath, info, hlsDir);
|
||||||
|
|
||||||
|
writeMasterPlaylist(info, hlsDir);
|
||||||
|
|
||||||
|
startVideoTranscoding(stream, filePath, info, hlsDir);
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error('❌ Error en el flujo de inicio:', err);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
function startVideoTranscoding(stream: ActiveStream, filePath: string, info: MediaInfo, hlsDir: string) {
|
||||||
|
const args: string[] = ['-i', filePath];
|
||||||
|
|
||||||
|
args.push(
|
||||||
|
'-map', '0:v:0',
|
||||||
|
'-c:v', 'libx264',
|
||||||
|
'-preset', 'veryfast',
|
||||||
|
'-profile:v', 'main',
|
||||||
|
'-g', '48',
|
||||||
|
'-keyint_min', '48',
|
||||||
|
'-sc_threshold', '0',
|
||||||
|
'-pix_fmt', 'yuv420p',
|
||||||
|
'-f', 'hls',
|
||||||
|
'-hls_time', '4',
|
||||||
|
'-hls_playlist_type', 'event',
|
||||||
|
|
||||||
|
'-hls_flags', 'independent_segments',
|
||||||
|
'-hls_segment_filename', path.join(hlsDir, 'v_%05d.ts'),
|
||||||
|
path.join(hlsDir, 'video.m3u8')
|
||||||
|
);
|
||||||
|
|
||||||
|
info.audio.forEach((a, i) => {
|
||||||
|
args.push(
|
||||||
|
'-map', `0:${a.index}`,
|
||||||
|
`-c:a:${i}`, 'aac',
|
||||||
|
`-b:a:${i}`, '128k',
|
||||||
|
'-f', 'hls',
|
||||||
|
'-hls_time', '4',
|
||||||
|
'-hls_playlist_type', 'event',
|
||||||
|
'-hls_flags', 'independent_segments',
|
||||||
|
'-hls_segment_filename', path.join(hlsDir, `a${i}_%05d.ts`),
|
||||||
|
path.join(hlsDir, `audio_${i}.m3u8`)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('🎬 Starting Video/Audio transcoding:', args.join(' '));
|
||||||
|
|
||||||
|
const ffmpeg = spawn(FFMPEG_PATH, args, {
|
||||||
|
windowsHide: true,
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe']
|
||||||
|
});
|
||||||
|
|
||||||
|
stream.process = ffmpeg;
|
||||||
|
|
||||||
|
ffmpeg.stderr.on('data', (data) => {
|
||||||
|
const text = data.toString();
|
||||||
|
|
||||||
|
if (text.includes('time=')) {
|
||||||
|
const timeMatch = text.match(/time=(\S+)/);
|
||||||
|
if (timeMatch) console.log(`⏱️ Converting ${stream.hash.substr(0,6)}: ${timeMatch[1]}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ffmpeg.on('close', (code) => {
|
||||||
|
if (code === 0) {
|
||||||
|
console.log('✅ Video transcoding complete');
|
||||||
|
stream.isComplete = true;
|
||||||
|
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const SUBTITLE_EXTENSIONS: Record<string, string> = {
|
||||||
|
'ass': 'ass',
|
||||||
|
'ssa': 'ass',
|
||||||
|
'subrip': 'srt',
|
||||||
|
'webvtt': 'vtt',
|
||||||
|
'hdmv_pgs_subtitle': 'sup',
|
||||||
|
'mov_text': 'srt',
|
||||||
|
'dvd_subtitle': 'sub',
|
||||||
|
'text': 'srt'
|
||||||
|
};
|
||||||
|
|
||||||
|
async function extractSubtitles(filePath: string, info: MediaInfo, hlsDir: string): Promise<void> {
|
||||||
|
if (info.subtitles.length === 0) return;
|
||||||
|
|
||||||
|
console.log('📝 Extrayendo subtítulos...');
|
||||||
|
|
||||||
|
const promises = info.subtitles.map((s, i) => {
|
||||||
|
return new Promise<void>((resolve, reject) => {
|
||||||
|
const codec = s.codec.toLowerCase();
|
||||||
|
const ext = codec === 'subrip' ? 'srt'
|
||||||
|
: codec === 'ass' || codec === 'ssa' ? 'ass'
|
||||||
|
: codec === 'webvtt' ? 'vtt'
|
||||||
|
: 'sub';
|
||||||
|
|
||||||
|
const outputFilename = `s${i}_full.${ext}`;
|
||||||
|
const outputPath = path.join(hlsDir, outputFilename);
|
||||||
|
const playlistPath = path.join(hlsDir, `subs_${i}.m3u8`);
|
||||||
|
|
||||||
|
if (s.duration === 0) {
|
||||||
|
console.log(`⚠️ Sub vacío, skip: ${i}`);
|
||||||
|
createDummySubtitlePlaylist(playlistPath, outputFilename, info.duration);
|
||||||
|
fs.writeFileSync(outputPath, '');
|
||||||
|
resolve();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(` Track ${i}: ${s.title || s.language || 'Unknown'} [${codec}] -> ${ext}`);
|
||||||
|
|
||||||
|
const args = [
|
||||||
|
'-i', filePath,
|
||||||
|
'-map', `0:s:${i}`
|
||||||
|
];
|
||||||
|
|
||||||
|
args.push('-c:s', 'copy');
|
||||||
|
args.push('-y', outputPath);
|
||||||
|
|
||||||
|
console.log(` Comando: ffmpeg ${args.join(' ')}`);
|
||||||
|
|
||||||
|
const p = spawn(FFMPEG_PATH, args, {
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe']
|
||||||
|
});
|
||||||
|
|
||||||
|
let errorOutput = '';
|
||||||
|
|
||||||
|
p.stderr.on('data', (data) => {
|
||||||
|
errorOutput += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
p.on('close', (code) => {
|
||||||
|
if (code === 0) {
|
||||||
|
try {
|
||||||
|
|
||||||
|
if (!fs.existsSync(outputPath)) {
|
||||||
|
console.error(` ❌ Archivo no creado: ${outputFilename}`);
|
||||||
|
|
||||||
|
fs.writeFileSync(outputPath, '');
|
||||||
|
} else {
|
||||||
|
const stat = fs.statSync(outputPath);
|
||||||
|
if (stat.size === 0) {
|
||||||
|
console.error(` ⚠️ Subtítulo ${i} tiene 0 bytes`);
|
||||||
|
console.error(` FFmpeg stderr:`, errorOutput.slice(-500));
|
||||||
|
} else {
|
||||||
|
console.log(` ✅ Subtítulo ${i} extraído: ${stat.size} bytes`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
createDummySubtitlePlaylist(playlistPath, outputFilename, info.duration);
|
||||||
|
resolve();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(` Error procesando subtítulo ${i}:`, e);
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error(` ❌ Error extrayendo subtítulo ${i}. Exit code: ${code}`);
|
||||||
|
console.error(` FFmpeg stderr:`, errorOutput.slice(-500));
|
||||||
|
|
||||||
|
fs.writeFileSync(outputPath, '');
|
||||||
|
createDummySubtitlePlaylist(playlistPath, outputFilename, info.duration);
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
p.on('error', (err) => {
|
||||||
|
console.error(` Error spawn ffmpeg subs ${i}:`, err);
|
||||||
|
fs.writeFileSync(outputPath, '');
|
||||||
|
createDummySubtitlePlaylist(playlistPath, outputFilename, info.duration);
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await Promise.all(promises);
|
||||||
|
console.log('✅ Proceso de subtítulos finalizado.');
|
||||||
|
}
|
||||||
|
|
||||||
|
function createDummySubtitlePlaylist(playlistPath: string, subtitleFilename: string, duration: number) {
|
||||||
|
const content = [
|
||||||
|
'#EXTM3U',
|
||||||
|
'#EXT-X-VERSION:3',
|
||||||
|
`#EXT-X-TARGETDURATION:${Math.ceil(duration)}`,
|
||||||
|
'#EXT-X-MEDIA-SEQUENCE:0',
|
||||||
|
'#EXT-X-PLAYLIST-TYPE:VOD',
|
||||||
|
`#EXTINF:${duration.toFixed(6)},`,
|
||||||
|
subtitleFilename,
|
||||||
|
'#EXT-X-ENDLIST'
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
fs.writeFileSync(playlistPath, content);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function probeMediaFile(filePath: string): Promise<MediaInfo> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const args = [
|
||||||
|
'-v', 'quiet',
|
||||||
|
'-print_format', 'json',
|
||||||
|
'-show_streams',
|
||||||
|
'-show_chapters',
|
||||||
|
'-show_format',
|
||||||
|
filePath
|
||||||
|
];
|
||||||
|
|
||||||
|
const ffprobe = spawn(FFPROBE_PATH, args);
|
||||||
|
let output = '';
|
||||||
|
|
||||||
|
ffprobe.stdout.on('data', (data) => {
|
||||||
|
output += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
ffprobe.on('close', (code) => {
|
||||||
|
if (code !== 0) {
|
||||||
|
return reject(new Error(`FFprobe failed with code ${code}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(output);
|
||||||
|
|
||||||
|
const video: VideoStreamInfo[] = data.streams
|
||||||
|
.filter((s: any) => s.codec_type === 'video')
|
||||||
|
.map((s: any) => ({
|
||||||
|
index: s.index,
|
||||||
|
codec: s.codec_name,
|
||||||
|
width: s.width,
|
||||||
|
height: s.height,
|
||||||
|
fps: eval(s.r_frame_rate) || 24
|
||||||
|
}));
|
||||||
|
|
||||||
|
const audio: AudioStreamInfo[] = data.streams
|
||||||
|
.filter((s: any) => s.codec_type === 'audio')
|
||||||
|
.map((s: any) => ({
|
||||||
|
index: s.index,
|
||||||
|
codec: s.codec_name,
|
||||||
|
language: s.tags?.language,
|
||||||
|
title: s.tags?.title,
|
||||||
|
channels: s.channels || 2,
|
||||||
|
sampleRate: parseInt(s.sample_rate) || 48000
|
||||||
|
}));
|
||||||
|
|
||||||
|
const subtitles: SubtitleStreamInfo[] = data.streams
|
||||||
|
.filter((s: any) => s.codec_type === 'subtitle')
|
||||||
|
.map((s: any) => ({
|
||||||
|
index: s.index,
|
||||||
|
codec: s.codec_name,
|
||||||
|
language: s.tags?.language,
|
||||||
|
title: s.tags?.title,
|
||||||
|
duration: parseFloat(s.duration) || 0
|
||||||
|
}));
|
||||||
|
|
||||||
|
const chapters: ChapterInfo[] = (data.chapters || []).map((c: any) => ({
|
||||||
|
id: c.id,
|
||||||
|
start: parseFloat(c.start_time),
|
||||||
|
end: parseFloat(c.end_time),
|
||||||
|
title: c.tags?.title || `Chapter ${c.id + 1}`
|
||||||
|
}));
|
||||||
|
|
||||||
|
const duration = parseFloat(data.format?.duration) || 0;
|
||||||
|
|
||||||
|
console.log(`📊 Media info: ${video.length} video, ${audio.length} audio, ${subtitles.length} subs`);
|
||||||
|
|
||||||
|
resolve({ video, audio, subtitles, chapters, duration });
|
||||||
|
} catch (e) {
|
||||||
|
reject(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ffprobe.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getStreamingManifest(filePath: string) {
|
||||||
|
if (!fs.existsSync(filePath)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hash = getStreamHash(filePath);
|
||||||
|
|
||||||
|
const formatSubtitles = (subs: SubtitleStreamInfo[]) => {
|
||||||
|
return subs.map((s, i) => {
|
||||||
|
const ext = SUBTITLE_EXTENSIONS[s.codec] || 'vtt';
|
||||||
|
return {
|
||||||
|
index: s.index,
|
||||||
|
codec: s.codec,
|
||||||
|
language: s.language || 'und',
|
||||||
|
title: s.title || `Subtitle ${s.index}`,
|
||||||
|
|
||||||
|
url: `/api/library/hls/${hash}/s${i}_full.${ext}`
|
||||||
|
};
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const existing = activeStreams.get(hash);
|
||||||
|
if (existing) {
|
||||||
|
existing.lastAccessed = Date.now();
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: 'hls',
|
||||||
|
hash,
|
||||||
|
masterPlaylist: `/api/library/hls/${hash}/master.m3u8`,
|
||||||
|
duration: existing.info.duration,
|
||||||
|
isComplete: existing.isComplete,
|
||||||
|
video: existing.info.video.map(v => ({
|
||||||
|
index: v.index,
|
||||||
|
codec: v.codec,
|
||||||
|
resolution: `${v.width}x${v.height}`,
|
||||||
|
fps: v.fps
|
||||||
|
})),
|
||||||
|
audio: existing.info.audio.map(a => ({
|
||||||
|
index: a.index,
|
||||||
|
codec: a.codec,
|
||||||
|
language: a.language || 'und',
|
||||||
|
title: a.title || `Audio ${a.index}`,
|
||||||
|
channels: a.channels
|
||||||
|
})),
|
||||||
|
|
||||||
|
subtitles: formatSubtitles(existing.info.subtitles),
|
||||||
|
chapters: existing.info.chapters.map(c => ({
|
||||||
|
id: c.id,
|
||||||
|
start: c.start,
|
||||||
|
end: c.end,
|
||||||
|
title: c.title
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const duplicateCheck = activeStreams.get(hash);
|
||||||
|
|
||||||
|
if (duplicateCheck) {
|
||||||
|
duplicateCheck.lastAccessed = Date.now();
|
||||||
|
return {
|
||||||
|
type: 'hls',
|
||||||
|
hash,
|
||||||
|
masterPlaylist: `/api/library/hls/${hash}/master.m3u8`,
|
||||||
|
duration: duplicateCheck.info.duration,
|
||||||
|
isComplete: duplicateCheck.isComplete,
|
||||||
|
video: duplicateCheck.info.video.map(v => ({
|
||||||
|
index: v.index,
|
||||||
|
codec: v.codec,
|
||||||
|
resolution: `${v.width}x${v.height}`,
|
||||||
|
fps: v.fps
|
||||||
|
})),
|
||||||
|
audio: duplicateCheck.info.audio.map(a => ({
|
||||||
|
index: a.index,
|
||||||
|
codec: a.codec,
|
||||||
|
language: a.language || 'und',
|
||||||
|
title: a.title || `Audio ${a.index}`,
|
||||||
|
channels: a.channels
|
||||||
|
})),
|
||||||
|
subtitles: formatSubtitles(duplicateCheck.info.subtitles),
|
||||||
|
chapters: duplicateCheck.info.chapters.map(c => ({
|
||||||
|
id: c.id,
|
||||||
|
start: c.start,
|
||||||
|
end: c.end,
|
||||||
|
title: c.title
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const info = await probeMediaFile(filePath);
|
||||||
|
return {
|
||||||
|
type: 'hls',
|
||||||
|
hash,
|
||||||
|
masterPlaylist: `/api/library/hls/${hash}/master.m3u8`,
|
||||||
|
duration: info.duration,
|
||||||
|
isComplete: false,
|
||||||
|
generating: true,
|
||||||
|
video: info.video.map(v => ({
|
||||||
|
index: v.index,
|
||||||
|
codec: v.codec,
|
||||||
|
resolution: `${v.width}x${v.height}`,
|
||||||
|
fps: v.fps
|
||||||
|
})),
|
||||||
|
audio: info.audio.map(a => ({
|
||||||
|
index: a.index,
|
||||||
|
codec: a.codec,
|
||||||
|
language: a.language || 'und',
|
||||||
|
title: a.title || `Audio ${a.index}`,
|
||||||
|
channels: a.channels
|
||||||
|
})),
|
||||||
|
subtitles: formatSubtitles(info.subtitles),
|
||||||
|
chapters: info.chapters.map(c => ({
|
||||||
|
id: c.id,
|
||||||
|
start: c.start,
|
||||||
|
end: c.end,
|
||||||
|
title: c.title
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSubtitleFileStream(hash: string, trackIndex: number) {
|
||||||
|
const stream = activeStreams.get(hash);
|
||||||
|
|
||||||
|
if (!stream) {
|
||||||
|
|
||||||
|
const tempDir = path.join(require('os').tmpdir(), 'hls-streams', hash);
|
||||||
|
if(fs.existsSync(tempDir)) {
|
||||||
|
|
||||||
|
const files = fs.readdirSync(tempDir);
|
||||||
|
const subFile = files.find(f => f.startsWith(`s${trackIndex}_full.`));
|
||||||
|
if (subFile) return fs.createReadStream(path.join(tempDir, subFile));
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!fs.existsSync(stream.hlsDir)) return null;
|
||||||
|
|
||||||
|
const files = fs.readdirSync(stream.hlsDir);
|
||||||
|
const subtitleFile = files.find(f => f.startsWith(`s${trackIndex}_full.`));
|
||||||
|
|
||||||
|
if (!subtitleFile) return null;
|
||||||
|
|
||||||
|
return fs.createReadStream(path.join(stream.hlsDir, subtitleFile));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getHLSFile(hash: string, filename: string) {
|
||||||
|
const stream = activeStreams.get(hash);
|
||||||
|
|
||||||
|
if (!stream) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
stream.lastAccessed = Date.now();
|
||||||
|
|
||||||
|
const filePath = path.join(stream.hlsDir, filename);
|
||||||
|
|
||||||
|
const maxWait = 30000;
|
||||||
|
|
||||||
|
const startWait = Date.now();
|
||||||
|
|
||||||
|
while (!fs.existsSync(filePath)) {
|
||||||
|
if (Date.now() - startWait > maxWait) {
|
||||||
|
console.error(`⏱️ Timeout esperando archivo: ${filename}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stream.isComplete && !fs.existsSync(filePath)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 100));
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
path: filePath,
|
||||||
|
stat: fs.statSync(filePath)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getActiveStreamsStatus() {
|
||||||
|
return Array.from(activeStreams.values()).map(stream => ({
|
||||||
|
hash: stream.hash,
|
||||||
|
filePath: stream.filePath,
|
||||||
|
isComplete: stream.isComplete,
|
||||||
|
startedAt: stream.startedAt,
|
||||||
|
lastAccessed: stream.lastAccessed,
|
||||||
|
age: Date.now() - stream.startedAt,
|
||||||
|
idle: Date.now() - stream.lastAccessed
|
||||||
|
}));
|
||||||
|
}
|
||||||
115
desktop/src/api/proxy/proxy.controller.ts
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
import {FastifyReply, FastifyRequest} from 'fastify';
|
||||||
|
import {processM3U8Content, proxyRequest, streamToReadable} from './proxy.service';
|
||||||
|
|
||||||
|
interface ProxyQuerystring {
|
||||||
|
url: string;
|
||||||
|
referer?: string;
|
||||||
|
origin?: string;
|
||||||
|
userAgent?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProxyRequest = FastifyRequest<{
|
||||||
|
Querystring: ProxyQuerystring
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export async function handleProxy(req: ProxyRequest, reply: FastifyReply) {
|
||||||
|
const { url, referer, origin, userAgent } = req.query;
|
||||||
|
|
||||||
|
if (!url) {
|
||||||
|
return reply.code(400).send({ error: "No URL provided" });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const rangeHeader = req.headers.range;
|
||||||
|
|
||||||
|
const { response, contentType, isM3U8, contentLength } = await proxyRequest(url, {
|
||||||
|
referer,
|
||||||
|
origin,
|
||||||
|
userAgent
|
||||||
|
}, rangeHeader);
|
||||||
|
|
||||||
|
|
||||||
|
reply.header('Access-Control-Allow-Origin', '*');
|
||||||
|
reply.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
|
||||||
|
reply.header('Access-Control-Allow-Headers', 'Content-Type, Range');
|
||||||
|
reply.header('Access-Control-Expose-Headers', 'Content-Length, Content-Range, Accept-Ranges');
|
||||||
|
|
||||||
|
if (isM3U8) {
|
||||||
|
reply.header('Content-Type', 'application/vnd.apple.mpegurl');
|
||||||
|
|
||||||
|
const text = await response.text();
|
||||||
|
const baseUrl = new URL(response.url);
|
||||||
|
|
||||||
|
const processedContent = processM3U8Content(text, baseUrl, {
|
||||||
|
referer,
|
||||||
|
origin,
|
||||||
|
userAgent
|
||||||
|
});
|
||||||
|
|
||||||
|
return reply.send(processedContent);
|
||||||
|
}
|
||||||
|
|
||||||
|
const isSubtitle = url.includes('.vtt') || url.includes('.srt') || url.includes('.ass') ||
|
||||||
|
contentType?.includes('text/vtt') || contentType?.includes('text/srt');
|
||||||
|
|
||||||
|
if (isSubtitle) {
|
||||||
|
const text = await response.text();
|
||||||
|
|
||||||
|
let mimeType = 'text/vtt';
|
||||||
|
if (url.includes('.srt') || contentType?.includes('srt')) {
|
||||||
|
mimeType = 'text/plain';
|
||||||
|
} else if (url.includes('.ass')) {
|
||||||
|
mimeType = 'text/plain';
|
||||||
|
}
|
||||||
|
|
||||||
|
reply.header('Content-Type', mimeType);
|
||||||
|
reply.header('Cache-Control', 'public, max-age=3600');
|
||||||
|
return reply.send(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (contentType) {
|
||||||
|
reply.header('Content-Type', contentType);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.status === 206) {
|
||||||
|
const contentRange = response.headers.get('content-range');
|
||||||
|
if (contentRange) {
|
||||||
|
reply.header('Content-Range', contentRange);
|
||||||
|
}
|
||||||
|
reply.code(206);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (contentLength) {
|
||||||
|
reply.header('Content-Length', contentLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (contentType?.startsWith('image/') || contentType?.startsWith('video/')) {
|
||||||
|
reply.header('Cache-Control', 'public, max-age=31536000, immutable');
|
||||||
|
}
|
||||||
|
|
||||||
|
reply.header('Accept-Ranges', 'bytes');
|
||||||
|
|
||||||
|
return reply.send(streamToReadable(response.body!));
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
req.server.log.error(err);
|
||||||
|
console.error('=== PROXY ERROR ===');
|
||||||
|
console.error('URL:', url);
|
||||||
|
console.error('Error:', err);
|
||||||
|
console.error('===================');
|
||||||
|
|
||||||
|
if (!reply.sent) {
|
||||||
|
return reply.code(500).send({
|
||||||
|
error: "Internal Server Error",
|
||||||
|
details: err instanceof Error ? err.message : String(err)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function handleProxyOptions(req: FastifyRequest, reply: FastifyReply) {
|
||||||
|
reply.header('Access-Control-Allow-Origin', '*');
|
||||||
|
reply.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
|
||||||
|
reply.header('Access-Control-Allow-Headers', 'Content-Type, Range');
|
||||||
|
return reply.code(204).send();
|
||||||
|
}
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
import { FastifyInstance } from 'fastify';
|
import { FastifyInstance } from 'fastify';
|
||||||
import { handleProxy } from './proxy.controller';
|
import {handleProxy, handleProxyOptions} from './proxy.controller';
|
||||||
|
|
||||||
async function proxyRoutes(fastify: FastifyInstance) {
|
async function proxyRoutes(fastify: FastifyInstance) {
|
||||||
fastify.get('/proxy', handleProxy);
|
fastify.get('/proxy', handleProxy);
|
||||||
|
fastify.options('/proxy', handleProxyOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default proxyRoutes;
|
export default proxyRoutes;
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Readable } from 'stream';
|
import {Readable} from 'stream';
|
||||||
|
|
||||||
interface ProxyHeaders {
|
interface ProxyHeaders {
|
||||||
referer?: string;
|
referer?: string;
|
||||||
@@ -13,25 +13,24 @@ interface ProxyResponse {
|
|||||||
contentLength: string | null;
|
contentLength: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function proxyRequest(url: string, { referer, origin, userAgent }: ProxyHeaders): Promise<ProxyResponse> {
|
export async function proxyRequest(url: string, { referer, origin, userAgent }: ProxyHeaders, rangeHeader?: string): Promise<ProxyResponse> {
|
||||||
const headers: Record<string, string> = {
|
const headers: Record<string, string> = {
|
||||||
'User-Agent': userAgent || "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
'User-Agent': userAgent || "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||||
'Accept': '*/*',
|
'Accept': '*/*',
|
||||||
'Accept-Language': 'en-US,en;q=0.9',
|
'Accept-Language': 'en-US,en;q=0.9',
|
||||||
'Accept-Encoding': 'identity',
|
'Accept-Encoding': 'identity',
|
||||||
|
|
||||||
'Connection': 'keep-alive'
|
'Connection': 'keep-alive'
|
||||||
};
|
};
|
||||||
|
|
||||||
if (referer) headers['Referer'] = referer;
|
if (referer) headers['Referer'] = referer;
|
||||||
if (origin) headers['Origin'] = origin;
|
if (origin) headers['Origin'] = origin;
|
||||||
|
if (rangeHeader) headers['Range'] = rangeHeader;
|
||||||
|
|
||||||
let lastError: Error | null = null;
|
let lastError: Error | null = null;
|
||||||
const maxRetries = 2;
|
const maxRetries = 2;
|
||||||
|
|
||||||
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
||||||
try {
|
try {
|
||||||
|
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
const timeoutId = setTimeout(() => controller.abort(), 60000);
|
const timeoutId = setTimeout(() => controller.abort(), 60000);
|
||||||
|
|
||||||
@@ -43,8 +42,7 @@ export async function proxyRequest(url: string, { referer, origin, userAgent }:
|
|||||||
|
|
||||||
clearTimeout(timeoutId);
|
clearTimeout(timeoutId);
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok && response.status !== 206) {
|
||||||
|
|
||||||
if (response.status === 404 || response.status === 403) {
|
if (response.status === 404 || response.status === 403) {
|
||||||
throw new Error(`Proxy Error: ${response.status} ${response.statusText}`);
|
throw new Error(`Proxy Error: ${response.status} ${response.statusText}`);
|
||||||
}
|
}
|
||||||
@@ -57,9 +55,16 @@ export async function proxyRequest(url: string, { referer, origin, userAgent }:
|
|||||||
throw new Error(`Proxy Error: ${response.status} ${response.statusText}`);
|
throw new Error(`Proxy Error: ${response.status} ${response.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const contentType = response.headers.get('content-type');
|
|
||||||
const contentLength = response.headers.get('content-length');
|
const contentLength = response.headers.get('content-length');
|
||||||
const isM3U8 = (contentType && contentType.includes('mpegurl')) || url.includes('.m3u8');
|
const contentType = response.headers.get('content-type');
|
||||||
|
const ct = contentType?.toLowerCase();
|
||||||
|
|
||||||
|
const isM3U8 =
|
||||||
|
!!ct && (
|
||||||
|
ct.includes('mpegurl') ||
|
||||||
|
ct.includes('m3u8')
|
||||||
|
) ||
|
||||||
|
url.toLowerCase().includes('.m3u8');
|
||||||
|
|
||||||
return {
|
return {
|
||||||
response,
|
response,
|
||||||
@@ -83,24 +88,57 @@ export async function proxyRequest(url: string, { referer, origin, userAgent }:
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function processM3U8Content(text: string, baseUrl: URL, { referer, origin, userAgent }: ProxyHeaders): string {
|
export function processM3U8Content(text: string, baseUrl: URL, { referer, origin, userAgent }: ProxyHeaders): string {
|
||||||
return text.replace(/^(?!#)(?!\s*$).+/gm, (line) => {
|
const buildProxy = (url: string) => {
|
||||||
line = line.trim();
|
|
||||||
let absoluteUrl: string;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
absoluteUrl = new URL(line, baseUrl).href;
|
const params = new URLSearchParams();
|
||||||
} catch (e) {
|
params.set('url', new URL(url, baseUrl).href);
|
||||||
return line;
|
if (referer) params.set('referer', referer);
|
||||||
|
if (origin) params.set('origin', origin);
|
||||||
|
if (userAgent) params.set('userAgent', userAgent);
|
||||||
|
return `/api/proxy?${params.toString()}`;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error building proxy URL for:', url, error);
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const isMasterPlaylist = text.includes('#EXT-X-STREAM-INF');
|
||||||
|
|
||||||
|
|
||||||
|
let lines = text.split('\n');
|
||||||
|
let result = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
const line = lines[i];
|
||||||
|
const trimmed = line.trim();
|
||||||
|
|
||||||
|
if (!trimmed) {
|
||||||
|
result.push(line);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const proxyParams = new URLSearchParams();
|
if (trimmed.startsWith('#')) {
|
||||||
proxyParams.set('url', absoluteUrl);
|
if (line.includes('URI=')) {
|
||||||
if (referer) proxyParams.set('referer', referer);
|
const processedLine = line.replace(/URI="([^"]+)"/g, (match, uri) => {
|
||||||
if (origin) proxyParams.set('origin', origin);
|
return `URI="${buildProxy(uri)}"`;
|
||||||
if (userAgent) proxyParams.set('userAgent', userAgent);
|
});
|
||||||
|
result.push(processedLine);
|
||||||
|
} else {
|
||||||
|
result.push(line);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
return `/api/proxy?${proxyParams.toString()}`;
|
try {
|
||||||
});
|
const proxiedUrl = buildProxy(trimmed);
|
||||||
|
result.push(proxiedUrl);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error processing M3U8 URL line:', trimmed, error);
|
||||||
|
result.push(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.join('\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
export function streamToReadable(webStream: ReadableStream): Readable {
|
export function streamToReadable(webStream: ReadableStream): Readable {
|
||||||
@@ -110,7 +148,6 @@ export function streamToReadable(webStream: ReadableStream): Readable {
|
|||||||
return new Readable({
|
return new Readable({
|
||||||
async read() {
|
async read() {
|
||||||
try {
|
try {
|
||||||
|
|
||||||
const timeoutPromise = new Promise((_, reject) => {
|
const timeoutPromise = new Promise((_, reject) => {
|
||||||
readTimeout = setTimeout(() => reject(new Error('Stream read timeout')), 10000);
|
readTimeout = setTimeout(() => reject(new Error('Stream read timeout')), 10000);
|
||||||
});
|
});
|
||||||
158
desktop/src/api/rooms/rooms.controller.ts
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
import { FastifyReply, FastifyRequest } from 'fastify';
|
||||||
|
import * as roomService from './rooms.service';
|
||||||
|
import { getUserById } from '../user/user.service';
|
||||||
|
import { openTunnel } from "./tunnel.manager";
|
||||||
|
|
||||||
|
interface CreateRoomBody {
|
||||||
|
name: string;
|
||||||
|
password?: string;
|
||||||
|
expose?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createRoom(req: any, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const { name, password, expose } = req.body as CreateRoomBody;
|
||||||
|
const userId = req.user?.id;
|
||||||
|
|
||||||
|
if (!userId) {
|
||||||
|
return reply.code(401).send({ error: "Authentication required to create room" });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!name || name.trim().length === 0) {
|
||||||
|
return reply.code(400).send({ error: "Room name is required" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await getUserById(userId);
|
||||||
|
if (!user) {
|
||||||
|
return reply.code(404).send({ error: "User not found" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const host = {
|
||||||
|
id: `user_${userId}`,
|
||||||
|
username: user.username,
|
||||||
|
avatar: user.profile_picture_url || undefined,
|
||||||
|
isHost: true,
|
||||||
|
isGuest: false,
|
||||||
|
userId
|
||||||
|
};
|
||||||
|
|
||||||
|
let publicUrl: string | undefined;
|
||||||
|
|
||||||
|
if (expose) {
|
||||||
|
publicUrl = await openTunnel();
|
||||||
|
}
|
||||||
|
|
||||||
|
const room = roomService.createRoom(
|
||||||
|
name,
|
||||||
|
host,
|
||||||
|
password,
|
||||||
|
!!expose,
|
||||||
|
publicUrl
|
||||||
|
);
|
||||||
|
|
||||||
|
if (expose && publicUrl) {
|
||||||
|
room.publicUrl = `${publicUrl}/room?id=${room.id}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return reply.send({
|
||||||
|
success: true,
|
||||||
|
room: {
|
||||||
|
id: room.id,
|
||||||
|
name: room.name,
|
||||||
|
hasPassword: !!room.password,
|
||||||
|
userCount: room.users.size,
|
||||||
|
exposed: room.exposed,
|
||||||
|
publicUrl: room.publicUrl
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Create Room Error:", err);
|
||||||
|
return reply.code(500).send({ error: "Failed to create room" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRooms(req: FastifyRequest, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const rooms = roomService.getAllRooms();
|
||||||
|
|
||||||
|
const roomList = rooms.map((room) => ({
|
||||||
|
id: room.id,
|
||||||
|
name: room.name,
|
||||||
|
host: room.host.username,
|
||||||
|
userCount: room.users.size,
|
||||||
|
hasPassword: !!room.password,
|
||||||
|
currentlyWatching: room.currentVideo ? {
|
||||||
|
animeId: room.currentVideo.animeId,
|
||||||
|
episode: room.currentVideo.episode
|
||||||
|
} : null
|
||||||
|
}));
|
||||||
|
|
||||||
|
return reply.send({ rooms: roomList });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Get Rooms Error:", err);
|
||||||
|
return reply.code(500).send({ error: "Failed to retrieve rooms" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRoom(req: FastifyRequest, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const room = roomService.getRoom(id);
|
||||||
|
|
||||||
|
if (!room) {
|
||||||
|
return reply.code(404).send({ error: "Room not found" });
|
||||||
|
}
|
||||||
|
|
||||||
|
return reply.send({
|
||||||
|
room: {
|
||||||
|
id: room.id,
|
||||||
|
name: room.name,
|
||||||
|
host: {
|
||||||
|
username: room.host.username,
|
||||||
|
avatar: room.host.avatar
|
||||||
|
},
|
||||||
|
users: Array.from(room.users.values()).map(u => ({
|
||||||
|
id: u.id,
|
||||||
|
username: u.username,
|
||||||
|
avatar: u.avatar,
|
||||||
|
isHost: u.isHost,
|
||||||
|
isGuest: u.isGuest
|
||||||
|
})),
|
||||||
|
hasPassword: !!room.password,
|
||||||
|
currentVideo: room.currentVideo,
|
||||||
|
exposed: room.exposed,
|
||||||
|
publicUrl: room.publicUrl
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Get Room Error:", err);
|
||||||
|
return reply.code(500).send({ error: "Failed to retrieve room" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteRoom(req: any, reply: FastifyReply) {
|
||||||
|
try {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const userId = req.user?.id;
|
||||||
|
|
||||||
|
if (!userId) {
|
||||||
|
return reply.code(401).send({ error: "Authentication required" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const room = roomService.getRoom(id);
|
||||||
|
if (!room) {
|
||||||
|
return reply.code(404).send({ error: "Room not found" });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (room.host.userId !== userId) {
|
||||||
|
return reply.code(403).send({ error: "Only the host can delete the room" });
|
||||||
|
}
|
||||||
|
|
||||||
|
roomService.deleteRoom(id);
|
||||||
|
|
||||||
|
return reply.send({ success: true });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Delete Room Error:", err);
|
||||||
|
return reply.code(500).send({ error: "Failed to delete room" });
|
||||||
|
}
|
||||||
|
}
|
||||||
11
desktop/src/api/rooms/rooms.routes.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { FastifyInstance } from 'fastify';
|
||||||
|
import * as controller from './rooms.controller';
|
||||||
|
|
||||||
|
async function roomRoutes(fastify: FastifyInstance) {
|
||||||
|
fastify.post('/rooms', controller.createRoom);
|
||||||
|
fastify.get('/rooms', controller.getRooms);
|
||||||
|
fastify.get('/rooms/:id', controller.getRoom);
|
||||||
|
fastify.delete('/rooms/:id', controller.deleteRoom);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default roomRoutes;
|
||||||
296
desktop/src/api/rooms/rooms.service.ts
Normal file
@@ -0,0 +1,296 @@
|
|||||||
|
import crypto from 'crypto';
|
||||||
|
import { closeTunnelIfUnused } from "./tunnel.manager";
|
||||||
|
|
||||||
|
interface RoomPermissions {
|
||||||
|
canControl: boolean;
|
||||||
|
canManageQueue: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RoomUser {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
avatar?: string;
|
||||||
|
isHost: boolean;
|
||||||
|
isGuest: boolean;
|
||||||
|
userId?: number;
|
||||||
|
permissions?: RoomPermissions;
|
||||||
|
ipAddress?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SourceContext {
|
||||||
|
animeId: string;
|
||||||
|
episode: string | number;
|
||||||
|
source: string;
|
||||||
|
extension: string;
|
||||||
|
server: string;
|
||||||
|
category: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QueueItem {
|
||||||
|
uid: string;
|
||||||
|
metadata: RoomMetadata;
|
||||||
|
videoData: any;
|
||||||
|
addedBy: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RoomMetadata {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
episode: number;
|
||||||
|
image?: string;
|
||||||
|
source?: string;
|
||||||
|
malId?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RoomData {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
host: RoomUser;
|
||||||
|
users: Map<string, RoomUser>;
|
||||||
|
createdAt: number;
|
||||||
|
currentVideo: {
|
||||||
|
animeId?: number;
|
||||||
|
episode?: number;
|
||||||
|
source?: string;
|
||||||
|
videoData?: any;
|
||||||
|
currentTime: number;
|
||||||
|
isPlaying: boolean;
|
||||||
|
context?: SourceContext;
|
||||||
|
} | null;
|
||||||
|
password?: string;
|
||||||
|
metadata?: RoomMetadata | null;
|
||||||
|
exposed: boolean;
|
||||||
|
publicUrl?: string;
|
||||||
|
queue: QueueItem[];
|
||||||
|
bannedIPs: Set<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_GUEST_PERMISSIONS: RoomPermissions = {
|
||||||
|
canControl: false,
|
||||||
|
canManageQueue: false
|
||||||
|
};
|
||||||
|
|
||||||
|
const rooms = new Map<string, RoomData>();
|
||||||
|
|
||||||
|
export function generateRoomId(): string {
|
||||||
|
return crypto.randomBytes(8).toString('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createRoom(name: string, host: RoomUser, password?: string, exposed = false, publicUrl?: string): RoomData {
|
||||||
|
const roomId = generateRoomId();
|
||||||
|
|
||||||
|
const room: RoomData = {
|
||||||
|
id: roomId,
|
||||||
|
name,
|
||||||
|
host,
|
||||||
|
users: new Map([[host.id, host]]),
|
||||||
|
createdAt: Date.now(),
|
||||||
|
currentVideo: null,
|
||||||
|
password: password || undefined,
|
||||||
|
metadata: null,
|
||||||
|
exposed,
|
||||||
|
publicUrl,
|
||||||
|
queue: [],
|
||||||
|
bannedIPs: new Set() // NUEVO
|
||||||
|
};
|
||||||
|
|
||||||
|
rooms.set(roomId, room);
|
||||||
|
return room;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateUserPermissions(roomId: string, userId: string, permissions: Partial<RoomPermissions>): boolean {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return false;
|
||||||
|
|
||||||
|
const user: any = room.users.get(userId);
|
||||||
|
if (!user) return false;
|
||||||
|
|
||||||
|
if (user.isHost) return false;
|
||||||
|
|
||||||
|
user.permissions = {
|
||||||
|
...user.permissions,
|
||||||
|
...permissions
|
||||||
|
};
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function banUserIP(roomId: string, ipAddress: string): boolean {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return false;
|
||||||
|
|
||||||
|
room.bannedIPs.add(ipAddress);
|
||||||
|
|
||||||
|
// Remover a todos los usuarios con esa IP
|
||||||
|
Array.from(room.users.values()).forEach(user => {
|
||||||
|
if (user.ipAddress === ipAddress) {
|
||||||
|
removeUserFromRoom(roomId, user.id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unbanUserIP(roomId: string, ipAddress: string): boolean {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return false;
|
||||||
|
|
||||||
|
return room.bannedIPs.delete(ipAddress);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isIPBanned(roomId: string, ipAddress: string): boolean {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return false;
|
||||||
|
return room.bannedIPs.has(ipAddress);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getBannedIPs(roomId: string): string[] {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return [];
|
||||||
|
return Array.from(room.bannedIPs);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasPermission(roomId: string, userId: string, permission: keyof RoomPermissions): boolean {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return false;
|
||||||
|
|
||||||
|
const user = room.users.get(userId);
|
||||||
|
if (!user) return false;
|
||||||
|
|
||||||
|
// El host siempre tiene todos los permisos
|
||||||
|
if (user.isHost) return true;
|
||||||
|
|
||||||
|
// Si no tiene permisos definidos, usar defaults
|
||||||
|
const userPerms = user.permissions || DEFAULT_GUEST_PERMISSIONS;
|
||||||
|
return userPerms[permission] || false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRoom(roomId: string): RoomData | null {
|
||||||
|
return rooms.get(roomId) || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllRooms(): RoomData[] {
|
||||||
|
return Array.from(rooms.values()).map(room => ({
|
||||||
|
...room,
|
||||||
|
users: room.users
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function addQueueItem(roomId: string, item: QueueItem): boolean {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return false;
|
||||||
|
room.queue.push(item);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeQueueItem(roomId: string, itemUid: string): boolean {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return false;
|
||||||
|
room.queue = room.queue.filter(i => i.uid !== itemUid);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getNextQueueItem(roomId: string): QueueItem | undefined {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room || room.queue.length === 0) return undefined;
|
||||||
|
return room.queue.shift(); // Saca el primero y lo retorna
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAndRemoveQueueItem(roomId: string, itemUid: string): QueueItem | undefined {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return undefined;
|
||||||
|
|
||||||
|
const index = room.queue.findIndex(i => i.uid === itemUid);
|
||||||
|
if (index === -1) return undefined;
|
||||||
|
|
||||||
|
const [item] = room.queue.splice(index, 1);
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function moveQueueItem(roomId: string, itemUid: string, direction: 'up' | 'down'): boolean {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return false;
|
||||||
|
|
||||||
|
const index = room.queue.findIndex(i => i.uid === itemUid);
|
||||||
|
if (index === -1) return false;
|
||||||
|
|
||||||
|
const newIndex = direction === 'up' ? index - 1 : index + 1;
|
||||||
|
|
||||||
|
if (newIndex < 0 || newIndex >= room.queue.length) return false;
|
||||||
|
|
||||||
|
const temp = room.queue[newIndex];
|
||||||
|
room.queue[newIndex] = room.queue[index];
|
||||||
|
room.queue[index] = temp;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function addUserToRoom(roomId: string, user: RoomUser): boolean {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return false;
|
||||||
|
|
||||||
|
room.users.set(user.id, user);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeUserFromRoom(roomId: string, userId: string): boolean {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return false;
|
||||||
|
|
||||||
|
room.users.delete(userId);
|
||||||
|
|
||||||
|
if (room.users.size === 0) {
|
||||||
|
if (room.exposed) {
|
||||||
|
closeTunnelIfUnused();
|
||||||
|
}
|
||||||
|
rooms.delete(roomId);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (room.host.id === userId && room.users.size > 0) {
|
||||||
|
const newHost = Array.from(room.users.values())[0];
|
||||||
|
newHost.isHost = true;
|
||||||
|
room.host = newHost;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateRoomVideo(roomId: string, videoData: any): boolean {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return false;
|
||||||
|
|
||||||
|
room.currentVideo = {
|
||||||
|
...room.currentVideo,
|
||||||
|
...videoData
|
||||||
|
};
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteRoom(roomId: string): boolean {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return false;
|
||||||
|
|
||||||
|
if (room.exposed) {
|
||||||
|
closeTunnelIfUnused();
|
||||||
|
}
|
||||||
|
|
||||||
|
return rooms.delete(roomId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function verifyRoomPassword(roomId: string, password?: string): boolean {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return false;
|
||||||
|
if (!room.password) return true;
|
||||||
|
if (!password) return false;
|
||||||
|
|
||||||
|
return room.password === password;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateRoomMetadata(roomId: string, metadata: any): boolean {
|
||||||
|
const room = rooms.get(roomId);
|
||||||
|
if (!room) return false;
|
||||||
|
|
||||||
|
room.metadata = metadata;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
588
desktop/src/api/rooms/rooms.websocket.ts
Normal file
@@ -0,0 +1,588 @@
|
|||||||
|
import { FastifyInstance, FastifyRequest } from 'fastify';
|
||||||
|
import * as roomService from './rooms.service';
|
||||||
|
import { getUserById } from '../user/user.service';
|
||||||
|
import jwt from 'jsonwebtoken';
|
||||||
|
|
||||||
|
import {getConfig} from '../../shared/config';
|
||||||
|
const { values } = getConfig();
|
||||||
|
const jwtSecret = values.server?.jwt_secret;
|
||||||
|
|
||||||
|
interface WSClient {
|
||||||
|
socket: any;
|
||||||
|
userId: string;
|
||||||
|
username: string;
|
||||||
|
roomId: string;
|
||||||
|
isGuest: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const clients = new Map<string, WSClient>();
|
||||||
|
|
||||||
|
|
||||||
|
function getClientIP(req: any): string {
|
||||||
|
return req.headers['x-forwarded-for']?.split(',')[0].trim() ||
|
||||||
|
req.headers['x-real-ip'] ||
|
||||||
|
req.connection?.remoteAddress ||
|
||||||
|
req.socket?.remoteAddress ||
|
||||||
|
'unknown';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setupRoomWebSocket(fastify: FastifyInstance) {
|
||||||
|
// @ts-ignore
|
||||||
|
fastify.get('/ws/room/:roomId', { websocket: true }, (connection: any, req: any) => {
|
||||||
|
handleWebSocketConnection(connection, req).catch(err => {
|
||||||
|
console.error('WebSocket error:', err);
|
||||||
|
try {
|
||||||
|
connection.socket.close();
|
||||||
|
} catch (e) {
|
||||||
|
// Socket already closed
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleWebSocketConnection(connection: any, req: any) {
|
||||||
|
const socket = connection.socket || connection;
|
||||||
|
const roomId = req.params.roomId;
|
||||||
|
const token = req.query.token;
|
||||||
|
const guestName = req.query.guestName;
|
||||||
|
const password = req.query.password;
|
||||||
|
const clientIP = getClientIP(req);
|
||||||
|
|
||||||
|
let userId: string;
|
||||||
|
let username: string;
|
||||||
|
let avatar: string | undefined;
|
||||||
|
let isGuest = false;
|
||||||
|
let realUserId: any;
|
||||||
|
|
||||||
|
const room = roomService.getRoom(roomId);
|
||||||
|
|
||||||
|
// 1. Validaciones básicas de existencia y Ban
|
||||||
|
if (!room) {
|
||||||
|
socket.send(JSON.stringify({ type: 'error', message: 'Room not found' }));
|
||||||
|
socket.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (roomService.isIPBanned(roomId, clientIP)) {
|
||||||
|
socket.send(JSON.stringify({ type: 'error', message: 'You have been banned from this room' }));
|
||||||
|
socket.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. MOVIDO ARRIBA: Autenticar usuario PRIMERO para saber quién es
|
||||||
|
if (token) {
|
||||||
|
try {
|
||||||
|
const decoded: any = jwt.verify(token, jwtSecret);
|
||||||
|
realUserId = decoded.id;
|
||||||
|
const user = await getUserById(realUserId);
|
||||||
|
|
||||||
|
if (user) {
|
||||||
|
userId = `user_${realUserId}`;
|
||||||
|
username = user.username;
|
||||||
|
avatar = user.profile_picture_url || undefined;
|
||||||
|
isGuest = false;
|
||||||
|
} else {
|
||||||
|
throw new Error('User not found');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
socket.send(JSON.stringify({ type: 'error', message: 'Invalid token' }));
|
||||||
|
socket.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else if (guestName && guestName.trim()) {
|
||||||
|
// ... (Lógica de Guest se mantiene igual) ...
|
||||||
|
const nameToCheck = guestName.trim();
|
||||||
|
const isNameTaken = Array.from(room.users.values()).some(
|
||||||
|
u => u.username.toLowerCase() === nameToCheck.toLowerCase()
|
||||||
|
);
|
||||||
|
if (isNameTaken) {
|
||||||
|
socket.send(JSON.stringify({ type: 'error', message: 'Username is already taken' }));
|
||||||
|
socket.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
userId = `guest_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||||
|
username = nameToCheck;
|
||||||
|
isGuest = true;
|
||||||
|
} else {
|
||||||
|
socket.send(JSON.stringify({ type: 'error', message: 'Authentication required' }));
|
||||||
|
socket.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Determinar si es Host
|
||||||
|
const isHost = room.host.userId === realUserId || room.host.id === userId;
|
||||||
|
|
||||||
|
// 4. MOVIDO ABAJO: Validar contraseña SOLO SI NO ES HOST
|
||||||
|
if (room.password && !isHost) {
|
||||||
|
if (!password || !roomService.verifyRoomPassword(roomId, password)) {
|
||||||
|
socket.send(JSON.stringify({ type: 'error', message: 'Invalid password' }));
|
||||||
|
socket.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const userInRoom = {
|
||||||
|
id: userId,
|
||||||
|
username,
|
||||||
|
avatar,
|
||||||
|
isHost: isHost,
|
||||||
|
isGuest,
|
||||||
|
userId: realUserId,
|
||||||
|
ipAddress: clientIP, // NUEVO
|
||||||
|
permissions: isHost ? undefined : { ...roomService.DEFAULT_GUEST_PERMISSIONS }
|
||||||
|
};
|
||||||
|
|
||||||
|
roomService.addUserToRoom(roomId, userInRoom);
|
||||||
|
|
||||||
|
// Registrar cliente
|
||||||
|
clients.set(userId, {
|
||||||
|
socket: socket,
|
||||||
|
userId,
|
||||||
|
username,
|
||||||
|
roomId,
|
||||||
|
isGuest
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.send(JSON.stringify({
|
||||||
|
type: 'init',
|
||||||
|
userId,
|
||||||
|
username,
|
||||||
|
isGuest,
|
||||||
|
isHost, // NUEVO: Enviar explícitamente
|
||||||
|
room: {
|
||||||
|
id: room.id,
|
||||||
|
name: room.name,
|
||||||
|
users: Array.from(room.users.values()).map(u => ({
|
||||||
|
id: u.id,
|
||||||
|
username: u.username,
|
||||||
|
avatar: u.avatar,
|
||||||
|
isHost: u.isHost,
|
||||||
|
isGuest: u.isGuest,
|
||||||
|
permissions: u.permissions // NUEVO
|
||||||
|
})),
|
||||||
|
currentVideo: room.currentVideo,
|
||||||
|
queue: room.queue || []
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Notificar a otros usuarios
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'user_joined',
|
||||||
|
user: {
|
||||||
|
id: userId,
|
||||||
|
username,
|
||||||
|
avatar,
|
||||||
|
isGuest
|
||||||
|
}
|
||||||
|
}, userId);
|
||||||
|
|
||||||
|
// Manejar mensajes
|
||||||
|
socket.on('message', (message: Buffer) => {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(message.toString());
|
||||||
|
handleMessage(roomId, userId, data);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('WebSocket message error:', err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Manejar desconexión
|
||||||
|
socket.on('close', () => {
|
||||||
|
clients.delete(userId);
|
||||||
|
roomService.removeUserFromRoom(roomId, userId);
|
||||||
|
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'user_left',
|
||||||
|
user: { userId, username }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMessage(roomId: string, userId: string, data: any) {
|
||||||
|
const room = roomService.getRoom(roomId);
|
||||||
|
if (!room) return;
|
||||||
|
|
||||||
|
const user = room.users.get(userId);
|
||||||
|
if (!user) return;
|
||||||
|
|
||||||
|
console.log('Handling message:', data.type, 'from user:', userId, 'isHost:', room.host.id === userId);
|
||||||
|
|
||||||
|
switch (data.type) {
|
||||||
|
case 'chat':
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'chat',
|
||||||
|
userId,
|
||||||
|
username: room.users.get(userId)?.username || 'Unknown',
|
||||||
|
avatar: room.users.get(userId)?.avatar,
|
||||||
|
message: data.message,
|
||||||
|
timestamp: Date.now()
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'update_permissions':
|
||||||
|
if (!user.isHost) {
|
||||||
|
console.warn('Non-host attempted to update permissions');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const success = roomService.updateUserPermissions(
|
||||||
|
roomId,
|
||||||
|
data.targetUserId,
|
||||||
|
data.permissions
|
||||||
|
);
|
||||||
|
|
||||||
|
if (success) {
|
||||||
|
const updatedRoom = roomService.getRoom(roomId);
|
||||||
|
if (updatedRoom) {
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'permissions_updated',
|
||||||
|
users: Array.from(updatedRoom.users.values()).map(u => ({
|
||||||
|
id: u.id,
|
||||||
|
username: u.username,
|
||||||
|
avatar: u.avatar,
|
||||||
|
isHost: u.isHost,
|
||||||
|
isGuest: u.isGuest,
|
||||||
|
permissions: u.permissions
|
||||||
|
}))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
// NUEVO: Baneo de usuarios (solo host)
|
||||||
|
case 'ban_user':
|
||||||
|
if (!user.isHost) {
|
||||||
|
console.warn('Non-host attempted to ban user');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetUser = room.users.get(data.targetUserId);
|
||||||
|
if (targetUser && targetUser.ipAddress) {
|
||||||
|
roomService.banUserIP(roomId, targetUser.ipAddress);
|
||||||
|
|
||||||
|
// Cerrar conexión del usuario baneado
|
||||||
|
const targetClient = clients.get(data.targetUserId);
|
||||||
|
if (targetClient && targetClient.socket) {
|
||||||
|
targetClient.socket.send(JSON.stringify({
|
||||||
|
type: 'banned',
|
||||||
|
message: 'You have been banned from this room'
|
||||||
|
}));
|
||||||
|
targetClient.socket.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
|
||||||
|
case 'queue_play_item':
|
||||||
|
if (!user.isHost && !roomService.hasPermission(roomId, userId, 'canManageQueue')) {
|
||||||
|
console.warn('User lacks permission for queue management');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemToPlay = roomService.getAndRemoveQueueItem(roomId, data.itemUid);
|
||||||
|
if (itemToPlay) {
|
||||||
|
const videoPayload = {
|
||||||
|
videoData: itemToPlay.videoData.videoData,
|
||||||
|
subtitles: itemToPlay.videoData.subtitles,
|
||||||
|
currentTime: 0,
|
||||||
|
isPlaying: true
|
||||||
|
};
|
||||||
|
|
||||||
|
roomService.updateRoomVideo(roomId, videoPayload);
|
||||||
|
roomService.updateRoomMetadata(roomId, itemToPlay.metadata);
|
||||||
|
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'video_update',
|
||||||
|
video: videoPayload,
|
||||||
|
metadata: itemToPlay.metadata
|
||||||
|
});
|
||||||
|
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'queue_update',
|
||||||
|
queue: room.queue
|
||||||
|
});
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'queue_move':
|
||||||
|
if (!user.isHost && !roomService.hasPermission(roomId, userId, 'canManageQueue')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const moved = roomService.moveQueueItem(roomId, data.itemUid, data.direction);
|
||||||
|
if (moved) {
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'queue_update',
|
||||||
|
queue: room.queue
|
||||||
|
});
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'request_sync':
|
||||||
|
// Cualquier usuario puede pedir sync
|
||||||
|
const host = clients.get(room.host.id);
|
||||||
|
if (host && host.socket && host.socket.readyState === 1) {
|
||||||
|
console.log(`[Sync Request] User ${userId} requested sync from host`);
|
||||||
|
|
||||||
|
host.socket.send(JSON.stringify({
|
||||||
|
type: 'sync_requested',
|
||||||
|
requestedBy: userId,
|
||||||
|
username: room.users.get(userId)?.username
|
||||||
|
}));
|
||||||
|
} else {
|
||||||
|
console.warn(`[Sync Request] Host not available for user ${userId}`);
|
||||||
|
|
||||||
|
if (room.currentVideo) {
|
||||||
|
const client = clients.get(userId);
|
||||||
|
if (client && client.socket && client.socket.readyState === 1) {
|
||||||
|
console.log(`[Sync Request] Sending cached video state to ${userId}`);
|
||||||
|
client.socket.send(JSON.stringify({
|
||||||
|
type: 'sync',
|
||||||
|
currentTime: room.currentVideo.currentTime || 0,
|
||||||
|
isPlaying: room.currentVideo.isPlaying || false
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'video_update':
|
||||||
|
const canUpdateVideo = user.isHost ||
|
||||||
|
roomService.hasPermission(roomId, userId, 'canControl') ||
|
||||||
|
roomService.hasPermission(roomId, userId, 'canManageQueue');
|
||||||
|
|
||||||
|
if (!canUpdateVideo) {
|
||||||
|
console.warn('User lacks permissions to update video');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
roomService.updateRoomVideo(roomId, data.video);
|
||||||
|
roomService.updateRoomMetadata(roomId, data.metadata);
|
||||||
|
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'video_update',
|
||||||
|
video: data.video,
|
||||||
|
metadata: data.metadata
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'queue_add_batch':
|
||||||
|
if (!user.isHost && !roomService.hasPermission(roomId, userId, 'canManageQueue')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(data.items)) {
|
||||||
|
data.items.forEach((item: any, i: number) => {
|
||||||
|
const newItem = {
|
||||||
|
uid: `q_${Date.now()}_${i}_${Math.random().toString(36).substr(2, 5)}`,
|
||||||
|
metadata: item.metadata,
|
||||||
|
videoData: item.video,
|
||||||
|
addedBy: room.users.get(userId)?.username || 'Unknown'
|
||||||
|
};
|
||||||
|
roomService.addQueueItem(roomId, newItem);
|
||||||
|
});
|
||||||
|
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'queue_update',
|
||||||
|
queue: room.queue
|
||||||
|
});
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'sync':
|
||||||
|
if (room.host.id !== userId) return;
|
||||||
|
|
||||||
|
if (room.currentVideo) {
|
||||||
|
room.currentVideo.currentTime = data.currentTime;
|
||||||
|
room.currentVideo.isPlaying = data.isPlaying;
|
||||||
|
}
|
||||||
|
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'sync',
|
||||||
|
currentTime: data.currentTime,
|
||||||
|
isPlaying: data.isPlaying
|
||||||
|
}, userId);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'request_users':
|
||||||
|
const currentRoom = roomService.getRoom(roomId);
|
||||||
|
if (currentRoom) {
|
||||||
|
const client = clients.get(userId);
|
||||||
|
if (client && client.socket && client.socket.readyState === 1) {
|
||||||
|
client.socket.send(JSON.stringify({
|
||||||
|
type: 'users_update', // Nuevo tipo de respuesta
|
||||||
|
users: Array.from(currentRoom.users.values()).map(u => ({
|
||||||
|
id: u.id,
|
||||||
|
username: u.username,
|
||||||
|
avatar: u.avatar,
|
||||||
|
isHost: u.isHost,
|
||||||
|
isGuest: u.isGuest
|
||||||
|
}))
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'play':
|
||||||
|
if (!user.isHost && !roomService.hasPermission(roomId, userId, 'canControl')) {
|
||||||
|
console.warn('User lacks control permissions');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'play',
|
||||||
|
currentTime: data.currentTime,
|
||||||
|
timestamp: Date.now()
|
||||||
|
}, userId);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'pause':
|
||||||
|
if (!user.isHost && !roomService.hasPermission(roomId, userId, 'canControl')) {
|
||||||
|
console.warn('User lacks control permissions for pause');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Broadcasting pause event to room:', roomId);
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'pause',
|
||||||
|
currentTime: data.currentTime,
|
||||||
|
timestamp: Date.now()
|
||||||
|
}, userId);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'seek':
|
||||||
|
if (!user.isHost && !roomService.hasPermission(roomId, userId, 'canControl')) {
|
||||||
|
console.warn('User lacks control permissions for seek');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Broadcasting seek event to room:', roomId);
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'seek',
|
||||||
|
currentTime: data.currentTime,
|
||||||
|
timestamp: Date.now()
|
||||||
|
}, userId);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'request_state':
|
||||||
|
const client = clients.get(userId);
|
||||||
|
if (client && client.socket && client.socket.readyState === 1) {
|
||||||
|
const updatedRoom = roomService.getRoom(roomId);
|
||||||
|
if (updatedRoom) {
|
||||||
|
client.socket.send(JSON.stringify({
|
||||||
|
type: 'init',
|
||||||
|
userId,
|
||||||
|
username: client.username,
|
||||||
|
isGuest: client.isGuest,
|
||||||
|
room: {
|
||||||
|
id: updatedRoom.id,
|
||||||
|
name: updatedRoom.name,
|
||||||
|
users: Array.from(updatedRoom.users.values()).map(u => ({
|
||||||
|
id: u.id,
|
||||||
|
username: u.username,
|
||||||
|
avatar: u.avatar,
|
||||||
|
isHost: u.isHost,
|
||||||
|
isGuest: u.isGuest
|
||||||
|
})),
|
||||||
|
currentVideo: room.currentVideo,
|
||||||
|
metadata: room.metadata
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'queue_add':
|
||||||
|
if (!user.isHost && !roomService.hasPermission(roomId, userId, 'canManageQueue')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const newItem = {
|
||||||
|
uid: `q_${Date.now()}_${Math.random().toString(36).substr(2, 5)}`,
|
||||||
|
metadata: data.metadata,
|
||||||
|
videoData: data.video,
|
||||||
|
addedBy: room.users.get(userId)?.username || 'Unknown'
|
||||||
|
};
|
||||||
|
|
||||||
|
roomService.addQueueItem(roomId, newItem);
|
||||||
|
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'queue_update',
|
||||||
|
queue: room.queue
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'queue_remove':
|
||||||
|
if (!user.isHost && !roomService.hasPermission(roomId, userId, 'canManageQueue')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
roomService.removeQueueItem(roomId, data.itemUid);
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'queue_update',
|
||||||
|
queue: room.queue
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'play_next':
|
||||||
|
if (room.host.id !== userId) return;
|
||||||
|
|
||||||
|
const nextItem = roomService.getNextQueueItem(roomId);
|
||||||
|
if (nextItem) {
|
||||||
|
const videoPayload = {
|
||||||
|
videoData: nextItem.videoData.videoData,
|
||||||
|
subtitles: nextItem.videoData.subtitles,
|
||||||
|
currentTime: 0,
|
||||||
|
isPlaying: true
|
||||||
|
};
|
||||||
|
|
||||||
|
roomService.updateRoomVideo(roomId, videoPayload);
|
||||||
|
roomService.updateRoomMetadata(roomId, nextItem.metadata);
|
||||||
|
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'video_update',
|
||||||
|
video: videoPayload,
|
||||||
|
metadata: nextItem.metadata
|
||||||
|
});
|
||||||
|
|
||||||
|
broadcastToRoom(roomId, {
|
||||||
|
type: 'queue_update',
|
||||||
|
queue: room.queue
|
||||||
|
});
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
console.warn('Unknown message type:', data.type);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function broadcastToRoom(roomId: string, message: any, excludeUserId?: string) {
|
||||||
|
const room = roomService.getRoom(roomId);
|
||||||
|
if (!room) return;
|
||||||
|
|
||||||
|
const messageStr = JSON.stringify(message);
|
||||||
|
|
||||||
|
console.log('Broadcasting to room:', roomId, 'message type:', message.type, 'excluding:', excludeUserId);
|
||||||
|
|
||||||
|
let sentCount = 0;
|
||||||
|
room.users.forEach((user) => {
|
||||||
|
if (user.id !== excludeUserId) {
|
||||||
|
const client = clients.get(user.id);
|
||||||
|
if (client && client.socket && client.socket.readyState === 1) {
|
||||||
|
try {
|
||||||
|
client.socket.send(messageStr);
|
||||||
|
sentCount++;
|
||||||
|
console.log('Sent to user:', user.id, user.username);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error sending message to user:', user.id, err);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.warn('User socket not ready:', user.id, 'readyState:', client?.socket?.readyState);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`Broadcast complete: sent to ${sentCount} users`);
|
||||||
|
}
|
||||||
111
desktop/src/api/rooms/tunnel.manager.ts
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
import { spawn, ChildProcess } from "child_process";
|
||||||
|
import { getConfig as loadConfig } from '../../shared/config';
|
||||||
|
const { values } = loadConfig();
|
||||||
|
const CLOUDFLARED_PATH = values.paths?.cloudflared || 'cloudflared';
|
||||||
|
|
||||||
|
let tunnelProcess: ChildProcess | null = null;
|
||||||
|
let exposedRooms = 0;
|
||||||
|
let publicUrl: string | null = null;
|
||||||
|
let tunnelPromise: Promise<string> | null = null;
|
||||||
|
|
||||||
|
export function openTunnel(): Promise<string> {
|
||||||
|
if (tunnelProcess && publicUrl) {
|
||||||
|
exposedRooms++;
|
||||||
|
return Promise.resolve(publicUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tunnelPromise) {
|
||||||
|
return tunnelPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
tunnelPromise = new Promise((resolve, reject) => {
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
cleanup();
|
||||||
|
reject(new Error("Timeout esperando URL del túnel (30s)"));
|
||||||
|
}, 30000);
|
||||||
|
|
||||||
|
tunnelProcess = spawn(CLOUDFLARED_PATH, [
|
||||||
|
"tunnel",
|
||||||
|
"--url",
|
||||||
|
"http://localhost:54322",
|
||||||
|
"--no-autoupdate"
|
||||||
|
]);
|
||||||
|
|
||||||
|
const cleanup = () => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
tunnelPromise = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
let outputBuffer = "";
|
||||||
|
|
||||||
|
const processOutput = (data: Buffer) => {
|
||||||
|
const text = data.toString();
|
||||||
|
outputBuffer += text;
|
||||||
|
|
||||||
|
const match = outputBuffer.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/);
|
||||||
|
if (match && !publicUrl) {
|
||||||
|
publicUrl = match[0];
|
||||||
|
exposedRooms = 1;
|
||||||
|
cleanup();
|
||||||
|
resolve(publicUrl);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
tunnelProcess.stdout?.on("data", (data) => {
|
||||||
|
processOutput(data);
|
||||||
|
});
|
||||||
|
|
||||||
|
tunnelProcess.stderr?.on("data", (data) => {
|
||||||
|
processOutput(data);
|
||||||
|
});
|
||||||
|
|
||||||
|
tunnelProcess.on("error", (error) => {
|
||||||
|
console.error("[Cloudflared Process Error]", error);
|
||||||
|
cleanup();
|
||||||
|
tunnelProcess = null;
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
|
||||||
|
tunnelProcess.on("exit", (code, signal) => {
|
||||||
|
tunnelProcess = null;
|
||||||
|
publicUrl = null;
|
||||||
|
exposedRooms = 0;
|
||||||
|
|
||||||
|
if (!publicUrl) {
|
||||||
|
cleanup();
|
||||||
|
reject(new Error(`Proceso cloudflared terminó antes de obtener URL (código: ${code})`));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return tunnelPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function closeTunnelIfUnused() {
|
||||||
|
exposedRooms--;
|
||||||
|
console.log(`[Tunnel Manager] Rooms expuestas: ${exposedRooms}`);
|
||||||
|
|
||||||
|
if (exposedRooms <= 0 && tunnelProcess) {
|
||||||
|
console.log("[Tunnel Manager] Cerrando túnel...");
|
||||||
|
tunnelProcess.kill();
|
||||||
|
tunnelProcess = null;
|
||||||
|
publicUrl = null;
|
||||||
|
exposedRooms = 0;
|
||||||
|
tunnelPromise = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTunnelUrl(): string | null {
|
||||||
|
return publicUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function forceTunnelClose() {
|
||||||
|
if (tunnelProcess) {
|
||||||
|
console.log("[Tunnel Manager] Forzando cierre del túnel...");
|
||||||
|
tunnelProcess.kill();
|
||||||
|
tunnelProcess = null;
|
||||||
|
publicUrl = null;
|
||||||
|
exposedRooms = 0;
|
||||||
|
tunnelPromise = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
97
desktop/src/api/rpc/rp.service.ts
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
import { Client } from "@xhayper/discord-rpc";
|
||||||
|
|
||||||
|
let rpcClient: Client | null = null;
|
||||||
|
let reconnectTimer: NodeJS.Timeout | null = null;
|
||||||
|
let connected = false;
|
||||||
|
|
||||||
|
interface RPCData {
|
||||||
|
details?: string;
|
||||||
|
state?: string;
|
||||||
|
mode?: string;
|
||||||
|
startTimestamp?: number;
|
||||||
|
endTimestamp?: number;
|
||||||
|
paused?: boolean;
|
||||||
|
version?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function attemptReconnect(clientId: string) {
|
||||||
|
connected = false;
|
||||||
|
|
||||||
|
if (reconnectTimer) {
|
||||||
|
clearTimeout(reconnectTimer);
|
||||||
|
reconnectTimer = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Discord RPC: Trying to reconnect...');
|
||||||
|
|
||||||
|
reconnectTimer = setTimeout(() => {
|
||||||
|
initRPC(clientId);
|
||||||
|
}, 10000);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function initRPC(clientId: string) {
|
||||||
|
if (rpcClient) {
|
||||||
|
try { rpcClient.destroy(); } catch {}
|
||||||
|
rpcClient = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reconnectTimer) {
|
||||||
|
clearTimeout(reconnectTimer);
|
||||||
|
reconnectTimer = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
rpcClient = new Client({ clientId });
|
||||||
|
|
||||||
|
rpcClient.on("ready", () => {
|
||||||
|
connected = true;
|
||||||
|
console.log("Discord RPC conectado");
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
setActivity({ details: "Browsing", state: "In App" });
|
||||||
|
}, 1000);
|
||||||
|
});
|
||||||
|
|
||||||
|
rpcClient.on("disconnected", () => {
|
||||||
|
connected = false;
|
||||||
|
attemptReconnect(clientId);
|
||||||
|
});
|
||||||
|
|
||||||
|
rpcClient.on("error", () => {
|
||||||
|
if (connected) attemptReconnect(clientId);
|
||||||
|
});
|
||||||
|
|
||||||
|
rpcClient.login().catch(() => {
|
||||||
|
attemptReconnect(clientId);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setActivity(data: RPCData = {}) {
|
||||||
|
if (!rpcClient || !connected) return;
|
||||||
|
|
||||||
|
let type = 0;
|
||||||
|
if (data.mode === "watching") type = 3;
|
||||||
|
if (data.mode === "reading") type = 0;
|
||||||
|
|
||||||
|
const activity: any = {
|
||||||
|
details: data.details,
|
||||||
|
state: data.state,
|
||||||
|
type,
|
||||||
|
instance: false
|
||||||
|
};
|
||||||
|
|
||||||
|
if (data.paused) {
|
||||||
|
activity.largeImageText = "⏸ ";
|
||||||
|
delete activity.startTimestamp;
|
||||||
|
delete activity.endTimestamp;
|
||||||
|
} else {
|
||||||
|
activity.largeImageKey = "bigpicture";
|
||||||
|
activity.largeImageText = data.version ?? "v2.0.0";
|
||||||
|
|
||||||
|
if (data.startTimestamp && data.endTimestamp) {
|
||||||
|
activity.startTimestamp = data.startTimestamp;
|
||||||
|
activity.endTimestamp = data.endTimestamp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rpcClient.user?.setActivity(activity);
|
||||||
|
}
|
||||||
@@ -11,16 +11,29 @@ export function init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function setRPC(request: FastifyRequest, reply: FastifyReply) {
|
export async function setRPC(request: FastifyRequest, reply: FastifyReply) {
|
||||||
const { details, state, mode } = request.body as {
|
const {
|
||||||
|
details,
|
||||||
|
state,
|
||||||
|
mode,
|
||||||
|
startTimestamp,
|
||||||
|
endTimestamp,
|
||||||
|
paused
|
||||||
|
} = request.body as {
|
||||||
details?: string;
|
details?: string;
|
||||||
state?: string;
|
state?: string;
|
||||||
mode?: "watching" | "reading" | string;
|
mode?: "watching" | "reading" | string;
|
||||||
|
startTimestamp?: number;
|
||||||
|
endTimestamp?: number;
|
||||||
|
paused?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
setActivity({
|
setActivity({
|
||||||
details,
|
details,
|
||||||
state,
|
state,
|
||||||
mode
|
mode,
|
||||||
|
startTimestamp,
|
||||||
|
endTimestamp,
|
||||||
|
paused
|
||||||
});
|
});
|
||||||
|
|
||||||
return reply.send({ ok: true });
|
return reply.send({ ok: true });
|
||||||
@@ -62,6 +62,7 @@ export interface ExtensionSearchOptions {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface ExtensionSearchResult {
|
export interface ExtensionSearchResult {
|
||||||
|
url: string;
|
||||||
format: string;
|
format: string;
|
||||||
headers: any;
|
headers: any;
|
||||||
id: string;
|
id: string;
|
||||||
@@ -79,6 +80,7 @@ export interface Episode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface Chapter {
|
export interface Chapter {
|
||||||
|
language?: string | null;
|
||||||
index: number;
|
index: number;
|
||||||
id: string;
|
id: string;
|
||||||
number: string | number;
|
number: string | number;
|
||||||
@@ -97,7 +99,7 @@ export interface Extension {
|
|||||||
mediaType?: 'manga' | 'ln';
|
mediaType?: 'manga' | 'ln';
|
||||||
search?: (options: ExtensionSearchOptions) => Promise<ExtensionSearchResult[]>;
|
search?: (options: ExtensionSearchOptions) => Promise<ExtensionSearchResult[]>;
|
||||||
findEpisodes?: (id: string) => Promise<Episode[]>;
|
findEpisodes?: (id: string) => Promise<Episode[]>;
|
||||||
findEpisodeServer?: (episode: Episode, server: string) => Promise<any>;
|
findEpisodeServer?: (s: any, server1: string | undefined, category: string | undefined) => Promise<any>;
|
||||||
findChapters?: (id: string) => Promise<Chapter[]>;
|
findChapters?: (id: string) => Promise<Chapter[]>;
|
||||||
findChapterPages?: (chapterId: string) => Promise<any>;
|
findChapterPages?: (chapterId: string) => Promise<any>;
|
||||||
getSettings?: () => ExtensionSettings;
|
getSettings?: () => ExtensionSettings;
|
||||||
@@ -157,6 +159,7 @@ export interface WatchStreamQuery {
|
|||||||
server?: string;
|
server?: string;
|
||||||
category?: string;
|
category?: string;
|
||||||
ext: string;
|
ext: string;
|
||||||
|
extensionAnimeId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface BookParams {
|
export interface BookParams {
|
||||||
@@ -2,6 +2,10 @@ import { FastifyReply, FastifyRequest } from 'fastify';
|
|||||||
import * as userService from './user.service';
|
import * as userService from './user.service';
|
||||||
import {queryOne} from '../../shared/database';
|
import {queryOne} from '../../shared/database';
|
||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
|
import { getConfig } from '../../shared/config';
|
||||||
|
const { values } = getConfig();
|
||||||
|
const jwtSecret = values.server?.jwt_secret;
|
||||||
|
|
||||||
|
|
||||||
interface UserIdParams { id: string; }
|
interface UserIdParams { id: string; }
|
||||||
interface CreateUserBody {
|
interface CreateUserBody {
|
||||||
@@ -75,7 +79,7 @@ export async function login(req: FastifyRequest, reply: FastifyReply) {
|
|||||||
|
|
||||||
const token = jwt.sign(
|
const token = jwt.sign(
|
||||||
{ id: userId },
|
{ id: userId },
|
||||||
process.env.JWT_SECRET!,
|
jwtSecret,
|
||||||
{ expiresIn: "7d" }
|
{ expiresIn: "7d" }
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -168,20 +172,39 @@ export async function deleteUser(req: FastifyRequest, reply: FastifyReply) {
|
|||||||
const { id } = req.params as { id: string };
|
const { id } = req.params as { id: string };
|
||||||
const userId = parseInt(id, 10);
|
const userId = parseInt(id, 10);
|
||||||
|
|
||||||
|
const body = (req.body ?? {}) as { password?: string };
|
||||||
|
const password = body.password;
|
||||||
|
|
||||||
if (!userId || isNaN(userId)) {
|
if (!userId || isNaN(userId)) {
|
||||||
return reply.code(400).send({ error: "Invalid user id" });
|
return reply.code(400).send({ error: "Invalid user id" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await userService.deleteUser(userId);
|
const user = await userService.getUserById(userId);
|
||||||
|
if (!user) {
|
||||||
if (result && result.changes > 0) {
|
|
||||||
return { success: true, message: "User deleted successfully" };
|
|
||||||
} else {
|
|
||||||
return reply.code(404).send({ error: "User not found" });
|
return reply.code(404).send({ error: "User not found" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (user.has_password) {
|
||||||
|
if (!password) {
|
||||||
|
return reply.code(401).send({ error: "Password required" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = await userService.verifyPassword(userId, password);
|
||||||
|
if (!isValid) {
|
||||||
|
return reply.code(401).send({ error: "Incorrect password" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await userService.deleteUser(userId);
|
||||||
|
|
||||||
|
if (result.changes > 0) {
|
||||||
|
return reply.send({ success: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
return reply.code(500).send({ error: "Failed to delete user" });
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Delete User Error:", (err as Error).message);
|
console.error("Delete User Error:", err);
|
||||||
return reply.code(500).send({ error: "Failed to delete user" });
|
return reply.code(500).send({ error: "Failed to delete user" });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -246,16 +269,17 @@ export async function changePassword(req: FastifyRequest, reply: FastifyReply) {
|
|||||||
return reply.code(404).send({ error: "User not found" });
|
return reply.code(404).send({ error: "User not found" });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Si el usuario tiene contraseña actual, debe proporcionar la contraseña actual
|
if (user.has_password) {
|
||||||
if (user.has_password && currentPassword) {
|
if (!currentPassword) {
|
||||||
const isValid = await userService.verifyPassword(userId, currentPassword);
|
return reply.code(401).send({ error: "Current password required" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = await userService.verifyPassword(userId, currentPassword);
|
||||||
if (!isValid) {
|
if (!isValid) {
|
||||||
return reply.code(401).send({ error: "Current password is incorrect" });
|
return reply.code(401).send({ error: "Current password is incorrect" });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualizar la contraseña (null para eliminarla, string para establecerla)
|
|
||||||
await userService.updateUser(userId, { password: newPassword });
|
await userService.updateUser(userId, { password: newPassword });
|
||||||
|
|
||||||
return reply.send({
|
return reply.send({
|
||||||
186
desktop/src/api/user/user.service.ts
Normal file
@@ -0,0 +1,186 @@
|
|||||||
|
import {queryAll, queryOne, run} from '../../shared/database';
|
||||||
|
import bcrypt from 'bcryptjs';
|
||||||
|
|
||||||
|
const USER_DB_NAME = 'userdata';
|
||||||
|
const SALT_ROUNDS = 10;
|
||||||
|
|
||||||
|
interface User {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
profile_picture_url: string | null;
|
||||||
|
has_password: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function userExists(id: number): Promise<boolean> {
|
||||||
|
const sql = 'SELECT 1 FROM User WHERE id = ?';
|
||||||
|
const row = await queryOne(sql, [id], USER_DB_NAME);
|
||||||
|
return !!row;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createUser(username: string, profilePictureUrl?: string, password?: string): Promise<{ lastID: number }> {
|
||||||
|
let passwordHash = null;
|
||||||
|
|
||||||
|
if (password && password.trim()) {
|
||||||
|
passwordHash = await bcrypt.hash(password.trim(), SALT_ROUNDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sql = `
|
||||||
|
INSERT INTO User (username, profile_picture_url, password_hash)
|
||||||
|
VALUES (?, ?, ?)
|
||||||
|
`;
|
||||||
|
const params = [username, profilePictureUrl || null, passwordHash];
|
||||||
|
|
||||||
|
const result = await run(sql, params, USER_DB_NAME);
|
||||||
|
|
||||||
|
return { lastID: result.lastID };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateUser(userId: number, updates: any): Promise<any> {
|
||||||
|
const fields: string[] = [];
|
||||||
|
const values: (string | number | null)[] = [];
|
||||||
|
|
||||||
|
if (updates.username !== undefined) {
|
||||||
|
fields.push('username = ?');
|
||||||
|
values.push(updates.username);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (updates.profilePictureUrl !== undefined) {
|
||||||
|
fields.push('profile_picture_url = ?');
|
||||||
|
values.push(updates.profilePictureUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (updates.password !== undefined) {
|
||||||
|
if (updates.password === null || updates.password === '') {
|
||||||
|
// Eliminar contraseña
|
||||||
|
fields.push('password_hash = ?');
|
||||||
|
values.push(null);
|
||||||
|
} else {
|
||||||
|
// Actualizar contraseña
|
||||||
|
const hash = await bcrypt.hash(updates.password.trim(), SALT_ROUNDS);
|
||||||
|
fields.push('password_hash = ?');
|
||||||
|
values.push(hash);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fields.length === 0) {
|
||||||
|
return { changes: 0, lastID: userId };
|
||||||
|
}
|
||||||
|
|
||||||
|
const setClause = fields.join(', ');
|
||||||
|
const sql = `UPDATE User SET ${setClause} WHERE id = ?`;
|
||||||
|
values.push(userId);
|
||||||
|
|
||||||
|
return await run(sql, values, USER_DB_NAME);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteUser(userId: number): Promise<any> {
|
||||||
|
await run(
|
||||||
|
`DELETE FROM ListEntry WHERE user_id = ?`,
|
||||||
|
[userId],
|
||||||
|
USER_DB_NAME
|
||||||
|
);
|
||||||
|
|
||||||
|
await run(
|
||||||
|
`DELETE FROM UserIntegration WHERE user_id = ?`,
|
||||||
|
[userId],
|
||||||
|
USER_DB_NAME
|
||||||
|
);
|
||||||
|
|
||||||
|
await run(
|
||||||
|
`DELETE FROM favorites WHERE user_id = ?`,
|
||||||
|
[userId],
|
||||||
|
'favorites'
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await run(
|
||||||
|
`DELETE FROM User WHERE id = ?`,
|
||||||
|
[userId],
|
||||||
|
USER_DB_NAME
|
||||||
|
);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAllUsers(): Promise<User[]> {
|
||||||
|
const sql = `
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
username,
|
||||||
|
profile_picture_url,
|
||||||
|
CASE WHEN password_hash IS NOT NULL THEN 1 ELSE 0 END as has_password
|
||||||
|
FROM User
|
||||||
|
ORDER BY id
|
||||||
|
`;
|
||||||
|
|
||||||
|
const users = await queryAll(sql, [], USER_DB_NAME);
|
||||||
|
|
||||||
|
return users.map((user: any) => ({
|
||||||
|
id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
profile_picture_url: user.profile_picture_url || null,
|
||||||
|
has_password: !!user.has_password
|
||||||
|
})) as User[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUserById(id: number): Promise<User | null> {
|
||||||
|
const sql = `
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
username,
|
||||||
|
profile_picture_url,
|
||||||
|
CASE WHEN password_hash IS NOT NULL THEN 1 ELSE 0 END as has_password
|
||||||
|
FROM User
|
||||||
|
WHERE id = ?
|
||||||
|
`;
|
||||||
|
|
||||||
|
const user = await queryOne(sql, [id], USER_DB_NAME);
|
||||||
|
|
||||||
|
if (!user) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
profile_picture_url: user.profile_picture_url || null,
|
||||||
|
has_password: !!user.has_password
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function verifyPassword(userId: number, password: string): Promise<boolean> {
|
||||||
|
const sql = 'SELECT password_hash FROM User WHERE id = ?';
|
||||||
|
const user = await queryOne(sql, [userId], USER_DB_NAME);
|
||||||
|
|
||||||
|
if (!user || !user.password_hash) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await bcrypt.compare(password, user.password_hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAniListIntegration(userId: number) {
|
||||||
|
const sql = `
|
||||||
|
SELECT anilist_user_id, expires_at
|
||||||
|
FROM UserIntegration
|
||||||
|
WHERE user_id = ? AND platform = ?
|
||||||
|
`;
|
||||||
|
|
||||||
|
const row = await queryOne(sql, [userId, "AniList"], USER_DB_NAME);
|
||||||
|
|
||||||
|
if (!row) {
|
||||||
|
return { connected: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
connected: true,
|
||||||
|
anilistUserId: row.anilist_user_id,
|
||||||
|
expiresAt: row.expires_at
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removeAniListIntegration(userId: number) {
|
||||||
|
const sql = `
|
||||||
|
DELETE FROM UserIntegration
|
||||||
|
WHERE user_id = ? AND platform = ?
|
||||||
|
`;
|
||||||
|
|
||||||
|
return run(sql, [userId, "AniList"], USER_DB_NAME);
|
||||||
|
}
|
||||||
@@ -92,6 +92,7 @@ function startHeroCycle() {
|
|||||||
|
|
||||||
async function updateHeroUI(anime) {
|
async function updateHeroUI(anime) {
|
||||||
if(!anime) return;
|
if(!anime) return;
|
||||||
|
anime.entry_type = 'ANIME';
|
||||||
|
|
||||||
const title = anime.title.english || anime.title.romaji || "Unknown Title";
|
const title = anime.title.english || anime.title.romaji || "Unknown Title";
|
||||||
const score = anime.averageScore ? anime.averageScore + '% Match' : 'N/A';
|
const score = anime.averageScore ? anime.averageScore + '% Match' : 'N/A';
|
||||||
408
desktop/src/scripts/anime/entry.js
Normal file
@@ -0,0 +1,408 @@
|
|||||||
|
let animeData = null;
|
||||||
|
let extensionName = null;
|
||||||
|
|
||||||
|
let animeId = null;
|
||||||
|
let isLocal = false;
|
||||||
|
|
||||||
|
const episodePagination = Object.create(PaginationManager);
|
||||||
|
episodePagination.init(50, renderEpisodes);
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
loadAnimeData();
|
||||||
|
setupDescriptionModal();
|
||||||
|
setupEpisodeSearch();
|
||||||
|
|
||||||
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
|
const initialEp = urlParams.get('episode');
|
||||||
|
|
||||||
|
if (initialEp) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (animeData) {
|
||||||
|
|
||||||
|
const source = isLocal ? 'local' : (extensionName || 'anilist');
|
||||||
|
|
||||||
|
if (typeof AnimePlayer !== 'undefined') {
|
||||||
|
AnimePlayer.init(animeId, source, isLocal, animeData);
|
||||||
|
AnimePlayer.playEpisode(parseInt(initialEp));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 800);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
async function loadAnimeData() {
|
||||||
|
try {
|
||||||
|
|
||||||
|
const pathParts = window.location.pathname.split('/');
|
||||||
|
|
||||||
|
const cleanParts = pathParts.filter(p => p.length > 0);
|
||||||
|
|
||||||
|
if (cleanParts.length >= 3 && cleanParts[0] === 'anime') {
|
||||||
|
|
||||||
|
extensionName = cleanParts[1];
|
||||||
|
animeId = cleanParts[2];
|
||||||
|
} else if (cleanParts.length === 2 && cleanParts[0] === 'anime') {
|
||||||
|
|
||||||
|
extensionName = null;
|
||||||
|
|
||||||
|
animeId = cleanParts[1];
|
||||||
|
} else {
|
||||||
|
showError("Invalid URL Format");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const localRes = await fetch(`/api/library/anime/${animeId}`);
|
||||||
|
if (localRes.ok) isLocal = true;
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
const fetchUrl = extensionName
|
||||||
|
? `/api/anime/${animeId}?source=${extensionName}`
|
||||||
|
: `/api/anime/${animeId}?source=anilist`;
|
||||||
|
|
||||||
|
const res = await fetch(fetchUrl, { headers: AuthUtils.getSimpleAuthHeaders() });
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (data.error) {
|
||||||
|
showError("Anime Not Found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
animeData = data;
|
||||||
|
animeData.entry_type = 'ANIME';
|
||||||
|
|
||||||
|
const metadata = MediaMetadataUtils.formatAnimeData(data, !!extensionName);
|
||||||
|
|
||||||
|
document.title = `${metadata.title} | WaifuBoard`;
|
||||||
|
document.getElementById('title').innerText = metadata.title;
|
||||||
|
if (metadata.poster) document.getElementById('poster').src = metadata.poster;
|
||||||
|
|
||||||
|
document.getElementById('score').innerText = `${metadata.score}% Score`;
|
||||||
|
document.getElementById('year').innerText = metadata.year;
|
||||||
|
document.getElementById('genres').innerText = metadata.genres.split(',').join(' • ');
|
||||||
|
document.getElementById('format').innerText = metadata.format;
|
||||||
|
document.getElementById('status').innerText = metadata.status;
|
||||||
|
document.getElementById('season').innerText = metadata.season;
|
||||||
|
document.getElementById('studio').innerText = metadata.studio;
|
||||||
|
document.getElementById('episodes').innerText = `${metadata.episodes} Ep`;
|
||||||
|
|
||||||
|
updateLocalPill();
|
||||||
|
updateDescription(data.description || data.summary);
|
||||||
|
updateRelations(data.relations?.edges);
|
||||||
|
updateCharacters(metadata.characters);
|
||||||
|
updateRecommendations(data.recommendations?.nodes);
|
||||||
|
|
||||||
|
const source = isLocal ? 'local' : (extensionName || 'anilist');
|
||||||
|
|
||||||
|
if (typeof AnimePlayer !== 'undefined') {
|
||||||
|
AnimePlayer.init(animeId, source, isLocal, animeData);
|
||||||
|
}
|
||||||
|
|
||||||
|
YouTubePlayerUtils.init('trailer-player');
|
||||||
|
YouTubePlayerUtils.playTrailer(metadata.trailer, 'trailer-player', metadata.banner);
|
||||||
|
|
||||||
|
const watchBtn = document.getElementById('watch-btn');
|
||||||
|
if (watchBtn) {
|
||||||
|
watchBtn.onclick = () => {
|
||||||
|
if (typeof AnimePlayer !== 'undefined') AnimePlayer.playEpisode(1);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const total = metadata.episodes || 12;
|
||||||
|
setupEpisodes(total);
|
||||||
|
|
||||||
|
setupAddToListButton();
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error loading anime details:', err);
|
||||||
|
showError("Error loading anime");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateLocalPill() {
|
||||||
|
if (isLocal) {
|
||||||
|
const pill = document.getElementById('local-pill');
|
||||||
|
if(pill) pill.style.display = 'inline-flex';
|
||||||
|
}
|
||||||
|
if (extensionName) {
|
||||||
|
const pill = document.getElementById('extension-pill');
|
||||||
|
if(pill) {
|
||||||
|
pill.innerText = extensionName;
|
||||||
|
pill.style.display = 'inline-flex';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateDescription(rawDescription) {
|
||||||
|
const desc = MediaMetadataUtils.truncateDescription(rawDescription, 3);
|
||||||
|
const previewEl = document.getElementById('description-preview');
|
||||||
|
const fullEl = document.getElementById('full-description');
|
||||||
|
|
||||||
|
if (previewEl) {
|
||||||
|
previewEl.innerHTML = desc.short +
|
||||||
|
(desc.isTruncated ? ' <span onclick="openDescriptionModal()" style="color:white; cursor:pointer; font-weight:700; margin-left:5px;">Read more</span>' : '');
|
||||||
|
}
|
||||||
|
if (fullEl) fullEl.innerHTML = desc.full;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupDescriptionModal() {
|
||||||
|
const modal = document.getElementById('desc-modal');
|
||||||
|
if (!modal) return;
|
||||||
|
modal.addEventListener('click', (e) => {
|
||||||
|
if (e.target.id === 'desc-modal') {
|
||||||
|
closeDescriptionModal();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function openDescriptionModal() {
|
||||||
|
const modal = document.getElementById('desc-modal');
|
||||||
|
if(modal) modal.classList.add('active');
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeDescriptionModal() {
|
||||||
|
const modal = document.getElementById('desc-modal');
|
||||||
|
if(modal) modal.classList.remove('active');
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupEpisodes(totalEpisodes) {
|
||||||
|
const limitedTotal = Math.min(Math.max(totalEpisodes, 1), 5000);
|
||||||
|
episodePagination.setTotalItems(limitedTotal);
|
||||||
|
renderEpisodes();
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderEpisodes() {
|
||||||
|
const grid = document.getElementById('episodes-grid');
|
||||||
|
if (!grid) return;
|
||||||
|
grid.innerHTML = '';
|
||||||
|
|
||||||
|
const range = episodePagination.getPageRange();
|
||||||
|
const currentEp = (typeof AnimePlayer !== 'undefined') ? AnimePlayer.getCurrentEpisode() : 0;
|
||||||
|
|
||||||
|
for (let i = range.start + 1; i <= range.end; i++) {
|
||||||
|
const btn = document.createElement('div');
|
||||||
|
btn.className = 'episode-btn';
|
||||||
|
if (currentEp === i) btn.classList.add('active-playing');
|
||||||
|
|
||||||
|
btn.innerText = i;
|
||||||
|
|
||||||
|
btn.onclick = () => {
|
||||||
|
if (typeof AnimePlayer !== 'undefined') {
|
||||||
|
AnimePlayer.playEpisode(i);
|
||||||
|
renderEpisodes();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
grid.appendChild(btn);
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalItems = episodePagination.totalItems || 0;
|
||||||
|
const itemsPerPage = episodePagination.itemsPerPage || 50;
|
||||||
|
const safeTotalPages = Math.ceil(totalItems / itemsPerPage) || 1;
|
||||||
|
|
||||||
|
const info = document.getElementById('page-info');
|
||||||
|
if(info) info.innerText = `Page ${episodePagination.currentPage} of ${safeTotalPages}`;
|
||||||
|
|
||||||
|
const prevBtn = document.getElementById('prev-page');
|
||||||
|
const nextBtn = document.getElementById('next-page');
|
||||||
|
|
||||||
|
if(prevBtn) {
|
||||||
|
prevBtn.disabled = episodePagination.currentPage === 1;
|
||||||
|
prevBtn.onclick = () => { episodePagination.prevPage(); };
|
||||||
|
}
|
||||||
|
|
||||||
|
if(nextBtn) {
|
||||||
|
|
||||||
|
nextBtn.disabled = episodePagination.currentPage >= safeTotalPages;
|
||||||
|
nextBtn.onclick = () => { episodePagination.nextPage(); };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupEpisodeSearch() {
|
||||||
|
const searchInput = document.getElementById('ep-search');
|
||||||
|
if (!searchInput) return;
|
||||||
|
|
||||||
|
searchInput.addEventListener('input', (e) => {
|
||||||
|
const val = parseInt(e.target.value);
|
||||||
|
const grid = document.getElementById('episodes-grid');
|
||||||
|
const controls = document.getElementById('pagination-controls');
|
||||||
|
|
||||||
|
if (val > 0) {
|
||||||
|
grid.innerHTML = '';
|
||||||
|
const btn = document.createElement('div');
|
||||||
|
btn.className = 'episode-btn';
|
||||||
|
btn.innerText = `${val}`;
|
||||||
|
btn.onclick = () => { if (typeof AnimePlayer !== 'undefined') AnimePlayer.playEpisode(val); };
|
||||||
|
grid.appendChild(btn);
|
||||||
|
if(controls) controls.style.display = 'none';
|
||||||
|
} else if (!e.target.value) {
|
||||||
|
if(controls) controls.style.display = 'flex';
|
||||||
|
renderEpisodes();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateCharacters(characters) {
|
||||||
|
const container = document.getElementById('char-list');
|
||||||
|
if (!container) return;
|
||||||
|
container.innerHTML = '';
|
||||||
|
if (!characters || characters.length === 0) return;
|
||||||
|
|
||||||
|
characters.forEach((char, index) => {
|
||||||
|
const img = char.node?.image?.large || char.image;
|
||||||
|
const name = char.node?.name?.full || char.name;
|
||||||
|
const role = char.role || 'Supporting';
|
||||||
|
|
||||||
|
const card = document.createElement('div');
|
||||||
|
card.className = `character-item ${index >= 12 ? 'hidden-char' : ''}`;
|
||||||
|
card.style.display = index >= 12 ? 'none' : 'flex';
|
||||||
|
|
||||||
|
card.innerHTML = `
|
||||||
|
<div class="char-avatar"><img src="${img}" loading="lazy"></div>
|
||||||
|
<div class="char-info"><div class="char-name">${name}</div><div class="char-role">${role}</div></div>
|
||||||
|
`;
|
||||||
|
container.appendChild(card);
|
||||||
|
});
|
||||||
|
|
||||||
|
const showMoreBtn = document.getElementById('show-more-chars');
|
||||||
|
if (showMoreBtn) {
|
||||||
|
if (characters.length > 12) {
|
||||||
|
showMoreBtn.style.display = 'block';
|
||||||
|
showMoreBtn.onclick = () => {
|
||||||
|
document.querySelectorAll('.hidden-char').forEach(el => el.style.display = 'flex');
|
||||||
|
showMoreBtn.style.display = 'none';
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
showMoreBtn.style.display = 'none';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateRelations(relations) {
|
||||||
|
const container = document.getElementById('relations-grid');
|
||||||
|
const section = document.getElementById('relations-section');
|
||||||
|
|
||||||
|
if (!container || !relations || relations.length === 0) {
|
||||||
|
if (section) section.style.display = 'none';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
section.style.display = 'block';
|
||||||
|
container.innerHTML = '';
|
||||||
|
|
||||||
|
const priorityMap = {
|
||||||
|
'ADAPTATION': 1,
|
||||||
|
'PREQUEL': 2,
|
||||||
|
'SEQUEL': 3,
|
||||||
|
'PARENT': 4,
|
||||||
|
'SIDE_STORY': 5,
|
||||||
|
'SPIN_OFF': 6,
|
||||||
|
'ALTERNATIVE': 7,
|
||||||
|
'CHARACTER': 8,
|
||||||
|
'OTHER': 99
|
||||||
|
};
|
||||||
|
|
||||||
|
relations.sort((a, b) => {
|
||||||
|
const pA = priorityMap[a.relationType] || 50;
|
||||||
|
const pB = priorityMap[b.relationType] || 50;
|
||||||
|
return pA - pB;
|
||||||
|
});
|
||||||
|
|
||||||
|
relations.forEach(rel => {
|
||||||
|
const media = rel.node;
|
||||||
|
if (!media) return;
|
||||||
|
|
||||||
|
const title = media.title?.romaji || media.title?.english || 'Unknown';
|
||||||
|
const cover = media.coverImage?.large || media.coverImage?.medium || '';
|
||||||
|
|
||||||
|
const typeDisplay = rel.relationType ? rel.relationType.replace(/_/g, ' ') : 'RELATION';
|
||||||
|
const rawType = rel.relationType;
|
||||||
|
|
||||||
|
const el = document.createElement('div');
|
||||||
|
el.className = 'relation-card-horizontal';
|
||||||
|
|
||||||
|
let targetUrl = null;
|
||||||
|
|
||||||
|
if (rawType === 'ADAPTATION') {
|
||||||
|
targetUrl = `/book/${media.id}`;
|
||||||
|
|
||||||
|
} else if (media.type === 'ANIME' && rawType !== 'OTHER') {
|
||||||
|
targetUrl = `/anime/${media.id}`;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if (targetUrl) {
|
||||||
|
el.onclick = () => { window.location.href = targetUrl; };
|
||||||
|
} else {
|
||||||
|
el.classList.add('no-link');
|
||||||
|
|
||||||
|
el.onclick = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
el.innerHTML = `
|
||||||
|
<img src="${cover}" class="rel-img" alt="${title}" onerror="this.src='/public/assets/placeholder.svg'">
|
||||||
|
<div class="rel-info">
|
||||||
|
<span class="rel-type">${typeDisplay}</span>
|
||||||
|
<span class="rel-title">${title}</span>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
container.appendChild(el);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateRecommendations(recommendations) {
|
||||||
|
const container = document.getElementById('recommendations-grid');
|
||||||
|
if (!container || !recommendations) return;
|
||||||
|
container.innerHTML = '';
|
||||||
|
|
||||||
|
recommendations.forEach(rec => {
|
||||||
|
const media = rec.mediaRecommendation;
|
||||||
|
if (!media) return;
|
||||||
|
|
||||||
|
const title = media.title?.romaji || 'Unknown';
|
||||||
|
const cover = media.coverImage?.large || media.coverImage?.medium || '';
|
||||||
|
|
||||||
|
const el = document.createElement('div');
|
||||||
|
el.className = 'card';
|
||||||
|
|
||||||
|
el.onclick = () => { window.location.href = `/anime/${media.id}`; };
|
||||||
|
|
||||||
|
el.innerHTML = `
|
||||||
|
<div class="card-img-wrap"><img src="${cover}" loading="lazy" onerror="this.src='/public/assets/no-cover.jpg'"></div>
|
||||||
|
<div class="card-content"><h3>${title}</h3></div>
|
||||||
|
`;
|
||||||
|
container.appendChild(el);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setupAddToListButton() {
|
||||||
|
const btn = document.getElementById('add-to-list-btn');
|
||||||
|
if (!btn || !animeData) return;
|
||||||
|
|
||||||
|
ListModalManager.currentData = animeData;
|
||||||
|
const entryType = 'ANIME';
|
||||||
|
await ListModalManager.checkIfInList(animeId, extensionName || 'anilist', entryType);
|
||||||
|
updateCustomAddButton();
|
||||||
|
btn.onclick = () => ListModalManager.open(animeData, extensionName || 'anilist');
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateCustomAddButton() {
|
||||||
|
const btn = document.getElementById('add-to-list-btn');
|
||||||
|
if (btn && ListModalManager.isInList) {
|
||||||
|
btn.innerHTML = `✓ In Your List`;
|
||||||
|
btn.style.background = 'rgba(34, 197, 94, 0.2)';
|
||||||
|
btn.style.borderColor = '#22c55e';
|
||||||
|
btn.style.color = '#22c55e';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function showError(msg) {
|
||||||
|
const el = document.getElementById('title');
|
||||||
|
if(el) el.innerText = msg;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.openDescriptionModal = openDescriptionModal;
|
||||||
|
window.closeDescriptionModal = closeDescriptionModal;
|
||||||
|
window.scrollRecommendations = (dir) => {
|
||||||
|
const el = document.getElementById('recommendations-grid');
|
||||||
|
if(el) el.scrollBy({ left: 240 * 3 * dir, behavior: 'smooth' });
|
||||||
|
};
|
||||||
2024
desktop/src/scripts/anime/player.js
Normal file
152
desktop/src/scripts/anime/subtitle-renderer.js
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
const BASE_PATH = '/src/scripts/jassub/';
|
||||||
|
class SubtitleRenderer {
|
||||||
|
constructor(video, canvas) {
|
||||||
|
this.video = video;
|
||||||
|
this.canvas = canvas;
|
||||||
|
this.instance = null;
|
||||||
|
this.currentUrl = null;
|
||||||
|
}
|
||||||
|
async init(subtitleUrl) {
|
||||||
|
if (!this.video || !this.canvas) return;
|
||||||
|
this.dispose();
|
||||||
|
const finalUrl = subtitleUrl.includes('/api/proxy')
|
||||||
|
? subtitleUrl
|
||||||
|
: `/api/proxy?url=${encodeURIComponent(subtitleUrl)}`;
|
||||||
|
this.currentUrl = finalUrl;
|
||||||
|
try {
|
||||||
|
this.instance = new JASSUB({
|
||||||
|
video: this.video,
|
||||||
|
canvas: this.canvas,
|
||||||
|
subUrl: finalUrl,
|
||||||
|
workerUrl: `${BASE_PATH}jassub-worker.js`,
|
||||||
|
wasmUrl: `${BASE_PATH}jassub-worker.wasm`,
|
||||||
|
modernWasmUrl: `${BASE_PATH}jassub-worker-modern.wasm`,
|
||||||
|
blendMode: 'js',
|
||||||
|
asyncRender: true,
|
||||||
|
onDemand: true,
|
||||||
|
targetFps: 60,
|
||||||
|
debug: false
|
||||||
|
});
|
||||||
|
console.log('JASSUB initialized for:', finalUrl);
|
||||||
|
} catch (e) {
|
||||||
|
console.error("JASSUB Init Error:", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
resize() {
|
||||||
|
if (this.instance && this.instance.resize) {
|
||||||
|
this.instance.resize();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setTrack(url) {
|
||||||
|
const finalUrl = url.includes('/api/proxy')
|
||||||
|
? url
|
||||||
|
: `/api/proxy?url=${encodeURIComponent(url)}`;
|
||||||
|
if (this.instance) {
|
||||||
|
this.instance.setTrackByUrl(finalUrl);
|
||||||
|
this.currentUrl = finalUrl;
|
||||||
|
} else {
|
||||||
|
this.init(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dispose() {
|
||||||
|
if (this.instance) {
|
||||||
|
try {
|
||||||
|
this.instance.destroy();
|
||||||
|
} catch (e) {
|
||||||
|
console.warn("Error destroying JASSUB:", e);
|
||||||
|
}
|
||||||
|
this.instance = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class SimpleSubtitleRenderer {
|
||||||
|
constructor(video, canvas) {
|
||||||
|
this.video = video;
|
||||||
|
this.canvas = canvas;
|
||||||
|
this.ctx = canvas.getContext('2d');
|
||||||
|
this.cues = [];
|
||||||
|
this.destroyed = false;
|
||||||
|
this.setupCanvas();
|
||||||
|
this.video.addEventListener('timeupdate', () => this.render());
|
||||||
|
}
|
||||||
|
setupCanvas() {
|
||||||
|
const updateSize = () => {
|
||||||
|
if (!this.video || !this.canvas) return;
|
||||||
|
const rect = this.video.getBoundingClientRect();
|
||||||
|
this.canvas.width = rect.width;
|
||||||
|
this.canvas.height = rect.height;
|
||||||
|
};
|
||||||
|
updateSize();
|
||||||
|
window.addEventListener('resize', updateSize);
|
||||||
|
this.resizeHandler = updateSize;
|
||||||
|
}
|
||||||
|
async loadSubtitles(url) {
|
||||||
|
try {
|
||||||
|
let finalUrl = url;
|
||||||
|
const isLocal = url.startsWith('/');
|
||||||
|
const isAlreadyProxied = url.includes('/api/proxy');
|
||||||
|
if (!isLocal && !isAlreadyProxied && (url.startsWith('http:') || url.startsWith('https:'))) {
|
||||||
|
finalUrl = `/api/proxy?url=${encodeURIComponent(url)}`;
|
||||||
|
}
|
||||||
|
console.log('Fetching subtitles from:', finalUrl);
|
||||||
|
const response = await fetch(finalUrl);
|
||||||
|
if (!response.ok) throw new Error(`Status: ${response.status}`);
|
||||||
|
const text = await response.text();
|
||||||
|
this.cues = this.parseSRT(text);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to load subtitles:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setTrack(url) {
|
||||||
|
this.cues = [];
|
||||||
|
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
||||||
|
this.loadSubtitles(url);
|
||||||
|
}
|
||||||
|
parseSRT(srtText) {
|
||||||
|
const normalizedText = srtText.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
||||||
|
const blocks = normalizedText.trim().split('\n\n');
|
||||||
|
return blocks.map(block => {
|
||||||
|
const lines = block.split('\n');
|
||||||
|
if (lines.length < 3) return null;
|
||||||
|
const timeMatch = lines[1].match(/(\d{2}):(\d{2}):(\d{2}),(\d{3}) --> (\d{2}):(\d{2}):(\d{2}),(\d{3})/);
|
||||||
|
if (!timeMatch) return null;
|
||||||
|
const start = parseInt(timeMatch[1]) * 3600 + parseInt(timeMatch[2]) * 60 + parseInt(timeMatch[3]) + parseInt(timeMatch[4]) / 1000;
|
||||||
|
const end = parseInt(timeMatch[5]) * 3600 + parseInt(timeMatch[6]) * 60 + parseInt(timeMatch[7]) + parseInt(timeMatch[8]) / 1000;
|
||||||
|
let text = lines.slice(2).join('\n');
|
||||||
|
text = text.replace(/<[^>]*>/g, '');
|
||||||
|
text = text.replace(/\{[^}]*\}/g, '');
|
||||||
|
return { start, end, text };
|
||||||
|
}).filter(Boolean);
|
||||||
|
}
|
||||||
|
render() {
|
||||||
|
if (this.destroyed) return;
|
||||||
|
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
||||||
|
const currentTime = this.video.currentTime;
|
||||||
|
const cue = this.cues.find(c => currentTime >= c.start && currentTime <= c.end);
|
||||||
|
if (cue) this.drawSubtitle(cue.text);
|
||||||
|
}
|
||||||
|
drawSubtitle(text) {
|
||||||
|
const lines = text.split('\n');
|
||||||
|
const fontSize = Math.max(20, this.canvas.height * 0.04);
|
||||||
|
this.ctx.font = `bold ${fontSize}px Arial, sans-serif`;
|
||||||
|
this.ctx.textAlign = 'center';
|
||||||
|
this.ctx.textBaseline = 'bottom';
|
||||||
|
const lineHeight = fontSize * 1.2;
|
||||||
|
const startY = this.canvas.height - 60;
|
||||||
|
lines.reverse().forEach((line, index) => {
|
||||||
|
const y = startY - (index * lineHeight);
|
||||||
|
this.ctx.strokeStyle = 'black';
|
||||||
|
this.ctx.lineWidth = 4;
|
||||||
|
this.ctx.strokeText(line, this.canvas.width / 2, y);
|
||||||
|
this.ctx.fillStyle = 'white';
|
||||||
|
this.ctx.fillText(line, this.canvas.width / 2, y);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
dispose() {
|
||||||
|
this.destroyed = true;
|
||||||
|
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
||||||
|
if (this.resizeHandler) window.removeEventListener('resize', this.resizeHandler);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.SubtitleRenderer = SubtitleRenderer;
|
||||||
|
window.SimpleSubtitleRenderer = SimpleSubtitleRenderer;
|
||||||
180
desktop/src/scripts/auth-guard.js
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
;(() => {
|
||||||
|
const token = localStorage.getItem("token")
|
||||||
|
|
||||||
|
if (!token && window.location.pathname !== "/") {
|
||||||
|
window.location.href = "/"
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
|
||||||
|
async function loadMeUI() {
|
||||||
|
const token = localStorage.getItem("token")
|
||||||
|
if (!token) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/me", {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!res.ok) return
|
||||||
|
|
||||||
|
const user = await res.json()
|
||||||
|
|
||||||
|
const navUser = document.getElementById("nav-user")
|
||||||
|
const navUsername = document.getElementById("nav-username")
|
||||||
|
const navAvatar = document.getElementById("nav-avatar")
|
||||||
|
const dropdownAvatar = document.getElementById("dropdown-avatar")
|
||||||
|
|
||||||
|
if (!navUser || !navUsername || !navAvatar) return
|
||||||
|
|
||||||
|
navUser.style.display = "flex"
|
||||||
|
navUsername.textContent = user.username
|
||||||
|
|
||||||
|
const avatarUrl = user.avatar || "/public/assets/avatar.png"
|
||||||
|
navAvatar.src = avatarUrl
|
||||||
|
if (dropdownAvatar) {
|
||||||
|
dropdownAvatar.src = avatarUrl
|
||||||
|
}
|
||||||
|
|
||||||
|
setupDropdown()
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Failed to load user UI:", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Variable para saber si el modal ya fue cargado
|
||||||
|
let settingsModalLoaded = false;
|
||||||
|
|
||||||
|
document.getElementById('nav-settings').addEventListener('click', openSettings)
|
||||||
|
|
||||||
|
async function openSettings() {
|
||||||
|
if (!settingsModalLoaded) {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/views/components/settings-modal.html')
|
||||||
|
const html = await res.text()
|
||||||
|
document.body.insertAdjacentHTML('beforeend', html)
|
||||||
|
settingsModalLoaded = true;
|
||||||
|
|
||||||
|
// Esperar un momento para que el DOM se actualice
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 50));
|
||||||
|
|
||||||
|
// Ahora cargar los settings
|
||||||
|
if (window.toggleSettingsModal) {
|
||||||
|
await window.toggleSettingsModal(false);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error loading settings modal:', err);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (window.toggleSettingsModal) {
|
||||||
|
await window.toggleSettingsModal(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeSettings() {
|
||||||
|
const modal = document.getElementById('settings-modal');
|
||||||
|
if (modal) {
|
||||||
|
modal.classList.add('hidden');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupDropdown() {
|
||||||
|
const userAvatarBtn = document.querySelector(".user-avatar-btn")
|
||||||
|
const navDropdown = document.getElementById("nav-dropdown")
|
||||||
|
const navLogout = document.getElementById("nav-logout")
|
||||||
|
|
||||||
|
if (!userAvatarBtn || !navDropdown || !navLogout) return
|
||||||
|
|
||||||
|
userAvatarBtn.addEventListener("click", (e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
navDropdown.classList.toggle("active")
|
||||||
|
})
|
||||||
|
|
||||||
|
document.addEventListener("click", (e) => {
|
||||||
|
if (!navDropdown.contains(e.target)) {
|
||||||
|
navDropdown.classList.remove("active")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
navDropdown.addEventListener("click", (e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
})
|
||||||
|
|
||||||
|
navLogout.addEventListener("click", () => {
|
||||||
|
localStorage.removeItem("token")
|
||||||
|
window.location.href = "/"
|
||||||
|
})
|
||||||
|
|
||||||
|
const dropdownLinks = navDropdown.querySelectorAll("a.dropdown-item")
|
||||||
|
dropdownLinks.forEach((link) => {
|
||||||
|
link.addEventListener("click", () => {
|
||||||
|
navDropdown.classList.remove("active")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
loadMeUI()
|
||||||
|
|
||||||
|
const mobileToggle = document.getElementById('mobile-menu-toggle');
|
||||||
|
const navCenter = document.querySelector('.nav-center');
|
||||||
|
|
||||||
|
let overlay = document.querySelector('.menu-overlay');
|
||||||
|
if (!overlay) {
|
||||||
|
overlay = document.createElement('div');
|
||||||
|
overlay.className = 'menu-overlay';
|
||||||
|
document.body.appendChild(overlay);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleMenu() {
|
||||||
|
navCenter.classList.toggle('open');
|
||||||
|
overlay.classList.toggle('active');
|
||||||
|
|
||||||
|
const isOpen = navCenter.classList.contains('open');
|
||||||
|
mobileToggle.innerHTML = isOpen
|
||||||
|
? '<svg width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>'
|
||||||
|
: '<svg width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"/></svg>';
|
||||||
|
}
|
||||||
|
|
||||||
|
mobileToggle.addEventListener('click', toggleMenu);
|
||||||
|
|
||||||
|
overlay.addEventListener('click', () => {
|
||||||
|
if (navCenter.classList.contains('open')) toggleMenu();
|
||||||
|
});
|
||||||
|
|
||||||
|
navCenter.querySelectorAll('.nav-button').forEach(btn => {
|
||||||
|
btn.addEventListener('click', () => {
|
||||||
|
if (navCenter.classList.contains('open')) toggleMenu();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const searchWrapper = document.querySelector('.search-wrapper');
|
||||||
|
const searchInput = document.getElementById('search-input');
|
||||||
|
|
||||||
|
searchWrapper.addEventListener('click', (e) => {
|
||||||
|
if (window.innerWidth <= 768) {
|
||||||
|
searchWrapper.classList.add('active-mobile');
|
||||||
|
searchInput.focus();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Cerrar el buscador si se hace clic fuera
|
||||||
|
document.addEventListener('click', (e) => {
|
||||||
|
if (!searchWrapper.contains(e.target)) {
|
||||||
|
searchWrapper.classList.remove('active-mobile');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const createRoomModal = new CreateRoomModal();
|
||||||
|
|
||||||
|
const createBtn = document.getElementById('nav-create-party');
|
||||||
|
if (createBtn) {
|
||||||
|
createBtn.addEventListener('click', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const dropdown = document.getElementById('nav-dropdown');
|
||||||
|
if(dropdown) dropdown.classList.remove('active');
|
||||||
|
|
||||||
|
createRoomModal.open();
|
||||||
|
});
|
||||||
|
}
|
||||||
655
desktop/src/scripts/books/book.js
Normal file
@@ -0,0 +1,655 @@
|
|||||||
|
let bookData = null;
|
||||||
|
let extensionName = null;
|
||||||
|
let bookId = null;
|
||||||
|
let bookSlug = null;
|
||||||
|
|
||||||
|
let allChapters = [];
|
||||||
|
let filteredChapters = [];
|
||||||
|
let availableExtensions = [];
|
||||||
|
let isLocal = false;
|
||||||
|
|
||||||
|
let currentLanguage = null;
|
||||||
|
let uniqueLanguages = [];
|
||||||
|
let isSortAscending = true;
|
||||||
|
let manualExtensionBookId = null;
|
||||||
|
|
||||||
|
const chapterPagination = Object.create(PaginationManager);
|
||||||
|
chapterPagination.init(6, () => renderChapterList());
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
init();
|
||||||
|
setupModalClickOutside();
|
||||||
|
document.getElementById('sort-btn')?.addEventListener('click', toggleSortOrder);
|
||||||
|
});
|
||||||
|
|
||||||
|
async function init() {
|
||||||
|
try {
|
||||||
|
const urlData = URLUtils.parseEntityPath('book');
|
||||||
|
if (!urlData) { showError("Book Not Found"); return; }
|
||||||
|
|
||||||
|
extensionName = urlData.extensionName;
|
||||||
|
bookId = urlData.entityId;
|
||||||
|
bookSlug = urlData.slug;
|
||||||
|
|
||||||
|
await loadBookMetadata();
|
||||||
|
await checkLocalLibraryEntry();
|
||||||
|
await loadAvailableExtensions();
|
||||||
|
await loadChapters();
|
||||||
|
await setupAddToListButton();
|
||||||
|
|
||||||
|
document.getElementById('manual-match-btn')?.addEventListener('click', () => {
|
||||||
|
const select = document.getElementById('provider-filter');
|
||||||
|
const provider = select.value;
|
||||||
|
|
||||||
|
// Obtener título para prellenar
|
||||||
|
const currentTitle = bookData?.title?.romaji || bookData?.title?.english || '';
|
||||||
|
|
||||||
|
MatchModal.open({
|
||||||
|
provider: provider,
|
||||||
|
initialQuery: currentTitle,
|
||||||
|
// Define CÓMO buscar
|
||||||
|
onSearch: async (query, prov) => {
|
||||||
|
const res = await fetch(`/api/search/books/${prov}?q=${encodeURIComponent(query)}`);
|
||||||
|
const data = await res.json();
|
||||||
|
return data.results || [];
|
||||||
|
},
|
||||||
|
// Define QUÉ hacer al seleccionar
|
||||||
|
onSelect: (item) => {
|
||||||
|
console.log("Selected Book ID:", item.id);
|
||||||
|
manualExtensionBookId = item.id;
|
||||||
|
|
||||||
|
// Lógica existente de tu book.js para recargar caps
|
||||||
|
loadChapters(provider);
|
||||||
|
|
||||||
|
// Feedback visual en el botón
|
||||||
|
const btn = document.getElementById('manual-match-btn');
|
||||||
|
if(btn) btn.style.color = '#22c55e';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Init Error:", err);
|
||||||
|
showError("Error loading book");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadBookMetadata() {
|
||||||
|
const source = extensionName || 'anilist';
|
||||||
|
const fetchUrl = `/api/book/${bookId}?source=${source}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(fetchUrl);
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (data.error || !data) { showError("Book Not Found"); return; }
|
||||||
|
|
||||||
|
const raw = Array.isArray(data) ? data[0] : data;
|
||||||
|
bookData = raw;
|
||||||
|
|
||||||
|
const metadata = MediaMetadataUtils.formatBookData(raw, !!extensionName);
|
||||||
|
bookData.entry_type = metadata.format === 'MANGA' ? 'MANGA' : 'NOVEL';
|
||||||
|
|
||||||
|
updatePageTitle(metadata.title);
|
||||||
|
updateMetadata(metadata, raw);
|
||||||
|
updateExtensionPill();
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
showError("Error loading metadata");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updatePageTitle(title) {
|
||||||
|
document.title = `${title} | WaifuBoard Books`;
|
||||||
|
const titleEl = document.getElementById('title');
|
||||||
|
if (titleEl) titleEl.innerText = title;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateMetadata(metadata, rawData) {
|
||||||
|
// 1. Cabecera (Score, Año, Status, Formato, Caps)
|
||||||
|
const elements = {
|
||||||
|
'description': metadata.description,
|
||||||
|
'published-date': metadata.year,
|
||||||
|
'status': metadata.status,
|
||||||
|
'format': metadata.format,
|
||||||
|
'chapters-count': metadata.chapters ? `${metadata.chapters} Ch` : '?? Ch',
|
||||||
|
'genres': metadata.genres ? metadata.genres.replace(/,/g, ' • ') : '',
|
||||||
|
'poster': metadata.poster,
|
||||||
|
'hero-bg': metadata.banner
|
||||||
|
};
|
||||||
|
|
||||||
|
if(document.getElementById('description')) document.getElementById('description').innerHTML = metadata.description;
|
||||||
|
if(document.getElementById('poster')) document.getElementById('poster').src = metadata.poster;
|
||||||
|
if(document.getElementById('hero-bg')) document.getElementById('hero-bg').src = metadata.banner;
|
||||||
|
|
||||||
|
['published-date','status','format','chapters-count','genres'].forEach(id => {
|
||||||
|
const el = document.getElementById(id);
|
||||||
|
if(el) el.innerText = elements[id];
|
||||||
|
});
|
||||||
|
|
||||||
|
const scoreEl = document.getElementById('score');
|
||||||
|
if (scoreEl) scoreEl.innerText = extensionName ? `${metadata.score}` : `${metadata.score}% Score`;
|
||||||
|
|
||||||
|
// 2. Sidebar: Sinónimos (Para llenar espacio vacío)
|
||||||
|
if (rawData.synonyms && rawData.synonyms.length > 0) {
|
||||||
|
const sidebarInfo = document.getElementById('sidebar-info');
|
||||||
|
const list = document.getElementById('synonyms-list');
|
||||||
|
if (sidebarInfo && list) {
|
||||||
|
sidebarInfo.style.display = 'block';
|
||||||
|
list.innerHTML = '';
|
||||||
|
// Mostrar máx 5 sinónimos para no alargar demasiado
|
||||||
|
rawData.synonyms.slice(0, 5).forEach(syn => {
|
||||||
|
const li = document.createElement('li');
|
||||||
|
li.innerText = syn;
|
||||||
|
list.appendChild(li);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Renderizar Personajes
|
||||||
|
if (rawData.characters && rawData.characters.nodes && rawData.characters.nodes.length > 0) {
|
||||||
|
renderCharacters(rawData.characters.nodes);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Renderizar Relaciones
|
||||||
|
if (rawData.relations && rawData.relations.edges && rawData.relations.edges.length > 0) {
|
||||||
|
renderRelations(rawData.relations.edges);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderCharacters(nodes) {
|
||||||
|
const container = document.getElementById('characters-list');
|
||||||
|
if(!container) return;
|
||||||
|
container.innerHTML = '';
|
||||||
|
|
||||||
|
nodes.forEach(char => {
|
||||||
|
const el = document.createElement('div');
|
||||||
|
el.className = 'character-item';
|
||||||
|
|
||||||
|
const img = char.image?.large || char.image?.medium || '/public/assets/no-image.png';
|
||||||
|
const name = char.name?.full || 'Unknown';
|
||||||
|
const role = char.role || 'Supporting';
|
||||||
|
|
||||||
|
el.innerHTML = `
|
||||||
|
<div class="char-avatar"><img src="${img}" loading="lazy"></div>
|
||||||
|
<div class="char-info">
|
||||||
|
<div class="char-name">${name}</div>
|
||||||
|
<div class="char-role">${role}</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
container.appendChild(el);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderRelations(edges) {
|
||||||
|
const container = document.getElementById('relations-list');
|
||||||
|
const section = document.getElementById('relations-section');
|
||||||
|
if(!container || !section) return;
|
||||||
|
|
||||||
|
if (!edges || edges.length === 0) {
|
||||||
|
section.style.display = 'none';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
section.style.display = 'block';
|
||||||
|
container.innerHTML = '';
|
||||||
|
|
||||||
|
edges.forEach(edge => {
|
||||||
|
const node = edge.node;
|
||||||
|
if (!node) return;
|
||||||
|
|
||||||
|
const el = document.createElement('div');
|
||||||
|
el.className = 'relation-card-horizontal';
|
||||||
|
|
||||||
|
const img = node.coverImage?.large || node.coverImage?.medium || '/public/assets/placeholder.svg';
|
||||||
|
const title = node.title?.romaji || node.title?.english || node.title?.native || 'Unknown';
|
||||||
|
const type = edge.relationType ? edge.relationType.replace(/_/g, ' ') : 'Related';
|
||||||
|
|
||||||
|
el.innerHTML = `
|
||||||
|
<img src="${img}" class="rel-img" alt="${title}" loading="lazy">
|
||||||
|
<div class="rel-info">
|
||||||
|
<span class="rel-type">${type}</span>
|
||||||
|
<span class="rel-title">${title}</span>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
el.onclick = () => {
|
||||||
|
const imgUrl = node.coverImage?.medium || '';
|
||||||
|
const targetType = imgUrl.includes('/manga/') ? 'book' : 'anime';
|
||||||
|
window.location.href = `/${targetType}/${node.id}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
container.appendChild(el);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function processChaptersData(chaptersData) {
|
||||||
|
allChapters = chaptersData;
|
||||||
|
const langSet = new Set(allChapters.map(ch => ch.language).filter(l => l));
|
||||||
|
uniqueLanguages = Array.from(langSet);
|
||||||
|
setupLanguageSelector();
|
||||||
|
filterAndRenderChapters();
|
||||||
|
setupReadButton();
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildProxyUrl(url, headers = {}) {
|
||||||
|
const origin = window.location.origin;
|
||||||
|
|
||||||
|
const params = new URLSearchParams({ url });
|
||||||
|
if (headers.Referer || headers.referer)
|
||||||
|
params.append("referer", headers.Referer || headers.referer);
|
||||||
|
if (headers["User-Agent"] || headers["user-agent"])
|
||||||
|
params.append("userAgent", headers["User-Agent"] || headers["user-agent"]);
|
||||||
|
if (headers.Origin || headers.origin)
|
||||||
|
params.append("origin", headers.Origin || headers.origin);
|
||||||
|
|
||||||
|
return `${origin}/api/proxy?${params.toString()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadChapter(chapterId, chapterNumber, provider, btnElement) {
|
||||||
|
// Validamos que tengamos bookId y un provider válido
|
||||||
|
if (!bookId || !provider) return showError("Error: Faltan datos del capítulo");
|
||||||
|
|
||||||
|
// Feedback visual
|
||||||
|
const originalText = btnElement.innerHTML;
|
||||||
|
btnElement.innerHTML = `<span class="spinner">↻</span>`; // Spinner pequeño
|
||||||
|
btnElement.disabled = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. OBTENER CONTENIDO USANDO EL PROVIDER DEL CAPÍTULO
|
||||||
|
// CAMBIO AQUÍ: Usamos 'provider' en lugar de 'extensionName'
|
||||||
|
const fetchUrl = `/api/book/${bookId}/${chapterId}/${provider}?source=${extensionName || 'anilist'}&lang=none`;
|
||||||
|
|
||||||
|
const contentRes = await fetch(fetchUrl);
|
||||||
|
|
||||||
|
if (!contentRes.ok) throw new Error("Error obteniendo contenido del capítulo");
|
||||||
|
const chapterData = await contentRes.json();
|
||||||
|
|
||||||
|
// 2. PREPARAR BODY (Misma lógica)
|
||||||
|
let payload = {
|
||||||
|
anilist_id: parseInt(bookId),
|
||||||
|
chapter_number: parseFloat(chapterNumber),
|
||||||
|
format: "",
|
||||||
|
};
|
||||||
|
|
||||||
|
if (chapterData.pages && Array.isArray(chapterData.pages)) {
|
||||||
|
payload.format = "manga";
|
||||||
|
payload.images = chapterData.pages.map((img, index) => {
|
||||||
|
let finalUrl = img.url;
|
||||||
|
if (img.headers && Object.keys(img.headers).length > 0) {
|
||||||
|
finalUrl = buildProxyUrl(img.url, img.headers);
|
||||||
|
}
|
||||||
|
return { index: index, url: finalUrl };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
else if (chapterData.content) {
|
||||||
|
payload.format = "novel";
|
||||||
|
payload.content = chapterData.content;
|
||||||
|
} else {
|
||||||
|
throw new Error("Formato desconocido");
|
||||||
|
}
|
||||||
|
|
||||||
|
const downloadRes = await fetch('/api/library/download/book', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
|
||||||
|
const downloadData = await downloadRes.json();
|
||||||
|
|
||||||
|
if (downloadRes.status === 200) {
|
||||||
|
btnElement.innerHTML = "✓";
|
||||||
|
btnElement.style.color = "#22c55e"; // Icono verde
|
||||||
|
} else if (downloadRes.status === 409) {
|
||||||
|
btnElement.innerHTML = "✓";
|
||||||
|
btnElement.style.color = "#3b82f6"; // Icono azul (ya existe)
|
||||||
|
} else {
|
||||||
|
throw new Error(downloadData.message || "Error");
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Download Error:", err);
|
||||||
|
btnElement.innerHTML = "✕"; // X roja
|
||||||
|
btnElement.style.color = "#ef4444";
|
||||||
|
btnElement.disabled = false;
|
||||||
|
|
||||||
|
// Restaurar icono original después de 3 seg
|
||||||
|
setTimeout(() => {
|
||||||
|
btnElement.innerHTML = originalText;
|
||||||
|
btnElement.style.color = "";
|
||||||
|
}, 3000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadChapters(targetProvider = null) {
|
||||||
|
const listContainer = document.getElementById('chapters-list');
|
||||||
|
const loadingMsg = document.getElementById('loading-msg');
|
||||||
|
|
||||||
|
if(listContainer) listContainer.innerHTML = '';
|
||||||
|
if(loadingMsg) loadingMsg.style.display = 'block';
|
||||||
|
|
||||||
|
if (!targetProvider) {
|
||||||
|
const select = document.getElementById('provider-filter');
|
||||||
|
targetProvider = select ? select.value : (availableExtensions[0] || 'all');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
let fetchUrl;
|
||||||
|
let isLocalRequest = targetProvider === 'local';
|
||||||
|
|
||||||
|
if (isLocalRequest) {
|
||||||
|
fetchUrl = `/api/library/${bookId}/units`;
|
||||||
|
} else {
|
||||||
|
const source = extensionName || 'anilist';
|
||||||
|
fetchUrl = `/api/book/${bookId}/chapters?source=${source}`;
|
||||||
|
if (targetProvider !== 'all') fetchUrl += `&provider=${targetProvider}`;
|
||||||
|
if (manualExtensionBookId && targetProvider !== 'all') {
|
||||||
|
fetchUrl += `&extensionBookId=${manualExtensionBookId}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(fetchUrl);
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if(loadingMsg) loadingMsg.style.display = 'none';
|
||||||
|
|
||||||
|
let rawData = [];
|
||||||
|
if (isLocalRequest) {
|
||||||
|
rawData = (data.units || []).map((unit, idx) => ({
|
||||||
|
id: unit.id || idx, number: unit.number, title: unit.name,
|
||||||
|
provider: 'local', index: idx, format: unit.format, language: 'local'
|
||||||
|
}));
|
||||||
|
} else {
|
||||||
|
rawData = data.chapters || [];
|
||||||
|
}
|
||||||
|
processChaptersData(rawData);
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
if(loadingMsg) loadingMsg.style.display = 'none';
|
||||||
|
if(listContainer) listContainer.innerHTML = '<div style="text-align:center; color: #ef4444;">Error loading chapters.</div>';
|
||||||
|
console.error(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupLanguageSelector() {
|
||||||
|
const selectorContainer = document.getElementById('language-selector-container');
|
||||||
|
const select = document.getElementById('language-select');
|
||||||
|
if (!selectorContainer || !select) return;
|
||||||
|
|
||||||
|
if (uniqueLanguages.length <= 1) {
|
||||||
|
selectorContainer.classList.add('hidden');
|
||||||
|
currentLanguage = uniqueLanguages[0] || null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
selectorContainer.classList.remove('hidden');
|
||||||
|
select.innerHTML = '';
|
||||||
|
|
||||||
|
const langNames = { 'es': 'Español', 'es-419': 'Latino', 'en': 'English', 'pt-br': 'Português', 'ja': '日本語' };
|
||||||
|
|
||||||
|
uniqueLanguages.forEach(lang => {
|
||||||
|
const option = document.createElement('option');
|
||||||
|
option.value = lang;
|
||||||
|
option.textContent = langNames[lang] || lang.toUpperCase();
|
||||||
|
select.appendChild(option);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (uniqueLanguages.includes('es-419')) currentLanguage = 'es-419';
|
||||||
|
else if (uniqueLanguages.includes('es')) currentLanguage = 'es';
|
||||||
|
else currentLanguage = uniqueLanguages[0];
|
||||||
|
select.value = currentLanguage;
|
||||||
|
|
||||||
|
select.onchange = (e) => {
|
||||||
|
currentLanguage = e.target.value;
|
||||||
|
chapterPagination.currentPage = 1;
|
||||||
|
filterAndRenderChapters();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function filterAndRenderChapters() {
|
||||||
|
let tempChapters = [...allChapters];
|
||||||
|
if (currentLanguage && uniqueLanguages.length > 1) {
|
||||||
|
tempChapters = tempChapters.filter(ch => ch.language === currentLanguage);
|
||||||
|
}
|
||||||
|
const searchQuery = document.getElementById('chapter-search')?.value.toLowerCase();
|
||||||
|
if(searchQuery){
|
||||||
|
tempChapters = tempChapters.filter(ch =>
|
||||||
|
(ch.title && ch.title.toLowerCase().includes(searchQuery)) ||
|
||||||
|
(ch.number && ch.number.toString().includes(searchQuery))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
tempChapters.sort((a, b) => {
|
||||||
|
const numA = parseFloat(a.number) || 0;
|
||||||
|
const numB = parseFloat(b.number) || 0;
|
||||||
|
return isSortAscending ? numA - numB : numB - numA;
|
||||||
|
});
|
||||||
|
filteredChapters = tempChapters;
|
||||||
|
chapterPagination.setTotalItems(filteredChapters.length);
|
||||||
|
renderChapterList();
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderChapterList() {
|
||||||
|
const container = document.getElementById('chapters-list');
|
||||||
|
if(!container) return;
|
||||||
|
container.innerHTML = '';
|
||||||
|
const itemsToShow = chapterPagination.getCurrentPageItems(filteredChapters);
|
||||||
|
|
||||||
|
if (itemsToShow.length === 0) {
|
||||||
|
container.innerHTML = '<div style="text-align:center; padding:2rem; color:#888;">No chapters found.</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
itemsToShow.forEach(chapter => {
|
||||||
|
const el = document.createElement('div');
|
||||||
|
el.className = 'chapter-item';
|
||||||
|
|
||||||
|
// El clic principal abre el lector
|
||||||
|
el.onclick = () => openReader(chapter.id, chapter.provider);
|
||||||
|
|
||||||
|
const dateStr = chapter.date ? new Date(chapter.date).toLocaleDateString() : '';
|
||||||
|
const providerLabel = chapter.provider !== 'local' ? chapter.provider : '';
|
||||||
|
|
||||||
|
// Definimos el icono SVG de descarga para no ensuciar tanto el template string
|
||||||
|
const downloadIcon = `
|
||||||
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
|
||||||
|
<polyline points="7 10 12 15 17 10"></polyline>
|
||||||
|
<line x1="12" y1="15" x2="12" y2="3"></line>
|
||||||
|
</svg>`;
|
||||||
|
|
||||||
|
const isLocal = chapter.provider === 'local';
|
||||||
|
const downloadBtnStyle = isLocal ? 'display:none;' : '';
|
||||||
|
|
||||||
|
el.innerHTML = `
|
||||||
|
<div class="chapter-info">
|
||||||
|
<span class="chapter-number">Chapter ${chapter.number}</span>
|
||||||
|
<span class="chapter-title">${chapter.title || ''}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="chapter-actions" style="display: flex; align-items: center; gap: 10px;">
|
||||||
|
<div class="chapter-meta">
|
||||||
|
${providerLabel ? `<span class="lang-tag">${providerLabel}</span>` : ''}
|
||||||
|
${dateStr ? `<span>${dateStr}</span>` : ''}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button class="download-btn"
|
||||||
|
style="${downloadBtnStyle}"
|
||||||
|
onclick="event.stopPropagation(); downloadChapter('${chapter.id}', '${chapter.number}', '${chapter.provider}', this)"
|
||||||
|
title="Descargar">
|
||||||
|
${downloadIcon}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<svg class="chapter-play-icon" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path d="M8 5v14l11-7z"/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
container.appendChild(el);
|
||||||
|
});
|
||||||
|
|
||||||
|
chapterPagination.renderControls('pagination', 'page-info', 'prev-page', 'next-page');
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleSortOrder() {
|
||||||
|
isSortAscending = !isSortAscending;
|
||||||
|
const btn = document.getElementById('sort-btn');
|
||||||
|
if(btn) btn.style.transform = isSortAscending ? 'rotate(180deg)' : 'rotate(0deg)';
|
||||||
|
filterAndRenderChapters();
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupReadButton() {
|
||||||
|
const readBtn = document.getElementById('read-start-btn');
|
||||||
|
if (!readBtn || allChapters.length === 0) return;
|
||||||
|
const firstChapter = [...allChapters].sort((a,b) => a.index - b.index)[0];
|
||||||
|
if (firstChapter) readBtn.onclick = () =>
|
||||||
|
openReader(firstChapter.index ?? firstChapter.id, firstChapter.provider);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
function openReader(chapterIndexOrId, provider) {
|
||||||
|
const lang = currentLanguage ?? 'none';
|
||||||
|
window.location.href =
|
||||||
|
URLUtils.buildReadUrl(bookId, chapterIndexOrId, provider, extensionName || 'anilist')
|
||||||
|
+ `?lang=${lang}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function checkLocalLibraryEntry() {
|
||||||
|
try {
|
||||||
|
const libraryType = bookData?.entry_type === 'NOVEL' ? 'novels' : 'manga';
|
||||||
|
const res = await fetch(`/api/library/${libraryType}/${bookId}`);
|
||||||
|
if (!res.ok) return;
|
||||||
|
const data = await res.json();
|
||||||
|
if (data.matched) {
|
||||||
|
isLocal = true;
|
||||||
|
const pill = document.getElementById('local-pill');
|
||||||
|
if (pill) {
|
||||||
|
pill.textContent = 'Local';
|
||||||
|
pill.style.display = 'inline-flex';
|
||||||
|
pill.style.background = 'rgba(34, 197, 94, 0.2)';
|
||||||
|
pill.style.color = '#22c55e';
|
||||||
|
pill.style.borderColor = 'rgba(34, 197, 94, 0.3)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { console.error("Error checking local:", e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAvailableExtensions() {
|
||||||
|
try {
|
||||||
|
if (!bookData?.entry_type) return;
|
||||||
|
console.log(bookData.entry_type)
|
||||||
|
|
||||||
|
const type = bookData.entry_type === 'MANGA' ? 'manga' : 'novel';
|
||||||
|
const res = await fetch(`/api/extensions/${type}`);
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
availableExtensions = data.extensions || [];
|
||||||
|
setupProviderFilter();
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupProviderFilter() {
|
||||||
|
const select = document.getElementById('provider-filter');
|
||||||
|
const manualBtn = document.getElementById('manual-match-btn'); // NUEVO
|
||||||
|
|
||||||
|
if (!select) return;
|
||||||
|
select.style.display = 'inline-block';
|
||||||
|
select.innerHTML = '';
|
||||||
|
|
||||||
|
const allOpt = document.createElement('option');
|
||||||
|
allOpt.value = 'all';
|
||||||
|
allOpt.innerText = 'All Providers';
|
||||||
|
select.appendChild(allOpt);
|
||||||
|
|
||||||
|
if (isLocal) {
|
||||||
|
const localOpt = document.createElement('option');
|
||||||
|
localOpt.value = 'local';
|
||||||
|
localOpt.innerText = 'Local';
|
||||||
|
select.appendChild(localOpt);
|
||||||
|
}
|
||||||
|
|
||||||
|
availableExtensions.forEach(ext => {
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = ext;
|
||||||
|
opt.innerText = ext.charAt(0).toUpperCase() + ext.slice(1);
|
||||||
|
select.appendChild(opt);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Lógica de selección inicial
|
||||||
|
if (isLocal) select.value = 'local';
|
||||||
|
else if (extensionName && availableExtensions.includes(extensionName)) select.value = extensionName;
|
||||||
|
else if (availableExtensions.length > 0) select.value = availableExtensions[0];
|
||||||
|
|
||||||
|
// Visibilidad inicial del botón manual
|
||||||
|
updateManualButtonVisibility(select.value);
|
||||||
|
|
||||||
|
select.onchange = () => {
|
||||||
|
// Al cambiar de proveedor, reseteamos la selección manual para evitar conflictos
|
||||||
|
manualExtensionBookId = null;
|
||||||
|
updateManualButtonVisibility(select.value);
|
||||||
|
loadChapters(select.value);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateManualButtonVisibility(provider) {
|
||||||
|
const btn = document.getElementById('manual-match-btn');
|
||||||
|
if (!btn) return;
|
||||||
|
|
||||||
|
// Solo mostrar si es un proveedor específico (no 'all' ni 'local')
|
||||||
|
if (provider !== 'all' && provider !== 'local') {
|
||||||
|
btn.style.display = 'flex';
|
||||||
|
} else {
|
||||||
|
btn.style.display = 'none';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateExtensionPill() {
|
||||||
|
const pill = document.getElementById('extension-pill');
|
||||||
|
if(pill && extensionName) { pill.innerText = extensionName; pill.style.display = 'inline-flex'; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setupAddToListButton() {
|
||||||
|
const btn = document.getElementById('add-to-list-btn');
|
||||||
|
if (!btn || !bookData) return;
|
||||||
|
ListModalManager.currentData = bookData;
|
||||||
|
const entryType = ListModalManager.getEntryType(bookData);
|
||||||
|
const idForCheck = extensionName ? bookSlug : bookId;
|
||||||
|
await ListModalManager.checkIfInList(idForCheck, extensionName || 'anilist', entryType);
|
||||||
|
updateCustomAddButton();
|
||||||
|
btn.onclick = () => ListModalManager.open(bookData, extensionName || 'anilist');
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateCustomAddButton() {
|
||||||
|
const btn = document.getElementById('add-to-list-btn');
|
||||||
|
if(btn && ListModalManager.isInList) {
|
||||||
|
btn.innerHTML = '✓ In Your List'; btn.style.background = 'rgba(34, 197, 94, 0.2)'; btn.style.color = '#22c55e'; btn.style.borderColor = '#22c55e';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupModalClickOutside() {
|
||||||
|
const addListModal = document.getElementById('add-list-modal');
|
||||||
|
if (addListModal) {
|
||||||
|
addListModal.addEventListener('click', (e) => {
|
||||||
|
if (e.target.id === 'add-list-modal') ListModalManager.close();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function showError(message) {
|
||||||
|
const titleEl = document.getElementById('title');
|
||||||
|
if (titleEl) titleEl.innerText = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exports
|
||||||
|
window.openReader = openReader;
|
||||||
|
window.saveToList = () => {
|
||||||
|
const idToSave = extensionName ? bookSlug : bookId;
|
||||||
|
ListModalManager.save(idToSave, extensionName || 'anilist');
|
||||||
|
};
|
||||||
|
window.deleteFromList = () => {
|
||||||
|
const idToDelete = extensionName ? bookSlug : bookId;
|
||||||
|
ListModalManager.delete(idToDelete, extensionName || 'anilist');
|
||||||
|
};
|
||||||
|
window.closeAddToListModal = () => ListModalManager.close();
|
||||||
|
window.openAddToListModal = () => ListModalManager.open(bookData, extensionName || 'anilist');
|
||||||
@@ -55,7 +55,8 @@ function startHeroCycle() {
|
|||||||
|
|
||||||
async function updateHeroUI(book) {
|
async function updateHeroUI(book) {
|
||||||
if(!book) return;
|
if(!book) return;
|
||||||
|
book.entry_type =
|
||||||
|
book.format === 'MANGA' ? 'MANGA' : 'NOVEL';
|
||||||
const title = book.title.english || book.title.romaji;
|
const title = book.title.english || book.title.romaji;
|
||||||
const desc = book.description || "No description available.";
|
const desc = book.description || "No description available.";
|
||||||
const poster = (book.coverImage && (book.coverImage.extraLarge || book.coverImage.large)) || '';
|
const poster = (book.coverImage && (book.coverImage.extraLarge || book.coverImage.large)) || '';
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
const reader = document.getElementById('reader');
|
const reader = document.getElementById('reader');
|
||||||
const panel = document.getElementById('settings-panel');
|
const panel = document.getElementById('settings-panel');
|
||||||
const overlay = document.getElementById('overlay');
|
const overlay = document.getElementById('overlay');
|
||||||
@@ -10,6 +11,16 @@ const nextBtn = document.getElementById('next-chapter');
|
|||||||
const lnSettings = document.getElementById('ln-settings');
|
const lnSettings = document.getElementById('ln-settings');
|
||||||
const mangaSettings = document.getElementById('manga-settings');
|
const mangaSettings = document.getElementById('manga-settings');
|
||||||
|
|
||||||
|
|
||||||
|
const rawSource = urlParams.get('source') || 'anilist';
|
||||||
|
const sourceParts = rawSource.split('?');
|
||||||
|
const source = sourceParts[0];
|
||||||
|
|
||||||
|
let lang =
|
||||||
|
urlParams.get('lang') ??
|
||||||
|
new URLSearchParams(sourceParts[1] || '').get('lang') ??
|
||||||
|
'none';
|
||||||
|
|
||||||
const config = {
|
const config = {
|
||||||
ln: {
|
ln: {
|
||||||
fontSize: 18,
|
fontSize: 18,
|
||||||
@@ -33,11 +44,12 @@ let currentType = null;
|
|||||||
let currentPages = [];
|
let currentPages = [];
|
||||||
let observer = null;
|
let observer = null;
|
||||||
|
|
||||||
|
// === CAMBIO: Parseo de URL para obtener ID ===
|
||||||
const parts = window.location.pathname.split('/');
|
const parts = window.location.pathname.split('/');
|
||||||
|
|
||||||
const bookId = parts[4];
|
const bookId = parts[4];
|
||||||
let chapter = parts[3];
|
let currentChapterId = parts[3]; // Ahora es un ID (string)
|
||||||
let provider = parts[2];
|
let provider = parts[2];
|
||||||
|
let chaptersList = []; // Buffer para guardar el orden de capítulos
|
||||||
|
|
||||||
function loadConfig() {
|
function loadConfig() {
|
||||||
try {
|
try {
|
||||||
@@ -97,7 +109,7 @@ function applyStyles() {
|
|||||||
document.documentElement.style.setProperty('--ln-max-width', config.ln.maxWidth + 'px');
|
document.documentElement.style.setProperty('--ln-max-width', config.ln.maxWidth + 'px');
|
||||||
document.documentElement.style.setProperty('--ln-font-family', config.ln.fontFamily);
|
document.documentElement.style.setProperty('--ln-font-family', config.ln.fontFamily);
|
||||||
document.documentElement.style.setProperty('--ln-text-color', config.ln.textColor);
|
document.documentElement.style.setProperty('--ln-text-color', config.ln.textColor);
|
||||||
document.documentElement.style.setProperty('--bg-base', config.ln.bg);
|
document.documentElement.style.setProperty('--color-bg-base', config.ln.bg);
|
||||||
document.documentElement.style.setProperty('--ln-text-align', config.ln.textAlign);
|
document.documentElement.style.setProperty('--ln-text-align', config.ln.textAlign);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,6 +128,28 @@ function updateSettingsVisibility() {
|
|||||||
mangaSettings.classList.toggle('hidden', currentType !== 'manga');
|
mangaSettings.classList.toggle('hidden', currentType !== 'manga');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// === CAMBIO: Nueva función para traer la lista de capítulos y saber el orden ===
|
||||||
|
async function fetchChapterList() {
|
||||||
|
try {
|
||||||
|
// Reusamos el endpoint que lista capítulos
|
||||||
|
const res = await fetch(`/api/book/${bookId}/chapters?source=${source}&provider=${provider}`);
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
// Ordenamos por número para asegurar navegación correcta
|
||||||
|
let list = data.chapters || [];
|
||||||
|
list.sort((a, b) => Number(a.number) - Number(b.number));
|
||||||
|
|
||||||
|
// Si hay filtro de idioma en la URL, filtramos la navegación también
|
||||||
|
if (lang !== 'none') {
|
||||||
|
list = list.filter(c => c.language === lang);
|
||||||
|
}
|
||||||
|
|
||||||
|
chaptersList = list;
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Error fetching chapter list:", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function loadChapter() {
|
async function loadChapter() {
|
||||||
reader.innerHTML = `
|
reader.innerHTML = `
|
||||||
<div class="loading-container">
|
<div class="loading-container">
|
||||||
@@ -124,26 +158,74 @@ async function loadChapter() {
|
|||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const urlParams = new URLSearchParams(window.location.search);
|
// === CAMBIO: Si no tenemos la lista de capítulos (y no es local), la pedimos ===
|
||||||
let source = urlParams.get('source');
|
if (provider !== 'local' && chaptersList.length === 0) {
|
||||||
if (!source) {
|
await fetchChapterList();
|
||||||
source = 'anilist';
|
}
|
||||||
|
|
||||||
|
let newEndpoint;
|
||||||
|
|
||||||
|
if (provider === 'local') {
|
||||||
|
newEndpoint = `/api/library/${bookId}/units`;
|
||||||
|
} else {
|
||||||
|
// === CAMBIO: Usamos currentChapterId en la URL ===
|
||||||
|
newEndpoint = `/api/book/${bookId}/${currentChapterId}/${provider}?source=${source}&lang=${lang}`;
|
||||||
}
|
}
|
||||||
const newEndpoint = `/api/book/${bookId}/${chapter}/${provider}?source=${source}`;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(newEndpoint);
|
const res = await fetch(newEndpoint);
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
|
|
||||||
if (data.title) {
|
const chapterMeta = chaptersList.find(
|
||||||
chapterLabel.textContent = data.title;
|
c => String(c.id) === String(currentChapterId)
|
||||||
document.title = data.title;
|
);
|
||||||
} else {
|
|
||||||
chapterLabel.textContent = `Chapter ${chapter}`;
|
if (chapterMeta) {
|
||||||
document.title = `Chapter ${chapter}`;
|
chapterLabel.textContent = `Chapter ${chapterMeta.number} - ${chapterMeta.title}`;
|
||||||
|
document.title = `Chapter ${chapterMeta.number} - ${chapterMeta.title}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
setupProgressTracking(data, source);
|
// Lógica específica para contenido LOCAL
|
||||||
|
if (provider === 'local') {
|
||||||
|
const unit = data.units.find(u => String(u.id) === String(currentChapterId));
|
||||||
|
|
||||||
|
if (!unit) {
|
||||||
|
reader.innerHTML = '<div class="loading-container"><span>Chapter not found (Local)</span></div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const manifestRes = await fetch(`/api/library/${unit.id}/manifest`);
|
||||||
|
const manifest = await manifestRes.json();
|
||||||
|
|
||||||
|
reader.innerHTML = '';
|
||||||
|
|
||||||
|
// Setup navegación manual para local (simple index +/- 1)
|
||||||
|
const unitIndex = data.units.findIndex(
|
||||||
|
u => String(u.id) === String(currentChapterId)
|
||||||
|
);
|
||||||
|
setupLocalNavigation(unitIndex, data.units.length);
|
||||||
|
|
||||||
|
|
||||||
|
if (manifest.type === 'manga') {
|
||||||
|
currentType = 'manga';
|
||||||
|
updateSettingsVisibility();
|
||||||
|
applyStyles();
|
||||||
|
currentPages = manifest.pages;
|
||||||
|
await loadManga(currentPages);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (manifest.type === 'ln') {
|
||||||
|
currentType = 'ln';
|
||||||
|
updateSettingsVisibility();
|
||||||
|
applyStyles();
|
||||||
|
const contentRes = await fetch(manifest.url);
|
||||||
|
const html = await contentRes.text();
|
||||||
|
loadLN(html);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const rawSource = urlParams.get('source') || 'anilist';
|
||||||
|
const source = rawSource.split('?')[0];
|
||||||
|
|
||||||
const res2 = await fetch(`/api/book/${bookId}?source=${source}`);
|
const res2 = await fetch(`/api/book/${bookId}?source=${source}`);
|
||||||
const data2 = await res2.json();
|
const data2 = await res2.json();
|
||||||
@@ -157,15 +239,27 @@ async function loadChapter() {
|
|||||||
mode: "reading"
|
mode: "reading"
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
if (data.error) {
|
if (data.error) {
|
||||||
reader.innerHTML = `
|
reader.innerHTML = `<div class="loading-container"><span style="color: #ef4444;">Error: ${data.error}</span></div>`;
|
||||||
<div class="loading-container">
|
|
||||||
<span style="color: #ef4444;">Error: ${data.error}</span>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!chapterMeta) {
|
||||||
|
if (data.title) {
|
||||||
|
chapterLabel.textContent = `Chapter ${data.number ?? ''} - ${data.title}`;
|
||||||
|
document.title = chapterLabel.textContent;
|
||||||
|
} else {
|
||||||
|
chapterLabel.textContent = `Chapter ${data.number ?? currentChapterId}`;
|
||||||
|
document.title = chapterLabel.textContent;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setupProgressTracking(data, source);
|
||||||
|
|
||||||
|
// === CAMBIO: Actualizar botones basado en IDs ===
|
||||||
|
updateNavigationButtons();
|
||||||
|
|
||||||
currentType = data.type;
|
currentType = data.type;
|
||||||
updateSettingsVisibility();
|
updateSettingsVisibility();
|
||||||
applyStyles();
|
applyStyles();
|
||||||
@@ -173,11 +267,12 @@ async function loadChapter() {
|
|||||||
|
|
||||||
if (data.type === 'manga') {
|
if (data.type === 'manga') {
|
||||||
currentPages = data.pages || [];
|
currentPages = data.pages || [];
|
||||||
loadManga(currentPages);
|
await loadManga(currentPages);
|
||||||
} else if (data.type === 'ln') {
|
} else if (data.type === 'ln') {
|
||||||
loadLN(data.content);
|
loadLN(data.content);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
reader.innerHTML = `
|
reader.innerHTML = `
|
||||||
<div class="loading-container">
|
<div class="loading-container">
|
||||||
<span style="color: #ef4444;">Error loading chapter: ${error.message}</span>
|
<span style="color: #ef4444;">Error loading chapter: ${error.message}</span>
|
||||||
@@ -186,7 +281,91 @@ async function loadChapter() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function loadManga(pages) {
|
// === CAMBIO: Lógica de navegación basada en IDs ===
|
||||||
|
function updateNavigationButtons() {
|
||||||
|
if (provider === 'local') return; // Se maneja aparte
|
||||||
|
|
||||||
|
// Buscamos el índice actual en la lista completa
|
||||||
|
const currentIndex = chaptersList.findIndex(c => String(c.id) === String(currentChapterId));
|
||||||
|
|
||||||
|
if (currentIndex === -1) {
|
||||||
|
console.warn("Current chapter not found in list, navigation disabled");
|
||||||
|
prevBtn.disabled = true;
|
||||||
|
nextBtn.disabled = true;
|
||||||
|
prevBtn.style.opacity = 0.5;
|
||||||
|
nextBtn.style.opacity = 0.5;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configurar botón ANTERIOR
|
||||||
|
if (currentIndex > 0) {
|
||||||
|
const prevId = chaptersList[currentIndex - 1].id;
|
||||||
|
prevBtn.onclick = () => changeChapter(prevId);
|
||||||
|
prevBtn.disabled = false;
|
||||||
|
prevBtn.style.opacity = 1;
|
||||||
|
} else {
|
||||||
|
prevBtn.onclick = null;
|
||||||
|
prevBtn.disabled = true;
|
||||||
|
prevBtn.style.opacity = 0.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configurar botón SIGUIENTE
|
||||||
|
if (currentIndex < chaptersList.length - 1) {
|
||||||
|
const nextId = chaptersList[currentIndex + 1].id;
|
||||||
|
nextBtn.onclick = () => changeChapter(nextId);
|
||||||
|
nextBtn.disabled = false;
|
||||||
|
nextBtn.style.opacity = 1;
|
||||||
|
} else {
|
||||||
|
nextBtn.onclick = null;
|
||||||
|
nextBtn.disabled = true;
|
||||||
|
nextBtn.style.opacity = 0.5;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback para navegación local (basada en índices)
|
||||||
|
function setupLocalNavigation(currentIndex, totalUnits) {
|
||||||
|
if (currentIndex > 0) {
|
||||||
|
prevBtn.onclick = () => changeChapter(currentIndex - 1);
|
||||||
|
prevBtn.disabled = false;
|
||||||
|
prevBtn.style.opacity = 1;
|
||||||
|
} else {
|
||||||
|
prevBtn.disabled = true;
|
||||||
|
prevBtn.style.opacity = 0.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentIndex < totalUnits - 1) {
|
||||||
|
nextBtn.onclick = () => changeChapter(currentIndex + 1);
|
||||||
|
nextBtn.disabled = false;
|
||||||
|
nextBtn.style.opacity = 1;
|
||||||
|
} else {
|
||||||
|
nextBtn.disabled = true;
|
||||||
|
nextBtn.style.opacity = 0.5;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function changeChapter(newId) {
|
||||||
|
currentChapterId = newId;
|
||||||
|
updateURL(newId);
|
||||||
|
window.scrollTo(0, 0);
|
||||||
|
loadChapter();
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadLongStrip(container, pages) {
|
||||||
|
pages.forEach((page, index) => {
|
||||||
|
const img = createImageElement(page, index);
|
||||||
|
img.classList.remove('fit-width', 'fit-height', 'fit-screen');
|
||||||
|
|
||||||
|
img.classList.add('longstrip-fit');
|
||||||
|
container.appendChild(img);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateURL(newId) {
|
||||||
|
const newUrl = `/read/${provider}/${newId}/${bookId}?source=${source}&lang=${lang}`;
|
||||||
|
window.history.pushState({}, '', newUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadManga(pages) {
|
||||||
if (!pages || pages.length === 0) {
|
if (!pages || pages.length === 0) {
|
||||||
reader.innerHTML = '<div class="loading-container"><span>No pages found</span></div>';
|
reader.innerHTML = '<div class="loading-container"><span>No pages found</span></div>';
|
||||||
return;
|
return;
|
||||||
@@ -195,18 +374,22 @@ function loadManga(pages) {
|
|||||||
const container = document.createElement('div');
|
const container = document.createElement('div');
|
||||||
container.className = 'manga-container';
|
container.className = 'manga-container';
|
||||||
|
|
||||||
let isLongStrip = false;
|
const analysis = await analyzePages(pages);
|
||||||
|
|
||||||
if (config.manga.mode === 'longstrip') {
|
const isLongStrip =
|
||||||
isLongStrip = true;
|
config.manga.mode === 'longstrip' ||
|
||||||
} else if (config.manga.mode === 'auto' && detectLongStrip(pages)) {
|
(config.manga.mode === 'auto' && analysis.tallRatio > 0.3);
|
||||||
isLongStrip = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const useDouble = config.manga.mode === 'double' ||
|
const useDouble =
|
||||||
(config.manga.mode === 'auto' && !isLongStrip && shouldUseDoublePage(pages));
|
!isLongStrip &&
|
||||||
|
(
|
||||||
|
config.manga.mode === 'double' ||
|
||||||
|
(config.manga.mode === 'auto' && analysis.wideRatio < 0.3)
|
||||||
|
);
|
||||||
|
|
||||||
if (useDouble) {
|
if (isLongStrip) {
|
||||||
|
loadLongStrip(container, pages);
|
||||||
|
} else if (useDouble) {
|
||||||
loadDoublePage(container, pages);
|
loadDoublePage(container, pages);
|
||||||
} else {
|
} else {
|
||||||
loadSinglePage(container, pages);
|
loadSinglePage(container, pages);
|
||||||
@@ -217,20 +400,6 @@ function loadManga(pages) {
|
|||||||
enableMangaPageNavigation();
|
enableMangaPageNavigation();
|
||||||
}
|
}
|
||||||
|
|
||||||
function shouldUseDoublePage(pages) {
|
|
||||||
if (pages.length <= 5) return false;
|
|
||||||
|
|
||||||
const widePages = pages.filter(p => {
|
|
||||||
if (!p.height || !p.width) return false;
|
|
||||||
const ratio = p.width / p.height;
|
|
||||||
return ratio > 1.3;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (widePages.length > pages.length * 0.3) return false;
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadSinglePage(container, pages) {
|
function loadSinglePage(container, pages) {
|
||||||
pages.forEach((page, index) => {
|
pages.forEach((page, index) => {
|
||||||
const img = createImageElement(page, index);
|
const img = createImageElement(page, index);
|
||||||
@@ -267,7 +436,6 @@ function loadDoublePage(container, pages) {
|
|||||||
i++;
|
i++;
|
||||||
} else {
|
} else {
|
||||||
const rightPage = createImageElement(nextPage, i + 1);
|
const rightPage = createImageElement(nextPage, i + 1);
|
||||||
|
|
||||||
if (config.manga.direction === 'rtl') {
|
if (config.manga.direction === 'rtl') {
|
||||||
doubleContainer.appendChild(rightPage);
|
doubleContainer.appendChild(rightPage);
|
||||||
doubleContainer.appendChild(leftPage);
|
doubleContainer.appendChild(leftPage);
|
||||||
@@ -275,7 +443,6 @@ function loadDoublePage(container, pages) {
|
|||||||
doubleContainer.appendChild(leftPage);
|
doubleContainer.appendChild(leftPage);
|
||||||
doubleContainer.appendChild(rightPage);
|
doubleContainer.appendChild(rightPage);
|
||||||
}
|
}
|
||||||
|
|
||||||
container.appendChild(doubleContainer);
|
container.appendChild(doubleContainer);
|
||||||
i += 2;
|
i += 2;
|
||||||
}
|
}
|
||||||
@@ -293,7 +460,9 @@ function createImageElement(page, index) {
|
|||||||
img.className = 'page-img';
|
img.className = 'page-img';
|
||||||
img.dataset.index = index;
|
img.dataset.index = index;
|
||||||
|
|
||||||
const url = buildProxyUrl(page.url, page.headers);
|
const url = provider === 'local'
|
||||||
|
? page.url
|
||||||
|
: buildProxyUrl(page.url, page.headers);
|
||||||
const placeholder = "/public/assets/placeholder.svg";
|
const placeholder = "/public/assets/placeholder.svg";
|
||||||
|
|
||||||
img.onerror = () => {
|
img.onerror = () => {
|
||||||
@@ -302,6 +471,18 @@ function createImageElement(page, index) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
img.onload = () => {
|
||||||
|
const ratio = img.naturalWidth / img.naturalHeight;
|
||||||
|
|
||||||
|
if (ratio > 1.3) {
|
||||||
|
const double = img.closest('.double-container');
|
||||||
|
if (double) {
|
||||||
|
double.replaceWith(img);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
if (config.manga.mode === 'longstrip' && index > 0) {
|
if (config.manga.mode === 'longstrip' && index > 0) {
|
||||||
img.classList.add('longstrip-fit');
|
img.classList.add('longstrip-fit');
|
||||||
} else {
|
} else {
|
||||||
@@ -316,35 +497,60 @@ function createImageElement(page, index) {
|
|||||||
img.dataset.src = url;
|
img.dataset.src = url;
|
||||||
img.loading = 'lazy';
|
img.loading = 'lazy';
|
||||||
}
|
}
|
||||||
|
|
||||||
img.alt = `Page ${index + 1}`;
|
img.alt = `Page ${index + 1}`;
|
||||||
|
|
||||||
return img;
|
return img;
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildProxyUrl(url, headers = {}) {
|
function buildProxyUrl(url, headers = {}) {
|
||||||
const params = new URLSearchParams({
|
const params = new URLSearchParams({ url });
|
||||||
url
|
if (headers.Referer || headers.referer)
|
||||||
});
|
params.append("referer", headers.Referer || headers.referer);
|
||||||
|
if (headers["User-Agent"] || headers["user-agent"])
|
||||||
if (headers.referer) params.append('referer', headers.referer);
|
params.append("userAgent", headers["User-Agent"] || headers["user-agent"]);
|
||||||
if (headers['user-agent']) params.append('ua', headers['user-agent']);
|
if (headers.Origin || headers.origin)
|
||||||
if (headers.cookie) params.append('cookie', headers.cookie);
|
params.append("origin", headers.Origin || headers.origin);
|
||||||
|
|
||||||
return `/api/proxy?${params.toString()}`;
|
return `/api/proxy?${params.toString()}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function detectLongStrip(pages) {
|
function analyzePages(pages, sample = 6) {
|
||||||
if (!pages || pages.length === 0) return false;
|
return new Promise(resolve => {
|
||||||
|
let tall = 0;
|
||||||
|
let wide = 0;
|
||||||
|
let loaded = 0;
|
||||||
|
|
||||||
const relevant = pages.slice(1);
|
const count = Math.min(sample, pages.length);
|
||||||
const tall = relevant.filter(p => p.height && p.width && (p.height / p.width) > 2);
|
|
||||||
return tall.length >= 2 || (tall.length / relevant.length) > 0.3;
|
for (let i = 0; i < count; i++) {
|
||||||
|
const img = new Image();
|
||||||
|
img.src = provider === 'local'
|
||||||
|
? pages[i].url
|
||||||
|
: buildProxyUrl(pages[i].url, pages[i].headers);
|
||||||
|
|
||||||
|
img.onload = () => {
|
||||||
|
const ratio = img.naturalWidth / img.naturalHeight;
|
||||||
|
if (ratio < 0.6) tall++;
|
||||||
|
else if (ratio > 1.3) wide++;
|
||||||
|
loaded++;
|
||||||
|
if (loaded === count) finish();
|
||||||
|
};
|
||||||
|
|
||||||
|
img.onerror = () => {
|
||||||
|
loaded++;
|
||||||
|
if (loaded === count) finish();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function finish() {
|
||||||
|
resolve({
|
||||||
|
tallRatio: tall / count,
|
||||||
|
wideRatio: wide / count
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function setupLazyLoading() {
|
function setupLazyLoading() {
|
||||||
if (observer) observer.disconnect();
|
if (observer) observer.disconnect();
|
||||||
|
|
||||||
observer = new IntersectionObserver((entries) => {
|
observer = new IntersectionObserver((entries) => {
|
||||||
entries.forEach(entry => {
|
entries.forEach(entry => {
|
||||||
if (entry.isIntersecting) {
|
if (entry.isIntersecting) {
|
||||||
@@ -356,10 +562,7 @@ function setupLazyLoading() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}, {
|
}, { rootMargin: '200px' });
|
||||||
rootMargin: '200px'
|
|
||||||
});
|
|
||||||
|
|
||||||
document.querySelectorAll('img[data-src]').forEach(img => observer.observe(img));
|
document.querySelectorAll('img[data-src]').forEach(img => observer.observe(img));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -370,161 +573,100 @@ function loadLN(html) {
|
|||||||
reader.appendChild(div);
|
reader.appendChild(div);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Listeners de configuración
|
||||||
document.getElementById('font-size').addEventListener('input', (e) => {
|
document.getElementById('font-size').addEventListener('input', (e) => {
|
||||||
config.ln.fontSize = parseInt(e.target.value);
|
config.ln.fontSize = parseInt(e.target.value);
|
||||||
document.getElementById('font-size-value').textContent = e.target.value + 'px';
|
document.getElementById('font-size-value').textContent = e.target.value + 'px';
|
||||||
applyStyles();
|
applyStyles(); saveConfig();
|
||||||
saveConfig();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('line-height').addEventListener('input', (e) => {
|
document.getElementById('line-height').addEventListener('input', (e) => {
|
||||||
config.ln.lineHeight = parseFloat(e.target.value);
|
config.ln.lineHeight = parseFloat(e.target.value);
|
||||||
document.getElementById('line-height-value').textContent = e.target.value;
|
document.getElementById('line-height-value').textContent = e.target.value;
|
||||||
applyStyles();
|
applyStyles(); saveConfig();
|
||||||
saveConfig();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('max-width').addEventListener('input', (e) => {
|
document.getElementById('max-width').addEventListener('input', (e) => {
|
||||||
config.ln.maxWidth = parseInt(e.target.value);
|
config.ln.maxWidth = parseInt(e.target.value);
|
||||||
document.getElementById('max-width-value').textContent = e.target.value + 'px';
|
document.getElementById('max-width-value').textContent = e.target.value + 'px';
|
||||||
applyStyles();
|
applyStyles(); saveConfig();
|
||||||
saveConfig();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('font-family').addEventListener('change', (e) => {
|
document.getElementById('font-family').addEventListener('change', (e) => {
|
||||||
config.ln.fontFamily = e.target.value;
|
config.ln.fontFamily = e.target.value;
|
||||||
applyStyles();
|
applyStyles(); saveConfig();
|
||||||
saveConfig();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('text-color').addEventListener('change', (e) => {
|
document.getElementById('text-color').addEventListener('change', (e) => {
|
||||||
config.ln.textColor = e.target.value;
|
config.ln.textColor = e.target.value;
|
||||||
applyStyles();
|
applyStyles(); saveConfig();
|
||||||
saveConfig();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('bg-color').addEventListener('change', (e) => {
|
document.getElementById('bg-color').addEventListener('change', (e) => {
|
||||||
config.ln.bg = e.target.value;
|
config.ln.bg = e.target.value;
|
||||||
applyStyles();
|
applyStyles(); saveConfig();
|
||||||
saveConfig();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
document.querySelectorAll('[data-align]').forEach(btn => {
|
document.querySelectorAll('[data-align]').forEach(btn => {
|
||||||
btn.addEventListener('click', () => {
|
btn.addEventListener('click', () => {
|
||||||
document.querySelectorAll('[data-align]').forEach(b => b.classList.remove('active'));
|
document.querySelectorAll('[data-align]').forEach(b => b.classList.remove('active'));
|
||||||
btn.classList.add('active');
|
btn.classList.add('active');
|
||||||
config.ln.textAlign = btn.dataset.align;
|
config.ln.textAlign = btn.dataset.align;
|
||||||
applyStyles();
|
applyStyles(); saveConfig();
|
||||||
saveConfig();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
document.querySelectorAll('[data-preset]').forEach(btn => {
|
document.querySelectorAll('[data-preset]').forEach(btn => {
|
||||||
btn.addEventListener('click', () => {
|
btn.addEventListener('click', () => {
|
||||||
const preset = btn.dataset.preset;
|
const preset = btn.dataset.preset;
|
||||||
|
|
||||||
const presets = {
|
const presets = {
|
||||||
dark: { bg: '#14141b', textColor: '#e5e7eb' },
|
dark: { bg: '#14141b', textColor: '#e5e7eb' },
|
||||||
sepia: { bg: '#f4ecd8', textColor: '#5c472d' },
|
sepia: { bg: '#f4ecd8', textColor: '#5c472d' },
|
||||||
light: { bg: '#fafafa', textColor: '#1f2937' },
|
light: { bg: '#fafafa', textColor: '#1f2937' },
|
||||||
amoled: { bg: '#000000', textColor: '#ffffff' }
|
amoled: { bg: '#000000', textColor: '#ffffff' }
|
||||||
};
|
};
|
||||||
|
|
||||||
if (presets[preset]) {
|
if (presets[preset]) {
|
||||||
Object.assign(config.ln, presets[preset]);
|
Object.assign(config.ln, presets[preset]);
|
||||||
document.getElementById('bg-color').value = config.ln.bg;
|
document.getElementById('bg-color').value = config.ln.bg;
|
||||||
document.getElementById('text-color').value = config.ln.textColor;
|
document.getElementById('text-color').value = config.ln.textColor;
|
||||||
applyStyles();
|
applyStyles(); saveConfig();
|
||||||
saveConfig();
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('display-mode').addEventListener('change', (e) => {
|
document.getElementById('display-mode').addEventListener('change', (e) => {
|
||||||
config.manga.mode = e.target.value;
|
config.manga.mode = e.target.value;
|
||||||
saveConfig();
|
saveConfig(); loadChapter();
|
||||||
loadChapter();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('image-fit').addEventListener('change', (e) => {
|
document.getElementById('image-fit').addEventListener('change', (e) => {
|
||||||
config.manga.imageFit = e.target.value;
|
config.manga.imageFit = e.target.value;
|
||||||
saveConfig();
|
saveConfig(); loadChapter();
|
||||||
loadChapter();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('page-spacing').addEventListener('input', (e) => {
|
document.getElementById('page-spacing').addEventListener('input', (e) => {
|
||||||
config.manga.spacing = parseInt(e.target.value);
|
config.manga.spacing = parseInt(e.target.value);
|
||||||
document.getElementById('page-spacing-value').textContent = e.target.value + 'px';
|
document.getElementById('page-spacing-value').textContent = e.target.value + 'px';
|
||||||
applyStyles();
|
applyStyles(); saveConfig();
|
||||||
saveConfig();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('preload-count').addEventListener('change', (e) => {
|
document.getElementById('preload-count').addEventListener('change', (e) => {
|
||||||
config.manga.preloadCount = parseInt(e.target.value);
|
config.manga.preloadCount = parseInt(e.target.value);
|
||||||
saveConfig();
|
saveConfig();
|
||||||
});
|
});
|
||||||
|
|
||||||
document.querySelectorAll('[data-direction]').forEach(btn => {
|
document.querySelectorAll('[data-direction]').forEach(btn => {
|
||||||
btn.addEventListener('click', () => {
|
btn.addEventListener('click', () => {
|
||||||
document.querySelectorAll('[data-direction]').forEach(b => b.classList.remove('active'));
|
document.querySelectorAll('[data-direction]').forEach(b => b.classList.remove('active'));
|
||||||
btn.classList.add('active');
|
btn.classList.add('active');
|
||||||
config.manga.direction = btn.dataset.direction;
|
config.manga.direction = btn.dataset.direction;
|
||||||
saveConfig();
|
saveConfig(); loadChapter();
|
||||||
loadChapter();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
prevBtn.addEventListener('click', () => {
|
// Botón "Atrás"
|
||||||
const current = parseInt(chapter);
|
|
||||||
if (current <= 0) return;
|
|
||||||
|
|
||||||
const newChapter = String(current - 1);
|
|
||||||
updateURL(newChapter);
|
|
||||||
window.scrollTo(0, 0);
|
|
||||||
loadChapter();
|
|
||||||
});
|
|
||||||
|
|
||||||
nextBtn.addEventListener('click', () => {
|
|
||||||
const newChapter = String(parseInt(chapter) + 1);
|
|
||||||
updateURL(newChapter);
|
|
||||||
window.scrollTo(0, 0);
|
|
||||||
loadChapter();
|
|
||||||
});
|
|
||||||
|
|
||||||
function updateURL(newChapter) {
|
|
||||||
chapter = newChapter;
|
|
||||||
const urlParams = new URLSearchParams(window.location.search);
|
|
||||||
let source = urlParams.get('source');
|
|
||||||
|
|
||||||
let src;
|
|
||||||
if (source === 'anilist') {
|
|
||||||
src= "?source=anilist"
|
|
||||||
} else {
|
|
||||||
src= `?source=${source}`
|
|
||||||
}
|
|
||||||
const newUrl = `/read/${provider}/${chapter}/${bookId}${src}`;
|
|
||||||
window.history.pushState({}, '', newUrl);
|
|
||||||
}
|
|
||||||
|
|
||||||
document.getElementById('back-btn').addEventListener('click', () => {
|
document.getElementById('back-btn').addEventListener('click', () => {
|
||||||
const parts = window.location.pathname.split('/');
|
|
||||||
const mangaId = parts[4];
|
|
||||||
|
|
||||||
const urlParams = new URLSearchParams(window.location.search);
|
if (source === 'anilist' || !source) {
|
||||||
let source = urlParams.get('source');
|
window.location.href = `/book/${bookId}`;
|
||||||
|
|
||||||
if (source === 'anilist') {
|
|
||||||
window.location.href = `/book/${mangaId}`;
|
|
||||||
} else {
|
} else {
|
||||||
window.location.href = `/book/${source}/${mangaId}`;
|
window.location.href = `/book/${source}/${bookId}`;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Panel de configuración
|
||||||
settingsBtn.addEventListener('click', () => {
|
settingsBtn.addEventListener('click', () => {
|
||||||
panel.classList.add('open');
|
panel.classList.add('open');
|
||||||
overlay.classList.add('active');
|
overlay.classList.add('active');
|
||||||
});
|
});
|
||||||
|
|
||||||
closePanel.addEventListener('click', closeSettings);
|
closePanel.addEventListener('click', closeSettings);
|
||||||
overlay.addEventListener('click', closeSettings);
|
overlay.addEventListener('click', closeSettings);
|
||||||
|
|
||||||
@@ -532,7 +674,6 @@ function closeSettings() {
|
|||||||
panel.classList.remove('open');
|
panel.classList.remove('open');
|
||||||
overlay.classList.remove('active');
|
overlay.classList.remove('active');
|
||||||
}
|
}
|
||||||
|
|
||||||
document.addEventListener('keydown', (e) => {
|
document.addEventListener('keydown', (e) => {
|
||||||
if (e.key === 'Escape' && panel.classList.contains('open')) {
|
if (e.key === 'Escape' && panel.classList.contains('open')) {
|
||||||
closeSettings();
|
closeSettings();
|
||||||
@@ -542,37 +683,24 @@ document.addEventListener('keydown', (e) => {
|
|||||||
function enableMangaPageNavigation() {
|
function enableMangaPageNavigation() {
|
||||||
if (currentType !== 'manga') return;
|
if (currentType !== 'manga') return;
|
||||||
const logicalPages = [];
|
const logicalPages = [];
|
||||||
|
|
||||||
document.querySelectorAll('.manga-container > *').forEach(el => {
|
document.querySelectorAll('.manga-container > *').forEach(el => {
|
||||||
if (el.classList.contains('double-container')) {
|
if (el.classList.contains('double-container') || el.tagName === 'IMG') {
|
||||||
logicalPages.push(el);
|
|
||||||
} else if (el.tagName === 'IMG') {
|
|
||||||
logicalPages.push(el);
|
logicalPages.push(el);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (logicalPages.length === 0) return;
|
if (logicalPages.length === 0) return;
|
||||||
|
|
||||||
function scrollToLogical(index) {
|
function scrollToLogical(index) {
|
||||||
if (index < 0 || index >= logicalPages.length) return;
|
if (index < 0 || index >= logicalPages.length) return;
|
||||||
|
|
||||||
const topBar = document.querySelector('.top-bar');
|
const topBar = document.querySelector('.top-bar');
|
||||||
const offset = topBar ? -topBar.offsetHeight : 0;
|
const offset = topBar ? -topBar.offsetHeight : 0;
|
||||||
|
const y = logicalPages[index].getBoundingClientRect().top + window.pageYOffset + offset;
|
||||||
const y = logicalPages[index].getBoundingClientRect().top
|
window.scrollTo({ top: y, behavior: 'smooth' });
|
||||||
+ window.pageYOffset
|
|
||||||
+ offset;
|
|
||||||
|
|
||||||
window.scrollTo({
|
|
||||||
top: y,
|
|
||||||
behavior: 'smooth'
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function getCurrentLogicalIndex() {
|
function getCurrentLogicalIndex() {
|
||||||
let closest = 0;
|
let closest = 0;
|
||||||
let minDist = Infinity;
|
let minDist = Infinity;
|
||||||
|
|
||||||
logicalPages.forEach((el, i) => {
|
logicalPages.forEach((el, i) => {
|
||||||
const rect = el.getBoundingClientRect();
|
const rect = el.getBoundingClientRect();
|
||||||
const dist = Math.abs(rect.top);
|
const dist = Math.abs(rect.top);
|
||||||
@@ -581,53 +709,36 @@ function enableMangaPageNavigation() {
|
|||||||
closest = i;
|
closest = i;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return closest;
|
return closest;
|
||||||
}
|
}
|
||||||
|
|
||||||
const rtl = () => config.manga.direction === 'rtl';
|
const rtl = () => config.manga.direction === 'rtl';
|
||||||
|
|
||||||
document.addEventListener('keydown', (e) => {
|
document.addEventListener('keydown', (e) => {
|
||||||
if (currentType !== 'manga') return;
|
if (currentType !== 'manga') return;
|
||||||
if (e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT') return;
|
if (e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT') return;
|
||||||
|
|
||||||
const index = getCurrentLogicalIndex();
|
const index = getCurrentLogicalIndex();
|
||||||
|
if (e.key === 'ArrowLeft') scrollToLogical(rtl() ? index + 1 : index - 1);
|
||||||
if (e.key === 'ArrowLeft') {
|
if (e.key === 'ArrowRight') scrollToLogical(rtl() ? index - 1 : index + 1);
|
||||||
scrollToLogical(rtl() ? index + 1 : index - 1);
|
|
||||||
}
|
|
||||||
if (e.key === 'ArrowRight') {
|
|
||||||
scrollToLogical(rtl() ? index - 1 : index + 1);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
reader.addEventListener('click', (e) => {
|
reader.addEventListener('click', (e) => {
|
||||||
if (currentType !== 'manga') return;
|
if (currentType !== 'manga') return;
|
||||||
|
|
||||||
const bounds = reader.getBoundingClientRect();
|
const bounds = reader.getBoundingClientRect();
|
||||||
const x = e.clientX - bounds.left;
|
const x = e.clientX - bounds.left;
|
||||||
const half = bounds.width / 2;
|
const half = bounds.width / 2;
|
||||||
|
|
||||||
const index = getCurrentLogicalIndex();
|
const index = getCurrentLogicalIndex();
|
||||||
|
if (x < half) scrollToLogical(rtl() ? index + 1 : index - 1);
|
||||||
if (x < half) {
|
else scrollToLogical(rtl() ? index - 1 : index + 1);
|
||||||
scrollToLogical(rtl() ? index + 1 : index - 1);
|
|
||||||
} else {
|
|
||||||
scrollToLogical(rtl() ? index - 1 : index + 1);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let resizeTimer;
|
let resizeTimer;
|
||||||
window.addEventListener('resize', () => {
|
window.addEventListener('resize', () => {
|
||||||
clearTimeout(resizeTimer);
|
clearTimeout(resizeTimer);
|
||||||
resizeTimer = setTimeout(() => {
|
resizeTimer = setTimeout(() => { applyStyles(); }, 250);
|
||||||
applyStyles();
|
|
||||||
}, 250);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let progressSaved = false;
|
let progressSaved = false;
|
||||||
|
|
||||||
function setupProgressTracking(data, source) {
|
function setupProgressTracking(data, source) {
|
||||||
progressSaved = false;
|
progressSaved = false;
|
||||||
|
|
||||||
@@ -640,25 +751,16 @@ function setupProgressTracking(data, source) {
|
|||||||
source: source,
|
source: source,
|
||||||
entry_type: data.type === 'manga' ? 'MANGA' : 'NOVEL',
|
entry_type: data.type === 'manga' ? 'MANGA' : 'NOVEL',
|
||||||
status: 'CURRENT',
|
status: 'CURRENT',
|
||||||
progress: source === 'anilist'
|
progress: source === 'anilist' ? Math.floor(chapterNumber) : chapterNumber
|
||||||
? Math.floor(chapterNumber)
|
|
||||||
|
|
||||||
: chapterNumber
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await fetch('/api/list/entry', {
|
await fetch('/api/list/entry', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Authorization': `Bearer ${token}`
|
|
||||||
},
|
|
||||||
body: JSON.stringify(body)
|
body: JSON.stringify(body)
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) { console.error('Error updating progress:', err); }
|
||||||
console.error('Error updating progress:', err);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function checkProgress() {
|
function checkProgress() {
|
||||||
@@ -668,25 +770,22 @@ function setupProgressTracking(data, source) {
|
|||||||
|
|
||||||
if (percent >= 0.8 && !progressSaved) {
|
if (percent >= 0.8 && !progressSaved) {
|
||||||
progressSaved = true;
|
progressSaved = true;
|
||||||
|
|
||||||
const chapterNumber = (typeof data.number !== 'undefined' && data.number !== null)
|
const chapterNumber = (typeof data.number !== 'undefined' && data.number !== null)
|
||||||
? data.number
|
? data.number
|
||||||
: Number(chapter);
|
: 0; // Fallback si no hay numero
|
||||||
|
|
||||||
sendProgress(chapterNumber);
|
sendProgress(chapterNumber);
|
||||||
|
|
||||||
window.removeEventListener('scroll', checkProgress);
|
window.removeEventListener('scroll', checkProgress);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
window.removeEventListener('scroll', checkProgress);
|
window.removeEventListener('scroll', checkProgress);
|
||||||
window.addEventListener('scroll', checkProgress);
|
window.addEventListener('scroll', checkProgress);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!bookId || !chapter || !provider) {
|
if (!bookId || !currentChapterId || !provider) {
|
||||||
reader.innerHTML = `
|
reader.innerHTML = `
|
||||||
<div class="loading-container">
|
<div class="loading-container">
|
||||||
<span style="color: #ef4444;">Missing required parameters (bookId, chapter, provider)</span>
|
<span style="color: #ef4444;">Missing required parameters (bookId, chapterId, provider)</span>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
} else {
|
} else {
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
const providerSelector = document.getElementById('provider-selector');
|
const providerSelector = document.getElementById('provider-selector');
|
||||||
const searchInput = document.getElementById('main-search-input');
|
const searchInput = document.getElementById('search-input');
|
||||||
const resultsContainer = document.getElementById('gallery-results');
|
const resultsContainer = document.getElementById('gallery-results');
|
||||||
|
|
||||||
let currentPage = 1;
|
let currentPage = 1;
|
||||||
@@ -299,7 +299,7 @@ async function searchGallery(isLoadMore = false) {
|
|||||||
const msg = favoritesMode
|
const msg = favoritesMode
|
||||||
? (query ? 'No favorites found matching your search' : 'You don\'t have any favorite images yet')
|
? (query ? 'No favorites found matching your search' : 'You don\'t have any favorite images yet')
|
||||||
: 'No results found';
|
: 'No results found';
|
||||||
resultsContainer.innerHTML = `<p style="text-align:center;color:var(--text-secondary);padding:4rem;font-size:1.1rem;">${msg}</p>`;
|
resultsContainer.innerHTML = `<p style="text-align:center;color:var(--color-text-secondary);padding:4rem;font-size:1.1rem;">${msg}</p>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (msnry) msnry.layout();
|
if (msnry) msnry.layout();
|
||||||
BIN
desktop/src/scripts/jassub/default.woff2
Normal file
BIN
desktop/src/scripts/jassub/jassub-worker-modern.wasm
Normal file
11
desktop/src/scripts/jassub/jassub-worker.js
Normal file
BIN
desktop/src/scripts/jassub/jassub-worker.wasm
Normal file
262
desktop/src/scripts/marketplace.js
Normal file
@@ -0,0 +1,262 @@
|
|||||||
|
const ORIGINAL_MARKETPLACE_URL = 'https://git.waifuboard.app/ItsSkaiya/WaifuBoard-Extensions/raw/branch/main/marketplace.json';
|
||||||
|
const MARKETPLACE_JSON_URL = `/api/proxy?url=${encodeURIComponent(ORIGINAL_MARKETPLACE_URL)}`;
|
||||||
|
const INSTALLED_EXTENSIONS_API = '/api/extensions';
|
||||||
|
const UPDATE_EXTENSIONS_API = '/api/extensions/update';
|
||||||
|
|
||||||
|
const marketplaceContent = document.getElementById('marketplace-content');
|
||||||
|
const filterSelect = document.getElementById('extension-filter');
|
||||||
|
const updateAllBtn = document.getElementById('btn-update-all');
|
||||||
|
|
||||||
|
const modal = document.getElementById('customModal');
|
||||||
|
const modalTitle = document.getElementById('modalTitle');
|
||||||
|
const modalMessage = document.getElementById('modalMessage');
|
||||||
|
const modalConfirmBtn = document.getElementById('modalConfirmButton');
|
||||||
|
const modalCloseBtn = document.getElementById('modalCloseButton');
|
||||||
|
|
||||||
|
let marketplaceMetadata = {};
|
||||||
|
let installedExtensions = [];
|
||||||
|
let currentTab = 'marketplace';
|
||||||
|
|
||||||
|
async function loadMarketplace() {
|
||||||
|
showSkeletons();
|
||||||
|
try {
|
||||||
|
const [metaRes, installedRes] = await Promise.all([
|
||||||
|
fetch(MARKETPLACE_JSON_URL).then(res => res.json()),
|
||||||
|
fetch(INSTALLED_EXTENSIONS_API).then(res => res.json())
|
||||||
|
]);
|
||||||
|
|
||||||
|
marketplaceMetadata = metaRes.extensions;
|
||||||
|
installedExtensions = (installedRes.extensions || []).map(e => e.toLowerCase());
|
||||||
|
|
||||||
|
initTabs();
|
||||||
|
renderGroupedView();
|
||||||
|
|
||||||
|
if (filterSelect) {
|
||||||
|
filterSelect.addEventListener('change', () => renderGroupedView());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (updateAllBtn) {
|
||||||
|
updateAllBtn.onclick = handleUpdateAll;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading marketplace:', error);
|
||||||
|
marketplaceContent.innerHTML = `<div class="error-msg">Error al cargar el marketplace.</div>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function initTabs() {
|
||||||
|
const tabs = document.querySelectorAll('.tab-button');
|
||||||
|
tabs.forEach(tab => {
|
||||||
|
tab.onclick = () => {
|
||||||
|
tabs.forEach(t => t.classList.remove('active'));
|
||||||
|
tab.classList.add('active');
|
||||||
|
currentTab = tab.dataset.tab;
|
||||||
|
|
||||||
|
if (updateAllBtn) {
|
||||||
|
if (currentTab === 'installed') {
|
||||||
|
updateAllBtn.classList.remove('hidden');
|
||||||
|
} else {
|
||||||
|
updateAllBtn.classList.add('hidden');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
renderGroupedView();
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleUpdateAll() {
|
||||||
|
const originalText = updateAllBtn.innerText;
|
||||||
|
try {
|
||||||
|
updateAllBtn.disabled = true;
|
||||||
|
updateAllBtn.innerText = 'Updating...';
|
||||||
|
|
||||||
|
const res = await fetch(UPDATE_EXTENSIONS_API, { method: 'POST' });
|
||||||
|
if (!res.ok) throw new Error('Update failed');
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (data.updated && data.updated.length > 0) {
|
||||||
|
|
||||||
|
const list = data.updated.join(', ');
|
||||||
|
window.NotificationUtils.success(`Updated: ${list}`);
|
||||||
|
|
||||||
|
await loadMarketplace();
|
||||||
|
} else {
|
||||||
|
window.NotificationUtils.info('Everything is up to date.');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Update All Error:', error);
|
||||||
|
window.NotificationUtils.error('Failed to perform bulk update.');
|
||||||
|
} finally {
|
||||||
|
updateAllBtn.disabled = false;
|
||||||
|
updateAllBtn.innerText = originalText;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderGroupedView() {
|
||||||
|
marketplaceContent.innerHTML = '';
|
||||||
|
const activeFilter = filterSelect.value;
|
||||||
|
const groups = {};
|
||||||
|
|
||||||
|
let listToRender = [];
|
||||||
|
|
||||||
|
if (currentTab === 'marketplace') {
|
||||||
|
for (const [id, data] of Object.entries(marketplaceMetadata)) {
|
||||||
|
listToRender.push({
|
||||||
|
id,
|
||||||
|
...data,
|
||||||
|
isInstalled: installedExtensions.includes(id.toLowerCase())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (const [id, data] of Object.entries(marketplaceMetadata)) {
|
||||||
|
if (installedExtensions.includes(id.toLowerCase())) {
|
||||||
|
listToRender.push({ id, ...data, isInstalled: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
installedExtensions.forEach(id => {
|
||||||
|
const existsInMeta = Object.keys(marketplaceMetadata).some(k => k.toLowerCase() === id);
|
||||||
|
if (!existsInMeta) {
|
||||||
|
listToRender.push({
|
||||||
|
id: id,
|
||||||
|
name: id.charAt(0).toUpperCase() + id.slice(1),
|
||||||
|
type: 'Local',
|
||||||
|
author: 'Unknown',
|
||||||
|
isInstalled: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
listToRender.forEach(ext => {
|
||||||
|
const type = ext.type || 'Other';
|
||||||
|
if (activeFilter !== 'All' && type !== activeFilter) return;
|
||||||
|
if (!groups[type]) groups[type] = [];
|
||||||
|
groups[type].push(ext);
|
||||||
|
});
|
||||||
|
|
||||||
|
const sortedTypes = Object.keys(groups).sort();
|
||||||
|
|
||||||
|
if (sortedTypes.length === 0) {
|
||||||
|
marketplaceContent.innerHTML = `<p class="empty-msg">No extensions found for this criteria.</p>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sortedTypes.forEach(type => {
|
||||||
|
const section = document.createElement('div');
|
||||||
|
section.className = 'category-group';
|
||||||
|
|
||||||
|
const title = document.createElement('h2');
|
||||||
|
title.className = 'marketplace-section-title';
|
||||||
|
title.innerText = type.replace('-', ' ');
|
||||||
|
|
||||||
|
const grid = document.createElement('div');
|
||||||
|
grid.className = 'marketplace-grid';
|
||||||
|
|
||||||
|
groups[type].forEach(ext => grid.appendChild(createCard(ext)));
|
||||||
|
|
||||||
|
section.appendChild(title);
|
||||||
|
section.appendChild(grid);
|
||||||
|
marketplaceContent.appendChild(section);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function createCard(ext) {
|
||||||
|
const card = document.createElement('div');
|
||||||
|
card.className = `extension-card ${ext.nsfw ? 'nsfw-ext' : ''} ${ext.broken ? 'broken-ext' : ''}`;
|
||||||
|
|
||||||
|
const iconUrl = `https://www.google.com/s2/favicons?domain=${ext.domain}&sz=128`;
|
||||||
|
|
||||||
|
let buttonHtml = '';
|
||||||
|
if (ext.isInstalled) {
|
||||||
|
buttonHtml = `<button class="extension-action-button btn-uninstall">Uninstall</button>`;
|
||||||
|
} else if (ext.broken) {
|
||||||
|
buttonHtml = `<button class="extension-action-button" style="background: #4b5563; cursor: not-allowed;" disabled>Broken</button>`;
|
||||||
|
} else {
|
||||||
|
buttonHtml = `<button class="extension-action-button btn-install">Install</button>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
card.innerHTML = `
|
||||||
|
<img class="extension-icon" src="${iconUrl}" onerror="this.src='/public/assets/waifuboards.ico'">
|
||||||
|
<div class="card-content-wrapper">
|
||||||
|
<h3 class="extension-name">${ext.name}</h3>
|
||||||
|
<span class="extension-author">by ${ext.author || 'Unknown'}</span>
|
||||||
|
<p class="extension-description">${ext.description || 'No description available.'}</p>
|
||||||
|
<div class="extension-tags">
|
||||||
|
<span class="extension-status-badge badge-${ext.isInstalled ? 'installed' : (ext.broken ? 'local' : 'available')}">
|
||||||
|
${ext.isInstalled ? 'Installed' : (ext.broken ? 'Broken' : 'Available')}
|
||||||
|
</span>
|
||||||
|
${ext.nsfw ? '<span class="extension-status-badge badge-local">NSFW</span>' : ''}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
${buttonHtml}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const btn = card.querySelector('.extension-action-button');
|
||||||
|
if (!ext.broken || ext.isInstalled) {
|
||||||
|
btn.onclick = () => ext.isInstalled ? promptUninstall(ext) : handleInstall(ext);
|
||||||
|
}
|
||||||
|
|
||||||
|
return card;
|
||||||
|
}
|
||||||
|
|
||||||
|
function showModal(title, message, showConfirm = false, onConfirm = null) {
|
||||||
|
modalTitle.innerText = title;
|
||||||
|
modalMessage.innerText = message;
|
||||||
|
if (showConfirm) {
|
||||||
|
modalConfirmBtn.classList.remove('hidden');
|
||||||
|
modalConfirmBtn.onclick = () => { hideModal(); if (onConfirm) onConfirm(); };
|
||||||
|
} else {
|
||||||
|
modalConfirmBtn.classList.add('hidden');
|
||||||
|
}
|
||||||
|
modalCloseBtn.onclick = hideModal;
|
||||||
|
modal.classList.remove('hidden');
|
||||||
|
}
|
||||||
|
|
||||||
|
function hideModal() { modal.classList.add('hidden'); }
|
||||||
|
|
||||||
|
async function handleInstall(ext) {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/extensions/install', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ url: ext.entry })
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
installedExtensions.push(ext.id.toLowerCase());
|
||||||
|
renderGroupedView();
|
||||||
|
window.NotificationUtils.success(`${ext.name} installed!`);
|
||||||
|
}
|
||||||
|
} catch (e) { window.NotificationUtils.error('Install failed.'); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function promptUninstall(ext) {
|
||||||
|
showModal('Confirm', `Uninstall ${ext.name}?`, true, () => handleUninstall(ext));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleUninstall(ext) {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/extensions/uninstall', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ fileName: ext.id + '.js' })
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
installedExtensions = installedExtensions.filter(id => id !== ext.id.toLowerCase());
|
||||||
|
renderGroupedView();
|
||||||
|
window.NotificationUtils.info(`${ext.name} uninstalled.`);
|
||||||
|
}
|
||||||
|
} catch (e) { window.NotificationUtils.error('Uninstall failed.'); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function showSkeletons() {
|
||||||
|
marketplaceContent.innerHTML = `
|
||||||
|
<div class="marketplace-grid">
|
||||||
|
${Array(3).fill('<div class="extension-card skeleton"></div>').join('')}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', loadMarketplace);
|
||||||
811
desktop/src/scripts/profile.js
Normal file
@@ -0,0 +1,811 @@
|
|||||||
|
const API_BASE = '/api';
|
||||||
|
|
||||||
|
const DashboardApp = {
|
||||||
|
|
||||||
|
State: {
|
||||||
|
currentList: [],
|
||||||
|
filteredList: [],
|
||||||
|
localLibraryData: [],
|
||||||
|
currentUserId: null,
|
||||||
|
currentLocalType: 'anime',
|
||||||
|
pagination: {
|
||||||
|
itemsPerPage: 50,
|
||||||
|
visibleCount: 50
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
init: async function() {
|
||||||
|
console.log('Initializing Dashboard...');
|
||||||
|
await this.User.init();
|
||||||
|
await this.Tracking.load();
|
||||||
|
|
||||||
|
this.UI.setupTabSystem();
|
||||||
|
this.initListeners();
|
||||||
|
|
||||||
|
const localInput = document.getElementById('local-search-input');
|
||||||
|
if(localInput) {
|
||||||
|
localInput.addEventListener('input', (e) => this.Library.filterContent(e.target.value));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
initListeners: function() {
|
||||||
|
|
||||||
|
document.getElementById('scan-incremental-btn')?.addEventListener('click', () => this.Library.triggerScan('incremental'));
|
||||||
|
document.getElementById('scan-full-btn')?.addEventListener('click', () => this.Library.triggerScan('full'));
|
||||||
|
|
||||||
|
document.getElementById('profile-form')?.addEventListener('submit', (e) => this.User.updateProfile(e));
|
||||||
|
document.getElementById('password-form')?.addEventListener('submit', (e) => this.User.changePassword(e));
|
||||||
|
document.getElementById('logout-btn')?.addEventListener('click', () => window.AuthUtils.logout());
|
||||||
|
|
||||||
|
const fileInput = document.getElementById('avatar-upload');
|
||||||
|
if (fileInput) {
|
||||||
|
fileInput.addEventListener('change', (e) => {
|
||||||
|
const file = e.target.files[0];
|
||||||
|
if (file) {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = evt => {
|
||||||
|
document.getElementById('user-avatar').src = evt.target.result;
|
||||||
|
const urlInput = document.getElementById('setting-avatar-url');
|
||||||
|
if(urlInput) urlInput.value = '';
|
||||||
|
};
|
||||||
|
reader.readAsDataURL(file);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const trackingInput = document.getElementById('tracking-search-input');
|
||||||
|
if (trackingInput) trackingInput.addEventListener('input', () => this.Tracking.applyFilters());
|
||||||
|
|
||||||
|
['status-filter', 'type-filter', 'sort-filter'].forEach(id => {
|
||||||
|
document.getElementById(id)?.addEventListener('change', () => this.Tracking.applyFilters());
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll('.view-btn').forEach(btn => {
|
||||||
|
btn.addEventListener('click', () => {
|
||||||
|
document.querySelectorAll('.view-btn').forEach(b => b.classList.remove('active'));
|
||||||
|
btn.classList.add('active');
|
||||||
|
const view = btn.dataset.view;
|
||||||
|
const container = document.getElementById('list-container');
|
||||||
|
view === 'list' ? container.classList.add('list-view') : container.classList.remove('list-view');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
User: {
|
||||||
|
init: async function() {
|
||||||
|
try {
|
||||||
|
const headers = window.AuthUtils.getSimpleAuthHeaders();
|
||||||
|
const res = await fetch(`${API_BASE}/me`, { headers });
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
document.getElementById('user-username').textContent = data.username;
|
||||||
|
const settingUsername = document.getElementById('setting-username');
|
||||||
|
if(settingUsername) settingUsername.value = data.username;
|
||||||
|
|
||||||
|
if (data.avatar) {
|
||||||
|
document.getElementById('user-avatar').src = data.avatar;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
if (token) {
|
||||||
|
const payload = JSON.parse(atob(token.split('.')[1]));
|
||||||
|
DashboardApp.State.currentUserId = payload.id;
|
||||||
|
await this.checkIntegrations(payload.id);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error loading user profile:", err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
checkIntegrations: async function(userId) {
|
||||||
|
if (!userId) return;
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_BASE}/users/${userId}/integration`);
|
||||||
|
let data = { connected: false };
|
||||||
|
if (res.ok) data = await res.json();
|
||||||
|
|
||||||
|
this.updateIntegrationUI(data, userId);
|
||||||
|
} catch (e) { console.error("Integration check error:", e); }
|
||||||
|
},
|
||||||
|
|
||||||
|
updateIntegrationUI: function(data, userId) {
|
||||||
|
const statusEl = document.getElementById('anilist-status');
|
||||||
|
const btn = document.getElementById('anilist-action-btn');
|
||||||
|
const headerBadge = document.getElementById('header-anilist-link');
|
||||||
|
|
||||||
|
if (data.connected) {
|
||||||
|
if (headerBadge) {
|
||||||
|
headerBadge.style.display = 'flex';
|
||||||
|
headerBadge.href = `https://anilist.co/user/${data.anilistUserId}`;
|
||||||
|
headerBadge.title = `Connected as ${data.anilistUserId}`;
|
||||||
|
}
|
||||||
|
if (statusEl) {
|
||||||
|
// CAMBIO: Mostrar fecha de expiración si existe
|
||||||
|
const expiresDate = data.expiresAt ? new Date(data.expiresAt).toLocaleDateString() : 'Unknown';
|
||||||
|
statusEl.innerHTML = `
|
||||||
|
<span style="color:var(--color-success)">Connected as: <b>${data.anilistUserId}</b></span>
|
||||||
|
<span style="display:block; font-size:0.75rem; color:#71717a">Expires: ${expiresDate}</span>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
if (btn) {
|
||||||
|
btn.textContent = 'Disconnect';
|
||||||
|
btn.className = 'btn-stream-outline link-danger';
|
||||||
|
btn.onclick = () => this.disconnectAniList(userId);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (headerBadge) headerBadge.style.display = 'none';
|
||||||
|
if (statusEl) {
|
||||||
|
statusEl.textContent = 'Not connected';
|
||||||
|
statusEl.style.color = 'var(--color-text-secondary)';
|
||||||
|
}
|
||||||
|
if (btn) {
|
||||||
|
btn.textContent = 'Connect';
|
||||||
|
btn.className = 'btn-stream-outline';
|
||||||
|
btn.onclick = () => this.openAniListModal();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
redirectToAniListLogin: async function() {
|
||||||
|
if (!DashboardApp.State.currentUserId) return;
|
||||||
|
try {
|
||||||
|
const clientId = 32898;
|
||||||
|
const redirectUri = encodeURIComponent(window.location.origin + '/api/anilist');
|
||||||
|
const state = encodeURIComponent(DashboardApp.State.currentUserId);
|
||||||
|
window.location.href = `https://anilist.co/api/v2/oauth/authorize?client_id=${clientId}&response_type=code&redirect_uri=${redirectUri}&state=${state}`;
|
||||||
|
} catch (err) { console.error(err); alert('Error starting AniList login'); }
|
||||||
|
},
|
||||||
|
openAniListModal: function() {
|
||||||
|
const modal = document.getElementById('anilist-connect-modal');
|
||||||
|
const body = document.getElementById('anilist-modal-body');
|
||||||
|
const clientId = 32898; // Tu Client ID
|
||||||
|
|
||||||
|
// Generamos el HTML del modal dinámicamente
|
||||||
|
body.innerHTML = `
|
||||||
|
<p class="modal-description">Connect your AniList account to sync your progress automatically.</p>
|
||||||
|
|
||||||
|
<div style="margin-bottom: 1.5rem;">
|
||||||
|
<label style="display:block; font-size:0.85rem; font-weight:600; color:#a1a1aa; margin-bottom:0.5rem">Step 1: Get Token</label>
|
||||||
|
<a href="https://anilist.co/api/v2/oauth/authorize?client_id=${clientId}&response_type=token"
|
||||||
|
target="_blank"
|
||||||
|
class="btn-blur"
|
||||||
|
style="width:100%; text-align:center; box-sizing:border-box; display:block;">
|
||||||
|
Open AniList Login ↗
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="input-group">
|
||||||
|
<label>Step 2: Paste Token</label>
|
||||||
|
<input type="text" id="manual-anilist-token" class="stream-input" placeholder="Paste the long access token here..." autocomplete="off">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-footer" style="padding:0; background:transparent;">
|
||||||
|
<button class="btn-primary" style="width:100%" onclick="DashboardApp.User.submitAniListToken()">Verify & Connect</button>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
modal.classList.remove('hidden');
|
||||||
|
},
|
||||||
|
|
||||||
|
closeAniListModal: function() {
|
||||||
|
document.getElementById('anilist-connect-modal').classList.add('hidden');
|
||||||
|
},
|
||||||
|
|
||||||
|
submitAniListToken: async function() {
|
||||||
|
const tokenInput = document.getElementById('manual-anilist-token');
|
||||||
|
const token = tokenInput.value.trim();
|
||||||
|
const userId = DashboardApp.State.currentUserId;
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
alert('Please paste the AniList token first');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const confirmBtn = document.querySelector('#anilist-connect-modal .btn-primary');
|
||||||
|
const originalText = confirmBtn.textContent;
|
||||||
|
confirmBtn.textContent = "Verifying...";
|
||||||
|
confirmBtn.disabled = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_BASE}/anilist/store`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
userId: userId,
|
||||||
|
accessToken: token
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (!res.ok) throw new Error(data.error || 'Failed to verify token');
|
||||||
|
|
||||||
|
this.closeAniListModal();
|
||||||
|
await this.checkIntegrations(userId);
|
||||||
|
alert('AniList connected successfully!');
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
alert(err.message || 'Invalid Token');
|
||||||
|
} finally {
|
||||||
|
confirmBtn.textContent = originalText;
|
||||||
|
confirmBtn.disabled = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
disconnectAniList: async function(userId) {
|
||||||
|
if(!confirm("Disconnect AniList?")) return;
|
||||||
|
try {
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
await fetch(`${API_BASE}/users/${userId}/integration`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
headers: { 'Authorization': `Bearer ${token}` }
|
||||||
|
});
|
||||||
|
this.checkIntegrations(userId);
|
||||||
|
} catch (e) { alert("Failed to disconnect"); }
|
||||||
|
},
|
||||||
|
|
||||||
|
updateProfile: async function(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
const userId = DashboardApp.State.currentUserId;
|
||||||
|
if (!userId) return;
|
||||||
|
|
||||||
|
const username = document.getElementById('setting-username').value;
|
||||||
|
const urlInput = document.getElementById('setting-avatar-url')?.value || '';
|
||||||
|
const fileInput = document.getElementById('avatar-upload');
|
||||||
|
let finalAvatar = null;
|
||||||
|
|
||||||
|
if (fileInput && fileInput.files && fileInput.files[0]) {
|
||||||
|
try {
|
||||||
|
finalAvatar = await DashboardApp.Utils.fileToBase64(fileInput.files[0]);
|
||||||
|
} catch (err) { alert("Error reading file"); return; }
|
||||||
|
} else if (urlInput.trim() !== "") {
|
||||||
|
finalAvatar = urlInput.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
const bodyData = { username };
|
||||||
|
if (finalAvatar) bodyData.profilePictureUrl = finalAvatar;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_BASE}/users/${userId}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { ...window.AuthUtils.getSimpleAuthHeaders(), 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(bodyData)
|
||||||
|
});
|
||||||
|
if (res.ok) alert('Profile updated successfully!');
|
||||||
|
else { const err = await res.json(); alert(err.error || 'Update failed'); }
|
||||||
|
} catch (e) { console.error(e); }
|
||||||
|
},
|
||||||
|
|
||||||
|
changePassword: async function(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
const userId = DashboardApp.State.currentUserId;
|
||||||
|
if (!userId) return;
|
||||||
|
const currentPassword = document.getElementById('current-password').value;
|
||||||
|
const newPassword = document.getElementById('new-password').value;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_BASE}/users/${userId}/password`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { ...window.AuthUtils.getSimpleAuthHeaders(), 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ currentPassword, newPassword })
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (res.ok) { alert("Password updated successfully"); document.getElementById('password-form').reset(); }
|
||||||
|
else alert(data.error || "Failed to update password");
|
||||||
|
} catch (e) { console.error(e); }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
Tracking: {
|
||||||
|
load: async function() {
|
||||||
|
const loadingState = document.getElementById('loading-state');
|
||||||
|
const emptyState = document.getElementById('empty-state');
|
||||||
|
const container = document.getElementById('list-container');
|
||||||
|
|
||||||
|
try {
|
||||||
|
loadingState.style.display = 'flex';
|
||||||
|
emptyState.style.display = 'none';
|
||||||
|
container.innerHTML = '';
|
||||||
|
|
||||||
|
const response = await fetch(`${API_BASE}/list`, { headers: window.AuthUtils.getSimpleAuthHeaders() });
|
||||||
|
if (!response.ok) throw new Error('Failed');
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
DashboardApp.State.currentList = data.results || [];
|
||||||
|
|
||||||
|
this.updateStats();
|
||||||
|
|
||||||
|
loadingState.style.display = 'none';
|
||||||
|
if (DashboardApp.State.currentList.length === 0) emptyState.style.display = 'flex';
|
||||||
|
else this.applyFilters();
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
loadingState.style.display = 'none';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
updateStats: function() {
|
||||||
|
const list = DashboardApp.State.currentList;
|
||||||
|
const animeCount = list.filter(item => item.entry_type === 'ANIME').length;
|
||||||
|
const mangaCount = list.filter(item => item.entry_type === 'MANGA').length;
|
||||||
|
|
||||||
|
document.getElementById('total-stat').textContent = list.length;
|
||||||
|
if (document.getElementById('anime-stat')) document.getElementById('anime-stat').textContent = animeCount;
|
||||||
|
if (document.getElementById('manga-stat')) document.getElementById('manga-stat').textContent = mangaCount;
|
||||||
|
},
|
||||||
|
|
||||||
|
applyFilters: function() {
|
||||||
|
const statusFilter = document.getElementById('status-filter').value;
|
||||||
|
const typeFilter = document.getElementById('type-filter').value;
|
||||||
|
const sortFilter = document.getElementById('sort-filter').value;
|
||||||
|
const searchInput = document.getElementById('tracking-search-input');
|
||||||
|
const searchQuery = searchInput ? searchInput.value.toLowerCase().trim() : '';
|
||||||
|
|
||||||
|
let result = [...DashboardApp.State.currentList];
|
||||||
|
|
||||||
|
if (searchQuery) {
|
||||||
|
result = result.filter(item => (item.title ? item.title.toLowerCase() : '').includes(searchQuery));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (statusFilter !== 'all') result = result.filter(item => item.status === statusFilter);
|
||||||
|
if (typeFilter !== 'all') result = result.filter(item => item.entry_type === typeFilter);
|
||||||
|
|
||||||
|
if (sortFilter === 'title') result.sort((a, b) => (a.title || '').localeCompare(b.title || ''));
|
||||||
|
else if (sortFilter === 'score') result.sort((a, b) => (b.score || 0) - (a.score || 0));
|
||||||
|
else result.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));
|
||||||
|
|
||||||
|
DashboardApp.State.filteredList = result;
|
||||||
|
DashboardApp.State.pagination.visibleCount = DashboardApp.State.pagination.itemsPerPage;
|
||||||
|
this.render();
|
||||||
|
},
|
||||||
|
|
||||||
|
render: function() {
|
||||||
|
const container = document.getElementById('list-container');
|
||||||
|
container.innerHTML = '';
|
||||||
|
const list = DashboardApp.State.filteredList;
|
||||||
|
const count = DashboardApp.State.pagination.visibleCount;
|
||||||
|
|
||||||
|
if (list.length === 0) {
|
||||||
|
container.innerHTML = '<div class="empty-text" style="grid-column: 1/-1; text-align:center; color: var(--color-text-secondary);">No matches found</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemsToShow = list.slice(0, count);
|
||||||
|
itemsToShow.forEach(item => container.appendChild(this.createItemElement(item)));
|
||||||
|
|
||||||
|
if (count < list.length) {
|
||||||
|
this.renderLoadMoreButton(container, list.length - count);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
createItemElement: function(item) {
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.className = 'list-item';
|
||||||
|
|
||||||
|
const itemLink = this.getEntryLink(item);
|
||||||
|
const posterUrl = item.poster || '/public/assets/placeholder.svg';
|
||||||
|
const progress = item.progress || 0;
|
||||||
|
const totalUnits = item.entry_type === 'ANIME' ? item.total_episodes || 0 : item.total_chapters || 0;
|
||||||
|
const progressPercent = totalUnits > 0 ? (progress / totalUnits) * 100 : 0;
|
||||||
|
const score = item.score ? item.score.toFixed(1) : null;
|
||||||
|
const entryType = (item.entry_type).toUpperCase();
|
||||||
|
|
||||||
|
const statusLabels = {
|
||||||
|
'CURRENT': entryType === 'ANIME' ? 'Watching' : 'Reading',
|
||||||
|
'COMPLETED': 'Completed', 'PLANNING': 'Planning', 'PAUSED': 'Paused',
|
||||||
|
'DROPPED': 'Dropped', 'REPEATING': entryType === 'ANIME' ? 'Rewatching' : 'Rereading'
|
||||||
|
};
|
||||||
|
|
||||||
|
const extraInfo = [];
|
||||||
|
if (item.repeat_count > 0) extraInfo.push(`<span class="meta-pill repeat-pill">🔁 ${item.repeat_count}</span>`);
|
||||||
|
if (item.is_private) extraInfo.push('<span class="meta-pill private-pill">🔒 Private</span>');
|
||||||
|
|
||||||
|
div.innerHTML = `
|
||||||
|
<a href="${itemLink}" class="item-poster-link">
|
||||||
|
<img src="${posterUrl}" alt="${item.title}" class="item-poster" onerror="this.src='/public/assets/placeholder.svg'">
|
||||||
|
</a>
|
||||||
|
<div class="item-content">
|
||||||
|
<div>
|
||||||
|
<a href="${itemLink}" style="text-decoration:none; color:inherit;">
|
||||||
|
<h3 class="item-title">${item.title || 'Unknown'}</h3>
|
||||||
|
</a>
|
||||||
|
<div class="item-meta">
|
||||||
|
<span class="meta-pill status-pill">${statusLabels[item.status] || item.status}</span>
|
||||||
|
<span class="meta-pill type-pill">${entryType}</span>
|
||||||
|
<span class="meta-pill source-pill">${item.source.toUpperCase()}</span>
|
||||||
|
${extraInfo.join('')}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="progress-bar-container"><div class="progress-bar" style="width: ${progressPercent}%"></div></div>
|
||||||
|
<div class="progress-text">
|
||||||
|
<span>${progress}${totalUnits > 0 ? ` / ${totalUnits}` : ''}</span>
|
||||||
|
${score ? `<span class="score-badge">⭐ ${score}</span>` : ''}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button class="edit-icon-btn">
|
||||||
|
<svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M15.232 5.232l3.536 3.536m-2.036-5.808a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.536L15.232 5.232z"/></svg>
|
||||||
|
</button>
|
||||||
|
`;
|
||||||
|
|
||||||
|
div.querySelector('.edit-icon-btn').onclick = (e) => {
|
||||||
|
e.preventDefault(); e.stopPropagation();
|
||||||
|
window.ListModalManager.currentData = item;
|
||||||
|
window.ListModalManager.isInList = true;
|
||||||
|
window.ListModalManager.currentEntry = item;
|
||||||
|
window.ListModalManager.open(item, item.source || 'anilist');
|
||||||
|
};
|
||||||
|
|
||||||
|
return div;
|
||||||
|
},
|
||||||
|
|
||||||
|
renderLoadMoreButton: function(container, remaining) {
|
||||||
|
const btnContainer = document.createElement('div');
|
||||||
|
Object.assign(btnContainer.style, { gridColumn: "1 / -1", display: "flex", justifyContent: "center", padding: "2rem 0" });
|
||||||
|
|
||||||
|
const loadMoreBtn = document.createElement('button');
|
||||||
|
loadMoreBtn.className = "btn-blur";
|
||||||
|
loadMoreBtn.textContent = `Show All (${remaining} more)`;
|
||||||
|
loadMoreBtn.onclick = () => {
|
||||||
|
DashboardApp.State.pagination.visibleCount = DashboardApp.State.filteredList.length;
|
||||||
|
this.render();
|
||||||
|
};
|
||||||
|
|
||||||
|
btnContainer.appendChild(loadMoreBtn);
|
||||||
|
container.appendChild(btnContainer);
|
||||||
|
},
|
||||||
|
|
||||||
|
getEntryLink: function(item) {
|
||||||
|
const baseRoute = (item.entry_type?.toUpperCase() === 'ANIME') ? '/anime' : '/book';
|
||||||
|
return `${baseRoute}/${item.entry_id}`;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
Library: {
|
||||||
|
tempMatchContext: null,
|
||||||
|
pollInterval: null,
|
||||||
|
updateDownloadStatus: async function() {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_BASE}/library/downloads/status`, {
|
||||||
|
headers: window.AuthUtils.getSimpleAuthHeaders()
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) return;
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
this.renderDownloadMonitor(data);
|
||||||
|
|
||||||
|
// Si hay descargas completadas nuevas, podríamos recargar la lista de archivos
|
||||||
|
// (Opcional: lógica para detectar cambios y llamar a loadContent)
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Error polling downloads:", e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
renderDownloadMonitor: function(data) {
|
||||||
|
const monitor = document.getElementById('downloads-monitor');
|
||||||
|
const listContainer = document.getElementById('downloads-list-container');
|
||||||
|
const activeCountEl = document.getElementById('dl-stat-active');
|
||||||
|
|
||||||
|
// Datos por defecto
|
||||||
|
const downloads = data.downloads || { list: [], active: 0, failed: 0 };
|
||||||
|
|
||||||
|
// Actualizar contadores cabecera
|
||||||
|
if(activeCountEl) activeCountEl.textContent = `${downloads.active} Active / ${downloads.list.length} Total`;
|
||||||
|
|
||||||
|
// Ocultar si vacío
|
||||||
|
if (downloads.list.length === 0) {
|
||||||
|
monitor.classList.add('hidden');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
monitor.classList.remove('hidden');
|
||||||
|
|
||||||
|
listContainer.innerHTML = downloads.list.map(item => {
|
||||||
|
const fileName = item.fileName || `Unknown_File_${item.unitNumber}`;
|
||||||
|
const folderName = item.folderName || 'Unsorted';
|
||||||
|
const status = item.status || 'pending';
|
||||||
|
const progress = item.progress || 0;
|
||||||
|
const speed = item.speed || '0 KB/s';
|
||||||
|
|
||||||
|
const isCompleted = status === 'completed';
|
||||||
|
const isFailed = status === 'failed';
|
||||||
|
|
||||||
|
let statusText = `${progress}%`;
|
||||||
|
if (isCompleted) statusText = 'Done';
|
||||||
|
if (isFailed) statusText = 'Failed';
|
||||||
|
|
||||||
|
const folderIcon = `<svg width="12" height="12" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"/></svg>`;
|
||||||
|
|
||||||
|
// ESTRUCTURA NUEVA: Más plana para permitir Flexbox horizontal
|
||||||
|
return `
|
||||||
|
<div class="dl-item compact">
|
||||||
|
<div class="dl-left-col">
|
||||||
|
<div class="dl-filename" title="${fileName}">${fileName}</div>
|
||||||
|
<div class="dl-folder" title="${folderName}">${folderIcon} ${folderName}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="dl-right-col">
|
||||||
|
<div class="dl-meta-info">
|
||||||
|
<span class="dl-speed">${isCompleted ? '' : speed}</span>
|
||||||
|
<span class="dl-status-text ${status}">${statusText}</span>
|
||||||
|
</div>
|
||||||
|
<div class="dl-progress-track">
|
||||||
|
<div class="dl-progress-fill ${status}" style="width: ${progress}%"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}).join('');
|
||||||
|
},
|
||||||
|
|
||||||
|
startPolling: function() {
|
||||||
|
if (this.pollInterval) clearInterval(this.pollInterval);
|
||||||
|
this.updateDownloadStatus(); // Primera llamada inmediata
|
||||||
|
this.pollInterval = setInterval(() => this.updateDownloadStatus(), 2000); // Cada 2 segundos
|
||||||
|
},
|
||||||
|
|
||||||
|
stopPolling: function() {
|
||||||
|
if (this.pollInterval) {
|
||||||
|
clearInterval(this.pollInterval);
|
||||||
|
this.pollInterval = null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
loadStats: async function() {
|
||||||
|
const types = ['anime', 'manga', 'novels'];
|
||||||
|
const elements = { 'anime': 'local-anime-count', 'manga': 'local-manga-count', 'novels': 'local-novel-count' };
|
||||||
|
|
||||||
|
for (const type of types) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_BASE}/library/${type}`, { headers: window.AuthUtils.getSimpleAuthHeaders() });
|
||||||
|
if(res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
const el = document.getElementById(elements[type]);
|
||||||
|
if (el) el.textContent = `${data.length} items`;
|
||||||
|
}
|
||||||
|
} catch (e) { console.error(e); }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
loadContent: async function(type) {
|
||||||
|
DashboardApp.State.currentLocalType = type;
|
||||||
|
const container = document.getElementById('local-list-container');
|
||||||
|
const loading = document.getElementById('local-loading');
|
||||||
|
const searchInput = document.getElementById('local-search-input');
|
||||||
|
|
||||||
|
container.innerHTML = '';
|
||||||
|
loading.style.display = 'flex';
|
||||||
|
if(searchInput) searchInput.value = '';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_BASE}/library/${type}`, { headers: window.AuthUtils.getSimpleAuthHeaders() });
|
||||||
|
if (!res.ok) throw new Error('Failed to load local content');
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
DashboardApp.State.localLibraryData = data;
|
||||||
|
this.renderGrid(data, type);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
container.innerHTML = `<div class="empty-state"><p>Error loading library</p></div>`;
|
||||||
|
} finally {
|
||||||
|
loading.style.display = 'none';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
renderGrid: function(entries, type) {
|
||||||
|
const container = document.getElementById('local-list-container');
|
||||||
|
container.innerHTML = '';
|
||||||
|
|
||||||
|
if (entries.length === 0) {
|
||||||
|
container.innerHTML = `
|
||||||
|
<div class="empty-state" style="grid-column: 1/-1;">
|
||||||
|
<p>No ${type} files found.</p>
|
||||||
|
<button onclick="DashboardApp.Library.triggerScan('incremental')" class="btn-blur">Scan Now</button>
|
||||||
|
</div>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
entries.forEach(entry => {
|
||||||
|
const isMatched = entry.matched && entry.metadata;
|
||||||
|
const meta = entry.metadata || {};
|
||||||
|
let poster = meta.coverImage?.large || '/public/assets/placeholder.svg';
|
||||||
|
|
||||||
|
let title = isMatched ? (meta.title?.english || meta.title?.romaji) : entry.path;
|
||||||
|
if (!isMatched) title = title.replace(/\[.*?\]|\(.*?\)|\.mkv|\.mp4/g, '').trim();
|
||||||
|
|
||||||
|
const url = isMatched ? (type === 'anime' ? `/anime/${meta.id}` : `/book/${meta.id}`) : '#';
|
||||||
|
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.className = 'list-item';
|
||||||
|
div.innerHTML = `
|
||||||
|
<div class="item-poster-link" onclick="${isMatched ? `window.location='${url}'` : ''}" style="cursor: ${isMatched ? 'pointer' : 'default'}">
|
||||||
|
<img src="${poster}" class="item-poster" loading="lazy">
|
||||||
|
${!isMatched ? `<div class="unmatched-badge"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg> UNMATCHED</div>` : ''}
|
||||||
|
</div>
|
||||||
|
<div class="item-content">
|
||||||
|
<h3 class="item-title" title="${entry.path}">${title}</h3>
|
||||||
|
<div class="item-meta">
|
||||||
|
<span class="meta-pill type-pill">${entry.files} FILES</span>
|
||||||
|
${isMatched ? '<span class="meta-pill status-pill">MATCHED</span>' : ''}
|
||||||
|
</div>
|
||||||
|
<div class="folder-path-tooltip">${entry.path}</div>
|
||||||
|
</div>
|
||||||
|
<button class="edit-icon-btn" onclick="DashboardApp.Library.openManualMatch('${entry.id}', '${type}')" title="${isMatched ? 'Rematch' : 'Fix Match'}">
|
||||||
|
<svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
|
||||||
|
</button>
|
||||||
|
`;
|
||||||
|
container.appendChild(div);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
filterContent: function(query) {
|
||||||
|
if (!DashboardApp.State.localLibraryData) return;
|
||||||
|
const lowerQuery = query.toLowerCase();
|
||||||
|
const filtered = DashboardApp.State.localLibraryData.filter(entry => {
|
||||||
|
const metaTitle = entry.metadata?.title?.english || entry.metadata?.title?.romaji || '';
|
||||||
|
const folderName = entry.folder_name || '';
|
||||||
|
return metaTitle.toLowerCase().includes(lowerQuery) || folderName.toLowerCase().includes(lowerQuery);
|
||||||
|
});
|
||||||
|
this.renderGrid(filtered, DashboardApp.State.currentLocalType);
|
||||||
|
},
|
||||||
|
|
||||||
|
triggerScan: async function(mode) {
|
||||||
|
const consoleDiv = document.getElementById('scan-console');
|
||||||
|
const statusText = document.getElementById('scan-status-text');
|
||||||
|
if(consoleDiv) consoleDiv.style.display = 'flex';
|
||||||
|
if(statusText) statusText.textContent = `Starting ${mode} scan...`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_BASE}/library/scan?mode=${mode}`, {
|
||||||
|
method: 'POST', headers: window.AuthUtils.getSimpleAuthHeaders()
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
if(statusText) statusText.textContent = "Scan completed successfully!";
|
||||||
|
setTimeout(() => { if(consoleDiv) consoleDiv.style.display = 'none'; this.loadStats(); }, 3000);
|
||||||
|
} else throw new Error('Scan failed');
|
||||||
|
} catch (e) {
|
||||||
|
if(statusText) { statusText.textContent = "Error during scan."; statusText.style.color = 'var(--color-danger)'; }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
openManualMatch: function(id, type) {
|
||||||
|
const item = DashboardApp.State.localLibraryData.find(x => x.id === id);
|
||||||
|
const pathName = item ? item.path : 'Unknown path';
|
||||||
|
|
||||||
|
this.tempMatchContext = { id, type };
|
||||||
|
|
||||||
|
document.getElementById('manual-match-path').textContent = pathName;
|
||||||
|
document.getElementById('manual-match-id').value = '';
|
||||||
|
|
||||||
|
const modal = document.getElementById('manual-match-modal');
|
||||||
|
modal.classList.remove('hidden');
|
||||||
|
|
||||||
|
setTimeout(() => document.getElementById('manual-match-id').focus(), 100);
|
||||||
|
},
|
||||||
|
|
||||||
|
closeManualMatch: function() {
|
||||||
|
document.getElementById('manual-match-modal').classList.add('hidden');
|
||||||
|
this.tempMatchContext = null;
|
||||||
|
},
|
||||||
|
|
||||||
|
submitManualMatch: async function() {
|
||||||
|
if (!this.tempMatchContext) return;
|
||||||
|
|
||||||
|
const newId = document.getElementById('manual-match-id').value;
|
||||||
|
if (!newId) {
|
||||||
|
alert("Please enter a valid ID");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id, type } = this.tempMatchContext;
|
||||||
|
|
||||||
|
const confirmBtn = document.querySelector('#manual-match-modal .btn-primary');
|
||||||
|
const originalText = confirmBtn.textContent;
|
||||||
|
confirmBtn.textContent = "Matching...";
|
||||||
|
confirmBtn.disabled = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_BASE}/library/${type}/${id}/match`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
...window.AuthUtils.getSimpleAuthHeaders(),
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
source: 'anilist',
|
||||||
|
matched_id: parseInt(newId)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
if(res.ok) {
|
||||||
|
this.closeManualMatch();
|
||||||
|
this.loadContent(type);
|
||||||
|
} else {
|
||||||
|
const errData = await res.json();
|
||||||
|
alert("Failed to match: " + (errData.error || "Unknown error"));
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
alert("Connection error");
|
||||||
|
} finally {
|
||||||
|
confirmBtn.textContent = originalText;
|
||||||
|
confirmBtn.disabled = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
switchType: function(type, btnElement) {
|
||||||
|
document.querySelectorAll('.type-pill-btn').forEach(b => b.classList.remove('active'));
|
||||||
|
if(btnElement) btnElement.classList.add('active');
|
||||||
|
this.loadContent(type);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
UI: {
|
||||||
|
setupTabSystem: function() {
|
||||||
|
const tabs = document.querySelectorAll('.nav-pill');
|
||||||
|
const sections = document.querySelectorAll('.tab-section');
|
||||||
|
|
||||||
|
tabs.forEach(tab => {
|
||||||
|
tab.addEventListener('click', () => {
|
||||||
|
// Gestión de clases activas
|
||||||
|
tabs.forEach(t => t.classList.remove('active'));
|
||||||
|
tab.classList.add('active');
|
||||||
|
|
||||||
|
const targetId = `section-${tab.dataset.target}`;
|
||||||
|
sections.forEach(sec => {
|
||||||
|
sec.classList.remove('active');
|
||||||
|
if (sec.id === targetId) sec.classList.add('active');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Lógica específica por pestaña
|
||||||
|
if (tab.dataset.target === 'local') {
|
||||||
|
DashboardApp.Library.loadStats();
|
||||||
|
DashboardApp.Library.loadContent(DashboardApp.State.currentLocalType || 'anime');
|
||||||
|
DashboardApp.Library.startPolling(); // <--- INICIAR POLLING
|
||||||
|
} else {
|
||||||
|
DashboardApp.Library.stopPolling(); // <--- DETENER POLLING AL SALIR
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
Utils: {
|
||||||
|
fileToBase64: (file) => new Promise((resolve, reject) => {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.readAsDataURL(file);
|
||||||
|
reader.onload = () => resolve(reader.result);
|
||||||
|
reader.onerror = error => reject(error);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
DashboardApp.init();
|
||||||
|
});
|
||||||
|
|
||||||
|
window.switchLocalType = (type, btn) => DashboardApp.Library.switchType(type, btn);
|
||||||
|
|
||||||
|
window.saveToList = async () => {
|
||||||
|
const data = window.ListModalManager.currentData;
|
||||||
|
if (!data) return;
|
||||||
|
const idToSave = data.entry_id || data.id;
|
||||||
|
await window.ListModalManager.save(idToSave, data.source || 'anilist');
|
||||||
|
await DashboardApp.Tracking.load();
|
||||||
|
};
|
||||||
|
|
||||||
|
window.deleteFromList = async () => {
|
||||||
|
const data = window.ListModalManager.currentData;
|
||||||
|
if (!data) return;
|
||||||
|
const idToDelete = data.entry_id || data.id;
|
||||||
|
await window.ListModalManager.delete(idToDelete, data.source || 'anilist');
|
||||||
|
await DashboardApp.Tracking.load();
|
||||||
|
};
|
||||||
|
|
||||||
|
window.closeAddToListModal = () => window.ListModalManager.close();
|
||||||
131
desktop/src/scripts/room-modal.js
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
class CreateRoomModal {
|
||||||
|
constructor() {
|
||||||
|
this.modalId = 'cr-modal-overlay';
|
||||||
|
this.isRendered = false;
|
||||||
|
this.render(); // Crear el HTML en el DOM al instanciar
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
if (document.getElementById(this.modalId)) return;
|
||||||
|
|
||||||
|
const modalHtml = `
|
||||||
|
<div class="cr-modal-overlay" id="${this.modalId}">
|
||||||
|
<div class="cr-modal-content">
|
||||||
|
<button class="cr-modal-close" id="cr-close">✕</button>
|
||||||
|
<h2 class="cr-modal-title">Create Watch Party</h2>
|
||||||
|
|
||||||
|
<form id="cr-form">
|
||||||
|
<div class="cr-form-group">
|
||||||
|
<label>Room Name</label>
|
||||||
|
<input type="text" class="cr-input" name="name" placeholder="My Awesome Room" required maxlength="50" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="cr-form-group">
|
||||||
|
<label>Password (Optional)</label>
|
||||||
|
<input type="password" class="cr-input" name="password" placeholder="Leave empty for public" maxlength="50" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="cr-form-group cr-checkbox-group">
|
||||||
|
<label class="cr-checkbox">
|
||||||
|
<input type="checkbox" name="expose" />
|
||||||
|
<span>Generate public link (via tunnel)</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="cr-actions">
|
||||||
|
<button type="button" class="cr-btn-cancel" id="cr-cancel">Cancel</button>
|
||||||
|
<button type="submit" class="cr-btn-confirm">Create Room</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
document.body.insertAdjacentHTML('beforeend', modalHtml);
|
||||||
|
this.bindEvents();
|
||||||
|
this.isRendered = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bindEvents() {
|
||||||
|
const modal = document.getElementById(this.modalId);
|
||||||
|
const closeBtn = document.getElementById('cr-close');
|
||||||
|
const cancelBtn = document.getElementById('cr-cancel');
|
||||||
|
const form = document.getElementById('cr-form');
|
||||||
|
|
||||||
|
const close = () => this.close();
|
||||||
|
|
||||||
|
closeBtn.onclick = close;
|
||||||
|
cancelBtn.onclick = close;
|
||||||
|
|
||||||
|
// Cerrar si clicamos fuera del contenido
|
||||||
|
modal.onclick = (e) => {
|
||||||
|
if (e.target === modal) close();
|
||||||
|
};
|
||||||
|
|
||||||
|
form.onsubmit = (e) => this.handleSubmit(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
open() {
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
if (!token) {
|
||||||
|
// Aquí puedes disparar tu modal de login o redirigir
|
||||||
|
alert('You must be logged in to create a room');
|
||||||
|
window.location.href = '/login'; // Opcional
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const modal = document.getElementById(this.modalId);
|
||||||
|
modal.classList.add('show');
|
||||||
|
document.querySelector('#cr-form input[name="name"]').focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
close() {
|
||||||
|
const modal = document.getElementById(this.modalId);
|
||||||
|
modal.classList.remove('show');
|
||||||
|
document.getElementById('cr-form').reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
async handleSubmit(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
const btn = e.target.querySelector('button[type="submit"]');
|
||||||
|
const originalText = btn.textContent;
|
||||||
|
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = 'Creating...';
|
||||||
|
|
||||||
|
const formData = new FormData(e.target);
|
||||||
|
const expose = formData.get('expose') === 'on';
|
||||||
|
const name = formData.get('name').trim();
|
||||||
|
const password = formData.get('password').trim();
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/rooms', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${token}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
name,
|
||||||
|
password: password || undefined,
|
||||||
|
expose
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) throw new Error(data.error || 'Failed to create room');
|
||||||
|
|
||||||
|
this.close();
|
||||||
|
|
||||||
|
window.location.href = `/room?id=${data.room.id}`
|
||||||
|
} catch (err) {
|
||||||
|
alert(err.message);
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = originalText;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.CreateRoomModal = CreateRoomModal;
|
||||||
2274
desktop/src/scripts/room.js
Normal file
213
desktop/src/scripts/settings.js
Normal file
@@ -0,0 +1,213 @@
|
|||||||
|
const API_BASE2 = '/api/config';
|
||||||
|
let currentConfig = {};
|
||||||
|
let currentSchema = {};
|
||||||
|
let activeSection = '';
|
||||||
|
let modal, navContainer, formContent, form;
|
||||||
|
|
||||||
|
window.toggleSettingsModal = async (forceClose = false) => {
|
||||||
|
modal = document.getElementById('settings-modal');
|
||||||
|
navContainer = document.getElementById('config-nav');
|
||||||
|
formContent = document.getElementById('config-section-content');
|
||||||
|
form = document.getElementById('config-form');
|
||||||
|
|
||||||
|
if (!modal) return;
|
||||||
|
|
||||||
|
if (forceClose) {
|
||||||
|
modal.classList.add('hidden');
|
||||||
|
} else {
|
||||||
|
const isHidden = modal.classList.contains('hidden');
|
||||||
|
if (isHidden) {
|
||||||
|
modal.classList.remove('hidden');
|
||||||
|
await loadSettings();
|
||||||
|
} else {
|
||||||
|
modal.classList.add('hidden');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
async function loadSettings() {
|
||||||
|
if (!formContent) return;
|
||||||
|
|
||||||
|
// Loading State
|
||||||
|
formContent.innerHTML = `
|
||||||
|
<div class="skeleton-loader">
|
||||||
|
<div class="skeleton title-skeleton"></div>
|
||||||
|
<div class="skeleton field-skeleton"></div>
|
||||||
|
<div class="skeleton field-skeleton"></div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(API_BASE2);
|
||||||
|
if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
|
||||||
|
// --- CORRECCIÓN AQUI ---
|
||||||
|
// Tu JSON devuelve "values", el código original buscaba "config"
|
||||||
|
currentConfig = data.values || data.config || data;
|
||||||
|
currentSchema = data.schema || {};
|
||||||
|
|
||||||
|
renderNav();
|
||||||
|
|
||||||
|
if (!activeSection || !currentConfig[activeSection]) {
|
||||||
|
activeSection = Object.keys(currentConfig)[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
switchSection(activeSection);
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error loading settings:', err);
|
||||||
|
formContent.innerHTML = `
|
||||||
|
<div style="padding: 2rem; text-align: center;">
|
||||||
|
<p style="color: #ef4444; margin-bottom: 1rem;">Failed to load settings</p>
|
||||||
|
<p style="color: #888; font-size: 0.9rem;">${err.message}</p>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function switchSection(section) {
|
||||||
|
if (!currentConfig[section]) return;
|
||||||
|
activeSection = section;
|
||||||
|
renderNav();
|
||||||
|
|
||||||
|
const sectionData = currentConfig[section];
|
||||||
|
const sectionSchema = currentSchema[section] || {};
|
||||||
|
|
||||||
|
formContent.innerHTML = `
|
||||||
|
<h2 class="section-title" style="margin-bottom: 2rem; text-transform: capitalize; font-size: 1.8rem;">
|
||||||
|
${section.replace(/_/g, ' ')}
|
||||||
|
</h2>
|
||||||
|
`;
|
||||||
|
|
||||||
|
Object.entries(sectionData).forEach(([key, value]) => {
|
||||||
|
const group = document.createElement('div');
|
||||||
|
group.className = 'config-group';
|
||||||
|
|
||||||
|
const isBool = typeof value === 'boolean';
|
||||||
|
const inputId = `input-${section}-${key}`;
|
||||||
|
const labelText = key.replace(/_/g, ' ');
|
||||||
|
|
||||||
|
// Obtener descripción
|
||||||
|
const description = sectionSchema[key]?.description || '';
|
||||||
|
const descHtml = description
|
||||||
|
? `<p class="config-description">${description}</p>`
|
||||||
|
: '';
|
||||||
|
|
||||||
|
if (isBool) {
|
||||||
|
group.innerHTML = `
|
||||||
|
<div style="display: flex; flex-direction: column; gap: 8px;">
|
||||||
|
<div style="display: flex; align-items: center; gap: 0.8rem;">
|
||||||
|
<input type="checkbox" id="${inputId}" name="${key}" ${value ? 'checked' : ''}
|
||||||
|
style="width: 20px; height: 20px; accent-color: var(--accent);">
|
||||||
|
<label for="${inputId}" style="margin: 0; cursor: pointer; font-size: 1rem;">${labelText}</label>
|
||||||
|
</div>
|
||||||
|
${descHtml} </div>
|
||||||
|
`;
|
||||||
|
} else {
|
||||||
|
// --- CAMBIO PRINCIPAL AQUI ---
|
||||||
|
// Movimos ${descHtml} para que esté DESPUÉS del input
|
||||||
|
group.innerHTML = `
|
||||||
|
<label for="${inputId}">${labelText}</label>
|
||||||
|
<input class="config-input" id="${inputId}" name="${key}"
|
||||||
|
type="${typeof value === 'number' ? 'number' : 'text'}"
|
||||||
|
value="${value || ''}"
|
||||||
|
placeholder="Not set">
|
||||||
|
${descHtml}
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
formContent.appendChild(group);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderNav() {
|
||||||
|
if (!navContainer) return;
|
||||||
|
navContainer.innerHTML = '';
|
||||||
|
|
||||||
|
Object.keys(currentConfig).forEach(section => {
|
||||||
|
const btn = document.createElement('div');
|
||||||
|
btn.className = `nav-item ${section === activeSection ? 'active' : ''}`;
|
||||||
|
|
||||||
|
// Icono opcional según la sección (puedes personalizar esto)
|
||||||
|
let icon = '';
|
||||||
|
if(section === 'library') icon = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"></path><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"></path></svg>';
|
||||||
|
if(section === 'paths') icon = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><folder></folder><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"></path></svg>';
|
||||||
|
|
||||||
|
btn.innerHTML = `${icon} ${section}`;
|
||||||
|
btn.onclick = () => switchSection(section);
|
||||||
|
navContainer.appendChild(btn);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handler de guardado
|
||||||
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
document.addEventListener('submit', async (e) => {
|
||||||
|
if (e.target.id === 'config-form') {
|
||||||
|
e.preventDefault();
|
||||||
|
await saveSettings();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
async function saveSettings() {
|
||||||
|
if (!form || !activeSection) return;
|
||||||
|
|
||||||
|
const updatedData = {};
|
||||||
|
const sectionConfig = currentConfig[activeSection];
|
||||||
|
|
||||||
|
Object.keys(sectionConfig).forEach(key => {
|
||||||
|
const input = form.elements[key];
|
||||||
|
if (!input) return;
|
||||||
|
|
||||||
|
if (input.type === 'checkbox') {
|
||||||
|
updatedData[key] = input.checked;
|
||||||
|
} else if (input.type === 'number') {
|
||||||
|
updatedData[key] = Number(input.value);
|
||||||
|
} else {
|
||||||
|
updatedData[key] = input.value;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_BASE2}/${activeSection}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(updatedData)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
currentConfig[activeSection] = updatedData; // Actualizamos localmente
|
||||||
|
showNotification('Settings saved successfully!');
|
||||||
|
} else {
|
||||||
|
throw new Error('Failed to save settings');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
showNotification('Error saving settings', true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function showNotification(msg, isError = false) {
|
||||||
|
const notification = document.createElement('div');
|
||||||
|
const bg = isError ? '#ef4444' : '#10b981';
|
||||||
|
|
||||||
|
notification.style.cssText = `
|
||||||
|
position: fixed; top: 20px; right: 20px;
|
||||||
|
background: ${bg}; color: white;
|
||||||
|
padding: 1rem 1.5rem; border-radius: 8px; font-weight: 600;
|
||||||
|
box-shadow: 0 10px 30px rgba(0,0,0,0.5); z-index: 20000;
|
||||||
|
animation: slideIn 0.3s ease-out; display: flex; align-items: center; gap: 10px;
|
||||||
|
`;
|
||||||
|
notification.innerHTML = isError
|
||||||
|
? `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg> ${msg}`
|
||||||
|
: `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"></polyline></svg> ${msg}`;
|
||||||
|
|
||||||
|
document.body.appendChild(notification);
|
||||||
|
setTimeout(() => {
|
||||||
|
notification.style.animation = 'slideOut 0.3s ease-out';
|
||||||
|
setTimeout(() => notification.remove(), 300);
|
||||||
|
}, 3000);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
const Gitea_OWNER = "ItsSkaiya";
|
const Gitea_OWNER = "ItsSkaiya";
|
||||||
const Gitea_REPO = "WaifuBoard";
|
const Gitea_REPO = "WaifuBoard";
|
||||||
const CURRENT_VERSION = "v2.0.0-rc.0";
|
const CURRENT_VERSION = "v2.0.0";
|
||||||
const UPDATE_CHECK_INTERVAL = 5 * 60 * 1000;
|
const UPDATE_CHECK_INTERVAL = 5 * 60 * 1000;
|
||||||
|
|
||||||
let currentVersionDisplay;
|
let currentVersionDisplay;
|
||||||
@@ -694,30 +694,102 @@ window.handleDeleteConfirmation = function(userId) {
|
|||||||
|
|
||||||
closeModal();
|
closeModal();
|
||||||
|
|
||||||
|
if (user.has_password) {
|
||||||
|
modalAniList.innerHTML = `
|
||||||
|
<div class="modal-overlay"></div>
|
||||||
|
<div class="modal-content" style="max-width:400px;">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h2>Confirm Deletion</h2>
|
||||||
|
<button class="modal-close" onclick="closeModal()">
|
||||||
|
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||||
|
<line x1="18" y1="6" x2="6" y2="18"></line>
|
||||||
|
<line x1="6" y1="6" x2="18" y2="18"></line>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form id="deleteWithPasswordForm">
|
||||||
|
<p style="margin-bottom:1.25rem; color:var(--color-text-secondary)">
|
||||||
|
Enter your password to permanently delete
|
||||||
|
<b>${user.username}</b>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="deletePassword">Password</label>
|
||||||
|
<div class="password-toggle-wrapper">
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
id="deletePassword"
|
||||||
|
required
|
||||||
|
placeholder="Enter password"
|
||||||
|
autofocus
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="password-toggle-btn"
|
||||||
|
onclick="togglePasswordVisibility('deletePassword', this)"
|
||||||
|
>
|
||||||
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||||
|
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
|
||||||
|
<circle cx="12" cy="12" r="3"></circle>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button type="button" class="btn-secondary" onclick="closeModal()">
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button type="submit" class="btn-disconnect">
|
||||||
|
Delete Profile
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
modalAniList.classList.add('active');
|
||||||
|
|
||||||
|
document
|
||||||
|
.getElementById('deleteWithPasswordForm')
|
||||||
|
.addEventListener('submit', e => {
|
||||||
|
e.preventDefault();
|
||||||
|
const password = document.getElementById('deletePassword').value;
|
||||||
|
handleConfirmedDeleteUser(userId, password);
|
||||||
|
});
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
showConfirmationModal(
|
showConfirmationModal(
|
||||||
'Confirm Deletion',
|
'Confirm Deletion',
|
||||||
`Are you absolutely sure you want to delete profile ${user.username}? This action cannot be undone.`,
|
`Are you absolutely sure you want to delete profile ${user.username}?`,
|
||||||
`handleConfirmedDeleteUser(${userId})`
|
`handleConfirmedDeleteUser(${userId})`
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
window.handleConfirmedDeleteUser = async function(userId) {
|
window.handleConfirmedDeleteUser = async function(userId, password = null) {
|
||||||
closeModal();
|
closeModal();
|
||||||
showUserToast('Deleting user...', 'info');
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${API_BASE}/users/${userId}`, { method: 'DELETE' });
|
const options = { method: 'DELETE' };
|
||||||
|
|
||||||
|
if (password) {
|
||||||
|
options.headers = { 'Content-Type': 'application/json' };
|
||||||
|
options.body = JSON.stringify({ password });
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(`${API_BASE}/users/${userId}`, options);
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const error = await res.json();
|
const error = await res.json();
|
||||||
throw new Error(error.error || 'Error deleting user');
|
throw new Error(error.error);
|
||||||
}
|
}
|
||||||
|
|
||||||
await loadUsers();
|
await loadUsers();
|
||||||
showUserToast('User deleted successfully!', 'success');
|
showUserToast('User deleted successfully!', 'success');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
showUserToast(err.message || 'Error deleting user', 'error');
|
||||||
showUserToast('Error deleting user', 'error');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -766,8 +838,7 @@ function openAniListModal(userId) {
|
|||||||
modalUserActions.classList.remove('active');
|
modalUserActions.classList.remove('active');
|
||||||
modalEditUser.classList.remove('active');
|
modalEditUser.classList.remove('active');
|
||||||
|
|
||||||
aniListContent.innerHTML = `<div style="text-align: center; padding: 2rem;">Loading integration status...</div>`;
|
// Estado de carga inicial
|
||||||
|
|
||||||
modalAniList.innerHTML = `
|
modalAniList.innerHTML = `
|
||||||
<div class="modal-overlay"></div>
|
<div class="modal-overlay"></div>
|
||||||
<div class="modal-content">
|
<div class="modal-content">
|
||||||
@@ -788,12 +859,15 @@ function openAniListModal(userId) {
|
|||||||
|
|
||||||
modalAniList.classList.add('active');
|
modalAniList.classList.add('active');
|
||||||
|
|
||||||
|
// Verificar si ya está conectado
|
||||||
getIntegrationStatus(userId).then(integration => {
|
getIntegrationStatus(userId).then(integration => {
|
||||||
const content = document.getElementById('aniListContent');
|
const content = document.getElementById('aniListContent');
|
||||||
|
const clientId = 32898; // Tu Client ID de AniList
|
||||||
|
|
||||||
content.innerHTML = `
|
if (integration.connected) {
|
||||||
<div class="anilist-status">
|
// VISTA: YA CONECTADO
|
||||||
${integration.connected ? `
|
content.innerHTML = `
|
||||||
|
<div class="anilist-status">
|
||||||
<div class="anilist-connected">
|
<div class="anilist-connected">
|
||||||
<div class="anilist-icon">
|
<div class="anilist-icon">
|
||||||
<img src="https://anilist.co/img/icons/icon.svg" alt="AniList" style="width:40px; height:40px;">
|
<img src="https://anilist.co/img/icons/icon.svg" alt="AniList" style="width:40px; height:40px;">
|
||||||
@@ -807,24 +881,43 @@ function openAniListModal(userId) {
|
|||||||
<button class="btn-disconnect" onclick="handleDisconnectAniList()">
|
<button class="btn-disconnect" onclick="handleDisconnectAniList()">
|
||||||
Disconnect AniList
|
Disconnect AniList
|
||||||
</button>
|
</button>
|
||||||
` : `
|
</div>
|
||||||
<div style="text-align: center; padding: 1rem;">
|
`;
|
||||||
<h3 style="margin-bottom: 0.5rem;">Connect with AniList</h3>
|
} else {
|
||||||
<p style="color: var(--color-text-secondary); margin-bottom: 1.5rem;">
|
// VISTA: NO CONECTADO (Formulario Manual)
|
||||||
Sync your anime list by logging in with AniList.
|
content.innerHTML = `
|
||||||
</p>
|
<div class="anilist-status">
|
||||||
<div style="display:flex; justify-content:center;">
|
<div style="text-align: left; padding: 0.5rem;">
|
||||||
<button class="btn-connect" onclick="redirectToAniListLogin()">
|
<h3 style="margin-bottom: 1rem; font-size: 1.1rem;">How to connect:</h3>
|
||||||
Login with AniList
|
|
||||||
</button>
|
<div style="margin-bottom: 1.5rem;">
|
||||||
|
<p style="color: var(--color-text-secondary); margin-bottom: 0.5rem; font-size: 0.9rem;">
|
||||||
|
1. Open the authorization page in a new tab:
|
||||||
|
</p>
|
||||||
|
<a href="https://anilist.co/api/v2/oauth/authorize?client_id=${clientId}&response_type=token"
|
||||||
|
target="_blank"
|
||||||
|
class="btn-secondary"
|
||||||
|
style="display: inline-block; text-decoration: none; text-align: center; width: 100%; padding: 0.8rem;">
|
||||||
|
Open AniList Login ↗
|
||||||
|
</a>
|
||||||
</div>
|
</div>
|
||||||
<p style="font-size:0.85rem; margin-top:1rem; color:var(--color-text-secondary)">
|
|
||||||
You will be redirected and then returned here.
|
<div style="margin-bottom: 1.5rem;">
|
||||||
</p>
|
<p style="color: var(--color-text-secondary); margin-bottom: 0.5rem; font-size: 0.9rem;">
|
||||||
|
2. Authorize the app, then copy the <b>Access Token</b> provided and paste it here:
|
||||||
|
</p>
|
||||||
|
<div class="form-group">
|
||||||
|
<input type="text" id="manualAniListToken" placeholder="Paste your Access Token here..." autocomplete="off">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button class="btn-connect" onclick="handleManualAniListToken()">
|
||||||
|
Verify & Save Token
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
`}
|
</div>
|
||||||
</div>
|
`;
|
||||||
`;
|
}
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
const content = document.getElementById('aniListContent');
|
const content = document.getElementById('aniListContent');
|
||||||
@@ -832,6 +925,49 @@ function openAniListModal(userId) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Nueva función para manejar el token pegado manualmente
|
||||||
|
async function handleManualAniListToken() {
|
||||||
|
const tokenInput = document.getElementById('manualAniListToken');
|
||||||
|
const token = tokenInput.value.trim();
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
showUserToast('Please paste the AniList token first', 'error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const submitBtn = document.querySelector('.btn-connect');
|
||||||
|
const originalText = submitBtn.textContent;
|
||||||
|
submitBtn.disabled = true;
|
||||||
|
submitBtn.textContent = 'Verifying...';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_BASE}/anilist/store`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
userId: currentUserId,
|
||||||
|
accessToken: token,
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(data.error || 'Failed to verify token');
|
||||||
|
}
|
||||||
|
|
||||||
|
showUserToast('AniList connected successfully!', 'success');
|
||||||
|
// Recargar el modal para mostrar el estado "Conectado"
|
||||||
|
openAniListModal(currentUserId);
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
showUserToast(err.message || 'Invalid Token', 'error');
|
||||||
|
submitBtn.disabled = false;
|
||||||
|
submitBtn.textContent = originalText;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function redirectToAniListLogin() {
|
async function redirectToAniListLogin() {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/login`, {
|
const res = await fetch(`/api/login`, {
|
||||||
@@ -846,15 +982,10 @@ async function redirectToAniListLogin() {
|
|||||||
localStorage.setItem('token', data.token);
|
localStorage.setItem('token', data.token);
|
||||||
|
|
||||||
const clientId = 32898;
|
const clientId = 32898;
|
||||||
const redirectUri = encodeURIComponent(window.location.origin + '/api/anilist');
|
window.open(
|
||||||
const state = encodeURIComponent(currentUserId);
|
`https://anilist.co/api/v2/oauth/authorize?client_id=${clientId}&response_type=token`,
|
||||||
|
'_blank'
|
||||||
window.location.href =
|
);
|
||||||
`https://anilist.co/api/v2/oauth/authorize` +
|
|
||||||
`?client_id=${clientId}` +
|
|
||||||
`&response_type=code` +
|
|
||||||
`&redirect_uri=${redirectUri}` +
|
|
||||||
`&state=${state}`;
|
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
@@ -966,7 +1097,7 @@ async function performLogin(userId, password = null) {
|
|||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
localStorage.setItem('token', data.token);
|
localStorage.setItem('token', data.token);
|
||||||
|
|
||||||
window.location.href = '/anime';
|
window.location.href = '/profile';
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Login error', err);
|
console.error('Login error', err);
|
||||||
showUserToast(err.message || 'Login failed', 'error');
|
showUserToast(err.message || 'Login failed', 'error');
|
||||||
@@ -52,10 +52,9 @@ const ContinueWatchingManager = {
|
|||||||
|
|
||||||
if (entryType === 'ANIME') {
|
if (entryType === 'ANIME') {
|
||||||
url = item.source === 'anilist'
|
url = item.source === 'anilist'
|
||||||
? `/watch/${item.entry_id}/${nextProgress}`
|
? `/anime/${item.entry_id}?episode=${nextProgress}`
|
||||||
: `/watch/${item.entry_id}/${nextProgress}?${item.source}`;
|
: `/anime/${item.entry_id}/${item.source}/?episode=${nextProgress}`;
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
url = item.source === 'anilist'
|
url = item.source === 'anilist'
|
||||||
? `/book/${item.entry_id}?chapter=${nextProgress}`
|
? `/book/${item.entry_id}?chapter=${nextProgress}`
|
||||||
: `/read/${item.source}/${nextProgress}/${item.entry_id}?source=${item.source}`;
|
: `/read/${item.source}/${nextProgress}/${item.entry_id}?source=${item.source}`;
|
||||||
@@ -83,7 +83,7 @@ const ListModalManager = {
|
|||||||
document.getElementById('progress-label');
|
document.getElementById('progress-label');
|
||||||
|
|
||||||
if (this.isInList && this.currentEntry) {
|
if (this.isInList && this.currentEntry) {
|
||||||
document.getElementById('entry-status').value = this.currentEntry.status || 'PLANNING';
|
document.getElementById('entry-status').value = this.normalizeStatus(this.currentEntry.status);
|
||||||
document.getElementById('entry-progress').value = this.currentEntry.progress || 0;
|
document.getElementById('entry-progress').value = this.currentEntry.progress || 0;
|
||||||
document.getElementById('entry-score').value = this.currentEntry.score || '';
|
document.getElementById('entry-score').value = this.currentEntry.score || '';
|
||||||
document.getElementById('entry-start-date').value = this.currentEntry.start_date?.split('T')[0] || '';
|
document.getElementById('entry-start-date').value = this.currentEntry.start_date?.split('T')[0] || '';
|
||||||
@@ -131,6 +131,12 @@ const ListModalManager = {
|
|||||||
document.getElementById('add-list-modal').classList.add('active');
|
document.getElementById('add-list-modal').classList.add('active');
|
||||||
},
|
},
|
||||||
|
|
||||||
|
normalizeStatus(status) {
|
||||||
|
if (!status) return 'PLANNING';
|
||||||
|
if (status === 'WATCHING' || status === 'READING') return 'CURRENT';
|
||||||
|
return status;
|
||||||
|
},
|
||||||
|
|
||||||
close() {
|
close() {
|
||||||
document.getElementById('add-list-modal').classList.remove('active');
|
document.getElementById('add-list-modal').classList.remove('active');
|
||||||
},
|
},
|
||||||
@@ -212,15 +218,21 @@ const ListModalManager = {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
async function loadListModal() {
|
||||||
|
if (document.getElementById('add-list-modal')) return;
|
||||||
|
|
||||||
|
const res = await fetch('/views/components/list-modal.html');
|
||||||
|
const html = await res.text();
|
||||||
|
document.body.insertAdjacentHTML('beforeend', html);
|
||||||
|
|
||||||
const modal = document.getElementById('add-list-modal');
|
const modal = document.getElementById('add-list-modal');
|
||||||
if (modal) {
|
modal.addEventListener('click', (e) => {
|
||||||
modal.addEventListener('click', (e) => {
|
if (e.target.id === 'add-list-modal') {
|
||||||
if (e.target.id === 'add-list-modal') {
|
ListModalManager.close();
|
||||||
ListModalManager.close();
|
}
|
||||||
}
|
});
|
||||||
});
|
}
|
||||||
}
|
|
||||||
});
|
document.addEventListener('DOMContentLoaded', loadListModal);
|
||||||
|
|
||||||
window.ListModalManager = ListModalManager;
|
window.ListModalManager = ListModalManager;
|
||||||
171
desktop/src/scripts/utils/match-modal.js
Normal file
@@ -0,0 +1,171 @@
|
|||||||
|
const MatchModal = (function() {
|
||||||
|
let _config = {
|
||||||
|
onSearch: async (query, provider) => [], // Debe devolver Array de objetos
|
||||||
|
onSelect: (item, provider) => {},
|
||||||
|
provider: 'generic'
|
||||||
|
};
|
||||||
|
|
||||||
|
let elements = {};
|
||||||
|
let searchTimeout = null;
|
||||||
|
|
||||||
|
function init() {
|
||||||
|
if (document.getElementById('waifu-match-modal')) return;
|
||||||
|
|
||||||
|
// Inyectar HTML
|
||||||
|
const modalHTML = `
|
||||||
|
<div class="match-modal-overlay" id="waifu-match-modal">
|
||||||
|
<div class="match-modal-content">
|
||||||
|
<div class="match-header">
|
||||||
|
<h3 class="match-title">Manual Match <span id="match-provider-badge" style="opacity:0.6; font-size:0.8em; margin-left:8px;"></span></h3>
|
||||||
|
<button class="match-close-btn" id="match-close-btn">✕</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="match-search-container">
|
||||||
|
<input type="text" id="match-input" class="match-input" placeholder="Search title..." autocomplete="off">
|
||||||
|
<button id="match-btn-action" class="match-search-btn">Search</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="match-results-body" id="match-results-container">
|
||||||
|
<div class="match-msg">Type to start searching...</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
document.body.insertAdjacentHTML('beforeend', modalHTML);
|
||||||
|
|
||||||
|
// Cachear elementos
|
||||||
|
elements = {
|
||||||
|
overlay: document.getElementById('waifu-match-modal'),
|
||||||
|
input: document.getElementById('match-input'),
|
||||||
|
results: document.getElementById('match-results-container'),
|
||||||
|
badge: document.getElementById('match-provider-badge'),
|
||||||
|
closeBtn: document.getElementById('match-close-btn'),
|
||||||
|
searchBtn: document.getElementById('match-btn-action')
|
||||||
|
};
|
||||||
|
|
||||||
|
// Event Listeners
|
||||||
|
elements.closeBtn.onclick = close;
|
||||||
|
elements.overlay.onclick = (e) => { if(e.target === elements.overlay) close(); };
|
||||||
|
|
||||||
|
// Búsqueda al hacer clic
|
||||||
|
elements.searchBtn.onclick = () => performSearch(elements.input.value);
|
||||||
|
|
||||||
|
// Búsqueda al escribir (Debounce)
|
||||||
|
elements.input.addEventListener('input', (e) => {
|
||||||
|
clearTimeout(searchTimeout);
|
||||||
|
if(e.target.value.trim().length === 0) return;
|
||||||
|
searchTimeout = setTimeout(() => performSearch(e.target.value), 600);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Enter key
|
||||||
|
elements.input.addEventListener('keypress', (e) => {
|
||||||
|
if (e.key === 'Enter') performSearch(elements.input.value);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function open(options) {
|
||||||
|
init(); // Asegurar que el DOM existe
|
||||||
|
|
||||||
|
_config = { ..._config, ...options };
|
||||||
|
|
||||||
|
// Resetear UI
|
||||||
|
elements.input.value = options.initialQuery || '';
|
||||||
|
elements.results.innerHTML = '<div class="match-msg">Search above to find matches...</div>';
|
||||||
|
elements.badge.innerText = options.provider ? `(${options.provider})` : '';
|
||||||
|
|
||||||
|
// Mostrar Modal
|
||||||
|
elements.overlay.classList.add('active');
|
||||||
|
|
||||||
|
// Auto-search si hay query inicial
|
||||||
|
if (options.initialQuery) {
|
||||||
|
performSearch(options.initialQuery);
|
||||||
|
}
|
||||||
|
|
||||||
|
setTimeout(() => elements.input.focus(), 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
function close() {
|
||||||
|
if(elements.overlay) elements.overlay.classList.remove('active');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function performSearch(query) {
|
||||||
|
if (!query || query.trim().length < 2) return;
|
||||||
|
|
||||||
|
elements.results.innerHTML = '<div class="match-spinner"></div>';
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Ejecutar la función de búsqueda pasada en la config
|
||||||
|
const results = await _config.onSearch(query, _config.provider);
|
||||||
|
renderResults(results);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
elements.results.innerHTML = '<div class="match-msg error">Error searching provider.</div>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderResults(results) {
|
||||||
|
elements.results.innerHTML = '';
|
||||||
|
|
||||||
|
if (!results || results.length === 0) {
|
||||||
|
elements.results.innerHTML = '<div class="match-msg">No matches found.</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const grid = document.createElement('div');
|
||||||
|
grid.className = 'match-list-grid';
|
||||||
|
|
||||||
|
results.forEach(item => {
|
||||||
|
const el = document.createElement('div');
|
||||||
|
el.className = 'match-item';
|
||||||
|
|
||||||
|
// Normalización de datos para asegurar compatibilidad con Anime/Libros
|
||||||
|
const img = item.coverImage?.large || item.coverImage || item.image || '/public/assets/no-image.png';
|
||||||
|
const title = item.title?.english || item.title?.romaji || item.title || 'Unknown Title';
|
||||||
|
const meta = item.releaseDate || item.year || item.startDate?.year || '';
|
||||||
|
const url = item.url || item.externalUrl || null;
|
||||||
|
|
||||||
|
el.innerHTML = `
|
||||||
|
<img src="${img}" class="match-poster" loading="lazy">
|
||||||
|
<div class="match-info">
|
||||||
|
<div class="match-item-title">${title}</div>
|
||||||
|
<div class="match-item-meta">${meta}</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
// Botón de enlace externo (si existe URL)
|
||||||
|
if (url) {
|
||||||
|
const linkBtn = document.createElement('a');
|
||||||
|
linkBtn.href = url;
|
||||||
|
linkBtn.target = "_blank";
|
||||||
|
linkBtn.className = "match-link-btn";
|
||||||
|
linkBtn.title = "View Source";
|
||||||
|
linkBtn.innerHTML = `
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
|
||||||
|
<polyline points="15 3 21 3 21 9"></polyline>
|
||||||
|
<line x1="10" y1="14" x2="21" y2="3"></line>
|
||||||
|
</svg>
|
||||||
|
`;
|
||||||
|
// Evitar que el click en el enlace dispare el select
|
||||||
|
linkBtn.onclick = (e) => e.stopPropagation();
|
||||||
|
el.appendChild(linkBtn);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Click en la tarjeta selecciona
|
||||||
|
el.onclick = () => {
|
||||||
|
_config.onSelect(item);
|
||||||
|
close();
|
||||||
|
};
|
||||||
|
|
||||||
|
grid.appendChild(el);
|
||||||
|
});
|
||||||
|
|
||||||
|
elements.results.appendChild(grid);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
open,
|
||||||
|
close
|
||||||
|
};
|
||||||
|
})();
|
||||||
131
desktop/src/shared/config.js
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import os from 'os';
|
||||||
|
import yaml from 'js-yaml';
|
||||||
|
import crypto from 'crypto';
|
||||||
|
|
||||||
|
const BASE_DIR = path.join(os.homedir(), 'WaifuBoards');
|
||||||
|
const CONFIG_PATH = path.join(BASE_DIR, 'config.yaml');
|
||||||
|
|
||||||
|
const DEFAULT_CONFIG = {
|
||||||
|
library: {
|
||||||
|
anime: null,
|
||||||
|
manga: null,
|
||||||
|
novels: null
|
||||||
|
},
|
||||||
|
paths: {
|
||||||
|
mpv: null,
|
||||||
|
ffmpeg: null,
|
||||||
|
ffprobe: null,
|
||||||
|
cloudflared: null,
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
jwt_secret: null
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const CONFIG_SCHEMA = {
|
||||||
|
library: {
|
||||||
|
anime: { description: "Path where anime is stored" },
|
||||||
|
manga: { description: "Path where manga is stored" },
|
||||||
|
novels: { description: "Path where novels are stored" }
|
||||||
|
},
|
||||||
|
paths: {
|
||||||
|
mpv: { description: "Required to open anime episodes in mpv on desktop version." },
|
||||||
|
ffmpeg: { description: "Required for downloading anime episodes." },
|
||||||
|
ffprobe: { description: "Required for watching local anime episodes." },
|
||||||
|
cloudflared: { description: "Required for creating pubic rooms." }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
function ensureConfigFile() {
|
||||||
|
if (!fs.existsSync(BASE_DIR)) {
|
||||||
|
fs.mkdirSync(BASE_DIR, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
let configExists = fs.existsSync(CONFIG_PATH);
|
||||||
|
|
||||||
|
if (!configExists) {
|
||||||
|
fs.writeFileSync(
|
||||||
|
CONFIG_PATH,
|
||||||
|
yaml.dump(DEFAULT_CONFIG),
|
||||||
|
'utf8'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
|
||||||
|
const loaded = yaml.load(raw) || {};
|
||||||
|
|
||||||
|
if (!loaded.server) loaded.server = {};
|
||||||
|
if (!loaded.server.jwt_secret) {
|
||||||
|
loaded.server.jwt_secret = crypto.randomBytes(32).toString('hex');
|
||||||
|
fs.writeFileSync(CONFIG_PATH, yaml.dump(deepMerge(structuredClone(DEFAULT_CONFIG), loaded)), 'utf8');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPublicConfig() {
|
||||||
|
const { values } = getConfig();
|
||||||
|
const publicConfig = structuredClone(values);
|
||||||
|
if (publicConfig.server) delete publicConfig.server.jwt_secret;
|
||||||
|
return publicConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getConfig() {
|
||||||
|
ensureConfigFile();
|
||||||
|
const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
|
||||||
|
const loaded = yaml.load(raw) || {};
|
||||||
|
|
||||||
|
return {
|
||||||
|
values: deepMerge(structuredClone(DEFAULT_CONFIG), loaded),
|
||||||
|
schema: CONFIG_SCHEMA
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeLoadedConfig(loaded) {
|
||||||
|
return {
|
||||||
|
library: loaded.library,
|
||||||
|
paths: loaded.paths
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setConfig(partialConfig) {
|
||||||
|
ensureConfigFile();
|
||||||
|
|
||||||
|
const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
|
||||||
|
const loadedRaw = yaml.load(raw) || {};
|
||||||
|
const loaded = sanitizeLoadedConfig(loadedRaw);
|
||||||
|
|
||||||
|
const next = deepMerge(
|
||||||
|
structuredClone(DEFAULT_CONFIG),
|
||||||
|
deepMerge(loaded, partialConfig)
|
||||||
|
);
|
||||||
|
|
||||||
|
const toSave = {
|
||||||
|
library: next.library,
|
||||||
|
paths: next.paths
|
||||||
|
};
|
||||||
|
|
||||||
|
fs.writeFileSync(CONFIG_PATH, yaml.dump(toSave), 'utf8');
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
function deepMerge(target, source) {
|
||||||
|
for (const key in source) {
|
||||||
|
if (
|
||||||
|
source[key] &&
|
||||||
|
typeof source[key] === 'object' &&
|
||||||
|
!Array.isArray(source[key])
|
||||||
|
) {
|
||||||
|
target[key] = deepMerge(target[key] || {}, source[key]);
|
||||||
|
} else {
|
||||||
|
target[key] = source[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
ensureConfigFile,
|
||||||
|
getConfig,
|
||||||
|
setConfig,
|
||||||
|
};
|
||||||
@@ -2,7 +2,7 @@ const sqlite3 = require('sqlite3').verbose();
|
|||||||
const os = require("os");
|
const os = require("os");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const {ensureUserDataDB, ensureAnilistSchema, ensureExtensionsTable, ensureCacheTable, ensureFavoritesDB} = require('./schemas');
|
const {ensureUserDataDB, ensureAnilistSchema, ensureExtensionsTable, ensureCacheTable, ensureFavoritesDB, ensureLocalLibrarySchema } = require('./schemas');
|
||||||
|
|
||||||
const databases = new Map();
|
const databases = new Map();
|
||||||
|
|
||||||
@@ -10,7 +10,8 @@ const DEFAULT_PATHS = {
|
|||||||
anilist: path.join(os.homedir(), "WaifuBoards", 'anilist_anime.db'),
|
anilist: path.join(os.homedir(), "WaifuBoards", 'anilist_anime.db'),
|
||||||
favorites: path.join(os.homedir(), "WaifuBoards", "favorites.db"),
|
favorites: path.join(os.homedir(), "WaifuBoards", "favorites.db"),
|
||||||
cache: path.join(os.homedir(), "WaifuBoards", "cache.db"),
|
cache: path.join(os.homedir(), "WaifuBoards", "cache.db"),
|
||||||
userdata: path.join(os.homedir(), "WaifuBoards", "user_data.db")
|
userdata: path.join(os.homedir(), "WaifuBoards", "user_data.db"),
|
||||||
|
local_library: path.join(os.homedir(), "WaifuBoards", "local_library.db")
|
||||||
};
|
};
|
||||||
|
|
||||||
function initDatabase(name = 'anilist', dbPath = null, readOnly = false) {
|
function initDatabase(name = 'anilist', dbPath = null, readOnly = false) {
|
||||||
@@ -49,6 +50,11 @@ function initDatabase(name = 'anilist', dbPath = null, readOnly = false) {
|
|||||||
|
|
||||||
databases.set(name, db);
|
databases.set(name, db);
|
||||||
|
|
||||||
|
if (name === "local_library") {
|
||||||
|
ensureLocalLibrarySchema(db)
|
||||||
|
.catch(err => console.error("Error creating local library schema:", err));
|
||||||
|
}
|
||||||
|
|
||||||
if (name === "anilist") {
|
if (name === "anilist") {
|
||||||
ensureAnilistSchema(db)
|
ensureAnilistSchema(db)
|
||||||
.then(() => ensureExtensionsTable(db))
|
.then(() => ensureExtensionsTable(db))
|
||||||
@@ -46,7 +46,6 @@ async function loadExtensions() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async function loadExtension(fileName) {
|
async function loadExtension(fileName) {
|
||||||
const homeDir = os.homedir();
|
const homeDir = os.homedir();
|
||||||
const extensionsDir = path.join(homeDir, 'WaifuBoards', 'extensions');
|
const extensionsDir = path.join(homeDir, 'WaifuBoards', 'extensions');
|
||||||
@@ -77,6 +76,7 @@ async function loadExtension(fileName) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const name = instance.constructor.name;
|
const name = instance.constructor.name;
|
||||||
|
instance.__fileName = fileName;
|
||||||
instance.scrape = scrape;
|
instance.scrape = scrape;
|
||||||
instance.cheerio = cheerio;
|
instance.cheerio = cheerio;
|
||||||
extensions.set(name, instance);
|
extensions.set(name, instance);
|
||||||
@@ -114,6 +114,14 @@ async function saveExtensionFile(fileName, downloadUrl) {
|
|||||||
file.on('finish', async () => {
|
file.on('finish', async () => {
|
||||||
file.close(async () => {
|
file.close(async () => {
|
||||||
try {
|
try {
|
||||||
|
const extName = fileName.replace('.js', '');
|
||||||
|
|
||||||
|
for (const key of extensions.keys()) {
|
||||||
|
if (key.toLowerCase() === extName.toLowerCase()) {
|
||||||
|
extensions.delete(key);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
await loadExtension(fileName);
|
await loadExtension(fileName);
|
||||||
resolve();
|
resolve();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -186,6 +194,26 @@ function getBookExtensionsMap() {
|
|||||||
return bookExts;
|
return bookExts;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getMangaExtensionsMap() {
|
||||||
|
const mangaExts = new Map();
|
||||||
|
for (const [name, ext] of extensions) {
|
||||||
|
if (ext.type === 'book-board' && ext.mediaType !== 'ln') {
|
||||||
|
mangaExts.set(name, ext);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return mangaExts;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getNovelExtensionsMap() {
|
||||||
|
const novelExts = new Map();
|
||||||
|
for (const [name, ext] of extensions) {
|
||||||
|
if (ext.type === 'book-board' && ext.mediaType === 'ln') {
|
||||||
|
novelExts.set(name, ext);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return novelExts;
|
||||||
|
}
|
||||||
|
|
||||||
function getGalleryExtensionsMap() {
|
function getGalleryExtensionsMap() {
|
||||||
const galleryExts = new Map();
|
const galleryExts = new Map();
|
||||||
for (const [name, ext] of extensions) {
|
for (const [name, ext] of extensions) {
|
||||||
@@ -205,5 +233,7 @@ module.exports = {
|
|||||||
getBookExtensionsMap,
|
getBookExtensionsMap,
|
||||||
getGalleryExtensionsMap,
|
getGalleryExtensionsMap,
|
||||||
saveExtensionFile,
|
saveExtensionFile,
|
||||||
deleteExtensionFile
|
deleteExtensionFile,
|
||||||
|
getMangaExtensionsMap,
|
||||||
|
getNovelExtensionsMap
|
||||||
};
|
};
|
||||||
147
desktop/src/shared/headless.js
Normal file
@@ -0,0 +1,147 @@
|
|||||||
|
const path = require("path");
|
||||||
|
const fs = require("fs");
|
||||||
|
const { chromium } = require("playwright-core");
|
||||||
|
|
||||||
|
let browser;
|
||||||
|
let context;
|
||||||
|
const BLOCK_LIST = [
|
||||||
|
"google-analytics", "doubleclick", "facebook", "twitter",
|
||||||
|
"adsystem", "analytics", "tracker", "pixel", "quantserve", "newrelic"
|
||||||
|
];
|
||||||
|
|
||||||
|
function isPackaged() {
|
||||||
|
return process.env.IS_PACKAGED === "true";
|
||||||
|
}
|
||||||
|
|
||||||
|
function getChromiumPath() {
|
||||||
|
if (isPackaged()) {
|
||||||
|
return path.join(
|
||||||
|
process.resourcesPath,
|
||||||
|
"playwright",
|
||||||
|
"chromium",
|
||||||
|
"chrome-headless-shell-win64",
|
||||||
|
"chrome-headless-shell.exe"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return chromium.executablePath();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function initHeadless() {
|
||||||
|
if (browser) return;
|
||||||
|
|
||||||
|
const exePath = getChromiumPath();
|
||||||
|
|
||||||
|
if (!fs.existsSync(exePath)) {
|
||||||
|
throw new Error("Chromium not found: " + exePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
browser = await chromium.launch({
|
||||||
|
headless: true,
|
||||||
|
executablePath: exePath,
|
||||||
|
args: [
|
||||||
|
"--no-sandbox",
|
||||||
|
"--disable-setuid-sandbox",
|
||||||
|
"--disable-dev-shm-usage",
|
||||||
|
"--disable-gpu",
|
||||||
|
"--disable-extensions",
|
||||||
|
"--disable-background-networking",
|
||||||
|
"--disable-sync",
|
||||||
|
"--disable-translate",
|
||||||
|
"--mute-audio",
|
||||||
|
"--no-first-run",
|
||||||
|
"--no-zygote",
|
||||||
|
]
|
||||||
|
});
|
||||||
|
context = await browser.newContext({
|
||||||
|
userAgent:
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/122.0.0.0 Safari/537.36"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function turboScroll(page) {
|
||||||
|
await page.evaluate(() => {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
let last = 0;
|
||||||
|
let same = 0;
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
const h = document.body.scrollHeight;
|
||||||
|
window.scrollTo(0, h);
|
||||||
|
if (h === last) {
|
||||||
|
same++;
|
||||||
|
if (same >= 5) {
|
||||||
|
clearInterval(timer);
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
same = 0;
|
||||||
|
last = h;
|
||||||
|
}
|
||||||
|
}, 20);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function scrape(url, handler, options = {}) {
|
||||||
|
const {
|
||||||
|
waitUntil = "domcontentloaded",
|
||||||
|
waitSelector = null,
|
||||||
|
timeout = 10000,
|
||||||
|
scrollToBottom = false,
|
||||||
|
renderWaitTime = 0,
|
||||||
|
loadImages = true
|
||||||
|
} = options;
|
||||||
|
if (!browser) await initHeadless();
|
||||||
|
const page = await context.newPage();
|
||||||
|
let collectedRequests = [];
|
||||||
|
await page.route("**/*", (route) => {
|
||||||
|
const req = route.request();
|
||||||
|
const rUrl = req.url().toLowerCase();
|
||||||
|
const type = req.resourceType();
|
||||||
|
|
||||||
|
collectedRequests.push({
|
||||||
|
url: req.url(),
|
||||||
|
method: req.method(),
|
||||||
|
resourceType: type
|
||||||
|
});
|
||||||
|
|
||||||
|
if (type === "font" || type === "media" || type === "manifest")
|
||||||
|
return route.abort();
|
||||||
|
|
||||||
|
if (BLOCK_LIST.some(k => rUrl.includes(k)))
|
||||||
|
return route.abort();
|
||||||
|
|
||||||
|
if (!loadImages && (
|
||||||
|
type === "image" || rUrl.match(/\.(jpg|jpeg|png|gif|webp|svg)$/)
|
||||||
|
)) return route.abort();
|
||||||
|
route.continue();
|
||||||
|
});
|
||||||
|
await page.goto(url, { waitUntil, timeout });
|
||||||
|
if (waitSelector) {
|
||||||
|
try {
|
||||||
|
await page.waitForSelector(waitSelector, { timeout });
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
if (scrollToBottom) {
|
||||||
|
await turboScroll(page);
|
||||||
|
}
|
||||||
|
if (renderWaitTime > 0) {
|
||||||
|
await new Promise(r => setTimeout(r, renderWaitTime));
|
||||||
|
}
|
||||||
|
const result = await handler(page);
|
||||||
|
await page.close();
|
||||||
|
|
||||||
|
return { result, requests: collectedRequests };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function closeScraper() {
|
||||||
|
if (context) await context.close();
|
||||||
|
if (browser) await browser.close();
|
||||||
|
context = null;
|
||||||
|
browser = null;
|
||||||
|
}
|
||||||
|
module.exports = {
|
||||||
|
initHeadless,
|
||||||
|
scrape,
|
||||||
|
closeScraper
|
||||||
|
};
|
||||||
@@ -2,6 +2,54 @@ const sqlite3 = require('sqlite3').verbose();
|
|||||||
const path = require("path");
|
const path = require("path");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
|
|
||||||
|
async function ensureLocalLibrarySchema(db) {
|
||||||
|
await run(db, `
|
||||||
|
CREATE TABLE IF NOT EXISTS local_entries (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
type TEXT NOT NULL,
|
||||||
|
path TEXT NOT NULL,
|
||||||
|
folder_name TEXT NOT NULL,
|
||||||
|
matched_id INTEGER,
|
||||||
|
matched_source TEXT,
|
||||||
|
last_scan INTEGER NOT NULL
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await run(db, `
|
||||||
|
CREATE TABLE IF NOT EXISTS local_files (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
entry_id TEXT NOT NULL,
|
||||||
|
file_path TEXT NOT NULL,
|
||||||
|
unit_number INTEGER,
|
||||||
|
FOREIGN KEY (entry_id) REFERENCES local_entries(id)
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await run(db, `
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_local_entries_type
|
||||||
|
ON local_entries(type)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await run(db, `
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_local_entries_matched
|
||||||
|
ON local_entries(matched_id)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await run(db, `
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_local_files_entry
|
||||||
|
ON local_files(entry_id)
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(db, sql, params = []) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
db.run(sql, params, err => {
|
||||||
|
if (err) reject(err);
|
||||||
|
else resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async function ensureUserDataDB(dbPath) {
|
async function ensureUserDataDB(dbPath) {
|
||||||
const dir = path.dirname(dbPath);
|
const dir = path.dirname(dbPath);
|
||||||
|
|
||||||
@@ -230,5 +278,6 @@ module.exports = {
|
|||||||
ensureAnilistSchema,
|
ensureAnilistSchema,
|
||||||
ensureExtensionsTable,
|
ensureExtensionsTable,
|
||||||
ensureCacheTable,
|
ensureCacheTable,
|
||||||
ensureFavoritesDB
|
ensureFavoritesDB,
|
||||||
|
ensureLocalLibrarySchema
|
||||||
};
|
};
|
||||||
146
desktop/src/views/views.routes.ts
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||||
|
import * as fs from 'fs';
|
||||||
|
import * as path from 'path';
|
||||||
|
|
||||||
|
let cachedNavbar: string | null = null;
|
||||||
|
|
||||||
|
function getNavbarHTML(activePage: string, showSearch: boolean = true): string {
|
||||||
|
if (!cachedNavbar) {
|
||||||
|
const navbarPath = path.join(__dirname, '..', '..', 'views', 'components', 'navbar.html');
|
||||||
|
cachedNavbar = fs.readFileSync(navbarPath, 'utf-8');
|
||||||
|
}
|
||||||
|
|
||||||
|
let navbar = cachedNavbar;
|
||||||
|
|
||||||
|
const pages = ['anime', 'books', 'gallery', 'schedule' , 'marketplace'];
|
||||||
|
pages.forEach(page => {
|
||||||
|
const regex = new RegExp(`(<button class="nav-button[^"]*)"\\s+data-page="${page}"`, 'g');
|
||||||
|
if (page === activePage) {
|
||||||
|
navbar = navbar.replace(regex, `$1 active" data-page="${page}"`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!showSearch) {
|
||||||
|
navbar = navbar.replace(
|
||||||
|
'<div class="search-wrapper">',
|
||||||
|
'<div class="search-wrapper" style="visibility: hidden;">'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return navbar;
|
||||||
|
}
|
||||||
|
|
||||||
|
function injectNavbar(htmlContent: string, activePage: string, showSearch: boolean = true): string {
|
||||||
|
const navbar = getNavbarHTML(activePage, showSearch);
|
||||||
|
|
||||||
|
return htmlContent.replace(/<body[^>]*>/, `$&\n${navbar}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function viewsRoutes(fastify: FastifyInstance) {
|
||||||
|
|
||||||
|
fastify.get('/', (req: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', 'users.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
reply.type('text/html').send(html);
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get('/anime', (req: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', 'anime', 'animes.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
const htmlWithNavbar = injectNavbar(html, 'anime', true);
|
||||||
|
reply.type('text/html').send(htmlWithNavbar);
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get('/profile', (req: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', 'profile.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
const htmlWithNavbar = injectNavbar(html, '', false);
|
||||||
|
reply.type('text/html').send(htmlWithNavbar);
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get('/books', (req: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', 'books', 'books.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
const htmlWithNavbar = injectNavbar(html, 'books', true);
|
||||||
|
reply.type('text/html').send(htmlWithNavbar);
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get('/schedule', (req: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', 'schedule.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
const htmlWithNavbar = injectNavbar(html, 'schedule', false);
|
||||||
|
reply.type('text/html').send(htmlWithNavbar);
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get('/gallery', (req: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', 'gallery', 'gallery.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
const htmlWithNavbar = injectNavbar(html, 'gallery', true);
|
||||||
|
reply.type('text/html').send(htmlWithNavbar);
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get('/marketplace', (req: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', 'marketplace.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
const htmlWithNavbar = injectNavbar(html, 'marketplace', false);
|
||||||
|
reply.type('text/html').send(htmlWithNavbar);
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get('/gallery/:extension/*', (req: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', 'gallery', 'image.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
const htmlWithNavbar = injectNavbar(html, 'gallery', true);
|
||||||
|
reply.type('text/html').send(htmlWithNavbar);
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get('/gallery/favorites/*', (req: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', 'gallery', 'image.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
const htmlWithNavbar = injectNavbar(html, 'gallery', true);
|
||||||
|
reply.type('text/html').send(htmlWithNavbar);
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get('/anime/:id', (req: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', 'anime', 'anime.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
reply.type('text/html').send(html);
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get('/anime/:extension/*', (req: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', 'anime', 'anime.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
reply.type('text/html').send(html);
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get('/book/:id', (req: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', 'books', 'book.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
reply.type('text/html').send(html);
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get('/book/:extension/*', (req: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', 'books', 'book.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
reply.type('text/html').send(html);
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get('/read/:provider/:chapter/*', (req: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', 'books', 'read.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
reply.type('text/html').send(html);
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get('/room', (req: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', 'room.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
reply.type('text/html').send(html);
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.setNotFoundHandler((req, reply) => {
|
||||||
|
const htmlPath = path.join(__dirname, '..', '..', 'views', '404.html');
|
||||||
|
const html = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
reply.code(404).type('text/html').send(html);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export default viewsRoutes;
|
||||||
139
desktop/views/404.html
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>404 - WaifuBoard</title>
|
||||||
|
<link rel="stylesheet" href="/views/css/globals.css">
|
||||||
|
<link rel="stylesheet" href="/views/css/components/navbar.css">
|
||||||
|
<link rel="stylesheet" href="/views/css/components/titlebar.css">
|
||||||
|
<link rel="icon" href="/public/assets/waifuboards.ico" type="image/x-icon">
|
||||||
|
|
||||||
|
<script src="/src/scripts/titlebar.js"></script>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.error-container {
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
text-align: center;
|
||||||
|
padding: var(--spacing-2xl);
|
||||||
|
background: var(--color-bg-base);
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-code {
|
||||||
|
font-size: 6rem;
|
||||||
|
font-weight: 900;
|
||||||
|
margin: 0;
|
||||||
|
color: var(--color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-message {
|
||||||
|
font-size: 1.1rem;
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
margin: var(--spacing-md) 0 var(--spacing-xl);
|
||||||
|
max-width: 420px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: var(--spacing-md);
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div id="titlebar">
|
||||||
|
<div class="title-left">
|
||||||
|
<img class="app-icon" src="/public/assets/waifuboards.ico" alt=""/>
|
||||||
|
<span class="app-title">WaifuBoard</span>
|
||||||
|
</div>
|
||||||
|
<div class="title-right">
|
||||||
|
<button class="min">−</button>
|
||||||
|
<button class="max">🗖</button>
|
||||||
|
<button class="close">✕</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<nav class="navbar" id="navbar">
|
||||||
|
<a href="#" class="nav-brand">
|
||||||
|
<div class="brand-icon">
|
||||||
|
<img src="/public/assets/waifuboards.ico" alt="WF Logo">
|
||||||
|
</div>
|
||||||
|
WaifuBoard
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<div class="nav-center">
|
||||||
|
<button class="nav-button" onclick="window.location.href='/anime'">Anime</button>
|
||||||
|
<button class="nav-button" onclick="window.location.href='/books'">Books</button>
|
||||||
|
<button class="nav-button" onclick="window.location.href='/gallery'">Gallery</button>
|
||||||
|
<button class="nav-button" onclick="window.location.href='/schedule'">Schedule</button>
|
||||||
|
<button class="nav-button" onclick="window.location.href='/my-list'">My List</button>
|
||||||
|
<button class="nav-button" onclick="window.location.href='/marketplace'">Marketplace</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="nav-right">
|
||||||
|
<div class="search-wrapper" style="visibility: hidden;">
|
||||||
|
<svg class="search-icon" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
|
||||||
|
<circle cx="11" cy="11" r="8"/>
|
||||||
|
<path d="M21 21l-4.35-4.35"/>
|
||||||
|
</svg>
|
||||||
|
<input type="text" class="search-input" id="search-input" placeholder="Search anime..." autocomplete="off">
|
||||||
|
<div class="search-results" id="search-results"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="nav-user" id="nav-user" style="display:none;">
|
||||||
|
<div class="user-avatar-btn">
|
||||||
|
<img id="nav-avatar" src="/public/assets/waifuboards.ico" alt="avatar">
|
||||||
|
<div class="online-indicator"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="nav-dropdown" id="nav-dropdown">
|
||||||
|
<div class="dropdown-header">
|
||||||
|
<img id="dropdown-avatar" src="/public/assets/waifuboards.ico" alt="avatar" class="dropdown-avatar">
|
||||||
|
<div class="dropdown-user-info">
|
||||||
|
<div class="dropdown-username" id="nav-username"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<a href="/my-list" class="dropdown-item">
|
||||||
|
<svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
|
||||||
|
<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/>
|
||||||
|
<polyline points="17 21 17 13 7 13 7 21"/>
|
||||||
|
<polyline points="7 3 7 8 15 8"/>
|
||||||
|
</svg>
|
||||||
|
<span>My List</span>
|
||||||
|
</a>
|
||||||
|
<button class="dropdown-item logout-item" id="nav-logout">
|
||||||
|
<svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
|
||||||
|
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
|
||||||
|
<polyline points="16 17 21 12 16 7"/>
|
||||||
|
<line x1="21" y1="12" x2="9" y2="12"/>
|
||||||
|
</svg>
|
||||||
|
<span>Logout</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<main class="error-container">
|
||||||
|
<div>
|
||||||
|
<h1 class="error-code">404</h1>
|
||||||
|
<p class="error-message">
|
||||||
|
This page doesn’t exist.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="error-actions">
|
||||||
|
<button class="btn-primary" onclick="location.href='/'">Home</button>
|
||||||
|
<button class="btn-blur" onclick="history.back()">Back</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script src="/src/scripts/utils/auth-utils.js"></script>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||