how to save file to shourcut folder - google-apps-script

I am trying to save attachment file from Gmail to Drive
I found a code sample here and its works BUT I need to save the file into the shared folder. at MyDrive I have a shortcut to the shared folder.
for example:
var GDRIVE_FILE = '_sheredFolder_/one/$name
function processThread(thread, label){
var attachments = message.getAttachments();
for(var i=0; i<attachments.length; i++) {
var attachment = attachments[i];
var info = {
'name': attachment.getName(),
'ext': getExtension(attachment.getName())}
var file = createFilename(GDRIVE_FILE, info);
saveAttachment(attachment, file);
}

If you have a folder shortcut in your "My Drive", then it's very likely that the folder is owned by someone else.
In order to be able to add files to a folder owned by someone else you should it should be shared with you as "editor". If it's shared with you as "viewer" you will not able to add the file to that folder.
Related
Moving Files In Google Drive Using Google Script
file.MoveTo doesn't move a file in a shared folder

Well after digging a while, I modify the core to support shortcuts or Shared folders
I add % at the begging of the initial path to identify when its a shared folder or local folder
that's the code:
var GDRIVE_FILE = '%TheSharedFolder/FOLDER/$name';
function getOrMakeFolder(path) {
var folder = DriveApp.getRootFolder();
var names = path.split('/');
while(names.length) {
var name = names.shift();
if(name.charAt(0)==='%')
{
var first = name.substring(1,name.length)
var folders = DriveApp.searchFolders('sharedWithMe');
while (folders.hasNext()) {
var folder = folders.next();
if(folder.getName()===first)
{
Logger.log("folder name is : "+folder.getName()+" folderID: " + folder.getId())
folder = DriveApp.getFolderById(folder.getId())
}
}
continue;
}
if(name === '') continue;
var folders = folder.getFoldersByName(name);
if(folders.hasNext()) {
folder = folders.next();
} else {
folder = folder.createFolder(name);
}
}
return folder;
}

Related

file.MoveTo doesn't move a file in a shared folder

I'm trying to move a file in a shared folder which I have editor access to a folder in my drive, but I can't. I can move the file to a different folder in my drive, though. The code is simple: file.moveTo(toFolder); Am I doing a wrong thing? How can I move a file in a shared folder to my folder. Here is my code:
function sendJudgeReqCN() {
var fromFolderId = "x";
var toFolderId = "y";
var saveFolderId = "z";
copyAndSaveAllFilesInFolder(fromFolderId, toFolderId, saveFolderId);
}
function copyAndSaveAllFilesInFolder(fromFolderId, toFolderId, saveFolderId) {
var fromFolder = DriveApp.getFolderById(fromFolderId);
var toFolder = DriveApp.getFolderById(toFolderId);
var saveFolder = DriveApp.getFolderById(saveFolderId);
var files = fromFolder.getFiles();
while (files.hasNext()) {
var file = files.next();
file.makeCopy(toFolder);
file.moveTo(saveFolder);
var fileName = file.getName();
Logger.log(fileName);
}
}
It is not enough to be editor in order to move a folder out of a shared Drive to your personal drive
You need to be organizer or owner to perform this kind of operation
This behavior is in agreement with the one of the Drive UI, wher only Manager but not Content Manager can move content from a shared drive to their own drive
Additional information here

How to log all files inside a folder

I want to navigate into a specific folder and then print all the files inside that specified folder using Google Apps Script:
function listFilesinSpecFolder(){
var files = DriveApp.getFolderById("specific folder id placed here");
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
}
}
When I tried to log this it gives me an error saying that hasNext() function is not a function.
But when I run the below code it gives me no errors...
function folder(){
var folders = DriveApp.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
Logger.log(folder.getName());
}
}
The following script will help you 'to navigate into a specific folder and then print all the files inside that specified folder'
CODE:
function listFilesinSpecFolder() {
var folder = DriveApp.getFolderById('FOLDER ID GOES HERE');
var file;
var contents = folder.getFiles();
while(contents.hasNext()) {
file = contents.next();
Logger.log(file.getName());
}
}
var files = DriveApp.getFolderById("specific folder id placed here");
this does not return files, it will return a folder
instead try something like:
var folder = DriveApp.getFolderById("specific folder id placed here");
var files = folder.getFiles()

duplicate folder and rename file structure

I'm trying to automate my duplicating folder process in google drive. As part of the process, I want to rename files and folders for each new client.
I've adapted some code found previously. It was previously working well, but for some reason now any folders/files that are more than 1 level deep of the root folder come back "undefined" in the replace section of the command.
function duplicatefolder(){
var newclientname = Browser.inputBox('Client Name')
var sourceFolder = "1. Master Client Folder";
var targetFolder = newclientname;
var source = DriveApp.getFoldersByName(sourceFolder);
var target = DriveApp.createFolder(targetFolder);
if (source.hasNext()) {
copyFolder(source.next(), target, newclientname);
}
}
function copyFolder(source, target,client) {
var folders = source.getFolders();
var files = source.getFiles();
while(files.hasNext()) {
var file = files.next();
var newname= file.getName().toString().replace("Master",client)
file.makeCopy(newname, target);
}
while(folders.hasNext()) {
var subFolder = folders.next();
var folderName = subFolder.getName();
var newFolderName = subFolder.getName().replace("Master",client)
var targetFolder = target.createFolder(newFolderName);
copyFolder(subFolder, targetFolder);
}
}
The script also creates the folder in the root directory of google drive. Ideally, I'd like it to be created inside the folder "Clients". How would I add this to the script?
Appreciate the help.
Cheers
Please see attached link hope this is it what you are looking for
https://yagisanatode.com/2018/07/08/google-apps-script-how-to-create-folders-in-directories-with-driveapp/

Specifying nested folder directly?

So I use this code to specify the folder in google drive that i want but I'm hoping there is a better way?
var folders = DriveApp.searchFolders("title contains '"+Values[3]+"' and 'jlfXPTjmRlS2dQf5SS3RaUWM....' in parents");
while (folders.hasNext()) {
var folder = folders.next();
var folder = folder.getId();
var subfolders = DriveApp.searchFolders("title contains '"+Values[4]+"' and '"+folder+"' in parents");
while (subfolders.hasNext()) {
var subfolder = subfolders.next(); // got My folder here!
// *Actions*
}}
The folder i want to specify is nested as such:
/shared folder(known by id)/subfolder(known by name)/subfolder(known by name)
My guess is this should be done with DocsList.getFolder(path) but I can't get it to work. Also I need this code to be compatible for collaborators that I have shared the base folder with.
Have a look at Mogsdad's answer in this post, I think it should help you: Migrating from DocsList to DriveApp?
Code is reproduced below, it does not need a lot of explanations : use the path as parameter and get a folder object as return.
function getFolderByPath(path) {
var parts = path.split("/");
if (parts[0] == '') parts.shift(); // Did path start at root, '/'?
var folder = DriveApp.getRootFolder();
for (var i = 0; i < parts.length; i++) {
var result = folder.getFoldersByName(parts[i]);
if (result.hasNext()) {
folder = result.next();
} else {
return null;
}
}
return folder;
}

Creating a zip file inside Google Drive with Apps Script

I have a folder in Google Drive folder containing few files. I want to make a Google Apps Script that will zip all files in that folder and create the zip file inside same folder.
I found a video that has Utilities.zip() function, but there is no API reference for that. How do I use it? Thanks in advance.
Actually it's even easier than that. Files are already Blobs (anything that has getBlob() can be passed in to any function that expects Blobs). So the code looks like this:
var folder = DocsList.getFolder('path/to/folder');
folder.createFile(Utilities.zip(folder.getFiles(), 'newFiles.zip'));
Additionally, it won't work if you have multiple files with the same name in the Folder... Google Drive folders support that, but Zip files do not.
To make this work with multiple files that have the same name:
var folder = DocsList.getFolder('path/to/folder');
var names = {};
folder.createFile(Utilities.zip(folder.getFiles().map(function(f){
var n = f.getName();
while (names[n]) { n = '_' + n }
names[n] = true;
return f.getBlob().setName(n);
}), 'newFiles.zip'));
As DocsList has been deprecated, You can use the following code to zip an entire folder containing files and sub-folders and also keep its structure:
var folder = DriveApp.getFolderById('<YOUR FOLDER ID>');
var zipped = Utilities.zip(getBlobs(folder, ''), folder.getName()+'.zip');
folder.getParents().next().createFile(zipped);
function getBlobs(rootFolder, path) {
var blobs = [];
var files = rootFolder.getFiles();
while (files.hasNext()) {
var file = files.next().getBlob();
file.setName(path+file.getName());
blobs.push(file);
}
var folders = rootFolder.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
var fPath = path+folder.getName()+'/';
blobs.push(Utilities.newBlob([]).setName(fPath)); //comment/uncomment this line to skip/include empty folders
blobs = blobs.concat(getBlobs(folder, fPath));
}
return blobs;
}
getBlobs function makes an array of all files in the folder and changes each file name to it's relative path to keep structure when became zipped.
To zip a folder containing multiple items with the same name use this getBlob function:
function getBlobs(rootFolder, path) {
var blobs = [];
var names = {};
var files = rootFolder.getFiles();
while (files.hasNext()) {
var file = files.next().getBlob();
var n = file.getName();
while(names[n]) { n = '_' + n }
names[n] = true;
blobs.push(file.setName(path+n));
}
names = {};
var folders = rootFolder.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
var n = folder.getName();
while(names[n]) { n = '_' + n }
names[n] = true;
var fPath = path+n+'/';
blobs.push(Utilities.newBlob([]).setName(fPath)); //comment/uncomment this line to skip/include empty folders
blobs = blobs.concat(getBlobs(folder, fPath));
}
return blobs;
}
I was able to use the code that #Hafez posted but I needed to modify it because It was not working for me. I added the first three lines because I needed the folder ID which is a string value and is not the name of the folder.
var folderName = DriveApp.getFoldersByName("<folderName>");
var theFolder = folderName.next();
var folderID =theFolder.getId();
var folder = DriveApp.getFolderById(folderID);
var zipped = Utilities.zip(getBlobs(folder, ''), folder.getName()+'.zip');
folder.getParents().next().createFile(zipped);
function getBlobs(rootFolder, path) {
var blobs = [];
var files = rootFolder.getFiles();
while (files.hasNext()) {
var file = files.next().getBlob();
file.setName(path+file.getName());
blobs.push(file);
}
var folders = rootFolder.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
var fPath = path+folder.getName()+'/';
blobs.push(Utilities.newBlob([]).setName(fPath)); //comment/uncomment this line to skip/include empty folders
blobs = blobs.concat(getBlobs(folder, fPath));
}
return blobs;
}
The only weird thing that I'm experiencing is that when I run the script it says TypeError: Cannot call method "getFiles" of undefined. (line 10, file "Code"). When I happened to look at the place where this script lives there was also 5 zip files that were complete. It works but I still get that error. Weird...but this code works for me. Thanks to everyone on this thread. Cheers!
There's no API reference indeed. You could open an issue request regarding this on Apps Script issue tracker. But deducing from what the code-completion shows, here is my understanding:
var folder = DocsList.getFolder('path/to/folder');
var files = folder.getFiles();
var blobs = [];
for( var i in files )
blobs.push(files[i].getBlob());
var zip = Utilities.zip(blobs, 'newFiles.zip');
folder.createFile(zip);
But I have not tested this code, so I don't know if it will work. Also, it may work only for files not converted to Google's format, or maybe only for those or a subset of it. Well, if you try it out and find something, please share here with us. One limit that you'll sure face is the filesize, it will probably not work if the zip file gets "too" big... yeah, you'll have to test this limit too.
If Hafez solution didn't worked out, and you get this error
TypeError: Cannot read property 'getFiles' of undefined
Try doing this
/**
* Creates a zipFile of the mentioned document ID and store it in Drive. You can search the zip by folderName.zip
*/
function createAndSendDocument() {
var files = DriveApp.getFolderById("DOCUMENT ID CAN BE FIND IN THE URL WHEN A DOCUMENT IS OPENED");
var folder = files;
var zipped = Utilities.zip(getBlobs(folder, ''), folder.getName() + '.zip');
folder.getParents().next().createFile(zipped);
}
function getBlobs(rootFolder, path) {
var blobs = [];
var files = rootFolder.getFiles();
while (files.hasNext()) {
var file = files.next().getBlob();
file.setName(path+file.getName());
blobs.push(file);
}
var folders = rootFolder.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
var fPath = path+folder.getName() + '/';
blobs.push(Utilities.newBlob([]).setName(fPath)); //comment/uncomment this line to skip/include empty folders
blobs = blobs.concat(getBlobs(folder, fPath));
}
return blobs;
}