new weather, fixes for minified version

This commit is contained in:
Martin Donnelly 2017-09-28 00:17:07 +01:00
parent 786237a5c8
commit c392de700f
21 changed files with 1084 additions and 1598 deletions

24
app.js
View File

@ -1,38 +1,36 @@
/*var app = require('express').createServer(); /* var app = require('express').createServer();
app.get('/', function(req, res) { app.get('/', function(req, res) {
res.send('Hello from <a href="http://appfog.com">AppFog.com</a>'); res.send('Hello from <a href="http://appfog.com">AppFog.com</a>');
}); });
app.listen(process.env.VCAP_APP_PORT || 3000);*/ app.listen(process.env.VCAP_APP_PORT || 3000);*/
var express = require('express'), path = require('path'), http = require('http');
var express = require('express'), path = require('path'), http = require('http');
var app = express(); var app = express();
app.configure(function() { app.configure(function() {
app.set('port', process.env.VCAP_APP_PORT || 3000); app.set('port', process.env.VCAP_APP_PORT || 3000);
app.use(express.logger('dev')); app.use(express.logger('dev'));
/* 'default', 'short', 'tiny', 'dev' */ /* 'default', 'short', 'tiny', 'dev' */
app.use(express.methodOverride()); app.use(express.methodOverride());
app.use(express.bodyParser()); app.use(express.bodyParser());
app.use(function(req, res, next) { app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); res.header('Access-Control-Allow-Origin', '*');
res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header('Access-Control-Allow-Headers', 'X-Requested-With');
next(); next();
}); });
app.use(app.router); app.use(app.router);
app.use(express.static(path.join(__dirname, 'www'))); app.use(express.static(path.join(__dirname, 'www')));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); app.use(express.errorHandler({ 'dumpExceptions': true, 'showStack': true }));
}); });
/** /**
* Routing handlers * Routing handlers
*/ */
/** /**
* create the server * create the server
*/ */
http.createServer(app).listen(app.get('port'), function() { http.createServer(app).listen(app.get('port'), function() {
console.log("Express server listening on port " + app.get('port')); console.log(`Express server listening on port ${ app.get('port')}`);
}); });

82
app/css/weather.css Normal file
View File

@ -0,0 +1,82 @@
.card {
position: relative;
background-color: #fff;
min-height: 72px;
}
.mui--text-display3 {
font-family: "Roboto Slab", "Helvetica Neue", Helvetica, Arial;
}
.temp0, .temp1, .temp2, .temp3, .temp4, .temp5 {
color: rgb(80, 181, 221)
}
.temp6 {
color: rgb(78, 178, 206)
}
.temp7 {
color: rgb(76, 176, 190)
}
.temp8 {
color: rgb(73, 173, 175)
}
.temp9 {
color: rgb(72, 171, 159)
}
.temp10 {
color: rgb(70, 168, 142)
}
.temp11 {
color: rgb(68, 166, 125)
}
.temp12 {
color: rgb(66, 164, 108)
}
.temp13 {
color: rgb(102, 173, 94)
}
.temp14 {
color: rgb(135, 190, 64)
}
.temp15 {
color: rgb(179, 204, 26)
}
.temp16 {
color: rgb(214, 213, 28)
}
.temp17 {
color: rgb(249, 202, 3)
}
.temp18 {
color: rgb(246, 181, 3)
}
.temp19 {
color: rgb(244, 150, 26)
}
.temp20 {
color: rgb(236, 110, 5)
}
.day {
font-family: "Roboto Slab", "Helvetica Neue", Helvetica, Arial, SansSerif;
text-transform: uppercase;
}
.summary::first-letter {
text-transform: capitalize
}

View File

@ -22,7 +22,7 @@ const BitcoinModel = Backbone.Model.extend({
}, },
'update': function () { 'update': function () {
this.getBTC(); this.getBTC();
// this.getBalance(); // this.getBalance();
const now = new Date(); const now = new Date();
const mod = 300000 - (now.getTime() % 300000); const mod = 300000 - (now.getTime() % 300000);
@ -94,7 +94,7 @@ const BitcoinModel = Backbone.Model.extend({
data.stub = Math.random(Number.MAX_SAFE_INTEGER).toString(32); data.stub = Math.random(Number.MAX_SAFE_INTEGER).toString(32);
this.set('btcdata', data); this.set('btcdata', data);
// total = myBTC * g; // total = myBTC * g;
}, },
'getBTC': function () { 'getBTC': function () {
console.log('>> getBTC'); console.log('>> getBTC');
@ -106,7 +106,7 @@ const BitcoinModel = Backbone.Model.extend({
'data': '', 'data': '',
'dataType': 'json', 'dataType': 'json',
'timeout': 10000, 'timeout': 10000,
// contentType: ('application/json'), // contentType: ('application/json'),
'headers': { 'headers': {
'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
@ -139,7 +139,7 @@ const BitcoinModel = Backbone.Model.extend({
'data': '', 'data': '',
'dataType': 'json', 'dataType': 'json',
'timeout': 10000, 'timeout': 10000,
// contentType: ('application/json'), // contentType: ('application/json'),
'headers': { 'headers': {
'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
@ -159,7 +159,7 @@ const BitcoinModel = Backbone.Model.extend({
}); });
}, },
'btcFromSocket': function (data) { 'btcFromSocket': function (data) {
let self = this; const self = this;
console.log('>> btc from the socket', data); console.log('>> btc from the socket', data);
const gbp = data.bpi.GBP.rate_float; const gbp = data.bpi.GBP.rate_float;
const usd = data.bpi.USD.rate_float; const usd = data.bpi.USD.rate_float;
@ -172,7 +172,7 @@ const BitcoinModel = Backbone.Model.extend({
self.recalc(); self.recalc();
}, },
'balanceFromSocket': function (data) { 'balanceFromSocket': function (data) {
let self = this; const self = this;
console.log('>> balance from the socket', data); console.log('>> balance from the socket', data);
const balance = data.balance; const balance = data.balance;
@ -191,10 +191,10 @@ const Bitcoin = Backbone.View.extend({
'render': function () { 'render': function () {
const btcdata = this.model.get('btcdata'); const btcdata = this.model.get('btcdata');
const balance = this.model.get('balance'); const balance = this.model.get('balance');
// console.log(`Balance: ${btcdata.balance.toFixed(4)}`); // console.log(`Balance: ${btcdata.balance.toFixed(4)}`);
// console.log(btcdata.lastGBP); // console.log(btcdata.lastGBP);
const owned = parseFloat(btcdata.lastGBP) * parseFloat(balance); const owned = parseFloat(btcdata.lastGBP) * parseFloat(balance);
// console.log(`owned: ${owned}`); // console.log(`owned: ${owned}`);
const title = `High: $${ parseFloat(btcdata.highs.usd.toFixed(2)) } / Low $${ parseFloat(btcdata.lows.usd.toFixed(2))}`; const title = `High: $${ parseFloat(btcdata.highs.usd.toFixed(2)) } / Low $${ parseFloat(btcdata.lows.usd.toFixed(2))}`;
let trendClass = ''; let trendClass = '';
@ -203,7 +203,7 @@ const Bitcoin = Backbone.View.extend({
else if (btcdata.trend < 1.00) else if (btcdata.trend < 1.00)
trendClass = 'trendDown'; trendClass = 'trendDown';
else else
trendClass = ''; trendClass = '';
this.$trend.removeClass(); this.$trend.removeClass();
this.$trend.addClass(trendClass); this.$trend.addClass(trendClass);

View File

@ -10,9 +10,9 @@ const TrainModel = Backbone.Model.extend({
'initialize': function () { 'initialize': function () {
const fromStation = this.get('from'); const fromStation = this.get('from');
const toStation = this.get('to'); const toStation = this.get('to');
const url = `/getnexttraintimes?from=${ fromStation }&to=${ toStation}`; const url = `/getnexttraintimes?from=${ this.get('from') }&to=${ this.get('to')}`;
const routeUrl = `/gettrains?from=${ fromStation }&to=${ toStation}`; const routeUrl = `/gettrains?from=${ this.get('from') }&to=${ this.get('to')}`;
const target = fromStation + toStation; const target = this.get('from') + this.get('to');
this.set('url', url); this.set('url', url);
this.set('routeUrl', routeUrl); this.set('routeUrl', routeUrl);
this.set('target', target); this.set('target', target);
@ -30,7 +30,7 @@ const TrainModel = Backbone.Model.extend({
if (hours >= 6) if (hours >= 6)
this.getTrain(); this.getTrain();
else else
this.set('trainData', { 'eta':'OFF', 'sta': 'OFF' }); this.set('trainData', { 'eta':'OFF', 'sta': 'OFF' });
const trainUpdateFn = function () { const trainUpdateFn = function () {
this.update(); this.update();
@ -69,32 +69,32 @@ const TrainModel = Backbone.Model.extend({
if (this.get('visible') === true) if (this.get('visible') === true)
this.set('visible', false); this.set('visible', false);
else else
$.ajax({ $.ajax({
'type': 'GET', 'type': 'GET',
'url': url, 'url': url,
'data': '', 'data': '',
'dataType': 'json', 'dataType': 'json',
'timeout': 10000, 'timeout': 10000,
'headers': { 'headers': {
'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type' 'Access-Control-Allow-Headers': 'Content-Type'
}, },
'success': function (data) { 'success': function (data) {
// getTrainsCB(data); // getTrainsCB(data);
// console.log('Got', data); // console.log('Got', data);
self.set('route', data); self.set('route', data);
self.set('visible', true); self.set('visible', true);
}, },
'error': function (xhr, type) { 'error': function (xhr, type) {
console.error('ajax error'); console.error('ajax error');
console.error(xhr); console.error(xhr);
console.error(type); console.error(type);
} }
}); });
} }
}); });
@ -161,8 +161,8 @@ const TrainView = Backbone.View.extend({
const time = item.sta !== null ? item.sta : `D ${item.std}`; const time = item.sta !== null ? item.sta : `D ${item.std}`;
const status = item.eta !== null ? item.eta : item.etd; const status = item.eta !== null ? item.eta : item.etd;
services.push({ 'location':dest.locationName, 'time':time, 'status':status, 'platform':platform, 'cancel':item.cancelReason, 'type':'bus' }); services.push({ 'location':dest.locationName, 'time':time, 'status':status, 'platform':platform, 'cancel':item.cancelReason, 'type':'bus' });
// ws = ws + `<div class="mui-row"><div class="mui-col-md-12"><strong>${dest.locationName} Bus</strong> ${via}</div></div>`; // ws = ws + `<div class="mui-row"><div class="mui-col-md-12"><strong>${dest.locationName} Bus</strong> ${via}</div></div>`;
// ws = ws + '<div class="mui-row"><div class="mui-col-md-12">' + item.sta + '</div></div>'; // ws = ws + '<div class="mui-row"><div class="mui-col-md-12">' + item.sta + '</div></div>';
ws = `${ws }<tr><td>🚌 ${dest.locationName} ${via}</td><td>${time}</td><td>${status}</td><td>${platform}</td></tr>`; ws = `${ws }<tr><td>🚌 ${dest.locationName} ${via}</td><td>${time}</td><td>${status}</td><td>${platform}</td></tr>`;
} }
@ -171,21 +171,21 @@ const TrainView = Backbone.View.extend({
this.$traintext.removeClass('mui--hide').addClass('mui--show'); this.$traintext.removeClass('mui--hide').addClass('mui--show');
} }
else else
this.$traintext.removeClass('mui--show').addClass('mui--hide'); this.$traintext.removeClass('mui--show').addClass('mui--hide');
}, },
'initView': function () { 'initView': function () {
// el: $('#myView').get(0) // el: $('#myView').get(0)
const self = this; const self = this;
const target = this.model.get('target'); const target = this.model.get('target');
const html = `<div class='mui-col-xs-12 mui-col-md-6'>${target.toUpperCase()}: <button class="mui-btn mui-btn--flat" id="${target}"></button></div>`; const html = `<div class='mui-col-xs-12 mui-col-md-6'>${target.toUpperCase()}: <button class="mui-btn mui-btn--flat" id="${target}"></button></div>`;
this.$html = $(html); this.$html = $(html);
this.$html.on('click', function () { this.$html.on('click', function () {
// console.log(self) // console.log(self)
self.model.getRoute(); self.model.getRoute();
}); });
this.$trains.append(this.$html); this.$trains.append(this.$html);
// this.el = `#${target}`; // this.el = `#${target}`;
this.$button = $(`#${target}`); this.$button = $(`#${target}`);

View File

@ -0,0 +1,80 @@
function reduceOpenWeather(item) {
// Openweather returns timestamps in seconds. Moment requires them in milliseconds.
const ts = moment(item.dt * 1000);
const weatherBlock = item.weather[0];
return {
'timestamp': item.dt,
'icon': `wi-owm-${weatherBlock.id}`,
'summary': weatherBlock.description,
'tempHigh': parseInt(item.temp.max, 10),
'tempLow': parseInt(item.temp.min, 10),
'datelong': ts.format(),
'time': item.dt,
'date': ts.format('D/M'),
'day': ts.format('ddd')
};
}
function reduceDarkSky(item) {
const ts = moment(item.time * 1000);
return {
'timestamp': item.time,
'icon': weatherIcons.get(item.icon),
'summary': item.summary,
'tempHigh': parseInt(item.temperatureHigh, 10),
'tempLow': parseInt(item.temperatureLow, 10),
'datelong': ts.format(),
'time': item.time,
'date': ts.format('D/M'),
'day': ts.format('ddd')
};
}
const WCollection = Backbone.Collection.extend({
'url': '/weather',
'parse': function(data) {
return data.list.map((item) => {
// Reduce the data
return reduceOpenWeather(item);
});
}
});
const WView = Backbone.View.extend({
'tagName': 'div',
'template': _.template(`
<% _.each(data, function(item) {%>
<div class="card mui--z1 mui-col-md-6 mui-col-lg-4">
<div class="mui-col-md-3">
<div class="mui--text-accent mui--text-title day mui--text-center"><%= item.day %></div>
<div class="mui--text-dark-secondary mui--text-subhead mui--text-center"><%= item.date %></div>
</div>
<div class="mui-col-md-9">
<div>
<i class="mui--text-headline wi <%= item.icon %>"></i>
<span class="mui--text-display1 temp<%=item.tempHigh %>"><%= item.tempHigh %>°</span> /
<span class="mui--text-headline temp<%=item.tempLow %>"><%= item.tempLow %>°</span></div>
<div class="mui--text-caption summary"><%= item.summary %></div>
</div>
</div>
<% });
%>`),
'initialize': function() {
_.bindAll(this, 'render');
this.collection = new WCollection();
this.listenTo(this.collection, 'reset sync', _.debounce(_.bind(this.render), 128));
this.collection.fetch();
},
'render': function() {
if (this.collection.length !== 0) {
const data = { 'data':this.collection.toJSON() };
this.$el.html(this.template(data));
}
}
});

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -18,6 +18,9 @@
"dependencies": { "dependencies": {
"moment": "^2.18.1", "moment": "^2.18.1",
"mui": "^0.9.21", "mui": "^0.9.21",
"float": "^1.0.2" "float": "^1.0.2",
"zepto": "^1.2.0",
"backbone": "^1.3.3",
"ejs": "^1.0.0"
} }
} }

View File

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

File diff suppressed because one or more lines are too long

View File

@ -8,8 +8,8 @@ const util = require('util');
const cron = require('node-cron'); const cron = require('node-cron');
const dateFormat = require('dateformat'); const dateFormat = require('dateformat');
const jsonfile = require('jsonfile'); const jsonfile = require('jsonfile');
let fs = require('fs'); const fs = require('fs');
//var nano = require('nano')('http://martind2000:1V3D4m526i@localhost:5984'); // var nano = require('nano')('http://martind2000:1V3D4m526i@localhost:5984');
const logger = require('log4js').getLogger(); const logger = require('log4js').getLogger();
const calHandler = require('./today/calHandler'); const calHandler = require('./today/calHandler');
const swedishWord = require('./today/swedishword'); const swedishWord = require('./today/swedishword');
@ -20,8 +20,10 @@ const mdMailer = require('./today/mailer');
const mdFitbit = require('./today/fitbit'); const mdFitbit = require('./today/fitbit');
const todayFTSE = require('./today/todayftse'); const todayFTSE = require('./today/todayftse');
const quotes = require('./today/quotes'); const quotes = require('./today/quotes');
//var db_name = 'silvrgit';
//var dbCloudant = nano.use(db_name); // const Sugar = require('sugar-date');
// var db_name = 'silvrgit';
// var dbCloudant = nano.use(db_name);
/* /*
@ -29,153 +31,155 @@ const quotes = require('./today/quotes');
https://25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix.cloudant.com/dashboard.html#usage https://25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix.cloudant.com/dashboard.html#usage
*/ */
logger.level = 'debug';
const credentials = { const credentials = {
"username": "25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix", 'username': '25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix',
"password": "8e417af1b0462ca55726848846cc6b8696fc76defe9d1864cbc334be59549e0c", 'password': '8e417af1b0462ca55726848846cc6b8696fc76defe9d1864cbc334be59549e0c',
"host": "25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix.cloudant.com", 'host': '25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix.cloudant.com',
"port": 443, 'port': 443,
"url": "https://25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix:8e417af1b0462ca55726848846cc6b8696fc76defe9d1864cbc334be59549e0c@25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix.cloudant.com", 'url': 'https://25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix:8e417af1b0462ca55726848846cc6b8696fc76defe9d1864cbc334be59549e0c@25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix.cloudant.com',
"database": "today" 'database': 'today'
}; };
const Cloudant = require('cloudant'); const Cloudant = require('cloudant');
const cloudant = Cloudant({account: credentials.username, password: credentials.password}); const cloudant = Cloudant({ 'account': credentials.username, 'password': credentials.password });
const dbCloudant = cloudant.db.use(credentials.database); const dbCloudant = cloudant.db.use(credentials.database);
let Sugar = require('sugar');
require('sugar-date');
String.prototype.hashCode = function () { String.prototype.hashCode = function () {
if (Array.prototype.reduce)
if (Array.prototype.reduce) { return this.split('').reduce(function (a, b) {
return this.split('').reduce(function (a, b) { a = ((a << 5) - a) + b.charCodeAt(0);
a = ((a << 5) - a) + b.charCodeAt(0);
return a & a return a & a;
}, 0); }, 0);
} else { else {
let hash = 0, i, chr, len;
let hash = 0, i, chr, len; if (this.length === 0) return hash;
if (this.length === 0) return hash; for (i = 0, len = this.length; i < len; i++) {
for (i = 0, len = this.length; i < len; i++) { chr = this.charCodeAt(i);
chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr;
hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer
hash |= 0; // Convert to 32bit integer
}
return hash;
} }
return hash;
}
}; };
let todayCache = { let todayCache = {
last: 0, data: { 'last': 0, 'data': {
trains: {last: 0, data: []}, 'trains': { 'last': 0, 'data': [] },
weather: {}, 'weather': {},
history: [], 'history': [],
today: '', 'today': '',
tv: {entries: []}, 'tv': { 'entries': [] },
cal: {today: [], tomorrow: [], week: []}, 'cal': { 'today': [], 'tomorrow': [], 'week': [] },
swedish: {}, 'swedish': {},
fitbit: {}, 'fitbit': {},
ftse: {} 'ftse': {}
}, expire: ((60 * 1000) * 60) }, 'expire': ((60 * 1000) * 60)
}; };
const file = __dirname + '/' + 'newdata.json'; const file = `${__dirname }/` + 'newdata.json';
let htmlfile = __dirname + '/' + 'today.html'; const htmlfile = `${__dirname }/` + 'today.html';
let eventEmitter; let eventEmitter;
function runable() { function runable() {
try { try {
const now = new Date().getTime(); const now = new Date().getTime();
console.log('last updated', ((now - todayCache.last) / 60000)); console.log('last updated', ((now - todayCache.last) / 60000));
if (now - todayCache.last < 3600000) { if (now - todayCache.last < 3600000)
return false; return false;
} else { else {
todayCache.last = now; todayCache.last = now;
return true;
} return true;
} }
catch (e) { }
todayCache.last = new Date().getTime(); catch (e) {
return true; todayCache.last = new Date().getTime();
} return true;
}
} }
function broadcastWeather() { function broadcastWeather() {
const wData = { const wData = {
temperature: todayCache.data.weather.data.currently.temperature, 'temperature': todayCache.data.weather.data.currently.temperature,
icon: todayCache.data.weather.data.currently.icon, 'icon': todayCache.data.weather.data.currently.icon,
summary: todayCache.data.weather.data.currently.summary 'summary': todayCache.data.weather.data.currently.summary
}; };
if (todayCache.data.weather.data.hasOwnProperty('alerts')) { if (todayCache.data.weather.data.hasOwnProperty('alerts'))
wData.alerts = todayCache.data.weather.data.alerts; wData.alerts = todayCache.data.weather.data.alerts;
}
eventEmitter.emit('sendSocket', {id: 'weather', data: wData}); eventEmitter.emit('sendSocket', { 'id': 'weather', 'data': wData });
} }
function loadData() { function loadData() {
console.log('Loading old data'); console.log('Loading old data');
try { try {
todayCache = jsonfile.readFileSync(file); todayCache = jsonfile.readFileSync(file);
} }
catch (e) { catch (e) {
console.error('Could not load previous data'); console.error('Could not load previous data');
} }
} }
function saveData() { function saveData() {
todayCache.last = new Date().getTime(); todayCache.last = new Date().getTime();
logger.info('Saving...'); logger.info('Saving...');
jsonfile.writeFileSync(file, todayCache); jsonfile.writeFileSync(file, todayCache);
} }
function saveToDB(data) { function saveToDB(data) {
saveData(); saveData();
logger.debug('Inserting into couch...'); logger.debug('Inserting into couch...');
// Logger.info(util.inspect(obj)); // Logger.info(util.inspect(obj));
dbCloudant.insert(data, function (err, body, header) { dbCloudant.insert(data, function (err, body, header) {
if (err) { if (err) {
logger.error('Error inserting into couch'); logger.error('Error inserting into couch');
logger.error(err); logger.error(err);
return;
} return;
}); }
});
} }
function nth(d) { function nth(d) {
// If (d > 3 && d < 21) {return 'th';} // Thanks kennebec // 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';} // 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; const n = d;
return Math.floor(n / 10) === 1 ? 'th' : (n % 10 === 1 ? 'st' : (n % 10 === 2 ? 'nd' : (n % 10 === 3 ? 'rd' : 'th')));
return Math.floor(n / 10) === 1 ? 'th' : (n % 10 === 1 ? 'st' : (n % 10 === 2 ? 'nd' : (n % 10 === 3 ? 'rd' : 'th')));
} }
function dayNumber() { function dayNumber() {
const now = new Date(); const now = new Date();
const start = new Date(now.getFullYear(), 0, 0); const start = new Date(now.getFullYear(), 0, 0);
const diff = now - start; const diff = now - start;
const oneDay = 1000 * 60 * 60 * 24; const oneDay = 1000 * 60 * 60 * 24;
return Math.floor(diff / oneDay);
return Math.floor(diff / oneDay);
} }
function breakDay() { function breakDay() {
const now = new Date(); const now = new Date();
return {
year: now.getFullYear(), return {
month: parseInt(now.getMonth()) + 1, 'year': now.getFullYear(),
day: now.getDate() 'month': parseInt(now.getMonth()) + 1,
}; 'day': now.getDate()
};
} }
function reduceTrains(d) { function reduceTrains(d) {
const titles = [], ta = [];
const titles = [], ta = []; // console.log('reducetrains',d);
// console.log('reducetrains',d); /* for (let items in d) {
/*for (let items in d) {
if (typeof d[items].title !== 'undefined') { if (typeof d[items].title !== 'undefined') {
const hash = d[items].title.hashCode(); const hash = d[items].title.hashCode();
if (titles.indexOf(hash) === -1) { if (titles.indexOf(hash) === -1) {
@ -187,280 +191,276 @@ function reduceTrains(d) {
}*/ }*/
for (let item in d) { for (const item in d)
if (typeof item.title !== 'undefined') { if (typeof item.title !== 'undefined') {
const hash = item.title.hashCode(); const hash = item.title.hashCode();
if (titles.indexOf(hash) === -1) { if (titles.indexOf(hash) === -1) {
titles.push(hash); titles.push(hash);
ta.push(item); ta.push(item);
} }
}
} }
return ta;
return ta;
} }
/** /**
* @return {number} * @return {number}
*/ */
function DayDiff(CurrentDate) { function DayDiff(CurrentDate) {
const TYear = CurrentDate.getFullYear(); const TYear = CurrentDate.getFullYear();
const TDay = new Date('January, 01, ' + (parseInt(TYear) + 1)); const TDay = new Date(`January, 01, ${ parseInt(TYear) + 1}`);
TDay.getFullYear(TYear); TDay.getFullYear(TYear);
let DayCount = (TDay - CurrentDate) / (1000 * 60 * 60 * 24); let DayCount = (TDay - CurrentDate) / (1000 * 60 * 60 * 24);
DayCount = Math.round(DayCount); DayCount = Math.round(DayCount);
const d = new Date(); const d = new Date();
DayCount = d.daysSince('beginning of this year'); DayCount = d.daysSince('beginning of this year');
return (DayCount);
return (DayCount);
} }
Array.prototype.indexOfOld = Array.prototype.indexOf; Array.prototype.indexOfOld = Array.prototype.indexOf;
Array.prototype.indexOf = function (e, fn) { Array.prototype.indexOf = function (e, fn) {
if (!fn) { if (!fn)
return this.indexOfOld(e); return this.indexOfOld(e);
} else { else {
if (typeof fn === 'string') { if (typeof fn === 'string') {
const att = fn; const att = fn;
fn = function (e) { fn = function (e) {
return e[att]; return e[att];
}; };
}
return this.map(fn).indexOfOld(e);
} }
return this.map(fn).indexOfOld(e);
}
}; };
module.exports = { module.exports = {
setEmitter: function (newEmitter) { 'setEmitter': function (newEmitter) {
console.log('Setting events', newEmitter); console.log('Setting events', newEmitter);
eventEmitter = newEmitter; eventEmitter = newEmitter;
}, },
getClock: function (req, res) { 'getClock': function (req, res) {
// Console.log(todayCache); // Console.log(todayCache);
res.render('pages/clock', todayCache); res.render('pages/clock', todayCache);
}, },
getToday: function (req, res) { 'getToday': function (req, res) {
logger.info(todayCache); logger.info(todayCache);
res.render('pages/today', todayCache); res.render('pages/today', todayCache);
}, },
getData: function (req, res) { 'getData': function (req, res) {
res.setHeader('Content-Type', 'application/json'); res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(todayCache)); res.end(JSON.stringify(todayCache));
}, },
getTodayDate: function () { 'getTodayDate': function () {
let s; let s;
const d = new Date(); // let d = new Date();
let nextYear = (parseInt(d.getFullYear()) + 1).toString() + '-01-01';
console.log(d.daysUntil('beginning of next year')); let d = new Sugar.Date();
const daysSinceStart = d.daysSince('beginning of this year'); console.log('>> D', d);
const daysRemaining = d.daysUntil('beginning of next year'); const nextYear = `${(parseInt(d.getFullYear()) + 1).toString() }-01-01`;
todayCache.data.history = []; console.log(d.daysUntil('beginning of next year'));
s = '<strong>' + d.format('{Weekday} {Month} {dd}, {yyyy}') + '</strong> - '; const daysSinceStart = d.daysSince('beginning of this year');
const daysRemaining = d.daysUntil('beginning of next year');
/* todayCache.data.history = [];
s = `<strong>${ d.format('{Weekday} {Month} {dd}, {yyyy}') }</strong> - `;
/*
s = s + 'The ' + daysSinceStart + nth(daysSinceStart) + ' day of ' + dateFormat( s = s + 'The ' + daysSinceStart + nth(daysSinceStart) + ' day of ' + dateFormat(
d, d,
'yyyy') + ', and there are ' + daysRemaining + ' days left until the end of the year.'; '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 until the end of the year` s = `${s }The ${daysSinceStart + nth(daysSinceStart)} day of ${d.format('{yyyy}')}, and there are ${daysRemaining} days until the end of the year`;
logger.debug(s); logger.debug(s);
todayCache.data.today = s; todayCache.data.today = s;
}, },
refreshTrain: function () { 'refreshTrain': function () {
trains.updateTrains()
.then((d) => {
'use strict';
trains.updateTrains() d = reduceTrains(d);
.then((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) => {
'use strict';
logger.error(e);
});
},
'refreshWeather': function () {
weather.newDoGetWeather()
.then((d) => {
todayCache.data.weather = d;
logger.info('Updating weather');
broadcastWeather();
}).catch((e) => {
logger.error(e);
});
},
eventEmitter.emit('sendSocket', {id: 'trains', data: d}); 'refreshTrainAndWeather': function () {
todayCache.data.trains.data = d; this.refreshTrain();
todayCache.data.trains.last = new Date(); this.refreshWeather();
}) },
.catch((e) => { 'preLoadToday': function () {
'use strict'; module.exports.getTodayDate();
logger.error(e); 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()
refreshWeather: function () { .then((d) => {
weather.newDoGetWeather() todayCache.data.ftse = d;
.then((d) => { })
todayCache.data.weather = d; .catch((e) => {
logger.info('Updating weather'); logger.error(e);
broadcastWeather(); });
}).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);
// logger.debug('>> today', todayCache.data.cal.today);
})
.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);
});
refreshTrainAndWeather: function () { /*mdFitbit.getYesterdayFitbit()
this.refreshTrain(); .then((d) => {
this.refreshWeather(); todayCache.data.fitbit = d;
}, })
preLoadToday: function () { .catch((e) => {
module.exports.getTodayDate(); 'use strict';
todayCache.data.cal = {today: [], tomorrow: [], week: []}; console.error(e);
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( todayCache.date = breakDay();
'http://www.pogdesign.co.uk/cat/download_ics/60cfdff469d0490545d33d7e3b5c0bcc') }, 'broadcast': function () {
.then((d) => { console.log('BROADCAST');
'use strict'; broadcastWeather();
todayCache.data.tv = d; eventEmitter.emit('sendSocket', { 'id': 'trains', 'data': todayCache.data.trains.data });
}) }
.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});
}
}; };
setTimeout(function () { setTimeout(function () {
loadData(); loadData();
if (runable()) { if (runable())
module.exports.preLoadToday(); module.exports.preLoadToday();
}
//Module.exports.preLoadToday(); // Module.exports.preLoadToday();
}, 5000); }, 5000);
setTimeout(function () { setTimeout(function () {
// mdMailer.sendEmailV1(todayCache, __dirname); // mdMailer.sendEmailV1(todayCache, __dirname);
// saveToDB(todayCache); // saveToDB(todayCache);
saveData();
// saveData();
}, 45000); }, 45000);
setInterval(function () { setInterval(function () {
// EventEmitter.emit('sendSocket',{id:'weather',data:todayCache.data.weather}); // EventEmitter.emit('sendSocket',{id:'weather',data:todayCache.data.weather});
// broadcastWeather(); // broadcastWeather();
// eventEmitter.emit('sendSocket', {id: 'trains', data: todayCache.data.trains.data}); // eventEmitter.emit('sendSocket', {id: 'trains', data: todayCache.data.trains.data});
// mdMailer.sendEmailV1(todayCache, __dirname);
}, (60000)); }, (60000));
cron.schedule('30 6 * * *', function () { cron.schedule('30 6 * * *', function () {
if (runable()) { if (runable())
module.exports.preLoadToday(); module.exports.preLoadToday();
}
return -1; return -1;
}); });
cron.schedule('0 */1 * * *', function () { cron.schedule('0 */1 * * *', function () {
// Module.exports.refreshTrainAndWeather(); // Module.exports.refreshTrainAndWeather();
// this.refreshTrain(); // this.refreshTrain();
module.exports.refreshWeather(); module.exports.refreshWeather();
return -1; return -1;
}); });
cron.schedule('*/15 * * * *', function () { cron.schedule('*/15 * * * *', function () {
module.exports.refreshTrain(); module.exports.refreshTrain();
// Module.exports.refreshWeather(); // Module.exports.refreshWeather();
return -1; return -1;
}); });
cron.schedule('45 6 * * *', function () { cron.schedule('45 6 * * *', function () {
mdMailer.sendEmailV1(todayCache, __dirname); // mdMailer.sendEmailV1(todayCache, __dirname);
saveToDB(todayCache); // saveToDB(todayCache);
// Console.log('tick'); // Console.log('tick');
return -1; return -1;
}); });

View File

@ -1,132 +1,129 @@
const request = require('request') const request = require('request');
const log4js = require('log4js') const log4js = require('log4js');
const logger = log4js.getLogger() const logger = log4js.getLogger();
const STRING = require('string') const STRING = require('string');
let util = require('util') const util = require('util');
const Elapsed = require('elapsed') const Elapsed = require('elapsed');
require('sugar-date'); const Sugar = require('sugar');
logger.level = 'debug';
function processICAL(ical) { function processICAL(ical) {
'use strict'; 'use strict';
logger.info('+ processICAL'); logger.info('+ processICAL');
let workingBlock = [] const workingBlock = [];
const segments = { const segments = {
meetingStartID: 'DTSTART;TZID=Europe/London:', 'meetingStartID': 'DTSTART;TZID=Europe/London:',
meetingStartAlt: 'DTSTART:', 'meetingStartAlt': 'DTSTART:',
meetingStartAltOther: 'DTSTART;VALUE=DATE:', 'meetingStartAltOther': 'DTSTART;VALUE=DATE:',
meetingEndID: 'DTEND;TZID=Europe/London:', 'meetingEndID': 'DTEND;TZID=Europe/London:',
meetingEndAlt: 'DTEND:', 'meetingEndAlt': 'DTEND:',
meetingEndAltOther: 'DTEND;VALUE=DATE:', 'meetingEndAltOther': 'DTEND;VALUE=DATE:',
meetingDescID: 'DESCRIPTION:', 'meetingDescID': 'DESCRIPTION:',
summaryID: 'SUMMARY:', 'summaryID': 'SUMMARY:',
begin: 'BEGIN:VEVENT', 'begin': 'BEGIN:VEVENT',
end: 'END:VEVENT', 'end': 'END:VEVENT',
beginAlarm: 'BEGIN:VALARM', 'beginAlarm': 'BEGIN:VALARM',
endAlarm: 'END:VALARM', 'endAlarm': 'END:VALARM',
recur: 'RRULE:' 'recur': 'RRULE:'
} };
const rules = ['FREQ', 'WKST', 'UNTIL', 'BYMONTH', 'BYMONTHDAY', 'INTERVAL', 'BYDAY'] const rules = ['FREQ', 'WKST', 'UNTIL', 'BYMONTH', 'BYMONTHDAY', 'INTERVAL', 'BYDAY'];
function nThDayOfMonth(monthsAhead, wantedDay) { function nThDayOfMonth(monthsAhead, wantedDay) {
const now = new Date() const now = new Date();
for(let t=0; t < monthsAhead; t++) { for(let t = 0; t < monthsAhead; t++) {
} }
} }
function processRecurrence(workBlock) { function processRecurrence(workBlock) {
let _workBlock = workBlock const _workBlock = workBlock;
// logger.debug('Processing recurrence...'); // logger.debug('Processing recurrence...');
// logger.debug('Processing recurrence...'); // logger.debug('Processing recurrence...');
const weekBits = {'SU': 0, 'MO': 1, 'TU': 2, 'WE': 3, 'TH': 4, 'FR': 5, 'SA': 6} const weekBits = { 'SU': 0, 'MO': 1, 'TU': 2, 'WE': 3, 'TH': 4, 'FR': 5, 'SA': 6 };
const now = new Date() const now = new Date();
const day = now.getDate() const day = now.getDate();
const dayNum = now.getDay() const dayNum = now.getDay();
const month = now.getMonth() const month = now.getMonth();
const year = now.getFullYear() const year = now.getFullYear();
let recurSettings = {freq: null, wkst: null, until: null, bymonth: null, bymonthday: null, interval: null, byday: null} const recurSettings = { 'freq': null, 'wkst': null, 'until': null, 'bymonth': null, 'bymonthday': null, 'interval': null, 'byday': null };
const firstSplit = _workBlock.recur.split(';') const firstSplit = _workBlock.recur.split(';');
for (let t=0; t< firstSplit.length; t++) for (let t = 0; t < firstSplit.length; t++) {
{ const ws = firstSplit[t].split('=');
const ws = firstSplit[t].split('=') if (rules.indexOf(ws[0]) > -1)
if (rules.indexOf(ws[0]) > -1) { recurSettings[ws[0].toLowerCase()] = ws[1];
recurSettings[ws[0].toLowerCase()] = ws[1]; }
}
}
// if all null discard.. // if all null discard..
if (recurSettings.freq === null && recurSettings.wkst === null && recurSettings.until === null && recurSettings.byday === null && recurSettings.bymonth === null && recurSettings.bymonthday === null && recurSettings.interval === null) { if (recurSettings.freq === null && recurSettings.wkst === null && recurSettings.until === null && recurSettings.byday === null && recurSettings.bymonth === null && recurSettings.bymonthday === null && recurSettings.interval === null)
return null; return null;
}
if (recurSettings.until !== null) { if (recurSettings.until !== null)
// have we expired? // have we expired?
//var _until = Date.create(recurSettings.until).isPast(); // var _until = Date.create(recurSettings.until).isPast();
return null; return null;
}
if (recurSettings.freq !== null) { if (recurSettings.freq !== null) {
// logger.debug(_workBlock);
let newStart, newEnd;
// logger.debug(_workBlock); // let d = new Sugar.Date();
let origStart, origEnd, distance, newStart, newEnd /* origStart = Date.create(_workBlock.dtstart);
origEnd = Date.create(_workBlock.dtend);*/
const origStart = new Sugar.Date(_workBlock.dtstart).raw;
const origEnd = new Sugar.Date(_workBlock.dtend).raw;
origStart = Date.create(_workBlock.dtstart); const _d = origStart.getDate();
origEnd = Date.create(_workBlock.dtend); const _m = origStart.getMonth();
const _d = origStart.getDate() const _h = origStart.getHours();
const _m = origStart.getMonth() const _min = origStart.getMinutes();
const _h = origStart.getHours() const _secs = origStart.getSeconds();
const _min = origStart.getMinutes() const distance = origEnd - origStart;
const _secs = origStart.getSeconds()
distance = origEnd - origStart;
// Sugar.Date()
if (recurSettings.freq === 'YEARLY') { if (recurSettings.freq === 'YEARLY') {
if (recurSettings.bymonth !== null && recurSettings.bymonthday !== null) { if (recurSettings.bymonth !== null && recurSettings.bymonthday !== null) {
// ok, a day and month. // ok, a day and month.
newStart = Date.create().set({year:year, month: recurSettings.bymonth - 1 , day: recurSettings.bymonthday, hour:_h, minutes:_min, seconds:_secs}); newStart = Sugar.Date().set({ 'year':year, 'month': recurSettings.bymonth - 1, 'day': recurSettings.bymonthday, 'hour':_h, 'minutes':_min, 'seconds':_secs }).raw;
newEnd = Date.create(newStart).addMilliseconds(distance); newEnd = Sugar.Date(newStart).addMilliseconds(distance).raw;
_workBlock.dtstart = newStart; _workBlock.dtstart = newStart;
_workBlock.dtend = newEnd; _workBlock.dtend = newEnd;
}
} else if (recurSettings.bymonth === null && recurSettings.bymonthday === null) { else if (recurSettings.bymonth === null && recurSettings.bymonthday === null) {
// extract month and year from dtstart // extract month and year from dtstart
newStart = Date.create().set({year:year, month: _m , day: _d, hour:_h, minutes:_min, seconds:_secs}); newStart = Sugar.Date().set({ 'year':year, 'month': _m, 'day': _d, 'hour':_h, 'minutes':_min, 'seconds':_secs }).raw;
newEnd = Date.create(newStart).addMilliseconds(distance); newEnd = Sugar.Date(newStart).addMilliseconds(distance).raw;
_workBlock.dtstart = newStart; _workBlock.dtstart = newStart;
_workBlock.dtend = newEnd; _workBlock.dtend = newEnd;
} }
return _workBlock; return _workBlock;
} }
if (recurSettings.freq === 'MONTHLY') { if (recurSettings.freq === 'MONTHLY')
if (recurSettings.bymonthday !== null) { if (recurSettings.bymonthday !== null) {
// ok, a day and month. // ok, a day and month.
newStart = Date.create().set({year:year, month: month , day: recurSettings.bymonthday, hour:_h, minutes:_min, seconds:_secs}); newStart = Sugar.Date().set({ 'year':year, 'month': month, 'day': recurSettings.bymonthday, 'hour':_h, 'minutes':_min, 'seconds':_secs }).raw;
newEnd = Date.create(newStart).addMilliseconds(distance); newEnd = Sugar.Date(newStart).addMilliseconds(distance).raw;
_workBlock.dtstart = newStart; _workBlock.dtstart = newStart;
_workBlock.dtend = newEnd; _workBlock.dtend = newEnd;
} }
}
if (recurSettings.freq === 'WEEKLY' && recurSettings.interval === null) { if (recurSettings.freq === 'WEEKLY' && recurSettings.interval === null) {
const byDayBit = recurSettings.byday.split(',')[0] const byDayBit = recurSettings.byday.split(',')[0];
const byDayNumber = weekBits[byDayBit] const byDayNumber = weekBits[byDayBit];
if (byDayNumber >= dayNum) { if (byDayNumber >= dayNum) {
const daysAdded = byDayNumber - dayNum const daysAdded = byDayNumber - dayNum;
newStart = Date.create().set({year:year, month: month , day: day, hour:_h, minutes:_min, seconds:_secs}).addDays(daysAdded); newStart = Sugar.Date().set({ 'year':year, 'month': month, 'day': day, 'hour':_h, 'minutes':_min, 'seconds':_secs }).addDays(daysAdded).raw;
newEnd = Date.create(newStart).addMilliseconds(distance); newEnd = Sugar.Date(newStart).addMilliseconds(distance).raw;
_workBlock.dtstart = newStart; _workBlock.dtstart = newStart;
_workBlock.dtend = newEnd; _workBlock.dtend = newEnd;
} }
@ -139,143 +136,149 @@ function processICAL(ical) {
} }
function processBlock(block) { function processBlock(block) {
let _wb let _wb;
let workBlock = { let workBlock = {
summary: '', 'summary': '',
dtstart: null, 'dtstart': null,
dtend: null, 'dtend': null,
description: '', 'description': '',
timeStart: null, 'timeStart': null,
timeEnd: null, 'timeEnd': null,
duration: 0, 'duration': 0,
combined: '', 'combined': '',
recur: null 'recur': null
} };
let alarmFlag = false, ws, blockStep let alarmFlag = false, ws, blockStep;
for (let step = 0; step < block.length; step++) { for (let step = 0; step < block.length; step++) {
blockStep = block[step]; blockStep = block[step];
if (blockStep.indexOf(segments.recur) >= 0) { if (blockStep.indexOf(segments.recur) >= 0)
workBlock.recur = STRING(block[step].split(segments.recur)[1]).collapseWhitespace().s; workBlock.recur = STRING(block[step].split(segments.recur)[1]).collapseWhitespace().s;
//logger.debug(workBlock.recur); // logger.debug(workBlock.recur);
}
if (blockStep.indexOf(segments.summaryID) >= 0) { if (blockStep.indexOf(segments.summaryID) >= 0)
workBlock.summary = STRING(block[step].split(segments.summaryID)[1]).collapseWhitespace().s; workBlock.summary = STRING(block[step].split(segments.summaryID)[1]).collapseWhitespace().s;
}
if (blockStep.indexOf(segments.meetingStartID) >= 0) { if (blockStep.indexOf(segments.meetingStartID) >= 0) {
ws = STRING(block[step].split(segments.meetingStartID)[1]).collapseWhitespace().s; ws = STRING(block[step].split(segments.meetingStartID)[1]).collapseWhitespace().s;
workBlock.dtstart = Date.create(ws); // workBlock.dtstart = Date.create(ws);
workBlock.dtstart = new Sugar.Date(ws).raw;
} }
if (blockStep.indexOf(segments.meetingEndID) >= 0) { if (blockStep.indexOf(segments.meetingEndID) >= 0) {
ws = STRING(block[step].split(segments.meetingEndID)[1]).collapseWhitespace().s; ws = STRING(block[step].split(segments.meetingEndID)[1]).collapseWhitespace().s;
workBlock.dtend = Date.create(ws); // workBlock.dtend = Date.create(ws);
workBlock.dtend = new Sugar.Date(ws).raw;
} }
if (blockStep.indexOf(segments.meetingStartAlt) >= 0) { if (blockStep.indexOf(segments.meetingStartAlt) >= 0) {
ws = STRING(block[step].split(segments.meetingStartAlt)[1]).collapseWhitespace().s; ws = STRING(block[step].split(segments.meetingStartAlt)[1]).collapseWhitespace().s;
workBlock.dtstart = Date.create(ws); console.log('>> ws', ws);
// workBlock.dtstart = Date.create(ws);
// let d = new Sugar.Date();
workBlock.dtstart = new Sugar.Date(ws).raw;
console.log('>> date', workBlock.dtstart);
} }
if (blockStep.indexOf(segments.meetingEndAlt) >= 0) { if (blockStep.indexOf(segments.meetingEndAlt) >= 0) {
ws = STRING(block[step].split(segments.meetingEndAlt)[1]).collapseWhitespace().s; ws = STRING(block[step].split(segments.meetingEndAlt)[1]).collapseWhitespace().s;
workBlock.dtend = Date.create(ws); // workBlock.dtend = Date.create(ws);
workBlock.dtend = new Sugar.Date(ws).raw;
console.log('>> date', workBlock.dtend);
} }
if (blockStep.indexOf(segments.meetingStartAltOther) >= 0) { if (blockStep.indexOf(segments.meetingStartAltOther) >= 0) {
ws = STRING(block[step].split(segments.meetingStartAltOther)[1]).collapseWhitespace().s; ws = STRING(block[step].split(segments.meetingStartAltOther)[1]).collapseWhitespace().s;
workBlock.dtstart = Date.create(ws); // workBlock.dtstart = Date.create(ws);
} workBlock.dtstart = new Sugar.Date(ws).raw;
if (blockStep.indexOf(segments.meetingEndAltOther) >= 0) { }
ws = STRING(block[step].split(segments.meetingEndAltOther)[1]).collapseWhitespace().s; if (blockStep.indexOf(segments.meetingEndAltOther) >= 0) {
workBlock.dtend = Date.create(ws); ws = STRING(block[step].split(segments.meetingEndAltOther)[1]).collapseWhitespace().s;
} console.log('>> ws', ws);
// workBlock.dtend = Date.create(ws);
workBlock.dtend = new Sugar.Date(ws).raw;
}
if (blockStep.indexOf(segments.meetingDescID) >= 0) { if (blockStep.indexOf(segments.meetingDescID) >= 0)
if (!alarmFlag) { if (!alarmFlag) {
workBlock.description = STRING(block[step].split(segments.meetingDescID)[1]).collapseWhitespace().s; workBlock.description = STRING(block[step].split(segments.meetingDescID)[1]).collapseWhitespace().s;
} }
}
if (blockStep.indexOf(segments.beginAlarm) >= 0) { if (blockStep.indexOf(segments.beginAlarm) >= 0)
alarmFlag = true; alarmFlag = true;
}
} }
// We have to check recuring stuff before the cron stuff is processed. // We have to check recuring stuff before the cron stuff is processed.
if (workBlock.recur !== null) { if (workBlock.recur !== null) {
_wb = processRecurrence(workBlock); _wb = processRecurrence(workBlock);
// logger.warn('returning:', _wb); // logger.warn('returning:', _wb);
if (_wb !== null) { if (_wb !== null)
if (!Array.isArray(_wb)) { if (!Array.isArray(_wb)) {
workBlock = _wb; workBlock = _wb;
} else { }
else {
logger.error('We made an array'); logger.error('We made an array');
} }
}
} }
//logger.debug(workBlock); // logger.debug(workBlock);
// let d = new Sugar.Date();
if (workBlock.dtstart !== null) { if (workBlock.dtstart !== null) {
workBlock.timeStart = workBlock.dtstart.format('{24hr}:{mm}:{ss}'); // workBlock.timeStart = workBlock.dtstart.format('{24hr}:{mm}:{ss}');
workBlock.timeStart = Sugar.Date(workBlock.dtstart).format('{24hr}:{mm}:{ss}').raw;
console.log('>> workBlock.timeStart', workBlock.timeStart);
workBlock.combined = `<em>${workBlock.timeStart}</em> - '`; workBlock.combined = `<em>${workBlock.timeStart}</em> - '`;
workBlock.long = `<em>${workBlock.dtstart.format('{Weekday}')}, ${workBlock.timeStart}</em> - `; workBlock.long = `<em>${Sugar.Date(workBlock.dtstart).format('{Weekday}').raw}, ${workBlock.timeStart}</em> - `;
console.log('>> workBlock.long', workBlock.long);
} }
workBlock.combined = workBlock.combined + workBlock.summary; workBlock.combined = workBlock.combined + workBlock.summary;
workBlock.longcombined = workBlock.long + workBlock.summary; workBlock.longcombined = workBlock.long + workBlock.summary;
if (workBlock.dtend !== null) { if (workBlock.dtend !== null)
workBlock.timeEnd = workBlock.dtend.format('{24hr}:{mm}:{ss}'); workBlock.timeEnd = Sugar.Date(workBlock.dtend).format('{24hr}:{mm}:{ss}').raw;
}
if (workBlock.dtstart !== null && workBlock.dtend !== null) { if (workBlock.dtstart !== null && workBlock.dtend !== null) {
const elapsedTime = new Elapsed(workBlock.dtstart, workBlock.dtend) const elapsedTime = new Elapsed(workBlock.dtstart, workBlock.dtend);
workBlock.duration = elapsedTime.optimal; workBlock.duration = elapsedTime.optimal;
workBlock.combined = workBlock.combined + ', ' + elapsedTime.optimal; workBlock.combined = `${workBlock.combined }, ${ elapsedTime.optimal}`;
workBlock.longcombined = workBlock.longcombined + ', ' + elapsedTime.optimal; workBlock.longcombined = `${workBlock.longcombined }, ${ elapsedTime.optimal}`;
} }
return workBlock; return workBlock;
} }
const lines = ical.split('\r\n'), l = lines.length const lines = ical.split('\r\n'), l = lines.length;
let counter = 0 let counter = 0;
let alarmed = false let alarmed = false;
while (counter < l) { while (counter < l)
if (lines[counter].indexOf(segments.begin) < 0) { if (lines[counter].indexOf(segments.begin) < 0)
counter++; counter++;
} else { else {
let subcounter = 0 let subcounter = 0;
const subBlock = [] const subBlock = [];
alarmed = false; alarmed = false;
while (subcounter < 75) { while (subcounter < 75)
if (lines[counter + subcounter].indexOf(segments.end) < 0) { if (lines[counter + subcounter].indexOf(segments.end) < 0) {
if (lines[counter + subcounter].indexOf(segments.beginAlarm) > -1)
if (lines[counter + subcounter].indexOf(segments.beginAlarm) > -1) {
alarmed = true; alarmed = true;
}
if (!alarmed) { if (!alarmed)
subBlock.push(lines[counter + subcounter]); subBlock.push(lines[counter + subcounter]);
}
if (lines[counter + subcounter].indexOf(segments.endAlarm) > -1) { if (lines[counter + subcounter].indexOf(segments.endAlarm) > -1)
alarmed = false; alarmed = false;
}
subcounter++; subcounter++;
} else { }
else
break; break;
}
}
counter = counter + subcounter; counter = counter + subcounter;
const b = processBlock(subBlock) const b = processBlock(subBlock);
if (Array.isArray(b)) { if (Array.isArray(b))
logger.error('!returned an array...'); logger.error('!returned an array...');
} else { else
if (b.dtstart !== null) { if (b.dtstart !== null)
workingBlock.push(b); workingBlock.push(b);
}
}
} }
}
logger.info('- processICAL'); logger.info('- processICAL');
// If (workingBlock.dtstart == null) return {}; // If (workingBlock.dtstart == null) return {};
@ -283,97 +286,97 @@ function processICAL(ical) {
} }
module.exports = { module.exports = {
calendars: ['https://calendar.google.com/calendar/ical/martind2000%40gmail.com/private-40cfebc9f7dcfa7fde6b9bf2f0092c93/basic.ics', 'calendars': ['https://calendar.google.com/calendar/ical/martind2000%40gmail.com/private-40cfebc9f7dcfa7fde6b9bf2f0092c93/basic.ics',
'https://calendar.google.com/calendar/ical/mt5pgdhknvgoc8usfnrso9vkv0%40group.calendar.google.com/private-58876002af9f302a593acfa6fa792dcf/basic.ics', 'https://calendar.google.com/calendar/ical/mt5pgdhknvgoc8usfnrso9vkv0%40group.calendar.google.com/private-58876002af9f302a593acfa6fa792dcf/basic.ics',
'https://www.tripit.com/feed/ical/private/DB96E4BB-94A9BD8F9CC1CF51C6CC0D920840F4F5/tripit.ics', 'https://www.tripit.com/feed/ical/private/DB96E4BB-94A9BD8F9CC1CF51C6CC0D920840F4F5/tripit.ics',
'https://calendar.google.com/calendar/ical/en.uk%23holiday%40group.v.calendar.google.com/public/basic.ics', 'https://calendar.google.com/calendar/ical/en.uk%23holiday%40group.v.calendar.google.com/public/basic.ics',
'https://calendar.google.com/calendar/ical/i8dglj12p5nuv20sbjmun5s588%40group.calendar.google.com/private-c8adccb41e56d6a2f285078aaed313f5/basic.ics'], 'https://calendar.google.com/calendar/ical/i8dglj12p5nuv20sbjmun5s588%40group.calendar.google.com/private-c8adccb41e56d6a2f285078aaed313f5/basic.ics'],
jsonBlock: [], 'jsonBlock': [],
getTodaysSimple: function() { 'getTodaysSimple': function() {
'use strict'; 'use strict';
logger.info('+ getTodaysSimple'); logger.info('+ getTodaysSimple');
const today = { const today = {
entries: [] 'entries': []
} };
for (let t = 0; t < this.jsonBlock.length; t++) { for (let t = 0; t < this.jsonBlock.length; t++) {
if (this.jsonBlock[t].dtstart.isToday()) { // if (this.jsonBlock[t].dtstart.isToday())
// logger.debug('>> isToday', Sugar.Date(this.jsonBlock[t].dtstart).isToday().raw);
if (Sugar.Date(this.jsonBlock[t].dtstart).isToday().raw)
today.entries.push(this.jsonBlock[t]); today.entries.push(this.jsonBlock[t]);
}
} }
logger.info('- getTodaysSimple'); logger.info('- getTodaysSimple');
return today; return today;
}, },
getTomorrow: function() { 'getTomorrow': function() {
'use strict'; 'use strict';
logger.info('+ getTomorrow'); logger.info('+ getTomorrow');
const today = { const today = {
entries: [] 'entries': []
} };
for (let t = 0; t < this.jsonBlock.length; t++)
if (Sugar.Date(this.jsonBlock[t].dtstart).isTomorrow().raw)
today.entries.push(this.jsonBlock[t]);
logger.info('- getTomorrow');
return today;
},
'getWeek': function() {
'use strict';
logger.info('+ getWeek');
const today = {
'entries': []
};
const now = new Sugar.Date('today').raw;
logger.debug('>> now', now);
const twoDays = new Sugar.Date('today').addDays(2).beginningOfDay().raw;
logger.debug('>> twoDays', twoDays);
const sevenDays = new Sugar.Date('today').addDays(7).beginningOfDay().raw;
logger.debug('>> sevenDays', sevenDays);
logger.debug('>> trip', { now, twoDays, sevenDays });
for (let t = 0; t < this.jsonBlock.length; t++) { for (let t = 0; t < this.jsonBlock.length; t++) {
if (this.jsonBlock[t].dtstart.isTomorrow()) { logger.debug('>> between', Sugar.Date(this.jsonBlock[t].dtstart).raw, Sugar.Date(this.jsonBlock[t].dtstart).isBetween(twoDays, sevenDays));
if (Sugar.Date(this.jsonBlock[t].dtstart).isBetween(twoDays, sevenDays).raw)
today.entries.push(this.jsonBlock[t]); today.entries.push(this.jsonBlock[t]);
} }
}
logger.info('- getTomorrow'); logger.info('- getWeek');
return today;
}, return today;
getWeek: function() { },
'use strict'; 'getTodaysMeetings': function() {
logger.info('+ getWeek');
const today = {
entries: []
}
let now, twoDays, sevenDays
now = Date.create('today');
// logger.debug(now);
twoDays = Date.create(now).addDays(2).beginningOfDay();
// logger.debug(twoDays);
sevenDays = Date.create(twoDays).addDays(5).beginningOfDay();
// logger.debug(now, twoDays, sevenDays);
for (let t = 0; t < this.jsonBlock.length; t++) {
if (this.jsonBlock[t].dtstart.isBetween(twoDays, sevenDays)) {
today.entries.push(this.jsonBlock[t]);
}
}
logger.info('- getWeek');
return today;
},
getTodaysMeetings: function() {
'use strict'; 'use strict';
logger.info('+ getTodaysMeetings'); logger.info('+ getTodaysMeetings');
const today = { const today = {
previous: [], upcoming: [], current: {} 'previous': [], 'upcoming': [], 'current': {}
} };
const now = new Date() const now = new Date();
for (let t = 0; t < this.jsonBlock.length; t++) { for (let t = 0; t < this.jsonBlock.length; t++)
if (this.jsonBlock[t].dtstart.isToday()) { if (Sugar.Date(this.jsonBlock[t].dtstart).isToday().raw) {
if (Sugar.Date(this.jsonBlock[t].dtstart).isAfter(now).raw)
if (this.jsonBlock[t].dtstart.isAfter(now)) {
today.upcoming.push(this.jsonBlock[t]); today.upcoming.push(this.jsonBlock[t]);
} else { else
today.previous.push(this.jsonBlock[t]); today.previous.push(this.jsonBlock[t]);
}
if (now.isBetween(this.jsonBlock[t].dtstart, this.jsonBlock[t].dtend)) { if (now.isBetween(this.jsonBlock[t].dtstart, this.jsonBlock[t].dtend))
today.current = this.jsonBlock[t]; today.current = this.jsonBlock[t];
}
} }
}
// logger.debug(today); // logger.debug(today);
logger.info('- getTodaysMeetings'); logger.info('- getTodaysMeetings');
return today; return today;
}, getSimpleCalV2: function(url, cb) { }, 'getSimpleCalV2': function(url, cb) {
'use strict'; 'use strict';
const self = this const self = this;
// Var calJson = []; // Var calJson = [];
try { try {
@ -381,105 +384,104 @@ module.exports = {
if (err) { if (err) {
logger.error('Get remote Calendar Request failed'); logger.error('Get remote Calendar Request failed');
// Callback.call(null, new Error('Request failed')); // Callback.call(null, new Error('Request failed'));
return; return;
} }
self.jsonBlock = processICAL(body); self.jsonBlock = processICAL(body);
// logger.debug(self.jsonBlock); // logger.debug(self.jsonBlock);
const st = self.getTodaysSimple() const st = self.getTodaysSimple();
if (typeof cb === 'function') { if (typeof cb === 'function')
cb(st); cb(st);
}
}, function(error, response, body) { }, function(error, response, body) {
if (response.statusCode !== 200) { if (response.statusCode !== 200) {
logger.error(response.statusCode); logger.error(response.statusCode);
logger.error(body); logger.error(body);
} }
}); });
} catch (e) { }
catch (e) {
console.log(e); console.log(e);
} }
}, 'getSimpleCalV3': function(url) {
}, getSimpleCalV3: function(url) {
'use strict'; 'use strict';
const self = this const self = this;
return new Promise(function(resolve, reject) { return new Promise(function(resolve, reject) {
try { try {
request(url, function(err, res, body) { request(url, function(err, res, body) {
if (err) { if (err)
// logger.error(err); // logger.error(err);
return reject(err); return reject(err);
// Throw err; // Throw err;
}
self.jsonBlock = processICAL(body); self.jsonBlock = processICAL(body);
// logger.debug(self.jsonBlock); // logger.debug(self.jsonBlock);
const st = self.getTodaysSimple() const st = self.getTodaysSimple();
return resolve(st); return resolve(st);
}, function(error, response, body) { }, function(error, response, body) {
if (response.statusCode !== 200) { if (response.statusCode !== 200) {
logger.error(response.statusCode); logger.error(response.statusCode);
logger.error(body); logger.error(body);
return reject(error); return reject(error);
} }
}); });
} catch (e) { }
catch (e) {
console.log(e); console.log(e);
return reject(e); return reject(e);
} }
}); });
// Var calJson = []; // Var calJson = [];
}, 'getAdvancedCalV3': function(url) {
}, getAdvancedCalV3: function(url) { 'use strict';
'use strict'; const self = this;
const self = this
return new Promise(function(resolve, reject) { return new Promise(function(resolve, reject) {
try { try {
request(url, function(err, res, body) { request(url, function(err, res, body) {
if (err) { if (err)
// logger.error(err); // logger.error(err);
return reject(err); return reject(err);
// Throw err; // Throw err;
}
self.jsonBlock = processICAL(body); self.jsonBlock = processICAL(body);
// logger.debug(self.jsonBlock); // logger.debug(self.jsonBlock);
const st = self.getTodaysSimple().entries const st = self.getTodaysSimple().entries;
const tom = self.getTomorrow().entries const tom = self.getTomorrow().entries;
const week = self.getWeek().entries const week = self.getWeek().entries;
const obj = {today: st, tomorrow: tom, week: week} const obj = { 'today': st, 'tomorrow': tom, 'week': week };
logger.debug(obj);
return resolve(obj);
}, function(error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
return reject(error);
}
});
} catch (e) {
console.log(e);
return reject(e);
}
});
// Var calJson = [];
}
// logger.warn(obj);
return resolve(obj);
}, function(error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
return reject(error);
}
});
}
catch (e) {
console.log(e);
return reject(e);
}
});
// Var calJson = [];
}
/** /**
* Created by Martin on 16/02/2016. * Created by Martin on 16/02/2016.

View File

@ -4,24 +4,24 @@ var STRING = require('string');
var logger = require('log4js').getLogger(); var logger = require('log4js').getLogger();
module.exports = { module.exports = {
getTechHistory: function() { 'getTechHistory': function() {
var url; var url;
var d; var d;
var day; var day;
var month; var month;
var monthNames = [ var monthNames = [
'January', 'January',
'February', 'February',
'March', 'March',
'April', 'April',
'May', 'May',
'June', 'June',
'July', 'July',
'August', 'August',
'September', 'September',
'October', 'October',
'November', 'November',
'December' 'December'
]; ];
d = new Date(); d = new Date();
@ -32,15 +32,15 @@ module.exports = {
url = ['http://www.computerhistory.org/tdih/', month, '/', day].join(''); url = ['http://www.computerhistory.org/tdih/', month, '/', day].join('');
logger.debug(url); logger.debug(url);
return new Promise(function(resolve, reject) { return new Promise(function(resolve, reject) {
'use strict'; 'use strict';
request(url, function(err, resp, body) { request(url, function(err, resp, body) {
if (err) { if (err)
// Logger.error(err); // Logger.error(err);
return reject(err); return reject(err);
// Throw err; // Throw err;
}
var $ = cheerio.load(body); var $ = cheerio.load(body);
var tdihbody = $('#tdihbody'); var tdihbody = $('#tdihbody');
@ -57,29 +57,29 @@ module.exports = {
if (response.statusCode !== 200) { if (response.statusCode !== 200) {
logger.error(response.statusCode); logger.error(response.statusCode);
logger.error(body); logger.error(body);
return reject(error); return reject(error);
} }
}); });
}); });
}, 'getHistory': function() {
}, getHistory: function() {
var url; var url;
var d = new Date(); var d = new Date();
var day; var day;
var month; var month;
var monthNames = [ var monthNames = [
'january', 'january',
'february', 'february',
'march', 'march',
'april', 'april',
'may', 'may',
'june', 'june',
'july', 'july',
'august', 'august',
'september', 'september',
'october', 'october',
'november', 'november',
'december' 'december'
]; ];
month = monthNames[d.getMonth()]; month = monthNames[d.getMonth()];
@ -87,20 +87,18 @@ module.exports = {
day = d.getDate(); day = d.getDate();
url = [ url = [
'http://www.bbc.co.uk/scotland/history/onthisday/', month, '/', 'http://www.bbc.co.uk/scotland/history/onthisday/', month, '/',
day day
].join(''); ].join('');
logger.debug(url); logger.debug(url);
return new Promise(function(resolve, reject) { return new Promise(function(resolve, reject) {
request(url, function(err, resp, body) { request(url, function(err, resp, body) {
if (err) { if (err)
// Logger.error(err); // Logger.error(err);
return reject(err); return reject(err);
// Throw err; // Throw err;
}
var $ = cheerio.load(body); var $ = cheerio.load(body);
@ -108,52 +106,48 @@ module.exports = {
var output = []; var output = [];
nbody.find('.story > p').each(function(div) { nbody.find('.story > p').each(function(div) {
var s = $(this).text(); var s = $(this).text();
if (s.indexOf('Today\'s recipe:') == -1) { if (s.indexOf('Today\'s recipe:') == -1)
output.push(s); output.push(s);
}
}); });
return resolve(output); return resolve(output);
}, function(error, response, body) { }, function(error, response, body) {
if (response.statusCode !== 200) { if (response.statusCode !== 200) {
logger.error(response.statusCode); logger.error(response.statusCode);
logger.error(body); logger.error(body);
return reject(error); return reject(error);
} }
}); });
}); });
}, },
updateHistory: function() { 'updateHistory': function() {
'use strict'; 'use strict';
var output = []; var output = [];
return new Promise(function(resolve, reject) { return new Promise(function(resolve, reject) {
module.exports.getHistory() module.exports.getHistory()
.then((d)=> { .then((d) => {
output = d;
output = d; module.exports.getTechHistory()
.then((d) => {
output = output.concat(d);
module.exports.getTechHistory() return resolve(output);
.then((d) => { })
output = output.concat(d); .catch((e) => {
logger.error(e);
return resolve(output);
}) return reject(e);
.catch((e) => { });
logger.error(e); })
return reject(e); .catch((e) => {
}); logger.error(e);
}) return reject(e);
.catch((e) => { });
logger.error(e); });
return reject(e);
});
})
} }
}; };

View File

@ -5,46 +5,44 @@ const Forecast = require('forecast.io');
const STRING = require('string'); const STRING = require('string');
const logger = require('log4js').getLogger(); const logger = require('log4js').getLogger();
const forecastOptions = { const forecastOptions = {
APIKey: '9ad2a41d420f3cf4960571bb886f710c', units: 'uk2' 'APIKey': '9ad2a41d420f3cf4960571bb886f710c', 'units': 'uk2'
}; };
module.exports = { module.exports = {
newDoGetWeather: function() { 'newDoGetWeather': function() {
'use strict'; 'use strict';
return new Promise(function(resolve, reject) {
logger.info('New Retrieving weather..'); return new Promise(function(resolve, reject) {
const j = {}; logger.info('New Retrieving weather..');
const forecast = new Forecast(forecastOptions); const j = {};
forecast.get(55.95, -4.566667, const forecast = new Forecast(forecastOptions);
{units: 'uk2'}, forecast.get(55.95, -4.566667,
function(err, res, data) { { 'units': 'uk2' },
if (err) { function(err, res, data) {
return reject(err); if (err)
} return reject(err);
const tempMin = parseInt(data.daily.data[0].temperatureMin); const tempMin = parseInt(data.daily.data[0].temperatureMin);
const tempMax = parseInt(data.daily.data[0].temperatureMax); const tempMax = parseInt(data.daily.data[0].temperatureMax);
j.currently = data.currently.summary; j.currently = data.currently.summary;
j.today = data.daily.data[0].summary; j.today = data.daily.data[0].summary;
j.later = data.daily.summary; j.later = data.daily.summary;
j.alerts = data.alerts || {}; j.alerts = data.alerts || {};
j.data = data; j.data = data;
const fs = STRING(j.currently).endsWith('.') ? '' : '.'; const fs = STRING(j.currently).endsWith('.') ? '' : '.';
if (tempMax === tempMin) { if (tempMax === tempMin)
j.currently += fs + ' Around ' + tempMin.toString() + ' degrees.'; j.currently += `${fs } Around ${ tempMin.toString() } degrees.`;
}
else { else
j.currently += fs + ' Around ' + tempMin.toString() + ' to ' + tempMax.toString() + ' degrees.'; j.currently += `${fs } Around ${ tempMin.toString() } to ${ tempMax.toString() } degrees.`;
}
// logger.debug(j); // logger.debug(j);
return resolve(j); return resolve(j);
});
}); });
} });
}
}; };

View File

@ -8,34 +8,48 @@ const util = require('util');
const jsonfile = require('jsonfile'); const jsonfile = require('jsonfile');
const fs = require('fs'); const fs = require('fs');
const logger = require('log4js').getLogger(); const logger = require('log4js').getLogger();
const weather = require('openweather-apis');
weather.setAPPID('936a0ed9eb23b95cf08fc9f693c24264');
weather.setLang('en');
weather.setCity('Glasgow City');
const forecastOptions = { const forecastOptions = {
APIKey: '0657dc0d81c037cbc89ca88e383b6bbf', 'APIKey': '0657dc0d81c037cbc89ca88e383b6bbf',
units: 'uk2' 'units': 'uk2'
}; };
const file = __dirname + '/' + 'data.json'; const file = `${__dirname }/` + 'data.json';
function saveData(d) { function saveData(d) {
jsonfile.writeFileSync(file, d); jsonfile.writeFileSync(file, d);
} }
module.exports = { function doGetWeatherOutlook () {
logger.info('Retrieving weather..');
const j = {};
const forecast = new Forecast(forecastOptions);
forecast.get(55.8582846, -4.2593033, { 'units': 'uk2' }, (err, res, data) => {
if (err) throw err;
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 || {};
});
}
doGetWeatherOutlook: function () { function doGetOpenWeather() {
logger.info('Retrieving weather..'); return new Promise((resolve, reject) => {
let j = {}; weather.getWeatherForecastForDays(5, function(err, wData) {
let forecast = new Forecast(forecastOptions); if (err)
forecast.get(55.8582846, -4.2593033, {units: 'uk2'}, (err, res, data) => { return reject(err);
if (err) throw err; else
logger.debug(util.inspect(data)); return resolve(wData);
saveData(data); });
j.currently = data.currently.summary; });
j.today = data.daily.data[0].summary; }
j.later = data.daily.summary;
j.alerts = data.alerts || {};
});
}
};
module.exports.doGetWeatherOutlook(); module.exports.doGetWeatherOutlook = doGetWeatherOutlook;
module.exports.doGetOpenWeather = doGetOpenWeather;

View File

@ -7,15 +7,15 @@
"babel-eslint": "^7.2.1", "babel-eslint": "^7.2.1",
"babel-preset-es2015": "^6.24.0", "babel-preset-es2015": "^6.24.0",
"cheerio": "^0.22.0", "cheerio": "^0.22.0",
"dateformat": "^2.0.0", "dateformat": "^2.2.0",
"ejs": "^2.5.7", "ejs": "^2.5.7",
"eslint": "^4.6.1", "eslint": "^4.7.2",
"eslint-config-defaults": "^9.0.0", "eslint-config-defaults": "^9.0.0",
"eslint-config-standard": "^10.2.1", "eslint-config-standard": "^10.2.1",
"eslint-plugin-import": "^2.7.0", "eslint-plugin-import": "^2.7.0",
"eslint-plugin-node": "^5.1.1", "eslint-plugin-node": "^5.1.1",
"eslint-plugin-promise": "^3.5.0", "eslint-plugin-promise": "^3.5.0",
"eslint-plugin-react": "^7.3.0", "eslint-plugin-react": "^7.4.0",
"eslint-plugin-standard": "^3.0.1", "eslint-plugin-standard": "^3.0.1",
"eslint-watch": "^3.0.1", "eslint-watch": "^3.0.1",
"fitbit-oauth2": "0.0.1", "fitbit-oauth2": "0.0.1",
@ -36,16 +36,16 @@
"gulp-uglify": "^3.0.0", "gulp-uglify": "^3.0.0",
"htmlparser": "^1.7.7", "htmlparser": "^1.7.7",
"jade": "^1.11.0", "jade": "^1.11.0",
"jest": "^21.0.2", "jest": "^21.2.1",
"jshint": "^2.9.4", "jshint": "^2.9.4",
"jsonfile": "^3.0.1", "jsonfile": "^3.0.1",
"lodash": "^4.11.2", "lodash": "^4.11.2",
"log4js": "^2.3.3", "log4js": "^2.3.4",
"lowdb": "^1.0.0", "lowdb": "^1.0.0",
"mammoth": "^1.4.2", "mammoth": "^1.4.2",
"nano": "^6.4.0", "nano": "^6.4.2",
"node-localstorage": "^1.3.0", "node-localstorage": "^1.3.0",
"request": "^2.81.0", "request": "^2.83.0",
"simple-weather": "^1.2.2", "simple-weather": "^1.2.2",
"sugar-date": "^2.0.4", "sugar-date": "^2.0.4",
"wordsoap": "^0.2.0", "wordsoap": "^0.2.0",
@ -53,30 +53,32 @@
"xmltojson": "^1.3.5" "xmltojson": "^1.3.5"
}, },
"dependencies": { "dependencies": {
"apicache": "^0.11.2", "apicache": "^1.1.0",
"body-parser": "^1.18.0", "body-parser": "^1.18.2",
"cloudant": "^1.6.2", "cloudant": "^1.6.2",
"cookie-parser": "^1.4.1", "cookie-parser": "^1.4.1",
"cookieparser": "^0.1.0", "cookieparser": "^0.1.0",
"elapsed": "0.0.7", "elapsed": "0.0.7",
"errorhandler": "^1.4.3", "errorhandler": "^1.4.3",
"express": "^4.15.4", "express": "^4.15.5",
"express-session": "^1.15.5", "express-session": "^1.15.6",
"ftse": "^1.0.6", "ftse": "^1.0.6",
"gulp": "^3.9.1", "gulp": "^3.9.1",
"ical2json": "^1.2.0", "ical2json": "^1.2.0",
"limitedarray": "git+https://gitlab.silvrtree.co.uk/martind2000/limitedArray.git", "limitedarray": "git+https://gitlab.silvrtree.co.uk/martind2000/limitedArray.git",
"logger": "0.0.1", "logger": "0.0.1",
"method-override": "^2.3.5", "method-override": "^2.3.10",
"morgan": "^1.7.0", "morgan": "^1.9.0",
"node-cron": "^1.2.1", "node-cron": "^1.2.1",
"pug": "^2.0.0-beta11", "openweather-apis": "^3.3.2",
"pug": "^2.0.0-rc.4",
"scrape": "^0.2.3", "scrape": "^0.2.3",
"string": "^3.3.1", "string": "^3.3.1",
"sugar": "^2.0.4",
"trend": "^0.3.0", "trend": "^0.3.0",
"ultrases": "^0.1.3", "ultrases": "^0.1.3",
"unstyler": "^0.2.2", "unstyler": "^0.2.2",
"ws": "^3.1.0" "ws": "^3.2.0"
}, },
"scripts": { "scripts": {
"start": "node web-server.js", "start": "node web-server.js",

View File

@ -20,7 +20,7 @@
<% include ../partials/links %> <% include ../partials/links %>
<div id='weather' class="mui-panel"></div> <div id='weather'></div>
</div> </div>
<script type="text/template" id="password-template"> <script type="text/template" id="password-template">
@ -31,20 +31,27 @@
<script src="live/js/app.js"></script> <script src="live/js/app.js"></script>
<script> <script>
;(function (w) { ;(function (w) {
navigator.geolocation.getCurrentPosition((show_weather) => { /*navigator.geolocation.getCurrentPosition((show_weather) => {
w.weather = new WeatherSlim({model: new WeatherModel({geo:show_weather})}); w.weather = new WeatherSlim({model: new WeatherModel({geo:show_weather})});
}); });*/
const webSocketModel = new SOCKETMANAGER();
w.contractEnds = new EventView({model:new EventModel({event:new Date(2017, 8, 29), label: 'Contract Ends:'})});
w.bitcoin = new Bitcoin({model: new BitcoinModel()}); const btcModel = new BitcoinModel();
w.fx = new FxView({model: new FxModel()}); webSocketModel.setBTC(btcModel);
w.dbqglqView = new TrainView({model: new TrainModel({from: 'dbe', to: 'glq'})});
w.glqdbeView = new TrainView({model: new TrainModel({from: 'glq', to: 'dbe'})}); w.wview = new WView({'el': document.getElementById('weather')});
w.glqhymView = new TrainView({model: new TrainModel({from: 'glq', to: 'hym'})}); w.contractEnds = new EventView({model: new EventModel({event: new Date(2017, 8, 29), label: 'Contract Ends:'})});
w.hymglqView = new TrainView({model: new TrainModel({from: 'hym', to: 'glq'})}); /*w.bitcoin = new Bitcoin({model: new BitcoinModel()});*/
w.bitcoin = new Bitcoin({model: btcModel});
w.fx = new FxView({model: new FxModel()});
w.dbqglqView = new TrainView({model: new TrainModel({'from': 'dbe', 'to': 'glq'})});
w.glqdbeView = new TrainView({model: new TrainModel({'from': 'glq', 'to': 'dbe'})});
w.glqhymView = new TrainView({model: new TrainModel({'from': 'glq', 'to': 'hym'})});
w.hymglqView = new TrainView({model: new TrainModel({'from': 'hym', 'to': 'glq'})});
w.passwords = new PasswordView(); w.passwords = new PasswordView();
})(window); })(window);
</script> </script>
</html> </html>

View File

@ -20,7 +20,7 @@
<% include ../partials/links %> <% include ../partials/links %>
<div id='weather' class="mui-panel"></div> <div id='weather'></div>
</div> </div>
<script type="text/template" id="password-template"> <script type="text/template" id="password-template">
@ -37,37 +37,38 @@
<script src="js/modules/bitcoin.js"></script> <script src="js/modules/bitcoin.js"></script>
<script src="js/modules/fx.js"></script> <script src="js/modules/fx.js"></script>
<script src="js/modules/train.js"></script> <script src="js/modules/train.js"></script>
<script src="js/modules/weather.js"></script> <script src="js/modules/weatherV2.js"></script>
<script src="js/modules/password.js"></script> <script src="js/modules/password.js"></script>
<script src="app.js"></script> <script src="app.js"></script>
<script> <script>
// slackV2.ejs // slackV2.ejs
(function (w) { (function (w) {
navigator.geolocation.getCurrentPosition((show_weather) => { /*navigator.geolocation.getCurrentPosition((show_weather) => {
w.weather = new WeatherSlim({model: new WeatherModel({geo:show_weather})}); w.weather = new WeatherSlim({model: new WeatherModel({geo:show_weather})});
}); });*/
const webSocketModel = new SOCKETMANAGER(); const webSocketModel = new SOCKETMANAGER();
const btcModel = new BitcoinModel(); const btcModel = new BitcoinModel();
webSocketModel.setBTC(btcModel); webSocketModel.setBTC(btcModel);
w.contractEnds = new EventView({model:new EventModel({event:new Date(2017, 8, 29), label: 'Contract Ends:'})}); w.contractEnds = new EventView({model: new EventModel({event: new Date(2017, 8, 29), label: 'Contract Ends:'})});
/*w.bitcoin = new Bitcoin({model: new BitcoinModel()});*/ /*w.bitcoin = new Bitcoin({model: new BitcoinModel()});*/
w.bitcoin = new Bitcoin({model: btcModel}); w.bitcoin = new Bitcoin({model: btcModel});
w.fx = new FxView({model: new FxModel()}); w.fx = new FxView({model: new FxModel()});
// w.dbqglqView = new TrainView({model: new TrainModel({from: 'dbe', to: 'glq'})}); w.dbqglqView = new TrainView({model: new TrainModel({from: 'dbe', to: 'glq'})});
//w.glqdbeView = new TrainView({model: new TrainModel({from: 'glq', to: 'dbe'})}); w.glqdbeView = new TrainView({model: new TrainModel({from: 'glq', to: 'dbe'})});
//w.glqhymView = new TrainView({model: new TrainModel({from: 'glq', to: 'hym'})}); w.glqhymView = new TrainView({model: new TrainModel({from: 'glq', to: 'hym'})});
//w.hymglqView = new TrainView({model: new TrainModel({from: 'hym', to: 'glq'})}); w.hymglqView = new TrainView({model: new TrainModel({from: 'hym', to: 'glq'})});
// console.log(PasswordView); // console.log(PasswordView);
w.passwords = new PasswordView(); w.passwords = new PasswordView();
webSocketModel.turnOn(); w.wview = new WView({'el': document.getElementById('weather')});
})(window); webSocketModel.turnOn();
})(window);
</script> </script>
</html> </html>

View File

@ -9,9 +9,9 @@
<meta name="Author" content=""/> <meta name="Author" content=""/>
<link rel="stylesheet" href="live/fonts/fonts.css"> <link rel="stylesheet" href="live/fonts/fonts.css">
<link href="//cdnjs.cloudflare.com/ajax/libs/weather-icons/2.0.9/css/weather-icons.css" rel="stylesheet" type="text/css"/>
<link href="live/css/mui.custom.css" rel="stylesheet" type="text/css"/> <link href="live/css/mui.custom.css" rel="stylesheet" type="text/css"/>
<link href="css/weather.css" rel="stylesheet" type="text/css"/>
</head> </head>
<body> <body>

View File

@ -9,8 +9,10 @@
<meta name="Author" content=""/> <meta name="Author" content=""/>
<link rel="stylesheet" href="fonts/fonts.css"> <link rel="stylesheet" href="fonts/fonts.css">
<link href="//cdnjs.cloudflare.com/ajax/libs/weather-icons/2.0.9/css/weather-icons.css" rel="stylesheet" type="text/css"/>
<link href="css/custom.css" rel="stylesheet" type="text/css"/> <link href="css/custom.css" rel="stylesheet" type="text/css"/>
<link href="css/weather.css" rel="stylesheet" type="text/css"/>
<script src="libs/zepto.min.js"></script> <script src="libs/zepto.min.js"></script>
<script src="libs/microevent.js"></script> <script src="libs/microevent.js"></script>

View File

@ -1,5 +1,6 @@
const express = require('express'); const express = require('express');
const path = require('path'); const path = require('path');
const apicache = require('apicache');
const http = require('http'); const http = require('http');
const fx = require('./lib/fx'); const fx = require('./lib/fx');
@ -13,7 +14,7 @@ const morgan = require('morgan');
const cookieParser = require('cookie-parser'); const cookieParser = require('cookie-parser');
const session = require('express-session'); const session = require('express-session');
const methodoverride = require('method-override'); // const methodoverride = require('method-override');
const bodyparser = require('body-parser'); const bodyparser = require('body-parser');
const errorhandler = require('errorhandler'); const errorhandler = require('errorhandler');
@ -22,6 +23,8 @@ const jsonfile = require('jsonfile');
const Events = require('events'); const Events = require('events');
const busEmitter = new Events.EventEmitter(); const busEmitter = new Events.EventEmitter();
const weather = require('./lib/weather');
// busEmitter.on('update', today.broadcast); // busEmitter.on('update', today.broadcast);
const WebSocket = require('ws'); const WebSocket = require('ws');
@ -44,7 +47,9 @@ const Fitbit = require('fitbit-oauth2');
const polys = require('./lib/poly.js'); const polys = require('./lib/poly.js');
const logger = require('log4js').getLogger('web-server'); const logger = require('log4js').getLogger('web-server');
const apicache = require('apicache');
logger.level = 'debug';
const app = express(); const app = express();
GLOBAL.lastcheck = 0; GLOBAL.lastcheck = 0;
@ -53,6 +58,9 @@ let btcCache = {}, fxCache = {}, trainCache = {};
const port = process.env.PORT || 9000; const port = process.env.PORT || 9000;
// apicache.options({ 'debug': true });
const cache = apicache.middleware;
// app.configure(function () { // app.configure(function () {
app.set('port', port); app.set('port', port);
app.set('view engine', 'ejs'); app.set('view engine', 'ejs');
@ -64,18 +72,13 @@ app.use(session({
})); }));
/* 'default', 'short', 'tiny', 'dev' */ /* 'default', 'short', 'tiny', 'dev' */
app.use(methodoverride()); // app.use(methodoverride());
app.use(bodyparser.urlencoded({ 'extended': false })); app.use(bodyparser.urlencoded({ 'extended': false }));
// parse application/json // parse application/json
app.use(bodyparser.json()); app.use(bodyparser.json());
// apicache.options({ 'debug': true });
// const cache = apicache.middleware;
// logger.debug(apicache);
app.use(function(req, res, next) { app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'X-Requested-With'); res.header('Access-Control-Allow-Headers', 'X-Requested-With');
@ -107,14 +110,25 @@ app.get('/cinema/:id', events.getCinema);
app.route('/poly').get(polys); app.route('/poly').get(polys);
app.get('/slack', function(req, res) { app.get('/slack', function(req, res) {
// res.render('pages/slackV2-min'); res.render('pages/slackV2-min');
res.render('pages/slackV2'); // res.render('pages/slackV2');
}); });
app.get('/temp', function(req, res) { app.get('/temp', function(req, res) {
res.render('pages/temp'); res.render('pages/temp');
}); });
app.get('/weather', /* cache('1 hour'),*/ (req, res) => {
weather.doGetOpenWeather()
.then((d) => {
res.send(d);
}).catch((e) => {
console.error(e);
res.status(500).send('There was an error!');
});
});
const tfile = 'fb-token.json'; const tfile = 'fb-token.json';
// Instanciate a fitbit client. See example config below. // Instanciate a fitbit client. See example config below.