@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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