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(/
  • [\s\S]*?<\/li>/g) || []; for (const result of searchResults) { try { const titleMatch = result.match(/class="title w-100 truncate">]*>([^<]+)<\/a>/); const magnetMatch = result.match(/href="(magnet:[^"]+)"/); const sizeMatch = result.match(/alt="Size"[^>]*>([^<]+)<\/div>/); const seedersMatch = result.match(/alt="Seeder"[^>]*>[^<]*]*>(\d+)<\/font>/); const leechersMatch = result.match(/alt="Leecher"[^>]*>[^<]*]*>(\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 };