Fixing today, recurring stuff in the calendar. finally

This commit is contained in:
Martin Donnelly 2017-10-13 10:39:58 +01:00
parent 41090f9a44
commit c1be3c55de
12 changed files with 813 additions and 663 deletions

View File

@ -3,29 +3,66 @@ var logger = log4js.getLogger();
var calHandler = require('./today/calHandler');
require('sugar-date');
var cal = { 'today': [], 'tomorrow': [], 'week': [] };
var _cal_tmp = { 'today': [], 'tomorrow': [], 'week': [] };
for (var t = 0; t < calHandler.calendars.length;t++)
/*
for (var t = 0; t < calHandler.calendars.length;t++)
calHandler.getAdvancedCalV3(calHandler.calendars[t])
.then((d) => {
'use strict';
cal.today = cal.today.concat(d.today);
cal.tomorrow = cal.tomorrow.concat(d.tomorrow);
cal.week = cal.week.concat(d.week);
.then((d) => {
'use strict';
// cal.today = cal.today.concat(d.today);
// cal.tomorrow = cal.tomorrow.concat(d.tomorrow);
cal.week = cal.week.concat(d.week);
logger.error(cal);
})
.catch((e) => {
'use strict';
logger.error(e);
});
logger.info(cal);
})
.catch((e) => {
'use strict';
logger.error(e);
});
*/
for (const item of calHandler.calendars)
calHandler.getAdvancedCalV3(item)
.then((d) => {
'use strict';
// cal.today = cal.today.concat(d.today);
// cal.tomorrow = cal.tomorrow.concat(d.tomorrow);
cal.week = cal.week.concat(d.week);
logger.info(cal);
})
.catch((e) => {
'use strict';
logger.error(e);
});
/*calHandler.getSimpleCalV3(
'http://www.pogdesign.co.uk/cat/download_ics/60cfdff469d0490545d33d7e3b5c0bcc')
.then((d) => {
'use strict';
let tv = d;
logger.info(tv);
})
.catch((e) => {
'use strict';
logger.error(e);
});*/
/*calHandler.getAdvancedCalV3(calHandler.calendars[4])
.then((d) => {
'use strict';
// cal.today = cal.today.concat(d.today);
// cal.tomorrow = cal.tomorrow.concat(d.tomorrow);
cal.week = cal.week.concat(d.week);
logger.error(cal);
})
.catch((e) => {
'use strict';
logger.error(e);
});*/

File diff suppressed because one or more lines are too long

31
lib/test.js Normal file
View File

@ -0,0 +1,31 @@
const http = require('http');
const request = require('request');
const cheerio = require('cheerio');
const util = require('util');
const cron = require('node-cron');
const dateFormat = require('dateformat');
const jsonfile = require('jsonfile');
const fs = require('fs');
const LocalStorage = require('node-localstorage').LocalStorage;
// var nano = require('nano')('http://martind2000:1V3D4m526i@localhost:5984');
const logger = require('log4js').getLogger();
const Sugar = require('sugar');
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 todayFTSE = require('./today/todayftse');
const quotes = require('./today/quotes');
history.updateHistory()
.then((d) => {
'use strict';
logger.debug('History result: ', d);
})
.catch((e) => {
'use strict';
console.error(e);
});

View File

@ -1,17 +1,19 @@
const request = require('request');
const log4js = require('log4js');
const logger = log4js.getLogger();
const logger = log4js.getLogger('calHandler');
const STRING = require('string');
const util = require('util');
const Elapsed = require('elapsed');
const Sugar = require('sugar');
Sugar.extend();
logger.level = 'debug';
function processICAL(ical) {
'use strict';
logger.info('+ processICAL');
const workingBlock = [];
let workingBlock = [];
const segments = {
'meetingStartID': 'DTSTART;TZID=Europe/London:',
'meetingStartAlt': 'DTSTART:',
@ -39,8 +41,13 @@ function processICAL(ical) {
}
function processRecurrence(workBlock) {
const _workBlock = workBlock;
// logger.debug('Processing recurrence...');
const _workBlock = Object.assign({}, workBlock);
const dateLimit = new Date().reset('month').addMonths(2);
const recurArray = [];
logger.info('---===---');
logger.debug('>> Processing recurrence...');
logger.debug(`Expanding ${_workBlock.summary}`);
logger.debug('DateLimit:', dateLimit);
// logger.debug('Processing recurrence...');
const weekBits = { 'SU': 0, 'MO': 1, 'TU': 2, 'WE': 3, 'TH': 4, 'FR': 5, 'SA': 6 };
@ -49,6 +56,7 @@ function processICAL(ical) {
const dayNum = now.getDay();
const month = now.getMonth();
const year = now.getFullYear();
const byDayRegEx = /(\d)(\w.)/;
const recurSettings = { 'freq': null, 'wkst': null, 'until': null, 'bymonth': null, 'bymonthday': null, 'interval': null, 'byday': null };
@ -65,20 +73,26 @@ function processICAL(ical) {
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();
return null;
const _until = Date.create(recurSettings.until).isPast();
if (_until) {
logger.warn('EXPIRED!!');
return null;
}
}
if (recurSettings.freq !== null) {
// logger.debug(_workBlock);
let 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;
const origStart = new Date(_workBlock.dtstart);
const origEnd = new Date(_workBlock.dtend);
const _dstart = new Date(_workBlock.dtstart);
const _dend = new Date(_workBlock.dtend);
logger.debug('>> origStart', origStart);
const _d = origStart.getDate();
const _m = origStart.getMonth();
@ -87,57 +101,141 @@ function processICAL(ical) {
const _secs = origStart.getSeconds();
const distance = origEnd - origStart;
// Sugar.Date()
_workBlock.details = {
_d,
_m,
_h,
_min,
_secs,
distance
};
logger.debug('freq:', recurSettings.freq);
if (recurSettings.freq === 'YEARLY') {
logger.warn('YEARLY');
if (recurSettings.bymonth !== null && recurSettings.bymonthday !== null) {
// ok, a day and month.
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;
let _yearCount = year;
logger.debug('>> Yearly with specific month / day');
let newBlock;
newStart = new Date().set({ 'year':_yearCount, 'month': recurSettings.bymonth - 1, 'day': recurSettings.bymonthday, 'hour':_h, 'minutes':_min, 'seconds':_secs });
newEnd = new Date(_dstart).addMilliseconds(distance);
do {
newBlock = Object.assign({}, _workBlock);
newBlock.dstart = new Date(newStart);
newBlock.dend = new Date(newEnd);
recurArray.push(newBlock);
_yearCount++;
newStart = new Date().set({ 'year':_yearCount, 'month': recurSettings.bymonth - 1, 'day': recurSettings.bymonthday, 'hour':_h, 'minutes':_min, 'seconds':_secs });
newEnd = new Date(_dstart).addMilliseconds(distance);
}
while(newStart < dateLimit);
}
else if (recurSettings.bymonth === null && recurSettings.bymonthday === null) {
logger.debug('>> Yearly no specific month / day');
// extract month and year from dtstart
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;
let newBlock;
do {
newBlock = Object.assign({}, _workBlock);
newBlock.dtstart = new Date(_dstart);
newBlock.dtend = new Date(_dend);
logger.info(newBlock.dtstart.medium());
recurArray.push(newBlock);
_dstart.advance({ 'year':1 });
_dend.advance({ 'year':1 });
}
while(_dstart < dateLimit);
}
return _workBlock;
// logger.info('** recurArray', recurArray);
return recurArray;
}
if (recurSettings.freq === 'MONTHLY')
if (recurSettings.bymonthday !== null) {
// ok, a day and month.
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;
if (recurSettings.freq === 'MONTHLY' ) {
const interval = parseInt(recurSettings.interval, 10) || 1;
logger.warn(`MONTHLY - ${interval}`);
let newBlock;
if (recurSettings.byday === null)
do {
newBlock = Object.assign({}, _workBlock);
newBlock.dtstart = new Date(_dstart);
newBlock.dtend = new Date(_dend);
logger.info(newBlock.dtstart.medium());
recurArray.push(newBlock);
_workBlock.dtstart = newStart;
_workBlock.dtend = newEnd;
_dstart.addMonths(interval);
_dend.addMonths(interval);
}
while(_dstart < dateLimit);
else {
logger.warn('BYDAY!!! ', recurSettings.byday);
_dstart.setUTC(true);
const byday = byDayRegEx.exec(recurSettings.byday);
const dayNumber = weekBits[byday[2]];
const stepCount = parseInt(byday[1], 10) - 1;
do {
const _findSun = new Date.create(_dstart, { 'fromUTC': true } ).reset('month');
const firstDay = _findSun.getDay();
// find first occurance of the wanted day.
if (firstDay !== dayNumber) {
const add = (dayNumber - firstDay + 7) ;
_findSun.addDays(add).addWeeks(stepCount);
}
else
_findSun.addWeeks(stepCount);
newBlock = Object.assign({}, _workBlock);
newBlock.dtstart = new Date(_findSun).addMilliseconds(_workBlock.timeStartMS);
newBlock.dtend = new Date(_findSun).addMilliseconds(_workBlock.timeEndMS);
logger.info(newBlock.dtstart.medium());
recurArray.push(newBlock);
// all done, next.
_dstart.reset('month').addDays(32);
_dend.reset('month').addDays(32);
}
while(_dstart < dateLimit);
// something
}
if (recurSettings.freq === 'WEEKLY' && recurSettings.interval === null) {
const byDayBit = recurSettings.byday.split(',')[0];
const byDayNumber = weekBits[byDayBit];
if (byDayNumber >= dayNum) {
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;
}
return recurArray;
}
if (recurSettings.freq === 'WEEKLY') {
const interval = parseInt(recurSettings.interval, 10) || 1;
logger.warn(`WEEKLY - ${interval}`);
let newBlock;
do {
newBlock = Object.assign({}, _workBlock);
newBlock.dtstart = new Date(_dstart);
newBlock.dtend = new Date(_dend);
logger.info(newBlock.dtstart.medium());
recurArray.push(newBlock);
_dstart.addWeeks(interval);
_dend.addWeeks(interval);
}
while(_dstart < dateLimit);
}
return recurArray;
}
// if we get here we've skipped everything just return the _workblock
return _workBlock;
return [];
}
function processBlock(block) {
let _wb;
let workBlock = {
const workBlock = {
'summary': '',
'dtstart': null,
'dtend': null,
@ -146,7 +244,9 @@ function processICAL(ical) {
'timeEnd': null,
'duration': 0,
'combined': '',
'recur': null
'recur': null,
'timeStartMS': null,
'timeEndMS': null
};
let alarmFlag = false, ws, blockStep;
for (let step = 0; step < block.length; step++) {
@ -170,17 +270,17 @@ function processICAL(ical) {
}
if (blockStep.indexOf(segments.meetingStartAlt) >= 0) {
ws = STRING(block[step].split(segments.meetingStartAlt)[1]).collapseWhitespace().s;
console.log('>> ws', 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);
// 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 = new Sugar.Date(ws).raw;
console.log('>> date', workBlock.dtend);
// console.log('>> date', workBlock.dtend);
}
if (blockStep.indexOf(segments.meetingStartAltOther) >= 0) {
@ -190,7 +290,7 @@ function processICAL(ical) {
}
if (blockStep.indexOf(segments.meetingEndAltOther) >= 0) {
ws = STRING(block[step].split(segments.meetingEndAltOther)[1]).collapseWhitespace().s;
console.log('>> ws', ws);
// console.log('>> ws', ws);
// workBlock.dtend = Date.create(ws);
workBlock.dtend = new Sugar.Date(ws).raw;
}
@ -204,34 +304,23 @@ function processICAL(ical) {
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)
if (!Array.isArray(_wb)) {
workBlock = _wb;
}
else {
logger.error('We made an array');
}
}
// logger.debug(workBlock);
// let d = new Sugar.Date();
if (workBlock.dtstart !== null) {
// 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.timeStartMS = ((workBlock.dtstart.getHours() * 60 * 60 ) + (workBlock.dtstart.getMinutes() * 60 ) + workBlock.dtstart.getSeconds()) * 1000;
// console.log('>> workBlock.timeStart', workBlock.timeStart);
workBlock.combined = `<em>${workBlock.timeStart}</em> - '`;
workBlock.long = `<em>${Sugar.Date(workBlock.dtstart).format('{Weekday}').raw}, ${workBlock.timeStart}</em> - `;
console.log('>> workBlock.long', workBlock.long);
// console.log('>> workBlock.long', workBlock.long);
}
workBlock.combined = workBlock.combined + workBlock.summary;
workBlock.longcombined = workBlock.long + workBlock.summary;
if (workBlock.dtend !== null)
if (workBlock.dtend !== null) {
workBlock.timeEnd = Sugar.Date(workBlock.dtend).format('{24hr}:{mm}:{ss}').raw;
workBlock.timeEndMS = ((workBlock.dtend.getHours() * 60 * 60 ) + (workBlock.dtend.getMinutes() * 60 ) + workBlock.dtend.getSeconds()) * 1000;
}
if (workBlock.dtstart !== null && workBlock.dtend !== null) {
const elapsedTime = new Elapsed(workBlock.dtstart, workBlock.dtend);
@ -243,6 +332,12 @@ function processICAL(ical) {
return workBlock;
}
function buildRecurranceArray(wb) {
const _wb = processRecurrence(wb);
return _wb;
}
const lines = ical.split('\r\n'), l = lines.length;
let counter = 0;
@ -272,11 +367,21 @@ function processICAL(ical) {
counter = counter + subcounter;
const b = processBlock(subBlock);
if (Array.isArray(b))
logger.error('!returned an array...');
else
if (b.dtstart !== null)
workingBlock.push(b);
if (!b.recur ) {
if (Array.isArray(b))
logger.error('!returned an array...');
else
if (b.dtstart !== null)
workingBlock.push(b);
}
else {
// logger.warn('We need to spread the recurrance!!');
// logger.debug(b);
const recurBlocks = buildRecurranceArray(b);
if (recurBlocks && recurBlocks.length > 0)
workingBlock = workingBlock.concat(recurBlocks);
}
}
logger.info('- processICAL');
@ -290,7 +395,9 @@ module.exports = {
'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'],
'https://calendar.google.com/calendar/ical/i8dglj12p5nuv20sbjmun5s588%40group.calendar.google.com/private-c8adccb41e56d6a2f285078aaed313f5/basic.ics',
'https://calendar.google.com/calendar/ical/qppj4ebvdur1qui4v0fdpl7l70%40group.calendar.google.com/private-b5071cb2c3fe49544ffbbd08645088f1/basic.ics',
'https://calendar.google.com/calendar/ical/8h3vi3rd5rvpfe11klvgre0q4c%40group.calendar.google.com/private-e9df93163a7046658946be45fb08db6f/basic.ics'],
'jsonBlock': [],
'getTodaysSimple': function() {
'use strict';
@ -299,13 +406,14 @@ module.exports = {
'entries': []
};
for (let t = 0; t < this.jsonBlock.length; t++) {
// 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)
const _td = new Date.create('today');
const _tm = new Date.create('tomorrow');
today.entries = this.jsonBlock.filter((item) => {
if (!item || !item.dtstart || !item.dtend) return false;
today.entries.push(this.jsonBlock[t]);
}
return item.dtstart.isBetween(_td, _tm) || item.dtend.isBetween(_td, _tm);
});
logger.info('- getTodaysSimple');
return today;
@ -317,10 +425,13 @@ module.exports = {
'entries': []
};
for (let t = 0; t < this.jsonBlock.length; t++)
if (Sugar.Date(this.jsonBlock[t].dtstart).isTomorrow().raw)
const _tm = new Date.create('tomorrow');
const _da = new Date.create('tomorrow').addDays(1);
today.entries = this.jsonBlock.filter((item) => {
if (!item || !item.dtstart || !item.dtend) return false;
today.entries.push(this.jsonBlock[t]);
return item.dtstart.isBetween(_tm, _da) || item.dtend.isBetween(_tm, _da);
});
logger.info('- getTomorrow');
@ -333,19 +444,24 @@ module.exports = {
'entries': []
};
const now = new Sugar.Date('today').raw;
const now = new Date.create('today');
logger.debug('>> now', now);
const twoDays = new Sugar.Date('today').addDays(2).beginningOfDay().raw;
const twoDays = new Date.create('today').addDays(2).beginningOfDay();
logger.debug('>> twoDays', twoDays);
const sevenDays = new Sugar.Date('today').addDays(7).beginningOfDay().raw;
const sevenDays = new Date.create('today').addDays(7).beginningOfDay();
logger.debug('>> sevenDays', sevenDays);
logger.debug('>> trip', { now, twoDays, sevenDays });
for (let t = 0; t < this.jsonBlock.length; t++) {
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]);
}
/* for (let t = 0; t < this.jsonBlock.length; t++)
// logger.debug('>> between', Sugar.Date(this.jsonBlock[t].dtstart).raw, Sugar.Date(this.jsonBlock[t].dtstart).isBetween(twoDays, sevenDays));
if (Date(this.jsonBlock[t].dtstart).isBetween(twoDays, sevenDays))
today.entries.push(this.jsonBlock[t]);*/
today.entries = this.jsonBlock.filter((item) => {
if (!item || !item.dtstart || !item.dtend) return false;
return item.dtstart.isBetween(twoDays, sevenDays) || item.dtend.isBetween(twoDays, sevenDays);
});
logger.info('- getWeek');
@ -419,14 +535,14 @@ module.exports = {
self.jsonBlock = processICAL(body);
// logger.debug(self.jsonBlock);
logger.debug(self.jsonBlock);
const st = self.getTodaysSimple();
return resolve(st);
}, function(error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
// logger.error(body);
return reject(error);
}
@ -454,6 +570,7 @@ module.exports = {
self.jsonBlock = processICAL(body);
logger.debug('jsonBlock length', self.jsonBlock.length);
// logger.debug(self.jsonBlock);
const st = self.getTodaysSimple().entries;
const tom = self.getTomorrow().entries;
@ -467,7 +584,7 @@ module.exports = {
}, function(error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
// logger.error(body);
return reject(error);
}

View File

@ -1,15 +1,15 @@
var request = require('request');
var cheerio = require('cheerio');
var STRING = require('string');
var logger = require('log4js').getLogger();
const request = require('request');
const cheerio = require('cheerio');
const STRING = require('string');
const logger = require('log4js').getLogger('history');
module.exports = {
'getTechHistory': function() {
var url;
var d;
var day;
var month;
var monthNames = [
let url;
let d;
let day;
let month;
const monthNames = [
'January',
'February',
'March',
@ -42,13 +42,12 @@ module.exports = {
return reject(err);
// Throw err;
var $ = cheerio.load(body);
var tdihbody = $('#tdihbody');
const $ = cheerio.load(body);
const tdihbody = $('#tdihbody .tdihevent');
const output = [];
var output = [];
tdihbody.find('.tdihevent > p').each(function(div) {
var s = $(this).text();
tdihbody.find('p').each(function(div) {
const s = $(this).text();
output.push(STRING(s).collapseWhitespace().s);
});
@ -63,11 +62,11 @@ module.exports = {
});
});
}, 'getHistory': function() {
var url;
var d = new Date();
var day;
var month;
var monthNames = [
let url;
const d = new Date();
let day;
let month;
const monthNames = [
'january',
'february',
'march',
@ -100,13 +99,13 @@ module.exports = {
return reject(err);
// Throw err;
var $ = cheerio.load(body);
const $ = cheerio.load(body);
var nbody = $('DIV#bbcPageContent').first();
var output = [];
const nbody = $('DIV#bbcPageContent').first();
const output = [];
nbody.find('.story > p').each(function(div) {
var s = $(this).text();
const s = $(this).text();
if (s.indexOf('Today\'s recipe:') == -1)
output.push(s);
});
@ -124,8 +123,8 @@ module.exports = {
},
'updateHistory': function() {
'use strict';
var output = [];
let output = [];
return new Promise(function(resolve, reject) {
module.exports.getHistory()
.then((d) => {

View File

@ -7,7 +7,7 @@
*/
var jade = require('pug'), UltraSES = require('ultrases'), dateFormat = require('dateformat');
var logger = require('log4js').getLogger();
var logger = require('log4js').getLogger('mailer');
var mailer = new UltraSES({
aws: {

View File

@ -1,43 +1,40 @@
/**
* Created by Martin on 31/03/2016.
*/
var https = require('https');
const https = require('https');
var STRING = require('string');
var logger = require('log4js').getLogger();
var options = {
host: 'andruxnet-random-famous-quotes.p.mashape.com',
path: '/?cat=famous',
headers: {
accept: "application/json",
"X-Mashape-Key": "5A0H980jK6mshSFL24ZmfiRrNHV2p1d1fhQjsngtx8QWuO9oe4",
'Content-Type': "application/x-www-form-urlencoded"
},
method: 'GET'
};
const STRING = require('string');
const logger = require('log4js').getLogger('quotes');
const options = {
'host': 'andruxnet-random-famous-quotes.p.mashape.com',
'path': '/?cat=famous',
'headers': {
'accept': 'application/json',
'X-Mashape-Key': '5A0H980jK6mshSFL24ZmfiRrNHV2p1d1fhQjsngtx8QWuO9oe4',
'Content-Type': 'application/x-www-form-urlencoded'
},
'method': 'GET'
};
module.exports = {
GetQuotes: function() {
'use strict';
return new Promise(function(resolve, reject) {
https.request(options).on('response', function (response) {
var data = '';
response.on("data", function (chunk) {
data += chunk;
});
response.on('end', function () {
//console.log(data);
//callback(JSON.parse(data));
resolve(JSON.parse(data));
});
}).end();
'GetQuotes': function() {
'use strict';
return new Promise(function(resolve, reject) {
https.request(options).on('response', function (response) {
let data = '';
response.on('data', function (chunk) {
data += chunk;
});
}
response.on('end', function () {
// console.log(data);
// callback(JSON.parse(data));
resolve(JSON.parse(data));
});
}).end();
});
}
};

View File

@ -1,41 +1,38 @@
/**
* Created by Martin on 15/02/2016.
*/
let http = require('http');
const http = require('http');
const request = require('request');
let util = require('util');
const logger = require('log4js').getLogger();
const util = require('util');
const logger = require('log4js').getLogger('swedish');
const to_json = require('xmljson').to_json;
require('sugar-date');
module.exports = {
getSwedishWord: function () {
return new Promise(function(resolve, reject) {
'getSwedishWord': function () {
return new Promise(function(resolve, reject) {
const t = new Date(), ms = t.getTime();
const t = new Date(), ms = t.getTime();
const url = ['http://wotd.transparent.com/rss/swedish-widget.xml?t=', ms].join('');
// logger.info(url);
request(url, function (err, resp, body) {
if (err) {
return reject(err);
}
to_json(body, function (error, data) {
return resolve(data);
});
}, function(error, response, body) {
if(response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
return reject(error);
}
});
const url = ['http://wotd.transparent.com/rss/swedish-widget.xml?t=', ms].join('');
// logger.info(url);
request(url, function (err, resp, body) {
if (err)
return reject(err);
to_json(body, function (error, data) {
return resolve(data);
});
}
}, function(error, response, body) {
if(response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
return reject(error);
}
});
});
}
};
//module.exports.getSwedishWord();
// module.exports.getSwedishWord();

View File

@ -9,21 +9,17 @@ const ftse = require('ftse');
module.exports = {
getFTSE: function() {
'getFTSE': function() {
return new Promise(function(resolve, reject) {
"use strict";
'use strict';
let err = 0;
const err = 0;
ftse('100', 10, 'risers', function(items) {
if (items === err) {
if (items === err)
return reject(err);
}
return resolve(items);
});
});
}
};

View File

@ -1,131 +1,122 @@
/**
* Created by Martin on 31/03/2016.
*/
let STRING = require('string');
const logger = require('log4js').getLogger();
const STRING = require('string');
const logger = require('log4js').getLogger('trains');
const request = require('request'), cheerio = require('cheerio');
const _ = require('lodash');
const trainList = [
{
id: 'dbeglq',
url: 'http://www.journeycheck.com/scotrail/route?from=DBE&to=GLQ&action=search&savedRoute='
},
{
id: 'glqhym',
url: 'http://www.journeycheck.com/scotrail/route?from=GLQ&to=HYM&action=search&savedRoute='
}
{
'id': 'dbeglq',
'url': 'http://www.journeycheck.com/scotrail/route?from=DBE&to=GLQ&action=search&savedRoute='
},
{
'id': 'glqhym',
'url': 'http://www.journeycheck.com/scotrail/route?from=GLQ&to=HYM&action=search&savedRoute='
}
];
module.exports = {
processTrainUpdates: function (body) {
const outputArray = [];
const $ = cheerio.load(body);
const lu = $('DIV#LU').first();
'processTrainUpdates': function (body) {
const outputArray = [];
const $ = cheerio.load(body);
const lu = $('DIV#LU').first();
const us = lu.find('.updatesSection').first();
us.find('.updateTitle').each(function (div) {
const wO = {title: '', description: ''};
title = $(this).find('A').first().text().trim();
wO.title = title;
outputArray.push(wO);
});
const us = lu.find('.updatesSection').first();
us.find('.updateTitle').each(function (div) {
const wO = { 'title': '', 'description': '' };
title = $(this).find('A').first().text().trim();
wO.title = title;
outputArray.push(wO);
});
us.find('.updateBodyStart').each(function (div) {
us.find('.updateBodyStart').each(function (div) {
let description = $(this).find('.bodyInner').first().find('.primaryStyle').first().text().trim();
const splitDesc = description.split('\r\n');
let description = $(this).find('.bodyInner').first().find('.primaryStyle').first().text().trim();
const splitDesc = description.split('\r\n');
const wa = [];
for (let i = 0; i < splitDesc.length; i++) {
let contentCheck = splitDesc[i].trim();
if (contentCheck.indexOf('Impact') > -1) contentCheck = '';
if (contentCheck.indexOf('Additional Information') > -1) contentCheck = '';
if (contentCheck.indexOf('apologise for the delay') > -1) contentCheck = '';
if (contentCheck.indexOf('Delay Repay') > -1) contentCheck = '';
if (contentCheck.length > 0) wa.push(contentCheck);
}
description = wa.join(' ');
outputArray[div].description = description;
});
const wa = [];
for (let i = 0; i < splitDesc.length; i++) {
let contentCheck = splitDesc[i].trim();
if (contentCheck.indexOf('Impact') > -1) contentCheck = '';
if (contentCheck.indexOf('Additional Information') > -1) contentCheck = '';
if (contentCheck.indexOf('apologise for the delay') > -1) contentCheck = '';
if (contentCheck.indexOf('Delay Repay') > -1) contentCheck = '';
if (contentCheck.length > 0) wa.push(contentCheck);
}
description = wa.join(' ');
outputArray[div].description = description;
});
return outputArray;
}, 'getTrainUpdates': function (id, out) {
return new Promise(function (resolve, reject) {
'use strict';
logger.info('Getting train events: ', id);
const url = trainList[id].url;
return outputArray;
const now = new Date();
}, getTrainUpdates: function (id, out) {
// if ((now - eventCache.last) > eventCache.expire) {
request(url, function (err, resp, body) {
if (err)
// logger.error(err);
return reject(err);
// throw err;
return new Promise(function (resolve, reject) {
"use strict";
logger.info('Getting train events: ', id);
const url = trainList[id].url;
let trainData = module.exports.processTrainUpdates(body);
let now = new Date();
for (let i = 0; i < out.length; i++) {
let flag = false;
for (let j = 0; j < trainData.length; j++)
flag = _.isEqual(trainData[j], out[i]);
// if ((now - eventCache.last) > eventCache.expire) {
request(url, function (err, resp, body) {
if (err) {
// logger.error(err);
return reject(err);
// throw err;
}
if (!flag)
trainData.push(out[i]);
}
trainData = _.uniq(trainData);
let trainData = module.exports.processTrainUpdates(body);
return resolve(trainData);
}, function (error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
}
if (error)
// logger.error(err);
return reject(err);
// throw err;
});
});
}, 'updateTrains': function () {
logger.info('New Updating trains..');
for (let i = 0; i < out.length; i++) {
let flag = false;
for (let j = 0; j < trainData.length; j++) {
flag = _.isEqual(trainData[j], out[i])
}
const output = [];
return new Promise(function (resolve, reject) {
'use strict';
module.exports.getTrainUpdates(0, [])
.then((d) => {
'use strict';
if (!flag) {
trainData.push(out[i]);
}
}
trainData = _.uniq(trainData);
return resolve(trainData);
}, function (error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
}
if (error) {
// logger.error(err);
return reject(err);
// throw err;
}
module.exports.getTrainUpdates(1, d)
.then((d) => {
'use strict';
return resolve(d);
})
.catch((e) => {
'use strict';
return reject(e);
});
})
.catch((e) => {
'use strict';
return reject(e);
});
}, updateTrains: function () {
logger.info('New Updating trains..');
let output = [];
return new Promise(function (resolve, reject) {
"use strict";
module.exports.getTrainUpdates(0, [])
.then((d)=> {
"use strict";
module.exports.getTrainUpdates(1, d)
.then((d)=> {
"use strict";
return resolve(d);
})
.catch((e)=> {
"use strict";
return reject(e);
});
})
.catch((e)=> {
"use strict";
return reject(e);
});
});
}
});
}
};

View File

@ -3,7 +3,7 @@
*/
const Forecast = require('forecast.io');
const STRING = require('string');
const logger = require('log4js').getLogger();
const logger = require('log4js').getLogger('weather');
const forecastOptions = {
'APIKey': '9ad2a41d420f3cf4960571bb886f710c', 'units': 'uk2'

View File

@ -8,10 +8,12 @@ const util = require('util');
const cron = require('node-cron');
const dateFormat = require('dateformat');
const jsonfile = require('jsonfile');
let fs = require('fs');
let LocalStorage = require('node-localstorage').LocalStorage;
//var nano = require('nano')('http://martind2000:1V3D4m526i@localhost:5984');
const fs = require('fs');
const LocalStorage = require('node-localstorage').LocalStorage;
// var nano = require('nano')('http://martind2000:1V3D4m526i@localhost:5984');
const logger = require('log4js').getLogger();
const Sugar = require('sugar');
const calHandler = require('./today/calHandler');
const swedishWord = require('./today/swedishword');
const weather = require('./today/weather');
@ -21,8 +23,8 @@ 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);
// var db_name = 'silvrgit';
// var dbCloudant = nano.use(db_name);
/*
@ -30,175 +32,173 @@ const quotes = require('./today/quotes');
https://25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix.cloudant.com/dashboard.html#usage
*/
localStorage = new LocalStorage('./scratch');
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');
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 todayCacheSrc = {
last: 0, data: {
trains: {last: 0, data: []},
weather: {},
history: [],
today: '',
tv: {entries: []},
cal: {today: [], tomorrow: [], week: []},
swedish: {},
fitbit: {},
ftse: {}
}, expire: ((60 * 1000) * 60)
const todayCacheSrc = {
'last': 0, 'data': {
'trains': { 'last': 0, 'data': [] },
'weather': {},
'history': [],
'today': '',
'tv': { 'entries': [] },
'cal': { 'today': [], 'tomorrow': [], 'week': [] },
'swedish': {},
'fitbit': {},
'ftse': {}
}, 'expire': ((60 * 1000) * 60)
};
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();
console.log(todayCache.last);
console.log('last updated', ((now - todayCache.last) / 60000));
if (now - todayCache.last < 3600000) {
return false;
} else {
todayCache.last = now;
return true;
}
try {
const now = new Date().getTime();
console.log(todayCache.last);
console.log('last updated', ((now - todayCache.last) / 60000));
if (now - todayCache.last < 3600000)
return false;
else {
todayCache.last = now;
return true;
}
catch (e) {
logger.debug('Creating new today object.. Lets go!')
todayCache = Object.assign({}, todayCacheSrc);
todayCache.last = new Date().getTime();
return true;
}
}
catch (e) {
logger.debug('Creating new today object.. Lets go!');
todayCache = Object.assign({}, todayCacheSrc);
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');
// localStorage.removeItem('today');
try {
let tempCache = localStorage.getItem('today');
if (tempCache !== null) {
todayCache = JSON.parse(tempCache);
}
}
catch (e) {
console.error('Could not load previous data');
}
console.log('Loading old data');
// localStorage.removeItem('today');
try {
const tempCache = localStorage.getItem('today');
if (tempCache !== null)
todayCache = JSON.parse(tempCache);
}
catch (e) {
console.error('Could not load previous data');
}
}
function saveData() {
todayCache.last = new Date().getTime();
logger.info('Saving...');
// jsonfile.writeFileSync(file, todayCache);
localStorage.setItem('today', JSON.stringify(todayCache));
todayCache.last = new Date().getTime();
logger.info('Saving...');
// jsonfile.writeFileSync(file, todayCache);
localStorage.setItem('today', JSON.stringify(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) {
@ -210,288 +210,273 @@ 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;
const d = new Sugar.Date();
const nextYear = `${(parseInt(d.getFullYear().raw) + 1).toString() }-01-01`;
console.log(d.daysUntil('beginning of next year'));
const daysSinceStart = d.daysSince('beginning of this year');
const daysRemaining = d.daysUntil('beginning of next year');
console.log(d.daysUntil('beginning of next year').raw);
const daysSinceStart = d.daysSince('beginning of this year').raw;
const daysRemaining = d.daysUntil('beginning of next year').raw;
todayCache.data.history = [];
s = '<strong>' + d.format('{Weekday} {Month} {dd}, {yyyy}') + '</strong> - ';
todayCache.data.history = [];
s = `<strong>${ d.format('{Weekday} {Month} {dd}, {yyyy}').raw }</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}').raw}, 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);
})
.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);
});
todayCache.date = breakDay();
},
'preLoadTodayTest': function () {
module.exports.getTodayDate();
todayCache.data.cal = { 'today': [], 'tomorrow': [], 'week': [] };
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();
},
preLoadTodayTest: function () {
module.exports.getTodayDate();
todayCache.data.cal = {today: [], tomorrow: [], week: []};
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});
}, (60000));
cron.schedule('15 7 * * *', function () {
if (runable()) {
module.exports.preLoadToday();
cron.schedule('30 6 * * *', function () {
if (runable()) {
module.exports.preLoadToday();
}
saveToDB(todayCache);
saveData();
}
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.refreshWeather();
return -1;
cron.schedule('30 7 * * *', function () {
mdMailer.sendEmailV1(todayCache, __dirname);
// saveToDB(todayCache);
// Console.log('tick');
return -1;
});
cron.schedule('45 6 * * *', function () {
mdMailer.sendEmailV1(todayCache, __dirname);
saveToDB(todayCache);
// Console.log('tick');
return -1;
});