diff --git a/README.md b/README.md index 30781e9..1d7e543 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,24 @@ -![Banner](https://github.com/prayag17/JellyPlayer/assets/55829513/cefdd218-51ce-4180-be53-8fd69d9a63a2) +![Banner](https://i.imgur.com/4LECQq3.png) +
+GitHub Release +GitHub Repo stars +GitHub License +GitHub Actions Workflow Status +
-# 📝 Prerequisites +### + +> [!IMPORTANT] +> **JellyPlayer** has been renamed to **Blink** to avoid confusion with first party Jellyfin apps + +## 📝 Prerequisites - Nodejs (â‰Ĩ19.1.0) - Rust (â‰Ĩ1.76.0) - Visual Studio C++ Build tools - [pnpm](https://pnpm.io/) -# â„šī¸ Getting started +## â„šī¸ Getting started - Install Nodejs, pnpm and Rust. > **Note** : Install Rust from @@ -17,7 +28,7 @@ pnpm install ``` -# đŸ› ī¸ Development +## đŸ› ī¸ Development - Running the app: @@ -33,20 +44,23 @@ - other commands can be found inside the `"scripts"` inside [package.json](https://github.com/prayag17/JellyPlayer/blob/main/package.json) -# đŸ’ģ Contribution +## đŸ’ģ Contribution - Checkout `issues` to see currently worked on features and bugs - Add features or fix bugs - Create a pull request -# ✨ Features +## ✨ Features - Play any media supported by the system (DirectPlay most files on windows, mac and linux) - Clean and minimal UI. -- Multiple Jellyfin server support - and more... +- Multi Jellyfin server support +- Cross Platform +- Mediainfo recognition (DolbyVision, DolbyAtoms, Dts, Hdr10+, and more...) +- Sort/Filter library items +- Queue playback support -# 📷 Screenshots +## 📷 Screenshots - Home ![home](https://github.com/prayag17/JellyPlayer/assets/55829513/ffda4dc5-c147-4278-a232-bb58b1051501) @@ -61,12 +75,12 @@ - About Dialog ![about](https://github.com/prayag17/JellyPlayer/assets/55829513/fc3adf83-87fd-4901-8abd-39b148418f8d) -# 📃 Roadmap +## 📃 Roadmap - Checkout [GitHub Project](https://github.com/users/prayag17/projects/3) -# 🎊 Special thanks to +## 🎊 Special thanks to - [@ferferga](https://github.com/ferferga) for helping in development behind the scenes. - All contributors of [jellyfin/jellyfin-vue](https://github.com/jellyfin/jellyfin-vue). diff --git a/index.html b/index.html index ffd8af5..cc6dd97 100644 --- a/index.html +++ b/index.html @@ -12,7 +12,7 @@ left: 0; bottom: 0; right: 0; - background: hsl(256, 100%, 4%); + background: #222; z-index: 100000; display: flex; align-items: center; @@ -22,19 +22,70 @@ } .app-loading.hidden { - opacity: 0; - pointer-events: none; + display: none; } .app-loading-logo { - width: 65vw; + width: 40vw; + opacity: 0; + animation: fadeIn linear 500ms forwards; + } + + .circular { + animation: rotate 1.2s linear infinite; + height: 50px; + left: 50%; + position: absolute; + bottom: 20%; + width: 50px; + } + .path { + stroke-dasharray: 1,200; + stroke-dashoffset: 0; + animation: + dash 800ms ease-in-out infinite, + color 6s ease-in-out infinite + ; + stroke-linecap: round; + stroke: #fff; + } + + @keyframes rotate { + 100% { + transform: rotate(360deg); + } + } + @keyframes dash { + 0% { + stroke-dasharray: 1,200; + stroke-dashoffset: 0; + } + 50% { + stroke-dasharray: 89,200; + stroke-dashoffset: -35; + } + 100% { + stroke-dasharray: 89,200; + stroke-dashoffset: -124; + } + } + @keyframes fadeIn { + 0%{ + opacity: 0; + } + 100%{ + opacity: 1; + } }
- + + + +
- - - - Document - - - -
- -
-
-
-
-
- - - - \ No newline at end of file diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index e08a244..dcdbcce 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,11 +1,11 @@ [package] -name = "jellyplayer" +name = "blink" version = "0.0.5-dev" description = "A Modern Jellyfin Client" authors = ["prayag17", "JellyPlayer contributors (https://github.com/prayag17/JellyPlayer/graphs/contributors)"] license = "GPL-3.0-only" repository = "https://github.com/prayag17/JellyPlayer/" -default-run = "jellyplayer" +default-run = "blink" edition = "2021" rust-version = "1.59" diff --git a/src-tauri/icons/128x128.png b/src-tauri/icons/128x128.png index e406097..98c7a65 100644 Binary files a/src-tauri/icons/128x128.png and b/src-tauri/icons/128x128.png differ diff --git a/src-tauri/icons/128x128@2x.png b/src-tauri/icons/128x128@2x.png index 9533575..a569495 100644 Binary files a/src-tauri/icons/128x128@2x.png and b/src-tauri/icons/128x128@2x.png differ diff --git a/src-tauri/icons/32x32.png b/src-tauri/icons/32x32.png index 6526d70..036bd27 100644 Binary files a/src-tauri/icons/32x32.png and b/src-tauri/icons/32x32.png differ diff --git a/src-tauri/icons/Square107x107Logo.png b/src-tauri/icons/Square107x107Logo.png index bea784d..68aa928 100644 Binary files a/src-tauri/icons/Square107x107Logo.png and b/src-tauri/icons/Square107x107Logo.png differ diff --git a/src-tauri/icons/Square142x142Logo.png b/src-tauri/icons/Square142x142Logo.png index 715124b..9f1894c 100644 Binary files a/src-tauri/icons/Square142x142Logo.png and b/src-tauri/icons/Square142x142Logo.png differ diff --git a/src-tauri/icons/Square150x150Logo.png b/src-tauri/icons/Square150x150Logo.png index 0f769e2..36e8b12 100644 Binary files a/src-tauri/icons/Square150x150Logo.png and b/src-tauri/icons/Square150x150Logo.png differ diff --git a/src-tauri/icons/Square284x284Logo.png b/src-tauri/icons/Square284x284Logo.png index 5a5e07b..401e7f9 100644 Binary files a/src-tauri/icons/Square284x284Logo.png and b/src-tauri/icons/Square284x284Logo.png differ diff --git a/src-tauri/icons/Square30x30Logo.png b/src-tauri/icons/Square30x30Logo.png index 0d95563..4b75b48 100644 Binary files a/src-tauri/icons/Square30x30Logo.png and b/src-tauri/icons/Square30x30Logo.png differ diff --git a/src-tauri/icons/Square310x310Logo.png b/src-tauri/icons/Square310x310Logo.png index 137206c..0047f7d 100644 Binary files a/src-tauri/icons/Square310x310Logo.png and b/src-tauri/icons/Square310x310Logo.png differ diff --git a/src-tauri/icons/Square44x44Logo.png b/src-tauri/icons/Square44x44Logo.png index 0185766..fc322a3 100644 Binary files a/src-tauri/icons/Square44x44Logo.png and b/src-tauri/icons/Square44x44Logo.png differ diff --git a/src-tauri/icons/Square71x71Logo.png b/src-tauri/icons/Square71x71Logo.png index cb7efdf..5c9c064 100644 Binary files a/src-tauri/icons/Square71x71Logo.png and b/src-tauri/icons/Square71x71Logo.png differ diff --git a/src-tauri/icons/Square89x89Logo.png b/src-tauri/icons/Square89x89Logo.png index cf4b240..49bd2b5 100644 Binary files a/src-tauri/icons/Square89x89Logo.png and b/src-tauri/icons/Square89x89Logo.png differ diff --git a/src-tauri/icons/StoreLogo.png b/src-tauri/icons/StoreLogo.png index 3bb630b..6ae9ac9 100644 Binary files a/src-tauri/icons/StoreLogo.png and b/src-tauri/icons/StoreLogo.png differ diff --git a/src-tauri/icons/icon.icns b/src-tauri/icons/icon.icns index 87dd3d9..2a1df53 100644 Binary files a/src-tauri/icons/icon.icns and b/src-tauri/icons/icon.icns differ diff --git a/src-tauri/icons/icon.ico b/src-tauri/icons/icon.ico index 7847aca..442f4a4 100644 Binary files a/src-tauri/icons/icon.ico and b/src-tauri/icons/icon.ico differ diff --git a/src-tauri/icons/icon.png b/src-tauri/icons/icon.png index 30c59b4..744f254 100644 Binary files a/src-tauri/icons/icon.png and b/src-tauri/icons/icon.png differ diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 439040e..2562eea 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -7,7 +7,7 @@ "distDir": "../dist" }, "package": { - "productName": "JellyPlayer", + "productName": "Blink", "version": "../package.json" }, "tauri": { @@ -46,7 +46,7 @@ "icons/icon.icns", "icons/icon.ico" ], - "identifier": "com.jellyplayer.prayag17", + "identifier": "com.blink.prayag17", "longDescription": "A modern desktop client for Jellyfin", "macOS": { "entitlements": null, @@ -56,7 +56,7 @@ "signingIdentity": null }, "resources": [], - "shortDescription": "JellyPlayer", + "shortDescription": "Blink", "targets": ["deb", "appimage", "nsis", "app", "dmg", "updater"], "windows": { "certificateThumbprint": null, @@ -68,10 +68,6 @@ "installerIcon": "icons/icon.ico", "displayLanguageSelector": true, "license": "../LICENSE" - }, - "webviewInstallMode": { - "silent": true, - "type": "offlineInstaller" } }, "appimage": { @@ -107,7 +103,7 @@ "height": 600, "width": 800, "resizable": true, - "title": "JellyPlayer", + "title": "Blink", "visible": true, "center": true, "label": "main" diff --git a/src/App.tsx b/src/App.tsx index cd082d3..aed15ea 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -40,14 +40,14 @@ import { } from "@mui/material"; // Routes -import About from "./routes/about"; -import MusicAlbumTitlePage from "./routes/album/index.jsx"; -import ArtistTitlePage from "./routes/artist/index.jsx"; -import BoxSetTitlePage from "./routes/boxset/index.jsx"; -import EpisodeTitlePage from "./routes/episode/index"; +import About from "./routes/_about"; +import MusicAlbumTitlePage from "./routes/album/$id.js"; +import ArtistTitlePage from "./routes/artist/$id.js"; +import BoxSetTitlePage from "./routes/boxset/$id.js"; +import EpisodeTitlePage from "./routes/episode/$id"; import FavoritePage from "./routes/favorite/index.jsx"; import Home from "./routes/home"; -import ItemDetail from "./routes/item"; +import ItemDetail from "./routes/item/$id"; import LibraryView from "./routes/library"; import { LoginRoute, @@ -55,39 +55,17 @@ import { UserLogin, UserLoginManual, } from "./routes/login"; -import PersonTitlePage from "./routes/person/index.jsx"; +import PersonTitlePage from "./routes/person/$id.jsx"; import VideoPlayer from "./routes/player/videoPlayer"; -import PlaylistTitlePage from "./routes/playlist/index.jsx"; +import PlaylistTitlePage from "./routes/playlist/$id.jsx"; import SearchPage from "./routes/search"; -import SeriesTitlePage from "./routes/series/index.jsx"; -import { ServerSetup } from "./routes/setup/server"; -import ServerList from "./routes/setup/serverList/index.jsx"; +import SeriesTitlePage from "./routes/series/$id.js"; +import { ServerSetup } from "./routes/setup/server.add"; +import ServerList from "./routes/setup/server.list.js"; import Markdown from "react-markdown"; import remarkGfm from "remark-gfm"; -// Fonts -import "@fontsource-variable/jetbrains-mono"; -import "@fontsource/noto-sans/100-italic.css"; -import "@fontsource/noto-sans/100.css"; -import "@fontsource/noto-sans/200-italic.css"; -import "@fontsource/noto-sans/200.css"; -import "@fontsource/noto-sans/300-italic.css"; -import "@fontsource/noto-sans/300.css"; -import "@fontsource/noto-sans/400-italic.css"; -import "@fontsource/noto-sans/400.css"; -import "@fontsource/noto-sans/500-italic.css"; -import "@fontsource/noto-sans/500.css"; -import "@fontsource/noto-sans/600-italic.css"; -import "@fontsource/noto-sans/600.css"; -import "@fontsource/noto-sans/700-italic.css"; -import "@fontsource/noto-sans/700.css"; -import "@fontsource/noto-sans/800-italic.css"; -import "@fontsource/noto-sans/800.css"; -import "@fontsource/noto-sans/900-italic.css"; -import "@fontsource/noto-sans/900.css"; - -import "material-symbols/rounded.scss"; // Components import { AppBar } from "./components/appBar/appBar.jsx"; @@ -251,12 +229,7 @@ function AppReady() { const location = useLocation(); const navigate = useNavigate(); - const [updateDialog, setUpdateDialog] = useState(false); - const [updateDialogButton, setUpdateDialogButton] = useState(false); - const [backdropLoading, setBackdropLoading] = useState(true); - const [updateInfo, setUpdateInfo] = useState( - undefined, - ); + const isQueryFetching = useIsFetching(); const isMutating = useIsMutating(); @@ -265,28 +238,7 @@ function AppReady() { const [videoPlaybackItem] = usePlaybackStore((state) => [state.item]); - // Reset BakcdropImageLoading for every new image - useEffect(() => { - setBackdropLoading(true); - }, [backdropId]); - useLayoutEffect(() => { - async function checkForUpdates() { - try { - const { shouldUpdate, manifest } = await checkUpdate(); - - if (shouldUpdate) { - setUpdateInfo(manifest); - setUpdateDialog(true); - - console.log(`Update found : ${manifest?.version}, ${manifest?.date}`); - } - } catch (error) { - console.error(error); - } - } - checkForUpdates(); - }, []); if (!initialRoute) { return ( @@ -304,142 +256,13 @@ function AppReady() { } return ( - - - - - - {updateInfo !== undefined && ( - <> - - Update Available! - update - } - label={`v${updateInfo.version}`} - color="success" - /> - - - - - {updateInfo.body} - - - - - - - - Update - - - - - - { - setUpdateDialogButton(true); - await installUpdate(); - enqueueSnackbar( - "Update has been installed! You need to relaunch JellyPlayer.", - { - variant: "success", - }, - ); - await relaunch(); - }} - > - Update - - - - )} - + - - + {/* Show Dialog if server not reachable */} -
- - setBackdropLoading(false)} - loading="lazy" - /> - -
+
- - {audioPlayerVisible && } + } /> @@ -527,7 +349,7 @@ function AppReady() {
-
+
); } diff --git a/src/assets/icon.png b/src/assets/icon.png index 14a5f2a..5b9d040 100644 Binary files a/src/assets/icon.png and b/src/assets/icon.png differ diff --git a/src/assets/icon.svg b/src/assets/icon.svg index a7aadc1..152a8bc 100644 --- a/src/assets/icon.svg +++ b/src/assets/icon.svg @@ -1,20 +1,12 @@ - - - - - + + + + + - - - - - - - - - - - - + + + + diff --git a/src/assets/logo.png b/src/assets/logo.png index 5f87dbd..e8493ac 100644 Binary files a/src/assets/logo.png and b/src/assets/logo.png differ diff --git a/src/assets/logo.svg b/src/assets/logo.svg index 44ecbb2..5bd5bb8 100644 --- a/src/assets/logo.svg +++ b/src/assets/logo.svg @@ -1,25 +1,13 @@ - - - - - - - - - - - - - - - - - - + + + + + + - - + + - + diff --git a/src/assets/logoBlack.png b/src/assets/logoBlack.png index 50f0e5a..9893166 100644 Binary files a/src/assets/logoBlack.png and b/src/assets/logoBlack.png differ diff --git a/src/assets/logoBlack.svg b/src/assets/logoBlack.svg index ce9c433..d09b71b 100644 --- a/src/assets/logoBlack.svg +++ b/src/assets/logoBlack.svg @@ -1,25 +1,13 @@ - - - - - - - - - - - - - - - - - - + + + + + + - - + + - + diff --git a/src/components/appBar/appBar.tsx b/src/components/appBar/appBar.tsx index d8ceaee..51127d7 100644 --- a/src/components/appBar/appBar.tsx +++ b/src/components/appBar/appBar.tsx @@ -1,4 +1,5 @@ -import React, { useEffect, useRef, useState } from "react"; +import type React from "react"; +import { useEffect, useRef, useState } from "react"; import { relaunch } from "@tauri-apps/api/process"; @@ -19,28 +20,31 @@ import useScrollTrigger from "@mui/material/useScrollTrigger"; import { red } from "@mui/material/colors"; import { - NavLink as NavLinkBase, - Link as RouterLink, - type LinkProps as RouterLinkProps, + Link, useLocation, useNavigate, -} from "react-router-dom"; + useRouteContext, +} from "@tanstack/react-router"; import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; import { getUserViewsApi } from "@jellyfin/sdk/lib/utils/api/user-views-api"; import { useQuery, useQueryClient } from "@tanstack/react-query"; -import { delServer } from "../../utils/storage/servers"; -import { delUser } from "../../utils/storage/user"; -import { useDrawerStore } from "../../utils/store/drawer"; +import { delServer } from "@/utils/storage/servers"; +import { delUser } from "@/utils/storage/user"; +import { useDrawerStore } from "@/utils/store/drawer"; import "./appBar.scss"; -import { EventEmitter as event } from "../../eventEmitter"; -import { useApi } from "../../utils/store/api"; +import { EventEmitter as event } from "@/eventEmitter"; import { getTypeIcon } from "../utils/iconsCollection"; +import { useApiInContext } from "@/utils/store/api"; +import useSettingsStore, { + setSettingsDialogOpen, + setSettingsTabValue, +} from "@/utils/store/settings"; import { Divider, Drawer, @@ -49,11 +53,6 @@ import { ListItemButton, ListItemText, } from "@mui/material"; -import logo from "../../assets/icon.svg"; -import useSettingsStore, { - setSettingsDialogOpen, - setSettingsTabValue, -} from "../../utils/store/settings"; interface ListItemLinkProps { icon?: React.ReactElement; @@ -61,24 +60,13 @@ interface ListItemLinkProps { to: string; } -const NavLink = React.forwardRef((props, ref) => ( - - `${props.className} ${isActive ? props.activeClassName : ""}` - } - /> -)); - function ListItemLink(props: ListItemLinkProps) { const { icon, primary, to } = props; return (
  • { - const [api] = useApi((state) => [state.api]); + const api = useApiInContext((s) => s.api); const navigate = useNavigate(); const [display, setDisplay] = useState(false); diff --git a/src/components/appBar/backOnly.jsx b/src/components/appBar/backOnly.jsx index 94606b1..bb335cc 100644 --- a/src/components/appBar/backOnly.jsx +++ b/src/components/appBar/backOnly.jsx @@ -1,13 +1,13 @@ import AppBar from "@mui/material/AppBar"; import IconButton from "@mui/material/IconButton"; import Toolbar from "@mui/material/Toolbar"; -import { useNavigate } from "react-router-dom"; +import { useRouter } from "@tanstack/react-router"; export const AppBarBackOnly = () => { - const navigate = useNavigate(); + const { history } = useRouter(); const handleBack = () => { - navigate(-1); + history.go(-1); }; return ( diff --git a/src/components/avatar/avatar.jsx b/src/components/avatar/avatar.jsx index d37817a..9b20eef 100644 --- a/src/components/avatar/avatar.jsx +++ b/src/components/avatar/avatar.jsx @@ -4,11 +4,10 @@ import React from "react"; import Box from "@mui/material/Box"; import "./avatar.module.scss"; - -import { useApi } from "../../utils/store/api"; +import { useRouteContext } from "@tanstack/react-router"; export const AvatarImage = ({ userId }) => { - const [api] = useApi((state) => [state.api]); + const api = useRouteContext({ from: "/_api" }).api; return (
    { + history.back(); + }; + + return ( + + arrow_back + + ); +} \ No newline at end of file diff --git a/src/components/buttons/likeButton.jsx b/src/components/buttons/likeButton.jsx index 60aebd7..95cfa8d 100644 --- a/src/components/buttons/likeButton.jsx +++ b/src/components/buttons/likeButton.jsx @@ -8,12 +8,11 @@ import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api" import CircularProgress from "@mui/material/CircularProgress"; import { pink } from "@mui/material/colors"; import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { useRouteContext } from "@tanstack/react-router"; import { useSnackbar } from "notistack"; -import { useApi } from "../../utils/store/api"; - const LikeButton = ({ itemId, isFavorite, queryKey, userId, itemName }) => { - const [api] = useApi((state) => [state.api]); + const api = useRouteContext({ from: "/" }).api; const queryClient = useQueryClient(); const { enqueueSnackbar } = useSnackbar(); diff --git a/src/components/buttons/markPlayedButton.jsx b/src/components/buttons/markPlayedButton.jsx index 3f42748..56b41a1 100644 --- a/src/components/buttons/markPlayedButton.jsx +++ b/src/components/buttons/markPlayedButton.jsx @@ -9,11 +9,11 @@ import { green } from "@mui/material/colors"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { getPlaystateApi } from "@jellyfin/sdk/lib/utils/api/playstate-api"; +import { useRouteContext } from "@tanstack/react-router"; import { useSnackbar } from "notistack"; -import { useApi } from "../../utils/store/api"; const MarkPlayedButton = ({ itemId, isPlayed, queryKey, userId, itemName }) => { - const [api] = useApi((state) => [state.api]); + const api = useRouteContext({ from: "/" }).api; const queryClient = useQueryClient(); const { enqueueSnackbar } = useSnackbar(); diff --git a/src/components/buttons/playButton.tsx b/src/components/buttons/playButton.tsx index bd1e9a5..b75bff6 100644 --- a/src/components/buttons/playButton.tsx +++ b/src/components/buttons/playButton.tsx @@ -9,6 +9,7 @@ import Fab from "@mui/material/Fab"; import LinearProgress from "@mui/material/LinearProgress"; import Typography from "@mui/material/Typography"; +import { playAudio } from "@/utils/store/audioPlayback"; import { type BaseItemDto, type BaseItemDtoQueryResult, @@ -23,26 +24,19 @@ import { getItemsApi } from "@jellyfin/sdk/lib/utils/api/items-api"; import { getPlaylistsApi } from "@jellyfin/sdk/lib/utils/api/playlists-api"; import { getTvShowsApi } from "@jellyfin/sdk/lib/utils/api/tv-shows-api"; import { useMutation } from "@tanstack/react-query"; +import { useNavigate, useRouteContext } from "@tanstack/react-router"; import { useSnackbar } from "notistack"; -import { useNavigate } from "react-router-dom"; -import { useApi } from "../../utils/store/api"; -import { useAudioPlayback } from "../../utils/store/audioPlayback"; -import useQueue, { setQueue } from "../../utils/store/queue"; +import useQueue, { setQueue } from "@/utils/store/queue"; -import { - playItem, - setItem, - usePlaybackDataLoadStore, - usePlaybackStore, -} from "../../utils/store/playback"; +import { playItem, usePlaybackDataLoadStore } from "@/utils/store/playback"; +import type PlayResult from "@//utils/types/playResult"; +import { getRuntimeCompact } from "@/utils/date/time"; +import playbackProfile from "@/utils/playback-profiles"; import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api/media-info-api"; import type { SxProps } from "@mui/material"; import type { AxiosResponse } from "axios"; -import type PlayResult from "src/utils/types/playResult"; -import { getRuntimeCompact } from "../../utils/date/time"; -import playbackProfile from "../../utils/playback-profiles"; type PlayButtonProps = { item: BaseItemDto; @@ -83,53 +77,9 @@ const PlayButton = ({ playlistItemId = "", trackIndex, }: PlayButtonProps) => { - const [api] = useApi((state) => [state.api]); + const api = useRouteContext({ from: "/" }).api; const navigate = useNavigate(); - // const [ - // setUrl, - // setPosition, - // setDuration, - // setItemId, - // setItemName, - // setAudioStreamIndex, - // setVideoStreamIndex, - // setSubtitleStreamIndex, - // setMediaSourceId, - // setUserId, - // setMediaContainer, - // setSeriesId, - // setEpisodeIndex, - // ] = usePlaybackStore((state) => [ - // state.setUrl, - // state.setPosition, - // state.setDuration, - // state.setItemId, - // state.setItemName, - // state.setAudioStreamIndex, - // state.setVideoStreamIndex, - // state.setSubtitleStreamIndex, - // state.setMediaSourceId, - // state.setUserId, - // state.setMediaContainer, - // state.setSeriesId, - // state.setEpisodeIndex, - // ]); - const [ - setAudioUrl, - setAudioDisplay, - setAudioItem, - setAudioTracks, - setCurrentTrack, - setPlaylistItemId, - ] = useAudioPlayback((state) => [ - state.setUrl, - state.setDisplay, - state.setItem, - state.setTracks, - state.setCurrentTrack, - state.setPlaylistItemId, - ]); const setPlaybackDataLoading = usePlaybackDataLoadStore( (state) => state.setisPending, ); @@ -255,24 +205,20 @@ const PlayButton = ({ }, onSuccess: (result: PlayResult | null) => { if (trackIndex) { - setPlaylistItemId(playlistItemId); - // setCurrentTrack(trackIndex); - // setAudioTracks(result.Items); - setAudioUrl( - `${api.basePath}/Audio/${result.Items[trackIndex].Id}/universal?deviceId=${api.deviceInfo.id}&userId=${userId}&api_key=${api.accessToken}`, - ); - setAudioItem(result.Items[trackIndex]); - setAudioDisplay(true); - - setQueue(result.Items, trackIndex); + // Playlist Playback + enqueueSnackbar("Playlist playback is WIP", { variant: "info" }); } else if (audio) { - setAudioItem(result.Items[0]); - setAudioTracks(result.Items); - setAudioUrl( - `${api.basePath}/Audio/${result.Items[0].Id}/universal?deviceId=${api.deviceInfo.id}&userId=${userId}&api_key=${api.accessToken}`, - ); - setAudioDisplay(true); - setQueue(result.Items, 0); + // Album/Individual audio track playback + const urlOptions = { + deviceId: api?.deviceInfo.id, + userId, + api_key: api?.accessToken, + }; + const urlParams = new URLSearchParams(urlOptions).toString(); + + const playbackUrl = `${api.basePath}/Audio/${result?.item.Items[0].Id}/universal?${urlParams}`; + playAudio(playbackUrl, result?.item.Items[0], undefined); + setQueue(result?.item.Items ?? [], 0); } else { // Creates a queue containing all Episodes for a particular season(series) or collection of movies const queue = result?.item.Items; @@ -342,7 +288,7 @@ const PlayButton = ({ result?.mediaSource.MediaSources[0].Id, result?.mediaSource.PlaySessionId, ); - navigate("/player"); + navigate({ to: "/player" }); } }, onSettled: () => { diff --git a/src/components/buttons/playNextButton.tsx b/src/components/buttons/playNextButton.tsx index ff31e5a..42011c5 100644 --- a/src/components/buttons/playNextButton.tsx +++ b/src/components/buttons/playNextButton.tsx @@ -1,13 +1,13 @@ +import { playItemFromQueue } from "@/utils/store/playback"; +import useQueue from "@/utils/store/queue"; import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; import { IconButton } from "@mui/material"; import { useMutation, useQuery } from "@tanstack/react-query"; +import { useRouteContext } from "@tanstack/react-router"; import React from "react"; -import { useApi } from "src/utils/store/api"; -import { playItemFromQueue } from "src/utils/store/playback"; -import useQueue from "src/utils/store/queue"; const PlayNextButton = () => { - const [api] = useApi((state) => [state.api]); + const api = useRouteContext({ from: "/" }).api; const user = useQuery({ queryKey: ["user"], queryFn: async () => { diff --git a/src/components/buttons/playPreviousButtom.tsx b/src/components/buttons/playPreviousButtom.tsx index 5d5ffd3..532a2c7 100644 --- a/src/components/buttons/playPreviousButtom.tsx +++ b/src/components/buttons/playPreviousButtom.tsx @@ -1,13 +1,13 @@ +import { playItemFromQueue } from "@/utils/store/playback"; +import useQueue from "@/utils/store/queue"; import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; import { IconButton } from "@mui/material"; import { useMutation, useQuery } from "@tanstack/react-query"; +import { useRouteContext } from "@tanstack/react-router"; import React from "react"; -import { useApi } from "src/utils/store/api"; -import { playItemFromQueue } from "src/utils/store/playback"; -import useQueue from "src/utils/store/queue"; const PlayPreviousButton = () => { - const [api] = useApi((state) => [state.api]); + const api = useRouteContext({ from: "/" }).api; const user = useQuery({ queryKey: ["user"], queryFn: async () => { diff --git a/src/components/buttons/queueButton.scss b/src/components/buttons/queueButton.scss index 847006b..59521bb 100644 --- a/src/components/buttons/queueButton.scss +++ b/src/components/buttons/queueButton.scss @@ -7,25 +7,37 @@ $image-size: 5em; display: grid !important; opacity: 1 !important; gap: 1em; + height: 5em; grid-template-columns: 3em $image-size 1fr; justify-items: center; align-items: center; &-image{ - max-height: $image-size; - max-width: $image-size; + max-height: 100%; + max-width: 100%; object-fit: cover; border-radius: $border-radius_04; overflow: hidden; &-container { aspect-ratio: 1; overflow: hidden; - width: $image-size; - height: $image-size; + height: 100%; display: flex; justify-content: center; align-items: center; position: relative; } + &-icon { + width: 100%; + height: 100%; + display: grid; + place-items: center; + background: rgb(255 255 255 / 0.2); + border-radius: 10px; + .material-symbols-rounded { + font-size: 2em; + } + + } } &-info{ display: flex; @@ -35,7 +47,7 @@ $image-size: 5em; } } &-item.Mui-disabled { - .queue-item-image{ + .queue-item-image,.queue-item-image-icon{ opacity: 0.5 !important; } } diff --git a/src/components/buttons/queueButton.tsx b/src/components/buttons/queueButton.tsx index 38a1d6e..7a011dc 100644 --- a/src/components/buttons/queueButton.tsx +++ b/src/components/buttons/queueButton.tsx @@ -1,3 +1,5 @@ +import { playItemFromQueue } from "@/utils/store/playback"; +import useQueue from "@/utils/store/queue"; import { IconButton, Menu, @@ -5,18 +7,15 @@ import { MenuList, Typography, } from "@mui/material"; -import React, { useRef, useState } from "react"; -import { useApi } from "src/utils/store/api"; -import { playItemFromQueue } from "src/utils/store/playback"; -import useQueue from "src/utils/store/queue"; +import React, { useState } from "react"; import { getTypeIcon } from "../utils/iconsCollection"; import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; import { useMutation, useQuery } from "@tanstack/react-query"; -import { useVirtualizer } from "@tanstack/react-virtual"; import "./queueButton.scss"; +import { useRouteContext } from "@tanstack/react-router"; const QueueButton = () => { - const [api] = useApi((state) => [state.api]); + const api = useRouteContext({ from: "/" }).api; const [queueItems, currentItemIndex] = useQueue((state) => [ state.tracks, state.currentItemIndex, @@ -45,14 +44,6 @@ const QueueButton = () => { }, }); - const menuRef = useRef(null); - const virtualizer = useVirtualizer({ - count: queueItems.length, - estimateSize: () => 86, - getScrollElement: () => menuRef.current, - overscan: 3, - }); - return ( <> { }} slotProps={{ paper: { - ref: menuRef, style: { maxHeight: "30em", overflowX: "hidden", @@ -80,32 +70,25 @@ const QueueButton = () => { > - {virtualizer.getVirtualItems().map((virtualItem) => { - const index = virtualItem.index; - const item = queueItems[index]; + {queueItems.map((item, index) => { return ( handlePlay.mutate({ index })} - key={virtualItem.key} - style={{ - position: "absolute", - top: 0, - left: 0, - height: `${virtualItem.size}px`, - transform: `translateY(${virtualItem.start}px)`, - }} + key={item.Id} > - {item.IndexNumberEnd - ? `S${item.ParentIndexNumber}:E${item.IndexNumber} / ${item.IndexNumberEnd}` - : `S${item.ParentIndexNumber}:E${item.IndexNumber}`} + {item.Type === "Audio" + ? item.IndexNumber ?? 0 + : item.IndexNumberEnd + ? `S${item.ParentIndexNumber}:E${item.IndexNumber} / ${item.IndexNumberEnd}` + : `S${item.ParentIndexNumber}:E${item.IndexNumber}`}
    {item.ImageTags?.Primary ? ( @@ -116,6 +99,14 @@ const QueueButton = () => { })} alt={item.Name} /> + ) : item.AlbumPrimaryImageTag?.length > 0 ? ( + {item.Name} ) : (
    {getTypeIcon(item.Type)} diff --git a/src/components/buttons/trailerButton.tsx b/src/components/buttons/trailerButton.tsx index 8f7c202..a58948d 100644 --- a/src/components/buttons/trailerButton.tsx +++ b/src/components/buttons/trailerButton.tsx @@ -1,4 +1,4 @@ -import { MediaUrl } from "@jellyfin/sdk/lib/generated-client"; +import type { MediaUrl } from "@jellyfin/sdk/lib/generated-client"; import { Dialog, IconButton } from "@mui/material"; import React, { useState } from "react"; import ReactPlayer from "react-player"; diff --git a/src/components/card/card.tsx b/src/components/card/card.tsx index d8fa1f9..529df53 100644 --- a/src/components/card/card.tsx +++ b/src/components/card/card.tsx @@ -3,7 +3,7 @@ import React from "react"; import { Component, useState } from "react"; -import { useNavigate } from "react-router-dom"; +import { useNavigate, useRouteContext } from "@tanstack/react-router"; import LinearProgress from "@mui/material/LinearProgress"; import Typography from "@mui/material/Typography"; @@ -12,7 +12,6 @@ import { type BaseItemDto, BaseItemKind, } from "@jellyfin/sdk/lib/generated-client"; -import { useApi } from "../../utils/store/api"; import LikeButton from "../buttons/likeButton"; import MarkPlayedButton from "../buttons/markPlayedButton"; import PlayButton from "../buttons/playButton"; @@ -57,21 +56,21 @@ export const Card = ({ userId: string; seriesId: string | null; hideText: boolean; - onClick: Function | null; + onClick: () => null | null; disableOverlay: boolean; overrideIcon: any; }) => { - const [api] = useApi((state) => [state.api]); + const api = useRouteContext({ from: "/" }).api; const navigate = useNavigate(); const defaultOnClick = () => { if (availableSpecialRoutes.includes(item.Type)) { - navigate(`/${item.Type.toLocaleLowerCase()}/${item.Id}`); + navigate({ to: `/${item.Type.toLocaleLowerCase()}/${item.Id}` }); } else if (!!item.Role || item.Type === BaseItemKind.Person) { - navigate(`/person/${item.Id}`); + navigate({ to: `/person/${item.Id}` }); } else if (item.Type === BaseItemKind.MusicArtist) { - navigate(`/artist/${item.Id}`); + navigate({ to: `/artist/${item.Id}` }); } else { - navigate(`/item/${item.Id}`); + navigate({ to: `/item/${item.Id}` }); } }; diff --git a/src/components/card/episodeCard.jsx b/src/components/card/episodeCard.jsx index e8214e2..a53c5df 100644 --- a/src/components/card/episodeCard.jsx +++ b/src/components/card/episodeCard.jsx @@ -1,5 +1,4 @@ import React from "react"; -import { useNavigate } from "react-router-dom"; import MuiCard from "@mui/material/Card"; import CardActionArea from "@mui/material/CardActionArea"; @@ -10,8 +9,8 @@ import { Blurhash } from "react-blurhash"; import "./card.scss"; -import { getRuntimeCompact } from "../../utils/date/time"; -import { useApi } from "../../utils/store/api"; +import { getRuntimeCompact } from "@/utils/date/time"; +import { useNavigate, useRouteContext } from "@tanstack/react-router"; import LikeButton from "../buttons/likeButton"; import MarkPlayedButton from "../buttons/markPlayedButton"; import PlayButton from "../buttons/playButton"; @@ -44,10 +43,10 @@ export const EpisodeCard = ({ disableRunTime = false, onClick, }) => { - const [api] = useApi((state) => [state.api]); + const api = useRouteContext({ from: "/" }).api; const navigate = useNavigate(); const defaultOnClick = () => { - navigate(`/episode/${item.Id}`); + navigate({ to: `/episode/${item.Id}` }); }; return (
    { - const [api] = useApi((state) => [state.api]); + const api = useRouteContext({ from: "/" }).api; const navigate = useNavigate(); const user = useQuery({ @@ -56,15 +55,18 @@ const CarouselSlide = ({ item }) => { const handleMoreInfo = () => { if (availableSpecialRoutes.includes(item.Type)) { - navigate(`/${item.Type.toLocaleLowerCase()}/${item.Id}`); + navigate({ + to: `/${item.Type.toLocaleLowerCase()}/$id`, + params: { id: item.Id }, + }); } else if (!!item.Role || item.Type === BaseItemKind.Person) { - navigate(`/person/${item.Id}`); + navigate({ to: "/person/$id", params: { id: item.Id } }); } else if (item.Type === BaseItemKind.MusicArtist) { - navigate(`/artist/${item.Id}`); + navigate({ to: "/artist/$id", params: { id: item.Id } }); } else if (item.Type === BaseItemKind.Episode) { - navigate(`/episode/${item.Id}`); + navigate({ to: "/episode/$id", params: { id: item.Id } }); } else { - navigate(`/item/${item.Id}`); + navigate({ to: "/item/$id", params: { id: item.Id } }); } }; diff --git a/src/components/layouts/artist/artistAlbum.jsx b/src/components/layouts/artist/artistAlbum.jsx index 40d0cd3..e36edca 100644 --- a/src/components/layouts/artist/artistAlbum.jsx +++ b/src/components/layouts/artist/artistAlbum.jsx @@ -5,24 +5,22 @@ import Paper from "@mui/material/Paper"; import Stack from "@mui/material/Stack"; import Typography from "@mui/material/Typography"; -import { Link } from "react-router-dom"; - import { getItemsApi } from "@jellyfin/sdk/lib/utils/api/items-api"; import { useQuery } from "@tanstack/react-query"; import { getRuntimeMusic } from "../../../utils/date/time"; import { SortOrder } from "@jellyfin/sdk/lib/generated-client"; -import { useApi } from "../../../utils/store/api"; import { useAudioPlayback } from "../../../utils/store/audioPlayback"; import LikeButton from "../../buttons/likeButton"; import PlayButton from "../../buttons/playButton"; import TrackList from "../tracksList/index"; import "./albumArtist.scss"; +import { Link, useRouteContext } from "@tanstack/react-router"; export const ArtistAlbum = ({ user, album, boxProps }) => { - const [api] = useApi((state) => [state.api]); + const api = useRouteContext({ from: "/" }).api; const albumTracks = useQuery({ queryKey: ["artist", "album", album.Id], queryFn: async () => { @@ -117,7 +115,7 @@ export const ArtistAlbum = ({ user, album, boxProps }) => { { - const [api] = useApi((state) => [state.api]); + const api = useRouteContext({ from: "/" }).api; const user = useQuery({ queryKey: ["user"], queryFn: async () => { diff --git a/src/components/layouts/item/hero.jsx b/src/components/layouts/item/hero.jsx deleted file mode 100644 index c885ae3..0000000 --- a/src/components/layouts/item/hero.jsx +++ /dev/null @@ -1,824 +0,0 @@ -import Chip from "@mui/material/Chip"; -import LinearProgress from "@mui/material/LinearProgress"; -import MenuItem from "@mui/material/MenuItem"; -import Stack from "@mui/material/Stack"; -import TextField from "@mui/material/TextField"; -import Typography from "@mui/material/Typography"; -import React, { useEffect, useState } from "react"; - -// import { BaseItemDto } from ""; -// import { BaseItemPerson } from "@jellyfin/sdk/lib/generated-client/models/base-item-person"; -import { BaseItemKind } from "@jellyfin/sdk/lib/generated-client/models/base-item-kind"; -import { MediaStreamType } from "@jellyfin/sdk/lib/generated-client/models/media-stream-type"; - -import { red, yellow } from "@mui/material/colors"; -import { endsAt, getRuntime, getRuntimeFull } from "../../../utils/date/time"; -import LikeButton from "../../buttons/likeButton"; -import MarkPlayedButton from "../../buttons/markPlayedButton"; -import PlayButton from "../../buttons/playButton"; -import { Card } from "../../card/card"; - -import { Blurhash } from "react-blurhash"; -import TextLink from "../../textLink"; -import "./hero.scss"; - -import { ErrorBoundary } from "react-error-boundary"; -import { useApi } from "../../../utils/store/api"; -/** - * @typedef {Object} Props - * @property {import("@jellyfin/sdk/lib/generated-client/models").BaseItemDto} item - * @property {Array} queryKey - * @property {string} userId - * @property {import("@jellyfin/sdk/lib/generated-client/models").BaseItemPerson[]} writers - * @property {import("@jellyfin/sdk/lib/generated-client/models").BaseItemPerson[]} directors - * @property {import("@jellyfin/sdk/lib/generated-client/models").BaseItemPerson[]} artists - * @property {import("@jellyfin/sdk/lib/generated-client/models").NameGuidPair[]} studios - * @property {bool} disableInfoStrip - * @property {bool} disablePlayButton - * @property {bool} disableLikeButton - * @property {bool} disableMarkAsPlayedButton - * @property {string} albumBy - * @property {bool} audioPlayButton - * @property {bool} favourParentImg - * @property {"portrait"| "thumb"| 'square'} cardType - * @property {bool} enableVideoInfoStrip - */ - -/** - * @description Hero section for item pages - * @param {Props} - * @returns {React.Component} - */ -const Hero = ({ - item, - queryKey, - userId, - writers = [], - directors = [], - artists = [], - studios = [], - disableInfoStrip, - disablePlayButton, - disableLikeButton, - disableMarkAsPlayedButton, - albumBy, - audioPlayButton = false, - favourParentImg = true, - isEpisode = false, - cardType = "portrait", - enableVideoInfoStrip = false, -}) => { - const [api] = useApi((state) => [state.api]); - - const filterMediaStreamVideo = (source) => { - if (source.Type === MediaStreamType.Video) { - return true; - } - return false; - }; - const filterMediaStreamAudio = (source) => { - if (source.Type === MediaStreamType.Audio) { - return true; - } - return false; - }; - const filterMediaStreamSubtitle = (source) => { - if (source.Type === MediaStreamType.Subtitle) { - return true; - } - return false; - }; - - const videoTracks = item.MediaStreams?.filter(filterMediaStreamVideo); - const audioTracks = item.MediaStreams?.filter(filterMediaStreamAudio); - const subtitleTracks = item.MediaStreams?.filter(filterMediaStreamSubtitle); - - const [currentVideoIndex, setCurrentVideoIndex] = useState(0); - const [currentAudioIndex, setCurrentAudioIndex] = useState(0); - const [currentSubtitleIndex, setCurrentSubtitleIndex] = useState(0); - - useEffect(() => { - if (!!videoTracks && !!audioTracks & !!subtitleTracks) { - setCurrentVideoIndex(videoTracks[0]?.Index); - setCurrentAudioIndex(audioTracks[0]?.Index); - setCurrentSubtitleIndex(subtitleTracks[0]?.Index); - } - }, []); - - const qualityLabel = () => { - if ( - videoTracks[0]?.DisplayTitle.toLocaleLowerCase().includes("2160p") || - videoTracks[0]?.DisplayTitle.toLocaleLowerCase().includes("4k") - ) { - return "4K"; - } - if ( - videoTracks[0]?.DisplayTitle.toLocaleLowerCase().includes("1080p") || - videoTracks[0]?.DisplayTitle.toLocaleLowerCase().includes("hd") - ) { - return "HD"; - } - return "SD"; - }; - - const atmosLabel = () => { - if ( - audioTracks[0]?.DisplayTitle.toLocaleLowerCase().includes("atmos") && - audioTracks[0]?.DisplayTitle.toLocaleLowerCase().includes("truehd") - ) { - return "TrueHD | Atmos"; - } - if (audioTracks[0]?.DisplayTitle.toLocaleLowerCase().includes("atmos")) { - return "Atmos"; - } - if (audioTracks[0]?.DisplayTitle.toLocaleLowerCase().includes("truehd")) { - return "TrueHD"; - } - return ""; - }; - - const surroundSoundLabel = () => { - if (audioTracks[0]?.DisplayTitle.includes("7.1")) { - return "7.1"; - } - if (audioTracks[0].DisplayTitle.includes("5.1")) { - return "5.1"; - } - return "2.0"; - }; - - return ( -
    -
    - {!!item.ImageBlurHashes.Backdrop && ( - <> - {Object.keys(item.ImageBlurHashes.Backdrop).length !== 0 && ( - - )} - { - e.target.style.opacity = 1; - }} - loading="eager" - /> - - )} -
    -
    -
    -
    -
    - {isEpisode ? ( - <> - - {item.ParentLogoImageTag ? ( - { - e.target.style.opacity = 1; - }} - /> - ) : ( - item.SeriesName - )} - - - {`S${item.ParentIndexNumber}:E${item.IndexNumber} ${item.Name}`} - - - ) : ( - - {item.ImageTags.Logo ? ( - { - e.target.style.opacity = 1; - }} - /> - ) : ( - item.Name - )} - - )} - {!!albumBy && ( - - By {albumBy.Name} - - )} -
    - {enableVideoInfoStrip && ( - - {!!qualityLabel() && ( - - {qualityLabel()} - - } - sx={{ - borderRadius: "8px !important", - "& .MuiChip-label": { - fontSize: "2.2em", - }, - }} - /> - )} - {!!surroundSoundLabel() && ( - - {surroundSoundLabel()} - - } - sx={{ - borderRadius: "8px !important", - "& .MuiChip-label": { - fontSize: "2.2em", - }, - }} - /> - )} - {!!videoTracks[0]?.VideoRangeType && ( - - {videoTracks[0].VideoRangeType} - - } - sx={{ - borderRadius: "8px !important", - "& .MuiChip-label": { - fontSize: "2.2em", - }, - }} - /> - )} - {!!atmosLabel() && ( - - {atmosLabel()} - - } - sx={{ - borderRadius: "8px !important", - "& .MuiChip-label": { - fontSize: "2.2em", - }, - }} - /> - )} - {!!subtitleTracks.length > 0 && ( - - CC - - } - sx={{ - borderRadius: "8px !important", - "& .MuiChip-label": { - fontSize: "2.2em", - }, - }} - /> - )} - - )} - {!disableInfoStrip && ( - - - {item.ProductionYear ? item.ProductionYear : "Unknown"} - - - -
    -
    - star -
    - - {Math.round(item.CommunityRating * 10) / 10} - -
    -
    - {Boolean(item.CriticRating) && ( -
    -
    - thumb_up -
    - - {item.CriticRating} - -
    - )} - - {!!item.RunTimeTicks && ( - - {getRuntime(item.RunTimeTicks)} - - )} - {!!item.RunTimeTicks && ( - - {endsAt(item.RunTimeTicks)} - - )} -
    - )} - - {item.Genres.join(", ")} - -
    - {item.UserData?.PlaybackPositionTicks > 0 && ( -
    - - - {getRuntimeFull( - item.RunTimeTicks - item.UserData.PlaybackPositionTicks, - )}{" "} - remaining - -
    - )} -
    - {!disablePlayButton && ( - - )} - {!disableLikeButton && ( - - )} - {!disableMarkAsPlayedButton && ( - - )}{" "} -
    - -
    - {Boolean(videoTracks?.length) && ( -
    - - Video - - setCurrentVideoIndex(e.target.value)} - SelectProps={{ - MenuProps: { - disableScrollLock: true, - }, - }} - > - {videoTracks.map((track) => { - return ( - - {track.DisplayTitle} - - ); - })} - -
    - )} - {Boolean(audioTracks?.length) && ( -
    - - Audio - - setCurrentAudioIndex(e.target.value)} - SelectProps={{ - MenuProps: { - disableScrollLock: true, - }, - }} - > - {audioTracks.map((track) => { - return ( - - {track.DisplayTitle} - - ); - })} - -
    - )} - {Boolean(subtitleTracks?.length) && ( -
    - - Subtitle - - { - console.log(e.target.value); - setCurrentSubtitleIndex(e.target.value); - }} - SelectProps={{ - MenuProps: { - disableScrollLock: true, - }, - }} - > - {subtitleTracks.map((track) => { - return ( - - {track.DisplayTitle} - - ); - })} - -
    - )} -
    -
    - - {item.Taglines[0]} - - {item.Overview} -
    -
    - {writers.length > 0 && ( -
    - - Written by - -
    - {writers.map((writer, index) => ( - <> - - {writer.Name} - - {index !== writers.length - 1 && ( - - ,{" "} - - )} - - ))} -
    -
    - )} - {directors.length > 0 && ( -
    - - Directed by - -
    - {directors.map((director, index) => ( - <> - - {director.Name} - - {index !== directors.length - 1 && ( - - ,{" "} - - )} - - ))} -
    -
    - )} - {artists.length > 0 && ( -
    - - Artists - -
    - {artists.map((artist, index) => ( - <> - - {artist.Name} - - {index !== artists.length - 1 && ( - - ,{" "} - - )} - - ))} -
    -
    - )} - {studios.length > 0 && ( -
    - - Studios - - - {studios.map((studio) => studio.Name).join(", ")} - -
    - )} -
    -
    -
    - {}} - /> -
    -
    - ); -}; - -export default Hero; - -Hero.defaultProps = { - disableInfoStrip: false, - disablePlayButton: false, - disableLikeButton: false, - disableMarkAsPlayedButton: false, -}; diff --git a/src/components/layouts/item/hero.scss b/src/components/layouts/item/hero.scss deleted file mode 100644 index 619cd8e..0000000 --- a/src/components/layouts/item/hero.scss +++ /dev/null @@ -1,70 +0,0 @@ -$maskPercentage: 40%; -.hero { - display: flex; - width: 100%; - gap: 2em; - justify-content: space-between; - padding-right: 1em; - .item-detail-primaryImage { - width: 26%; - flex-shrink: 0; - } - &-backdrop { - position: absolute; - background-attachment: scroll; - width: calc(100vw + 100px); - height: calc(100vh + 100px); - top: -50px; - left: -50px; - z-index: -1; - filter: brightness(0.4); - mask-image: linear-gradient(to bottom, black 40%, transparent), - linear-gradient(to left, black 40%, transparent); - -webkit-mask-image: linear-gradient(to bottom, black 40%, transparent), - linear-gradient(to left, black 40%, transparent); - mask-composite: source-in; - -webkit-mask-composite: source-in; - & > * { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - width: 100%; - height: 100%; - } - &-image { - object-fit: cover; - z-index: 1; - } - &-blurhash { - z-index: 0; - } - &-icon { - &-container { - background: url(../../../assets/herobg.png); - background-size: cover; - z-index: -1; - } - } - } - &-grid { - display: grid; - width: 100%; - grid-template-columns: 1fr 85%; - } - - &-name-logo { - width: 10.4em; - max-height: 2.6em; - object-fit: contain; - object-position: left; - opacity: 0; - transition: opacity $transition-time-fast; - filter: drop-shadow(0px 4px 10px rgb(0 0 0 / 0.5)); - } - &-text-container { - display: flex; - flex-wrap: wrap; - } -} diff --git a/src/components/layouts/library/genreView/index.jsx b/src/components/layouts/library/genreView/index.jsx index 8efd01c..b2a8775 100644 --- a/src/components/layouts/library/genreView/index.jsx +++ b/src/components/layouts/library/genreView/index.jsx @@ -2,13 +2,14 @@ import { BaseItemKind } from "@jellyfin/sdk/lib/generated-client"; import { getItemsApi } from "@jellyfin/sdk/lib/utils/api/items-api"; import Typography from "@mui/material/Typography"; import { useQuery } from "@tanstack/react-query"; +import { useRouteContext } from "@tanstack/react-router"; import React from "react"; -import { useApi } from "../../../../utils/store/api"; import { Card } from "../../../card/card"; import { CardScroller } from "../../../cardScroller/cardScroller"; const GenreView = ({ libraryId, genreId, genreName, userId }) => { - const [api] = useApi((state) => [state.api]); + const api = useRouteContext({ from: "/" }).api; + const items = useQuery({ queryKey: ["library", "genreItem", genreId], queryFn: async () => { diff --git a/src/components/layouts/tracksList/index.tsx b/src/components/layouts/tracksList/index.tsx index a478eba..cfbdef7 100644 --- a/src/components/layouts/tracksList/index.tsx +++ b/src/components/layouts/tracksList/index.tsx @@ -5,17 +5,17 @@ import React from "react"; import type { BaseItemDto, UserDto } from "@jellyfin/sdk/lib/generated-client"; import { getRuntimeMusic } from "../../../utils/date/time"; -import { useApi } from "../../../utils/store/api"; import { useAudioPlayback } from "../../../utils/store/audioPlayback"; import LikeButton from "../../buttons/likeButton"; import "./tracksList.scss"; +import { useRouteContext } from "@tanstack/react-router"; export default function TracksList({ tracks, user, queryKey, }: { tracks: BaseItemDto[]; user: UserDto; queryKey: [] }) { - const [api] = useApi((state) => [state.api]); + const api = useRouteContext({ from: "/" }).api; const [ currentItem, diff --git a/src/components/musicTrack/index.jsx b/src/components/musicTrack/index.jsx index 77a8003..cb3d28f 100644 --- a/src/components/musicTrack/index.jsx +++ b/src/components/musicTrack/index.jsx @@ -1,12 +1,12 @@ import Typography from "@mui/material/Typography"; import React from "react"; import { getRuntimeMusic } from "../../utils/date/time"; -import { useApi } from "../../utils/store/api"; import { useAudioPlayback } from "../../utils/store/audioPlayback"; import LikeButton from "../buttons/likeButton"; import PlayButton from "../buttons/playButton"; import TextLink from "../textLink"; import "./musicTrack.scss"; +import { useRouteContext } from "@tanstack/react-router"; /** * @typedef {Object} Props @@ -33,7 +33,7 @@ const MusicTrack = ({ trackIndex, className = "", }) => { - const [api] = useApi((state) => [state.api]); + const api = useRouteContext({ from: "/" }).api; const [currentTrackItem] = useAudioPlayback((state) => [state.item]); return ( diff --git a/src/components/notices/errorNotice/errorNotice.jsx b/src/components/notices/errorNotice/errorNotice.jsx index df1dd8a..1d94a27 100644 --- a/src/components/notices/errorNotice/errorNotice.jsx +++ b/src/components/notices/errorNotice/errorNotice.jsx @@ -4,8 +4,8 @@ import Typography from "@mui/material/Typography"; import { red } from "@mui/material/colors"; import React from "react"; -export const ErrorNotice = ({ error, resetErrorBoundary }) => { - console.error(error); +export const ErrorNotice = ({ error }) => { + console.log(error); return ( { // opacity: 0.6, }} > - {error.message} + {JSON.stringify(error.message)} ); diff --git a/src/components/playback/audioPlayer/audioPlayer.scss b/src/components/playback/audioPlayer/audioPlayer.scss index 691f32c..5b56748 100644 --- a/src/components/playback/audioPlayer/audioPlayer.scss +++ b/src/components/playback/audioPlayer/audioPlayer.scss @@ -4,19 +4,13 @@ $image-size: 4em; position: fixed; bottom: 0; right: 0; - background: rgb(0 0 0 / 0.6); z-index: 10; display: grid; - padding: 0.5em 1em; - // margin: 1em; - backdrop-filter: blur(10px); - // border-radius: 10px; - // overflow: hidden; + padding: 0.5em 1.5em; gap: 1em; box-shadow: 0 0 20px rgb(0 0 0 / 0.25); - border-top: 1.2px solid rgb(255 255 255 / 0.2); - grid-template-columns: 25% 1fr 25%; - + grid-template-columns: 30% 1fr 30%; + background: rgb(0 0 0 / 0.8) !important; #waveform { width: 100%; transform: scaleY(0); @@ -35,7 +29,7 @@ $image-size: 4em; } &-info { display: grid; - gap: 0.5em; + gap: 1em; grid-template-columns: minmax(0, $image-size) minmax(0, 1fr); width: fit-content; align-items: center; @@ -53,14 +47,12 @@ $image-size: 4em; position: relative; &-container { - border-radius: 5px; + border-radius: $border-radius_04; position: relative; overflow: hidden; height: fit-content; aspect-ratio: 1; background: rgb(255 255 255 / 0.1); - - border: 1.2px solid rgb(255 255 255 / 0.1); } &-icon { position: absolute; diff --git a/src/components/playback/audioPlayer/index.jsx b/src/components/playback/audioPlayer/index.jsx index fc44cc7..9417489 100644 --- a/src/components/playback/audioPlayer/index.jsx +++ b/src/components/playback/audioPlayer/index.jsx @@ -19,23 +19,24 @@ import Typography from "@mui/material/Typography"; import WaveSurfer from "wavesurfer.js"; -import { useAudioPlayback } from "../../../utils/store/audioPlayback"; -import useQueue, { setTrackIndex } from "../../../utils/store/queue"; +import { useAudioPlayback } from "@/utils/store/audioPlayback"; +import useQueue from "@/utils/store/queue"; import { AnimatePresence } from "framer-motion"; import "./audioPlayer.scss"; +import { getRuntimeMusic, secToTicks } from "@/utils/date/time"; import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; import { useQuery } from "@tanstack/react-query"; -import { getRuntimeMusic, secToTicks } from "../../../utils/date/time"; -import { getPlaystateApi } from "@jellyfin/sdk/lib/utils/api/playstate-api"; -import { theme } from "../../../theme"; -import { useApi } from "../../../utils/store/api"; -import MusicTrack from "../../musicTrack"; +import PlayNextButton from "@/components/buttons/playNextButton"; +import PlayPreviousButton from "@/components/buttons/playPreviousButtom"; +import QueueButton from "@/components/buttons/queueButton"; +import { useApiInContext } from "@/utils/store/api"; +import { useRouteContext } from "@tanstack/react-router"; const AudioPlayer = () => { - const [api] = useApi((state) => [state.api]); + const api = useApiInContext((s) => s.api); const [ url, display, @@ -43,22 +44,10 @@ const AudioPlayer = () => { // tracks, // currentTrack, setCurrentTrack, - setAudioUrl, - setAudioItem, - setAudioTracks, - resetPlayer, - playlistItemId, ] = useAudioPlayback((state) => [ state.url, state.display, state.item, - // state.tracks, - // state.currentTrack, - state.setCurrentTrack, - state.setUrl, - state.setItem, - state.setTracks, - state.reset, state.playlistItemId, ]); @@ -91,11 +80,6 @@ const AudioPlayer = () => { const [currentTime, setCurrentTime] = useState(0); - const [queueButton, setQueueButton] = useState(null); - const handleOpenQueue = (event) => { - setQueueButton(queueButton ? null : event.currentTarget); - }; - useEffect(() => { if (display) { const waveSurfer = WaveSurfer.create({ @@ -170,43 +154,6 @@ const AudioPlayer = () => { waveSurferRef.current.playPause(); }; - const handleNext = () => { - setPlaying(false); - // setCurrentTrack(currentTrack + 1); - setAudioUrl( - `${api.basePath}/Audio/${ - tracks[currentTrack + 1].Id - }/universal?deviceId=${api.deviceInfo.id}&userId=${ - user.data.Id - }&api_key=${api.accessToken}`, - ); - - setTrackIndex(currentTrack + 1); - - // console.info(tracks[currentTrack + 1]); - - console.log(currentTrack); - // setAudioItem(tracks[currentTrack + 1]); - setShowWaveform(false); - }; - - const handlePrevious = () => { - setPlaying(false); - // setCurrentTrack(currentTrack - 1); - setAudioUrl( - `${api.basePath}/Audio/${ - tracks[currentTrack - 1].Id - }/universal?deviceId=${api.deviceInfo.id}&userId=${ - user.data.Id - }&api_key=${api.accessToken}`, - ); - setTrackIndex(currentTrack - 1); - // setAudioItem(tracks[currentTrack - 1]); - setShowWaveform(false); - }; - - console.log(tracks); - const info = useMemo( () => (
    { {tracks[currentTrack]?.Name} {
    - {tracks[currentTrack].IndexNumber - ? `${tracks[currentTrack].IndexNumber}. ${tracks[currentTrack].Name}` - : tracks[currentTrack].Name} + {item?.Name} - by {tracks[currentTrack].Artists.map((artist) => artist).join(",")} + by {item?.Artists.map((artist) => artist).join(",")}
    ), - [currentTrack], + [tracks[currentTrack]?.Id, currentTrack], ); const controls = useMemo( () => (
    - -
    skip_previous
    -
    +
    { position: "relative", }} > -
    {
    - -
    skip_next
    -
    +
    ), - [currentTrack, loading, playing, tracks.length], + [tracks[currentTrack]?.Id, loading, playing, tracks.length], ); const buttons = useMemo( @@ -323,130 +248,7 @@ const AudioPlayer = () => { justifyContent: "flex-end", }} > - - {({ TransitionProps }) => ( - - - {tracks.map((track, index) => { - return ( -
    setTrackIndex(index)} - > -
    - {Object.keys(track.ImageTags).includes("Primary") ? ( - {track.Name} - ) : track.AlbumPrimaryImageTag ? ( - {track.Name} - ) : ( - <> - )} -
    -
    - - {track.Name} - - - {track.Artists.join(", ")} - -
    - - {getRuntimeMusic(track.RunTimeTicks)} - -
    - ); - })} -
    -
    - )} -
    - -
    queue_music
    -
    + { setIsMuted(!isMuted); @@ -490,130 +292,79 @@ const AudioPlayer = () => { }, }} /> - + { + useAudioPlayback.setState(useAudioPlayback.getInitialState()); + }} + >
    close
    ), - [queueButton, volume, isMuted, currentTrack], + [volume, isMuted, currentTrack], ); return ( - - {/* -
    - {tracks[currentTrack].Name} - - music_note - -
    -
    - - {tracks[currentTrack].IndexNumber - ? `${tracks[currentTrack].IndexNumber}. ${tracks[currentTrack].Name}` - : tracks[currentTrack].Name} - + {display && ( + + {info} + +
    + {controls} +
    - by{" "} - {tracks[currentTrack].Artists.map((artist) => artist).join(",")} + {getRuntimeMusic(secToTicks(currentTime))} + +
    + + {getRuntimeMusic(item?.RunTimeTicks ?? 0)}
    - */} - {info} - -
    - {controls} -
    - - {getRuntimeMusic(secToTicks(currentTime))} - -
    - - {getRuntimeMusic(tracks[currentTrack].RunTimeTicks)} -
    -
    - {buttons} - + {buttons} + + )} ); }; diff --git a/src/components/settings/index.tsx b/src/components/settings/index.tsx index f5ea1cb..192e07e 100644 --- a/src/components/settings/index.tsx +++ b/src/components/settings/index.tsx @@ -1,3 +1,7 @@ +import useSettingsStore, { + setSettingsDialogOpen, + setSettingsTabValue, +} from "@/utils/store/settings"; import { Button, Chip, @@ -21,34 +25,30 @@ import { } from "@mui/material"; import { AnimatePresence, motion, transform } from "framer-motion"; import React, { useEffect, useState } from "react"; -import useSettingsStore, { - setSettingsDialogOpen, - setSettingsTabValue, -} from "../../utils/store/settings"; -import logo from "../../assets/logoBlack.png"; +import logo from "@/assets/logo.png"; +import { createApi, jellyfin, useApiInContext } from "@/utils/store/api"; +import { useCentralStore } from "@/utils/store/central"; import { getSystemApi } from "@jellyfin/sdk/lib/utils/api/system-api"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { createApi, useApi } from "../../utils/store/api"; -import { useCentralStore } from "../../utils/store/central"; import "./settings.scss"; -import type { RecommendedServerInfo } from "@jellyfin/sdk"; -import { LoadingButton } from "@mui/lab"; -import { red, yellow } from "@mui/material/colors"; -import { relaunch } from "@tauri-apps/api/process"; -import { checkUpdate, installUpdate } from "@tauri-apps/api/updater"; -import { enqueueSnackbar, useSnackbar } from "notistack"; -import { useNavigate } from "react-router-dom"; import { delServer, getAllServers, getDefaultServer, setDefaultServer, setServer, -} from "../../utils/storage/servers"; -import { delUser } from "../../utils/storage/user"; +} from "@/utils/storage/servers"; +import { delUser } from "@/utils/storage/user"; +import type { RecommendedServerInfo } from "@jellyfin/sdk"; +import { LoadingButton } from "@mui/lab"; +import { red, yellow } from "@mui/material/colors"; +import { useNavigate, useRouteContext } from "@tanstack/react-router"; +import { relaunch } from "@tauri-apps/api/process"; +import { checkUpdate, installUpdate } from "@tauri-apps/api/updater"; +import { enqueueSnackbar, useSnackbar } from "notistack"; const motionConfig = { initial: { @@ -64,7 +64,8 @@ const Settings = () => { state.dialogOpen, state.tabValue, ]); - const [api, jellyfin] = useApi((state) => [state.api, state.jellyfin]); + const api = useApiInContext((s) => s.api); + const systemInfo = useQuery({ queryKey: ["about", "systemInfo"], queryFn: async () => { @@ -116,7 +117,7 @@ const Settings = () => { }, onSuccess: async () => { setSettingsDialogOpen(false); - navigate("/login/index"); + navigate({ to: "/login/index" }); }, onError: (error) => { console.error(error); @@ -139,12 +140,12 @@ const Settings = () => { setDefaultServer(serversOnDisk.data[0].id); createApi(serversOnDisk.data[0].address, null); } else { - // Reset Api as no server is present on disk - useApi.setState(useApi.getInitialState()); + // TODO: Reset api in context + // useApi.setState(useApi.getInitialState()); } setSettingsDialogOpen(false); await queryClient.removeQueries(); - navigate("/"); + navigate({ to: "/" }); } enqueueSnackbar("Server deleted successfully!", { variant: "success" }); await serversOnDisk.refetch(); @@ -193,7 +194,9 @@ const Settings = () => { maxWidth="md" PaperProps={{ className: "settings glass", + elevation: 10, }} + hideBackdrop onClose={() => setSettingsDialogOpen(false)} > { {/* General */} {tabValue === 1 && (
    - } - label={ -
    - - Enable DiscordRPC - - - this a test - -
    - } - labelPlacement="start" - className="settings-option" - /> - } - label={ -
    - - Enable DiscordRPC - - - this a test - -
    - } - labelPlacement="start" - className="settings-option" - /> - } - label={ -
    - - Enable DiscordRPC - - - this a test - -
    - } - labelPlacement="start" - className="settings-option" - /> - } - label={ -
    - - Enable DiscordRPC - - - this a test - -
    - } - labelPlacement="start" - className="settings-option" - /> - } - label={ -
    - - Enable DiscordRPC - - - this a test - -
    - } - labelPlacement="start" - className="settings-option" - /> - } - label={ -
    - - Enable DiscordRPC - - - this a test - -
    - } - labelPlacement="start" - className="settings-option" - /> - } - label={ -
    - - Enable DiscordRPC - - - this a test - -
    - } - labelPlacement="start" - className="settings-option" - /> - } - label={ -
    - - Enable DiscordRPC - - - this a test - -
    - } - labelPlacement="start" - className="settings-option" - /> - } - label={ -
    - - Enable DiscordRPC - - - this a test - -
    - } - labelPlacement="start" - className="settings-option" - /> - } - label={ -
    - - Enable DiscordRPC - - - this a test - -
    - } - labelPlacement="start" - className="settings-option" - /> - } - label={ -
    - - Enable DiscordRPC - - - this a test - -
    - } - labelPlacement="start" - className="settings-option" - /> - } - label={ -
    - - Enable DiscordRPC - - - this a test - -
    - } - labelPlacement="start" - className="settings-option" - /> - } - label={ -
    - - Enable DiscordRPC - - - this a test - -
    - } - labelPlacement="start" - className="settings-option" - /> - } - label={ -
    - - Enable DiscordRPC - - - this a test - -
    - } - labelPlacement="start" - className="settings-option" - /> - } - label={ -
    - - Enable DiscordRPC - - - this a test - -
    - } - labelPlacement="start" - className="settings-option" - /> + {Array.from(new Array(10)).map((i) => ( + } + label={ +
    + + Some dummy setting + + + this a test + +
    + } + labelPlacement="start" + className="settings-option" + /> + ))}
    )} @@ -516,7 +301,7 @@ const Settings = () => { opacity: 0, }} animate={{ transform: "translateY(0px)", opacity: 1 }} - exit={{ transform: "translateY(-10px)", opacity: 1 }} + exit={{ transform: "translateY(-10px)", opacity: 0 }} transition={{ delay: 0.1 * index, duration: 0.15, @@ -644,7 +429,7 @@ const Settings = () => {
    - Client Version: + Client Version: @@ -654,27 +439,45 @@ const Settings = () => { } label={ - + {applicationVersion} } - color={ - updateInfo.data?.shouldUpdate ? "error" : "success" - } - size="medium" + color={updateInfo.data?.shouldUpdate ? "error" : "info"} + size="small" style={{ width: "fit-content !important", }} />
    - Update Available: - - {updateInfo.isFetching - ? "Checking for new updates..." - : updateInfo.data?.shouldUpdate - ? updateInfo.data.manifest?.version - : "No update found."} + + Update Available: + + + {updateInfo.isFetching ? ( + "Checking for new updates..." + ) : updateInfo.data?.shouldUpdate ? ( + + update + + } + label={ + + {applicationVersion} + + } + color="success" + size="small" + style={{ + width: "fit-content !important", + }} + /> + ) : ( + "No update found." + )}
    { {systemInfo.isSuccess ? (
    - Server: - {systemInfo.data?.ServerName} + Server: + + {systemInfo.data?.ServerName} +
    - Jellyfin Version: - {systemInfo.data?.Version} + + Jellyfin Version: + + + {systemInfo.data?.Version} +
    - Operating System: - + + Operating System: + + {systemInfo.data?.OperatingSystemDisplayName}
    - Server Architecture: - + + Server Architecture: + + {systemInfo.data?.SystemArchitecture}
    @@ -745,10 +558,9 @@ const Settings = () => { background: "rgb(0 0 0 / 0.3)", padding: "1em", borderRadius: "10px", - border: "1px solid rgb(255 255 255 / 0.1)", }} > - + Links:
    { gap: "0.1em", }} > - https://github.com/prayag17/JellyPlayer - - + + https://jellyfin.org - +
    @@ -776,7 +595,12 @@ const Settings = () => { {/* Add Server */} - + Add Server
    @@ -875,10 +880,13 @@ const EpisodeTitlePage = () => { Writers
    {writers.map((actor) => ( - {actor.PrimaryImageTag ? ( { {actor.Role}
    - + ))}
    @@ -918,10 +926,13 @@ const EpisodeTitlePage = () => { Directors
    {directors.map((actor) => ( - {actor.PrimaryImageTag ? ( { {actor.Role}
    - + ))}
    @@ -961,10 +972,13 @@ const EpisodeTitlePage = () => { Producers
    {producers.map((actor) => ( - {actor.PrimaryImageTag ? ( { {actor.Role}
    - + ))}
    @@ -1007,6 +1021,6 @@ const EpisodeTitlePage = () => { if (item.isError) { return ; } -}; +} export default EpisodeTitlePage; diff --git a/src/routes/episode/episode.scss b/src/routes/_api/episode/episode.scss similarity index 100% rename from src/routes/episode/episode.scss rename to src/routes/_api/episode/episode.scss diff --git a/src/routes/favorite/favorite.scss b/src/routes/_api/favorite/favorite.scss similarity index 100% rename from src/routes/favorite/favorite.scss rename to src/routes/_api/favorite/favorite.scss diff --git a/src/routes/favorite/index.jsx b/src/routes/_api/favorite/index.tsx similarity index 94% rename from src/routes/favorite/index.jsx rename to src/routes/_api/favorite/index.tsx index abffea5..3bcda07 100644 --- a/src/routes/favorite/index.jsx +++ b/src/routes/_api/favorite/index.tsx @@ -1,20 +1,24 @@ import React, { useEffect } from "react"; -import { useBackdropStore } from "../../utils/store/backdrop"; +import { useBackdropStore } from "@/utils/store/backdrop"; import Typography from "@mui/material/Typography"; import { useQuery } from "@tanstack/react-query"; import "./favorite.scss"; +import { Card } from "@/components/card/card"; +import { CardScroller } from "@/components/cardScroller/cardScroller"; import { BaseItemKind } from "@jellyfin/sdk/lib/generated-client"; import { getItemsApi } from "@jellyfin/sdk/lib/utils/api/items-api"; import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; -import { Card } from "../../components/card/card"; -import { CardScroller } from "../../components/cardScroller/cardScroller"; -import { useApi } from "../../utils/store/api"; +import { createFileRoute } from "@tanstack/react-router"; -const FavoritePage = () => { - const [api] = useApi((state) => [state.api]); +export const Route = createFileRoute("/_api/favorite/")({ + component: FavoritePage, +}); + +function FavoritePage() { + const api = Route.useRouteContext().api; const [setBackdrop] = useBackdropStore((state) => [state.setBackdrop]); const user = useQuery({ @@ -167,7 +171,7 @@ const FavoritePage = () => { item.EndDate ? new Date(item.EndDate).toLocaleString([], { year: "numeric", - }) + }) : "Present" }`} cardType="portrait" @@ -297,6 +301,6 @@ const FavoritePage = () => { )} ); -}; +} export default FavoritePage; diff --git a/src/routes/home/home.scss b/src/routes/_api/home/home.scss similarity index 100% rename from src/routes/home/home.scss rename to src/routes/_api/home/home.scss diff --git a/src/routes/home/index.jsx b/src/routes/_api/home/index.tsx similarity index 92% rename from src/routes/home/index.jsx rename to src/routes/_api/home/index.tsx index e3dc22f..ea27985 100644 --- a/src/routes/home/index.jsx +++ b/src/routes/_api/home/index.tsx @@ -4,14 +4,14 @@ import { useQuery } from "@tanstack/react-query"; import "./home.scss"; -import Carousel from "../../components/carousel"; +import Carousel from "@/components/carousel"; // Custom Components -import { Card } from "../../components/card/card"; -import { CardScroller } from "../../components/cardScroller/cardScroller"; -import { LatestMediaSection } from "../../components/layouts/homeSection/latestMediaSection"; -import { CardsSkeleton } from "../../components/skeleton/cards"; -import { CarouselSkeleton } from "../../components/skeleton/carousel"; +import { Card } from "@/components/card/card"; +import { CardScroller } from "@/components/cardScroller/cardScroller"; +import { LatestMediaSection } from "@/components/layouts/homeSection/latestMediaSection"; +import { CardsSkeleton } from "@/components/skeleton/cards"; +import { CarouselSkeleton } from "@/components/skeleton/carousel"; import { getItemsApi } from "@jellyfin/sdk/lib/utils/api/items-api"; import { getTvShowsApi } from "@jellyfin/sdk/lib/utils/api/tv-shows-api"; @@ -19,20 +19,23 @@ import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api"; import { getUserViewsApi } from "@jellyfin/sdk/lib/utils/api/user-views-api"; -import { useNavigate } from "react-router-dom"; +import { createFileRoute, useNavigate } from "@tanstack/react-router"; -import { setBackdrop, useBackdropStore } from "../../utils/store/backdrop"; +import { setBackdrop, useBackdropStore } from "@/utils/store/backdrop"; +import CarouselSlide from "@/components/carouselSlide"; +import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice"; import { BaseItemKind, ItemFields } from "@jellyfin/sdk/lib/generated-client"; import Typography from "@mui/material/Typography"; import { useSnackbar } from "notistack"; import { ErrorBoundary } from "react-error-boundary"; -import CarouselSlide from "../../components/carouselSlide"; -import { ErrorNotice } from "../../components/notices/errorNotice/errorNotice"; -import { useApi } from "../../utils/store/api"; -const Home = () => { - const [api] = useApi((state) => [state.api]); +export const Route = createFileRoute("/_api/home/")({ + component: Home, +}); + +function Home() { + const api = Route.useRouteContext().api; const user = useQuery({ queryKey: ["user"], @@ -91,7 +94,7 @@ const Home = () => { return resumeItems.data; }, enabled: !!user.data, - refetchOnMount: true + refetchOnMount: true, }); const resumeItemsAudio = useQuery({ @@ -127,7 +130,7 @@ const Home = () => { return upNext.data; }, enabled: !!user.data, - refetchOnMount: true + refetchOnMount: true, }); const [latestMediaLibs, setLatestMediaLibs] = useState([]); @@ -221,7 +224,7 @@ const Home = () => { imageType="Primary" cardType="thumb" disableOverlay - onClick={() => navigate(`/library/${item.Id}`)} + onClick={() => navigate({ to: `/library/${item.Id}` })} imageBlurhash={ !!item.ImageBlurHashes?.Primary && item.ImageBlurHashes?.Primary[ @@ -412,6 +415,6 @@ const Home = () => { ); -}; +} export default React.memo(Home); diff --git a/src/routes/item/index.tsx b/src/routes/_api/item/$id.tsx similarity index 91% rename from src/routes/item/index.tsx rename to src/routes/_api/item/$id.tsx index d4e2756..6360385 100644 --- a/src/routes/item/index.tsx +++ b/src/routes/_api/item/$id.tsx @@ -14,10 +14,8 @@ import { green, red, yellow } from "@mui/material/colors"; import { Blurhash } from "react-blurhash"; -import { Link, NavLink, useParams } from "react-router-dom"; - +import useParallax from "@/utils/hooks/useParallax"; import { motion, useScroll } from "framer-motion"; -import useParallax from "../../utils/hooks/useParallax"; import { BaseItemKind, @@ -30,47 +28,46 @@ import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api" import { useQuery } from "@tanstack/react-query"; -import heroBg from "../../assets/herobg.png"; -import { Card } from "../../components/card/card"; -import { CardScroller } from "../../components/cardScroller/cardScroller"; +import heroBg from "@/assets/herobg.png"; +import { Card } from "@/components/card/card"; +import { CardScroller } from "@/components/cardScroller/cardScroller"; import "./item.scss"; -import { ErrorNotice } from "../../components/notices/errorNotice/errorNotice"; +import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice"; -import LikeButton from "../../components/buttons/likeButton"; -import MarkPlayedButton from "../../components/buttons/markPlayedButton"; -import PlayButton from "../../components/buttons/playButton"; -import TrailerButton from "../../components/buttons/trailerButton"; -import ShowMoreText from "../../components/showMoreText"; -import TextLink from "../../components/textLink"; -import { getTypeIcon } from "../../components/utils/iconsCollection"; -import { endsAt, getRuntime } from "../../utils/date/time"; -import { useApi } from "../../utils/store/api"; -import { setBackdrop, useBackdropStore } from "../../utils/store/backdrop"; +import LikeButton from "@/components/buttons/likeButton"; +import MarkPlayedButton from "@/components/buttons/markPlayedButton"; +import PlayButton from "@/components/buttons/playButton"; +import TrailerButton from "@/components/buttons/trailerButton"; +import ShowMoreText from "@/components/showMoreText"; +import { getTypeIcon } from "@/components/utils/iconsCollection"; +import { endsAt, getRuntime } from "@/utils/date/time"; +import { setBackdrop, useBackdropStore } from "@/utils/store/backdrop"; -import ItemSkeleton from "../../components/skeleton/item"; +import ItemSkeleton from "@/components/skeleton/item"; -import ultraHdIcon from "../../assets/icons/4k.svg"; -import dolbyAtmosIcon from "../../assets/icons/dolby-atmos.svg"; -import dolbyDigitalPlusIcon from "../../assets/icons/dolby-digital-plus.svg"; -import dolbyDigitalIcon from "../../assets/icons/dolby-digital.svg"; -import dolbyTrueHDIcon from "../../assets/icons/dolby-truehd.svg"; -import dolbyVisionAtmosIcon from "../../assets/icons/dolby-vision-atmos.png"; -import dolbyVisionIcon from "../../assets/icons/dolby-vision.svg"; -import dtsHdMaIcon from "../../assets/icons/dts-hd-ma.svg"; -import dtsIcon from "../../assets/icons/dts.svg"; -import hdIcon from "../../assets/icons/hd.svg"; -import hdrIcon from "../../assets/icons/hdr.svg"; -import hdr10PlusIcon from "../../assets/icons/hdr10-plus.svg"; -import hdr10Icon from "../../assets/icons/hdr10.svg"; -import imaxIcon from "../../assets/icons/imax.svg"; -import sdIcon from "../../assets/icons/sd.svg"; -import sdrIcon from "../../assets/icons/sdr.svg"; +import ultraHdIcon from "@/assets/icons/4k.svg"; +import dolbyAtmosIcon from "@/assets/icons/dolby-atmos.svg"; +import dolbyDigitalPlusIcon from "@/assets/icons/dolby-digital-plus.svg"; +import dolbyDigitalIcon from "@/assets/icons/dolby-digital.svg"; +import dolbyTrueHDIcon from "@/assets/icons/dolby-truehd.svg"; +import dolbyVisionAtmosIcon from "@/assets/icons/dolby-vision-atmos.png"; +import dolbyVisionIcon from "@/assets/icons/dolby-vision.svg"; +import dtsHdMaIcon from "@/assets/icons/dts-hd-ma.svg"; +import dtsIcon from "@/assets/icons/dts.svg"; +import hdIcon from "@/assets/icons/hd.svg"; +import hdrIcon from "@/assets/icons/hdr.svg"; +import hdr10PlusIcon from "@/assets/icons/hdr10-plus.svg"; +import hdr10Icon from "@/assets/icons/hdr10.svg"; +import imaxIcon from "@/assets/icons/imax.svg"; +import sdIcon from "@/assets/icons/sd.svg"; +import sdrIcon from "@/assets/icons/sdr.svg"; -import type MediaQualityInfo from "../../utils/types/mediaQualityInfo"; +import type MediaQualityInfo from "@/utils/types/mediaQualityInfo"; -import IconLink from "../../components/iconLink"; +import IconLink from "@/components/iconLink"; +import { Link, createFileRoute } from "@tanstack/react-router"; function TabPanel(props) { const { children, value, index, ...other } = props; @@ -95,10 +92,14 @@ TabPanel.propTypes = { value: PropTypes.number.isRequired, }; -const ItemDetail = () => { - const { id } = useParams(); +export const Route = createFileRoute("/_api/item/$id")({ + component: ItemDetail, +}); - const [api] = useApi((state) => [state.api]); +function ItemDetail() { + const { id } = Route.useParams(); + + const api = Route.useRouteContext().api; const user = useQuery({ queryKey: ["user"], @@ -824,10 +825,13 @@ const ItemDetail = () => { Actors
    {actors.map((actor) => ( - {actor.PrimaryImageTag ? ( { {actor.Role}
    - + ))} @@ -867,7 +871,7 @@ const ItemDetail = () => { Writers
    {writers.map((actor) => ( - { {actor.Role}
    - + ))} @@ -910,10 +914,13 @@ const ItemDetail = () => { Directors
    {directors.map((actor) => ( - {actor.PrimaryImageTag ? ( { {actor.Role}
    - + ))} @@ -953,10 +960,13 @@ const ItemDetail = () => { Producers
    {producers.map((actor) => ( - {actor.PrimaryImageTag ? ( { {actor.Role}
    - + ))} @@ -1049,6 +1059,6 @@ const ItemDetail = () => { if (item.isError || similarItems.isError) { return ; } -}; +} export default ItemDetail; diff --git a/src/routes/item/item.scss b/src/routes/_api/item/item.scss similarity index 100% rename from src/routes/item/item.scss rename to src/routes/_api/item/item.scss diff --git a/src/routes/library/index.tsx b/src/routes/_api/library/$id.tsx similarity index 97% rename from src/routes/library/index.tsx rename to src/routes/_api/library/$id.tsx index 7f344aa..9a12300 100644 --- a/src/routes/library/index.tsx +++ b/src/routes/_api/library/$id.tsx @@ -1,8 +1,7 @@ import { motion } from "framer-motion"; import React, { useState, useEffect, useLayoutEffect } from "react"; -import { useParams } from "react-router-dom"; -import { useInfiniteQuery, useQuery } from "@tanstack/react-query"; +import { useQuery } from "@tanstack/react-query"; import Accordion from "@mui/material/Accordion"; import AccordionDetails from "@mui/material/AccordionDetails"; @@ -31,27 +30,26 @@ import { getPersonsApi } from "@jellyfin/sdk/lib/utils/api/persons-api"; import { getStudiosApi } from "@jellyfin/sdk/lib/utils/api/studios-api"; import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; -import { Card } from "../../components/card/card"; -import { EmptyNotice } from "../../components/notices/emptyNotice/emptyNotice"; +import { Card } from "@/components/card/card"; +import { EmptyNotice } from "@/components/notices/emptyNotice/emptyNotice"; +import GenreView from "@/components/layouts/library/genreView"; +import MusicTrack from "@/components/musicTrack"; +import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice"; +import { setBackdrop, useBackdropStore } from "@/utils/store/backdrop"; import { type BaseItemDtoQueryResult, BaseItemKind, ItemFields, SortOrder, } from "@jellyfin/sdk/lib/generated-client"; -import GenreView from "../../components/layouts/library/genreView"; -import MusicTrack from "../../components/musicTrack"; -import { ErrorNotice } from "../../components/notices/errorNotice/errorNotice"; -import { setBackdrop, useBackdropStore } from "../../utils/store/backdrop"; import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api"; import { useScrollTrigger } from "@mui/material"; -import { useVirtualizer, useWindowVirtualizer } from "@tanstack/react-virtual"; +import { useWindowVirtualizer } from "@tanstack/react-virtual"; import type { AxiosResponse } from "axios"; -import { enqueueSnackbar } from "notistack"; -import { useApi } from "../../utils/store/api"; import "./library.scss"; +import { createFileRoute } from "@tanstack/react-router"; const useWindowWidth = () => { const [width, setWidth] = React.useState(window.innerWidth); @@ -72,11 +70,14 @@ const useWindowWidth = () => { return width; }; -const LibraryView = () => { - const [api] = useApi((state) => [state.api]); - const maxDisplayItems = 100; +export const Route = createFileRoute("/_api/library/$id")({ + component: LibraryView, +}); - const { id } = useParams(); +function LibraryView() { + const api = Route.useRouteContext().api; + + const { id } = Route.useParams(); const user = useQuery({ queryKey: ["user"], @@ -370,6 +371,14 @@ const LibraryView = () => { const backdropItemsTemp = items.data.Items?.filter( (item) => item.BackdropImageTags?.length > 0, ); + const backdropItem = backdropItemsTemp[0]; + // enqueueSnackbar("Running"); + setBackdrop( + api?.getItemImageUrl(backdropItem?.Id, "Backdrop", { + tag: backdropItem?.BackdropImageTags[0], + }), + backdropItem?.BackdropImageTags[0] ?? "none", + ); setBackdropItems(backdropItemsTemp); } }, [items.isSuccess]); @@ -384,7 +393,7 @@ const LibraryView = () => { api?.getItemImageUrl(backdropItem.Id, "Backdrop", { tag: backdropItem.BackdropImageTags[0], }), - backdropItem.Id, + backdropItem.BackdropImageTags[0] ?? "none", ); }, 10000); // Update backdrop every 10s return () => clearInterval(intervalId); @@ -1333,6 +1342,6 @@ const LibraryView = () => { if (currentLib.isError) { return
    {currentLib.error}
    ; } -}; +} export default LibraryView; diff --git a/src/routes/library/library.scss b/src/routes/_api/library/library.scss similarity index 100% rename from src/routes/library/library.scss rename to src/routes/_api/library/library.scss diff --git a/src/routes/_api/login/$userId.$userName.tsx b/src/routes/_api/login/$userId.$userName.tsx new file mode 100644 index 0000000..01268c4 --- /dev/null +++ b/src/routes/_api/login/$userId.$userName.tsx @@ -0,0 +1,211 @@ +import LoadingButton from "@mui/lab/LoadingButton"; +import { OutlinedInput, Paper, Typography } from "@mui/material"; +import Checkbox from "@mui/material/Checkbox"; +import FormControl from "@mui/material/FormControl"; +import FormControlLabel from "@mui/material/FormControlLabel"; +import FormGroup from "@mui/material/FormGroup"; +import IconButton from "@mui/material/IconButton"; +import InputAdornment from "@mui/material/InputAdornment"; +import InputLabel from "@mui/material/InputLabel"; + +import { useSnackbar } from "notistack"; + +import { AppBarBackOnly } from "@/components/appBar/backOnly.jsx"; +import { AvatarImage } from "@/components/avatar/avatar.jsx"; +import { createApi } from "@/utils/store/api.js"; +import "./login.scss"; + +import { saveUser } from "@/utils/storage/user"; +import { setBackdrop } from "@/utils/store/backdrop.js"; +import { createFileRoute, useNavigate } from "@tanstack/react-router"; +import React, { useLayoutEffect, useState } from "react"; + +export const Route = createFileRoute("/_api/login/$userId/$userName")({ + component: LoginUser, +}); + +function LoginUser() { + const { userName, userId } = Route.useParams(); + + const api = Route.useRouteContext().api; + + const [password, setPassword] = useState({ + showpass: false, + }); + const [loading, setLoading] = useState(false); + const [rememberMe, setRememberMe] = useState(true); + + const navigate = useNavigate({ from: "/login/$userId/$userName" }); + + const { enqueueSnackbar } = useSnackbar(); + + const handlePassword = (prop) => (event) => { + setPassword({ + ...password, + [prop]: event.target.value, + }); + }; + + const handleShowPassword = () => { + setPassword({ + ...password, + showpass: !password.showpass, + }); + }; + + const authUser = async () => { + try { + const auth = await api.authenticateUserByName( + userName, + password.password, + ); + return auth; + } catch (error) { + if (error.response?.status === 500) { + enqueueSnackbar( + "Unable to connect to server. Please try again after some time.", + { variant: "error" }, + ); + } else { + enqueueSnackbar("Incorrect Password.", { variant: "error" }); + } + setLoading(false); + console.error(error); + } + }; + + const handleLogin = async () => { + setLoading(true); + const user = await authUser(); + sessionStorage.setItem("accessToken", user.data.AccessToken); + createApi(api.basePath, user.data.AccessToken); + if (rememberMe === true) { + await saveUser(userName, user.data.AccessToken); + } + setLoading(false); + navigate("/home"); + }; + + useLayoutEffect(() => { + setBackdrop("", ""); + }, []); + + const handleCheckRememberMe = (event) => { + setRememberMe(event.target.checked); + }; + + return ( + <> + +
    +
    + +
    + + + Login as{" "} + + {userName} + + + + + Password: + + + {password.showpass ? ( + + visibility + + ) : ( + + visibility_off + + )} + + + } + /> + + + } + label="Remember me" + /> + + chevron_right + } + onClick={handleLogin} + loading={loading} + loadingPosition="end" + size="large" + fullWidth + > + Login + + +
    + + ); +} diff --git a/src/routes/_api/login/index.tsx b/src/routes/_api/login/index.tsx new file mode 100644 index 0000000..d7d8064 --- /dev/null +++ b/src/routes/_api/login/index.tsx @@ -0,0 +1,91 @@ +import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; +import { Typography } from "@mui/material"; +import CircularProgress from "@mui/material/CircularProgress"; +import { useQuery } from "@tanstack/react-query"; +import { useLocation, useNavigate } from "@tanstack/react-router"; +import React, { Suspense, useState } from "react"; + +import "./login.scss"; + +import { createFileRoute } from "@tanstack/react-router"; +import { AnimatePresence, motion } from "framer-motion"; +import Markdown from "react-markdown"; +import remarkGfm from "remark-gfm"; + +export const Route = createFileRoute("/_api/login/")({ + component: LoginRoute, +}); + +function LoginRoute() { + const location = useLocation(); + const navigate = useNavigate(); + const api = Route.useRouteContext().api; + const [status, setStatus] = useState("Fetching public users..."); + + const usersList = useQuery({ + queryKey: ["public-users"], + queryFn: async () => { + const result = await getUserApi(api).getPublicUsers(); + return result.data; + }, + enabled: Boolean(api), + }); + + if (location.pathname === "/login") { + console.log(api); + if (usersList.isSuccess && !usersList.isFetching) { + if (usersList.data.length > 0) { + setStatus("Public users found!"); + navigate({ to: "/login/list" }); + } else { + setStatus("No public users found"); + navigate({ to: "/login/manual" }); + } + } + } + + return ( + Loading /login}> +
    + + + + + {status} + + + +
    +
    + ); +} diff --git a/src/routes/_api/login/list.tsx b/src/routes/_api/login/list.tsx new file mode 100644 index 0000000..f602e91 --- /dev/null +++ b/src/routes/_api/login/list.tsx @@ -0,0 +1,342 @@ +import { EventEmitter as event } from "@/eventEmitter.js"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import React, { useLayoutEffect, useState } from "react"; + +import { saveUser } from "@/utils/storage/user.js"; + +import LoadingButton from "@mui/lab/LoadingButton"; +import { + Dialog, + DialogActions, + DialogContent, + DialogContentText, + Grid, + OutlinedInput, + Paper, + Tooltip, + Typography, +} from "@mui/material"; +import Button from "@mui/material/Button"; +import Checkbox from "@mui/material/Checkbox"; +import Container from "@mui/material/Container"; +import FormControlLabel from "@mui/material/FormControlLabel"; +import LinearProgress from "@mui/material/LinearProgress"; + +import { useSnackbar } from "notistack"; + +import { AppBarBackOnly } from "@/components/appBar/backOnly.jsx"; +import { Card } from "@/components/card/card.js"; + +import { getQuickConnectApi } from "@jellyfin/sdk/lib/utils/api/quick-connect-api"; +import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; + +import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice.jsx"; +import { createApi } from "@/utils/store/api.js"; +import "./login.scss"; + +import { setBackdrop } from "@/utils/store/backdrop.js"; +import { blue } from "@mui/material/colors"; +import { createFileRoute, useNavigate } from "@tanstack/react-router"; + +export const Route = createFileRoute("/_api/login/list")({ + component: LoginPublicUsersList, + loader: async ({context}) => { + const api = context.api; + const result = await getUserApi(api).getPublicUsers(); + return result.data; + }, +}); + +function LoginPublicUsersList() { + const navigate = useNavigate(); + + const { enqueueSnackbar } = useSnackbar(); + + const api = Route.useRouteContext().api; + + const [loading, setLoading] = useState(false); + const [rememberMe, setRememberMe] = useState(true); + const [quickConnectLoading, setQuickConnectLoading] = useState(-1); + const [quickConnectCode, setQuickConnectCode] = useState(""); + + const handleCheckRememberMe = (event) => { + setRememberMe(event.target.checked); + }; + + const handleChangeServer = () => { + // navigate("/servers/list"); + }; + const handleManualLogin = () => { + // navigate("/login/manual"); + }; + const users = Route.useLoaderData(); + + const handleQuickConnect = async () => { + setQuickConnectLoading(0); + + const quickApi = getQuickConnectApi(api); + + const headers = { + "X-Emby-Authorization": `MediaBrowser Client="${api.clientInfo.name}", Device="${api.deviceInfo.name}", DeviceId="${api.deviceInfo.id}", Version="${api.clientInfo.version}"`, + }; + + const quickConnectInitiation = await quickApi + .initiate({ + headers, + }) + .catch(() => ({ status: 401 })); + + if (quickConnectInitiation.status !== 200) { + setQuickConnectLoading(-1); + enqueueSnackbar("Unable to use Quick Connect", { + variant: "error", + }); + return; + } + + setQuickConnectLoading(1); + + const { Secret, Code } = quickConnectInitiation.data; + + setQuickConnectCode(Code); + + const interval = setInterval(async () => { + const quickConnectCheck = await quickApi + .connect({ + secret: Secret, + }) + .catch(() => ({ status: 401, data: { Authenticated: false } })); + + if (quickConnectCheck.status !== 200) { + setQuickConnectCode(""); + enqueueSnackbar("Unable to use Quick Connect", { + variant: "error", + }); + + setQuickConnectLoading(-1); + clearInterval(interval); + return; + } + + if (!quickConnectCheck.data.Authenticated) { + return; + } + + const auth = await getUserApi(api) + .authenticateWithQuickConnect({ + quickConnectDto: { + Secret: Secret, + }, + }) + .catch(() => ({ status: 401 })); + + api.accessToken = auth.data.AccessToken; + + clearInterval(interval); + + if (auth.status !== 200) { + enqueueSnackbar("Unable to use Quick Connect", { + variant: "error", + }); + setQuickConnectLoading(-1); + return; + } + + sessionStorage.setItem("accessToken", auth.data.AccessToken); + createApi(api.basePath, auth.data.AccessToken); + + if (rememberMe === true) { + await saveUser(auth.data.User.Name, auth.data.AccessToken); + } + + setQuickConnectLoading(-1); + enqueueSnackbar(`Logged in as ${auth.data.User.Name}!`, { + variant: "success", + }); + navigate("/home"); + }, 1000); + + setLoading(false); + }; + + useLayoutEffect(() => { + setBackdrop("", ""); + }, []); + + if (users.isPending) { + return ; + } + + if (users.isSuccess) { + return ( + <> + + + + Users + + + + {users.data.map((item, index) => { + return ( + + + navigate(`/login/withImg/${item.Name}/${item.Id}/`) + } + overrideIcon="User" + imageType="Primary" + /> + + ); + })} + + +
    + + + Quick Connect + + +
    + + + + + Quick Connect Code: + + + Use this code in the Quick Connect tab in your server to login. + +
    + + { + navigator.clipboard.writeText(quickConnectCode); + enqueueSnackbar("Quick Connect Code copied!", { + variant: "info", + key: "copiedText", + }); + }} + > + {quickConnectCode} + + +
    +
    + + + } + label="Remember device" + /> + + +
    +
    + + ); + } + if (users.isError) { + return ; + } +} diff --git a/src/routes/login/login.scss b/src/routes/_api/login/login.scss similarity index 100% rename from src/routes/login/login.scss rename to src/routes/_api/login/login.scss diff --git a/src/routes/_api/login/manual.tsx b/src/routes/_api/login/manual.tsx new file mode 100644 index 0000000..31ccb58 --- /dev/null +++ b/src/routes/_api/login/manual.tsx @@ -0,0 +1,448 @@ +import { queryOptions, useQuery } from "@tanstack/react-query"; +import React, { useLayoutEffect, useState } from "react"; + +import { saveUser } from "@/utils/storage/user.js"; + +import LoadingButton from "@mui/lab/LoadingButton"; +import { + Dialog, + DialogActions, + DialogContent, + DialogContentText, + Grid, + OutlinedInput, + Paper, + Tooltip, + Typography, +} from "@mui/material"; +import Button from "@mui/material/Button"; +import Checkbox from "@mui/material/Checkbox"; +import Container from "@mui/material/Container"; +import FormControl from "@mui/material/FormControl"; +import FormControlLabel from "@mui/material/FormControlLabel"; +import FormGroup from "@mui/material/FormGroup"; +import IconButton from "@mui/material/IconButton"; +import InputAdornment from "@mui/material/InputAdornment"; +import InputLabel from "@mui/material/InputLabel"; + +import { useSnackbar } from "notistack"; + +import { AppBarBackOnly } from "@/components/appBar/backOnly.jsx"; +import { createApi, useApiInContext } from "@/utils/store/api.js"; +import { getBrandingApi } from "@jellyfin/sdk/lib/utils/api/branding-api"; +import { getQuickConnectApi } from "@jellyfin/sdk/lib/utils/api/quick-connect-api"; +import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; +import "./login.scss"; + +import { queryClient } from "@/main.js"; +import { setBackdrop } from "@/utils/store/backdrop.js"; +import { blue } from "@mui/material/colors"; +import { createFileRoute, useNavigate } from "@tanstack/react-router"; +import { redirect } from "@tanstack/react-router"; + +export const Route = createFileRoute("/_api/login/manual")({ + component: UserLoginManual, +}); + +function UserLoginManual() { + const [loading, setLoading] = useState(false); + const [quickConnectLoading, setQuickConnectLoading] = useState(-1); + const [quickConnectCode, setQuickConnectCode] = useState(""); + const [rememberMe, setRememberMe] = useState(true); + const api = Route.useRouteContext().api; + + const server = useQuery({ + queryKey: ["login", "manual", "serverInfo"], + queryFn: async () => { + return (await getBrandingApi(api).getBrandingOptions()).data; + }, + }); + + const navigate = useNavigate(); + const { enqueueSnackbar } = useSnackbar(); + + const [password, setPassword] = useState({ + showpass: false, + }); + const [userName, setUserName] = useState(""); + + const handleUsername = (event) => { + setUserName(event.target.value); + }; + + const handlePassword = (prop) => (event) => { + setPassword({ + ...password, + [prop]: event.target.value, + }); + }; + + const handleShowPassword = () => { + setPassword({ + ...password, + showpass: !password.showpass, + }); + }; + + const authUser = async () => { + try { + const auth = await api.authenticateUserByName( + userName, + password.password, + ); + return auth; + } catch (error) { + enqueueSnackbar("Incorrect Username or Password!", { + variant: "error", + }); + setLoading(false); + console.error(error); + } + }; + + const handleLogin = async () => { + setLoading(true); + const user = await authUser(); + sessionStorage.setItem("accessToken", user.data.AccessToken); + createApi(api.basePath, user.data.AccessToken); + if (rememberMe === true) { + await saveUser(userName, user.data.AccessToken); + } + setLoading(false); + navigate("/home"); + }; + + const handleCheckRememberMe = (event) => { + setRememberMe(event.target.checked); + }; + + const handleQuickConnect = async () => { + setQuickConnectLoading(0); + + const quickApi = getQuickConnectApi(api); + + const headers = { + "X-Emby-Authorization": `MediaBrowser Client="${api.clientInfo.name}", Device="${api.deviceInfo.name}", DeviceId="${api.deviceInfo.id}", Version="${api.clientInfo.version}"`, + }; + + const quickConnectInitiation = await quickApi + .initiate({ + headers, + }) + .catch(() => ({ status: 401 })); + + if (quickConnectInitiation.status !== 200) { + setQuickConnectCode(""); + setQuickConnectLoading(-1); + enqueueSnackbar("Unable to use Quick Connect", { + variant: "error", + }); + return; + } + + setQuickConnectLoading(1); + + const { Secret, Code } = quickConnectInitiation.data; + + setQuickConnectCode(Code); + + const interval = setInterval(async () => { + const quickConnectCheck = await quickApi + .connect({ + secret: Secret, + }) + .catch(() => ({ status: 401, data: { Authenticated: false } })); + + if (quickConnectCheck.status !== 200) { + enqueueSnackbar("Unable to use Quick Connect", { + variant: "error", + }); + + setQuickConnectLoading(-1); + clearInterval(interval); + return; + } + + if (!quickConnectCheck.data.Authenticated) { + return; + } + + const auth = await getUserApi(api) + .authenticateWithQuickConnect({ + quickConnectDto: { + Secret: Secret, + }, + }) + .catch(() => ({ status: 401 })); + + api.accessToken = auth.data.AccessToken; + + clearInterval(interval); + + if (auth.status !== 200) { + enqueueSnackbar("Unable to use Quick Connect", { + variant: "error", + }); + setQuickConnectLoading(-1); + return; + } + + sessionStorage.setItem("accessToken", auth.data.AccessToken); + createApi(api.basePath, auth.data.AccessToken); + + if (rememberMe === true) { + await saveUser(userName, auth.data.AccessToken); + } + + setQuickConnectLoading(-1); + enqueueSnackbar(`Logged in as ${auth.data.User.Name}!`, { + variant: "success", + }); + navigate("/home"); + }, 1000); + + setLoading(false); + }; + + useLayoutEffect(() => { + setBackdrop("", ""); + }, []); + + return ( + <> + + + + + + Login + + + + + Username: + + + + + + + Password: + { + if (event.key === "Enter") { + handleLogin(); + } + }} + label="Password:" + endAdornment={ + + + {password.showpass ? ( + + visibility + + ) : ( + + visibility_off + + )} + + + } + /> + + + } + label="Remember me" + /> + + +
    + chevron_right + } + onClick={handleLogin} + loading={loading} + loadingPosition="end" + size="large" + sx={{ width: "100%" }} + > + Login + + + Quick Connect + + +
    + + + + Quick Connect Code: + + + Use this code in the Quick Connect tab in your server to login. + +
    + + { + navigator.clipboard.writeText(quickConnectCode); + enqueueSnackbar("Quick Connect Code copied!", { + variant: "info", + key: "copiedText", + }); + }} + > + {quickConnectCode} + + +
    +
    + + + } + label="Remember device" + /> + + +
    + + {server.isSuccess && server.data.LoginDisclaimer && ( + +
    + + info + + Notice +
    + + {server.data.LoginDisclaimer} + +
    + )} +
    +
    +
    + + ); +} diff --git a/src/routes/person/index.jsx b/src/routes/_api/person/$id.tsx similarity index 94% rename from src/routes/person/index.jsx rename to src/routes/_api/person/$id.tsx index 002b943..8426397 100644 --- a/src/routes/person/index.jsx +++ b/src/routes/_api/person/$id.tsx @@ -1,5 +1,5 @@ import PropTypes from "prop-types"; -import React, { useState, useEffect, useLayoutEffect, useRef } from "react"; +import React, { useState, useLayoutEffect, useRef } from "react"; import Box from "@mui/material/Box"; import CircularProgress from "@mui/material/CircularProgress"; @@ -8,10 +8,8 @@ import Tab from "@mui/material/Tab"; import Tabs from "@mui/material/Tabs"; import Typography from "@mui/material/Typography"; +import useParallax from "@/utils/hooks/useParallax"; import { AnimatePresence, motion, useScroll } from "framer-motion"; -import useParallax from "../../utils/hooks/useParallax"; - -import { Link, useParams } from "react-router-dom"; import { BaseItemKind, @@ -22,21 +20,21 @@ import { getItemsApi } from "@jellyfin/sdk/lib/utils/api/items-api"; import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api"; +import { Card } from "@/components/card/card"; import { useQuery } from "@tanstack/react-query"; -import { Card } from "../../components/card/card"; import { Blurhash } from "react-blurhash"; -import LikeButton from "../../components/buttons/likeButton"; -import { ErrorNotice } from "../../components/notices/errorNotice/errorNotice"; -import { useApi } from "../../utils/store/api"; -import { setBackdrop } from "../../utils/store/backdrop"; +import LikeButton from "@/components/buttons/likeButton"; +import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice"; +import { setBackdrop } from "@/utils/store/backdrop"; -import meshBg from "../../assets/herobg.png"; -import ShowMoreText from "../../components/showMoreText"; +import meshBg from "@/assets/herobg.png"; +import ShowMoreText from "@/components/showMoreText"; import "./person.scss"; -import IconLink from "../../components/iconLink"; +import IconLink from "@/components/iconLink"; +import { createFileRoute } from "@tanstack/react-router"; function TabPanel(props) { const { children, value, index, ...other } = props; @@ -68,9 +66,13 @@ function a11yProps(index) { }; } -const PersonTitlePage = () => { - const { id } = useParams(); - const [api] = useApi((state) => [state.api]); +export const Route = createFileRoute("/_api/person/$id")({ + component: PersonTitlePage, +}); + +function PersonTitlePage() { + const { id } = Route.useParams(); + const api = Route.useRouteContext().api; const user = useQuery({ queryKey: ["user"], @@ -511,6 +513,6 @@ const PersonTitlePage = () => { if (item.isError) { return ; } -}; +} export default PersonTitlePage; diff --git a/src/routes/person/person.scss b/src/routes/_api/person/person.scss similarity index 100% rename from src/routes/person/person.scss rename to src/routes/_api/person/person.scss diff --git a/src/routes/player/Noto-Sans-Indosphere.ttf b/src/routes/_api/player/Noto-Sans-Indosphere.ttf similarity index 100% rename from src/routes/player/Noto-Sans-Indosphere.ttf rename to src/routes/_api/player/Noto-Sans-Indosphere.ttf diff --git a/src/routes/player/videoPlayer.tsx b/src/routes/_api/player/index.tsx similarity index 94% rename from src/routes/player/videoPlayer.tsx rename to src/routes/_api/player/index.tsx index 82b075c..3c984bb 100644 --- a/src/routes/player/videoPlayer.tsx +++ b/src/routes/_api/player/index.tsx @@ -14,11 +14,11 @@ import Typography from "@mui/material/Typography"; import ReactPlayer from "react-player"; -import { usePlaybackStore } from "../../utils/store/playback"; +import { usePlaybackStore } from "@/utils/store/playback"; +import { getRuntimeMusic, secToTicks, ticksToSec } from "@/utils/date/time"; import { useCallback, useEffect, useRef, useState } from "react"; import { Navigate, useNavigate } from "react-router-dom"; -import { getRuntimeMusic, secToTicks, ticksToSec } from "../../utils/date/time"; import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api/media-info-api"; import { getPlaystateApi } from "@jellyfin/sdk/lib/utils/api/playstate-api"; @@ -26,26 +26,30 @@ import { getTvShowsApi } from "@jellyfin/sdk/lib/utils/api/tv-shows-api"; import "./videoPlayer.scss"; -import { endsAt } from "../../utils/date/time"; +import { endsAt } from "@/utils/date/time"; import { useQuery } from "@tanstack/react-query"; -import { ItemFields, LocationType, PlayMethod, RepeatMode } from "@jellyfin/sdk/lib/generated-client"; +import { + ItemFields, + LocationType, + PlayMethod, + RepeatMode, +} from "@jellyfin/sdk/lib/generated-client"; import { AnimatePresence, motion } from "framer-motion"; -import useDebounce from "../../utils/hooks/useDebounce"; -import { useApi } from "../../utils/store/api"; -import { setBackdrop } from "../../utils/store/backdrop"; +import { setBackdrop } from "@/utils/store/backdrop"; import { FormControl, TextField } from "@mui/material"; import type JASSUB from "jassub"; import workerUrl from "jassub/dist/jassub-worker.js?url"; import wasmUrl from "jassub/dist/jassub-worker.wasm?url"; +import PlayNextButton from "@/components/buttons/playNextButton"; +import PlayPreviousButton from "@/components/buttons/playPreviousButtom"; +import QueueButton from "@/components/buttons/queueButton"; import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; -import PlayNextButton from "src/components/buttons/playNextButton"; -import PlayPreviousButton from "src/components/buttons/playPreviousButtom"; -import QueueButton from "src/components/buttons/queueButton"; +import { createFileRoute, useRouter } from "@tanstack/react-router"; import subtitleFont from "./Noto-Sans-Indosphere.ttf"; const ticksDisplay = (ticks: number) => { @@ -70,10 +74,13 @@ const ticksDisplay = (ticks: number) => { return formatedTime; }; -const VideoPlayer = () => { - const navigate = useNavigate(); - const [api] = useApi((state) => [state.api]); +export const Route = createFileRoute("/_api/player/")({ + component: VideoPlayer, +}); +function VideoPlayer() { + const api = Route.useRouteContext().api; + const { history } = useRouter(); const [hoveringOsd, setHoveringOsd] = useState(false); const [ @@ -115,12 +122,12 @@ const VideoPlayer = () => { mediaSource.subtitleTrack, ); const [volume, setVolume] = useState(1); - const [muted, setMuted]= useState(false) + const [muted, setMuted] = useState(false); useEffect(() => setBackdrop("", ""), []); const [subtitleRenderer, setSubtitleRenderer] = useState(null); - + const handleReady = async () => { if (!isReady) { if (selectedSubtitle !== "nosub") { @@ -185,17 +192,14 @@ const VideoPlayer = () => { if (subtitleRenderer) { subtitleRenderer.destroy(); } - navigate(-1); + history.back(); // Report Jellyfin server: Playback has ended/stopped getPlaystateApi(api).reportPlaybackStopped({ playbackStopInfo: { Failed: false, - Item: item, ItemId: item?.Id, MediaSourceId: mediaSource.id, - PlayMethod: PlayMethod.DirectPlay, PlaySessionId: playsessionId, - PlaybackStartTimeTicks: startPosition, PositionTicks: progress, }, }); @@ -236,8 +240,8 @@ const VideoPlayer = () => { case "F": case "f": setAppFullscreen((state) => { - appWindow.setFullscreen(!state) - return !state + appWindow.setFullscreen(!state); + return !state; }); break; case "P": @@ -585,6 +589,6 @@ const VideoPlayer = () => { /> ); -}; +} export default VideoPlayer; diff --git a/src/routes/player/videoPlayer.scss b/src/routes/_api/player/videoPlayer.scss similarity index 100% rename from src/routes/player/videoPlayer.scss rename to src/routes/_api/player/videoPlayer.scss diff --git a/src/routes/playlist/index.jsx b/src/routes/_api/playlist/$id.jsx similarity index 84% rename from src/routes/playlist/index.jsx rename to src/routes/_api/playlist/$id.jsx index 052472a..2b0cd5a 100644 --- a/src/routes/playlist/index.jsx +++ b/src/routes/_api/playlist/$id.jsx @@ -4,8 +4,6 @@ import React, { useEffect } from "react"; import Box from "@mui/material/Box"; import CircularProgress from "@mui/material/CircularProgress"; -import { useParams } from "react-router-dom"; - import { BaseItemKind, ItemFields } from "@jellyfin/sdk/lib/generated-client"; import { getLibraryApi } from "@jellyfin/sdk/lib/utils/api/library-api"; import { getPlaylistsApi } from "@jellyfin/sdk/lib/utils/api/playlists-api"; @@ -14,15 +12,14 @@ import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api" import { useQuery } from "@tanstack/react-query"; -import { Card } from "../../components/card/card"; -import { CardScroller } from "../../components/cardScroller/cardScroller"; -import Hero from "../../components/layouts/item/hero"; +import { Card } from "@/components/card/card"; +import { CardScroller } from "@/components/cardScroller/cardScroller"; -import MusicTrack from "../../components/musicTrack"; -import { ErrorNotice } from "../../components/notices/errorNotice/errorNotice"; -import { useApi } from "../../utils/store/api"; -import { useBackdropStore } from "../../utils/store/backdrop"; +import MusicTrack from "@/components/musicTrack"; +import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice"; +import { useBackdropStore } from "@/utils/store/backdrop"; import "./playlist.scss"; +import { createFileRoute } from "@tanstack/react-router"; function TabPanel(props) { const { children, value, index, ...other } = props; @@ -53,9 +50,13 @@ function a11yProps(index) { }; } -const PlaylistTitlePage = () => { - const { id } = useParams(); - const [api] = useApi((state) => [state.api]); +export const Route = createFileRoute("/_api/playlist/$id")({ + component: PlaylistTitlePage, +}); + +function PlaylistTitlePage() { + const { id } = Route.useParams(); + const api = Route.useRouteContext().api; const user = useQuery({ queryKey: ["user"], @@ -122,7 +123,7 @@ const PlaylistTitlePage = () => { item.data.Id, ); } - }); + }, []); if (item.isPending || similarItems.isPending) { return ( @@ -142,7 +143,7 @@ const PlaylistTitlePage = () => { if (item.isSuccess && similarItems.isSuccess) { return (
    { gap: "0.5em", }} > - {musicTracks.isPending ? ( <> ) : ( @@ -200,14 +192,14 @@ const PlaylistTitlePage = () => { similar.Type === BaseItemKind.Episode ? `S${similar.ParentIndexNumber}:E${similar.IndexNumber} - ${similar.Name}` : similar.Type === BaseItemKind.Series - ? `${similar.ProductionYear} - ${ + ? `${similar.ProductionYear} - ${ similar.EndDate ? new Date(similar.EndDate).toLocaleString([], { year: "numeric", - }) + }) : "Present" - }` - : similar.ProductionYear + }` + : similar.ProductionYear } cardType={ similar.Type === BaseItemKind.MusicAlbum || @@ -234,6 +226,6 @@ const PlaylistTitlePage = () => { if (item.isError || similarItems.isError) { return ; } -}; +} export default PlaylistTitlePage; diff --git a/src/routes/playlist/playlist.scss b/src/routes/_api/playlist/playlist.scss similarity index 100% rename from src/routes/playlist/playlist.scss rename to src/routes/_api/playlist/playlist.scss diff --git a/src/routes/search/index.jsx b/src/routes/_api/search/index.jsx similarity index 95% rename from src/routes/search/index.jsx rename to src/routes/_api/search/index.jsx index 7f154b5..cc8ab4e 100644 --- a/src/routes/search/index.jsx +++ b/src/routes/_api/search/index.jsx @@ -4,27 +4,31 @@ import CircularProgress from "@mui/material/CircularProgress"; import InputAdornment from "@mui/material/InputAdornment"; import TextField from "@mui/material/TextField"; -import { useBackdropStore } from "../../utils/store/backdrop"; +import { useBackdropStore } from "@/utils/store/backdrop"; import { useQuery } from "@tanstack/react-query"; +import { EmptyNotice } from "@/components/notices/emptyNotice/emptyNotice"; import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; -import { EmptyNotice } from "../../components/notices/emptyNotice/emptyNotice"; -import useDebounce from "../../utils/hooks/useDebounce"; +import useDebounce from "@/utils/hooks/useDebounce"; +import { Card } from "@/components/card/card"; +import { EpisodeCard } from "@/components/card/episodeCard"; +import { CardScroller } from "@/components/cardScroller/cardScroller"; import { BaseItemKind } from "@jellyfin/sdk/lib/generated-client"; import { getItemsApi } from "@jellyfin/sdk/lib/utils/api/items-api"; import { getPersonsApi } from "@jellyfin/sdk/lib/utils/api/persons-api"; import { getSearchApi } from "@jellyfin/sdk/lib/utils/api/search-api"; -import { Card } from "../../components/card/card"; -import { EpisodeCard } from "../../components/card/episodeCard"; -import { CardScroller } from "../../components/cardScroller/cardScroller"; -import { useApi } from "../../utils/store/api"; import "./search.scss"; +import { createFileRoute } from "@tanstack/react-router"; -const SearchPage = () => { - const [api] = useApi((state) => [state.api]); +export const Route = createFileRoute("/_api/search/")({ + component: SearchPage, +}); + +function SearchPage() { + const api = Route.useRouteContext().api; const [searchTerm, setSearchTerm] = useState(""); const searchParam = useDebounce(searchTerm, 500); @@ -441,6 +445,6 @@ const SearchPage = () => { )}
    ); -}; +} export default SearchPage; diff --git a/src/routes/search/search.scss b/src/routes/_api/search/search.scss similarity index 100% rename from src/routes/search/search.scss rename to src/routes/_api/search/search.scss diff --git a/src/routes/series/index.tsx b/src/routes/_api/series/$id.tsx similarity index 94% rename from src/routes/series/index.tsx rename to src/routes/_api/series/$id.tsx index 0e044d3..6b7c6c3 100644 --- a/src/routes/series/index.tsx +++ b/src/routes/_api/series/$id.tsx @@ -16,10 +16,8 @@ import TextField from "@mui/material/TextField"; import Typography from "@mui/material/Typography"; import { green, red, yellow } from "@mui/material/colors"; +import useParallax from "@/utils/hooks/useParallax"; import { AnimatePresence, motion, useScroll } from "framer-motion"; -import useParallax from "../../utils/hooks/useParallax"; - -import { useNavigate, useParams } from "react-router-dom"; import { Blurhash } from "react-blurhash"; @@ -35,31 +33,34 @@ import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api" import { useQuery } from "@tanstack/react-query"; -import { endsAt, getRuntime, getRuntimeCompact, getRuntimeMusic } from "../../utils/date/time"; +import { + endsAt, + getRuntime, + getRuntimeCompact, + getRuntimeMusic, +} from "@/utils/date/time"; -import { Card } from "../../components/card/card"; -import { EpisodeCard } from "../../components/card/episodeCard"; -import { CardScroller } from "../../components/cardScroller/cardScroller"; +import { Card } from "@/components/card/card"; +import { EpisodeCard } from "@/components/card/episodeCard"; +import { CardScroller } from "@/components/cardScroller/cardScroller"; -import { ErrorNotice } from "../../components/notices/errorNotice/errorNotice"; +import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice"; import "./series.scss"; -import { Link } from "react-router-dom"; -import { NavLink } from "react-router-dom"; -import heroBg from "../../assets/herobg.png"; -import LikeButton from "../../components/buttons/likeButton"; -import MarkPlayedButton from "../../components/buttons/markPlayedButton"; -import PlayButton from "../../components/buttons/playButton"; -import TrailerButton from "../../components/buttons/trailerButton"; -import ShowMoreText from "../../components/showMoreText"; -import { SeasonSelectorSkeleton } from "../../components/skeleton/seasonSelector"; -import TextLink from "../../components/textLink"; -import { getTypeIcon } from "../../components/utils/iconsCollection"; -import { useApi } from "../../utils/store/api"; -import { useBackdropStore } from "../../utils/store/backdrop"; +import heroBg from "@/assets/herobg.png"; +import LikeButton from "@/components/buttons/likeButton"; +import MarkPlayedButton from "@/components/buttons/markPlayedButton"; +import PlayButton from "@/components/buttons/playButton"; +import TrailerButton from "@/components/buttons/trailerButton"; +import ShowMoreText from "@/components/showMoreText"; +import { SeasonSelectorSkeleton } from "@/components/skeleton/seasonSelector"; +import { getTypeIcon } from "@/components/utils/iconsCollection"; +import { useBackdropStore } from "@/utils/store/backdrop"; -import IconLink from "../../components/iconLink"; -import EpisodeSkeleton from "../../components/skeleton/episode"; +import IconLink from "@/components/iconLink"; +import EpisodeSkeleton from "@/components/skeleton/episode"; +import { createFileRoute } from "@tanstack/react-router"; +import { Link } from "@tanstack/react-router"; function TabPanel(props) { const { children, value, index, ...other } = props; @@ -87,14 +88,18 @@ TabPanel.propTypes = { const getEpisodeDateString = (date: Date) => { const formatter = new Intl.DateTimeFormat(navigator.language ?? "en-US", { dateStyle: "full", - }) + }); return formatter.format(date).toString(); -} +}; -const SeriesTitlePage = () => { - const { id } = useParams(); +export const Route = createFileRoute("/_api/series/$id")({ + component: SeriesTitlePage, +}); - const [api] = useApi((state) => [state.api]); +function SeriesTitlePage() { + const { id } = Route.useParams(); + + const api = Route.useRouteContext().api; const user = useQuery({ queryKey: ["user"], @@ -293,7 +298,7 @@ const SeriesTitlePage = () => { }), currentSeasonItem.data.Id, ); - setBackdropImageLoaded(false) + setBackdropImageLoaded(false); } else if (item.isSuccess && item.data?.BackdropImageTags?.length > 0) { sessionStorage.setItem( `backdrop-${item.data?.Id}`, @@ -313,7 +318,7 @@ const SeriesTitlePage = () => { }), item.data.Id, ); - setBackdropImageLoaded(false) + setBackdropImageLoaded(false); } }, [currentSeasonItem.dataUpdatedAt]); @@ -643,10 +648,13 @@ const SeriesTitlePage = () => {
    {actors.map((actor) => ( - {actor.PrimaryImageTag ? ( { {actor.Role}
    - + ))} @@ -688,10 +696,13 @@ const SeriesTitlePage = () => {
    {writers.map((actor) => ( - {actor.PrimaryImageTag ? ( { {actor.Role}
    - + ))} @@ -733,10 +744,13 @@ const SeriesTitlePage = () => {
    {directors.map((actor) => ( - {actor.PrimaryImageTag ? ( { {actor.Role}
    - + ))} @@ -778,10 +792,13 @@ const SeriesTitlePage = () => {
    {producers.map((actor) => ( - {actor.PrimaryImageTag ? ( { {actor.Role}
    - + ))} @@ -1187,6 +1204,6 @@ const SeriesTitlePage = () => { if (item.isError || similarItems.isError) { return ; } -}; +} export default SeriesTitlePage; diff --git a/src/routes/series/series.scss b/src/routes/_api/series/series.scss similarity index 100% rename from src/routes/series/series.scss rename to src/routes/_api/series/series.scss diff --git a/src/routes/about/about.scss b/src/routes/about/about.scss deleted file mode 100644 index 8cdf451..0000000 --- a/src/routes/about/about.scss +++ /dev/null @@ -1,30 +0,0 @@ - -.about { - display: grid; - grid-template-columns: 1fr 1fr; - padding: 4em; - align-items: start; - &-section { - background: $clr-background-dark; - padding: 1em; - border-radius: 12px; - &.monospace * { - font-family: "JetBrains Mono Variable" !important; - } - } - &-logo { - max-width: 50vw; - height: 5em; - object-fit: contain; - object-position: center; - margin-bottom: 1em !important; - border-bottom: 1.4px solid rgb(255 255 255 / 0.05); - } - &-grid { - display: grid; - grid-template-columns: 1fr 1fr; - width: 100%; - padding: 0.5em 0; - gap: 1em; - } -} diff --git a/src/routes/about/index.jsx b/src/routes/about/index.jsx deleted file mode 100644 index 1369a85..0000000 --- a/src/routes/about/index.jsx +++ /dev/null @@ -1,153 +0,0 @@ -import CircularProgress from "@mui/material/CircularProgress"; -import Stack from "@mui/material/Stack"; -import Typography from "@mui/material/Typography"; -import React, { useEffect } from "react"; - -import logo from "../../assets/logo.svg"; - -import { useQuery } from "@tanstack/react-query"; - -import { getSystemApi } from "@jellyfin/sdk/lib/utils/api/system-api"; - -import { useApi } from "../../utils/store/api"; -import { useBackdropStore } from "../../utils/store/backdrop"; -import { useCentralStore } from "../../utils/store/central"; -import "./about.scss"; - -const About = () => { - const [api] = useApi((state) => [state.api]); - const systemInfo = useQuery({ - queryKey: ["about", "systemInfo"], - queryFn: async () => { - const result = await getSystemApi(api).getSystemInfo(); - return result.data; - }, - enabled: Boolean(api), - }); - - const [setBackdrop] = useBackdropStore((state) => [state.setBackdrop]); - const [applicationVersion] = useCentralStore((state) => [ - state.clientVersion, - ]); - - useEffect(() => { - setBackdrop("", ""); - }); - if (systemInfo.isPending) { - return ( -
    - -
    - ); - } - return ( -
    - - - JellyPlayer - -
    -
    - - Server - - - {systemInfo.data.ServerName} - -
    - -
    - - Server Version - - - {systemInfo.data.Version} - -
    - -
    - - Operating System - - - {systemInfo.data.OperatingSystemDisplayName} - -
    - -
    - - Architecture - - - {systemInfo.data.SystemArchitecture} - -
    - -
    - - JellyPlayer Version - - - {applicationVersion} - -
    -
    -
    -
    - ); -}; - -export default About; diff --git a/src/routes/index.tsx b/src/routes/index.tsx new file mode 100644 index 0000000..a118408 --- /dev/null +++ b/src/routes/index.tsx @@ -0,0 +1,107 @@ +import { + type ServerInfo, + getAllServers, + getDefaultServer, + getServer, +} from "@/utils/storage/servers"; +import { UserStore, delUser, getUser } from "@/utils/storage/user"; +import { useApiInContext } from "@/utils/store/api"; +import { setAppReady, useCentralStore } from "@/utils/store/central"; +import { getSystemApi } from "@jellyfin/sdk/lib/utils/api/system-api"; +import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; +import { + Button, + ButtonGroup, + CircularProgress, + Typography, +} from "@mui/material"; +import { Outlet, createFileRoute, useNavigate } from "@tanstack/react-router"; +import axios from "axios"; +import { AnimatePresence, motion } from "framer-motion"; +import * as React from "react"; +import Markdown from "react-markdown"; +import remarkGfm from "remark-gfm"; + +type LoaderData = { + serversOnDisk: ServerInfo[]; + currentServer: ServerInfo | undefined; + userOnDisk: { Name: string; AccessToken: string } | null; +}; + +export const Route = createFileRoute("/")({ + component: Index, + errorComponent: (error) => { + console.error(error.error); + }, + beforeLoad: async ({ context, navigate }) => { + const api = context.api; + const serversOnDisk = await getAllServers(); + const currentServerId = await getDefaultServer(); + const currentServer = await getServer(currentServerId); + const userOnDisk = await getUser(); + const createApi = context.createApi; + + if (serversOnDisk.length > 0) { + if (currentServer) { + // setStatus( + // `Server found! + // Checking server status...`, + // ); + // setIsError(false); + const pingServer = async () => { + const result = ( + await axios.get(`${currentServer.address}/System/Ping`) + ).data; + return result === "Jellyfin Server"; + }; + pingServer() + .then(async (isOnline) => { + if (isOnline) { + // setStatus("Server online!"); + // setIsError(false); + + createApi(currentServer.address, undefined); + + if (userOnDisk) { + // setStatus( + // `User found! + // Trying to authenticate user...`, + // ); + + createApi(currentServer.address, userOnDisk.AccessToken); + + // const api = useApiInContext((s) => s.api); + try { + console.log(); + await getUserApi(api).getCurrentUser(); + } catch (err) { + console.error(err); + // setStatus("Unable to authenticate."); + // setIsError(true); + // setIsAuthError(true); + } + } else { + navigate({ to: "/login" }); + } + } else { + // setStatus("Unable to reach server"); + // setIsError(false); + } + }) + .catch((error) => { + // setStatus("Unable to reach server"); + // setIsError(true); + console.error(error); + }); + } else { + // setStatus("No server found."); + // setIsError(false); + navigate({ to: "/setup/server/list" }); + } + } + }, +}); + +function Index() { + return

    Loading...

    ; +} diff --git a/src/routes/login/index.jsx b/src/routes/login/index.jsx deleted file mode 100644 index b14b04a..0000000 --- a/src/routes/login/index.jsx +++ /dev/null @@ -1,974 +0,0 @@ -import { useMutation, useQuery } from "@tanstack/react-query"; -import React, { useLayoutEffect, useState } from "react"; -import { useNavigate, useParams } from "react-router-dom"; -import { EventEmitter as event } from "../../eventEmitter.js"; - -import { saveUser } from "../../utils/storage/user"; - -import LoadingButton from "@mui/lab/LoadingButton"; -import { - Dialog, - DialogActions, - DialogContent, - DialogContentText, - Grid, - OutlinedInput, - Paper, - Tooltip, - Typography, -} from "@mui/material"; -import Button from "@mui/material/Button"; -import Checkbox from "@mui/material/Checkbox"; -import CircularProgress from "@mui/material/CircularProgress"; -import Container from "@mui/material/Container"; -import FormControl from "@mui/material/FormControl"; -import FormControlLabel from "@mui/material/FormControlLabel"; -import FormGroup from "@mui/material/FormGroup"; -import IconButton from "@mui/material/IconButton"; -import InputAdornment from "@mui/material/InputAdornment"; -import InputLabel from "@mui/material/InputLabel"; -import LinearProgress from "@mui/material/LinearProgress"; - -import { useSnackbar } from "notistack"; - -import { AppBarBackOnly } from "../../components/appBar/backOnly.jsx"; -import { AvatarImage } from "../../components/avatar/avatar.jsx"; -import { Card } from "../../components/card/card"; - -import { getBrandingApi } from "@jellyfin/sdk/lib/utils/api/branding-api"; -import { getQuickConnectApi } from "@jellyfin/sdk/lib/utils/api/quick-connect-api"; -import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; - -import { ErrorNotice } from "../../components/notices/errorNotice/errorNotice.jsx"; -import { createApi, useApi } from "../../utils/store/api"; -import "./login.scss"; - -import { blue } from "@mui/material/colors"; -import { setBackdrop } from "../../utils/store/backdrop.js"; - -export const LoginRoute = () => { - const navigate = useNavigate(); - const [api] = useApi((state) => [state.api]); - - const usersList = useQuery({ - queryKey: ["public-users"], - queryFn: async () => { - const result = await getUserApi(api).getPublicUsers(); - return result.data; - }, - enabled: Boolean(api), - }); - - if (usersList.isSuccess && !usersList.isFetching) { - if (usersList.data.length > 0) { - navigate("/login/users"); - } else { - navigate("/login/manual"); - } - } - - return ( -
    - -
    - ); -}; - -export const LoginWithImage = () => { - const { userName, userId } = useParams(); - - const [api] = useApi((state) => [state.api]); - - const [password, setPassword] = useState({ - showpass: false, - }); - const [loading, setLoading] = useState(false); - const [rememberMe, setRememberMe] = useState(true); - - const navigate = useNavigate(); - - const { enqueueSnackbar } = useSnackbar(); - - const handlePassword = (prop) => (event) => { - setPassword({ - ...password, - [prop]: event.target.value, - }); - }; - - const handleShowPassword = () => { - setPassword({ - ...password, - showpass: !password.showpass, - }); - }; - - const authUser = async () => { - try { - const auth = await api.authenticateUserByName( - userName, - password.password, - ); - return auth; - } catch (error) { - if (error.response?.status === 500) { - enqueueSnackbar( - "Unable to connect to server. Please try again after some time.", - { variant: "error" }, - ); - } else { - enqueueSnackbar("Incorrect Password.", { variant: "error" }); - } - setLoading(false); - console.error(error); - } - }; - - const handleLogin = async () => { - setLoading(true); - const user = await authUser(); - sessionStorage.setItem("accessToken", user.data.AccessToken); - createApi(api.basePath, user.data.AccessToken); - if (rememberMe === true) { - await saveUser(userName, user.data.AccessToken); - } - setLoading(false); - navigate("/home"); - }; - - useLayoutEffect(() => { - setBackdrop("", ""); - }, []); - - const handleCheckRememberMe = (event) => { - setRememberMe(event.target.checked); - }; - - return ( - <> - -
    -
    - -
    - - - Login as{" "} - - {userName} - - - - - Password: - - - {password.showpass ? ( - - visibility - - ) : ( - - visibility_off - - )} - - - } - /> - - - } - label="Remember me" - /> - - chevron_right - } - onClick={handleLogin} - loading={loading} - loadingPosition="end" - size="large" - fullWidth - > - Login - - -
    - - ); -}; - -export const UserLogin = () => { - const navigate = useNavigate(); - - const { enqueueSnackbar } = useSnackbar(); - - const [api] = useApi((state) => [state.api]); - - const [loading, setLoading] = useState(false); - const [rememberMe, setRememberMe] = useState(true); - const [quickConnectLoading, setQuickConnectLoading] = useState(-1); - const [quickConnectCode, setQuickConnectCode] = useState(""); - - const handleCheckRememberMe = (event) => { - setRememberMe(event.target.checked); - }; - - const handleChangeServer = () => { - navigate("/servers/list"); - }; - const handleManualLogin = () => { - navigate("/login/manual"); - }; - const users = useQuery({ - queryKey: ["login", "users"], - queryFn: async () => { - const users = await getUserApi(api).getPublicUsers(); - return users.data; - }, - staleTime: 0, - }); - - const handleQuickConnect = async () => { - setQuickConnectLoading(0); - - const quickApi = getQuickConnectApi(api); - - const headers = { - "X-Emby-Authorization": `MediaBrowser Client="${api.clientInfo.name}", Device="${api.deviceInfo.name}", DeviceId="${api.deviceInfo.id}", Version="${api.clientInfo.version}"`, - }; - - const quickConnectInitiation = await quickApi - .initiate({ - headers, - }) - .catch(() => ({ status: 401 })); - - if (quickConnectInitiation.status !== 200) { - setQuickConnectLoading(-1); - enqueueSnackbar("Unable to use Quick Connect", { - variant: "error", - }); - return; - } - - setQuickConnectLoading(1); - - const { Secret, Code } = quickConnectInitiation.data; - - setQuickConnectCode(Code); - - const interval = setInterval(async () => { - const quickConnectCheck = await quickApi - .connect({ - secret: Secret, - }) - .catch(() => ({ status: 401, data: { Authenticated: false } })); - - if (quickConnectCheck.status !== 200) { - setQuickConnectCode(""); - enqueueSnackbar("Unable to use Quick Connect", { - variant: "error", - }); - - setQuickConnectLoading(-1); - clearInterval(interval); - return; - } - - if (!quickConnectCheck.data.Authenticated) { - return; - } - - const auth = await getUserApi(api) - .authenticateWithQuickConnect({ - quickConnectDto: { - Secret: Secret, - }, - }) - .catch(() => ({ status: 401 })); - - api.accessToken = auth.data.AccessToken; - - clearInterval(interval); - - if (auth.status !== 200) { - enqueueSnackbar("Unable to use Quick Connect", { - variant: "error", - }); - setQuickConnectLoading(-1); - return; - } - - sessionStorage.setItem("accessToken", auth.data.AccessToken); - createApi(api.basePath, auth.data.AccessToken); - - if (rememberMe === true) { - await saveUser(auth.data.User.Name, auth.data.AccessToken); - } - - setQuickConnectLoading(-1); - enqueueSnackbar(`Logged in as ${auth.data.User.Name}!`, { - variant: "success", - }); - navigate("/home"); - }, 1000); - - setLoading(false); - }; - - useLayoutEffect(() => { - setBackdrop("", ""); - }, []); - - if (users.isPending) { - return ; - } - - if (users.isSuccess) { - return ( - <> - - - - Users - - - - {users.data.map((item, index) => { - return ( - - - navigate(`/login/withImg/${item.Name}/${item.Id}/`) - } - overrideIcon="User" - imageType="Primary" - /> - - ); - })} - - -
    - - - Quick Connect - - -
    - - - - - Quick Connect Code: - - - Use this code in the Quick Connect tab in your server to login. - -
    - - { - navigator.clipboard.writeText(quickConnectCode); - enqueueSnackbar("Quick Connect Code copied!", { - variant: "info", - key: "copiedText", - }); - }} - > - {quickConnectCode} - - -
    -
    - - - } - label="Remember device" - /> - - -
    -
    - - ); - } - if (users.isError) { - return ; - } -}; - -export const UserLoginManual = () => { - const [loading, setLoading] = useState(false); - const [quickConnectLoading, setQuickConnectLoading] = useState(-1); - const [quickConnectCode, setQuickConnectCode] = useState(""); - const [rememberMe, setRememberMe] = useState(true); - const [api] = useApi((state) => [state.api]); - - const navigate = useNavigate(); - const { enqueueSnackbar } = useSnackbar(); - - const [password, setPassword] = useState({ - showpass: false, - }); - const [userName, setUserName] = useState(""); - - const server = useQuery({ - queryKey: ["login, manual", "serverInfo"], - queryFn: async () => { - const result = await getBrandingApi(api).getBrandingOptions(); - return result.data; - }, - networkMode: "always", - }); - - const handleUsername = (event) => { - setUserName(event.target.value); - }; - - const handlePassword = (prop) => (event) => { - setPassword({ - ...password, - [prop]: event.target.value, - }); - }; - - const handleShowPassword = () => { - setPassword({ - ...password, - showpass: !password.showpass, - }); - }; - - const authUser = async () => { - try { - const auth = await api.authenticateUserByName( - userName, - password.password, - ); - return auth; - } catch (error) { - enqueueSnackbar("Incorrect Username or Password!", { - variant: "error", - }); - setLoading(false); - console.error(error); - } - }; - - const handleLogin = async () => { - setLoading(true); - const user = await authUser(); - sessionStorage.setItem("accessToken", user.data.AccessToken); - createApi(api.basePath, user.data.AccessToken); - if (rememberMe === true) { - await saveUser(userName, user.data.AccessToken); - } - setLoading(false); - navigate("/home"); - }; - - const handleCheckRememberMe = (event) => { - setRememberMe(event.target.checked); - }; - - const handleQuickConnect = async () => { - setQuickConnectLoading(0); - - const quickApi = getQuickConnectApi(api); - - const headers = { - "X-Emby-Authorization": `MediaBrowser Client="${api.clientInfo.name}", Device="${api.deviceInfo.name}", DeviceId="${api.deviceInfo.id}", Version="${api.clientInfo.version}"`, - }; - - const quickConnectInitiation = await quickApi - .initiate({ - headers, - }) - .catch(() => ({ status: 401 })); - - if (quickConnectInitiation.status !== 200) { - setQuickConnectCode(""); - setQuickConnectLoading(-1); - enqueueSnackbar("Unable to use Quick Connect", { - variant: "error", - }); - return; - } - - setQuickConnectLoading(1); - - const { Secret, Code } = quickConnectInitiation.data; - - setQuickConnectCode(Code); - - const interval = setInterval(async () => { - const quickConnectCheck = await quickApi - .connect({ - secret: Secret, - }) - .catch(() => ({ status: 401, data: { Authenticated: false } })); - - if (quickConnectCheck.status !== 200) { - enqueueSnackbar("Unable to use Quick Connect", { - variant: "error", - }); - - setQuickConnectLoading(-1); - clearInterval(interval); - return; - } - - if (!quickConnectCheck.data.Authenticated) { - return; - } - - const auth = await getUserApi(api) - .authenticateWithQuickConnect({ - quickConnectDto: { - Secret: Secret, - }, - }) - .catch(() => ({ status: 401 })); - - api.accessToken = auth.data.AccessToken; - - clearInterval(interval); - - if (auth.status !== 200) { - enqueueSnackbar("Unable to use Quick Connect", { - variant: "error", - }); - setQuickConnectLoading(-1); - return; - } - - sessionStorage.setItem("accessToken", auth.data.AccessToken); - createApi(api.basePath, auth.data.AccessToken); - - if (rememberMe === true) { - await saveUser(userName, auth.data.AccessToken); - } - - setQuickConnectLoading(-1); - enqueueSnackbar(`Logged in as ${auth.data.User.Name}!`, { - variant: "success", - }); - navigate("/home"); - }, 1000); - - setLoading(false); - }; - - useLayoutEffect(() => { - setBackdrop("", ""); - }, []); - - return ( - <> - {server.isPending && } - - - - - - Login - - - - - Username: - - - - - - - Password: - { - if (event.key === "Enter") { - handleLogin(); - } - }} - label="Password:" - endAdornment={ - - - {password.showpass ? ( - - visibility - - ) : ( - - visibility_off - - )} - - - } - /> - - - } - label="Remember me" - /> - - -
    - chevron_right - } - onClick={handleLogin} - loading={loading} - loadingPosition="end" - size="large" - sx={{ width: "100%" }} - > - Login - - - Quick Connect - - -
    - - - - Quick Connect Code: - - - Use this code in the Quick Connect tab in your server to login. - -
    - - { - navigator.clipboard.writeText(quickConnectCode); - enqueueSnackbar("Quick Connect Code copied!", { - variant: "info", - key: "copiedText", - }); - }} - > - {quickConnectCode} - - -
    -
    - - - } - label="Remember device" - /> - - -
    - - -
    - - info - - Notice -
    - - {server.isSuccess && server.data.LoginDisclaimer} - -
    -
    -
    -
    - - ); -}; diff --git a/src/routes/setup/server/index.jsx b/src/routes/setup/server.add.tsx similarity index 86% rename from src/routes/setup/server/index.jsx rename to src/routes/setup/server.add.tsx index 0a12161..d0f39b6 100644 --- a/src/routes/setup/server/index.jsx +++ b/src/routes/setup/server.add.tsx @@ -1,33 +1,33 @@ import React, { useState } from "react"; -import { useNavigate } from "react-router-dom"; -import { setDefaultServer, setServer } from "../../../utils/storage/servers"; +import { setDefaultServer, setServer } from "@/utils/storage/servers"; import LoadingButton from "@mui/lab/LoadingButton"; import Container from "@mui/material/Container"; import Grid from "@mui/material/Grid"; import LinearProgress from "@mui/material/LinearProgress"; -import SvgIcon from "@mui/material/SvgIcon"; -// MUI import TextField from "@mui/material/TextField"; import Typography from "@mui/material/Typography"; import { useSnackbar } from "notistack"; +import { createApi, jellyfin } from "@/utils/store/api"; import { yellow } from "@mui/material/colors"; import { useMutation } from "@tanstack/react-query"; -import { createApi, useApi } from "../../../utils/store/api"; // SCSS import "./server.scss"; +import { createFileRoute, useNavigate } from "@tanstack/react-router"; -export const ServerSetup = () => { - const [jellyfin] = useApi((state) => [state.jellyfin]); +export const Route = createFileRoute("/setup/server/add")({ + component: ServerSetup, +}); +function ServerSetup() { const [serverIp, setServerIp] = useState(""); const { enqueueSnackbar } = useSnackbar(); - const navigate = useNavigate(); + const navigate = useNavigate({ from: "/setup/server/add" }); const checkServer = useMutation({ mutationFn: async () => { @@ -40,14 +40,14 @@ export const ServerSetup = () => { if (bestServer) { createApi(bestServer.address, undefined); - setDefaultServer(bestServer.systemInfo.Id); - setServer(bestServer.systemInfo.Id, bestServer); + setDefaultServer(bestServer.systemInfo?.Id); + setServer(bestServer.systemInfo?.Id, bestServer); enqueueSnackbar("Client added successfully", { variant: "success", }); - navigate("/login/index"); + navigate({ to: "/login/index" }); } }, onError: (err) => { @@ -149,4 +149,4 @@ export const ServerSetup = () => { ); -}; +} diff --git a/src/routes/setup/serverList/index.jsx b/src/routes/setup/server.list.tsx similarity index 86% rename from src/routes/setup/serverList/index.jsx rename to src/routes/setup/server.list.tsx index 4d314e1..28f2599 100644 --- a/src/routes/setup/serverList/index.jsx +++ b/src/routes/setup/server.list.tsx @@ -1,29 +1,31 @@ import React, { useLayoutEffect, useState } from "react"; -import { relaunch } from "@tauri-apps/api/process"; - import Chip from "@mui/material/Chip"; import IconButton from "@mui/material/IconButton"; import Paper from "@mui/material/Paper"; import Typography from "@mui/material/Typography"; import { red } from "@mui/material/colors"; -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { useSnackbar } from "notistack"; -import { useNavigate } from "react-router-dom"; -import { AppBarBackOnly } from "../../../components/appBar/backOnly"; +import { AppBarBackOnly } from "@/components/appBar/backOnly"; import { delServer, getAllServers, getDefaultServer, setDefaultServer, -} from "../../../utils/storage/servers"; -import { delUser } from "../../../utils/storage/user"; -import { createApi, useApi } from "../../../utils/store/api"; -import { setBackdrop } from "../../../utils/store/backdrop"; +} from "@/utils/storage/servers"; +import { delUser } from "@/utils/storage/user"; +import { createApi } from "@/utils/store/api"; +import { setBackdrop } from "@/utils/store/backdrop"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { createFileRoute, useNavigate } from "@tanstack/react-router"; +import { useSnackbar } from "notistack"; import "./serverList.scss"; -const ServerList = () => { +export const Route = createFileRoute("/setup/server/list")({ + component: ServerList, +}); + +function ServerList() { const navigate = useNavigate(); const [serverState, setServerState] = useState(null); const { enqueueSnackbar } = useSnackbar(); @@ -46,11 +48,11 @@ const ServerList = () => { await setDefaultServer(serverState.id); queryClient.clear(); await defaultServer.refetch(); - createApi(serverState.address); + createApi(serverState.address, undefined); queryClient.removeQueries(); }, onSuccess: async () => { - navigate("/login/index"); + navigate({ to: "/login/index" }); }, onError: (error) => { console.error(error); @@ -69,12 +71,12 @@ const ServerList = () => { if (servers.length > 0) { setDefaultServer(servers[0].id); - createApi(servers[0].address); + createApi(servers[0].address, undefined); } else { - useApi.setState(useApi.getInitialState()); + // TODO: reset api in context here } queryClient.removeQueries(); - navigate("/"); + navigate({ to: "/" }); } enqueueSnackbar("Server deleted successfully!", { variant: "success" }); @@ -105,7 +107,7 @@ const ServerList = () => { style={{ fontSize: "1.64em", }} - onClick={() => navigate("/setup/server")} + onClick={() => navigate({ to: "/setup/server" })} >
    add
    @@ -198,5 +200,5 @@ const ServerList = () => { ); -}; +} export default ServerList; diff --git a/src/routes/setup/server/server.scss b/src/routes/setup/server.scss similarity index 100% rename from src/routes/setup/server/server.scss rename to src/routes/setup/server.scss diff --git a/src/routes/setup/serverList/serverList.scss b/src/routes/setup/serverList.scss similarity index 100% rename from src/routes/setup/serverList/serverList.scss rename to src/routes/setup/serverList.scss diff --git a/src/styles/global.scss b/src/styles/global.scss index ef523cc..94970b0 100644 --- a/src/styles/global.scss +++ b/src/styles/global.scss @@ -33,7 +33,7 @@ div::-webkit-scrollbar { } body { - font-family: "Noto Sans"; + font-family: "Noto Sans Variable",system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; background: $clr-background-default; margin: 0; padding: 0; @@ -87,14 +87,14 @@ body { } .fadeIn { - animation: 0.5s fadeIn forwards; + animation: 0.5s fadeInPage forwards; } .fadeOut { - animation: 0.5s fadeOut forwards; + animation: 0.5s fadeOutPage forwards; } -@keyframes fadeIn { +@keyframes fadeInPage { from { opacity: 0; transform: translate(-20px, 0); @@ -105,7 +105,7 @@ body { } } -@keyframes fadeOut { +@keyframes fadeOutPage { from { opacity: 1; transform: translate(0px, 0px); @@ -292,6 +292,6 @@ h1 { } .glass { - background: rgb(0 0 0 / 0.2) !important; + background: rgb(0 0 0 / 0.3) !important; backdrop-filter: blur(40px); } \ No newline at end of file diff --git a/src/theme.js b/src/theme.js index e30fc75..4cd8214 100644 --- a/src/theme.js +++ b/src/theme.js @@ -29,7 +29,7 @@ export const theme = createTheme({ mode: "dark", }, typography: { - fontFamily: "Noto Sans", + fontFamily: "Noto Sans Variable", }, components: { MuiButton: { diff --git a/src/utils/playback-profiles/helpers/audio-formats.ts b/src/utils/playback-profiles/helpers/audio-formats.ts index 2ad2384..9e89dae 100644 --- a/src/utils/playback-profiles/helpers/audio-formats.ts +++ b/src/utils/playback-profiles/helpers/audio-formats.ts @@ -2,7 +2,7 @@ * @deprecated - Check @/utils/playback-profiles/index */ -import { isApple, isTizen, isTv, isWebOS } from "src/utils/browser-detection"; +import { isApple, isTizen, isTv, isWebOS } from "@/utils/browser-detection"; /** * Determines if audio codec is supported diff --git a/src/utils/playback-profiles/helpers/codec-profiles.ts b/src/utils/playback-profiles/helpers/codec-profiles.ts index 4ce62e3..7eda5d7 100644 --- a/src/utils/playback-profiles/helpers/codec-profiles.ts +++ b/src/utils/playback-profiles/helpers/codec-profiles.ts @@ -2,13 +2,6 @@ * @deprecated - Check @/utils/playback-profiles/index */ -import { - type CodecProfile, - CodecType, - type ProfileCondition, - ProfileConditionType, - ProfileConditionValue, -} from "@jellyfin/sdk/lib/generated-client"; import { isApple, isChromiumBased, @@ -20,7 +13,14 @@ import { isWebOS, isXbox, safariVersion, -} from "src/utils/browser-detection"; +} from "@/utils/browser-detection"; +import { + type CodecProfile, + CodecType, + type ProfileCondition, + ProfileConditionType, + ProfileConditionValue, +} from "@jellyfin/sdk/lib/generated-client"; /** * Gets the max video bitrate diff --git a/src/utils/playback-profiles/helpers/fmp4-audio-formats.ts b/src/utils/playback-profiles/helpers/fmp4-audio-formats.ts index 9bdcb2c..b5aea50 100644 --- a/src/utils/playback-profiles/helpers/fmp4-audio-formats.ts +++ b/src/utils/playback-profiles/helpers/fmp4-audio-formats.ts @@ -2,7 +2,7 @@ * @deprecated - Check @/utils/playback-profiles/index */ -import { isEdge } from "src/utils/browser-detection"; +import { isEdge } from "@/utils/browser-detection"; import { getSupportedAudioCodecs } from "./audio-formats"; import { hasAacSupport, diff --git a/src/utils/playback-profiles/helpers/fmp4-video-formats.ts b/src/utils/playback-profiles/helpers/fmp4-video-formats.ts index f5d3a88..f048611 100644 --- a/src/utils/playback-profiles/helpers/fmp4-video-formats.ts +++ b/src/utils/playback-profiles/helpers/fmp4-video-formats.ts @@ -9,7 +9,7 @@ import { isFirefox, isTizen, isWebOS, -} from "src/utils/browser-detection"; +} from "@/utils/browser-detection"; import { hasH264Support, hasHevcSupport } from "./mp4-video-formats"; /** diff --git a/src/utils/playback-profiles/helpers/hls-formats.ts b/src/utils/playback-profiles/helpers/hls-formats.ts index 896ee68..9ece006 100644 --- a/src/utils/playback-profiles/helpers/hls-formats.ts +++ b/src/utils/playback-profiles/helpers/hls-formats.ts @@ -2,7 +2,7 @@ * @deprecated - Check @/utils/playback-profiles/index */ -import { isTv } from "src/utils/browser-detection"; +import { isTv } from "@/utils/browser-detection"; import { getSupportedAudioCodecs } from "./audio-formats"; import { hasAacSupport, hasEac3Support } from "./mp4-audio-formats"; import { hasH264Support, hasH265Support } from "./mp4-video-formats"; diff --git a/src/utils/playback-profiles/helpers/mp4-audio-formats.ts b/src/utils/playback-profiles/helpers/mp4-audio-formats.ts index e1ef931..3cabf1e 100644 --- a/src/utils/playback-profiles/helpers/mp4-audio-formats.ts +++ b/src/utils/playback-profiles/helpers/mp4-audio-formats.ts @@ -9,7 +9,7 @@ import { isTizen55, isTv, isWebOS, -} from "src/utils/browser-detection"; +} from "@/utils/browser-detection"; import { getSupportedAudioCodecs } from "./audio-formats"; import { hasVp8Support } from "./mp4-video-formats"; diff --git a/src/utils/playback-profiles/helpers/mp4-video-formats.ts b/src/utils/playback-profiles/helpers/mp4-video-formats.ts index 6baf710..2612d99 100644 --- a/src/utils/playback-profiles/helpers/mp4-video-formats.ts +++ b/src/utils/playback-profiles/helpers/mp4-video-formats.ts @@ -8,7 +8,7 @@ import { isTizen55, isTv, isWebOS5, -} from "src/utils/browser-detection"; +} from "@/utils/browser-detection"; /** * Checks if the client has support for the H264 codec diff --git a/src/utils/playback-profiles/helpers/transcoding-formats.ts b/src/utils/playback-profiles/helpers/transcoding-formats.ts index 93b6cf7..1faf109 100644 --- a/src/utils/playback-profiles/helpers/transcoding-formats.ts +++ b/src/utils/playback-profiles/helpers/transcoding-formats.ts @@ -7,7 +7,7 @@ import { isTizen, isTv, supportsMediaSource, -} from "src/utils/browser-detection"; +} from "@/utils/browser-detection"; /** * Checks if the client can play native HLS diff --git a/src/utils/playback-profiles/helpers/webm-audio-formats.ts b/src/utils/playback-profiles/helpers/webm-audio-formats.ts index 57f5f91..18771d6 100644 --- a/src/utils/playback-profiles/helpers/webm-audio-formats.ts +++ b/src/utils/playback-profiles/helpers/webm-audio-formats.ts @@ -2,7 +2,7 @@ * @deprecated - Check @/utils/playback-profiles/index */ -import { isWebOS } from "src/utils/browser-detection"; +import { isWebOS } from "@/utils/browser-detection"; /** * Get an array of supported codecs diff --git a/src/utils/playback-profiles/transcoding-profile.ts b/src/utils/playback-profiles/transcoding-profile.ts index 1dcbe14..e99b338 100644 --- a/src/utils/playback-profiles/transcoding-profile.ts +++ b/src/utils/playback-profiles/transcoding-profile.ts @@ -2,11 +2,6 @@ * @deprecated - Check @/utils/playback-profiles/index */ -import { - DlnaProfileType, - EncodingContext, - type TranscodingProfile, -} from "@jellyfin/sdk/lib/generated-client"; import { isAndroid, isApple, @@ -14,7 +9,12 @@ import { isEdge, isTizen, isTv, -} from "src/utils/browser-detection"; +} from "@/utils/browser-detection"; +import { + DlnaProfileType, + EncodingContext, + type TranscodingProfile, +} from "@jellyfin/sdk/lib/generated-client"; import { getSupportedAudioCodecs } from "./helpers/audio-formats"; import { getSupportedMP4AudioCodecs } from "./helpers/mp4-audio-formats"; import { diff --git a/src/utils/storage/servers.ts b/src/utils/storage/servers.ts index f19bc39..fe1c942 100644 --- a/src/utils/storage/servers.ts +++ b/src/utils/storage/servers.ts @@ -1,7 +1,7 @@ -import { RecommendedServerInfo } from "@jellyfin/sdk"; +import type { RecommendedServerInfo } from "@jellyfin/sdk"; import { Store } from "tauri-plugin-store-api"; -interface ServerInfo extends RecommendedServerInfo { +export interface ServerInfo extends RecommendedServerInfo { id: string; } @@ -41,7 +41,7 @@ export const setDefaultServer = async ( /** * Get a Server */ -export const getServer = async (serverId: string) => { +export const getServer = async (serverId: string | null) => { const servers = await getAllServers(); return servers.find((server) => server.id === serverId); diff --git a/src/utils/store/api.ts b/src/utils/store/api.ts deleted file mode 100644 index 9851245..0000000 --- a/src/utils/store/api.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { Api, Jellyfin } from "@jellyfin/sdk"; -import { create } from "zustand"; -import { version as appVer } from "../../../package.json"; - -// Initial custom axios client to use tauri's http module -import axios from "axios"; -import axiosTauriApiAdapter from "axios-tauri-api-adapter"; - -export const axiosClient = axios.create({ - adapter: axiosTauriApiAdapter, - headers: { - "Access-Control-Allow-Origin": "*", - }, - timeout: 60000, -}); - -const deviceId = localStorage.getItem("deviceId") || crypto.randomUUID(); - -if (!localStorage.getItem("deviceId")) { - localStorage.setItem("deviceId", deviceId); -} - -const jellyfin = new Jellyfin({ - clientInfo: { - name: "JellyPlayer", - version: appVer, - }, - deviceInfo: { - name: "JellyPlayer", - id: deviceId, - }, -}); - -export const useApi = create<{ - api: Api | null; - deviceId: string | null; - jellyfin: Jellyfin; -}>(() => ({ - api: null, - deviceId: deviceId, - jellyfin: jellyfin, -})); - -export const createApi = ( - serverAddress: string, - accessToken: string | undefined, -) => - useApi.setState((state) => ({ - ...state, - api: jellyfin.createApi(serverAddress, accessToken, axiosClient), - })); diff --git a/src/utils/store/api.tsx b/src/utils/store/api.tsx new file mode 100644 index 0000000..792e152 --- /dev/null +++ b/src/utils/store/api.tsx @@ -0,0 +1,95 @@ +import { type Api, Jellyfin } from "@jellyfin/sdk"; +import React, { createContext, useContext, useRef } from "react"; +import { type StoreApi, createStore, useStore } from "zustand"; +import { version as appVer } from "../../../package.json"; + +// Initial custom axios client to use tauri's http module +import axios from "axios"; +import axiosTauriApiAdapter from "axios-tauri-api-adapter"; + +type ApiStore = { + api: Api; + deviceId: string | null; + jellyfin: Jellyfin; + createApi: ( + serverAddress: string | undefined, + accessToken?: string | undefined, + ) => void; +}; + +export const axiosClient = axios.create({ + adapter: axiosTauriApiAdapter, + headers: { + "Access-Control-Allow-Origin": "*", + }, + timeout: 60000, +}); + +const deviceId = localStorage.getItem("deviceId") || crypto.randomUUID(); + +if (!localStorage.getItem("deviceId")) { + localStorage.setItem("deviceId", deviceId); +} + +export const jellyfin = new Jellyfin({ + clientInfo: { + name: "JellyPlayer", + version: appVer, + }, + deviceInfo: { + name: "JellyPlayer", + id: deviceId, + }, +}); + +// export const useApi = create<{ +// api: Api; +// deviceId: string | null; +// jellyfin: Jellyfin; +// }>(() => ({ +// api: undefined, +// deviceId: deviceId, +// jellyfin: jellyfin, +// })); + +const ApiContext = createContext(null); + +export const ApiProvider = ({ children }) => { + const storeRef = useRef>(); + + if (!storeRef.current) { + storeRef.current = createStore()((set) => ({ + api: undefined, + deviceId: deviceId, + jellyfin: jellyfin, + createApi: async (serverAddress, accessToken?) => { + set((state) => ({ + ...state, + api: jellyfin.createApi(serverAddress, accessToken, axiosClient), + })); + await Promise.resolve(); + }, + })); + } + return ( + + {children} + + ); +}; + +export function useApiInContext(selector?: (state: ApiStore) => T) { + const store = useContext(ApiContext); + if (!store) { + throw new Error("Missing StoreProvider"); + } + return useStore(store, selector!); +} + +export const createApi = ( + serverAddress: string | undefined, + accessToken: string | undefined, +) => { + const createApiFn = useApiInContext((s) => s.createApi); + createApiFn(serverAddress, accessToken); +}; diff --git a/src/utils/store/audioPlayback.js b/src/utils/store/audioPlayback.js deleted file mode 100644 index dab9f44..0000000 --- a/src/utils/store/audioPlayback.js +++ /dev/null @@ -1,27 +0,0 @@ -import { create } from "zustand"; - -const initialState = { - display: false, - url: "", - item: {}, - tracks: [], - currentTrack: 0, - playlistItemId: "", -}; - -export const useAudioPlayback = create((set) => ({ - ...initialState, - setUrl: (aurl) => set((state) => ({ ...state, url: aurl })), - setDisplay: (adisplay) => - set((state) => ({ - ...state, - display: adisplay, - })), - setItem: (aitem) => set((state) => ({ ...state, item: aitem })), - setPlaylistItemId: (aitem) => - set((state) => ({ ...state, playlistItemId: aitem })), - setTracks: (aitem) => set((state) => ({ ...state, tracks: aitem })), - setCurrentTrack: (aitem) => - set((state) => ({ ...state, currentTrack: aitem })), - reset: () => set(initialState), -})); diff --git a/src/utils/store/audioPlayback.ts b/src/utils/store/audioPlayback.ts new file mode 100644 index 0000000..a3b14bb --- /dev/null +++ b/src/utils/store/audioPlayback.ts @@ -0,0 +1,32 @@ +import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client"; +import { create } from "zustand"; +import { setQueue } from "./queue"; + +type AudioPlaybackStore = { + display: boolean; + url: string; + item: BaseItemDto | undefined | null; + playlistItemId: string | undefined; +}; +export const useAudioPlayback = create(() => ({ + display: false, + url: "", + item: undefined, + playlistItemId: undefined, +})); + +export const playAudio = ( + url: string, + item: BaseItemDto | undefined | null, + playlistItemId: string | undefined, + queue: BaseItemDto[] | undefined, + queueItemIndex: number, +): void => { + useAudioPlayback.setState({ + display: true, + url, + item, + playlistItemId, + }); + setQueue(queue, queueItemIndex); +}; diff --git a/src/utils/store/central.js b/src/utils/store/central.js index 3114d1a..77a6e99 100644 --- a/src/utils/store/central.js +++ b/src/utils/store/central.js @@ -16,6 +16,7 @@ export const useCentralStore = create(() => ({ /** This is the initial route that app goes to just after app startups */ initialRoute: null, clientVersion: version, + appReady: false, })); /** @@ -25,3 +26,7 @@ export const useCentralStore = create(() => ({ export const setInitialRoute = (route) => { useCentralStore.setState((state) => ({ ...state, initialRoute: route })); }; + +export const setAppReady = (appReady) => { + useCentralStore.setState((state) => ({ ...state, appReady })); +}; \ No newline at end of file diff --git a/src/utils/store/playback.ts b/src/utils/store/playback.ts index 51c4811..f6d0525 100644 --- a/src/utils/store/playback.ts +++ b/src/utils/store/playback.ts @@ -6,110 +6,10 @@ import type { import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api/media-info-api"; import { create } from "zustand"; import playbackProfile from "../playback-profiles"; -import { useApi } from "./api"; +import { useApiInContext } from "./api"; +import { playAudio } from "./audioPlayback"; import useQueue, { setQueue, setTrackIndex } from "./queue"; -// export interface PlaybackState { -// url: string; -// startPosition: number; -// duration: number; -// itemId: string; -// itemName: string | Element; -// subtitleTracks: unknown[]; -// selectedSubtitleTrack: number; -// mediaSourceId: string; -// audioStreamIndex: number; -// videoStreamIndex: number; -// subtitleStreamIndex: number; -// userId: string; -// mediaContainer: string; -// seriesId: string; -// queue: unknown[]; -// episodeIndex: number; -// item: BaseItemDto; -// setUrl: (aurl: string) => void; -// setPosition: (apos: number) => void; -// setDuration: (adur: number) => void; -// setItemId: (aid: string) => void; -// setItemName: (anm: string | Element) => void; -// setUserId: (anm: string) => void; -// setSeriesId: (anm: string) => void; -// setMediaContainer: (anm: string) => void; -// setMediaSourceId: (anm: string) => void; -// setAudioStreamIndex: (anm: number) => void; -// setVideoStreamIndex: (anm: number) => void; -// setSubtitleStreamIndex: (anm: number) => void; -// setSubtitleTracks: (asub: unknown[]) => void; -// setSelectedSubtitleTrack: (asub: number) => void; -// setQueue: (qitem: unknown[]) => void; -// setEpisodeIndex: (aitem: number) => void; -// } - -// export const usePlaybackStore = create((set) => ({ -// url: "", -// startPosition: 0, -// duration: 0, -// itemId: "", -// itemName: "", -// subtitleTracks: [], -// selectedSubtitleTrack: 0, -// mediaSourceId: "", -// audioStreamIndex: 0, -// videoStreamIndex: 0, -// subtitleStreamIndex: 0, -// userId: "", -// mediaContainer: "", -// seriesId: "", -// queue: [], -// episodeIndex: 0, - -// item: {} as BaseItemDto, -// setUrl: (aurl: string) => -// set((state: PlaybackState) => ({ ...state, url: aurl })), -// setPosition: (apos: number) => -// set((state: PlaybackState) => ({ ...state, startPosition: apos })), -// setDuration: (adur: number) => -// set((state: PlaybackState) => ({ ...state, duration: adur })), -// setItemId: (aid: string) => -// set((state: PlaybackState) => ({ ...state, itemId: aid })), -// setItemName: (anm: string | Element) => -// set((state: PlaybackState) => ({ ...state, itemName: anm })), -// setUserId: (anm: string) => -// set((state: PlaybackState) => ({ ...state, userId: anm })), -// setSeriesId: (anm: string) => -// set((state: PlaybackState) => ({ ...state, seriesId: anm })), -// setMediaContainer: (anm: string) => -// set((state: PlaybackState) => ({ ...state, mediaContainer: anm })), -// setMediaSourceId: (anm: string) => -// set((state: PlaybackState) => ({ ...state, mediaSourceId: anm })), -// setAudioStreamIndex: (anm: number) => -// set((state: PlaybackState) => ({ ...state, audioStreamIndex: anm })), -// setVideoStreamIndex: (anm: number) => -// set((state: PlaybackState) => ({ ...state, videoStreamIndex: anm })), -// setSubtitleStreamIndex: (anm: number) => -// set((state: PlaybackState) => ({ ...state, subtitleStreamIndex: anm })), -// setSubtitleTracks: (asub: unknown[]) => -// set((state: PlaybackState) => ({ -// ...state, -// subtitleTracks: asub, -// })), -// setSelectedSubtitleTrack: (asub: number) => -// set((state: PlaybackState) => ({ -// ...state, -// selectedSubtitleTrack: asub, -// })), -// setQueue: (qitem: unknown[]) => -// set((state: PlaybackState) => ({ ...state, queue: qitem })), -// setEpisodeIndex: (aitem: number) => -// set((state: PlaybackState) => ({ ...state, episodeIndex: aitem })), -// })); - -// export const setItem = (item: BaseItemDto) => -// usePlaybackStore.setState((state: PlaybackState) => ({ -// ...state, -// item: item, -// })); - type PlaybackStore = { itemName: string | React.Component; episodeTitle: string | React.Component; @@ -223,85 +123,98 @@ export const playItemFromQueue = async ( ? currentItemIndex - 1 : index; const item = queueItems[requestedItemIndex]; - const api = useApi.getState().api; - const mediaInfo = await getMediaInfoApi(api).getPostedPlaybackInfo({ - audioStreamIndex: item.MediaSources[0].DefaultAudioStreamIndex ?? 0, - subtitleStreamIndex: item.MediaSources[0].DefaultSubtitleStreamIndex ?? 0, - itemId: item.Id, - startTimeTicks: item.UserData?.PlaybackPositionTicks, - userId: userId, - mediaSourceId: item.MediaSources[0].Id, - playbackInfoDto: { - DeviceProfile: playbackProfile, - }, - }); - console.log(mediaInfo); - let itemName = item.Name; - let episodeTitle = ""; - if (item.SeriesId) { - itemName = item.SeriesName; - episodeTitle = `S${item.ParentIndexNumber ?? 0}:E${item.IndexNumber ?? 0} ${ - item.Name - }`; - } + const api = useApiInContext((s) => s.api); + if (item.Type === "Audio") { + const urlOptions = { + deviceId: api?.deviceInfo.id, + userId, + api_key: api?.accessToken, + }; + const urlParams = new URLSearchParams(urlOptions).toString(); - // Select correct subtitle track, this is useful if item is played with playbutton from card since that does not provide coorect default subtitle track index. - let selectedSubtitleTrack: number | "nosub" | undefined = -1; - const subtitles = mediaInfo.data.MediaSources[0].MediaStreams?.filter( - (value) => value.Type === "Subtitle", - ); - let enableSubtitles = true; - if (mediaInfo.data.MediaSources[0].DefaultSubtitleStreamIndex) { - selectedSubtitleTrack = - mediaInfo.data.MediaSources[0].DefaultSubtitleStreamIndex; - } else if (subtitles?.length > 0) { - selectedSubtitleTrack = subtitles[0].Index; + const playbackUrl = `${api.basePath}/Audio/${item?.Id}/universal?${urlParams}`; + console.log(item); + playAudio(playbackUrl, item, undefined, queueItems, requestedItemIndex); } else { - enableSubtitles = false; + const mediaInfo = await getMediaInfoApi(api).getPostedPlaybackInfo({ + audioStreamIndex: item.MediaSources[0].DefaultAudioStreamIndex ?? 0, + subtitleStreamIndex: item.MediaSources[0].DefaultSubtitleStreamIndex ?? 0, + itemId: item.Id, + startTimeTicks: item.UserData?.PlaybackPositionTicks, + userId: userId, + mediaSourceId: item.MediaSources[0].Id, + playbackInfoDto: { + DeviceProfile: playbackProfile, + }, + }); + console.log(mediaInfo); + let itemName = item.Name; + let episodeTitle = ""; + if (item.SeriesId) { + itemName = item.SeriesName; + episodeTitle = `S${item.ParentIndexNumber ?? 0}:E${ + item.IndexNumber ?? 0 + } ${item.Name}`; + } + + // Select correct subtitle track, this is useful if item is played with playbutton from card since that does not provide coorect default subtitle track index. + let selectedSubtitleTrack: number | "nosub" | undefined = -1; + const subtitles = mediaInfo.data.MediaSources[0].MediaStreams?.filter( + (value) => value.Type === "Subtitle", + ); + let enableSubtitles = true; + if (mediaInfo.data.MediaSources[0].DefaultSubtitleStreamIndex) { + selectedSubtitleTrack = + mediaInfo.data.MediaSources[0].DefaultSubtitleStreamIndex; + } else if (subtitles?.length > 0) { + selectedSubtitleTrack = subtitles[0].Index; + } else { + enableSubtitles = false; + } + const videoTrack = mediaInfo.data.MediaSources[0].MediaStreams?.filter( + (value) => value.Type === "Subtitle", + ); + + const urlOptions = { + Static: true, + tag: mediaInfo.data.MediaSources[0].ETag, + mediaSourceId: mediaInfo.data.MediaSources[0].Id, + deviceId: api?.deviceInfo.id, + api_key: api?.accessToken, + startTimeTicks: item.UserData?.PlaybackPositionTicks, + }; + + const urlParams = new URLSearchParams(urlOptions).toString(); + let playbackUrl = `${api?.basePath}/Videos/${mediaInfo.data.MediaSources[0].Id}/stream.${mediaInfo.data.MediaSources[0].Container}?${urlParams}`; + + if ( + mediaInfo.data.MediaSources[0].SupportsTranscoding && + mediaInfo.data.MediaSources[0].TranscodingUrl + ) { + playbackUrl = `${api.basePath}${mediaInfo.data.MediaSources[0].TranscodingUrl}`; + } else if (mediaInfo.data.MediaSources[0].hlsStream) { + playbackUrl = mediaInfo.data.MediaSources[0].hlsStream; + } + playItem( + itemName, + episodeTitle, + videoTrack[0].Index, + mediaInfo.data.MediaSources[0].DefaultAudioStreamIndex ?? 0, + selectedSubtitleTrack, + mediaInfo.data?.MediaSources[0].Container ?? "mkv", + enableSubtitles, + playbackUrl, + userId, + item.UserData?.PlaybackPositionTicks, + item.RunTimeTicks, + item, + queueItems, + requestedItemIndex, + subtitles, + mediaInfo.data.MediaSources[0].Id, + mediaInfo.data.PlaySessionId, + ); } - const videoTrack = mediaInfo.data.MediaSources[0].MediaStreams?.filter( - (value) => value.Type === "Subtitle", - ); - - const urlOptions = { - Static: true, - tag: mediaInfo.data.MediaSources[0].ETag, - mediaSourceId: mediaInfo.data.MediaSources[0].Id, - deviceId: api?.deviceInfo.id, - api_key: api?.accessToken, - startTimeTicks: item.UserData?.PlaybackPositionTicks, - }; - - const urlParams = new URLSearchParams(urlOptions).toString(); - let playbackUrl = `${api?.basePath}/Videos/${mediaInfo.data.MediaSources[0].Id}/stream.${mediaInfo.data.MediaSources[0].Container}?${urlParams}`; - - if ( - mediaInfo.data.MediaSources[0].SupportsTranscoding && - mediaInfo.data.MediaSources[0].TranscodingUrl - ) { - playbackUrl = `${api.basePath}${mediaInfo.data.MediaSources[0].TranscodingUrl}`; - } else if (mediaInfo.data.MediaSources[0].hlsStream) { - playbackUrl = mediaInfo.data.MediaSources[0].hlsStream; - } - playItem( - itemName, - episodeTitle, - videoTrack[0].Index, - mediaInfo.data.MediaSources[0].DefaultAudioStreamIndex ?? 0, - selectedSubtitleTrack, - mediaInfo.data?.MediaSources[0].Container ?? "mkv", - enableSubtitles, - playbackUrl, - userId, - item.UserData?.PlaybackPositionTicks, - item.RunTimeTicks, - item, - queueItems, - requestedItemIndex, - subtitles, - mediaInfo.data.MediaSources[0].Id, - mediaInfo.data.PlaySessionId, - ); return "playing"; // Return any value to end mutation pending status }; diff --git a/src/utils/store/queue.ts b/src/utils/store/queue.ts index 9318665..606b24a 100644 --- a/src/utils/store/queue.ts +++ b/src/utils/store/queue.ts @@ -1,4 +1,4 @@ -import { BaseItemDto } from "@jellyfin/sdk/lib/generated-client"; +import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client"; import { create } from "zustand"; interface QueueStore { @@ -11,7 +11,10 @@ const useQueue = create(() => ({ currentItemIndex: 0, })); -export const setQueue = (tracks: BaseItemDto[], currentItemIndex: number) => { +export const setQueue = ( + tracks: BaseItemDto[] | undefined, + currentItemIndex: number, +) => { useQueue.setState(() => ({ tracks, currentItemIndex })); }; diff --git a/tsconfig.json b/tsconfig.json index cb54163..6277951 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,5 +1,10 @@ { "compilerOptions": { + "paths": { + "@/*": [ + "./src/*" + ] + }, "target": "ESNext", // Specify ECMAScript target version "lib": [ "dom", @@ -33,5 +38,5 @@ "exclude": [ "node_modules", "build" - ] // *** The files to not type check *** + ] } \ No newline at end of file diff --git a/vite.config.js b/vite.config.js index 7188750..0e7d0b2 100644 --- a/vite.config.js +++ b/vite.config.js @@ -1,43 +1,46 @@ import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import svgr from "vite-plugin-svgr"; -import million from "million/compiler"; +import { TanStackRouterVite } from '@tanstack/router-vite-plugin' +import MillionLint from '@million/lint'; +import path from "path"; // https://vitejs.dev/config/ +const plugins = [MillionLint.vite(),react(), svgr(), TanStackRouterVite()]; export default defineConfig({ - plugins: [react(), svgr()], - css: { - modules: { - scopeBehaviour: "global" - }, - preprocessorOptions: { - scss: { - additionalData: '@use "./src/styles/variables.scss" as *;', - }, - }, - }, - resolve: { - alias: { - src: "/src", - }, - }, - // prevent vite from obscuring rust errors - clearScreen: false, - // Tauri expects a fixed port, fail if that port is not available - server: { - strictPort: true, - }, - // to make use of `TAURI_PLATFORM`, `TAURI_ARCH`, `TAURI_FAMILY`, - // `TAURI_PLATFORM_VERSION`, `TAURI_PLATFORM_TYPE` and `TAURI_DEBUG` - // env variables - envPrefix: ["VITE_", "TAURI_"], - build: { - // Tauri uses Chromium on Windows and WebKit on macOS and Linux - target: process.env.TAURI_PLATFORM == "windows" ? "chrome105" : "safari13", - // don't minify for debug builds - minify: !process.env.TAURI_DEBUG ? "esbuild" : false, - // produce sourcemaps for debug builds - sourcemap: !!process.env.TAURI_DEBUG, - cssCodeSplit: process.env.TAURI_DEBUG ? false : undefined, - }, -}); + plugins: plugins, + css: { + modules: { + scopeBehaviour: "global" + }, + preprocessorOptions: { + scss: { + additionalData: '@use "./src/styles/variables.scss" as *;' + } + } + }, + resolve: { + alias: [ + { find: '@', replacement: path.resolve(__dirname, 'src') }, + ] + }, + // prevent vite from obscuring rust errors + clearScreen: false, + // Tauri expects a fixed port, fail if that port is not available + server: { + strictPort: true + }, + // to make use of `TAURI_PLATFORM`, `TAURI_ARCH`, `TAURI_FAMILY`, + // `TAURI_PLATFORM_VERSION`, `TAURI_PLATFORM_TYPE` and `TAURI_DEBUG` + // env variables + envPrefix: ["VITE_", "TAURI_"], + build: { + // Tauri uses Chromium on Windows and WebKit on macOS and Linux + target: process.env.TAURI_PLATFORM == "windows" ? "chrome105" : "safari13", + // don't minify for debug builds + minify: !process.env.TAURI_DEBUG ? "esbuild" : false, + // produce sourcemaps for debug builds + sourcemap: !!process.env.TAURI_DEBUG, + cssCodeSplit: process.env.TAURI_DEBUG ? false : undefined + } +}); \ No newline at end of file