import fetch from 'node-fetch'; import fs from 'fs'; import readTorrent from 'read-torrent'; import os from 'os'; import path from 'path'; const JACKETT_API_URL = 'http://82.172.152.9:9117/api/v2.0/indexers/all/results'; const JACKETT_API_KEY = process.env.JACKETT_API_KEY || 'kptut9ad0fqgllyeykn27dhr9p6cd3hq'; /** * Fetch torrents from Jackett API, parse results, and return valid streams. */ async function fetchRSSFeeds(query) { // Construct API URL with provided query and other parameters const apiUrl = `${JACKETT_API_URL}?apikey=${JACKETT_API_KEY}&Query=${encodeURIComponent(query)}` + `&Category%5B%5D=2000&Category%5B%5D=5000&Category%5B%5D=8000&Category%5B%5D=100012` + `&Category%5B%5D=100013&Category%5B%5D=100014&Category%5B%5D=100015&Category%5B%5D=100026` + `&Category%5B%5D=100027&Category%5B%5D=100032&Category%5B%5D=100037&Category%5B%5D=100043` + `&Category%5B%5D=100047&Tracker%5B%5D=torrentleech&cache=false`; console.log('🔍 Requesting Jackett API:', apiUrl); try { const response = await fetch(apiUrl); if (!response.ok) throw new Error(`Failed to fetch from Jackett: ${response.status}`); const jsonData = await response.json(); console.log('📄 Jackett API Response:', JSON.stringify(jsonData, null, 2)); // Debugging output if (!jsonData.Results || jsonData.Results.length === 0) { console.log('❌ No torrents found.'); return []; } console.log(`✅ Found ${jsonData.Results.length} torrents`); // Process each result and try to fetch the magnet link const torrentResults = await Promise.all( jsonData.Results.map(async (item) => { if (!item.Title || !item.Guid) return null; // Use "Guid" to fetch the torrent let magnetLink = item.MagnetUri; if (!magnetLink) { magnetLink = await fetchMagnetFromTorrent(item.Guid); // Using the Guid URL to fetch the .torrent file } if (!magnetLink) { console.warn(`⚠️ No magnet link found for: ${item.Title}`); return null; } return { title: item.Title, magnetLink, quality: extractQuality(item.Title), size: formatSize(item.Size), seeders: item.Seeders || 0, leechers: item.Peers || 0, source: item.Tracker, details: item.Details }; }) ); const validStreams = torrentResults.filter(Boolean); console.log(`✅ Processed ${validStreams.length} valid streams`); return validStreams; } catch (error) { console.error('❌ Error fetching torrents:', error); return []; } } /** * Fetch and parse magnet link from a .torrent file. * The torrent file URL is fetched from `Guid`. */ async function fetchMagnetFromTorrent(torrentUrl) { try { console.log(`📥 Fetching .torrent file from: ${torrentUrl}`); // Download the .torrent file from the provided URL (Guid) const response = await fetch(torrentUrl); if (!response.ok) throw new Error(`Failed to fetch torrent file: ${response.status}`); const buffer = await response.buffer(); const tempFilePath = path.join(os.tmpdir(), 'downloaded.torrent'); // Save the .torrent file to a temporary path fs.writeFileSync(tempFilePath, buffer); return new Promise((resolve, reject) => { // Read the .torrent file and extract magnet link readTorrent(tempFilePath, (err, torrent) => { if (err) { console.error('❌ Error reading .torrent file:', err); reject(null); } else { // If magnet link exists, use it, otherwise create it from the info hash resolve(torrent.magnet || `magnet:?xt=urn:btih:${torrent.infoHash}`); } }); }); } catch (error) { console.error('❌ Error fetching magnet link:', error); return null; } } /** * Extract quality information from the title. */ function extractQuality(title) { const qualityMatch = title.match(/\b(2160p|1080p|720p|4k|uhd|hdr|blu[- ]?ray|webrip|brrip|hdtv)\b/i); return qualityMatch ? qualityMatch[1].toLowerCase().replace(/[- ]/g, '') : 'unknown'; } /** * Convert size from bytes to human-readable format. */ function formatSize(size) { if (!size) return 'Unknown'; const i = Math.floor(Math.log(size) / Math.log(1024)); const units = ['B', 'KB', 'MB', 'GB', 'TB']; return `${(size / Math.pow(1024, i)).toFixed(2)} ${units[i]}`; } export { fetchRSSFeeds };