File size: 9,954 Bytes
ea5d04f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import { ERROR } from './const.js';
import { createHash } from 'crypto';

class BaseDebrid {
    #apiKey;
    
    constructor(apiKey, prefix) {
        this.#apiKey = apiKey.replace(`${prefix}=`, '');
    }

    getKey() {
        return this.#apiKey;
    }
}

class DebridLink extends BaseDebrid {
    constructor(apiKey) {
        super(apiKey, 'dl');
    }

    static canHandle(apiKey) {
        return apiKey.startsWith('dl=');
    }

    async #request(method, path, opts = {}) {
        try {
            const query = opts.query || {};
            const queryString = new URLSearchParams(query).toString();
            const url = `https://debrid-link.com/api/v2${path}${queryString ? '?' + queryString : ''}`;

            opts = {
                method,
                headers: {
                    'User-Agent': 'Stremio',
                    'Accept': 'application/json',
                    'Authorization': `Bearer ${this.getKey()}`,
                    ...(method === 'POST' && {
                        'Content-Type': 'application/json'
                    }),
                    ...(opts.headers || {})
                },
                ...opts
            };

            console.log('\nπŸ”· DebridLink Request:', method, path);
            if (opts.body) console.log('Request Body:', opts.body);
            console.log('Request URL:', url);
            console.log('Request Headers:', opts.headers);

            const startTime = Date.now();
            const res = await fetch(url, opts);
            console.log(`Response Time: ${Date.now() - startTime}ms`);
            console.log('Response Status:', res.status);

            const data = await res.json();
            console.log('Response Data:', data);

            if (!data.success) {
                switch (data.error) {
                    case 'badToken':
                        throw new Error(ERROR.INVALID_API_KEY);
                    case 'maxLink':
                    case 'maxLinkHost':
                    case 'maxData':
                    case 'maxDataHost':
                    case 'maxTorrent':
                    case 'torrentTooBig':
                    case 'freeServerOverload':
                        throw new Error(ERROR.NOT_PREMIUM);
                    default:
                        throw new Error(`API Error: ${JSON.stringify(data)}`);
                }
            }

            return data.value;

        } catch (error) {
            console.error('❌ Request failed:', error);
            throw error;
        }
    }

    async checkCacheStatuses(hashes) {
        try {
            console.log(`\nπŸ“‘ DebridLink: Batch checking ${hashes.length} hashes`);
            console.log('Sample hashes being checked:', hashes.slice(0, 3));
            
            const response = await this.#request('GET', '/seedbox/cached', {
                query: { url: hashes.join(',') }
            });
            
            console.log('Raw cache check response:', response);
            
            const results = {};
            for (const hash of hashes) {
                const cacheInfo = response[hash];
                results[hash] = {
                    cached: !!cacheInfo,
                    files: cacheInfo?.files || [],
                    fileCount: cacheInfo?.files?.length || 0,
                    service: 'DebridLink'
                };
            }

            const cachedCount = Object.values(results).filter(r => r.cached).length;
            console.log(`DebridLink found ${cachedCount} cached torrents out of ${hashes.length}`);
            
            return results;
        } catch (error) {
            if (error.message === ERROR.INVALID_API_KEY) {
                console.error('❌ Invalid DebridLink API key');
                return {};
            }
            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);

            const videoFiles = data.files
                .filter(file => /\.(mp4|mkv|avi|mov|webm)$/i.test(file.name))
                .sort((a, b) => b.size - a.size);

            if (!videoFiles.length) {
                console.error('No video files found in torrent');
                throw new Error('No video files found');
            }

            console.log('Selected video file:', videoFiles[0].name);
            return videoFiles[0].downloadUrl;
        } catch (error) {
            console.error('❌ Failed to get stream URL:', error);
            throw error;
        }
    }
}

class Premiumize extends BaseDebrid {
    #apiUrl = 'https://www.premiumize.me/api';

    constructor(apiKey) {
        super(apiKey, 'pr');
    }

    static canHandle(apiKey) {
        return apiKey.startsWith('pr=');
    }

    async #request(method, url, opts = {}) {
        const retries = 3;
        let lastError;

        for (let i = 0; i < retries; i++) {
            try {
                console.log(`\nπŸ”· Premiumize Request (Attempt ${i + 1}/${retries}):`, method, url);
                if (opts.body) console.log('Request Body:', opts.body);

                const controller = new AbortController();
                const timeout = setTimeout(() => controller.abort(), 30000);

                const startTime = Date.now();
                const response = await fetch(url, {
                    ...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);
                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('Sample hashes being checked:', hashes.slice(0, 3));
            
            const params = new URLSearchParams({ apikey: this.getKey() });
            hashes.forEach(hash => params.append('items[]', hash));

            const data = await this.#request('GET', `${this.#apiUrl}/cache/check?${params}`);
            
            if (data.status !== 'success') {
                if (data.message === 'Invalid API key.') {
                    console.error('❌ Invalid Premiumize API key');
                    return {};
                }
                throw new Error('API Error: ' + JSON.stringify(data));
            }

            const results = {};
            hashes.forEach((hash, index) => {
                results[hash] = {
                    cached: data.response[index],
                    files: [],
                    fileCount: 0,
                    service: 'Premiumize'
                };
            });
            
            const cachedCount = Object.values(results).filter(r => r.cached).length;
            console.log(`Premiumize 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('apikey', this.getKey());
            body.append('src', magnetLink);

            const data = await this.#request('POST', `${this.#apiUrl}/transfer/directdl`, {
                body
            });

            if (data.status !== 'success') {
                console.error('API Error:', data);
                throw new Error('Failed to add magnet');
            }

            const videoFiles = data.content
                .filter(file => /\.(mp4|mkv|avi|mov|webm)$/i.test(file.path))
                .sort((a, b) => b.size - a.size);
                
            if (!videoFiles.length) {
                console.error('No video files found in torrent');
                throw new Error('No video files found');
            }

            console.log('Selected video file:', videoFiles[0].path);
            return videoFiles[0].link;
        } 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 {
            console.log('Unknown service key format:', key);
        }
    }
    
    console.log(`Initialized ${services.length} debrid services`);
    return services;
}

export { DebridLink, Premiumize };