fix: modernize

This commit is contained in:
Diego Rodriguez Baquero 2021-06-14 20:54:41 -05:00
parent 8a97b7e2bf
commit e5994d2ebd
No known key found for this signature in database
GPG Key ID: 6B27C0E5443D1E77
27 changed files with 491 additions and 513 deletions

View File

@ -39,7 +39,7 @@ if (argv.version) {
} }
if (argv.help) { if (argv.help) {
console.log(function () { console.log((() => {
/* /*
bittorrent-tracker - Start a bittorrent tracker server bittorrent-tracker - Start a bittorrent tracker server
@ -64,7 +64,7 @@ if (argv.help) {
-v, --version print the current version -v, --version print the current version
*/ */
}.toString().split(/\n/).slice(2, -2).join('\n')) }).toString().split(/\n/).slice(2, -2).join('\n'))
process.exit(0) process.exit(0)
} }
@ -85,23 +85,23 @@ const server = new Server({
ws: argv.ws ws: argv.ws
}) })
server.on('error', function (err) { server.on('error', err => {
if (!argv.silent) console.error('ERROR: ' + err.message) if (!argv.silent) console.error(`ERROR: ${err.message}`)
}) })
server.on('warning', function (err) { server.on('warning', err => {
if (!argv.quiet) console.log('WARNING: ' + err.message) if (!argv.quiet) console.log(`WARNING: ${err.message}`)
}) })
server.on('update', function (addr) { server.on('update', addr => {
if (!argv.quiet) console.log('update: ' + addr) if (!argv.quiet) console.log(`update: ${addr}`)
}) })
server.on('complete', function (addr) { server.on('complete', addr => {
if (!argv.quiet) console.log('complete: ' + addr) if (!argv.quiet) console.log(`complete: ${addr}`)
}) })
server.on('start', function (addr) { server.on('start', addr => {
if (!argv.quiet) console.log('start: ' + addr) if (!argv.quiet) console.log(`start: ${addr}`)
}) })
server.on('stop', function (addr) { server.on('stop', addr => {
if (!argv.quiet) console.log('stop: ' + addr) if (!argv.quiet) console.log(`stop: ${addr}`)
}) })
const hostname = { const hostname = {
@ -110,35 +110,35 @@ const hostname = {
udp6: argv['udp6-hostname'] udp6: argv['udp6-hostname']
} }
server.listen(argv.port, hostname, function () { server.listen(argv.port, hostname, () => {
if (server.http && argv.http && !argv.quiet) { if (server.http && argv.http && !argv.quiet) {
const httpAddr = server.http.address() const httpAddr = server.http.address()
const httpHost = httpAddr.address !== '::' ? httpAddr.address : 'localhost' const httpHost = httpAddr.address !== '::' ? httpAddr.address : 'localhost'
const httpPort = httpAddr.port const httpPort = httpAddr.port
console.log('HTTP tracker: http://' + httpHost + ':' + httpPort + '/announce') console.log(`HTTP tracker: http://${httpHost}:${httpPort}/announce`)
} }
if (server.udp && !argv.quiet) { if (server.udp && !argv.quiet) {
const udpAddr = server.udp.address() const udpAddr = server.udp.address()
const udpHost = udpAddr.address const udpHost = udpAddr.address
const udpPort = udpAddr.port const udpPort = udpAddr.port
console.log('UDP tracker: udp://' + udpHost + ':' + udpPort) console.log(`UDP tracker: udp://${udpHost}:${udpPort}`)
} }
if (server.udp6 && !argv.quiet) { if (server.udp6 && !argv.quiet) {
const udp6Addr = server.udp6.address() const udp6Addr = server.udp6.address()
const udp6Host = udp6Addr.address !== '::' ? udp6Addr.address : 'localhost' const udp6Host = udp6Addr.address !== '::' ? udp6Addr.address : 'localhost'
const udp6Port = udp6Addr.port const udp6Port = udp6Addr.port
console.log('UDP6 tracker: udp://' + udp6Host + ':' + udp6Port) console.log(`UDP6 tracker: udp://${udp6Host}:${udp6Port}`)
} }
if (server.ws && !argv.quiet) { if (server.ws && !argv.quiet) {
const wsAddr = server.http.address() const wsAddr = server.http.address()
const wsHost = wsAddr.address !== '::' ? wsAddr.address : 'localhost' const wsHost = wsAddr.address !== '::' ? wsAddr.address : 'localhost'
const wsPort = wsAddr.port const wsPort = wsAddr.port
console.log('WebSocket tracker: ws://' + wsHost + ':' + wsPort) console.log(`WebSocket tracker: ws://${wsHost}:${wsPort}`)
} }
if (server.http && argv.stats && !argv.quiet) { if (server.http && argv.stats && !argv.quiet) {
const statsAddr = server.http.address() const statsAddr = server.http.address()
const statsHost = statsAddr.address !== '::' ? statsAddr.address : 'localhost' const statsHost = statsAddr.address !== '::' ? statsAddr.address : 'localhost'
const statsPort = statsAddr.port const statsPort = statsAddr.port
console.log('Tracker stats: http://' + statsHost + ':' + statsPort + '/stats') console.log(`Tracker stats: http://${statsHost}:${statsPort}/stats`)
} }
}) })

View File

@ -281,9 +281,7 @@ Client.scrape = (opts, cb) => {
}) })
opts.infoHash = Array.isArray(opts.infoHash) opts.infoHash = Array.isArray(opts.infoHash)
? opts.infoHash.map(infoHash => { ? opts.infoHash.map(infoHash => Buffer.from(infoHash, 'hex'))
return Buffer.from(infoHash, 'hex')
})
: Buffer.from(opts.infoHash, 'hex') : Buffer.from(opts.infoHash, 'hex')
client.scrape({ infoHash: opts.infoHash }) client.scrape({ infoHash: opts.infoHash })
return client return client

View File

@ -13,7 +13,7 @@ const server = new Server({
http: false, // we do our own http: false, // we do our own
udp: false, // not interested udp: false, // not interested
ws: false, // not interested ws: false, // not interested
filter: function (params) { filter (params) {
// black/whitelist for disallowing/allowing specific clients [default=allow all] // black/whitelist for disallowing/allowing specific clients [default=allow all]
// this example only allows the uTorrent client // this example only allows the uTorrent client
const client = params.peer_id[1] + params.peer_id[2] const client = params.peer_id[1] + params.peer_id[2]

View File

@ -17,7 +17,7 @@ const HTTP_SCRAPE_SUPPORT = /\/(announce)[^/]*$/
* @param {Object} opts options object * @param {Object} opts options object
*/ */
class HTTPTracker extends Tracker { class HTTPTracker extends Tracker {
constructor (client, announceUrl, opts) { constructor (client, announceUrl) {
super(client, announceUrl) super(client, announceUrl)
debug('new http tracker %s', announceUrl) debug('new http tracker %s', announceUrl)
@ -62,9 +62,7 @@ class HTTPTracker extends Tracker {
} }
const infoHashes = (Array.isArray(opts.infoHash) && opts.infoHash.length > 0) const infoHashes = (Array.isArray(opts.infoHash) && opts.infoHash.length > 0)
? opts.infoHash.map(infoHash => { ? opts.infoHash.map(infoHash => infoHash.toString('binary'))
return infoHash.toString('binary')
})
: (opts.infoHash && opts.infoHash.toString('binary')) || this.client._infoHashBinary : (opts.infoHash && opts.infoHash.toString('binary')) || this.client._infoHashBinary
const params = { const params = {
info_hash: infoHashes info_hash: infoHashes

View File

@ -16,7 +16,7 @@ const Tracker = require('./tracker')
* @param {Object} opts options object * @param {Object} opts options object
*/ */
class UDPTracker extends Tracker { class UDPTracker extends Tracker {
constructor (client, announceUrl, opts) { constructor (client, announceUrl) {
super(client, announceUrl) super(client, announceUrl)
debug('new udp tracker %s', announceUrl) debug('new udp tracker %s', announceUrl)
@ -181,7 +181,7 @@ class UDPTracker extends Tracker {
return onError(new Error('invalid scrape message')) return onError(new Error('invalid scrape message'))
} }
const infoHashes = (Array.isArray(opts.infoHash) && opts.infoHash.length > 0) const infoHashes = (Array.isArray(opts.infoHash) && opts.infoHash.length > 0)
? opts.infoHash.map(infoHash => { return infoHash.toString('hex') }) ? opts.infoHash.map(infoHash => infoHash.toString('hex'))
: [(opts.infoHash && opts.infoHash.toString('hex')) || self.client.infoHash] : [(opts.infoHash && opts.infoHash.toString('hex')) || self.client.infoHash]
for (let i = 0, len = (msg.length - 8) / 12; i < len; i += 1) { for (let i = 0, len = (msg.length - 8) / 12; i < len; i += 1) {

View File

@ -17,7 +17,7 @@ const RECONNECT_VARIANCE = 5 * 60 * 1000
const OFFER_TIMEOUT = 50 * 1000 const OFFER_TIMEOUT = 50 * 1000
class WebSocketTracker extends Tracker { class WebSocketTracker extends Tracker {
constructor (client, announceUrl, opts) { constructor (client, announceUrl) {
super(client, announceUrl) super(client, announceUrl)
debug('new websocket tracker %s', announceUrl) debug('new websocket tracker %s', announceUrl)
@ -76,9 +76,7 @@ class WebSocketTracker extends Tracker {
} }
const infoHashes = (Array.isArray(opts.infoHash) && opts.infoHash.length > 0) const infoHashes = (Array.isArray(opts.infoHash) && opts.infoHash.length > 0)
? opts.infoHash.map(infoHash => { ? opts.infoHash.map(infoHash => infoHash.toString('binary'))
return infoHash.toString('binary')
})
: (opts.infoHash && opts.infoHash.toString('binary')) || this.client._infoHashBinary : (opts.infoHash && opts.infoHash.toString('binary')) || this.client._infoHashBinary
const params = { const params = {
action: 'scrape', action: 'scrape',

View File

@ -50,9 +50,7 @@ exports.toUInt32 = toUInt32
* @param {string} q * @param {string} q
* @return {Object} * @return {Object}
*/ */
exports.querystringParse = function (q) { exports.querystringParse = q => querystring.parse(q, null, null, { decodeURIComponent: unescape })
return querystring.parse(q, null, null, { decodeURIComponent: unescape })
}
/** /**
* `querystring.stringify` using `escape` instead of encodeURIComponent, since bittorrent * `querystring.stringify` using `escape` instead of encodeURIComponent, since bittorrent
@ -60,11 +58,9 @@ exports.querystringParse = function (q) {
* @param {Object} obj * @param {Object} obj
* @return {string} * @return {string}
*/ */
exports.querystringStringify = function (obj) { exports.querystringStringify = obj => {
let ret = querystring.stringify(obj, null, null, { encodeURIComponent: escape }) let ret = querystring.stringify(obj, null, null, { encodeURIComponent: escape })
ret = ret.replace(/[@*/+]/g, function (char) { ret = ret.replace(/[@*/+]/g, char => // `escape` doesn't encode the characters @*/+ so we do it manually
// `escape` doesn't encode the characters @*/+ so we do it manually `%${char.charCodeAt(0).toString(16).toUpperCase()}`)
return '%' + char.charCodeAt(0).toString(16).toUpperCase()
})
return ret return ret
} }

View File

@ -5,14 +5,14 @@
exports.DEFAULT_ANNOUNCE_PEERS = 50 exports.DEFAULT_ANNOUNCE_PEERS = 50
exports.MAX_ANNOUNCE_PEERS = 82 exports.MAX_ANNOUNCE_PEERS = 82
exports.binaryToHex = function (str) { exports.binaryToHex = str => {
if (typeof str !== 'string') { if (typeof str !== 'string') {
str = String(str) str = String(str)
} }
return Buffer.from(str, 'binary').toString('hex') return Buffer.from(str, 'binary').toString('hex')
} }
exports.hexToBinary = function (str) { exports.hexToBinary = str => {
if (typeof str !== 'string') { if (typeof str !== 'string') {
str = String(str) str = String(str)
} }
@ -31,7 +31,7 @@ exports.hexToBinary = function (str) {
// Bug reports: // Bug reports:
// - Chrome: https://bugs.chromium.org/p/chromium/issues/detail?id=734880 // - Chrome: https://bugs.chromium.org/p/chromium/issues/detail?id=734880
// - Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1374505 // - Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1374505
exports.parseUrl = function (str) { exports.parseUrl = str => {
const url = new URL(str.replace(/^udp:/, 'http:')) const url = new URL(str.replace(/^udp:/, 'http:'))
if (str.match(/^udp:/)) { if (str.match(/^udp:/)) {

View File

@ -36,7 +36,7 @@ function parseHttpRequest (req, opts) {
params.ip = opts.trustProxy params.ip = opts.trustProxy
? req.headers['x-forwarded-for'] || req.connection.remoteAddress ? req.headers['x-forwarded-for'] || req.connection.remoteAddress
: req.connection.remoteAddress.replace(common.REMOVE_IPV4_MAPPED_IPV6_RE, '') // force ipv4 : req.connection.remoteAddress.replace(common.REMOVE_IPV4_MAPPED_IPV6_RE, '') // force ipv4
params.addr = (common.IPV6_RE.test(params.ip) ? '[' + params.ip + ']' : params.ip) + ':' + params.port params.addr = `${common.IPV6_RE.test(params.ip) ? `[${params.ip}]` : params.ip}:${params.port}`
params.headers = req.headers params.headers = req.headers
} else if (opts.action === 'scrape' || s[0] === '/scrape') { } else if (opts.action === 'scrape' || s[0] === '/scrape') {
@ -44,7 +44,7 @@ function parseHttpRequest (req, opts) {
if (typeof params.info_hash === 'string') params.info_hash = [params.info_hash] if (typeof params.info_hash === 'string') params.info_hash = [params.info_hash]
if (Array.isArray(params.info_hash)) { if (Array.isArray(params.info_hash)) {
params.info_hash = params.info_hash.map(function (binaryInfoHash) { params.info_hash = params.info_hash.map(binaryInfoHash => {
if (typeof binaryInfoHash !== 'string' || binaryInfoHash.length !== 20) { if (typeof binaryInfoHash !== 'string' || binaryInfoHash.length !== 20) {
throw new Error('invalid info_hash') throw new Error('invalid info_hash')
} }
@ -52,7 +52,7 @@ function parseHttpRequest (req, opts) {
}) })
} }
} else { } else {
throw new Error('invalid action in HTTP request: ' + req.url) throw new Error(`invalid action in HTTP request: ${req.url}`)
} }
return params return params

View File

@ -44,7 +44,7 @@ function parseUdpRequest (msg, rinfo) {
) )
params.port = msg.readUInt16BE(96) || rinfo.port // optional params.port = msg.readUInt16BE(96) || rinfo.port // optional
params.addr = params.ip + ':' + params.port // TODO: ipv6 brackets params.addr = `${params.ip}:${params.port}` // TODO: ipv6 brackets
params.compact = 1 // udp is always compact params.compact = 1 // udp is always compact
} else if (params.action === common.ACTIONS.SCRAPE) { // scrape message } else if (params.action === common.ACTIONS.SCRAPE) { // scrape message
if ((msg.length - 16) % 20 !== 0) throw new Error('invalid scrape message') if ((msg.length - 16) % 20 !== 0) throw new Error('invalid scrape message')
@ -54,7 +54,7 @@ function parseUdpRequest (msg, rinfo) {
params.info_hash.push(infoHash) params.info_hash.push(infoHash)
} }
} else { } else {
throw new Error('Invalid action in UDP packet: ' + params.action) throw new Error(`Invalid action in UDP packet: ${params.action}`)
} }
return params return params

View File

@ -41,7 +41,7 @@ function parseWebSocketRequest (socket, opts, params) {
if (typeof params.info_hash === 'string') params.info_hash = [params.info_hash] if (typeof params.info_hash === 'string') params.info_hash = [params.info_hash]
if (Array.isArray(params.info_hash)) { if (Array.isArray(params.info_hash)) {
params.info_hash = params.info_hash.map(function (binaryInfoHash) { params.info_hash = params.info_hash.map(binaryInfoHash => {
if (typeof binaryInfoHash !== 'string' || binaryInfoHash.length !== 20) { if (typeof binaryInfoHash !== 'string' || binaryInfoHash.length !== 20) {
throw new Error('invalid info_hash') throw new Error('invalid info_hash')
} }
@ -49,7 +49,7 @@ function parseWebSocketRequest (socket, opts, params) {
}) })
} }
} else { } else {
throw new Error('invalid action in WS request: ' + params.action) throw new Error(`invalid action in WS request: ${params.action}`)
} }
// On first parse, save important data from `socket.upgradeReq` and delete it // On first parse, save important data from `socket.upgradeReq` and delete it
@ -60,7 +60,7 @@ function parseWebSocketRequest (socket, opts, params) {
: socket.upgradeReq.connection.remoteAddress.replace(common.REMOVE_IPV4_MAPPED_IPV6_RE, '') // force ipv4 : socket.upgradeReq.connection.remoteAddress.replace(common.REMOVE_IPV4_MAPPED_IPV6_RE, '') // force ipv4
socket.port = socket.upgradeReq.connection.remotePort socket.port = socket.upgradeReq.connection.remotePort
if (socket.port) { if (socket.port) {
socket.addr = (common.IPV6_RE.test(socket.ip) ? '[' + socket.ip + ']' : socket.ip) + ':' + socket.port socket.addr = `${common.IPV6_RE.test(socket.ip) ? `[${socket.ip}]` : socket.ip}:${socket.port}`
} }
socket.headers = socket.upgradeReq.headers socket.headers = socket.upgradeReq.headers

View File

@ -1,5 +1,3 @@
module.exports = Swarm
const arrayRemove = require('unordered-array-remove') const arrayRemove = require('unordered-array-remove')
const debug = require('debug')('bittorrent-tracker:swarm') const debug = require('debug')('bittorrent-tracker:swarm')
const LRU = require('lru') const LRU = require('lru')
@ -7,142 +5,146 @@ const randomIterate = require('random-iterate')
// Regard this as the default implementation of an interface that you // Regard this as the default implementation of an interface that you
// need to support when overriding Server.createSwarm() and Server.getSwarm() // need to support when overriding Server.createSwarm() and Server.getSwarm()
function Swarm (infoHash, server) { class Swarm {
const self = this constructor (infoHash, server) {
self.infoHash = infoHash const self = this
self.complete = 0 self.infoHash = infoHash
self.incomplete = 0 self.complete = 0
self.incomplete = 0
self.peers = new LRU({ self.peers = new LRU({
max: server.peersCacheLength || 1000, max: server.peersCacheLength || 1000,
maxAge: server.peersCacheTtl || 20 * 60 * 1000 // 20 minutes maxAge: server.peersCacheTtl || 20 * 60 * 1000 // 20 minutes
}) })
// When a peer is evicted from the LRU store, send a synthetic 'stopped' event // When a peer is evicted from the LRU store, send a synthetic 'stopped' event
// so the stats get updated correctly. // so the stats get updated correctly.
self.peers.on('evict', function (data) { self.peers.on('evict', data => {
const peer = data.value const peer = data.value
const params = { const params = {
type: peer.type, type: peer.type,
event: 'stopped', event: 'stopped',
numwant: 0, numwant: 0,
peer_id: peer.peerId peer_id: peer.peerId
}
self._onAnnounceStopped(params, peer, peer.peerId)
peer.socket = null
})
}
announce (params, cb) {
const self = this
const id = params.type === 'ws' ? params.peer_id : params.addr
// Mark the source peer as recently used in cache
const peer = self.peers.get(id)
if (params.event === 'started') {
self._onAnnounceStarted(params, peer, id)
} else if (params.event === 'stopped') {
self._onAnnounceStopped(params, peer, id)
} else if (params.event === 'completed') {
self._onAnnounceCompleted(params, peer, id)
} else if (params.event === 'update') {
self._onAnnounceUpdate(params, peer, id)
} else {
cb(new Error('invalid event'))
return
} }
self._onAnnounceStopped(params, peer, peer.peerId) cb(null, {
peer.socket = null complete: self.complete,
}) incomplete: self.incomplete,
} peers: self._getPeers(params.numwant, params.peer_id, !!params.socket)
})
Swarm.prototype.announce = function (params, cb) {
const self = this
const id = params.type === 'ws' ? params.peer_id : params.addr
// Mark the source peer as recently used in cache
const peer = self.peers.get(id)
if (params.event === 'started') {
self._onAnnounceStarted(params, peer, id)
} else if (params.event === 'stopped') {
self._onAnnounceStopped(params, peer, id)
} else if (params.event === 'completed') {
self._onAnnounceCompleted(params, peer, id)
} else if (params.event === 'update') {
self._onAnnounceUpdate(params, peer, id)
} else {
cb(new Error('invalid event'))
return
}
cb(null, {
complete: self.complete,
incomplete: self.incomplete,
peers: self._getPeers(params.numwant, params.peer_id, !!params.socket)
})
}
Swarm.prototype.scrape = function (params, cb) {
cb(null, {
complete: this.complete,
incomplete: this.incomplete
})
}
Swarm.prototype._onAnnounceStarted = function (params, peer, id) {
if (peer) {
debug('unexpected `started` event from peer that is already in swarm')
return this._onAnnounceUpdate(params, peer, id) // treat as an update
} }
if (params.left === 0) this.complete += 1 scrape (params, cb) {
else this.incomplete += 1 cb(null, {
this.peers.set(id, { complete: this.complete,
type: params.type, incomplete: this.incomplete
complete: params.left === 0, })
peerId: params.peer_id, // as hex
ip: params.ip,
port: params.port,
socket: params.socket // only websocket
})
}
Swarm.prototype._onAnnounceStopped = function (params, peer, id) {
if (!peer) {
debug('unexpected `stopped` event from peer that is not in swarm')
return // do nothing
} }
if (peer.complete) this.complete -= 1 _onAnnounceStarted (params, peer, id) {
else this.incomplete -= 1 if (peer) {
debug('unexpected `started` event from peer that is already in swarm')
return this._onAnnounceUpdate(params, peer, id) // treat as an update
}
// If it's a websocket, remove this swarm's infohash from the list of active if (params.left === 0) this.complete += 1
// swarms that this peer is participating in. else this.incomplete += 1
if (peer.socket && !peer.socket.destroyed) { this.peers.set(id, {
const index = peer.socket.infoHashes.indexOf(this.infoHash) type: params.type,
arrayRemove(peer.socket.infoHashes, index) complete: params.left === 0,
peerId: params.peer_id, // as hex
ip: params.ip,
port: params.port,
socket: params.socket // only websocket
})
} }
this.peers.remove(id) _onAnnounceStopped (params, peer, id) {
} if (!peer) {
debug('unexpected `stopped` event from peer that is not in swarm')
return // do nothing
}
Swarm.prototype._onAnnounceCompleted = function (params, peer, id) { if (peer.complete) this.complete -= 1
if (!peer) { else this.incomplete -= 1
debug('unexpected `completed` event from peer that is not in swarm')
return this._onAnnounceStarted(params, peer, id) // treat as a start // If it's a websocket, remove this swarm's infohash from the list of active
} // swarms that this peer is participating in.
if (peer.complete) { if (peer.socket && !peer.socket.destroyed) {
debug('unexpected `completed` event from peer that is already completed') const index = peer.socket.infoHashes.indexOf(this.infoHash)
return this._onAnnounceUpdate(params, peer, id) // treat as an update arrayRemove(peer.socket.infoHashes, index)
}
this.peers.remove(id)
} }
this.complete += 1 _onAnnounceCompleted (params, peer, id) {
this.incomplete -= 1 if (!peer) {
peer.complete = true debug('unexpected `completed` event from peer that is not in swarm')
this.peers.set(id, peer) return this._onAnnounceStarted(params, peer, id) // treat as a start
} }
if (peer.complete) {
debug('unexpected `completed` event from peer that is already completed')
return this._onAnnounceUpdate(params, peer, id) // treat as an update
}
Swarm.prototype._onAnnounceUpdate = function (params, peer, id) {
if (!peer) {
debug('unexpected `update` event from peer that is not in swarm')
return this._onAnnounceStarted(params, peer, id) // treat as a start
}
if (!peer.complete && params.left === 0) {
this.complete += 1 this.complete += 1
this.incomplete -= 1 this.incomplete -= 1
peer.complete = true peer.complete = true
this.peers.set(id, peer)
}
_onAnnounceUpdate (params, peer, id) {
if (!peer) {
debug('unexpected `update` event from peer that is not in swarm')
return this._onAnnounceStarted(params, peer, id) // treat as a start
}
if (!peer.complete && params.left === 0) {
this.complete += 1
this.incomplete -= 1
peer.complete = true
}
this.peers.set(id, peer)
}
_getPeers (numwant, ownPeerId, isWebRTC) {
const peers = []
const ite = randomIterate(this.peers.keys)
let peerId
while ((peerId = ite()) && peers.length < numwant) {
// Don't mark the peer as most recently used on announce
const peer = this.peers.peek(peerId)
if (!peer) continue
if (isWebRTC && peer.peerId === ownPeerId) continue // don't send peer to itself
if ((isWebRTC && peer.type !== 'ws') || (!isWebRTC && peer.type === 'ws')) continue // send proper peer type
peers.push(peer)
}
return peers
} }
this.peers.set(id, peer)
} }
Swarm.prototype._getPeers = function (numwant, ownPeerId, isWebRTC) { module.exports = Swarm
const peers = []
const ite = randomIterate(this.peers.keys)
let peerId
while ((peerId = ite()) && peers.length < numwant) {
// Don't mark the peer as most recently used on announce
const peer = this.peers.peek(peerId)
if (!peer) continue
if (isWebRTC && peer.peerId === ownPeerId) continue // don't send peer to itself
if ((isWebRTC && peer.type !== 'ws') || (!isWebRTC && peer.type === 'ws')) continue // send proper peer type
peers.push(peer)
}
return peers
}

View File

@ -47,16 +47,16 @@
"ws": "^7.4.5" "ws": "^7.4.5"
}, },
"devDependencies": { "devDependencies": {
"@webtorrent/semantic-release-config": "^1.0.5", "@webtorrent/semantic-release-config": "1.0.5",
"magnet-uri": "6.2.0", "magnet-uri": "6.2.0",
"semantic-release": "^17.4.3", "semantic-release": "17.4.3",
"standard": "*", "standard": "*",
"tape": "5.2.2", "tape": "5.2.2",
"webtorrent-fixtures": "1.7.3", "webtorrent-fixtures": "1.7.3",
"wrtc": "0.4.7" "wrtc": "0.4.7"
}, },
"engines": { "engines": {
"node": ">=10" "node": ">=12"
}, },
"keywords": [ "keywords": [
"bittorrent", "bittorrent",

View File

@ -239,11 +239,11 @@ class Server extends EventEmitter {
}) })
}) })
const isSeederOnly = peer => { return peer.seeder && peer.leecher === false } const isSeederOnly = peer => peer.seeder && peer.leecher === false
const isLeecherOnly = peer => { return peer.leecher && peer.seeder === false } const isLeecherOnly = peer => peer.leecher && peer.seeder === false
const isSeederAndLeecher = peer => { return peer.seeder && peer.leecher } const isSeederAndLeecher = peer => peer.seeder && peer.leecher
const isIPv4 = peer => { return peer.ipv4 } const isIPv4 = peer => peer.ipv4
const isIPv6 = peer => { return peer.ipv6 } const isIPv6 = peer => peer.ipv6
const stats = { const stats = {
torrents: infoHashes.length, torrents: infoHashes.length,
@ -678,26 +678,16 @@ class Server extends EventEmitter {
const peers = response.peers const peers = response.peers
// Find IPv4 peers // Find IPv4 peers
response.peers = string2compact(peers.filter(peer => { response.peers = string2compact(peers.filter(peer => common.IPV4_RE.test(peer.ip)).map(peer => `${peer.ip}:${peer.port}`))
return common.IPV4_RE.test(peer.ip)
}).map(peer => {
return `${peer.ip}:${peer.port}`
}))
// Find IPv6 peers // Find IPv6 peers
response.peers6 = string2compact(peers.filter(peer => { response.peers6 = string2compact(peers.filter(peer => common.IPV6_RE.test(peer.ip)).map(peer => `[${peer.ip}]:${peer.port}`))
return common.IPV6_RE.test(peer.ip)
}).map(peer => {
return `[${peer.ip}]:${peer.port}`
}))
} else if (params.compact === 0) { } else if (params.compact === 0) {
// IPv6 peers are not separate for non-compact responses // IPv6 peers are not separate for non-compact responses
response.peers = response.peers.map(peer => { response.peers = response.peers.map(peer => ({
return { 'peer id': common.hexToBinary(peer.peerId),
'peer id': common.hexToBinary(peer.peerId), ip: peer.ip,
ip: peer.ip, port: peer.port
port: peer.port }))
}
})
} // else, return full peer objects (used for websocket responses) } // else, return full peer objects (used for websocket responses)
cb(null, response) cb(null, response)
@ -712,24 +702,22 @@ class Server extends EventEmitter {
params.info_hash = Object.keys(this.torrents) params.info_hash = Object.keys(this.torrents)
} }
series(params.info_hash.map(infoHash => { series(params.info_hash.map(infoHash => cb => {
return cb => { this.getSwarm(infoHash, (err, swarm) => {
this.getSwarm(infoHash, (err, swarm) => { if (err) return cb(err)
if (err) return cb(err) if (swarm) {
if (swarm) { swarm.scrape(params, (err, scrapeInfo) => {
swarm.scrape(params, (err, scrapeInfo) => { if (err) return cb(err)
if (err) return cb(err) cb(null, {
cb(null, { infoHash,
infoHash, complete: (scrapeInfo && scrapeInfo.complete) || 0,
complete: (scrapeInfo && scrapeInfo.complete) || 0, incomplete: (scrapeInfo && scrapeInfo.incomplete) || 0
incomplete: (scrapeInfo && scrapeInfo.incomplete) || 0
})
}) })
} else { })
cb(null, { infoHash, complete: 0, incomplete: 0 }) } else {
} cb(null, { infoHash, complete: 0, incomplete: 0 })
}) }
} })
}), (err, results) => { }), (err, results) => {
if (err) return cb(err) if (err) return cb(err)

View File

@ -8,7 +8,7 @@ const peerId = Buffer.from('01234567890123456789')
function testLargeTorrent (t, serverType) { function testLargeTorrent (t, serverType) {
t.plan(9) t.plan(9)
common.createServer(t, serverType, function (server, announceUrl) { common.createServer(t, serverType, (server, announceUrl) => {
const client = new Client({ const client = new Client({
infoHash: fixtures.sintel.parsedTorrent.infoHash, infoHash: fixtures.sintel.parsedTorrent.infoHash,
peerId, peerId,
@ -18,24 +18,24 @@ function testLargeTorrent (t, serverType) {
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client) if (serverType === 'ws') common.mockWebsocketTracker(client)
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.once('update', function (data) { client.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(typeof data.complete, 'number') t.equal(typeof data.complete, 'number')
t.equal(typeof data.incomplete, 'number') t.equal(typeof data.incomplete, 'number')
client.update() client.update()
client.once('update', function (data) { client.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(typeof data.complete, 'number') t.equal(typeof data.complete, 'number')
t.equal(typeof data.incomplete, 'number') t.equal(typeof data.incomplete, 'number')
client.stop() client.stop()
client.once('update', function (data) { client.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(typeof data.complete, 'number') t.equal(typeof data.complete, 'number')
t.equal(typeof data.incomplete, 'number') t.equal(typeof data.incomplete, 'number')
@ -50,14 +50,14 @@ function testLargeTorrent (t, serverType) {
}) })
} }
test('http: large torrent: client.start()', function (t) { test('http: large torrent: client.start()', t => {
testLargeTorrent(t, 'http') testLargeTorrent(t, 'http')
}) })
test('udp: large torrent: client.start()', function (t) { test('udp: large torrent: client.start()', t => {
testLargeTorrent(t, 'udp') testLargeTorrent(t, 'udp')
}) })
test('ws: large torrent: client.start()', function (t) { test('ws: large torrent: client.start()', t => {
testLargeTorrent(t, 'ws') testLargeTorrent(t, 'ws')
}) })

View File

@ -11,7 +11,7 @@ function testMagnet (t, serverType) {
const parsedTorrent = magnet(fixtures.leaves.magnetURI) const parsedTorrent = magnet(fixtures.leaves.magnetURI)
common.createServer(t, serverType, function (server, announceUrl) { common.createServer(t, serverType, (server, announceUrl) => {
const client = new Client({ const client = new Client({
infoHash: parsedTorrent.infoHash, infoHash: parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -21,24 +21,24 @@ function testMagnet (t, serverType) {
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client) if (serverType === 'ws') common.mockWebsocketTracker(client)
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.once('update', function (data) { client.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(typeof data.complete, 'number') t.equal(typeof data.complete, 'number')
t.equal(typeof data.incomplete, 'number') t.equal(typeof data.incomplete, 'number')
client.update() client.update()
client.once('update', function (data) { client.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(typeof data.complete, 'number') t.equal(typeof data.complete, 'number')
t.equal(typeof data.incomplete, 'number') t.equal(typeof data.incomplete, 'number')
client.stop() client.stop()
client.once('update', function (data) { client.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(typeof data.complete, 'number') t.equal(typeof data.complete, 'number')
t.equal(typeof data.incomplete, 'number') t.equal(typeof data.incomplete, 'number')
@ -53,14 +53,14 @@ function testMagnet (t, serverType) {
}) })
} }
test('http: magnet: client.start/update/stop()', function (t) { test('http: magnet: client.start/update/stop()', t => {
testMagnet(t, 'http') testMagnet(t, 'http')
}) })
test('udp: magnet: client.start/update/stop()', function (t) { test('udp: magnet: client.start/update/stop()', t => {
testMagnet(t, 'udp') testMagnet(t, 'udp')
}) })
test('ws: magnet: client.start/update/stop()', function (t) { test('ws: magnet: client.start/update/stop()', t => {
testMagnet(t, 'ws') testMagnet(t, 'ws')
}) })

View File

@ -6,10 +6,10 @@ const test = require('tape')
const peerId = Buffer.from('01234567890123456789') const peerId = Buffer.from('01234567890123456789')
const port = 6681 const port = 6681
test('ensure client.destroy() callback is called with re-used websockets in socketPool', function (t) { test('ensure client.destroy() callback is called with re-used websockets in socketPool', t => {
t.plan(4) t.plan(4)
common.createServer(t, 'ws', function (server, announceUrl) { common.createServer(t, 'ws', (server, announceUrl) => {
const client1 = new Client({ const client1 = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -19,12 +19,12 @@ test('ensure client.destroy() callback is called with re-used websockets in sock
}) })
common.mockWebsocketTracker(client1) common.mockWebsocketTracker(client1)
client1.on('error', function (err) { t.error(err) }) client1.on('error', err => { t.error(err) })
client1.on('warning', function (err) { t.error(err) }) client1.on('warning', err => { t.error(err) })
client1.start() client1.start()
client1.once('update', function () { client1.once('update', () => {
t.pass('got client1 update') t.pass('got client1 update')
// second ws client using same announce url will re-use the same websocket // second ws client using same announce url will re-use the same websocket
const client2 = new Client({ const client2 = new Client({
@ -36,16 +36,16 @@ test('ensure client.destroy() callback is called with re-used websockets in sock
}) })
common.mockWebsocketTracker(client2) common.mockWebsocketTracker(client2)
client2.on('error', function (err) { t.error(err) }) client2.on('error', err => { t.error(err) })
client2.on('warning', function (err) { t.error(err) }) client2.on('warning', err => { t.error(err) })
client2.start() client2.start()
client2.once('update', function () { client2.once('update', () => {
t.pass('got client2 update') t.pass('got client2 update')
client1.destroy(function (err) { client1.destroy(err => {
t.error(err, 'got client1 destroy callback') t.error(err, 'got client1 destroy callback')
client2.destroy(function (err) { client2.destroy(err => {
t.error(err, 'got client2 destroy callback') t.error(err, 'got client2 destroy callback')
server.close() server.close()
}) })

View File

@ -11,7 +11,7 @@ const port = 6881
function testClientStart (t, serverType) { function testClientStart (t, serverType) {
t.plan(4) t.plan(4)
common.createServer(t, serverType, function (server, announceUrl) { common.createServer(t, serverType, (server, announceUrl) => {
const client = new Client({ const client = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -21,17 +21,17 @@ function testClientStart (t, serverType) {
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client) if (serverType === 'ws') common.mockWebsocketTracker(client)
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.once('update', function (data) { client.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(typeof data.complete, 'number') t.equal(typeof data.complete, 'number')
t.equal(typeof data.incomplete, 'number') t.equal(typeof data.incomplete, 'number')
client.stop() client.stop()
client.once('update', function () { client.once('update', () => {
t.pass('got response to stop') t.pass('got response to stop')
server.close() server.close()
client.destroy() client.destroy()
@ -42,22 +42,22 @@ function testClientStart (t, serverType) {
}) })
} }
test('http: client.start()', function (t) { test('http: client.start()', t => {
testClientStart(t, 'http') testClientStart(t, 'http')
}) })
test('udp: client.start()', function (t) { test('udp: client.start()', t => {
testClientStart(t, 'udp') testClientStart(t, 'udp')
}) })
test('ws: client.start()', function (t) { test('ws: client.start()', t => {
testClientStart(t, 'ws') testClientStart(t, 'ws')
}) })
function testClientStop (t, serverType) { function testClientStop (t, serverType) {
t.plan(4) t.plan(4)
common.createServer(t, serverType, function (server, announceUrl) { common.createServer(t, serverType, (server, announceUrl) => {
const client = new Client({ const client = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -67,17 +67,17 @@ function testClientStop (t, serverType) {
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client) if (serverType === 'ws') common.mockWebsocketTracker(client)
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.start() client.start()
client.once('update', function () { client.once('update', () => {
t.pass('client received response to "start" message') t.pass('client received response to "start" message')
client.stop() client.stop()
client.once('update', function (data) { client.once('update', data => {
// receive one final update after calling stop // receive one final update after calling stop
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(typeof data.complete, 'number') t.equal(typeof data.complete, 'number')
@ -90,22 +90,22 @@ function testClientStop (t, serverType) {
}) })
} }
test('http: client.stop()', function (t) { test('http: client.stop()', t => {
testClientStop(t, 'http') testClientStop(t, 'http')
}) })
test('udp: client.stop()', function (t) { test('udp: client.stop()', t => {
testClientStop(t, 'udp') testClientStop(t, 'udp')
}) })
test('ws: client.stop()', function (t) { test('ws: client.stop()', t => {
testClientStop(t, 'ws') testClientStop(t, 'ws')
}) })
function testClientStopDestroy (t, serverType) { function testClientStopDestroy (t, serverType) {
t.plan(2) t.plan(2)
common.createServer(t, serverType, function (server, announceUrl) { common.createServer(t, serverType, (server, announceUrl) => {
const client = new Client({ const client = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -115,26 +115,26 @@ function testClientStopDestroy (t, serverType) {
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client) if (serverType === 'ws') common.mockWebsocketTracker(client)
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.start() client.start()
client.once('update', function () { client.once('update', () => {
t.pass('client received response to "start" message') t.pass('client received response to "start" message')
client.stop() client.stop()
client.on('update', function () { t.fail('client should not receive update after destroy is called') }) client.on('update', () => { t.fail('client should not receive update after destroy is called') })
// Call destroy() in the same tick as stop(), but the message should still // Call destroy() in the same tick as stop(), but the message should still
// be received by the server, though obviously the client won't receive the // be received by the server, though obviously the client won't receive the
// response. // response.
client.destroy() client.destroy()
server.once('stop', function (peer, params) { server.once('stop', (peer, params) => {
t.pass('server received "stop" message') t.pass('server received "stop" message')
setTimeout(function () { setTimeout(() => {
// give the websocket server time to finish in progress (stream) messages // give the websocket server time to finish in progress (stream) messages
// to peers // to peers
server.close() server.close()
@ -144,22 +144,22 @@ function testClientStopDestroy (t, serverType) {
}) })
} }
test('http: client.stop(); client.destroy()', function (t) { test('http: client.stop(); client.destroy()', t => {
testClientStopDestroy(t, 'http') testClientStopDestroy(t, 'http')
}) })
test('udp: client.stop(); client.destroy()', function (t) { test('udp: client.stop(); client.destroy()', t => {
testClientStopDestroy(t, 'udp') testClientStopDestroy(t, 'udp')
}) })
test('ws: client.stop(); client.destroy()', function (t) { test('ws: client.stop(); client.destroy()', t => {
testClientStopDestroy(t, 'ws') testClientStopDestroy(t, 'ws')
}) })
function testClientUpdate (t, serverType) { function testClientUpdate (t, serverType) {
t.plan(4) t.plan(4)
common.createServer(t, serverType, function (server, announceUrl) { common.createServer(t, serverType, (server, announceUrl) => {
const client = new Client({ const client = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -169,25 +169,25 @@ function testClientUpdate (t, serverType) {
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client) if (serverType === 'ws') common.mockWebsocketTracker(client)
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.setInterval(500) client.setInterval(500)
client.start() client.start()
client.once('update', function () { client.once('update', () => {
client.setInterval(500) client.setInterval(500)
// after interval, we should get another update // after interval, we should get another update
client.once('update', function (data) { client.once('update', data => {
// received an update! // received an update!
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(typeof data.complete, 'number') t.equal(typeof data.complete, 'number')
t.equal(typeof data.incomplete, 'number') t.equal(typeof data.incomplete, 'number')
client.stop() client.stop()
client.once('update', function () { client.once('update', () => {
t.pass('got response to stop') t.pass('got response to stop')
server.close() server.close()
client.destroy() client.destroy()
@ -197,22 +197,22 @@ function testClientUpdate (t, serverType) {
}) })
} }
test('http: client.update()', function (t) { test('http: client.update()', t => {
testClientUpdate(t, 'http') testClientUpdate(t, 'http')
}) })
test('udp: client.update()', function (t) { test('udp: client.update()', t => {
testClientUpdate(t, 'udp') testClientUpdate(t, 'udp')
}) })
test('ws: client.update()', function (t) { test('ws: client.update()', t => {
testClientUpdate(t, 'ws') testClientUpdate(t, 'ws')
}) })
function testClientScrape (t, serverType) { function testClientScrape (t, serverType) {
t.plan(4) t.plan(4)
common.createServer(t, serverType, function (server, announceUrl) { common.createServer(t, serverType, (server, announceUrl) => {
const client = new Client({ const client = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -222,10 +222,10 @@ function testClientScrape (t, serverType) {
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client) if (serverType === 'ws') common.mockWebsocketTracker(client)
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.once('scrape', function (data) { client.once('scrape', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(typeof data.complete, 'number') t.equal(typeof data.complete, 'number')
t.equal(typeof data.incomplete, 'number') t.equal(typeof data.incomplete, 'number')
@ -239,22 +239,22 @@ function testClientScrape (t, serverType) {
}) })
} }
test('http: client.scrape()', function (t) { test('http: client.scrape()', t => {
testClientScrape(t, 'http') testClientScrape(t, 'http')
}) })
test('udp: client.scrape()', function (t) { test('udp: client.scrape()', t => {
testClientScrape(t, 'udp') testClientScrape(t, 'udp')
}) })
test('ws: client.scrape()', function (t) { test('ws: client.scrape()', t => {
testClientScrape(t, 'ws') testClientScrape(t, 'ws')
}) })
function testClientAnnounceWithParams (t, serverType) { function testClientAnnounceWithParams (t, serverType) {
t.plan(5) t.plan(5)
common.createServer(t, serverType, function (server, announceUrl) { common.createServer(t, serverType, (server, announceUrl) => {
const client = new Client({ const client = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -263,22 +263,22 @@ function testClientAnnounceWithParams (t, serverType) {
wrtc: {} wrtc: {}
}) })
server.on('start', function (peer, params) { server.on('start', (peer, params) => {
t.equal(params.testParam, 'this is a test') t.equal(params.testParam, 'this is a test')
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client) if (serverType === 'ws') common.mockWebsocketTracker(client)
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.once('update', function (data) { client.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(typeof data.complete, 'number') t.equal(typeof data.complete, 'number')
t.equal(typeof data.incomplete, 'number') t.equal(typeof data.incomplete, 'number')
client.stop() client.stop()
client.once('update', function () { client.once('update', () => {
t.pass('got response to stop') t.pass('got response to stop')
server.close() server.close()
client.destroy() client.destroy()
@ -291,24 +291,24 @@ function testClientAnnounceWithParams (t, serverType) {
}) })
} }
test('http: client.announce() with params', function (t) { test('http: client.announce() with params', t => {
testClientAnnounceWithParams(t, 'http') testClientAnnounceWithParams(t, 'http')
}) })
test('ws: client.announce() with params', function (t) { test('ws: client.announce() with params', t => {
testClientAnnounceWithParams(t, 'ws') testClientAnnounceWithParams(t, 'ws')
}) })
function testClientGetAnnounceOpts (t, serverType) { function testClientGetAnnounceOpts (t, serverType) {
t.plan(5) t.plan(5)
common.createServer(t, serverType, function (server, announceUrl) { common.createServer(t, serverType, (server, announceUrl) => {
const client = new Client({ const client = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
peerId: peerId1, peerId: peerId1,
port, port,
getAnnounceOpts: function () { getAnnounceOpts () {
return { return {
testParam: 'this is a test' testParam: 'this is a test'
} }
@ -316,22 +316,22 @@ function testClientGetAnnounceOpts (t, serverType) {
wrtc: {} wrtc: {}
}) })
server.on('start', function (peer, params) { server.on('start', (peer, params) => {
t.equal(params.testParam, 'this is a test') t.equal(params.testParam, 'this is a test')
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client) if (serverType === 'ws') common.mockWebsocketTracker(client)
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.once('update', function (data) { client.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(typeof data.complete, 'number') t.equal(typeof data.complete, 'number')
t.equal(typeof data.incomplete, 'number') t.equal(typeof data.incomplete, 'number')
client.stop() client.stop()
client.once('update', function () { client.once('update', () => {
t.pass('got response to stop') t.pass('got response to stop')
server.close() server.close()
client.destroy() client.destroy()
@ -342,18 +342,18 @@ function testClientGetAnnounceOpts (t, serverType) {
}) })
} }
test('http: client `opts.getAnnounceOpts`', function (t) { test('http: client `opts.getAnnounceOpts`', t => {
testClientGetAnnounceOpts(t, 'http') testClientGetAnnounceOpts(t, 'http')
}) })
test('ws: client `opts.getAnnounceOpts`', function (t) { test('ws: client `opts.getAnnounceOpts`', t => {
testClientGetAnnounceOpts(t, 'ws') testClientGetAnnounceOpts(t, 'ws')
}) })
function testClientAnnounceWithNumWant (t, serverType) { function testClientAnnounceWithNumWant (t, serverType) {
t.plan(4) t.plan(4)
common.createServer(t, serverType, function (server, announceUrl) { common.createServer(t, serverType, (server, announceUrl) => {
const client1 = new Client({ const client1 = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
announce: [announceUrl], announce: [announceUrl],
@ -363,11 +363,11 @@ function testClientAnnounceWithNumWant (t, serverType) {
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client1) if (serverType === 'ws') common.mockWebsocketTracker(client1)
client1.on('error', function (err) { t.error(err) }) client1.on('error', err => { t.error(err) })
client1.on('warning', function (err) { t.error(err) }) client1.on('warning', err => { t.error(err) })
client1.start() client1.start()
client1.once('update', function () { client1.once('update', () => {
const client2 = new Client({ const client2 = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -377,11 +377,11 @@ function testClientAnnounceWithNumWant (t, serverType) {
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client2) if (serverType === 'ws') common.mockWebsocketTracker(client2)
client2.on('error', function (err) { t.error(err) }) client2.on('error', err => { t.error(err) })
client2.on('warning', function (err) { t.error(err) }) client2.on('warning', err => { t.error(err) })
client2.start() client2.start()
client2.once('update', function () { client2.once('update', () => {
const client3 = new Client({ const client3 = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -391,11 +391,11 @@ function testClientAnnounceWithNumWant (t, serverType) {
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client3) if (serverType === 'ws') common.mockWebsocketTracker(client3)
client3.on('error', function (err) { t.error(err) }) client3.on('error', err => { t.error(err) })
client3.on('warning', function (err) { t.error(err) }) client3.on('warning', err => { t.error(err) })
client3.start({ numwant: 1 }) client3.start({ numwant: 1 })
client3.on('peer', function () { client3.on('peer', () => {
t.pass('got one peer (this should only fire once)') t.pass('got one peer (this should only fire once)')
let num = 3 let num = 3
@ -405,19 +405,19 @@ function testClientAnnounceWithNumWant (t, serverType) {
} }
client1.stop() client1.stop()
client1.once('update', function () { client1.once('update', () => {
t.pass('got response to stop (client1)') t.pass('got response to stop (client1)')
client1.destroy() client1.destroy()
tryCloseServer() tryCloseServer()
}) })
client2.stop() client2.stop()
client2.once('update', function () { client2.once('update', () => {
t.pass('got response to stop (client2)') t.pass('got response to stop (client2)')
client2.destroy() client2.destroy()
tryCloseServer() tryCloseServer()
}) })
client3.stop() client3.stop()
client3.once('update', function () { client3.once('update', () => {
t.pass('got response to stop (client3)') t.pass('got response to stop (client3)')
client3.destroy() client3.destroy()
tryCloseServer() tryCloseServer()
@ -428,21 +428,21 @@ function testClientAnnounceWithNumWant (t, serverType) {
}) })
} }
test('http: client announce with numwant', function (t) { test('http: client announce with numwant', t => {
testClientAnnounceWithNumWant(t, 'http') testClientAnnounceWithNumWant(t, 'http')
}) })
test('udp: client announce with numwant', function (t) { test('udp: client announce with numwant', t => {
testClientAnnounceWithNumWant(t, 'udp') testClientAnnounceWithNumWant(t, 'udp')
}) })
test('http: userAgent', function (t) { test('http: userAgent', t => {
t.plan(2) t.plan(2)
common.createServer(t, 'http', function (server, announceUrl) { common.createServer(t, 'http', (server, announceUrl) => {
// Confirm that user-agent header is set // Confirm that user-agent header is set
server.http.on('request', function (req, res) { server.http.on('request', (req, res) => {
t.ok(req.headers['user-agent'].indexOf('WebTorrent') !== -1) t.ok(req.headers['user-agent'].includes('WebTorrent'))
}) })
const client = new Client({ const client = new Client({
@ -454,10 +454,10 @@ test('http: userAgent', function (t) {
wrtc: {} wrtc: {}
}) })
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.once('update', function (data) { client.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
server.close() server.close()
@ -471,7 +471,7 @@ test('http: userAgent', function (t) {
function testSupportedTracker (t, serverType) { function testSupportedTracker (t, serverType) {
t.plan(1) t.plan(1)
common.createServer(t, serverType, function (server, announceUrl) { common.createServer(t, serverType, (server, announceUrl) => {
const client = new Client({ const client = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -481,12 +481,12 @@ function testSupportedTracker (t, serverType) {
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client) if (serverType === 'ws') common.mockWebsocketTracker(client)
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.start() client.start()
client.once('update', function (data) { client.once('update', data => {
t.pass('tracker is valid') t.pass('tracker is valid')
server.close() server.close()
@ -495,15 +495,15 @@ function testSupportedTracker (t, serverType) {
}) })
} }
test('http: valid tracker port', function (t) { test('http: valid tracker port', t => {
testSupportedTracker(t, 'http') testSupportedTracker(t, 'http')
}) })
test('udp: valid tracker port', function (t) { test('udp: valid tracker port', t => {
testSupportedTracker(t, 'udp') testSupportedTracker(t, 'udp')
}) })
test('ws: valid tracker port', function (t) { test('ws: valid tracker port', t => {
testSupportedTracker(t, 'ws') testSupportedTracker(t, 'ws')
}) })
@ -518,50 +518,50 @@ function testUnsupportedTracker (t, announceUrl) {
wrtc: {} wrtc: {}
}) })
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { client.on('warning', err => {
t.ok(err.message.includes('tracker'), 'got warning') t.ok(err.message.includes('tracker'), 'got warning')
client.destroy() client.destroy()
}) })
} }
test('unsupported tracker protocol', function (t) { test('unsupported tracker protocol', t => {
testUnsupportedTracker(t, 'badprotocol://127.0.0.1:8080/announce') testUnsupportedTracker(t, 'badprotocol://127.0.0.1:8080/announce')
}) })
test('http: invalid tracker port', function (t) { test('http: invalid tracker port', t => {
testUnsupportedTracker(t, 'http://127.0.0.1:69691337/announce') testUnsupportedTracker(t, 'http://127.0.0.1:69691337/announce')
}) })
test('http: invalid tracker url', function (t) { test('http: invalid tracker url', t => {
testUnsupportedTracker(t, 'http:') testUnsupportedTracker(t, 'http:')
}) })
test('http: invalid tracker url with slash', function (t) { test('http: invalid tracker url with slash', t => {
testUnsupportedTracker(t, 'http://') testUnsupportedTracker(t, 'http://')
}) })
test('udp: invalid tracker port', function (t) { test('udp: invalid tracker port', t => {
testUnsupportedTracker(t, 'udp://127.0.0.1:69691337') testUnsupportedTracker(t, 'udp://127.0.0.1:69691337')
}) })
test('udp: invalid tracker url', function (t) { test('udp: invalid tracker url', t => {
testUnsupportedTracker(t, 'udp:') testUnsupportedTracker(t, 'udp:')
}) })
test('udp: invalid tracker url with slash', function (t) { test('udp: invalid tracker url with slash', t => {
testUnsupportedTracker(t, 'udp://') testUnsupportedTracker(t, 'udp://')
}) })
test('ws: invalid tracker port', function (t) { test('ws: invalid tracker port', t => {
testUnsupportedTracker(t, 'ws://127.0.0.1:69691337') testUnsupportedTracker(t, 'ws://127.0.0.1:69691337')
}) })
test('ws: invalid tracker url', function (t) { test('ws: invalid tracker url', t => {
testUnsupportedTracker(t, 'ws:') testUnsupportedTracker(t, 'ws:')
}) })
test('ws: invalid tracker url with slash', function (t) { test('ws: invalid tracker url with slash', t => {
testUnsupportedTracker(t, 'ws://') testUnsupportedTracker(t, 'ws://')
}) })

View File

@ -1,6 +1,6 @@
const Server = require('../').Server const Server = require('../').Server
exports.createServer = function (t, opts, cb) { exports.createServer = (t, opts, cb) => {
if (typeof opts === 'string') opts = { serverType: opts } if (typeof opts === 'string') opts = { serverType: opts }
opts.http = (opts.serverType === 'http') opts.http = (opts.serverType === 'http')
@ -9,31 +9,31 @@ exports.createServer = function (t, opts, cb) {
const server = new Server(opts) const server = new Server(opts)
server.on('error', function (err) { t.error(err) }) server.on('error', err => { t.error(err) })
server.on('warning', function (err) { t.error(err) }) server.on('warning', err => { t.error(err) })
server.listen(0, function () { server.listen(0, () => {
const port = server[opts.serverType].address().port const port = server[opts.serverType].address().port
let announceUrl let announceUrl
if (opts.serverType === 'http') { if (opts.serverType === 'http') {
announceUrl = 'http://127.0.0.1:' + port + '/announce' announceUrl = `http://127.0.0.1:${port}/announce`
} else if (opts.serverType === 'udp') { } else if (opts.serverType === 'udp') {
announceUrl = 'udp://127.0.0.1:' + port announceUrl = `udp://127.0.0.1:${port}`
} else if (opts.serverType === 'ws') { } else if (opts.serverType === 'ws') {
announceUrl = 'ws://127.0.0.1:' + port announceUrl = `ws://127.0.0.1:${port}`
} }
cb(server, announceUrl) cb(server, announceUrl)
}) })
} }
exports.mockWebsocketTracker = function (client) { exports.mockWebsocketTracker = client => {
client._trackers[0]._generateOffers = function (numwant, cb) { client._trackers[0]._generateOffers = (numwant, cb) => {
const offers = [] const offers = []
for (let i = 0; i < numwant; i++) { for (let i = 0; i < numwant; i++) {
offers.push({ fake_offer: 'fake_offer_' + i }) offers.push({ fake_offer: `fake_offer_${i}` })
} }
process.nextTick(function () { process.nextTick(() => {
cb(offers) cb(offers)
}) })
} }

View File

@ -9,7 +9,7 @@ const port = 6881
function testNoEventsAfterDestroy (t, serverType) { function testNoEventsAfterDestroy (t, serverType) {
t.plan(1) t.plan(1)
common.createServer(t, serverType, function (server, announceUrl) { common.createServer(t, serverType, (server, announceUrl) => {
const client = new Client({ const client = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -19,10 +19,10 @@ function testNoEventsAfterDestroy (t, serverType) {
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client) if (serverType === 'ws') common.mockWebsocketTracker(client)
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.once('update', function () { client.once('update', () => {
t.fail('no "update" event should fire, since client is destroyed') t.fail('no "update" event should fire, since client is destroyed')
}) })
@ -30,21 +30,21 @@ function testNoEventsAfterDestroy (t, serverType) {
client.update() client.update()
client.destroy() client.destroy()
setTimeout(function () { setTimeout(() => {
t.pass('wait to see if any events are fired') t.pass('wait to see if any events are fired')
server.close() server.close()
}, 1000) }, 1000)
}) })
} }
test('http: no "update" events after destroy()', function (t) { test('http: no "update" events after destroy()', t => {
testNoEventsAfterDestroy(t, 'http') testNoEventsAfterDestroy(t, 'http')
}) })
test('udp: no "update" events after destroy()', function (t) { test('udp: no "update" events after destroy()', t => {
testNoEventsAfterDestroy(t, 'udp') testNoEventsAfterDestroy(t, 'udp')
}) })
test('ws: no "update" events after destroy()', function (t) { test('ws: no "update" events after destroy()', t => {
testNoEventsAfterDestroy(t, 'ws') testNoEventsAfterDestroy(t, 'ws')
}) })

View File

@ -20,11 +20,11 @@ function serverTest (t, serverType, serverFamily) {
peersCacheLength: 2 // LRU cache can only contain a max of 2 peers peersCacheLength: 2 // LRU cache can only contain a max of 2 peers
} }
common.createServer(t, opts, function (server) { common.createServer(t, opts, server => {
// Not using announceUrl param from `common.createServer()` since we // Not using announceUrl param from `common.createServer()` since we
// want to control IPv4 vs IPv6. // want to control IPv4 vs IPv6.
const port = server[serverType].address().port const port = server[serverType].address().port
const announceUrl = serverType + '://' + hostname + ':' + port + '/announce' const announceUrl = `${serverType}://${hostname}:${port}/announce`
const client1 = new Client({ const client1 = new Client({
infoHash, infoHash,
@ -37,7 +37,7 @@ function serverTest (t, serverType, serverFamily) {
client1.start() client1.start()
client1.once('update', function (data) { client1.once('update', data => {
const client2 = new Client({ const client2 = new Client({
infoHash, infoHash,
announce: [announceUrl], announce: [announceUrl],
@ -49,15 +49,15 @@ function serverTest (t, serverType, serverFamily) {
client2.start() client2.start()
client2.once('update', function (data) { client2.once('update', data => {
server.getSwarm(infoHash, function (err, swarm) { server.getSwarm(infoHash, (err, swarm) => {
t.error(err) t.error(err)
t.equal(swarm.complete + swarm.incomplete, 2) t.equal(swarm.complete + swarm.incomplete, 2)
// Ensure that first peer is evicted when a third one is added // Ensure that first peer is evicted when a third one is added
let evicted = false let evicted = false
swarm.peers.once('evict', function (evictedPeer) { swarm.peers.once('evict', evictedPeer => {
t.equal(evictedPeer.value.peerId, peerId.toString('hex')) t.equal(evictedPeer.value.peerId, peerId.toString('hex'))
t.equal(swarm.complete + swarm.incomplete, 2) t.equal(swarm.complete + swarm.incomplete, 2)
evicted = true evicted = true
@ -74,23 +74,23 @@ function serverTest (t, serverType, serverFamily) {
client3.start() client3.start()
client3.once('update', function (data) { client3.once('update', data => {
t.ok(evicted, 'client1 was evicted from server before client3 gets response') t.ok(evicted, 'client1 was evicted from server before client3 gets response')
t.equal(swarm.complete + swarm.incomplete, 2) t.equal(swarm.complete + swarm.incomplete, 2)
client1.destroy(function () { client1.destroy(() => {
t.pass('client1 destroyed') t.pass('client1 destroyed')
}) })
client2.destroy(function () { client2.destroy(() => {
t.pass('client3 destroyed') t.pass('client3 destroyed')
}) })
client3.destroy(function () { client3.destroy(() => {
t.pass('client3 destroyed') t.pass('client3 destroyed')
}) })
server.close(function () { server.close(() => {
t.pass('server destroyed') t.pass('server destroyed')
}) })
}) })
@ -100,18 +100,18 @@ function serverTest (t, serverType, serverFamily) {
}) })
} }
test('evict: ipv4 server', function (t) { test('evict: ipv4 server', t => {
serverTest(t, 'http', 'inet') serverTest(t, 'http', 'inet')
}) })
test('evict: http ipv6 server', function (t) { test('evict: http ipv6 server', t => {
serverTest(t, 'http', 'inet6') serverTest(t, 'http', 'inet6')
}) })
test('evict: udp server', function (t) { test('evict: udp server', t => {
serverTest(t, 'udp', 'inet') serverTest(t, 'udp', 'inet')
}) })
test('evict: ws server', function (t) { test('evict: ws server', t => {
serverTest(t, 'ws', 'inet') serverTest(t, 'ws', 'inet')
}) })

View File

@ -9,8 +9,8 @@ function testFilterOption (t, serverType) {
t.plan(8) t.plan(8)
const opts = { serverType } // this is test-suite-only option const opts = { serverType } // this is test-suite-only option
opts.filter = function (infoHash, params, cb) { opts.filter = (infoHash, params, cb) => {
process.nextTick(function () { process.nextTick(() => {
if (infoHash === fixtures.alice.parsedTorrent.infoHash) { if (infoHash === fixtures.alice.parsedTorrent.infoHash) {
cb(new Error('disallowed info_hash (Alice)')) cb(new Error('disallowed info_hash (Alice)'))
} else { } else {
@ -19,7 +19,7 @@ function testFilterOption (t, serverType) {
}) })
} }
common.createServer(t, opts, function (server, announceUrl) { common.createServer(t, opts, (server, announceUrl) => {
const client1 = new Client({ const client1 = new Client({
infoHash: fixtures.alice.parsedTorrent.infoHash, infoHash: fixtures.alice.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -28,13 +28,13 @@ function testFilterOption (t, serverType) {
wrtc: {} wrtc: {}
}) })
client1.on('error', function (err) { t.error(err) }) client1.on('error', err => { t.error(err) })
if (serverType === 'ws') common.mockWebsocketTracker(client1) if (serverType === 'ws') common.mockWebsocketTracker(client1)
client1.once('warning', function (err) { client1.once('warning', err => {
t.ok(err.message.includes('disallowed info_hash (Alice)'), 'got client warning') t.ok(err.message.includes('disallowed info_hash (Alice)'), 'got client warning')
client1.destroy(function () { client1.destroy(() => {
t.pass('client1 destroyed') t.pass('client1 destroyed')
const client2 = new Client({ const client2 = new Client({
@ -46,16 +46,16 @@ function testFilterOption (t, serverType) {
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client2) if (serverType === 'ws') common.mockWebsocketTracker(client2)
client2.on('error', function (err) { t.error(err) }) client2.on('error', err => { t.error(err) })
client2.on('warning', function (err) { t.error(err) }) client2.on('warning', err => { t.error(err) })
client2.on('update', function () { client2.on('update', () => {
t.pass('got announce') t.pass('got announce')
client2.destroy(function () { t.pass('client2 destroyed') }) client2.destroy(() => { t.pass('client2 destroyed') })
server.close(function () { t.pass('server closed') }) server.close(() => { t.pass('server closed') })
}) })
server.on('start', function () { server.on('start', () => {
t.equal(Object.keys(server.torrents).length, 1) t.equal(Object.keys(server.torrents).length, 1)
}) })
@ -64,7 +64,7 @@ function testFilterOption (t, serverType) {
}) })
server.removeAllListeners('warning') server.removeAllListeners('warning')
server.once('warning', function (err) { server.once('warning', err => {
t.ok(err.message.includes('disallowed info_hash (Alice)'), 'got server warning') t.ok(err.message.includes('disallowed info_hash (Alice)'), 'got server warning')
t.equal(Object.keys(server.torrents).length, 0) t.equal(Object.keys(server.torrents).length, 0)
}) })
@ -73,15 +73,15 @@ function testFilterOption (t, serverType) {
}) })
} }
test('http: filter option blocks tracker from tracking torrent', function (t) { test('http: filter option blocks tracker from tracking torrent', t => {
testFilterOption(t, 'http') testFilterOption(t, 'http')
}) })
test('udp: filter option blocks tracker from tracking torrent', function (t) { test('udp: filter option blocks tracker from tracking torrent', t => {
testFilterOption(t, 'udp') testFilterOption(t, 'udp')
}) })
test('ws: filter option blocks tracker from tracking torrent', function (t) { test('ws: filter option blocks tracker from tracking torrent', t => {
testFilterOption(t, 'ws') testFilterOption(t, 'ws')
}) })
@ -89,8 +89,8 @@ function testFilterCustomError (t, serverType) {
t.plan(8) t.plan(8)
const opts = { serverType } // this is test-suite-only option const opts = { serverType } // this is test-suite-only option
opts.filter = function (infoHash, params, cb) { opts.filter = (infoHash, params, cb) => {
process.nextTick(function () { process.nextTick(() => {
if (infoHash === fixtures.alice.parsedTorrent.infoHash) { if (infoHash === fixtures.alice.parsedTorrent.infoHash) {
cb(new Error('alice blocked')) cb(new Error('alice blocked'))
} else { } else {
@ -99,7 +99,7 @@ function testFilterCustomError (t, serverType) {
}) })
} }
common.createServer(t, opts, function (server, announceUrl) { common.createServer(t, opts, (server, announceUrl) => {
const client1 = new Client({ const client1 = new Client({
infoHash: fixtures.alice.parsedTorrent.infoHash, infoHash: fixtures.alice.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -108,13 +108,13 @@ function testFilterCustomError (t, serverType) {
wrtc: {} wrtc: {}
}) })
client1.on('error', function (err) { t.error(err) }) client1.on('error', err => { t.error(err) })
if (serverType === 'ws') common.mockWebsocketTracker(client1) if (serverType === 'ws') common.mockWebsocketTracker(client1)
client1.once('warning', function (err) { client1.once('warning', err => {
t.ok(/alice blocked/.test(err.message), 'got client warning') t.ok(/alice blocked/.test(err.message), 'got client warning')
client1.destroy(function () { client1.destroy(() => {
t.pass('client1 destroyed') t.pass('client1 destroyed')
const client2 = new Client({ const client2 = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
@ -125,16 +125,16 @@ function testFilterCustomError (t, serverType) {
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client2) if (serverType === 'ws') common.mockWebsocketTracker(client2)
client2.on('error', function (err) { t.error(err) }) client2.on('error', err => { t.error(err) })
client2.on('warning', function (err) { t.error(err) }) client2.on('warning', err => { t.error(err) })
client2.on('update', function () { client2.on('update', () => {
t.pass('got announce') t.pass('got announce')
client2.destroy(function () { t.pass('client2 destroyed') }) client2.destroy(() => { t.pass('client2 destroyed') })
server.close(function () { t.pass('server closed') }) server.close(() => { t.pass('server closed') })
}) })
server.on('start', function () { server.on('start', () => {
t.equal(Object.keys(server.torrents).length, 1) t.equal(Object.keys(server.torrents).length, 1)
}) })
@ -143,7 +143,7 @@ function testFilterCustomError (t, serverType) {
}) })
server.removeAllListeners('warning') server.removeAllListeners('warning')
server.once('warning', function (err) { server.once('warning', err => {
t.ok(/alice blocked/.test(err.message), 'got server warning') t.ok(/alice blocked/.test(err.message), 'got server warning')
t.equal(Object.keys(server.torrents).length, 0) t.equal(Object.keys(server.torrents).length, 0)
}) })
@ -152,14 +152,14 @@ function testFilterCustomError (t, serverType) {
}) })
} }
test('http: filter option with custom error', function (t) { test('http: filter option with custom error', t => {
testFilterCustomError(t, 'http') testFilterCustomError(t, 'http')
}) })
test('udp: filter option filter option with custom error', function (t) { test('udp: filter option filter option with custom error', t => {
testFilterCustomError(t, 'udp') testFilterCustomError(t, 'udp')
}) })
test('ws: filter option filter option with custom error', function (t) { test('ws: filter option filter option with custom error', t => {
testFilterCustomError(t, 'ws') testFilterCustomError(t, 'ws')
}) })

View File

@ -2,7 +2,7 @@ const common = require('../lib/common')
const test = require('tape') const test = require('tape')
// https://github.com/webtorrent/webtorrent/issues/196 // https://github.com/webtorrent/webtorrent/issues/196
test('encode special chars +* in http tracker urls', function (t) { test('encode special chars +* in http tracker urls', t => {
const q = Object.create(null) const q = Object.create(null)
q.info_hash = Buffer.from('a2a15537542b22925ad10486bf7a8b2a9c42f0d1', 'hex').toString('binary') q.info_hash = Buffer.from('a2a15537542b22925ad10486bf7a8b2a9c42f0d1', 'hex').toString('binary')

View File

@ -13,7 +13,7 @@ function testRequestHandler (t, serverType) {
class Swarm extends Server.Swarm { class Swarm extends Server.Swarm {
announce (params, cb) { announce (params, cb) {
super.announce(params, function (err, response) { super.announce(params, (err, response) => {
if (err) return cb(response) if (err) return cb(response)
response.complete = 246 response.complete = 246
response.extraData = 'hi' response.extraData = 'hi'
@ -25,11 +25,11 @@ function testRequestHandler (t, serverType) {
// Use a custom Swarm implementation for this test only // Use a custom Swarm implementation for this test only
const OldSwarm = Server.Swarm const OldSwarm = Server.Swarm
Server.Swarm = Swarm Server.Swarm = Swarm
t.on('end', function () { t.on('end', () => {
Server.Swarm = OldSwarm Server.Swarm = OldSwarm
}) })
common.createServer(t, opts, function (server, announceUrl) { common.createServer(t, opts, (server, announceUrl) => {
const client1 = new Client({ const client1 = new Client({
infoHash: fixtures.alice.parsedTorrent.infoHash, infoHash: fixtures.alice.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -38,22 +38,22 @@ function testRequestHandler (t, serverType) {
wrtc: {} wrtc: {}
}) })
client1.on('error', function (err) { t.error(err) }) client1.on('error', err => { t.error(err) })
if (serverType === 'ws') common.mockWebsocketTracker(client1) if (serverType === 'ws') common.mockWebsocketTracker(client1)
server.once('start', function () { server.once('start', () => {
t.pass('got start message from client1') t.pass('got start message from client1')
}) })
client1.once('update', function (data) { client1.once('update', data => {
t.equal(data.complete, 246) t.equal(data.complete, 246)
t.equal(data.extraData.toString(), 'hi') t.equal(data.extraData.toString(), 'hi')
client1.destroy(function () { client1.destroy(() => {
t.pass('client1 destroyed') t.pass('client1 destroyed')
}) })
server.close(function () { server.close(() => {
t.pass('server destroyed') t.pass('server destroyed')
}) })
}) })
@ -62,11 +62,11 @@ function testRequestHandler (t, serverType) {
}) })
} }
test('http: request handler option intercepts announce requests and responses', function (t) { test('http: request handler option intercepts announce requests and responses', t => {
testRequestHandler(t, 'http') testRequestHandler(t, 'http')
}) })
test('ws: request handler option intercepts announce requests and responses', function (t) { test('ws: request handler option intercepts announce requests and responses', t => {
testRequestHandler(t, 'ws') testRequestHandler(t, 'ws')
}) })

View File

@ -10,7 +10,7 @@ const test = require('tape')
const peerId = Buffer.from('01234567890123456789') const peerId = Buffer.from('01234567890123456789')
function testSingle (t, serverType) { function testSingle (t, serverType) {
commonTest.createServer(t, serverType, function (server, announceUrl) { commonTest.createServer(t, serverType, (server, announceUrl) => {
const client = new Client({ const client = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
announce: announceUrl, announce: announceUrl,
@ -20,51 +20,51 @@ function testSingle (t, serverType) {
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client) if (serverType === 'ws') common.mockWebsocketTracker(client)
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.scrape() client.scrape()
client.on('scrape', function (data) { client.on('scrape', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(data.infoHash, fixtures.leaves.parsedTorrent.infoHash) t.equal(data.infoHash, fixtures.leaves.parsedTorrent.infoHash)
t.equal(typeof data.complete, 'number') t.equal(typeof data.complete, 'number')
t.equal(typeof data.incomplete, 'number') t.equal(typeof data.incomplete, 'number')
t.equal(typeof data.downloaded, 'number') t.equal(typeof data.downloaded, 'number')
client.destroy() client.destroy()
server.close(function () { server.close(() => {
t.end() t.end()
}) })
}) })
}) })
} }
test('http: single info_hash scrape', function (t) { test('http: single info_hash scrape', t => {
testSingle(t, 'http') testSingle(t, 'http')
}) })
test('udp: single info_hash scrape', function (t) { test('udp: single info_hash scrape', t => {
testSingle(t, 'udp') testSingle(t, 'udp')
}) })
test('ws: single info_hash scrape', function (t) { test('ws: single info_hash scrape', t => {
testSingle(t, 'ws') testSingle(t, 'ws')
}) })
function clientScrapeStatic (t, serverType) { function clientScrapeStatic (t, serverType) {
commonTest.createServer(t, serverType, function (server, announceUrl) { commonTest.createServer(t, serverType, (server, announceUrl) => {
const client = Client.scrape({ const client = Client.scrape({
announce: announceUrl, announce: announceUrl,
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
wrtc: {} wrtc: {}
}, function (err, data) { }, (err, data) => {
t.error(err) t.error(err)
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(data.infoHash, fixtures.leaves.parsedTorrent.infoHash) t.equal(data.infoHash, fixtures.leaves.parsedTorrent.infoHash)
t.equal(typeof data.complete, 'number') t.equal(typeof data.complete, 'number')
t.equal(typeof data.incomplete, 'number') t.equal(typeof data.incomplete, 'number')
t.equal(typeof data.downloaded, 'number') t.equal(typeof data.downloaded, 'number')
server.close(function () { server.close(() => {
t.end() t.end()
}) })
}) })
@ -72,43 +72,43 @@ function clientScrapeStatic (t, serverType) {
}) })
} }
test('http: scrape using Client.scrape static method', function (t) { test('http: scrape using Client.scrape static method', t => {
clientScrapeStatic(t, 'http') clientScrapeStatic(t, 'http')
}) })
test('udp: scrape using Client.scrape static method', function (t) { test('udp: scrape using Client.scrape static method', t => {
clientScrapeStatic(t, 'udp') clientScrapeStatic(t, 'udp')
}) })
test('ws: scrape using Client.scrape static method', function (t) { test('ws: scrape using Client.scrape static method', t => {
clientScrapeStatic(t, 'ws') clientScrapeStatic(t, 'ws')
}) })
// Ensure the callback function gets called when an invalid url is passed // Ensure the callback function gets called when an invalid url is passed
function clientScrapeStaticInvalid (t, serverType) { function clientScrapeStaticInvalid (t, serverType) {
let announceUrl = serverType + '://invalid.lol' let announceUrl = `${serverType}://invalid.lol`
if (serverType === 'http') announceUrl += '/announce' if (serverType === 'http') announceUrl += '/announce'
const client = Client.scrape({ const client = Client.scrape({
announce: announceUrl, announce: announceUrl,
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
wrtc: {} wrtc: {}
}, function (err, data) { }, (err, data) => {
t.ok(err instanceof Error) t.ok(err instanceof Error)
t.end() t.end()
}) })
if (serverType === 'ws') common.mockWebsocketTracker(client) if (serverType === 'ws') common.mockWebsocketTracker(client)
} }
test('http: scrape using Client.scrape static method (invalid url)', function (t) { test('http: scrape using Client.scrape static method (invalid url)', t => {
clientScrapeStaticInvalid(t, 'http') clientScrapeStaticInvalid(t, 'http')
}) })
test('udp: scrape using Client.scrape static method (invalid url)', function (t) { test('udp: scrape using Client.scrape static method (invalid url)', t => {
clientScrapeStaticInvalid(t, 'udp') clientScrapeStaticInvalid(t, 'udp')
}) })
test('ws: scrape using Client.scrape static method (invalid url)', function (t) { test('ws: scrape using Client.scrape static method (invalid url)', t => {
clientScrapeStaticInvalid(t, 'ws') clientScrapeStaticInvalid(t, 'ws')
}) })
@ -116,11 +116,11 @@ function clientScrapeMulti (t, serverType) {
const infoHash1 = fixtures.leaves.parsedTorrent.infoHash const infoHash1 = fixtures.leaves.parsedTorrent.infoHash
const infoHash2 = fixtures.alice.parsedTorrent.infoHash const infoHash2 = fixtures.alice.parsedTorrent.infoHash
commonTest.createServer(t, serverType, function (server, announceUrl) { commonTest.createServer(t, serverType, (server, announceUrl) => {
Client.scrape({ Client.scrape({
infoHash: [infoHash1, infoHash2], infoHash: [infoHash1, infoHash2],
announce: announceUrl announce: announceUrl
}, function (err, results) { }, (err, results) => {
t.error(err) t.error(err)
t.equal(results[infoHash1].announce, announceUrl) t.equal(results[infoHash1].announce, announceUrl)
@ -135,35 +135,35 @@ function clientScrapeMulti (t, serverType) {
t.equal(typeof results[infoHash2].incomplete, 'number') t.equal(typeof results[infoHash2].incomplete, 'number')
t.equal(typeof results[infoHash2].downloaded, 'number') t.equal(typeof results[infoHash2].downloaded, 'number')
server.close(function () { server.close(() => {
t.end() t.end()
}) })
}) })
}) })
} }
test('http: MULTI scrape using Client.scrape static method', function (t) { test('http: MULTI scrape using Client.scrape static method', t => {
clientScrapeMulti(t, 'http') clientScrapeMulti(t, 'http')
}) })
test('udp: MULTI scrape using Client.scrape static method', function (t) { test('udp: MULTI scrape using Client.scrape static method', t => {
clientScrapeMulti(t, 'udp') clientScrapeMulti(t, 'udp')
}) })
test('server: multiple info_hash scrape (manual http request)', function (t) { test('server: multiple info_hash scrape (manual http request)', t => {
t.plan(13) t.plan(13)
const binaryInfoHash1 = commonLib.hexToBinary(fixtures.leaves.parsedTorrent.infoHash) const binaryInfoHash1 = commonLib.hexToBinary(fixtures.leaves.parsedTorrent.infoHash)
const binaryInfoHash2 = commonLib.hexToBinary(fixtures.alice.parsedTorrent.infoHash) const binaryInfoHash2 = commonLib.hexToBinary(fixtures.alice.parsedTorrent.infoHash)
commonTest.createServer(t, 'http', function (server, announceUrl) { commonTest.createServer(t, 'http', (server, announceUrl) => {
const scrapeUrl = announceUrl.replace('/announce', '/scrape') const scrapeUrl = announceUrl.replace('/announce', '/scrape')
const url = scrapeUrl + '?' + commonLib.querystringStringify({ const url = `${scrapeUrl}?${commonLib.querystringStringify({
info_hash: [binaryInfoHash1, binaryInfoHash2] info_hash: [binaryInfoHash1, binaryInfoHash2]
}) })}`
get.concat(url, function (err, res, data) { get.concat(url, (err, res, data) => {
t.error(err) t.error(err)
t.equal(res.statusCode, 200) t.equal(res.statusCode, 200)
@ -182,17 +182,17 @@ test('server: multiple info_hash scrape (manual http request)', function (t) {
t.equal(typeof data.files[binaryInfoHash2].incomplete, 'number') t.equal(typeof data.files[binaryInfoHash2].incomplete, 'number')
t.equal(typeof data.files[binaryInfoHash2].downloaded, 'number') t.equal(typeof data.files[binaryInfoHash2].downloaded, 'number')
server.close(function () { t.pass('server closed') }) server.close(() => { t.pass('server closed') })
}) })
}) })
}) })
test('server: all info_hash scrape (manual http request)', function (t) { test('server: all info_hash scrape (manual http request)', t => {
t.plan(10) t.plan(10)
const binaryInfoHash = commonLib.hexToBinary(fixtures.leaves.parsedTorrent.infoHash) const binaryInfoHash = commonLib.hexToBinary(fixtures.leaves.parsedTorrent.infoHash)
commonTest.createServer(t, 'http', function (server, announceUrl) { commonTest.createServer(t, 'http', (server, announceUrl) => {
const scrapeUrl = announceUrl.replace('/announce', '/scrape') const scrapeUrl = announceUrl.replace('/announce', '/scrape')
// announce a torrent to the tracker // announce a torrent to the tracker
@ -202,14 +202,14 @@ test('server: all info_hash scrape (manual http request)', function (t) {
peerId, peerId,
port: 6881 port: 6881
}) })
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.start() client.start()
server.once('start', function () { server.once('start', () => {
// now do a scrape of everything by omitting the info_hash param // now do a scrape of everything by omitting the info_hash param
get.concat(scrapeUrl, function (err, res, data) { get.concat(scrapeUrl, (err, res, data) => {
t.error(err) t.error(err)
t.equal(res.statusCode, 200) t.equal(res.statusCode, 200)
@ -222,8 +222,8 @@ test('server: all info_hash scrape (manual http request)', function (t) {
t.equal(typeof data.files[binaryInfoHash].incomplete, 'number') t.equal(typeof data.files[binaryInfoHash].incomplete, 'number')
t.equal(typeof data.files[binaryInfoHash].downloaded, 'number') t.equal(typeof data.files[binaryInfoHash].downloaded, 'number')
client.destroy(function () { t.pass('client destroyed') }) client.destroy(() => { t.pass('client destroyed') })
server.close(function () { t.pass('server closed') }) server.close(() => { t.pass('server closed') })
}) })
}) })
}) })

View File

@ -22,11 +22,11 @@ function serverTest (t, serverType, serverFamily) {
serverType serverType
} }
common.createServer(t, opts, function (server) { common.createServer(t, opts, server => {
// Not using announceUrl param from `common.createServer()` since we // Not using announceUrl param from `common.createServer()` since we
// want to control IPv4 vs IPv6. // want to control IPv4 vs IPv6.
const port = server[serverType].address().port const port = server[serverType].address().port
const announceUrl = serverType + '://' + hostname + ':' + port + '/announce' const announceUrl = `${serverType}://${hostname}:${port}/announce`
const client1 = new Client({ const client1 = new Client({
infoHash, infoHash,
@ -39,16 +39,16 @@ function serverTest (t, serverType, serverFamily) {
client1.start() client1.start()
server.once('start', function () { server.once('start', () => {
t.pass('got start message from client1') t.pass('got start message from client1')
}) })
client1.once('update', function (data) { client1.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(data.complete, 0) t.equal(data.complete, 0)
t.equal(data.incomplete, 1) t.equal(data.incomplete, 1)
server.getSwarm(infoHash, function (err, swarm) { server.getSwarm(infoHash, (err, swarm) => {
t.error(err) t.error(err)
t.equal(Object.keys(server.torrents).length, 1) t.equal(Object.keys(server.torrents).length, 1)
@ -58,7 +58,7 @@ function serverTest (t, serverType, serverFamily) {
const id = serverType === 'ws' const id = serverType === 'ws'
? peerId.toString('hex') ? peerId.toString('hex')
: hostname + ':6881' : `${hostname}:6881`
const peer = swarm.peers.peek(id) const peer = swarm.peers.peek(id)
t.equal(peer.type, serverType) t.equal(peer.type, serverType)
@ -75,14 +75,14 @@ function serverTest (t, serverType, serverFamily) {
client1.complete() client1.complete()
client1.once('update', function (data) { client1.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(data.complete, 1) t.equal(data.complete, 1)
t.equal(data.incomplete, 0) t.equal(data.incomplete, 0)
client1.scrape() client1.scrape()
client1.once('scrape', function (data) { client1.once('scrape', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(data.complete, 1) t.equal(data.complete, 1)
t.equal(data.incomplete, 0) t.equal(data.incomplete, 0)
@ -99,11 +99,11 @@ function serverTest (t, serverType, serverFamily) {
client2.start() client2.start()
server.once('start', function () { server.once('start', () => {
t.pass('got start message from client2') t.pass('got start message from client2')
}) })
client2.once('update', function (data) { client2.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(data.complete, 1) t.equal(data.complete, 1)
t.equal(data.incomplete, 1) t.equal(data.incomplete, 1)
@ -119,38 +119,38 @@ function serverTest (t, serverType, serverFamily) {
client3.start() client3.start()
server.once('start', function () { server.once('start', () => {
t.pass('got start message from client3') t.pass('got start message from client3')
}) })
client3.once('update', function (data) { client3.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(data.complete, 1) t.equal(data.complete, 1)
t.equal(data.incomplete, 2) t.equal(data.incomplete, 2)
client2.stop() client2.stop()
client2.once('update', function (data) { client2.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(data.complete, 1) t.equal(data.complete, 1)
t.equal(data.incomplete, 1) t.equal(data.incomplete, 1)
client2.destroy(function () { client2.destroy(() => {
t.pass('client2 destroyed') t.pass('client2 destroyed')
client3.stop() client3.stop()
client3.once('update', function (data) { client3.once('update', data => {
t.equal(data.announce, announceUrl) t.equal(data.announce, announceUrl)
t.equal(data.complete, 1) t.equal(data.complete, 1)
t.equal(data.incomplete, 0) t.equal(data.incomplete, 0)
client1.destroy(function () { client1.destroy(() => {
t.pass('client1 destroyed') t.pass('client1 destroyed')
}) })
client3.destroy(function () { client3.destroy(() => {
t.pass('client3 destroyed') t.pass('client3 destroyed')
}) })
server.close(function () { server.close(() => {
t.pass('server destroyed') t.pass('server destroyed')
}) })
}) })
@ -165,18 +165,18 @@ function serverTest (t, serverType, serverFamily) {
}) })
} }
test('http ipv4 server', function (t) { test('http ipv4 server', t => {
serverTest(t, 'http', 'inet') serverTest(t, 'http', 'inet')
}) })
test('http ipv6 server', function (t) { test('http ipv6 server', t => {
serverTest(t, 'http', 'inet6') serverTest(t, 'http', 'inet6')
}) })
test('udp server', function (t) { test('udp server', t => {
serverTest(t, 'udp', 'inet') serverTest(t, 'udp', 'inet')
}) })
test('ws server', function (t) { test('ws server', t => {
serverTest(t, 'ws', 'inet') serverTest(t, 'ws', 'inet')
}) })

View File

@ -9,9 +9,7 @@ const unknownPeerId = Buffer.from('01234567890123456789')
function parseHtml (html) { function parseHtml (html) {
const extractValue = /[^v^h](\d+)/ const extractValue = /[^v^h](\d+)/
const array = html.replace('torrents', '\n').split('\n').filter(function (line) { const array = html.replace('torrents', '\n').split('\n').filter(line => line && line.trim().length > 0).map(line => {
return line && line.trim().length > 0
}).map(function (line) {
const a = extractValue.exec(line) const a = extractValue.exec(line)
if (a) { if (a) {
return parseInt(a[1]) return parseInt(a[1])
@ -31,13 +29,13 @@ function parseHtml (html) {
} }
} }
test('server: get empty stats', function (t) { test('server: get empty stats', t => {
t.plan(11) t.plan(11)
commonTest.createServer(t, 'http', function (server, announceUrl) { commonTest.createServer(t, 'http', (server, announceUrl) => {
const url = announceUrl.replace('/announce', '/stats') const url = announceUrl.replace('/announce', '/stats')
get.concat(url, function (err, res, data) { get.concat(url, (err, res, data) => {
t.error(err) t.error(err)
const stats = parseHtml(data.toString()) const stats = parseHtml(data.toString())
@ -51,15 +49,15 @@ test('server: get empty stats', function (t) {
t.equal(stats.peersIPv4, 0) t.equal(stats.peersIPv4, 0)
t.equal(stats.peersIPv6, 0) t.equal(stats.peersIPv6, 0)
server.close(function () { t.pass('server closed') }) server.close(() => { t.pass('server closed') })
}) })
}) })
}) })
test('server: get empty stats with json header', function (t) { test('server: get empty stats with json header', t => {
t.plan(11) t.plan(11)
commonTest.createServer(t, 'http', function (server, announceUrl) { commonTest.createServer(t, 'http', (server, announceUrl) => {
const opts = { const opts = {
url: announceUrl.replace('/announce', '/stats'), url: announceUrl.replace('/announce', '/stats'),
headers: { headers: {
@ -68,7 +66,7 @@ test('server: get empty stats with json header', function (t) {
json: true json: true
} }
get.concat(opts, function (err, res, stats) { get.concat(opts, (err, res, stats) => {
t.error(err) t.error(err)
t.equal(res.statusCode, 200) t.equal(res.statusCode, 200)
@ -81,21 +79,21 @@ test('server: get empty stats with json header', function (t) {
t.equal(stats.peersIPv4, 0) t.equal(stats.peersIPv4, 0)
t.equal(stats.peersIPv6, 0) t.equal(stats.peersIPv6, 0)
server.close(function () { t.pass('server closed') }) server.close(() => { t.pass('server closed') })
}) })
}) })
}) })
test('server: get empty stats on stats.json', function (t) { test('server: get empty stats on stats.json', t => {
t.plan(11) t.plan(11)
commonTest.createServer(t, 'http', function (server, announceUrl) { commonTest.createServer(t, 'http', (server, announceUrl) => {
const opts = { const opts = {
url: announceUrl.replace('/announce', '/stats.json'), url: announceUrl.replace('/announce', '/stats.json'),
json: true json: true
} }
get.concat(opts, function (err, res, stats) { get.concat(opts, (err, res, stats) => {
t.error(err) t.error(err)
t.equal(res.statusCode, 200) t.equal(res.statusCode, 200)
@ -108,15 +106,15 @@ test('server: get empty stats on stats.json', function (t) {
t.equal(stats.peersIPv4, 0) t.equal(stats.peersIPv4, 0)
t.equal(stats.peersIPv6, 0) t.equal(stats.peersIPv6, 0)
server.close(function () { t.pass('server closed') }) server.close(() => { t.pass('server closed') })
}) })
}) })
}) })
test('server: get leecher stats.json', function (t) { test('server: get leecher stats.json', t => {
t.plan(11) t.plan(11)
commonTest.createServer(t, 'http', function (server, announceUrl) { commonTest.createServer(t, 'http', (server, announceUrl) => {
// announce a torrent to the tracker // announce a torrent to the tracker
const client = new Client({ const client = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
@ -124,18 +122,18 @@ test('server: get leecher stats.json', function (t) {
peerId, peerId,
port: 6881 port: 6881
}) })
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.start() client.start()
server.once('start', function () { server.once('start', () => {
const opts = { const opts = {
url: announceUrl.replace('/announce', '/stats.json'), url: announceUrl.replace('/announce', '/stats.json'),
json: true json: true
} }
get.concat(opts, function (err, res, stats) { get.concat(opts, (err, res, stats) => {
t.error(err) t.error(err)
t.equal(res.statusCode, 200) t.equal(res.statusCode, 200)
@ -147,17 +145,17 @@ test('server: get leecher stats.json', function (t) {
t.equal(stats.peersSeederAndLeecher, 0) t.equal(stats.peersSeederAndLeecher, 0)
t.equal(stats.clients.WebTorrent['0.91'], 1) t.equal(stats.clients.WebTorrent['0.91'], 1)
client.destroy(function () { t.pass('client destroyed') }) client.destroy(() => { t.pass('client destroyed') })
server.close(function () { t.pass('server closed') }) server.close(() => { t.pass('server closed') })
}) })
}) })
}) })
}) })
test('server: get leecher stats.json (unknown peerId)', function (t) { test('server: get leecher stats.json (unknown peerId)', t => {
t.plan(11) t.plan(11)
commonTest.createServer(t, 'http', function (server, announceUrl) { commonTest.createServer(t, 'http', (server, announceUrl) => {
// announce a torrent to the tracker // announce a torrent to the tracker
const client = new Client({ const client = new Client({
infoHash: fixtures.leaves.parsedTorrent.infoHash, infoHash: fixtures.leaves.parsedTorrent.infoHash,
@ -165,18 +163,18 @@ test('server: get leecher stats.json (unknown peerId)', function (t) {
peerId: unknownPeerId, peerId: unknownPeerId,
port: 6881 port: 6881
}) })
client.on('error', function (err) { t.error(err) }) client.on('error', err => { t.error(err) })
client.on('warning', function (err) { t.error(err) }) client.on('warning', err => { t.error(err) })
client.start() client.start()
server.once('start', function () { server.once('start', () => {
const opts = { const opts = {
url: announceUrl.replace('/announce', '/stats.json'), url: announceUrl.replace('/announce', '/stats.json'),
json: true json: true
} }
get.concat(opts, function (err, res, stats) { get.concat(opts, (err, res, stats) => {
t.error(err) t.error(err)
t.equal(res.statusCode, 200) t.equal(res.statusCode, 200)
@ -188,8 +186,8 @@ test('server: get leecher stats.json (unknown peerId)', function (t) {
t.equal(stats.peersSeederAndLeecher, 0) t.equal(stats.peersSeederAndLeecher, 0)
t.equal(stats.clients.unknown['01234567'], 1) t.equal(stats.clients.unknown['01234567'], 1)
client.destroy(function () { t.pass('client destroyed') }) client.destroy(() => { t.pass('client destroyed') })
server.close(function () { t.pass('server closed') }) server.close(() => { t.pass('server closed') })
}) })
}) })
}) })