Browse Source

Move to API v3, support train groups

master
Kenneth Bruen 2 years ago
parent
commit
ccc3d8e127
Signed by: kbruen
GPG Key ID: C1980A470C3EE5B1
  1. 19
      sw.js
  2. 9
      view-train.html
  3. 99
      view-train.js
  4. 4
      worker.js

19
sw.js

@ -1,6 +1,6 @@
const VERSION = 'v1' const VERSION = 'v5'
const API_ORIGIN = 'https://scraper.infotren.dcdev.ro/' const API_ORIGIN = 'https://scraper.infotren.dcdev.ro/'
const API_TRAINS = `${API_ORIGIN}v2/trains` const API_TRAINS = `${API_ORIGIN}v3/trains`
const API_STATIONS = `${API_ORIGIN}v2/stations` const API_STATIONS = `${API_ORIGIN}v2/stations`
self.addEventListener('install', (event) => { self.addEventListener('install', (event) => {
@ -50,10 +50,6 @@ const deleteOldCaches = async () => {
await Promise.all(cachesToDelete.map(deleteCache)) await Promise.all(cachesToDelete.map(deleteCache))
} }
self.addEventListener('activate', (event) => {
event.waitUntil(deleteOldCaches())
})
// Enable navigation preload // Enable navigation preload
const enableNavigationPreload = async () => { const enableNavigationPreload = async () => {
if (self.registration.navigationPreload) { if (self.registration.navigationPreload) {
@ -62,6 +58,10 @@ const enableNavigationPreload = async () => {
} }
} }
self.addEventListener('activate', (event) => {
event.waitUntil(Promise.all([deleteOldCaches(), enableNavigationPreload()]))
})
const putInCache = async (request, response) => { const putInCache = async (request, response) => {
const cache = await caches.open(VERSION) const cache = await caches.open(VERSION)
await cache.put(request, response) await cache.put(request, response)
@ -87,12 +87,17 @@ const cacheFirst = async ({ request, preloadResponsePromise, refreshAnyway }) =>
} }
// Next try to use (and cache) the preloaded response, if it's there // Next try to use (and cache) the preloaded response, if it's there
if (preloadResponsePromise) {
const preloadResponse = await preloadResponsePromise const preloadResponse = await preloadResponsePromise
if (preloadResponse) { if (preloadResponse && preloadResponse.ok) {
console.info('using preload response', preloadResponse) console.info('using preload response', preloadResponse)
putInCache(request, preloadResponse.clone()) putInCache(request, preloadResponse.clone())
return preloadResponse return preloadResponse
} }
else {
console.log('got not ok preloadResponse, ignoring', preloadResponse)
}
}
// Next try to get the resource from the network // Next try to get the resource from the network
const responseFromNetwork = await fetch(request) const responseFromNetwork = await fetch(request)

9
view-train.html

@ -13,16 +13,21 @@
<script src="/worker.js"></script> <script src="/worker.js"></script>
<script src="/back.js"></script> <script src="/back.js"></script>
<script src="/items.js"></script>
<script src="view-train.js"></script> <script src="view-train.js"></script>
</head> </head>
<body> <body>
<h1>Train Info</h1> <h1 id="title"></h1>
<div id="comp-date"> <div id="comp-date">
<p class="sec" id="company"></p> <p class="sec" id="company"></p>
<p class="sec" id="date"></p> <p class="sec" id="date"></p>
</div> </div>
<div class="content" tabindex="0"> <div id="group-choice" class="content hidden">
</div>
<div id="train-info" class="content hidden" tabindex="0">
<div id="route"> <div id="route">
<h4>Route</h4> <h4>Route</h4>
<p class="thi">From</p> <p class="thi">From</p>

99
view-train.js

@ -1,5 +1,6 @@
var trainNumber var trainNumber
var date var date
var groupIndex = null
var showKm = false var showKm = false
@ -7,7 +8,7 @@ var trainData = null
var lastSuccessfulFetch = null var lastSuccessfulFetch = null
function onTrainData(data) { function onTrainData(data) {
var title = document.getElementsByTagName('h1')[0] var title = document.getElementById('title')
title.textContent = '' title.textContent = ''
title.appendChild(document.createTextNode('Train ')) title.appendChild(document.createTextNode('Train '))
var rankSpan = document.createElement('span') var rankSpan = document.createElement('span')
@ -19,10 +20,80 @@ function onTrainData(data) {
document.getElementById('company').textContent = data.operator document.getElementById('company').textContent = data.operator
document.getElementById('date').textContent = data.date document.getElementById('date').textContent = data.date
document.getElementById('route-from').textContent = data.route.from var group = null;
document.getElementById('route-to').textContent = data.route.to if (data.groups.length > 1 && groupIndex == null) {
document.getElementById('group-choice').classList.remove('hidden')
document.getElementById('group-choice').focus()
document.getElementById('train-info').classList.add('hidden')
if (data.status) { document.getElementsByClassName('rsk')[0].textContent = ''
document.getElementsByClassName('csk')[0].textContent = 'Select'
title.textContent = `Select Group for ${data.rank} ${data.number}`
var gc = document.getElementById('group-choice')
while (gc.childNodes.length > 0) {
gc.childNodes[0].remove()
}
for (var i = 0; i < data.groups.length; i++) {
var g = data.groups[i]
var groupLi = document.createElement('li')
gc.append(groupLi)
groupLi.tabIndex = i
groupLi.classList.add('items')
if (i === currentIndex) {
groupLi.focus()
}
(function (i) {
function onAction(e) {
var url = new URL(window.location.toString())
groupIndex = i
url.searchParams.append('groupIndex', groupIndex)
window.history.pushState({'groupIndex': groupIndex}, '', url.toString( ))
onTrainData(data)
}
groupLi.addEventListener('click', onAction)
groupLi.addEventListener('keypress', function (e) {
if (e.key == 'Enter') {
onAction(e)
}
})
})(i)
var routeP = document.createElement('p')
groupLi.append(routeP)
routeP.classList.add('pri')
routeP.textContent = `${g.route.from}${g.route.to}`
var groupP = document.createElement('p')
groupLi.append(groupP)
groupP.classList.add('thi')
groupP.textContent = i === 0 ? 'Main train' : `Group ${i}`
}
return
}
else if (data.groups.length === 1) {
group = data.groups[0]
}
else {
group = data.groups[groupIndex]
}
document.getElementById('group-choice').classList.add('hidden')
document.getElementById('train-info').classList.remove('hidden')
document.getElementById('train-info').focus()
document.getElementsByClassName('rsk')[0].textContent = 'Refresh'
document.getElementsByClassName('csk')[0].textContent = ''
document.getElementById('route-from').textContent = group.route.from
document.getElementById('route-to').textContent = group.route.to
if (group.status) {
document.getElementById('status').classList.remove('hidden') document.getElementById('status').classList.remove('hidden')
var statusDelay = document.getElementById('status-delay') var statusDelay = document.getElementById('status-delay')
@ -30,7 +101,7 @@ function onTrainData(data) {
statusDelay.childNodes[0].remove() statusDelay.childNodes[0].remove()
} }
var delayString = '' var delayString = ''
var delayMinutes = data.status.delay var delayMinutes = group.status.delay
if (delayMinutes === 0) { if (delayMinutes === 0) {
delayString = 'On time' delayString = 'On time'
statusDelay.appendChild(document.createTextNode(delayString)) statusDelay.appendChild(document.createTextNode(delayString))
@ -81,19 +152,19 @@ function onTrainData(data) {
statusLocation.childNodes[0].remove() statusLocation.childNodes[0].remove()
} }
var stateString = '' var stateString = ''
if (data.status.state === 'arrival') { if (group.status.state === 'arrival') {
stateString += 'when arriving at ' stateString += 'when arriving at '
} }
else if (data.status.state === 'departure') { else if (group.status.state === 'departure') {
stateString += 'when departing from ' stateString += 'when departing from '
} }
else if (data.status.state === 'passing') { else if (group.status.state === 'passing') {
stateString += 'while passing through ' stateString += 'while passing through '
} }
statusLocation.appendChild(document.createTextNode(stateString)) statusLocation.appendChild(document.createTextNode(stateString))
var stationSpan = document.createElement('span') var stationSpan = document.createElement('span')
statusLocation.appendChild(stationSpan) statusLocation.appendChild(stationSpan)
stationSpan.textContent = data.status.station stationSpan.textContent = group.status.station
stationSpan.classList.add('station') stationSpan.classList.add('station')
} }
else { else {
@ -112,7 +183,7 @@ function onTrainData(data) {
var stationsList = document.createElement('ul') var stationsList = document.createElement('ul')
stationsDiv.appendChild(stationsList) stationsDiv.appendChild(stationsList)
data.stations.forEach(function (station) { group.stations.forEach(function (station) {
var stationItem = document.createElement('li') var stationItem = document.createElement('li')
stationsList.appendChild(stationItem) stationsList.appendChild(stationItem)
stationItem.classList.add('stationItem') stationItem.classList.add('stationItem')
@ -202,7 +273,7 @@ function refresh() {
}, timeout || 60000) }, timeout || 60000)
} }
return fetch( return fetch(
`https://scraper.infotren.dcdev.ro/v2/train/${trainNumber}?date=${date.getFullYear().toString()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`, `https://scraper.infotren.dcdev.ro/v3/trains/${trainNumber}?date=${date.getFullYear().toString()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`,
{ {
cache: 'no-store', cache: 'no-store',
}, },
@ -235,6 +306,11 @@ function rsk() {
refresh() refresh()
} }
window.addEventListener('popstate', function (e) {
groupIndex = null
refresh()
})
window.addEventListener('load', function (e) { window.addEventListener('load', function (e) {
if (!new URL(window.location.href).searchParams.has('train')) { if (!new URL(window.location.href).searchParams.has('train')) {
window.history.back() window.history.back()
@ -249,6 +325,7 @@ window.addEventListener('load', function (e) {
trainNumber = sp.get('train') trainNumber = sp.get('train')
date = sp.has('date') ? new Date(sp.get('date')) : new Date() date = sp.has('date') ? new Date(sp.get('date')) : new Date()
groupIndex = sp.has('groupIndex') ? parseInt(sp.get('groupIndex')) : null
document.querySelectorAll('.rsk').forEach(function (rskElem) { document.querySelectorAll('.rsk').forEach(function (rskElem) {
rskElem.addEventListener('click', function (e) { rskElem.addEventListener('click', function (e) {

4
worker.js

@ -20,4 +20,6 @@ const registerServiceWorker = async () => {
} }
}; };
registerServiceWorker(); if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
registerServiceWorker();
}

Loading…
Cancel
Save