-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathcreateTorrent.js
More file actions
70 lines (62 loc) · 2.28 KB
/
Copy pathcreateTorrent.js
File metadata and controls
70 lines (62 loc) · 2.28 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
var url = require('url');
function buildTorrent(streamingServerURL, infoHash, fileIdx, sources) {
var query = Array.isArray(sources) && sources.length > 0 ?
'?' + new URLSearchParams(sources.map(function(source) {
return ['tr', source];
}))
:
'';
return {
url: url.resolve(streamingServerURL, '/' + encodeURIComponent(infoHash) + '/' + encodeURIComponent(fileIdx)) + query,
infoHash: infoHash,
fileIdx: fileIdx,
sources: sources
};
}
function createTorrent(streamingServerURL, infoHash, fileIdx, sources, seriesInfo) {
if ((!Array.isArray(sources) || sources.length === 0) && (fileIdx !== null && isFinite(fileIdx))) {
return Promise.resolve(buildTorrent(streamingServerURL, infoHash, fileIdx, sources));
}
var body = {
torrent: {
infoHash: infoHash,
}
};
if (Array.isArray(sources) && sources.length > 0) {
body.peerSearch = {
sources: ['dht:' + infoHash].concat(sources).filter(function(source, index, sources) {
return sources.indexOf(source) === index;
}),
min: 40,
max: 200
};
}
if (fileIdx === null || !isFinite(fileIdx)) {
body.guessFileIdx = {};
if (seriesInfo) {
if (seriesInfo.season !== null && isFinite(seriesInfo.season)) {
body.guessFileIdx.season = seriesInfo.season;
}
if (seriesInfo.episode !== null && isFinite(seriesInfo.episode)) {
body.guessFileIdx.episode = seriesInfo.episode;
}
}
} else {
body.guessFileIdx = false;
}
return fetch(url.resolve(streamingServerURL, '/' + encodeURIComponent(infoHash) + '/create'), {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(body)
}).then(function(resp) {
if (resp.ok) {
return resp.json();
}
throw new Error(resp.status + ' (' + resp.statusText + ')');
}).then(function(resp) {
return buildTorrent(streamingServerURL, infoHash, body.guessFileIdx ? resp.guessedFileIdx : fileIdx, body.peerSearch ? body.peerSearch.sources : []);
});
}
module.exports = createTorrent;