meeng-sdk 0.1.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.
meeng/__init__.py ADDED
@@ -0,0 +1,88 @@
1
+ # Code generated by sdk/generator. DO NOT EDIT.
2
+ """meeng's SDK for Python, generated from meeng's API contract."""
3
+
4
+ from . import models
5
+ from ._client import Meeng, Transport, urllib_transport
6
+ from ._core import RequestOptions
7
+ from ._errors import ErrorResponse, MeengHTTPError, WebhookVerificationError
8
+ from ._services import EmailsService, DomainsService, ContactsService, ContactBooksService, CampaignsService, AnalyticsService
9
+ from ._version import API_PREFIX, API_VERSION, DEFAULT_BASE_URL, VERSION
10
+ from .webhooks import (
11
+ DEFAULT_TOLERANCE_MS,
12
+ WEBHOOK_CALL_HEADER,
13
+ WEBHOOK_EVENT_HEADER,
14
+ WEBHOOK_SIGNATURE_HEADER,
15
+ WEBHOOK_TIMESTAMP_HEADER,
16
+ ContactWebhookEvent,
17
+ ContactWebhookEventType,
18
+ DomainWebhookEvent,
19
+ DomainWebhookEventType,
20
+ EmailWebhookEvent,
21
+ EmailWebhookEventType,
22
+ EmailBouncedWebhookEvent,
23
+ EmailBouncedWebhookEventType,
24
+ EmailClickedWebhookEvent,
25
+ EmailClickedWebhookEventType,
26
+ EmailFailedWebhookEvent,
27
+ EmailFailedWebhookEventType,
28
+ EmailOpenedWebhookEvent,
29
+ EmailOpenedWebhookEventType,
30
+ EmailSuppressedWebhookEvent,
31
+ EmailSuppressedWebhookEventType,
32
+ TestWebhookEvent,
33
+ TestWebhookEventType,
34
+ WebhookEvent,
35
+ WebhookEventType,
36
+ Webhooks,
37
+ )
38
+
39
+ types = models
40
+ """The typed dicts of the requests: ``meeng.types.EmailsSendParams``."""
41
+
42
+ __all__ = [
43
+ "API_PREFIX",
44
+ "API_VERSION",
45
+ "DEFAULT_BASE_URL",
46
+ "DEFAULT_TOLERANCE_MS",
47
+ "VERSION",
48
+ "WEBHOOK_CALL_HEADER",
49
+ "WEBHOOK_EVENT_HEADER",
50
+ "WEBHOOK_SIGNATURE_HEADER",
51
+ "WEBHOOK_TIMESTAMP_HEADER",
52
+ "ErrorResponse",
53
+ "Meeng",
54
+ "MeengHTTPError",
55
+ "RequestOptions",
56
+ "Transport",
57
+ "WebhookEvent",
58
+ "WebhookEventType",
59
+ "WebhookVerificationError",
60
+ "Webhooks",
61
+ "models",
62
+ "types",
63
+ "urllib_transport",
64
+ "ContactWebhookEvent",
65
+ "ContactWebhookEventType",
66
+ "DomainWebhookEvent",
67
+ "DomainWebhookEventType",
68
+ "EmailWebhookEvent",
69
+ "EmailWebhookEventType",
70
+ "EmailBouncedWebhookEvent",
71
+ "EmailBouncedWebhookEventType",
72
+ "EmailClickedWebhookEvent",
73
+ "EmailClickedWebhookEventType",
74
+ "EmailFailedWebhookEvent",
75
+ "EmailFailedWebhookEventType",
76
+ "EmailOpenedWebhookEvent",
77
+ "EmailOpenedWebhookEventType",
78
+ "EmailSuppressedWebhookEvent",
79
+ "EmailSuppressedWebhookEventType",
80
+ "TestWebhookEvent",
81
+ "TestWebhookEventType",
82
+ "EmailsService",
83
+ "DomainsService",
84
+ "ContactsService",
85
+ "ContactBooksService",
86
+ "CampaignsService",
87
+ "AnalyticsService",
88
+ ]
meeng/_client.py ADDED
@@ -0,0 +1,225 @@
1
+ # Code generated by sdk/generator. DO NOT EDIT.
2
+
3
+ from __future__ import annotations
4
+
5
+ import ipaddress
6
+ import json
7
+ import os
8
+ import random
9
+ import time
10
+ import urllib.error
11
+ import urllib.request
12
+ from collections.abc import Callable
13
+ from typing import Any
14
+ from urllib.parse import urlencode, urlsplit
15
+
16
+ from ._errors import ErrorResponse, MeengHTTPError, error_of
17
+ from ._services import EmailsService, DomainsService, ContactsService, ContactBooksService, CampaignsService, AnalyticsService
18
+ from ._version import API_PREFIX, DEFAULT_BASE_URL, VERSION
19
+ from .webhooks import Webhooks
20
+
21
+ Transport = Callable[[str, str, dict[str, str], "bytes | None", float], "tuple[int, dict[str, str], bytes]"]
22
+ """Sends one request: (method, url, headers, body, timeout) -> (status, headers in lower case, body)."""
23
+
24
+ MAX_RETRY_DELAY = 30.0
25
+ """The longest, in seconds, a call waits before a repetition."""
26
+
27
+ _TRANSIENT = frozenset({500, 502, 503, 504})
28
+
29
+ _INSECURE = "meeng: the base URL must be https (http is accepted only for localhost, 127.0.0.0/8 and ::1), so the API key is never sent in clear text"
30
+
31
+
32
+ class _RefuseRedirects(urllib.request.HTTPRedirectHandler):
33
+ """The API never redirects, and a redirect would carry the key to wherever it points."""
34
+
35
+ def redirect_request(self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str) -> Any:
36
+ raise urllib.error.HTTPError(req.full_url, code, msg, headers, fp)
37
+
38
+
39
+ _OPENER = urllib.request.build_opener(_RefuseRedirects)
40
+
41
+
42
+ def urllib_transport(method: str, url: str, headers: dict[str, str], body: bytes | None, timeout: float) -> tuple[int, dict[str, str], bytes]:
43
+ """The standard library's HTTP, so the SDK depends on nothing. It refuses redirects."""
44
+ request = urllib.request.Request(url, data=body, headers=headers, method=method)
45
+ try:
46
+ with _OPENER.open(request, timeout=timeout) as response:
47
+ return response.status, {key.lower(): value for key, value in response.headers.items()}, response.read()
48
+ except urllib.error.HTTPError as error:
49
+ try:
50
+ try:
51
+ raw = error.read()
52
+ except OSError:
53
+ # A refusal whose body never arrived is still a refusal.
54
+ raw = b""
55
+ return error.code, {key.lower(): value for key, value in error.headers.items()}, raw
56
+ finally:
57
+ error.close()
58
+
59
+
60
+ def _check_base_url(base_url: str) -> None:
61
+ """Raises ValueError unless base_url is https, or http to localhost, 127.0.0.0/8 or ::1."""
62
+ try:
63
+ parts = urlsplit(base_url)
64
+ host = (parts.hostname or "").lower()
65
+ except ValueError:
66
+ raise ValueError(_INSECURE) from None
67
+ try:
68
+ loopback = host == "localhost" or ipaddress.ip_address(host).is_loopback
69
+ except ValueError:
70
+ loopback = False
71
+ if parts.scheme.lower() != "https" and not (parts.scheme.lower() == "http" and loopback):
72
+ raise ValueError(_INSECURE)
73
+
74
+
75
+ class Meeng:
76
+ """meeng's API with one team's API key.
77
+
78
+ Every call answers ``(data, error)``. By default a
79
+ refusal raises ``MeengHTTPError`` and ``error`` is always ``None``; build the
80
+ client with ``raise_on_error=False`` to get ``(None, error)`` instead.
81
+
82
+ meeng = Meeng("mg_123")
83
+ data, _ = meeng.emails.send({
84
+ "from": "hello@acme.com",
85
+ "to": "customer@example.com",
86
+ "subject": "Hello",
87
+ "html": "<p>Hello</p>",
88
+ })
89
+
90
+ Without a key it is read from MEENG_API_KEY, and the address of the app from
91
+ MEENG_BASE_URL.
92
+
93
+ A call that may be repeated is repeated up to ``max_retries`` times (2 by
94
+ default; 0 sends every call once) after the first attempt. It is repeated
95
+ when the API answers 429, which means it was not processed, so any call may
96
+ be; and when the API answers 500, 502, 503 or 504, or the connection fails,
97
+ only if repeating it cannot do the work twice: a read, a PUT, a DELETE, or any
98
+ call that carries an idempotency key. Any other refusal, a 409 included, is
99
+ never repeated. The first repetition waits ``retry_delay`` seconds, each next
100
+ one twice as long, and a ``Retry-After`` from the API replaces the wait.
101
+ """
102
+
103
+ def __init__(
104
+ self,
105
+ key: str | None = None,
106
+ url: str | None = None,
107
+ *,
108
+ raise_on_error: bool = True,
109
+ timeout: float = 30.0,
110
+ max_retries: int = 2,
111
+ retry_delay: float = 0.5,
112
+ transport: Transport | None = None,
113
+ ) -> None:
114
+ resolved = key or os.environ.get("MEENG_API_KEY")
115
+ if not resolved:
116
+ raise ValueError("Missing API key. Pass it to Meeng('mg_123') or set MEENG_API_KEY")
117
+ self.key: str = resolved
118
+ base = (url or os.environ.get("MEENG_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
119
+ _check_base_url(base)
120
+ self.url: str = base + API_PREFIX
121
+ self.raise_on_error = raise_on_error
122
+ self._timeout = timeout
123
+ self._max_retries = max(0, max_retries)
124
+ self._retry_delay = max(0.0, retry_delay)
125
+ self._transport = transport or urllib_transport
126
+ self.emails = EmailsService(self)
127
+ self.domains = DomainsService(self)
128
+ self.contacts = ContactsService(self)
129
+ self.contact_books = ContactBooksService(self)
130
+ self.contactBooks = self.contact_books
131
+ self.campaigns = CampaignsService(self)
132
+ self.analytics = AnalyticsService(self)
133
+
134
+ def webhooks(self, secret: str) -> Webhooks:
135
+ """Checks and reads the webhooks a team's endpoint receives.
136
+
137
+ event = meeng.webhooks("whsec_xxx").construct_event(body, headers=request.headers)
138
+ """
139
+ return Webhooks(secret)
140
+
141
+ def request(
142
+ self,
143
+ method: str,
144
+ path: str,
145
+ *,
146
+ query: dict[str, Any] | None = None,
147
+ body: Any = None,
148
+ idempotency_key: str | None = None,
149
+ ) -> tuple[Any, ErrorResponse | None]:
150
+ """Calls the API and answers ``(data, error)``; a refusal raises MeengHTTPError when ``raise_on_error`` is true."""
151
+ pairs: list[tuple[str, str]] = []
152
+ for name, value in (query or {}).items():
153
+ if value is None or value == "":
154
+ continue
155
+ if isinstance(value, (list, tuple)):
156
+ pairs.extend((name, str(each)) for each in value)
157
+ else:
158
+ pairs.append((name, str(value)))
159
+ url = self.url + path + ("?" + urlencode(pairs) if pairs else "")
160
+ headers = {
161
+ "Authorization": f"Bearer {self.key}",
162
+ "Accept": "application/json",
163
+ "User-Agent": f"meeng-python/{VERSION}",
164
+ }
165
+ data = None
166
+ if body is not None:
167
+ data = json.dumps(body).encode()
168
+ headers["Content-Type"] = "application/json"
169
+ if idempotency_key:
170
+ headers["Idempotency-Key"] = idempotency_key
171
+ may_repeat = method.upper() in ("GET", "HEAD", "PUT", "DELETE") or bool(idempotency_key)
172
+ attempt = 0
173
+ while True:
174
+ try:
175
+ status, answer_headers, raw = self._transport(method, url, headers, data, self._timeout)
176
+ except OSError:
177
+ # The connection failed or timed out: the call may or may not have arrived.
178
+ if not may_repeat or attempt >= self._max_retries:
179
+ raise
180
+ self._wait(attempt, None)
181
+ attempt += 1
182
+ continue
183
+ if status == 429 or (may_repeat and status in _TRANSIENT):
184
+ if attempt < self._max_retries:
185
+ self._wait(attempt, answer_headers.get("retry-after"))
186
+ attempt += 1
187
+ continue
188
+ break
189
+ if status >= 300:
190
+ error = error_of(status, _REASONS.get(status, "Error"), raw)
191
+ if self.raise_on_error:
192
+ raise MeengHTTPError(status, error, method, path)
193
+ return None, error
194
+ try:
195
+ return json.loads(raw), None
196
+ except ValueError:
197
+ error = {"code": "INTERNAL_SERVER_ERROR", "message": _REASONS.get(status, "Error")}
198
+ if self.raise_on_error:
199
+ raise MeengHTTPError(status, error, method, path) from None
200
+ return None, error
201
+
202
+ def _wait(self, attempt: int, retry_after: str | None) -> None:
203
+ """Sleeps before repetition number attempt + 1: the API's Retry-After, or the base delay doubled each time and spread over its upper half."""
204
+ try:
205
+ seconds = float(retry_after) if retry_after is not None else 0.0
206
+ except ValueError:
207
+ seconds = 0.0
208
+ if seconds <= 0:
209
+ delay = min(self._retry_delay * 2 ** min(attempt, 10), MAX_RETRY_DELAY)
210
+ seconds = delay / 2 + random.random() * delay / 2
211
+ time.sleep(min(seconds, MAX_RETRY_DELAY))
212
+
213
+
214
+ _REASONS = {
215
+ 400: "Bad Request",
216
+ 401: "Unauthorized",
217
+ 403: "Forbidden",
218
+ 404: "Not Found",
219
+ 409: "Conflict",
220
+ 422: "Unprocessable Entity",
221
+ 429: "Too Many Requests",
222
+ 500: "Internal Server Error",
223
+ 502: "Bad Gateway",
224
+ 503: "Service Unavailable",
225
+ }
meeng/_core.py ADDED
@@ -0,0 +1,32 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, NotRequired, Protocol, TypedDict
4
+ from urllib.parse import quote
5
+
6
+ from ._errors import ErrorResponse
7
+
8
+
9
+ class Requester(Protocol):
10
+ """What a service calls the API through."""
11
+
12
+ def request(
13
+ self,
14
+ method: str,
15
+ path: str,
16
+ *,
17
+ query: dict[str, Any] | None = None,
18
+ body: Any = None,
19
+ idempotency_key: str | None = None,
20
+ ) -> tuple[Any, ErrorResponse | None]: ...
21
+
22
+
23
+ def segment(value: object) -> str:
24
+ """A path parameter, escaped."""
25
+ return quote(str(value), safe="")
26
+
27
+
28
+ class RequestOptions(TypedDict):
29
+ """Options of a call that takes an idempotency key."""
30
+
31
+ idempotency_key: NotRequired[str | None]
32
+ """Makes a send safe to retry: the same key with the same body answers the first result again; with another body, a 409 NOT_UNIQUE. Up to 256 characters, kept for 24 hours."""
meeng/_errors.py ADDED
@@ -0,0 +1,78 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Literal, TypedDict
4
+
5
+
6
+ class ErrorResponse(TypedDict):
7
+ """What an error answer says."""
8
+
9
+ code: str
10
+ message: str
11
+
12
+
13
+ class MeengHTTPError(Exception):
14
+ """Raised when the API refuses a request and ``raise_on_error`` is true (the default)."""
15
+
16
+ def __init__(self, status_code: int, error: ErrorResponse, method: str, path: str) -> None:
17
+ self.status_code = status_code
18
+ self.error = error
19
+ self.method = method
20
+ self.path = path
21
+ super().__init__(f"{method} {path} -> {status_code} {error['code']}: {error['message']}")
22
+
23
+
24
+ def error_of(status: int, reason: str, raw: bytes) -> ErrorResponse:
25
+ """The error a refused answer carries: ``{"error": {"code", "message"}}``, ``{"error": "text"}`` or the error itself."""
26
+ import json
27
+
28
+ error: ErrorResponse = {"code": "INTERNAL_SERVER_ERROR", "message": reason}
29
+ try:
30
+ body: Any = json.loads(raw)
31
+ except ValueError:
32
+ return error
33
+ if not isinstance(body, dict):
34
+ return error
35
+ found: Any = body.get("error", body)
36
+ if isinstance(found, str):
37
+ found = {"message": found}
38
+ if isinstance(found, dict):
39
+ code, message = found.get("code"), found.get("message")
40
+ if not (isinstance(code, str) and code):
41
+ # A refused validation answers {"success": false, "error": {"issues", "name"}}, with no code of its own.
42
+ code = found.get("name")
43
+ if isinstance(code, str) and code:
44
+ error["code"] = code
45
+ if not (isinstance(message, str) and message):
46
+ issues = found.get("issues")
47
+ first = issues[0] if isinstance(issues, list) and issues else None
48
+ if isinstance(first, dict) and isinstance(first.get("message"), str):
49
+ path = first.get("path")
50
+ where = ".".join(str(part) for part in path) + ": " if isinstance(path, list) and path else ""
51
+ message = where + first["message"]
52
+ if isinstance(message, str) and message:
53
+ error["message"] = message
54
+ return error
55
+
56
+
57
+ WebhookVerificationErrorCode = Literal[
58
+ "MISSING_SIGNATURE",
59
+ "MISSING_TIMESTAMP",
60
+ "INVALID_SIGNATURE_FORMAT",
61
+ "INVALID_TIMESTAMP",
62
+ "TIMESTAMP_OUT_OF_RANGE",
63
+ "SIGNATURE_MISMATCH",
64
+ "INVALID_BODY",
65
+ "INVALID_JSON",
66
+ ]
67
+
68
+
69
+ class WebhookVerificationError(Exception):
70
+ """A request meeng did not sign, signed too long ago, or that is not an event."""
71
+
72
+ def __init__(self, code: WebhookVerificationErrorCode, message: str) -> None:
73
+ super().__init__(message)
74
+ self.code = code
75
+ self.message = message
76
+
77
+ def __str__(self) -> str:
78
+ return f"{self.code}: {self.message}"
meeng/_services.py ADDED
@@ -0,0 +1,246 @@
1
+ # Code generated by sdk/generator. DO NOT EDIT.
2
+
3
+ from __future__ import annotations
4
+
5
+ import builtins
6
+
7
+ from . import models
8
+ from ._core import Requester, RequestOptions, segment
9
+ from ._errors import ErrorResponse
10
+
11
+
12
+ class EmailsService:
13
+ """The API's emails."""
14
+
15
+ def __init__(self, client: Requester) -> None:
16
+ self._client = client
17
+
18
+ def send(self, payload: models.EmailsSendParams, *, options: RequestOptions | None = None) -> tuple[models.EmailsSendResponse | None, ErrorResponse | None]:
19
+ """Sends an email, now or at scheduledAt."""
20
+ data, error = self._client.request("POST", "/v1/emails", body=payload, idempotency_key=(options or {}).get("idempotency_key"))
21
+ return data, error
22
+
23
+ create = send
24
+
25
+ def batch(self, payload: builtins.list[models.EmailsBatchParams], *, options: RequestOptions | None = None) -> tuple[models.EmailsBatchResponse | None, ErrorResponse | None]:
26
+ """Sends up to 100 emails in one request."""
27
+ data, error = self._client.request("POST", "/v1/emails/batch", body=payload, idempotency_key=(options or {}).get("idempotency_key"))
28
+ return data, error
29
+
30
+ def get(self, email_id: str | int) -> tuple[models.Email | None, ErrorResponse | None]:
31
+ """Reads one email with its events."""
32
+ data, error = self._client.request("GET", f"/v1/emails/{segment(email_id)}")
33
+ return data, error
34
+
35
+ def list(self, *, page: int | None = None, limit: int | None = None, start_date: str | None = None, end_date: str | None = None, domain_id: str | builtins.list[str] | None = None) -> tuple[models.EmailsListResponse | None, ErrorResponse | None]:
36
+ """Lists emails, newest first, with an optional date range and domain filter."""
37
+ query = {
38
+ "page": page,
39
+ "limit": limit,
40
+ "startDate": start_date,
41
+ "endDate": end_date,
42
+ "domainId": domain_id,
43
+ }
44
+ data, error = self._client.request("GET", "/v1/emails", query=query)
45
+ return data, error
46
+
47
+ def update(self, email_id: str | int, payload: models.EmailsUpdateParams) -> tuple[models.EmailsUpdateResponse | None, ErrorResponse | None]:
48
+ """Reschedules an email that has not been sent."""
49
+ data, error = self._client.request("PATCH", f"/v1/emails/{segment(email_id)}", body=payload)
50
+ return data, error
51
+
52
+ def cancel(self, email_id: str | int) -> tuple[models.EmailsCancelResponse | None, ErrorResponse | None]:
53
+ """Cancels a scheduled email."""
54
+ data, error = self._client.request("POST", f"/v1/emails/{segment(email_id)}/cancel", body={})
55
+ return data, error
56
+
57
+
58
+ class DomainsService:
59
+ """The API's domains."""
60
+
61
+ def __init__(self, client: Requester) -> None:
62
+ self._client = client
63
+
64
+ def list(self) -> tuple[builtins.list[models.Domain] | None, ErrorResponse | None]:
65
+ """Lists the sending domains of the team."""
66
+ data, error = self._client.request("GET", "/v1/domains")
67
+ return data, error
68
+
69
+ def create(self, payload: models.DomainsCreateParams) -> tuple[models.Domain | None, ErrorResponse | None]:
70
+ """Adds a sending domain and returns the DNS records to publish."""
71
+ data, error = self._client.request("POST", "/v1/domains", body=payload)
72
+ return data, error
73
+
74
+ def verify(self, id: str | int) -> tuple[models.DomainsVerifyResponse | None, ErrorResponse | None]:
75
+ """Asks for the domain's DNS records to be checked again."""
76
+ data, error = self._client.request("PUT", f"/v1/domains/{segment(id)}/verify", body={})
77
+ return data, error
78
+
79
+ def get(self, id: str | int) -> tuple[models.Domain | None, ErrorResponse | None]:
80
+ """Reads one domain with its DNS records."""
81
+ data, error = self._client.request("GET", f"/v1/domains/{segment(id)}")
82
+ return data, error
83
+
84
+ def delete(self, id: str | int) -> tuple[models.DomainsDeleteResponse | None, ErrorResponse | None]:
85
+ """Removes a domain."""
86
+ data, error = self._client.request("DELETE", f"/v1/domains/{segment(id)}")
87
+ return data, error
88
+
89
+
90
+ class ContactsService:
91
+ """The API's contacts."""
92
+
93
+ def __init__(self, client: Requester) -> None:
94
+ self._client = client
95
+
96
+ def create(self, contact_book_id: str | int, payload: models.ContactsCreateParams) -> tuple[models.ContactsCreateResponse | None, ErrorResponse | None]:
97
+ """Adds a contact to a contact book."""
98
+ data, error = self._client.request("POST", f"/v1/contactBooks/{segment(contact_book_id)}/contacts", body=payload)
99
+ return data, error
100
+
101
+ def list(self, contact_book_id: str | int, *, emails: str | None = None, page: int | None = None, limit: int | None = None, ids: str | None = None) -> tuple[builtins.list[models.Contact] | None, ErrorResponse | None]:
102
+ """Lists the contacts of a contact book, optionally by email or id."""
103
+ query = {
104
+ "emails": emails,
105
+ "page": page,
106
+ "limit": limit,
107
+ "ids": ids,
108
+ }
109
+ data, error = self._client.request("GET", f"/v1/contactBooks/{segment(contact_book_id)}/contacts", query=query)
110
+ return data, error
111
+
112
+ def get(self, contact_book_id: str | int, contact_id: str | int) -> tuple[models.Contact | None, ErrorResponse | None]:
113
+ """Reads one contact."""
114
+ data, error = self._client.request("GET", f"/v1/contactBooks/{segment(contact_book_id)}/contacts/{segment(contact_id)}")
115
+ return data, error
116
+
117
+ def update(self, contact_book_id: str | int, contact_id: str | int, payload: models.ContactsUpdateParams) -> tuple[models.ContactsUpdateResponse | None, ErrorResponse | None]:
118
+ """Changes the fields of a contact that are sent."""
119
+ data, error = self._client.request("PATCH", f"/v1/contactBooks/{segment(contact_book_id)}/contacts/{segment(contact_id)}", body=payload)
120
+ return data, error
121
+
122
+ def upsert(self, contact_book_id: str | int, contact_id: str | int, payload: models.ContactsUpsertParams) -> tuple[models.ContactsUpsertResponse | None, ErrorResponse | None]:
123
+ """Creates the contact, or replaces it when it exists."""
124
+ data, error = self._client.request("PUT", f"/v1/contactBooks/{segment(contact_book_id)}/contacts/{segment(contact_id)}", body=payload)
125
+ return data, error
126
+
127
+ def delete(self, contact_book_id: str | int, contact_id: str | int) -> tuple[models.ContactsDeleteResponse | None, ErrorResponse | None]:
128
+ """Removes a contact."""
129
+ data, error = self._client.request("DELETE", f"/v1/contactBooks/{segment(contact_book_id)}/contacts/{segment(contact_id)}")
130
+ return data, error
131
+
132
+ def bulk_create(self, contact_book_id: str | int, payload: builtins.list[models.ContactsBulkCreateParams]) -> tuple[models.ContactsBulkCreateResponse | None, ErrorResponse | None]:
133
+ """Adds many contacts to a contact book in one request."""
134
+ data, error = self._client.request("POST", f"/v1/contactBooks/{segment(contact_book_id)}/contacts/bulk", body=payload)
135
+ return data, error
136
+
137
+ def bulk_delete(self, contact_book_id: str | int, payload: models.ContactsBulkDeleteParams) -> tuple[models.ContactsBulkDeleteResponse | None, ErrorResponse | None]:
138
+ """Removes many contacts from a contact book in one request."""
139
+ data, error = self._client.request("DELETE", f"/v1/contactBooks/{segment(contact_book_id)}/contacts/bulk", body=payload)
140
+ return data, error
141
+
142
+
143
+ class ContactBooksService:
144
+ """The API's contactBooks."""
145
+
146
+ def __init__(self, client: Requester) -> None:
147
+ self._client = client
148
+
149
+ def list(self) -> tuple[builtins.list[models.ContactBook] | None, ErrorResponse | None]:
150
+ """Lists the contact books of the team."""
151
+ data, error = self._client.request("GET", "/v1/contactBooks")
152
+ return data, error
153
+
154
+ def create(self, payload: models.ContactBooksCreateParams) -> tuple[models.ContactBook | None, ErrorResponse | None]:
155
+ """Creates a contact book."""
156
+ data, error = self._client.request("POST", "/v1/contactBooks", body=payload)
157
+ return data, error
158
+
159
+ def get(self, contact_book_id: str | int) -> tuple[models.ContactBook | None, ErrorResponse | None]:
160
+ """Reads one contact book."""
161
+ data, error = self._client.request("GET", f"/v1/contactBooks/{segment(contact_book_id)}")
162
+ return data, error
163
+
164
+ def update(self, contact_book_id: str | int, payload: models.ContactBooksUpdateParams) -> tuple[models.ContactBook | None, ErrorResponse | None]:
165
+ """Changes the fields of a contact book that are sent."""
166
+ data, error = self._client.request("PATCH", f"/v1/contactBooks/{segment(contact_book_id)}", body=payload)
167
+ return data, error
168
+
169
+ def delete(self, contact_book_id: str | int) -> tuple[models.ContactBooksDeleteResponse | None, ErrorResponse | None]:
170
+ """Removes a contact book and its contacts."""
171
+ data, error = self._client.request("DELETE", f"/v1/contactBooks/{segment(contact_book_id)}")
172
+ return data, error
173
+
174
+
175
+ class CampaignsService:
176
+ """The API's campaigns."""
177
+
178
+ def __init__(self, client: Requester) -> None:
179
+ self._client = client
180
+
181
+ def create(self, payload: models.CampaignsCreateParams) -> tuple[models.Campaign | None, ErrorResponse | None]:
182
+ """Creates a campaign, and sends it now when sendNow is true."""
183
+ data, error = self._client.request("POST", "/v1/campaigns", body=payload)
184
+ return data, error
185
+
186
+ def list(self, *, page: int | None = None, status: str | None = None, search: str | None = None) -> tuple[models.CampaignsListResponse | None, ErrorResponse | None]:
187
+ """Lists campaigns, optionally by status or a search text."""
188
+ query = {
189
+ "page": page,
190
+ "status": status,
191
+ "search": search,
192
+ }
193
+ data, error = self._client.request("GET", "/v1/campaigns", query=query)
194
+ return data, error
195
+
196
+ get_all = list
197
+
198
+ def get(self, campaign_id: str | int) -> tuple[models.Campaign | None, ErrorResponse | None]:
199
+ """Reads one campaign with its counters."""
200
+ data, error = self._client.request("GET", f"/v1/campaigns/{segment(campaign_id)}")
201
+ return data, error
202
+
203
+ def delete(self, campaign_id: str | int) -> tuple[models.CampaignRow | None, ErrorResponse | None]:
204
+ """Removes a campaign."""
205
+ data, error = self._client.request("DELETE", f"/v1/campaigns/{segment(campaign_id)}")
206
+ return data, error
207
+
208
+ def schedule(self, campaign_id: str | int, payload: models.CampaignsScheduleParams) -> tuple[models.CampaignsScheduleResponse | None, ErrorResponse | None]:
209
+ """Schedules a campaign, or sends it now when no time is given."""
210
+ data, error = self._client.request("POST", f"/v1/campaigns/{segment(campaign_id)}/schedule", body=payload)
211
+ return data, error
212
+
213
+ def pause(self, campaign_id: str | int) -> tuple[models.CampaignActionResponse | None, ErrorResponse | None]:
214
+ """Pauses a running or scheduled campaign."""
215
+ data, error = self._client.request("POST", f"/v1/campaigns/{segment(campaign_id)}/pause", body={})
216
+ return data, error
217
+
218
+ def resume(self, campaign_id: str | int) -> tuple[models.CampaignActionResponse | None, ErrorResponse | None]:
219
+ """Resumes a paused campaign."""
220
+ data, error = self._client.request("POST", f"/v1/campaigns/{segment(campaign_id)}/resume", body={})
221
+ return data, error
222
+
223
+
224
+ class AnalyticsService:
225
+ """The API's analytics."""
226
+
227
+ def __init__(self, client: Requester) -> None:
228
+ self._client = client
229
+
230
+ def email_time_series(self, *, days: str | None = None, domain_id: str | None = None) -> tuple[models.AnalyticsEmailTimeSeriesResponse | None, ErrorResponse | None]:
231
+ """Counts emails by day over the last 7 or 30 days."""
232
+ query = {
233
+ "days": days,
234
+ "domainId": domain_id,
235
+ }
236
+ data, error = self._client.request("GET", "/v1/analytics/email-time-series", query=query)
237
+ return data, error
238
+
239
+ def reputation_metrics(self, *, domain_id: str | None = None) -> tuple[models.AnalyticsReputationMetricsResponse | None, ErrorResponse | None]:
240
+ """Reads the bounce and complaint rates of the sending reputation."""
241
+ query = {
242
+ "domainId": domain_id,
243
+ }
244
+ data, error = self._client.request("GET", "/v1/analytics/reputation-metrics", query=query)
245
+ return data, error
246
+