-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathm3u_utils.js
More file actions
286 lines (263 loc) · 12.8 KB
/
m3u_utils.js
File metadata and controls
286 lines (263 loc) · 12.8 KB
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
function parseM3U(content, sourceOrigin = null) {
const lines = content.split(/\r\n?|\n/).map(line => line.trim()).filter(Boolean);
const parsedChannels = [];
let currentChannel = null;
const seenGroups = new Set();
const orderedGroups = [];
if (lines.length > 0 && !lines[0].startsWith('#EXTM3U')) {
}
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.startsWith('#EXTINF:')) {
if (currentChannel && !currentChannel.url) {
}
currentChannel = {
name: `Canal ${parsedChannels.length + 1}`,
url: null,
attributes: {},
kodiProps: {},
vlcOptions: {},
extHttp: {},
effectiveEpgId: null,
sourceOrigin: sourceOrigin
};
try {
const extinfMatch = line.match(/^#EXTINF:(-?\d*(?:\.\d+)?)([^,]*),(.*)$/);
if (extinfMatch) {
currentChannel.attributes.duration = extinfMatch[1];
const attrString = extinfMatch[2].trim();
const channelName = extinfMatch[3].trim();
currentChannel.name = channelName || `Canal ${parsedChannels.length + 1}`;
const attributeMatchRegex = /([a-zA-Z0-9_-]+)=("([^"]*)"|'([^']*)'|([^"\s',]+))/g;
let attrMatch;
while ((attrMatch = attributeMatchRegex.exec(attrString)) !== null) {
const attrName = attrMatch[1].toLowerCase();
const attrValue = attrMatch[3] || attrMatch[4] || attrMatch[5] || '';
currentChannel.attributes[attrName] = attrValue.trim();
}
currentChannel['tvg-id'] = currentChannel.attributes['tvg-id'] || '';
currentChannel['tvg-name'] = currentChannel.attributes['tvg-name'] || '';
currentChannel['tvg-logo'] = currentChannel.attributes['tvg-logo'] || '';
currentChannel['group-title'] = currentChannel.attributes['group-title'] || '';
currentChannel.attributes['ch-number'] = currentChannel.attributes['ch-number'] || currentChannel.attributes['tvg-chno'] || '';
if (currentChannel.attributes['source-origin']) {
currentChannel.sourceOrigin = currentChannel.attributes['source-origin'];
}
const groupTitle = currentChannel['group-title'];
if (groupTitle && groupTitle.trim() !== '' && !seenGroups.has(groupTitle)) {
seenGroups.add(groupTitle); orderedGroups.push(groupTitle);
}
} else {
const commaIndex = line.indexOf(',');
if (commaIndex !== -1) {
currentChannel.name = line.substring(commaIndex + 1).trim() || `Canal ${parsedChannels.length + 1}`;
currentChannel.attributes.duration = line.substring("#EXTINF:".length, commaIndex).trim();
} else { currentChannel = null; }
}
} catch (e) { console.warn("Error parsing #EXTINF line:", line, e); currentChannel = null; }
} else if (currentChannel && line.startsWith('#KODIPROP:')) {
const propMatch = line.match(/^#KODIPROP:([^=]+)=(.*)$/);
if (propMatch && propMatch[1] && typeof propMatch[2] === 'string') {
currentChannel.kodiProps[propMatch[1].trim()] = propMatch[2].trim();
}
} else if (currentChannel && line.startsWith('#EXTVLCOPT:')) {
const propMatch = line.match(/^#EXTVLCOPT:([^=]+)=(.*)$/);
if (propMatch && propMatch[1] && typeof propMatch[2] === 'string') {
const key = propMatch[1].trim();
let value = propMatch[2].trim();
if (key === 'http-user-agent' && value.includes('&Referer=')) {
const parts = value.split('&Referer=');
currentChannel.vlcOptions['http-user-agent'] = parts[0];
if (parts.length > 1 && parts[1]) {
currentChannel.vlcOptions['http-referrer'] = parts[1];
}
} else if (key === 'http-user-agent' && value.includes('&referer=')) {
const parts = value.split('&referer=');
currentChannel.vlcOptions['http-user-agent'] = parts[0];
if (parts.length > 1 && parts[1]) {
currentChannel.vlcOptions['http-referrer'] = parts[1];
}
}
else {
currentChannel.vlcOptions[key] = value;
}
}
} else if (currentChannel && line.startsWith('#EXTHTTP:')) {
try {
const httpJson = line.substring('#EXTHTTP:'.length).trim();
if (httpJson) { currentChannel.extHttp = JSON.parse(httpJson); }
} catch (e) { console.warn("Error parsing #EXTHTTP JSON:", line, e); }
} else if (currentChannel && line.startsWith('#EXTGRP:')) {
const groupName = line.substring('#EXTGRP:'.length).trim();
if (!currentChannel['group-title'] && groupName) {
currentChannel['group-title'] = groupName;
if (!seenGroups.has(groupName)) { seenGroups.add(groupName); orderedGroups.push(groupName); }
} else if (groupName && groupName.trim() !== '' && !seenGroups.has(groupName)) {
seenGroups.add(groupName); orderedGroups.push(groupName);
}
} else if (!line.startsWith('#') && currentChannel && !currentChannel.url) {
const url = line.trim();
if (url) {
currentChannel.url = url;
if (!currentChannel.attributes['source-origin']) {
if (url.includes('atres-live.atresmedia.com')) {
currentChannel.sourceOrigin = 'Atresplayer';
} else if (url.includes('orangetv.orange.es')) {
currentChannel.sourceOrigin = 'OrangeTV';
} else if (url.toLowerCase().includes('dazn')) {
currentChannel.sourceOrigin = 'DAZN';
} else if (url.toLowerCase().includes('telefonica.com') || url.toLowerCase().includes('movistarplus.es')) {
currentChannel.sourceOrigin = 'Movistar+';
}
}
if (currentChannel.attributes['source-origin']) {
currentChannel.sourceOrigin = currentChannel.attributes['source-origin'];
}
parsedChannels.push(currentChannel);
currentChannel = null;
} else {
currentChannel = null;
}
} else if (!line.startsWith('#') && !currentChannel) {
}
}
if (currentChannel && !currentChannel.url) {
}
const finalOrderedGroups = Array.from(new Set(orderedGroups));
return { channels: parsedChannels, groupOrder: finalOrderedGroups };
}
function normalizeStringForComparison(str) {
if (typeof str !== 'string') return '';
return str.toLowerCase()
.normalize("NFD").replace(/[\u0300-\u036f]/g, "")
.replace(/[hd|sd|fhd|uhd|4k|8k|(\(\d+p\))|[,.:;\-_\s()\[\]&+'!¡¿?]/g, '')
.replace(/\s+/g, '');
}
function getStringSimilarity(str1, str2) {
const s1 = normalizeStringForComparison(str1);
const s2 = normalizeStringForComparison(str2);
if (s1 === s2) return 1.0;
if (s1.length < 2 || s2.length < 2) return 0.0;
const profile1 = {};
for (let i = 0; i < s1.length - 1; i++) {
const bigram = s1.substring(i, i + 2);
profile1[bigram] = (profile1[bigram] || 0) + 1;
}
const profile2 = {};
for (let i = 0; i < s2.length - 1; i++) {
const bigram = s2.substring(i, i + 2);
profile2[bigram] = (profile2[bigram] || 0) + 1;
}
const union = new Set([...Object.keys(profile1), ...Object.keys(profile2)]);
let intersectionSize = 0;
for (const bigram of union) {
if (profile1[bigram] && profile2[bigram]) {
intersectionSize += Math.min(profile1[bigram], profile2[bigram]);
}
}
return (2.0 * intersectionSize) / (s1.length - 1 + s2.length - 1);
}
function base64ToHex(base64) {
try {
const b64Str = String(base64 || '');
const binary = atob(b64Str.replace(/-/g, '+').replace(/_/g, '/'));
let hex = '';
for (let i = 0; i < binary.length; i++) {
const byte = binary.charCodeAt(i).toString(16).padStart(2, '0');
hex += byte;
}
return hex.toLowerCase();
} catch (e) {
return null;
}
}
function parseClearKey(keyString) {
if (!keyString || typeof keyString !== 'string') {
return null;
}
keyString = keyString.trim();
const clearKeys = {};
try {
if (keyString.startsWith('{') && keyString.endsWith('}')) {
try {
const parsed = JSON.parse(keyString);
if (parsed.keys && Array.isArray(parsed.keys)) {
for (const keyObj of parsed.keys) {
if (keyObj.kty !== 'oct') { continue; }
if (!keyObj.k || !keyObj.kid) { continue; }
const kidHex = base64ToHex(keyObj.kid);
const keyHex = base64ToHex(keyObj.k);
if (kidHex && keyHex && /^[0-9a-f]{32}$/.test(kidHex) && /^[0-9a-f]{32}$/.test(keyHex)) {
clearKeys[kidHex] = keyHex;
}
}
} else {
for (const kid_orig in parsed) {
if (Object.prototype.hasOwnProperty.call(parsed, kid_orig)) {
const key_orig = parsed[kid_orig];
if (typeof kid_orig !== 'string' || typeof key_orig !== 'string') {
continue;
}
let kidHexStr, keyHexStr;
if (!/^[0-9a-fA-F]{32}$/.test(kid_orig)) {
const converted = base64ToHex(kid_orig);
kidHexStr = converted ? converted : '';
} else {
kidHexStr = kid_orig.toLowerCase();
}
if (!/^[0-9a-fA-F]{32}$/.test(key_orig)) {
const converted = base64ToHex(key_orig);
keyHexStr = converted ? converted : '';
} else {
keyHexStr = key_orig.toLowerCase();
}
if (/^[0-9a-f]{32}$/.test(kidHexStr) && /^[0-9a-f]{32}$/.test(keyHexStr)) {
clearKeys[kidHexStr] = keyHexStr;
}
}
}
}
} catch (jsonParseError) {
const compactObjectMatch = keyString.match(/^\{([0-9a-fA-F]{32}):([0-9a-fA-F]{32})\}$/);
if (compactObjectMatch) {
clearKeys[compactObjectMatch[1].toLowerCase()] = compactObjectMatch[2].toLowerCase();
}
}
}
if (Object.keys(clearKeys).length === 0) {
const simpleHexMatch = keyString.match(/^([0-9a-fA-F]{32}):([0-9a-fA-F]{32})$/);
if (simpleHexMatch) {
clearKeys[simpleHexMatch[1].toLowerCase()] = simpleHexMatch[2].toLowerCase();
return clearKeys;
}
const simpleBase64Match = keyString.match(/^([A-Za-z0-9+/_-]+={0,2}):([A-Za-z0-9+/_-]+={0,2})$/);
if (simpleBase64Match) {
const kidHex = base64ToHex(simpleBase64Match[1]);
const keyHex = base64ToHex(simpleBase64Match[2]);
if (kidHex && keyHex && /^[0-9a-f]{32}$/.test(kidHex) && /^[0-9a-f]{32}$/.test(keyHex)) {
clearKeys[kidHex] = keyHex;
return clearKeys;
}
}
}
if (Object.keys(clearKeys).length === 0) {
return null;
}
return clearKeys;
} catch (e) {
console.error("Error parsing clearkey string:", e, keyString);
return null;
}
}
function safeParseInt(value, defaultValue = 0) {
const parsed = parseInt(value, 10);
return isNaN(parsed) ? defaultValue : parsed;
}
function detectMimeType(url) {
if (typeof url !== 'string') return '';
const u = url.toLowerCase();
const urlWithoutQuery = u.split('?')[0];
if (urlWithoutQuery.endsWith('.m3u8')) return 'application/x-mpegURL';
if (urlWithoutQuery.endsWith('.mpd')) return 'application/dash+xml';
return '';
}