PaulJ
PaulJ

Reputation: 1718

Google Drive API: how to find files *not* shared with me?

I'm trying to get a list of all the files that I have in the root folder of my Google Drive, excluding those shared with me... and yet Google Drive keeps giving me both the files in my root folder and the shared ones.

I am using this search query (Python code):

results = service.files().list(
   q="(name contains 'zip' or name contains 'gz') and 'root' in parents and 'me' in owners", fields="files(id, name, parents, owners)").execute()
items = results.get('files', [])

print('Files:')
for item in items:
   print(u'{0}   {1}   {2}'.format(item['name'], item['owners'], item['parents']))

Looking at the docs, it seems that I'm doing everything right:

And yet, in the list of files I get back, I have stuff like this:

backup_2020-04-15-1033.zip   [{'kind': 'drive#user', 'displayName': 'OTHER USER'S NAME', 'me': False, 'permissionId': 'XXXXXXXXXX', 'emailAddress': '[email protected]'}]   ['{FOLDER ID OBSCURED']

This is one of the shared files; notice the 'me': False there. Also, although I obscured the parent folder, it's different than the ID of my root folder. In other words: this file should have not been returned?

Is this a Google Drive bug? How can I search only for my files then?

Upvotes: 0

Views: 704

Answers (1)

ravioli
ravioli

Reputation: 3833

ziganotschka's comment to use the "in owners" query filter worked for me too. Posting example:

def get_google_service(service, version, permissions = ['read'], credentials = None):
    return build(serviceName=service, version=version, credentials=credentials)

class GoogleService(object):

    connection = None

    def __init__(
        self, 
        service = 'drive', 
        version = 'v3', 
        permissions = ['read'], 
        autoconnect = True, 
        *args, 
        **kwargs
    ):
        super(GoogleService, self).__init__()

        self.service = service
        self.version = version
        self.permissions = permissions
        self.owner = '[email protected]' # use your account here

        # Connect automatically
        if autoconnect:
            self.connect()

    def connect(self):
        self.connection = get_google_service(
            service = self.service, 
            version = self.version, 
            permissions = self.permissions
        )

class GoogleDrive(GoogleService):

    def __init__(self, service='drive', version='v3', *args, **kwargs):
        super(GoogleDrive, self).__init__(service, version, *args, **kwargs)

    def get_files(
        self, 
        scope = "user", 
        driveid = None, 
        fields = 'files({0})'.format(GD_FILE_FIELDS), 
        spaces = "drive", 
        paginateflag = False, 
        ownerfilesonlyflag = True,
        searchquery = '', 
        **kwargs
    ):

        if ownerfilesonlyflag:
            searchquery += (' and ' if searchquery else '') \
                        +  "'" + self.owner + "'" + ' in owners'

        # Include nextPageToken
        fields = "nextPageToken" + ("," + fields if fields else '')

        # Map parameters to Google API
        params = {
            'driveId' : driveid, 
            'corpora' : scope, 
            'fields' : fields, 
            'spaces' : spaces, 
            'q' : searchquery, 
            **kwargs
        }

        # Return all results at once
        if not paginateflag:
            result = []
            pagetoken = None

            while True:
                
                # Use pagetoken from previous iteration
                if pagetoken:
                    params['pageToken'] = pagetoken

                # Retrieve / store next file batch
                files = self.connection.files().list(**params).execute()
                result.extend(files['files'])
                
                pagetoken = files.get('nextPageToken')

                if not pagetoken:
                    break
            
            return result

        # Paginate
        else:
            return self.connection.files().list(**params)

Upvotes: 0

Related Questions