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