feat: load video from providers

This commit is contained in:
Adrian Castro
2024-02-05 12:27:46 +01:00
parent 8976b939b6
commit 552b9b52bc
10 changed files with 244 additions and 120 deletions

View File

@@ -19,7 +19,7 @@ const defineConfig = (): ExpoConfig => ({
ios: { ios: {
bundleIdentifier: "dev.movieweb.app", bundleIdentifier: "dev.movieweb.app",
supportsTablet: true, supportsTablet: true,
requireFullScreen: true, requireFullScreen: true,
}, },
android: { android: {
package: "dev.movieweb.app", package: "dev.movieweb.app",
@@ -41,13 +41,15 @@ const defineConfig = (): ExpoConfig => ({
tsconfigPaths: true, tsconfigPaths: true,
typedRoutes: true, typedRoutes: true,
}, },
plugins: ["expo-router", [ plugins: [
"expo-screen-orientation", "expo-router",
{ [
initialOrientation: "DEFAULT" "expo-screen-orientation",
} {
] initialOrientation: "DEFAULT",
], },
],
],
}); });
export default defineConfig; export default defineConfig;

View File

@@ -1 +1,2 @@
import "expo-router/entry"; import "expo-router/entry";
import "@react-native-anywhere/polyfill-base64";

View File

@@ -19,7 +19,10 @@
}, },
"dependencies": { "dependencies": {
"@expo/metro-config": "^0.17.3", "@expo/metro-config": "^0.17.3",
"@movie-web/provider-utils": "*",
"@movie-web/tmdb": "*", "@movie-web/tmdb": "*",
"@react-native-anywhere/polyfill-base64": "0.0.1-alpha.0",
"@react-navigation/native": "^6.1.9",
"class-variance-authority": "^0.7.0", "class-variance-authority": "^0.7.0",
"clsx": "^2.1.0", "clsx": "^2.1.0",
"expo": "~50.0.5", "expo": "~50.0.5",

View File

@@ -1,5 +1,12 @@
import { Image, TouchableOpacity, View } from "react-native";
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import { Image, View, TouchableOpacity } from "react-native"; import * as ScreenOrientation from "expo-screen-orientation";
import {
getVideoUrl,
transformSearchResultToScrapeMedia,
} from "@movie-web/provider-utils";
import { fetchMediaDetails } from "@movie-web/tmdb";
import { Text } from "~/components/ui/Text"; import { Text } from "~/components/ui/Text";
@@ -13,38 +20,67 @@ export interface ItemData {
export default function Item({ data }: { data: ItemData }) { export default function Item({ data }: { data: ItemData }) {
const router = useRouter(); const router = useRouter();
const { title, type, year, posterUrl } = data; const { id, title, type, year, posterUrl } = data;
const handlePress = () => { const handlePress = async () => {
router.push('/video-player'); router.push("/video-player");
// router.push({
// pathname: '/video-player', const media = await fetchMediaDetails(id, type);
// params: { videoUrl: 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4' } if (!media) return;
// });
const { result } = media;
let season: number | undefined;
let episode: number | undefined;
if (type === "tv") {
// season = <chosen by user> ?? undefined;
// episode = <chosen by user> ?? undefined;
}
const scrapeMedia = transformSearchResultToScrapeMedia(
type,
result,
season,
episode,
);
const videoUrl = await getVideoUrl(scrapeMedia);
if (!videoUrl) {
await ScreenOrientation.lockAsync(
ScreenOrientation.OrientationLock.PORTRAIT_UP,
);
return router.push("/(tabs)");
}
console.log(videoUrl);
router.push({
pathname: "/video-player",
params: { videoUrl },
});
}; };
return ( return (
<TouchableOpacity onPress={handlePress} style={{ width: '100%' }}> <TouchableOpacity onPress={handlePress} style={{ width: "100%" }}>
{ {
<View className="w-full"> <View className="w-full">
<View className="mb-2 aspect-[9/14] w-full overflow-hidden rounded-2xl"> <View className="mb-2 aspect-[9/14] w-full overflow-hidden rounded-2xl">
<Image <Image
source={{ source={{
uri: posterUrl, uri: posterUrl,
}} }}
className="h-full w-full" className="h-full w-full"
/> />
</View> </View>
<Text className="font-bold">{title}</Text> <Text className="font-bold">{title}</Text>
<View className="flex-row items-center gap-3"> <View className="flex-row items-center gap-3">
<Text className="text-xs text-gray-600"> <Text className="text-xs text-gray-600">
{type === "tv" ? "Show" : "Movie"} {type === "tv" ? "Show" : "Movie"}
</Text> </Text>
<View className="h-1 w-1 rounded-3xl bg-gray-600" /> <View className="h-1 w-1 rounded-3xl bg-gray-600" />
<Text className="text-sm text-gray-600">{year}</Text> <Text className="text-sm text-gray-600">{year}</Text>
</View> </View>
</View> </View>
} }
</TouchableOpacity> </TouchableOpacity>
); );
} }

View File

@@ -1,10 +1,10 @@
import React, { Component } from 'react'; import type { VideoRef } from "react-native-video";
import { StyleSheet, ActivityIndicator } from 'react-native'; import React, { Component } from "react";
import { SafeAreaView } from 'react-native-safe-area-context'; import { ActivityIndicator, StyleSheet } from "react-native";
import type { VideoRef } from 'react-native-video'; import { SafeAreaView } from "react-native-safe-area-context";
import Video from 'react-native-video'; import Video from "react-native-video";
import * as ScreenOrientation from 'expo-screen-orientation';
import { useLocalSearchParams } from "expo-router"; import { useLocalSearchParams } from "expo-router";
import * as ScreenOrientation from "expo-screen-orientation";
interface VideoPlayerState { interface VideoPlayerState {
videoUrl: string; videoUrl: string;
@@ -14,53 +14,57 @@ interface VideoPlayerState {
} }
interface VideoPlayerProps { interface VideoPlayerProps {
videoUrl: string; videoUrl: string;
} }
export default function VideoPlayerWrapper() { export default function VideoPlayerWrapper() {
const params = useLocalSearchParams(); const params = useLocalSearchParams();
const videoUrl = typeof params.videoUrl === 'string' ? params.videoUrl : ''; const videoUrl = typeof params.videoUrl === "string" ? params.videoUrl : "";
return <VideoPlayer videoUrl={videoUrl} />; return <VideoPlayer videoUrl={videoUrl} />;
} }
class VideoPlayer extends Component<VideoPlayerProps, VideoPlayerState> { class VideoPlayer extends Component<VideoPlayerProps, VideoPlayerState> {
private videoPlayer: React.RefObject<VideoRef>; private videoPlayer: React.RefObject<VideoRef>;
constructor(props: VideoPlayerProps) { constructor(props: VideoPlayerProps) {
super(props); super(props);
this.state = { this.state = {
videoUrl: props.videoUrl || '', videoUrl: props.videoUrl || "",
fullscreen: true, fullscreen: true,
isLoading: true, isLoading: true,
paused: false paused: false,
}; };
this.videoPlayer = React.createRef(); this.videoPlayer = React.createRef();
} }
componentDidMount() { componentDidMount() {
const lockOrientation = async () => { const lockOrientation = async () => {
await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.LANDSCAPE); await ScreenOrientation.lockAsync(
}; ScreenOrientation.OrientationLock.LANDSCAPE,
);
const { videoUrl } = this.props; };
this.setState({ videoUrl }, () => { const { videoUrl } = this.props;
if (this.videoPlayer.current) {
this.videoPlayer.current.presentFullscreenPlayer(); this.setState({ videoUrl }, () => {
void lockOrientation(); if (this.videoPlayer.current) {
} this.videoPlayer.current.presentFullscreenPlayer();
}); void lockOrientation();
}
});
} }
componentWillUnmount() { componentWillUnmount() {
const unlockOrientation = async () => { const unlockOrientation = async () => {
await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT_UP); await ScreenOrientation.lockAsync(
} ScreenOrientation.OrientationLock.PORTRAIT_UP,
);
};
if (this.videoPlayer.current) { if (this.videoPlayer.current) {
this.videoPlayer.current.dismissFullscreenPlayer(); this.videoPlayer.current.dismissFullscreenPlayer();
} }
void unlockOrientation(); void unlockOrientation();
} }
onVideoLoadStart = () => { onVideoLoadStart = () => {
@@ -71,9 +75,9 @@ export default function VideoPlayerWrapper() {
this.setState({ isLoading: false }); this.setState({ isLoading: false });
}; };
// onVideoError = () => { // probably useful later // onVideoError = () => { // probably useful later
// console.log("Video playback error"); // console.log("Video playback error");
// }; // };
render() { render() {
return ( return (
@@ -84,7 +88,7 @@ export default function VideoPlayerWrapper() {
style={styles.fullScreen} style={styles.fullScreen}
fullscreen={this.state.fullscreen} fullscreen={this.state.fullscreen}
paused={this.state.paused} paused={this.state.paused}
controls={true} controls={true}
onLoadStart={this.onVideoLoadStart} onLoadStart={this.onVideoLoadStart}
onReadyForDisplay={this.onReadyForDisplay} onReadyForDisplay={this.onReadyForDisplay}
// onError={this.onVideoError} // onError={this.onVideoError}
@@ -98,18 +102,18 @@ export default function VideoPlayerWrapper() {
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
// taken from example, probably needs to be nativewind stuff instead
container: { container: {
flex: 1, flex: 1,
justifyContent: 'center', justifyContent: "center",
alignItems: 'center', alignItems: "center",
backgroundColor: 'black', backgroundColor: "black",
}, },
fullScreen: { fullScreen: {
position: 'absolute', position: "absolute",
top: 0, top: 0,
left: 0, left: 0,
bottom: 0, bottom: 0,
right: 0, right: 0,
}, },
}); });

View File

@@ -29,6 +29,7 @@
}, },
"prettier": "@movie-web/prettier-config", "prettier": "@movie-web/prettier-config",
"dependencies": { "dependencies": {
"@movie-web/providers": "^2.1.1" "@movie-web/providers": "^2.1.1",
"tmdb-ts": "^1.6.1"
} }
} }

View File

@@ -1 +1,3 @@
export const name = "provider-utils"; export const name = "provider-utils";
export * from "./video";
export * from "./util";

View File

@@ -0,0 +1,43 @@
import type { MovieDetails, TvShowDetails } from "tmdb-ts";
import type { ScrapeMedia } from "@movie-web/providers";
export function transformSearchResultToScrapeMedia(
type: "tv" | "movie",
result: TvShowDetails | MovieDetails,
season?: number,
episode?: number,
): ScrapeMedia {
if (type === "tv") {
const tvResult = result as TvShowDetails;
return {
type: "show",
tmdbId: tvResult.id.toString(),
title: tvResult.name,
releaseYear: new Date(tvResult.first_air_date).getFullYear(),
season: {
number: season ?? tvResult.seasons[0]?.season_number ?? 1,
tmdbId: season
? tvResult.seasons
.find((s) => s.season_number === season)
?.id.toString() ?? ""
: tvResult.seasons[0]?.id.toString() ?? "",
},
episode: {
number: episode ?? 1,
tmdbId: "",
},
};
}
if (type === "movie") {
const movieResult = result as MovieDetails;
return {
type: "movie",
tmdbId: movieResult.id.toString(),
title: movieResult.title,
releaseYear: new Date(movieResult.release_date).getFullYear(),
};
}
throw new Error("Invalid type parameter");
}

View File

@@ -1,47 +1,57 @@
import type { import type {
FileBasedStream, FileBasedStream,
Qualities, Qualities,
RunnerOptions, RunnerOptions,
ScrapeMedia} from '@movie-web/providers'; ScrapeMedia,
} from "@movie-web/providers";
import { import {
makeProviders, makeProviders,
makeStandardFetcher, makeStandardFetcher,
targets, targets,
} from '@movie-web/providers'; } from "@movie-web/providers";
export async function getVideoUrl(media: ScrapeMedia): Promise<string|null> { export async function getVideoUrl(media: ScrapeMedia): Promise<string | null> {
const providers = makeProviders({ const providers = makeProviders({
fetcher: makeStandardFetcher(fetch), fetcher: makeStandardFetcher(fetch),
target: targets.NATIVE, target: targets.NATIVE,
consistentIpForRequests: true, consistentIpForRequests: true,
}); });
const options: RunnerOptions = { const options: RunnerOptions = {
media media,
}; };
const results = await providers.runAll(options); const results = await providers.runAll(options);
if (!results) return null; if (!results) return null;
let highestQuality; let highestQuality;
let url; let url;
switch (results.stream.type) { switch (results.stream.type) {
case 'file': case "file":
highestQuality = findHighestQuality(results.stream); highestQuality = findHighestQuality(results.stream);
url = highestQuality ? results.stream.qualities[highestQuality]?.url : null; url = highestQuality
return url ?? null; ? results.stream.qualities[highestQuality]?.url
case 'hls': : null;
return results.stream.playlist; return url ?? null;
} case "hls":
return results.stream.playlist;
}
} }
function findHighestQuality(stream: FileBasedStream): Qualities | undefined { function findHighestQuality(stream: FileBasedStream): Qualities | undefined {
const qualityOrder: Qualities[] = ['4k', '1080', '720', '480', '360', 'unknown']; const qualityOrder: Qualities[] = [
for (const quality of qualityOrder) { "4k",
if (stream.qualities[quality]) { "1080",
return quality; "720",
} "480",
} "360",
return undefined; "unknown",
} ];
for (const quality of qualityOrder) {
if (stream.qualities[quality]) {
return quality;
}
}
return undefined;
}

22
pnpm-lock.yaml generated
View File

@@ -34,9 +34,18 @@ importers:
'@expo/metro-config': '@expo/metro-config':
specifier: ^0.17.3 specifier: ^0.17.3
version: 0.17.3(@react-native/babel-preset@0.73.20) version: 0.17.3(@react-native/babel-preset@0.73.20)
'@movie-web/provider-utils':
specifier: '*'
version: link:../../packages/provider-utils
'@movie-web/tmdb': '@movie-web/tmdb':
specifier: '*' specifier: '*'
version: link:../../packages/tmdb version: link:../../packages/tmdb
'@react-native-anywhere/polyfill-base64':
specifier: 0.0.1-alpha.0
version: 0.0.1-alpha.0
'@react-navigation/native':
specifier: ^6.1.9
version: 6.1.9(react-native@0.73.2)(react@18.2.0)
class-variance-authority: class-variance-authority:
specifier: ^0.7.0 specifier: ^0.7.0
version: 0.7.0 version: 0.7.0
@@ -149,6 +158,9 @@ importers:
'@movie-web/providers': '@movie-web/providers':
specifier: ^2.1.1 specifier: ^2.1.1
version: 2.1.1 version: 2.1.1
tmdb-ts:
specifier: ^1.6.1
version: 1.6.1
devDependencies: devDependencies:
'@movie-web/eslint-config': '@movie-web/eslint-config':
specifier: workspace:^0.2.0 specifier: workspace:^0.2.0
@@ -2387,6 +2399,12 @@ packages:
react: 18.2.0 react: 18.2.0
dev: false dev: false
/@react-native-anywhere/polyfill-base64@0.0.1-alpha.0:
resolution: {integrity: sha512-OF3idcETV622AyFvvK54ot2EG0G43tZTZJyWtFHtrEKUmoUvSuC5DOMeLino0TwBQJn2s26MBnIPVgokBJb/xw==}
dependencies:
base-64: 0.1.0
dev: false
/@react-native-community/cli-clean@12.3.0: /@react-native-community/cli-clean@12.3.0:
resolution: {integrity: sha512-iAgLCOWYRGh9ukr+eVQnhkV/OqN3V2EGd/in33Ggn/Mj4uO6+oUncXFwB+yjlyaUNz6FfjudhIz09yYGSF+9sg==} resolution: {integrity: sha512-iAgLCOWYRGh9ukr+eVQnhkV/OqN3V2EGd/in33Ggn/Mj4uO6+oUncXFwB+yjlyaUNz6FfjudhIz09yYGSF+9sg==}
dependencies: dependencies:
@@ -3838,6 +3856,10 @@ packages:
/balanced-match@1.0.2: /balanced-match@1.0.2:
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
/base-64@0.1.0:
resolution: {integrity: sha512-Y5gU45svrR5tI2Vt/X9GPd3L0HNIKzGu202EjxrXMpuc2V2CiKgemAbUUsqYmZJvPtCXoUKjNZwBJzsNScUbXA==}
dev: false
/base64-js@1.5.1: /base64-js@1.5.1:
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}