查询 Google Drive 文件夹并更改共享权限
Posted
技术标签:
【中文标题】查询 Google Drive 文件夹并更改共享权限【英文标题】:Query Google Drive folder and change sharing permission 【发布时间】:2020-02-10 23:13:18 【问题描述】:Google Drive API 的新手,我想知道您是否可以查询 Google Drive 文件夹并批量更改共享权限。我工作的公司一直在外部共享文件,但没有人跟踪这些文件。一旦项目被归档,我们希望确保没有文件仍然被共享。 我一直在检查 API 文档,但只能找到我想要实现的点点滴滴。 有人可以指出我正确的方向吗?我敢肯定这一定是以前做过的.....
亲切的问候!
编辑:
这是我现在拥有的代码。根据我在下面的评论,我收到一个 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("-----------------------------------");
【问题讨论】:
【参考方案1】:您可以list 驱动器文件的权限,也可以iterate 通过文件夹的文件。然后,您需要获取每一项权限才能检索EmailAddress
和Role
。
我假设您使用的是 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");
请注意,我省略了“导入”,您可以使用快速入门中的导入。此外,范围设置为 .Drive 而不是 .DRIVE_METADATA_READONLY。
在主类中,我声明了 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();
然后:
-
列出文件夹的文件
FileList result = service.files().list()
.setFields("nextPageToken, files(id, name)")
.setQ("'your folder Id' in parents")
.execute();
List<File> files = result.getFiles();
-
获取每个文件的权限List
for (File file : files)
System.out.println("File: " + file.getName());
PermissionList result2 = service.permissions().list(file.getId())
.execute();
List<Permission> permsList = result2.getPermissions();
-
Get权限列表中的每个权限并打印结果:
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("-----------------------------------");
希望对你有帮助!
【讨论】:
这是最有帮助的!谢谢你这么详细的回答。请给我一些时间来解决这个问题,经过多年不编码,我已经相当生疏了。 我一直在检查您的代码,这很有意义。不幸的是,我从 Gradle 收到构建失败错误,我似乎无法弄清楚发生了什么。据说“此版本中使用了已弃用的 Gradle 功能,使其与 Gradle 7.0 不兼容。”我将发布完整的代码。 这可能是因为我可能使用了一些旧的依赖项。看看this post的解决方案,看看是哪一行导致了这个问题。 啊哈!这需要一点时间,我会回来报告的。以上是关于查询 Google Drive 文件夹并更改共享权限的主要内容,如果未能解决你的问题,请参考以下文章
使用 Java 和 Google Drive API V3 将文件上传到共享的 Google Drive 位置?
如何将 Google Drive 推送通知响应链接到更改的文件
如何从Colab / Jupyter中的共享Google Drive链接获取文件?