From 9b2ffdf0d8ef706121f46af04d92c7b072c28d34 Mon Sep 17 00:00:00 2001 From: martind2000 Date: Wed, 22 Mar 2017 15:48:36 +0000 Subject: [PATCH] tidying up --- app/app.js | 215 ++++++------ app/js/modules/bitcoin.js | 117 +++++++ gulpfile.js | 65 ++++ lib/today.js | 606 ++++++++++++++++++---------------- lib/today/mailer.js | 2 +- lib/today/swedishword.js | 24 +- lib/today/swedishword.spec.js | 16 + lib/today/todayftse.js | 5 +- lib/today/trains.spec.js | 13 + lib/today/weather.js | 22 +- lib/today/weather.spec.js | 13 + lib/train.js | 87 +++-- lib/weather.js | 30 +- package.json | 25 ++ serverV2.js | 201 +++++++++++ views/pages/slackV2.ejs | 380 +++++++++++++++++++++ views/partials/head.ejs | 7 +- web-server.js | 216 ++++++------ 18 files changed, 1441 insertions(+), 603 deletions(-) create mode 100644 app/js/modules/bitcoin.js create mode 100644 gulpfile.js create mode 100644 lib/today/swedishword.spec.js create mode 100644 lib/today/trains.spec.js create mode 100644 lib/today/weather.spec.js create mode 100644 serverV2.js create mode 100644 views/pages/slackV2.ejs diff --git a/app/app.js b/app/app.js index a8d4fd5..d625a4f 100644 --- a/app/app.js +++ b/app/app.js @@ -1,9 +1,8 @@ -(function () { - - var lastGBP = 0.0, +(function() { + let lastGBP = 0.0, lastUSD = 0.0, _fasttimer, _slowTimer, myBTC = 3.49524333; - var lows = { + let lows = { gbp: 0, usd: 0 }, @@ -12,65 +11,66 @@ usd: 0 }; - var list = [{ + let list = [{ title: '101B ends', y: 2013, m: 9, d: 24, add: 1001 }, - { - title: 'Ends', - y: 2016, - m: 4, - d: 4 - }]; + { + title: 'Ends', + y: 2016, + m: 4, + d: 4 + }]; MicroEvent.mixin(this); - var self = this; + let self = this; - var addDays = function (myDate, days) { + let addDays = function(myDate, days) { return new Date(myDate.getTime() + days * 24 * 60 * 60 * 1000); }; - var getDays = function (startdate, enddate) { - var r, s, e; + let getDays = function(startdate, enddate) { + let r, s, e; s = startdate.getTime(); e = enddate.getTime(); r = (e - s) / (24 * 60 * 60 * 1000); return r; }; - var tick = function () { - var today = new Date(); - var start101 = new Date(); - var end101; - var endContract = new Date(); - var third = new Date(); + let tick = function() { + let today = new Date(); + let start101 = new Date(); + let end101; + let endContract = new Date(); + let third = new Date(); start101.setFullYear(2013, 9, 24); end101 = addDays(start101, 1001); - endContract.setFullYear(2016, 4, 4); + endContract.setFullYear(2017, 6, 5); third.setFullYear(2013, 7, 25); - $('#one').text('101B ends: ' + Math.ceil(getDays(today, - end101)) + " days / " + Math.ceil(getDays(today, - end101) / 7) + " weeks"); + /*$('#one').text('101B ends: ' + Math.ceil(getDays(today, + end101)) + ' days / ' + Math.ceil(getDays(today, + end101) / 7) + ' weeks');*/ + $('#one').hide(); $('#two').text('Ends: ' + Math.ceil(getDays(today, - endContract)) + " days / " + Math.ceil(getDays(today, - endContract) / 7) + " weeks"); + endContract)) + ' days / ' + Math.ceil(getDays(today, + endContract) / 7) + ' weeks'); $('#three').hide(); }; - var get_weather = function () { + let get_weather = function() { navigator.geolocation.getCurrentPosition(show_weather); }; - this.bind('displayWeather', function (data) { - $('#weather').html(data.currently.summary + ' ' + data.currently.temperature + '°c ' + data.daily.summary + ''); + this.bind('displayWeather', function(data) { + $('#weather').html(data.currently.summary + ' ' + data.currently.temperature + '°c ' + data.daily.summary + ''); }); - var show_weather = function (position) { - var latitude = position.coords.latitude; - var longitude = position.coords.longitude; + var show_weather = function(position) { + let latitude = position.coords.latitude; + let longitude = position.coords.longitude; // let's show a map or do something interesting! $.ajax({ type: 'GET', @@ -85,28 +85,26 @@ 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type' }, - success: function (data) { + success: function(data) { self.trigger('displayWeather', data); }, - error: function (xhr, type) { - console.log("ajax error"); + error: function(xhr, type) { + console.log('ajax error'); console.log(xhr); console.log(type); } }); }; - var updateBTC = function (g, u) { - var title, total, elm = $('#btc'); + let updateBTC = function(g, u) { + let title, total, elm = $('#btc'); if (lastGBP !== 0) { - elm.removeClass(); if (g > lastGBP) { elm.addClass('up'); } else if (g < lastGBP) { elm.addClass('down'); } - } else { lows.gbp = g; lows.usd = u; @@ -126,23 +124,23 @@ total = myBTC * g; - title = "High: $" + parseFloat(highs.usd.toFixed(2)) + " / Low $" + parseFloat(lows.usd.toFixed(2)); - elm.html("$" + parseFloat(u.toFixed(2)) + " / £" + parseFloat(g.toFixed(2)) + " (£" + parseFloat(total.toFixed(2)) + ")"); + title = 'High: $' + parseFloat(highs.usd.toFixed(2)) + ' / Low $' + parseFloat(lows.usd.toFixed(2)); + elm.html('$' + parseFloat(u.toFixed(2)) + ' / £' + parseFloat(g.toFixed(2)) + ' (£' + parseFloat(total.toFixed(2)) + ')'); elm.prop('title', title); }; - var updateFX = function (data) { - var elm = $('#fx'); - elm.html("£1 = $" + parseFloat(data.gpbe.toFixed(2)) + " = " + parseFloat(data.sekex.toFixed(2)) + " SEK"); + let updateFX = function(data) { + let elm = $('#fx'); + elm.html('£1 = $' + parseFloat(data.gpbe.toFixed(2)) + ' = ' + parseFloat(data.sekex.toFixed(2)) + ' SEK'); }; - this.bind('updateFX', function (data) { - $('#fx').html("£1 = $" + parseFloat(data.gpbe.toFixed(2)) + " = " + parseFloat(data.sekex.toFixed(2)) + " SEK"); + this.bind('updateFX', function(data) { + $('#fx').html('£1 = $' + parseFloat(data.gpbe.toFixed(2)) + ' = ' + parseFloat(data.sekex.toFixed(2)) + ' SEK'); }); - var btcValue = function () { - var url = '/btc'; + let btcValue = function() { + let url = '/btc'; $.ajax({ type: 'GET', @@ -159,27 +157,27 @@ 'Access-Control-Allow-Headers': 'Content-Type' }, - success: function (data) { + success: function(data) { // console.log(data); - var gbp = data.bpi.GBP.rate_float, + let gbp = data.bpi.GBP.rate_float, usd = data.bpi.USD.rate_float; updateBTC(gbp, usd); }, - error: function (xhr, type) { - console.log("ajax error"); + error: function(xhr, type) { + console.log('ajax error'); console.log(xhr); console.log(type); } }); }; - this.bind('getBTC', function () { + /*this.bind('getBTC', function() { btcValue(); - }); + });*/ - var getFX = function () { - var url = '/fx'; + let getFX = function() { + let url = '/fx'; $.ajax({ type: 'GET', @@ -196,10 +194,10 @@ 'Access-Control-Allow-Headers': 'Content-Type' }, - success: function (data) { - var gpbex = (1 / data.rates.GBP); - var sekex = (gpbex * data.rates.SEK); - var fxdata = { + 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, @@ -208,21 +206,21 @@ }; self.trigger('updateFX', fxdata); }, - error: function (xhr, type) { - console.log("ajax error"); + error: function(xhr, type) { + console.log('ajax error'); console.log(xhr); console.log(type); } }); }; - this.bind('getFX', function () { + this.bind('getFX', function() { getFX(); }); - var getNextTrainTime = function (toStation, fromStation) { - var url = '/getnexttraintimes?from=' + fromStation + '&to=' + toStation; - var target = fromStation + toStation; + let getNextTrainTime = function(toStation, fromStation) { + let url = '/getnexttraintimes?from=' + fromStation + '&to=' + toStation; + let target = fromStation + toStation; $.ajax({ type: 'GET', url: url, @@ -236,42 +234,41 @@ 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type' }, - success: function (data) { + success: function(data) { updateTrain(target, data); }, - error: function (xhr, type) { - console.log("ajax error"); + error: function(xhr, type) { + console.log('ajax error'); console.log(xhr); console.log(type); } }); - }; - var updateTrain = function (n, obj) { - var elm = $('#' + n); + var updateTrain = function(n, obj) { + let elm = $('#' + n); - var output, status; + let output, status; - output = (obj.eta == "On Time") ? obj.eta : obj.sta; - status = (obj.eta == "On Time") ? 'delayed' : 'ontime'; + output = (obj.eta == 'On Time') ? obj.eta : obj.sta; + status = (obj.eta == 'On Time') ? 'delayed' : 'ontime'; elm.html(output); elm.removeClass('delayed').removeClass('ontime').addClass( status); //elm.addClass( status); }; - var getTrainsCB = function (results) { - var dest$ = $('#trainResults'); - var html = new EJS({url: '/template/trains.ejs'}).render(results); + let getTrainsCB = function(results) { + let dest$ = $('#trainResults'); + let html = new EJS({url: '/template/trains.ejs'}).render(results); dest$.empty(); dest$.append(html); dest$.toggle(); }; - var getTrains = function (from, to) { - var url = '/gettrains?from=' + from + "&to=" + to; + let getTrains = function(from, to) { + let url = '/gettrains?from=' + from + '&to=' + to; $.ajax({ type: 'GET', @@ -286,28 +283,27 @@ 'Access-Control-Allow-Headers': 'Content-Type' }, - success: function (data) { + success: function(data) { getTrainsCB(data); }, - error: function (xhr, type) { - console.log("ajax error"); + error: function(xhr, type) { + console.log('ajax error'); console.log(xhr); console.log(type); } }); }; - var formatPassword = function (data) { - - var dest$ = $('#passwordOut'); - var html = new EJS({url: '/template/password.ejs'}).render(data); + let formatPassword = function(data) { + let dest$ = $('#passwordOut'); + let html = new EJS({url: '/template/password.ejs'}).render(data); dest$.empty(); dest$.append(html); dest$.show(); }; - var generatePassword = function (from, to) { - var url = '/generate'; + let generatePassword = function(from, to) { + let url = '/generate'; $.ajax({ type: 'GET', @@ -323,11 +319,11 @@ 'Access-Control-Allow-Headers': 'Content-Type' }, - success: function (data) { + success: function(data) { formatPassword(data); }, - error: function (xhr, type) { - console.log("ajax error"); + error: function(xhr, type) { + console.log('ajax error'); console.log(xhr); console.log(type); } @@ -343,47 +339,46 @@ // start 15 minute timer - _fastTimer = setInterval(function () { + _fastTimer = setInterval(function() { self.trigger('getBTC'); getNextTrainTime('dbe', 'glq'); getNextTrainTime('glq', 'dbe'); }, (60000)); - _slowTimer = setInterval(function () { - + _slowTimer = setInterval(function() { self.trigger('getFX'); get_weather(); }, (60000 * 15)); - $('#dbeglq').on('click', function () { + $('#dbeglq').on('click', function() { self.trigger('getTrains', 'dbe', 'glq'); }); - $('#glqdbe').on('click', function () { + $('#glqdbe').on('click', function() { self.trigger('getTrains', 'glq', 'dbe'); }); - $('#newPassword').on('click', function () { + $('#newPassword').on('click', function() { generatePassword(); }); - this.bind('getTrains', function (start, end) { + this.bind('getTrains', function(start, end) { getTrains(start, end); }); document.title = 'Slack'; })(); -var popitout = function (url) { - var newwindow = window.open(url, 'name', 'height=600,width=570'); - if (window.focus) { - newwindow.focus() - } - return false; -}; - -var popitoutSmall = function (url) { - var newwindow = window.open(url, 'name', 'height=400,width=520'); +let popitout = function(url) { + let newwindow = window.open(url, 'name', 'height=600,width=570'); + if (window.focus) { + newwindow.focus(); + } + return false; +}; + +let popitoutSmall = function(url) { + let newwindow = window.open(url, 'name', 'height=400,width=520'); if (window.focus) { newwindow.focus(); } diff --git a/app/js/modules/bitcoin.js b/app/js/modules/bitcoin.js new file mode 100644 index 0000000..312c0c9 --- /dev/null +++ b/app/js/modules/bitcoin.js @@ -0,0 +1,117 @@ +/** + * Created by mdonnel on 22/03/2017. + */ + +let BitcoinModel = Backbone.Model.extend({ + initialize: function () { + this.set('url', '/btc'); + let data = { + lastGBP: 0.0, + lastUSD: 0.0, + lows: {gbp: 0, usd: 0}, + highs: {gbp: 0, usd: 0}, + eclass: '' + }; + this.set('btcdata', data); + this.update(); + }, + update: function () { + this.getBTC(); + const now = new Date; + const mod = 60000 - (now.getTime() % 60000); + + let btcupdateFn = function() { + this.update(); + }; + setTimeout(btcupdateFn.bind(this), mod + 10); + }, + recalc: function () { + let data = this.get('btcdata'); + let lastGBP = data.lastGBP; + let lastUSD = data.lastUSD; + let g = data.gbp; + let u = data.usd; + let lows = data.lows; + let highs = data.highs; + let eclass = data.eclass; + + 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, + lastUSD, + lows, + highs, + eclass + }; + this.set('btcdata', data); + // total = myBTC * g; + }, + getBTC: function () { + let self = this; + let 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 (data) { + let gbp = data.bpi.GBP.rate_float, + usd = data.bpi.USD.rate_float; + let btcdata = self.get('btcdata'); + btcdata.gbp = gbp; + btcdata.usd = usd; + self.set('btcdata', btcdata); + self.recalc(); + }, + error: function (xhr, type) { + console.log('ajax error'); + console.log(xhr); + console.log(type); + } + }); + } +}); +let Bitcoin = Backbone.View.extend({ + tagName: 'div', + initialize: function () { + _.bindAll(this, 'render'); + this.model.bind('change', this.render); + this.$btc = $('#btc'); + }, + render: function () { + let btcdata = this.model.get('btcdata'); + let title = 'High: $' + parseFloat(btcdata.highs.usd.toFixed(2)) + ' / Low $' + parseFloat(btcdata.lows.usd.toFixed(2)); + this.$btc.removeClass(); + this.$btc.addClass(btcdata.eclass); + this.$btc.html(`$${parseFloat(btcdata.lastUSD.toFixed(2)) } / £${parseFloat(btcdata.lastGBP.toFixed(2))}` ); + this.$btc.prop('title', title); + } +}); diff --git a/gulpfile.js b/gulpfile.js new file mode 100644 index 0000000..47e9d99 --- /dev/null +++ b/gulpfile.js @@ -0,0 +1,65 @@ +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'); + +let filePath = { + build_dir: 'live' +}; + +let dest = 'live'; + + +let fontOptions = { }; + +gulp.task('appJS', function() { + return gulp.src(['app/app.js']) + .pipe(stripDebug()) + .pipe(jshint('.jshintrc')) + .pipe(jshint.reporter('default')) + .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: false, // 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('vendor', function() { + return gulp.src([ + 'app/libs/zepto.min.js', + 'app/libs/microevent.js', + 'app/libs/ejs.js' + ]) + .pipe(concat('vendor.js')) + .pipe(uglify({mangle: false})) + .pipe(gulp.dest(dest + '/js')); + }); \ No newline at end of file diff --git a/lib/today.js b/lib/today.js index 0fa77bf..a9fd5ff 100644 --- a/lib/today.js +++ b/lib/today.js @@ -1,15 +1,16 @@ /** -* Created by marti on 30/01/2016. -*/ -let http = require('http'), request = require('request'), cheerio = require( - 'cheerio'), util = require('util'); + * Created by marti on 30/01/2016. + */ +const http = require('http'); +const request = require('request'); +const cheerio = require('cheerio'); +const util = require('util'); const cron = require('node-cron'); const dateFormat = require('dateformat'); const jsonfile = require('jsonfile'); let fs = require('fs'); //var nano = require('nano')('http://martind2000:1V3D4m526i@localhost:5984'); -const log4js = require('log4js'); -const logger = log4js.getLogger(); +const logger = require('log4js').getLogger(); const calHandler = require('./today/calHandler'); const swedishWord = require('./today/swedishword'); const weather = require('./today/weather'); @@ -37,7 +38,7 @@ const credentials = { "host": "25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix.cloudant.com", "port": 443, "url": "https://25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix:8e417af1b0462ca55726848846cc6b8696fc76defe9d1864cbc334be59549e0c@25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix.cloudant.com", - "database": "keeper" + "database": "today" }; const Cloudant = require('cloudant'); @@ -46,25 +47,27 @@ const cloudant = Cloudant({account: credentials.username, password: credentials. const dbCloudant = cloudant.db.use(credentials.database); - require('sugar-date'); -String.prototype.hashCode = function() { +String.prototype.hashCode = function () { if (Array.prototype.reduce) { - return this.split('').reduce(function(a,b) {a = ((a << 5) - a) + b.charCodeAt(0);return a & a},0); + return this.split('').reduce(function (a, b) { + a = ((a << 5) - a) + b.charCodeAt(0); + return a & a + }, 0); } else { - let hash = 0, i, chr, len; - if (this.length == 0) return hash; - for (i = 0, len = this.length; i < len; i++) { - chr = this.charCodeAt(i); - hash = ((hash << 5) - hash) + chr; - hash |= 0; // Convert to 32bit integer - } - return hash; + let hash = 0, i, chr, len; + if (this.length === 0) return hash; + for (i = 0, len = this.length; i < len; i++) { + chr = this.charCodeAt(i); + hash = ((hash << 5) - hash) + chr; + hash |= 0; // Convert to 32bit integer + } + return hash; } - }; +}; let todayCache = { last: 0, data: { @@ -84,363 +87,380 @@ let htmlfile = __dirname + '/' + 'today.html'; let eventEmitter; function runable() { - try { - const now = new Date().getTime(); + try { + const now = new Date().getTime(); - console.log('last updated', ((now - todayCache.last) / 60000)); - if (now - todayCache.last < 3600000) { - return false; - } else { - todayCache.last = now; - return true; + console.log('last updated', ((now - todayCache.last) / 60000)); + if (now - todayCache.last < 3600000) { + return false; + } else { + todayCache.last = now; + return true; + } } - } - catch (e) { - todayCache.last = new Date().getTime(); - return true; + catch (e) { + todayCache.last = new Date().getTime(); + return true; - } + } } function broadcastWeather() { - const wData = { - temperature: todayCache.data.weather.data.currently.temperature, - icon: todayCache.data.weather.data.currently.icon, - summary: todayCache.data.weather.data.currently.summary - }; + const wData = { + temperature: todayCache.data.weather.data.currently.temperature, + icon: todayCache.data.weather.data.currently.icon, + summary: todayCache.data.weather.data.currently.summary + }; - if (todayCache.data.weather.data.hasOwnProperty('alerts')) { - wData.alerts = todayCache.data.weather.data.alerts; - } - eventEmitter.emit('sendSocket', {id: 'weather', data: wData}); + if (todayCache.data.weather.data.hasOwnProperty('alerts')) { + wData.alerts = todayCache.data.weather.data.alerts; + } + eventEmitter.emit('sendSocket', {id: 'weather', data: wData}); } function loadData() { - console.log('Loading old data'); - try { - todayCache = jsonfile.readFileSync(file); - } - catch (e) { - console.error('Could not load previous data'); - } + console.log('Loading old data'); + try { + todayCache = jsonfile.readFileSync(file); + } + catch (e) { + console.error('Could not load previous data'); + } } function saveData() { - todayCache.last = new Date().getTime(); - logger.info('Saving...'); - jsonfile.writeFileSync(file, todayCache); + todayCache.last = new Date().getTime(); + logger.info('Saving...'); + jsonfile.writeFileSync(file, todayCache); } function saveToDB(data) { - saveData(); + saveData(); - logger.debug('Inserting into couch...'); - // Logger.info(util.inspect(obj)); - dbCloudant.insert(data, function(err, body, header) { - if (err) { - logger.error('Error inserting into couch'); - logger.error(err); - return; - } - }); + logger.debug('Inserting into couch...'); + // Logger.info(util.inspect(obj)); + dbCloudant.insert(data, function (err, body, header) { + if (err) { + logger.error('Error inserting into couch'); + logger.error(err); + return; + } + }); } function nth(d) { - // If (d > 3 && d < 21) {return 'th';} // Thanks kennebec - // if (d % 10 === 1) {return 'st';} else if (d % 10 === 2) {return 'nd';} else if (d % 10 === 3) {return 'rd';} else {return 'th';} - const n = d; - return Math.floor(n / 10) === 1 ? 'th' : (n % 10 === 1 ? 'st' : (n % 10 === 2 ? 'nd' : (n % 10 === 3 ? 'rd' : 'th'))); + // If (d > 3 && d < 21) {return 'th';} // Thanks kennebec + // if (d % 10 === 1) {return 'st';} else if (d % 10 === 2) {return 'nd';} else if (d % 10 === 3) {return 'rd';} else {return 'th';} + const n = d; + return Math.floor(n / 10) === 1 ? 'th' : (n % 10 === 1 ? 'st' : (n % 10 === 2 ? 'nd' : (n % 10 === 3 ? 'rd' : 'th'))); } function dayNumber() { - const now = new Date(); - const start = new Date(now.getFullYear(), 0, 0); - const diff = now - start; - const oneDay = 1000 * 60 * 60 * 24; - return Math.floor(diff / oneDay); + const now = new Date(); + const start = new Date(now.getFullYear(), 0, 0); + const diff = now - start; + const oneDay = 1000 * 60 * 60 * 24; + return Math.floor(diff / oneDay); } function breakDay() { - const now = new Date(); - return { - year: now.getFullYear(), - month: parseInt(now.getMonth()) + 1, - day: now.getDate() - }; + const now = new Date(); + return { + year: now.getFullYear(), + month: parseInt(now.getMonth()) + 1, + day: now.getDate() + }; } function reduceTrains(d) { - const titles = [], ta = []; - console.log('reducetrains',d); - for (let items in d) { - if (typeof d[items].title !== 'undefined') { - const hash = d[items].title.hashCode(); - if (titles.indexOf(hash) === -1) { - titles.push(hash); - ta.push(d[items]); - } + const titles = [], ta = []; + // console.log('reducetrains',d); + /*for (let items in d) { + if (typeof d[items].title !== 'undefined') { + const hash = d[items].title.hashCode(); + if (titles.indexOf(hash) === -1) { + titles.push(hash); + ta.push(d[items]); + } + } + + }*/ + + for (let item in d) { + if (typeof item.title !== 'undefined') { + const hash = item.title.hashCode(); + if (titles.indexOf(hash) === -1) { + titles.push(hash); + ta.push(item); + } + } } - - } - return ta; + return ta; } /** * @return {number} */ function DayDiff(CurrentDate) { - const TYear = CurrentDate.getFullYear(); - const TDay = new Date('January, 01, ' + (parseInt(TYear) + 1)); - TDay.getFullYear(TYear); - let DayCount = (TDay - CurrentDate) / (1000 * 60 * 60 * 24); - DayCount = Math.round(DayCount); + const TYear = CurrentDate.getFullYear(); + const TDay = new Date('January, 01, ' + (parseInt(TYear) + 1)); + TDay.getFullYear(TYear); + let DayCount = (TDay - CurrentDate) / (1000 * 60 * 60 * 24); + DayCount = Math.round(DayCount); - const d = new Date(); - DayCount = d.daysSince('beginning of this year'); - return (DayCount); + const d = new Date(); + DayCount = d.daysSince('beginning of this year'); + return (DayCount); } Array.prototype.indexOfOld = Array.prototype.indexOf; -Array.prototype.indexOf = function(e, fn) { - if (!fn) { - return this.indexOfOld(e); - } else { - if (typeof fn === 'string') { - const att = fn; - fn = function(e) { - return e[att]; - }; +Array.prototype.indexOf = function (e, fn) { + if (!fn) { + return this.indexOfOld(e); + } else { + if (typeof fn === 'string') { + const att = fn; + fn = function (e) { + return e[att]; + }; + } + return this.map(fn).indexOfOld(e); } - return this.map(fn).indexOfOld(e); - } }; module.exports = { - setEmitter: function(newEmitter) { - console.log('Setting events', newEmitter); - eventEmitter = newEmitter; - }, getClock: function(req, res) { - // Console.log(todayCache); - res.render('pages/clock', todayCache); - }, getToday: function(req, res) { - logger.info(todayCache); - res.render('pages/today', todayCache); - }, getData: function(req, res) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(todayCache)); - }, getTodayDate: function() { - let s; + setEmitter: function (newEmitter) { + console.log('Setting events', newEmitter); + eventEmitter = newEmitter; + }, + getClock: function (req, res) { + // Console.log(todayCache); + res.render('pages/clock', todayCache); + }, + getToday: function (req, res) { + logger.info(todayCache); + res.render('pages/today', todayCache); + }, + getData: function (req, res) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(todayCache)); + }, + getTodayDate: function () { + let s; const d = new Date(); let nextYear = (parseInt(d.getFullYear()) + 1).toString() + '-01-01'; - console.log(d.daysUntil('beginning of next year')); - const daysSinceStart = d.daysSince('beginning of this year'); - const daysRemaining = d.daysUntil('beginning of next year'); + console.log(d.daysUntil('beginning of next year')); + const daysSinceStart = d.daysSince('beginning of this year'); + const daysRemaining = d.daysUntil('beginning of next year'); - todayCache.data.history = []; - s = '' + d.format('{Weekday} {Month} {dd}, {yyyy}') + ' - '; + todayCache.data.history = []; + s = '' + d.format('{Weekday} {Month} {dd}, {yyyy}') + ' - '; - s = s + 'The ' + daysSinceStart + nth(daysSinceStart) + ' day of ' + dateFormat( - d, - 'yyyy') + ', and there are ' + daysRemaining + ' days left until the end of the year.'; + /* + s = s + 'The ' + daysSinceStart + nth(daysSinceStart) + ' day of ' + dateFormat( + d, + 'yyyy') + ', and there are ' + daysRemaining + ' days left until the end of the year.'; + */ - logger.debug(s); - todayCache.data.today = s; - }, - refreshTrain: function() { + s = s + `The ${daysSinceStart + nth(daysSinceStart)} day of ${dateFormat(d, 'yyyy')}, and there are ${daysRemaining} days until the end of the year` - trains.updateTrains() - .then((d) => { - 'use strict'; + logger.debug(s); + todayCache.data.today = s; + }, + refreshTrain: function () { - d = reduceTrains(d); - console.log('Trains: ', d); - - eventEmitter.emit('sendSocket', {id: 'trains', data: d}); - todayCache.data.trains.data = d; - todayCache.data.trains.last = new Date(); - }) - .catch((e)=> { - 'use strict'; - console.error(e); - }); - - - }, - refreshWeather: function() { - weather.newDoGetWeather() - .then((d) => { - todayCache.data.weather = d; - console.log('Updating weather'); - broadcastWeather(); - }).catch((e) => { - logger.error(e); - }); - - }, - - refreshTrainAndWeather: function() { - this.refreshTrain(); - this.refreshWeather(); - }, preLoadToday: function() { - module.exports.getTodayDate(); - todayCache.data.cal = {today: [], tomorrow: [], week: []}; - weather.newDoGetWeather() - .then((d)=> { - todayCache.data.weather = d; - }) - .catch((e) => { - logger.error(e); - }); - trains.updateTrains() - .then((d) => { - 'use strict'; - console.log('Trains: ', d); - todayCache.data.trains.data = d; - todayCache.data.trains.last = new Date(); - }) - .catch((e)=> { - 'use strict'; - console.error(e); - }); - history.updateHistory() - .then((d) => { - 'use strict'; - console.log('History result: ', d); - todayCache.data.history = d; - }) - .catch((e)=> { - 'use strict'; - console.error(e); - }); - - calHandler.getSimpleCalV3( - 'http://www.pogdesign.co.uk/cat/download_ics/60cfdff469d0490545d33d7e3b5c0bcc') - .then((d) => { - 'use strict'; - todayCache.data.tv = d; - }) - .catch((e) => { - 'use strict'; - logger.error(e); - }); - - todayFTSE.getFTSE() - .then((d) => { - todayCache.data.ftse = d; - }) - .catch((e) => { - logger.error(e); - }); - - quotes.GetQuotes() + trains.updateTrains() .then((d) => { - todayCache.data.quotes = d; + 'use strict'; + + d = reduceTrains(d); + + eventEmitter.emit('sendSocket', {id: 'trains', data: d}); + todayCache.data.trains.data = d; + todayCache.data.trains.last = new Date(); }) - .catch((e)=> { - logger.error(e); + .catch((e) => { + 'use strict'; + logger.error(e); }); - - for (let t = 0; t < calHandler.calendars.length; t++) { - calHandler.getAdvancedCalV3(calHandler.calendars[t]) - .then((d) => { - 'use strict'; - todayCache.data.cal.today = todayCache.data.cal.today.concat(d.today); - todayCache.data.cal.tomorrow = todayCache.data.cal.tomorrow.concat(d.tomorrow); - todayCache.data.cal.week = todayCache.data.cal.week.concat(d.week); - }) - .catch((e) => { - 'use strict'; + }, + refreshWeather: function () { + weather.newDoGetWeather() + .then((d) => { + todayCache.data.weather = d; + logger.info('Updating weather'); + broadcastWeather(); + }).catch((e) => { logger.error(e); - }); + }); + + }, + + refreshTrainAndWeather: function () { + this.refreshTrain(); + this.refreshWeather(); + }, + preLoadToday: function () { + module.exports.getTodayDate(); + todayCache.data.cal = {today: [], tomorrow: [], week: []}; + weather.newDoGetWeather() + .then((d) => { + todayCache.data.weather = d; + }) + .catch((e) => { + logger.error(e); + }); + trains.updateTrains() + .then((d) => { + 'use strict'; + console.log('Trains: ', d); + todayCache.data.trains.data = d; + todayCache.data.trains.last = new Date(); + }) + .catch((e) => { + 'use strict'; + console.error(e); + }); + history.updateHistory() + .then((d) => { + 'use strict'; + console.log('History result: ', d); + todayCache.data.history = d; + }) + .catch((e) => { + 'use strict'; + console.error(e); + }); + + calHandler.getSimpleCalV3( + 'http://www.pogdesign.co.uk/cat/download_ics/60cfdff469d0490545d33d7e3b5c0bcc') + .then((d) => { + 'use strict'; + todayCache.data.tv = d; + }) + .catch((e) => { + 'use strict'; + logger.error(e); + }); + + todayFTSE.getFTSE() + .then((d) => { + todayCache.data.ftse = d; + }) + .catch((e) => { + logger.error(e); + }); + + quotes.GetQuotes() + .then((d) => { + todayCache.data.quotes = d; + }) + .catch((e) => { + logger.error(e); + }); + + + for (let t = 0; t < calHandler.calendars.length; t++) { + calHandler.getAdvancedCalV3(calHandler.calendars[t]) + .then((d) => { + 'use strict'; + todayCache.data.cal.today = todayCache.data.cal.today.concat(d.today); + todayCache.data.cal.tomorrow = todayCache.data.cal.tomorrow.concat(d.tomorrow); + todayCache.data.cal.week = todayCache.data.cal.week.concat(d.week); + }) + .catch((e) => { + 'use strict'; + logger.error(e); + }); + } + + swedishWord.getSwedishWord() + .then((d) => { + 'use strict'; + console.log('Swedish result: ', d); + todayCache.data.swedish = d; + }) + .catch((e) => { + 'use strict'; + console.error(e); + }); + + mdFitbit.getYesterdayFitbit() + .then((d) => { + todayCache.data.fitbit = d; + }) + .catch((e) => { + 'use strict'; + console.error(e); + }); + + todayCache.date = breakDay(); + }, broadcast: function () { + console.log('BROADCAST'); + broadcastWeather(); + eventEmitter.emit('sendSocket', {id: 'trains', data: todayCache.data.trains.data}); + } - - swedishWord.getSwedishWord() - .then((d) => { - 'use strict'; - console.log('Swedish result: ', d); - todayCache.data.swedish = d; - }) - .catch((e)=> { - 'use strict'; - console.error(e); - }); - - mdFitbit.getYesterdayFitbit() - .then((d) => { - todayCache.data.fitbit = d; - }) - .catch((e)=> { - 'use strict'; - console.error(e); - }); - - todayCache.date = breakDay(); - }, broadcast: function() { - console.log('BROADCAST'); - broadcastWeather(); - eventEmitter.emit('sendSocket', {id: 'trains', data: todayCache.data.trains.data}); - - } }; -setTimeout(function() { - loadData(); - if (runable()) { - module.exports.preLoadToday(); - } - //Module.exports.preLoadToday(); +setTimeout(function () { + loadData(); + if (runable()) { + module.exports.preLoadToday(); + } + //Module.exports.preLoadToday(); }, 5000); -setTimeout(function() { - // mdMailer.sendEmailV1(todayCache, __dirname); - // saveToDB(todayCache); - saveData(); +setTimeout(function () { + // mdMailer.sendEmailV1(todayCache, __dirname); + // saveToDB(todayCache); + saveData(); }, 45000); -setInterval(function() { +setInterval(function () { - // EventEmitter.emit('sendSocket',{id:'weather',data:todayCache.data.weather}); - // broadcastWeather(); - // eventEmitter.emit('sendSocket', {id: 'trains', data: todayCache.data.trains.data}); + // EventEmitter.emit('sendSocket',{id:'weather',data:todayCache.data.weather}); + // broadcastWeather(); + // eventEmitter.emit('sendSocket', {id: 'trains', data: todayCache.data.trains.data}); }, (60000)); -cron.schedule('30 6 * * *', function() { - if (runable()) { - module.exports.preLoadToday(); - } +cron.schedule('30 6 * * *', function () { + if (runable()) { + module.exports.preLoadToday(); + } - return -1; + return -1; }); -cron.schedule('0 */1 * * *', function() { - // Module.exports.refreshTrainAndWeather(); - // this.refreshTrain(); - module.exports.refreshWeather(); +cron.schedule('0 */1 * * *', function () { + // Module.exports.refreshTrainAndWeather(); + // this.refreshTrain(); + module.exports.refreshWeather(); - return -1; + return -1; }); -cron.schedule('*/15 * * * *', function() { - module.exports.refreshTrain(); +cron.schedule('*/15 * * * *', function () { + module.exports.refreshTrain(); - // Module.exports.refreshWeather(); + // Module.exports.refreshWeather(); - return -1; + return -1; }); -cron.schedule('45 6 * * *', function() { - mdMailer.sendEmailV1(todayCache, __dirname); - saveToDB(todayCache); - // Console.log('tick'); - return -1; +cron.schedule('45 6 * * *', function () { + mdMailer.sendEmailV1(todayCache, __dirname); + saveToDB(todayCache); + // Console.log('tick'); + return -1; }); diff --git a/lib/today/mailer.js b/lib/today/mailer.js index 873d848..4251349 100644 --- a/lib/today/mailer.js +++ b/lib/today/mailer.js @@ -5,7 +5,7 @@ * Time: 16:35 * */ -var jade = require('jade'), UltraSES = require('ultrases'), dateFormat = require('dateformat'); +var jade = require('pug'), UltraSES = require('ultrases'), dateFormat = require('dateformat'); var logger = require('log4js').getLogger(); diff --git a/lib/today/swedishword.js b/lib/today/swedishword.js index d2653aa..9ee4b80 100644 --- a/lib/today/swedishword.js +++ b/lib/today/swedishword.js @@ -1,30 +1,22 @@ /** * Created by Martin on 15/02/2016. */ -var http = require('http'), request = require('request'), util = require('util'); -var jsonfile = require('jsonfile'); -var log4js = require('log4js'); -var logger = log4js.getLogger(); -var to_json = require('xmljson').to_json; +let http = require('http'); +const request = require('request'); +let util = require('util'); +const logger = require('log4js').getLogger(); +const to_json = require('xmljson').to_json; require('sugar-date'); - -var file = __dirname + '/' + 'cal.json'; - -function saveData(v) { - jsonfile.writeFileSync(file, v); -} - module.exports = { getSwedishWord: function () { return new Promise(function(resolve, reject) { - "use strict"; - var t= new Date(), ms = t.getTime(); + const t = new Date(), ms = t.getTime(); - var url = ['http://wotd.transparent.com/rss/swedish-widget.xml?t=', ms].join(''); - logger.info(url); + const url = ['http://wotd.transparent.com/rss/swedish-widget.xml?t=', ms].join(''); + // logger.info(url); request(url, function (err, resp, body) { if (err) { return reject(err); diff --git a/lib/today/swedishword.spec.js b/lib/today/swedishword.spec.js new file mode 100644 index 0000000..b167191 --- /dev/null +++ b/lib/today/swedishword.spec.js @@ -0,0 +1,16 @@ +const swedishWord = require('./swedishword.js'); + +test('Test swedishword', () => { + return swedishWord.getSwedishWord() + .then((d) => { + + console.log('Swedish result: ', JSON.stringify(d)); + console.log(d.xml.words.language); + //expect(d.xml.words.language).toEqual('Swedish'); + }) + .catch((e)=> { + 'use strict'; + expect(e).toBeNull(); + }); + done(); +}); \ No newline at end of file diff --git a/lib/today/todayftse.js b/lib/today/todayftse.js index e93ab88..6a30b0b 100644 --- a/lib/today/todayftse.js +++ b/lib/today/todayftse.js @@ -5,8 +5,7 @@ * Time: 11:45 * */ -var ftse = require('ftse'); - +const ftse = require('ftse'); module.exports = { @@ -15,7 +14,7 @@ module.exports = { return new Promise(function(resolve, reject) { "use strict"; - var err = 0; + let err = 0; ftse('100', 10, 'risers', function(items) { if (items === err) { diff --git a/lib/today/trains.spec.js b/lib/today/trains.spec.js new file mode 100644 index 0000000..8414044 --- /dev/null +++ b/lib/today/trains.spec.js @@ -0,0 +1,13 @@ +const trains = require('./trains.js'); + +test('Test trains', () => { + return trains.updateTrains() + .then((d) => { + console.log('Trains: ', d); + expect(d).toBeDefined(); + }) + .catch((e)=> { + expect(e).toBeNull(); + }); + done(); +}); \ No newline at end of file diff --git a/lib/today/weather.js b/lib/today/weather.js index 17ebd39..e70e272 100644 --- a/lib/today/weather.js +++ b/lib/today/weather.js @@ -1,12 +1,12 @@ /** * Created by Martin on 31/03/2016. */ -var Forecast = require('forecast.io'); -var STRING = require('string'); -var logger = require('log4js').getLogger(); +const Forecast = require('forecast.io'); +const STRING = require('string'); +const logger = require('log4js').getLogger(); -var forecastOptions = { +const forecastOptions = { APIKey: '9ad2a41d420f3cf4960571bb886f710c', units: 'uk2' }; @@ -15,19 +15,17 @@ module.exports = { 'use strict'; return new Promise(function(resolve, reject) { logger.info('New Retrieving weather..'); - var j = {}; - var forecast = new Forecast(forecastOptions); + const j = {}; + const forecast = new Forecast(forecastOptions); forecast.get(55.95, -4.566667, {units: 'uk2'}, function(err, res, data) { if (err) { - // logger.error(err); return reject(err); - // throw err; } - var tempMin = parseInt(data.daily.data[0].temperatureMin); - var tempMax = parseInt(data.daily.data[0].temperatureMax); + const tempMin = parseInt(data.daily.data[0].temperatureMin); + const tempMax = parseInt(data.daily.data[0].temperatureMax); j.currently = data.currently.summary; j.today = data.daily.data[0].summary; @@ -35,8 +33,8 @@ module.exports = { j.alerts = data.alerts || {}; j.data = data; - var fs = STRING(j.currently).endsWith('.') ? '' : '.'; - if (tempMax == tempMin) { + const fs = STRING(j.currently).endsWith('.') ? '' : '.'; + if (tempMax === tempMin) { j.currently += fs + ' Around ' + tempMin.toString() + ' degrees.'; } else { diff --git a/lib/today/weather.spec.js b/lib/today/weather.spec.js new file mode 100644 index 0000000..1ef3bbc --- /dev/null +++ b/lib/today/weather.spec.js @@ -0,0 +1,13 @@ +const weather = require('./weather.js'); + +test('Test weather', () => { + return weather.newDoGetWeather() + .then((d) => { + expect(d.data.latitude).toEqual(55.95); + expect(d.data.longitude).toEqual(-4.566667); + }).catch((e) => { + console.error(e); + expect(e).toBeNull(); + }); + done(); +}); \ No newline at end of file diff --git a/lib/train.js b/lib/train.js index ed003e7..7a72418 100644 --- a/lib/train.js +++ b/lib/train.js @@ -1,31 +1,27 @@ // train.js -var http = require('http'); -var trainCache = { +const http = require('http'); +const logger = require('log4js').getLogger(); +let trainCache = { last: {}, data: {} }; module.exports = { - - - dbe_glq: function (req, res) { - console.log('DBE:GLQ request'); + logger.info('DBE:GLQ request'); - var now = new Date(); - var nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60); - console.log('Now Seconds: ' + nowSeconds); - if (trainCache.last.dbeglq == null || nowSeconds != trainCache.last.dbeglq) { + const now = new Date(); + const nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60); + + if (trainCache.last.dbeglq === null || nowSeconds !== trainCache.last.dbeglq) { Query(function (a, b) { - var ts = a.departures[0].service; - var output = {}; - console.log(ts); - - console.log(ts.sta); - + const ts = a.departures[0].service; + let output = {}; + logger.debug(ts); + logger.debug(ts.sta); output.sta = ts.sta; output.eta = ts.eta; trainCache.data.dbeglq = output; @@ -38,20 +34,20 @@ module.exports = { }, glq_dbe: function (req, res) { - console.log('GLQ:DBE request'); + logger.info('GLQ:DBE request'); - var now = new Date(); - var nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60); - console.log('Now Seconds: ' + nowSeconds); - if (trainCache.last.glqdbe == null || nowSeconds != trainCache.last.dbeglq) { + const now = new Date(); + const nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60); + + if (trainCache.last.glqdbe === null || nowSeconds !== trainCache.last.dbeglq) { Query(function (a, b) { - var ts = a.departures[0].service; - var output = {}; - console.log(ts); + const ts = a.departures[0].service; + const output = {}; + logger.debug(ts); //GLOBAL.lastcheck = now; - console.log(ts.sta); - console.log(toSeconds(ts.sta)); + logger.debug(ts.sta); + logger.debug(toSeconds(ts.sta)); output.sta = ts.sta; output.eta = ts.eta; @@ -66,11 +62,11 @@ module.exports = { }, getTrainTimes: function(req, res) { // console.log(req); - console.log('getTrainTimes: ' + JSON.stringify(req.query)); + logger.info('getTrainTimes: ' + JSON.stringify(req.query)); if (req.query.hasOwnProperty('from') && req.query.hasOwnProperty('from')) { - var url = '/all/' + req.query.from + '/to/' + req.query.to + '/10?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8'; + const url = '/all/' + req.query.from + '/to/' + req.query.to + '/10?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8'; Query(function (a, b) { res.setHeader('Content-Type', 'application/json'); @@ -84,8 +80,8 @@ module.exports = { }, getNextTrainTimes: function(req, res) { - console.log('getNextTrainTimes: ' + JSON.stringify(req.query)); - var trainFrom, trainTo, trainToken, url; + logger.info('getNextTrainTimes: ' + JSON.stringify(req.query)); + let trainFrom, trainTo, trainToken, url; if (req.query.hasOwnProperty('from') && req.query.hasOwnProperty('from')) { trainFrom = req.query.from; trainTo = req.query.to; @@ -93,21 +89,21 @@ module.exports = { url = '/next/' + trainFrom + '/to/' + trainTo + '/1?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8'; console.log('Requesting latest time for : ' + trainToken); - var now = new Date(); - var nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60); + const now = new Date(); + const nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60); console.log('Now Seconds: ' + nowSeconds); - if (trainCache.last[trainToken] == null || nowSeconds != trainCache.last[trainToken]) { + if (trainCache.last[trainToken] === null || nowSeconds !== trainCache.last[trainToken]) { Query(function (a, b) { - var output = {}; - var ts = a.departures[0].service; + const output = {}; + const ts = a.departures[0].service; if ( ts !== null) { // console.log(ts); //GLOBAL.lastcheck = now; - console.log(ts.sta); - console.log(toSeconds(ts.sta)); + logger.debug(ts.sta); + logger.debug(toSeconds(ts.sta)); output.sta = ts.sta; output.eta = (ts.eta !== null ? ts.eta : ts.sta); @@ -115,7 +111,7 @@ module.exports = { // console.log(ts); } else { - console.log('*** NO SERVICE'); + logger.warn('*** NO SERVICE'); output.sta = 'No Service'; output.eta = 'No Service'; } @@ -130,8 +126,9 @@ module.exports = { } }, getRoute: function(req, res) { - console.log('getRoute: ' + JSON.stringify(req.query)); - var routeID, data={}; + logger.info('getRoute: ' + JSON.stringify(req.query)); + let routeID; + const data = {}; if (req.query.hasOwnProperty('route')) { routeID = req.query.route; @@ -149,15 +146,15 @@ module.exports = { }; function toSeconds(inval) { - var a = inval.split(':'); + const a = inval.split(':'); return ((parseInt(a[0]) * (60 * 60)) + (parseInt(a[1]) * 60)); } function Query(callback, r, host, path) { - console.log(path); - var req = r; - var options = { + logger.debug(path); + const req = r; + const options = { host: host, // port: 80, path: path, @@ -167,7 +164,7 @@ function Query(callback, r, host, path) { try { http.request(options).on('response', function (response) { - var data = ''; + let data = ''; response.on("data", function (chunk) { data += chunk; }); diff --git a/lib/weather.js b/lib/weather.js index cba0cad..34dc0f9 100644 --- a/lib/weather.js +++ b/lib/weather.js @@ -1,18 +1,21 @@ /** * Created by marti on 14/02/2016. */ -var http = require('http'), request = require('request'), cheerio = require('cheerio'), Forecast = require('forecast.io'), util = require('util'), UltraSES = require('ultrases'), cron = require('node-cron'); -var jade = require('jade'), _ = require('lodash'), dateFormat = require('dateformat'); -var jsonfile = require('jsonfile'), fs = require('fs'); -var log4js = require('log4js'); -var logger = log4js.getLogger(); +const http = require('http'); +const request = require('request'); +const Forecast = require('forecast.io'); +const util = require('util'); +const jsonfile = require('jsonfile'); +const fs = require('fs'); +const logger = require('log4js').getLogger(); -var forecastOptions = { +const forecastOptions = { APIKey: '0657dc0d81c037cbc89ca88e383b6bbf', units: 'uk2' }; -var file = __dirname + '/' + 'data.json'; +const file = __dirname + '/' + 'data.json'; + function saveData(d) { jsonfile.writeFileSync(file, d); } @@ -20,21 +23,18 @@ function saveData(d) { module.exports = { doGetWeatherOutlook: function () { - console.log('Retrieving weather..'); - var j = {}; - var forecast = new Forecast(forecastOptions); - forecast.get(55.8582846, -4.2593033, {units: 'uk2'}, function (err, res, data) { + logger.info('Retrieving weather..'); + let j = {}; + let forecast = new Forecast(forecastOptions); + forecast.get(55.8582846, -4.2593033, {units: 'uk2'}, (err, res, data) => { if (err) throw err; -console.log(util.inspect(data)); + logger.debug(util.inspect(data)); saveData(data); j.currently = data.currently.summary; j.today = data.daily.data[0].summary; j.later = data.daily.summary; j.alerts = data.alerts || {}; - - // todayCache.data.weather = j; }); - } }; diff --git a/package.json b/package.json index fd094f4..1618cd8 100644 --- a/package.json +++ b/package.json @@ -2,13 +2,33 @@ "name": "silvrtree", "version": "0.1.1", "devDependencies": { + "babel": "^6.23.0", + "babel-core": "^6.24.0", + "babel-eslint": "^7.2.0", + "babel-preset-es2015": "^6.24.0", "cheerio": "^0.20.0", "dateformat": "^1.0.12", "ejs": "^2.3.4", "fitbit-oauth2": "0.0.1", "forecast.io": "0.0.9", + "gulp-autoprefixer": "^3.1.1", + "gulp-babel": "^6.1.2", + "gulp-cache": "^0.4.6", + "gulp-concat": "^2.6.1", + "gulp-cssnano": "^2.1.2", + "gulp-google-webfonts": "0.0.14", + "gulp-html-replace": "^1.6.2", + "gulp-htmlmin": "^3.0.0", + "gulp-jshint": "^2.0.4", + "gulp-rename": "^1.2.2", + "gulp-sass": "^3.1.0", + "gulp-scss": "^1.4.0", + "gulp-strip-debug": "^1.1.0", + "gulp-uglify": "^2.1.2", "htmlparser": "^1.7.7", "jade": "^1.11.0", + "jest": "^19.0.2", + "jshint": "^2.9.4", "jsonfile": "^2.3.0", "lodash": "^4.11.2", "log4js": "^0.6.35", @@ -31,12 +51,14 @@ "express": "^4.13.4", "express-session": "^1.13.0", "ftse": "^1.0.6", + "gulp": "^3.9.1", "ical2json": "^0.2.0", "logger": "0.0.1", "method-override": "^2.3.5", "morgan": "^1.7.0", "nano": "^6.2.0", "node-cron": "^1.0.0", + "pug": "^2.0.0-beta11", "scrape": "^0.2.3", "string": "^3.3.1", "sugar-date": "^1.5.1", @@ -47,5 +69,8 @@ "scripts": { "start": "node web-server.js", "copy": "sudo cp -r ./. /var/www/silvrtree" + }, + "jest": { + "verbose": true } } diff --git a/serverV2.js b/serverV2.js new file mode 100644 index 0000000..7da58d9 --- /dev/null +++ b/serverV2.js @@ -0,0 +1,201 @@ +const express = require('express'); +const path = require('path'); +const server = require('http').createServer(); + +const fx = require('./lib/fx'); +const btc = require('./lib/btc'); +const train = require('./lib/train'); +const password = require('./lib/password'); +const clean = require('./lib/clean'); +const events = require('./lib/events'); + +const morgan = require('morgan'); +const cookieParser = require('cookie-parser'); +const session = require('express-session'); + +const methodoverride = require('method-override'); +const bodyparser = require('body-parser'); +const errorhandler = require('errorhandler'); + +const jsonfile = require('jsonfile'); + +const Events = require('events'); +let busEmitter = new Events.EventEmitter(); + + + +const WebSocketServer = require('ws').Server; +const wss = new WebSocketServer({server: server}); + +const SocketHandler = require('./lib/wshandlerv2'); + +let webSocket = new SocketHandler(busEmitter, wss); + + + + // train = require('lib/train') +/* ,submit = require('./routes/mongo/submit') */ +; + +let fs = require('fs'); +const config = require('./config/config.json'); +const Fitbit = require('fitbit-oauth2'); + +const polys = require('./lib/poly.js'); + +const logger = require('log4js').getLogger(); +const app = express(); +GLOBAL.lastcheck = 0; +let btcCache = {}, fxCache = {}, trainCache = {}; + +const port = process.env.PORT || 9010; + + +// 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 +})); + /* 'default', 'short', 'tiny', 'dev' */ +app.use(methodoverride()); + +app.use(bodyparser.urlencoded({extended: false})); + +// parse application/json +app.use(bodyparser.json()); + +app.use(function(req, res, next) { + res.header('Access-Control-Allow-Origin', '*'); + res.header('Access-Control-Allow-Headers', 'X-Requested-With'); + next(); +}); + // app.use(app.router); +app.use(express.static(path.join(__dirname, 'app'))); + +app.use(errorhandler({dumpExceptions: true, showStack: true})); + +app.use('/btc', btc.doBTC); + +app.use('/fx', fx.doFx); + +app.use('/dbeglq', train.dbe_glq); +app.use('/glqdbe', train.glq_dbe); +app.use('/gettrains', train.getTrainTimes); +app.use('/getnexttraintimes', train.getNextTrainTimes); +app.use('/getroute', train.getRoute); + +app.use('/generate', password.generate); + +app.use('/cleanit', clean.cleanit); + + + +app.use('/events', events.getEvents); +app.get('/cinema/:id', events.getCinema); + + +app.route('/poly').get(polys); + + +/*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) { + if (err) { + return console.error('could not connect to postgres', err); + } + client.query(q, function(err, result) { + if (err) { + return console.error('error running query', err); + } + console.log(result.rows[0].theTime); + // output: Tue Jan 15 2013 19:12:47 GMT-600 (CST) + client.end(); + }); + }); +});*/ + +app.get('/slack', function(req, res) { + res.render('pages/slackV2'); +}); + +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. +// +app.get('/fitbit', function(req, res) { + res.redirect(fitbit.authorizeURL()); +}); + +// Callback service parsing the authorization token and asking for the access token. This +// endpoint is refered to in config.fitbit.authorization_uri.redirect_uri. See example +// config below. +// +app.get('/fitbit_auth_callback', function(req, res, next) { + const code = req.query.code; + fitbit.fetchToken(code, function(err, token) { + if (err) { + return next(err); + } + + // persist the token + jsonfile.writeFile(tfile, token, function(err) { + if (err) { + return next(err); + } + 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); + } +}); + + +// }); + +/** + * create the server + */ +/* +http.createServer(app).listen(app.get('port'), function () { + logger.warn("Express server listening on port " + app.get('port')); + //console.log("Express server listening on port " + app.get('port')); +}); +*/ + + + +server.on('request', app); +server.listen(port, () => { logger.info('New server listening on ' + server.address().port); }); + diff --git a/views/pages/slackV2.ejs b/views/pages/slackV2.ejs new file mode 100644 index 0000000..a936463 --- /dev/null +++ b/views/pages/slackV2.ejs @@ -0,0 +1,380 @@ +<% include ../partials/head %> + + +
+
+
+
+
+
+
+
+
+ +
+ +
+ + + + + +
+ + + + +
+
Travel
+ + DBEGLQ: GLQDBE: + + +
+ +
+ + + +
+
+
Computer Software, etc.
+ +
+ +
+
Reference & Special sites
+ + +
+ + +
+ + +
+ +
+
+ + + + + + + + + + diff --git a/views/partials/head.ejs b/views/partials/head.ejs index 02b457f..6d07bb3 100644 --- a/views/partials/head.ejs +++ b/views/partials/head.ejs @@ -7,12 +7,13 @@ Events - + - + - + + diff --git a/web-server.js b/web-server.js index f6a6340..5cb73a6 100644 --- a/web-server.js +++ b/web-server.js @@ -1,186 +1,192 @@ -var express = require('express'), path = require('path'), server = require('http').createServer(); +const express = require('express'); +const path = require('path'); +const server = require('http').createServer(); -var fx = require('./lib/fx'), btc = require('./lib/btc'), train = require('./lib/train'), - password = require('./lib/password') , clean = require('./lib/clean'), events = require('./lib/events'), - today = require('./lib/today'), - morgan = require('morgan'), cookieParser = require('cookie-parser'),session = require('express-session') - methodoverride = require('method-override'), bodyparser = require('body-parser'), errorhandler = require('errorhandler'); +const fx = require('./lib/fx'); +const btc = require('./lib/btc'); +const train = require('./lib/train'); +const password = require('./lib/password'); +const clean = require('./lib/clean'); +const events = require('./lib/events'); +const today = require('./lib/today'); +const morgan = require('morgan'); +const cookieParser = require('cookie-parser'); +const session = require('express-session'); -var jsonfile = require('jsonfile'); +const methodoverride = require('method-override'); +const bodyparser = require('body-parser'); +const errorhandler = require('errorhandler'); -var Events = require('events'); -var busEmitter = new Events.EventEmitter(); +const jsonfile = require('jsonfile'); + +const Events = require('events'); +let busEmitter = new Events.EventEmitter(); busEmitter.on('update', today.broadcast); -var WebSocketServer = require('ws').Server; -var wss = new WebSocketServer({ server: server }); +const WebSocketServer = require('ws').Server; +const wss = new WebSocketServer({server: server}); -var SocketHandler = require('./lib/wshandlerv2'); - -var webSocket = new SocketHandler(busEmitter, wss); +const SocketHandler = require('./lib/wshandlerv2'); +let webSocket = new SocketHandler(busEmitter, wss); today.setEmitter(busEmitter); - //train = require('lib/train') + // train = require('lib/train') /* ,submit = require('./routes/mongo/submit') */ - ; +; -var fs = require('fs'); -var config = require('./config/config.json'); -var Fitbit = require('fitbit-oauth2'); +let fs = require('fs'); +const config = require('./config/config.json'); +const Fitbit = require('fitbit-oauth2'); -var polys = require('./lib/poly.js'); +const polys = require('./lib/poly.js'); -var logger = require('log4js').getLogger(); -var app = express(); +const logger = require('log4js').getLogger(); +const app = express(); GLOBAL.lastcheck = 0; -var btcCache = {}, fxCache = {} , trainCache = {}; +let btcCache = {}, fxCache = {}, trainCache = {}; -var port = process.env.PORT || 9000; +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.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: '1234567890QWERTY', resave: false, - saveUninitialized: false + secret: 'd2jRT6ZpYFsXsF3kGS21ZszKbPAaEa', resave: false, + saveUninitialized: false })); /* 'default', 'short', 'tiny', 'dev' */ - app.use(methodoverride()); +app.use(methodoverride()); app.use(bodyparser.urlencoded({extended: false})); // parse application/json app.use(bodyparser.json()); - app.use(function (req, res, next) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "X-Requested-With"); - next(); - }); +app.use(function(req, res, next) { + res.header('Access-Control-Allow-Origin', '*'); + res.header('Access-Control-Allow-Headers', 'X-Requested-With'); + next(); +}); // app.use(app.router); - app.use(express.static(path.join(__dirname, 'app'))); +app.use(express.static(path.join(__dirname, 'app'))); app.use(errorhandler({dumpExceptions: true, showStack: true})); app.use('/btc', btc.doBTC); - app.use('/fx', fx.doFx); +app.use('/fx', fx.doFx); - app.use('/dbeglq', train.dbe_glq); - app.use('/glqdbe', train.glq_dbe); - app.use('/gettrains', train.getTrainTimes); - app.use('/getnexttraintimes', train.getNextTrainTimes); - app.use('/getroute', train.getRoute); +app.use('/dbeglq', train.dbe_glq); +app.use('/glqdbe', train.glq_dbe); +app.use('/gettrains', train.getTrainTimes); +app.use('/getnexttraintimes', train.getNextTrainTimes); +app.use('/getroute', train.getRoute); - app.use('/generate', password.generate); +app.use('/generate', password.generate); - app.use('/cleanit', clean.cleanit); +app.use('/cleanit', clean.cleanit); - app.use('/events', events.getEvents); - app.get('/cinema/:id', events.getCinema); +app.use('/events', events.getEvents); +app.get('/cinema/:id', events.getCinema); - app.get('/today', today.getToday); - app.get('/today/data', today.getData); +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) { - var pg = require('pg'); +/*app.use('/lot', function(req, res) { + const pg = require('pg'); - var conString = "postgres://pguser:1V3D4m526i@localhost/silver"; - console.log(conString); + const conString = 'postgres://pguser:1V3D4m526i@localhost/silver'; + console.log(conString); - var client = new pg.Client(conString); - var q = 'select * from lot order by d desc'; - client.connect(function(err) { - if(err) { - return console.error('could not connect to postgres', err); - } - client.query(q, function(err, result) { - if(err) { - return console.error('error running query', err); - } - console.log(result.rows[0].theTime); - //output: Tue Jan 15 2013 19:12:47 GMT-600 (CST) - client.end(); - }); - }); + const client = new pg.Client(conString); + const q = 'select * from lot order by d desc'; + client.connect(function(err) { + if (err) { + return console.error('could not connect to postgres', err); + } + client.query(q, function(err, result) { + if (err) { + return console.error('error running query', err); + } + console.log(result.rows[0].theTime); + // output: Tue Jan 15 2013 19:12:47 GMT-600 (CST) + client.end(); }); + }); +});*/ - app.get('/slack', function (req, res) { - res.render('pages/slack'); - }); +app.get('/slack', function(req, res) { + res.render('pages/slack'); +}); - app.get('/temp', function (req, res) { - res.render('pages/temp'); - }); +app.get('/temp', function(req, res) { + res.render('pages/temp'); +}); -var tfile = 'fb-token.json'; +const tfile = 'fb-token.json'; // Instanciate a fitbit client. See example config below. // -var fitbit = new Fitbit( config.fitbit); +const fitbit = new Fitbit(config.fitbit); // In a browser, http://localhost:4000/fitbit to authorize a user for the first time. // -app.get('/fitbit', function (req, res) { - res.redirect( fitbit.authorizeURL() ); +app.get('/fitbit', function(req, res) { + res.redirect(fitbit.authorizeURL()); }); // Callback service parsing the authorization token and asking for the access token. This // endpoint is refered to in config.fitbit.authorization_uri.redirect_uri. See example // config below. // -app.get('/fitbit_auth_callback', function (req, res, next) { - var code = req.query.code; - fitbit.fetchToken( code, function( err, token ) { - if ( err ) { - return next( err ); - } +app.get('/fitbit_auth_callback', function(req, res, next) { + const code = req.query.code; + fitbit.fetchToken(code, function(err, token) { + if (err) { + return next(err); + } // persist the token - jsonfile.writeFile( tfile, token, function( err ) { - if ( err ) { - return next( err ); - } - console.log("!!!! Fitbit token saved"); - res.redirect( '/fb-profile' ); + jsonfile.writeFile(tfile, token, function(err) { + if (err) { + return next(err); + } + 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); - - } - }); + if (err) { + logger.error(err); + } else { + fitbit.setToken(obj); + } +}); -//}); +// }); /** * create the server @@ -195,5 +201,5 @@ http.createServer(app).listen(app.get('port'), function () { server.on('request', app); -server.listen(port, function() { logger.info('New server listening on ' + server.address().port); }); +server.listen(port, () => { logger.info('New server listening on ' + server.address().port); });