gre89 commited on
Commit
d9c040a
·
verified ·
1 Parent(s): 9c990a4

Upload 5 files

Browse files
Files changed (5) hide show
  1. jackett.js +364 -0
  2. magnet-fix.js +129 -0
  3. package.json +24 -0
  4. server-with-jackett.js +499 -0
  5. torrent-utils.js +395 -0
jackett.js ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // jackett.js - Module for searching torrents via Jackett's API
2
+ import { analyzeTorrentFromUrl } from './torrent-utils.js';
3
+ import { fixMagnetUri, processMagnetLink, likelyContainsVideo } from './magnet-fix.js';
4
+
5
+ async function fetchWithTimeout(url, options = {}, timeout = 30000) {
6
+ const controller = new AbortController();
7
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
8
+
9
+ try {
10
+ const response = await fetch(url, {
11
+ ...options,
12
+ signal: controller.signal,
13
+ headers: {
14
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
15
+ 'Accept': 'application/json',
16
+ 'Accept-Language': 'en-US,en;q=0.9',
17
+ ...options.headers
18
+ }
19
+ });
20
+ clearTimeout(timeoutId);
21
+ return response;
22
+ } catch (error) {
23
+ clearTimeout(timeoutId);
24
+ throw error;
25
+ }
26
+ }
27
+
28
+ function parseSize(sizeStr) {
29
+ if (!sizeStr || typeof sizeStr !== 'string') return 0;
30
+ // Convert size string to bytes
31
+ const units = { KB: 1024, MB: 1024 ** 2, GB: 1024 ** 3, TB: 1024 ** 4 };
32
+ const match = sizeStr.match(/^(\d+(?:\.\d+)?)\s*([KMGT]B)$/i);
33
+ if (!match) return 0;
34
+ const [, size, unit] = match;
35
+ return parseFloat(size) * (units[unit.toUpperCase()] || 1);
36
+ }
37
+
38
+ function extractQuality(title) {
39
+ if (!title || typeof title !== 'string') return '';
40
+ const qualityMatch = title.match(/\b(2160p|1080p|720p|4k|uhd)\b/i);
41
+ return qualityMatch ? qualityMatch[1].toLowerCase() : '';
42
+ }
43
+
44
+ // Safely get property from object with a default value if not present or wrong type
45
+ function safeGet(obj, path, defaultValue) {
46
+ if (!obj) return defaultValue;
47
+
48
+ const pathParts = path.split('.');
49
+ let current = obj;
50
+
51
+ for (const part of pathParts) {
52
+ if (current === null || current === undefined || typeof current !== 'object') {
53
+ return defaultValue;
54
+ }
55
+ current = current[part];
56
+ }
57
+
58
+ return current !== undefined ? current : defaultValue;
59
+ }
60
+
61
+ /**
62
+ * Sanitizes a search query by removing special characters
63
+ * @param {string} query - The original search query
64
+ * @returns {string} - The sanitized search query
65
+ */
66
+ function sanitizeSearchQuery(query) {
67
+ if (!query || typeof query !== 'string') {
68
+ return '';
69
+ }
70
+
71
+ // Remove apostrophes, quotes, and other special characters
72
+ // but preserve spaces, numbers, and alphanumeric characters
73
+ return query.replace(/[''"&?!:;,.()\[\]{}<>]/g, '')
74
+ .replace(/\s+/g, ' ') // Replace multiple spaces with single space
75
+ .trim(); // Remove leading/trailing whitespace
76
+ }
77
+
78
+ async function searchJackett(searchQuery, config, type = 'movie') {
79
+ if (!searchQuery || typeof searchQuery !== 'string') {
80
+ console.log('No search query provided');
81
+ return [];
82
+ }
83
+
84
+ // Sanitize the search query to remove special characters
85
+ const sanitizedQuery = sanitizeSearchQuery(searchQuery);
86
+
87
+ if (!sanitizedQuery) {
88
+ console.log('Search query is empty after sanitization');
89
+ return [];
90
+ }
91
+
92
+ const { apiKey, baseUrl, trackers = [] } = config || {};
93
+ if (!apiKey || !baseUrl) {
94
+ throw new Error('Missing required configuration: apiKey or baseUrl');
95
+ }
96
+
97
+ console.log(`\n🔄 Searching Jackett for: ${sanitizedQuery} (original: "${searchQuery}")`);
98
+ console.log(`Using trackers: ${trackers.length > 0 ? trackers.join(', ') : 'All available'}`);
99
+
100
+ try {
101
+ // Construct the query URL with tracker filtering
102
+ let jackettUrl = `${baseUrl}/api/v2.0/indexers/all/results?apikey=${apiKey}&Query=${encodeURIComponent(sanitizedQuery)}`;
103
+
104
+ // Add tracker filtering if trackers are specified
105
+ if (trackers && trackers.length > 0) {
106
+ const trackerParams = trackers.map(tracker => `Tracker[]=${encodeURIComponent(tracker)}`).join('&');
107
+ jackettUrl += `&${trackerParams}`;
108
+ }
109
+
110
+ console.log('Request URL:', jackettUrl);
111
+
112
+ const response = await fetchWithTimeout(jackettUrl);
113
+ if (!response.ok) {
114
+ throw new Error(`Jackett API error: ${response.status}`);
115
+ }
116
+
117
+ const data = await response.json();
118
+ console.log(`Found ${safeGet(data, 'Results.length', 0)} results from Jackett`);
119
+
120
+ if (!data.Results || !Array.isArray(data.Results) || data.Results.length === 0) {
121
+ return [];
122
+ }
123
+
124
+ // Filter by type if needed
125
+ let filteredResults = data.Results;
126
+ if (type === 'movie') {
127
+ // Filter for movie categories - typically 2000's range represents movies
128
+ filteredResults = data.Results.filter(result => {
129
+ const categories = Array.isArray(result.Category) ? result.Category : [result.Category];
130
+ return categories.some(cat => (cat >= 2000 && cat < 3000) || cat === 1);
131
+ });
132
+ } else if (type === 'series') {
133
+ // Filter for TV show categories - typically 5000's range represents TV
134
+ filteredResults = data.Results.filter(result => {
135
+ const categories = Array.isArray(result.Category) ? result.Category : [result.Category];
136
+ return categories.some(cat => (cat >= 5000 && cat < 6000) || cat === 2);
137
+ });
138
+ }
139
+
140
+ // Map results to our standardized format
141
+ const streams = filteredResults.map(result => {
142
+ // Extract the year if present in the title
143
+ const title = safeGet(result, 'Title', '');
144
+ const yearMatch = typeof title === 'string' ? title.match(/(?:19|20)\d{2}/) : null;
145
+ const year = yearMatch ? yearMatch[0] : null;
146
+
147
+ // Calculate seeders/leechers count
148
+ const seeders = typeof result.Seeders === 'number' ? result.Seeders : 0;
149
+ const leechers = typeof result.Peers === 'number' ? result.Peers : 0;
150
+
151
+ // Fix magnet link immediately if present
152
+ let magnetLink = safeGet(result, 'MagnetUri', null);
153
+ if (magnetLink) {
154
+ magnetLink = fixMagnetUri(magnetLink);
155
+ }
156
+
157
+ return {
158
+ title: title,
159
+ magnetLink: magnetLink,
160
+ torrentLink: safeGet(result, 'Link', null),
161
+ infoHash: safeGet(result, 'InfoHash', null),
162
+ quality: extractQuality(title),
163
+ size: result.Size ? `${(result.Size / (1024 * 1024 * 1024)).toFixed(2)} GB` : 'Unknown',
164
+ source: safeGet(result, 'Tracker', 'Jackett'),
165
+ seeders: seeders,
166
+ leechers: leechers,
167
+ year: year,
168
+ category: safeGet(result, 'CategoryDesc', ''),
169
+ mainFileSize: safeGet(result, 'Size', 0),
170
+ gain: safeGet(result, 'Gain', 0),
171
+ publishDate: safeGet(result, 'PublishDate', null),
172
+ likelyVideo: likelyContainsVideo(title)
173
+ };
174
+ });
175
+
176
+ // Filter out results that don't look like they contain video content
177
+ const videoStreams = streams.filter(stream => stream.likelyVideo);
178
+ console.log(`Filtered to ${videoStreams.length} results that likely contain video content`);
179
+
180
+ // Process results
181
+ const processedStreams = await Promise.all(videoStreams.map(async (stream) => {
182
+ // If we already have a working magnet link, just process it directly
183
+ if (stream.magnetLink) {
184
+ // Try to process the magnet link directly for additional info
185
+ try {
186
+ const magnetInfo = processMagnetLink(stream.magnetLink);
187
+ if (magnetInfo) {
188
+ return {
189
+ ...stream,
190
+ infoHash: magnetInfo.infoHash || stream.infoHash,
191
+ // Use quality from title if not already detected
192
+ quality: stream.quality || magnetInfo.quality
193
+ };
194
+ }
195
+ } catch (error) {
196
+ // If direct processing fails, continue with the original stream data
197
+ console.error(`Error processing magnet link: ${error.message}`);
198
+ }
199
+ return stream;
200
+ }
201
+
202
+ // If we have a torrent link but no magnet, try to analyze the torrent
203
+ if (stream.torrentLink) {
204
+ try {
205
+ console.log(`Converting torrent to magnet for: ${stream.title}`);
206
+
207
+ // Check if torrentLink is actually a magnet URI (can happen with some indexers)
208
+ if (stream.torrentLink.startsWith('magnet:')) {
209
+ const fixedMagnetUri = fixMagnetUri(stream.torrentLink);
210
+ const magnetInfo = processMagnetLink(fixedMagnetUri);
211
+ if (magnetInfo) {
212
+ return {
213
+ ...stream,
214
+ magnetLink: fixedMagnetUri,
215
+ infoHash: magnetInfo.infoHash,
216
+ quality: magnetInfo.quality || stream.quality
217
+ };
218
+ }
219
+ } else {
220
+ // It's a real torrent URL
221
+ const torrentInfo = await analyzeTorrentFromUrl(stream.torrentLink);
222
+
223
+ if (torrentInfo) {
224
+ return {
225
+ ...stream,
226
+ magnetLink: torrentInfo.magnetLink,
227
+ filename: torrentInfo.filename,
228
+ infoHash: torrentInfo.infoHash,
229
+ mainFileSize: torrentInfo.mainFileSize || stream.mainFileSize,
230
+ quality: torrentInfo.quality || stream.quality
231
+ };
232
+ }
233
+ }
234
+ } catch (error) {
235
+ console.error(`Error analyzing torrent: ${error.message}`);
236
+
237
+ // If direct torrent analysis fails but we have an info hash, try to create a basic magnet
238
+ if (stream.infoHash) {
239
+ const basicMagnet = `magnet:?xt=urn:btih:${stream.infoHash}&dn=${encodeURIComponent(stream.title)}`;
240
+ console.log(`Created basic magnet link from info hash for: ${stream.title}`);
241
+ return {
242
+ ...stream,
243
+ magnetLink: basicMagnet
244
+ };
245
+ }
246
+ }
247
+ }
248
+
249
+ return stream;
250
+ }));
251
+
252
+ // Filter out results without magnetUri
253
+ const validStreams = processedStreams.filter(stream => stream.magnetLink);
254
+ console.log(`Found ${validStreams.length} valid streams with magnet links`);
255
+
256
+ // Sort results by quality, then seeders, then size
257
+ validStreams.sort((a, b) => {
258
+ const qualityOrder = { '2160p': 4, '4k': 4, 'uhd': 4, '1080p': 3, '720p': 2 };
259
+ const aQuality = qualityOrder[a.quality] || 0;
260
+ const bQuality = qualityOrder[b.quality] || 0;
261
+
262
+ if (aQuality !== bQuality) {
263
+ return bQuality - aQuality;
264
+ }
265
+
266
+ if (a.seeders !== b.seeders) {
267
+ return b.seeders - a.seeders;
268
+ }
269
+
270
+ return b.mainFileSize - a.mainFileSize;
271
+ });
272
+
273
+ return validStreams;
274
+ } catch (error) {
275
+ console.error(`❌ Error searching Jackett:`, error);
276
+ return [];
277
+ }
278
+ }
279
+
280
+ // Helper function to find the best torrent match based on user preferences
281
+ function findBestTorrent(torrents, preferences = {}) {
282
+ if (!Array.isArray(torrents) || torrents.length === 0) {
283
+ return null;
284
+ }
285
+
286
+ const {
287
+ minSeeders = 5,
288
+ maxSize = Infinity,
289
+ minSize = 0,
290
+ preferredQuality = '1080p',
291
+ preferredCodec = 'x265'
292
+ } = preferences || {};
293
+
294
+ // First filter by minimum seeders and size constraints
295
+ let filtered = torrents.filter(t => {
296
+ return (t.seeders || 0) >= minSeeders &&
297
+ (t.mainFileSize || 0) >= minSize &&
298
+ (t.mainFileSize || 0) <= maxSize;
299
+ });
300
+
301
+ if (filtered.length === 0) return null;
302
+
303
+ // Scoring system
304
+ const scored = filtered.map(torrent => {
305
+ let score = 0;
306
+
307
+ // Quality scoring
308
+ const qualityScores = { '2160p': 10, '4k': 10, 'uhd': 10, '1080p': 8, '720p': 5 };
309
+ score += qualityScores[torrent.quality] || 0;
310
+
311
+ // Preferred quality exact match bonus
312
+ if (torrent.quality === preferredQuality) {
313
+ score += 5;
314
+ }
315
+
316
+ // Codec scoring
317
+ const title = typeof torrent.title === 'string' ? torrent.title.toLowerCase() : '';
318
+ if (title.includes(preferredCodec.toLowerCase())) {
319
+ score += 3;
320
+ }
321
+
322
+ // Seeders scoring - logarithmic scale to avoid extremely popular torrents dominating
323
+ score += Math.min(10, Math.log10((torrent.seeders || 0) + 1) * 3);
324
+
325
+ // Size scoring - prefer middle size range
326
+ const sizeGB = (torrent.mainFileSize || 0) / (1024 * 1024 * 1024);
327
+ if (preferredQuality === '2160p' || preferredQuality === '4k') {
328
+ // For 4K content, optimal size is around 15-40GB
329
+ if (sizeGB >= 15 && sizeGB <= 40) score += 5;
330
+ else if (sizeGB > 40) score += 2;
331
+ else if (sizeGB > 8) score += 3;
332
+ } else if (preferredQuality === '1080p') {
333
+ // For 1080p content, optimal size is around 4-12GB
334
+ if (sizeGB >= 4 && sizeGB <= 12) score += 5;
335
+ else if (sizeGB > 12) score += 2;
336
+ else if (sizeGB > 2) score += 3;
337
+ } else {
338
+ // For 720p content, optimal size is around 1-4GB
339
+ if (sizeGB >= 1 && sizeGB <= 4) score += 5;
340
+ else if (sizeGB > 4) score += 2;
341
+ }
342
+
343
+ // Trusted release group bonus
344
+ const trustedGroups = ['qxr', 'tigole', 'etrg', 'yts', 'rarbg', 'framestor'];
345
+ for (const group of trustedGroups) {
346
+ if (title.includes(group)) {
347
+ score += 2;
348
+ break;
349
+ }
350
+ }
351
+
352
+ return { torrent, score };
353
+ });
354
+
355
+ // Sort by score and return the highest
356
+ scored.sort((a, b) => b.score - a.score);
357
+ return scored[0]?.torrent || null;
358
+ }
359
+
360
+ export {
361
+ sanitizeSearchQuery,
362
+ searchJackett,
363
+ findBestTorrent
364
+ };
magnet-fix.js ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Fixes malformed magnet URIs that start with "magnet:/?" instead of "magnet:?"
3
+ * This is a common issue with some trackers and Jackett's responses
4
+ *
5
+ * @param {string} magnetUri - The potentially malformed magnet URI
6
+ * @returns {string} - Properly formatted magnet URI
7
+ */
8
+ function fixMagnetUri(magnetUri) {
9
+ if (!magnetUri) return magnetUri;
10
+
11
+ // Check for the incorrect format and fix it
12
+ if (magnetUri.startsWith('magnet:/?')) {
13
+ return magnetUri.replace('magnet:/?', 'magnet:?');
14
+ }
15
+
16
+ return magnetUri;
17
+ }
18
+
19
+ /**
20
+ * Processes a magnet link directly without using read-torrent
21
+ * Extracts info hash and other useful information from the magnet URI
22
+ *
23
+ * @param {string} magnetUri - The magnet URI to process
24
+ * @returns {Object|null} - Object containing parsed magnet information or null if invalid
25
+ */
26
+ function processMagnetLink(magnetUri) {
27
+ if (!magnetUri) return null;
28
+
29
+ // Fix the URI if needed
30
+ magnetUri = fixMagnetUri(magnetUri);
31
+
32
+ try {
33
+ // Extract info hash (should be after xt=urn:btih:)
34
+ const infoHashMatch = magnetUri.match(/xt=urn:btih:([a-zA-Z0-9]+)/i);
35
+ if (!infoHashMatch || !infoHashMatch[1]) return null;
36
+
37
+ const infoHash = infoHashMatch[1].toLowerCase();
38
+
39
+ // Extract name (after dn=)
40
+ const nameMatch = magnetUri.match(/dn=([^&]+)/i);
41
+ const name = nameMatch ? decodeURIComponent(nameMatch[1]) : null;
42
+
43
+ // Extract trackers (multiple tr= parameters)
44
+ const trackerMatches = magnetUri.matchAll(/tr=([^&]+)/gi);
45
+ const trackers = [];
46
+ for (const match of trackerMatches) {
47
+ if (match[1]) {
48
+ trackers.push(decodeURIComponent(match[1]));
49
+ }
50
+ }
51
+
52
+ return {
53
+ magnetLink: magnetUri,
54
+ infoHash,
55
+ name,
56
+ trackers,
57
+ // Make a guess at quality based on name
58
+ quality: name ? extractQualityFromTitle(name) : null
59
+ };
60
+ } catch (error) {
61
+ console.error('Error processing magnet link:', error);
62
+ return null;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Extracts video quality information from a title string
68
+ * @param {string} title - The title to analyze
69
+ * @returns {string|null} - Quality identifier or null if none found
70
+ */
71
+ function extractQualityFromTitle(title) {
72
+ if (!title) return null;
73
+
74
+ const lowerTitle = title.toLowerCase();
75
+
76
+ // Check for common quality indicators
77
+ if (lowerTitle.includes('2160p') || lowerTitle.includes('4k') || lowerTitle.includes('uhd')) {
78
+ return '2160p';
79
+ } else if (lowerTitle.includes('1080p') || lowerTitle.includes('fhd')) {
80
+ return '1080p';
81
+ } else if (lowerTitle.includes('720p') || lowerTitle.includes('hd')) {
82
+ return '720p';
83
+ } else if (lowerTitle.includes('480p')) {
84
+ return '480p';
85
+ }
86
+
87
+ return null;
88
+ }
89
+
90
+ /**
91
+ * Makes a best guess at whether a torrent contains video content based on title
92
+ * @param {string} title - Torrent title
93
+ * @returns {boolean} - True if likely contains video
94
+ */
95
+ function likelyContainsVideo(title) {
96
+ if (!title) return false;
97
+
98
+ const lowerTitle = title.toLowerCase();
99
+
100
+ // Check for common video file extensions
101
+ const videoExtensions = ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.m4v'];
102
+ if (videoExtensions.some(ext => lowerTitle.includes(ext))) {
103
+ return true;
104
+ }
105
+
106
+ // Check for quality indicators
107
+ if (/\b(2160p|1080p|720p|480p|4k|uhd|hd)\b/i.test(lowerTitle)) {
108
+ return true;
109
+ }
110
+
111
+ // Check for common encoding terms
112
+ if (/\b(x264|x265|h264|h265|hevc|avc|xvid|divx)\b/i.test(lowerTitle)) {
113
+ return true;
114
+ }
115
+
116
+ // Check for release group patterns
117
+ if (/\b(bluray|web-dl|webrip|bdrip|dvdrip)\b/i.test(lowerTitle)) {
118
+ return true;
119
+ }
120
+
121
+ return false;
122
+ }
123
+
124
+ export {
125
+ fixMagnetUri,
126
+ processMagnetLink,
127
+ extractQualityFromTitle,
128
+ likelyContainsVideo
129
+ };
package.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "torrent-api",
3
+ "version": "1.0.0",
4
+ "description": "API server for searching torrents with TMDB integration",
5
+ "main": "server.js",
6
+ "type": "module",
7
+ "scripts": {
8
+ "start": "node server-with-jackett.js",
9
+ "dev": "nodemon server-with-jackett.js"
10
+ },
11
+ "dependencies": {
12
+ "express": "^4.18.2",
13
+ "node-fetch": "^3.3.2",
14
+ "read-torrent": "^1.3.1",
15
+ "xml2js": "^0.6.2"
16
+ },
17
+ "devDependencies": {
18
+ "nodemon": "^3.0.2"
19
+ },
20
+ "engines": {
21
+ "node": ">=18.0.0"
22
+ },
23
+ "private": true
24
+ }
server-with-jackett.js ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from 'express';
2
+ import { searchJackett, findBestTorrent } from './jackett.js';
3
+ import path from 'path';
4
+ import { fileURLToPath } from 'url';
5
+ import { analyzeTorrentFromUrl } from './torrent-utils.js';
6
+ import { fixMagnetUri, processMagnetLink } from './magnet-fix.js';
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = path.dirname(__filename);
10
+
11
+ const app = express();
12
+ const port = process.env.PORT || 7006;
13
+ const TMDB_API_KEY = 'f051e7366c6105ad4f9aafe4733d9dae';
14
+ const TMDB_BASE_URL = 'https://api.themoviedb.org/3';
15
+
16
+ // Jackett configuration
17
+ const JACKETT_CONFIG = {
18
+ apiKey: 'yiwsudq0qv16vtdjmeru6ohi26h2yr7i',
19
+ baseUrl: 'http://163.172.89.194:9117',
20
+ trackers: ['therarbg'] // Specify the trackers you want to search
21
+ };
22
+ //http://163.172.89.194:9117/jackett/api/v2.0/indexers/all/results?apikey=yiwsudq0qv16vtdjmeru6ohi26h2yr7i&Query=bad%20boys%20ride%20or%20die&Tracker%5B%5D=therarbg&_=1745251669649
23
+ app.use(express.json());
24
+ app.use(express.static(path.join(__dirname, 'public')));
25
+
26
+ function standardizeEpisodeFormat(query) {
27
+ // Handle 1x01 format
28
+ const altMatch = query.match(/^(.*?)(\d{1,2})x(\d{1,2})/i);
29
+ if (altMatch) {
30
+ const [_, title, season, episode] = altMatch;
31
+ const paddedSeason = String(season).padStart(2, '0');
32
+ const paddedEpisode = String(episode).padStart(2, '0');
33
+ return `${title.trim()} S${paddedSeason}E${paddedEpisode}`;
34
+ }
35
+ return query;
36
+ }
37
+
38
+ function normalizeTitle(title) {
39
+ return title.toLowerCase()
40
+ .replace(/[^a-z0-9\s]/g, '')
41
+ .replace(/\s+/g, ' ')
42
+ .trim();
43
+ }
44
+
45
+ function isExactEpisodeMatch(torrentTitle, showTitle, seasonNum, episodeNum) {
46
+ if (!torrentTitle || !showTitle) return false;
47
+
48
+ // Remove HTML tags and clean up title
49
+ torrentTitle = torrentTitle.replace(/<[^>]*>/g, '')
50
+ .replace(/\[.*?\]/g, '') // Remove bracketed content
51
+ .replace(/\(.*?\)/g, '') // Remove parenthetical content
52
+ .replace(/\s+/g, ' ')
53
+ .trim();
54
+
55
+ // Normalize the titles for comparison
56
+ const normalizedTorrentTitle = torrentTitle.toLowerCase();
57
+
58
+ // Also normalize show title to remove special characters
59
+ const normalizedShowTitle = showTitle.toLowerCase()
60
+ .replace(/[^\w\s]/g, ' ') // Replace special chars with spaces
61
+ .replace(/\s+/g, ' ') // Replace multiple spaces with one
62
+ .trim();
63
+
64
+ // Split show title into significant words
65
+ const showWords = normalizedShowTitle.split(' ')
66
+ .filter(word => word.length > 2)
67
+ .filter(word => !['the', 'and', 'or', 'in', 'on', 'at', 'to'].includes(word));
68
+
69
+ const hasAllShowWords = showWords.every(word =>
70
+ normalizedTorrentTitle.includes(word)
71
+ );
72
+
73
+ if (!hasAllShowWords) return false;
74
+
75
+ // Format season and episode numbers
76
+ const seasonStr = String(seasonNum).padStart(2, '0');
77
+ const episodeStr = String(episodeNum).padStart(2, '0');
78
+
79
+ // Common episode patterns
80
+ const patterns = [
81
+ new RegExp(`s${seasonStr}e${episodeStr}`, 'i'), // S01E01
82
+ new RegExp(`${seasonNum}x${episodeStr}`, 'i'), // 1x01
83
+ new RegExp(`[^0-9]${seasonNum}${episodeStr}[^0-9]`, 'i'), // 101
84
+ new RegExp(`season\\s*${seasonNum}\\s*episode\\s*${episodeNum}`, 'i'), // Season 1 Episode 1
85
+ new RegExp(`s${seasonStr}\\.?e${episodeStr}`, 'i'), // S01.E01
86
+ new RegExp(`${seasonStr}${episodeStr}`, 'i'), // 0101
87
+ new RegExp(`^${seasonNum}${episodeStr}\\s`, 'i'), // 101 at start
88
+ new RegExp(`\\s${seasonNum}${episodeStr}$`, 'i'), // 101 at end
89
+ new RegExp(`episode\\s*${episodeNum}`, 'i') // Just episode number if title matches
90
+ ];
91
+
92
+ return patterns.some(pattern => pattern.test(normalizedTorrentTitle));
93
+ }
94
+
95
+ function isExactMovieMatch(torrentTitle, movieTitle, year) {
96
+ if (!torrentTitle || !movieTitle) return false;
97
+
98
+ // Remove HTML tags and clean title
99
+ torrentTitle = torrentTitle.replace(/<[^>]*>/g, '')
100
+ .replace(/\[.*?\]/g, '') // Remove bracketed content
101
+ .replace(/\(.*?\)/g, '') // Remove parenthetical content
102
+ .replace(/\s+/g, ' ')
103
+ .trim();
104
+
105
+ // Normalize for comparison
106
+ const normalizedTorrentTitle = torrentTitle.toLowerCase();
107
+
108
+ // Important: Normalize movie title by removing special characters
109
+ const normalizedMovieTitle = movieTitle.toLowerCase()
110
+ .replace(/[^\w\s]/g, ' ') // Replace special chars with spaces
111
+ .replace(/\s+/g, ' ') // Replace multiple spaces with one
112
+ .trim();
113
+
114
+ // Split movie title into significant words and check if all are present
115
+ const movieWords = normalizedMovieTitle.split(' ')
116
+ .filter(word => word.length > 2)
117
+ .filter(word => !['the', 'and', 'or', 'in', 'on', 'at', 'to'].includes(word));
118
+
119
+ const hasAllMovieWords = movieWords.every(word =>
120
+ normalizedTorrentTitle.includes(word)
121
+ );
122
+
123
+ if (!hasAllMovieWords) return false;
124
+
125
+ // Check year
126
+ const yearMatch = torrentTitle.match(/(?:19|20)\d{2}/);
127
+ return yearMatch && yearMatch[0] === year.toString();
128
+ }
129
+
130
+ async function getTMDBDetails(tmdbId, type = 'movie') {
131
+ try {
132
+ const response = await fetch(`${TMDB_BASE_URL}/${type}/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`);
133
+ if (!response.ok) throw new Error(`TMDB API error: ${response.status}`);
134
+ return await response.json();
135
+ } catch (error) {
136
+ console.error('TMDB fetch error:', error);
137
+ return null;
138
+ }
139
+ }
140
+
141
+ async function getTVShowDetails(tmdbId, seasonNum, episodeNum) {
142
+ try {
143
+ // Get basic show info
144
+ const showResponse = await fetch(
145
+ `${TMDB_BASE_URL}/tv/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`
146
+ );
147
+ if (!showResponse.ok) throw new Error(`TMDB API error: ${showResponse.status}`);
148
+ const showData = await showResponse.json();
149
+
150
+ // Get specific episode info
151
+ const episodeResponse = await fetch(
152
+ `${TMDB_BASE_URL}/tv/${tmdbId}/season/${seasonNum}/episode/${episodeNum}?api_key=${TMDB_API_KEY}`
153
+ );
154
+ if (!episodeResponse.ok) throw new Error(`TMDB API error: ${episodeResponse.status}`);
155
+ const episodeData = await episodeResponse.json();
156
+
157
+ return {
158
+ showTitle: showData.name,
159
+ episodeTitle: episodeData.name,
160
+ seasonNumber: seasonNum,
161
+ episodeNumber: episodeNum,
162
+ airDate: episodeData.air_date,
163
+ imdbId: showData.external_ids?.imdb_id
164
+ };
165
+ } catch (error) {
166
+ console.error('TMDB fetch error:', error);
167
+ return null;
168
+ }
169
+ }
170
+
171
+ async function handleSearch({ query, type, trackers = null }) {
172
+ if (!query) throw new Error('Missing required parameter: query');
173
+ if (!['movie', 'series'].includes(type)) throw new Error('Invalid type. Must be either "movie" or "series"');
174
+
175
+ let searchQuery = query;
176
+ let exactMatchParams = {};
177
+ let tmdbData = null;
178
+
179
+ if (type === 'series') {
180
+ // Handle TMDB ID format: "tmdb:12345:1:1" (show_id:season:episode)
181
+ const tmdbMatch = query.match(/^tmdb:(\d+):(\d+):(\d+)$/);
182
+ if (tmdbMatch) {
183
+ const [_, tmdbId, seasonNum, episodeNum] = tmdbMatch;
184
+ tmdbData = await getTVShowDetails(tmdbId, parseInt(seasonNum), parseInt(episodeNum));
185
+ if (tmdbData) {
186
+ exactMatchParams = {
187
+ title: tmdbData.showTitle,
188
+ season: parseInt(seasonNum),
189
+ episode: parseInt(episodeNum)
190
+ };
191
+
192
+ // Use standard format for search
193
+ searchQuery = `${tmdbData.showTitle} S${String(seasonNum).padStart(2, '0')}E${String(episodeNum).padStart(2, '0')}`;
194
+ }
195
+ }
196
+ // Handle IMDB ID format: "tt1234567:1:1" (imdb_id:season:episode)
197
+ else if (query.startsWith('tt')) {
198
+ const imdbMatch = query.match(/^(tt\d+):(\d+):(\d+)$/);
199
+ if (imdbMatch) {
200
+ const [_, imdbId, seasonNum, episodeNum] = imdbMatch;
201
+ // First get TMDB ID from IMDB ID
202
+ const findResponse = await fetch(
203
+ `${TMDB_BASE_URL}/find/${imdbId}?api_key=${TMDB_API_KEY}&external_source=imdb_id`
204
+ );
205
+ if (findResponse.ok) {
206
+ const findData = await findResponse.json();
207
+ if (findData.tv_results && findData.tv_results[0]) {
208
+ const tmdbId = findData.tv_results[0].id;
209
+ tmdbData = await getTVShowDetails(tmdbId, parseInt(seasonNum), parseInt(episodeNum));
210
+ if (tmdbData) {
211
+ exactMatchParams = {
212
+ title: tmdbData.showTitle,
213
+ season: parseInt(seasonNum),
214
+ episode: parseInt(episodeNum)
215
+ };
216
+ searchQuery = `${tmdbData.showTitle} S${String(seasonNum).padStart(2, '0')}E${String(episodeNum).padStart(2, '0')}`;
217
+ }
218
+ }
219
+ }
220
+ }
221
+ }
222
+ // Handle text formats
223
+ else {
224
+ // Convert 1x01 format to S01E01
225
+ searchQuery = standardizeEpisodeFormat(query);
226
+
227
+ // Try to extract season/episode info
228
+ const seasonEpisodeMatch = searchQuery.match(/^(.*?)S(\d{1,2})E(\d{1,2})/i);
229
+ if (seasonEpisodeMatch) {
230
+ exactMatchParams = {
231
+ title: seasonEpisodeMatch[1].trim(),
232
+ season: parseInt(seasonEpisodeMatch[2]),
233
+ episode: parseInt(seasonEpisodeMatch[3])
234
+ };
235
+ }
236
+ }
237
+ } else if (type === 'movie') {
238
+ // Handle TMDB ID format
239
+ if (query.startsWith('tmdb:')) {
240
+ const tmdbId = query.replace('tmdb:', '');
241
+ tmdbData = await getTMDBDetails(tmdbId, 'movie');
242
+ if (tmdbData) {
243
+ exactMatchParams = {
244
+ title: tmdbData.title,
245
+ year: new Date(tmdbData.release_date).getFullYear()
246
+ };
247
+ searchQuery = `${tmdbData.title} ${exactMatchParams.year}`;
248
+ }
249
+ }
250
+ // Handle IMDB ID format
251
+ else if (query.startsWith('tt')) {
252
+ const findResponse = await fetch(
253
+ `${TMDB_BASE_URL}/find/${query}?api_key=${TMDB_API_KEY}&external_source=imdb_id`
254
+ );
255
+ if (findResponse.ok) {
256
+ const findData = await findResponse.json();
257
+ if (findData.movie_results && findData.movie_results[0]) {
258
+ tmdbData = findData.movie_results[0];
259
+ exactMatchParams = {
260
+ title: tmdbData.title,
261
+ year: new Date(tmdbData.release_date).getFullYear()
262
+ };
263
+ searchQuery = `${tmdbData.title} ${exactMatchParams.year}`;
264
+ }
265
+ }
266
+ }
267
+ // Handle text format with year
268
+ else {
269
+ const movieYearMatch = query.match(/^(.+?)(?:\s+|$)(\d{4})$/);
270
+ if (movieYearMatch) {
271
+ exactMatchParams = {
272
+ title: movieYearMatch[1].trim(),
273
+ year: parseInt(movieYearMatch[2])
274
+ };
275
+ }
276
+ }
277
+ }
278
+
279
+ // Create a config with custom trackers if specified
280
+ const jackettConfig = {...JACKETT_CONFIG};
281
+ if (trackers && Array.isArray(trackers) && trackers.length > 0) {
282
+ jackettConfig.trackers = trackers;
283
+ }
284
+
285
+ // Search through Jackett
286
+ const jackettResults = await searchJackett(searchQuery, jackettConfig, type);
287
+
288
+ // Filter results based on exact match parameters
289
+ let filteredResults = [...jackettResults];
290
+
291
+ if (type === 'series' && exactMatchParams.season !== undefined) {
292
+ filteredResults = filteredResults.filter(result =>
293
+ isExactEpisodeMatch(
294
+ result.title || result.name,
295
+ exactMatchParams.title,
296
+ exactMatchParams.season,
297
+ exactMatchParams.episode
298
+ )
299
+ );
300
+ } else if (type === 'movie' && exactMatchParams.year) {
301
+ filteredResults = filteredResults.filter(result =>
302
+ isExactMovieMatch(
303
+ result.title || result.name,
304
+ exactMatchParams.title,
305
+ exactMatchParams.year
306
+ )
307
+ );
308
+ }
309
+
310
+ // Sort results by quality, seeders, and size
311
+ filteredResults.sort((a, b) => {
312
+ const qualityOrder = { '2160p': 4, '4k': 4, 'uhd': 4, '1080p': 3, '720p': 2 };
313
+ const aQuality = qualityOrder[a.quality] || 0;
314
+ const bQuality = qualityOrder[b.quality] || 0;
315
+
316
+ if (aQuality !== bQuality) {
317
+ return bQuality - aQuality;
318
+ }
319
+
320
+ // Next, sort by seeders
321
+ const seedersA = a.seeders || 0;
322
+ const seedersB = b.seeders || 0;
323
+ if (seedersA !== seedersB) {
324
+ return seedersB - seedersA;
325
+ }
326
+
327
+ // Finally, sort by size (prefer larger files within same quality tier)
328
+ const sizeA = a.mainFileSize || 0;
329
+ const sizeB = b.mainFileSize || 0;
330
+ return sizeB - sizeA;
331
+ });
332
+
333
+ // Find the best torrent based on preferences
334
+ const bestTorrent = findBestTorrent(filteredResults, {
335
+ minSeeders: 3,
336
+ maxSize: 30 * 1024 * 1024 * 1024, // 30GB max
337
+ minSize: type === 'movie' ? 1 * 1024 * 1024 * 1024 : 100 * 1024 * 1024, // 1GB for movies, 100MB for TV
338
+ preferredQuality: '1080p',
339
+ preferredCodec: 'x265' // Prefer HEVC/x265 for better compression
340
+ });
341
+
342
+ return {
343
+ query: searchQuery,
344
+ originalQuery: query,
345
+ type,
346
+ tmdbData,
347
+ results: filteredResults.map(result => ({
348
+ title: result.title,
349
+ filename: result.filename,
350
+ quality: result.quality,
351
+ size: result.size,
352
+ seeders: result.seeders,
353
+ leechers: result.leechers,
354
+ magnetLink: result.magnetLink,
355
+ source: result.source || 'Unknown',
356
+ bestMatch: bestTorrent && (result.infoHash === bestTorrent.infoHash ||
357
+ result.title === bestTorrent.title)
358
+ }))
359
+ };
360
+ }
361
+
362
+ app.get('/api/search', async (req, res) => {
363
+ try {
364
+ // Parse trackers if provided
365
+ let trackers = null;
366
+ if (req.query.trackers) {
367
+ try {
368
+ trackers = req.query.trackers.split(',').map(t => t.trim());
369
+ } catch (e) {
370
+ console.warn('Invalid trackers parameter:', e);
371
+ }
372
+ }
373
+
374
+ const result = await handleSearch({
375
+ query: req.query.query,
376
+ type: req.query.type,
377
+ trackers
378
+ });
379
+ res.json(result);
380
+ } catch (error) {
381
+ res.status(500).json({ error: 'Internal server error', message: error.message });
382
+ }
383
+ });
384
+
385
+ app.post('/api/search', async (req, res) => {
386
+ try {
387
+ const result = await handleSearch({
388
+ query: req.body.query,
389
+ type: req.body.type,
390
+ trackers: req.body.trackers
391
+ });
392
+ res.json(result);
393
+ } catch (error) {
394
+ res.status(500).json({ error: 'Internal server error', message: error.message });
395
+ }
396
+ });
397
+
398
+ // API endpoint to analyze a torrent file or magnet link directly
399
+ app.get('/api/analyze-torrent', async (req, res) => {
400
+ try {
401
+ const url = req.query.url;
402
+ if (!url) {
403
+ return res.status(400).json({
404
+ error: 'Bad request',
405
+ message: 'Missing required parameter: url'
406
+ });
407
+ }
408
+
409
+ // Check if it's a magnet link
410
+ if (url.startsWith('magnet:')) {
411
+ // Fix and process the magnet link immediately
412
+ const fixedMagnetLink = fixMagnetUri(url);
413
+ const magnetInfo = processMagnetLink(fixedMagnetLink);
414
+
415
+ if (magnetInfo) {
416
+ return res.json({
417
+ magnetLink: fixedMagnetLink,
418
+ infoHash: magnetInfo.infoHash,
419
+ name: magnetInfo.name,
420
+ quality: magnetInfo.quality,
421
+ isMagnetOnly: true
422
+ });
423
+ } else {
424
+ return res.status(400).json({
425
+ error: 'Invalid magnet link',
426
+ message: 'Could not process the magnet link'
427
+ });
428
+ }
429
+ }
430
+
431
+ // Analyze the torrent file
432
+ const result = await analyzeTorrentFromUrl(url);
433
+
434
+ if (!result) {
435
+ return res.status(404).json({
436
+ error: 'Not found',
437
+ message: 'Could not analyze the torrent or no video files found'
438
+ });
439
+ }
440
+
441
+ res.json(result);
442
+ } catch (error) {
443
+ console.error('Error analyzing torrent:', error);
444
+ res.status(500).json({
445
+ error: 'Internal server error',
446
+ message: error.message
447
+ });
448
+ }
449
+ });
450
+
451
+ // Fallback route to fix magnet links
452
+ app.get('/api/fix-magnet', (req, res) => {
453
+ const magnetUri = req.query.magnet;
454
+
455
+ if (!magnetUri) {
456
+ return res.status(400).json({
457
+ error: 'Bad request',
458
+ message: 'Missing required parameter: magnet'
459
+ });
460
+ }
461
+
462
+ try {
463
+ const fixedMagnetUri = fixMagnetUri(magnetUri);
464
+ const magnetInfo = processMagnetLink(fixedMagnetUri);
465
+
466
+ if (!magnetInfo) {
467
+ return res.status(400).json({
468
+ error: 'Invalid magnet link',
469
+ message: 'Could not process the magnet link'
470
+ });
471
+ }
472
+
473
+ res.json({
474
+ original: magnetUri,
475
+ fixed: fixedMagnetUri,
476
+ infoHash: magnetInfo.infoHash,
477
+ name: magnetInfo.name,
478
+ trackers: magnetInfo.trackers
479
+ });
480
+ } catch (error) {
481
+ res.status(500).json({
482
+ error: 'Internal server error',
483
+ message: error.message
484
+ });
485
+ }
486
+ });
487
+
488
+ // Serve the frontend
489
+ app.get('/', (req, res) => {
490
+ res.sendFile(path.join(__dirname, 'public', 'index.html'));
491
+ });
492
+
493
+ app.listen(port, () => {
494
+ console.log(`Server running at http://localhost:${port}`);
495
+ console.log(`Jackett integration: ${JACKETT_CONFIG.baseUrl}`);
496
+ if (!TMDB_API_KEY) {
497
+ console.warn('Warning: TMDB_API_KEY not set. TMDB features will not work.');
498
+ }
499
+ });
torrent-utils.js ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // torrent-utils.js - Utility functions for torrent verification and processing
2
+ import readTorrent from 'read-torrent';
3
+ import { promisify } from 'util';
4
+ import { fixMagnetUri, processMagnetLink } from './magnet-fix.js';
5
+
6
+ const readTorrentPromise = promisify(readTorrent);
7
+
8
+ // Video file extensions we consider valid
9
+ const VIDEO_EXTENSIONS = [
10
+ '.mp4', '.mkv', '.avi', '.mov', '.wmv', '.m4v', '.flv', '.webm',
11
+ '.mpg', '.mpeg', '.ts', '.m2ts', '.vob'
12
+ ];
13
+
14
+ /**
15
+ * Checks if a file is a recognized video format
16
+ * @param {string} filePath - Path or filename to check
17
+ * @returns {boolean} - True if the file has a video extension
18
+ */
19
+ function isVideoFile(filePath) {
20
+ if (!filePath) return false;
21
+ const lowercasePath = filePath.toLowerCase();
22
+ return VIDEO_EXTENSIONS.some(ext => lowercasePath.endsWith(ext));
23
+ }
24
+
25
+ /**
26
+ * Finds the main video file in a list of files (typically the largest video)
27
+ * @param {Array} files - Array of files from a torrent
28
+ * @returns {Object|null} - The main video file object or null if none found
29
+ */
30
+ function findMainVideoFile(files) {
31
+ if (!files || !Array.isArray(files) || files.length === 0) {
32
+ return null;
33
+ }
34
+
35
+ // Filter to only video files
36
+ const videoFiles = files.filter(file => {
37
+ const filePath = Array.isArray(file.path) ? file.path.join('/') : file.path;
38
+ return isVideoFile(filePath);
39
+ });
40
+
41
+ if (videoFiles.length === 0) {
42
+ return null;
43
+ }
44
+
45
+ // Sort by size (largest first) and return the largest
46
+ videoFiles.sort((a, b) => b.length - a.length);
47
+ return videoFiles[0];
48
+ }
49
+
50
+ /**
51
+ * Checks if a torrent contains video content
52
+ * @param {Object} torrentInfo - The parsed torrent object
53
+ * @returns {boolean} - True if the torrent contains video files
54
+ */
55
+ function containsVideoContent(torrentInfo) {
56
+ if (!torrentInfo || !torrentInfo.files || !Array.isArray(torrentInfo.files)) {
57
+ return false;
58
+ }
59
+
60
+ return torrentInfo.files.some(file => {
61
+ const filePath = Array.isArray(file.path) ? file.path.join('/') : file.path;
62
+ return isVideoFile(filePath);
63
+ });
64
+ }
65
+
66
+ /**
67
+ * Estimates video quality based on file size and name
68
+ * @param {string} fileName - Name of the video file
69
+ * @param {number} fileSize - Size of the file in bytes
70
+ * @returns {string} - Estimated quality (4K, 1080p, 720p, etc.)
71
+ */
72
+ function estimateQuality(fileName, fileSize) {
73
+ if (!fileName) return null;
74
+
75
+ // First, check for explicit quality markers in the filename
76
+ const lowerName = fileName.toLowerCase();
77
+ if (lowerName.includes('2160p') || lowerName.includes('4k') || lowerName.includes('uhd')) {
78
+ return '2160p';
79
+ } else if (lowerName.includes('1080p') || lowerName.includes('fhd')) {
80
+ return '1080p';
81
+ } else if (lowerName.includes('720p') || lowerName.includes('hd')) {
82
+ return '720p';
83
+ } else if (lowerName.includes('480p')) {
84
+ return '480p';
85
+ }
86
+
87
+ // If no explicit marker, estimate based on file size
88
+ if (fileSize) {
89
+ const sizeGB = fileSize / (1024 * 1024 * 1024);
90
+
91
+ if (sizeGB > 20) {
92
+ return '2160p'; // Very large files are likely 4K
93
+ } else if (sizeGB > 4) {
94
+ return '1080p'; // Large files are likely 1080p
95
+ } else if (sizeGB > 1.5) {
96
+ return '720p'; // Medium files are likely 720p
97
+ } else {
98
+ return '480p'; // Small files are likely SD
99
+ }
100
+ }
101
+
102
+ return null; // Can't determine quality
103
+ }
104
+
105
+ /**
106
+ * Extracts a magnet link from a torrent object
107
+ * @param {Object} torrentInfo - The parsed torrent information
108
+ * @returns {string|null} - Magnet URI or null if not possible
109
+ */
110
+ function createMagnetLink(torrentInfo) {
111
+ if (!torrentInfo || !torrentInfo.infoHash) {
112
+ return null;
113
+ }
114
+
115
+ let magnetUri = `magnet:?xt=urn:btih:${torrentInfo.infoHash}`;
116
+
117
+ // Add name if available
118
+ if (torrentInfo.name) {
119
+ magnetUri += `&dn=${encodeURIComponent(torrentInfo.name)}`;
120
+ }
121
+
122
+ // Add trackers if available
123
+ if (torrentInfo.announce && Array.isArray(torrentInfo.announce)) {
124
+ torrentInfo.announce.forEach(tracker => {
125
+ magnetUri += `&tr=${encodeURIComponent(tracker)}`;
126
+ });
127
+ }
128
+
129
+ return magnetUri;
130
+ }
131
+
132
+ /**
133
+ * Extract a magnet URI from an error message if possible
134
+ * @param {Error} error - The error potentially containing a magnet URI
135
+ * @returns {string|null} - Extracted magnet URI or null if not found
136
+ */
137
+ function extractMagnetFromError(error) {
138
+ if (!error || !error.message) return null;
139
+
140
+ // Look for a magnet URI pattern in the error message
141
+ const magnetMatch = error.message.match(/(magnet:\/?[^"'\s]+)/i);
142
+ if (magnetMatch && magnetMatch[1]) {
143
+ return magnetMatch[1];
144
+ }
145
+
146
+ return null;
147
+ }
148
+
149
+ /**
150
+ * Extract possible magnet link or info hash from URL or filename
151
+ * @param {string} url - URL or filename to analyze
152
+ * @returns {Object|null} - Object with extracted info or null
153
+ */
154
+ function extractTorrentInfoFromString(url) {
155
+ if (!url) return null;
156
+
157
+ // Try to extract info hash from URL or filename
158
+ const infoHashMatch = url.match(/([a-fA-F0-9]{40})/);
159
+ if (infoHashMatch) {
160
+ const infoHash = infoHashMatch[1].toLowerCase();
161
+ const name = url.split('/').pop().replace(/\.[^.]+$/, ''); // Extract filename without extension
162
+
163
+ // Create a basic magnet link with the info hash
164
+ const magnetUri = `magnet:?xt=urn:btih:${infoHash}&dn=${encodeURIComponent(name)}`;
165
+
166
+ return {
167
+ magnetLink: magnetUri,
168
+ infoHash: infoHash,
169
+ name: name,
170
+ quality: estimateQuality(name, 0)
171
+ };
172
+ }
173
+
174
+ // Extract any magnet link in the URL
175
+ const magnetMatch = url.match(/(magnet:[^"'\s]+)/i);
176
+ if (magnetMatch) {
177
+ const magnetUri = fixMagnetUri(magnetMatch[1]);
178
+ const magnetInfo = processMagnetLink(magnetUri);
179
+ if (magnetInfo) {
180
+ return {
181
+ magnetLink: magnetUri,
182
+ infoHash: magnetInfo.infoHash,
183
+ name: magnetInfo.name,
184
+ quality: magnetInfo.quality
185
+ };
186
+ }
187
+ }
188
+
189
+ // Just extract the filename as a fallback
190
+ const filename = url.split('/').pop();
191
+ return {
192
+ magnetLink: null,
193
+ infoHash: null,
194
+ name: filename,
195
+ filename: filename,
196
+ quality: estimateQuality(filename, 0)
197
+ };
198
+ }
199
+
200
+ /**
201
+ * Try to download a torrent with retries
202
+ * @param {string} url - URL to torrent file
203
+ * @param {number} maxRetries - Maximum number of retry attempts
204
+ * @param {number} timeout - Timeout for each attempt
205
+ * @returns {Object|null} - Torrent info or null if failed
206
+ */
207
+ async function downloadTorrentWithRetry(url, maxRetries = 2, timeout = 10000) {
208
+ const options = {
209
+ headers: {
210
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
211
+ 'Accept': '*/*',
212
+ 'Accept-Language': 'en-US,en;q=0.9',
213
+ 'Cache-Control': 'no-cache',
214
+ 'Pragma': 'no-cache'
215
+ },
216
+ timeout: timeout // Timeout to prevent hanging
217
+ };
218
+
219
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
220
+ try {
221
+ console.log(`Attempt ${attempt + 1}/${maxRetries} to download torrent from ${url}`);
222
+ return await readTorrentPromise(url, options);
223
+ } catch (error) {
224
+ console.error(`Attempt ${attempt + 1}/${maxRetries} failed:`, error.message);
225
+
226
+ // Check if the error contains a magnet URI
227
+ const magnetUri = extractMagnetFromError(error);
228
+ if (magnetUri) {
229
+ console.log('Found magnet URI in error, will process it directly');
230
+ // Return special value to indicate magnet was found
231
+ return { _isMagnetFromError: true, magnetUri: magnetUri };
232
+ }
233
+
234
+ // If this is the last attempt, throw the error
235
+ if (attempt === maxRetries - 1) {
236
+ throw error;
237
+ }
238
+
239
+ // Wait before next retry (exponential backoff)
240
+ const backoffTime = 1000 * Math.pow(2, attempt);
241
+ console.log(`Waiting ${backoffTime}ms before next attempt...`);
242
+ await new Promise(resolve => setTimeout(resolve, backoffTime));
243
+ }
244
+ }
245
+
246
+ // Should never reach here, but just in case
247
+ throw new Error('Failed to download torrent after all retries');
248
+ }
249
+
250
+ /**
251
+ * Downloads and analyzes a torrent file from URL with timeout protection
252
+ * @param {string} url - URL to the torrent file
253
+ * @param {number} globalTimeout - Overall timeout for the entire operation
254
+ * @returns {Object|null} - Processed torrent info or null if invalid
255
+ */
256
+ async function analyzeTorrentFromUrl(url, globalTimeout = 30000) {
257
+ // Create a promise that rejects after the timeout
258
+ const timeoutPromise = new Promise((_, reject) => {
259
+ const id = setTimeout(() => {
260
+ clearTimeout(id);
261
+ reject(new Error('Operation timed out after ' + globalTimeout + 'ms'));
262
+ }, globalTimeout);
263
+ });
264
+
265
+ try {
266
+ // Race the actual operation against the timeout
267
+ return await Promise.race([
268
+ _analyzeTorrentFromUrl(url),
269
+ timeoutPromise
270
+ ]);
271
+ } catch (error) {
272
+ console.error('Torrent analysis failed with timeout or other error:', error.message);
273
+
274
+ // Try to extract basic info from the URL as a fallback
275
+ return extractTorrentInfoFromString(url);
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Core implementation of torrent analysis logic
281
+ * @private
282
+ */
283
+ async function _analyzeTorrentFromUrl(url) {
284
+ try {
285
+ console.log('Analyzing torrent from:', url);
286
+
287
+ // FIRST check if the URL is a magnet link and handle it directly
288
+ if (url.startsWith('magnet:')) {
289
+ console.log('URL is a magnet link, fixing if needed and processing directly');
290
+ const fixedMagnetUri = fixMagnetUri(url); // Fix it first
291
+
292
+ // Process the fixed magnet URI
293
+ const magnetInfo = processMagnetLink(fixedMagnetUri);
294
+ if (magnetInfo) {
295
+ return {
296
+ magnetLink: fixedMagnetUri,
297
+ infoHash: magnetInfo.infoHash,
298
+ name: magnetInfo.name,
299
+ filename: magnetInfo.name,
300
+ mainFileSize: 0, // We don't know the size from just the magnet link
301
+ quality: estimateQuality(magnetInfo.name, 0)
302
+ };
303
+ }
304
+
305
+ console.log('Failed to extract valid info from magnet link');
306
+ return null;
307
+ }
308
+
309
+ // For actual torrent file URLs, try to download with retry logic
310
+ try {
311
+ const torrentResult = await downloadTorrentWithRetry(url);
312
+
313
+ // Check if we got a magnet from the error
314
+ if (torrentResult && torrentResult._isMagnetFromError) {
315
+ console.log('Processing magnet URI extracted from error');
316
+ const fixedMagnetUri = fixMagnetUri(torrentResult.magnetUri);
317
+ const magnetInfo = processMagnetLink(fixedMagnetUri);
318
+
319
+ if (magnetInfo) {
320
+ return {
321
+ magnetLink: fixedMagnetUri,
322
+ infoHash: magnetInfo.infoHash,
323
+ name: magnetInfo.name,
324
+ filename: magnetInfo.name,
325
+ mainFileSize: 0,
326
+ quality: estimateQuality(magnetInfo.name, 0)
327
+ };
328
+ }
329
+
330
+ return null;
331
+ }
332
+
333
+ // We got a valid torrent, proceed with normal processing
334
+ if (!torrentResult || !torrentResult.files) {
335
+ console.log('No valid torrent info or files found');
336
+ return extractTorrentInfoFromString(url);
337
+ }
338
+
339
+ // Verify this torrent contains video files
340
+ if (!containsVideoContent(torrentResult)) {
341
+ console.log('No video files found in torrent');
342
+ return extractTorrentInfoFromString(url);
343
+ }
344
+
345
+ // Find the main video file
346
+ const mainFile = findMainVideoFile(torrentResult.files);
347
+ if (!mainFile) {
348
+ console.log('No main video file identified');
349
+ return extractTorrentInfoFromString(url);
350
+ }
351
+
352
+ const mainFilePath = Array.isArray(mainFile.path) ? mainFile.path.join('/') : mainFile.path;
353
+ const magnetLink = createMagnetLink(torrentResult);
354
+
355
+ return {
356
+ magnetLink,
357
+ infoHash: torrentResult.infoHash,
358
+ name: torrentResult.name,
359
+ filename: mainFilePath,
360
+ mainFileSize: mainFile.length,
361
+ totalSize: torrentResult.length,
362
+ fileCount: torrentResult.files.length,
363
+ files: torrentResult.files.map(file => {
364
+ const filePath = Array.isArray(file.path) ? file.path.join('/') : file.path;
365
+ return {
366
+ path: filePath,
367
+ size: file.length,
368
+ isVideo: isVideoFile(filePath)
369
+ };
370
+ }),
371
+ quality: estimateQuality(mainFilePath, mainFile.length)
372
+ };
373
+
374
+ } catch (error) {
375
+ console.error('Download/processing of torrent failed:', error.message);
376
+
377
+ // As a fallback, try to extract info from the URL itself
378
+ return extractTorrentInfoFromString(url);
379
+ }
380
+ } catch (error) {
381
+ console.error('Error analyzing torrent:', error.message);
382
+ return null;
383
+ }
384
+ }
385
+
386
+ export {
387
+ analyzeTorrentFromUrl,
388
+ isVideoFile,
389
+ findMainVideoFile,
390
+ containsVideoContent,
391
+ estimateQuality,
392
+ createMagnetLink,
393
+ extractMagnetFromError,
394
+ extractTorrentInfoFromString
395
+ };