promises promises

This commit is contained in:
Martin Donnelly 2016-03-31 17:12:25 +01:00
parent db37320e4c
commit f7b9642aab
12 changed files with 684 additions and 515 deletions

2
app/css/mui.min.css vendored

File diff suppressed because one or more lines are too long

2
app/libs/zepto.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,28 +1,12 @@
/**
* Created by Martin on 15/02/2016.
*/
var http = require('http'), request = require('request'), calHandler = require('./calHandler'), util = require('util');
var jsonfile = require('jsonfile');
var log4js = require('log4js');
var logger = log4js.getLogger();
require('sugar-date');
var file = __dirname + '/' + 'cal.json';
function saveData(v) {
jsonfile.writeFileSync(file, v);
}
module.exports = {
getCal: function () {
var swedishword = require('./today/swedishword');
calHandler.getSimpleCalV2('https://www.tripit.com/feed/ical/private/DB96E4BB-94A9BD8F9CC1CF51C6CC0D920840F4F5/tripit.ics', function(v) {
logger.debug(v) ;
});
}
};
module.exports.getCal();
swedishword.getSwedishWord()
.then((d) => {
"use strict";
console.log('Wanted result: ' , d);
})
.catch((e)=>{
"use strict";
console.error(e);
});

View File

@ -2,7 +2,7 @@
* Created by marti on 30/01/2016.
*/
var http = require('http'), request = require('request'), cheerio = require(
'cheerio'), Forecast = require('forecast.io'), util = require('util'), UltraSES = require(
'cheerio'), util = require('util'), UltraSES = require(
'ultrases'), cron = require('node-cron');
var jade = require('jade'), _ = require('lodash'), dateFormat = require(
'dateformat');
@ -12,533 +12,334 @@ var nano = require('nano')('http://localhost:5984');
var log4js = require('log4js');
var logger = log4js.getLogger();
var calHandler = require('./calHandler');
var swedishWord = require('./swedishword');
var calHandler = require('./today/calHandler');
var swedishWord = require('./today/swedishword');
var weather = require('./today/weather');
var trains = require('./today/trains');
var history = require('./today/history');
var db_name = 'silvrgit';
var dbCouch = nano.use(db_name);
var todayCache = {
last: 0, data: {
trains: {last: 0, data: []},
weather: {},
history: [],
today: '',
tv: {entries: []},
cal: {entries: []},
swedish: {}
}, expire: ((60 * 1000) * 60)
};
var trainList = [
{
id: 'dbeglq',
url: 'http://www.journeycheck.com/scotrail/route?from=DBE&to=GLQ&action=search&savedRoute='
},
{
id: 'glqdbe',
url: 'http://www.journeycheck.com/scotrail/route?from=GLQ&to=DBE&action=search&savedRoute='
}
];
//https://api.forecast.io/forecast/0657dc0d81c037cbc89ca88e383b6bbf/55.8582846,-4.2593033?units=uk2
var forecastOptions = {
APIKey: '0657dc0d81c037cbc89ca88e383b6bbf', units: 'uk2'
last: 0, data: {
trains: {last: 0, data: []},
weather: {},
history: [],
today: '',
tv: {entries: []},
cal: {entries: []},
swedish: {}
}, expire: ((60 * 1000) * 60)
};
var mailer = new UltraSES({
aws: {
accessKeyId: 'AKIAJWJS75F7WNCGK64A',
secretAccessKey: '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',
"region": "eu-west-1"
}, defaults: {
from: 'Martin Donnelly <martind2000@gmail.com>'
}
aws: {
accessKeyId: 'AKIAJWJS75F7WNCGK64A',
secretAccessKey: '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',
"region": "eu-west-1"
}, defaults: {
from: 'Martin Donnelly <martind2000@gmail.com>'
}
});
var file = __dirname + '/' + 'newdata.json';
var htmlfile = __dirname + '/' + 'today.html';
function saveData() {
logger.info('Saving...');
jsonfile.writeFileSync(file, todayCache);
logger.info('Saving...');
jsonfile.writeFileSync(file, todayCache);
}
function saveToDB(data) {
logger.debug('Inserting into couch...');
// logger.info(util.inspect(obj));
dbCouch.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));
dbCouch.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
switch (d % 10) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
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 dayNumber() {
var now = new Date();
var start = new Date(now.getFullYear(), 0, 0);
var diff = now - start;
var oneDay = 1000 * 60 * 60 * 24;
return Math.floor(diff / oneDay);
var now = new Date();
var start = new Date(now.getFullYear(), 0, 0);
var diff = now - start;
var oneDay = 1000 * 60 * 60 * 24;
return Math.floor(diff / oneDay);
}
function breakDay() {
var now = new Date();
return {year:now.getFullYear(), month:parseInt(now.getMonth()) + 1, day:now.getDate()}
var now = new Date();
return {year: now.getFullYear(), month: parseInt(now.getMonth()) + 1, day: now.getDate()}
}
/**
* @return {number}
*/
function DayDiff(CurrentDate) {
var TYear = CurrentDate.getFullYear();
var TDay = new Date("January, 01, " + (parseInt(TYear) + 1));
TDay.getFullYear(TYear);
var DayCount = (TDay - CurrentDate) / (1000 * 60 * 60 * 24);
DayCount = Math.round(DayCount);
return (DayCount);
var TYear = CurrentDate.getFullYear();
var TDay = new Date("January, 01, " + (parseInt(TYear) + 1));
TDay.getFullYear(TYear);
var DayCount = (TDay - CurrentDate) / (1000 * 60 * 60 * 24);
DayCount = Math.round(DayCount);
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') {
var att = fn;
fn = function(e) {
return e[att];
}
Array.prototype.indexOf = function (e, fn) {
if (!fn) {
return this.indexOfOld(e)
}
else {
if (typeof fn === 'string') {
var att = fn;
fn = function (e) {
return e[att];
}
}
return this.map(fn).indexOfOld(e);
}
return this.map(fn).indexOfOld(e);
}
};
module.exports = {
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() {
var s, d = new Date();
todayCache.data.history = [];
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 () {
var s, d = new Date();
todayCache.data.history = [];
s = '<strong>' + dateFormat(d, "mmmm d") + '</strong> - ';
s = s + 'The ' + dayNumber() + nth(dayNumber) + ' day of ' + dateFormat(d,
"yyyy") + ', and there are ' + DayDiff(d) + ' days left until the end of the year.';
s = '<strong>' + dateFormat(d, "mmmm d") + '</strong> - ';
s = s + 'The ' + dayNumber() + nth(dayNumber) + ' day of ' + dateFormat(d,
"yyyy") + ', and there are ' + DayDiff(d) + ' days left until the end of the year.';
logger.debug(s);
todayCache.data.today = s;
},
logger.debug(s);
todayCache.data.today = s;
},
getTechHistory: function() {
var url, d, day, month, monthNames = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
refreshTrainAndWeather: function () {
d = new Date();
weather.newDoGetWeather()
.then((d)=> {
todayCache.data.weather = d;
})
.catch((e) => {
logger.error(e);
});
month = monthNames[d.getMonth()];
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);
});
day = d.getDate();
}, preLoadToday: function () {
module.exports.getTodayDate();
var self = this;
todayCache.data.cal.entries = [];
url = ['http://www.computerhistory.org/tdih/', month, '/', day].join('');
logger.info(url);
request(url, function(err, resp, body) {
if (err)
throw err;
weather.newDoGetWeather()
.then((d)=> {
todayCache.data.weather = d;
})
.catch((e) => {
logger.error(e);
});
$ = cheerio.load(body);
var tdihbody = $('#tdihbody');
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);
});
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);
}, function(error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
}
});
}, getHistory: function() {
var url, d, day, month, monthNames = [
"january",
"february",
"march",
"april",
"may",
"june",
"july",
"august",
"september",
"october",
"november",
"december"
];
history.updateHistory()
.then((d) => {
"use strict";
console.log('History result: ' , d);
todayCache.data.history = d;
})
.catch((e)=>{
"use strict";
console.error(e);
});
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);
request(url, function(err, resp, body) {
if (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);
calHandler.getSimpleCalV3('http://www.pogdesign.co.uk/cat/download_ics/60cfdff469d0490545d33d7e3b5c0bcc')
.then((d)=>{
"use strict";
todayCache.data.tv = d;
})
.catch(e)=>{
logger.error(e);
}
});
todayCache.data.history = todayCache.data.history.concat(output);
logger.info(todayCache.data.history);
module.exports.getTechHistory();
}, function(error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
}
});
}, processTrainUpdates: function(body) {
var outputArray = [];
var $ = cheerio.load(body);
var lu = $('DIV#LU').first();
calHandler.getSimpleCalV3(
'https://calendar.google.com/calendar/ical/martind2000%40gmail.com/private-40cfebc9f7dcfa7fde6b9bf2f0092c93/basic.ics'
)
.then((d)=>{
"use strict";
todayCache.data.cal.entries = todayCache.data.cal.entries.concat(d.entries);
})
.catch(e)=>{
logger.error(e);
}
var us = lu.find('.updatesSection').first();
us.find('.updateTitle').each(function(div) {
var wO = {title: '', description: ''};
title = $(this).find('A').first().text().trim();
wO.title = title;
outputArray.push(wO);
});
us.find('.updateBodyStart').each(function(div) {
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)=>{
logger.error(e);
}
var description = $(this).find('.bodyInner').first().find('.primaryStyle').first().text().trim();
var splitDesc = description.split('\r\n');
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)=>{
logger.error(e);
}
var wa = [];
for (var i = 0; i < splitDesc.length; i++) {
var 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;
});
swedishWord.getSwedishWord()
.then((d) => {
"use strict";
console.log('Swedish result: ' , d);
todayCache.data.swedish =d;
})
.catch((e)=>{
"use strict";
console.error(e);
});
// join arrays
todayCache.date = breakDay();
// word of the day http://wotd.transparent.com/rss/swedish-widget.xml?t=1455840000000
// time stamp
for (var i = 0; i < outputArray.length; i++) {
var flag = false;
for (var j = 0; j < todayCache.data.trains.data.length; j++) {
flag = _.isEqual(todayCache.data.trains.data[j], outputArray[i])
}
if (!flag) {
todayCache.data.trains.data.push(outputArray[i]);
}
}
todayCache.data.trains.data = _.uniq(todayCache.data.trains.data);
}, getTrainUpdates: function(id) {
logger.info('Getting train events...');
var url = trainList[id].url;
var now = new Date();
// if ((now - eventCache.last) > eventCache.expire) {
request(url, function(err, resp, body) {
if (err)
throw err;
module.exports.processTrainUpdates(body);
}, function(error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
}
});
todayCache.data.trains.last = now;
}, updateTrains: function() {
logger.info('Updating trains..');
todayCache.data.trains.data = [];
module.exports.getTrainUpdates(0);
module.exports.getTrainUpdates(1);
},
doGetWeatherOutlook: function() {
logger.info('Retrieving weather..');
var j = {};
var forecast = new Forecast(forecastOptions);
forecast.get(55.8582846,
-4.2593033,
{units: 'uk2'},
function(err, res, data) {
if (err) throw err;
var tempMin = parseInt(data.daily.data[0].temperatureMin);
var tempMax = parseInt(data.daily.data[0].temperatureMax);
j.currently = data.currently.summary;
j.today = data.daily.data[0].summary;
j.later = data.daily.summary;
j.alerts = data.alerts || {};
j.data = data;
var fs = STRING(j.currently).endsWith('.') ? '' : '.';
if (tempMax == tempMin) {
j.currently += fs + ' Around ' + tempMin.toString() + ' degrees.';
}
else {
j.currently += fs + ' Around ' + tempMin.toString() + ' to ' + tempMax.toString() + ' degrees.';
}
todayCache.data.weather = j;
});
}, refreshTrainAndWeather: function() {
try {
module.exports.doGetWeatherOutlook();
}
catch (e) {
// statements to handle any exceptions
logger.error(e);
}
try {
module.exports.updateTrains();
}
catch (e) {
// statements to handle any exceptions
logger.error(e);
}
}, preLoadToday: function() {
module.exports.getTodayDate();
var self = this;
try {
module.exports.doGetWeatherOutlook();
}
catch (e) {
// statements to handle any exceptions
logger.error(e);
}
try {
module.exports.updateTrains();
}
catch (e) {
// statements to handle any exceptions
logger.error(e);
}
try {
module.exports.getHistory();
}
catch (e) {
// statements to handle any exceptions
logger.error(e);
}
try {
calHandler.getSimpleCalV2(
'http://www.pogdesign.co.uk/cat/download_ics/60cfdff469d0490545d33d7e3b5c0bcc',
function(v) {
todayCache.data.tv = v;
});
}
catch (e) {
logger.error(e);
}
try {
calHandler.getSimpleCalV2(
'https://calendar.google.com/calendar/ical/martind2000%40gmail.com/private-40cfebc9f7dcfa7fde6b9bf2f0092c93/basic.ics',
function(v) {
todayCache.data.cal.entries = todayCache.data.cal.entries.concat(v.entries);
});
}
catch (e) {
logger.error(e);
}
try {
calHandler.getSimpleCalV2(
'https://calendar.google.com/calendar/ical/mt5pgdhknvgoc8usfnrso9vkv0%40group.calendar.google.com/private-58876002af9f302a593acfa6fa792dcf/basic.ics',
function(v) {
todayCache.data.cal.entries = todayCache.data.cal.entries.concat(v.entries);
});
}
catch (e) {
logger.error(e);
}
try {
calHandler.getSimpleCalV2(
'https://www.tripit.com/feed/ical/private/DB96E4BB-94A9BD8F9CC1CF51C6CC0D920840F4F5/tripit.ics',
function(v) {
todayCache.data.cal.entries = todayCache.data.cal.entries.concat(v.entries);
});
}
catch (e) {
logger.error(e);
}
try {
swedishWord.getSwedishWord(function(v) {
todayCache.data.swedish = v;
});
}
catch (e) {
logger.error(e);
}
todayCache.date = breakDay();
// word of the day http://wotd.transparent.com/rss/swedish-widget.xml?t=1455840000000
// time stamp
}
};
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',
subject: 'Today - ' + dateFormat(now, "dddd, mmmm dS, yyyy")
};
var template = {
file: __dirname + '/' + 'jade/today.jade',
locals: todayCache
};
var template = {
file: __dirname + '/' + 'jade/today.jade',
locals: todayCache
};
logger.debug(__dirname);
logger.debug(__dirname.substr(__dirname.lastIndexOf('/'), __dirname.length));
logger.debug(__dirname);
logger.debug(__dirname.substr(__dirname.lastIndexOf('/'), __dirname.length));
//if (__dirname.substr(__dirname.lastIndexOf('/'),__dirname.length))
//if (__dirname.substr(__dirname.lastIndexOf('/'),__dirname.length))
mailer.sendTemplate(email, template, function(err) {
if (err) throw err;
logger.info('compiled template email sent');
});
mailer.sendTemplate(email, template, function (err) {
if (err) throw err;
logger.info('compiled template email sent');
});
// saveData();
var fn = jade.compileFile(template.file);
// saveData();
var fn = jade.compileFile(template.file);
//console.log(fn(todayCache));
//console.log(fn(todayCache));
// fs.writeFileSync(htmlfile, fn(todayCache));
// fs.writeFileSync(htmlfile, fn(todayCache));
}
function sendEmail() {
logger.log('Simple email');
var now = new Date();
logger.log('Simple email');
var now = new Date();
var email = {
to: 'martind2000@gmail.com',
subject: 'Today - ' + dateFormat(now, "dddd, mmmm dS, yyyy")
};
var email = {
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() {
module.exports.preLoadToday();
}, 15000);
setTimeout(function () {
module.exports.preLoadToday();
}, 5000);
setTimeout(function () {
saveToDB(todayCache);
}, 45000);
saveToDB(todayCache);
}, 45000);
cron.schedule('45 6 * * *', function() {
module.exports.preLoadToday();
return -1;
cron.schedule('45 6 * * *', function () {
module.exports.preLoadToday();
return -1;
});
cron.schedule('0 */1 * * *', function() {
module.exports.refreshTrainAndWeather();
return -1;
cron.schedule('0 */1 * * *', function () {
module.exports.refreshTrainAndWeather();
return -1;
});
cron.schedule('0 7 * * *', function() {
sendEmailV1();
saveToDB(todayCache);
// console.log('tick');
return -1;
cron.schedule('0 7 * * *', function () {
sendEmailV1();
saveToDB(todayCache);
// console.log('tick');
return -1;
});

View File

@ -20,11 +20,20 @@ function processICAL(ical) {
begin: 'BEGIN:VEVENT',
end: 'END:VEVENT',
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 workBlock = {
summary: '',
dtstart: null,
dtend: null,
description: '',
timeStart: null,
timeEnd: null,
duration: 0,
combined: ''
};
var alarmFlag = false, ws, blockStep;
for (var step = 0; step < block.length; step++) {
blockStep = block[step];
@ -57,12 +66,12 @@ function processICAL(ical) {
}
}
if (workBlock.dtstart !== null ){
if (workBlock.dtstart !== null) {
workBlock.timeStart = workBlock.dtstart.format('{12hr}:{mm}:{ss} {tt}');
workBlock.combined = '<em>' + workBlock.timeStart + '</em> - ';
}
workBlock.combined = workBlock.combined + workBlock.summary;
if (workBlock.dtend !== null ){
if (workBlock.dtend !== null) {
workBlock.timeEnd = workBlock.dtend.format('{12hr}:{mm}:{ss} {tt}');
}
if (workBlock.dtstart !== null && workBlock.dtend !== null) {
@ -71,8 +80,6 @@ function processICAL(ical) {
workBlock.combined = workBlock.combined + ', ' + elapsedTime.optimal;
}
return workBlock;
}
@ -101,7 +108,7 @@ function processICAL(ical) {
}
}
logger.info('- processICAL');
// if (workingBlock.dtstart == null) return {};
// if (workingBlock.dtstart == null) return {};
return workingBlock;
}
@ -121,7 +128,7 @@ module.exports = {
today.entries.push(this.jsonBlock[t]);
}
}
// logger.debug(today);
// logger.debug(today);
logger.info('- getTodaysSimple');
return today;
},
@ -148,7 +155,7 @@ module.exports = {
}
}
}
// logger.debug(today);
// logger.debug(today);
logger.info('- getTodaysMeetings');
return today;
}, getSimpleCalV2: function (url, cb) {
@ -156,31 +163,66 @@ module.exports = {
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;
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) {
"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);
}
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);
}
// var calJson = [];
}

160
lib/today/history.js Normal file
View File

@ -0,0 +1,160 @@
/**
* Created by Martin on 31/03/2016.
*/
var request = require('request'), cheerio = require('cheerio')
var STRING = require('string');
var logger = require('log4js').getLogger();
module.exports = {
getTechHistory: 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.computerhistory.org/tdih/', month, '/', day].join('');
logger.debug(url);
return new Promise(function (resolve, reject) {
"use strict";
request(url, function (err, resp, body) {
if (err) {
// logger.error(err);
return reject(err);
// throw err;
}
$ = cheerio.load(body);
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 = [];
return new Promise(function (resolve, reject) {
module.exports.getHistory()
.then((d)=> {
output = d;
module.exports.getTechHistory()
.then((d) => {
output = output.concat(d);
return resolve(output)
})
.catch((e) => {
logger.error(e);
return reject(e);
});
})
.catch((e) => {
logger.error(e);
return reject(e);
});
})
}
};

View File

@ -17,33 +17,32 @@ function saveData(v) {
}
module.exports = {
getSwedishWord: function (cb) {
getSwedishWord: function () {
return new Promise(function(resolve, reject) {
"use strict";
var t= new Date(), ms = t.getTime();
url = ['http://wotd.transparent.com/rss/swedish-widget.xml?t=', ms].join('');
var url = ['http://wotd.transparent.com/rss/swedish-widget.xml?t=', ms].join('');
logger.info(url);
request(url, function (err, resp, body) {
if (err)
throw err;
logger.debug(body);
if (err) {
return reject(err);
}
to_json(body, function (error, data) {
console.log(data);
if(typeof cb === 'function') {
cb(data);
}
return resolve(data);
});
}, function(error, response, body) {
if(response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
return reject(error);
}
});
});
}
};

131
lib/today/trains.js Normal file
View File

@ -0,0 +1,131 @@
/**
* Created by Martin on 31/03/2016.
*/
var STRING = require('string');
var logger = require('log4js').getLogger();
var request = require('request'), cheerio = require('cheerio');
var _ = require('lodash');
var trainList = [
{
id: 'dbeglq',
url: 'http://www.journeycheck.com/scotrail/route?from=DBE&to=GLQ&action=search&savedRoute='
},
{
id: 'glqdbe',
url: 'http://www.journeycheck.com/scotrail/route?from=GLQ&to=DBE&action=search&savedRoute='
}
];
module.exports = {
processTrainUpdates: function (body) {
var outputArray = [];
var $ = cheerio.load(body);
var lu = $('DIV#LU').first();
var us = lu.find('.updatesSection').first();
us.find('.updateTitle').each(function (div) {
var wO = {title: '', description: ''};
title = $(this).find('A').first().text().trim();
wO.title = title;
outputArray.push(wO);
});
us.find('.updateBodyStart').each(function (div) {
var description = $(this).find('.bodyInner').first().find('.primaryStyle').first().text().trim();
var splitDesc = description.split('\r\n');
var wa = [];
for (var i = 0; i < splitDesc.length; i++) {
var 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);
var url = trainList[id].url;
var now = new Date();
// if ((now - eventCache.last) > eventCache.expire) {
request(url, function (err, resp, body) {
if (err) {
// logger.error(err);
return reject(err);
// throw err;
}
var trainData = module.exports.processTrainUpdates(body);
for (var i = 0; i < out.length; i++) {
var flag = false;
for (var j = 0; j < trainData.length; j++) {
flag = _.isEqual(trainData[j], out[i])
}
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;
}
});
});
}, updateTrains: function () {
logger.info('New Updating trains..');
var 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);
});
});
}
};

53
lib/today/weather.js Normal file
View File

@ -0,0 +1,53 @@
/**
* Created by Martin on 31/03/2016.
*/
var Forecast = require('forecast.io');
var STRING = require('string');
var logger = require('log4js').getLogger();
var forecastOptions = {
APIKey: '0657dc0d81c037cbc89ca88e383b6bbf', units: 'uk2'
};
module.exports = {
newDoGetWeather: function() {
'use strict';
return new Promise(function(resolve, reject) {
logger.info('New Retrieving weather..');
var j = {};
var forecast = new Forecast(forecastOptions);
forecast.get(55.8582846,
-4.2593033,
{units: 'uk2'},
function(err, res, data) {
if (err) {
// logger.error(err);
return reject(err);
// throw err;
}
var tempMin = parseInt(data.daily.data[0].temperatureMin);
var tempMax = parseInt(data.daily.data[0].temperatureMax);
j.currently = data.currently.summary;
j.today = data.daily.data[0].summary;
j.later = data.daily.summary;
j.alerts = data.alerts || {};
j.data = data;
var fs = STRING(j.currently).endsWith('.') ? '' : '.';
if (tempMax == tempMin) {
j.currently += fs + ' Around ' + tempMin.toString() + ' degrees.';
}
else {
j.currently += fs + ' Around ' + tempMin.toString() + ' to ' + tempMax.toString() + ' degrees.';
}
// logger.debug(j);
return resolve(j);
});
});
}
};

View File

@ -17,7 +17,6 @@ function saveData(d) {
jsonfile.writeFileSync(file, d);
}
module.exports = {
doGetWeatherOutlook: function () {
@ -37,8 +36,6 @@ console.log(util.inspect(data));
});
}
}
;
};
module.exports.doGetWeatherOutlook();

View File

@ -2,7 +2,7 @@
<div class="mui-container">
<div class="mui-panel">
<div class="mui-text-headline mui-text-accent">Slack - I have plenty of talent and vision I just don't give a damn</div>
<div class="mui--text-headline mui--text-accent">Slack - I have plenty of talent and vision I just don't give a damn</div>
</div>
<div id="container" class="mui-panel">
<div class="mui-row">
@ -66,7 +66,7 @@
<li><a href="https://tools.bartlweb.net/webssh/">WebSSH</a></li>
<li><a href="http://jade-lang.com/demo/">Jade Tester</a></li>
<li><span id='newPassword'>Generate Password</span></li>
<li><button class="mui-btn mui-btn--flat" id='newPassword'>Generate Password</button></li>
</ul>
<div id='passwordOut' class='password' style='display:none;'></div>
</div>
@ -221,7 +221,7 @@
<div class="mui-col-md-4">
<div class="mui-text-title mui-text-black">Travel <span id="fx"></div>
<!-- Travel -->
<span>DBEGLQ: <span id="dbeglq">---</span></span> <span>GLQDBE: <span id="glqdbe">---</span></span>
<span>DBEGLQ: <button class="mui-btn mui-btn--flat" id="dbeglq"></button></span> <span>GLQDBE: <button class="mui-btn mui-btn--flat" id="glqdbe"></button></span>
<div id='trainResults' style='display:none'></div>
<ul>
<li>

View File

@ -9,7 +9,7 @@
<meta name="Author" content="" />
<link href="//fonts.googleapis.com/css?family=Roboto+Slab:400,300,700" rel="stylesheet" type="text/css">
<link href="//cdn.muicss.com/mui-0.4.6/css/mui.min.css" rel="stylesheet" type="text/css" />
<link href="css/mui.min.css" rel="stylesheet" type="text/css" />
<style>
body {
font-family: 'Roboto Slab', "Helvetica Neue", Helvetica, Arial;
@ -32,7 +32,7 @@
}
#btc, #fx {
font-size: 75%;
font-size: 85%;
}
.up, .ontime {
@ -57,7 +57,7 @@
color: #F44336;
}
</style>
<script src="//cdnjs.cloudflare.com/ajax/libs/zepto/1.1.4/zepto.min.js"></script>
<script src="libs/zepto.min.js"></script>
<script src="libs/microevent.js"></script></head>