getOwner()在文件夹中的Google驱动器中失败

时间:2019-03-14 21:13:34

标签: google-apps-script google-drive-api

基本上,这是一个递归函数,它爬升文件的目录树,直到找到我不拥有的文件夹。问题是它根本不起作用!我遇到了两个不同的问题,1表示我确实拥有一个我不拥有的文件夹,2表示其他所有者未定义返回。

function returnParent(gDrive){
  //check if I own parent
  gDrive = getIdFromUrl(gDrive);
  Logger.log(gDrive);

  var file = DriveApp.getFileById(gDrive);
  var folders = file.getParents();
  // Logger.log(parents[0].getName());
  while (folders.hasNext()) {
    var folder = folders.next();
    var owner = folder.getOwner(); 
    Logger.log(owner+" "+ folder.getName());  
    if (owner=="DriveUser") {
      Logger.log("Still Me");
      return returnParent(folder.getId())
    }  
    else
      return owner.getName();
  }

对于最后一行,我尝试了返回所有者和return owner.getName();

1 个答案:

答案 0 :(得分:1)

您的代码存在的问题是,用于检查文件所有者是否为您的验证将不起作用,因为Owner对象将始终打印“ DriveUser”,因此条件始终为true,不会不管是谁。您需要使用getName()函数[1]更改该条件:

owner.getName() == "[Your name]"

或者更好的是,由于名称不一定是唯一的,因此可以使用getEmail函数[1]比较在同一G套件域下唯一的电子邮件:

owner.getEmail() == "[Your email]"

另外,您还需要根据要使用的ID设置使用getFileById()或getFolderById()[2]的条件。

最后,当您正在处理的文件夹是根文件夹时,我设置了另一个条件来停止递归功能:

folder.getName() == "My Drive"

这是我测试并成功运行的代码:

Code.gs:

//Initiate the recursive function with fileID
function test(){
  returnParent("[fileID]”, "file");
}

//recursive function until different owner or root folder
function returnParent(gDrive, type){
  // Commenting this because is not part of my answer.
  //check if I own parents
  //gDrive = getIdFromUrl(gDrive);
  //Logger.log(gDrive);

  if (type === "file") {
      var file = DriveApp.getFileById(gDrive);
  }
  else {
      var file = DriveApp.getFolderById(gDrive);
  }

  var folders = file.getParents();

  while (folders.hasNext()) {
    var folder = folders.next();
    var owner = folder.getOwner(); 
    Logger.log(owner.getName()+ " " + folder.getName());  
    if (owner.getEmail() == "Your email") { 
      Logger.log("Still Me");
      if ( folder.getName() == "My Drive") {
    // As example it will return this String.
          return "This is the root folder";
      }
      return returnParent(folder.getId(), "folder")
    } else {
       return owner.getName();
    }
  }
}

[1] https://developers.google.com/apps-script/reference/drive/user#getEmail()

[2] https://developers.google.com/apps-script/reference/drive/drive-app#getfolderbyidid