Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import Constants from "expo-constants";
3import * as Crypto from "expo-crypto";
4import { PROVIDER_SEND_TURN_MAX_FILE_BYTES } from "@t3tools/contracts";
5import {
6 clearSharedPayloads,
7 getResolvedSharedPayloadsAsync,
8 getSharedPayloads,
9 type ResolvedSharePayload,
10 type SharePayload,
11} from "expo-sharing";
12import React, { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
13import { AppState, Platform } from "react-native";
14
15import {
16 buildIncomingShareDraft,
17 isShareFileUriUnderOwnedRoots,
18 type IncomingShareDestination,
19 type IncomingShareDraft,
20} from "./incoming-share-model";
21import { createIncomingSharePayloadReader } from "./incoming-share-native";
22import { IncomingShareInbox } from "./incoming-share-inbox";
23import { persistComposerAttachmentFile } from "../../lib/composerImages";
24import {
25 loadIncomingShareDrafts,
26 removeIncomingShareDraft,
27 writeIncomingShareDraft,
28} from "./incoming-share-storage";
29
30type IncomingShareContextValue = {
31 readonly pendingShare: IncomingShareDraft | null;
32 readonly isLoading: boolean;
33 readonly error: Error | null;
34 readonly getShare: (shareId: string) => IncomingShareDraft | null;
35 readonly reserveShare: (shareId: string, destination: IncomingShareDestination) => Promise<void>;
36 readonly releaseShareReservation: (
37 shareId: string,
38 expectedDestination: IncomingShareDestination,
39 ) => Promise<void>;
40 readonly consumeShare: (shareId: string) => Promise<void>;
41 readonly refresh: () => Promise<void>;
42};
43
44const IncomingShareContext = React.createContext<IncomingShareContextValue | null>(null);
45
46function receiveSharingEnabled(): boolean {
47 if (Platform.OS === "android") {
48 return true;
49 }
50 if (Platform.OS !== "ios") {
51 return false;
52 }
53 return Constants.expoConfig?.extra?.iosPersonalTeamBuild !== true;
54}
55
56const getIncomingSharePayloads = createIncomingSharePayloadReader({
57 platform: Platform.OS,
58 readPayloads: getSharedPayloads,
59});
60
61async function resolvedPayloadsForFiles(): Promise<ReadonlyArray<ResolvedSharePayload>> {
62 try {
63 return await getResolvedSharedPayloadsAsync();
64 } catch (error) {
65 // Raw iOS copied file URLs remain usable; Android's File API can read content URIs when resolution fails.
66 console.warn("[incoming-share] could not resolve shared file metadata", error);
67 return [];
68 }
69}
70
71async function incomingShareIdForPayloads(payloads: ReadonlyArray<SharePayload>): Promise<string> {
72 const fingerprint = JSON.stringify(
73 payloads.map((payload) => ({
74 shareType: payload.shareType,
75 mimeType: payload.mimeType ?? null,
76 value: payload.value,
77 })),
78 );
79 const digest = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, fingerprint);
80 return `share-${digest}`;
81}
82
83async function readBase64(uri: string): Promise<string> {
84 const { File } = await import("expo-file-system");
85 return new File(uri).base64();
86}
87
88async function readFileSize(uri: string): Promise<number | null> {
89 const { File } = await import("expo-file-system");
90 return new File(uri).size ?? null;
91}
92
93async function removeOwnedFile(uri: string): Promise<void> {
94 if (!uri.startsWith("file:")) {
95 return;
96 }
97 try {
98 const { File, Paths } = await import("expo-file-system");
99 // Delete only app-owned files; iOS open-in-place shares can reference the sender's original.
100 const ownedRootUris = [
101 Paths.document.uri,
102 Paths.cache.uri,
103 ...Object.values(Paths.appleSharedContainers ?? {}).map((directory) => directory.uri),
104 ];
105 if (!isShareFileUriUnderOwnedRoots(uri, ownedRootUris)) {
106 return;
107 }
108 const file = new File(uri);
109 if (file.exists) {
110 file.delete();
111 }
112 } catch (error) {
113 console.warn("[incoming-share] could not remove temporary shared file", error);
114 }
115}
116
117async function removeReplayedPayloadFiles(payloads: ReadonlyArray<SharePayload>): Promise<void> {
118 const uris = new Set<string>();
119 for (const payload of payloads) {
120 if (["image", "file", "audio", "video"].includes(payload.shareType)) {
121 uris.add(payload.value);
122 }
123 }
124 if (uris.size === 0) {
125 return;
126 }
127 const resolvedPayloads = payloads.some((payload) =>
128 ["file", "audio", "video"].includes(payload.shareType),
129 )
130 ? []
131 : await resolvedPayloadsForFiles();
132 for (const payload of resolvedPayloads) {
133 if (["image", "file", "audio", "video"].includes(payload.shareType) && payload.contentUri) {
134 uris.add(payload.contentUri);
135 }
136 }
137 await Promise.all([...uris].map(removeOwnedFile));
138}
139
140// Share the queue across remounts so lifecycle notifications cannot ingest one handoff twice.
141const incomingShareInbox = new IncomingShareInbox({
142 loadDrafts: loadIncomingShareDrafts,
143 writeDraft: writeIncomingShareDraft,
144 removeDraft: removeIncomingShareDraft,
145 getPayloads: getIncomingSharePayloads,
146 clearPayloads: clearSharedPayloads,
147 buildDraft: async ({ payloads, id, createdAt }) => {
148 const cleanupUris = new Set<string>();
149 const persistedUris = new Set<string>();
150 const hasGenericFilePayload = payloads.some((payload) =>
151 ["file", "audio", "video"].includes(payload.shareType),
152 );
153 const resolvedPayloads =
154 !hasGenericFilePayload && payloads.some((payload) => payload.shareType === "image")
155 ? await resolvedPayloadsForFiles()
156 : [];
157 const draft = await buildIncomingShareDraft({
158 payloads,
159 resolvedPayloads,
160 fileReader: {
161 readBase64,
162 persistFile: async (uri, name) => {
163 const persistedUri = await persistComposerAttachmentFile(
164 uri,
165 name,
166 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
167 );
168 persistedUris.add(persistedUri);
169 return persistedUri;
170 },
171 readSize: readFileSize,
172 removeOwnedFile: (uri) => {
173 cleanupUris.add(uri);
174 },
175 },
176 id,
177 createdAt,
178 });
179 return {
180 draft,
181 cleanup: async () => {
182 await Promise.all([...cleanupUris].map(removeOwnedFile));
183 },
184 rollback: async () => {
185 await Promise.all([...persistedUris].map(removeOwnedFile));
186 },
187 };
188 },
189 cleanupReplayedPayloads: removeReplayedPayloadFiles,
190 idForPayloads: incomingShareIdForPayloads,
191 now: () => new Date().toISOString(),
192 onClearError: (error) => {
193 console.warn("[incoming-share] could not acknowledge native payload", error);
194 },
195 onCleanupError: (error) => {
196 console.warn("[incoming-share] could not remove temporary shared file", error);
197 },
198});
199
200export function IncomingShareProvider(props: React.PropsWithChildren) {
201 const enabled = receiveSharingEnabled();
202 const [drafts, setDrafts] = useState<ReadonlyArray<IncomingShareDraft>>([]);
203 const [isLoading, setIsLoading] = useState(true);
204 const [error, setError] = useState<Error | null>(null);
205 const refreshPromiseRef = useRef<Promise<void> | null>(null);
206 const mountedRef = useRef(false);
207
208 useEffect(() => {
209 mountedRef.current = true;
210 return () => {
211 mountedRef.current = false;
212 };
213 }, []);
214
215 const refresh = useCallback(async () => {
216 if (refreshPromiseRef.current) {
217 return refreshPromiseRef.current;
218 }
219
220 const operation = (async () => {
221 try {
222 const snapshot = await incomingShareInbox.refresh({ ingestNative: enabled });
223 if (mountedRef.current) {
224 setDrafts(snapshot);
225 setError(null);
226 }
227 } catch (cause) {
228 const persisted = await incomingShareInbox
229 .refresh({ ingestNative: false })
230 .catch(() => null);
231 if (mountedRef.current) {
232 if (persisted) {
233 setDrafts(persisted);
234 }
235 setError(cause instanceof Error ? cause : new Error("Could not import shared content."));
236 }
237 }
238 })().finally(() => {
239 refreshPromiseRef.current = null;
240 });
241
242 refreshPromiseRef.current = operation;
243 return operation;
244 }, [enabled]);
245
246 useEffect(() => {
247 void refresh().finally(() => {
248 if (mountedRef.current) {
249 setIsLoading(false);
250 }
251 });
252 }, [refresh]);
253
254 const refreshOnAppActive = useEffectEvent(() => {
255 void refresh();
256 });
257
258 useEffect(() => {
259 if (!enabled) {
260 return;
261 }
262 const subscription = AppState.addEventListener("change", (state) => {
263 if (state === "active") {
264 refreshOnAppActive();
265 }
266 });
267 return () => subscription.remove();
268 }, [enabled]);
269
270 useEffect(() => {
271 if (!error) {
272 return;
273 }
274 Dialog.alert("Could not import shared content", error.message, [
275 { text: "Dismiss", style: "cancel", onPress: () => setError(null) },
276 {
277 text: "Retry",
278 onPress: () => {
279 setError(null);
280 void refresh();
281 },
282 },
283 ]);
284 }, [error, refresh]);
285
286 const consumeShare = useCallback(async (shareId: string) => {
287 const snapshot = await incomingShareInbox.consume(shareId);
288 if (mountedRef.current) {
289 setDrafts(snapshot);
290 }
291 }, []);
292 const reserveShare = useCallback(
293 async (shareId: string, destination: IncomingShareDestination) => {
294 const snapshot = await incomingShareInbox.reserve(shareId, destination);
295 if (mountedRef.current) {
296 setDrafts(snapshot);
297 }
298 },
299 [],
300 );
301 const releaseShareReservation = useCallback(
302 async (shareId: string, expectedDestination: IncomingShareDestination) => {
303 const snapshot = await incomingShareInbox.releaseReservation(shareId, expectedDestination);
304 if (mountedRef.current) {
305 setDrafts(snapshot);
306 }
307 },
308 [],
309 );
310 const getShare = useCallback(
311 (shareId: string) => drafts.find((draft) => draft.id === shareId) ?? null,
312 [drafts],
313 );
314
315 const value = useMemo<IncomingShareContextValue>(
316 () => ({
317 pendingShare: drafts[0] ?? null,
318 isLoading,
319 error,
320 getShare,
321 releaseShareReservation,
322 reserveShare,
323 consumeShare,
324 refresh,
325 }),
326 [
327 consumeShare,
328 drafts,
329 error,
330 getShare,
331 isLoading,
332 refresh,
333 releaseShareReservation,
334 reserveShare,
335 ],
336 );
337
338 return (
339 <IncomingShareContext.Provider value={value}>{props.children}</IncomingShareContext.Provider>
340 );
341}
342
343export function useIncomingShare(): IncomingShareContextValue {
344 const value = React.use(IncomingShareContext);
345 if (value === null) {
346 throw new Error("useIncomingShare must be used within IncomingShareProvider.");
347 }
348 return value;
349}