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: input.name }}' is empty or could not be read.`));
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: input.name }}' is empty or could not be read.`));
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: PROVIDER_SEND_TURN_MAX_ATTACHMENTS }} files per message.`,
326 ),
327 };
328 }
329
330 const { getDocumentAsync } = await import("expo-document-picker");
331 const endHandoff = beginForegroundHandoff();
332 let result: DocumentPickerResult;
333 try {
334 // Import a readable cache copy because FileSystem may not read provider URIs directly.
335 result = await getDocumentAsync({ multiple: true, copyToCacheDirectory: true });
336 } catch (cause) {
337 return {
338 files: [],
339 error: errorDisplayMessage(cause, m) ?? m(msg("Could not open the file picker.")),
340 };
341 } finally {
342 endHandoff();
343 }
344 if (result.canceled || input.acceptSelection?.() === false) {
345 return { files: [], error: null };
346 }
347
348 const maxBytes = clampFileAttachmentUploadBytes(
349 input.maxBytes ?? PROVIDER_SEND_TURN_MAX_FILE_BYTES,
350 );
351 const attachments: DraftComposerAttachment[] = [];
352 let error: string | null = null;
353 let exceededAttachmentLimit = false;
354 for (const file of result.assets) {
355 if (attachments.length >= remainingSlots) {
356 exceededAttachmentLimit = true;
357 break;
358 }
359 // SAF can return blank display names, but the wire contract rejects them; fill before persisting.
360 const name = file.name.trim().length > 0 ? file.name : "file";
361 try {
362 const mimeType = imageMimeType({ name, mimeType: file.mimeType ?? "" });
363 const attachment = await createComposerFileAttachment({
364 uri: file.uri,
365 name,
366 mimeType: file.mimeType || "application/octet-stream",
367 sizeBytes: file.size ?? null,
368 maxBytes:
369 mimeType === null ? maxBytes : Math.max(maxBytes, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES),
370 });
371 if (mimeType === null || attachment.sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
372 attachments.push(attachment);
373 continue;
374 }
375 const { File } = await import("expo-file-system");
376 let fileUri = attachment.fileUri;
377 try {
378 const original = await new File(fileUri).base64();
379 const candidate = await fitComposerImage({ uri: fileUri, mimeType, base64: original });
380 const fitted =
381 candidate !== null &&
382 estimateBase64ByteSize(candidate.base64) <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
383 ? candidate
384 : null;
385 if (fitted !== null) {
386 fileUri = await persistComposerAttachmentFile(
387 fitted.uri,
388 name,
389 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
390 );
391 await removePersistedComposerAttachmentFile(attachment.fileUri);
392 }
393 } catch (cause) {
394 await removePersistedComposerAttachmentFile(attachment.fileUri);
395 throw cause;
396 }
397 attachments.push(await ownedComposerImageAttachment({ fileUri, name, mimeType }));
398 } catch (cause) {
399 error = errorDisplayMessage(cause, m) ?? m(msg`Could not read '${{ name }}'.`);
400 }
401 }
402 if (exceededAttachmentLimit) {
403 error = m(
404 msg`You can attach up to ${{ max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS }} files per message.`,
405 );
406 }
407 return { files: attachments, error };
408}
409
410async function loadImagePicker() {
411 try {
412 return await import("expo-image-picker");
413 } catch (error) {
414 throw new Error(m(msg("The photo library is unavailable right now.")), { cause: error });
415 }
416}
417
418export async function pickComposerImages(input: { readonly existingCount: number }): Promise<{
419 readonly images: ReadonlyArray<DraftComposerImageAttachment>;
420 readonly error: string | null;
421}> {
422 const result = await pickComposerMedia(input);
423 return {
424 images: result.attachments.filter((attachment) => attachment.type === "image"),
425 error: result.error,
426 };
427}
428
429export async function pickComposerMedia(input: {
430 readonly existingCount: number;
431 readonly maxVideoBytes?: number;
432 readonly acceptSelection?: () => boolean;
433}): Promise<{
434 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
435 readonly error: string | null;
436}> {
437 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
438 if (remainingSlots <= 0) {
439 return {
440 attachments: [],
441 error: m(
442 msg`You can attach up to ${{ max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS }} attachments per message.`,
443 ),
444 };
445 }
446
447 let imagePicker: Awaited<ReturnType<typeof loadImagePicker>>;
448 try {
449 imagePicker = await loadImagePicker();
450 } catch (error) {
451 return {
452 attachments: [],
453 error: errorDisplayMessage(error, m) ?? m(msg("The photo library is unavailable right now.")),
454 };
455 }
456
457 // Android pickers report background state; guard against deferred restarts mid-pick.
458 const endHandoff = beginForegroundHandoff();
459 let result: Awaited<ReturnType<typeof imagePicker.launchImageLibraryAsync>>;
460 try {
461 result = await imagePicker.launchImageLibraryAsync({
462 mediaTypes: input.maxVideoBytes === undefined ? ["images"] : ["images", "videos"],
463 allowsMultipleSelection: true,
464 selectionLimit: remainingSlots,
465 // Base64 makes iOS decode all full-size photos and stalls JS with large strings; read bytes only as needed.
466 base64: false,
467 quality: 1,
468 shouldDownloadFromNetwork: true,
469 });
470 } catch (error) {
471 return {
472 attachments: [],
473 error: errorDisplayMessage(error, m) ?? m(msg("Could not open the photo library.")),
474 };
475 } finally {
476 endHandoff();
477 }
478
479 if (result.canceled || input.acceptSelection?.() === false) {
480 return {
481 attachments: [],
482 error: null,
483 };
484 }
485
486 const attachments: DraftComposerAttachment[] = [];
487 let error: string | null = null;
488
489 for (const asset of result.assets) {
490 if (attachments.length >= remainingSlots) {
491 error = m(
492 msg`You can attach up to ${{ max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS }} attachments per message.`,
493 );
494 break;
495 }
496 const mimeType = asset.mimeType?.toLowerCase();
497 if (asset.type === "video" || mimeType?.startsWith("video/")) {
498 if (input.maxVideoBytes === undefined) {
499 error = m(msg("Video attachments are unavailable here."));
500 continue;
501 }
502 try {
503 const { File } = await import("expo-file-system");
504 const file = new File(asset.uri);
505 attachments.push(
506 await createComposerFileAttachment({
507 uri: asset.uri,
508 name: asset.fileName?.trim() || file.name || "video",
509 mimeType: mimeType || file.type || "application/octet-stream",
510 sizeBytes: asset.fileSize ?? null,
511 maxBytes: clampFileAttachmentUploadBytes(input.maxVideoBytes),
512 }),
513 );
514 } catch (cause) {
515 error =
516 errorDisplayMessage(cause, m) ??
517 m(msg`Could not read '${{ name: asset.fileName ?? "video" }}'.`);
518 }
519 continue;
520 }
521 if (asset.type !== "image" && !mimeType?.startsWith("image/")) {
522 error = m(msg`Unsupported file type for '${{ name: asset.fileName ?? "image" }}'.`);
523 continue;
524 }
525
526 const name = asset.fileName?.trim() || "image";
527 // Android content streams can exceed their reported size; measure the file before loading bytes into JS.
528 let sourceBytes: number | null = null;
529 try {
530 const { File } = await import("expo-file-system");
531 sourceBytes = new File(asset.uri).size;
532 } catch {
533 sourceBytes = null;
534 }
535 // Pass through supported, under-cap originals unchanged to preserve transparency and animation.
536 const originalMimeType =
537 mimeType !== undefined &&
538 isProviderSendTurnSupportedImageMimeType(mimeType) &&
539 sourceBytes !== null &&
540 sourceBytes > 0 &&
541 sourceBytes <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
542 ? mimeType
543 : null;
544
545 let image: { base64: string; mimeType: string; name: string; uri: string };
546 try {
547 if (originalMimeType !== null) {
548 const { File } = await import("expo-file-system");
549 const base64 = await new File(asset.uri).base64();
550 const fitted = await fitComposerImage({
551 uri: asset.uri,
552 mimeType: originalMimeType,
553 base64,
554 });
555 image = {
556 base64: fitted?.base64 ?? base64,
557 mimeType: originalMimeType,
558 name,
559 uri: fitted?.uri ?? asset.uri,
560 };
561 } else {
562 const rendered = await renderPhoto(asset.uri);
563 image = {
564 base64: rendered.base64,
565 mimeType: "image/jpeg",
566 name: /\.jpe?g$/i.test(name) ? name : `${name.replace(/\.[^.]+$/, "")}.jpg`,
567 uri: rendered.uri,
568 };
569 }
570 } catch {
571 error = m(msg`Failed to read '${{ name }}'.`);
572 continue;
573 }
574
575 const sizeBytes = estimateBase64ByteSize(image.base64);
576 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
577 error = m(msg`'${{ name }}' exceeds the 10 MB attachment limit.`);
578 continue;
579 }
580
581 try {
582 const fileUri = await persistComposerAttachmentFile(
583 image.uri,
584 image.name,
585 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
586 );
587 attachments.push(
588 await ownedComposerImageAttachment({ fileUri, name: image.name, mimeType: image.mimeType }),
589 );
590 } catch (cause) {
591 error = errorDisplayMessage(cause, m) ?? m(msg`Failed to read '${{ name }}'.`);
592 }
593 }
594
595 return {
596 attachments,
597 error,
598 };
599}
600
601function mimeTypeFromUri(uri: string): string {
602 const ext = uri.split(".").pop()?.toLowerCase();
603 switch (ext) {
604 case "png":
605 return "image/png";
606 case "jpg":
607 case "jpeg":
608 return "image/jpeg";
609 case "gif":
610 return "image/gif";
611 case "webp":
612 return "image/webp";
613 case "heic":
614 return "image/heic";
615 default:
616 return "image/png";
617 }
618}
619
620function isOwnedPastedImageUri(uri: string): boolean {
621 try {
622 const url = new URL(uri);
623 if (url.protocol !== "file:") {
624 return false;
625 }
626 const segments = url.pathname.split("/").filter(Boolean);
627 return segments.at(-2) === OWNED_PASTED_IMAGE_DIRECTORY;
628 } catch {
629 return false;
630 }
631}
632
633/** Leave out existingCount when the draft store caps after its duplicate check. */
634export async function convertPastedImagesToAttachments(input: {
635 readonly uris: ReadonlyArray<string>;
636 readonly existingCount?: number;
637}): Promise<{
638 readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
639 readonly error: string | null;
640}> {
641 const { File } = await import("expo-file-system");
642 const remainingSlots =
643 input.existingCount === undefined
644 ? Number.POSITIVE_INFINITY
645 : PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
646 const attachments: DraftComposerImageAttachment[] = [];
647 let error: string | null = null;
648
649 for (const [index, uri] of input.uris.entries()) {
650 const temporaryUris = isOwnedPastedImageUri(uri) ? [uri] : [];
651 try {
652 if (index >= Math.max(0, remainingSlots)) {
653 continue;
654 }
655 const file = new File(uri);
656 const reportedMimeType = file.type;
657 const sourceMimeType = reportedMimeType?.startsWith("image/")
658 ? reportedMimeType
659 : mimeTypeFromUri(uri);
660 let mimeType = isProviderSendTurnSupportedImageMimeType(sourceMimeType)
661 ? sourceMimeType
662 : "image/jpeg";
663 const rendered = mimeType === sourceMimeType ? null : await renderPhoto(uri);
664 const pastedBase64 = rendered?.base64 ?? (await file.base64());
665 const fitted = rendered ?? (await fitComposerImage({ uri, mimeType, base64: pastedBase64 }));
666 if (fitted !== null) {
667 temporaryUris.push(fitted.uri);
668 }
669 let base64 = fitted?.base64 ?? pastedBase64;
670 let sourceUri = fitted?.uri ?? uri;
671 if (
672 rendered === null &&
673 estimateBase64ByteSize(base64) > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
674 ) {
675 const jpeg = await renderPhoto(uri);
676 temporaryUris.push(jpeg.uri);
677 mimeType = "image/jpeg";
678 base64 = jpeg.base64;
679 sourceUri = jpeg.uri;
680 }
681 const sizeBytes = estimateBase64ByteSize(base64);
682 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
683 error =
684 sizeBytes > 0
685 ? m(msg("A pasted image exceeds the 10 MB attachment limit."))
686 : m(msg("Could not read a pasted image."));
687 continue;
688 }
689 const name = `pasted-image.${mimeType.split("/")[1] ?? "png"}`;
690 const { CryptoDigestAlgorithm, digestStringAsync } = await import("expo-crypto");
691 const contentDigest = await digestStringAsync(CryptoDigestAlgorithm.SHA256, base64);
692 const fileUri = await persistComposerAttachmentFile(
693 sourceUri,
694 name,
695 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
696 );
697 attachments.push(
698 await ownedComposerImageAttachment({ fileUri, name, mimeType, contentDigest }),
699 );
700 } catch (cause) {
701 console.warn("Failed to read pasted image", uri, cause);
702 error = m(msg("Could not read a pasted image."));
703 } finally {
704 for (const temporaryUri of temporaryUris) {
705 try {
706 const file = new File(temporaryUri);
707 if (file.exists) {
708 file.delete();
709 }
710 } catch (error) {
711 console.warn("Failed to remove temporary pasted image", temporaryUri, error);
712 }
713 }
714 }
715 }
716
717 return { attachments, error };
718}