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/__init__.py +3 -0
- maco_cli/__main__.py +4 -0
- maco_cli/accounts.py +366 -0
- maco_cli/cli.py +491 -0
- maco_cli/device_login.py +197 -0
- maco_cli/device_store.py +69 -0
- maco_cli/errors.py +10 -0
- maco_cli/gmail_api.py +210 -0
- maco_cli/graph_api.py +254 -0
- maco_cli/helper_client.py +204 -0
- maco_cli/incoming.py +440 -0
- maco_cli/mail_query.py +46 -0
- maco_cli/mail_socket.py +436 -0
- maco_cli/message_text.py +53 -0
- maco_cli/oauth.py +139 -0
- maco_cli/outgoing.py +181 -0
- maco_cli/provider.py +272 -0
- maco_cli/strict_search.py +81 -0
- maco_cli/transport.py +303 -0
- maco_cli-0.4.5.dist-info/METADATA +66 -0
- maco_cli-0.4.5.dist-info/RECORD +24 -0
- maco_cli-0.4.5.dist-info/WHEEL +5 -0
- maco_cli-0.4.5.dist-info/entry_points.txt +3 -0
- maco_cli-0.4.5.dist-info/top_level.txt +1 -0
maco_cli/cli.py
ADDED
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
"""Command-line interface. Successful mail operations always produce one JSON object."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import imaplib
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import smtplib
|
|
10
|
+
import sys
|
|
11
|
+
from contextlib import contextmanager, nullcontext
|
|
12
|
+
from email.errors import MessageError
|
|
13
|
+
|
|
14
|
+
from . import __version__, accounts, incoming, mail_socket, outgoing, transport
|
|
15
|
+
from .errors import MacoError
|
|
16
|
+
from .mail_query import parse_date
|
|
17
|
+
from .message_text import body_text
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
OPERATION_ERRORS = (MacoError, OSError, UnicodeError, imaplib.IMAP4.error, smtplib.SMTPException, MessageError)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class UsageError(MacoError):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Parser(argparse.ArgumentParser):
|
|
28
|
+
def error(self, message):
|
|
29
|
+
raise UsageError(f"{self.prog}: {message}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def uid_number(value):
|
|
33
|
+
try:
|
|
34
|
+
number = int(value)
|
|
35
|
+
except ValueError:
|
|
36
|
+
number = 0
|
|
37
|
+
if not 1 <= number <= 4294967295:
|
|
38
|
+
raise argparse.ArgumentTypeError("expected a positive 32-bit IMAP identifier")
|
|
39
|
+
return number
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def date_argument(value):
|
|
43
|
+
try:
|
|
44
|
+
return parse_date(value)
|
|
45
|
+
except ValueError:
|
|
46
|
+
raise argparse.ArgumentTypeError("expected a date in YYYY-MM-DD format") from None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def add_folder_reference(parser):
|
|
50
|
+
parser.add_argument("--folder", default="INBOX", help="source folder (default INBOX)")
|
|
51
|
+
parser.add_argument("--uidvalidity", type=uid_number, help="IMAP only: folder generation from emails/search")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def add_identity(parser):
|
|
55
|
+
parser.add_argument("uid", metavar="ID", help="message ID or IMAP UID from emails/search")
|
|
56
|
+
add_folder_reference(parser)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def add_composition(parser, reply=False):
|
|
60
|
+
if not reply:
|
|
61
|
+
parser.add_argument("--to", action="append", default=[], help="recipient, repeatable")
|
|
62
|
+
parser.add_argument("--subject", default="")
|
|
63
|
+
parser.add_argument("--cc", action="append", default=[])
|
|
64
|
+
parser.add_argument("--bcc", action="append", default=[])
|
|
65
|
+
body = parser.add_mutually_exclusive_group()
|
|
66
|
+
body.add_argument("--body", help="plain-text message body")
|
|
67
|
+
body.add_argument("--body-file", help="UTF-8 text file or - for standard input")
|
|
68
|
+
parser.add_argument("--attach", action="append", default=[], metavar="FILE")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def build_parser():
|
|
72
|
+
common = Parser(add_help=False)
|
|
73
|
+
# SUPPRESS preserves options supplied before the subcommand.
|
|
74
|
+
common.add_argument("--account", default=argparse.SUPPRESS, metavar="NAME",
|
|
75
|
+
help="profile (default MACO_ACCOUNT or the only profile)")
|
|
76
|
+
common.add_argument("--json", action="store_true", default=argparse.SUPPRESS,
|
|
77
|
+
help="emit JSON (the default)")
|
|
78
|
+
common.add_argument("--debug", action="store_true", default=argparse.SUPPRESS,
|
|
79
|
+
help="write sanitized network and mail command diagnostics to stderr")
|
|
80
|
+
root = Parser(prog="maco", parents=[common],
|
|
81
|
+
description="Operate a mailbox over IMAP/SMTP, Gmail API or Microsoft Graph. Results are JSON.")
|
|
82
|
+
root.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
83
|
+
commands = root.add_subparsers(dest="command", required=True)
|
|
84
|
+
commands.add_parser("accounts", parents=[common], help="list configured profiles")
|
|
85
|
+
proxy = commands.add_parser("proxy", parents=[common], help="manage the local IMAP/SMTP proxy setting")
|
|
86
|
+
proxy_sub = proxy.add_subparsers(dest="operation", required=True)
|
|
87
|
+
set_proxy = proxy_sub.add_parser("set", parents=[common], help="save a proxy for future terminals")
|
|
88
|
+
set_proxy.add_argument("url", nargs="?", help="proxy URL or direct (omitted: use the current environment)")
|
|
89
|
+
proxy_sub.add_parser("show", parents=[common], help="check the saved proxy setting")
|
|
90
|
+
proxy_sub.add_parser("clear", parents=[common], help="remove the saved proxy setting")
|
|
91
|
+
account = commands.add_parser("account", parents=[common], help="configure a profile")
|
|
92
|
+
account_sub = account.add_subparsers(dest="operation", required=True)
|
|
93
|
+
login = account_sub.add_parser("login", parents=[common], help="link mailboxes through browser approval")
|
|
94
|
+
login.add_argument("name", nargs="?", help="profile name or prefix (defaults to the mailbox address)")
|
|
95
|
+
login.add_argument("--helper-url", help="HTTPS Helper base (default https://macomail.app/cli)")
|
|
96
|
+
stages = login.add_mutually_exclusive_group()
|
|
97
|
+
stages.add_argument("--start", action="store_true", help="print a login link as JSON and exit")
|
|
98
|
+
stages.add_argument("--finish", nargs="?", const=True, metavar="REQUEST_ID",
|
|
99
|
+
help="finish a request (default: most recent pending request)")
|
|
100
|
+
connect = account_sub.add_parser("connect", parents=[common], help="connect a Maco Mail Helper mailbox")
|
|
101
|
+
connect.add_argument("name")
|
|
102
|
+
connect.add_argument("--helper-url", required=True, help="HTTPS base URL of Maco Mail Helper")
|
|
103
|
+
connect.add_argument("--agent-token-env", default="MACO_AGENT_TOKEN",
|
|
104
|
+
help="name of the environment variable with the Maco Agent grant")
|
|
105
|
+
add = account_sub.add_parser("add", parents=[common], help="create a locally authenticated profile")
|
|
106
|
+
add.add_argument("name")
|
|
107
|
+
add.add_argument("--email", required=True, help="sender's mailbox address")
|
|
108
|
+
add.add_argument("--username", help="protocol login if different from the email address")
|
|
109
|
+
add.add_argument("--auth", choices=("password", "xoauth2", "microsoft"), default="password")
|
|
110
|
+
add.add_argument("--secret-env", help="name of the environment variable containing a credential")
|
|
111
|
+
add.add_argument("--client-id", help="Microsoft Entra public client application ID")
|
|
112
|
+
add.add_argument("--tenant", default="common", help="Microsoft tenant (default common)")
|
|
113
|
+
add.add_argument("--imap-host", help="IMAP server (Microsoft 365 has a preset)")
|
|
114
|
+
add.add_argument("--imap-port", type=int, default=993)
|
|
115
|
+
add.add_argument("--smtp-host", help="SMTP server (Microsoft 365 has a preset)")
|
|
116
|
+
add.add_argument("--smtp-security", choices=("tls", "starttls"),
|
|
117
|
+
help="implicit TLS (default) or STARTTLS (Microsoft default)")
|
|
118
|
+
add.add_argument("--smtp-port", type=int, help="defaults to 465 for TLS or 587 for STARTTLS")
|
|
119
|
+
|
|
120
|
+
auth = commands.add_parser("auth", parents=[common], help="sign in or check protocol access")
|
|
121
|
+
auth_sub = auth.add_subparsers(dest="operation", required=True)
|
|
122
|
+
auth_sub.add_parser("login", parents=[common], help="sign in with a Microsoft device code")
|
|
123
|
+
auth_sub.add_parser("logout", parents=[common], help="remove the locally cached Microsoft tokens")
|
|
124
|
+
check = auth_sub.add_parser("check", parents=[common], help="test authentication")
|
|
125
|
+
check.add_argument("--protocol", choices=("imap", "smtp", "both", "gmail", "outlook"), default=None)
|
|
126
|
+
|
|
127
|
+
commands.add_parser("folders", parents=[common], help="list folders or Gmail labels")
|
|
128
|
+
for name, description in (("emails", "list messages"), ("search", "search message headers and text")):
|
|
129
|
+
listing = commands.add_parser(name, parents=[common], help=description)
|
|
130
|
+
if name == "search":
|
|
131
|
+
listing.add_argument("query", nargs="?", help="literal phrase or alternative phrases joined by uppercase OR")
|
|
132
|
+
matching = listing.add_mutually_exclusive_group()
|
|
133
|
+
matching.add_argument("--strict", action="store_true",
|
|
134
|
+
help="verify literal matches within the first 100 provider candidates")
|
|
135
|
+
matching.add_argument("--native", action="store_true", help="use the provider's matches directly")
|
|
136
|
+
listing.add_argument("--match", choices=("any", "subject", "from", "body"),
|
|
137
|
+
help="where to verify a literal query (default any)")
|
|
138
|
+
listing.add_argument("--folder", default="INBOX", help="folder name or provider ID (default INBOX)")
|
|
139
|
+
listing.add_argument("--limit", type=int, default=20)
|
|
140
|
+
listing.add_argument("--offset", type=int, default=0)
|
|
141
|
+
listing.add_argument("--unread", action="store_true")
|
|
142
|
+
listing.add_argument("--from", dest="sender", metavar="SENDER",
|
|
143
|
+
help="sender address, name or server-indexed text")
|
|
144
|
+
listing.add_argument("--subject", help="subject text filter")
|
|
145
|
+
listing.add_argument("--after", type=date_argument, metavar="YYYY-MM-DD", help="first day of the date range")
|
|
146
|
+
listing.add_argument("--before", type=date_argument, metavar="YYYY-MM-DD", help="exclusive end of the date range")
|
|
147
|
+
read = commands.add_parser("read", parents=[common], help="read messages and list their attachments")
|
|
148
|
+
read.add_argument("message_ids", nargs="*", metavar="ID", help="message IDs or IMAP UIDs from emails/search")
|
|
149
|
+
read.add_argument("--ids-file", metavar="FILE", help="UTF-8 file with one ID per line, or - for standard input")
|
|
150
|
+
read.add_argument("--text", action="store_true", help="return the message body as plain text")
|
|
151
|
+
add_folder_reference(read)
|
|
152
|
+
attachment = commands.add_parser("attachment", parents=[common], help="download an attachment")
|
|
153
|
+
add_identity(attachment)
|
|
154
|
+
attachment.add_argument("--part", required=True, help="part ID from read")
|
|
155
|
+
attachment.add_argument("--output", required=True, metavar="PATH", help="path for a new file")
|
|
156
|
+
action = commands.add_parser("action", parents=[common], help="mark or move a message")
|
|
157
|
+
action.add_argument("operation", choices=("read", "unread", "flag", "unflag", "move", "archive", "trash"))
|
|
158
|
+
add_identity(action)
|
|
159
|
+
action.add_argument("--target", help="destination folder for move, archive or trash")
|
|
160
|
+
for name, description in (("draft", "save a new draft"), ("send", "submit a new message"),
|
|
161
|
+
("reply", "draft a reply to one message, or send with --send")):
|
|
162
|
+
compose = commands.add_parser(name, parents=[common], help=description)
|
|
163
|
+
if name == "reply":
|
|
164
|
+
add_identity(compose)
|
|
165
|
+
compose.add_argument("--send", action="store_true", help="submit the reply")
|
|
166
|
+
if name != "send":
|
|
167
|
+
compose.add_argument("--draft-folder", help="destination if server does not advertise a Drafts folder")
|
|
168
|
+
add_composition(compose, reply=name == "reply")
|
|
169
|
+
return root
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def create_profile(args):
|
|
173
|
+
microsoft = args.auth == "microsoft"
|
|
174
|
+
if not microsoft and not (args.imap_host and args.smtp_host):
|
|
175
|
+
raise UsageError("--imap-host and --smtp-host are required for this authentication method")
|
|
176
|
+
security = args.smtp_security or ("starttls" if microsoft else "tls")
|
|
177
|
+
profile = accounts.Account(
|
|
178
|
+
name=args.name, email=args.email, username=args.username,
|
|
179
|
+
imap_host=args.imap_host or "outlook.office365.com", imap_port=args.imap_port,
|
|
180
|
+
smtp_host=args.smtp_host or "smtp.office365.com",
|
|
181
|
+
smtp_port=args.smtp_port if args.smtp_port is not None else (587 if security == "starttls" else 465),
|
|
182
|
+
smtp_security=security, auth=args.auth, secret_env=args.secret_env,
|
|
183
|
+
client_id=args.client_id, tenant=args.tenant)
|
|
184
|
+
accounts.add_account(profile)
|
|
185
|
+
return {"account": accounts.public_account(profile)}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def authenticate(args, profile):
|
|
189
|
+
if args.operation == "login":
|
|
190
|
+
accounts.login(profile, notify=lambda message: print(message, file=sys.stderr, flush=True))
|
|
191
|
+
return {"status": "authenticated"}
|
|
192
|
+
if args.operation == "logout":
|
|
193
|
+
accounts.logout(profile)
|
|
194
|
+
return {"status": "logged_out"}
|
|
195
|
+
if args.protocol in ("gmail", "outlook"):
|
|
196
|
+
raise UsageError("Choose imap, smtp or both for this account.")
|
|
197
|
+
checked = []
|
|
198
|
+
protocols = profile.protocols or ("imap", "smtp")
|
|
199
|
+
if args.protocol is not None:
|
|
200
|
+
protocols = ("imap", "smtp") if args.protocol == "both" else (args.protocol,)
|
|
201
|
+
with mail_socket.capture_route() as route:
|
|
202
|
+
for protocol in protocols:
|
|
203
|
+
transport.check_protocol(profile, protocol)
|
|
204
|
+
checked.append(protocol)
|
|
205
|
+
return {"status": "authenticated", "protocols": checked, **route}
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def compose(args, profile, provider=None):
|
|
209
|
+
if args.body_file == "-":
|
|
210
|
+
# Read bytes regardless of the machine's default console encoding.
|
|
211
|
+
body = sys.stdin.buffer.read().decode("utf-8-sig")
|
|
212
|
+
elif args.body_file is not None:
|
|
213
|
+
body = Path(args.body_file).read_text(encoding="utf-8-sig")
|
|
214
|
+
else:
|
|
215
|
+
body = args.body or ""
|
|
216
|
+
message = dict(cc=args.cc, bcc=args.bcc, attachments=args.attach, body=body)
|
|
217
|
+
if args.command == "reply":
|
|
218
|
+
if args.send and args.draft_folder is not None:
|
|
219
|
+
raise UsageError("--draft-folder applies only when saving a draft")
|
|
220
|
+
if provider is None:
|
|
221
|
+
original = incoming.read(profile, args.folder, args.uid, args.uidvalidity)
|
|
222
|
+
else:
|
|
223
|
+
original = provider.headers(args.uid)
|
|
224
|
+
recipient = original["reply_to"] or original["from"]
|
|
225
|
+
if not recipient:
|
|
226
|
+
raise MacoError("The original message has no reply address.")
|
|
227
|
+
subject = original["subject"]
|
|
228
|
+
if not subject.lower().lstrip().startswith("re:"):
|
|
229
|
+
subject = f"Re: {subject}"
|
|
230
|
+
message.update(to=[recipient], subject=subject, in_reply_to=original["message_id"] or None,
|
|
231
|
+
references=original["references"])
|
|
232
|
+
else:
|
|
233
|
+
message.update(to=args.to, subject=args.subject)
|
|
234
|
+
sending = args.command == "send" or (args.command == "reply" and args.send)
|
|
235
|
+
if provider is not None:
|
|
236
|
+
if getattr(args, "draft_folder", None):
|
|
237
|
+
raise UsageError("API-backed drafts use the provider's Drafts folder.")
|
|
238
|
+
return provider.submit_message(profile, message, draft=not sending,
|
|
239
|
+
reply_id=args.uid if args.command == "reply" else None)
|
|
240
|
+
if sending:
|
|
241
|
+
return outgoing.send(profile, **message)
|
|
242
|
+
return outgoing.save_draft(profile, folder=args.draft_folder, **message)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _read_ids(args, provider):
|
|
246
|
+
ids = args.message_ids.copy()
|
|
247
|
+
if args.ids_file is not None:
|
|
248
|
+
if args.ids_file == "-":
|
|
249
|
+
data = sys.stdin.buffer.read().decode("utf-8-sig")
|
|
250
|
+
else:
|
|
251
|
+
data = Path(args.ids_file).read_text(encoding="utf-8-sig")
|
|
252
|
+
ids.extend(line.strip() for line in data.splitlines() if line.strip())
|
|
253
|
+
if not ids:
|
|
254
|
+
raise UsageError("read requires a message ID or --ids-file containing IDs.")
|
|
255
|
+
if not provider:
|
|
256
|
+
try:
|
|
257
|
+
ids = [uid_number(value) for value in ids]
|
|
258
|
+
except argparse.ArgumentTypeError:
|
|
259
|
+
raise UsageError("Expected a positive 32-bit IMAP UID.") from None
|
|
260
|
+
return ids
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _provider_reads(provider, ids):
|
|
264
|
+
for message_id in ids:
|
|
265
|
+
try:
|
|
266
|
+
result = provider.read(message_id)
|
|
267
|
+
except OPERATION_ERRORS as exc:
|
|
268
|
+
yield message_id, None, exc
|
|
269
|
+
else:
|
|
270
|
+
yield message_id, result, None
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _read_text(result, text):
|
|
274
|
+
if text and result.get("body_type") == "text/html":
|
|
275
|
+
result["body"] = body_text(result["body"], result["body_type"])
|
|
276
|
+
result["body_type"] = "text/plain"
|
|
277
|
+
return _message_reference(result)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def read_messages(args, profile, provider):
|
|
281
|
+
ids = _read_ids(args, provider)
|
|
282
|
+
if len(ids) == 1 and args.ids_file is None:
|
|
283
|
+
message_id = ids[0]
|
|
284
|
+
result = (provider.read(message_id) if provider else
|
|
285
|
+
incoming.read(profile, args.folder, message_id, args.uidvalidity))
|
|
286
|
+
return _read_text(result, args.text)
|
|
287
|
+
if provider:
|
|
288
|
+
provider.acquire()
|
|
289
|
+
reads = _provider_reads(provider, ids)
|
|
290
|
+
else:
|
|
291
|
+
reads = incoming.read_batch(profile, args.folder, ids, args.uidvalidity)
|
|
292
|
+
response = {"messages": [], "errors": []}
|
|
293
|
+
try:
|
|
294
|
+
for message_id, result, error in reads:
|
|
295
|
+
if error is None:
|
|
296
|
+
try:
|
|
297
|
+
response["messages"].append(_read_text(result, args.text))
|
|
298
|
+
except MacoError as exc:
|
|
299
|
+
error = exc
|
|
300
|
+
if error is not None:
|
|
301
|
+
response["errors"].append({"id": message_id, "error": error_payload(error)})
|
|
302
|
+
except OPERATION_ERRORS as exc:
|
|
303
|
+
consumed = len(response["messages"]) + len(response["errors"])
|
|
304
|
+
for message_id in ids[consumed:]:
|
|
305
|
+
response["errors"].append({"id": message_id, "error": error_payload(exc)})
|
|
306
|
+
return response
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _message_reference(result):
|
|
310
|
+
if "uid" in result:
|
|
311
|
+
result.setdefault("id", str(result["uid"]))
|
|
312
|
+
return result
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _list_messages(args, profile, provider):
|
|
316
|
+
query = getattr(args, "query", None)
|
|
317
|
+
criteria = (query, args.sender, args.subject, args.unread, args.after, args.before)
|
|
318
|
+
if args.command == "search" and not any(criteria):
|
|
319
|
+
raise UsageError("search requires a query or a filter")
|
|
320
|
+
if not 1 <= args.limit <= 200 or args.offset < 0:
|
|
321
|
+
raise UsageError("--limit must be from 1 to 200 and --offset must be non-negative")
|
|
322
|
+
if args.after and args.before and args.after >= args.before:
|
|
323
|
+
raise UsageError("--after must be earlier than --before")
|
|
324
|
+
filters = dict(limit=args.limit, offset=args.offset, unread=args.unread, sender=args.sender,
|
|
325
|
+
subject=args.subject, text=query)
|
|
326
|
+
if args.after:
|
|
327
|
+
filters["after"] = args.after
|
|
328
|
+
if args.before:
|
|
329
|
+
filters["before"] = args.before
|
|
330
|
+
|
|
331
|
+
strict = getattr(args, "strict", False)
|
|
332
|
+
match = getattr(args, "match", None)
|
|
333
|
+
verify_gmail = (args.command == "search" and profile.mailbox_auth == "gmail" and not args.native
|
|
334
|
+
and any((query, args.sender, args.subject)))
|
|
335
|
+
if match and (not (strict or verify_gmail) or not query):
|
|
336
|
+
raise UsageError("--match requires a search query with literal verification")
|
|
337
|
+
with provider.http.query_budget() if provider else nullcontext():
|
|
338
|
+
if strict or verify_gmail:
|
|
339
|
+
from . import strict_search
|
|
340
|
+
result = strict_search.search(profile, provider, args.folder, scope=match or "any",
|
|
341
|
+
fill_page_only=verify_gmail and not strict, **filters)
|
|
342
|
+
else:
|
|
343
|
+
result = (provider.api.emails(args.folder, **filters) if provider else
|
|
344
|
+
incoming.emails(profile, args.folder, **filters))
|
|
345
|
+
rows = result.get("messages", result.get("emails", []))
|
|
346
|
+
for row in rows:
|
|
347
|
+
_message_reference(row)
|
|
348
|
+
row.setdefault("folder", args.folder)
|
|
349
|
+
result["messages"] = rows
|
|
350
|
+
return result
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def run(args):
|
|
354
|
+
if args.command == "accounts":
|
|
355
|
+
return {"accounts": [accounts.public_account(p) for p in accounts.list_accounts()]}
|
|
356
|
+
if args.command == "proxy":
|
|
357
|
+
if args.operation == "set":
|
|
358
|
+
return mail_socket.save_proxy(args.url)
|
|
359
|
+
if args.operation == "show":
|
|
360
|
+
return mail_socket.show_proxy()
|
|
361
|
+
return mail_socket.clear_proxy()
|
|
362
|
+
if args.command == "account":
|
|
363
|
+
if args.operation == "login":
|
|
364
|
+
from . import device_login
|
|
365
|
+
if args.finish is not None:
|
|
366
|
+
if args.name is not None or args.helper_url is not None:
|
|
367
|
+
raise UsageError("--finish uses the name and Helper from the original login request.")
|
|
368
|
+
return device_login.finish(None if args.finish is True else args.finish)
|
|
369
|
+
origin = args.helper_url if args.helper_url is not None else device_login.DEFAULT_HELPER
|
|
370
|
+
if args.start:
|
|
371
|
+
return device_login.start(args.name, origin)
|
|
372
|
+
return device_login.login(args.name, origin, lambda message: print(message, file=sys.stderr, flush=True))
|
|
373
|
+
if args.operation == "connect":
|
|
374
|
+
from .helper_client import connect_account
|
|
375
|
+
with mail_socket.capture_route() as route:
|
|
376
|
+
profile = connect_account(args.name, args.helper_url, args.agent_token_env)
|
|
377
|
+
accounts.add_account(profile)
|
|
378
|
+
return {"account": accounts.public_account(profile), **route}
|
|
379
|
+
return create_profile(args)
|
|
380
|
+
name = getattr(args, "account", None) or os.environ.get("MACO_ACCOUNT") or None
|
|
381
|
+
profile = accounts.get_account(name)
|
|
382
|
+
provider = None
|
|
383
|
+
if profile.mailbox_auth in ("gmail", "outlook"):
|
|
384
|
+
from .provider import ProviderMailbox
|
|
385
|
+
provider = ProviderMailbox(profile)
|
|
386
|
+
if getattr(args, "uidvalidity", None) is not None:
|
|
387
|
+
raise UsageError("--uidvalidity applies to IMAP accounts.")
|
|
388
|
+
elif hasattr(args, "uid"):
|
|
389
|
+
try:
|
|
390
|
+
args.uid = uid_number(args.uid)
|
|
391
|
+
except (ValueError, argparse.ArgumentTypeError):
|
|
392
|
+
raise UsageError("Expected a positive 32-bit IMAP UID.") from None
|
|
393
|
+
if args.command == "auth":
|
|
394
|
+
if provider:
|
|
395
|
+
if args.operation != "check" or args.protocol not in (None, profile.mailbox_auth):
|
|
396
|
+
raise UsageError("Use auth check for a connected provider API account.")
|
|
397
|
+
result = provider.api.check()
|
|
398
|
+
else:
|
|
399
|
+
result = authenticate(args, profile)
|
|
400
|
+
elif args.command == "folders":
|
|
401
|
+
result = provider.api.folders() if provider else incoming.folders(profile)
|
|
402
|
+
for folder in result["folders"]:
|
|
403
|
+
folder.setdefault("id", folder["name"])
|
|
404
|
+
elif args.command in ("emails", "search"):
|
|
405
|
+
result = _list_messages(args, profile, provider)
|
|
406
|
+
elif args.command == "read":
|
|
407
|
+
result = read_messages(args, profile, provider)
|
|
408
|
+
elif args.command == "attachment":
|
|
409
|
+
result = (provider.attachment(args.uid, args.part, args.output) if provider else
|
|
410
|
+
incoming.attachment(profile, args.folder, args.uid, args.part, args.output, args.uidvalidity))
|
|
411
|
+
elif args.command == "action":
|
|
412
|
+
if args.operation == "move" and not args.target:
|
|
413
|
+
raise UsageError("action move requires --target")
|
|
414
|
+
if args.target is not None and args.operation not in ("move", "archive", "trash"):
|
|
415
|
+
raise UsageError("--target applies only to move, archive and trash")
|
|
416
|
+
result = (provider.api.action(args.folder, args.uid, args.operation, args.target) if provider else
|
|
417
|
+
incoming.action(profile, args.folder, args.uid, args.operation, args.target, args.uidvalidity))
|
|
418
|
+
else:
|
|
419
|
+
result = compose(args, profile, provider)
|
|
420
|
+
return {"account": profile.name, **_message_reference(result)}
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def emit(stream, payload):
|
|
424
|
+
# Preserve legible non-ASCII text wherever stdout/stderr support UTF-8.
|
|
425
|
+
is_utf8 = (stream.encoding or "").lower().replace("-", "") == "utf8"
|
|
426
|
+
print(json.dumps(payload, ensure_ascii=not is_utf8), file=stream)
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def error_payload(exc):
|
|
430
|
+
if isinstance(exc, MacoError):
|
|
431
|
+
message = str(exc)
|
|
432
|
+
elif isinstance(exc, UnicodeError):
|
|
433
|
+
message = "Invalid text encoding. Supply UTF-8 input and check the mailbox data."
|
|
434
|
+
elif isinstance(exc, MessageError):
|
|
435
|
+
message = "Could not decode the mail server's message."
|
|
436
|
+
elif isinstance(exc, (smtplib.SMTPException, imaplib.IMAP4.error)):
|
|
437
|
+
message = "Mail server rejected the operation or closed the connection."
|
|
438
|
+
else:
|
|
439
|
+
message = exc.strerror or "A network or filesystem operation failed."
|
|
440
|
+
if exc.filename:
|
|
441
|
+
message = f"{message}: {exc.filename}"
|
|
442
|
+
error = {"message": message}
|
|
443
|
+
if hasattr(exc, "details"):
|
|
444
|
+
error["details"] = exc.details
|
|
445
|
+
return error
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
@contextmanager
|
|
449
|
+
def _debug_output(enabled):
|
|
450
|
+
if not enabled:
|
|
451
|
+
yield
|
|
452
|
+
return
|
|
453
|
+
logger = logging.getLogger("maco_cli")
|
|
454
|
+
handler = logging.StreamHandler(sys.stderr)
|
|
455
|
+
handler.setFormatter(logging.Formatter("maco debug: %(message)s"))
|
|
456
|
+
level, propagate = logger.level, logger.propagate
|
|
457
|
+
logger.setLevel(logging.DEBUG)
|
|
458
|
+
logger.propagate = False
|
|
459
|
+
logger.addHandler(handler)
|
|
460
|
+
try:
|
|
461
|
+
yield
|
|
462
|
+
finally:
|
|
463
|
+
logger.removeHandler(handler)
|
|
464
|
+
logger.setLevel(level)
|
|
465
|
+
logger.propagate = propagate
|
|
466
|
+
handler.close()
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def main(argv=None):
|
|
470
|
+
args = None
|
|
471
|
+
try:
|
|
472
|
+
args = build_parser().parse_args(argv)
|
|
473
|
+
with _debug_output(getattr(args, "debug", False)):
|
|
474
|
+
result = run(args)
|
|
475
|
+
failed_batch = args.command == "read" and bool(result.get("errors"))
|
|
476
|
+
if failed_batch:
|
|
477
|
+
result["error"] = {"message": "One or more messages could not be read."}
|
|
478
|
+
emit(sys.stdout, result)
|
|
479
|
+
return int(failed_batch)
|
|
480
|
+
except OPERATION_ERRORS as exc:
|
|
481
|
+
emit(sys.stderr, {"error": error_payload(exc)})
|
|
482
|
+
return 2 if isinstance(exc, UsageError) else 1
|
|
483
|
+
except KeyboardInterrupt:
|
|
484
|
+
emit(sys.stderr, {"error": {"message": "Interrupted."}})
|
|
485
|
+
return 130
|
|
486
|
+
except Exception as exc:
|
|
487
|
+
# Keep the CLI's error contract without exposing process state or mail data in a traceback.
|
|
488
|
+
if getattr(args, "debug", False):
|
|
489
|
+
print(f"maco debug: unexpected {type(exc).__name__}", file=sys.stderr)
|
|
490
|
+
emit(sys.stderr, {"error": {"message": "An unexpected error prevented the command from completing."}})
|
|
491
|
+
return 1
|