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