Check Google site if page name already exists when uploading folders - google-apps-script

I am uploading folders to a created google site using appscript, but sometimes an error occures during which the code is uploading the filenames to the site as a parentpage and does not finish uploading all hte file names. So, when I restart the code it will throw an error saying that a page with that name already exists. Is there a way to do an if statement around the create page portion of code so that it checks to see if the name already exists. the code is provided below,
while (folders.hasNext()) {
var folder = folders.next();
if (folder.getName() == "Work_Orders(Evadale)3"){
Logger.log("I made it into the uploads folder");
var subFolders = folder.getFolders();
while(subFolders.hasNext()){
var subFolder = subFolders.next();
var files = subFolder.getFilesByType('text/html');
var stringChange = subFolder.getName();
var parentname = stringChange.replace(" ","-");
for (var c = 0; c<5; c++){
parentname = parentname.replace(" ","-");
parentname = parentname.replace("#","_");
parentname = parentname.replace("(","-");
parentname = parentname.replace(")","-");
parentname = parentname.replace("&","and");
}
Logger.log(parentname);
Logger.log("About to enter the if statement");
var pageParent = site.createWebPage(parentname, parentname, "");
var counter = 0;
while (files.hasNext()){
Logger.log(maxFiles);
var file = files.next();
var html = file.getBlob();
var datas = html.getAs('text/plain');
var infoString = datas.getDataAsString(); //this has a quota, see if this can be done some other way?
var name = file.getName();
Logger.log(name);
name = name.replace(".html","");
cache.put("parent"+maxFiles,parentname);
cache.put("child"+maxFiles, name);
cache.put("infoString"+maxFiles, infoString);
maxFiles++;
}
Logger.log("Counter"+counter);
Logger.log("maxFiles"+maxFiles);
Logger.log("Just exited the if statement");
cache.put("counter", counter);
}
}
cache.put("maxFiles", maxFiles);
cache.put("begin", begin);
cache.put("end",end);
}

Maybe you could use the getAllDescendants() method?
Google Documentation - getAllDescendants()
That would get you an array of descendant page names. Then you could use the JavaScript indexOf() method of the array name to check if the page name exists in the array.
JavaScript indexOf() method

Related

Upload file using a form. Moving a file to a specific folder issue

High School teacher here with hardly any experience in GAS or Javascript. Using a google form to have students upload a file(s). The file gets moved to an assignment folder in a period folder based off what the student enters. The file should get renamed so that it has the student's name in Last First name order at the beginning of the file.
All of that is working! BUT for some reason it is giving me two versions of the file! One in the correct place, but another one in the root directory of my Google Form. What is wrong with my code?
function myFunction2() {
const folderId = ""; // I deleted the ID since I don\'t know if there is any privacy issues
const form = FormApp.getActiveForm(); //gets the form
const formResponses = form.getResponses(); //gets all the responses
const itemResponses = formResponses[formResponses.length-1].getItemResponses(); //gets the last response
// Prepare the folder names
const rootFolder = DriveApp.getFolderById(folderId); //root folder
const periodName = itemResponses[1].getResponse(); //period name
const assignmentName = itemResponses[2].getResponse(); //assignment name
// Checks to see if the period folder exists
const periodIterator = rootFolder.getFoldersByName(periodName); //Folder iterator
const periodFolder = periodIterator.hasNext() ? periodIterator.next() : rootFolder.createFolder(periodName); //does the period Folder exist?
// Checks to see if the assignment folder in the period exists
const assignmentIterator = periodFolder.getFoldersByName(assignmentName); //Assignment iterator
const assignmentFolder = assignmentIterator.hasNext() ? assignmentIterator.next() : periodFolder.createFolder(assignmentName);//does the assignment folder exist
// Puts all files in the Period/Assignment folder
// Renames files so that it has Last Name, First Name order at beginning of the name
files = itemResponses[3].getResponse();
if (files.length > 0) {
for (var n in files) {
var dFile = DriveApp.getFileById(files[n]);
var fullFileName = dFile.getName();
var firstPart = fullFileName.substring(0, fullFileName.lastIndexOf("-")-1);
var namePart = fullFileName.substring(fullFileName.lastIndexOf("-")+2, fullFileName.lastIndexOf("."));
var firstName = namePart.substring(0,namePart.indexOf(" "));
var lastName = namePart.substring(namePart.indexOf(" ")+1);
var flippedName = lastName+", "+firstName;
dFile.setName(flippedName+" - "+ firstPart); //Rename the file
dFile.moveTo(assignmentFolder); //Move the file
}
}
}

List all files and folder in google drive

I've been trying to figure this out for a while now. I hope I can get some guidance on this. The purpose of the following script is to get a full list of folders and files with subfolders and their files included.
Here is what I currently have:
var counter = 0
var files = folder.getFiles();
var subfolders = folder.getFolders();
var folderPath = folder.getName();
while (subfolders.hasNext()){
subfolder = subfolders.next();
var row = [];
//row.push(subfolder.getName(),'',subfolder.getId(),subfolder.getUrl(),subfolder.getSize(),subfolder.getDateCreated(),subfolder.getLastUpdated());
//list.push(row);
if(counter > 0){
var files = subfolder.getFiles();
}
while (files.hasNext()){
file = files.next();
var vals = file.getUrl();
var row = [];
if(counter == 0){
row.push(folder.getName(),file.getName(),file.getId(),file.getUrl(),file.getSize(),file.getDateCreated(),file.getLastUpdated())
}else{
row.push(folderPath + '/' + subfolder.getName(),file.getName(),file.getId(),file.getUrl(),file.getSize(),file.getDateCreated(),file.getLastUpdated())
}
list.push(row);
}
counter = counter + 1
}
It currently gets the folder names and file names for the current folder and it's subfolder. It doesn't go any further than that. I'm stuck trying to figure out how to get a loop going to continue until there are no more sub-folders.
It isn't a very big drive. There are less than 10 levels but would like the flexibility to go further if needed.
Recursion is beneficial in this case. The code below calls the recursive method recurseFolder() which takes a Folder and Array as a parameter. It adds all the files in the folder to a list, then calls itself on any subfolders it finds.
function test(){
var root = DriveApp.getRootFolder();
var list = [];
var list = recurseFolder(root, list);
Logger.log(JSON.stringify(list));
//This is just how I am testing the outputed list. You can do what you need.
var sheet = SpreadsheetApp.getActiveSheet();
list.forEach(function (row){
sheet.appendRow(row);
});
}
function recurseFolder(folder, list){
var files = folder.getFiles();
var subfolders = folder.getFolders();
while (files.hasNext()){ //add all the files to our list first.
var file = files.next();
var row = [];
Logger.log("File: " + folder.getName());
row.push(folder.getName(),file.getName(),file.getId(),file.getUrl(),file.getSize(),file.getDateCreated(),file.getLastUpdated())
list.push(row);
}
while (subfolders.hasNext()){ //Recurse through child folders.
subfolder = subfolders.next();
Logger.log("Folder: " + subfolder.getName());
list = recurseFolder(subfolder, list); //Past the original list in so it stays a 2D Array suitible for inserting into a range.
}
return list;
}
I'm not sure if the output is formatted how you intended so you might need to play with it a little. Note: It will easily time out if run on a larger Drive.
You need a function that will navigate the folder structure recursively, meaning that if it runs into a subfolder within a folder, it will call itself again passing that folder as a new parent.
function listFolders(parentFolderId) {
var sourceFolder = DriveApp.getFolderById(parentFolderId) || DriveApp.getRootFolder();
var folders = sourceFolder.getFolders();
var files = sourceFolder.getFiles();
while (files.hasNext()) {
var file = files.next();
//Do something
}
while (folders.hasNext()) {
var folder = folders.next();
listFolders(folder.getId());
}
}
Note that this function will still time out if you have lots of files in your Drive, in which case you need to store the state of your app using PropertiesService and schedule the function to run again using triggers via the ScriptApp. You can achieve this by saving the continuation token for your Files Iterator between script executions
More on ContinuationToken

Skip processing .xls to Google Sheets script if the file already exists in Google Drive

I am currently using this code to automatically convert all uploaded .xls files in Google Drive to Google Sheets.
function importXLS(){
var files = DriveApp.searchFiles('title contains ".xls"');
while(files.hasNext()){
var xFile = files.next();
var name = xFile.getName();
if (name.indexOf('.xls')>-1){
var ID = xFile.getId();
var xBlob = xFile.getBlob();
var newFile = { title : name,
key : ID,
'parents':[{"id":"12FcKokB-ppW7rSBtAIG96uoBOJtTlNDT"}]
}
file = Drive.Files.insert(newFile, xBlob, {
convert: true
});
}
}
}
It works perfectly, but fails if there is already a file in the output folder with the same name. Even though I never technically get to see this error below (since it runs on a schedule and not fired manually like in the screenshot), I would prefer to simply skip the conversion process if the file already exists.
If possible, I would also like to avoid overwriting it each time, as I feel that would be a waste of processing time. How would I edit this code to say that if the file name already exists in that folder, skip the entire code completely?
Thanks!
Two things you can try:
Get the files names that are already in the destination folder and check if the file exists before you try copying.
Wrap the section of your code that does the copying in a try..catch statement.
Both of these should work independently, but using the try..catch statement will catch all errors, so it would be best to combine them. (You can review the error logs in the Developer Console.) Doing this you'll be able to skip files that have the same name as those already in your destination folder and any other error that might come up will not terminate your script from completing.
function importXLS(){
var files = DriveApp.searchFiles('title contains ".xls"');
var destinationFolderId = "12FcKokB-ppW7rSBtAIG96uoBOJtTlNDT";
var existingFileNames = getFilesInFolder(destinationFolderId);
while(files.hasNext()){
var xFile = files.next();
var name = xFile.getName();
try {
if (!existingFileNames[name] && (name.indexOf('.xls')>-1)) {
var ID = xFile.getId();
var xBlob = xFile.getBlob();
var newFile = { title : name,
key : ID,
'parents':[{"id": destinationFolderId}]
}
file = Drive.Files.insert(newFile, xBlob, {
convert: true
});
}
} catch (error) {
console.error("Error with file " + name + ": " + error);
}
}
}
/**
* Get an object of all file names in the specified folder.
* #param {string} folderId
* #returns {Object} files - {filename: true}
*/
function getFilesInFolder(folderId) {
var folder = DriveApp.getFolderById(folderId);
var filesIterator = folder.getFiles();
var files = {};
while (filesIterator.hasNext()) {
var file = filesIterator.next();
files[file.getName()] = true;
}
return files;
}

Drive Folder ID from file

after the renewal of DriveApp API I'm struggling to update my script.
It was able to find the Drive Folder ID starting from a file.
Basically starting from a Spreadsheet, I found what was the ID of the folder that contained the file.
Now if i try:
var thisFile =(the file I have)
var newFile = (the file I want to add to the same folder)
var parentFold = thisFile.getParents()[0];
var targetFolder = DriveApp.getFolderById(parentFold);
targetFolder.addFile(newFile);
The system sends an error at line 4 "No item with the given ID could be found, or you do not have permission to access it." (even if I open all the permissions).
Any suggestion?
Thanks!
The getParents() method returns a FolderIterator. It doesn't return the folder ID. You need to get the folder:
var folder = folders.next();
The code given assumes that there is only one parent folder to the file.
Updated Answer:
function copyToParent() {
var thisFile = DriveApp.getFileById('file ID');
//var newFile = (the file I want to add to the same folder)
var parentFold = thisFile.getParents();//Get all parents - normally just one parent
var folder = parentFold.next();//Get the first parent folder
//Logger.log('folder name: ' + folder.getName());//For testing - log folder name
folder.addFile(newFile);
}
Old Answer:
This answer has unneeded steps.
Then get the ID of the folder:
var theId = folder.getId();
Full code:
function copyToParent() {
var thisFile = DriveApp.getFileById('file ID');
//var newFile = (the file I want to add to the same folder)
var parentFold = thisFile.getParents();
var folder = parentFold.next();
var theId = folder.getId();
var targetFolder = DriveApp.getFolderById(theId);
Logger.log('targetFolder name: ' + targetFolder.getName());
targetFolder.addFile(newFile);
};

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;
}