#!/usr/bin/env python

from argparse import ArgumentParser
import json
import logging
from base64 import b64encode

from requests import Request, Session
from requests_foauth import Foauth


logging.basicConfig()

log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


parser = ArgumentParser(description='Delete your last 3200 tweets and backup tweeted photos to Google Drive')
parser.add_argument('email', help='foauth.org email')
parser.add_argument('password', help='foauth.org password')
parser.add_argument('--debug', action='store_true')

args = parser.parse_args()


session = Session()
session.mount('https://', Foauth(args.email, args.password))


def _prepare_upload(title, file_):
    '''Prepares a Request to upload the file <file_>, giving it the title <title>.'''
    metadata = {
        'title': title,
    }

    request = Request('post', 'https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart', files={
        'metadata': json.dumps(metadata),
        'file': b64encode(file_.read()),
    }, headers={
        'Content-Type': '',  # Hack to make Google Drive's API work
    })

    return request


if __name__ == '__main__':
    # TODO: Search first

    with open('/Users/beau/Pictures/1418760457552.png', mode='rb') as file_:
        request = _prepare_upload('lel.png', file_)

    request = session.prepare_request(request)
    response = session.send(request)

    log.debug('Request headers {}'.format(response.request.headers))
    log.debug('Request body {}'.format(response.request.body))
    response.raise_for_status()

    log.debug('Response body {}'.format(response.text))

@@ -56,35 +56,8 @@
 ser%0A
-import json%0Aimport logging%0A
 from
@@ -80,16 +80,79 @@
 64encode
+%0Afrom collections import OrderedDict%0Aimport json%0Aimport logging
 %0A%0Afrom r
@@ -716,16 +716,25 @@
 _upload(
+session, 
 title, f
@@ -882,288 +882,582 @@
     
-request = Request('post', 'https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart', files=%7B%0A        'metadata': json.dumps(metadata),%0A        'file': b64encode(fil
+files = OrderedDict()%0A    files%5B'metadata'%5D = ('metadata', json.dumps(metadata), 'application/json')%0A    files%5B'file'%5D = ('file', b64encode(file_.read()), 'image/png', %7B'Content-Transfer-Encoding': 'base64'%7D)%0A%0A    request = Request('post', 'https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart', files=files)%0A%0A    # requests sets the content-type as multipart/form-data, Google Drive expects multipart/related%0A    request = session.prepar
 e_
-.
 re
-ad()),%0A    %7D, headers=%7B%0A        'Content-Type': '',  # Hack to make Google Drive's API work%0A    %7D
+quest(request)%0A    request.headers%5B'Content-Type'%5D = request.headers%5B'Content-Type'%5D.replace('form-data', 'related'
 )%0A%0A 
@@ -1640,16 +1640,25 @@
 _upload(
+session, 
 'lel.png
@@ -1672,55 +1672,8 @@
 _)%0A%0A
-    request = session.prepare_request(request)%0A
     

Fix upload