Add support for message/partial

This doesn't handle the case where total isn't present on all parts, but
I don't actually expect to encounter that (and if I do, it will crash
and I can fix it).
This commit is contained in:
Peter J. Holzer 2019-02-28 17:17:44 +01:00
parent d5e557e8e4
commit b5c979d5cb
1 changed files with 29 additions and 0 deletions

View File

@ -1,5 +1,6 @@
#!/usr/bin/python3
import email.parser
import html
import html.parser
import mailbox
@ -45,6 +46,8 @@ def render_message(msg):
msghtml = msgtmpl.render(context)
return jinja2.Markup(msghtml)
partial_message_cache = {}
def render_body(msg):
content_type = msg.get_content_type()
@ -88,6 +91,32 @@ def render_body(msg):
elif content_type == "text/enriched":
tepart = TextEnrichedPart(msg.get_payload())
bodyhtml = tepart.as_string()
elif content_type == "message/partial":
# Default header for get_param is Content-Type
whole_msg_id = msg.get_param("id")
if not whole_msg_id in partial_message_cache:
# For now we assume that total is present on all parts. This
# isn't guarantueed, however, and we may need to handle the
# case where total is only present on the last part.
partial_message_cache[whole_msg_id] = [None] * int(msg.get_param("total"))
payload = msg.get_payload()
s = payload[0].as_string() # Only one part
partial_message_cache[whole_msg_id][int(msg.get_param("number"))-1] = s
if not None in partial_message_cache[whole_msg_id]:
p = email.parser.Parser()
whole_msg = p.parsestr("".join(partial_message_cache[whole_msg_id]))
whole_msg_embedded_id = whole_msg["Message-Id"]
if not whole_msg_embedded_id:
whole_msg.add_header("Message-Id", "<" + whole_msg_id + ">")
whole_msg_embedded_id = whole_msg_id
archive(whole_msg)
del partial_message_cache[whole_msg_id]
bodyhtml = "<p>This is part %d of %d of <a href='../%s/'>%s</a></p>" % (
int(msg.get_param("number")),
int(msg.get_param("total")),
encode_message_id(whole_msg_id),
html.escape(whole_msg_id))
else:
raise RuntimeError("Content-type " + content_type + " not implemented yet")