silvrgit/lib/today.js

447 lines
11 KiB
JavaScript
Raw Normal View History

2016-03-08 21:52:21 +00:00
/**
* Created by marti on 30/01/2016.
*/
let http = require('http'), request = require('request'), cheerio = require(
'cheerio'), util = require('util');
const cron = require('node-cron');
const dateFormat = require('dateformat');
const jsonfile = require('jsonfile');
let fs = require('fs');
2016-12-22 16:24:06 +00:00
//var nano = require('nano')('http://martind2000:1V3D4m526i@localhost:5984');
const log4js = require('log4js');
const logger = log4js.getLogger();
const calHandler = require('./today/calHandler');
const swedishWord = require('./today/swedishword');
const weather = require('./today/weather');
const trains = require('./today/trains');
const history = require('./today/history');
const mdMailer = require('./today/mailer');
const mdFitbit = require('./today/fitbit');
const todayFTSE = require('./today/todayftse');
const quotes = require('./today/quotes');
2016-12-22 16:24:06 +00:00
//var db_name = 'silvrgit';
//var dbCloudant = nano.use(db_name);
/*
We've moved to cloudant through IBM Bluemix for the database
https://25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix.cloudant.com/dashboard.html#usage
*/
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": "keeper"
2016-12-22 16:24:06 +00:00
};
const Cloudant = require('cloudant');
const cloudant = Cloudant({account: credentials.username, password: credentials.password});
2016-12-22 16:24:06 +00:00
const dbCloudant = cloudant.db.use(credentials.database);
2016-12-22 16:24:06 +00:00
2016-04-11 15:40:34 +00:00
require('sugar-date');
2016-10-05 14:09:12 +00:00
String.prototype.hashCode = function() {
if (Array.prototype.reduce) {
2016-10-23 22:52:59 +00:00
return this.split('').reduce(function(a,b) {a = ((a << 5) - a) + b.charCodeAt(0);return a & a},0);
2016-10-05 14:09:12 +00:00
} else {
let hash = 0, i, chr, len;
2016-10-23 22:52:59 +00:00
if (this.length == 0) return hash;
for (i = 0, len = this.length; i < len; i++) {
2016-10-05 14:09:12 +00:00
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
2016-10-23 22:52:59 +00:00
}
return hash;
2016-10-05 14:09:12 +00:00
}
2016-10-23 22:52:59 +00:00
};
2016-10-05 14:09:12 +00:00
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)
2016-03-08 21:52:21 +00:00
};
const file = __dirname + '/' + 'newdata.json';
let htmlfile = __dirname + '/' + 'today.html';
let eventEmitter;
2016-09-09 13:51:52 +00:00
function runable() {
2016-10-05 14:09:12 +00:00
try {
const now = new Date().getTime();
2016-09-09 13:51:52 +00:00
2016-10-05 14:09:12 +00:00
console.log('last updated', ((now - todayCache.last) / 60000));
2016-09-09 14:48:22 +00:00
if (now - todayCache.last < 3600000) {
2016-09-09 13:51:52 +00:00
return false;
2016-10-23 22:52:59 +00:00
} else {
2016-09-09 13:51:52 +00:00
todayCache.last = now;
return true;
}
}
2016-10-05 14:09:12 +00:00
catch (e) {
2016-09-09 13:51:52 +00:00
todayCache.last = new Date().getTime();
return true;
}
}
2016-10-05 14:09:12 +00:00
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
};
if (todayCache.data.weather.data.hasOwnProperty('alerts')) {
wData.alerts = todayCache.data.weather.data.alerts;
}
eventEmitter.emit('sendSocket', {id: 'weather', data: wData});
}
2016-09-09 13:51:52 +00:00
function loadData() {
console.log('Loading old data');
try {
todayCache = jsonfile.readFileSync(file);
}
2016-10-05 14:09:12 +00:00
catch (e) {
2016-09-09 13:51:52 +00:00
console.error('Could not load previous data');
}
}
2016-03-08 21:52:21 +00:00
function saveData() {
2016-09-09 13:51:52 +00:00
todayCache.last = new Date().getTime();
2016-03-31 22:00:47 +00:00
logger.info('Saving...');
jsonfile.writeFileSync(file, todayCache);
2016-03-08 21:52:21 +00:00
}
2016-03-24 17:09:42 +00:00
function saveToDB(data) {
2016-09-09 13:51:52 +00:00
saveData();
2016-10-05 14:09:12 +00:00
2016-03-31 22:00:47 +00:00
logger.debug('Inserting into couch...');
// Logger.info(util.inspect(obj));
2016-12-22 16:24:06 +00:00
dbCloudant.insert(data, function(err, body, header) {
2016-03-31 22:00:47 +00:00
if (err) {
logger.error('Error inserting into couch');
logger.error(err);
return;
}
});
2016-03-24 17:09:42 +00:00
}
2016-03-08 21:52:21 +00:00
function nth(d) {
2016-05-02 22:30:55 +00:00
// 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;
2016-10-05 14:09:12 +00:00
return Math.floor(n / 10) === 1 ? 'th' : (n % 10 === 1 ? 'st' : (n % 10 === 2 ? 'nd' : (n % 10 === 3 ? 'rd' : 'th')));
2016-03-08 21:52:21 +00:00
}
2016-03-08 21:52:21 +00:00
function dayNumber() {
const now = new Date();
const start = new Date(now.getFullYear(), 0, 0);
const diff = now - start;
const oneDay = 1000 * 60 * 60 * 24;
2016-03-31 22:00:47 +00:00
return Math.floor(diff / oneDay);
2016-03-08 21:52:21 +00:00
}
2016-03-24 17:09:42 +00:00
function breakDay() {
const now = new Date();
2016-10-05 14:09:12 +00:00
return {
year: now.getFullYear(),
month: parseInt(now.getMonth()) + 1,
day: now.getDate()
};
2016-03-24 17:09:42 +00:00
}
2016-10-23 22:52:59 +00:00
function reduceTrains(d) {
2016-10-05 14:09:12 +00:00
const titles = [], ta = [];
2016-10-05 14:09:12 +00:00
console.log('reducetrains',d);
for (let items in d) {
2016-10-23 22:52:59 +00:00
if (typeof d[items].title !== 'undefined') {
const hash = d[items].title.hashCode();
2016-10-23 22:52:59 +00:00
if (titles.indexOf(hash) === -1) {
titles.push(hash);
ta.push(d[items]);
}
}
2016-10-05 14:09:12 +00:00
}
2016-10-23 22:52:59 +00:00
return ta;
}
2016-10-05 14:09:12 +00:00
2016-03-08 21:52:21 +00:00
/**
* @return {number}
*/
function DayDiff(CurrentDate) {
const TYear = CurrentDate.getFullYear();
const TDay = new Date('January, 01, ' + (parseInt(TYear) + 1));
2016-03-31 22:00:47 +00:00
TDay.getFullYear(TYear);
let DayCount = (TDay - CurrentDate) / (1000 * 60 * 60 * 24);
2016-03-31 22:00:47 +00:00
DayCount = Math.round(DayCount);
2016-04-11 15:40:34 +00:00
const d = new Date();
2016-04-11 15:40:34 +00:00
DayCount = d.daysSince('beginning of this year');
2016-03-31 22:00:47 +00:00
return (DayCount);
2016-03-08 21:52:21 +00:00
}
2016-03-08 21:52:21 +00:00
Array.prototype.indexOfOld = Array.prototype.indexOf;
2016-03-31 22:00:47 +00:00
Array.prototype.indexOf = function(e, fn) {
if (!fn) {
return this.indexOfOld(e);
2016-10-23 22:52:59 +00:00
} else {
2016-03-31 22:00:47 +00:00
if (typeof fn === 'string') {
const att = fn;
2016-03-31 22:00:47 +00:00
fn = function(e) {
return e[att];
2016-04-11 15:40:34 +00:00
};
2016-03-08 21:52:21 +00:00
}
2016-03-31 22:00:47 +00:00
return this.map(fn).indexOfOld(e);
}
2016-03-08 21:52:21 +00:00
};
2016-03-08 21:52:21 +00:00
module.exports = {
2016-10-05 14:09:12 +00:00
setEmitter: function(newEmitter) {
console.log('Setting events', newEmitter);
eventEmitter = newEmitter;
}, getClock: function(req, res) {
2016-03-31 22:00:47 +00:00
// 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';
2016-04-11 15:40:34 +00:00
console.log(d.daysUntil('beginning of next year'));
const daysSinceStart = d.daysSince('beginning of this year');
const daysRemaining = d.daysUntil('beginning of next year');
2016-04-11 15:40:34 +00:00
2016-03-31 22:00:47 +00:00
todayCache.data.history = [];
2016-04-11 15:40:34 +00:00
s = '<strong>' + d.format('{Weekday} {Month} {dd}, {yyyy}') + '</strong> - ';
2016-10-05 14:09:12 +00:00
s = s + 'The ' + daysSinceStart + nth(daysSinceStart) + ' day of ' + dateFormat(
d,
2016-04-11 15:40:34 +00:00
'yyyy') + ', and there are ' + daysRemaining + ' days left until the end of the year.';
2016-03-31 22:00:47 +00:00
logger.debug(s);
todayCache.data.today = s;
2016-10-05 14:09:12 +00:00
},
2016-10-23 22:52:59 +00:00
refreshTrain: function() {
2016-10-05 14:09:12 +00:00
trains.updateTrains()
.then((d) => {
'use strict';
d = reduceTrains(d);
console.log('Trains: ', d);
eventEmitter.emit('sendSocket', {id: 'trains', data: d});
todayCache.data.trains.data = d;
todayCache.data.trains.last = new Date();
})
.catch((e)=> {
'use strict';
console.error(e);
});
},
2016-10-23 22:52:59 +00:00
refreshWeather: function() {
2016-03-31 22:00:47 +00:00
weather.newDoGetWeather()
.then((d) => {
todayCache.data.weather = d;
2016-10-05 14:09:12 +00:00
console.log('Updating weather');
broadcastWeather();
2016-03-31 22:00:47 +00:00
}).catch((e) => {
2016-10-05 14:09:12 +00:00
logger.error(e);
});
},
refreshTrainAndWeather: function() {
this.refreshTrain();
this.refreshWeather();
2016-03-31 22:00:47 +00:00
}, preLoadToday: function() {
module.exports.getTodayDate();
2016-10-05 14:09:12 +00:00
todayCache.data.cal = {today: [], tomorrow: [], week: []};
2016-03-31 22:00:47 +00:00
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);
});
2016-10-05 14:09:12 +00:00
calHandler.getSimpleCalV3(
'http://www.pogdesign.co.uk/cat/download_ics/60cfdff469d0490545d33d7e3b5c0bcc')
2016-03-31 22:00:47 +00:00
.then((d) => {
'use strict';
todayCache.data.tv = d;
})
.catch((e) => {
'use strict';
logger.error(e);
});
2016-05-02 22:30:55 +00:00
2016-06-23 11:04:25 +00:00
todayFTSE.getFTSE()
.then((d) => {
todayCache.data.ftse = d;
})
.catch((e) => {
logger.error(e);
});
2016-10-23 22:52:59 +00:00
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])
2016-10-05 14:09:12 +00:00
.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);
});
2016-05-02 22:30:55 +00:00
}
2016-03-31 22:00:47 +00:00
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)=> {
2016-05-02 22:30:55 +00:00
'use strict';
console.error(e);
});
2016-03-31 22:00:47 +00:00
todayCache.date = breakDay();
2016-10-23 22:52:59 +00:00
}, broadcast: function() {
2016-10-05 14:09:12 +00:00
console.log('BROADCAST');
broadcastWeather();
eventEmitter.emit('sendSocket', {id: 'trains', data: todayCache.data.trains.data});
2016-03-31 22:00:47 +00:00
}
2016-03-23 17:03:15 +00:00
};
2016-03-31 22:00:47 +00:00
setTimeout(function() {
2016-09-09 13:51:52 +00:00
loadData();
if (runable()) {
module.exports.preLoadToday();
}
2016-10-23 22:52:59 +00:00
//Module.exports.preLoadToday();
2016-09-09 13:51:52 +00:00
2016-03-31 16:12:25 +00:00
}, 5000);
2016-08-05 10:58:47 +00:00
2016-03-31 22:00:47 +00:00
setTimeout(function() {
2016-08-05 12:00:17 +00:00
// mdMailer.sendEmailV1(todayCache, __dirname);
2016-05-02 22:30:55 +00:00
// saveToDB(todayCache);
// saveData();
2016-03-31 16:12:25 +00:00
}, 45000);
2016-08-05 10:58:47 +00:00
2016-10-05 14:09:12 +00:00
setInterval(function() {
2016-10-23 22:52:59 +00:00
// EventEmitter.emit('sendSocket',{id:'weather',data:todayCache.data.weather});
// broadcastWeather();
// eventEmitter.emit('sendSocket', {id: 'trains', data: todayCache.data.trains.data});
2016-10-05 14:09:12 +00:00
}, (60000));
cron.schedule('30 6 * * *', function() {
2016-09-09 13:51:52 +00:00
if (runable()) {
module.exports.preLoadToday();
}
2016-03-31 22:00:47 +00:00
return -1;
2016-03-08 21:52:21 +00:00
});
2016-10-05 14:09:12 +00:00
2016-03-31 22:00:47 +00:00
cron.schedule('0 */1 * * *', function() {
2016-10-23 22:52:59 +00:00
// Module.exports.refreshTrainAndWeather();
// this.refreshTrain();
2016-10-05 14:09:12 +00:00
module.exports.refreshWeather();
return -1;
});
cron.schedule('*/15 * * * *', function() {
module.exports.refreshTrain();
2016-10-23 22:52:59 +00:00
// Module.exports.refreshWeather();
2016-10-05 14:09:12 +00:00
2016-03-31 22:00:47 +00:00
return -1;
2016-03-08 21:52:21 +00:00
});
2016-10-05 14:09:12 +00:00
cron.schedule('45 6 * * *', function() {
2016-04-12 08:16:21 +00:00
mdMailer.sendEmailV1(todayCache, __dirname);
2016-03-31 22:00:47 +00:00
saveToDB(todayCache);
// Console.log('tick');
return -1;
2016-03-08 21:52:21 +00:00
});
2016-10-05 14:09:12 +00:00