Update server.js
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514634514 unmodified lines202122167168169170171172173174232425261761771782728293018018118231323334353618418518618718818937383940193414219543444546474849505152532052062072082092102112122132142152162172182192202212222232242252262275455565758596061626364656667686970717273230747576102 unmodified lines1791801813391821833411841851861877 unmodified lines1951961973551981993572002012022038 unmodified lines2122132142153722162173742182193763773783793803813822202212222232243863873883893902252262272283 unmodified lines232233234400235236237238import express from 'express';import { fetchRSSFeeds } from './anime.js';import fetch from 'node-fetch';import { JSDOM } from 'jsdom';
// Function to extract video quality from the titlefunction extractQuality(title) { if (!title) return ''; const qualityMatch = title.match(/\b(2160p|1080p|720p|4k|uhd)\b/i); return qualityMatch ? qualityMatch[1].toLowerCase() : '';}
// Function to extract hash from BTSOW detail URLsfunction extractHash(detailUrl) { const hashMatch = detailUrl.match(/hash\/([A-Fa-f0-9]{40})/); return hashMatch ? hashMatch[1] : '';}
// Function to generate a direct magnet link from a hashfunction createMagnetLink(hash) { return `magnet:?xt=urn:btih:${hash}`;}
// Function to extract magnet links from a BTSOW detail pageasync function extractMagnetLinksFromPage(url) { try { await new Promise(resolve => setTimeout(resolve, 2000)); // Prevents rate-limiting
const response = await fetch(url, { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36', 'Referer': 'https://btsow.motorcycles/', 'Accept-Language': 'en-US,en;q=0.9', 'Connection': 'keep-alive', 'DNT': '1', 'Upgrade-Insecure-Requests': '1' } });
if (!response.ok) { console.error(`β Failed to fetch page (${response.status}):`, url); return null; }
const html = await response.text(); const dom = new JSDOM(html); const magnetLinks = dom.window.document.querySelectorAll('a[href^="magnet:?xt=urn:btih:"]');
return Array.from(magnetLinks).map(link => link.href); } catch (error) { console.error('β Error fetching magnet links:', error); return null; }}
// Function to fetch and parse BTSOW search resultsasync function fetchRSSFeeds(searchQuery) { console.log(`π Searching BTSOW for: "${searchQuery}"`);
try { await new Promise(resolve => setTimeout(resolve, 2000)); // Prevents bot detection
const url = `https://btsow.motorcycles/search/${encodeURIComponent(searchQuery)}`; const response = await fetch(url, { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36', 'Referer': 'https://btsow.motorcycles/', 'Accept-Language': 'en-US,en;q=0.9', 'Connection': 'keep-alive', 'DNT': '1', 'Upgrade-Insecure-Requests': '1' } });
if (!response.ok) { throw new Error(`Failed to fetch BTSOW search page: ${response.status}`); }
const html = await response.text(); const dom = new JSDOM(html); const torrents = [];
dom.window.document.querySelectorAll('.data-list .row').forEach(row => { const magnetLinkElement = row.querySelector('a[href^="//btsow.motorcycles/magnet/detail/hash/"]'); const titleElement = row.querySelector('.file'); const metaElement = row.querySelector('.size-date');
if (!magnetLinkElement || !titleElement || !metaElement) return;
const detailUrl = 'https:' + magnetLinkElement.getAttribute('href'); const title = titleElement.textContent.trim(); const quality = extractQuality(title);
// Extract hash to generate direct magnet link const hash = extractHash(detailUrl); const directMagnet = hash ? createMagnetLink(hash) : '';
// Extract meta information (size & date) const metaText = metaElement.textContent.trim(); const sizeMatch = metaText.match(/Size:([^/]+)/); const dateMatch = metaText.match(/Convert Date:(.+)/);
const size = sizeMatch ? sizeMatch[1].trim() : 'Unknown'; const date = dateMatch ? dateMatch[1].trim() : 'Unknown';
torrents.push({ title, detailUrl, hash, size, date, quality, magnetLinks: directMagnet ? [directMagnet] : [], }); });
// Fetch additional magnet links await Promise.all(torrents.map(async (torrent) => { if (!torrent.magnetLinks.length) { const magnetLinks = await extractMagnetLinksFromPage(torrent.detailUrl); if (magnetLinks) { torrent.magnetLinks.push(...magnetLinks); } } }));
// Filter out torrents with no magnet links const validTorrents = torrents.filter(torrent => torrent.magnetLinks.length > 0);
// Sort by quality validTorrents.sort((a, b) => { const qualityOrder = { '4k': 1, '2160p': 2, '1080p': 3, '720p': 4, '': 5 }; return (qualityOrder[a.quality] || 5) - (qualityOrder[b.quality] || 5); });
console.log(`β
Found ${validTorrents.length} torrents.`); return validTorrents;
} catch (error) { console.error('β Error fetching from BTSOW:', error); return []; }}
// Export fetchRSSFeeds as the single functionexport { fetchRSSFeeds };
const app = express();const port = process.env.PORT || 7860;14 unmodified lines return query;}
function isExactEpisodeMatch(torrentTitle, showTitle, seasonNum, episodeNum) { if (!torrentTitle || !showTitle || seasonNum == null || episodeNum == null) { return false; // πΉ Prevents crashes if values are missing }
// πΉ Ensure input is a string before using replace() torrentTitle = String(torrentTitle); showTitle = String(showTitle);function isExactEpisodeMatch(torrentTitle, showTitle, seasonNum, episodeNum) { // Early return if any of the inputs are missing if (!torrentTitle || !showTitle || seasonNum == null || episodeNum == null) return false;
// πΉ Normalize titles: Remove special characters & lowercase const cleanTorrentTitle = torrentTitle.replace(/[^\w\s]/g, '').toLowerCase(); const cleanShowTitle = showTitle.replace(/[^\w\s]/g, '').toLowerCase(); // Clean up and normalize titles const cleanTorrentTitle = String(torrentTitle).replace(/[^\w\s]/g, '').toLowerCase(); const cleanShowTitle = String(showTitle).replace(/[^\w\s]/g, '').toLowerCase();
// πΉ Extract meaningful words (ignore short/common words) const showWords = cleanShowTitle.split(' ') .filter(word => word.length > 2 && !['the', 'and', 'or', 'in', 'on', 'at', 'to', 'of', 'a'].includes(word)); // Split the show title into significant words const showWords = cleanShowTitle.split(' ').filter(word => word.length > 2); // Check if all significant words in the show title are present in the cleaned torrent title if (!showWords.every(word => cleanTorrentTitle.includes(word))) return false;
// πΉ Ensure all show title words exist in torrent title if (!showWords.every(word => cleanTorrentTitle.includes(word))) { return false; }
// πΉ Normalize season & episode numbers // Format season and episode numbers with leading zeros const seasonStr = seasonNum.toString().padStart(2, '0'); const episodeStr = episodeNum.toString().padStart(2, '0');
// πΉ Episode matching patterns (S01E05, 1x05, etc.) // β
FIX: Add support for different episode formats const patterns = [ new RegExp(`s${seasonStr}e${episodeStr}`, 'i'), // S01E05 new RegExp(`s${seasonStr}e${episodeStr}`, 'i'), // S01E05 new RegExp(`\\b${seasonNum}x${episodeNum}\\b`, 'i'), // 1x05 new RegExp(`\\b${seasonStr}${episodeStr}\\b`, 'i'), // 0105 new RegExp(`season\\s*${seasonNum}\\s*episode\\s*${episodeNum}`, 'i') // Season 1 Episode 5 ];
// Check if any of the episode patterns match the cleaned torrent title return patterns.some(pattern => pattern.test(cleanTorrentTitle));}
function isExactMovieMatch(torrentTitle, movieTitle, year) { if (!torrentTitle || !movieTitle || year == null) { // β
Prevent crashes if year is missing return false; } // πΉ Ensure input is a string before using replace() torrentTitle = String(torrentTitle); movieTitle = String(movieTitle);
// πΉ Normalize titles: Remove special characters & lowercase const cleanTorrentTitle = torrentTitle.replace(/[^\w\s]/g, '').toLowerCase(); const cleanMovieTitle = movieTitle.replace(/[^\w\s]/g, '').toLowerCase();
// πΉ Extract meaningful words (ignore short/common words) const movieWords = cleanMovieTitle.split(' ') .filter(word => word.length > 2 && !['the', 'and', 'or', 'in', 'on', 'at', 'to', 'of', 'a'].includes(word));
// πΉ Ensure all movie title words exist in torrent title if (!movieWords.every(word => cleanTorrentTitle.includes(word))) { return false; }
// πΉ Check for the release year in torrent title const yearMatch = torrentTitle.match(/(?:19|20)\d{2}/); return yearMatch ? yearMatch[0] === year.toString() : false; // Early return if any input is missing if (!torrentTitle || !movieTitle || year == null) return false;
// Clean and normalize the titles const cleanTorrentTitle = String(torrentTitle).replace(/[^\w\s]/g, '').toLowerCase(); const cleanMovieTitle = String(movieTitle).replace(/[^\w\s]/g, '').toLowerCase();
// Split the movie title into words and filter out short words const movieWords = cleanMovieTitle.split(' ').filter(word => word.length > 2); // Check if all words in the movie title are present in the cleaned torrent title if (!movieWords.every(word => cleanTorrentTitle.includes(word))) return false;
// β
FIX: Improve year matching, allowing variations const yearMatch = torrentTitle.match(/\b(19\d{2}|20\d{2})\b/); // Check if the year in the title matches the provided year return yearMatch ? parseInt(yearMatch[0]) === year : false;}
async function getTMDBDetails(tmdbId, type = 'movie') { try { const response = await fetch(`${TMDB_BASE_URL}/${type}/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`);102 unmodified lines if (tmdbData) { exactMatchParams = { title: tmdbData.title, year: new Date(tmdbData.release_date).getFullYear() year: tmdbData.release_date ? new Date(tmdbData.release_date).getFullYear() : null }; searchQuery = `${tmdbData.title} (${exactMatchParams.year})`; searchQuery = exactMatchParams.year ? `${tmdbData.title} (${exactMatchParams.year})` : tmdbData.title; } } // Handle IMDB ID format7 unmodified lines tmdbData = findData.movie_results[0]; exactMatchParams = { title: tmdbData.title, year: new Date(tmdbData.release_date).getFullYear() year: tmdbData.release_date ? new Date(tmdbData.release_date).getFullYear() : null }; searchQuery = `${tmdbData.title} (${exactMatchParams.year})`; searchQuery = exactMatchParams.year ? `${tmdbData.title} (${exactMatchParams.year})` : tmdbData.title; } } }8 unmodified lines } }
// β
FIX: `fetchRSSFeeds()` should be called without `type` parameter let results = await fetchRSSFeeds(searchQuery, type); let results = await fetchRSSFeeds(searchQuery);
// Filter results based on exact match parameters // β
FIX: Ensure filtering uses `result.title` instead of `result.websiteTitle` if (type === 'series' && exactMatchParams.season !== undefined) { results = results.filter(result => isExactEpisodeMatch( result.websiteTitle, exactMatchParams.title, exactMatchParams.season, exactMatchParams.episode ) results = results.filter(result => isExactEpisodeMatch(result.title, exactMatchParams.title, exactMatchParams.season, exactMatchParams.episode) ); } else if (type === 'movie' && exactMatchParams.year) { results = results.filter(result => isExactMovieMatch( result.websiteTitle, exactMatchParams.title, exactMatchParams.year ) isExactMovieMatch(result.title, exactMatchParams.title, exactMatchParams.year) ); }
3 unmodified lines type, tmdbData, results: results.map(result => ({ title: result.websiteTitle, title: result.title, quality: result.quality, size: result.size, seeders: 0, // Knaben RSS doesn't provide seeder infoserver.js+44-209