You can control the number of files downloaded during a single download command execution by implementing the downloadFilePrepareCallback and downloadFileFinishCallback functions.
To achieve this, use PluginUtil.KV to track the count of files processed within a specific downloadActionId and use PluginUtil.HashTool.md5Hex on the driveFilePath to track the status of individual files.
Logic flow:
- In
downloadFilePrepareCallback, check if the current count for the downloadActionId has reached your desired limit. If so, set downloadApproved to "no". - If the limit is not reached, mark the file as
"downloading" in the KV store. - In
downloadFileFinishCallback, mark the file as "finish" in the KV store to prevent re-downloading in future runs.
function downloadFilePrepareCallback(context, params) {
var result = {
"downloadApproved": "yes",
"localFilePath": ""
};
// Limit for this download action
const maxCountOfDownloadAction = 3;
// Only process files
if (params["driveFileType"] != "file") {
return
}
// Get current count for this download action
var keyOfThisDownloadAction = "download:" + params["downloadActionId"];
var valueOfThisDownloadAction = PluginUtil.KV.getString(keyOfThisDownloadAction);
if (valueOfThisDownloadAction == "") {
valueOfThisDownloadAction = "0";
}
var countOfThisDownloadAction = parseInt(valueOfThisDownloadAction);
if (countOfThisDownloadAction >= maxCountOfDownloadAction) {
// Limit reached, skip remaining files
result["downloadApproved"] = "no";
return result;
}
// Track individual file status
var keyOfThisDownloadFile = "file:" + PluginUtil.HashTool.md5Hex(params["driveFilePath"]);
var valueOfThisDownloadFile = PluginUtil.KV.getString(keyOfThisDownloadFile);
if (valueOfThisDownloadFile == "finish") {
// Already finished, skip
return result;
}
PluginUtil.KV.putString(keyOfThisDownloadFile, "downloading");
// Increment and save count
countOfThisDownloadAction += 1;
PluginUtil.KV.putString(keyOfThisDownloadAction, String(countOfThisDownloadAction));
return result;
}
function downloadFileFinishCallback(context, params) {
var keyOfThisDownloadFile = "file:" + PluginUtil.HashTool.md5Hex(params["driveFilePath"]);
console.log(keyOfThisDownloadFile)
PluginUtil.KV.putString(keyOfThisDownloadFile, "finish");
}