forked from popcorn-time/popcornflix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.js
98 lines (79 loc) · 2.35 KB
/
storage.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
var partFile = require('part-file');
var piece = require('./piece');
var fs = require('fs');
var events = require('events');
module.exports = function(torrent, file, options)
{
/* TODO: modify this to be able to handle multiple files
* */
var storage = new events.EventEmitter();
var missing = [];
var start = (file.offset / torrent.pieceLength) | 0;
var end = ((file.offset + file.length + 1) / torrent.pieceLength) | 0;
var dest = partFile(options.destination, torrent.pieceLength, torrent.pieces.slice(start, end+1));
var lastFile = torrent.files[torrent.files.length-1];
var pieces = torrent.pieces.map(function(_, i) {
if (i < start) return;
if (i > end) return;
missing.push(i);
if (i === torrent.pieces.length-1) return piece(((lastFile.length + lastFile.offset) % torrent.pieceLength) || torrent.pieceLength);
return piece(torrent.pieceLength);
});
dest.on('readable', function(index) {
index += start;
var i = missing.indexOf(index);
pieces[index] = null;
if (i > -1) missing.splice(i, 1);
storage.emit('readable', index);
if (pieces.every(function(piece) { return !piece }))
storage.emit('finished');
});
/* Try to resume the download
* */
fs.exists(options.destination, function(exists)
{
if (!exists) return;
var i = start;
function verifyNext()
{
dest.verify(i, function(err, r) {
if (++i <= end) verifyNext();
});
}
verifyNext();
});
storage.missing = missing;
storage.filename = file.name;
storage.dest = dest;
storage.torrent = torrent;
storage.sizeof = function(index, offset) {
var p = pieces[index];
return p ? p.sizeof(offset) : 0;
};
storage.select = function(index, force) {
var p = pieces[index];
if (!p) return -1;
var i = p.select();
return i === -1 && force ? p.select(true) : i;
};
storage.deselect = function(index, offset) {
var p = pieces[index];
if (p) p.deselect(offset);
};
storage.write = function(index, offset, block) {
var p = pieces[index];
if (!p) return;
var buffer = p.write(offset, block);
if (!buffer) return;
dest.write(index - start, buffer, function(err) {
if (err) return p.reset();
});
};
storage.read = function(index, offset, length, callback) {
dest.read(index - start, function(err, buffer) {
if (err) return callback(err);
callback(null, buffer.slice(offset, offset+length));
});
};
return storage;
}