-
Notifications
You must be signed in to change notification settings - Fork 2
/
TorrentLibrary.js
548 lines (500 loc) · 17.7 KB
/
TorrentLibrary.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
// JSDoc custom typedef
/**
* The result of parsing file name
* @typedef {Object} TorrentLibrary~TPN
* @see {@link https://github.com/clement-escolano/parse-torrent-title}
* @property {(string)} title - The file title
* @property {(number|undefined)} season - The season number
* @property {(number|undefined)} episode - The episode number
* @property {(number|undefined)} year - The year
* @property {(string|undefined)} resolution - The resolution
* @property {(string|undefined)} codec - The codec
* @property {(string|undefined)} audio - The audio
* @property {(string|undefined)} group - The group that releases this file
* @property {(string|undefined)} region - The region
* @property {(string|undefined)} container - The container
* @property {(string|undefined)} language - The file language
* @property {(boolean|undefined)} extended - extended ?
* @property {(boolean|undefined)} unrated - unrated ?
* @property {(boolean|undefined)} proper - proper ?
* @property {(boolean|undefined)} repack - repack ?
* @property {(boolean|undefined)} convert - convert ?
* @property {(boolean|undefined)} hardcoded - hardcoded ?
* @property {(boolean|undefined)} retail - retail ?
* @property {(boolean|undefined)} remastered - remastered ?
* @property {(string|undefined)} source - the source
*/
/**
* The extended TPN object
* @typedef {TorrentLibrary~TPN} TorrentLibrary~TPN_Extended
* @property {string} filePath - additionnal property useful for this library
*/
/**
* The variable where we store all kind of media files found in paths
* @typedef {Map.<string, {( Set<TorrentLibrary~TPN_Extended>| Map.<string,Set<TorrentLibrary~TPN_Extended>> )}>} TorrentLibrary~StoreVar
* @example
* // An example of the variable after the scan method
* [
* "MOVIES" : [
* {
* "year": 2014,
* "resolution": '1080p',
* "source": 'brrip',
* "codec": 'x264',
* "container": 'mkv',
* "title": 'Captain Russia The Summer Soldier',
* "filePath": "D:\somePath\Captain Russia The Summer Soldier (2014) 1080p BrRip x264.MKV"
* }
* ],
* "TV_SERIES" : [
* "The Blacklist" : [
* {
* "season": 4,
* "episode": 21,
* "source": "webrip",
* "codec": "xvid",
* "container": "avi",
* "language": "french"
* "filePath" : "D:\somePath\The.Blacklist.S04E21.FRENCH.WEBRip.XviD.avi"
* }
* ]
* ]
* ]
*/
/**
* module for exploring directories
* @see {@link https://nspragg.github.io/filehound/}
*/
import FileHound from 'filehound';
/**
* Access method from module fs (node) with constants
* @see {@link https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback}
* @see {@link https://nodejs.org/api/fs.html#fs_fs_constants_1}
*/
import {
access,
constants as FsConstants,
} from 'fs';
/**
* Basename and normalize methods from module path (node)
* @see {@link https://nodejs.org/api/path.html#path_path_basename_path_ext}
* @see {@link https://nodejs.org/api/path.html#path_path_normalize_path}
*/
import { basename, normalize } from 'path';
/**
* uniq and difference methods from Lodash
* @see {@link https://lodash.com/docs/4.17.4#uniq}
* @see {@link https://lodash.com/docs/4.17.4#difference}
* @see {@link https://lodash.com/docs/4.17.4#partition}
*/
import { uniq, difference, partition } from 'lodash';
/**
* A promise object provided by the bluebird promise library.
* @external Promise
* @see {@link http://bluebirdjs.com/docs/api-reference.html}
*/
import PromiseLib from 'bluebird';
/**
* List of video file extensions
* @see {@link https://github.com/sindresorhus/video-extensions}
*/
import videosExtension from 'video-extensions';
/**
* Parser for media files name
* @see {@link https://github.com/clement-escolano/parse-torrent-title}
*/
import { parse as nameParser } from 'parse-torrent-title';
import {
EventEmitter,
} from 'events';
// check if an object has these properties and they are not undefined
function checkProperties(obj, properties) {
return properties.every(x => x in obj && obj[x]);
}
// rejected promise when someone doesn't provide
function missingParam() {
return new PromiseLib(((resolve, reject) => {
reject(new Error('Missing parameter'));
}));
}
/**
* Bluebird seems to have an issue with fs.access - Workaround function
* @private
* @param {string} path a path
* @returns {Promise} an Promise object resolved or rejected
* @see {@link https://github.com/petkaantonov/bluebird/issues/1442}
*/
function promisifiedAccess(path) {
return new PromiseLib(((resolve, reject) => {
access(path, FsConstants.F_OK | FsConstants.R_OK, (err) => {
if (err) reject(err);
resolve();
});
}));
}
/**
* Class representing the TorrentLibrary
* @class
* @extends EventEmitter
* @see {@link https://nodejs.org/api/events.html#events_class_eventemitter } for further information.
*/
class TorrentLibrary extends EventEmitter {
/**
* constant for movie category
* @since 0.0.0
* @return {string} the movies constant
* @static
* @memberOf TorrentLibrary
*/
static get MOVIES_TYPE() {
return 'MOVIES';
}
/**
* constant for tv series category
* @return {string} tv series constant
* @since 0.0.0
* @static
* @memberOf TorrentLibrary
*/
static get TV_SERIES_TYPE() {
return 'TV_SERIES';
}
/**
* Create a TorrentLibrary
*/
constructor() {
super();
/**
* just an easy way to scan the current directory path, if not other paths provided
* @member {string}
* @default the directory from which you invoked the node command
*/
this.defaultPath = process.cwd();
/**
* the paths where we are looking the media files
* @member {String[]}
* @default []
* @example
* // after have added some paths ...
* [ "D:\somePath", "D:\anotherPath" ]
*/
this.paths = [];
/**
* The variable where we store all kind of media files found in paths
* @member {TorrentLibrary~StoreVar}
*/
this.stores = new Map([
[TorrentLibrary.MOVIES_TYPE, new Set()],
[TorrentLibrary.TV_SERIES_TYPE, new Map()],
]);
/**
* Mapping filepath => category
* @member {Map.<string,string>}
* @example
* { "D:\somePath\Captain Russia The Summer Soldier (2014) 1080p BrRip x264.MKV" => TorrentLibrary.MOVIES_TYPE }
*/
this.categoryForFile = new Map();
/**
* Private method for adding new files
* @private
* @returns {external:Promise} an resolved or reject promise
* @param {string[]} files An array of filePath
* @memberOf TorrentLibrary
*/
this.addNewFiles = function addNewFiles(files) {
const that = this;
return new PromiseLib((resolve, reject) => {
try {
// find the new files to be added
const alreadyFoundFiles = [...that.categoryForFile.keys()];
const newFiles = difference(files, alreadyFoundFiles);
// temp var for new files before adding them to stores var
const moviesSet = new Set();
const tvSeriesSet = new Set();
// get previous result of stores var
let newMovies = that.allMovies;
const newTvSeries = that.allTvSeries;
// process each file
for (const file of newFiles) {
// get data from nameParser lib
// what we need is only the basename, not the full path
const jsonFile = nameParser(basename(file));
// extend this object in order to be used by this library
Object.assign(jsonFile, { filePath: file });
// find out which type of this file
// if it has not undefined properties (season and episode) => TV_SERIES , otherwise MOVIE
const fileCategory =
(checkProperties(jsonFile, ['season', 'episode']))
? TorrentLibrary.TV_SERIES_TYPE : TorrentLibrary.MOVIES_TYPE;
// add it in found files
that.categoryForFile.set(file, fileCategory);
// also in temp var
if (fileCategory !== TorrentLibrary.TV_SERIES_TYPE) {
moviesSet.add(jsonFile);
} else {
tvSeriesSet.add(jsonFile);
}
}
// add the movies into newMovies
newMovies = new Set([...newMovies, ...moviesSet]);
// add the tv series into newTvSeries
// First step : find all the series not in newTvSeries and add them to newTvSeries
difference(
uniq(
[...tvSeriesSet].map(tvSeries => tvSeries.title),
),
...newTvSeries.keys(),
).forEach((tvSeriesToInsert) => {
newTvSeries.set(tvSeriesToInsert, new Set());
});
// Second step : add the new files into the correct tvSeries Set
uniq(
[...tvSeriesSet].map(tvSeries => tvSeries.title),
).forEach((tvSerie) => {
// get the current set for this tvSerie
const currentTvSerie = newTvSeries.get(tvSerie);
// find all the episodes in the new one for this serie
const episodes = [...tvSeriesSet]
.filter(episode => episode.title === tvSerie);
// add them and updates newTvSeries
newTvSeries.set(tvSerie, new Set([...currentTvSerie, ...episodes]));
});
// updates the stores var
that.stores.set(TorrentLibrary.MOVIES_TYPE, newMovies);
that.stores.set(TorrentLibrary.TV_SERIES_TYPE, newTvSeries);
resolve();
} catch (err) {
reject(err);
}
});
};
}
/**
* Provides the array of files extensions considered to be media extensions
* @return {string[]} array of files extensions
* @since 0.0.0
* @example
* // Returns [..., 'webm', 'wmv']
* TorrentLibrary.listVideosExtension()
* @static
* @memberOf TorrentLibrary
*/
static listVideosExtension() {
return videosExtension;
}
/**
* Add the path(s) to be analyzed by the library if they exist and are readable
* @param {...string} paths - A or more path(s)
* @instance
* @method
* @since 0.0.0
* @memberOf TorrentLibrary
* @example
* // return resolved Promise "All paths were added!"
* TorrentLibraryInstance.addNewPath("C:\Users\jy95\Desktop\New folder","C:\Users\jy95\Desktop\New folder2");
* @return {external:Promise} On success the promise will be resolved with "All paths were added!"<br>
* On error the promise will be rejected with an Error object "Missing parameter" if the argument is missing<br>
* or an Error object from fs <br>
*/
addNewPath(...paths) {
// the user should provide us at lest a path
if (paths.length === 0) { return missingParam(); }
const that = this;
return new PromiseLib(((resolve, reject) => {
PromiseLib.map(paths, path => promisifiedAccess(path)).then(() => {
// keep only unique paths
// use normalize for cross platform's code
that.paths = uniq([...that.paths, ...paths.map(normalize)]);
resolve('All paths were added!');
}).catch((e) => {
reject(e);
});
}));
}
/**
* Tell us if the user has provided us paths
* @instance
* @method
* @memberOf TorrentLibrary
* @since 0.0.0
* @returns {boolean} Has user provided us paths ?
* @example
* TorrentLibraryInstance.addNewPath("C:\Users\jy95\Desktop\New folder","C:\Users\jy95\Desktop\New folder2");
* TorrentLibraryInstance.hasPathsProvidedByUser() // TRUE
*/
hasPathsProvidedByUser() {
return this.paths.length === 0;
}
/**
* Scans the paths in search for new files to be added inside this lib
* @instance
* @method
* @memberOf TorrentLibrary
* @since 0.0.0
* @return {external:Promise} On success the promise will be resolved with "Scanning completed"<br>
* On error the promise will be rejected with an Error object from sub modules<br>
*/
scan() {
const foundFiles = FileHound.create()
.paths((this.paths.length === 0) ? this.defaultPath : this.paths)
.ext(videosExtension)
.find();
const that = this;
return new PromiseLib((resolve, reject) => {
foundFiles
.then(files => that.addNewFiles(files)).then(() => {
resolve('Scanning completed');
}).catch((err) => {
reject(err);
});
});
}
/**
* Removes files stored in this library
* @param {...string} files An array of filePath (for example the keys of allFilesWithCategory())
* @since 1.0.3
* @return {external:Promise} an resolved or rejected promise<br>
* On success, the resolve will contain an message and the removed filePaths<br>
* On error the promise will be rejected with an Error object from sub modules<br>
* @example
* // with multiples files
* TorrentLibraryInstance.removeOldFiles(
* "D:\somePath\Captain Russia The Summer Soldier (2014) 1080p BrRip x264.MKV",
* "D:\\workspaceNodeJs\\torrent-files-library\\test\\folder1\\The.Blacklist.S04E21.FRENCH.WEBRip.XviD.avi"
* )
*/
removeOldFiles(...files) {
const that = this;
return new PromiseLib((resolve, reject) => {
try {
// get the data to handle this case
// in the first group, we got all the tv series files and in the second, the movies
const processData = partition(files, file =>
that.categoryForFile.get(file) === TorrentLibrary.TV_SERIES_TYPE);
// for movies, just an easy removal
that.stores.set(TorrentLibrary.MOVIES_TYPE,
new Set(
[...that.allMovies]
.filter(movie => !(processData[1].includes(movie.filePath))),
),
);
// for the tv-series, a bit more complicated
// first step : find the unique tv series of these files
const tvSeriesShows = uniq(
processData[0]
.map(file => nameParser(basename(file)).title),
);
// second step : foreach each series in tvSeriesShows
const newTvSeriesMap = that.allTvSeries;
for (const serie of tvSeriesShows) {
// get the set for this serie
const filteredSet = new Set(
[...newTvSeriesMap.get(serie)]
.filter(episode =>
!(processData[0].includes(episode.filePath))),
);
// if the filtered set is empty => no more episodes for this series
if (filteredSet.size === 0) {
newTvSeriesMap.delete(serie);
} else newTvSeriesMap.set(serie, filteredSet);
}
// save the updated map
that.stores.set(TorrentLibrary.TV_SERIES_TYPE, newTvSeriesMap);
// remove the mapping
files.forEach((file) => {
that.categoryForFile.delete(file);
});
resolve({
message: 'The files have been deleted from the library',
files,
});
} catch (err) {
reject(err);
}
});
}
/**
* Getter for all found movies
* @instance
* @since 0.0.0
* @memberOf TorrentLibrary
* @type {Set.<TorrentLibrary~TPN_Extended>}
* @example
* // an JSON stringified example of this method
* [
* {
* "year":2012,
* "source":"dvdrip",
* "codec":"xvid",
* "group":"-www.zone-telechargement.ws.avi",
* "container":"avi",
* "language":"truefrench",
* "title":"Bad Ass",
* "filePath":"D:\\workspaceNodeJs\\torrent-files-library\\test\\folder1\\Bad.Ass.2012.LiMiTED.TRUEFRENCH.DVDRiP.XviD-www.zone-telechargement.ws.avi"
* }
* ]
*/
get allMovies() {
return this.stores.get(TorrentLibrary.MOVIES_TYPE);
}
/**
* Getter for all found tv-series
* @instance
* @since 0.0.0
* @memberOf TorrentLibrary
* @type {Map.<string, Set.<TorrentLibrary~TPN_Extended>>}
* @example
* // an JSON stringified example of this method
* {
* "The Blacklist":[
* {
* "season":4,
* "episode":21,
* "source":"webrip",
* "codec":"xvid",
* "container":"avi",
* "language":"french",
* "title":"The Blacklist",
* "filePath":"D:\\workspaceNodeJs\\torrent-files-library\\test\\folder1\\The.Blacklist.S04E21.FRENCH.WEBRip.XviD.avi"
* },
* {
* "season":4,
* "episode":14,
* "source":"webrip",
* "codec":"xvid",
* "container":"avi",
* "language":"french",
* "title":"The Blacklist",
* "filePath":"D:\\workspaceNodeJs\\torrent-files-library\\test\\folder2\\The.Blacklist.S04E14.FRENCH.WEBRip.XviD.avi"
* }
* ]
* }
*/
get allTvSeries() {
return this.stores.get(TorrentLibrary.TV_SERIES_TYPE);
}
/**
* Getter for the mapping between filepaths and category
* @type {Map.<string,string>}
* @instance
* @memberOf TorrentLibrary
* @since 0.0.0
* @example
* { "D:\somePath\Captain Russia The Summer Soldier (2014) 1080p BrRip x264.MKV" => TorrentLibrary.MOVIES_TYPE }
*/
get allFilesWithCategory() {
return this.categoryForFile;
}
toJSON() {
const tvSeries = this.allTvSeries;
return `{
"paths":${JSON.stringify([...this.paths])},
"allFilesWithCategory":${JSON.stringify([...this.allFilesWithCategory])},
"movies":${JSON.stringify([...this.allMovies])},
"tv-series":${JSON.stringify([...tvSeries].map(serie =>
// serie[0] contains the title and [1] the wrong JSON ; let fix it
[serie[0], [...tvSeries.get(serie[0])]]))}
}`;
}
}
export default TorrentLibrary;