File size: 5,998 Bytes
81d2771
af50600
81d2771
af50600
 
81d2771
 
 
efe49f7
af50600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2806d2
 
efe49f7
af50600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
786b5a6
d2806d2
efe49f7
81d2771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2806d2
 
efe49f7
81d2771
 
 
 
ef2ad72
 
81d2771
af50600
 
 
81d2771
af50600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81d2771
 
 
af50600
81d2771
 
 
 
efe49f7
af50600
 
 
 
 
 
efe49f7
af50600
81d2771
 
 
 
d2806d2
efe49f7
 
 
 
81d2771
 
efe49f7
83699aa
c7b5706
af50600
 
 
 
 
 
 
 
81d2771
 
 
efe49f7
81d2771
af50600
81d2771
 
 
 
 
 
 
 
 
 
d2806d2
af50600
d2806d2
 
 
af50600
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
const SITE_CONFIG = {
    baseUrl: 'https://bitsearch.to',
    fallbackUrls: [
        'https://bitsearch.st',
        'https://bitsearch.eu'
    ]
};

// Helper function to fetch Cinemeta metadata (optional, for movie details)
async function getCinemetaMetadata(imdbId) {
    try {
        if (!imdbId.startsWith('tt')) {
            return null;
        }

        console.log(`\n🎬 Fetching Cinemeta data for ${imdbId}`);
        const response = await fetch(`https://v3-cinemeta.strem.io/meta/movie/${imdbId}.json`);
        if (!response.ok) throw new Error('Failed to fetch from Cinemeta');
        const data = await response.json();
        console.log('✅ Found:', data.meta.name);
        return data;
    } catch (error) {
        console.error('❌ Cinemeta error:', error);
        return null;
    }
}

// Timeout function to prevent hanging requests
async function fetchWithTimeout(url, options = {}, timeout = 30000) {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);

    try {
        const response = await fetch(url, {
            ...options,
            signal: controller.signal,
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9',
                'Accept-Language': 'en-US,en;q=0.9',
                ...options.headers
            }
        });
        clearTimeout(timeoutId);
        return response;
    } catch (error) {
        clearTimeout(timeoutId);
        throw error;
    }
}

// Parse the file size from a string (e.g., "1.2 GB")
function parseSize(sizeStr) {
    if (!sizeStr) return 0;
    const match = sizeStr.match(/([\d.]+)\s*(B|KB|MB|GB|TB)/i);
    if (!match) return 0;

    const [, value, unit] = match;
    const multipliers = {
        'B': 1,
        'KB': 1024,
        'MB': 1024 * 1024,
        'GB': 1024 * 1024 * 1024,
        'TB': 1024 * 1024 * 1024 * 1024
    };

    return parseFloat(value) * multipliers[unit.toUpperCase()];
}

// Parse search results from HTML
function parseSearchResults(html) {
    if (!html) {
        console.log('No HTML content to parse');
        return [];
    }

    const results = [];
    const searchResults = html.match(/<li class="card search-result my-2">[\s\S]*?<\/li>/g) || [];

    for (const result of searchResults) {
        try {
            const titleMatch = result.match(/class="title w-100 truncate"><a[^>]*>([^<]+)<\/a>/);
            const magnetMatch = result.match(/href="(magnet:[^"]+)"/);
            const sizeMatch = result.match(/alt="Size"[^>]*>([^<]+)<\/div>/);
            const seedersMatch = result.match(/alt="Seeder"[^>]*>[^<]*<font[^>]*>(\d+)<\/font>/);
            const leechersMatch = result.match(/alt="Leecher"[^>]*>[^<]*<font[^>]*>(\d+)<\/font>/);
            const categoryMatch = result.match(/class="category">([^<]+)<\/a>/);
            const dateMatch = result.match(/alt="Date"[^>]*>([^<]+)<\/div>/);

            if (titleMatch && magnetMatch) {
                const title = titleMatch[1].trim();
                const quality = extractQuality(title);
                const size = sizeMatch ? sizeMatch[1].trim() : 'Unknown';

                results.push({
                    title,
                    magnetLink: magnetMatch[1],
                    quality,
                    size,
                    source: 'BitSearch',
                    seeders: seedersMatch ? parseInt(seedersMatch[1]) : 0,
                    leechers: leechersMatch ? parseInt(leechersMatch[1]) : 0,
                    category: categoryMatch ? categoryMatch[1].trim() : 'Unknown',
                    uploadDate: dateMatch ? dateMatch[1].trim() : '',
                    mainFileSize: parseSize(size)
                });
            }
        } catch (error) {
            console.error('Error parsing result:', error);
        }
    }

    return results;
}

// Extract the video quality from the title (e.g., "1080p", "4k")
function extractQuality(title) {
    if (!title) return '';
    const qualityMatch = title.match(/\b(2160p|1080p|720p|4k|uhd|hdr|dv|blu[- ]?ray)\b/i);
    return qualityMatch ? qualityMatch[1].toLowerCase().replace(/[- ]/g, '') : '';
}

// Search for torrents while ignoring the year in the search query
async function searchTorrents(searchQuery, type = 'movie') {
    if (!searchQuery) {
        console.log('No search query provided');
        return [];
    }

    // Step 1: Remove year-like patterns (e.g., "2021", "2022") from the search query
    const queryWithoutYear = searchQuery.replace(/\s*(\d{4})\s*/g, '').trim();

    console.log('\n🔄 Searching BitSearch for:', queryWithoutYear);
    
    try {
        const formattedQuery = queryWithoutYear.replace(/\s+/g, '+').toLowerCase();
        const url = `${SITE_CONFIG.baseUrl}/search?q=${encodeURIComponent(formattedQuery)}&sort=size&category=1&subcat=2&order=desc`;

        console.log('Request URL:', url);

        const response = await fetchWithTimeout(url);
        if (!response.ok) {
            throw new Error(`Search request failed: ${response.status}`);
        }

        const html = await response.text();
        const results = parseSearchResults(html);
        console.log(`✅ Found ${results.length} raw results`);

        // Sort results based on quality and seeders
        results.sort((a, b) => {
            const qualityOrder = { '2160p': 5, '4k': 5, 'hdr': 4, 'dv': 4, '1080p': 3, '720p': 2 };
            const aQuality = qualityOrder[a.quality] || 0;
            const bQuality = qualityOrder[b.quality] || 0;
            
            if (aQuality !== bQuality) {
                return bQuality - aQuality;
            }
            return b.seeders - a.seeders;
        });

        return results;
    } catch (error) {
        console.error('❌ Error searching BitSearch:', error);
        return [];
    }
}
export { searchTorrents };