Skip to content

Commit

Permalink
fix: handle done event when new files selected (#2183)
Browse files Browse the repository at this point in the history
  • Loading branch information
hicom150 committed Aug 25, 2021
1 parent 4954f4f commit c543788
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/torrent.js
Expand Up @@ -1697,6 +1697,8 @@ class Torrent extends EventEmitter {
this.done = true
this._debug(`torrent done: ${this.infoHash}`)
this.emit('done')
} else {
this.done = false
}
this._gcSelections()

Expand Down
54 changes: 54 additions & 0 deletions test/node/torrent-events.js
Expand Up @@ -2,6 +2,7 @@ const fixtures = require('webtorrent-fixtures')
const test = require('tape')
const WebTorrent = require('../../')
const MemoryChunkStore = require('memory-chunk-store')
const randombytes = require('randombytes')

test('client.add: emit torrent events in order', t => {
t.plan(6)
Expand Down Expand Up @@ -81,3 +82,56 @@ test('client.seed: emit torrent events in order', t => {
client.destroy(err => { t.error(err, 'client destroyed') })
})
})

test('file.select: check multiple done events', t => {
t.plan(5)

const client1 = new WebTorrent({ dht: false, tracker: false, lsd: false, utp: false })
const client2 = new WebTorrent({ dht: false, tracker: false, lsd: false, utp: false })

client1.on('error', err => { t.fail(err) })
client1.on('warning', err => { t.fail(err) })

client2.on('error', err => { t.fail(err) })
client2.on('warning', err => { t.fail(err) })

const fileA = Buffer.from(randombytes(16 * 1024).toString('hex'))
const fileB = Buffer.from(randombytes(16 * 1024).toString('hex'))

// Start seeding
client2.seed([fileA, fileB], { announce: [] }, seedTorrent => {
// Select only fileA (index 0)
const magnet = seedTorrent.magnetURI + '&so=0'

// Start downloading
const torrent = client1.add(magnet, { store: MemoryChunkStore })

// Manually connect peers
torrent.addPeer(`127.0.0.1:${client2.address().port}`)

let order = 0

torrent.on('infoHash', () => {
t.equal(++order, 1)
})

torrent.on('metadata', () => {
t.equal(++order, 2)
})

torrent.on('ready', () => {
t.equal(++order, 3)
})

torrent.on('done', () => {
++order

if (order === 4) {
torrent.files[1].select(0)
} else if (order === 5) {
client1.destroy(err => { t.error(err, 'client 1 destroyed') })
client2.destroy(err => { t.error(err, 'client 2 destroyed') })
}
})
})
})

0 comments on commit c543788

Please sign in to comment.