无法使用 Google 驱动器 API 获取文件所有者

Can't get File Owner using Google Drive API

试图通过获取文件的权限找到文件的所有者,遍历它们,并检索具有 "owner" 角色的权限的用户信息(特别是电子邮件地址)。

PermissionList filePermissions = service.permissions().list(fileID).execute();

for (Permission permission : filePermissions) {

    if (permission.getRole().toLowerCase().equals("owner")) {
        String fileOwner = permission.getEmailAddress();
    }

}

"permission.getEmailAddress()" 一直返回 null,所以我决定在每个权限上调用 "toPrettyString()",它表明权限对象只始终包含 "id"、"kind"、"role" 和 "type",但从来没有 "emailAddress"。

Google documentation for the Drive API 将 "emailAddress" 列为权限对象的属性之一,所以我很困惑为什么我无法检索它。

我认为这可能与用于获取 Drive Service 的用户凭据有关,但即使使用文件所有者的凭据仍然会产生相同的结果。

如果您用于 运行 该程序的用户帐户与文件所有者位于不同的 GSuite(Google 应用程序)域中,那么您将无权访问他们的电子邮件地址。您的选择是:

  1. 使用显示名称代替电子邮件地址。
  2. 运行 您的程序在同一个 GSuite 域中有一个 Google 帐户
  3. 运行 您的程序具有能够模拟 GSuite 域用户的授权(请参阅标题为 "Delegating domain-wide authority to the service account" here
  4. 的部分

Google Drive REST APIs v3 只会 return 某些默认字段。如果你需要一些字段,你必须通过 .setFields() 方法设置它来明确请求它。

像这样修改你的代码 -

PermissionList filePermissions = service.permissions().list(fileID).setFields('permissions(emailAddress,id,kind,role,type)').execute();

您可以在此处阅读有关此行为的更多信息 https://developers.google.com/drive/v3/web/migration

引用上面link -

Notable changes

  • Full resources are no longer returned by default. Use the fields query parameter to request specific fields to be returned. If left unspecified only a subset of commonly used fields are returned.

如果答案对您有用,请采纳,这样面临此问题的其他人也可能受益。

Drive API Permission resource 有四种类型。

  • user
  • group
  • domain
  • anyone

emailAddress 字段仅在类型为 usergroup 时出现,而 domain 字段仅在类型 domain 上出现。

还要确保您使用 fields 查询参数明确要求 emailAddress 字段。