-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransport.py
399 lines (320 loc) · 14.4 KB
/
transport.py
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
import requests
import sys
import numpy as mp
import datetime
import datetime
from config import *
def gettripinfos(tripId: str) -> dict:
url = f'{instance}/trips/{tripId}'
try: dat = requests.get(url).json()
except:
print("wrong tripid or something")
return
if len(dat) > 0: return dat
class Location:
def __init__(self, lat, lon):
self.lat = lat
self.lon = lon
if self.lat == None or self.lon == None: return
self.osmlink = self.getLink()
def getLink(self, marker=True) -> str:
link = "https://www.openstreetmap.org/"
if marker is True: link += f"?mlat={self.lat}"
if marker is True: link += f"&mlon={self.lon}"
link += f"#map=17/{self.lat}/{self.lon}"
return link
class Trip:
def __init__(self, tripId: str = None , fetchData = True, loadedStation = None, tripData: dict = None, dataType: str = None):
self.dataType = dataType
self.tripId = tripId
if self.tripId == None:
self.tripId = tripData['tripId']
if self.tripId == None:
print("NO TRIPID")
return
if '|' not in self.tripId: raise Exception
if fetchData == False: dat = tripData
else:
url = f'{instance}/trips/{tripId}'
try: dat = requests.get(url).json()['trip']
except:
print("wrong tripid or something")
return
if len(dat) < 1: raise Exception
self.tripData = dat
try:
self.originName = dat['origin']['name']
self.origin = Stop(dat['origin'])
except:
self.originName = None
self.originObject = None
try:
self.lineName = dat['line']['name']
self.line = Line(dat['line'])
except: pass
# Ziel und Zieltext
try:
self.destinationName = dat['destination']['name']
except:
try: self.destinationName = dat['direction']
except: self.destinationName = "error"
if self.dataType == "arrival" and loadedStation != None:
# Falls es sich bei den eingegebenen Daten um Daten aus /stop/:id/arrivals
# handelt, so setze den destinationName auf den zurzeit im Programm geladenen
# Halt (loadedStation)
self.destination = loadedStation
self.destinationName = loadedStation.name
try:
self.destination = Stop(dat['destination']['id'], False, dat['destination'])
except: pass
if self.dataType == "arrival" or self.dataType == "departure":
try: self.DOText = dat['origin']
except: self.DOText = dat['provenance']
try:
if dat['when']: self.when = dat['when']
else: self.when = dat['plannedWhen']
if dat['when']: self.plannedWhen = dat['when']
else: self.plannedWhen = dat['plannedWhen']
try:
if dat['platform']: self.platform = dat['platform']
else: self.platform = dat['plannedPlatform']
if dat['plannedPlatform']: self.plannedPlatform = dat['plannedPlatform']
else: self.plannedPlatform = dat['platform']
except: pass
except: pass
else:
try: self.DOText = dat['stopovers'][0]['stop']['name']
except: self.DOText = "Error."
try:self.departureTime = datetime.datetime.fromisoformat(dat['when'])
except:
try: self.departureTime = datetime.datetime.fromisoformat(dat['plannedWhen'])
except: self.departureTime = None
try: self.departureString = self.departureTime.strftime(humantimeformat)
except: self.departureString = None
try:
self.stopoverStops = []
for i in range(len(dat['stopovers'])):
currentStop = Stop(dat['stopovers'][i]['stop']['id'], False)
self.stopoverStops.insert(i, currentStop)
except: pass
try:
self.departureDelay = int(dat['departureDelay']) / 60
self.arrivalDelay = int(dat['arrivalDelay']) / 60
self.delayData: bool = True
except:
try:
self.delay = int(dat['delay']) / 60
self.delayData: bool = True
except:
self.delayData: bool = False
try: self.delay = int(dat['departureDelay']) / 60
except: self.delay = 0
# currentTripPosition
try:
self.currentPosition = Location(dat['currentLocation']['latitude'], dat['currentLocation']['longitude'])
except: self.currentPosition = None
# Falls gegeben, überprüfe, ob die Fahrt am gegebenen, im Programm geladenen
# Bahnhof endet, das heißt eine Ankunft besteht
try:
if type(loadedStation) == Stop and str(loadedStation.id) == str(self.destination.id):
self.isArrival = True
elif type(loadedStation) == Stop and loadedStation.name != self.destination.name:
self.isArrival = False
else:
self.isArrival = None
except: pass
def getOrigin(self):
url = f'{instance}/trips/{self.tripId}'
try:
self.tripData = requests.get(url).json()['trip']
except:
print("wrong tripid or something")
return
self.origin = Stop(None, False, self.tripData['origin'])
def getVia(self, startStopId: str):
if self.stopoverStops is None or self.stopoverStops == []:
self.getStopovers()
# Zu prüfende Stops
tstops = []
a = False
if len(self.stopoverStops) == 0: return []
for i in self.stopoverStops:
if a: tstops.append(i)
if i.stop.id == startStopId:
a = True
viastops = []
for i, e in enumerate(tstops):
viastops.insert(i, Station(e.stop.id, True))
highestCategory = 12
bestStations: Station = None
for i in viastops:
if i.category is None: continue
if i.category < highestCategory and i.id != self.destination.id:
highestCategory = i.category
bestStations = i
return bestStations
def getStopovers(self):
url = f'{instance}/trips/{self.tripId}'
try:
dat = requests.get(url).json()['trip']
for i in dat['stopovers']:
self.stopoverStops.append(TripStop(i))
except:
print(f"error while fetching stopovers for trip {self.tripId}")
return
def getStopData(self, stopId: str) -> dict:
inMyStopovers = False
for i in self.tripData['stopovers']: # da unten auch anpassen! die stopover-Informationen müssen aus dem tripdata['stopovers'] bezogen werden
if str(stopId) == str(i['stop']['id']):
inMyStopovers = True
return TripStop(i)
# ^^^^^^^^^^
# Durchsuche die self.stopoverStops-Liste nach dem Stop, der dem für die Funktion
# angegegebenen Stop entspricht
return("error")
class Line:
def __init__(self, lineData: dict = None):
# in the transport.rest-api, there's no extra support for lines (yet?,
# the hafas-client supports it). The only way to get the data is through
# the "stops" requests followed by the "linesOfStop" parameter set to true.
# Because of that, there's no option to fetch the data inside this function.
self.lineData = lineData
try:
self.id = self.lineData['id']
self.name = self.lineData['name']
self.productName = self.lineData['productName']
self.productType = self.lineData['product']
self.number = ""
for char in reversed(self.name):
if char.isdigit():
self.number = char + self.number
else:
if self.number:
break
self.shortName = self.getShortName()
except:
print(f"Error: Line {self.id} seems to have corrupt data")
return
def getShortName(self) -> str:
# TODO: Mehr Sonderfälle für andere Zuggattungen
if self.name.startswith("BRB"): return self.name.split(' ')[1]
elif self.name.startswith("ICE"): return "ICE"
else: return self.name.replace(' ', '')
class Station:
def __init__(self, id: str = None, fetchData = True, data = None):
if id is None:
try:
self.id = data['id']
except: return
if data != None:
self.stationData = data
elif fetchData == False: return
if fetchData == True:
url = f'{instance}/stations/{id}/?language=de'
self.stationData = requests.get(url).json()
try:
d = self.stationData['name']
except:
# Fallback für ausländische Stations
url = f'{instance}/stops/{id}/?language=de'
self.stationData = requests.get(url).json()
self.name = self.stationData['name']
self.id = self.stationData['id']
self.locationDat = self.stationData['location']
self.latitude = self.locationDat['latitude']
self.longitude = self.locationDat['longitude']
self.hasTripData: bool = False
try:
try: self.category = self.stationData['category']
except: self.category = self.stationData['priceCategory']
except: self.category = None
class Stop:
def __init__(self, stopId: str = None, fetchData = True, data = None, fetchLineData: bool = False):
if stopId == None:
try:
self.stopId = data['id']
except: return
if data != None:
self.stopData = data
elif fetchData == False: return
if fetchData == True:
url = f'{instance}/stations/{stopId}/?language=de'
if fetchLineData == True: url += "&linesOfStops=true"
self.stopData = requests.get(url).json()
self.name = self.stopData['name']
self.id = self.stopData['id']
self.locationDat = self.stopData['location']
self.latitude = self.locationDat['latitude']
self.longitude = self.locationDat['longitude']
self.hasTripData: bool = False
try:
try: self.category = self.stopData['category']
except: self.category = self.stopData['priceCategory']
except: self.category = None
# If given, save the lines
self.lines = []
if fetchLineData == True:
try:
for i in self.stopData['lines']:
self.lines.append(Line(i))
except: pass
else: pass
fetchedStops.append(self)
def getTrips(self):
departures = requests.get(f"{instance}/stops/{self.id}/departures{params}").json()
arrivals = requests.get(f"{instance}/stops/{self.id}/arrivals{params}").json()
trips = []
for i in departures['departures']:
doubled = False
for y in trips:
if i['tripId'] == y.tripId: doubled = True
if not doubled: trips.append(Trip(None, False, self, i, 'departure'))
for i in arrivals['arrivals']:
doubled = False
for y in trips:
if i['tripId'] == y.tripId: doubled = True
if not doubled: trips.append(Trip(None, False, self, i, 'arrival'))
self.trips = sorted(trips, key=lambda x: x.departureString)
def getDepartures(self):
apidata = requests.get(f"{instance}/stops/{self.id}/departures{params}").json()
departures = []
for i in apidata['departures']:
departures.append(Trip(None, False, self, i, 'departure'))
self.departures = departures
class TripStop:
def __init__(self, tripStopData):
self.dat = tripStopData
self.stop = Stop(self.dat['stop']['id'], False, self.dat['stop'])
self.arrival = None
self.departure = None
try:
try: self.arrival = datetime.datetime.fromisoformat(str(self.dat['arrival'])).strftime(humantimeformat)
except: self.arrival = datetime.datetime.fromisoformat(str(self.dat['plannedArival'])).strftime(humantimeformat)
except: pass
try:
try: self.departure = datetime.datetime.fromisoformat(str(self.dat['departure'])).strftime(humantimeformat)
except: self.departure = datetime.datetime.fromisoformat(str(self.dat['plannedDeparture'])).strftime(humantimeformat)
except: pass
# AnkunftsGleis
try: self.arrivalPlatform = self.dat['arrivalPlatform']
except: self.arrivalPlatform = self.dat['plannedArrivalPlatform']
if self.dat['arrivalPlatform'] != None and self.dat['arrivalPlatform'] != self.dat['plannedArrivalPlatform']:
# Falls anderes Gleis als geplant:
self.arrivalPlatformText = f"""<p><s>{self.dat['plannedArrivalPlatform']}</s> <span style="color:#c0392b"><strong>{self.dat['arrivalPlatform']}</strong></span></p>"""
else: self.arrivalPlatformText = f'{self.arrivalPlatform}'
# AbfahrtsGleis
try: self.departurePlatform = self.dat['departurePlatform']
except: self.departurePlatform = self.dat['plannedDeparturePlatform']
if self.dat['departurePlatform'] != None and self.dat['departurePlatform'] != self.dat['plannedDeparturePlatform']:
# Falls anderes Gleis als geplant:
self.departurePlatformText = f"""<p><s>{self.dat['plannedDeparturePlatform']}</s> <span style="color:#c0392b"><strong>{self.dat['departurePlatform']}</strong></span></p>"""
else: self.departurePlatformText = f'{self.departurePlatform}'
fetchedStops = []
def getFetchedStop(stopId) -> Stop:
success = False
while not success:
for i in fetchedStops:
if str(stopId) == str(i.id):
success = True
return i
return None