travel news and handling the view

This commit is contained in:
Martin Donnelly 2017-12-29 15:55:13 +00:00
parent a805ce77b2
commit 2bca74520d
9 changed files with 386 additions and 136 deletions

View File

@ -19,7 +19,7 @@ const googleWebFonts = require('gulp-google-webfonts');
const fontOptions = { };
gulp.task('styles', function() {
return gulp.src(['src/css/common.css'])
return gulp.src(['node_modules/backbone.modal/backbone.modal.css', 'node_modules/backbone.modal/backbone.modal.theme.css'])
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
/* .pipe(gulp.dest('dist/css'))*/

131
package-lock.json generated
View File

@ -35,6 +35,12 @@
"through2": "2.0.3"
}
},
"@types/node": {
"version": "8.5.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-8.5.2.tgz",
"integrity": "sha512-KA4GKOpgXnrqEH2eCVhiv2CsxgXGQJgV1X0vsGlh+WCnxbeAE1GT44ZsTU1IN5dEeV/gDupKa7gWo08V5IxWVQ==",
"dev": true
},
"Base64": {
"version": "0.2.1",
"resolved": "https://registry.npmjs.org/Base64/-/Base64-0.2.1.tgz",
@ -1269,6 +1275,12 @@
"underscore": "1.8.3"
}
},
"backbone.modal": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/backbone.modal/-/backbone.modal-1.1.6.tgz",
"integrity": "sha1-9iz4vMQBtGWUcVP+mpUvEHYxrIc=",
"dev": true
},
"balanced-match": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
@ -1397,6 +1409,12 @@
"type-is": "1.6.15"
}
},
"boolbase": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
"integrity": "sha1-aN/1++YMUes3cl6p4+0xDcwed24=",
"dev": true
},
"boom": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/boom/-/boom-4.3.1.tgz",
@ -1840,6 +1858,20 @@
"integrity": "sha1-tUc7M9yXxCTl2Y3IfVXU2KKci/I=",
"dev": true
},
"cheerio": {
"version": "1.0.0-rc.2",
"resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.2.tgz",
"integrity": "sha1-S59TqBsn5NXawxwP/Qz6A8xoMNs=",
"dev": true,
"requires": {
"css-select": "1.2.0",
"dom-serializer": "0.1.0",
"entities": "1.1.1",
"htmlparser2": "3.9.2",
"lodash": "4.17.4",
"parse5": "3.0.3"
}
},
"chokidar": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-1.7.0.tgz",
@ -2373,6 +2405,24 @@
"integrity": "sha1-gIrcLnnPhHOAabZGyyDsJ762KeA=",
"dev": true
},
"css-select": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/css-select/-/css-select-1.2.0.tgz",
"integrity": "sha1-KzoRBTnFNV8c2NMUYj6HCxIeyFg=",
"dev": true,
"requires": {
"boolbase": "1.0.0",
"css-what": "2.1.0",
"domutils": "1.5.1",
"nth-check": "1.0.1"
}
},
"css-what": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/css-what/-/css-what-2.1.0.tgz",
"integrity": "sha1-lGfQMsOM+u+58teVASUwYvh/ob0=",
"dev": true
},
"cssnano": {
"version": "3.10.0",
"resolved": "https://registry.npmjs.org/cssnano/-/cssnano-3.10.0.tgz",
@ -2781,11 +2831,54 @@
"esutils": "2.0.2"
}
},
"dom-serializer": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.1.0.tgz",
"integrity": "sha1-BzxpdUbOB4DOI75KKOKT5AvDDII=",
"dev": true,
"requires": {
"domelementtype": "1.1.3",
"entities": "1.1.1"
},
"dependencies": {
"domelementtype": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.1.3.tgz",
"integrity": "sha1-vSh3PiZCiBrsUVRJJCmcXNgiGFs=",
"dev": true
}
}
},
"domain-browser": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/domain-browser/-/domain-browser-1.1.7.tgz",
"integrity": "sha1-hnqksJP6oF8d4IwG9NeyH9+GmLw="
},
"domelementtype": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.0.tgz",
"integrity": "sha1-sXrtguirWeUt2cGbF1bg/BhyBMI=",
"dev": true
},
"domhandler": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.4.1.tgz",
"integrity": "sha1-iS5HAAqZvlW783dP/qBWHYh5wlk=",
"dev": true,
"requires": {
"domelementtype": "1.3.0"
}
},
"domutils": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz",
"integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=",
"dev": true,
"requires": {
"dom-serializer": "0.1.0",
"domelementtype": "1.3.0"
}
},
"double-ended-queue": {
"version": "2.1.0-0",
"resolved": "https://registry.npmjs.org/double-ended-queue/-/double-ended-queue-2.1.0-0.tgz",
@ -2890,6 +2983,12 @@
"tapable": "0.1.10"
}
},
"entities": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/entities/-/entities-1.1.1.tgz",
"integrity": "sha1-blwtClYhtdra7O+AuQ7ftc13cvA=",
"dev": true
},
"errno": {
"version": "0.1.6",
"resolved": "https://registry.npmjs.org/errno/-/errno-0.1.6.tgz",
@ -6831,6 +6930,20 @@
"resolved": "https://registry.npmjs.org/htmlescape/-/htmlescape-1.1.1.tgz",
"integrity": "sha1-OgPtwiFLyjtmQko+eVk0lQnLA1E="
},
"htmlparser2": {
"version": "3.9.2",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.9.2.tgz",
"integrity": "sha1-G9+HrMoPP55T+k/M6w9LTLsAszg=",
"dev": true,
"requires": {
"domelementtype": "1.3.0",
"domhandler": "2.4.1",
"domutils": "1.5.1",
"entities": "1.1.1",
"inherits": "2.0.3",
"readable-stream": "2.3.3"
}
},
"http-browserify": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/http-browserify/-/http-browserify-1.3.2.tgz",
@ -9441,6 +9554,15 @@
"set-blocking": "2.0.0"
}
},
"nth-check": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/nth-check/-/nth-check-1.0.1.tgz",
"integrity": "sha1-mSms32KPwsQQmN6rgqxYDPFJquQ=",
"dev": true,
"requires": {
"boolbase": "1.0.0"
}
},
"num2fraction": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/num2fraction/-/num2fraction-1.2.2.tgz",
@ -9858,6 +9980,15 @@
"integrity": "sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY=",
"dev": true
},
"parse5": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-3.0.3.tgz",
"integrity": "sha512-rgO9Zg5LLLkfJF9E6CCmXlSE4UVceloys8JrFqCcHloC3usd/kJCyPDwH2SOlzix2j3xaP9sUX3e8+kvkuleAA==",
"dev": true,
"requires": {
"@types/node": "8.5.2"
}
},
"parseurl": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz",

View File

@ -27,6 +27,8 @@
"babel-preset-env": "^1.6.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"backbone.modal": "^1.1.6",
"cheerio": "^1.0.0-rc.2",
"del": "^3.0.0",
"eslint": "^4.12.0",
"eslint-plugin-react": "^7.4.0",

View File

@ -16,9 +16,10 @@ const cache = apicache.middleware;
app.use(express.static(path.join(__dirname, sitePath)));
app.use('/gettrains', train.getTrainTimes);
app.use('/getnexttraintimes', train.getNextTrainTimes);
app.use('/getroute', train.getRoute);
app.use('/gettrains', cache('60 seconds'), train.getTrainTimes);
app.use('/getnexttraintimes', cache('60 seconds'), train.getNextTrainTimes);
app.use('/getroute', cache('60 seconds'), train.getRoute);
app.use('/getnews', cache('30 minutes'), train.getNews);
app.listen(port, (err) => {
if (err)

View File

@ -1,130 +1,140 @@
// 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': {}
};
module.exports = {
'dbe_glq': function (req, res) {
logger.info('DBE:GLQ request');
logger.level = 'debug';
const now = new Date();
const nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60);
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`;
if (trainCache.last.dbeglq === null || nowSeconds !== trainCache.last.dbeglq)
Query(function (a, b) {
const ts = a.departures[0].service;
const output = {};
logger.debug(ts);
logger.debug(ts.sta);
output.sta = ts.sta;
output.eta = ts.eta;
trainCache.data.dbeglq = output;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(trainCache.data.dbeglq));
}, res, 'huxley.apphb.com', '/next/dbe/to/glq/1?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8');
},
'glq_dbe': function (req, res) {
logger.info('GLQ:DBE request');
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) {
const ts = a.departures[0].service;
const output = {};
logger.debug(ts);
// GLOBAL.lastcheck = now;
logger.debug(ts.sta);
// logger.debug(toSeconds(ts.sta));
output.sta = ts.sta;
output.eta = ts.eta;
trainCache.data.glqdbe = output;
// trainCache.last.glqdbe = toSeconds(ts.sta);
// console.log(ts);
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(trainCache.data.glqdbe));
}, res, 'huxley.apphb.com', '/next/glq/to/dbe/1?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8');
},
'getTrainTimes': function (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`;
Query(function (a, b) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(a));
}, res, 'huxley.apphb.com', url);
}
else {
Query(function (a, b) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({}));
}
},
'getNextTrainTimes': function (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}`);
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);
}
}, '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`);
}
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}`);
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) {
@ -167,3 +177,4 @@ function Query(callback, r, host, path) {
console.log(e);
}
}

View File

@ -17,6 +17,8 @@
<meta name="application-name" content="Train Times">
<meta name="theme-color" content="#ffffff">
<link href="css/backbone.modal.css" rel="stylesheet" type="text/css"/>
<link href="css/backbone.modal.theme.css" rel="stylesheet" type="text/css"/>
</head>
<body>
@ -29,12 +31,28 @@
<div class="mui--appbar-height"></div>
<div class="mui-container">
<div class="app"></div>
<div id="trains"></div>
<div id='trainResults' class="mui--hide"></div>
</div>
<div id="snackbar">⚡ Offline, waiting to reconnect...</div>
<script type="text/template" id="modal-template">
<!--<div class="bbm-modal__topbar">
<h3 class="bbm-modal__title">Backbone.Modal</h3>
</div>-->
<div class="bbm-modal__section" id="modalContent">
</div>
<div class="bbm-modal__bottombar">
<a href="#" class="bbm-button">close</a>
</div>
</script>
<!--<script src="//cdn.muicss.com/mui-0.9.26/js/mui.min.js"></script>-->
<script src="js/vendor.js" async></script>
<script src="js/bundle.js" async></script>

View File

@ -2,6 +2,7 @@ require('muicss');
const $ = require('jquery');
const _ = require('underscore');
const Backbone = require('backbone');
require('backbone.modal');
const { TrainModel, TrainView } = require('./train');
const { RouteModel, RouteView } = require('./route');
@ -18,12 +19,19 @@ const { RouteModel, RouteView } = require('./route');
{ 'from': 'glc', 'to': 'ptk' },
{ 'from': 'ptk', 'to': 'dbe' },
{ 'from': 'glc', 'to': 'eus' },
{ 'from': 'eus', 'to': 'glc' }
{ 'from': 'eus', 'to': 'glc' },
{ 'from': 'pad', 'to': 'hxx' }
],
'views':{}
};
const Modal = Backbone.Modal.extend({
'template': '#modal-template',
'cancelEl': '.bbm-button',
'content' : 'bob'
});
app.eventBus = _.extend({}, Backbone.Events);
app.eventBus.on('offline', function() {
@ -42,7 +50,23 @@ const { RouteModel, RouteView } = require('./route');
}
}, this);
app.routeView = new RouteView( { 'model': new RouteModel(), 'eventBus': app.eventBus });
app.eventBus.on('showModal', function(d) {
// 'template': '#modal-template',
console.log('!! ShowModal');
console.log('d', d);
const obj = { 'content': d.d };
const modalView = new Modal();
console.log(modalView);
const html = modalView.render().el;
$('.app').html(html);
let $modalContent = $('#modalContent');
$modalContent.html(d.d);
}, this);
app.routeView = new RouteView( { 'model': new RouteModel({ 'bus': app.eventBus }), 'eventBus': app.eventBus, 'el': $('#trainResults') });
app.createViews = function() {
for (const route of this.routes) {
@ -54,12 +78,12 @@ const { RouteModel, RouteView } = require('./route');
}
};
if ('serviceWorker' in navigator)
/* if ('serviceWorker' in navigator)
navigator.serviceWorker
.register('./service-worker.js')
.then(function() {
console.log('Service Worker Registered');
});
});*/
app.createViews();
})();

View File

@ -6,6 +6,7 @@ const RouteModel = Backbone.Model.extend({
'initialize': function () {
const fromStation = this.get('from');
const toStation = this.get('to');
const routeUrl = `/gettrains?from=${ this.get('from') }&to=${ this.get('to')}`;
const target = this.get('from') + this.get('to');
this.set('url', routeUrl);
@ -14,12 +15,13 @@ const RouteModel = Backbone.Model.extend({
this.set('visible', false);
this.set('trainData', { 'eta':'OFF', 'sta': 'OFF' });
this.set('interval', null);
this.interval = null;
this.update();
},
'update': function (m) {
console.log('Route model update');
console.log(this.changedAttributes());
console.log(_.keys(this.changedAttributes()));
console.log(_.keys(this.changedAttributes()));
if (!this.get('to'))
return;
@ -28,6 +30,7 @@ const RouteModel = Backbone.Model.extend({
const limit = (hours < 6) ? 3600000 : 95000;
const mod = limit - (now.getTime() % limit);
console.log('mod', mod);
if (hours >= 6)
this.getRoute();
@ -38,9 +41,10 @@ const RouteModel = Backbone.Model.extend({
console.log('routeUpdateFn');
this.update();
};
if (!this.get('interval'))
this.set('interval', setInterval(routeUpdateFn.bind(this), mod + 10)) ;
clearTimeout(this.interval);
this.interval = 0;
this.interval = setTimeout(routeUpdateFn.bind(this), mod + 10);
},
'getRoute': function () {
const url = `/gettrains?from=${ this.get('from') }&to=${ this.get('to')}`;
@ -77,13 +81,48 @@ const RouteModel = Backbone.Model.extend({
'setRoute': function(from, to) {
this.set('from', from);
this.set('to', to);
},
'getNews': function(query) {
console.log('model:getNews');
const url = `/getnews?q=${ query}`;
const self = this;
const bus = this.get('bus');
$.ajax({
'type': 'GET',
'url': url,
'data': '',
'dataType': 'json',
'timeout': 10000,
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
},
'success': function (data) {
// getTrainsCB(data);
console.log('Got', data);
bus.trigger('showModal', data);
// self.set('route', data);
// self.set('visible', true);
},
'error': function (xhr, type) {
console.error('ajax error');
console.log('readyState', xhr.readyState);
console.log('status', xhr.status);
console.error(type);
}
});
}
});
const RouteView = Backbone.View.extend({
'tagName': 'div',
'initialize': function (options) {
_.bindAll(this, 'render');
_.bindAll(this, 'render', 'stations', 'news');
this.eventBus = options.eventBus;
// this.model.bind('change', this.render);
/* this.model.bind('change:route', function(e){
@ -93,8 +132,10 @@ const RouteView = Backbone.View.extend({
this.$trains = $('#trains');
this.$traininfo = $('#traininfo');
this.$traintext = $('#trainResults');
this.$el = this.$traintext;
this.urlParse = /^(?:(http[s]?|ftp[s]):\/\/)?([^:\/\s]+)(:[0-9]+)?((?:\/\w+)*\/)([\w\-\.]+[^#?\s]+)([^#\s]*)?(#[\w\-]+)?$/;
// this.$el = this.$traintext;
// this.el = this.$traintext[0];
console.log(this);
this.eventBus.on('showRoute', function(d) {
console.log('Showroute', d);
@ -106,10 +147,31 @@ const RouteView = Backbone.View.extend({
this.initView();
},
'events': {
'click a': 'news',
'click .station': 'stations'
},
'render': function () {
'stations': function(e) {
console.log('Stations', e);
this.eventBus.trigger('showModal');
},
'news': function(e) {
const target = e.currentTarget;
const data = target.dataset;
console.log('News', e);
if (data.hasOwnProperty('url')) {
const url = data.url;
const query = this.urlParse.exec(url)[5];
console.log(url);
console.log(query);
this.model.getNews(query);
}
},
'render': function (m) {
console.log('Routeview:Render');
console.log('m', m);
console.log('r', m.changedAttributes());
console.log('r', _.keys(m.changedAttributes()));
const route = this.model.get('route');
console.log(route);
@ -126,11 +188,11 @@ const RouteView = Backbone.View.extend({
const status = item.eta !== null ? item.eta : item.etd;
const statusMode = (status.toLowerCase() === 'on time') ? 'ontime' : 'delayed';
const delayReason = (item.delayReason !== null) ? '<tr><td colspan="4" class="mui--bg-danger mui--text-white" style="padding-bottom:2px;">${item.delayReason}</td></tr>' : '';
const delayReason = (item.delayReason !== null) ? `<tr><td colspan="4" class="mui--bg-danger mui--text-white" style="font-size:75%;">${item.delayReason}</td></tr>` : '';
services.push({ 'location':dest.locationName, 'time':time, 'status':status, 'platform':platform, 'cancel':item.cancelReason, 'type':'train' });
if (!item.isCancelled)
ws = `${ws }<tr><td>${dest.locationName} ${via}</td>
ws = `${ws }<tr><td data-id="${item.serviceIdUrlSafe}" class="station">${dest.locationName} ${via}</td>
<td class="mui--text-center">${time}</td>
<td class="mui--text-center ${statusMode}">${status}</td>
<td class="mui--text-center">${platform}</td>
@ -157,7 +219,7 @@ const RouteView = Backbone.View.extend({
// we have national rail messages so put a box at the top
// <div class="mui--bg-danger .mui--text-white" style="height:10px;"></div>
for (const item of route.nrccMessages) {
const msg = item.value;
const msg = item.value.replace('href=', 'data-url=');
nrMessages = `${nrMessages}<div class="mui--bg-danger mui--text-white" style="padding:2px;">${msg}</div>`;
}
@ -175,6 +237,7 @@ ${nrMessages}
this.$traintext.removeClass('mui--hide').addClass('mui--show');
},
'initView': function () {
},
'showTrains': function () {
console.log('Show train');

View File

@ -75,7 +75,7 @@ self.addEventListener('activate', function(e) {
});
self.addEventListener('fetch', function(e) {
console.log('[Service Worker] Fetch', e.request.url);
console.warn('[Service Worker] Fetch', e.request.url);
const dataUrl = '/getnexttraintimes?';
if (e.request.url.indexOf(dataUrl) > -1) {
console.log('!');