from bs4 import BeautifulSoup import sys import requests from ics import Calendar import arrow import locale # TODO: Handling missing arguments is way more complex in Python :( if len(sys.argv) != 2: print("Usage: python3 {} ".format(sys.argv[0])) # TODO: Reading from the same file as the output of this script is piped into leads to synchronization/buffering issues, we therefore have to do some quirks in entrypoint.sh sourcefile = "/opt/lektor/project/content/contents.lr" fallbackreplacestr = "
Leider unbekannt, aber frag mal den Vorstand der müsste es wissen
" with open(sourcefile) as fp: soup = BeautifulSoup(fp, 'html.parser') cols = soup.find_all('div', {'class' : 'nextevent'}) sourcestr = "" if len(cols) != 1 : sourcestr = "" else: sourcestr = str(cols[0]) with open(sourcefile, 'r') as file: file_contents = file.read() url = sys.argv[1] #TODO: Handling HTTP request or pasring errors is currently completely missing (although I implemented such a nice handling if the script would just gracefully continue on exceptions) c = Calendar(requests.get(url).text) locale.setlocale(locale.LC_TIME, locale.normalize("de_DE.UTF-8")) colevents = list(c.timeline.start_after(arrow.now())) if len(colevents) > 0 : weekday = colevents[0].begin.strftime("%A") date = colevents[0].begin.strftime("%-d. %B") time = colevents[0].begin.strftime(" %-H:%M") if not colevents[0].all_day else "" name = colevents[0].name location = " in " + colevents[0].location if colevents[0].location != None else "" replacestr = "
{} {}{}, {}{}
".format(weekday, date, time, name, location) else: replacestr = fallbackreplacestr # Why should we check if sourcestring is in the file when it originates from there?!? # Because theoretically it could be that BeautifulSoup extracts it slightly different (sepcial characters or such). # And as here we do a simple replace it wouldn't catch anything if it isn't an exact match. # Also an empty string is a perfect match and matches in the wrong place, therefore we check for a minimal length > 0 # TODO: Most probably replacement could be done by BeautifulSoup too. # But as this is a collection of StackOverflow roadkill rather than fine crafted menu of purest python ingredients, that's just what I could catch most easily. if len(sourcestr) > 0 and sourcestr in file_contents: updated_contents = file_contents.replace(sourcestr, replacestr) print(updated_contents) else: print("_model: htmlpage") print("---") print("title: Willkommen beim PC Stammertal") print("---") print("html:") print("") print("

Unser nächster Anlass:


") print(fallbackreplacestr) print("
") print("
") print(" \"Terminkalender\" All unsere Termine") print("
") print("
") print(" \"Buch\" Alle Infos über uns") print("
") print("
") print(" \"Briefe\" Kontaktiere uns") print("
") print("
") print("---") print("_template:") print("") print("page.html") print("") print("")