Tidying other modules, fixing password and fx

This commit is contained in:
Martin Donnelly 2017-09-06 08:42:13 +01:00
parent 7fd7b54743
commit 973c689ac5
18 changed files with 1516 additions and 803 deletions

View File

@ -12,34 +12,44 @@
"es6": true "es6": true
}, },
"rules": { "rules": {
"no-new-object": 1, "arrow-spacing": "error",
"no-reserved-keys": 1, "block-scoped-var": "error",
"no-array-constructor": 1, "block-spacing": "error",
"quotes": [1, "single"], "brace-style": ["error", "stroustrup", {}],
"max-len": [1, 120, 2], // 2 spaces per tab, max 80 chars per line "camelcase": "error",
"no-inner-declarations": [1, "both"], "comma-dangle": ["error", "never"],
"no-shadow-restricted-names": 1, "comma-spacing": ["error", { "before": false, "after": true }],
"one-var": 0, "comma-style": [1, "last"],
"vars-on-top": 1, "consistent-this": [1, "_this"],
"eqeqeq": 1,
"curly": [1, "multi"], "curly": [1, "multi"],
"eol-last": 1,
"eqeqeq": 1,
"func-names": 1,
"indent": ["error", 2, { "SwitchCase": 1 }],
"lines-around-comment": ["error", { "beforeBlockComment": true, "allowArrayStart": true }],
"max-len": [1, 240, 2], // 2 spaces per tab, max 80 chars per line
"new-cap": 1,
"newline-before-return": "error",
"no-array-constructor": 1,
"no-inner-declarations": [1, "both"],
"no-mixed-spaces-and-tabs": 1, "no-mixed-spaces-and-tabs": 1,
"no-multi-spaces": 2,
"no-new-object": 1,
"no-shadow-restricted-names": 1,
"object-curly-spacing": ["error", "always"],
"padded-blocks": ["error", { "blocks": "never", "switches": "always" }],
"prefer-const": "error",
"prefer-template": "error",
"one-var": 0,
"quote-props": ["error", "always"],
"quotes": [1, "single"],
"radix": 1,
"semi": [1, "always"],
"space-before-blocks": [1, "always"], "space-before-blocks": [1, "always"],
"space-infix-ops": 1, "space-infix-ops": 1,
"eol-last": 1, "vars-on-top": 1,
"comma-style": [1, "last"], "no-multiple-empty-lines": ["error", { "max": 1, "maxEOF": 1 }],
"no-comma-dangle": 1, "spaced-comment": ["error", "always", { "markers": ["/"] }]
"semi": [1, "always"],
"radix": 1,
"camelcase": 1,
"new-cap": 1,
"consistent-this": [1, "_this"],
"func-names": 1,
"no-multi-spaces": 2,
"brace-style": [2,"1tbs",{}],
"indent": [2,2],
"comma-spacing": ["error", { "before": false, "after": true }]
} }
} }

View File

@ -2,56 +2,55 @@
* Created by mdonnel on 22/03/2017. * Created by mdonnel on 22/03/2017.
*/ */
let BitcoinModel = Backbone.Model.extend({ const BitcoinModel = Backbone.Model.extend({
initialize: function () { 'initialize': function () {
this.set('url', '/btc'); this.set('url', '/btc');
this.set('balanceUrl', '/balance'); this.set('balanceUrl', '/balance');
let data = { const data = {
lastGBP: 0.0, 'lastGBP': 0.0,
lastUSD: 0.0, 'lastUSD': 0.0,
lows: {gbp: 0, usd: 0}, 'lows': { 'gbp': 0, 'usd': 0 },
highs: {gbp: 0, usd: 0}, 'highs': { 'gbp': 0, 'usd': 0 },
eclass: '', 'eclass': '',
balance: 0.0, 'balance': 0.0,
trend: 0 'trend': 0
}; };
this.set('btcdata', data); this.set('btcdata', data);
this.set('balance', 0); this.set('balance', 0);
this.update(); this.update();
this.updateHourly(); this.updateHourly();
}, },
update: function () { 'update': function () {
this.getBTC(); this.getBTC();
//this.getBalance(); // this.getBalance();
const now = new Date(); const now = new Date();
const mod = 300000 - (now.getTime() % 300000); const mod = 300000 - (now.getTime() % 300000);
let btcupdateFn = function() { const btcupdateFn = function() {
this.update(); this.update();
}; };
setTimeout(btcupdateFn.bind(this), mod + 10); setTimeout(btcupdateFn.bind(this), mod + 10);
}, },
updateHourly: function () { 'updateHourly': function () {
this.getBalance(); this.getBalance();
const now = new Date(); const now = new Date();
const mod = 3600000 - (now.getTime() % 3600000); const mod = 3600000 - (now.getTime() % 3600000);
let btcupdateFn = function() { const btcupdateFn = function() {
this.update(); this.update();
}; };
setTimeout(btcupdateFn.bind(this), mod + 10); setTimeout(btcupdateFn.bind(this), mod + 10);
}, },
recalc: function () { 'recalc': function () {
let data = this.get('btcdata'); let data = this.get('btcdata');
let lastGBP = data.lastGBP; let lastGBP = data.lastGBP;
let lastUSD; let lastUSD;
let g = data.gbp; const g = data.gbp;
let u = data.usd; const u = data.usd;
let lows = data.lows; const lows = data.lows;
let highs = data.highs; const highs = data.highs;
let eclass = data.eclass; let eclass = data.eclass;
let balance = data.balance; const balance = data.balance;
let trend = data.trend; let trend = data.trend;
if ((trend === undefined) || ( trend === null)) trend = 1; if ((trend === undefined) || ( trend === null)) trend = 1;
@ -60,7 +59,8 @@ let BitcoinModel = Backbone.Model.extend({
if (data.lastGBP !== 0) if (data.lastGBP !== 0)
if (g > lastGBP) { if (g > lastGBP) {
eclass = 'up'; eclass = 'up';
} else { }
else {
eclass = 'down'; eclass = 'down';
} }
else { else {
@ -94,61 +94,61 @@ let BitcoinModel = Backbone.Model.extend({
this.set('btcdata', data); this.set('btcdata', data);
// total = myBTC * g; // total = myBTC * g;
}, },
getBTC: function () { 'getBTC': function () {
let self = this; const self = this;
let url = this.get('url'); const url = this.get('url');
$.ajax({ $.ajax({
type: 'GET', 'type': 'GET',
url: url, 'url': url,
data: '', 'data': '',
dataType: 'json', 'dataType': 'json',
timeout: 10000, 'timeout': 10000,
//contentType: ('application/json'), // contentType: ('application/json'),
headers: { 'headers': {
'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type' 'Access-Control-Allow-Headers': 'Content-Type'
}, },
success: function (data) { 'success': function (data) {
let gbp = data.bpi.GBP.rate_float, let gbp = data.bpi.GBP.rate_float,
usd = data.bpi.USD.rate_float; usd = data.bpi.USD.rate_float;
let trend = data.trend; const trend = data.trend;
let btcdata = self.get('btcdata'); const btcdata = self.get('btcdata');
btcdata.gbp = gbp; btcdata.gbp = gbp;
btcdata.usd = usd; btcdata.usd = usd;
btcdata.trend = trend; btcdata.trend = trend;
self.set('btcdata', btcdata); self.set('btcdata', btcdata);
self.recalc(); self.recalc();
}, },
error: function (xhr, type) { 'error': function (xhr, type) {
console.log('ajax error'); console.log('ajax error');
console.log(xhr); console.log(xhr);
console.log(type); console.log(type);
} }
}); });
}, },
getBalance: function() { 'getBalance': function() {
let self = this; const self = this;
let url = this.get('balanceUrl'); const url = this.get('balanceUrl');
$.ajax({ $.ajax({
type: 'GET', 'type': 'GET',
url: url, 'url': url,
data: '', 'data': '',
dataType: 'json', 'dataType': 'json',
timeout: 10000, 'timeout': 10000,
//contentType: ('application/json'), // contentType: ('application/json'),
headers: { 'headers': {
'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type' 'Access-Control-Allow-Headers': 'Content-Type'
}, },
success: function (data) { 'success': function (data) {
let balance = data.balance; const balance = data.balance;
self.set('balance', balance); self.set('balance', balance);
self.recalc(); self.recalc();
}, },
error: function (xhr, type) { 'error': function (xhr, type) {
console.log('ajax error'); console.log('ajax error');
console.log(xhr); console.log(xhr);
console.log(type); console.log(type);
@ -156,22 +156,22 @@ let BitcoinModel = Backbone.Model.extend({
}); });
} }
}); });
let Bitcoin = Backbone.View.extend({ const Bitcoin = Backbone.View.extend({
tagName: 'div', 'tagName': 'div',
initialize: function () { 'initialize': function () {
_.bindAll(this, 'render'); _.bindAll(this, 'render');
this.model.bind('change', this.render); this.model.bind('change', this.render);
this.$btc = $('#btc'); this.$btc = $('#btc');
this.$trend = $('#trend'); this.$trend = $('#trend');
}, },
render: function () { 'render': function () {
let btcdata = this.model.get('btcdata'); const btcdata = this.model.get('btcdata');
let balance = this.model.get('balance'); const balance = this.model.get('balance');
//console.log(`Balance: ${btcdata.balance.toFixed(4)}`); // console.log(`Balance: ${btcdata.balance.toFixed(4)}`);
//console.log(btcdata.lastGBP); // console.log(btcdata.lastGBP);
let owned = parseFloat(btcdata.lastGBP) * parseFloat(balance); const owned = parseFloat(btcdata.lastGBP) * parseFloat(balance);
//console.log(`owned: ${owned}`); // console.log(`owned: ${owned}`);
let title = 'High: $' + parseFloat(btcdata.highs.usd.toFixed(2)) + ' / Low $' + parseFloat(btcdata.lows.usd.toFixed(2)); const title = `High: $${ parseFloat(btcdata.highs.usd.toFixed(2)) } / Low $${ parseFloat(btcdata.lows.usd.toFixed(2))}`;
let trendClass = ''; let trendClass = '';
if (btcdata.trend > 1.00) if (btcdata.trend > 1.00)

View File

@ -5,17 +5,17 @@
* Time: 14:20 * Time: 14:20
* *
*/ */
var ClockModel = Backbone.Model.extend({ const ClockModel = Backbone.Model.extend({
initialize: function() { 'initialize': function () {
this.set('now',new Date); this.set('now', new Date);
this.update(); this.update();
}, },
update: function() { 'update': function () {
var now = new Date; const now = new Date;
var mod = 60000 - (now.getTime() % 60000); const mod = 60000 - (now.getTime() % 60000);
this.set('now',now); this.set('now', now);
var clockFn = function() { const clockFn = function () {
this.update(); this.update();
}; };
@ -23,21 +23,21 @@ var ClockModel = Backbone.Model.extend({
} }
}); });
var Clock = Backbone.View.extend({ const Clock = Backbone.View.extend({
tagName: 'div', 'tagName': 'div',
initialize: function() { 'initialize': function () {
_.bindAll(this, 'render'); _.bindAll(this, 'render');
this.model.bind('change', this.render); this.model.bind('change', this.render);
this.$date = $('#date'); this.$date = $('#date');
this.$time = $('#time'); this.$time = $('#time');
this.render(); this.render();
}, },
render: function() { 'render': function () {
var now = this.model.get('now'); const now = this.model.get('now');
//var curTime = now.format('<span class="hour">{24hr}</span>{mm}'); // var curTime = now.format('<span class="hour">{24hr}</span>{mm}');
var curTime = now.format('<span class="time">{24hr} {mm}</span>'); const curTime = now.format('<span class="time">{24hr} {mm}</span>');
var curDate = now.format('{yyyy}-{MM}-{dd}'); const curDate = now.format('{yyyy}-{MM}-{dd}');
if (this.prevTime !== curTime) { if (this.prevTime !== curTime) {
this.$time.html(curTime); this.$time.html(curTime);
this.prevTime = curTime; this.prevTime = curTime;

View File

@ -1,55 +1,56 @@
/** /**
* Created by mdonnel on 10/04/2017. * Created by mdonnel on 10/04/2017.
*/ */
let EventModel = Backbone.Model.extend({ const EventModel = Backbone.Model.extend({
initialize: function () { 'initialize': function () {
this.update(); this.update();
}, },
getDays : function(startdate, enddate) { 'getDays' : function(startdate, enddate) {
let r, s, e; let r, s, e;
s = startdate.getTime(); s = startdate.getTime();
e = enddate.getTime(); e = enddate.getTime();
r = (e - s) / (24 * 60 * 60 * 1000); r = (e - s) / (24 * 60 * 60 * 1000);
return r;
}, return r;
update: function () { },
const now = new Date 'update': function () {
const mod = 3600000 - (now.getTime() % 3600000) const now = new Date;
let data = {}; const mod = 3600000 - (now.getTime() % 3600000);
const data = {};
data.days = Math.ceil(this.getDays(now, this.get('event'))); data.days = Math.ceil(this.getDays(now, this.get('event')));
data.weeks = Math.ceil(this.getDays(now, this.get('event')) / 7); data.weeks = Math.ceil(this.getDays(now, this.get('event')) / 7);
this.set('data', data); this.set('data', data);
const clockFn = function () { const clockFn = function () {
this.update() this.update();
} };
setTimeout(clockFn.bind(this), mod + 10) setTimeout(clockFn.bind(this), mod + 10);
} }
}); });
let EventView = Backbone.View.extend({ const EventView = Backbone.View.extend({
tagName: 'div', 'tagName': 'div',
initialize: function () { 'initialize': function () {
_.bindAll(this, 'render'); _.bindAll(this, 'render');
this.model.bind('change', this.render); this.model.bind('change', this.render);
this.id = 'e_' + Math.random().toString(36).substr(2, 9); this.id = `e_${ Math.random().toString(36).substr(2, 9)}`;
this.$events = $('#events'); this.$events = $('#events');
this.$myEvent = null; this.$myEvent = null;
this.$el = this.$events; this.$el = this.$events;
this.initView(); this.initView();
this.render(); this.render();
}, },
render: function () { 'render': function () {
let label = this.model.get('label'); const label = this.model.get('label');
let data = this.model.get('data'); const data = this.model.get('data');
let str = `${label} ${data.days} days / ${data.weeks} weeks`; const str = `${label} ${data.days} days / ${data.weeks} weeks`;
this.$myEvent.empty().append(str); this.$myEvent.empty().append(str);
}, },
initView: function () { 'initView': function () {
let html = `<div class='mui-col-xs-12 mui-col-md-3' id="${this.id}"></div>`; const html = `<div class='mui-col-xs-12 mui-col-md-3' id="${this.id}"></div>`;
this.$html = $(html); this.$html = $(html);
this.$events.append(this.$html); this.$events.append(this.$html);
this.$myEvent = $(`#${this.id}`); this.$myEvent = $(`#${this.id}`);
} }
}); });

View File

@ -2,71 +2,74 @@
* Created by mdonnel on 22/03/2017. * Created by mdonnel on 22/03/2017.
*/ */
let FxModel = Backbone.Model.extend({ const FxModel = Backbone.Model.extend({
initialize: function () { 'initialize': function () {
this.set('url', '/fx'); this.set('url', '/fx');
this.set('fxdata', {}); this.set('fxdata', {});
this.update(); this.update();
}, },
update: function () { 'update': function () {
this.getFX(); this.getFX();
const now = new Date; const now = new Date;
const mod = 900000 - (now.getTime() % 900000); const mod = 900000 - (now.getTime() % 900000);
let fxUpdateFn = function() { const fxUpdateFn = function() {
this.update(); this.update();
}; };
setTimeout(fxUpdateFn.bind(this), mod + 10); setTimeout(fxUpdateFn.bind(this), mod + 10);
}, },
getFX: function() { 'getFX': function() {
let url = this.get('url'); const url = this.get('url');
let self = this; const self = this;
$.ajax({ $.ajax({
type: 'GET', 'type': 'GET',
url: url, 'url': url,
data: '', 'data': '',
dataType: 'json', 'dataType': 'json',
timeout: 10000, 'timeout': 10000,
//contentType: ('application/json'), // contentType: ('application/json'),
headers: { 'headers': {
'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type' 'Access-Control-Allow-Headers': 'Content-Type'
}, },
success: function(data) { 'success': function(data) {
let gpbex = (1 / data.rates.GBP); let fxdata = {};
let sekex = (gpbex * data.rates.SEK); if (data.rates !== undefined) {
let fxdata = { const gpbex = (1 / data.rates.GBP);
usd: 1, const sekex = (gpbex * data.rates.SEK);
gbp: data.rates.GBP, fxdata = {
sek: data.rates.SEK, 'usd': 1,
gpbe: gpbex, 'gbp': data.rates.GBP,
sekex: sekex 'sek': data.rates.SEK,
}; 'gpbe': gpbex,
self.set('fxdata', fxdata); 'sekex': sekex
}, };
error: function(xhr, type) {
console.log('ajax error');
console.log(xhr);
console.log(type);
}
});
} }
});
self.set('fxdata', fxdata);
},
'error': function(xhr, type) {
console.log('ajax error');
console.log(xhr);
console.log(type);
}
});
}
});
const FxView = Backbone.View.extend({ const FxView = Backbone.View.extend({
tagName: 'div', 'tagName': 'div',
initialize: function () { 'initialize': function () {
_.bindAll(this, 'render'); _.bindAll(this, 'render');
this.model.bind('change', this.render); this.model.bind('change', this.render);
this.$fx = $('#fx'); this.$fx = $('#fx');
}, },
render: function () { 'render': function () {
let fxdata = this.model.get('fxdata'); const fxdata = this.model.get('fxdata');
this.$fx.html(`&pound;1 = &#36;${parseFloat(fxdata.gpbe.toFixed(2))} = ${ parseFloat(fxdata.sekex.toFixed(2))} SEK`); this.$fx.html(`&pound;1 = &#36;${parseFloat(fxdata.gpbe.toFixed(2))} = ${ parseFloat(fxdata.sekex.toFixed(2))} SEK`);
} }
}); });

View File

@ -1,83 +1,103 @@
/** /**
* Created by mdonnel on 20/04/2017. * Created by mdonnel on 20/04/2017.
*/ */
_.templateSettings = { /*_.templateSettings = {
evaluate: /\{\{(.+?)\}\}/g, 'evaluate': /\{\{(.+?)\}\}/g,
interpolate: /\{\{=(.+?)\}\}/g, 'interpolate': /\{\{=(.+?)\}\}/g,
escape: /\{\{-(.+?)\}\}/g 'escape': /\{\{-(.+?)\}\}/g
}; };*/
Array.prototype.random = function () { Array.prototype.random = function () {
return this[Math.floor((Math.random() * this.length))]; return this[Math.floor((Math.random() * this.length))];
}; };
const PasswordView = Backbone.View.extend({ const PasswordView = Backbone.View.extend({
el: '#passwords', 'el': '#passwords',
passwordTemplate: _.template($('#password-template').html()), 'passwordTemplate': _.template('<div>Long: <%=long%></div><div>Short: <%=short%></div>'),
initialize: function () { 'initialize': function () {
this.alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; this.alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
this.whitespace = ['.', '~', '#', '!', '$', '+', '-', '+']; 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
this.numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
this.left = ['Alabama', this.whitespace = ['.', '~', '#', '!', '$', '+', '-', '+'];
'Alaska', this.numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
'Arizona', this.left = ['Alabama',
'Maryland', 'Alaska',
'Nevada', 'Arizona',
'Mexico', 'Maryland',
'Texas', 'Nevada',
'Utah', 'Mexico',
'Glasgow', 'Texas',
'Inverness', 'Utah',
'Edinburgh', 'Glasgow',
'Dumbarton', 'Inverness',
'Balloch', 'Edinburgh',
'Renton', 'Dumbarton',
'Cardross', 'Balloch',
'Dundee', 'Renton',
'Paisley', 'Cardross',
'Hamilton', 'Dundee',
'Greenock', 'Paisley',
'Falkirk', 'Hamilton',
'Irvine', 'Greenock',
'Renfrew', 'Falkirk',
'Erskine', 'Irvine',
'London', 'Renfrew',
'Hammersmith', 'Erskine',
'Islington', 'London',
'Silver', 'Black', 'Yellow', 'Purple', 'White', 'Pink', 'Red', 'Orange', 'Brown', 'Green', 'Blue', 'Amber', 'Aqua', 'Azure', 'Bronze', 'Coral', 'Copper', 'Crimson', 'Cyan', 'Ginger', 'Gold', 'Indigo', 'Jade' 'Hammersmith',
'Islington',
'Silver', 'Black', 'Yellow', 'Purple', 'White', 'Pink', 'Red', 'Orange', 'Brown', 'Green', 'Blue',
'Amber', 'Aqua', 'Azure', 'Bronze', 'Coral', 'Copper', 'Crimson', 'Cyan', 'Ginger', 'Gold', 'Indigo', 'Jade'
]; ];
this.right = ['Aganju', 'Cygni', 'Akeron', 'Antares', 'Aragoth', 'Ardus', 'Carpenter', 'Cooper', 'Dahin', 'Capella', 'Endriago', 'Gallina', 'Fenris', 'Freya', 'Glenn', 'Grissom', 'Jotunheim', 'Kailaasa', 'Lagarto', 'Muspelheim', 'Nifleheim', 'Primus', 'Vega', 'Ragnarok', 'Shepard', 'Slayton', 'Tarsis', 'Mercury', 'Venus', 'Mars', 'Earth', 'Terra', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto', 'Europa', 'Ganymede', 'Callisto', 'Titan', 'Juno', 'Eridanus', 'Scorpius', 'Crux', 'Cancer', 'Taurus', 'Lyra', 'Andromeda', 'Virgo', 'Aquarius', 'Cygnus', 'Corvus', 'Taurus', 'Draco', 'Perseus', 'Pegasus', 'Gemini', 'Columbia', 'Bootes', 'Orion', 'Deneb', 'Merope', 'Agate', 'Amber', 'Beryl', 'Calcite', 'Citrine', 'Coral', 'Diamond', 'Emerald', 'Garnet', 'Jade', 'Lapis', 'Moonstone', 'Obsidian', 'Onyx', 'Opal', 'Pearl', 'Quartz', 'Ruby', 'Sapphire', 'Topaz', 'Iron', 'Lead', 'Nickel', 'Copper', 'Zinc', 'Tin', 'Manes', 'Argon', 'Neon', 'Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Golf', 'Hotel', 'India', 'Juliett', 'Kilo', 'Lima', 'Mike', 'November', 'Oscar', 'Papa', 'Quebec', 'Romeo', 'Sierra', 'Tango', 'Uniform', 'Victor', 'Whisky', 'Xray', 'Yankee', 'Zulu']; this.right = ['Aganju', 'Cygni', 'Akeron', 'Antares', 'Aragoth', 'Ardus', 'Carpenter',
'Cooper', 'Dahin', 'Capella', 'Endriago', 'Gallina', 'Fenris', 'Freya', 'Glenn', 'Grissom',
'Jotunheim', 'Kailaasa', 'Lagarto', 'Muspelheim', 'Nifleheim', 'Primus', 'Vega', 'Ragnarok',
'Shepard', 'Slayton', 'Tarsis', 'Mercury', 'Venus', 'Mars', 'Earth', 'Terra', 'Jupiter',
'Saturn', 'Uranus', 'Neptune', 'Pluto', 'Europa', 'Ganymede', 'Callisto', 'Titan', 'Juno',
'Eridanus', 'Scorpius', 'Crux', 'Cancer', 'Taurus', 'Lyra', 'Andromeda', 'Virgo', 'Aquarius',
'Cygnus', 'Corvus', 'Taurus', 'Draco', 'Perseus', 'Pegasus', 'Gemini', 'Columbia', 'Bootes',
'Orion', 'Deneb', 'Merope', 'Agate', 'Amber', 'Beryl', 'Calcite', 'Citrine', 'Coral', 'Diamond',
'Emerald', 'Garnet', 'Jade', 'Lapis', 'Moonstone', 'Obsidian', 'Onyx', 'Opal', 'Pearl', 'Quartz',
'Ruby', 'Sapphire', 'Topaz', 'Iron', 'Lead', 'Nickel', 'Copper', 'Zinc', 'Tin', 'Manes', 'Argon',
'Neon', 'Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Golf', 'Hotel', 'India', 'Juliett',
'Kilo', 'Lima', 'Mike', 'November', 'Oscar', 'Papa', 'Quebec', 'Romeo', 'Sierra', 'Tango', 'Uniform',
'Victor', 'Whisky', 'Xray', 'Yankee', 'Zulu'];
this.passwordOut = this.$('#passwordOut');
_.bindAll(this, 'newClick');
},
'events': {
'click #newPassword': 'newClick'
},
'numberCluster': numberCluster,
'randomAmount': randomAmount,
'newClick': newClick
this.passwordOut = this.$('#passwordOut');
_.bindAll(this, "newClick");
},
events: {
"click #newPassword": "newClick"
},
numberCluster: function () {
return this.numbers.random() + this.numbers.random() + this.numbers.random();
},
randomAmount: function (i) {
let str = '';
for (let t = 0; t < i; t++) {
str = str + this.alpha.random();
}
return str;
},
newClick: function (e) {
let long = (this.left.random() + ' ' + this.right.random() + ' ' + this.numberCluster()).split(' ').join(this.whitespace.random());
let short = (this.randomAmount(5) + ' ' + this.randomAmount(5)).split(' ').join(this.whitespace.random());
this.passwordOut.removeClass('mui--hide');
this.passwordOut.empty().append(this.passwordTemplate({
long: long,
short: short
}));
}
}); });
function randomAmount(i) {
let str = '';
for (let t = 0; t < i; t++)
str = str + this.alpha.random();
return str;
}
function newClick(e) {
const long = (`${this.left.random() } ${ this.right.random() } ${ this.numberCluster()}`).split(' ').join(this.whitespace.random());
const short = (`${this.randomAmount(5) } ${ this.randomAmount(5)}`).split(' ').join(this.whitespace.random());
const html = this.passwordTemplate({
'long': long,
'short': short
});
this.passwordOut.removeClass('mui--hide');
this.passwordOut.empty().append(html);
}
function numberCluster() {
return this.numbers.random() + this.numbers.random() + this.numbers.random();
}

View File

@ -6,136 +6,125 @@
* *
*/ */
let TrainModel = Backbone.Model.extend({ const TrainModel = Backbone.Model.extend({
initialize: function () { 'initialize': function () {
const fromStation = this.get('from');
const toStation = this.get('to');
const url = `/getnexttraintimes?from=${ fromStation }&to=${ toStation}`;
const routeUrl = `/gettrains?from=${ fromStation }&to=${ toStation}`;
const target = fromStation + toStation;
this.set('url', url);
this.set('routeUrl', routeUrl);
this.set('target', target);
this.set('visible', false);
this.set('trainData', { 'eta':'OFF', 'sta': 'OFF' });
this.update();
},
'update': function () {
const now = new Date;
const hours = now.getHours();
const limit = (hours < 6) ? 3600000 : 60000;
let fromStation = this.get('from'); const mod = limit - (now.getTime() % limit);
let toStation = this.get('to');
let url = '/getnexttraintimes?from=' + fromStation + '&to=' + toStation;
let routeUrl = '/gettrains?from=' + fromStation + '&to=' + toStation;
let target = fromStation + toStation;
this.set('url', url);
this.set('routeUrl', routeUrl);
this.set('target', target);
this.set('visible', false);
this.set('trainData', {eta:'OFF', sta: 'OFF'});
this.update();
},
update: function () {
const now = new Date; if (hours >= 6)
const hours = now.getHours(); this.getTrain();
const limit = (hours < 6) ? 3600000 : 60000; else
this.set('trainData', { 'eta':'OFF', 'sta': 'OFF' });
const mod = limit - (now.getTime() % limit); const trainUpdateFn = function () {
this.update();
};
if (hours >= 6) { setTimeout(trainUpdateFn.bind(this), mod + 10);
this.getTrain(); },
} else { 'getTrain': function () {
this.set('trainData', {eta:'OFF', sta: 'OFF'}); const url = this.get('url');
} const self = this;
$.ajax({
'type': 'GET',
'url': url,
'data': '',
'dataType': 'json',
'timeout': 10000,
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
},
'success': function (data) {
self.set('trainData', data);
},
'error': function (xhr, type) {
console.log('ajax error');
console.log(xhr);
console.log(type);
}
});
},
'getRoute': function () {
const url = this.get('routeUrl');
const self = this;
let trainUpdateFn = function () { if (this.get('visible') === true)
this.set('visible', false);
else
$.ajax({
'type': 'GET',
'url': url,
'data': '',
'dataType': 'json',
this.update(); 'timeout': 10000,
}; 'headers': {
setTimeout(trainUpdateFn.bind(this), mod + 10);
},
getTrain: function () {
let url = this.get('url');
let self = this;
$.ajax({
type: 'GET',
url: url,
data: '',
dataType: 'json',
timeout: 10000,
headers: {
'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type' 'Access-Control-Allow-Headers': 'Content-Type'
},
success: function (data) {
/*
console.log(data);
*/
self.set('trainData', data);
},
error: function (xhr, type) {
console.log('ajax error');
console.log(xhr);
console.log(type);
}
});
},
getRoute: function () {
let url = this.get('routeUrl');
let self = this;
if (this.get('visible') === true) { },
this.set('visible', false); 'success': function (data) {
} else {
$.ajax({
type: 'GET',
url: url,
data: '',
dataType: 'json',
timeout: 10000,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
},
success: function (data) {
// getTrainsCB(data); // getTrainsCB(data);
//console.log('Got', data); // console.log('Got', data);
self.set('route', data); self.set('route', data);
self.set('visible', true); self.set('visible', true);
}, },
error: function (xhr, type) { 'error': function (xhr, type) {
console.error('ajax error'); console.error('ajax error');
console.error(xhr); console.error(xhr);
console.error(type); console.error(type);
} }
}); });
} }
}
}); });
let TrainView = Backbone.View.extend({ const TrainView = Backbone.View.extend({
tagName: 'div', 'tagName': 'div',
initialize: function () { 'initialize': function () {
_.bindAll(this, 'render'); _.bindAll(this, 'render');
this.model.bind('change', this.render); this.model.bind('change', this.render);
this.$trains = $('#trains'); this.$trains = $('#trains');
this.$traininfo = $('#traininfo'); this.$traininfo = $('#traininfo');
this.$traintext = $('#trainResults'); this.$traintext = $('#trainResults');
this.$el = this.$trains; this.$el = this.$trains;
this.initView(); this.initView();
}, },
events: { 'events': {
'click': 'showTrains' 'click': 'showTrains'
}, },
render: function () { 'render': function () {
const obj = this.model.get('trainData');
const visible = this.model.get('visible');
const route = this.model.get('route');
let output, status; const output = (obj.eta.toLowerCase() === 'on time') ? obj.sta : obj.eta;
let obj = this.model.get('trainData'); const status = (obj.eta.toLowerCase() === 'on time') ? 'ontime' : 'delayed';
let visible = this.model.get('visible');
let route = this.model.get('route');
output = (obj.eta.toLowerCase() === 'on time') ? obj.sta : obj.eta; this.$button.html(output);
status = (obj.eta.toLowerCase() === 'on time') ? 'ontime' : 'delayed'; this.$button.removeClass('delayed').removeClass('ontime').addClass(status);
this.$button.html(output); if (visible) {
this.$button.removeClass('delayed').removeClass('ontime').addClass(status); let ws = `<div>${route.locationName} TO ${route.filterLocationName}</div>
if (visible) {
let ws = `<div>${route.locationName} TO ${route.filterLocationName}</div>
<table class="mui-table mui-table-bordered"> <table class="mui-table mui-table-bordered">
<tr><th>Destination</th> <tr><th>Destination</th>
<th>Time</th> <th>Time</th>
@ -143,89 +132,75 @@ let TrainView = Backbone.View.extend({
<th>Platform</th></tr> <th>Platform</th></tr>
`; `;
let services = []; const services = [];
if (typeof route.trainServices === 'object' && route.trainServices !== null) { if (typeof route.trainServices === 'object' && route.trainServices !== null)
for (let item of route.trainServices) { for (const item of route.trainServices) {
let dest = item.destination[0]; const dest = item.destination[0];
let via = dest.via !== null ? `<em>${dest.via}</em>` : ''; const via = dest.via !== null ? `<em>${dest.via}</em>` : '';
let platform = item.platform !== null ? item.platform : '💠'; const platform = item.platform !== null ? item.platform : '💠';
let time = item.sta !== null ? item.sta : `D ${item.std}`; const time = item.sta !== null ? item.sta : `D ${item.std}`;
let status = item.eta !== null ? item.eta : item.etd; const status = item.eta !== null ? item.eta : item.etd;
services.push({location:dest.locationName, time:time,status:status,platform:platform, cancel:item.cancelReason, type:'train'}); services.push({ 'location':dest.locationName, 'time':time, 'status':status, 'platform':platform, 'cancel':item.cancelReason, 'type':'train' });
if (!item.isCancelled) { if (!item.isCancelled)
ws = ws + `<tr> ws = `${ws }<tr><td>${dest.locationName} ${via}</td>
<td>${dest.locationName} ${via}</td> <td>${time}</td>
<td>${time}</td> <td>${status}</td>
<td>${status}</td> <td>${platform}</td>
<td>${platform}</td> </tr>`;
</tr>`; else
} else { ws = `${ws }<tr><td>${dest.locationName} ${via}</td><td>${time}</td>
ws = ws + `<tr> <td colspan="2"> ${item.cancelReason}</td></tr>`;
<td>${dest.locationName} ${via}</td> }
<td>${time}</td>
<td colspan="2"> ${item.cancelReason}</td>
</tr>`;
}
}
}
if (typeof route.busServices === 'object' && route.busServices !== null) { if (typeof route.busServices === 'object' && route.busServices !== null)
for (let item of route.busServices) { for (const item of route.busServices) {
let dest = item.destination[0]; const dest = item.destination[0];
let via = dest.via !== null ? `<em>${dest.via}</em>` : ''; const via = dest.via !== null ? `<em>${dest.via}</em>` : '';
let platform = item.platform !== null ? item.platform : ''; const platform = item.platform !== null ? item.platform : '';
let time = item.sta !== null ? item.sta : `D ${item.std}`; const time = item.sta !== null ? item.sta : `D ${item.std}`;
let status = item.eta !== null ? item.eta : item.etd; const status = item.eta !== null ? item.eta : item.etd;
services.push({location:dest.locationName, time:time,status:status,platform:platform, cancel:item.cancelReason, type:'bus'}); services.push({ 'location':dest.locationName, 'time':time, 'status':status, 'platform':platform, 'cancel':item.cancelReason, 'type':'bus' });
// ws = ws + `<div class="mui-row"><div class="mui-col-md-12"><strong>${dest.locationName} Bus</strong> ${via}</div></div>`; // ws = ws + `<div class="mui-row"><div class="mui-col-md-12"><strong>${dest.locationName} Bus</strong> ${via}</div></div>`;
// ws = ws + '<div class="mui-row"><div class="mui-col-md-12">' + item.sta + '</div></div>'; // ws = ws + '<div class="mui-row"><div class="mui-col-md-12">' + item.sta + '</div></div>';
ws = ws + `<tr> ws = `${ws }<tr><td>🚌 ${dest.locationName} ${via}</td><td>${time}</td><td>${status}</td><td>${platform}</td></tr>`;
<td>🚌 ${dest.locationName} ${via}</td>
<td>${time}</td>
<td>${status}</td>
<td>${platform}</td>
</tr>`;
}
}
ws = ws + '</table>';
this.$traintext.empty().html(ws);
this.$traintext.removeClass('mui--hide').addClass('mui--show');
} else {
this.$traintext.removeClass('mui--show').addClass('mui--hide');
} }
},
initView: function () { ws = `${ws }</table>`;
//el: $('#myView').get(0) this.$traintext.empty().html(ws);
let self = this; this.$traintext.removeClass('mui--hide').addClass('mui--show');
let target = this.model.get('target'); }
let html = `<div class='mui-col-xs-12 mui-col-md-6'>${target.toUpperCase()}: <button class="mui-btn mui-btn--flat" id="${target}"></button></div>`; else
this.$html = $(html); this.$traintext.removeClass('mui--show').addClass('mui--hide');
this.$html.on('click', function () { },
'initView': function () {
// el: $('#myView').get(0)
const self = this;
const target = this.model.get('target');
const html = `<div class='mui-col-xs-12 mui-col-md-6'>${target.toUpperCase()}: <button class="mui-btn mui-btn--flat" id="${target}"></button></div>`;
this.$html = $(html);
this.$html.on('click', function () {
// console.log(self) // console.log(self)
self.model.getRoute(); self.model.getRoute();
}); });
this.$trains.append(this.$html); this.$trains.append(this.$html);
// this.el = `#${target}`; // this.el = `#${target}`;
this.$button = $(`#${target}`); this.$button = $(`#${target}`);
let output = 'OFF'; const output = 'OFF';
let status = (output === 'on time') ? 'ontime' : 'delayed'; const status = (output === 'on time') ? 'ontime' : 'delayed';
this.$button.html(output); this.$button.html(output);
this.$button.removeClass('delayed').removeClass('ontime').addClass(status); this.$button.removeClass('delayed').removeClass('ontime').addClass(status);
let cevent = `click #$(target)`; const cevent = 'click #$(target)';
this.events[cevent] = "showTrains"; this.events[cevent] = 'showTrains';
}, },
showTrains: function () { 'showTrains': function () {
console.log('Show train'); console.log('Show train');
} }
}); });

View File

@ -6,92 +6,91 @@
* *
*/ */
let WeatherModel = Backbone.Model.extend({ const WeatherModel = Backbone.Model.extend({
initialize: function() { 'initialize': function() {
let geo = this.get('geo'); const geo = this.get('geo');
this.set('url','https://api.darksky.net/forecast/9ad2a41d420f3cf4960571bb886f710c/' + geo.coords.latitude.toString() + ',' + geo.coords.longitude.toString() + '?units=uk2&exclude=minutely,hourly,alerts,flags'); this.set('url', `https://api.darksky.net/forecast/9ad2a41d420f3cf4960571bb886f710c/${ geo.coords.latitude.toString() },${ geo.coords.longitude.toString() }?units=uk2&exclude=minutely,hourly,alerts,flags`);
this.update(); this.update();
}, },
update: function() { 'update': function() {
this.getWeather(); this.getWeather();
let now = new Date; const now = new Date;
let mod = 1800000 - (now.getTime() % 1800000); const mod = 1800000 - (now.getTime() % 1800000);
let weatherTrigger = function() { const weatherTrigger = () => {
this.update(); this.update();
}; };
setTimeout(weatherTrigger.bind(this), mod + 10); setTimeout(weatherTrigger.bind(this), mod + 10);
}, },
getWeather: function() { 'getWeather': function() {
let self = this; const self = this;
$.ajax({ $.ajax({
type: 'GET', 'type': 'GET',
url: self.get('url'), 'url': self.get('url'),
data: '', 'data': '',
dataType: 'jsonp', 'dataType': 'jsonp',
timeout: 10000, 'timeout': 10000,
context: $('body'), 'context': $('body'),
contentType: ('application/json'), 'contentType': ('application/json'),
headers: { 'headers': {
'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type' 'Access-Control-Allow-Headers': 'Content-Type'
}, },
success: function(data) { 'success': function(data) {
var stored = { const stored = {
temperature: data.currently.temperature, 'temperature': data.currently.temperature,
icon: data.currently.icon, 'icon': data.currently.icon,
summary: data.currently.summary, 'summary': data.currently.summary,
daily: data.daily.summary 'daily': data.daily.summary
}; };
self.set(stored); self.set(stored);
}, },
error: function(xhr, type) { 'error': function(xhr, type) {
console.error('ajax error'); console.error('ajax error');
console.error(xhr); console.error(xhr);
console.error(type); console.error(type);
} }
}); });
} }
}); });
let Weather = Backbone.View.extend({ const Weather = Backbone.View.extend({
tagName: 'div', 'tagName': 'div',
initialize: function() { 'initialize': function() {
_.bindAll(this, 'render'); _.bindAll(this, 'render');
this.model.bind('change', this.render); this.model.bind('change', this.render);
this.$weatherText = $('#weatherDescription'); this.$weatherText = $('#weatherDescription');
this.$weatherTemp = $('#temp'); this.$weatherTemp = $('#temp');
this.$weatherIcon = $('#weatherIcon'); this.$weatherIcon = $('#weatherIcon');
}, },
render: function() { 'render': function() {
console.log('Weather:Render'); console.log('Weather:Render');
var ws = '<i class="wi wi-forecast-io-' + this.model.get('icon') + '"></i>'; const ws = `<i class="wi wi-forecast-io-${ this.model.get('icon') }"></i>`;
this.$weatherTemp.empty().html(parseInt(this.model.get('temperature')) + '&deg;c&nbsp;'); this.$weatherTemp.empty().html(`${parseInt(this.model.get('temperature')) }&deg;c&nbsp;`);
this.$weatherText.empty().html(this.model.get('summary')); this.$weatherText.empty().html(this.model.get('summary'));
this.$weatherIcon.empty().html(ws); this.$weatherIcon.empty().html(ws);
} }
}); });
let WeatherSlim = Backbone.View.extend({ const WeatherSlim = Backbone.View.extend({
tagName: 'div', 'tagName': 'div',
initialize: function() { 'initialize': function() {
_.bindAll(this, 'render'); _.bindAll(this, 'render');
this.model.bind('change', this.render); this.model.bind('change', this.render);
this.$weather = $('#weather'); this.$weather = $('#weather');
this.render(); this.render();
}, },
render: function() { 'render': function() {
const summary = this.model.get('summary');
const temp = this.model.get('temperature');
const daily = this.model.get('daily');
let summary = this.model.get('summary'); const ws = `${summary} ${temp}&deg;&nbsp;<em>${daily}</em>`;
let temp = this.model.get('temperature');
let daily = this.model.get('daily');
let ws = `${summary} ${temp}&deg;&nbsp;<em>${daily}</em>`;
this.$weather.empty().html(ws); this.$weather.empty().html(ws);
} }

File diff suppressed because one or more lines are too long

View File

@ -1,83 +1,82 @@
const gulp = require('gulp'); const gulp = require('gulp');
let autoprefixer = require('gulp-autoprefixer'); const autoprefixer = require('gulp-autoprefixer');
let cssnano = require('gulp-cssnano'); const cssnano = require('gulp-cssnano');
let jshint = require('gulp-jshint'); const jshint = require('gulp-jshint');
let uglify = require('gulp-uglify'); const uglify = require('gulp-uglify');
let rename = require('gulp-rename'); const rename = require('gulp-rename');
let concat = require('gulp-concat'); const concat = require('gulp-concat');
let cache = require('gulp-cache'); const cache = require('gulp-cache');
let htmlmin = require('gulp-htmlmin'); const htmlmin = require('gulp-htmlmin');
let htmlreplace = require('gulp-html-replace'); const htmlreplace = require('gulp-html-replace');
let stripDebug = require('gulp-strip-debug'); const stripDebug = require('gulp-strip-debug');
let scss = require('gulp-scss'); const scss = require('gulp-scss');
let sass = require('gulp-sass'); const sass = require('gulp-sass');
let googleWebFonts = require('gulp-google-webfonts'); const googleWebFonts = require('gulp-google-webfonts');
let babel = require('gulp-babel'); const babel = require('gulp-babel');
let filePath = { const filePath = {
build_dir: 'live' 'build_dir': 'live'
}; };
let dest = 'app/live'; const dest = 'app/live';
let fontOptions = { }; const fontOptions = { };
gulp.task('appJS', function() { gulp.task('appJS', function() {
return gulp.src(['app/js/modules/events.js', 'app/js/modules/bitcoin.js', 'app/js/modules/fx.js', 'app/js/modules/train.js','app/js/modules/weather.js','app/js/modules/password.js', 'app/app.js']) return gulp.src(['app/js/modules/events.js', 'app/js/modules/bitcoin.js', 'app/js/modules/fx.js', 'app/js/modules/train.js', 'app/js/modules/weather.js', 'app/js/modules/password.js', 'app/app.js'])
.pipe(stripDebug()) .pipe(stripDebug())
.pipe(jshint('.jshintrc')) .pipe(jshint('.jshintrc'))
.pipe(jshint.reporter('default')) .pipe(jshint.reporter('default'))
.pipe(babel({presets: ['es2015']})) .pipe(babel({ 'presets': ['es2015'] }))
.pipe(concat('app.js')) .pipe(concat('app.js'))
.pipe(uglify({mangle: true, compress: {sequences: true, // Join consecutive statemets with the “comma operator” /*.pipe(uglify({ 'mangle': true, 'compress': { 'sequences': true, // Join consecutive statemets with the comma operator
properties: true, // Optimize property access: a["foo"] → a.foo 'properties': true, // Optimize property access: a["foo"] → a.foo
dead_code: true, // Discard unreachable code 'dead_code': true, // Discard unreachable code
drop_debugger: true, // Discard “debugger” statements 'drop_debugger': true, // Discard “debugger” statements
unsafe: false, // Some unsafe optimizations (see below) 'unsafe': false, // Some unsafe optimizations (see below)
conditionals: true, // Optimize if-s and conditional expressions 'conditionals': true, // Optimize if-s and conditional expressions
comparisons: true, // Optimize comparisons 'comparisons': true, // Optimize comparisons
evaluate: true, // Evaluate constant expressions 'evaluate': true, // Evaluate constant expressions
booleans: true, // Optimize boolean expressions 'booleans': true, // Optimize boolean expressions
loops: true, // Optimize loops 'loops': true, // Optimize loops
unused: true, // Drop unused variables/functions 'unused': true, // Drop unused variables/functions
hoist_funs: true, // Hoist function declarations 'hoist_funs': true, // Hoist function declarations
hoist_vars: true, // Hoist variable declarations 'hoist_vars': true, // Hoist variable declarations
if_return: true, // Optimize if-s followed by return/continue 'if_return': true, // Optimize if-s followed by return/continue
join_vars: true, // Join var declarations 'join_vars': true, // Join var declarations
cascade: true, // Try to cascade `right` into `left` in sequences 'cascade': true, // Try to cascade `right` into `left` in sequences
side_effects: true, // Drop side-effect-free statements 'side_effects': true, // Drop side-effect-free statements
warnings: true, // Warn about potentially dangerous optimizations/code 'warnings': true, // Warn about potentially dangerous optimizations/code
global_defs: {} // global definitions 'global_defs': {} // global definitions
}})) } }))*/
.pipe(gulp.dest(dest + '/js')); .pipe(gulp.dest(`${dest }/js`));
}); });
gulp.task('customMUI', function() { gulp.task('customMUI', function() {
return gulp.src(['app/css/custom.scss']) return gulp.src(['app/css/custom.scss'])
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError)) .pipe(sass({ 'outputStyle': 'compressed' }).on('error', sass.logError))
//.pipe(cssnano()) // .pipe(cssnano())
.pipe(rename('mui.custom.css')) .pipe(rename('mui.custom.css'))
.pipe(gulp.dest(dest + '/css')); .pipe(gulp.dest(`${dest }/css`));
}); });
gulp.task('vendor', function() { gulp.task('vendor', function() {
return gulp.src([ return gulp.src([
'bower_components/zepto/zepto.min.js', 'bower_components/zepto/zepto.min.js',
'bower_components/ejs/ejs.min.js', 'bower_components/ejs/ejs.min.js',
'bower_components/underscore/underscore-min.js', 'bower_components/underscore/underscore-min.js',
'bower_components/backbone/backbone-min.js' 'bower_components/backbone/backbone-min.js'
]) ])
.pipe(concat('vendor.js')) .pipe(concat('vendor.js'))
.pipe(uglify({mangle: false})) .pipe(uglify({ 'mangle': false }))
.pipe(gulp.dest(dest + '/js')); .pipe(gulp.dest(`${dest }/js`));
}); });
gulp.task('fonts', function() { gulp.task('fonts', function() {
return gulp.src('./fonts.list') return gulp.src('./fonts.list')
.pipe(googleWebFonts(fontOptions)) .pipe(googleWebFonts(fontOptions))
.pipe(gulp.dest(dest + '/fonts')) .pipe(gulp.dest(`${dest }/fonts`))
; ;
}); });
gulp.task('default', ['appJS', 'vendor', 'customMUI', 'fonts']); gulp.task('default', ['appJS', 'vendor', 'customMUI', 'fonts']);

View File

@ -5,17 +5,18 @@ const trend = require('trend');
const logger = require('log4js').getLogger('btc'); const logger = require('log4js').getLogger('btc');
let btcCache = {}; let btcCache = {};
let balanceCache = {}; let balanceCache = {};
let history = new LimitedArray(288); // one days worth in 5 minute chunks const history = new LimitedArray(288); // one days worth in 5 minute chunks
function getBitcoin () { function getBitcoin () {
logger.info('>> getting bitcoin'); logger.info('>> getting bitcoin');
function btcQuery (callback) { function btcQuery (callback) {
const options = { const options = {
host: 'api.coindesk.com', 'host': 'api.coindesk.com',
// port: 80, // port: 80,
path: '/v1/bpi/currentprice.json', 'path': '/v1/bpi/currentprice.json',
// method: 'GET', // method: 'GET',
headers: { 'headers': {
/* 'Content-Type': 'application/json', /* 'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)*/ 'Content-Length': Buffer.byteLength(data)*/
@ -28,43 +29,43 @@ function getBitcoin () {
data += chunk; data += chunk;
}); });
response.on('end', () => { response.on('end', () => {
let cData = {}; let cData = {};
try { try {
cData = JSON.parse(data); cData = JSON.parse(data);
} catch (e) { }
catch (e) {
logger.error(e); logger.error(e);
} finally{ }
finally{
callback(cData); callback(cData);
} }
}); });
response.on('error', e => { response.on('error', e => {
logger.error(e); logger.error(e);
}); });
}).end(); }).end();
} catch (e) { }
catch (e) {
logger.error(e); logger.error(e);
} }
} }
btcQuery(a => { btcQuery(a => {
// logger.info(a); // logger.info(a);
logger.info('Got btc data. Storing it'); logger.info('Got btc data. Storing it');
logger.debug('>> btc', a); logger.debug('>> btc', a);
btcCache = a; btcCache = a;
history.push(a.bpi.USD.rate_float); history.push(a.bpi.USD.rate_float);
btcCache.history = history.get(); btcCache.history = history.get();
btcCache.trend = trend(btcCache.history, {avgPoints: 12}); btcCache.trend = trend(btcCache.history, { 'avgPoints': 12 });
GLOBAL.lastcheck = new Date(); GLOBAL.lastcheck = new Date();
}); });
} }
function getBalance() { function getBalance() {
logger.info('>> getting Balance'); logger.info('>> getting Balance');
function balanceQuery (callback, r) { function balanceQuery (callback, r) {
try { try {
https.get('https://blockexplorer.com/api/addr/18sLVW5Aswp2KWLr4hMFZsuSPtvAauFiif').on('response', response => { https.get('https://blockexplorer.com/api/addr/18sLVW5Aswp2KWLr4hMFZsuSPtvAauFiif').on('response', response => {
let data = ''; let data = '';
@ -75,18 +76,20 @@ function getBalance() {
let cData = {}; let cData = {};
try { try {
cData = JSON.parse(data); cData = JSON.parse(data);
} catch (e) { }
catch (e) {
logger.error(e); logger.error(e);
} finally{ }
finally{
callback(cData, r); callback(cData, r);
} }
}); });
response.on('error', e => { response.on('error', e => {
logger.error(e); logger.error(e);
}); });
}).end(); }).end();
} catch (e) { }
catch (e) {
logger.error(e); logger.error(e);
} }
} }
@ -94,12 +97,9 @@ function getBalance() {
balanceQuery(a => { balanceQuery(a => {
logger.info('Got balance data. Storing it'); logger.info('Got balance data. Storing it');
balanceCache = a; balanceCache = a;
}); });
} }
exports.doBTC = (req, res) => { exports.doBTC = (req, res) => {
logger.info('Bitcoin request'); logger.info('Bitcoin request');
res.setHeader('Content-Type', 'application/json'); res.setHeader('Content-Type', 'application/json');
@ -110,30 +110,27 @@ exports.doBalance = (req, res) => {
logger.info('Balance request'); logger.info('Balance request');
res.setHeader('Content-Type', 'application/json'); res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(balanceCache)); res.end(JSON.stringify(balanceCache));
}; };
function updateBitcoin() { function updateBitcoin() {
logger.warn('updateBitcoin'); logger.warn('updateBitcoin');
getBitcoin(); getBitcoin();
const now = new Date(); const now = new Date();
const mod = 300000 - (now.getTime() % 300000); const mod = 300000 - (now.getTime() % 300000);
let btcupdateFn = () => { const btcupdateFn = () => {
updateBitcoin(); updateBitcoin();
}; };
setTimeout(btcupdateFn.bind(this), mod + 10); setTimeout(btcupdateFn.bind(this), mod + 10);
} }
function updateBalance() { function updateBalance() {
logger.warn('updateBalance'); logger.warn('updateBalance');
getBalance(); getBalance();
const now = new Date(); const now = new Date();
const mod = 3.6e+6 - (now.getTime() % 3.6e+6); const mod = 3.6e+6 - (now.getTime() % 3.6e+6);
let balanceUpdateFn = () => { const balanceUpdateFn = () => {
updateBalance(); updateBalance();
}; };
setTimeout(balanceUpdateFn.bind(this), mod + 10); setTimeout(balanceUpdateFn.bind(this), mod + 10);

View File

@ -6,16 +6,16 @@ var calHandler = require('./today/calHandler');
require('sugar-date'); require('sugar-date');
var cal = {today: [], tomorrow: [], week: []}; var cal = { 'today': [], 'tomorrow': [], 'week': [] };
var _cal_tmp = {today: [], tomorrow: [], week: []}; var _cal_tmp = { 'today': [], 'tomorrow': [], 'week': [] };
for (var t = 0; t < calHandler.calendars.length;t++) { for (var t = 0; t < calHandler.calendars.length;t++)
calHandler.getAdvancedCalV3(calHandler.calendars[t]) calHandler.getAdvancedCalV3(calHandler.calendars[t])
.then((d) => { .then((d) => {
'use strict'; 'use strict';
cal.today = cal.today.concat(d.today); cal.today = cal.today.concat(d.today);
cal.tomorrow = cal.tomorrow.concat(d.tomorrow); cal.tomorrow = cal.tomorrow.concat(d.tomorrow);
cal.week = cal.week.concat(d.week); cal.week = cal.week.concat(d.week);
logger.error(cal); logger.error(cal);
@ -24,7 +24,7 @@ for (var t = 0; t < calHandler.calendars.length;t++) {
'use strict'; 'use strict';
logger.error(e); logger.error(e);
}); });
}

View File

@ -2,48 +2,48 @@ var http = require('http'), sys = require('sys');
module.exports = { module.exports = {
cleanit: function (req, res) { 'cleanit': function (req, res) {
var r = { var r = {
// from http://tim.mackey.ie/CleanWordHTMLUsingRegularExpressions.aspx // from http://tim.mackey.ie/CleanWordHTMLUsingRegularExpressions.aspx
msoTags: /<[\/]?(font|span|xml|del|ins|[ovwxp]:\w+)[^>]*?>/g, 'msoTags': /<[\/]?(font|span|xml|del|ins|[ovwxp]:\w+)[^>]*?>/g,
msoAttributes: /<([^>]*)(?:class|lang|style|size|face|[ovwxp]:\w+)=(?:'[^']*'|""[^""]*""|[^\s>]+)([^>]*)>/, 'msoAttributes': /<([^>]*)(?:class|lang|style|size|face|[ovwxp]:\w+)=(?:'[^']*'|""[^""]*""|[^\s>]+)([^>]*)>/,
msoParagraphs: /<([^>]*)(?:|[p]:\w+)=(?:'[^']*'|""[^""]*""|[^\s>]+)([^>]*)>/g, 'msoParagraphs': /<([^>]*)(?:|[p]:\w+)=(?:'[^']*'|""[^""]*""|[^\s>]+)([^>]*)>/g,
crlf: /(\\r\\n)/g 'crlf': /(\\r\\n)/g
}; };
var front = '<?xml version="1.0" encoding="utf-8"?>\r\n <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\r\n <html xmlns="http://www.w3.org/1999/xhtml">\r\n <head>\r\n <title>Spellbinder - Chapter </title>\r\n <link rel="stylesheet" type="text/css" href="imperaWeb.css"/>\r\n <link rel="stylesheet" type= "application/vnd.adobe-page-template+xml" href= "page-template.xpgt"/>\r\n </head>\r\n <body>\r\n <div id="text">\r\n <div class="section" id="xhtmldocuments">\r\n'; var front = '<?xml version="1.0" encoding="utf-8"?>\r\n <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\r\n <html xmlns="http://www.w3.org/1999/xhtml">\r\n <head>\r\n <title>Spellbinder - Chapter </title>\r\n <link rel="stylesheet" type="text/css" href="imperaWeb.css"/>\r\n <link rel="stylesheet" type= "application/vnd.adobe-page-template+xml" href= "page-template.xpgt"/>\r\n </head>\r\n <body>\r\n <div id="text">\r\n <div class="section" id="xhtmldocuments">\r\n';
var back = ' </div> </div> </body> </html> '; var back = ' </div> </div> </body> </html> ';
var source = req.body.source; var source = req.body.source;
// console.log(source); // console.log(source);
var output = source.replace(r.msoTags, ""); var output = source.replace(r.msoTags, '');
output = output.replace(r.msoParagraphs, '<p>'); output = output.replace(r.msoParagraphs, '<p>');
output = output.replace(/(\r\n)/g, " "); output = output.replace(/(\r\n)/g, ' ');
output = output.replace(/(\\r\\n)/g, " "); output = output.replace(/(\\r\\n)/g, ' ');
output = output.replace(/<i><\/i>/g, ""); output = output.replace(/<i><\/i>/g, '');
output = output.replace(/[“|”]/g, '"'); output = output.replace(/[“|”]/g, '"');
output = output.replace(//g, "'"); output = output.replace(//g, '\'');
output = output.replace(/…/g, "&#8230;"); output = output.replace(/…/g, '&#8230;');
output = output.replace(/<i>(.*?)<\/i>/g, "<em>$1</em>"); output = output.replace(/<i>(.*?)<\/i>/g, '<em>$1</em>');
output = output.replace(/<b>(.*?)<\/b>/g, "<strong>$1</strong>"); output = output.replace(/<b>(.*?)<\/b>/g, '<strong>$1</strong>');
output = output.replace(/<p>\*\*\*<\/p>/g, "<p class='break'>* * *</p>"); output = output.replace(/<p>\*\*\*<\/p>/g, '<p class=\'break\'>* * *</p>');
output = output.replace(/<p>CHAPTER\s(\d.?)<\/p>/, "<h1>$1</h1>"); output = output.replace(/<p>CHAPTER\s(\d.?)<\/p>/, '<h1>$1</h1>');
output = output.replace(/<p>(&nbsp;|\s|<em>\s<\/em>)<\/p>/g, ""); output = output.replace(/<p>(&nbsp;|\s|<em>\s<\/em>)<\/p>/g, '');
output = output.replace(/&nbsp;/g, " "); output = output.replace(/&nbsp;/g, ' ');
output = output.replace(/<p><em>\s<\/em><\/p>/g, ""); output = output.replace(/<p><em>\s<\/em><\/p>/g, '');
output = output.replace(/<p>\s<\/p>/g, ""); output = output.replace(/<p>\s<\/p>/g, '');
output = output.replace(/\s+/g, " "); output = output.replace(/\s+/g, ' ');
output = output.replace(/<\/p>/g, "</p>\r\n"); output = output.replace(/<\/p>/g, '</p>\r\n');
// sys.puts(sys.inspect(output, false, null)); // sys.puts(sys.inspect(output, false, null));
res.setHeader('Content-Type', 'application/html'); res.setHeader('Content-Type', 'application/html');
res.end(front + output + back); res.end(front + output + back);
} }
}; };

View File

@ -1,145 +1,142 @@
var http = require('http'), request = require('request'), cheerio = require('cheerio'); const http = require('http'), request = require('request'), cheerio = require('cheerio');
var eventTimer = 0; const eventTimer = 0;
var eventCache = { const eventCache = {
last: 0, 'last': 0,
data: {}, 'data': {},
expire: ((60 * 1000) * 60) * 12, 'expire': ((60 * 1000) * 60) * 12,
cinema: {} 'cinema': {}
}; };
// 'cwr':{data: {}, last:0}; // 'cwr':{data: {}, last:0};
var cinemas = [{id: 'cwr', url: 'https://film.list.co.uk/cinema/14982-cineworld-renfrew-street/'}, const cinemas = [{ 'id': 'cwr', 'url': 'https://film.list.co.uk/cinema/14982-cineworld-renfrew-street/' },
{id: 'gsc', url: 'https://film.list.co.uk/cinema/13590-cineworld-glasgow-science-centre/'}, { 'id': 'gsc', 'url': 'https://film.list.co.uk/cinema/13590-cineworld-glasgow-science-centre/' },
{id: 'pho', url: 'https://film.list.co.uk/cinema/12500-showcase-cinema-paisley/'}]; { 'id': 'pho', 'url': 'https://film.list.co.uk/cinema/12500-showcase-cinema-paisley/' }];
module.exports = { module.exports = {
getEvents: function (req, res) { 'getEvents': function (req, res) {
console.log('Getting events...');
const j = [], url = 'https://www.list.co.uk/events/days-out/when:this%20weekend/location:Dumbarton(55.9460,-4.5556)/distance:20/';
console.log('Getting events...'); const now = new Date();
var j = [], url = 'https://www.list.co.uk/events/days-out/when:this%20weekend/location:Dumbarton(55.9460,-4.5556)/distance:20/';
var now = new Date(); if ((now - eventCache.last) > eventCache.expire)
request(url, function (err, resp, body) {
if ((now - eventCache.last) > eventCache.expire) { if (err)
request(url, function (err, resp, body) { throw err;
if (err) $ = cheerio.load(body);
throw err;
$ = cheerio.load(body);
// console.log($); // console.log($);
// TODO: scraping goes here! // TODO: scraping goes here!
$('.resultsRow').each(function (div) { $('.resultsRow').each(function (div) {
var item = {}; const item = {};
var eventSummary = $(this).find('.eventSummary').first(); const eventSummary = $(this).find('.eventSummary').first();
var byDate = $(this).find('.byDate').first(); const byDate = $(this).find('.byDate').first();
var title = eventSummary.find('.head').first(); const title = eventSummary.find('.head').first();
var description = eventSummary.find('P').first(); const description = eventSummary.find('P').first();
var link = ' https://www.list.co.uk' + eventSummary.find('A').first().attr('href'); const link = ` https://www.list.co.uk${ eventSummary.find('A').first().attr('href')}`;
var price = byDate.find('.price').first(); const price = byDate.find('.price').first();
var dt = byDate.find('.dtstart').first().attr('title'); const dt = byDate.find('.dtstart').first().attr('title');
item.title = title.text(); item.title = title.text();
item.description = description.text(); item.description = description.text();
item.link = link; item.link = link;
item.price = price.text(); item.price = price.text();
item.date = dt; item.date = dt;
j.push(item); j.push(item);
}); });
eventCache.last = now; eventCache.last = now;
eventCache.data = j; eventCache.data = j;
res.render('pages/events', eventCache); res.render('pages/events', eventCache);
}, function(error, response, body) {
}, function(error, response, body) { if(response.statusCode !== 200) {
if(response.statusCode !== 200) { logger.error(response.statusCode);
logger.error(response.statusCode); logger.error(body);
logger.error(body);
}
});
} else {
console.log('Using event cache...');
res.render('pages/events', eventCache);
} }
});
else {
console.log('Using event cache...');
}, res.render('pages/events', eventCache);
doGetCinema: function (id) {
var cinemaID = cinemas[id].id;
var url = cinemas[id].url;
var thisCinema = eventCache[cinemaID] || {data: {}, last: 0};
console.log(cinemaID);
console.log(url);
var j = [];
var now = new Date();
if ((now - thisCinema.last) > eventCache.expire) {
request(url, function (err, resp, body) {
console.log('Working');
if (err)
throw err;
$ = cheerio.load(body);
$('.byEvent').each(function (div) {
var item = {};
var title = $(this).find('H4').first();
var eventSummary = $(this).find('.eventSummary').first();
var description = eventSummary.find('P').first();
var link = ' https://www.list.co.uk' + eventSummary.find('A').first().attr('href');
item.title = title.text();
item.description = description.text();
item.link = link;
j.push(item);
});
thisCinema.last = now;
thisCinema.data = j;
eventCache[cinemaID] = thisCinema;
console.log('returning');
return thisCinema;
}, function(error, response, body) {
if(response.statusCode !== 200) {
console.error(response.statusCode);
console.error(body);
}
});
} else {
console.log('Using event cache...');
return thisCinema;
}
},
getCinema: function (req, res) {
var id = parseInt(req.params.id);
console.log('Getting cinema: ' +id);
var output = module.exports.doGetCinema(id);
res.render('pages/cinema', output);
},
preLoad: function () {
var output = module.exports.doGetCinema(0);
output = module.exports.doGetCinema(1);
output = module.exports.doGetCinema(2);
setTimeout(function () {
module.exports.preLoad();
}, eventCache.expire);
} }
},
'doGetCinema': function (id) {
const cinemaID = cinemas[id].id;
const url = cinemas[id].url;
const thisCinema = eventCache[cinemaID] || { 'data': {}, 'last': 0 };
console.log(cinemaID);
console.log(url);
const j = [];
const now = new Date();
if ((now - thisCinema.last) > eventCache.expire)
request(url, function (err, resp, body) {
console.log('Working');
if (err)
throw err;
$ = cheerio.load(body);
$('.byEvent').each(function (div) {
const item = {};
const title = $(this).find('H4').first();
const eventSummary = $(this).find('.eventSummary').first();
const description = eventSummary.find('P').first();
const link = ` https://www.list.co.uk${ eventSummary.find('A').first().attr('href')}`;
item.title = title.text();
item.description = description.text();
item.link = link;
j.push(item);
});
thisCinema.last = now;
thisCinema.data = j;
eventCache[cinemaID] = thisCinema;
console.log('returning');
return thisCinema;
}, function(error, response, body) {
if(response.statusCode !== 200) {
console.error(response.statusCode);
console.error(body);
}
});
else {
console.log('Using event cache...');
return thisCinema;
}
},
'getCinema': function (req, res) {
const id = parseInt(req.params.id);
console.log(`Getting cinema: ${ id}`);
const output = module.exports.doGetCinema(id);
res.render('pages/cinema', output);
},
'preLoad': function () {
let output = module.exports.doGetCinema(0);
output = module.exports.doGetCinema(1);
output = module.exports.doGetCinema(2);
setTimeout(function () {
module.exports.preLoad();
}, eventCache.expire);
}
}; };
setTimeout(function () { setTimeout(function () {
console.log('Pre loading cinemas...'); console.log('Pre loading cinemas...');
module.exports.preLoad(); module.exports.preLoad();
}, 10000); }, 10000);

View File

@ -4,17 +4,17 @@ const trend = require('trend');
const logger = require('log4js').getLogger('fx'); const logger = require('log4js').getLogger('fx');
const delay = 2764800; // 32 days divided by 1000 const delay = 2764800; // 32 days divided by 1000
let fxCache = {}; let fxCache = {};
let history = new LimitedArray(48); // one days worth in 5 minute chunks const history = new LimitedArray(48); // one days worth in 5 minute chunks
function getFx() { function getFx() {
logger.info('FX request'); logger.info('FX request');
function fxQuery(callback) { function fxQuery(callback) {
let options = { const options = {
host: 'openexchangerates.org', 'host': 'openexchangerates.org',
// port: 80, // port: 80,
path: '/api/latest.json?app_id=0eb932cee3bc40259f824d4b4c96c7d2', 'path': '/api/latest.json?app_id=0eb932cee3bc40259f824d4b4c96c7d2',
// method: 'GET', // method: 'GET',
headers: { } 'headers': { }
}; };
http.request(options).on('response', response => { http.request(options).on('response', response => {
@ -36,12 +36,10 @@ function getFx() {
logger.info('Got FX data. Storing it'); logger.info('Got FX data. Storing it');
fxCache = a; fxCache = a;
let minRates = {USD:fxCache.rates.USD, GBP:fxCache.rates.GBP, SEK:fxCache.rates.SEK}; fxCache.rates = { 'USD': fxCache.rates.USD, 'GBP': fxCache.rates.GBP, 'SEK': fxCache.rates.SEK };
fxCache.rates = minRates;
history.push(a.rates.GBP); history.push(a.rates.GBP);
fxCache.history = history.get(); fxCache.history = history.get();
fxCache.trend = trend(fxCache.history, {avgPoints: 12}); fxCache.trend = trend(fxCache.history, { 'avgPoints': 12 });
}); });
} }
@ -55,7 +53,7 @@ function updateFX() {
const mod = delay - (now.getTime() % delay); const mod = delay - (now.getTime() % delay);
let fxUpdateFn = () => { const fxUpdateFn = () => {
updateFX(); updateFX();
}; };
setTimeout(fxUpdateFn.bind(this), mod + 10); setTimeout(fxUpdateFn.bind(this), mod + 10);
@ -67,5 +65,4 @@ exports.doFx = (req, res) => {
logger.info('FX request'); logger.info('FX request');
res.setHeader('Content-Type', 'application/json'); res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(fxCache)); res.end(JSON.stringify(fxCache));
}; };

View File

@ -46,19 +46,18 @@ var numberCluster = function () {
var randomAmount = function (i) { var randomAmount = function (i) {
var str = ''; var str = '';
for (var t = 0; t < i; t++) { for (var t = 0; t < i; t++)
str = str + alpha.random(); str = str + alpha.random();
}
return str; return str;
}; };
module.exports = { module.exports = {
generate: function (req, res) { 'generate': function (req, res) {
var reply = { var reply = {
long: (left.random() + ' ' + right.random() + ' ' + numberCluster() + ' ' + numberCluster()).split(' ').join(whitespace.random()), 'long': (`${left.random() } ${ right.random() } ${ numberCluster() } ${ numberCluster()}`).split(' ').join(whitespace.random()),
short: randomAmount(10) 'short': randomAmount(10)
}; };
res.setHeader('Content-Type', 'application/json'); res.setHeader('Content-Type', 'application/json');

View File

@ -24,7 +24,7 @@
</div> </div>
<script type="text/template" id="password-template"> <script type="text/template" id="password-template">
<div>Long: {{ long }}</div><div>Short: {{ short }}</div> <div>Long: {{=long }}</div><div>Short: {{=short }}</div>
</script> </script>
</body> </body>
<script src="live/js/vendor.js"></script> <script src="live/js/vendor.js"></script>

View File

@ -20,24 +20,23 @@ const errorhandler = require('errorhandler');
const jsonfile = require('jsonfile'); const jsonfile = require('jsonfile');
const Events = require('events'); const Events = require('events');
let busEmitter = new Events.EventEmitter(); const busEmitter = new Events.EventEmitter();
//busEmitter.on('update', today.broadcast); // busEmitter.on('update', today.broadcast);
const WebSocketServer = require('ws').Server; const WebSocketServer = require('ws').Server;
const wss = new WebSocketServer({server: server}); const wss = new WebSocketServer({ 'server': server });
const SocketHandler = require('./lib/wshandlerv2'); const SocketHandler = require('./lib/wshandlerv2');
let webSocket = new SocketHandler(busEmitter, wss); const webSocket = new SocketHandler(busEmitter, wss);
//today.setEmitter(busEmitter); // today.setEmitter(busEmitter);
// train = require('lib/train') // train = require('lib/train')
/* ,submit = require('./routes/mongo/submit') */ /* ,submit = require('./routes/mongo/submit') */
const fs = require('fs');
let fs = require('fs');
const config = require('./config/config.json'); const config = require('./config/config.json');
const Fitbit = require('fitbit-oauth2'); const Fitbit = require('fitbit-oauth2');
@ -51,20 +50,20 @@ let btcCache = {}, fxCache = {}, trainCache = {};
const port = process.env.PORT || 9000; const port = process.env.PORT || 9000;
// app.configure(function () { // app.configure(function () {
app.set('port', port); app.set('port', port);
app.set('view engine', 'ejs'); app.set('view engine', 'ejs');
app.use(morgan('dev')); app.use(morgan('dev'));
app.use(cookieParser('your secret here')); app.use(cookieParser('your secret here'));
app.use(session({ app.use(session({
secret: 'd2jRT6ZpYFsXsF3kGS21ZszKbPAaEa', resave: false, 'secret': 'd2jRT6ZpYFsXsF3kGS21ZszKbPAaEa', 'resave': false,
saveUninitialized: false 'saveUninitialized': false
})); }));
/* 'default', 'short', 'tiny', 'dev' */ /* 'default', 'short', 'tiny', 'dev' */
app.use(methodoverride()); app.use(methodoverride());
app.use(bodyparser.urlencoded({extended: false})); app.use(bodyparser.urlencoded({ 'extended': false }));
// parse application/json // parse application/json
app.use(bodyparser.json()); app.use(bodyparser.json());
@ -77,7 +76,7 @@ app.use(function(req, res, next) {
// app.use(app.router); // app.use(app.router);
app.use(express.static(path.join(__dirname, 'app'))); app.use(express.static(path.join(__dirname, 'app')));
app.use(errorhandler({dumpExceptions: true, showStack: true})); app.use(errorhandler({ 'dumpExceptions': true, 'showStack': true }));
app.use('/btc', btc.doBTC); app.use('/btc', btc.doBTC);
app.use('/balance', btc.doBalance); app.use('/balance', btc.doBalance);
@ -94,26 +93,22 @@ app.use('/generate', password.generate);
app.use('/cleanit', clean.cleanit); app.use('/cleanit', clean.cleanit);
app.use('/events', events.getEvents); app.use('/events', events.getEvents);
app.get('/cinema/:id', events.getCinema); app.get('/cinema/:id', events.getCinema);
// app.get('/today', today.getToday); // app.get('/today', today.getToday);
// app.get('/today/data', today.getData); // app.get('/today/data', today.getData);
//app.route('/clock').get(today.getClock); // app.route('/clock').get(today.getClock);
app.route('/poly').get(polys); app.route('/poly').get(polys);
/* app.use('/lot', function(req, res) {
/*app.use('/lot', function(req, res) {
const pg = require('pg'); const pg = require('pg');
const conString = 'postgres://pguser:1V3D4m526i@localhost/silver'; const conString = 'postgres://pguser:1V3D4m526i@localhost/silver';
console.log(conString); console.log(conString);
const client = new pg.Client(conString); const client = new pg.Client(conString);
const q = 'select * from lot order by d desc'; const q = 'select * from lot order by d desc';
client.connect(function(err) { client.connect(function(err) {
@ -140,15 +135,11 @@ app.get('/temp', function(req, res) {
res.render('pages/temp'); res.render('pages/temp');
}); });
const tfile = 'fb-token.json'; const tfile = 'fb-token.json';
// Instanciate a fitbit client. See example config below. // Instanciate a fitbit client. See example config below.
// //
const fitbit = new Fitbit(config.fitbit); const fitbit = new Fitbit(config.fitbit);
// In a browser, http://localhost:4000/fitbit to authorize a user for the first time. // In a browser, http://localhost:4000/fitbit to authorize a user for the first time.
@ -157,11 +148,10 @@ app.get('/fitbit', function(req, res) {
res.redirect(fitbit.authorizeURL()); res.redirect(fitbit.authorizeURL());
}); });
app.get( '/fb-profile', function( req, res, next ) { app.get( '/fb-profile', function( req, res, next ) {
fitbit.request({ fitbit.request({
uri: 'https://api.fitbit.com/1/user/-/profile.json', 'uri': 'https://api.fitbit.com/1/user/-/profile.json',
method: 'GET', 'method': 'GET'
}, function( err, body, token ) { }, function( err, body, token ) {
if ( err ) return next( err ); if ( err ) return next( err );
var profile = JSON.parse( body ); var profile = JSON.parse( body );
@ -169,20 +159,20 @@ app.get( '/fb-profile', function( req, res, next ) {
if ( token ) if ( token )
persist.write( tfile, token, function( err ) { persist.write( tfile, token, function( err ) {
if ( err ) return next( err ); if ( err ) return next( err );
res.send( '<pre>' + JSON.stringify( profile, null, 2 ) + '</pre>' ); res.send( `<pre>${ JSON.stringify( profile, null, 2 ) }</pre>` );
}); });
else else
res.send( '<pre>' + JSON.stringify( profile, null, 2 ) + '</pre>' ); res.send( `<pre>${ JSON.stringify( profile, null, 2 ) }</pre>` );
}); });
}); });
app.get( '/fb-today', function( req, res, next ) { app.get( '/fb-today', function( req, res, next ) {
const today = Date.create('today').format('{yyyy}-{MM}-{dd}'); const today = Date.create('today').format('{yyyy}-{MM}-{dd}');
const url = 'https://api.fitbit.com/1/user/-/activities/date/' + today + '.json'; const url = `https://api.fitbit.com/1/user/-/activities/date/${ today }.json`;
fitbit.request({ fitbit.request({
uri: url, 'uri': url,
method: 'GET', 'method': 'GET'
}, function( err, body, token ) { }, function( err, body, token ) {
if ( err ) return next( err ); if ( err ) return next( err );
var profile = JSON.parse( body ); var profile = JSON.parse( body );
@ -190,10 +180,10 @@ app.get( '/fb-today', function( req, res, next ) {
if ( token ) if ( token )
persist.write( tfile, token, function( err ) { persist.write( tfile, token, function( err ) {
if ( err ) return next( err ); if ( err ) return next( err );
res.send( '<pre>' + JSON.stringify( profile, null, 2 ) + '</pre>' ); res.send( `<pre>${ JSON.stringify( profile, null, 2 ) }</pre>` );
}); });
else else
res.send( '<pre>' + JSON.stringify( profile, null, 2 ) + '</pre>' ); res.send( `<pre>${ JSON.stringify( profile, null, 2 ) }</pre>` );
}); });
}); });
@ -206,7 +196,6 @@ app.get('/fitbit_auth_callback', function(req, res, next) {
fitbit.fetchToken(code, function(err, token) { fitbit.fetchToken(code, function(err, token) {
if (err) if (err)
return next(err); return next(err);
// persist the token // persist the token
jsonfile.writeFile(tfile, token, function(err) { jsonfile.writeFile(tfile, token, function(err) {
@ -215,21 +204,17 @@ app.get('/fitbit_auth_callback', function(req, res, next) {
console.log('!!!! Fitbit token saved'); console.log('!!!! Fitbit token saved');
res.redirect('/fb-profile'); res.redirect('/fb-profile');
}); });
}); });
}); });
jsonfile.readFile('./fb-token.json', function(err, obj) { jsonfile.readFile('./fb-token.json', function(err, obj) {
if (err) if (err)
logger.error(err); logger.error(err);
else else
fitbit.setToken(obj); fitbit.setToken(obj);
}); });
// }); // });
/** /**
@ -242,10 +227,8 @@ http.createServer(app).listen(app.get('port'), function () {
}); });
*/ */
server.on('request', app); server.on('request', app);
server.listen(port, () => { server.listen(port, () => {
logger.info('New server listening on ' + server.address().port); logger.info(`New server listening on ${ server.address().port}`);
}); });