autopep8 everything - how could I ever work like this?
This commit is contained in:
parent
ffa4b29637
commit
6a8a614b3d
|
@ -1,177 +1,202 @@
|
||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
|
|
||||||
class Connection:
|
class Connection:
|
||||||
def __init__(self, details = False):
|
def __init__(self, details=False):
|
||||||
self.services = []
|
self.services = []
|
||||||
self.details = details
|
self.details = details
|
||||||
self.via = []
|
self.via = []
|
||||||
|
|
||||||
def addService(self, service):
|
def addService(self, service):
|
||||||
self.services.append(service)
|
self.services.append(service)
|
||||||
|
|
||||||
def addVia(self, station):
|
def addVia(self, station):
|
||||||
self.via.append(station)
|
self.via.append(station)
|
||||||
|
|
||||||
def depst(self):
|
def depst(self):
|
||||||
try:
|
try:
|
||||||
return self.services[0].depst
|
return self.services[0].depst
|
||||||
except:
|
except:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def arrst(self):
|
def arrst(self):
|
||||||
try:
|
try:
|
||||||
return self.services[-1].arrst
|
return self.services[-1].arrst
|
||||||
except:
|
except:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def deptime(self):
|
def deptime(self):
|
||||||
try:
|
try:
|
||||||
return self.services[0].deptime
|
return self.services[0].deptime
|
||||||
except:
|
except:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def arrtime(self):
|
def arrtime(self):
|
||||||
try:
|
try:
|
||||||
return self.services[-1].arrtime
|
return self.services[-1].arrtime
|
||||||
except:
|
except:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def currdep(self):
|
def currdep(self):
|
||||||
try:
|
try:
|
||||||
return self.services[0].currdep
|
return self.services[0].currdep
|
||||||
except:
|
except:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def currarr(self):
|
def currarr(self):
|
||||||
try:
|
try:
|
||||||
return self.services[-1].currarr
|
return self.services[-1].currarr
|
||||||
except:
|
except:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def duration(self):
|
def duration(self):
|
||||||
try:
|
try:
|
||||||
return self.services[-1].arrtime - self.services[0].deptime
|
return self.services[-1].arrtime - self.services[0].deptime
|
||||||
except:
|
except:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def durationString(self):
|
def durationString(self):
|
||||||
hrs, scs = divmod(self.duration().total_seconds(), 3600)
|
hrs, scs = divmod(self.duration().total_seconds(), 3600)
|
||||||
mns, rmd = divmod(scs, 60)
|
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):
|
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)
|
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 = {}):
|
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)
|
out = " " * indent + \
|
||||||
|
"<connection%s>\n" % ("" if cid is False else " id=\"%i\"" % cid)
|
||||||
|
|
||||||
if frm and self.depst():
|
if frm and self.depst():
|
||||||
out += " " * indent + " <from>\n"
|
out += " " * indent + " <from>\n"
|
||||||
out += self.depst().xml(indent + 2, **stationkwargs) + "\n"
|
out += self.depst().xml(indent + 2, **stationkwargs) + "\n"
|
||||||
out += " " * indent + " </from>\n"
|
out += " " * indent + " </from>\n"
|
||||||
|
|
||||||
if via and self.via:
|
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"
|
|
||||||
|
|
||||||
out += " " * indent + " </via>\n"
|
for vst in self.via:
|
||||||
|
out += vst.xml(indent + 2, **stationkwargs) + "\n"
|
||||||
|
|
||||||
if to and self.arrst():
|
out += " " * indent + " </via>\n"
|
||||||
out += " " * indent + " <to>\n"
|
|
||||||
out += self.arrst().xml(indent + 2, **stationkwargs) + "\n"
|
|
||||||
out += " " * indent + " </to>\n"
|
|
||||||
|
|
||||||
if (deptime and self.deptime()) or (arrtime and self.arrtime()) or (duration and self.duration()) or (changes and self.changes()):
|
if to and self.arrst():
|
||||||
out += " " * indent + " <details>\n"
|
out += " " * indent + " <to>\n"
|
||||||
|
out += self.arrst().xml(indent + 2, **stationkwargs) + "\n"
|
||||||
|
out += " " * indent + " </to>\n"
|
||||||
|
|
||||||
if deptime and self.deptime():
|
if (deptime and self.deptime()) or (arrtime and self.arrtime()) or (duration and self.duration()) or (changes and self.changes()):
|
||||||
out += " " * indent + " <departure>\n"
|
out += " " * indent + " <details>\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 arrtime and self.arrtime():
|
if deptime and self.deptime():
|
||||||
out += " " * indent + " <arrival>\n"
|
out += " " * indent + " <departure>\n"
|
||||||
out += " " * indent + " <date>%s</date>\n" % datetime.datetime.strftime(self.arrtime(), "%d.%m.%Y")
|
out += " " * indent + \
|
||||||
out += " " * indent + " <time>%s</time>\n" % datetime.datetime.strftime(self.arrtime(), "%H:%M")
|
" <date>%s</date>\n" % datetime.datetime.strftime(
|
||||||
out += " " * indent + " </arrival>\n"
|
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 ""
|
if arrtime and self.arrtime():
|
||||||
out += (" " * indent + " <changes>%i</changes>\n" % self.changes()) if changes and self.changes() else ""
|
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 + " </details>\n"
|
||||||
out += " " * indent + " <services>\n"
|
|
||||||
|
|
||||||
for i in range(len(self.services)):
|
if services and self.services:
|
||||||
out += self.services[i].xml(indent + 2, i, **servicekwargs) + "\n"
|
out += " " * indent + " <services>\n"
|
||||||
|
|
||||||
out += " " * indent + " </services>\n"
|
for i in range(len(self.services)):
|
||||||
|
out += self.services[i].xml(indent + 2,
|
||||||
out += " " * indent + "</connection>"
|
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 + "</connection>"
|
||||||
out = " " * indent + "{\n"
|
|
||||||
|
|
||||||
out += (" " * indent + " \"@id\": %i,\n" % cid) if cid is not False else ""
|
return out
|
||||||
|
|
||||||
if frm and self.depst():
|
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 + " \"from\":\n"
|
out = " " * indent + "{\n"
|
||||||
out += self.depst().json(indent + 2, **stationkwargs) + ",\n"
|
|
||||||
|
|
||||||
if via and self.via:
|
out += (" " * indent + " \"@id\": %i,\n" %
|
||||||
out += " " * indent + " \"via\": [\n"
|
cid) if cid is not False else ""
|
||||||
|
|
||||||
for vst in self.via:
|
if frm and self.depst():
|
||||||
out += vst.json(indent + 3, **stationkwargs) + ",\n"
|
out += " " * indent + " \"from\":\n"
|
||||||
|
out += self.depst().json(indent + 2, **stationkwargs) + ",\n"
|
||||||
|
|
||||||
out = "".join(out.rsplit(",", 1))
|
if via and self.via:
|
||||||
out += " " * indent + " ],\n"
|
out += " " * indent + " \"via\": [\n"
|
||||||
|
|
||||||
if to and self.arrst():
|
for vst in self.via:
|
||||||
out += " " * indent + " \"to\":\n"
|
out += vst.json(indent + 3, **stationkwargs) + ",\n"
|
||||||
out += self.arrst().json(indent + 2, **stationkwargs) + ",\n"
|
|
||||||
|
|
||||||
if (deptime and self.deptime()) or (arrtime and self.arrtime()) or (duration and self.duration()) or (changes and self.changes()):
|
out = "".join(out.rsplit(",", 1))
|
||||||
det = ""
|
out += " " * indent + " ],\n"
|
||||||
det += " " * indent + " \"details\": {\n"
|
|
||||||
|
|
||||||
if deptime and self.deptime():
|
if to and self.arrst():
|
||||||
det += " " * indent + " \"departure\": {\n"
|
out += " " * indent + " \"to\":\n"
|
||||||
det += " " * indent + " \"date\": \"%s\",\n" % datetime.datetime.strftime(self.deptime(), "%d.%m.%Y")
|
out += self.arrst().json(indent + 2, **stationkwargs) + ",\n"
|
||||||
det += " " * indent + " \"time\": \"%s\"\n" % datetime.datetime.strftime(self.deptime(), "%H:%M")
|
|
||||||
det += " " * indent + " },\n"
|
|
||||||
|
|
||||||
if arrtime and self.arrtime():
|
if (deptime and self.deptime()) or (arrtime and self.arrtime()) or (duration and self.duration()) or (changes and self.changes()):
|
||||||
det += " " * indent + " \"arrival\": {\n"
|
det = ""
|
||||||
det += " " * indent + " \"date\": \"%s\",\n" % datetime.datetime.strftime(self.arrtime(), "%d.%m.%Y")
|
det += " " * indent + " \"details\": {\n"
|
||||||
det += " " * indent + " \"time\": \"%s\"\n"% datetime.datetime.strftime(self.arrtime(), "%H:%M")
|
|
||||||
det += " " * indent + " },\n"
|
|
||||||
|
|
||||||
det += (" " * indent + " \"duration\": \"%s\",\n" % self.durationString()) if duration and self.duration() else ""
|
if deptime and self.deptime():
|
||||||
det += (" " * indent + " \"changes\": %i,\n" % self.changes()) if changes and self.changes() else ""
|
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))
|
if arrtime and self.arrtime():
|
||||||
out += det
|
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:
|
det = "".join(det.rsplit(",", 1))
|
||||||
out += " " * indent + " \"services\": [\n"
|
out += det
|
||||||
|
|
||||||
for i in range(len(self.services)):
|
out += " " * indent + " },\n"
|
||||||
out += self.services[i].json(indent + 2, i, **servicekwargs) + (",\n" if not i == len(self.services) - 1 else "\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
|
||||||
|
|
|
@ -1,7 +1,8 @@
|
||||||
import requests
|
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)"}
|
||||||
|
|
|
@ -1,57 +1,60 @@
|
||||||
try:
|
try:
|
||||||
from urllib.parse import parse_qs
|
from urllib.parse import parse_qs
|
||||||
except ImportError:
|
except ImportError:
|
||||||
from cgi import parse_qs
|
from cgi import parse_qs
|
||||||
|
|
||||||
|
|
||||||
class IllegalMethodException(BaseException):
|
class IllegalMethodException(BaseException):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class InvalidArgumentException(BaseException):
|
class InvalidArgumentException(BaseException):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class Request:
|
class Request:
|
||||||
def __init__(self, env = None):
|
def __init__(self, env=None):
|
||||||
if env:
|
if env:
|
||||||
self.fromEnv(env)
|
self.fromEnv(env)
|
||||||
|
|
||||||
def fromEnv(self, env):
|
def fromEnv(self, env):
|
||||||
if env["REQUEST_METHOD"] == "POST":
|
if env["REQUEST_METHOD"] == "POST":
|
||||||
self.args = parse_qs(env['wsgi.input'].readline().decode(), True)
|
self.args = parse_qs(env['wsgi.input'].readline().decode(), True)
|
||||||
elif env["REQUEST_METHOD"] == "GET":
|
elif env["REQUEST_METHOD"] == "GET":
|
||||||
self.args = parse_qs(env['QUERY_STRING'], True)
|
self.args = parse_qs(env['QUERY_STRING'], True)
|
||||||
else:
|
else:
|
||||||
raise IllegalMethodException()
|
raise IllegalMethodException()
|
||||||
|
|
||||||
self.conn = False
|
self.conn = False
|
||||||
self.val = False
|
self.val = False
|
||||||
self.cfrm = None
|
self.cfrm = None
|
||||||
self.cto = None
|
self.cto = None
|
||||||
|
|
||||||
self.json = "json" in self.args
|
self.json = "json" in self.args
|
||||||
|
|
||||||
split = env["PATH_INFO"].split("/")
|
split = env["PATH_INFO"].split("/")
|
||||||
split = [i.strip() for i in split]
|
split = [i.strip() for i in split]
|
||||||
|
|
||||||
while "" in split:
|
while "" in split:
|
||||||
split.remove("")
|
split.remove("")
|
||||||
|
|
||||||
if len(split) > 2:
|
if len(split) > 2:
|
||||||
output = "<h1>400 Bad Request</h1>\n"
|
output = "<h1>400 Bad Request</h1>\n"
|
||||||
output += "Only one (validate) or two (conn) arguments may be passed as path."
|
output += "Only one (validate) or two (conn) arguments may be passed as path."
|
||||||
raise InvalidArgumentException(output)
|
raise InvalidArgumentException(output)
|
||||||
|
|
||||||
if len(split) > 0:
|
if len(split) > 0:
|
||||||
if len(split) == 1:
|
if len(split) == 1:
|
||||||
self.val = True
|
self.val = True
|
||||||
else:
|
else:
|
||||||
self.conn = True
|
self.conn = True
|
||||||
self.cto = split[1].encode("latin-1").decode("utf-8")
|
self.cto = split[1].encode("latin-1").decode("utf-8")
|
||||||
self.cfrm = split[0].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)
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
class Response:
|
class Response:
|
||||||
def __init__(self, status, ctype, content):
|
def __init__(self, status, ctype, content):
|
||||||
self.status = status
|
self.status = status
|
||||||
self.ctype = ctype
|
self.ctype = ctype
|
||||||
self.content = content
|
self.content = content
|
||||||
|
|
|
@ -1,110 +1,140 @@
|
||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
|
|
||||||
class Service:
|
class Service:
|
||||||
def __init__(self, name, depst, deptime, arrst, arrtime, dest = None, deppf = None, currdep = None, arrpf = None, curarr = None):
|
def __init__(self, name, depst, deptime, arrst, arrtime, dest=None, deppf=None, currdep=None, arrpf=None, curarr=None):
|
||||||
self.name = name
|
self.name = name
|
||||||
self.dest = dest
|
self.dest = dest
|
||||||
self.depst = depst
|
self.depst = depst
|
||||||
self.deptime = deptime
|
self.deptime = deptime
|
||||||
self.arrst = arrst
|
self.arrst = arrst
|
||||||
self.arrtime = arrtime
|
self.arrtime = arrtime
|
||||||
self.deppf = deppf
|
self.deppf = deppf
|
||||||
self.currdep = currdep
|
self.currdep = currdep
|
||||||
self.arrpf = arrpf
|
self.arrpf = arrpf
|
||||||
self.curarr = curarr
|
self.curarr = curarr
|
||||||
|
|
||||||
def duration(self):
|
def duration(self):
|
||||||
return self.arrtime - self.deptime
|
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 = {}):
|
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 + \
|
||||||
|
"<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:
|
if dest and self.dest:
|
||||||
out += " " * indent + " <destination>\n"
|
out += " " * indent + " <destination>\n"
|
||||||
out += self.dest.xml(indent + 2, **stationkwargs) + "\n"
|
out += self.dest.xml(indent + 2, **stationkwargs) + "\n"
|
||||||
out += " " * indent + " </destination>\n"
|
out += " " * indent + " </destination>\n"
|
||||||
|
|
||||||
if depst or deptime or deppf or currdep:
|
if depst or deptime or deppf or currdep:
|
||||||
out += " " * indent + " <departure>\n"
|
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:
|
if deptime:
|
||||||
out += " " * indent + " <date>%s</date>\n" % datetime.datetime.strftime(self.deptime, "%d.%m.%Y")
|
out += " " * indent + \
|
||||||
out += " " * indent + " <time>%s</time>\n" % datetime.datetime.strftime(self.deptime, "%H:%M")
|
" <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 + " <current>%s</current>\n" %
|
||||||
out += (" " * indent + " <platform>%s</platform>\n" % self.deppf) if deppf and self.deppf else ""
|
self.currdep) if currdep and self.currdep else ""
|
||||||
|
out += (" " * indent + " <platform>%s</platform>\n" %
|
||||||
out += " " * indent + " </departure>\n"
|
self.deppf) if deppf and self.deppf else ""
|
||||||
|
|
||||||
if arrst or arrtime or arrpf or curarr:
|
out += " " * indent + " </departure>\n"
|
||||||
out += " " * indent + " <arrival>\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 += (self.arrst.xml(indent + 2, **stationkwargs) +
|
||||||
out += " " * indent + " <date>%s</date>\n" % datetime.datetime.strftime(self.arrtime, "%d.%m.%Y")
|
"\n") if arrst else ""
|
||||||
out += " " * indent + " <time>%s</time>\n" % datetime.datetime.strftime(self.arrtime, "%H:%M")
|
|
||||||
|
|
||||||
out += (" " * indent + " <current>%s</current>\n" % self.curarr) if curarr and self.curarr else ""
|
if arrtime:
|
||||||
out += (" " * indent + " <platform>%s</platform>\n" % self.arrpf) if arrpf and self.arrpf else ""
|
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 = {}):
|
return out
|
||||||
out = " " * indent + "{\n"
|
|
||||||
|
|
||||||
out += (" " * indent + " \"@id\": %i,\n" % iid) if iid is not False 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 + " \"name\": \"%s\",\n" % self.name) if name else ""
|
out = " " * indent + "{\n"
|
||||||
|
|
||||||
if dest and self.dest:
|
out += (" " * indent + " \"@id\": %i,\n" %
|
||||||
out += " " * indent + " \"destination\":\n"
|
iid) if iid is not False else ""
|
||||||
out += self.dest.json(indent + 2, **stationkwargs) + ",\n"
|
out += (" " * indent + " \"name\": \"%s\",\n" %
|
||||||
|
self.name) if name else ""
|
||||||
if depst or deptime or deppf or currdep:
|
|
||||||
dep = " " * indent + " \"departure\": {\n"
|
|
||||||
|
|
||||||
if depst:
|
if dest and self.dest:
|
||||||
dep += " " * indent + " \"station\":\n"
|
out += " " * indent + " \"destination\":\n"
|
||||||
dep += self.depst.json(indent + 3, **stationkwargs) + ",\n"
|
out += self.dest.json(indent + 2, **stationkwargs) + ",\n"
|
||||||
|
|
||||||
if deptime:
|
if depst or deptime or deppf or currdep:
|
||||||
dep += " " * indent + " \"date\": \"%s\",\n" % datetime.datetime.strftime(self.deptime, "%d.%m.%Y")
|
dep = " " * indent + " \"departure\": {\n"
|
||||||
dep += " " * indent + " \"time\": \"%s\",\n" % datetime.datetime.strftime(self.deptime, "%H:%M")
|
|
||||||
|
|
||||||
dep += (" " * indent + " \"current\": \"%s\",\n" % self.currdep) if currdep and self.currdep else ""
|
if depst:
|
||||||
dep += (" " * indent + " \"platform\": \"%s\",\n" % self.deppf) if deppf and self.deppf else ""
|
dep += " " * indent + " \"station\":\n"
|
||||||
|
dep += self.depst.json(indent + 3, **stationkwargs) + ",\n"
|
||||||
|
|
||||||
dep = "".join(dep.rsplit(",", 1))
|
if deptime:
|
||||||
out += dep + " " * indent + " },\n"
|
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:
|
dep += (" " * indent + " \"current\": \"%s\",\n" %
|
||||||
arr = " " * indent + " \"arrival\": {\n"
|
self.currdep) if currdep and self.currdep else ""
|
||||||
|
dep += (" " * indent + " \"platform\": \"%s\",\n" %
|
||||||
|
self.deppf) if deppf and self.deppf else ""
|
||||||
|
|
||||||
if arrst:
|
dep = "".join(dep.rsplit(",", 1))
|
||||||
arr += " " * indent + " \"station\":\n"
|
out += dep + " " * indent + " },\n"
|
||||||
arr += self.arrst.json(indent + 3, **stationkwargs) + ",\n"
|
|
||||||
|
|
||||||
if arrtime:
|
if arrst or arrtime or arrpf or curarr:
|
||||||
arr += " " * indent + " \"date\": \"%s\",\n" % datetime.datetime.strftime(self.arrtime, "%d.%m.%Y")
|
arr = " " * indent + " \"arrival\": {\n"
|
||||||
arr += " " * indent + " \"time\": \"%s\",\n" % datetime.datetime.strftime(self.arrtime, "%H:%M")
|
|
||||||
|
|
||||||
arr += (" " * indent + " \"current\": \"%s\",\n" % self.curarr) if curarr and self.curarr else ""
|
if arrst:
|
||||||
arr += (" " * indent + " \"platform\": \"%s\",\n" % self.arrpf) if arrpf and self.arrpf else ""
|
arr += " " * indent + " \"station\":\n"
|
||||||
|
arr += self.arrst.json(indent + 3, **stationkwargs) + ",\n"
|
||||||
|
|
||||||
arr = "".join(arr.rsplit(",", 1))
|
if arrtime:
|
||||||
out += arr + " " * indent + " },\n"
|
arr += " " * indent + \
|
||||||
|
" \"date\": \"%s\",\n" % datetime.datetime.strftime(
|
||||||
out += " " * indent + "}"
|
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
|
||||||
|
|
|
@ -1,80 +1,91 @@
|
||||||
class Station:
|
class Station:
|
||||||
def __init__(self, name, sttype, extid = None, xcoord = None, ycoord = None, prodclass = None):
|
def __init__(self, name, sttype, extid=None, xcoord=None, ycoord=None, prodclass=None):
|
||||||
self.name = name
|
self.name = name
|
||||||
self.sttype = sttype
|
self.sttype = sttype
|
||||||
self.extid = extid
|
self.extid = extid
|
||||||
self.xcoord = float(xcoord)/1000000 if xcoord else None
|
self.xcoord = float(xcoord)/1000000 if xcoord else None
|
||||||
self.ycoord = float(ycoord)/1000000 if ycoord else None
|
self.ycoord = float(ycoord)/1000000 if ycoord else None
|
||||||
self.prodclass = prodclass
|
self.prodclass = prodclass
|
||||||
self.services = []
|
self.services = []
|
||||||
|
|
||||||
def addService(self, svc):
|
def addService(self, svc):
|
||||||
self.services += [svc]
|
self.services += [svc]
|
||||||
|
|
||||||
def useId(self):
|
def useId(self):
|
||||||
return self.extid or self.name
|
return self.extid or self.name
|
||||||
|
|
||||||
def lat(self):
|
def lat(self):
|
||||||
return self.ycoord
|
return self.ycoord
|
||||||
|
|
||||||
def lon(self):
|
def lon(self):
|
||||||
return self.xcoord
|
return self.xcoord
|
||||||
|
|
||||||
def json(self, indent = 0, name = True, extid = True, sttype = False, coords = False, prodclass = False, distance = False, services = False, servicekwargs = {}):
|
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 + "{\n"
|
||||||
|
|
||||||
out += (" " * indent + " \"name\": \"%s\",\n" % self.name) if name else ""
|
out += (" " * indent + " \"name\": \"%s\",\n" %
|
||||||
out += (" " * indent + " \"id\": \"%s\",\n" % self.useId()) if extid else ""
|
self.name) if name else ""
|
||||||
out += (" " * indent + " \"distance\": %i,\n" % int(self.distance)) if distance else ""
|
out += (" " * indent + " \"id\": \"%s\",\n" %
|
||||||
out += (" " * indent + " \"type\": \"%s\",\n" % self.sttype) if sttype else ""
|
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:
|
if coords and self.xcoord:
|
||||||
out += " " * indent + " \"coords\": {\n"
|
out += " " * indent + " \"coords\": {\n"
|
||||||
out += " " * indent + " \"lon\": %f,\n" % self.xcoord
|
out += " " * indent + " \"lon\": %f,\n" % self.xcoord
|
||||||
out += " " * indent + " \"lat\": %f\n" % self.ycoord
|
out += " " * indent + " \"lat\": %f\n" % self.ycoord
|
||||||
out += " " * indent + " },\n"
|
out += " " * indent + " },\n"
|
||||||
|
|
||||||
if services and self.services:
|
if services and self.services:
|
||||||
out += " " * indent + " \"services\": [\n"
|
out += " " * indent + " \"services\": [\n"
|
||||||
|
|
||||||
for i in range(len(self.services)):
|
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 += 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 = {}):
|
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 + "<station>\n"
|
||||||
|
|
||||||
out += (" " * indent + " <name>%s</name>\n" % self.name) if name else ""
|
out += (" " * indent + " <name>%s</name>\n" %
|
||||||
out += (" " * indent + " <id>%s</id>\n" % self.useId()) if extid else ""
|
self.name) if name else ""
|
||||||
out += (" " * indent + " <distance>%i</distance>\n" % int(self.distance)) if distance else ""
|
out += (" " * indent + " <id>%s</id>\n" %
|
||||||
out += (" " * indent + " <type>%s</type>\n" % self.sttype) if sttype else ""
|
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:
|
if coords and self.xcoord:
|
||||||
out += " " * indent + " <coords>\n"
|
out += " " * indent + " <coords>\n"
|
||||||
out += " " * indent + " <lon>%f</lon>\n" % self.xcoord
|
out += " " * indent + " <lon>%f</lon>\n" % self.xcoord
|
||||||
out += " " * indent + " <lat>%f</lat>\n" % self.ycoord
|
out += " " * indent + " <lat>%f</lat>\n" % self.ycoord
|
||||||
out += " " * indent + " </coords>\n"
|
out += " " * indent + " </coords>\n"
|
||||||
|
|
||||||
if services and self.services:
|
if services and self.services:
|
||||||
out += " " * indent + " <services>\n"
|
out += " " * indent + " <services>\n"
|
||||||
|
|
||||||
for i in range(len(self.services)):
|
for i in range(len(self.services)):
|
||||||
out += self.services[i].xml(indent + 2, i, **servicekwargs) + "\n"
|
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>"
|
out += " " * indent + "</station>"
|
||||||
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
return out
|
||||||
|
|
100
classes/train.py
100
classes/train.py
|
@ -1,69 +1,73 @@
|
||||||
import workers.val
|
import workers.val
|
||||||
|
|
||||||
|
|
||||||
class Train:
|
class Train:
|
||||||
def __init__(self, name, tid, dest, xcoord, ycoord, prodclass):
|
def __init__(self, name, tid, dest, xcoord, ycoord, prodclass):
|
||||||
self.name = name
|
self.name = name
|
||||||
self.tid = tid
|
self.tid = tid
|
||||||
self.dest = dest
|
self.dest = dest
|
||||||
self.xcoord = float(xcoord)/1000000
|
self.xcoord = float(xcoord)/1000000
|
||||||
self.ycoord = float(ycoord)/1000000
|
self.ycoord = float(ycoord)/1000000
|
||||||
self.prodclass = prodclass
|
self.prodclass = prodclass
|
||||||
|
|
||||||
def lat(self):
|
def lat(self):
|
||||||
return self.ycoord
|
return self.ycoord
|
||||||
|
|
||||||
def lon(self):
|
def lon(self):
|
||||||
return self.xcoord
|
return self.xcoord
|
||||||
|
|
||||||
def destStation(self):
|
def destStation(self):
|
||||||
return list(workers.val.validateName(self.name))[0]
|
return list(workers.val.validateName(self.name))[0]
|
||||||
|
|
||||||
def json(self, indent = 0, name = True, tid = True, dest = True, coords = True, prodclass = False, stationkwargs = {}):
|
def json(self, indent=0, name=True, tid=True, dest=True, coords=True, prodclass=False, stationkwargs={}):
|
||||||
out = " " * indent + "{\n"
|
out = " " * indent + "{\n"
|
||||||
|
|
||||||
out += (" " * indent + " \"name\": \"%s\",\n" % self.name) if name else ""
|
out += (" " * indent + " \"name\": \"%s\",\n" %
|
||||||
out += (" " * indent + " \"id\": \"%s\",\n" % self.tid) if tid else ""
|
self.name) if name else ""
|
||||||
|
out += (" " * indent + " \"id\": \"%s\",\n" % self.tid) if tid else ""
|
||||||
|
|
||||||
if dest:
|
if dest:
|
||||||
# out += " " * indent + " \"destination\":\n"
|
# out += " " * indent + " \"destination\":\n"
|
||||||
# out += self.dest.json(indent + 2, **stationkwargs) + "\n"
|
# out += self.dest.json(indent + 2, **stationkwargs) + "\n"
|
||||||
out += " " * indent + " \"destination\": \"%s\",\n" % self.dest
|
out += " " * indent + " \"destination\": \"%s\",\n" % self.dest
|
||||||
|
|
||||||
if coords:
|
if coords:
|
||||||
out += " " * indent + " \"coords\": {\n"
|
out += " " * indent + " \"coords\": {\n"
|
||||||
out += " " * indent + " \"lon\": %f,\n" % self.xcoord
|
out += " " * indent + " \"lon\": %f,\n" % self.xcoord
|
||||||
out += " " * indent + " \"lat\": %f\n" % self.ycoord
|
out += " " * indent + " \"lat\": %f\n" % self.ycoord
|
||||||
out += " " * indent + " },\n"
|
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 = {}):
|
def xml(self, indent=0, name=True, tid=True, dest=True, coords=True, prodclass=False, stationkwargs={}):
|
||||||
out = " " * indent + "<train>\n"
|
out = " " * indent + "<train>\n"
|
||||||
|
|
||||||
out += (" " * indent + " <name>%s</name>\n" % self.name) if name else ""
|
out += (" " * indent + " <name>%s</name>\n" %
|
||||||
out += (" " * indent + " <id>%s</id>\n" % self.tid) if tid else ""
|
self.name) if name else ""
|
||||||
|
out += (" " * indent + " <id>%s</id>\n" % self.tid) if tid else ""
|
||||||
|
|
||||||
if dest:
|
if dest:
|
||||||
# out += " " * indent + " <destination>\n"
|
# out += " " * indent + " <destination>\n"
|
||||||
# out += self.dest.xml(indent + 2, **stationkwargs) + "\n"
|
# out += self.dest.xml(indent + 2, **stationkwargs) + "\n"
|
||||||
# out += " " * indent + " </destination>\n"
|
# out += " " * indent + " </destination>\n"
|
||||||
out += " " * indent + " <destination>%s</destination>\n" % self.dest
|
out += " " * indent + " <destination>%s</destination>\n" % self.dest
|
||||||
|
|
||||||
if coords:
|
if coords:
|
||||||
out += " " * indent + " <coords>\n"
|
out += " " * indent + " <coords>\n"
|
||||||
out += " " * indent + " <lon>%f</lon>\n" % self.xcoord
|
out += " " * indent + " <lon>%f</lon>\n" % self.xcoord
|
||||||
out += " " * indent + " <lat>%f</lat>\n" % self.ycoord
|
out += " " * indent + " <lat>%f</lat>\n" % self.ycoord
|
||||||
out += " " * indent + " </coords>\n"
|
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>"
|
out += " " * indent + "</train>"
|
||||||
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
return out
|
||||||
|
|
339
main.py
339
main.py
|
@ -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.'
|
DOCSTR = ' Check out the <a href="https://kumig.it/kumitterer/oebb_py#request">documentation</a> for usage instructions.'
|
||||||
|
|
||||||
|
|
||||||
def doConn(req):
|
def doConn(req):
|
||||||
try:
|
try:
|
||||||
getfrm = req.cfrm if "cfrm" in dir(req) and req.cfrm else req.args["from"][0] if "from" in req.args else None
|
getfrm = req.cfrm if "cfrm" in dir(
|
||||||
getto = req.cto if "cto" in dir(req) and req.cto else req.args["to"][0] if "to" in req.args else None
|
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:
|
try:
|
||||||
frm = html.unescape(getfrm.encode("latin-1").decode("utf-8"))
|
frm = html.unescape(getfrm.encode("latin-1").decode("utf-8"))
|
||||||
to = html.unescape(getto.encode("latin-1").decode("utf-8"))
|
to = html.unescape(getto.encode("latin-1").decode("utf-8"))
|
||||||
except UnicodeDecodeError:
|
except UnicodeDecodeError:
|
||||||
frm = html.unescape(getfrm)
|
frm = html.unescape(getfrm)
|
||||||
to = html.unescape(getto)
|
to = html.unescape(getto)
|
||||||
|
|
||||||
if not frm or not to:
|
if not frm or not to:
|
||||||
raise ValueError()
|
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:
|
count = req.args["count"][0] if "count" in req.args and req.args["count"] else 6
|
||||||
content = "<h1>400 Bad Request</h1>\n"
|
date = req.args["date"][0] if "date" in req.args and req.args["date"] else datetime.datetime.strftime(
|
||||||
content += "\"from\"and \"to\" values are required for this type of request."
|
datetime.datetime.now(pytz.timezone("Europe/Vienna")), "%d.%m.%Y")
|
||||||
return Response(HTTP400, HTML, content)
|
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
|
try:
|
||||||
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")
|
count = int(count)
|
||||||
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")
|
if count < 0 or count > 10:
|
||||||
mode = True if "mode" in req.args and req.args["mode"] and req.args["mode"][0].lower() == "arr" else False
|
raise ValueError()
|
||||||
details = True if "details" in req.args else False
|
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:
|
try:
|
||||||
count = int(count)
|
outtime = datetime.datetime.strptime(
|
||||||
if count < 0 or count > 10:
|
"%s %s" % (date, time), "%d.%m.%Y %H:%M")
|
||||||
raise ValueError()
|
except:
|
||||||
except:
|
content = "<h1>400 Bad Request</h1>\n"
|
||||||
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."
|
||||||
content += "The \"count\" value must be a value between 0 and 10."
|
return Response(HTTP400, HTML, content)
|
||||||
return Response(HTTP400, HTML, content)
|
|
||||||
|
|
||||||
try:
|
via = list(req.args["via"]) if "via" in req.args else None
|
||||||
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
|
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:
|
try:
|
||||||
content = "<h1>400 Bad Request</h1>\n"
|
content = workers.conn.worker(
|
||||||
content += "It is not possible to route through more than three \"via\" stations."
|
frm, to, count, outtime, mode, details, req.json, via)
|
||||||
return Response(HTTP400, 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)
|
||||||
|
|
||||||
try:
|
return Response(HTTP200, JSON if req.json else XML, content)
|
||||||
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)
|
|
||||||
|
|
||||||
def doVal(req):
|
def doVal(req):
|
||||||
try:
|
try:
|
||||||
try:
|
try:
|
||||||
name = (req.cfrm or req.args["name"][0]).encode("latin-1").decode("utf-8")
|
name = (req.cfrm or req.args["name"][0]).encode(
|
||||||
except UnicodeDecodeError:
|
"latin-1").decode("utf-8")
|
||||||
name = req.cfrm or req.args["name"][0]
|
except UnicodeDecodeError:
|
||||||
|
name = req.cfrm or req.args["name"][0]
|
||||||
|
|
||||||
if not name:
|
if not name:
|
||||||
raise ValueError()
|
raise ValueError()
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
content = "<h1>400 Bad Request</h1>\n"
|
content = "<h1>400 Bad Request</h1>\n"
|
||||||
content += "A \"name\" value is required for this type of request."
|
content += "A \"name\" value is required for this type of request."
|
||||||
return Response(HTTP400, HTML, content)
|
return Response(HTTP400, HTML, content)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
content = workers.val.worker(name, req.json)
|
content = workers.val.worker(name, req.json)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
content = "<h1>500 Internal Server Error</h1>\n"
|
content = "<h1>500 Internal Server Error</h1>\n"
|
||||||
if "debug" in req.args:
|
if "debug" in req.args:
|
||||||
content += traceback.format_exc().replace("\n", "<br />")
|
content += traceback.format_exc().replace("\n", "<br />")
|
||||||
return Response(HTTP500, HTML, content)
|
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):
|
def doNearby(req):
|
||||||
try:
|
try:
|
||||||
lat = float(req.args["lat"][0].replace(",", "."))
|
lat = float(req.args["lat"][0].replace(",", "."))
|
||||||
lon = float(req.args["lon"][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)):
|
if (not lat and not lat == float(0)) or (not lon and not lon == float(0)):
|
||||||
raise ValueError()
|
raise ValueError()
|
||||||
|
|
||||||
except:
|
except:
|
||||||
content = "<h1>400 Bad Request</h1>\n"
|
content = "<h1>400 Bad Request</h1>\n"
|
||||||
content += "\"lat\" and \"lon\" values are required for this type of request."
|
content += "\"lat\" and \"lon\" values are required for this type of request."
|
||||||
return Response(HTTP400, HTML, content)
|
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:
|
try:
|
||||||
distance = int(distance)
|
distance = int(distance)
|
||||||
if distance < 0 or distance > 10000:
|
if distance < 0 or distance > 10000:
|
||||||
raise ValueError()
|
raise ValueError()
|
||||||
except:
|
except:
|
||||||
content = "<h1>400 Bad Request</h1>\n"
|
content = "<h1>400 Bad Request</h1>\n"
|
||||||
content += "\"distance\" must be a value between 0 and 10000."
|
content += "\"distance\" must be a value between 0 and 10000."
|
||||||
return Response(HTTP400, HTML, content)
|
return Response(HTTP400, HTML, content)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
content = workers.closest.worker(lat, lon, distance, req.json)
|
content = workers.closest.worker(lat, lon, distance, req.json)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
content = "<h1>500 Internal Server Error</h1>"
|
content = "<h1>500 Internal Server Error</h1>"
|
||||||
if "debug" in req.args:
|
if "debug" in req.args:
|
||||||
content += traceback.format_exc().replace("\n", "<br />")
|
content += traceback.format_exc().replace("\n", "<br />")
|
||||||
return Response(HTTP500, HTML, content)
|
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):
|
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:
|
try:
|
||||||
content = workers.radar.worker(trains, req.json)
|
content = workers.radar.worker(trains, req.json)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
content = "<h1>500 Internal Server Error</h1>\n"
|
content = "<h1>500 Internal Server Error</h1>\n"
|
||||||
if "debug" in req.args:
|
if "debug" in req.args:
|
||||||
content += traceback.format_exc().replace("\n", "<br />")
|
content += traceback.format_exc().replace("\n", "<br />")
|
||||||
return Response(HTTP500, HTML, content)
|
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):
|
def doDepArr(req):
|
||||||
try:
|
try:
|
||||||
name = req.args["name"][0]
|
name = req.args["name"][0]
|
||||||
try:
|
try:
|
||||||
name = name.encode("latin-1").decode("utf-8")
|
name = name.encode("latin-1").decode("utf-8")
|
||||||
except UnicodeDecodeError:
|
except UnicodeDecodeError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
content = "<h1>400 Bad Request</h1>\n"
|
content = "<h1>400 Bad Request</h1>\n"
|
||||||
content += "A \"name\" value is required for this type of request."
|
content += "A \"name\" value is required for this type of request."
|
||||||
return Response(HTTP400, HTML, content)
|
return Response(HTTP400, HTML, content)
|
||||||
|
|
||||||
count = req.args["count"][0] if "count" in req.args and req.args["count"] else 30
|
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")
|
date = req.args["date"][0] if "date" in req.args and req.args["date"] else datetime.datetime.strftime(
|
||||||
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")
|
datetime.datetime.now(pytz.timezone("Europe/Vienna")), "%d.%m.%Y")
|
||||||
mode = True if req.rtype[:3] == "arr" else False
|
time = req.args["time"][0] if "time" in req.args and req.args["time"] else datetime.datetime.strftime(
|
||||||
details = True
|
datetime.datetime.now(pytz.timezone("Europe/Vienna")), "%H:%M")
|
||||||
|
mode = True if req.rtype[:3] == "arr" else False
|
||||||
|
details = True
|
||||||
|
|
||||||
try:
|
try:
|
||||||
count = int(count)
|
count = int(count)
|
||||||
except:
|
except:
|
||||||
content = "<h1>400 Bad Request</h1>\n"
|
content = "<h1>400 Bad Request</h1>\n"
|
||||||
content += "The \"count\" value must be a numeric value."
|
content += "The \"count\" value must be a numeric value."
|
||||||
return Response(HTTP400, HTML, content)
|
return Response(HTTP400, HTML, content)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
outtime = datetime.datetime.strptime("%s %s" % (date, time), "%d.%m.%Y %H:%M")
|
outtime = datetime.datetime.strptime(
|
||||||
except:
|
"%s %s" % (date, time), "%d.%m.%Y %H:%M")
|
||||||
content = "<h1>400 Bad Request</h1>\n"
|
except:
|
||||||
content += "The \"date\" value must be in DD.MM.YYYY format, the \"time\" value must be in HH:MM format."
|
content = "<h1>400 Bad Request</h1>\n"
|
||||||
return Response(HTTP400, HTML, content)
|
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:
|
try:
|
||||||
content = workers.deparr.worker(name, count, outtime, mode, details, req.json)
|
content = workers.deparr.worker(
|
||||||
except Exception as e:
|
name, count, outtime, mode, details, req.json)
|
||||||
content = "<h1>500 Internal Server Error</h1>\n"
|
except Exception as e:
|
||||||
if "debug" in req.args:
|
content = "<h1>500 Internal Server Error</h1>\n"
|
||||||
content += traceback.format_exc().replace("\n", "<br />")
|
if "debug" in req.args:
|
||||||
return Response(HTTP500, HTML, content)
|
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):
|
def doNot(req):
|
||||||
content = "<h1>400 Bad Request</h1>"
|
content = "<h1>400 Bad Request</h1>"
|
||||||
content += "The request type you submitted is invalid."
|
content += "The request type you submitted is invalid."
|
||||||
return Response(HTTP400, HTML, content)
|
return Response(HTTP400, HTML, content)
|
||||||
|
|
||||||
|
|
||||||
def application(env, re):
|
def application(env, re):
|
||||||
try:
|
try:
|
||||||
req = Request(env)
|
req = Request(env)
|
||||||
|
|
||||||
if req.rtype in ["conn", "connection", "connections"]:
|
if req.rtype in ["conn", "connection", "connections"]:
|
||||||
res = doConn(req)
|
res = doConn(req)
|
||||||
elif req.rtype in ["val", "validate"]:
|
elif req.rtype in ["val", "validate"]:
|
||||||
res = doVal(req)
|
res = doVal(req)
|
||||||
elif req.rtype in ["closest", "close", "near", "nearby"]:
|
elif req.rtype in ["closest", "close", "near", "nearby"]:
|
||||||
res = doNearby(req)
|
res = doNearby(req)
|
||||||
elif req.rtype in ["radar", "live", "trains"]:
|
elif req.rtype in ["radar", "live", "trains"]:
|
||||||
res = doRadar(req)
|
res = doRadar(req)
|
||||||
elif req.rtype in ["dep", "arr", "departure", "arrival", "departures", "arrivals"]:
|
elif req.rtype in ["dep", "arr", "departure", "arrival", "departures", "arrivals"]:
|
||||||
res = doDepArr(req)
|
res = doDepArr(req)
|
||||||
else:
|
else:
|
||||||
res = doNot(req)
|
res = doNot(req)
|
||||||
|
|
||||||
except IllegalMethodException as e:
|
except IllegalMethodException as e:
|
||||||
res = Response(HTTP405, HTML, str(e) + DOCSTR)
|
res = Response(HTTP405, HTML, str(e) + DOCSTR)
|
||||||
except InvalidArgumentException as e:
|
except InvalidArgumentException as e:
|
||||||
res = Response(HTTP400, HTML, str(e) + DOCSTR)
|
res = Response(HTTP400, HTML, str(e) + DOCSTR)
|
||||||
|
|
||||||
re(res.status, [("Content-Type", res.ctype)])
|
|
||||||
yield res.content.encode()
|
|
||||||
return
|
|
||||||
|
|
||||||
|
re(res.status, [("Content-Type", res.ctype)])
|
||||||
|
yield res.content.encode()
|
||||||
|
return
|
||||||
|
|
|
@ -3,8 +3,9 @@ import math
|
||||||
import workers.val
|
import workers.val
|
||||||
from classes.httpclient import HTTPClient
|
from classes.httpclient import HTTPClient
|
||||||
|
|
||||||
def getOSM(lat, lon, distance = 1000):
|
|
||||||
query = """[out:json];
|
def getOSM(lat, lon, distance=1000):
|
||||||
|
query = """[out:json];
|
||||||
(
|
(
|
||||||
node
|
node
|
||||||
(around:%i,%f,%f)
|
(around:%i,%f,%f)
|
||||||
|
@ -21,62 +22,71 @@ def getOSM(lat, lon, distance = 1000):
|
||||||
out;
|
out;
|
||||||
""" % (distance, lat, lon, distance, lat, lon)
|
""" % (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
|
json = HTTPClient().post(endpoint, data={"data": query}).text
|
||||||
res = overpy.Overpass().parse_json(json)
|
res = overpy.Overpass().parse_json(json)
|
||||||
|
|
||||||
|
return res.nodes
|
||||||
|
|
||||||
return res.nodes
|
|
||||||
|
|
||||||
def cDistance(lat1, lon1, lat2, lon2):
|
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
|
dila = lat2 - lat1
|
||||||
dilo = lon2 - lon1
|
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):
|
def getStations(nodes, distance=1000, lat=None, lon=None):
|
||||||
stations = list(getStations(getOSM(lat, lon, distance), distance, lat if validate else None, lon if validate else 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):
|
if validate:
|
||||||
outtext = """{
|
return sorted(stations, key=lambda station: station.distance)
|
||||||
|
|
||||||
|
return stations
|
||||||
|
|
||||||
|
|
||||||
|
def worker(lat, lon, distance=1000, json=False):
|
||||||
|
outtext = """{
|
||||||
"stations": [
|
"stations": [
|
||||||
""" if json else """<?xml version="1.0" encoding="UTF-8"?>
|
""" if json else """<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<stations>
|
<stations>
|
||||||
"""
|
"""
|
||||||
|
|
||||||
for station in findStations(lat, lon, distance):
|
for station in findStations(lat, lon, distance):
|
||||||
outtext += ",\n" if (json and not outtext.strip()[-1] == "[") else ""
|
outtext += ",\n" if (json and not outtext.strip()[-1] == "[") else ""
|
||||||
station.distance = station.distance or int(cDistance(station.lat(), station.lon(), lat, lon))
|
station.distance = station.distance or int(
|
||||||
outtext += station.json(2, distance = True) if json else station.xml(1, distance = True)
|
cDistance(station.lat(), station.lon(), lat, lon))
|
||||||
outtext += "\n" if not json else ""
|
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>"
|
}""" if json else "</stations>"
|
||||||
|
|
||||||
return outtext
|
return outtext
|
||||||
|
|
344
workers/conn.py
344
workers/conn.py
|
@ -8,75 +8,95 @@ import sys
|
||||||
import workers.val
|
import workers.val
|
||||||
from classes import *
|
from classes import *
|
||||||
|
|
||||||
|
|
||||||
def getStation(name):
|
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]
|
def getService(sid, lines, q, eq=None):
|
||||||
depdate = dep.find("td", { "class": "date" }).string.strip() or None
|
try:
|
||||||
deptime = dep.find("td", { "class": "timeValue" }).find("span").string.split()[1].strip()
|
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
|
depst = list(workers.val.validateName(
|
||||||
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
|
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"
|
depprog = dep.find("span", {"class": "prognosis"}).find("span").string.strip() if dep.find(
|
||||||
name = dep.find("img", { "class": "product" }).get("alt") if not walk else "Walk"
|
"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]
|
walk = dep.find("img", {"class": "product"}).get(
|
||||||
arrdate = (arr.find("td", { "class": "date" }).find("span") or arr.find("td", { "class": "date" })).string.strip() or depdate
|
"src") == "/img/vs_oebb/fuss_pic.gif"
|
||||||
arrtime = arr.find("td", { "class": "timeValue" }).find("span").string.split()[1].strip()
|
name = dep.find("img", {"class": "product"}).get(
|
||||||
arrprog = (arr.find("span", { "class": "prognosis" }).find("span") or arr.find("span", { "class": "prognosis" })).string.strip() or None
|
"alt") if not walk else "Walk"
|
||||||
arrplat = (arr.find("td", { "class": "platform" }).find("span") or arr.find("td", { "class": "platform" })).string.strip() or None
|
|
||||||
|
|
||||||
if arrdate and not depdate:
|
arrst = list(workers.val.validateName(
|
||||||
arrdts = datetime.datetime.strptime(arrdate, "%d.%m.%Y")
|
arr.find("td", {"class": "station"}).findAll("a")[0].string))[0]
|
||||||
depdts = arrdts - datetime.timedelta(days=1)
|
arrdate = (arr.find("td", {"class": "date"}).find("span") or arr.find(
|
||||||
depdate = datetime.datetime.strftime(depdts, "%d.%m.%Y")
|
"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):
|
dest = None
|
||||||
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
|
|
||||||
|
|
||||||
if not walk and not depdate:
|
if not (walk or depdate):
|
||||||
depdate = "01.01.2000"
|
try:
|
||||||
arrdate = depdate
|
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")
|
if not walk and not depdate:
|
||||||
arrts = datetime.datetime.strptime("%s %s" % (arrdate, arrtime), "%d.%m.%Y %H:%M")
|
depdate = "01.01.2000"
|
||||||
|
arrdate = depdate
|
||||||
|
|
||||||
depprog = deptime if depprog == "pünktlich" else depprog
|
depts = datetime.datetime.strptime(
|
||||||
arrprog = arrtime if arrprog == "pünktlich" else arrprog
|
"%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)
|
depprog = deptime if depprog == "pünktlich" else depprog
|
||||||
q.put((sid, svc))
|
arrprog = arrtime if arrprog == "pünktlich" else arrprog
|
||||||
|
|
||||||
except Exception as e:
|
svc = Service(name, depst, depts, arrst, arrts, dest,
|
||||||
if eq:
|
depplat, depprog, arrplat, arrprog)
|
||||||
eq.put(sys.exc_info())
|
q.put((sid, svc))
|
||||||
raise
|
|
||||||
|
|
||||||
def getDetails(cid, url, q, via = [], eq = None):
|
except Exception as e:
|
||||||
try:
|
if eq:
|
||||||
ssource = HTTPClient().get(url).text
|
eq.put(sys.exc_info())
|
||||||
suppe = BeautifulSoup(ssource, "html5lib")
|
raise
|
||||||
|
|
||||||
cont = suppe.find("tr", id="trC0-%i" % cid)
|
|
||||||
if not cont:
|
def getDetails(cid, url, q, via=[], eq=None):
|
||||||
return
|
try:
|
||||||
|
ssource = HTTPClient().get(url).text
|
||||||
|
suppe = BeautifulSoup(ssource, "html5lib")
|
||||||
|
|
||||||
|
cont = suppe.find("tr", id="trC0-%i" % cid)
|
||||||
|
if not cont:
|
||||||
|
return
|
||||||
|
|
||||||
# buyurl = None
|
# 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"):
|
# if url.get("href") and "https://tickets.oebb.at/de/ticket/ticket?" in url.get("href"):
|
||||||
# buyurl = url.get("href")
|
# buyurl = url.get("href")
|
||||||
|
|
||||||
conn = Connection(True)
|
conn = Connection(True)
|
||||||
|
|
||||||
for vst in via:
|
for vst in via:
|
||||||
conn.addVia(vst)
|
conn.addVia(vst)
|
||||||
|
|
||||||
lines = cont.findAll("tr", { "class": "tpDetails" })[1:]
|
lines = cont.findAll("tr", {"class": "tpDetails"})[1:]
|
||||||
threads = []
|
threads = []
|
||||||
iq = queue.PriorityQueue()
|
iq = queue.PriorityQueue()
|
||||||
|
|
||||||
for line in range(0, len(lines), 3):
|
for line in range(0, len(lines), 3):
|
||||||
t = threading.Thread(target=getService, args=(line, lines[line:line + 3], iq, eq), daemon = True)
|
t = threading.Thread(target=getService, args=(
|
||||||
t.start()
|
line, lines[line:line + 3], iq, eq), daemon=True)
|
||||||
threads += [t]
|
t.start()
|
||||||
|
threads += [t]
|
||||||
|
|
||||||
for t in threads:
|
for t in threads:
|
||||||
t.join()
|
t.join()
|
||||||
|
|
||||||
wdate = None
|
wdate = None
|
||||||
|
|
||||||
while not iq.empty():
|
while not iq.empty():
|
||||||
svc = iq.get()[1]
|
svc = iq.get()[1]
|
||||||
|
|
||||||
if not wdate or svc.arrtime > wdate:
|
if not wdate or svc.arrtime > wdate:
|
||||||
wdate = svc.arrtime
|
wdate = svc.arrtime
|
||||||
elif svc.deptime < wdate:
|
elif svc.deptime < wdate:
|
||||||
ttime0 = datetime.datetime(wdate.year, wdate.month, wdate.day)
|
ttime0 = datetime.datetime(wdate.year, wdate.month, wdate.day)
|
||||||
ttime1 = ttime0 + datetime.timedelta(hours=svc.deptime.hour, minutes=svc.deptime.minute)
|
ttime1 = ttime0 + \
|
||||||
ttime2 = ttime0 + datetime.timedelta(hours=svc.arrtime.hour, minutes=svc.arrtime.minute)
|
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:
|
if ttime1 < wdate:
|
||||||
ttime1 += datetime.timedelta(days=1)
|
ttime1 += datetime.timedelta(days=1)
|
||||||
ttime2 += datetime.timedelta(days=1)
|
ttime2 += datetime.timedelta(days=1)
|
||||||
|
|
||||||
if ttime1 > ttime2:
|
if ttime1 > ttime2:
|
||||||
ttime2 += datetime.timedelta(days=1)
|
ttime2 += datetime.timedelta(days=1)
|
||||||
|
|
||||||
svc.deptime = ttime1
|
svc.deptime = ttime1
|
||||||
svc.arrtime = ttime2
|
svc.arrtime = ttime2
|
||||||
|
|
||||||
conn.addService(svc)
|
conn.addService(svc)
|
||||||
|
|
||||||
q.put((cid, conn))
|
q.put((cid, conn))
|
||||||
|
|
||||||
except:
|
except:
|
||||||
if eq:
|
if eq:
|
||||||
eq.put(sys.exc_info())
|
eq.put(sys.exc_info())
|
||||||
raise
|
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 = "http://fahrplan.oebb.at/bin/query.exe/dn?start=1&S=%s&Z=%s&REQ0JourneyDate=%s&time=%s&REQ0HafasNumCons0=%s%s" % (
|
||||||
url += "&REQ0JourneyStops%i.0G=%s&REQ0JourneyStops%i.0A=1" % (i + 1, via[i].extid if via[i].extid else via[i].name, i + 1)
|
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:
|
source = HTTPClient().get(url).text
|
||||||
raise ValueError("No connection found.")
|
|
||||||
|
|
||||||
juha = BeautifulSoup(source, "html5lib")
|
if "GO_conViewMode=outward" not in source:
|
||||||
|
raise ValueError("No connection found.")
|
||||||
if details:
|
|
||||||
conns = []
|
|
||||||
|
|
||||||
for a in juha.findAll("a"):
|
juha = BeautifulSoup(source, "html5lib")
|
||||||
if a.get("href") and "GO_conViewMode" in a.get("href"):
|
|
||||||
conns += [a.get("href")]
|
|
||||||
|
|
||||||
threads = []
|
if details:
|
||||||
eq = queue.Queue()
|
conns = []
|
||||||
q = queue.PriorityQueue()
|
|
||||||
|
|
||||||
for i in range(len(conns)):
|
for a in juha.findAll("a"):
|
||||||
t = threading.Thread(target=getDetails, args=(i, conns[i], q, via, eq), daemon = True)
|
if a.get("href") and "GO_conViewMode" in a.get("href"):
|
||||||
t.start()
|
conns += [a.get("href")]
|
||||||
threads += [t]
|
|
||||||
|
|
||||||
for t in threads:
|
threads = []
|
||||||
t.join()
|
eq = queue.Queue()
|
||||||
|
q = queue.PriorityQueue()
|
||||||
|
|
||||||
if not eq.empty():
|
for i in range(len(conns)):
|
||||||
exc = eq.get()
|
t = threading.Thread(target=getDetails, args=(
|
||||||
raise exc[1].with_traceback(exc[2])
|
i, conns[i], q, via, eq), daemon=True)
|
||||||
|
t.start()
|
||||||
|
threads += [t]
|
||||||
|
|
||||||
while not q.empty():
|
for t in threads:
|
||||||
yield q.get()[1]
|
t.join()
|
||||||
|
|
||||||
else:
|
if not eq.empty():
|
||||||
for i in range(0, count):
|
exc = eq.get()
|
||||||
det = juha.find("tr", id="trOverviewC0-%i" % i)
|
raise exc[1].with_traceback(exc[2])
|
||||||
if not det:
|
|
||||||
break
|
|
||||||
|
|
||||||
stations = det.find("td", { "class": "station" }).findAll("div")
|
while not q.empty():
|
||||||
depst = getStation(stations[0].text.strip())
|
yield q.get()[1]
|
||||||
arrst = getStation(stations[-1].text.strip())
|
|
||||||
|
|
||||||
dates = list(det.find("td", { "class": "date" }).strings)
|
else:
|
||||||
depdate = dates[0]
|
for i in range(0, count):
|
||||||
try:
|
det = juha.find("tr", id="trOverviewC0-%i" % i)
|
||||||
arrdate = dates[1]
|
if not det:
|
||||||
except:
|
break
|
||||||
arrdate = depdate
|
|
||||||
|
|
||||||
times = det.find("div", { "class": "planed" }).text
|
stations = det.find("td", {"class": "station"}).findAll("div")
|
||||||
deptime = times.split()[0]
|
depst = getStation(stations[0].text.strip())
|
||||||
arrtime = times.split()[2]
|
arrst = getStation(stations[-1].text.strip())
|
||||||
|
|
||||||
projections = det.find("div", { "class": "prognosis" })
|
dates = list(det.find("td", {"class": "date"}).strings)
|
||||||
curdep = None
|
depdate = dates[0]
|
||||||
curarr = None
|
try:
|
||||||
|
arrdate = dates[1]
|
||||||
|
except:
|
||||||
|
arrdate = depdate
|
||||||
|
|
||||||
depts = datetime.datetime.strptime("%s %s" % (depdate, deptime), "%d.%m.%Y %H:%M")
|
times = det.find("div", {"class": "planed"}).text
|
||||||
arrts = datetime.datetime.strptime("%s %s" % (arrdate, arrtime), "%d.%m.%Y %H:%M")
|
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")
|
# ticketurl = det.find("td", { "class": "fares" }).find("a").get("href")
|
||||||
|
|
||||||
svc = Service(name, depst, depts, arrst, arrts, currdep = curdep, curarr = curarr)
|
svc = Service(name, depst, depts, arrst, arrts,
|
||||||
conn = Connection(details)
|
currdep=curdep, curarr=curarr)
|
||||||
|
conn = Connection(details)
|
||||||
|
|
||||||
for vst in via:
|
for vst in via:
|
||||||
conn.addVia(vst)
|
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>
|
<connections>
|
||||||
""" if not json else """{
|
""" if not json else """{
|
||||||
\"connections\": [
|
\"connections\": [
|
||||||
"""
|
"""
|
||||||
|
|
||||||
for i in range(len(conns)):
|
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 += (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
|
||||||
|
|
|
@ -8,96 +8,107 @@ import sys
|
||||||
import workers.val
|
import workers.val
|
||||||
from classes import *
|
from classes import *
|
||||||
|
|
||||||
|
|
||||||
def getStation(name):
|
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(")", "")
|
def getService(sid, url, dtime, q=None, eq=None):
|
||||||
ddate = zuppa.findAll("div", { "class": "block" })[1].text.strip()
|
try:
|
||||||
|
zuppa = BeautifulSoup(HTTPClient().get(url).text, "html5lib")
|
||||||
|
|
||||||
table = zuppa.find("table", { "class": "resultTable" })
|
name = zuppa.findAll("div", {"class": "block"})[0].text.strip().replace(
|
||||||
rows = table.findAll("tr")[1:]
|
"(Zug-Nr. ", " - ").replace(")", "")
|
||||||
|
ddate = zuppa.findAll("div", {"class": "block"})[1].text.strip()
|
||||||
|
|
||||||
for row in rows:
|
table = zuppa.find("table", {"class": "resultTable"})
|
||||||
if len(row.findAll("td")) > 6 and row.findAll("td")[4].text.strip() == dtime:
|
rows = table.findAll("tr")[1:]
|
||||||
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
|
|
||||||
|
|
||||||
dest = getStation(rows[-1].findAll("td")[1].text.strip())
|
for row in rows:
|
||||||
atime = rows[-1].findAll("td")[2].text.strip()
|
if len(row.findAll("td")) > 6 and row.findAll("td")[4].text.strip() == dtime:
|
||||||
curarr = rows[-1].findAll("td")[3].text.strip()
|
depst = getStation(row.findAll("td")[1].text.strip())
|
||||||
curarr = atime if curarr == "pünktlich" else curarr or None
|
currdep = row.findAll("td")[5].text.strip()
|
||||||
arrpf = rows[-1].findAll("td")[-1].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")
|
dest = getStation(rows[-1].findAll("td")[1].text.strip())
|
||||||
arrtime = datetime.datetime.strptime("%s %s" % (ddate, atime), "%d.%m.%Y %H:%M")
|
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:
|
deptime = datetime.datetime.strptime(
|
||||||
arrtime += datetime.timedelta(days = 1)
|
"%s %s" % (ddate, dtime), "%d.%m.%Y %H:%M")
|
||||||
|
arrtime = datetime.datetime.strptime(
|
||||||
|
"%s %s" % (ddate, atime), "%d.%m.%Y %H:%M")
|
||||||
|
|
||||||
if q:
|
if arrtime < deptime:
|
||||||
q.put((sid, Service(name, depst, deptime, dest, arrtime, dest, deppf, currdep, arrpf, curarr)))
|
arrtime += datetime.timedelta(days=1)
|
||||||
return q
|
|
||||||
|
|
||||||
except:
|
if q:
|
||||||
if eq:
|
q.put((sid, Service(name, depst, deptime, dest,
|
||||||
eq.put(sys.exc_info())
|
arrtime, dest, deppf, currdep, arrpf, curarr)))
|
||||||
raise
|
return q
|
||||||
|
|
||||||
def daRequest(station, count = 3, time = datetime.datetime.now(), mode = False, details = False):
|
except:
|
||||||
outdate = datetime.datetime.strftime(time, "%d.%m.%Y")
|
if eq:
|
||||||
outtime = datetime.datetime.strftime(time, "%H:%M")
|
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:
|
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" % (
|
||||||
raise ValueError("No services found.")
|
station.extid if station.extid else station.name, "arr" if mode else "dep", outtime, outdate, count)
|
||||||
|
|
||||||
juha = BeautifulSoup(source, "html5lib")
|
source = HTTPClient().get(url).text
|
||||||
|
|
||||||
services = []
|
|
||||||
|
|
||||||
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]:
|
juha = BeautifulSoup(source, "html5lib")
|
||||||
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()
|
|
||||||
|
|
||||||
for i in range(len(services)):
|
services = []
|
||||||
t = threading.Thread(target=getService, args=(i, services[i][0], services[i][1], q, eq), daemon = True)
|
|
||||||
t.start()
|
|
||||||
threads += [t]
|
|
||||||
|
|
||||||
for t in threads:
|
table = juha.find("table", {"class": "resultTable"})
|
||||||
t.join()
|
|
||||||
|
|
||||||
if not eq.empty():
|
for row in table.findAll("tr")[1:-1]:
|
||||||
exc = eq.get()
|
if not len(row.findAll("td")) < 4:
|
||||||
raise exc[1].with_traceback(exc[2])
|
services += [(row.findAll("a")[0].get("href"),
|
||||||
|
row.findAll("td")[0].text.strip())]
|
||||||
|
|
||||||
while not q.empty():
|
threads = []
|
||||||
station.addService(q.get()[1])
|
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):
|
for t in threads:
|
||||||
station = daRequest(getStation(station), count, time, mode, details)
|
t.join()
|
||||||
|
|
||||||
if json:
|
if not eq.empty():
|
||||||
output = station.json(services = True)
|
exc = eq.get()
|
||||||
else:
|
raise exc[1].with_traceback(exc[2])
|
||||||
output = """<?xml version="1.0" encoding="UTF-8"?>\n"""
|
|
||||||
output += station.xml(services = True)
|
|
||||||
|
|
||||||
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
|
||||||
|
|
|
@ -2,44 +2,47 @@ import json
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
from classes import *
|
from classes import *
|
||||||
|
|
||||||
|
|
||||||
def getRadar():
|
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"]
|
def getTrains(names=None):
|
||||||
for train in trains:
|
trains = json.loads(getRadar())["t"]
|
||||||
name = " ".join(train["n"].split())
|
for train in trains:
|
||||||
|
name = " ".join(train["n"].split())
|
||||||
# destination = workers.conn.getStation(train["l"])
|
# destination = workers.conn.getStation(train["l"])
|
||||||
destination = train["l"]
|
destination = train["l"]
|
||||||
xcoord = train["x"]
|
xcoord = train["x"]
|
||||||
ycoord = train["y"]
|
ycoord = train["y"]
|
||||||
prodclass = train["c"]
|
prodclass = train["c"]
|
||||||
tid = train["i"]
|
tid = train["i"]
|
||||||
|
|
||||||
find = False if names else True
|
find = False if names else True
|
||||||
|
|
||||||
if not find:
|
if not find:
|
||||||
for cname in names:
|
for cname in names:
|
||||||
if cname.lower().replace(" ", "") == name.split("-")[0].lower().replace(" ", "") or name.lower().replace(" ", "").startswith(cname.lower().replace(" ", "")):
|
if cname.lower().replace(" ", "") == name.split("-")[0].lower().replace(" ", "") or name.lower().replace(" ", "").startswith(cname.lower().replace(" ", "")):
|
||||||
find = True
|
find = True
|
||||||
|
|
||||||
if find:
|
if find:
|
||||||
yield Train(name = name, dest = destination, xcoord = xcoord, ycoord = ycoord, prodclass = prodclass, tid = tid)
|
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": [
|
"trains": [
|
||||||
""" if json else """<?xml version="1.0" encoding="UTF-8"?>
|
""" if json else """<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<trains>
|
<trains>
|
||||||
"""
|
"""
|
||||||
|
|
||||||
for train in getTrains(trains):
|
for train in getTrains(trains):
|
||||||
outtext += ",\n" if (json and not outtext.strip()[-1] == "[") else ""
|
outtext += ",\n" if (json and not outtext.strip()[-1] == "[") else ""
|
||||||
outtext += train.json(2) if json else train.xml(1)
|
outtext += train.json(2) if json else train.xml(1)
|
||||||
outtext += "\n" if not json else ""
|
outtext += "\n" if not json else ""
|
||||||
|
|
||||||
outtext += """
|
outtext += """
|
||||||
]
|
]
|
||||||
}""" if json else "</trains>"
|
}""" if json else "</trains>"
|
||||||
|
|
||||||
return outtext
|
return outtext
|
||||||
|
|
|
@ -2,40 +2,43 @@ import json
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
from classes import *
|
from classes import *
|
||||||
|
|
||||||
|
|
||||||
def getValidator(name):
|
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
|
data = HTTPClient().get("http://scotty.oebb.at/bin/ajax-getstop.exe/dn?REQ0JourneyStopsS0A=255&REQ0JourneyStopsB=12&S='%s'?&js=true&" %
|
||||||
return "=".join(data.split("=")[1:]).split(";")[0]
|
urllib.parse.quote(name.encode("latin-1"))).text
|
||||||
|
return "=".join(data.split("=")[1:]).split(";")[0]
|
||||||
|
|
||||||
|
|
||||||
def validateName(name):
|
def validateName(name):
|
||||||
stations = json.loads(getValidator(name))
|
stations = json.loads(getValidator(name))
|
||||||
for station in stations["suggestions"]:
|
for station in stations["suggestions"]:
|
||||||
name = station["value"]
|
name = station["value"]
|
||||||
sttype = station["type"]
|
sttype = station["type"]
|
||||||
try:
|
try:
|
||||||
extid = station["extId"]
|
extid = station["extId"]
|
||||||
except:
|
except:
|
||||||
extid = None
|
extid = None
|
||||||
xcoord = station["xcoord"]
|
xcoord = station["xcoord"]
|
||||||
ycoord = station["ycoord"]
|
ycoord = station["ycoord"]
|
||||||
prodclass = station["prodClass"]
|
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": [
|
"stations": [
|
||||||
""" if json else """<?xml version="1.0" encoding="UTF-8"?>
|
""" if json else """<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<stations>
|
<stations>
|
||||||
"""
|
"""
|
||||||
|
|
||||||
for station in validateName(name):
|
for station in validateName(name):
|
||||||
outtext += ",\n" if (json and not outtext.strip()[-1] == "[") else ""
|
outtext += ",\n" if (json and not outtext.strip()[-1] == "[") else ""
|
||||||
outtext += station.json(2) if json else station.xml(1)
|
outtext += station.json(2) if json else station.xml(1)
|
||||||
outtext += "\n" if not json else ""
|
outtext += "\n" if not json else ""
|
||||||
|
|
||||||
outtext += """
|
outtext += """
|
||||||
]
|
]
|
||||||
}""" if json else "</stations>"
|
}""" if json else "</stations>"
|
||||||
|
|
||||||
return outtext
|
return outtext
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue