-
Notifications
You must be signed in to change notification settings - Fork 3
/
MakeNFO.js
executable file
·1557 lines (1484 loc) · 42.6 KB
/
MakeNFO.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
// API keys and URL paths
var TVDB_API_KEY = "88445D4B8F5F27A3",
TMDB_API_KEY = "5261508c7eb4c0ea4a7c335c8d8e2074",
TVDB_API_PATH = "http://www.thetvdb.com/",
TMDB_API_PATH = "http://api.themoviedb.org/2.1/%method%/%lang%/%type%/%key%/%arg%",
LANGUAGE = "en";
// Load libraries
var http = require("http"),
fs = require("fs"),
readline = require('readline'),
path = require("path"),
child_process = require('child_process'),
querystring = require("querystring"),
request = require("request"),
mime = require("mime"),
nomnom = require("nomnom"),
xml2js = require("xml2js"),
gunzip = require('zlib').gunzip,
tmdb = require("./tmdb").init(TMDB_API_KEY);
//console.log(request);
var parser = new xml2js.Parser();
function setTitle(title){
if(opts && !opts.noInput){
if(!isWin){
process.stdout.write("\033]0;" + title + "\007");
}
}
}
process.on("exit", function(){
if(opts){
setTitle("");
}
});
// Helper functions for TMDB and TVDB
function TMDBRequest(method, arg, callback, i){
if(!i){
i = 0;
}
if(i > 3){
// Retry 3 times, then give up
errDie("TMDB is offline!");
}
var url = TMDB_API_PATH.replace("%method%", method).replace("%lang%", LANGUAGE).replace("%type%", "json").replace("%key%", TMDB_API_KEY).replace("%arg%", arg);
request({url: url}, function(error, response, body){
if(error){
return TMDBRequest(method, arg, callback, i+1);
}
try{
var out = JSON.parse(body);
callback(null, out);
}catch(e){
TMDBRequest(method, arg, callback, i+1);
}
});}
function TVDBStaticRequest(path, callback){
var url = TVDB_API_PATH + "data/" + path;
request({url: url}, function(error, response, body){
if(error){
callback(error, null);
}else{
function parse(err, body){
body = body.toString('utf-8');
parser.parseString(body, function(err, data){
callback(err, data);
});
}
var encoding = response.headers['content-encoding'];
if(encoding && encoding.indexOf('gzip') >= 0) {
gunzip(body, parse);
}else{
parse(null, body);
}
}
});
}
function TVDBDynamicRequest(inf, args, callback){
args.apikey = TVDB_API_KEY;
var url = TVDB_API_PATH + "api/" + inf + ".php?" + querystring.stringify(args);
request({url: url}, function(error, response, body){
if(error){
callback(error, null);
}else{
var encoding = response.headers['content-encoding'];
if(encoding && encoding.indexOf('gzip') >= 0) {
body = uncompress(body);
}
body = body.toString('utf-8');
parser.parseString(body, function(err, data){
callback(err, data);
});
}
});
}
// Detect Windows
var isWin = process.platform === 'win32';
// Detect OSX
var isMac = process.platform === 'darwin';
// Set some constants
var MOVIE = "M",
TV = "T",
ABSOLUTE = "A",
DATE = "D";
// Set up some reused regexes.
var TVTitleRegex = /(?:\s|-)(?:(?:S([0-9]{2,})E([0-9]{2,})\b)|(?:([0-9]+)x([0-9]{2,}))|(?:EP([0-9]{2,}))|([0-9]{3})|(?:([0-9]{4})(?: |-|\/)([0-9]{2})(?: |-|\/)([0-9]{2})))\b/i;
var MovieTitleRegex = /(?:\b-\b)|(?:\s(?:(?:(?:\(|\[)?([0-9]{4})(?:\)|\])?)|4K|2K|1080p|720p|480p|360p|SD|MKV|X264|H264|H\.264|XVID|AC3|AAC|MKV|MP4|AVI|BluRay|Blu-Ray|BRRIP|DVDRip|DVD|DVDR|DVD-R|R[1-9]|HDTV|HDRip|HDTVRip|DTVRip|DTV|TS|TSRip|CAM|CAMRip|ReadNFO|iNTERNAL))(?:\b)|\(|\[/i;
var RGRegex = /\b(IMMERSE|DIMENSION|LOL|mSD|ORENJI|DHD|ASAP|AFG|THORA|KILLERS|2HD|LMAO|LEGi0N|RiVER|DiVERSiTY|GECKOS|ROVERS|BARGE|CRiMSON|TASTETV|BiA|TLA|BBnRG|KYR|PTpOWeR|MRFIXIT|FRAGMENT|FILMHD|UNVEiL|BLOWME|RELOADED|initialanime|SONiDO|FiHTV|WAF|QCF|SYA|THC|C4TV|DEADPiXEL|KNiFESHARP|eXceSs|SKmbr|RiPRG|UNVEiL|W4F|DEPRiVED)\b/i;
process.title = "NFOMaker";
// Parse arguments with nomnom
var parsedOpts = nomnom
.script("makeNFO")
.colors()
.options({
path: {
position: 0,
help: "File to generate an NFO for.",
list: false,
required: true
},
output: {
position: 1,
help: 'File to save the NFO to. Default is the name of the input file with the extension replaced with "nfo". Set to "-" to write to stdout.',
list: false
},
noGuess: {
abbr: "N",
full: "no-guess",
flag: true,
help: "Don't try to guess; ask about everything."
},
noInput: {
abbr: "u",
full: "no-ui",
flag: true,
help: "Don't ask about things; bug out if something can't be guessed."
},
type: {
abbr: "t",
help: "Type of video (either Movie or TV).",
choices: ["TV", "Movie"],
required: false
},
name: {
abbr: "n",
help: "Name of the movie or TV show to search for."
},
year: {
abbr: "y",
help: "Original release year of the video."
},
source: {
abbr: "s",
help: "Source RG of the video (OPTIONAL). If specified, they will be credited."
},
user: {
abbr: "u",
help: "Username to add to the title (OPTIONAL).",
default: ""
},
id: {
abbr: "i",
help: "IMDB movie/series or TheTVDB series ID (including tt if it's an IMDB ID)."
},
episodeID: {
full: "episode-id",
abbr: "I",
help: "TheTVDB episode ID."
},
episode: {
abbr: "e",
help: "Episode to search for. Formats are: S01E01 and 1x01 for season/episode; EP001 and 001 for absolute numbering. 101 will NOT match S01E01."
},
snapshotCount: {
abbr: "c",
default: 4,
full: "snapshot-count",
help: "Number of snapshots to take of the video file (uploaded to Lookpic)."
},
signature: {
default: "",
help: "Signature to use at the end of the edit."
},
sourceMedia: {
full: "source-media",
help: "Source media type to show in the title (e.g. DVDRip, HDTVRip, WEB-DL).",
default: ""
},
maxCastMembers: {
full: "max-cast",
help: "Maximum number of cast members to show in the output (default 10; 0 removes cast section).",
default: 10
},
dvdSort: {
full: "dvd-order",
abbr: "d",
help: "Use DVD ordering instead of aired ordering for episode numbers on TVDB.",
flag: true
},
noFile: {
full: "no-file",
abbr: "x",
help: "Don't load from a file. Disable screenshots and mediainfo.",
flag: true
},
sceneTitle: {
full: "scene-title",
help: "Title to use in the output NFO (defaults to an auto-generated one)."
},
addInfo: {
full: "add-info",
abbr: "a",
help: "Add additional info to the final NFO (useful with -x)."
},
addShots: {
full: "shots",
abbr: "b",
help: "Add external screenshots (preformatted)."
},
addNote: {
full: "note",
abbr: "c",
help: "Add a note (greetz, etc...)"
}
})
.parse();
if(process.argv.indexOf("-") != -1){
parsedOpts.output = "-";
}
var presetOpts = {};
if(fs.existsSync("~/.mknfo_settings")){
try{
presetOpts = JSON.parse(fs.readFileSync("~/.mknfo_settings"));
}catch(e){
// gulp(e);
}
}
// Setup an object to store options and meta that have been parsed and checked
var opts = {
formats: {}
},
meta = {},
mediaInfo;
if(parsedOpts.sourceMedia){
opts.sourceMedia = parsedOpts.sourceMedia;
}
if(parsedOpts.signature){
opts.signature = parsedOpts.signature;
}else if(presetOpts.signature){
opts.signature = presetOpts.signature;
}else{
opts.signature = "";
}
// The path should always be right; it's required
opts.path = parsedOpts.path;
if(parsedOpts.noFile){
opts.noMediaInfo = true;
opts.snapshotCount = 0;
opts.sceneTitle = path.basename(opts.path, path.extname(opts.path));
}else if(!fs.existsSync(opts.path)){
// Bug out if the file doesn't exist
errorDie('The file "' + opts.path + '" doesn\'t exist!');
}else{
opts.snapshotCount = parsedOpts.snapshotCount;
opts.sceneTitle = parsedOpts.sceneTitle;
}
// Function to bug out in errors
function errorDie(message){
console.error(message);
process.exit(1);
}
// Set the output file to <mediafilename>.nfo if it's not given.
opts.output = parsedOpts.output || path.dirname(opts.path) + "/" + path.basename(opts.path, path.extname(opts.path)) + ".nfo";
// Set noInput
opts.noInput = parsedOpts.noInput;
if(opts.output == "-"){
// Override noInput if writing to stdout.
opts.noInput = true;
}
setTitle("NFOMaker");
// Get the file's basename, remove the extension, and replace "." with " "
var basename = path.basename(opts.path, path.extname(opts.path)).replace(/\./g, " ");
// Initiate readline interface (use stderr, as stdout may be used for output)
var rl = readline.createInterface(process.stdin, process.stderr, null);
// If close is called, clean up interfaces and exit with code 0.
function close(){
// These two lines together allow the program to terminate. Without
// them, it would run forever.
rl.close();
process.stdin.destroy();
if(opts.output != "-"){
outStream.end();
}
}
if(parsedOpts.episodeID){
// If a TVDB episode ID was provided, use it!
opts.type = TV;
opts.episodeID = parsedOpts.episodeID;
searchTVDB();
}else if(parsedOpts.id && parsedOpts.id.indexOf("tt") != 0){
// Series IDs are the next-best thing. Use them, then guess the episode number.
opts.type = TV;
opts.id = parsedOpts.id;
getEpisode();
}else if(parsedOpts.type){
// No TVDB ID, but at least we have a media type. Moving on!
if(parsedOpts.type.toLowerCase() == "movie"){
opts.type = MOVIE;
}else if(parsedOpts.type.toLowerCase() == "tv"){
opts.type = TV;
}else{
errorDie("Specify a valid media type, or leave it out!");
}
// If we have an IMDB ID, use it now.
if(parsedOpts.id && parsedOpts.id.indexOf("tt") == 0){
opts.id = parsedOpts.id;
if(opts.type == TV){
searchTVDB();
}else{
searchTMDB();
}
}else{
// Otherwise, guess/ask for the name.
getName();
}
}else{
// If the type isn't specified, guess with a regex; if that fails, ask the user.
if(parsedOpts.noGuess){
if(opts.noInput){
errorDie("Can't guess the media type, and input isn't allowed!");
}else{
var ask = function(){
rl.question("What type of media is the file? [TV or Movie]", function(type){
if(["tv", "movie"].indexOf(type.toLowerCase()) == -1){
console.error("Please answer either TV or Movie!");
ask();
}else{
if(type.toLowerCase() == "tv"){
opts.type = TV;
}else{
opts.type = MOVIE;
}
if(parsedOpts.id && parsedOpts.id.indexOf("tt") == 0){
if(opts.type == TV){
searchTVDB();
}else{
searchTMDB();
}
}
getName();
}
});
}
ask();
}
}else{
if(basename.search(TVTitleRegex) != -1){
opts.type = TV;
getName();
}else{
opts.type = MOVIE;
getName();
}
}
}
// Guess the name of a TV show or movie based on its filename (RISKY!).
// Return false if we can't guess.
function guessName(name, type){
if(type == TV){
// Match everything before the episode number
return basename.substring(0, basename.search(TVTitleRegex));
}else{
// Match everything before one of a set of red flags for movie titles. They're all good indicators, but it's not 100% accurate.
var index = basename.search(MovieTitleRegex);
if(index == -1){
// No indicators. We did our best, but it's time to ask the user.
return false;
}
return basename.substring(0, index);
}
}
// Guess or ask for the series/movie name
function getName(){
if(parsedOpts.name){
// Name was provided; move on!
opts.name = parsedOpts.name;
if(opts.type == TV){
getEpisode();
}else{
getYear();
}
}else{
// Name wasn't provided; Guess or ask.
var ask = function(){
rl.question("What is the name of the TV show or movie? ", function(name){
if(name.length == 0){
console.error("Please enter a name!");
ask();
}else{
opts.name = name;
if(opts.type == TV){
getEpisode();
}else{
getYear();
}
}
});
}
if(parsedOpts.noGuess){
// Guessing isn't allowed...
if(opts.noInput){
// You dumbass.
errorDie("Can't guess the media name, and input isn't allowed!");
}else{
// No guessing; ask the user.
ask();
}
}else{
// Take your best guess based on the name and the type.
var guess = guessName(basename, opts.type);
if(guess){
opts.name = guess;
if(opts.type == TV){
getEpisode();
}else{
getYear();
}
}else{
if(opts.noInput){
errorDie("Can't guess the media name, and input isn't allowed!");
}else{
// Ask the user if possible.
ask();
}
}
}
}
}
// Guess the release year (don't ask, as it's not that helpful)
function getYear(){
if(!parsedOpts.noGuess){
var match = basename.match(MovieTitleRegex);
if(match){
opts.year = match[1];
}
}
searchTMDB();
}
// Guess or ask for the episode and season numbers
function getEpisode(){
var ask = function(){
rl.question("What episode is the file? Formats are: S01E01 and 1x01 for season/episode; EP001 and 001 for absolute numbering. 101 will NOT match S01E01.", function(episode){
parseEpisode(episode);
});
}
var parseEpisode = function(string){
var matches = string.match(TVTitleRegex);
var numbers = [];
for(var i = 1; i < matches.length; i++){
if(matches[i]){
numbers.push(matches[i]);
}
}
if(numbers.length > 3){
errorDie("WTF is this? Episode number is badly mangled.");
}else if(numbers.length == 3){
opts.episode = numbers[0] + "/" + numbers[1] + "/" + numbers[2];
opts.season = DATE;
searchTVDB();
}else if(numbers.length == 2){
opts.season = parseInt(numbers[0], 10);
opts.episode = parseInt(numbers[1], 10);
searchTVDB();
}else if(numbers.length == 1){
opts.season = ABSOLUTE;
opts.episode = parseInt(numbers[0], 10);
searchTVDB();
}else{
if(opts.noInput){
errorDie("Can't parse episode and input isn't allowed!");
}else{
console.error("Please enter a valid episode number.");
ask();
}
}
}
if(parsedOpts.episode){
parseEpisode(" " + parsedOpts.episode);
}else if(parsedOpts.noGuess){
if(opts.noInput){
errorDie("Can't guess episode and input isn't allowed!");
}else{
ask();
}
}else{
parseEpisode(basename);
}
}
// Load a movie object from TMDB
function loadMovie(id){
var parseResponse = function(error, data){
if(error){
throw error;
}else if(!data){
errorDie(error + " " + data);
}else{
parseMovie(data[0]);
if(global.waitCalled){
formatOutput();
}
}
}
TMDBRequest("Movie.getInfo", id, parseResponse);
}
function parseMovie(movie){
meta.title = movie.name;
meta.imdb_url = "http://imdb.com/title/" + movie.imdb_id;
meta.plot = movie.overview;
meta.score = movie.rating;
meta.certification = movie.certification;
meta.runtime = movie.runtime;
meta.genres = movie.genres;
meta.year = ((typeof movie.released == "string") ? movie.released.split("-")[0] : "");
if(!meta.year){
meta.year = "";
}
meta.tagline = movie.tagline;
meta.budget = movie.budget;
meta.revenue = movie.revenue;
meta.people = movie.cast;
meta.studios = movie.studios;
meta.trailer = movie.trailer;
meta.homepage = movie.homepage;
for(var i = 0; i < movie.posters.length; i++){
if(movie.posters[i].image.type == "poster" && movie.posters[i].image.size == "mid"){
meta.poster = movie.posters[i].image.url;
break;
}
}
}
// Ask the user which of a list of movies the file contains.
function askWhichMovie(movies){
var str = "Search returned multiple movies:\n";
for(var i = 0; i < movies.length; i++){
str += "[" + i + "] " + movies[i].name + " (" + movies[i].released + "): " + movies[i].overview + "\n";
}
str += "Which one of the above movies is the file? [0]: ";
function ask(){
rl.question(str, function(str){
var num = parseInt(str, 10);
if(movies[num]){
loadMovie(movies[num].id);
}else{
loadMovie(movies[0].id);
}
});
}
ask();
}
function parseTVDBList(list){
if(!list || typeof list != "string"){
return "";
}
var arr = list.split("|");
arr = arr.splice(1, arr.length - 2);
return arr.join(", ");
}
function parseTVDBBanners(banners, season, callback){
if(typeof banners != "object"){
callback("");
return;
}
if(banners.BannerPath){
// Only one banner?
downloadAndReuploadImage("http://thetvdb.com/banners/" + banners.BannerPath, -1, callback);
return;
}
for(var i = 0; i < banners.length; i++){
if(banners[i].BannerType2 == "seasonwide" && banners[i].Season == season){
downloadAndReuploadImage("http://thetvdb.com/banners/" + banners[i].BannerPath, -1, callback);
return;
}
}
for(var i = 0; i < banners.length; i++){
if(banners[i].BannerType2 == "graphical"){
downloadAndReuploadImage("http://thetvdb.com/banners/" + banners[i].BannerPath, -1, callback);
return;
}
}
callback("");
}
function parseTVDBData(series, actors, banners, episode){
if(typeof series.Airs_DayOfWeek == "string"){
meta.airs = series.Airs_DayOfWeek + ((typeof series.Airs_Time == "string") ? (" at " + series.Airs_Time) : "");
}
meta.series_first_aired = series.FirstAired;
if(series.FirstAired && series.FirstAired.split){
meta.year = series.FirstAired.split("-")[0];
}
if(!meta.year){
meta.year = "";
}
meta.episode_first_aired = episode.FirstAired;
if(typeof episode.IMDB_ID == "string"){
meta.imdb_url = "http://www.imdb.com/title/" + episode.IMDB_ID + "/";
}
meta.tvdb_url = "http://thetvdb.com/?tab=episode&seriesid=" + episode.seriesid + "&seasonid=" + episode.seasonid + "&id=" + episode.id + "&lid=7";
if(typeof series.IMDB_ID == "string"){
meta.series_imdb_url = "http://www.imdb.com/title/" + series.IMDB_ID + "/";
}
meta.series_tvdb_url = "http://thetvdb.com/?tab=series&id=" + episode.seriesid + "&lid=7";
meta.network = series.Network;
meta.series_plot = series.Overview;
meta.episode_plot = episode.Overview;
meta.series_score = series.Rating;
meta.score = episode.Rating;
meta.certification = series.ContentRating;
if(episode.EpisodeNumber && typeof episode.EpisodeNumber !== "object" && episode.SeasonNumber !== ""){
if(episode.SeasonNumber == "0"){
meta.episode = "Special #" + episode.EpisodeNumber;
meta.aired_episode = "Special #" + episode.EpisodeNumber;
}else{
meta.episode = "S" + pad(episode.SeasonNumber, 2) + "E" + pad(episode.EpisodeNumber, 2);
meta.aired_episode = "S" + pad(episode.SeasonNumber, 2) + "E" + pad(episode.EpisodeNumber, 2);
}
}
if(episode.DVD_season !== "" && typeof episode.DVD_season !== "object" && episode.DVD_episodenumber){
if(episode.DVD_season === "0"){
if(!meta.episode || opts.DVDSort){
meta.episode = "Special #" + episode.DVD_episodenumber;
}
meta.dvd_episode = "Special #" + episode.DVD_episodenumber;
}else{
if(!meta.episode || opts.DVDSort){
meta.episode = "S" + pad(episode.DVD_season, 2) + "E" + pad(episode.DVD_episodenumber, 2);
}
meta.dvd_episode = "S" + pad(episode.DVD_season, 2) + "E" + pad(episode.DVD_episodenumber, 2);
}
}
meta.genres = parseTVDBList(series.Genre);
meta.runtime = series.Runtime;
meta.title = series.SeriesName;
meta.status = series.Status;
meta.guest_stars = parseTVDBList(episode.GuestStars);
meta.director = parseTVDBList(series.Director);
meta.writer = parseTVDBList(series.Writer);
meta.episode_name = episode.EpisodeName;
meta.people = actors;
parseTVDBBanners(banners, episode.SeasonNumber, function(poster){
meta.poster = poster;
if(global.waitCalled){
formatOutput();
}
});
}
function requestSeries(seriesID){
TVDBStaticRequest("/series/" + seriesID + "/" + LANGUAGE + ".xml", function(err, record){
if(err){
throw(err);
}
var series = record.Series;
if(opts.season == DATE){
TVDBDynamicRequest("GetEpisodeByAirDate", {airdate: opts.episode, seriesid: seriesID}, function(err, record){
if(err){
throw(err);
}
if(record.Error){
errorDie("No episode found for that airdate!");
}
TVDBStaticRequest("/episodes/" + record.Episode.id + "/" + LANGUAGE + ".xml", function(err, record){
if(err){
throw(err);
}
var episode = record.Episode;
TVDBStaticRequest("/series/" + seriesID + "/banners.xml", function(err, record){
if(err){
throw(err);
}
var banners = record.Banner;
TVDBStaticRequest("/series/" + seriesID + "/actors.xml", function(err, record){
if(err){
throw(err);
}
var actors = record.Actor;
parseTVDBData(series, actors, banners, episode);
});
});
});
});
}else{
// DECIDE ABSOLUTE OR NORMAL; DEFAULT OR DVD SORTING
var url;
if(opts.season == ABSOLUTE){
url = "/series/" + seriesID + "/absolute/" + opts.episode + "/" + LANGUAGE + ".xml";
}else{
url = "/series/" + seriesID + "/" + (parsedOpts.dvdSort ? "dvd" : "default") + "/" + opts.season + "/" + opts.episode + "/" + LANGUAGE + ".xml";
}
TVDBStaticRequest(url, function(err, record){
if(err){
throw(err);
}
if(record.body && record.body.h1 == "Not Found"){
errorDie("Episode not listed in TVDB!");
}
var episode = record.Episode;
TVDBStaticRequest("/series/" + seriesID + "/banners.xml", function(err, record){
if(err){
throw(err);
}
var banners = record.Banner;
TVDBStaticRequest("/series/" + seriesID + "/actors.xml", function(err, record){
if(err){
throw(err);
}
var actors = record.Actor;
parseTVDBData(series, actors, banners, episode);
});
});
});
}
});
}
function searchTVDB(){
// Load MediaInfo and take screenshots while other stuff happens
loadMediaInfo();
if(opts.id){
if(opts.id.indexOf("tt") == 0){
TVDBDynamicRequest("GetSeriesByRemoteID", {imdbid: opts.id}, function(err, record){
requestSeries(record.Series.seriesid);
});
}else{
requestSeries(opts.id);
}
}else if(opts.episodeID){
TVDBStaticRequest("/episodes/" + opts.episodeID + "/" + LANGUAGE + ".xml", function(err, record){
if(err){
throw(err);
}
var episode = record.Episode;
TVDBStaticRequest("/series/" + episode.seriesid + "/" + LANGUAGE + ".xml", function(err, record){
if(err){
throw(err);
}
var series = record.Series;
TVDBStaticRequest("/series/" + episode.seriesid + "/banners.xml", function(err, record){
if(err){
throw(err);
}
var banners = record.Banner;
TVDBStaticRequest("/series/" + episode.seriesid + "/actors.xml", function(err, record){
if(err){
throw(err);
}
var actors = record.Actor;
parseTVDBData(series, actors, banners, episode);
});
});
});
});
}else{
TVDBDynamicRequest("GetSeries", {seriesname: opts.name, language: LANGUAGE}, function(err, record){
if(err){
throw(err);
}
if(Array.isArray(record.Series)){
// If there are multiple TV matches, either guess or ask.
if(opts.noInput){
if(parsedOpts.noGuess){
// If no guessing, die
errorDie("No guessing allowed, and no input allowed!");
}else{
requestSeries(record.Series[0].seriesid);
}
}else{
askWhichShow(record.Series);
}
}else if(!record.Series){
errorDie("No such series!");
}else{
requestSeries(record.Series.seriesid);
}
});
}
}
// Ask which of an array of shows is correct.
function askWhichShow(shows){
shows = shows.splice(0, 5);
var str = "Search returned multiple shows; listing first " + shows.length + ":\n";
for(var i = 0; i < shows.length; i++){
str += "[" + i + "] " + shows[i].SeriesName + (shows[i].FirstAired ? " (" + shows[i].FirstAired + "):" : ":") + " " + shows[i].Overview + "\n";
}
str += "Which one of the above shows is correct? [0]: ";
function ask(){
rl.question(str, function(str){
var num = parseInt(str, 10);
if(shows[num]){
requestSeries(shows[num].id);
}else{
requestSeries(shows[0].id);
}
});
}
ask();
}
// Search TMDB for a movie
function searchTMDB(){
// Load MediaInfo and take screenshots while other stuff happens
loadMediaInfo();
var parseResponse = function(error, data){
if(error){
throw error;
}else if(!data){
errorDie(error + " " + data);
}else{
if(data.length == 0){
errorDie("No movies returned by TMDB!");
}else if(data.length == 1){
if(!data[0].id){
errorDie("No movies returned by TMDB!");
}
loadMovie(data[0].id);
}else{
if(opts.year){
var newList = [];
for(var i = 0; i < data.length; i++){
var movie = data[i];
if(!(typeof movie.released == "string") || movie.released.split("-")[0] == opts.year){
newList.push(movie);
}
}
if(newList.length == 1){
loadMovie(newList[0].id);
}else if(newList.length > 1){
data = newList;
}
}
// If there are multiple movie matches, either guess or ask.
if(opts.noInput){
if(parsedOpts.noGuess){
// If no guessing, die
errorDie("No guessing allowed, and no input allowed!");
}else{
loadMovie(data[0].id);
}
}else{
askWhichMovie(data);
}
}
}
}
if(opts.id){
TMDBRequest("Movie.imdbLookup", opts.id, parseResponse);
}else{
var name = opts.name.replace(/( |_)/g, "+");
TMDBRequest("Movie.search", name, parseResponse);
}
}
// Load the MediaInfo on a file
function loadMediaInfo(){
if(opts.noMediaInfo){
takeScreenshots();
return;
}
var mediaInfoPath = "mediainfo";
if(isWin){
mediaInfoPath = __dirname + "/deps/win32/mediainfo.exe";
}
if(isMac){
mediaInfoPath = __dirname + "/deps/darwin/mediainfo";
}
child_process.exec('"' + mediaInfoPath + '" --Output=XML "' + parsedOpts.path + '"', function(err, data){
if(err){
throw(err);
}else{
parser.parseString(data, function(err, out){
if(err){
throw(err);
}else{
var tracks = out.File.track;
for(var i = 0; i < tracks.length; i++){
tracks[i].type = tracks[i]["@"].type;
}
mediaInfo = out.File.track;
takeScreenshots();
}
});
}
});
}
function durationToSeconds(str){
var hms = str.match(/^(?:(\d+)h )?(\d+)mn?(?: (\d+)s)?$/);
var seconds = 0;
if(hms[1]){
seconds += parseInt(hms[1], 10)*60*60;
}
if(hms[2]){
seconds += parseInt(hms[2], 10)*60;
}
if(hms[3]){
seconds += parseInt(hms[3], 10);
}
return seconds;
}
function takeScreenshots(){
if(opts.snapshotCount > 0){
console.error("Taking snapshots...");
takeAndUploadScreenshots(opts.path, durationToSeconds(mediaInfo[0].Duration), false, parsedOpts.snapshotCount, function(URLs, times){
console.error("Finished taking screenshots.");
meta.screenshots = [];
for(var i = 0; i < URLs.length; i++){
meta.screenshots.push({
URL: URLs[i],
time: times[i]
});
}
waitThenFormatOutput();
}, function(number, total, url, time){
console.error("Uploaded screenshot " + number + "/" + total + " from timecode " + time + " to " + url);
});
}else{
console.error("Skipping snapshots...");
waitThenFormatOutput();
}
}
function guessMoreMeta(){
if(parsedOpts.noGuess){
return;
}
if(!opts.sourceMedia){
var match = basename.match(/\b((?:HDTV|HDRip|DTV|TV|PDTV|BluRay|BR|BD|DVD\d?|DVD-?R|R\d|CAM|TS|WEB(?:-?DL)?)(?:-?Rip)?)\b/i);
if(match){
opts.sourceMedia = match[0];
}else{
opts.sourceMedia = "";
}
}
}
function waitThenFormatOutput(){
if(meta.title){
// DB Search Finished
formatOutput();
}else{
global.waitCalled = true;
}
}
function getQuality(){
if(!mediaInfo){
return "";
}
var vertical, horizontal;
for(var i = 0; i < mediaInfo.length; i++){
var track = mediaInfo[i];
if(track.type != "Video"){
continue;