#!/usr/bin/python
import email, os, re, sys, time
from xml.sax.saxutils import escape
from post import sanitize, writeComment
# change directory to the data dir, ensuring that this code remains in the path
from config import directory
if directory.codebase not in sys.path:
sys.path.insert(0, directory.codebase)
os.chdir(directory.data)
# parse the e-mail message
msg = email.message_from_file(sys.stdin)
title = escape(msg['Subject'])
name = escape(msg['From'].split(' <')[0]).replace('"','')
addr = escape(msg.get_unixfrom().split(' ')[1]).replace('"','"')
path = escape(re.sub('\s+', ' ', msg['Received'])).replace('"','"')
if 'Sender' in msg:
name = escape(msg['Sender'].split(' <')[0]).replace('"','')
# support X-URL Mime header (known to be supported by emacs)
if 'X-URL' in msg:
href=msg['X-URL']
else:
href='mailto:'+addr
# determine the target blog entry. If this fails, python will throw
# an exception, and procmail will resume
target = re.findall("(^|\W)blog\W(\d+)(\W|$)",msg['To'])[0][1]
# bail on spamAssasin marked e-mail
if title.find('*****SPAM*****')==0: sys.exit(99)
if msg['X-Spam-Flag']=='YES': sys.exit(99)
# bail on open relays that have proven problematic
if path.find('62.118.249.10')>=0: sys.exit(99)
if path.find('194.226.128.51')>=0: sys.exit(99)
if path.find('209.61.183.90')>=0: sys.exit(99) # unknown prankser
# only allow email for 30 days
entry=directory.data+target+'.txt'
age=(time.mktime(time.localtime())-os.stat(entry).st_mtime)/86400
if age>=31: sys.exit(99)
# extract and escape the text portion of the payload
body = msg.get_payload()
if isinstance(body,list): body=body[0].get_payload()
body = re.compile("^-- $",re.M).split(body)[0].strip()
body = sanitize(body.strip())
body = body.replace("
\n","\n")
# write the comment out where blosxom will find it
writeComment(target, title, """%s
Emailed by %s
""" % (body, href, path, name))