-
-
Save darkseed/1001409 to your computer and use it in GitHub Desktop.
gexport.py - Export Google Docs to a local directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 <[email protected]>" | |
__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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment