mikmc5 commited on
Commit
3752c89
·
verified ·
1 Parent(s): 6499d38

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +421 -40
server.js CHANGED
@@ -1,290 +1,671 @@
1
  import express from 'express';
2
- import { searchTorrents } from './solid.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
  });
 
1
  import express from 'express';
2
+
3
+ import { searchTorrents } from './bitsearch.js';
4
+
5
+
6
 
7
  const app = express();
8
+
9
  const port = process.env.PORT || 7860;
10
+
11
  const TMDB_API_KEY = 'f051e7366c6105ad4f9aafe4733d9dae';
12
+
13
  const TMDB_BASE_URL = 'https://api.themoviedb.org/3';
14
 
15
+
16
+
17
  app.use(express.json());
18
 
19
+
20
+
21
  function standardizeEpisodeFormat(query) {
22
+
23
  // Handle 1x01 format
24
+
25
  const altMatch = query.match(/^(.*?)(\d{1,2})x(\d{1,2})/i);
26
+
27
  if (altMatch) {
28
+
29
  const [_, title, season, episode] = altMatch;
30
+
31
  const paddedSeason = String(season).padStart(2, '0');
32
+
33
  const paddedEpisode = String(episode).padStart(2, '0');
34
+
35
  return `${title.trim()} S${paddedSeason}E${paddedEpisode}`;
36
+
37
  }
38
+
39
  return query;
40
+
41
+ }
42
+
43
+
44
+
45
+ function normalizeTitle(title) {
46
+
47
+ return title.toLowerCase()
48
+
49
+ .replace(/[^a-z0-9\s]/g, '')
50
+
51
+ .replace(/\s+/g, ' ')
52
+
53
+ .trim();
54
+
55
  }
56
 
57
+
58
+
59
  function isExactEpisodeMatch(torrentTitle, showTitle, seasonNum, episodeNum) {
60
+
61
  if (!torrentTitle || !showTitle) return false;
62
+
63
 
64
+
65
+ // Remove HTML tags and clean up title
66
+
67
+ torrentTitle = torrentTitle.replace(/<[^>]*>/g, '')
68
+
69
+ .replace(/\[.*?\]/g, '') // Remove bracketed content
70
+
71
+ .replace(/\(.*?\)/g, '') // Remove parenthetical content
72
+
73
  .replace(/\s+/g, ' ')
74
+
75
  .trim();
76
+
77
 
78
+
79
+ // Normalize the titles for comparison
80
+
81
  const normalizedTorrentTitle = torrentTitle.toLowerCase();
82
+
83
  const normalizedShowTitle = showTitle.toLowerCase().trim();
84
+
85
 
86
+
87
  // Split show title into significant words
88
+
89
  const showWords = normalizedShowTitle.split(' ')
90
+
91
  .filter(word => word.length > 2)
92
+
93
  .filter(word => !['the', 'and', 'or', 'in', 'on', 'at', 'to'].includes(word));
94
+
95
 
96
+
97
  const hasAllShowWords = showWords.every(word =>
98
+
99
  normalizedTorrentTitle.includes(word)
100
+
101
  );
102
+
103
 
104
+
105
  if (!hasAllShowWords) return false;
106
+
107
 
108
+
109
  // Format season and episode numbers
110
+
111
  const seasonStr = String(seasonNum).padStart(2, '0');
112
+
113
  const episodeStr = String(episodeNum).padStart(2, '0');
114
+
115
 
116
+
117
  // Common episode patterns
118
+
119
  const patterns = [
120
+
121
+ new RegExp(`s${seasonStr}e${episodeStr}`, 'i'), // S01E01
122
+
123
+ new RegExp(`${seasonNum}x${episodeStr}`, 'i'), // 1x01
124
+
125
+ new RegExp(`[^0-9]${seasonNum}${episodeStr}[^0-9]`, 'i'), // 101
126
+
127
+ new RegExp(`season\\s*${seasonNum}\\s*episode\\s*${episodeNum}`, 'i'), // Season 1 Episode 1
128
+
129
+ new RegExp(`s${seasonStr}\\.?e${episodeStr}`, 'i'), // S01.E01
130
+
131
+ new RegExp(`${seasonStr}${episodeStr}`, 'i'), // 0101
132
+
133
+ new RegExp(`^${seasonNum}${episodeStr}\\s`, 'i'), // 101 at start
134
+
135
+ new RegExp(`\\s${seasonNum}${episodeStr}$`, 'i'), // 101 at end
136
+
137
+ new RegExp(`episode\\s*${episodeNum}`, 'i') // Just episode number if title matches
138
+
139
  ];
140
+
141
 
142
+
143
  return patterns.some(pattern => pattern.test(normalizedTorrentTitle));
144
+
145
  }
146
 
147
+
148
+
149
  function isExactMovieMatch(torrentTitle, movieTitle, year) {
150
+
151
+ // Remove HTML tags and clean title
152
+
153
+ torrentTitle = torrentTitle.replace(/<[^>]*>/g, '')
154
+
155
+ .replace(/\[.*?\]/g, '') // Remove bracketed content
156
+
157
+ .replace(/\(.*?\)/g, '') // Remove parenthetical content
158
+
159
  .replace(/\s+/g, ' ')
160
+
161
  .trim();
162
+
163
 
164
+
165
+ // Normalize for comparison
166
+
167
  const normalizedTorrentTitle = torrentTitle.toLowerCase();
168
+
169
  const normalizedMovieTitle = movieTitle.toLowerCase();
170
+
171
 
172
+
173
+ // Split movie title into significant words and check if all are present
174
+
175
  const movieWords = normalizedMovieTitle.split(' ')
176
+
177
  .filter(word => word.length > 2)
178
+
179
  .filter(word => !['the', 'and', 'or', 'in', 'on', 'at', 'to'].includes(word));
180
+
181
 
182
+
183
  const hasAllMovieWords = movieWords.every(word =>
184
+
185
  normalizedTorrentTitle.includes(word)
186
+
187
  );
188
+
189
 
190
+
191
  if (!hasAllMovieWords) return false;
192
+
193
 
194
+
195
+ // Check year
196
+
197
  const yearMatch = torrentTitle.match(/(?:19|20)\d{2}/);
198
+
199
  return yearMatch && yearMatch[0] === year.toString();
200
+
201
  }
202
 
203
+
204
+
205
  async function getTMDBDetails(tmdbId, type = 'movie') {
206
+
207
  try {
208
+
209
  const response = await fetch(`${TMDB_BASE_URL}/${type}/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`);
210
+
211
  if (!response.ok) throw new Error(`TMDB API error: ${response.status}`);
212
+
213
  return await response.json();
214
+
215
  } catch (error) {
216
+
217
  console.error('TMDB fetch error:', error);
218
+
219
  return null;
220
+
221
  }
222
+
223
  }
224
 
225
+
226
+
227
  async function getTVShowDetails(tmdbId, seasonNum, episodeNum) {
228
+
229
  try {
 
 
 
 
230
 
231
+ // Get basic show info
232
+
233
+ const showResponse = await fetch(
234
+
235
+ `${TMDB_BASE_URL}/tv/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`
236
+
237
+ );
238
+
239
+ if (!showResponse.ok) throw new Error(`TMDB API error: ${showResponse.status}`);
240
+
241
+ const showData = await showResponse.json();
242
+
243
+
244
+
245
+ // Get specific episode info
246
+
247
+ const episodeResponse = await fetch(
248
+
249
+ `${TMDB_BASE_URL}/tv/${tmdbId}/season/${seasonNum}/episode/${episodeNum}?api_key=${TMDB_API_KEY}`
250
+
251
+ );
252
+
253
+ if (!episodeResponse.ok) throw new Error(`TMDB API error: ${episodeResponse.status}`);
254
+
255
+ const episodeData = await episodeResponse.json();
256
+
257
 
 
 
 
 
258
 
259
  return {
260
+
261
  showTitle: showData.name,
262
+
263
  episodeTitle: episodeData.name,
264
+
265
  seasonNumber: seasonNum,
266
+
267
  episodeNumber: episodeNum,
268
+
269
  airDate: episodeData.air_date,
270
+
271
  imdbId: showData.external_ids?.imdb_id
272
+
273
  };
274
+
275
  } catch (error) {
276
+
277
  console.error('TMDB fetch error:', error);
278
+
279
  return null;
280
+
281
  }
282
+
283
  }
284
 
285
+
286
+
287
  async function handleSearch({ query, type }) {
288
+
289
  if (!query) throw new Error('Missing required parameter: query');
290
+
291
  if (!['movie', 'series'].includes(type)) throw new Error('Invalid type. Must be either "movie" or "series"');
292
 
293
+
294
+
295
  let searchQuery = query;
296
+
297
  let exactMatchParams = {};
298
+
299
  let tmdbData = null;
300
 
301
+
302
+
303
  if (type === 'series') {
304
+
305
+ // Handle TMDB ID format: "tmdb:12345:1:1" (show_id:season:episode)
306
+
307
  const tmdbMatch = query.match(/^tmdb:(\d+):(\d+):(\d+)$/);
308
+
309
  if (tmdbMatch) {
310
+
311
  const [_, tmdbId, seasonNum, episodeNum] = tmdbMatch;
312
+
313
  tmdbData = await getTVShowDetails(tmdbId, parseInt(seasonNum), parseInt(episodeNum));
314
+
315
  if (tmdbData) {
316
+
317
  exactMatchParams = {
318
+
319
  title: tmdbData.showTitle,
320
+
321
  season: parseInt(seasonNum),
322
+
323
  episode: parseInt(episodeNum)
324
+
325
  };
326
+
327
+ // Try multiple search patterns
328
+
329
+ const searchPatterns = [
330
+
331
+ `${tmdbData.showTitle} S${String(seasonNum).padStart(2, '0')}E${String(episodeNum).padStart(2, '0')}`,
332
+
333
+ `${tmdbData.showTitle} ${seasonNum}x${String(episodeNum).padStart(2, '0')}`,
334
+
335
+ `${tmdbData.showTitle} Season ${seasonNum} Episode ${episodeNum}`,
336
+
337
+ tmdbData.showTitle // Try just the show name if specific episode search fails
338
+
339
+ ];
340
+
341
+
342
+
343
+ // Try each search pattern until we get results
344
+
345
+ for (const pattern of searchPatterns) {
346
+
347
+ const results = await searchTorrents(pattern, type);
348
+
349
+ if (results.length > 0) {
350
+
351
+ searchQuery = pattern;
352
+
353
+ break;
354
+
355
+ }
356
+
357
+ }
358
+
359
+ if (!searchQuery) {
360
+
361
+ searchQuery = searchPatterns[0]; // Default to first pattern if none worked
362
+
363
+ }
364
+
365
  }
366
+
367
  }
368
+
369
+ // Handle IMDB ID format: "tt1234567:1:1" (imdb_id:season:episode)
370
+
371
  else if (query.startsWith('tt')) {
372
+
373
  const imdbMatch = query.match(/^(tt\d+):(\d+):(\d+)$/);
374
+
375
  if (imdbMatch) {
376
+
377
  const [_, imdbId, seasonNum, episodeNum] = imdbMatch;
378
+
379
+ // First get TMDB ID from IMDB ID
380
+
381
  const findResponse = await fetch(
382
+
383
  `${TMDB_BASE_URL}/find/${imdbId}?api_key=${TMDB_API_KEY}&external_source=imdb_id`
384
+
385
  );
386
+
387
  if (findResponse.ok) {
388
+
389
  const findData = await findResponse.json();
390
+
391
+ if (findData.tv_results && findData.tv_results[0]) {
392
+
393
  const tmdbId = findData.tv_results[0].id;
394
+
395
  tmdbData = await getTVShowDetails(tmdbId, parseInt(seasonNum), parseInt(episodeNum));
396
+
397
  if (tmdbData) {
398
+
399
  exactMatchParams = {
400
+
401
  title: tmdbData.showTitle,
402
+
403
  season: parseInt(seasonNum),
404
+
405
  episode: parseInt(episodeNum)
406
+
407
  };
408
+
409
  searchQuery = `${tmdbData.showTitle} S${String(seasonNum).padStart(2, '0')}E${String(episodeNum).padStart(2, '0')}`;
410
+
411
  }
412
+
413
  }
414
+
415
  }
416
+
417
  }
418
+
419
  }
420
+
421
+ // Handle text formats
422
+
423
  else {
424
+
425
+ // Convert 1x01 format to S01E01
426
+
427
  searchQuery = standardizeEpisodeFormat(query);
428
+
429
+
430
+
431
+ // Try to extract season/episode info
432
+
433
  const seasonEpisodeMatch = searchQuery.match(/^(.*?)S(\d{1,2})E(\d{1,2})/i);
434
+
435
  if (seasonEpisodeMatch) {
436
+
437
  exactMatchParams = {
438
+
439
  title: seasonEpisodeMatch[1].trim(),
440
+
441
  season: parseInt(seasonEpisodeMatch[2]),
442
+
443
  episode: parseInt(seasonEpisodeMatch[3])
444
+
445
  };
446
+
447
  }
448
+
449
  }
450
+
451
  } else if (type === 'movie') {
452
+
453
  // Handle TMDB ID format
454
+
455
  if (query.startsWith('tmdb:')) {
456
+
457
  const tmdbId = query.replace('tmdb:', '');
458
+
459
  tmdbData = await getTMDBDetails(tmdbId, 'movie');
460
+
461
  if (tmdbData) {
462
+
463
  exactMatchParams = {
464
+
465
  title: tmdbData.title,
466
+
467
  year: new Date(tmdbData.release_date).getFullYear()
468
+
469
  };
470
+
471
+ searchQuery = `${tmdbData.title} ${exactMatchParams.year}`;
472
+
473
  }
474
+
475
  }
476
+
477
  // Handle IMDB ID format
478
+
479
  else if (query.startsWith('tt')) {
480
+
481
  const findResponse = await fetch(
482
+
483
  `${TMDB_BASE_URL}/find/${query}?api_key=${TMDB_API_KEY}&external_source=imdb_id`
484
+
485
  );
486
+
487
  if (findResponse.ok) {
488
+
489
  const findData = await findResponse.json();
490
+
491
+ if (findData.movie_results && findData.movie_results[0]) {
492
+
493
  tmdbData = findData.movie_results[0];
494
+
495
  exactMatchParams = {
496
+
497
  title: tmdbData.title,
498
+
499
  year: new Date(tmdbData.release_date).getFullYear()
500
+
501
  };
502
+
503
+ searchQuery = `${tmdbData.title} ${exactMatchParams.year}`;
504
+
505
  }
506
+
507
  }
508
+
509
  }
510
+
511
+ // Handle text format with year
512
+
513
  else {
514
+
515
+ const movieYearMatch = query.match(/^(.+?)(?:\s+|$)(\d{4})$/);
516
+
517
  if (movieYearMatch) {
518
+
519
  exactMatchParams = {
520
+
521
  title: movieYearMatch[1].trim(),
522
+
523
+ year: parseInt(movieYearMatch[2])
524
+
525
  };
526
+
527
  }
528
+
529
  }
530
+
531
  }
532
 
533
+
534
+
535
+ let results = await searchTorrents(searchQuery, type);
536
+
537
+
538
 
539
  // Filter results based on exact match parameters
540
+
541
  if (type === 'series' && exactMatchParams.season !== undefined) {
542
+
543
  results = results.filter(result =>
544
+
545
  isExactEpisodeMatch(
546
+
547
+ result.title || result.websiteTitle,
548
+
549
  exactMatchParams.title,
550
+
551
  exactMatchParams.season,
552
+
553
  exactMatchParams.episode
554
+
555
  )
556
+
557
  );
558
+
559
  } else if (type === 'movie' && exactMatchParams.year) {
560
+
561
  results = results.filter(result =>
562
+
563
  isExactMovieMatch(
564
+
565
+ result.title || result.websiteTitle,
566
+
567
  exactMatchParams.title,
568
+
569
  exactMatchParams.year
570
+
571
  )
572
+
573
  );
574
+
575
  }
576
 
577
+
578
+
579
+ // Sort results
580
+
581
+ results.sort((a, b) => {
582
+
583
+ const qualityOrder = { '2160p': 4, '4k': 4, '1080p': 3, '720p': 2 };
584
+
585
+ return (qualityOrder[b.quality] || 0) - (qualityOrder[a.quality] || 0) || b.seeders - a.seeders;
586
+
587
+ });
588
+
589
+
590
+
591
  return {
592
+
593
  query: searchQuery,
594
+
595
  originalQuery: query,
596
+
597
  type,
598
+
599
  tmdbData,
600
+
601
  results: results.map(result => ({
602
+
603
+ title: result.title || result.websiteTitle,
604
+
605
+ filename: result.filename,
606
+
607
  quality: result.quality,
608
+
609
  size: result.size,
610
+
611
+ seeders: result.seeders,
612
+
613
+ leechers: result.leechers,
614
+
615
  magnetLink: result.magnetLink
616
+
617
  }))
618
+
619
  };
620
+
621
  }
622
 
623
+
624
+
625
  app.get('/api/search', async (req, res) => {
626
+
627
  try {
628
+
629
  const result = await handleSearch({ query: req.query.query, type: req.query.type });
630
+
631
  res.json(result);
632
+
633
  } catch (error) {
634
+
635
  res.status(500).json({ error: 'Internal server error', message: error.message });
636
+
637
  }
638
+
639
  });
640
 
641
+
642
+
643
  app.post('/api/search', async (req, res) => {
644
+
645
  try {
646
+
647
  const result = await handleSearch(req.body);
648
+
649
  res.json(result);
650
+
651
  } catch (error) {
652
+
653
  res.status(500).json({ error: 'Internal server error', message: error.message });
654
+
655
  }
656
+
657
  });
658
 
659
+
660
+
661
  app.listen(port, () => {
662
+
663
  console.log(`Server running at http://localhost:${port}`);
664
+
665
  if (!TMDB_API_KEY) {
666
+
667
  console.warn('Warning: TMDB_API_KEY not set. TMDB features will not work.');
668
+
669
  }
670
+
671
  });