iceshrimp/cli/clean-cached-remote-files.js

102 lines
2.3 KiB
JavaScript
Raw Normal View History

2018-05-04 17:20:40 +09:00
const chalk = require('chalk');
const log = require('single-line-log').stdout;
const sequential = require('promise-sequential');
const { default: DriveFile, DriveFileChunk } = require('../built/models/drive-file');
const { default: DriveFileThumbnail, DriveFileThumbnailChunk } = require('../built/models/drive-file-thumbnail');
const { default: User } = require('../built/models/user');
const q = {
'metadata._user.host': {
$ne: null
},
2018-07-24 05:04:43 +09:00
'metadata.withoutChunks': false
2018-05-04 17:20:40 +09:00
};
async function main() {
const promiseGens = [];
const count = await DriveFile.count(q);
let prev;
for (let i = 0; i < count; i++) {
promiseGens.push(() => {
const promise = new Promise(async (res, rej) => {
const file = await DriveFile.findOne(prev ? Object.assign({
_id: { $lt: prev._id }
}, q) : q, {
sort: {
_id: -1
}
});
prev = file;
2018-05-04 17:27:14 +09:00
function skip() {
res([i, file, false]);
}
2018-05-04 17:20:40 +09:00
2018-05-04 17:27:14 +09:00
if (file == null) return skip();
log(chalk`{gray ${i}} scanning {bold ${file._id}} ${file.filename} ...`);
const attachingUsersCount = await User.count({
$or: [{
avatarId: file._id
}, {
bannerId: file._id
}]
}, { limit: 1 });
if (attachingUsersCount !== 0) return skip();
Promise.all([
// チャンクをすべて削除
DriveFileChunk.remove({
files_id: file._id
}),
DriveFile.update({ _id: file._id }, {
$set: {
2018-07-24 05:04:43 +09:00
'metadata.withoutChunks': true
2018-05-04 17:27:14 +09:00
}
})
2018-05-04 17:38:34 +09:00
]).then(async () => {
2018-05-04 17:27:14 +09:00
res([i, file, true]);
//#region サムネイルもあれば削除
const thumbnail = await DriveFileThumbnail.findOne({
'metadata.originalId': file._id
});
2018-05-04 17:20:40 +09:00
2018-05-04 17:27:14 +09:00
if (thumbnail) {
DriveFileThumbnailChunk.remove({
files_id: thumbnail._id
});
2018-05-04 17:20:40 +09:00
2018-05-04 17:27:14 +09:00
DriveFileThumbnail.remove({ _id: thumbnail._id });
}
//#endregion
2018-05-04 17:20:40 +09:00
});
});
2018-05-04 17:27:14 +09:00
promise.then(([i, file, deleted]) => {
if (deleted) {
log(chalk`{gray ${i}} {red deleted: {bold ${file._id}} ${file.filename}}`);
} else {
log(chalk`{gray ${i}} {green skipped: {bold ${file._id}} ${file.filename}}`);
2018-05-04 17:20:40 +09:00
}
2018-05-04 17:27:14 +09:00
log.clear();
console.log();
2018-05-04 17:20:40 +09:00
});
return promise;
});
}
return await sequential(promiseGens);
}
main().then(() => {
console.log('ALL DONE');
}).catch(console.error);