-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
executable file
·100 lines (92 loc) · 3.04 KB
/
index.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
'use strict';
let fs = require('fs');
let mguri = require('magnet-uri');
let request = require('request');
let zlib = require('zlib');
let servUrl = [
function(hash) {
return 'http://bt.box.n0808.com/' + hash.slice(0, 2) + '/' + hash.slice(-2) + '/' + hash + '.torrent';
},
function(hash) {
return 'https://torrage.com/torrent/' + hash + '.torrent';
},
function(hash) {
return 'http://torcache.net/torrent/' + hash + '.torrent';
}
//http://btcache.me/torrent/013060CD7E3C6CD61A2CC983F1714C9359928EFE
];
function parseInfoHash(uri) {
let uriObj = mguri.decode(uri);
let hash = uriObj.infoHash || uri;
if (/^[A-Za-z0-9]{40}$/.test(hash)) {
return hash.toUpperCase();
}
}
function getTorrent(url, hash, cb) {
console.log('Get torrent from:', url);
let options = {
url: url,
headers: {
'User-Agent': 'Node.js/12.0 io.js/2.0',
'Accept-Encoding': 'gzip,deflate'
}
};
request.get(options)
.on('error', function(err) {
cb(err);
})
.on('response', function(response) {
if (response.statusCode === 200) {
if (response.headers['content-type'] === 'application/octet-stream' ||
response.headers['content-type'] === 'application/x-bittorrent') {
let filename = hash + '.torrent';
let dest;
switch (response.headers['content-encoding']) {
case 'gzip':
case 'deflate':
dest = response.pipe(zlib.createUnzip()).on('error', function(err) {
cb(err);
})
.pipe(fs.createWriteStream(filename));
break;
default:
dest = response.pipe(fs.createWriteStream(filename));
break;
}
dest.on('finish', function() {
cb(null, filename);
})
.on('error', function(err) {
cb(err);
});
} else {
cb('Invalid content type: ' + response.headers['content-type']);
}
} else {
cb('Error response: ' + response.statusCode);
}
});
}
module.exports = function(uri, cb) {
let hash = parseInfoHash(uri);
if (!hash) {
process.nextTick(cb, 'Invalid magnet uri or info hash.');
return;
}
let servIdx = 0;
let getNext = function() {
if (servIdx !== servUrl.length) {
getTorrent(servUrl[servIdx++](hash), hash, function(err, filename) {
if (err) {
console.log(err);
getNext();
} else {
cb(null, filename);
}
});
} else {
process.nextTick(cb, 'All services tried.');
}
};
getNext();
};