Upload 4 files
Browse filesFiles changed (4)
- Dockerfile+19-37
- kick.jsAdded+120
- package.jsonAdded+26
- server.jsAdded+290
12345678910111213141516171819202122232425262728293031323334353637# Stage 1: Use Alpine to install required toolsFROM alpine:latest AS builderRUN apk add --no-cache curl jq# Stage 2: Use the original imageFROM registry.hf.space/hankchin-ai-ui:latest# Copy required binaries from Alpine stageCOPY --from=builder /usr/bin/curl /usr/bin/curlCOPY --from=builder /usr/bin/jq /usr/bin/jq# Create necessary directories with proper permissionsRUN mkdir -p /usr/src/app/log /usr/src/app/cache /usr/src/app/public && \chmod -R 755 /usr/src/app && \chown -R node:node /usr/src/app# Ensure necessary files and directories have correct permissionsRUN chmod -R 755 /usr/src/app && \chown -R node:node /usr/src/app# Set user to node for better securityUSER node# Expose the port the application runs onEXPOSE 7000# Set environment variables# BASE_URL=http://localhost:7000# CATALOG_CONTENT_CACHE_DURATION=3d# RPDB_POSTER_CACHE_DURATION=3d# LOG_INTERVAL_DELETION=3d# LOG_LEVEL=info# NODE_ENV=production# PORT=7000# Run the applicationCMD ["node", "index.js"]12345678910111213141516171819FROM node:20-slimWORKDIR /code# Copy package filesCOPY package*.json ./# Install dependencies (adding dotenv)RUN npm install express node-fetch cors dotenv# Bundle app sourceCOPY . .# Default environment variables if not provided at runtimeENV PORT=7860ENV NODE_ENV=production# Start the applicationCMD ["node", "server.js"]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120import fetch from 'node-fetch';
// ✅ Extracts video quality from title
function extractQuality(title) {
if (!title) return '';
const qualityMatch = title.match(/\b(2160p|1080p|720p|4k|uhd|WEBRip|BluRay|REMUX)\b/i);
return qualityMatch ? qualityMatch[1].toLowerCase() : '';
}
// ✅ Formats size into human-readable format
function formatSize(bytes) {
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0 B';
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;
}
// ✅ Extracts magnet link from "Guid"
function extractMagnetFromGuid(guid) {
if (!guid) return null;
const magnetMatch = guid.match(/magnet:\?xt=urn:btih:[A-Za-z0-9]+[^"'\s]*/);
return magnetMatch ? magnetMatch[0] : null;
}
// ✅ Removes the year from queries
function cleanQuery(query) {
return query.replace(/\(\d{4}\)/g, '').trim(); // Removes (YYYY)
}
// ✅ Caches results to prevent duplicate requests
const cache = new Map();
// ✅ Fetch data from Jackett API (KickassTorrents)
async function fetchRSSFeeds(searchQuery, type = 'movie') {
const cleanedQuery = cleanQuery(searchQuery);
console.log(`🔄 Fetching RSS feed for: "${cleanedQuery}"`);
if (cache.has(cleanedQuery)) {
console.log(`⚡ Using cached results for: "${cleanedQuery}"`);
return cache.get(cleanedQuery);
}
const API_URL = `http://108.235.59.57:9117/api/v2.0/indexers/all/results?apikey=fpd190akyklnljgxah7xlagid9s62moe&Query=${encodeURIComponent(cleanedQuery)}&Category%5B%5D=2000&Category%5B%5D=5000&Category%5B%5D=8000&Category%5B%5D=103583&Category%5B%5D=112696&Category%5B%5D=138096&Tracker%5B%5D=kickasstorrents-ws&_=1741811334192`;
try {
await new Promise(resolve => setTimeout(resolve, 2000)); // Prevents bot detection
const response = await fetch(API_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',
'Accept-Language': 'en-US,en;q=0.9',
'Connection': 'keep-alive',
'Cookie': 'Jackett=your_cookie_here' // ✅ Use your Jackett cookie if required
}
});
if (!response.ok) {
throw new Error(`❌ Failed to fetch Jackett API: ${response.status}`);
}
const jsonResponse = await response.text();
const data = JSON.parse(jsonResponse);
const results = data.Results || [];
const streams = results.map((item) => {
if (!item || !item.Title || !item.Guid) return null;
// ✅ Extract magnet link from "Guid"
const magnetLink = extractMagnetFromGuid(item.Guid);
if (!magnetLink) return null;
// ✅ Extract size
const size = item.Size ? formatSize(item.Size) : 'Unknown';
// ✅ Convert size to bytes for sorting
let sizeInBytes = item.Size || 0;
// ✅ Extract IMDb ID if available
const imdbId = item.Imdb ? `tt${item.Imdb}` : null;
return {
magnetLink,
websiteTitle: item.Title,
quality: extractQuality(item.Title),
size,
source: item.Tracker || 'Unknown',
infoHash: item.InfoHash || null,
seeders: item.Seeders || 0,
peers: item.Peers || 0,
imdbId,
mainFileSize: sizeInBytes,
pubDate: item.PublishDate,
categories: Array.isArray(item.CategoryDesc) ? item.CategoryDesc : [item.CategoryDesc]
};
}).filter(Boolean);
// ✅ Sort by quality and size
streams.sort((a, b) => {
const qualityOrder = { '2160p': 4, '4k': 4, 'uhd': 4, '1080p': 3, '720p': 2 };
const qualityDiff = (qualityOrder[b.quality] || 0) - (qualityOrder[a.quality] || 0);
if (qualityDiff === 0) {
return b.mainFileSize - a.mainFileSize;
}
return qualityDiff;
});
console.log(`✅ Processed ${streams.length} valid streams`);
// ✅ Store result in cache
cache.set(cleanedQuery, streams);
return streams;
} catch (error) {
console.error('❌ Error fetching from Jackett:', error);
return [];
}
}
// ✅ Export function for Stremio addon
export { fetchRSSFeeds };1234567891011121314151617181920212223242526{
"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.js",
"dev": "nodemon server.js"
},
"dependencies": {
"express": "^4.18.2",
"node-fetch": "^3.3.2",
"read-torrent": "^1.3.1",
"fast-xml-parser": "^4.0.0",
"jsdom": "^21.1.0",
"cheerio": "^1.0.0-rc.12"
},
"devDependencies": {
"nodemon": "^3.0.2"
},
"engines": {
"node": ">=18.0.0"
},
"private": true
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290import express from 'express';
import { fetchRSSFeeds } from './rarbg.js';
const app = express();
const port = process.env.PORT || 7860;
const TMDB_API_KEY = 'f051e7366c6105ad4f9aafe4733d9dae';
const TMDB_BASE_URL = 'https://api.themoviedb.org/3';
app.use(express.json());
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 isExactEpisodeMatch(torrentTitle, showTitle, seasonNum, episodeNum) {
if (!torrentTitle || !showTitle) return false;
// Clean up title
torrentTitle = torrentTitle.replace(/\[.*?\]/g, '')
.replace(/\(.*?\)/g, '')
.replace(/\s+/g, ' ')
.trim();
// Normalize the titles
const normalizedTorrentTitle = torrentTitle.toLowerCase();
const normalizedShowTitle = showTitle.toLowerCase().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'),
new RegExp(`${seasonNum}x${episodeStr}`, 'i'),
new RegExp(`[^0-9]${seasonNum}${episodeStr}[^0-9]`, 'i'),
new RegExp(`season\\s*${seasonNum}\\s*episode\\s*${episodeNum}`, 'i'),
new RegExp(`s${seasonStr}\\.?e${episodeStr}`, 'i'),
new RegExp(`${seasonStr}${episodeStr}`, 'i')
];
return patterns.some(pattern => pattern.test(normalizedTorrentTitle));
}
function isExactMovieMatch(torrentTitle, movieTitle, year) {
// Clean title
torrentTitle = torrentTitle.replace(/\[.*?\]/g, '')
.replace(/\(.*?\)/g, '')
.replace(/\s+/g, ' ')
.trim();
const normalizedTorrentTitle = torrentTitle.toLowerCase();
const normalizedMovieTitle = movieTitle.toLowerCase();
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;
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 {
const [showResponse, episodeResponse] = await Promise.all([
fetch(`${TMDB_BASE_URL}/tv/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`),
fetch(`${TMDB_BASE_URL}/tv/${tmdbId}/season/${seasonNum}/episode/${episodeNum}?api_key=${TMDB_API_KEY}`)
]);
if (!showResponse.ok || !episodeResponse.ok) {
throw new Error('TMDB API error');
}
const [showData, episodeData] = await Promise.all([
showResponse.json(),
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 }) {
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"
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)
};
searchQuery = `${tmdbData.showTitle} S${String(seasonNum).padStart(2, '0')}E${String(episodeNum).padStart(2, '0')}`;
}
}
// Handle IMDB ID format: "tt1234567:1:1"
else if (query.startsWith('tt')) {
const imdbMatch = query.match(/^(tt\d+):(\d+):(\d+)$/);
if (imdbMatch) {
const [_, imdbId, seasonNum, episodeNum] = imdbMatch;
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?.[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')}`;
}
}
}
}
}
else {
searchQuery = standardizeEpisodeFormat(query);
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?.[0]) {
tmdbData = findData.movie_results[0];
exactMatchParams = {
title: tmdbData.title,
year: new Date(tmdbData.release_date).getFullYear()
};
searchQuery = `${tmdbData.title} (${exactMatchParams.year})`;
}
}
}
else {
const movieYearMatch = query.match(/^(.+?)(?:\s*\(?(\d{4})\)?)?$/);
if (movieYearMatch) {
exactMatchParams = {
title: movieYearMatch[1].trim(),
year: movieYearMatch[2] ? parseInt(movieYearMatch[2]) : null
};
}
}
}
let results = await fetchRSSFeeds(searchQuery, type);
// Filter results based on exact match parameters
if (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
)
);
}
return {
query: searchQuery,
originalQuery: query,
type,
tmdbData,
results: results.map(result => ({
title: result.websiteTitle,
quality: result.quality,
size: result.size,
seeders: 0, // Knaben RSS doesn't provide seeder info
leechers: 0, // Knaben RSS doesn't provide leecher info
magnetLink: result.magnetLink
}))
};
}
app.get('/api/search', async (req, res) => {
try {
const result = await handleSearch({ query: req.query.query, type: req.query.type });
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(req.body);
res.json(result);
} catch (error) {
res.status(500).json({ error: 'Internal server error', message: error.message });
}
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
if (!TMDB_API_KEY) {
console.warn('Warning: TMDB_API_KEY not set. TMDB features will not work.');
}
});Dockerfile+19-37
kick.jsAdded+120
package.jsonAdded+26
server.jsAdded+290