File size: 7,728 Bytes
d2806d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
const SITE_CONFIG = {
    baseUrl: 'https://bitsearch.to',
    fallbackUrls: [
        'https://bitsearch.st',
        'https://bitsearch.eu'
    ]
};

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;
    }
}

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;
    }
}

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()];
}

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;
}

function extractQuality(title) {
    if (!title) return '';
    const qualityMatch = title.match(/\b(2160p|1080p|720p|4k|uhd)\b/i);
    return qualityMatch ? qualityMatch[1].toLowerCase() : '';
}

function isCorrectEpisode(title, searchQuery) {
    if (!title || !searchQuery) return false;
    
    const queryMatch = searchQuery.match(/S(\d{2})E(\d{2})/i);
    if (!queryMatch) return false;
    
    const querySeasonNum = parseInt(queryMatch[1]);
    const queryEpisodeNum = parseInt(queryMatch[2]);

    const patterns = [
        /S(\d{2})E(\d{2})/i,
        /(\d{1,2})x(\d{2})/i,
        /[. ](\d{1,2})(\d{2})[. ]/,
        /Season (\d{1,2}) Episode (\d{1,2})/i
    ];

    for (const pattern of patterns) {
        const match = title.match(pattern);
        if (match) {
            const seasonNum = parseInt(match[1]);
            const episodeNum = parseInt(match[2]);
            if (seasonNum === querySeasonNum && episodeNum === queryEpisodeNum) {
                return true;
            }
        }
    }

    return false;
}

async function searchTorrents(searchQuery, type = 'movie') {
    if (!searchQuery) {
        console.log('No search query provided');
        return [];
    }

    console.log('\n๐Ÿ”„ Searching BitSearch for:', searchQuery);
    
    try {
        let title = searchQuery;
        let year = '';
        let searchTitle = searchQuery;

        if (type === 'movie' && searchQuery.startsWith('tt')) {
            const metadata = await getCinemetaMetadata(searchQuery);
            if (metadata && metadata.meta) {
                title = metadata.meta.name;
                year = new Date(metadata.meta.released).getFullYear().toString();
                searchTitle = `${title} ${year}`;
                console.log('Searching with title and year:', searchTitle);
            }
        }

        const formattedQuery = searchTitle.replace(/\s+/g, '+').toLowerCase();
        const url = `${SITE_CONFIG.baseUrl}/search?q=${encodeURIComponent(formattedQuery)}`;
        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`);

        let filteredResults = results;
        
        if (type === 'series') {
            filteredResults = results.filter(result => 
                isCorrectEpisode(result.title, searchQuery)
            );
        } else if (type === 'movie' && year) {
            filteredResults = results.filter(result => {
                const yearMatch = result.title.match(/(?:19|20)\d{2}/);
                return yearMatch && yearMatch[0] === year;
            });
        }

        console.log(`Found ${filteredResults.length} relevant results after filtering`);

        filteredResults.sort((a, b) => {
            const qualityOrder = { '2160p': 4, '4k': 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 filteredResults;

    } catch (error) {
        console.error('โŒ Error searching BitSearch:', error);
        
        for (const fallbackUrl of SITE_CONFIG.fallbackUrls) {
            try {
                console.log(`Trying fallback URL: ${fallbackUrl}`);
                SITE_CONFIG.baseUrl = fallbackUrl;
                return await searchTorrents(searchQuery, type);
            } catch (fallbackError) {
                console.error(`Fallback ${fallbackUrl} also failed:`, fallbackError);
            }
        }
        
        return [];
    }
}

export { searchTorrents };