diff --git a/README.md b/README.md index 01e010c2..c11f488a 100644 --- a/README.md +++ b/README.md @@ -36,32 +36,6 @@ Soon iOS users can test Streamyfin in beta via TestFlight. To join the beta prog - Ensure you have an active Jellyfin server. - Make sure your device is connected to the same network as your Jellyfin server. -### Installation - -Clone the repository: - -```bash -git clone https://github.com/your-username/streamyfin.git -``` - -Navigate to the project directory: - -```bash -cd streamyfin -``` - -Install the dependencies: - -```bash -npm install -``` - -Run the app: - -```bash -expo start -``` - ## 🙌 Contributing We welcome any help to make Streamyfin better. If you'd like to contribute, please fork the repository and submit a pull request. For major changes, it's best to open an issue first to discuss your ideas. diff --git a/app/(auth)/(tabs)/search.tsx b/app/(auth)/(tabs)/search.tsx index dc88ba89..028657f4 100644 --- a/app/(auth)/(tabs)/search.tsx +++ b/app/(auth)/(tabs)/search.tsx @@ -6,8 +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 } from "@/utils/jellyfin"; -import { getUserItemData } from "@/utils/jellyfin/items/getUserItemData"; +import { getPrimaryImageUrl } from "@/utils/jellyfin/image/getPrimaryImageUrl"; +import { getUserItemData } from "@/utils/jellyfin/user-library/getUserItemData"; import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models"; import { getSearchApi } from "@jellyfin/sdk/lib/utils/api"; import { useQuery } from "@tanstack/react-query"; @@ -117,7 +117,7 @@ export default function search() { {item.Name} diff --git a/app/(auth)/downloads.tsx b/app/(auth)/downloads.tsx index 53805108..1ccd3af8 100644 --- a/app/(auth)/downloads.tsx +++ b/app/(auth)/downloads.tsx @@ -6,21 +6,31 @@ import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models"; import AsyncStorage from "@react-native-async-storage/async-storage"; import { useQuery } from "@tanstack/react-query"; import { useEffect, useMemo } from "react"; -import { ActivityIndicator, ScrollView, View } from "react-native"; +import { + ActivityIndicator, + ScrollView, + TouchableOpacity, + View, +} from "react-native"; import * as FileSystem from "expo-file-system"; +import { useAtom } from "jotai"; +import { runningProcesses } from "@/utils/atoms/downloads"; +import { router } from "expo-router"; +import { Ionicons } from "@expo/vector-icons"; +import { FFmpegKit } from "ffmpeg-kit-react-native"; const downloads: React.FC = () => { const { data: downloadedFiles, isLoading } = useQuery({ queryKey: ["downloaded_files"], queryFn: async () => JSON.parse( - (await AsyncStorage.getItem("downloaded_files")) || "[]" + (await AsyncStorage.getItem("downloaded_files")) || "[]", ) as BaseItemDto[], }); const movies = useMemo( () => downloadedFiles?.filter((f) => f.Type === "Movie") || [], - [downloadedFiles] + [downloadedFiles], ); const groupedBySeries = useMemo(() => { @@ -39,10 +49,12 @@ const downloads: React.FC = () => { name: i.Name, codec: i.SourceType, media: i.MediaSources?.[0].Container, - })) + })), ); }, [downloadedFiles]); + const [process, setProcess] = useAtom(runningProcesses); + if (isLoading) { return ( @@ -64,6 +76,55 @@ const downloads: React.FC = () => { return ( + + Active download + {process?.item ? ( + + router.push(`/(auth)/items/${process.item.Id}/page`) + } + className="relative bg-neutral-900 border border-neutral-800 p-4 rounded-2xl overflow-hidden flex flex-row items-center justify-between" + > + + {process.item.Name} + {process.item.Type} + + + {process.progress.toFixed(0)}% + + {process.speed?.toFixed(2)}x + {process.startTime && ( + + {formatNumber( + new Date().getTime() - process.startTime.getTime(), + )} + + )} + + + { + FFmpegKit.cancel(); + setProcess(null); + }} + > + + + + + ) : ( + No active downloads + )} + {movies.length > 0 && ( @@ -88,3 +149,15 @@ const downloads: React.FC = () => { }; export default downloads; + +/* + * Format a number (Date.getTime) to a human readable string ex. 2m 34s + * @param {number} num - The number to format + * + * @returns {string} - The formatted string + */ +const formatNumber = (num: number) => { + const minutes = Math.floor(num / 60000); + const seconds = ((num % 60000) / 1000).toFixed(0); + return `${minutes}m ${seconds}s`; +}; diff --git a/app/(auth)/items/[id]/page.tsx b/app/(auth)/items/[id]/page.tsx index b407ffd2..12d50259 100644 --- a/app/(auth)/items/[id]/page.tsx +++ b/app/(auth)/items/[id]/page.tsx @@ -7,7 +7,6 @@ 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 } from "@/utils/jellyfin"; import { useQuery } from "@tanstack/react-query"; import { Image } from "expo-image"; import { router, useLocalSearchParams } from "expo-router"; @@ -20,7 +19,9 @@ import { View, } from "react-native"; import { ParallaxScrollView } from "../../../../components/ParallaxPage"; -import { getUserItemData } from "@/utils/jellyfin/items/getUserItemData"; +import { getUserItemData } from "@/utils/jellyfin/user-library/getUserItemData"; +import { getBackdropUrl } from "@/utils/jellyfin/image/getBackdropUrl"; +import { getLogoImageUrlById } from "@/utils/jellyfin/image/getLogoImageUrlById"; const page: React.FC = () => { const local = useLocalSearchParams(); @@ -45,7 +46,7 @@ const page: React.FC = () => { const backdropUrl = useMemo( () => - getBackdrop({ + getBackdropUrl({ api, item, quality: 90, @@ -55,7 +56,7 @@ const page: React.FC = () => { ); const logoUrl = useMemo( - () => (item?.Type === "Movie" ? getLogoImageById({ api, item }) : null), + () => (item?.Type === "Movie" ? getLogoImageUrlById({ api, item }) : null), [item], ); diff --git a/app/(auth)/series/[id]/page.tsx b/app/(auth)/series/[id]/page.tsx index 04f35321..effbca67 100644 --- a/app/(auth)/series/[id]/page.tsx +++ b/app/(auth)/series/[id]/page.tsx @@ -3,8 +3,9 @@ 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 } from "@/utils/jellyfin"; -import { getUserItemData } from "@/utils/jellyfin/items/getUserItemData"; +import { getBackdropUrl } from "@/utils/jellyfin/image/getBackdropUrl"; +import { getLogoImageUrlById } from "@/utils/jellyfin/image/getLogoImageUrlById"; +import { getUserItemData } from "@/utils/jellyfin/user-library/getUserItemData"; import { useQuery } from "@tanstack/react-query"; import { Image } from "expo-image"; import { useLocalSearchParams } from "expo-router"; @@ -33,7 +34,7 @@ const page: React.FC = () => { const backdropUrl = useMemo( () => - getBackdrop({ + getBackdropUrl({ api, item, quality: 90, @@ -44,7 +45,7 @@ const page: React.FC = () => { const logoUrl = useMemo( () => - getLogoImageById({ + getLogoImageUrlById({ api, item, }), diff --git a/app/(auth)/settings.tsx b/app/(auth)/settings.tsx index 696a037e..3f65e53a 100644 --- a/app/(auth)/settings.tsx +++ b/app/(auth)/settings.tsx @@ -2,7 +2,7 @@ import { Button } from "@/components/Button"; import { Text } from "@/components/common/Text"; import { ListItem } from "@/components/ListItem"; import { apiAtom, useJellyfin, userAtom } from "@/providers/JellyfinProvider"; -import { readFromLog } from "@/utils/log"; +import { clearLogs, readFromLog } from "@/utils/log"; import { useQuery } from "@tanstack/react-query"; import * as FileSystem from "expo-file-system"; import { useAtom } from "jotai"; @@ -20,6 +20,7 @@ export default function settings() { const { data: logs } = useQuery({ queryKey: ["logs"], queryFn: async () => readFromLog(), + refetchInterval: 1000, }); return ( @@ -32,9 +33,10 @@ export default function settings() { - - - + + + - Logs + Logs {logs?.map((log, index) => ( {log.message} ))} + {logs?.length === 0 && ( + No logs available + )} diff --git a/app/_layout.tsx b/app/_layout.tsx index da82317c..125cae31 100644 --- a/app/_layout.tsx +++ b/app/_layout.tsx @@ -6,13 +6,17 @@ import { useEffect, useRef } from "react"; import "react-native-reanimated"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { Provider as JotaiProvider } from "jotai"; +import { Provider as JotaiProvider, useAtom } from "jotai"; import { JellyfinProvider } from "@/providers/JellyfinProvider"; import { TouchableOpacity } from "react-native"; import Feather from "@expo/vector-icons/Feather"; import { StatusBar } from "expo-status-bar"; import { Ionicons } from "@expo/vector-icons"; +import { View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; +import { Text } from "@/components/common/Text"; +import { runningProcesses } from "@/utils/atoms/downloads"; // Prevent the splash screen from auto-hiding before asset loading is complete. SplashScreen.preventAutoHideAsync(); @@ -37,7 +41,7 @@ export default function RootLayout() { retryOnMount: true, }, }, - }) + }), ); useEffect(() => { @@ -46,6 +50,10 @@ export default function RootLayout() { } }, [loaded]); + const insets = useSafeAreaInsets(); + + const [process] = useAtom(runningProcesses); + if (!loaded) { return null; } diff --git a/components/Button.tsx b/components/Button.tsx index 616e6764..52069f13 100644 --- a/components/Button.tsx +++ b/components/Button.tsx @@ -2,7 +2,7 @@ import React, { PropsWithChildren, ReactNode, useMemo } from "react"; import { TouchableOpacity, Text, ActivityIndicator, View } from "react-native"; import * as Haptics from "expo-haptics"; -interface ButtonProps { +interface ButtonProps extends React.ComponentProps { onPress?: () => void; className?: string; textClassName?: string; @@ -26,6 +26,7 @@ export const Button: React.FC> = ({ iconLeft, children, justify = "center", + ...props }) => { const colorClasses = useMemo(() => { switch (color) { @@ -34,7 +35,7 @@ export const Button: React.FC> = ({ case "red": return "bg-red-600"; case "black": - return "bg-black border border-neutral-900"; + return "bg-neutral-900 border border-neutral-800"; } }, [color]); @@ -53,6 +54,7 @@ export const Button: React.FC> = ({ } }} disabled={disabled || loading} + {...props} > {loading ? ( diff --git a/components/Chromecast.tsx b/components/Chromecast.tsx index b1420861..9dc0afef 100644 --- a/components/Chromecast.tsx +++ b/components/Chromecast.tsx @@ -33,7 +33,6 @@ export const Chromecast: React.FC = ({ item, startTimeTicks }) => { await discoveryManager.startDiscovery(); const started = await discoveryManager.isRunning(); - console.log("started", started); console.log({ devices, diff --git a/components/ContinueWatchingPoster.tsx b/components/ContinueWatchingPoster.tsx index 9841bba5..35eae051 100644 --- a/components/ContinueWatchingPoster.tsx +++ b/components/ContinueWatchingPoster.tsx @@ -1,11 +1,11 @@ import { apiAtom } from "@/providers/JellyfinProvider"; -import { getPrimaryImage } from "@/utils/jellyfin"; import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models"; import { Image } from "expo-image"; import { useAtom } from "jotai"; import { useMemo, useState } from "react"; import { View } from "react-native"; import { WatchedIndicator } from "./WatchedIndicator"; +import { getPrimaryImageUrl } from "@/utils/jellyfin/image/getPrimaryImageUrl"; type ContinueWatchingPosterProps = { item: BaseItemDto; @@ -18,17 +18,17 @@ const ContinueWatchingPoster: React.FC = ({ const url = useMemo( () => - getPrimaryImage({ + getPrimaryImageUrl({ api, item, quality: 70, width: 300, }), - [item] + [item], ); const [progress, setProgress] = useState( - item.UserData?.PlayedPercentage || 0 + item.UserData?.PlayedPercentage || 0, ); if (!url) diff --git a/components/DownloadItem.tsx b/components/DownloadItem.tsx index 83936afd..4877804b 100644 --- a/components/DownloadItem.tsx +++ b/components/DownloadItem.tsx @@ -12,7 +12,7 @@ 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"; +import { getPlaybackInfo } from "@/utils/jellyfin/media/getPlaybackInfo"; type DownloadProps = { item: BaseItemDto; diff --git a/components/MoviePoster.tsx b/components/MoviePoster.tsx index 3c5f79d3..6ea71a48 100644 --- a/components/MoviePoster.tsx +++ b/components/MoviePoster.tsx @@ -1,12 +1,11 @@ import { apiAtom } from "@/providers/JellyfinProvider"; -import { getPrimaryImage, getPrimaryImageById } from "@/utils/jellyfin"; import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models"; -import { useQuery } from "@tanstack/react-query"; import { Image } from "expo-image"; import { useAtom } from "jotai"; import { useMemo, useState } from "react"; import { View } from "react-native"; import { WatchedIndicator } from "./WatchedIndicator"; +import { getPrimaryImageUrl } from "@/utils/jellyfin/image/getPrimaryImageUrl"; type MoviePosterProps = { item: BaseItemDto; @@ -21,15 +20,15 @@ const MoviePoster: React.FC = ({ const url = useMemo( () => - getPrimaryImage({ + getPrimaryImageUrl({ api, item, }), - [item] + [item], ); const [progress, setProgress] = useState( - item.UserData?.PlayedPercentage || 0 + item.UserData?.PlayedPercentage || 0, ); if (!url) diff --git a/components/VideoPlayer.tsx b/components/VideoPlayer.tsx index be81532e..299fc5fc 100644 --- a/components/VideoPlayer.tsx +++ b/components/VideoPlayer.tsx @@ -13,22 +13,16 @@ import React, { } from "react"; import { TouchableOpacity, View } from "react-native"; import { useCastDevice, useRemoteMediaClient } from "react-native-google-cast"; -import Video, { - OnBufferData, - OnPlaybackStateChangedData, - OnProgressData, - OnVideoErrorData, - VideoRef, -} from "react-native-video"; +import Video, { OnProgressData, VideoRef } from "react-native-video"; import * as DropdownMenu from "zeego/dropdown-menu"; import { Button } from "./Button"; import { Text } from "./common/Text"; 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"; +import { getUserItemData } from "@/utils/jellyfin/user-library/getUserItemData"; +import { getStreamUrl } from "@/utils/jellyfin/media/getStreamUrl"; type VideoPlayerProps = { itemId: string; @@ -169,7 +163,7 @@ export const VideoPlayer: React.FC = ({ () => item?.UserData?.PlaybackPositionTicks ? Math.round(item.UserData.PlaybackPositionTicks / 10000) - : null, + : 0, [item], ); diff --git a/components/downloads/EpisodeCard.tsx b/components/downloads/EpisodeCard.tsx index 8d420ee6..e8fb551c 100644 --- a/components/downloads/EpisodeCard.tsx +++ b/components/downloads/EpisodeCard.tsx @@ -5,13 +5,14 @@ import * as ContextMenu from "zeego/context-menu"; import { Text } from "../common/Text"; import { useFiles } from "@/hooks/useFiles"; import * as Haptics from "expo-haptics"; -import { useRef, useMemo } from "react"; +import { useRef, useMemo, useState } 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(null); + const [isPlaying, setIsPlaying] = useState(false); const openFile = () => { videoRef.current?.presentFullscreenPlayer(); @@ -38,7 +39,7 @@ export const EpisodeCard: React.FC<{ item: BaseItemDto }> = ({ item }) => { {item.Name} @@ -79,9 +80,17 @@ export const EpisodeCard: React.FC<{ item: BaseItemDto }> = ({ item }) => { isNetwork: false, }} controls + onFullscreenPlayerDidDismiss={() => { + setIsPlaying(false); + videoRef.current?.pause(); + }} + onFullscreenPlayerDidPresent={() => { + setIsPlaying(true); + videoRef.current?.resume(); + }} ref={videoRef} resizeMode="contain" - reportBandwidth + paused={!isPlaying} /> ); diff --git a/components/downloads/MovieCard.tsx b/components/downloads/MovieCard.tsx index c7fec199..8496d535 100644 --- a/components/downloads/MovieCard.tsx +++ b/components/downloads/MovieCard.tsx @@ -13,12 +13,13 @@ import Video, { VideoRef, } from "react-native-video"; import * as FileSystem from "expo-file-system"; -import { useMemo, useRef } from "react"; +import { useMemo, useRef, useState } from "react"; import * as Haptics from "expo-haptics"; export const MovieCard: React.FC<{ item: BaseItemDto }> = ({ item }) => { const { deleteFile } = useFiles(); const videoRef = useRef(null); + const [isPlaying, setIsPlaying] = useState(false); const openFile = () => { videoRef.current?.presentFullscreenPlayer(); @@ -45,7 +46,7 @@ export const MovieCard: React.FC<{ item: BaseItemDto }> = ({ item }) => { {item.Name} @@ -89,9 +90,17 @@ export const MovieCard: React.FC<{ item: BaseItemDto }> = ({ item }) => { isNetwork: false, }} controls + onFullscreenPlayerDidDismiss={() => { + setIsPlaying(false); + videoRef.current?.pause(); + }} + onFullscreenPlayerDidPresent={() => { + setIsPlaying(true); + videoRef.current?.resume(); + }} ref={videoRef} resizeMode="contain" - reportBandwidth + paused={!isPlaying} /> ); diff --git a/components/series/CastAndCrew.tsx b/components/series/CastAndCrew.tsx index 85a75e4a..aed9da1e 100644 --- a/components/series/CastAndCrew.tsx +++ b/components/series/CastAndCrew.tsx @@ -1,4 +1,3 @@ -import { getPrimaryImage } from "@/utils/jellyfin"; import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models"; import React from "react"; import { TouchableOpacity, View } from "react-native"; @@ -7,6 +6,7 @@ import { Text } from "../common/Text"; import Poster from "../Poster"; import { useAtom } from "jotai"; import { apiAtom } from "@/providers/JellyfinProvider"; +import { getPrimaryImageUrl } from "@/utils/jellyfin/image/getPrimaryImageUrl"; export const CastAndCrew = ({ item }: { item: BaseItemDto }) => { const [api] = useAtom(apiAtom); @@ -17,7 +17,7 @@ export const CastAndCrew = ({ item }: { item: BaseItemDto }) => { data={item.People} renderItem={(item, index) => ( - + {item.Name} {item.Role} diff --git a/components/series/CurrentSeries.tsx b/components/series/CurrentSeries.tsx index 9eb22722..3255ddb5 100644 --- a/components/series/CurrentSeries.tsx +++ b/components/series/CurrentSeries.tsx @@ -1,5 +1,4 @@ import { apiAtom } from "@/providers/JellyfinProvider"; -import { getPrimaryImage, getPrimaryImageById } from "@/utils/jellyfin"; import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models"; import { router } from "expo-router"; import { useAtom } from "jotai"; @@ -8,6 +7,7 @@ import { TouchableOpacity, View } from "react-native"; import Poster from "../Poster"; import { HorizontalScroll } from "../common/HorrizontalScroll"; import { Text } from "../common/Text"; +import { getPrimaryImageUrlById } from "@/utils/jellyfin/image/getPrimaryImageUrlById"; export const CurrentSeries = ({ item }: { item: BaseItemDto }) => { const [api] = useAtom(apiAtom); @@ -25,7 +25,7 @@ export const CurrentSeries = ({ item }: { item: BaseItemDto }) => { > {item.SeriesName} diff --git a/hooks/useRemuxHlsToMp4.ts b/hooks/useRemuxHlsToMp4.ts index 8f0b2702..1ddd31ed 100644 --- a/hooks/useRemuxHlsToMp4.ts +++ b/hooks/useRemuxHlsToMp4.ts @@ -28,11 +28,11 @@ export const useRemuxHlsToMp4 = (url: string, item: BaseItemDto) => { const startRemuxing = useCallback(async () => { writeToLog( "INFO", - `useRemuxHlsToMp4 ~ startRemuxing for item ${item.Id} with url ${url}`, + `useRemuxHlsToMp4 ~ startRemuxing for item ${item.Name}`, ); try { - setProgress({ item, progress: 0 }); + setProgress({ item, progress: 0, startTime: new Date(), speed: 0 }); FFmpegKitConfig.enableStatisticsCallback((statistics) => { const videoLength = diff --git a/utils/atoms/downloads.ts b/utils/atoms/downloads.ts index 89828aa7..143345f0 100644 --- a/utils/atoms/downloads.ts +++ b/utils/atoms/downloads.ts @@ -5,6 +5,7 @@ export type ProcessItem = { item: BaseItemDto; progress: number; speed?: number; + startTime?: Date; }; export const runningProcesses = atom(null); diff --git a/utils/jellyfin.ts b/utils/jellyfin.ts deleted file mode 100644 index c9fc48d8..00000000 --- a/utils/jellyfin.ts +++ /dev/null @@ -1,363 +0,0 @@ -import { Api } from "@jellyfin/sdk"; -import { - BaseItemDto, - BaseItemPerson, - MediaSourceInfo, - PlaybackInfoResponse, -} from "@jellyfin/sdk/lib/generated-client/models"; -import { - getMediaInfoApi, - getUserLibraryApi, -} from "@jellyfin/sdk/lib/utils/api"; -import ios12 from "./profiles/ios12"; - -/** - * Retrieves the playback URL for the given item ID and user ID. - * - * @param api - The Jellyfin API instance. - * @param itemId - The ID of the media item to retrieve playback URL for. - * @param userId - The ID of the user requesting the playback URL. - * @returns The playback URL as a string. - */ -export const getPlaybackUrl = async ( - api: Api, - itemId: string, - userId: string, -): Promise => { - const playbackData = await getMediaInfoApi(api).getPlaybackInfo({ - itemId, - userId, - }); - - const mediaSources = playbackData.data?.MediaSources; - if (!mediaSources || mediaSources.length === 0) { - throw new Error( - "No media sources available for the requested item and user.", - ); - } - - const mediaSource = mediaSources[0]; - const transcodeUrl = mediaSource.TranscodingUrl; - if (transcodeUrl) { - return transcodeUrl; - } - - // Construct a fallback URL if the TranscodingUrl is not available - const { Id, ETag } = mediaSource; - if (!Id) { - throw new Error("Media source ID is missing."); - } - - const queryParams = new URLSearchParams({ - videoBitRate: "4000", - videoCodec: "h264", - audioCodec: "aac", - container: "mp4", - SegmentContainer: "mp4", - deviceId: api.deviceInfo?.id || "", - api_key: api.accessToken || "", - Tag: ETag || "", - MediaSourceId: Id || "", - }); - - return `/Videos/${Id}/stream?${queryParams}`; -}; - -/** - * Retrieves an item by its ID from the API. - * - * @param api - The Jellyfin API instance. - * @param itemId - The ID of the item to retrieve. - * @returns The item object or undefined if no item matches the ID. - */ -export const getItemById = async ( - api?: Api | null | undefined, - itemId?: string | null | undefined, -): Promise => { - if (!api || !itemId) { - return undefined; - } - - try { - const itemData = await getUserLibraryApi(api).getItem({ itemId }); - - const item = itemData.data; - if (!item) { - console.error("No items found with the specified ID:", itemId); - return undefined; - } - - return item; - } catch (error) { - console.error("Failed to retrieve the item:", error); - throw new Error(`Failed to retrieve the item due to an error: ${error}`); - } -}; - -export const getStreamUrl = async ({ - api, - item, - userId, - startTimeTicks = 0, - maxStreamingBitrate, - sessionData, - deviceProfile = ios12, -}: { - api: Api | null | undefined; - item: BaseItemDto | null | undefined; - userId: string | null | undefined; - startTimeTicks: number; - maxStreamingBitrate?: number; - sessionData: PlaybackInfoResponse; - deviceProfile: any; -}) => { - if (!api || !userId || !item?.Id) { - return null; - } - - const itemId = item.Id; - - const response = await api.axiosInstance.post( - `${api.basePath}/Items/${itemId}/PlaybackInfo`, - { - DeviceProfile: deviceProfile, - UserId: userId, - MaxStreamingBitrate: maxStreamingBitrate, - StartTimeTicks: startTimeTicks, - EnableTranscoding: maxStreamingBitrate ? true : undefined, - AutoOpenLiveStream: true, - MediaSourceId: itemId, - AllowVideoStreamCopy: maxStreamingBitrate ? false : true, - }, - { - headers: { - Authorization: `MediaBrowser DeviceId="${api.deviceInfo.id}", Token="${api.accessToken}"`, - }, - }, - ); - - const mediaSource = response.data.MediaSources?.[0] as MediaSourceInfo; - - if (!mediaSource) { - throw new Error("No media source"); - } - if (!sessionData.PlaySessionId) { - throw new Error("no PlaySessionId"); - } - - if (mediaSource.SupportsDirectPlay) { - console.log("Using direct stream!"); - return `${api.basePath}/Videos/${itemId}/stream.mp4?playSessionId=${sessionData.PlaySessionId}&mediaSourceId=${itemId}&static=true`; - } - - console.log("Using transcoded stream!"); - return `${api.basePath}${mediaSource.TranscodingUrl}`; -}; - -/** - * Retrieves the primary image URL for a given item. - * - * @param api - The Jellyfin API instance. - * @param item - The media item to retrieve the backdrop image URL for. - * @param quality - The desired image quality (default: 90). - */ -export const getPrimaryImage = ({ - api, - item, - quality = 90, - width = 500, -}: { - api?: Api | null; - item?: BaseItemDto | BaseItemPerson | null; - quality?: number | null; - width?: number | null; -}) => { - if (!item || !api) { - return null; - } - - if (!isBaseItemDto(item)) { - return `${api?.basePath}/Items/${item?.Id}/Images/Primary`; - } - - const backdropTag = item.BackdropImageTags?.[0]; - const primaryTag = item.ImageTags?.["Primary"]; - - const params = new URLSearchParams({ - fillWidth: width ? String(width) : "500", - quality: quality ? String(quality) : "90", - }); - - if (primaryTag) { - params.set("tag", primaryTag); - } else if (backdropTag) { - params.set("tag", backdropTag); - } - - return `${api?.basePath}/Items/${ - item.Id - }/Images/Primary?${params.toString()}`; -}; - -/** - * Retrieves the primary image URL for a given item. - * - * @param api - The Jellyfin API instance. - * @param item - The media item to retrieve the backdrop image URL for. - * @param quality - The desired image quality (default: 90). - */ -export const getPrimaryImageById = ({ - api, - id, - quality = 90, - width = 500, -}: { - api?: Api | null; - id?: string | null; - quality?: number | null; - width?: number | null; -}) => { - if (!id) { - return null; - } - - const params = new URLSearchParams({ - fillWidth: width ? String(width) : "500", - quality: quality ? String(quality) : "90", - }); - - return `${api?.basePath}/Items/${id}/Images/Primary?${params.toString()}`; -}; - -function isBaseItemDto(item: any): item is BaseItemDto { - return item && "BackdropImageTags" in item && "ImageTags" in item; -} - -/** - * Retrieves the primary image URL for a given item. - * - * @param api - The Jellyfin API instance. - * @param item - The media item to retrieve the backdrop image URL for. - * @param quality - The desired image quality (default: 10). - */ -export const getLogoImageById = ({ - api, - item, -}: { - api?: Api | null; - item?: BaseItemDto | null; -}) => { - if (!api || !item) { - return null; - } - - const imageTags = item.ImageTags?.["Logo"]; - - if (!imageTags) return null; - - const params = new URLSearchParams(); - - params.append("tag", imageTags); - params.append("quality", "90"); - params.append("fillHeight", "130"); - - return `${api.basePath}/Items/${item.Id}/Images/Logo?${params.toString()}`; -}; - -/** - * Retrieves the primary image URL for a given item. - * - * @param api - The Jellyfin API instance. - * @param item - The media item to retrieve the backdrop image URL for. - * @param quality - The desired image quality (default: 10). - */ -export const getBackdrop = ({ - api, - item, - quality, - width, -}: { - api?: Api | null; - item?: BaseItemDto | null; - quality?: number; - width?: number; -}) => { - if (!api || !item) { - return null; - } - - const backdropImageTags = item.BackdropImageTags?.[0]; - - const params = new URLSearchParams(); - - if (quality) { - params.append("quality", quality.toString()); - } - - if (width) { - params.append("fillWidth", width.toString()); - } - - if (backdropImageTags) { - params.append("tag", backdropImageTags); - return `${api.basePath}/Items/${ - item.Id - }/Images/Backdrop/0?${params.toString()}`; - } else { - return getPrimaryImage({ api, item, quality, width }); - } -}; - -/** - * Builds a stream URL for the given item ID, user ID, and other parameters. - * - * @param {object} options - Options to build the stream URL. - * @param {string} options.deviceId - The device ID of the requesting client. - * @param {string} options.apiKey - The API key used for authentication. - * @param {string} options.sessionId - The session ID of the user requesting the stream. - * @param {string} options.itemId - The ID of the media item to retrieve the stream URL for. - * @param {string} options.serverUrl - The base URL of the Jellyfin server. - * @param {string} options.mediaSourceId - The ID of the media source requested. - * @param {string} options.tag - The ETag tag of the media source. - * - * @returns {URL} A URL that can be used to stream the media item. - */ -function buildStreamUrl({ - deviceId, - apiKey, - sessionId, - itemId, - serverUrl, - mediaSourceId, - tag, -}: { - deviceId: string; - apiKey: string; - sessionId: string; - itemId: string; - serverUrl: string; - mediaSourceId: string; - tag: string; -}): URL { - const streamParams = new URLSearchParams({ - Static: "true", - deviceId, - api_key: apiKey, - playSessionId: sessionId, - videoCodec: "h264", - audioCodec: "aac,mp3,ac3,eac3,flac,alac", - maxAudioChannels: "6", - mediaSourceId, - Tag: tag, - }); - return new URL( - `${serverUrl}/Videos/${itemId}/stream.mp4?${streamParams.toString()}`, - ); -} - -export const bitrateToString = (bitrate: number) => { - const kbps = bitrate / 1000; - const mbps = (bitrate / 1000000).toFixed(2); - - return `${mbps} Mb/s`; -}; diff --git a/utils/jellyfin/image/getBackdropUrl.ts b/utils/jellyfin/image/getBackdropUrl.ts new file mode 100644 index 00000000..7fdf7efe --- /dev/null +++ b/utils/jellyfin/image/getBackdropUrl.ts @@ -0,0 +1,47 @@ +import { Api } from "@jellyfin/sdk"; +import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models"; +import { getPrimaryImageUrl } from "./getPrimaryImageUrl"; + +/** + * Retrieves the primary image URL for a given item. + * + * @param api - The Jellyfin API instance. + * @param item - The media item to retrieve the backdrop image URL for. + * @param quality - The desired image quality (default: 10). + */ +export const getBackdropUrl = ({ + api, + item, + quality, + width, +}: { + api?: Api | null; + item?: BaseItemDto | null; + quality?: number; + width?: number; +}) => { + if (!api || !item) { + return null; + } + + const backdropImageTags = item.BackdropImageTags?.[0]; + + const params = new URLSearchParams(); + + if (quality) { + params.append("quality", quality.toString()); + } + + if (width) { + params.append("fillWidth", width.toString()); + } + + if (backdropImageTags) { + params.append("tag", backdropImageTags); + return `${api.basePath}/Items/${ + item.Id + }/Images/Backdrop/0?${params.toString()}`; + } else { + return getPrimaryImageUrl({ api, item, quality, width }); + } +}; diff --git a/utils/jellyfin/image/getLogoImageUrlById.ts b/utils/jellyfin/image/getLogoImageUrlById.ts new file mode 100644 index 00000000..5cdb410f --- /dev/null +++ b/utils/jellyfin/image/getLogoImageUrlById.ts @@ -0,0 +1,33 @@ +import { Api } from "@jellyfin/sdk"; +import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models"; + +/** + * Retrieves the primary image URL for a given item. + * + * @param api - The Jellyfin API instance. + * @param item - The media item to retrieve the backdrop image URL for. + * @param quality - The desired image quality (default: 10). + */ +export const getLogoImageUrlById = ({ + api, + item, +}: { + api?: Api | null; + item?: BaseItemDto | null; +}) => { + if (!api || !item) { + return null; + } + + const imageTags = item.ImageTags?.["Logo"]; + + if (!imageTags) return null; + + const params = new URLSearchParams(); + + params.append("tag", imageTags); + params.append("quality", "90"); + params.append("fillHeight", "130"); + + return `${api.basePath}/Items/${item.Id}/Images/Logo?${params.toString()}`; +}; diff --git a/utils/jellyfin/image/getPrimaryImage.ts b/utils/jellyfin/image/getPrimaryImage.ts deleted file mode 100644 index 0058c7ce..00000000 --- a/utils/jellyfin/image/getPrimaryImage.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Api } from "@jellyfin/sdk"; -import { getImageApi } from "@jellyfin/sdk/lib/utils/api"; - -export const getPrimaryImage = async ( - api: Api, - itemId: string, -): Promise => { - const image = await getImageApi(api).getItemImage({ - itemId, - imageType: "Primary", - quality: 90, - width: 1000, - }); - - console.log("getPrimaryImage ~", image.data); - - return image.data; -}; diff --git a/utils/jellyfin/image/getPrimaryImageUrl.ts b/utils/jellyfin/image/getPrimaryImageUrl.ts new file mode 100644 index 00000000..25b485bd --- /dev/null +++ b/utils/jellyfin/image/getPrimaryImageUrl.ts @@ -0,0 +1,51 @@ +import { Api } from "@jellyfin/sdk"; +import { + BaseItemDto, + BaseItemPerson, +} from "@jellyfin/sdk/lib/generated-client/models"; +import { isBaseItemDto } from "../jellyfin"; + +/** + * Retrieves the primary image URL for a given item. + * + * @param api - The Jellyfin API instance. + * @param item - The media item to retrieve the backdrop image URL for. + * @param quality - The desired image quality (default: 90). + */ +export const getPrimaryImageUrl = ({ + api, + item, + quality = 90, + width = 500, +}: { + api?: Api | null; + item?: BaseItemDto | BaseItemPerson | null; + quality?: number | null; + width?: number | null; +}) => { + if (!item || !api) { + return null; + } + + if (!isBaseItemDto(item)) { + return `${api?.basePath}/Items/${item?.Id}/Images/Primary`; + } + + const backdropTag = item.BackdropImageTags?.[0]; + const primaryTag = item.ImageTags?.["Primary"]; + + const params = new URLSearchParams({ + fillWidth: width ? String(width) : "500", + quality: quality ? String(quality) : "90", + }); + + if (primaryTag) { + params.set("tag", primaryTag); + } else if (backdropTag) { + params.set("tag", backdropTag); + } + + return `${api?.basePath}/Items/${ + item.Id + }/Images/Primary?${params.toString()}`; +}; diff --git a/utils/jellyfin/image/getPrimaryImageUrlById.ts b/utils/jellyfin/image/getPrimaryImageUrlById.ts new file mode 100644 index 00000000..736d1a0e --- /dev/null +++ b/utils/jellyfin/image/getPrimaryImageUrlById.ts @@ -0,0 +1,31 @@ +import { Api } from "@jellyfin/sdk"; + +/** + * Retrieves the primary image URL for a given item. + * + * @param api - The Jellyfin API instance. + * @param item - The media item to retrieve the backdrop image URL for. + * @param quality - The desired image quality (default: 90). + */ +export const getPrimaryImageUrlById = ({ + api, + id, + quality = 90, + width = 500, +}: { + api?: Api | null; + id?: string | null; + quality?: number | null; + width?: number | null; +}) => { + if (!id) { + return null; + } + + const params = new URLSearchParams({ + fillWidth: width ? String(width) : "500", + quality: quality ? String(quality) : "90", + }); + + return `${api?.basePath}/Items/${id}/Images/Primary?${params.toString()}`; +}; diff --git a/utils/jellyfin/jellyfin.ts b/utils/jellyfin/jellyfin.ts index e3f64c66..80738422 100644 --- a/utils/jellyfin/jellyfin.ts +++ b/utils/jellyfin/jellyfin.ts @@ -1,8 +1,29 @@ import { Api } from "@jellyfin/sdk"; +import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models"; /** * Generates the authorization headers for Jellyfin API requests. + * + * @param {Api} api - The Jellyfin API instance. + * @returns {Record} - The authorization headers. */ -export const getAuthHeaders = (api: Api) => ({ +export const getAuthHeaders = (api: Api): Record => ({ Authorization: `MediaBrowser DeviceId="${api.deviceInfo.id}", Token="${api.accessToken}"`, }); + +/** + * Converts a bitrate to a human-readable string. + * + * @param {number} bitrate - The bitrate to convert. + * @returns {string} - The bitrate as a human-readable string. + */ +export const bitrateToString = (bitrate: number): string => { + const kbps = bitrate / 1000; + const mbps = (bitrate / 1000000).toFixed(2); + + return `${mbps} Mb/s`; +}; + +export function isBaseItemDto(item: any): item is BaseItemDto { + return item && "BackdropImageTags" in item && "ImageTags" in item; +} diff --git a/utils/jellyfin/media/getPlaybackInfo.ts b/utils/jellyfin/media/getPlaybackInfo.ts new file mode 100644 index 00000000..5d85376e --- /dev/null +++ b/utils/jellyfin/media/getPlaybackInfo.ts @@ -0,0 +1,19 @@ +import { Api } from "@jellyfin/sdk"; +import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api"; + +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; +}; diff --git a/utils/jellyfin/media/getPlaybackUrl.ts b/utils/jellyfin/media/getPlaybackUrl.ts new file mode 100644 index 00000000..74257348 --- /dev/null +++ b/utils/jellyfin/media/getPlaybackUrl.ts @@ -0,0 +1,49 @@ +import { Api } from "@jellyfin/sdk"; +import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api"; + +/** + * Retrieves the playback URL for the given item ID and user ID. + * + * @param api - The Jellyfin API instance. + * @param itemId - The ID of the media item to retrieve playback URL for. + * @param userId - The ID of the user requesting the playback URL. + * @returns The playback URL as a string. + */ +export const getPlaybackUrl = async ( + api: Api, + itemId: string, + userId: string, +): Promise => { + const playbackData = await getMediaInfoApi(api).getPlaybackInfo({ + itemId, + userId, + }); + + const mediaSources = playbackData.data?.MediaSources; + if (!mediaSources || mediaSources.length === 0) { + throw new Error( + "No media sources available for the requested item and user.", + ); + } + + const mediaSource = mediaSources[0]; + const transcodeUrl = mediaSource.TranscodingUrl; + if (transcodeUrl) { + return transcodeUrl; + } + + // Construct a fallback URL if the TranscodingUrl is not available + const { Id, ETag } = mediaSource; + if (!Id) { + throw new Error("Media source ID is missing."); + } + + const queryParams = new URLSearchParams({ + deviceId: api.deviceInfo?.id || "", + api_key: api.accessToken || "", + Tag: ETag || "", + MediaSourceId: Id || "", + }); + + return `/Videos/${Id}/stream?${queryParams}`; +}; diff --git a/utils/jellyfin/media/getStreamUrl.ts b/utils/jellyfin/media/getStreamUrl.ts new file mode 100644 index 00000000..fbc6d8bb --- /dev/null +++ b/utils/jellyfin/media/getStreamUrl.ts @@ -0,0 +1,67 @@ +import ios12 from "@/utils/profiles/ios12"; +import { Api } from "@jellyfin/sdk"; +import { + BaseItemDto, + PlaybackInfoResponse, + MediaSourceInfo, +} from "@jellyfin/sdk/lib/generated-client/models"; + +export const getStreamUrl = async ({ + api, + item, + userId, + startTimeTicks = 0, + maxStreamingBitrate, + sessionData, + deviceProfile = ios12, +}: { + api: Api | null | undefined; + item: BaseItemDto | null | undefined; + userId: string | null | undefined; + startTimeTicks: number; + maxStreamingBitrate?: number; + sessionData: PlaybackInfoResponse; + deviceProfile: any; +}) => { + if (!api || !userId || !item?.Id) { + return null; + } + + const itemId = item.Id; + + const response = await api.axiosInstance.post( + `${api.basePath}/Items/${itemId}/PlaybackInfo`, + { + DeviceProfile: deviceProfile, + UserId: userId, + MaxStreamingBitrate: maxStreamingBitrate, + StartTimeTicks: startTimeTicks, + EnableTranscoding: maxStreamingBitrate ? true : undefined, + AutoOpenLiveStream: true, + MediaSourceId: itemId, + AllowVideoStreamCopy: maxStreamingBitrate ? false : true, + }, + { + headers: { + Authorization: `MediaBrowser DeviceId="${api.deviceInfo.id}", Token="${api.accessToken}"`, + }, + }, + ); + + const mediaSource = response.data.MediaSources?.[0] as MediaSourceInfo; + + if (!mediaSource) { + throw new Error("No media source"); + } + if (!sessionData.PlaySessionId) { + throw new Error("no PlaySessionId"); + } + + if (mediaSource.SupportsDirectPlay) { + console.log("Using direct stream!"); + return `${api.basePath}/Videos/${itemId}/stream.mp4?playSessionId=${sessionData.PlaySessionId}&mediaSourceId=${itemId}&static=true`; + } + + console.log("Using transcoded stream!"); + return `${api.basePath}${mediaSource.TranscodingUrl}`; +}; diff --git a/utils/jellyfin/user-library/getItemById.ts b/utils/jellyfin/user-library/getItemById.ts new file mode 100644 index 00000000..79914abc --- /dev/null +++ b/utils/jellyfin/user-library/getItemById.ts @@ -0,0 +1,34 @@ +import { Api } from "@jellyfin/sdk"; +import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models"; +import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api"; + +/** + * Retrieves an item by its ID from the API. + * + * @param api - The Jellyfin API instance. + * @param itemId - The ID of the item to retrieve. + * @returns The item object or undefined if no item matches the ID. + */ +export const getItemById = async ( + api?: Api | null | undefined, + itemId?: string | null | undefined, +): Promise => { + if (!api || !itemId) { + return undefined; + } + + try { + const itemData = await getUserLibraryApi(api).getItem({ itemId }); + + const item = itemData.data; + if (!item) { + console.error("No items found with the specified ID:", itemId); + return undefined; + } + + return item; + } catch (error) { + console.error("Failed to retrieve the item:", error); + throw new Error(`Failed to retrieve the item due to an error: ${error}`); + } +}; diff --git a/utils/jellyfin/items/getUserItemData.ts b/utils/jellyfin/user-library/getUserItemData.ts similarity index 60% rename from utils/jellyfin/items/getUserItemData.ts rename to utils/jellyfin/user-library/getUserItemData.ts index b2d1b9f1..56b0dae0 100644 --- a/utils/jellyfin/items/getUserItemData.ts +++ b/utils/jellyfin/user-library/getUserItemData.ts @@ -1,8 +1,6 @@ import { Api } from "@jellyfin/sdk"; -import { - getMediaInfoApi, - getUserLibraryApi, -} from "@jellyfin/sdk/lib/utils/api"; +import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models"; +import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api"; /** * Fetches the media info for a given item. @@ -21,26 +19,9 @@ export const getUserItemData = async ({ api: Api | null | undefined; itemId: string | null | undefined; userId: string | null | undefined; -}) => { +}): Promise => { 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; -};