File size: 5,297 Bytes
03ee7cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// premiumize.js
import { ERROR } from './const.js';
import { BaseDebrid, findBestFile } from './base-debrid.js';

export 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);

                if (method === 'POST' && opts.body instanceof FormData) {
                    opts.body.append('apikey', this.getKey());
                }

                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 = [];

            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`);

            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}`);

                batch.forEach((hash, index) => {
                    results[hash] = {
                        cached: data.response[index],
                        files: [],
                        fileCount: 0,
                        service: 'Premiumize' // Mark as Premiumize service
                    };
                });

                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 });

            // Extract potential media info from magnet title
            const mediaInfo = this.extractMediaInfo(magnetLink);
            console.log('Extracted media info:', mediaInfo);
            
            const bestFile = findBestFile(
                data.content,
                mediaInfo.type,
                mediaInfo
            );

            if (!bestFile) {
                console.error('No suitable video file found');
                throw new Error('No suitable video file found');
            }

            console.log('Selected file for streaming:', bestFile.path);
            return bestFile.stream_link || bestFile.link;
        } catch (error) {
            console.error('❌ Failed to get stream URL:', error);
            throw error;
        }
    }
}