salix/back/models/image.js

113 lines
3.5 KiB
JavaScript
Raw Normal View History

2020-07-13 09:58:31 +00:00
const fs = require('fs-extra');
const path = require('path');
const gm = require('gm');
2020-07-13 09:58:31 +00:00
module.exports = Self => {
2020-11-10 07:39:34 +00:00
require('../methods/image/download')(Self);
2020-11-27 12:10:39 +00:00
require('../methods/image/upload')(Self);
require('../methods/image/scrub')(Self);
2020-11-10 07:39:34 +00:00
Self.resize = async function({collectionName, srcFile, fileName, entityId}) {
2020-07-13 09:58:31 +00:00
const models = Self.app.models;
const collection = await models.ImageCollection.findOne(
{
2020-07-13 09:58:31 +00:00
fields: [
'id',
'maxWidth',
'maxHeight',
'model',
'property',
2020-07-13 09:58:31 +00:00
],
where: {name: collectionName},
include: {
relation: 'sizes',
scope: {
fields: ['width', 'height', 'crop'],
},
},
}
);
2020-07-13 09:58:31 +00:00
// Insert image row
2023-04-17 20:24:19 +00:00
const imageName = path.parse(fileName).name;
await models.Image.upsertWithWhere(
{
2023-04-17 20:24:19 +00:00
name: imageName,
2020-07-13 09:58:31 +00:00
collectionFk: collectionName
},
{
2023-04-17 20:24:19 +00:00
name: imageName,
2020-07-13 09:58:31 +00:00
collectionFk: collectionName,
updated: Date.vnNow() / 1000,
2020-07-13 09:58:31 +00:00
}
);
// Update entity image file name
const model = models[collection.model];
if (!model) throw new Error('No matching model found');
const entity = await model.findById(entityId);
if (entity) {
await entity.updateAttribute(
collection.property,
2023-04-17 20:24:19 +00:00
imageName
);
}
2020-07-13 09:58:31 +00:00
// Resize
const container = await models.ImageContainer.container(
collectionName
);
const rootPath = container.client.root;
const collectionDir = path.join(rootPath, collectionName);
// To max size
const {maxWidth, maxHeight} = collection;
const fullSizePath = path.join(collectionDir, 'full');
const toFullSizePath = `${fullSizePath}/${fileName}`;
await fs.mkdir(fullSizePath, {recursive: true});
await new Promise((resolve, reject) => {
gm(srcFile)
.resize(maxWidth, maxHeight, '>')
.setFormat('png')
2023-04-14 11:19:17 +00:00
.quality(100)
.write(toFullSizePath, function(err) {
if (err) reject(err);
if (!err) resolve();
});
});
// To collection sizes
for (const size of collection.sizes()) {
const {width, height} = size;
const sizePath = path.join(collectionDir, `${width}x${height}`);
const toSizePath = `${sizePath}/${fileName}`;
await fs.mkdir(sizePath, {recursive: true});
await new Promise((resolve, reject) => {
const gmInstance = gm(srcFile);
if (size.crop) {
gmInstance
.resize(width, height, '^')
.gravity('Center')
.crop(width, height);
}
2020-08-27 11:53:11 +00:00
if (!size.crop) gmInstance.resize(width, height, '>');
gmInstance
.setFormat('png')
2023-04-14 11:19:17 +00:00
.quality(100)
.write(toSizePath, function(err) {
if (err) reject(err);
if (!err) resolve();
});
});
2020-07-13 09:58:31 +00:00
}
};
};