Today the part of the script that defines how to save PDFs to a shared folder in Google Drive looks like this:
var token = ScriptApp.getOAuthToken();
var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' + token } });
var pdfBlob = docurl.getBlob();
//...get token and Blob (do not create the file);
var fileName = spreadsheet.getSheetByName("Gerais").getRange("H2").getValue();
//Access or create the 'Squads' folder;
var folder; //declare folder;
var folders = DriveApp.getFoldersByName("Squads"); //returns iterator;
if(folders.hasNext()) {
folder = folders.next();
}else {
folder = DriveApp.createFolder("Squads");
}
//Remove duplicate file with the same name;
var existing = folder.getFilesByName(fileName); //returns iterator;
if(existing.hasNext()) {
var duplicate = existing.next();
var durl = 'https://www.googleapis.com/drive/v3/files/'+duplicate.getId();
var dres = UrlFetchApp.fetch(durl,{
method: 'delete',
muteHttpExceptions: true,
headers: {'Authorization': 'Bearer '+token}
});
if(dres.getResponseCode()>=400) {
//handle errors;
}
}
//add file;
folder.createFile(pdfBlob).setName(fileName);
As I share the folder with others, I can only edit the files owned by me.
I would like some help on the following problem...
1 - Analyze if there is a file with the name I am trying to save and try to delete it to save a new one over if I own the file. (Already exists in script)
2 - If the file is from someone else, he will not be able to delete it in the step above. (Already exists in script)
3 - If can not delete it, he will give up trying to save the file, because this way, never have a duplicate file with the same data in the folder. (Does not exist in script yet → My need)
Problem: In the current format it tries to delete the existing file to create a new one over, being able to delete or not it, he saves the new file, sometimes resulting in two files from two different people in the same folder. This can not happen.
And I need it not to give an error message if it can't save, because there are more lines below it that need to keep running until the end of the script if it doesn't save the file because there is already one with the same name.
I tried using the IF method, but it causes an error that makes the script stop, the base I tried to use was:
var existing = folder.getFilesByName(fileName); //returns iterator;
if(existing.hasNext()) {
var duplicate = existing.next();
if(dres.getResponseCode()>=400) {
//handle errors;