Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

incoming-share-model.ts

448 lines15.4 KB

1import {
2 clampFileAttachmentUploadBytes,
3 fileAttachmentTooLargeMessage,
4} from "@t3tools/client-runtime/state/attachments";
5import {
6 isProviderSendTurnSupportedImageMimeType,
7 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
8 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
9 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
10} from "@t3tools/contracts";
11import * as Schema from "effect/Schema";
12import type { ResolvedSharePayload, SharePayload } from "expo-sharing";
13​
14import { DraftComposerAttachmentSchema } from "../../lib/composer-image-schema";
15import { fitComposerImage } from "../../lib/composerImageFit";
16import type { DraftComposerAttachment } from "../../lib/composerImages";
17import { estimateBase64ByteSize } from "../../lib/base64";
18​
19export interface IncomingShareDraft {
20 readonly schemaVersion: 1;
21 readonly id: string;
22 readonly createdAt: string;
23 readonly destination?: IncomingShareDestination;
24 readonly text: string;
25 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
26 readonly warnings: ReadonlyArray<string>;
28​
29export interface IncomingShareDestination {
30 readonly environmentId: string;
31 readonly projectId: string;
33​
34const IncomingShareDestinationSchema = Schema.Struct({
35 environmentId: Schema.String,
36 projectId: Schema.String,
37});
38​
39export const IncomingShareDraftSchema = Schema.Struct({
40 schemaVersion: Schema.Literal(1),
41 id: Schema.String,
42 createdAt: Schema.String,
43 destination: Schema.optional(IncomingShareDestinationSchema),
44 text: Schema.String,
45 attachments: Schema.Array(DraftComposerAttachmentSchema),
46 warnings: Schema.Array(Schema.String),
47});
48​
49const decodeIncomingShareDraftSync = Schema.decodeUnknownSync(IncomingShareDraftSchema);
50​
51export function decodeIncomingShareDraft(value: unknown): IncomingShareDraft {
52 return decodeIncomingShareDraftSync(value);
54​
55/**
56 * `file:` path with the iOS `/private` prefix stripped, so URIs that reach the
57 * same file through the `/var` symlink and through `/private/var` compare
58 * equal.
59 */
60function normalizedFileUriPath(uri: string): string | null {
61 try {
62 const url = new URL(uri);
63 if (url.protocol !== "file:") {
64 return null;
65 }
66 const path = decodeURIComponent(url.pathname);
67 // URL parsing collapses literal ".." segments, but an encoded separator
68 // survives it: "..%2F.." decodes to "../..", which the filesystem would
69 // resolve outside the root the lexical containment check accepted.
70 if (path.split("/").includes("..")) {
71 return null;
72 }
73 return path.startsWith("/private/var/") ? path.slice("/private".length) : path;
74 } catch {
75 return null;
76 }
78​
79/**
80 * Whether a shared `file:` URI points strictly inside one of the directories
81 * this app owns (its sandbox and its share-extension App Group container).
82 * Share cleanup must never delete anything else: an iOS open-in-place share
83 * hands over the sender's own file URL, and deleting it destroys the user's
84 * document.
85 */
86export function isShareFileUriUnderOwnedRoots(
87 uri: string,
88 ownedRootUris: ReadonlyArray<string>,
89): boolean {
90 const path = normalizedFileUriPath(uri);
91 if (path === null) {
92 return false;
93 }
94 return ownedRootUris.some((rootUri) => {
95 const rootPath = normalizedFileUriPath(rootUri);
96 if (rootPath === null) {
97 return false;
98 }
99 const root = rootPath.endsWith("/") ? rootPath : `${rootPath}/`;
100 return path.startsWith(root) && path.length > root.length;
101 });
103​
104export interface IncomingShareFileReader {
105 readonly readBase64: (uri: string) => Promise<string>;
106 readonly removeOwnedFile: (uri: string) => Promise<void> | void;
107 readonly persistFile?: (uri: string, name: string) => Promise<string>;
108 readonly readSize?: (uri: string) => Promise<number | null>;
110​
111export function selectIncomingShareAttachments(input: {
112 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
113 readonly maxFileAttachmentBytes: number | null;
114}): {
115 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
116 readonly warnings: ReadonlyArray<string>;
117} {
118 const attachments: DraftComposerAttachment[] = [];
119 const warnings: string[] = [];
120​
121 for (const attachment of input.attachments) {
122 if (attachment.type === "image") {
123 attachments.push(attachment);
124 continue;
125 }
126 if (input.maxFileAttachmentBytes === null) {
127 warnings.push(`'${attachment.name}' was skipped because this server does not support files.`);
128 continue;
129 }
130 const maxFileAttachmentBytes = clampFileAttachmentUploadBytes(input.maxFileAttachmentBytes);
131 if (attachment.sizeBytes > maxFileAttachmentBytes) {
132 warnings.push(fileAttachmentTooLargeMessage(attachment.name, maxFileAttachmentBytes));
133 continue;
134 }
135 attachments.push(attachment);
136 }
137​
138 return { attachments, warnings };
140​
141export function selectIncomingShareAttachmentsForServer(input: {
142 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
143 readonly serverConfig: {
144 readonly environment: {
145 readonly capabilities: {
146 readonly attachmentUploads?: boolean;
147 readonly fileAttachments?: { readonly maxUploadBytes: number };
148 };
149 };
150 } | null;
151}):
152 | { readonly status: "pending" }
153 | {
154 readonly status: "ready";
155 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
156 readonly warnings: ReadonlyArray<string>;
157 } {
158 const hasFiles = input.attachments.some((attachment) => attachment.type === "file");
159 if (hasFiles && input.serverConfig === null) {
160 return { status: "pending" };
161 }
162 const capabilities = input.serverConfig?.environment.capabilities;
163 const maxFileAttachmentBytes =
164 capabilities?.attachmentUploads === true
165 ? (capabilities.fileAttachments?.maxUploadBytes ?? null)
166 : null;
167 return {
168 status: "ready",
169 ...selectIncomingShareAttachments({
170 attachments: input.attachments,
171 maxFileAttachmentBytes,
172 }),
173 };
175​
176function sharedText(payloads: ReadonlyArray<SharePayload>): string {
177 const seen = new Set<string>();
178 const values: string[] = [];
179 for (const payload of payloads) {
180 if (payload.shareType !== "text" && payload.shareType !== "url") {
181 continue;
182 }
183 const value = payload.value.trim();
184 if (!value || seen.has(value)) {
185 continue;
186 }
187 seen.add(value);
188 values.push(value);
189 }
190 return values.join("\n\n");
192​
193function resolvedImageFor(
194 payload: SharePayload,
195 index: number,
196 resolvedPayloads: ReadonlyArray<ResolvedSharePayload>,
197 consumedIndexes: Set<number>,
198): ResolvedSharePayload | undefined {
199 const sameIndex = resolvedPayloads[index];
200 if (
201 !consumedIndexes.has(index) &&
202 sameIndex?.shareType === payload.shareType &&
203 sameIndex.value === payload.value
204 ) {
205 consumedIndexes.add(index);
206 return sameIndex;
207 }
208 const matchingIndex = resolvedPayloads.findIndex(
209 (candidate, candidateIndex) =>
210 !consumedIndexes.has(candidateIndex) &&
211 candidate.shareType === payload.shareType &&
212 candidate.value === payload.value,
213 );
214 if (matchingIndex < 0) {
215 return undefined;
216 }
217 consumedIndexes.add(matchingIndex);
218 return resolvedPayloads[matchingIndex];
220​
221async function releaseOwnedFiles(
222 fileReader: IncomingShareFileReader,
223 uris: ReadonlyArray<string | undefined>,
224): Promise<void> {
225 for (const uri of new Set(uris.filter((candidate): candidate is string => Boolean(candidate)))) {
226 try {
227 await fileReader.removeOwnedFile(uri);
228 } catch {}
229 }
231​
232function fallbackName(uri: string, index: number, mimeType: string): string {
233 try {
234 const pathName = new URL(uri).pathname.split("/").findLast((segment) => segment.length > 0);
235 if (pathName) {
236 return decodeURIComponent(pathName);
237 }
238 } catch {}
239 const family = mimeType.split("/")[0]?.toLowerCase();
240 const kind = family === "image" || family === "audio" || family === "video" ? family : "file";
241 const extension =
242 mimeType.split("/")[1]?.replace(/[^a-z0-9.+-]/gi, "") || (kind === "image" ? "png" : "bin");
243 return `shared-${kind}-${index + 1}.${extension}`;
245​
246export async function buildIncomingShareDraft(input: {
247 readonly payloads: ReadonlyArray<SharePayload>;
248 readonly resolvedPayloads: ReadonlyArray<ResolvedSharePayload>;
249 readonly fileReader: IncomingShareFileReader;
250 readonly id: string;
251 readonly createdAt: string;
252}): Promise<IncomingShareDraft> {
253 const attachments: DraftComposerAttachment[] = [];
254 const warnings: string[] = [];
255 const consumedResolvedPayloadIndexes = new Set<number>();
256 let warnedAttachmentLimit = false;
257​
258 for (const [index, payload] of input.payloads.entries()) {
259 if (
260 payload.shareType !== "image" &&
261 payload.shareType !== "file" &&
262 payload.shareType !== "audio" &&
263 payload.shareType !== "video"
264 ) {
265 continue;
266 }
267 const resolved = resolvedImageFor(
268 payload,
269 index,
270 input.resolvedPayloads,
271 consumedResolvedPayloadIndexes,
272 );
273 const uri = resolved?.contentUri ?? payload.value;
274 if (attachments.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
275 if (!warnedAttachmentLimit) {
276 warnings.push(
277 `Only the first ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} shared ${payload.shareType === "image" ? "images" : "files"} were attached.`,
278 );
279 warnedAttachmentLimit = true;
280 }
281 await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
282 continue;
283 }
284​
285 const mimeType = (
286 resolved?.contentMimeType ??
287 payload.mimeType ??
288 (payload.shareType === "image" ? "image/png" : "application/octet-stream")
289 ).toLowerCase();
290 if (payload.shareType !== "image") {
291 const sharedFileName =
292 typeof payload.originalName === "string" && payload.originalName.trim().length > 0
293 ? payload.originalName
294 : undefined;
295 const name = resolved?.originalName ?? sharedFileName ?? fallbackName(uri, index, mimeType);
296 if (!uri) {
297 warnings.push("One shared file could not be read.");
298 continue;
299 }
300 let persistedFileUri: string | undefined;
301 let retainedFileUri: string | undefined;
302 try {
303 let sizeBytes = resolved?.contentSize ?? (await input.fileReader.readSize?.(uri)) ?? null;
304 if (
305 (sizeBytes === null || (sizeBytes === 0 && uri.startsWith("content:"))) &&
306 input.fileReader.persistFile
307 ) {
308 persistedFileUri = await input.fileReader.persistFile(uri, name);
309 sizeBytes = (await input.fileReader.readSize?.(persistedFileUri)) ?? null;
310 }
311 if (sizeBytes === null) {
312 warnings.push(`The size of '${name}' could not be determined.`);
313 if (persistedFileUri) {
314 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
315 }
316 continue;
317 }
318 if (sizeBytes <= 0) {
319 warnings.push(`'${name}' is empty or could not be read.`);
320 if (persistedFileUri) {
321 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
322 }
323 continue;
324 }
325 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
326 warnings.push(fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_FILE_BYTES));
327 if (persistedFileUri) {
328 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
329 }
330 continue;
331 }
332 if (persistedFileUri === undefined && input.fileReader.persistFile) {
333 persistedFileUri = await input.fileReader.persistFile(uri, name);
334 // An Android content: source can misreport its size while the stored
335 // copy is what uploads, so the copy's measured size is what the
336 // attachment must record.
337 const storedSize = (await input.fileReader.readSize?.(persistedFileUri)) ?? null;
338 if (storedSize !== null) {
339 sizeBytes = storedSize;
340 }
341 if (sizeBytes <= 0) {
342 warnings.push(`'${name}' is empty or could not be read.`);
343 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
344 continue;
345 }
346 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
347 warnings.push(fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_FILE_BYTES));
348 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
349 continue;
350 }
351 }
352 attachments.push({
353 id: `${input.id}:file:${index}`,
354 type: "file",
355 name,
356 mimeType,
357 sizeBytes,
358 fileUri: persistedFileUri ?? uri,
359 });
360 retainedFileUri = persistedFileUri ?? uri;
361 } catch (error) {
362 warnings.push(error instanceof Error ? error.message : `Could not read '${name}'.`);
363 if (persistedFileUri !== undefined) {
364 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
365 }
366 } finally {
367 await releaseOwnedFiles(
368 input.fileReader,
369 [uri, payload.value].filter((candidate) => candidate !== retainedFileUri),
370 );
371 }
372 continue;
373 }
374 if (!uri || !mimeType.startsWith("image/")) {
375 warnings.push("One shared item was not a supported image.");
376 await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
377 continue;
378 }
379 if (!isProviderSendTurnSupportedImageMimeType(mimeType)) {
380 warnings.push(
381 `'${resolved?.originalName ?? fallbackName(uri, index, mimeType)}' is not a supported image type.`,
382 );
383 await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
384 continue;
385 }
386 if (
387 resolved?.contentSize !== null &&
388 resolved?.contentSize !== undefined &&
389 resolved.contentSize > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
390 ) {
391 warnings.push(
392 `'${resolved.originalName ?? fallbackName(uri, index, mimeType)}' exceeds the 10 MB attachment limit.`,
393 );
394 await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
395 continue;
396 }
397​
398 try {
399 const sharedBase64 = await input.fileReader.readBase64(uri);
400 // Rendered from the bytes already read, since the provider's file may not be readable
401 // by the native image loader.
402 const fitted = await fitComposerImage({
403 uri: `data:${mimeType};base64,${sharedBase64}`,
404 mimeType,
405 base64: sharedBase64,
406 });
407 const base64 = fitted?.base64 ?? sharedBase64;
408 const sizeBytes = fitted
409 ? estimateBase64ByteSize(base64)
410 : (resolved?.contentSize ?? estimateBase64ByteSize(base64));
411 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
412 warnings.push(
413 `'${resolved?.originalName ?? fallbackName(uri, index, mimeType)}' exceeds the 10 MB attachment limit.`,
414 );
415 continue;
416 }
417 const dataUrl = `data:${mimeType};base64,${base64}`;
418 attachments.push({
419 id: `${input.id}:image:${index}`,
420 type: "image",
421 name: resolved?.originalName ?? fallbackName(uri, index, mimeType),
422 mimeType,
423 sizeBytes,
424 dataUrl,
425 // The share provider's file is temporary. A data-backed preview keeps
426 // the composer valid after its source file and App Group entry are gone.
427 previewUri: dataUrl,
428 });
429 } catch {
430 warnings.push(`Could not read '${fallbackName(uri, index, mimeType)}'.`);
431 } finally {
432 await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
433 }
434 }
435​
436 return {
437 schemaVersion: 1,
438 id: input.id,
439 createdAt: input.createdAt,
440 text: sharedText(input.payloads),
441 attachments,
442 warnings,
443 };
445​
446export function hasIncomingShareContent(draft: IncomingShareDraft): boolean {
447 return draft.text.trim().length > 0 || draft.attachments.length > 0;