Files
barsic/extensions/google_calendar/client.py
2026-11-07 22:34:12 +03:00

357 lines
14 KiB
Python

"""Google Calendar client supporting both Service Account and OAuth2 across all calendars."""
import asyncio
import logging
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Optional
from google.auth.transport.requests import Request
from google.oauth2 import service_account
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from homeagent.config import get_settings
logger = logging.getLogger(__name__)
SCOPES = ["https://www.googleapis.com/auth/calendar"]
def _execute_with_retry(request: Any, retries: int = 3, initial_delay: float = 0.5) -> Any:
"""Execute Google API request with retry on transient SSL/network errors."""
for attempt in range(retries):
try:
return request.execute()
except Exception as e:
if attempt == retries - 1:
raise
logger.warning(
"Google Calendar API call attempt %d failed: %s. Retrying in %.1fs...",
attempt + 1,
e,
initial_delay * (2 ** attempt),
)
time.sleep(initial_delay * (2 ** attempt))
class GoogleCalendarClient:
"""Client for Google Calendar v3 supporting Service Account and OAuth2 across multiple calendars."""
def __init__(self) -> None:
self.settings = get_settings()
self.default_calendar_id = self.settings.GOOGLE_CALENDAR_ID or "primary"
self._service: Optional[Any] = None
def _get_credentials(self) -> Optional[Any]:
auth_type = self.settings.GOOGLE_AUTH_TYPE
sa_file = Path(self.settings.GOOGLE_SERVICE_ACCOUNT_FILE or "service_account.json")
oauth_creds_file = Path(self.settings.GOOGLE_OAUTH_CREDENTIALS_FILE or "credentials.json")
oauth_token_file = Path(self.settings.GOOGLE_OAUTH_TOKEN_FILE)
# 1. Service Account
if auth_type in ("service_account", "auto") and sa_file.exists():
try:
logger.info("Using Google Calendar Service Account credentials from %s", sa_file)
return service_account.Credentials.from_service_account_file(
str(sa_file), scopes=SCOPES
)
except Exception as e:
logger.error("Failed to load service account credentials: %s", e)
if auth_type == "service_account":
raise
# 2. OAuth2
if auth_type in ("oauth2", "auto"):
creds = None
if oauth_token_file.exists():
try:
creds = Credentials.from_authorized_user_file(str(oauth_token_file), SCOPES)
except Exception as e:
logger.warning("Could not read token file %s: %s", oauth_token_file, e)
if creds and creds.valid:
return creds
if creds and creds.expired and creds.refresh_token:
try:
creds.refresh(Request())
oauth_token_file.parent.mkdir(parents=True, exist_ok=True)
with open(oauth_token_file, "w", encoding="utf-8") as token_f:
token_f.write(creds.to_json())
return creds
except Exception as e:
logger.warning("Failed refreshing token: %s", e)
if oauth_creds_file.exists():
logger.info("Credentials file found (%s). Initiating OAuth flow...", oauth_creds_file)
try:
flow = InstalledAppFlow.from_client_secrets_file(str(oauth_creds_file), SCOPES)
creds = flow.run_local_server(port=0)
oauth_token_file.parent.mkdir(parents=True, exist_ok=True)
with open(oauth_token_file, "w", encoding="utf-8") as token_f:
token_f.write(creds.to_json())
return creds
except Exception as e:
logger.error("OAuth flow failed: %s", e)
if auth_type == "oauth2":
raise
return None
def is_configured(self) -> bool:
try:
return self._get_credentials() is not None
except Exception:
return False
def _get_service(self) -> Any:
if self._service is None:
creds = self._get_credentials()
if not creds:
raise ValueError(
"Google Calendar credentials not found. Provide either 'service_account.json' "
"or 'credentials.json' (OAuth2) as configured in .env."
)
self._service = build("calendar", "v3", credentials=creds, cache_discovery=False)
return self._service
async def list_calendars(self) -> list[dict[str, Any]]:
"""List all calendars accessible by the user/service account."""
service = self._get_service()
def _fetch_calendars() -> list[dict[str, Any]]:
configured_ids: list[str] = []
if self.default_calendar_id and self.default_calendar_id != "primary":
configured_ids.append(self.default_calendar_id)
for cid in self.settings.GOOGLE_ADDITIONAL_CALENDAR_IDS:
if cid not in configured_ids:
configured_ids.append(cid)
creds = self._get_credentials()
sa_email = getattr(creds, "service_account_email", None)
# 1. If service account, auto-sync configured calendars into service account calendarList
if sa_email and configured_ids:
for cid in configured_ids:
try:
_execute_with_retry(service.calendarList().insert(body={"id": cid}))
logger.debug("Registered calendar %s in service account calendarList", cid)
except Exception:
# 409 already exists or no permission, safe to ignore
pass
# 2. Query calendarList with retry
calendar_items: list[dict[str, Any]] = []
try:
result = _execute_with_retry(service.calendarList().list())
calendar_items = result.get("items", [])
except Exception as e:
logger.warning("Could not list calendars via calendarList(): %s", e)
# 3. Filter out service account's own empty primary calendar
filtered_items: list[dict[str, Any]] = []
for item in calendar_items:
cal_id = item.get("id", "")
if sa_email and cal_id == sa_email:
# Skip service account's internal empty primary calendar
continue
filtered_items.append(item)
# 4. Ensure all configured calendars are present
existing_ids = {item.get("id") for item in filtered_items}
for cid in configured_ids:
if cid not in existing_ids:
try:
meta = _execute_with_retry(service.calendars().get(calendarId=cid))
filtered_items.append({
"id": cid,
"summary": meta.get("summary") or cid,
"primary": (cid == self.default_calendar_id),
"description": meta.get("description", ""),
})
existing_ids.add(cid)
except Exception as e:
logger.warning("Could not fetch calendar metadata for %s: %s", cid, e)
filtered_items.append({
"id": cid,
"summary": cid,
"primary": (cid == self.default_calendar_id),
})
existing_ids.add(cid)
# 5. Determine primary calendar
has_primary = False
for item in filtered_items:
if self.default_calendar_id and self.default_calendar_id != "primary":
if item.get("id") == self.default_calendar_id:
item["primary"] = True
has_primary = True
else:
item["primary"] = False
elif item.get("primary"):
has_primary = True
if not has_primary and filtered_items:
filtered_items[0]["primary"] = True
if not filtered_items:
return [{"id": self.default_calendar_id, "summary": "Основной", "primary": True}]
return filtered_items
return await asyncio.to_thread(_fetch_calendars)
async def resolve_calendar_id(self, identifier: Optional[str]) -> str:
"""Resolve calendar name or ID to an actual calendarId."""
calendars = await self.list_calendars()
if not identifier or identifier.lower() in ("primary", "основной", "default"):
for cal in calendars:
if cal.get("primary"):
return cal["id"]
if self.default_calendar_id != "primary":
return self.default_calendar_id
if calendars:
return calendars[0]["id"]
return "primary"
clean = identifier.strip().lower()
# Check by ID exact match
for cal in calendars:
if cal.get("id", "").lower() == clean:
return cal["id"]
# Check by Summary substring / exact match
for cal in calendars:
summary = cal.get("summary", "").lower()
if clean in summary or summary in clean:
return cal["id"]
# Fallback to passed identifier
return identifier.strip()
async def list_events(
self,
time_min: Optional[datetime] = None,
time_max: Optional[datetime] = None,
max_results: int = 25,
calendar_id: Optional[str] = None,
) -> list[dict[str, Any]]:
"""List events in time window across all calendars (if calendar_id is None) or a specific calendar."""
service = self._get_service()
if time_min is None:
time_min = datetime.now(timezone.utc)
if time_max is None:
time_max = time_min + timedelta(days=7)
t_min_str = time_min.isoformat()
t_max_str = time_max.isoformat()
# Determine target calendars
if calendar_id:
resolved_id = await self.resolve_calendar_id(calendar_id)
target_calendars = [{"id": resolved_id, "summary": resolved_id}]
else:
target_calendars = await self.list_calendars()
def _fetch_from_calendars() -> list[dict[str, Any]]:
all_events: list[dict[str, Any]] = []
for cal in target_calendars:
cal_id = cal.get("id")
if not cal_id:
continue
cal_name = cal.get("summary", "Календарь")
try:
request = service.events().list(
calendarId=cal_id,
timeMin=t_min_str,
timeMax=t_max_str,
maxResults=max_results,
singleEvents=True,
orderBy="startTime",
)
events_result = _execute_with_retry(request)
items = events_result.get("items", [])
for item in items:
item["_calendar_id"] = cal_id
item["_calendar_name"] = cal_name
item["_is_primary"] = cal.get("primary", False)
all_events.append(item)
except Exception as e:
logger.warning("Failed to fetch events from calendar '%s' (%s): %s", cal_name, cal_id, e)
# Sort all combined events chronologically by start date/time
def _get_start_key(ev: dict[str, Any]) -> str:
start = ev.get("start", {})
return str(start.get("dateTime") or start.get("date") or "")
all_events.sort(key=_get_start_key)
return all_events[:max_results]
return await asyncio.to_thread(_fetch_from_calendars)
async def create_event(
self,
summary: str,
start_time: datetime,
end_time: datetime,
description: str = "",
attendees: Optional[list[str]] = None,
calendar_id: Optional[str] = None,
) -> dict[str, Any]:
"""Create a new event in calendar."""
service = self._get_service()
target_cal_id = await self.resolve_calendar_id(calendar_id or self.default_calendar_id)
event_body: dict[str, Any] = {
"summary": summary,
"description": description,
"start": {"dateTime": start_time.isoformat()},
"end": {"dateTime": end_time.isoformat()},
}
if attendees:
event_body["attendees"] = [{"email": email} for email in attendees]
def _insert() -> dict[str, Any]:
return _execute_with_retry(service.events().insert(calendarId=target_cal_id, body=event_body))
return await asyncio.to_thread(_insert)
async def delete_event(self, event_id: str, calendar_id: Optional[str] = None) -> None:
"""Delete an event by ID, searching across calendars if calendar_id is not specified."""
service = self._get_service()
if calendar_id:
target_cal_id = await self.resolve_calendar_id(calendar_id)
await asyncio.to_thread(
lambda: _execute_with_retry(service.events().delete(calendarId=target_cal_id, eventId=event_id))
)
return
# If calendar not specified, search and delete
calendars = await self.list_calendars()
def _search_and_delete() -> None:
last_err = None
for cal in calendars:
cal_id = cal.get("id")
if not cal_id:
continue
try:
_execute_with_retry(service.events().delete(calendarId=cal_id, eventId=event_id))
logger.info("Deleted event %s from calendar %s", event_id, cal_id)
return
except Exception as e:
last_err = e
if last_err:
raise last_err
await asyncio.to_thread(_search_and_delete)