#!/usr/bin/env python2.4
# -*-*- encoding:iso-8859-15 filetype:python expandtab:yes tabstop:4 shiftwidth:4 softtabstop:4
# autoindent:yes -*-*-
#
# havard@dahle.no GPL (C) 2005

__doc__ = "Usage: pipe email message to this script for automatic post on your blog"

BLURL = "http://www.orakel.ntnu.no/~havardda/blogg/xmlrpc.php"
BLOGG = "kibbitz"
USRNM = "user"
PSWRD = "pass"
CTGRY = "10"

DEBUG = 0

import sys

try:
    import xmlrpclib, time, email
    from email.Header import decode_header
    from email.Iterators import typed_subpart_iterator
    from email.Utils import parsedate
    from string import join
    import html_entity_converter # local helper lib
except ImportError:
    print  "Import Error"
    sys.exit(100)

def striptags(s):
# stolen from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440481
# this list is neccesarry because chk() would otherwise not know
# that intag in stripTags() is ment, and not a new intag variable in chk().
        intag = [False]
        
        def chk(c):
                if intag[0]:
                        intag[0] = (c != '>')
                        return False
                elif c == '<':
                        intag[0] = True
                        return False
                return True
        
        return ''.join(c for c in s if chk(c))

def post(msg, categories = None):
    t = decode_header(msg.get("Subject"))
    topic =  join([i[0] for i in t])
    parts = typed_subpart_iterator(msg) # loops through "text/*" parts
    contents = None
    try:
        while not contents:
            p = parts.next()
            contents = p.get_payload(decode=1)
            if p.get_content_subtype() == "html":
                #convert from html
                contents = striptags(contents)
    except StopIteration:
        print "Crap! No text message part found"
        return 100

    
    p = map(html_entity_converter.html_entity_fixer, (topic, contents))
    post = "<title>%s</title>%s" % (tuple(p))

    try: isodate = time.strftime("%Y-%m-%dT%H:%M:%S", parsedate(msg['date']))
    except TypeError: isodate = None
    
   
    rpc = xmlrpclib.ServerProxy(BLURL, encoding="iso-8859-15", verbose=DEBUG)

    publish = xmlrpclib.Boolean(1)

    if not categories:
        cats = [{'categoryId': CTGRY},]
    else: 
        cats = []
        for c in rpc.metaWeblog.getCategories(BLOGG, USRNM, PSWRD):
            if categories.count(c["categoryName"]): 
                cats.append({'categoryId':c['categoryId']})
    try:
        id = rpc.blogger.newPost("",            # appkey
                    BLOGG,     # blogid
                    USRNM,   # username
                    PSWRD,   # password
                    post,    #content
                    publish     # publish?
                   )
        # set categories
        rpc.mt.setPostCategories(id, #postID
                                 USRNM, #username
                                 PSWRD, #password
                                 cats
                                )

        # set date
        if isodate:
            metaWeblog.editPost(id, #postID
                                USRNM, #username
                                PSWRD, #password
                                {'dateCreated':isodate}, #date
                                publish
                            )
    except xmlrpclib.Fault, (msg):
        print msg
        return 100
    except:
        return 100

    return 0

if __name__ == "__main__":
    if sys.stdin.isatty():
        print __doc__
        sys.exit(100)

    try:
        msg = email.message_from_file(sys.stdin)
        cats = sys.argv[1:]
        sys.exit(post(msg, cats))
    except:
        raise
        print "ouch could not post email on blog"
        sys.exit(100)
    
    

