chore: refactor

This commit is contained in:
Fredrik Burmester
2024-08-06 23:53:00 +02:00
parent 415db8f1c2
commit d4d3cbbc43
28 changed files with 1075 additions and 1445 deletions

View File

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

View File

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

View File

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

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

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

View 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}"`,
});

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

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

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

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

View 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 [];
}
};

View 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",
},
],
};

View File

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