diff options
author | fisch0920 <fisch0920@gmail.com> | 2014-05-30 22:48:31 +0400 |
---|---|---|
committer | fisch0920 <fisch0920@gmail.com> | 2014-05-30 22:48:31 +0400 |
commit | 32bac0c2cd3a2b2af99c9caf90b0d68db0c1b42b (patch) | |
tree | 7c35cc83814c39bf835b348d47843df2e07c7615 /lib/fs_storage.js | |
parent | 809df8e56e9b2ff7f4032adfeec1c72350923b76 (diff) |
fs_storage changes for correctness and efficiency of initial piece verification for resuming torrent downloads
Diffstat (limited to 'lib/fs_storage.js')
-rw-r--r-- | lib/fs_storage.js | 35 |
1 files changed, 22 insertions, 13 deletions
diff --git a/lib/fs_storage.js b/lib/fs_storage.js index 0205ad7..ae0232e 100644 --- a/lib/fs_storage.js +++ b/lib/fs_storage.js @@ -12,6 +12,7 @@ var rimraf = require('rimraf') var thunky = require('thunky') var TMP = fs.existsSync('/tmp') ? '/tmp' : os.tmpDir() +var noop = function () {} inherits(FSStorage, Storage) @@ -35,19 +36,19 @@ function FSStorage (parsedTorrent, opts) { } self.path = opts.path - self.piecesMap = [] + + self.nonExistentError = new Error("Cannot read from non-existent file") + self.files.forEach(function (file) { var fileStart = file.offset var fileEnd = fileStart + file.length - var firstPiece = file.pieces[0].index - var lastPiece = file.pieces[file.pieces.length - 1].index var pieceLength = file.pieceLength + var filePath = path.join(self.path, file.path) - var open = thunky(function (cb) { - var filePath = path.join(self.path, file.path) - var fileDir = path.dirname(filePath) + var openWrite = thunky(function (cb) { + var fileDir = path.dirname(filePath) mkdirp(fileDir, function (err) { if (err) return cb(err) @@ -59,6 +60,13 @@ function FSStorage (parsedTorrent, opts) { }) }) + var openRead = thunky(function (cb) { + fs.exists(filePath, function (exists) { + if (exists) return openWrite(cb) + cb(self.nonExistentError) + }) + }) + file.pieces.forEach(function (piece) { var index = piece.index @@ -72,10 +80,11 @@ function FSStorage (parsedTorrent, opts) { if (!self.piecesMap[index]) self.piecesMap[index] = [] self.piecesMap[index].push({ - from: from, - to: to, - offset: offset, - open: open + from : from, + to : to, + offset : offset, + openWrite : openWrite, + openRead : openRead }) }) }) @@ -124,8 +133,8 @@ FSStorage.prototype.readBlock = function (index, offset, length, cb) { from = rangeFrom } - target.open(function (err, file) { - if (err) return cb(err) + target.openRead(function (err, file) { + if (err) return (err === self.nonExistentError ? readFromNextFile(null, new Buffer(0)) : cb(err)) file.read(offset, to - from, readFromNextFile) }) } @@ -147,7 +156,7 @@ FSStorage.prototype._onPieceDone = function (piece) { } var target = targets[i++] - target.open(function (err, file) { + target.openWrite(function (err, file) { if (err) return self.emit('error', err) file.write(target.offset, piece.buffer.slice(target.from, target.to), writeToNextFile) }) |