mikmc5 commited on
Commit
29b2ee8
·
verified ·
1 Parent(s): 1257a7e

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +263 -126
server.js CHANGED
@@ -1,153 +1,290 @@
1
- import xml2js from 'xml2js';
 
2
 
3
- const parser = new xml2js.Parser({
4
- explicitArray: false,
5
- ignoreAttrs: true
6
- });
7
 
8
- // Function to extract quality from the title
9
- function extractQuality(title) {
10
- if (!title) return '';
11
- const qualityMatch = title.match(/\b(2160p|1080p|720p|4k|uhd)\b/i);
12
- return qualityMatch ? qualityMatch[1].toLowerCase() : '';
13
- }
14
 
15
- // Function to format size from bytes to readable format
16
- function formatSize(bytes) {
17
- const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
18
- if (bytes === 0) return '0 B';
19
- const i = Math.floor(Math.log(bytes) / Math.log(1024));
20
- return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;
 
 
 
 
21
  }
22
 
23
- // Function to extract magnet link from the description
24
- function extractMagnetFromDescription(description) {
25
- if (!description) return null;
26
- const magnetMatch = description.match(/magnet:\?xt=urn:btih:[A-Za-z0-9]+[^"'\s]*/);
27
- return magnetMatch ? magnetMatch[0] : null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  }
29
 
30
- // Function to create a magnet link from the hash ID
31
- function createMagnetLink(hashId) {
32
- const baseUrl = "magnet:?xt=urn:btih:";
33
- return baseUrl + hashId;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  }
35
 
36
- async function fetchRSSFeeds(searchQuery, type = 'movie') {
37
- console.log('\n🔄 Fetching RSS feed for:', searchQuery);
38
-
39
  try {
40
- // Extract title and year from the search query
41
- const yearMatch = searchQuery.match(/\(\d{4}\)/);
42
- const year = yearMatch ? yearMatch[0].replace(/[()]/g, '') : '';
43
- const title = searchQuery.replace(/\(\d{4}\)/, '').trim();
44
-
45
- // Construct the Knaben RSS URL with search codes
46
- const searchTerm = `${title} ${year}`.trim();
47
- const encodedSearch = encodeURIComponent(searchTerm);
48
- // Note: These are search codes, not size filters
49
- const rssUrl = `https://rss.knaben.org/${encodedSearch}/1004000|3000000|2000000`;
50
-
51
- console.log('Request URL:', rssUrl);
52
-
53
- const response = await fetch(rssUrl, {
54
- headers: {
55
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
56
- 'Accept': 'application/rss+xml,application/xml,text/xml'
57
- }
58
- });
59
-
60
- if (!response.ok) {
61
- throw new Error(`Failed to fetch from Knaben: ${response.status}`);
62
- }
63
-
64
- const rssData = await response.text();
65
- console.log('Received RSS Data:', rssData.substring(0, 500)); // Log first 500 characters
66
 
67
- const result = await parser.parseStringPromise(rssData);
68
- console.log('Parsed RSS Result:', result); // Log parsed result
 
 
 
 
69
 
70
- if (!result?.rss?.channel?.item) {
71
- console.log('No items found');
72
- return [];
73
  }
74
 
75
- const items = Array.isArray(result.rss.channel.item) ?
76
- result.rss.channel.item : [result.rss.channel.item];
77
-
78
- console.log(`Found ${items.length} items`);
79
 
80
- const streams = items.map(item => {
81
- if (!item || !item.title || !item.description) return null;
 
 
 
 
 
 
 
 
 
 
 
82
 
83
- // Extract magnet link from description
84
- const magnetLink = extractMagnetFromDescription(item.description);
85
- if (!magnetLink) return null;
86
 
87
- // Extract size from description
88
- const sizeMatch = item.description.match(/Size:\s*([\d.]+)\s*(MB|GB|TB)/i);
89
- const size = sizeMatch ? `${sizeMatch[1]} ${sizeMatch[2]}` : 'Unknown';
90
 
91
- // Convert size to bytes for sorting
92
- let sizeInBytes = 0;
93
- if (sizeMatch) {
94
- const [, value, unit] = sizeMatch;
95
- const multiplier = unit.toUpperCase() === 'TB' ? 1024 * 1024 * 1024 * 1024 :
96
- unit.toUpperCase() === 'GB' ? 1024 * 1024 * 1024 :
97
- 1024 * 1024;
98
- sizeInBytes = parseFloat(value) * multiplier;
 
 
 
 
 
99
  }
100
-
101
- // Extract info hash from magnet link (guid)
102
- const infoHashMatch = item.guid.match(/([A-Za-z0-9]{40})/i);
103
- const infoHash = infoHashMatch ? infoHashMatch[0] : null;
104
-
105
- // Create a magnet link using the hash ID
106
- const magnetLinkWithHash = createMagnetLink(infoHash);
107
-
108
- return {
109
- magnetLink: magnetLinkWithHash, // Updated magnet link with hash
110
- websiteTitle: item.title,
111
- quality: extractQuality(item.title),
112
- size,
113
- source: item.author || 'Unknown',
114
- infoHash,
115
- mainFileSize: sizeInBytes,
116
- pubDate: item.pubDate,
117
- categories: Array.isArray(item.category) ? item.category : [item.category]
118
- };
119
- }).filter(Boolean);
120
-
121
- // Sort by quality and size
122
- streams.sort((a, b) => {
123
- const qualityOrder = { '2160p': 4, '4k': 4, 'uhd': 4, '1080p': 3, '720p': 2 };
124
- const qualityDiff = (qualityOrder[b.quality] || 0) - (qualityOrder[a.quality] || 0);
125
- if (qualityDiff === 0) {
126
- return b.mainFileSize - a.mainFileSize;
 
 
 
 
 
 
 
 
127
  }
128
- return qualityDiff;
129
- });
130
-
131
- console.log(`✅ Processed ${streams.length} valid streams`);
132
-
133
- if (streams.length > 0) {
134
- console.log('Sample stream:', {
135
- title: streams[0].websiteTitle,
136
- quality: streams[0].quality,
137
- size: streams[0].size,
138
- source: streams[0].source
139
- });
140
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
- // Final count message
143
- console.log(`✅ Found ${streams.length} torrents for "${searchQuery}"`);
144
 
145
- return streams;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
 
 
 
 
 
147
  } catch (error) {
148
- console.error('❌ Error fetching from Knaben:', error);
149
- return [];
150
  }
151
- }
152
 
153
- export { fetchRSSFeeds };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from 'express';
2
+ import { fetchRSSFeeds } from './rutracker.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
+ function standardizeEpisodeFormat(query) {
12
+ // Handle 1x01 format
13
+ const altMatch = query.match(/^(.*?)(\d{1,2})x(\d{1,2})/i);
14
+ if (altMatch) {
15
+ const [_, title, season, episode] = altMatch;
16
+ const paddedSeason = String(season).padStart(2, '0');
17
+ const paddedEpisode = String(episode).padStart(2, '0');
18
+ return `${title.trim()} S${paddedSeason}E${paddedEpisode}`;
19
+ }
20
+ return query;
21
  }
22
 
23
+ function isExactEpisodeMatch(torrentTitle, showTitle, seasonNum, episodeNum) {
24
+ if (!torrentTitle || !showTitle) return false;
25
+
26
+ // Clean up title
27
+ torrentTitle = torrentTitle.replace(/\[.*?\]/g, '')
28
+ .replace(/\(.*?\)/g, '')
29
+ .replace(/\s+/g, ' ')
30
+ .trim();
31
+
32
+ // Normalize the titles
33
+ const normalizedTorrentTitle = torrentTitle.toLowerCase();
34
+ const normalizedShowTitle = showTitle.toLowerCase().trim();
35
+
36
+ // Split show title into significant words
37
+ const showWords = normalizedShowTitle.split(' ')
38
+ .filter(word => word.length > 2)
39
+ .filter(word => !['the', 'and', 'or', 'in', 'on', 'at', 'to'].includes(word));
40
+
41
+ const hasAllShowWords = showWords.every(word =>
42
+ normalizedTorrentTitle.includes(word)
43
+ );
44
+
45
+ if (!hasAllShowWords) return false;
46
+
47
+ // Format season and episode numbers
48
+ const seasonStr = String(seasonNum).padStart(2, '0');
49
+ const episodeStr = String(episodeNum).padStart(2, '0');
50
+
51
+ // Common episode patterns
52
+ const patterns = [
53
+ new RegExp(`s${seasonStr}e${episodeStr}`, 'i'),
54
+ new RegExp(`${seasonNum}x${episodeStr}`, 'i'),
55
+ new RegExp(`[^0-9]${seasonNum}${episodeStr}[^0-9]`, 'i'),
56
+ new RegExp(`season\\s*${seasonNum}\\s*episode\\s*${episodeNum}`, 'i'),
57
+ new RegExp(`s${seasonStr}\\.?e${episodeStr}`, 'i'),
58
+ new RegExp(`${seasonStr}${episodeStr}`, 'i')
59
+ ];
60
+
61
+ return patterns.some(pattern => pattern.test(normalizedTorrentTitle));
62
  }
63
 
64
+ function isExactMovieMatch(torrentTitle, movieTitle, year) {
65
+ // Clean title
66
+ torrentTitle = torrentTitle.replace(/\[.*?\]/g, '')
67
+ .replace(/\(.*?\)/g, '')
68
+ .replace(/\s+/g, ' ')
69
+ .trim();
70
+
71
+ const normalizedTorrentTitle = torrentTitle.toLowerCase();
72
+ const normalizedMovieTitle = movieTitle.toLowerCase();
73
+
74
+ const movieWords = normalizedMovieTitle.split(' ')
75
+ .filter(word => word.length > 2)
76
+ .filter(word => !['the', 'and', 'or', 'in', 'on', 'at', 'to'].includes(word));
77
+
78
+ const hasAllMovieWords = movieWords.every(word =>
79
+ normalizedTorrentTitle.includes(word)
80
+ );
81
+
82
+ if (!hasAllMovieWords) return false;
83
+
84
+ const yearMatch = torrentTitle.match(/(?:19|20)\d{2}/);
85
+ return yearMatch && yearMatch[0] === year.toString();
86
  }
87
 
88
+ async function getTMDBDetails(tmdbId, type = 'movie') {
 
 
89
  try {
90
+ const response = await fetch(`${TMDB_BASE_URL}/${type}/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`);
91
+ if (!response.ok) throw new Error(`TMDB API error: ${response.status}`);
92
+ return await response.json();
93
+ } catch (error) {
94
+ console.error('TMDB fetch error:', error);
95
+ return null;
96
+ }
97
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
+ async function getTVShowDetails(tmdbId, seasonNum, episodeNum) {
100
+ try {
101
+ const [showResponse, episodeResponse] = await Promise.all([
102
+ fetch(`${TMDB_BASE_URL}/tv/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`),
103
+ fetch(`${TMDB_BASE_URL}/tv/${tmdbId}/season/${seasonNum}/episode/${episodeNum}?api_key=${TMDB_API_KEY}`)
104
+ ]);
105
 
106
+ if (!showResponse.ok || !episodeResponse.ok) {
107
+ throw new Error('TMDB API error');
 
108
  }
109
 
110
+ const [showData, episodeData] = await Promise.all([
111
+ showResponse.json(),
112
+ episodeResponse.json()
113
+ ]);
114
 
115
+ return {
116
+ showTitle: showData.name,
117
+ episodeTitle: episodeData.name,
118
+ seasonNumber: seasonNum,
119
+ episodeNumber: episodeNum,
120
+ airDate: episodeData.air_date,
121
+ imdbId: showData.external_ids?.imdb_id
122
+ };
123
+ } catch (error) {
124
+ console.error('TMDB fetch error:', error);
125
+ return null;
126
+ }
127
+ }
128
 
129
+ async function handleSearch({ query, type }) {
130
+ if (!query) throw new Error('Missing required parameter: query');
131
+ if (!['movie', 'series'].includes(type)) throw new Error('Invalid type. Must be either "movie" or "series"');
132
 
133
+ let searchQuery = query;
134
+ let exactMatchParams = {};
135
+ let tmdbData = null;
136
 
137
+ if (type === 'series') {
138
+ // Handle TMDB ID format: "tmdb:12345:1:1"
139
+ const tmdbMatch = query.match(/^tmdb:(\d+):(\d+):(\d+)$/);
140
+ if (tmdbMatch) {
141
+ const [_, tmdbId, seasonNum, episodeNum] = tmdbMatch;
142
+ tmdbData = await getTVShowDetails(tmdbId, parseInt(seasonNum), parseInt(episodeNum));
143
+ if (tmdbData) {
144
+ exactMatchParams = {
145
+ title: tmdbData.showTitle,
146
+ season: parseInt(seasonNum),
147
+ episode: parseInt(episodeNum)
148
+ };
149
+ searchQuery = `${tmdbData.showTitle} S${String(seasonNum).padStart(2, '0')}E${String(episodeNum).padStart(2, '0')}`;
150
  }
151
+ }
152
+ // Handle IMDB ID format: "tt1234567:1:1"
153
+ else if (query.startsWith('tt')) {
154
+ const imdbMatch = query.match(/^(tt\d+):(\d+):(\d+)$/);
155
+ if (imdbMatch) {
156
+ const [_, imdbId, seasonNum, episodeNum] = imdbMatch;
157
+ const findResponse = await fetch(
158
+ `${TMDB_BASE_URL}/find/${imdbId}?api_key=${TMDB_API_KEY}&external_source=imdb_id`
159
+ );
160
+ if (findResponse.ok) {
161
+ const findData = await findResponse.json();
162
+ if (findData.tv_results?.[0]) {
163
+ const tmdbId = findData.tv_results[0].id;
164
+ tmdbData = await getTVShowDetails(tmdbId, parseInt(seasonNum), parseInt(episodeNum));
165
+ if (tmdbData) {
166
+ exactMatchParams = {
167
+ title: tmdbData.showTitle,
168
+ season: parseInt(seasonNum),
169
+ episode: parseInt(episodeNum)
170
+ };
171
+ searchQuery = `${tmdbData.showTitle} S${String(seasonNum).padStart(2, '0')}E${String(episodeNum).padStart(2, '0')}`;
172
+ }
173
+ }
174
+ }
175
+ }
176
+ }
177
+ else {
178
+ searchQuery = standardizeEpisodeFormat(query);
179
+ const seasonEpisodeMatch = searchQuery.match(/^(.*?)S(\d{1,2})E(\d{1,2})/i);
180
+ if (seasonEpisodeMatch) {
181
+ exactMatchParams = {
182
+ title: seasonEpisodeMatch[1].trim(),
183
+ season: parseInt(seasonEpisodeMatch[2]),
184
+ episode: parseInt(seasonEpisodeMatch[3])
185
+ };
186
  }
 
 
 
 
 
 
 
 
 
 
 
 
187
  }
188
+ } else if (type === 'movie') {
189
+ // Handle TMDB ID format
190
+ if (query.startsWith('tmdb:')) {
191
+ const tmdbId = query.replace('tmdb:', '');
192
+ tmdbData = await getTMDBDetails(tmdbId, 'movie');
193
+ if (tmdbData) {
194
+ exactMatchParams = {
195
+ title: tmdbData.title,
196
+ year: new Date(tmdbData.release_date).getFullYear()
197
+ };
198
+ searchQuery = `${tmdbData.title} (${exactMatchParams.year})`;
199
+ }
200
+ }
201
+ // Handle IMDB ID format
202
+ else if (query.startsWith('tt')) {
203
+ const findResponse = await fetch(
204
+ `${TMDB_BASE_URL}/find/${query}?api_key=${TMDB_API_KEY}&external_source=imdb_id`
205
+ );
206
+ if (findResponse.ok) {
207
+ const findData = await findResponse.json();
208
+ if (findData.movie_results?.[0]) {
209
+ tmdbData = findData.movie_results[0];
210
+ exactMatchParams = {
211
+ title: tmdbData.title,
212
+ year: new Date(tmdbData.release_date).getFullYear()
213
+ };
214
+ searchQuery = `${tmdbData.title} (${exactMatchParams.year})`;
215
+ }
216
+ }
217
+ }
218
+ else {
219
+ const movieYearMatch = query.match(/^(.+?)(?:\s*\(?(\d{4})\)?)?$/);
220
+ if (movieYearMatch) {
221
+ exactMatchParams = {
222
+ title: movieYearMatch[1].trim(),
223
+ year: movieYearMatch[2] ? parseInt(movieYearMatch[2]) : null
224
+ };
225
+ }
226
+ }
227
+ }
228
 
229
+ let results = await fetchRSSFeeds(searchQuery, type);
 
230
 
231
+ // Filter results based on exact match parameters
232
+ if (type === 'series' && exactMatchParams.season !== undefined) {
233
+ results = results.filter(result =>
234
+ isExactEpisodeMatch(
235
+ result.websiteTitle,
236
+ exactMatchParams.title,
237
+ exactMatchParams.season,
238
+ exactMatchParams.episode
239
+ )
240
+ );
241
+ } else if (type === 'movie' && exactMatchParams.year) {
242
+ results = results.filter(result =>
243
+ isExactMovieMatch(
244
+ result.websiteTitle,
245
+ exactMatchParams.title,
246
+ exactMatchParams.year
247
+ )
248
+ );
249
+ }
250
+
251
+ return {
252
+ query: searchQuery,
253
+ originalQuery: query,
254
+ type,
255
+ tmdbData,
256
+ results: results.map(result => ({
257
+ title: result.websiteTitle,
258
+ quality: result.quality,
259
+ size: result.size,
260
+ seeders: 0, // Knaben RSS doesn't provide seeder info
261
+ leechers: 0, // Knaben RSS doesn't provide leecher info
262
+ magnetLink: result.magnetLink
263
+ }))
264
+ };
265
+ }
266
 
267
+ app.get('/api/search', async (req, res) => {
268
+ try {
269
+ const result = await handleSearch({ query: req.query.query, type: req.query.type });
270
+ res.json(result);
271
  } catch (error) {
272
+ res.status(500).json({ error: 'Internal server error', message: error.message });
 
273
  }
274
+ });
275
 
276
+ app.post('/api/search', async (req, res) => {
277
+ try {
278
+ const result = await handleSearch(req.body);
279
+ res.json(result);
280
+ } catch (error) {
281
+ res.status(500).json({ error: 'Internal server error', message: error.message });
282
+ }
283
+ });
284
+
285
+ app.listen(port, () => {
286
+ console.log(`Server running at http://localhost:${port}`);
287
+ if (!TMDB_API_KEY) {
288
+ console.warn('Warning: TMDB_API_KEY not set. TMDB features will not work.');
289
+ }
290
+ });