将替换现有文件添加到GmailToDrive应用程序脚本 [英] Adding Replace Existing File to GmailToDrive App Script

查看:50
本文介绍了将替换现有文件添加到GmailToDrive应用程序脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找这部分应用程序脚本,以替换google驱动器中的现有文件,而不是在确定驱动器中已存在文件时写入它们的重复项.我已经尝试了一些方法,但无法按预期工作.

I'm looking to get this bit of app script to replace existing files in the google drive instead of writing duplicates of them when it identifies that the file already exists in the drive. I've tried a few things but I can't get it to work as intended.

它要求我添加其他信息,但是我的问题不需要更多的上下文.我将其添加为填充物.

It is requesting that I add additional information, but my question doesn't need any more context. I'm adding this as filler.

  // GLOBALS
//Array of file extension which you would like to extract to Drive
var fileTypesToExtract = ['csv'];
//Name of the folder in google drive i which files will be put
var folderName = 'GmailToDrive';
//Name of the label which will be applied after processing the mail message
var labelName = 'GmailToDrive';



function GmailToDrive(){
  //build query to search emails
  var query = '';
  //filename:jpg OR filename:tif OR filename:gif OR fileName:png OR filename:bmp OR filename:svg'; //'after:'+formattedDate+
  for(var i in fileTypesToExtract){
 query += (query === '' ?('filename:'+fileTypesToExtract[i]) : (' OR filename:'+fileTypesToExtract[i]));
  }
  query = 'in:inbox has:nouserlabels ' + query;
  var threads = GmailApp.search(query);
  var label = getGmailLabel_(labelName);
  var parentFolder;
  if(threads.length > 0){
    parentFolder = getFolder_(folderName);
  }
  var root = DriveApp.getRootFolder();
  for(var i in threads){
    var mesgs = threads[i].getMessages();
 for(var j in mesgs){
      //get attachments
      var attachments = mesgs[j].getAttachments();
      for(var k in attachments){
        var attachment = attachments[k];
        var isDefinedType = checkIfDefinedType_(attachment);
     if(!isDefinedType) continue;
     var attachmentBlob = attachment.copyBlob();
        var file = DriveApp.createFile(attachmentBlob);
        parentFolder.addFile(file);
        root.removeFile(file);
      }
 }
 threads[i].addLabel(label);
  }
}

//This function will get the parent folder in Google drive
function getFolder_(folderName){
  var folder;
  var fi = DriveApp.getFoldersByName(folderName);
  if(fi.hasNext()){
    folder = fi.next();
  }
  else{
    folder = DriveApp.createFolder(folderName);
  }
  return folder;
}

//getDate n days back
// n must be integer
function getDateNDaysBack_(n){
  n = parseInt(n);
  var date = new Date();
  date.setDate(date.getDate() - n);
  return Utilities.formatDate(date, Session.getScriptTimeZone(), 'yyyy/MM/dd');
}

function getGmailLabel_(name){
  var label = GmailApp.getUserLabelByName(name);
  if(!label){
 label = GmailApp.createLabel(name);
  }
  return label;
}

//this function will check for filextension type.
// and return boolean
function checkIfDefinedType_(attachment){
  var fileName = attachment.getName();
  var temp = fileName.split('.');
  var fileExtension = temp[temp.length-1].toLowerCase();
  if(fileTypesToExtract.indexOf(fileExtension) !== -1) return true;
  else return false;
}

推荐答案

  • 使用var file = DriveApp.createFile(attachmentBlob)创建文件时,如果存在与attachmentBlob相同的文件名,则要将现有文件替换为使用attachmentBlob创建的新文件.
    • When a file is created by var file = DriveApp.createFile(attachmentBlob), if the same filename with attachmentBlob is existing, you want to replace the existing file to new file created with attachmentBlob.
    • 如果我的理解是正确的,那么该修改如何?请认为这只是几种解决方案之一.修改后的脚本的流程如下.

      If my understanding is correct, how about this modification? Please think of this as just one of several solutions. The flow of this modified script is as follows.

      1. 检索attachment的文件名.
      2. 如果文件名与检索到的文件名相同,则会删除现有文件.
      3. 使用attachment创建新文件.
      1. Retrieve the filename of attachment.
      2. If there is the file which is the same filename with the retrieved filename, the existing file is deleted.
      3. Create new file with attachment.

      修改后的脚本:

      请进行如下修改. 反映此修改后,现有文件将放入垃圾箱.所以请注意这一点.

      var attachmentBlob = attachment.copyBlob();
      var file = DriveApp.createFile(attachmentBlob);
      parentFolder.addFile(file);
      root.removeFile(file);
      

      到:

      var attachmentBlob = attachment.copyBlob();
      var existingFile = DriveApp.getFilesByName(attachment.getName());
      if (existingFile.hasNext()) {
        var file = existingFile.next();
        file.setTrashed(true);
      }
      var file = DriveApp.createFile(attachmentBlob);
      parentFolder.addFile(file);
      root.removeFile(file);
      

      注意:

      • 此修改后的脚本假定驱动器中只有一个重复的文件.如果有几个文件名相同的文件,请告诉我.
      • file.setTrashed(true)只是将文件放入垃圾箱.如果要完全删除文件,请将file.setTrashed(true);替换为以下脚本.以下脚本使用了Drive API的delete方法.
      • Note:

        • This modified script supposes that there is only one duplicated file in your drive. If there are several files with the same filename, please tell me.
        • file.setTrashed(true) just puts a file to the trash box. If you want to completely delete the file, please replace file.setTrashed(true); to the following script. The following script used the delete method of Drive API.
        • var url = "https://www.googleapis.com/drive/v3/files/" + file.getId();
          var params = {
            method: "delete",
            headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}
          }
          UrlFetchApp.fetch(url, params);
          

          参考文献:

          • getFilesByName(name)
          • setTrashed(被破坏)
          • 文件:删除Drive API
          • References:

            • getFilesByName(name)
            • setTrashed(trashed)
            • Files: delete of Drive API
            • 如果我误解了您的问题,而此修改不是您想要的结果,我深表歉意.

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

              如果要将attachmentBlob覆盖为与attachmentBlob相同文件名的现有文件,则可以使用以下脚本.

              If you want to overwrite attachmentBlob to the existing file which is the same filename with attachmentBlob, you can use the following script.

              使用此脚本时,请在Advanced Google Services和API控制台上启用Drive API.您可以在此处查看.

              When you use this script, please enable Drive API at Advanced Google Services and API console. You can see about this at here.

              var attachmentBlob = attachment.copyBlob();
              var file = DriveApp.createFile(attachmentBlob);
              parentFolder.addFile(file);
              root.removeFile(file);
              

              到:

              var attachmentBlob = attachment.copyBlob();
              var existingFile = DriveApp.getFilesByName(attachment.getName());
              if (existingFile.hasNext()) {
                var file = existingFile.next();
                Drive.Files.update({}, file.getId(), attachmentBlob);
              } else { // Added
                var file = DriveApp.createFile(attachmentBlob); // Added
                parentFolder.addFile(file); // Added
                root.removeFile(file); // Added
              }
              

              注意:

              • 运行此脚本时,现有文件将被覆盖.因此,首先请注意这一点.因此,我建议它使用虚拟文件来测试此脚本.
              • Note:

                • When you run this script, the existing file is overwritten. So at first, please be careful this. So I recommend that it tests this script using a dummy file.
                • 这篇关于将替换现有文件添加到GmailToDrive应用程序脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆