public
Last active — forked from mnot/gexport.py

gexport.py - Export Google Docs to a local directory

  • Download Gist
gexport.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
#!/usr/bin/env python
 
"""\
gexport.py
 
Export Google Docs to a local directory.
 
Requires the GData Python client library:
http://code.google.com/p/gdata-python-client/
"""
 
__version__ = "0.1"
__author__ = "Mark Nottingham <mnot@mnot.net>"
__copyright__ = """\
Copyright (c) 2010 Mark Nottingham
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
 
from dateutil import parser as date_parser
import getpass
from optparse import OptionParser
import os
import sys
 
import gdata.docs.data
import gdata.docs.client
from gdata.spreadsheet.service import SpreadsheetsService
 
 
class GDocDownloader():
id = 'mnot.net-dl-gdocs'
exts = {
'spreadsheet': 'xls',
'document': 'doc'
}
def __init__(self, username, password):
self.client = gdata.docs.client.DocsClient(source=self.id)
self.client.ssl = True
self.client.http_client.debug = False
self.client.ClientLogin(username, password, self.client.source)
self.doc_token = self.client.auth_token
 
ss_client = SpreadsheetsService(source=self.id)
ss_client.ClientLogin(username, password, self.client.source)
self.ss_token = \
gdata.gauth.ClientLoginToken(ss_client.GetClientLoginToken())
 
def run(self, save_dir, extra_formats, msg):
feed = self.client.GetDocList()
if not feed.entry:
msg('No entries in feed.')
return
for entry in feed.entry:
doc_title = entry.title.text.encode('UTF-8')
doc_type = entry.GetDocumentType()
update = int(date_parser.parse(entry.updated.text).strftime("%s"))
if doc_type == "spreadsheet":
self.client.auth_token = self.ss_token
else:
self.client.auth_token = self.doc_token
try:
# just use the first one
folder = os.path.basename(entry.InFolders()[0].title)
folder_dir = os.path.join(save_dir, folder)
if not os.path.exists(folder_dir):
os.makedirs(folder_dir)
except IndexError, why:
folder = ''
except IOError, why:
msg("ERROR: Can't create folder (%s)" % why, True)
folder = ''
native_format = self.exts.get(doc_type, 'pdf')
exts = set(extra_formats + [native_format])
msg("%12s: %s" % (doc_type, doc_title))
for ext in exts:
file_path = os.path.join(
save_dir,
folder,
"%s.%s" % (doc_title, ext)
)
if os.path.exists(file_path) \
and update == os.stat(file_path).st_mtime:
continue
try:
self.client.Export(entry, file_path)
os.utime(file_path, (update, update))
except IOError, why:
msg("ERROR: %s" % why, True)
return len(feed.entry)
 
 
if __name__ == "__main__":
usage = "Usage: %prog [options] <google username> <destination dir>"
version = "gdl version %s" % __version__
option_parser = OptionParser(usage=usage, version=version)
option_parser.set_defaults(
password = None,
quiet = False,
html = False,
pdf = False
)
 
option_parser.add_option("-q", "--quiet",
action="store_true", dest="quiet",
help="Suppress non-error messages")
 
option_parser.add_option("-p", "--password",
action="store", dest="password",
help="Google password"
)
option_parser.add_option("-P", "--pdf",
action="store_true", dest="pdf",
help="Also export PDF"
)
 
(options, args) = option_parser.parse_args()
if len(args) != 2:
option_parser.error(
"Please specify a username and a destination."
)
if options.password:
password = options.password
else:
password = getpass.getpass()
 
def msg(m, err=False):
if err or not options.quiet:
sys.stderr.write("%s\n" % m)
 
extra_formats = []
options.pdf and extra_formats.append("pdf")
try:
dler = GDocDownloader(args[0], password)
doc_count = dler.run(args[1], extra_formats, msg)
msg("%s docs." % doc_count)
except gdata.client.BadAuthentication:
msg("Bad username or password.", True)
except KeyboardInterrupt:
pass

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.