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