#! /usr/bin/python
# Depends on gdata-1.3.2.  See examples in it.
# 
# Edit the lines below "CONFIG" with the values appropriate for
# you.
# 
# You might notice that the filenames of the downloaded docs
# are a bit weird.  They include the "resource ID" so that if
# two documents have the same title (name), they'll be backed
# up to different files.
# 
# Google is generating an internal server error today when I
# try to download PDFs, so those are skipped for now.

from xml.etree import ElementTree
import sys
import os
from string import rstrip
import dbhash
from email.Utils import encode_rfc2231
sys.path.insert(0, '/home/ecashin/opt/gdata-1.3.2/lib/python')
import gdata.docs.service
import gdata.spreadsheet.service

# CONFIG
email = 'ecashin@gmail.com'
bkpdir = '/mnt/hda7/ecashin/remote/google-documents'

def backup(doc, db):
	id = doc.resourceId.text
	t = doc.GetDocumentType()
	print "title: ", doc.title.text
	print "  id: %s" % (id)
	print "  GetDocumentType: %s" % (t)
	print "  updated: ", doc.updated.text
	if db.has_key(id):
		print "  last backup: ", db[id]
	lpath = bkpdir + '/'
	lpath += encode_rfc2231(doc.title.text)
	lpath += '-' + encode_rfc2231(id)
	if t == 'spreadsheet':
		tok = dclient.GetClientLoginToken()
		dclient.SetClientLoginToken(sclient.GetClientLoginToken())
		lpath += '.xls'
		print ' ---> ' + lpath
		dclient.DownloadSpreadsheet(id, lpath)
		dclient.SetClientLoginToken(tok)
	else:
		if t == 'pdf':
			lpath += '.pdf'
			print "  SKIP PDF"
			return
		elif t == 'presentation':
			lpath += '.ppt'
		else:
			lpath += '.doc'
		print ' ---> ' + lpath
		dclient.DownloadDocument(id, lpath)

db = dbhash.open(bkpdir + '/bgddb', 'c', 0666)

os.system("stty -echo")
print 'password for %s: ' % (email),
auth = rstrip(sys.stdin.readline(), "\n")
os.system("stty echo")

dclient = gdata.docs.service.DocsService()
dclient.ClientLogin(email, auth)
sclient = gdata.spreadsheet.service.SpreadsheetsService()
sclient.ClientLogin(email, auth)
feed = dclient.GetDocumentListFeed()
for doc in feed.entry:
	id = doc.resourceId.text
	if db.has_key(id) and db[id] == doc.updated.text:
		print ".",
		sys.stdout.flush()
		continue
	print
	backup(doc, db)
	db[id] = doc.updated.text
