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

attachmentDocument.ts

208 lines8.1 KB

1import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
2import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3import { Atom, AsyncResult } from "effect/reactivity";
4import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5import * as Dialog from "../components/ui/Dialog";
6import { msg, useMessages } from "gt-react-native";
7import { m } from "../i18n/messages";
8import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
9import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
10import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
11import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview";
12import { fetch } from "expo/fetch";
13import { File } from "expo-file-system";
14import * as Effect from "effect/Effect";
15import * as Option from "effect/Option";
16import * as Schema from "effect/Schema";
17import { useEffect, useRef, useState } from "react";
18​
19import type { FileBackedComposerAttachment } from "./composerImages";
20import { localAttachmentPreviewAtom, localAttachmentPreviewState } from "./localAttachmentPreview";
21import { downloadAndShareAttachment, shareLocalAttachment } from "./attachmentDownload";
22import { refreshAssetUrl, useFreshAssetUrl, useRefreshAssetUrl } from "../state/assets";
23import { attachmentDocumentPresentation } from "./attachmentDocumentPresentation";
24​
25const isLocalUri = (uri: string) => /^(file|content):/.test(uri);
26​
27/** Signed asset URLs live for an hour; treat anything older than this as worth re-minting. */
28const STALE_URL_MS = 5 * 60_000;
29​
30interface AttachmentTextKey {
31 readonly uri: string;
32 /** When a remote `uri` was signed; null for local files. */
33 readonly authorizedAt: number | null;
34 readonly environmentId: EnvironmentId | null;
35 readonly resource: AssetResource;
36 readonly sizeBytes: number;
37 readonly revision: number;
39​
40async function readAttachmentText(key: AttachmentTextKey, signal: AbortSignal) {
41 if (isLocalUri(key.uri)) {
42 return readFilePreviewResponse({ ok: true, body: new File(key.uri).readableStream() }, signal);
43 }
44 // Reauthorize before source reads; the opening URL may have expired.
45 let target = key.uri;
46 if (key.authorizedAt === null || Date.now() - key.authorizedAt > STALE_URL_MS) {
47 const refreshed =
48 key.environmentId === null
49 ? null
50 : await refreshAssetUrl(key.environmentId, key.resource, signal).catch(() => null);
51 if (!refreshed) throw new Error(m(msg("Reconnect to this environment and try again.")));
52 target = refreshed;
53 }
54 const response = await fetch(target, {
55 signal,
56 headers: {
57 ...(key.sizeBytes > 0 ? { Range: `bytes=0-${FILE_TEXT_PREVIEW_MAX_BYTES}` } : {}),
58 ...(key.revision > 0 ? { "Cache-Control": "no-cache" } : {}),
59 },
60 });
61 return readFilePreviewResponse(response, signal);
63​
64class AttachmentTextReadError extends Schema.TaggedError<AttachmentTextReadError>()(
65 "AttachmentTextReadError",
66 {
67 message: Schema.String,
68 cause: Schema.Defect(),
69 },
70) {}
71​
72// Plain-object keys compare structurally (Effect `Equal`/`Hash`). Unmounting the
73// last reader interrupts the read, which aborts the fetch.
74export const attachmentTextAtom = Atom.family((key: AttachmentTextKey) =>
75 Atom.make(
76 Effect.tryPromise({
77 try: (signal) => readAttachmentText(key, signal),
78 catch: (cause) =>
79 new AttachmentTextReadError({
80 message: errorDisplayMessage(cause, m) ?? m(msg("Could not read this file.")),
81 cause,
82 }),
83 }),
84 ).pipe(Atom.withLabel("attachment-text")),
85);
86​
87export const noAttachmentText = Atom.make(
88 AsyncResult.initial<{ text: string; truncated: boolean }, AttachmentTextReadError>(),
89).pipe(Atom.withLabel("attachment-text:none"));
90​
91/** Captured bytes never resolve against the workspace. */
92export function useAttachmentDocument(input: {
93 readonly name: string;
94 readonly mimeType: string;
95 readonly sizeBytes: number;
96 readonly attachmentId: string;
97 readonly environmentId: EnvironmentId | null;
98 readonly attachment: FileBackedComposerAttachment | null;
99}) {
100 const resolve = useMessages();
101 const richKind = filePreviewKind(input);
102 const kind =
103 richKind === "epub" && !input.attachment && input.environmentId
104 ? "epub"
105 : filePreviewKind(input, { richDocuments: false });
106 const delimiter = filePreviewDelimiter(input);
107 const shareController = useRef<AbortController | null>(null);
108 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- aborts the in-flight attachment share download when the component unmounts
109 useEffect(() => () => shareController.current?.abort(), []);
110 const resource = {
111 _tag: "attachment" as const,
112 attachmentId: input.attachmentId,
113 fileName: input.name,
114 mimeType: input.mimeType,
115 disposition: "inline" as const,
116 };
117 const environmentId = input.attachment ? null : input.environmentId;
118 const refresh = useRefreshAssetUrl(environmentId, resource);
119 const [rendered, setRendered] = useState(true);
120 const [revision, setRevision] = useState(0);
121 const [sharing, setSharing] = useState(false);
122 const attachment = input.attachment;
123 const localPreviewAtom = localAttachmentPreviewAtom(attachment);
124 const localPreview = localAttachmentPreviewState(useAtomValue(localPreviewAtom));
125 const refreshLocalPreview = useAtomRefresh(localPreviewAtom);
126 const remote = useFreshAssetUrl(environmentId, attachment ? null : resource, revision);
127 const remoteUrl = AsyncResult.isSuccess(remote) && !remote.waiting ? remote.value : null;
128 const uri = attachment ? localPreview.uri : (remoteUrl?.url ?? null);
129 const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered);
130 const text = useAtomValue(
131 uri && needsText
132 ? attachmentTextAtom({
133 uri,
134 authorizedAt: remoteUrl?.authorizedAt ?? null,
135 environmentId,
136 resource,
137 sizeBytes: input.sizeBytes,
138 revision,
139 })
140 : noAttachmentText,
141 );
142 const content = AsyncResult.isSuccess(text) ? text.value : null;
143 const contentError = AsyncResult.isFailure(text)
144 ? (Option.getOrNull(AsyncResult.error(text))?.message ??
145 resolve(msg("Could not read this file.")))
146 : null;
147 const table =
148 content && delimiter
149 ? parseDelimitedPreview(content.text, delimiter, { inputComplete: !content.truncated })
150 : null;
151 const presentation = attachmentDocumentPresentation({
152 kind,
153 hasTable: table !== null,
154 hasEnvironment: input.environmentId !== null,
155 rendered,
156 });
157 const error = attachment
158 ? localPreview.error &&
159 (localPreview.error.message || resolve(msg("The local file is unavailable.")))
160 : AsyncResult.isFailure(remote)
161 ? (Option.getOrNull(AsyncResult.error(remote))?.message ??
162 resolve(msg("The attachment is unavailable.")))
163 : null;
164 const share = async () => {
165 if (!uri || sharing) return;
166 setSharing(true);
167 const controller = new AbortController();
168 shareController.current = controller;
169 const request = {
170 attachment: { name: input.name, mimeType: input.mimeType },
171 signal: controller.signal,
172 };
173 const result = await settlePromise(async () => {
174 if (isLocalUri(uri)) await shareLocalAttachment({ ...request, uri });
175 else await downloadAndShareAttachment({ ...request, url: (await refresh()) ?? uri });
176 });
177 if (shareController.current === controller) shareController.current = null;
178 if (controller.signal.aborted) return;
179 setSharing(false);
180 if (AsyncResult.isFailure(result)) {
181 const cause = squashAtomCommandFailure(result);
182 Dialog.alert(
183 m(msg("Could not share file")),
184 errorDisplayMessage(cause, m) ?? m(msg("Please try again.")),
185 );
186 }
187 };
188 return {
189 kind,
190 ...presentation,
191 uri,
192 /** Native viewers resolve their own fresh URL from this instead of reusing `uri`. */
193 resource,
194 content,
195 table,
196 error: error ?? contentError,
197 needsText,
198 rendered,
199 setRendered,
200 revision,
201 retry: () => {
202 setRevision((value) => value + 1);
203 if (attachment) refreshLocalPreview();
204 },
205 share,
206 sharing,
207 };