-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathloadTorrent.js
More file actions
executable file
·84 lines (70 loc) · 2.24 KB
/
loadTorrent.js
File metadata and controls
executable file
·84 lines (70 loc) · 2.24 KB
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
'use strict';
const config = require('./config/database');
const Promise = require('bluebird');
const mongoose = require('mongoose');
mongoose.Promise = Promise;
mongoose.connect(config.db.uri);
const fs = require('fs');
Promise.promisifyAll(fs);
const path = require('path');
const minimist = require('minimist');
const rt = require('read-torrent');
const Torrent = require('./models/Torrent.js');
const bunyan = require('bunyan');
const logger = bunyan.createLogger({
name: 'torrentLoader'
});
const chokidar = require('chokidar');
const glob = require('glob');
const TORRENT_PATH = `${__dirname}/torrent`;
const TORRENT_GLOB = `${TORRENT_PATH}/*.torrent`;
function loadTorrent(fsfile) {
logger.info(`File ${fsfile} treatment in progress...`);
return new Promise((resolve, reject) => {
rt(fsfile, (err, ftorrent) => {
if (err) {
reject(err)
}
resolve(ftorrent);
})
})
.then(ftorrent => [ftorrent, Torrent.findById(ftorrent.infoHash).exec()])
.spread((ftorrent, res) =>
(res) ? Promise.reject('TEXISTS') : Promise.resolve(ftorrent))
.then(ftorrent => {
return [
ftorrent,
new Torrent({
'_id': ftorrent.infoHash,
'title': ftorrent.name,
'details': ftorrent.announce,
'size': ftorrent.length,
'files': ftorrent.files.map(f => f.path),
'imported': new Date()
}).save()
]
})
.spread((ftorrent, res) => Promise.resolve(
logger.info(`File ${ftorrent.infoHash} added`)))
.catch(err => (err === 'TEXISTS') ? Promise.resolve(
logger.info(`File ${fsfile} already loaded`)) : Promise.reject(err))
.then(() => fs.unlinkAsync(fsfile))
.catch(err => Promise.reject(logger.error(err)))
}
const argv = minimist(process.argv.slice(2));
if (argv.f || argv.force) {
return glob(TORRENT_GLOB, {
silent: true,
absolute: false
}, (err, fsfiles) =>
Promise.all(fsfiles.map(fsfile => loadTorrent(fsfile))));
} else if (argv.w || argv.watch) {
const watcher = chokidar.watch(TORRENT_GLOB);
watcher.on('add', (fsfile) => loadTorrent(fsfile));
} else {
process.stdout.write(
`Usage :
+ Watch mode : loadTorrent --watch
+ Force load : loadTorrent --force`
);
}