示例#1
0
文件: sync.py 项目: jasharpe/docsync
def getAuthenticatedClient(user):
    try:
        with open("token", "r") as f:
            auth_token = f.readline().strip()
            try:
                client = gdata.docs.client.DocsClient(
                    auth_token=gdata.gauth.ClientLoginToken(auth_token),
                    source='jasharpe-docssync-v1')
                client.ssl = True
                client.http_client.debug = False
                # check that we're authorized
                client.GetDocList(limit=0)
            except gdata.client.Unauthorized as e:
                print "Bad authentication information from saved token."
                raise e
    except (IOError, gdata.client.Unauthorized):
        client = gdata.docs.client.DocsClient(source='jsharpe-docsync-v1')
        client.ssl = True
        client.http_client.debug = False
        while 1:
            # get password
            password = getpass.getpass("password for %s: " % user)

            try:
                client.ClientLogin(user, password, client.source)
                break
            except gdata.client.BadAuthentication as e:
                print "Bad authentication information."

        f = open("token", "w")
        f.write(client.auth_token.token_string)
        f.close()
    return client
def getGDriveClient(email=settings.DEFAULT_GDRIVE_EMAIL,
                    password=settings.DEFAULT_GDRIVE_PW):
    client = gdata.docs.client.DocsClient(source='MyTest')
    client.api_version = "3"
    client.ssl = True
    client.ClientLogin(email, password, client.source)
    return client
示例#3
0
 def gd_login(email, password):
     client = gdata.docs.client.DocsClient(source="Recluse SEO Suite")
     client.api_version = "3"
     client.ssl = True
     # pp.pprint(vars(client))
     client.ClientLogin(email, password, client.source)
     return client
示例#4
0
def export(username, password, docs_name, output_format, dest_path='' ):
    """
    To download we need:
        - filename
        - google doc ressource_id
        - destination path
    """
    logger = logging.getLogger('edgdd')
    try:
        client = gdata.docs.client.DocsClient(source='edggd-v0.5')
        client.ssl = True
        client.http_client.debug = False
        client.ClientLogin(username, password, source=client.source)

        gs_client = gdata.spreadsheet.service.SpreadsheetsService(source='edggd-v0.5')
        gs_client.ClientLogin(username, password, source=gs_client.source)
  
    except gdata.service.BadAuthentication:
        print "Error : Authentification refused by Google. Check supplied username and password."
        sys.exit(-2)
    
    for doc_name in docs_name:
    
        feed = client.GetDocList(uri=("/feeds/default/private/full?title=%s&title-exact=true&max-results=5" % (doc_name,)))
        
        if not feed.entry :
            print "Error : Document '%s' not found !" % (doc_name, )
            sys.exit(-3)

        # now we check query returns only one file
        if len(feed.entry) > 1 :
            print "Warning : Query for '%s' returned %i documents!!!" % (doc_name, len(feed.entry) ) 

        entry_counter =  0
        for entry in feed.entry :
            resource_id = entry.resource_id.text
        
            doc_type = resource_id[:resource_id.find(':')]
            if dest_path:
                dest_path += '/' if dest_path[-1] <> '/' else '' 
            if entry_counter :
                file_path = dest_path+doc_name+'.'+output_format+'.'+str(entry_counter)
            else :
                file_path = dest_path+doc_name+'.'+output_format

            # When downloading a spreadsheet, the authenticated request needs to be
            # sent with the spreadsheet service's auth token.
            if doc_type == 'spreadsheet':
                docs_token = client.auth_token # we save token
                client.auth_token = gdata.gauth.ClientLoginToken(gs_client.GetClientLoginToken())
                client.Export(resource_id, file_path, gid=0)
                client.auth_token = docs_token  # restore the DocList auth token            
                        
            else: # download a doc not a spreadsheet
                client.Export(entry, file_path)

            print "Info : %s exported"  % (file_path,)
            entry_counter+=1
示例#5
0
    def __init__(self, parent):
        QTreeWidget.__init__(self, parent)
        import gdata
        import gdata.docs.client

        client = gdata.docs.client.DocsClient()
        client.ClientLogin('*****@*****.**', 'oWertryN8..//vim', API().config.info.title)
        self.feed = client.GetDocList()
        self.fill()
示例#6
0
def CreateClient():
  client = gdata.docs.client.DocsClient(source=TorXMPPBot.APP_NAME)
  client.http_client.debug = TorXMPPBot.DEBUG
  try:
     client.ClientLogin('*****@*****.**', sys.argv[2], client.source)
  except gdata.client.BadAuthentication:
    exit('Invalid user credentials given.')
  except gdata.client.Error:
    exit('Login Error')
  return client
示例#7
0
def CreateClient(config):
    """Create a service client."""
    client = config.SERVICE(source=config.APP_NAME)
    client.http_client.debug = config.DEBUG
    try:
        client.ClientLogin(config.LOGIN, config.PASSWORD, config.APP_NAME)
    except gdata.client.BadAuthentication:
        exit('Invalid user credentials given.')
    except gdata.client.Error:
        exit('Login Error')
    return client
示例#8
0
def CreateClient():
    client = gdata.docs.client.DocsClient(source=TorXMPPBot.APP_NAME)
    client.http_client.debug = TorXMPPBot.DEBUG
    try:
        client.ClientLogin(config.LOGIN_EMAIL, config.EMAIL_PASS,
                           client.source)
    except gdata.client.BadAuthentication:
        exit('Invalid login.')
    except gdata.client.Error:
        exit('Login Error')
    return client
示例#9
0
def getCSVsByKey(key, datafoldername, foldernames):
    client = gdata.docs.client.DocsClient()
    client.ClientLogin(
        raw_input("GMail username: "******"GMail password: "******"wise")
    print "Login successful!"
    indexResource = client.GetResourceById(key)
    for gid in range(1, len(foldernames) + 1):
        path = datafoldername + foldernames[gid - 1] + "/cache/Index.csv"
        print "Downloading into", path
        client.DownloadResource(indexResource, path, {
            'gid': gid,
            'exportFormat': 'csv'
        })
示例#10
0
def create_empty_table(table_name):
    try:
        key, gd_client = get_spreadsheet_key(table_name)
        print >> sys.stderr, 'table %s exists, skip' % table_name
    except:
        import gdata.docs.data
        import gdata.docs.client
        client = gdata.docs.client.DocsClient(source=SOURCE)
        client.ssl = True  # Force all API requests through HTTPS
        client.http_client.debug = False  # Set to True for debugging HTTP requests
        
        client.ClientLogin(EMAIL,PASS,client.source)
        
        new_spreadsheet = client.Create(gdata.docs.data.SPREADSHEET_LABEL, table_name , writers_can_invite=False)
        print >> sys.stderr, 'Spreadsheet "%s" created' % new_spreadsheet.title.text
示例#11
0
def docify(prepend):
    """creates and uploads a shared google doc from the template in filename

    This method is only called when adding a new trip.

    This first alters the template document to have the trip info stored on the
    first line of the file. It then proceeds to set up a client for the google
    docs interactions using my secret credentials.

    The edited template is uploaded with a generic name and the link to the
    document is shortened to be returned. The document is then found in the
    DocsList and the ACL permissions are altered so anyone can edit the file.

    Before returning the shortened link, the template is restored by removing
    the trip description from the first line.

    """

    link = ''
    add_first(prepend)

    client = gdata.docs.client.DocsClient(source='trailbot')
    client.ClientLogin(sekret_username, sekret_password, client.source)

    entry = client.Upload(filename, 'trip', content_type='text/plain')
    link = tinyurl.create_one(entry.GetAlternateLink().href)

    feed = client.GetDocList(
        uri='https://docs.google.com/feeds/default/private/full')
    doc_entry = feed.entry[0]

    scope = gdata.acl.data.AclScope(type='default')
    role = gdata.acl.data.AclRole(value='writer')
    acl_entry = gdata.docs.data.Acl(scope=scope, role=role)
    client.Post(acl_entry, doc_entry.GetAclFeedLink().href)

    remove_first()

    return link
示例#12
0
def dedocify(to_remove):
    """trashes a matching google doc from my account

    This method is called when removing a trip with keywords about the trip.
    After logging in to the google account, the DocsList feed is searched for
    files containing the trip keywords, then the matching file is trashed.

    A matching trip has already been found when this method is called, so as
    long as the google doc was generated when the trip was added, a match
    should be found to trash.

    """

    client = gdata.docs.client.DocsClient(source='trailbot')
    client.ClientLogin(sekret_username, sekret_password, client.source)

    search = to_remove.replace(' ', '+')
    urluri = 'https://docs.google.com/feeds/default/private/full?q=' + search
    feed = client.GetDocList(uri=urluri)

    if feed.entry:
        doc_entry = feed.entry[0]
        client.Delete(doc_entry)
示例#13
0
文件: simple.py 项目: alfaceor/ceor
import gdata.docs.data
import gdata.docs.client

client = gdata.docs.client.DocsClient(source='myapp_ceor-v0')
client.ssl = True
client.http_client.debug = False
client.ClientLogin('*****@*****.**', 'password', client.source)


def PrintFeed(feed):
    print '\n'
    if not feed.entry:
        print 'No entries in feed.\n'
    for entry in feed.entry:
        print entry.title.text.encode(
            'UTF-8'), entry.GetDocumentType(), entry.resource_id.text

        # List folders the document is in.
        for folder in entry.InFolders():
            print folder.title


feed = client.GetDocList(
    uri='/feeds/[email protected]/private/full?showfolders=true')
PrintFeed(feed)

#new_folder= client.Create(gdata.docs.data.FOLDER_LABEL, 'Research')
import gdata.data
ms = gdata.data.MediaSource(
    file_path='/home/alfaceor/Research/Eskeleton_ProteinFolding.txt',
    content_type='text/plain')
示例#14
0
 if args.dryRun:
     LOG.info(
         "Dry Run enabled - No modification will be made to your documents")
 LOG.info("System Encoding              : %s" % sys.getfilesystemencoding())
 LOG.info(
     "====================================================================")
 LOG.info("ATTENTION : SEUL LES DOCUMENTS APPARTENANT A " + args.login +
          " SERONT RECUPERES !!!")
 LOG.info(
     "====================================================================")
 raw_input("ENTREE pour continuer, ou CTRL+C pour annuler...")
 LOG.info("Connexion sur le serveur Google...")
 client = gdata.docs.client.DocsClient(source="jgraglia-gdocsbackup-v1")
 client.ssl = True
 client.http_client.debug = args.debug
 client.ClientLogin(args.login, args.password, client.source)
 LOG.info("    -> succès")
 LOG.info("Récupération de la liste des documents appartenant à %s" %
          args.login)
 feed = client.GetEverything(uri='/feeds/default/private/full/-/mine')
 spreadsheets_client = gdata.spreadsheet.service.SpreadsheetsService()
 spreadsheets_client.ClientLogin(args.login, args.password)
 #client.auth_token = gdata.gauth.ClientLoginToken(spreadsheets_client.GetClientLoginToken())
 login = args.login
 stats = downloadFeed(
     client, client.auth_token,
     gdata.gauth.ClientLoginToken(
         spreadsheets_client.GetClientLoginToken()), feed, folder,
     args.flat, args.ignore)
 LOG.info(
     "Storing log in backup folder (contains important ownership and share infos, that you could use when re-importing documents)"
示例#15
0
import gdata.docs.service


class SampleConfig(object):
    APP_NAME = 'GDataDocumentsListAPISample-v1.0'
    DEBUG = False


def PrintResource(resource):
    """Display a resource to Standard Out."""
    print resource.resource_id.text, resource.GetResourceType()


client = gdata.docs.client.DocsClient(source=SampleConfig.APP_NAME)
client.ClientLogin('*****@*****.**', 'vum-v0d7xaju', "", "")


def PrintFeed(feed):
    print '\n'
    if not feed.entry:
        print 'No entries in feed.\n'
    for entry in feed.entry:
        print entry.title.text.encode(
            'UTF-8'), entry.GetDocumentType(), entry.resource_id.text

        # List folders the document is in.
        for folder in entry.InFolders():
            print folder.title

classcode=
assignment=

# Connect to Google-Spreadsheet
gd_client = gdata.spreadsheet.service.SpreadsheetsService()
gd_client.email = username
gd_client.password = password
gd_client.source = 'OpenSource-CreateDocs-v1'
gd_client.ProgrammaticLogin()

# Connect to Google-DocList
client = gdata.docs.client.DocsClient(source='OpenSource-CreateDocs-v1')
client.ssl = True
client.http_client.debug = False
client = gdata.docs.client.DocsClient(source='OpenSource-CreateDocs-v1')
client.ClientLogin(username, password, client.source);

#
q = gdata.spreadsheet.service.DocumentQuery()
q['title'] = students_data
q['title-exact'] = 'true'
feed = gd_client.GetSpreadsheetsFeed(query=q)
spreadsheet_id = feed.entry[0].id.text.rsplit('/',1)[1]
feed = gd_client.GetWorksheetsFeed(spreadsheet_id)
worksheet_id = feed.entry[0].id.text.rsplit('/',1)[1]
rows = gd_client.GetListFeed(spreadsheet_id, worksheet_id).entry
for row in rows:
 firstname=row.custom['firstname'].text
 lastname=row.custom['lastname'].text
 email=row.custom['email'].text
 title_doc=assignment+' - '+lastname
示例#17
0
else:
    file_on_disk = args.fl
if args.fg is None:
    file_on_google = os.path.basename(file_on_disk)
else:
    file_on_google = args.fg

client = gdata.docs.client.DocsClient(source=source)
client.http_client.debug = False
client.http_client.ssl = True
login = False

while login is False:
    try:
        login = True
        client.ClientLogin(email, password, source)
    except gdata.client.CaptchaChallenge as captcha:
        captcha_token = captcha.captcha_token
        captcha_url = captcha.captcha_url
        print "Need to complete captcha challenge at this URL: " + captcha_url
        captcha_response = raw_input("Please type the answer: ")
        try:
            client.ClientLogin(email,
                               password,
                               source,
                               captcha_token=captcha_token,
                               captcha_response=captcha_response)
            login = True
        except gdata.client.CaptchaChallenge:
            print "Captcha check failed."
            login = False
示例#18
0
文件: client.py 项目: arfrank/Locker
import sys
import os
import gdata.docs.data
import gdata.docs.client
import gdata.spreadsheet.service

#gd_client.email = sys.argv[1]
#gd_client.password = sys.argv[2]

client = gdata.docs.client.DocsClient(source='yourCo-yourAppName-v1')
client.ssl = True  # Force all API requests through HTTPS
client.http_client.debug = False  # Set to True for debugging HTTP requests

client.ClientLogin(sys.argv[1], sys.argv[2], client.source)

spreadsheets_client = gdata.spreadsheet.service.SpreadsheetsService(
    source='yourCo-yourAppName-v1')
spreadsheets_client.ClientLogin(sys.argv[1], sys.argv[2], client.source)

# substitute the spreadsheets token into our client
docs_token = client.auth_token
ss_token = gdata.gauth.ClientLoginToken(
    spreadsheets_client.GetClientLoginToken())


def PrintFeed(feed):

    doc_dir = "my/{0}".format(sys.argv[1])

    try:
        os.makedirs(doc_dir)
示例#19
0
    def handle(self, *args, **options):
        if not GOOGLE_DOCS_ACCOUNT and GOOGLE_DOCS_PASSWORD and GOOGLE_DOCS_RESOURCE_ID:
            raise CommandError(
                'You must set both GOOGLE_DOCS_ACCOUNT, GOOGLE_DOCS_PASSWORD and GOOGLE_DOCS_RESOURCE_ID in your settings file.'
            )
        verbosity = int(options.get('verbosity', 1))
        output_all = options.get('output_all')
        dry_run = options.get('dry_run')
        fields = ('email', 'first_name', 'last_name', 'phone', 'city', 'state',
                  'zipcode', 'is_a', 'broadcasters', 'date_created',
                  'share_info')

        profile_list = NonUserProfile.objects.order_by('-date_created')
        if not output_all:
            profile_list = profile_list.filter(share_info=True)

        if len(profile_list):
            if verbosity > 1:
                self.stdout.write('{0} signups to record.'.format(
                    len(profile_list)))
            fp = NamedTemporaryFile(delete=False)
            writer = csv.DictWriter(fp, fields)
            writer.writeheader()

            for signup in profile_list:
                output = {
                    'email':
                    signup.email,
                    'first_name':
                    signup.first_name,
                    'last_name':
                    signup.last_name,
                    'phone':
                    signup.phone,
                    'city':
                    signup.city,
                    'state':
                    signup.state,
                    'zipcode':
                    signup.zipcode,
                    'is_a':
                    signup.is_a,
                    'date_created':
                    signup.date_created.strftime('%m/%d/%Y %H:%M:%S'),
                    'share_info':
                    signup.share_info
                }
                extra_fields_data = signup.extra_fields
                for extra_field in SIGNUP_EXTRA_FIELDS:
                    input_val = None
                    if isinstance(extra_fields_data[extra_field], list):
                        input_val = ', '.join(extra_fields_data[extra_field])
                    else:
                        input_val = extra_fields_data[extra_field]
                    output[extra_field] = input_val
                writer.writerow(output)
            if dry_run:
                self.stdout.write('Row created:\n{0}\n'.format('|'.join(
                    [str(output[f]) for f in fields])))
            del (writer)

            if not dry_run:
                client = gdata.docs.client.DocsClient()
                login_token = client.ClientLogin(GOOGLE_DOCS_ACCOUNT,
                                                 GOOGLE_DOCS_PASSWORD,
                                                 'politicaladsleuth')
                fp.close()
                media = gdata.data.MediaSource(file_path=fp.name,
                                               content_type='text/csv')
                try:
                    resource = client.get_resource_by_id(
                        GOOGLE_DOCS_RESOURCE_ID)
                    updated_resource = client.update_resource(
                        resource,
                        media=media,
                        update_metadata=False,
                        new_revision=True)
                    self.stdout.write('Data uploaded to "%s"\n'.format(
                        updated_resource.title.text))
                except gdata.client.RequestError as e:
                    self.stderr.write(e.message + '\n')
                    self.stdout.write(
                        '****Upload may have succeeded despite an InvalidEntryException error****\n'
                    )

            fp.close()
            fp.unlink(fp.name)
        else:
            self.stdout.write('No signups for the given parameters\n')