#!/usr/bin/env python3
import sys
from pathlib import Path
from datetime import datetime, date, timezone
from typing import Optional, NamedTuple
from dataclasses import dataclass
from bs4 import BeautifulSoup
import locale
from calendarstuff import get_events
@dataclass
class EventDetails:
weekday: str
date: str
time: str
summary: str
location: str
def to_html(self) -> str:
return (
f'
{self.weekday} '
f'{self.date}{self.time}, {self.summary}'
f'{self.location}
'
)
class EventProcessor:
def __init__(self, ics_url: str, content_file: str):
self.ics_url = ics_url
self.content_file = Path(content_file)
self.fallback_html = (
'Leider unbekannt, aber '
'frag mal den Vorstand der müsste es wissen
'
)
@property
def fallback_content(self) -> str:
return f"""_model: htmlpage
---
title: Willkommen beim PC Stammertal
---
html:
Unser nächster Anlass:
{self.fallback_html}
...und auch nicht verpassen:
---
_template:
page.html
"""
def setup_locale(self) -> None:
try:
locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8')
except locale.Error as e:
print(f"Warning: Failed to set locale: {e}", file=sys.stderr)
def format_event_time(self, start: datetime | date) -> str:
return "" if isinstance(start, date) and not isinstance(start, datetime) else start.strftime(" %-H:%M")
def get_next_event(self) -> Optional[EventDetails]:
try:
events = get_events(self.ics_url)
event = events[0]
start = event.get('dtstart').dt
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 ""
)
except (StopIteration, AttributeError) as e:
print(f"No upcoming events found: {e}", file=sys.stderr)
return None
def read_current_content(self) -> tuple[str, str]:
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 ""
except (IOError, IndexError) as e:
print(f"Error reading content file: {e}", file=sys.stderr)
return "", ""
def process(self) -> str:
self.setup_locale()
content, source_str = self.read_current_content()
if not content:
return self.fallback_content
if len(source_str) > 0 and source_str in content:
event = self.get_next_event()
if not event:
return content.replace(source_str, self.fallback_html).rstrip()
return content.replace(source_str, event.to_html()).rstrip()
return self.fallback_content
def main() -> None:
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} ", file=sys.stderr)
sys.exit(1)
processor = EventProcessor(
ics_url=sys.argv[1],
content_file="/opt/lektor/project/content/contents.lr"
)
print(processor.process(), end='')
print("")
print("")
if __name__ == "__main__":
main()