#!/usr/bin/env python
# -*- coding: utf-8 -*-

import mimetypes
import email
import email.Header
import urllib
import time

def get_parts(msgbody):
    """
    Find out body,attached image, and return them.
    msgbody : mime message of email
    """
    
    msg = email.message_from_string(msgbody)
    
    subj_l = email.Header.decode_header(msg.get('subject'))[0]
    enc = 'us-ascii'
    if subj_l[1]:
        enc = subj_l[1]
    subj = unicode(subj_l[0],enc).encode('utf-8')

    body = ""
    images = []
    for part in msg.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        tp = part.get_type()
        if not body and tp.find('text') != -1:
            # body like part was found !!
            body = part
            continue
        if tp.find('image') != -1:
            # Image found!
            images.append(part)
    return body,subj,images

def add_moblog_entry(msgbody,blogbase,passwd):
    """
    Add entry from mail
    
    msgbody  : This argument will be mime message of one email.
    blogbase : This argument will be url for blog.
               Authentication informations(user/pass) must be included.
    """

    body,subj,images = get_parts(msgbody)

    if not body:
        # no body was found
        return

    # get body_str and passwd chk
    body_str = body.get_payload(decode=1)
    if body_str.find(passwd) != 0 and body_str.find(passwd[1:]) != 0:
        return
    else:
        if not body_str.find(passwd) != 0:
            body_str = body_str.replace(passwd,'')
        else:
            # for t902 text mail
            body_str = body_str.replace(passwd[1:],'')
        while body_str[0] == '\n':
            body_str = body_str[1:]
    body_str = body_str.split('---')[0]
    body_str = unicode(body_str,'iso-2022-jp').encode('utf-8')
    
    # Add images
    if images:
        # filename(s)
        fns = []
        # image(s) counter
        img_number = 0
        for img in images:
            filename = img.get_filename()
            if not filename:
                ext = None
                try:
                    ext = mimetypes.guess_extension(img.get_type())
                except:
                    pass
                if not ext:
                    # Use a generic bag-of-bits extension
                    ext = '.bin'
                filename = 'image-%d%s' % (time.time(),ext)
            # Invoke factory to add image
            # image(s) counter up
            img_number = img_number + 1
            # img_titel => subj(number/total)
            img_title = '%s(%s/%s)' % (subj, str(img_number), str(len(images)))
            dt = urllib.urlencode({'id':filename,'type_name':'Image'})
            urllib.urlopen(blogbase+'images/invokeFactory',dt)
            # Send raw content
            dt = urllib.urlencode({'title':img_title,
                                   'content_type':img.get_type(),
                                   'filedata':str(img.get_payload(decode=1)) })
            urllib.urlopen(blogbase+'images/'+filename + '/manage_edit',dt)
            fns.append('images/'+filename)
            
        # filename(s) gen
        fns = ','.join(fns)
    else:
        fns = '' # fns = 'images/nopics.jpg'
    
    # Add entry (id => 'moblog-9999-12-31-12-59-59')
    id = time.strftime('moblog%Y-%m-%d-%H-%M-%S',time.localtime())
    dt = urllib.urlencode({'entry_id':id,'title':subj,
                           'body':body_str,
                           'image_path':fns})
    urllib.urlopen(blogbase+'modi_add_moblog_entry',dt)

def main():

    #
    # Please set some information,(host of mail server,etc) to use
    #

    import poplib
    s = poplib.POP3('pop.yourmailserver')
    # for apop
#    s.apop('yourmailaccount','mailpassword')
    # for pop
    s.user('yourmailaccount')
    s.pass_('mailpassword')

    # blog url
    blogbase='http://yourploneaccount:yourplonepassword@your.server/blog/path/'
    # entry password
    entrypass='\nEntrypassword'

    l = s.list()
    if len(l) and l[1]:
        numMessages = len(l[1])
        
        for i in range(numMessages):
            m = s.retr(i+1)
            msgbody = '\n'.join(m[1])
            add_moblog_entry(msgbody,blogbase,entrypass)
            s.dele(i+1)

    s.quit()

    return

if __name__ == '__main__':
    main()
