From 6a8a614b3dc53fb51ce44989e9d39a0cc1738c99 Mon Sep 17 00:00:00 2001 From: Kumi Date: Tue, 19 Apr 2022 15:01:03 +0200 Subject: [PATCH] autopep8 everything - how could I ever work like this? --- classes/connection.py | 283 ++++++++++++++++++---------------- classes/httpclient.py | 9 +- classes/request.py | 85 ++++++----- classes/response.py | 8 +- classes/service.py | 184 ++++++++++++---------- classes/station.py | 123 ++++++++------- classes/train.py | 100 ++++++------ main.py | 339 +++++++++++++++++++++-------------------- workers/closest.py | 88 ++++++----- workers/conn.py | 344 +++++++++++++++++++++++------------------- workers/deparr.py | 147 +++++++++--------- workers/radar.py | 53 ++++--- workers/val.py | 49 +++--- 13 files changed, 983 insertions(+), 829 deletions(-) diff --git a/classes/connection.py b/classes/connection.py index c7254d5..a2e64f1 100644 --- a/classes/connection.py +++ b/classes/connection.py @@ -1,177 +1,202 @@ import datetime + class Connection: - def __init__(self, details = False): - self.services = [] - self.details = details - self.via = [] + def __init__(self, details=False): + self.services = [] + self.details = details + self.via = [] - def addService(self, service): - self.services.append(service) + def addService(self, service): + self.services.append(service) - def addVia(self, station): - self.via.append(station) + def addVia(self, station): + self.via.append(station) - def depst(self): - try: - return self.services[0].depst - except: - return None + def depst(self): + try: + return self.services[0].depst + except: + return None - def arrst(self): - try: - return self.services[-1].arrst - except: - return None + def arrst(self): + try: + return self.services[-1].arrst + except: + return None - def deptime(self): - try: - return self.services[0].deptime - except: - return None + def deptime(self): + try: + return self.services[0].deptime + except: + return None - def arrtime(self): - try: - return self.services[-1].arrtime - except: - return None + def arrtime(self): + try: + return self.services[-1].arrtime + except: + return None - def currdep(self): - try: - return self.services[0].currdep - except: - return None + def currdep(self): + try: + return self.services[0].currdep + except: + return None - def currarr(self): - try: - return self.services[-1].currarr - except: - return None + def currarr(self): + try: + return self.services[-1].currarr + except: + return None - def duration(self): - try: - return self.services[-1].arrtime - self.services[0].deptime - except: - return None + def duration(self): + try: + return self.services[-1].arrtime - self.services[0].deptime + except: + return None - def durationString(self): - hrs, scs = divmod(self.duration().total_seconds(), 3600) - mns, rmd = divmod(scs, 60) + def durationString(self): + hrs, scs = divmod(self.duration().total_seconds(), 3600) + mns, rmd = divmod(scs, 60) - return "%i:%s" % (hrs, str(int(mns)).zfill(2)) + return "%i:%s" % (hrs, str(int(mns)).zfill(2)) - def changes(self): - return max(len([service for service in self.services if service.name != "Walk"]) - 1, 0) if self.details else max(len([service for service in self.services[0].name.split("/") if service != "Walk"]) - 1, 0) + def changes(self): + return max(len([service for service in self.services if service.name != "Walk"]) - 1, 0) if self.details else max(len([service for service in self.services[0].name.split("/") if service != "Walk"]) - 1, 0) - def xml(self, indent = 0, cid = False, frm = True, to = True, deptime = True, arrtime = True, duration = True, changes = True, services = True, via = True, servicekwargs = {}, stationkwargs = {}): - out = " " * indent + "\n" % ("" if cid is False else " id=\"%i\"" % cid) + def xml(self, indent=0, cid=False, frm=True, to=True, deptime=True, arrtime=True, duration=True, changes=True, services=True, via=True, servicekwargs={}, stationkwargs={}): + out = " " * indent + \ + "\n" % ("" if cid is False else " id=\"%i\"" % cid) - if frm and self.depst(): - out += " " * indent + " \n" - out += self.depst().xml(indent + 2, **stationkwargs) + "\n" - out += " " * indent + " \n" + if frm and self.depst(): + out += " " * indent + " \n" + out += self.depst().xml(indent + 2, **stationkwargs) + "\n" + out += " " * indent + " \n" - if via and self.via: - out += " " * indent + " \n" - - for vst in self.via: - out += vst.xml(indent + 2, **stationkwargs) + "\n" + if via and self.via: + out += " " * indent + " \n" - out += " " * indent + " \n" + for vst in self.via: + out += vst.xml(indent + 2, **stationkwargs) + "\n" - if to and self.arrst(): - out += " " * indent + " \n" - out += self.arrst().xml(indent + 2, **stationkwargs) + "\n" - out += " " * indent + " \n" + out += " " * indent + " \n" - if (deptime and self.deptime()) or (arrtime and self.arrtime()) or (duration and self.duration()) or (changes and self.changes()): - out += " " * indent + "
\n" + if to and self.arrst(): + out += " " * indent + " \n" + out += self.arrst().xml(indent + 2, **stationkwargs) + "\n" + out += " " * indent + " \n" - if deptime and self.deptime(): - out += " " * indent + " \n" - out += " " * indent + " %s\n" % datetime.datetime.strftime(self.deptime(), "%d.%m.%Y") - out += " " * indent + " \n" % datetime.datetime.strftime(self.deptime(), "%H:%M") - out += " " * indent + " \n" + if (deptime and self.deptime()) or (arrtime and self.arrtime()) or (duration and self.duration()) or (changes and self.changes()): + out += " " * indent + "
\n" - if arrtime and self.arrtime(): - out += " " * indent + " \n" - out += " " * indent + " %s\n" % datetime.datetime.strftime(self.arrtime(), "%d.%m.%Y") - out += " " * indent + " \n" % datetime.datetime.strftime(self.arrtime(), "%H:%M") - out += " " * indent + " \n" + if deptime and self.deptime(): + out += " " * indent + " \n" + out += " " * indent + \ + " %s\n" % datetime.datetime.strftime( + self.deptime(), "%d.%m.%Y") + out += " " * indent + \ + " \n" % datetime.datetime.strftime( + self.deptime(), "%H:%M") + out += " " * indent + " \n" - out += (" " * indent + " %s\n" % self.durationString()) if duration and self.duration() else "" - out += (" " * indent + " %i\n" % self.changes()) if changes and self.changes() else "" + if arrtime and self.arrtime(): + out += " " * indent + " \n" + out += " " * indent + \ + " %s\n" % datetime.datetime.strftime( + self.arrtime(), "%d.%m.%Y") + out += " " * indent + \ + " \n" % datetime.datetime.strftime( + self.arrtime(), "%H:%M") + out += " " * indent + " \n" - out += " " * indent + "
\n" + out += (" " * indent + " %s\n" % + self.durationString()) if duration and self.duration() else "" + out += (" " * indent + " %i\n" % + self.changes()) if changes and self.changes() else "" - if services and self.services: - out += " " * indent + " \n" + out += " " * indent + "
\n" - for i in range(len(self.services)): - out += self.services[i].xml(indent + 2, i, **servicekwargs) + "\n" + if services and self.services: + out += " " * indent + " \n" - out += " " * indent + " \n" - - out += " " * indent + "" + for i in range(len(self.services)): + out += self.services[i].xml(indent + 2, + i, **servicekwargs) + "\n" - return out + out += " " * indent + " \n" - def json(self, indent = 0, cid = False, frm = True, to = True, deptime = True, arrtime = True, duration = True, changes = True, services = True, via = True, servicekwargs = {}, stationkwargs = {}): - out = " " * indent + "{\n" + out += " " * indent + "" - out += (" " * indent + " \"@id\": %i,\n" % cid) if cid is not False else "" + return out - if frm and self.depst(): - out += " " * indent + " \"from\":\n" - out += self.depst().json(indent + 2, **stationkwargs) + ",\n" + def json(self, indent=0, cid=False, frm=True, to=True, deptime=True, arrtime=True, duration=True, changes=True, services=True, via=True, servicekwargs={}, stationkwargs={}): + out = " " * indent + "{\n" - if via and self.via: - out += " " * indent + " \"via\": [\n" + out += (" " * indent + " \"@id\": %i,\n" % + cid) if cid is not False else "" - for vst in self.via: - out += vst.json(indent + 3, **stationkwargs) + ",\n" + if frm and self.depst(): + out += " " * indent + " \"from\":\n" + out += self.depst().json(indent + 2, **stationkwargs) + ",\n" - out = "".join(out.rsplit(",", 1)) - out += " " * indent + " ],\n" + if via and self.via: + out += " " * indent + " \"via\": [\n" - if to and self.arrst(): - out += " " * indent + " \"to\":\n" - out += self.arrst().json(indent + 2, **stationkwargs) + ",\n" + for vst in self.via: + out += vst.json(indent + 3, **stationkwargs) + ",\n" - if (deptime and self.deptime()) or (arrtime and self.arrtime()) or (duration and self.duration()) or (changes and self.changes()): - det = "" - det += " " * indent + " \"details\": {\n" + out = "".join(out.rsplit(",", 1)) + out += " " * indent + " ],\n" - if deptime and self.deptime(): - det += " " * indent + " \"departure\": {\n" - det += " " * indent + " \"date\": \"%s\",\n" % datetime.datetime.strftime(self.deptime(), "%d.%m.%Y") - det += " " * indent + " \"time\": \"%s\"\n" % datetime.datetime.strftime(self.deptime(), "%H:%M") - det += " " * indent + " },\n" + if to and self.arrst(): + out += " " * indent + " \"to\":\n" + out += self.arrst().json(indent + 2, **stationkwargs) + ",\n" - if arrtime and self.arrtime(): - det += " " * indent + " \"arrival\": {\n" - det += " " * indent + " \"date\": \"%s\",\n" % datetime.datetime.strftime(self.arrtime(), "%d.%m.%Y") - det += " " * indent + " \"time\": \"%s\"\n"% datetime.datetime.strftime(self.arrtime(), "%H:%M") - det += " " * indent + " },\n" + if (deptime and self.deptime()) or (arrtime and self.arrtime()) or (duration and self.duration()) or (changes and self.changes()): + det = "" + det += " " * indent + " \"details\": {\n" - det += (" " * indent + " \"duration\": \"%s\",\n" % self.durationString()) if duration and self.duration() else "" - det += (" " * indent + " \"changes\": %i,\n" % self.changes()) if changes and self.changes() else "" + if deptime and self.deptime(): + det += " " * indent + " \"departure\": {\n" + det += " " * indent + \ + " \"date\": \"%s\",\n" % datetime.datetime.strftime( + self.deptime(), "%d.%m.%Y") + det += " " * indent + \ + " \"time\": \"%s\"\n" % datetime.datetime.strftime( + self.deptime(), "%H:%M") + det += " " * indent + " },\n" - det = "".join(det.rsplit(",", 1)) - out += det + if arrtime and self.arrtime(): + det += " " * indent + " \"arrival\": {\n" + det += " " * indent + \ + " \"date\": \"%s\",\n" % datetime.datetime.strftime( + self.arrtime(), "%d.%m.%Y") + det += " " * indent + \ + " \"time\": \"%s\"\n" % datetime.datetime.strftime( + self.arrtime(), "%H:%M") + det += " " * indent + " },\n" - out += " " * indent + " },\n" + det += (" " * indent + " \"duration\": \"%s\",\n" % + self.durationString()) if duration and self.duration() else "" + det += (" " * indent + " \"changes\": %i,\n" % + self.changes()) if changes and self.changes() else "" - if services and self.services: - out += " " * indent + " \"services\": [\n" + det = "".join(det.rsplit(",", 1)) + out += det - for i in range(len(self.services)): - out += self.services[i].json(indent + 2, i, **servicekwargs) + (",\n" if not i == len(self.services) - 1 else "\n") + out += " " * indent + " },\n" - out += " " * indent + " ],\n" + if services and self.services: + out += " " * indent + " \"services\": [\n" - out += " " * indent + "}" + for i in range(len(self.services)): + out += self.services[i].json(indent + 2, i, **servicekwargs) + ( + ",\n" if not i == len(self.services) - 1 else "\n") - out = "".join(out.rsplit(",", 1)) + out += " " * indent + " ],\n" - return out + out += " " * indent + "}" + + out = "".join(out.rsplit(",", 1)) + + return out diff --git a/classes/httpclient.py b/classes/httpclient.py index 4fc3397..6348697 100644 --- a/classes/httpclient.py +++ b/classes/httpclient.py @@ -1,7 +1,8 @@ import requests -class HTTPClient(requests.Session): - def __init__(self, *args, **kwargs): - requests.Session.__init__(self, *args, **kwargs) - self.headers = {"User-Agent": "oebb_py/git (+https://kumig.it/kumitterer/oebb_py)"} +class HTTPClient(requests.Session): + def __init__(self, *args, **kwargs): + requests.Session.__init__(self, *args, **kwargs) + self.headers = { + "User-Agent": "oebb_py/git (+https://kumig.it/kumitterer/oebb_py)"} diff --git a/classes/request.py b/classes/request.py index 94332f9..511469f 100644 --- a/classes/request.py +++ b/classes/request.py @@ -1,57 +1,60 @@ try: - from urllib.parse import parse_qs + from urllib.parse import parse_qs except ImportError: - from cgi import parse_qs + from cgi import parse_qs + class IllegalMethodException(BaseException): - pass + pass + class InvalidArgumentException(BaseException): - pass + pass + class Request: - def __init__(self, env = None): - if env: - self.fromEnv(env) + def __init__(self, env=None): + if env: + self.fromEnv(env) - def fromEnv(self, env): - if env["REQUEST_METHOD"] == "POST": - self.args = parse_qs(env['wsgi.input'].readline().decode(), True) - elif env["REQUEST_METHOD"] == "GET": - self.args = parse_qs(env['QUERY_STRING'], True) - else: - raise IllegalMethodException() + def fromEnv(self, env): + if env["REQUEST_METHOD"] == "POST": + self.args = parse_qs(env['wsgi.input'].readline().decode(), True) + elif env["REQUEST_METHOD"] == "GET": + self.args = parse_qs(env['QUERY_STRING'], True) + else: + raise IllegalMethodException() - self.conn = False - self.val = False - self.cfrm = None - self.cto = None + self.conn = False + self.val = False + self.cfrm = None + self.cto = None - self.json = "json" in self.args + self.json = "json" in self.args - split = env["PATH_INFO"].split("/") - split = [i.strip() for i in split] + split = env["PATH_INFO"].split("/") + split = [i.strip() for i in split] - while "" in split: - split.remove("") + while "" in split: + split.remove("") - if len(split) > 2: - output = "

400 Bad Request

\n" - output += "Only one (validate) or two (conn) arguments may be passed as path." - raise InvalidArgumentException(output) + if len(split) > 2: + output = "

400 Bad Request

\n" + output += "Only one (validate) or two (conn) arguments may be passed as path." + raise InvalidArgumentException(output) - if len(split) > 0: - if len(split) == 1: - self.val = True - else: - self.conn = True - self.cto = split[1].encode("latin-1").decode("utf-8") - self.cfrm = split[0].encode("latin-1").decode("utf-8") - - try: - self.rtype = "conn" if self.conn else "val" if self.val else self.args["type"][0].lower() - except: - output = "

400 Bad Request

\n" - output += "A request type must be provided." - raise InvalidArgumentException(output) + if len(split) > 0: + if len(split) == 1: + self.val = True + else: + self.conn = True + self.cto = split[1].encode("latin-1").decode("utf-8") + self.cfrm = split[0].encode("latin-1").decode("utf-8") + try: + self.rtype = "conn" if self.conn else "val" if self.val else self.args["type"][0].lower( + ) + except: + output = "

400 Bad Request

\n" + output += "A request type must be provided." + raise InvalidArgumentException(output) diff --git a/classes/response.py b/classes/response.py index ff1a820..9d1ec78 100644 --- a/classes/response.py +++ b/classes/response.py @@ -1,5 +1,5 @@ class Response: - def __init__(self, status, ctype, content): - self.status = status - self.ctype = ctype - self.content = content + def __init__(self, status, ctype, content): + self.status = status + self.ctype = ctype + self.content = content diff --git a/classes/service.py b/classes/service.py index 4523e43..feb8c70 100644 --- a/classes/service.py +++ b/classes/service.py @@ -1,110 +1,140 @@ import datetime + class Service: - def __init__(self, name, depst, deptime, arrst, arrtime, dest = None, deppf = None, currdep = None, arrpf = None, curarr = None): - self.name = name - self.dest = dest - self.depst = depst - self.deptime = deptime - self.arrst = arrst - self.arrtime = arrtime - self.deppf = deppf - self.currdep = currdep - self.arrpf = arrpf - self.curarr = curarr + def __init__(self, name, depst, deptime, arrst, arrtime, dest=None, deppf=None, currdep=None, arrpf=None, curarr=None): + self.name = name + self.dest = dest + self.depst = depst + self.deptime = deptime + self.arrst = arrst + self.arrtime = arrtime + self.deppf = deppf + self.currdep = currdep + self.arrpf = arrpf + self.curarr = curarr - def duration(self): - return self.arrtime - self.deptime + def duration(self): + return self.arrtime - self.deptime - def xml(self, indent = 0, iid = False, name = True, depst = True, deptime = True, arrst = True, arrtime = True, deppf = True, currdep = True, arrpf = True, curarr = True, duration = True, dest = True, stationkwargs = {}): - out = " " * indent + "\n" % ("" if iid is False else " id=\"%i\"" % iid) + def xml(self, indent=0, iid=False, name=True, depst=True, deptime=True, arrst=True, arrtime=True, deppf=True, currdep=True, arrpf=True, curarr=True, duration=True, dest=True, stationkwargs={}): + out = " " * indent + \ + "\n" % ("" if iid is False else " id=\"%i\"" % iid) - out += (" " * indent + " %s\n" % self.name) if name else "" + out += (" " * indent + " %s\n" % + self.name) if name else "" - if dest and self.dest: - out += " " * indent + " \n" - out += self.dest.xml(indent + 2, **stationkwargs) + "\n" - out += " " * indent + " \n" + if dest and self.dest: + out += " " * indent + " \n" + out += self.dest.xml(indent + 2, **stationkwargs) + "\n" + out += " " * indent + " \n" - if depst or deptime or deppf or currdep: - out += " " * indent + " \n" + if depst or deptime or deppf or currdep: + out += " " * indent + " \n" - out += (self.depst.xml(indent + 2, **stationkwargs) + "\n") if depst else "" + out += (self.depst.xml(indent + 2, **stationkwargs) + + "\n") if depst else "" - if deptime: - out += " " * indent + " %s\n" % datetime.datetime.strftime(self.deptime, "%d.%m.%Y") - out += " " * indent + " \n" % datetime.datetime.strftime(self.deptime, "%H:%M") + if deptime: + out += " " * indent + \ + " %s\n" % datetime.datetime.strftime( + self.deptime, "%d.%m.%Y") + out += " " * indent + \ + " \n" % datetime.datetime.strftime( + self.deptime, "%H:%M") - out += (" " * indent + " %s\n" % self.currdep) if currdep and self.currdep else "" - out += (" " * indent + " %s\n" % self.deppf) if deppf and self.deppf else "" - - out += " " * indent + " \n" + out += (" " * indent + " %s\n" % + self.currdep) if currdep and self.currdep else "" + out += (" " * indent + " %s\n" % + self.deppf) if deppf and self.deppf else "" - if arrst or arrtime or arrpf or curarr: - out += " " * indent + " \n" + out += " " * indent + " \n" - out += (self.arrst.xml(indent + 2, **stationkwargs) + "\n") if arrst else "" + if arrst or arrtime or arrpf or curarr: + out += " " * indent + " \n" - if arrtime: - out += " " * indent + " %s\n" % datetime.datetime.strftime(self.arrtime, "%d.%m.%Y") - out += " " * indent + " \n" % datetime.datetime.strftime(self.arrtime, "%H:%M") + out += (self.arrst.xml(indent + 2, **stationkwargs) + + "\n") if arrst else "" - out += (" " * indent + " %s\n" % self.curarr) if curarr and self.curarr else "" - out += (" " * indent + " %s\n" % self.arrpf) if arrpf and self.arrpf else "" + if arrtime: + out += " " * indent + \ + " %s\n" % datetime.datetime.strftime( + self.arrtime, "%d.%m.%Y") + out += " " * indent + \ + " \n" % datetime.datetime.strftime( + self.arrtime, "%H:%M") - out += " " * indent + " \n" + out += (" " * indent + " %s\n" % + self.curarr) if curarr and self.curarr else "" + out += (" " * indent + " %s\n" % + self.arrpf) if arrpf and self.arrpf else "" - out += " " * indent + "" + out += " " * indent + " \n" - return out + out += " " * indent + "" - def json(self, indent = 0, iid = False, name = True, depst = True, deptime = True, arrst = True, arrtime = True, deppf = True, currdep = True, arrpf = True, curarr = True, duration = True, dest = True, stationkwargs = {}): - out = " " * indent + "{\n" + return out - out += (" " * indent + " \"@id\": %i,\n" % iid) if iid is not False else "" - out += (" " * indent + " \"name\": \"%s\",\n" % self.name) if name else "" + def json(self, indent=0, iid=False, name=True, depst=True, deptime=True, arrst=True, arrtime=True, deppf=True, currdep=True, arrpf=True, curarr=True, duration=True, dest=True, stationkwargs={}): + out = " " * indent + "{\n" - if dest and self.dest: - out += " " * indent + " \"destination\":\n" - out += self.dest.json(indent + 2, **stationkwargs) + ",\n" - - if depst or deptime or deppf or currdep: - dep = " " * indent + " \"departure\": {\n" + out += (" " * indent + " \"@id\": %i,\n" % + iid) if iid is not False else "" + out += (" " * indent + " \"name\": \"%s\",\n" % + self.name) if name else "" - if depst: - dep += " " * indent + " \"station\":\n" - dep += self.depst.json(indent + 3, **stationkwargs) + ",\n" + if dest and self.dest: + out += " " * indent + " \"destination\":\n" + out += self.dest.json(indent + 2, **stationkwargs) + ",\n" - if deptime: - dep += " " * indent + " \"date\": \"%s\",\n" % datetime.datetime.strftime(self.deptime, "%d.%m.%Y") - dep += " " * indent + " \"time\": \"%s\",\n" % datetime.datetime.strftime(self.deptime, "%H:%M") + if depst or deptime or deppf or currdep: + dep = " " * indent + " \"departure\": {\n" - dep += (" " * indent + " \"current\": \"%s\",\n" % self.currdep) if currdep and self.currdep else "" - dep += (" " * indent + " \"platform\": \"%s\",\n" % self.deppf) if deppf and self.deppf else "" + if depst: + dep += " " * indent + " \"station\":\n" + dep += self.depst.json(indent + 3, **stationkwargs) + ",\n" - dep = "".join(dep.rsplit(",", 1)) - out += dep + " " * indent + " },\n" + if deptime: + dep += " " * indent + \ + " \"date\": \"%s\",\n" % datetime.datetime.strftime( + self.deptime, "%d.%m.%Y") + dep += " " * indent + \ + " \"time\": \"%s\",\n" % datetime.datetime.strftime( + self.deptime, "%H:%M") - if arrst or arrtime or arrpf or curarr: - arr = " " * indent + " \"arrival\": {\n" + dep += (" " * indent + " \"current\": \"%s\",\n" % + self.currdep) if currdep and self.currdep else "" + dep += (" " * indent + " \"platform\": \"%s\",\n" % + self.deppf) if deppf and self.deppf else "" - if arrst: - arr += " " * indent + " \"station\":\n" - arr += self.arrst.json(indent + 3, **stationkwargs) + ",\n" + dep = "".join(dep.rsplit(",", 1)) + out += dep + " " * indent + " },\n" - if arrtime: - arr += " " * indent + " \"date\": \"%s\",\n" % datetime.datetime.strftime(self.arrtime, "%d.%m.%Y") - arr += " " * indent + " \"time\": \"%s\",\n" % datetime.datetime.strftime(self.arrtime, "%H:%M") + if arrst or arrtime or arrpf or curarr: + arr = " " * indent + " \"arrival\": {\n" - arr += (" " * indent + " \"current\": \"%s\",\n" % self.curarr) if curarr and self.curarr else "" - arr += (" " * indent + " \"platform\": \"%s\",\n" % self.arrpf) if arrpf and self.arrpf else "" + if arrst: + arr += " " * indent + " \"station\":\n" + arr += self.arrst.json(indent + 3, **stationkwargs) + ",\n" - arr = "".join(arr.rsplit(",", 1)) - out += arr + " " * indent + " },\n" - - out += " " * indent + "}" + if arrtime: + arr += " " * indent + \ + " \"date\": \"%s\",\n" % datetime.datetime.strftime( + self.arrtime, "%d.%m.%Y") + arr += " " * indent + \ + " \"time\": \"%s\",\n" % datetime.datetime.strftime( + self.arrtime, "%H:%M") - out = "".join(out.rsplit(",", 1)) + arr += (" " * indent + " \"current\": \"%s\",\n" % + self.curarr) if curarr and self.curarr else "" + arr += (" " * indent + " \"platform\": \"%s\",\n" % + self.arrpf) if arrpf and self.arrpf else "" - return out + arr = "".join(arr.rsplit(",", 1)) + out += arr + " " * indent + " },\n" + out += " " * indent + "}" + + out = "".join(out.rsplit(",", 1)) + + return out diff --git a/classes/station.py b/classes/station.py index 81988c9..24dcc96 100644 --- a/classes/station.py +++ b/classes/station.py @@ -1,80 +1,91 @@ class Station: - def __init__(self, name, sttype, extid = None, xcoord = None, ycoord = None, prodclass = None): - self.name = name - self.sttype = sttype - self.extid = extid - self.xcoord = float(xcoord)/1000000 if xcoord else None - self.ycoord = float(ycoord)/1000000 if ycoord else None - self.prodclass = prodclass - self.services = [] + def __init__(self, name, sttype, extid=None, xcoord=None, ycoord=None, prodclass=None): + self.name = name + self.sttype = sttype + self.extid = extid + self.xcoord = float(xcoord)/1000000 if xcoord else None + self.ycoord = float(ycoord)/1000000 if ycoord else None + self.prodclass = prodclass + self.services = [] - def addService(self, svc): - self.services += [svc] + def addService(self, svc): + self.services += [svc] - def useId(self): - return self.extid or self.name + def useId(self): + return self.extid or self.name - def lat(self): - return self.ycoord + def lat(self): + return self.ycoord - def lon(self): - return self.xcoord + def lon(self): + return self.xcoord - def json(self, indent = 0, name = True, extid = True, sttype = False, coords = False, prodclass = False, distance = False, services = False, servicekwargs = {}): - out = " " * indent + "{\n" + def json(self, indent=0, name=True, extid=True, sttype=False, coords=False, prodclass=False, distance=False, services=False, servicekwargs={}): + out = " " * indent + "{\n" - out += (" " * indent + " \"name\": \"%s\",\n" % self.name) if name else "" - out += (" " * indent + " \"id\": \"%s\",\n" % self.useId()) if extid else "" - out += (" " * indent + " \"distance\": %i,\n" % int(self.distance)) if distance else "" - out += (" " * indent + " \"type\": \"%s\",\n" % self.sttype) if sttype else "" + out += (" " * indent + " \"name\": \"%s\",\n" % + self.name) if name else "" + out += (" " * indent + " \"id\": \"%s\",\n" % + self.useId()) if extid else "" + out += (" " * indent + " \"distance\": %i,\n" % + int(self.distance)) if distance else "" + out += (" " * indent + " \"type\": \"%s\",\n" % + self.sttype) if sttype else "" - if coords and self.xcoord: - out += " " * indent + " \"coords\": {\n" - out += " " * indent + " \"lon\": %f,\n" % self.xcoord - out += " " * indent + " \"lat\": %f\n" % self.ycoord - out += " " * indent + " },\n" + if coords and self.xcoord: + out += " " * indent + " \"coords\": {\n" + out += " " * indent + " \"lon\": %f,\n" % self.xcoord + out += " " * indent + " \"lat\": %f\n" % self.ycoord + out += " " * indent + " },\n" - if services and self.services: - out += " " * indent + " \"services\": [\n" + if services and self.services: + out += " " * indent + " \"services\": [\n" - for i in range(len(self.services)): - out += self.services[i].json(indent + 2, i, **servicekwargs) + (",\n" if not i == len(self.services) - 1 else "\n") + for i in range(len(self.services)): + out += self.services[i].json(indent + 2, i, **servicekwargs) + ( + ",\n" if not i == len(self.services) - 1 else "\n") - out += " " * indent + " ]," + out += " " * indent + " ]," - out += (" " * indent + " \"prodclass\": \"%s\",\n" % self.prodclass) if prodclass else "" + out += (" " * indent + " \"prodclass\": \"%s\",\n" % + self.prodclass) if prodclass else "" - out = "".join(out.rsplit(",", 1)) + out = "".join(out.rsplit(",", 1)) - out += " " * indent + "}" + out += " " * indent + "}" - return out + return out - def xml(self, indent = 0, name = True, extid = True, sttype = False, coords = False, prodclass = False, distance = False, services = False, servicekwargs = {}): - out = " " * indent + "\n" + def xml(self, indent=0, name=True, extid=True, sttype=False, coords=False, prodclass=False, distance=False, services=False, servicekwargs={}): + out = " " * indent + "\n" - out += (" " * indent + " %s\n" % self.name) if name else "" - out += (" " * indent + " %s\n" % self.useId()) if extid else "" - out += (" " * indent + " %i\n" % int(self.distance)) if distance else "" - out += (" " * indent + " %s\n" % self.sttype) if sttype else "" + out += (" " * indent + " %s\n" % + self.name) if name else "" + out += (" " * indent + " %s\n" % + self.useId()) if extid else "" + out += (" " * indent + " %i\n" % + int(self.distance)) if distance else "" + out += (" " * indent + " %s\n" % + self.sttype) if sttype else "" - if coords and self.xcoord: - out += " " * indent + " \n" - out += " " * indent + " %f\n" % self.xcoord - out += " " * indent + " %f\n" % self.ycoord - out += " " * indent + " \n" + if coords and self.xcoord: + out += " " * indent + " \n" + out += " " * indent + " %f\n" % self.xcoord + out += " " * indent + " %f\n" % self.ycoord + out += " " * indent + " \n" - if services and self.services: - out += " " * indent + " \n" + if services and self.services: + out += " " * indent + " \n" - for i in range(len(self.services)): - out += self.services[i].xml(indent + 2, i, **servicekwargs) + "\n" + for i in range(len(self.services)): + out += self.services[i].xml(indent + 2, + i, **servicekwargs) + "\n" - out += " " * indent + " \n" + out += " " * indent + " \n" - out += (" " * indent + " %s\n" % self.prodclass) if prodclass else "" + out += (" " * indent + " %s\n" % + self.prodclass) if prodclass else "" - out += " " * indent + "" - - return out + out += " " * indent + "" + return out diff --git a/classes/train.py b/classes/train.py index 3315fe0..cdb7b90 100644 --- a/classes/train.py +++ b/classes/train.py @@ -1,69 +1,73 @@ import workers.val + class Train: - def __init__(self, name, tid, dest, xcoord, ycoord, prodclass): - self.name = name - self.tid = tid - self.dest = dest - self.xcoord = float(xcoord)/1000000 - self.ycoord = float(ycoord)/1000000 - self.prodclass = prodclass + def __init__(self, name, tid, dest, xcoord, ycoord, prodclass): + self.name = name + self.tid = tid + self.dest = dest + self.xcoord = float(xcoord)/1000000 + self.ycoord = float(ycoord)/1000000 + self.prodclass = prodclass - def lat(self): - return self.ycoord + def lat(self): + return self.ycoord - def lon(self): - return self.xcoord + def lon(self): + return self.xcoord - def destStation(self): - return list(workers.val.validateName(self.name))[0] + def destStation(self): + return list(workers.val.validateName(self.name))[0] - def json(self, indent = 0, name = True, tid = True, dest = True, coords = True, prodclass = False, stationkwargs = {}): - out = " " * indent + "{\n" + def json(self, indent=0, name=True, tid=True, dest=True, coords=True, prodclass=False, stationkwargs={}): + out = " " * indent + "{\n" - out += (" " * indent + " \"name\": \"%s\",\n" % self.name) if name else "" - out += (" " * indent + " \"id\": \"%s\",\n" % self.tid) if tid else "" + out += (" " * indent + " \"name\": \"%s\",\n" % + self.name) if name else "" + out += (" " * indent + " \"id\": \"%s\",\n" % self.tid) if tid else "" - if dest: -# out += " " * indent + " \"destination\":\n" -# out += self.dest.json(indent + 2, **stationkwargs) + "\n" - out += " " * indent + " \"destination\": \"%s\",\n" % self.dest + if dest: + # out += " " * indent + " \"destination\":\n" + # out += self.dest.json(indent + 2, **stationkwargs) + "\n" + out += " " * indent + " \"destination\": \"%s\",\n" % self.dest - if coords: - out += " " * indent + " \"coords\": {\n" - out += " " * indent + " \"lon\": %f,\n" % self.xcoord - out += " " * indent + " \"lat\": %f\n" % self.ycoord - out += " " * indent + " },\n" + if coords: + out += " " * indent + " \"coords\": {\n" + out += " " * indent + " \"lon\": %f,\n" % self.xcoord + out += " " * indent + " \"lat\": %f\n" % self.ycoord + out += " " * indent + " },\n" - out += (" " * indent + " \"prodclass\": \"%s\",\n" % self.prodclass) if prodclass else "" + out += (" " * indent + " \"prodclass\": \"%s\",\n" % + self.prodclass) if prodclass else "" - out = "".join(out.rsplit(",", 1)) + out = "".join(out.rsplit(",", 1)) - out += " " * indent + "}" + out += " " * indent + "}" - return out + return out - def xml(self, indent = 0, name = True, tid = True, dest = True, coords = True, prodclass = False, stationkwargs = {}): - out = " " * indent + "\n" + def xml(self, indent=0, name=True, tid=True, dest=True, coords=True, prodclass=False, stationkwargs={}): + out = " " * indent + "\n" - out += (" " * indent + " %s\n" % self.name) if name else "" - out += (" " * indent + " %s\n" % self.tid) if tid else "" + out += (" " * indent + " %s\n" % + self.name) if name else "" + out += (" " * indent + " %s\n" % self.tid) if tid else "" - if dest: -# out += " " * indent + " \n" -# out += self.dest.xml(indent + 2, **stationkwargs) + "\n" -# out += " " * indent + " \n" - out += " " * indent + " %s\n" % self.dest + if dest: + # out += " " * indent + " \n" + # out += self.dest.xml(indent + 2, **stationkwargs) + "\n" + # out += " " * indent + " \n" + out += " " * indent + " %s\n" % self.dest - if coords: - out += " " * indent + " \n" - out += " " * indent + " %f\n" % self.xcoord - out += " " * indent + " %f\n" % self.ycoord - out += " " * indent + " \n" + if coords: + out += " " * indent + " \n" + out += " " * indent + " %f\n" % self.xcoord + out += " " * indent + " %f\n" % self.ycoord + out += " " * indent + " \n" - out += (" " * indent + " %s\n" % self.prodclass) if prodclass else "" + out += (" " * indent + " %s\n" % + self.prodclass) if prodclass else "" - out += " " * indent + "" - - return out + out += " " * indent + "" + return out diff --git a/main.py b/main.py index 3833c7a..8e12309 100644 --- a/main.py +++ b/main.py @@ -24,211 +24,228 @@ XML = "text/xml; charset=UTF-8" DOCSTR = ' Check out the documentation for usage instructions.' + def doConn(req): - try: - getfrm = req.cfrm if "cfrm" in dir(req) and req.cfrm else req.args["from"][0] if "from" in req.args else None - getto = req.cto if "cto" in dir(req) and req.cto else req.args["to"][0] if "to" in req.args else None + try: + getfrm = req.cfrm if "cfrm" in dir( + req) and req.cfrm else req.args["from"][0] if "from" in req.args else None + getto = req.cto if "cto" in dir( + req) and req.cto else req.args["to"][0] if "to" in req.args else None - try: - frm = html.unescape(getfrm.encode("latin-1").decode("utf-8")) - to = html.unescape(getto.encode("latin-1").decode("utf-8")) - except UnicodeDecodeError: - frm = html.unescape(getfrm) - to = html.unescape(getto) + try: + frm = html.unescape(getfrm.encode("latin-1").decode("utf-8")) + to = html.unescape(getto.encode("latin-1").decode("utf-8")) + except UnicodeDecodeError: + frm = html.unescape(getfrm) + to = html.unescape(getto) - if not frm or not to: - raise ValueError() + if not frm or not to: + raise ValueError() + except Exception: + content = "

400 Bad Request

\n" + content += "\"from\"and \"to\" values are required for this type of request." + return Response(HTTP400, HTML, content) - except Exception: - content = "

400 Bad Request

\n" - content += "\"from\"and \"to\" values are required for this type of request." - return Response(HTTP400, HTML, content) + count = req.args["count"][0] if "count" in req.args and req.args["count"] else 6 + date = req.args["date"][0] if "date" in req.args and req.args["date"] else datetime.datetime.strftime( + datetime.datetime.now(pytz.timezone("Europe/Vienna")), "%d.%m.%Y") + time = req.args["time"][0] if "time" in req.args and req.args["time"] else datetime.datetime.strftime( + datetime.datetime.now(pytz.timezone("Europe/Vienna")), "%H:%M") + mode = True if "mode" in req.args and req.args["mode"] and req.args["mode"][0].lower( + ) == "arr" else False + details = True if "details" in req.args else False - count = req.args["count"][0] if "count" in req.args and req.args["count"] else 6 - date = req.args["date"][0] if "date" in req.args and req.args["date"] else datetime.datetime.strftime(datetime.datetime.now(pytz.timezone("Europe/Vienna")),"%d.%m.%Y") - time = req.args["time"][0] if "time" in req.args and req.args["time"] else datetime.datetime.strftime(datetime.datetime.now(pytz.timezone("Europe/Vienna")),"%H:%M") - mode = True if "mode" in req.args and req.args["mode"] and req.args["mode"][0].lower() == "arr" else False - details = True if "details" in req.args else False + try: + count = int(count) + if count < 0 or count > 10: + raise ValueError() + except: + content = "

400 Bad Request

\n" + content += "The \"count\" value must be a value between 0 and 10." + return Response(HTTP400, HTML, content) - try: - count = int(count) - if count < 0 or count > 10: - raise ValueError() - except: - content = "

400 Bad Request

\n" - content += "The \"count\" value must be a value between 0 and 10." - return Response(HTTP400, HTML, content) + try: + outtime = datetime.datetime.strptime( + "%s %s" % (date, time), "%d.%m.%Y %H:%M") + except: + content = "

400 Bad Request

\n" + content += "The \"date\" value must be in DD.MM.YYYY format, the \"time\" value must be in HH:MM format." + return Response(HTTP400, HTML, content) - try: - outtime = datetime.datetime.strptime("%s %s" % (date, time), "%d.%m.%Y %H:%M") - except: - content = "

400 Bad Request

\n" - content += "The \"date\" value must be in DD.MM.YYYY format, the \"time\" value must be in HH:MM format." - return Response(HTTP400, HTML, content) + via = list(req.args["via"]) if "via" in req.args else None - via = list(req.args["via"]) if "via" in req.args else None + if via and len(via) > 3: + content = "

400 Bad Request

\n" + content += "It is not possible to route through more than three \"via\" stations." + return Response(HTTP400, HTML, content) - if via and len(via) > 3: - content = "

400 Bad Request

\n" - content += "It is not possible to route through more than three \"via\" stations." - return Response(HTTP400, HTML, content) + try: + content = workers.conn.worker( + frm, to, count, outtime, mode, details, req.json, via) + except Exception as e: + content = "

500 Internal Server Error

\n" + if "debug" in req.args: + content += traceback.format_exc().replace("\n", "
") + return Response(HTTP500, HTML, content) - try: - content = workers.conn.worker(frm, to, count, outtime, mode, details, req.json, via) - except Exception as e: - content = "

500 Internal Server Error

\n" - if "debug" in req.args: - content += traceback.format_exc().replace("\n", "
") - return Response(HTTP500, HTML, content) + return Response(HTTP200, JSON if req.json else XML, content) - return Response(HTTP200, JSON if req.json else XML, content) def doVal(req): - try: - try: - name = (req.cfrm or req.args["name"][0]).encode("latin-1").decode("utf-8") - except UnicodeDecodeError: - name = req.cfrm or req.args["name"][0] + try: + try: + name = (req.cfrm or req.args["name"][0]).encode( + "latin-1").decode("utf-8") + except UnicodeDecodeError: + name = req.cfrm or req.args["name"][0] - if not name: - raise ValueError() + if not name: + raise ValueError() - except Exception: - content = "

400 Bad Request

\n" - content += "A \"name\" value is required for this type of request." - return Response(HTTP400, HTML, content) + except Exception: + content = "

400 Bad Request

\n" + content += "A \"name\" value is required for this type of request." + return Response(HTTP400, HTML, content) - try: - content = workers.val.worker(name, req.json) + try: + content = workers.val.worker(name, req.json) - except Exception as e: - content = "

500 Internal Server Error

\n" - if "debug" in req.args: - content += traceback.format_exc().replace("\n", "
") - return Response(HTTP500, HTML, content) + except Exception as e: + content = "

500 Internal Server Error

\n" + if "debug" in req.args: + content += traceback.format_exc().replace("\n", "
") + return Response(HTTP500, HTML, content) + + return Response(HTTP200, JSON if req.json else XML, content) - return Response(HTTP200, JSON if req.json else XML, content) def doNearby(req): - try: - lat = float(req.args["lat"][0].replace(",", ".")) - lon = float(req.args["lon"][0].replace(",", ".")) + try: + lat = float(req.args["lat"][0].replace(",", ".")) + lon = float(req.args["lon"][0].replace(",", ".")) - if (not lat and not lat == float(0)) or (not lon and not lon == float(0)): - raise ValueError() + if (not lat and not lat == float(0)) or (not lon and not lon == float(0)): + raise ValueError() - except: - content = "

400 Bad Request

\n" - content += "\"lat\" and \"lon\" values are required for this type of request." - return Response(HTTP400, HTML, content) + except: + content = "

400 Bad Request

\n" + content += "\"lat\" and \"lon\" values are required for this type of request." + return Response(HTTP400, HTML, content) - distance = req.args["distance"][0] if "distance" in req.args and req.args["distance"] else 1000 + distance = req.args["distance"][0] if "distance" in req.args and req.args["distance"] else 1000 - try: - distance = int(distance) - if distance < 0 or distance > 10000: - raise ValueError() - except: - content = "

400 Bad Request

\n" - content += "\"distance\" must be a value between 0 and 10000." - return Response(HTTP400, HTML, content) + try: + distance = int(distance) + if distance < 0 or distance > 10000: + raise ValueError() + except: + content = "

400 Bad Request

\n" + content += "\"distance\" must be a value between 0 and 10000." + return Response(HTTP400, HTML, content) - try: - content = workers.closest.worker(lat, lon, distance, req.json) + try: + content = workers.closest.worker(lat, lon, distance, req.json) - except Exception as e: - content = "

500 Internal Server Error

" - if "debug" in req.args: - content += traceback.format_exc().replace("\n", "
") - return Response(HTTP500, HTML, content) + except Exception as e: + content = "

500 Internal Server Error

" + if "debug" in req.args: + content += traceback.format_exc().replace("\n", "
") + return Response(HTTP500, HTML, content) + + return Response(HTTP200, JSON if req.json else XML, content) - return Response(HTTP200, JSON if req.json else XML, content) def doRadar(req): - trains = req.args["train"] if "train" in req.args else None + trains = req.args["train"] if "train" in req.args else None - try: - content = workers.radar.worker(trains, req.json) - except Exception as e: - content = "

500 Internal Server Error

\n" - if "debug" in req.args: - content += traceback.format_exc().replace("\n", "
") - return Response(HTTP500, HTML, content) + try: + content = workers.radar.worker(trains, req.json) + except Exception as e: + content = "

500 Internal Server Error

\n" + if "debug" in req.args: + content += traceback.format_exc().replace("\n", "
") + return Response(HTTP500, HTML, content) + + return Response(HTTP200, JSON if req.json else XML, content) - return Response(HTTP200, JSON if req.json else XML, content) def doDepArr(req): - try: - name = req.args["name"][0] - try: - name = name.encode("latin-1").decode("utf-8") - except UnicodeDecodeError: - pass + try: + name = req.args["name"][0] + try: + name = name.encode("latin-1").decode("utf-8") + except UnicodeDecodeError: + pass - except Exception: - content = "

400 Bad Request

\n" - content += "A \"name\" value is required for this type of request." - return Response(HTTP400, HTML, content) + except Exception: + content = "

400 Bad Request

\n" + content += "A \"name\" value is required for this type of request." + return Response(HTTP400, HTML, content) - count = req.args["count"][0] if "count" in req.args and req.args["count"] else 30 - date = req.args["date"][0] if "date" in req.args and req.args["date"] else datetime.datetime.strftime(datetime.datetime.now(pytz.timezone("Europe/Vienna")),"%d.%m.%Y") - time = req.args["time"][0] if "time" in req.args and req.args["time"] else datetime.datetime.strftime(datetime.datetime.now(pytz.timezone("Europe/Vienna")),"%H:%M") - mode = True if req.rtype[:3] == "arr" else False - details = True + count = req.args["count"][0] if "count" in req.args and req.args["count"] else 30 + date = req.args["date"][0] if "date" in req.args and req.args["date"] else datetime.datetime.strftime( + datetime.datetime.now(pytz.timezone("Europe/Vienna")), "%d.%m.%Y") + time = req.args["time"][0] if "time" in req.args and req.args["time"] else datetime.datetime.strftime( + datetime.datetime.now(pytz.timezone("Europe/Vienna")), "%H:%M") + mode = True if req.rtype[:3] == "arr" else False + details = True - try: - count = int(count) - except: - content = "

400 Bad Request

\n" - content += "The \"count\" value must be a numeric value." - return Response(HTTP400, HTML, content) + try: + count = int(count) + except: + content = "

400 Bad Request

\n" + content += "The \"count\" value must be a numeric value." + return Response(HTTP400, HTML, content) - try: - outtime = datetime.datetime.strptime("%s %s" % (date, time), "%d.%m.%Y %H:%M") - except: - content = "

400 Bad Request

\n" - content += "The \"date\" value must be in DD.MM.YYYY format, the \"time\" value must be in HH:MM format." - return Response(HTTP400, HTML, content) + try: + outtime = datetime.datetime.strptime( + "%s %s" % (date, time), "%d.%m.%Y %H:%M") + except: + content = "

400 Bad Request

\n" + content += "The \"date\" value must be in DD.MM.YYYY format, the \"time\" value must be in HH:MM format." + return Response(HTTP400, HTML, content) - try: - content = workers.deparr.worker(name, count, outtime, mode, details, req.json) - except Exception as e: - content = "

500 Internal Server Error

\n" - if "debug" in req.args: - content += traceback.format_exc().replace("\n", "
") - return Response(HTTP500, HTML, content) + try: + content = workers.deparr.worker( + name, count, outtime, mode, details, req.json) + except Exception as e: + content = "

500 Internal Server Error

\n" + if "debug" in req.args: + content += traceback.format_exc().replace("\n", "
") + return Response(HTTP500, HTML, content) + + return Response(HTTP200, JSON if req.json else XML, content) - return Response(HTTP200, JSON if req.json else XML, content) def doNot(req): - content = "

400 Bad Request

" - content += "The request type you submitted is invalid." - return Response(HTTP400, HTML, content) + content = "

400 Bad Request

" + content += "The request type you submitted is invalid." + return Response(HTTP400, HTML, content) + def application(env, re): - try: - req = Request(env) + try: + req = Request(env) - if req.rtype in ["conn", "connection", "connections"]: - res = doConn(req) - elif req.rtype in ["val", "validate"]: - res = doVal(req) - elif req.rtype in ["closest", "close", "near", "nearby"]: - res = doNearby(req) - elif req.rtype in ["radar", "live", "trains"]: - res = doRadar(req) - elif req.rtype in ["dep", "arr", "departure", "arrival", "departures", "arrivals"]: - res = doDepArr(req) - else: - res = doNot(req) + if req.rtype in ["conn", "connection", "connections"]: + res = doConn(req) + elif req.rtype in ["val", "validate"]: + res = doVal(req) + elif req.rtype in ["closest", "close", "near", "nearby"]: + res = doNearby(req) + elif req.rtype in ["radar", "live", "trains"]: + res = doRadar(req) + elif req.rtype in ["dep", "arr", "departure", "arrival", "departures", "arrivals"]: + res = doDepArr(req) + else: + res = doNot(req) - except IllegalMethodException as e: - res = Response(HTTP405, HTML, str(e) + DOCSTR) - except InvalidArgumentException as e: - res = Response(HTTP400, HTML, str(e) + DOCSTR) - - re(res.status, [("Content-Type", res.ctype)]) - yield res.content.encode() - return + except IllegalMethodException as e: + res = Response(HTTP405, HTML, str(e) + DOCSTR) + except InvalidArgumentException as e: + res = Response(HTTP400, HTML, str(e) + DOCSTR) + re(res.status, [("Content-Type", res.ctype)]) + yield res.content.encode() + return diff --git a/workers/closest.py b/workers/closest.py index 9af9fb5..d1301ca 100644 --- a/workers/closest.py +++ b/workers/closest.py @@ -3,8 +3,9 @@ import math import workers.val from classes.httpclient import HTTPClient -def getOSM(lat, lon, distance = 1000): - query = """[out:json]; + +def getOSM(lat, lon, distance=1000): + query = """[out:json]; ( node (around:%i,%f,%f) @@ -21,62 +22,71 @@ def getOSM(lat, lon, distance = 1000): out; """ % (distance, lat, lon, distance, lat, lon) - endpoint = "https://overpass.kumi.systems/api/interpreter" + endpoint = "https://overpass.kumi.systems/api/interpreter" - json = HTTPClient().post(endpoint, data={"data": query}).text - res = overpy.Overpass().parse_json(json) + json = HTTPClient().post(endpoint, data={"data": query}).text + res = overpy.Overpass().parse_json(json) + + return res.nodes - return res.nodes def cDistance(lat1, lon1, lat2, lon2): - lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2]) + lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2]) - dila = lat2 - lat1 - dilo = lon2 - lon1 + dila = lat2 - lat1 + dilo = lon2 - lon1 - diff = 2 * math.asin(math.sqrt(math.sin(dila/2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dilo/2) ** 2)) + diff = 2 * math.asin(math.sqrt(math.sin(dila/2) ** 2 + + math.cos(lat1) * math.cos(lat2) * math.sin(dilo/2) ** 2)) - dis = diff * 6371000 + dis = diff * 6371000 - return dis + return dis -def getStations(nodes, distance = 1000, lat = None, lon = None): - unodes = list(set([node.tags["alt_name"].split(",")[0] if "alt_name" in node.tags and len(node.tags["alt_name"].split(",")[0]) > len(node.tags["name"]) else node.tags["name"] for node in nodes])) - for node in unodes: - for station in workers.val.validateName(node): - if lat and lon: - idistance = cDistance(station.lat(), station.lon(), lat, lon) - if idistance < distance: - station.distance = idistance - yield station - break - else: - yield station - break -def findStations(lat, lon, distance = 1000, validate = True): - stations = list(getStations(getOSM(lat, lon, distance), distance, lat if validate else None, lon if validate else None)) +def getStations(nodes, distance=1000, lat=None, lon=None): + unodes = list(set([node.tags["alt_name"].split(",")[0] if "alt_name" in node.tags and len( + node.tags["alt_name"].split(",")[0]) > len(node.tags["name"]) else node.tags["name"] for node in nodes])) + for node in unodes: + for station in workers.val.validateName(node): + if lat and lon: + idistance = cDistance(station.lat(), station.lon(), lat, lon) + if idistance < distance: + station.distance = idistance + yield station + break + else: + yield station + break - if validate: - return sorted(stations, key = lambda station: station.distance) - return stations +def findStations(lat, lon, distance=1000, validate=True): + stations = list(getStations(getOSM(lat, lon, distance), distance, + lat if validate else None, lon if validate else None)) -def worker(lat, lon, distance = 1000, json = False): - outtext = """{ + if validate: + return sorted(stations, key=lambda station: station.distance) + + return stations + + +def worker(lat, lon, distance=1000, json=False): + outtext = """{ "stations": [ """ if json else """ """ - for station in findStations(lat, lon, distance): - outtext += ",\n" if (json and not outtext.strip()[-1] == "[") else "" - station.distance = station.distance or int(cDistance(station.lat(), station.lon(), lat, lon)) - outtext += station.json(2, distance = True) if json else station.xml(1, distance = True) - outtext += "\n" if not json else "" + for station in findStations(lat, lon, distance): + outtext += ",\n" if (json and not outtext.strip()[-1] == "[") else "" + station.distance = station.distance or int( + cDistance(station.lat(), station.lon(), lat, lon)) + outtext += station.json(2, + distance=True) if json else station.xml(1, distance=True) + outtext += "\n" if not json else "" - outtext += """ + outtext += """ ] }""" if json else "" - return outtext + return outtext diff --git a/workers/conn.py b/workers/conn.py index bd8b012..3ee72b6 100644 --- a/workers/conn.py +++ b/workers/conn.py @@ -8,75 +8,95 @@ import sys import workers.val from classes import * + def getStation(name): - return list(workers.val.validateName(name))[0] + return list(workers.val.validateName(name))[0] -def getService(sid, lines, q, eq = None): - try: - dep = lines[0] - arr = lines[1] - det = lines[2] - depst = list(workers.val.validateName(dep.find("td", { "class": "station" }).findAll("a")[0].string))[0] - depdate = dep.find("td", { "class": "date" }).string.strip() or None - deptime = dep.find("td", { "class": "timeValue" }).find("span").string.split()[1].strip() +def getService(sid, lines, q, eq=None): + try: + dep = lines[0] + arr = lines[1] + det = lines[2] - depprog = dep.find("span", { "class": "prognosis" }).find("span").string.strip() if dep.find("span", { "class": "prognosis" }) and dep.find("span", { "class": "prognosis" }).find("span") else None - depplat = dep.find("td", { "class": "platform" }).find("span").string.strip() if dep.find("td", { "class": "platform" }) and dep.find("td", { "class": "platform" }).find("span") else None + depst = list(workers.val.validateName( + dep.find("td", {"class": "station"}).findAll("a")[0].string))[0] + depdate = dep.find("td", {"class": "date"}).string.strip() or None + deptime = dep.find("td", {"class": "timeValue"}).find( + "span").string.split()[1].strip() - walk = dep.find("img", { "class": "product" }).get("src") == "/img/vs_oebb/fuss_pic.gif" - name = dep.find("img", { "class": "product" }).get("alt") if not walk else "Walk" + depprog = dep.find("span", {"class": "prognosis"}).find("span").string.strip() if dep.find( + "span", {"class": "prognosis"}) and dep.find("span", {"class": "prognosis"}).find("span") else None + depplat = dep.find("td", {"class": "platform"}).find("span").string.strip() if dep.find( + "td", {"class": "platform"}) and dep.find("td", {"class": "platform"}).find("span") else None - arrst = list(workers.val.validateName(arr.find("td", { "class": "station" }).findAll("a")[0].string))[0] - arrdate = (arr.find("td", { "class": "date" }).find("span") or arr.find("td", { "class": "date" })).string.strip() or depdate - arrtime = arr.find("td", { "class": "timeValue" }).find("span").string.split()[1].strip() - arrprog = (arr.find("span", { "class": "prognosis" }).find("span") or arr.find("span", { "class": "prognosis" })).string.strip() or None - arrplat = (arr.find("td", { "class": "platform" }).find("span") or arr.find("td", { "class": "platform" })).string.strip() or None + walk = dep.find("img", {"class": "product"}).get( + "src") == "/img/vs_oebb/fuss_pic.gif" + name = dep.find("img", {"class": "product"}).get( + "alt") if not walk else "Walk" - if arrdate and not depdate: - arrdts = datetime.datetime.strptime(arrdate, "%d.%m.%Y") - depdts = arrdts - datetime.timedelta(days=1) - depdate = datetime.datetime.strftime(depdts, "%d.%m.%Y") + arrst = list(workers.val.validateName( + arr.find("td", {"class": "station"}).findAll("a")[0].string))[0] + arrdate = (arr.find("td", {"class": "date"}).find("span") or arr.find( + "td", {"class": "date"})).string.strip() or depdate + arrtime = arr.find("td", {"class": "timeValue"}).find( + "span").string.split()[1].strip() + arrprog = (arr.find("span", {"class": "prognosis"}).find("span") or arr.find( + "span", {"class": "prognosis"})).string.strip() or None + arrplat = (arr.find("td", {"class": "platform"}).find("span") or arr.find( + "td", {"class": "platform"})).string.strip() or None - dest = None + if arrdate and not depdate: + arrdts = datetime.datetime.strptime(arrdate, "%d.%m.%Y") + depdts = arrdts - datetime.timedelta(days=1) + depdate = datetime.datetime.strftime(depdts, "%d.%m.%Y") - if not (walk or depdate): - try: - purl = dep.find("td", { "class": "product" }).find("a").get("href") - psource = HTTPClient().get(purl).text - zuppa = BeautifulSoup(psource, "html5lib") - depdate = zuppa.findAll("div", { "class": "block" })[1].text.strip() - arrdate = depdate - dest = list(workers.val.validateName(zuppa.findAll("div", { "class": "block" })[2].text.split(":")[1].strip()))[0] - except: - pass + dest = None - if not walk and not depdate: - depdate = "01.01.2000" - arrdate = depdate + if not (walk or depdate): + try: + purl = dep.find("td", {"class": "product"}).find( + "a").get("href") + psource = HTTPClient().get(purl).text + zuppa = BeautifulSoup(psource, "html5lib") + depdate = zuppa.findAll("div", {"class": "block"})[ + 1].text.strip() + arrdate = depdate + dest = list(workers.val.validateName(zuppa.findAll( + "div", {"class": "block"})[2].text.split(":")[1].strip()))[0] + except: + pass - depts = datetime.datetime.strptime("%s %s" % (depdate, deptime), "%d.%m.%Y %H:%M") - arrts = datetime.datetime.strptime("%s %s" % (arrdate, arrtime), "%d.%m.%Y %H:%M") + if not walk and not depdate: + depdate = "01.01.2000" + arrdate = depdate - depprog = deptime if depprog == "pünktlich" else depprog - arrprog = arrtime if arrprog == "pünktlich" else arrprog + depts = datetime.datetime.strptime( + "%s %s" % (depdate, deptime), "%d.%m.%Y %H:%M") + arrts = datetime.datetime.strptime( + "%s %s" % (arrdate, arrtime), "%d.%m.%Y %H:%M") - svc = Service(name, depst, depts, arrst, arrts, dest, depplat, depprog, arrplat, arrprog) - q.put((sid, svc)) + depprog = deptime if depprog == "pünktlich" else depprog + arrprog = arrtime if arrprog == "pünktlich" else arrprog - except Exception as e: - if eq: - eq.put(sys.exc_info()) - raise + svc = Service(name, depst, depts, arrst, arrts, dest, + depplat, depprog, arrplat, arrprog) + q.put((sid, svc)) -def getDetails(cid, url, q, via = [], eq = None): - try: - ssource = HTTPClient().get(url).text - suppe = BeautifulSoup(ssource, "html5lib") + except Exception as e: + if eq: + eq.put(sys.exc_info()) + raise - cont = suppe.find("tr", id="trC0-%i" % cid) - if not cont: - return + +def getDetails(cid, url, q, via=[], eq=None): + try: + ssource = HTTPClient().get(url).text + suppe = BeautifulSoup(ssource, "html5lib") + + cont = suppe.find("tr", id="trC0-%i" % cid) + if not cont: + return # buyurl = None # @@ -84,151 +104,167 @@ def getDetails(cid, url, q, via = [], eq = None): # if url.get("href") and "https://tickets.oebb.at/de/ticket/ticket?" in url.get("href"): # buyurl = url.get("href") - conn = Connection(True) + conn = Connection(True) - for vst in via: - conn.addVia(vst) + for vst in via: + conn.addVia(vst) - lines = cont.findAll("tr", { "class": "tpDetails" })[1:] - threads = [] - iq = queue.PriorityQueue() + lines = cont.findAll("tr", {"class": "tpDetails"})[1:] + threads = [] + iq = queue.PriorityQueue() - for line in range(0, len(lines), 3): - t = threading.Thread(target=getService, args=(line, lines[line:line + 3], iq, eq), daemon = True) - t.start() - threads += [t] + for line in range(0, len(lines), 3): + t = threading.Thread(target=getService, args=( + line, lines[line:line + 3], iq, eq), daemon=True) + t.start() + threads += [t] - for t in threads: - t.join() + for t in threads: + t.join() - wdate = None + wdate = None - while not iq.empty(): - svc = iq.get()[1] + while not iq.empty(): + svc = iq.get()[1] - if not wdate or svc.arrtime > wdate: - wdate = svc.arrtime - elif svc.deptime < wdate: - ttime0 = datetime.datetime(wdate.year, wdate.month, wdate.day) - ttime1 = ttime0 + datetime.timedelta(hours=svc.deptime.hour, minutes=svc.deptime.minute) - ttime2 = ttime0 + datetime.timedelta(hours=svc.arrtime.hour, minutes=svc.arrtime.minute) + if not wdate or svc.arrtime > wdate: + wdate = svc.arrtime + elif svc.deptime < wdate: + ttime0 = datetime.datetime(wdate.year, wdate.month, wdate.day) + ttime1 = ttime0 + \ + datetime.timedelta(hours=svc.deptime.hour, + minutes=svc.deptime.minute) + ttime2 = ttime0 + \ + datetime.timedelta(hours=svc.arrtime.hour, + minutes=svc.arrtime.minute) - if ttime1 < wdate: - ttime1 += datetime.timedelta(days=1) - ttime2 += datetime.timedelta(days=1) + if ttime1 < wdate: + ttime1 += datetime.timedelta(days=1) + ttime2 += datetime.timedelta(days=1) - if ttime1 > ttime2: - ttime2 += datetime.timedelta(days=1) + if ttime1 > ttime2: + ttime2 += datetime.timedelta(days=1) - svc.deptime = ttime1 - svc.arrtime = ttime2 + svc.deptime = ttime1 + svc.arrtime = ttime2 - conn.addService(svc) + conn.addService(svc) - q.put((cid, conn)) + q.put((cid, conn)) - except: - if eq: - eq.put(sys.exc_info()) - raise + except: + if eq: + eq.put(sys.exc_info()) + raise -def connRequest(frm, to, count = 3, time = datetime.datetime.now(), mode = False, details = False, via = []): - outdate = datetime.datetime.strftime(time, "%d.%m.%Y") - outtime = datetime.datetime.strftime(time, "%H:%M") - url = "http://fahrplan.oebb.at/bin/query.exe/dn?start=1&S=%s&Z=%s&REQ0JourneyDate=%s&time=%s&REQ0HafasNumCons0=%s%s" % (frm.extid if frm.extid else frm.name, to.extid if to.extid else to.name, outdate, outtime, count, "×el=arrive" if mode else "") +def connRequest(frm, to, count=3, time=datetime.datetime.now(), mode=False, details=False, via=[]): + outdate = datetime.datetime.strftime(time, "%d.%m.%Y") + outtime = datetime.datetime.strftime(time, "%H:%M") - for i in range(len(via)): - url += "&REQ0JourneyStops%i.0G=%s&REQ0JourneyStops%i.0A=1" % (i + 1, via[i].extid if via[i].extid else via[i].name, i + 1) + url = "http://fahrplan.oebb.at/bin/query.exe/dn?start=1&S=%s&Z=%s&REQ0JourneyDate=%s&time=%s&REQ0HafasNumCons0=%s%s" % ( + frm.extid if frm.extid else frm.name, to.extid if to.extid else to.name, outdate, outtime, count, "×el=arrive" if mode else "") - source = HTTPClient().get(url).text + for i in range(len(via)): + url += "&REQ0JourneyStops%i.0G=%s&REQ0JourneyStops%i.0A=1" % ( + i + 1, via[i].extid if via[i].extid else via[i].name, i + 1) - if "GO_conViewMode=outward" not in source: - raise ValueError("No connection found.") + source = HTTPClient().get(url).text - juha = BeautifulSoup(source, "html5lib") - - if details: - conns = [] + if "GO_conViewMode=outward" not in source: + raise ValueError("No connection found.") - for a in juha.findAll("a"): - if a.get("href") and "GO_conViewMode" in a.get("href"): - conns += [a.get("href")] + juha = BeautifulSoup(source, "html5lib") - threads = [] - eq = queue.Queue() - q = queue.PriorityQueue() + if details: + conns = [] - for i in range(len(conns)): - t = threading.Thread(target=getDetails, args=(i, conns[i], q, via, eq), daemon = True) - t.start() - threads += [t] + for a in juha.findAll("a"): + if a.get("href") and "GO_conViewMode" in a.get("href"): + conns += [a.get("href")] - for t in threads: - t.join() + threads = [] + eq = queue.Queue() + q = queue.PriorityQueue() - if not eq.empty(): - exc = eq.get() - raise exc[1].with_traceback(exc[2]) + for i in range(len(conns)): + t = threading.Thread(target=getDetails, args=( + i, conns[i], q, via, eq), daemon=True) + t.start() + threads += [t] - while not q.empty(): - yield q.get()[1] + for t in threads: + t.join() - else: - for i in range(0, count): - det = juha.find("tr", id="trOverviewC0-%i" % i) - if not det: - break + if not eq.empty(): + exc = eq.get() + raise exc[1].with_traceback(exc[2]) - stations = det.find("td", { "class": "station" }).findAll("div") - depst = getStation(stations[0].text.strip()) - arrst = getStation(stations[-1].text.strip()) + while not q.empty(): + yield q.get()[1] - dates = list(det.find("td", { "class": "date" }).strings) - depdate = dates[0] - try: - arrdate = dates[1] - except: - arrdate = depdate + else: + for i in range(0, count): + det = juha.find("tr", id="trOverviewC0-%i" % i) + if not det: + break - times = det.find("div", { "class": "planed" }).text - deptime = times.split()[0] - arrtime = times.split()[2] + stations = det.find("td", {"class": "station"}).findAll("div") + depst = getStation(stations[0].text.strip()) + arrst = getStation(stations[-1].text.strip()) - projections = det.find("div", { "class": "prognosis" }) - curdep = None - curarr = None + dates = list(det.find("td", {"class": "date"}).strings) + depdate = dates[0] + try: + arrdate = dates[1] + except: + arrdate = depdate - depts = datetime.datetime.strptime("%s %s" % (depdate, deptime), "%d.%m.%Y %H:%M") - arrts = datetime.datetime.strptime("%s %s" % (arrdate, arrtime), "%d.%m.%Y %H:%M") + times = det.find("div", {"class": "planed"}).text + deptime = times.split()[0] + arrtime = times.split()[2] - name = "/".join([img.get("title") for img in det.findAll("img", { "class": "product" })]) + projections = det.find("div", {"class": "prognosis"}) + curdep = None + curarr = None + + depts = datetime.datetime.strptime( + "%s %s" % (depdate, deptime), "%d.%m.%Y %H:%M") + arrts = datetime.datetime.strptime( + "%s %s" % (arrdate, arrtime), "%d.%m.%Y %H:%M") + + name = "/".join([img.get("title") + for img in det.findAll("img", {"class": "product"})]) # ticketurl = det.find("td", { "class": "fares" }).find("a").get("href") - svc = Service(name, depst, depts, arrst, arrts, currdep = curdep, curarr = curarr) - conn = Connection(details) + svc = Service(name, depst, depts, arrst, arrts, + currdep=curdep, curarr=curarr) + conn = Connection(details) - for vst in via: - conn.addVia(vst) + for vst in via: + conn.addVia(vst) - conn.addService(svc) + conn.addService(svc) - yield conn + yield conn -def worker(frm, to, count = 3, time = datetime.datetime.now(pytz.timezone("Europe/Vienna")), mode = False, details = False, json = False, via = None): - conns = list(connRequest(getStation(frm), getStation(to), count, time, mode, details, [getStation(vst) for vst in via] if via else [])) - conns = conns[::-1] if mode else conns - output = """ +def worker(frm, to, count=3, time=datetime.datetime.now(pytz.timezone("Europe/Vienna")), mode=False, details=False, json=False, via=None): + conns = list(connRequest(getStation(frm), getStation(to), count, time, + mode, details, [getStation(vst) for vst in via] if via else [])) + conns = conns[::-1] if mode else conns + + output = """ """ if not json else """{ \"connections\": [ """ - for i in range(len(conns)): - output += (conns[i].xml(1, i) + "\n") if not json else (conns[i].json(2, i) + ("\n" if i == len(conns) - 1 else ",\n")) + for i in range(len(conns)): + output += (conns[i].xml(1, i) + "\n") if not json else ( + conns[i].json(2, i) + ("\n" if i == len(conns) - 1 else ",\n")) - output += "" if not json else " ]\n}" + output += "" if not json else " ]\n}" - return output + return output diff --git a/workers/deparr.py b/workers/deparr.py index 08c6847..0848186 100644 --- a/workers/deparr.py +++ b/workers/deparr.py @@ -8,96 +8,107 @@ import sys import workers.val from classes import * + def getStation(name): - return list(workers.val.validateName(name))[0] + return list(workers.val.validateName(name))[0] -def getService(sid, url, dtime, q = None, eq = None): - try: - zuppa = BeautifulSoup(HTTPClient().get(url).text, "html5lib") - name = zuppa.findAll("div", { "class": "block" })[0].text.strip().replace("(Zug-Nr. ", " - ").replace(")", "") - ddate = zuppa.findAll("div", { "class": "block" })[1].text.strip() +def getService(sid, url, dtime, q=None, eq=None): + try: + zuppa = BeautifulSoup(HTTPClient().get(url).text, "html5lib") - table = zuppa.find("table", { "class": "resultTable" }) - rows = table.findAll("tr")[1:] + name = zuppa.findAll("div", {"class": "block"})[0].text.strip().replace( + "(Zug-Nr. ", " - ").replace(")", "") + ddate = zuppa.findAll("div", {"class": "block"})[1].text.strip() - for row in rows: - if len(row.findAll("td")) > 6 and row.findAll("td")[4].text.strip() == dtime: - depst = getStation(row.findAll("td")[1].text.strip()) - currdep = row.findAll("td")[5].text.strip() - currdep = dtime if currdep == "pünktlich" else currdep or None - deppf = row.findAll("td")[-1].text.strip() or None + table = zuppa.find("table", {"class": "resultTable"}) + rows = table.findAll("tr")[1:] - dest = getStation(rows[-1].findAll("td")[1].text.strip()) - atime = rows[-1].findAll("td")[2].text.strip() - curarr = rows[-1].findAll("td")[3].text.strip() - curarr = atime if curarr == "pünktlich" else curarr or None - arrpf = rows[-1].findAll("td")[-1].text.strip() + for row in rows: + if len(row.findAll("td")) > 6 and row.findAll("td")[4].text.strip() == dtime: + depst = getStation(row.findAll("td")[1].text.strip()) + currdep = row.findAll("td")[5].text.strip() + currdep = dtime if currdep == "pünktlich" else currdep or None + deppf = row.findAll("td")[-1].text.strip() or None - deptime = datetime.datetime.strptime("%s %s" % (ddate, dtime), "%d.%m.%Y %H:%M") - arrtime = datetime.datetime.strptime("%s %s" % (ddate, atime), "%d.%m.%Y %H:%M") + dest = getStation(rows[-1].findAll("td")[1].text.strip()) + atime = rows[-1].findAll("td")[2].text.strip() + curarr = rows[-1].findAll("td")[3].text.strip() + curarr = atime if curarr == "pünktlich" else curarr or None + arrpf = rows[-1].findAll("td")[-1].text.strip() - if arrtime < deptime: - arrtime += datetime.timedelta(days = 1) + deptime = datetime.datetime.strptime( + "%s %s" % (ddate, dtime), "%d.%m.%Y %H:%M") + arrtime = datetime.datetime.strptime( + "%s %s" % (ddate, atime), "%d.%m.%Y %H:%M") - if q: - q.put((sid, Service(name, depst, deptime, dest, arrtime, dest, deppf, currdep, arrpf, curarr))) - return q + if arrtime < deptime: + arrtime += datetime.timedelta(days=1) - except: - if eq: - eq.put(sys.exc_info()) - raise + if q: + q.put((sid, Service(name, depst, deptime, dest, + arrtime, dest, deppf, currdep, arrpf, curarr))) + return q -def daRequest(station, count = 3, time = datetime.datetime.now(), mode = False, details = False): - outdate = datetime.datetime.strftime(time, "%d.%m.%Y") - outtime = datetime.datetime.strftime(time, "%H:%M") + except: + if eq: + eq.put(sys.exc_info()) + raise - url = "http://fahrplan.oebb.at/bin/stboard.exe/dn?input=%s&boardType=%s&time=%s&productsFilter=1111111111111111&dateBegin=%s&dateEnd=&selectDate=&maxJourneys=%i&start=yes&dirInput=&sqView=2" % (station.extid if station.extid else station.name, "arr" if mode else "dep", outtime, outdate, count) - source = HTTPClient().get(url).text +def daRequest(station, count=3, time=datetime.datetime.now(), mode=False, details=False): + outdate = datetime.datetime.strftime(time, "%d.%m.%Y") + outtime = datetime.datetime.strftime(time, "%H:%M") - if "traininfo.exe/dn/" not in source: - raise ValueError("No services found.") + url = "http://fahrplan.oebb.at/bin/stboard.exe/dn?input=%s&boardType=%s&time=%s&productsFilter=1111111111111111&dateBegin=%s&dateEnd=&selectDate=&maxJourneys=%i&start=yes&dirInput=&sqView=2" % ( + station.extid if station.extid else station.name, "arr" if mode else "dep", outtime, outdate, count) - juha = BeautifulSoup(source, "html5lib") - - services = [] + source = HTTPClient().get(url).text - table = juha.find("table", {"class": "resultTable"}) + if "traininfo.exe/dn/" not in source: + raise ValueError("No services found.") - for row in table.findAll("tr")[1:-1]: - if not len(row.findAll("td")) < 4: - services += [(row.findAll("a")[0].get("href"), row.findAll("td")[0].text.strip())] - - threads = [] - eq = queue.Queue() - q = queue.PriorityQueue() + juha = BeautifulSoup(source, "html5lib") - for i in range(len(services)): - t = threading.Thread(target=getService, args=(i, services[i][0], services[i][1], q, eq), daemon = True) - t.start() - threads += [t] + services = [] - for t in threads: - t.join() + table = juha.find("table", {"class": "resultTable"}) - if not eq.empty(): - exc = eq.get() - raise exc[1].with_traceback(exc[2]) + for row in table.findAll("tr")[1:-1]: + if not len(row.findAll("td")) < 4: + services += [(row.findAll("a")[0].get("href"), + row.findAll("td")[0].text.strip())] - while not q.empty(): - station.addService(q.get()[1]) + threads = [] + eq = queue.Queue() + q = queue.PriorityQueue() - return station + for i in range(len(services)): + t = threading.Thread(target=getService, args=( + i, services[i][0], services[i][1], q, eq), daemon=True) + t.start() + threads += [t] -def worker(station, count = 30, time = datetime.datetime.now(pytz.timezone("Europe/Vienna")), mode = False, details = False, json = False): - station = daRequest(getStation(station), count, time, mode, details) + for t in threads: + t.join() - if json: - output = station.json(services = True) - else: - output = """\n""" - output += station.xml(services = True) + if not eq.empty(): + exc = eq.get() + raise exc[1].with_traceback(exc[2]) - return output + while not q.empty(): + station.addService(q.get()[1]) + + return station + + +def worker(station, count=30, time=datetime.datetime.now(pytz.timezone("Europe/Vienna")), mode=False, details=False, json=False): + station = daRequest(getStation(station), count, time, mode, details) + + if json: + output = station.json(services=True) + else: + output = """\n""" + output += station.xml(services=True) + + return output diff --git a/workers/radar.py b/workers/radar.py index 7d8e4cf..864f6d3 100644 --- a/workers/radar.py +++ b/workers/radar.py @@ -2,44 +2,47 @@ import json import urllib.parse from classes import * + def getRadar(): - return HTTPClient().get("http://zugradar.oebb.at/bin/query.exe/dny?look_minx=-180000000&look_maxx=180000000&look_miny=-90000000&look_maxy=90000000&tpl=trains2json2&look_json=yes&performLocating=1&look_nv=get_zntrainname|no|attr|81|get_rtonly|yes|zugposmode|2|interval|30000|intervalstep|2000|maxnumberoftrains|500000000000|").text + return HTTPClient().get("http://zugradar.oebb.at/bin/query.exe/dny?look_minx=-180000000&look_maxx=180000000&look_miny=-90000000&look_maxy=90000000&tpl=trains2json2&look_json=yes&performLocating=1&look_nv=get_zntrainname|no|attr|81|get_rtonly|yes|zugposmode|2|interval|30000|intervalstep|2000|maxnumberoftrains|500000000000|").text -def getTrains(names = None): - trains = json.loads(getRadar())["t"] - for train in trains: - name = " ".join(train["n"].split()) + +def getTrains(names=None): + trains = json.loads(getRadar())["t"] + for train in trains: + name = " ".join(train["n"].split()) # destination = workers.conn.getStation(train["l"]) - destination = train["l"] - xcoord = train["x"] - ycoord = train["y"] - prodclass = train["c"] - tid = train["i"] + destination = train["l"] + xcoord = train["x"] + ycoord = train["y"] + prodclass = train["c"] + tid = train["i"] - find = False if names else True + find = False if names else True - if not find: - for cname in names: - if cname.lower().replace(" ", "") == name.split("-")[0].lower().replace(" ", "") or name.lower().replace(" ", "").startswith(cname.lower().replace(" ", "")): - find = True + if not find: + for cname in names: + if cname.lower().replace(" ", "") == name.split("-")[0].lower().replace(" ", "") or name.lower().replace(" ", "").startswith(cname.lower().replace(" ", "")): + find = True - if find: - yield Train(name = name, dest = destination, xcoord = xcoord, ycoord = ycoord, prodclass = prodclass, tid = tid) + if find: + yield Train(name=name, dest=destination, xcoord=xcoord, ycoord=ycoord, prodclass=prodclass, tid=tid) -def worker(trains = None, json = False): - outtext = """{ + +def worker(trains=None, json=False): + outtext = """{ "trains": [ """ if json else """ """ - for train in getTrains(trains): - outtext += ",\n" if (json and not outtext.strip()[-1] == "[") else "" - outtext += train.json(2) if json else train.xml(1) - outtext += "\n" if not json else "" + for train in getTrains(trains): + outtext += ",\n" if (json and not outtext.strip()[-1] == "[") else "" + outtext += train.json(2) if json else train.xml(1) + outtext += "\n" if not json else "" - outtext += """ + outtext += """ ] }""" if json else "" - return outtext + return outtext diff --git a/workers/val.py b/workers/val.py index 632a22f..97157e4 100644 --- a/workers/val.py +++ b/workers/val.py @@ -2,40 +2,43 @@ import json import urllib.parse from classes import * + def getValidator(name): - data = HTTPClient().get("http://scotty.oebb.at/bin/ajax-getstop.exe/dn?REQ0JourneyStopsS0A=255&REQ0JourneyStopsB=12&S='%s'?&js=true&" % urllib.parse.quote(name.encode("latin-1"))).text - return "=".join(data.split("=")[1:]).split(";")[0] + data = HTTPClient().get("http://scotty.oebb.at/bin/ajax-getstop.exe/dn?REQ0JourneyStopsS0A=255&REQ0JourneyStopsB=12&S='%s'?&js=true&" % + urllib.parse.quote(name.encode("latin-1"))).text + return "=".join(data.split("=")[1:]).split(";")[0] + def validateName(name): - stations = json.loads(getValidator(name)) - for station in stations["suggestions"]: - name = station["value"] - sttype = station["type"] - try: - extid = station["extId"] - except: - extid = None - xcoord = station["xcoord"] - ycoord = station["ycoord"] - prodclass = station["prodClass"] + stations = json.loads(getValidator(name)) + for station in stations["suggestions"]: + name = station["value"] + sttype = station["type"] + try: + extid = station["extId"] + except: + extid = None + xcoord = station["xcoord"] + ycoord = station["ycoord"] + prodclass = station["prodClass"] - yield Station(name = name, sttype = sttype, extid = extid, xcoord = xcoord, ycoord = ycoord, prodclass = prodclass) + yield Station(name=name, sttype=sttype, extid=extid, xcoord=xcoord, ycoord=ycoord, prodclass=prodclass) -def worker(name, json = False): - outtext = """{ + +def worker(name, json=False): + outtext = """{ "stations": [ """ if json else """ """ - for station in validateName(name): - outtext += ",\n" if (json and not outtext.strip()[-1] == "[") else "" - outtext += station.json(2) if json else station.xml(1) - outtext += "\n" if not json else "" + for station in validateName(name): + outtext += ",\n" if (json and not outtext.strip()[-1] == "[") else "" + outtext += station.json(2) if json else station.xml(1) + outtext += "\n" if not json else "" - outtext += """ + outtext += """ ] }""" if json else "" - return outtext - + return outtext