salix/back/models/image.js

106 lines
3.3 KiB
JavaScript
Raw Normal View History

2020-07-13 09:58:31 +00:00
const fs = require('fs-extra');
const sharp = require('sharp');
const path = require('path');
module.exports = Self => {
2020-11-10 07:39:34 +00:00
require('../methods/image/download')(Self);
2020-07-14 07:32:50 +00:00
Self.getPath = function() {
2020-08-18 07:48:02 +00:00
return '/var/lib/salix/image';
2020-07-14 07:32:50 +00:00
};
Self.registerImage = async(collectionName, file, srcFilePath) => {
2020-07-13 09:58:31 +00:00
const models = Self.app.models;
const tx = await Self.beginTransaction({});
const myOptions = {transaction: tx};
try {
const collection = await models.ImageCollection.findOne({
fields: [
'id',
'name',
'maxWidth',
'maxHeight',
'model',
'property'
],
where: {name: collectionName},
include: {
relation: 'sizes',
scope: {
fields: ['width', 'height', 'crop']
}
}
2020-07-14 07:32:50 +00:00
}, myOptions);
2020-07-13 09:58:31 +00:00
const fileName = file.split('.')[0];
2020-07-14 07:32:50 +00:00
const rootPath = Self.getPath();
2020-07-13 09:58:31 +00:00
const data = {
name: fileName,
collectionFk: collectionName
};
const newImage = await Self.upsertWithWhere(data, {
name: fileName,
collectionFk: collectionName,
updated: (new Date).getTime()
}, myOptions);
// Resizes and saves the image
const collectionDir = path.join(rootPath, collectionName);
const dstDir = path.join(collectionDir, 'full');
const dstFile = path.join(dstDir, file);
const resizeOpts = {
withoutEnlargement: true,
fit: 'inside'
};
await fs.mkdir(dstDir, {recursive: true});
2020-08-18 07:45:26 +00:00
await sharp(srcFilePath, {failOnError: false})
2020-07-13 09:58:31 +00:00
.resize(collection.maxWidth, collection.maxHeight, resizeOpts)
2020-08-18 07:45:26 +00:00
.png()
2020-07-13 09:58:31 +00:00
.toFile(dstFile);
const sizes = collection.sizes();
for (let size of sizes) {
const dstDir = path.join(collectionDir, `${size.width}x${size.height}`);
const dstFile = path.join(dstDir, file);
const resizeOpts = {
withoutEnlargement: true,
fit: size.crop ? 'cover' : 'inside'
};
await fs.mkdir(dstDir, {recursive: true});
2020-08-18 07:45:26 +00:00
await sharp(srcFilePath, {failOnError: false})
2020-07-13 09:58:31 +00:00
.resize(size.width, size.height, resizeOpts)
2020-08-18 07:45:26 +00:00
.png()
2020-07-13 09:58:31 +00:00
.toFile(dstFile);
}
const model = models[collection.model];
if (!model)
throw new Error('Matching model not found');
const item = await model.findById(fileName, null, myOptions);
if (item) {
await item.updateAttribute(
collection.property,
fileName,
myOptions
);
}
2020-08-27 12:00:40 +00:00
if (fs.existsSync(srcFilePath))
2020-08-27 11:53:11 +00:00
await fs.unlink(srcFilePath);
2020-07-13 09:58:31 +00:00
await tx.commit();
return newImage;
} catch (e) {
await tx.rollback();
throw e;
}
};
};