diff --git a/index.js b/index.js index 61995e21..157f5135 100644 --- a/index.js +++ b/index.js @@ -168,8 +168,17 @@ WebTorrent.prototype.download = function (torrentId, opts, ontorrent) { if (ontorrent) self.on('torrent', clientOnTorrent) torrent.on('error', function (err) { - self.emit('error', err, torrent) - self.remove(torrent) + var alreadyExistsMessage = 'There is already a swarm with info hash' + if (ontorrent && err.message && err.message.substr(0, alreadyExistsMessage.length) === alreadyExistsMessage) { + self.torrents.splice(self.torrents.indexOf(torrent), 1) + torrent = self.torrents.filter(function (_torrent) { + return torrent.infoHash === _torrent.infoHash + })[0] + process.nextTick(clientOnTorrent.bind(null, torrent)) + } else { + self.emit('error', err, torrent) + self.remove(torrent) + } }) torrent.on('listening', function (port) { diff --git a/test/duplicates.js b/test/duplicates.js new file mode 100644 index 00000000..46351ba5 --- /dev/null +++ b/test/duplicates.js @@ -0,0 +1,45 @@ +var fs = require('fs') +var test = require('tape') +var WebTorrent = require('../') + +var leavesBook = fs.readFileSync(__dirname + '/content/Leaves of Grass by Walt Whitman.epub') + +test('client.seed followed by duplicate client.add', function (t) { + t.plan(2) + + var opts = { + name: 'Leaves of Grass by Walt Whitman.epub' + } + + var client = new WebTorrent({ dht: false, tracker: false }) + client.seed(leavesBook, opts, function (torrent1) { + client.add(torrent1.infoHash, function (torrent2) { + t.equal(torrent1.infoHash, torrent2.infoHash) + t.equal(client.torrents.length, 1) + }) + }) +}) + +test('client.seed followed by duplicate client.add, twice', function (t) { + t.plan(4) + + var opts = { + name: 'Leaves of Grass by Walt Whitman.epub' + } + + var client = new WebTorrent({ dht: false, tracker: false }) + + client.seed(leavesBook, opts, function (torrent1) { + client.add(torrent1.infoHash, function (torrent2) { + t.equal(torrent1.infoHash, torrent2.infoHash) + t.equal(client.torrents.length, 1) + }) + }) + + client.seed(leavesBook, opts, function (torrent1) { + client.add(torrent1.infoHash, function (torrent2) { + t.equal(torrent1.infoHash, torrent2.infoHash) + t.equal(client.torrents.length, 1) + }) + }) +})