#! /usr/bin/python
"""
Utility to migrate an mbox mailbox (from mailman, ideally) to Google Groups
"""

import argparse
import pprint
import sys
import mailbox
import httplib2
import os

from apiclient.errors import HttpError
from apiclient.http import BatchHttpRequest
from apiclient.http import HttpMock
from apiclient.http import MediaInMemoryUpload
from apiclient import sample_tools
from oauth2client.client import AccessTokenRefreshError

def main(argv):
    # Declare command-line flags.
    # addHelp=False here because it's added downstream in the sample_init
    argparser = argparse.ArgumentParser(add_help=False)

    argparser.add_argument(
        '-m',
        '--mailbox',
        help='The mailbox file containing the messages to be migrated.',
        required=True)
    argparser.add_argument(
        '-g',
        '--group',
        help='The email address of the group to receive the migrated messages.',
        required=True)
    argparser.add_argument(
        '-f',
        '--failed',
        help='The mailbox file containing the messages that failed to be migrated.',
        required=False)
    argparser.add_argument(
        '-v',
        '--verbose',
        help='Show progress',
        action='store_true')

    # Authenticate and construct service
    scope = ("https://www.googleapis.com/auth/apps.groups.migration")

    service, flags = sample_tools.init(
        argv, 'groupsmigration', 'v1', __doc__, __file__, parents=[argparser],
        scope=scope
        )

    mbox = mailbox.mbox(flags.mailbox, create=False)
    # create a new mbox with failed messages, to make reruns shorter
    if flags.failed:
        failbox = mailbox.mbox(flags.failed, create=True)
        failbox.lock()
    try:
        for message in mbox:
            # pprint.pprint(message)
            print message['message-id']
            print message['subject']
            media = MediaInMemoryUpload(str(message), mimetype='message/rfc822')
            request = service.archive().insert(groupId=flags.group,
                                               media_body=media)
            result = request.execute()
            print 'Response code was: %s' % result['responseCode']
            if flags.failed and result['responseCode'] != 'SUCCESS':
                failbox.add(message)
    except AccessTokenRefreshError:
        print ('The credentials have been revoked or expired, please re-run the '
               'application to re-authorize')
    if flags.failed:
        failbox.flush()
        failbox.unlock()



if __name__ == '__main__':
    main(sys.argv)

@@ -178,16 +178,119 @@
 mport os
+%0Aimport logging%0Alogging.basicConfig(format='%25(asctime)s %25(levelname)s %25(message)s',level=logging.DEBUG)
 %0A%0Afrom a
@@ -321,16 +321,37 @@
 ttpError
+,MediaUploadSizeError
 %0Afrom ap
@@ -562,16 +562,17 @@
 hError%0A%0A
+%0A
 def main
@@ -1927,37 +1927,64 @@
 ge)%0A            
-print
+logging.debug(%22message-id: %25s%22 %25
  message%5B'messag
@@ -1989,16 +1989,18 @@
 age-id'%5D
+ )
 %0A       
@@ -2004,21 +2004,45 @@
         
-print
+logging.debug(%22subject: %25s%22 %25
  message
@@ -2052,16 +2052,17 @@
 ubject'%5D
+)
 %0A       
@@ -2135,16 +2135,37 @@
 fc822')%0A
+            try:%0A    
         
@@ -2267,24 +2267,28 @@
             
+    
 media_body=m
@@ -2305,16 +2305,20 @@
         
+ 
+   
 result =
@@ -2352,37 +2352,40 @@
     
-print 'Response code was
+    logging.debug(%22response
 : %25s
-'
+%22
  %25 r
@@ -2405,17 +2405,22 @@
 seCode'%5D
-%0A
+)%0A    
         
@@ -2488,32 +2488,36 @@
                 
+  
+  
 failbox.add(mess
@@ -2517,24 +2517,231 @@
 dd(message)%0A
+            except (MediaUploadSizeError,HttpError) as e:%0A                if flags.failed:%0A                    failbox.add(message)%0A                logging.error( %22%25s: %25s%22 %25 (message%5B'message-id'%5D,str(e)) )%0A
     except A
@@ -2776,14 +2776,21 @@
     
-print 
+logging.error
 ('Th
@@ -2899,16 +2899,17 @@
 orize')%0A
+%0A
     if f
@@ -2971,18 +2971,16 @@
 lock()%0A%0A
-%0A%0A
 if __nam

add logging, exception handling for large files