lit-reader 1.2.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.
lit_reader/mail.py ADDED
@@ -0,0 +1,240 @@
1
+ """Email a reading copy to yourself (--email). Plain SMTP from the standard
2
+ library: the same paper and settings always send the same message.
3
+
4
+ Settings, in the [email] section of the settings file:
5
+ to = "you@example.com" required
6
+ smtp_host = "smtp.gmail.com" required
7
+ smtp_port = "587" 587 (STARTTLS, the default) or 465 (TLS)
8
+ smtp_user = "you@example.com" default: to
9
+ from = "you@example.com" default: smtp_user
10
+
11
+ The password is never kept in the settings file. It comes from the
12
+ LIT_READER_SMTP_PASSWORD environment variable or, on a Mac, from Keychain:
13
+ security add-generic-password -s lit-reader -a you@example.com -w
14
+ """
15
+ import os
16
+ import re
17
+ import shutil
18
+ import smtplib
19
+ import ssl
20
+ import subprocess
21
+ from email.message import EmailMessage
22
+
23
+ MAX_BYTES = 18 * 1000 * 1000 # Gmail refuses messages over 25 MB, and base64 adds a third
24
+ KEYCHAIN_SERVICE = "lit-reader"
25
+ TYPES = {".epub": ("application", "epub+zip"), ".html": ("text", "html")}
26
+
27
+
28
+ class MailError(Exception):
29
+ pass
30
+
31
+
32
+ def settings(conf, config_path):
33
+ """The [email] settings, checked, with the password found, before any build starts."""
34
+ e = conf.get("email") if isinstance(conf.get("email"), dict) else {}
35
+ missing = [k for k in ("to", "smtp_host") if not e.get(k)]
36
+ if missing:
37
+ raise MailError("--email needs an [email] section in %s with %s. Run: lit-reader setup-email"
38
+ % (config_path, " and ".join(missing)))
39
+ port = e.get("smtp_port") or "587"
40
+ if port not in ("587", "465"):
41
+ raise MailError("smtp_port must be 587 (STARTTLS) or 465 (TLS), not %s" % port)
42
+ user = e.get("smtp_user") or e["to"]
43
+ return {"to": e["to"], "host": e["smtp_host"], "port": int(port), "user": user,
44
+ "from": e.get("from") or user, "password": password(user)}
45
+
46
+
47
+ def password(user):
48
+ pw = os.environ.get("LIT_READER_SMTP_PASSWORD")
49
+ if pw:
50
+ return pw
51
+ if has_keychain(): # macOS Keychain; arguments, never a shell
52
+ r = subprocess.run(["security", "find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", user, "-w"],
53
+ capture_output=True, text=True)
54
+ if r.returncode == 0 and r.stdout.strip():
55
+ return r.stdout.rstrip("\n")
56
+ raise MailError("no email password found for %s. Run lit-reader setup-email to store it in Keychain, "
57
+ "or set LIT_READER_SMTP_PASSWORD" % user)
58
+
59
+
60
+ def has_keychain():
61
+ return shutil.which("security") is not None
62
+
63
+
64
+ def in_keychain(user):
65
+ return has_keychain() and subprocess.run(
66
+ ["security", "find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", user],
67
+ capture_output=True).returncode == 0
68
+
69
+
70
+ # Mail services whose server can be filled in from the address, and where their app passwords live.
71
+ PROVIDERS = {
72
+ "gmail.com": ("smtp.gmail.com", "Gmail needs an app password, made at https://myaccount.google.com/apppasswords "
73
+ "(2-Step Verification has to be on)."),
74
+ "icloud.com": ("smtp.mail.me.com", "iCloud Mail needs an app-specific password, made at https://account.apple.com "
75
+ "under Sign-In and Security."),
76
+ }
77
+ PROVIDERS["googlemail.com"] = PROVIDERS["gmail.com"]
78
+ PROVIDERS["me.com"] = PROVIDERS["mac.com"] = PROVIDERS["icloud.com"]
79
+ MANAGED = ("to", "smtp_host", "smtp_port", "smtp_user", "from")
80
+ ADDRESS = re.compile(r"[^@\s\"'\\]+@[^@\s\"'\\]+\.[^@\s\"'\\]+")
81
+ SECTION = re.compile(r"\s*\[([A-Za-z0-9_-]+)\]\s*") # the same rule as core.read_settings
82
+ UNQUOTABLE = re.compile(r"[\"\\\n]")
83
+
84
+
85
+ def ask(label, default=None, check=None, why=""):
86
+ while True:
87
+ got = input("%s%s: " % (label, " [%s]" % default if default else "")).strip() or default or ""
88
+ if got and (check is None or check(got)):
89
+ return got
90
+ print(" " + (why or "This one is needed."))
91
+
92
+
93
+ def yes(label, default=True):
94
+ got = input("%s [%s] " % (label, "Y/n" if default else "y/N")).strip().lower()
95
+ return default if not got else got.startswith("y")
96
+
97
+
98
+ def with_section(text, values):
99
+ """The settings file's text with its [email] keys set to values. Other
100
+ sections, other keys and comments are kept as they were."""
101
+ lines = text.splitlines()
102
+ body = ['%s = "%s"' % (k, values[k]) for k in MANAGED if values.get(k)]
103
+ start = next((i for i, l in enumerate(lines) if (SECTION.fullmatch(l) or [None, None])[1] == "email"), None)
104
+ if start is None:
105
+ while lines and not lines[-1].strip():
106
+ lines.pop()
107
+ return "\n".join(lines + ([""] if lines else []) + ["[email]"] + body) + "\n"
108
+ end = next((i for i in range(start + 1, len(lines)) if SECTION.fullmatch(lines[i])), len(lines))
109
+ kept = [l for l in lines[start + 1:end] if not re.match(r"\s*(%s)\s*=" % "|".join(MANAGED), l)]
110
+ return "\n".join(lines[:start + 1] + body + kept + lines[end:]) + "\n"
111
+
112
+
113
+ def setup(config_path, read_settings, version):
114
+ """lit-reader setup-email: ask for the settings, write them, store the
115
+ password and send a test. Returns the exit status."""
116
+ try:
117
+ return run_setup(config_path, read_settings, version)
118
+ except (KeyboardInterrupt, EOFError):
119
+ print("\nstopped; anything confirmed before this was kept.")
120
+ return 1
121
+
122
+
123
+ def run_setup(config_path, read_settings, version):
124
+ conf = read_settings(config_path) if config_path.is_file() else {}
125
+ old = conf.get("email") if isinstance(conf.get("email"), dict) else {}
126
+ print("This sets up --email, which sends reading copies through your own mail account.\n"
127
+ "Press Return to keep the value in brackets.\n")
128
+ to = ask("Your email address (copies go here)", old.get("to"), ADDRESS.fullmatch,
129
+ "That doesn't look like an email address.")
130
+ host_default, hint = PROVIDERS.get(to.rsplit("@", 1)[1].lower(), (None, ""))
131
+ if old.get("to") and old["to"].rsplit("@", 1)[-1].lower() != to.rsplit("@", 1)[1].lower():
132
+ old = {} # a new mail service: the old server and login don't carry over
133
+ host = ask("Mail server (SMTP)", old.get("smtp_host") or host_default,
134
+ lambda v: re.fullmatch(r"[A-Za-z0-9.:-]+", v),
135
+ "That should be a server name such as smtp.example.com, or an address such as 127.0.0.1.")
136
+ port = ask("Port, 587 or 465", old.get("smtp_port") or "587", lambda v: v in ("587", "465"),
137
+ "587 (STARTTLS) or 465 (TLS); 587 suits most services.")
138
+ user = ask("Login name", old.get("smtp_user") or to, lambda v: not re.search(r"[\s\"'\\]", v),
139
+ "A login name can't contain spaces or quotes.")
140
+ sender = old.get("from") if old.get("from") and not UNQUOTABLE.search(old["from"]) else None
141
+ if old.get("from") and not sender:
142
+ print(" Your from line can't be written back as it is, so it's left out: %s" % old["from"])
143
+ values = {"to": to, "smtp_host": host, "smtp_port": port, "smtp_user": user if user != to else None,
144
+ "from": sender}
145
+ new = with_section(config_path.read_text(encoding="utf-8") if config_path.is_file() else "", values)
146
+ print("\nThe [email] section of %s will read:\n" % config_path)
147
+ print("\n".join(' %s = "%s"' % (k, values[k]) for k in MANAGED if values.get(k)))
148
+ if not yes("\nWrite it?"):
149
+ print("Nothing was written.")
150
+ return 1
151
+ config_path.parent.mkdir(parents=True, exist_ok=True)
152
+ tmp = config_path.with_name(config_path.name + ".tmp")
153
+ try:
154
+ tmp.write_text(new, encoding="utf-8")
155
+ read_settings(tmp) # the file must still read back before it replaces the old one
156
+ os.replace(str(tmp), str(config_path))
157
+ finally:
158
+ if tmp.exists():
159
+ tmp.unlink()
160
+ print("wrote %s" % config_path)
161
+
162
+ print()
163
+ if hint:
164
+ print(hint)
165
+ if os.environ.get("LIT_READER_SMTP_PASSWORD"):
166
+ print("LIT_READER_SMTP_PASSWORD is set, so lit-reader uses that password.")
167
+ elif has_keychain():
168
+ if not in_keychain(user) or yes("Keychain already holds a password for %s. Replace it?" % user, False):
169
+ print("Keychain will ask for the password twice. It is kept in Keychain, not in the settings file.")
170
+ r = subprocess.run(["security", "add-generic-password", "-U", "-s", KEYCHAIN_SERVICE, "-a", user,
171
+ "-l", "lit-reader email", "-w"]) # -w last, with no value: security prompts for it
172
+ if r.returncode != 0:
173
+ print("Keychain didn't store it. To try again: lit-reader setup-email")
174
+ return 1
175
+ print("stored the password in Keychain")
176
+ else:
177
+ print("Set the LIT_READER_SMTP_PASSWORD environment variable to your password, then run this again to test.")
178
+ return 0
179
+
180
+ if not yes("\nSend a test email to %s now?" % to):
181
+ return 0
182
+ try:
183
+ s = settings(read_settings(config_path), config_path)
184
+ m = EmailMessage()
185
+ m["Subject"], m["From"], m["To"] = "lit-reader test", s["from"], s["to"]
186
+ m.set_content("Your email settings work. To send a paper:\n\n lit-reader paper.pdf --email\n\n"
187
+ "Sent by lit-reader %s.\n" % version)
188
+ send(s, m)
189
+ except MailError as e:
190
+ print("The test didn't go through: %s\nRun lit-reader setup-email again to change anything." % e)
191
+ return 1
192
+ print("sent. If it arrives, --email is ready.")
193
+ return 0
194
+
195
+
196
+ def message(s, path, title, reference, version):
197
+ data = path.read_bytes()
198
+ if len(data) > MAX_BYTES:
199
+ raise MailError("%s is %.1f MB, too large to email; most mail services stop at 25 MB"
200
+ % (path.name, len(data) / 1e6))
201
+ kind = TYPES.get(path.suffix)
202
+ if not kind:
203
+ raise MailError("can't email %s: only .epub and .html copies are sent" % path.name)
204
+ how = ("On an iPhone, open it from Mail and it goes into Apple Books; in the Gmail app, use the share button and choose Books."
205
+ if path.suffix == ".epub" else
206
+ "Open it in a browser. A phone's attachment preview shows the text but may not run the page's script.")
207
+ m = EmailMessage()
208
+ m["Subject"] = "Reading copy: %s" % title
209
+ m["From"] = s["from"]
210
+ m["To"] = s["to"]
211
+ m.set_content("%s\n\nAttached: %s (%.1f MB). %s\n\nSent by lit-reader %s.\n"
212
+ % (reference, path.name, len(data) / 1e6, how, version))
213
+ m.add_attachment(data, maintype=kind[0], subtype=kind[1], filename=path.name) # base64, so no server can re-encode it
214
+ return m
215
+
216
+
217
+ def send(s, m):
218
+ ctx = ssl.create_default_context()
219
+ try:
220
+ tls = s["port"] == 465
221
+ with (smtplib.SMTP_SSL(s["host"], 465, context=ctx, timeout=60) if tls
222
+ else smtplib.SMTP(s["host"], 587, timeout=60)) as server:
223
+ if not tls:
224
+ server.starttls(context=ctx) # never log in over an unencrypted connection
225
+ server.ehlo_or_helo_if_needed()
226
+ if "PLAIN" in server.esmtp_features.get("auth", "").upper().split():
227
+ # One mechanism only. Gmail hangs up after refusing a password, so login()'s
228
+ # fallback to the next mechanism turns a refusal into "Connection unexpectedly closed".
229
+ server.user, server.password = s["user"], s["password"]
230
+ server.auth("PLAIN", server.auth_plain)
231
+ else:
232
+ server.login(s["user"], s["password"])
233
+ server.send_message(m)
234
+ except smtplib.SMTPAuthenticationError:
235
+ raise MailError("%s refused the login for %s. Gmail and many providers need an app password, not your normal one."
236
+ % (s["host"], s["user"]))
237
+ except UnicodeError: # smtplib sends the login in ASCII
238
+ raise MailError("the login name or password has a character outside plain ASCII, which mail servers don't accept")
239
+ except (smtplib.SMTPException, OSError) as e:
240
+ raise MailError("couldn't send through %s: %s" % (s["host"], e))