-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.js
421 lines (359 loc) · 12.5 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
const parseTorrent = require("parse-torrent");
const express = require("express");
const app = express();
const fetch = require("node-fetch");
const torrentStream = require("torrent-stream");
const bodyParser = require("body-parser");
const pLimit = require('p-limit');
const http = require("http");
const limit = pLimit(10);
function getSize(size) {
const gb = 1024 * 1024 * 1024;
const mb = 1024 * 1024;
return (
"💾 " +
(size / gb > 1 ? `${(size / gb).toFixed(2)} GB` : `${(size / mb).toFixed(2)} MB`)
);
}
function getQuality(name) {
name = name.toLowerCase();
if (["2160", "4k", "uhd"].some((x) => name.includes(x))) return "🌟4k";
if (["1080", "fhd"].some((x) => name.includes(x))) return " 🎥FHD";
if (["720", "hd"].some((x) => name.includes(x))) return "📺HD";
if (["480p", "380p", "sd"].some((x) => name.includes(x))) return "📱SD";
return "";
}
const toStream = async (parsed, uri, tor, type, s, e) => {
const infoHash = parsed.infoHash.toLowerCase();
let title = tor.extraTag || parsed.name;
let index = 0;
if (!parsed.files && uri.startsWith("magnet")) {
try {
const engine = torrentStream("magnet:" + uri, {
connections: 3, // Limit the number of connections/streams
});
const res = await new Promise((resolve, reject) => {
engine.on("ready", function () {
resolve(engine.files);
});
setTimeout(() => {
resolve([]);
}, 5000); // Timeout if the server is too slow
});
parsed.files = res;
// Properly close the torrent engine
engine.on("idle", () => {
engine.destroy((err) => {
if (err) {
console.error("Error destroying engine:", err);
}
});
});
} catch (error) {
console.error("Error fetching torrent data:", error);
}
}
if (type === "series") {
index = (parsed.files || []).findIndex((element) => {
return (
element["name"]?.toLowerCase()?.includes(`s0${s}`) &&
element["name"]?.toLowerCase()?.includes(`e0${e}`) &&
[".mkv", ".mp4", ".avi", ".flv"].some((ext) =>
element["name"]?.toLowerCase()?.includes(ext)
)
);
});
if (index === -1) {
return null;
}
title += index === -1 ? "" : `\n${parsed.files[index]["name"]}`;
}
title += "\n" + getQuality(title);
const subtitle = "S:" + tor["Seeders"] + " /P:" + tor["Peers"];
title += ` | ${
index === -1
? `${getSize(parsed.length || 0)}`
: `${getSize((parsed.files && parsed.files[index]?.length) || 0)}`
} | ${subtitle} `;
return {
name: tor["Tracker"],
type,
infoHash,
fileIdx: index === -1 ? 0 : index,
sources: (parsed.announce || []).map((x) => {
return "tracker:" + x;
}).concat(["dht:" + infoHash]),
title,
behaviorHints: {
bingeGroup: `Jackett-Addon|${infoHash}`,
notWebReady: true,
},
};
};
const isRedirect = async (url) => {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error("Request timeout"));
}, 5000); // 5-second timeout
const urlObject = new URL(url);
// Ensure the protocol is either "http" or "https"
if (urlObject.protocol !== "http:" && urlObject.protocol !== "https:") {
reject(new Error("Invalid protocol. Expected 'http:' or 'https:'"));
}
const requestOptions = {
protocol: urlObject.protocol,
hostname: urlObject.hostname,
port: urlObject.port || (urlObject.protocol === 'http:' ? 80 : 443), // Use 80 for HTTP and 443 for HTTPS
path: urlObject.pathname + urlObject.search,
method: "HEAD",
};
const request = http.request(requestOptions, (response) => {
clearTimeout(timeoutId);
if (response.statusCode === 301 || response.statusCode === 302) {
const locationURL = new URL(response.headers.location);
if (locationURL.href.startsWith("http") || locationURL.href.startsWith("https")) {
resolve(isRedirect(locationURL.href));
} else {
resolve(locationURL.href);
}
} else if (response.statusCode >= 200 && response.statusCode < 300) {
resolve(url);
} else {
resolve(null);
}
});
request.on("error", (error) => {
clearTimeout(timeoutId);
console.error("Error while following redirection:", error);
resolve(null);
});
request.end();
});
};
const streamFromMagnet = async (tor, uri, type, s, e, retries = 3) => {
return new Promise(async (resolve, reject) => {
let retryCount = 0;
const attemptStream = async () => {
try {
if (uri.startsWith("magnet:?")) {
const parsedTorrent = parseTorrent(uri);
resolve(await toStream(parsedTorrent, uri, tor, type, s, e));
} else {
// Follow redirection in case the URI is not directly accessible
const realUrl = await isRedirect(uri);
if (!realUrl) {
console.log("No real URL found.");
resolve(null);
return;
}
if (realUrl.startsWith("magnet:?")) {
const parsedTorrent = parseTorrent(realUrl);
resolve(await toStream(parsedTorrent, realUrl, tor, type, s, e));
} else if (realUrl.startsWith("http")) {
parseTorrent.remote(realUrl, (err, parsed) => {
if (!err) {
resolve(toStream(parsed, realUrl, tor, type, s, e));
} else {
console.error("Error parsing HTTP:", err);
resolve(null);
}
});
} else {
console.error("No HTTP nor magnet URI found.");
resolve(null);
}
}
} catch (error) {
console.error("Error while streaming from magnet:", error);
retryCount++;
if (retryCount < retries) {
console.log("Retrying...");
attemptStream();
} else {
console.error("Exceeded retry attempts. Giving up.");
resolve(null);
}
}
};
attemptStream();
});
};
let stream_results = [];
let torrent_results = [];
const host1 = {
hostUrl: "http://94.61.74.253:9117",
apiKey: "e71yh2n0fopfnyk2j2ywzjfa3sz4xv8d",
};
const host2 = {
hostUrl: "http://100.12.26.164:9117",
apiKey: "b3f8f3fb4rtt4vcsml7cz82dtkjbj3df",
};
const fetchTorrentFromHost1 = async (query) => {
const { hostUrl, apiKey } = host1;
const url = `${hostUrl}/api/v2.0/indexers/all/results?apikey=${apiKey}&Query=${query}&Category%5B%5D=2000&Category%5B%5D=5000&Category%5B%5D=8000&Tracker%5B%5D=solidtorrents`;
try {
const response = await fetch(url, {
headers: {
accept: "*/*",
"accept-language": "en-US,en;q=0.9",
"x-requested-with": "XMLHttpRequest",
cookie:
"Jackett=CfDJ8HP8067qbltBhRjGgbPRVDdaKWzrsM6C5svHO9U2nsmpw_Zc5Z5_U0qeH1Cec8ue0evNAtm2AtGvt2u-b6-NWCGJpVDkXJuwIk1q4AOhr6KW5zc4ekB0dSmc_qrsJJcOeHiIvlyz-l-S8m-V8r7qPiDemc0pHbtO2CO-UlOR5pet-jGWnVGSlVLclt6XxqTjqaz2r60Sr8Qo9ETKcZ4FS4HLwYjcQuM2q4UEXbM8Jo0prlQCqWazpyeciepwhLCLs9OLayav19hrd31XWm7KUZG4J1MJAbAfiq-TzLXlVE5svg6LodvEYVSGODI0z9DJSYWtjS2xjxayWc6guKtqVYU",
},
referrerPolicy: "no-referrer",
method: "GET",
});
if (!response.ok) {
console.error("Error fetching torrents from host 1. Status:", response.status);
return [];
}
const results = await response.json();
console.log({ Host1: results["Results"].length });
if (results["Results"].length !== 0) {
return results["Results"].map((result) => ({
Tracker: result["Tracker"],
Category: result["CategoryDesc"],
Title: result["Title"],
Seeders: result["Seeders"],
Peers: result["Peers"],
Link: result["Link"],
MagnetUri: result["MagnetUri"],
Host: "Host1", // Add a new property indicating the host
}));
} else {
return [];
}
} catch (error) {
console.error("Error fetching torrents from host 1:", error);
return [];
}
};
const fetchTorrentFromHost2 = async (query) => {
const { hostUrl, apiKey } = host2;
const url = `${hostUrl}/api/v2.0/indexers/all/results?apikey=${apiKey}&Query=${query}&Category%5B%5D=8000&Tracker%5B%5D=torrentscsv`;
try {
const response = await fetch(url, {
headers: {
accept: "*/*",
"accept-language": "en-US,en;q=0.9",
"x-requested-with": "XMLHttpRequest",
cookie:
"Jackett=CfDJ8JGMKzAOIg1GpbGxjar2TujvQ1tVmIta0XThcBG4V_j32mQnx6z3GDTiqYsDLv0jLvfan6JOfx_Mr61hId8KLu389GzmDM6RDqq6yN7K3-ucA7FSricYvgWGmNnVq5xL7cdQfNVIvv78fhRG0Z7lw_Yjz47ZPY9ChVi2ppvE9NFr8dMUg_-fto8XEFEy29ZI6bsxX4KWYoEP-S_zUhhymLf54VJSQKCAvo7d0ZLzWh9p_08kEGaGxyTA8tZYhbolyjKEBoGno80BawzJq2jog8ThKhmtN45rAQdb1CrOkT9dl0S8e0M0_ivZJj-_YeLWOtRn9ygYhiAFhZkIRTJXXbw",
},
referrerPolicy: "no-referrer",
method: "GET",
});
if (!response.ok) {
console.error("Error fetching torrents from host 2. Status:", response.status);
return [];
}
const results = await response.json();
console.log({ Host2: results["Results"].length });
if (results["Results"].length !== 0) {
return results["Results"].map((result) => ({
Tracker: result["Tracker"],
Category: result["CategoryDesc"],
Title: result["Title"],
Seeders: result["Seeders"],
Peers: result["Peers"],
Link: result["Link"],
MagnetUri: result["MagnetUri"],
Host: "Host2", // Add a new property indicating the host
}));
} else {
return [];
}
} catch (error) {
console.error("Error fetching torrents from host 2:", error);
return [];
}
};
function getMeta(id, type) {
var [tt, s, e] = id.split(":");
return fetch(`https://v2.sg.media-imdb.com/suggestion/t/${tt}.json`)
.then((res) => res.json())
.then((json) => json.d[0])
.then(({ l, y }) => ({ name: l, year: y }))
.catch((err) =>
fetch(`https://v3-cinemeta.strem.io/meta/${type}/${tt}.json`)
.then((res) => res.json())
.then((json) => json.meta)
);
}
app.get("/manifest.json", (req, res) => {
const manifest = {
id: "hy.torr.org",
version: "1.0.1",
name: "HYJackett",
description: "Movie & TV Torrents from Jackett",
logo: "https://raw.githubusercontent.com/mikmc55/hyackett/main/hyjackett.jpg",
resources: ["stream"],
types: ["movie", "series"],
idPrefixes: ["tt"],
catalogs: [],
};
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "*");
res.setHeader("Content-Type", "application/json");
return res.send(manifest);
});
app.get("/stream/:type/:id", async (req, res) => {
const media = req.params.type;
let id = req.params.id;
id = id.replace(".json", "");
let [tt, s, e] = id.split(":");
let query = "";
let meta = await getMeta(tt, media);
console.log({ meta: id });
console.log({ meta });
query = meta?.name;
if (media === "movie") {
query += " " + meta?.year;
} else if (media === "series") {
query += " S" + (s ?? "1").padStart(2, "0");
}
query = encodeURIComponent(query);
// Fetch torrents from both hosts
const result1 = await limit(() => fetchTorrentFromHost1(query));
const result2 = await limit(() => fetchTorrentFromHost2(query));
// Combine results from both hosts
const combinedResults = result1.concat(result2);
// Process and filter the combined results
const uniqueResults = [];
const seenTorrents = new Set();
for (const torrent of combinedResults) {
const torrentKey = `${torrent.Tracker}-${torrent.Title}`;
if (
!seenTorrents.has(torrentKey) &&
(torrent["MagnetUri"] !== "" || torrent["Link"] !== "") &&
torrent["Peers"] > 0
) {
seenTorrents.add(torrentKey);
uniqueResults.push(torrent);
}
}
// Use the global stream_results variable, no need to re-declare it here
stream_results = await Promise.all(
uniqueResults.map((torrent) => {
return limit(() => streamFromMagnet(
torrent,
torrent["MagnetUri"] || torrent["Link"],
media,
s,
e
));
})
);
stream_results = stream_results.filter((e) => !!e);
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "*");
res.setHeader("Content-Type", "application/json");
// Send the response with the stream_results
res.send({ streams: stream_results });
console.log({ check: "check" });
console.log({ Final: stream_results.length });
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log("The server is working on port " + port);
});