salix/back/methods/image/scrub.js

71 lines
2.2 KiB
JavaScript
Raw Normal View History

const fs = require('fs-extra');
const path = require('path');
module.exports = Self => {
Self.remoteMethod('scrub', {
description: 'Cleans collection images directory',
accessType: 'WRITE',
accepts: [
{
arg: 'collection',
type: 'string',
description: 'The collection name',
required: true
}, {
arg: 'limit',
type: 'number',
description: 'Maximun number of image to clean'
}
],
returns: {
type: 'number',
root: true
},
http: {
path: `/scrub`,
verb: 'POST'
}
});
Self.scrub = async function(collection, limit) {
const models = Self.app.models;
const container = await models.ImageContainer.container(
collection
);
const rootPath = container.client.root;
const now = Date.vnNew().toJSON();
const scrubDir = path.join(rootPath, '.scrub', now);
const collectionDir = path.join(rootPath, collection);
const sizes = await fs.readdir(collectionDir);
let cleanCount = 0;
mainLoop: for (const size of sizes) {
const sizeDir = path.join(collectionDir, size);
const scrubSizeDir = path.join(scrubDir, collection, size);
const images = await fs.readdir(sizeDir);
for (const image of images) {
const imageName = path.parse(image).name;
const count = await models.Image.count({
collectionFk: collection,
name: imageName
});
const exists = count > 0;
if (!exists) {
cleanCount++;
const srcDir = path.join(sizeDir, image);
const dstDir = path.join(scrubSizeDir, image);
await fs.mkdir(scrubSizeDir, {recursive: true});
await fs.rename(srcDir, dstDir);
if (limit && cleanCount == limit)
break mainLoop;
}
}
}
return cleanCount;
};
};