Skip to content

Instantly share code, notes, and snippets.

@pkspro
Forked from evangs/delete-old-files.js
Created March 9, 2020 05:15
Show Gist options
  • Save pkspro/3e13828dac881ba169adc1cda06bad57 to your computer and use it in GitHub Desktop.
Save pkspro/3e13828dac881ba169adc1cda06bad57 to your computer and use it in GitHub Desktop.
var https = require('https');
// CONFIGURATION #######################################################################################################
var token = '';
var delay = 300; // delay between delete operations in millisecond
// GLOBALS #############################################################################################################
var baseApiUrl = 'https://slack.com/api/';
var fileListApiUrl= baseApiUrl + 'files.list?token=' + token + '&count=1000';
var deleteApiUrl = baseApiUrl + 'files.delete?token=' + token;
var files = [];
var thirtyDaysAgoTimeStamp = (new Date().getTime() - (1000 * 60 * 60 * 24 * 30)) / 1000;
// ---------------------------------------------------------------------------------------------------------------------
function deleteFile() {
if (files.length == 0) {
return;
}
var fileId = files.shift();
https.get(deleteApiUrl + '&file=' + fileId, function (res) {
var body = '';
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function(){
var response = JSON.parse(body);
if (response.ok === true) {
console.log(fileId + ' deleted!');
} else if (response.ok === false) {
files.push(fileId);
}
setTimeout(deleteFile, delay);
});
}).on('error', function (e) {
console.log("Got an error: ", e);
});
}
// ---------------------------------------------------------------------------------------------------------------------
https.get(fileListApiUrl + '&ts_to=' + thirtyDaysAgoTimeStamp, function(res) {
var body = '';
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function() {
var response = JSON.parse(body);
for (var i = 0; i < response.files.length; i++) {
files.push(response.files[i].id);
}
deleteFile();
});
}).on('error', function(e) {
console.log("got an error: ", e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment