calculus / src /torrenting.js
no1b4me's picture
Update src/torrenting.js
396151e verified
raw
history blame
6.6 kB
import xml2js from 'xml2js';
import readTorrent from 'read-torrent';
import { promisify } from 'util';
const readTorrentPromise = promisify(readTorrent);
const RSS_FEEDS = [
{
name: 'TT',
url: 'https://torrenting.com/t.rss?5;18;4;82;49;99;47;38;11;55;3;40;1;download;u=1750838;tp=axsrnyklbmpybwmsysakkectdkwjkrhb;mikmc;private;do-not-share',
domain: 'torrenting.com'
}
];
const parser = new xml2js.Parser({
explicitArray: false,
ignoreAttrs: true
});
function parseTorrentInfo(item) {
const desc = item.description || '';
const match = desc.match(/Category:\s*([^]+?)Size:\s*([^]+?)$/);
if (!match) {
return { size: 'Unknown', category: 'Unknown', sizeInMB: 0 };
}
const category = match[1].trim();
const size = match[2].trim();
const sizeMatch = size.match(/([\d.]+)\s*(GB|MB|TB)/i);
let sizeInMB = 0;
if (sizeMatch) {
const [, value, unit] = sizeMatch;
sizeInMB = parseFloat(value);
switch (unit.toUpperCase()) {
case 'TB':
sizeInMB *= 1024 * 1024;
break;
case 'GB':
sizeInMB *= 1024;
break;
}
}
return { size, category, sizeInMB };
}
async function downloadAndParseTorrent(url) {
try {
console.log('Downloading torrent from:', url);
const options = {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': '*/*',
'Referer': 'https://torrenting.com/',
'Origin': 'https://torrenting.com'
}
};
const torrentInfo = await readTorrentPromise(url, options);
console.log('Parsed torrent info:', {
name: torrentInfo.name,
length: torrentInfo.length,
files: torrentInfo.files?.length || 0
});
if (!torrentInfo?.infoHash) {
console.error('No info hash found');
return null;
}
const videoFiles = torrentInfo.files?.filter(file => {
const filePath = Array.isArray(file.path) ? file.path.join('/') : file.path;
return /\.(mp4|mkv|avi|mov|wmv)$/i.test(filePath);
}) || [];
if (videoFiles.length === 0) {
console.log('No video files found');
return null;
}
videoFiles.sort((a, b) => b.length - a.length);
const mainFile = videoFiles[0];
const mainFilePath = Array.isArray(mainFile.path) ? mainFile.path.join('/') : mainFile.path;
const magnetUri = `magnet:?xt=urn:btih:${torrentInfo.infoHash}` +
`&dn=${encodeURIComponent(torrentInfo.name)}` +
(torrentInfo.announce ? torrentInfo.announce.map(tr => `&tr=${encodeURIComponent(tr)}`).join('') : '');
return {
magnetLink: magnetUri,
files: videoFiles,
infoHash: torrentInfo.infoHash,
mainFile: {
path: mainFilePath,
length: mainFile.length
}
};
} catch (error) {
console.error('Error:', error);
return null;
}
}
async function fetchRSSFeeds(imdbId) {
console.log('\n🔄 Fetching RSS feeds for:', imdbId);
let allStreams = [];
for (const feed of RSS_FEEDS) {
try {
console.log(`\nFetching from ${feed.name}...`);
const rssUrl = `${feed.url}&q=${imdbId}`;
const response = await fetch(rssUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/rss+xml,application/xml,text/xml',
'Referer': 'https://torrenting.com/',
'Origin': 'https://torrenting.com'
}
});
if (!response.ok) {
console.error(`❌ Failed to fetch from ${feed.name}:`, response.status);
continue;
}
const rssData = await response.text();
const result = await parser.parseStringPromise(rssData);
if (!result?.rss?.channel?.item) {
console.log(`No items found in ${feed.name}`);
continue;
}
const items = Array.isArray(result.rss.channel.item) ?
result.rss.channel.item : [result.rss.channel.item];
console.log(`Found ${items.length} items in ${feed.name}`);
const streams = await Promise.all(items.map(async (item, index) => {
try {
console.log(`\nProcessing item ${index + 1}/${items.length}:`, item.title);
const torrentInfo = await downloadAndParseTorrent(item.link);
if (!torrentInfo) return null;
const { size, category } = parseTorrentInfo(item);
const quality = extractQuality(item.title);
return {
magnetLink: torrentInfo.magnetLink,
filename: torrentInfo.mainFile.path,
websiteTitle: item.title,
quality,
size,
category,
source: feed.name,
infoHash: torrentInfo.infoHash,
mainFileSize: torrentInfo.mainFile.length,
pubDate: item.pubDate
};
} catch (error) {
console.error(`Error processing item ${index + 1}:`, error);
return null;
}
}));
const validStreams = streams.filter(Boolean);
console.log(`✅ Processed ${validStreams.length} valid streams from ${feed.name}`);
allStreams = [...allStreams, ...validStreams];
} catch (error) {
console.error(`❌ Error fetching ${feed.name}:`, error);
}
}
allStreams.sort((a, b) => {
const qualityOrder = { '2160p': 4, '4k': 4, 'uhd': 4, '1080p': 3, '720p': 2 };
return (qualityOrder[b.quality] || 0) - (qualityOrder[a.quality] || 0);
});
return allStreams;
}
function extractQuality(title) {
const qualityMatch = title.match(/\b(2160p|1080p|720p|4k|uhd)\b/i);
return qualityMatch ? qualityMatch[1].toLowerCase() : '';
}
export { fetchRSSFeeds };