仅当Google Apps脚本中有新功能时才解压缩文件 [英] Unzip File Only If New in Google Apps Scripts

查看:97
本文介绍了仅当Google Apps脚本中有新功能时才解压缩文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Google云端硬盘上有一个文件夹(我们称其为源文件夹),该文件夹会不时更新为新的zip文件(底层文件为PDF)。我正在尝试使用Google Apps脚本仅解压缩新的zip文件,并将基础PDF放置在另一个文件夹中(我们称之为目标文件夹)。

I have a folder (let's call it the source folder) on Google Drive that is updated from time to time with new zip files (underlying files are PDFs). I am trying to use Google Apps Script to unzip only the new zip files and place the underlying PDFs in another folder (let's call it the destination folder).

我目前正在使用以下代码在基于时间的触发器上将源文件夹中的文件解压缩。我当前的代码无法区分旧的和新的zip文件,因此我在目标文件夹中积累了大量重复项。 (我在WeirdGeek上找到了以下代码: https:/ /www.weirdgeek.com/2019/10/unzip-files-using-google-apps-script/

I am currently using the following code to unzip the files in the source folder, running on a time-based trigger. My current code does not differentiate between old and new zip files so I am getting a large number of duplicates accumulating in the destination folder. (I found this code on WeirdGeek: https://www.weirdgeek.com/2019/10/unzip-files-using-google-apps-script/)

function Unzip() {
  //Add folder ID to select the folder where zipped files are placed
  var SourceFolder = DriveApp.getFolderById("1KbyB2vTUfbwYdzBEyIwzTliXKjATbW8A")
  //Add folder ID to save the where unzipped files to be placed
  var DestinationFolder = DriveApp.getFolderById("1Z-iVlcROe5kVX8IkBlV9a98WKlvlfp3U")
  //Select the Zip files from source folder using the Mimetype of ZIP
  var ZIPFiles = SourceFolder.getFilesByType(MimeType.ZIP)

  //Loop over all the Zip files
  while (ZIPFiles.hasNext()){
   // Get the blob of all the zip files one by one
    var fileBlob = ZIPFiles.next().getBlob();
   //Use the Utilities Class to unzip the blob
    var unZippedfile = Utilities.unzip(fileBlob);
   //Unzip the file and save it on destination folder
    var newDriveFile = DestinationFolder.createFile(unZippedfile[0]);
    }
}

我最初以为是基于时间的功能上的限制,但是由于源文件夹正在与sFTP站点同步(使用MultCloud),所以我不想这样做。

I initially thought to add some sort of time-based restriction to the function, but because the source folder is being synced (using MultCloud) with an sFTP site, I don't want to go that direction.

我还发现以下代码用于对保存新电子表格进行替换限制,但无法弄清楚如何将此代码与我的代码集成。 (代码来自用户Tainake)

I ALSO found the following code is used to put a "replace" restriction on saving new spreadsheets but couldn't figure out how to integrate this with my code. (Code is from user Tainake)

function saveAsSpreadsheet() {
  var folderId = "0B8xnkPYxGFbUMktOWm14TVA3Yjg";
  var folder = DriveApp.getFolderById(folderId);
  var files = folder.getFilesByName(getFilename());
  if (files.hasNext()) {
    files.next().setTrashed(true);
  }
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  DriveApp.getFileById(sheet.getId()).makeCopy(getFilename(), folder);
}

任何有关解决此问题的想法将不胜感激!我是一个完全菜鸟,所以如果这是一个愚蠢的问题,我会提前道歉。

Any ideas on how to solve this problem would be appreciated! I am a complete noob so I apologize in advance if this is a stupid question.

编辑:我不知道如何在源代码中仅解压缩新文件文件夹,因此我的新代码移至目标文件夹中的所有文件,然后解压缩源文件夹中的所有文件。代码如下:

I could not figure out how to unzip only "new" files in the source folder, and so my new code moves to trash all files in the destination folder, and then unzips all files in the source folder. Code is below:



function Unzip() {
  //Add folder ID to select the folder where zipped files are placed
  var SourceFolder = DriveApp.getFolderById("1KbyB2vTUfbwYdzBEyIwzTliXKjATbW8A")
  //Add folder ID to save the where unzipped files to be placed
  var DestinationFolder = DriveApp.getFolderById("1Z-iVlcROe5kVX8IkBlV9a98WKlvlfp3U")

 //Delete files from the destination folder
  //Get the files in the destination folder
    var files = DestinationFolder.getFiles();

    //Loop through the files in the destination folder
    while(files.hasNext()){

      //Get the individual file in the destination folder to process
      var file = files.next(); 

      //Trash that file
        file.setTrashed(true);
      }


  //Select the Zip files from source folder using the Mimetype of ZIP
  var ZIPFiles = SourceFolder.getFilesByType(MimeType.ZIP)

  //Loop over all the Zip files
  while (ZIPFiles.hasNext()){
   // Get the blob of all the zip files one by one
    var fileBlob = ZIPFiles.next().getBlob();
   //Use the Utilities Class to unzip the blob
    var unZippedfile = Utilities.unzip(fileBlob);
   //Unzip the file and save it on destination folder
    var newDriveFile = DestinationFolder.createFile(unZippedfile[0]);
    }
}

我知道这可能不是最佳解决方案解决此问题的方法,但这使我可以让MultCloud将zip文件同步到我的Google云端硬盘中,然后通过不时运行的功能将这些文件解压缩。任何人都有一个更好的主意,如何在不删除和重新创建所有文件的情况下完成同一件事?

I could see how this may not be the best solution to this issue, but this allows me to have a MultCloud sync the zip files into my Google Drive, and then allows me to have those files unzipped with a function that runs from time to time. Anyone have a better idea how to accomplish the same thing without deleteing and recreating all the files every time?

编辑2:
感谢Cameron,这个问题被回答。我为后代/其他新手粘贴了我正在使用的完整代码,以使他们不必将它们拼凑在一起:

EDIT 2: Thank you to Cameron, this question is answered. I am pasting the full code I am using below, for posterity / other newbies so that they don't have to piece it together:

function Unzip() {
  //Add folder ID to select the folder where zipped files are placed
  var SourceFolder = DriveApp.getFolderById("1KbyB2vTUfbwYdzBEyIwzTliXKjATbW8A")
  //Add folder ID to save the where unzipped files to be placed
  var DestinationFolder = DriveApp.getFolderById("1Z-iVlcROe5kVX8IkBlV9a98WKlvlfp3U")

  //Select the Zip files from source folder using the Mimetype of ZIP
  var ZIPFiles = SourceFolder.getFilesByType(MimeType.ZIP);

  var now = new Date(); //get current time after you fetch the file list from Drive.

  //Get script properties and check for stored "last_execution_time"
  var properties = PropertiesService.getScriptProperties();
  var cutoff_datetime = properties.getProperty('last_execution_time');

  //if we have last execution date, stored as a string, convert it to a Date object.
  if(cutoff_datetime)
     cutoff_datetime = new Date(cutoff_datetime);

  //Loop over all the Zip files
  while (ZIPFiles.hasNext()){
    var file = ZIPFiles.next();

    //if no stored last execution, or file is newer than last execution, process the file.
    if(!cutoff_datetime || file.getDateCreated() > cutoff_datetime){
        var fileBlob = file.getBlob();
       //Use the Utilities Class to unzip the blob
       var unZippedfile = Utilities.unzip(fileBlob);
       //Unzip the file and save it on destination folder
       var newDriveFile = DestinationFolder.createFile(unZippedfile[0]);
    }
  }

  //store "now" as last execution time as a string, to be referenced on next run.
  properties.setProperty('last_execution_time',now.toString());
}


推荐答案

您可以在文件对象上使用 getDateCreated()函数确定何时创建文件。通过对照时间限制检查此值,您应该能够确定文件是否为新文件。如果在两次执行之间至少有几个小时的时间触发脚本,则可以使用硬编码的截止时间。因此,例如,如果每六个小时触发一次脚本,则可以忽略最近6个小时内未创建的任何文件。

You can use the getDateCreated() function on a File object to determine when the file was created. By checking this value against a time limit, you should be able to determine if the file is new. If you are triggering your script with at least a few hours between executions, you could use a hardcoded cutoff time. So if you are triggering your script every six hours, you could ignore any files not created within the last 6 hours, for example.

但是,一种更可靠的方法是将上一次成功执行的时间存储在脚本属性中,因此您可以始终处理自上次成功执行以来创建的所有文件。

However, a more robust approach would be to store the last successful execution time in a Script Property, so you could always process any files created since the last successful execution.

请注意,此代码将在第一次运行时处理当前文件夹中的所有文件,之后将仅处理文件

Note that this code will process all files currently in the folder the first time it runs, after that it will only process files created since the last run.

  var ZIPFiles = SourceFolder.getFilesByType(MimeType.ZIP);

  var now = new Date(); //get current time after you fetch the file list from Drive.

  //Get script properties and check for stored "last_execution_time"
  var properties = PropertiesService.getScriptProperties();
  var cutoff_datetime = properties.getProperty('last_execution_time');

  //if we have last execution date, stored as a string, convert it to a Date object.
  if(cutoff_datetime)
     cutoff_datetime = new Date(cutoff_datetime);

  //Loop over all the Zip files
  while (ZIPFiles.hasNext()){
    var file = ZIPFiles.next();

    //if no stored last execution, or file is newer than last execution, process the file.
    if(!cutoff_datetime || file.getDateCreated() > cutoff_datetime){
        var fileBlob = file.getBlob();
       //Use the Utilities Class to unzip the blob
       var unZippedfile = Utilities.unzip(fileBlob);
       //Unzip the file and save it on destination folder
       var newDriveFile = DestinationFolder.createFile(unZippedfile[0]);
    }
  }

  //store "now" as last execution time as a string, to be referenced on next run.
  properties.setProperty('last_execution_time',now.toString());

这篇关于仅当Google Apps脚本中有新功能时才解压缩文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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