axt-google-api 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ from .gmail import GmailClient
2
+
3
+ __all__ = [
4
+ "GmailClient",
5
+ ]
axt_google_api/base.py ADDED
@@ -0,0 +1,84 @@
1
+ from google.oauth2.credentials import Credentials
2
+ from google_auth_oauthlib.flow import InstalledAppFlow
3
+ from googleapiclient.discovery import build
4
+ from pydantic import SecretStr
5
+
6
+ from axt_google_api.settings import GoogleBaseSettings
7
+
8
+
9
+ class GoogleClient:
10
+ """Base client handling auth for interacting with Google APIs."""
11
+
12
+ def __init__(
13
+ self,
14
+ service_name: str,
15
+ client_id: str,
16
+ client_secret: SecretStr,
17
+ refresh_token: SecretStr,
18
+ ):
19
+ """Initialize the GoogleClient."""
20
+ self._service_name = service_name
21
+ self._client_id = client_id
22
+ self._client_secret = client_secret
23
+ self._refresh_token = refresh_token
24
+ self._settings = GoogleBaseSettings()
25
+
26
+ @staticmethod
27
+ def _acquire_refresh_token(
28
+ client_id: str, client_secret: SecretStr, scopes: list[str]
29
+ ) -> SecretStr:
30
+ """Acquire a refresh token using the OAuth 2.0 flow.
31
+
32
+ Args:
33
+ client_id: The client ID.
34
+ client_secret: The client secret.
35
+ scopes: A list of scopes for which to request access.
36
+ Returns:
37
+ A SecretStr containing the refresh token.
38
+ """
39
+
40
+ settings = GoogleBaseSettings()
41
+
42
+ flow = InstalledAppFlow.from_client_config(
43
+ client_config={
44
+ "installed": {
45
+ "client_id": client_id,
46
+ "client_secret": client_secret.get_secret_value(),
47
+ "auth_uri": settings.auth_uri,
48
+ "token_uri": settings.token_uri,
49
+ "redirect_uris": ["http://localhost"],
50
+ }
51
+ },
52
+ scopes=scopes,
53
+ )
54
+
55
+ credentials = flow.run_local_server(
56
+ host="localhost",
57
+ port=0,
58
+ access_type="offline",
59
+ prompt="consent",
60
+ success_message="Sign in successful! You may close this window.",
61
+ )
62
+
63
+ if not credentials.refresh_token:
64
+ raise ValueError("No refresh token was obtained.")
65
+
66
+ return SecretStr(credentials.refresh_token)
67
+
68
+ def _build_client(self):
69
+ """Build the Google API client.
70
+
71
+ Returns:
72
+ A Google API client instance for the specified service.
73
+ """
74
+ return build(
75
+ self._service_name,
76
+ "v1",
77
+ credentials=Credentials(
78
+ token=None,
79
+ refresh_token=self._refresh_token.get_secret_value(),
80
+ client_id=self._client_id,
81
+ client_secret=self._client_secret.get_secret_value(),
82
+ token_uri=self._settings.token_uri,
83
+ ),
84
+ )
@@ -0,0 +1,144 @@
1
+ import base64
2
+
3
+ from googleapiclient.errors import HttpError
4
+ from pydantic import SecretStr
5
+
6
+ from axt_google_api.base import GoogleClient
7
+
8
+
9
+ class GmailClient(GoogleClient):
10
+ """Client for interacting with the Gmail API."""
11
+
12
+ def __init__(
13
+ self,
14
+ client_id: str,
15
+ client_secret: SecretStr,
16
+ refresh_token: SecretStr,
17
+ ) -> None:
18
+ """Initialize the GmailClient."""
19
+ super().__init__(
20
+ service_name="gmail",
21
+ client_id=client_id,
22
+ client_secret=client_secret,
23
+ refresh_token=refresh_token,
24
+ )
25
+
26
+ def _get_email_body(self, message: dict) -> str:
27
+ """Extract the email body from the message payload.
28
+
29
+ Args:
30
+ message: The email message dictionary.
31
+ Returns:
32
+ The email body as a string.
33
+ """
34
+
35
+ mime = message.get("mimeType", "")
36
+ data = message.get("body", {}).get("data")
37
+
38
+ if mime in ["text/plain", "text/html"] and data:
39
+ decoded = base64.urlsafe_b64decode(data + "=" * (-len(data) % 4))
40
+ return decoded.decode("utf-8", errors="replace")
41
+
42
+ for part in message.get("parts", []):
43
+ result = self._get_email_body(part)
44
+ if result:
45
+ return result
46
+
47
+ return ""
48
+
49
+ def fetch_email(self, message_id: str, client=None) -> dict:
50
+ """Fetch an email by its message ID.
51
+
52
+ Args:
53
+ message_id: The ID of the email message to fetch.
54
+ client: Optional Google API client instance. If not provided, a new client will be built.
55
+ Returns:
56
+ A dictionary containing `id`, `sender`, `subject`, and `body`.
57
+ """
58
+
59
+ if not client:
60
+ client = self._build_client()
61
+
62
+ with client as service:
63
+ try:
64
+ message = (
65
+ service.users().messages().get(userId="me", id=message_id).execute()
66
+ )
67
+
68
+ headers = {
69
+ h["name"].lower(): h["value"]
70
+ for h in message["payload"].get("headers", [])
71
+ }
72
+
73
+ return {
74
+ "id": message["id"],
75
+ "sender": headers.get("from"),
76
+ "subject": headers.get("subject"),
77
+ "body": self._get_email_body(message["payload"]),
78
+ }
79
+ except HttpError as e:
80
+ if e.resp.status == 404:
81
+ raise ValueError(f"Message ID {message_id} not found.") from e
82
+ raise
83
+
84
+ def fetch_received_email_history(
85
+ self,
86
+ history_id: int,
87
+ max_results: int = 100,
88
+ senders_filter: list[str] | None = None,
89
+ exclude_message_ids: list[str] | None = None,
90
+ ) -> list[dict]:
91
+ """Fetch history of received emails from Gmail API.
92
+
93
+ Args:
94
+ history_id: The history ID to fetch email history from.
95
+ max_results: The maximum number of results to return.
96
+ senders_filter: Optional list of sender email addresses to filter the results.
97
+ exclude_message_ids: Optional list of message IDs to exclude from the results.
98
+ Returns:
99
+ A list of dictionaries containing the email information.
100
+ """
101
+
102
+ added_messages = []
103
+
104
+ with self._build_client() as service:
105
+ request = (
106
+ service.users()
107
+ .history()
108
+ .list(
109
+ userId="me",
110
+ startHistoryId=history_id,
111
+ maxResults=max_results,
112
+ historyTypes=["messageAdded"],
113
+ )
114
+ )
115
+ while request is not None:
116
+ try:
117
+ response = request.execute()
118
+ except HttpError as e:
119
+ if e.resp.status == 404:
120
+ raise ValueError(
121
+ f"History ID {history_id} not found. It may be too old or invalid."
122
+ ) from e
123
+ raise
124
+ added_messages.extend(
125
+ message
126
+ for h in response.get("history", [])
127
+ for message in h.get("messagesAdded", [])
128
+ if not exclude_message_ids
129
+ or message["message"]["id"] not in exclude_message_ids
130
+ )
131
+
132
+ request = service.users().history().list_next(request, response)
133
+
134
+ emails = []
135
+
136
+ for message in added_messages:
137
+ message = self.fetch_email(message["message"]["id"])
138
+ if senders_filter is None or any(
139
+ message["sender"] is not None and s in message["sender"]
140
+ for s in senders_filter
141
+ ):
142
+ emails.append(message)
143
+
144
+ return emails
@@ -0,0 +1,9 @@
1
+ from pydantic_settings import BaseSettings, SettingsConfigDict
2
+
3
+
4
+ class GoogleBaseSettings(BaseSettings):
5
+ """Google API settings"""
6
+
7
+ model_config = SettingsConfigDict(env_prefix="GOOGLE_")
8
+ auth_uri: str = "https://accounts.google.com/o/oauth2/auth"
9
+ token_uri: str = "https://oauth2.googleapis.com/token" # noqa: S105
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.3
2
+ Name: axt-google-api
3
+ Version: 1.0.0
4
+ Summary: Python client library for the Google API
5
+ Requires-Dist: google-api-python-client>=2.202.0
6
+ Requires-Dist: google-auth-oauthlib>=1.5.0
7
+ Requires-Dist: pydantic>=2.13.1
8
+ Requires-Dist: pydantic-settings>=2.13.1
9
+ Requires-Python: >=3.13
10
+ Description-Content-Type: text/markdown
11
+
12
+ # axt-google-api
13
+
14
+ Python client library for the Google API.
15
+
16
+ ## Publishing
17
+
18
+ Commits pushed to `main` are checked by
19
+ [`.github/workflows/publish.yml`](.github/workflows/publish.yml). Conventional
20
+ Commit messages determine whether a release is needed and the version bump:
21
+
22
+ - `fix: ...` bumps the patch version.
23
+ - `feat: ...` bumps the minor version.
24
+ - Include `BREAKING CHANGE: ...` in the commit body, or use `type!: ...`, to
25
+ bump the major version.
26
+ - Other commit types do not trigger a release unless they include a breaking
27
+ change.
28
+
29
+ To enable publishing without a PyPI API token, configure a trusted publisher in
30
+ the PyPI project's **Publishing** settings:
31
+
32
+ - Owner and repository: this GitHub repository
33
+ - Workflow name: `publish.yml`
34
+ - Environment: leave blank (the workflow does not use a GitHub environment)
@@ -0,0 +1,7 @@
1
+ axt_google_api/__init__.py,sha256=Ik5KGzlsL6wRYbFWL2Y26igvDKPTxwub0zXy__4j4EY,65
2
+ axt_google_api/base.py,sha256=tva_5jKQuSikNagdFCzJ8LrcaFtyErM_BwnKG6-fzv0,2664
3
+ axt_google_api/gmail.py,sha256=yWCy2ImkkS06OF5KyEQp0qv9OnseUTPExOmsM-xZKOo,4823
4
+ axt_google_api/settings.py,sha256=r0R-K-736sy_wCdHpvbw_48YPr9N8LNCn6yC_hN6Bqk,333
5
+ axt_google_api-1.0.0.dist-info/WHEEL,sha256=eh7sammvW2TypMMMGKgsM83HyA_3qQ5Lgg3ynoecH3M,79
6
+ axt_google_api-1.0.0.dist-info/METADATA,sha256=p3e_CrazD5CgAdd2jSwdBlkw5BvxEIkYEuNOWCmeKmQ,1157
7
+ axt_google_api-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.8.24
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any