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

attachmentDownload.ts

304 lines9.9 KB

1import type { ChatFileAttachment } from "@t3tools/contracts";
2import type { Directory } from "expo-file-system";
3import type { SharingOptions } from "expo-sharing";
4​
5import { beginForegroundHandoff } from "./foreground-handoff";
6import { uuidv4 } from "./uuid";
7​
8const ATTACHMENT_DOWNLOAD_DIRECTORY = "t3-attachment-downloads";
9const DOWNLOAD_RETENTION_MS = 24 * 60 * 60_000;
10const DOWNLOAD_DIRECTORY_NAME = /^(\d+)-[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;
11const activeDirectories = new Set<string>();
12​
13function downloadFileName(name: string): string {
14 const basename = name.split(/[\\/]/).at(-1) ?? "";
15 const sanitized = Array.from(basename, (character) => {
16 const codePoint = character.codePointAt(0)!;
17 return codePoint < 32 ||
18 (codePoint >= 127 && codePoint <= 159) ||
19 (codePoint >= 0xd800 && codePoint <= 0xdfff)
20 ? "_"
21 : character;
22 })
23 .join("")
24 .trim();
25 if (!sanitized || /^\.+$/.test(sanitized)) {
26 return "attachment";
27 }
28 const encoder = new TextEncoder();
29 if (encoder.encode(sanitized).byteLength <= 255) {
30 return sanitized;
31 }
32 const extensionMatch = /\.[a-z0-9]{1,16}$/i.exec(sanitized);
33 const extension = extensionMatch && extensionMatch.index > 0 ? extensionMatch[0] : "";
34 const stem = extension ? sanitized.slice(0, -extension.length) : sanitized;
35 let remainingBytes = 255 - encoder.encode(extension).byteLength;
36 let shortStem = "";
37 for (const character of stem) {
38 const bytes = encoder.encode(character).byteLength;
39 if (bytes > remainingBytes) break;
40 shortStem += character;
41 remainingBytes -= bytes;
42 }
43 return `${shortStem || "attachment"}${extension}`;
45​
46function removeDownloadDirectory(directory: Directory): void {
47 try {
48 if (directory.exists) {
49 directory.delete();
50 }
51 } catch (error) {
52 console.warn("[attachment-downloads] could not remove a cached file", error);
53 }
55​
56type AttachmentFileMetadata = Pick<ChatFileAttachment, "name" | "mimeType">;
57​
58export interface AttachmentPreviewFile {
59 readonly uri: string;
60 readonly share: (signal: AbortSignal, sourceIdentifier?: string) => Promise<void>;
61 readonly dispose: () => void;
63​
64async function availableSharing(signal: AbortSignal) {
65 if (signal.aborted) return null;
66 const Sharing = await import("expo-sharing");
67 const canShare = await Sharing.isAvailableAsync();
68 if (signal.aborted) return null;
69 if (!canShare) {
70 throw new Error("Saving and sharing files is unavailable on this device.");
71 }
72 return Sharing;
74​
75async function createCachedAttachmentFile(attachment: AttachmentFileMetadata) {
76 const { Directory, File, Paths } = await import("expo-file-system");
77 const cache = new Directory(Paths.cache, ATTACHMENT_DOWNLOAD_DIRECTORY);
78 cache.create({ idempotent: true, intermediates: true });
79 const now = Date.now();
80 try {
81 for (const entry of cache.list()) {
82 const match = DOWNLOAD_DIRECTORY_NAME.exec(entry.name);
83 if (
84 entry instanceof Directory &&
85 match &&
86 Number(match[1]) < now - DOWNLOAD_RETENTION_MS &&
87 !activeDirectories.has(entry.uri)
88 ) {
89 removeDownloadDirectory(entry);
90 }
91 }
92 } catch (error) {
93 console.warn("[attachment-downloads] could not inspect cached files", error);
94 }
95​
96 const directory = new Directory(cache, `${now}-${uuidv4()}`);
97 directory.create();
98 let file: InstanceType<typeof File>;
99 try {
100 file = new File(directory, downloadFileName(attachment.name));
101 } catch (error) {
102 removeDownloadDirectory(directory);
103 throw error;
104 }
105 activeDirectories.add(directory.uri);
106 let disposed = false;
107 let shared = false;
108 let sharing = false;
109 const release = () => {
110 if (!disposed || sharing) return;
111 activeDirectories.delete(directory.uri);
112 // A receiver can still be reading after Android's chooser returns.
113 if (!shared) removeDownloadDirectory(directory);
114 };
115 const preview: AttachmentPreviewFile = {
116 uri: file.uri,
117 dispose: () => {
118 disposed = true;
119 release();
120 },
121 share: async (signal, sourceIdentifier) => {
122 if (disposed || sharing || signal.aborted) return;
123 sharing = true;
124 try {
125 const Sharing = await availableSharing(signal);
126 if (Sharing === null || disposed) return;
127 const endHandoff = beginForegroundHandoff();
128 try {
129 const options: SharingOptions = {
130 mimeType: attachment.mimeType.split(";", 1)[0]?.trim() || "application/octet-stream",
131 dialogTitle: attachment.name,
132 };
133 if (sourceIdentifier) {
134 const { shareFileFromSource } = await import("./shareFileFromSource");
135 if (signal.aborted || disposed) return;
136 await shareFileFromSource(file.uri, options, sourceIdentifier);
137 } else {
138 await Sharing.shareAsync(file.uri, options);
139 }
140 shared = true;
141 } catch (cause) {
142 if (!signal.aborted) {
143 throw new Error("Could not open the share sheet. Try again.", { cause });
144 }
145 } finally {
146 endHandoff();
147 }
148 } finally {
149 sharing = false;
150 release();
151 }
152 },
153 };
154 return {
155 file,
156 preview,
157 retainAfterHandoff: () => {
158 shared = true;
159 },
160 };
162​
163export function nativeViewerErrorMessage(cause: unknown): string {
164 const text = cause instanceof Error ? cause.message : String(cause);
165 return /ActivityNotFound|cannot be previewed/i.test(text)
166 ? "No app on this device can show this format. Save or share it to open it elsewhere."
167 : "The file could not be opened. Check the connection and try again.";
169​
170export async function openAttachmentInViewer(input: {
171 readonly uri: string;
172 readonly attachment: AttachmentFileMetadata;
173 readonly signal: AbortSignal;
174}): Promise<void> {
175 const { File } = await import("expo-file-system");
176 const { requireNativeModule } = await import("expo");
177 if (input.signal.aborted) return;
178 const cached = await createCachedAttachmentFile(input.attachment);
179 try {
180 if (/^(file|content):/.test(input.uri)) {
181 await new File(input.uri).copy(cached.file);
182 } else {
183 await File.downloadFileAsync(input.uri, cached.file, { signal: input.signal });
184 }
185 if (input.signal.aborted) return;
186 const endHandoff = beginForegroundHandoff();
187 try {
188 await requireNativeModule<{ openFile(uri: string, mimeType: string): Promise<void> }>(
189 "T3NativeControls",
190 ).openFile(
191 cached.file.uri,
192 input.attachment.mimeType.split(";", 1)[0]?.trim() || "application/octet-stream",
193 );
194 cached.retainAfterHandoff();
195 } finally {
196 endHandoff();
197 }
198 } finally {
199 cached.preview.dispose();
200 }
202​
203/** The caller owns this cached file until disposal, unless it has been shared with another app. */
204export async function downloadAttachmentForPreview(input: {
205 readonly url: string;
206 readonly attachment: AttachmentFileMetadata;
207 readonly signal: AbortSignal;
208}): Promise<AttachmentPreviewFile | null> {
209 if (input.signal.aborted) return null;
210 const { File } = await import("expo-file-system");
211 const cached = await createCachedAttachmentFile(input.attachment);
212 try {
213 if (input.signal.aborted) {
214 cached.preview.dispose();
215 return null;
216 }
217 await File.downloadFileAsync(input.url, cached.file, { signal: input.signal });
218 if (input.signal.aborted) {
219 cached.preview.dispose();
220 return null;
221 }
222 return cached.preview;
223 } catch (cause) {
224 // Android may leave a partial file after a failed or interrupted request.
225 cached.preview.dispose();
226 if (input.signal.aborted) return null;
227 throw new Error("Could not download the attachment. Check the connection and try again.", {
228 cause,
229 });
230 }
232​
233export async function downloadAndShareAttachment(input: {
234 readonly url: string;
235 readonly attachment: AttachmentFileMetadata;
236 readonly signal: AbortSignal;
237 readonly sourceIdentifier?: string;
238}): Promise<void> {
239 if ((await availableSharing(input.signal)) === null) return;
240 const file = await downloadAttachmentForPreview(input);
241 if (file === null) return;
242 try {
243 await file.share(input.signal, input.sourceIdentifier);
244 } finally {
245 file.dispose();
246 }
248​
249export async function shareLocalAttachment(input: {
250 readonly uri: string;
251 readonly attachment: AttachmentFileMetadata;
252 readonly signal: AbortSignal;
253 readonly sourceIdentifier?: string;
254}): Promise<void> {
255 if ((await availableSharing(input.signal)) === null) return;
256 const { File } = await import("expo-file-system");
257 const cached = await createCachedAttachmentFile(input.attachment);
258 try {
259 if (input.signal.aborted) return;
260 try {
261 await new File(input.uri).copy(cached.file);
262 } catch (cause) {
263 if (input.signal.aborted) return;
264 throw new Error("Could not prepare the attachment for sharing.", { cause });
265 }
266 if (!input.signal.aborted) {
267 await cached.preview.share(input.signal, input.sourceIdentifier);
268 }
269 } finally {
270 cached.preview.dispose();
271 }
273​
274export async function writeGeneratedAttachmentFile(input: {
275 readonly bytes: Uint8Array;
276 readonly attachment: AttachmentFileMetadata;
277}): Promise<AttachmentPreviewFile> {
278 const cached = await createCachedAttachmentFile(input.attachment);
279 try {
280 await cached.file.write(input.bytes);
281 return cached.preview;
282 } catch (error) {
283 cached.preview.dispose();
284 throw error;
285 }
287​
288export async function shareGeneratedAttachment(input: {
289 readonly bytes: Uint8Array;
290 readonly attachment: AttachmentFileMetadata;
291 readonly signal: AbortSignal;
292}): Promise<boolean> {
293 const sharing = await availableSharing(input.signal).catch(() => null);
294 if (sharing === null) return false;
295 const cached = await createCachedAttachmentFile(input.attachment);
296 try {
297 if (input.signal.aborted) return false;
298 cached.file.write(input.bytes);
299 await cached.preview.share(input.signal);
300 return true;
301 } finally {
302 cached.preview.dispose();
303 }