Reputation: 2107
I created this script to delete files published more than 3 hours ago. And even if the latest file is older than 3 hours, it will not be deleted, so the folder will never be empty.
I enabled google's advanced service called DRIVE API V2.
I activated a trigger to analyze the folder every 5 minutes, but often the files are not deleted, they remain in the folder. The script works sometimes yes and sometimes no.
I would like to know what is wrong or what I need to edit to make it work perfectly.
function getOldFileIDs() {
// Old date is 3 Hours
var oldDate = new Date().getTime() - 3600*1000*3;
var cutOffDate = new Date(oldDate).toISOString();
// Get folderID using the URL on google drive
var folder = DriveApp.getFolderById('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
var files = folder.searchFiles('modifiedDate < "' + cutOffDate + '"');
var obj = [];
while (files.hasNext()) {
var file = files.next();
obj.push({id: file.getId(), date: file.getDateCreated()});
}
obj.sort(function(x, y) {return x.date < y.date ? 1 : -1});
obj.shift();
var fileIDs = obj.map(function(e) {return e.id});
return fileIDs;
};
function deleteFiles() {
var fileIDs = getOldFileIDs();
fileIDs.forEach(function(fileID) {
Drive.Files.remove(fileID);
});
};
I also want some help so that this script can analyze if there are files with the same name inside the folder, if it exists, it delete surplus ones so that there is always only one file with each name.
And new detail, a new error appeared that until earlier did not happen ... Saying that:
API call failed for drive.files.delete with error Insufficient permissions for this file (line 24)
Line 24:
Drive.Files.remove(fileID);
Upvotes: 2
Views: 1379
Reputation: 38121
By using consumer (free) accounts, only the file owner is able to delete them. To prevent the error, before calling Drive.Files.remove(fileID)
your code should check if you are the file owner.
Related
Upvotes: 3
Reputation: 64032
Try this:
obj.sort(function(a, b) {
var a=new Date(a.date).valueOf();
var b=new Date(b.date).valueOf();
return b-a;
});
Upvotes: 1