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

incoming-share-model.ts

448 lines15.7 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 type { DraftComposerAttachment } from "../../lib/composerImages";
16import { estimateBase64ByteSize } from "../../lib/base64";
17​
18export interface IncomingShareDraft {
19 readonly schemaVersion: 1;
20 readonly id: string;
21 readonly createdAt: string;
22 readonly destination?: IncomingShareDestination;
23 readonly text: string;
24 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
25 readonly warnings: ReadonlyArray<string>;
27​
28export interface IncomingShareDestination {
29 readonly environmentId: string;
30 readonly projectId: string;
32​
33const IncomingShareDestinationSchema = Schema.Struct({
34 environmentId: Schema.String,
35 projectId: Schema.String,
36});
37​
38export const IncomingShareDraftSchema = Schema.Struct({
39 schemaVersion: Schema.Literal(1),
40 id: Schema.String,
41 createdAt: Schema.String,
42 destination: Schema.optional(IncomingShareDestinationSchema),
43 text: Schema.String,
44 attachments: Schema.Array(DraftComposerAttachmentSchema),
45 warnings: Schema.Array(Schema.String),
46});
47​
48const decodeIncomingShareDraftSync = Schema.decodeUnknownSync(IncomingShareDraftSchema);
49​
50export function decodeIncomingShareDraft(value: unknown): IncomingShareDraft {
51 return decodeIncomingShareDraftSync(value);
53​
54/**
55 * `file:` path with the iOS `/private` prefix stripped, so URIs that reach the
56 * same file through the `/var` symlink and through `/private/var` compare
57 * equal. Null for anything that is not a `file:` URI.
58 */
59function normalizedFileUriPath(uri: string): string | null {
60 try {
61 const url = new URL(uri);
62 if (url.protocol !== "file:") {
63 return null;
64 }
65 const path = decodeURIComponent(url.pathname);
66 // URL parsing collapses literal ".." segments, but an encoded separator
67 // survives it: "..%2F.." decodes to "../..", which the filesystem would
68 // resolve outside the root the lexical containment check accepted.
69 if (path.split("/").includes("..")) {
70 return null;
71 }
72 return path.startsWith("/private/var/") ? path.slice("/private".length) : path;
73 } catch {
74 return null;
75 }
77​
78/**
79 * Whether a shared `file:` URI points strictly inside one of the directories
80 * this app owns (its sandbox and its share-extension App Group container).
81 * Share cleanup must never delete anything else: an iOS open-in-place share
82 * hands over the sender's own file URL, and deleting it destroys the user's
83 * document.
84 */
85export function isShareFileUriUnderOwnedRoots(
86 uri: string,
87 ownedRootUris: ReadonlyArray<string>,
88): boolean {
89 const path = normalizedFileUriPath(uri);
90 if (path === null) {
91 return false;
92 }
93 return ownedRootUris.some((rootUri) => {
94 const rootPath = normalizedFileUriPath(rootUri);
95 if (rootPath === null) {
96 return false;
97 }
98 const root = rootPath.endsWith("/") ? rootPath : `${rootPath}/`;
99 return path.startsWith(root) && path.length > root.length;
100 });
102​
103export interface IncomingShareFileReader {
104 readonly readBase64: (uri: string) => Promise<string>;
105 readonly removeOwnedFile: (uri: string) => Promise<void> | void;
106 readonly persistFile?: (uri: string, name: string) => Promise<string>;
107 readonly readSize?: (uri: string) => Promise<number | null>;
109​
110/** Apply the destination server's file support after the user chooses a project. */
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 // Temporary-file cleanup is best-effort and must never discard content
230 // that was successfully converted into a durable composer attachment.
231 }
232 }
234​
235function fallbackName(uri: string, index: number, mimeType: string): string {
236 try {
237 const pathName = new URL(uri).pathname.split("/").findLast((segment) => segment.length > 0);
238 if (pathName) {
239 return decodeURIComponent(pathName);
240 }
241 } catch {
242 // Fall through to a deterministic attachment name.
243 }
244 const family = mimeType.split("/")[0]?.toLowerCase();
245 const kind = family === "image" || family === "audio" || family === "video" ? family : "file";
246 const extension =
247 mimeType.split("/")[1]?.replace(/[^a-z0-9.+-]/gi, "") || (kind === "image" ? "png" : "bin");
248 return `shared-${kind}-${index + 1}.${extension}`;
250​
251export async function buildIncomingShareDraft(input: {
252 readonly payloads: ReadonlyArray<SharePayload>;
253 readonly resolvedPayloads: ReadonlyArray<ResolvedSharePayload>;
254 readonly fileReader: IncomingShareFileReader;
255 readonly id: string;
256 readonly createdAt: string;
257}): Promise<IncomingShareDraft> {
258 const attachments: DraftComposerAttachment[] = [];
259 const warnings: string[] = [];
260 const consumedResolvedPayloadIndexes = new Set<number>();
261 let warnedAttachmentLimit = false;
262​
263 for (const [index, payload] of input.payloads.entries()) {
264 if (
265 payload.shareType !== "image" &&
266 payload.shareType !== "file" &&
267 payload.shareType !== "audio" &&
268 payload.shareType !== "video"
269 ) {
270 continue;
271 }
272 const resolved = resolvedImageFor(
273 payload,
274 index,
275 input.resolvedPayloads,
276 consumedResolvedPayloadIndexes,
277 );
278 const uri = resolved?.contentUri ?? payload.value;
279 if (attachments.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
280 if (!warnedAttachmentLimit) {
281 warnings.push(
282 `Only the first ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} shared ${payload.shareType === "image" ? "images" : "files"} were attached.`,
283 );
284 warnedAttachmentLimit = true;
285 }
286 await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
287 continue;
288 }
289​
290 const mimeType = (
291 resolved?.contentMimeType ??
292 payload.mimeType ??
293 (payload.shareType === "image" ? "image/png" : "application/octet-stream")
294 ).toLowerCase();
295 if (payload.shareType !== "image") {
296 // The patched native module never emits a blank display name, but keep
297 // the guard: an empty name would fail the attachment name contract.
298 const sharedFileName =
299 typeof payload.originalName === "string" && payload.originalName.trim().length > 0
300 ? payload.originalName
301 : undefined;
302 const name = resolved?.originalName ?? sharedFileName ?? fallbackName(uri, index, mimeType);
303 if (!uri) {
304 warnings.push("One shared file could not be read.");
305 continue;
306 }
307 let persistedFileUri: string | undefined;
308 let retainedFileUri: string | undefined;
309 try {
310 let sizeBytes = resolved?.contentSize ?? (await input.fileReader.readSize?.(uri)) ?? null;
311 if (
312 (sizeBytes === null || (sizeBytes === 0 && uri.startsWith("content:"))) &&
313 input.fileReader.persistFile
314 ) {
315 persistedFileUri = await input.fileReader.persistFile(uri, name);
316 sizeBytes = (await input.fileReader.readSize?.(persistedFileUri)) ?? null;
317 }
318 if (sizeBytes === null) {
319 warnings.push(`The size of '${name}' could not be determined.`);
320 if (persistedFileUri) {
321 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
322 }
323 continue;
324 }
325 if (sizeBytes <= 0) {
326 warnings.push(`'${name}' is empty or could not be read.`);
327 if (persistedFileUri) {
328 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
329 }
330 continue;
331 }
332 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
333 warnings.push(fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_FILE_BYTES));
334 if (persistedFileUri) {
335 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
336 }
337 continue;
338 }
339 if (persistedFileUri === undefined && input.fileReader.persistFile) {
340 persistedFileUri = await input.fileReader.persistFile(uri, name);
341 // An Android content: source can misreport its size while the
342 // stored copy is what uploads, so the copy's measured size is what
343 // the attachment must record. A measured zero means the copy holds
344 // no bytes: reject it, whatever the source claimed.
345 const storedSize = (await input.fileReader.readSize?.(persistedFileUri)) ?? null;
346 if (storedSize !== null) {
347 sizeBytes = storedSize;
348 }
349 if (sizeBytes <= 0) {
350 warnings.push(`'${name}' is empty or could not be read.`);
351 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
352 continue;
353 }
354 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
355 warnings.push(fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_FILE_BYTES));
356 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
357 continue;
358 }
359 }
360 attachments.push({
361 id: `${input.id}:file:${index}`,
362 type: "file",
363 name,
364 mimeType,
365 sizeBytes,
366 fileUri: persistedFileUri ?? uri,
367 });
368 retainedFileUri = persistedFileUri ?? uri;
369 } catch (error) {
370 warnings.push(error instanceof Error ? error.message : `Could not read '${name}'.`);
371 // A copy persisted before the failure has no attachment referencing
372 // it; release it or it leaks in the app's attachment directory.
373 if (persistedFileUri !== undefined) {
374 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
375 }
376 } finally {
377 await releaseOwnedFiles(
378 input.fileReader,
379 [uri, payload.value].filter((candidate) => candidate !== retainedFileUri),
380 );
381 }
382 continue;
383 }
384 if (!uri || !mimeType.startsWith("image/")) {
385 warnings.push("One shared item was not a supported image.");
386 await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
387 continue;
388 }
389 if (!isProviderSendTurnSupportedImageMimeType(mimeType)) {
390 warnings.push(
391 `'${resolved?.originalName ?? fallbackName(uri, index, mimeType)}' is not a supported image type.`,
392 );
393 await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
394 continue;
395 }
396 if (
397 resolved?.contentSize !== null &&
398 resolved?.contentSize !== undefined &&
399 resolved.contentSize > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
400 ) {
401 warnings.push(
402 `'${resolved.originalName ?? fallbackName(uri, index, mimeType)}' exceeds the 10 MB attachment limit.`,
403 );
404 await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
405 continue;
406 }
407​
408 try {
409 const base64 = await input.fileReader.readBase64(uri);
410 const sizeBytes = 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;