diff --git a/controllers/node.js b/controllers/node.js index 1ffb1d3..37750d5 100644 --- a/controllers/node.js +++ b/controllers/node.js @@ -1,9 +1,14 @@ -const tor = require('../lib/tor'); +const tor = require('../lib/tor'); +const bandwidthChart = require('../lib/bandwidth-chart'); module.exports = (req, res, next) => { - tor.node(req.params.id) - .then(node => res.render('node.html', { - node: node, + Promise.all([ + tor.node(req.params.id), + tor.bandwidth(req.params.id) + ]) + .then(data => res.render('node.html', { + node: data[0], + bandwidth: bandwidthChart(data[1]) })) .catch(error => res.render('node.html', { error: error diff --git a/lib/bandwidth-chart.js b/lib/bandwidth-chart.js new file mode 100644 index 0000000..97ec289 --- /dev/null +++ b/lib/bandwidth-chart.js @@ -0,0 +1,52 @@ +const chart = require('ascii-chart'); + +function pointsFromBandwidthData(values, numPoints) { + + // Define vars + const len = values.length; + const points = []; + let i = 0; + let size; + + // Split values into n points + if(numPoints < 2) { + points.push(values); + } else { + if(len % numPoints === 0) { + size = Math.floor(len / numPoints); + while (i < len) { + points.push(values.slice(i, i += size)); + } + } + while (i < len) { + size = Math.ceil((len - i) / numPoints--); + points.push(values.slice(i, i += size)); + } + } + + // Return points + const result = points + + // Calculate average value of each point + .map(point => Math.round(point.reduce((a,b) => a + b) / point.length)) + + // Convert bytes to megabytes + .map(bytes => Number((bytes / 1000000).toPrecision(3))); + + return result; +} + +module.exports = values => { + if(values && values.length) { + const points = pointsFromBandwidthData(values, 57); + return chart(points, { + width: 125, + height: 20, + padding: 0, + pointChar: '*', + negativePointChar: '.' + }); + } else { + return ''; + } +} diff --git a/lib/tor.js b/lib/tor.js index 5acdb76..d976322 100644 --- a/lib/tor.js +++ b/lib/tor.js @@ -21,5 +21,18 @@ module.exports = { return details.bridges[0]; } }); + }, + bandwidth: id => { + return onionoo + .bandwidth({ lookup: id }) + .then(bandwidth => { + try { + const lastMonth = bandwidth.relays[0].write_history['1_month']; + return lastMonth.values.map(value => value * lastMonth.factor) + } + catch(e) { + return []; + } + }); } }; diff --git a/package.json b/package.json index f7d9be0..bc0af0e 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,7 @@ "description": "Explore the Tor network without JS", "main": "index.js", "dependencies": { + "ascii-chart": "^1.2.0", "compression": "^1.6.2", "express": "^4.14.0", "express-minify": "^0.2.0",