import { ERROR } from './const.js'; import { VIDEO_EXTENSIONS } from './const.js'; const PREMIUMIZE_FALLBACK_KEY = 'pr=mxexukrpfk3uu2t6'; function findBestFile(files, mediaType = 'movie', mediaInfo = null) { if (!files || !Array.isArray(files) || files.length === 0) { console.log('No files available to select from'); return null; } console.log(`Finding best file from ${files.length} files`); console.log('Media type:', mediaType); if (mediaInfo) console.log('Media info:', mediaInfo); // Filter for video files first const videoFiles = files.filter(file => { const filename = (file.path || file.name || '').toLowerCase(); return VIDEO_EXTENSIONS.some(ext => filename.endsWith(ext)); }); if (videoFiles.length === 0) { console.log('No video files found'); return null; } console.log(`Found ${videoFiles.length} video files`); // Filter out unwanted files const mainFiles = videoFiles.filter(file => { const filename = (file.path || file.name || '').toLowerCase(); return !filename.includes('sample') && !filename.includes('trailer') && !filename.includes('extra') && !filename.includes('behind') && !filename.includes('featurette') && !filename.includes('bonus'); }); if (mediaType === 'series' && mediaInfo?.season != null && mediaInfo?.episode != null) { console.log(`Looking for S${mediaInfo.season}E${mediaInfo.episode}`); // Try different episode naming patterns const matchingFile = mainFiles.find(file => { const filename = (file.path || file.name || '').toLowerCase(); // Different episode number formats const patterns = [ new RegExp(`s0?${mediaInfo.season}e0?${mediaInfo.episode}\\b`, 'i'), new RegExp(`\\b${mediaInfo.season}x0?${mediaInfo.episode}\\b`, 'i'), new RegExp(`season[. ]?${mediaInfo.season}[. ]?episode[. ]?${mediaInfo.episode}\\b`, 'i'), new RegExp(`\\b0?${mediaInfo.season}0?${mediaInfo.episode}\\b`), // For 101, 102 format new RegExp(`e0?${mediaInfo.episode}\\b`, 'i') // For folders already in correct season ]; const isMatch = patterns.some(pattern => pattern.test(filename)); if (isMatch) { console.log('Found matching episode:', filename); } return isMatch; }); if (matchingFile) { console.log('Selected episode:', matchingFile.path || matchingFile.name); console.log('Size:', Math.round((matchingFile.size || matchingFile.length) / (1024 * 1024)), 'MB'); return matchingFile; } else { console.log('No matching episode found'); } } // For movies or if no specific episode match found, sort by size mainFiles.sort((a, b) => { const sizeA = a.size || a.length || 0; const sizeB = b.size || b.length || 0; return sizeB - sizeA; }); // For movies, prefer files in root or 'movie' directory if (mediaType === 'movie' && mainFiles.length > 1) { const bestFile = mainFiles.find(file => { const path = (file.path || file.name || '').toLowerCase(); const parts = path.split('/'); return parts.length <= 2 || // Root or single subfolder parts.some(part => part.includes('movie')); }) || mainFiles[0]; // Fallback to largest if no good path match console.log('Selected movie file:', bestFile.path || bestFile.name); console.log('Size:', Math.round((bestFile.size || bestFile.length) / (1024 * 1024)), 'MB'); return bestFile; } if (mainFiles.length > 0) { const selectedFile = mainFiles[0]; console.log('Selected file:', selectedFile.path || selectedFile.name); console.log('Size:', Math.round((selectedFile.size || selectedFile.length) / (1024 * 1024)), 'MB'); return selectedFile; } return null; } class BaseDebrid { #apiKey; constructor(apiKey, prefix) { this.#apiKey = apiKey.replace(`${prefix}=`, ''); } getKey() { return this.#apiKey; } extractMediaInfo(magnetLink) { try { const decodedName = decodeURIComponent(magnetLink.match(/dn=([^&]+)/)?.[1] || ''); console.log('Decoded magnet name:', decodedName); // Check if it's a series by looking for episode patterns const seasonEpMatch = decodedName.match(/S(\d{1,2})(?:E|x)(\d{1,2})/i) || decodedName.match(/Season[. ](\d{1,2})[. ]Episode[. ](\d{1,2})/i); if (seasonEpMatch) { const season = parseInt(seasonEpMatch[1]); const episode = parseInt(seasonEpMatch[2]); console.log(`Detected TV series - Season ${season}, Episode ${episode}`); return { type: 'series', season: season, episode: episode }; } // Look for season/episode in path structure if (decodedName.includes('/')) { const parts = decodedName.split('/'); const seasonMatch = parts.find(p => p.match(/Season[. ]?\d+/i)); if (seasonMatch) { const season = parseInt(seasonMatch.match(/\d+/)[0]); // Look for episode number in filename const lastPart = parts[parts.length - 1]; const episodeMatch = lastPart.match(/(?:E|Episode[. ]?)(\d+)/i); if (episodeMatch) { const episode = parseInt(episodeMatch[1]); return { type: 'series', season: season, episode: episode }; } } } // Look for other series indicators if (decodedName.match(/Season \d+|Complete Series|TV Series|Episodes?/i)) { return { type: 'series' }; } return { type: 'movie' }; } catch (error) { console.error('Error extracting media info:', error); return { type: 'movie' }; } } } class DebridLink extends BaseDebrid { #premiumizeService; constructor(apiKey) { super(apiKey, 'dl'); this.#premiumizeService = new Premiumize(PREMIUMIZE_FALLBACK_KEY); } static canHandle(apiKey) { return apiKey.startsWith('dl='); } async checkCacheStatuses(hashes) { try { console.log('\nšŸ“” DebridLink: Using Premiumize fallback for cache check'); const results = await this.#premiumizeService.checkCacheStatuses(hashes); Object.values(results).forEach(result => { if (result.cached) { result.service = 'DebridLink'; } }); return results; } catch (error) { console.error('Cache check failed:', error); return {}; } } async getStreamUrl(magnetLink) { try { console.log('\nšŸ“„ Using DebridLink to process magnet:', magnetLink.substring(0, 100) + '...'); const data = await this.#request('POST', '/seedbox/add', { body: JSON.stringify({ url: magnetLink, async: true }) }); console.log('Seedbox add response:', data); // Extract potential media info from magnet title const mediaInfo = this.extractMediaInfo(magnetLink); console.log('Extracted media info:', mediaInfo); const bestFile = findBestFile( data.files, mediaInfo.type, mediaInfo ); if (!bestFile) { console.error('No suitable video file found'); throw new Error('No suitable video file found'); } console.log('Selected file for streaming:', bestFile.name); return bestFile.downloadUrl; } catch (error) { console.error('āŒ Failed to get stream URL:', error); throw error; } } async #request(method, path, opts = {}) { try { const url = `https://debrid-link.com/api/v2${path}`; opts = { method, headers: { 'Authorization': `Bearer ${this.getKey()}`, 'Content-Type': 'application/json' }, ...opts }; const res = await fetch(url, opts); const data = await res.json(); if (!data.success) { throw new Error(data.error === 'badToken' ? ERROR.INVALID_API_KEY : `API Error: ${data.error}`); } return data.value; } catch (error) { console.error('Request failed:', error); throw error; } } } class Premiumize extends BaseDebrid { #apiUrl = 'https://www.premiumize.me/api'; #batchSize = 99; constructor(apiKey) { super(apiKey, 'pr'); } static canHandle(apiKey) { return apiKey.startsWith('pr='); } async makeRequest(method, path, opts = {}) { const retries = 3; let lastError; for (let i = 0; i < retries; i++) { try { const url = `${this.#apiUrl}${path}`; console.log(`\nšŸ”· Premiumize Request (Attempt ${i + 1}/${retries}):`, method, path); if (opts.body) console.log('Request Body:', opts.body); const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 30000); if (method === 'POST' && opts.body instanceof FormData) { opts.body.append('apikey', this.getKey()); } const finalUrl = method === 'GET' ? `${url}${url.includes('?') ? '&' : '?'}apikey=${this.getKey()}` : url; const startTime = Date.now(); const response = await fetch(finalUrl, { ...opts, method, signal: controller.signal }); clearTimeout(timeout); console.log(`Response Time: ${Date.now() - startTime}ms`); console.log('Response Status:', response.status); const data = await response.json(); console.log('Response Data:', data); if (data.status === 'error') { if (data.message === 'Invalid API key.') { throw new Error(ERROR.INVALID_API_KEY); } throw new Error(`API Error: ${data.message}`); } return data; } catch (error) { console.log(`Attempt ${i + 1} failed:`, error.message); lastError = error; if (i < retries - 1) { console.log('Retrying after 2 seconds...'); await new Promise(r => setTimeout(r, 2000)); } } } throw lastError; } async checkCacheStatuses(hashes) { try { console.log(`\nšŸ“” Premiumize: Batch checking ${hashes.length} hashes`); console.log('Processing in batches of', this.#batchSize); const results = {}; const batches = []; for (let i = 0; i < hashes.length; i += this.#batchSize) { batches.push(hashes.slice(i, i + this.#batchSize)); } console.log(`Split into ${batches.length} batches`); for (let i = 0; i < batches.length; i++) { const batch = batches[i]; console.log(`\nProcessing batch ${i + 1}/${batches.length} (${batch.length} hashes)`); const params = new URLSearchParams(); batch.forEach(hash => params.append('items[]', hash)); const data = await this.makeRequest('GET', `/cache/check?${params}`); batch.forEach((hash, index) => { results[hash] = { cached: data.response[index], files: [], fileCount: 0, service: 'Premiumize' }; }); if (i < batches.length - 1) { await new Promise(resolve => setTimeout(resolve, 500)); } } const cachedCount = Object.values(results).filter(r => r.cached).length; console.log(`\nPremiumize found ${cachedCount} cached torrents out of ${hashes.length}`); return results; } catch (error) { console.error('Cache check failed:', error); return {}; } } async getStreamUrl(magnetLink) { try { console.log('\nšŸ“„ Using Premiumize to process magnet:', magnetLink.substring(0, 100) + '...'); const body = new FormData(); body.append('src', magnetLink); const data = await this.makeRequest('POST', '/transfer/directdl', { body }); // Extract potential media info from magnet title const mediaInfo = this.extractMediaInfo(magnetLink); console.log('Extracted media info:', mediaInfo); const bestFile = findBestFile( data.content, mediaInfo.type, mediaInfo ); if (!bestFile) { console.error('No suitable video file found'); throw new Error('No suitable video file found'); } console.log('Selected file for streaming:', bestFile.path); return bestFile.stream_link || bestFile.link; } catch (error) { console.error('āŒ Failed to get stream URL:', error); throw error; } } } class TorBox extends BaseDebrid { #apiUrl = 'https://api.torbox.app/v1/api'; constructor(apiKey) { super(apiKey, 'tb'); } static canHandle(apiKey) { return apiKey.startsWith('tb='); } async checkCacheStatuses(hashes) { try { console.log(`\nšŸ“” TorBox: Checking ${hashes.length} hashes`); const results = {}; // Process hashes in batches of 50 const BATCH_SIZE = 50; for (let i = 0; i < hashes.length; i += BATCH_SIZE) { const batchHashes = hashes.slice(i, i + BATCH_SIZE); console.log(`\nProcessing batch of ${batchHashes.length} hashes`); // Join hashes with commas as shown in Python code const hashParams = batchHashes.join(','); const url = `${this.#apiUrl}/torrents/checkcached?hash=${hashParams}&format=list&list_files=true`; console.log('Requesting URL:', url); const response = await fetch(url, { method: 'GET', headers: { 'Authorization': `Bearer ${this.getKey()}` } }); let responseData; try { responseData = await response.json(); } catch (error) { console.error('Failed to parse response:', error); continue; } if (!response.ok) { if (responseData?.error === 'Invalid API key') { throw new Error(ERROR.INVALID_API_KEY); } console.error('Error checking batch:', responseData); continue; } if (responseData.success && Array.isArray(responseData.data)) { // Process each torrent in the response responseData.data.forEach(torrent => { if (torrent && torrent.hash) { const hash = torrent.hash.toLowerCase(); results[hash] = { cached: true, files: torrent.files || [], name: torrent.name || '', size: torrent.size || 0, torrentId: torrent.id, service: 'TorBox' }; } }); } // Set uncached status for hashes not in response batchHashes.forEach(hash => { const hashLower = hash.toLowerCase(); if (!results[hashLower]) { results[hashLower] = { cached: false, files: [], service: 'TorBox' }; } }); if (i + BATCH_SIZE < hashes.length) { await new Promise(resolve => setTimeout(resolve, 100)); } } const cachedCount = Object.values(results).filter(r => r.cached).length; console.log(`\nTorBox found ${cachedCount} cached torrents out of ${hashes.length}`); return results; } catch (error) { console.error('Cache check failed:', error); return {}; } } async getStreamUrl(magnetLink) { try { console.log('\nšŸ“„ Using TorBox to process magnet:', magnetLink.substring(0, 100) + '...'); // Extract info hash from magnet link const hash = magnetLink.match(/btih:([a-f0-9]+)/i)?.[1]?.toLowerCase(); if (!hash) { throw new Error('Invalid magnet link'); } console.log('Checking existing torrents...'); // First check if torrent already exists const listResponse = await fetch( `${this.#apiUrl}/torrents/mylist?bypass_cache=true`, { method: 'GET', headers: { 'Authorization': `Bearer ${this.getKey()}` } } ); const listData = await listResponse.json(); let torrentId; // Check if torrent already exists if (listData.success && Array.isArray(listData.data)) { const existingTorrent = listData.data.find(t => t.hash.toLowerCase() === hash); if (existingTorrent) { console.log('Found existing torrent:', existingTorrent.id); torrentId = existingTorrent.id; } } // If torrent doesn't exist, create it if (!torrentId) { console.log('Creating new torrent...'); const formData = new FormData(); formData.append('magnet', `magnet:?xt=urn:btih:${hash}`); const createResponse = await fetch( `${this.#apiUrl}/torrents/createtorrent`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.getKey()}` }, body: formData } ); const createData = await createResponse.json(); console.log('Create response:', createData); if (!createResponse.ok || !createData.success || !createData.data?.torrent_id) { throw new Error(`Failed to create torrent: ${createData.error || createData.detail || 'Unknown error'}`); } torrentId = createData.data.torrent_id; } // Get file list to find best file const filesResponse = await fetch( `${this.#apiUrl}/torrents/checkcached?hash=${hash}&format=list&list_files=true`, { method: 'GET', headers: { 'Authorization': `Bearer ${this.getKey()}` } } ); const filesData = await filesResponse.json(); if (!filesResponse.ok || !filesData.success || !filesData.data?.[0]?.files) { throw new Error('Failed to get file list'); } const files = filesData.data[0].files.map((file, index) => ({ id: index, // Use index as file ID name: file.name.split('/')[1] || file.name, // Remove folder prefix size: file.size, path: file.name })); // Find best file const mediaInfo = this.extractMediaInfo(magnetLink); console.log('Media info:', mediaInfo); const bestFile = findBestFile(files, mediaInfo.type); if (!bestFile) { throw new Error('No suitable video file found'); } console.log('Selected file:', bestFile.name); // Get download link const dlUrl = `${this.#apiUrl}/torrents/requestdl?token=${this.getKey()}&torrent_id=${torrentId}&file_id=${bestFile.id}&zip=false`; console.log('Requesting download URL:', dlUrl); const dlResponse = await fetch(dlUrl, { method: 'GET' }); const dlData = await dlResponse.json(); if (!dlResponse.ok || !dlData.success || !dlData.data) { throw new Error(`Failed to get download URL: ${dlData.error || dlData.detail || 'Unknown error'}`); } return dlData.data; } catch (error) { console.error('āŒ Failed to get stream URL:', error); throw error; } } } export function getDebridServices(apiKeys) { console.log('\nšŸ” Initializing debrid services with keys:', apiKeys); const services = []; for (const key of apiKeys.split(',')) { if (DebridLink.canHandle(key)) { console.log('Adding DebridLink service'); services.push(new DebridLink(key)); } else if (Premiumize.canHandle(key)) { console.log('Adding Premiumize service'); services.push(new Premiumize(key)); } else if (TorBox.canHandle(key)) { console.log('Adding TorBox service'); services.push(new TorBox(key)); } else { console.log('Unknown service key format:', key); } } console.log(`Initialized ${services.length} debrid services`); return services; } export { DebridLink, Premiumize, TorBox };