Newer
Older
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
//#region Basic Extractors
function extractText_String(item) {
if(typeof item === 'string')
return item;
if(item?.simpleText)
return item.simpleText;
if(item?.runs)
return extractRuns_String(item.runs);
if(item)
log("Unknown string object: " + JSON.stringify(item, null, " "));
return null;
}
function extractRuns_String(runs) {
if(!runs)
return null;
let str = "";
for(let runi = 0; runi < runs.length; runi++) {
const run = runs[runi];
if(run.text)
str += run.text;
else if(run.emoji?.image?.accessibility?.accessibilityData?.label)
str += "__" + run.emoji?.image?.accessibility?.accessibilityData?.label + "__"
}
return str;
}
function extractRuns_Html(runs) {
if(!runs)
return null;
let str = "";
for(let runi = 0; runi < runs.length; runi++) {
const run = runs[runi];
if(run.text)
str += run.text;
}
return str;
}
function extractRuns_Url(runs) {
for(let runi = 0; runi < runs.length; runi++) {
const run = runs[runi];
if(run.navigationEndpoint && run.navigationEndpoint.browseEndpoint && run.navigationEndpoint.browseEndpoint.canonicalBaseUrl)
return URL_BASE + run.navigationEndpoint.browseEndpoint.canonicalBaseUrl;
}
}
function extractNavigationEndpoint_Url(navEndpoint, baseUrl) {
if(!baseUrl)
baseUrl = URL_BASE;
if(!navEndpoint)
return null;
if(navEndpoint?.browseEndpoint?.browseId && navEndpoint?.browseEndpoint?.canonicalBaseUrl && navEndpoint.browseEndpoint.canonicalBaseUrl.startsWith("/@"))
return baseUrl + "/channel/" + navEndpoint?.browseEndpoint?.browseId;
if(navEndpoint?.browseEndpoint?.canonicalBaseUrl)
return baseUrl + navEndpoint?.browseEndpoint?.canonicalBaseUrl;
if(navEndpoint.commandMetadata?.webCommandMetadata?.url)
return baseUrl + navEndpoint.commandMetadata?.webCommandMetadata?.url;
return null;
}
function extractAgoTextRuns_Timestamp(runs) {
const runStr = (typeof runs === "string") ? runs : extractRuns_String(runs);
return extractAgoText_Timestamp(runStr);
}
function extractAgoText_Timestamp(str) {
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
const match = str.match(REGEX_HUMAN_AGO);
if(!match)
return 0;
const value = parseInt(match[1]);
const now = parseInt(new Date().getTime() / 1000);
switch(match[2]) {
case "second":
case "seconds":
return now - value;
case "minute":
case "minutes":
return now - value * 60;
case "hour":
case "hours":
return now - value * 60 * 60;
case "day":
case "days":
return now - value * 60 * 60 * 24;
case "week":
case "weeks":
return now - value * 60 * 60 * 24 * 7;
case "month":
case "months":
return now - value * 60 * 60 * 24 * 30; //For now it will suffice
case "year":
case "years":
return now - value * 60 * 60 * 24 * 365;
default:
if(bridge.devSubmit) bridge.devSubmit("extractAgoText_Timestamp - Unknown time type: " + match[2], match[2]);
throw new ScriptException("Unknown time type: " + match[2]);
}
}
function extractRuns_ViewerCount(runs) {
if(runs && runs.length > 0) {
const item = runs[0].text.replaceAll(".", "").replaceAll(",", "");
if(isNaN(item))
return -1;
return parseInt(item);
}
return -1;
}
function extractHumanTime_Seconds(str) {
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
if(str.indexOf(" ") >= 0)
str = str.split(" ")[0];
const parts = str.split(":");
let scale = 1;
let seconds = 0;
for(let i = parts.length-1; i >= 0; i--) {
if(isNaN(parts[i]))
return seconds;
seconds += parseInt(parts[i]) * scale;
scale *= 60;
}
return parseInt(seconds);
}
function extractFirstNumber_Integer(str) {
if(str) {
const parts = str.split(' ');
if(parts && parts.length > 0) {
const num = parts[0].replaceAll(".","").replaceAll(",","");
if(isNaN(num))
return -1;
return parseInt(num);
}
}
return -1;
}
function extractHumanNumber_Integer(str) {
if(!str)
return -1;
const match = str.match(REGEX_HUMAN_NUMBER);
if(!match)
return extractFirstNumber_Integer(str);
const value = parseFloat(match[1]);
switch(match[2]) {
case "T":
return parseInt(1000000000000 * value);
case "B":
return parseInt(1000000000 * value);
case "M":
return parseInt(1000000 * value);
case "K":
return parseInt(1000 * value);
default:
return parseInt(value);
}
}
function extractDate_Timestamp(dateStr) {
if(!dateStr)
return -1;
if(dateStr.indexOf("ago") > 0)
return extractAgoText_Timestamp(dateStr);
let matchDate = dateStr.match(REGEX_DATE_HUMAN);
if(matchDate) return extractHumanDate_Timestamp(matchDate.slice(1));
matchDate = dateStr.match(REGEX_DATE_EU);
if(matchDate) return new Date(matchDate[0]).getTime() / 1000;
matchDate = dateStr.match(REGEX_DATE_EU);
if(matchDate) return new Date(matchDate[0]).getTime() / 1000;
return -1;
}
function extractHumanDate_Timestamp(dateParts) {
if(dateParts.length != 3)
return -1;
let day = -1;
let month = -1;
let year = -1;
for(let i = 0; i < dateParts.length; i++) {
const part = dateParts[i];
if(part.length > 2) {
const newMonth = monthNameToNumber(part);
if(newMonth > 0)
month = newMonth;
}
if(part.length == 4 && !isNaN(part))
year = parseInt(part);
if(part.length <= 2 && !isNaN(part))
day = parseInt(part);
}
return (day > 0 && month > 0 && year > 0) ?
new Date(year + "-" + month + "-" + day).getTime() / 1000 :
-1;
}
function escapeUnicode(str) {
if(!str)
return str;
return str.replace("\\u0026", "&");
}
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
//#endregion
//#region Filters
const FILTER_DATE_HOUR = 1;
const FILTER_DATE_DAY = 2;
const FILTER_DATE_WEEK = 3;
const FILTER_DATE_MONTH = 4;
const FILTER_DATE_YEAR = 5;
const FILTER_DURATION_4MIN = 1;
const FILTER_DURATION_4_20MIN = 3;
const FILTER_DURATION_20MIN = 2;
const FILTER_HD = 32;
const FILTER_SUBS = 40;
const FILTER_LIVE = 64;
const FILTER_4K = 112;
const FILTER_CreativeCommons = 48;
const FILTER_360 = 120
const FILTER_VR = 208;
const FILTER_3D = 56;
const FILTER_HDR = 200
const FILTERS = [
{
id: "date",
name: "Upload Date",
isMultiSelect: false,
filters: [
new FilterCapability("Last Hour", FILTER_DATE_HOUR, Type.Date.LastHour),
new FilterCapability("This Day", FILTER_DATE_DAY, Type.Date.Today),
new FilterCapability("This Week", FILTER_DATE_WEEK, Type.Date.LastWeek),
new FilterCapability("This Month", FILTER_DATE_MONTH, Type.Date.LastMonth),
new FilterCapability("This Year", FILTER_DATE_YEAR, Type.Date.LastYear),
]
},
{
id: "duration",
name: "Duration",
isMultiSelect: false,
filters: [
new FilterCapability("Under 4 minutes", FILTER_DURATION_4MIN, Type.Duration.Short),
new FilterCapability("4-20 minutes", FILTER_DURATION_4_20MIN, Type.Duration.Medium),
new FilterCapability("Over 20 minutes", FILTER_DURATION_20MIN, Type.Duration.Long)
]
},
{
id: "features",
name: "Features",
isMultiSelect: true,
filters: [
new FilterCapability("HD", FILTER_HD),
new FilterCapability("4K", FILTER_4K),
new FilterCapability("HDR", FILTER_HDR),
new FilterCapability("Subtitles", FILTER_SUBS),
new FilterCapability("Live", FILTER_LIVE),
new FilterCapability("Creative Commons", FILTER_CreativeCommons),
new FilterCapability("VR", FILTER_VR),
new FilterCapability("3D", FILTER_3D),
new FilterCapability("360", FILTER_360)
]
}
]
const SORT_RELEVANCE = 18;
const SORT_DATE = 2;
const SORT_VIEWS = 3;
const SORT_RATING = 1;
const TYPE_VIDEO = 1;
const TYPE_CHANNEL = 2;
const TYPE_PLAYLIST = 3;
const TYPE_MOVIES = 4;
const PREFIX_TYPE = 16;
const PREFIX_LENGTH = 18;
const PREFIX_ORDER = 8;
const PREFIX_DATE = 8;
const PREFIX_DURATION = 24;
function sortToByte(sort) {
switch(sort) {
case Type.Order.Chronological:
return SORT_DATE;
case SORT_RATING_STRING:
return SORT_RATING;
case SORT_VIEWS_STRING:
return SORT_VIEWS;
default:
throw new ScriptException("Unknown sort");
}
}
function searchQueryToSP(sort, type, filters) {
if(!type)
type = TYPE_VIDEO;
let filter_date = (filters?.date && filters.date.length > 0) ? filters.date[0] : null;
let filter_duration = (filters?.duration && filters.duration.length > 0) ? filters.duration[0] : null;
let filter_features = filters?.features ?? [];
const sortByte = sort ? sortToByte(sort) : null;//SORT_RELEVANCE;
let arrLength = 0;
let filterLength = 0;
if(sortByte)
arrLength += 2;
if(type) {
filterLength += 2;
arrLength += 2;
}
if(filter_date) {
filterLength += 2;
arrLength += 2;
}
if(filter_duration) {
filterLength += 2;
arrLength += 2;
}
if(filter_features.length > 0) {
for(let i = 0; i < filter_features.length; i++) {
arrLength += 2;
filterLength += 2;
if(filter_features[i] > 128) {
arrLength += 1;
filterLength += 1;
}
}
}
if(filterLength > 0)
arrLength += 2;
const array = new Uint8Array(arrLength);
let index = 0;
if(sortByte) {
array[index] = PREFIX_ORDER;
array[index + 1] = sortByte;
index += 2;
}
if(filterLength > 0) {
array[index] = PREFIX_LENGTH;
array[index + 1] = filterLength;
index += 2;
}
if(filter_date) {
array[index] = PREFIX_DATE;
array[index + 1] = filter_date;
index += 2;
}
if(filter_duration) {
array[index] = PREFIX_DURATION;
array[index + 1] = filter_duration;
index += 2;
}
if(type) {
array[index] = PREFIX_TYPE;
array[index + 1] = type;
index += 2;
}
for(let i = 0; i < filter_features.length; i++) {
array[index] = filter_features[i];
array[index + 1] = 1;
index += 2;
if(filter_features[i] > 128) {
array[index] = 1;
index += 1;
}
}
return utility.toBase64(array);
}
//#endregion
//#region Utility
const htmlEncodedCharacters = {
"amp": "&",
"lt": "<",
"gt": ">",
"quot": "\"",
"apos": "'"
}
function decodeHtml(text) {
return text.replace(/(?:&|&)#([0-9]*);/gm, function(match, dec) {
return String.fromCharCode(dec);
}).replace(/&([a-z]*);(#.*?;)?/gm, function(match, c){
if(htmlEncodedCharacters[c])
return htmlEncodedCharacters[c];
return c;
});
}
function monthNameToNumber(month) {
if(!month)
return -1;
month = month.toLowerCase();
//Either partial or full month name
if(month.startsWith("jan")) return 1;
if(month.startsWith("feb")) return 2;
if(month.startsWith("mar")) return 3;
if(month.startsWith("apr")) return 4;
if(month.startsWith("may")) return 5;
if(month.startsWith("jun")) return 6;
if(month.startsWith("jul")) return 7;
if(month.startsWith("aug")) return 8;
if(month.startsWith("sep")) return 9;
if(month.startsWith("oct")) return 10;
if(month.startsWith("nov")) return 11;
if(month.startsWith("dec")) return 12;
return -1;
}
const ytLangMap = {
"ar": Language.ARABIC,
"es": Language.SPANISH,
"fr": Language.FRENCH,
"hi": Language.HINDI,
"id": Language.INDONESIAN,
"ko": Language.KOREAN,
"pt-BR": Language.PORTBRAZIL,
"ru": Language.RUSSIAN,
"th": Language.THAI,
"tr": Language.TURKISH,
"vi": Language.VIETNAMESE,
"en": Language.ENGLISH,
"en-US": Language.ENGLISH
};
function ytLangIdToLanguage(id) {
if(!id)
return Language.UNKNOWN;
const langParts = id?.split(".");
let langPart = (langParts && langParts.length > 0) ? langParts[0] : "";
return ytLangMap[langPart]; //Backwards compat
if(langPart.indexOf("-") > 0)
langPart = langPart.split("-")[0].trim();
if(ytLangMap[langPart])
return ytLangMap[langPart]; //Backwards compat
if(langPart && langPart.length > 0)
return langPart.trim();
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
return Language.UNKNOWN;
}
function findRenderer(obj, rendererName) {
if(!obj)
return null;
const keys = Object.keys(obj);
if(!keys || keys.length == 0)
return null;
const objName = keys[0];
const renderer = obj[objName];
if(objName == rendererName)
return renderer;
if(renderer.contents) {
for(let content of renderer.contents) {
const result = findRenderer(content, rendererName);
if(result)
return result;
}
}
if(renderer.content)
return findRenderer(renderer.content, rendererName);
return null;
}
function switchKey(obj, handlers) {
const objName = Object.keys(obj)[0];
if(!objName) {
if(handlers["null"])
return handlers["null"];
return null;
}
if(handlers[objName])
return handlers[objName](obj[objName]);
if(handlers["default"])
return handlers["default"](objName);
return null;
}
//#endregion
function validateContinuation(reqcb, useAuth = false) {
const clientContext = getClientContext(useAuth);
const result = reqcb();
const append = result?.onResponseReceivedCommands ?? result?.onResponseReceivedActions;
if(append && append.length > 0 && append[0].appendContinuationItemsAction) {
const appendResults = append[0].appendContinuationItemsAction.continuationItems;
if(!appendResults) {
if(IS_TESTING)
console.log("Continuation found without items?", result);
return [];
}
else
return appendResults;
}
else if(!clientContext.INNERTUBE_CONTEXT.client.visitorData && result.responseContext?.visitorData) {
log("[validateContinuation] No visitor data set, found visitor data in response, retrying");
clientContext.INNERTUBE_CONTEXT.client.visitorData = result.responseContext.visitorData;
//Retry with visitorData
const reResult = reqcb();
log("[validateContinuation] retry result");
if(append && append.length > 0 && append[0].appendContinuationItemsAction) {
const appendResults = append[0].appendContinuationItemsAction.continuationItems;
if(!appendResults) {
if(IS_TESTING)
console.log("Continuation found without items?", result);
return [];
}
else
return appendResults;
}
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
else
return [];
}
else
return [];
}
//#region Cipher/Decryption
var _cipherDecode = {
};
var _nDecrypt = {
};
var _sts = {
};
const REGEX_CIPHERS = [
new RegExp("(?:\\b|[^a-zA-Z0-9$])([a-zA-Z0-9$]{2,})\\s*=\\s*function\\(\\s*a\\s*\\)\\s*\\{\\s*a\\s*=\\s*a\\.split\\(\\s*\"\"\\s*\\)"),
new RegExp("\\bm=([a-zA-Z0-9$]{2,})\\(decodeURIComponent\\(h\\.s\\)\\)"),
new RegExp("\\bc&&\\(c=([a-zA-Z0-9$]{2,})\\(decodeURIComponent\\(c\\)\\)"),
new RegExp("([\\w$]+)\\s*=\\s*function\\((\\w+)\\)\\{\\s*\\2=\\s*\\2\\.split\\(\"\"\\)\\s*;"),
new RegExp("\\b([\\w$]{2,})\\s*=\\s*function\\((\\w+)\\)\\{\\s*\\2=\\s*\\2\\.split\\(\"\"\\)\\s*;"),
new RegExp("\\bc\\s*&&\\s*d\\.set\\([^,]+\\s*,\\s*(:encodeURIComponent\\s*\\()([a-zA-Z0-9$]+)\\(")
];
const REGEX_DECRYPT_N_VARIANTS = [
/\.get\(\"n\"\)\)&&\([a-zA-Z0-9$_]=([a-zA-Z0-9$_]+)(?:\[(\d+)])?\([a-zA-Z0-9$_]\)/,
/[a-zA-Z0-9$_]+=String\.fromCharCode\(110\),[a-zA-Z0-9$_]+=[a-zA-Z0-9$_]+\.get\([a-zA-Z0-9$_]+\)\)&&\([a-zA-Z0-9$_]=([a-zA-Z0-9$_]+)(?:\[(\d+)])?\([a-zA-Z0-9$_]\)/,
/[a-zA-Z]+="[n]+"\[.+\],[a-zA-Z0-9$_]+=[a-zA-Z0-9$_]+\.get\([a-zA-Z0-9$_]+\)\)&&\([a-zA-Z0-9$_]=([a-zA-Z0-9$_]+)(?:\[(\d+)])?\([a-zA-Z0-9$_]\)/,
/\/file\/index\.m3u8.+?[a-zA-Z0-9$_]=([a-zA-Z0-9$_]+)(?:\[(\d+)])?\([a-zA-Z0-9$_]\)/
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
const REGEX_PARAM_N = new RegExp("[?&]n=([^&]*)");
const STS_REGEX = new RegExp("signatureTimestamp[=:](\\d+)");
source.decryptUrlTest = function(encrypted) {
prepareCipher();
let url = decryptUrlN(encrypted.url, true);
if(!url)
url = decryptUrl(encrypted.cipher, true);
if(!url)
url = decryptUrl(encrypted.signatureCipher, true);
return url;
}
source.decryptUrlTestN = function(n) {
prepareCipher();
let url = "https://whatever.com/asdgdsag?a=b&n=" + n + "&u=asd"
return decryptUrlN(url, true);
}
function decryptUrl(encrypted, jsUrl, doLogging) {
if(!encrypted) return null;
const query = parseQueryString(encrypted);
const baseUrl = query.url;
const sigKey = query.sp;
const sigValue = decodeCipher(decodeURIComponent(query.s), jsUrl);
let decryptedUrl = decodeURIComponent(baseUrl) + "&" + sigKey + "=" + sigValue;
if(doLogging) {
log("SigKey: " + sigKey);
log("SigValue: " + sigValue);
log("Decrypted: " + decryptedUrl);
}
return decryptUrlN(decryptedUrl, jsUrl, doLogging);
}
function decryptUrlN(url, jsUrl, doLogging) {
const nParamMatch = REGEX_PARAM_N.exec(url);
if(nParamMatch) {
const encryptedN = nParamMatch[1];
const decryptedN = decryptN(encryptedN, jsUrl);
if(doLogging) {
log("Encrypt URL:" + url);
log("NParam Found: " + encryptedN + " (length:" + encryptedN.length + ")");
log("NParam Decrypted: " + decryptedN + " (size:" + decryptedN.length + ")");
log("Decrypted URL:" + url.replace(encryptedN, decryptedN));
}
url = url.replace(encryptedN, decryptedN);
}
else if(doLogging)
log("No NParam found in (" + url + ")");
return url;
}
function decodeCipher(cipher, jsUrl) {
if(!_cipherDecode[jsUrl])
throw new ScriptException("Cipher decoder was not available [" + jsUrl + "]");
return _cipherDecode[jsUrl](cipher);
}
function decryptN(encryptedN, jsUrl) {
if(!_nDecrypt[jsUrl])
throw new ScriptException("N Decryptor was not available [" + jsUrl + "]");
return _nDecrypt[jsUrl](encryptedN);
}
function testCipher(hash) {
const jsUrl = CIPHER_TEST_PREFIX + hash + CIPHER_TEST_SUFFIX;
try{
const result = prepareCipher(jsUrl);
clearCipher(jsUrl);
return {
success: result,
exception: ""
};
}
catch(ex) {
return {
success: false,
exception: ex
};
}
}
source.testCipher = testCipher;
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
function testCiphers() {
let testResults = [];
for(hash of CIPHER_TEST_HASHES) {
const jsUrl = CIPHER_TEST_PREFIX + hash + CIPHER_TEST_SUFFIX;
try{
if(prepareCipher(jsUrl))
testResults.push("CipherTest [" + hash + "]: PASSED");
else
testResults.push("CipherTest [" + hash + "]: FAIL");
}
catch(ex) {
testResults.push(["CipherTest [" + hash + "]: FAIL", ex]);
}
clearCipher(jsUrl);
}
for(result of testResults) {
if(result.constructor === Array)
console.log(result[0], result[1]);
else
console.log(result);
}
}
source.testCiphers = testCiphers;
function prepareCipher(jsUrl) {
if(_cipherDecode[jsUrl])
return false;//_cipherDecode[jsUrl];
log("New JS Url found: [" + jsUrl + "], fetching new js (total: " + (Object.keys(_cipherDecode).length + 1) + ")");
try{
const playerCodeResp = http.GET(URL_BASE + jsUrl, {});
if(!playerCodeResp.isOk) {
if(bridge.devSubmit) bridge.devSubmit("prepareCipher - Failed to get player js", jsUrl);
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
console.log("Javascript Url: " + URL_BASE + jsUrl);
const playerCode = playerCodeResp.body;
const cipherFunctionCode = getCipherFunctionCode(playerCode, jsUrl);
console.log("DecodeCipher Function: " + cipherFunctionCode);
_cipherDecode[jsUrl] = eval(cipherFunctionCode);
const decryptFunctionCode = getNDecryptorFunctionCode(playerCode, jsUrl);
console.log("DecryptN Function: " + decryptFunctionCode);
_nDecrypt[jsUrl] = eval(decryptFunctionCode);
const stsMatch = playerCode.match(STS_REGEX);
console.log("stsMatch: " + stsMatch);
if (stsMatch !== null && stsMatch.length > 1) {
const sts = stsMatch[1];
_sts[jsUrl] = sts;
console.log("sts: " + sts);
}
return true;//_cipherDecode[jsUrl];
}
catch(ex) {
clearCipher(jsUrl);
if(bridge.devSubmit) bridge.devSubmit("prepareCipher - Failed to get Cipher due to: " + ex, jsUrl);
throw new ScriptException("Failed to get Cipher due to: " + ex);
}
}
source.prepareCipher = prepareCipher;
function clearCipher(jsUrl) {
if(_cipherDecode[jsUrl])
_cipherDecode[jsUrl] = undefined;
if(_nDecrypt[jsUrl])
_nDecrypt[jsUrl] = undefined;
}
function getNDecryptorFunctionCode(code, jsUrl) {
if(_nDecrypt[jsUrl])
return _nDecrypt[jsUrl];
let nDecryptFunctionArrNameMatch = undefined;
for(let i = 0; i < REGEX_DECRYPT_N_VARIANTS.length; i++) {
nDecryptFunctionArrNameMatch = REGEX_DECRYPT_N_VARIANTS[i].exec(code);
if(!nDecryptFunctionArrNameMatch) {
console.log("NDecryptor failed, trying fallback to [" + i + 2 + "]");
}
else
break;
if(!nDecryptFunctionArrNameMatch) {
if(bridge.devSubmit) bridge.devSubmit("getNDecryptorFunctionCode - Failed to find n decryptor (name)", jsUrl);
throw new ScriptException("Failed to find n decryptor (name)\n" + jsUrl);
const nDecryptFunctionArrName = nDecryptFunctionArrNameMatch[1];
const nDecryptFunctionArrIndex = parseInt(nDecryptFunctionArrNameMatch[2]);
const nDecryptFunctionNameMatch = code.match(escapeRegex(nDecryptFunctionArrName) + "\\s*=\\s*\\[([$a-zA-Z0-9,\\(,\\)\\.]+?)]");
if(!nDecryptFunctionNameMatch) {
if(bridge.devSubmit) bridge.devSubmit("getNDecryptorFunctionCode - Failed to find n decryptor (array)", jsUrl);
Kelvin
committed
throw new ScriptException("Failed to find n decryptor (array)\n" + jsUrl);
if(nDecryptArray.length <= nDecryptFunctionArrIndex) {
if(bridge.devSubmit) bridge.devSubmit("getNDecryptorFunctionCode - Failed to find n decryptor (index)", jsUrl);
Kelvin
committed
throw new ScriptException("Failed to find n decryptor (index)\n" + jsUrl);
const nDecryptFunctionName = nDecryptArray[nDecryptFunctionArrIndex]
const nDecryptFunctionCodeMatches = [
escapeRegex(nDecryptFunctionName) + "=function\\(a\\)\\{[\\s\\S]*?join\\(\\\"\\\"\\)};",
escapeRegex(nDecryptFunctionName) + "=function\\(a\\)\\{[\\s\\S]*?join\\.call\\([a-zA-Z$_]+,\\\"\\\"\\)};",
new RegExp(escapeRegex(nDecryptFunctionName) + "=function\\(a\\)\\{[\\s\\S]*?join\\.call\\(.*?\\).*?};", "s")
]
let nDecryptFunctionCodeMatch = undefined;
for(let functionRegex of nDecryptFunctionCodeMatches) {
const match = code.match(functionRegex);
if(match && match.length > 0 && (!nDecryptFunctionCodeMatch || nDecryptFunctionCodeMatch.length > match[0].length))
nDecryptFunctionCodeMatch = match[0];
if(!nDecryptFunctionCodeMatch) {
if(bridge.devSubmit) bridge.devSubmit("getNDecryptorFunctionCode - Failed to find n decryptor (code)", jsUrl, code);
Kelvin
committed
throw new ScriptException("Failed to find n decryptor (code)\n" + jsUrl);
"return function decryptN(nEncrypted){ return " + nDecryptFunctionName + "(nEncrypted); } \n" +
"})()";
}
function getCipherFunctionCode(playerCode, jsUrl) {
if(_cipherDecode[jsUrl])
return _cipherDecode[jsUrl];
let cipherFunctionName = null;
for(let i = 0; i < REGEX_CIPHERS.length; i++) {
const match = playerCode.match(REGEX_CIPHERS[i]);
if(match) {
cipherFunctionName = match[1];
break;
}
}
if(!cipherFunctionName) {
if(bridge.devSubmit) bridge.devSubmit("getCipherFunctionCode - Failed to find cipher (name)", jsUrl);
Kelvin
committed
throw new ScriptException("Failed to find cipher (name)\n" + jsUrl);
const cipherFunctionCodeMatch = playerCode.match("(" + escapeRegex(cipherFunctionName) + "=function\\([a-zA-Z0-9_]+\\)\\{.+?\\})");
if(!cipherFunctionCodeMatch) {
if(IS_TESTING)
console.log("Failed to find cipher function in: ", playerCode);
if(bridge.devSubmit) bridge.devSubmit("getCipherFunctionCode - Failed to find cipher (function)", jsUrl);
Kelvin
committed
throw new ScriptException("Failed to find cipher (function)\n" + jsUrl);
}
const cipherFunctionCode = cipherFunctionCodeMatch[1];
const cipherFunctionCodeVar = "var " + cipherFunctionCode;
const helperObjNameMatch = cipherFunctionCode.match(";([A-Za-z0-9_\\$]{2,3})\\...\\(");
if(!helperObjNameMatch) {
if(IS_TESTING)
console.log("Failed to find helper name in: ", playerCode);
if(bridge.devSubmit) bridge.devSubmit("getCipherFunctionCode - Failed to find helper (name)", jsUrl);
Kelvin
committed
throw new ScriptException("Failed to find helper (name)\n" + jsUrl);
}
if(IS_TESTING)
console.log("Cipher Code: ", cipherFunctionCode);
const helperObjName = helperObjNameMatch[1];
const helperObjMatch = playerCode.match("(var " + escapeRegex(helperObjName) + "=\\{[\\s\\S]*?\\};)");
if(!helperObjMatch) {
if(IS_TESTING)
console.log("Failed to find helper method [" + helperObjName + "] in: ", playerCode);
if(bridge.devSubmit) bridge.devSubmit("getCipherFunctionCode - Failed to find helper (methods)", jsUrl);
Kelvin
committed
throw new ScriptException("Failed to extract helper (methods)\n" + jsUrl);
}
const helperObj = helperObjMatch[1];
const functionCode = "return function decodeCipher(str){ return " + cipherFunctionName + "(str); }";
return "(function(){" + helperObj + "\n" +
cipherFunctionCodeVar + "\n" +
functionCode + "})()";
}
function escapeRegex(str) {
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
}
function decodeHexEncodedString(str) {
return str.replace(/\\x([0-9A-Fa-f]{2})/g, function() {
return String.fromCharCode(parseInt(arguments[1], 16));
});
}
function parseQueryString(query) {
if(query.indexOf("?") >= 0)
query = query.substring(query.indexOf("?") + 1);
const parts = query.split("&");
const results = {};
for(let i = 0; i < parts.length; i++) {
const part = parts[i];
const valueIndex = part.indexOf("=");
if(valueIndex == -1)
results[part] = true;
else
results[part.substring(0, valueIndex)] = part.substring(valueIndex + 1);
}
return results;
}
//#endregion
//#region Others
const RANDOM_CHARACTER_SET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
function randomString(length) {
let str = "";
for(let i = 0; i < length; i++)
str += RANDOM_CHARACTER_SET[Math.floor(Math.random() * RANDOM_CHARACTER_SET.length)]
return str;
}
function randomInt(start, end) {
return Math.floor(random() * (end + start) - end);
}
//#endregion
console.log("LOADED");