Spaces:
Runtime error
Runtime error
Upload 5 files
#1
by gre89 - opened
Files changed (5)
- jackett.jsAdded+364
- magnet-fix.jsAdded+129
- package.jsonAdded+24
- server-with-jackett.jsAdded+500
- torrent-utils.jsAdded+395
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364// jackett.js - Module for searching torrents via Jackett's APIimport { analyzeTorrentFromUrl } from './torrent-utils.js';import { fixMagnetUri, processMagnetLink, likelyContainsVideo } from './magnet-fix.js';
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': 'application/json', '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 || typeof sizeStr !== 'string') return 0; // Convert size string to bytes const units = { KB: 1024, MB: 1024 ** 2, GB: 1024 ** 3, TB: 1024 ** 4 }; const match = sizeStr.match(/^(\d+(?:\.\d+)?)\s*([KMGT]B)$/i); if (!match) return 0; const [, size, unit] = match; return parseFloat(size) * (units[unit.toUpperCase()] || 1);}
function extractQuality(title) { if (!title || typeof title !== 'string') return ''; const qualityMatch = title.match(/\b(2160p|1080p|720p|4k|uhd)\b/i); return qualityMatch ? qualityMatch[1].toLowerCase() : '';}
// Safely get property from object with a default value if not present or wrong typefunction safeGet(obj, path, defaultValue) { if (!obj) return defaultValue; const pathParts = path.split('.'); let current = obj; for (const part of pathParts) { if (current === null || current === undefined || typeof current !== 'object') { return defaultValue; } current = current[part]; } return current !== undefined ? current : defaultValue;}
/** * Sanitizes a search query by removing special characters * @param {string} query - The original search query * @returns {string} - The sanitized search query */function sanitizeSearchQuery(query) { if (!query || typeof query !== 'string') { return ''; } // Remove apostrophes, quotes, and other special characters // but preserve spaces, numbers, and alphanumeric characters return query.replace(/[''"&?!:;,.()\[\]{}<>]/g, '') .replace(/\s+/g, ' ') // Replace multiple spaces with single space .trim(); // Remove leading/trailing whitespace}
async function searchJackett(searchQuery, config, type = 'movie') { if (!searchQuery || typeof searchQuery !== 'string') { console.log('No search query provided'); return []; } // Sanitize the search query to remove special characters const sanitizedQuery = sanitizeSearchQuery(searchQuery); if (!sanitizedQuery) { console.log('Search query is empty after sanitization'); return []; } const { apiKey, baseUrl, trackers = [] } = config || {}; if (!apiKey || !baseUrl) { throw new Error('Missing required configuration: apiKey or baseUrl'); }
console.log(`\n🔄 Searching Jackett for: ${sanitizedQuery} (original: "${searchQuery}")`); console.log(`Using trackers: ${trackers.length > 0 ? trackers.join(', ') : 'All available'}`); try { // Construct the query URL with tracker filtering let jackettUrl = `${baseUrl}/api/v2.0/indexers/all/results?apikey=${apiKey}&Query=${encodeURIComponent(sanitizedQuery)}`; // Add tracker filtering if trackers are specified if (trackers && trackers.length > 0) { const trackerParams = trackers.map(tracker => `Tracker[]=${encodeURIComponent(tracker)}`).join('&'); jackettUrl += `&${trackerParams}`; } console.log('Request URL:', jackettUrl);
const response = await fetchWithTimeout(jackettUrl); if (!response.ok) { throw new Error(`Jackett API error: ${response.status}`); }
const data = await response.json(); console.log(`Found ${safeGet(data, 'Results.length', 0)} results from Jackett`);
if (!data.Results || !Array.isArray(data.Results) || data.Results.length === 0) { return []; }
// Filter by type if needed let filteredResults = data.Results; if (type === 'movie') { // Filter for movie categories - typically 2000's range represents movies filteredResults = data.Results.filter(result => { const categories = Array.isArray(result.Category) ? result.Category : [result.Category]; return categories.some(cat => (cat >= 2000 && cat < 3000) || cat === 1); }); } else if (type === 'series') { // Filter for TV show categories - typically 5000's range represents TV filteredResults = data.Results.filter(result => { const categories = Array.isArray(result.Category) ? result.Category : [result.Category]; return categories.some(cat => (cat >= 5000 && cat < 6000) || cat === 2); }); }
// Map results to our standardized format const streams = filteredResults.map(result => { // Extract the year if present in the title const title = safeGet(result, 'Title', ''); const yearMatch = typeof title === 'string' ? title.match(/(?:19|20)\d{2}/) : null; const year = yearMatch ? yearMatch[0] : null; // Calculate seeders/leechers count const seeders = typeof result.Seeders === 'number' ? result.Seeders : 0; const leechers = typeof result.Peers === 'number' ? result.Peers : 0; // Fix magnet link immediately if present let magnetLink = safeGet(result, 'MagnetUri', null); if (magnetLink) { magnetLink = fixMagnetUri(magnetLink); } return { title: title, magnetLink: magnetLink, torrentLink: safeGet(result, 'Link', null), infoHash: safeGet(result, 'InfoHash', null), quality: extractQuality(title), size: result.Size ? `${(result.Size / (1024 * 1024 * 1024)).toFixed(2)} GB` : 'Unknown', source: safeGet(result, 'Tracker', 'Jackett'), seeders: seeders, leechers: leechers, year: year, category: safeGet(result, 'CategoryDesc', ''), mainFileSize: safeGet(result, 'Size', 0), gain: safeGet(result, 'Gain', 0), publishDate: safeGet(result, 'PublishDate', null), likelyVideo: likelyContainsVideo(title) }; });
// Filter out results that don't look like they contain video content const videoStreams = streams.filter(stream => stream.likelyVideo); console.log(`Filtered to ${videoStreams.length} results that likely contain video content`);
// Process results const processedStreams = await Promise.all(videoStreams.map(async (stream) => { // If we already have a working magnet link, just process it directly if (stream.magnetLink) { // Try to process the magnet link directly for additional info try { const magnetInfo = processMagnetLink(stream.magnetLink); if (magnetInfo) { return { ...stream, infoHash: magnetInfo.infoHash || stream.infoHash, // Use quality from title if not already detected quality: stream.quality || magnetInfo.quality }; } } catch (error) { // If direct processing fails, continue with the original stream data console.error(`Error processing magnet link: ${error.message}`); } return stream; } // If we have a torrent link but no magnet, try to analyze the torrent if (stream.torrentLink) { try { console.log(`Converting torrent to magnet for: ${stream.title}`); // Check if torrentLink is actually a magnet URI (can happen with some indexers) if (stream.torrentLink.startsWith('magnet:')) { const fixedMagnetUri = fixMagnetUri(stream.torrentLink); const magnetInfo = processMagnetLink(fixedMagnetUri); if (magnetInfo) { return { ...stream, magnetLink: fixedMagnetUri, infoHash: magnetInfo.infoHash, quality: magnetInfo.quality || stream.quality }; } } else { // It's a real torrent URL const torrentInfo = await analyzeTorrentFromUrl(stream.torrentLink); if (torrentInfo) { return { ...stream, magnetLink: torrentInfo.magnetLink, filename: torrentInfo.filename, infoHash: torrentInfo.infoHash, mainFileSize: torrentInfo.mainFileSize || stream.mainFileSize, quality: torrentInfo.quality || stream.quality }; } } } catch (error) { console.error(`Error analyzing torrent: ${error.message}`); // If direct torrent analysis fails but we have an info hash, try to create a basic magnet if (stream.infoHash) { const basicMagnet = `magnet:?xt=urn:btih:${stream.infoHash}&dn=${encodeURIComponent(stream.title)}`; console.log(`Created basic magnet link from info hash for: ${stream.title}`); return { ...stream, magnetLink: basicMagnet }; } } } return stream; }));
// Filter out results without magnetUri const validStreams = processedStreams.filter(stream => stream.magnetLink); console.log(`Found ${validStreams.length} valid streams with magnet links`); // Sort results by quality, then seeders, then size validStreams.sort((a, b) => { const qualityOrder = { '2160p': 4, '4k': 4, 'uhd': 4, '1080p': 3, '720p': 2 }; const aQuality = qualityOrder[a.quality] || 0; const bQuality = qualityOrder[b.quality] || 0; if (aQuality !== bQuality) { return bQuality - aQuality; } if (a.seeders !== b.seeders) { return b.seeders - a.seeders; } return b.mainFileSize - a.mainFileSize; });
return validStreams; } catch (error) { console.error(`❌ Error searching Jackett:`, error); return []; }}
// Helper function to find the best torrent match based on user preferencesfunction findBestTorrent(torrents, preferences = {}) { if (!Array.isArray(torrents) || torrents.length === 0) { return null; } const { minSeeders = 5, maxSize = Infinity, minSize = 0, preferredQuality = '1080p', preferredCodec = 'x265' } = preferences || {}; // First filter by minimum seeders and size constraints let filtered = torrents.filter(t => { return (t.seeders || 0) >= minSeeders && (t.mainFileSize || 0) >= minSize && (t.mainFileSize || 0) <= maxSize; }); if (filtered.length === 0) return null; // Scoring system const scored = filtered.map(torrent => { let score = 0; // Quality scoring const qualityScores = { '2160p': 10, '4k': 10, 'uhd': 10, '1080p': 8, '720p': 5 }; score += qualityScores[torrent.quality] || 0; // Preferred quality exact match bonus if (torrent.quality === preferredQuality) { score += 5; } // Codec scoring const title = typeof torrent.title === 'string' ? torrent.title.toLowerCase() : ''; if (title.includes(preferredCodec.toLowerCase())) { score += 3; } // Seeders scoring - logarithmic scale to avoid extremely popular torrents dominating score += Math.min(10, Math.log10((torrent.seeders || 0) + 1) * 3); // Size scoring - prefer middle size range const sizeGB = (torrent.mainFileSize || 0) / (1024 * 1024 * 1024); if (preferredQuality === '2160p' || preferredQuality === '4k') { // For 4K content, optimal size is around 15-40GB if (sizeGB >= 15 && sizeGB <= 40) score += 5; else if (sizeGB > 40) score += 2; else if (sizeGB > 8) score += 3; } else if (preferredQuality === '1080p') { // For 1080p content, optimal size is around 4-12GB if (sizeGB >= 4 && sizeGB <= 12) score += 5; else if (sizeGB > 12) score += 2; else if (sizeGB > 2) score += 3; } else { // For 720p content, optimal size is around 1-4GB if (sizeGB >= 1 && sizeGB <= 4) score += 5; else if (sizeGB > 4) score += 2; } // Trusted release group bonus const trustedGroups = ['qxr', 'tigole', 'etrg', 'yts', 'rarbg', 'framestor']; for (const group of trustedGroups) { if (title.includes(group)) { score += 2; break; } } return { torrent, score }; }); // Sort by score and return the highest scored.sort((a, b) => b.score - a.score); return scored[0]?.torrent || null;}
export { sanitizeSearchQuery, searchJackett, findBestTorrent };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129/** * Fixes malformed magnet URIs that start with "magnet:/?" instead of "magnet:?" * This is a common issue with some trackers and Jackett's responses * * @param {string} magnetUri - The potentially malformed magnet URI * @returns {string} - Properly formatted magnet URI */function fixMagnetUri(magnetUri) { if (!magnetUri) return magnetUri; // Check for the incorrect format and fix it if (magnetUri.startsWith('magnet:/?')) { return magnetUri.replace('magnet:/?', 'magnet:?'); } return magnetUri;}
/** * Processes a magnet link directly without using read-torrent * Extracts info hash and other useful information from the magnet URI * * @param {string} magnetUri - The magnet URI to process * @returns {Object|null} - Object containing parsed magnet information or null if invalid */function processMagnetLink(magnetUri) { if (!magnetUri) return null; // Fix the URI if needed magnetUri = fixMagnetUri(magnetUri); try { // Extract info hash (should be after xt=urn:btih:) const infoHashMatch = magnetUri.match(/xt=urn:btih:([a-zA-Z0-9]+)/i); if (!infoHashMatch || !infoHashMatch[1]) return null; const infoHash = infoHashMatch[1].toLowerCase(); // Extract name (after dn=) const nameMatch = magnetUri.match(/dn=([^&]+)/i); const name = nameMatch ? decodeURIComponent(nameMatch[1]) : null; // Extract trackers (multiple tr= parameters) const trackerMatches = magnetUri.matchAll(/tr=([^&]+)/gi); const trackers = []; for (const match of trackerMatches) { if (match[1]) { trackers.push(decodeURIComponent(match[1])); } } return { magnetLink: magnetUri, infoHash, name, trackers, // Make a guess at quality based on name quality: name ? extractQualityFromTitle(name) : null }; } catch (error) { console.error('Error processing magnet link:', error); return null; }}
/** * Extracts video quality information from a title string * @param {string} title - The title to analyze * @returns {string|null} - Quality identifier or null if none found */function extractQualityFromTitle(title) { if (!title) return null; const lowerTitle = title.toLowerCase(); // Check for common quality indicators if (lowerTitle.includes('2160p') || lowerTitle.includes('4k') || lowerTitle.includes('uhd')) { return '2160p'; } else if (lowerTitle.includes('1080p') || lowerTitle.includes('fhd')) { return '1080p'; } else if (lowerTitle.includes('720p') || lowerTitle.includes('hd')) { return '720p'; } else if (lowerTitle.includes('480p')) { return '480p'; } return null;}
/** * Makes a best guess at whether a torrent contains video content based on title * @param {string} title - Torrent title * @returns {boolean} - True if likely contains video */function likelyContainsVideo(title) { if (!title) return false; const lowerTitle = title.toLowerCase(); // Check for common video file extensions const videoExtensions = ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.m4v']; if (videoExtensions.some(ext => lowerTitle.includes(ext))) { return true; } // Check for quality indicators if (/\b(2160p|1080p|720p|480p|4k|uhd|hd)\b/i.test(lowerTitle)) { return true; } // Check for common encoding terms if (/\b(x264|x265|h264|h265|hevc|avc|xvid|divx)\b/i.test(lowerTitle)) { return true; } // Check for release group patterns if (/\b(bluray|web-dl|webrip|bdrip|dvdrip)\b/i.test(lowerTitle)) { return true; } return false;}
export { fixMagnetUri, processMagnetLink, extractQualityFromTitle, likelyContainsVideo };123456789101112131415161718192021222324{ "name": "torrent-api", "version": "1.0.0", "description": "API server for searching torrents with TMDB integration", "main": "server.js", "type": "module", "scripts": { "start": "node server-with-jackett.js", "dev": "nodemon server-with-jackett.js" }, "dependencies": { "express": "^4.18.2", "node-fetch": "^3.3.2", "read-torrent": "^1.3.1", "xml2js": "^0.6.2" }, "devDependencies": { "nodemon": "^3.0.2" }, "engines": { "node": ">=18.0.0" }, "private": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500import express from 'express';import { searchJackett, findBestTorrent } from './jackett.js';import path from 'path';import { fileURLToPath } from 'url';import { analyzeTorrentFromUrl } from './torrent-utils.js';import { fixMagnetUri, processMagnetLink } from './magnet-fix.js';
const __filename = fileURLToPath(import.meta.url);const __dirname = path.dirname(__filename);
const app = express();const port = process.env.PORT || 7006;const TMDB_API_KEY = 'nn6a4ekizom285jrsgs5koivj7wlyx9s';const TMDB_BASE_URL = 'https://api.themoviedb.org/3';
// Jackett configurationconst JACKETT_CONFIG = { apiKey: 'f051e7366c6105ad4f9aafe4733d9dae', baseUrl: 'http://76.28.181.26:9117', trackers: ['torrentday'] // Specify the trackers you want to search};//http://:9117/jackett/api/v2.0/indexers/all/results?apikey=&Query=bad%20boys%20ride%20or%20die&Tracker%5B%5D=&_=1745248667366
app.use(express.json());app.use(express.static(path.join(__dirname, 'public')));
function standardizeEpisodeFormat(query) { // Handle 1x01 format const altMatch = query.match(/^(.*?)(\d{1,2})x(\d{1,2})/i); if (altMatch) { const [_, title, season, episode] = altMatch; const paddedSeason = String(season).padStart(2, '0'); const paddedEpisode = String(episode).padStart(2, '0'); return `${title.trim()} S${paddedSeason}E${paddedEpisode}`; } return query;}
function normalizeTitle(title) { return title.toLowerCase() .replace(/[^a-z0-9\s]/g, '') .replace(/\s+/g, ' ') .trim();}
function isExactEpisodeMatch(torrentTitle, showTitle, seasonNum, episodeNum) { if (!torrentTitle || !showTitle) return false; // Remove HTML tags and clean up title torrentTitle = torrentTitle.replace(/<[^>]*>/g, '') .replace(/\[.*?\]/g, '') // Remove bracketed content .replace(/\(.*?\)/g, '') // Remove parenthetical content .replace(/\s+/g, ' ') .trim(); // Normalize the titles for comparison const normalizedTorrentTitle = torrentTitle.toLowerCase(); // Also normalize show title to remove special characters const normalizedShowTitle = showTitle.toLowerCase() .replace(/[^\w\s]/g, ' ') // Replace special chars with spaces .replace(/\s+/g, ' ') // Replace multiple spaces with one .trim(); // Split show title into significant words const showWords = normalizedShowTitle.split(' ') .filter(word => word.length > 2) .filter(word => !['the', 'and', 'or', 'in', 'on', 'at', 'to'].includes(word)); const hasAllShowWords = showWords.every(word => normalizedTorrentTitle.includes(word) ); if (!hasAllShowWords) return false; // Format season and episode numbers const seasonStr = String(seasonNum).padStart(2, '0'); const episodeStr = String(episodeNum).padStart(2, '0'); // Common episode patterns const patterns = [ new RegExp(`s${seasonStr}e${episodeStr}`, 'i'), // S01E01 new RegExp(`${seasonNum}x${episodeStr}`, 'i'), // 1x01 new RegExp(`[^0-9]${seasonNum}${episodeStr}[^0-9]`, 'i'), // 101 new RegExp(`season\\s*${seasonNum}\\s*episode\\s*${episodeNum}`, 'i'), // Season 1 Episode 1 new RegExp(`s${seasonStr}\\.?e${episodeStr}`, 'i'), // S01.E01 new RegExp(`${seasonStr}${episodeStr}`, 'i'), // 0101 new RegExp(`^${seasonNum}${episodeStr}\\s`, 'i'), // 101 at start new RegExp(`\\s${seasonNum}${episodeStr}$`, 'i'), // 101 at end new RegExp(`episode\\s*${episodeNum}`, 'i') // Just episode number if title matches ]; return patterns.some(pattern => pattern.test(normalizedTorrentTitle));}
function isExactMovieMatch(torrentTitle, movieTitle, year) { if (!torrentTitle || !movieTitle) return false; // Remove HTML tags and clean title torrentTitle = torrentTitle.replace(/<[^>]*>/g, '') .replace(/\[.*?\]/g, '') // Remove bracketed content .replace(/\(.*?\)/g, '') // Remove parenthetical content .replace(/\s+/g, ' ') .trim(); // Normalize for comparison const normalizedTorrentTitle = torrentTitle.toLowerCase(); // Important: Normalize movie title by removing special characters const normalizedMovieTitle = movieTitle.toLowerCase() .replace(/[^\w\s]/g, ' ') // Replace special chars with spaces .replace(/\s+/g, ' ') // Replace multiple spaces with one .trim(); // Split movie title into significant words and check if all are present const movieWords = normalizedMovieTitle.split(' ') .filter(word => word.length > 2) .filter(word => !['the', 'and', 'or', 'in', 'on', 'at', 'to'].includes(word)); const hasAllMovieWords = movieWords.every(word => normalizedTorrentTitle.includes(word) ); if (!hasAllMovieWords) return false; // Check year const yearMatch = torrentTitle.match(/(?:19|20)\d{2}/); return yearMatch && yearMatch[0] === year.toString();}
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`); if (!response.ok) throw new Error(`TMDB API error: ${response.status}`); return await response.json(); } catch (error) { console.error('TMDB fetch error:', error); return null; }}
async function getTVShowDetails(tmdbId, seasonNum, episodeNum) { try { // Get basic show info const showResponse = await fetch( `${TMDB_BASE_URL}/tv/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids` ); if (!showResponse.ok) throw new Error(`TMDB API error: ${showResponse.status}`); const showData = await showResponse.json();
// Get specific episode info const episodeResponse = await fetch( `${TMDB_BASE_URL}/tv/${tmdbId}/season/${seasonNum}/episode/${episodeNum}?api_key=${TMDB_API_KEY}` ); if (!episodeResponse.ok) throw new Error(`TMDB API error: ${episodeResponse.status}`); const episodeData = await episodeResponse.json();
return { showTitle: showData.name, episodeTitle: episodeData.name, seasonNumber: seasonNum, episodeNumber: episodeNum, airDate: episodeData.air_date, imdbId: showData.external_ids?.imdb_id }; } catch (error) { console.error('TMDB fetch error:', error); return null; }}
async function handleSearch({ query, type, trackers = null }) { if (!query) throw new Error('Missing required parameter: query'); if (!['movie', 'series'].includes(type)) throw new Error('Invalid type. Must be either "movie" or "series"');
let searchQuery = query; let exactMatchParams = {}; let tmdbData = null;
if (type === 'series') { // Handle TMDB ID format: "tmdb:12345:1:1" (show_id:season:episode) const tmdbMatch = query.match(/^tmdb:(\d+):(\d+):(\d+)$/); if (tmdbMatch) { const [_, tmdbId, seasonNum, episodeNum] = tmdbMatch; tmdbData = await getTVShowDetails(tmdbId, parseInt(seasonNum), parseInt(episodeNum)); if (tmdbData) { exactMatchParams = { title: tmdbData.showTitle, season: parseInt(seasonNum), episode: parseInt(episodeNum) }; // Use standard format for search searchQuery = `${tmdbData.showTitle} S${String(seasonNum).padStart(2, '0')}E${String(episodeNum).padStart(2, '0')}`; } } // Handle IMDB ID format: "tt1234567:1:1" (imdb_id:season:episode) else if (query.startsWith('tt')) { const imdbMatch = query.match(/^(tt\d+):(\d+):(\d+)$/); if (imdbMatch) { const [_, imdbId, seasonNum, episodeNum] = imdbMatch; // First get TMDB ID from IMDB ID const findResponse = await fetch( `${TMDB_BASE_URL}/find/${imdbId}?api_key=${TMDB_API_KEY}&external_source=imdb_id` ); if (findResponse.ok) { const findData = await findResponse.json(); if (findData.tv_results && findData.tv_results[0]) { const tmdbId = findData.tv_results[0].id; tmdbData = await getTVShowDetails(tmdbId, parseInt(seasonNum), parseInt(episodeNum)); if (tmdbData) { exactMatchParams = { title: tmdbData.showTitle, season: parseInt(seasonNum), episode: parseInt(episodeNum) }; searchQuery = `${tmdbData.showTitle} S${String(seasonNum).padStart(2, '0')}E${String(episodeNum).padStart(2, '0')}`; } } } } } // Handle text formats else { // Convert 1x01 format to S01E01 searchQuery = standardizeEpisodeFormat(query); // Try to extract season/episode info const seasonEpisodeMatch = searchQuery.match(/^(.*?)S(\d{1,2})E(\d{1,2})/i); if (seasonEpisodeMatch) { exactMatchParams = { title: seasonEpisodeMatch[1].trim(), season: parseInt(seasonEpisodeMatch[2]), episode: parseInt(seasonEpisodeMatch[3]) }; } } } else if (type === 'movie') { // Handle TMDB ID format if (query.startsWith('tmdb:')) { const tmdbId = query.replace('tmdb:', ''); tmdbData = await getTMDBDetails(tmdbId, 'movie'); if (tmdbData) { exactMatchParams = { title: tmdbData.title, year: new Date(tmdbData.release_date).getFullYear() }; searchQuery = `${tmdbData.title} ${exactMatchParams.year}`; } } // Handle IMDB ID format else if (query.startsWith('tt')) { const findResponse = await fetch( `${TMDB_BASE_URL}/find/${query}?api_key=${TMDB_API_KEY}&external_source=imdb_id` ); if (findResponse.ok) { const findData = await findResponse.json(); if (findData.movie_results && findData.movie_results[0]) { tmdbData = findData.movie_results[0]; exactMatchParams = { title: tmdbData.title, year: new Date(tmdbData.release_date).getFullYear() }; searchQuery = `${tmdbData.title} ${exactMatchParams.year}`; } } } // Handle text format with year else { const movieYearMatch = query.match(/^(.+?)(?:\s+|$)(\d{4})$/); if (movieYearMatch) { exactMatchParams = { title: movieYearMatch[1].trim(), year: parseInt(movieYearMatch[2]) }; } } } // Create a config with custom trackers if specified const jackettConfig = {...JACKETT_CONFIG}; if (trackers && Array.isArray(trackers) && trackers.length > 0) { jackettConfig.trackers = trackers; } // Search through Jackett const jackettResults = await searchJackett(searchQuery, jackettConfig, type); // Filter results based on exact match parameters let filteredResults = [...jackettResults]; if (type === 'series' && exactMatchParams.season !== undefined) { filteredResults = filteredResults.filter(result => isExactEpisodeMatch( result.title || result.name, exactMatchParams.title, exactMatchParams.season, exactMatchParams.episode ) ); } else if (type === 'movie' && exactMatchParams.year) { filteredResults = filteredResults.filter(result => isExactMovieMatch( result.title || result.name, exactMatchParams.title, exactMatchParams.year ) ); }
// Sort results by quality, seeders, and size filteredResults.sort((a, b) => { const qualityOrder = { '2160p': 4, '4k': 4, 'uhd': 4, '1080p': 3, '720p': 2 }; const aQuality = qualityOrder[a.quality] || 0; const bQuality = qualityOrder[b.quality] || 0; if (aQuality !== bQuality) { return bQuality - aQuality; } // Next, sort by seeders const seedersA = a.seeders || 0; const seedersB = b.seeders || 0; if (seedersA !== seedersB) { return seedersB - seedersA; } // Finally, sort by size (prefer larger files within same quality tier) const sizeA = a.mainFileSize || 0; const sizeB = b.mainFileSize || 0; return sizeB - sizeA; });
// Find the best torrent based on preferences const bestTorrent = findBestTorrent(filteredResults, { minSeeders: 3, maxSize: 30 * 1024 * 1024 * 1024, // 30GB max minSize: type === 'movie' ? 1 * 1024 * 1024 * 1024 : 100 * 1024 * 1024, // 1GB for movies, 100MB for TV preferredQuality: '1080p', preferredCodec: 'x265' // Prefer HEVC/x265 for better compression });
return { query: searchQuery, originalQuery: query, type, tmdbData, results: filteredResults.map(result => ({ title: result.title, filename: result.filename, quality: result.quality, size: result.size, seeders: result.seeders, leechers: result.leechers, magnetLink: result.magnetLink, source: result.source || 'Unknown', bestMatch: bestTorrent && (result.infoHash === bestTorrent.infoHash || result.title === bestTorrent.title) })) };}
app.get('/api/search', async (req, res) => { try { // Parse trackers if provided let trackers = null; if (req.query.trackers) { try { trackers = req.query.trackers.split(',').map(t => t.trim()); } catch (e) { console.warn('Invalid trackers parameter:', e); } } const result = await handleSearch({ query: req.query.query, type: req.query.type, trackers }); res.json(result); } catch (error) { res.status(500).json({ error: 'Internal server error', message: error.message }); }});
app.post('/api/search', async (req, res) => { try { const result = await handleSearch({ query: req.body.query, type: req.body.type, trackers: req.body.trackers }); res.json(result); } catch (error) { res.status(500).json({ error: 'Internal server error', message: error.message }); }});
// API endpoint to analyze a torrent file or magnet link directlyapp.get('/api/analyze-torrent', async (req, res) => { try { const url = req.query.url; if (!url) { return res.status(400).json({ error: 'Bad request', message: 'Missing required parameter: url' }); } // Check if it's a magnet link if (url.startsWith('magnet:')) { // Fix and process the magnet link immediately const fixedMagnetLink = fixMagnetUri(url); const magnetInfo = processMagnetLink(fixedMagnetLink); if (magnetInfo) { return res.json({ magnetLink: fixedMagnetLink, infoHash: magnetInfo.infoHash, name: magnetInfo.name, quality: magnetInfo.quality, isMagnetOnly: true }); } else { return res.status(400).json({ error: 'Invalid magnet link', message: 'Could not process the magnet link' }); } } // Analyze the torrent file const result = await analyzeTorrentFromUrl(url); if (!result) { return res.status(404).json({ error: 'Not found', message: 'Could not analyze the torrent or no video files found' }); } res.json(result); } catch (error) { console.error('Error analyzing torrent:', error); res.status(500).json({ error: 'Internal server error', message: error.message }); }});
// Fallback route to fix magnet linksapp.get('/api/fix-magnet', (req, res) => { const magnetUri = req.query.magnet; if (!magnetUri) { return res.status(400).json({ error: 'Bad request', message: 'Missing required parameter: magnet' }); } try { const fixedMagnetUri = fixMagnetUri(magnetUri); const magnetInfo = processMagnetLink(fixedMagnetUri); if (!magnetInfo) { return res.status(400).json({ error: 'Invalid magnet link', message: 'Could not process the magnet link' }); } res.json({ original: magnetUri, fixed: fixedMagnetUri, infoHash: magnetInfo.infoHash, name: magnetInfo.name, trackers: magnetInfo.trackers }); } catch (error) { res.status(500).json({ error: 'Internal server error', message: error.message }); }});
// Serve the frontendapp.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'public', 'index.html'));});
app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); console.log(`Jackett integration: ${JACKETT_CONFIG.baseUrl}`); if (!TMDB_API_KEY) { console.warn('Warning: TMDB_API_KEY not set. TMDB features will not work.'); }});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395// torrent-utils.js - Utility functions for torrent verification and processingimport readTorrent from 'read-torrent';import { promisify } from 'util';import { fixMagnetUri, processMagnetLink } from './magnet-fix.js';
const readTorrentPromise = promisify(readTorrent);
// Video file extensions we consider validconst VIDEO_EXTENSIONS = [ '.mp4', '.mkv', '.avi', '.mov', '.wmv', '.m4v', '.flv', '.webm', '.mpg', '.mpeg', '.ts', '.m2ts', '.vob'];
/** * Checks if a file is a recognized video format * @param {string} filePath - Path or filename to check * @returns {boolean} - True if the file has a video extension */function isVideoFile(filePath) { if (!filePath) return false; const lowercasePath = filePath.toLowerCase(); return VIDEO_EXTENSIONS.some(ext => lowercasePath.endsWith(ext));}
/** * Finds the main video file in a list of files (typically the largest video) * @param {Array} files - Array of files from a torrent * @returns {Object|null} - The main video file object or null if none found */function findMainVideoFile(files) { if (!files || !Array.isArray(files) || files.length === 0) { return null; }
// Filter to only video files const videoFiles = files.filter(file => { const filePath = Array.isArray(file.path) ? file.path.join('/') : file.path; return isVideoFile(filePath); });
if (videoFiles.length === 0) { return null; }
// Sort by size (largest first) and return the largest videoFiles.sort((a, b) => b.length - a.length); return videoFiles[0];}
/** * Checks if a torrent contains video content * @param {Object} torrentInfo - The parsed torrent object * @returns {boolean} - True if the torrent contains video files */function containsVideoContent(torrentInfo) { if (!torrentInfo || !torrentInfo.files || !Array.isArray(torrentInfo.files)) { return false; }
return torrentInfo.files.some(file => { const filePath = Array.isArray(file.path) ? file.path.join('/') : file.path; return isVideoFile(filePath); });}
/** * Estimates video quality based on file size and name * @param {string} fileName - Name of the video file * @param {number} fileSize - Size of the file in bytes * @returns {string} - Estimated quality (4K, 1080p, 720p, etc.) */function estimateQuality(fileName, fileSize) { if (!fileName) return null; // First, check for explicit quality markers in the filename const lowerName = fileName.toLowerCase(); if (lowerName.includes('2160p') || lowerName.includes('4k') || lowerName.includes('uhd')) { return '2160p'; } else if (lowerName.includes('1080p') || lowerName.includes('fhd')) { return '1080p'; } else if (lowerName.includes('720p') || lowerName.includes('hd')) { return '720p'; } else if (lowerName.includes('480p')) { return '480p'; } // If no explicit marker, estimate based on file size if (fileSize) { const sizeGB = fileSize / (1024 * 1024 * 1024); if (sizeGB > 20) { return '2160p'; // Very large files are likely 4K } else if (sizeGB > 4) { return '1080p'; // Large files are likely 1080p } else if (sizeGB > 1.5) { return '720p'; // Medium files are likely 720p } else { return '480p'; // Small files are likely SD } } return null; // Can't determine quality}
/** * Extracts a magnet link from a torrent object * @param {Object} torrentInfo - The parsed torrent information * @returns {string|null} - Magnet URI or null if not possible */function createMagnetLink(torrentInfo) { if (!torrentInfo || !torrentInfo.infoHash) { return null; }
let magnetUri = `magnet:?xt=urn:btih:${torrentInfo.infoHash}`; // Add name if available if (torrentInfo.name) { magnetUri += `&dn=${encodeURIComponent(torrentInfo.name)}`; } // Add trackers if available if (torrentInfo.announce && Array.isArray(torrentInfo.announce)) { torrentInfo.announce.forEach(tracker => { magnetUri += `&tr=${encodeURIComponent(tracker)}`; }); } return magnetUri;}
/** * Extract a magnet URI from an error message if possible * @param {Error} error - The error potentially containing a magnet URI * @returns {string|null} - Extracted magnet URI or null if not found */function extractMagnetFromError(error) { if (!error || !error.message) return null; // Look for a magnet URI pattern in the error message const magnetMatch = error.message.match(/(magnet:\/?[^"'\s]+)/i); if (magnetMatch && magnetMatch[1]) { return magnetMatch[1]; } return null;}
/** * Extract possible magnet link or info hash from URL or filename * @param {string} url - URL or filename to analyze * @returns {Object|null} - Object with extracted info or null */function extractTorrentInfoFromString(url) { if (!url) return null; // Try to extract info hash from URL or filename const infoHashMatch = url.match(/([a-fA-F0-9]{40})/); if (infoHashMatch) { const infoHash = infoHashMatch[1].toLowerCase(); const name = url.split('/').pop().replace(/\.[^.]+$/, ''); // Extract filename without extension // Create a basic magnet link with the info hash const magnetUri = `magnet:?xt=urn:btih:${infoHash}&dn=${encodeURIComponent(name)}`; return { magnetLink: magnetUri, infoHash: infoHash, name: name, quality: estimateQuality(name, 0) }; } // Extract any magnet link in the URL const magnetMatch = url.match(/(magnet:[^"'\s]+)/i); if (magnetMatch) { const magnetUri = fixMagnetUri(magnetMatch[1]); const magnetInfo = processMagnetLink(magnetUri); if (magnetInfo) { return { magnetLink: magnetUri, infoHash: magnetInfo.infoHash, name: magnetInfo.name, quality: magnetInfo.quality }; } } // Just extract the filename as a fallback const filename = url.split('/').pop(); return { magnetLink: null, infoHash: null, name: filename, filename: filename, quality: estimateQuality(filename, 0) };}
/** * Try to download a torrent with retries * @param {string} url - URL to torrent file * @param {number} maxRetries - Maximum number of retry attempts * @param {number} timeout - Timeout for each attempt * @returns {Object|null} - Torrent info or null if failed */async function downloadTorrentWithRetry(url, maxRetries = 2, timeout = 10000) { const options = { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Accept': '*/*', 'Accept-Language': 'en-US,en;q=0.9', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' }, timeout: timeout // Timeout to prevent hanging };
for (let attempt = 0; attempt < maxRetries; attempt++) { try { console.log(`Attempt ${attempt + 1}/${maxRetries} to download torrent from ${url}`); return await readTorrentPromise(url, options); } catch (error) { console.error(`Attempt ${attempt + 1}/${maxRetries} failed:`, error.message); // Check if the error contains a magnet URI const magnetUri = extractMagnetFromError(error); if (magnetUri) { console.log('Found magnet URI in error, will process it directly'); // Return special value to indicate magnet was found return { _isMagnetFromError: true, magnetUri: magnetUri }; } // If this is the last attempt, throw the error if (attempt === maxRetries - 1) { throw error; } // Wait before next retry (exponential backoff) const backoffTime = 1000 * Math.pow(2, attempt); console.log(`Waiting ${backoffTime}ms before next attempt...`); await new Promise(resolve => setTimeout(resolve, backoffTime)); } } // Should never reach here, but just in case throw new Error('Failed to download torrent after all retries');}
/** * Downloads and analyzes a torrent file from URL with timeout protection * @param {string} url - URL to the torrent file * @param {number} globalTimeout - Overall timeout for the entire operation * @returns {Object|null} - Processed torrent info or null if invalid */async function analyzeTorrentFromUrl(url, globalTimeout = 30000) { // Create a promise that rejects after the timeout const timeoutPromise = new Promise((_, reject) => { const id = setTimeout(() => { clearTimeout(id); reject(new Error('Operation timed out after ' + globalTimeout + 'ms')); }, globalTimeout); }); try { // Race the actual operation against the timeout return await Promise.race([ _analyzeTorrentFromUrl(url), timeoutPromise ]); } catch (error) { console.error('Torrent analysis failed with timeout or other error:', error.message); // Try to extract basic info from the URL as a fallback return extractTorrentInfoFromString(url); }}
/** * Core implementation of torrent analysis logic * @private */async function _analyzeTorrentFromUrl(url) { try { console.log('Analyzing torrent from:', url); // FIRST check if the URL is a magnet link and handle it directly if (url.startsWith('magnet:')) { console.log('URL is a magnet link, fixing if needed and processing directly'); const fixedMagnetUri = fixMagnetUri(url); // Fix it first // Process the fixed magnet URI const magnetInfo = processMagnetLink(fixedMagnetUri); if (magnetInfo) { return { magnetLink: fixedMagnetUri, infoHash: magnetInfo.infoHash, name: magnetInfo.name, filename: magnetInfo.name, mainFileSize: 0, // We don't know the size from just the magnet link quality: estimateQuality(magnetInfo.name, 0) }; } console.log('Failed to extract valid info from magnet link'); return null; } // For actual torrent file URLs, try to download with retry logic try { const torrentResult = await downloadTorrentWithRetry(url); // Check if we got a magnet from the error if (torrentResult && torrentResult._isMagnetFromError) { console.log('Processing magnet URI extracted from error'); const fixedMagnetUri = fixMagnetUri(torrentResult.magnetUri); const magnetInfo = processMagnetLink(fixedMagnetUri); if (magnetInfo) { return { magnetLink: fixedMagnetUri, infoHash: magnetInfo.infoHash, name: magnetInfo.name, filename: magnetInfo.name, mainFileSize: 0, quality: estimateQuality(magnetInfo.name, 0) }; } return null; } // We got a valid torrent, proceed with normal processing if (!torrentResult || !torrentResult.files) { console.log('No valid torrent info or files found'); return extractTorrentInfoFromString(url); } // Verify this torrent contains video files if (!containsVideoContent(torrentResult)) { console.log('No video files found in torrent'); return extractTorrentInfoFromString(url); } // Find the main video file const mainFile = findMainVideoFile(torrentResult.files); if (!mainFile) { console.log('No main video file identified'); return extractTorrentInfoFromString(url); } const mainFilePath = Array.isArray(mainFile.path) ? mainFile.path.join('/') : mainFile.path; const magnetLink = createMagnetLink(torrentResult); return { magnetLink, infoHash: torrentResult.infoHash, name: torrentResult.name, filename: mainFilePath, mainFileSize: mainFile.length, totalSize: torrentResult.length, fileCount: torrentResult.files.length, files: torrentResult.files.map(file => { const filePath = Array.isArray(file.path) ? file.path.join('/') : file.path; return { path: filePath, size: file.length, isVideo: isVideoFile(filePath) }; }), quality: estimateQuality(mainFilePath, mainFile.length) }; } catch (error) { console.error('Download/processing of torrent failed:', error.message); // As a fallback, try to extract info from the URL itself return extractTorrentInfoFromString(url); } } catch (error) { console.error('Error analyzing torrent:', error.message); return null; }}
export { analyzeTorrentFromUrl, isVideoFile, findMainVideoFile, containsVideoContent, estimateQuality, createMagnetLink, extractMagnetFromError, extractTorrentInfoFromString};jackett.jsAdded+364
magnet-fix.jsAdded+129
package.jsonAdded+24
server-with-jackett.jsAdded+500
torrent-utils.jsAdded+395