Browse Source

Follow xo style

pull/11/head
Luke Childs 8 years ago
parent
commit
3b568f7b2e
  1. 1
      controllers/error.js
  2. 5
      controllers/listing.js
  3. 6
      controllers/node.js
  4. 3
      index.js
  5. 10
      lib/bandwidth-chart.js
  6. 1
      lib/minify.js
  7. 30
      lib/nunjucks-filters.js
  8. 2
      lib/nunjucks-middleware.js
  9. 15
      lib/tor.js
  10. 39
      public/assets/enhancements.js
  11. 11
      public/sw.js

1
controllers/error.js

@ -1,3 +1,4 @@
/* eslint no-unused-vars: ["error", { "argsIgnorePattern": "next" }] */
module.exports = (err, req, res, next) => {
const statusCode = err.statusCode || 500;
const error = err.statusMessage || 'Something went wrong';

5
controllers/listing.js

@ -1,7 +1,6 @@
const tor = require('../lib/tor');
module.exports = (req, res, next) => {
let title = 'Top nodes by consensus weight';
const query = {
limit: 10
@ -25,9 +24,9 @@ module.exports = (req, res, next) => {
numOfNodes: query.limit
}))
.catch(err => {
if(err.statusCode == 400 && req.query.s) {
if (err.statusCode === 400 && req.query.s) {
err.statusMessage = 'Bad Search Query';
}
next(err);
});
}
};

6
controllers/node.js

@ -19,12 +19,12 @@ module.exports = (req, res, next) => {
pageTitle: `${data[0].type}: ${data[0].nickname}`,
node: data[0],
bandwidth: bandwidthChart(data[1])
})
});
})
.catch(err => {
if(err.statusCode == 400) {
if (err.statusCode === 400) {
err.statusMessage = 'Invalid node';
}
next(err);
});
}
};

3
index.js

@ -1,11 +1,12 @@
const express = require('express');
const anonlytics = require('anonlytics-express');
const nunjucks = require('nunjucks');
const compression = require('compression');
const nunjucksFilters = require('./lib/nunjucks-filters');
const nunjucksMiddleware = require('./lib/nunjucks-middleware');
const compression = require('compression');
const minify = require('./lib/minify');
const controllers = require('./controllers');
const app = express();
const port = process.env.port || 3000;

10
lib/bandwidth-chart.js

@ -1,7 +1,6 @@
const chart = require('ascii-chart');
function pointsFromBandwidthData(values, numPoints) {
// Define vars
const len = values.length;
const points = [];
@ -35,7 +34,9 @@ function pointsFromBandwidthData(values, numPoints) {
}
module.exports = values => {
if(values && values.length) {
if (!values || values.length < 1) {
return '';
}
const points = pointsFromBandwidthData(values, 57);
return chart(points, {
width: 120,
@ -45,7 +46,4 @@ module.exports = values => {
negativePointChar: '.',
axisChar: '.'
});
} else {
return '';
}
}
};

1
lib/minify.js

@ -1,6 +1,7 @@
const minify = require('express-minify');
const minifyHTML = require('express-minify-html');
const CleanCSS = require('clean-css');
const cleanCSS = new CleanCSS();
module.exports = [

30
lib/nunjucks-filters.js

@ -1,6 +1,6 @@
const querystring = require('querystring');
const prettyBytes = require('pretty-bytes');
const moment = require('moment');
const querystring = require('querystring');
function humanTimeAgo(utcDate) {
const diff = moment.utc().diff(moment.utc(utcDate));
@ -18,7 +18,9 @@ function humanTimeAgo(utcDate) {
let readableUptime = '';
readableUptime += uptime.d ? ` ${uptime.d}d` : '';
readableUptime += uptime.h ? ` ${uptime.h}h` : '';
readableUptime += !uptime.d || !uptime.h && uptime.m ? ` ${uptime.m}m` : '';
if ((!uptime.d || !uptime.h) && uptime.m) {
readableUptime += ` ${uptime.m}m`;
}
return readableUptime.trim();
}
@ -26,7 +28,6 @@ function humanTimeAgo(utcDate) {
const filters = {
bandwidth: node => `${prettyBytes(node.advertised_bandwidth)}/s`,
uptime: node => {
// Check node is up
if (!node.running) {
return 'Down';
@ -36,7 +37,6 @@ const filters = {
return humanTimeAgo(node.last_restarted);
},
pagination: (req, direction) => {
// Clone query string
const query = Object.assign({}, req.query);
@ -44,27 +44,35 @@ const filters = {
query.p = query.p ? query.p : 1;
// Update page
if(direction == 'next') {
if (direction === 'next') {
query.p++;
} else if(direction == 'prev') {
} else if (direction === 'prev') {
query.p--;
}
// Don't add p var if it's page 1
query.p == 1 && delete query.p
if (query.p === 1) {
delete query.p;
}
// Encode query string
const queryString = querystring.encode(query);
return queryString ? `/?${queryString}` : '/';
},
name: node => node.nickname
|| node.fingerprint && node.fingerprint.slice(0, 8)
|| node.hashed_fingerprint && node.hashed_fingerprint.slice(0, 8),
name: node => {
let name = '';
if (node.nickname) {
name = node.nickname;
} else if (node.fingerprint || node.hashed_fingerprint) {
name = (node.fingerprint || node.hashed_fingerprint).slice(0, 8);
}
return name;
},
status: node => node.running ?
`Up for ${humanTimeAgo(node.last_restarted)}` :
`Down for ${humanTimeAgo(node.last_seen)}`
};
module.exports = app => Object.keys(filters).forEach(filter => {
app.settings.nunjucksEnv.addFilter(filter, filters[filter])
app.settings.nunjucksEnv.addFilter(filter, filters[filter]);
});

2
lib/nunjucks-middleware.js

@ -2,4 +2,4 @@ module.exports = (req, res, next) => {
res.locals.req = req;
res.locals.res = res;
next();
}
};

15
lib/tor.js

@ -1,14 +1,20 @@
const Onionoo = require('onionoo');
const onionoo = new Onionoo();
const setNodeType = type => node => {
node.type = type;
return node;
};
module.exports = {
listNodes: query => {
return onionoo
.details(query)
.then(response => {
const details = response.body;
details.relays.forEach(node => node.type = 'relay');
details.bridges.forEach(node => node.type = 'bridge');
details.relays.map(setNodeType('relay'));
details.bridges.map(setNodeType('bridge'));
return details.relays.concat(details.bridges);
});
},
@ -33,9 +39,8 @@ module.exports = {
const bandwidth = response.body;
try {
const lastMonth = bandwidth.relays[0].write_history['1_month'];
return lastMonth.values.map(value => value * lastMonth.factor)
}
catch(e) {
return lastMonth.values.map(value => value * lastMonth.factor);
} catch (err) {
return [];
}
});

39
public/assets/enhancements.js

@ -1,13 +1,12 @@
/* eslint-env browser */
(function () {
// Space optimisations
var doc = document;
var find = doc.querySelector.bind(doc);
var create = doc.createElement.bind(doc);
// Run callback when DOM is ready
function DOMReady(cb) {
function domReady(cb) {
// Run now if DOM has already loaded as we're loading async
if (['interactive', 'complete'].indexOf(doc.readyState) >= 0) {
cb();
@ -22,7 +21,7 @@
var supports = {
test: function (features) {
var self = this;
if(!features || !features.length) {
if (!features || features.length < 1) {
return false;
}
return features.every(function (feature) {
@ -35,7 +34,7 @@
localStorage.setItem('test', 'test');
localStorage.removeItem('test');
return true;
} catch (e) {
} catch (err) {
return false;
}
})(),
@ -43,10 +42,10 @@
var div = create('div');
div.innerHTML = '<svg/>';
return (
typeof SVGRect != 'undefined'
&& div.firstChild
&& div.firstChild.namespaceURI
) == 'http://www.w3.org/2000/svg';
typeof SVGRect !== 'undefined' &&
div.firstChild &&
div.firstChild.namespaceURI
) === 'http://www.w3.org/2000/svg';
})(),
querySelector: typeof doc.querySelector === 'function',
classList: (function () {
@ -123,7 +122,7 @@
var menuHTML = '';
var heartedNodes = favouriteNodes.getHeartedNodes();
var nodeHashes = Object.keys(heartedNodes);
if(nodeHashes.length) {
if (nodeHashes.length > 0) {
menuHTML += '<ul>';
nodeHashes.forEach(function (node) {
menuHTML += '<li><a href="/node/' + node + '">' + heartedNodes[node] + '</a></li>';
@ -132,12 +131,12 @@
} else {
menuHTML += '<div class="empty">Click the heart next to a node\'s title on it\'s own page to save it here for easy access :)</div>';
}
return menu.innerHTML = menuHTML;
menu.innerHTML = menuHTML;
return menu.innerHTML;
},
// Load SVG, run callback when loaded
loadSVG: function (cb) {
// Get heart SVG
var xhr = new XMLHttpRequest();
xhr.open('GET', favouriteNodes.heartPath);
@ -149,10 +148,8 @@
// Initiate node favouriting
init: function () {
// Start loading heart SVG before DOM
favouriteNodes.loadSVG(function (svg) {
// Create heart SVG elem
var div = create('div');
div.innerHTML = svg;
@ -166,7 +163,6 @@
// Add click handler
heartEl.addEventListener('click', function () {
// Heart/unheart node
var node = favouriteNodes.getCurrentNode();
if (favouriteNodes.isHearted(node)) {
@ -179,7 +175,7 @@
});
// Then inject into DOM when it's ready
DOMReady(function() {
domReady(function () {
var headerHeight = find('.title').offsetHeight;
var headerBoxShadow = 3;
@ -213,7 +209,6 @@
// If current node is hearted
var node = favouriteNodes.getCurrentNode();
if (favouriteNodes.isHearted(node)) {
// Heart it again so we get the new name if it's updated
favouriteNodes.heart(node);
}
@ -222,12 +217,11 @@
// Service worker
if (supports.test(['serviceWorker', 'querySelector', 'classList'])) {
// Register service worker
navigator.serviceWorker.register('/sw.js');
// Show cache message on stale pages
DOMReady(function() {
domReady(function () {
if (window.cacheDate) {
var offlineMessage = create('div');
offlineMessage.classList.add('cache-message');
@ -248,14 +242,13 @@
// Add ios class to body on iOS devices
if (supports.test(['classList'])) {
DOMReady(function() {
domReady(function () {
if (
/iPad|iPhone|iPod/.test(navigator.userAgent)
&& !window.MSStream
/iPad|iPhone|iPod/.test(navigator.userAgent) &&
!window.MSStream
) {
doc.body.classList.add('ios');
}
});
}
})();

11
public/sw.js

@ -1,9 +1,9 @@
/* eslint-env browser */
var cacheName = 'onionite-cache-v1';
var offlineUrl = '/no-connection';
// Install
self.addEventListener('install', function (event) {
// Cache assets
event.waitUntil(
caches.open(cacheName)
@ -35,11 +35,9 @@ self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function (response) {
// If we don't have it make the request
return response || fetch(event.request);
}
)
})
);
return;
}
@ -54,13 +52,10 @@ self.addEventListener('fetch', function(event) {
// Make the request
fetch(event.request)
.then(function (response) {
// If it's the homepage or a node page
if (requestUrl.pathname === '/' || requestUrl.pathname.startsWith('/node/')) {
// Clone the response and read the html
response.clone().text().then(function (html) {
// Modify the html so we know when it was cached
html = html.replace('window.cacheDate=false;', 'window.cacheDate="' + Date() + '";');
var modifiedResponse = new Response(new Blob([html]), {headers: response.headers});
@ -78,11 +73,9 @@ self.addEventListener('fetch', function(event) {
// If it fails
.catch(function () {
// Try and return a previously cached version
return caches.match(event.request)
.then(function (response) {
// If we don't have a cached version show pretty offline page
return response || caches.match(offlineUrl);
});

Loading…
Cancel
Save