import fetch from 'node-fetch'; // ✅ Maps quality numbers to standard formats function 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 (fallback if sizeName not available) function formatSize(bytes) { const sizes = ['B', 'KB', 'MB', 'GB', 'TB']; if (bytes === 0) return '0 B'; const i = Math.floor(Math.log(bytes) / Math.log(1024)); return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`; } // ✅ Extracts info hash from magnet link function extractInfoHash(magnetLink) { if (!magnetLink) return null; const match = magnetLink.match(/btih:([a-fA-F0-9]+)/); return match ? match[1] : null; } // ✅ Removes the year and brackets from queries function cleanQuery(query) { return query .replace(/\(\d{4}\)/g, '') // Removes (YYYY) .replace(/\[\d{4}\]/g, '') // Removes [YYYY] .replace(/\{\d{4}\}/g, '') // Removes {YYYY} .replace(/\s+/g, ' ') // Replace multiple spaces with single space .trim(); // Remove leading/trailing whitespace } // ✅ Decodes Unicode escape sequences function decodeUnicode(str) { if (!str) return ''; return str.replace(/\\u[\dA-F]{4}/gi, (match) => { return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16)); }); } // ✅ Enhanced content type detection to handle documentary types function getContentType(item) { if (!item.types || !Array.isArray(item.types)) return 'movie'; // default // Check for series-like content (including documentaries) const seriesTypes = ['serial', 'docuserial', 'tvshow', 'miniseries']; const movieTypes = ['movie', 'documovie', 'film']; // Check if any type indicates series content const hasSeriesType = item.types.some(type => seriesTypes.some(seriesType => type.toLowerCase().includes(seriesType.toLowerCase())) ); // Check if any type indicates movie content const hasMovieType = item.types.some(type => movieTypes.some(movieType => type.toLowerCase().includes(movieType.toLowerCase())) ); // Handle mixed types (like docuserial + documovie) if (hasSeriesType && hasMovieType) { // If it has seasons or episode info, treat as series if (item.seasons && item.seasons.length > 0) return 'series'; // Check title for episode patterns like "01-02 из 02" if (item.title && /\d+-\d+\s*из\s*\d+|\d+\s*of\s*\d+|episode|ep\s*\d+/i.test(item.title)) { return 'series'; } // Default to movie for mixed types without clear series indicators return 'movie'; } if (hasSeriesType) return 'series'; if (hasMovieType) return 'movie'; // Fallback: check for season info if (item.seasons && item.seasons.length > 0) return 'series'; return 'movie'; // default } // ✅ Caches results to prevent duplicate requests const cache = new Map(); // ✅ Fetch data from Jacred API (Rutor) - JSON format // Updated to match your server.js expected function signature async function fetchRSSFeeds(searchQuery, type = 'movie') { const cleanedQuery = cleanQuery(searchQuery); 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); } // ✅ 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, 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': '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 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.magnet || !item.title) return null; // ✅ Enhanced content type detection const contentType = getContentType(item); // ✅ Enhanced filtering logic - more flexible matching const shouldInclude = (() => { if (type === 'movie') { // Include movies and mixed content that defaults to movie return contentType === 'movie' || (item.types && item.types.includes('documovie')); } if (type === 'series') { // Include series and mixed content that has series indicators return contentType === 'series' || (item.types && item.types.includes('docuserial')); } return true; // If no specific type requested, include everything })(); if (!shouldInclude) 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 quality from both numeric field and title const quality = mapQualityToStandard(item.quality, decodedTitle); // ✅ Use provided size or calculate from bytes const 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.js return { magnetLink, websiteTitle: displayTitle, originalTitle: decodedTitle, quality, size, 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: 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 seeders streams.sort((a, b) => { // 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; } // Seeders priority (more seeders is better) return b.seeders - a.seeders; }); 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 Jacred:', error); return []; } } // ✅ Export function for Stremio addon (matches your server.js import) export { fetchRSSFeeds };