mirror of
https://git.bolliret.ch/pcs/pcs-website
synced 2026-01-18 15:51:36 +01:00
Claude.ai refactored my script and optimized error handling along the way. ...looking for a new job now. ... ...me, not Claude!
This commit is contained in:
parent
73cee8a653
commit
f6d1d46dc9
1 changed files with 130 additions and 92 deletions
|
|
@ -1,110 +1,148 @@
|
||||||
from bs4 import BeautifulSoup
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
from datetime import datetime, date
|
from datetime import datetime, date
|
||||||
import recurring_ical_events
|
from typing import Optional, NamedTuple
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
from bs4 import BeautifulSoup
|
||||||
from icalendar import Calendar
|
from icalendar import Calendar
|
||||||
|
import recurring_ical_events
|
||||||
import locale
|
import locale
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class EventDetails:
|
||||||
|
weekday: str
|
||||||
|
date: str
|
||||||
|
time: str
|
||||||
|
summary: str
|
||||||
|
location: str
|
||||||
|
|
||||||
# TODO: Handling missing arguments is way more complex in Python :(
|
def to_html(self) -> str:
|
||||||
if len(sys.argv) != 2:
|
return (
|
||||||
print("Usage: python3 {} <ICS_URL>".format(sys.argv[0]))
|
f'<div class="nextevent">{self.weekday} '
|
||||||
|
f'<strong>{self.date}{self.time}, {self.summary}</strong>'
|
||||||
|
f'{self.location}</div>'
|
||||||
|
)
|
||||||
|
|
||||||
# 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
|
class EventProcessor:
|
||||||
sourcefile = "/opt/lektor/project/content/contents.lr"
|
def __init__(self, ics_url: str, content_file: str):
|
||||||
|
self.ics_url = ics_url
|
||||||
|
self.content_file = Path(content_file)
|
||||||
|
self.fallback_html = (
|
||||||
|
'<div class="nextevent">Leider unbekannt, aber '
|
||||||
|
'<strong>frag mal den Vorstand</strong> der müsste es wissen</div>'
|
||||||
|
)
|
||||||
|
|
||||||
fallbackreplacestr = "<div class=\"nextevent\">Leider unbekannt, aber <strong>frag mal den Vorstand</strong> der müsste es wissen</div>"
|
@property
|
||||||
|
def fallback_content(self) -> str:
|
||||||
|
return f"""_model: htmlpage
|
||||||
|
---
|
||||||
|
title: Willkommen beim PC Stammertal
|
||||||
|
---
|
||||||
|
html:
|
||||||
|
|
||||||
with open(sourcefile) as fp:
|
<h3>Unser nächster Anlass: </h3><br/>
|
||||||
soup = BeautifulSoup(fp, 'html.parser')
|
{self.fallback_html}
|
||||||
cols = soup.find_all('div', {'class' : 'nextevent'})
|
<div class="threecolumn">
|
||||||
|
<div>
|
||||||
|
<a href="termine/"><img src=" /images/termine_square.jpg" alt="Terminkalender"> All unsere Termine</a><!-- Fallback>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<a href="about/"><img src="/images/about_square.jpg" alt="Buch"> Alle Infos über uns</a>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<a href="kontakt/"><img src="/images/kontakt_square.jpg" alt="Briefe"> Kontaktiere uns</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
---
|
||||||
|
_template:
|
||||||
|
|
||||||
sourcestr = ""
|
page.html
|
||||||
|
"""
|
||||||
|
|
||||||
if len(cols) != 1 :
|
def setup_locale(self) -> None:
|
||||||
sourcestr = ""
|
try:
|
||||||
else:
|
locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8')
|
||||||
sourcestr = str(cols[0])
|
except locale.Error as e:
|
||||||
|
print(f"Warning: Failed to set locale: {e}", file=sys.stderr)
|
||||||
|
|
||||||
with open(sourcefile, 'r') as file:
|
def fetch_calendar(self) -> Optional[Calendar]:
|
||||||
file_contents = file.read()
|
try:
|
||||||
|
response = requests.get(self.ics_url, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return Calendar.from_ical(response.content)
|
||||||
|
except (requests.RequestException, ValueError) as e:
|
||||||
|
print(f"Error fetching calendar: {e}", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def format_event_time(self, start: datetime | date) -> str:
|
||||||
|
return "" if isinstance(start, date) and not isinstance(start, datetime) else start.strftime(" %-H:%M")
|
||||||
|
|
||||||
url = sys.argv[1]
|
def get_next_event(self, calendar: Calendar) -> Optional[EventDetails]:
|
||||||
|
try:
|
||||||
|
events = recurring_ical_events.of(calendar).after(datetime.now())
|
||||||
|
event = next(events)
|
||||||
|
start = event.get('dtstart').dt
|
||||||
|
|
||||||
locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8')
|
return EventDetails(
|
||||||
|
weekday=start.strftime("%A"),
|
||||||
|
date=start.strftime("%-d. %B"),
|
||||||
|
time=self.format_event_time(start),
|
||||||
|
summary=event.get('summary', ''),
|
||||||
|
location=f", {event.get('location')}" if event.get('location') else ""
|
||||||
|
)
|
||||||
|
|
||||||
#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)
|
except (StopIteration, AttributeError) as e:
|
||||||
response = requests.get(url)
|
print(f"No upcoming events found: {e}", file=sys.stderr)
|
||||||
calendar = Calendar.from_ical(response.content)
|
return None
|
||||||
|
|
||||||
# Get recurring and non-recurring events
|
def read_current_content(self) -> tuple[str, str]:
|
||||||
events = recurring_ical_events.of(calendar).after(datetime.now())
|
try:
|
||||||
|
content = self.content_file.read_text()
|
||||||
|
soup = BeautifulSoup(content, 'html.parser')
|
||||||
|
events = soup.find_all('div', {'class': 'nextevent'})
|
||||||
|
return content, str(events[0]) if len(events) == 1 else ""
|
||||||
|
|
||||||
try:
|
except (IOError, IndexError) as e:
|
||||||
event = next(events)
|
print(f"Error reading content file: {e}", file=sys.stderr)
|
||||||
|
return "", ""
|
||||||
|
|
||||||
|
def process(self) -> str:
|
||||||
|
self.setup_locale()
|
||||||
|
|
||||||
start = event.get('dtstart').dt
|
content, source_str = self.read_current_content()
|
||||||
out_summary = event.get('summary')
|
if not content:
|
||||||
location = event.get('location', 'No location specified')
|
return self.fallback_content
|
||||||
|
|
||||||
out_weekday = start.strftime("%A")
|
if len(source_str) > 0 and source_str in content:
|
||||||
out_startdate = start.strftime("%-d. %B")
|
calendar = self.fetch_calendar()
|
||||||
|
if not calendar:
|
||||||
|
return content.replace(source_str, self.fallback_html).rstrip()
|
||||||
|
|
||||||
# Format output based on whether it's an all-day event
|
event = self.get_next_event(calendar)
|
||||||
if isinstance(start, date) and not isinstance(start, datetime):
|
if not event:
|
||||||
out_starttime = ""
|
return content.replace(source_str, self.fallback_html).rstrip()
|
||||||
else:
|
|
||||||
out_starttime = start.strftime(" %-H:%M")
|
|
||||||
|
|
||||||
if location != 'No location specified':
|
return content.replace(source_str, event.to_html()).rstrip()
|
||||||
out_location = f", {location}"
|
|
||||||
else:
|
|
||||||
out_location = ""
|
|
||||||
|
|
||||||
replacestr = "<div class=\"nextevent\">{} <strong> {}{}, {}</strong>{}</div>".format(out_weekday, out_startdate, out_starttime, out_summary, out_location)
|
return self.fallback_content
|
||||||
|
|
||||||
except StopIteration:
|
def main() -> None:
|
||||||
|
if len(sys.argv) != 2:
|
||||||
|
print(f"Usage: {sys.argv[0]} <ICS_URL>", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
replacestr = fallbackreplacestr
|
processor = EventProcessor(
|
||||||
|
ics_url=sys.argv[1],
|
||||||
|
content_file="/opt/lektor/project/content/contents.lr"
|
||||||
|
)
|
||||||
|
|
||||||
# Why should we check if sourcestring is in the file when it originates from there?!?
|
print(processor.process(), end='')
|
||||||
# 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("<h3>Unser nächster Anlass: </h3><br/>")
|
|
||||||
print(fallbackreplacestr)
|
|
||||||
print("<div class=\"threecolumn\">")
|
|
||||||
print(" <div>")
|
|
||||||
print(" <a href=\"termine/\"><img src=\" /images/termine_square.jpg\" alt=\"Terminkalender\"> All unsere Termine</a>")
|
|
||||||
print(" </div>")
|
|
||||||
print(" <div>")
|
|
||||||
print(" <a href=\"about/\"><img src=\"/images/about_square.jpg\" alt=\"Buch\"> Alle Infos über uns</a>")
|
|
||||||
print(" </div>")
|
|
||||||
print(" <div>")
|
|
||||||
print(" <a href=\"kontakt/\"><img src=\"/images/kontakt_square.jpg\" alt=\"Briefe\"> Kontaktiere uns</a>")
|
|
||||||
print(" </div>")
|
|
||||||
print("</div>")
|
|
||||||
print("---")
|
|
||||||
print("_template:")
|
|
||||||
print("")
|
|
||||||
print("page.html")
|
|
||||||
print("")
|
print("")
|
||||||
print("")
|
print("")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Loading…
Add table
Reference in a new issue