-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathvideo-player.tsx
More file actions
248 lines (223 loc) · 7.78 KB
/
Copy pathvideo-player.tsx
File metadata and controls
248 lines (223 loc) · 7.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { Text } from "@/components/ui/text";
import { useRefToLatest } from "@/components/use-ref-to-latest";
import { useAuth } from "@/lib/auth-context";
import { updateMediaLocation } from "@/lib/media-location";
import { requestAPI } from "@/lib/request";
import { useQueryClient } from "@tanstack/react-query";
import * as Sentry from "@sentry/react-native";
import { Stack, useLocalSearchParams } from "expo-router";
import { useVideoPlayer, VideoView, type VideoPlayerStatus } from "expo-video";
import { useEffect, useRef, useState } from "react";
import { AppState, type AppStateStatus, StyleSheet, View } from "react-native";
const fetchStreamingPlaylistUrl = async (streamingUrl: string, accessToken: string): Promise<string> =>
(await requestAPI<{ playlist_url: string }>(streamingUrl, { accessToken })).playlist_url;
const isReleasedPlayerError = (error: unknown): boolean => {
const { code, message } = (error ?? {}) as { code?: string; message?: string };
if (code === "ERR_USING_RELEASED_SHARED_OBJECT" || code === "ERR_NATIVE_SHARED_OBJECT_NOT_FOUND") return true;
return /shared object that was already released|find the native shared object/i.test(message ?? "");
};
const withReleasedPlayerGuard = (operation: () => void) => {
try {
operation();
} catch (error) {
if (isReleasedPlayerError(error)) return;
throw error;
}
};
export default function VideoPlayerScreen() {
const { accessToken } = useAuth();
const { uri, streamingUrl, title, urlRedirectId, productFileId, purchaseId, initialPosition } = useLocalSearchParams<{
uri: string;
streamingUrl?: string;
title?: string;
urlRedirectId?: string;
productFileId?: string;
purchaseId?: string;
initialPosition?: string;
}>();
const queryClient = useQueryClient();
const [videoUrl, setVideoUrl] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [playbackError, setPlaybackError] = useState<string | null>(null);
const [currentPosition, setCurrentPosition] = useState(initialPosition ? Number(initialPosition) : 0);
const currentPositionRef = useRefToLatest(currentPosition);
useEffect(() => {
if (!accessToken) return;
const resolveVideoUrl = async () => {
setIsLoading(true);
try {
if (streamingUrl) {
const playlistUrl = await fetchStreamingPlaylistUrl(streamingUrl, accessToken);
setVideoUrl(playlistUrl);
} else {
setVideoUrl(uri);
}
} catch (error) {
console.warn("Failed to fetch streaming URL, falling back to direct URL:", error);
Sentry.captureException(error);
setVideoUrl(uri);
} finally {
setIsLoading(false);
}
};
resolveVideoUrl();
}, [accessToken, streamingUrl, uri]);
const player = useVideoPlayer(videoUrl, (player) => {
player.loop = false;
player.staysActiveInBackground = false;
if (initialPosition) {
player.currentTime = Number(initialPosition);
}
player.play();
});
const wasPlayingBeforeBackgroundRef = useRef(false);
const positionBeforeBackgroundRef = useRef<number | null>(null);
useEffect(() => {
const subscription = AppState.addEventListener("change", (nextState: AppStateStatus) => {
withReleasedPlayerGuard(() => {
if (nextState === "background" || nextState === "inactive") {
wasPlayingBeforeBackgroundRef.current = player.playing;
positionBeforeBackgroundRef.current = player.currentTime;
player.pause();
} else if (nextState === "active") {
const savedPosition = positionBeforeBackgroundRef.current;
if (savedPosition !== null && player.currentTime < savedPosition - 1) {
player.currentTime = savedPosition;
}
positionBeforeBackgroundRef.current = null;
if (wasPlayingBeforeBackgroundRef.current) {
player.play();
wasPlayingBeforeBackgroundRef.current = false;
}
}
});
});
return () => subscription.remove();
}, [player]);
useEffect(() => () => withReleasedPlayerGuard(() => player.pause()), [player]);
useEffect(() => {
const subscription = player.addListener(
"statusChange",
({ status, error }: { status: VideoPlayerStatus; error?: { message: string } }) => {
if (status === "error") {
const message = error?.message ?? "Unknown playback error";
setPlaybackError(message);
Sentry.captureMessage("Video playback failed", {
level: "error",
extra: {
message,
videoUrl,
sourceUri: uri,
streamingUrl,
urlRedirectId,
productFileId,
purchaseId,
},
});
} else if (status === "readyToPlay") {
setPlaybackError(null);
}
},
);
return () => subscription.remove();
}, [player, videoUrl, uri, streamingUrl, urlRedirectId, productFileId, purchaseId]);
useEffect(
() => () => {
if (!urlRedirectId || !productFileId) return;
updateMediaLocation({
urlRedirectId,
productFileId,
purchaseId,
// We deliberately use the latest value of the ref for the latest media location
location: currentPositionRef.current,
accessToken,
}).then(() => queryClient.invalidateQueries({ queryKey: ["purchase", urlRedirectId] }));
},
[urlRedirectId, productFileId, purchaseId, currentPositionRef, accessToken, queryClient],
);
useEffect(() => {
if (!player || !urlRedirectId || !productFileId) return;
const interval = setInterval(() => {
const position = player.currentTime;
setCurrentPosition(position);
updateMediaLocation({
urlRedirectId,
productFileId,
purchaseId,
location: position,
accessToken,
});
}, 5000);
return () => clearInterval(interval);
}, [player, urlRedirectId, productFileId, purchaseId, accessToken]);
if (isLoading || !videoUrl) {
return (
<View style={styles.container}>
<Stack.Screen options={{ title: title ?? "Video" }} />
<View style={styles.loadingContainer}>
<LoadingSpinner size="large" />
</View>
</View>
);
}
if (playbackError) {
return (
<View style={styles.container}>
<Stack.Screen
options={{
title: title ?? "Video",
headerStyle: { backgroundColor: "#000" },
headerTintColor: "#fff",
}}
/>
<View style={styles.errorContainer}>
<Text className="text-center text-lg font-semibold text-white">This video failed to load</Text>
<Text className="mt-2 text-center text-sm text-white/70">
Try downloading the file from the product page instead.
</Text>
<Text className="mt-4 text-center text-xs text-white/50">{playbackError}</Text>
</View>
</View>
);
}
return (
<View style={styles.container}>
<Stack.Screen
options={{
title: title ?? "Video",
headerStyle: { backgroundColor: "#000" },
headerTintColor: "#fff",
}}
/>
<VideoView
style={styles.video}
player={player}
allowsPictureInPicture
fullscreenOptions={{ enable: true, orientation: "landscape", autoExitOnRotate: true }}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#000",
},
loadingContainer: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
errorContainer: {
flex: 1,
justifyContent: "center",
alignItems: "center",
padding: 24,
},
video: {
flex: 1,
width: "100%",
height: "100%",
},
});