From 6e55e01baab0f929bce7aed438b0a8c74188b62d Mon Sep 17 00:00:00 2001 From: lonkaars Date: Tue, 22 Nov 2022 12:14:35 +0100 Subject: working --- .gitignore | 1 - config | 3 +++ config.def.json | 0 trein.py | 48 ++++++++++++++++++++++++++++++++++++++++++++---- 4 files changed, 47 insertions(+), 5 deletions(-) create mode 100644 config delete mode 100644 config.def.json diff --git a/.gitignore b/.gitignore index a9284fa..06bfde4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1 @@ key -config.json diff --git a/config b/config new file mode 100644 index 0000000..25529df --- /dev/null +++ b/config @@ -0,0 +1,3 @@ +'s-Hertogenbosch +Oss +Nijmegen diff --git a/config.def.json b/config.def.json deleted file mode 100644 index e69de29..0000000 diff --git a/trein.py b/trein.py index 2f09938..9afad6d 100755 --- a/trein.py +++ b/trein.py @@ -1,8 +1,18 @@ #!/bin/python3 -import http.client, urllib.request, urllib.parse, urllib.error, base64 +import http.client +import urllib.request +import urllib.parse +import urllib.error +import json +import dateutil.parser +from icalendar import Calendar, Event + +cal = Calendar() +cal.add('prodid', 'trein') +cal.add('version', '2.0') def read_file(filename): - f = open(filename) + f = open(filename, "r") r = str(f.read()) f.close() return r @@ -22,7 +32,37 @@ def real_disruptions(): return data def get_disruptions(): - return fake_disruptions() + return real_disruptions() + +def disruption2ical(disruption): + ev = Event() + ev['uid'] = disruption['id'] + ev.add('name', f"{disruption['timespans'][0]['cause']['label']} {disruption['title']}") + description = disruption['expectedDuration']['description'] + "\n\n" + for timespan in disruption['timespans']: + description += timespan['situation']['label'] + "\n\n" + description += timespan['alternativeTransport']['label'] + "\n\n" + ev.add('description', description) + ev.add('dtstart', dateutil.parser.parse(disruption['start'])) + ev.add('dtend', dateutil.parser.parse(disruption['end'])) + cal.add_component(ev) + +def main(): + disruptions = json.loads(get_disruptions()) + relevant_stations = read_file("./config").strip().split("\n") + + for disruption in disruptions: + relevant = False + for section in disruption['publicationSections']: + consequence_stations = list(map(lambda x: x['name'], section['consequence']['section']['stations'])) + for i in range(len(relevant_stations)): + if relevant_stations[(i + 0) % len(relevant_stations)] in consequence_stations and \ + relevant_stations[(i + 1) % len(relevant_stations)] in consequence_stations: + relevant = True # only relevant if consequence contains current and next station + if relevant: disruption2ical(disruption) + + print(cal.to_ical()) if __name__ == "__main__": - print(get_disruptions()) + main() + -- cgit v1.2.3