Accessing shared drive with DriveApp - google-apps-script

I am trying to create a new file in a shared drive using google apps script so that other people using the shared drive can also access the file. Is there a method on DriveApp that allows me to do that?
I have tried using DriveApp.getFoldersByName but this is for the root folder in my private drive only.

You need to use the Advanced Drive Service based on the Drive API
The method Drive.Drives.insert allows you to specify the Drive Id.
Keep in mind that for shared drives, you need to specify the
additional parameter supportsAllDrives: true. Also, you need to enable the Advanced Drive Service before using.
Sample:
function myFunction() {
var optionalArgs={supportsAllDrives: true};
var resource = {
title: 'mySharedFile',
mimeType: 'application/pdf',
parents:[{
"id": "ID OF THE SHARED DRIVE"
}]
}
Drive.Files.insert(resource, null, optionalArgs)
}

Related

Get file permissions list in Google Shared Drive with Apps Script

I'm trying to get folder and file permissions which is located in Shared Drive. All I can get is permissions list for root Shared Drive but trying to run below code on any ID of file or folder inside throw error.
Relavant Facts
We are using Google Workspace Business Plus subscription
I am domain superadmin
I have access to this file in Shared Drive but I expect to have access to every file as an domain admin.
Right now I'm calling the below script from web IDE of Apps Script so it is working in my grant scope.
I am the script owner
Script is on My rive
Script
function getPermissions_(driveFileID, sharedDriveSupport){
var thisDrivePermissions = Drive.Permissions.list(
driveFileID,
{
useDomainAdminAccess: USE_DOMAIN_ADMIN_ACCESS,
supportsAllDrives: sharedDriveSupport
}
);
return thisDrivePermissions;
}
Errors
GoogleJsonResponseException: API call to drive.permissions.list failed with error: Shared drive not found: xxxxxxxx
GoogleJsonResponseException: API call to drive.permissions.list failed with error: File not found:
How can I get the file permissions list in Google Shared Drive with Apps Script?
As superadminin you don't have access to all files by default through Google Drive user interface / Google Apps Script. In order to get access to all files in your domain throught Apps Script you have to make use of domain-wide deletegation of authority.
The "not found" errors might occur because the file or shared drive ids are wrong or you don't have access, do double check that the ids are correct and that you passing the parameters correctly. For this you could use Logger.log
/ console.log to print the variable values to the execution log or use the Apps Script debugger.
Related
How to add a Google Drive folder to "My Drive" section to other users
Take ownership of other users Drive-files using Google Apps Script
If I understand correctly, you need to list all the permissions that a drive file contained in a folder from a shared drive has. To do that, you may check the following script as an example:
function myFunction() {
var driveFileID = "FILE ID";
var sharedDriveSupport = true;
var request = {
"supportsAllDrives": sharedDriveSupport,
"useDomainAdminAccess": true,
"fields": "permissionIds"
};
var permissionsRequest = {
"supportsAllDrives": sharedDriveSupport,
"fields": "role"
};
var permissionsIDs = Drive.Files.get(driveFileID, request);
for(var i=0; i<permissionsIDs.permissionIds.length; i++)
{
Logger.log((Drive.Permissions.get(driveFileID, permissionsIDs.permissionIds[i], permissionsRequest)).role);
}
}
This is how it would display the information, by listing all the permission types from the specified file:
Note that this works because you mentioned you have access to the shared drive, however as Rubén mentioned in his answer Google Workspace admins do not have access to all the files, just to the ones that are shared with them, and if you want to have access you can do it using domain wide delegation and user impersonation.
References:
Files: get
Permissions: get

Google Drive API - Adding new users to Shared Drive

I am using a Google App Script to automate the creation of some Google Accounts inside our of our domain. I have been having a little trouble with some of the API calls and such, however this question is more related to whether or not the Drive API gives me the ability to do something. I have code below that adds editor permissions to the new user for their needed Shared Drives, however I would like to give them 'Content Manager' access to the Shared Drive. From the documentation I have looked at it, it does not seem like this is possible using the Google Drive API however I wanted to ask here to make sure I am not missing something when proceeding with the rest of my automation.
switch(ssValues[i][9]){
case "Accounting":
AdminDirectory.Members.insert(groupMember, "notourcompany");
DriveApp.getFolderById("TH1SDR!v3").addEditor(email);
break;
Does not matter if I need to use a different method or another API to achieve this functionality, I just want to know if it is possible to do this using their API's or SDK's through an App Scripts project.
Documentation:
Folder Class-https://developers.google.com/apps-script/reference/drive/folder
Drive API - Drives - https://developers.google.com/drive/api/v3/reference/drives
Drive API - Permissions - https://developers.google.com/drive/api/v3/reference/permissions
It should be possible to manage users over a Shared Drive utilizing the Drive API. The important thing is that you would need to give access over the API and make sure the parameter or argument for supportsAllDrives is set to true.
There is a sample Java code over the official documentation that shows how you can add permissions to a Shared Drive that is "orphaned" or you can test it over it in the permission.create documentation:
You can test it yourself over here.
As you can see in the image, the function is very similar to the code that was created on an old thread utilizing the Drive API V2, however it is using the argument supportsTeamDrive. Sample code that could be edited:
Edit:
I have updated the code based on the one suggested from the thread to a more simplify version.
// Using Apps Script with Advance Google Services v2 of the Drive API enable
function insertPermission() {
const sharedid= 'sharedDriveID' //ID of the Shared Drive
var resource = {
// enter email address here
value: 'emailtest#domain.com',
type: 'user',
// choose from: "owner" or "fileOrganizer". File Organizer would basically be the contentManager of a SharedDrive.
role: 'fileOrganizer'
};
var optionalArgs = {
sendNotificationEmails: false,
supportsAllDrives: true
};
Drive.Permissions.insert(resource, sharedid, optionalArgs);
}
You can review the thread and code here.
References
https://developers.google.com/drive/api/v3/reference/permissions/create
https://developers.google.com/drive/api/guides/manage-shareddrives
I agree with Ricardo Jose Velasquez Cruz. I'm a super admin in my org and this solution finally allowed it to work for me. I had to tweak the optionalArgs to include useDomainAdminAccess.
// Using Apps Script with Advance Google Services v2 of the Drive API enable
function insertPermission() {
const sharedid= 'sharedDriveID' //ID of the Shared Drive
var resource = {
// enter email address here
value: 'emailtest#domain.com',
type: 'user',
// choose from: "owner" or "fileOrganizer". File Organizer would basically be the contentManager of a SharedDrive.
role: 'fileOrganizer'
};
var optionalArgs = {
useDomainAdminAccess: true,
sendNotificationEmails: false,
supportsAllDrives: true
};
Drive.Permissions.insert(resource, sharedid, optionalArgs);
}

Copy a Google Apps Script-file using... Google Apps script into a teamDrive

I'm trying to place a copy of a Google Apps Script-file in a shared drive using apps script.
My code looks like this:
function copyFileToSharedDrive(){
var sharedDriveId = "sharedriveidcomeshere";
var sharedDrive = DriveApp.getFolderById(sharedDriveId);
var appsScriptFileId = "appsscriptfileidcomeshere";
DriveApp.getFileById(appsScriptFileId).makeCopy(sharedDrive).setName("This is a copy of the original apps script file");
}
The result, however, is a copy of the apps script file, but it's in my root folder of my Google Drive, instead of in the Shared Drive.
If I do the exact same thing with a Spreadsheet, Google Doc or Slides, the code works like a charm.
I also tried the Advanced Google Services and used the Drive API. No luck there... File is still being created in the root folder of the user executing the code.
Drive.Files.copy(
{title: "This is a copy of the appsscript file", parents: [{id: sharedDriveId}]},
"appsScriptFileId",
{supportsAllDrives: true}
);
Any help?
How about this answer?
Modification points:
Unfortunately, the Google Apps Script file cannot be directly copied to the shared Drive using makeCopy. The file is copied to the root drive of MyDrive. I think that this might be a bug.
So in this case, how about using Drive API? When your script is modified, it becomes as follows.
Modified script:
Before you run the script, please enable Drive API at Advanced Google services.
function copyFileToSharedDrive(){
var sharedDriveId = "sharedriveidcomeshere";
var appsScriptFileId = "appsscriptfileidcomeshere";
Drive.Files.copy(
{title: "This is a copy of the original apps script file", parents: [{id: sharedDriveId}]},
appsScriptFileId,
{supportsAllDrives: true}
);
}
References:
Advanced Google services
Files: copy
Added:
You want to copy a Google Apps Script file to the specifc folder in the shared Drive.
For this, how about the following script? In this script, the following flow is used.
Copy the Google Apps Script file. At this time, the file is created to the root folder.
Move the GAS file to the specific folder in the shared Drive using the Files.patch method of Drive API.
Sample script:
function copyFileToSharedDrive(){
var destinationFolderId = "###"; // Please set the destination folder ID of shared Drive.
var appsScriptFileId = "###"; // Please set the GAS script ID.
var file = DriveApp.getFileById(appsScriptFileId)
var copiedFile = file.makeCopy().setName(file.getName()).getId();
Drive.Files.patch(
{title: "This is a copy of the original apps script file"},
copiedFile,
{removeParents: "root", addParents: destinationFolderId, supportsAllDrives: true}
);
}
Note:
About supportsAllDrives, the official document says as follows.
Deprecated - Whether the requesting application supports both My Drives and shared drives. This parameter will only be effective until June 1, 2020. Afterwards all applications are assumed to support shared drives.
By this, from June 1, 2020, even when supportsAllDrives is not used, the shared Drive can be used.
Reference:
Files: patch

How do I delete a specific type of file (CSV files) within a specific folder with google app script on a shared google drive folder

I am having trouble adding files to the shared google drive folder as well as not being able to remove specific types of files of any kind within my script. The shared google drive file gives me issues. The code below works for me on my own personal google drive folder for adding and removing CSV's from one google drive folder to any another that I specify. However, it does not work with our general shared google drive folder. I have been authorized permission via the google cloud console API for Drive & Sheets but I am still having permission issues. Any help or clarification on this issue would be greatly appreciated.
Here are two different pieces of code. The first one with function moveFiles() works on my personal drive but not in the shared folders. Here is also some more code that I was playing around with to test the shared folders in a simpler manner. I was able to get the putFile() function to put a newDoc inside a shared google drive folder but not able to remove it.
function moveFiles(source_folder, dest_folder)
{
// set current destination to grab the folder from
var currentFolder=DriveApp.getFolderById("1emSsRay_WI_z_qBUpQIoccxQID28FvB0");
// grab only the csv's within current folder
var docs = DriveApp.getFilesByType(MimeType.CSV);
// set target destination where we will store old csv's that have been processed & Analyzed
var destination = DriveApp.getFolderById("1wYG1Gd5z0-nucedSMOBn8ZJs68ZgR8Hb");
// iterate through the csv's files within the currentFolder, add them to the destination and remove them from the current folder
while (docs.hasNext())
{
var doc = docs.next();
destination.addFile(doc); // get error "Cannot use this operation on a shared drive item(line 13, file "SharedDriveMove")
currentFolder.removeFile(doc);
}
}
function putFile()
{
var newDoc = DocumentApp.create('Testing Team Drive MoveTo').getId();
var file = DriveApp.getFileById(newDoc);
var moveFile = DriveApp.getFolderById('1emSsRay_WI_z_qBUpQIoccxQID28FvB0').addFile(file);
}
function takeFile()
{
var filesIterator = DriveApp.getFilesByName('Testing Team Drive MoveTo');
while (filesIterator.hasNext())
{
var file = filesIterator.next();
}
var cleanup = DriveApp.getFolderById('1wYG1Gd5z0-nucedSMOBn8ZJs68ZgR8Hb').addFile(file,{"supportsAllDrives": true}); // get error "Cannot find method addFile(File,Object).(line 15,file"Code")
var moveFile = DriveApp.getFolderById('1emSsRay_WI_z_qBUpQIoccxQID28FvB0').removeFile(file,{"supportsAllDrives": true});
}
DriveApp is an Apps Script class whereby it has it's limitations among Drive. Also, as the documentation says:
This method does not delete the file, but if a file is removed from
all of its parents, it cannot be seen in Drive except by searching for
it or using the "All items" view.
You should do it with the Drive API instead:
Use "supportsAllDrives", otherwise it won't find the file if it's in a Shared Drive (until this is deprecated in 2020).
Drive.Files.remove("your file ID", {"supportsAllDrives": true});
You also have to authorize the Drive.File scope.

How to set where SpreadsheetApp saves spreadsheet?

I am trying to save a spreadsheet to a specific folder on Drive using google app script. However, I cannot see a method that allows me to do so.
using:
SpreadsheetApp.create(name)
saves it directly to Drive, is there a way to save it in a folder?
Any help much appreciated.
How about these solutions? You can choose one of them freely.
SpreadsheetApp.create() cannot directly create in a special folder. It is created to the root folder. When you want to create new spreadsheet in a special folder, you can achieve using DriveApp and Drive API. The sample scripts are as follows.
1. Use DriveApp
When you use this, you can use by only copy and paste this to your script editor.
var fileId = SpreadsheetApp.create(name).getId();
var file = DriveApp.getFileById(fileId);
DriveApp.getFolderById("### folder ID ###").addFile(file);
file.getParents().next().removeFile(file);
Flow :
Create new spreadsheet to root folder.
Add a special folder to the parents of created spreadsheet.
Remove the root folder from the parents of created spreadsheet.
2. Use Drive API
This can create directly new spreadsheet to the special folder. When you use this, you can use by copy and paste this to your script editor. And then, please enable Drive API at Advanced Google Services and API console.
Drive.Files.insert({
"mimeType": "application/vnd.google-apps.spreadsheet",
"parents": [{"id": "### folder ID ###"}],
"title": name
});
Enable Drive API at Advanced Google Services
On script editor
Resources -> Advanced Google Services
Turn on Drive API v2
Enable Drive API at API console
On script editor
Resources -> Cloud Platform project
View API console
At Getting started, click Enable APIs and get credentials like keys.
At left side, click Library.
At Search for APIs & services, input "Drive API". And click Google Drive API.
Click Enable button.
References :
getParents()
addFile()
removeFile()
Advanced Google Services : https://developers.google.com/apps-script/guides/services/advanced
Drive API v2: https://developers.google.com/drive/v2/reference/
If I misunderstand your question, I'm sorry.
Updated at August 28, 2020:
By updating at July 27, 2020, addFile(File), addFolder(Folder), removeFile(File) and removeFolder(Folder) have been deprecated. Ref From July 27, 2020, file.moveTo(destination) and folder.moveTo(destination) are used.
By this, above sample script can be changed as follows.
From:
var folderId = "###";
var fileId = SpreadsheetApp.create("sample name").getId();
var file = DriveApp.getFileById(fileId);
DriveApp.getFolderById(folderId).addFile(file);
file.getParents().next().removeFile(file);
To:
var folderId = "###";
var fileId = SpreadsheetApp.create("sample name").getId();
var file = DriveApp.getFileById(fileId);
var folder = DriveApp.getFolderById(folderId);
file.moveTo(folder);
References:
file.moveTo(destination)
folder.moveTo(destination)