From bb07d4db0e213611899d834b022e00936172557e Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Mon, 26 Jan 2015 18:04:18 -0800 Subject: JavaScript Standard Style --- README.md | 10 +++++-- bin/cmd.js | 56 ++++++++++++++++++++++-------------- examples/browser-download.js | 45 +++++++++++++++-------------- examples/browser-seed.js | 24 ++++++++-------- examples/browser-stream-to-audio.js | 39 +++++++++++++------------ examples/browser-stream-to-video.js | 39 +++++++++++++------------ examples/node-save-to-file-system.js | 33 ++++++++++----------- lib/file-stream.js | 2 +- lib/fs-storage.js | 6 +++- lib/server.js | 5 +++- lib/storage.js | 28 ++++++++++-------- lib/torrent.js | 22 ++++++++------ test/cmd.js | 1 - test/download-dht-magnet.js | 3 +- test/download-dht-torrent.js | 3 +- test/storage.js | 9 +++--- 16 files changed, 179 insertions(+), 146 deletions(-) diff --git a/README.md b/README.md index 4d24927..77277d7 100644 --- a/README.md +++ b/README.md @@ -111,8 +111,9 @@ standards (no plugins, just HTML5 and WebRTC)! It's easy to get started! var WebTorrent = require('webtorrent') var client = new WebTorrent() +var magnetUri = '...' -client.add(magnet_uri, function (torrent) { +client.add(magnetUri, function (torrent) { // Got torrent metadata! console.log('Torrent info hash:', torrent.infoHash) @@ -155,8 +156,9 @@ dragDrop('body', function (files) { var WebTorrent = require('webtorrent') var client = new WebTorrent() +var magnetUri = '...' -client.add(magnet_uri, function (torrent) { +client.add(magnetUri, function (torrent) { // Got torrent metadata! console.log('Torrent info hash:', torrent.infoHash) @@ -395,7 +397,9 @@ Here is a usage example: ```js var client = new WebTorrent() -client.add(magnet_uri, function (torrent) { +var magnetUri = '...' + +client.add(magnetUri, function (torrent) { // create HTTP server for this torrent var server = torrent.createServer() server.listen(port) // start the server listening to a port diff --git a/bin/cmd.js b/bin/cmd.js index 05c0d89..73cc4e4 100755 --- a/bin/cmd.js +++ b/bin/cmd.js @@ -95,7 +95,8 @@ function HELP () { clivas.line('{bold:' + line.substring(0, 20) + '}{red:' + line.substring(20) + '}') }) - console.log(function () {/* + console.log(function () { + /* Usage: webtorrent [command] @@ -135,7 +136,8 @@ function HELP () { Please report bugs! https://github.com/feross/webtorrent/issues - */}.toString().split(/\n/).slice(1, -1).join('\n')) + */ + }.toString().split(/\n/).slice(2, -2).join('\n')) process.exit(0) } @@ -205,7 +207,7 @@ function DOWNLOAD (torrentId) { function updateMetadata () { var numPeers = torrent.swarm.numPeers clivas.clear() - clivas.line('{green:fetching torrent metadata from} {bold:'+numPeers+'} {green:peers}') + clivas.line('{green:fetching torrent metadata from} {bold:%s} {green:peers}', numPeers) } if (!argv.quiet && !argv.list) { @@ -235,7 +237,10 @@ function DOWNLOAD (torrentId) { if (argv.list) { torrent.files.forEach(function (file, i) { - clivas.line('{3+bold:'+i+'} : {magenta:'+file.name+'} {blue:('+prettyBytes(file.length)+')}') + clivas.line( + '{3+bold:%s} : {magenta:%s} {blue:(%s)}', + i, file.name, prettyBytes(file.length) + ) }) return done() } @@ -244,8 +249,9 @@ function DOWNLOAD (torrentId) { if (argv.quiet) return clivas.clear() clivas.line( - '{green:verifying existing torrent} {bold:'+Math.floor(data.percentDone)+'%} ' + - '({bold:'+Math.floor(data.percentVerified)+'%} {green:passed verification})' + '{green:verifying existing torrent} {bold:%s%} ({bold:%s%} {green:verified})', + Math.floor(data.percentDone), + Math.floor(data.percentVerified) ) }) @@ -256,9 +262,11 @@ function DOWNLOAD (torrentId) { return num + (wire.downloaded > 0) }, 0) clivas.line( - 'torrent downloaded {green:successfully} from ' + - '{bold:'+numActiveWires+'/'+torrent.swarm.wires.length+'} {green:peers} ' + - 'in {bold:'+getRuntime()+'s}!' + 'torrent downloaded {green:successfully} from {bold:%s/%s} {green:peers} ' + + 'in {bold:%ss}!', + numActiveWires, + torrent.swarm.wires.length, + getRuntime() ) } done() @@ -371,7 +379,7 @@ function DOWNLOAD (torrentId) { var xbmc = require('nodebmc') new xbmc.Browser() .on('deviceOn', function (device) { - device.play(href, function () {}) + device.play(href, function () {}) }) } @@ -409,7 +417,8 @@ function drawTorrent (torrent) { var linesremaining = clivas.height var peerslisted = 0 var speed = torrent.swarm.downloadSpeed() - var estimatedSecondsRemaining = Math.max(0, torrent.length - torrent.swarm.downloaded) / (speed > 0 ? speed : -1) + var estimatedSecondsRemaining = + Math.max(0, torrent.length - torrent.swarm.downloaded) / (speed > 0 ? speed : -1) var estimate = moment.duration(estimatedSecondsRemaining, 'seconds').humanize() clivas.clear() @@ -444,13 +453,13 @@ function drawTorrent (torrent) { for (var i = 0; i < pieces.length; i++) { var piece = pieces[i] if (piece.verified || piece.blocksWritten === 0) { - continue; + continue } var bar = '' for (var j = 0; j < piece.blocks.length; j++) { - bar += piece.blocks[j] ? '{green:█}' : '{red:█}'; + bar += piece.blocks[j] ? '{green:█}' : '{red:█}' } - clivas.line('{4+cyan:' + i + '} ' + bar); + clivas.line('{4+cyan:' + i + '} ' + bar) linesremaining -= 1 } clivas.line('{80:}') @@ -471,15 +480,18 @@ function drawTorrent (torrent) { var tags = [] if (wire.peerChoking) tags.push('choked') var reqStats = wire.requests.map(function (req) { - return req.piece; + return req.piece }) clivas.line( - '{3:' + progress + '} ' + - '{25+magenta:' + wire.remoteAddress + '} {10:'+prettyBytes(wire.downloaded)+'} ' + - '{10+cyan:' + prettyBytes(wire.downloadSpeed()) + '/s} ' + - '{10+red:' + prettyBytes(wire.uploadSpeed()) + '/s} ' + - '{15+grey:' + tags.join(', ') + '}' + - '{15+cyan:' + reqStats.join(' ') + '}' + '{3:%s} {25+magenta:%s} {10:%s} {10+cyan:%s/s} {10+red:%s/s} {15+grey:%s}' + + '{15+cyan:%s}', + progress, + wire.remoteAddress, + prettyBytes(wire.downloaded), + prettyBytes(wire.downloadSpeed()), + prettyBytes(wire.uploadSpeed()), + tags.join(', '), + reqStats.join(' ') ) peerslisted++ return linesremaining - peerslisted > 4 @@ -488,7 +500,7 @@ function drawTorrent (torrent) { if (torrent.swarm.wires.length > peerslisted) { clivas.line('{80:}') - clivas.line('... and '+(torrent.swarm.wires.length - peerslisted)+' more') + clivas.line('... and %s more', torrent.swarm.wires.length - peerslisted) } clivas.line('{80:}') diff --git a/examples/browser-download.js b/examples/browser-download.js index 3428f72..a60e3bd 100644 --- a/examples/browser-download.js +++ b/examples/browser-download.js @@ -1,22 +1,23 @@ -var WebTorrent = require('webtorrent') - -var client = new WebTorrent() - -client.add(magnet_uri, function (torrent) { - // Got torrent metadata! - console.log('Torrent info hash:', torrent.infoHash) - - torrent.files.forEach(function (file) { - // Get a url for each file - file.getBlobURL(function (err, url) { - if (err) throw err - - // Add a link to the page - var a = document.createElement('a') - a.download = file.name - a.href = url - a.textContent = 'Download ' + file.name - document.body.appendChild(a) - }) - }) -}) +var WebTorrent = require('webtorrent') + +var client = new WebTorrent() +var magnetUri = 'magnet:?xt=urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36' + +client.add(magnetUri, function (torrent) { + // Got torrent metadata! + console.log('Torrent info hash:', torrent.infoHash) + + torrent.files.forEach(function (file) { + // Get a url for each file + file.getBlobURL(function (err, url) { + if (err) throw err + + // Add a link to the page + var a = document.createElement('a') + a.download = file.name + a.href = url + a.textContent = 'Download ' + file.name + document.body.appendChild(a) + }) + }) +}) diff --git a/examples/browser-seed.js b/examples/browser-seed.js index 6a6d498..cad1061 100644 --- a/examples/browser-seed.js +++ b/examples/browser-seed.js @@ -1,12 +1,12 @@ -var dragDrop = require('drag-drop/buffer') -var WebTorrent = require('webtorrent') - -var client = new WebTorrent() - -// When user drops files on the browser, create a new torrent and start seeding it! -dragDrop('body', function (files) { - client.seed(files, function onTorrent (torrent) { - // Client is seeding the file! - console.log('Torrent info hash:', torrent.infoHash) - }) -}) +var dragDrop = require('drag-drop/buffer') +var WebTorrent = require('webtorrent') + +var client = new WebTorrent() + +// When user drops files on the browser, create a new torrent and start seeding it! +dragDrop('body', function (files) { + client.seed(files, function onTorrent (torrent) { + // Client is seeding the file! + console.log('Torrent info hash:', torrent.infoHash) + }) +}) diff --git a/examples/browser-stream-to-audio.js b/examples/browser-stream-to-audio.js index 84dfdfd..01c6499 100644 --- a/examples/browser-stream-to-audio.js +++ b/examples/browser-stream-to-audio.js @@ -1,19 +1,20 @@ -var WebTorrent = require('webtorrent') - -var client = new WebTorrent() - -client.add(magnet_uri, function (torrent) { - // Got torrent metadata! - console.log('Torrent info hash:', torrent.infoHash) - - // Let's say the first file is an mp3 audio file - var file = torrent.files[0] - - // Create an audio element - var audio = document.createElement('audio') - audio.controls = true - document.body.appendChild(audio) - - // Stream the audio into the audio tag - file.createReadStream().pipe(audio) -}) +var WebTorrent = require('webtorrent') + +var client = new WebTorrent() +var magnetUri = 'magnet:?xt=urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36' + +client.add(magnetUri, function (torrent) { + // Got torrent metadata! + console.log('Torrent info hash:', torrent.infoHash) + + // Let's say the first file is an mp3 audio file + var file = torrent.files[0] + + // Create an audio element + var audio = document.createElement('audio') + audio.controls = true + document.body.appendChild(audio) + + // Stream the audio into the audio tag + file.createReadStream().pipe(audio) +}) diff --git a/examples/browser-stream-to-video.js b/examples/browser-stream-to-video.js index 7943a64..e721cee 100644 --- a/examples/browser-stream-to-video.js +++ b/examples/browser-stream-to-video.js @@ -1,19 +1,20 @@ -var WebTorrent = require('webtorrent') - -var client = new WebTorrent() - -client.add(magnet_uri, function (torrent) { - // Got torrent metadata! - console.log('Torrent info hash:', torrent.infoHash) - - // Let's say the first file is a webm (vp8) or mp4 (h264) video... - var file = torrent.files[0] - - // Create a video element - var video = document.createElement('video') - video.controls = true - document.body.appendChild(video) - - // Stream the video into the video tag - file.createReadStream().pipe(video) -}) +var WebTorrent = require('webtorrent') + +var client = new WebTorrent() +var magnetUri = 'magnet:?xt=urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36' + +client.add(magnetUri, function (torrent) { + // Got torrent metadata! + console.log('Torrent info hash:', torrent.infoHash) + + // Let's say the first file is a webm (vp8) or mp4 (h264) video... + var file = torrent.files[0] + + // Create a video element + var video = document.createElement('video') + video.controls = true + document.body.appendChild(video) + + // Stream the video into the video tag + file.createReadStream().pipe(video) +}) diff --git a/examples/node-save-to-file-system.js b/examples/node-save-to-file-system.js index 5b33d0c..1d5e7e6 100644 --- a/examples/node-save-to-file-system.js +++ b/examples/node-save-to-file-system.js @@ -1,16 +1,17 @@ -var WebTorrent = require('webtorrent') -var fs = require('fs') - -var client = new WebTorrent() - -client.download(magnet_uri, function (torrent) { - // Got torrent metadata! - console.log('Torrent info hash:', torrent.infoHash) - - torrent.files.forEach(function (file) { - // Stream each file to the disk - var source = file.createReadStream() - var destination = fs.createWriteStream(file.name) - source.pipe(destination) - }) -}) +var WebTorrent = require('webtorrent') +var fs = require('fs') + +var client = new WebTorrent() +var magnetUri = 'magnet:?xt=urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36' + +client.download(magnetUri, function (torrent) { + // Got torrent metadata! + console.log('Torrent info hash:', torrent.infoHash) + + torrent.files.forEach(function (file) { + // Stream each file to the disk + var source = file.createReadStream() + var destination = fs.createWriteStream(file.name) + source.pipe(destination) + }) +}) diff --git a/lib/file-stream.js b/lib/file-stream.js index 2abfd61..a2b80a0 100644 --- a/lib/file-stream.js +++ b/lib/file-stream.js @@ -67,7 +67,7 @@ FileStream.prototype.notify = function () { var p = self._piece debug('before read %s', p) self._storage.read(self._piece++, function (err, buffer) { - debug('after read %s (buffer.length %s) (err %s)', p, buffer.length, (err && err.message) || err) + debug('after read %s (length %s) (err %s)', p, buffer.length, err && err.message) self._notifying = false if (self._destroyed) return diff --git a/lib/fs-storage.js b/lib/fs-storage.js index cd32d4e..504f142 100644 --- a/lib/fs-storage.js +++ b/lib/fs-storage.js @@ -136,7 +136,11 @@ FSStorage.prototype.readBlock = function (index, offset, length, cb) { } target.openRead(function (err, file) { - if (err) return (err === self.nonExistentError ? readFromNextFile(null, new Buffer(0)) : cb(err)) + if (err) { + return err === self.nonExistentError + ? readFromNextFile(null, new Buffer(0)) + : cb(err) + } file.read(offset, to - from, readFromNextFile) }) } diff --git a/lib/server.js b/lib/server.js index 1e659b1..4a8f9b4 100644 --- a/lib/server.js +++ b/lib/server.js @@ -59,7 +59,10 @@ module.exports = function Server (torrent, opts) { // Support DLNA streaming res.setHeader('transferMode.dlna.org', 'Streaming') - res.setHeader('contentFeatures.dlna.org', 'DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=017000 00000000000000000000000000') + res.setHeader( + 'contentFeatures.dlna.org', + 'DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=017000 00000000000000000000000000' + ) var range if (req.headers.range) { diff --git a/lib/storage.js b/lib/storage.js index 570ae08..e6f1417 100644 --- a/lib/storage.js +++ b/lib/storage.js @@ -27,7 +27,7 @@ inherits(Piece, EventEmitter) * * @param {number} index piece index * @param {string} hash sha1 hash (hex) for this piece - * @param {Buffer|number} buffer backing buffer for this piece or length of piece if the backing buffer is lazy + * @param {Buffer|number} buffer backing buffer, or piece length if backing buffer is lazy * @param {boolean=} noVerify skip piece verification (used when seeding a new file) */ function Piece (index, hash, buffer, noVerify) { @@ -138,9 +138,7 @@ Piece.prototype.verify = function (buffer) { return } - var expectedHash - sha1(buffer, function (_expectedHash) { - expectedHash = _expectedHash + sha1(buffer, function (expectedHash) { self.verified = (expectedHash === self.hash) onResult() }) @@ -149,7 +147,7 @@ Piece.prototype.verify = function (buffer) { if (self.verified) { self.emit('done') } else { - self.emit('warning', new Error('piece ' + self.index + ' failed verification; ' + expectedHash + ' expected ' + self.hash)) + self.emit('warning', new Error('piece ' + self.index + ' failed verification')) self._reset() } } @@ -160,7 +158,10 @@ Piece.prototype._verifyOffset = function (offset) { if (offset % BLOCK_LENGTH === 0) { return true } else { - self.emit('warning', new Error('piece ' + self.index + ' invalid offset ' + offset + ' not multiple of ' + BLOCK_LENGTH + ' bytes')) + self.emit( + 'warning', + new Error('invalid block offset ' + offset + ', not multiple of ' + BLOCK_LENGTH) + ) return false } } @@ -170,13 +171,12 @@ Piece.prototype._verifyBlock = function (offset, buffer) { if (buffer.length === BLOCK_LENGTH) { // normal block length return true - - } else if (buffer.length === self.length - offset - && self.length - offset < BLOCK_LENGTH) { + } else if (buffer.length === self.length - offset && + self.length - offset < BLOCK_LENGTH) { // last block in piece is allowed to be less than block length return true } else { - self.emit('warning', new Error('piece ' + self.index + ' invalid block of size ' + buffer.length + ' bytes')) + self.emit('warning', new Error('invalid block size ' + buffer.length)) return false } } @@ -230,7 +230,9 @@ function File (storage, file, pieces, pieceLength) { File.prototype.select = function () { var self = this if (self.pieces.length > 0) { - self.storage.emit('select', self.pieces[0].index, self.pieces[self.pieces.length - 1].index, false) + var start = self.pieces[0].index + var end = self.pieces[self.pieces.length - 1].index + self.storage.emit('select', start, end, false) } } @@ -241,7 +243,9 @@ File.prototype.select = function () { File.prototype.deselect = function () { var self = this if (self.pieces.length > 0) { - self.storage.emit('deselect', self.pieces[0].index, self.pieces[self.pieces.length - 1].index, false) + var start = self.pieces[0].index + var end = self.pieces[self.pieces.length - 1].index + self.storage.emit('deselect', start, end, false) } } diff --git a/lib/torrent.js b/lib/torrent.js index 9127eba..f3ec093 100644 --- a/lib/torrent.js +++ b/lib/torrent.js @@ -75,7 +75,6 @@ function Torrent (torrentId, opts) { var parsedTorrent = (torrentId && torrentId.parsedTorrent) || parseTorrent(torrentId) if (parsedTorrent && parsedTorrent.infoHash) { onTorrentId(parsedTorrent) - } else if (typeof get === 'function' && /^https?:/.test(torrentId)) { // http or https url to torrent file get.concat({ @@ -86,14 +85,12 @@ function Torrent (torrentId, opts) { return self.emit('error', new Error('error downloading torrent: ' + err.message)) onTorrentId(data) }) - } else if (typeof fs.readFile === 'function') { // assume it's a filesystem path fs.readFile(torrentId, function (err, torrent) { if (err) return self.emit('error', new Error('invalid torrent id')) onTorrentId(torrent) }) - } else throw new Error('invalid torrent id') function onTorrentId (torrentId) { @@ -277,7 +274,7 @@ Torrent.prototype._onMetadata = function (metadata) { numPieces += 1 self.emit('verifying', { percentDone: 100 * numPieces / self.storage.pieces.length, - percentVerified: 100 * numVerified / self.storage.pieces.length, + percentVerified: 100 * numVerified / self.storage.pieces.length }) if (!err && buffer) { @@ -432,7 +429,7 @@ Torrent.prototype._onWire = function (wire) { // use ut_pex extension if (typeof ut_pex === 'function') wire.use(ut_pex()) - //wire.ut_pex.start() // TODO two-way communication + // wire.ut_pex.start() // TODO two-way communication if (wire.ut_pex) wire.ut_pex.on('peer', function (peer) { debug('got peer via ut_pex ' + peer) self.addPeer(peer) @@ -481,7 +478,8 @@ Torrent.prototype._onWireWithMetadata = function (wire) { function onChokeTimeout () { if (self._destroyed || wire._destroyed) return - if (self.swarm.numQueued > 2 * (self.swarm.numConns - self.swarm.numPeers) && wire.amInterested) { + if (self.swarm.numQueued > 2 * (self.swarm.numConns - self.swarm.numPeers) && + wire.amInterested) { wire.destroy() } else { timeoutId = setTimeout(onChokeTimeout, timeoutMs) @@ -963,12 +961,18 @@ Torrent.prototype._request = function (wire, index, hotswap) { if (r[i] === wire) r[i] = null if (err) { - debug('error getting piece ' + index + '(offset: ' + block.offset + ' length: ' + block.length + ') from ' + wire.remoteAddress + ' ' + err.message) + debug( + 'error getting piece %s (offset: %s length: %s) from %s: %s', + index, block.offset, block.length, wire.remoteAddress, err.message + ) self.storage.cancelBlock(index, block.offset) process.nextTick(self._update.bind(self)) return false } else { - // debug('got piece ' + index + '(offset: ' + block.offset + ' length: ' + block.length + ') from ' + wire.remoteAddress) + debug( + 'got piece %s (offset: %s length: %s) from %s', + index, block.offset, block.length, wire.remoteAddress + ) self.storage.writeBlock(index, block.offset, buffer, function (err) { if (err) { debug('error writing block') @@ -993,7 +997,7 @@ Torrent.prototype.createServer = function (opts) { } function getPipelineLength (wire, duration) { - return Math.ceil(2 + duration * wire.downloadSpeed() / Storage.BLOCK_LENGTH); + return Math.ceil(2 + duration * wire.downloadSpeed() / Storage.BLOCK_LENGTH) } /** diff --git a/test/cmd.js b/test/cmd.js index 196104a..36e2c0b 100644 --- a/test/cmd.js +++ b/test/cmd.js @@ -22,7 +22,6 @@ test('Command line: webtorrent help', function (t) { t.error(err) // no error, exit code 0 t.ok(data.toLowerCase().indexOf('usage') !== -1) }) - }) test('Command line: webtorrent version', function (t) { diff --git a/test/download-dht-magnet.js b/test/download-dht-magnet.js index 639f485..6290464 100644 --- a/test/download-dht-magnet.js +++ b/test/download-dht-magnet.js @@ -85,8 +85,7 @@ test('Download using DHT (via magnet uri)', function (t) { cb(null, client2) }) }) - }], - + }] }, function (err, r) { t.error(err) r.client1.destroy(function () { diff --git a/test/download-dht-torrent.js b/test/download-dht-torrent.js index 510092f..09b9b50 100644 --- a/test/download-dht-torrent.js +++ b/test/download-dht-torrent.js @@ -84,8 +84,7 @@ test('Download using DHT (via .torrent file)', function (t) { cb(null, client2) }) }) - }], - + }] }, function (err, r) { t.error(err) r.client1.destroy(function () { diff --git a/test/storage.js b/test/storage.js index bc7117b..6665be6 100644 --- a/test/storage.js +++ b/test/storage.js @@ -7,9 +7,9 @@ var torrents = [ 'leaves', 'pride' ].map(function (name) { var torrent = fs.readFileSync(__dirname + '/torrents/' + name + '.torrent') return { - name : name, - torrent : torrent, - parsedTorrent : parseTorrent(torrent) + name: name, + torrent: torrent, + parsedTorrent: parseTorrent(torrent) } }) @@ -21,7 +21,8 @@ torrents.forEach(function (torrent) { t.equal(storage.files.length, parsedTorrent.files.length) t.equal(storage.pieces.length, parsedTorrent.pieces.length) - var length = 0, pieces = 0 + var length = 0 + var pieces = 0 storage.pieces.forEach(function (piece, index) { t.notOk(piece.verified) -- cgit v1.2.3