refactor: improve library page, fix playbutton issues, improve overall app performance

This commit is contained in:
--remove-section committed 2025-12-18 22:16:43 +05:30
1 parent 120e283e3d
commit d39c064600
12 files changed
+1867 -2017

No files matched your search

+85 -58
View File
@@ -1,5 +1,7 @@
import React, { useState, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import type { BaseItemDtoQueryResult } from "@jellyfin/sdk/lib/generated-client";
import type { UseQueryResult, useQuery } from "@tanstack/react-query";
import type React from "react";
import { useEffect, useState } from "react";
/**
* Custom hook for selecting and managing the default season for a TV series.
@@ -9,84 +11,80 @@ import { useQuery } from "@tanstack/react-query";
* - Only falls back to special seasons if no regular seasons exist
* - Properly handles the case where some episodes in special seasons are watched
*/
// Define a type for Season UserData
type SeasonUserData = {
Played?: boolean;
PlayedPercentage?: number;
};
// Define a type for Season
type Season = {
Id: string;
IndexNumber: number | null;
UserData?: SeasonUserData;
// Add any other properties you expect from a season item
[key: string]: any;
};
function useDefaultSeason(
seasons: ReturnType<typeof useQuery>,
itemId: string | undefined
): [number, React.Dispatch<React.SetStateAction<number>>] { const [currentSeason, setCurrentSeason] = useState<number>(() => {
seasons: UseQueryResult<BaseItemDtoQueryResult | null, unknown>,
itemId: string | undefined,
): [number, React.Dispatch<React.SetStateAction<number>>] {
const [currentSeason, setCurrentSeason] = useState<number>(() => {
const result = sessionStorage.getItem(`season-${itemId}`);
return result ? Number(result) : 0;
});
// Track if this is the initial load to avoid switching during episode updates
const [hasInitialized, setHasInitialized] = useState(false); useEffect(() => {
const [hasInitialized, setHasInitialized] = useState(false);
useEffect(() => {
if (seasons.isSuccess && seasons.data?.Items) {
const savedSeason = sessionStorage.getItem(`season-${itemId}`);
// Always re-evaluate the best season based on viewing progress
let defaultSeasonIndex = 0;
// Map all seasons with their original index
const allSeasonsWithIndex = seasons.data.Items.map((season: Season, index: number) => ({
...season,
originalIndex: index
}));
// Separate regular seasons (not specials) and special seasons
const regularSeasons = allSeasonsWithIndex.filter((season: Season) =>
season.IndexNumber !== 0 && season.IndexNumber != null
const allSeasonsWithIndex = seasons.data.Items.map(
(season, index: number) => ({
...season,
originalIndex: index,
}),
);
const specialSeasons = allSeasonsWithIndex.filter((season: Season) =>
season.IndexNumber === 0
// Separate regular seasons (not specials) and special seasons
const regularSeasons = allSeasonsWithIndex.filter(
(season) => season.IndexNumber !== 0 && season.IndexNumber != null,
);
const specialSeasons = allSeasonsWithIndex.filter(
(season) => season.IndexNumber === 0,
);
// Find the optimal season based on viewing progress
if (regularSeasons.length > 0) {
let targetSeason = regularSeasons[0];
// Look for the first season that isn't fully watched
for (const season of regularSeasons) {
// A season is considered "unwatched" if:
// 1. The season itself isn't marked as played, AND
// 2. The season has a play percentage less than 100%
const isSeasonFullyWatched = season.UserData?.Played ||
(season.UserData?.PlayedPercentage && season.UserData.PlayedPercentage >= 100);
const isSeasonFullyWatched =
season.UserData?.Played ||
(season.UserData?.PlayedPercentage &&
season.UserData.PlayedPercentage >= 100);
if (!isSeasonFullyWatched) {
targetSeason = season;
break;
}
}
// If the selected season is still fully watched, try to move to the next one
const isTargetFullyWatched = targetSeason.UserData?.Played ||
(targetSeason.UserData?.PlayedPercentage && targetSeason.UserData.PlayedPercentage >= 100);
const isTargetFullyWatched =
targetSeason.UserData?.Played ||
(targetSeason.UserData?.PlayedPercentage &&
targetSeason.UserData.PlayedPercentage >= 100);
if (isTargetFullyWatched) {
const currentIndex = regularSeasons.findIndex((s: Season) => s.Id === targetSeason.Id);
const currentIndex = regularSeasons.findIndex(
(s) => s.Id === targetSeason.Id,
);
const nextSeasonIndex = currentIndex + 1;
if (nextSeasonIndex < regularSeasons.length) {
targetSeason = regularSeasons[nextSeasonIndex];
}
// If we're at the last season and it's fully watched, stay on it
}
defaultSeasonIndex = targetSeason.originalIndex;
}
}
// Only fall back to special seasons if no regular seasons exist
else if (specialSeasons.length > 0) {
// For special seasons, just pick the first one
@@ -97,24 +95,32 @@ function useDefaultSeason(
if (savedSeason) {
const savedSeasonNumber = Number(savedSeason);
const currentSeasonData = allSeasonsWithIndex[savedSeasonNumber];
// Check if user is currently in a special season
const isInSpecialSeason = currentSeasonData?.IndexNumber === 0;
// Check if current season is fully complete
const isCurrentSeasonComplete = currentSeasonData?.UserData?.Played ||
(currentSeasonData?.UserData?.PlayedPercentage && currentSeasonData.UserData.PlayedPercentage >= 100);
const isCurrentSeasonComplete =
currentSeasonData?.UserData?.Played ||
(currentSeasonData?.UserData?.PlayedPercentage &&
currentSeasonData.UserData.PlayedPercentage >= 100);
if (isInSpecialSeason) {
// For special seasons: advance to regular seasons if specials are complete
if (isCurrentSeasonComplete && regularSeasons.length > 0) {
// Special season is done, move to optimal regular season
setCurrentSeason(defaultSeasonIndex);
sessionStorage.setItem(`season-${itemId}`, defaultSeasonIndex.toString());
sessionStorage.setItem(
`season-${itemId}`,
defaultSeasonIndex.toString(),
);
} else if (!hasInitialized && regularSeasons.length > 0) {
// Initial load: prioritize regular seasons over specials
setCurrentSeason(defaultSeasonIndex);
sessionStorage.setItem(`season-${itemId}`, defaultSeasonIndex.toString());
sessionStorage.setItem(
`season-${itemId}`,
defaultSeasonIndex.toString(),
);
} else {
// Stay in specials (either no regular seasons or specials not complete)
setCurrentSeason(savedSeasonNumber);
@@ -123,21 +129,39 @@ function useDefaultSeason(
// For regular seasons: advance to next season if current is complete
if (isCurrentSeasonComplete) {
// Find next season after current
const currentRegularIndex = regularSeasons.findIndex((s: Season & { originalIndex: number }) => s.originalIndex === savedSeasonNumber);
if (currentRegularIndex >= 0 && currentRegularIndex < regularSeasons.length - 1) {
const currentRegularIndex = regularSeasons.findIndex(
(s: { originalIndex: number }) =>
s.originalIndex === savedSeasonNumber,
);
if (
currentRegularIndex >= 0 &&
currentRegularIndex < regularSeasons.length - 1
) {
// Move to next regular season
const nextSeason = regularSeasons[currentRegularIndex + 1];
setCurrentSeason(nextSeason.originalIndex);
sessionStorage.setItem(`season-${itemId}`, nextSeason.originalIndex.toString());
sessionStorage.setItem(
`season-${itemId}`,
nextSeason.originalIndex.toString(),
);
} else {
// At last season or use calculated optimal
setCurrentSeason(defaultSeasonIndex);
sessionStorage.setItem(`season-${itemId}`, defaultSeasonIndex.toString());
sessionStorage.setItem(
`season-${itemId}`,
defaultSeasonIndex.toString(),
);
}
} else if (!hasInitialized && savedSeasonNumber !== defaultSeasonIndex) {
} else if (
!hasInitialized &&
savedSeasonNumber !== defaultSeasonIndex
) {
// Initial load: use calculated optimal season
setCurrentSeason(defaultSeasonIndex);
sessionStorage.setItem(`season-${itemId}`, defaultSeasonIndex.toString());
sessionStorage.setItem(
`season-${itemId}`,
defaultSeasonIndex.toString(),
);
} else {
// Stay in current season
setCurrentSeason(savedSeasonNumber);
@@ -146,9 +170,12 @@ function useDefaultSeason(
} else {
// No saved season, use the calculated default
setCurrentSeason(defaultSeasonIndex);
sessionStorage.setItem(`season-${itemId}`, defaultSeasonIndex.toString());
sessionStorage.setItem(
`season-${itemId}`,
defaultSeasonIndex.toString(),
);
}
// Mark as initialized after first run
if (!hasInitialized) {
setHasInitialized(true);
+250
View File
@@ -0,0 +1,250 @@
import type { Api } from "@jellyfin/sdk";
import {
type BaseItemDto,
BaseItemKind,
ItemFields,
ItemFilter,
ItemSortBy,
LocationType,
SortOrder,
} from "@jellyfin/sdk/lib/generated-client";
import { getItemsApi } from "@jellyfin/sdk/lib/utils/api/items-api";
import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api/media-info-api";
import { getMediaSegmentsApi } from "@jellyfin/sdk/lib/utils/api/media-segments-api";
import { getPlaylistsApi } from "@jellyfin/sdk/lib/utils/api/playlists-api";
import { getTvShowsApi } from "@jellyfin/sdk/lib/utils/api/tv-shows-api";
import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api";
import playbackProfile from "@/utils/playback-profiles";
export async function getNextEpisode(
api: Api,
userId: string,
seriesId: string,
season: number,
) {
const episode = (
await getTvShowsApi(api).getEpisodes({
seriesId: seriesId,
userId: userId,
enableUserData: true,
season,
fields: [ItemFields.MediaStreams, ItemFields.MediaSources],
})
).data.Items?.find((ep) => ep.UserData?.Played !== true);
if (episode) {
return episode;
}
const allEpisodes = (
await getTvShowsApi(api).getEpisodes({
seriesId: seriesId,
userId: userId,
enableUserData: true,
fields: [ItemFields.MediaStreams, ItemFields.MediaSources],
})
).data.Items;
if (allEpisodes) {
return allEpisodes[0];
}
return null;
}
export interface PlaybackInfoOptions {
currentAudioTrack?: number | "auto";
currentSubTrack?: number | "nosub";
currentEpisodeId?: string;
playlistItem?: boolean;
playlistItemId?: string;
}
export async function getPlaybackInfo(
api: Api,
userId: string,
item: BaseItemDto,
options: PlaybackInfoOptions = {},
) {
const {
currentAudioTrack = "auto",
currentSubTrack,
currentEpisodeId,
playlistItem,
playlistItemId,
} = options;
let result: any;
let mediaSource: any;
let mediaSegments: any;
let index = 0;
if (playlistItem && playlistItemId) {
result = await getPlaylistsApi(api).getPlaylistItems({
userId: userId,
playlistId: playlistItemId,
});
} else {
switch (item.Type) {
case BaseItemKind.Episode:
if (item.SeriesId && item.SeasonId) {
result = await getTvShowsApi(api).getEpisodes({
seriesId: item.SeriesId,
fields: [
ItemFields.MediaSources,
ItemFields.MediaStreams,
ItemFields.Overview,
ItemFields.Chapters,
ItemFields.Trickplay,
],
enableUserData: true,
userId: userId,
seasonId: item.SeasonId,
isMissing: false,
});
if (currentEpisodeId) {
index =
result.data.Items?.map((i: any) => i.Id).indexOf(
currentEpisodeId,
) ?? 0;
} else {
index =
result.data.Items?.map((i: any) => i.Id).indexOf(item.Id) ?? 0;
}
if (index === -1) index = 0;
}
break;
case BaseItemKind.Series:
result = await getTvShowsApi(api).getEpisodes({
seriesId: item.Id || "",
fields: [
ItemFields.MediaSources,
ItemFields.MediaStreams,
ItemFields.Overview,
ItemFields.Chapters,
ItemFields.Trickplay,
],
enableUserData: true,
userId: userId,
isMissing: false,
});
if (currentEpisodeId) {
index =
result.data.Items?.map((i: any) => i.Id).indexOf(
currentEpisodeId,
) ?? 0;
}
if (index === -1) index = 0;
break;
case BaseItemKind.Playlist:
case BaseItemKind.MusicAlbum:
result = await getItemsApi(api).getItems({
parentId: item.Id,
userId: userId,
fields: [ItemFields.MediaSources, ItemFields.MediaStreams],
sortOrder: [SortOrder.Ascending],
sortBy: ["IndexNumber"],
});
break;
case BaseItemKind.MusicArtist:
result = await getItemsApi(api).getItems({
artistIds: [item.Id ?? ""],
recursive: true,
includeItemTypes: [BaseItemKind.Audio],
userId: userId,
fields: [ItemFields.MediaSources, ItemFields.MediaStreams],
sortOrder: [SortOrder.Ascending],
sortBy: ["PremiereDate", "ProductionYear", "SortName"],
});
break;
case BaseItemKind.BoxSet:
result = await getItemsApi(api).getItems({
parentId: item.Id,
userId,
fields: [
ItemFields.MediaSources,
ItemFields.MediaStreams,
ItemFields.Chapters,
ItemFields.Trickplay,
],
sortOrder: [SortOrder.Ascending],
sortBy: ["IndexNumber"],
});
break;
case BaseItemKind.Photo: {
const photo = (
await getUserLibraryApi(api).getItem({
itemId: item.Id || "",
})
).data;
result = await getItemsApi(api).getItems({
parentId: photo.ParentId ?? "",
filters: [ItemFilter.IsNotFolder],
recursive: false,
sortBy: ["SortName"],
mediaTypes: ["Photo"],
excludeLocationTypes: [LocationType.Virtual],
collapseBoxSetItems: false,
});
break;
}
default:
result = await getItemsApi(api).getItems({
ids: [item.Id ?? ""],
userId: userId,
fields: [
ItemFields.MediaSources,
ItemFields.MediaStreams,
ItemFields.Chapters,
ItemFields.Trickplay,
],
sortOrder: [SortOrder.Ascending],
sortBy: ["IndexNumber"],
});
break;
}
}
if (
result?.data?.Items?.[index]?.Id &&
(result.data.Items[index].MediaSources?.[0]?.Id ||
item.Type === BaseItemKind.Photo)
) {
const targetItem = result.data.Items[index];
if (item.Type !== BaseItemKind.Photo) {
let audioStreamIndex = currentAudioTrack;
if (audioStreamIndex === "auto") {
audioStreamIndex =
targetItem.MediaSources?.[0].DefaultAudioStreamIndex ?? 0;
}
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
audioStreamIndex: Number(audioStreamIndex),
subtitleStreamIndex: currentSubTrack === "nosub" ? -1 : currentSubTrack,
itemId: targetItem.Id,
startTimeTicks: targetItem.UserData?.PlaybackPositionTicks,
userId: userId,
mediaSourceId: targetItem.MediaSources?.[0]?.Id,
playbackInfoDto: {
DeviceProfile: playbackProfile,
},
});
mediaSegments = (
await getMediaSegmentsApi(api).getItemSegments({
itemId: targetItem.Id,
})
)?.data;
}
}
return {
item: result?.data,
mediaSource: mediaSource?.data,
mediaSegments,
episodeIndex: index,
};
}
+6 -2
View File
@@ -46,6 +46,7 @@ export const getLibraryItemsQueryOptions = (
params: LibraryItemsParams,
) => {
return queryOptions<BaseItemDtoQueryResult>({
enabled: !!params.currentViewType,
queryKey: [
"library",
"items",
@@ -64,8 +65,13 @@ export const getLibraryItemsQueryOptions = (
],
queryFn: async () => {
if (!api || !userId || !libraryId || !params.currentViewType) {
console.warn(
"getLibraryItemsQueryOptions: Missing required parameters",
{ api, userId, libraryId, currentViewType: params.currentViewType },
);
return { Items: [], TotalRecordCount: 0 } as BaseItemDtoQueryResult;
}
console.info("Fetching library items with params:", params);
const { currentViewType, videoTypesState, filters } = params;
const buildVideoTypes = (state: typeof videoTypesState) => {
const videoTypes: VideoType[] = [];
@@ -168,7 +174,5 @@ export const getLibraryItemsQueryOptions = (
},
staleTime: 5_000,
gcTime: 5 * 60_000,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
});
};
+56
View File
@@ -0,0 +1,56 @@
import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client";
let intervalId: number | undefined;
let backdropItems: BaseItemDto[] = [];
let backdropIndex = 0;
const updateBackdrop = () => {
if (backdropItems.length === 0) {
return;
}
backdropIndex = (backdropIndex + 1) % backdropItems.length;
const item = backdropItems[backdropIndex];
const keys = Object.keys(item?.ImageBlurHashes?.Backdrop ?? {});
const nextHash = item?.ImageBlurHashes?.Backdrop?.[keys[0]];
if (nextHash) {
self.postMessage({ type: "UPDATE_BACKDROP", payload: nextHash });
}
};
self.onmessage = (event: MessageEvent) => {
const { type, payload } = event.data;
switch (type) {
case "SET_BACKDROP_ITEMS":
backdropItems = payload;
backdropIndex = 0;
if (backdropItems.length > 0) {
const firstBackdrop = backdropItems[0];
const firstKey = Object.keys(
firstBackdrop?.ImageBlurHashes?.Backdrop ?? {},
)[0];
const initialHash =
firstBackdrop?.ImageBlurHashes?.Backdrop?.[firstKey];
if (initialHash) {
self.postMessage({ type: "UPDATE_BACKDROP", payload: initialHash });
}
}
break;
case "START":
if (intervalId) {
clearInterval(intervalId);
}
intervalId = self.setInterval(updateBackdrop, 10_000);
break;
case "STOP":
if (intervalId) {
clearInterval(intervalId);
intervalId = undefined;
}
break;
default:
console.warn("Unknown message type in backdrop worker:", type);
}
};