This repository was archived by the owner on May 22, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
318 lines (268 loc) · 16.2 KB
/
Copy pathserver.js
File metadata and controls
318 lines (268 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
require("dotenv").config();
const express = require("express");
const axios = require("axios");
const path = require("path");
const fs = require("fs");
const { getRouter } = require("stremio-addon-sdk");
const { addonInterface } = require("./addon");
const { selectBestVideoFile } = require("./lib/parser");
const app = express();
app.use(express.json());
//===============
// CORS & PREFLIGHT HANDLING
// This middleware ensures that strict environments like Stremio Web
// on Apple devices (WebKit) do not block the addon requests.
// We explicitly allow the "Range" header for subtitle seeking.
//===============
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, HEAD");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Range");
res.setHeader("Access-Control-Expose-Headers", "Content-Length, Content-Range");
if (req.method === "OPTIONS") {
return res.status(204).end();
}
next();
});
//===============
// GLOBAL ERROR HANDLER
// Prevents the Node.js process from crashing if a promise is rejected
// without a ".catch()" block somewhere in the async operations.
//===============
process.on("unhandledRejection", (reason, promise) => {
console.error("Unhandled Rejection at:", promise, "reason:", reason);
});
app.use(express.static(path.join(__dirname, "public")));
app.use(express.static(path.join(__dirname, "static")));
const port = process.env.PORT || 7002;
// Fallback for missing environment variables when self-hosting
let BASE_URL = process.env.BASE_URL || "http://127.0.0.1:7002";
BASE_URL = BASE_URL.replace(/\/+$/, "");
const NYAA_DOMAIN = (process.env.NYAA_DOMAIN || "https://nyaa.iss.one").replace(/\/+$/, "");
// API status endpoint
app.get("/health", (req, res) => res.status(200).json({ "status": "alive" }));
//===============
// NYAA STATUS CHECK
// Caches the Nyaa.si health status for 5 minutes (300000ms) to prevent
// spamming the tracker with health check pings from the frontend UI.
//===============
let nyaaCache = { "status": "checking", "timestamp": 0 };
app.get("/nyaa-status", async (req, res) => {
const now = Date.now();
if (now - nyaaCache.timestamp < 300000 && nyaaCache.status !== "checking") {
return res.json({ "status": nyaaCache.status });
}
try {
await axios.get(NYAA_DOMAIN, {
"timeout": 5000,
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8"
},
"validateStatus": function (status) {
// Nyaa often returns 403 or 503 when under Cloudflare protection,
// but that still means the server is "alive" and reachable.
return (status >= 200 && status < 300) || status === 403 || status === 503;
}
});
nyaaCache = { "status": "online", "timestamp": now };
res.json({ "status": "online" });
} catch (error) {
nyaaCache = { "status": "online", "timestamp": now };
res.json({ "status": "online" });
}
});
app.get("/configure", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
//===============
// BULLETPROOF SUBTITLE PROXY
// Bypasses CORS and bandwidth limitations by piping the subtitle file
// directly through our backend to the Stremio video player.
// Includes connection-drop detection to prevent memory leaks.
//===============
app.get("/sub/:provider/:apiKey/:hash/:fileId", async (req, res) => {
const { provider, apiKey, hash, fileId } = req.params;
let clientAborted = false;
// Detect if the user closed the video player prematurely
req.on("close", () => { clientAborted = true; });
try {
let downloadUrl = null;
let fileName = req.query.filename || "sub.srt";
//===============
// REAL-DEBRID SUBTITLE RESOLUTION
// Fetches the torrent, finds the correct file ID, grabs the
// restricted link, and unrestricts it for direct download.
//===============
if (provider === "realdebrid") {
let list = await axios.get("https://api.real-debrid.com/rest/1.0/torrents?limit=250", { "headers": { "Authorization": "Bearer " + apiKey } });
let torrent = list.data.find(t => t.hash.toLowerCase() === hash.toLowerCase());
// Retry logic in case the torrent was just added and isn't listed yet
if (!torrent) {
await new Promise(resolve => setTimeout(resolve, 2500));
list = await axios.get("https://api.real-debrid.com/rest/1.0/torrents?limit=250", { "headers": { "Authorization": "Bearer " + apiKey } });
torrent = list.data.find(t => t.hash.toLowerCase() === hash.toLowerCase());
}
if (torrent) {
const info = await axios.get("https://api.real-debrid.com/rest/1.0/torrents/info/" + torrent.id, { "headers": { "Authorization": "Bearer " + apiKey } });
const fileIdx = info.data.files.findIndex(f => f.id == fileId);
if (fileIdx !== -1) {
const targetFile = info.data.files[fileIdx];
if (targetFile.selected === 0) return res.status(404).send("Subtitle not selected");
fileName = targetFile.path;
let targetLink = null;
let linkCounter = 0;
// Real-Debrid maps "links" to "selected files".
// We must count how many files are selected BEFORE our target file
// to find the matching unrestrict link index.
for (let i = 0; i < info.data.files.length; i++) {
if (i === fileIdx) { targetLink = info.data.links[linkCounter]; break; }
if (info.data.files[i].selected === 1) linkCounter++;
}
if (targetLink) {
const unrestrict = await axios.post("https://api.real-debrid.com/rest/1.0/unrestrict/link", new URLSearchParams({ "link": targetLink }), { "headers": { "Authorization": "Bearer " + apiKey } });
downloadUrl = unrestrict.data.download;
}
}
}
}
//===============
// TORBOX SUBTITLE RESOLUTION
// Much simpler API. Direct request for the download link using file_id.
//===============
else if (provider === "torbox") {
let dlRes = null;
try {
dlRes = await axios.get("https://api.torbox.app/v1/api/torrents/requestdl?token=" + apiKey + "&hash=" + hash + "&file_id=" + fileId);
} catch (err) {
await new Promise(resolve => setTimeout(resolve, 2500));
dlRes = await axios.get("https://api.torbox.app/v1/api/torrents/requestdl?token=" + apiKey + "&hash=" + hash + "&file_id=" + fileId);
}
if (dlRes && dlRes.data && dlRes.data.data) downloadUrl = dlRes.data.data;
}
if (!downloadUrl) return res.status(404).send("Subtitle not found");
// Open a stream to download the subtitle file
const subResponse = await axios.get(downloadUrl, { "responseType": "stream", "timeout": 10000 });
if (clientAborted) { if (subResponse.data?.destroy) subResponse.data.destroy(); return; }
const ext = fileName.split(".").pop().toLowerCase();
let finalMime = subResponse.headers["content-type"];
// Enforce strict MIME types. Some Debrid providers send "octet-stream"
// which prevents Stremio from rendering the subtitles correctly.
if (!finalMime || finalMime.includes("octet-stream") || finalMime.includes("plain")) {
if (ext === "vtt") finalMime = "text/vtt";
else if (ext === "ass" || ext === "ssa") finalMime = "text/x-ssa";
else if (ext === "srt") finalMime = "application/x-subrip";
else finalMime = "text/plain";
}
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Content-Type", finalMime);
res.setHeader("Cache-Control", "public, max-age=86400");
// Pipe the stream and ensure cleanup if connection closes
subResponse.data.on("error", () => res.end());
req.on("close", () => { if (subResponse.data?.destroy) subResponse.data.destroy(); });
subResponse.data.pipe(res);
} catch (e) {
console.error("[Sub Proxy Error]", e.message);
res.status(500).send("Error fetching subtitle data");
}
});
//===============
// FALLBACK VIDEOS
// When a torrent is uncached and needs to be downloaded by the Debrid service,
// Stremio cannot wait. We send a small looping video back immediately.
//===============
function serveLoadingVideo(req, res) {
res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
res.redirect(BASE_URL + "/waiting.mp4");
}
function serveArchiveVideo(req, res) {
res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
res.redirect(BASE_URL + "/archive.mp4");
}
//===============
// STREAM RESOLVER
// Receives the direct click from the user in Stremio.
// Locates the hash on the Debrid service, determines the best file,
// unrestricts it, and redirects the Stremio player to the raw MP4/MKV URL.
//===============
app.get("/resolve/:provider/:apiKey/:hash/:episode?", async (req, res) => {
const { provider, apiKey, hash, episode } = req.params;
const requestedEp = episode || "1";
const magnet = "magnet:?xt=urn:btih:" + hash;
try {
if (provider === "realdebrid") {
const listRes = await axios.get("https://api.real-debrid.com/rest/1.0/torrents?limit=250", { "headers": { "Authorization": "Bearer " + apiKey } });
let torrent = listRes.data.find(t => t.hash.toLowerCase() === hash.toLowerCase());
// If the torrent is missing from RD, add it dynamically
if (!torrent) {
const add = await axios.post("https://api.real-debrid.com/rest/1.0/torrents/addMagnet", new URLSearchParams({ "magnet": magnet }), { "headers": { "Authorization": "Bearer " + apiKey } });
torrent = { "id": add.data.id };
}
let info = await axios.get("https://api.real-debrid.com/rest/1.0/torrents/info/" + torrent.id, { "headers": { "Authorization": "Bearer " + apiKey } });
// Clean up dead/errored torrents immediately
if (["magnet_error", "error", "virus", "dead"].includes(info.data.status)) {
await axios.delete("https://api.real-debrid.com/rest/1.0/torrents/delete/" + torrent.id, { "headers": { "Authorization": "Bearer " + apiKey } }).catch(() => null);
return res.status(404).send("Torrent is dead.");
}
if (info.data.status !== "downloaded") {
// If it's waiting for file selection, automatically select all valid media and subtitle files
if (info.data.status === "waiting_files_selection") {
const selectedIds = info.data.files.filter(f => /\.(mkv|mp4|avi|wmv|flv|webm|m4v|ts|m2ts|mov|ass|srt|ssa|vtt)$/.test((f.path || "").toLowerCase())).map(f => f.id);
await axios.post("https://api.real-debrid.com/rest/1.0/torrents/selectFiles/" + torrent.id, "files=" + (selectedIds.length > 0 ? selectedIds.join(",") : "all"), {
"headers": { "Authorization": "Bearer " + apiKey, "Content-Type": "application/x-www-form-urlencoded" }
});
await new Promise(resolve => setTimeout(resolve, 1500));
info = await axios.get("https://api.real-debrid.com/rest/1.0/torrents/info/" + torrent.id, { "headers": { "Authorization": "Bearer " + apiKey } });
}
// If still downloading, serve the waiting video
if (info.data.status !== "downloaded") return serveLoadingVideo(req, res);
}
// Use our parser library to find the exact episode within a potentially large batch torrent
const isBatch = /batch|complete|all\s+episodes/i.test(info.data.filename || "");
const bestFileFresh = selectBestVideoFile(info.data.files, requestedEp, 1, !isBatch);
if (!bestFileFresh) return serveArchiveVideo(req, res);
// If the best file wasn't selected during the initial RD process, delete the torrent
// so it can be re-added and re-selected correctly on the next click.
if (bestFileFresh.selected === 0) {
await axios.delete("https://api.real-debrid.com/rest/1.0/torrents/delete/" + torrent.id, { "headers": { "Authorization": "Bearer " + apiKey } }).catch(() => null);
return res.redirect(req.originalUrl);
}
const targetFileIndex = info.data.files.findIndex(f => f.id === bestFileFresh.id);
let targetLink = info.data.links[0];
if (targetFileIndex !== -1) {
let linkCounter = 0;
for (let i = 0; i < info.data.files.length; i++) {
if (i === targetFileIndex) { targetLink = info.data.links[linkCounter]; break; }
if (info.data.files[i].selected === 1) linkCounter++;
}
}
if (!targetLink) return serveLoadingVideo(req, res);
// Finally, unrestrict the valid link and redirect the player
const unrestrict = await axios.post("https://api.real-debrid.com/rest/1.0/unrestrict/link", new URLSearchParams({ "link": targetLink }), { "headers": { "Authorization": "Bearer " + apiKey } });
return res.redirect(unrestrict.data.download);
}
if (provider === "torbox") {
const list = await axios.get("https://api.torbox.app/v1/api/torrents/mylist?bypass_cache=true", { "headers": { "Authorization": "Bearer " + apiKey } });
let torrent = list.data.data ? list.data.data.find(t => t.hash.toLowerCase() === hash.toLowerCase()) : null;
if (!torrent) {
const boundary = "----WebKitFormBoundaryAmatsu";
try {
await axios.post("https://api.torbox.app/v1/api/torrents/createtorrent", "--" + boundary + "\r\nContent-Disposition: form-data; name=\"magnet\"\r\n\r\n" + magnet + "\r\n--" + boundary + "--", { "headers": { "Authorization": "Bearer " + apiKey, "Content-Type": "multipart/form-data; boundary=" + boundary } });
} catch (e) { return serveLoadingVideo(req, res); }
return serveLoadingVideo(req, res);
}
if (["error", "failed", "dead", "deleted"].includes(torrent.download_state)) return res.status(404).send("Torrent is dead.");
if (torrent.download_state !== "completed" && torrent.download_state !== "cached") return serveLoadingVideo(req, res);
const isBatch = /batch|complete|all\s+episodes/i.test(torrent.name || "");
const bestFile = selectBestVideoFile(torrent.files, requestedEp, 1, !isBatch);
if (!bestFile) return serveArchiveVideo(req, res);
const dl = await axios.get("https://api.torbox.app/v1/api/torrents/requestdl?token=" + apiKey + "&torrent_id=" + torrent.id + "&file_id=" + bestFile.id);
return res.redirect(dl.data.data);
}
} catch (e) {
console.error("[Resolve Error] Core resolution failure: " + e.message);
return serveLoadingVideo(req, res);
}
});
app.use("/", getRouter(addonInterface));
app.listen(port, "0.0.0.0", () => console.log("AMATSU ONLINE | PORT " + port));