Open History to see the last commit
1import * as Dialog from "./ui/Dialog";
2import { useIsFocused } from "@react-navigation/native";
3import { requireNativeModule } from "expo";
4import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5import { AsyncResult } from "effect/reactivity";
6import { useEffect, useEffectEvent, useId, useState } from "react";
7import { Keyboard } from "react-native";
8
9import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
10import { fullscreenVideoClosed, fullscreenVideoOpened } from "../lib/videoAudioSession";
11import { mediaVideoPreviewUri, type VideoPreviewSource } from "../lib/videoPreviewSource";
12import { useAssetUrlState, useRefreshAssetUrl } from "../state/assets";
13import { usePreparedConnection } from "../state/session";
14import {
15 acquireAudioSession,
16 activateAudioSession,
17 isAudioSessionOwner,
18 releaseAudioSession,
19} from "../lib/audioSession";
20
21export type { VideoPreviewSource } from "../lib/videoPreviewSource";
22
23const NativeControls = requireNativeModule<{
24 presentVideo(
25 uri: string,
26 title: string,
27 sourceIdentifier: string,
28 identifier: string,
29 ): Promise<void>;
30 dismissVideo(identifier: string): Promise<void>;
31 addListener(
32 event: "videoPlaybackChange",
33 listener: (event: { identifier: string; isPlaying: boolean }) => void,
34 ): { remove(): void };
35}>("T3NativeControls");
36
37function NativeVideoPreview(props: {
38 readonly source: VideoPreviewSource;
39 readonly onRequestClose: () => void;
40}) {
41 const { source } = props;
42 const localAttachment = source.type === "local" ? source.attachment : null;
43 const identifier = useId();
44 const onRequestClose = useEffectEvent(props.onRequestClose);
45 const environmentId =
46 source.type === "media" && "environmentId" in source ? source.environmentId : null;
47 const resource = source.type === "media" && "resource" in source ? source.resource : null;
48 const preparedConnection = usePreparedConnection(environmentId);
49 const assetUrl = useAssetUrlState(environmentId, resource);
50 const refreshAssetUrl = useEffectEvent(useRefreshAssetUrl(environmentId, resource));
51 const name = source.type === "media" ? source.name : source.attachment.name;
52 // The first minted URL is kept so a background refresh does not restart playback.
53 const resolvedUrl =
54 source.type === "media"
55 ? mediaVideoPreviewUri(source, assetUrl._tag === "Success" ? assetUrl.url : null)
56 : null;
57 const [playbackUrl, setPlaybackUrl] = useState<string | null>(resolvedUrl);
58 const loadError =
59 resource !== null && playbackUrl === null
60 ? preparedConnection._tag === "None"
61 ? "Reconnect to this environment and open the video again."
62 : assetUrl._tag === "Failure"
63 ? "Could not load this video. Check the connection and try again."
64 : null
65 : null;
66
67 useEffect(() => Keyboard.dismiss(), []);
68 useEffect(() => {
69 fullscreenVideoOpened();
70 return () => fullscreenVideoClosed();
71 }, []);
72 useEffect(() => {
73 if (playbackUrl === null && resolvedUrl !== null) setPlaybackUrl(resolvedUrl);
74 }, [playbackUrl, resolvedUrl]);
75 useEffect(() => {
76 if (!loadError) return;
77 Dialog.alert("Could not open video", loadError);
78 onRequestClose();
79 }, [loadError]);
80
81 useEffect(() => {
82 if (localAttachment === null && playbackUrl === null) return;
83 const controller = new AbortController();
84 let token: ReturnType<typeof acquireAudioSession> | null = null;
85 const release = () => {
86 if (token) void releaseAudioSession(token).catch(() => {});
87 token = null;
88 };
89 const acquire = () => {
90 const next = acquireAudioSession("playback", () => {
91 release();
92 void NativeControls.dismissVideo(identifier).catch(() => {});
93 });
94 if (!isAudioSessionOwner(next)) {
95 void NativeControls.dismissVideo(identifier).catch(() => {});
96 return null;
97 }
98 token = next;
99 return next;
100 };
101 const subscription = NativeControls.addListener("videoPlaybackChange", (event) => {
102 if (event.identifier !== identifier || controller.signal.aborted) return;
103 if (event.isPlaying) {
104 if (!token) acquire();
105 } else release();
106 });
107 let ready = false;
108 void (async () => {
109 const file =
110 localAttachment !== null
111 ? await loadLocalAttachmentPreview(localAttachment, controller.signal)
112 : null;
113 if (localAttachment !== null && !file) return;
114 if (controller.signal.aborted) {
115 file?.dispose();
116 return;
117 }
118 const current = acquire();
119 if (!current || !(await activateAudioSession(current, true)) || controller.signal.aborted) {
120 release();
121 file?.dispose();
122 if (!controller.signal.aborted) onRequestClose();
123 return;
124 }
125 ready = true;
126 const presented = await settlePromise(() =>
127 NativeControls.presentVideo(
128 file?.uri ?? playbackUrl!,
129 name,
130 source.sourceIdentifier ?? "",
131 identifier,
132 ),
133 );
134 // Native completion follows dismissal, so local playback keeps its file lease.
135 file?.dispose();
136 release();
137 if (AsyncResult.isFailure(presented)) throw squashAtomCommandFailure(presented);
138 if (!controller.signal.aborted) onRequestClose();
139 })().catch((error: unknown) => {
140 release();
141 if (controller.signal.aborted) return;
142 // AVKit gives no retry, so re-mint now; the cached URL may simply have expired.
143 if (ready) void refreshAssetUrl();
144 Dialog.alert(
145 "Could not open video",
146 ready
147 ? "This video couldn't be loaded or played. Check the connection, or touch and hold the video to save or share the original."
148 : error instanceof Error
149 ? error.message
150 : "Could not load this video.",
151 );
152 onRequestClose();
153 });
154 return () => {
155 controller.abort();
156 subscription.remove();
157 release();
158 void NativeControls.dismissVideo(identifier).catch(() => undefined);
159 };
160 }, [localAttachment, name, source.sourceIdentifier, playbackUrl, identifier]);
161
162 return null;
163}
164
165export function VideoPreviewModal(props: {
166 readonly source: VideoPreviewSource | null;
167 readonly onRequestClose: () => void;
168}) {
169 const isFocused = useIsFocused();
170 const hasSource = props.source !== null;
171 const onRequestClose = useEffectEvent(props.onRequestClose);
172 useEffect(() => {
173 if (!isFocused && hasSource) onRequestClose();
174 }, [isFocused, hasSource]);
175
176 if (!props.source || !isFocused) return null;
177 return <NativeVideoPreview source={props.source} onRequestClose={props.onRequestClose} />;
178}