mirror of
https://github.com/streamyfin/streamyfin.git
synced 2026-01-15 23:59:08 +00:00
chore: refactor
This commit is contained in:
@@ -3,9 +3,12 @@ import { Text } from "@/components/common/Text";
|
||||
import ContinueWatchingPoster from "@/components/ContinueWatchingPoster";
|
||||
import { ItemCardText } from "@/components/ItemCardText";
|
||||
import { apiAtom, userAtom } from "@/providers/JellyfinProvider";
|
||||
import { nextUp } from "@/utils/jellyfin";
|
||||
import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
import { getItemsApi, getSuggestionsApi } from "@jellyfin/sdk/lib/utils/api";
|
||||
import {
|
||||
getItemsApi,
|
||||
getSuggestionsApi,
|
||||
getTvShowsApi,
|
||||
} from "@jellyfin/sdk/lib/utils/api";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useRouter } from "expo-router";
|
||||
import { useAtom } from "jotai";
|
||||
@@ -19,22 +22,24 @@ import {
|
||||
} from "react-native";
|
||||
|
||||
export default function index() {
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [api] = useAtom(apiAtom);
|
||||
const [user] = useAtom(userAtom);
|
||||
const router = useRouter();
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { data, isLoading, isError } = useQuery<BaseItemDto[]>({
|
||||
queryKey: ["resumeItems", user?.Id],
|
||||
queryFn: async () => {
|
||||
if (!api || !user?.Id) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const response = await getItemsApi(api).getResumeItems({
|
||||
userId: user.Id,
|
||||
});
|
||||
return response.data.Items || [];
|
||||
},
|
||||
queryFn: async () =>
|
||||
(api &&
|
||||
(
|
||||
await getItemsApi(api).getResumeItems({
|
||||
userId: user?.Id,
|
||||
})
|
||||
).data.Items) ||
|
||||
[],
|
||||
enabled: !!api && !!user?.Id,
|
||||
staleTime: 60,
|
||||
});
|
||||
@@ -42,10 +47,14 @@ export default function index() {
|
||||
const { data: _nextUpData } = useQuery({
|
||||
queryKey: ["nextUp-all", user?.Id],
|
||||
queryFn: async () =>
|
||||
await nextUp({
|
||||
userId: user?.Id,
|
||||
api,
|
||||
}),
|
||||
(api &&
|
||||
(
|
||||
await getTvShowsApi(api).getNextUp({
|
||||
userId: user?.Id,
|
||||
fields: ["MediaSourceCount"],
|
||||
})
|
||||
).data.Items) ||
|
||||
[],
|
||||
enabled: !!api && !!user?.Id,
|
||||
staleTime: 0,
|
||||
});
|
||||
@@ -87,26 +96,20 @@ export default function index() {
|
||||
|
||||
const { data: suggestions } = useQuery<BaseItemDto[]>({
|
||||
queryKey: ["suggestions", user?.Id],
|
||||
queryFn: async () => {
|
||||
if (!api || !user?.Id) {
|
||||
return [];
|
||||
}
|
||||
const response = await getSuggestionsApi(api).getSuggestions({
|
||||
userId: user.Id,
|
||||
limit: 5,
|
||||
mediaType: ["Video"],
|
||||
});
|
||||
|
||||
return response.data.Items || [];
|
||||
},
|
||||
queryFn: async () =>
|
||||
(api &&
|
||||
(
|
||||
await getSuggestionsApi(api).getSuggestions({
|
||||
userId: user?.Id,
|
||||
limit: 5,
|
||||
mediaType: ["Video"],
|
||||
})
|
||||
).data.Items) ||
|
||||
[],
|
||||
enabled: !!api && !!user?.Id,
|
||||
staleTime: 60,
|
||||
});
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const refetch = useCallback(async () => {
|
||||
setLoading(true);
|
||||
await queryClient.refetchQueries({ queryKey: ["resumeItems", user?.Id] });
|
||||
|
||||
@@ -6,7 +6,8 @@ import { ItemCardText } from "@/components/ItemCardText";
|
||||
import MoviePoster from "@/components/MoviePoster";
|
||||
import Poster from "@/components/Poster";
|
||||
import { apiAtom, userAtom } from "@/providers/JellyfinProvider";
|
||||
import { getPrimaryImage, getUserItemData } from "@/utils/jellyfin";
|
||||
import { getPrimaryImage } from "@/utils/jellyfin";
|
||||
import { getUserItemData } from "@/utils/jellyfin/items/getUserItemData";
|
||||
import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
import { getSearchApi } from "@jellyfin/sdk/lib/utils/api";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
@@ -146,21 +147,6 @@ export default function search() {
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* <Text>Series</Text>
|
||||
|
||||
<HorizontalScroll
|
||||
data={series}
|
||||
renderItem={(item, index) => <Poster itemId={item.Id} key={index} />}
|
||||
/>
|
||||
|
||||
<Text>Episodes</Text>
|
||||
<HorizontalScroll
|
||||
data={episodes}
|
||||
renderItem={(item, index) => (
|
||||
<ContinueWatchingPoster item={item} key={index} />
|
||||
)}
|
||||
/> */}
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
@@ -187,13 +173,15 @@ const SearchItemWrapper: React.FC<Props> = ({ ids, renderItem }) => {
|
||||
api,
|
||||
userId: user.Id,
|
||||
itemId: id,
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
const results = await Promise.all(itemPromises);
|
||||
|
||||
// Filter out null items
|
||||
return results.filter((item) => item !== null);
|
||||
return results.filter(
|
||||
(item) => item !== null,
|
||||
) as unknown as BaseItemDto[];
|
||||
},
|
||||
enabled: !!ids && ids.length > 0 && !!api && !!user?.Id,
|
||||
staleTime: Infinity,
|
||||
|
||||
@@ -25,19 +25,14 @@ const page: React.FC = () => {
|
||||
|
||||
const { data: collection } = useQuery({
|
||||
queryKey: ["collection", collectionId],
|
||||
queryFn: async () => {
|
||||
if (!api || !user?.Id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = (
|
||||
await getItemsApi(api).getItems({
|
||||
userId: user.Id,
|
||||
})
|
||||
).data;
|
||||
|
||||
return data.Items?.find((item) => item.Id == collectionId);
|
||||
},
|
||||
queryFn: async () =>
|
||||
(api &&
|
||||
(
|
||||
await getItemsApi(api).getItems({
|
||||
userId: user?.Id,
|
||||
})
|
||||
).data.Items?.find((item) => item.Id == collectionId)) ||
|
||||
null,
|
||||
enabled: !!api && !!user?.Id,
|
||||
staleTime: 0,
|
||||
});
|
||||
@@ -77,7 +72,7 @@ const page: React.FC = () => {
|
||||
headers: {
|
||||
Authorization: `MediaBrowser DeviceId="${api.deviceInfo.id}", Token="${api.accessToken}"`,
|
||||
},
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
return response.data || [];
|
||||
|
||||
@@ -7,11 +7,7 @@ import { CurrentSeries } from "@/components/series/CurrentSeries";
|
||||
import { SimilarItems } from "@/components/SimilarItems";
|
||||
import { VideoPlayer } from "@/components/VideoPlayer";
|
||||
import { apiAtom, userAtom } from "@/providers/JellyfinProvider";
|
||||
import {
|
||||
getBackdrop,
|
||||
getLogoImageById,
|
||||
getUserItemData,
|
||||
} from "@/utils/jellyfin";
|
||||
import { getBackdrop, getLogoImageById } from "@/utils/jellyfin";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Image } from "expo-image";
|
||||
import { router, useLocalSearchParams } from "expo-router";
|
||||
@@ -24,6 +20,7 @@ import {
|
||||
View,
|
||||
} from "react-native";
|
||||
import { ParallaxScrollView } from "../../../../components/ParallaxPage";
|
||||
import { getUserItemData } from "@/utils/jellyfin/items/getUserItemData";
|
||||
|
||||
const page: React.FC = () => {
|
||||
const local = useLocalSearchParams();
|
||||
@@ -54,12 +51,12 @@ const page: React.FC = () => {
|
||||
quality: 90,
|
||||
width: 1000,
|
||||
}),
|
||||
[item]
|
||||
[item],
|
||||
);
|
||||
|
||||
const logoUrl = useMemo(
|
||||
() => (item?.Type === "Movie" ? getLogoImageById({ api, item }) : null),
|
||||
[item]
|
||||
[item],
|
||||
);
|
||||
|
||||
if (l1)
|
||||
|
||||
@@ -3,13 +3,8 @@ import { ParallaxScrollView } from "@/components/ParallaxPage";
|
||||
import { NextUp } from "@/components/series/NextUp";
|
||||
import { SeasonPicker } from "@/components/series/SeasonPicker";
|
||||
import { apiAtom, userAtom } from "@/providers/JellyfinProvider";
|
||||
import {
|
||||
getBackdrop,
|
||||
getLogoImageById,
|
||||
getPrimaryImage,
|
||||
getPrimaryImageById,
|
||||
getUserItemData,
|
||||
} from "@/utils/jellyfin";
|
||||
import { getBackdrop, getLogoImageById } from "@/utils/jellyfin";
|
||||
import { getUserItemData } from "@/utils/jellyfin/items/getUserItemData";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Image } from "expo-image";
|
||||
import { useLocalSearchParams } from "expo-router";
|
||||
@@ -44,7 +39,7 @@ const page: React.FC = () => {
|
||||
quality: 90,
|
||||
width: 1000,
|
||||
}),
|
||||
[item]
|
||||
[item],
|
||||
);
|
||||
|
||||
const logoUrl = useMemo(
|
||||
@@ -53,7 +48,7 @@ const page: React.FC = () => {
|
||||
api,
|
||||
item,
|
||||
}),
|
||||
[item]
|
||||
[item],
|
||||
);
|
||||
|
||||
if (!item || !backdropUrl) return null;
|
||||
|
||||
@@ -2,13 +2,13 @@ import { Button } from "@/components/Button";
|
||||
import { Text } from "@/components/common/Text";
|
||||
import { ListItem } from "@/components/ListItem";
|
||||
import { apiAtom, useJellyfin, userAtom } from "@/providers/JellyfinProvider";
|
||||
import { useFiles } from "@/utils/files/useFiles";
|
||||
import { readFromLog } from "@/utils/log";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import * as FileSystem from "expo-file-system";
|
||||
import { useAtom } from "jotai";
|
||||
import { ScrollView, View } from "react-native";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useFiles } from "@/hooks/useFiles";
|
||||
|
||||
export default function settings() {
|
||||
const { logout } = useJellyfin();
|
||||
@@ -39,7 +39,9 @@ export default function settings() {
|
||||
color="red"
|
||||
onPress={async () => {
|
||||
await deleteAllFiles();
|
||||
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success)
|
||||
Haptics.notificationAsync(
|
||||
Haptics.NotificationFeedbackType.Success,
|
||||
);
|
||||
}}
|
||||
>
|
||||
Delete all downloaded files
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
import { apiAtom, userAtom } from "@/providers/JellyfinProvider";
|
||||
import { runningProcesses } from "@/utils/atoms/downloads";
|
||||
import {
|
||||
getPlaybackInfo,
|
||||
useDownloadMedia,
|
||||
useRemuxHlsToMp4,
|
||||
} from "@/utils/jellyfin";
|
||||
import Ionicons from "@expo/vector-icons/Ionicons";
|
||||
import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
@@ -15,6 +10,9 @@ import { useCallback, useEffect, useState } from "react";
|
||||
import { ActivityIndicator, TouchableOpacity, View } from "react-native";
|
||||
import ProgressCircle from "./ProgressCircle";
|
||||
import { Text } from "./common/Text";
|
||||
import { useDownloadMedia } from "@/hooks/useDownloadMedia";
|
||||
import { useRemuxHlsToMp4 } from "@/hooks/useRemuxHlsToMp4";
|
||||
import { getPlaybackInfo } from "@/utils/jellyfin/items/getUserItemData";
|
||||
|
||||
type DownloadProps = {
|
||||
item: BaseItemDto;
|
||||
@@ -50,7 +48,7 @@ export const DownloadItem: React.FC<DownloadProps> = ({
|
||||
downloadMedia(item);
|
||||
} else {
|
||||
throw new Error(
|
||||
"Direct play not supported thus the file cannot be downloaded"
|
||||
"Direct play not supported thus the file cannot be downloaded",
|
||||
);
|
||||
}
|
||||
}, [item, user, playbackInfo]);
|
||||
@@ -60,7 +58,7 @@ export const DownloadItem: React.FC<DownloadProps> = ({
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
const data: BaseItemDto[] = JSON.parse(
|
||||
(await AsyncStorage.getItem("downloaded_files")) || "[]"
|
||||
(await AsyncStorage.getItem("downloaded_files")) || "[]",
|
||||
);
|
||||
|
||||
if (data.find((d) => d.Id === item.Id)) setDownloaded(true);
|
||||
@@ -96,26 +94,28 @@ export const DownloadItem: React.FC<DownloadProps> = ({
|
||||
}}
|
||||
className="flex flex-row items-center"
|
||||
>
|
||||
<View className="relative">
|
||||
<View className="-rotate-45">
|
||||
<ProgressCircle
|
||||
size={26}
|
||||
fill={process.progress}
|
||||
width={3}
|
||||
tintColor="#3498db"
|
||||
backgroundColor="#bdc3c7"
|
||||
/>
|
||||
</View>
|
||||
{process.progress > 0 ? (
|
||||
{process.progress === 0 ? (
|
||||
<ActivityIndicator size={"small"} color={"white"} />
|
||||
) : (
|
||||
<View className="relative">
|
||||
<View className="-rotate-45">
|
||||
<ProgressCircle
|
||||
size={28}
|
||||
fill={process.progress}
|
||||
width={4}
|
||||
tintColor="#3498db"
|
||||
backgroundColor="#bdc3c7"
|
||||
/>
|
||||
</View>
|
||||
<View className="absolute top-0 left-0 font-bold w-full h-full flex flex-col items-center justify-center">
|
||||
<Text className="text-[6px]">
|
||||
<Text className="text-[7px]">
|
||||
{process.progress.toFixed(0)}%
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{process?.speed && (process?.speed || 0) > 0 ? (
|
||||
{process?.speed && process.speed > 0 ? (
|
||||
<View className="ml-2">
|
||||
<Text>{process.speed.toFixed(2)}x</Text>
|
||||
</View>
|
||||
@@ -125,7 +125,7 @@ export const DownloadItem: React.FC<DownloadProps> = ({
|
||||
<TouchableOpacity
|
||||
onPress={() => {
|
||||
router.push(
|
||||
`/(auth)/player/offline/page?url=${item.Id}.mp4&itemId=${item.Id}`
|
||||
`/(auth)/player/offline/page?url=${item.Id}.mp4&itemId=${item.Id}`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { apiAtom, userAtom } from "@/providers/JellyfinProvider";
|
||||
import { markAsNotPlayed, markAsPlayed } from "@/utils/jellyfin";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
import { useQueryClient, InvalidateQueryFilters } from "@tanstack/react-query";
|
||||
@@ -7,6 +6,8 @@ import { useAtom } from "jotai";
|
||||
import React, { useCallback } from "react";
|
||||
import { TouchableOpacity, View } from "react-native";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { markAsNotPlayed } from "@/utils/jellyfin/playstate/markAsNotPlayed";
|
||||
import { markAsPlayed } from "@/utils/jellyfin/playstate/markAsPlayed";
|
||||
|
||||
export const PlayedStatus: React.FC<{ item: BaseItemDto }> = ({ item }) => {
|
||||
const [api] = useAtom(apiAtom);
|
||||
|
||||
@@ -1,15 +1,4 @@
|
||||
import { apiAtom, userAtom } from "@/providers/JellyfinProvider";
|
||||
import {
|
||||
chromecastProfile,
|
||||
iosProfile,
|
||||
iOSProfile_2,
|
||||
} from "@/utils/device-profiles";
|
||||
import {
|
||||
getStreamUrl,
|
||||
getUserItemData,
|
||||
reportPlaybackProgress,
|
||||
reportPlaybackStopped,
|
||||
} from "@/utils/jellyfin";
|
||||
import { runtimeTicksToMinutes } from "@/utils/time";
|
||||
import { Feather, Ionicons } from "@expo/vector-icons";
|
||||
import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api";
|
||||
@@ -34,8 +23,12 @@ import Video, {
|
||||
import * as DropdownMenu from "zeego/dropdown-menu";
|
||||
import { Button } from "./Button";
|
||||
import { Text } from "./common/Text";
|
||||
import iosFmp4 from "../utils/profiles/iosFmp4";
|
||||
import ios12 from "../utils/profiles/ios12";
|
||||
import { getUserItemData } from "@/utils/jellyfin/items/getUserItemData";
|
||||
import { getStreamUrl } from "@/utils/jellyfin";
|
||||
import { reportPlaybackProgress } from "@/utils/jellyfin/playstate/reportPlaybackProgress";
|
||||
import { chromecastProfile } from "@/utils/profiles/chromecast";
|
||||
import { reportPlaybackStopped } from "@/utils/jellyfin/playstate/reportPlaybackStopped";
|
||||
|
||||
type VideoPlayerProps = {
|
||||
itemId: string;
|
||||
@@ -75,7 +68,6 @@ export const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
|
||||
const castDevice = useCastDevice();
|
||||
const client = useRemoteMediaClient();
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data: item } = useQuery({
|
||||
@@ -130,40 +122,20 @@ export const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
});
|
||||
|
||||
const onProgress = useCallback(
|
||||
({ currentTime, playableDuration, seekableDuration }: OnProgressData) => {
|
||||
if (!currentTime || !sessionData?.PlaySessionId) return;
|
||||
if (paused) return;
|
||||
|
||||
({ currentTime }: OnProgressData) => {
|
||||
if (!currentTime || !sessionData?.PlaySessionId || paused) return;
|
||||
const newProgress = currentTime * 10000000;
|
||||
setProgress(newProgress);
|
||||
reportPlaybackProgress({
|
||||
api,
|
||||
itemId: itemId,
|
||||
itemId,
|
||||
positionTicks: newProgress,
|
||||
sessionId: sessionData.PlaySessionId,
|
||||
});
|
||||
},
|
||||
[sessionData?.PlaySessionId, item, api, paused]
|
||||
[sessionData?.PlaySessionId, item, api, paused],
|
||||
);
|
||||
|
||||
const onSeek = ({
|
||||
currentTime,
|
||||
seekTime,
|
||||
}: {
|
||||
currentTime: number;
|
||||
seekTime: number;
|
||||
}) => {
|
||||
// console.log("Seek to time: ", seekTime);
|
||||
};
|
||||
|
||||
const onError = (error: OnVideoErrorData) => {
|
||||
console.log("Video Error: ", JSON.stringify(error.error));
|
||||
};
|
||||
|
||||
const onBuffer = (error: OnBufferData) => {
|
||||
console.log("Video buffering: ", error.isBuffering);
|
||||
};
|
||||
|
||||
const play = () => {
|
||||
if (videoRef.current) {
|
||||
videoRef.current.resume();
|
||||
@@ -171,114 +143,90 @@ export const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
}
|
||||
};
|
||||
|
||||
const startPosition = useMemo(() => {
|
||||
return Math.round((item?.UserData?.PlaybackPositionTicks || 0) / 10000);
|
||||
}, [item]);
|
||||
const pause = useCallback(() => {
|
||||
videoRef.current?.pause();
|
||||
setPaused(true);
|
||||
|
||||
const [hidePlayer, setHidePlayer] = useState(true);
|
||||
if (progress > 0)
|
||||
reportPlaybackStopped({
|
||||
api,
|
||||
itemId: item?.Id,
|
||||
positionTicks: progress,
|
||||
sessionId: sessionData?.PlaySessionId,
|
||||
});
|
||||
|
||||
const enableVideo = useMemo(() => {
|
||||
return (
|
||||
playbackURL !== undefined &&
|
||||
item !== undefined &&
|
||||
item !== null &&
|
||||
startPosition !== undefined &&
|
||||
sessionData !== undefined
|
||||
);
|
||||
}, [playbackURL, item, startPosition, sessionData]);
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["nextUp", item?.SeriesId],
|
||||
refetchType: "all",
|
||||
});
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["episodes"],
|
||||
refetchType: "all",
|
||||
});
|
||||
}, [api, item, progress, sessionData, queryClient]);
|
||||
|
||||
const startPosition = useMemo(
|
||||
() =>
|
||||
item?.UserData?.PlaybackPositionTicks
|
||||
? Math.round(item.UserData.PlaybackPositionTicks / 10000)
|
||||
: null,
|
||||
[item],
|
||||
);
|
||||
|
||||
const enableVideo = useMemo(
|
||||
() => !!(playbackURL && item && startPosition !== null && sessionData),
|
||||
[playbackURL, item, startPosition, sessionData],
|
||||
);
|
||||
|
||||
const chromecastReady = useMemo(
|
||||
() => !!(castDevice?.deviceId && item),
|
||||
[castDevice, item],
|
||||
);
|
||||
|
||||
const cast = useCallback(() => {
|
||||
if (client === null) {
|
||||
console.log("no client ");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!playbackURL) {
|
||||
console.log("no playback url");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!item) {
|
||||
console.log("no item");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!client || !playbackURL || !item) return;
|
||||
client.loadMedia({
|
||||
mediaInfo: {
|
||||
contentUrl: playbackURL,
|
||||
contentType: "video/mp4",
|
||||
metadata: {
|
||||
type: item?.Type === "Episode" ? "tvShow" : "movie",
|
||||
title: item?.Name || "",
|
||||
subtitle: item?.Overview || "",
|
||||
type: item.Type === "Episode" ? "tvShow" : "movie",
|
||||
title: item.Name || "",
|
||||
subtitle: item.Overview || "",
|
||||
},
|
||||
streamDuration: Math.floor((item?.RunTimeTicks || 0) / 10000),
|
||||
streamDuration: Math.floor((item.RunTimeTicks || 0) / 10000),
|
||||
},
|
||||
startTime: Math.floor(
|
||||
(item?.UserData?.PlaybackPositionTicks || 0) / 10000
|
||||
(item.UserData?.PlaybackPositionTicks || 0) / 10000,
|
||||
),
|
||||
});
|
||||
}, [item, client, playbackURL]);
|
||||
|
||||
useEffect(() => {
|
||||
if (videoRef.current) {
|
||||
videoRef.current.pause();
|
||||
}
|
||||
videoRef.current?.pause();
|
||||
}, []);
|
||||
|
||||
const chromecastReady = useMemo(() => {
|
||||
return castDevice?.deviceId && item;
|
||||
}, [castDevice, item]);
|
||||
|
||||
return (
|
||||
<View>
|
||||
{enableVideo === true ? (
|
||||
{enableVideo === true && startPosition !== null && !!playbackURL ? (
|
||||
<Video
|
||||
style={{ width: 0, height: 0 }}
|
||||
source={{
|
||||
uri: playbackURL!,
|
||||
uri: playbackURL,
|
||||
isNetwork: true,
|
||||
startPosition,
|
||||
}}
|
||||
debug={{
|
||||
enable: true,
|
||||
thread: true,
|
||||
}}
|
||||
ref={videoRef}
|
||||
onBuffer={onBuffer}
|
||||
onSeek={(t) => onSeek(t)}
|
||||
onError={onError}
|
||||
onBuffer={(e) => (e.isBuffering ? console.log("Buffering...") : null)}
|
||||
onProgress={(e) => onProgress(e)}
|
||||
onFullscreenPlayerDidDismiss={() => {
|
||||
videoRef.current?.pause();
|
||||
setPaused(true);
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["nextUp", item?.SeriesId],
|
||||
refetchType: "all",
|
||||
});
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["episodes"],
|
||||
refetchType: "all",
|
||||
});
|
||||
|
||||
if (progress === 0) return;
|
||||
|
||||
reportPlaybackStopped({
|
||||
api,
|
||||
itemId: item?.Id,
|
||||
positionTicks: progress,
|
||||
sessionId: sessionData?.PlaySessionId,
|
||||
});
|
||||
|
||||
setHidePlayer(true);
|
||||
pause();
|
||||
}}
|
||||
onFullscreenPlayerDidPresent={() => {
|
||||
play();
|
||||
}}
|
||||
paused={paused}
|
||||
onPlaybackStateChanged={(e: OnPlaybackStateChangedData) => {}}
|
||||
ignoreSilentSwitch="ignore"
|
||||
preferredForwardBufferDuration={1}
|
||||
/>
|
||||
) : null}
|
||||
<View className="flex flex-row items-center justify-between">
|
||||
@@ -326,7 +274,6 @@ export const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
if (chromecastReady) {
|
||||
cast();
|
||||
} else {
|
||||
setHidePlayer(false);
|
||||
setTimeout(() => {
|
||||
if (!videoRef.current) return;
|
||||
videoRef.current.presentFullscreenPlayer();
|
||||
|
||||
@@ -3,66 +3,86 @@ import { router } from "expo-router";
|
||||
import { TouchableOpacity } from "react-native";
|
||||
import * as ContextMenu from "zeego/context-menu";
|
||||
import { Text } from "../common/Text";
|
||||
import { useFiles } from "@/utils/files/useFiles";
|
||||
import * as Haptics from 'expo-haptics';
|
||||
import { useFiles } from "@/hooks/useFiles";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useRef, useMemo } from "react";
|
||||
import Video, { VideoRef } from "react-native-video";
|
||||
import * as FileSystem from "expo-file-system";
|
||||
|
||||
export const EpisodeCard: React.FC<{ item: BaseItemDto }> = ({ item }) => {
|
||||
const { deleteFile } = useFiles();
|
||||
const videoRef = useRef<VideoRef | null>(null);
|
||||
|
||||
const openFile = () => {
|
||||
router.push(
|
||||
`/(auth)/player/offline/page?url=${item.Id}.${item.MediaSources?.[0].Container}&itemId=${item.Id}`
|
||||
);
|
||||
videoRef.current?.presentFullscreenPlayer();
|
||||
};
|
||||
|
||||
const fileUrl = useMemo(() => {
|
||||
return `${FileSystem.documentDirectory}/${item.Id}.mp4`;
|
||||
}, [item]);
|
||||
|
||||
const options = [
|
||||
{
|
||||
label: "Delete",
|
||||
onSelect: (id: string) => {
|
||||
deleteFile(id)
|
||||
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success)
|
||||
deleteFile(id);
|
||||
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
|
||||
},
|
||||
destructive: true,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<ContextMenu.Root>
|
||||
<ContextMenu.Trigger>
|
||||
<TouchableOpacity
|
||||
onPress={openFile}
|
||||
className="bg-neutral-800 border border-neutral-900 rounded-2xl p-4"
|
||||
>
|
||||
<Text className=" font-bold">{item.Name}</Text>
|
||||
<Text className=" text-xs opacity-50">
|
||||
Episode {item.IndexNumber}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
</ContextMenu.Trigger>
|
||||
<ContextMenu.Content
|
||||
alignOffset={0}
|
||||
avoidCollisions
|
||||
collisionPadding={10}
|
||||
loop={false}
|
||||
>
|
||||
{options.map((i) => (
|
||||
<ContextMenu.Item
|
||||
onSelect={() => {
|
||||
i.onSelect(item.Id!);
|
||||
}}
|
||||
key={i.label}
|
||||
destructive={i.destructive}
|
||||
<>
|
||||
<ContextMenu.Root>
|
||||
<ContextMenu.Trigger>
|
||||
<TouchableOpacity
|
||||
onPress={openFile}
|
||||
className="bg-neutral-800 border border-neutral-900 rounded-2xl p-4"
|
||||
>
|
||||
<ContextMenu.ItemTitle
|
||||
style={{
|
||||
color: "red",
|
||||
<Text className=" font-bold">{item.Name}</Text>
|
||||
<Text className=" text-xs opacity-50">
|
||||
Episode {item.IndexNumber}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
</ContextMenu.Trigger>
|
||||
<ContextMenu.Content
|
||||
alignOffset={0}
|
||||
avoidCollisions
|
||||
collisionPadding={10}
|
||||
loop={false}
|
||||
>
|
||||
{options.map((i) => (
|
||||
<ContextMenu.Item
|
||||
onSelect={() => {
|
||||
i.onSelect(item.Id!);
|
||||
}}
|
||||
key={i.label}
|
||||
destructive={i.destructive}
|
||||
>
|
||||
{i.label}
|
||||
</ContextMenu.ItemTitle>
|
||||
</ContextMenu.Item>
|
||||
))}
|
||||
</ContextMenu.Content>
|
||||
</ContextMenu.Root>
|
||||
<ContextMenu.ItemTitle
|
||||
style={{
|
||||
color: "red",
|
||||
}}
|
||||
>
|
||||
{i.label}
|
||||
</ContextMenu.ItemTitle>
|
||||
</ContextMenu.Item>
|
||||
))}
|
||||
</ContextMenu.Content>
|
||||
</ContextMenu.Root>
|
||||
|
||||
<Video
|
||||
style={{ width: 0, height: 0 }}
|
||||
source={{
|
||||
uri: fileUrl,
|
||||
isNetwork: false,
|
||||
}}
|
||||
controls
|
||||
ref={videoRef}
|
||||
resizeMode="contain"
|
||||
reportBandwidth
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -4,65 +4,95 @@ import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
import { runtimeTicksToMinutes } from "@/utils/time";
|
||||
import * as ContextMenu from "zeego/context-menu";
|
||||
import { router } from "expo-router";
|
||||
import { useFiles } from "@/utils/files/useFiles";
|
||||
import { useFiles } from "@/hooks/useFiles";
|
||||
import Video, {
|
||||
OnBufferData,
|
||||
OnPlaybackStateChangedData,
|
||||
OnProgressData,
|
||||
OnVideoErrorData,
|
||||
VideoRef,
|
||||
} from "react-native-video";
|
||||
import * as FileSystem from "expo-file-system";
|
||||
import { useMemo, useRef } from "react";
|
||||
import * as Haptics from "expo-haptics";
|
||||
|
||||
export const MovieCard: React.FC<{ item: BaseItemDto }> = ({ item }) => {
|
||||
const { deleteFile } = useFiles();
|
||||
const videoRef = useRef<VideoRef | null>(null);
|
||||
|
||||
const openFile = () => {
|
||||
router.push(
|
||||
`/(auth)/player/offline/page?url=${item.Id}.${item.MediaSources?.[0].Container}&itemId=${item.Id}`
|
||||
);
|
||||
videoRef.current?.presentFullscreenPlayer();
|
||||
};
|
||||
|
||||
const fileUrl = useMemo(() => {
|
||||
return `${FileSystem.documentDirectory}/${item.Id}.mp4`;
|
||||
}, [item]);
|
||||
|
||||
const options = [
|
||||
{
|
||||
label: "Delete",
|
||||
onSelect: (id: string) => deleteFile(id),
|
||||
onSelect: (id: string) => {
|
||||
deleteFile(id);
|
||||
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
|
||||
},
|
||||
destructive: true,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<ContextMenu.Root>
|
||||
<ContextMenu.Trigger>
|
||||
<TouchableOpacity
|
||||
onPress={openFile}
|
||||
className="bg-neutral-800 border border-neutral-900 rounded-2xl p-4"
|
||||
>
|
||||
<Text className=" font-bold">{item.Name}</Text>
|
||||
<View className="flex flex-row items-center justify-between">
|
||||
<Text className=" text-xs opacity-50">{item.ProductionYear}</Text>
|
||||
<Text className=" text-xs opacity-50">
|
||||
{runtimeTicksToMinutes(item.RunTimeTicks)}
|
||||
</Text>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
</ContextMenu.Trigger>
|
||||
<ContextMenu.Content
|
||||
alignOffset={0}
|
||||
avoidCollisions={false}
|
||||
collisionPadding={0}
|
||||
loop={false}
|
||||
>
|
||||
{options.map((i) => (
|
||||
<ContextMenu.Item
|
||||
onSelect={() => {
|
||||
i.onSelect(item.Id!);
|
||||
}}
|
||||
key={i.label}
|
||||
destructive={i.destructive}
|
||||
<>
|
||||
<ContextMenu.Root>
|
||||
<ContextMenu.Trigger>
|
||||
<TouchableOpacity
|
||||
onPress={openFile}
|
||||
className="bg-neutral-800 border border-neutral-900 rounded-2xl p-4"
|
||||
>
|
||||
<ContextMenu.ItemTitle
|
||||
style={{
|
||||
color: "red",
|
||||
<Text className=" font-bold">{item.Name}</Text>
|
||||
<View className="flex flex-row items-center justify-between">
|
||||
<Text className=" text-xs opacity-50">{item.ProductionYear}</Text>
|
||||
<Text className=" text-xs opacity-50">
|
||||
{runtimeTicksToMinutes(item.RunTimeTicks)}
|
||||
</Text>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
</ContextMenu.Trigger>
|
||||
<ContextMenu.Content
|
||||
alignOffset={0}
|
||||
avoidCollisions={false}
|
||||
collisionPadding={0}
|
||||
loop={false}
|
||||
>
|
||||
{options.map((i) => (
|
||||
<ContextMenu.Item
|
||||
onSelect={() => {
|
||||
i.onSelect(item.Id!);
|
||||
}}
|
||||
key={i.label}
|
||||
destructive={i.destructive}
|
||||
>
|
||||
{i.label}
|
||||
</ContextMenu.ItemTitle>
|
||||
</ContextMenu.Item>
|
||||
))}
|
||||
</ContextMenu.Content>
|
||||
</ContextMenu.Root>
|
||||
<ContextMenu.ItemTitle
|
||||
style={{
|
||||
color: "red",
|
||||
}}
|
||||
>
|
||||
{i.label}
|
||||
</ContextMenu.ItemTitle>
|
||||
</ContextMenu.Item>
|
||||
))}
|
||||
</ContextMenu.Content>
|
||||
</ContextMenu.Root>
|
||||
|
||||
<Video
|
||||
style={{ width: 0, height: 0 }}
|
||||
source={{
|
||||
uri: fileUrl,
|
||||
isNetwork: false,
|
||||
}}
|
||||
controls
|
||||
ref={videoRef}
|
||||
resizeMode="contain"
|
||||
reportBandwidth
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -7,10 +7,11 @@ import Poster from "../Poster";
|
||||
import ContinueWatchingPoster from "../ContinueWatchingPoster";
|
||||
import { ItemCardText } from "../ItemCardText";
|
||||
import { router } from "expo-router";
|
||||
import { nextUp } from "@/utils/jellyfin";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useAtom } from "jotai";
|
||||
import { apiAtom, userAtom } from "@/providers/JellyfinProvider";
|
||||
import { nextUp } from "@/utils/jellyfin/tvshows/nextUp";
|
||||
import { getTvShowsApi } from "@jellyfin/sdk/lib/utils/api";
|
||||
|
||||
export const NextUp: React.FC<{ seriesId: string }> = ({ seriesId }) => {
|
||||
const [user] = useAtom(userAtom);
|
||||
@@ -18,12 +19,16 @@ export const NextUp: React.FC<{ seriesId: string }> = ({ seriesId }) => {
|
||||
|
||||
const { data: items } = useQuery({
|
||||
queryKey: ["nextUp", seriesId],
|
||||
queryFn: async () =>
|
||||
await nextUp({
|
||||
userId: user?.Id,
|
||||
api,
|
||||
itemId: seriesId,
|
||||
}),
|
||||
queryFn: async () => {
|
||||
if (!api) return null;
|
||||
return (
|
||||
await getTvShowsApi(api).getNextUp({
|
||||
userId: user?.Id,
|
||||
seriesId,
|
||||
fields: ["MediaSourceCount"],
|
||||
})
|
||||
).data.Items;
|
||||
},
|
||||
enabled: !!api && !!seriesId && !!user?.Id,
|
||||
staleTime: 0,
|
||||
});
|
||||
|
||||
117
hooks/useDownloadMedia.ts
Normal file
117
hooks/useDownloadMedia.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { useAtom } from "jotai";
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import * as FileSystem from "expo-file-system";
|
||||
import { Api } from "@jellyfin/sdk";
|
||||
import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
import { runningProcesses } from "@/utils/atoms/downloads";
|
||||
|
||||
/**
|
||||
* Custom hook for downloading media using the Jellyfin API.
|
||||
*
|
||||
* @param api - The Jellyfin API instance
|
||||
* @param userId - The user ID
|
||||
* @returns An object with download-related functions and state
|
||||
*/
|
||||
export const useDownloadMedia = (api: Api | null, userId?: string | null) => {
|
||||
const [isDownloading, setIsDownloading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [_, setProgress] = useAtom(runningProcesses);
|
||||
const downloadResumableRef = useRef<FileSystem.DownloadResumable | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const downloadMedia = useCallback(
|
||||
async (item: BaseItemDto | null): Promise<boolean> => {
|
||||
if (!item?.Id || !api || !userId) {
|
||||
setError("Invalid item or API");
|
||||
return false;
|
||||
}
|
||||
|
||||
setIsDownloading(true);
|
||||
setError(null);
|
||||
setProgress({ item, progress: 0 });
|
||||
|
||||
try {
|
||||
const filename = item.Id;
|
||||
const fileUri = `${FileSystem.documentDirectory}${filename}`;
|
||||
const url = `${api.basePath}/Items/${item.Id}/File`;
|
||||
|
||||
downloadResumableRef.current = FileSystem.createDownloadResumable(
|
||||
url,
|
||||
fileUri,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `MediaBrowser DeviceId="${api.deviceInfo.id}", Token="${api.accessToken}"`,
|
||||
},
|
||||
},
|
||||
(downloadProgress) => {
|
||||
const currentProgress =
|
||||
downloadProgress.totalBytesWritten /
|
||||
downloadProgress.totalBytesExpectedToWrite;
|
||||
setProgress({ item, progress: currentProgress * 100 });
|
||||
},
|
||||
);
|
||||
|
||||
const res = await downloadResumableRef.current.downloadAsync();
|
||||
|
||||
if (!res?.uri) {
|
||||
throw new Error("Download failed: No URI returned");
|
||||
}
|
||||
|
||||
await updateDownloadedFiles(item);
|
||||
|
||||
setIsDownloading(false);
|
||||
setProgress(null);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error downloading media:", error);
|
||||
setError("Failed to download media");
|
||||
setIsDownloading(false);
|
||||
setProgress(null);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[api, userId, setProgress],
|
||||
);
|
||||
|
||||
const cancelDownload = useCallback(async (): Promise<void> => {
|
||||
if (!downloadResumableRef.current) return;
|
||||
|
||||
try {
|
||||
await downloadResumableRef.current.pauseAsync();
|
||||
setIsDownloading(false);
|
||||
setError("Download cancelled");
|
||||
setProgress(null);
|
||||
downloadResumableRef.current = null;
|
||||
} catch (error) {
|
||||
console.error("Error cancelling download:", error);
|
||||
setError("Failed to cancel download");
|
||||
}
|
||||
}, [setProgress]);
|
||||
|
||||
return { downloadMedia, isDownloading, error, cancelDownload };
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the list of downloaded files in AsyncStorage.
|
||||
*
|
||||
* @param item - The item to add to the downloaded files list
|
||||
*/
|
||||
async function updateDownloadedFiles(item: BaseItemDto): Promise<void> {
|
||||
try {
|
||||
const currentFiles: BaseItemDto[] = JSON.parse(
|
||||
(await AsyncStorage.getItem("downloaded_files")) ?? "[]",
|
||||
);
|
||||
const updatedFiles = [
|
||||
...currentFiles.filter((file) => file.Id !== item.Id),
|
||||
item,
|
||||
];
|
||||
await AsyncStorage.setItem(
|
||||
"downloaded_files",
|
||||
JSON.stringify(updatedFiles),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error updating downloaded files:", error);
|
||||
}
|
||||
}
|
||||
84
hooks/useFiles.ts
Normal file
84
hooks/useFiles.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import * as FileSystem from "expo-file-system";
|
||||
|
||||
/**
|
||||
* Custom hook for managing downloaded files.
|
||||
* @returns An object with functions to delete individual files and all files.
|
||||
*/
|
||||
export const useFiles = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
/**
|
||||
* Deletes all downloaded files and clears the download record.
|
||||
*/
|
||||
const deleteAllFiles = async (): Promise<void> => {
|
||||
const directoryUri = FileSystem.documentDirectory;
|
||||
if (!directoryUri) {
|
||||
console.error("Document directory is undefined");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const fileNames = await FileSystem.readDirectoryAsync(directoryUri);
|
||||
await Promise.all(
|
||||
fileNames.map((item) =>
|
||||
FileSystem.deleteAsync(`${directoryUri}/${item}`, {
|
||||
idempotent: true,
|
||||
}),
|
||||
),
|
||||
);
|
||||
await AsyncStorage.removeItem("downloaded_files");
|
||||
queryClient.invalidateQueries({ queryKey: ["downloaded_files"] });
|
||||
} catch (error) {
|
||||
console.error("Failed to delete all files:", error);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes a specific file and updates the download record.
|
||||
* @param id - The ID of the file to delete.
|
||||
*/
|
||||
const deleteFile = async (id: string): Promise<void> => {
|
||||
if (!id) {
|
||||
console.error("Invalid file ID");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await FileSystem.deleteAsync(
|
||||
`${FileSystem.documentDirectory}/${id}.mp4`,
|
||||
{ idempotent: true },
|
||||
);
|
||||
|
||||
const currentFiles = await getDownloadedFiles();
|
||||
const updatedFiles = currentFiles.filter((f) => f.Id !== id);
|
||||
|
||||
await AsyncStorage.setItem(
|
||||
"downloaded_files",
|
||||
JSON.stringify(updatedFiles),
|
||||
);
|
||||
|
||||
queryClient.invalidateQueries({ queryKey: ["downloaded_files"] });
|
||||
} catch (error) {
|
||||
console.error(`Failed to delete file with ID ${id}:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
return { deleteFile, deleteAllFiles };
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the list of downloaded files from AsyncStorage.
|
||||
* @returns An array of BaseItemDto objects representing downloaded files.
|
||||
*/
|
||||
async function getDownloadedFiles(): Promise<BaseItemDto[]> {
|
||||
try {
|
||||
const filesJson = await AsyncStorage.getItem("downloaded_files");
|
||||
return filesJson ? JSON.parse(filesJson) : [];
|
||||
} catch (error) {
|
||||
console.error("Failed to retrieve downloaded files:", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
127
hooks/useRemuxHlsToMp4.ts
Normal file
127
hooks/useRemuxHlsToMp4.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import { useCallback } from "react";
|
||||
import { useAtom } from "jotai";
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import * as FileSystem from "expo-file-system";
|
||||
import { FFmpegKit, FFmpegKitConfig } from "ffmpeg-kit-react-native";
|
||||
import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
import { runningProcesses } from "@/utils/atoms/downloads";
|
||||
import { writeToLog } from "@/utils/log";
|
||||
|
||||
/**
|
||||
* Custom hook for remuxing HLS to MP4 using FFmpeg.
|
||||
*
|
||||
* @param url - The URL of the HLS stream
|
||||
* @param item - The BaseItemDto object representing the media item
|
||||
* @returns An object with remuxing-related functions
|
||||
*/
|
||||
export const useRemuxHlsToMp4 = (url: string, item: BaseItemDto) => {
|
||||
const [_, setProgress] = useAtom(runningProcesses);
|
||||
|
||||
if (!item.Id || !item.Name) {
|
||||
writeToLog("ERROR", "useRemuxHlsToMp4 ~ missing arguments");
|
||||
throw new Error("Item must have an Id and Name");
|
||||
}
|
||||
|
||||
const output = `${FileSystem.documentDirectory}${item.Id}.mp4`;
|
||||
const command = `-y -fflags +genpts -i ${url} -c copy -bufsize 10M -max_muxing_queue_size 4096 ${output}`;
|
||||
|
||||
const startRemuxing = useCallback(async () => {
|
||||
writeToLog(
|
||||
"INFO",
|
||||
`useRemuxHlsToMp4 ~ startRemuxing for item ${item.Id} with url ${url}`,
|
||||
);
|
||||
|
||||
try {
|
||||
setProgress({ item, progress: 0 });
|
||||
|
||||
FFmpegKitConfig.enableStatisticsCallback((statistics) => {
|
||||
const videoLength =
|
||||
(item.MediaSources?.[0]?.RunTimeTicks || 0) / 10000000; // In seconds
|
||||
const fps = item.MediaStreams?.[0]?.RealFrameRate || 25;
|
||||
const totalFrames = videoLength * fps;
|
||||
const processedFrames = statistics.getVideoFrameNumber();
|
||||
const speed = statistics.getSpeed();
|
||||
|
||||
const percentage =
|
||||
totalFrames > 0
|
||||
? Math.floor((processedFrames / totalFrames) * 100)
|
||||
: 0;
|
||||
|
||||
setProgress((prev) =>
|
||||
prev?.item.Id === item.Id!
|
||||
? { ...prev, progress: percentage, speed }
|
||||
: prev,
|
||||
);
|
||||
});
|
||||
|
||||
await FFmpegKit.executeAsync(command, async (session) => {
|
||||
const returnCode = await session.getReturnCode();
|
||||
|
||||
if (returnCode.isValueSuccess()) {
|
||||
await updateDownloadedFiles(item);
|
||||
writeToLog(
|
||||
"INFO",
|
||||
`useRemuxHlsToMp4 ~ remuxing completed successfully for item: ${item.Name}`,
|
||||
);
|
||||
} else if (returnCode.isValueError()) {
|
||||
writeToLog(
|
||||
"ERROR",
|
||||
`useRemuxHlsToMp4 ~ remuxing failed for item: ${item.Name}`,
|
||||
);
|
||||
} else if (returnCode.isValueCancel()) {
|
||||
writeToLog(
|
||||
"INFO",
|
||||
`useRemuxHlsToMp4 ~ remuxing was canceled for item: ${item.Name}`,
|
||||
);
|
||||
}
|
||||
|
||||
setProgress(null);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to remux:", error);
|
||||
writeToLog(
|
||||
"ERROR",
|
||||
`useRemuxHlsToMp4 ~ remuxing failed for item: ${item.Name}`,
|
||||
);
|
||||
setProgress(null);
|
||||
}
|
||||
}, [output, item, command, setProgress]);
|
||||
|
||||
const cancelRemuxing = useCallback(() => {
|
||||
FFmpegKit.cancel();
|
||||
setProgress(null);
|
||||
writeToLog(
|
||||
"INFO",
|
||||
`useRemuxHlsToMp4 ~ remuxing cancelled for item: ${item.Name}`,
|
||||
);
|
||||
}, [item.Name, setProgress]);
|
||||
|
||||
return { startRemuxing, cancelRemuxing };
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the list of downloaded files in AsyncStorage.
|
||||
*
|
||||
* @param item - The item to add to the downloaded files list
|
||||
*/
|
||||
async function updateDownloadedFiles(item: BaseItemDto): Promise<void> {
|
||||
try {
|
||||
const currentFiles: BaseItemDto[] = JSON.parse(
|
||||
(await AsyncStorage.getItem("downloaded_files")) || "[]",
|
||||
);
|
||||
const updatedFiles = [
|
||||
...currentFiles.filter((i) => i.Id !== item.Id),
|
||||
item,
|
||||
];
|
||||
await AsyncStorage.setItem(
|
||||
"downloaded_files",
|
||||
JSON.stringify(updatedFiles),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error updating downloaded files:", error);
|
||||
writeToLog(
|
||||
"ERROR",
|
||||
`Failed to update downloaded files for item: ${item.Name}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,477 +0,0 @@
|
||||
import {
|
||||
DeviceProfile,
|
||||
DlnaProfileType,
|
||||
} from "@jellyfin/sdk/lib/generated-client/models";
|
||||
|
||||
const MediaTypes = {
|
||||
Audio: "Audio",
|
||||
Video: "Video",
|
||||
Photo: "Photo",
|
||||
Book: "Book",
|
||||
};
|
||||
|
||||
const BaseProfile = {
|
||||
Name: "Expo Base Video Profile",
|
||||
MaxStaticBitrate: 100000000,
|
||||
MaxStreamingBitrate: 120000000,
|
||||
MusicStreamingTranscodingBitrate: 384000,
|
||||
CodecProfiles: [
|
||||
{
|
||||
Codec: "h264",
|
||||
Conditions: [
|
||||
{
|
||||
Condition: "NotEquals",
|
||||
IsRequired: false,
|
||||
Property: "IsAnamorphic",
|
||||
Value: "true",
|
||||
},
|
||||
{
|
||||
Condition: "EqualsAny",
|
||||
IsRequired: false,
|
||||
Property: "VideoProfile",
|
||||
Value: "high|main|baseline|constrained baseline",
|
||||
},
|
||||
{
|
||||
Condition: "LessThanEqual",
|
||||
IsRequired: false,
|
||||
Property: "VideoLevel",
|
||||
Value: "51",
|
||||
},
|
||||
{
|
||||
Condition: "NotEquals",
|
||||
IsRequired: false,
|
||||
Property: "IsInterlaced",
|
||||
Value: "true",
|
||||
},
|
||||
],
|
||||
Type: MediaTypes.Video,
|
||||
},
|
||||
{
|
||||
Codec: "hevc",
|
||||
Conditions: [
|
||||
{
|
||||
Condition: "NotEquals",
|
||||
IsRequired: false,
|
||||
Property: "IsAnamorphic",
|
||||
Value: "true",
|
||||
},
|
||||
{
|
||||
Condition: "EqualsAny",
|
||||
IsRequired: false,
|
||||
Property: "VideoProfile",
|
||||
Value: "main|main 10",
|
||||
},
|
||||
{
|
||||
Condition: "LessThanEqual",
|
||||
IsRequired: false,
|
||||
Property: "VideoLevel",
|
||||
Value: "183",
|
||||
},
|
||||
{
|
||||
Condition: "NotEquals",
|
||||
IsRequired: false,
|
||||
Property: "IsInterlaced",
|
||||
Value: "true",
|
||||
},
|
||||
],
|
||||
Type: MediaTypes.Video,
|
||||
},
|
||||
],
|
||||
ContainerProfiles: [],
|
||||
DirectPlayProfiles: [],
|
||||
ResponseProfiles: [
|
||||
{
|
||||
Container: "m4v",
|
||||
MimeType: "video/mp4",
|
||||
Type: MediaTypes.Video,
|
||||
},
|
||||
],
|
||||
SubtitleProfiles: [
|
||||
{
|
||||
Format: "vtt",
|
||||
Method: "Hls",
|
||||
},
|
||||
],
|
||||
TranscodingProfiles: [],
|
||||
};
|
||||
|
||||
export const iosProfile = {
|
||||
...BaseProfile,
|
||||
Name: "Expo iOS Video Profile",
|
||||
DirectPlayProfiles: [
|
||||
{
|
||||
AudioCodec: "aac,mp3,ac3,eac3,flac,alac",
|
||||
Container: "mp4,m4v",
|
||||
Type: MediaTypes.Video,
|
||||
VideoCodec: "hevc,h264",
|
||||
},
|
||||
{
|
||||
AudioCodec: "aac,mp3,ac3,eac3,flac,alac",
|
||||
Container: "mov",
|
||||
Type: MediaTypes.Video,
|
||||
VideoCodec: "hevc,h264",
|
||||
},
|
||||
{
|
||||
Container: "mp3",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
{
|
||||
Container: "aac",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
{
|
||||
AudioCodec: "aac",
|
||||
Container: "m4a",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
{
|
||||
AudioCodec: "aac",
|
||||
Container: "m4b",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
{
|
||||
Container: "flac",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
{
|
||||
Container: "alac",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
{
|
||||
AudioCodec: "alac",
|
||||
Container: "m4a",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
{
|
||||
AudioCodec: "alac",
|
||||
Container: "m4b",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
{
|
||||
Container: "wav",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
],
|
||||
TranscodingProfiles: [
|
||||
{
|
||||
AudioCodec: "aac",
|
||||
BreakOnNonKeyFrames: true,
|
||||
Container: "aac",
|
||||
Context: "Streaming",
|
||||
MaxAudioChannels: "6",
|
||||
MinSegments: "2",
|
||||
Protocol: "hls",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
{
|
||||
AudioCodec: "aac",
|
||||
Container: "aac",
|
||||
Context: "Streaming",
|
||||
MaxAudioChannels: "6",
|
||||
Protocol: "http",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
{
|
||||
AudioCodec: "mp3",
|
||||
Container: "mp3",
|
||||
Context: "Streaming",
|
||||
MaxAudioChannels: "6",
|
||||
Protocol: "http",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
{
|
||||
AudioCodec: "wav",
|
||||
Container: "wav",
|
||||
Context: "Streaming",
|
||||
MaxAudioChannels: "6",
|
||||
Protocol: "http",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
{
|
||||
AudioCodec: "mp3",
|
||||
Container: "mp3",
|
||||
Context: "Static",
|
||||
MaxAudioChannels: "6",
|
||||
Protocol: "http",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
{
|
||||
AudioCodec: "aac",
|
||||
Container: "aac",
|
||||
Context: "Static",
|
||||
MaxAudioChannels: "6",
|
||||
Protocol: "http",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
{
|
||||
AudioCodec: "wav",
|
||||
Container: "wav",
|
||||
Context: "Static",
|
||||
MaxAudioChannels: "6",
|
||||
Protocol: "http",
|
||||
Type: MediaTypes.Audio,
|
||||
},
|
||||
{
|
||||
AudioCodec: "aac,mp3",
|
||||
BreakOnNonKeyFrames: true,
|
||||
Container: "ts",
|
||||
Context: "Streaming",
|
||||
MaxAudioChannels: "6",
|
||||
MinSegments: "2",
|
||||
Protocol: "hls",
|
||||
Type: MediaTypes.Video,
|
||||
VideoCodec: "h264",
|
||||
},
|
||||
{
|
||||
AudioCodec: "aac,mp3,ac3,eac3,flac,alac",
|
||||
Container: "mp4",
|
||||
Context: "Static",
|
||||
Protocol: "http",
|
||||
Type: MediaTypes.Video,
|
||||
VideoCodec: "h264",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const chromecastProfile: DeviceProfile = {
|
||||
Name: "Chromecast",
|
||||
Id: "chromecast-001",
|
||||
MaxStreamingBitrate: 4000000, // 4 Mbps
|
||||
MaxStaticBitrate: 4000000, // 4 Mbps
|
||||
MusicStreamingTranscodingBitrate: 384000, // 384 kbps
|
||||
DirectPlayProfiles: [
|
||||
{
|
||||
Container: "mp4,webm",
|
||||
Type: "Video",
|
||||
VideoCodec: "h264,vp8,vp9",
|
||||
AudioCodec: "aac,mp3,opus,vorbis",
|
||||
},
|
||||
{
|
||||
Container: "mp3",
|
||||
Type: "Audio",
|
||||
},
|
||||
{
|
||||
Container: "aac",
|
||||
Type: "Audio",
|
||||
},
|
||||
{
|
||||
Container: "flac",
|
||||
Type: "Audio",
|
||||
},
|
||||
{
|
||||
Container: "wav",
|
||||
Type: "Audio",
|
||||
},
|
||||
],
|
||||
TranscodingProfiles: [
|
||||
{
|
||||
Container: "ts",
|
||||
Type: "Video",
|
||||
VideoCodec: "h264",
|
||||
AudioCodec: "aac,mp3",
|
||||
Protocol: "hls",
|
||||
Context: "Streaming",
|
||||
MaxAudioChannels: "2",
|
||||
MinSegments: 2,
|
||||
BreakOnNonKeyFrames: true,
|
||||
},
|
||||
{
|
||||
Container: "mp4",
|
||||
Type: "Video",
|
||||
VideoCodec: "h264",
|
||||
AudioCodec: "aac",
|
||||
Protocol: "http",
|
||||
Context: "Streaming",
|
||||
MaxAudioChannels: "2",
|
||||
},
|
||||
{
|
||||
Container: "mp3",
|
||||
Type: "Audio",
|
||||
AudioCodec: "mp3",
|
||||
Protocol: "http",
|
||||
Context: "Streaming",
|
||||
MaxAudioChannels: "2",
|
||||
},
|
||||
{
|
||||
Container: "aac",
|
||||
Type: "Audio",
|
||||
AudioCodec: "aac",
|
||||
Protocol: "http",
|
||||
Context: "Streaming",
|
||||
MaxAudioChannels: "2",
|
||||
},
|
||||
],
|
||||
ContainerProfiles: [
|
||||
{
|
||||
Type: "Video",
|
||||
Container: "mp4",
|
||||
},
|
||||
{
|
||||
Type: "Video",
|
||||
Container: "webm",
|
||||
},
|
||||
],
|
||||
CodecProfiles: [
|
||||
{
|
||||
Type: "Video",
|
||||
Codec: "h264",
|
||||
Conditions: [
|
||||
{
|
||||
Condition: "LessThanEqual",
|
||||
Property: "VideoBitDepth",
|
||||
Value: "8",
|
||||
},
|
||||
{
|
||||
Condition: "LessThanEqual",
|
||||
Property: "VideoLevel",
|
||||
Value: "41",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
Type: "Video",
|
||||
Codec: "vp9",
|
||||
Conditions: [
|
||||
{
|
||||
Condition: "LessThanEqual",
|
||||
Property: "VideoBitDepth",
|
||||
Value: "10",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
SubtitleProfiles: [
|
||||
{
|
||||
Format: "vtt",
|
||||
Method: "Hls",
|
||||
},
|
||||
{
|
||||
Format: "vtt",
|
||||
Method: "External",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const iOSProfile_2: DeviceProfile = {
|
||||
Id: "iPhone",
|
||||
Name: "iPhone",
|
||||
MaxStreamingBitrate: 20000000,
|
||||
MaxStaticBitrate: 30000000,
|
||||
MusicStreamingTranscodingBitrate: 192000,
|
||||
DirectPlayProfiles: [
|
||||
{
|
||||
Container: "mp4,m4v",
|
||||
Type: "Video",
|
||||
VideoCodec: "h264,hevc,mp4v",
|
||||
AudioCodec: "aac,mp3,ac3,eac3,flac,alac",
|
||||
},
|
||||
{
|
||||
Container: "mov",
|
||||
Type: "Video",
|
||||
VideoCodec: "h264,hevc",
|
||||
AudioCodec: "aac,mp3,ac3,eac3,flac,alac",
|
||||
},
|
||||
{
|
||||
Container: "m4a",
|
||||
Type: "Audio",
|
||||
AudioCodec: "aac,alac",
|
||||
},
|
||||
{
|
||||
Container: "mp3",
|
||||
Type: "Audio",
|
||||
AudioCodec: "mp3",
|
||||
},
|
||||
],
|
||||
TranscodingProfiles: [
|
||||
{
|
||||
Container: "ts",
|
||||
Type: "Video",
|
||||
VideoCodec: "h264",
|
||||
AudioCodec: "aac",
|
||||
Context: "Streaming",
|
||||
Protocol: "hls",
|
||||
MaxAudioChannels: "2",
|
||||
MinSegments: 2,
|
||||
BreakOnNonKeyFrames: true,
|
||||
},
|
||||
{
|
||||
Container: "mp3",
|
||||
Type: "Audio",
|
||||
AudioCodec: "mp3",
|
||||
Context: "Streaming",
|
||||
Protocol: "http",
|
||||
},
|
||||
],
|
||||
ContainerProfiles: [],
|
||||
CodecProfiles: [
|
||||
{
|
||||
Type: "VideoAudio",
|
||||
Codec: "aac",
|
||||
Conditions: [
|
||||
{
|
||||
Condition: "Equals",
|
||||
Property: "IsSecondaryAudio",
|
||||
Value: "false",
|
||||
IsRequired: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
Type: "VideoAudio",
|
||||
Conditions: [
|
||||
{
|
||||
Condition: "LessThanEqual",
|
||||
Property: "AudioChannels",
|
||||
Value: "2",
|
||||
IsRequired: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
Type: "Video",
|
||||
Codec: "h264",
|
||||
Conditions: [
|
||||
{
|
||||
Condition: "LessThanEqual",
|
||||
Property: "VideoLevel",
|
||||
Value: "51",
|
||||
IsRequired: true,
|
||||
},
|
||||
{
|
||||
Condition: "EqualsAny",
|
||||
Property: "VideoProfile",
|
||||
Value: "main|high|baseline",
|
||||
IsRequired: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
Type: "Video",
|
||||
Codec: "hevc",
|
||||
Conditions: [
|
||||
{
|
||||
Condition: "LessThanEqual",
|
||||
Property: "VideoLevel",
|
||||
Value: "153",
|
||||
IsRequired: true,
|
||||
},
|
||||
{
|
||||
Condition: "EqualsAny",
|
||||
Property: "VideoProfile",
|
||||
Value: "main|main10",
|
||||
IsRequired: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
SubtitleProfiles: [
|
||||
{
|
||||
Format: "vtt",
|
||||
Method: "External",
|
||||
},
|
||||
{
|
||||
Format: "mov_text",
|
||||
Method: "Embed",
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -1,63 +0,0 @@
|
||||
import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import * as FileSystem from "expo-file-system";
|
||||
|
||||
export const useFiles = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const deleteAllFiles = async () => {
|
||||
const directoryUri = FileSystem.documentDirectory;
|
||||
|
||||
try {
|
||||
const fileNames = await FileSystem.readDirectoryAsync(directoryUri!);
|
||||
for (let item of fileNames) {
|
||||
await FileSystem.deleteAsync(`${directoryUri}/${item}`);
|
||||
}
|
||||
|
||||
AsyncStorage.removeItem("downloaded_files");
|
||||
} catch (error) {
|
||||
console.error("Failed to delete the directory:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const deleteFile = async (id: string) => {
|
||||
try {
|
||||
const files = await FileSystem.readDirectoryAsync(
|
||||
`${FileSystem.documentDirectory}`
|
||||
);
|
||||
console.log(`Files:`, files);
|
||||
|
||||
await FileSystem.deleteAsync(
|
||||
`${FileSystem.documentDirectory}/${id}.mp4`
|
||||
).catch((err) => console.error(err));
|
||||
|
||||
const currentFiles = JSON.parse(
|
||||
(await AsyncStorage.getItem("downloaded_files")) ?? "[]"
|
||||
) as BaseItemDto[];
|
||||
|
||||
console.log(
|
||||
"Current files",
|
||||
currentFiles.map((i) => i.Name)
|
||||
);
|
||||
|
||||
const updatedFiles = currentFiles.filter((f) => f.Id !== id);
|
||||
|
||||
console.log(
|
||||
"Current files",
|
||||
currentFiles.map((i) => i.Name)
|
||||
);
|
||||
|
||||
await AsyncStorage.setItem(
|
||||
"downloaded_files",
|
||||
JSON.stringify(updatedFiles)
|
||||
);
|
||||
|
||||
queryClient.invalidateQueries({ queryKey: ["downloaded_files"] });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
return { deleteFile, deleteAllFiles };
|
||||
};
|
||||
@@ -9,521 +9,7 @@ import {
|
||||
getMediaInfoApi,
|
||||
getUserLibraryApi,
|
||||
} from "@jellyfin/sdk/lib/utils/api";
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import * as FileSystem from "expo-file-system";
|
||||
import { useAtom } from "jotai";
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { runningProcesses } from "./atoms/downloads";
|
||||
import { iosProfile } from "./device-profiles";
|
||||
import {
|
||||
FFmpegKit,
|
||||
FFmpegKitConfig,
|
||||
ReturnCode,
|
||||
} from "ffmpeg-kit-react-native";
|
||||
import { writeToLog } from "./log";
|
||||
|
||||
/**
|
||||
* Try to convert the downloaded file to a supported format on-device. Leveraging the capability of modern phones.
|
||||
*
|
||||
* ⚠️ This function does not work, and the app crashes when running it.
|
||||
*/
|
||||
// const convertAndReplaceVideo = async (id: string) => {
|
||||
// const input = FileSystem.documentDirectory + id;
|
||||
// const output = FileSystem.documentDirectory + id + "_tmp.mp4";
|
||||
|
||||
// const command = `-i ${input} -c:v h264 -profile:v baseline -level 3.0 -pix_fmt yuv420p -c:a aac -b:a 128k -movflags +faststart ${output}`;
|
||||
// try {
|
||||
// const session = await FFmpegKit.execute(command);
|
||||
// const rc: ReturnCode = await session.getReturnCode();
|
||||
// if (ReturnCode.isSuccess(rc)) {
|
||||
// console.log("Conversion successful, replacing the original file");
|
||||
|
||||
// await FileSystem.moveAsync({
|
||||
// from: output,
|
||||
// to: input,
|
||||
// });
|
||||
|
||||
// console.log("Replacement successful");
|
||||
// } else {
|
||||
// console.log("Conversion failed");
|
||||
// }
|
||||
// } catch (error) {
|
||||
// console.error("Error during conversion", error);
|
||||
// }
|
||||
// };
|
||||
|
||||
export const useDownloadMedia = (api: Api | null, userId?: string | null) => {
|
||||
const [isDownloading, setIsDownloading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [_, setProgress] = useAtom(runningProcesses);
|
||||
const downloadResumableRef = useRef<FileSystem.DownloadResumable | null>(
|
||||
null
|
||||
);
|
||||
|
||||
const downloadMedia = useCallback(
|
||||
async (item: BaseItemDto | null) => {
|
||||
if (!item?.Id || !api || !userId) {
|
||||
setError("Invalid item or API");
|
||||
return false;
|
||||
}
|
||||
|
||||
setIsDownloading(true);
|
||||
setError(null);
|
||||
setProgress({
|
||||
item,
|
||||
progress: 0,
|
||||
});
|
||||
|
||||
const itemId = item.Id;
|
||||
|
||||
try {
|
||||
const filename = `${itemId}`;
|
||||
const fileUri = `${FileSystem.documentDirectory}${filename}`;
|
||||
|
||||
const url = `${api.basePath}/Items/${itemId}/File`;
|
||||
|
||||
downloadResumableRef.current = FileSystem.createDownloadResumable(
|
||||
url,
|
||||
fileUri,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `MediaBrowser DeviceId="${api.deviceInfo.id}", Token="${api.accessToken}"`,
|
||||
},
|
||||
},
|
||||
(downloadProgress) => {
|
||||
const currentProgress =
|
||||
downloadProgress.totalBytesWritten /
|
||||
downloadProgress.totalBytesExpectedToWrite;
|
||||
|
||||
setProgress({
|
||||
item,
|
||||
progress: currentProgress * 100,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
const res = await downloadResumableRef.current.downloadAsync();
|
||||
const uri = res?.uri;
|
||||
|
||||
console.log("File downloaded to:", uri);
|
||||
|
||||
const currentFiles: BaseItemDto[] = JSON.parse(
|
||||
(await AsyncStorage.getItem("downloaded_files")) ?? "[]"
|
||||
);
|
||||
|
||||
const updatedFiles = [
|
||||
...currentFiles.filter((file) => file.Id !== itemId),
|
||||
item,
|
||||
];
|
||||
|
||||
await AsyncStorage.setItem(
|
||||
"downloaded_files",
|
||||
JSON.stringify(updatedFiles)
|
||||
);
|
||||
|
||||
setIsDownloading(false);
|
||||
setProgress(null);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error downloading media:", error);
|
||||
setError("Failed to download media");
|
||||
setIsDownloading(false);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[api, setProgress]
|
||||
);
|
||||
|
||||
const cancelDownload = useCallback(async () => {
|
||||
if (downloadResumableRef.current) {
|
||||
try {
|
||||
await downloadResumableRef.current.pauseAsync();
|
||||
setIsDownloading(false);
|
||||
setError("Download cancelled");
|
||||
setProgress(null);
|
||||
downloadResumableRef.current = null;
|
||||
} catch (error) {
|
||||
console.error("Error cancelling download:", error);
|
||||
setError("Failed to cancel download");
|
||||
}
|
||||
}
|
||||
}, [setProgress]);
|
||||
|
||||
return { downloadMedia, isDownloading, error, cancelDownload };
|
||||
};
|
||||
|
||||
export const useRemuxHlsToMp4 = (url: string, item: BaseItemDto) => {
|
||||
const [_, setProgress] = useAtom(runningProcesses);
|
||||
|
||||
if (!item.Id || !item.Name) {
|
||||
writeToLog("ERROR", "useRemuxHlsToMp4 ~ missing arguments");
|
||||
throw new Error("Item must have an Id and Name");
|
||||
}
|
||||
|
||||
const output = `${FileSystem.documentDirectory}${item.Id}.mp4`;
|
||||
|
||||
const command = `-y -fflags +genpts -i ${url} -c copy -bufsize 10M -max_muxing_queue_size 4096 ${output}`;
|
||||
|
||||
const startRemuxing = useCallback(async () => {
|
||||
if (!item.Id || !item.Name) {
|
||||
writeToLog(
|
||||
"ERROR",
|
||||
"useRemuxHlsToMp4 ~ startRemuxing ~ missing arguments"
|
||||
);
|
||||
throw new Error("Item must have an Id and Name");
|
||||
}
|
||||
|
||||
writeToLog(
|
||||
"INFO",
|
||||
`useRemuxHlsToMp4 ~ startRemuxing for item ${item.Id} with url ${url}`
|
||||
);
|
||||
|
||||
try {
|
||||
setProgress({
|
||||
item,
|
||||
progress: 0,
|
||||
});
|
||||
|
||||
FFmpegKitConfig.enableStatisticsCallback((statistics) => {
|
||||
let percentage = 0;
|
||||
|
||||
const videoLength =
|
||||
(item.MediaSources?.[0].RunTimeTicks || 0) / 10000000; // In seconds
|
||||
const fps = item.MediaStreams?.[0].RealFrameRate || 25;
|
||||
const totalFrames = videoLength * fps;
|
||||
|
||||
const processedFrames = statistics.getVideoFrameNumber();
|
||||
const speed = statistics.getSpeed();
|
||||
|
||||
if (totalFrames > 0) {
|
||||
percentage = Math.floor((processedFrames / totalFrames) * 100);
|
||||
}
|
||||
|
||||
setProgress((prev) => {
|
||||
return prev?.item.Id === item.Id!
|
||||
? { ...prev, progress: percentage, speed }
|
||||
: prev;
|
||||
});
|
||||
});
|
||||
|
||||
await FFmpegKit.executeAsync(command, async (session) => {
|
||||
const returnCode = await session.getReturnCode();
|
||||
if (returnCode.isValueSuccess()) {
|
||||
const currentFiles: BaseItemDto[] = JSON.parse(
|
||||
(await AsyncStorage.getItem("downloaded_files")) || "[]"
|
||||
);
|
||||
|
||||
const otherItems = currentFiles.filter((i) => i.Id !== item.Id);
|
||||
|
||||
await AsyncStorage.setItem(
|
||||
"downloaded_files",
|
||||
JSON.stringify([...otherItems, item])
|
||||
);
|
||||
|
||||
writeToLog(
|
||||
"INFO",
|
||||
`useRemuxHlsToMp4 ~ remuxing completed successfully for item: ${item.Name}`
|
||||
);
|
||||
setProgress(null);
|
||||
} else if (returnCode.isValueError()) {
|
||||
console.error("Failed to remux:");
|
||||
writeToLog(
|
||||
"ERROR",
|
||||
`useRemuxHlsToMp4 ~ remuxing failed for item: ${item.Name}`
|
||||
);
|
||||
setProgress(null);
|
||||
} else if (returnCode.isValueCancel()) {
|
||||
console.log("Remuxing was cancelled");
|
||||
writeToLog(
|
||||
"INFO",
|
||||
`useRemuxHlsToMp4 ~ remuxing was canceled for item: ${item.Name}`
|
||||
);
|
||||
setProgress(null);
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to remux:", error);
|
||||
writeToLog(
|
||||
"ERROR",
|
||||
`useRemuxHlsToMp4 ~ remuxing failed for item: ${item.Name}`
|
||||
);
|
||||
}
|
||||
}, [output, item, command]);
|
||||
|
||||
const cancelRemuxing = useCallback(async () => {
|
||||
FFmpegKit.cancel();
|
||||
setProgress(null);
|
||||
console.log("Remuxing cancelled");
|
||||
}, []);
|
||||
|
||||
return { startRemuxing, cancelRemuxing };
|
||||
};
|
||||
|
||||
export const markAsNotPlayed = async ({
|
||||
api,
|
||||
itemId,
|
||||
userId,
|
||||
}: {
|
||||
api?: Api | null;
|
||||
itemId?: string | null;
|
||||
userId?: string | null;
|
||||
}) => {
|
||||
if (!itemId || !userId || !api) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await api.axiosInstance.delete(
|
||||
`${api.basePath}/UserPlayedItems/${itemId}`,
|
||||
{
|
||||
params: {
|
||||
userId,
|
||||
},
|
||||
headers: {
|
||||
Authorization: `MediaBrowser DeviceId="${api.deviceInfo.id}", Token="${api.accessToken}"`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (response.status === 200) return true;
|
||||
return false;
|
||||
} catch (error) {
|
||||
const e = error as any;
|
||||
console.error("Failed to report playback progress", e.message, e.status);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const markAsPlayed = async ({
|
||||
api,
|
||||
item,
|
||||
userId,
|
||||
}: {
|
||||
api?: Api | null;
|
||||
item?: BaseItemDto | null;
|
||||
userId?: string | null;
|
||||
}) => {
|
||||
if (!item || !userId || !api || !item.RunTimeTicks) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const itemId = item.Id;
|
||||
|
||||
try {
|
||||
const response = await api.axiosInstance.post(
|
||||
`${api.basePath}/UserPlayedItems/${itemId}`,
|
||||
{
|
||||
userId,
|
||||
datePlayed: new Date().toISOString(),
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
Authorization: `MediaBrowser DeviceId="${api.deviceInfo.id}", Token="${api.accessToken}"`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const response2 = await api.axiosInstance.post(
|
||||
`${api.basePath}/Sessions/Playing/Progress`,
|
||||
{
|
||||
ItemId: itemId,
|
||||
PositionTicks: item.RunTimeTicks,
|
||||
MediaSourceId: itemId,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
Authorization: `MediaBrowser DeviceId="${api.deviceInfo.id}", Token="${api.accessToken}"`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
console.log(response, response2);
|
||||
|
||||
if (response.status === 200) return true;
|
||||
return false;
|
||||
} catch (error) {
|
||||
const e = error as any;
|
||||
console.error("Failed to mark as played:", {
|
||||
message: e.message,
|
||||
status: e.response?.status,
|
||||
statusText: e.response?.statusText,
|
||||
url: e.config?.url,
|
||||
method: e.config?.method,
|
||||
data: e.response?.data,
|
||||
headers: e.response?.headers,
|
||||
});
|
||||
|
||||
if (e.response) {
|
||||
// The request was made and the server responded with a status code
|
||||
// that falls out of the range of 2xx
|
||||
console.error("Server responded with error:", e.response.data);
|
||||
} else if (e.request) {
|
||||
// The request was made but no response was received
|
||||
console.error("No response received from server");
|
||||
} else {
|
||||
// Something happened in setting up the request that triggered an Error
|
||||
console.error("Error setting up the request:", e.message);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const nextUp = async ({
|
||||
itemId,
|
||||
userId,
|
||||
api,
|
||||
}: {
|
||||
itemId?: string | null;
|
||||
userId?: string | null;
|
||||
api?: Api | null;
|
||||
}) => {
|
||||
if (!userId || !api) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await api.axiosInstance.get(
|
||||
`${api.basePath}/Shows/NextUp`,
|
||||
{
|
||||
params: {
|
||||
SeriesId: itemId ? itemId : undefined,
|
||||
UserId: userId,
|
||||
Fields: "MediaSourceCount",
|
||||
},
|
||||
headers: {
|
||||
Authorization: `MediaBrowser DeviceId="${api.deviceInfo.id}", Token="${api.accessToken}"`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
return response?.data.Items as BaseItemDto[];
|
||||
} catch (error) {
|
||||
const e = error as any;
|
||||
console.error("Failed to get next up", e.message, e.status);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const reportPlaybackStopped = async ({
|
||||
api,
|
||||
sessionId,
|
||||
itemId,
|
||||
positionTicks,
|
||||
}: {
|
||||
api: Api | null | undefined;
|
||||
sessionId: string | null | undefined;
|
||||
itemId: string | null | undefined;
|
||||
positionTicks: number | null | undefined;
|
||||
}) => {
|
||||
if (!api || !sessionId || !itemId || !positionTicks) {
|
||||
console.log("Missing required parameters", {
|
||||
api,
|
||||
sessionId,
|
||||
itemId,
|
||||
positionTicks,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await api.axiosInstance.delete(`${api.basePath}/PlayingItems/${itemId}`, {
|
||||
params: {
|
||||
playSessionId: sessionId,
|
||||
positionTicks: Math.round(positionTicks),
|
||||
mediaSourceId: itemId,
|
||||
},
|
||||
headers: {
|
||||
Authorization: `MediaBrowser DeviceId="${api.deviceInfo.id}", Token="${api.accessToken}"`,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to report playback progress", error);
|
||||
}
|
||||
};
|
||||
|
||||
export const reportPlaybackProgress = async ({
|
||||
api,
|
||||
sessionId,
|
||||
itemId,
|
||||
positionTicks,
|
||||
}: {
|
||||
api: Api | null | undefined;
|
||||
sessionId: string | null | undefined;
|
||||
itemId: string | null | undefined;
|
||||
positionTicks: number | null | undefined;
|
||||
}) => {
|
||||
if (!api || !sessionId || !itemId || !positionTicks) {
|
||||
console.log("Missing required parameters", {
|
||||
api,
|
||||
sessionId,
|
||||
itemId,
|
||||
positionTicks,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await api.axiosInstance.post(
|
||||
`${api.basePath}/Sessions/Playing/Progress`,
|
||||
{
|
||||
ItemId: itemId,
|
||||
PlaySessionId: sessionId,
|
||||
IsPaused: false,
|
||||
PositionTicks: Math.round(positionTicks),
|
||||
CanSeek: true,
|
||||
MediaSourceId: itemId,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
Authorization: `MediaBrowser DeviceId="${api.deviceInfo.id}", Token="${api.accessToken}"`,
|
||||
},
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Failed to report playback progress", error);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches the media info for a given item.
|
||||
*
|
||||
* @param {Api} api - The Jellyfin API instance.
|
||||
* @param {string} itemId - The ID of the media to fetch info for.
|
||||
* @param {string} userId - The ID of the user to fetch info for.
|
||||
*
|
||||
* @returns {Promise<BaseItemDto>} - The media info.
|
||||
*/
|
||||
export const getUserItemData = async ({
|
||||
api,
|
||||
itemId,
|
||||
userId,
|
||||
}: {
|
||||
api: Api | null | undefined;
|
||||
itemId: string | null | undefined;
|
||||
userId: string | null | undefined;
|
||||
}) => {
|
||||
if (!api || !itemId || !userId) {
|
||||
return null;
|
||||
}
|
||||
return (await getUserLibraryApi(api).getItem({ itemId, userId })).data;
|
||||
};
|
||||
|
||||
export const getPlaybackInfo = async (
|
||||
api?: Api | null | undefined,
|
||||
itemId?: string | null | undefined,
|
||||
userId?: string | null | undefined
|
||||
) => {
|
||||
if (!api || !itemId || !userId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const a = await getMediaInfoApi(api).getPlaybackInfo({
|
||||
itemId,
|
||||
userId,
|
||||
});
|
||||
|
||||
return a.data;
|
||||
};
|
||||
import ios12 from "./profiles/ios12";
|
||||
|
||||
/**
|
||||
* Retrieves the playback URL for the given item ID and user ID.
|
||||
@@ -536,7 +22,7 @@ export const getPlaybackInfo = async (
|
||||
export const getPlaybackUrl = async (
|
||||
api: Api,
|
||||
itemId: string,
|
||||
userId: string
|
||||
userId: string,
|
||||
): Promise<string> => {
|
||||
const playbackData = await getMediaInfoApi(api).getPlaybackInfo({
|
||||
itemId,
|
||||
@@ -546,7 +32,7 @@ export const getPlaybackUrl = async (
|
||||
const mediaSources = playbackData.data?.MediaSources;
|
||||
if (!mediaSources || mediaSources.length === 0) {
|
||||
throw new Error(
|
||||
"No media sources available for the requested item and user."
|
||||
"No media sources available for the requested item and user.",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -586,7 +72,7 @@ export const getPlaybackUrl = async (
|
||||
*/
|
||||
export const getItemById = async (
|
||||
api?: Api | null | undefined,
|
||||
itemId?: string | null | undefined
|
||||
itemId?: string | null | undefined,
|
||||
): Promise<BaseItemDto | undefined> => {
|
||||
if (!api || !itemId) {
|
||||
return undefined;
|
||||
@@ -615,7 +101,7 @@ export const getStreamUrl = async ({
|
||||
startTimeTicks = 0,
|
||||
maxStreamingBitrate,
|
||||
sessionData,
|
||||
deviceProfile = iosProfile,
|
||||
deviceProfile = ios12,
|
||||
}: {
|
||||
api: Api | null | undefined;
|
||||
item: BaseItemDto | null | undefined;
|
||||
@@ -647,7 +133,7 @@ export const getStreamUrl = async ({
|
||||
headers: {
|
||||
Authorization: `MediaBrowser DeviceId="${api.deviceInfo.id}", Token="${api.accessToken}"`,
|
||||
},
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const mediaSource = response.data.MediaSources?.[0] as MediaSourceInfo;
|
||||
@@ -865,7 +351,7 @@ function buildStreamUrl({
|
||||
Tag: tag,
|
||||
});
|
||||
return new URL(
|
||||
`${serverUrl}/Videos/${itemId}/stream.mp4?${streamParams.toString()}`
|
||||
`${serverUrl}/Videos/${itemId}/stream.mp4?${streamParams.toString()}`,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
18
utils/jellyfin/image/getPrimaryImage.ts
Normal file
18
utils/jellyfin/image/getPrimaryImage.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Api } from "@jellyfin/sdk";
|
||||
import { getImageApi } from "@jellyfin/sdk/lib/utils/api";
|
||||
|
||||
export const getPrimaryImage = async (
|
||||
api: Api,
|
||||
itemId: string,
|
||||
): Promise<string> => {
|
||||
const image = await getImageApi(api).getItemImage({
|
||||
itemId,
|
||||
imageType: "Primary",
|
||||
quality: 90,
|
||||
width: 1000,
|
||||
});
|
||||
|
||||
console.log("getPrimaryImage ~", image.data);
|
||||
|
||||
return image.data;
|
||||
};
|
||||
46
utils/jellyfin/items/getUserItemData.ts
Normal file
46
utils/jellyfin/items/getUserItemData.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { Api } from "@jellyfin/sdk";
|
||||
import {
|
||||
getMediaInfoApi,
|
||||
getUserLibraryApi,
|
||||
} from "@jellyfin/sdk/lib/utils/api";
|
||||
|
||||
/**
|
||||
* Fetches the media info for a given item.
|
||||
*
|
||||
* @param {Api} api - The Jellyfin API instance.
|
||||
* @param {string} itemId - The ID of the media to fetch info for.
|
||||
* @param {string} userId - The ID of the user to fetch info for.
|
||||
*
|
||||
* @returns {Promise<BaseItemDto>} - The media info.
|
||||
*/
|
||||
export const getUserItemData = async ({
|
||||
api,
|
||||
itemId,
|
||||
userId,
|
||||
}: {
|
||||
api: Api | null | undefined;
|
||||
itemId: string | null | undefined;
|
||||
userId: string | null | undefined;
|
||||
}) => {
|
||||
if (!api || !itemId || !userId) {
|
||||
return null;
|
||||
}
|
||||
return (await getUserLibraryApi(api).getItem({ itemId, userId })).data;
|
||||
};
|
||||
|
||||
export const getPlaybackInfo = async (
|
||||
api?: Api | null | undefined,
|
||||
itemId?: string | null | undefined,
|
||||
userId?: string | null | undefined,
|
||||
) => {
|
||||
if (!api || !itemId || !userId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const a = await getMediaInfoApi(api).getPlaybackInfo({
|
||||
itemId,
|
||||
userId,
|
||||
});
|
||||
|
||||
return a.data;
|
||||
};
|
||||
8
utils/jellyfin/jellyfin.ts
Normal file
8
utils/jellyfin/jellyfin.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Api } from "@jellyfin/sdk";
|
||||
|
||||
/**
|
||||
* Generates the authorization headers for Jellyfin API requests.
|
||||
*/
|
||||
export const getAuthHeaders = (api: Api) => ({
|
||||
Authorization: `MediaBrowser DeviceId="${api.deviceInfo.id}", Token="${api.accessToken}"`,
|
||||
});
|
||||
47
utils/jellyfin/playstate/markAsNotPlayed.ts
Normal file
47
utils/jellyfin/playstate/markAsNotPlayed.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { Api } from "@jellyfin/sdk";
|
||||
import { AxiosError } from "axios";
|
||||
|
||||
interface MarkAsNotPlayedParams {
|
||||
api: Api | null | undefined;
|
||||
itemId: string | null | undefined;
|
||||
userId: string | null | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a media item as not played for a specific user.
|
||||
*
|
||||
* @param params - The parameters for marking an item as not played
|
||||
* @returns A promise that resolves to true if the operation was successful, false otherwise
|
||||
*/
|
||||
export const markAsNotPlayed = async ({
|
||||
api,
|
||||
itemId,
|
||||
userId,
|
||||
}: MarkAsNotPlayedParams): Promise<boolean> => {
|
||||
if (!api || !itemId || !userId) {
|
||||
console.error("Invalid parameters for markAsNotPlayed");
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await api.axiosInstance.delete(
|
||||
`${api.basePath}/UserPlayedItems/${itemId}`,
|
||||
{
|
||||
params: { userId },
|
||||
headers: {
|
||||
Authorization: `MediaBrowser DeviceId="${api.deviceInfo.id}", Token="${api.accessToken}"`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return response.status === 200;
|
||||
} catch (error) {
|
||||
const axiosError = error as AxiosError;
|
||||
console.error(
|
||||
"Failed to mark item as not played:",
|
||||
axiosError.message,
|
||||
axiosError.response?.status,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
50
utils/jellyfin/playstate/markAsPlayed.ts
Normal file
50
utils/jellyfin/playstate/markAsPlayed.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { Api } from "@jellyfin/sdk";
|
||||
import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
import { AxiosError } from "axios";
|
||||
import { getAuthHeaders } from "../jellyfin";
|
||||
|
||||
interface MarkAsPlayedParams {
|
||||
api: Api | null | undefined;
|
||||
item: BaseItemDto | null | undefined;
|
||||
userId: string | null | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a media item as played and updates its progress to completion.
|
||||
*
|
||||
* @param params - The parameters for marking an item as played
|
||||
* @returns A promise that resolves to true if the operation was successful, false otherwise
|
||||
*/
|
||||
export const markAsPlayed = async ({
|
||||
api,
|
||||
item,
|
||||
userId,
|
||||
}: MarkAsPlayedParams): Promise<boolean> => {
|
||||
if (!api || !item?.Id || !userId || !item.RunTimeTicks) {
|
||||
console.error("Invalid parameters for markAsPlayed");
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const [playedResponse, progressResponse] = await Promise.all([
|
||||
api.axiosInstance.post(
|
||||
`${api.basePath}/UserPlayedItems/${item.Id}`,
|
||||
{ userId, datePlayed: new Date().toISOString() },
|
||||
{ headers: getAuthHeaders(api) },
|
||||
),
|
||||
api.axiosInstance.post(
|
||||
`${api.basePath}/Sessions/Playing/Progress`,
|
||||
{
|
||||
ItemId: item.Id,
|
||||
PositionTicks: item.RunTimeTicks,
|
||||
MediaSourceId: item.Id,
|
||||
},
|
||||
{ headers: getAuthHeaders(api) },
|
||||
),
|
||||
]);
|
||||
|
||||
return playedResponse.status === 200 && progressResponse.status === 200;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
44
utils/jellyfin/playstate/reportPlaybackProgress.ts
Normal file
44
utils/jellyfin/playstate/reportPlaybackProgress.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { Api } from "@jellyfin/sdk";
|
||||
import { AxiosError } from "axios";
|
||||
import { getAuthHeaders } from "../jellyfin";
|
||||
|
||||
interface ReportPlaybackProgressParams {
|
||||
api: Api | null | undefined;
|
||||
sessionId: string | null | undefined;
|
||||
itemId: string | null | undefined;
|
||||
positionTicks: number | null | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports playback progress to the Jellyfin server.
|
||||
*
|
||||
* @param params - The parameters for reporting playback progress
|
||||
* @throws {Error} If any required parameter is missing
|
||||
*/
|
||||
export const reportPlaybackProgress = async ({
|
||||
api,
|
||||
sessionId,
|
||||
itemId,
|
||||
positionTicks,
|
||||
}: ReportPlaybackProgressParams): Promise<void> => {
|
||||
if (!api || !sessionId || !itemId || positionTicks == null) {
|
||||
throw new Error("Missing required parameters for reportPlaybackProgress");
|
||||
}
|
||||
|
||||
try {
|
||||
await api.axiosInstance.post(
|
||||
`${api.basePath}/Sessions/Playing/Progress`,
|
||||
{
|
||||
ItemId: itemId,
|
||||
PlaySessionId: sessionId,
|
||||
IsPaused: false,
|
||||
PositionTicks: Math.round(positionTicks),
|
||||
CanSeek: true,
|
||||
MediaSourceId: itemId,
|
||||
},
|
||||
{ headers: getAuthHeaders(api) },
|
||||
);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
};
|
||||
61
utils/jellyfin/playstate/reportPlaybackStopped.ts
Normal file
61
utils/jellyfin/playstate/reportPlaybackStopped.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { Api } from "@jellyfin/sdk";
|
||||
import { AxiosError } from "axios";
|
||||
import { getAuthHeaders } from "../jellyfin";
|
||||
|
||||
interface PlaybackStoppedParams {
|
||||
api: Api | null | undefined;
|
||||
sessionId: string | null | undefined;
|
||||
itemId: string | null | undefined;
|
||||
positionTicks: number | null | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports playback stopped event to the Jellyfin server.
|
||||
*
|
||||
* @param {PlaybackStoppedParams} params - The parameters for the report.
|
||||
* @param {Api} params.api - The Jellyfin API instance.
|
||||
* @param {string} params.sessionId - The session ID.
|
||||
* @param {string} params.itemId - The item ID.
|
||||
* @param {number} params.positionTicks - The playback position in ticks.
|
||||
*/
|
||||
export const reportPlaybackStopped = async ({
|
||||
api,
|
||||
sessionId,
|
||||
itemId,
|
||||
positionTicks,
|
||||
}: PlaybackStoppedParams): Promise<void> => {
|
||||
// Validate input parameters
|
||||
if (!api || !sessionId || !itemId || !positionTicks) {
|
||||
console.log("Missing required parameters", {
|
||||
api,
|
||||
sessionId,
|
||||
itemId,
|
||||
positionTicks,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = `${api.basePath}/PlayingItems/${itemId}`;
|
||||
const params = {
|
||||
playSessionId: sessionId,
|
||||
positionTicks: Math.round(positionTicks),
|
||||
mediaSourceId: itemId,
|
||||
};
|
||||
const headers = getAuthHeaders(api);
|
||||
|
||||
// Send DELETE request to report playback stopped
|
||||
await api.axiosInstance.delete(url, { params, headers });
|
||||
} catch (error) {
|
||||
// Log the error with additional context
|
||||
if (error instanceof AxiosError) {
|
||||
console.error(
|
||||
"Failed to report playback progress",
|
||||
error.message,
|
||||
error.response?.data,
|
||||
);
|
||||
} else {
|
||||
console.error("Failed to report playback progress", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
45
utils/jellyfin/tvshows/nextUp.ts
Normal file
45
utils/jellyfin/tvshows/nextUp.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { Api } from "@jellyfin/sdk";
|
||||
import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
import { AxiosError } from "axios";
|
||||
import { getAuthHeaders } from "../jellyfin";
|
||||
|
||||
interface NextUpParams {
|
||||
itemId?: string | null;
|
||||
userId?: string | null;
|
||||
api?: Api | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the next up episodes for a series or all series for a user.
|
||||
*
|
||||
* @param params - The parameters for fetching next up episodes
|
||||
* @returns A promise that resolves to an array of BaseItemDto representing the next up episodes
|
||||
*/
|
||||
export const nextUp = async ({
|
||||
itemId,
|
||||
userId,
|
||||
api,
|
||||
}: NextUpParams): Promise<BaseItemDto[]> => {
|
||||
if (!userId || !api) {
|
||||
console.error("Invalid parameters for nextUp: missing userId or api");
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await api.axiosInstance.get<{ Items: BaseItemDto[] }>(
|
||||
`${api.basePath}/Shows/NextUp`,
|
||||
{
|
||||
params: {
|
||||
SeriesId: itemId || undefined,
|
||||
UserId: userId,
|
||||
Fields: "MediaSourceCount",
|
||||
},
|
||||
headers: getAuthHeaders(api),
|
||||
},
|
||||
);
|
||||
|
||||
return response.data.Items;
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
130
utils/profiles/chromecast.ts
Normal file
130
utils/profiles/chromecast.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
import {
|
||||
DeviceProfile,
|
||||
DlnaProfileType,
|
||||
} from "@jellyfin/sdk/lib/generated-client/models";
|
||||
|
||||
const MediaTypes = {
|
||||
Audio: "Audio",
|
||||
Video: "Video",
|
||||
Photo: "Photo",
|
||||
Book: "Book",
|
||||
};
|
||||
|
||||
export const chromecastProfile: DeviceProfile = {
|
||||
Name: "Chromecast",
|
||||
Id: "chromecast-001",
|
||||
MaxStreamingBitrate: 4000000, // 4 Mbps
|
||||
MaxStaticBitrate: 4000000, // 4 Mbps
|
||||
MusicStreamingTranscodingBitrate: 384000, // 384 kbps
|
||||
DirectPlayProfiles: [
|
||||
{
|
||||
Container: "mp4,webm",
|
||||
Type: "Video",
|
||||
VideoCodec: "h264,vp8,vp9",
|
||||
AudioCodec: "aac,mp3,opus,vorbis",
|
||||
},
|
||||
{
|
||||
Container: "mp3",
|
||||
Type: "Audio",
|
||||
},
|
||||
{
|
||||
Container: "aac",
|
||||
Type: "Audio",
|
||||
},
|
||||
{
|
||||
Container: "flac",
|
||||
Type: "Audio",
|
||||
},
|
||||
{
|
||||
Container: "wav",
|
||||
Type: "Audio",
|
||||
},
|
||||
],
|
||||
TranscodingProfiles: [
|
||||
{
|
||||
Container: "ts",
|
||||
Type: "Video",
|
||||
VideoCodec: "h264",
|
||||
AudioCodec: "aac,mp3",
|
||||
Protocol: "hls",
|
||||
Context: "Streaming",
|
||||
MaxAudioChannels: "2",
|
||||
MinSegments: 2,
|
||||
BreakOnNonKeyFrames: true,
|
||||
},
|
||||
{
|
||||
Container: "mp4",
|
||||
Type: "Video",
|
||||
VideoCodec: "h264",
|
||||
AudioCodec: "aac",
|
||||
Protocol: "http",
|
||||
Context: "Streaming",
|
||||
MaxAudioChannels: "2",
|
||||
},
|
||||
{
|
||||
Container: "mp3",
|
||||
Type: "Audio",
|
||||
AudioCodec: "mp3",
|
||||
Protocol: "http",
|
||||
Context: "Streaming",
|
||||
MaxAudioChannels: "2",
|
||||
},
|
||||
{
|
||||
Container: "aac",
|
||||
Type: "Audio",
|
||||
AudioCodec: "aac",
|
||||
Protocol: "http",
|
||||
Context: "Streaming",
|
||||
MaxAudioChannels: "2",
|
||||
},
|
||||
],
|
||||
ContainerProfiles: [
|
||||
{
|
||||
Type: "Video",
|
||||
Container: "mp4",
|
||||
},
|
||||
{
|
||||
Type: "Video",
|
||||
Container: "webm",
|
||||
},
|
||||
],
|
||||
CodecProfiles: [
|
||||
{
|
||||
Type: "Video",
|
||||
Codec: "h264",
|
||||
Conditions: [
|
||||
{
|
||||
Condition: "LessThanEqual",
|
||||
Property: "VideoBitDepth",
|
||||
Value: "8",
|
||||
},
|
||||
{
|
||||
Condition: "LessThanEqual",
|
||||
Property: "VideoLevel",
|
||||
Value: "41",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
Type: "Video",
|
||||
Codec: "vp9",
|
||||
Conditions: [
|
||||
{
|
||||
Condition: "LessThanEqual",
|
||||
Property: "VideoBitDepth",
|
||||
Value: "10",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
SubtitleProfiles: [
|
||||
{
|
||||
Format: "vtt",
|
||||
Method: "Hls",
|
||||
},
|
||||
{
|
||||
Format: "vtt",
|
||||
Method: "External",
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -1,76 +0,0 @@
|
||||
import { MediaSourceInfo } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
|
||||
export function createVideoUrl(mediaSource: MediaSourceInfo): string {
|
||||
const baseUrl = `/videos/${mediaSource.Id}/main.m3u8`;
|
||||
const urlParams = new URLSearchParams();
|
||||
|
||||
// Extract query parameters from TranscodingUrl
|
||||
const transcodingUrlParts = mediaSource.TranscodingUrl?.split("?") ?? [];
|
||||
if (transcodingUrlParts.length > 1) {
|
||||
const queryParams = new URLSearchParams(transcodingUrlParts[1]);
|
||||
queryParams.forEach((value, key) => {
|
||||
urlParams.append(key, value);
|
||||
});
|
||||
}
|
||||
|
||||
// Add or update specific parameters based on the mediaSource object
|
||||
if (mediaSource.DefaultAudioStreamIndex !== undefined) {
|
||||
urlParams.set(
|
||||
"AudioStreamIndex",
|
||||
mediaSource.DefaultAudioStreamIndex?.toString() || ""
|
||||
);
|
||||
}
|
||||
|
||||
if (mediaSource.DefaultSubtitleStreamIndex !== undefined) {
|
||||
urlParams.set(
|
||||
"SubtitleStreamIndex",
|
||||
mediaSource.DefaultSubtitleStreamIndex?.toString() || ""
|
||||
);
|
||||
}
|
||||
|
||||
// Add information about available streams
|
||||
if (mediaSource.MediaStreams) {
|
||||
const videoStreams = mediaSource.MediaStreams.filter(
|
||||
(stream) => stream.Type === "Video"
|
||||
);
|
||||
const audioStreams = mediaSource.MediaStreams.filter(
|
||||
(stream) => stream.Type === "Audio"
|
||||
);
|
||||
const subtitleStreams = mediaSource.MediaStreams.filter(
|
||||
(stream) => stream.Type === "Subtitle"
|
||||
);
|
||||
|
||||
if (videoStreams.length > 0) {
|
||||
urlParams.set(
|
||||
"VideoStreamIndex",
|
||||
videoStreams[0].Index?.toString() || ""
|
||||
);
|
||||
}
|
||||
|
||||
if (audioStreams.length > 0) {
|
||||
const defaultAudioStream =
|
||||
audioStreams.find((stream) => stream.IsDefault) || audioStreams[0];
|
||||
urlParams.set(
|
||||
"AudioStreamIndex",
|
||||
defaultAudioStream.Index?.toString() || ""
|
||||
);
|
||||
urlParams.set("AudioCodec", defaultAudioStream.Codec || "");
|
||||
}
|
||||
|
||||
if (subtitleStreams.length > 0) {
|
||||
const defaultSubtitleStream = subtitleStreams.find(
|
||||
(stream) => stream.IsDefault
|
||||
);
|
||||
if (defaultSubtitleStream?.Index) {
|
||||
urlParams.set(
|
||||
"SubtitleStreamIndex",
|
||||
defaultSubtitleStream.Index.toString()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log("createVideoUrl ~", `${baseUrl}?${urlParams.toString()}`);
|
||||
|
||||
return `${baseUrl}?${urlParams.toString()}`;
|
||||
}
|
||||
Reference in New Issue
Block a user