Added server implementation

This commit is contained in:
Filip Znachor 2022-11-15 16:09:38 +01:00
commit 0c01e24e15

97
server/departures.py Normal file
View file

@ -0,0 +1,97 @@
from requests.structures import CaseInsensitiveDict
import json
import requests
from time import sleep
from dateutil import parser
from datetime import datetime
class Departure:
storage = dict()
@staticmethod
def clear():
remove = []
for did in Departure.storage:
d = Departure.storage[did]
if -(datetime.now().timestamp() - (d.departure + d.delay*60))/60 <= -1:
remove.append(did)
for did in remove:
Departure.storage.pop(did)
@staticmethod
def fetch(stop_id, limit):
url = "https://jizdnirady.pmdp.cz/odjezdy/vyhledat"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
data = {
"Stop": {
"StopId": stop_id
},
"DateAndTime": None,
"MaxResults": limit,
"FullResults": False
}
resp = requests.post(url, headers=headers, data=json.dumps(data), timeout=100).json()
for c in resp:
did = f"{stop_id}|{abs(c['ConnectionId']['ConnectionId'])}"
if did not in Departure.storage:
Departure(
did,
c["Line"]["Name"],
c["LastStopName"],
c["DepartureTime"],
c["DelayMin"]
)
else:
Departure.storage[did].update(
c["DelayMin"]
)
def __init__(self, id, line, last_stop, departure, delay):
Departure.storage[id] = self
self.id = id
self.line = line
self.last_stop = last_stop
self.departure = (parser.parse(departure)).timestamp()
self.update(delay)
def update(self, delay):
if not delay:
delay = 0
self.delay = delay
def __repr__(self):
departure = -round((datetime.now().timestamp() - (self.departure + self.delay*60))/60)
return f"{self.id:<15} {self.line:<2} {self.last_stop:<30} {departure if departure > 0 else '<1':>3}"
refetch = 0
while True:
print("")
for did in Departure.storage:
print(Departure.storage[did])
sleep(1)
if refetch == 0:
Departure.fetch("40", 5)
refetch = (refetch + 1) % 10
sleep(1)
Departure.clear()
sleep(1)
# {'ConnectionId': {'ConnectionId': -302285, 'InTraffic': True, 'BoardingStopIndex': None, 'GettingOffStopIndex': None}, 'Line': {'Name': '30', 'Number': 445030, 'TractionType': 3, 'IsBarrierFree': True, 'IsNightConnection': False}, 'DepartureTime': '2022-11-14T21:55:00+01:00', 'LastStopName': 'Sídliště Košutka', 'DelayMin': 0, 'LeavingInMin': 0, 'Stops': None, 'QuickMessageIds': []}