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

IncomingShareProvider.tsx

357 lines10.7 KB

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;
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 // iOS already gives the containing app a copied file:// URL, so raw
66 // payloads remain usable. Android normally resolves content:// into a
67 // private cache file; its modern File API can still read the raw URI when
68 // resolution fails.
69 console.warn("[incoming-share] could not resolve shared file metadata", error);
70 return [];
71 }
73​
74async function incomingShareIdForPayloads(payloads: ReadonlyArray<SharePayload>): Promise<string> {
75 const fingerprint = JSON.stringify(
76 payloads.map((payload) => ({
77 shareType: payload.shareType,
78 mimeType: payload.mimeType ?? null,
79 value: payload.value,
80 })),
81 );
82 const digest = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, fingerprint);
83 return `share-${digest}`;
85​
86async function readBase64(uri: string): Promise<string> {
87 const { File } = await import("expo-file-system");
88 return new File(uri).base64();
90​
91async function readFileSize(uri: string): Promise<number | null> {
92 const { File } = await import("expo-file-system");
93 return new File(uri).size ?? null;
95​
96async function removeOwnedFile(uri: string): Promise<void> {
97 if (!uri.startsWith("file:")) {
98 return;
99 }
100 try {
101 const { File, Paths } = await import("expo-file-system");
102 // Only delete files in directories this app owns: its documents and cache
103 // sandbox and its share-extension App Group container. An iOS
104 // open-in-place share points at the sender's own storage; deleting that
105 // URI would destroy the user's document.
106 const ownedRootUris = [
107 Paths.document.uri,
108 Paths.cache.uri,
109 ...Object.values(Paths.appleSharedContainers ?? {}).map((directory) => directory.uri),
110 ];
111 if (!isShareFileUriUnderOwnedRoots(uri, ownedRootUris)) {
112 return;
113 }
114 const file = new File(uri);
115 if (file.exists) {
116 file.delete();
117 }
118 } catch (error) {
119 console.warn("[incoming-share] could not remove temporary shared file", error);
120 }
122​
123async function removeReplayedPayloadFiles(payloads: ReadonlyArray<SharePayload>): Promise<void> {
124 const uris = new Set<string>();
125 for (const payload of payloads) {
126 if (["image", "file", "audio", "video"].includes(payload.shareType)) {
127 uris.add(payload.value);
128 }
129 }
130 if (uris.size === 0) {
131 return;
132 }
133 const resolvedPayloads = payloads.some((payload) =>
134 ["file", "audio", "video"].includes(payload.shareType),
135 )
136 ? []
137 : await resolvedPayloadsForFiles();
138 for (const payload of resolvedPayloads) {
139 if (["image", "file", "audio", "video"].includes(payload.shareType) && payload.contentUri) {
140 uris.add(payload.contentUri);
141 }
142 }
143 await Promise.all([...uris].map(removeOwnedFile));
145​
146// Keep one operation queue across provider remounts (including development
147// Strict Mode remounts) so two app lifecycle notifications cannot ingest the
148// same native handoff independently.
149const incomingShareInbox = new IncomingShareInbox({
150 loadDrafts: loadIncomingShareDrafts,
151 writeDraft: writeIncomingShareDraft,
152 removeDraft: removeIncomingShareDraft,
153 getPayloads: getIncomingSharePayloads,
154 clearPayloads: clearSharedPayloads,
155 buildDraft: async ({ payloads, id, createdAt }) => {
156 const cleanupUris = new Set<string>();
157 const persistedUris = new Set<string>();
158 const hasGenericFilePayload = payloads.some((payload) =>
159 ["file", "audio", "video"].includes(payload.shareType),
160 );
161 const resolvedPayloads =
162 !hasGenericFilePayload && payloads.some((payload) => payload.shareType === "image")
163 ? await resolvedPayloadsForFiles()
164 : [];
165 const draft = await buildIncomingShareDraft({
166 payloads,
167 resolvedPayloads,
168 fileReader: {
169 readBase64,
170 persistFile: async (uri, name) => {
171 const persistedUri = await persistComposerAttachmentFile(
172 uri,
173 name,
174 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
175 );
176 persistedUris.add(persistedUri);
177 return persistedUri;
178 },
179 readSize: readFileSize,
180 removeOwnedFile: (uri) => {
181 cleanupUris.add(uri);
182 },
183 },
184 id,
185 createdAt,
186 });
187 return {
188 draft,
189 cleanup: async () => {
190 await Promise.all([...cleanupUris].map(removeOwnedFile));
191 },
192 rollback: async () => {
193 await Promise.all([...persistedUris].map(removeOwnedFile));
194 },
195 };
196 },
197 cleanupReplayedPayloads: removeReplayedPayloadFiles,
198 idForPayloads: incomingShareIdForPayloads,
199 now: () => new Date().toISOString(),
200 onClearError: (error) => {
201 console.warn("[incoming-share] could not acknowledge native payload", error);
202 },
203 onCleanupError: (error) => {
204 console.warn("[incoming-share] could not remove temporary shared file", error);
205 },
206});
207​
208export function IncomingShareProvider(props: React.PropsWithChildren) {
209 const enabled = receiveSharingEnabled();
210 const [drafts, setDrafts] = useState<ReadonlyArray<IncomingShareDraft>>([]);
211 const [isLoading, setIsLoading] = useState(true);
212 const [error, setError] = useState<Error | null>(null);
213 const refreshPromiseRef = useRef<Promise<void> | null>(null);
214 const mountedRef = useRef(false);
215​
216 useEffect(() => {
217 mountedRef.current = true;
218 return () => {
219 mountedRef.current = false;
220 };
221 }, []);
222​
223 const refresh = useCallback(async () => {
224 if (refreshPromiseRef.current) {
225 return refreshPromiseRef.current;
226 }
227​
228 const operation = (async () => {
229 try {
230 const snapshot = await incomingShareInbox.refresh({ ingestNative: enabled });
231 if (mountedRef.current) {
232 setDrafts(snapshot);
233 setError(null);
234 }
235 } catch (cause) {
236 const persisted = await incomingShareInbox
237 .refresh({ ingestNative: false })
238 .catch(() => null);
239 if (mountedRef.current) {
240 if (persisted) {
241 setDrafts(persisted);
242 }
243 setError(cause instanceof Error ? cause : new Error("Could not import shared content."));
244 }
245 }
246 })().finally(() => {
247 refreshPromiseRef.current = null;
248 });
249​
250 refreshPromiseRef.current = operation;
251 return operation;
252 }, [enabled]);
253​
254 useEffect(() => {
255 void refresh().finally(() => {
256 if (mountedRef.current) {
257 setIsLoading(false);
258 }
259 });
260 }, [refresh]);
261​
262 const refreshOnAppActive = useEffectEvent(() => {
263 void refresh();
264 });
265​
266 useEffect(() => {
267 if (!enabled) {
268 return;
269 }
270 const subscription = AppState.addEventListener("change", (state) => {
271 if (state === "active") {
272 refreshOnAppActive();
273 }
274 });
275 return () => subscription.remove();
276 }, [enabled]);
277​
278 useEffect(() => {
279 if (!error) {
280 return;
281 }
282 Dialog.alert("Could not import shared content", error.message, [
283 { text: "Dismiss", style: "cancel", onPress: () => setError(null) },
284 {
285 text: "Retry",
286 onPress: () => {
287 setError(null);
288 void refresh();
289 },
290 },
291 ]);
292 }, [error, refresh]);
293​
294 const consumeShare = useCallback(async (shareId: string) => {
295 const snapshot = await incomingShareInbox.consume(shareId);
296 if (mountedRef.current) {
297 setDrafts(snapshot);
298 }
299 }, []);
300 const reserveShare = useCallback(
301 async (shareId: string, destination: IncomingShareDestination) => {
302 const snapshot = await incomingShareInbox.reserve(shareId, destination);
303 if (mountedRef.current) {
304 setDrafts(snapshot);
305 }
306 },
307 [],
308 );
309 const releaseShareReservation = useCallback(
310 async (shareId: string, expectedDestination: IncomingShareDestination) => {
311 const snapshot = await incomingShareInbox.releaseReservation(shareId, expectedDestination);
312 if (mountedRef.current) {
313 setDrafts(snapshot);
314 }
315 },
316 [],
317 );
318 const getShare = useCallback(
319 (shareId: string) => drafts.find((draft) => draft.id === shareId) ?? null,
320 [drafts],
321 );
322​
323 const value = useMemo<IncomingShareContextValue>(
324 () => ({
325 pendingShare: drafts[0] ?? null,
326 isLoading,
327 error,
328 getShare,
329 releaseShareReservation,
330 reserveShare,
331 consumeShare,
332 refresh,
333 }),
334 [
335 consumeShare,
336 drafts,
337 error,
338 getShare,
339 isLoading,
340 refresh,
341 releaseShareReservation,
342 reserveShare,
343 ],
344 );
345​
346 return (
347 <IncomingShareContext.Provider value={value}>{props.children}</IncomingShareContext.Provider>
348 );
350​
351export function useIncomingShare(): IncomingShareContextValue {
352 const value = React.use(IncomingShareContext);
353 if (value === null) {
354 throw new Error("useIncomingShare must be used within IncomingShareProvider.");
355 }
356 return value;