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/incoming.py ADDED
@@ -0,0 +1,440 @@
1
+ """IMAP mailbox operations. UID references are scoped to a folder and UIDVALIDITY."""
2
+
3
+ import base64
4
+ import logging
5
+ import os
6
+ import re
7
+ from contextlib import contextmanager
8
+ from email import policy
9
+ from email.errors import MessageError
10
+ from email.parser import BytesParser
11
+ from pathlib import Path
12
+
13
+ from .errors import MacoError, MailError
14
+ from .mail_query import phrases
15
+ from .transport import connect_imap, imap_command
16
+
17
+
18
+ LOG = logging.getLogger(__name__)
19
+
20
+
21
+ def _quote(value):
22
+ return b'"' + value.replace(b"\\", b"\\\\").replace(b'"', b'\\"') + b'"'
23
+
24
+
25
+ def _check_string(value):
26
+ if any(ord(char) < 32 or ord(char) == 127 for char in value):
27
+ raise MacoError("IMAP arguments cannot contain control characters.")
28
+
29
+
30
+ def mailbox_arg(name):
31
+ """Encode and quote a user-visible mailbox name for IMAP4rev1."""
32
+ if not name:
33
+ raise MacoError("A folder name is required.")
34
+ _check_string(name)
35
+
36
+ def encode_run(match):
37
+ encoded = base64.b64encode(match[0].encode("utf-16-be"), altchars=b"+,")
38
+ return "&" + encoded.rstrip(b"=").decode("ascii") + "-"
39
+
40
+ escaped = name.replace("&", "&-")
41
+ return _quote(re.sub(r"[^ -~]+", encode_run, escaped).encode("ascii"))
42
+
43
+
44
+ def _decode_mailbox(value):
45
+ def decode_run(match):
46
+ if not match[1]:
47
+ return "&"
48
+ encoded = match[1].encode("ascii")
49
+ padded = encoded + b"=" * (-len(encoded) % 4)
50
+ return base64.b64decode(padded, altchars=b"+,", validate=True).decode("utf-16-be")
51
+
52
+ try:
53
+ return re.sub(r"&([A-Za-z0-9+,]*)-", decode_run, value.decode("ascii"))
54
+ except (UnicodeError, ValueError) as exc:
55
+ raise MacoError("Invalid modified UTF-7 in IMAP folder name.") from exc
56
+
57
+
58
+ def _unquote(value):
59
+ if value.startswith(b'"') and value.endswith(b'"'):
60
+ return re.sub(rb'\\(["\\])', rb'\1', value[1:-1])
61
+ return value
62
+
63
+
64
+ _LIST_RECORD = re.compile(rb'^\(([^)]*)\)\s+(NIL|"(?:[^"\\]|\\.)*")\s+(.+)$', re.I)
65
+
66
+
67
+ def _folders(client):
68
+ result = []
69
+ pattern = '"*" RETURN (SPECIAL-USE)' if "SPECIAL-USE" in client.capabilities else "*"
70
+ for row in imap_command("LIST", client.list, pattern=pattern):
71
+ if not row:
72
+ continue # imaplib includes the empty line following a literal.
73
+ prefix, literal = row if isinstance(row, tuple) else (row, None)
74
+ match = _LIST_RECORD.fullmatch(prefix)
75
+ if not match:
76
+ raise MacoError("Cannot parse the server's IMAP LIST response.")
77
+ flags, delimiter, name = match.groups()
78
+ result.append({
79
+ "name": _decode_mailbox(_unquote(name) if literal is None else literal),
80
+ "delimiter": None if delimiter.upper() == b"NIL" else _unquote(delimiter).decode("ascii"),
81
+ "flags": flags.decode("ascii").split(),
82
+ })
83
+ return result
84
+
85
+
86
+ def folders(account):
87
+ with connect_imap(account) as client:
88
+ return {"folders": _folders(client)}
89
+
90
+
91
+ def special_folder(client, flag):
92
+ matches = [entry["name"] for entry in _folders(client)
93
+ if flag.lower() in {f.lower() for f in entry["flags"]}]
94
+ if len(matches) != 1:
95
+ raise MacoError(f"Could not identify a unique {flag} folder. Specify its name explicitly.")
96
+ return matches[0]
97
+
98
+
99
+ def _number(value, label):
100
+ if not re.fullmatch(r"[1-9][0-9]{0,9}", str(value)) or int(value) > 4294967295:
101
+ raise MacoError(f"{label} must be a positive 32-bit number.")
102
+ return int(value)
103
+
104
+
105
+ def _select(client, folder, expected=None, readonly=True):
106
+ command = "EXAMINE" if readonly else "SELECT"
107
+ imap_command(command, client.select, mailbox_arg(folder), readonly=readonly)
108
+ _, values = client.response("UIDVALIDITY")
109
+ if not values or not isinstance(values[-1], bytes) or not values[-1].isdigit():
110
+ raise MailError("The IMAP server did not provide UIDVALIDITY.", "imap", "imap_command",
111
+ command=command, reason="invalid_response")
112
+ actual = _number(values[-1].decode("ascii"), "UIDVALIDITY")
113
+ if expected is not None and actual != _number(expected, "UIDVALIDITY"):
114
+ raise MacoError("Folder UIDVALIDITY has changed. List the folder again to obtain current UIDs.")
115
+ return actual
116
+
117
+
118
+ def _imap_date(day):
119
+ months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
120
+ return f"{day.day}-{months[day.month - 1]}-{day.year:04d}"
121
+
122
+
123
+ def _search(client, unread, filters, after=None, before=None):
124
+ criteria = ["UNSEEN"] if unread else []
125
+ if after:
126
+ criteria.extend(("SINCE", _imap_date(after)))
127
+ if before:
128
+ criteria.extend(("BEFORE", _imap_date(before)))
129
+ literals = []
130
+ for key, value in filters:
131
+ if not value:
132
+ continue
133
+ _check_string(value)
134
+ if value.isascii():
135
+ criteria.extend([key, _quote(value.encode("ascii"))])
136
+ else:
137
+ literals.append((key, value.encode("utf-8")))
138
+
139
+ # imaplib can send one synchronizing literal at the end of each command.
140
+ # For multiple non-ASCII terms, intersect UID SEARCH results in this session.
141
+ queries = []
142
+ for key, literal in literals:
143
+ queries.append((["CHARSET", "UTF-8", *criteria, key], literal))
144
+ criteria = []
145
+ if not queries:
146
+ queries.append((criteria or ["ALL"], None))
147
+ result = None
148
+ for args, literal in queries:
149
+ if literal is not None:
150
+ client.literal = literal
151
+ fields = ",".join(word for word in args if isinstance(word, str)
152
+ and word in ("FROM", "SUBJECT", "BODY", "TEXT", "UNSEEN", "SINCE", "BEFORE", "ALL"))
153
+ LOG.debug("protocol=imap command='UID SEARCH' fields=%s charset=%s",
154
+ fields, "UTF-8" if literal is not None else "default")
155
+ rows = imap_command("UID SEARCH", client.uid, "SEARCH", *args)
156
+ matches = set()
157
+ for row in rows or ():
158
+ if row is None:
159
+ continue
160
+ if not isinstance(row, bytes):
161
+ raise _invalid_search_response()
162
+ for uid in row.split():
163
+ if not re.fullmatch(rb"[1-9][0-9]{0,9}", uid) or int(uid) > 4294967295:
164
+ raise _invalid_search_response()
165
+ matches.add(int(uid))
166
+ LOG.debug("protocol=imap command='UID SEARCH' status=OK returned_uids=%d", len(matches))
167
+ result = matches if result is None else result & matches
168
+ if not result:
169
+ break
170
+ return sorted(result, reverse=True)
171
+
172
+
173
+ def _invalid_search_response():
174
+ return MailError("The IMAP server returned an invalid UID SEARCH result.", "imap", "imap_command",
175
+ command="UID SEARCH", reason="invalid_response")
176
+
177
+
178
+ _UID = re.compile(rb"\bUID ([0-9]+)\b", re.I)
179
+ _FLAGS = re.compile(rb"\bFLAGS \(([^)]*)\)", re.I)
180
+ _SUMMARY = "(UID FLAGS BODY.PEEK[HEADER.FIELDS (FROM TO CC REPLY-TO SUBJECT DATE MESSAGE-ID REFERENCES)])"
181
+ _FULL_MESSAGE = "(UID FLAGS BODY.PEEK[])"
182
+
183
+
184
+ def _response_uid(meta):
185
+ # User-defined flag keywords may themselves be "UID" followed by a number.
186
+ match = _UID.search(_FLAGS.sub(b"", meta))
187
+ return int(match[1]) if match else None
188
+
189
+
190
+ def parse_message(raw):
191
+ try:
192
+ return BytesParser(policy=policy.default).parsebytes(raw)
193
+ except (MessageError, ValueError, LookupError, RecursionError):
194
+ raise MacoError("Could not decode the mail server's message.") from None
195
+
196
+
197
+ def _fetch(client, uids, fields):
198
+ """Handle servers placing UID and FLAGS after the response literal."""
199
+ rows = imap_command("UID FETCH", client.uid, "FETCH", ",".join(map(str, uids)), fields)
200
+ wanted = set(uids)
201
+ messages = {}
202
+ for index, row in enumerate(rows):
203
+ if not isinstance(row, tuple):
204
+ continue
205
+ meta, raw = row
206
+ if index + 1 < len(rows) and isinstance(rows[index + 1], bytes):
207
+ meta += b" " + rows[index + 1]
208
+ uid = _response_uid(meta)
209
+ if uid is None:
210
+ raise MacoError("A fetched message was missing its UID.")
211
+ if uid in wanted:
212
+ flags = _FLAGS.search(meta)
213
+ messages[uid] = (
214
+ flags[1].decode("ascii", "replace").split() if flags else [],
215
+ parse_message(raw),
216
+ )
217
+ return messages
218
+
219
+
220
+ def _headers(message, folder, uid, validity, flags):
221
+ return {"folder": folder, "uid": uid, "uidvalidity": validity, "flags": flags, **message_headers(message)}
222
+
223
+
224
+ def message_headers(message):
225
+ headers = {}
226
+ try:
227
+ for key in ("Subject", "From", "To", "Cc", "Reply-To", "Message-ID", "References", "Date"):
228
+ headers[key.lower().replace("-", "_")] = str(message.get(key, ""))
229
+ except (MessageError, ValueError, LookupError, RecursionError):
230
+ raise MacoError("Could not decode the message headers.") from None
231
+ return headers
232
+
233
+
234
+ def _listing(client, folder, limit, offset, unread, filters, *, text, query_field, after, before):
235
+ if limit < 1 or offset < 0:
236
+ raise MacoError("Limit must be positive and offset must be nonnegative.")
237
+ validity = _select(client, folder)
238
+ candidates = set()
239
+ for phrase in phrases(text) or (None,):
240
+ candidates.update(_search(client, unread, (*filters, (query_field, phrase)), after, before))
241
+ matches = sorted(candidates, reverse=True)
242
+ page = matches[offset:offset + limit]
243
+ items = []
244
+ # Bound the wire length and memory used by any single FETCH command.
245
+ for start in range(0, len(page), 100):
246
+ batch = page[start:start + 100]
247
+ fetched = _fetch(client, batch, _SUMMARY)
248
+ for uid in batch:
249
+ if uid in fetched: # Another client may expunge between SEARCH and FETCH.
250
+ flags, message = fetched[uid]
251
+ items.append(_headers(message, folder, uid, validity, flags))
252
+ return {"folder": folder, "uidvalidity": validity, "total": len(matches), "offset": offset, "emails": items}
253
+
254
+
255
+ def emails(account, folder="INBOX", limit=20, offset=0, unread=False, sender=None, subject=None, text=None,
256
+ after=None, before=None):
257
+ with connect_imap(account) as client:
258
+ return _listing(client, folder, limit, offset, unread, (("FROM", sender), ("SUBJECT", subject)),
259
+ text=text, query_field="TEXT", after=after, before=before)
260
+
261
+
262
+ @contextmanager
263
+ def search_candidates(account, folder, *, limit, unread, sender, subject, text, scope, after=None, before=None):
264
+ """Keep the same read-only folder open while verifying candidates by UID."""
265
+ query_field = {"any": "TEXT", "subject": "SUBJECT", "from": "FROM", "body": "BODY"}[scope]
266
+ with connect_imap(account) as client:
267
+ listing = _listing(client, folder, limit, 0, unread, (("FROM", sender), ("SUBJECT", subject)),
268
+ text=text, query_field=query_field, after=after, before=before)
269
+
270
+ def read_body(uid):
271
+ record = _fetch(client, [uid], _FULL_MESSAGE).get(uid)
272
+ if record is None:
273
+ return None # It was expunged after the header fetch.
274
+ return message_details(record[1], {}, include_attachments=False)
275
+
276
+ yield listing, read_body
277
+
278
+
279
+ def _message(account, folder, uid, expected):
280
+ uid = _number(uid, "UID")
281
+ with connect_imap(account) as client:
282
+ validity = _select(client, folder, expected)
283
+ return _selected_message(client, folder, uid, validity)
284
+
285
+
286
+ def _selected_message(client, folder, uid, validity):
287
+ records = _fetch(client, [uid], _FULL_MESSAGE)
288
+ if uid not in records:
289
+ raise MacoError(f"UID {uid} does not exist in {folder}.")
290
+ flags, message = records[uid]
291
+ return message, _headers(message, folder, uid, validity, flags)
292
+
293
+
294
+ def _attachments(message, path=""):
295
+ if (message.get_filename() or message.get_content_disposition() == "attachment"
296
+ or message.get_content_maintype() not in ("multipart", "text")):
297
+ yield path or "1", message
298
+ elif message.is_multipart():
299
+ for number, child in enumerate(message.iter_parts(), 1):
300
+ yield from _attachments(child, f"{path}.{number}" if path else str(number))
301
+
302
+
303
+ def _payload(part):
304
+ data = part.get_payload(decode=True)
305
+ if data is not None:
306
+ return data
307
+ if part.get_content_type() == "message/rfc822" and part.is_multipart():
308
+ return part.get_payload(0).as_bytes(policy=policy.SMTP)
309
+ return part.as_bytes(policy=policy.SMTP)
310
+
311
+
312
+ def read(account, folder, uid, uidvalidity=None):
313
+ message, result = _message(account, folder, uid, uidvalidity)
314
+ return message_details(message, result)
315
+
316
+
317
+ def read_batch(account, folder, uids, uidvalidity=None):
318
+ """Yield each requested UID and its message details or per-message error."""
319
+ uids = [_number(uid, "UID") for uid in uids]
320
+ with connect_imap(account) as client:
321
+ validity = _select(client, folder, uidvalidity)
322
+ for uid in uids:
323
+ try:
324
+ message, result = _selected_message(client, folder, uid, validity)
325
+ details = message_details(message, result)
326
+ except MacoError as exc:
327
+ yield uid, None, exc
328
+ else:
329
+ yield uid, details, None
330
+
331
+
332
+ def message_details(message, result, *, include_attachments=True):
333
+ try:
334
+ return _message_details(message, result, include_attachments)
335
+ except (MessageError, ValueError, LookupError, RecursionError):
336
+ raise MacoError("Could not decode the message body or attachment metadata.") from None
337
+
338
+
339
+ def _message_details(message, result, include_attachments):
340
+ parts = list(_attachments(message))
341
+ body = message.get_body(preferencelist=("plain", "html"))
342
+ if body is not None and any(part is body for _, part in parts):
343
+ body = None
344
+ result["body_type"] = body.get_content_type() if body is not None else None
345
+ result["body"] = ""
346
+ if body is not None:
347
+ try:
348
+ result["body"] = body.get_content()
349
+ except (LookupError, UnicodeError):
350
+ result["body"] = _payload(body).decode("utf-8", "replace")
351
+ if include_attachments:
352
+ result["attachments"] = [
353
+ {"part": path, "filename": part.get_filename(), "content_type": part.get_content_type(),
354
+ "size": len(_payload(part))}
355
+ for path, part in parts
356
+ ]
357
+ return result
358
+
359
+
360
+ def attachment(account, folder, uid, part, output, uidvalidity=None):
361
+ message, result = _message(account, folder, uid, uidvalidity)
362
+ identity = {"folder": folder, "uid": result["uid"], "uidvalidity": result["uidvalidity"]}
363
+ return save_attachment(message, identity, part, output)
364
+
365
+
366
+ def save_attachment(message, identity, part, output):
367
+ attachments = dict(_attachments(message))
368
+ if str(part) not in attachments:
369
+ raise MacoError(f"No attachment with part ID {part}.")
370
+ data = _payload(attachments[str(part)])
371
+ path = Path(output).expanduser()
372
+ try:
373
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0), 0o600)
374
+ except FileExistsError as exc:
375
+ raise MacoError(f"Output file already exists: {path}") from exc
376
+ try:
377
+ with os.fdopen(descriptor, "wb") as stream:
378
+ stream.write(data)
379
+ except OSError:
380
+ path.unlink(missing_ok=True)
381
+ raise
382
+ return {**identity, "part": str(part), "output": str(path.resolve()), "size": len(data)}
383
+
384
+
385
+ _ACTIONS = {
386
+ "read": ("+FLAGS", r"(\Seen)"),
387
+ "unread": ("-FLAGS", r"(\Seen)"),
388
+ "flag": ("+FLAGS", r"(\Flagged)"),
389
+ "unflag": ("-FLAGS", r"(\Flagged)"),
390
+ }
391
+
392
+
393
+ def _has_uid(rows, uid):
394
+ return any(isinstance(row, bytes) and _response_uid(row) == uid for row in rows)
395
+
396
+
397
+ def _flag_state(rows, uid):
398
+ for row in rows:
399
+ if isinstance(row, bytes) and _response_uid(row) == uid:
400
+ match = _FLAGS.search(row)
401
+ if match:
402
+ return {flag.upper() for flag in match[1].split()}
403
+ return None
404
+
405
+
406
+ def action(account, folder, uid, operation, target=None, uidvalidity=None):
407
+ uid = _number(uid, "UID")
408
+ if operation not in (*_ACTIONS, "move", "archive", "trash"):
409
+ raise MacoError(f"Unknown IMAP action: {operation}")
410
+ if target is not None and operation in _ACTIONS:
411
+ raise MacoError("A target folder is only used for move, archive and trash.")
412
+ with connect_imap(account) as client:
413
+ validity = _select(client, folder, uidvalidity, readonly=False)
414
+ result = {"folder": folder, "uid": uid, "uidvalidity": validity, "action": operation}
415
+ if operation in _ACTIONS:
416
+ modifier, flag = _ACTIONS[operation]
417
+ rows = imap_command("UID STORE", client.uid, "STORE", str(uid), modifier, flag)
418
+ flags = _flag_state(rows, uid)
419
+ if flags is None:
420
+ # Some servers omit the FETCH response for an already-set flag.
421
+ rows = imap_command("UID FETCH", client.uid, "FETCH", str(uid), "(UID FLAGS)")
422
+ flags = _flag_state(rows, uid)
423
+ wanted = flag[1:-1].upper().encode("ascii")
424
+ if flags is None or (wanted in flags) != modifier.startswith("+"):
425
+ raise MacoError("Server did not confirm the UID flag update. List the folder again.")
426
+ return result
427
+
428
+ if "MOVE" not in client.capabilities and "IMAP4REV2" not in client.capabilities:
429
+ raise MacoError("The IMAP server does not support MOVE.")
430
+ if target is None and operation != "move":
431
+ target = special_folder(client, {"archive": r"\Archive", "trash": r"\Trash"}[operation])
432
+ destination = mailbox_arg(target)
433
+ if target == folder or target.upper() == folder.upper() == "INBOX":
434
+ raise MacoError("The destination is the selected folder.")
435
+ exists = imap_command("UID FETCH", client.uid, "FETCH", str(uid), "(UID)")
436
+ if not _has_uid(exists, uid):
437
+ raise MacoError(f"UID {uid} does not exist in {folder}.")
438
+ imap_command("UID MOVE", client.uid, "MOVE", str(uid), destination)
439
+ result["target"] = target
440
+ return result
maco_cli/mail_query.py ADDED
@@ -0,0 +1,46 @@
1
+ """Literal search alternatives and date values shared by the mailbox backends."""
2
+
3
+ import re
4
+ from datetime import date
5
+
6
+ from .errors import MacoError
7
+
8
+
9
+ _QUOTED = r'"(?:\\.|[^"\\])*"'
10
+ _QUERY_PART = re.compile(_QUOTED + r"|(?<!\S)OR(?!\S)")
11
+
12
+
13
+ def parse_date(value):
14
+ day = date.fromisoformat(value)
15
+ if day.isoformat() != value:
16
+ raise ValueError("Expected YYYY-MM-DD.")
17
+ return day
18
+
19
+
20
+ def utc_seconds(day):
21
+ return (day - date(1970, 1, 1)).days * 86400
22
+
23
+
24
+ def midnight_utc(day):
25
+ return f"{day.isoformat()}T00:00:00Z"
26
+
27
+
28
+ def phrases(text):
29
+ """Split uppercase OR outside quoted text. Each part is a literal phrase."""
30
+ if text is None:
31
+ return ()
32
+ parts = []
33
+ start = 0
34
+ for token in _QUERY_PART.finditer(text):
35
+ if token[0] == "OR":
36
+ parts.append(text[start:token.start()].strip())
37
+ start = token.end()
38
+ parts.append(text[start:].strip())
39
+ result = []
40
+ for part in parts:
41
+ if re.fullmatch(_QUOTED, part):
42
+ part = re.sub(r'\\(["\\])', r'\1', part[1:-1])
43
+ if not part.strip():
44
+ raise MacoError("Use a non-blank search phrase on each side of OR.")
45
+ result.append(part)
46
+ return tuple(result)