Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Transport for EMF HAFAS #15

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,3 @@ config.json
*.pyc
.venv
*.swp
#*.ttf
*.TTF
8 changes: 8 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/package-hafas.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 5 additions & 6 deletions COPYRIGHT
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,11 @@ silkscreen.ttf:

<http://kottke.org/plus/type/silkscreen/>

bus.png, high_speed_rail.png, low_speed_rail.png, tram.png, u_bahn.png:

Part of twemoji <https://github.com/twitter/twemoji>
Licensed under CC-BY 4.0

s_bahn.png
s_bahn.png:

<https://commons.wikimedia.org/wiki/File:S-Bahn-Logo.svg>
Public Domain

Emoji:

Iconography from Mutant Standard Emoji <https://mutant.tech>
Binary file added CymruSansTransport-Medium.otf
Binary file not shown.
Binary file added NRE_Powered_logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified bus.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions cache_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ def fetch_stop(stop, endpoint):
stop=stop,
minutes=MINUTES,
key=KEY,
language=CONFIG["query_language"],
)
)
r.raise_for_status()
Expand Down
136 changes: 89 additions & 47 deletions hafas_event.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
import re
from datetime import datetime, timedelta

import hashlib
import pytz
from datetime import datetime, timedelta, tzinfo
from helper import Helper
from hosted import CONFIG
from mapping import CATEGORY_MAPPING, COLOUR_MAPPING, OPERATOR_LABEL_MAPPING

REMOVE = re.escape(CONFIG["remove_string"].strip())
REMOVE = re.escape(CONFIG["remove_string"].strip()) if CONFIG["remove_string"] else None


class FixedOffset(tzinfo):
def __init__(self, offset, name):
self.__offset = timedelta(minutes=offset)
self.__name = name

def utcoffset(self, _dt):
return self.__offset

def tzname(self, _dt):
return self.__name

def dst(self, _dt):
return timedelta(0)


class HAFASEvent:
Expand All @@ -15,16 +31,18 @@ def __init__(self, data):
self.follow = None

self.id = data["JourneyDetailRef"]["ref"]
self.cancelled = data.get("cancelled", False)

for product in data["Product"]:
if product.get("name") and product.get("catCode"):
self.category = product["catCode"]
self.operator = product.get("operatorCode", None)
self.operatorName = product.get("operatorInfo", {}).get("name", None)
self.icon = product.get("icon", None)

symbol = product["name"]
for regex, replacement in OPERATOR_LABEL_MAPPING.get(
CONFIG["api_provider"], {}
CONFIG["api_provider"], {}
).items():
symbol = re.sub(regex, replacement, symbol)
self.symbol = symbol
Expand All @@ -33,6 +51,7 @@ def __init__(self, data):
self.symbol = ""
self.category = -1
self.operator = None
self.operatorName = None
self.icon = None

if CONFIG["api_provider"] in CATEGORY_MAPPING:
Expand All @@ -42,18 +61,27 @@ def __init__(self, data):
else:
self.category_icon = ""

scheduled = datetime.strptime(
data["date"] + " " + data["time"], "%Y-%m-%d %H:%M:%S"
self.scheduled = datetime.strptime(
data["date"] + " " + data["time"], "%Y-%m-%d %H:%M:%S",
)
if data.get("tz", None) is not None:
self.scheduled = self.scheduled.replace(tzinfo=FixedOffset(data["tz"], ""))
else:
self.scheduled = pytz.timezone(CONFIG["timezone"]).localize(self.scheduled)

if "rtTime" in data and "rtDate" in data:
self.realtime = datetime.strptime(
data["rtDate"] + " " + data["rtTime"], "%Y-%m-%d %H:%M:%S"
)
diff = self.realtime - scheduled
if data.get("rtTz", None) is not None:
self.realtime = self.realtime.replace(tzinfo=FixedOffset(data["rtTz"], ""))
else:
self.realtime = pytz.timezone(CONFIG["timezone"]).localize(self.realtime)
diff = self.realtime - self.scheduled
self.delay = int(diff.total_seconds() / 60)
else:
self.realtime = scheduled
self.delay = -1
self.realtime = self.scheduled
self.delay = None

def __lt__(self, other):
assert isinstance(other, HAFASEvent)
Expand All @@ -63,18 +91,19 @@ def _clean(self, key):
if key not in self.json:
return None
else:
for possible_match in (
"^(" + REMOVE + "[, -]+)",
"( *\(" + REMOVE + "\))",
"(" + REMOVE + " +)",
):
if re.search(possible_match, self.json[key].strip()):
return re.sub(
possible_match,
"",
self.json[key].strip(),
flags=re.IGNORECASE,
).strip()
if REMOVE:
for possible_match in (
"^(" + REMOVE + "[, -]+)",
"( *\(" + REMOVE + "\))",
"(" + REMOVE + " +)",
):
if re.search(possible_match, self.json[key].strip()):
return re.sub(
possible_match,
"",
self.json[key].strip(),
flags=re.IGNORECASE,
).strip()
return self.json[key].strip()

@property
Expand All @@ -88,11 +117,11 @@ def origin(self):
@property
def ignore_destination(self):
if (
CONFIG["ignore_destination"]
and self.destination
and re.search(
CONFIG["ignore_destination"], self.destination, flags=re.IGNORECASE
)
CONFIG["ignore_destination"]
and self.destination
and re.search(
CONFIG["ignore_destination"], self.destination, flags=re.IGNORECASE
)
):
return True
return False
Expand All @@ -102,22 +131,24 @@ def line_colour(self):
provider = CONFIG["api_provider"]

if (
provider in COLOUR_MAPPING
and self.operator in COLOUR_MAPPING[provider]
and self.symbol in COLOUR_MAPPING[provider][self.operator]
provider in COLOUR_MAPPING
and self.operator in COLOUR_MAPPING[provider]
and self.symbol in COLOUR_MAPPING[provider][self.operator]
):
(r, g, b), (font_r, font_g, font_b) = COLOUR_MAPPING[provider][
self.operator
][self.symbol]
elif provider in COLOUR_MAPPING and self.symbol in COLOUR_MAPPING[provider]:
(r, g, b), (font_r, font_g, font_b) = COLOUR_MAPPING[provider][self.symbol]
elif provider in COLOUR_MAPPING and self.operator in COLOUR_MAPPING[provider]:
(r, g, b), (font_r, font_g, font_b) = COLOUR_MAPPING[provider][self.operator]
elif self.icon is not None:
r, g, b = Helper.hex2rgb(self.icon["backgroundColor"]["hex"][1:])
font_r, font_g, font_b = Helper.hex2rgb(
self.icon["foregroundColor"]["hex"][1:]
)
else:
name_hash = md5(self.json["name"]).hexdigest()
name_hash = hashlib.md5(self.json["name"]).hexdigest()
r, g, b = Helper.hex2rgb(name_hash[:6])
h, s, v = Helper.rgb2hsv(r * 255, g * 255, b * 255)
if v > 0.75:
Expand All @@ -140,28 +171,39 @@ def line_colour(self):
@property
def notes(self):
notes = []
for note in self.json["Notes"]["Note"]:
# Apparently:
# A: Accessibility Information
# I: Internal Stuff
# R: Travel information ("faellt aus" etc.)
if note["type"].upper() in ("R",):
notes.append(note["value"])
if notes:
return ' | '.join(notes)
return None
if "Notes" in self.json:
for note in self.json["Notes"]["Note"]:
note_type = note["type"].upper()
# Apparently:
# A: Accessibility Information
# I: Internal Stuff
# R: Travel information ("faellt aus" etc.)
# P: Cancellation reason
# D: Late running reason
if note_type in ("R", "P", "D"):
notes.append({
"type": note_type,
"text": note["value"]
})
return notes

@property
def stop(self):
return self._clean("stop")

@property
def platform(self):
if "platform" in self.json:
return "{} {}".format(
self.json["platform"].get("type", ""),
self.json["platform"].get("text", ""),
).strip()
if "rtPlatform" in self.json or "platform" in self.json:
platform = self.json["rtPlatform"] if "rtPlatform" in self.json else self.json["platform"]
if platform.get("hidden", False):
return None
return {
"type": platform.get("type", "X"),
"value": platform.get("text", ""),
}
if "track" in self.json:
return self.json["track"]
return ""
return {
"type": "PL",
"value": self.json["track"]
}
return None
Loading