Open History to see the last commit
1import type { ChatFileAttachment } from "@t3tools/contracts";
2import type { Directory } from "expo-file-system";
3
4import { beginForegroundHandoff } from "./foreground-handoff";
5import { uuidv4 } from "./uuid";
6
7const ATTACHMENT_DOWNLOAD_DIRECTORY = "t3-attachment-downloads";
8const DOWNLOAD_RETENTION_MS = 24 * 60 * 60_000;
9const DOWNLOAD_DIRECTORY_NAME = /^(\d+)-[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;
10const activeDirectories = new Set<string>();
11
12function downloadFileName(name: string): string {
13 const basename = name.split(/[\\/]/).at(-1) ?? "";
14 const sanitized = Array.from(basename, (character) => {
15 const codePoint = character.codePointAt(0)!;
16 return codePoint < 32 ||
17 (codePoint >= 127 && codePoint <= 159) ||
18 (codePoint >= 0xd800 && codePoint <= 0xdfff)
19 ? "_"
20 : character;
21 })
22 .join("")
23 .trim();
24 if (!sanitized || /^\.+$/.test(sanitized)) {
25 return "attachment";
26 }
27 const encoder = new TextEncoder();
28 if (encoder.encode(sanitized).byteLength <= 255) {
29 return sanitized;
30 }
31 const extensionMatch = /\.[a-z0-9]{1,16}$/i.exec(sanitized);
32 const extension = extensionMatch && extensionMatch.index > 0 ? extensionMatch[0] : "";
33 const stem = extension ? sanitized.slice(0, -extension.length) : sanitized;
34 let remainingBytes = 255 - encoder.encode(extension).byteLength;
35 let shortStem = "";
36 for (const character of stem) {
37 const bytes = encoder.encode(character).byteLength;
38 if (bytes > remainingBytes) break;
39 shortStem += character;
40 remainingBytes -= bytes;
41 }
42 return `${shortStem || "attachment"}${extension}`;
43}
44
45function removeDownloadDirectory(directory: Directory): void {
46 try {
47 if (directory.exists) {
48 directory.delete();
49 }
50 } catch (error) {
51 console.warn("[attachment-downloads] could not remove a cached file", error);
52 }
53}
54
55/** Downloads original bytes for the native save/share sheet, including inline video responses. */
56export async function downloadAndShareAttachment(input: {
57 readonly url: string;
58 readonly attachment: Pick<ChatFileAttachment, "name" | "mimeType">;
59 readonly signal: AbortSignal;
60}): Promise<void> {
61 const [{ Directory, File, Paths }, Sharing] = await Promise.all([
62 import("expo-file-system"),
63 import("expo-sharing"),
64 ]);
65 if (input.signal.aborted) return;
66 const canShare = await Sharing.isAvailableAsync();
67 if (input.signal.aborted) return;
68 if (!canShare) {
69 throw new Error("Saving and sharing files is unavailable on this device.");
70 }
71
72 const cache = new Directory(Paths.cache, ATTACHMENT_DOWNLOAD_DIRECTORY);
73 cache.create({ idempotent: true, intermediates: true });
74 const now = Date.now();
75 try {
76 for (const entry of cache.list()) {
77 const match = DOWNLOAD_DIRECTORY_NAME.exec(entry.name);
78 if (
79 entry instanceof Directory &&
80 match &&
81 Number(match[1]) < now - DOWNLOAD_RETENTION_MS &&
82 !activeDirectories.has(entry.uri)
83 ) {
84 removeDownloadDirectory(entry);
85 }
86 }
87 } catch (error) {
88 console.warn("[attachment-downloads] could not inspect cached files", error);
89 }
90
91 const directory = new Directory(cache, `${now}-${uuidv4()}`);
92 activeDirectories.add(directory.uri);
93 let shared = false;
94 let openingShareSheet = false;
95 try {
96 directory.create();
97 const destination = new File(directory, downloadFileName(input.attachment.name));
98 const file = await File.downloadFileAsync(input.url, destination, { signal: input.signal });
99 if (input.signal.aborted) return;
100
101 openingShareSheet = true;
102 const endHandoff = beginForegroundHandoff();
103 try {
104 await Sharing.shareAsync(file.uri, {
105 mimeType: input.attachment.mimeType.split(";", 1)[0]?.trim() || "application/octet-stream",
106 dialogTitle: input.attachment.name,
107 });
108 shared = true;
109 } finally {
110 endHandoff();
111 }
112 } catch (cause) {
113 if (input.signal.aborted) return;
114 throw new Error(
115 openingShareSheet
116 ? "Could not open the share sheet. Try again."
117 : "Could not download the attachment. Check the connection and try again.",
118 { cause },
119 );
120 } finally {
121 activeDirectories.delete(directory.uri);
122 // A receiver can still be reading after Android's chooser returns.
123 // Successful exports expire on a later open; partial downloads do not.
124 if (!shared) {
125 removeDownloadDirectory(directory);
126 }
127 }
128}