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

attachmentDocument.ts

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