Added importer script

This commit is contained in:
Antonia 2022-03-26 12:27:37 +01:00
commit 6152381985

66
importer.py Normal file
View file

@ -0,0 +1,66 @@
#!env python3
# Copyright (C) 2022 Antonia <antonia@antonia.is>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import datetime
import json
import requests
import sys
if len(sys.argv) < 3 :
print("Usage: {} CSV_FILE API_TOKEN".format(sys.argv[0]))
exit(1)
CSV_FILE=sys.argv[1]
API_TOKEN=sys.argv[2]
API_ENDPOINT="https://travelynx.de/api/v1/import"
f = open(CSV_FILE, "r")
def ts_to_unix(ts) :
return int(datetime.datetime.strptime(ts, "%Y-%m-%dT%H:%M:%S%z").timestamp())
def station(fields, offset):
return {"name": fields[offset].replace('"', ""), "scheduledTime": ts_to_unix(fields[offset+2]), "realTime": ts_to_unix(fields[offset+3])}
def train(fields):
t = fields[2].replace('"', "").split(" ")
return {"type" : t[0], "no": t[1]}
for line in f.readlines()[1:] :
data = {"token": API_TOKEN, "cancelled": False, "dryRun": False}
fields = line.split("\t")
try:
data["train"] = train(fields)
if data["train"]["type"] in ["STR", "U", "Bus", "STB"]:
continue # Travelynx does not support urban transport.
data["fromStation"] = station(fields, 3)
data["toStation"] = station(fields, 7)
except:
continue ## shady shit going on...
response = requests.post(API_ENDPOINT, json=data)
jsr = json.loads(response.text)
if not jsr["success"] :
print("Import failed for: " + " ".join(data["train"].values()) + " From {} to {} ".format(data["fromStation"]["name"],data["toStation"]["name"])+ " Message: " + jsr["error"])