diff --git a/.eslintrc.json b/.eslintrc.json index 67aab34..edf8f40 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -12,34 +12,44 @@ "es6": true }, "rules": { - "no-new-object": 1, - "no-reserved-keys": 1, - "no-array-constructor": 1, - "quotes": [1, "single"], - "max-len": [1, 120, 2], // 2 spaces per tab, max 80 chars per line - "no-inner-declarations": [1, "both"], - "no-shadow-restricted-names": 1, - "one-var": 0, - "vars-on-top": 1, - "eqeqeq": 1, + "arrow-spacing": "error", + "block-scoped-var": "error", + "block-spacing": "error", + "brace-style": ["error", "stroustrup", {}], + "camelcase": "error", + "comma-dangle": ["error", "never"], + "comma-spacing": ["error", { "before": false, "after": true }], + "comma-style": [1, "last"], + "consistent-this": [1, "_this"], "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-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-infix-ops": 1, - "eol-last": 1, - "comma-style": [1, "last"], - "no-comma-dangle": 1, - "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 }] + "vars-on-top": 1, + "no-multiple-empty-lines": ["error", { "max": 1, "maxEOF": 1 }], + "spaced-comment": ["error", "always", { "markers": ["/"] }] } -} \ No newline at end of file +} diff --git a/app/js/modules/bitcoin.js b/app/js/modules/bitcoin.js index fb8bdf6..0e00ae9 100644 --- a/app/js/modules/bitcoin.js +++ b/app/js/modules/bitcoin.js @@ -2,56 +2,55 @@ * Created by mdonnel on 22/03/2017. */ -let BitcoinModel = Backbone.Model.extend({ - initialize: function () { +const BitcoinModel = Backbone.Model.extend({ + 'initialize': function () { this.set('url', '/btc'); this.set('balanceUrl', '/balance'); - let data = { - lastGBP: 0.0, - lastUSD: 0.0, - lows: {gbp: 0, usd: 0}, - highs: {gbp: 0, usd: 0}, - eclass: '', - balance: 0.0, - trend: 0 + const data = { + 'lastGBP': 0.0, + 'lastUSD': 0.0, + 'lows': { 'gbp': 0, 'usd': 0 }, + 'highs': { 'gbp': 0, 'usd': 0 }, + 'eclass': '', + 'balance': 0.0, + 'trend': 0 }; this.set('btcdata', data); this.set('balance', 0); this.update(); this.updateHourly(); }, - update: function () { + 'update': function () { this.getBTC(); - //this.getBalance(); + // this.getBalance(); const now = new Date(); const mod = 300000 - (now.getTime() % 300000); - let btcupdateFn = function() { + const btcupdateFn = function() { this.update(); }; setTimeout(btcupdateFn.bind(this), mod + 10); }, - updateHourly: function () { - + 'updateHourly': function () { this.getBalance(); const now = new Date(); const mod = 3600000 - (now.getTime() % 3600000); - let btcupdateFn = function() { + const btcupdateFn = function() { this.update(); }; setTimeout(btcupdateFn.bind(this), mod + 10); }, - recalc: function () { + 'recalc': function () { let data = this.get('btcdata'); let lastGBP = data.lastGBP; let lastUSD; - let g = data.gbp; - let u = data.usd; - let lows = data.lows; - let highs = data.highs; + const g = data.gbp; + const u = data.usd; + const lows = data.lows; + const highs = data.highs; let eclass = data.eclass; - let balance = data.balance; + const balance = data.balance; let trend = data.trend; if ((trend === undefined) || ( trend === null)) trend = 1; @@ -60,7 +59,8 @@ let BitcoinModel = Backbone.Model.extend({ if (data.lastGBP !== 0) if (g > lastGBP) { eclass = 'up'; - } else { + } + else { eclass = 'down'; } else { @@ -94,61 +94,61 @@ let BitcoinModel = Backbone.Model.extend({ this.set('btcdata', data); // total = myBTC * g; }, - getBTC: function () { - let self = this; - let url = this.get('url'); + 'getBTC': function () { + const self = this; + const url = this.get('url'); $.ajax({ - type: 'GET', - url: url, - data: '', - dataType: 'json', - timeout: 10000, - //contentType: ('application/json'), - headers: { + 'type': 'GET', + 'url': url, + 'data': '', + 'dataType': 'json', + 'timeout': 10000, + // contentType: ('application/json'), + 'headers': { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type' }, - success: function (data) { + 'success': function (data) { let gbp = data.bpi.GBP.rate_float, usd = data.bpi.USD.rate_float; - let trend = data.trend; - let btcdata = self.get('btcdata'); + const trend = data.trend; + const btcdata = self.get('btcdata'); btcdata.gbp = gbp; btcdata.usd = usd; btcdata.trend = trend; self.set('btcdata', btcdata); self.recalc(); }, - error: function (xhr, type) { + 'error': function (xhr, type) { console.log('ajax error'); console.log(xhr); console.log(type); } }); }, - getBalance: function() { - let self = this; - let url = this.get('balanceUrl'); + 'getBalance': function() { + const self = this; + const url = this.get('balanceUrl'); $.ajax({ - type: 'GET', - url: url, - data: '', - dataType: 'json', - timeout: 10000, - //contentType: ('application/json'), - headers: { + 'type': 'GET', + 'url': url, + 'data': '', + 'dataType': 'json', + 'timeout': 10000, + // contentType: ('application/json'), + 'headers': { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type' }, - success: function (data) { - let balance = data.balance; + 'success': function (data) { + const balance = data.balance; self.set('balance', balance); self.recalc(); }, - error: function (xhr, type) { + 'error': function (xhr, type) { console.log('ajax error'); console.log(xhr); console.log(type); @@ -156,22 +156,22 @@ let BitcoinModel = Backbone.Model.extend({ }); } }); -let Bitcoin = Backbone.View.extend({ - tagName: 'div', - initialize: function () { +const Bitcoin = Backbone.View.extend({ + 'tagName': 'div', + 'initialize': function () { _.bindAll(this, 'render'); this.model.bind('change', this.render); this.$btc = $('#btc'); this.$trend = $('#trend'); }, - render: function () { - let btcdata = this.model.get('btcdata'); - let balance = this.model.get('balance'); - //console.log(`Balance: ${btcdata.balance.toFixed(4)}`); - //console.log(btcdata.lastGBP); - let owned = parseFloat(btcdata.lastGBP) * parseFloat(balance); - //console.log(`owned: ${owned}`); - let title = 'High: $' + parseFloat(btcdata.highs.usd.toFixed(2)) + ' / Low $' + parseFloat(btcdata.lows.usd.toFixed(2)); + 'render': function () { + const btcdata = this.model.get('btcdata'); + const balance = this.model.get('balance'); + // console.log(`Balance: ${btcdata.balance.toFixed(4)}`); + // console.log(btcdata.lastGBP); + const owned = parseFloat(btcdata.lastGBP) * parseFloat(balance); + // console.log(`owned: ${owned}`); + const title = `High: $${ parseFloat(btcdata.highs.usd.toFixed(2)) } / Low $${ parseFloat(btcdata.lows.usd.toFixed(2))}`; let trendClass = ''; if (btcdata.trend > 1.00) diff --git a/app/js/modules/clock.js b/app/js/modules/clock.js index ae76a01..d6e1f9a 100644 --- a/app/js/modules/clock.js +++ b/app/js/modules/clock.js @@ -5,17 +5,17 @@ * Time: 14:20 * */ -var ClockModel = Backbone.Model.extend({ - initialize: function() { - this.set('now',new Date); +const ClockModel = Backbone.Model.extend({ + 'initialize': function () { + this.set('now', new Date); this.update(); }, - update: function() { - var now = new Date; - var mod = 60000 - (now.getTime() % 60000); - this.set('now',now); + 'update': function () { + const now = new Date; + const mod = 60000 - (now.getTime() % 60000); + this.set('now', now); - var clockFn = function() { + const clockFn = function () { this.update(); }; @@ -23,21 +23,21 @@ var ClockModel = Backbone.Model.extend({ } }); -var Clock = Backbone.View.extend({ - tagName: 'div', - initialize: function() { +const Clock = Backbone.View.extend({ + 'tagName': 'div', + 'initialize': function () { _.bindAll(this, 'render'); this.model.bind('change', this.render); this.$date = $('#date'); this.$time = $('#time'); this.render(); }, - render: function() { - var now = this.model.get('now'); - //var curTime = now.format('{24hr}{mm}'); - var curTime = now.format('{24hr} {mm}'); + 'render': function () { + const now = this.model.get('now'); + // var curTime = now.format('{24hr}{mm}'); + const curTime = now.format('{24hr} {mm}'); - var curDate = now.format('{yyyy}-{MM}-{dd}'); + const curDate = now.format('{yyyy}-{MM}-{dd}'); if (this.prevTime !== curTime) { this.$time.html(curTime); this.prevTime = curTime; diff --git a/app/js/modules/events.js b/app/js/modules/events.js index 9e51953..2901639 100644 --- a/app/js/modules/events.js +++ b/app/js/modules/events.js @@ -1,55 +1,56 @@ /** * Created by mdonnel on 10/04/2017. */ -let EventModel = Backbone.Model.extend({ - initialize: function () { +const EventModel = Backbone.Model.extend({ + 'initialize': function () { this.update(); }, - getDays : function(startdate, enddate) { - let r, s, e; - s = startdate.getTime(); - e = enddate.getTime(); - r = (e - s) / (24 * 60 * 60 * 1000); - return r; - }, - update: function () { - const now = new Date - const mod = 3600000 - (now.getTime() % 3600000) - let data = {}; + 'getDays' : function(startdate, enddate) { + let r, s, e; + s = startdate.getTime(); + e = enddate.getTime(); + r = (e - s) / (24 * 60 * 60 * 1000); + + return r; + }, + 'update': function () { + const now = new Date; + const mod = 3600000 - (now.getTime() % 3600000); + const data = {}; data.days = Math.ceil(this.getDays(now, this.get('event'))); data.weeks = Math.ceil(this.getDays(now, this.get('event')) / 7); this.set('data', data); const clockFn = function () { - this.update() - } + this.update(); + }; - setTimeout(clockFn.bind(this), mod + 10) + setTimeout(clockFn.bind(this), mod + 10); } }); -let EventView = Backbone.View.extend({ - tagName: 'div', - initialize: function () { - _.bindAll(this, 'render'); - this.model.bind('change', this.render); - this.id = 'e_' + Math.random().toString(36).substr(2, 9); - this.$events = $('#events'); - this.$myEvent = null; - this.$el = this.$events; - this.initView(); - this.render(); - }, - render: function () { - let label = this.model.get('label'); - let data = this.model.get('data'); - let str = `${label} ${data.days} days / ${data.weeks} weeks`; - this.$myEvent.empty().append(str); - }, - initView: function () { - let html = `
`; - this.$html = $(html); - this.$events.append(this.$html); - this.$myEvent = $(`#${this.id}`); - } +const EventView = Backbone.View.extend({ + 'tagName': 'div', + 'initialize': function () { + _.bindAll(this, 'render'); + this.model.bind('change', this.render); + this.id = `e_${ Math.random().toString(36).substr(2, 9)}`; + this.$events = $('#events'); + this.$myEvent = null; + this.$el = this.$events; + this.initView(); + this.render(); + }, + 'render': function () { + const label = this.model.get('label'); + const data = this.model.get('data'); + const str = `${label} ${data.days} days / ${data.weeks} weeks`; + this.$myEvent.empty().append(str); + }, + 'initView': function () { + const html = `
`; + this.$html = $(html); + this.$events.append(this.$html); + this.$myEvent = $(`#${this.id}`); + } }); diff --git a/app/js/modules/fx.js b/app/js/modules/fx.js index 7dbe4b1..d77a9d7 100644 --- a/app/js/modules/fx.js +++ b/app/js/modules/fx.js @@ -2,71 +2,74 @@ * Created by mdonnel on 22/03/2017. */ -let FxModel = Backbone.Model.extend({ - initialize: function () { - this.set('url', '/fx'); - this.set('fxdata', {}); - this.update(); - }, - update: function () { - this.getFX(); - const now = new Date; - const mod = 900000 - (now.getTime() % 900000); +const FxModel = Backbone.Model.extend({ + 'initialize': function () { + this.set('url', '/fx'); + this.set('fxdata', {}); + this.update(); + }, + 'update': function () { + this.getFX(); + const now = new Date; + const mod = 900000 - (now.getTime() % 900000); - let fxUpdateFn = function() { - this.update(); - }; - setTimeout(fxUpdateFn.bind(this), mod + 10); - }, - getFX: function() { - let url = this.get('url'); - let self = this; - $.ajax({ - type: 'GET', - url: url, - data: '', - dataType: 'json', + const fxUpdateFn = function() { + this.update(); + }; + setTimeout(fxUpdateFn.bind(this), mod + 10); + }, + 'getFX': function() { + const url = this.get('url'); + const self = this; + $.ajax({ + 'type': 'GET', + 'url': url, + 'data': '', + 'dataType': 'json', - timeout: 10000, + 'timeout': 10000, - //contentType: ('application/json'), - headers: { - 'Access-Control-Allow-Origin': '*', - 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', - 'Access-Control-Allow-Headers': 'Content-Type' + // contentType: ('application/json'), + 'headers': { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type' - }, - success: function(data) { - let gpbex = (1 / data.rates.GBP); - let sekex = (gpbex * data.rates.SEK); - let fxdata = { - usd: 1, - gbp: data.rates.GBP, - sek: data.rates.SEK, - gpbe: gpbex, - sekex: sekex - }; - self.set('fxdata', fxdata); - }, - error: function(xhr, type) { - console.log('ajax error'); - console.log(xhr); - console.log(type); - } - }); + }, + 'success': function(data) { + let fxdata = {}; + if (data.rates !== undefined) { + const gpbex = (1 / data.rates.GBP); + const sekex = (gpbex * data.rates.SEK); + fxdata = { + 'usd': 1, + 'gbp': data.rates.GBP, + 'sek': data.rates.SEK, + 'gpbe': gpbex, + 'sekex': sekex + }; } -}); + self.set('fxdata', fxdata); + }, + 'error': function(xhr, type) { + console.log('ajax error'); + console.log(xhr); + console.log(type); + } + }); + } +}); const FxView = Backbone.View.extend({ - tagName: 'div', - initialize: function () { - _.bindAll(this, 'render'); - this.model.bind('change', this.render); - this.$fx = $('#fx'); - }, - render: function () { - let fxdata = this.model.get('fxdata'); - this.$fx.html(`£1 = $${parseFloat(fxdata.gpbe.toFixed(2))} = ${ parseFloat(fxdata.sekex.toFixed(2))} SEK`); - } + 'tagName': 'div', + 'initialize': function () { + _.bindAll(this, 'render'); + this.model.bind('change', this.render); + this.$fx = $('#fx'); + }, + 'render': function () { + const fxdata = this.model.get('fxdata'); + this.$fx.html(`£1 = $${parseFloat(fxdata.gpbe.toFixed(2))} = ${ parseFloat(fxdata.sekex.toFixed(2))} SEK`); + } }); diff --git a/app/js/modules/password.js b/app/js/modules/password.js index c44a9a8..606f96c 100644 --- a/app/js/modules/password.js +++ b/app/js/modules/password.js @@ -1,83 +1,103 @@ /** * Created by mdonnel on 20/04/2017. */ -_.templateSettings = { - evaluate: /\{\{(.+?)\}\}/g, - interpolate: /\{\{=(.+?)\}\}/g, - escape: /\{\{-(.+?)\}\}/g -}; +/*_.templateSettings = { + 'evaluate': /\{\{(.+?)\}\}/g, + 'interpolate': /\{\{=(.+?)\}\}/g, + 'escape': /\{\{-(.+?)\}\}/g +};*/ 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({ - el: '#passwords', - passwordTemplate: _.template($('#password-template').html()), - 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.whitespace = ['.', '~', '#', '!', '$', '+', '-', '+']; - this.numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; - this.left = ['Alabama', - 'Alaska', - 'Arizona', - 'Maryland', - 'Nevada', - 'Mexico', - 'Texas', - 'Utah', - 'Glasgow', - 'Inverness', - 'Edinburgh', - 'Dumbarton', - 'Balloch', - 'Renton', - 'Cardross', - 'Dundee', - 'Paisley', - 'Hamilton', - 'Greenock', - 'Falkirk', - 'Irvine', - 'Renfrew', - 'Erskine', - 'London', - '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' + 'el': '#passwords', + 'passwordTemplate': _.template('
Long: <%=long%>
Short: <%=short%>
'), + '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.whitespace = ['.', '~', '#', '!', '$', '+', '-', '+']; + this.numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; + this.left = ['Alabama', + 'Alaska', + 'Arizona', + 'Maryland', + 'Nevada', + 'Mexico', + 'Texas', + 'Utah', + 'Glasgow', + 'Inverness', + 'Edinburgh', + 'Dumbarton', + 'Balloch', + 'Renton', + 'Cardross', + 'Dundee', + 'Paisley', + 'Hamilton', + 'Greenock', + 'Falkirk', + 'Irvine', + 'Renfrew', + 'Erskine', + 'London', + '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(); +} + diff --git a/app/js/modules/train.js b/app/js/modules/train.js index 2112bf9..37dc340 100644 --- a/app/js/modules/train.js +++ b/app/js/modules/train.js @@ -6,136 +6,125 @@ * */ -let TrainModel = Backbone.Model.extend({ - initialize: function () { +const TrainModel = Backbone.Model.extend({ + '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'); - 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 mod = limit - (now.getTime() % limit); - const now = new Date; - const hours = now.getHours(); - const limit = (hours < 6) ? 3600000 : 60000; + if (hours >= 6) + this.getTrain(); + else + this.set('trainData', { 'eta':'OFF', 'sta': 'OFF' }); - const mod = limit - (now.getTime() % limit); + const trainUpdateFn = function () { + this.update(); + }; - if (hours >= 6) { - this.getTrain(); - } else { - this.set('trainData', {eta:'OFF', sta: 'OFF'}); - } + setTimeout(trainUpdateFn.bind(this), mod + 10); + }, + 'getTrain': function () { + 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(); - }; - - 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: { + '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) { - /* - 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); - } 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) { + }, + 'success': function (data) { // getTrainsCB(data); - //console.log('Got', data); + // console.log('Got', data); - self.set('route', data); - self.set('visible', true); - }, - error: function (xhr, type) { - console.error('ajax error'); - console.error(xhr); - console.error(type); - } + self.set('route', data); + self.set('visible', true); + }, + 'error': function (xhr, type) { + console.error('ajax error'); + console.error(xhr); + console.error(type); + } }); - } - - } + } }); -let TrainView = Backbone.View.extend({ - tagName: 'div', - initialize: function () { - _.bindAll(this, 'render'); - this.model.bind('change', this.render); - this.$trains = $('#trains'); - this.$traininfo = $('#traininfo'); - this.$traintext = $('#trainResults'); - this.$el = this.$trains; - this.initView(); - }, - events: { - 'click': 'showTrains' - }, - render: function () { +const TrainView = Backbone.View.extend({ + 'tagName': 'div', + 'initialize': function () { + _.bindAll(this, 'render'); + this.model.bind('change', this.render); + this.$trains = $('#trains'); + this.$traininfo = $('#traininfo'); + this.$traintext = $('#trainResults'); + this.$el = this.$trains; + this.initView(); + }, + 'events': { + 'click': 'showTrains' + }, + 'render': function () { + const obj = this.model.get('trainData'); + const visible = this.model.get('visible'); + const route = this.model.get('route'); - let output, status; - let obj = this.model.get('trainData'); - let visible = this.model.get('visible'); - let route = this.model.get('route'); + const output = (obj.eta.toLowerCase() === 'on time') ? obj.sta : obj.eta; + const status = (obj.eta.toLowerCase() === 'on time') ? 'ontime' : 'delayed'; - output = (obj.eta.toLowerCase() === 'on time') ? obj.sta : obj.eta; - status = (obj.eta.toLowerCase() === 'on time') ? 'ontime' : 'delayed'; + this.$button.html(output); + this.$button.removeClass('delayed').removeClass('ontime').addClass(status); - this.$button.html(output); - this.$button.removeClass('delayed').removeClass('ontime').addClass(status); - - if (visible) { - let ws = `
${route.locationName} TO ${route.filterLocationName}
+ if (visible) { + let ws = `
${route.locationName} TO ${route.filterLocationName}
@@ -143,89 +132,75 @@ let TrainView = Backbone.View.extend({ `; - let services = []; - if (typeof route.trainServices === 'object' && route.trainServices !== null) { - for (let item of route.trainServices) { - let dest = item.destination[0]; - let via = dest.via !== null ? `${dest.via}` : ''; - let platform = item.platform !== null ? item.platform : 'đź’ '; - let time = item.sta !== null ? item.sta : `D ${item.std}`; - let status = item.eta !== null ? item.eta : item.etd; + const services = []; + if (typeof route.trainServices === 'object' && route.trainServices !== null) + for (const item of route.trainServices) { + const dest = item.destination[0]; + const via = dest.via !== null ? `${dest.via}` : ''; + const platform = item.platform !== null ? item.platform : 'đź’ '; + const time = item.sta !== null ? item.sta : `D ${item.std}`; + 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'}); - if (!item.isCancelled) { - ws = ws + ` - - - - - `; - } else { - ws = ws + ` - - - - - `; - } - } - } + services.push({ 'location':dest.locationName, 'time':time, 'status':status, 'platform':platform, 'cancel':item.cancelReason, 'type':'train' }); + if (!item.isCancelled) + ws = `${ws } + + + + `; + else + ws = `${ws } + `; + } - if (typeof route.busServices === 'object' && route.busServices !== null) { - for (let item of route.busServices) { - let dest = item.destination[0]; - let via = dest.via !== null ? `${dest.via}` : ''; - let platform = item.platform !== null ? item.platform : ''; - let time = item.sta !== null ? item.sta : `D ${item.std}`; - let status = item.eta !== null ? item.eta : item.etd; - services.push({location:dest.locationName, time:time,status:status,platform:platform, cancel:item.cancelReason, type:'bus'}); + if (typeof route.busServices === 'object' && route.busServices !== null) + for (const item of route.busServices) { + const dest = item.destination[0]; + const via = dest.via !== null ? `${dest.via}` : ''; + const platform = item.platform !== null ? item.platform : ''; + const time = item.sta !== null ? item.sta : `D ${item.std}`; + 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' }); // ws = ws + `
${dest.locationName} Bus ${via}
`; // ws = ws + '
' + item.sta + '
'; - ws = ws + ` - - - - - `; - } - } - - ws = ws + '
Destination TimePlatform
${dest.locationName} ${via}${time}${status}${platform}
${dest.locationName} ${via}${time}❌ ${item.cancelReason}
${dest.locationName} ${via}${time}${status}${platform}
${dest.locationName} ${via}${time}❌ ${item.cancelReason}
🚌 ${dest.locationName} ${via}${time}${status}${platform}
'; - this.$traintext.empty().html(ws); - this.$traintext.removeClass('mui--hide').addClass('mui--show'); - - } else { - this.$traintext.removeClass('mui--show').addClass('mui--hide'); + ws = `${ws }🚌 ${dest.locationName} ${via}${time}${status}${platform}`; } - }, - initView: function () { - //el: $('#myView').get(0) - let self = this; - let target = this.model.get('target'); - let html = `
${target.toUpperCase()}:
`; - this.$html = $(html); - this.$html.on('click', function () { + + ws = `${ws }`; + this.$traintext.empty().html(ws); + this.$traintext.removeClass('mui--hide').addClass('mui--show'); + } + else + this.$traintext.removeClass('mui--show').addClass('mui--hide'); + }, + 'initView': function () { + // el: $('#myView').get(0) + const self = this; + const target = this.model.get('target'); + const html = `
${target.toUpperCase()}:
`; + this.$html = $(html); + this.$html.on('click', function () { // console.log(self) - self.model.getRoute(); - }); - this.$trains.append(this.$html); + self.model.getRoute(); + }); + this.$trains.append(this.$html); // this.el = `#${target}`; - this.$button = $(`#${target}`); + this.$button = $(`#${target}`); - let output = 'OFF'; - let status = (output === 'on time') ? 'ontime' : 'delayed'; + const output = 'OFF'; + const status = (output === 'on time') ? 'ontime' : 'delayed'; - this.$button.html(output); - this.$button.removeClass('delayed').removeClass('ontime').addClass(status); + this.$button.html(output); + this.$button.removeClass('delayed').removeClass('ontime').addClass(status); - let cevent = `click #$(target)`; - this.events[cevent] = "showTrains"; - }, - showTrains: function () { - console.log('Show train'); - } + const cevent = 'click #$(target)'; + this.events[cevent] = 'showTrains'; + }, + 'showTrains': function () { + console.log('Show train'); + } }); diff --git a/app/js/modules/weather.js b/app/js/modules/weather.js index eaf7dcd..071c71d 100644 --- a/app/js/modules/weather.js +++ b/app/js/modules/weather.js @@ -6,92 +6,91 @@ * */ -let WeatherModel = Backbone.Model.extend({ - initialize: function() { - let 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'); +const WeatherModel = Backbone.Model.extend({ + 'initialize': function() { + 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.update(); }, - update: function() { + 'update': function() { this.getWeather(); - let now = new Date; - let mod = 1800000 - (now.getTime() % 1800000); - let weatherTrigger = function() { + const now = new Date; + const mod = 1800000 - (now.getTime() % 1800000); + const weatherTrigger = () => { this.update(); }; setTimeout(weatherTrigger.bind(this), mod + 10); }, - getWeather: function() { - let self = this; + 'getWeather': function() { + const self = this; $.ajax({ - type: 'GET', - url: self.get('url'), - data: '', - dataType: 'jsonp', - timeout: 10000, - context: $('body'), - contentType: ('application/json'), - headers: { - 'Access-Control-Allow-Origin': '*', - 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', - 'Access-Control-Allow-Headers': 'Content-Type' - }, - success: function(data) { - var stored = { - temperature: data.currently.temperature, - icon: data.currently.icon, - summary: data.currently.summary, - daily: data.daily.summary - }; - self.set(stored); - }, - error: function(xhr, type) { - console.error('ajax error'); - console.error(xhr); - console.error(type); - } - }); + 'type': 'GET', + 'url': self.get('url'), + 'data': '', + 'dataType': 'jsonp', + 'timeout': 10000, + 'context': $('body'), + 'contentType': ('application/json'), + 'headers': { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type' + }, + 'success': function(data) { + const stored = { + 'temperature': data.currently.temperature, + 'icon': data.currently.icon, + 'summary': data.currently.summary, + 'daily': data.daily.summary + }; + self.set(stored); + }, + 'error': function(xhr, type) { + console.error('ajax error'); + console.error(xhr); + console.error(type); + } + }); } }); -let Weather = Backbone.View.extend({ - tagName: 'div', - initialize: function() { +const Weather = Backbone.View.extend({ + 'tagName': 'div', + 'initialize': function() { _.bindAll(this, 'render'); this.model.bind('change', this.render); this.$weatherText = $('#weatherDescription'); this.$weatherTemp = $('#temp'); this.$weatherIcon = $('#weatherIcon'); }, - render: function() { + 'render': function() { console.log('Weather:Render'); - var ws = ''; + const ws = ``; - this.$weatherTemp.empty().html(parseInt(this.model.get('temperature')) + '°c '); - this.$weatherText.empty().html(this.model.get('summary')); + this.$weatherTemp.empty().html(`${parseInt(this.model.get('temperature')) }°c `); + this.$weatherText.empty().html(this.model.get('summary')); - this.$weatherIcon.empty().html(ws); + this.$weatherIcon.empty().html(ws); } }); -let WeatherSlim = Backbone.View.extend({ - tagName: 'div', - initialize: function() { +const WeatherSlim = Backbone.View.extend({ + 'tagName': 'div', + 'initialize': function() { _.bindAll(this, 'render'); this.model.bind('change', this.render); this.$weather = $('#weather'); 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'); - let temp = this.model.get('temperature'); - let daily = this.model.get('daily'); - - let ws = `${summary} ${temp}° ${daily}`; + const ws = `${summary} ${temp}° ${daily}`; this.$weather.empty().html(ws); } diff --git a/app/live/js/app.js b/app/live/js/app.js index 03f8ca8..a86cdcb 100644 --- a/app/live/js/app.js +++ b/app/live/js/app.js @@ -1 +1,734 @@ -"use strict";var BitcoinModel,Bitcoin,FxModel,FxView,_typeof,TrainModel,TrainView,WeatherModel,Weather,WeatherSlim,PasswordView,popitout,popitoutSmall,EventModel=Backbone.Model.extend({initialize:function(){this.update()},getDays:function(t,e){var i=void 0,a=void 0;return i=t.getTime(),a=e.getTime(),(a-i)/864e5},update:function(){var t,e=new Date,i=36e5-e.getTime()%36e5,a={};a.days=Math.ceil(this.getDays(e,this.get("event"))),a.weeks=Math.ceil(this.getDays(e,this.get("event"))/7),this.set("data",a),t=function(){this.update()},setTimeout(t.bind(this),i+10)}}),EventView=Backbone.View.extend({tagName:"div",initialize:function(){_.bindAll(this,"render"),this.model.bind("change",this.render),this.id="e_"+Math.random().toString(36).substr(2,9),this.$events=$("#events"),this.$myEvent=null,this.$el=this.$events,this.initView(),this.render()},render:function(){var t=this.model.get("label"),e=this.model.get("data"),i=t+" "+e.days+" days / "+e.weeks+" weeks";this.$myEvent.empty().append(i)},initView:function(){var t="
';this.$html=$(t),this.$events.append(this.$html),this.$myEvent=$("#"+this.id)}});BitcoinModel=Backbone.Model.extend({initialize:function(){this.set("url","/btc"),this.set("balanceUrl","/balance");var t={lastGBP:0,lastUSD:0,lows:{gbp:0,usd:0},highs:{gbp:0,usd:0},eclass:"",balance:0,trend:0};this.set("btcdata",t),this.set("balance",0),this.update(),this.updateHourly()},update:function(){var t,e,i;this.getBTC(),t=new Date,e=3e5-t.getTime()%3e5,i=function(){this.update()},setTimeout(i.bind(this),e+10)},updateHourly:function(){var t,e,i;this.getBalance(),t=new Date,e=36e5-t.getTime()%36e5,i=function(){this.update()},setTimeout(i.bind(this),e+10)},recalc:function(){var t=this.get("btcdata"),e=t.lastGBP,i=void 0,a=t.gbp,n=t.usd,s=t.lows,o=t.highs,r=t.eclass,l=t.balance,d=t.trend;void 0!==d&&null!==d||(d=1),void 0!==a&&(0!==t.lastGBP?r=a>e?"up":"down":(s.gbp=a,s.usd=n,o.gbp=a,o.usd=n),e=a,i=n,a1?"trendUp":t.trend<1?"trendDown":"",this.$trend.removeClass(),this.$trend.addClass(n),this.$btc.removeClass(),this.$btc.addClass(t.eclass),this.$btc.html("$"+parseFloat(t.lastUSD.toFixed(2))+" / £"+parseFloat(t.lastGBP.toFixed(2))+"
₿"+e+" £"+parseFloat(i.toFixed(2))+"
"),this.$btc.prop("title",a)}}),FxModel=Backbone.Model.extend({initialize:function(){this.set("url","/fx"),this.set("fxdata",{}),this.update()},update:function(){var t,e,i;this.getFX(),t=new Date,e=9e5-t.getTime()%9e5,i=function(){this.update()},setTimeout(i.bind(this),e+10)},getFX:function(){var t=this.get("url"),e=this;$.ajax({type:"GET",url:t,data:"",dataType:"json",timeout:1e4,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"PUT, GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type"},success:function(t){var i=1/t.rates.GBP,a=i*t.rates.SEK,n={usd:1,gbp:t.rates.GBP,sek:t.rates.SEK,gpbe:i,sekex:a};e.set("fxdata",n)},error:function(t,e){}})}}),FxView=Backbone.View.extend({tagName:"div",initialize:function(){_.bindAll(this,"render"),this.model.bind("change",this.render),this.$fx=$("#fx")},render:function(){var t=this.model.get("fxdata");this.$fx.html("£1 = $"+parseFloat(t.gpbe.toFixed(2))+" = "+parseFloat(t.sekex.toFixed(2))+" SEK")}}),_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},TrainModel=Backbone.Model.extend({initialize:function(){var t=this.get("from"),e=this.get("to"),i="/getnexttraintimes?from="+t+"&to="+e,a="/gettrains?from="+t+"&to="+e,n=t+e;this.set("url",i),this.set("routeUrl",a),this.set("target",n),this.set("visible",!1),this.set("trainData",{eta:"OFF",sta:"OFF"}),this.update()},update:function(){var t,e=new Date,i=e.getHours(),a=i<6?36e5:6e4,n=a-e.getTime()%a;i>=6?this.getTrain():this.set("trainData",{eta:"OFF",sta:"OFF"}),t=function(){this.update()},setTimeout(t.bind(this),n+10)},getTrain:function(){var t=this.get("url"),e=this;$.ajax({type:"GET",url:t,data:"",dataType:"json",timeout:1e4,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"PUT, GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type"},success:function(t){e.set("trainData",t)},error:function(t,e){}})},getRoute:function(){var t=this.get("routeUrl"),e=this;!0===this.get("visible")?this.set("visible",!1):$.ajax({type:"GET",url:t,data:"",dataType:"json",timeout:1e4,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"PUT, GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type"},success:function(t){e.set("route",t),e.set("visible",!0)},error:function(t,e){}})}}),TrainView=Backbone.View.extend({tagName:"div",initialize:function(){_.bindAll(this,"render"),this.model.bind("change",this.render),this.$trains=$("#trains"),this.$traininfo=$("#traininfo"),this.$traintext=$("#trainResults"),this.$el=this.$trains,this.initView()},events:{click:"showTrains"},render:function(){var t,e,i,a,n,s,o,r,l,d,h,u,c,m,p,g,b,f,w,v,y,T,$,C,A=void 0,x=void 0,S=this.model.get("trainData"),E=this.model.get("visible"),k=this.model.get("route");if(A="on time"===S.eta.toLowerCase()?S.sta:S.eta,x="on time"===S.eta.toLowerCase()?"ontime":"delayed",this.$button.html(A),this.$button.removeClass("delayed").removeClass("ontime").addClass(x),E){if(t="
"+k.locationName+" TO "+k.filterLocationName+'
\n \n \n \n \n \n ',e=[],"object"===_typeof(k.trainServices)&&null!==k.trainServices){i=!0,a=!1,n=void 0;try{for(s=k.trainServices[Symbol.iterator]();!(i=(o=s.next()).done);i=!0)r=o.value,l=r.destination[0],d=null!==l.via?""+l.via+"":"",h=null!==r.platform?r.platform:"đź’ ",u=null!==r.sta?r.sta:"D "+r.std,c=null!==r.eta?r.eta:r.etd,e.push({location:l.locationName,time:u,status:c,platform:h,cancel:r.cancelReason,type:"train"}),t=r.isCancelled?t+"\n \n \n \n \n ":t+"\n \n \n \n \n "}catch(t){a=!0,n=t}finally{try{!i&&s.return&&s.return()}finally{if(a)throw n}}}if("object"===_typeof(k.busServices)&&null!==k.busServices){m=!0,p=!1,g=void 0;try{for(b=k.busServices[Symbol.iterator]();!(m=(f=b.next()).done);m=!0)w=f.value,v=w.destination[0],y=null!==v.via?""+v.via+"":"",T=null!==w.platform?w.platform:"",$=null!==w.sta?w.sta:"D "+w.std,C=null!==w.eta?w.eta:w.etd,e.push({location:v.locationName,time:$,status:C,platform:T,cancel:w.cancelReason,type:"bus"}),t=t+"\n \n \n \n \n "}catch(t){p=!0,g=t}finally{try{!m&&b.return&&b.return()}finally{if(p)throw g}}}t+="
DestinationTimeStatusPlatform
"+l.locationName+" "+d+""+u+'❌ '+r.cancelReason+"
"+l.locationName+" "+d+""+u+""+c+""+h+"
🚌 "+v.locationName+" "+y+""+$+""+C+""+T+"
",this.$traintext.empty().html(t),this.$traintext.removeClass("mui--hide").addClass("mui--show")}else this.$traintext.removeClass("mui--show").addClass("mui--hide")},initView:function(){var t,e,i,a=this,n=this.model.get("target"),s="
"+n.toUpperCase()+':
';this.$html=$(s),this.$html.on("click",function(){a.model.getRoute()}),this.$trains.append(this.$html),this.$button=$("#"+n),t="OFF",e="on time"===t?"ontime":"delayed",this.$button.html(t),this.$button.removeClass("delayed").removeClass("ontime").addClass(e),i="click #$(target)",this.events[i]="showTrains"},showTrains:function(){}}),WeatherModel=Backbone.Model.extend({initialize:function(){var t=this.get("geo");this.set("url","https://api.darksky.net/forecast/9ad2a41d420f3cf4960571bb886f710c/"+t.coords.latitude.toString()+","+t.coords.longitude.toString()+"?units=uk2&exclude=minutely,hourly,alerts,flags"),this.update()},update:function(){var t,e,i;this.getWeather(),t=new Date,e=18e5-t.getTime()%18e5,i=function(){this.update()},setTimeout(i.bind(this),e+10)},getWeather:function(){var t=this;$.ajax({type:"GET",url:t.get("url"),data:"",dataType:"jsonp",timeout:1e4,context:$("body"),contentType:"application/json",headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"PUT, GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type"},success:function(e){var i={temperature:e.currently.temperature,icon:e.currently.icon,summary:e.currently.summary,daily:e.daily.summary};t.set(i)},error:function(t,e){}})}}),Weather=Backbone.View.extend({tagName:"div",initialize:function(){_.bindAll(this,"render"),this.model.bind("change",this.render),this.$weatherText=$("#weatherDescription"),this.$weatherTemp=$("#temp"),this.$weatherIcon=$("#weatherIcon")},render:function(){var t='';this.$weatherTemp.empty().html(parseInt(this.model.get("temperature"))+"°c "),this.$weatherText.empty().html(this.model.get("summary")),this.$weatherIcon.empty().html(t)}}),WeatherSlim=Backbone.View.extend({tagName:"div",initialize:function(){_.bindAll(this,"render"),this.model.bind("change",this.render),this.$weather=$("#weather"),this.render()},render:function(){var t=this.model.get("summary"),e=this.model.get("temperature"),i=this.model.get("daily"),a=t+" "+e+"° "+i+"";this.$weather.empty().html(a)}}),_.templateSettings={evaluate:/\{\{(.+?)\}\}/g,interpolate:/\{\{=(.+?)\}\}/g,escape:/\{\{-(.+?)\}\}/g},Array.prototype.random=function(){return this[Math.floor(Math.random()*this.length)]},PasswordView=Backbone.View.extend({el:"#passwords",passwordTemplate:_.template($("#password-template").html()),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.whitespace=[".","~","#","!","$","+","-","+"],this.numbers=["0","1","2","3","4","5","6","7","8","9"],this.left=["Alabama","Alaska","Arizona","Maryland","Nevada","Mexico","Texas","Utah","Glasgow","Inverness","Edinburgh","Dumbarton","Balloch","Renton","Cardross","Dundee","Paisley","Hamilton","Greenock","Falkirk","Irvine","Renfrew","Erskine","London","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.passwordOut=this.$("#passwordOut"),_.bindAll(this,"newClick")},events:{"click #newPassword":"newClick"},numberCluster:function(){return this.numbers.random()+this.numbers.random()+this.numbers.random()},randomAmount:function(t){var e,i="";for(e=0;e'; + this.$html = $(html); + this.$events.append(this.$html); + this.$myEvent = $('#' + this.id); + } +}); +'use strict'; + +/** + * Created by mdonnel on 22/03/2017. + */ + +var BitcoinModel = Backbone.Model.extend({ + 'initialize': function initialize() { + this.set('url', '/btc'); + this.set('balanceUrl', '/balance'); + var data = { + 'lastGBP': 0.0, + 'lastUSD': 0.0, + 'lows': { 'gbp': 0, 'usd': 0 }, + 'highs': { 'gbp': 0, 'usd': 0 }, + 'eclass': '', + 'balance': 0.0, + 'trend': 0 + }; + this.set('btcdata', data); + this.set('balance', 0); + this.update(); + this.updateHourly(); + }, + 'update': function update() { + this.getBTC(); + // this.getBalance(); + var now = new Date(); + var mod = 300000 - now.getTime() % 300000; + + var btcupdateFn = function btcupdateFn() { + this.update(); + }; + setTimeout(btcupdateFn.bind(this), mod + 10); + }, + 'updateHourly': function updateHourly() { + this.getBalance(); + var now = new Date(); + var mod = 3600000 - now.getTime() % 3600000; + + var btcupdateFn = function btcupdateFn() { + this.update(); + }; + setTimeout(btcupdateFn.bind(this), mod + 10); + }, + 'recalc': function recalc() { + var data = this.get('btcdata'); + var lastGBP = data.lastGBP; + var lastUSD = void 0; + var g = data.gbp; + var u = data.usd; + var lows = data.lows; + var highs = data.highs; + var eclass = data.eclass; + var balance = data.balance; + var trend = data.trend; + + if (trend === undefined || trend === null) trend = 1; + + if (g !== undefined) { + if (data.lastGBP !== 0) { + if (g > lastGBP) { + eclass = 'up'; + } else { + eclass = 'down'; + } + } else { + lows.gbp = g; + lows.usd = u; + + highs.gbp = g; + highs.usd = u; + } + lastGBP = g; + lastUSD = u; + + if (g < lows.gbp) lows.gbp = g; + if (u < lows.usd) lows.usd = u; + + if (highs.gbp < g) highs.gbp = g; + if (highs.usd < u) highs.usd = u; + + data = { + lastGBP: lastGBP, + lastUSD: lastUSD, + lows: lows, + highs: highs, + eclass: eclass, + balance: balance, + trend: trend + }; + } + data.stub = Math.random(Number.MAX_SAFE_INTEGER).toString(32); + + this.set('btcdata', data); + // total = myBTC * g; + }, + 'getBTC': function getBTC() { + var self = this; + var url = this.get('url'); + $.ajax({ + 'type': 'GET', + 'url': url, + 'data': '', + 'dataType': 'json', + 'timeout': 10000, + // contentType: ('application/json'), + 'headers': { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type' + }, + 'success': function success(data) { + var gbp = data.bpi.GBP.rate_float, + usd = data.bpi.USD.rate_float; + var trend = data.trend; + var btcdata = self.get('btcdata'); + btcdata.gbp = gbp; + btcdata.usd = usd; + btcdata.trend = trend; + self.set('btcdata', btcdata); + self.recalc(); + }, + 'error': function error(xhr, type) { + void 0; + void 0; + void 0; + } + }); + }, + 'getBalance': function getBalance() { + var self = this; + var url = this.get('balanceUrl'); + $.ajax({ + 'type': 'GET', + 'url': url, + 'data': '', + 'dataType': 'json', + 'timeout': 10000, + // contentType: ('application/json'), + 'headers': { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type' + }, + 'success': function success(data) { + var balance = data.balance; + + self.set('balance', balance); + self.recalc(); + }, + 'error': function error(xhr, type) { + void 0; + void 0; + void 0; + } + }); + } +}); +var Bitcoin = Backbone.View.extend({ + 'tagName': 'div', + 'initialize': function initialize() { + _.bindAll(this, 'render'); + this.model.bind('change', this.render); + this.$btc = $('#btc'); + this.$trend = $('#trend'); + }, + 'render': function render() { + var btcdata = this.model.get('btcdata'); + var balance = this.model.get('balance'); + // console.log(`Balance: ${btcdata.balance.toFixed(4)}`); + // console.log(btcdata.lastGBP); + var owned = parseFloat(btcdata.lastGBP) * parseFloat(balance); + // console.log(`owned: ${owned}`); + var title = 'High: $' + parseFloat(btcdata.highs.usd.toFixed(2)) + ' / Low $' + parseFloat(btcdata.lows.usd.toFixed(2)); + var trendClass = ''; + + if (btcdata.trend > 1.00) trendClass = 'trendUp';else if (btcdata.trend < 1.00) trendClass = 'trendDown';else trendClass = ''; + + this.$trend.removeClass(); + this.$trend.addClass(trendClass); + this.$btc.removeClass(); + this.$btc.addClass(btcdata.eclass); + this.$btc.html('$' + parseFloat(btcdata.lastUSD.toFixed(2)) + ' / £' + parseFloat(btcdata.lastGBP.toFixed(2)) + '
₿' + balance + ' £' + parseFloat(owned.toFixed(2)) + '
'); + this.$btc.prop('title', title); + } +}); +'use strict'; + +/** + * Created by mdonnel on 22/03/2017. + */ + +var FxModel = Backbone.Model.extend({ + 'initialize': function initialize() { + this.set('url', '/fx'); + this.set('fxdata', {}); + this.update(); + }, + 'update': function update() { + this.getFX(); + var now = new Date(); + var mod = 900000 - now.getTime() % 900000; + + var fxUpdateFn = function fxUpdateFn() { + this.update(); + }; + setTimeout(fxUpdateFn.bind(this), mod + 10); + }, + 'getFX': function getFX() { + var url = this.get('url'); + var self = this; + $.ajax({ + 'type': 'GET', + 'url': url, + 'data': '', + 'dataType': 'json', + + 'timeout': 10000, + + // contentType: ('application/json'), + 'headers': { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type' + + }, + 'success': function success(data) { + var fxdata = {}; + if (data.rates !== undefined) { + var gpbex = 1 / data.rates.GBP; + var sekex = gpbex * data.rates.SEK; + fxdata = { + 'usd': 1, + 'gbp': data.rates.GBP, + 'sek': data.rates.SEK, + 'gpbe': gpbex, + 'sekex': sekex + }; + } + + self.set('fxdata', fxdata); + }, + 'error': function error(xhr, type) { + void 0; + void 0; + void 0; + } + }); + } +}); + +var FxView = Backbone.View.extend({ + 'tagName': 'div', + 'initialize': function initialize() { + _.bindAll(this, 'render'); + this.model.bind('change', this.render); + this.$fx = $('#fx'); + }, + 'render': function render() { + var fxdata = this.model.get('fxdata'); + this.$fx.html('£1 = $' + parseFloat(fxdata.gpbe.toFixed(2)) + ' = ' + parseFloat(fxdata.sekex.toFixed(2)) + ' SEK'); + } +}); +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +/** + * + * User: Martin Donnelly + * Date: 2016-10-03 + * Time: 14:20 + * + */ + +var TrainModel = Backbone.Model.extend({ + 'initialize': function initialize() { + var fromStation = this.get('from'); + var toStation = this.get('to'); + var url = '/getnexttraintimes?from=' + fromStation + '&to=' + toStation; + var routeUrl = '/gettrains?from=' + fromStation + '&to=' + toStation; + var 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 update() { + var now = new Date(); + var hours = now.getHours(); + var limit = hours < 6 ? 3600000 : 60000; + + var mod = limit - now.getTime() % limit; + + if (hours >= 6) this.getTrain();else this.set('trainData', { 'eta': 'OFF', 'sta': 'OFF' }); + + var trainUpdateFn = function trainUpdateFn() { + this.update(); + }; + + setTimeout(trainUpdateFn.bind(this), mod + 10); + }, + 'getTrain': function getTrain() { + var url = this.get('url'); + var 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 success(data) { + self.set('trainData', data); + }, + 'error': function error(xhr, type) { + void 0; + void 0; + void 0; + } + }); + }, + 'getRoute': function getRoute() { + var url = this.get('routeUrl'); + var self = this; + + if (this.get('visible') === true) this.set('visible', false);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 success(data) { + // getTrainsCB(data); + // console.log('Got', data); + + self.set('route', data); + self.set('visible', true); + }, + 'error': function error(xhr, type) { + void 0; + void 0; + void 0; + } + }); + } +}); + +var TrainView = Backbone.View.extend({ + 'tagName': 'div', + 'initialize': function initialize() { + _.bindAll(this, 'render'); + this.model.bind('change', this.render); + this.$trains = $('#trains'); + this.$traininfo = $('#traininfo'); + this.$traintext = $('#trainResults'); + this.$el = this.$trains; + this.initView(); + }, + 'events': { + 'click': 'showTrains' + }, + 'render': function render() { + var obj = this.model.get('trainData'); + var visible = this.model.get('visible'); + var route = this.model.get('route'); + + var output = obj.eta.toLowerCase() === 'on time' ? obj.sta : obj.eta; + var status = obj.eta.toLowerCase() === 'on time' ? 'ontime' : 'delayed'; + + this.$button.html(output); + this.$button.removeClass('delayed').removeClass('ontime').addClass(status); + + if (visible) { + var ws = '
' + route.locationName + ' TO ' + route.filterLocationName + '
\n \n \n \n \n \n '; + + var services = []; + if (_typeof(route.trainServices) === 'object' && route.trainServices !== null) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = route.trainServices[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _item = _step.value; + + var dest = _item.destination[0]; + var via = dest.via !== null ? '' + dest.via + '' : ''; + var platform = _item.platform !== null ? _item.platform : 'đź’ '; + var time = _item.sta !== null ? _item.sta : 'D ' + _item.std; + var _status = _item.eta !== null ? _item.eta : _item.etd; + + services.push({ 'location': dest.locationName, 'time': time, 'status': _status, 'platform': platform, 'cancel': _item.cancelReason, 'type': 'train' }); + if (!_item.isCancelled) ws = ws + '\n \n \n \n ';else ws = ws + '\n '; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + }if (_typeof(route.busServices) === 'object' && route.busServices !== null) { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = route.busServices[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var _item2 = _step2.value; + + var _dest = _item2.destination[0]; + var _via = _dest.via !== null ? '' + _dest.via + '' : ''; + var _platform = _item2.platform !== null ? _item2.platform : ''; + var _time = _item2.sta !== null ? _item2.sta : 'D ' + _item2.std; + var _status2 = _item2.eta !== null ? _item2.eta : _item2.etd; + services.push({ 'location': _dest.locationName, 'time': _time, 'status': _status2, 'platform': _platform, 'cancel': _item2.cancelReason, 'type': 'bus' }); + // ws = ws + `
${dest.locationName} Bus ${via}
`; + // ws = ws + '
' + item.sta + '
'; + ws = ws + ''; + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + }ws = ws + '
DestinationTimeStatusPlatform
' + dest.locationName + ' ' + via + '' + time + '' + _status + '' + platform + '
' + dest.locationName + ' ' + via + '' + time + '\u274C ' + _item.cancelReason + '
\uD83D\uDE8C ' + _dest.locationName + ' ' + _via + '' + _time + '' + _status2 + '' + _platform + '
'; + this.$traintext.empty().html(ws); + this.$traintext.removeClass('mui--hide').addClass('mui--show'); + } else this.$traintext.removeClass('mui--show').addClass('mui--hide'); + }, + 'initView': function initView() { + // el: $('#myView').get(0) + var self = this; + var target = this.model.get('target'); + var html = '
' + target.toUpperCase() + ':
'; + this.$html = $(html); + this.$html.on('click', function () { + // console.log(self) + self.model.getRoute(); + }); + this.$trains.append(this.$html); + + // this.el = `#${target}`; + + this.$button = $('#' + target); + + var output = 'OFF'; + var status = output === 'on time' ? 'ontime' : 'delayed'; + + this.$button.html(output); + this.$button.removeClass('delayed').removeClass('ontime').addClass(status); + + var cevent = 'click #$(target)'; + this.events[cevent] = 'showTrains'; + }, + 'showTrains': function showTrains() { + void 0; + } + +}); +'use strict'; + +/** + * + * User: Martin Donnelly + * Date: 2016-10-03 + * Time: 14:20 + * + */ + +var WeatherModel = Backbone.Model.extend({ + 'initialize': function initialize() { + var 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.update(); + }, + 'update': function update() { + var _this = this; + + this.getWeather(); + var now = new Date(); + var mod = 1800000 - now.getTime() % 1800000; + var weatherTrigger = function weatherTrigger() { + _this.update(); + }; + + setTimeout(weatherTrigger.bind(this), mod + 10); + }, + 'getWeather': function getWeather() { + var self = this; + $.ajax({ + 'type': 'GET', + 'url': self.get('url'), + 'data': '', + 'dataType': 'jsonp', + 'timeout': 10000, + 'context': $('body'), + 'contentType': 'application/json', + 'headers': { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type' + }, + 'success': function success(data) { + var stored = { + 'temperature': data.currently.temperature, + 'icon': data.currently.icon, + 'summary': data.currently.summary, + 'daily': data.daily.summary + }; + self.set(stored); + }, + 'error': function error(xhr, type) { + void 0; + void 0; + void 0; + } + }); + } +}); + +var Weather = Backbone.View.extend({ + 'tagName': 'div', + 'initialize': function initialize() { + _.bindAll(this, 'render'); + this.model.bind('change', this.render); + this.$weatherText = $('#weatherDescription'); + this.$weatherTemp = $('#temp'); + this.$weatherIcon = $('#weatherIcon'); + }, + 'render': function render() { + void 0; + + var ws = ''; + + this.$weatherTemp.empty().html(parseInt(this.model.get('temperature')) + '°c '); + this.$weatherText.empty().html(this.model.get('summary')); + + this.$weatherIcon.empty().html(ws); + } + +}); + +var WeatherSlim = Backbone.View.extend({ + 'tagName': 'div', + 'initialize': function initialize() { + _.bindAll(this, 'render'); + this.model.bind('change', this.render); + this.$weather = $('#weather'); + this.render(); + }, + 'render': function render() { + var summary = this.model.get('summary'); + var temp = this.model.get('temperature'); + var daily = this.model.get('daily'); + + var ws = summary + ' ' + temp + '° ' + daily + ''; + + this.$weather.empty().html(ws); + } + +}); +'use strict'; + +/** + * Created by mdonnel on 20/04/2017. + */ +/*_.templateSettings = { + 'evaluate': /\{\{(.+?)\}\}/g, + 'interpolate': /\{\{=(.+?)\}\}/g, + 'escape': /\{\{-(.+?)\}\}/g +};*/ + +Array.prototype.random = function () { + return this[Math.floor(Math.random() * this.length)]; +}; + +var PasswordView = Backbone.View.extend({ + 'el': '#passwords', + 'passwordTemplate': _.template('
Long: <%=long%>
Short: <%=short%>
'), + 'initialize': function initialize() { + 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.whitespace = ['.', '~', '#', '!', '$', '+', '-', '+']; + this.numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; + this.left = ['Alabama', 'Alaska', 'Arizona', 'Maryland', 'Nevada', 'Mexico', 'Texas', 'Utah', 'Glasgow', 'Inverness', 'Edinburgh', 'Dumbarton', 'Balloch', 'Renton', 'Cardross', 'Dundee', 'Paisley', 'Hamilton', 'Greenock', 'Falkirk', 'Irvine', 'Renfrew', 'Erskine', 'London', '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.passwordOut = this.$('#passwordOut'); + _.bindAll(this, 'newClick'); + }, + 'events': { + 'click #newPassword': 'newClick' + }, + 'numberCluster': numberCluster, + 'randomAmount': randomAmount, + 'newClick': newClick + +}); + +function randomAmount(i) { + var str = ''; + + for (var t = 0; t < i; t++) { + str = str + this.alpha.random(); + }return str; +} + +function newClick(e) { + var long = (this.left.random() + ' ' + this.right.random() + ' ' + this.numberCluster()).split(' ').join(this.whitespace.random()); + var short = (this.randomAmount(5) + ' ' + this.randomAmount(5)).split(' ').join(this.whitespace.random()); + var 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(); +} +'use strict'; + +(function () { + document.title = 'Slack'; +})(); + +var popitout = function popitout(url) { + var newwindow = window.open(url, 'name', 'height=600,width=570'); + if (window.focus) { + newwindow.focus(); + } + return false; +}; + +var popitoutSmall = function popitoutSmall(url) { + var newwindow = window.open(url, 'name', 'height=400,width=520'); + if (window.focus) { + newwindow.focus(); + } + return false; +}; \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js index 1432ad0..266eb27 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1,83 +1,82 @@ const gulp = require('gulp'); -let autoprefixer = require('gulp-autoprefixer'); -let cssnano = require('gulp-cssnano'); -let jshint = require('gulp-jshint'); -let uglify = require('gulp-uglify'); -let rename = require('gulp-rename'); -let concat = require('gulp-concat'); -let cache = require('gulp-cache'); -let htmlmin = require('gulp-htmlmin'); -let htmlreplace = require('gulp-html-replace'); -let stripDebug = require('gulp-strip-debug'); -let scss = require('gulp-scss'); -let sass = require('gulp-sass'); -let googleWebFonts = require('gulp-google-webfonts'); -let babel = require('gulp-babel'); +const autoprefixer = require('gulp-autoprefixer'); +const cssnano = require('gulp-cssnano'); +const jshint = require('gulp-jshint'); +const uglify = require('gulp-uglify'); +const rename = require('gulp-rename'); +const concat = require('gulp-concat'); +const cache = require('gulp-cache'); +const htmlmin = require('gulp-htmlmin'); +const htmlreplace = require('gulp-html-replace'); +const stripDebug = require('gulp-strip-debug'); +const scss = require('gulp-scss'); +const sass = require('gulp-sass'); +const googleWebFonts = require('gulp-google-webfonts'); +const babel = require('gulp-babel'); -let filePath = { - build_dir: 'live' +const filePath = { + 'build_dir': 'live' }; -let dest = 'app/live'; +const dest = 'app/live'; -let fontOptions = { }; +const fontOptions = { }; 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(jshint('.jshintrc')) .pipe(jshint.reporter('default')) - .pipe(babel({presets: ['es2015']})) + .pipe(babel({ 'presets': ['es2015'] })) .pipe(concat('app.js')) - .pipe(uglify({mangle: true, compress: {sequences: true, // Join consecutive statemets with the “comma operator” - properties: true, // Optimize property access: a["foo"] → a.foo - dead_code: true, // Discard unreachable code - drop_debugger: true, // Discard “debugger” statements - unsafe: false, // Some unsafe optimizations (see below) - conditionals: true, // Optimize if-s and conditional expressions - comparisons: true, // Optimize comparisons - evaluate: true, // Evaluate constant expressions - booleans: true, // Optimize boolean expressions - loops: true, // Optimize loops - unused: true, // Drop unused variables/functions - hoist_funs: true, // Hoist function declarations - hoist_vars: true, // Hoist variable declarations - if_return: true, // Optimize if-s followed by return/continue - join_vars: true, // Join var declarations - cascade: true, // Try to cascade `right` into `left` in sequences - side_effects: true, // Drop side-effect-free statements - warnings: true, // Warn about potentially dangerous optimizations/code - global_defs: {} // global definitions - }})) - .pipe(gulp.dest(dest + '/js')); + /*.pipe(uglify({ 'mangle': true, 'compress': { 'sequences': true, // Join consecutive statemets with the “comma operator” + 'properties': true, // Optimize property access: a["foo"] → a.foo + 'dead_code': true, // Discard unreachable code + 'drop_debugger': true, // Discard “debugger” statements + 'unsafe': false, // Some unsafe optimizations (see below) + 'conditionals': true, // Optimize if-s and conditional expressions + 'comparisons': true, // Optimize comparisons + 'evaluate': true, // Evaluate constant expressions + 'booleans': true, // Optimize boolean expressions + 'loops': true, // Optimize loops + 'unused': true, // Drop unused variables/functions + 'hoist_funs': true, // Hoist function declarations + 'hoist_vars': true, // Hoist variable declarations + 'if_return': true, // Optimize if-s followed by return/continue + 'join_vars': true, // Join var declarations + 'cascade': true, // Try to cascade `right` into `left` in sequences + 'side_effects': true, // Drop side-effect-free statements + 'warnings': true, // Warn about potentially dangerous optimizations/code + 'global_defs': {} // global definitions + } }))*/ + .pipe(gulp.dest(`${dest }/js`)); }); gulp.task('customMUI', function() { return gulp.src(['app/css/custom.scss']) - .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError)) - //.pipe(cssnano()) + .pipe(sass({ 'outputStyle': 'compressed' }).on('error', sass.logError)) + // .pipe(cssnano()) .pipe(rename('mui.custom.css')) - .pipe(gulp.dest(dest + '/css')); + .pipe(gulp.dest(`${dest }/css`)); }); - gulp.task('vendor', function() { - return gulp.src([ - 'bower_components/zepto/zepto.min.js', - 'bower_components/ejs/ejs.min.js', - 'bower_components/underscore/underscore-min.js', - 'bower_components/backbone/backbone-min.js' - ]) + return gulp.src([ + 'bower_components/zepto/zepto.min.js', + 'bower_components/ejs/ejs.min.js', + 'bower_components/underscore/underscore-min.js', + 'bower_components/backbone/backbone-min.js' + ]) .pipe(concat('vendor.js')) - .pipe(uglify({mangle: false})) - .pipe(gulp.dest(dest + '/js')); - }); + .pipe(uglify({ 'mangle': false })) + .pipe(gulp.dest(`${dest }/js`)); +}); gulp.task('fonts', function() { return gulp.src('./fonts.list') .pipe(googleWebFonts(fontOptions)) - .pipe(gulp.dest(dest + '/fonts')) + .pipe(gulp.dest(`${dest }/fonts`)) ; }); -gulp.task('default', ['appJS', 'vendor', 'customMUI', 'fonts']); \ No newline at end of file +gulp.task('default', ['appJS', 'vendor', 'customMUI', 'fonts']); diff --git a/lib/btc.js b/lib/btc.js index 1a1b884..184a204 100644 --- a/lib/btc.js +++ b/lib/btc.js @@ -5,17 +5,18 @@ const trend = require('trend'); const logger = require('log4js').getLogger('btc'); let btcCache = {}; 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 () { logger.info('>> getting bitcoin'); function btcQuery (callback) { const options = { - host: 'api.coindesk.com', + 'host': 'api.coindesk.com', // port: 80, - path: '/v1/bpi/currentprice.json', + 'path': '/v1/bpi/currentprice.json', // method: 'GET', - headers: { + 'headers': { + /* 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data)*/ @@ -28,43 +29,43 @@ function getBitcoin () { data += chunk; }); response.on('end', () => { - let cData = {}; try { cData = JSON.parse(data); - } catch (e) { + } + catch (e) { logger.error(e); - } finally{ + } + finally{ callback(cData); } - }); response.on('error', e => { logger.error(e); }); }).end(); - } catch (e) { + } + catch (e) { logger.error(e); } } btcQuery(a => { // logger.info(a); + logger.info('Got btc data. Storing it'); logger.debug('>> btc', a); btcCache = a; history.push(a.bpi.USD.rate_float); btcCache.history = history.get(); - btcCache.trend = trend(btcCache.history, {avgPoints: 12}); + btcCache.trend = trend(btcCache.history, { 'avgPoints': 12 }); GLOBAL.lastcheck = new Date(); - }); } function getBalance() { logger.info('>> getting Balance'); function balanceQuery (callback, r) { - try { https.get('https://blockexplorer.com/api/addr/18sLVW5Aswp2KWLr4hMFZsuSPtvAauFiif').on('response', response => { let data = ''; @@ -75,18 +76,20 @@ function getBalance() { let cData = {}; try { cData = JSON.parse(data); - } catch (e) { + } + catch (e) { logger.error(e); - } finally{ + } + finally{ callback(cData, r); } - }); response.on('error', e => { logger.error(e); }); }).end(); - } catch (e) { + } + catch (e) { logger.error(e); } } @@ -94,12 +97,9 @@ function getBalance() { balanceQuery(a => { logger.info('Got balance data. Storing it'); balanceCache = a; - }); - } - exports.doBTC = (req, res) => { logger.info('Bitcoin request'); res.setHeader('Content-Type', 'application/json'); @@ -110,30 +110,27 @@ exports.doBalance = (req, res) => { logger.info('Balance request'); res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(balanceCache)); - }; function updateBitcoin() { - logger.warn('updateBitcoin'); getBitcoin(); const now = new Date(); const mod = 300000 - (now.getTime() % 300000); - let btcupdateFn = () => { + const btcupdateFn = () => { updateBitcoin(); }; setTimeout(btcupdateFn.bind(this), mod + 10); } function updateBalance() { - logger.warn('updateBalance'); getBalance(); const now = new Date(); const mod = 3.6e+6 - (now.getTime() % 3.6e+6); - let balanceUpdateFn = () => { + const balanceUpdateFn = () => { updateBalance(); }; setTimeout(balanceUpdateFn.bind(this), mod + 10); diff --git a/lib/caltest.js b/lib/caltest.js index 2bcef9d..d6bff49 100644 --- a/lib/caltest.js +++ b/lib/caltest.js @@ -6,16 +6,16 @@ var calHandler = require('./today/calHandler'); require('sugar-date'); -var cal = {today: [], tomorrow: [], week: []}; -var _cal_tmp = {today: [], tomorrow: [], week: []}; +var cal = { 'today': [], 'tomorrow': [], 'week': [] }; +var _cal_tmp = { 'today': [], 'tomorrow': [], 'week': [] }; -for (var t = 0; t < calHandler.calendars.length;t++) { - calHandler.getAdvancedCalV3(calHandler.calendars[t]) +for (var t = 0; t < calHandler.calendars.length;t++) + calHandler.getAdvancedCalV3(calHandler.calendars[t]) .then((d) => { 'use strict'; cal.today = cal.today.concat(d.today); - cal.tomorrow = cal.tomorrow.concat(d.tomorrow); - cal.week = cal.week.concat(d.week); + cal.tomorrow = cal.tomorrow.concat(d.tomorrow); + cal.week = cal.week.concat(d.week); logger.error(cal); @@ -24,7 +24,7 @@ for (var t = 0; t < calHandler.calendars.length;t++) { 'use strict'; logger.error(e); }); - } + diff --git a/lib/clean.js b/lib/clean.js index ab479ee..f96db8a 100644 --- a/lib/clean.js +++ b/lib/clean.js @@ -2,48 +2,48 @@ var http = require('http'), sys = require('sys'); module.exports = { - cleanit: function (req, res) { - var r = { + 'cleanit': function (req, res) { + var r = { // from http://tim.mackey.ie/CleanWordHTMLUsingRegularExpressions.aspx - msoTags: /<[\/]?(font|span|xml|del|ins|[ovwxp]:\w+)[^>]*?>/g, - msoAttributes: /<([^>]*)(?:class|lang|style|size|face|[ovwxp]:\w+)=(?:'[^']*'|""[^""]*""|[^\s>]+)([^>]*)>/, - msoParagraphs: /<([^>]*)(?:|[p]:\w+)=(?:'[^']*'|""[^""]*""|[^\s>]+)([^>]*)>/g, - crlf: /(\\r\\n)/g - }; + 'msoTags': /<[\/]?(font|span|xml|del|ins|[ovwxp]:\w+)[^>]*?>/g, + 'msoAttributes': /<([^>]*)(?:class|lang|style|size|face|[ovwxp]:\w+)=(?:'[^']*'|""[^""]*""|[^\s>]+)([^>]*)>/, + 'msoParagraphs': /<([^>]*)(?:|[p]:\w+)=(?:'[^']*'|""[^""]*""|[^\s>]+)([^>]*)>/g, + 'crlf': /(\\r\\n)/g + }; - var front = '\r\n \r\n \r\n \r\n Spellbinder - Chapter \r\n \r\n \r\n \r\n \r\n
\r\n
\r\n'; + var front = '\r\n \r\n \r\n \r\n Spellbinder - Chapter \r\n \r\n \r\n \r\n \r\n
\r\n
\r\n'; var back = '
'; - var source = req.body.source; + var source = req.body.source; // console.log(source); - var output = source.replace(r.msoTags, ""); - output = output.replace(r.msoParagraphs, '

'); - output = output.replace(/(\r\n)/g, " "); - output = output.replace(/(\\r\\n)/g, " "); + var output = source.replace(r.msoTags, ''); + output = output.replace(r.msoParagraphs, '

'); + output = output.replace(/(\r\n)/g, ' '); + output = output.replace(/(\\r\\n)/g, ' '); - output = output.replace(/<\/i>/g, ""); - output = output.replace(/[“|”]/g, '"'); - output = output.replace(/’/g, "'"); - output = output.replace(/…/g, "…"); - output = output.replace(/(.*?)<\/i>/g, "$1"); - output = output.replace(/(.*?)<\/b>/g, "$1"); - output = output.replace(/

\*\*\*<\/p>/g, "

* * *

"); + output = output.replace(/<\/i>/g, ''); + output = output.replace(/[“|”]/g, '"'); + output = output.replace(/’/g, '\''); + output = output.replace(/…/g, '…'); + output = output.replace(/(.*?)<\/i>/g, '$1'); + output = output.replace(/(.*?)<\/b>/g, '$1'); + output = output.replace(/

\*\*\*<\/p>/g, '

* * *

'); - output = output.replace(/

CHAPTER\s(\d.?)<\/p>/, "

$1

"); - output = output.replace(/

( |\s|\s<\/em>)<\/p>/g, ""); - output = output.replace(/ /g, " "); + output = output.replace(/

CHAPTER\s(\d.?)<\/p>/, '

$1

'); + output = output.replace(/

( |\s|\s<\/em>)<\/p>/g, ''); + output = output.replace(/ /g, ' '); - output = output.replace(/

\s<\/em><\/p>/g, ""); - output = output.replace(/

\s<\/p>/g, ""); + output = output.replace(/

\s<\/em><\/p>/g, ''); + output = output.replace(/

\s<\/p>/g, ''); - output = output.replace(/\s+/g, " "); - output = output.replace(/<\/p>/g, "

\r\n"); + output = output.replace(/\s+/g, ' '); + output = output.replace(/<\/p>/g, '

\r\n'); // sys.puts(sys.inspect(output, false, null)); - res.setHeader('Content-Type', 'application/html'); - res.end(front + output + back); - } -}; \ No newline at end of file + res.setHeader('Content-Type', 'application/html'); + res.end(front + output + back); + } +}; diff --git a/lib/events.js b/lib/events.js index 4437783..d4220d7 100644 --- a/lib/events.js +++ b/lib/events.js @@ -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; -var eventCache = { - last: 0, - data: {}, - expire: ((60 * 1000) * 60) * 12, - cinema: {} +const eventTimer = 0; +const eventCache = { + 'last': 0, + 'data': {}, + 'expire': ((60 * 1000) * 60) * 12, + 'cinema': {} }; // 'cwr':{data: {}, last:0}; -var 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: 'pho', url: 'https://film.list.co.uk/cinema/12500-showcase-cinema-paisley/'}]; +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': 'pho', 'url': 'https://film.list.co.uk/cinema/12500-showcase-cinema-paisley/' }]; 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...'); - var j = [], url = 'https://www.list.co.uk/events/days-out/when:this%20weekend/location:Dumbarton(55.9460,-4.5556)/distance:20/'; + const now = new Date(); - var now = new Date(); - - if ((now - eventCache.last) > eventCache.expire) { - request(url, function (err, resp, body) { - if (err) - throw err; - $ = cheerio.load(body); + if ((now - eventCache.last) > eventCache.expire) + request(url, function (err, resp, body) { + if (err) + throw err; + $ = cheerio.load(body); // console.log($); // TODO: scraping goes here! - $('.resultsRow').each(function (div) { - var item = {}; - var eventSummary = $(this).find('.eventSummary').first(); - var byDate = $(this).find('.byDate').first(); + $('.resultsRow').each(function (div) { + const item = {}; + const eventSummary = $(this).find('.eventSummary').first(); + const byDate = $(this).find('.byDate').first(); - var title = eventSummary.find('.head').first(); - var description = eventSummary.find('P').first(); - var link = ' https://www.list.co.uk' + eventSummary.find('A').first().attr('href'); + const title = eventSummary.find('.head').first(); + const description = eventSummary.find('P').first(); + const link = ` https://www.list.co.uk${ eventSummary.find('A').first().attr('href')}`; - var price = byDate.find('.price').first(); - var dt = byDate.find('.dtstart').first().attr('title'); + const price = byDate.find('.price').first(); + const dt = byDate.find('.dtstart').first().attr('title'); - item.title = title.text(); - item.description = description.text(); - item.link = link; - item.price = price.text(); - item.date = dt; + item.title = title.text(); + item.description = description.text(); + item.link = link; + item.price = price.text(); + item.date = dt; - j.push(item); - }); + j.push(item); + }); - eventCache.last = now; - eventCache.data = j; + eventCache.last = now; + eventCache.data = j; - res.render('pages/events', eventCache); - - }, function(error, response, body) { - if(response.statusCode !== 200) { - logger.error(response.statusCode); - logger.error(body); - } - }); - } else { - console.log('Using event cache...'); - - res.render('pages/events', eventCache); + res.render('pages/events', eventCache); + }, function(error, response, body) { + if(response.statusCode !== 200) { + logger.error(response.statusCode); + logger.error(body); } + }); + else { + console.log('Using event cache...'); - }, - 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); + res.render('pages/events', eventCache); } + }, + '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 () { - console.log('Pre loading cinemas...'); - module.exports.preLoad(); + console.log('Pre loading cinemas...'); + module.exports.preLoad(); }, 10000); diff --git a/lib/fx.js b/lib/fx.js index d3e2252..def928e 100644 --- a/lib/fx.js +++ b/lib/fx.js @@ -4,17 +4,17 @@ const trend = require('trend'); const logger = require('log4js').getLogger('fx'); const delay = 2764800; // 32 days divided by 1000 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() { logger.info('FX request'); function fxQuery(callback) { - let options = { - host: 'openexchangerates.org', - // port: 80, - path: '/api/latest.json?app_id=0eb932cee3bc40259f824d4b4c96c7d2', + const options = { + 'host': 'openexchangerates.org', + // port: 80, + 'path': '/api/latest.json?app_id=0eb932cee3bc40259f824d4b4c96c7d2', // method: 'GET', - headers: { } + 'headers': { } }; http.request(options).on('response', response => { @@ -36,12 +36,10 @@ function getFx() { logger.info('Got FX data. Storing it'); fxCache = a; - let minRates = {USD:fxCache.rates.USD, GBP:fxCache.rates.GBP, SEK:fxCache.rates.SEK}; - fxCache.rates = minRates; + fxCache.rates = { 'USD': fxCache.rates.USD, 'GBP': fxCache.rates.GBP, 'SEK': fxCache.rates.SEK }; history.push(a.rates.GBP); 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); - let fxUpdateFn = () => { + const fxUpdateFn = () => { updateFX(); }; setTimeout(fxUpdateFn.bind(this), mod + 10); @@ -67,5 +65,4 @@ exports.doFx = (req, res) => { logger.info('FX request'); res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(fxCache)); - }; diff --git a/lib/password.js b/lib/password.js index f9b8656..e35bfba 100644 --- a/lib/password.js +++ b/lib/password.js @@ -46,19 +46,18 @@ var numberCluster = function () { var randomAmount = function (i) { var str = ''; - for (var t = 0; t < i; t++) { + for (var t = 0; t < i; t++) str = str + alpha.random(); - } return str; }; module.exports = { - generate: function (req, res) { + 'generate': function (req, res) { var reply = { - long: (left.random() + ' ' + right.random() + ' ' + numberCluster() + ' ' + numberCluster()).split(' ').join(whitespace.random()), - short: randomAmount(10) + 'long': (`${left.random() } ${ right.random() } ${ numberCluster() } ${ numberCluster()}`).split(' ').join(whitespace.random()), + 'short': randomAmount(10) }; res.setHeader('Content-Type', 'application/json'); diff --git a/views/pages/slackV2-min.ejs b/views/pages/slackV2-min.ejs index 9b4c413..b1160ab 100644 --- a/views/pages/slackV2-min.ejs +++ b/views/pages/slackV2-min.ejs @@ -24,7 +24,7 @@
diff --git a/web-server.js b/web-server.js index a8a2510..e9e6d19 100644 --- a/web-server.js +++ b/web-server.js @@ -20,24 +20,23 @@ const errorhandler = require('errorhandler'); const jsonfile = require('jsonfile'); 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 wss = new WebSocketServer({server: server}); +const wss = new WebSocketServer({ 'server': server }); 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') /* ,submit = require('./routes/mongo/submit') */ - -let fs = require('fs'); +const fs = require('fs'); const config = require('./config/config.json'); const Fitbit = require('fitbit-oauth2'); @@ -51,20 +50,20 @@ let btcCache = {}, fxCache = {}, trainCache = {}; const port = process.env.PORT || 9000; - // app.configure(function () { app.set('port', port); app.set('view engine', 'ejs'); app.use(morgan('dev')); app.use(cookieParser('your secret here')); app.use(session({ - secret: 'd2jRT6ZpYFsXsF3kGS21ZszKbPAaEa', resave: false, - saveUninitialized: false + 'secret': 'd2jRT6ZpYFsXsF3kGS21ZszKbPAaEa', 'resave': false, + 'saveUninitialized': false })); + /* 'default', 'short', 'tiny', 'dev' */ app.use(methodoverride()); -app.use(bodyparser.urlencoded({extended: false})); +app.use(bodyparser.urlencoded({ 'extended': false })); // parse application/json app.use(bodyparser.json()); @@ -77,7 +76,7 @@ app.use(function(req, res, next) { // app.use(app.router); 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('/balance', btc.doBalance); @@ -94,26 +93,22 @@ app.use('/generate', password.generate); app.use('/cleanit', clean.cleanit); - - app.use('/events', events.getEvents); app.get('/cinema/:id', events.getCinema); // app.get('/today', today.getToday); // app.get('/today/data', today.getData); -//app.route('/clock').get(today.getClock); +// app.route('/clock').get(today.getClock); app.route('/poly').get(polys); - -/*app.use('/lot', function(req, res) { +/* app.use('/lot', function(req, res) { const pg = require('pg'); const conString = 'postgres://pguser:1V3D4m526i@localhost/silver'; console.log(conString); - const client = new pg.Client(conString); const q = 'select * from lot order by d desc'; client.connect(function(err) { @@ -140,15 +135,11 @@ app.get('/temp', function(req, res) { res.render('pages/temp'); }); - - const tfile = 'fb-token.json'; - // Instanciate a fitbit client. See example config below. // - const fitbit = new Fitbit(config.fitbit); // 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()); }); - app.get( '/fb-profile', function( req, res, next ) { fitbit.request({ - uri: 'https://api.fitbit.com/1/user/-/profile.json', - method: 'GET', + 'uri': 'https://api.fitbit.com/1/user/-/profile.json', + 'method': 'GET' }, function( err, body, token ) { if ( err ) return next( err ); var profile = JSON.parse( body ); @@ -169,20 +159,20 @@ app.get( '/fb-profile', function( req, res, next ) { if ( token ) persist.write( tfile, token, function( err ) { if ( err ) return next( err ); - res.send( '
' + JSON.stringify( profile, null, 2 ) + '
' ); + res.send( `
${ JSON.stringify( profile, null, 2 ) }
` ); }); else - res.send( '
' + JSON.stringify( profile, null, 2 ) + '
' ); + res.send( `
${ JSON.stringify( profile, null, 2 ) }
` ); }); }); app.get( '/fb-today', function( req, res, next ) { 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({ - uri: url, - method: 'GET', + 'uri': url, + 'method': 'GET' }, function( err, body, token ) { if ( err ) return next( err ); var profile = JSON.parse( body ); @@ -190,10 +180,10 @@ app.get( '/fb-today', function( req, res, next ) { if ( token ) persist.write( tfile, token, function( err ) { if ( err ) return next( err ); - res.send( '
' + JSON.stringify( profile, null, 2 ) + '
' ); + res.send( `
${ JSON.stringify( profile, null, 2 ) }
` ); }); else - res.send( '
' + JSON.stringify( profile, null, 2 ) + '
' ); + res.send( `
${ JSON.stringify( profile, null, 2 ) }
` ); }); }); @@ -206,7 +196,6 @@ app.get('/fitbit_auth_callback', function(req, res, next) { fitbit.fetchToken(code, function(err, token) { if (err) return next(err); - // persist the token jsonfile.writeFile(tfile, token, function(err) { @@ -215,21 +204,17 @@ app.get('/fitbit_auth_callback', function(req, res, next) { console.log('!!!! Fitbit token saved'); res.redirect('/fb-profile'); - }); }); }); - jsonfile.readFile('./fb-token.json', function(err, obj) { if (err) logger.error(err); else fitbit.setToken(obj); - }); - // }); /** @@ -242,10 +227,8 @@ http.createServer(app).listen(app.get('port'), function () { }); */ - - server.on('request', app); server.listen(port, () => { - logger.info('New server listening on ' + server.address().port); + logger.info(`New server listening on ${ server.address().port}`); });