tidying up

This commit is contained in:
martind2000 2017-03-22 15:48:36 +00:00
parent 5e217385ce
commit 9b2ffdf0d8
18 changed files with 1441 additions and 603 deletions

View File

@ -1,9 +1,8 @@
(function () {
var lastGBP = 0.0,
(function() {
let lastGBP = 0.0,
lastUSD = 0.0,
_fasttimer, _slowTimer, myBTC = 3.49524333;
var lows = {
let lows = {
gbp: 0,
usd: 0
},
@ -12,65 +11,66 @@
usd: 0
};
var list = [{
let list = [{
title: '101B ends',
y: 2013,
m: 9,
d: 24,
add: 1001
},
{
title: 'Ends',
y: 2016,
m: 4,
d: 4
}];
{
title: 'Ends',
y: 2016,
m: 4,
d: 4
}];
MicroEvent.mixin(this);
var self = this;
let self = this;
var addDays = function (myDate, days) {
let addDays = function(myDate, days) {
return new Date(myDate.getTime() + days * 24 * 60 * 60 * 1000);
};
var getDays = function (startdate, enddate) {
var r, s, e;
let getDays = function(startdate, enddate) {
let r, s, e;
s = startdate.getTime();
e = enddate.getTime();
r = (e - s) / (24 * 60 * 60 * 1000);
return r;
};
var tick = function () {
var today = new Date();
var start101 = new Date();
var end101;
var endContract = new Date();
var third = new Date();
let tick = function() {
let today = new Date();
let start101 = new Date();
let end101;
let endContract = new Date();
let third = new Date();
start101.setFullYear(2013, 9, 24);
end101 = addDays(start101, 1001);
endContract.setFullYear(2016, 4, 4);
endContract.setFullYear(2017, 6, 5);
third.setFullYear(2013, 7, 25);
$('#one').text('101B ends: ' + Math.ceil(getDays(today,
end101)) + " days / " + Math.ceil(getDays(today,
end101) / 7) + " weeks");
/*$('#one').text('101B ends: ' + Math.ceil(getDays(today,
end101)) + ' days / ' + Math.ceil(getDays(today,
end101) / 7) + ' weeks');*/
$('#one').hide();
$('#two').text('Ends: ' + Math.ceil(getDays(today,
endContract)) + " days / " + Math.ceil(getDays(today,
endContract) / 7) + " weeks");
endContract)) + ' days / ' + Math.ceil(getDays(today,
endContract) / 7) + ' weeks');
$('#three').hide();
};
var get_weather = function () {
let get_weather = function() {
navigator.geolocation.getCurrentPosition(show_weather);
};
this.bind('displayWeather', function (data) {
$('#weather').html(data.currently.summary + ' ' + data.currently.temperature + '&deg;c&nbsp;<em>' + data.daily.summary + '</em>');
this.bind('displayWeather', function(data) {
$('#weather').html(data.currently.summary + ' ' + data.currently.temperature + '&deg;c&nbsp;<em>' + data.daily.summary + '</em>');
});
var show_weather = function (position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var show_weather = function(position) {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
// let's show a map or do something interesting!
$.ajax({
type: 'GET',
@ -85,28 +85,26 @@
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
},
success: function (data) {
success: function(data) {
self.trigger('displayWeather', data);
},
error: function (xhr, type) {
console.log("ajax error");
error: function(xhr, type) {
console.log('ajax error');
console.log(xhr);
console.log(type);
}
});
};
var updateBTC = function (g, u) {
var title, total, elm = $('#btc');
let updateBTC = function(g, u) {
let title, total, elm = $('#btc');
if (lastGBP !== 0) {
elm.removeClass();
if (g > lastGBP) {
elm.addClass('up');
} else if (g < lastGBP) {
elm.addClass('down');
}
} else {
lows.gbp = g;
lows.usd = u;
@ -126,23 +124,23 @@
total = myBTC * g;
title = "High: $" + parseFloat(highs.usd.toFixed(2)) + " / Low $" + parseFloat(lows.usd.toFixed(2));
elm.html("&#36;" + parseFloat(u.toFixed(2)) + " / &pound;" + parseFloat(g.toFixed(2)) + " (&pound;" + parseFloat(total.toFixed(2)) + ")");
title = 'High: $' + parseFloat(highs.usd.toFixed(2)) + ' / Low $' + parseFloat(lows.usd.toFixed(2));
elm.html('&#36;' + parseFloat(u.toFixed(2)) + ' / &pound;' + parseFloat(g.toFixed(2)) + ' (&pound;' + parseFloat(total.toFixed(2)) + ')');
elm.prop('title', title);
};
var updateFX = function (data) {
var elm = $('#fx');
elm.html("&pound;1 = &#36;" + parseFloat(data.gpbe.toFixed(2)) + " = " + parseFloat(data.sekex.toFixed(2)) + " SEK");
let updateFX = function(data) {
let elm = $('#fx');
elm.html('&pound;1 = &#36;' + parseFloat(data.gpbe.toFixed(2)) + ' = ' + parseFloat(data.sekex.toFixed(2)) + ' SEK');
};
this.bind('updateFX', function (data) {
$('#fx').html("&pound;1 = &#36;" + parseFloat(data.gpbe.toFixed(2)) + " = " + parseFloat(data.sekex.toFixed(2)) + " SEK");
this.bind('updateFX', function(data) {
$('#fx').html('&pound;1 = &#36;' + parseFloat(data.gpbe.toFixed(2)) + ' = ' + parseFloat(data.sekex.toFixed(2)) + ' SEK');
});
var btcValue = function () {
var url = '/btc';
let btcValue = function() {
let url = '/btc';
$.ajax({
type: 'GET',
@ -159,27 +157,27 @@
'Access-Control-Allow-Headers': 'Content-Type'
},
success: function (data) {
success: function(data) {
// console.log(data);
var gbp = data.bpi.GBP.rate_float,
let gbp = data.bpi.GBP.rate_float,
usd = data.bpi.USD.rate_float;
updateBTC(gbp, usd);
},
error: function (xhr, type) {
console.log("ajax error");
error: function(xhr, type) {
console.log('ajax error');
console.log(xhr);
console.log(type);
}
});
};
this.bind('getBTC', function () {
/*this.bind('getBTC', function() {
btcValue();
});
});*/
var getFX = function () {
var url = '/fx';
let getFX = function() {
let url = '/fx';
$.ajax({
type: 'GET',
@ -196,10 +194,10 @@
'Access-Control-Allow-Headers': 'Content-Type'
},
success: function (data) {
var gpbex = (1 / data.rates.GBP);
var sekex = (gpbex * data.rates.SEK);
var fxdata = {
success: function(data) {
let gpbex = (1 / data.rates.GBP);
let sekex = (gpbex * data.rates.SEK);
let fxdata = {
usd: 1,
gbp: data.rates.GBP,
sek: data.rates.SEK,
@ -208,21 +206,21 @@
};
self.trigger('updateFX', fxdata);
},
error: function (xhr, type) {
console.log("ajax error");
error: function(xhr, type) {
console.log('ajax error');
console.log(xhr);
console.log(type);
}
});
};
this.bind('getFX', function () {
this.bind('getFX', function() {
getFX();
});
var getNextTrainTime = function (toStation, fromStation) {
var url = '/getnexttraintimes?from=' + fromStation + '&to=' + toStation;
var target = fromStation + toStation;
let getNextTrainTime = function(toStation, fromStation) {
let url = '/getnexttraintimes?from=' + fromStation + '&to=' + toStation;
let target = fromStation + toStation;
$.ajax({
type: 'GET',
url: url,
@ -236,42 +234,41 @@
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
},
success: function (data) {
success: function(data) {
updateTrain(target, data);
},
error: function (xhr, type) {
console.log("ajax error");
error: function(xhr, type) {
console.log('ajax error');
console.log(xhr);
console.log(type);
}
});
};
var updateTrain = function (n, obj) {
var elm = $('#' + n);
var updateTrain = function(n, obj) {
let elm = $('#' + n);
var output, status;
let output, status;
output = (obj.eta == "On Time") ? obj.eta : obj.sta;
status = (obj.eta == "On Time") ? 'delayed' : 'ontime';
output = (obj.eta == 'On Time') ? obj.eta : obj.sta;
status = (obj.eta == 'On Time') ? 'delayed' : 'ontime';
elm.html(output);
elm.removeClass('delayed').removeClass('ontime').addClass( status);
//elm.addClass( status);
};
var getTrainsCB = function (results) {
var dest$ = $('#trainResults');
var html = new EJS({url: '/template/trains.ejs'}).render(results);
let getTrainsCB = function(results) {
let dest$ = $('#trainResults');
let html = new EJS({url: '/template/trains.ejs'}).render(results);
dest$.empty();
dest$.append(html);
dest$.toggle();
};
var getTrains = function (from, to) {
var url = '/gettrains?from=' + from + "&to=" + to;
let getTrains = function(from, to) {
let url = '/gettrains?from=' + from + '&to=' + to;
$.ajax({
type: 'GET',
@ -286,28 +283,27 @@
'Access-Control-Allow-Headers': 'Content-Type'
},
success: function (data) {
success: function(data) {
getTrainsCB(data);
},
error: function (xhr, type) {
console.log("ajax error");
error: function(xhr, type) {
console.log('ajax error');
console.log(xhr);
console.log(type);
}
});
};
var formatPassword = function (data) {
var dest$ = $('#passwordOut');
var html = new EJS({url: '/template/password.ejs'}).render(data);
let formatPassword = function(data) {
let dest$ = $('#passwordOut');
let html = new EJS({url: '/template/password.ejs'}).render(data);
dest$.empty();
dest$.append(html);
dest$.show();
};
var generatePassword = function (from, to) {
var url = '/generate';
let generatePassword = function(from, to) {
let url = '/generate';
$.ajax({
type: 'GET',
@ -323,11 +319,11 @@
'Access-Control-Allow-Headers': 'Content-Type'
},
success: function (data) {
success: function(data) {
formatPassword(data);
},
error: function (xhr, type) {
console.log("ajax error");
error: function(xhr, type) {
console.log('ajax error');
console.log(xhr);
console.log(type);
}
@ -343,47 +339,46 @@
// start 15 minute timer
_fastTimer = setInterval(function () {
_fastTimer = setInterval(function() {
self.trigger('getBTC');
getNextTrainTime('dbe', 'glq');
getNextTrainTime('glq', 'dbe');
}, (60000));
_slowTimer = setInterval(function () {
_slowTimer = setInterval(function() {
self.trigger('getFX');
get_weather();
}, (60000 * 15));
$('#dbeglq').on('click', function () {
$('#dbeglq').on('click', function() {
self.trigger('getTrains', 'dbe', 'glq');
});
$('#glqdbe').on('click', function () {
$('#glqdbe').on('click', function() {
self.trigger('getTrains', 'glq', 'dbe');
});
$('#newPassword').on('click', function () {
$('#newPassword').on('click', function() {
generatePassword();
});
this.bind('getTrains', function (start, end) {
this.bind('getTrains', function(start, end) {
getTrains(start, end);
});
document.title = 'Slack';
})();
var popitout = function (url) {
var newwindow = window.open(url, 'name', 'height=600,width=570');
if (window.focus) {
newwindow.focus()
}
return false;
};
var popitoutSmall = function (url) {
var newwindow = window.open(url, 'name', 'height=400,width=520');
let popitout = function(url) {
let newwindow = window.open(url, 'name', 'height=600,width=570');
if (window.focus) {
newwindow.focus();
}
return false;
};
let popitoutSmall = function(url) {
let newwindow = window.open(url, 'name', 'height=400,width=520');
if (window.focus) {
newwindow.focus();
}

117
app/js/modules/bitcoin.js Normal file
View File

@ -0,0 +1,117 @@
/**
* Created by mdonnel on 22/03/2017.
*/
let BitcoinModel = Backbone.Model.extend({
initialize: function () {
this.set('url', '/btc');
let data = {
lastGBP: 0.0,
lastUSD: 0.0,
lows: {gbp: 0, usd: 0},
highs: {gbp: 0, usd: 0},
eclass: ''
};
this.set('btcdata', data);
this.update();
},
update: function () {
this.getBTC();
const now = new Date;
const mod = 60000 - (now.getTime() % 60000);
let btcupdateFn = function() {
this.update();
};
setTimeout(btcupdateFn.bind(this), mod + 10);
},
recalc: function () {
let data = this.get('btcdata');
let lastGBP = data.lastGBP;
let lastUSD = data.lastUSD;
let g = data.gbp;
let u = data.usd;
let lows = data.lows;
let highs = data.highs;
let eclass = data.eclass;
if (data.lastGBP !== 0) {
if (g > lastGBP) {
eclass = 'up';
} else {
eclass = 'down';
}
} else {
lows.gbp = g;
lows.usd = u;
highs.gbp = g;
highs.usd = u;
}
lastGBP = g;
lastUSD = u;
if (g < lows.gbp) lows.gbp = g;
if (u < lows.usd) lows.usd = u;
if (highs.gbp < g) highs.gbp = g;
if (highs.usd < u) highs.usd = u;
data = {
lastGBP,
lastUSD,
lows,
highs,
eclass
};
this.set('btcdata', data);
// total = myBTC * g;
},
getBTC: function () {
let self = this;
let url = this.get('url');
$.ajax({
type: 'GET',
url: url,
data: '',
dataType: 'json',
timeout: 10000,
//contentType: ('application/json'),
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
},
success: function (data) {
let gbp = data.bpi.GBP.rate_float,
usd = data.bpi.USD.rate_float;
let btcdata = self.get('btcdata');
btcdata.gbp = gbp;
btcdata.usd = usd;
self.set('btcdata', btcdata);
self.recalc();
},
error: function (xhr, type) {
console.log('ajax error');
console.log(xhr);
console.log(type);
}
});
}
});
let Bitcoin = Backbone.View.extend({
tagName: 'div',
initialize: function () {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
this.$btc = $('#btc');
},
render: function () {
let btcdata = this.model.get('btcdata');
let title = 'High: $' + parseFloat(btcdata.highs.usd.toFixed(2)) + ' / Low $' + parseFloat(btcdata.lows.usd.toFixed(2));
this.$btc.removeClass();
this.$btc.addClass(btcdata.eclass);
this.$btc.html(`&#36;${parseFloat(btcdata.lastUSD.toFixed(2)) } / &pound;${parseFloat(btcdata.lastGBP.toFixed(2))}` );
this.$btc.prop('title', title);
}
});

65
gulpfile.js Normal file
View File

@ -0,0 +1,65 @@
const gulp = require('gulp');
let autoprefixer = require('gulp-autoprefixer');
let cssnano = require('gulp-cssnano');
let jshint = require('gulp-jshint');
let uglify = require('gulp-uglify');
let rename = require('gulp-rename');
let concat = require('gulp-concat');
let cache = require('gulp-cache');
let htmlmin = require('gulp-htmlmin');
let htmlreplace = require('gulp-html-replace');
let stripDebug = require('gulp-strip-debug');
let scss = require('gulp-scss');
let sass = require('gulp-sass');
let googleWebFonts = require('gulp-google-webfonts');
let babel = require('gulp-babel');
let filePath = {
build_dir: 'live'
};
let dest = 'live';
let fontOptions = { };
gulp.task('appJS', function() {
return gulp.src(['app/app.js'])
.pipe(stripDebug())
.pipe(jshint('.jshintrc'))
.pipe(jshint.reporter('default'))
.pipe(babel({presets: ['es2015']}))
.pipe(concat('app.js'))
.pipe(uglify({mangle: true, compress: {sequences: true, // Join consecutive statemets with the “comma operator”
properties: true, // Optimize property access: a["foo"] → a.foo
dead_code: true, // Discard unreachable code
drop_debugger: true, // Discard “debugger” statements
unsafe: false, // Some unsafe optimizations (see below)
conditionals: true, // Optimize if-s and conditional expressions
comparisons: true, // Optimize comparisons
evaluate: true, // Evaluate constant expressions
booleans: true, // Optimize boolean expressions
loops: true, // Optimize loops
unused: true, // Drop unused variables/functions
hoist_funs: true, // Hoist function declarations
hoist_vars: false, // Hoist variable declarations
if_return: true, // Optimize if-s followed by return/continue
join_vars: true, // Join var declarations
cascade: true, // Try to cascade `right` into `left` in sequences
side_effects: true, // Drop side-effect-free statements
warnings: true, // Warn about potentially dangerous optimizations/code
global_defs: {} // global definitions
}}))
.pipe(gulp.dest(dest + '/js'));
});
gulp.task('vendor', function() {
return gulp.src([
'app/libs/zepto.min.js',
'app/libs/microevent.js',
'app/libs/ejs.js'
])
.pipe(concat('vendor.js'))
.pipe(uglify({mangle: false}))
.pipe(gulp.dest(dest + '/js'));
});

View File

@ -1,15 +1,16 @@
/**
* Created by marti on 30/01/2016.
*/
let http = require('http'), request = require('request'), cheerio = require(
'cheerio'), util = require('util');
* 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');
let fs = require('fs');
//var nano = require('nano')('http://martind2000:1V3D4m526i@localhost:5984');
const log4js = require('log4js');
const logger = log4js.getLogger();
const logger = require('log4js').getLogger();
const calHandler = require('./today/calHandler');
const swedishWord = require('./today/swedishword');
const weather = require('./today/weather');
@ -37,7 +38,7 @@ const credentials = {
"host": "25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix.cloudant.com",
"port": 443,
"url": "https://25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix:8e417af1b0462ca55726848846cc6b8696fc76defe9d1864cbc334be59549e0c@25f854ee-1b51-49ff-acd9-5b0ff478d944-bluemix.cloudant.com",
"database": "keeper"
"database": "today"
};
const Cloudant = require('cloudant');
@ -46,25 +47,27 @@ const cloudant = Cloudant({account: credentials.username, password: credentials.
const dbCloudant = cloudant.db.use(credentials.database);
require('sugar-date');
String.prototype.hashCode = function() {
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);
return this.split('').reduce(function (a, b) {
a = ((a << 5) - a) + b.charCodeAt(0);
return a & a
}, 0);
} else {
let hash = 0, i, chr, len;
if (this.length == 0) return hash;
for (i = 0, len = this.length; i < len; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
let hash = 0, i, chr, len;
if (this.length === 0) return hash;
for (i = 0, len = this.length; i < len; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
};
};
let todayCache = {
last: 0, data: {
@ -84,363 +87,380 @@ let htmlfile = __dirname + '/' + 'today.html';
let eventEmitter;
function runable() {
try {
const now = new Date().getTime();
try {
const now = new Date().getTime();
console.log('last updated', ((now - todayCache.last) / 60000));
if (now - todayCache.last < 3600000) {
return false;
} else {
todayCache.last = now;
return true;
console.log('last updated', ((now - todayCache.last) / 60000));
if (now - todayCache.last < 3600000) {
return false;
} else {
todayCache.last = now;
return true;
}
}
}
catch (e) {
todayCache.last = new Date().getTime();
return true;
catch (e) {
todayCache.last = new Date().getTime();
return true;
}
}
}
function broadcastWeather() {
const wData = {
temperature: todayCache.data.weather.data.currently.temperature,
icon: todayCache.data.weather.data.currently.icon,
summary: todayCache.data.weather.data.currently.summary
};
const wData = {
temperature: todayCache.data.weather.data.currently.temperature,
icon: todayCache.data.weather.data.currently.icon,
summary: todayCache.data.weather.data.currently.summary
};
if (todayCache.data.weather.data.hasOwnProperty('alerts')) {
wData.alerts = todayCache.data.weather.data.alerts;
}
eventEmitter.emit('sendSocket', {id: 'weather', data: wData});
if (todayCache.data.weather.data.hasOwnProperty('alerts')) {
wData.alerts = todayCache.data.weather.data.alerts;
}
eventEmitter.emit('sendSocket', {id: 'weather', data: wData});
}
function loadData() {
console.log('Loading old data');
try {
todayCache = jsonfile.readFileSync(file);
}
catch (e) {
console.error('Could not load previous data');
}
console.log('Loading old data');
try {
todayCache = jsonfile.readFileSync(file);
}
catch (e) {
console.error('Could not load previous data');
}
}
function saveData() {
todayCache.last = new Date().getTime();
logger.info('Saving...');
jsonfile.writeFileSync(file, todayCache);
todayCache.last = new Date().getTime();
logger.info('Saving...');
jsonfile.writeFileSync(file, todayCache);
}
function saveToDB(data) {
saveData();
saveData();
logger.debug('Inserting into couch...');
// Logger.info(util.inspect(obj));
dbCloudant.insert(data, function(err, body, header) {
if (err) {
logger.error('Error inserting into couch');
logger.error(err);
return;
}
});
logger.debug('Inserting into couch...');
// Logger.info(util.inspect(obj));
dbCloudant.insert(data, function (err, body, header) {
if (err) {
logger.error('Error inserting into couch');
logger.error(err);
return;
}
});
}
function nth(d) {
// If (d > 3 && d < 21) {return 'th';} // Thanks kennebec
// if (d % 10 === 1) {return 'st';} else if (d % 10 === 2) {return 'nd';} else if (d % 10 === 3) {return 'rd';} else {return 'th';}
const n = d;
return Math.floor(n / 10) === 1 ? 'th' : (n % 10 === 1 ? 'st' : (n % 10 === 2 ? 'nd' : (n % 10 === 3 ? 'rd' : 'th')));
// If (d > 3 && d < 21) {return 'th';} // Thanks kennebec
// if (d % 10 === 1) {return 'st';} else if (d % 10 === 2) {return 'nd';} else if (d % 10 === 3) {return 'rd';} else {return 'th';}
const n = d;
return Math.floor(n / 10) === 1 ? 'th' : (n % 10 === 1 ? 'st' : (n % 10 === 2 ? 'nd' : (n % 10 === 3 ? 'rd' : 'th')));
}
function dayNumber() {
const now = new Date();
const start = new Date(now.getFullYear(), 0, 0);
const diff = now - start;
const oneDay = 1000 * 60 * 60 * 24;
return Math.floor(diff / oneDay);
const now = new Date();
const start = new Date(now.getFullYear(), 0, 0);
const diff = now - start;
const oneDay = 1000 * 60 * 60 * 24;
return Math.floor(diff / oneDay);
}
function breakDay() {
const now = new Date();
return {
year: now.getFullYear(),
month: parseInt(now.getMonth()) + 1,
day: now.getDate()
};
const now = new Date();
return {
year: now.getFullYear(),
month: parseInt(now.getMonth()) + 1,
day: now.getDate()
};
}
function reduceTrains(d) {
const titles = [], ta = [];
console.log('reducetrains',d);
for (let items in d) {
if (typeof d[items].title !== 'undefined') {
const hash = d[items].title.hashCode();
if (titles.indexOf(hash) === -1) {
titles.push(hash);
ta.push(d[items]);
}
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 (let item in d) {
if (typeof item.title !== 'undefined') {
const hash = item.title.hashCode();
if (titles.indexOf(hash) === -1) {
titles.push(hash);
ta.push(item);
}
}
}
}
return ta;
return ta;
}
/**
* @return {number}
*/
function DayDiff(CurrentDate) {
const TYear = CurrentDate.getFullYear();
const TDay = new Date('January, 01, ' + (parseInt(TYear) + 1));
TDay.getFullYear(TYear);
let DayCount = (TDay - CurrentDate) / (1000 * 60 * 60 * 24);
DayCount = Math.round(DayCount);
const TYear = CurrentDate.getFullYear();
const TDay = new Date('January, 01, ' + (parseInt(TYear) + 1));
TDay.getFullYear(TYear);
let DayCount = (TDay - CurrentDate) / (1000 * 60 * 60 * 24);
DayCount = Math.round(DayCount);
const d = new Date();
DayCount = d.daysSince('beginning of this year');
return (DayCount);
const d = new Date();
DayCount = d.daysSince('beginning of this year');
return (DayCount);
}
Array.prototype.indexOfOld = Array.prototype.indexOf;
Array.prototype.indexOf = function(e, fn) {
if (!fn) {
return this.indexOfOld(e);
} else {
if (typeof fn === 'string') {
const att = fn;
fn = function(e) {
return e[att];
};
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);
}
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;
setEmitter: function (newEmitter) {
console.log('Setting events', newEmitter);
eventEmitter = newEmitter;
},
getClock: function (req, res) {
// Console.log(todayCache);
res.render('pages/clock', todayCache);
},
getToday: function (req, res) {
logger.info(todayCache);
res.render('pages/today', todayCache);
},
getData: function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(todayCache));
},
getTodayDate: function () {
let s;
const d = new Date();
let nextYear = (parseInt(d.getFullYear()) + 1).toString() + '-01-01';
console.log(d.daysUntil('beginning of next year'));
const daysSinceStart = d.daysSince('beginning of this year');
const daysRemaining = d.daysUntil('beginning of next year');
console.log(d.daysUntil('beginning of next year'));
const daysSinceStart = d.daysSince('beginning of this year');
const daysRemaining = d.daysUntil('beginning of next year');
todayCache.data.history = [];
s = '<strong>' + d.format('{Weekday} {Month} {dd}, {yyyy}') + '</strong> - ';
todayCache.data.history = [];
s = '<strong>' + d.format('{Weekday} {Month} {dd}, {yyyy}') + '</strong> - ';
s = s + 'The ' + daysSinceStart + nth(daysSinceStart) + ' day of ' + dateFormat(
d,
'yyyy') + ', and there are ' + daysRemaining + ' days left until the end of the year.';
/*
s = s + 'The ' + daysSinceStart + nth(daysSinceStart) + ' day of ' + dateFormat(
d,
'yyyy') + ', and there are ' + daysRemaining + ' days left until the end of the year.';
*/
logger.debug(s);
todayCache.data.today = s;
},
refreshTrain: function() {
s = s + `The ${daysSinceStart + nth(daysSinceStart)} day of ${dateFormat(d, 'yyyy')}, and there are ${daysRemaining} days until the end of the year`
trains.updateTrains()
.then((d) => {
'use strict';
logger.debug(s);
todayCache.data.today = s;
},
refreshTrain: function () {
d = reduceTrains(d);
console.log('Trains: ', d);
eventEmitter.emit('sendSocket', {id: 'trains', data: d});
todayCache.data.trains.data = d;
todayCache.data.trains.last = new Date();
})
.catch((e)=> {
'use strict';
console.error(e);
});
},
refreshWeather: function() {
weather.newDoGetWeather()
.then((d) => {
todayCache.data.weather = d;
console.log('Updating weather');
broadcastWeather();
}).catch((e) => {
logger.error(e);
});
},
refreshTrainAndWeather: function() {
this.refreshTrain();
this.refreshWeather();
}, preLoadToday: function() {
module.exports.getTodayDate();
todayCache.data.cal = {today: [], tomorrow: [], week: []};
weather.newDoGetWeather()
.then((d)=> {
todayCache.data.weather = d;
})
.catch((e) => {
logger.error(e);
});
trains.updateTrains()
.then((d) => {
'use strict';
console.log('Trains: ', d);
todayCache.data.trains.data = d;
todayCache.data.trains.last = new Date();
})
.catch((e)=> {
'use strict';
console.error(e);
});
history.updateHistory()
.then((d) => {
'use strict';
console.log('History result: ', d);
todayCache.data.history = d;
})
.catch((e)=> {
'use strict';
console.error(e);
});
calHandler.getSimpleCalV3(
'http://www.pogdesign.co.uk/cat/download_ics/60cfdff469d0490545d33d7e3b5c0bcc')
.then((d) => {
'use strict';
todayCache.data.tv = d;
})
.catch((e) => {
'use strict';
logger.error(e);
});
todayFTSE.getFTSE()
.then((d) => {
todayCache.data.ftse = d;
})
.catch((e) => {
logger.error(e);
});
quotes.GetQuotes()
trains.updateTrains()
.then((d) => {
todayCache.data.quotes = 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)=> {
logger.error(e);
.catch((e) => {
'use strict';
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';
},
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: function () {
module.exports.getTodayDate();
todayCache.data.cal = {today: [], tomorrow: [], week: []};
weather.newDoGetWeather()
.then((d) => {
todayCache.data.weather = d;
})
.catch((e) => {
logger.error(e);
});
trains.updateTrains()
.then((d) => {
'use strict';
console.log('Trains: ', d);
todayCache.data.trains.data = d;
todayCache.data.trains.last = new Date();
})
.catch((e) => {
'use strict';
console.error(e);
});
history.updateHistory()
.then((d) => {
'use strict';
console.log('History result: ', d);
todayCache.data.history = d;
})
.catch((e) => {
'use strict';
console.error(e);
});
calHandler.getSimpleCalV3(
'http://www.pogdesign.co.uk/cat/download_ics/60cfdff469d0490545d33d7e3b5c0bcc')
.then((d) => {
'use strict';
todayCache.data.tv = d;
})
.catch((e) => {
'use strict';
logger.error(e);
});
todayFTSE.getFTSE()
.then((d) => {
todayCache.data.ftse = d;
})
.catch((e) => {
logger.error(e);
});
quotes.GetQuotes()
.then((d) => {
todayCache.data.quotes = d;
})
.catch((e) => {
logger.error(e);
});
for (let t = 0; t < calHandler.calendars.length; t++) {
calHandler.getAdvancedCalV3(calHandler.calendars[t])
.then((d) => {
'use strict';
todayCache.data.cal.today = todayCache.data.cal.today.concat(d.today);
todayCache.data.cal.tomorrow = todayCache.data.cal.tomorrow.concat(d.tomorrow);
todayCache.data.cal.week = todayCache.data.cal.week.concat(d.week);
})
.catch((e) => {
'use strict';
logger.error(e);
});
}
swedishWord.getSwedishWord()
.then((d) => {
'use strict';
console.log('Swedish result: ', d);
todayCache.data.swedish = d;
})
.catch((e) => {
'use strict';
console.error(e);
});
mdFitbit.getYesterdayFitbit()
.then((d) => {
todayCache.data.fitbit = d;
})
.catch((e) => {
'use strict';
console.error(e);
});
todayCache.date = breakDay();
}, broadcast: function () {
console.log('BROADCAST');
broadcastWeather();
eventEmitter.emit('sendSocket', {id: 'trains', data: todayCache.data.trains.data});
}
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();
}, 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();
setTimeout(function () {
loadData();
if (runable()) {
module.exports.preLoadToday();
}
//Module.exports.preLoadToday();
}, 5000);
setTimeout(function() {
// mdMailer.sendEmailV1(todayCache, __dirname);
// saveToDB(todayCache);
saveData();
setTimeout(function () {
// mdMailer.sendEmailV1(todayCache, __dirname);
// saveToDB(todayCache);
saveData();
}, 45000);
setInterval(function() {
setInterval(function () {
// EventEmitter.emit('sendSocket',{id:'weather',data:todayCache.data.weather});
// broadcastWeather();
// eventEmitter.emit('sendSocket', {id: 'trains', data: todayCache.data.trains.data});
// EventEmitter.emit('sendSocket',{id:'weather',data:todayCache.data.weather});
// broadcastWeather();
// eventEmitter.emit('sendSocket', {id: 'trains', data: todayCache.data.trains.data});
}, (60000));
cron.schedule('30 6 * * *', function() {
if (runable()) {
module.exports.preLoadToday();
}
cron.schedule('30 6 * * *', function () {
if (runable()) {
module.exports.preLoadToday();
}
return -1;
return -1;
});
cron.schedule('0 */1 * * *', function() {
// Module.exports.refreshTrainAndWeather();
// this.refreshTrain();
module.exports.refreshWeather();
cron.schedule('0 */1 * * *', function () {
// Module.exports.refreshTrainAndWeather();
// this.refreshTrain();
module.exports.refreshWeather();
return -1;
return -1;
});
cron.schedule('*/15 * * * *', function() {
module.exports.refreshTrain();
cron.schedule('*/15 * * * *', function () {
module.exports.refreshTrain();
// Module.exports.refreshWeather();
// Module.exports.refreshWeather();
return -1;
return -1;
});
cron.schedule('45 6 * * *', function() {
mdMailer.sendEmailV1(todayCache, __dirname);
saveToDB(todayCache);
// Console.log('tick');
return -1;
cron.schedule('45 6 * * *', function () {
mdMailer.sendEmailV1(todayCache, __dirname);
saveToDB(todayCache);
// Console.log('tick');
return -1;
});

View File

@ -5,7 +5,7 @@
* Time: 16:35
*
*/
var jade = require('jade'), UltraSES = require('ultrases'), dateFormat = require('dateformat');
var jade = require('pug'), UltraSES = require('ultrases'), dateFormat = require('dateformat');
var logger = require('log4js').getLogger();

View File

@ -1,30 +1,22 @@
/**
* Created by Martin on 15/02/2016.
*/
var http = require('http'), request = require('request'), util = require('util');
var jsonfile = require('jsonfile');
var log4js = require('log4js');
var logger = log4js.getLogger();
var to_json = require('xmljson').to_json;
let http = require('http');
const request = require('request');
let util = require('util');
const logger = require('log4js').getLogger();
const to_json = require('xmljson').to_json;
require('sugar-date');
var file = __dirname + '/' + 'cal.json';
function saveData(v) {
jsonfile.writeFileSync(file, v);
}
module.exports = {
getSwedishWord: function () {
return new Promise(function(resolve, reject) {
"use strict";
var t= new Date(), ms = t.getTime();
const t = new Date(), ms = t.getTime();
var url = ['http://wotd.transparent.com/rss/swedish-widget.xml?t=', ms].join('');
logger.info(url);
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);

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();
});

View File

@ -5,8 +5,7 @@
* Time: 11:45
*
*/
var ftse = require('ftse');
const ftse = require('ftse');
module.exports = {
@ -15,7 +14,7 @@ module.exports = {
return new Promise(function(resolve, reject) {
"use strict";
var err = 0;
let err = 0;
ftse('100', 10, 'risers', function(items) {
if (items === err) {

13
lib/today/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();
});

View File

@ -1,12 +1,12 @@
/**
* Created by Martin on 31/03/2016.
*/
var Forecast = require('forecast.io');
var STRING = require('string');
var logger = require('log4js').getLogger();
const Forecast = require('forecast.io');
const STRING = require('string');
const logger = require('log4js').getLogger();
var forecastOptions = {
const forecastOptions = {
APIKey: '9ad2a41d420f3cf4960571bb886f710c', units: 'uk2'
};
@ -15,19 +15,17 @@ module.exports = {
'use strict';
return new Promise(function(resolve, reject) {
logger.info('New Retrieving weather..');
var j = {};
var forecast = new Forecast(forecastOptions);
const j = {};
const forecast = new Forecast(forecastOptions);
forecast.get(55.95, -4.566667,
{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);
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;
@ -35,8 +33,8 @@ module.exports = {
j.alerts = data.alerts || {};
j.data = data;
var fs = STRING(j.currently).endsWith('.') ? '' : '.';
if (tempMax == tempMin) {
const fs = STRING(j.currently).endsWith('.') ? '' : '.';
if (tempMax === tempMin) {
j.currently += fs + ' Around ' + tempMin.toString() + ' degrees.';
}
else {

13
lib/today/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();
});

View File

@ -1,31 +1,27 @@
// train.js
var http = require('http');
var trainCache = {
const http = require('http');
const logger = require('log4js').getLogger();
let trainCache = {
last: {},
data: {}
};
module.exports = {
dbe_glq: function (req, res) {
console.log('DBE:GLQ request');
logger.info('DBE:GLQ request');
var now = new Date();
var nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60);
console.log('Now Seconds: ' + nowSeconds);
if (trainCache.last.dbeglq == null || nowSeconds != trainCache.last.dbeglq) {
const now = new Date();
const nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60);
if (trainCache.last.dbeglq === null || nowSeconds !== trainCache.last.dbeglq) {
Query(function (a, b) {
var ts = a.departures[0].service;
var output = {};
console.log(ts);
console.log(ts.sta);
const ts = a.departures[0].service;
let output = {};
logger.debug(ts);
logger.debug(ts.sta);
output.sta = ts.sta;
output.eta = ts.eta;
trainCache.data.dbeglq = output;
@ -38,20 +34,20 @@ module.exports = {
},
glq_dbe: function (req, res) {
console.log('GLQ:DBE request');
logger.info('GLQ:DBE request');
var now = new Date();
var nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60);
console.log('Now Seconds: ' + nowSeconds);
if (trainCache.last.glqdbe == null || nowSeconds != trainCache.last.dbeglq) {
const now = new Date();
const nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60);
if (trainCache.last.glqdbe === null || nowSeconds !== trainCache.last.dbeglq) {
Query(function (a, b) {
var ts = a.departures[0].service;
var output = {};
console.log(ts);
const ts = a.departures[0].service;
const output = {};
logger.debug(ts);
//GLOBAL.lastcheck = now;
console.log(ts.sta);
console.log(toSeconds(ts.sta));
logger.debug(ts.sta);
logger.debug(toSeconds(ts.sta));
output.sta = ts.sta;
output.eta = ts.eta;
@ -66,11 +62,11 @@ module.exports = {
},
getTrainTimes: function(req, res) {
// console.log(req);
console.log('getTrainTimes: ' + JSON.stringify(req.query));
logger.info('getTrainTimes: ' + JSON.stringify(req.query));
if (req.query.hasOwnProperty('from') && req.query.hasOwnProperty('from'))
{
var url = '/all/' + req.query.from + '/to/' + req.query.to + '/10?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8';
const url = '/all/' + req.query.from + '/to/' + req.query.to + '/10?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8';
Query(function (a, b) {
res.setHeader('Content-Type', 'application/json');
@ -84,8 +80,8 @@ module.exports = {
},
getNextTrainTimes: function(req, res) {
console.log('getNextTrainTimes: ' + JSON.stringify(req.query));
var trainFrom, trainTo, trainToken, url;
logger.info('getNextTrainTimes: ' + JSON.stringify(req.query));
let trainFrom, trainTo, trainToken, url;
if (req.query.hasOwnProperty('from') && req.query.hasOwnProperty('from')) {
trainFrom = req.query.from;
trainTo = req.query.to;
@ -93,21 +89,21 @@ module.exports = {
url = '/next/' + trainFrom + '/to/' + trainTo + '/1?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8';
console.log('Requesting latest time for : ' + trainToken);
var now = new Date();
var nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60);
const now = new Date();
const nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60);
console.log('Now Seconds: ' + nowSeconds);
if (trainCache.last[trainToken] == null || nowSeconds != trainCache.last[trainToken]) {
if (trainCache.last[trainToken] === null || nowSeconds !== trainCache.last[trainToken]) {
Query(function (a, b) {
var output = {};
var ts = a.departures[0].service;
const output = {};
const ts = a.departures[0].service;
if ( ts !== null)
{
// console.log(ts);
//GLOBAL.lastcheck = now;
console.log(ts.sta);
console.log(toSeconds(ts.sta));
logger.debug(ts.sta);
logger.debug(toSeconds(ts.sta));
output.sta = ts.sta;
output.eta = (ts.eta !== null ? ts.eta : ts.sta);
@ -115,7 +111,7 @@ module.exports = {
// console.log(ts);
} else
{
console.log('*** NO SERVICE');
logger.warn('*** NO SERVICE');
output.sta = 'No Service';
output.eta = 'No Service';
}
@ -130,8 +126,9 @@ module.exports = {
}
}, getRoute: function(req, res) {
console.log('getRoute: ' + JSON.stringify(req.query));
var routeID, data={};
logger.info('getRoute: ' + JSON.stringify(req.query));
let routeID;
const data = {};
if (req.query.hasOwnProperty('route')) {
routeID = req.query.route;
@ -149,15 +146,15 @@ module.exports = {
};
function toSeconds(inval) {
var a = inval.split(':');
const a = inval.split(':');
return ((parseInt(a[0]) * (60 * 60)) + (parseInt(a[1]) * 60));
}
function Query(callback, r, host, path) {
console.log(path);
var req = r;
var options = {
logger.debug(path);
const req = r;
const options = {
host: host,
// port: 80,
path: path,
@ -167,7 +164,7 @@ function Query(callback, r, host, path) {
try {
http.request(options).on('response', function (response) {
var data = '';
let data = '';
response.on("data", function (chunk) {
data += chunk;
});

View File

@ -1,18 +1,21 @@
/**
* Created by marti on 14/02/2016.
*/
var http = require('http'), request = require('request'), cheerio = require('cheerio'), Forecast = require('forecast.io'), util = require('util'), UltraSES = require('ultrases'), cron = require('node-cron');
var jade = require('jade'), _ = require('lodash'), dateFormat = require('dateformat');
var jsonfile = require('jsonfile'), fs = require('fs');
var log4js = require('log4js');
var logger = log4js.getLogger();
const http = require('http');
const request = require('request');
const Forecast = require('forecast.io');
const util = require('util');
const jsonfile = require('jsonfile');
const fs = require('fs');
const logger = require('log4js').getLogger();
var forecastOptions = {
const forecastOptions = {
APIKey: '0657dc0d81c037cbc89ca88e383b6bbf',
units: 'uk2'
};
var file = __dirname + '/' + 'data.json';
const file = __dirname + '/' + 'data.json';
function saveData(d) {
jsonfile.writeFileSync(file, d);
}
@ -20,21 +23,18 @@ function saveData(d) {
module.exports = {
doGetWeatherOutlook: function () {
console.log('Retrieving weather..');
var j = {};
var forecast = new Forecast(forecastOptions);
forecast.get(55.8582846, -4.2593033, {units: 'uk2'}, function (err, res, data) {
logger.info('Retrieving weather..');
let j = {};
let forecast = new Forecast(forecastOptions);
forecast.get(55.8582846, -4.2593033, {units: 'uk2'}, (err, res, data) => {
if (err) throw err;
console.log(util.inspect(data));
logger.debug(util.inspect(data));
saveData(data);
j.currently = data.currently.summary;
j.today = data.daily.data[0].summary;
j.later = data.daily.summary;
j.alerts = data.alerts || {};
// todayCache.data.weather = j;
});
}
};

View File

@ -2,13 +2,33 @@
"name": "silvrtree",
"version": "0.1.1",
"devDependencies": {
"babel": "^6.23.0",
"babel-core": "^6.24.0",
"babel-eslint": "^7.2.0",
"babel-preset-es2015": "^6.24.0",
"cheerio": "^0.20.0",
"dateformat": "^1.0.12",
"ejs": "^2.3.4",
"fitbit-oauth2": "0.0.1",
"forecast.io": "0.0.9",
"gulp-autoprefixer": "^3.1.1",
"gulp-babel": "^6.1.2",
"gulp-cache": "^0.4.6",
"gulp-concat": "^2.6.1",
"gulp-cssnano": "^2.1.2",
"gulp-google-webfonts": "0.0.14",
"gulp-html-replace": "^1.6.2",
"gulp-htmlmin": "^3.0.0",
"gulp-jshint": "^2.0.4",
"gulp-rename": "^1.2.2",
"gulp-sass": "^3.1.0",
"gulp-scss": "^1.4.0",
"gulp-strip-debug": "^1.1.0",
"gulp-uglify": "^2.1.2",
"htmlparser": "^1.7.7",
"jade": "^1.11.0",
"jest": "^19.0.2",
"jshint": "^2.9.4",
"jsonfile": "^2.3.0",
"lodash": "^4.11.2",
"log4js": "^0.6.35",
@ -31,12 +51,14 @@
"express": "^4.13.4",
"express-session": "^1.13.0",
"ftse": "^1.0.6",
"gulp": "^3.9.1",
"ical2json": "^0.2.0",
"logger": "0.0.1",
"method-override": "^2.3.5",
"morgan": "^1.7.0",
"nano": "^6.2.0",
"node-cron": "^1.0.0",
"pug": "^2.0.0-beta11",
"scrape": "^0.2.3",
"string": "^3.3.1",
"sugar-date": "^1.5.1",
@ -47,5 +69,8 @@
"scripts": {
"start": "node web-server.js",
"copy": "sudo cp -r ./. /var/www/silvrtree"
},
"jest": {
"verbose": true
}
}

201
serverV2.js Normal file
View File

@ -0,0 +1,201 @@
const express = require('express');
const path = require('path');
const server = require('http').createServer();
const fx = require('./lib/fx');
const btc = require('./lib/btc');
const train = require('./lib/train');
const password = require('./lib/password');
const clean = require('./lib/clean');
const events = require('./lib/events');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const methodoverride = require('method-override');
const bodyparser = require('body-parser');
const errorhandler = require('errorhandler');
const jsonfile = require('jsonfile');
const Events = require('events');
let busEmitter = new Events.EventEmitter();
const WebSocketServer = require('ws').Server;
const wss = new WebSocketServer({server: server});
const SocketHandler = require('./lib/wshandlerv2');
let webSocket = new SocketHandler(busEmitter, wss);
// train = require('lib/train')
/* ,submit = require('./routes/mongo/submit') */
;
let fs = require('fs');
const config = require('./config/config.json');
const Fitbit = require('fitbit-oauth2');
const polys = require('./lib/poly.js');
const logger = require('log4js').getLogger();
const app = express();
GLOBAL.lastcheck = 0;
let btcCache = {}, fxCache = {}, trainCache = {};
const port = process.env.PORT || 9010;
// app.configure(function () {
app.set('port', port);
app.set('view engine', 'ejs');
app.use(morgan('dev'));
app.use(cookieParser('your secret here'));
app.use(session({
secret: 'd2jRT6ZpYFsXsF3kGS21ZszKbPAaEa', resave: false,
saveUninitialized: false
}));
/* 'default', 'short', 'tiny', 'dev' */
app.use(methodoverride());
app.use(bodyparser.urlencoded({extended: false}));
// parse application/json
app.use(bodyparser.json());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
next();
});
// app.use(app.router);
app.use(express.static(path.join(__dirname, 'app')));
app.use(errorhandler({dumpExceptions: true, showStack: true}));
app.use('/btc', btc.doBTC);
app.use('/fx', fx.doFx);
app.use('/dbeglq', train.dbe_glq);
app.use('/glqdbe', train.glq_dbe);
app.use('/gettrains', train.getTrainTimes);
app.use('/getnexttraintimes', train.getNextTrainTimes);
app.use('/getroute', train.getRoute);
app.use('/generate', password.generate);
app.use('/cleanit', clean.cleanit);
app.use('/events', events.getEvents);
app.get('/cinema/:id', events.getCinema);
app.route('/poly').get(polys);
/*app.use('/lot', function(req, res) {
const pg = require('pg');
const conString = 'postgres://pguser:1V3D4m526i@localhost/silver';
console.log(conString);
const client = new pg.Client(conString);
const q = 'select * from lot order by d desc';
client.connect(function(err) {
if (err) {
return console.error('could not connect to postgres', err);
}
client.query(q, function(err, result) {
if (err) {
return console.error('error running query', err);
}
console.log(result.rows[0].theTime);
// output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
client.end();
});
});
});*/
app.get('/slack', function(req, res) {
res.render('pages/slackV2');
});
app.get('/temp', function(req, res) {
res.render('pages/temp');
});
const tfile = 'fb-token.json';
// Instanciate a fitbit client. See example config below.
//
const fitbit = new Fitbit(config.fitbit);
// In a browser, http://localhost:4000/fitbit to authorize a user for the first time.
//
app.get('/fitbit', function(req, res) {
res.redirect(fitbit.authorizeURL());
});
// Callback service parsing the authorization token and asking for the access token. This
// endpoint is refered to in config.fitbit.authorization_uri.redirect_uri. See example
// config below.
//
app.get('/fitbit_auth_callback', function(req, res, next) {
const code = req.query.code;
fitbit.fetchToken(code, function(err, token) {
if (err) {
return next(err);
}
// persist the token
jsonfile.writeFile(tfile, token, function(err) {
if (err) {
return next(err);
}
console.log('!!!! Fitbit token saved');
res.redirect('/fb-profile');
});
});
});
jsonfile.readFile('./fb-token.json', function(err, obj) {
if (err) {
logger.error(err);
} else {
fitbit.setToken(obj);
}
});
// });
/**
* create the server
*/
/*
http.createServer(app).listen(app.get('port'), function () {
logger.warn("Express server listening on port " + app.get('port'));
//console.log("Express server listening on port " + app.get('port'));
});
*/
server.on('request', app);
server.listen(port, () => { logger.info('New server listening on ' + server.address().port); });

380
views/pages/slackV2.ejs Normal file
View File

@ -0,0 +1,380 @@
<% include ../partials/head %>
<!-- Slack - I have plenty of talent and vision I just don't give a damn -->
<header id="header">
<div class="mui-appbar mui--appbar-line-height">
<div class="mui-container-fluid">
Slack
</div>
</div>
</header>
<div class="mui-container">
<div class="mui--appbar-height">
</div>
<div id="container" class="mui-panel">
<div class="mui-row">
<div class="mui-col-md-3" id="one"></div>
<div class="mui-col-md-3 " id="two"></div>
<div class="mui-col-md-3 " id="three"></div>
</div>
</div>
<div class="mui-panel">
<div class="mui-row">
<div class="mui-col-md-4">
<div class="mui--text-title mui-text-black">Starting Points/Metasites</div>
<ul>
<li><a href="https://www.silvrtree.co.uk/today">Today</a></li>
<li><a href="https://www.silvrtree.co.uk/events">Events</a></li>
<li><a href="https://www.silvrtree.co.uk/cinema/0">Cinema</a></li>
<li><a href="https://feedly.com/#my">Feedly</a></li>
<li><a href="https://www.reddit.com">Reddit</a></li>
<li><a href="http://www.facebook.com/">Facebook</a></li>
<li><a href="http://www.yahoo.com/">Yahoo!</a></li>
<li><a href="https://stackedit.io/editor">Journal Editor</a></li>
<li><a href="http://www.unmajestic.com/home/bookmarks.php">Slack Bookmarks</a></li>
<li><a href="http://www.rssmix.com/u/7711845">Paleo Mix</a></li>
<li><a href="http://status.hivehome.com/">Hive Status</a></li>
</ul>
</div>
<div class="mui-col-md-4">
<div class="mui--text-title mui-text-black">Tools</div>
<ul>
<li><a href='https://kanbanflow.com'>Kanban Flow</a></li>
<li><a href="https://www.linode.com/">Linode</a></li>
<li><a href="http://www.colorzilla.com/gradient-editor/">CSS Gradient Generator</a></li>
<li><a href="http://utilities-online.info/xmltojson">XML to JSON</a></li>
<li><a href="http://shancarter.com/data_converter">CSV to JSON</a></li>
<li><a href="http://cubic-bezier.com/">Cubic Bezier</a></li>
<li><a href="http://gskinner.com/RegExr/">RegEx Tool</a></li>
<li><a href="http://closure-compiler.appspot.com/home">Closure Compiler</a></li>
<li><a href="http://jsonlint.com/">JSON Lint</a></li>
<li><a href="http://jsoneditoronline.org/">JSON Editor</a></li>
<li><a href="http://www.base64decode.org/">Base64 Decoder</a></li>
<li><a href="http://jsbeautifier.org/">JS Beautifier</a></li>
<li><a href="http://spritepad.wearekiss.com/">Spritepad</a></li>
<li><a href="http://draeton.github.com/stitches/">Sprite Sheet Generator</a></li>
<li><a href="http://www.cleancss.com/">CSS Optimizer</a></li>
<li><a href="http://fontello.com/">Icon Font Generator</a></li>
<li><a href="http://html2jade.aaron-powell.com/">HTML to Jade</a></li>
<li><a href="http://cdnjs.com//">Cloudflare JS CDN</a></li>
<li><a href="http://www.willpeavy.com/minifier/">HTML Minifier</a></li>
<li><a href='https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet'>XSS Cheat Sheet</a></li>
<li><a href='http://jsfiddle.net/'>JSFiddle</a></li>
<li><a href="http://jsbin.com/">JS Bin</a></li>
<li><a href='https://draftin.com/documents'>Draftin</a></li>
<li><a href="https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html">Android Asset</a></li>
<li><a href="https://xkpasswd.net/s/">Password Generator</a></li>
<li><a href="https://howsecureismypassword.net/">Password Checker</a></li>
<li><a href="https://archive.today">Archive Today</a></li>
<li><a href="http://staticmapmaker.com/google/">Static Map Generator</a></li>
<li><a href="https://httpbin.org/">AJAX Endpoints</a></li>
<li><a href="https://tools.bartlweb.net/webssh/">WebSSH</a></li>
<li><a href="http://jade-lang.com/demo/">Jade Tester</a></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>
<div class="mui-col-md-4">
<div class="mui--text-title mui-text-black">Bitcoin <span id="btc"></span></div>
<ul>
<li><a href="https://www.bitstamp.net">Bitstamp</a></li>
<li><a href="https://www.kraken.net">Kraken</a></li>
<li><a href="https://cryptowat.ch/">Cryptowat.ch</a></li>
<li><a href="http://www.coindesk.com/price/">BTC Chart</a></li>
<li><a href="https://bitcoinwisdom.com/">BTC Chart 2</a></li>
<li><a href="http://bitcoinity.org/markets/bitstamp/USD">BitStamp Chart</a></li>
<li><a href="http://btc-chart.com/market/bitstamp/86400">Bitstamp Chart 2</a></li>
<li><a href="https://bitbargain.co.uk">BitBargin UK</a></li>
<li><a href="https://yacuna.com/">Yacuna UK</a></li>
<li><a href="http://blockchain.info/">Blockchain</a></li>
<li><a href="http://bitminter.com/">Bitminter</a></li>
<li><a href="http://preev.com/">BTC Exchange Rate</a></li>
<li><a href="http://www.silvrtree.co.uk/watch.html">CFT Watcher</a>
<span style="cursor: pointer;"
onclick="popitoutSmall('http://www.silvrtree.co.uk/watch.html');"><img
src="gfx/popout.png"></span>
</li>
</ul>
</div>
</div>
<div class="mui-row">
<div class="mui-col-md-4">
<div class="mui--text-title mui-text-black">Package Tracking</div>
<!-- Computer News -->
<ul><li><a href="http://m.ups.com/">UPS</a></li></ul>
</div>
<div class="mui-col-md-4">
<div class="mui--text-title mui-text-black">Weather</div>
<ul>
<li>
<a href="http://www.accuweather.com/ukie/index-forecast.asp?postalcode=G82%201RG">Dumbarton
Weather</a>
</li>
<li>
<a href="http://www.wunderground.com/cgi-bin/findweather/getForecast?query=dumbarton,%20uk&wuSelect=WEATHER">WU
Dumbarton Weather</a>
</li>
<li>
<a href="http://weather.yahoo.com/forecast/UKXX0663.html?unit=c">Y! Dumbarton Weather</a>
</li>
<li>
<a href="http://www.accuweather.com/ukie/index-forecast.asp?postalcode=G9%202SU">Glasgow
Weather</a>
</li>
<li>
<a href="http://www.wunderground.com/cgi-bin/findweather/getForecast?query=glasgow,%20uk&wuSelect=WEATHER">WU
Glasgow Weather</a>
</li>
<li><a href="http://www.nowcast.co.uk/lightning/">Live Lightning</a>
</li>
<li>
<a href="http://www.upminsterweather.co.uk/test/live_lightning.htm">Other Live Lightning</a>
</li>
<li>
<a href="http://www.meteorologica.info/freedata_lightning.htm">Closer Live Lightning</a>
</li>
<li>
<a href="http://www.malvernwx.co.uk/lightning_data/lightning.htm">Multiple Lightning</a>
</li>
<li>
<a href="http://www.blitzortung.org/Webpages/index.php">European Lightning</a>
</li>
<li>
<a href="http://www.madpaddler.net/wxlightning.php">East Kilbride Lightning</a>
</li>
<li>
<a href="http://www.bordersweather.co.uk/wxlightning.php">Borders Lightning</a>
</li>
<li><a href='http://www.lightningmaps.org/blitzortung/europe/index.php?bo_page=map&lang=en'>Best Live Lightning</a></li>
<li><a href="http://www.madpaddler.net/wxais.php">Ships</a></li>
<li><a href='http://www.raintoday.co.uk/'>Rain Today</a></li>
</ul>
</div>
<div class="mui-col-md-4">
<div class="mui--text-title mui-text-black">Free Email WEBpages</div>
<!-- Free Email WEBpages -->
<ul>
<li><a href="http://gmail.google.com/">Gmail</a></li>
<li>
<a href="http://www.unmajestic.com/webmail/">Unmajestic Webmail</a>
</li>
<li>
<a href="http://www.artizanconsulting.co.uk/webmail/">Artizan Webmail</a>
</li>
<li><a href="http://mail.yahoo.com">Yahoo Mail</a></li>
<li>
<a href="https://www.guerrillamail.com/">Guerrilla Mail Anti Spam</a>
</li>
</ul>
</div>
</div>
<div class="mui-row">
<div class="mui-col-md-4">
<div class="mui--text-title mui-text-black">Contracting</div>
<ul>
<li><a href='https://outsauce.backofficeportal.com/Secure/Candidate/Default.aspx'>Outsauce Timesheets</a></li>
<li><a href='https://worksheets.computerfutures.com/'>CF Timesheets</a></li>
<li><a href="http://www.monster.co.uk/">monster</a></li>
<li><a href="http://www.cwjobs.co.uk/">cwjobs</a></li>
<li><a href="http://www.s1jobs.com/myaccount/">s1jobs</a></li>
<li><a href="http://www.jobserve.com/">jobserve</a></li>
<li><a href="http://www.jobsite.co.uk/jbe/myprofile/">jobsite</a>
</li>
<li>
<a href="http://www.itjobswatch.co.uk/contracts/scotland/asp.do">IT Jobs Watch Scotland</a>
</li>
</ul>
</div>
<div class="mui-col-md-4">
<div class="mui--text-title mui-text-black">Entertainment</div>
<!-- Entertainment -->
<ul>
<li>
<a href="http://genre.amazingradio.co.uk:8000/stream.mp3?arplayer=1">Amazing Radio Chill</a>
</li>
<li>
<a href="http://www.cineworld.co.uk/cinemas/28?fallback=false&isMobileAgent=false">Cineworld</a>
</li>
<li>
<a href="http://www.showcasecinemas.co.uk/showtimes/default.asp?selectTheatre=8508">Showcase</a>
</li>
<li><a href="http://www.imdb.com/">Imdb</a></li>
<li><a href="http://www.epguides.com/">EPGuides</a></li>
<li><a href="http://eztv.it">Eztv</a></li>
<li><a href="http://www.mininova.org">Mininova</a></li>
<li><a href="http://www.scrapetorrent.com">Scrapetorrent</a></li>
<li>
<a href="http://glasgow.myvillage.com/events">Whats on In Glasgow</a>
</li>
<li><a href="http://www.5pm.co.uk/Search/Event/">Local Events</a>
</li>
<li><a href="http://necta.jansenit.com:8000/necta192.mp3">Nectarine</a>
</li>
<li><a href="/playlists/str.pls">STR - Space Travel Radio</a>
</li>
<li><a href="/playlists/musik.drumstep.pls">musik.drumstep</a>
</li>
</ul>
</div>
<div class="mui-col-md-4">
<div class="mui--text-title mui-text-black">Travel <span id="fx"></div>
<!-- Travel -->
<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>
<a href='http://www.journeycheck.com/firstscotrail'>Journey Check</a>
<a href="http://www.bbc.co.uk/travel/2650802/incidents/road">BBC Road
news</a>
</li>
<li>
<a href="http://ojp.nationalrail.co.uk/service/ldbboard/dep/DBE/WES/To?ar=true">DBE->WES</a>
/
<a href="http://www.traintime.uk/index.php?view=desktop&from=DBE&to=WES">Advanced</a>
</li>
<li>
<a href="http://ojp.nationalrail.co.uk/service/ldbboard/dep/WES/DBE/To?ar=true">WES->DBE</a>
<span style="cursor: pointer;"
onclick="popitout('http://ojp.nationalrail.co.uk/service/ldbboard/dep/WES/DBE/To?ar=true#skip-content-hold');"><img
src="gfx/popout.png"></span>
/
<a href="http://www.traintime.uk/index.php?view=desktop&from=WES&to=DBE">Advanced</a>
</li>
<li>
<a href="http://www.livedepartureboards.co.uk/ldb/summary.aspx?T=DBE">DBE Board</a>
/
<a href="http://www.stationboard.uk/index.php?view=desktop&station1=DBE&direction=departures">Advanced</a>
</li>
<li>
<a href="http://www.livedepartureboards.co.uk/ldb/summary.aspx?T=GLQ">GLQ Trains</a> /
<a href="http://www.stationboard.uk/index.php?view=desktop&station1=GLQ&direction=departures">Adv</a> /
<a href="http://www.traintime.uk/index.php?view=desktop&from=GLQ&to=DBE">GLQ->DBE</a>
</li>
<li><a href="http://www.kayak.co.uk/">Kayak</a></li>
<li><a href="http://www.travelocity.co.uk/">Travelocity</a></li>
<li><a href="http://www.travel.com/sitemap.htm">Travel.com</a></li>
<li>
<a href="http://www.landings.com/_landings/pages/commercial.html">Airlines</a>
</li>
<li><a href="http://www.flightstats.com">Landings</a></li>
<li>
<a href="http://www.lib.utexas.edu/Libs/PCL/Map_collection/map_sites/map_sites.html#general">Maps</a>
</li>
<li><a href="http://www.sitesatlas.com/Maps/">Maps2</a></li>
<li><a href="http://www.itn.net/">ITN</a></li>
<li><a href="http://bahn.hafas.de/bin/query.exe/en">HAFAS</a></li>
<li><a href="http://bahn.hafas.de/bin/query.exe/en">DieBahn</a></li>
<li><a href="http://www.cwrr.com/nmra/travelreg.html">RailUSA</a>
</li>
<li>
<a href="http://www.trainweb.com/frames_travel.html">TrainWeb</a>
</li>
<li><a href="http://www.cwrr.com/nmra/travelw2.html">RailWorld</a>
</li>
<li><a href="http://www.xe.net/currency/">Currency Converter</a>
</li>
<li>
<a href="http://www.cia.gov/cia/publications/factbook/index.html">CIA</a>
</li>
<li><a href="http://maps.google.com/">GMaps</a></li>
<li><a href='https://unop.uk/tube/'>Tube Status</a></li>
</ul>
</div>
</div>
<div class="mui-row">
<div class="mui-col-md-4">
<div class="mui--text-title mui-text-black">Computer Software, etc.</div>
<ul>
<li><a href="">Portable Apps</a></li>
<li><a href="http://www.newfreeware.com/">NewFreeware</a></li>
<li>
<a href="http://www.makeuseof.com/tag/portable-software-usb/">Portable Software</a>
</li>
<li>
<a href="http://www.portablefreeware.com/">Portable Freeware Collection</a>
</li>
</ul>
</div>
<div class="mui-col-md-4">
<div class="mui--text-title mui-text-black">Reference &amp; Special sites</div>
<!-- Reference and Special sites -->
<ul>
<li><a href="http://www.glossarist.com/default.asp">Glossaries</a>
</li>
<li><a href="http://www.convert-me.com/en/">Converters</a></li>
<li>
<a href="http://decoder.americom.com/cgi-bin/decoder.cgi">DECODE</a>
</li>
<li><a href="http://www.rxlist.com/">Drugs</a></li>
<li><a href="http://www.ncbi.nlm.nih.gov/PubMed/">Medline</a></li>
<li>
<a href="http://www.logos.it/dictionary/owa/sp?lg=EN">Translation</a>
</li>
<li><a href="http://www.onelook.com/">One Look</a></li>
<li><a href="http://www.defenselink.mil/">US Military</a></li>
<li><a href="http://www.fedworld.gov/">US Fed</a></li>
<li><a href="http://www.ih2000.net/ira/legal.htm">Legal</a></li>
<li><a href="http://www.nih.gov/">NIH</a></li>
<li><a href="http://www.refdesk.com/">RefDESK</a></li>
<li><a href="http://www.britannica.com/">Britannica</a></li>
<li><a href="http://www.capitolimpact.com/gw/">States</a></li>
<li><a href="http://www.packtrack.com/">PackTrack</a></li>
<li><a href="http://www.acronymfinder.com/">Acronym</a></li>
<li><a href="http://www.visualthesaurus.com/">V-Thes</a></li>
<li>
<a href="http://www.timelineindex.com/content/home/forced">Timelines</a>
</li>
<li><a href="http://en.wikipedia.org/wiki/Main_Page">Wikipedia</a>
</li>
</ul>
</div>
<div class="mui-col-md-4">
<div class="mui--text-title mui-text-black">Earth and Beyond</div>
<!-- Good Reading Misc. -->
<ul>
<li><a href="http://enbarsenal.com">ENB Arsenal</a></li>
<li><a href="http://enb.wikia.com/">ENB Wikia</a></li>
<li><a href="http://enb.gearlist.co.uk/">Gear List</a></li>
<li><a href='http://forum.enb-emulator.com/'>Emu Forum</a></li>
<li><a href="http://net-7.org/wiki/index.php?title=Main_Page">Net 7 Wiki</a></li>
<li><a href="http://spaceengineers.wikia.com/wiki/Space_Engineers_Wiki">Space Engineers Wiki</a></li>
<li><a href="http://forums.keenswh.com/">Space Engineers Forum</a></li>
</ul>
</div>
</div>
</div>
<div id='weather' class="mui-panel"></div>
</div>
</body>
<script src="libs/ejs.js"></script>
<script src="libs/underscore.js"></script>
<script src="libs/backbone.js"></script>
<script src="js/modules/bitcoin.js"></script>
<script src="app.js"></script>
<script>
this.bitcoin = new Bitcoin({model: new BitcoinModel()});
</script>
</html>

View File

@ -7,12 +7,13 @@
<meta charset="UTF-8">
<title>Events</title>
<meta name="Author" content="" />
<meta name="Author" content=""/>
<link rel="stylesheet" href="fonts/fonts.css">
<link href="css/custom.css" rel="stylesheet" type="text/css" />
<link href="css/custom.css" rel="stylesheet" type="text/css"/>
<script src="libs/zepto.min.js"></script>
<script src="libs/microevent.js"></script></head>
<script src="libs/microevent.js"></script>
</head>
<body>

View File

@ -1,186 +1,192 @@
var express = require('express'), path = require('path'), server = require('http').createServer();
const express = require('express');
const path = require('path');
const server = require('http').createServer();
var fx = require('./lib/fx'), btc = require('./lib/btc'), train = require('./lib/train'),
password = require('./lib/password') , clean = require('./lib/clean'), events = require('./lib/events'),
today = require('./lib/today'),
morgan = require('morgan'), cookieParser = require('cookie-parser'),session = require('express-session')
methodoverride = require('method-override'), bodyparser = require('body-parser'), errorhandler = require('errorhandler');
const fx = require('./lib/fx');
const btc = require('./lib/btc');
const train = require('./lib/train');
const password = require('./lib/password');
const clean = require('./lib/clean');
const events = require('./lib/events');
const today = require('./lib/today');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const session = require('express-session');
var jsonfile = require('jsonfile');
const methodoverride = require('method-override');
const bodyparser = require('body-parser');
const errorhandler = require('errorhandler');
var Events = require('events');
var busEmitter = new Events.EventEmitter();
const jsonfile = require('jsonfile');
const Events = require('events');
let busEmitter = new Events.EventEmitter();
busEmitter.on('update', today.broadcast);
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ server: server });
const WebSocketServer = require('ws').Server;
const wss = new WebSocketServer({server: server});
var SocketHandler = require('./lib/wshandlerv2');
var webSocket = new SocketHandler(busEmitter, wss);
const SocketHandler = require('./lib/wshandlerv2');
let webSocket = new SocketHandler(busEmitter, wss);
today.setEmitter(busEmitter);
//train = require('lib/train')
// train = require('lib/train')
/* ,submit = require('./routes/mongo/submit') */
;
;
var fs = require('fs');
var config = require('./config/config.json');
var Fitbit = require('fitbit-oauth2');
let fs = require('fs');
const config = require('./config/config.json');
const Fitbit = require('fitbit-oauth2');
var polys = require('./lib/poly.js');
const polys = require('./lib/poly.js');
var logger = require('log4js').getLogger();
var app = express();
const logger = require('log4js').getLogger();
const app = express();
GLOBAL.lastcheck = 0;
var btcCache = {}, fxCache = {} , trainCache = {};
let btcCache = {}, fxCache = {}, trainCache = {};
var port = process.env.PORT || 9000;
const port = process.env.PORT || 9000;
//app.configure(function () {
app.set('port', port);
app.set('view engine', 'ejs');
app.use(morgan('dev'));
app.use(cookieParser('your secret here'));
// app.configure(function () {
app.set('port', port);
app.set('view engine', 'ejs');
app.use(morgan('dev'));
app.use(cookieParser('your secret here'));
app.use(session({
secret: '1234567890QWERTY', resave: false,
saveUninitialized: false
secret: 'd2jRT6ZpYFsXsF3kGS21ZszKbPAaEa', resave: false,
saveUninitialized: false
}));
/* 'default', 'short', 'tiny', 'dev' */
app.use(methodoverride());
app.use(methodoverride());
app.use(bodyparser.urlencoded({extended: false}));
// parse application/json
app.use(bodyparser.json());
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
next();
});
// app.use(app.router);
app.use(express.static(path.join(__dirname, 'app')));
app.use(express.static(path.join(__dirname, 'app')));
app.use(errorhandler({dumpExceptions: true, showStack: true}));
app.use('/btc', btc.doBTC);
app.use('/fx', fx.doFx);
app.use('/fx', fx.doFx);
app.use('/dbeglq', train.dbe_glq);
app.use('/glqdbe', train.glq_dbe);
app.use('/gettrains', train.getTrainTimes);
app.use('/getnexttraintimes', train.getNextTrainTimes);
app.use('/getroute', train.getRoute);
app.use('/dbeglq', train.dbe_glq);
app.use('/glqdbe', train.glq_dbe);
app.use('/gettrains', train.getTrainTimes);
app.use('/getnexttraintimes', train.getNextTrainTimes);
app.use('/getroute', train.getRoute);
app.use('/generate', password.generate);
app.use('/generate', password.generate);
app.use('/cleanit', clean.cleanit);
app.use('/cleanit', clean.cleanit);
app.use('/events', events.getEvents);
app.get('/cinema/:id', events.getCinema);
app.use('/events', events.getEvents);
app.get('/cinema/:id', events.getCinema);
app.get('/today', today.getToday);
app.get('/today/data', today.getData);
app.get('/today', today.getToday);
app.get('/today/data', today.getData);
app.route('/clock')
.get(today.getClock);
app.route('/clock').get(today.getClock);
app.route('/poly').get(polys);
app.use('/lot', function (req, res) {
var pg = require('pg');
/*app.use('/lot', function(req, res) {
const pg = require('pg');
var conString = "postgres://pguser:1V3D4m526i@localhost/silver";
console.log(conString);
const conString = 'postgres://pguser:1V3D4m526i@localhost/silver';
console.log(conString);
var client = new pg.Client(conString);
var q = 'select * from lot order by d desc';
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query(q, function(err, result) {
if(err) {
return console.error('error running query', err);
}
console.log(result.rows[0].theTime);
//output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
client.end();
});
});
const client = new pg.Client(conString);
const q = 'select * from lot order by d desc';
client.connect(function(err) {
if (err) {
return console.error('could not connect to postgres', err);
}
client.query(q, function(err, result) {
if (err) {
return console.error('error running query', err);
}
console.log(result.rows[0].theTime);
// output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
client.end();
});
});
});*/
app.get('/slack', function (req, res) {
res.render('pages/slack');
});
app.get('/slack', function(req, res) {
res.render('pages/slack');
});
app.get('/temp', function (req, res) {
res.render('pages/temp');
});
app.get('/temp', function(req, res) {
res.render('pages/temp');
});
var tfile = 'fb-token.json';
const tfile = 'fb-token.json';
// Instanciate a fitbit client. See example config below.
//
var fitbit = new Fitbit( config.fitbit);
const fitbit = new Fitbit(config.fitbit);
// In a browser, http://localhost:4000/fitbit to authorize a user for the first time.
//
app.get('/fitbit', function (req, res) {
res.redirect( fitbit.authorizeURL() );
app.get('/fitbit', function(req, res) {
res.redirect(fitbit.authorizeURL());
});
// Callback service parsing the authorization token and asking for the access token. This
// endpoint is refered to in config.fitbit.authorization_uri.redirect_uri. See example
// config below.
//
app.get('/fitbit_auth_callback', function (req, res, next) {
var code = req.query.code;
fitbit.fetchToken( code, function( err, token ) {
if ( err ) {
return next( err );
}
app.get('/fitbit_auth_callback', function(req, res, next) {
const code = req.query.code;
fitbit.fetchToken(code, function(err, token) {
if (err) {
return next(err);
}
// persist the token
jsonfile.writeFile( tfile, token, function( err ) {
if ( err ) {
return next( err );
}
console.log("!!!! Fitbit token saved");
res.redirect( '/fb-profile' );
jsonfile.writeFile(tfile, token, function(err) {
if (err) {
return next(err);
}
console.log('!!!! Fitbit token saved');
res.redirect('/fb-profile');
});
});
});
});
jsonfile.readFile('./fb-token.json', function(err, obj) {
if (err) {
logger.error(err);
}
else {
fitbit.setToken(obj);
}
});
if (err) {
logger.error(err);
} else {
fitbit.setToken(obj);
}
});
//});
// });
/**
* create the server
@ -195,5 +201,5 @@ http.createServer(app).listen(app.get('port'), function () {
server.on('request', app);
server.listen(port, function() { logger.info('New server listening on ' + server.address().port); });
server.listen(port, () => { logger.info('New server listening on ' + server.address().port); });