简体   繁体   中英

Query Google Drive folder and change sharing permission

New to the Google Drive API and I'm wondering if you can query a Google Drive folder and bulk-change the sharing permissions. The company I work for has been sharing files externally but nobody has kept track of the files. Once projects get archived we want to make sure that none of the files are still shared. I've been checking the API documentation but can only find bits and pieces of what I'm trying to achieve. Can someone point me in the right direction? I'm sure this must have been done before.....

Kind Regards!

Edit:

Here is the code as I have it now. As per my comment below, I'm getting a Gradle error saying deprecated Gradle features were used.

import com.google.api.client.auth.oauth2.Credential;
importcom.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalleApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class DrivePerms {
    private static final String APPLICATION_NAME = "Google Drive API Java Quickstart";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String TOKENS_DIRECTORY_PATH = "tokens";

    /**
     * Global instance of the scopes required by this quickstart.
     * If modifying these scopes, delete your previously saved tokens/ folder.
     */
    private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
    private static final String CREDENTIALS_FILE_PATH = "/credentials.json";

    /**
     * Creates an authorized Credential object.
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws IOException If the credentials.json file cannot be found.
     */
    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        // Load client secrets.
        InputStream in = DrivePerms.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (in == null) {
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("offline")
                .build();
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
        return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
    }

    public static void main(String... args) throws IOException, GeneralSecurityException {
        // Build a new authorized API client service.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();

        // Print the names and IDs for up to 10 files.
           FileList result = service.files().list()
                .setFields("nextPageToken, files(id, name)")
                .setQ("'Folder ID'")
                .execute();
         for (File file : files){

        System.out.println("File: " + file.getName());
        PermissionList result2 = service.permissions().list(file.getId())
                .execute();

        List<Permission> permsList = result2.getPermissions();
            }
        for (Permission perms : permsList){
            Permission roles  = service.permissions().get(file.getId(), perms.getId())
                    .setFields("emailAddress, role")
                    .execute();
            System.out.println("Email: " + roles.getEmailAddress());
            System.out.println("Role: " + roles.getRole());
            System.out.println("-----------------------------------");


        }

    }
}

You can list the Permissions of a Drive file and you can alsoiterate through the files of a folder. You will then need to get each one of the Permissions in order to retrieve the EmailAddress and the Role .

I assume you are using Java, so if we take a look at the Quickstart , we can use it to set the credentials and tokens for the Script and ignore the rest of the code.

public class DrivePerms {
private static final String APPLICATION_NAME = "Google Drive API Java Quickstart";

    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String TOKENS_DIRECTORY_PATH = "tokens";

    /**
     * Global instance of the scopes required by this quickstart.
     * If modifying these scopes, delete your previously saved tokens/ folder.
     */
    private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
    private static final String CREDENTIALS_FILE_PATH = "/credentials.json";

    /**
     * Creates an authorized Credential object.
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws IOException If the credentials.json file cannot be found.
     */
    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        // Load client secrets.
        InputStream in = DrivePerms.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (in == null) {
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("offline")
                .build();
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
        return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
    }

Notice I omitted the "imports", you can use the ones from the Quickstart. Also, the Scopes are set to .Drive instead of .DRIVE_METADATA_READONLY .

In the main Class I'm declaring the HTT_TRANSPORT and the Drive service (just like in the Quickstart):

public static void main(String... args) throws IOException, GeneralSecurityException {
    // Build a new authorized API client service.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build();

Then:

  1. List the files of the folder
     FileList result = service.files().list()
                .setFields("nextPageToken, files(id, name)")
                .setQ("'your folder Id' in parents")
                .execute();
        List<File> files = result.getFiles();
  1. Get the List of permissions of each file
 for (File file : files){

        System.out.println("File: " + file.getName());
        PermissionList result2 = service.permissions().list(file.getId())
                .execute();

        List<Permission> permsList = result2.getPermissions();
  1. Get each permission of the permission list and print the results:
for (Permission perms : permsList){
            Permission roles  = service.permissions().get(file.getId(), perms.getId())
                    .setFields("emailAddress, role")
                    .execute();
            System.out.println("Email: " + roles.getEmailAddress());
            System.out.println("Role: " + roles.getRole());
            System.out.println("-----------------------------------");


        }

    }
}

I hope this is helpful!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM