File size: 9,592 Bytes
1fa01b6
 
2e38ad5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fa01b6
 
2e38ad5
1fa01b6
 
 
 
 
 
 
2e38ad5
 
 
 
 
1fa01b6
 
4b287a3
1fa01b6
4b287a3
 
 
 
 
 
1fa01b6
 
2e38ad5
 
 
 
 
 
 
 
2d3873e
2e38ad5
2d3873e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e38ad5
2d3873e
2e38ad5
 
 
1fa01b6
 
 
2e38ad5
 
1fa01b6
 
2e38ad5
 
 
 
1fa01b6
 
 
 
 
 
2e38ad5
 
1fa01b6
 
2e38ad5
1fa01b6
 
 
 
2e38ad5
 
 
 
1fa01b6
 
 
 
2e38ad5
1fa01b6
 
2e38ad5
 
 
 
 
 
 
 
 
1fa01b6
2e38ad5
1fa01b6
2e38ad5
 
2d3873e
2e38ad5
2d3873e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fa01b6
2e38ad5
 
 
 
 
 
1fa01b6
2e38ad5
 
1fa01b6
2e38ad5
 
1fa01b6
2e38ad5
 
1fa01b6
2e38ad5
 
 
 
1fa01b6
 
2e38ad5
 
 
1fa01b6
2e38ad5
 
 
 
1fa01b6
2e38ad5
 
 
 
 
 
 
 
 
1fa01b6
 
 
2e38ad5
1fa01b6
2e38ad5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fa01b6
 
2e38ad5
 
 
1fa01b6
 
2e38ad5
1fa01b6
 
 
 
 
 
2e38ad5
1fa01b6
 
 
 
2e38ad5
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import fetch from 'node-fetch';

// βœ… Maps quality numbers to standard formats
function mapQualityToStandard(quality, title) {
    if (!quality && !title) return '';
    
    // Check title for quality indicators first
    const titleQuality = title ? title.match(/\b(2160p|1080p|720p|4k|uhd|WEBRip|BluRay|REMUX|BDRemux|BDRip|WEB-DL)\b/i) : null;
    if (titleQuality) {
        return titleQuality[1].toLowerCase();
    }
    
    // Map numeric quality to standard format
    switch (quality) {
        case 2160: return '4k';
        case 1080: return '1080p';
        case 720: return '720p';
        case 480: return '480p';
        default: return quality ? `${quality}p` : '';
    }
}

// βœ… Formats size into human-readable format (fallback if sizeName not available)
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 info hash from magnet link
function extractInfoHash(magnetLink) {
    if (!magnetLink) return null;
    const match = magnetLink.match(/btih:([a-fA-F0-9]+)/);
    return match ? match[1] : null;
}

// βœ… Removes the year and brackets from queries
function cleanQuery(query) {
    return query
        .replace(/\(\d{4}\)/g, '')     // Removes (YYYY)
        .replace(/\[\d{4}\]/g, '')     // Removes [YYYY]
        .replace(/\{\d{4}\}/g, '')     // Removes {YYYY}
        .replace(/\s+/g, ' ')          // Replace multiple spaces with single space
        .trim();                       // Remove leading/trailing whitespace
}

// βœ… Decodes Unicode escape sequences
function decodeUnicode(str) {
    if (!str) return '';
    return str.replace(/\\u[\dA-F]{4}/gi, (match) => {
        return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
    });
}

// βœ… Enhanced content type detection to handle documentary types
function getContentType(item) {
    if (!item.types || !Array.isArray(item.types)) return 'movie'; // default
    
    // Check for series-like content (including documentaries)
    const seriesTypes = ['serial', 'docuserial', 'tvshow', 'miniseries'];
    const movieTypes = ['movie', 'documovie', 'film'];
    
    // Check if any type indicates series content
    const hasSeriesType = item.types.some(type => 
        seriesTypes.some(seriesType => type.toLowerCase().includes(seriesType.toLowerCase()))
    );
    
    // Check if any type indicates movie content
    const hasMovieType = item.types.some(type => 
        movieTypes.some(movieType => type.toLowerCase().includes(movieType.toLowerCase()))
    );
    
    // Handle mixed types (like docuserial + documovie)
    if (hasSeriesType && hasMovieType) {
        // If it has seasons or episode info, treat as series
        if (item.seasons && item.seasons.length > 0) return 'series';
        // Check title for episode patterns like "01-02 ΠΈΠ· 02"
        if (item.title && /\d+-\d+\s*ΠΈΠ·\s*\d+|\d+\s*of\s*\d+|episode|ep\s*\d+/i.test(item.title)) {
            return 'series';
        }
        // Default to movie for mixed types without clear series indicators
        return 'movie';
    }
    
    if (hasSeriesType) return 'series';
    if (hasMovieType) return 'movie';
    
    // Fallback: check for season info
    if (item.seasons && item.seasons.length > 0) return 'series';
    
    return 'movie'; // default
}

// βœ… Caches results to prevent duplicate requests
const cache = new Map();

// βœ… Fetch data from Jacred API (Rutor) - JSON format
// Updated to match your server.js expected function signature
async function fetchRSSFeeds(searchQuery, type = 'movie') {
    const cleanedQuery = cleanQuery(searchQuery);
    console.log(`πŸ”„ Fetching Jacred feed for: "${cleanedQuery}"`);

    // Convert type format to match Jacred expectations
    const jacredType = type === 'series' ? 'serial' : 'movie';

    if (cache.has(cleanedQuery)) {
        console.log(`⚑ Using cached results for: "${cleanedQuery}"`);
        return cache.get(cleanedQuery);
    }

    // βœ… Updated API URL for Jacred JSON endpoint
    const API_URL = `https://jacred.xyz/api/v1.0/torrents?search=${encodeURIComponent(cleanedQuery)}&apikey=null&exact=true`;

    try {
        await new Promise(resolve => setTimeout(resolve, 1000)); // Rate limiting

        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': 'application/json, text/javascript, */*; q=0.01',
                'Accept-Language': 'en-GB,en;q=0.9',
                'Cache-Control': 'no-cache',
                'Pragma': 'no-cache'
            }
        });

        if (!response.ok) {
            throw new Error(`❌ Failed to fetch Jacred API: ${response.status}`);
        }

        const data = await response.json();
        
        // βœ… Handle both array and object responses
        const results = Array.isArray(data) ? data : (data.results || []);
        
        if (!Array.isArray(results)) {
            console.log('❌ No valid results array found in response');
            return [];
        }

        // βœ… Process each torrent item
        const streams = results.map((item) => {
            if (!item || !item.magnet || !item.title) return null;

            // βœ… Enhanced content type detection
            const contentType = getContentType(item);

            // βœ… Enhanced filtering logic - more flexible matching
            const shouldInclude = (() => {
                if (type === 'movie') {
                    // Include movies and mixed content that defaults to movie
                    return contentType === 'movie' || 
                           (item.types && item.types.includes('documovie'));
                }
                if (type === 'series') {
                    // Include series and mixed content that has series indicators
                    return contentType === 'series' || 
                           (item.types && item.types.includes('docuserial'));
                }
                return true; // If no specific type requested, include everything
            })();

            if (!shouldInclude) return null;

            // βœ… Clean and decode Unicode in title
            const decodedTitle = decodeUnicode(item.title);
            const originalName = decodeUnicode(item.originalname || '');
            
            // βœ… Use the best available title (prefer English if available)
            const displayTitle = originalName || decodedTitle;

            // βœ… Extract quality from both numeric field and title
            const quality = mapQualityToStandard(item.quality, decodedTitle);

            // βœ… Use provided size or calculate from bytes
            const size = item.sizeName || formatSize(item.size || 0);

            // βœ… Clean magnet link (decode HTML entities)
            const magnetLink = item.magnet.replace(/\\u0026/g, '&');

            // βœ… Extract IMDb ID if available (not typically in Rutor)
            const imdbId = null;

            // βœ… Return in format expected by your server.js
            return {
                magnetLink,
                websiteTitle: displayTitle,
                originalTitle: decodedTitle,
                quality,
                size,
                source: item.tracker || 'rutor',
                infoHash: extractInfoHash(magnetLink),
                seeders: item.sid || 0,  // Map from Jacred's 'sid' field
                peers: item.pir || 0,    // Map from Jacred's 'pir' field
                imdbId,
                mainFileSize: item.size || 0,
                pubDate: item.createTime || null,
                categories: item.types || ['movie'],
                originalLink: item.url,
                releaseYear: item.relased || null,
                videoType: item.videotype || 'sdr',
                seasons: item.seasons || [],
                voices: item.voices || [],
                contentType: contentType
            };
        }).filter(Boolean);

        // βœ… Sort by quality, then by size, then by seeders
        streams.sort((a, b) => {
            // Quality priority
            const qualityOrder = { 
                '4k': 6, '2160p': 6, 'uhd': 6,
                '1080p': 5, 'remux': 5, 'bdremux': 5,
                '720p': 4, 'bdrip': 3, 'web-dl': 3, 'webrip': 2,
                '480p': 1
            };
            
            const aQuality = qualityOrder[a.quality.toLowerCase()] || 0;
            const bQuality = qualityOrder[b.quality.toLowerCase()] || 0;
            
            if (bQuality !== aQuality) {
                return bQuality - aQuality;
            }
            
            // Size priority (larger is better for same quality)
            if (b.mainFileSize !== a.mainFileSize) {
                return b.mainFileSize - a.mainFileSize;
            }
            
            // Seeders priority (more seeders is better)
            return b.seeders - a.seeders;
        });

        console.log(`βœ… Processed ${streams.length} valid streams from Jacred (Rutor)`);

        // βœ… Store result in cache
        cache.set(cleanedQuery, streams);

        return streams;
    } catch (error) {
        console.error('❌ Error fetching from Jacred:', error);
        return [];
    }
}

// βœ… Export function for Stremio addon (matches your server.js import)
export { fetchRSSFeeds };