Update server.js
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814914 unmodified lines164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233102 unmodified lines3363373383393403413423433447 unmodified lines3523533543553563573583593608 unmodified lines3693703713723733743753763773783793803813823833843853863873883893903913923933 unmodified lines397398399400401402403import 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-limitingconst 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 detectionconst 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 linkconst 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 linksawait 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 linksconst validTorrents = torrents.filter(torrent => torrent.magnetLinks.length > 0);// Sort by qualityvalidTorrents.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 linesreturn 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);// 🔹 Normalize titles: Remove special characters & lowercaseconst cleanTorrentTitle = torrentTitle.replace(/[^\w\s]/g, '').toLowerCase();const cleanShowTitle = 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));// 🔹 Ensure all show title words exist in torrent titleif (!showWords.every(word => cleanTorrentTitle.includes(word))) {return false;}// 🔹 Normalize season & episode numbersconst seasonStr = seasonNum.toString().padStart(2, '0');const episodeStr = episodeNum.toString().padStart(2, '0');// 🔹 Episode matching patterns (S01E05, 1x05, etc.)const patterns = [new RegExp(`s${seasonStr}e${episodeStr}`, 'i'), // S01E05new RegExp(`\\b${seasonNum}x${episodeNum}\\b`, 'i'), // 1x05new RegExp(`\\b${seasonStr}${episodeStr}\\b`, 'i'), // 0105new RegExp(`season\\s*${seasonNum}\\s*episode\\s*${episodeNum}`, 'i') // Season 1 Episode 5];return patterns.some(pattern => pattern.test(cleanTorrentTitle));}function isExactMovieMatch(torrentTitle, movieTitle, year) {if (!torrentTitle || !movieTitle || year == null) { // ✅ Prevent crashes if year is missingreturn false;}// 🔹 Ensure input is a string before using replace()torrentTitle = String(torrentTitle);movieTitle = String(movieTitle);// 🔹 Normalize titles: Remove special characters & lowercaseconst 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 titleif (!movieWords.every(word => cleanTorrentTitle.includes(word))) {return false;}// 🔹 Check for the release year in torrent titleconst yearMatch = torrentTitle.match(/(?:19|20)\d{2}/);return yearMatch ? yearMatch[0] === year.toString() : 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 linesif (tmdbData) {exactMatchParams = {title: tmdbData.title,year: new Date(tmdbData.release_date).getFullYear()};searchQuery = `${tmdbData.title} (${exactMatchParams.year})`;}}// Handle IMDB ID format7 unmodified linestmdbData = findData.movie_results[0];exactMatchParams = {title: tmdbData.title,year: new Date(tmdbData.release_date).getFullYear()};searchQuery = `${tmdbData.title} (${exactMatchParams.year})`;}}}8 unmodified lines}}let results = await fetchRSSFeeds(searchQuery, type);// Filter results based on exact match parametersif (type === 'series' && exactMatchParams.season !== undefined) {results = results.filter(result =>isExactEpisodeMatch(result.websiteTitle,exactMatchParams.title,exactMatchParams.season,exactMatchParams.episode));} else if (type === 'movie' && exactMatchParams.year) {results = results.filter(result =>isExactMovieMatch(result.websiteTitle,exactMatchParams.title,exactMatchParams.year));}3 unmodified linestype,tmdbData,results: results.map(result => ({title: result.websiteTitle,quality: result.quality,size: result.size,seeders: 0, // Knaben RSS doesn't provide seeder info1234514 unmodified lines202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576102 unmodified lines1791801811821831841851861877 unmodified lines1951961971981992002012022038 unmodified lines2122132142152162172182192202212222232242252262272283 unmodified lines232233234235236237238import express from 'express';import { fetchRSSFeeds } from './anime.js';const app = express();const port = process.env.PORT || 7860;14 unmodified linesreturn query;}function isExactEpisodeMatch(torrentTitle, showTitle, seasonNum, episodeNum) {// Early return if any of the inputs are missingif (!torrentTitle || !showTitle || seasonNum == null || episodeNum == null) return false;// Clean up and normalize titlesconst cleanTorrentTitle = String(torrentTitle).replace(/[^\w\s]/g, '').toLowerCase();const cleanShowTitle = String(showTitle).replace(/[^\w\s]/g, '').toLowerCase();// Split the show title into significant wordsconst showWords = cleanShowTitle.split(' ').filter(word => word.length > 2);// Check if all significant words in the show title are present in the cleaned torrent titleif (!showWords.every(word => cleanTorrentTitle.includes(word))) return false;// Format season and episode numbers with leading zerosconst seasonStr = seasonNum.toString().padStart(2, '0');const episodeStr = episodeNum.toString().padStart(2, '0');// ✅ FIX: Add support for different episode formatsconst patterns = [new RegExp(`s${seasonStr}e${episodeStr}`, 'i'), // S01E05new RegExp(`\\b${seasonNum}x${episodeNum}\\b`, 'i'), // 1x05new RegExp(`\\b${seasonStr}${episodeStr}\\b`, 'i'), // 0105new RegExp(`season\\s*${seasonNum}\\s*episode\\s*${episodeNum}`, 'i') // Season 1 Episode 5];// Check if any of the episode patterns match the cleaned torrent titlereturn patterns.some(pattern => pattern.test(cleanTorrentTitle));}function isExactMovieMatch(torrentTitle, movieTitle, year) {// Early return if any input is missingif (!torrentTitle || !movieTitle || year == null) return false;// Clean and normalize the titlesconst 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 wordsconst movieWords = cleanMovieTitle.split(' ').filter(word => word.length > 2);// Check if all words in the movie title are present in the cleaned torrent titleif (!movieWords.every(word => cleanTorrentTitle.includes(word))) return false;// ✅ FIX: Improve year matching, allowing variationsconst yearMatch = torrentTitle.match(/\b(19\d{2}|20\d{2})\b/);// Check if the year in the title matches the provided yearreturn 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 linesif (tmdbData) {exactMatchParams = {title: tmdbData.title,year: tmdbData.release_date ? new Date(tmdbData.release_date).getFullYear() : null};searchQuery = exactMatchParams.year ? `${tmdbData.title} (${exactMatchParams.year})` : tmdbData.title;}}// Handle IMDB ID format7 unmodified linestmdbData = findData.movie_results[0];exactMatchParams = {title: tmdbData.title,year: tmdbData.release_date ? new Date(tmdbData.release_date).getFullYear() : null};searchQuery = exactMatchParams.year ? `${tmdbData.title} (${exactMatchParams.year})` : tmdbData.title;}}}8 unmodified lines}}// ✅ FIX: `fetchRSSFeeds()` should be called without `type` parameterlet results = await fetchRSSFeeds(searchQuery);// ✅ FIX: Ensure filtering uses `result.title` instead of `result.websiteTitle`if (type === 'series' && exactMatchParams.season !== undefined) {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.title, exactMatchParams.title, exactMatchParams.year));}3 unmodified linestype,tmdbData,results: results.map(result => ({title: result.title,quality: result.quality,size: result.size,seeders: 0, // Knaben RSS doesn't provide seeder info
server.js+44-209