-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathloadDHT.js
More file actions
executable file
·76 lines (64 loc) · 2.11 KB
/
Copy pathloadDHT.js
File metadata and controls
executable file
·76 lines (64 loc) · 2.11 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
'use strict';
const config = require('./config/database');
const Promise = require('bluebird');
const Aria2 = require('aria2');
const fs = require('fs');
const magnet = require('magnet-uri');
const redis = require('redis');
Promise.promisifyAll(redis.RedisClient.prototype);
const client1 = redis.createClient(config.redis.port, config.redis.host,
config.redis.options);
const client2 = redis.createClient(config.redis.port, config.redis.host,
config.redis.options);
const bunyan = require('bunyan');
const logger = bunyan.createLogger({ name: 'loader' });
const MAGNET_TEMPLATE =
magnet.encode({ xt: 'urn:btih:{DHTHASH}', tr: config.trackers })
const aria2 = new Aria2(config.aria2);
const aria2Options =
{
'bt-metadata-only': 'true',
'bt-save-metadata': 'true',
'follow-torrent': 'false',
'seed-time': 0
}
client1.on('subscribe', (channel, count) => {
logger.info(`Subscribed : ${channel}`);
})
client1.on('message', (channel, message) => {
let magnetLink = MAGNET_TEMPLATE;
return Promise.resolve(message)
.then(hash => {
return new Promise((resolve, reject) => {
return client2.get(hash, (err, reply) => {
if (err) reject(err);
if (reply) reject(`${hash} already present`);
return client2.setex(hash, 60, "OK", () => {
resolve(hash)
})
})
})
})
.then(hash => {
return new Promise((resolve, reject) => {
if (!hash)
reject('No torrent in queue');
const filename =
`${__dirname}/torrent/${hash.toString().toUpperCase()}.torrent`;
magnetLink = MAGNET_TEMPLATE.replace(
'{DHTHASH}', hash.toString().toUpperCase());
if (fs.existsSync(filename)) {
reject(`File ${filename} already exists`);
}
resolve(magnetLink)
});
})
.then(() => aria2.open())
.then(() => aria2.getVersion())
.then(() => aria2.addUri([magnetLink], aria2Options))
.then(res => Promise.resolve(
logger.info(`Added : ${magnetLink} => ${res}`)))
.then(() => aria2.close())
.catch((err) => logger.error(err));
});
client1.subscribe('DHTS');