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