initial commit heh

This commit is contained in:
timka123 committed 2026-11-07 22:34:12 +03:00
commit 5eea9d0f2c
78 files changed
+11181

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
"""Google Calendar extension package with multi-calendar support."""
from extensions.google_calendar.tools import (
calendar_create_event,
calendar_date_schedule,
calendar_delete_event,
calendar_list_calendars,
calendar_list_events,
calendar_today_schedule,
calendar_tomorrow_schedule,
)
__all__ = [
"calendar_list_calendars",
"calendar_list_events",
"calendar_today_schedule",
"calendar_tomorrow_schedule",
"calendar_date_schedule",
"calendar_create_event",
"calendar_delete_event",
]
+356
View File
@@ -0,0 +1,356 @@
"""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)
+334
View File
@@ -0,0 +1,334 @@
"""Google Calendar tools exposed to HomeAgent and Gemini (multi-calendar support)."""
from datetime import datetime, time, timedelta, timezone
from typing import Optional
from extensions.google_calendar.client import GoogleCalendarClient
from homeagent.config import get_settings
from homeagent.tools.base import tool
_calendar_client: Optional[GoogleCalendarClient] = None
def get_calendar_client() -> GoogleCalendarClient:
global _calendar_client
if _calendar_client is None:
_calendar_client = GoogleCalendarClient()
return _calendar_client
def _parse_iso_datetime(dt_str: str) -> datetime:
"""Parse ISO formatted string into datetime."""
dt_str = dt_str.strip()
if dt_str.endswith("Z"):
dt_str = dt_str[:-1] + "+00:00"
dt = datetime.fromisoformat(dt_str)
if dt.tzinfo is None:
dt = dt.astimezone()
return dt
@tool(
name="calendar_list_calendars",
description="Показать список всех доступных Google Календарей (основной, рабочие, личные, командные).",
)
async def calendar_list_calendars() -> str:
"""Список доступных календарей."""
settings = get_settings()
if not settings.GOOGLE_CALENDAR_ENABLED:
return "Интеграция с Google Календарем отключена (GOOGLE_CALENDAR_ENABLED=False)."
client = get_calendar_client()
if not client.is_configured():
return (
"Google Календарь не настроен. Добавьте service_account.json или credentials.json "
"согласно инструкциям в docs/SETUP.md"
)
try:
calendars = await client.list_calendars()
if not calendars:
return "Не найдено ни одного доступного календаря."
lines = [f"Доступные Google Календари ({len(calendars)}):"]
for cal in calendars:
cal_id = cal.get("id", "")
summary = cal.get("summary", "Без названия")
primary_tag = " ⭐ (Основной)" if cal.get("primary") else ""
lines.append(f"- **{summary}**{primary_tag} [ID: `{cal_id}`]")
return "\n".join(lines)
except Exception as e:
return f"Ошибка получения списка календарей: {type(e).__name__}: {str(e)}"
@tool(
name="calendar_list_events",
description="Получить события и встречи сразу со ВСЕХ доступных Google Календарей (или из конкретного календаря) на указанное количество дней вперед.",
)
async def calendar_list_events(
days_ahead: int = 7,
max_results: int = 25,
calendar: Optional[str] = None,
) -> str:
"""Список событий календаря.
Args:
days_ahead: На сколько дней вперед искать события (по умолчанию 7)
max_results: Максимальное количество событий (по умолчанию 25)
calendar: Имя или ID конкретного календаря, если нужно отфильтровать (по умолчанию проверяются ВСЕ календари)
"""
settings = get_settings()
if not settings.GOOGLE_CALENDAR_ENABLED:
return "Интеграция с Google Календарем отключена (GOOGLE_CALENDAR_ENABLED=False)."
client = get_calendar_client()
if not client.is_configured():
return (
"Google Календарь не настроен. Добавьте service_account.json или credentials.json "
"в корень проекта согласно инструкциям в docs/SETUP.md"
)
try:
now = datetime.now().astimezone()
future = now + timedelta(days=days_ahead)
events = await client.list_events(
time_min=now,
time_max=future,
max_results=max_results,
calendar_id=calendar,
)
scope_desc = f"календаря '{calendar}'" if calendar else "всех доступных календарей"
if not events:
return f"В ближайшие {days_ahead} дн. событий из {scope_desc} не найдено."
lines = [f"События из {scope_desc} на ближайшие {days_ahead} дн. (найдено: {len(events)}):"]
for event in events:
event_id = event.get("id", "")
summary = event.get("summary", "Без названия")
start = event.get("start", {}).get("dateTime") or event.get("start", {}).get("date")
end = event.get("end", {}).get("dateTime") or event.get("end", {}).get("date")
cal_label = f"[{event.get('_calendar_name', 'Календарь')}] " if not calendar else ""
lines.append(f"- {cal_label}**{summary}**: c {start} по {end} [ID: `{event_id}`]")
return "\n".join(lines)
except Exception as e:
return f"Ошибка получения событий календаря: {type(e).__name__}: {str(e)}"
@tool(
name="calendar_today_schedule",
description="Получить расписание встреч и событий на сегодня (или захватить завтра) сразу со ВСЕХ доступных Google Календарей (личных, рабочих, учебных, командных).",
)
async def calendar_today_schedule(calendar: Optional[str] = None, include_tomorrow: bool = False) -> str:
"""Расписание на сегодняшний день по всем календарям.
Args:
calendar: Опционально: фильтр по конкретному календарю (название или ID)
include_tomorrow: Если True, включить также расписание на завтрашний день
"""
client = get_calendar_client()
if not client.is_configured():
return "Google Календарь не настроен в .env"
try:
now = datetime.now().astimezone()
start_of_day = datetime.combine(now.date(), time.min).replace(tzinfo=now.tzinfo)
target_date = now.date() + timedelta(days=1) if include_tomorrow else now.date()
end_of_day = datetime.combine(target_date, time.max).replace(tzinfo=now.tzinfo)
events = await client.list_events(
time_min=start_of_day,
time_max=end_of_day,
max_results=50,
calendar_id=calendar,
)
scope_desc = f"календарю '{calendar}'" if calendar else "всем календарям"
period_title = f"сегодня ({now.strftime('%d.%m.%Y')})" if not include_tomorrow else f"сегодня и завтра ({now.strftime('%d.%m')} - {target_date.strftime('%d.%m.%Y')})"
if not events:
return f"На {period_title} по {scope_desc} запланированных встреч нет."
lines = [f"📅 Расписание на {period_title} по {scope_desc}:"]
for event in events:
summary = event.get("summary", "Без названия")
start = event.get("start", {}).get("dateTime") or event.get("start", {}).get("date")
end = event.get("end", {}).get("dateTime") or event.get("end", {}).get("date")
desc = event.get("description", "")
desc_note = f" ({desc[:60]}...)" if desc else ""
cal_label = f"[{event.get('_calendar_name', 'Календарь')}] " if not calendar else ""
lines.append(f"- {cal_label}**{summary}**: {start} - {end}{desc_note}")
return "\n".join(lines)
except Exception as e:
return f"Ошибка получения расписания: {type(e).__name__}: {str(e)}"
@tool(
name="calendar_tomorrow_schedule",
description="Получить расписание встреч и событий на ЗАВТРА сразу со ВСЕХ доступных Google Календарей (личных, рабочих, учебных, командных).",
)
async def calendar_tomorrow_schedule(calendar: Optional[str] = None) -> str:
"""Расписание на завтрашний день по всем календарям.
Args:
calendar: Опционально: фильтр по конкретному календарю (название или ID)
"""
client = get_calendar_client()
if not client.is_configured():
return "Google Календарь не настроен в .env"
try:
now = datetime.now().astimezone()
tomorrow_date = now.date() + timedelta(days=1)
start_of_day = datetime.combine(tomorrow_date, time.min).replace(tzinfo=now.tzinfo)
end_of_day = datetime.combine(tomorrow_date, time.max).replace(tzinfo=now.tzinfo)
events = await client.list_events(
time_min=start_of_day,
time_max=end_of_day,
max_results=50,
calendar_id=calendar,
)
scope_desc = f"календарю '{calendar}'" if calendar else "всем календарям"
if not events:
return f"На завтра ({tomorrow_date.strftime('%d.%m.%Y')}) по {scope_desc} запланированных встреч нет."
lines = [f"📅 Расписание на завтра ({tomorrow_date.strftime('%A, %d.%m.%Y')}) по {scope_desc}:"]
for event in events:
summary = event.get("summary", "Без названия")
start = event.get("start", {}).get("dateTime") or event.get("start", {}).get("date")
end = event.get("end", {}).get("dateTime") or event.get("end", {}).get("date")
desc = event.get("description", "")
desc_note = f" ({desc[:60]}...)" if desc else ""
cal_label = f"[{event.get('_calendar_name', 'Календарь')}] " if not calendar else ""
lines.append(f"- {cal_label}**{summary}**: {start} - {end}{desc_note}")
return "\n".join(lines)
except Exception as e:
return f"Ошибка получения расписания на завтра: {type(e).__name__}: {str(e)}"
@tool(
name="calendar_date_schedule",
description="Получить расписание встреч и событий на любую конкретную дату (формат 'YYYY-MM-DD' или ключевые слова 'сегодня', 'завтра') со всех доступных Google Календарей.",
)
async def calendar_date_schedule(date_str: str, calendar: Optional[str] = None) -> str:
"""Расписание на указанную дату.
Args:
date_str: Дата в формате 'YYYY-MM-DD' (например '2026-11-08') или слова 'today', 'сегодня', 'tomorrow', 'завтра'
calendar: Опционально: фильтр по конкретному календарю
"""
client = get_calendar_client()
if not client.is_configured():
return "Google Календарь не настроен в .env"
try:
now = datetime.now().astimezone()
clean = date_str.strip().lower()
if clean in ("today", "сегодня"):
target_date = now.date()
elif clean in ("tomorrow", "завтра"):
target_date = now.date() + timedelta(days=1)
elif clean in ("yesterday", "вчера"):
target_date = now.date() - timedelta(days=1)
else:
target_date = datetime.strptime(clean, "%Y-%m-%d").date()
start_of_day = datetime.combine(target_date, time.min).replace(tzinfo=now.tzinfo)
end_of_day = datetime.combine(target_date, time.max).replace(tzinfo=now.tzinfo)
events = await client.list_events(
time_min=start_of_day,
time_max=end_of_day,
max_results=50,
calendar_id=calendar,
)
scope_desc = f"календарю '{calendar}'" if calendar else "всем календарям"
if not events:
return f"На дату {target_date.strftime('%d.%m.%Y')} по {scope_desc} запланированных встреч нет."
lines = [f"📅 Расписание на {target_date.strftime('%A, %d.%m.%Y')} по {scope_desc}:"]
for event in events:
summary = event.get("summary", "Без названия")
start = event.get("start", {}).get("dateTime") or event.get("start", {}).get("date")
end = event.get("end", {}).get("dateTime") or event.get("end", {}).get("date")
desc = event.get("description", "")
desc_note = f" ({desc[:60]}...)" if desc else ""
cal_label = f"[{event.get('_calendar_name', 'Календарь')}] " if not calendar else ""
lines.append(f"- {cal_label}**{summary}**: {start} - {end}{desc_note}")
return "\n".join(lines)
except Exception as e:
return f"Ошибка получения расписания на {date_str}: {type(e).__name__}: {str(e)}"
@tool(
name="calendar_create_event",
description="Создать новое событие или встречу в Google Календаре. Можно указать в какой именно календарь добавить (по умолчанию — в основной).",
)
async def calendar_create_event(
summary: str,
start_iso: str,
end_iso: str,
description: str = "",
attendees: Optional[list[str]] = None,
calendar: Optional[str] = "primary",
) -> str:
"""Создать встречу в календаре.
Args:
summary: Название встречи или события
start_iso: Время начала в формате ISO 8601 (например: '2026-11-08T10:00:00+03:00')
end_iso: Время окончания в формате ISO 8601 (например: '2026-11-08T11:00:00+03:00')
description: Описание или повестка встречи
attendees: Список email участников
calendar: Название или ID календаря, в который добавить событие (по умолчанию 'primary' — основной)
"""
client = get_calendar_client()
if not client.is_configured():
return "Google Календарь не настроен в .env"
try:
start_dt = _parse_iso_datetime(start_iso)
end_dt = _parse_iso_datetime(end_iso)
event = await client.create_event(
summary=summary,
start_time=start_dt,
end_time=end_dt,
description=description,
attendees=attendees,
calendar_id=calendar,
)
event_id = event.get("id", "")
link = event.get("htmlLink", "")
return f"Событие '{summary}' успешно создано в календаре! ID: {event_id}. Ссылка: {link}"
except Exception as e:
return f"Ошибка создания события: {type(e).__name__}: {str(e)}"
@tool(
name="calendar_delete_event",
description="Удалить событие из Google Календаря по его ID.",
)
async def calendar_delete_event(event_id: str, calendar: Optional[str] = None) -> str:
"""Удалить событие из календаря.
Args:
event_id: ID события (полученный из calendar_list_events)
calendar: Название или ID календаря (если известно)
"""
client = get_calendar_client()
if not client.is_configured():
return "Google Календарь не настроен в .env"
try:
await client.delete_event(event_id=event_id.strip(), calendar_id=calendar)
return f"Событие с ID '{event_id}' успешно удалено."
except Exception as e:
return f"Ошибка удаления события '{event_id}': {type(e).__name__}: {str(e)}"