diff options
-rw-r--r-- | lib/file.js | 24 | ||||
-rw-r--r-- | test/node/basic.js | 13 |
2 files changed, 30 insertions, 7 deletions
diff --git a/lib/file.js b/lib/file.js index 4d7d71a..2715fbb 100644 --- a/lib/file.js +++ b/lib/file.js @@ -36,18 +36,30 @@ class File extends EventEmitter { get downloaded () { if (!this._torrent.bitfield) return 0 - let downloaded = 0 - for (let index = this._startPiece; index <= this._endPiece; ++index) { - if (this._torrent.bitfield.get(index)) { + + const { pieces, bitfield, pieceLength } = this._torrent + const { _startPiece: start, _endPiece: end } = this + const piece = pieces[start] + + // Calculate first piece diffrently, it sometimes have a offset + let downloaded = bitfield.get(start) + ? pieceLength - this.offset + : Math.max(piece.length - piece.missing - this.offset, 0) + + for (let index = start + 1; index <= end; ++index) { + if (bitfield.get(index)) { // verified data - downloaded += (index === this._endPiece) ? this._torrent.lastPieceLength : this._torrent.pieceLength + downloaded += pieceLength } else { // "in progress" data - const piece = this._torrent.pieces[index] + const piece = pieces[index] downloaded += piece.length - piece.missing } } - return downloaded + + // We don't have a end-offset and one small file can fith in the middle + // of one chunk, so return this.length if it's oversized + return Math.min(downloaded, this.length) } get progress () { diff --git a/test/node/basic.js b/test/node/basic.js index 7559309..f01aeef 100644 --- a/test/node/basic.js +++ b/test/node/basic.js @@ -112,7 +112,7 @@ test('client.seed: filesystem path to folder with one file, string', function (t }) test('client.seed: filesystem path to folder with multiple files, string', function (t) { - t.plan(6) + t.plan(7) var client = new WebTorrent({ dht: false, tracker: false }) @@ -124,6 +124,17 @@ test('client.seed: filesystem path to folder with multiple files, string', funct t.equal(torrent.infoHash, fixtures.numbers.parsedTorrent.infoHash) t.equal(torrent.magnetURI, fixtures.numbers.magnetURI) + const downloaded = torrent.files.map(file => ({ + length: file.length, + downloaded: file.downloaded + })) + + t.deepEqual(downloaded, [ + { length: 1, downloaded: 1 }, + { length: 2, downloaded: 2 }, + { length: 3, downloaded: 3 } + ], 'expected downloaded to be calculated correctly') + client.remove(torrent, function (err) { t.error(err, 'torrent destroyed') }) t.equal(client.torrents.length, 0) |