import fetch from 'node-fetch'; import * as cheerio from 'cheerio'; // ============================== // sanitizeTitle: Clean Cyrillic & Noise // ============================== function sanitizeTitle(rawTitle) { return rawTitle .replace(/[\u0400-\u04FF]+/g, '') // Remove Cyrillic .replace(/[^\x00-\x7F]+/g, '') // Remove non-ASCII remnants .replace(/\[\s*[\u0400-\u04FF\d]+\s*[\u0400-\u04FF]*\]/g, match => { const digits = match.match(/\d+/); return digits ? `[${digits[0]}]` : ''; }) .replace(/^[\s/\\]+/, '') // Remove leading slashes or backslashes .replace(/\s{2,}/g, ' ') // Collapse multiple spaces .trim(); } // ============================== // fetchMegapeerTorrents: Main Export Function // ============================== async function fetchMegapeerTorrents(searchQuery) { console.log(`\nšŸ”„ Fetching Megapeer results for: ${searchQuery}`); const encodedQuery = encodeURIComponent(searchQuery); const searchUrl = `https://megapeer.vip/browse.php?search=${encodedQuery}&age=&cat=0&stype=0&sort=0&ascdesc=0`; console.log(`šŸ“” Fetching: ${searchUrl}`); try { const response = await fetch(searchUrl, { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/134.0.0.0 Safari/537.36', 'Accept': 'text/html', 'Referer': 'https://megapeer.vip/', }, method: 'GET', }); if (!response.ok) { throw new Error(`Failed to fetch from Megapeer: ${response.status}`); } const pageHtml = await response.text(); const $ = cheerio.load(pageHtml); const torrents = []; $('tr.table_fon').each((_, element) => { const titleElement = $(element).find('a.url'); const rawTitle = titleElement.text().trim(); const sanitizedTitle = sanitizeTitle(rawTitle); const torrentPage = titleElement.attr('href'); const downloadLink = $(element).find('a[href^="/download/"]').attr('href'); const size = $(element).find('td[align="right"]').text().trim(); const dateElement = $(element).find('td').first(); const date = dateElement.text().trim(); const seedLeechCell = $(element).find('td[align="center"]'); const seedsMatch = seedLeechCell.html().match(/]*>(\d+)<\/font>/i); const leechesMatch = seedLeechCell.html().match(/]*>(\d+)<\/font>/i); const seeds = seedsMatch ? parseInt(seedsMatch[1]) : 0; const leeches = leechesMatch ? parseInt(leechesMatch[1]) : 0; if (!torrentPage) return; const torrentPageUrl = `https://megapeer.vip${torrentPage}`; const directDownloadUrl = `https://megapeer.vip${downloadLink}`; const quality = extractQuality(sanitizedTitle); torrents.push({ title: sanitizedTitle, quality, size, date, seeds, leeches, torrentPageUrl, directDownloadUrl }); }); const completedTorrents = await Promise.all( torrents.map(async (torrent) => { try { const magnetLink = await extractMagnetLink(torrent.torrentPageUrl); return { websiteTitle: torrent.title, quality: torrent.quality, size: torrent.size, date: torrent.date, seeds: torrent.seeds, leeches: torrent.leeches, mainFileSize: parseSizeToBytes(torrent.size), torrentPageUrl: torrent.torrentPageUrl, directDownloadUrl: torrent.directDownloadUrl, magnetLink: magnetLink || null, }; } catch (error) { console.error(`Error processing torrent ${torrent.title}:`, error); return null; } }) ); const validTorrents = completedTorrents.filter(Boolean); validTorrents.sort((a, b) => { if (b.seeds !== a.seeds) return b.seeds - a.seeds; const qualityOrder = { '2160p': 4, '4k': 4, 'uhd': 4, '1080p': 3, '720p': 2 }; const qualityDiff = (qualityOrder[b.quality] || 0) - (qualityOrder[a.quality] || 0); return qualityDiff === 0 ? b.mainFileSize - a.mainFileSize : qualityDiff; }); console.log(`āœ… Processed ${validTorrents.length} valid torrents from Megapeer`); return validTorrents; } catch (error) { console.error('āŒ Error fetching from Megapeer:', error); return []; } } // ============================== // extractMagnetLink: Try to find magnet links (if available) // ============================== async function extractMagnetLink(torrentPageUrl) { try { await new Promise(resolve => setTimeout(resolve, Math.random() * 2000 + 1000)); const response = await fetch(torrentPageUrl, { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/134.0.0.0 Safari/537.36', 'Accept': 'text/html', 'Referer': 'https://megapeer.vip/' }, method: 'GET', }); if (!response.ok) { throw new Error(`Failed to fetch torrent page: ${response.status}`); } const pageHtml = await response.text(); const magnetMatch = pageHtml.match(/href="(magnet:\?xt=urn:btih:[^"]+)"/); return magnetMatch ? magnetMatch[1] : null; } catch (error) { console.error('āŒ Error extracting magnet link:', error); return null; } } // ============================== // parseSizeToBytes: Convert Sizes for Sorting // ============================== function parseSizeToBytes(size) { if (!size) return 0; const sizeMatch = size.match(/([\d.]+)\s*(MB|GB|TB)/i); if (!sizeMatch) return 0; const [, value, unit] = sizeMatch; const multiplier = unit.toUpperCase() === 'TB' ? 1024 ** 4 : unit.toUpperCase() === 'GB' ? 1024 ** 3 : 1024 ** 2; return parseFloat(value) * multiplier; } // ============================== // extractQuality: Identify Quality from Title // ============================== function extractQuality(title) { if (!title) return ''; const qualityMatch = title.match(/\b(2160p|1080p|720p|4k|uhd)\b/i); return qualityMatch ? qualityMatch[1].toLowerCase() : ''; } // ============================== // Export for Server.js // ============================== export { fetchMegapeerTorrents };