mikmc5 commited on
Commit
c55b197
·
verified ·
1 Parent(s): 7c03adb

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +118 -395
server.js CHANGED
@@ -1,421 +1,144 @@
1
- import express from 'express';
2
- import { fetchRSSFeeds } from './rarbg.js';
3
 
4
- const app = express();
5
- const port = process.env.PORT || 7860;
6
- const TMDB_API_KEY = 'f051e7366c6105ad4f9aafe4733d9dae';
7
- const TMDB_BASE_URL = 'https://api.themoviedb.org/3';
 
8
 
9
- app.use(express.json());
 
 
10
 
11
- // Utility function for retrying network requests
12
- async function fetchWithRetry(url, options = {}, maxRetries = 3) {
13
- let lastError;
14
-
15
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
16
- try {
17
- const response = await fetch(url, options);
18
- return response;
19
- } catch (error) {
20
- console.error(`Fetch attempt ${attempt}/${maxRetries} failed: ${error.message}`);
21
- lastError = error;
22
-
23
- if (attempt < maxRetries) {
24
- // Wait with exponential backoff before retrying
25
- const delay = Math.min(1000 * Math.pow(2, attempt), 10000);
26
- await new Promise(resolve => setTimeout(resolve, delay));
27
- }
28
  }
29
- }
30
-
31
- throw lastError || new Error('All fetch attempts failed');
32
- }
33
 
34
- function standardizeEpisodeFormat(query) {
35
- // Handle 1x01 format
36
- const altMatch = query.match(/^(.*?)(\d{1,2})x(\d{1,2})/i);
37
- if (altMatch) {
38
- const [_, title, season, episode] = altMatch;
39
- const paddedSeason = String(season).padStart(2, '0');
40
- const paddedEpisode = String(episode).padStart(2, '0');
41
- return `${title.trim()} S${paddedSeason}E${paddedEpisode}`;
42
- }
43
- return query;
44
- }
45
 
46
- function isExactEpisodeMatch(torrentTitle, showTitle, seasonNum, episodeNum) {
47
- if (!torrentTitle || !showTitle) return false;
48
-
49
- // Clean up title
50
- torrentTitle = torrentTitle.replace(/\[.*?\]/g, '')
51
- .replace(/\(.*?\)/g, '')
52
- .replace(/\s+/g, ' ')
53
- .trim();
54
-
55
- // Normalize the titles
56
- const normalizedTorrentTitle = torrentTitle.toLowerCase();
57
- const normalizedShowTitle = showTitle.toLowerCase().trim();
58
-
59
- // Split show title into significant words
60
- const showWords = normalizedShowTitle.split(' ')
61
- .filter(word => word.length > 2)
62
- .filter(word => !['the', 'and', 'or', 'in', 'on', 'at', 'to'].includes(word));
63
-
64
- const hasAllShowWords = showWords.every(word =>
65
- normalizedTorrentTitle.includes(word)
66
- );
67
-
68
- if (!hasAllShowWords) return false;
69
-
70
- // Format season and episode numbers
71
- const seasonStr = String(seasonNum).padStart(2, '0');
72
- const episodeStr = String(episodeNum).padStart(2, '0');
73
-
74
- // Common episode patterns
75
- const patterns = [
76
- new RegExp(`s${seasonStr}e${episodeStr}`, 'i'),
77
- new RegExp(`${seasonNum}x${episodeStr}`, 'i'),
78
- new RegExp(`[^0-9]${seasonNum}${episodeStr}[^0-9]`, 'i'),
79
- new RegExp(`season\\s*${seasonNum}\\s*episode\\s*${episodeNum}`, 'i'),
80
- new RegExp(`s${seasonStr}\\.?e${episodeStr}`, 'i'),
81
- new RegExp(`${seasonStr}${episodeStr}`, 'i')
82
- ];
83
-
84
- return patterns.some(pattern => pattern.test(normalizedTorrentTitle));
85
- }
86
 
87
- function isExactMovieMatch(torrentTitle, movieTitle, year) {
88
- if (!torrentTitle || !movieTitle) return false;
89
 
90
- // Clean title
91
- torrentTitle = torrentTitle.replace(/\[.*?\]/g, '')
92
- .replace(/\(.*?\)/g, '')
93
- .replace(/\s+/g, ' ')
94
- .trim();
95
-
96
- const normalizedTorrentTitle = torrentTitle.toLowerCase();
97
- const normalizedMovieTitle = movieTitle.toLowerCase();
98
-
99
- const movieWords = normalizedMovieTitle.split(' ')
100
- .filter(word => word.length > 2)
101
- .filter(word => !['the', 'and', 'or', 'in', 'on', 'at', 'to'].includes(word));
102
-
103
- // Skip the check if movie title is too short
104
- if (movieWords.length === 0) return true;
105
-
106
- const hasAllMovieWords = movieWords.some(word =>
107
- normalizedTorrentTitle.includes(word)
108
- );
109
-
110
- if (!hasAllMovieWords) return false;
111
-
112
- // If year is specified, check for it
113
- if (year) {
114
- const yearMatch = torrentTitle.match(/(?:19|20)\d{2}/);
115
- return yearMatch && yearMatch[0] === year.toString();
116
- }
117
-
118
- return true;
119
- }
120
 
121
- async function getTMDBDetails(tmdbId, type = 'movie') {
122
- try {
123
- const response = await fetchWithRetry(
124
- `${TMDB_BASE_URL}/${type}/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`
125
- );
126
-
127
- if (!response.ok) {
128
- const errorText = await response.text();
129
- console.error(`TMDB API error (${response.status}): ${errorText}`);
130
- throw new Error(`TMDB API error: ${response.status}`);
131
- }
132
-
133
- return await response.json();
134
- } catch (error) {
135
- console.error('TMDB fetch error:', error);
136
- return null;
137
- }
138
- }
139
 
140
- async function getTVShowDetails(tmdbId, seasonNum, episodeNum) {
141
- try {
142
- // Request show data first
143
- const showResponse = await fetchWithRetry(
144
- `${TMDB_BASE_URL}/tv/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`
145
- );
146
-
147
- if (!showResponse.ok) {
148
- const errorText = await showResponse.text();
149
- console.error(`TMDB show API error (${showResponse.status}): ${errorText}`);
150
- throw new Error(`TMDB show API error: ${showResponse.status}`);
151
- }
152
-
153
- const showData = await showResponse.json();
154
-
155
- // Then request episode data
156
- const episodeResponse = await fetchWithRetry(
157
- `${TMDB_BASE_URL}/tv/${tmdbId}/season/${seasonNum}/episode/${episodeNum}?api_key=${TMDB_API_KEY}`
 
 
 
 
 
 
158
  );
159
-
160
- if (!episodeResponse.ok) {
161
- const errorText = await episodeResponse.text();
162
- console.error(`TMDB episode API error (${episodeResponse.status}): ${errorText}`);
163
-
164
- // Return partial data if we at least have the show
165
- return {
166
- showTitle: showData.name,
167
- episodeTitle: `Episode ${episodeNum}`,
168
- seasonNumber: seasonNum,
169
- episodeNumber: episodeNum,
170
- airDate: null,
171
- imdbId: showData.external_ids?.imdb_id,
172
- error: `Episode data not available (${episodeResponse.status})`
173
- };
174
- }
175
-
176
- const episodeData = await episodeResponse.json();
177
 
178
- return {
179
- showTitle: showData.name,
180
- episodeTitle: episodeData.name,
181
- seasonNumber: seasonNum,
182
- episodeNumber: episodeNum,
183
- airDate: episodeData.air_date,
184
- imdbId: showData.external_ids?.imdb_id
185
- };
 
 
 
186
  } catch (error) {
187
- console.error('TMDB fetch error:', error);
188
- throw error; // Re-throw to allow better handling in calling code
189
  }
190
  }
191
 
192
- async function handleSearch({ query, type }) {
193
- if (!query) throw new Error('Missing required parameter: query');
194
- if (!['movie', 'series'].includes(type)) throw new Error('Invalid type. Must be either "movie" or "series"');
195
-
196
- let searchQuery = query;
197
- let exactMatchParams = {};
198
- let tmdbData = null;
199
 
200
- console.log(`🔍 Received search request: ${query} (Type: ${type})`);
 
 
 
 
 
 
 
201
 
202
- try {
203
- if (type === 'series') {
204
- const tmdbMatch = query.match(/^tmdb:(\d+):(\d+):(\d+)$/);
205
- if (tmdbMatch) {
206
- const [_, tmdbId, seasonNum, episodeNum] = tmdbMatch;
207
- try {
208
- tmdbData = await getTVShowDetails(
209
- tmdbId,
210
- parseInt(seasonNum),
211
- parseInt(episodeNum)
212
- );
213
- if (tmdbData) {
214
- exactMatchParams = {
215
- title: tmdbData.showTitle,
216
- season: parseInt(seasonNum),
217
- episode: parseInt(episodeNum)
218
- };
219
- searchQuery = `${tmdbData.showTitle} S${String(seasonNum).padStart(2, '0')}E${String(episodeNum).padStart(2, '0')}`;
220
- console.log(`📺 TMDB ID resolved to: ${searchQuery}`);
221
- }
222
- } catch (error) {
223
- console.error('Failed to get TV show details:', error);
224
- // Continue with the original query
225
- }
226
- } else if (query.startsWith('tt')) {
227
- const imdbMatch = query.match(/^(tt\d+):(\d+):(\d+)$/);
228
- if (imdbMatch) {
229
- const [_, imdbId, seasonNum, episodeNum] = imdbMatch;
230
- try {
231
- const findResponse = await fetchWithRetry(
232
- `${TMDB_BASE_URL}/find/${imdbId}?api_key=${TMDB_API_KEY}&external_source=imdb_id`
233
- );
234
- if (findResponse.ok) {
235
- const findData = await findResponse.json();
236
- if (findData.tv_results?.[0]) {
237
- const tmdbId = findData.tv_results[0].id;
238
- tmdbData = await getTVShowDetails(
239
- tmdbId,
240
- parseInt(seasonNum),
241
- parseInt(episodeNum)
242
- );
243
- if (tmdbData) {
244
- exactMatchParams = {
245
- title: tmdbData.showTitle,
246
- season: parseInt(seasonNum),
247
- episode: parseInt(episodeNum)
248
- };
249
- searchQuery = `${tmdbData.showTitle} S${String(seasonNum).padStart(2, '0')}E${String(episodeNum).padStart(2, '0')}`;
250
- console.log(`📺 IMDb ID resolved to: ${searchQuery}`);
251
- }
252
- }
253
- }
254
- } catch (error) {
255
- console.error('Failed to resolve IMDb ID:', error);
256
- // Continue with the original query
257
- }
258
- }
259
- } else {
260
- searchQuery = standardizeEpisodeFormat(query);
261
- const seasonEpisodeMatch = searchQuery.match(/^(.*?)S(\d{1,2})E(\d{1,2})/i);
262
- if (seasonEpisodeMatch) {
263
- exactMatchParams = {
264
- title: seasonEpisodeMatch[1].trim(),
265
- season: parseInt(seasonEpisodeMatch[2]),
266
- episode: parseInt(seasonEpisodeMatch[3])
267
- };
268
- }
269
- }
270
- } else if (type === 'movie') {
271
- if (query.startsWith('tmdb:')) {
272
- const tmdbId = query.replace('tmdb:', '');
273
- console.log(`🔎 TMDB ID detected: ${tmdbId}`);
274
- try {
275
- tmdbData = await getTMDBDetails(tmdbId, 'movie');
276
- if (tmdbData) {
277
- exactMatchParams = {
278
- title: tmdbData.title,
279
- year: new Date(tmdbData.release_date).getFullYear()
280
- };
281
- searchQuery = `${tmdbData.title} (${exactMatchParams.year})`;
282
- console.log(`🎬 TMDB ID resolved to: ${searchQuery}`);
283
- }
284
- } catch (error) {
285
- console.error('Failed to get movie details:', error);
286
- // Continue with the original query
287
- }
288
- } else if (query.startsWith('tt')) {
289
- try {
290
- const findResponse = await fetchWithRetry(
291
- `${TMDB_BASE_URL}/find/${query}?api_key=${TMDB_API_KEY}&external_source=imdb_id`
292
- );
293
- if (findResponse.ok) {
294
- const findData = await findResponse.json();
295
- if (findData.movie_results?.[0]) {
296
- tmdbData = findData.movie_results[0];
297
- exactMatchParams = {
298
- title: tmdbData.title,
299
- year: new Date(tmdbData.release_date).getFullYear()
300
- };
301
- searchQuery = `${tmdbData.title} (${exactMatchParams.year})`;
302
- console.log(`🎬 IMDb ID resolved to: ${searchQuery}`);
303
- }
304
- }
305
- } catch (error) {
306
- console.error('Failed to resolve IMDb ID:', error);
307
- // Continue with the original query
308
- }
309
- } else {
310
- const movieYearMatch = query.match(/^(.+?)(?:\s*\(?(\d{4})\)?)?$/);
311
- if (movieYearMatch) {
312
- exactMatchParams = {
313
- title: movieYearMatch[1].trim(),
314
- year: movieYearMatch[2] ? parseInt(movieYearMatch[2]) : null
315
- };
316
- }
317
- }
318
  }
319
- } catch (error) {
320
- console.error('Error processing search metadata:', error);
321
- // Continue with the original query without metadata
322
- }
323
 
324
- console.log(`🔄 Fetching torrents for: ${searchQuery} (Original: ${query})`);
325
-
326
- let results = [];
327
- try {
328
- results = await fetchRSSFeeds(searchQuery, type);
329
- console.log(`✅ Found ${results.length} torrents for "${searchQuery}"`);
330
  } catch (error) {
331
- console.error('Error fetching RSS feeds:', error);
332
- }
333
-
334
- // Only apply filters if we have valid match parameters
335
- if (type === 'series' && exactMatchParams.season !== undefined) {
336
- const filteredResults = results.filter(result =>
337
- isExactEpisodeMatch(
338
- result.websiteTitle,
339
- exactMatchParams.title,
340
- exactMatchParams.season,
341
- exactMatchParams.episode
342
- )
343
- );
344
-
345
- if (filteredResults.length > 0) {
346
- results = filteredResults;
347
- console.log(`✅ Filtered to ${results.length} exact episode matches`);
348
- } else {
349
- console.log(`⚠️ No exact episode matches found, returning all results`);
350
- }
351
- } else if (type === 'movie' && exactMatchParams.title) {
352
- const filteredResults = results.filter(result =>
353
- isExactMovieMatch(
354
- result.websiteTitle,
355
- exactMatchParams.title,
356
- exactMatchParams.year
357
- )
358
- );
359
-
360
- if (filteredResults.length > 0) {
361
- results = filteredResults;
362
- console.log(`✅ Filtered to ${results.length} exact movie matches`);
363
- } else {
364
- console.log(`⚠️ No exact movie matches found, returning all results`);
365
- }
366
  }
367
-
368
- return {
369
- query: searchQuery,
370
- originalQuery: query,
371
- type,
372
- tmdbData,
373
- results: results.map(result => ({
374
- title: result.websiteTitle,
375
- quality: result.quality,
376
- size: result.size,
377
- magnetLink: result.magnetLink
378
- }))
379
- };
380
  }
381
 
382
- app.get('/api/search', async (req, res) => {
383
- try {
384
- const result = await handleSearch({ query: req.query.query, type: req.query.type });
385
- res.json(result);
386
- } catch (error) {
387
- console.error('Search API error:', error);
388
- res.status(500).json({ error: 'Internal server error', message: error.message });
389
- }
390
- });
 
 
 
 
 
391
 
392
- app.post('/api/search', async (req, res) => {
393
- try {
394
- const result = await handleSearch(req.body);
395
- res.json(result);
396
- } catch (error) {
397
- console.error('Search API error:', error);
398
- res.status(500).json({ error: 'Internal server error', message: error.message });
399
- }
400
- });
401
 
402
- app.listen(port, () => {
403
- console.log(`===== Application Startup at ${new Date().toISOString().replace('T', ' ').substring(0, 19)} =====`);
404
- console.log(`Server running at http://localhost:${port}`);
405
- if (!TMDB_API_KEY) {
406
- console.warn('Warning: TMDB_API_KEY not set. TMDB features will not work.');
407
- } else {
408
- // Test TMDB API key on startup
409
- fetch(`${TMDB_BASE_URL}/movie/550?api_key=${TMDB_API_KEY}`)
410
- .then(response => {
411
- if (!response.ok) {
412
- console.warn(`⚠️ TMDB API key test failed with status ${response.status}`);
413
- } else {
414
- console.log('✅ TMDB API key verified');
415
- }
416
- })
417
- .catch(error => {
418
- console.warn(`⚠️ TMDB API key test failed: ${error.message}`);
419
- });
420
- }
421
- });
 
1
+ import fetch from 'node-fetch';
2
+ import * as cheerio from 'cheerio';
3
 
4
+ // ==============================
5
+ // fetchRSSFeeds: Main Export Function
6
+ // ==============================
7
+ async function fetchRSSFeeds(searchQuery) {
8
+ console.log(`\n🔄 Fetching RARBG results for: ${searchQuery}`);
9
 
10
+ const encodedQuery = encodeURIComponent(searchQuery);
11
+ const searchUrl = `https://therarbg.to/get-posts/keywords:${encodedQuery}:keywords:ita:category:Movies:category:TV:size__gte:100000000/`;
12
+ console.log(`📡 Fetching: ${searchUrl}`);
13
 
14
+ try {
15
+ const response = await fetch(searchUrl, {
16
+ headers: {
17
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/134.0.0.0 Safari/537.36',
18
+ 'Accept': 'text/html',
19
+ 'Referer': 'https://therarbg.to/',
20
+ 'Cookie': 'cf_clearance=your_clearance_cookie_here;', // Replace with actual clearance if needed
21
+ },
22
+ method: 'GET',
23
+ });
24
+
25
+ if (!response.ok) {
26
+ throw new Error(`Failed to fetch from RARBG: ${response.status}`);
 
 
 
 
27
  }
 
 
 
 
28
 
29
+ const pageHtml = await response.text();
30
+ const $ = cheerio.load(pageHtml);
31
+ const torrents = [];
 
 
 
 
 
 
 
 
32
 
33
+ $('tr.list-entry').each((_, element) => {
34
+ const titleElement = $(element).find('td.cellName a:first');
35
+ const websiteTitle = titleElement.text().trim();
36
+ const torrentPage = titleElement.attr('href');
37
+ const size = $(element).find('td.sizeCell').text().trim();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
 
 
39
 
40
+ if (!torrentPage) return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
+ const torrentPageUrl = `https://therarbg.to${torrentPage}`;
43
+ const quality = extractQuality(websiteTitle);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ torrents.push({
46
+ title: websiteTitle,
47
+ quality,
48
+ size,
49
+ torrentPageUrl
50
+ });
51
+ });
52
+
53
+ // Process and Attach Magnet Links
54
+ const completedTorrents = await Promise.all(
55
+ torrents.map(async (torrent) => {
56
+ const magnetLink = await extractMagnetLink(torrent.torrentPageUrl);
57
+ if (magnetLink) {
58
+ return {
59
+ magnetLink,
60
+ websiteTitle: torrent.title,
61
+ quality: torrent.quality,
62
+ size: torrent.size,
63
+ mainFileSize: parseSizeToBytes(torrent.size),
64
+ categories: ['Movies', 'TV'],
65
+ };
66
+ }
67
+ return null;
68
+ })
69
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
+ const validTorrents = completedTorrents.filter(Boolean);
72
+
73
+ // Sorting: Highest Quality & Size First
74
+ validTorrents.sort((a, b) => {
75
+ const qualityOrder = { '2160p': 4, '4k': 4, 'uhd': 4, '1080p': 3, '720p': 2 };
76
+ const qualityDiff = (qualityOrder[b.quality] || 0) - (qualityOrder[a.quality] || 0);
77
+ return qualityDiff === 0 ? b.mainFileSize - a.mainFileSize : qualityDiff;
78
+ });
79
+
80
+ console.log(`✅ Processed ${validTorrents.length} valid torrents`);
81
+ return validTorrents;
82
  } catch (error) {
83
+ console.error('❌ Error fetching from RARBG:', error);
84
+ return [];
85
  }
86
  }
87
 
88
+ // ==============================
89
+ // extractMagnetLink: Fetch Magnet Links
90
+ // ==============================
91
+ async function extractMagnetLink(torrentPageUrl) {
92
+ try {
93
+ await new Promise(resolve => setTimeout(resolve, Math.random() * 2000 + 1000)); // 1-3 sec delay
 
94
 
95
+ const response = await fetch(torrentPageUrl, {
96
+ headers: {
97
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/134.0.0.0 Safari/537.36',
98
+ 'Accept': 'text/html',
99
+ 'Referer': 'https://therarbg.to/'
100
+ },
101
+ method: 'GET',
102
+ });
103
 
104
+ if (!response.ok) {
105
+ throw new Error(`Failed to fetch torrent page: ${response.status}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  }
 
 
 
 
107
 
108
+ const pageHtml = await response.text();
109
+ const magnetMatch = pageHtml.match(/href="(magnet:\?xt=urn:btih:[^"]+)"/);
110
+ return magnetMatch ? magnetMatch[1] : null;
 
 
 
111
  } catch (error) {
112
+ console.error('❌ Error extracting magnet link:', error);
113
+ return null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  }
116
 
117
+ // ==============================
118
+ // parseSizeToBytes: Convert Sizes for Sorting
119
+ // ==============================
120
+ function parseSizeToBytes(size) {
121
+ if (!size) return 0;
122
+ const sizeMatch = size.match(/([\d.]+)\s*(MB|GB|TB)/i);
123
+ if (!sizeMatch) return 0;
124
+
125
+ const [, value, unit] = sizeMatch;
126
+ const multiplier = unit.toUpperCase() === 'TB' ? 1024 ** 4 :
127
+ unit.toUpperCase() === 'GB' ? 1024 ** 3 :
128
+ 1024 ** 2;
129
+ return parseFloat(value) * multiplier;
130
+ }
131
 
132
+ // ==============================
133
+ // extractQuality: Identify Quality from Title
134
+ // ==============================
135
+ function extractQuality(title) {
136
+ if (!title) return '';
137
+ const qualityMatch = title.match(/\b(2160p|1080p|720p|4k|uhd)\b/i);
138
+ return qualityMatch ? qualityMatch[1].toLowerCase() : '';
139
+ }
 
140
 
141
+ // ==============================
142
+ // Export for Server.js
143
+ // ==============================
144
+ export { fetchRSSFeeds };