mikmc5 commited on
Commit
2e38ad5
Β·
verified Β·
1 Parent(s): f1c2db0

Create rutor.js

Browse files
Files changed (1) hide show
  1. rutor.js +127 -50
rutor.js CHANGED
@@ -1,13 +1,26 @@
1
  import fetch from 'node-fetch';
2
 
3
- // βœ… Extracts video quality from title
4
- function extractQuality(title) {
5
- if (!title) return '';
6
- const qualityMatch = title.match(/\b(2160p|1080p|720p|4k|uhd|WEBRip|BluRay|REMUX)\b/i);
7
- return qualityMatch ? qualityMatch[1].toLowerCase() : '';
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  }
9
 
10
- // βœ… Formats size into human-readable format
11
  function formatSize(bytes) {
12
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
13
  if (bytes === 0) return '0 B';
@@ -15,11 +28,11 @@ function formatSize(bytes) {
15
  return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;
16
  }
17
 
18
- // βœ… Extracts magnet link from "Guid"
19
- function extractMagnetFromGuid(guid) {
20
- if (!guid) return null;
21
- const magnetMatch = guid.match(/magnet:\?xt=urn:btih:[A-Za-z0-9]+[^"'\s]*/);
22
- return magnetMatch ? magnetMatch[0] : null;
23
  }
24
 
25
  // βœ… Removes the year from queries
@@ -27,94 +40,158 @@ function cleanQuery(query) {
27
  return query.replace(/\(\d{4}\)/g, '').trim(); // Removes (YYYY)
28
  }
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  // βœ… Caches results to prevent duplicate requests
31
  const cache = new Map();
32
 
33
- // βœ… Fetch data from Jackett API (The Pirate Bay)
 
34
  async function fetchRSSFeeds(searchQuery, type = 'movie') {
35
  const cleanedQuery = cleanQuery(searchQuery);
36
- console.log(`πŸ”„ Fetching RSS feed for: "${cleanedQuery}"`);
 
 
 
37
 
38
  if (cache.has(cleanedQuery)) {
39
  console.log(`⚑ Using cached results for: "${cleanedQuery}"`);
40
  return cache.get(cleanedQuery);
41
  }
42
 
43
- const API_URL = `http://81.150.31.153:9117/api/v2.0/indexers/all/results?apikey=1c99yaajym29qbrb715q3me1qwj2d42g&Query=${encodeURIComponent(cleanedQuery)}&Category%5B%5D=2000&Category%5B%5D=2020&Category%5B%5D=2030&Category%5B%5D=2040&Category%5B%5D=2045&Category%5B%5D=5000&Category%5B%5D=5040&Category%5B%5D=5045&Category%5B%5D=5050&Category%5B%5D=8000&Tracker%5B%5D=btdirectory&Tracker%5B%5D=thepiratebay&_=1744900417403`;
 
44
 
45
  try {
46
- await new Promise(resolve => setTimeout(resolve, 2000)); // Prevents bot detection
47
 
48
  const response = await fetch(API_URL, {
49
  headers: {
50
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
51
- 'Accept-Language': 'en-US,en;q=0.9',
52
- 'Connection': 'keep-alive',
53
- 'Cookie': 'Jackett=your_cookie_here' // βœ… Use your Jackett cookie if required
 
54
  }
55
  });
56
 
57
  if (!response.ok) {
58
- throw new Error(`❌ Failed to fetch Jackett API: ${response.status}`);
59
  }
60
 
61
- const jsonResponse = await response.text();
62
- const data = JSON.parse(jsonResponse);
63
- const results = data.Results || [];
 
 
 
 
 
 
64
 
 
65
  const streams = results.map((item) => {
66
- if (!item || !item.Title || !item.Guid) return null;
 
 
 
 
 
67
 
68
- // βœ… Extract magnet link from "Guid"
69
- const magnetLink = extractMagnetFromGuid(item.Guid);
70
- if (!magnetLink) return null;
 
 
 
71
 
72
- // βœ… Extract size
73
- const size = item.Size ? formatSize(item.Size) : 'Unknown';
74
 
75
- // βœ… Convert size to bytes for sorting
76
- let sizeInBytes = item.Size || 0;
77
 
78
- // βœ… Extract IMDb ID if available
79
- const imdbId = item.Imdb ? `tt${item.Imdb}` : null;
80
 
 
 
 
 
81
  return {
82
  magnetLink,
83
- websiteTitle: item.Title,
84
- quality: extractQuality(item.Title),
 
85
  size,
86
- source: item.Tracker || 'Unknown',
87
- infoHash: item.InfoHash || null,
88
- seeders: item.Seeders || 0,
89
- peers: item.Peers || 0,
90
  imdbId,
91
- mainFileSize: sizeInBytes,
92
- pubDate: item.PublishDate,
93
- categories: Array.isArray(item.CategoryDesc) ? item.CategoryDesc : [item.CategoryDesc]
 
 
 
 
 
 
94
  };
95
  }).filter(Boolean);
96
 
97
- // βœ… Sort by quality and size
98
  streams.sort((a, b) => {
99
- const qualityOrder = { '2160p': 4, '4k': 4, 'uhd': 4, '1080p': 3, '720p': 2 };
100
- const qualityDiff = (qualityOrder[b.quality] || 0) - (qualityOrder[a.quality] || 0);
101
- if (qualityDiff === 0) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  return b.mainFileSize - a.mainFileSize;
103
  }
104
- return qualityDiff;
 
 
105
  });
106
 
107
- console.log(`βœ… Processed ${streams.length} valid streams`);
108
 
109
  // βœ… Store result in cache
110
  cache.set(cleanedQuery, streams);
111
 
112
  return streams;
113
  } catch (error) {
114
- console.error('❌ Error fetching from Jackett:', error);
115
  return [];
116
  }
117
  }
118
 
119
- // βœ… Export function for Stremio addon
120
- export { fetchRSSFeeds };
 
1
  import fetch from 'node-fetch';
2
 
3
+ // βœ… Maps quality numbers to standard formats
4
+ function mapQualityToStandard(quality, title) {
5
+ if (!quality && !title) return '';
6
+
7
+ // Check title for quality indicators first
8
+ const titleQuality = title ? title.match(/\b(2160p|1080p|720p|4k|uhd|WEBRip|BluRay|REMUX|BDRemux|BDRip|WEB-DL)\b/i) : null;
9
+ if (titleQuality) {
10
+ return titleQuality[1].toLowerCase();
11
+ }
12
+
13
+ // Map numeric quality to standard format
14
+ switch (quality) {
15
+ case 2160: return '4k';
16
+ case 1080: return '1080p';
17
+ case 720: return '720p';
18
+ case 480: return '480p';
19
+ default: return quality ? `${quality}p` : '';
20
+ }
21
  }
22
 
23
+ // βœ… Formats size into human-readable format (fallback if sizeName not available)
24
  function formatSize(bytes) {
25
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
26
  if (bytes === 0) return '0 B';
 
28
  return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;
29
  }
30
 
31
+ // βœ… Extracts info hash from magnet link
32
+ function extractInfoHash(magnetLink) {
33
+ if (!magnetLink) return null;
34
+ const match = magnetLink.match(/btih:([a-fA-F0-9]+)/);
35
+ return match ? match[1] : null;
36
  }
37
 
38
  // βœ… Removes the year from queries
 
40
  return query.replace(/\(\d{4}\)/g, '').trim(); // Removes (YYYY)
41
  }
42
 
43
+ // βœ… Decodes Unicode escape sequences
44
+ function decodeUnicode(str) {
45
+ if (!str) return '';
46
+ return str.replace(/\\u[\dA-F]{4}/gi, (match) => {
47
+ return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
48
+ });
49
+ }
50
+
51
+ // βœ… Determines content type for filtering
52
+ function getContentType(item) {
53
+ if (item.types && item.types.includes('serial')) return 'series';
54
+ if (item.types && item.types.includes('movie')) return 'movie';
55
+ if (item.seasons && item.seasons.length > 0) return 'series';
56
+ return 'movie'; // default
57
+ }
58
+
59
  // βœ… Caches results to prevent duplicate requests
60
  const cache = new Map();
61
 
62
+ // βœ… Fetch data from Jacred API (Rutor) - JSON format
63
+ // Updated to match your server.js expected function signature
64
  async function fetchRSSFeeds(searchQuery, type = 'movie') {
65
  const cleanedQuery = cleanQuery(searchQuery);
66
+ console.log(`πŸ”„ Fetching Jacred feed for: "${cleanedQuery}"`);
67
+
68
+ // Convert type format to match Jacred expectations
69
+ const jacredType = type === 'series' ? 'serial' : 'movie';
70
 
71
  if (cache.has(cleanedQuery)) {
72
  console.log(`⚑ Using cached results for: "${cleanedQuery}"`);
73
  return cache.get(cleanedQuery);
74
  }
75
 
76
+ // βœ… Updated API URL for Jacred JSON endpoint
77
+ const API_URL = `https://jacred.xyz/api/v1.0/torrents?search=${encodeURIComponent(cleanedQuery)}&apikey=null&exact=true`;
78
 
79
  try {
80
+ await new Promise(resolve => setTimeout(resolve, 1000)); // Rate limiting
81
 
82
  const response = await fetch(API_URL, {
83
  headers: {
84
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
85
+ 'Accept': 'application/json, text/javascript, */*; q=0.01',
86
+ 'Accept-Language': 'en-GB,en;q=0.9',
87
+ 'Cache-Control': 'no-cache',
88
+ 'Pragma': 'no-cache'
89
  }
90
  });
91
 
92
  if (!response.ok) {
93
+ throw new Error(`❌ Failed to fetch Jacred API: ${response.status}`);
94
  }
95
 
96
+ const data = await response.json();
97
+
98
+ // βœ… Handle both array and object responses
99
+ const results = Array.isArray(data) ? data : (data.results || []);
100
+
101
+ if (!Array.isArray(results)) {
102
+ console.log('❌ No valid results array found in response');
103
+ return [];
104
+ }
105
 
106
+ // βœ… Process each torrent item
107
  const streams = results.map((item) => {
108
+ if (!item || !item.magnet || !item.title) return null;
109
+
110
+ // βœ… Filter by content type if specified
111
+ const contentType = getContentType(item);
112
+ if (type === 'movie' && contentType === 'series') return null;
113
+ if (type === 'series' && contentType === 'movie') return null;
114
 
115
+ // βœ… Clean and decode Unicode in title
116
+ const decodedTitle = decodeUnicode(item.title);
117
+ const originalName = decodeUnicode(item.originalname || '');
118
+
119
+ // βœ… Use the best available title (prefer English if available)
120
+ const displayTitle = originalName || decodedTitle;
121
 
122
+ // βœ… Extract quality from both numeric field and title
123
+ const quality = mapQualityToStandard(item.quality, decodedTitle);
124
 
125
+ // βœ… Use provided size or calculate from bytes
126
+ const size = item.sizeName || formatSize(item.size || 0);
127
 
128
+ // βœ… Clean magnet link (decode HTML entities)
129
+ const magnetLink = item.magnet.replace(/\\u0026/g, '&');
130
 
131
+ // βœ… Extract IMDb ID if available (not typically in Rutor)
132
+ const imdbId = null;
133
+
134
+ // βœ… Return in format expected by your server.js
135
  return {
136
  magnetLink,
137
+ websiteTitle: displayTitle,
138
+ originalTitle: decodedTitle,
139
+ quality,
140
  size,
141
+ source: item.tracker || 'rutor',
142
+ infoHash: extractInfoHash(magnetLink),
143
+ seeders: item.sid || 0, // Map from Jacred's 'sid' field
144
+ peers: item.pir || 0, // Map from Jacred's 'pir' field
145
  imdbId,
146
+ mainFileSize: item.size || 0,
147
+ pubDate: item.createTime || null,
148
+ categories: item.types || ['movie'],
149
+ originalLink: item.url,
150
+ releaseYear: item.relased || null,
151
+ videoType: item.videotype || 'sdr',
152
+ seasons: item.seasons || [],
153
+ voices: item.voices || [],
154
+ contentType: contentType
155
  };
156
  }).filter(Boolean);
157
 
158
+ // βœ… Sort by quality, then by size, then by seeders
159
  streams.sort((a, b) => {
160
+ // Quality priority
161
+ const qualityOrder = {
162
+ '4k': 6, '2160p': 6, 'uhd': 6,
163
+ '1080p': 5, 'remux': 5, 'bdremux': 5,
164
+ '720p': 4, 'bdrip': 3, 'web-dl': 3, 'webrip': 2,
165
+ '480p': 1
166
+ };
167
+
168
+ const aQuality = qualityOrder[a.quality.toLowerCase()] || 0;
169
+ const bQuality = qualityOrder[b.quality.toLowerCase()] || 0;
170
+
171
+ if (bQuality !== aQuality) {
172
+ return bQuality - aQuality;
173
+ }
174
+
175
+ // Size priority (larger is better for same quality)
176
+ if (b.mainFileSize !== a.mainFileSize) {
177
  return b.mainFileSize - a.mainFileSize;
178
  }
179
+
180
+ // Seeders priority (more seeders is better)
181
+ return b.seeders - a.seeders;
182
  });
183
 
184
+ console.log(`βœ… Processed ${streams.length} valid streams from Jacred (Rutor)`);
185
 
186
  // βœ… Store result in cache
187
  cache.set(cleanedQuery, streams);
188
 
189
  return streams;
190
  } catch (error) {
191
+ console.error('❌ Error fetching from Jacred:', error);
192
  return [];
193
  }
194
  }
195
 
196
+ // βœ… Export function for Stremio addon (matches your server.js import)
197
+ export { fetchRSSFeeds };