108 lines
3.4 KiB
Python
108 lines
3.4 KiB
Python
import json
|
|
from init import db, Meals, scheduler
|
|
import datetime
|
|
import requests
|
|
import hashlib
|
|
import time
|
|
|
|
nomeal = 'Essen nicht (mehr) verfügbar'
|
|
|
|
|
|
def getMeals(day: datetime):
|
|
day = formatDay(day)
|
|
essen = []
|
|
query = Meals.query.filter_by(date=day).all()
|
|
if len(query) != 0:
|
|
for i in query:
|
|
essen += [i.name]
|
|
essen.sort(key=len, reverse=True)
|
|
return essen
|
|
return getMealsFromAPI(day, dbentry=True)
|
|
|
|
|
|
def getMealsFromAPI(day: str, dbentry: bool = False):
|
|
url = "https://dh-api.paulmartin.cloud/plans/" + day + "?canteens=erzberger"
|
|
response = requests.request("GET", url)
|
|
response = response.content
|
|
jres = json.loads(response.decode("utf-8"))
|
|
essen = []
|
|
|
|
try:
|
|
num = len(jres["data"][0]["lines"])
|
|
for i in range(num):
|
|
try:
|
|
jsmeal = jres["data"][0]["lines"][i]["meals"]
|
|
cont = True
|
|
except IndexError:
|
|
essen = []
|
|
cont = False
|
|
if cont:
|
|
for e in range(len(jsmeal)):
|
|
ji = jsmeal[e]
|
|
name = ji["name"]
|
|
if pricetofloat(ji["price"]) >= 1.1:
|
|
vegan = ji["classifiers"].count("VG") == 1
|
|
schwein = ji["classifiers"].count("S") == 1
|
|
if vegan:
|
|
veget = True
|
|
else:
|
|
veget = ji["classifiers"].count("VEG") == 1
|
|
if veget:
|
|
if name.count("Reibekäse") > 0:
|
|
vegan = True
|
|
|
|
essen += [name]
|
|
if dbentry:
|
|
mid = int(hashlib.sha1((day + name).encode("utf-8")).hexdigest(), 16) % (8 ** 8)
|
|
neu = Meals(date=day, name=name, id=mid, vegan=vegan, vegetarian=veget, schwein=schwein)
|
|
db.session.add(neu)
|
|
db.session.commit()
|
|
if not essen:
|
|
essen = [nomeal]
|
|
except KeyError:
|
|
essen = [nomeal]
|
|
return essen
|
|
|
|
|
|
def pricetofloat(price: str):
|
|
price = price[:-2]
|
|
price = price.replace(",", ".")
|
|
try:
|
|
return float(price)
|
|
except ValueError:
|
|
return 0
|
|
|
|
|
|
def formatDay(day: datetime):
|
|
if day.day < 10:
|
|
tag = "0" + str(day.day)
|
|
else:
|
|
tag = str(day.day)
|
|
day = str(day.year) + "-" + str(day.month) + "-" + tag
|
|
return day
|
|
|
|
|
|
@scheduler.task('cron', id="refreshMeals", hour='*', day_of_week='*', minute='1-59', week='*', second='30')
|
|
def refreshMeals():
|
|
print("Aktualisiere Essenspläne...\n")
|
|
with scheduler.app.app_context():
|
|
table = Meals.query.all()
|
|
dates = []
|
|
for i in table:
|
|
if i.date not in dates:
|
|
dates += [i.date]
|
|
for i in range(len(dates)):
|
|
dates[i] = formatDay(dates[i])
|
|
for i in dates:
|
|
apinames = getMealsFromAPI(i)
|
|
dbmeals = Meals.query.filter_by(date=i).all()
|
|
dbnames = []
|
|
for m in dbmeals:
|
|
dbnames += [m.name]
|
|
if set (dbnames) != set(apinames) and nomeal not in apinames:
|
|
print (dbnames, apinames)
|
|
for n in dbnames:
|
|
db.session.delete(Meals.query.filter_by(date=i, name=n).first())
|
|
db.session.commit()
|
|
getMealsFromAPI(i, True)
|