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

attachmentDocument.ts

203 lines8.6 KB

1import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
2import type { EnvironmentId } from "@t3tools/contracts";
3import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
4import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview";
5import { fetch } from "expo/fetch";
6import { File } from "expo-file-system";
7import { useEffect, useMemo, useRef, useState } from "react";
8import { Alert } from "react-native";
9​
10import type { FileBackedComposerAttachment } from "./composerImages";
11import { loadLocalAttachmentPreview } from "./localAttachmentPreview";
12import { downloadAndShareAttachment, shareLocalAttachment } from "./attachmentDownload";
13import { useRefreshAssetUrl } from "../state/assets";
14​
15const isLocalUri = (uri: string) => /^(file|content):/.test(uri);
16​
17/** Signed asset URLs live for an hour; treat anything older than this as worth re-minting. */
18const STALE_URL_MS = 5 * 60_000;
19​
20/**
21 * Loads a captured attachment for viewing: a fresh signed URL for a sent or uploaded file,
22 * a leased local file for a draft. Text kinds read a bounded prefix; documents hand their
23 * URL to a native or web renderer. Captured bytes never resolve against the workspace.
24 */
25export function useAttachmentDocument(input: {
26 readonly name: string;
27 readonly mimeType: string;
28 readonly sizeBytes: number;
29 readonly attachmentId: string;
30 readonly environmentId: EnvironmentId | null;
31 readonly attachment: FileBackedComposerAttachment | null;
32}) {
33 const kind = filePreviewKind(input);
34 const delimiter = filePreviewDelimiter(input);
35 const renderedMode =
36 kind === "markdown" ? "markdown" : kind === "html" ? "html" : delimiter ? "table" : null;
37 const shareController = useRef<AbortController | null>(null);
38 useEffect(() => () => shareController.current?.abort(), []);
39 const resource = useMemo(
40 () => ({
41 _tag: "attachment" as const,
42 attachmentId: input.attachmentId,
43 fileName: input.name,
44 mimeType: input.mimeType,
45 disposition: "inline" as const,
46 }),
47 [input.attachmentId, input.name, input.mimeType],
48 );
49 const environmentId = input.attachment ? null : input.environmentId;
50 const refresh = useRefreshAssetUrl(environmentId, resource);
51 const [localUri, setLocalUri] = useState<string | null>(null);
52 const [remoteUri, setRemoteUri] = useState<string | null>(null);
53 const [content, setContent] = useState<{ text: string; truncated: boolean } | null>(null);
54 const table = useMemo(
55 () => (content && delimiter ? parseDelimitedPreview(content.text, delimiter) : null),
56 [content, delimiter],
57 );
58 const [error, setError] = useState<string | null>(null);
59 // Reading source is a separate failure from loading the file: a rendered HTML page can be
60 // fine while its bytes are not UTF-8, and switching back to the page must not stay stuck.
61 const [contentError, setContentError] = useState<string | null>(null);
62 const textReadUrl = useRef<{ uri: string; authorizedAt: number } | null>(null);
63 const [rendered, setRendered] = useState(true);
64 const [revision, setRevision] = useState(0);
65 const [sharing, setSharing] = useState(false);
66 const uri = input.attachment ? localUri : remoteUri;
67 const attachment = input.attachment;
68 useEffect(() => {
69 if (attachment) return;
70 let cancelled = false;
71 // Await a fresh signed URL: cached links can expire while the client is suspended.
72 // oxlint-disable-next-line react/set-state-in-effect -- A new preview request clears its previous URL and error.
73 setRemoteUri(null);
74 setError(null);
75 textReadUrl.current = null;
76 void refresh()
77 .then((url) => {
78 if (cancelled) return;
79 if (!url) throw new Error("Reconnect to this environment and try again.");
80 textReadUrl.current = { uri: url, authorizedAt: Date.now() };
81 setRemoteUri(url);
82 })
83 .catch((cause: unknown) => {
84 if (!cancelled)
85 setError(cause instanceof Error ? cause.message : "The attachment is unavailable.");
86 });
87 return () => {
88 cancelled = true;
89 };
90 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reauthorize the remote file.
91 }, [attachment, refresh, revision]);
92 useEffect(() => {
93 if (!attachment) return;
94 // A new attachment must not keep the previous file behind it: `share()` would otherwise
95 // send the old bytes under the new name if this load fails.
96 // oxlint-disable-next-line react/set-state-in-effect -- A new attachment invalidates the last one.
97 setLocalUri(null);
98 setContent(null);
99 setContentError(null);
100 const controller = new AbortController();
101 let release: (() => void) | undefined;
102 void loadLocalAttachmentPreview(attachment, controller.signal)
103 .then((file) => {
104 if (!file) return;
105 if (controller.signal.aborted) return file.dispose();
106 release = file.dispose;
107 setLocalUri(file.uri);
108 setError(null);
109 })
110 .catch((cause: unknown) => {
111 if (!controller.signal.aborted)
112 setError(cause instanceof Error ? cause.message : "The local file is unavailable.");
113 });
114 return () => {
115 controller.abort();
116 release?.();
117 };
118 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reacquire a local file lease after a failed load.
119 }, [attachment, revision]);
120 const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered);
121 const sizeBytes = input.sizeBytes;
122 useEffect(() => {
123 if (!uri || !needsText) return;
124 const controller = new AbortController();
125 // oxlint-disable-next-line react/set-state-in-effect -- A new external resource must clear the previous response before loading.
126 setContent(null);
127 setContentError(null);
128 const response = isLocalUri(uri)
129 ? Promise.resolve().then(() => ({ ok: true, body: new File(uri).readableStream() }))
130 : (async () => {
131 // A signed URL minted when the file opened may have expired by the time the user
132 // switches to source; reauthorize before fetching instead of reading a stale link.
133 const authorized = textReadUrl.current;
134 let target = authorized?.uri ?? uri;
135 if (!authorized || Date.now() - authorized.authorizedAt > STALE_URL_MS) {
136 const refreshed = await refresh();
137 if (!refreshed) throw new Error("Reconnect to this environment and try again.");
138 target = refreshed;
139 if (!controller.signal.aborted) {
140 // Keep the source-read URL and its age together without restarting active media.
141 textReadUrl.current = { uri: refreshed, authorizedAt: Date.now() };
142 }
143 }
144 return fetch(target, {
145 signal: controller.signal,
146 headers: {
147 ...(sizeBytes > 0 ? { Range: `bytes=0-${FILE_TEXT_PREVIEW_MAX_BYTES}` } : {}),
148 ...(revision > 0 ? { "Cache-Control": "no-cache" } : {}),
149 },
150 });
151 })();
152 void response
153 .then((value) => readFilePreviewResponse(value, controller.signal))
154 .then((value) => {
155 if (!controller.signal.aborted) setContent(value);
156 })
157 .catch((cause: unknown) => {
158 if (!controller.signal.aborted)
159 setContentError(cause instanceof Error ? cause.message : "Could not read this file.");
160 });
161 return () => controller.abort();
162 }, [uri, needsText, revision, sizeBytes, refresh]);
163 const share = async () => {
164 if (!uri || sharing) return;
165 setSharing(true);
166 const controller = new AbortController();
167 shareController.current = controller;
168 const request = {
169 attachment: { name: input.name, mimeType: input.mimeType },
170 signal: controller.signal,
171 };
172 try {
173 if (isLocalUri(uri)) await shareLocalAttachment({ ...request, uri });
174 else await downloadAndShareAttachment({ ...request, url: (await refresh()) ?? uri });
175 } catch (cause) {
176 if (controller.signal.aborted) return;
177 Alert.alert(
178 "Could not share file",
179 cause instanceof Error ? cause.message : "Please try again.",
180 );
181 } finally {
182 if (shareController.current === controller) shareController.current = null;
183 if (!controller.signal.aborted) setSharing(false);
184 }
185 };
186 return {
187 kind,
188 renderedMode,
189 uri,
190 /** Native viewers resolve their own fresh URL from this instead of reusing `uri`. */
191 resource,
192 content,
193 table,
194 error: error ?? (needsText ? contentError : null),
195 needsText,
196 rendered,
197 setRendered,
198 revision,
199 retry: () => setRevision((value) => value + 1),
200 share,
201 sharing,
202 };