Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modernize some lib files #1480

Merged
merged 3 commits into from Aug 24, 2018
Merged
Changes from all commits
Commits
File filter...
Filter file types
Jump to…
Jump to file or symbol
Failed to load files and symbols.

Always

Just for now

@@ -1,44 +1,41 @@
module.exports = Server

var arrayRemove = require('unordered-array-remove')
var http = require('http')
var mime = require('mime')
var pump = require('pump')
var rangeParser = require('range-parser')
var url = require('url')

function Server (torrent, opts) {
var server = http.createServer()
if (!opts) opts = {}
const arrayRemove = require('unordered-array-remove')
const http = require('http')
const mime = require('mime')
const pump = require('pump')
const rangeParser = require('range-parser')
const url = require('url')

function Server (torrent, opts = {}) {
const server = http.createServer()
if (!opts.origin) opts.origin = '*' // allow all origins by default

var sockets = []
var pendingReady = []
var closed = false
const sockets = []
const pendingReady = []
let closed = false

server.on('connection', onConnection)
server.on('request', onRequest)

var _close = server.close
server.close = function (cb) {
const _close = server.close
server.close = cb => {
closed = true
server.removeListener('connection', onConnection)
server.removeListener('request', onRequest)
while (pendingReady.length) {
var onReady = pendingReady.pop()
const onReady = pendingReady.pop()
torrent.removeListener('ready', onReady)
}
torrent = null
_close.call(server, cb)
}

server.destroy = function (cb) {
sockets.forEach(function (socket) {
server.destroy = cb => {
sockets.forEach(socket => {
socket.destroy()
})

// Only call `server.close` if user has not called it already
if (!cb) cb = function () {}
if (!cb) cb = () => {}
if (closed) process.nextTick(cb)
else server.close(cb)
}
@@ -68,13 +65,13 @@ function Server (torrent, opts) {
function onConnection (socket) {
socket.setTimeout(36000000)
sockets.push(socket)
socket.once('close', function () {
socket.once('close', () => {
arrayRemove(sockets, sockets.indexOf(socket))
})
}

function onRequest (req, res) {
var pathname = url.parse(req.url).pathname
const pathname = url.parse(req.url).pathname

if (pathname === '/favicon.ico') {
return serve404Page()
@@ -132,27 +129,24 @@ function Server (torrent, opts) {
return serveIndexPage()
}

var index = Number(pathname.split('/')[1])
const index = Number(pathname.split('/')[1])
if (Number.isNaN(index) || index >= torrent.files.length) {
return serve404Page()
}

var file = torrent.files[index]
const file = torrent.files[index]
serveFile(file)
}

function serveIndexPage () {
res.statusCode = 200
res.setHeader('Content-Type', 'text/html')

var listHtml = torrent.files.map(function (file, i) {
return '<li><a download="' + file.name + '" href="/' + i + '/' + file.name + '">' + file.path + '</a> ' +
'(' + file.length + ' bytes)</li>'
}).join('<br>')
const listHtml = torrent.files.map((file, i) => `<li><a download="${file.name}" href="/${i}/${file.name}">${file.path}</a> (${file.length} bytes)</li>`).join('<br>')

var html = getPageHTML(
torrent.name + ' - WebTorrent',
'<h1>' + torrent.name + '</h1><ol>' + listHtml + '</ol>'
const html = getPageHTML(
`${torrent.name} - WebTorrent`,
`<h1>${torrent.name}</h1><ol>${listHtml}</ol>`
)
res.end(html)
}
@@ -161,7 +155,7 @@ function Server (torrent, opts) {
res.statusCode = 404
res.setHeader('Content-Type', 'text/html')

var html = getPageHTML('404 - Not Found', '<h1>404 - Not Found</h1>')
const html = getPageHTML('404 - Not Found', '<h1>404 - Not Found</h1>')
res.end(html)
}

@@ -175,7 +169,7 @@ function Server (torrent, opts) {
// Set name of file (for "Save Page As..." dialog)
res.setHeader(
'Content-Disposition',
'inline; filename*=UTF-8\'\'' + encodeRFC5987(file.name)
`inline; filename*=UTF-8''${encodeRFC5987(file.name)}`
)

// Support DLNA streaming
@@ -187,7 +181,7 @@ function Server (torrent, opts) {

// `rangeParser` returns an array of ranges, or an error code (number) if
// there was an error parsing the range.
var range = rangeParser(file.length, req.headers.range || '')
let range = rangeParser(file.length, req.headers.range || '')

if (Array.isArray(range)) {
res.statusCode = 206 // indicates that range-request was understood
@@ -197,7 +191,7 @@ function Server (torrent, opts) {

res.setHeader(
'Content-Range',
'bytes ' + range.start + '-' + range.end + '/' + file.length
`bytes ${range.start}-${range.end}/${file.length}`
)
res.setHeader('Content-Length', range.end - range.start + 1)
} else {
@@ -215,7 +209,7 @@ function Server (torrent, opts) {
function serveMethodNotAllowed () {
res.statusCode = 405
res.setHeader('Content-Type', 'text/html')
var html = getPageHTML('405 - Method Not Allowed', '<h1>405 - Method Not Allowed</h1>')
const html = getPageHTML('405 - Method Not Allowed', '<h1>405 - Method Not Allowed</h1>')
res.end(html)
}
}
@@ -224,10 +218,7 @@ function Server (torrent, opts) {
}

function getPageHTML (title, pageHtml) {
return '<!DOCTYPE html><html lang="en"><head>' +
'<meta charset="utf-8">' +
'<title>' + title + '</title>' +
'</head><body>' + pageHtml + '</body></html>'
return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>${title}</title></head><body>${pageHtml}</body></html>`
}

// From https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
@@ -241,3 +232,5 @@ function encodeRFC5987 (str) {
// so we can allow for a little better readability over the wire: |`^
.replace(/%(?:7C|60|5E)/g, unescape)
}

module.exports = Server
@@ -1,10 +1,8 @@
module.exports = TCPPool

var arrayRemove = require('unordered-array-remove')
var debug = require('debug')('webtorrent:tcp-pool')
var net = require('net') // browser exclude
const arrayRemove = require('unordered-array-remove')
const debug = require('debug')('webtorrent:tcp-pool')
const net = require('net') // browser exclude

var Peer = require('./peer')
const Peer = require('./peer')

/**
* TCPPool
@@ -15,114 +13,116 @@ var Peer = require('./peer')
*
* @param {number} port
*/
function TCPPool (client) {
var self = this
debug('create tcp pool (port %s)', client.torrentPort)

self.server = net.createServer()
self._client = client
class TCPPool {
constructor (client) {
debug('create tcp pool (port %s)', client.torrentPort)

// Temporarily store incoming connections so they can be destroyed if the server is
// closed before the connection is passed off to a Torrent.
self._pendingConns = []
this.server = net.createServer()
this._client = client

self._onConnectionBound = function (conn) {
self._onConnection(conn)
}
// Temporarily store incoming connections so they can be destroyed if the server is
// closed before the connection is passed off to a Torrent.
this._pendingConns = []

self._onListening = function () {
self._client._onListening()
}
this._onConnectionBound = conn => {
this._onConnection(conn)
}

self._onError = function (err) {
self._client._destroy(err)
}
this._onListening = () => {
this._client._onListening()
}

self.server.on('connection', self._onConnectionBound)
self.server.on('listening', self._onListening)
self.server.on('error', self._onError)
this._onError = err => {
this._client._destroy(err)
}

self.server.listen(client.torrentPort)
}
this.server.on('connection', this._onConnectionBound)
this.server.on('listening', this._onListening)
this.server.on('error', this._onError)

/**
* Destroy this TCP pool.
* @param {function} cb
*/
TCPPool.prototype.destroy = function (cb) {
var self = this
debug('destroy tcp pool')

self.server.removeListener('connection', self._onConnectionBound)
self.server.removeListener('listening', self._onListening)
self.server.removeListener('error', self._onError)

// Destroy all open connection objects so server can close gracefully without waiting
// for connection timeout or remote peer to disconnect.
self._pendingConns.forEach(function (conn) {
conn.on('error', noop)
conn.destroy()
})

try {
self.server.close(cb)
} catch (err) {
if (cb) process.nextTick(cb)
this.server.listen(client.torrentPort)
}

self.server = null
self._client = null
self._pendingConns = null
}
/**
* Destroy this TCP pool.
* @param {function} cb
*/
destroy (cb) {
debug('destroy tcp pool')

this.server.removeListener('connection', this._onConnectionBound)
this.server.removeListener('listening', this._onListening)
this.server.removeListener('error', this._onError)

// Destroy all open connection objects so server can close gracefully without waiting
// for connection timeout or remote peer to disconnect.
this._pendingConns.forEach(conn => {
conn.on('error', noop)
conn.destroy()
})

try {
this.server.close(cb)
} catch (err) {
if (cb) process.nextTick(cb)
}

/**
* On incoming connections, we expect the remote peer to send a handshake first. Based
* on the infoHash in that handshake, route the peer to the right swarm.
*/
TCPPool.prototype._onConnection = function (conn) {
var self = this

// If the connection has already been closed before the `connect` event is fired,
// then `remoteAddress` will not be available, and we can't use this connection.
// - Node.js issue: https://github.com/nodejs/node-v0.x-archive/issues/7566
// - WebTorrent issue: https://github.com/webtorrent/webtorrent/issues/398
if (!conn.remoteAddress) {
conn.on('error', noop)
conn.destroy()
return
this.server = null
this._client = null
this._pendingConns = null
}

self._pendingConns.push(conn)
conn.once('close', cleanupPending)
/**
* On incoming connections, we expect the remote peer to send a handshake first. Based
* on the infoHash in that handshake, route the peer to the right swarm.
*/
_onConnection (conn) {
const self = this

// If the connection has already been closed before the `connect` event is fired,
// then `remoteAddress` will not be available, and we can't use this connection.
// - Node.js issue: https://github.com/nodejs/node-v0.x-archive/issues/7566
// - WebTorrent issue: https://github.com/webtorrent/webtorrent/issues/398
if (!conn.remoteAddress) {
conn.on('error', noop)
conn.destroy()
return
}

self._pendingConns.push(conn)
conn.once('close', cleanupPending)

var peer = Peer.createTCPIncomingPeer(conn)
const peer = Peer.createTCPIncomingPeer(conn)

var wire = peer.wire
wire.once('handshake', onHandshake)
const wire = peer.wire
wire.once('handshake', onHandshake)

function onHandshake (infoHash, peerId) {
cleanupPending()
function onHandshake (infoHash, peerId) {
cleanupPending()

var torrent = self._client.get(infoHash)
if (torrent) {
peer.swarm = torrent
torrent._addIncomingPeer(peer)
peer.onHandshake(infoHash, peerId)
} else {
var err = new Error(
'Unexpected info hash ' + infoHash + ' from incoming peer ' + peer.id
)
peer.destroy(err)
const torrent = self._client.get(infoHash)
if (torrent) {
peer.swarm = torrent
torrent._addIncomingPeer(peer)
peer.onHandshake(infoHash, peerId)
} else {
const err = new Error(
`Unexpected info hash ${infoHash} from incoming peer ${peer.id}`
)
peer.destroy(err)
}
}
}

function cleanupPending () {
conn.removeListener('close', cleanupPending)
wire.removeListener('handshake', onHandshake)
if (self._pendingConns) {
arrayRemove(self._pendingConns, self._pendingConns.indexOf(conn))
function cleanupPending () {
conn.removeListener('close', cleanupPending)
wire.removeListener('handshake', onHandshake)
if (self._pendingConns) {
arrayRemove(self._pendingConns, self._pendingConns.indexOf(conn))
}
}
}
}

function noop () {}

module.exports = TCPPool
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.