Files
planka/server/api/helpers/background-images/process-uploaded-file.js

106 lines
2.3 KiB
JavaScript
Raw Normal View History

/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
2025-08-23 00:03:20 +02:00
const { v4: uuid } = require('uuid');
const { rimraf } = require('rimraf');
const mime = require('mime');
const sharp = require('sharp');
module.exports = {
inputs: {
file: {
type: 'json',
required: true,
},
},
exits: {
fileIsNotImage: {},
},
async fn(inputs) {
const mimeType = mime.getType(inputs.file.filename);
if (['image/svg+xml', 'application/pdf'].includes(mimeType)) {
await rimraf(inputs.file.fd);
throw 'fileIsNotImage';
}
let image = sharp(inputs.file.fd, {
animated: true,
});
let metadata;
2025-08-23 00:03:20 +02:00
let originalBuffer;
try {
metadata = await image.metadata();
2025-08-23 00:03:20 +02:00
if (metadata.orientation && metadata.orientation > 4) {
image = image.rotate();
}
originalBuffer = await image.toBuffer();
} catch (error) {
await rimraf(inputs.file.fd);
throw 'fileIsNotImage';
}
const fileManager = sails.hooks['file-manager'].getInstance();
2025-08-23 00:03:20 +02:00
const extension = metadata.format === 'jpeg' ? 'jpg' : metadata.format;
const size = originalBuffer.length;
2025-08-23 00:03:20 +02:00
const { id: uploadedFileId } = await UploadedFile.qm.createOne({
mimeType,
size,
id: uuid(),
type: UploadedFile.Types.BACKGROUND_IMAGE,
});
2025-08-23 00:03:20 +02:00
const dirPathSegment = `${sails.config.custom.backgroundImagesPathSegment}/${uploadedFileId}`;
try {
await fileManager.save(
`${dirPathSegment}/original.${extension}`,
originalBuffer,
inputs.file.type,
);
const outside360Buffer = await image
.resize(360, 360, {
fit: 'outside',
withoutEnlargement: true,
})
.png({
quality: 75,
force: false,
})
.toBuffer();
await fileManager.save(
`${dirPathSegment}/outside-360.${extension}`,
outside360Buffer,
inputs.file.type,
);
} catch (error) {
sails.log.warn(error.stack);
await fileManager.deleteDir(dirPathSegment);
await rimraf(inputs.file.fd);
2025-08-23 00:03:20 +02:00
await UploadedFile.qm.deleteOne(uploadedFileId);
throw 'fileIsNotImage';
}
await rimraf(inputs.file.fd);
return {
2025-08-23 00:03:20 +02:00
uploadedFileId,
extension,
2025-08-23 00:03:20 +02:00
size,
};
},
};