autopep8 everything - how could I ever work like this?

This commit is contained in:
Kumi 2022-04-19 15:01:03 +02:00
parent ffa4b29637
commit 6a8a614b3d
Signed by: kumi
GPG key ID: 5D1CE6AF1805ECA2
13 changed files with 983 additions and 829 deletions

View file

@ -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 + "<connection%s>\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 + \
"<connection%s>\n" % ("" if cid is False else " id=\"%i\"" % cid)
if frm and self.depst():
out += " " * indent + " <from>\n"
out += self.depst().xml(indent + 2, **stationkwargs) + "\n"
out += " " * indent + " </from>\n"
if frm and self.depst():
out += " " * indent + " <from>\n"
out += self.depst().xml(indent + 2, **stationkwargs) + "\n"
out += " " * indent + " </from>\n"
if via and self.via:
out += " " * indent + " <via>\n"
for vst in self.via:
out += vst.xml(indent + 2, **stationkwargs) + "\n"
if via and self.via:
out += " " * indent + " <via>\n"
out += " " * indent + " </via>\n"
for vst in self.via:
out += vst.xml(indent + 2, **stationkwargs) + "\n"
if to and self.arrst():
out += " " * indent + " <to>\n"
out += self.arrst().xml(indent + 2, **stationkwargs) + "\n"
out += " " * indent + " </to>\n"
out += " " * indent + " </via>\n"
if (deptime and self.deptime()) or (arrtime and self.arrtime()) or (duration and self.duration()) or (changes and self.changes()):
out += " " * indent + " <details>\n"
if to and self.arrst():
out += " " * indent + " <to>\n"
out += self.arrst().xml(indent + 2, **stationkwargs) + "\n"
out += " " * indent + " </to>\n"
if deptime and self.deptime():
out += " " * indent + " <departure>\n"
out += " " * indent + " <date>%s</date>\n" % datetime.datetime.strftime(self.deptime(), "%d.%m.%Y")
out += " " * indent + " <time>%s</time>\n" % datetime.datetime.strftime(self.deptime(), "%H:%M")
out += " " * indent + " </departure>\n"
if (deptime and self.deptime()) or (arrtime and self.arrtime()) or (duration and self.duration()) or (changes and self.changes()):
out += " " * indent + " <details>\n"
if arrtime and self.arrtime():
out += " " * indent + " <arrival>\n"
out += " " * indent + " <date>%s</date>\n" % datetime.datetime.strftime(self.arrtime(), "%d.%m.%Y")
out += " " * indent + " <time>%s</time>\n" % datetime.datetime.strftime(self.arrtime(), "%H:%M")
out += " " * indent + " </arrival>\n"
if deptime and self.deptime():
out += " " * indent + " <departure>\n"
out += " " * indent + \
" <date>%s</date>\n" % datetime.datetime.strftime(
self.deptime(), "%d.%m.%Y")
out += " " * indent + \
" <time>%s</time>\n" % datetime.datetime.strftime(
self.deptime(), "%H:%M")
out += " " * indent + " </departure>\n"
out += (" " * indent + " <duration>%s</duration>\n" % self.durationString()) if duration and self.duration() else ""
out += (" " * indent + " <changes>%i</changes>\n" % self.changes()) if changes and self.changes() else ""
if arrtime and self.arrtime():
out += " " * indent + " <arrival>\n"
out += " " * indent + \
" <date>%s</date>\n" % datetime.datetime.strftime(
self.arrtime(), "%d.%m.%Y")
out += " " * indent + \
" <time>%s</time>\n" % datetime.datetime.strftime(
self.arrtime(), "%H:%M")
out += " " * indent + " </arrival>\n"
out += " " * indent + " </details>\n"
out += (" " * indent + " <duration>%s</duration>\n" %
self.durationString()) if duration and self.duration() else ""
out += (" " * indent + " <changes>%i</changes>\n" %
self.changes()) if changes and self.changes() else ""
if services and self.services:
out += " " * indent + " <services>\n"
out += " " * indent + " </details>\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 + " <services>\n"
out += " " * indent + " </services>\n"
out += " " * indent + "</connection>"
for i in range(len(self.services)):
out += self.services[i].xml(indent + 2,
i, **servicekwargs) + "\n"
return out
out += " " * indent + " </services>\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 + "</connection>"
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

View file

@ -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)"}

View file

@ -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 = "<h1>400 Bad Request</h1>\n"
output += "Only one (validate) or two (conn) arguments may be passed as path."
raise InvalidArgumentException(output)
if len(split) > 2:
output = "<h1>400 Bad Request</h1>\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 = "<h1>400 Bad Request</h1>\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 = "<h1>400 Bad Request</h1>\n"
output += "A request type must be provided."
raise InvalidArgumentException(output)

View file

@ -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

View file

@ -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 + "<service%s>\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 + \
"<service%s>\n" % ("" if iid is False else " id=\"%i\"" % iid)
out += (" " * indent + " <name>%s</name>\n" % self.name) if name else ""
out += (" " * indent + " <name>%s</name>\n" %
self.name) if name else ""
if dest and self.dest:
out += " " * indent + " <destination>\n"
out += self.dest.xml(indent + 2, **stationkwargs) + "\n"
out += " " * indent + " </destination>\n"
if dest and self.dest:
out += " " * indent + " <destination>\n"
out += self.dest.xml(indent + 2, **stationkwargs) + "\n"
out += " " * indent + " </destination>\n"
if depst or deptime or deppf or currdep:
out += " " * indent + " <departure>\n"
if depst or deptime or deppf or currdep:
out += " " * indent + " <departure>\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 + " <date>%s</date>\n" % datetime.datetime.strftime(self.deptime, "%d.%m.%Y")
out += " " * indent + " <time>%s</time>\n" % datetime.datetime.strftime(self.deptime, "%H:%M")
if deptime:
out += " " * indent + \
" <date>%s</date>\n" % datetime.datetime.strftime(
self.deptime, "%d.%m.%Y")
out += " " * indent + \
" <time>%s</time>\n" % datetime.datetime.strftime(
self.deptime, "%H:%M")
out += (" " * indent + " <current>%s</current>\n" % self.currdep) if currdep and self.currdep else ""
out += (" " * indent + " <platform>%s</platform>\n" % self.deppf) if deppf and self.deppf else ""
out += " " * indent + " </departure>\n"
out += (" " * indent + " <current>%s</current>\n" %
self.currdep) if currdep and self.currdep else ""
out += (" " * indent + " <platform>%s</platform>\n" %
self.deppf) if deppf and self.deppf else ""
if arrst or arrtime or arrpf or curarr:
out += " " * indent + " <arrival>\n"
out += " " * indent + " </departure>\n"
out += (self.arrst.xml(indent + 2, **stationkwargs) + "\n") if arrst else ""
if arrst or arrtime or arrpf or curarr:
out += " " * indent + " <arrival>\n"
if arrtime:
out += " " * indent + " <date>%s</date>\n" % datetime.datetime.strftime(self.arrtime, "%d.%m.%Y")
out += " " * indent + " <time>%s</time>\n" % datetime.datetime.strftime(self.arrtime, "%H:%M")
out += (self.arrst.xml(indent + 2, **stationkwargs) +
"\n") if arrst else ""
out += (" " * indent + " <current>%s</current>\n" % self.curarr) if curarr and self.curarr else ""
out += (" " * indent + " <platform>%s</platform>\n" % self.arrpf) if arrpf and self.arrpf else ""
if arrtime:
out += " " * indent + \
" <date>%s</date>\n" % datetime.datetime.strftime(
self.arrtime, "%d.%m.%Y")
out += " " * indent + \
" <time>%s</time>\n" % datetime.datetime.strftime(
self.arrtime, "%H:%M")
out += " " * indent + " </arrival>\n"
out += (" " * indent + " <current>%s</current>\n" %
self.curarr) if curarr and self.curarr else ""
out += (" " * indent + " <platform>%s</platform>\n" %
self.arrpf) if arrpf and self.arrpf else ""
out += " " * indent + "</service>"
out += " " * indent + " </arrival>\n"
return out
out += " " * indent + "</service>"
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

View file

@ -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 + "<station>\n"
def xml(self, indent=0, name=True, extid=True, sttype=False, coords=False, prodclass=False, distance=False, services=False, servicekwargs={}):
out = " " * indent + "<station>\n"
out += (" " * indent + " <name>%s</name>\n" % self.name) if name else ""
out += (" " * indent + " <id>%s</id>\n" % self.useId()) if extid else ""
out += (" " * indent + " <distance>%i</distance>\n" % int(self.distance)) if distance else ""
out += (" " * indent + " <type>%s</type>\n" % self.sttype) if sttype else ""
out += (" " * indent + " <name>%s</name>\n" %
self.name) if name else ""
out += (" " * indent + " <id>%s</id>\n" %
self.useId()) if extid else ""
out += (" " * indent + " <distance>%i</distance>\n" %
int(self.distance)) if distance else ""
out += (" " * indent + " <type>%s</type>\n" %
self.sttype) if sttype else ""
if coords and self.xcoord:
out += " " * indent + " <coords>\n"
out += " " * indent + " <lon>%f</lon>\n" % self.xcoord
out += " " * indent + " <lat>%f</lat>\n" % self.ycoord
out += " " * indent + " </coords>\n"
if coords and self.xcoord:
out += " " * indent + " <coords>\n"
out += " " * indent + " <lon>%f</lon>\n" % self.xcoord
out += " " * indent + " <lat>%f</lat>\n" % self.ycoord
out += " " * indent + " </coords>\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].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 + " </services>\n"
out += " " * indent + " </services>\n"
out += (" " * indent + " <prodclass>%s</prodclass>\n" % self.prodclass) if prodclass else ""
out += (" " * indent + " <prodclass>%s</prodclass>\n" %
self.prodclass) if prodclass else ""
out += " " * indent + "</station>"
return out
out += " " * indent + "</station>"
return out

View file

@ -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 + "<train>\n"
def xml(self, indent=0, name=True, tid=True, dest=True, coords=True, prodclass=False, stationkwargs={}):
out = " " * indent + "<train>\n"
out += (" " * indent + " <name>%s</name>\n" % self.name) if name else ""
out += (" " * indent + " <id>%s</id>\n" % self.tid) if tid else ""
out += (" " * indent + " <name>%s</name>\n" %
self.name) if name else ""
out += (" " * indent + " <id>%s</id>\n" % self.tid) if tid else ""
if dest:
# out += " " * indent + " <destination>\n"
# out += self.dest.xml(indent + 2, **stationkwargs) + "\n"
# out += " " * indent + " </destination>\n"
out += " " * indent + " <destination>%s</destination>\n" % self.dest
if dest:
# out += " " * indent + " <destination>\n"
# out += self.dest.xml(indent + 2, **stationkwargs) + "\n"
# out += " " * indent + " </destination>\n"
out += " " * indent + " <destination>%s</destination>\n" % self.dest
if coords:
out += " " * indent + " <coords>\n"
out += " " * indent + " <lon>%f</lon>\n" % self.xcoord
out += " " * indent + " <lat>%f</lat>\n" % self.ycoord
out += " " * indent + " </coords>\n"
if coords:
out += " " * indent + " <coords>\n"
out += " " * indent + " <lon>%f</lon>\n" % self.xcoord
out += " " * indent + " <lat>%f</lat>\n" % self.ycoord
out += " " * indent + " </coords>\n"
out += (" " * indent + " <prodclass>%s</prodclass>\n" % self.prodclass) if prodclass else ""
out += (" " * indent + " <prodclass>%s</prodclass>\n" %
self.prodclass) if prodclass else ""
out += " " * indent + "</train>"
return out
out += " " * indent + "</train>"
return out

339
main.py
View file

@ -24,211 +24,228 @@ XML = "text/xml; charset=UTF-8"
DOCSTR = ' Check out the <a href="https://kumig.it/kumitterer/oebb_py#request">documentation</a> 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 = "<h1>400 Bad Request</h1>\n"
content += "\"from\"and \"to\" values are required for this type of request."
return Response(HTTP400, HTML, content)
except Exception:
content = "<h1>400 Bad Request</h1>\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 = "<h1>400 Bad Request</h1>\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 = "<h1>400 Bad Request</h1>\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 = "<h1>400 Bad Request</h1>\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 = "<h1>400 Bad Request</h1>\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 = "<h1>400 Bad Request</h1>\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 = "<h1>400 Bad Request</h1>\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 = "<h1>500 Internal Server Error</h1>\n"
if "debug" in req.args:
content += traceback.format_exc().replace("\n", "<br />")
return Response(HTTP500, HTML, content)
try:
content = workers.conn.worker(frm, to, count, outtime, mode, details, req.json, via)
except Exception as e:
content = "<h1>500 Internal Server Error</h1>\n"
if "debug" in req.args:
content += traceback.format_exc().replace("\n", "<br />")
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 = "<h1>400 Bad Request</h1>\n"
content += "A \"name\" value is required for this type of request."
return Response(HTTP400, HTML, content)
except Exception:
content = "<h1>400 Bad Request</h1>\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 = "<h1>500 Internal Server Error</h1>\n"
if "debug" in req.args:
content += traceback.format_exc().replace("\n", "<br />")
return Response(HTTP500, HTML, content)
except Exception as e:
content = "<h1>500 Internal Server Error</h1>\n"
if "debug" in req.args:
content += traceback.format_exc().replace("\n", "<br />")
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 = "<h1>400 Bad Request</h1>\n"
content += "\"lat\" and \"lon\" values are required for this type of request."
return Response(HTTP400, HTML, content)
except:
content = "<h1>400 Bad Request</h1>\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 = "<h1>400 Bad Request</h1>\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 = "<h1>400 Bad Request</h1>\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 = "<h1>500 Internal Server Error</h1>"
if "debug" in req.args:
content += traceback.format_exc().replace("\n", "<br />")
return Response(HTTP500, HTML, content)
except Exception as e:
content = "<h1>500 Internal Server Error</h1>"
if "debug" in req.args:
content += traceback.format_exc().replace("\n", "<br />")
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 = "<h1>500 Internal Server Error</h1>\n"
if "debug" in req.args:
content += traceback.format_exc().replace("\n", "<br />")
return Response(HTTP500, HTML, content)
try:
content = workers.radar.worker(trains, req.json)
except Exception as e:
content = "<h1>500 Internal Server Error</h1>\n"
if "debug" in req.args:
content += traceback.format_exc().replace("\n", "<br />")
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 = "<h1>400 Bad Request</h1>\n"
content += "A \"name\" value is required for this type of request."
return Response(HTTP400, HTML, content)
except Exception:
content = "<h1>400 Bad Request</h1>\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 = "<h1>400 Bad Request</h1>\n"
content += "The \"count\" value must be a numeric value."
return Response(HTTP400, HTML, content)
try:
count = int(count)
except:
content = "<h1>400 Bad Request</h1>\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 = "<h1>400 Bad Request</h1>\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 = "<h1>400 Bad Request</h1>\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 = "<h1>500 Internal Server Error</h1>\n"
if "debug" in req.args:
content += traceback.format_exc().replace("\n", "<br />")
return Response(HTTP500, HTML, content)
try:
content = workers.deparr.worker(
name, count, outtime, mode, details, req.json)
except Exception as e:
content = "<h1>500 Internal Server Error</h1>\n"
if "debug" in req.args:
content += traceback.format_exc().replace("\n", "<br />")
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 = "<h1>400 Bad Request</h1>"
content += "The request type you submitted is invalid."
return Response(HTTP400, HTML, content)
content = "<h1>400 Bad Request</h1>"
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

View file

@ -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 """<?xml version="1.0" encoding="UTF-8"?>
<stations>
"""
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 "</stations>"
return outtext
return outtext

View file

@ -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, "&timesel=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, "&timesel=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 = """<?xml version="1.0" encoding="UTF-8"?>
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 = """<?xml version="1.0" encoding="UTF-8"?>
<connections>
""" 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 += "</connections>" if not json else " ]\n}"
output += "</connections>" if not json else " ]\n}"
return output
return output

View file

@ -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 = """<?xml version="1.0" encoding="UTF-8"?>\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 = """<?xml version="1.0" encoding="UTF-8"?>\n"""
output += station.xml(services=True)
return output

View file

@ -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 """<?xml version="1.0" encoding="UTF-8"?>
<trains>
"""
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 "</trains>"
return outtext
return outtext

View file

@ -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 """<?xml version="1.0" encoding="UTF-8"?>
<stations>
"""
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 "</stations>"
return outtext
return outtext