File size: 10,968 Bytes
ea5d04f 8740315 ea5d04f 8740315 ea5d04f 8740315 ea5d04f 8740315 ea5d04f 8740315 ea5d04f 8740315 ea5d04f 8740315 ea5d04f 8740315 ea5d04f 8740315 ea5d04f 8740315 ea5d04f 8740315 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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 | import { ERROR } from './const.js';
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';
#batchSize = 99;
constructor(apiKey) {
super(apiKey, 'pr');
}
static canHandle(apiKey) {
return apiKey.startsWith('pr=');
}
async makeRequest(method, path, opts = {}) {
const retries = 3;
let lastError;
for (let i = 0; i < retries; i++) {
try {
const url = `${this.#apiUrl}${path}`;
console.log(`\n🔷 Premiumize Request (Attempt ${i + 1}/${retries}):`, method, path);
if (opts.body) console.log('Request Body:', opts.body);
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 30000);
// Add API key to FormData if it's a POST request
if (method === 'POST' && opts.body instanceof FormData) {
opts.body.append('apikey', this.getKey());
}
// For GET requests, add API key to URL
const finalUrl = method === 'GET'
? `${url}${url.includes('?') ? '&' : '?'}apikey=${this.getKey()}`
: url;
const startTime = Date.now();
const response = await fetch(finalUrl, {
...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);
if (data.status === 'error') {
if (data.message === 'Invalid API key.') {
throw new Error(ERROR.INVALID_API_KEY);
}
throw new Error(`API Error: ${data.message}`);
}
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('Processing in batches of', this.#batchSize);
const results = {};
const batches = [];
// Split hashes into batches
for (let i = 0; i < hashes.length; i += this.#batchSize) {
batches.push(hashes.slice(i, i + this.#batchSize));
}
console.log(`Split into ${batches.length} batches`);
// Process each batch
for (let i = 0; i < batches.length; i++) {
const batch = batches[i];
console.log(`\nProcessing batch ${i + 1}/${batches.length} (${batch.length} hashes)`);
const params = new URLSearchParams();
batch.forEach(hash => params.append('items[]', hash));
const data = await this.makeRequest('GET', `/cache/check?${params}`);
// Map the responses to the corresponding hashes
batch.forEach((hash, index) => {
results[hash] = {
cached: data.response[index],
files: [],
fileCount: 0,
service: 'Premiumize'
};
});
// Add a small delay between batches to avoid rate limiting
if (i < batches.length - 1) {
await new Promise(resolve => setTimeout(resolve, 500));
}
}
const cachedCount = Object.values(results).filter(r => r.cached).length;
console.log(`\nPremiumize 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('src', magnetLink);
const data = await this.makeRequest('POST', '/transfer/directdl', {
body
});
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 };
|