The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import * as Dialog from "./Dialog"; |
| 3 | import { requireNativeModule } from "expo"; |
| 4 | import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; |
| 5 | import { AsyncResult } from "effect/reactivity"; |
| 6 | import { msg } from "gt-react-native"; |
| 7 | import { useEffect, useEffectEvent, useId } from "react"; |
| 8 | |
| 9 | import { m } from "../../i18n/messages"; |
| 10 | import { loadLocalAttachmentPreview } from "../../lib/localAttachmentPreview"; |
| 11 | import { usePreviewPresentation, videoPreviewKey } from "../../lib/previewPresentation"; |
| 12 | import { fullscreenVideoClosed, fullscreenVideoOpened } from "../../lib/videoAudioSession"; |
| 13 | import { mediaVideoPreviewUri, type VideoPreviewSource } from "../../lib/videoPreviewSource"; |
| 14 | import { refreshAssetUrl } from "../../state/assets"; |
| 15 | import { usePreparedConnection } from "../../state/session"; |
| 16 | import { |
| 17 | acquireAudioSession, |
| 18 | activateAudioSession, |
| 19 | isAudioSessionOwner, |
| 20 | releaseAudioSession, |
| 21 | } from "../../lib/audioSession"; |
| 22 | |
| 23 | export type { VideoPreviewSource } from "../../lib/videoPreviewSource"; |
| 24 | |
| 25 | const 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 | |
| 39 | function 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 (!current || !(await activateAudioSession(current, true)) || controller.signal.aborted) { |
| 112 | release(); |
| 113 | file?.dispose(); |
| 114 | if (!controller.signal.aborted) onRequestClose(); |
| 115 | return; |
| 116 | } |
| 117 | ready = true; |
| 118 | const presented = await settlePromise(() => |
| 119 | NativeControls.presentVideo(uri, name, source.sourceIdentifier ?? "", identifier), |
| 120 | ); |
| 121 | // Native completion follows dismissal, so local playback keeps its file lease. |
| 122 | file?.dispose(); |
| 123 | release(); |
| 124 | if (AsyncResult.isFailure(presented)) throw squashAtomCommandFailure(presented); |
| 125 | if (!controller.signal.aborted) onRequestClose(); |
| 126 | })().catch((error: unknown) => { |
| 127 | release(); |
| 128 | if (controller.signal.aborted) return; |
| 129 | // AVKit gives no retry, so re-mint now; the minted URL may already be unusable. |
| 130 | if (ready) reauthorize(); |
| 131 | Dialog.alert( |
| 132 | m(msg("Could not open video")), |
| 133 | ready |
| 134 | ? m( |
| 135 | msg( |
| 136 | "This video couldn't be loaded or played. Check the connection, or touch and hold the video to save or share the original.", |
| 137 | ), |
| 138 | ) |
| 139 | : error instanceof Error |
| 140 | ? (errorDisplayMessage(error, m) ?? error.message) |
| 141 | : m(msg("Could not load this video.")), |
| 142 | ); |
| 143 | onRequestClose(); |
| 144 | }); |
| 145 | return () => { |
| 146 | controller.abort(); |
| 147 | fullscreenVideoClosed(); |
| 148 | subscription.remove(); |
| 149 | release(); |
| 150 | void NativeControls.dismissVideo(identifier).catch(() => undefined); |
| 151 | }; |
| 152 | }, [localAttachment, name, source.sourceIdentifier, identifier]); |
| 153 | |
| 154 | return null; |
| 155 | } |
| 156 | |
| 157 | export function VideoPreviewModal(props: { |
| 158 | readonly source: VideoPreviewSource | null; |
| 159 | readonly onRequestClose: () => void; |
| 160 | }) { |
| 161 | usePreviewPresentation( |
| 162 | props.source === null ? null : videoPreviewKey(props.source), |
| 163 | props.onRequestClose, |
| 164 | ); |
| 165 | if (!props.source) return null; |
| 166 | return <NativeVideoPreview source={props.source} onRequestClose={props.onRequestClose} />; |
| 167 | } |