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