-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathimage.ts
236 lines (185 loc) · 7.6 KB
/
image.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
"use strict";
import becca from "../becca/becca.js";
import log from "./log.js";
import protectedSessionService from "./protected_session.js";
import noteService from "./notes.js";
import optionService from "./options.js";
import sql from "./sql.js";
import { Jimp } from "jimp";
import imageType from "image-type";
import sanitizeFilename from "sanitize-filename";
import isSvg from "is-svg";
import isAnimated from "is-animated";
import htmlSanitizer from "./html_sanitizer.js";
async function processImage(uploadBuffer: Buffer, originalName: string, shrinkImageSwitch: boolean) {
const compressImages = optionService.getOptionBool("compressImages");
const origImageFormat = await getImageType(uploadBuffer);
if (!origImageFormat || !["jpg", "png"].includes(origImageFormat.ext)) {
shrinkImageSwitch = false;
} else if (isAnimated(uploadBuffer)) {
// recompression of animated images will make them static
shrinkImageSwitch = false;
}
let finalImageBuffer;
let imageFormat;
if (compressImages && shrinkImageSwitch) {
finalImageBuffer = await shrinkImage(uploadBuffer, originalName);
imageFormat = await getImageType(finalImageBuffer);
} else {
finalImageBuffer = uploadBuffer;
imageFormat = origImageFormat || {
ext: "dat"
};
}
return {
buffer: finalImageBuffer,
imageFormat
};
}
async function getImageType(buffer: Buffer) {
if (isSvg(buffer.toString())) {
return { ext: "svg" };
} else {
return (await imageType(buffer)) || { ext: "jpg" }; // optimistic JPG default
}
}
function getImageMimeFromExtension(ext: string) {
ext = ext.toLowerCase();
return `image/${ext === "svg" ? "svg+xml" : ext}`;
}
function updateImage(noteId: string, uploadBuffer: Buffer, originalName: string) {
log.info(`Updating image ${noteId}: ${originalName}`);
originalName = htmlSanitizer.sanitize(originalName);
const note = becca.getNote(noteId);
if (!note) {
throw new Error("Unable to find note.");
}
note.saveRevision();
note.setLabel("originalFileName", originalName);
// 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);
});
});
}
function saveImage(parentNoteId: string, uploadBuffer: Buffer, originalName: string, shrinkImageSwitch: boolean, trimFilename = false) {
log.info(`Saving image ${originalName} into parent ${parentNoteId}`);
if (trimFilename && originalName.length > 40) {
// https://github.com/zadam/trilium/issues/2307
originalName = "image";
}
const fileName = sanitizeFilename(originalName);
const parentNote = becca.getNote(parentNoteId);
if (!parentNote) {
throw new Error("Unable to find parent note.");
}
const { note } = noteService.createNewNote({
parentNoteId,
title: fileName,
type: "image",
mime: "unknown",
content: "",
isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()
});
note.addLabel("originalFileName", originalName);
// 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);
}
note.setContent(buffer, { forceSave: true });
});
});
return {
fileName,
note,
noteId: note.noteId,
url: `api/images/${note.noteId}/${encodeURIComponent(fileName)}`
};
}
function saveImageToAttachment(noteId: string, uploadBuffer: Buffer, originalName: string, shrinkImageSwitch?: boolean, 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);
let attachment = note.saveAttachment({
role: "image",
mime: "unknown",
title: fileName
});
// TODO: this is a quick-fix solution of a recursive bug - this is called from asyncPostProcessContent()
// find some async way to do this - perhaps some global timeout with a Set of noteIds needing one more
// run of asyncPostProcessContent
setTimeout(() => {
sql.transactional(() => {
const note = becca.getNoteOrThrow(noteId);
noteService.asyncPostProcessContent(note, note.getContent()); // to mark an unused attachment for deletion
});
}, 5000);
// resizing images asynchronously since JIMP does not support sync operation
processImage(uploadBuffer, originalName, !!shrinkImageSwitch).then(({ buffer, imageFormat }) => {
sql.transactional(() => {
// re-read, might be changed in the meantime
if (!attachment.attachmentId) {
throw new Error("Missing attachment ID.");
}
attachment = becca.getAttachmentOrThrow(attachment.attachmentId);
attachment.mime = getImageMimeFromExtension(imageFormat.ext);
if (!originalName.includes(".")) {
originalName += `.${imageFormat.ext}`;
attachment.title = sanitizeFilename(originalName);
}
attachment.setContent(buffer, { forceSave: true });
});
});
return attachment;
}
async function shrinkImage(buffer: Buffer, originalName: string) {
let jpegQuality = optionService.getOptionInt("imageJpegQuality", 0);
if (jpegQuality < 10 || jpegQuality > 100) {
jpegQuality = 75;
}
let finalImageBuffer;
try {
finalImageBuffer = await resize(buffer, jpegQuality);
} catch (e: any) {
log.error(`Failed to resize image '${originalName}', stack: ${e.stack}`);
finalImageBuffer = buffer;
}
// 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;
}
return finalImageBuffer;
}
async function resize(buffer: Buffer, quality: number) {
const imageMaxWidthHeight = optionService.getOptionInt("imageMaxWidthHeight");
const start = Date.now();
const image = await Jimp.read(buffer);
if (image.bitmap.width > image.bitmap.height && image.bitmap.width > imageMaxWidthHeight) {
image.resize({ w: imageMaxWidthHeight });
} else if (image.bitmap.height > imageMaxWidthHeight) {
image.resize({ h: imageMaxWidthHeight });
}
// when converting PNG to JPG, we lose the alpha channel, this is replaced by white to match Trilium white background
image.background = 0xffffffff;
const resultBuffer = await image.getBuffer("image/jpeg", { quality });
log.info(`Resizing image of ${resultBuffer.byteLength} took ${Date.now() - start}ms`);
return resultBuffer;
}
export default {
saveImage,
saveImageToAttachment,
updateImage
};