Files
luk/src/services/microsoft_graph/calendar.py
2025-07-07 11:50:16 -04:00

62 lines
2.0 KiB
Python

"""
Calendar operations for Microsoft Graph API.
"""
import os
from datetime import datetime, timedelta
from .client import fetch_with_aiohttp
async def fetch_calendar_events(
headers, days_back=1, days_forward=6, start_date=None, end_date=None
):
"""
Fetch calendar events from Microsoft Graph API.
Args:
headers (dict): Headers including authentication.
days_back (int): Number of days to look back.
days_forward (int): Number of days to look forward.
start_date (datetime): Optional start date, overrides days_back if provided.
end_date (datetime): Optional end date, overrides days_forward if provided.
Returns:
tuple: (events, total_count) where events is a list of event dictionaries
and total_count is the total number of events.
"""
# Calculate date range
if start_date is None:
start_date = datetime.now() - timedelta(days=days_back)
if end_date is None:
end_date = start_date + timedelta(days=days_forward)
# Format dates for API
start_date_str = start_date.strftime("%Y-%m-%dT00:00:00Z")
end_date_str = end_date.strftime("%Y-%m-%dT23:59:59Z")
# Prepare the API query
calendar_url = (
f"https://graph.microsoft.com/v1.0/me/calendarView?"
f"startDateTime={start_date_str}&endDateTime={end_date_str}&"
f"$select=id,subject,organizer,start,end,location,isAllDay,showAs,sensitivity&$count=true"
)
events = []
# Make the API request
response_data = await fetch_with_aiohttp(calendar_url, headers)
events.extend(response_data.get("value", []))
# Check if there are more events (pagination)
next_link = response_data.get("@odata.nextLink")
while next_link:
response_data = await fetch_with_aiohttp(next_link, headers)
events.extend(response_data.get("value", []))
next_link = response_data.get("@odata.nextLink")
# Return events and total count
total_count = response_data.get("@odata.count", len(events))
return events, total_count