Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

mediaContent.ts

114 lines4.0 KB

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​
9// Data URL escapes are raw bytes, not UTF-8, so `%89` must stay one byte.
10function decodePercentBytes(payload: string) {
11 const encoder = new TextEncoder();
12 return Uint8Array.from(
13 payload
14 .split(/(%[0-9a-f]{2})/i)
15 .flatMap((part) =>
16 /^%[0-9a-f]{2}$/i.test(part)
17 ? [Number.parseInt(part.slice(1), 16)]
18 : [...encoder.encode(part)],
19 ),
20 );
22​
23/** Decodes inline media locally; desktop connect-src omits `data:`, so fetch() cannot read it. */
24function readDataUrlBlob(src: string): Blob {
25 // A fragment is never part of the payload; a literal `#` in data must be escaped as `%23`.
26 const url = src.split("#", 1)[0] ?? src;
27 const comma = url.indexOf(",");
28 const [mimeType = "", ...parameters] = url.slice("data:".length, comma).split(";");
29 const payload = url.slice(comma + 1);
30 try {
31 if (comma < 0) throw new Error("Missing data URL payload.");
32 const isBase64 = parameters.some((parameter) => parameter.trim().toLowerCase() === "base64");
33 // Base64 text is ASCII, so any escape that is not valid UTF-8 is malformed anyway.
34 const bytes = isBase64
35 ? Uint8Array.from(atob(decodeURIComponent(payload)), (char) => char.charCodeAt(0))
36 : decodePercentBytes(payload);
37 return new Blob([bytes], { type: mimeType || "text/plain" });
38 } catch (cause) {
39 throw new Error("This inline media could not be decoded.", { cause });
40 }
42​
43async function readMediaBlob(src: string): Promise<Blob> {
44 if (/^data:/i.test(src)) return readDataUrlBlob(src);
45 let response: Response;
46 try {
47 response = await fetch(src);
48 } catch (cause) {
49 throw new Error(
50 "The file could not be fetched. The host may block browser access (CORS), or the connection may be unavailable.",
51 { cause },
52 );
53 }
54 if (!response.ok) throw new Error(`The file could not be fetched (HTTP ${response.status}).`);
55 const blob = await response.blob();
56 if (blob.type.split(";", 1)[0] === "text/html") {
57 throw new Error("This link returned a web page instead of media. Open the original URL.");
58 }
59 return blob;
61​
62export async function downloadMedia(src: string, name: string): Promise<void> {
63 const url = URL.createObjectURL(await readMediaBlob(src));
64 try {
65 const anchor = document.createElement("a");
66 anchor.href = url;
67 anchor.download = name;
68 anchor.click();
69 } finally {
70 setTimeout(() => URL.revokeObjectURL(url), 30_000);
71 }
73​
74export async function readMediaPng(src: string): Promise<Blob> {
75 const blob = await readMediaBlob(src);
76 if (blob.type.split(";", 1)[0] === "image/png") return blob;
77​
78 const url = URL.createObjectURL(blob);
79 const image = new Image();
80 image.src = url;
81 try {
82 try {
83 await image.decode();
84 } catch (cause) {
85 throw new Error(
86 "The browser could not decode this image for copying. Try saving it instead.",
87 {
88 cause,
89 },
90 );
91 }
92 const { naturalWidth: width, naturalHeight: height } = image;
93 if (width <= 0 || height <= 0 || width * height > 64_000_000) {
94 throw new Error(
95 "This image is too large or has no usable dimensions. Try saving it instead.",
96 );
97 }
98 const canvas = document.createElement("canvas");
99 canvas.width = width;
100 canvas.height = height;
101 const context = canvas.getContext("2d");
102 if (!context) throw new Error("Image copying is unavailable in this browser.");
103 context.drawImage(image, 0, 0);
104 return await new Promise<Blob>((resolve, reject) => {
105 canvas.toBlob(
106 (png) =>
107 png ? resolve(png) : reject(new Error("The image could not be converted to PNG.")),
108 "image/png",
109 );
110 });
111 } finally {
112 URL.revokeObjectURL(url);
113 }