refactor: improve library page, fix playbutton issues, improve overall app performance
This commit is contained in:
12 files changed
+1867
-2017
No files matched your search
+40
-40
@@ -23,72 +23,72 @@
|
||||
"@fontsource-variable/noto-sans": "^5.2.10",
|
||||
"@fontsource-variable/plus-jakarta-sans": "^5.2.8",
|
||||
"@fontsource-variable/space-grotesk": "^5.2.10",
|
||||
"@jellyfin/sdk": "0.12.0",
|
||||
"@mui/lab": "7.0.1-beta.18",
|
||||
"@mui/material": "7.3.4",
|
||||
"@jellyfin/sdk": "0.13.0",
|
||||
"@mui/lab": "7.0.1-beta.20",
|
||||
"@mui/material": "7.3.6",
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@react-spring/web": "^10.0.3",
|
||||
"@tanem/react-nprogress": "^5.0.56",
|
||||
"@tanstack/react-form": "^1.23.7",
|
||||
"@tanstack/react-query": "^5.90.5",
|
||||
"@tanstack/react-query-devtools": "^5.90.2",
|
||||
"@tanstack/react-router": "^1.133.21",
|
||||
"@tanstack/react-router-devtools": "^1.133.21",
|
||||
"@tanstack/react-virtual": "^3.13.12",
|
||||
"@tauri-apps/api": "2.9.0",
|
||||
"@tauri-apps/plugin-clipboard-manager": "2.3.0",
|
||||
"@tauri-apps/plugin-dialog": "2.4.0",
|
||||
"@tauri-apps/plugin-notification": "2.3.1",
|
||||
"@tauri-apps/plugin-process": "2.3.0",
|
||||
"@tanstack/react-form": "^1.27.5",
|
||||
"@tanstack/react-query": "^5.90.12",
|
||||
"@tanstack/react-query-devtools": "^5.91.1",
|
||||
"@tanstack/react-router": "^1.141.6",
|
||||
"@tanstack/react-router-devtools": "^1.141.6",
|
||||
"@tanstack/react-virtual": "^3.13.13",
|
||||
"@tauri-apps/api": "2.9.1",
|
||||
"@tauri-apps/plugin-clipboard-manager": "2.3.2",
|
||||
"@tauri-apps/plugin-dialog": "2.4.2",
|
||||
"@tauri-apps/plugin-notification": "2.3.3",
|
||||
"@tauri-apps/plugin-process": "2.3.1",
|
||||
"@tauri-apps/plugin-store": "github:tauri-apps/tauri-plugin-store#v2",
|
||||
"@tauri-apps/plugin-updater": "2.9.0",
|
||||
"@tauri-apps/plugin-upload": "2.3.1",
|
||||
"@tauri-apps/plugin-window-state": "~2.4.0",
|
||||
"@types/node": "^24.9.1",
|
||||
"@types/react": "^19.2.2",
|
||||
"@types/react-dom": "^19.2.2",
|
||||
"axios": "^1.12.2",
|
||||
"@tauri-apps/plugin-upload": "2.3.2",
|
||||
"@tauri-apps/plugin-window-state": "~2.4.1",
|
||||
"@types/node": "^25.0.3",
|
||||
"@types/react": "^19.2.7",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"axios": "^1.13.2",
|
||||
"axios-tauri-api-adapter": "^2.0.6",
|
||||
"blurhash": "^2.0.5",
|
||||
"blurhash-wasm": "^0.2.0",
|
||||
"immer": "^10.1.3",
|
||||
"immer": "^11.0.1",
|
||||
"jassub": "^1.8.6",
|
||||
"libpgs": "^0.8.1",
|
||||
"lodash": "^4.17.21",
|
||||
"material-symbols": "^0.38.0",
|
||||
"motion": "^12.23.24",
|
||||
"material-symbols": "^0.40.2",
|
||||
"motion": "^12.23.26",
|
||||
"notistack": "^3.0.2",
|
||||
"react": "^19.2.0",
|
||||
"react": "^19.2.3",
|
||||
"react-blurhash": "^0.3.0",
|
||||
"react-dnd": "^16.0.1",
|
||||
"react-dnd-html5-backend": "^16.0.1",
|
||||
"react-dom": "^19.2.0",
|
||||
"react-dom": "^19.2.3",
|
||||
"react-error-boundary": "^6.0.0",
|
||||
"react-intersection-observer": "^9.16.0",
|
||||
"react-intersection-observer": "^10.0.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-multi-carousel": "^2.8.6",
|
||||
"react-player": "^3.3.3",
|
||||
"react-player": "^3.4.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"typescript": "^5.9.3",
|
||||
"vite-plugin-svgr": "^4.5.0",
|
||||
"wavesurfer.js": "^7.11.0",
|
||||
"zod": "^4.1.12",
|
||||
"zustand": "5.0.8"
|
||||
"wavesurfer.js": "^7.12.1",
|
||||
"zod": "^4.2.1",
|
||||
"zustand": "5.0.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/plugin-proposal-optional-chaining-assign": "^7.27.1",
|
||||
"@biomejs/biome": "^2.2.6",
|
||||
"@tanstack/router-cli": "^1.133.20",
|
||||
"@tanstack/router-devtools": "^1.133.21",
|
||||
"@tanstack/router-vite-plugin": "^1.133.21",
|
||||
"@tauri-apps/cli": "2.9.0",
|
||||
"@types/lodash": "^4.17.20",
|
||||
"@vitejs/plugin-react": "^5.0.4",
|
||||
"@biomejs/biome": "^2.3.10",
|
||||
"@tanstack/router-cli": "^1.141.7",
|
||||
"@tanstack/router-devtools": "^1.141.6",
|
||||
"@tanstack/router-vite-plugin": "^1.141.7",
|
||||
"@tauri-apps/cli": "2.9.6",
|
||||
"@types/lodash": "^4.17.21",
|
||||
"@vitejs/plugin-react": "^5.1.2",
|
||||
"babel-plugin-react-compiler": "19.1.0-rc.2",
|
||||
"eslint-plugin-react-hooks": "7.0.0",
|
||||
"eslint-plugin-react-hooks": "7.0.1",
|
||||
"prop-types": "^15.8.1",
|
||||
"sass": "^1.93.2",
|
||||
"vite": "^7.1.11",
|
||||
"sass": "^1.97.0",
|
||||
"vite": "^7.3.0",
|
||||
"vite-plugin-wasm": "^3.5.0"
|
||||
},
|
||||
"license": "GPL-3.0-only"
|
||||
|
||||
Generated
+1164
-1191
File diff suppressed because it is too large.
Load diff
@@ -1,22 +1,9 @@
|
||||
import {
|
||||
type BaseItemDto,
|
||||
type BaseItemDtoQueryResult,
|
||||
BaseItemKind,
|
||||
ItemFields,
|
||||
ItemFilter,
|
||||
LocationType,
|
||||
type MediaSegmentDtoQueryResult,
|
||||
type PlaybackInfoResponse,
|
||||
SortOrder,
|
||||
} from "@jellyfin/sdk/lib/generated-client";
|
||||
import { getDisplayPreferencesApi } from "@jellyfin/sdk/lib/utils/api/display-preferences-api";
|
||||
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 { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api";
|
||||
import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api";
|
||||
import type { SxProps } from "@mui/material";
|
||||
import Button, { type ButtonProps } from "@mui/material/Button";
|
||||
import Fab from "@mui/material/Fab";
|
||||
@@ -24,16 +11,14 @@ import LinearProgress from "@mui/material/LinearProgress";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import type { AxiosResponse } from "axios";
|
||||
import { useSnackbar } from "notistack";
|
||||
import React, { type MouseEvent, memo } from "react"; // Import memo
|
||||
import type PlayResult from "@//utils/types/playResult";
|
||||
import { getRuntimeCompact } from "@/utils/date/time";
|
||||
import getSubtitle from "@/utils/methods/getSubtitles";
|
||||
import playbackProfile from "@/utils/playback-profiles";
|
||||
import { getNextEpisode, getPlaybackInfo } from "@/utils/methods/playback";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
import { generateAudioStreamUrl, playAudio } from "@/utils/store/audioPlayback";
|
||||
import { useCentralStore } from "@/utils/store/central";
|
||||
import { usePhotosPlayback } from "@/utils/store/photosPlayback";
|
||||
import { playItem } from "@/utils/store/playback";
|
||||
import { setQueue } from "@/utils/store/queue";
|
||||
@@ -73,7 +58,7 @@ const MemoizedLinearProgress = memo(({ value }: { value: number }) => (
|
||||
zIndex: 0,
|
||||
mixBlendMode: "difference",
|
||||
}}
|
||||
//@ts-ignore
|
||||
//@ts-expect-error
|
||||
color="white"
|
||||
/>
|
||||
));
|
||||
@@ -95,7 +80,6 @@ const PlayButton = ({
|
||||
playlistItemId = "",
|
||||
}: PlayButtonProps) => {
|
||||
const api = useApiInContext((s) => s.api);
|
||||
const user = useCentralStore((s) => s.currentUser);
|
||||
const navigate = useNavigate();
|
||||
// const setPlaybackDataLoading = usePlaybackDataLoadStore(
|
||||
// (state) => state.setisPending,
|
||||
@@ -107,348 +91,23 @@ const PlayButton = ({
|
||||
const itemQuery = useMutation({
|
||||
mutationKey: ["playButton", item?.Id, userId],
|
||||
mutationFn: async (currentEpisodeId?: string) => {
|
||||
// setPlaybackDataLoading(true);
|
||||
|
||||
/**
|
||||
* Item / Items QueryResult
|
||||
*/
|
||||
let result: undefined | AxiosResponse<BaseItemDtoQueryResult, any>;
|
||||
/**
|
||||
* Current item MediaSource info
|
||||
*/
|
||||
let mediaSource: undefined | AxiosResponse<PlaybackInfoResponse, any>;
|
||||
/**
|
||||
* Current item MediaSegments
|
||||
*/
|
||||
let mediaSegments: undefined | MediaSegmentDtoQueryResult;
|
||||
/**
|
||||
* Index of episode or item in queue
|
||||
*/
|
||||
let index = 0;
|
||||
if (!api) {
|
||||
throw new Error("API is not available");
|
||||
}
|
||||
if (!userId) {
|
||||
throw new Error("User ID is not available");
|
||||
}
|
||||
if (!item.Id) {
|
||||
throw new Error("Item ID is not available");
|
||||
}
|
||||
if (playlistItem) {
|
||||
result = await getPlaylistsApi(api).getPlaylistItems({
|
||||
userId: userId,
|
||||
playlistId: playlistItemId,
|
||||
});
|
||||
} else {
|
||||
switch (itemType) {
|
||||
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,
|
||||
// startItemId: item.Id,
|
||||
});
|
||||
|
||||
if (
|
||||
result.data.Items?.map((i) => i.Id).indexOf(
|
||||
currentEpisodeId,
|
||||
) === -1
|
||||
) {
|
||||
throw new Error(
|
||||
`Episode having id ${currentEpisodeId} not found, index return -1`,
|
||||
);
|
||||
}
|
||||
index =
|
||||
result.data.Items?.map((i) => i.Id).indexOf(currentEpisodeId) ??
|
||||
0;
|
||||
if (currentAudioTrack === "auto") {
|
||||
const defaultAudioStreamIndex =
|
||||
result.data.Items?.[index].MediaSources?.[0]
|
||||
.DefaultAudioStreamIndex;
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: Number(defaultAudioStreamIndex),
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: result.data.Items?.[index]?.Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[index].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[index].MediaSources?.[0]?.Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: currentAudioTrack,
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: result.data.Items?.[index]?.Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[index].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[index].MediaSources?.[0]?.Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
}
|
||||
mediaSegments = (
|
||||
await getMediaSegmentsApi(api).getItemSegments({
|
||||
itemId: result.data.Items?.[index]?.Id ?? "",
|
||||
})
|
||||
)?.data;
|
||||
}
|
||||
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 &&
|
||||
result.data.Items?.map((i) => i.Id).indexOf(currentEpisodeId) ===
|
||||
-1
|
||||
) {
|
||||
throw new Error(
|
||||
`Episode having id=${currentEpisodeId} not found, index return -1`,
|
||||
);
|
||||
}
|
||||
if (!currentEpisodeId) {
|
||||
index = 0;
|
||||
} else {
|
||||
index =
|
||||
result.data.Items?.map((i) => i.Id).indexOf(currentEpisodeId) ??
|
||||
0;
|
||||
}
|
||||
if (
|
||||
result.data.Items?.[index].Id &&
|
||||
result.data.Items?.[index].MediaSources?.[0]?.Id
|
||||
) {
|
||||
if (currentAudioTrack === "auto") {
|
||||
const defaultAudioStreamIndex =
|
||||
result?.data.Items?.[
|
||||
index
|
||||
].MediaSources?.[0].MediaStreams?.find(
|
||||
(track) => track.IsDefault,
|
||||
)?.Index ??
|
||||
result?.data.Items?.[
|
||||
index
|
||||
].MediaSources?.[0].MediaStreams?.find(
|
||||
(track) =>
|
||||
track.Language ===
|
||||
user?.Configuration?.AudioLanguagePreference,
|
||||
)?.Index ??
|
||||
result.data.Items?.[index].MediaSources?.[0]
|
||||
.DefaultAudioStreamIndex;
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: Number(defaultAudioStreamIndex),
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: result.data.Items[index].Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[0].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[index].MediaSources?.[0].Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: currentAudioTrack,
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: result.data.Items[index].Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[0].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[index].MediaSources?.[0].Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
mediaSegments = (
|
||||
await getMediaSegmentsApi(api).getItemSegments({
|
||||
itemId: result.data.Items?.[index].Id ?? "",
|
||||
})
|
||||
)?.data;
|
||||
} else {
|
||||
throw new Error(
|
||||
`No media source id provieded for the episode. Return values are seriesId = ${result.data.Items?.[index].Id}, mediaSourceId = ${result.data.Items?.[index].MediaSources?.[0]?.Id}, index = ${index}`,
|
||||
);
|
||||
}
|
||||
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"],
|
||||
});
|
||||
if (
|
||||
result.data.Items?.[index]?.Id &&
|
||||
result.data.Items?.[index].MediaSources?.[0]?.Id
|
||||
) {
|
||||
if (currentAudioTrack === "auto") {
|
||||
const defaultAudioStreamIndex =
|
||||
result.data.Items?.[index].MediaSources?.[0]
|
||||
.DefaultAudioStreamIndex;
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: Number(defaultAudioStreamIndex),
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: result.data.Items?.[index].Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[0].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[index].MediaSources?.[0].Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: currentAudioTrack,
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: result.data.Items?.[index].Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[0].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[index].MediaSources?.[0].Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
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"],
|
||||
});
|
||||
if (currentAudioTrack === "auto") {
|
||||
const defaultAudioStreamIndex =
|
||||
result.data.Items?.[index].MediaSources?.[0]
|
||||
.DefaultAudioStreamIndex;
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: Number(defaultAudioStreamIndex),
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: item.Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[0].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[0].MediaSources?.[0]?.Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: currentAudioTrack,
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: item.Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[0].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[0].MediaSources?.[0]?.Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return {
|
||||
item: result?.data,
|
||||
mediaSource: mediaSource?.data,
|
||||
mediaSegments,
|
||||
episodeIndex: index,
|
||||
};
|
||||
return await getPlaybackInfo(api, userId, item, {
|
||||
currentAudioTrack,
|
||||
currentSubTrack,
|
||||
currentEpisodeId,
|
||||
playlistItem,
|
||||
playlistItemId,
|
||||
});
|
||||
},
|
||||
onSuccess: async (result: PlayResult | null) => {
|
||||
if (!api) {
|
||||
@@ -472,14 +131,6 @@ const PlayButton = ({
|
||||
return;
|
||||
}
|
||||
|
||||
const displayPreferences = await getDisplayPreferencesApi(
|
||||
api,
|
||||
).getDisplayPreferences({
|
||||
userId: userId,
|
||||
displayPreferencesId: api.deviceInfo.id,
|
||||
client: "blink",
|
||||
});
|
||||
|
||||
if (audio) {
|
||||
// Album/Individual audio track playback
|
||||
const playbackUrl = generateAudioStreamUrl(
|
||||
@@ -522,41 +173,55 @@ const PlayButton = ({
|
||||
}
|
||||
|
||||
// Subtitle
|
||||
const userSubtitleLanguagePreference = (await getUserApi(api).getCurrentUser()).data.Configuration?.SubtitleLanguagePreference;
|
||||
const userSubtitleLanguagePreference = (
|
||||
await getUserApi(api).getCurrentUser()
|
||||
).data.Configuration?.SubtitleLanguagePreference;
|
||||
// Get all subtitle streams
|
||||
const allSubtitles = result?.mediaSource?.MediaSources?.[0]?.MediaStreams?.filter(
|
||||
(stream) => stream.Type === "Subtitle"
|
||||
);
|
||||
const allSubtitles =
|
||||
result?.mediaSource?.MediaSources?.[0]?.MediaStreams?.filter(
|
||||
(stream) => stream.Type === "Subtitle",
|
||||
);
|
||||
// Find preferred subtitle based on user's language preference
|
||||
const preferredSubtitle =
|
||||
allSubtitles?.find(sub => sub.Language === userSubtitleLanguagePreference)
|
||||
|| null;
|
||||
allSubtitles?.find(
|
||||
(sub) => sub.Language === userSubtitleLanguagePreference,
|
||||
) || null;
|
||||
|
||||
const subtitle = getSubtitle(
|
||||
preferredSubtitle?.Index ?? result.mediaSource.MediaSources?.[0].DefaultSubtitleStreamIndex ?? -1,
|
||||
preferredSubtitle?.Index ??
|
||||
result.mediaSource.MediaSources?.[0].DefaultSubtitleStreamIndex ??
|
||||
-1,
|
||||
result?.mediaSource?.MediaSources?.[0]?.MediaStreams,
|
||||
);
|
||||
|
||||
// Audio
|
||||
const userAudioLanguagePreference = (await getUserApi(api).getCurrentUser()).data.Configuration?.AudioLanguagePreference;
|
||||
const userAudioLanguagePreference = (
|
||||
await getUserApi(api).getCurrentUser()
|
||||
).data.Configuration?.AudioLanguagePreference;
|
||||
// Get all audio streams
|
||||
const allAudioTracks = result.mediaSource.MediaSources?.[0].MediaStreams?.filter(
|
||||
(value) => value.Type === "Audio",
|
||||
);
|
||||
const allAudioTracks =
|
||||
result.mediaSource.MediaSources?.[0].MediaStreams?.filter(
|
||||
(value) => value.Type === "Audio",
|
||||
);
|
||||
// Find preferred audio track based on user's language preference
|
||||
const preferredAudioTrack =
|
||||
allAudioTracks?.find(track => track.Language === userAudioLanguagePreference)
|
||||
|| allAudioTracks?.find(track => track.IsDefault)
|
||||
|| allAudioTracks?.[0];
|
||||
const preferredAudioTrack =
|
||||
allAudioTracks?.find(
|
||||
(track) => track.Language === userAudioLanguagePreference,
|
||||
) ||
|
||||
allAudioTracks?.find((track) => track.IsDefault) ||
|
||||
allAudioTracks?.[0];
|
||||
|
||||
const audio = {
|
||||
track: preferredAudioTrack?.Index ?? result.mediaSource.MediaSources?.[0].DefaultAudioStreamIndex ?? 0,
|
||||
track:
|
||||
preferredAudioTrack?.Index ??
|
||||
result.mediaSource.MediaSources?.[0].DefaultAudioStreamIndex ??
|
||||
0,
|
||||
allTracks: allAudioTracks,
|
||||
};
|
||||
|
||||
// URL generation
|
||||
const urlOptions: URLSearchParams = {
|
||||
//@ts-ignore
|
||||
//@ts-expect-error
|
||||
Static: true,
|
||||
tag: result?.mediaSource.MediaSources?.[0].ETag,
|
||||
mediaSourceId: result?.mediaSource.MediaSources?.[0].Id,
|
||||
@@ -579,14 +244,6 @@ const PlayButton = ({
|
||||
const startPosition =
|
||||
result?.item?.Items?.[episodeIndex].UserData?.PlaybackPositionTicks;
|
||||
|
||||
let initVolume = "1";
|
||||
if (
|
||||
displayPreferences.data.CustomPrefs?.RememberVolume &&
|
||||
displayPreferences.data.CustomPrefs?.Volume
|
||||
) {
|
||||
initVolume = displayPreferences.data.CustomPrefs?.Volume;
|
||||
}
|
||||
|
||||
const videoTrack =
|
||||
result.mediaSource.MediaSources?.[0].MediaStreams?.filter(
|
||||
(value) => value.Type === "Video",
|
||||
@@ -659,46 +316,44 @@ const PlayButton = ({
|
||||
if (!item.Id) {
|
||||
throw new Error("Item ID is not available");
|
||||
}
|
||||
let data: BaseItemDtoQueryResult | null = null;
|
||||
const continueWatching = await getItemsApi(api).getResumeItems({
|
||||
const seasons = await getTvShowsApi(api).getSeasons({
|
||||
seriesId: item.Id,
|
||||
userId: userId,
|
||||
limit: 1,
|
||||
mediaTypes: ["Video"],
|
||||
parentId: item.Id,
|
||||
enableUserData: true,
|
||||
fields: [ItemFields.MediaStreams, ItemFields.MediaSources],
|
||||
});
|
||||
const nextUp = await getTvShowsApi(api).getNextUp({
|
||||
userId: userId,
|
||||
parentId: item.Id,
|
||||
limit: 1,
|
||||
|
||||
const currentSeason = seasons.data.Items?.find((season) => {
|
||||
return season.UserData?.Played !== true;
|
||||
});
|
||||
if ((continueWatching.data.Items?.length ?? 0) > 0) {
|
||||
data = continueWatching.data;
|
||||
} else if ((nextUp.data.Items?.length ?? 0) > 0) {
|
||||
data = nextUp.data;
|
||||
} else {
|
||||
return null;
|
||||
|
||||
const episode = await getNextEpisode(
|
||||
api,
|
||||
userId,
|
||||
item.Id,
|
||||
currentSeason?.IndexNumber ?? 0,
|
||||
);
|
||||
if (episode) {
|
||||
return { Items: [episode] };
|
||||
}
|
||||
return data;
|
||||
return { Items: [] };
|
||||
},
|
||||
// enabled: itemType === BaseItemKind.Series,
|
||||
});
|
||||
|
||||
if (iconOnly) {
|
||||
return (
|
||||
//@ts-ignore
|
||||
//@ts-expect-error
|
||||
<Fab
|
||||
color="primary"
|
||||
aria-label="Play"
|
||||
className={className}
|
||||
onClick={(e) => {
|
||||
if (item.Type === "Episode") {
|
||||
handleClick(e, item.Id)
|
||||
handleClick(e, item.Id);
|
||||
} else if (itemType === BaseItemKind.Series) {
|
||||
handleClick(e, currentEpisode.data?.Items?.[0]?.Id)
|
||||
handleClick(e, currentEpisode.data?.Items?.[0]?.Id);
|
||||
} else {
|
||||
handleClick(e)
|
||||
handleClick(e);
|
||||
}
|
||||
}}
|
||||
sx={sx}
|
||||
@@ -759,7 +414,7 @@ const PlayButton = ({
|
||||
position: "relative",
|
||||
overflow: "hidden",
|
||||
}}
|
||||
//@ts-ignore - white color is a custom color in the theme which mui's types don't know about
|
||||
//@ts-expect-error - white color is a custom color in the theme which mui's types don't know about
|
||||
color="white"
|
||||
size={size}
|
||||
disabled={
|
||||
@@ -770,31 +425,30 @@ const PlayButton = ({
|
||||
!currentEpisode.data.Items[0].Id
|
||||
}
|
||||
>
|
||||
{currentEpisode.isPending
|
||||
? "Loading..."
|
||||
: !currentEpisode.data ||
|
||||
!currentEpisode.data.Items ||
|
||||
currentEpisode.data.Items.length === 0
|
||||
? "No episodes to watch found"
|
||||
: (
|
||||
<>
|
||||
Watch S{currentEpisode.data.Items[0].ParentIndexNumber ?? 1}E
|
||||
{currentEpisode.data.Items[0]?.IndexNumber ?? 1}
|
||||
<MemoizedLinearProgress
|
||||
//@ts-ignore
|
||||
value={
|
||||
100 >
|
||||
(currentEpisode.data.Items[0].UserData?.PlayedPercentage ??
|
||||
100) &&
|
||||
{currentEpisode.isPending ? (
|
||||
"Loading..."
|
||||
) : !currentEpisode.data ||
|
||||
!currentEpisode.data.Items ||
|
||||
currentEpisode.data.Items.length === 0 ? (
|
||||
"No episodes to watch found"
|
||||
) : (
|
||||
<>
|
||||
Watch S{currentEpisode.data.Items[0].ParentIndexNumber ?? 1}E
|
||||
{currentEpisode.data.Items[0]?.IndexNumber ?? 1}
|
||||
<MemoizedLinearProgress
|
||||
//@ts-expect-error
|
||||
value={
|
||||
100 >
|
||||
(currentEpisode.data.Items[0].UserData?.PlayedPercentage ??
|
||||
0) > 0
|
||||
? currentEpisode.data.Items[0].UserData?.PlayedPercentage
|
||||
: 0
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
100) &&
|
||||
(currentEpisode.data.Items[0].UserData?.PlayedPercentage ??
|
||||
0) > 0
|
||||
? currentEpisode.data.Items[0].UserData?.PlayedPercentage
|
||||
: 0
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
{(currentEpisode.data?.Items?.[0]?.UserData?.PlaybackPositionTicks ??
|
||||
0) > 0 && (
|
||||
@@ -849,7 +503,7 @@ const PlayButton = ({
|
||||
position: "relative",
|
||||
overflow: "hidden",
|
||||
}}
|
||||
//@ts-ignore - white color is a custom color in the theme which mui's types don't know about
|
||||
//@ts-expect-error - white color is a custom color in the theme which mui's types don't know about
|
||||
color="white"
|
||||
size={size}
|
||||
>
|
||||
@@ -863,7 +517,7 @@ const PlayButton = ({
|
||||
? "Play Now"
|
||||
: "Watch Now"}
|
||||
<MemoizedLinearProgress
|
||||
//@ts-ignore
|
||||
//@ts-expect-error
|
||||
value={
|
||||
100 > (item.UserData?.PlayedPercentage ?? 100) &&
|
||||
(item.UserData?.PlayedPercentage ?? 0) > 0
|
||||
|
||||
+124
-79
@@ -1,40 +1,24 @@
|
||||
/** @format */
|
||||
|
||||
|
||||
import {
|
||||
type BaseItemDto,
|
||||
BaseItemKind,
|
||||
type ImageType,
|
||||
} from "@jellyfin/sdk/lib/generated-client";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import React, { memo } from "react";
|
||||
import type React from "react";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import { ErrorBoundary } from "react-error-boundary";
|
||||
import { useInView } from "react-intersection-observer";
|
||||
import getImageUrlsApi from "@/utils/methods/getImageUrlsApi";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
import LikeButton from "../buttons/likeButton";
|
||||
import MarkPlayedButton from "../buttons/markPlayedButton";
|
||||
import PlayButton from "../buttons/playButton";
|
||||
import { getTypeIcon } from "../utils/iconsCollection";
|
||||
import "./card.scss";
|
||||
|
||||
import { useInView } from "react-intersection-observer";
|
||||
import getImageUrlsApi from "@/utils/methods/getImageUrlsApi";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
|
||||
const CardComponent = ({
|
||||
item,
|
||||
cardTitle,
|
||||
cardCaption,
|
||||
imageType = "Primary",
|
||||
cardType = "square",
|
||||
queryKey,
|
||||
userId,
|
||||
seriesId,
|
||||
hideText = false,
|
||||
onClick,
|
||||
disableOverlay = false,
|
||||
overrideIcon,
|
||||
skipInView = false,
|
||||
}: {
|
||||
interface CardProps {
|
||||
item: BaseItemDto;
|
||||
cardTitle: string | undefined | null;
|
||||
cardCaption?: string | null | number;
|
||||
@@ -48,10 +32,32 @@ const CardComponent = ({
|
||||
disableOverlay?: boolean;
|
||||
overrideIcon?: any;
|
||||
skipInView?: boolean;
|
||||
}
|
||||
|
||||
const CardContent = ({
|
||||
item,
|
||||
cardTitle,
|
||||
cardCaption,
|
||||
imageType = "Primary",
|
||||
cardType = "square",
|
||||
queryKey,
|
||||
userId,
|
||||
seriesId,
|
||||
hideText = false,
|
||||
onClick,
|
||||
disableOverlay = false,
|
||||
overrideIcon,
|
||||
inView,
|
||||
forwardedRef,
|
||||
}: CardProps & {
|
||||
inView: boolean;
|
||||
forwardedRef?: React.Ref<HTMLDivElement>;
|
||||
}) => {
|
||||
const api = useApiInContext((s) => s.api);
|
||||
const navigate = useNavigate();
|
||||
const defaultOnClick = () => {
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
|
||||
const defaultOnClick = useCallback(() => {
|
||||
if (item?.Id) {
|
||||
switch (item?.Type) {
|
||||
case BaseItemKind.BoxSet:
|
||||
@@ -80,21 +86,23 @@ const CardComponent = ({
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
}, [item?.Id, item?.Type, navigate]);
|
||||
|
||||
const { ref, inView } = useInView({
|
||||
threshold: 0.1,
|
||||
skip: skipInView,
|
||||
});
|
||||
const handleInteractionStart = useCallback(() => setIsHovered(true), []);
|
||||
const handleInteractionEnd = useCallback(() => setIsHovered(false), []);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="card"
|
||||
ref={ref}
|
||||
onClick={onClick ? onClick : defaultOnClick}
|
||||
ref={forwardedRef}
|
||||
onClick={onClick || defaultOnClick}
|
||||
onMouseEnter={handleInteractionStart}
|
||||
onMouseLeave={handleInteractionEnd}
|
||||
onFocus={handleInteractionStart}
|
||||
onBlur={handleInteractionEnd}
|
||||
>
|
||||
<div className={`card-image-container ${cardType}`}>
|
||||
<ErrorBoundary fallback>
|
||||
<ErrorBoundary fallback={<></>}>
|
||||
<div
|
||||
className="card-indicator check"
|
||||
style={{
|
||||
@@ -109,13 +117,17 @@ const CardComponent = ({
|
||||
opacity: item.UserData?.UnplayedItemCount ? 1 : 0,
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant="subtitle2"
|
||||
padding="0.1em 0.4em"
|
||||
fontWeight={400}
|
||||
<span
|
||||
style={{
|
||||
padding: "0.1em 0.4em",
|
||||
fontWeight: 400,
|
||||
fontSize: "0.875rem",
|
||||
lineHeight: 1.57,
|
||||
fontFamily: "inherit",
|
||||
}}
|
||||
>
|
||||
{item.UserData?.UnplayedItemCount}
|
||||
</Typography>
|
||||
</span>
|
||||
</div>
|
||||
</ErrorBoundary>
|
||||
<div className="card-image-icon-container">
|
||||
@@ -123,7 +135,7 @@ const CardComponent = ({
|
||||
? getTypeIcon(overrideIcon)
|
||||
: getTypeIcon(item.Type ?? "universal")}
|
||||
</div>
|
||||
{(skipInView || inView) && (
|
||||
{inView && (
|
||||
<img
|
||||
alt={item.Name ?? "blink"}
|
||||
src={
|
||||
@@ -146,48 +158,53 @@ const CardComponent = ({
|
||||
width: "100%",
|
||||
opacity: 0,
|
||||
display: "block",
|
||||
transition: "opacity 0.3s ease-in-out",
|
||||
}}
|
||||
loading="lazy"
|
||||
onLoad={(e) => {
|
||||
e.currentTarget.style.setProperty("opacity", "1");
|
||||
e.currentTarget.style.opacity = "1";
|
||||
}}
|
||||
className="card-image"
|
||||
/>
|
||||
)}
|
||||
{(skipInView || inView) && !disableOverlay && (
|
||||
{inView && !disableOverlay && (
|
||||
<div className="card-overlay">
|
||||
<PlayButton
|
||||
item={item}
|
||||
userId={userId}
|
||||
itemType={item.Type ?? "Movie"}
|
||||
currentAudioTrack="auto"
|
||||
currentSubTrack={-1}
|
||||
currentVideoTrack={0}
|
||||
className="card-play-button"
|
||||
iconOnly
|
||||
audio={
|
||||
item.Type === BaseItemKind.MusicAlbum ||
|
||||
item.Type === BaseItemKind.Audio ||
|
||||
item.Type === BaseItemKind.AudioBook ||
|
||||
item.Type === BaseItemKind.Playlist
|
||||
}
|
||||
playlistItem={item.Type === BaseItemKind.Playlist}
|
||||
playlistItemId={item.Id}
|
||||
/>
|
||||
<LikeButton
|
||||
itemId={item.Id}
|
||||
itemName={item.Name ?? ""}
|
||||
isFavorite={item.UserData?.IsFavorite}
|
||||
queryKey={queryKey}
|
||||
userId={userId}
|
||||
/>
|
||||
<MarkPlayedButton
|
||||
itemId={item.Id}
|
||||
itemName={item.Name ?? ""}
|
||||
isPlayed={item.UserData?.Played}
|
||||
queryKey={queryKey}
|
||||
userId={userId}
|
||||
/>
|
||||
{isHovered && (
|
||||
<>
|
||||
<PlayButton
|
||||
item={item}
|
||||
userId={userId}
|
||||
itemType={item.Type ?? "Movie"}
|
||||
currentAudioTrack="auto"
|
||||
currentSubTrack={-1}
|
||||
currentVideoTrack={0}
|
||||
className="card-play-button"
|
||||
iconOnly
|
||||
audio={
|
||||
item.Type === BaseItemKind.MusicAlbum ||
|
||||
item.Type === BaseItemKind.Audio ||
|
||||
item.Type === BaseItemKind.AudioBook ||
|
||||
item.Type === BaseItemKind.Playlist
|
||||
}
|
||||
playlistItem={item.Type === BaseItemKind.Playlist}
|
||||
playlistItemId={item.Id}
|
||||
/>
|
||||
<LikeButton
|
||||
itemId={item.Id}
|
||||
itemName={item.Name ?? ""}
|
||||
isFavorite={item.UserData?.IsFavorite}
|
||||
queryKey={queryKey}
|
||||
userId={userId}
|
||||
/>
|
||||
<MarkPlayedButton
|
||||
itemId={item.Id}
|
||||
itemName={item.Name ?? ""}
|
||||
isPlayed={item.UserData?.Played}
|
||||
queryKey={queryKey}
|
||||
userId={userId}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{(item.UserData?.PlaybackPositionTicks ?? -1) > 0 && (
|
||||
@@ -205,20 +222,48 @@ const CardComponent = ({
|
||||
className="card-text-container"
|
||||
style={{ display: hideText ? "none" : "block", marginLeft: "0.2em" }}
|
||||
>
|
||||
<Typography mt={1} variant="subtitle2" noWrap style={{ opacity: 0.9 }}>
|
||||
<div
|
||||
style={{
|
||||
marginTop: "8px",
|
||||
opacity: 0.9,
|
||||
fontSize: "0.875rem",
|
||||
fontWeight: 500,
|
||||
whiteSpace: "nowrap",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
}}
|
||||
>
|
||||
{cardTitle}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="caption"
|
||||
noWrap
|
||||
style={{ opacity: 0.6 }}
|
||||
lineHeight="auto"
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
opacity: 0.6,
|
||||
fontSize: "0.75rem",
|
||||
whiteSpace: "nowrap",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
}}
|
||||
>
|
||||
{cardCaption}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const CardWithInView = (props: CardProps) => {
|
||||
const { ref, inView } = useInView({
|
||||
threshold: 0.1,
|
||||
});
|
||||
|
||||
return <CardContent {...props} inView={inView} forwardedRef={ref} />;
|
||||
};
|
||||
|
||||
const CardComponent = (props: CardProps) => {
|
||||
if (props.skipInView) {
|
||||
return <CardContent {...props} inView={true} />;
|
||||
}
|
||||
return <CardWithInView {...props} />;
|
||||
};
|
||||
|
||||
export const Card = memo(CardComponent);
|
||||
@@ -0,0 +1,7 @@
|
||||
import React from "react";
|
||||
|
||||
const ItemHeader = () => {
|
||||
return <div>Item Header</div>;
|
||||
};
|
||||
|
||||
export default ItemHeader;
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
} from "@jellyfin/sdk/lib/generated-client";
|
||||
import { useSuspenseQuery } from "@tanstack/react-query";
|
||||
import { getRouteApi } from "@tanstack/react-router";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { useWindowVirtualizer } from "@tanstack/react-virtual";
|
||||
import React, {
|
||||
useCallback,
|
||||
useEffect,
|
||||
@@ -20,6 +20,8 @@ import { useApiInContext } from "@/utils/store/api";
|
||||
import { useBackdropStore } from "@/utils/store/backdrop";
|
||||
import { useCentralStore } from "@/utils/store/central";
|
||||
import { useLibraryStateStore } from "@/utils/store/libraryState";
|
||||
// @ts-expect-error: Vite worker import
|
||||
import BackdropWorker from "@/utils/workers/backdrop.worker?worker";
|
||||
import { Card } from "../card/card";
|
||||
|
||||
const libraryRoute = getRouteApi("/_api/library/$id");
|
||||
@@ -64,6 +66,20 @@ const LibraryItemsGrid = () => {
|
||||
const currentLibrary = useSuspenseQuery(
|
||||
getLibraryQueryOptions(api, user?.Id, currentLibraryId),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (currentLibraryId && !currentViewType && currentLibrary.data?.Type) {
|
||||
updateLibrary(currentLibraryId, {
|
||||
currentViewType: currentLibrary.data.Type as BaseItemKind,
|
||||
});
|
||||
}
|
||||
}, [
|
||||
currentLibrary.data?.Type,
|
||||
currentLibraryId,
|
||||
currentViewType,
|
||||
updateLibrary,
|
||||
]);
|
||||
|
||||
const items = useSuspenseQuery(
|
||||
getLibraryItemsQueryOptions(api, user?.Id, currentLibraryId, {
|
||||
currentViewType,
|
||||
@@ -78,44 +94,39 @@ const LibraryItemsGrid = () => {
|
||||
);
|
||||
// --- Backdrop ---
|
||||
const setBackdrop = useBackdropStore(useShallow((s) => s.setBackdrop));
|
||||
const backdropIndexRef = useRef(0);
|
||||
const backdropItems = useMemo<BaseItemDto[]>(() => {
|
||||
if (!items.isSuccess || !items.data?.Items) return [];
|
||||
return items.data.Items.filter(
|
||||
(item) => Object.keys(item.ImageBlurHashes?.Backdrop ?? {}).length > 0,
|
||||
);
|
||||
}, [items.isSuccess, items.data?.Items]);
|
||||
useEffect(() => {
|
||||
if (!api || !backdropItems || backdropItems.length === 0) return;
|
||||
// Set initial backdrop once when items change
|
||||
const firstBackdrop = backdropItems[0];
|
||||
const firstKey = Object.keys(
|
||||
firstBackdrop?.ImageBlurHashes?.Backdrop ?? {},
|
||||
)[0];
|
||||
const initialHash = firstBackdrop?.ImageBlurHashes?.Backdrop?.[firstKey];
|
||||
if (initialHash) setBackdrop(initialHash);
|
||||
backdropIndexRef.current = 0;
|
||||
|
||||
const intervalId = setInterval(() => {
|
||||
backdropIndexRef.current =
|
||||
(backdropIndexRef.current + 1) % backdropItems.length;
|
||||
const idx = backdropIndexRef.current;
|
||||
const keys = Object.keys(
|
||||
backdropItems[idx]?.ImageBlurHashes?.Backdrop ?? {},
|
||||
);
|
||||
const nextHash = backdropItems[idx]?.ImageBlurHashes?.Backdrop?.[keys[0]];
|
||||
if (nextHash) {
|
||||
// Defer backdrop update to idle/raf to avoid blocking UI
|
||||
useEffect(() => {
|
||||
const worker = new BackdropWorker();
|
||||
|
||||
worker.onmessage = (event: MessageEvent) => {
|
||||
if (event.data.type === "UPDATE_BACKDROP") {
|
||||
const schedule =
|
||||
(window as any).requestIdleCallback || window.requestAnimationFrame;
|
||||
schedule(() => setBackdrop(nextHash));
|
||||
schedule(() => setBackdrop(event.data.payload));
|
||||
}
|
||||
}, 10_000); // Update backdrop every 10s
|
||||
return () => clearInterval(intervalId);
|
||||
}, [api, backdropItems, setBackdrop]);
|
||||
};
|
||||
|
||||
if (backdropItems.length > 0) {
|
||||
worker.postMessage({
|
||||
type: "SET_BACKDROP_ITEMS",
|
||||
payload: backdropItems,
|
||||
});
|
||||
worker.postMessage({ type: "START" });
|
||||
}
|
||||
|
||||
return () => {
|
||||
worker.postMessage({ type: "STOP" });
|
||||
worker.terminate();
|
||||
};
|
||||
}, [backdropItems, setBackdrop]);
|
||||
// --- Virtualization setup ---
|
||||
const parentRef = useRef<HTMLDivElement | null>(null);
|
||||
const scrollParentRef = useRef<HTMLElement | null>(null);
|
||||
const [containerWidth, setContainerWidth] = useState<number>(0);
|
||||
|
||||
// Determine column count based on container width (simple heuristic)
|
||||
@@ -132,10 +143,7 @@ const LibraryItemsGrid = () => {
|
||||
useEffect(() => {
|
||||
measureColumns();
|
||||
if (!parentRef.current) return;
|
||||
// Find the page's scroll container ('.scrollY') to avoid nested scrolling
|
||||
scrollParentRef.current = parentRef.current.closest(
|
||||
".scrollY",
|
||||
) as HTMLElement | null;
|
||||
|
||||
const ro = new ResizeObserver(() => measureColumns());
|
||||
ro.observe(parentRef.current);
|
||||
return () => ro.disconnect();
|
||||
@@ -166,11 +174,11 @@ const LibraryItemsGrid = () => {
|
||||
[estimatedTallCardHeight],
|
||||
);
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
const virtualizer = useWindowVirtualizer({
|
||||
count: rowCount,
|
||||
getScrollElement: () => scrollParentRef.current,
|
||||
estimateSize: estimateRowHeight,
|
||||
overscan: 2,
|
||||
overscan: 6,
|
||||
scrollMargin: parentRef.current?.offsetTop ?? 0,
|
||||
});
|
||||
|
||||
const virtualItems = virtualizer.getVirtualItems();
|
||||
@@ -229,7 +237,9 @@ const LibraryItemsGrid = () => {
|
||||
key={row.key}
|
||||
style={{
|
||||
position: "absolute",
|
||||
transform: `translateY(${row.start}px)`,
|
||||
transform: `translateY(${
|
||||
row.start - virtualizer.options.scrollMargin
|
||||
}px)`,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
display: "flex",
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ const router = createRouter({
|
||||
fetchCurrentUser: undefined!,
|
||||
queryClient,
|
||||
},
|
||||
defaultPreload: "intent",
|
||||
defaultPreload: false,
|
||||
defaultPreloadStaleTime: 0,
|
||||
defaultViewTransition: true,
|
||||
scrollRestoration: true,
|
||||
|
||||
@@ -109,180 +109,4 @@ function Library() {
|
||||
</Suspense>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
// const genres = useQuery({
|
||||
// queryKey: ["library", "genreItem", id],
|
||||
// queryFn: async () => {
|
||||
// if (!api) return null;
|
||||
// if (currentLib.data?.CollectionType === "music") {
|
||||
// const result = await getMusicGenresApi(api).getMusicGenres({
|
||||
// parentId: id,
|
||||
// userId: user?.Id,
|
||||
// });
|
||||
// return result.data;
|
||||
// }
|
||||
// const result = await getGenresApi(api).getGenres({
|
||||
// parentId: id,
|
||||
// userId: user?.Id,
|
||||
// });
|
||||
// return result.data;
|
||||
// },
|
||||
// });
|
||||
|
||||
// const [genreFilter, setGenreFilter] = useState<string[]>(() => {
|
||||
// const cachedVal = sessionStorage.getItem(
|
||||
// `library-${currentLib.data?.Id}-config_genreFilter`,
|
||||
// );
|
||||
// if (cachedVal) {
|
||||
// return JSON.parse(cachedVal);
|
||||
// }
|
||||
// return [];
|
||||
// });
|
||||
// const _handleGenreFilter = useCallback(
|
||||
// (e: ChangeEvent<HTMLInputElement>, genre: BaseItemDto) => {
|
||||
// if (e.target.checked) {
|
||||
// const genreFilterTemp = [...genreFilter, genre.Id];
|
||||
// setGenreFilter((s) => (genre.Id ? [...s, genre.Id] : s));
|
||||
// sessionStorage.setItem(
|
||||
// `library-${currentLib.data?.Id}-config_genreFilter`,
|
||||
// JSON.stringify(genreFilterTemp),
|
||||
// );
|
||||
// } else {
|
||||
// const genreFilterTemp = genreFilter.filter((id) => id !== genre.Id);
|
||||
// setGenreFilter((s) => s.filter((id) => id !== genre.Id));
|
||||
// sessionStorage.setItem(
|
||||
// `library-${currentLib.data?.Id}-config_genreFilter`,
|
||||
// JSON.stringify(genreFilterTemp),
|
||||
// );
|
||||
// }
|
||||
// },
|
||||
// [genres.data?.Items?.length, id],
|
||||
// );
|
||||
|
||||
// const [currentViewType, setCurrentViewType] = useState<
|
||||
// BaseItemKind | "Artist"
|
||||
// >(undefined!);
|
||||
|
||||
// // DONE
|
||||
// const _availableViewTypes: ViewObject[] = useMemo(() => {
|
||||
// const result: ViewObject[] = undefined!;
|
||||
|
||||
// if (
|
||||
// sessionStorage.getItem(
|
||||
// `library-${currentLib.data?.Id}-config_currentViewType`,
|
||||
// )
|
||||
// ) {
|
||||
// setCurrentViewType(
|
||||
// sessionStorage.getItem(
|
||||
// `library-${currentLib.data?.Id}-config_currentViewType`,
|
||||
// ) as BaseItemKind | "Artist",
|
||||
// );
|
||||
// } else {
|
||||
// setCurrentViewType(result?.[0]?.value);
|
||||
// }
|
||||
// return result;
|
||||
// }, [currentLib.data?.CollectionType]);
|
||||
|
||||
// const [_videoTypesState, _setVideoTypesState] = useState<
|
||||
// Record<VideoType, boolean | undefined>
|
||||
// >({
|
||||
// VideoFile: undefined,
|
||||
// Iso: undefined,
|
||||
// BluRay: undefined,
|
||||
// Dvd: undefined,
|
||||
// });
|
||||
|
||||
// const [_sortBy, setSortBy] = useState<string>("Name");
|
||||
// const [_sortAscending, setSortAscending] = useState(
|
||||
// () =>
|
||||
// JSON.parse(
|
||||
// sessionStorage.getItem(
|
||||
// `library-${currentLib.data?.Id}-config_sort`,
|
||||
// ) as string,
|
||||
// )?.sortAscending ?? true,
|
||||
// );
|
||||
// useEffect(() => {
|
||||
// // I don't know why this works, don't ask...
|
||||
// const cachedVal = sessionStorage.getItem(
|
||||
// `library-${currentLib.data?.Id}-config_sort`,
|
||||
// ) as unknown as {
|
||||
// sortAscending?: boolean;
|
||||
// sortBy?: ItemSortBy;
|
||||
// };
|
||||
// if (cachedVal?.sortAscending) {
|
||||
// console.log(cachedVal.sortAscending);
|
||||
// setSortAscending(cachedVal.sortAscending);
|
||||
// }
|
||||
// }, [currentLib.data?.Id]);
|
||||
// const _sortByOptions: SortByObject[] = useMemo(() => {
|
||||
// const result: SortByObject[] = undefined!;
|
||||
|
||||
// const cachedVal = JSON.parse(
|
||||
// sessionStorage.getItem(
|
||||
// `library-${currentLib.data?.Id}-config_sort`,
|
||||
// ) as string,
|
||||
// );
|
||||
// if (cachedVal) {
|
||||
// setSortBy(cachedVal.sortBy);
|
||||
// } else {
|
||||
// setSortBy(result?.[0]?.value);
|
||||
// }
|
||||
// return result;
|
||||
// }, [currentLib.data?.CollectionType, currentViewType]);
|
||||
|
||||
// const [filters, _setFilters] = useState<Record<string, undefined | boolean>>(
|
||||
// () => {
|
||||
// const cachedVal = sessionStorage.getItem(
|
||||
// `library-${currentLib.data?.Id}-config_fliters`,
|
||||
// );
|
||||
// if (cachedVal !== null) {
|
||||
// return JSON.parse(cachedVal);
|
||||
// }
|
||||
// return {
|
||||
// isPlayed: false,
|
||||
// isUnPlayed: false,
|
||||
// isResumable: false,
|
||||
// isFavorite: false,
|
||||
// isLiked: false,
|
||||
// isUnliked: false,
|
||||
// hasSubtitles: false,
|
||||
// hasTrailer: false,
|
||||
// hasSpecialFeature: false,
|
||||
// hasThemeSong: false,
|
||||
// hasThemeVideo: false,
|
||||
// isBluRay: false,
|
||||
// isDVD: false,
|
||||
// isHD: undefined,
|
||||
// isSD: false,
|
||||
// is4K: false,
|
||||
// is3D: false,
|
||||
// };
|
||||
// },
|
||||
// );
|
||||
// useEffect(() => {
|
||||
// sessionStorage.setItem(
|
||||
// `library-${currentLib.data?.Id}-config_fliters`,
|
||||
// JSON.stringify(filters),
|
||||
// );
|
||||
// }, [filters, currentLib.data?.Id]);
|
||||
|
||||
// // const _rowVirtualizer = useWindowVirtualizer({
|
||||
// // count: items.data?.TotalRecordCount ?? 1,
|
||||
// // estimateSize: () => 80,
|
||||
// // overscan: 4,
|
||||
// // });
|
||||
// // const onlyStatusFilterViews = ["books", "music"];
|
||||
|
||||
// const [filterButtonAnchorEl, setFilterButtonAnchorEl] =
|
||||
// useState<HTMLButtonElement | null>(null);
|
||||
// const _filterMenuOpen = useMemo(
|
||||
// () => Boolean(filterButtonAnchorEl),
|
||||
// [filterButtonAnchorEl],
|
||||
// );
|
||||
// const _handleFilterDropdown = useCallback(
|
||||
// (e: MouseEvent<HTMLButtonElement>) => {
|
||||
// setFilterButtonAnchorEl(e.currentTarget);
|
||||
// },
|
||||
// [currentViewType, filterButtonAnchorEl],
|
||||
// );
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
Reference in new issue
Block a user