1
0
Fork 1
mirror of https://example.com synced 2024-11-27 10:36:38 +09:00
firefish/cli/clean-unused-drive-files.js

81 lines
2 KiB
JavaScript
Raw Normal View History

2018-05-04 13:24:08 +09:00
const chalk = require('chalk');
const log = require('single-line-log').stdout;
const sequential = require('promise-sequential');
const { default: DriveFile, deleteDriveFile } = require('../built/models/drive-file');
const { default: Note } = require('../built/models/note');
const { default: MessagingMessage } = require('../built/models/messaging-message');
const { default: User } = require('../built/models/user');
async function main() {
const promiseGens = [];
const count = await DriveFile.count({});
let prev;
2018-05-04 17:20:40 +09:00
for (let i = 0; i < count; i++) {
2018-05-04 13:24:08 +09:00
promiseGens.push(() => {
const promise = new Promise(async (res, rej) => {
const file = await DriveFile.findOne(prev ? {
2018-05-04 15:07:02 +09:00
_id: { $lt: prev._id }
2018-05-04 13:24:08 +09:00
} : {}, {
sort: {
2018-05-04 15:07:02 +09:00
_id: -1
2018-05-04 13:24:08 +09:00
}
});
2018-05-04 13:24:08 +09:00
prev = file;
2018-05-04 17:27:14 +09:00
function skip() {
res([i, file, false]);
}
2018-05-04 15:07:02 +09:00
if (file == null) return skip();
2018-05-04 15:15:17 +09:00
log(chalk`{gray ${i}} scanning {bold ${file._id}} ${file.filename} ...`);
2018-05-04 13:24:08 +09:00
const attachingUsersCount = await User.count({
$or: [{
avatarId: file._id
}, {
bannerId: file._id
}]
}, { limit: 1 });
2018-05-04 15:07:02 +09:00
if (attachingUsersCount !== 0) return skip();
2018-05-04 13:24:08 +09:00
const attachingNotesCount = await Note.count({
mediaIds: file._id
}, { limit: 1 });
2018-05-04 15:07:02 +09:00
if (attachingNotesCount !== 0) return skip();
2018-05-04 13:24:08 +09:00
const attachingMessagesCount = await MessagingMessage.count({
fileId: file._id
}, { limit: 1 });
2018-05-04 15:07:02 +09:00
if (attachingMessagesCount !== 0) return skip();
2018-05-04 13:24:08 +09:00
2018-05-04 15:07:02 +09:00
deleteDriveFile(file).then(() => {
res([i, file, true]);
}).catch(rej);
2018-05-04 13:24:08 +09:00
});
2018-05-04 15:07:02 +09:00
promise.then(([i, file, deleted]) => {
if (deleted) {
2018-05-04 15:15:17 +09:00
log(chalk`{gray ${i}} {red deleted: {bold ${file._id}} ${file.filename}}`);
2018-05-04 15:07:02 +09:00
} else {
2018-05-04 15:15:17 +09:00
log(chalk`{gray ${i}} {green skipped: {bold ${file._id}} ${file.filename}}`);
2018-05-04 13:24:08 +09:00
}
log.clear();
console.log();
});
2018-05-04 13:24:08 +09:00
return promise;
});
}
return await sequential(promiseGens);
}
2018-05-04 15:15:17 +09:00
main().then(() => {
console.log('done');
}).catch(console.error);