Skip to content

Commit

Permalink
perf(core): resize image using Jimp
Browse files Browse the repository at this point in the history
  • Loading branch information
soyombo-baterdene authored and dulguun0225 committed Aug 7, 2023
1 parent b1ba6a1 commit 768485a
Show file tree
Hide file tree
Showing 4 changed files with 545 additions and 70 deletions.
3 changes: 2 additions & 1 deletion packages/core/package.json
Expand Up @@ -59,6 +59,7 @@
"stream-array": "^1.1.2",
"ts-node": "^10.7.0",
"validator": "^9.0.0",
"xlsx-populate": "^1.20.1"
"xlsx-populate": "^1.20.1",
"jimp":"^0.22.10"
}
}
88 changes: 28 additions & 60 deletions packages/core/src/data/utils.ts
Expand Up @@ -17,8 +17,7 @@ import { IModels } from '../connectionResolver';
import { USER_ROLES } from '@erxes/api-utils/src/constants';
import { getService, getServices, redis } from '../serviceDiscovery';
import { sendContactsMessage } from '../messageBroker';
// import * as sharp from 'sharp';

import * as jimp from 'jimp';
export interface IEmailParams {
toEmails?: string[];
fromEmail?: string;
Expand Down Expand Up @@ -294,6 +293,8 @@ export const checkFile = async (models: IModels, file, source?: string) => {
// determine file type using magic numbers
const ft = fileType(buffer);

console.log('FILE TYPEeeeeeeee', ft);

const unsupportedMimeTypes = [
'text/csv',
'image/svg+xml',
Expand All @@ -308,6 +309,8 @@ export const checkFile = async (models: IModels, file, source?: string) => {
'application/vnd.ms-powerpoint'
];

console.log('FILE TYPE', file.type);

// allow csv, svg to be uploaded
if (!ft && unsupportedMimeTypes.includes(file.type)) {
return 'ok';
Expand Down Expand Up @@ -443,6 +446,7 @@ export const uploadFileAWS = async (
const s3 = await createAWS(models);

// generate unique name

const fileName = `${AWS_PREFIX}${Math.random()}${file.name.replace(
/ /g,
''
Expand Down Expand Up @@ -1059,65 +1063,29 @@ export const handleUnsubscription = async (

export const resizeImage = async (
file: any,
_maxWidth: number,
_maxHeight: number
maxWidth?: number,
maxHeight?: number
) => {
// TODO: implement image resize again

// const response: any = await new Promise(resolve => {
// sharp(file['path']).metadata((err, metadata) => {
// if (err) {
// console.error('Error reading image metadata:', err);
// resolve(file);
// } else {
// let width = metadata.width;
// let height = metadata.height;

// let scaledWidth = 0;
// let scaledHeight = 0;

// if (width && height) {
// if (maxWidth && width >= maxWidth) {
// const ratio = maxWidth / width;
// scaledHeight = Math.floor(height * ratio);
// scaledWidth = Math.floor(width * ratio);
// } else if (maxHeight && height >= maxHeight) {
// const ratio = maxHeight / height;
// scaledWidth = Math.floor(width * ratio);
// scaledHeight = Math.floor(height * ratio);
// }
// }
// // Resize image
// const outputFilePath = file['path'] + 'resizedImage';

// if (scaledHeight > 0 && scaledWidth > 0) {
// sharp(file['path'])
// .resize(scaledWidth, scaledHeight)
// .toFile(outputFilePath, err => {
// if (err) {
// console.log(err);
// resolve(file);
// } else {
// const buffer = fs.readFileSync(outputFilePath);
// const newFile = {
// size: buffer.length,
// type: file['type'],
// path: outputFilePath,
// name: file['name']
// } as any;
// resolve(newFile);
// }
// });
// } else {
// resolve(file);
// }
// }
// });
// });
// if (response) {
// return response;
// }
return file;
try {
let image = await jimp.read(`${file.path}`);

if (!image) {
throw new Error('Error reading image');
}

if (maxWidth && image.getWidth() > maxWidth) {
image = image.resize(maxWidth, jimp.AUTO);
} else if (maxHeight && image.getHeight() > maxHeight) {
image = image.resize(jimp.AUTO, maxHeight);
}

await image.writeAsync(file.path);

return file;
} catch (error) {
console.error(error);
return file;
}
};

export const getEnv = utils.getEnv;
Expand Down
23 changes: 18 additions & 5 deletions packages/core/src/middlewares/fileMiddleware.ts
Expand Up @@ -3,9 +3,11 @@ import * as formidable from 'formidable';
import * as request from 'request';
import { generateModels } from '../connectionResolver';
import * as _ from 'underscore';
import * as fileType from 'file-type';
import * as fs from 'fs';
import { filterXSS } from 'xss';

import { checkFile, uploadFile } from '../data/utils';
import { checkFile, resizeImage, uploadFile } from '../data/utils';
import { debugExternalApi } from '../debuggers';
import { getSubdomain } from '@erxes/api-utils/src/core';

Expand All @@ -16,6 +18,9 @@ export const uploader = async (req: any, res, next) => {
const domain = DOMAIN.replace('<subdomain>', subdomain);
const models = await generateModels(subdomain);

const maxHeight = Number(req.query.maxHeight);
const maxWidth = Number(req.query.maxWidth);

const INTEGRATIONS_API_DOMAIN = `${domain}/gateway/pl:integrations`;

if (req.query.kind === 'nylas') {
Expand All @@ -42,16 +47,24 @@ export const uploader = async (req: any, res, next) => {
const form = new formidable.IncomingForm();

form.parse(req, async (_error, _fields, response) => {
const file = response.file || response.upload;
const file: any = response.file || response.upload;

// check file ====
const status = await checkFile(models, file, req.headers.source);
let fileResult = file;

const detectedType = fileType(fs.readFileSync(file.path));
if (detectedType && detectedType.mime.startsWith('image/')) {
if (maxHeight || maxWidth) {
fileResult = await resizeImage(file, maxWidth, maxHeight);
}
}

// check file ====
const status = await checkFile(models, fileResult, req.headers.source);
if (status === 'ok') {
try {
const result = await uploadFile(
`${domain}/gateway`,
file,
fileResult,
response.upload ? true : false,
models
);
Expand Down

0 comments on commit 768485a

Please sign in to comment.