-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
638 lines (557 loc) · 16.7 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
import turfDistance from '@turf/distance'
import apicache from 'apicache'
import { exec as rawExec } from 'child_process'
import compression from 'compression'
import cors from 'cors'
import express from 'express'
import { readFile } from 'fs/promises'
import {
closeDb,
getAgencies,
getCalendarDates,
getCalendars,
getFrequencies,
getRoutes,
getShapesAsGeoJSON,
getStopTimeUpdates,
getStops,
getStopsAsGeoJSON,
getStoptimes,
getTrips,
importGtfs,
openDb,
updateGtfsRealtime,
} from 'gtfs'
import util from 'util'
import { buildAgencySymbolicGeojsons } from './buildAgencyGeojsons.js'
import {
areDisjointBboxes,
bboxArea,
dateHourMinutes,
filterFeatureCollection,
joinFeatureCollections,
rejectNullValues,
} from './utils.js'
let cacheMiddleware = apicache.middleware
const exec = util.promisify(rawExec)
import Cache from 'file-system-cache'
import { buildAgencyAreas } from './buildAgencyAreas.js'
import {
dateFromString,
getWeekday,
isAfternoon,
isLunch,
isMorning,
} from './timetableAnalysis.js'
const month = 60 * 60 * 24 * 30
const cache = Cache.default({
basePath: './.cache', // (optional) Path where cache files are stored (default).
ttl: month, // (optional) A time-to-live (in secs) on how long an item remains cached.
})
const runtimeCache = { agencyAreas: null }
// This because retrieving the cache takes 1 sec
cache
.get('agencyAreas')
.then((result) => {
runtimeCache.agencyAreas = result // This because retrieving the cache takes 1 sec
console.log('runtimeCache chargé depuis cache')
})
.catch((err) => console.log('Erreur dans le chargement du runtime cache'))
let config
const readConfig = async () => {
const newConfig = await JSON.parse(
await readFile(new URL('./config.json', import.meta.url))
)
config = newConfig
return newConfig
}
await readConfig()
let dbName = await cache.get('dbName', null)
if (!dbName) {
dbName = dateHourMinutes()
await cache.set('dbName', dbName)
}
config.sqlitePath = 'db/' + dbName
console.log(`set db name ${dbName} from disc cache`)
const app = express()
app.use(
cors({
origin: '*',
})
)
// Désactivation temporaire pour régler nos pb de multiples entrées db
//app.use(cacheMiddleware('20 minutes'))
app.use(compression())
/* For the french parlementary elections, we experimented serving pmtiles. See data/. It's very interesting, we're keeping this code here since it could be used to produce new contextual maps covering news. Same for geojsons. */
app.use(express.static('data/pmtiles'))
app.use(express.static('data/geojson'))
let resultats
try {
resultats = await JSON.parse(
await readFile(
new URL(
'./data/geojson/resultats-legislatives-2024.geojson',
import.meta.url
)
)
)
} catch (e) {
console.log(
'Les résultats du premier tour des legislatives, qui incluent les circonscriptions, ne sont pas chargées, pas grave mais allez voir data/circo.ts si ça vous intéresse'
)
}
app.get('/elections-legislatives-2024/:circo', (req, res) => {
if (!resultats)
return res.send("Les résultats n'ont pas été précalculés sur ce serveur")
try {
const { circo } = req.params
const result = resultats.features.find(
(feature) => feature.properties.circo === circo
)
res.json(result)
closeDb(db)
} catch (e) {
console.error(e)
}
})
const port = process.env.PORT || 3001
const parseGTFS = async (newDbName) => {
const config = await readConfig()
console.log('will load GTFS files in node-gtfs')
config.sqlitePath = 'db/' + newDbName
await importGtfs(config)
await updateGtfsRealtime(config)
return "C'est bon !"
}
app.get('/agency/geojsons/:agency_id', (req, res) => {
try {
const db = openDb(config)
const { agency_id } = req.params
const agency = getAgencies({ agency_id })[0]
const geojsons = buildAgencySymbolicGeojsons(db, agency)
res.json(geojsons)
closeDb(db)
} catch (e) {
console.error(e)
}
})
app.get('/buildAgencyAreas', (req, res) => {
try {
const db = openDb(config)
const areas = buildAgencyAreas(db, cache, runtimeCache)
closeDb(db)
res.json(areas)
} catch (e) {
console.error(e)
}
})
app.get('/dev-agency', (req, res) => {
const db = openDb(config)
const areas = buildAgencySymbolicGeojsons(db, { agency_id: '1187' })
//res.json(areas)
return res.json([['1187', areas]])
})
app.get('/agencyAreas', async (req, res) => {
const { agencyAreas } = runtimeCache
return res.json(agencyAreas)
})
app.get(
'/agencyArea/:latitude/:longitude2/:latitude2/:longitude/:format/:selection?',
async (req, res) => {
try {
const db = openDb(config)
//TODO switch to polylines once the functionnality is judged interesting client-side, to lower the bandwidth client costs
const {
longitude,
latitude,
latitude2,
longitude2,
selection,
format = 'geojson',
} = req.params,
userBbox = [+longitude, +latitude, +longitude2, +latitude2]
const { noCache } = req.query
const selectionList = selection?.split('|')
if (selection && noCache) {
const agencies = getAgencies({ agency_id: selectionList })
console.log(
'Will build geojson shapes for ',
selection,
'. Agencies found : ',
agencies
)
const result = agencies.map((agency) => {
const agency_id = agency.agency_id
const geojson =
agency_id == '1187'
? buildAgencySymbolicGeojsons(db, agency_id)
: buildAgencySymbolicGeojsons(db, agency_id, true)
return [agency_id, { agency, geojson }]
})
//res.json(areas)
return res.json(result)
}
const { day } = req.query
const { agencyAreas } = runtimeCache
if (agencyAreas == null)
return res.send(
`Construisez d'abord le cache des aires d'agences avec /buildAgencyAreas`
)
const entries = Object.entries(agencyAreas)
const selectedAgencies = entries.filter(([id, agency]) => {
const inSelection = !selection || selectionList.includes(id)
if (!inSelection) return false
const disjointBboxes = areDisjointBboxes(agency.bbox, userBbox)
if (disjointBboxes) return false
const bboxRatio = bboxArea(userBbox) / bboxArea(agency.bbox),
zoomedEnough = Math.sqrt(bboxRatio) < 3,
notTooZoomed = Math.sqrt(bboxRatio) > 0.02
/*
console.log(
id,
disjointBboxes,
userBbox,
agency.bbox,
isAgencyBigEnough
)
*/
return zoomedEnough && notTooZoomed
})
if (format === 'prefetch')
return res.json(selectedAgencies.map(([id]) => id))
return res.json(selectedAgencies)
const withDistances = entries
.map(([agencyId, agency]) => {
const { bbox } = agency
const isIncluded =
longitude > bbox[0] &&
longitude < bbox[2] &&
latitude > bbox[1] &&
latitude < bbox[3]
if (!isIncluded) return false
const bboxCenter = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]
const distance = turfDistance(
createPoint(bboxCenter),
createPoint([longitude, latitude])
)
return { agencyId, ...agency, bboxCenter, distance }
})
.filter(Boolean)
.sort((a, b) => a.distance - b.distance)
// Return only the closest agency for now. No algorithm is perfect, so will need to let the user choose in a following iteration
const theOne = withDistances[0].geojson
const goodDay = day
? filterFeatureCollection(
theOne,
(feature) => feature.properties.calendarDates.date === +day
)
: theOne
res.send(goodDay)
} catch (error) {
console.error(error)
}
}
)
app.get('/agency/:agency_id?', (req, res) => {
try {
const { agency_id } = req.params
console.log(`Requesting agency by id ${agency_id}`)
const db = openDb(config)
if (agency_id == null) res.json(getAgencies())
else res.json(getAgencies({ agency_id })[0])
return closeDb(db)
} catch (error) {
console.error(error)
}
})
app.get('/agencyArea/:agency_id', async (req, res) => {
const { agency_id } = req.params
const { agencyAreas } = runtimeCache
const result = agencyAreas[agency_id]
return res.json(result)
})
app.get('/agencyBbox/:agency_id', async (req, res) => {
const { agency_id } = req.params
const { agencyAreas } = runtimeCache
const result = agencyAreas[agency_id].bbox
return res.json(result)
})
app.get('/stop/:stop_id?', (req, res) => {
try {
const { stop_id } = req.params
console.log(`Requesting agency by id ${stop_id}`)
const db = openDb(config)
res.json(getStops({ stop_id })[0])
return closeDb(db)
} catch (error) {
console.error(error)
}
})
app.get('/getStopIdsAroundGPS', (req, res) => {
try {
const latitude = req.query.latitude
const longitude = req.query.longitude
const distance = req.query.distance || 20
const db = openDb(config)
const test = getStops({ stop_lat: latitude, stop_lon: longitude }, [], [], {
bounding_box_side_m: distance,
})
if (test.length === 0) {
res.json({ stopIds: null })
} else {
res.json({
// Filters location_type=(0|null) to return only stop/platform
stopIds: test
.filter((stop) => {
return !stop.location_type
})
.map((stop) => stop.stop_id),
})
}
closeDb(db)
} catch (error) {
console.error(error)
}
})
app.get('/stopTimes/:ids/:day?', (req, res) => {
try {
const ids = req.params.ids.split('|')
// TODO implement this, to reduce radically the weight of the payload returned to the client for the basic usage of displaying stop times at the present or another future date
const day = req.params.day
const db = openDb(config)
const results = ids.map((id) => {
console.time('stoptimes')
const stops = getStoptimes({
stop_id: [id],
})
const stopTrips = stops.map((stop) => stop.trip_id)
const trips = getTrips({ trip_id: stopTrips }).map((trip) => ({
...trip,
frequencies: getFrequencies({ trip_id: trip.trip_id }),
calendar: getCalendars({ service_id: trip.service_id }),
calendarDates: getCalendarDates({ service_id: trip.service_id }),
//realtime: getStopTimeUpdates({ trip_id: trip.trip_id }),
}))
const tripRoutes = trips.reduce(
(memo, next) => [...memo, next.route_id],
[]
)
const routes = getRoutes({ route_id: tripRoutes }).map((route) => ({
...route,
tripsCount: trips.filter((trip) => trip.route_id === route.route_id)
.length,
}))
console.timeLog('stoptimes')
console.time('shapes')
const features = routes
.map((route) => [
...getShapesAsGeoJSON({
route_id: route.route_id,
}).features,
...getStopsAsGeoJSON({
route_id: route.route_id,
}).features,
])
.flat()
console.timeLog('shapes')
const result = {
stops: stops.map(rejectNullValues),
trips: trips.map(rejectNullValues),
routes,
features,
}
return [id, result]
})
res.json(results)
closeDb(db)
} catch (error) {
console.error(error)
}
})
app.get('/realtime/getStopTimeUpdates', async (req, res) => {
const db = openDb(config)
await updateGtfsRealtime(config)
res.json(getStopTimeUpdates())
return closeDb(db)
})
app.get('/routes/trip/:tripId', (req, res) => {
try {
const tripId = req.params.tripId
const db = openDb(config)
const routeIds = getTrips({ trip_id: [tripId] }).map((el) => el.route_id)
const routes = getRoutes({
route_id: routeIds,
})
res.json({ routes })
// closeDb(db);
} catch (error) {
console.error(error)
}
})
app.get('/agencies', (req, res) => {
try {
const db = openDb(config)
const agencies = getAgencies()
res.json({ agencies })
} catch (error) {
console.error(error)
}
})
app.get('/route/:routeId', (req, res) => {
const { routeId: route_id } = req.params
try {
const db = openDb(config)
const route = getRoutes({ route_id })[0]
const trips = getTrips({ route_id })
const times = getStoptimes({
trip_id: trips.map((trip) => trip.trip_id),
}).map((el) => {
const h = +el.departure_time.slice(0, 2)
return {
...el,
debugSchool:
isMorning(h) || isAfternoon(h) || isLunch(h)
? 'school'
: 'not school',
isMorning: isMorning(h),
isAfternoon: isAfternoon(h),
isLunch: isLunch(h),
}
})
const calendarDates = getCalendarDates({
service_id: trips.map((el) => el.service_id),
}).map((el) => {
const day = {
...el,
date_o: dateFromString('' + el.date),
weekday: getWeekday(dateFromString('' + el.date)),
}
return day
})
res.json({ route, trips, calendarDates, times })
closeDb(db)
} catch (error) {
console.error(error)
}
})
app.get('/routes/:routeIds', (req, res) => {
const { routeIds } = req.params
try {
const db = openDb(config)
const routes = getRoutes({ route_id: routeIds.split('|') })
res.json(routes)
closeDb(db)
} catch (error) {
console.error(error)
}
})
app.get('/geojson/route/:routeid', (req, res) => {
try {
const { routeId } = req.params
const { day } = req.query
const db = openDb(config)
const trips = db
.prepare(
`SELECT trips.trip_id
FROM trips
JOIN calendar_dates ON trips.service_id = calendar_dates.service_id
WHERE trips.route_id = '${routeId}' AND calendar_dates.date = '${day}'
` //AND end_date >= $date'
)
//JOIN shapes ON trips.shape_id = shapes.shape_id
.all({ day })
const featureCollections = trips.map(({ trip_id }) =>
getShapesAsGeoJSON({ trip_id })
)
return res.json(joinFeatureCollections(featureCollections))
const shapesGeojson = getShapesAsGeoJSON({
route_id: req.params.routeId,
})
res.json(shapesGeojson)
closeDb(db)
} catch (error) {
console.error(error)
}
})
app.get('/geojson/shape/:shapeId', (req, res) => {
try {
const { shapeId } = req.params
const db = openDb(config)
const result = getShapesAsGeoJSON({ shape_id: shapeId })
res.json(result)
closeDb(db)
} catch (error) {
console.error(error)
}
})
app.get('/geoStops/:lat/:lon/:distance', (req, res) => {
try {
const db = openDb(config)
const { lat, lon, distance } = req.params
console.log('Will query stops for lat ', lat, ' and lon ', lon)
const results = getStops(
{
stop_lat: lat,
stop_lon: lon,
},
[],
[],
{ bounding_box_side_m: distance }
)
res.json(results)
closeDb(db)
} catch (error) {
console.error(error)
}
})
/* Update the DB from the local GTFS files */
app.get('/parse', async (req, res) => {
const alors = await parseGTFS(dateHourMinutes())
res.send(alors)
})
app.get('/update', async (req, res) => {
try {
const oldDb = openDb(config)
const { stdout, stderr } = await exec('yarn build-config')
console.log('-------------------------------')
console.log('Build config OK')
console.log('stdout:', stdout)
console.log('stderr:', stderr)
const newDbName = dateHourMinutes()
cache.set('dbName', newDbName)
await parseGTFS(newDbName)
console.log('-------------------------------')
console.log(`Parsed GTFS in new node-gtfs DB ${newDbName} OK`)
console.log(
'Will build agency areas, long not optimized step for now, ~ 30 minutes for SNCF + STAR + TAN'
)
closeDb(oldDb)
const db = openDb(config)
buildAgencyAreas(db, cache, runtimeCache)
apicache.clear()
const { stdout4, stderr4 } = await exec(
`find db/ ! -name '${newDbName}' -type f -exec rm -f {} +`
)
console.log('-------------------------------')
console.log('Removed older dbs')
console.log('stdout:', stdout4)
console.log('stderr:', stderr4)
const { stdout2, stderr2 } = await exec('systemctl restart motis.service')
console.log('-------------------------------')
console.log('Restart Motis OK')
console.log('stdout:', stdout2)
console.log('stderr:', stderr2)
closeDb(db)
console.log('Done updating 😀')
res.send({ ok: true })
} catch (e) {
console.log(
"Couldn't update the GTFS server, or the Motis service. Please investigate.",
e
)
res.send({ ok: false })
}
})
app.listen(port, () => {
console.log(`Cartes.app GTFS server listening on port ${port}`)
})