from datetime import datetime, timedelta from typing import Iterator from fastapi import APIRouter, Depends from pydantic import BaseModel from .. import caldav_principal from ._common import CalendarNameLister, PrefixFinder, PrefixUnique router = APIRouter(prefix="/calendar", tags=["calendar"]) _lister = CalendarNameLister() _finder = PrefixFinder(_lister) _unique = PrefixUnique(_finder) @router.get("/list", response_model=list[str]) async def list_calendars( names: Iterator[str] = Depends(_lister), ) -> list[str]: return list(names) @router.get("/find/{prefix}", response_model=list[str]) async def find_calendars( names: Iterator[str] = Depends(_finder), ) -> list[str]: return list(names) class CalEvent(BaseModel): summary: str description: str dtstart: datetime dtend: datetime @router.get("/get/{prefix}", response_model=list[CalEvent]) async def get_calendar( name: Iterator[str] = Depends(_unique), ) -> list[CalEvent]: calendar = caldav_principal().calendar(name=name) return ( CalEvent( summary=vevent.summary.value, description=vevent.description.value, dtstart=vevent.dtstart.value, dtend=vevent.dtend.value, ) for event in calendar.date_search( start=datetime.now(), end=datetime.now() + timedelta(days=365), expand=True, ) for vevent in event.vobject_instance.contents["vevent"] )