maco-cli 0.4.5__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.
maco_cli/outgoing.py ADDED
@@ -0,0 +1,181 @@
1
+ """Compose RFC 5322 mail and submit it through SMTP or IMAP APPEND."""
2
+ import imaplib
3
+ import mimetypes
4
+ import re
5
+ import smtplib
6
+ from contextlib import suppress
7
+ from datetime import datetime, timezone
8
+ from email import policy
9
+ from email.errors import HeaderParseError, NonASCIILocalPartDefect
10
+ from email.headerregistry import Address
11
+ from email.message import EmailMessage
12
+ from email.utils import format_datetime, make_msgid
13
+ from pathlib import Path
14
+
15
+ from .errors import MacoError
16
+ from .incoming import mailbox_arg, special_folder
17
+ from .transport import connect_imap, connect_smtp, imap_command_error, imap_rejection
18
+
19
+
20
+ class SubmissionError(MacoError):
21
+ def __init__(self, message, **details):
22
+ super().__init__(message)
23
+ self.details = details
24
+
25
+
26
+ def _header_text(value, field):
27
+ if not isinstance(value, str) or re.search(r"[\x00-\x1f\x7f]", value):
28
+ raise MacoError(f"{field} must be a single line without control characters.")
29
+ return value
30
+
31
+
32
+ def _addresses(values, field):
33
+ addresses = []
34
+ for value in ([values] if isinstance(values, str) else values):
35
+ _header_text(value, field)
36
+ try:
37
+ header = policy.SMTP.header_factory(field, value)
38
+ if (not header.addresses or any(group.display_name is not None for group in header.groups)
39
+ or any(not isinstance(d, NonASCIILocalPartDefect) for d in header.defects)):
40
+ raise ValueError()
41
+ for address in header.addresses:
42
+ if not address.username or not address.domain:
43
+ raise ValueError()
44
+ for part in (address.username, address.domain, address.display_name):
45
+ _header_text(part, field)
46
+ domain = address.domain.encode("idna").decode("ascii").lower()
47
+ addresses.append(Address(address.display_name, address.username, domain))
48
+ except (ValueError, IndexError, HeaderParseError):
49
+ raise MacoError(f"Invalid {field} address. Use a full mailbox address.") from None
50
+ return addresses
51
+
52
+
53
+ def _message_id(value):
54
+ if not re.fullmatch(r"<[^<>@\s]+@[^<>@\s]+>", _header_text(value, "Message ID"), re.ASCII) or not value.isascii():
55
+ raise MacoError("Invalid reply message ID. Expected <id@domain>.")
56
+ return value
57
+
58
+
59
+ def _compose(account, to, cc, bcc, subject, body, attachments, in_reply_to, references):
60
+ sender, = _addresses(account.email, "From")
61
+ msg = EmailMessage(policy=policy.SMTP)
62
+ msg["From"] = sender
63
+ recipients = []
64
+ for field, values in (("To", to), ("Cc", cc), ("Bcc", bcc)):
65
+ addresses = _addresses(values, field)
66
+ if addresses:
67
+ msg[field] = addresses
68
+ recipients.extend(addr.addr_spec for addr in addresses)
69
+ msg["Subject"] = _header_text(subject, "Subject")
70
+ msg["Date"] = format_datetime(datetime.now(timezone.utc))
71
+ msg["Message-ID"] = make_msgid(domain=sender.domain)
72
+ refs = []
73
+ for value in ([references] if isinstance(references, str) else references or ()):
74
+ # Unfold the original References header and reconstruct it solely from IDs.
75
+ refs.extend(_message_id(ref) for ref in value.split())
76
+ if in_reply_to:
77
+ msg["In-Reply-To"] = _message_id(in_reply_to)
78
+ if in_reply_to not in refs:
79
+ refs.append(in_reply_to)
80
+ if refs:
81
+ msg["References"] = " ".join(refs)
82
+ msg.set_content(body, charset="utf-8", cte="quoted-printable")
83
+ for value in attachments:
84
+ path = Path(value)
85
+ filename = _header_text(path.name, "Attachment filename")
86
+ try:
87
+ if not path.is_file():
88
+ raise MacoError(f"Attachment is not a regular file: {filename}")
89
+ data = path.read_bytes()
90
+ except (OSError, ValueError):
91
+ raise MacoError(f"Unable to read attachment: {filename}") from None
92
+ mime_type, encoding = mimetypes.guess_type(filename)
93
+ # Encapsulated messages and multiparts have structural MIME rules.
94
+ # Represent an explicitly attached file as octets to preserve its bytes.
95
+ if not mime_type or encoding or mime_type.startswith(("message/", "multipart/")):
96
+ mime_type = "application/octet-stream"
97
+ maintype, subtype = mime_type.split("/", 1)
98
+ msg.add_attachment(data, maintype=maintype, subtype=subtype, filename=filename)
99
+ return msg, sender.addr_spec, list(dict.fromkeys(recipients))
100
+
101
+
102
+ def _refusals(errors):
103
+ return [{"address": address, "code": response[0]} for address, response in errors.items()]
104
+
105
+
106
+ def send(account, *, to=(), cc=(), bcc=(), subject="", body="", attachments=(),
107
+ in_reply_to=None, references=()):
108
+ msg, sender, recipients = _compose(account, to, cc, bcc, subject, body, attachments,
109
+ in_reply_to, references)
110
+ if not recipients:
111
+ raise MacoError("Sending requires at least one To, Cc or Bcc recipient.")
112
+ message_id = str(msg["Message-ID"])
113
+ smtp = connect_smtp(account)
114
+ try:
115
+ # send_message removes Bcc from the wire copy and negotiates SMTPUTF8
116
+ # for internationalized envelope addresses when the server supports it.
117
+ refused = smtp.send_message(msg, from_addr=sender, to_addrs=recipients)
118
+ except smtplib.SMTPRecipientsRefused as exc:
119
+ raise SubmissionError("SMTP declined the recipient transaction. No message was submitted.",
120
+ status="rejected", message_id=message_id, accepted=[],
121
+ refused=_refusals(exc.recipients)) from None
122
+ except smtplib.SMTPNotSupportedError:
123
+ raise SubmissionError("Address requires SMTPUTF8, which this server does not advertise.",
124
+ status="rejected", message_id=message_id) from None
125
+ except smtplib.SMTPResponseException as exc:
126
+ if isinstance(exc, smtplib.SMTPDataError) and not 400 <= exc.smtp_code < 600:
127
+ raise SubmissionError("SMTP returned an unexpected DATA reply. Check delivery before retrying.",
128
+ status="unknown", message_id=message_id, code=exc.smtp_code) from None
129
+ raise SubmissionError(f"SMTP rejected the submission (code {exc.smtp_code}).",
130
+ status="rejected", message_id=message_id, code=exc.smtp_code) from None
131
+ except OSError:
132
+ # A connection failure after DATA can follow a successful submission.
133
+ raise SubmissionError("SMTP connection failed during submission. Check delivery before retrying.",
134
+ status="unknown", message_id=message_id) from None
135
+ finally:
136
+ # A failed QUIT cannot change the outcome returned for DATA.
137
+ with suppress(OSError):
138
+ smtp.quit()
139
+ with suppress(OSError):
140
+ smtp.close()
141
+ accepted = [address for address in recipients if address not in refused]
142
+ if refused:
143
+ raise SubmissionError("SMTP accepted some recipients. Retry only the refused addresses.",
144
+ status="partial", message_id=message_id, accepted=accepted,
145
+ refused=_refusals(refused))
146
+ return {"status": "sent", "message_id": message_id, "accepted": accepted}
147
+
148
+
149
+ def save_draft(account, *, folder=None, to=(), cc=(), bcc=(), subject="", body="",
150
+ attachments=(), in_reply_to=None, references=()):
151
+ msg, sender, recipients = _compose(account, to, cc, bcc, subject, body, attachments,
152
+ in_reply_to, references)
153
+ if any(not addr.isascii() for addr in [sender, *recipients]):
154
+ raise MacoError("Saving a draft requires ASCII mailbox local parts.")
155
+ data = msg.as_bytes()
156
+ message_id = str(msg["Message-ID"])
157
+ imap = connect_imap(account)
158
+ try:
159
+ if folder is None:
160
+ folder = special_folder(imap, r"\Drafts")
161
+ result = {"status": "draft_saved", "folder": folder, "message_id": message_id}
162
+ try:
163
+ status, response = imap.append(mailbox_arg(folder), r"(\Draft)", None, data)
164
+ except (imaplib.IMAP4.abort, OSError) as exc:
165
+ raise SubmissionError("IMAP connection failed during APPEND. Check the folder before retrying.",
166
+ status="unknown", message_id=message_id, folder=folder,
167
+ **imap_command_error("APPEND", exc).details) from None
168
+ except imaplib.IMAP4.error as exc:
169
+ raise imap_command_error("APPEND", exc) from None
170
+ if status != "OK":
171
+ raise imap_rejection("APPEND", status, response)
172
+ # UIDPLUS servers include the newly assigned UID in the tagged reply.
173
+ for item in response or ():
174
+ match = re.search(rb"\[APPENDUID (\d+) (\d+)\]", item, re.I) if isinstance(item, bytes) else None
175
+ if match:
176
+ result.update(uidvalidity=int(match[1]), uid=int(match[2]))
177
+ break
178
+ return result
179
+ finally:
180
+ with suppress(OSError, imaplib.IMAP4.error):
181
+ imap.logout()
maco_cli/provider.py ADDED
@@ -0,0 +1,272 @@
1
+ """Operate on an account-owned Gmail or Outlook connection over its provider API."""
2
+ import json
3
+ import logging
4
+ import os
5
+ import socket
6
+ import ssl
7
+ import time
8
+ from concurrent.futures import ThreadPoolExecutor
9
+ from contextlib import contextmanager
10
+ from http.client import HTTPException, IncompleteRead
11
+ from urllib.error import HTTPError, URLError
12
+ from urllib.parse import urlencode, urlsplit
13
+ from urllib.request import Request, HTTPSHandler, build_opener
14
+
15
+ from . import __version__, incoming, outgoing
16
+ from .errors import MacoError
17
+ from .helper_client import _NoRedirect, lease_credential
18
+
19
+
20
+ BASES = {"gmail": "https://gmail.googleapis.com/gmail/v1/users/me/",
21
+ "outlook": "https://graph.microsoft.com/v1.0/me/"}
22
+ LOG = logging.getLogger(__name__)
23
+ MAX_BYTES = 128 * 1024 * 1024
24
+ READ_RETRY_DELAYS = (1, 2)
25
+ QUERY_BUDGET = 30
26
+ QUERY_REQUEST_TIMEOUT = 10
27
+ QUERY_TIMEOUT_MESSAGE = "Mailbox query timed out. Narrow the query or add a date range."
28
+ _TRANSIENT_STATUS = {429, 500, 502, 503, 504}
29
+ _GMAIL_RETRY_REASONS = {"rateLimitExceeded", "userRateLimitExceeded"}
30
+ _GMAIL_ERROR_REASONS = _GMAIL_RETRY_REASONS | {
31
+ "abuseRateLimitExceeded", "accessNotConfigured", "authError", "backendError", "badRequest",
32
+ "dailyLimitExceeded", "domainPolicy", "forbidden", "insufficientPermissions", "invalid",
33
+ "invalidArgument", "notFound", "quotaExceeded", "required",
34
+ "INVALID_ARGUMENT", "NOT_FOUND", "PERMISSION_DENIED", "RESOURCE_EXHAUSTED", "UNAUTHENTICATED",
35
+ "UNAVAILABLE", "INTERNAL", "FAILED_PRECONDITION", "ACCESS_TOKEN_SCOPE_INSUFFICIENT",
36
+ }
37
+ _GRAPH_ERROR_CODES = {
38
+ "BadRequest", "Forbidden", "InefficientFilter", "InvalidAuthenticationToken", "InvalidRequest",
39
+ "MailboxNotEnabledForRESTAPI", "ResourceNotFound", "ServiceUnavailable", "TooManyRequests",
40
+ "ErrorAccessDenied", "ErrorInvalidIdMalformed", "ErrorInvalidIdEmpty", "ErrorInvalidIdNotAnItemAttachmentId",
41
+ "ErrorInvalidRequest", "ErrorItemNotFound", "ErrorMailboxStoreUnavailable", "ErrorMessageSizeExceeded",
42
+ "ErrorMimeContentConversionFailed", "ErrorMimeContentInvalid", "ErrorMimeContentInvalidBase64String",
43
+ "ErrorServerBusy", "ErrorInvalidOperation", "ErrorInternalServerError",
44
+ }
45
+
46
+
47
+ def _read_failure(error):
48
+ reason = error.reason if isinstance(error, URLError) else error
49
+ if isinstance(reason, socket.gaierror):
50
+ return "dns", "DNS lookup for the mail provider failed.", reason.errno == socket.EAI_AGAIN
51
+ if isinstance(reason, ssl.SSLCertVerificationError):
52
+ return "tls_certificate", "TLS certificate verification for the mail provider failed.", False
53
+ if isinstance(reason, TimeoutError):
54
+ return "timeout", "The connection to the mail provider timed out.", True
55
+ if isinstance(reason, (ConnectionError, IncompleteRead, ssl.SSLEOFError)):
56
+ return "interrupted", "The connection to the mail provider was interrupted.", True
57
+ if isinstance(reason, ssl.SSLError):
58
+ return "tls", "The TLS connection to the mail provider failed.", False
59
+ return "network", "Could not complete the request to the mail provider.", False
60
+
61
+
62
+ def _diagnostic_reason(provider, response):
63
+ # Only display known protocol identifiers. Raw error messages can contain
64
+ # mailbox addresses, message identifiers, full request URLs or content.
65
+ try:
66
+ error = json.loads(response.read(16 * 1024)).get("error")
67
+ except (ValueError, AttributeError, OSError, HTTPException, RecursionError):
68
+ return None
69
+ if not isinstance(error, dict):
70
+ return None
71
+ if provider == "outlook":
72
+ code = error.get("code")
73
+ return code if isinstance(code, str) and code in _GRAPH_ERROR_CODES else None
74
+ for key in ("errors", "details"):
75
+ rows = error.get(key)
76
+ if isinstance(rows, list):
77
+ for row in rows:
78
+ reason = row.get("reason") if isinstance(row, dict) else None
79
+ if isinstance(reason, str) and reason in _GMAIL_ERROR_REASONS:
80
+ return reason
81
+ status = error.get("status")
82
+ return status if isinstance(status, str) and status in _GMAIL_ERROR_REASONS else None
83
+
84
+
85
+ class ProviderHTTP:
86
+ """One CLI invocation connects to a fixed provider with an in-memory access token."""
87
+ def __init__(self, account):
88
+ self.account = account
89
+ self.provider = account.mailbox_auth
90
+ self.base = BASES[self.provider]
91
+ self._token = None
92
+ self._query_deadline = None
93
+ context = ssl.create_default_context(cafile=os.environ.get("SSL_CERT_FILE") or None)
94
+ self.opener = build_opener(_NoRedirect(), HTTPSHandler(context=context))
95
+
96
+ @contextmanager
97
+ def query_budget(self):
98
+ self._query_deadline = time.monotonic() + QUERY_BUDGET
99
+ try:
100
+ yield
101
+ finally:
102
+ self._query_deadline = None
103
+
104
+ def _query_remaining(self):
105
+ remaining = self._query_deadline - time.monotonic()
106
+ if remaining <= 0:
107
+ self._fail(QUERY_TIMEOUT_MESSAGE, category="timeout")
108
+ return remaining
109
+
110
+ def _response_data(self, response):
111
+ if self._query_deadline is None:
112
+ return response.read(MAX_BYTES + 1)
113
+ chunks = bytearray()
114
+ while len(chunks) <= MAX_BYTES:
115
+ self._query_remaining()
116
+ chunk = response.read1(min(65536, MAX_BYTES + 1 - len(chunks)))
117
+ if not chunk:
118
+ break
119
+ chunks.extend(chunk)
120
+ return bytes(chunks)
121
+
122
+ def acquire(self):
123
+ if self._token is None:
124
+ started = time.monotonic()
125
+ try:
126
+ self._token = lease_credential(self.account, self.provider)
127
+ except MacoError as exc:
128
+ exc.details = {**getattr(exc, "details", {}), "provider": self.provider, "stage": "helper_lease"}
129
+ LOG.debug("provider=%s stage=helper_lease outcome=failed elapsed_ms=%d",
130
+ self.provider, (time.monotonic() - started) * 1000)
131
+ raise
132
+ LOG.debug("provider=%s stage=helper_lease outcome=success elapsed_ms=%d",
133
+ self.provider, (time.monotonic() - started) * 1000)
134
+
135
+ def request(self, method, path, *, params=None, json_body=None, data=None, content_type=None, raw=False):
136
+ parts = urlsplit(path)
137
+ if (parts.scheme or parts.netloc or parts.fragment or not parts.path or path.startswith("/")
138
+ or any(s in (".", "..") for s in parts.path.split("/")) or "\\" in path
139
+ or any(ord(char) < 32 for char in path)):
140
+ raise MacoError("Invalid mailbox API path.")
141
+ url = self.base + path
142
+ if params:
143
+ url += ("&" if parts.query else "?") + urlencode(params, doseq=True)
144
+ self.acquire()
145
+ headers = {"Authorization": "Bearer " + self._token, "Accept": "*/*" if raw else "application/json",
146
+ "User-Agent": "maco-cli/" + __version__}
147
+ if self.provider == "outlook":
148
+ headers["Prefer"] = 'IdType="ImmutableId"'
149
+ if json_body is not None:
150
+ data = json.dumps(json_body).encode("utf-8")
151
+ content_type = "application/json"
152
+ if content_type:
153
+ headers["Content-Type"] = content_type
154
+ req = Request(url, method=method, data=data, headers=headers)
155
+ payload = self._read_response(req)
156
+ if len(payload) > MAX_BYTES:
157
+ raise MacoError("The mail provider response exceeds the supported size.")
158
+ if not payload and method == "GET":
159
+ self._fail("The mail provider returned an empty response.", category="invalid_response")
160
+ if raw:
161
+ return payload
162
+ try:
163
+ result = json.loads(payload) if payload else {}
164
+ if not isinstance(result, dict):
165
+ raise ValueError()
166
+ return result
167
+ except (ValueError, RecursionError):
168
+ self._fail("The mail provider returned an invalid response.", category="invalid_response")
169
+
170
+ def get_many(self, paths, *, params):
171
+ # Gmail returns message IDs first. Bound parallel header requests and
172
+ # keep their results in the original server order.
173
+ if len(paths) < 2:
174
+ return [self.request("GET", path, params=params) for path in paths]
175
+ self.acquire()
176
+ with ThreadPoolExecutor(max_workers=4) as pool:
177
+ return list(pool.map(lambda path: self.request("GET", path, params=params), paths))
178
+
179
+ def _fail(self, message, **details):
180
+ error = MacoError(message)
181
+ error.details = {"provider": self.provider, "stage": "mail_api", **details}
182
+ raise error from None
183
+
184
+ def _read_response(self, request):
185
+ method = request.get_method()
186
+ delays = iter(READ_RETRY_DELAYS if method == "GET" else ())
187
+ attempt = 0
188
+ while True:
189
+ attempt += 1
190
+ started = time.monotonic()
191
+ timeout = 45 if self._query_deadline is None else min(QUERY_REQUEST_TIMEOUT, self._query_remaining())
192
+ try:
193
+ with self.opener.open(request, timeout=timeout) as response:
194
+ payload = self._response_data(response)
195
+ LOG.debug("provider=%s stage=mail_api method=%s attempt=%d outcome=success elapsed_ms=%d",
196
+ self.provider, method, attempt, (time.monotonic() - started) * 1000)
197
+ return payload
198
+ except HTTPError as exc:
199
+ try:
200
+ reason = _diagnostic_reason(self.provider, exc)
201
+ retry_after = exc.headers.get("Retry-After", "") if exc.headers else ""
202
+ finally:
203
+ exc.close()
204
+ status = exc.code
205
+ LOG.debug("provider=%s stage=mail_api method=%s attempt=%d status=%d elapsed_ms=%d",
206
+ self.provider, method, attempt, status, (time.monotonic() - started) * 1000)
207
+ details = {"http_status": status, "attempts": attempt}
208
+ if reason:
209
+ details["reason"] = reason
210
+ throttled = status == 429 or (status == 403 and reason in _GMAIL_RETRY_REASONS)
211
+ retryable = status in _TRANSIENT_STATUS or throttled
212
+ delay = next(delays, None) if retryable and (not retry_after or
213
+ (retry_after.isascii() and retry_after.isdecimal() and len(retry_after) <= 2)) else None
214
+ if delay is not None and retry_after:
215
+ delay = max(delay, int(retry_after)) if int(retry_after) <= 5 else None
216
+ if delay is None:
217
+ if throttled:
218
+ message = "The mail provider is rate limiting requests. Try again later."
219
+ elif status in (401, 403):
220
+ message = "The mail provider denied access. Check this mailbox's authorization in Maco."
221
+ elif method != "GET" and status >= 500:
222
+ message = "Mailbox update outcome is unknown. Check the mailbox before retrying."
223
+ else:
224
+ message = f"The mail provider returned HTTP {status}."
225
+ self._fail(message, **details)
226
+ except (OSError, HTTPException) as exc:
227
+ category, message, retryable = _read_failure(exc)
228
+ LOG.debug("provider=%s stage=mail_api method=%s attempt=%d category=%s elapsed_ms=%d",
229
+ self.provider, method, attempt, category, (time.monotonic() - started) * 1000)
230
+ if method != "GET":
231
+ self._fail("Mailbox update outcome is unknown. Check the mailbox before retrying.",
232
+ category=category, attempts=attempt)
233
+ delay = next(delays, None) if retryable else None
234
+ if delay is None:
235
+ self._fail(message, category=category, attempts=attempt)
236
+ if self._query_deadline is not None and delay >= self._query_remaining():
237
+ self._fail(QUERY_TIMEOUT_MESSAGE, category="timeout")
238
+ time.sleep(delay)
239
+
240
+
241
+ class ProviderMailbox:
242
+ def __init__(self, account):
243
+ from .gmail_api import GmailAPI
244
+ from .graph_api import GraphAPI
245
+ api = GmailAPI if account.mailbox_auth == "gmail" else GraphAPI
246
+ self.http = ProviderHTTP(account)
247
+ self.api = api(self.http)
248
+
249
+ def acquire(self):
250
+ self.http.acquire()
251
+
252
+ def _message(self, message_id):
253
+ return incoming.parse_message(self.api.raw(message_id))
254
+
255
+ def headers(self, message_id):
256
+ return incoming.message_headers(self._message(message_id))
257
+
258
+ def read(self, message_id, *, include_attachments=True):
259
+ message = self._message(message_id)
260
+ return incoming.message_details(message, {"id": message_id, **incoming.message_headers(message)},
261
+ include_attachments=include_attachments)
262
+
263
+ def attachment(self, message_id, part, output):
264
+ return incoming.save_attachment(self._message(message_id), {"id": message_id}, part, output)
265
+
266
+ def submit_message(self, profile, fields, *, draft, reply_id):
267
+ fields.setdefault("in_reply_to", None)
268
+ fields.setdefault("references", ())
269
+ message, _, recipients = outgoing._compose(profile, **fields)
270
+ if not draft and not recipients:
271
+ raise MacoError("Sending requires at least one To, Cc or Bcc recipient.")
272
+ return self.api.submit(message, draft=draft, reply_id=reply_id)
@@ -0,0 +1,81 @@
1
+ """Verify literal matches in native search candidates and rank by matched field."""
2
+ import unicodedata
3
+
4
+ from . import incoming
5
+ from .errors import MacoError
6
+ from .mail_query import phrases
7
+ from .message_text import body_text
8
+
9
+
10
+ CANDIDATE_LIMIT = 100
11
+
12
+
13
+ def _normalized(value):
14
+ return " ".join(unicodedata.normalize("NFKC", value).casefold().split())
15
+
16
+
17
+ def _matches(value, needles):
18
+ normalized = _normalized(value)
19
+ return any(needle in normalized for needle in needles)
20
+
21
+
22
+ def _verified(listed, key, read_body, header_filters, query, scope, limit, offset, fill_page_only):
23
+ candidates = listed[key][:CANDIDATE_LIMIT]
24
+ ranked = []
25
+ body_candidates = []
26
+ for position, row in enumerate(candidates):
27
+ if any(needle not in _normalized(row[field]) for field, needle in header_filters):
28
+ continue
29
+ fields = [field for field, _ in header_filters]
30
+ score = 0
31
+ if query:
32
+ hits = [field for field in ("subject", "from")
33
+ if scope in ("any", field) and _matches(row[field], query)]
34
+ if hits:
35
+ score = 3 if "subject" in hits else 2
36
+ elif scope in ("any", "body"):
37
+ body_candidates.append((position, row, fields))
38
+ if not hits:
39
+ continue
40
+ fields = list(dict.fromkeys([*fields, *hits]))
41
+ ranked.append((score, position, row, fields))
42
+
43
+ bodies_checked = 0
44
+ for position, row, fields in body_candidates:
45
+ # All header hits outrank body-only hits, so the remainder cannot change a full page.
46
+ if fill_page_only and len(ranked) >= offset + limit:
47
+ break
48
+ details = read_body(row)
49
+ bodies_checked += 1
50
+ if details is not None and _matches(body_text(details["body"], details["body_type"]), query):
51
+ ranked.append((1, position, row, [*fields, "body"]))
52
+
53
+ ranked.sort(key=lambda item: (-item[0], item[1]))
54
+ matches = [{**row, "matched_fields": fields} for _, _, row, fields in ranked[offset:offset + limit]]
55
+ more = (listed.get("truncated", False) or listed.get("total", len(listed[key])) > CANDIDATE_LIMIT
56
+ or bodies_checked < len(body_candidates))
57
+ result = {"folder": listed["folder"], "offset": offset, key: matches,
58
+ "strict": {"scope": scope, "candidates_checked": len(candidates),
59
+ "more_candidates": more,
60
+ "matches": len(ranked)}}
61
+ if "uidvalidity" in listed:
62
+ result["uidvalidity"] = listed["uidvalidity"]
63
+ return result
64
+
65
+
66
+ def search(account, provider, folder, *, limit, offset, unread, sender, subject, text, scope,
67
+ after=None, before=None, fill_page_only=False):
68
+ headers = [(field, _normalized(value)) for field, value in (("from", sender), ("subject", subject))
69
+ if value is not None]
70
+ query = tuple(_normalized(phrase) for phrase in phrases(text))
71
+ if any(not term for _, term in headers) or any(not term for term in query):
72
+ raise MacoError("Strict search requires non-blank search terms.")
73
+ filters = dict(limit=CANDIDATE_LIMIT + 1, unread=unread, sender=sender, subject=subject, text=text,
74
+ scope=scope, after=after, before=before)
75
+ if provider:
76
+ listed = provider.api.emails(folder, offset=0, **filters)
77
+ return _verified(listed, "messages", lambda row: provider.read(row["id"], include_attachments=False),
78
+ headers, query, scope, limit, offset, fill_page_only)
79
+ with incoming.search_candidates(account, folder, **filters) as (listed, read_body):
80
+ return _verified(listed, "emails", lambda row: read_body(row["uid"]),
81
+ headers, query, scope, limit, offset, fill_page_only)