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) {
res.send('Hello from <a href="http://appfog.com">AppFog.com</a>');
});
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();
app.configure(function() {
app.set('port', process.env.VCAP_APP_PORT || 3000);
app.use(express.logger('dev'));
/* 'default', 'short', 'tiny', 'dev' */
app.use(express.methodOverride());
app.use(express.methodOverride());
app.use(express.bodyParser());
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, 'www')));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
app.use(express.errorHandler({ 'dumpExceptions': true, 'showStack': true }));
});
/**
* Routing handlers
*/
/**
* create the server
*/
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 () {
this.getBTC();
// this.getBalance();
// this.getBalance();
const now = new Date();
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);
this.set('btcdata', data);
// total = myBTC * g;
// total = myBTC * g;
},
'getBTC': function () {
console.log('>> getBTC');
@ -106,7 +106,7 @@ const BitcoinModel = Backbone.Model.extend({
'data': '',
'dataType': 'json',
'timeout': 10000,
// contentType: ('application/json'),
// contentType: ('application/json'),
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
@ -139,7 +139,7 @@ const BitcoinModel = Backbone.Model.extend({
'data': '',
'dataType': 'json',
'timeout': 10000,
// contentType: ('application/json'),
// contentType: ('application/json'),
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
@ -159,7 +159,7 @@ const BitcoinModel = Backbone.Model.extend({
});
},
'btcFromSocket': function (data) {
let self = this;
const self = this;
console.log('>> btc from the socket', data);
const gbp = data.bpi.GBP.rate_float;
const usd = data.bpi.USD.rate_float;
@ -172,7 +172,7 @@ const BitcoinModel = Backbone.Model.extend({
self.recalc();
},
'balanceFromSocket': function (data) {
let self = this;
const self = this;
console.log('>> balance from the socket', data);
const balance = data.balance;
@ -191,10 +191,10 @@ const Bitcoin = Backbone.View.extend({
'render': function () {
const btcdata = this.model.get('btcdata');
const balance = this.model.get('balance');
// console.log(`Balance: ${btcdata.balance.toFixed(4)}`);
// console.log(btcdata.lastGBP);
// console.log(`Balance: ${btcdata.balance.toFixed(4)}`);
// console.log(btcdata.lastGBP);
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))}`;
let trendClass = '';
@ -203,7 +203,7 @@ const Bitcoin = Backbone.View.extend({
else if (btcdata.trend < 1.00)
trendClass = 'trendDown';
else
trendClass = '';
trendClass = '';
this.$trend.removeClass();
this.$trend.addClass(trendClass);

View File

@ -10,9 +10,9 @@ const TrainModel = Backbone.Model.extend({
'initialize': function () {
const fromStation = this.get('from');
const toStation = this.get('to');
const url = `/getnexttraintimes?from=${ fromStation }&to=${ toStation}`;
const routeUrl = `/gettrains?from=${ fromStation }&to=${ toStation}`;
const target = fromStation + toStation;
const url = `/getnexttraintimes?from=${ this.get('from') }&to=${ this.get('to')}`;
const routeUrl = `/gettrains?from=${ this.get('from') }&to=${ this.get('to')}`;
const target = this.get('from') + this.get('to');
this.set('url', url);
this.set('routeUrl', routeUrl);
this.set('target', target);
@ -30,7 +30,7 @@ const TrainModel = Backbone.Model.extend({
if (hours >= 6)
this.getTrain();
else
this.set('trainData', { 'eta':'OFF', 'sta': 'OFF' });
this.set('trainData', { 'eta':'OFF', 'sta': 'OFF' });
const trainUpdateFn = function () {
this.update();
@ -69,32 +69,32 @@ const TrainModel = Backbone.Model.extend({
if (this.get('visible') === true)
this.set('visible', false);
else
$.ajax({
'type': 'GET',
'url': url,
'data': '',
'dataType': 'json',
$.ajax({
'type': 'GET',
'url': url,
'data': '',
'dataType': 'json',
'timeout': 10000,
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
'timeout': 10000,
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
},
'success': function (data) {
// getTrainsCB(data);
// console.log('Got', data);
},
'success': function (data) {
// getTrainsCB(data);
// console.log('Got', data);
self.set('route', data);
self.set('visible', true);
},
'error': function (xhr, type) {
console.error('ajax error');
console.error(xhr);
console.error(type);
}
});
self.set('route', data);
self.set('visible', true);
},
'error': function (xhr, type) {
console.error('ajax error');
console.error(xhr);
console.error(type);
}
});
}
});
@ -161,8 +161,8 @@ const TrainView = Backbone.View.extend({
const time = item.sta !== null ? item.sta : `D ${item.std}`;
const status = item.eta !== null ? item.eta : item.etd;
services.push({ 'location':dest.locationName, 'time':time, 'status':status, 'platform':platform, 'cancel':item.cancelReason, 'type':'bus' });
// ws = ws + `<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"><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 }<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');
}
else
this.$traintext.removeClass('mui--show').addClass('mui--hide');
this.$traintext.removeClass('mui--show').addClass('mui--hide');
},
'initView': function () {
// el: $('#myView').get(0)
// el: $('#myView').get(0)
const self = this;
const target = this.model.get('target');
const html = `<div class='mui-col-xs-12 mui-col-md-6'>${target.toUpperCase()}: <button class="mui-btn mui-btn--flat" id="${target}"></button></div>`;
this.$html = $(html);
this.$html.on('click', function () {
// console.log(self)
// console.log(self)
self.model.getRoute();
});
this.$trains.append(this.$html);
// this.el = `#${target}`;
// this.el = `#${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": {
"moment": "^2.18.1",
"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 = { };
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'])
.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': true, // Hoist variable declarations
'if_return': true, // Optimize if-s followed by return/continue
'join_vars': true, // Join var declarations
'cascade': true, // Try to cascade `right` into `left` in sequences
'side_effects': true, // Drop side-effect-free statements
'warnings': true, // Warn about potentially dangerous optimizations/code
'global_defs': {} // global definitions
} }))
.pipe(gulp.dest(`${dest }/js`));
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(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': true, // Hoist variable declarations
'if_return': true, // Optimize if-s followed by return/continue
'join_vars': true, // Join var declarations
'cascade': true, // Try to cascade `right` into `left` in sequences
'side_effects': true, // Drop side-effect-free statements
'warnings': true, // Warn about potentially dangerous optimizations/code
'global_defs': {} // global definitions
} }))
.pipe(gulp.dest(`${dest }/js`));
});
gulp.task('customMUI', function() {
@ -57,7 +57,7 @@ gulp.task('customMUI', function() {
.pipe(sass({ 'outputStyle': 'compressed' }).on('error', sass.logError))
// .pipe(cssnano())
.pipe(rename('mui.custom.css'))
.pipe(gulp.dest(`${dest }/css`));
.pipe(gulp.dest(`${dest}/css`));
});
gulp.task('vendor', function() {
@ -65,18 +65,26 @@ gulp.task('vendor', function() {
'bower_components/zepto/zepto.min.js',
'bower_components/ejs/ejs.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(uglify({ 'mangle': false }))
.pipe(gulp.dest(`${dest }/js`));
.pipe(concat('vendor.js'))
/*.pipe(uglify({ 'mangle': false }))*/
.pipe(gulp.dest(`${dest }/js`));
});
gulp.task('fonts', function() {
return gulp.src('./fonts.list')
.pipe(googleWebFonts(fontOptions))
.pipe(gulp.dest(`${dest }/fonts`))
;
.pipe(googleWebFonts(fontOptions))
.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 dateFormat = require('dateformat');
const jsonfile = require('jsonfile');
let fs = require('fs');
//var nano = require('nano')('http://martind2000:1V3D4m526i@localhost:5984');
const fs = require('fs');
// var nano = require('nano')('http://martind2000:1V3D4m526i@localhost:5984');
const logger = require('log4js').getLogger();
const calHandler = require('./today/calHandler');
const swedishWord = require('./today/swedishword');
@ -20,8 +20,10 @@ const mdMailer = require('./today/mailer');
const mdFitbit = require('./today/fitbit');
const todayFTSE = require('./today/todayftse');
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
*/
logger.level = 'debug';
const credentials = {
"username": "25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix",
"password": "8e417af1b0462ca55726848846cc6b8696fc76defe9d1864cbc334be59549e0c",
"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": "today"
'username': '25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix',
'password': '8e417af1b0462ca55726848846cc6b8696fc76defe9d1864cbc334be59549e0c',
'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': 'today'
};
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);
require('sugar-date');
let Sugar = require('sugar');
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);
} 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;
if (Array.prototype.reduce)
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 todayCache = {
last: 0, data: {
trains: {last: 0, data: []},
weather: {},
history: [],
today: '',
tv: {entries: []},
cal: {today: [], tomorrow: [], week: []},
swedish: {},
fitbit: {},
ftse: {}
}, expire: ((60 * 1000) * 60)
'last': 0, 'data': {
'trains': { 'last': 0, 'data': [] },
'weather': {},
'history': [],
'today': '',
'tv': { 'entries': [] },
'cal': { 'today': [], 'tomorrow': [], 'week': [] },
'swedish': {},
'fitbit': {},
'ftse': {}
}, 'expire': ((60 * 1000) * 60)
};
const file = __dirname + '/' + 'newdata.json';
let htmlfile = __dirname + '/' + 'today.html';
const file = `${__dirname }/` + 'newdata.json';
const 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) {
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) {
@ -187,280 +191,276 @@ function reduceTrains(d) {
}*/
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);
}
}
for (const 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];
};
}
return this.map(fn).indexOfOld(e);
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);
}
};
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;
const d = new Date();
let nextYear = (parseInt(d.getFullYear()) + 1).toString() + '-01-01';
'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;
// let d = new Date();
console.log(d.daysUntil('beginning of next year'));
const daysSinceStart = d.daysSince('beginning of this year');
const daysRemaining = d.daysUntil('beginning of next year');
let d = new Sugar.Date();
console.log('>> D', d);
const nextYear = `${(parseInt(d.getFullYear()) + 1).toString() }-01-01`;
todayCache.data.history = [];
s = '<strong>' + d.format('{Weekday} {Month} {dd}, {yyyy}') + '</strong> - ';
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 = `<strong>${ d.format('{Weekday} {Month} {dd}, {yyyy}') }</strong> - `;
/*
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 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);
todayCache.data.today = s;
},
refreshTrain: function () {
logger.debug(s);
todayCache.data.today = s;
},
'refreshTrain': function () {
trains.updateTrains()
.then((d) => {
'use strict';
trains.updateTrains()
.then((d) => {
'use strict';
d = reduceTrains(d);
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});
todayCache.data.trains.data = d;
todayCache.data.trains.last = new Date();
})
.catch((e) => {
'use strict';
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);
});
},
refreshWeather: function () {
weather.newDoGetWeather()
.then((d) => {
todayCache.data.weather = d;
logger.info('Updating weather');
broadcastWeather();
}).catch((e) => {
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);
// 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 () {
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);
});
/*mdFitbit.getYesterdayFitbit()
.then((d) => {
todayCache.data.fitbit = 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});
}
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();
loadData();
if (runable())
module.exports.preLoadToday();
// Module.exports.preLoadToday();
}, 5000);
setTimeout(function () {
// mdMailer.sendEmailV1(todayCache, __dirname);
// saveToDB(todayCache);
saveData();
// mdMailer.sendEmailV1(todayCache, __dirname);
// saveToDB(todayCache);
// saveData();
}, 45000);
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});
// mdMailer.sendEmailV1(todayCache, __dirname);
}, (60000));
cron.schedule('30 6 * * *', function () {
if (runable()) {
module.exports.preLoadToday();
}
if (runable())
module.exports.preLoadToday();
return -1;
return -1;
});
cron.schedule('0 */1 * * *', function () {
// Module.exports.refreshTrainAndWeather();
// this.refreshTrain();
module.exports.refreshWeather();
// Module.exports.refreshTrainAndWeather();
// this.refreshTrain();
module.exports.refreshWeather();
return -1;
return -1;
});
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 () {
mdMailer.sendEmailV1(todayCache, __dirname);
saveToDB(todayCache);
// Console.log('tick');
return -1;
// mdMailer.sendEmailV1(todayCache, __dirname);
// saveToDB(todayCache);
// Console.log('tick');
return -1;
});

View File

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

View File

@ -4,24 +4,24 @@ var STRING = require('string');
var logger = require('log4js').getLogger();
module.exports = {
getTechHistory: function() {
'getTechHistory': function() {
var url;
var d;
var day;
var month;
var monthNames = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
d = new Date();
@ -32,15 +32,15 @@ module.exports = {
url = ['http://www.computerhistory.org/tdih/', month, '/', day].join('');
logger.debug(url);
return new Promise(function(resolve, reject) {
'use strict';
request(url, function(err, resp, body) {
if (err) {
if (err)
// Logger.error(err);
return reject(err);
// Throw err;
}
// Throw err;
var $ = cheerio.load(body);
var tdihbody = $('#tdihbody');
@ -57,29 +57,29 @@ module.exports = {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
return reject(error);
}
});
});
}, getHistory: function() {
}, 'getHistory': function() {
var url;
var d = new Date();
var day;
var month;
var monthNames = [
'january',
'february',
'march',
'april',
'may',
'june',
'july',
'august',
'september',
'october',
'november',
'december'
'january',
'february',
'march',
'april',
'may',
'june',
'july',
'august',
'september',
'october',
'november',
'december'
];
month = monthNames[d.getMonth()];
@ -87,20 +87,18 @@ module.exports = {
day = d.getDate();
url = [
'http://www.bbc.co.uk/scotland/history/onthisday/', month, '/',
day
'http://www.bbc.co.uk/scotland/history/onthisday/', month, '/',
day
].join('');
logger.debug(url);
return new Promise(function(resolve, reject) {
request(url, function(err, resp, body) {
if (err) {
if (err)
// Logger.error(err);
return reject(err);
// Throw err;
}
// Throw err;
var $ = cheerio.load(body);
@ -108,52 +106,48 @@ module.exports = {
var output = [];
nbody.find('.story > p').each(function(div) {
var s = $(this).text();
if (s.indexOf('Today\'s recipe:') == -1) {
if (s.indexOf('Today\'s recipe:') == -1)
output.push(s);
}
});
return resolve(output);
}, function(error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
return reject(error);
}
});
});
},
updateHistory: function() {
'updateHistory': function() {
'use strict';
var output = [];
return new Promise(function(resolve, reject) {
module.exports.getHistory()
.then((d)=> {
.then((d) => {
output = d;
output = d;
module.exports.getTechHistory()
.then((d) => {
output = output.concat(d);
module.exports.getTechHistory()
.then((d) => {
output = output.concat(d);
return resolve(output);
})
.catch((e) => {
logger.error(e);
return reject(e);
});
})
.catch((e) => {
logger.error(e);
return reject(e);
});
})
return resolve(output);
})
.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 logger = require('log4js').getLogger();
const forecastOptions = {
APIKey: '9ad2a41d420f3cf4960571bb886f710c', units: 'uk2'
'APIKey': '9ad2a41d420f3cf4960571bb886f710c', 'units': 'uk2'
};
module.exports = {
newDoGetWeather: function() {
'use strict';
return new Promise(function(resolve, reject) {
logger.info('New Retrieving weather..');
const j = {};
const forecast = new Forecast(forecastOptions);
forecast.get(55.95, -4.566667,
{units: 'uk2'},
function(err, res, data) {
if (err) {
return reject(err);
}
'newDoGetWeather': function() {
'use strict';
return new Promise(function(resolve, reject) {
logger.info('New Retrieving weather..');
const j = {};
const forecast = new Forecast(forecastOptions);
forecast.get(55.95, -4.566667,
{ 'units': 'uk2' },
function(err, res, data) {
if (err)
return reject(err);
const tempMin = parseInt(data.daily.data[0].temperatureMin);
const 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;
j.later = data.daily.summary;
j.alerts = data.alerts || {};
j.data = data;
j.currently = data.currently.summary;
j.today = data.daily.data[0].summary;
j.later = data.daily.summary;
j.alerts = data.alerts || {};
j.data = data;
const fs = STRING(j.currently).endsWith('.') ? '' : '.';
if (tempMax === tempMin) {
j.currently += fs + ' Around ' + tempMin.toString() + ' degrees.';
}
else {
j.currently += fs + ' Around ' + tempMin.toString() + ' to ' + tempMax.toString() + ' degrees.';
}
// logger.debug(j);
return resolve(j);
});
const fs = STRING(j.currently).endsWith('.') ? '' : '.';
if (tempMax === tempMin)
j.currently += `${fs } Around ${ tempMin.toString() } degrees.`;
else
j.currently += `${fs } Around ${ tempMin.toString() } to ${ tempMax.toString() } degrees.`;
// logger.debug(j);
return resolve(j);
});
}
});
}
};

View File

@ -8,34 +8,48 @@ const util = require('util');
const jsonfile = require('jsonfile');
const fs = require('fs');
const logger = require('log4js').getLogger();
const weather = require('openweather-apis');
weather.setAPPID('936a0ed9eb23b95cf08fc9f693c24264');
weather.setLang('en');
weather.setCity('Glasgow City');
const forecastOptions = {
APIKey: '0657dc0d81c037cbc89ca88e383b6bbf',
units: 'uk2'
'APIKey': '0657dc0d81c037cbc89ca88e383b6bbf',
'units': 'uk2'
};
const file = __dirname + '/' + 'data.json';
const file = `${__dirname }/` + 'data.json';
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 () {
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;
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 || {};
});
}
};
function doGetOpenWeather() {
return new Promise((resolve, reject) => {
weather.getWeatherForecastForDays(5, function(err, wData) {
if (err)
return reject(err);
else
return resolve(wData);
});
});
}
module.exports.doGetWeatherOutlook();
module.exports.doGetWeatherOutlook = doGetWeatherOutlook;
module.exports.doGetOpenWeather = doGetOpenWeather;

View File

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

View File

@ -20,7 +20,7 @@
<% include ../partials/links %>
<div id='weather' class="mui-panel"></div>
<div id='weather'></div>
</div>
<script type="text/template" id="password-template">
@ -31,20 +31,27 @@
<script src="live/js/app.js"></script>
<script>
;(function (w) {
navigator.geolocation.getCurrentPosition((show_weather) => {
/*navigator.geolocation.getCurrentPosition((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()});
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'})});
const btcModel = new BitcoinModel();
webSocketModel.setBTC(btcModel);
w.wview = new WView({'el': document.getElementById('weather')});
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: 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();
})(window);
})(window);
</script>
</html>

View File

@ -20,7 +20,7 @@
<% include ../partials/links %>
<div id='weather' class="mui-panel"></div>
<div id='weather'></div>
</div>
<script type="text/template" id="password-template">
@ -37,37 +37,38 @@
<script src="js/modules/bitcoin.js"></script>
<script src="js/modules/fx.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="app.js"></script>
<script>
// slackV2.ejs
(function (w) {
navigator.geolocation.getCurrentPosition((show_weather) => {
w.weather = new WeatherSlim({model: new WeatherModel({geo:show_weather})});
});
// slackV2.ejs
(function (w) {
/*navigator.geolocation.getCurrentPosition((show_weather) => {
w.weather = new WeatherSlim({model: new WeatherModel({geo:show_weather})});
});*/
const webSocketModel = new SOCKETMANAGER();
const webSocketModel = new SOCKETMANAGER();
const btcModel = new BitcoinModel();
webSocketModel.setBTC(btcModel);
const btcModel = new BitcoinModel();
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: 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.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'})});
// console.log(PasswordView);
w.passwords = new PasswordView();
// console.log(PasswordView);
w.passwords = new PasswordView();
webSocketModel.turnOn();
})(window);
w.wview = new WView({'el': document.getElementById('weather')});
webSocketModel.turnOn();
})(window);
</script>
</html>

View File

@ -9,9 +9,9 @@
<meta name="Author" content=""/>
<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="css/weather.css" rel="stylesheet" type="text/css"/>
</head>
<body>

View File

@ -9,8 +9,10 @@
<meta name="Author" content=""/>
<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/weather.css" rel="stylesheet" type="text/css"/>
<script src="libs/zepto.min.js"></script>
<script src="libs/microevent.js"></script>

View File

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