Many hyperlinks are disabled.
Use anonymous login
to enable hyperlinks.
Overview
Comment: | Code up message reading |
---|---|
Downloads: | Tarball | ZIP archive | SQL archive |
Timelines: | family | ancestors | descendants | both | master | trunk |
Files: | files | file ages | folders |
SHA3-256: |
634e282a4196418fc5439a00243188e2 |
User & Date: | ajv-899-334-8894@vsta.org 2016-11-27 16:05:32 |
Context
2016-11-28
| ||
14:07 | Deal with imap server idle/timeout and reconnect. check-in: 3a6568daae user: ajv-899-334-8894@vsta.org tags: master, trunk | |
2016-11-27
| ||
16:05 | Code up message reading check-in: 634e282a41 user: ajv-899-334-8894@vsta.org tags: master, trunk | |
01:17 | Forward and back in message lists. Fix noop check of server status. Emphasis on date, don't use space for message index. check-in: 17e03cf724 user: ajv-899-334-8894@vsta.org tags: master, trunk | |
Changes
Changes to get.py.
82
83
84
85
86
87
88
89
90
91
92
93
94
95
...
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
|
# All alnum if any((not s.isalnum()) for s in tup): return False return True # See if this names a folder, then list contents def list_folder(self): pp = self.paths if len(pp) != 1: return False,None # Which folder? ................................................................................ srv = self.get_server() tup = srv.messages(fn, startidx, NMSG) if tup is None: return False,None nmsg,msgs = tup # Here's your messages buf = self.build_header("Messages %d-%d" % (startidx, startidx+len(msgs)-1)) buf += '<table>\n' for msgidx,flags,fields in msgs: buf += ' <tr>\n' # Time if today # mm/dd if this year # mm/yy if previous years today = time.localtime() tm = srv.dt_parse(fields["date"]) # This year if tm.tm_year == today.tm_year: # Today if (tm.tm_mon == today.tm_mon) and \ (tm.tm_mday == today.tm_mday): tms = "%02d:%02d" % (tm.tm_hour, tm.tm_min) else: # Some month of this year tms = "%d/%d" % (tm.tm_mon, tm.tm_mday) else: # Some month of that year tms = "%d/%04d" % (tm.tm_mon, tm.tm_year) # Emphasize time for unread if "Seen" not in flags: tms = "<em>%s</em>" % (tms,) # Add date buf += ' <td>%s</td>\n' % (tms,) # Who if "from" in fields: tup = parseaddr(fields["from"]) s = tup[0].strip() or tup[1].strip() or "--" s = s[:20] buf += ' <td>%s</td>\n' % (cgi.escape(s),) else: buf += ' <td>--</td>\n' # Subject buf += ' <td>%s</td>\n' % \ (cgi.escape(fields.get("subject", "--")),) buf += ' </tr>\n' buf += '</table>\n' # Next and previous pages? ourpath = '/'.join(self.paths) if startidx > 1: buf += '<a href="/%s?from=%d">Older</a>\n' % ( ourpath, (1 if (startidx <= NMSG) else (startidx-NMSG)) ) if (startidx + NMSG) < nmsg: buf += '<a href="/%s?from=%d">Newer</a>\n' % ( ourpath, startidx+NMSG ) buf = self.build_tailer(buf) return True,self.send_result(buf, "text/html") # Message number under folder, render contents def read_msg(self): return None |
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
|
|
<
<
<
|
<
<
>
|
|
|
<
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
...
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
|
# All alnum if any((not s.isalnum()) for s in tup): return False return True # Time if today # mm/dd if this year # mm/yy if previous years def get_when(self, fields): srv = self.srv today = time.localtime() tm = srv.dt_parse(fields["date"]) # This year if tm.tm_year == today.tm_year: # Today if (tm.tm_mon == today.tm_mon) and \ (tm.tm_mday == today.tm_mday): tms = "%02d:%02d" % (tm.tm_hour, tm.tm_min) else: # Some month of this year tms = "%d/%d" % (tm.tm_mon, tm.tm_mday) else: # Some month of that year tms = "%d/%04d" % (tm.tm_mon, tm.tm_year) return tms # Name or email address or just '--' def get_who(self, fields): if "from" not in fields: return '--' tup = parseaddr(fields["from"]) s = tup[0].strip() or tup[1].strip() or "--" return cgi.escape(s) # See if this names a folder, then list contents def list_folder(self): pp = self.paths if len(pp) != 1: return False,None # Which folder? ................................................................................ srv = self.get_server() tup = srv.messages(fn, startidx, NMSG) if tup is None: return False,None nmsg,msgs = tup # Here's your messages ourpath = '/'.join(self.paths) buf = self.build_header("Messages %d-%d" % (startidx, startidx+len(msgs)-1)) buf += '<table border="1" frame="void" rules="rows">\n' for msgidx,flags,fields in msgs: buf += ' <tr>\n' # Date/time when = self.get_when(fields) # Emphasize time for unread if "Seen" not in flags: tms = "<em>%s</em>" % (when,) # Add date buf += ' <td>%s</td>\n' % (when,) # Who, truncated who = self.get_who(fields)[:20] buf += ' <td>%s</td>\n' % (who,) # Subject msgurl = "/%s/%d" % (ourpath, msgidx) buf += ' <td><a href="%s">%s</a></td>\n' % \ (msgurl, cgi.escape(fields.get("subject", "--")),) buf += ' </tr>\n' buf += '</table>\n' # Next and previous pages? And "Done" in between. if startidx > 1: buf += '<a href="/%s?from=%d">Older</a>\n' % ( ourpath, (1 if (startidx <= NMSG) else (startidx-NMSG)) ) buf += '<a href="/">Done</a>\n' if (startidx + NMSG) < nmsg: buf += '<a href="/%s?from=%d">Newer</a>\n' % ( ourpath, startidx+NMSG ) buf = self.build_tailer(buf) return True,self.send_result(buf, "text/html") # Return straight text, with blank lines replaced with <p> # This'll make reflowable-friendly HTML. def para_body(self, body): while "\n\n" in body: idx = body.index("\n\n") body = body[:idx] + "\n<p>\n" + body[idx+2:] return body # Message number under folder, render contents def read_msg(self): # /<folder>/<msg#> pp = self.paths if len(pp) != 2: return False,None # Which folder? fn = urllib.unquote_plus(pp[0]) if not self.valid_fname(fn): return False,None # Valid message #? try: msgidx = int(pp[1]) if msgidx < 1: return False,None except: return False,None # Move to that folder srv = self.get_server() nmsg = srv.folder(fn) if nmsg is None: return False,None # Legal message number? if msgidx > nmsg: return False,None # Headers and text of body fields,body = srv.msg_text(msgidx) # Render to page who = self.get_who(fields) when = self.get_when(fields) buf = self.build_header("%s %s" % (when, who)) buf += self.para_body(body) buf = self.build_tailer(buf) return True,self.send_result(buf, "text/html") |
Changes to imap.py.
1
2
3
4
5
6
7
8
9
10
11
12
13
...
181
182
183
184
185
186
187
188
189
190
191
192
193
194
|
#
# imap.py
# imaplib services
#
import imaplib, time, sys
from email.header import decode_header
# Wrapper around imaplib connection
class Server(object):
def __init__(self, user, srv):
self.user = user
self.srv = srv
................................................................................
# On to next
msgidx += 1
msgcount += 1
if msgcount >= maxmsg:
break
return nmsg,res
# Get or start an imap server connection
def get(user, uconfig, imaps):
# Existing connection?
srv = imaps.get(user)
if srv is not None:
# Make sure it's still alive
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
...
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
|
# # imap.py # imaplib services # import imaplib, time, sys, html2text from email.header import decode_header import chore # Turn an imap BODYSTRUCTURE into a Python list representation class BodyParser(object): def __init__(self, s): self.s = s self.peeked = None # Return next lexical element def lex(self): s = self.s # Lookahead already got it? if self.peeked is not None: res = self.peeked self.peeked = None return res # Whitespace while s and s[0].isspace(): s = s[1:] # EOF if not s: self.s = s return None # Next char c = s[0] # Parens if c in ('(', ')'): self.s = s[1:] return c # Quoted string if c == '"': if '"' not in s[1:]: raise Exception, "Missing closing quote" idx = s[1:].index('"')+1 res = s[:idx+1] self.s = s[idx+1:] return res # Identifier if not c.isalnum(): raise Exception, "Unknown token" res = "" while s[0].isalnum(): res += s[0] s = s[1:] self.s = s return res # Peek next lexical element def peek(self): if self.peeked is not None: return self.peeked res = self.peeked = self.lex() return res # Consume either a single element, or a list of elem's # within (...) def elem(self): t = self.lex() # List of elem's if t == '(': res = [] while self.peek() != ')': e = self.elem() res.append(e) self.lex() return res # A single elem return t def parse(self): # BODYSTRUCTURE ...elems... end-of-string t = self.lex() if t != "BODYSTRUCTURE": raise Exception, "Not parsing a bodystructure" res = self.elem() t = self.lex() if t != None: raise Exception, "Residual content" return res # Wrapper around imaplib connection class Server(object): def __init__(self, user, srv): self.user = user self.srv = srv ................................................................................ # On to next msgidx += 1 msgcount += 1 if msgcount >= maxmsg: break return nmsg,res # Select folder, return message count in it # None for failure. def folder(self, fn, readonly=False): # Select folder, get message count tup = self.srv.select(fn, readonly=readonly) if tup[0] != "OK": return None nmsg = int(tup[1][0]) return nmsg # Fill in self.bodstruct from MIME description # out of imap def load_bodstruct(self, m): tup = self.srv.fetch(m, '(BODYSTRUCTURE)') if tup[0] != 'OK': raise Exception, "Can't parse %d: %s" % (m, tup[1]) s = tup[1][0] # Should start with '<num> (' and end with ')' idx = s.index('(') assert s.endswith(')') s = s[idx+1:][:-1] assert s.startswith('BODYSTRUCTURE') return BodyParser(s).parse() # Return the MIME index for this type # Find MIME index for this type # Returns None for failure, otherwise # ( (indices...), (entry-which-matched) ) def _find_type(self, st, typ1, typ2, prefix=()): for idx,tup in enumerate(st): # Nested if isinstance(tup[0], list): res = self._find_type(tup, typ1, typ2, prefix + (idx+1,)) if res is not None: return res continue # Not a usable message part if len(tup) < 6: continue # Match type & subtype if (tup[0] == typ1) and (tup[1] == typ2): return (prefix + (idx+1,), tup) # Didn't find it return None # Given the specified type/subtype, return its contents def _get_type(self, bods, m, typ1, typ2): # Single body contents if not isinstance(bods[0], list): e = bods if (e[0] != typ1) or (e[1] != typ2): return None tup = self.srv.fetch(m, "(BODY[TEXT])") if tup[0] != 'OK': raise Exception, "Can't get body %d: %s" % (m, tup[1]) bod = tup[1][0][1] else: # Find MIME variant res = self._find_type(bods, typ1, typ2) if res is None: # Didn't find it return None key,e = res key = ".".join(str(k) for k in key) # Get body of this MIME section tup = self.srv.fetch(m, "(BODY.PEEK[%s])" % (key,)) if tup[0] != 'OK': raise Exception, \ "Can't get MIME body %d: %s" % (m, tup[1]) bod = tup[1][0][1] # If encoded base64, get back original text if e[5] == '"base64"': bod = base64.b64decode(bod) elif e[5] == '"quoted-printable"': bod = quopri.decodestring(bod) # Streamline UTF-8 and such bod = chore.utils.uncharenc(bod) # Field DOS-style line endings bod = bod.replace("\r\n", "\n") return bod # Get a textual-ish body # Return (fields, body-text) def msg_text(self, msgidx): # MIME structure of message bods = self.load_bodstruct(msgidx) # Try for textual, then HTML (plus render to text) t = self._get_type(bods, msgidx, '"text"', '"plain"') if t is None: bodhtml = self._get_type(bods, msgidx, '"text"', '"html"') if bodhtml is None: return None t = html2text.html2text(bodhtml) # Message header fields tup = self.srv.fetch(msgidx, '(BODY[HEADER.FIELDS (FROM TO DATE STATUS SUBJECT)])') if tup[0] != "OK": sys.stderr.write("%s msg %d failed: %s\n" % (self.user, msgidx, tup[1])) return None fields = self.field_dict(tup[1][0][1]) return fields,t # Get or start an imap server connection def get(user, uconfig, imaps): # Existing connection? srv = imaps.get(user) if srv is not None: # Make sure it's still alive |