Open History to see the last commit
1/** Resolves web references without inheriting the desktop renderer's custom app scheme. */
2export function resolveProtocolRelativeMediaUrl(src: string): string {
3 if (!src.startsWith("//")) return src;
4 const protocol =
5 typeof window !== "undefined" && window.location.protocol === "http:" ? "http:" : "https:";
6 return `${protocol}${src}`;
7}
8
9async function readMediaBlob(src: string): Promise<Blob> {
10 let response: Response;
11 try {
12 response = await fetch(src);
13 } catch (cause) {
14 throw new Error(
15 "The file could not be fetched. The host may block browser access (CORS), or the connection may be unavailable.",
16 { cause },
17 );
18 }
19 if (!response.ok) throw new Error(`The file could not be fetched (HTTP ${response.status}).`);
20 const blob = await response.blob();
21 if (blob.type.split(";", 1)[0] === "text/html") {
22 throw new Error("This link returned a web page instead of media. Open the original URL.");
23 }
24 return blob;
25}
26
27export async function downloadMedia(src: string, name: string): Promise<void> {
28 const url = URL.createObjectURL(await readMediaBlob(src));
29 try {
30 const anchor = document.createElement("a");
31 anchor.href = url;
32 anchor.download = name;
33 anchor.click();
34 } finally {
35 setTimeout(() => URL.revokeObjectURL(url), 30_000);
36 }
37}
38
39export async function readMediaPng(src: string): Promise<Blob> {
40 const blob = await readMediaBlob(src);
41 if (blob.type.split(";", 1)[0] === "image/png") return blob;
42
43 const url = URL.createObjectURL(blob);
44 const image = new Image();
45 image.src = url;
46 try {
47 try {
48 await image.decode();
49 } catch (cause) {
50 throw new Error(
51 "The browser could not decode this image for copying. Try saving it instead.",
52 {
53 cause,
54 },
55 );
56 }
57 const { naturalWidth: width, naturalHeight: height } = image;
58 if (width <= 0 || height <= 0 || width * height > 64_000_000) {
59 throw new Error(
60 "This image is too large or has no usable dimensions. Try saving it instead.",
61 );
62 }
63 const canvas = document.createElement("canvas");
64 canvas.width = width;
65 canvas.height = height;
66 const context = canvas.getContext("2d");
67 if (!context) throw new Error("Image copying is unavailable in this browser.");
68 context.drawImage(image, 0, 0);
69 return await new Promise<Blob>((resolve, reject) => {
70 canvas.toBlob(
71 (png) =>
72 png ? resolve(png) : reject(new Error("The image could not be converted to PNG.")),
73 "image/png",
74 );
75 });
76 } finally {
77 URL.revokeObjectURL(url);
78 }
79}