mikmc5 commited on
Commit
29150c5
·
verified ·
1 Parent(s): 363ae61

Upload 4 files

Browse files
Files changed (4) hide show
  1. Dockerfile +19 -37
  2. kick.js +120 -0
  3. package.json +26 -0
  4. server.js +290 -0
Dockerfile CHANGED
@@ -1,37 +1,19 @@
1
- # Stage 1: Use Alpine to install required tools
2
- FROM alpine:latest AS builder
3
- RUN apk add --no-cache curl jq
4
-
5
- # Stage 2: Use the original image
6
- FROM registry.hf.space/hankchin-ai-ui:latest
7
-
8
- # Copy required binaries from Alpine stage
9
- COPY --from=builder /usr/bin/curl /usr/bin/curl
10
- COPY --from=builder /usr/bin/jq /usr/bin/jq
11
-
12
- # Create necessary directories with proper permissions
13
- RUN mkdir -p /usr/src/app/log /usr/src/app/cache /usr/src/app/public && \
14
- chmod -R 755 /usr/src/app && \
15
- chown -R node:node /usr/src/app
16
-
17
- # Ensure necessary files and directories have correct permissions
18
- RUN chmod -R 755 /usr/src/app && \
19
- chown -R node:node /usr/src/app
20
-
21
- # Set user to node for better security
22
- USER node
23
-
24
- # Expose the port the application runs on
25
- EXPOSE 7000
26
-
27
- # Set environment variables
28
- # BASE_URL=http://localhost:7000
29
- # CATALOG_CONTENT_CACHE_DURATION=3d
30
- # RPDB_POSTER_CACHE_DURATION=3d
31
- # LOG_INTERVAL_DELETION=3d
32
- # LOG_LEVEL=info
33
- # NODE_ENV=production
34
- # PORT=7000
35
-
36
- # Run the application
37
- CMD ["node", "index.js"]
 
1
+ FROM node:20-slim
2
+
3
+ WORKDIR /code
4
+
5
+ # Copy package files
6
+ COPY package*.json ./
7
+
8
+ # Install dependencies (adding dotenv)
9
+ RUN npm install express node-fetch cors dotenv
10
+
11
+ # Bundle app source
12
+ COPY . .
13
+
14
+ # Default environment variables if not provided at runtime
15
+ ENV PORT=7860
16
+ ENV NODE_ENV=production
17
+
18
+ # Start the application
19
+ CMD ["node", "server.js"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
kick.js ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fetch from 'node-fetch';
2
+
3
+ // ✅ Extracts video quality from title
4
+ function extractQuality(title) {
5
+ if (!title) return '';
6
+ const qualityMatch = title.match(/\b(2160p|1080p|720p|4k|uhd|WEBRip|BluRay|REMUX)\b/i);
7
+ return qualityMatch ? qualityMatch[1].toLowerCase() : '';
8
+ }
9
+
10
+ // ✅ Formats size into human-readable format
11
+ function formatSize(bytes) {
12
+ const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
13
+ if (bytes === 0) return '0 B';
14
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
15
+ return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;
16
+ }
17
+
18
+ // ✅ Extracts magnet link from "Guid"
19
+ function extractMagnetFromGuid(guid) {
20
+ if (!guid) return null;
21
+ const magnetMatch = guid.match(/magnet:\?xt=urn:btih:[A-Za-z0-9]+[^"'\s]*/);
22
+ return magnetMatch ? magnetMatch[0] : null;
23
+ }
24
+
25
+ // ✅ Removes the year from queries
26
+ function cleanQuery(query) {
27
+ return query.replace(/\(\d{4}\)/g, '').trim(); // Removes (YYYY)
28
+ }
29
+
30
+ // ✅ Caches results to prevent duplicate requests
31
+ const cache = new Map();
32
+
33
+ // ✅ Fetch data from Jackett API (KickassTorrents)
34
+ async function fetchRSSFeeds(searchQuery, type = 'movie') {
35
+ const cleanedQuery = cleanQuery(searchQuery);
36
+ console.log(`🔄 Fetching RSS feed for: "${cleanedQuery}"`);
37
+
38
+ if (cache.has(cleanedQuery)) {
39
+ console.log(`⚡ Using cached results for: "${cleanedQuery}"`);
40
+ return cache.get(cleanedQuery);
41
+ }
42
+
43
+ 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`;
44
+
45
+ try {
46
+ await new Promise(resolve => setTimeout(resolve, 2000)); // Prevents bot detection
47
+
48
+ const response = await fetch(API_URL, {
49
+ headers: {
50
+ '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',
51
+ 'Accept-Language': 'en-US,en;q=0.9',
52
+ 'Connection': 'keep-alive',
53
+ 'Cookie': 'Jackett=your_cookie_here' // ✅ Use your Jackett cookie if required
54
+ }
55
+ });
56
+
57
+ if (!response.ok) {
58
+ throw new Error(`❌ Failed to fetch Jackett API: ${response.status}`);
59
+ }
60
+
61
+ const jsonResponse = await response.text();
62
+ const data = JSON.parse(jsonResponse);
63
+ const results = data.Results || [];
64
+
65
+ const streams = results.map((item) => {
66
+ if (!item || !item.Title || !item.Guid) return null;
67
+
68
+ // ✅ Extract magnet link from "Guid"
69
+ const magnetLink = extractMagnetFromGuid(item.Guid);
70
+ if (!magnetLink) return null;
71
+
72
+ // ✅ Extract size
73
+ const size = item.Size ? formatSize(item.Size) : 'Unknown';
74
+
75
+ // ✅ Convert size to bytes for sorting
76
+ let sizeInBytes = item.Size || 0;
77
+
78
+ // ✅ Extract IMDb ID if available
79
+ const imdbId = item.Imdb ? `tt${item.Imdb}` : null;
80
+
81
+ return {
82
+ magnetLink,
83
+ websiteTitle: item.Title,
84
+ quality: extractQuality(item.Title),
85
+ size,
86
+ source: item.Tracker || 'Unknown',
87
+ infoHash: item.InfoHash || null,
88
+ seeders: item.Seeders || 0,
89
+ peers: item.Peers || 0,
90
+ imdbId,
91
+ mainFileSize: sizeInBytes,
92
+ pubDate: item.PublishDate,
93
+ categories: Array.isArray(item.CategoryDesc) ? item.CategoryDesc : [item.CategoryDesc]
94
+ };
95
+ }).filter(Boolean);
96
+
97
+ // ✅ Sort by quality and size
98
+ streams.sort((a, b) => {
99
+ const qualityOrder = { '2160p': 4, '4k': 4, 'uhd': 4, '1080p': 3, '720p': 2 };
100
+ const qualityDiff = (qualityOrder[b.quality] || 0) - (qualityOrder[a.quality] || 0);
101
+ if (qualityDiff === 0) {
102
+ return b.mainFileSize - a.mainFileSize;
103
+ }
104
+ return qualityDiff;
105
+ });
106
+
107
+ console.log(`✅ Processed ${streams.length} valid streams`);
108
+
109
+ // ✅ Store result in cache
110
+ cache.set(cleanedQuery, streams);
111
+
112
+ return streams;
113
+ } catch (error) {
114
+ console.error('❌ Error fetching from Jackett:', error);
115
+ return [];
116
+ }
117
+ }
118
+
119
+ // ✅ Export function for Stremio addon
120
+ export { fetchRSSFeeds };
package.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "torrent-api",
3
+ "version": "1.0.0",
4
+ "description": "API server for searching torrents with TMDB integration",
5
+ "main": "server.js",
6
+ "type": "module",
7
+ "scripts": {
8
+ "start": "node server.js",
9
+ "dev": "nodemon server.js"
10
+ },
11
+ "dependencies": {
12
+ "express": "^4.18.2",
13
+ "node-fetch": "^3.3.2",
14
+ "read-torrent": "^1.3.1",
15
+ "fast-xml-parser": "^4.0.0",
16
+ "jsdom": "^21.1.0",
17
+ "cheerio": "^1.0.0-rc.12"
18
+ },
19
+ "devDependencies": {
20
+ "nodemon": "^3.0.2"
21
+ },
22
+ "engines": {
23
+ "node": ">=18.0.0"
24
+ },
25
+ "private": true
26
+ }
server.js ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from 'express';
2
+ import { fetchRSSFeeds } from './rarbg.js';
3
+
4
+ const app = express();
5
+ const port = process.env.PORT || 7860;
6
+ const TMDB_API_KEY = 'f051e7366c6105ad4f9aafe4733d9dae';
7
+ const TMDB_BASE_URL = 'https://api.themoviedb.org/3';
8
+
9
+ app.use(express.json());
10
+
11
+ function standardizeEpisodeFormat(query) {
12
+ // Handle 1x01 format
13
+ const altMatch = query.match(/^(.*?)(\d{1,2})x(\d{1,2})/i);
14
+ if (altMatch) {
15
+ const [_, title, season, episode] = altMatch;
16
+ const paddedSeason = String(season).padStart(2, '0');
17
+ const paddedEpisode = String(episode).padStart(2, '0');
18
+ return `${title.trim()} S${paddedSeason}E${paddedEpisode}`;
19
+ }
20
+ return query;
21
+ }
22
+
23
+ function isExactEpisodeMatch(torrentTitle, showTitle, seasonNum, episodeNum) {
24
+ if (!torrentTitle || !showTitle) return false;
25
+
26
+ // Clean up title
27
+ torrentTitle = torrentTitle.replace(/\[.*?\]/g, '')
28
+ .replace(/\(.*?\)/g, '')
29
+ .replace(/\s+/g, ' ')
30
+ .trim();
31
+
32
+ // Normalize the titles
33
+ const normalizedTorrentTitle = torrentTitle.toLowerCase();
34
+ const normalizedShowTitle = showTitle.toLowerCase().trim();
35
+
36
+ // Split show title into significant words
37
+ const showWords = normalizedShowTitle.split(' ')
38
+ .filter(word => word.length > 2)
39
+ .filter(word => !['the', 'and', 'or', 'in', 'on', 'at', 'to'].includes(word));
40
+
41
+ const hasAllShowWords = showWords.every(word =>
42
+ normalizedTorrentTitle.includes(word)
43
+ );
44
+
45
+ if (!hasAllShowWords) return false;
46
+
47
+ // Format season and episode numbers
48
+ const seasonStr = String(seasonNum).padStart(2, '0');
49
+ const episodeStr = String(episodeNum).padStart(2, '0');
50
+
51
+ // Common episode patterns
52
+ const patterns = [
53
+ new RegExp(`s${seasonStr}e${episodeStr}`, 'i'),
54
+ new RegExp(`${seasonNum}x${episodeStr}`, 'i'),
55
+ new RegExp(`[^0-9]${seasonNum}${episodeStr}[^0-9]`, 'i'),
56
+ new RegExp(`season\\s*${seasonNum}\\s*episode\\s*${episodeNum}`, 'i'),
57
+ new RegExp(`s${seasonStr}\\.?e${episodeStr}`, 'i'),
58
+ new RegExp(`${seasonStr}${episodeStr}`, 'i')
59
+ ];
60
+
61
+ return patterns.some(pattern => pattern.test(normalizedTorrentTitle));
62
+ }
63
+
64
+ function isExactMovieMatch(torrentTitle, movieTitle, year) {
65
+ // Clean title
66
+ torrentTitle = torrentTitle.replace(/\[.*?\]/g, '')
67
+ .replace(/\(.*?\)/g, '')
68
+ .replace(/\s+/g, ' ')
69
+ .trim();
70
+
71
+ const normalizedTorrentTitle = torrentTitle.toLowerCase();
72
+ const normalizedMovieTitle = movieTitle.toLowerCase();
73
+
74
+ const movieWords = normalizedMovieTitle.split(' ')
75
+ .filter(word => word.length > 2)
76
+ .filter(word => !['the', 'and', 'or', 'in', 'on', 'at', 'to'].includes(word));
77
+
78
+ const hasAllMovieWords = movieWords.every(word =>
79
+ normalizedTorrentTitle.includes(word)
80
+ );
81
+
82
+ if (!hasAllMovieWords) return false;
83
+
84
+ const yearMatch = torrentTitle.match(/(?:19|20)\d{2}/);
85
+ return yearMatch && yearMatch[0] === year.toString();
86
+ }
87
+
88
+ async function getTMDBDetails(tmdbId, type = 'movie') {
89
+ try {
90
+ const response = await fetch(`${TMDB_BASE_URL}/${type}/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`);
91
+ if (!response.ok) throw new Error(`TMDB API error: ${response.status}`);
92
+ return await response.json();
93
+ } catch (error) {
94
+ console.error('TMDB fetch error:', error);
95
+ return null;
96
+ }
97
+ }
98
+
99
+ async function getTVShowDetails(tmdbId, seasonNum, episodeNum) {
100
+ try {
101
+ const [showResponse, episodeResponse] = await Promise.all([
102
+ fetch(`${TMDB_BASE_URL}/tv/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`),
103
+ fetch(`${TMDB_BASE_URL}/tv/${tmdbId}/season/${seasonNum}/episode/${episodeNum}?api_key=${TMDB_API_KEY}`)
104
+ ]);
105
+
106
+ if (!showResponse.ok || !episodeResponse.ok) {
107
+ throw new Error('TMDB API error');
108
+ }
109
+
110
+ const [showData, episodeData] = await Promise.all([
111
+ showResponse.json(),
112
+ episodeResponse.json()
113
+ ]);
114
+
115
+ return {
116
+ showTitle: showData.name,
117
+ episodeTitle: episodeData.name,
118
+ seasonNumber: seasonNum,
119
+ episodeNumber: episodeNum,
120
+ airDate: episodeData.air_date,
121
+ imdbId: showData.external_ids?.imdb_id
122
+ };
123
+ } catch (error) {
124
+ console.error('TMDB fetch error:', error);
125
+ return null;
126
+ }
127
+ }
128
+
129
+ async function handleSearch({ query, type }) {
130
+ if (!query) throw new Error('Missing required parameter: query');
131
+ if (!['movie', 'series'].includes(type)) throw new Error('Invalid type. Must be either "movie" or "series"');
132
+
133
+ let searchQuery = query;
134
+ let exactMatchParams = {};
135
+ let tmdbData = null;
136
+
137
+ if (type === 'series') {
138
+ // Handle TMDB ID format: "tmdb:12345:1:1"
139
+ const tmdbMatch = query.match(/^tmdb:(\d+):(\d+):(\d+)$/);
140
+ if (tmdbMatch) {
141
+ const [_, tmdbId, seasonNum, episodeNum] = tmdbMatch;
142
+ tmdbData = await getTVShowDetails(tmdbId, parseInt(seasonNum), parseInt(episodeNum));
143
+ if (tmdbData) {
144
+ exactMatchParams = {
145
+ title: tmdbData.showTitle,
146
+ season: parseInt(seasonNum),
147
+ episode: parseInt(episodeNum)
148
+ };
149
+ searchQuery = `${tmdbData.showTitle} S${String(seasonNum).padStart(2, '0')}E${String(episodeNum).padStart(2, '0')}`;
150
+ }
151
+ }
152
+ // Handle IMDB ID format: "tt1234567:1:1"
153
+ else if (query.startsWith('tt')) {
154
+ const imdbMatch = query.match(/^(tt\d+):(\d+):(\d+)$/);
155
+ if (imdbMatch) {
156
+ const [_, imdbId, seasonNum, episodeNum] = imdbMatch;
157
+ const findResponse = await fetch(
158
+ `${TMDB_BASE_URL}/find/${imdbId}?api_key=${TMDB_API_KEY}&external_source=imdb_id`
159
+ );
160
+ if (findResponse.ok) {
161
+ const findData = await findResponse.json();
162
+ if (findData.tv_results?.[0]) {
163
+ const tmdbId = findData.tv_results[0].id;
164
+ tmdbData = await getTVShowDetails(tmdbId, parseInt(seasonNum), parseInt(episodeNum));
165
+ if (tmdbData) {
166
+ exactMatchParams = {
167
+ title: tmdbData.showTitle,
168
+ season: parseInt(seasonNum),
169
+ episode: parseInt(episodeNum)
170
+ };
171
+ searchQuery = `${tmdbData.showTitle} S${String(seasonNum).padStart(2, '0')}E${String(episodeNum).padStart(2, '0')}`;
172
+ }
173
+ }
174
+ }
175
+ }
176
+ }
177
+ else {
178
+ searchQuery = standardizeEpisodeFormat(query);
179
+ const seasonEpisodeMatch = searchQuery.match(/^(.*?)S(\d{1,2})E(\d{1,2})/i);
180
+ if (seasonEpisodeMatch) {
181
+ exactMatchParams = {
182
+ title: seasonEpisodeMatch[1].trim(),
183
+ season: parseInt(seasonEpisodeMatch[2]),
184
+ episode: parseInt(seasonEpisodeMatch[3])
185
+ };
186
+ }
187
+ }
188
+ } else if (type === 'movie') {
189
+ // Handle TMDB ID format
190
+ if (query.startsWith('tmdb:')) {
191
+ const tmdbId = query.replace('tmdb:', '');
192
+ tmdbData = await getTMDBDetails(tmdbId, 'movie');
193
+ if (tmdbData) {
194
+ exactMatchParams = {
195
+ title: tmdbData.title,
196
+ year: new Date(tmdbData.release_date).getFullYear()
197
+ };
198
+ searchQuery = `${tmdbData.title} (${exactMatchParams.year})`;
199
+ }
200
+ }
201
+ // Handle IMDB ID format
202
+ else if (query.startsWith('tt')) {
203
+ const findResponse = await fetch(
204
+ `${TMDB_BASE_URL}/find/${query}?api_key=${TMDB_API_KEY}&external_source=imdb_id`
205
+ );
206
+ if (findResponse.ok) {
207
+ const findData = await findResponse.json();
208
+ if (findData.movie_results?.[0]) {
209
+ tmdbData = findData.movie_results[0];
210
+ exactMatchParams = {
211
+ title: tmdbData.title,
212
+ year: new Date(tmdbData.release_date).getFullYear()
213
+ };
214
+ searchQuery = `${tmdbData.title} (${exactMatchParams.year})`;
215
+ }
216
+ }
217
+ }
218
+ else {
219
+ const movieYearMatch = query.match(/^(.+?)(?:\s*\(?(\d{4})\)?)?$/);
220
+ if (movieYearMatch) {
221
+ exactMatchParams = {
222
+ title: movieYearMatch[1].trim(),
223
+ year: movieYearMatch[2] ? parseInt(movieYearMatch[2]) : null
224
+ };
225
+ }
226
+ }
227
+ }
228
+
229
+ let results = await fetchRSSFeeds(searchQuery, type);
230
+
231
+ // Filter results based on exact match parameters
232
+ if (type === 'series' && exactMatchParams.season !== undefined) {
233
+ results = results.filter(result =>
234
+ isExactEpisodeMatch(
235
+ result.websiteTitle,
236
+ exactMatchParams.title,
237
+ exactMatchParams.season,
238
+ exactMatchParams.episode
239
+ )
240
+ );
241
+ } else if (type === 'movie' && exactMatchParams.year) {
242
+ results = results.filter(result =>
243
+ isExactMovieMatch(
244
+ result.websiteTitle,
245
+ exactMatchParams.title,
246
+ exactMatchParams.year
247
+ )
248
+ );
249
+ }
250
+
251
+ return {
252
+ query: searchQuery,
253
+ originalQuery: query,
254
+ type,
255
+ tmdbData,
256
+ results: results.map(result => ({
257
+ title: result.websiteTitle,
258
+ quality: result.quality,
259
+ size: result.size,
260
+ seeders: 0, // Knaben RSS doesn't provide seeder info
261
+ leechers: 0, // Knaben RSS doesn't provide leecher info
262
+ magnetLink: result.magnetLink
263
+ }))
264
+ };
265
+ }
266
+
267
+ app.get('/api/search', async (req, res) => {
268
+ try {
269
+ const result = await handleSearch({ query: req.query.query, type: req.query.type });
270
+ res.json(result);
271
+ } catch (error) {
272
+ res.status(500).json({ error: 'Internal server error', message: error.message });
273
+ }
274
+ });
275
+
276
+ app.post('/api/search', async (req, res) => {
277
+ try {
278
+ const result = await handleSearch(req.body);
279
+ res.json(result);
280
+ } catch (error) {
281
+ res.status(500).json({ error: 'Internal server error', message: error.message });
282
+ }
283
+ });
284
+
285
+ app.listen(port, () => {
286
+ console.log(`Server running at http://localhost:${port}`);
287
+ if (!TMDB_API_KEY) {
288
+ console.warn('Warning: TMDB_API_KEY not set. TMDB features will not work.');
289
+ }
290
+ });