-
Notifications
You must be signed in to change notification settings - Fork 90
/
gtfsService.ts
170 lines (151 loc) · 5.03 KB
/
gtfsService.ts
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
import axios from 'axios'
import {
GtfsApi,
GtfsRideStopPydanticModel,
GtfsRideWithRelatedPydanticModel,
} from 'open-bus-stride-client'
import moment, { Moment } from 'moment'
import { BusRoute, fromGtfsRoute } from 'src/model/busRoute'
import { BusStop, fromGtfsStop } from 'src/model/busStop'
import { API_CONFIG, MAX_HITS_COUNT, BASE_PATH } from 'src/api/apiConfig'
// import { Route } from 'react-router'
const GTFS_API = new GtfsApi(API_CONFIG)
//const USER_CASES_API = new UserCasesApi(API_CONFIG)
const JOIN_SEPARATOR = ','
const SEARCH_MARGIN_HOURS = 4
type StopHitsPayLoadType = {
gtfsRideIds: string
gtfsStopIds: string
arrival_time_to: number
arrival_time_from: number
}
export async function getRoutesAsync(
fromTimestamp: moment.Moment,
toTimestamp: moment.Moment,
operatorId: string | undefined,
lineNumber: string | undefined,
signal?: AbortSignal | undefined,
): Promise<BusRoute[]> {
const gtfsRoutes = await GTFS_API.gtfsRoutesListGet(
{
routeShortName: lineNumber,
operatorRefs: operatorId,
dateFrom: fromTimestamp.startOf('day').toDate(),
dateTo: moment.min(toTimestamp.endOf('day'), moment()).toDate(),
limit: 100,
},
{ signal },
)
const routes = Object.values(
gtfsRoutes
.filter(
(route) =>
route.date.getDate() >= fromTimestamp.date() &&
route.date.getDate() <= toTimestamp.date(),
)
.map((route) => fromGtfsRoute(route))
.reduce(
(agg, line) => {
const groupByKey = line.key
const prevLine = agg[groupByKey] || { routeIds: [] }
agg[groupByKey] = {
...line,
...prevLine,
routeIds: [...prevLine.routeIds, ...line.routeIds],
}
return agg
},
{} as Record<string, BusRoute>,
),
)
return routes
}
export async function getStopsForRouteAsync(
routeIds: number[],
timestamp: Moment,
): Promise<BusStop[]> {
const stops: BusStop[] = []
for (const routeId of routeIds) {
const rides = await GTFS_API.gtfsRidesListGet({
gtfsRouteId: routeId,
startTimeFrom: moment(timestamp).subtract(1, 'days').second(0).milliseconds(0).toDate(),
startTimeTo: moment(timestamp).add(1, 'days').second(0).milliseconds(0).toDate(),
limit: 1,
orderBy: 'start_time',
})
if (rides.length === 0) {
continue
}
const rideRepresentative = rides[0]
const rideStops = await GTFS_API.gtfsRideStopsListGet({
gtfsRideIds: rideRepresentative.id!.toString(),
})
await Promise.all(
rideStops.map(async (rideStop) => {
const stop = await GTFS_API.gtfsStopsGetGet({ id: rideStop.gtfsStopId })
stops.push(fromGtfsStop(rideStop, stop, rideRepresentative))
}),
)
}
return stops.sort((a, b) =>
a.stopSequence === b.stopSequence
? a.name.localeCompare(b.name)
: a.stopSequence - b.stopSequence,
)
}
export async function getGtfsStopHitTimesAsync(stop: BusStop, timestamp: Moment) {
const targetStartTime = moment(timestamp).subtract(stop.minutesFromRouteStartTime, 'minutes')
const rides = await GTFS_API.gtfsRidesListGet({
gtfsRouteId: stop.routeId,
startTimeFrom: moment(targetStartTime)
.subtract(SEARCH_MARGIN_HOURS, 'hours')
.second(0)
.milliseconds(0)
.toDate(),
startTimeTo: moment(targetStartTime)
.add(SEARCH_MARGIN_HOURS, 'hours')
.second(0)
.milliseconds(0)
.toDate(),
limit: 1024,
orderBy: 'start_time asc',
})
if (rides.length === 0) {
return []
}
const diffFromTargetStart = (ride: GtfsRideWithRelatedPydanticModel): number =>
Math.abs(timestamp.diff(ride.startTime, 'seconds'))
const closestInTimeRides = rides
.sort((a, b) => diffFromTargetStart(a) - diffFromTargetStart(b))
.slice(0, MAX_HITS_COUNT)
const rideIds = closestInTimeRides.map((ride) => ride.id).join(JOIN_SEPARATOR)
const minStartTime = Math.min(...rides.map((ride) => Number(ride.startTime)))
const maxEndTime = Math.max(...rides.map((ride) => Number(ride.endTime)))
/* Fix StopHits bugs next steps TODO:
1. Add a test to ensure this feature is working correctly.
2. Optimize the axios request to minimize latency. - Currently takes forever.
3. Fix any on this- define the hit type
*/
try {
const stopHitsRequestPayLoad: StopHitsPayLoadType = {
gtfsRideIds: rideIds,
gtfsStopIds: stop.stopId.toString(),
arrival_time_from: minStartTime,
arrival_time_to: maxEndTime,
}
const stopHitsRes = await axios.get(`${BASE_PATH}/gtfs_ride_stops/list`, {
params: stopHitsRequestPayLoad,
})
if (stopHitsRes.status !== 200) {
throw new Error(`Error fetching stop hits: ${stopHitsRes.statusText}`)
}
if (stopHitsRes.data.length === 0) {
throw new Error(`No stop hits found`)
}
const stopHits: GtfsRideStopPydanticModel[] = stopHitsRes.data
return stopHits.sort((hit1, hit2) => +hit1.arrivalTime! - +hit2.arrivalTime!)
} catch (error) {
console.error(`Error fetching stop hits:`, error)
return []
}
}