Open History to see the last commit
1import { videoMimeType } from "@t3tools/shared/video";
2
3import type { FileBackedComposerAttachment } from "./composerImages";
4import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";
5import { shareLocalAttachment, type AttachmentPreviewFile } from "./attachmentDownload";
6import { retainComposerAttachmentFileForPreview } from "./composerAttachmentPreviewRetention";
7
8export async function loadLocalAttachmentPreview(
9 attachment: FileBackedComposerAttachment,
10 signal: AbortSignal,
11): Promise<AttachmentPreviewFile | null> {
12 if (signal.aborted) return null;
13 const release = retainComposerAttachmentFileForPreview(attachment);
14 try {
15 const { File, Paths } = await import("expo-file-system");
16 if (signal.aborted) {
17 release();
18 return null;
19 }
20 const uri =
21 resolveOwnedComposerAttachmentFileUri(attachment.fileUri, Paths.document.uri) ??
22 attachment.fileUri;
23 const file = new File(uri);
24 if (!file.exists) {
25 throw new Error("The local attachment file is missing.");
26 }
27 let disposed = false;
28 return {
29 uri: file.uri,
30 dispose: () => {
31 if (disposed) return;
32 disposed = true;
33 release();
34 },
35 share: async (shareSignal, sourceIdentifier) => {
36 if (disposed || shareSignal.aborted) return;
37 const releaseShare = retainComposerAttachmentFileForPreview(attachment);
38 try {
39 await shareLocalAttachment({
40 uri: file.uri,
41 attachment: {
42 name: attachment.name,
43 mimeType:
44 attachment.type === "file"
45 ? (videoMimeType(attachment) ?? attachment.mimeType)
46 : attachment.mimeType,
47 },
48 signal: shareSignal,
49 sourceIdentifier,
50 });
51 } finally {
52 releaseShare();
53 }
54 },
55 };
56 } catch (cause) {
57 release();
58 if (signal.aborted) return null;
59 throw new Error("This attachment is no longer available. Attach the file again.", { cause });
60 }
61}