forked from bgette/crunchyroll-downloader-nx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrunchy.js
1431 lines (1358 loc) · 53.4 KB
/
crunchy.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
// build-in
const fs = require('fs');
const path = require('path');
// package program
const packageJson = require('./package.json');
console.log(`\n=== Crunchyroll Downloader NX ${packageJson.version} ===\n`);
// plugins
const { lookpath } = require('lookpath');
const shlp = require('sei-helper');
const got = require('got');
const yaml = require('yaml');
const chio = require('cheerio');
const xhtml2js = shlp.xhtml2js; // todo: use cheerio directly
const m3u8 = require('m3u8-parsed');
const streamdl = require('hls-download');
// custom modules
const fontsData = require('./modules/module.fontsData');
const cookieFile = require('./modules/module.cookieFile');
const langsData = require('./modules/module.langsData');
const getYamlCfg = require('./modules/module.cfg-loader');
const appYargs = require('./modules/module.app-args');
// new-cfg
const curDirname = process.pkg ? path.dirname(process.execPath) : __dirname;
const cfgFolder = path.join(curDirname, '/config');
const binCfgFile = path.join(cfgFolder, 'bin-path');
const dirCfgFile = path.join(cfgFolder, 'dir-path');
const cliCfgFile = path.join(cfgFolder, 'cli-defaults');
const sessCfgFile = path.join(cfgFolder, 'session');
const sessTxtFile = path.join(cfgFolder, 'cookies.txt');
// params
const cfg = {
bin: getYamlCfg(binCfgFile),
dir: getYamlCfg(dirCfgFile),
cli: getYamlCfg(cliCfgFile),
};
// custom
let session = getYamlCfg(sessCfgFile, true);
// args
const argv = appYargs.appArgv(cfg.cli, langsData);
// fn variables
let audDubT = '',
audDubE = '',
audDubP = '',
fnTitle = '',
fnEpNum = '',
fnEpTitl = '',
fnSuffix = '',
fnOutput = '',
isBatch = false,
dlFailed = false,
sxList = [];
// api domains
const domain = 'https://www.crunchyroll.com';
const apidomain = 'https://api.crunchyroll.com';
// api script urls
const api = {
search1: `${domain}/ajax/?req=RpcApiSearch_GetSearchCandidates`,
search2: `${domain}/search_page`,
search3: `${apidomain}/autocomplete.0.json`,
session: `${apidomain}/start_session.0.json`,
collectins: `${apidomain}/list_collections.0.json`,
rss_cid: `${domain}/syndication/feed?type=episodes&id=`, // &lang=enUS
rss_gid: `${domain}/syndication/feed?type=episodes&group_id=`, // &lang=enUS
media_page: `${domain}/media-`,
series_page: `${domain}/series-`,
subs_list: `${domain}/xml/?req=RpcApiSubtitle_GetListing&media_id=`,
subs_file: `${domain}/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=`,
auth: `${domain}/login`,
// ${domain}/showseriesmedia?id=24631
// ${domain}/{GROUP_URL}/videos,
};
// set usable cookies
const usefulCookies = {
auth: [
'etp_rt',
'c_visitor',
],
sess: [
'session_id',
],
};
(async () => {
// select mode
if(argv.auth){
await doAuth();
}
else if(argv.dlfonts){
await getFonts();
}
else if(argv.search && argv.search.length > 2){
await doSearch();
}
else if(argv.search2 && argv.search2.length > 2){
await doSearch2();
}
else if(argv.s && !isNaN(parseInt(argv.s, 10)) && parseInt(argv.s, 10) > 0){
await getShowById();
}
else if(argv.e){
await getMediaById();
}
else{
console.log(argv);
appYargs.showHelp();
}
})();
// auth method
async function doAuth(){
console.log('[INFO] Authentication');
const iLogin = argv.user ? argv.user : await shlp.question('[Q] LOGIN/EMAIL');
const iPsswd = argv.pass ? argv.pass : await shlp.question('[Q] PASSWORD ');
const authData = new URLSearchParams({
name: iLogin,
password: iPsswd
});
let auth = await getData(api.auth,{ method: 'POST', body: authData.toString(), useProxy: true, skipCookies: true });
if(!auth.ok){
console.log('[ERROR] Authentication failed!');
if(auth.error && auth.error.res && auth.error.res.body){
console.log('[AUTH] Body:', auth.error.res.body);
}
return;
}
setNewCookie(auth.res.headers['set-cookie'], true);
console.log('[INFO] Authentication successful!');
}
// get cr fonts
async function getFonts(){
console.log('[INFO] Downloading fonts...');
for(let f of Object.keys(fontsData.fonts)){
let fontFile = fontsData.fonts[f];
let fontLoc = path.join(cfg.dir.fonts, fontFile);
if(fs.existsSync(fontLoc) && fs.statSync(fontLoc).size != 0){
console.log(`[INFO] ${f} (${fontFile}) already downloaded!`);
}
else{
if(fs.existsSync(fontLoc) && fs.statSync(fontLoc).size == 0){
fs.unlinkSync(fontLoc);
}
let fontUrl = fontsData.root + fontFile;
let getFont = await getData(fontUrl, { useProxy: true, skipCookies: true, binary: true });
if(getFont.ok){
fs.writeFileSync(fontLoc, getFont.res.body);
console.log(`[INFO] Downloaded: ${f} (${fontFile})`);
}
else{
console.log(`[WARN] Failed to download: ${f} (${fontFile})`);
}
}
}
console.log('[INFO] All required fonts downloaded!');
}
async function doSearch(){
// session
let apiSession = '';
if(session.session_id && checkSessId(session.session_id) && !argv.nosess){
apiSession = session.session_id.value;
}
// seacrh params
const params = new URLSearchParams({
q: argv.search,
clases: 'series',
media_types: 'anime',
fields: 'series.series_id,series.name,series.year',
offset: argv.p ? (parseInt(argv.p)-1)*100 : 0,
limit: 100,
locale: 'enUS',
});
if(apiSession != ''){
params.append('session_id', apiSession);
}
else{
const crDevices = {
win10: {
device_type: 'com.crunchyroll.windows.desktop',
access_token: 'LNDJgOit5yaRIWN',
},
android: {
device_type: 'com.crunchyroll.crunchyroid',
access_token: 'WveH9VkPLrXvuNm',
},
};
const sessionParams = new URLSearchParams({
device_type: crDevices.win10.device_type,
device_id : '00000000-0000-0000-0000-000000000000',
access_token: crDevices.win10.access_token,
});
let reqSession = await getData(`${api.session}?${sessionParams.toString()}`,{useProxy:true});
if(!reqSession.ok){
console.log('[ERROR] Can\'t update session id!');
return;
}
reqSession = JSON.parse(reqSession.res.body);
if(reqSession.error){
console.log(`[ERROR] ${aniList.message}`);
}
else{
argv.nosess = false;
console.log(`[INFO] Your country: ${reqSession.data.country_code}\n`);
apiSession = session.session_id.value;
params.append('session_id', apiSession);
}
}
// request
let aniList = await getData(`${api.search3}?${params.toString()}`,{useProxy:true});
if(!aniList.ok){
console.log('[ERROR] Can\'t get search data!');
return;
}
aniList = JSON.parse(aniList.res.body);
if(aniList.error){
console.log(`[ERROR] ${aniList.message}`);
}
else{
if(aniList.data.length > 0){
console.log('[INFO] Search Results:');
for(let a of aniList.data){
await printSeasons(a,apiSession);
}
console.log(`\n[INFO] Total results: ${aniList.data.length}\n`);
}
else{
console.log('[INFO] Nothing Found!');
}
}
}
async function printSeasons(a,apiSession){
console.log(`[SERIES] #${a.series_id} ${a.name}`,(a.year?`(${a.year})`:''));
let collParams = new URLSearchParams({
session_id: apiSession,
series_id: a.series_id,
fields: 'collection.collection_id,collection.name',
limit: 5000,
offset: 0,
locale: 'enUS',
});
let seasonList = await getData(`${api.collectins}?${collParams.toString()}`,{useProxy:true});
if(seasonList.ok){
seasonList = JSON.parse(seasonList.res.body);
if(seasonList.error){
console.log(` [ERROR] Can't fetch seasons list: ${seasonList.message}`);
}
else{
if(seasonList.data.length>0){
for(let s of seasonList.data){
console.log(` [S:${s.collection_id}] ${s.name}`);
}
}
else{
console.log(' [ERROR] Seasons list is empty');
}
}
}
else{
console.log(' [ERROR] Can\'t fetch seasons list (request failed)');
}
}
async function doSearch2(){
// search params
const params = new URLSearchParams({
q: argv.search2,
sp: argv.p ? parseInt(argv.p) - 1 : 0,
limit: 100,
st: 'm'
});
// request
let reqAniSearch = await getData(`${api.search2}?${params.toString()}`,{useProxy:true});
if(!reqAniSearch.ok){ return; }
let reqRefAniList = await getData(`${api.search1}`,{useProxy:true});
if(!reqRefAniList.ok){ return; }
// parse fix
let aniSearchSec = reqAniSearch.res.body.replace(/^\/\*-secure-\n(.*)\n\*\/$/,'$1');
let aniRefListSec = reqRefAniList.res.body.replace(/^\/\*-secure-\n(.*)\n\*\/$/,'$1');
aniSearchSec = JSON.parse(aniSearchSec);
aniRefListSec = JSON.parse(aniRefListSec);
let totalResults = 0;
// data
const mainHtml = xhtml2js({ src: '<html>'+aniSearchSec.data.main_html+'</html>', el: 'body' }).$;
const results0 = mainHtml.find('p');
const results1 = results0.eq(0).text().trim();
const results2 = results0.eq(1).text().trim();
const resultsStr = results2 != '' ? results2 :
results1 != '' ? results1 : 'NOTHING FOUND!';
console.log(`[INFO] ${resultsStr}`);
// seasons
const searchData = mainHtml.find('li');
for(let v=0; v<searchData.length; v++){
let href = searchData.eq(v).find('a')[0].attribs.href;
let data = aniRefListSec.data.filter(value => value.link == href).shift();
let notLib = href.match(/^\/library\//) ? false : true;
if(notLib && data && data.type == 'Series'){
if(session.session_id && checkSessId(session.session_id) && !argv.nosess){
await printSeasons({series_id: data.id, name: data.name},session.session_id.value);
}
else{
console.log(' [ERROR] Can\'t fetch seasons list, session_id cookie required');
}
totalResults++;
}
if(notLib && !data){
console.log('[SERIES] #??????', href.replace(/^\//,'').replace(/-/g,' '));
console.log(' [ERROR] Can\'t fetch seasons list, not listed in search data');
console.log(` [ERROR] URL: ${domain}${href}`);
totalResults++;
}
}
if(totalResults>0){
console.log('[INFO] Non-anime results is hidden');
console.log(`[INFO] Total results: ${totalResults}\n`);
}
}
async function getShowById(){
// request episode list
const epListRss = `${api.rss_cid}${argv.s}`;
const epListReq = await getData(epListRss,{useProxy:true});
// request failed
if(!epListReq.ok){ return 0; }
// set data
const epListBody = epListReq.res.body;
const epListXML = xhtml2js({ src: epListBody, el: 'channel', isXml: true }).$;
// set and show main title // image title
const showTitle = (
epListXML.find('image title').eq(0).text()
? epListXML.find('image title').eq(0).text()
: epListXML.find('title').eq(0).text().replace(/ Episodes$/i,'')
);
const isSimul = epListXML.find('crunchyroll\\:simulcast').length > 0 ? true : false;
// if dubbed title
if(showTitle.match(langsData.dubRegExp)){
audDubT = langsData.dubLangs[showTitle.match(langsData.dubRegExp)[1]];
console.log(`[INFO] audio language code detected, setted to ${audDubT} for this title`);
}
// display title
console.log(`[S:${argv.s}] ${showTitle}`,(isSimul?'[simulcast]':''));
// parse list
const titleEpsList = { media: {}, episodes: [], specials: [], meta: {} };
const epsList = epListXML.find('item');
const vdsCount = epsList.length;
const dateNow = Date.now() + 1;
// st num length
const epNumLen = { E: 4, S: 3, M: 6 };
// create list
epsList.each((idx) => {
// set index
idx = isSimul ? vdsCount - idx - 1 : idx;
// add eps nums
const videoTitleData = {
season: showTitle,
episodeNo: epsList.eq(idx).find('crunchyroll\\:episodeNumber').text(),
episode: epsList.eq(idx).find('crunchyroll\\:episodeTitle').text(),
};
let epNumStr = videoTitleData.episodeNo;
let epNum = epNumStr;
epNum = epNum.match(/^\d+$/) ? epNum.padStart(epNumLen['E'], '0') : epNum;
if(titleEpsList.episodes.indexOf(epNum) > -1 || !epNum.match(/^\d+$/) ){
epNum = 'S' + (titleEpsList.specials.length + 1).toString().padStart(epNumLen['S'], '0');
titleEpsList.specials.push(epNum);
}
else{
titleEpsList.episodes.push(epNum);
}
// add media-episode relation
let mediaId = epsList.eq(idx).find('crunchyroll\\:mediaId').text();
let mediaIdPad = mediaId.padStart(epNumLen['M'], '0');
let epType = epNum.match('S') ? 'specials' : 'episodes';
titleEpsList.media[mediaIdPad] = `${epType}:${titleEpsList[epType].length-1}`;
// episode info
let ssTitle = videoTitleData.season;
let epTitle = videoTitleData.episode;
let airDate = new Date(epsList.eq(idx).find('crunchyroll\\:premiumPubDate').text());
let airFree = new Date(epsList.eq(idx).find('crunchyroll\\:freePubDate').text());
let endDate = new Date(epsList.eq(idx).find('crunchyroll\\:endPubDate').text());
let subsArr = epsList.eq(idx).find('crunchyroll\\:subtitleLanguages').text();
// add data
titleEpsList.meta[mediaIdPad] = {
m: mediaId,
t: ssTitle,
e: epNumStr,
te: epTitle,
epd: false,
};
// print info
let listEpTitle = '';
listEpTitle += epNumStr ? epNumStr : '';
listEpTitle += epNumStr && epTitle ? ' - ' : '';
listEpTitle += epTitle ? epTitle : '';
listEpTitle = listEpTitle ? listEpTitle :
epsList.eq(idx).find('title').text();
console.log(` [${epNum}|${mediaIdPad}] ${listEpTitle}`);
// print dates
let dateStrPrem = shlp.dateString(airDate)
+ ( dateNow < airDate ? ` (in ${shlp.formatTime((airDate-dateNow)/1000)})` : '');
let dateStrFree = shlp.dateString(airFree)
+ ( dateNow < airFree ? ` (in ${shlp.formatTime((airFree-dateNow)/1000)})` : '');
if(dateStrFree.match(/in/)){
console.log(` - PremPubDate: ${dateStrPrem}`);
}
console.log(` - FreePubDate: ${dateStrFree}`);
if(endDate < 5000000000000){
console.log(` - EndPubDate: ${shlp.dateString(endDate)}`);
}
if(endDate < dateNow){
titleEpsList.meta[mediaIdPad].epd = true;
}
// subtitles
if(subsArr){
console.log(` - Subtitles: ${langsData.parseRssSubsString(subsArr)}`);
}
});
let inputEps = typeof argv.e != 'undefined'
? argv.e.toString().split(',') : [];
let inputEpsRange = [];
if(inputEps.length<1){
console.log('\n[INFO] Episodes not selected!\n');
return;
}
// selectors
const selData = { media: [], eps: [] };
const epRexVr = `^(?:E?\\d{1,${epNumLen['E']}}|S\\d{1,${epNumLen['S']}}|M\\d{1,${epNumLen['M']}})$`;
const epRegex = new RegExp (epRexVr);
// const filter wrong numbers
inputEps = inputEps.map((e) => {
// conver to uppercase
e = e.toUpperCase();
// if range
if(e.match('-') && e.split('-').length == 2){
let eRange = e.split('-');
let mch1 = eRange[0].match(epRegex);
if (!mch1) return '';
let epLetter = eRange[0].match(/(?:E|S|M)/) ? eRange[0].match(/(?:E|S|M)/)[0] : 'E';
let mch2 = eRange[1].match(new RegExp (`^\\d{1,${epNumLen[epLetter]}}$`));
if (!mch2) return '';
eRange[0] = eRange[0].replace(/(?:E|S|M)/,'');
eRange[0] = parseInt(eRange[0]);
eRange[1] = parseInt(eRange[1]);
if (eRange[0] > eRange[1]) return epLetter + eRange[0];
let rangeLength = eRange[1] - eRange[0] + 1;
let epsRangeArr = Array(rangeLength).fill(0).map((x, y) => x + y + eRange[0]);
epsRangeArr.forEach((i)=>{
let selEpStr = epLetter + i.toString().padStart(epNumLen[epLetter],'0');
inputEpsRange.push(selEpStr);
});
return '';
}
else if(e.match(epRegex)){
return e;
}
return '';
});
// remove empty and duplicates
inputEps = [...new Set(inputEps.concat(inputEpsRange))];
const mediaList = Object.keys(titleEpsList.media).sort();
console.log();
// select episodes
inputEps.map((e) => {
if(e.match(/M/)){
e = e.replace(/M/,'').padStart(epNumLen['M'],'0');
if(selData.media.indexOf(e) > -1) return '';
let idx = mediaList.indexOf(e);
if(idx > -1 && selData.media.indexOf(e) < 0 && !titleEpsList.meta[e].epd){
let epArr = titleEpsList.media[e].split(':');
selData.eps.push(titleEpsList[epArr[0]][epArr[1]]);
selData.media.push(e);
}
if(titleEpsList.meta[e].epd){
let mMeta = titleEpsList.meta[e];
console.log(`[INFO] Skipped due EndPubDate: [${mMeta.m}] ${mMeta.t} - ${mMeta.e} - ${mMeta.te}`);
}
}
else{
if(e == '') return '';
let eLetter = e.match(/S/) ? 'S' : 'E';
e = (eLetter == 'S' ? 'S' : '') + e.replace(/E|S/, '').padStart(epNumLen[eLetter], '0');
if(selData.eps.indexOf(e) > -1) return '';
let seqArr = eLetter == 'S' ? 'specials' : 'episodes';
let seqIdx = titleEpsList[seqArr].indexOf(e);
if(seqIdx > -1){
let idx = Object.values(titleEpsList.media).indexOf(`${seqArr}:${seqIdx}`);
let msq = mediaList[idx];
if(selData.media.indexOf(msq) < 0 && !titleEpsList.meta[msq].epd){
selData.media.push(msq);
selData.eps.push(e);
}
if(titleEpsList.meta[msq].epd){
let mMeta = titleEpsList.meta[msq];
console.log(`[INFO] Skipped due EndPubDate: [${mMeta.m}] ${mMeta.t} - ${mMeta.e} - ${mMeta.te}`);
}
}
}
});
// display
if(selData.eps.length < 1){
console.log('[INFO] Episodes not selected!\n');
return;
}
selData.eps.sort();
console.log('[INFO] Selected Episodes:', selData.eps.join(', ')+'\n');
const selMedia = selData.media;
// start selecting from list
if(selMedia.length > 0){
for(let sm of selMedia){
await getMedia(titleEpsList.meta[sm]);
}
}
}
async function getMediaById(){
// default
let e = argv.e.split(','), inpMedia = [''];
// map select
e.map((e) => {
if(e.match('-') && e.split('-').length == 2){
let eRange = e.split('-');
if(eRange[0].match(/^m\d{1,6}$/i) && eRange[1].match(/^\d{1,6}$/)){
eRange[0] = eRange[0].replace(/^m/i,'');
eRange[0] = parseInt(eRange[0]);
eRange[1] = parseInt(eRange[1]);
if (eRange[0] > eRange[1]) {
inpMedia.push(eRange[0]);
}
else{
let rangeLength = eRange[1] - eRange[0] + 1;
let epsRangeArr = Array(rangeLength).fill(0).map((x, y) => x + y + eRange[0]);
epsRangeArr.forEach((i)=>{
let selEpStr = i.toString();
inpMedia.push(selEpStr);
});
}
}
}
else if(e.match(/^m\d{1,6}$/i)){
inpMedia.push(parseInt(e.replace(/^m/i,'')));
}
});
inpMedia = [...new Set(inpMedia)].splice(1);
if(inpMedia.length > 0){
console.log('[INFO] Selected media:', inpMedia.join(', '), '\n');
for(let mid of inpMedia){
await getMedia({ m: mid });
}
}
else{
console.log('[INFO] Media not selected!');
}
}
async function getMedia(mMeta){
let mediaName = mMeta.t && mMeta.e && mMeta.te ? `${mMeta.t} - ${mMeta.e} - ${mMeta.te}` : '...';
console.log(`Requesting: [${mMeta.m}] ${mediaName}`);
const mediaPage = await getData(`${api.media_page}${mMeta.m}`, {useProxy:true});
if(!mediaPage.ok){
console.log('[ERROR] Failed to get video page!');
return;
}
const contextData = mediaPage.res.body.match(/({"@context":.*)(<\/script>)/);
const contextJson = JSON.parse(contextData[1]);
const eligibleRegion = contextJson.potentialAction
.actionAccessibilityRequirement.eligibleRegion;
const vHtml = chio.load(mediaPage.res.body);
const ccEl = vHtml('#footer_country_flag');
const ccLocUserArr = ccEl.attr('src').split('/');
const ccLocUser = ccLocUserArr[ccLocUserArr.length-1].split('.')[0].toUpperCase();
console.log('[INFO] Your region:', ccLocUser, ccEl.attr('alt'));
const userDetect = mediaPage.res.body.match(/\$\.extend\(traits, (.*)\);/);
const curUser = userDetect ? JSON.parse(userDetect[1]) : {'username': 'anonimous'};
console.log('[INFO] Your account:', curUser.username, '\n');
const availDetect = eligibleRegion.filter((r)=>{ return r.name == ccLocUser; });
const isAvailVideo = availDetect.length > 0 ? true : false;
// page msgs
let msgItems = mediaPage.res.body.match(/Page.messaging_box_controller.addItems\((.*)\);/);
msgItems = msgItems ? JSON.parse(msgItems[1]) : [];
msgItems.map(m => {
m.type = m.type.toUpperCase();
return m;
});
let msgHasErrors = msgItems.filter(m => m.type == 'ERROR').length > 0 ? true : false;
if(msgItems.length > 0 && argv.pagemsgs || msgItems && msgHasErrors){
let msgItemsArr = [];
console.log('[INFO] PAGE MSGs:');
for(let m of msgItems){
msgItemsArr.push(` [${m.type}] ${m.message_body.replace(/<[^>]*>?/gm, '')}`);
}
msgItemsArr = [...new Set(msgItemsArr)];
console.log(msgItemsArr.join('\n'),'\n');
}
// --
let mediaData = mediaPage.res.body.match(/vilos.config.media = \{(.*)\};/);
if(!mediaData && !isAvailVideo){
console.log('[ERROR] VIDEO NOT AVAILABLE FOR YOUR REGION!');
return;
}
else if(!mediaData){
console.log('[ERROR] CAN\'T DETECT VIDEO INFO / PREMIUM LOCKED FOR YOUR REGION?');
return;
}
else{
mediaData = mediaData[1];
mediaData = JSON.parse(`{${mediaData}}`);
if(argv.debug){
console.log('[DEBUG]', contextJson);
console.log('[DEBUG]', mediaData);
}
}
if(mediaName == '...'){
mMeta.t = mMeta.t ? mMeta.t : contextJson.partOfSeason.name;
mMeta.e = mMeta.e ? mMeta.e : mediaData.metadata.episode_number;
mMeta.te = mMeta.te ? mMeta.te : mediaData.metadata.title;
mMeta.epd = false;
// show name
mediaName = `${mMeta.t} - ${mMeta.e} - ${mMeta.te}`;
console.log(`Requesting: [${mMeta.m}] ${mediaName}`);
}
audDubE = '';
if(audDubT == '' && mMeta.te.match(langsData.dubRegExp)){
audDubE = langsData.dubLangs[mMeta.te.match(langsData.dubRegExp)[1]];
console.log(`[INFO] audio language code detected, setted to ${audDubE} for this episode`);
}
let epNum = mMeta.e;
let metaEpNum = mediaData ? mediaData.metadata.episode_number : epNum.replace(/^E/,'');
if(metaEpNum != '' && metaEpNum !== null){
epNum = metaEpNum.match(/^\d+$/) ? metaEpNum.padStart(argv.el,'0') : metaEpNum;
}
if(typeof argv.q == 'object' && argv.q.length > 1){
argv.q = argv.q[argv.q.length-1];
}
fnTitle = argv.t ? argv.t : mMeta.t;
fnEpNum = !isBatch && argv.ep ? argv.ep : epNum;
fnEpTitl = mMeta.te;
fnSuffix = argv.suffix.replace('SIZEp', argv.q);
fnOutput = fnOutputGen();
let streams = mediaData ? mediaData.streams : [],
streamKey = '';
let isClip = false,
hlsStream = '';
if(argv.oldstreams){
let videoSrcStr = mediaPage.res.body.match(/<link rel="video_src" href="(.*)" \/>/);
if(videoSrcStr){
isClip = true;
let parseCfg = new URL(videoSrcStr[1]).searchParams;
let parseCfgUrl = parseCfg.get('config_url') + '¤t_page=' + domain;
let streamData = await getData(parseCfgUrl.replace(/http:/, 'https:'), {useProxy: argv.ssp});
if(streamData.ok){
let videoDataBody = streamData.res.body.replace(/\n/g,'').replace(/ +/g,' ');
let xmlMediaId = videoDataBody.match(/<media_id>(\d+)<\/media_id>/);
let xmlFileUrl = videoDataBody.match(/<file>(.*)<\/file>/);
let xmlError = videoDataBody.match(/<error>(.*)<\/error>/);
let countdown = videoDataBody.match(/<countdown_seconds>(\d+)<\/countdown_seconds>/);
if(countdown && countdown[1] && countdown[1] > 0){
console.log('[INFO] Episode not aired yet!');
return;
}
if(xmlMediaId && xmlMediaId[1] && xmlMediaId[1] != mMeta.m){
mMeta.m = xmlMediaId[1];
}
if(xmlFileUrl && xmlFileUrl[1]){
streamKey = 'api_hls';
hlsStream = xmlFileUrl[1].replace(/&/g,'&');
console.log('[INFO] Full raw stream found!');
}
else if(xmlError && xmlError[1]){
isClip = false;
let xmlErrorData = xmlError[1].trim().match(/<code>(\d+)<\/code>(.*)<msg>(.*)<\/msg>/);
console.log(`[ERROR] CODE ${xmlErrorData[1]}: ${xmlErrorData[3]}`);
}
}
}
}
else if(streams.length>0){
let hlsStreams = {};
let hlsStreamIndex = 1;
// streams.reverse();
// set hardsubs
let hsLang = argv.hslang ? argv.hslang : null;
if(langsData.subsLangsFilter.indexOf(hsLang) > 0 && ['all', 'none'].indexOf(hsLang) < 0){
console.log('[INFO] Selecting stream with %s hardsubs', hsLang);
argv.dlsubs = 'none';
}
else{
console.log('[INFO] Selecting raw stream');
hsLang = null;
}
// --
for(let s in streams){
let isHls = streams[s].format.match(/hls/)
&& !streams[s].format.match(/drm/) ? true : false;
let checkParams = isHls && streams[s].hardsub_lang === hsLang;
if(streams[s].url.match(/clipFrom/)){
isClip = true;
}
if(checkParams && !isClip){
let sKeyStr = `${streams[s].format}/${streams[s].audio_lang}`;
hlsStreams[sKeyStr] = streams[s].url;
console.log(`[INFO] Full stream found! (${hlsStreamIndex}: ${sKeyStr})`);
hlsStreamIndex++;
}
}
let hlsStreamKeys = Object.keys(hlsStreams);
if(hlsStreamKeys.length>0){
argv.kstream = argv.kstream > hlsStreamKeys.length ? 1 : argv.kstream;
for(let k in hlsStreamKeys){
k = parseInt(k);
if(hlsStream == '' || argv.kstream == k + 1){
streamKey = hlsStreamKeys[k];
hlsStream = hlsStreams[streamKey];
}
}
}
else{
hlsStream = '';
}
}
else{
console.log('[WARN] No streams found!');
}
if(argv.nullstream){
hlsStream = '';
}
// reset playlist
audDubP = '';
// download stream
if(!isAvailVideo){
console.log('[ERROR] No available full raw stream! Video not available for your region!');
argv.skipmux = true;
}
else if(hlsStream == '' && !isClip){
console.log('[ERROR] No available full raw stream! Session expired?');
argv.skipmux = true;
}
else if(hlsStream == '' && isClip){
console.log('[ERROR] No available full raw stream! Only clip streams available.');
argv.skipmux = true;
}
else{
// get
console.log('[INFO] Downloading video...');
let streamKeyStr = streamKey != '' ? `(${streamKey})` : '';
let streamUrlTxt = argv.ssu ? hlsStream : '';
// check lng
let streamDubLang = typeof streamKey == 'string' ? streamKey.split('/') : '';
if(streamDubLang[1] && langsData.langCodes[streamDubLang[1]]){
let PlAudioLang = langsData.langCodes[streamDubLang[1]];
if(audDubT == '' && audDubE == '' && PlAudioLang.code != argv.dub){
audDubP = PlAudioLang.code;
console.log(`[INFO] audio language code detected, setted to ${PlAudioLang.lang} for this episode`);
}
}
// request
console.log('[INFO] Playlist URL:', streamUrlTxt, streamKeyStr);
let streamPlaylist = await getData(hlsStream, {useProxy: argv.ssp});
if(!streamPlaylist.ok){
console.log(streamPlaylist);
console.log('[ERROR] CAN\'T FETCH VIDEO PLAYLISTS!');
dlFailed = true;
}
else{
// parse
let plQualityLinkList = m3u8(streamPlaylist.res.body);
// variables
let plServerList = [],
plStreams = {},
plQualityStr = [],
plMaxQuality = 240;
// set variables
for(let s of plQualityLinkList.playlists){
let plResolution = s.attributes.RESOLUTION.height;
let plResText = `${plResolution}p`;
plMaxQuality = plMaxQuality < plResolution ? plResolution : plMaxQuality;
let plUrlDl = s.uri;
let plServer;
plServer = plUrlDl.split('/')[2];
if(plUrlDl.match(/&cdn=([a-z-]+)/)){
plServer = `${plUrlDl.split('/')[2]} (${plUrlDl.match(/&cdn=([a-z-]+)/)[1]})`;
}
if(!plServerList.includes(plServer)){
plServerList.push(plServer);
}
if(!Object.keys(plStreams).includes(plServer)){
plStreams[plServer] = {};
}
if(plStreams[plServer][plResText] && plStreams[plServer][plResText] != plUrlDl && typeof plStreams[plServer][plResText] != 'undefined'){
console.log(`[WARN] Non duplicate url for ${plServer} detected, please report to developer!`);
}
else{
plStreams[plServer][plResText] = plUrlDl;
}
// set plQualityStr
let plBandwidth = Math.round(s.attributes.BANDWIDTH/1024);
if(plResolution<1000){
plResolution = plResolution.toString().padStart(4,' ');
}
let qualityStrAdd = `${plResolution}p (${plBandwidth}KiB/s)`;
let qualityStrRegx = new RegExp(qualityStrAdd.replace(/(:|\(|\)|\/)/g,'\\$1'),'m');
let qualityStrMatch = !plQualityStr.join('\r\n').match(qualityStrRegx);
if(qualityStrMatch){
plQualityStr.push(qualityStrAdd);
}
}
argv.q = argv.q == 'max' ? `${plMaxQuality}p` : argv.q;
let plSelectedServer = plServerList[argv.x-1];
let plSelectedList = plStreams[plSelectedServer];
let videoUrl = argv.x < plServerList.length+1 && plSelectedList[argv.q] ? plSelectedList[argv.q] : '';
plQualityStr.sort();
console.log(`[INFO] Servers available:\n\t${plServerList.join('\n\t')}`);
console.log(`[INFO] Available qualities:\n\t${plQualityStr.join('\n\t')}`);
if(videoUrl != ''){
console.log(`[INFO] Selected quality: ${argv.q} @ ${plSelectedServer}`);
if(argv.ssu){
console.log('[INFO] Stream URL:',videoUrl);
}
if(argv.ssuex){
console.log('[INFO] Streams Data:', plStreams);
}
// filename
fnSuffix = argv.suffix.replace('SIZEp',argv.q);
fnOutput = fnOutputGen();
console.log(`[INFO] Output filename: ${fnOutput}`);
if(argv.skipdl){
console.log('[INFO] Video download skipped!\n');
}
else{
// request
let chunkPage = await getData(videoUrl,{useProxy: argv.ssp});
if(!chunkPage.ok){
console.log('[ERROR] CAN\'T FETCH VIDEO PLAYLIST!');
argv.skipmux = true;
}
else{
let chunkList = m3u8(chunkPage.res.body);
chunkList.baseUrl = videoUrl.split('/').slice(0, -1).join('/')+'/';
// proxy
let proxyHLS = false;
if(argv.proxy && !argv.ssp){
try{
proxyHLS = {};
proxyHLS.url = buildProxy(argv.proxy, argv['proxy-auth']);
proxyHLS.url = proxyHLS.url.toString();
}
catch(e){
console.log(`\n[WARN] Not valid proxy URL${e.input?' ('+e.input+')':''}!`);
console.log('[WARN] Skiping...');
proxyHLS = false;
}
}
let totalParts = chunkList.segments.length;
let mathParts = Math.ceil(totalParts / argv.tsparts);
let mathMsg = `(${mathParts}*${argv.tsparts})`;
console.log('[INFO] Total parts in stream:', totalParts, mathMsg);
let tsFile = path.join(cfg.dir.content, fnOutput);
let streamdlParams = {
fn: `${tsFile}.ts`,
m3u8json: chunkList,
baseurl: chunkList.baseUrl,
pcount: argv.tsparts,
partsOffset: 0,
proxy: ( proxyHLS ? proxyHLS : false),
};
let dldata = await new streamdl(streamdlParams).download();
if(!dldata.ok){
fs.writeFileSync(`${tsFile}.ts.resume`, JSON.stringify(dldata.parts));
console.log(`[ERROR] DL Stats: ${JSON.stringify(dldata.parts)}\n`);
dlFailed = true;
}
else if(fs.existsSync(`${tsFile}.ts.resume`) && dldata.ok){
fs.unlinkSync(`${tsFile}.ts.resume`);
}
}
}
}
else if(argv.x > plServerList.length){
console.log('[ERROR] Server not selected!\n');
dlFailed = true;
}
else{
console.log('[ERROR] Quality not selected!\n');
dlFailed = true;
}
}
}
// fix max quality for non streams
if(argv.q == 'max'){
argv.q = '1080p';
fnSuffix = argv.suffix.replace('SIZEp', argv.q);
fnOutput = fnOutputGen();
}
// download subs
sxList = [];
if(!argv.skipsubs && argv.dlsubs != 'none'){
console.log('[INFO] Downloading subtitles...');
if(mediaData.subtitles.length < 1){
console.log('[WARN] Can\'t find urls for subtitles!');
}
else if(mediaData.subtitles.length > 0){
mediaData.subtitles = langsData.sortSubtitles(mediaData.subtitles);
for(let si in mediaData.subtitles){
let s = mediaData.subtitles[si];
let cl = langsData.langCodes[s.language];
let sxData = {};
sxData.file = langsData.subsFile(fnOutput, si, cl);
sxData.langExtCode = s.language;
sxData.langCode = cl.code;
sxData.langTag = cl.tag;
sxData.langName = cl.name;
sxData.langStr = cl.local;
if(argv.dlsubs.includes('all') || argv.dlsubs.includes(s.language)){
let subsAssApi = await getData(s.url, {useProxy: argv.ssp});
if(subsAssApi.ok){
let sBody = '\ufeff' + subsAssApi.res.body;
sxData.title = sBody.split('\r\n')[1].replace(/^Title: /, '');
sxData.fonts = fontsData.assFonts(sBody);
fs.writeFileSync(path.join(cfg.dir.content, sxData.file), sBody);
console.log(`[INFO] Subtitle downloaded: ${sxData.file}`);
sxList.push(sxData);
}
else{
console.log(`[WARN] Failed to download subtitle: ${sxData.file}`);
}
}
}
if(sxList.length > 0){
langsData.subsStr(sxList);
}
}
}
else{
console.log('[INFO] Subtitles downloading skipped');
}
// go to muxing
if(!argv.skipmux && !dlFailed){
await muxStreams();
}
else{
console.log();
}
dlFailed = false;
return;
}