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

mediaContent.ts

137 lines4.8 KB

1import { msg } from "gt-react";
2​
3import { m } from "~/i18n/messages";
4​
5/** Resolves web references without inheriting the desktop renderer's custom app scheme. */
6export function resolveProtocolRelativeMediaUrl(src: string): string {
7 if (!src.startsWith("//")) return src;
8 const protocol =
9 typeof window !== "undefined" && window.location.protocol === "http:" ? "http:" : "https:";
10 return `${protocol}${src}`;
12​
13// Data URL escapes are raw bytes, not UTF-8, so `%89` must stay one byte.
14function decodePercentBytes(payload: string) {
15 const encoder = new TextEncoder();
16 return Uint8Array.from(
17 payload
18 .split(/(%[0-9a-f]{2})/i)
19 .flatMap((part) =>
20 /^%[0-9a-f]{2}$/i.test(part)
21 ? [Number.parseInt(part.slice(1), 16)]
22 : [...encoder.encode(part)],
23 ),
24 );
26​
27/** Decodes inline media locally; desktop connect-src omits `data:`, so fetch() cannot read it. */
28function readDataUrlBlob(src: string): Blob {
29 // A fragment is never part of the payload; a literal `#` in data must be escaped as `%23`.
30 const url = src.split("#", 1)[0] ?? src;
31 const comma = url.indexOf(",");
32 const header = url.slice("data:".length, comma);
33 const mimeType = (header.split(";", 1)[0] ?? "").trim();
34 const payload = url.slice(comma + 1);
35 try {
36 if (comma < 0) throw new Error(m(msg("Missing data URL payload.")));
37 const isBase64 = /;\s*base64\s*$/i.test(header);
38 // Base64 text is ASCII, so any escape that is not valid UTF-8 is malformed anyway.
39 const bytes = isBase64
40 ? Uint8Array.from(atob(decodeURIComponent(payload)), (char) => char.charCodeAt(0))
41 : decodePercentBytes(payload);
42 return new Blob([bytes], { type: mimeType || "text/plain" });
43 } catch (cause) {
44 throw new Error(m(msg("This inline media could not be decoded.")), { cause });
45 }
47​
48async function fetchMediaBlob(src: string): Promise<Blob> {
49 const response = await fetch(src).catch(() => null);
50 if (response?.ok) return response.blob();
51 // An <img> can show media that fetch() may not read (CORS, CSP, cookies); desktop reads it natively.
52 const desktop = typeof window === "undefined" ? undefined : window.desktopBridge;
53 const native =
54 desktop && /^https?:/i.test(src) ? await desktop.readMedia(src).catch(() => null) : null;
55 if (native && native.status >= 200 && native.status < 300) {
56 return new Blob([new Uint8Array(native.data)], { type: native.mimeType });
57 }
58 const status = native?.status ?? response?.status;
59 if (status !== undefined)
60 throw new Error(m(msg`The file could not be fetched (HTTP ${{ status }}).`));
61 throw new Error(
62 desktop
63 ? m(msg("The file could not be fetched. Check the connection and try again."))
64 : m(
65 msg(
66 "The file could not be fetched. The host may block browser access (CORS), or the connection may be unavailable.",
67 ),
68 ),
69 );
71​
72async function readMediaBlob(src: string): Promise<Blob> {
73 if (/^data:/i.test(src)) return readDataUrlBlob(src);
74 const blob = await fetchMediaBlob(src);
75 if (blob.type.split(";", 1)[0] === "text/html") {
76 throw new Error(
77 m(msg("This link returned a web page instead of media. Open the original URL.")),
78 );
79 }
80 return blob;
82​
83export async function downloadMedia(src: string, name: string): Promise<void> {
84 const url = URL.createObjectURL(await readMediaBlob(src));
85 try {
86 const anchor = document.createElement("a");
87 anchor.href = url;
88 anchor.download = name;
89 anchor.click();
90 } finally {
91 setTimeout(() => URL.revokeObjectURL(url), 30_000);
92 }
94​
95export async function readMediaPng(src: string): Promise<Blob> {
96 const blob = await readMediaBlob(src);
97 if (blob.type.split(";", 1)[0] === "image/png") return blob;
98​
99 const url = URL.createObjectURL(blob);
100 const image = new Image();
101 image.src = url;
102 try {
103 try {
104 await image.decode();
105 } catch (cause) {
106 throw new Error(
107 m(msg("The browser could not decode this image for copying. Try saving it instead.")),
108 {
109 cause,
110 },
111 );
112 }
113 const { naturalWidth: width, naturalHeight: height } = image;
114 if (width <= 0 || height <= 0 || width * height > 64_000_000) {
115 throw new Error(
116 m(msg("This image is too large or has no usable dimensions. Try saving it instead.")),
117 );
118 }
119 const canvas = document.createElement("canvas");
120 canvas.width = width;
121 canvas.height = height;
122 const context = canvas.getContext("2d");
123 if (!context) throw new Error(m(msg("Image copying is unavailable in this browser.")));
124 context.drawImage(image, 0, 0);
125 return await new Promise<Blob>((resolve, reject) => {
126 canvas.toBlob(
127 (png) =>
128 png
129 ? resolve(png)
130 : reject(new Error(m(msg("The image could not be converted to PNG.")))),
131 "image/png",
132 );
133 });
134 } finally {
135 URL.revokeObjectURL(url);
136 }