-1

Is there a method in google apps script to get the files of a suspended owner based on his/her email id? I am literally trying to implement transfer drive files to a new owner using google apps script, I am using this code to find the details of all the suspended users:

/**
 * Fetches the suspended user details from the AdminDirectory.
 */
function fetchUser() {
  // Set the constant options only once.
  const options = {
    domain: 'xyz.com',
    orderBy: 'email',
    query: 'isSuspended=true',
    maxResults: 500,
    fields: "nextPageToken,users"
  };
  // Could log the options here to ensure they are valid and in the right format.

  const results = [];
  do {
    var search = AdminDirectory.Users.list(options);
    // Update the page token in case we have more than 1 page of results.
    options.pageToken = search.nextPageToken;
    // Append this page of results to our collected results.
    if(search.users && search.users.length)
      Array.prototype.push.apply(results, search.users);
  } while (options.pageToken);
  //Logger.log(results);

  for(var k = 0; k < results.length; k++){
     var fullEmail = results[k].primaryEmail;
     Logger.log(fullEmail);
     fetchFiles(fullEmail);
  }
}

/**
 * Fetches the files of the suspended users based on their email.
 */
function fetchFiles(email){
  var pageToken;
    var filesList = Drive.Files.list({  // Invalid value error is thrown here, I am not sure if this the right way to use Drive API in google script
      domain: 'xyz.com',
      orderBy: 'email',
      q: "'email' in owners",
      maxResults: 500,
      pageToken: pageToken
    });  
  Logger.log('filesList:' +filesList);
}

I am trying to implement something like Transfer ownership of a file to another user in Google Apps Script, but is there some way by which I can fetch the files of the user from the details obtained from the above code which basically returns the following output:

[
  {
    orgUnitPath = /,
    ipWhitelisted = false,
    gender = {type = other},
    creationTime = 2017-06-13T14:38:44.000Z,
    isMailboxSetup = true,
    isEnrolledIn2Sv = false,
    kind = admin#directory#user,
    suspensionReason = ADMIN,
    isAdmin = false,
    suspended = true,
    emails = [{
      address = john.seb@xyz.com,
      primary = true
    }],
    lastLoginTime = 2017-09-12T00:27:00.000Z,
    isDelegatedAdmin = false,
    isEnforcedIn2Sv = false,
    changePasswordAtNextLogin = false,
    customerId = v12idsa,
    name = {
      givenName = John,
      familyName = Seb,
      fullName = John Seb
    },
    etag = "npJcgeAc7Xbfksfwer22344/sfasdfaffUDsfdsjfhsfhsdfw-ec",
    id = 1033392392142423424,
    primaryEmail = john.seb@xyz.com,
    agreedToTerms = true,
    includeInGlobalAddressList = true
  },
  ...
] 

I am trying to use the Drive API in the google apps script in order to access the files of suspended users using their email, but its throwing

"Invalid Value" error

for the line Drive.Files.list, I am not sure if this is the right way to use the DRIVE API in google script, is there any other way to use this api in google script?

merilstack
  • 703
  • 9
  • 29
  • `Drive API` -> `Files` -> `list` -> `"'email' in owners"` ? If the account you are running as doesn't have the right permissions I imagine that may not work 100% correctly. – tehhowch Jun 23 '18 at 06:59
  • I do have permissions, but how will `Drive API` -> `Files` -> `list` -> `"'email' in owners"` work? – merilstack Jun 23 '18 at 23:02
  • Exactly as the API documentation suggests... you write a search `q` for the email of the user you want to find files for. It'll show those files you can access. – tehhowch Jun 23 '18 at 23:46
  • @tehhowch can you specify the search query please? Because, I only found these methods: `getFileById(id)`, `getFiles()`, `getFilesByName(name)` and `getFilesByType(mimeType)` none of which accepts `email` . – merilstack Jun 24 '18 at 20:06
  • please re-read my comment - I am not referencing `DriveApp`. Construction of search queries for the Drive API's `Files.list` method is extensively covered in Drive API documentation. – tehhowch Jun 24 '18 at 21:40
  • Thank you for re-referencing it, but can you please help me out on how to use that here in Google apps script? Because I couldn't find on how to do a query with just `Drive API` in google apps script, the only one method which I formulated on my own is: `function fetchFiles(email){ var pageToken; var filesList = Drive.Files.list({ domain: 'xyz.com', orderBy: 'email', q: "'email' in owners", maxResults: 500, pageToken: pageToken }); }` I am not sure if it works. – merilstack Jun 25 '18 at 16:50
  • Note that you have a multitude of emails that correspond to the suspended users... try using those emails instead of the literal `'email'` – tehhowch Jun 25 '18 at 16:52
  • Yes, I am passing those multitudes of emails as a parameter `'email'` in the query. – merilstack Jun 25 '18 at 16:54
  • Thank you for re-referencing it, but can you please help me out on how to use that here in Google apps script? Because I couldn't find on how to do a query with just `Drive API` in google apps script, the only one method which I formulated on my own is: `function fetchFiles(email){ var pageToken; var filesList = Drive.Files.list({ domain: 'xyz.com', orderBy: 'email', q: "'email' in owners", maxResults: 500, pageToken: pageToken }); }` But It doesn't work and throws a `Invalid Value (line 86, file "Code")` error. – merilstack Jun 25 '18 at 17:00
  • we have no way to know what line 86 is. Please edit your question to be more specific and detailed – tehhowch Jun 25 '18 at 17:06
  • It throws the error for the line `Drive.Files.list`, I am thinking its primarily because there is no api called `Drive` in google script. – merilstack Jun 25 '18 at 18:08
  • The code in your original question uses the advanced service `AdminDirectory`. The Drive REST API is similarly an advanced service. You **still** have not edited your question to include the actual code you are using to try to list files. Include your MCVE! https://stackoverflow.com/help/how-to-ask – tehhowch Jun 25 '18 at 19:04
  • @tehhowch I am sorry for not giving a clear clarity, I have updated the question for more information. – merilstack Jun 25 '18 at 21:21
  • I have re-edited it and posted the question here for more reference: https://stackoverflow.com/q/51032383/4877962 – merilstack Jun 25 '18 at 22:05

1 Answers1

1

In your function fetchFiles, you never use the input argument email. Instead, you query the Drive REST API for the literal text 'email' in owners. Since the text string 'email' is not a valid email address, you correctly receive the error message "Invalid value".

Rather than this code:

/**
 * Fetches the files of the suspended users based on their email.
 */
function fetchFiles(email){
  var pageToken;
    var filesList = Drive.Files.list({
      domain: 'jerseystem.org',
      orderBy: 'email',
      q: "'email' in owners",
      maxResults: 500,
      pageToken: pageToken
    });  
  Logger.log('filesList:' +filesList);
}

You should perform the substitution first, to set up all constant options (as I mentioned and demonstrated in your other question), and then repeatedly query the Drive API for the files owned by the user with that email address:

function fetchAllFilesOwnedByEmail(email) {
  const searchParams = {
    corpora: 'some corpora',
    orderBy: 'some ordering criteria',
    q: "'" + email + "' in owners",
    fields: 'nextPageToken,items(id,title,mimeType,userPermission)'
  };

  const results = [];
  do {
    var search = Drive.Files.list(searchParams);
    if (search.items)
      Array.prototype.push.apply(results, search.items);
    searchParams.pageToken = search.nextPageToken;
  } while (searchParams.pageToken);
  return results;
}

You need to review the Drive REST API documentation, see Drive.Files.list and Search for Files at minimum. Don't forget to enable the Drive advanced service if you haven't.

Also note that while the above code will resolve the "Invalid Value" error you get, it won't necessarily make the user's files show up, even if you're executing the code as the G-Suite admin. Your research should have turned up at least these two related questions:

  1. How can an Admin access the Google Drive contents of all the users in a particular domain?
  2. Most efficient process for transferring ownership of all of a user's files using the Google Drive API
tehhowch
  • 9,645
  • 4
  • 24
  • 42
  • even though the [`Drive` in advanced service](https://developers.google.com/apps-script/guides/services/advanced) is enabled, it still throws **Invalid value** error for the line `Drive.Files.list(searchParams)` – merilstack Jun 26 '18 at 00:41
  • @JijoJohny And? If you log the current value of `searchParams` when the error is thrown, what do you find? When you reference the allowed `q` parameters in the `Search for Files` link I gave above, are you using valid values? When you reference the allowed parameters for `Files.list` (on the API reference link above), are you using only valid parameters? – tehhowch Jun 26 '18 at 00:44
  • It just returns `[object Object]` – merilstack Jun 26 '18 at 00:47
  • @JijoJohny Stop using `Logger.log` for complex objects - use Stackdriver Logging. You can also run in Debug mode, and the script will pause when an error occurs, which will let you inspect the call stack and active objects in each namespace. Debugging is a fundamental programming tool you MUST learn – tehhowch Jun 26 '18 at 00:49
  • I will do that for sure. In the Stackdriver logs it throws error `Invalid Value at fetchAllFilesOwnedByEmail(Code:99) at fetchUser(Code:73) at test(Code:13)` for `Drive.Files.list(searchParams)` – merilstack Jun 26 '18 at 00:58
  • After debugging the `searchParams` is returning `({corpora:"xyz", orderBy:"createdDate", q:"'alen.john@xyz.org' in owners", fields:"nextPageToken,items(id,title,mimeType,userPermission)"})` whereas `search` is returning `undefined` and `results` returns an empty array `[]` – merilstack Jun 26 '18 at 01:31
  • @JijoJohny note that `corpora` takes a very specific set of values, of which `xyz` is not a valid value. – tehhowch Jun 26 '18 at 01:52
  • thank you so much the error was because of the value to `corpora`, when I gave `domain` as value to it, even though it removes the error it returns an empty array `[]` for `results` and `search` – merilstack Jun 26 '18 at 02:36
  • @JijoJohny who are you executing as? If you cannot find these files in the Drive website when logged in as the user you are executing as, you cannot find them using the API. I mentioned this 2 days ago: https://stackoverflow.com/questions/50997602/fetch-the-files-of-suspended-users/51032859?noredirect=1#comment89005215_50997602 – tehhowch Jun 26 '18 at 02:42
  • I am executing as a G-Suite admin, do I need to have super admin privileges? – merilstack Jun 26 '18 at 03:19
  • @JijoJohny you have to be the user, really. https://stackoverflow.com/questions/37602929/how-can-an-admin-access-the-google-drive-contents-of-all-the-users-in-a-particul https://stackoverflow.com/questions/32344681/most-efficient-process-for-transferring-ownership-of-all-of-a-users-files-using These were very easy links to find! Please research! – tehhowch Jun 26 '18 at 03:37
  • thank you so much for your patience and pardon me for my lack of research. – merilstack Jun 26 '18 at 05:15