Do not save PDF if a file with the same name already exists (Google App Script + Google Sheets)

Viewed 521

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;
1 Answers
  • You want to create new file only when the file could be deleted.
  • You don't want to stop the script even when the file couldn't be deleted.

If my understanding is correct, how about this answer? Please think of this as just one of several answers.

Modification points:

  • In your script, I think that the if statement of if(existing.hasNext()) {} is required to be modified.
  • muteHttpExceptions: true is used for the request. So even if the status code is not 200, the script is not stopped.
  • When you want to create new file only when the file could be deleted, how about adding if (status == 200)?

Modified script:

When your script is modified, please modify he if statement of if(existing.hasNext()) {} of your script.

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}
  });
  var status = dres.getResponseCode(); // Added
  if (status >=400) { // Modified
    //handle errors;
  } else if (status == 200) {
    folder.createFile(pdfBlob).setName(fileName); // Added
  }
} else {
  folder.createFile(pdfBlob).setName(fileName); // Added
}
  • In this modification, please remove folder.createFile(pdfBlob).setName(fileName); at the last line of your script in your question.

Note:

  • As other pattern, at first, if the owner of the file is checked, how about the following modified script?

    if(existing.hasNext()) {
      var duplicate = existing.next();
      if (duplicate.getOwner().getEmail() == Session.getActiveUser().getEmail()) { // Added
        var durl = 'https://www.googleapis.com/drive/v3/files/'+duplicate.getId();
        var dres = UrlFetchApp.fetch(durl,{
          method: 'delete',
          muteHttpExceptions: true,
          headers: {'Authorization': 'Bearer '+token}
        });
        var status = dres.getResponseCode(); // Added
        if (status >=400) { // Modified
          //handle errors;
        } else if (status == 200) {
          folder.createFile(pdfBlob).setName(fileName); // Added
        }
      }
    } else {
      folder.createFile(pdfBlob).setName(fileName); // Added
    }
    

If I misunderstood your question and this was not the direction you want, I apologize.

Related