Skip to content

Commit e578718

Browse files
committed
feat: [#409] show error image when proxied image
cant' be loaded becuse: - The image proxy returns an error. - The image extension is not allowed.
1 parent 84816bf commit e578718

File tree

1 file changed

+39
-3
lines changed

1 file changed

+39
-3
lines changed

src/domain/services/sanitizer.ts

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { createCanvas, registerFont, CanvasRenderingContext2D } from "canvas";
12
import DOMPurify from "dompurify";
23
import { useRestApi } from "#imports";
34

@@ -23,6 +24,7 @@ async function remove_user_tracking (html: string) {
2324
const htmlDoc = parser.parseFromString(html, "text/html");
2425

2526
remove_all_external_links(htmlDoc);
27+
2628
await replace_images_with_proxied_images(htmlDoc);
2729

2830
return document_to_html(htmlDoc);
@@ -46,10 +48,16 @@ async function replace_images_with_proxied_images (htmlDoc: Document) {
4648

4749
if (src) {
4850
if (isAllowedImage(src)) {
49-
const imageDataSrc = await getImageDataUrl(src);
50-
img.setAttribute("src", imageDataSrc);
51+
try {
52+
const imageDataSrc = await getImageDataUrl(src);
53+
img.setAttribute("src", imageDataSrc);
54+
} catch (e) {
55+
const imageDataUrl = createImageWithText(`Can't load proxied image: ${src}`, 1000, 50, 15);
56+
img.setAttribute("src", imageDataUrl);
57+
}
5158
} else {
52-
img.remove();
59+
const imageDataUrl = createImageWithText(`Not allowed image extension. It must be: ${allowedImageExtensions.concat()}`, 1000, 50, 15);
60+
img.setAttribute("src", imageDataUrl);
5361
}
5462
}
5563
}
@@ -95,3 +103,31 @@ function blobToDataURL (blob: Blob): Promise<string> {
95103
reader.readAsDataURL(blob);
96104
});
97105
}
106+
107+
function createImageWithText (text: string, width: number, height: number, font: number): string {
108+
// Create a canvas element
109+
const canvas = document.createElement("canvas");
110+
canvas.width = width;
111+
canvas.height = height;
112+
const context = canvas.getContext("2d");
113+
114+
if (context) {
115+
// Set background color (optional)
116+
context.fillStyle = "white"; // or "transparent" for a transparent background
117+
context.fillRect(0, 0, width, height);
118+
119+
// Set text properties
120+
context.fillStyle = "black";
121+
context.font = `${font}px Arial`; // Change font size and family as needed
122+
123+
// Align text
124+
context.textAlign = "center";
125+
context.textBaseline = "middle";
126+
127+
// Draw text
128+
context.fillText(text, width / 2, height / 2);
129+
}
130+
131+
// Convert canvas to data URL (base64 encoded string)
132+
return canvas.toDataURL("image/png");
133+
}

0 commit comments

Comments
 (0)