File size: 7,069 Bytes
194f0ef
3e27c05
194f0ef
5cfa0e3
 
 
 
 
 
 
 
 
 
 
54a84b7
5cfa0e3
 
 
 
3e27c05
 
 
 
 
194f0ef
3e27c05
 
 
194f0ef
 
3e27c05
 
 
 
 
 
 
194f0ef
 
3e27c05
 
 
194f0ef
3e27c05
 
194f0ef
 
3e27c05
 
5cfa0e3
 
 
3e27c05
 
 
 
 
5cfa0e3
3e27c05
 
 
5cfa0e3
3e27c05
 
 
 
194f0ef
3e27c05
 
5cfa0e3
3e27c05
 
5cfa0e3
3e27c05
 
 
 
 
 
 
 
194f0ef
 
3e27c05
194f0ef
3e27c05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194f0ef
 
 
 
3e27c05
 
 
 
5cfa0e3
3e27c05
 
5cfa0e3
3e27c05
 
 
 
194f0ef
 
3e27c05
194f0ef
 
 
 
3e27c05
 
 
 
194f0ef
5cfa0e3
3e27c05
 
 
 
 
 
 
 
 
194f0ef
3e27c05
 
 
194f0ef
3e27c05
 
 
194f0ef
3e27c05
194f0ef
 
 
 
3e27c05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194f0ef
 
3e27c05
 
 
5cfa0e3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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(/<font color="#008000"[^>]*>(\d+)<\/font>/i);
            const leechesMatch = seedLeechCell.html().match(/<font color="#8b0000"[^>]*>(\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 };