updated .gitignore file

This commit is contained in:
martind2000 2016-03-31 23:00:47 +01:00
parent f7b9642aab
commit 2057c171a0
4 changed files with 549 additions and 632 deletions

View File

@ -5,6 +5,7 @@
"window", "window",
"-Promise" "-Promise"
], ],
"node":true,
"browser": true, "browser": true,
"boss": true, "boss": true,
"curly": true, "curly": true,

View File

@ -1,15 +1,11 @@
/** /**
* Created by marti on 30/01/2016. * Created by marti on 30/01/2016.
*/ */
var http = require('http'), request = require('request'), cheerio = require( var http = require('http'), request = require('request'), cheerio = require('cheerio'), util = require('util'), UltraSES = require(
'cheerio'), util = require('util'), UltraSES = require(
'ultrases'), cron = require('node-cron'); 'ultrases'), cron = require('node-cron');
var jade = require('jade'), _ = require('lodash'), dateFormat = require( var jade = require('jade'), _ = require('lodash'), dateFormat = require('dateformat');
'dateformat'); var jsonfile = require('jsonfile'), fs = require('fs'), STRING = require('string');
var jsonfile = require('jsonfile'), fs = require('fs'), STRING = require(
'string');
var nano = require('nano')('http://localhost:5984'); var nano = require('nano')('http://localhost:5984');
var log4js = require('log4js'); var log4js = require('log4js');
var logger = log4js.getLogger(); var logger = log4js.getLogger();
var calHandler = require('./today/calHandler'); var calHandler = require('./today/calHandler');
@ -17,329 +13,252 @@ var swedishWord = require('./today/swedishword');
var weather = require('./today/weather'); var weather = require('./today/weather');
var trains = require('./today/trains'); var trains = require('./today/trains');
var history = require('./today/history'); var history = require('./today/history');
var db_name = 'silvrgit'; var db_name = 'silvrgit';
var dbCouch = nano.use(db_name); var dbCouch = nano.use(db_name);
var todayCache = { var todayCache = {
last: 0, data: { last: 0, data: {
trains: {last: 0, data: []}, trains: {last: 0, data: []}, weather: {}, history: [], today: '', tv: {entries: []}, cal: {entries: []}, swedish: {}
weather: {}, }, expire: ((60 * 1000) * 60)
history: [],
today: '',
tv: {entries: []},
cal: {entries: []},
swedish: {}
}, expire: ((60 * 1000) * 60)
}; };
var mailer = new UltraSES({ var mailer = new UltraSES({
aws: { aws: {
accessKeyId: 'AKIAJWJS75F7WNCGK64A', accessKeyId: 'AKIAJWJS75F7WNCGK64A',
secretAccessKey: '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', secretAccessKey: '8irYxThCp4xxyrbr00HzWcODe2qdNrR7X7S5BKup',
"region": "eu-west-1" region: 'eu-west-1'
}, defaults: { }, defaults: {
from: 'Martin Donnelly <martind2000@gmail.com>' from: 'Martin Donnelly <martind2000@gmail.com>'
} }
}); });
var file = __dirname + '/' + 'newdata.json'; var file = __dirname + '/' + 'newdata.json';
var htmlfile = __dirname + '/' + 'today.html'; var htmlfile = __dirname + '/' + 'today.html';
function saveData() { function saveData() {
logger.info('Saving...'); logger.info('Saving...');
jsonfile.writeFileSync(file, todayCache); jsonfile.writeFileSync(file, todayCache);
} }
function saveToDB(data) { function saveToDB(data) {
logger.debug('Inserting into couch...'); logger.debug('Inserting into couch...');
// logger.info(util.inspect(obj)); // Logger.info(util.inspect(obj));
dbCouch.insert(data, function (err, body, header) { dbCouch.insert(data, function(err, body, header) {
if (err) { if (err) {
logger.error('Error inserting into couch'); logger.error('Error inserting into couch');
logger.error(err); logger.error(err);
return; return;
}
});
}
function nth(d) {
if (d > 3 && d < 21) return 'th'; // thanks kennebec
switch (d % 10) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
} }
});
}
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';}
} }
function dayNumber() { function dayNumber() {
var now = new Date(); var now = new Date();
var start = new Date(now.getFullYear(), 0, 0); var start = new Date(now.getFullYear(), 0, 0);
var diff = now - start; var diff = now - start;
var oneDay = 1000 * 60 * 60 * 24; var oneDay = 1000 * 60 * 60 * 24;
return Math.floor(diff / oneDay); return Math.floor(diff / oneDay);
} }
function breakDay() { function breakDay() {
var now = new Date(); var now = new Date();
return {year: now.getFullYear(), month: parseInt(now.getMonth()) + 1, day: now.getDate()} return {year: now.getFullYear(), month: parseInt(now.getMonth()) + 1, day: now.getDate()}
} }
/** /**
* @return {number} * @return {number}
*/ */
function DayDiff(CurrentDate) { function DayDiff(CurrentDate) {
var TYear = CurrentDate.getFullYear(); var TYear = CurrentDate.getFullYear();
var TDay = new Date("January, 01, " + (parseInt(TYear) + 1)); var TDay = new Date('January, 01, ' + (parseInt(TYear) + 1));
TDay.getFullYear(TYear); TDay.getFullYear(TYear);
var DayCount = (TDay - CurrentDate) / (1000 * 60 * 60 * 24); var DayCount = (TDay - CurrentDate) / (1000 * 60 * 60 * 24);
DayCount = Math.round(DayCount); DayCount = Math.round(DayCount);
return (DayCount); return (DayCount);
} }
Array.prototype.indexOfOld = Array.prototype.indexOf; Array.prototype.indexOfOld = Array.prototype.indexOf;
Array.prototype.indexOf = function(e, fn) {
Array.prototype.indexOf = function (e, fn) { if (!fn) {
if (!fn) { return this.indexOfOld(e);
return this.indexOfOld(e) } else {
} if (typeof fn === 'string') {
else { var att = fn;
if (typeof fn === 'string') { fn = function(e) {
var att = fn; return e[att];
fn = function (e) { }
return e[att];
}
}
return this.map(fn).indexOfOld(e);
} }
return this.map(fn).indexOfOld(e);
}
}; };
module.exports = { module.exports = {
getClock: function (req, res) { getClock: function(req, res) {
// console.log(todayCache); // Console.log(todayCache);
res.render('pages/clock', todayCache); res.render('pages/clock', todayCache);
}, getToday: function (req, res) { }, getToday: function(req, res) {
logger.info(todayCache); logger.info(todayCache);
res.render('pages/today', todayCache); res.render('pages/today', todayCache);
}, getData: function (req, res) { }, getData: function(req, res) {
res.setHeader('Content-Type', 'application/json'); res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(todayCache)); res.end(JSON.stringify(todayCache));
}, getTodayDate: function () { }, getTodayDate: function() {
var s, d = new Date(); var s, d = new Date();
todayCache.data.history = []; todayCache.data.history = [];
s = '<strong>' + dateFormat(d, 'mmmm d') + '</strong> - ';
s = '<strong>' + dateFormat(d, "mmmm d") + '</strong> - '; s = s + 'The ' + dayNumber() + nth(dayNumber) + ' day of ' + dateFormat(d,
s = s + 'The ' + dayNumber() + nth(dayNumber) + ' day of ' + dateFormat(d, 'yyyy') + ', and there are ' + DayDiff(d) + ' days left until the end of the year.';
"yyyy") + ', and there are ' + DayDiff(d) + ' days left until the end of the year.'; logger.debug(s);
todayCache.data.today = s;
logger.debug(s); }, refreshTrainAndWeather: function() {
todayCache.data.today = s; weather.newDoGetWeather()
}, .then((d) => {
todayCache.data.weather = d;
refreshTrainAndWeather: function () { }).catch((e) => {
logger.error(e);
weather.newDoGetWeather() });
.then((d)=> { trains.updateTrains()
todayCache.data.weather = d; .then((d) => {
}) 'use strict';
.catch((e) => { console.log('Trains: ', d);
logger.error(e); todayCache.data.trains.data = d;
}); todayCache.data.trains.last = new Date();
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);
});
}, preLoadToday: function () {
module.exports.getTodayDate();
var self = this;
todayCache.data.cal.entries = [];
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)=>{ .catch((e)=> {
logger.error(e); 'use strict';
} console.error(e);
});
}, preLoadToday: function() {
calHandler.getSimpleCalV3( module.exports.getTodayDate();
'https://calendar.google.com/calendar/ical/martind2000%40gmail.com/private-40cfebc9f7dcfa7fde6b9bf2f0092c93/basic.ics' var self = this;
) todayCache.data.cal.entries = [];
.then((d)=>{ weather.newDoGetWeather()
"use strict"; .then((d)=> {
todayCache.data.cal.entries = todayCache.data.cal.entries.concat(d.entries); todayCache.data.weather = d;
}) })
.catch(e)=>{ .catch((e) => {
logger.error(e); logger.error(e);
} });
trains.updateTrains()
.then((d) => {
calHandler.getSimpleCalV3( 'use strict';
'https://calendar.google.com/calendar/ical/mt5pgdhknvgoc8usfnrso9vkv0%40group.calendar.google.com/private-58876002af9f302a593acfa6fa792dcf/basic.ics' console.log('Trains: ', d);
) todayCache.data.trains.data = d;
.then((d)=>{ todayCache.data.trains.last = new Date();
"use strict"; })
todayCache.data.cal.entries = todayCache.data.cal.entries.concat(d.entries); .catch((e)=> {
}) 'use strict';
.catch(e)=>{ console.error(e);
logger.error(e); });
} history.updateHistory()
.then((d) => {
calHandler.getSimpleCalV3( 'use strict';
'https://www.tripit.com/feed/ical/private/DB96E4BB-94A9BD8F9CC1CF51C6CC0D920840F4F5/tripit.ics' console.log('History result: ', d);
) todayCache.data.history = d;
.then((d)=>{ })
"use strict"; .catch((e)=> {
todayCache.data.cal.entries = todayCache.data.cal.entries.concat(d.entries); 'use strict';
}) console.error(e);
.catch(e)=>{ });
logger.error(e); calHandler.getSimpleCalV3('http://www.pogdesign.co.uk/cat/download_ics/60cfdff469d0490545d33d7e3b5c0bcc')
} .then((d) => {
'use strict';
swedishWord.getSwedishWord() todayCache.data.tv = d;
.then((d) => { })
"use strict"; .catch((e) => {
console.log('Swedish result: ' , d); 'use strict';
todayCache.data.swedish =d; logger.error(e);
}) });
.catch((e)=>{ calHandler.getSimpleCalV3(
"use strict"; 'https://calendar.google.com/calendar/ical/martind2000%40gmail.com/private-40cfebc9f7dcfa7fde6b9bf2f0092c93/basic.ics')
console.error(e); .then((d) => {
}); 'use strict';
todayCache.data.cal.entries = todayCache.data.cal.entries.concat(d.entries);
todayCache.date = breakDay(); })
// word of the day http://wotd.transparent.com/rss/swedish-widget.xml?t=1455840000000 .catch((e) => {
// time stamp 'use strict';
logger.error(e);
} });
calHandler.getSimpleCalV3(
'https://calendar.google.com/calendar/ical/mt5pgdhknvgoc8usfnrso9vkv0%40group.calendar.google.com/private-58876002af9f302a593acfa6fa792dcf/basic.ics')
.then((d) => {
'use strict';
todayCache.data.cal.entries = todayCache.data.cal.entries.concat(d.entries);
})
.catch((e) => {
'use strict';
logger.error(e);
});
calHandler.getSimpleCalV3(
'https://www.tripit.com/feed/ical/private/DB96E4BB-94A9BD8F9CC1CF51C6CC0D920840F4F5/tripit.ics')
.then((d) => {
'use strict';
todayCache.data.cal.entries = todayCache.data.cal.entries.concat(d.entries);
})
.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);
});
todayCache.date = breakDay();
// word of the day http://wotd.transparent.com/rss/swedish-widget.xml?t=1455840000000
// time stamp
}
}; };
function sendEmailV1() { function sendEmailV1() {
var now = new Date();
var now = new Date(); var email = {
to: 'martind2000@gmail.com', subject: 'Today - ' + dateFormat(now, 'dddd, mmmm dS, yyyy')
var email = { };
to: 'martind2000@gmail.com', var template = {
subject: 'Today - ' + dateFormat(now, "dddd, mmmm dS, yyyy") file: __dirname + '/' + 'jade/today.jade', locals: todayCache
}; };
logger.debug(__dirname);
var template = { logger.debug(__dirname.substr(__dirname.lastIndexOf('/'), __dirname.length));
file: __dirname + '/' + 'jade/today.jade', // If (__dirname.substr(__dirname.lastIndexOf('/'),__dirname.length))
locals: todayCache mailer.sendTemplate(email, template, function(err) {
}; if (err) throw err;
logger.info('compiled template email sent');
logger.debug(__dirname); });
logger.debug(__dirname.substr(__dirname.lastIndexOf('/'), __dirname.length)); // SaveData();
var fn = jade.compileFile(template.file);
//if (__dirname.substr(__dirname.lastIndexOf('/'),__dirname.length)) // Console.log(fn(todayCache));
// Fs.writeFileSync(htmlfile, fn(todayCache));
mailer.sendTemplate(email, template, function (err) {
if (err) throw err;
logger.info('compiled template email sent');
});
// saveData();
var fn = jade.compileFile(template.file);
//console.log(fn(todayCache));
// fs.writeFileSync(htmlfile, fn(todayCache));
} }
function sendEmail() { function sendEmail() {
logger.log('Simple email'); logger.log('Simple email');
var now = new Date(); var now = new Date();
var email = {
var email = { to: 'martind2000@gmail.com', subject: 'Today - ' + dateFormat(now, 'dddd, mmmm dS, yyyy')
to: 'martind2000@gmail.com', };
subject: 'Today - ' + dateFormat(now, "dddd, mmmm dS, yyyy") /* Mailer.sendText(email, 'Look at this fantastic email body!', function (err) {
}; if (err) throw err;
console.log('email sent!');
/* mailer.sendText(email, 'Look at this fantastic email body!', function (err) { });
if (err) throw err; */
console.log('email sent!'); saveData();
});
*/
saveData();
} }
setTimeout(function() {
setTimeout(function () { module.exports.preLoadToday();
module.exports.preLoadToday();
}, 5000); }, 5000);
setTimeout(function() {
setTimeout(function () { saveToDB(todayCache);
saveToDB(todayCache);
}, 45000); }, 45000);
cron.schedule('45 6 * * *', function() {
cron.schedule('45 6 * * *', function () { module.exports.preLoadToday();
module.exports.preLoadToday(); return -1;
return -1; });
}); cron.schedule('0 */1 * * *', function() {
module.exports.refreshTrainAndWeather();
cron.schedule('0 */1 * * *', function () { return -1;
module.exports.refreshTrainAndWeather(); });
return -1; cron.schedule('0 7 * * *', function() {
}); sendEmailV1();
saveToDB(todayCache);
cron.schedule('0 7 * * *', function () { // Console.log('tick');
sendEmailV1(); return -1;
saveToDB(todayCache);
// console.log('tick');
return -1;
}); });

View File

@ -7,228 +7,226 @@ var Elapsed = require('elapsed');
require('sugar-date'); require('sugar-date');
function processICAL(ical) { function processICAL(ical) {
"use strict"; 'use strict';
logger.info('+ processICAL'); logger.info('+ processICAL');
var workingBlock = []; var workingBlock = [];
var segments = { var segments = {
meetingStartID: "DTSTART;TZID=Europe/London:", meetingStartID: 'DTSTART;TZID=Europe/London:',
meetingStartAlt: 'DTSTART:', meetingStartAlt: 'DTSTART:',
meetingEndID: "DTEND;TZID=Europe/London:", meetingEndID: 'DTEND;TZID=Europe/London:',
meetingEndAlt: 'DTEND:', meetingEndAlt: 'DTEND:',
meetingDescID: "DESCRIPTION:", meetingDescID: 'DESCRIPTION:',
summaryID: 'SUMMARY:', summaryID: 'SUMMARY:',
begin: 'BEGIN:VEVENT', begin: 'BEGIN:VEVENT',
end: 'END:VEVENT', end: 'END:VEVENT',
beginAlarm: 'BEGIN:VALARM', beginAlarm: 'BEGIN:VALARM',
recur: 'RRULE' recur: 'RRULE'
};
function processBlock(block) {
var workBlock = {
summary: '',
dtstart: null,
dtend: null,
description: '',
timeStart: null,
timeEnd: null,
duration: 0,
combined: ''
}; };
var alarmFlag = false, ws, blockStep;
function processBlock(block) { for (var step = 0; step < block.length; step++) {
var workBlock = { blockStep = block[step];
summary: '', if (blockStep.indexOf(segments.summaryID) >= 0) {
dtstart: null, workBlock.summary = STRING(block[step].split(segments.summaryID)[1]).collapseWhitespace().s;
dtend: null, }
description: '', if (blockStep.indexOf(segments.meetingStartID) >= 0) {
timeStart: null, ws = STRING(block[step].split(segments.meetingStartID)[1]).collapseWhitespace().s;
timeEnd: null, workBlock.dtstart = Date.create(ws);
duration: 0, }
combined: '' if (blockStep.indexOf(segments.meetingEndID) >= 0) {
}; ws = STRING(block[step].split(segments.meetingEndID)[1]).collapseWhitespace().s;
var alarmFlag = false, ws, blockStep; workBlock.dtend = Date.create(ws);
for (var step = 0; step < block.length; step++) { }
blockStep = block[step]; if (blockStep.indexOf(segments.meetingStartAlt) >= 0) {
if (blockStep.indexOf(segments.summaryID) >= 0) { ws = STRING(block[step].split(segments.meetingStartAlt)[1]).collapseWhitespace().s;
workBlock.summary = STRING(block[step].split(segments.summaryID)[1]).collapseWhitespace().s; workBlock.dtstart = Date.create(ws);
} }
if (blockStep.indexOf(segments.meetingStartID) >= 0) { if (blockStep.indexOf(segments.meetingEndAlt) >= 0) {
ws = STRING(block[step].split(segments.meetingStartID)[1]).collapseWhitespace().s; ws = STRING(block[step].split(segments.meetingEndAlt)[1]).collapseWhitespace().s;
workBlock.dtstart = Date.create(ws); workBlock.dtend = Date.create(ws);
} }
if (blockStep.indexOf(segments.meetingEndID) >= 0) { if (blockStep.indexOf(segments.meetingDescID) >= 0) {
ws = STRING(block[step].split(segments.meetingEndID)[1]).collapseWhitespace().s; if (!alarmFlag) {
workBlock.dtend = Date.create(ws); workBlock.description = STRING(block[step].split(segments.meetingDescID)[1]).collapseWhitespace().s;
}
if (blockStep.indexOf(segments.meetingStartAlt) >= 0) {
ws = STRING(block[step].split(segments.meetingStartAlt)[1]).collapseWhitespace().s;
workBlock.dtstart = Date.create(ws);
}
if (blockStep.indexOf(segments.meetingEndAlt) >= 0) {
ws = STRING(block[step].split(segments.meetingEndAlt)[1]).collapseWhitespace().s;
workBlock.dtend = Date.create(ws);
}
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) {
alarmFlag = true;
}
} }
}
if (workBlock.dtstart !== null) { if (blockStep.indexOf(segments.beginAlarm) >= 0) {
workBlock.timeStart = workBlock.dtstart.format('{12hr}:{mm}:{ss} {tt}'); alarmFlag = true;
workBlock.combined = '<em>' + workBlock.timeStart + '</em> - '; }
}
workBlock.combined = workBlock.combined + workBlock.summary;
if (workBlock.dtend !== null) {
workBlock.timeEnd = workBlock.dtend.format('{12hr}:{mm}:{ss} {tt}');
}
if (workBlock.dtstart !== null && workBlock.dtend !== null) {
var elapsedTime = new Elapsed(workBlock.dtstart, workBlock.dtend);
workBlock.duration = elapsedTime.optimal;
workBlock.combined = workBlock.combined + ', ' + elapsedTime.optimal;
}
return workBlock;
} }
var lines = ical.split('\r\n'), l = lines.length, counter = 0; if (workBlock.dtstart !== null) {
workBlock.timeStart = workBlock.dtstart.format('{12hr}:{mm}:{ss} {tt}');
while (counter < l) { workBlock.combined = '<em>' + workBlock.timeStart + '</em> - ';
if (lines[counter].indexOf(segments.begin) < 0) { }
counter++; workBlock.combined = workBlock.combined + workBlock.summary;
} else { if (workBlock.dtend !== null) {
var subcounter = 0, subBlock = []; workBlock.timeEnd = workBlock.dtend.format('{12hr}:{mm}:{ss} {tt}');
while (subcounter < 75) { }
if (lines[counter + subcounter].indexOf(segments.end) < 0) { if (workBlock.dtstart !== null && workBlock.dtend !== null) {
subBlock.push(lines[counter + subcounter]); var elapsedTime = new Elapsed(workBlock.dtstart, workBlock.dtend);
subcounter++; workBlock.duration = elapsedTime.optimal;
} workBlock.combined = workBlock.combined + ', ' + elapsedTime.optimal;
else {
break;
}
}
counter = counter + subcounter;
var b = processBlock(subBlock);
if (b.dtstart !== null) {
workingBlock.push(b);
}
}
} }
logger.info('- processICAL');
// if (workingBlock.dtstart == null) return {};
return workingBlock; return workBlock;
}
var lines = ical.split('\r\n'), l = lines.length, counter = 0;
while (counter < l) {
if (lines[counter].indexOf(segments.begin) < 0) {
counter++;
} else {
var subcounter = 0, subBlock = [];
while (subcounter < 75) {
if (lines[counter + subcounter].indexOf(segments.end) < 0) {
subBlock.push(lines[counter + subcounter]);
subcounter++;
} else {
break;
}
}
counter = counter + subcounter;
var b = processBlock(subBlock);
if (b.dtstart !== null) {
workingBlock.push(b);
}
}
}
logger.info('- processICAL');
// If (workingBlock.dtstart == null) return {};
return workingBlock;
} }
module.exports = { module.exports = {
jsonBlock: [], jsonBlock: [],
getTodaysSimple: function () { getTodaysSimple: function() {
"use strict"; 'use strict';
logger.info('+ getTodaysSimple'); logger.info('+ getTodaysSimple');
var today = { var today = {
entries: [] entries: []
}; };
for (var t = 0; t < this.jsonBlock.length; t++) { for (var t = 0; t < this.jsonBlock.length; t++) {
if (this.jsonBlock[t].dtstart.isToday()) { if (this.jsonBlock[t].dtstart.isToday()) {
today.entries.push(this.jsonBlock[t]); today.entries.push(this.jsonBlock[t]);
} }
} }
// logger.debug(today); // Logger.debug(today);
logger.info('- getTodaysSimple'); logger.info('- getTodaysSimple');
return today; return today;
}, },
getTodaysMeetings: function () { getTodaysMeetings: function() {
"use strict"; 'use strict';
logger.info('+ getTodaysMeetings'); logger.info('+ getTodaysMeetings');
var today = { var today = {
previous: [], upcoming: [], current: {} previous: [], upcoming: [], current: {}
}; };
var now = new Date(); var now = new Date();
for (var t = 0; t < this.jsonBlock.length; t++) { for (var t = 0; t < this.jsonBlock.length; t++) {
if (this.jsonBlock[t].dtstart.isToday()) { if (this.jsonBlock[t].dtstart.isToday()) {
if (this.jsonBlock[t].dtstart.isAfter(now)) { if (this.jsonBlock[t].dtstart.isAfter(now)) {
today.upcoming.push(this.jsonBlock[t]); today.upcoming.push(this.jsonBlock[t]);
} } else {
else { today.previous.push(this.jsonBlock[t]);
today.previous.push(this.jsonBlock[t]);
}
if (now.isBetween(this.jsonBlock[t].dtstart, this.jsonBlock[t].dtend)) {
today.current = this.jsonBlock[t];
}
}
}
// logger.debug(today);
logger.info('- getTodaysMeetings');
return today;
}, getSimpleCalV2: function (url, cb) {
"use strict";
var self = this;
// var calJson = [];
try {
request(url, function (err, res, body) {
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);
var st = self.getTodaysSimple();
if (typeof cb === 'function') {
cb(st);
}
}, function (error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
}
});
} catch (e) {
console.log(e);
} }
},getSimpleCalV3: function (url) { if (now.isBetween(this.jsonBlock[t].dtstart, this.jsonBlock[t].dtend)) {
"use strict"; today.current = this.jsonBlock[t];
var self = this; }
}
}
// Logger.debug(today);
logger.info('- getTodaysMeetings');
return today;
}, getSimpleCalV2: function(url, cb) {
'use strict';
var self = this;
return new Promise(function(resolve, reject) { // Var calJson = [];
try { try {
request(url, function (err, res, body) { request(url, function(err, res, body) {
if (err) { if (err) {
// logger.error(err); logger.error('Get remote Calendar Request failed');
return reject(err); // Callback.call(null, new Error('Request failed'));
// throw err; return;
} }
self.jsonBlock = processICAL(body); self.jsonBlock = processICAL(body);
// logger.debug(self.jsonBlock); // Logger.debug(self.jsonBlock);
var st = self.getTodaysSimple(); var 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) {
console.log(e);
return reject(e);
}
});
// var calJson = [];
if (typeof cb === 'function') {
cb(st);
}
}, function(error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
}
});
} catch (e) {
console.log(e);
} }
}, getSimpleCalV3: function(url) {
'use strict';
var 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;
}
self.jsonBlock = processICAL(body);
// Logger.debug(self.jsonBlock);
var 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) {
console.log(e);
return reject(e);
}
});
// Var calJson = [];
}
/**
* Created by Martin on 16/02/2016. /**
*/ * Created by Martin on 16/02/2016.
*/
}; };

View File

@ -1,160 +1,159 @@
/** var request = require('request');
* Created by Martin on 31/03/2016. var cheerio = require('cheerio');
*/
var request = require('request'), cheerio = require('cheerio')
var STRING = require('string'); var STRING = require('string');
var logger = require('log4js').getLogger(); var logger = require('log4js').getLogger();
module.exports = { module.exports = {
getTechHistory: function () { getTechHistory: function() {
var url, d, day, month, monthNames = [ var url;
"January", var d;
"February", var day;
"March", var month;
"April", var monthNames = [
"May", 'January',
"June", 'February',
"July", 'March',
"August", 'April',
"September", 'May',
"October", 'June',
"November", 'July',
"December" 'August',
]; 'September',
'October',
'November',
'December'
];
d = new Date(); d = new Date();
month = monthNames[d.getMonth()]; month = monthNames[d.getMonth()];
day = d.getDate(); day = d.getDate();
url = ['http://www.computerhistory.org/tdih/', month, '/', day].join(''); url = ['http://www.computerhistory.org/tdih/', month, '/', day].join('');
logger.debug(url); logger.debug(url);
return new Promise(function (resolve, reject) { return new Promise(function(resolve, reject) {
"use strict"; 'use strict';
request(url, function (err, resp, body) { request(url, function(err, resp, body) {
if (err) { if (err) {
// logger.error(err); // Logger.error(err);
return reject(err); return reject(err);
// throw err; // Throw err;
} }
$ = cheerio.load(body); var $ = cheerio.load(body);
var tdihbody = $('#tdihbody'); var tdihbody = $('#tdihbody');
var output = [];
tdihbody.find('.tdihevent > p').each(function (div) {
var s = $(this).text();
output.push(STRING(s).collapseWhitespace().s);
});
//todayCache.data.history = todayCache.data.history.concat(output);
// logger.info(todayCache.data.history);
return resolve(output);
}, function (error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
return reject(error);
}
});
});
}, getHistory: function () {
var url, d, day, month, monthNames = [
"january",
"february",
"march",
"april",
"may",
"june",
"july",
"august",
"september",
"october",
"november",
"december"
];
d = new Date();
month = monthNames[d.getMonth()];
day = d.getDate();
url = [
'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) {
// logger.error(err);
return reject(err);
// throw err;
}
$ = cheerio.load(body);
var body = $('DIV#bbcPageContent').first();
var output = [];
body.find('.story > p').each(function (div) {
var s = $(this).text();
if (s.indexOf('Today\'s recipe:') == -1) {
output.push(s);
}
});
return resolve(output);
// todayCache.data.history = todayCache.data.history.concat(output);
// logger.info(todayCache.data.history);
// module.getTechHistory();
}, function (error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
return reject(error);
}
});
});
},
updateHistory: function () {
"use strict";
var output = []; var output = [];
return new Promise(function (resolve, reject) {
module.exports.getHistory() tdihbody.find('.tdihevent > p').each(function(div) {
var s = $(this).text();
output.push(STRING(s).collapseWhitespace().s);
});
return resolve(output);
}, function(error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
return reject(error);
}
});
});
}, 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'
];
month = monthNames[d.getMonth()];
day = d.getDate();
url = [
'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) {
// Logger.error(err);
return reject(err);
// Throw err;
}
var $ = cheerio.load(body);
var nbody = $('DIV#bbcPageContent').first();
var output = [];
nbody.find('.story > p').each(function(div) {
var s = $(this).text();
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() {
'use strict';
var output = [];
return new Promise(function(resolve, reject) {
module.exports.getHistory()
.then((d)=> { .then((d)=> {
output = d; output = d;
module.exports.getTechHistory() module.exports.getTechHistory()
.then((d) => { .then((d) => {
output = output.concat(d); output = output.concat(d);
return resolve(output) return resolve(output)
}) })
.catch((e) => { .catch((e) => {
logger.error(e); logger.error(e);
return reject(e); return reject(e);
}); });
}) })
.catch((e) => { .catch((e) => {
logger.error(e); logger.error(e);
return reject(e); return reject(e);
}); });
}) })
} }
}; };