chore: refactor

This commit is contained in:
Fredrik Burmester
2024-08-07 08:15:30 +02:00
parent d4d3cbbc43
commit 49b2e594d6
31 changed files with 525 additions and 487 deletions

View File

@@ -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.

View File

@@ -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() {
<Poster
item={item}
key={item.Id}
url={getPrimaryImage({ api, item })}
url={getPrimaryImageUrl({ api, item })}
/>
<Text className="mt-2">{item.Name}</Text>
<Text className="opacity-50 text-xs">

View File

@@ -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 (
<View className="h-full flex flex-col items-center justify-center -mt-6">
@@ -64,6 +76,55 @@ const downloads: React.FC = () => {
return (
<ScrollView>
<View className="px-4 py-4">
<View className="mb-4">
<Text className="text-2xl font-bold mb-2">Active download</Text>
{process?.item ? (
<TouchableOpacity
onPress={() =>
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"
>
<View>
<Text className="font-semibold">{process.item.Name}</Text>
<Text className="text-xs opacity-50">{process.item.Type}</Text>
<View className="flex flex-row items-center space-x-2 mt-1 text-red-600">
<Text className="text-xs">
{process.progress.toFixed(0)}%
</Text>
<Text className="text-xs">{process.speed?.toFixed(2)}x</Text>
{process.startTime && (
<Text className="text-xs">
{formatNumber(
new Date().getTime() - process.startTime.getTime(),
)}
</Text>
)}
</View>
</View>
<TouchableOpacity
onPress={() => {
FFmpegKit.cancel();
setProcess(null);
}}
>
<Ionicons name="close" size={24} color="red" />
</TouchableOpacity>
<View
className={`
absolute bottom-0 left-0 h-1 bg-red-600
`}
style={{
width: process.progress
? `${Math.max(5, process.progress)}%`
: "5%",
}}
></View>
</TouchableOpacity>
) : (
<Text className="opacity-50">No active downloads</Text>
)}
</View>
{movies.length > 0 && (
<View className="mb-4">
<View className="flex flex-row items-center justify-between mb-2">
@@ -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`;
};

View File

@@ -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],
);

View File

@@ -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,
}),

View File

@@ -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() {
<ListItem title="Server" subTitle={api?.basePath} />
</View>
<Button onPress={logout}>Log out</Button>
<View className="my-2">
<View className="flex flex-col space-y-2">
<Button color="black" onPress={logout}>
Log out
</Button>
<Button
color="red"
onPress={async () => {
@@ -46,9 +48,20 @@ export default function settings() {
>
Delete all downloaded files
</Button>
<Button
color="red"
onPress={async () => {
await clearLogs();
Haptics.notificationAsync(
Haptics.NotificationFeedbackType.Success,
);
}}
>
Delete all logs
</Button>
</View>
<Text className="font-bold">Logs</Text>
<Text className="font-bold text-2xl">Logs</Text>
<View className="flex flex-col space-y-2">
{logs?.map((log, index) => (
<View
@@ -66,6 +79,9 @@ export default function settings() {
<Text>{log.message}</Text>
</View>
))}
{logs?.length === 0 && (
<Text className="opacity-50">No logs available</Text>
)}
</View>
</View>
</ScrollView>

View File

@@ -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;
}

View File

@@ -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<typeof TouchableOpacity> {
onPress?: () => void;
className?: string;
textClassName?: string;
@@ -26,6 +26,7 @@ export const Button: React.FC<PropsWithChildren<ButtonProps>> = ({
iconLeft,
children,
justify = "center",
...props
}) => {
const colorClasses = useMemo(() => {
switch (color) {
@@ -34,7 +35,7 @@ export const Button: React.FC<PropsWithChildren<ButtonProps>> = ({
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<PropsWithChildren<ButtonProps>> = ({
}
}}
disabled={disabled || loading}
{...props}
>
{loading ? (
<ActivityIndicator color={"white"} size={24} />

View File

@@ -33,7 +33,6 @@ export const Chromecast: React.FC<Props> = ({ item, startTimeTicks }) => {
await discoveryManager.startDiscovery();
const started = await discoveryManager.isRunning();
console.log("started", started);
console.log({
devices,

View File

@@ -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<ContinueWatchingPosterProps> = ({
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)

View File

@@ -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;

View File

@@ -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<MoviePosterProps> = ({
const url = useMemo(
() =>
getPrimaryImage({
getPrimaryImageUrl({
api,
item,
}),
[item]
[item],
);
const [progress, setProgress] = useState(
item.UserData?.PlayedPercentage || 0
item.UserData?.PlayedPercentage || 0,
);
if (!url)

View File

@@ -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<VideoPlayerProps> = ({
() =>
item?.UserData?.PlaybackPositionTicks
? Math.round(item.UserData.PlaybackPositionTicks / 10000)
: null,
: 0,
[item],
);

View File

@@ -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<VideoRef | null>(null);
const [isPlaying, setIsPlaying] = useState(false);
const openFile = () => {
videoRef.current?.presentFullscreenPlayer();
@@ -38,7 +39,7 @@ export const EpisodeCard: React.FC<{ item: BaseItemDto }> = ({ item }) => {
<ContextMenu.Trigger>
<TouchableOpacity
onPress={openFile}
className="bg-neutral-800 border border-neutral-900 rounded-2xl p-4"
className="bg-neutral-900 border border-neutral-800 rounded-2xl p-4"
>
<Text className=" font-bold">{item.Name}</Text>
<Text className=" text-xs opacity-50">
@@ -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}
/>
</>
);

View File

@@ -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<VideoRef | null>(null);
const [isPlaying, setIsPlaying] = useState(false);
const openFile = () => {
videoRef.current?.presentFullscreenPlayer();
@@ -45,7 +46,7 @@ export const MovieCard: React.FC<{ item: BaseItemDto }> = ({ item }) => {
<ContextMenu.Trigger>
<TouchableOpacity
onPress={openFile}
className="bg-neutral-800 border border-neutral-900 rounded-2xl p-4"
className="bg-neutral-900 border border-neutral-800 rounded-2xl p-4"
>
<Text className=" font-bold">{item.Name}</Text>
<View className="flex flex-row items-center justify-between">
@@ -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}
/>
</>
);

View File

@@ -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) => (
<TouchableOpacity key={item.Id} className="flex flex-col w-32">
<Poster item={item} url={getPrimaryImage({ api, item })} />
<Poster item={item} url={getPrimaryImageUrl({ api, item })} />
<Text className="mt-2">{item.Name}</Text>
<Text className="text-xs opacity-50">{item.Role}</Text>
</TouchableOpacity>

View File

@@ -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 }) => {
>
<Poster
item={item}
url={getPrimaryImageById({ api, id: item.ParentId })}
url={getPrimaryImageUrlById({ api, id: item.ParentId })}
/>
<Text>{item.SeriesName}</Text>
</TouchableOpacity>

View File

@@ -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 =

View File

@@ -5,6 +5,7 @@ export type ProcessItem = {
item: BaseItemDto;
progress: number;
speed?: number;
startTime?: Date;
};
export const runningProcesses = atom<ProcessItem | null>(null);

View File

@@ -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<string> => {
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<BaseItemDto | undefined> => {
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`;
};

View File

@@ -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 });
}
};

View File

@@ -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()}`;
};

View File

@@ -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<string> => {
const image = await getImageApi(api).getItemImage({
itemId,
imageType: "Primary",
quality: 90,
width: 1000,
});
console.log("getPrimaryImage ~", image.data);
return image.data;
};

View File

@@ -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()}`;
};

View File

@@ -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()}`;
};

View File

@@ -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<string, string>} - The authorization headers.
*/
export const getAuthHeaders = (api: Api) => ({
export const getAuthHeaders = (api: Api): Record<string, string> => ({
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;
}

View File

@@ -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;
};

View File

@@ -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<string> => {
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}`;
};

View File

@@ -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}`;
};

View File

@@ -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<BaseItemDto | undefined> => {
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}`);
}
};

View File

@@ -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<BaseItemDto | null> => {
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;
};