|
| 1 | +"""Gmail connector returning structured message payloads.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import json |
| 7 | +import logging |
| 8 | +from datetime import UTC, datetime |
| 9 | +from pathlib import Path |
| 10 | +from typing import Any |
| 11 | + |
| 12 | +import httpx |
| 13 | + |
| 14 | +from agent_pm.connectors.base import Connector |
| 15 | +from agent_pm.settings import settings |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +class EmailConnector(Connector): |
| 21 | + def __init__(self) -> None: |
| 22 | + super().__init__(name="gmail") |
| 23 | + self._delegated_user = settings.gmail_delegated_user |
| 24 | + self._labels = settings.gmail_label_filter |
| 25 | + self._scopes = settings.gmail_scopes |
| 26 | + |
| 27 | + @property |
| 28 | + def enabled(self) -> bool: |
| 29 | + json_creds = settings.gmail_service_account_json |
| 30 | + file_creds = settings.gmail_service_account_file |
| 31 | + return bool(json_creds or (file_creds and Path(file_creds).exists())) |
| 32 | + |
| 33 | + def _build_query(self, since: datetime | None) -> str: |
| 34 | + clauses: list[str] = [] |
| 35 | + if since: |
| 36 | + clauses.append(f"after:{since.strftime('%Y/%m/%d')}") |
| 37 | + if self._labels: |
| 38 | + clauses.append(" OR ".join(f"label:{label}" for label in self._labels)) |
| 39 | + return " ".join(filter(None, clauses)) |
| 40 | + |
| 41 | + async def sync(self, *, since: datetime | None = None) -> list[dict[str, Any]]: |
| 42 | + query = self._build_query(since) |
| 43 | + if settings.dry_run or not self.enabled: |
| 44 | + return [ |
| 45 | + { |
| 46 | + "dry_run": True, |
| 47 | + "query": query, |
| 48 | + "labels": self._labels, |
| 49 | + "delegated_user": self._delegated_user, |
| 50 | + } |
| 51 | + ] |
| 52 | + |
| 53 | + token = await self._get_token() |
| 54 | + headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} |
| 55 | + params = {"q": query} if query else {} |
| 56 | + async with httpx.AsyncClient() as client: |
| 57 | + response = await client.get( |
| 58 | + "https://gmail.googleapis.com/gmail/v1/users/me/messages", |
| 59 | + headers=headers, |
| 60 | + params=params, |
| 61 | + timeout=30, |
| 62 | + ) |
| 63 | + response.raise_for_status() |
| 64 | + message_list = response.json() |
| 65 | + |
| 66 | + ids = [item.get("id") for item in message_list.get("messages", []) if item.get("id")] |
| 67 | + if not ids: |
| 68 | + return [message_list] |
| 69 | + |
| 70 | + messages: list[dict[str, Any]] = [] |
| 71 | + async with httpx.AsyncClient() as client: |
| 72 | + for message_id in ids: |
| 73 | + detail = await client.get( |
| 74 | + f"https://gmail.googleapis.com/gmail/v1/users/me/messages/{message_id}", |
| 75 | + headers=headers, |
| 76 | + timeout=30, |
| 77 | + ) |
| 78 | + detail.raise_for_status() |
| 79 | + data = detail.json() |
| 80 | + payload = data.get("payload", {}) |
| 81 | + headers_list = payload.get("headers", []) |
| 82 | + header_map = {item.get("name"): item.get("value") for item in headers_list} |
| 83 | + messages.append( |
| 84 | + { |
| 85 | + "id": message_id, |
| 86 | + "thread_id": data.get("threadId"), |
| 87 | + "snippet": data.get("snippet"), |
| 88 | + "subject": header_map.get("Subject"), |
| 89 | + "from": header_map.get("From"), |
| 90 | + "to": header_map.get("To"), |
| 91 | + "date": header_map.get("Date"), |
| 92 | + "labels": data.get("labelIds", []), |
| 93 | + } |
| 94 | + ) |
| 95 | + return [message_list, {"messages": messages}] |
| 96 | + |
| 97 | + async def _get_token(self) -> str: |
| 98 | + creds = await asyncio.to_thread(self._load_credentials) |
| 99 | + if not creds: |
| 100 | + raise RuntimeError("Gmail credentials missing") |
| 101 | + if not creds.valid or creds.expired: |
| 102 | + await asyncio.to_thread(creds.refresh, self._request()) |
| 103 | + if not creds.token: |
| 104 | + raise RuntimeError("Failed to refresh Gmail access token") |
| 105 | + return creds.token |
| 106 | + |
| 107 | + def _load_credentials(self): |
| 108 | + info: dict[str, Any] | None = None |
| 109 | + if settings.gmail_service_account_json: |
| 110 | + try: |
| 111 | + info = json.loads(settings.gmail_service_account_json) |
| 112 | + except json.JSONDecodeError as exc: # pragma: no cover - defensive |
| 113 | + logger.error("Invalid GMAIL_SERVICE_ACCOUNT_JSON: %s", exc) |
| 114 | + elif settings.gmail_service_account_file: |
| 115 | + try: |
| 116 | + info = json.loads(Path(settings.gmail_service_account_file).read_text(encoding="utf-8")) |
| 117 | + except FileNotFoundError: |
| 118 | + logger.error("GMAIL_SERVICE_ACCOUNT_FILE not found: %s", settings.gmail_service_account_file) |
| 119 | + except json.JSONDecodeError as exc: # pragma: no cover - defensive |
| 120 | + logger.error("Invalid GMAIL_SERVICE_ACCOUNT_FILE: %s", exc) |
| 121 | + if not info: |
| 122 | + return None |
| 123 | + |
| 124 | + try: |
| 125 | + from google.oauth2 import service_account |
| 126 | + except ImportError as exc: # pragma: no cover - optional dependency |
| 127 | + raise RuntimeError("google-auth not installed") from exc |
| 128 | + |
| 129 | + credentials = service_account.Credentials.from_service_account_info(info, scopes=self._scopes) |
| 130 | + if self._delegated_user: |
| 131 | + credentials = credentials.with_subject(self._delegated_user) |
| 132 | + return credentials |
| 133 | + |
| 134 | + @staticmethod |
| 135 | + def _request(): |
| 136 | + try: |
| 137 | + from google.auth.transport.requests import Request |
| 138 | + except ImportError as exc: # pragma: no cover - optional dependency |
| 139 | + raise RuntimeError("google-auth not installed") from exc |
| 140 | + return Request() |
0 commit comments