-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtvgeek.js
721 lines (635 loc) · 21.7 KB
/
tvgeek.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
// Generated by CoffeeScript 2.3.1
(function() {
//!/usr/bin/env coffee
var App, Async, CLI, CLIColor, Config, File, FileSystem, HTTP, LibXML, Log, Path, PushoverAPI, Request, SizeFormatter, TheTVDBAPI, app, log, options, sprintf;
FileSystem = require('fs');
Path = require('path');
HTTP = require('http');
sprintf = require('sprintf').sprintf;
LibXML = require('libxmljs');
Async = require('async');
CLIColor = require('cli-color');
CLI = require('commander');
Request = require('request');
options = {};
Log = (function() {
var LEVELS;
class Log {
static StdErr() {
return new Log(process.stderr);
}
constructor(stream) {
var level;
this.stream = stream;
this.colored = true;
this.timestamp = false;
this.level = 0;
this.buffer = '';
this.paused = false;
for (level in LEVELS) {
((level) => {
return this[level] = (message, ...parameters) => {
return this.log(level, message, ...parameters);
};
})(level);
}
}
colorize(string, ...colors) {
var chain, color, i, len;
if (!this.colored || (colors == null) || colors.length === 0) {
return string;
}
chain = CLIColor;
for (i = 0, len = colors.length; i < len; i++) {
color = colors[i];
chain = chain[color];
}
return chain(string);
}
log(level, message, ...parameters) {
var line;
if (!(LEVELS[level].level >= this.level)) {
return;
}
line = '';
if (this.timestamp) {
line += this.colorize('[' + new Date() + '] ', 'blackBright');
}
line += this.colorize('[' + level.toUpperCase() + ']', ...LEVELS[level].colors);
line += ' ' + this.colorize(sprintf(message, ...parameters), ...LEVELS[level].textColors);
return this.write(line + "\n");
}
write(message) {
if (this.paused) {
return this.buffer += message;
} else {
return this.stream.write(message, 'utf8');
}
}
pause() {
return this.paused = true;
}
resume() {
this.paused = false;
this.write(this.buffer);
return this.buffer = '';
}
};
LEVELS = {
debug: {
level: 0,
colors: ['blue'],
textColors: ['blackBright']
},
info: {
level: 1,
colors: ['cyan'],
textColors: []
},
warn: {
level: 2,
colors: ['black', 'bgYellow'],
textColors: ['yellow']
},
error: {
level: 3,
colors: ['red'],
textColors: ['red']
},
fatal: {
level: 4,
colors: ['white', 'bgRedBright'],
textColors: ['red']
}
};
return Log;
}).call(this);
log = Log.StdErr();
Config = (function() {
var DEFAULTS;
class Config {
constructor(file1) {
this.file = file1;
}
read(next) {
return FileSystem.readFile(this.file, (error, data) => {
if (error != null) {
return next(error);
} else {
this.load(JSON.parse(data.toString()));
return next();
}
});
}
load(config) {
var key;
this.config = DEFAULTS;
for (key in config) {
if (key in DEFAULTS) {
this.config[key] = config[key];
} else {
log.warn('Unknown option "%s" in configuration file', key);
}
}
return this.config.considerExtensions = this.config.considerExtensions.map(function(extension) {
return '.' + extension;
});
}
get() {
return this.config;
}
};
DEFAULTS = {
inbox: null,
library: null,
structure: '%show_sortable%/Season %season%/%show% S%season_00%E%episode_00% %title%',
policy: 'replaceWhenBigger',
considerExtensions: ["mp4", "mkv", "avi", "mov"],
deleteExtensions: [],
pushoverAPIToken: null,
pushoverUserKey: null
};
return Config;
}).call(this);
PushoverAPI = class PushoverAPI {
constructor(appToken, userKey) {
this.sendPushNotification = this.sendPushNotification.bind(this);
this.appToken = appToken;
this.userKey = userKey;
}
sendPushNotification(title, message, next) {
var formData;
formData = {
token: this.appToken,
user: this.userKey,
title: title,
message: message
};
return Request({
method: 'POST',
url: 'https://api.pushover.net/1/messages.json',
formData: formData,
form: true
}, (error, response, data) => {
console.log(data);
return next(error);
});
}
};
TheTVDBAPI = (function() {
var API_KEY, BASE;
class TheTVDBAPI {
requestXML(url, next) {
return Request({
method: "GET",
url: url
}, (error, response, data) => {
var apiError, parserError, xml;
if (error != null) {
return next(error);
} else {
try {
xml = LibXML.parseXmlString(data);
} catch (error1) {
parserError = error1;
return next(new Error("XML parser error: " + parserError + "\nXML:\n" + data));
}
apiError = xml.get('/Data/Error');
if (apiError != null) {
return next(new Error("TVDB API Error: " + apiError.toString()));
} else {
return next(null, xml);
}
}
});
}
show(name, next) {
return this.requestXML(`${BASE}/api/GetSeries.php?seriesname=` + encodeURIComponent(name), (error, xml) => {
var get, i, len, node, ref, shows;
if (error != null) {
return next(error);
} else {
shows = [];
ref = xml.find('/Data/Series');
for (i = 0, len = ref.length; i < len; i++) {
node = ref[i];
get = function(path) {
var subnode;
subnode = node.get(path);
if (subnode != null) {
return subnode.text();
} else {
return null;
}
};
shows.push({
id: get('seriesid'),
language: get('language'),
name: get('SeriesName'),
since: get('FirstAired')
});
}
return next(null, shows);
}
});
}
episodeByAirdate(showID, airdate, next) {
airdate = sprintf('%04f-%02f-%02f', airdate.getFullYear(), airdate.getMonth() + 1, airdate.getDate());
return this.episodeByURL(`${BASE}/api/GetEpisodeByAirDate.php?apikey=${API_KEY}&seriesid=${showID}&airdate=${airdate}`, next);
}
episodeBySeasonAndEpisode(showID, season, episode, next) {
return this.episodeByURL(`${BASE}/api/${API_KEY}/series/${showID}/default/${season}/${episode}/en.xml`, next);
}
episodeByURL(url, next) {
return this.requestXML(url, (error, xml) => {
var episode, get;
if (error != null) {
return next(error);
} else {
get = function(key) {
var node;
node = xml.get('/Data/Episode/' + key);
if (node != null) {
return node.text();
} else {
return null;
}
};
episode = {
id: get('id'),
airdate: get('FirstAired'),
title: get('EpisodeName'),
season: get('SeasonNumber'),
episode: get('EpisodeNumber'),
director: get('Director')
};
return next(null, episode);
}
});
}
};
API_KEY = '5EFCC7790F190138';
BASE = 'http://thetvdb.com';
return TheTVDBAPI;
}).call(this);
SizeFormatter = (function() {
var UNITS;
class SizeFormatter {
static Format(bytes) {
var factor, unit;
factor = 1;
unit = 0;
while ((factor * 1024) < bytes) {
factor *= 1024;
unit++;
}
return (Math.round((bytes / factor) * 100) / 100) + ' ' + UNITS[unit];
}
};
UNITS = ['bytes', 'KiB', 'MiB', 'GiB', 'PiB'];
return SizeFormatter;
}).call(this);
File = (function() {
var AIRDATE_RE, DELIMITERS, SEASON_EPISODE_RE, TVDB, sortable;
class File {
constructor(directory1, filename1) {
this.directory = directory1;
this.filename = filename1;
this.extension = Path.extname(this.filename);
this.name = Path.basename(this.filename, this.extension);
this.filepath = Path.join(this.directory, this.filename);
this.info = {};
}
match(next) {
log.info('Matching "%s"', this.filename);
this.nameNormalized = this.name.replace(DELIMITERS, ' ');
return Async.series([this.extract.bind(this), this.fetchShow.bind(this), this.fetchEpisode.bind(this)], (error) => {
if (error != null) {
log.error("%s: %s", this.filename, error);
}
return next(error);
});
}
extract(next) {
var i, len, method, ref;
ref = ['extractSeasonAndEpisode', 'extractAirdate'];
for (i = 0, len = ref.length; i < len; i++) {
method = ref[i];
if (this[method]()) {
return next();
}
}
return next(new Error(`Could not extract season/episode or airdate from '${this.nameNormalized}'`));
}
extractSeasonAndEpisode() {
var i, len, match, regexp;
log.debug('Extracting season/episode from "%s"', this.nameNormalized);
for (i = 0, len = SEASON_EPISODE_RE.length; i < len; i++) {
regexp = SEASON_EPISODE_RE[i];
match = regexp.exec(this.nameNormalized);
if (match != null) {
this.extracted = {
fetch: 'fetchEpisodeBySeasonAndEpisode',
show: match[1],
season: parseInt(match[2]),
episode: parseInt(match[3])
};
log.debug('Extracted -> "%s" S%02fE%02f', this.extracted.show, this.extracted.season, this.extracted.episode);
regexp.lastIndex = 0;
return true;
}
}
return false;
}
extractAirdate(next) {
var i, len, match, regexp;
log.debug('Extracting airdate from "%s"', this.nameNormalized);
for (i = 0, len = AIRDATE_RE.length; i < len; i++) {
regexp = AIRDATE_RE[i];
match = regexp.exec(this.nameNormalized);
if (match != null) {
this.extracted = {
fetch: 'fetchEpisodeByAirdate',
show: match[1],
airdate: new Date(match[2], parseInt(match[3]) - 1, match[4])
};
log.debug('Extracted -> "%s" airdate %s', this.extracted.show, this.extracted.airdate);
regexp.lastIndex = 0;
return true;
}
}
return false;
}
fetchShow(next) {
return TVDB.show(this.extracted.show, (error, shows) => {
if (error != null) {
return next(new Error("Failed to get show information: " + error));
} else {
if (shows.length === 1) {
return next(null, this.show = shows[0]);
} else if (shows.length === 0) {
return next(new Error(`Show named '${this.extracted.show}' not found`));
} else {
return next(null, this.show = shows[0]);
}
}
});
}
fetchEpisode(next) {
return this[this.extracted.fetch]((error, episode) => {
if (error != null) {
return next(new Error("Failed to get episode information: " + error));
} else {
return next(null, this.episode = episode);
}
});
}
fetchEpisodeBySeasonAndEpisode(next) {
return TVDB.episodeBySeasonAndEpisode(this.show.id, this.extracted.season, this.extracted.episode, next);
}
fetchEpisodeByAirdate(next) {
return TVDB.episodeByAirdate(this.show.id, this.extracted.airdate, next);
}
libraryPath(pattern) {
var escapeRegExp, key, path, placeholders, value;
path = pattern;
placeholders = {
show: this.show.name,
season: this.episode.season,
episode: this.episode.episode,
title: this.episode.title
};
for (key in placeholders) {
value = placeholders[key];
if (value == null) {
value = '';
}
value = value.toString().replace(/(\/|\\|:|;)/g, '');
placeholders[key] = value;
placeholders[key + '_sortable'] = sortable(value);
if (/^\d+$/.test(value)) {
placeholders[key + '_00'] = sprintf('%02f', parseInt(value));
}
}
escapeRegExp = function(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
};
for (key in placeholders) {
value = placeholders[key];
path = path.replace(new RegExp(escapeRegExp('%' + key + '%'), 'g'), value);
}
return path;
}
move(libraryDir, pattern, overwritePolicy, next) {
var basename, libraryDirectory, path;
path = this.libraryPath(pattern);
basename = Path.basename(path);
libraryDirectory = Path.join(libraryDir, Path.dirname(path));
return this.makeLibraryPath(libraryDir, Path.dirname(path), (error, existed) => {
if (error != null) {
return next(error);
} else {
return this.overwrite(libraryDirectory, basename, overwritePolicy, (fileExisted, move) => {
if (move) {
return this.moveTo(libraryDir, path, next);
} else {
return FileSystem.unlink(Path.join(this.directory, this.filename), (error) => {
return next(error, true);
});
}
});
}
});
}
overwrite(libraryDirectory, basename, overwritePolicy, next) {
return FileSystem.stat(this.filepath, (error, info) => {
this.info = info;
return FileSystem.readdir(libraryDirectory, (error, files) => {
return Async.eachSeries(files, (file, done) => {
var filename;
if (Path.basename(file, Path.extname(file)) === basename) {
filename = Path.join(libraryDirectory, file);
return FileSystem.stat(filename, (error, stat) => {
var overwrite;
if (error != null) {
error = new Error(`Could not get size of file ${filename} in library: ${error}`);
return done(error);
}
overwrite = false;
if (overwritePolicy === 'replaceWhenBigger') {
if (stat.size < this.info.size) {
log.warn("Smaller file '%s' in library will be replaced", file);
overwrite = true;
} else if (stat.size > this.info.size) {
log.warn("Bigger file '%s' (%s > %s) already in library", file, SizeFormatter.Format(stat.size), SizeFormatter.Format(this.info.size));
} else {
log.warn("File '%s' already in library", file);
}
} else if (overwritePolicy === 'always') {
log.warn("File '%s' in library will be replaced", file);
overwrite = true;
}
if (overwrite) {
return FileSystem.unlink(filename, (error) => {
if (error != null) {
log.error("Failed to remove existing file '%s' in library: %s", filename, error);
}
done(1);
return next(true, error == null);
});
} else {
done(1);
return next(true, false);
}
});
} else {
return done();
}
}, (error) => {
if (error == null) {
return next(false, true);
}
});
});
});
}
moveTo(library, path, next) {
var destination, origin;
origin = Path.join(this.directory, this.filename);
destination = Path.join(library, path + this.extension);
return FileSystem.rename(origin, destination, next);
}
makeLibraryPath(library, directory, next) {
return this.makeLibraryPathRecursive(library, '', directory.split(Path.sep), next);
}
makeLibraryPathRecursive(library, path, remaining, next) {
var directory, recurse;
directory = Path.join(library, path);
recurse = () => {
if (remaining.length > 0) {
return this.makeLibraryPathRecursive(library, Path.join(path, remaining.shift()), remaining, next);
} else {
return next();
}
};
return FileSystem.exists(directory, (exists) => {
if (!exists) {
log.debug('Creating directory "%s"', directory);
return FileSystem.mkdir(directory, (error) => {
if (error) {
return next(error);
} else {
return recurse();
}
});
} else {
return recurse();
}
});
}
toString() {
return sprintf('%s S%02fE%02f %s', this.show.name, parseInt(this.episode.season), parseInt(this.episode.episode), this.episode.title, SizeFormatter.Format(this.info.size));
}
};
// Extract <showName> <seasonNumber> <episodeNumber> from filename
SEASON_EPISODE_RE = [/^(.*) season\s*(\d+)\s*episode\s*(\d+)/gi, /^(.*) s(\d+)e(\d+)/gi, /^(.*?) (\d{1})(\d{2}) /gi, /^(.*?) (\d{1,2})x(\d{1,2})/gi];
// Extract <year> <month> <day> from filename
AIRDATE_RE = [/^(.*) (\d{4}) (\d{2}) (\d{2})/gi];
TVDB = new TheTVDBAPI();
DELIMITERS = /[\s,\.\-\+]+/g;
sortable = function(string) {
var i, len, prefix, ref, regexp;
ref = ['The', 'Der', 'Die', 'Das', 'Le', 'Les', 'La', 'Los'];
for (i = 0, len = ref.length; i < len; i++) {
prefix = ref[i];
regexp = new RegExp('^' + prefix + ' ', 'i');
if (regexp.test(string)) {
return string.replace(regexp, '') + ', ' + prefix;
}
}
return string;
};
return File;
}).call(this);
App = class App {
main() {
this.parseArguments();
if (!CLI.verbose) {
log.level = 1;
}
this.config = new Config(__dirname + '/config.json');
return this.config.read(() => {
this.config = this.config.get();
if ((this.config.pushoverAPIToken != null) && (this.config.pushoverUserKey != null)) {
this.pushoverAPI = new PushoverAPI(this.config.pushoverAPIToken, this.config.pushoverUserKey);
}
return this.processFiles(this.config.inbox);
});
}
parseArguments() {
return CLI.version('0.1').option('-n, --noninteractive', 'Don\'t ask anything').option('-v, --verbose', 'Log debug messages').parse(process.argv);
}
printHelp() {
return console.log(this.cli.toString());
}
processFiles(inbox) {
return FileSystem.readdir(inbox, (error, files) => {
var extension, file, i, len, results;
if (error != null) {
return log.error('Failed to enumerate files in inbox "%s": %s', inbox, error);
} else {
results = [];
for (i = 0, len = files.length; i < len; i++) {
file = files[i];
if (this.config.considerExtensions.indexOf(Path.extname(file)) >= 0) {
results.push(this.processFile(inbox, file));
} else {
results.push((function() {
var j, len1, ref, results1;
ref = this.config.deleteExtensions;
results1 = [];
for (j = 0, len1 = ref.length; j < len1; j++) {
extension = ref[j];
if (Path.extname(file) === '.' + extension) {
log.info("Deleting file '%s' from inbox", file);
results1.push(FileSystem.unlink(Path.join(inbox, file), (error) => {
if (error != null) {
return log.error("Failed to delete '%s' from inbox: %s", file, error);
}
}));
} else {
results1.push(void 0);
}
}
return results1;
}).call(this));
}
}
return results;
}
});
}
processFile(inbox, file) {
var item;
item = new File(inbox, file);
return item.match((error) => {
if (error == null) {
return item.move(this.config.library, this.config.structure, this.config.policy, (error) => {
if (error != null) {
log.error("Failed to move '%s' to library: %s", item.filename, error);
return;
}
log.info('-> %s', item.toString());
return this.pushoverAPI.sendPushNotification("New Episode", item.toString(), (error) => {
if (error != null) {
return log.error("Failed to send pushover notification for '%s': %s", item.filename, error);
}
});
});
}
});
}
};
app = new App();
app.main();
}).call(this);