2022-08-10 10:13:31 +00:00
|
|
|
const UserError = require('vn-loopback/util/user-error');
|
2022-05-03 09:16:56 +00:00
|
|
|
const fs = require('fs-extra');
|
|
|
|
const path = require('path');
|
|
|
|
|
|
|
|
module.exports = Self => {
|
|
|
|
Self.remoteMethod('deleteTrashFiles', {
|
|
|
|
description: 'Deletes files that have trash type',
|
|
|
|
accessType: 'WRITE',
|
|
|
|
returns: {
|
|
|
|
type: 'object',
|
|
|
|
root: true
|
|
|
|
},
|
|
|
|
http: {
|
|
|
|
path: `/deleteTrashFiles`,
|
2022-09-13 11:53:44 +00:00
|
|
|
verb: 'POST'
|
2022-05-03 09:16:56 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2022-07-26 09:47:43 +00:00
|
|
|
Self.deleteTrashFiles = async options => {
|
2022-05-03 09:16:56 +00:00
|
|
|
const tx = await Self.beginTransaction({});
|
|
|
|
const myOptions = {};
|
|
|
|
|
|
|
|
if (typeof options == 'object')
|
|
|
|
Object.assign(myOptions, options);
|
|
|
|
|
|
|
|
if (!myOptions.transaction)
|
|
|
|
myOptions.transaction = tx;
|
|
|
|
|
|
|
|
try {
|
2022-08-10 10:13:31 +00:00
|
|
|
if (process.env.NODE_ENV == 'test')
|
|
|
|
throw new UserError(`Action not allowed on the test environment`);
|
|
|
|
|
2022-05-03 09:16:56 +00:00
|
|
|
const models = Self.app.models;
|
|
|
|
const DmsContainer = models.DmsContainer;
|
|
|
|
|
|
|
|
const trashDmsType = await models.DmsType.findOne({
|
|
|
|
where: {code: 'trash'}
|
|
|
|
}, myOptions);
|
|
|
|
|
2022-08-10 10:13:31 +00:00
|
|
|
const date = new Date();
|
|
|
|
date.setMonth(date.getMonth() - 4);
|
|
|
|
|
2022-05-03 09:16:56 +00:00
|
|
|
const dmsToDelete = await models.Dms.find({
|
|
|
|
where: {
|
2022-08-10 10:13:31 +00:00
|
|
|
and: [
|
|
|
|
{dmsTypeFk: trashDmsType.id},
|
|
|
|
{created: {lt: date}}
|
|
|
|
]
|
2022-05-03 09:16:56 +00:00
|
|
|
}
|
|
|
|
}, myOptions);
|
|
|
|
|
|
|
|
for (let dms of dmsToDelete) {
|
|
|
|
const pathHash = DmsContainer.getHash(dms.id);
|
|
|
|
const dmsContainer = await DmsContainer.container(pathHash);
|
|
|
|
const dstFile = path.join(dmsContainer.client.root, pathHash, dms.file);
|
2022-09-21 06:56:13 +00:00
|
|
|
try {
|
|
|
|
await fs.unlink(dstFile);
|
|
|
|
} catch (err) {
|
|
|
|
continue;
|
|
|
|
}
|
2022-08-10 10:13:31 +00:00
|
|
|
const dstFolder = path.join(dmsContainer.client.root, pathHash);
|
|
|
|
try {
|
|
|
|
await fs.rmdir(dstFolder);
|
|
|
|
await dms.destroy(myOptions);
|
|
|
|
} catch (err) {
|
|
|
|
await dms.destroy(myOptions);
|
|
|
|
}
|
2022-05-03 09:16:56 +00:00
|
|
|
}
|
|
|
|
if (tx) await tx.commit();
|
|
|
|
} catch (e) {
|
|
|
|
if (tx) await tx.rollback();
|
2022-07-26 09:47:43 +00:00
|
|
|
|
2022-05-03 09:16:56 +00:00
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|