'Set file permissions with Google App Script

I regularly need to change file share permissions on large numbers of files on Google Drive. I would rather not have to do this manually on a file by file basis. I have no issues extracting the File IDs, but can't seem to find any information associated with setting permissions for specific users.

Suppose I have a file with ID - 1132asdfasdf5sdf564sdf Suppose I have a user named John Smith whose email address is [email protected] and this user is a Google user.

Here's a sample script:

function myFunction() {      
  // this grabs the ID of the source file
  var sourcefile=DriveApp.getFileById("1132asdfasdf5sdf564sdf");      
}

Question. Once I grab the file by ID, is it possible to set either edit or view permissions for this specific user?



Solution 1:[1]

I haven't tried this, but I would imagine you could use addviewer(email) or addeditor(email). There is also an option for multiple emails.

source: https://developers.google.com/apps-script/reference/drive/file#methods

Solution 2:[2]

You can try to use the Drive Service. This service allows scripts to create, find, and modify files and folders in Google Drive.

// Log the name of every file in the user's Drive.
var files = DriveApp.getFiles();
while (files.hasNext()) {
  var file = files.next();
  Logger.log(file.getName());
}

By using the enum permission, that represents the permissions granted to users who can access a file or folder, besides any individual users who have been explicitly given access. These properties can be accessed from DriveApp.Permission.

  • VIEW - Users who can access the file or folder are able only to view it or copy it. Passing this value to File.setSharing(accessType, permissionType) throws an exception if the type of file does not support it.

  • EDIT - Users who can access the file or folder are able to edit it. Unless File.setShareableByEditors(shareable) is set to false, users can also change the sharing settings. Passing this value to File.setSharing(accessType, permissionType) throws an exception if the type of file does not support it.

Try also to check this SO question for more information.

Solution 3:[3]

Are you replacing old users with new ones in the permission scheme? If you are, you need to invoke the File or Document class methods removeEditor(s) or removeViewer(s), and then follow up with addEditor(s) or addViewer(s).

The problem with using built in methods (as far as I can tell) is that it is difficult to stop a blizzard of email notifications going out to the users if you are doing bulk permission inserts. You can use the flexibility of the Drive API to specifically stop email notifications, but may experience with calling the Drive API is that it eats up a lot of time.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Community
Solution 3 Dharman