Share a library by using google apps script - google-apps-script

To share spreadsheets and documents it is easy to write a script:
var sheet = SpreadsheetApp.openById("xxxxxxxxxxxxxxxxxxxxxxxx");
sheet.addViewer("email#gmail.com");
A libray ia a stand alone Google Apps Script file. Is there a comparable script to share such a file?

You can achieve it using DriveApp as follows.
var file = DriveApp.getFileById("xxxxxxxxxxxxxxxxxxxxxxxx");
file.addViewer("email#gmail.com");
If you want to share files as ANYONE, you can use the following sample.
var file = DriveApp.getFileById("xxxxxxxxxxxxxxxxxxxxxxxx");
file.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW);
References :
Access
Permission

Related

Apps Script - Search Gmail label for all attachments and overwrite files to google drive folder

Using prior articles and questions found within stack overflow I was able to find a snippet of App Script that searches Gmail labels for attachments and moves them to a specific folder in Google Drive.
function saveAttachmentInFolder(){
var folder = DriveApp.getFolderById('xxosi2');
var userId = "please.thanks#gmail.com";
var query = "label:thankyoucards-reports";
var res = Gmail.Users.Messages.list(userId, {q: query});//I assumed that this works
res.messages.forEach(function(m){
var attA=GmailApp.getMessageById(m.id).getAttachments();
attA.forEach(function(a){
folder.createFile(a.copyBlob()).setName(a.getName());
});
});
}
I need to modify this code to perform the following additional functions:
If file exists, overwrite and retain version history
I have also played around with the answer found in the following thread to no avail as I believe this is hard coded in some way and too specific to the one file type (xlsx) Copying attachments from Gmail to Google Drive folder and overwriting old files with Apps Script.
I believe your goal is as follows.
You want to check this using the filename between the existing file in the folder and the attachment file.
You want to overwrite the existing file with the attachment file.
In this case, how about the following modification? In this case, Drive API is used. So, please enable Drive API at Advanced Google services.
From:
folder.createFile(a.copyBlob()).setName(a.getName());
To:
var filename = a.getName();
var files = folder.getFilesByName(filename);
if (files.hasNext()) {
Drive.Files.update({}, files.next().getId(), a.copyBlob(), {supportsAllDrives: true});
} else {
folder.createFile(a.copyBlob()).setName(filename);
}
When this modified script is run, the existing file is searched from the folder using the filename of the attachment file. When the file is found, the file is overwritten by the attachment file. When the file is not found, the file is created as a new file.
Note:
In this modified script, the existing file is overwritten. So, please be careful about this. I would like to recommend using a sample file for testing the script.
Reference:
Files: update of Drive API v2

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

Rename appsscript project on duplication of spreadsheet

I'm duplicating spreadsheets based on a template file with attached appsscript project. Below you can see the basic code.
This works perfectly for the spreadsheets, but the name of the appsscript project remains the same as the template file. Which is a problem, as I can't distinguish them anymore. I will have hundreds of duplicates in the end.
Is there a way to set the appsscript project name on duplication?
Thank you in advance!
function copyTemplatev2(filename, sheetID) {
var ss = SpreadsheetApp.openById(sheetID);
//Make a copy of the template file
var copy = DriveApp.getFileById(sheetID).makeCopy()
var documentId = copy.getId();
// Set permissions
copy.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.EDIT)
//Rename the copied file
DriveApp.getFileById(documentId).setName(filename);
}
attached appsscript project of a template file with attached appsscript project is the container-bound script of Spreadsheet.
You want to rename the GAS project name of the container-bound script of Spreadsheet which was copied.
The Spreadsheet is used as the template, and the container-bound script is included in the Spreadsheet.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Issue and workaround:
The container-bound script of Google Docs cannot be retrieved by the methods of Files: list and Files: get in Drive API. This has already been reported to issue tracker.
The metadata of container-bound script of Google Docs can be updated by the method of Files: update in Drive API.
In your case, the GAS project ID (the script ID) is not changed because it is included in the template Spreadsheet. I think that this can be used for achieving your issue.
From above situation, I would like to propose the following flow.
Flow:
Set the variables of the container-bound script ID of the template Spreadsheet and the original project name of container-bound script ID of the template Spreadsheet.
Rename of the GAS project of the template Spreadsheet to the new project name.
Copy the template Spreadsheet. At this time, the GAS project is also copied as the new project name.
Rename of the GAS project of the template Spreadsheet to the original project name.
By above flow, the GAS project name of container-bound script in the copied Spreadsheet can be renamed.
When above workaround is reflected to your script, it becomes as follows.
Modified script:
Before you run the script, please enable Drive API at Advanced Google services. And please set the variables of GASProjectId, originalGASProjectName and newGASProjectName.
function copyTemplatev2(filename, sheetID) {
var GASProjectId = "###"; // Please set the container-bound script ID of the template Spreadsheet.
var originalGASProjectName = "originalName"; // Please set the original project name of container-bound script ID of the template Spreadsheet.
var newGASProjectName = "newName"; // Please set the new GAS project name.
// Rename to new project name.
Drive.Files.update({title: newGASProjectName}, GASProjectId);
var ss = SpreadsheetApp.openById(sheetID);
//Make a copy of the template file
var copy = DriveApp.getFileById(sheetID).makeCopy()
var documentId = copy.getId();
// Set permissions
copy.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.EDIT)
//Rename the copied file
DriveApp.getFileById(documentId).setName(filename);
// Rename to original project name.
Drive.Files.update({title: originalGASProjectName}, GASProjectId);
}
References:
Advanced Google services
Files: update
If I misunderstood your question and this was not the direction you want, I apologize.

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)

Reading xml-files on Google Drive using Apps Script

I have some XML-files saved on Google Drive. I want to save their content into a spreadsheet.
Google Apps Script should be the tool:
DriveApp locates files.
XmlService reads XML-files.
SpreadsheetApp stores the content.
I don't know how to read the content from a XML-file saved on Drive.
DriveApp gives a downloadUrl but GAS doesn't allow downloading files.
UrlFetchApp isn't authenticated.
It it impossible or is there a workaround?
here a little code that may help you:
function xmlRead(){
var id = "ID_OF_THE_FILE";
var rawXml = DriveApp.getFileById(id).getBlob().getDataAsString();
var xml = XmlService.parse(rawXml).;
// then it's your job to extract what you want from this XML
var ssid = "ID_OF_THE_SPREADSHEET";
var ss = SpreadsheetApp.openById(ssid);
ss.appendRow(["some stuff you extracted"]);
}