traintimesPWA/server/lib/train.js
2019-01-16 15:14:52 +00:00

186 lines
4.9 KiB
JavaScript

// train.js
const request = require('request');
const http = require('http');
const cheerio = require('cheerio');
// const STRING = require('string');
const logger = require('log4js').getLogger('train');
const trainCache = {
'last': {},
'data': {}
};
logger.level = 'info';
function getTrainTimes(req, res) {
// console.log(req);
logger.info(`getTrainTimes: ${ JSON.stringify(req.query)}`);
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`;
// logger.debug(`https://huxley.apphb.com${url}`);
Query(function (a, b) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(a));
}, res, 'huxley.apphb.com', url);
}
else {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({}));
}
}
function getNextTrainTimes(req, res) {
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;
trainToken = trainFrom + trainTo;
url = `/next/${ trainFrom }/to/${ trainTo }/1?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8`;
logger.info(`Requesting latest time for : ${ trainToken}`);
// logger.debug(`https://huxley.apphb.com${url}`);
const now = new Date();
const nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60);
logger.info(`Now Seconds: ${ nowSeconds}`);
if (trainCache.last[trainToken] === null || nowSeconds !== trainCache.last[trainToken])
Query(function (a, b) {
const output = {};
const ts = a.departures[0].service;
if (ts !== null) {
// console.log(ts);
// GLOBAL.lastcheck = now;
logger.debug(ts.sta, ts.std);
// logger.debug(toSeconds(ts.sta));
output.sta = (ts.sta !== null) ? ts.sta : ts.std;
output.eta = (ts.eta !== null ? ts.eta : ts.etd);
// trainCache.last.glqdbe = toSeconds(ts.sta);
// console.log(ts);
}
else {
logger.warn('*** NO SERVICE');
output.sta = 'No Service';
output.eta = 'No Service';
}
trainCache.data[trainToken] = output;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(trainCache.data[trainToken]));
}, res, 'huxley.apphb.com', url);
}
}
function getRoute(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 grabNews(q) {
const url = `http://nationalrail.co.uk/service_disruptions/${ q }`;
logger.debug(url);
return new Promise(function(resolve, reject) {
request(url, function(err, resp, body) {
if (err)
// Logger.error(err);
return reject(err);
// Throw err;
// logger.debug(body);
const $ = cheerio.load(body);
const nbody = $('.zebra').first().html();
logger.debug(nbody);
return resolve(nbody);
}, function(error, response, body) {
if (response.statusCode !== 200) {
logger.error(response.statusCode);
logger.error(body);
return reject(error);
}
});
});
}
function getNews(req, res) {
logger.info(`getNews: ${ JSON.stringify(req.query)}`);
if (req.query.hasOwnProperty('q')) {
const q = req.query.q;
grabNews(q)
.then((d) => {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ 'd':d }));
});
}
}
module.exports = {
getTrainTimes,
getNextTrainTimes,
getRoute,
getNews
};
function toSeconds(inval) {
console.log('inval', typeof inval);
if (typeof inval === 'string') {
const a = inval.split(':');
return ((parseInt(a[0]) * (60 * 60)) + (parseInt(a[1]) * 60));
}
return '';
}
function Query(callback, r, host, path) {
logger.debug(path);
const req = r;
const options = {
'host': host,
// port: 80,
'path': path,
// method: 'GET',
'headers': {}
};
try {
http.request(options).on('response', function (response) {
let data = '';
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function () {
callback(JSON.parse(data), r);
});
response.on('error', function (e) {
console.error(e);
});
}).end();
}
catch (e) {
console.log(e);
}
}