1
+ import { createCanvas , registerFont , CanvasRenderingContext2D } from "canvas" ;
1
2
import DOMPurify from "dompurify" ;
2
3
import { useRestApi } from "#imports" ;
3
4
@@ -23,6 +24,7 @@ async function remove_user_tracking (html: string) {
23
24
const htmlDoc = parser . parseFromString ( html , "text/html" ) ;
24
25
25
26
remove_all_external_links ( htmlDoc ) ;
27
+
26
28
await replace_images_with_proxied_images ( htmlDoc ) ;
27
29
28
30
return document_to_html ( htmlDoc ) ;
@@ -46,10 +48,16 @@ async function replace_images_with_proxied_images (htmlDoc: Document) {
46
48
47
49
if ( src ) {
48
50
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
+ }
51
58
} 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 ) ;
53
61
}
54
62
}
55
63
}
@@ -95,3 +103,31 @@ function blobToDataURL (blob: Blob): Promise<string> {
95
103
reader . readAsDataURL ( blob ) ;
96
104
} ) ;
97
105
}
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