Pelican plugin for generating comments from an mbox-Mailbox
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.4 KiB

#!/usr/bin/python3
import mailbox
import email.utils
from datetime import datetime
import re
import os
import os.path
import sys
def sluggish ( txt ):
return re.sub( r'[^a-z0-9\-_]', '', txt.lower().replace(" ", "-" ) )
def writeMarkdown ( filename, obj, content ):
os.makedirs(os.path.dirname(filename), exist_ok=True)
if os.path.isfile ( filename ):
print ("MBOX: File ", filename, " already exists, skipping")
return
txt = ""
for k in obj:
txt += "{}: {}\n".format(k,obj[k])
txt += "\n{}".format(content)
with open(filename, "w+") as f:
f.write(txt)
print ("Written comment to", filename)
return
fields = [ "commenter", "title", "comment_to", "category", "body" ]
def parseContent ( content ):
lines = content.split("\n")
if len(lines) <= 0:
raise KeyError("Comment message should have lines")
cont = {}
lastLeft = ""
for line in lines:
index = line.find("=")
if index == -1:
if lastLeft == "body":
cont[lastLeft] += "\n" + line
continue
left = line[:index].strip()
if left not in fields:
if lastLeft == "body":
cont[lastLeft] += "\n" + line
right = line[index+1:].strip()
cont[left]=right
lastLeft = left
return cont
if len(sys.argv) < 2:
print ("usage: {} mbox-path [content-path]", sys.argv[0])
sys.exit(1)
mboxfile = sys.argv[1]
try:
contentpath = sys.argv[2]
except (KeyError, IndexError):
contentpath = "content"
mbox = mailbox.mbox ( mboxfile )
for mail in mbox:
obj = {}
if mail.get_content_type() != "text/plain":
print ("Content type not supported, use text/plain | actual content-type ", mail.get_content_type())
try:
dt = email.utils.parsedate_to_datetime ( mail.get("date") )
except ValueError:
print ("date cannot be parsed", mail.get("date"))
continue
content = parseContent(mail.get_payload())
obj["from"] = mail.get_from()
obj["date"] = dt.isoformat()
obj["category"] = "comment"
obj["commenter"] = content["commenter"]
obj["comment_to"] = content["comment_to"]
obj["title"] = content["title"]
obj["slug"] = "{}_{}_{}".format(dt.year, obj["comment_to"], sluggish(obj["title"]))
content_text = content["body"]
path = os.path.join(contentpath, "comment", "{}.md".format(obj["slug"]))
writeMarkdown ( path, obj, content_text )