Spaces:
Riviss
/
Paused

File size: 8,404 Bytes
ed280e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a01a404
 
 
 
ed280e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a01a404
 
d6fc3bf
a01a404
 
d6fc3bf
a01a404
d6fc3bf
a01a404
 
ed280e7
a01a404
ed280e7
 
 
 
a01a404
ed280e7
 
 
 
 
 
 
a01a404
ed280e7
 
 
 
 
 
 
 
 
 
a01a404
 
 
 
 
 
ed280e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a01a404
 
 
ed280e7
 
 
 
 
 
 
 
 
a01a404
 
 
ed280e7
 
 
a01a404
 
 
 
 
 
ed280e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const axios = require('axios');

function createXtreamModule(xtreamBaseUrl, username, password) {
    const xtreamApiUrl = `${xtreamBaseUrl}/player_api.php`;

    async function getDetailsFromCinemeta(ttnumber, type = 'movie') {
        const url = `https://v3-cinemeta.strem.io/meta/${type}/${ttnumber}.json`;
        try {
            const response = await axios.get(url);
            const { name: title, season, episode } = response.data.meta;
            return { title, season, episode };
        } catch (error) {
            console.error('Error fetching data from Cinemeta:', error);
            throw error;
        }
    }

    async function getVodStreams() {
        const params = { username, password, action: 'get_vod_streams' };
        try {
            const response = await axios.get(xtreamApiUrl, { params });
            return response.data;
        } catch (error) {
            console.error('Error fetching VOD streams from Xtream Codes:', error);
            throw error;
        }
    }

    async function getSeries() {
        const params = { username, password, action: 'get_series' };
        try {
            const response = await axios.get(xtreamApiUrl, { params });
            return response.data;
        } catch (error) {
            console.error('Error fetching series from Xtream Codes:', error);
            throw error;
        }
    }

    async function getSeriesInfo(seriesId) {
        const params = { username, password, action: 'get_series_info', series_id: seriesId };
        try {
            const response = await axios.get(xtreamApiUrl, { params });
            return response.data;
        } catch (error) {
            console.error('Error fetching series info from Xtream Codes:', error);
            throw error;
        }
    }

    function normalizeTitle(title) {
        // Remove the year and any surrounding parentheses or brackets
        let normalized = title.replace(/\s*\([^)]*\)|\s*\[[^\]]*\]|\s*\d{4}$/g, '');
        // Convert to lowercase and remove all non-alphanumeric characters except spaces
        normalized = normalized.toLowerCase().replace(/[^a-z0-9\s]/g, '').trim();
        // Replace multiple spaces with a single space
        normalized = normalized.replace(/\s+/g, ' ');
        return normalized;
    }

    function findBestMatchingContent(contentList, title) {
        const normalizedTitle = normalizeTitle(title);
        console.log(`Searching for best match for normalized title: ${normalizedTitle}`);
        
        let bestMatch = null;
        let highestSimilarity = 0;

        contentList.forEach(item => {
            const itemNormalizedTitle = normalizeTitle(item.name);
            const similarity = calculateSimilarity(normalizedTitle, itemNormalizedTitle);
            console.log(`Comparing with: ${itemNormalizedTitle}, Similarity: ${similarity}`);
            
            if (similarity > highestSimilarity) {
                highestSimilarity = similarity;
                bestMatch = item;
            }
        });

        // Adjust threshold based on title length
        const minLength = Math.min(normalizedTitle.length, bestMatch ? normalizeTitle(bestMatch.name).length : 0);
        let threshold = 0.6; // Default threshold

        if (minLength <= 4) {
            threshold = 0.2; // Lower threshold for short titles
        } else if (minLength <= 6) {
            threshold = 0.3;
        }

        console.log(`Best match found: ${bestMatch ? bestMatch.name : 'None'} with similarity: ${highestSimilarity}`);
        return highestSimilarity >= threshold ? bestMatch : null;
    }

    function calculateSimilarity(str1, str2) {
        const len = Math.max(str1.length, str2.length);
        if (len === 0) return 1; // Both strings are empty
        const editDistance = levenshteinDistance(str1, str2);
        return 1 - editDistance / len;
    }

    function levenshteinDistance(str1, str2) {
        const m = str1.length;
        const n = str2.length;
        const dp = Array.from({ length: m + 1 }, () => Array(n + 1));

        for (let i = 0; i <= m; i++) {
            dp[i][0] = i;
        }
        for (let j = 0; j <= n; j++) {
            dp[0][j] = j;
        }

        for (let i = 1; i <= m; i++) {
            for (let j = 1; j <= n; j++) {
                const cost = str1[i - 1] === str2[j - 1] ? 0 : 1;
                dp[i][j] = Math.min(
                    dp[i - 1][j] + 1,      // Deletion
                    dp[i][j - 1] + 1,      // Insertion
                    dp[i - 1][j - 1] + cost // Substitution
                );
            }
        }

        return dp[m][n];
    }

    function buildStreamUrl(content) {
        let url;
        if (content.stream_type) {
            // For movies
            url = `${xtreamBaseUrl}/${content.stream_type}/${username}/${password}/${content.stream_id}.${content.container_extension}`;
        } else if (content.id) {
            // For series episodes
            url = `${xtreamBaseUrl}/series/${username}/${password}/${content.id}.${content.container_extension}`;
        }
        console.log('Constructed stream URL:', url);
        return url;
    }

    return async function(input) {
        try {
            const [ttNumber, season, episode] = input.split(':');
            
            const type = ttNumber.startsWith('tt') ? (season && episode ? 'series' : 'movie') : 'series';
            
            const { title } = await getDetailsFromCinemeta(ttNumber, type);
            console.log(`Title from Cinemeta: ${title} (${type})`);

            let contentList, matchingContent, contentInfo, specificEpisode;
            if (type === 'movie') {
                contentList = await getVodStreams();

                matchingContent = findBestMatchingContent(contentList, title);

                if (matchingContent) {
                    const contentUrl = buildStreamUrl(matchingContent);
                    return { title: matchingContent.name, contentUrl, type };
                } else {
                    console.log(`No matching content found for movie: ${title}`);
                    return null;
                }
            } else {
                contentList = await getSeries();

                matchingContent = findBestMatchingContent(contentList, title);

                if (matchingContent) {
                    contentInfo = await getSeriesInfo(matchingContent.series_id);
                    if (season && episode) {
                        const episodes = contentInfo.episodes[season] || [];
                        specificEpisode = episodes.find(ep => ep.episode_num == episode);
                        if (!specificEpisode) {
                            // Sometimes episode numbers are strings, try matching as strings
                            specificEpisode = episodes.find(ep => ep.episode_num == String(episode));
                        }
                        if (specificEpisode) {
                            const episodeUrl = buildStreamUrl(specificEpisode);
                            return {
                                title: matchingContent.name,
                                type,
                                seriesId: matchingContent.series_id,
                                season,
                                episode,
                                episodeTitle: specificEpisode.title,
                                contentUrl: episodeUrl
                            };
                        } else {
                            console.log(`Episode not found: ${title} S${season}E${episode}`);
                            return null;
                        }
                    } else {
                        return {
                            title: matchingContent.name,
                            type,
                            seriesId: matchingContent.series_id,
                            seasons: contentInfo.seasons,
                            episodes: contentInfo.episodes
                        };
                    }
                } else {
                    console.log(`No matching content found for series: ${title}`);
                    return null;
                }
            }
        } catch (error) {
            console.error('Error:', error.message);
            throw error;
        }
    };
}

module.exports = { createXtreamModule };