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

attachmentDocument.ts

201 lines8.4 KB

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