This commit is contained in:
Martin Donnelly 2017-10-26 10:46:54 +01:00
commit c0d3b15694
21 changed files with 5466 additions and 0 deletions

3
.babelrc Normal file
View File

@ -0,0 +1,3 @@
{
"presets": ["es2015"]
}

55
.eslintrc.json Normal file
View File

@ -0,0 +1,55 @@
{
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": false
}
},
"env": {
"browser": true,
"node": true,
"es6": true
},
"rules": {
"arrow-spacing": "error",
"block-scoped-var": "error",
"block-spacing": "error",
"brace-style": ["error", "stroustrup", {}],
"camelcase": "error",
"comma-dangle": ["error", "never"],
"comma-spacing": ["error", { "before": false, "after": true }],
"comma-style": [1, "last"],
"consistent-this": [1, "_this"],
"curly": [1, "multi"],
"eol-last": 1,
"eqeqeq": 1,
"func-names": 1,
"indent": ["error", 2, { "SwitchCase": 1 }],
"lines-around-comment": ["error", { "beforeBlockComment": true, "allowArrayStart": true }],
"max-len": [1, 240, 2], // 2 spaces per tab, max 80 chars per line
"new-cap": 1,
"newline-before-return": "error",
"no-array-constructor": 1,
"no-inner-declarations": [1, "both"],
"no-mixed-spaces-and-tabs": 1,
"no-multi-spaces": 2,
"no-new-object": 1,
"no-shadow-restricted-names": 1,
"object-curly-spacing": ["error", "always"],
"padded-blocks": ["error", { "blocks": "never", "switches": "always" }],
"prefer-const": "error",
"prefer-template": "error",
"one-var": 0,
"quote-props": ["error", "always"],
"quotes": [1, "single"],
"radix": 1,
"semi": [1, "always"],
"space-before-blocks": [1, "always"],
"space-infix-ops": 1,
"vars-on-top": 1,
"no-multiple-empty-lines": ["error", { "max": 1, "maxEOF": 1 }],
"spaced-comment": ["error", "always", { "markers": ["/"] }]
}
}

191
.gitignore vendored Normal file
View File

@ -0,0 +1,191 @@
### Archives template
# It's better to unpack these files and commit the raw source because
# git has its own built in compression methods.
*.7z
*.jar
*.rar
*.zip
*.gz
*.bzip
*.bz2
*.xz
*.lzma
*.cab
#packing-only formats
*.iso
*.tar
#package management formats
*.dmg
*.xpi
*.gem
*.egg
*.deb
*.rpm
*.msi
*.msm
*.msp
### Windows template
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio
*.iml
## Directory-based project format:
.idea/
# if you remove the above rule, at least ignore the following:
# User-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries
# Sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# .idea/uiDesigner.xml
# Gradle:
# .idea/gradle.xml
# .idea/libraries
# Mongo Explorer plugin:
# .idea/mongoSettings.xml
## File-based project format:
*.ipr
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
### Xcode template
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## Build generated
build/
DerivedData
## Various settings
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
## Other
*.xccheckout
*.moved-aside
*.xcuserstate
### OSX template
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### Node template
# Logs
logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directory
# https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git
node_modules
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist
/tmp
# dependencies
/node_modules
/bower_components
# misc
/.sass-cache
/connect.lock
/coverage/*
/libpeerconnection.log
npm-debug.log
testem.log
/lib/newdata.json

46
.jscsrc Normal file
View File

@ -0,0 +1,46 @@
{
"disallowKeywords": ["with"],
"disallowKeywordsOnNewLine": ["else"],
"disallowMixedSpacesAndTabs": true,
"disallowMultipleVarDecl": "exceptUndefined",
"disallowNewlineBeforeBlockStatements": true,
"disallowQuotedKeysInObjects": true,
"disallowSpaceAfterObjectKeys": true,
"disallowSpaceAfterPrefixUnaryOperators": true,
"disallowSpacesInFunction": {
"beforeOpeningRoundBrace": true
},
"disallowSpacesInsideParentheses": true,
"disallowTrailingWhitespace": true,
"maximumLineLength": 120,
"requireCamelCaseOrUpperCaseIdentifiers": false,
"requireCapitalizedComments": true,
"requireCapitalizedConstructors": true,
"requireCurlyBraces": true,
"requireSpaceAfterKeywords": [
"if",
"else",
"for",
"while",
"do",
"switch",
"case",
"return",
"try",
"catch",
"typeof"
],
"requireSpaceAfterLineComment": true,
"requireSpaceAfterBinaryOperators": true,
"requireSpaceBeforeBinaryOperators": true,
"requireSpaceBeforeBlockStatements": true,
"requireSpaceBeforeObjectValues": true,
"requireSpacesInFunction": {
"beforeOpeningCurlyBrace": true
},
"requireTrailingComma": false,
"requireEarlyReturn": true,
"validateIndentation": 2,
"validateLineBreaks": "LF",
"validateQuoteMarks": "'"
}

34
.jshintrc Normal file
View File

@ -0,0 +1,34 @@
{
"predef": [
"server",
"document",
"window",
"-Promise"
],
"node":true,
"browser": true,
"boss": true,
"curly": true,
"debug": false,
"devel": true,
"eqeqeq": true,
"evil": true,
"forin": false,
"immed": false,
"laxbreak": false,
"newcap": true,
"noarg": true,
"noempty": false,
"nonew": false,
"nomen": false,
"onevar": false,
"plusplus": false,
"regexp": false,
"undef": true,
"sub": true,
"strict": false,
"white": false,
"eqnull": true,
"esnext": true,
"unused": true
}

617
lib/calHandler.js Normal file
View File

@ -0,0 +1,617 @@
const request = require('request');
const log4js = require('log4js');
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 = 'error';
function processICAL(ical) {
'use strict';
logger.info('+ processICAL');
let workingBlock = [];
const segments = {
'meetingStartID': 'DTSTART;TZID=Europe/London:',
'meetingStartAlt': 'DTSTART:',
'meetingStartAltOther': 'DTSTART;VALUE=DATE:',
'meetingEndID': 'DTEND;TZID=Europe/London:',
'meetingEndAlt': 'DTEND:',
'meetingEndAltOther': 'DTEND;VALUE=DATE:',
'meetingDescID': 'DESCRIPTION:',
'summaryID': 'SUMMARY:',
'begin': 'BEGIN:VEVENT',
'end': 'END:VEVENT',
'beginAlarm': 'BEGIN:VALARM',
'endAlarm': 'END:VALARM',
'recur': 'RRULE:'
};
const rules = ['FREQ', 'WKST', 'UNTIL', 'BYMONTH', 'BYMONTHDAY', 'INTERVAL', 'BYDAY'];
function nThDayOfMonth(monthsAhead, wantedDay) {
const now = new Date();
for(let t = 0; t < monthsAhead; t++) {
}
}
function processRecurrence(workBlock) {
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 };
const now = new Date();
const day = now.getDate();
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 };
const firstSplit = _workBlock.recur.split(';');
for (let t = 0; t < firstSplit.length; t++) {
const ws = firstSplit[t].split('=');
if (rules.indexOf(ws[0]) > -1)
recurSettings[ws[0].toLowerCase()] = ws[1];
}
// if all null discard..
if (recurSettings.freq === null && recurSettings.wkst === null && recurSettings.until === null && recurSettings.byday === null && recurSettings.bymonth === null && recurSettings.bymonthday === null && recurSettings.interval === null)
return null;
if (recurSettings.until !== null) {
// have we expired?
const _until = Date.create(recurSettings.until).isPast();
if (_until) {
logger.warn('EXPIRED!!');
return null;
}
}
if (recurSettings.freq !== null) {
// logger.debug(_workBlock);
let newStart, newEnd;
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();
const _h = origStart.getHours();
const _min = origStart.getMinutes();
const _secs = origStart.getSeconds();
const distance = origEnd - origStart;
_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) {
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
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);
}
// logger.info('** recurArray', recurArray);
return recurArray;
}
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);
_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
}
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 [];
}
function processBlock(block) {
let _wb;
const workBlock = {
'summary': '',
'dtstart': null,
'dtend': null,
'description': '',
'timeStart': null,
'timeEnd': null,
'duration': 0,
'combined': '',
'recur': null,
'timeStartMS': null,
'timeEndMS': null,
'ts' : null
};
let alarmFlag = false, ws, blockStep;
for (let step = 0; step < block.length; step++) {
blockStep = block[step];
if (blockStep.indexOf(segments.recur) >= 0)
workBlock.recur = STRING(block[step].split(segments.recur)[1]).collapseWhitespace().s;
// logger.debug(workBlock.recur);
if (blockStep.indexOf(segments.summaryID) >= 0)
workBlock.summary = STRING(block[step].split(segments.summaryID)[1]).collapseWhitespace().s;
if (blockStep.indexOf(segments.meetingStartID) >= 0) {
ws = STRING(block[step].split(segments.meetingStartID)[1]).collapseWhitespace().s;
// workBlock.dtstart = Date.create(ws);
workBlock.dtstart = new Sugar.Date(ws).raw;
}
if (blockStep.indexOf(segments.meetingEndID) >= 0) {
ws = STRING(block[step].split(segments.meetingEndID)[1]).collapseWhitespace().s;
// workBlock.dtend = Date.create(ws);
workBlock.dtend = new Sugar.Date(ws).raw;
}
if (blockStep.indexOf(segments.meetingStartAlt) >= 0) {
ws = STRING(block[step].split(segments.meetingStartAlt)[1]).collapseWhitespace().s;
// console.log('>> ws', ws);
// workBlock.dtstart = Date.create(ws);
// let d = new Sugar.Date();
workBlock.dtstart = new Sugar.Date(ws).raw;
// console.log('>> date', workBlock.dtstart);
}
if (blockStep.indexOf(segments.meetingEndAlt) >= 0) {
ws = STRING(block[step].split(segments.meetingEndAlt)[1]).collapseWhitespace().s;
// workBlock.dtend = Date.create(ws);
workBlock.dtend = new Sugar.Date(ws).raw;
// console.log('>> date', workBlock.dtend);
}
if (blockStep.indexOf(segments.meetingStartAltOther) >= 0) {
ws = STRING(block[step].split(segments.meetingStartAltOther)[1]).collapseWhitespace().s;
// workBlock.dtstart = Date.create(ws);
workBlock.dtstart = new Sugar.Date(ws).raw;
}
if (blockStep.indexOf(segments.meetingEndAltOther) >= 0) {
ws = STRING(block[step].split(segments.meetingEndAltOther)[1]).collapseWhitespace().s;
// console.log('>> ws', ws);
// workBlock.dtend = Date.create(ws);
workBlock.dtend = new Sugar.Date(ws).raw;
}
if (blockStep.indexOf(segments.meetingDescID) >= 0)
if (!alarmFlag) {
workBlock.description = STRING(block[step].split(segments.meetingDescID)[1]).collapseWhitespace().s;
}
if (blockStep.indexOf(segments.beginAlarm) >= 0)
alarmFlag = true;
}
if (workBlock.dtstart !== null) {
// workBlock.timeStart = workBlock.dtstart.format('{24hr}:{mm}:{ss}');
workBlock.timeStart = Sugar.Date(workBlock.dtstart).format('{24hr}:{mm}:{ss}').raw;
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);
}
workBlock.combined = workBlock.combined + workBlock.summary;
workBlock.longcombined = workBlock.long + workBlock.summary;
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);
workBlock.duration = elapsedTime.optimal;
workBlock.combined = `${workBlock.combined }, ${ elapsedTime.optimal}`;
workBlock.longcombined = `${workBlock.longcombined }, ${ elapsedTime.optimal}`;
}
return workBlock;
}
function buildRecurranceArray(wb) {
const _wb = processRecurrence(wb);
return _wb;
}
const lines = ical.split('\r\n'), l = lines.length;
let counter = 0;
let alarmed = false;
while (counter < l)
if (lines[counter].indexOf(segments.begin) < 0)
counter++;
else {
let subcounter = 0;
const subBlock = [];
alarmed = false;
while (subcounter < 75)
if (lines[counter + subcounter].indexOf(segments.end) < 0) {
if (lines[counter + subcounter].indexOf(segments.beginAlarm) > -1)
alarmed = true;
if (!alarmed)
subBlock.push(lines[counter + subcounter]);
if (lines[counter + subcounter].indexOf(segments.endAlarm) > -1)
alarmed = false;
subcounter++;
}
else
break;
counter = counter + subcounter;
const b = processBlock(subBlock);
if (!b.recur ) {
if (Array.isArray(b))
logger.error('!returned an array...');
else
if (b.dtstart !== null) {
b.ts = b.dtstart.format('{X}');
workingBlock.push(b);
}
}
else {
// logger.warn('We need to spread the recurrance!!');
// logger.debug(b);
let recurBlocks = buildRecurranceArray(b);
if (recurBlocks)
recurBlocks = recurBlocks.map((item) => {
if (item.dtstart)
item.ts = item.dtstart.format('{X}');
return item;
});
if (recurBlocks && recurBlocks.length > 0)
workingBlock = workingBlock.concat(recurBlocks);
}
}
logger.info('- processICAL');
// If (workingBlock.dtstart == null) return {};
return workingBlock;
}
module.exports = {
'calendars': ['https://calendar.google.com/calendar/ical/martind2000%40gmail.com/private-40cfebc9f7dcfa7fde6b9bf2f0092c93/basic.ics',
'https://calendar.google.com/calendar/ical/mt5pgdhknvgoc8usfnrso9vkv0%40group.calendar.google.com/private-58876002af9f302a593acfa6fa792dcf/basic.ics',
'https://www.tripit.com/feed/ical/private/DB96E4BB-94A9BD8F9CC1CF51C6CC0D920840F4F5/tripit.ics',
'https://calendar.google.com/calendar/ical/en.uk%23holiday%40group.v.calendar.google.com/public/basic.ics',
'https://calendar.google.com/calendar/ical/i8dglj12p5nuv20sbjmun5s588%40group.calendar.google.com/private-c8adccb41e56d6a2f285078aaed313f5/basic.ics',
'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';
logger.info('+ getTodaysSimple');
const today = {
'entries': []
};
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;
return item.dtstart.isBetween(_td, _tm) || item.dtend.isBetween(_td, _tm);
});
logger.info('- getTodaysSimple');
return today;
},
'getTomorrow': function() {
'use strict';
logger.info('+ getTomorrow');
const today = {
'entries': []
};
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;
return item.dtstart.isBetween(_tm, _da) || item.dtend.isBetween(_tm, _da);
});
logger.info('- getTomorrow');
return today;
},
'getWeek': function() {
'use strict';
logger.info('+ getWeek');
const today = {
'entries': []
};
const now = new Date.create('today');
logger.debug('>> now', now);
const twoDays = new Date.create('today').addDays(2).beginningOfDay();
logger.debug('>> twoDays', twoDays);
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 (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');
return today;
},
'getTodaysMeetings': function() {
'use strict';
logger.info('+ getTodaysMeetings');
const today = {
'previous': [], 'upcoming': [], 'current': {}
};
const now = new Date();
for (let t = 0; t < this.jsonBlock.length; t++)
if (Sugar.Date(this.jsonBlock[t].dtstart).isToday().raw) {
if (Sugar.Date(this.jsonBlock[t].dtstart).isAfter(now).raw)
today.upcoming.push(this.jsonBlock[t]);
else
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';
const 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);
const 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) {
logger.error(e);
}
}, 'getSimpleCalV3': function(url) {
'use strict';
const self = this;
return new Promise(function(resolve, reject) {
try {
request(url, function(err, res, body) {
if (err)
// logger.error(err);
return reject(err);
// Throw err;
self.jsonBlock = processICAL(body);
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);
return reject(error);
}
});
}
catch (e) {
logger.error(e);
return reject(e);
}
});
// Var calJson = [];
}, 'getAdvancedCalV3': function(url) {
'use strict';
const self = this;
return new Promise(function(resolve, reject) {
try {
request(url, function(err, res, body) {
if (err)
// logger.error(err);
return reject(err);
// Throw err;
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;
const week = self.getWeek().entries;
const obj = { 'today': st, 'tomorrow': tom, 'week': week };
// logger.warn(obj);
return resolve(obj);
}, function(error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
// logger.error(body);
return reject(error);
}
});
}
catch (e) {
logger.error(e);
return reject(e);
}
});
// Var calJson = [];
}
/**
* Created by Martin on 16/02/2016.
*/
};

59
lib/fitbit.js Normal file
View File

@ -0,0 +1,59 @@
const jsonfile = require('jsonfile');
const config = require('../../config/config.json');
const Fitbit = require('fitbit-oauth2');
const logger = require('log4js').getLogger();
require('sugar-date');
const fitbit = new Fitbit(config.fitbit);
const tokenFile = 'fb-token.json';
module.exports = {
getYesterdayFitbit: function() {
return new Promise(function(resolve, reject) {
const yesterday = Date.create('yesterday').format('{yyyy}-{MM}-{dd}');
const url = 'https://api.fitbit.com/1/user/-/activities/date/' + yesterday + '.json';
logger.info('Getting fitbit for: ', yesterday);
logger.debug(url);
fitbit.request({
uri: url,
method: 'GET'
}, function( err, body, token ) {
if ( err ) {
return reject(err);
}
const profile = JSON.parse(body);
// if token is not null, a refesh has happened and we need to persist the new token
if ( token )
jsonfile.writeFile(tokenFile, token, function( err ) {
if ( err ) {
return reject(err);
}
return resolve(profile);
});
else
{
return resolve(profile);
}
});
});
}
};
jsonfile.readFile(tokenFile, function(err, obj) {
if (err) {
logger.error('Today Fitbit token failed to load');
logger.warn(err);
}
else {
logger.info('Fitbit token loaded...');
fitbit.setToken(obj);
}
});

152
lib/history.js Normal file
View File

@ -0,0 +1,152 @@
const request = require('request');
const cheerio = require('cheerio');
const STRING = require('string');
const logger = require('log4js').getLogger('history');
module.exports = {
'getTechHistory': function() {
let url;
let d;
let day;
let month;
const 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;
const $ = cheerio.load(body);
const tdihbody = $('#tdihbody .tdihevent');
const output = [];
tdihbody.find('p').each(function(div) {
const 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() {
let url;
const d = new Date();
let day;
let month;
const 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;
const $ = cheerio.load(body);
const nbody = $('DIV#bbcPageContent').first();
const output = [];
nbody.find('.story > p').each(function(div) {
const 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';
let 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);
});
});
}
};

37
lib/mailer.js Normal file
View File

@ -0,0 +1,37 @@
/**
*
* User: Martin Donnelly
* Date: 2016-04-08
* Time: 16:35
*
*/
var jade = require('pug'), UltraSES = require('ultrases'), dateFormat = require('dateformat');
var logger = require('log4js').getLogger('mailer');
var mailer = new UltraSES({
aws: {
accessKeyId: 'AKIAJWJS75F7WNCGK64A',
secretAccessKey: '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',
region: 'eu-west-1'
}, defaults: {
from: 'Martin Donnelly <martind2000@gmail.com>'
}
});
module.exports = {
sendEmailV1: function(todayCache, newpath) {
var now = new Date();
var email = {
to: 'martind2000@gmail.com', subject: 'Today - ' + dateFormat(now, 'dddd, mmmm dS, yyyy')
};
var template = {
file: newpath + '/' + 'jade/today.jade', locals: todayCache
};
mailer.sendTemplate(email, template, function(err) {
if (err) throw err;
logger.info('compiled template email sent');
});
}
};

40
lib/quotes.js Normal file
View File

@ -0,0 +1,40 @@
/**
* Created by Martin on 31/03/2016.
*/
const https = require('https');
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) {
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();
});
}
};

38
lib/swedishword.js Normal file
View File

@ -0,0 +1,38 @@
/**
* Created by Martin on 15/02/2016.
*/
const http = require('http');
const request = require('request');
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) {
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);
}
});
});
}
};
// module.exports.getSwedishWord();

16
lib/swedishword.spec.js Normal file
View File

@ -0,0 +1,16 @@
const swedishWord = require('./swedishword.js');
test('Test swedishword', () => {
return swedishWord.getSwedishWord()
.then((d) => {
console.log('Swedish result: ', JSON.stringify(d));
console.log(d.xml.words.language);
//expect(d.xml.words.language).toEqual('Swedish');
})
.catch((e)=> {
'use strict';
expect(e).toBeNull();
});
done();
});

26
lib/test.js Normal file
View File

@ -0,0 +1,26 @@
/**
*
* User: Martin Donnelly
* Date: 2016-10-23
* Time: 23:22
*
*/
const calHandler = require('./calHandler');
const logger = require('log4js').getLogger();
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);
});

25
lib/todayftse.js Normal file
View File

@ -0,0 +1,25 @@
/**
*
* User: Martin Donnelly
* Date: 2016-06-23
* Time: 11:45
*
*/
const ftse = require('ftse');
module.exports = {
'getFTSE': function() {
return new Promise(function(resolve, reject) {
'use strict';
const err = 0;
ftse('100', 10, 'risers', function(items) {
if (items === err)
return reject(err);
return resolve(items);
});
});
}
};

122
lib/trains.js Normal file
View File

@ -0,0 +1,122 @@
/**
* Created by Martin on 31/03/2016.
*/
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='
}
];
module.exports = {
'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);
});
us.find('.updateBodyStart').each(function (div) {
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;
});
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;
const 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;
let trainData = module.exports.processTrainUpdates(body);
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 (!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..');
const 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);
});
});
}
};

13
lib/trains.spec.js Normal file
View File

@ -0,0 +1,13 @@
const trains = require('./trains.js');
test('Test trains', () => {
return trains.updateTrains()
.then((d) => {
console.log('Trains: ', d);
expect(d).toBeDefined();
})
.catch((e)=> {
expect(e).toBeNull();
});
done();
});

48
lib/weather.js Normal file
View File

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

13
lib/weather.spec.js Normal file
View File

@ -0,0 +1,13 @@
const weather = require('./weather.js');
test('Test weather', () => {
return weather.newDoGetWeather()
.then((d) => {
expect(d.data.latitude).toEqual(55.95);
expect(d.data.longitude).toEqual(-4.566667);
}).catch((e) => {
console.error(e);
expect(e).toBeNull();
});
done();
});

3392
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

36
package.json Normal file
View File

@ -0,0 +1,36 @@
{
"name": "today",
"version": "1.0.0",
"description": "Today Emailer",
"main": "todayV2.js",
"scripts": {
"start": "node todayV2.js"
},
"repository": {
"type": "git",
"url": "https://gitlab.silvrtree.co.uk/martind2000/today.git"
},
"author": "",
"license": "ISC",
"dependencies": {
"cheerio": "^1.0.0-rc.2",
"cloudant": "^1.8.0",
"dateformat": "^3.0.2",
"elapsed": "0.0.7",
"fitbit-oauth2": "0.0.1",
"forecast.io": "0.0.11",
"ftse": "^1.0.6",
"jsonfile": "^4.0.0",
"lodash": "^4.17.4",
"log4js": "^2.3.10",
"node-cron": "^1.2.1",
"node-localstorage": "^1.3.0",
"pug": "^2.0.0-rc.4",
"request": "^2.83.0",
"string": "^3.3.3",
"sugar": "^2.0.4",
"sugar-date": "^2.0.4",
"ultrases": "^0.1.3",
"xmljson": "^0.2.0"
}
}

503
todayV2.js Normal file
View File

@ -0,0 +1,503 @@
/**
* Created by marti on 30/01/2016.
*/
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('./lib/calHandler');
const swedishWord = require('./lib/swedishword');
const weather = require('./lib/weather');
const trains = require('./lib/trains');
const history = require('./lib/history');
const mdMailer = require('./lib/mailer');
// const mdFitbit = require('./lib/fitbit');
const todayFTSE = require('./lib/todayftse');
const quotes = require('./lib/quotes');
// var db_name = 'silvrgit';
// var dbCloudant = nano.use(db_name);
/*
We've moved to cloudant through IBM Bluemix for the database
https://25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix.cloudant.com/dashboard.html#usage
*/
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'
};
const Cloudant = require('cloudant');
const cloudant = Cloudant({ 'account': credentials.username, 'password': credentials.password });
const dbCloudant = cloudant.db.use(credentials.database);
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;
}
};
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)
};
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;
}
}
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
};
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 {
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));
}
function saveToDB(data) {
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;
}
});
}
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')));
}
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);
}
function breakDay() {
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) {
if (typeof d[items].title !== 'undefined') {
const hash = d[items].title.hashCode();
if (titles.indexOf(hash) === -1) {
titles.push(hash);
ta.push(d[items]);
}
}
}*/
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 {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 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);
}
};
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 Sugar.Date();
const nextYear = `${(parseInt(d.getFullYear().raw) + 1).toString() }-01-01`;
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}').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 ${d.format('{yyyy}').raw}, and there are ${daysRemaining} days until the end of the year`;
logger.debug(s);
todayCache.data.today = s;
},
'refreshTrain': function () {
trains.updateTrains()
.then((d) => {
'use strict';
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);
});
},
'refreshTrainAndWeather': function () {
this.refreshTrain();
this.refreshWeather();
},
'preLoadToday': async function () {
function compare(a, b) {
if (a.ts < b.ts) {
return -1;
}
if (a.ts > b.ts) {
return 1;
}
return 0;
}
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);
});
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);
});*/
for (const item of calHandler.calendars)
await calHandler.getAdvancedCalV3(item)
.then((d) => {
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);
});
console.log('>> SORT!!');
todayCache.data.cal.today = todayCache.data.cal.today.sort(compare);
todayCache.data.cal.tomorrow = todayCache.data.cal.tomorrow.sort(compare);
todayCache.data.cal.week = todayCache.data.cal.week.sort(compare);
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 });
}
};
setTimeout(function () {
loadData();
if (runable())
module.exports.preLoadToday();
// Module.exports.preLoadToday();
}, 5000);
setTimeout(function () {
logger.debug('Going to do the email...');
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});
}, (60000));
cron.schedule('15 7 * * *', function () {
if (runable()) {
module.exports.preLoadToday();
saveToDB(todayCache);
saveData();
}
return -1;
});
cron.schedule('30 7 * * *', function () {
mdMailer.sendEmailV1(todayCache, __dirname);
// saveToDB(todayCache);
// Console.log('tick');
return -1;
});