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 { |
| 2 | clampFileAttachmentUploadBytes, |
| 3 | fileAttachmentTooLargeMessage, |
| 4 | } from "@t3tools/client-runtime/state/attachments"; |
| 5 | import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 6 | import { |
| 7 | isProviderSendTurnSupportedImageMimeType, |
| 8 | PROVIDER_SEND_TURN_MAX_ATTACHMENTS, |
| 9 | PROVIDER_SEND_TURN_MAX_FILE_BYTES, |
| 10 | PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, |
| 11 | type EnvironmentId, |
| 12 | type PastedTextAttachmentSource, |
| 13 | type UploadChatImageAttachment, |
| 14 | } from "@t3tools/contracts"; |
| 15 | import type { AttachmentUploadStatus } from "@t3tools/client-runtime/state/attachment-uploads"; |
| 16 | import type { DocumentPickerResult } from "expo-document-picker"; |
| 17 | import { msg } from "gt-react-native"; |
| 18 | import { m } from "../i18n/messages"; |
| 19 | import { estimateBase64ByteSize } from "./base64"; |
| 20 | import { |
| 21 | COMPOSER_ATTACHMENT_DIRECTORY, |
| 22 | isComposerAttachmentFileRetained, |
| 23 | resolveOwnedComposerAttachmentFileUri, |
| 24 | } from "./composerAttachmentFiles"; |
| 25 | import { imageMimeType } from "@t3tools/shared/image"; |
| 26 | import { videoMimeType } from "@t3tools/shared/video"; |
| 27 | import { fitComposerImage, renderPhoto } from "./composerImageFit"; |
| 28 | import { beginForegroundHandoff } from "./foreground-handoff"; |
| 29 | import { uuidv4 } from "./uuid"; |
| 30 | import { writeFileAtomically } from "./atomic-file"; |
| 31 | |
| 32 | export interface DraftComposerImageAttachment extends Omit<UploadChatImageAttachment, "dataUrl"> { |
| 33 | readonly id: string; |
| 34 | readonly previewUri: string; |
| 35 | readonly fileUri?: string; |
| 36 | readonly dataUrl?: string; |
| 37 | readonly uploadedAttachmentId?: string; |
| 38 | readonly uploadEnvironmentId?: EnvironmentId; |
| 39 | } |
| 40 | |
| 41 | export interface DraftComposerFileAttachment { |
| 42 | readonly id: string; |
| 43 | readonly type: "file"; |
| 44 | readonly name: string; |
| 45 | readonly mimeType: string; |
| 46 | readonly sizeBytes: number; |
| 47 | readonly fileUri: string; |
| 48 | readonly source?: PastedTextAttachmentSource; |
| 49 | readonly uploadedAttachmentId?: string; |
| 50 | readonly uploadEnvironmentId?: EnvironmentId; |
| 51 | } |
| 52 | |
| 53 | export async function createPastedTextComposerAttachment(input: { |
| 54 | readonly text: string; |
| 55 | readonly name: string; |
| 56 | readonly maxBytes: number; |
| 57 | }): Promise<DraftComposerFileAttachment> { |
| 58 | const bytes = new TextEncoder().encode(input.text).byteLength; |
| 59 | if (bytes <= 0) { |
| 60 | throw new Error(m(msg("Clipboard is empty."))); |
| 61 | } |
| 62 | if (bytes > input.maxBytes) { |
| 63 | throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes, m)); |
| 64 | } |
| 65 | |
| 66 | const { Directory, File, Paths } = await import("expo-file-system"); |
| 67 | const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY); |
| 68 | directory.create({ idempotent: true, intermediates: true }); |
| 69 | const file = new File(directory, `${uuidv4()}-${input.name}`); |
| 70 | await writeFileAtomically(file, input.text); |
| 71 | return { |
| 72 | id: uuidv4(), |
| 73 | type: "file", |
| 74 | name: input.name, |
| 75 | mimeType: "text/plain;charset=utf-8", |
| 76 | sizeBytes: bytes, |
| 77 | fileUri: file.uri, |
| 78 | source: { _tag: "pasted-text" }, |
| 79 | }; |
| 80 | } |
| 81 | |
| 82 | export type DraftComposerAttachment = DraftComposerImageAttachment | DraftComposerFileAttachment; |
| 83 | |
| 84 | /** |
| 85 | * Non-media attachments require chip references; missing references mean lost draft files. |
| 86 | * A chip cannot retry an upload or show its progress, so a document whose upload failed joins |
| 87 | * the strip until its retry finishes. |
| 88 | */ |
| 89 | export function composerStripAttachments( |
| 90 | attachments: ReadonlyArray<DraftComposerAttachment>, |
| 91 | uploadStatus: (attachment: DraftComposerAttachment) => AttachmentUploadStatus | undefined, |
| 92 | ): ReadonlyArray<DraftComposerAttachment> { |
| 93 | return attachments.filter((attachment) => { |
| 94 | if ( |
| 95 | attachment.type === "image" || |
| 96 | imageMimeType(attachment) !== null || |
| 97 | videoMimeType(attachment) !== null |
| 98 | ) { |
| 99 | return true; |
| 100 | } |
| 101 | const upload = uploadStatus(attachment); |
| 102 | return ( |
| 103 | upload?.status === "failed" || (upload?.status === "uploading" && upload.retrying === true) |
| 104 | ); |
| 105 | }); |
| 106 | } |
| 107 | |
| 108 | /** Promote legacy document-picked images only when their originals fit the image contract. */ |
| 109 | export function isComposerImageAttachment( |
| 110 | attachment: DraftComposerAttachment, |
| 111 | ): attachment is DraftComposerImageAttachment { |
| 112 | return ( |
| 113 | attachment.type === "image" || |
| 114 | (attachment.sizeBytes <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES && |
| 115 | imageMimeType(attachment) !== null) |
| 116 | ); |
| 117 | } |
| 118 | |
| 119 | export type FileBackedComposerAttachment = DraftComposerAttachment & { readonly fileUri: string }; |
| 120 | |
| 121 | export function isFileBackedComposerAttachment( |
| 122 | attachment: DraftComposerAttachment, |
| 123 | ): attachment is FileBackedComposerAttachment { |
| 124 | return attachment.fileUri !== undefined; |
| 125 | } |
| 126 | |
| 127 | /** Inline library/clipboard images own no file; local ids cannot resolve server assets. */ |
| 128 | export function composerAttachmentInlineUri( |
| 129 | attachment: DraftComposerAttachment | undefined, |
| 130 | ): string | undefined { |
| 131 | if (attachment === undefined || isFileBackedComposerAttachment(attachment)) return undefined; |
| 132 | return attachment.type === "image" ? (attachment.dataUrl ?? attachment.previewUri) : undefined; |
| 133 | } |
| 134 | |
| 135 | const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste"; |
| 136 | const ATTACHMENT_COPY_CHUNK_BYTES = 64 * 1024; |
| 137 | |
| 138 | export async function persistComposerAttachmentFile( |
| 139 | uri: string, |
| 140 | name: string, |
| 141 | maxBytes?: number, |
| 142 | ): Promise<string> { |
| 143 | const { Directory, File, FileMode, Paths } = await import("expo-file-system"); |
| 144 | const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY); |
| 145 | directory.create({ idempotent: true, intermediates: true }); |
| 146 | // Android's java.net.URI rejects characters expo-file-system leaves unencoded, such as `[` and `]`. |
| 147 | const safeName = name.replace(/[^\w. -]/g, "-") || "file"; |
| 148 | const destination = new File(directory, `${uuidv4()}-${safeName}`); |
| 149 | const source = new File(uri); |
| 150 | const sourceSize = source.size; |
| 151 | if ( |
| 152 | maxBytes !== undefined && |
| 153 | (sourceSize === null || (sourceSize === 0 && uri.startsWith("content:"))) |
| 154 | ) { |
| 155 | destination.create(); |
| 156 | try { |
| 157 | const reader = source.open(FileMode.ReadOnly); |
| 158 | try { |
| 159 | const writer = destination.open(FileMode.WriteOnly); |
| 160 | try { |
| 161 | let copiedBytes = 0; |
| 162 | while (true) { |
| 163 | const chunk = await reader.readBytes( |
| 164 | Math.min(ATTACHMENT_COPY_CHUNK_BYTES, maxBytes - copiedBytes + 1), |
| 165 | ); |
| 166 | if (chunk.byteLength === 0) { |
| 167 | break; |
| 168 | } |
| 169 | copiedBytes += chunk.byteLength; |
| 170 | if (copiedBytes > maxBytes) { |
| 171 | throw new Error(fileAttachmentTooLargeMessage(name, maxBytes, m)); |
| 172 | } |
| 173 | await writer.writeBytes(chunk); |
| 174 | } |
| 175 | } finally { |
| 176 | writer.close(); |
| 177 | } |
| 178 | } finally { |
| 179 | reader.close(); |
| 180 | } |
| 181 | } catch (error) { |
| 182 | if (destination.exists) { |
| 183 | destination.delete(); |
| 184 | } |
| 185 | throw error; |
| 186 | } |
| 187 | return destination.uri; |
| 188 | } |
| 189 | |
| 190 | if (maxBytes !== undefined && sourceSize !== null && sourceSize > maxBytes) { |
| 191 | throw new Error(fileAttachmentTooLargeMessage(name, maxBytes, m)); |
| 192 | } |
| 193 | try { |
| 194 | await source.copy(destination); |
| 195 | } catch (error) { |
| 196 | // Failed copies may leave untracked partial files; delete before surfacing failure. |
| 197 | try { |
| 198 | if (destination.exists) { |
| 199 | destination.delete(); |
| 200 | } |
| 201 | } catch (cleanupError) { |
| 202 | console.warn("[composer-attachments] could not remove a partial copy", cleanupError); |
| 203 | } |
| 204 | throw error; |
| 205 | } |
| 206 | // Android content streams may exceed reported size; validate the persisted copy. |
| 207 | const copiedSize = destination.size; |
| 208 | if (maxBytes !== undefined && copiedSize !== null && copiedSize > maxBytes) { |
| 209 | try { |
| 210 | if (destination.exists) { |
| 211 | destination.delete(); |
| 212 | } |
| 213 | } catch (cleanupError) { |
| 214 | console.warn("[composer-attachments] could not remove an oversized copy", cleanupError); |
| 215 | } |
| 216 | throw new Error(fileAttachmentTooLargeMessage(name, maxBytes, m)); |
| 217 | } |
| 218 | return destination.uri; |
| 219 | } |
| 220 | |
| 221 | export async function removePersistedComposerAttachmentFile(uri: string): Promise<void> { |
| 222 | try { |
| 223 | const { File, Paths } = await import("expo-file-system"); |
| 224 | const ownedUri = resolveOwnedComposerAttachmentFileUri(uri, Paths.document.uri); |
| 225 | if (ownedUri === null || isComposerAttachmentFileRetained(ownedUri)) { |
| 226 | return; |
| 227 | } |
| 228 | const file = new File(ownedUri); |
| 229 | if (file.exists) { |
| 230 | file.delete(); |
| 231 | } |
| 232 | } catch (error) { |
| 233 | console.warn("[composer-attachments] could not remove local file", error); |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | export async function createComposerFileAttachment(input: { |
| 238 | readonly uri: string; |
| 239 | readonly name: string; |
| 240 | readonly mimeType: string; |
| 241 | readonly sizeBytes: number | null; |
| 242 | readonly maxBytes: number; |
| 243 | }): Promise<DraftComposerFileAttachment> { |
| 244 | if (input.sizeBytes !== null && input.sizeBytes > input.maxBytes) { |
| 245 | throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes, m)); |
| 246 | } |
| 247 | const { File } = await import("expo-file-system"); |
| 248 | const fileUri = await persistComposerAttachmentFile(input.uri, input.name, input.maxBytes); |
| 249 | try { |
| 250 | const sizeBytes = new File(fileUri).size ?? input.sizeBytes ?? 0; |
| 251 | if (sizeBytes <= 0) { |
| 252 | throw new Error(m(msg("''{name}'' is empty or could not be read.", { name: input.name }))); |
| 253 | } |
| 254 | if (sizeBytes > input.maxBytes) { |
| 255 | throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes, m)); |
| 256 | } |
| 257 | return { |
| 258 | id: uuidv4(), |
| 259 | type: "file", |
| 260 | name: input.name, |
| 261 | mimeType: input.mimeType, |
| 262 | sizeBytes, |
| 263 | fileUri, |
| 264 | }; |
| 265 | } catch (error) { |
| 266 | await removePersistedComposerAttachmentFile(fileUri); |
| 267 | throw error; |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | export async function pickComposerFiles(input: { |
| 272 | readonly existingCount: number; |
| 273 | readonly maxBytes?: number; |
| 274 | readonly acceptSelection?: () => boolean; |
| 275 | }): Promise<{ |
| 276 | readonly files: ReadonlyArray<DraftComposerAttachment>; |
| 277 | readonly error: string | null; |
| 278 | }> { |
| 279 | const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount; |
| 280 | if (remainingSlots <= 0) { |
| 281 | return { |
| 282 | files: [], |
| 283 | error: m( |
| 284 | msg("You can attach up to {max} files per message.", { |
| 285 | max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS, |
| 286 | }), |
| 287 | ), |
| 288 | }; |
| 289 | } |
| 290 | |
| 291 | const { getDocumentAsync } = await import("expo-document-picker"); |
| 292 | const endHandoff = beginForegroundHandoff(); |
| 293 | let result: DocumentPickerResult; |
| 294 | try { |
| 295 | // Import a readable cache copy because FileSystem may not read provider URIs directly. |
| 296 | result = await getDocumentAsync({ multiple: true, copyToCacheDirectory: true }); |
| 297 | } catch (cause) { |
| 298 | return { |
| 299 | files: [], |
| 300 | error: errorDisplayMessage(cause, m) ?? m(msg("Could not open the file picker.")), |
| 301 | }; |
| 302 | } finally { |
| 303 | endHandoff(); |
| 304 | } |
| 305 | if (result.canceled || input.acceptSelection?.() === false) { |
| 306 | return { files: [], error: null }; |
| 307 | } |
| 308 | |
| 309 | const maxBytes = clampFileAttachmentUploadBytes( |
| 310 | input.maxBytes ?? PROVIDER_SEND_TURN_MAX_FILE_BYTES, |
| 311 | ); |
| 312 | const attachments: DraftComposerAttachment[] = []; |
| 313 | let error: string | null = null; |
| 314 | let exceededAttachmentLimit = false; |
| 315 | for (const file of result.assets) { |
| 316 | if (attachments.length >= remainingSlots) { |
| 317 | exceededAttachmentLimit = true; |
| 318 | break; |
| 319 | } |
| 320 | // SAF can return blank display names, but the wire contract rejects them; fill before persisting. |
| 321 | const name = file.name.trim().length > 0 ? file.name : "file"; |
| 322 | try { |
| 323 | const mimeType = imageMimeType({ name, mimeType: file.mimeType ?? "" }); |
| 324 | const attachment = await createComposerFileAttachment({ |
| 325 | uri: file.uri, |
| 326 | name, |
| 327 | mimeType: file.mimeType || "application/octet-stream", |
| 328 | sizeBytes: file.size ?? null, |
| 329 | maxBytes: |
| 330 | mimeType === null ? maxBytes : Math.max(maxBytes, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES), |
| 331 | }); |
| 332 | if (mimeType === null || attachment.sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { |
| 333 | attachments.push(attachment); |
| 334 | continue; |
| 335 | } |
| 336 | try { |
| 337 | const { File } = await import("expo-file-system"); |
| 338 | const original = await new File(attachment.fileUri).base64(); |
| 339 | const candidate = await fitComposerImage({ |
| 340 | uri: attachment.fileUri, |
| 341 | mimeType, |
| 342 | base64: original, |
| 343 | }); |
| 344 | const fitted = |
| 345 | candidate !== null && |
| 346 | estimateBase64ByteSize(candidate.base64) <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES |
| 347 | ? candidate |
| 348 | : null; |
| 349 | const base64 = fitted?.base64 ?? original; |
| 350 | const sizeBytes = estimateBase64ByteSize(base64); |
| 351 | if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { |
| 352 | throw new Error(m(msg("''{name}'' exceeds the 10 MB attachment limit.", { name }))); |
| 353 | } |
| 354 | const dataUrl = `data:${mimeType};base64,${base64}`; |
| 355 | attachments.push({ |
| 356 | id: attachment.id, |
| 357 | type: "image", |
| 358 | name, |
| 359 | mimeType, |
| 360 | sizeBytes, |
| 361 | dataUrl, |
| 362 | previewUri: fitted?.uri ?? dataUrl, |
| 363 | }); |
| 364 | } finally { |
| 365 | await removePersistedComposerAttachmentFile(attachment.fileUri); |
| 366 | } |
| 367 | } catch (cause) { |
| 368 | error = errorDisplayMessage(cause, m) ?? m(msg("Could not read ''{name}''.", { name })); |
| 369 | } |
| 370 | } |
| 371 | if (exceededAttachmentLimit) { |
| 372 | error = m( |
| 373 | msg("You can attach up to {max} files per message.", { |
| 374 | max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS, |
| 375 | }), |
| 376 | ); |
| 377 | } |
| 378 | return { files: attachments, error }; |
| 379 | } |
| 380 | |
| 381 | async function loadImagePicker() { |
| 382 | try { |
| 383 | return await import("expo-image-picker"); |
| 384 | } catch (error) { |
| 385 | throw new Error(m(msg("The photo library is unavailable right now.")), { cause: error }); |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | export async function pickComposerImages(input: { readonly existingCount: number }): Promise<{ |
| 390 | readonly images: ReadonlyArray<DraftComposerImageAttachment>; |
| 391 | readonly error: string | null; |
| 392 | }> { |
| 393 | const result = await pickComposerMedia(input); |
| 394 | return { |
| 395 | images: result.attachments.filter((attachment) => attachment.type === "image"), |
| 396 | error: result.error, |
| 397 | }; |
| 398 | } |
| 399 | |
| 400 | export async function pickComposerMedia(input: { |
| 401 | readonly existingCount: number; |
| 402 | readonly maxVideoBytes?: number; |
| 403 | readonly acceptSelection?: () => boolean; |
| 404 | }): Promise<{ |
| 405 | readonly attachments: ReadonlyArray<DraftComposerAttachment>; |
| 406 | readonly error: string | null; |
| 407 | }> { |
| 408 | const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount; |
| 409 | if (remainingSlots <= 0) { |
| 410 | return { |
| 411 | attachments: [], |
| 412 | error: m( |
| 413 | msg("You can attach up to {max} attachments per message.", { |
| 414 | max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS, |
| 415 | }), |
| 416 | ), |
| 417 | }; |
| 418 | } |
| 419 | |
| 420 | let imagePicker: Awaited<ReturnType<typeof loadImagePicker>>; |
| 421 | try { |
| 422 | imagePicker = await loadImagePicker(); |
| 423 | } catch (error) { |
| 424 | return { |
| 425 | attachments: [], |
| 426 | error: errorDisplayMessage(error, m) ?? m(msg("The photo library is unavailable right now.")), |
| 427 | }; |
| 428 | } |
| 429 | |
| 430 | // Android pickers report background state; guard against deferred restarts mid-pick. |
| 431 | const endHandoff = beginForegroundHandoff(); |
| 432 | let result: Awaited<ReturnType<typeof imagePicker.launchImageLibraryAsync>>; |
| 433 | try { |
| 434 | result = await imagePicker.launchImageLibraryAsync({ |
| 435 | mediaTypes: input.maxVideoBytes === undefined ? ["images"] : ["images", "videos"], |
| 436 | allowsMultipleSelection: true, |
| 437 | selectionLimit: remainingSlots, |
| 438 | // Base64 makes iOS decode all full-size photos and stalls JS with large strings; read bytes only as needed. |
| 439 | base64: false, |
| 440 | quality: 1, |
| 441 | shouldDownloadFromNetwork: true, |
| 442 | }); |
| 443 | } catch (error) { |
| 444 | return { |
| 445 | attachments: [], |
| 446 | error: errorDisplayMessage(error, m) ?? m(msg("Could not open the photo library.")), |
| 447 | }; |
| 448 | } finally { |
| 449 | endHandoff(); |
| 450 | } |
| 451 | |
| 452 | if (result.canceled || input.acceptSelection?.() === false) { |
| 453 | return { |
| 454 | attachments: [], |
| 455 | error: null, |
| 456 | }; |
| 457 | } |
| 458 | |
| 459 | const attachments: DraftComposerAttachment[] = []; |
| 460 | let error: string | null = null; |
| 461 | |
| 462 | for (const asset of result.assets) { |
| 463 | if (attachments.length >= remainingSlots) { |
| 464 | error = m( |
| 465 | msg("You can attach up to {max} attachments per message.", { |
| 466 | max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS, |
| 467 | }), |
| 468 | ); |
| 469 | break; |
| 470 | } |
| 471 | const mimeType = asset.mimeType?.toLowerCase(); |
| 472 | if (asset.type === "video" || mimeType?.startsWith("video/")) { |
| 473 | if (input.maxVideoBytes === undefined) { |
| 474 | error = m(msg("Video attachments are unavailable here.")); |
| 475 | continue; |
| 476 | } |
| 477 | try { |
| 478 | const { File } = await import("expo-file-system"); |
| 479 | const file = new File(asset.uri); |
| 480 | attachments.push( |
| 481 | await createComposerFileAttachment({ |
| 482 | uri: asset.uri, |
| 483 | name: asset.fileName?.trim() || file.name || "video", |
| 484 | mimeType: mimeType || file.type || "application/octet-stream", |
| 485 | sizeBytes: asset.fileSize ?? null, |
| 486 | maxBytes: clampFileAttachmentUploadBytes(input.maxVideoBytes), |
| 487 | }), |
| 488 | ); |
| 489 | } catch (cause) { |
| 490 | error = |
| 491 | errorDisplayMessage(cause, m) ?? |
| 492 | m(msg("Could not read ''{name}''.", { name: asset.fileName ?? "video" })); |
| 493 | } |
| 494 | continue; |
| 495 | } |
| 496 | if (asset.type !== "image" && !mimeType?.startsWith("image/")) { |
| 497 | error = m(msg("Unsupported file type for ''{name}''.", { name: asset.fileName ?? "image" })); |
| 498 | continue; |
| 499 | } |
| 500 | |
| 501 | const name = asset.fileName?.trim() || "image"; |
| 502 | // Android content streams can exceed their reported size; measure the file before loading bytes into JS. |
| 503 | let sourceBytes: number | null = null; |
| 504 | try { |
| 505 | const { File } = await import("expo-file-system"); |
| 506 | sourceBytes = new File(asset.uri).size; |
| 507 | } catch { |
| 508 | sourceBytes = null; |
| 509 | } |
| 510 | // Pass through supported, under-cap originals unchanged to preserve transparency and animation. |
| 511 | const originalMimeType = |
| 512 | mimeType !== undefined && |
| 513 | isProviderSendTurnSupportedImageMimeType(mimeType) && |
| 514 | sourceBytes !== null && |
| 515 | sourceBytes > 0 && |
| 516 | sourceBytes <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES |
| 517 | ? mimeType |
| 518 | : null; |
| 519 | |
| 520 | let image: { base64: string; mimeType: string; name: string; previewUri: string }; |
| 521 | try { |
| 522 | if (originalMimeType !== null) { |
| 523 | const { File } = await import("expo-file-system"); |
| 524 | const base64 = await new File(asset.uri).base64(); |
| 525 | const fitted = await fitComposerImage({ |
| 526 | uri: asset.uri, |
| 527 | mimeType: originalMimeType, |
| 528 | base64, |
| 529 | }); |
| 530 | image = { |
| 531 | base64: fitted?.base64 ?? base64, |
| 532 | mimeType: originalMimeType, |
| 533 | name, |
| 534 | previewUri: fitted?.uri ?? asset.uri, |
| 535 | }; |
| 536 | } else { |
| 537 | const rendered = await renderPhoto(asset.uri); |
| 538 | image = { |
| 539 | base64: rendered.base64, |
| 540 | mimeType: "image/jpeg", |
| 541 | name: /\.jpe?g$/i.test(name) ? name : `${name.replace(/\.[^.]+$/, "")}.jpg`, |
| 542 | previewUri: rendered.uri, |
| 543 | }; |
| 544 | } |
| 545 | } catch { |
| 546 | error = m(msg("Failed to read ''{name}''.", { name })); |
| 547 | continue; |
| 548 | } |
| 549 | |
| 550 | const sizeBytes = estimateBase64ByteSize(image.base64); |
| 551 | if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { |
| 552 | error = m(msg("''{name}'' exceeds the 10 MB attachment limit.", { name })); |
| 553 | continue; |
| 554 | } |
| 555 | |
| 556 | attachments.push({ |
| 557 | id: uuidv4(), |
| 558 | type: "image", |
| 559 | name: image.name, |
| 560 | mimeType: image.mimeType, |
| 561 | sizeBytes, |
| 562 | dataUrl: `data:${image.mimeType};base64,${image.base64}`, |
| 563 | previewUri: image.previewUri, |
| 564 | }); |
| 565 | } |
| 566 | |
| 567 | return { |
| 568 | attachments, |
| 569 | error, |
| 570 | }; |
| 571 | } |
| 572 | |
| 573 | function mimeTypeFromUri(uri: string): string { |
| 574 | const ext = uri.split(".").pop()?.toLowerCase(); |
| 575 | switch (ext) { |
| 576 | case "png": |
| 577 | return "image/png"; |
| 578 | case "jpg": |
| 579 | case "jpeg": |
| 580 | return "image/jpeg"; |
| 581 | case "gif": |
| 582 | return "image/gif"; |
| 583 | case "webp": |
| 584 | return "image/webp"; |
| 585 | case "heic": |
| 586 | return "image/heic"; |
| 587 | default: |
| 588 | return "image/png"; |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | function isOwnedPastedImageUri(uri: string): boolean { |
| 593 | try { |
| 594 | const url = new URL(uri); |
| 595 | if (url.protocol !== "file:") { |
| 596 | return false; |
| 597 | } |
| 598 | const segments = url.pathname.split("/").filter(Boolean); |
| 599 | return segments.at(-2) === OWNED_PASTED_IMAGE_DIRECTORY; |
| 600 | } catch { |
| 601 | return false; |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | /** Leave out existingCount when the draft store caps after its duplicate check. */ |
| 606 | export async function convertPastedImagesToAttachments(input: { |
| 607 | readonly uris: ReadonlyArray<string>; |
| 608 | readonly existingCount?: number; |
| 609 | }): Promise<{ |
| 610 | readonly attachments: ReadonlyArray<DraftComposerImageAttachment>; |
| 611 | readonly error: string | null; |
| 612 | }> { |
| 613 | const { File } = await import("expo-file-system"); |
| 614 | const remainingSlots = |
| 615 | input.existingCount === undefined |
| 616 | ? Number.POSITIVE_INFINITY |
| 617 | : PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount; |
| 618 | const attachments: DraftComposerImageAttachment[] = []; |
| 619 | let error: string | null = null; |
| 620 | |
| 621 | for (const [index, uri] of input.uris.entries()) { |
| 622 | const temporaryUris = isOwnedPastedImageUri(uri) ? [uri] : []; |
| 623 | try { |
| 624 | if (index >= Math.max(0, remainingSlots)) { |
| 625 | continue; |
| 626 | } |
| 627 | const file = new File(uri); |
| 628 | const reportedMimeType = file.type; |
| 629 | const sourceMimeType = reportedMimeType?.startsWith("image/") |
| 630 | ? reportedMimeType |
| 631 | : mimeTypeFromUri(uri); |
| 632 | let mimeType = isProviderSendTurnSupportedImageMimeType(sourceMimeType) |
| 633 | ? sourceMimeType |
| 634 | : "image/jpeg"; |
| 635 | const rendered = mimeType === sourceMimeType ? null : await renderPhoto(uri); |
| 636 | const pastedBase64 = rendered?.base64 ?? (await file.base64()); |
| 637 | const fitted = rendered ?? (await fitComposerImage({ uri, mimeType, base64: pastedBase64 })); |
| 638 | if (fitted !== null) { |
| 639 | temporaryUris.push(fitted.uri); |
| 640 | } |
| 641 | let base64 = fitted?.base64 ?? pastedBase64; |
| 642 | if ( |
| 643 | rendered === null && |
| 644 | estimateBase64ByteSize(base64) > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES |
| 645 | ) { |
| 646 | const jpeg = await renderPhoto(uri); |
| 647 | temporaryUris.push(jpeg.uri); |
| 648 | mimeType = "image/jpeg"; |
| 649 | base64 = jpeg.base64; |
| 650 | } |
| 651 | const sizeBytes = estimateBase64ByteSize(base64); |
| 652 | if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { |
| 653 | error = |
| 654 | sizeBytes > 0 |
| 655 | ? m(msg("A pasted image exceeds the 10 MB attachment limit.")) |
| 656 | : m(msg("Could not read a pasted image.")); |
| 657 | continue; |
| 658 | } |
| 659 | const dataUrl = `data:${mimeType};base64,${base64}`; |
| 660 | attachments.push({ |
| 661 | id: uuidv4(), |
| 662 | type: "image", |
| 663 | name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`, |
| 664 | mimeType, |
| 665 | sizeBytes, |
| 666 | dataUrl, |
| 667 | previewUri: dataUrl, |
| 668 | }); |
| 669 | } catch (cause) { |
| 670 | console.warn("Failed to read pasted image", uri, cause); |
| 671 | error = m(msg("Could not read a pasted image.")); |
| 672 | } finally { |
| 673 | for (const temporaryUri of temporaryUris) { |
| 674 | try { |
| 675 | const file = new File(temporaryUri); |
| 676 | if (file.exists) { |
| 677 | file.delete(); |
| 678 | } |
| 679 | } catch (error) { |
| 680 | console.warn("Failed to remove temporary pasted image", temporaryUri, error); |
| 681 | } |
| 682 | } |
| 683 | } |
| 684 | } |
| 685 | |
| 686 | return { attachments, error }; |
| 687 | } |