Updating server modules

This commit is contained in:
Martin Donnelly 2017-08-18 15:08:28 +01:00
parent 36b32b5c1d
commit f20f9bc8fc
7 changed files with 388 additions and 340 deletions

View File

@ -1,24 +1,45 @@
{ {
"plugins": [ "parserOptions": {
"react" "ecmaVersion": 6,
], "sourceType": "module",
"parserOptions": { "ecmaFeatures": {
"ecmaVersion": 6, "jsx": false
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"env": {
"es6": true,
"browser": true,
"node": true,
"mocha": true
},
"extends": [
"eslint:recommended",
"plugin:react/recommended"
],
"rules": {
} }
},
"env": {
"browser": true,
"node": true,
"es6": true
},
"rules": {
"no-new-object": 1,
"no-reserved-keys": 1,
"no-array-constructor": 1,
"quotes": [1, "single"],
"max-len": [1, 120, 2], // 2 spaces per tab, max 80 chars per line
"no-inner-declarations": [1, "both"],
"no-shadow-restricted-names": 1,
"one-var": 0,
"vars-on-top": 1,
"eqeqeq": 1,
"curly": [1, "multi"],
"no-mixed-spaces-and-tabs": 1,
"space-before-blocks": [1, "always"],
"space-infix-ops": 1,
"eol-last": 1,
"comma-style": [1, "last"],
"no-comma-dangle": 1,
"semi": [1, "always"],
"radix": 1,
"camelcase": 1,
"new-cap": 1,
"consistent-this": [1, "_this"],
"func-names": 1,
"no-multi-spaces": 2,
"brace-style": [2,"1tbs",{}],
"indent": [2,2],
"comma-spacing": ["error", { "before": false, "after": true }]
}
} }

View File

@ -1,128 +1,141 @@
let http = require('http'); const http = require('http');
let https = require('https'); const https = require('https');
const LimitedArray = require('limitedarray');
const trend = require('trend');
const logger = require('log4js').getLogger('btc');
let btcCache = {}; let btcCache = {};
let balanceCache = {}; let balanceCache = {};
exports.doBTC = function (req, res) { let history = new LimitedArray(288); // one days worth in 5 minute chunks
console.log('Bitcoin request');
function btcQuery (callback, r) { function getBitcoin () {
var req = r; logger.info('>> getting bitcoin');
var options = { function btcQuery (callback) {
const options = {
host: 'api.coindesk.com', host: 'api.coindesk.com',
// port: 80, // port: 80,
path: '/v1/bpi/currentprice.json', path: '/v1/bpi/currentprice.json',
// method: 'GET', // method: 'GET',
headers: { headers: {
/* 'Content-Type': 'application/json', /* 'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)*/ 'Content-Length': Buffer.byteLength(data)*/
} }
}; };
try { try {
http.request(options).on('response', function (response) { http.request(options).on('response', response => {
var data = ''; let data = '';
response.on('data', function (chunk) { response.on('data', chunk => {
data += chunk; data += chunk;
}); });
response.on('end', function () { response.on('end', () => {
console.log('>> data', data);
let cData = {}; let cData = {};
try { try {
cData = JSON.parse(data); cData = JSON.parse(data);
} } catch (e) {
catch (e) { logger.error(e);
console.error(e); } finally{
callback(cData);
} }
finally{
});
response.on('error', e => {
logger.error(e);
});
}).end();
} catch (e) {
logger.error(e);
}
}
btcQuery(a => {
// logger.info(a);
logger.info('Got btc data. Storing it');
btcCache = a;
history.push(a.bpi.USD.rate_float);
btcCache.history = history.get();
btcCache.trend = trend(btcCache.history, {avgPoints: 12});
GLOBAL.lastcheck = new Date();
});
}
function getBalance() {
logger.info('>> getting Balance');
function balanceQuery (callback, r) {
try {
https.get('https://blockexplorer.com/api/addr/18sLVW5Aswp2KWLr4hMFZsuSPtvAauFiif').on('response', response => {
let data = '';
response.on('data', chunk => {
data += chunk;
});
response.on('end', () => {
let cData = {};
try {
cData = JSON.parse(data);
} catch (e) {
logger.error(e);
} finally{
callback(cData, r); callback(cData, r);
} }
}); });
response.on('error', function (e) { response.on('error', e => {
console.error(e); logger.error(e);
}); });
}).end(); }).end();
} catch (e) { } catch (e) {
console.error(e); logger.error(e);
} }
} }
let now = new Date(); balanceQuery(a => {
if (now - GLOBAL.lastcheck > (59000 )) { logger.info('Got balance data. Storing it');
btcQuery(function (a) { balanceCache = a;
// console.log(a);
console.log('Got btc data.'); });
btcCache = a;
GLOBAL.lastcheck = now; }
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(btcCache));
}, res); exports.doBTC = (req, res) => {
} else { logger.info('Bitcoin request');
console.log('Using cache'); res.setHeader('Content-Type', 'application/json');
res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(btcCache));
res.end(JSON.stringify(btcCache));
}
}; };
exports.doBalance = function (req, res) { exports.doBalance = (req, res) => {
console.log('Bitcoin request'); logger.info('Balance request');
function balanceQuery (callback, r) { res.setHeader('Content-Type', 'application/json');
var req = r; res.end(JSON.stringify(balanceCache));
// https://blockexplorer.com/api/addr/18sLVW5Aswp2KWLr4hMFZsuSPtvAauFiif
var options = {
host: 'blockexplorer.com',
// port: 80,
path: '/api/addr/18sLVW5Aswp2KWLr4hMFZsuSPtvAauFiif',
// method: 'GET',
headers: {
/* 'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)*/
}
};
try {
https.get('https://blockexplorer.com/api/addr/18sLVW5Aswp2KWLr4hMFZsuSPtvAauFiif').on('response', function (response) {
var data = '';
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function () {
console.log('>> data', data);
let cData = {};
try {
cData = JSON.parse(data);
}
catch (e) {
console.error(e);
}
finally{
callback(cData, r);
}
});
response.on('error', function (e) {
console.error(e);
});
}).end();
} catch (e) {
console.error(e);
}
}
let now = new Date();
if (now - GLOBAL.lastcheck > (59000 )) {
balanceQuery(function (a) {
// console.log(a);
console.log('Got balance data.');
balanceCache = a;
GLOBAL.lastcheck = now;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(balanceCache));
}, res);
} else {
console.log('Using cache');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(balanceCache));
}
}; };
function updateBitcoin() {
logger.warn('updateBitcoin');
getBitcoin();
const now = new Date();
const mod = 300000 - (now.getTime() % 300000);
let btcupdateFn = () => {
updateBitcoin();
};
setTimeout(btcupdateFn.bind(this), mod + 10);
}
function updateBalance() {
logger.warn('updateBalance');
getBalance();
const now = new Date();
const mod = 3.6e+6 - (now.getTime() % 3.6e+6);
let balanceUpdateFn = () => {
updateBalance();
};
setTimeout(balanceUpdateFn.bind(this), mod + 10);
}
updateBitcoin();
updateBalance();

103
lib/fx.js
View File

@ -1,52 +1,65 @@
const http = require('http'); const http = require('http');
const LimitedArray = require('limitedarray');
const trend = require('trend');
const logger = require('log4js').getLogger('fx');
let fxCache = {}; let fxCache = {};
exports.doFx = function (req,res) { let history = new LimitedArray(96); // one days worth in 5 minute chunks
console.log('FX request');
function fxQuery(callback, r) {
let req = r;
let options = {
host: 'openexchangerates.org',
// port: 80,
path: '/api/latest.json?app_id=0eb932cee3bc40259f824d4b4c96c7d2',
// method: 'GET',
headers: {
/* 'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)*/
} function getFx() {
}; logger.info('FX request');
function fxQuery(callback) {
let options = {
host: 'openexchangerates.org',
// port: 80,
path: '/api/latest.json?app_id=0eb932cee3bc40259f824d4b4c96c7d2',
// method: 'GET',
headers: { }
};
http.request(options).on('response', function (response) { http.request(options).on('response', response => {
let data = ''; let data = '';
response.on("data", function (chunk) { response.on('data', chunk => {
data += chunk; data += chunk;
}); });
response.on('end', function () { response.on('end', () => {
console.log('Data done...'); logger.info('Data done...');
callback(JSON.parse(data), r); callback(JSON.parse(data));
}); });
response.on('error', function(e) { response.on('error', e => {
console.error(e); logger.error(e);
}); });
}).end(); }).end();
} }
let now = new Date(); fxQuery(a => {
if (now - GLOBAL.fxLastCheck > (60000 * 14)) { logger.info('Got FX data. Storing it');
fxQuery(function (a, b) { fxCache = a;
console.log(a);
fxCache = a; history.push(a.rates.GBP);
GLOBAL.fxLastCheck = now; fxCache.history = history.get();
res.setHeader('Content-Type', 'application/json'); fxCache.trend = trend(fxCache.history, {avgPoints: 24});
res.end(JSON.stringify(fxCache));
}, res); });
} }
else {
console.log("Using cache"); function updateFX() {
res.setHeader('Content-Type', 'application/json');
console.log('Cache length:', JSON.stringify(fxCache).length); logger.warn('updateBitcoin');
console.log(JSON.stringify(fxCache).substring(0,50)); getFx();
res.end(JSON.stringify(fxCache)); const now = new Date();
} const mod = (60000 * 15) - (now.getTime() % (60000 * 15));
let fxUpdateFn = () => {
updateFX();
};
setTimeout(fxUpdateFn.bind(this), mod + 10);
}
updateFX();
exports.doFx = (req, res) => {
logger.info('FX request');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(fxCache));
}; };

File diff suppressed because one or more lines are too long

View File

@ -1,185 +1,182 @@
// train.js // train.js
const http = require('http'); const http = require('http');
const logger = require('log4js').getLogger(); const logger = require('log4js').getLogger('train');
let trainCache = { let trainCache = {
last: {}, last: {},
data: {} data: {}
}; };
module.exports = { module.exports = {
dbe_glq: function (req, res) { dbe_glq: function (req, res) {
logger.info('DBE:GLQ request'); logger.info('DBE:GLQ request');
const now = new Date(); const now = new Date();
const nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60); const nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60);
if (trainCache.last.dbeglq === null || nowSeconds !== trainCache.last.dbeglq) { if (trainCache.last.dbeglq === null || nowSeconds !== trainCache.last.dbeglq)
Query(function (a, b) { Query(function (a, b) {
const ts = a.departures[0].service; const ts = a.departures[0].service;
let output = {}; let output = {};
logger.debug(ts); logger.debug(ts);
logger.debug(ts.sta); logger.debug(ts.sta);
output.sta = ts.sta; output.sta = ts.sta;
output.eta = ts.eta; output.eta = ts.eta;
trainCache.data.dbeglq = output; trainCache.data.dbeglq = output;
res.setHeader('Content-Type', 'application/json'); res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(trainCache.data.dbeglq)); res.end(JSON.stringify(trainCache.data.dbeglq));
}, res, 'huxley.apphb.com', '/next/dbe/to/glq/1?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8'); }, res, 'huxley.apphb.com', '/next/dbe/to/glq/1?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8');
}
}, },
glq_dbe: function (req, res) { glq_dbe: function (req, res) {
logger.info('GLQ:DBE request'); logger.info('GLQ:DBE request');
const now = new Date(); const now = new Date();
const nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60); const nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60);
if (trainCache.last.glqdbe === null || nowSeconds !== trainCache.last.dbeglq) { if (trainCache.last.glqdbe === null || nowSeconds !== trainCache.last.dbeglq)
Query(function (a, b) { Query(function (a, b) {
const ts = a.departures[0].service; const ts = a.departures[0].service;
const output = {}; const output = {};
logger.debug(ts); logger.debug(ts);
//GLOBAL.lastcheck = now; //GLOBAL.lastcheck = now;
logger.debug(ts.sta); logger.debug(ts.sta);
// logger.debug(toSeconds(ts.sta)); // logger.debug(toSeconds(ts.sta));
output.sta = ts.sta; output.sta = ts.sta;
output.eta = ts.eta; output.eta = ts.eta;
trainCache.data.glqdbe = output; trainCache.data.glqdbe = output;
// trainCache.last.glqdbe = toSeconds(ts.sta); // trainCache.last.glqdbe = toSeconds(ts.sta);
// console.log(ts); // console.log(ts);
res.setHeader('Content-Type', 'application/json'); res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(trainCache.data.glqdbe)); res.end(JSON.stringify(trainCache.data.glqdbe));
}, res, 'huxley.apphb.com', '/next/glq/to/dbe/1?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8'); }, res, 'huxley.apphb.com', '/next/glq/to/dbe/1?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8');
}
}, },
getTrainTimes: function (req, res) { getTrainTimes: function (req, res) {
// console.log(req); // console.log(req);
logger.info('getTrainTimes: ' + JSON.stringify(req.query)); logger.info('getTrainTimes: ' + JSON.stringify(req.query));
if (req.query.hasOwnProperty('from') && req.query.hasOwnProperty('from')) { if (req.query.hasOwnProperty('from') && req.query.hasOwnProperty('from')) {
const 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) { Query(function (a, b) {
res.setHeader('Content-Type', 'application/json'); res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(a)); res.end(JSON.stringify(a));
}, res, 'huxley.apphb.com', url); }, res, 'huxley.apphb.com', url);
} } else {
else { res.setHeader('Content-Type', 'application/json');
res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({}));
res.end(JSON.stringify({})); }
}
}, },
getNextTrainTimes: function (req, res) { getNextTrainTimes: function (req, res) {
logger.info('getNextTrainTimes: ' + JSON.stringify(req.query)); logger.info('getNextTrainTimes: ' + JSON.stringify(req.query));
let trainFrom, trainTo, trainToken, url; let trainFrom, trainTo, trainToken, url;
if (req.query.hasOwnProperty('from') && req.query.hasOwnProperty('from')) { if (req.query.hasOwnProperty('from') && req.query.hasOwnProperty('from')) {
trainFrom = req.query.from; trainFrom = req.query.from;
trainTo = req.query.to; trainTo = req.query.to;
trainToken = trainFrom + trainTo; trainToken = trainFrom + trainTo;
url = '/next/' + trainFrom + '/to/' + trainTo + '/1?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8'; url = '/next/' + trainFrom + '/to/' + trainTo + '/1?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8';
console.log('Requesting latest time for : ' + trainToken); logger.info('Requesting latest time for : ' + trainToken);
const now = new Date(); const now = new Date();
const nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60); const nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60);
console.log('Now Seconds: ' + nowSeconds); logger.info('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) { Query(function (a, b) {
const output = {}; const output = {};
logger.log('a', a); const ts = a.departures[0].service;
const ts = a.departures[0].service; if (ts !== null) {
if (ts !== null) {
// console.log(ts); // console.log(ts);
//GLOBAL.lastcheck = now; //GLOBAL.lastcheck = now;
logger.debug(ts.sta, ts.std); logger.debug(ts.sta, ts.std);
// logger.debug(toSeconds(ts.sta)); // logger.debug(toSeconds(ts.sta));
output.sta = (ts.sta !== null) ? ts.sta : ts.std; output.sta = (ts.sta !== null) ? ts.sta : ts.std;
output.eta = (ts.eta !== null ? ts.eta : ts.etd); output.eta = (ts.eta !== null ? ts.eta : ts.etd);
// trainCache.last.glqdbe = toSeconds(ts.sta); // trainCache.last.glqdbe = toSeconds(ts.sta);
// console.log(ts); // console.log(ts);
} else { } else {
logger.warn('*** NO SERVICE'); logger.warn('*** NO SERVICE');
output.sta = 'No Service'; output.sta = 'No Service';
output.eta = 'No Service'; output.eta = 'No Service';
} }
trainCache.data[trainToken] = output; trainCache.data[trainToken] = output;
res.setHeader('Content-Type', 'application/json'); res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(trainCache.data[trainToken])); res.end(JSON.stringify(trainCache.data[trainToken]));
}, res, 'huxley.apphb.com', url); }, res, 'huxley.apphb.com', url);
}
}
}, getRoute: function (req, res) {
logger.info('getRoute: ' + JSON.stringify(req.query));
let routeID;
let data = {};
if (req.query.hasOwnProperty('route')) {
routeID = req.query.route;
Query(function (a, b) {
if (a !== null && a.message === null) {
data = a;
}
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(data));
}, res, 'huxley.apphb.com', '/service/' + routeID + '?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8');
}
} }
}, getRoute: function (req, res) {
logger.info('getRoute: ' + JSON.stringify(req.query));
let routeID;
let data = {};
if (req.query.hasOwnProperty('route')) {
routeID = req.query.route;
Query(function (a, b) {
if (a !== null && a.message === null)
data = a;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(data));
}, res, 'huxley.apphb.com', '/service/' + routeID + '?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8');
}
}
}; };
function toSeconds(inval) { function toSeconds(inval) {
console.log('inval', typeof inval); console.log('inval', typeof inval);
if (typeof inval === 'string') { if (typeof inval === 'string') {
const a = inval.split(':'); const a = inval.split(':');
return ((parseInt(a[0]) * (60 * 60)) + (parseInt(a[1]) * 60)); return ((parseInt(a[0]) * (60 * 60)) + (parseInt(a[1]) * 60));
} }
return ''; return '';
} }
function Query(callback, r, host, path) { function Query(callback, r, host, path) {
logger.debug(path); logger.debug(path);
const req = r; const req = r;
const options = { const options = {
host: host, host: host,
// port: 80, // port: 80,
path: path, path: path,
//method: 'GET', //method: 'GET',
headers: {} headers: {}
}; };
try { try {
http.request(options).on('response', function (response) { http.request(options).on('response', function (response) {
let data = ''; let data = '';
response.on("data", function (chunk) { response.on('data', function (chunk) {
data += chunk; data += chunk;
}); });
response.on('end', function () { response.on('end', function () {
callback(JSON.parse(data), r); callback(JSON.parse(data), r);
}); });
response.on('error', function (e) { response.on('error', function (e) {
console.error(e); console.error(e);
}); });
}).end(); }).end();
} catch (e) { } catch (e) {
console.log(e); console.log(e);
} }
} }

View File

@ -65,6 +65,7 @@
"ftse": "^1.0.6", "ftse": "^1.0.6",
"gulp": "^3.9.1", "gulp": "^3.9.1",
"ical2json": "^0.2.0", "ical2json": "^0.2.0",
"limitedarray": "git+https://gitlab.silvrtree.co.uk/martind2000/limitedArray.git",
"logger": "0.0.1", "logger": "0.0.1",
"method-override": "^2.3.5", "method-override": "^2.3.5",
"morgan": "^1.7.0", "morgan": "^1.7.0",
@ -74,6 +75,7 @@
"scrape": "^0.2.3", "scrape": "^0.2.3",
"string": "^3.3.1", "string": "^3.3.1",
"sugar-date": "^1.5.1", "sugar-date": "^1.5.1",
"trend": "^0.3.0",
"ultrases": "^0.1.3", "ultrases": "^0.1.3",
"unstyler": "^0.2.2", "unstyler": "^0.2.2",
"ws": "^1.1.1" "ws": "^1.1.1"

View File

@ -8,7 +8,7 @@ const train = require('./lib/train');
const password = require('./lib/password'); const password = require('./lib/password');
const clean = require('./lib/clean'); const clean = require('./lib/clean');
const events = require('./lib/events'); const events = require('./lib/events');
const today = require('./lib/today'); // const today = require('./lib/today');
const morgan = require('morgan'); const morgan = require('morgan');
const cookieParser = require('cookie-parser'); const cookieParser = require('cookie-parser');
const session = require('express-session'); const session = require('express-session');
@ -22,7 +22,7 @@ const jsonfile = require('jsonfile');
const Events = require('events'); const Events = require('events');
let busEmitter = new Events.EventEmitter(); let busEmitter = new Events.EventEmitter();
busEmitter.on('update', today.broadcast); //busEmitter.on('update', today.broadcast);
const WebSocketServer = require('ws').Server; const WebSocketServer = require('ws').Server;
const wss = new WebSocketServer({server: server}); const wss = new WebSocketServer({server: server});
@ -31,7 +31,7 @@ const SocketHandler = require('./lib/wshandlerv2');
let webSocket = new SocketHandler(busEmitter, wss); let webSocket = new SocketHandler(busEmitter, wss);
today.setEmitter(busEmitter); //today.setEmitter(busEmitter);
// train = require('lib/train') // train = require('lib/train')
/* ,submit = require('./routes/mongo/submit') */ /* ,submit = require('./routes/mongo/submit') */
@ -43,7 +43,7 @@ const Fitbit = require('fitbit-oauth2');
const polys = require('./lib/poly.js'); const polys = require('./lib/poly.js');
const logger = require('log4js').getLogger(); const logger = require('log4js').getLogger('web-server');
const app = express(); const app = express();
GLOBAL.lastcheck = 0; GLOBAL.lastcheck = 0;
GLOBAL.fxLastCheck = 0; GLOBAL.fxLastCheck = 0;
@ -99,10 +99,10 @@ app.use('/cleanit', clean.cleanit);
app.use('/events', events.getEvents); app.use('/events', events.getEvents);
app.get('/cinema/:id', events.getCinema); app.get('/cinema/:id', events.getCinema);
app.get('/today', today.getToday); // app.get('/today', today.getToday);
app.get('/today/data', today.getData); // app.get('/today/data', today.getData);
app.route('/clock').get(today.getClock); //app.route('/clock').get(today.getClock);
app.route('/poly').get(polys); app.route('/poly').get(polys);
@ -159,42 +159,42 @@ app.get('/fitbit', function(req, res) {
app.get( '/fb-profile', function( req, res, next ) { app.get( '/fb-profile', function( req, res, next ) {
fitbit.request({ fitbit.request({
uri: "https://api.fitbit.com/1/user/-/profile.json", uri: 'https://api.fitbit.com/1/user/-/profile.json',
method: 'GET', method: 'GET',
}, function( err, body, token ) { }, function( err, body, token ) {
if ( err ) return next( err ); if ( err ) return next( err );
var profile = JSON.parse( body ); var profile = JSON.parse( body );
// if token is not null, a refesh has happened and we need to persist the new token // if token is not null, a refesh has happened and we need to persist the new token
if ( token ) if ( token )
persist.write( tfile, token, function( err ) { persist.write( tfile, token, function( err ) {
if ( err ) return next( err ); if ( err ) return next( err );
res.send( '<pre>' + JSON.stringify( profile, null, 2 ) + '</pre>' ); res.send( '<pre>' + JSON.stringify( profile, null, 2 ) + '</pre>' );
}); });
else else
res.send( '<pre>' + JSON.stringify( profile, null, 2 ) + '</pre>' ); res.send( '<pre>' + JSON.stringify( profile, null, 2 ) + '</pre>' );
}); });
}); });
app.get( '/fb-today', function( req, res, next ) { app.get( '/fb-today', function( req, res, next ) {
const today = Date.create('today').format('{yyyy}-{MM}-{dd}'); const today = Date.create('today').format('{yyyy}-{MM}-{dd}');
const url = 'https://api.fitbit.com/1/user/-/activities/date/' + today + '.json'; const url = 'https://api.fitbit.com/1/user/-/activities/date/' + today + '.json';
fitbit.request({ fitbit.request({
uri: url, uri: url,
method: 'GET', method: 'GET',
}, function( err, body, token ) { }, function( err, body, token ) {
if ( err ) return next( err ); if ( err ) return next( err );
var profile = JSON.parse( body ); var profile = JSON.parse( body );
// if token is not null, a refesh has happened and we need to persist the new token // if token is not null, a refesh has happened and we need to persist the new token
if ( token ) if ( token )
persist.write( tfile, token, function( err ) { persist.write( tfile, token, function( err ) {
if ( err ) return next( err ); if ( err ) return next( err );
res.send( '<pre>' + JSON.stringify( profile, null, 2 ) + '</pre>' ); res.send( '<pre>' + JSON.stringify( profile, null, 2 ) + '</pre>' );
}); });
else else
res.send( '<pre>' + JSON.stringify( profile, null, 2 ) + '</pre>' ); res.send( '<pre>' + JSON.stringify( profile, null, 2 ) + '</pre>' );
}); });
}); });
// Callback service parsing the authorization token and asking for the access token. This // Callback service parsing the authorization token and asking for the access token. This
@ -204,15 +204,15 @@ app.get( '/fb-today', function( req, res, next ) {
app.get('/fitbit_auth_callback', function(req, res, next) { app.get('/fitbit_auth_callback', function(req, res, next) {
const code = req.query.code; const code = req.query.code;
fitbit.fetchToken(code, function(err, token) { fitbit.fetchToken(code, function(err, token) {
if (err) { if (err)
return next(err); return next(err);
}
// persist the token // persist the token
jsonfile.writeFile(tfile, token, function(err) { jsonfile.writeFile(tfile, token, function(err) {
if (err) { if (err)
return next(err); return next(err);
}
console.log('!!!! Fitbit token saved'); console.log('!!!! Fitbit token saved');
res.redirect('/fb-profile'); res.redirect('/fb-profile');
@ -222,11 +222,11 @@ app.get('/fitbit_auth_callback', function(req, res, next) {
jsonfile.readFile('./fb-token.json', function(err, obj) { jsonfile.readFile('./fb-token.json', function(err, obj) {
if (err) { if (err)
logger.error(err); logger.error(err);
} else { else
fitbit.setToken(obj); fitbit.setToken(obj);
}
}); });
@ -245,5 +245,7 @@ http.createServer(app).listen(app.get('port'), function () {
server.on('request', app); server.on('request', app);
server.listen(port, () => { logger.info('New server listening on ' + server.address().port); }); server.listen(port, () => {
logger.info('New server listening on ' + server.address().port);
});