简体   繁体   English

查询 Google Drive 文件夹并更改共享权限

[英]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. Google Drive API 的新手,我想知道您是否可以查询 Google Drive 文件夹并批量更改共享权限。 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.我一直在检查 API 文档,但只能找到我想要实现的点点滴滴。 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.根据我下面的评论,我收到一个 Gradle 错误,说使用了不推荐使用的 Gradle 功能。

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.您可以列出Drive 文件的权限,也可以遍历文件夹的文件。 You will then need to get each one of the Permissions in order to retrieve the EmailAddress and the Role .然后您需要获取每一项 Permissions 以检索EmailAddressRole

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.我假设您使用的是 Java,因此如果我们查看Quickstart ,我们可以使用它来设置脚本的凭据和令牌,而忽略其余代码。

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 .此外,作用域被设置为.Drive而不是.DRIVE_METADATA_READONLY。

In the main Class I'm declaring the HTT_TRANSPORT and the Drive service (just like in the Quickstart):在主类中,我声明了 HTT_TRANSPORT 和 Drive 服务(就像在快速入门中一样):

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!我希望这是有帮助的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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