Notes/src/services/image.js

228 lines
6.7 KiB
JavaScript
Raw Normal View History

2018-02-11 00:18:59 -05:00
"use strict";
2021-06-29 22:15:57 +02:00
const becca = require('../becca/becca');
const log = require('./log');
const protectedSessionService = require('./protected_session');
2018-11-08 11:08:16 +01:00
const noteService = require('./notes');
const optionService = require('./options');
const sql = require('./sql');
2018-02-11 00:18:59 -05:00
const jimp = require('jimp');
const imageType = require('image-type');
const sanitizeFilename = require('sanitize-filename');
2020-03-25 11:28:44 +01:00
const isSvg = require('is-svg');
const isAnimated = require('is-animated');
const htmlSanitizer = require("./html_sanitizer");
2018-02-11 00:18:59 -05:00
async function processImage(uploadBuffer, originalName, shrinkImageSwitch) {
const compressImages = optionService.getOptionBool("compressImages");
2020-03-25 11:28:44 +01:00
const origImageFormat = getImageType(uploadBuffer);
2019-07-10 20:38:27 +02:00
if (!origImageFormat || !["jpg", "png"].includes(origImageFormat.ext)) {
2019-07-10 20:38:27 +02:00
shrinkImageSwitch = false;
}
else if (isAnimated(uploadBuffer)) {
// recompression of animated images will make them static
shrinkImageSwitch = false;
}
2019-07-10 20:38:27 +02:00
let finalImageBuffer;
let imageFormat;
2018-02-11 00:18:59 -05:00
if (compressImages && shrinkImageSwitch) {
finalImageBuffer = await shrinkImage(uploadBuffer, originalName);
imageFormat = getImageType(finalImageBuffer);
} else {
finalImageBuffer = uploadBuffer;
imageFormat = origImageFormat || {
ext: 'dat'
};
}
2018-02-11 00:18:59 -05:00
2019-11-08 22:34:30 +01:00
return {
buffer: finalImageBuffer,
imageFormat
};
}
2020-03-25 11:28:44 +01:00
function getImageType(buffer) {
if (isSvg(buffer)) {
return {
ext: 'svg'
}
}
else {
return imageType(buffer) || {
ext: "jpg"
}; // optimistic JPG default
2020-03-25 11:28:44 +01:00
}
}
2020-03-25 18:21:55 +01:00
function getImageMimeFromExtension(ext) {
ext = ext.toLowerCase();
return `image/${ext === 'svg' ? 'svg+xml' : ext}`;
2020-03-25 18:21:55 +01:00
}
2020-06-20 12:31:38 +02:00
function updateImage(noteId, uploadBuffer, originalName) {
2020-04-08 11:07:38 +02:00
log.info(`Updating image ${noteId}: ${originalName}`);
originalName = htmlSanitizer.sanitize(originalName);
2021-05-02 11:23:58 +02:00
const note = becca.getNote(noteId);
2019-11-08 22:34:30 +01:00
2022-06-13 22:38:59 +02:00
note.saveNoteRevision();
2019-11-08 22:34:30 +01:00
2020-06-20 12:31:38 +02:00
note.setLabel('originalFileName', originalName);
2019-11-08 23:09:57 +01:00
// resizing images asynchronously since JIMP does not support sync operation
processImage(uploadBuffer, originalName, true).then(({buffer, imageFormat}) => {
sql.transactional(() => {
note.mime = getImageMimeFromExtension(imageFormat.ext);
note.save();
note.setContent(buffer);
2023-01-25 15:20:53 +01:00
});
});
2019-11-08 22:34:30 +01:00
}
function saveImage(parentNoteId, uploadBuffer, originalName, shrinkImageSwitch, trimFilename = false) {
2022-02-20 12:33:50 +01:00
log.info(`Saving image ${originalName} into parent ${parentNoteId}`);
2020-04-08 11:07:38 +02:00
if (trimFilename && originalName.length > 40) {
// https://github.com/zadam/trilium/issues/2307
originalName = "image";
}
2018-02-11 00:18:59 -05:00
const fileName = sanitizeFilename(originalName);
2021-05-02 11:23:58 +02:00
const parentNote = becca.getNote(parentNoteId);
2019-11-08 22:34:30 +01:00
2020-06-20 12:31:38 +02:00
const {note} = noteService.createNewNote({
2019-11-16 11:09:52 +01:00
parentNoteId,
title: fileName,
2018-11-08 11:08:16 +01:00
type: 'image',
mime: 'unknown',
content: '',
2019-11-16 11:09:52 +01:00
isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()
2018-11-08 11:08:16 +01:00
});
2018-02-11 00:18:59 -05:00
2020-06-20 12:31:38 +02:00
note.addLabel('originalFileName', originalName);
2019-11-16 11:09:52 +01:00
// resizing images asynchronously since JIMP does not support sync operation
processImage(uploadBuffer, originalName, shrinkImageSwitch).then(({buffer, imageFormat}) => {
sql.transactional(() => {
note.mime = getImageMimeFromExtension(imageFormat.ext);
if (!originalName.includes(".")) {
originalName += `.${imageFormat.ext}`;
note.setLabel('originalFileName', originalName);
note.title = sanitizeFilename(originalName);
}
2023-03-16 18:34:39 +01:00
note.setContent(buffer, { forceSave: true });
2023-01-26 09:42:11 +01:00
});
});
return {
fileName,
2019-02-25 21:22:57 +01:00
note,
2018-11-08 11:08:16 +01:00
noteId: note.noteId,
2023-03-16 20:13:34 +01:00
url: `api/images/${note.noteId}/${encodeURIComponent(fileName)}`
};
2018-02-11 00:18:59 -05:00
}
2023-03-16 18:34:39 +01:00
function saveImageToAttachment(noteId, uploadBuffer, originalName, shrinkImageSwitch, trimFilename = false) {
log.info(`Saving image '${originalName}' as attachment into note '${noteId}'`);
if (trimFilename && originalName.length > 40) {
// https://github.com/zadam/trilium/issues/2307
originalName = "image";
}
const fileName = sanitizeFilename(originalName);
const note = becca.getNoteOrThrow(noteId);
2023-03-16 18:34:39 +01:00
const attachment = note.saveAttachment({
role: 'image',
mime: 'unknown',
title: fileName
});
// resizing images asynchronously since JIMP does not support sync operation
processImage(uploadBuffer, originalName, shrinkImageSwitch).then(({buffer, imageFormat}) => {
sql.transactional(() => {
attachment.mime = getImageMimeFromExtension(imageFormat.ext);
if (!originalName.includes(".")) {
originalName += `.${imageFormat.ext}`;
attachment.title = sanitizeFilename(originalName);
}
attachment.setContent(buffer, { forceSave: true });
});
});
return {
attachment,
2023-04-17 22:40:53 +02:00
url: `api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(fileName)}`
2023-03-16 18:34:39 +01:00
};
}
2019-03-03 20:41:03 +01:00
async function shrinkImage(buffer, originalName) {
let jpegQuality = optionService.getOptionInt('imageJpegQuality', 0);
if (jpegQuality < 10 || jpegQuality > 100) {
jpegQuality = 75;
}
let finalImageBuffer;
try {
finalImageBuffer = await resize(buffer, jpegQuality);
}
catch (e) {
2023-01-25 15:20:53 +01:00
log.error(`Failed to resize image '${originalName}', stack: ${e.stack}`);
finalImageBuffer = buffer;
2019-02-24 12:24:28 +01:00
}
2023-05-05 23:41:11 +02:00
// if resizing did not help with size, then save the original
// (can happen when e.g., resizing PNG into JPEG)
if (finalImageBuffer.byteLength >= buffer.byteLength) {
finalImageBuffer = buffer;
}
2019-02-24 12:24:28 +01:00
return finalImageBuffer;
}
async function resize(buffer, quality) {
2020-06-20 12:31:38 +02:00
const imageMaxWidthHeight = optionService.getOptionInt('imageMaxWidthHeight');
2023-01-25 15:20:53 +01:00
const start = Date.now();
const image = await jimp.read(buffer);
2018-02-11 00:18:59 -05:00
if (image.bitmap.width > image.bitmap.height && image.bitmap.width > imageMaxWidthHeight) {
image.resize(imageMaxWidthHeight, jimp.AUTO);
2018-02-11 00:18:59 -05:00
}
else if (image.bitmap.height > imageMaxWidthHeight) {
image.resize(jimp.AUTO, imageMaxWidthHeight);
2018-02-11 00:18:59 -05:00
}
image.quality(quality);
2018-02-11 00:18:59 -05:00
2023-05-05 23:41:11 +02:00
// when converting PNG to JPG, we lose the alpha channel, this is replaced by white to match Trilium white background
2018-02-11 00:18:59 -05:00
image.background(0xFFFFFFFF);
2023-01-25 15:20:53 +01:00
const resultBuffer = await image.getBufferAsync(jimp.MIME_JPEG);
log.info(`Resizing image of ${resultBuffer.byteLength} took ${Date.now() - start}ms`);
return resultBuffer;
2018-02-11 00:18:59 -05:00
}
module.exports = {
2019-11-08 22:34:30 +01:00
saveImage,
2023-03-16 18:34:39 +01:00
saveImageToAttachment,
2019-11-08 22:34:30 +01:00
updateImage
2020-06-20 12:31:38 +02:00
};