forked from noctarius/funimation-downloader-nx-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crunchy.ts
1474 lines (1393 loc) · 46.1 KB
/
crunchy.ts
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
// build-in
import path from 'path';
import fs from 'fs-extra';
// package program
import packageJson from './package.json';
// plugins
import shlp from 'sei-helper';
import m3u8 from 'm3u8-parsed';
import streamdl from 'hls-download';
// custom modules
import * as fontsData from './modules/module.fontsData';
import * as langsData from './modules/module.langsData';
import * as yamlCfg from './modules/module.cfg-loader';
import * as yargs from './modules/module.app-args';
import Merger, { Font, MergerInput, SubtitleInput } from './modules/module.merger';
// new-cfg paths
const cfg = yamlCfg.loadCfg();
let token = yamlCfg.loadCRToken();
let cmsToken: {
cms?: Record<string, string>
} = {};
export type sxItem = {
language: langsData.LanguageItem,
path: string,
file: string
title: string,
fonts: Font[]
}
// args
const argv = yargs.appArgv(cfg.cli);
// load req
import { domain, api } from './modules/module.api-urls';
import * as reqModule from './modules/module.req';
import { CrunchySearch } from './@types/crunchySearch';
import { CrunchyEpisodeList, Item } from './@types/crunchyEpisodeList';
import { CrunchyEpMeta, DownloadedMedia, ParseItem, SeriesSearch, SeriesSearchItem } from './@types/crunchyTypes';
import { ObjectInfo } from './@types/objectInfo';
import parseFileName, { Variable } from './modules/module.filename';
import { PlaybackData } from './@types/playbackData';
import { downloaded } from './modules/module.downloadArchive';
import parseSelect from './modules/module.parseSelect';
import { AvailableFilenameVars } from './modules/module.args';
const req = new reqModule.Req(domain, argv);
// select
export default (async () => {
console.log(`\n=== Multi Downloader NX ${packageJson.version} ===\n`);
// load binaries
cfg.bin = await yamlCfg.loadBinCfg();
if (argv.allDubs) {
argv.dubLang = langsData.dubLanguageCodes;
}
// select mode
if (argv.silentAuth && !argv.auth) {
await doAuth();
}
if(argv.dlFonts){
await getFonts();
}
else if(argv.auth){
await doAuth();
}
else if(argv.cmsindex){
await refreshToken();
await getCmsData();
}
else if(argv.new){
await refreshToken();
await getNewlyAdded();
}
else if(argv.search && argv.search.length > 2){
await refreshToken();
await doSearch();
}
else if(argv.series && argv.series.match(/^[0-9A-Z]{9}$/)){
await refreshToken();
await getSeriesById();
return await downloadFromSeriesID();
}
else if(argv['movie-listing'] && argv['movie-listing'].match(/^[0-9A-Z]{9}$/)){
await refreshToken();
await getMovieListingById();
}
else if(argv.s && argv.s.match(/^[0-9A-Z]{9}$/)){
await refreshToken();
if (argv.dubLang.length > 1) {
console.log('[INFO] One show can only be downloaded with one dub. Use --srz instead.');
}
argv.dubLang = [argv.dubLang[0]];
return await getSeasonById();
}
else if(argv.e){
await refreshToken();
await getObjectById();
}
else{
yargs.showHelp();
}
});
// get cr fonts
async function getFonts(){
console.log('[INFO] Downloading fonts...');
const fonts = Object.values(fontsData.fontFamilies).reduce((pre, curr) => pre.concat(curr));
for(const f of fonts) {
const fontLoc = path.join(cfg.dir.fonts, f);
if(fs.existsSync(fontLoc) && fs.statSync(fontLoc).size != 0){
console.log(`[INFO] ${f} already downloaded!`);
}
else{
const fontFolder = path.dirname(fontLoc);
if(fs.existsSync(fontLoc) && fs.statSync(fontLoc).size == 0){
fs.unlinkSync(fontLoc);
}
try{
fs.ensureDirSync(fontFolder);
}
catch(e){
console.log();
}
const fontUrl = fontsData.root + f;
const getFont = await req.getData<Buffer>(fontUrl, { binary: true });
if(getFont.ok && getFont.res){
fs.writeFileSync(fontLoc, getFont.res.body);
console.log(`[INFO] Downloaded: ${f}`);
}
else{
console.log(`[WARN] Failed to download: ${f}`);
}
}
}
console.log('[INFO] All required fonts downloaded!');
}
// auth method
async function doAuth(){
const iLogin = argv.username ?? await shlp.question('[Q] LOGIN/EMAIL');
const iPsswd = argv.password ?? await shlp.question('[Q] PASSWORD ');
const authData = new URLSearchParams({
'username': iLogin,
'password': iPsswd,
'grant_type': 'password',
'scope': 'offline_access'
}).toString();
const authReqOpts: reqModule.Params = {
method: 'POST',
headers: api.beta_authHeaderMob,
body: authData
};
const authReq = await req.getData(api.beta_auth, authReqOpts);
if(!authReq.ok || !authReq.res){
console.log('[ERROR] Authentication failed!');
return;
}
token = JSON.parse(authReq.res.body);
token.expires = new Date(Date.now() + token.expires_in);
yamlCfg.saveCRToken(token);
await getProfile();
console.log('[INFO] Your Country: %s', token.country);
}
async function getProfile(){
if(!token.access_token){
console.log('[ERROR] No access token!');
return;
}
const profileReqOptions = {
headers: {
Authorization: `Bearer ${token.access_token}`,
},
useProxy: true
};
const profileReq = await req.getData(api.beta_profile, profileReqOptions);
if(!profileReq.ok || !profileReq.res){
console.log('[ERROR] Get profile failed!');
return;
}
const profile = JSON.parse(profileReq.res.body);
console.log('[INFO] USER: %s (%s)', profile.username, profile.email);
}
// auth method
async function doAnonymousAuth(){
const authData = new URLSearchParams({
'grant_type': 'client_id',
'scope': 'offline_access',
}).toString();
const authReqOpts: reqModule.Params = {
method: 'POST',
headers: api.beta_authHeaderMob,
body: authData
};
const authReq = await req.getData(api.beta_auth, authReqOpts);
if(!authReq.ok || !authReq.res){
console.log('[ERROR] Authentication failed!');
return;
}
token = JSON.parse(authReq.res.body);
token.expires = new Date(Date.now() + token.expires_in);
yamlCfg.saveCRToken(token);
}
// refresh token
async function refreshToken(){
if(!token.access_token && !token.refresh_token || token.access_token && !token.refresh_token){
await doAnonymousAuth();
}
else{
if(Date.now() > new Date(token.expires).getTime()){
// return;
}
const authData = new URLSearchParams({
'refresh_token': token.refresh_token,
'grant_type': 'refresh_token',
'scope': 'offline_access'
}).toString();
const authReqOpts: reqModule.Params = {
method: 'POST',
headers: api.beta_authHeaderMob,
body: authData
};
const authReq = await req.getData(api.beta_auth, authReqOpts);
if(!authReq.ok || !authReq.res){
console.log('[ERROR] Authentication failed!');
return;
}
token = JSON.parse(authReq.res.body);
token.expires = new Date(Date.now() + token.expires_in);
yamlCfg.saveCRToken(token);
}
if(token.refresh_token){
await getProfile();
}
else{
console.log('[INFO] USER: Anonymous');
}
await getCMStoken();
}
async function getCMStoken(){
if(!token.access_token){
console.log('[ERROR] No access token!');
return;
}
const cmsTokenReqOpts = {
headers: {
Authorization: `Bearer ${token.access_token}`,
},
useProxy: true
};
const cmsTokenReq = await req.getData(api.beta_cmsToken, cmsTokenReqOpts);
if(!cmsTokenReq.ok || !cmsTokenReq.res){
console.log('[ERROR] Authentication CMS token failed!');
return;
}
cmsToken = JSON.parse(cmsTokenReq.res.body);
console.log('[INFO] Your Country: %s\n', cmsToken.cms?.bucket.split('/')[1]);
}
async function getCmsData(){
// check token
if(!cmsToken.cms){
console.log('[ERROR] Authentication required!');
return;
}
// opts
const indexReqOpts = [
api.beta_cms,
cmsToken.cms.bucket,
'/index?',
new URLSearchParams({
'Policy': cmsToken.cms.policy,
'Signature': cmsToken.cms.signature,
'Key-Pair-Id': cmsToken.cms.key_pair_id,
}),
].join('');
const indexReq = await req.getData(indexReqOpts);
if(!indexReq.ok || ! indexReq.res){
console.log('[ERROR] Get CMS index FAILED!');
return;
}
console.log(JSON.parse(indexReq.res.body));
}
async function doSearch(){
if(!token.access_token){
console.log('[ERROR] Authentication required!');
return;
}
const searchReqOpts = {
headers: {
Authorization: `Bearer ${token.access_token}`,
},
useProxy: true
};
const searchParams = new URLSearchParams({
q: argv.search as string,
n: '5',
start: argv.page ? `${(argv.page-1)*5}` : '0',
type: argv['search-type'],
locale: argv['search-locale'],
}).toString();
const searchReq = await req.getData(`${api.beta_search}?${searchParams}`, searchReqOpts);
if(!searchReq.ok || ! searchReq.res){
console.log('[ERROR] Search FAILED!');
return;
}
const searchResults = JSON.parse(searchReq.res.body) as CrunchySearch;
if(searchResults.total < 1){
console.log('[INFO] Nothing Found!');
return;
}
const searchTypesInfo = {
'top_results': 'Top results',
'series': 'Found series',
'movie_listing': 'Found movie lists',
'episode': 'Found episodes'
};
for(const search_item of searchResults.items){
console.log('[INFO] %s:', searchTypesInfo[search_item.type as keyof typeof searchTypesInfo]);
// calculate pages
const itemPad = parseInt(new URL(search_item.__href__, domain.api_beta).searchParams.get('start') || '');
const pageCur = itemPad > 0 ? Math.ceil(itemPad/5) + 1 : 1;
const pageMax = Math.ceil(search_item.total/5);
// pages per category
if(search_item.total < 1){
console.log(' [INFO] Nothing Found...');
}
if(search_item.total > 0){
if(pageCur > pageMax){
console.log(' [INFO] Last page is %s...', pageMax);
continue;
}
for(const item of search_item.items){
await parseObject(item);
}
console.log(` [INFO] Total results: ${search_item.total} (Page: ${pageCur}/${pageMax})`);
}
}
}
async function parseObject(item: ParseItem, pad?: number, getSeries?: boolean, getMovieListing?: boolean){
if(argv.debug){
console.log(item);
}
pad = pad ?? 2;
getSeries = getSeries === undefined ? true : getSeries;
getMovieListing = getMovieListing === undefined ? true : getMovieListing;
item.isSelected = item.isSelected === undefined ? false : item.isSelected;
if(!item.type) {
item.type = item.__class__;
}
const oTypes = {
'series': 'Z', // SRZ
'season': 'S', // VOL
'episode': 'E', // EPI
'movie_listing': 'F', // FLM
'movie': 'M', // MED
};
// check title
item.title = item.title != '' ? item.title : 'NO_TITLE';
// static data
const oMetadata = [],
oBooleans = [],
tMetadata = item.type + '_metadata',
iMetadata = (Object.prototype.hasOwnProperty.call(item, tMetadata) ? item[tMetadata as keyof ParseItem] : item) as Record<string, any>,
iTitle = [ item.title ];
// set object booleans
if(iMetadata.duration_ms){
oBooleans.push(shlp.formatTime(iMetadata.duration_ms/1000));
}
if(iMetadata.is_simulcast){
oBooleans.push('SIMULCAST');
}
if(iMetadata.is_mature){
oBooleans.push('MATURE');
}
if(iMetadata.is_subbed){
oBooleans.push('SUB');
}
if(iMetadata.is_dubbed){
oBooleans.push('DUB');
}
if(item.playback && item.type != 'movie_listing'){
oBooleans.push('STREAM');
}
// set object metadata
if(iMetadata.season_count){
oMetadata.push(`Seasons: ${iMetadata.season_count}`);
}
if(iMetadata.episode_count){
oMetadata.push(`EPs: ${iMetadata.episode_count}`);
}
if(item.season_number && !iMetadata.hide_season_title && !iMetadata.hide_season_number){
oMetadata.push(`Season: ${item.season_number}`);
}
if(item.type == 'episode'){
if(iMetadata.episode){
iTitle.unshift(iMetadata.episode);
}
if(!iMetadata.hide_season_title && iMetadata.season_title){
iTitle.unshift(iMetadata.season_title);
}
}
if(item.is_premium_only){
iTitle[0] = `☆ ${iTitle[0]}`;
}
// display metadata
if(item.hide_metadata){
iMetadata.hide_metadata = item.hide_metadata;
}
const showObjectMetadata = oMetadata.length > 0 && !iMetadata.hide_metadata ? true : false;
const showObjectBooleans = oBooleans.length > 0 && !iMetadata.hide_metadata ? true : false;
// make obj ids
const objects_ids = [];
objects_ids.push(oTypes[item.type as keyof typeof oTypes] + ':' + item.id);
if(item.seq_id){
objects_ids.unshift(item.seq_id);
}
if(item.f_num){
objects_ids.unshift(item.f_num);
}
if(item.s_num){
objects_ids.unshift(item.s_num);
}
if(item.external_id){
objects_ids.push(item.external_id);
}
if(item.ep_num){
objects_ids.push(item.ep_num);
}
// show entry
console.log(
'%s%s[%s] %s%s%s',
''.padStart(item.isSelected ? pad-1 : pad, ' '),
item.isSelected ? '✓' : '',
objects_ids.join('|'),
iTitle.join(' - '),
showObjectMetadata ? ` (${oMetadata.join(', ')})` : '',
showObjectBooleans ? ` [${oBooleans.join(', ')}]` : '',
);
if(item.last_public){
console.log(''.padStart(pad+1, ' '), '- Last updated:', item.last_public);
}
if(item.subtitle_locales){
iMetadata.subtitle_locales = item.subtitle_locales;
}
if(iMetadata.subtitle_locales && iMetadata.subtitle_locales.length > 0){
console.log(
'%s- Subtitles: %s',
''.padStart(pad + 2, ' '),
langsData.parseSubtitlesArray(iMetadata.subtitle_locales)
);
}
if(item.availability_notes && argv.shownotes){
console.log(
'%s- Availability notes: %s',
''.padStart(pad + 2, ' '),
item.availability_notes.replace(/\[[^\]]*\]?/gm, '')
);
}
if(item.type == 'series' && getSeries){
argv.series = item.id;
await getSeriesById(pad, true);
console.log();
}
if(item.type == 'movie_listing' && getMovieListing){
argv['movie-listing'] = item.id;
await getMovieListingById(pad+2);
console.log();
}
}
async function getSeriesById(pad?: number, hideSeriesTitle?: boolean){
// parse
pad = pad || 0;
hideSeriesTitle = hideSeriesTitle !== undefined ? hideSeriesTitle : false;
// check token
if(!cmsToken.cms){
console.log('[ERROR] Authentication required!');
return;
}
// opts
const seriesReqOpts = [
api.beta_cms,
cmsToken.cms.bucket,
'/series/',
argv.series,
'?',
new URLSearchParams({
'Policy': cmsToken.cms.policy,
'Signature': cmsToken.cms.signature,
'Key-Pair-Id': cmsToken.cms.key_pair_id,
}),
].join('');
const seriesSeasonListReqOpts = [
api.beta_cms,
cmsToken.cms.bucket,
'/seasons?',
new URLSearchParams({
'series_id': argv.series as string,
'Policy': cmsToken.cms.policy,
'Signature': cmsToken.cms.signature,
'Key-Pair-Id': cmsToken.cms.key_pair_id,
}),
].join('');
// reqs
if(!hideSeriesTitle){
const seriesReq = await req.getData(seriesReqOpts);
if(!seriesReq.ok || !seriesReq.res){
console.log('[ERROR] Series Request FAILED!');
return;
}
const seriesData = JSON.parse(seriesReq.res.body);
await parseObject(seriesData, pad, false);
}
// seasons list
const seriesSeasonListReq = await req.getData(seriesSeasonListReqOpts);
if(!seriesSeasonListReq.ok || !seriesSeasonListReq.res){
console.log('[ERROR] Series Request FAILED!');
return;
}
// parse data
const seasonsList = JSON.parse(seriesSeasonListReq.res.body) as SeriesSearch;
if(seasonsList.total < 1){
console.log('[INFO] Series is empty!');
return;
}
for(const item of seasonsList.items){
await parseObject(item, pad+2);
}
}
async function getMovieListingById(pad?: number){
pad = pad || 2;
if(!cmsToken.cms){
console.log('[ERROR] Authentication required!');
return;
}
const movieListingReqOpts = [
api.beta_cms,
cmsToken.cms.bucket,
'/movies?',
new URLSearchParams({
'movie_listing_id': argv['movie-listing'] as string,
'Policy': cmsToken.cms.policy,
'Signature': cmsToken.cms.signature,
'Key-Pair-Id': cmsToken.cms.key_pair_id,
}),
].join('');
const movieListingReq = await req.getData(movieListingReqOpts);
if(!movieListingReq.ok || !movieListingReq.res){
console.log('[ERROR] Movie Listing Request FAILED!');
return;
}
const movieListing = JSON.parse(movieListingReq.res.body);
if(movieListing.total < 1){
console.log('[INFO] Movie Listing is empty!');
return;
}
for(const item of movieListing.items){
parseObject(item, pad);
}
}
async function getNewlyAdded(){
if(!token.access_token){
console.log('[ERROR] Authentication required!');
return;
}
const newlyAddedReqOpts = {
headers: {
Authorization: `Bearer ${token.access_token}`,
},
useProxy: true
};
const newlyAddedParams = new URLSearchParams({
sort_by: 'newly_added',
n: '25',
start: (argv.page ? (argv.page-1)*25 : 0).toString(),
}).toString();
const newlyAddedReq = await req.getData(`${api.beta_browse}?${newlyAddedParams}`, newlyAddedReqOpts);
if(!newlyAddedReq.ok || !newlyAddedReq.res){
console.log('[ERROR] Get newly added FAILED!');
return;
}
const newlyAddedResults = JSON.parse(newlyAddedReq.res.body);
console.log('[INFO] Newly added:');
for(const i of newlyAddedResults.items){
await parseObject(i, 2);
}
// calculate pages
const itemPad = parseInt(new URL(newlyAddedResults.__href__, domain.api_beta).searchParams.get('start') as string);
const pageCur = itemPad > 0 ? Math.ceil(itemPad/5) + 1 : 1;
const pageMax = Math.ceil(newlyAddedResults.total/5);
console.log(` [INFO] Total results: ${newlyAddedResults.total} (Page: ${pageCur}/${pageMax})`);
}
async function getSeasonById(){
if(!cmsToken.cms){
console.log('[ERROR] Authentication required!');
return;
}
const showInfoReqOpts = [
api.beta_cms,
cmsToken.cms.bucket,
'/seasons/',
argv.s,
'?',
new URLSearchParams({
'Policy': cmsToken.cms.policy,
'Signature': cmsToken.cms.signature,
'Key-Pair-Id': cmsToken.cms.key_pair_id,
}),
].join('');
const showInfoReq = await req.getData(showInfoReqOpts);
if(!showInfoReq.ok || !showInfoReq.res){
console.log('[ERROR] Show Request FAILED!');
return;
}
const showInfo = JSON.parse(showInfoReq.res.body);
parseObject(showInfo, 0);
const reqEpsListOpts = [
api.beta_cms,
cmsToken.cms.bucket,
'/episodes?',
new URLSearchParams({
'season_id': argv.s as string,
'Policy': cmsToken.cms.policy,
'Signature': cmsToken.cms.signature,
'Key-Pair-Id': cmsToken.cms.key_pair_id,
}),
].join('');
const reqEpsList = await req.getData(reqEpsListOpts);
if(!reqEpsList.ok || !reqEpsList.res){
console.log('[ERROR] Episode List Request FAILED!');
return;
}
const episodeList = JSON.parse(reqEpsList.res.body) as CrunchyEpisodeList;
const epNumList: {
ep: number[],
sp: number
} = { ep: [], sp: 0 };
const epNumLen = argv.numbers;
if(episodeList.total < 1){
console.log(' [INFO] Season is empty!');
return;
}
const doEpsFilter = parseSelect(argv.e as string);
const selectedMedia: CrunchyEpMeta[] = [];
episodeList.items.forEach((item) => {
item.hide_season_title = true;
if(item.season_title == '' && item.series_title != ''){
item.season_title = item.series_title;
item.hide_season_title = false;
item.hide_season_number = true;
}
if(item.season_title == '' && item.series_title == ''){
item.season_title = 'NO_TITLE';
}
// set data
const epMeta: CrunchyEpMeta = {
data: [
{
mediaId: item.id
}
],
seasonTitle: item.season_title,
episodeNumber: item.episode,
episodeTitle: item.title,
seasonID: item.season_id,
season: item.season_number
};
if(item.playback){
epMeta.data[0].playback = item.playback;
}
// find episode numbers
const epNum = item.episode;
let isSpecial = false;
item.isSelected = false;
if(!epNum.match(/^\d+$/) || epNumList.ep.indexOf(parseInt(epNum, 10)) > -1){
isSpecial = true;
epNumList.sp++;
}
else{
epNumList.ep.push(parseInt(epNum, 10));
}
const selEpId = (
isSpecial
? 'S' + epNumList.sp.toString().padStart(epNumLen, '0')
: '' + parseInt(epNum, 10).toString().padStart(epNumLen, '0')
);
if((argv.but && item.playback && !doEpsFilter.isSelected([selEpId, item.id])) || (argv.all && item.playback) || (!argv.but && doEpsFilter.isSelected([selEpId, item.id]) && !item.isSelected && item.playback)){
selectedMedia.push(epMeta);
item.isSelected = true;
}
// show ep
item.seq_id = selEpId;
parseObject(item);
});
// display
if(selectedMedia.length < 1){
console.log('\n[INFO] Episodes not selected!\n');
return;
}
console.log();
let ok = true;
for(const media of selectedMedia){
const res = await downloadMediaList(media);
if (res === undefined) {
ok = false;
} else {
muxStreams(res.data, res.fileName);
downloaded({
service: 'crunchy',
type: 's'
}, argv.s as string, [media.episodeNumber]);
}
}
return ok;
}
async function getObjectById(returnData?: boolean){
if(!cmsToken.cms){
console.log('[ERROR] Authentication required!');
return;
}
const doEpsFilter = parseSelect(argv.e as string);
if(doEpsFilter.values.length < 1){
console.log('\n[INFO] Objects not selected!\n');
return;
}
// node crunchy-beta -e G6497Z43Y,GRZXCMN1W,G62PEZ2E6,G25FVGDEK,GZ7UVPVX5
console.log('[INFO] Requested object ID: %s', doEpsFilter.values.join(', '));
const objectReqOpts = [
api.beta_cms,
cmsToken.cms.bucket,
'/objects/',
doEpsFilter.values.join(','),
'?',
new URLSearchParams({
'Policy': cmsToken.cms.policy,
'Signature': cmsToken.cms.signature,
'Key-Pair-Id': cmsToken.cms.key_pair_id,
}),
].join('');
const objectReq = await req.getData(objectReqOpts);
if(!objectReq.ok || !objectReq.res){
console.log('[ERROR] Objects Request FAILED!');
if(objectReq.error && objectReq.error.res && objectReq.error.res.body){
const objectInfo = JSON.parse(objectReq.error.res.body as string);
console.log('[INFO] Body:', JSON.stringify(objectInfo, null, '\t'));
objectInfo.error = true;
return objectInfo;
}
return { error: true };
}
const objectInfo = JSON.parse(objectReq.res.body) as ObjectInfo;
if(returnData){
return objectInfo;
}
const selectedMedia = [];
for(const item of objectInfo.items){
if(item.type != 'episode' && item.type != 'movie'){
await parseObject(item, 2, true, false);
continue;
}
const epMeta: Partial<CrunchyEpMeta> = {};
switch (item.type) {
case 'episode':
item.s_num = 'S:' + item.episode_metadata.season_id;
epMeta.data = [
{
mediaId: 'E:'+ item.id
}
];
epMeta.seasonTitle = item.episode_metadata.season_title;
epMeta.episodeNumber = item.episode_metadata.episode;
epMeta.episodeTitle = item.title;
break;
case 'movie':
item.f_num = 'F:' + item.movie_metadata?.movie_listing_id;
epMeta.data = [
{
mediaId: 'M:'+ item.id
}
];
epMeta.seasonTitle = item.movie_metadata?.movie_listing_title;
epMeta.episodeNumber = 'Movie';
epMeta.episodeTitle = item.title;
break;
}
if(item.playback){
epMeta.data[0].playback = item.playback;
selectedMedia.push(epMeta);
item.isSelected = true;
}
await parseObject(item, 2);
}
console.log();
for(const media of selectedMedia){
const res = await downloadMediaList(media as CrunchyEpMeta);
if (res) {
await muxStreams(res.data, res.fileName);
}
}
}
async function muxStreams(data: DownloadedMedia[], output: string) {
if (argv.novids || data.filter(a => a.type === 'Video').length === 0)
return console.log('[INFO] Skip muxing since no vids are downloaded');
const merger = new Merger({
onlyVid: [],
skipSubMux: argv.skipSubMux,
onlyAudio: [],
output: `${output}.${argv.mp4 ? 'mp4' : 'mkv'}`,
subtitles: data.filter(a => a.type === 'Subtitle').map((a) : SubtitleInput => {
if (a.type === 'Video')
throw new Error('Never');
return {
file: a.path,
language: a.language
};
}),
simul: false,
fonts: Merger.makeFontsList(cfg.dir.fonts, data.filter(a => a.type === 'Subtitle') as sxItem[]),
videoAndAudio: data.filter(a => a.type === 'Video').map((a) : MergerInput => {
if (a.type === 'Subtitle')
throw new Error('Never');
return {
lang: a.lang,
path: a.path,
};
})
});
const bin = Merger.checkMerger(cfg.bin, argv.mp4, argv.forceMuxer);
// collect fonts info
// mergers
let isMuxed = false;
if (bin.MKVmerge) {
const command = merger.MkvMerge();
shlp.exec('mkvmerge', `"${bin.MKVmerge}"`, command);
isMuxed = true;
} else if (bin.FFmpeg) {
const command = merger.FFmpeg();
shlp.exec('ffmpeg', `"${bin.FFmpeg}"`, command);
isMuxed = true;
} else{
console.log('\n[INFO] Done!\n');
return;
}
if (isMuxed && !argv.nocleanup)
merger.cleanUp();
}
// MULTI DOWNLOADING
const downloadFromSeriesID = async () => {
const parsed = await parseSeriesById();
if (!parsed)
return;
const result = parseSeriesResult(parsed);
const episodes : Record<string, {
items: Item[],
langs: langsData.LanguageItem[]
}> = {};
for(const season of Object.keys(result) as unknown as number[]) {
for (const key of Object.keys(result[season])) {
const s = result[season][key];
(await getSeasonDataById(s))?.items.forEach(a => {
if (Object.prototype.hasOwnProperty.call(episodes, `S${a.season_number}E${a.episode_number || a.episode}`)) {
const item = episodes[`S${a.season_number}E${a.episode_number || a.episode}`];
item.items.push(a);
item.langs.push(langsData.languages.find(a => a.code == key) as langsData.LanguageItem);
} else {
episodes[`S${a.season_number}E${a.episode_number || a.episode}`] = {
items: [a],
langs: [langsData.languages.find(a => a.code == key) as langsData.LanguageItem]
};
}
});
}
}
const itemIndexes = {
sp: 1,
no: 1
};
for (const key of Object.keys(episodes)) {
const item = episodes[key];
const isSpecial = !item.items[0].episode.match(/^\d+$/);
episodes[`${isSpecial ? 'S' : 'E'}${itemIndexes[isSpecial ? 'sp' : 'no']}`] = item;
if (isSpecial)
itemIndexes.sp++;
else
itemIndexes.no++;
delete episodes[key];
}
for (const key of Object.keys(episodes)) {
const item = episodes[key];
console.log(`[${key}] ${
item.items.find(a => !a.season_title.match(/\(\w+ Dub\)/))?.season_title ?? item.items[0].season_title.replace(/\(\w+ Dub\)/g, '').trimEnd()
} - Season ${item.items[0].season_number} - ${item.items[0].title} [${
item.items.map((a, index) => {
return `${a.is_premium_only ? '☆ ' : ''}${item.langs[index].name}`;
}).join(', ')
}]`);
}
console.log();
console.log('-'.repeat(30));
console.log();
const selected = itemSelectMultiDub(episodes);
for (const key of Object.keys(selected)) {
const item = selected[key];
console.log(`[S${item.season}E${item.episodeNumber}] - ${item.episodeTitle} [${
item.data.map(a => {
return `✓ ${a.lang?.name || 'Unknown Language'}`;
}).join(', ')
}]`);
}
for (const key of Object.keys(selected)) {
const item = selected[key];
console.log(item);
const res = await downloadMediaList(item);
if (!res)
return;
downloaded({
service: 'crunchy',
type: 'srz'
}, argv.series as string, [item.episodeNumber]);
muxStreams(res.data, res.fileName);
}
return true;
};
const itemSelectMultiDub = (eps: Record<string, {
items: Item[],
langs: langsData.LanguageItem[]
}>) => {
const doEpsFilter = parseSelect(argv.e as string);
const ret: Record<string, CrunchyEpMeta> = {};
for (const key of Object.keys(eps)) {
const itemE = eps[key];
itemE.items.forEach((item, index) => {
if (!argv.dubLang.includes(itemE.langs[index].code))
return;
item.hide_season_title = true;
if(item.season_title == '' && item.series_title != ''){
item.season_title = item.series_title;
item.hide_season_title = false;
item.hide_season_number = true;
}
if(item.season_title == '' && item.series_title == ''){
item.season_title = 'NO_TITLE';
}
// set data
const epMeta: CrunchyEpMeta = {
data: [
{
mediaId: item.id
}
],
seasonTitle: itemE.items.find(a => !a.season_title.match(/\(\w+ Dub\)/))?.season_title ?? itemE.items[0].season_title.replace(/\(\w+ Dub\)/g, '').trimEnd(),
episodeNumber: item.episode,
episodeTitle: item.title,
seasonID: item.season_id,
season: item.season_number
};
if(item.playback){
epMeta.data[0].playback = item.playback;
}
const epNum = key.startsWith('E') ? key.slice(1) : key;
// find episode numbers