-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
376 lines (346 loc) · 10.7 KB
/
main.js
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
let LOGGING = true;
const FORMAT_MAP = {
251: {
itag: 251,
type: "webm",
vCodec: "NONE",
aCodec: "OPUS",
bitrate: 160,
adaptive: true,
},
250: {
itag: 250,
type: "webm",
vCodec: "NONE",
aCodec: "OPUS",
bitrate: 64,
adaptive: true,
},
249: {
itag: 249,
type: "webm",
vCodec: "NONE",
aCodec: "OPUS",
bitrate: 48,
adaptive: true,
},
};
const FactoryState = {
SUCCESS: "SUCCESS",
ERROR: "ERROR",
LOADING: "LOADING",
INIT: "INIT",
};
const jsExecuting = {
wait: (timeout) => new Promise((resolve) => setTimeout(resolve, timeout)),
signal: () => {}, // This will be a function that signals when execution is complete
};
let decipheredSignature = null;
let decipherJsFileName = null;
let decipherFunctions = null;
let decipherFunctionName = null;
const USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36";
const patPlayerResponse = /var ytInitialPlayerResponse\s*=\s*(\{.+?\})\s*;/;
const patSigEncUrl = /url=(.+?)(\u0026|$)/;
const patSignature = /s=(.+?)(\u0026|$)/;
const patVariableFunction =
/([{; =])([a-zA-Z$][a-zA-Z0-9$]{0,2})\.([a-zA-Z$][a-zA-Z0-9$]{0,2})\(/g;
const patFunction = /([{; =])([a-zA-Z\$_][a-zA-Z0-9$]{0,2})\(/g;
const patDecryptionJsFile = /\\\/s\\\\\/player\\\\\/([^\"]+?)\.js/g;
const patDecryptionJsFileWithoutSlash = /\/s\/player\/([^\"]+?)\.js/g;
const patSignatureDecFunction =
/(?:\b|[^a-zA-Z0-9$])([a-zA-Z0-9$]{1,4})\s*=\s*function\(\s*a\s*\)\s*\{\s*a\s*=\s*a\.split\(\s*\"\"\s*\)/g;
async function getStreamUrls(videoID) {
const encSignatures = new Map();
let file = {}; // Initialize file as an empty object
let pageHtml;
let urlConnection = null;
let reader = null;
const getUrl = `https://youtube.com/watch?v=${videoID}`;
try {
urlConnection = await fetch(getUrl, {
headers: {
"User-Agent": USER_AGENT,
},
});
pageHtml = await urlConnection.text();
} finally {
if (reader) reader.close();
}
const mat = patPlayerResponse.exec(pageHtml);
if (mat) {
const ytPlayerResponse = JSON.parse(mat[1]);
const streamingData = ytPlayerResponse.streamingData;
const adaptiveFormats = streamingData.adaptiveFormats;
parseFormats(
adaptiveFormats,
file,
encSignatures,
patSigEncUrl,
patSignature
);
} else {
if(LOGGING) console.log("ytPlayerResponse was not found");
}
if (encSignatures.size > 0) {
let curJsFileName;
let mat = patDecryptionJsFile.exec(pageHtml);
if (!mat) mat = patDecryptionJsFileWithoutSlash.exec(pageHtml);
if (mat) {
curJsFileName = mat[0].replace(/\\\//g, "/");
if (!decipherJsFileName || decipherJsFileName !== curJsFileName) {
decipherFunctions = null;
decipherFunctionName = null;
}
decipherJsFileName = curJsFileName;
}
if(LOGGING) console.log(`Decipher signatures: ${encSignatures.size}, video: ${file}`);
if (await decipherSignature(encSignatures)) {
if(LOGGING) console.log("Deciphered signature correctly");
}
else {
if(LOGGING) console.error("Could not decipher signature");
}
const signature = decipheredSignature;
if (!signature) {
if(LOGGING) console.error("Could not decipher signature");
return null;
} else {
const sigs = signature.split("\n").filter((s) => s.trim() !== "");
let i = 0;
for (let key of encSignatures.keys()) {
let url = file.url;
console.log(`url: ${url}`);
url += `&sig=${sigs[i]}`;
file.type = FORMAT_MAP[key];
file.url = url;
console.log(`file: ${sigs[i]}`);
i++;
c
}
}
}
if (file == null) {
if(LOGGING) console.log(pageHtml);
return null;
}
return file;
}
function parseFormats(
formats,
file,
encSignatures,
patSigEncUrl,
patSignature
) {
if (formats) {
for (let i = 0; i < formats.length; i++) {
const format = formats[formats.length - i - 1];
const type = format.type;
if (type === "FORMAT_STREAM_TYPE_OTF") continue;
const itag = format.itag;
if (FORMAT_MAP[itag]) {
if (format.url) {
let url = format.url.replace("\\u0026", "&");
file.type = FORMAT_MAP[itag];
file.url = url;
} else if (format.signatureCipher) {
const mat = patSigEncUrl.exec(format.signatureCipher);
const matSig = patSignature.exec(format.signatureCipher);
if (mat && matSig) {
const url = decodeURIComponent(mat[1]);
const signature = decodeURIComponent(matSig[1]);
console.log(`sign: ${signature}`);
file.type = FORMAT_MAP[itag];
file.url = url;
if(LOGGING) console.log(`file: ${file.url}`);
encSignatures.set(itag, signature);
}
}
break;
}
}
}
}
async function testHttp403Code(url) {
let urlConnection = null;
try {
const response = await fetch(url, {
method: "HEAD", // Send a HEAD request to check the status code without downloading the content
headers: {
"User-Agent": USER_AGENT,
},
});
if (response.status === 403) {
return true;
}
} catch (error) {
if(LOGGING) console.error("An error occurred:", error);
} finally {
if (urlConnection) {
urlConnection.disconnect();
}
}
return false;
}
async function decipherViaWebView(encSignatures) {
let stb = `${decipherFunctions} function decipher(){return `;
const keys = Array.from(encSignatures.keys());
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (i < keys.length - 1) {
stb += `${decipherFunctionName}('` + encSignatures.get(key) + "')+'\\n'+";
} else {
stb += `${decipherFunctionName}('` + encSignatures.get(key) + "')";
}
}
stb += "};decipher();";
// Execute the JavaScript code using eval()
try {
const result = eval(stb);
decipheredSignature = result;
jsExecuting.signal();
} catch (error) {
if(LOGGING) console.error(error);
jsExecuting.signal();
}
}
async function decipherSignature(encSignatures) {
// Assume the functions don't change that much
if (!decipherFunctionName || !decipherFunctions) {
const decipherFunctUrl = `https://youtube.com${decipherJsFileName}`;
try {
const response = await fetch(decipherFunctUrl, {
headers: {
"User-Agent": USER_AGENT,
},
});
const javascriptFile = await response.text();
if(LOGGING) console.log(`Decipher FunctURL: ${decipherFunctUrl}`);
let mat = patSignatureDecFunction.exec(javascriptFile);
if (mat) {
decipherFunctionName = mat[1];
if(LOGGING) console.log(`Decipher Functname: ${decipherFunctionName}`);
const patMainVariable = new RegExp(
`(var |\\s|,|;)${decipherFunctionName.replace(
"$",
"\\$"
)}(=function\\((.{1,3})\\)\\{)`
);
mat = patMainVariable.exec(javascriptFile);
let mainDecipherFunct;
if (mat) {
mainDecipherFunct = `var ${decipherFunctionName}${mat[2]}`;
} else {
const patMainFunction = new RegExp(
`function ${decipherFunctionName.replace(
"$",
"\\$"
)}(\\((.{1,3})\\)\\{)`
);
mat = patMainFunction.exec(javascriptFile);
if (!mat) return false;
mainDecipherFunct = `function ${decipherFunctionName}${mat[2]}`;
}
let startIndex = mat.index + mat[0].length;
let braces = 1;
let i = startIndex;
while (i < javascriptFile.length) {
if (braces === 0 && startIndex + 5 < i) {
mainDecipherFunct += javascriptFile.substring(startIndex, i) + ";";
break;
}
if (javascriptFile[i] === "{") braces++;
else if (javascriptFile[i] === "}") braces--;
i++;
}
decipherFunctions = mainDecipherFunct;
if(LOGGING) console.log(`Main Decipher Function: ${mainDecipherFunct}`);
// Search the main function for extra functions and variables needed for deciphering
// Search for variables
var max = 0;
while ((mat = patVariableFunction.exec(mainDecipherFunct))) {
const variableDef = `var ${mat[2]}={`;
if (decipherFunctions.includes(variableDef)) {
max++;
if (max > 10) break;
if(LOGGING) console.log(`variables: ${variableDef}`);
continue;
}
let startIndex =
javascriptFile.indexOf(variableDef) + variableDef.length;
let bracesVariable = 1;
let i1 = startIndex;
while (i1 < javascriptFile.length) {
if (bracesVariable === 0) {
decipherFunctions += `${variableDef}${javascriptFile.substring(
startIndex,
i1
)};`;
break;
}
if (javascriptFile[i1] === "{") bracesVariable++;
else if (javascriptFile[i1] === "}") bracesVariable--;
i1++;
}
}
// Search for functions
while ((mat = patFunction.exec(mainDecipherFunct))) {
const functionDef = `function ${mat[2]}(`;
if (decipherFunctions.includes(functionDef)) {
continue;
}
startIndex =
javascriptFile.indexOf(functionDef, mat.index) + functionDef.length;
let bracesFunction = 0;
let i2 = startIndex;
while (i2 < javascriptFile.length) {
if (bracesFunction === 0 && startIndex + 5 < i2) {
decipherFunctions += `${functionDef}${javascriptFile.substring(
startIndex,
i2
)};`;
break;
}
if (javascriptFile[i2] === "{") bracesFunction++;
else if (javascriptFile[i2] === "}") bracesFunction--;
i2++;
}
}
if(LOGGING) console.log(`Decipher Functions: ${decipherFunctions}`);
decipherViaWebView(encSignatures);
} else {
return false;
}
} catch (error) {
if(LOGGING) console.error("An error occurred:", error);
return false;
}
} else {
decipherViaWebView(encSignatures);
}
return true;
}
const videoID = "tZLDEUFtnX0";
(async () => {
let ok = false;
retry = 1;
i = 0;
try {
while (!ok && i < retry) {
const file = await getStreamUrls(videoID);
if (file) {
if (testHttp403Code(file.url)) {
console.log("file:", file);
ok = true;
}
} else {
console.log("No YouTube files found.");
}
i ++;
}
} catch (error) {
console.error("An error occurred:", error);
}
})();