How to move a shortcut in google drive - file

I need to move a shortcut file from one destination to another using google apps script.
Usually I would move a file or folder like this:
function move(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sStamdata = ss.getSheetByName("New");
var folderOld = DriveApp.getFolderById(folderOldId);
var destination = DriveApp.getFolderById(folderId);
var id = sStamdata.getRange('D77').getValue();
var file = DriveApp.getFileById(id);
folderOld.removeFile(file)
destination.addFile(file)
But this doesn't work with shortcuts. Any ideas?

How about this answer?
Modification points:
It seems that in the current stage, the shortcut cannot be moved using Drive service. I think that this might be resolve in the future update.
So as the current workaround, in this answer, I would like to propose to use the method of "Files: patch" Drive API v2, because Drive API of Advanced Google services is used.
When your script is modified, please modify as follows.
Modified script:
Before you run the script, please enable Drive API at Advanced Google services.
function move(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sStamdata = ss.getSheetByName("New");
// var folderOld = DriveApp.getFolderById(folderOldId);
// var destination = DriveApp.getFolderById(folderId);
var id = sStamdata.getRange('D77').getValue();
// var file = DriveApp.getFileById(id);
Drive.Files.patch({parents: [{id: folderId}]}, id); // Added
}
folderId is the destination folder ID.
Please confirm the file ID of the shortcut again.
Note:
For example, when the file ID of the shortcut is confirmed with the shared link using the browser, the file ID is ID of the original file. Please be careful this.
References:
Advanced Google services
Files: patch

Related

Cannot add Firebase library to Apps Script

I want to sync a Google Sheet with my Firebase real-time database.
My code is:
function writeDataToFirebase() {
var ss =
SpreadsheetApp.openById("18AU9ZP9UHs9lvIeTA0SyJv6tcHPe7ux0tLopkRAz1T0");
var sheet = ss.getSheets()[0];
var data = sheet.getDataRange().getValues();
var dataToImport = {};
for(var i = 2; i < data.length; i++) {
var date = data[i][1];
dataToImport[date] = {
niftyclose:data[i][2],
sensexclose:data[i][5]
};
}
var firebaseUrl = "<MY database URL>"; //Yes I have entered the URL in my actual code
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
base.setData("", dataToImport);
}
But when I run the script, I get this error:
ReferenceError: FirebaseApp is not defined
I tried adding the Firebase Library and got this error:
Firebase Library Error
Can someone help me figure this out?
Thanks in advance.
I think that MYeP8ZEEt1ylVDxS7uyg9plDOcoke7-2l is the project key. In this case, it can be used for the legacy editor. But, in the current stage, the script ID is used for installing the GAS library. And also, when you use new script editor, it is required to use the script ID for installing the library. I thought that this is the reason of your issue.
When the project key of MYeP8ZEEt1ylVDxS7uyg9plDOcoke7-2l is installed using the the legacy editor and check appsscript.json, the script ID of the library can be known. It's 1hguuh4Zx72XVC1Zldm_vTtcUUKUA6iBUOoGnJUWLfqDWx5WlOJHqYkrt. So please modify your situation as follows.
1hguuh4Zx72XVC1Zldm_vTtcUUKUA6iBUOoGnJUWLfqDWx5WlOJHqYkrt
Please install the library using above script ID. This script ID can be also seen at https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/firebase/source
References:
Libraries
Firebase

Move files automatically from one folder to another in Google Drive

Problem:
Files get pulled automatically from my emails to a folder on my Google Drive.
The files are automatically given a name, which was the subject of the email, e.g. "Beach". Multiple files can thus have the same name if emails have the same subject name.
Once the files have landed in Google Drive, I want to move the files, say the ones called "Beach", to another folder called "Beach".
What is the best way to do this? I have tried using scripts, lists of folders/ID/file names etc in spreadsheets, yet can't quite get it.
According to this article, you can use Google Apps Scripts to move files across folders.
function moveFiles(source_folder, dest_folder) {
var files = source_folder.getFiles();
while (files.hasNext()) {
var file = files.next();
dest_folder.addFile(file);
source_folder.removeFile(file);
}
}
Here are some related threads which might help:
Google Drive: Move file to folder
SCRIPT TO MOVE FILES FROM MYDRIVE TO ANOTHER FOLDER IN GOOGLE DRIVE
This is what I use and it works well
The_unique_File_id is the part after drive.google.com/drive/folders/ the letters and numbers
function copyFiles(source_folder, dest_folder) {
var source_folder = DriveApp.getFolderById('The_unique_File_id');
var dest_folder = DriveApp.getFolderById('The_unique_File_id');
var files = source_folder.getFiles();
while (files.hasNext()) {
var file = files.next();
dest_folder.addFile(file);
source_folder.removeFile(file);
}
}

How to get notification from google drive sheet on edit?

I want to send notification to third party application when someone make changes in document stored in google drive.
can someone please help me that how to bound script with any document and when someone make changes in that script should run and send notification to third party application.
I have tried the following code But it is not working.
function onEdit(event){
var sheet = event.source.getActiveSheet();
var editedRow = sheet.getActiveRange().getRowIndex();
var editedolumn = sheet.getActiveRange().getColumnIndex();
var values = sheet.getSheetValues(editedRow, editedolumn, 1, 6);
Logger.log(values);
getSession();
}
function getSession(){
var payload =
{
"username" : "username",
"password" : "password",
};
var options =
{
"method" : "post",
"payload" : payload,
"followRedirects" : false
};
var login = UrlFetchApp.fetch("https://abcd.service-now.com/nav_to.do?uri=login.do" , options);
Logger.log(login);
var sessionDetails = login.getAllHeaders()['Set-Cookie'];
Logger.log(sessionDetails);
sendHttpPost(sessionDetails);
}
function sendHttpPost(data) {
var payload = {"category" : "network","short_description" : "Test"};
var headers = {"Cookie" : data}
var url = 'https://abcd.service-now.com/api/now/table/incident';
var options = {'method': 'post','headers': headers,'payload': payload,'json': true};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}
To send notification to third party application when someone make changes in document stored in google drive
Based from this Google Drive Help Forum, this feature hasn't been added yet. However, you may set notifications in a spreadsheet to find out when there's some modifications done in your spreadsheet. To set notifications in a spreadsheet:
Open the spreadsheet where you want to set notifications.
Click Tools > Notification rules.
In the window that appears, select when and how often you want to
receive notifications.
Click Save.
And, to bound script with any document
You may find the complete guide in Scripts Bound to Google Sheets, Docs, or Forms documentation. As mentioned,
To create a bound script, open a Google Sheets, Docs, or Forms file, then select Tools > Script editor. To reopen the script in the future, do the same thing. Because bound scripts do not appear in Google Drive, that menu is the only way to find or open the script.

How to delete a File in Google Drive?

How do I write a Google Apps Script that deletes files?
This finds files:
var ExistingFiles = DocsList.find(fileName);
But DocsList.deleteFile does not exist to delete a file.
Is there a way to move those files to another Folder or to Trash?
The other workaround I would consider is to be able to override an existing file with the same name.
Currently when I want to create a file with a name already used in MyDrive then it creates a second file with the same name. I would like to keep 1 file (the new one is kept and the old one is lost).
There are 3 services available to delete a file.
DriveApp - Built-in to Apps Script
Advanced Drive Service - Built-in to Apps Script but must be enabled. Has more capability than DriveApp
Google Drive API - Not built-in to Apps Script, but can be used from Apps Script using the Drive REST API together with UrlFetchApp.fetch(url,options)
The DocsList service is now deprecated.
The Advanced Drive Service can be used to delete a file without sending it to the trash. Seriously consider the risk of not being able to retrieve the deleted file. The Advanced Drive Service has a remove method which removes a file without sending it to the trash folder. Advanced services have many of the same capabilities as the API's, without needing to make an HTTPS GET or POST request, and not needing an OAuth library.
function delteFile(myFileName) {
var allFiles, idToDLET, myFolder, rtrnFromDLET, thisFile;
myFolder = DriveApp.getFolderById('Put_The_Folder_ID_Here');
allFiles = myFolder.getFilesByName(myFileName);
while (allFiles.hasNext()) {//If there is another element in the iterator
thisFile = allFiles.next();
idToDLET = thisFile.getId();
//Logger.log('idToDLET: ' + idToDLET);
rtrnFromDLET = Drive.Files.remove(idToDLET);
};
};
This combines the DriveApp service and the Drive API to delete the file without sending it to the trash. The Drive API method .remove(id) needs the file ID. If the file ID is not available, but the file name is, then the file can first be looked up by name, and then get the file ID.
In order to use DriveAPI, you need to add it through the Resources, Advanced Google Services menu. Set the Drive API to ON. AND make sure that the Drive API is turned on in your Google Cloud Platform. If it's not turned on in BOTH places, it won't be available.
Now you may use the following if the file is as a spreadsheet, doc etc.:
DriveApp.getFileById(spreadsheet.getId()).setTrashed(true);
or if you already have the file instead of a spreadsheet, doc etc. you may use:
file.setTrashed(true);
This code uses the DocsList Class which is now deprecated.
try this :
function test(){
deleteDocByName('Name-of-the-file-to-delete')
}
function deleteDocByName(fileName){
var docs=DocsList.find(fileName)
for(n=0;n<docs.length;++n){
if(docs[n].getName() == fileName){
var ID = docs[n].getId()
DocsList.getFileById(ID).setTrashed(true)
}
}
}
since you can have many docs with the same name I used a for loop to get all the docs in the array of documents and delete them one by one if necessary.
I used a function with the filename as parameter to simplify its use in a script, use test function to try it.
Note : be aware that all files with this name will be trashed (and recoverable ;-)
About the last part of your question about keeping the most recent and deleting the old one, it would be doable (by reading the last accessed date & time) but I think it is a better idea to delete the old file before creating a new one with the same name... far more logical and safe !
Though the The service DocsList is now deprecated, as from the Class Folder references, the settrashed method is still valid:
https://developers.google.com/apps-script/reference/drive/folder#settrashedtrashed
So should work simply this:
ExistingFiles.settrashed(true);
Here is another way to do it without the need of Drive API. (based on Allan response).
function deleteFile(fileName, folderName) {
var myFolder, allFiles, file;
myFolder = DriveApp.getFoldersByName(folderName).next();
allFiles = myFolder.getFilesByName(fileName);
while (allFiles.hasNext()) {
file = allFiles.next();
file.getParents().next().removeFile(file);
}
}
Here is a slightly modified version using the above. This will backup said file to specified folder, also remove any old previous backups with the same name so there are no duplicates.
The idea is here to backup once per day, and will retain 1 month of backups in your backup folder of choice. Remember to set your trigger to daily in your Apps Script.
https://gist.github.com/fmarais/a962a8b54ce3f53f0ed57100112b453c
function archiveCopy() {
var file = DriveApp.getFileById("original_file_id_to_backup");
var destination = DriveApp.getFolderById("backup_folder_name");
var timeZone = Session.getScriptTimeZone();
var formattedDate = Utilities.formatDate(new Date(),timeZone,"dd"); // 1 month backup, one per day
var name = SpreadsheetApp.getActiveSpreadsheet().getName()+"_"+formattedDate;
// remove old backup
var allFiles = destination.getFilesByName(name);
while (allFiles.hasNext()) {
var thisFile = allFiles.next();
thisFile.setTrashed(true);
};
// make new backup
file.makeCopy(name,destination);
}

Using Google Picker to upload files to Google Drive and place in specific folder

I am attempting to use Google Picker to upload files to a specific folder in Google Drive. Everything works fine when I am just uploading to the root folder, but even after specifying the parent folder as shown in my code below, the files still go to the root folder, not the folder I am specifying. I am certain the folderID is correct, as I am using the same ID elsewhere to create textiles in my GAE app, and place them in subfolders. My code is below:
function createPicker() {
// Create a view to search images.
var view = new google.picker.View(google.picker.ViewId.DOCS);
view.setMimeTypes('image/png,image/jpeg');
// Use DocsUploadView to upload documents to Google Drive.
var uploadView = new google.picker.DocsUploadView().setParent('THE Parent folder ID');
var picker = new google.picker.PickerBuilder().
addView(view).
addView(uploadView).
setAppId("pressomatic").
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
You have to add:
enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
In your case it becomes:
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(view).
addView(uploadView).
setAppId("pressomatic").
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
This is a bug documented in the Picker API Forum: https://groups.google.com/forum/#!topic/Google-Picker-API/xaHcET7JYLw
You have to add:
.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
In your case it becomes:
var picker = new google.picker.PickerBuilder()
.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
.addView(view)
.addView(uploadView)
.setAppId("pressomatic")
.setCallback(pickerCallback)
.build();
Hope this helps.

Resources