Create rutor.js
Browse files123456789101112131 unmodified line15161718192021222324251 unmodified line27282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120import 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() : '';}// β Formats size into human-readable formatfunction formatSize(bytes) {const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];if (bytes === 0) return '0 B';1 unmodified linereturn `${(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;}// β Removes the year from queries1 unmodified linereturn query.replace(/\(\d{4}\)/g, '').trim(); // Removes (YYYY)}// β Caches results to prevent duplicate requestsconst cache = new Map();// β Fetch data from Jackett API (The Pirate Bay)async function fetchRSSFeeds(searchQuery, type = 'movie') {const cleanedQuery = cleanQuery(searchQuery);console.log(`π Fetching RSS feed for: "${cleanedQuery}"`);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`;try {await new Promise(resolve => setTimeout(resolve, 2000)); // Prevents bot detectionconst 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}});if (!response.ok) {throw new Error(`β Failed to fetch Jackett API: ${response.status}`);}const jsonResponse = await response.text();const data = JSON.parse(jsonResponse);const results = data.Results || [];const streams = results.map((item) => {if (!item || !item.Title || !item.Guid) return null;// β Extract magnet link from "Guid"const magnetLink = extractMagnetFromGuid(item.Guid);if (!magnetLink) return null;// β Extract sizeconst size = item.Size ? formatSize(item.Size) : 'Unknown';// β Convert size to bytes for sortinglet sizeInBytes = item.Size || 0;// β Extract IMDb ID if availableconst imdbId = item.Imdb ? `tt${item.Imdb}` : null;return {magnetLink,websiteTitle: item.Title,quality: extractQuality(item.Title),size,source: item.Tracker || 'Unknown',infoHash: item.InfoHash || null,seeders: item.Seeders || 0,peers: item.Peers || 0,imdbId,mainFileSize: sizeInBytes,pubDate: item.PublishDate,categories: Array.isArray(item.CategoryDesc) ? item.CategoryDesc : [item.CategoryDesc]};}).filter(Boolean);// β Sort by quality and sizestreams.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) {return b.mainFileSize - a.mainFileSize;}return qualityDiff;});console.log(`β Processed ${streams.length} valid streams`);// β Store result in cachecache.set(cleanedQuery, streams);return streams;} catch (error) {console.error('β Error fetching from Jackett:', error);return [];}}// β Export function for Stremio addonexport { fetchRSSFeeds };12345678910111213141516171819202122232425261 unmodified line28293031323334353637381 unmodified line404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197import fetch from 'node-fetch';// β Maps quality numbers to standard formatsfunction mapQualityToStandard(quality, title) {if (!quality && !title) return '';// Check title for quality indicators firstconst 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 formatswitch (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 (fallback if sizeName not available)function formatSize(bytes) {const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];if (bytes === 0) return '0 B';1 unmodified linereturn `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;}// β 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 linereturn 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 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 Jacred feed for: "${cleanedQuery}"`);// Convert type format to match Jacred expectationsconst jacredType = type === 'series' ? 'serial' : 'movie';if (cache.has(cleanedQuery)) {console.log(`β‘ Using cached results for: "${cleanedQuery}"`);return cache.get(cleanedQuery);}// β Updated API URL for Jacred JSON endpointconst API_URL = `https://jacred.xyz/api/v1.0/torrents?search=${encodeURIComponent(cleanedQuery)}&apikey=null&exact=true`;try {await new Promise(resolve => setTimeout(resolve, 1000)); // Rate limitingconst 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': '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 Jacred API: ${response.status}`);}const data = await response.json();// β Handle both array and object responsesconst results = Array.isArray(data) ? data : (data.results || []);if (!Array.isArray(results)) {console.log('β No valid results array found in response');return [];}// β Process each torrent itemconst streams = results.map((item) => {if (!item || !item.magnet || !item.title) return null;// β Filter by content type if specifiedconst contentType = getContentType(item);if (type === 'movie' && contentType === 'series') return null;if (type === 'series' && contentType === 'movie') return null;// β Clean and decode Unicode in titleconst decodedTitle = decodeUnicode(item.title);const originalName = decodeUnicode(item.originalname || '');// β Use the best available title (prefer English if available)const displayTitle = originalName || decodedTitle;// β Extract quality from both numeric field and titleconst quality = mapQualityToStandard(item.quality, decodedTitle);// β Use provided size or calculate from bytesconst size = item.sizeName || formatSize(item.size || 0);// β 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.jsreturn {magnetLink,websiteTitle: displayTitle,originalTitle: decodedTitle,quality,size,source: item.tracker || 'rutor',infoHash: extractInfoHash(magnetLink),seeders: item.sid || 0, // Map from Jacred's 'sid' fieldpeers: item.pir || 0, // Map from Jacred's 'pir' fieldimdbId,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, then by size, then by seedersstreams.sort((a, b) => {// Quality priorityconst 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;}// Seeders priority (more seeders is better)return b.seeders - a.seeders;});console.log(`β Processed ${streams.length} valid streams from Jacred (Rutor)`);// β Store result in cachecache.set(cleanedQuery, streams);return streams;} catch (error) {console.error('β Error fetching from Jacred:', error);return [];}}// β Export function for Stremio addon (matches your server.js import)export { fetchRSSFeeds };
rutor.js+127-50