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