Create rutor.js
Browse files123456734567891011121314151617181920212210232425261 unmodified line282930181920212231323334353637381 unmodified line4041424344454647484950515253545556575859606133626364653666676869707172737475437677787946808182838451525385868788899091925893949561626396979899100101102103104105106107661081091101111121131146869701151161171181191201217273122123124757612512612778791281291301311321331341351368384137138139140868788891411421431441459192931461471481491501511521531541551561579715815999100101160161162163164165166167168169170171172173174175176177178104179180181182183107184185186187188189190114191192193194195119120196197import fetch from 'node-fetch';
// β
Extracts video quality from titlefunction extractQuality(title) { if (!title) return ''; const qualityMatch = title.match(/\b(2160p|1080p|720p|4k|uhd|WEBRip|BluRay|REMUX)\b/i); return qualityMatch ? qualityMatch[1].toLowerCase() : '';// β
Maps quality numbers to standard formatsfunction mapQualityToStandard(quality, title) { if (!quality && !title) return ''; // Check title for quality indicators first const titleQuality = title ? title.match(/\b(2160p|1080p|720p|4k|uhd|WEBRip|BluRay|REMUX|BDRemux|BDRip|WEB-DL)\b/i) : null; if (titleQuality) { return titleQuality[1].toLowerCase(); } // Map numeric quality to standard format switch (quality) { case 2160: return '4k'; case 1080: return '1080p'; case 720: return '720p'; case 480: return '480p'; default: return quality ? `${quality}p` : ''; }}
// β
Formats size into human-readable format// β
Formats size into human-readable format (fallback if sizeName not available)function formatSize(bytes) { const sizes = ['B', 'KB', 'MB', 'GB', 'TB']; if (bytes === 0) return '0 B';1 unmodified line return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;}
// β
Extracts magnet link from "Guid"function extractMagnetFromGuid(guid) { if (!guid) return null; const magnetMatch = guid.match(/magnet:\?xt=urn:btih:[A-Za-z0-9]+[^"'\s]*/); return magnetMatch ? magnetMatch[0] : null;// β
Extracts info hash from magnet linkfunction extractInfoHash(magnetLink) { if (!magnetLink) return null; const match = magnetLink.match(/btih:([a-fA-F0-9]+)/); return match ? match[1] : null;}
// β
Removes the year from queries1 unmodified line return query.replace(/\(\d{4}\)/g, '').trim(); // Removes (YYYY)}
// β
Decodes Unicode escape sequencesfunction decodeUnicode(str) { if (!str) return ''; return str.replace(/\\u[\dA-F]{4}/gi, (match) => { return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16)); });}
// β
Determines content type for filteringfunction getContentType(item) { if (item.types && item.types.includes('serial')) return 'series'; if (item.types && item.types.includes('movie')) return 'movie'; if (item.seasons && item.seasons.length > 0) return 'series'; return 'movie'; // default}
// β
Caches results to prevent duplicate requestsconst cache = new Map();
// β
Fetch data from Jackett API (The Pirate Bay)// β
Fetch data from Jacred API (Rutor) - JSON format// Updated to match your server.js expected function signatureasync function fetchRSSFeeds(searchQuery, type = 'movie') { const cleanedQuery = cleanQuery(searchQuery); console.log(`π Fetching RSS feed for: "${cleanedQuery}"`); console.log(`π Fetching Jacred feed for: "${cleanedQuery}"`);
// Convert type format to match Jacred expectations const jacredType = type === 'series' ? 'serial' : 'movie';
if (cache.has(cleanedQuery)) { console.log(`β‘ Using cached results for: "${cleanedQuery}"`); return cache.get(cleanedQuery); }
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`; // β
Updated API URL for Jacred JSON endpoint const API_URL = `https://jacred.xyz/api/v1.0/torrents?search=${encodeURIComponent(cleanedQuery)}&apikey=null&exact=true`;
try { await new Promise(resolve => setTimeout(resolve, 2000)); // Prevents bot detection await new Promise(resolve => setTimeout(resolve, 1000)); // Rate limiting
const response = await fetch(API_URL, { headers: { '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', 'Accept-Language': 'en-US,en;q=0.9', 'Connection': 'keep-alive', 'Cookie': 'Jackett=your_cookie_here' // β
Use your Jackett cookie if required 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Language': 'en-GB,en;q=0.9', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' } });
if (!response.ok) { throw new Error(`β Failed to fetch Jackett API: ${response.status}`); throw new Error(`β Failed to fetch Jacred API: ${response.status}`); }
const jsonResponse = await response.text(); const data = JSON.parse(jsonResponse); const results = data.Results || []; const data = await response.json(); // β
Handle both array and object responses const results = Array.isArray(data) ? data : (data.results || []); if (!Array.isArray(results)) { console.log('β No valid results array found in response'); return []; }
// β
Process each torrent item const streams = results.map((item) => { if (!item || !item.Title || !item.Guid) return null; if (!item || !item.magnet || !item.title) return null;
// β
Filter by content type if specified const contentType = getContentType(item); if (type === 'movie' && contentType === 'series') return null; if (type === 'series' && contentType === 'movie') return null;
// β
Extract magnet link from "Guid" const magnetLink = extractMagnetFromGuid(item.Guid); if (!magnetLink) return null; // β
Clean and decode Unicode in title const decodedTitle = decodeUnicode(item.title); const originalName = decodeUnicode(item.originalname || ''); // β
Use the best available title (prefer English if available) const displayTitle = originalName || decodedTitle;
// β
Extract size const size = item.Size ? formatSize(item.Size) : 'Unknown'; // β
Extract quality from both numeric field and title const quality = mapQualityToStandard(item.quality, decodedTitle);
// β
Convert size to bytes for sorting let sizeInBytes = item.Size || 0; // β
Use provided size or calculate from bytes const size = item.sizeName || formatSize(item.size || 0);
// β
Extract IMDb ID if available const imdbId = item.Imdb ? `tt${item.Imdb}` : null; // β
Clean magnet link (decode HTML entities) const magnetLink = item.magnet.replace(/\\u0026/g, '&');
// β
Extract IMDb ID if available (not typically in Rutor) const imdbId = null;
// β
Return in format expected by your server.js return { magnetLink, websiteTitle: item.Title, quality: extractQuality(item.Title), websiteTitle: displayTitle, originalTitle: decodedTitle, quality, size, source: item.Tracker || 'Unknown', infoHash: item.InfoHash || null, seeders: item.Seeders || 0, peers: item.Peers || 0, source: item.tracker || 'rutor', infoHash: extractInfoHash(magnetLink), seeders: item.sid || 0, // Map from Jacred's 'sid' field peers: item.pir || 0, // Map from Jacred's 'pir' field imdbId, mainFileSize: sizeInBytes, pubDate: item.PublishDate, categories: Array.isArray(item.CategoryDesc) ? item.CategoryDesc : [item.CategoryDesc] mainFileSize: item.size || 0, pubDate: item.createTime || null, categories: item.types || ['movie'], originalLink: item.url, releaseYear: item.relased || null, videoType: item.videotype || 'sdr', seasons: item.seasons || [], voices: item.voices || [], contentType: contentType }; }).filter(Boolean);
// β
Sort by quality and size // β
Sort by quality, then by size, then by seeders streams.sort((a, b) => { const qualityOrder = { '2160p': 4, '4k': 4, 'uhd': 4, '1080p': 3, '720p': 2 }; const qualityDiff = (qualityOrder[b.quality] || 0) - (qualityOrder[a.quality] || 0); if (qualityDiff === 0) { // Quality priority const qualityOrder = { '4k': 6, '2160p': 6, 'uhd': 6, '1080p': 5, 'remux': 5, 'bdremux': 5, '720p': 4, 'bdrip': 3, 'web-dl': 3, 'webrip': 2, '480p': 1 }; const aQuality = qualityOrder[a.quality.toLowerCase()] || 0; const bQuality = qualityOrder[b.quality.toLowerCase()] || 0; if (bQuality !== aQuality) { return bQuality - aQuality; } // Size priority (larger is better for same quality) if (b.mainFileSize !== a.mainFileSize) { return b.mainFileSize - a.mainFileSize; } return qualityDiff; // Seeders priority (more seeders is better) return b.seeders - a.seeders; });
console.log(`β
Processed ${streams.length} valid streams`); console.log(`β
Processed ${streams.length} valid streams from Jacred (Rutor)`);
// β
Store result in cache cache.set(cleanedQuery, streams);
return streams; } catch (error) { console.error('β Error fetching from Jackett:', error); console.error('β Error fetching from Jacred:', error); return []; }}
// β
Export function for Stremio addonexport { fetchRSSFeeds };// β
Export function for Stremio addon (matches your server.js import)export { fetchRSSFeeds };rutor.js+127-50