refactor: implement new login logic and verify context.api status

This commit is contained in:
Prayag Prajapati committed 2024-05-29 18:10:22 +05:30
1 parent b1737b82e8
commit b8552ac35d
25 files changed
+314 -238

No files matched your search

+4 -1
View File
@@ -23,5 +23,8 @@
"editor.defaultFormatter": "biomejs.biome" "editor.defaultFormatter": "biomejs.biome"
}, },
"rust-analyzer.linkedProjects": ["./src-tauri/Cargo.toml"], "rust-analyzer.linkedProjects": ["./src-tauri/Cargo.toml"],
"typescript.tsdk": "node_modules/typescript/lib" "typescript.tsdk": "node_modules/typescript/lib",
"[scss]": {
"editor.defaultFormatter": "vscode.css-language-features"
}
} }
+1
View File
@@ -4,6 +4,7 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="http://localhost:8097"></script>
<title>Jellyplayer</title> <title>Jellyplayer</title>
<style> <style>
.app-loading { .app-loading {
+4 -14
View File
@@ -53,6 +53,7 @@ import {
ListItemButton, ListItemButton,
ListItemText, ListItemText,
} from "@mui/material"; } from "@mui/material";
import BackButton from "../buttons/backButton";
interface ListItemLinkProps { interface ListItemLinkProps {
icon?: React.ReactElement; icon?: React.ReactElement;
@@ -103,24 +104,18 @@ export const AppBar = () => {
return usr.data; return usr.data;
}, },
enabled: display, enabled: display,
networkMode: "always",
}); });
const libraries = useQuery({ const libraries = useQuery({
queryKey: ["libraries"], queryKey: ["libraries"],
queryFn: async () => { queryFn: async () => {
const libs = await getUserViewsApi(api).getUserViews({ const libs = await getUserViewsApi(api).getUserViews({
userId: user.data.Id, userId: user.data?.Id,
}); });
return libs.data; return libs.data;
}, },
enabled: !!user.data && !!api.accessToken, enabled: !!user.data && !!api.accessToken,
networkMode: "always", networkMode: "always",
}); });
useEffect(() => {
if (user.isError) {
console.error(user.error);
}
}, [user]);
const trigger = useScrollTrigger({ const trigger = useScrollTrigger({
disableHysteresis: true, disableHysteresis: true,
@@ -197,13 +192,8 @@ export const AppBar = () => {
<IconButton onClick={() => setShowDrawer(true)}> <IconButton onClick={() => setShowDrawer(true)}>
<div className="material-symbols-rounded">menu</div> <div className="material-symbols-rounded">menu</div>
</IconButton> </IconButton>
<IconButton <BackButton />
disabled={!backButtonVisible} <IconButton onClick={() => navigate({ to: "/home/" })}>
onClick={() => navigate(-1)}
>
<div className="material-symbols-rounded">arrow_back</div>
</IconButton>
<IconButton onClick={() => navigate("/home")}>
<div <div
className={ className={
location.pathname === "/home" location.pathname === "/home"
+2 -1
View File
@@ -4,6 +4,7 @@ import React, { useEffect } from "react";
import IconButton from "@mui/material/IconButton"; import IconButton from "@mui/material/IconButton";
import { useApiInContext } from "@/utils/store/api";
import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api"; import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api";
import CircularProgress from "@mui/material/CircularProgress"; import CircularProgress from "@mui/material/CircularProgress";
import { pink } from "@mui/material/colors"; import { pink } from "@mui/material/colors";
@@ -12,7 +13,7 @@ import { useRouteContext } from "@tanstack/react-router";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
const LikeButton = ({ itemId, isFavorite, queryKey, userId, itemName }) => { const LikeButton = ({ itemId, isFavorite, queryKey, userId, itemName }) => {
const api = useRouteContext({ from: "/" }).api; const api = useApiInContext((s) => s.api);
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const { enqueueSnackbar } = useSnackbar(); const { enqueueSnackbar } = useSnackbar();
+2 -1
View File
@@ -8,12 +8,13 @@ import IconButton from "@mui/material/IconButton";
import { green } from "@mui/material/colors"; import { green } from "@mui/material/colors";
import { useMutation, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useApiInContext } from "@/utils/store/api";
import { getPlaystateApi } from "@jellyfin/sdk/lib/utils/api/playstate-api"; import { getPlaystateApi } from "@jellyfin/sdk/lib/utils/api/playstate-api";
import { useRouteContext } from "@tanstack/react-router"; import { useRouteContext } from "@tanstack/react-router";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
const MarkPlayedButton = ({ itemId, isPlayed, queryKey, userId, itemName }) => { const MarkPlayedButton = ({ itemId, isPlayed, queryKey, userId, itemName }) => {
const api = useRouteContext({ from: "/" }).api; const api = useApiInContext((s) => s.api);
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const { enqueueSnackbar } = useSnackbar(); const { enqueueSnackbar } = useSnackbar();
+2 -1
View File
@@ -34,6 +34,7 @@ import { playItem, usePlaybackDataLoadStore } from "@/utils/store/playback";
import type PlayResult from "@//utils/types/playResult"; import type PlayResult from "@//utils/types/playResult";
import { getRuntimeCompact } from "@/utils/date/time"; import { getRuntimeCompact } from "@/utils/date/time";
import playbackProfile from "@/utils/playback-profiles"; import playbackProfile from "@/utils/playback-profiles";
import { useApiInContext } from "@/utils/store/api";
import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api/media-info-api"; import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api/media-info-api";
import type { SxProps } from "@mui/material"; import type { SxProps } from "@mui/material";
import type { AxiosResponse } from "axios"; import type { AxiosResponse } from "axios";
@@ -77,7 +78,7 @@ const PlayButton = ({
playlistItemId = "", playlistItemId = "",
trackIndex, trackIndex,
}: PlayButtonProps) => { }: PlayButtonProps) => {
const api = useRouteContext({ from: "/" }).api; const api = useApiInContext((s) => s.api);
const navigate = useNavigate(); const navigate = useNavigate();
const setPlaybackDataLoading = usePlaybackDataLoadStore( const setPlaybackDataLoading = usePlaybackDataLoadStore(
+2 -1
View File
@@ -1,3 +1,4 @@
import { useApiInContext } from "@/utils/store/api";
import { playItemFromQueue } from "@/utils/store/playback"; import { playItemFromQueue } from "@/utils/store/playback";
import useQueue from "@/utils/store/queue"; import useQueue from "@/utils/store/queue";
import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api";
@@ -7,7 +8,7 @@ import { useRouteContext } from "@tanstack/react-router";
import React from "react"; import React from "react";
const PlayNextButton = () => { const PlayNextButton = () => {
const api = useRouteContext({ from: "/" }).api; const api = useApiInContext((s) => s.api);
const user = useQuery({ const user = useQuery({
queryKey: ["user"], queryKey: ["user"],
queryFn: async () => { queryFn: async () => {
@@ -7,7 +7,7 @@ import { useRouteContext } from "@tanstack/react-router";
import React from "react"; import React from "react";
const PlayPreviousButton = () => { const PlayPreviousButton = () => {
const api = useRouteContext({ from: "/" }).api; const api = useApiInContext((s) => s.api);
const user = useQuery({ const user = useQuery({
queryKey: ["user"], queryKey: ["user"],
queryFn: async () => { queryFn: async () => {
+1 -1
View File
@@ -15,7 +15,7 @@ import { useMutation, useQuery } from "@tanstack/react-query";
import "./queueButton.scss"; import "./queueButton.scss";
import { useRouteContext } from "@tanstack/react-router"; import { useRouteContext } from "@tanstack/react-router";
const QueueButton = () => { const QueueButton = () => {
const api = useRouteContext({ from: "/" }).api; const api = useApiInContext((s) => s.api);
const [queueItems, currentItemIndex] = useQueue((state) => [ const [queueItems, currentItemIndex] = useQueue((state) => [
state.tracks, state.tracks,
state.currentItemIndex, state.currentItemIndex,
+2 -1
View File
@@ -18,6 +18,7 @@ import PlayButton from "../buttons/playButton";
import ErrorBoundary from "../errorBoundary"; import ErrorBoundary from "../errorBoundary";
import { getTypeIcon } from "../utils/iconsCollection"; import { getTypeIcon } from "../utils/iconsCollection";
import "./card.scss"; import "./card.scss";
import { useApiInContext } from "@/utils/store/api";
const cardImageAspectRatios = { const cardImageAspectRatios = {
thumb: 1.777, thumb: 1.777,
@@ -60,7 +61,7 @@ export const Card = ({
disableOverlay: boolean; disableOverlay: boolean;
overrideIcon: any; overrideIcon: any;
}) => { }) => {
const api = useRouteContext({ from: "/" }).api; const api = useApiInContext((s) => s.api);
const navigate = useNavigate(); const navigate = useNavigate();
const defaultOnClick = () => { const defaultOnClick = () => {
if (availableSpecialRoutes.includes(item.Type)) { if (availableSpecialRoutes.includes(item.Type)) {
+2 -1
View File
@@ -17,6 +17,7 @@ import { useQuery } from "@tanstack/react-query";
import { useNavigate, useRouteContext } from "@tanstack/react-router"; import { useNavigate, useRouteContext } from "@tanstack/react-router";
import { getTypeIcon } from "../utils/iconsCollection"; import { getTypeIcon } from "../utils/iconsCollection";
import { useApiInContext } from "@/utils/store/api";
import { useCarouselStore } from "@/utils/store/carousel"; import { useCarouselStore } from "@/utils/store/carousel";
import { BaseItemKind } from "@jellyfin/sdk/lib/generated-client"; import { BaseItemKind } from "@jellyfin/sdk/lib/generated-client";
import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api";
@@ -41,7 +42,7 @@ const availableSpecialRoutes = [
* @returns {React.Component} * @returns {React.Component}
*/ */
const CarouselSlide = ({ item }) => { const CarouselSlide = ({ item }) => {
const api = useRouteContext({ from: "/" }).api; const api = useApiInContext((s) => s.api);
const navigate = useNavigate(); const navigate = useNavigate();
const user = useQuery({ const user = useQuery({
@@ -4,6 +4,7 @@ import { Card } from "../../card/card";
import { CardScroller } from "../../cardScroller/cardScroller"; import { CardScroller } from "../../cardScroller/cardScroller";
import { CardsSkeleton } from "../../skeleton/cards"; import { CardsSkeleton } from "../../skeleton/cards";
import { useApiInContext } from "@/utils/store/api";
import { BaseItemKind } from "@jellyfin/sdk/lib/generated-client"; import { BaseItemKind } from "@jellyfin/sdk/lib/generated-client";
import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api";
import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api"; import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api";
@@ -13,7 +14,7 @@ import { useRouteContext } from "@tanstack/react-router";
* @description Latest Media Section * @description Latest Media Section
*/ */
export const LatestMediaSection = ({ latestMediaLib }) => { export const LatestMediaSection = ({ latestMediaLib }) => {
const api = useRouteContext({ from: "/" }).api; const api = useApiInContext((s) => s.api);
const user = useQuery({ const user = useQuery({
queryKey: ["user"], queryKey: ["user"],
queryFn: async () => { queryFn: async () => {
+2 -2
View File
@@ -1,6 +1,6 @@
import { LinearProgress } from "@mui/material"; import { LinearProgress } from "@mui/material";
import { useNProgress } from "@tanem/react-nprogress"; import { useNProgress } from "@tanem/react-nprogress";
import React from "react"; import type React from "react";
const NProgress: React.FC<{ isAnimating: boolean | number }> = ({ const NProgress: React.FC<{ isAnimating: boolean | number }> = ({
isAnimating, isAnimating,
@@ -19,7 +19,7 @@ const NProgress: React.FC<{ isAnimating: boolean | number }> = ({
top: "0", top: "0",
left: "0", left: "0",
right: "0", right: "0",
zIndex: "10000", zIndex: "10001",
}} }}
> >
<LinearProgress <LinearProgress
+2 -1
View File
@@ -46,7 +46,8 @@ function ProviderWrapper() {
ReactDOM.createRoot(document.getElementById("root")!).render( ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode> <React.StrictMode>
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<Suspense fallback={<h1>Fuck react</h1>}> {/* TODO: Create a proper loading fallback component */}
<Suspense fallback={<h1>Loading in main.tsx</h1>}>
<ApiProvider> <ApiProvider>
<ProviderWrapper /> <ProviderWrapper />
</ApiProvider> </ApiProvider>
+81 -4
View File
@@ -19,6 +19,7 @@ import { Route as ApiLoginIndexImport } from './routes/_api/login/index'
import { Route as ApiHomeIndexImport } from './routes/_api/home/index' import { Route as ApiHomeIndexImport } from './routes/_api/home/index'
import { Route as ApiFavoriteIndexImport } from './routes/_api/favorite/index' import { Route as ApiFavoriteIndexImport } from './routes/_api/favorite/index'
import { Route as SetupServerListImport } from './routes/setup/server.list' import { Route as SetupServerListImport } from './routes/setup/server.list'
import { Route as SetupServerErrorImport } from './routes/setup/server.error'
import { Route as SetupServerAddImport } from './routes/setup/server.add' import { Route as SetupServerAddImport } from './routes/setup/server.add'
import { Route as ApiSeriesIdImport } from './routes/_api/series/$id' import { Route as ApiSeriesIdImport } from './routes/_api/series/$id'
import { Route as ApiPlaylistIdImport } from './routes/_api/playlist/$id' import { Route as ApiPlaylistIdImport } from './routes/_api/playlist/$id'
@@ -75,6 +76,11 @@ const SetupServerListRoute = SetupServerListImport.update({
getParentRoute: () => rootRoute, getParentRoute: () => rootRoute,
} as any) } as any)
const SetupServerErrorRoute = SetupServerErrorImport.update({
path: '/setup/server/error',
getParentRoute: () => rootRoute,
} as any)
const SetupServerAddRoute = SetupServerAddImport.update({ const SetupServerAddRoute = SetupServerAddImport.update({
path: '/setup/server/add', path: '/setup/server/add',
getParentRoute: () => rootRoute, getParentRoute: () => rootRoute,
@@ -145,86 +151,156 @@ const ApiLoginUserIdUserNameRoute = ApiLoginUserIdUserNameImport.update({
declare module '@tanstack/react-router' { declare module '@tanstack/react-router' {
interface FileRoutesByPath { interface FileRoutesByPath {
'/': { '/': {
id: '/'
path: '/'
fullPath: '/'
preLoaderRoute: typeof IndexImport preLoaderRoute: typeof IndexImport
parentRoute: typeof rootRoute parentRoute: typeof rootRoute
} }
'/_api': { '/_api': {
id: '/_api'
path: ''
fullPath: ''
preLoaderRoute: typeof ApiImport preLoaderRoute: typeof ApiImport
parentRoute: typeof rootRoute parentRoute: typeof rootRoute
} }
'/_api/album/$id': { '/_api/album/$id': {
id: '/_api/album/$id'
path: '/album/$id'
fullPath: '/album/$id'
preLoaderRoute: typeof ApiAlbumIdImport preLoaderRoute: typeof ApiAlbumIdImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/_api/artist/$id': { '/_api/artist/$id': {
id: '/_api/artist/$id'
path: '/artist/$id'
fullPath: '/artist/$id'
preLoaderRoute: typeof ApiArtistIdImport preLoaderRoute: typeof ApiArtistIdImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/_api/boxset/$id': { '/_api/boxset/$id': {
id: '/_api/boxset/$id'
path: '/boxset/$id'
fullPath: '/boxset/$id'
preLoaderRoute: typeof ApiBoxsetIdImport preLoaderRoute: typeof ApiBoxsetIdImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/_api/episode/$id': { '/_api/episode/$id': {
id: '/_api/episode/$id'
path: '/episode/$id'
fullPath: '/episode/$id'
preLoaderRoute: typeof ApiEpisodeIdImport preLoaderRoute: typeof ApiEpisodeIdImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/_api/item/$id': { '/_api/item/$id': {
id: '/_api/item/$id'
path: '/item/$id'
fullPath: '/item/$id'
preLoaderRoute: typeof ApiItemIdImport preLoaderRoute: typeof ApiItemIdImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/_api/library/$id': { '/_api/library/$id': {
id: '/_api/library/$id'
path: '/library/$id'
fullPath: '/library/$id'
preLoaderRoute: typeof ApiLibraryIdImport preLoaderRoute: typeof ApiLibraryIdImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/_api/login/list': { '/_api/login/list': {
id: '/_api/login/list'
path: '/login/list'
fullPath: '/login/list'
preLoaderRoute: typeof ApiLoginListImport preLoaderRoute: typeof ApiLoginListImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/_api/login/manual': { '/_api/login/manual': {
id: '/_api/login/manual'
path: '/login/manual'
fullPath: '/login/manual'
preLoaderRoute: typeof ApiLoginManualImport preLoaderRoute: typeof ApiLoginManualImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/_api/person/$id': { '/_api/person/$id': {
id: '/_api/person/$id'
path: '/person/$id'
fullPath: '/person/$id'
preLoaderRoute: typeof ApiPersonIdImport preLoaderRoute: typeof ApiPersonIdImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/_api/playlist/$id': { '/_api/playlist/$id': {
id: '/_api/playlist/$id'
path: '/playlist/$id'
fullPath: '/playlist/$id'
preLoaderRoute: typeof ApiPlaylistIdImport preLoaderRoute: typeof ApiPlaylistIdImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/_api/series/$id': { '/_api/series/$id': {
id: '/_api/series/$id'
path: '/series/$id'
fullPath: '/series/$id'
preLoaderRoute: typeof ApiSeriesIdImport preLoaderRoute: typeof ApiSeriesIdImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/setup/server/add': { '/setup/server/add': {
id: '/setup/server/add'
path: '/setup/server/add'
fullPath: '/setup/server/add'
preLoaderRoute: typeof SetupServerAddImport preLoaderRoute: typeof SetupServerAddImport
parentRoute: typeof rootRoute parentRoute: typeof rootRoute
} }
'/setup/server/error': {
id: '/setup/server/error'
path: '/setup/server/error'
fullPath: '/setup/server/error'
preLoaderRoute: typeof SetupServerErrorImport
parentRoute: typeof rootRoute
}
'/setup/server/list': { '/setup/server/list': {
id: '/setup/server/list'
path: '/setup/server/list'
fullPath: '/setup/server/list'
preLoaderRoute: typeof SetupServerListImport preLoaderRoute: typeof SetupServerListImport
parentRoute: typeof rootRoute parentRoute: typeof rootRoute
} }
'/_api/favorite/': { '/_api/favorite/': {
id: '/_api/favorite/'
path: '/favorite/'
fullPath: '/favorite/'
preLoaderRoute: typeof ApiFavoriteIndexImport preLoaderRoute: typeof ApiFavoriteIndexImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/_api/home/': { '/_api/home/': {
id: '/_api/home/'
path: '/home/'
fullPath: '/home/'
preLoaderRoute: typeof ApiHomeIndexImport preLoaderRoute: typeof ApiHomeIndexImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/_api/login/': { '/_api/login/': {
id: '/_api/login/'
path: '/login/'
fullPath: '/login/'
preLoaderRoute: typeof ApiLoginIndexImport preLoaderRoute: typeof ApiLoginIndexImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/_api/player/': { '/_api/player/': {
id: '/_api/player/'
path: '/player/'
fullPath: '/player/'
preLoaderRoute: typeof ApiPlayerIndexImport preLoaderRoute: typeof ApiPlayerIndexImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/_api/search/': { '/_api/search/': {
id: '/_api/search/'
path: '/search/'
fullPath: '/search/'
preLoaderRoute: typeof ApiSearchIndexImport preLoaderRoute: typeof ApiSearchIndexImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
'/_api/login/$userId/$userName': { '/_api/login/$userId/$userName': {
id: '/_api/login/$userId/$userName'
path: '/login/$userId/$userName'
fullPath: '/login/$userId/$userName'
preLoaderRoute: typeof ApiLoginUserIdUserNameImport preLoaderRoute: typeof ApiLoginUserIdUserNameImport
parentRoute: typeof ApiImport parentRoute: typeof ApiImport
} }
@@ -233,9 +309,9 @@ declare module '@tanstack/react-router' {
// Create and export the route tree // Create and export the route tree
export const routeTree = rootRoute.addChildren([ export const routeTree = rootRoute.addChildren({
IndexRoute, IndexRoute,
ApiRoute.addChildren([ ApiRoute: ApiRoute.addChildren({
ApiAlbumIdRoute, ApiAlbumIdRoute,
ApiArtistIdRoute, ApiArtistIdRoute,
ApiBoxsetIdRoute, ApiBoxsetIdRoute,
@@ -253,9 +329,10 @@ export const routeTree = rootRoute.addChildren([
ApiPlayerIndexRoute, ApiPlayerIndexRoute,
ApiSearchIndexRoute, ApiSearchIndexRoute,
ApiLoginUserIdUserNameRoute, ApiLoginUserIdUserNameRoute,
]), }),
SetupServerAddRoute, SetupServerAddRoute,
SetupServerErrorRoute,
SetupServerListRoute, SetupServerListRoute,
]) })
/* prettier-ignore-end */ /* prettier-ignore-end */
+26 -2
View File
@@ -8,6 +8,7 @@ import { LoadingButton } from "@mui/lab";
import { import {
Button, Button,
Chip, Chip,
CircularProgress,
CssBaseline, CssBaseline,
Dialog, Dialog,
DialogActions, DialogActions,
@@ -24,6 +25,7 @@ import {
createRootRoute, createRootRoute,
createRootRouteWithContext, createRootRouteWithContext,
useNavigate, useNavigate,
useRouterState,
} from "@tanstack/react-router"; } from "@tanstack/react-router";
import { TanStackRouterDevtools } from "@tanstack/router-devtools"; import { TanStackRouterDevtools } from "@tanstack/router-devtools";
import { relaunch } from "@tauri-apps/api/process"; import { relaunch } from "@tauri-apps/api/process";
@@ -46,7 +48,6 @@ import "@fontsource-variable/jetbrains-mono";
import "@fontsource-variable/noto-sans"; import "@fontsource-variable/noto-sans";
import "material-symbols/rounded.scss"; import "material-symbols/rounded.scss";
import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice";
import type { Api } from "@jellyfin/sdk"; import type { Api } from "@jellyfin/sdk";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
@@ -65,6 +66,7 @@ export const Route = createRootRouteWithContext<ApiContext>()({
component: () => { component: () => {
const isQueryFetching = useIsFetching(); const isQueryFetching = useIsFetching();
const isMutating = useIsMutating(); const isMutating = useIsMutating();
const routeIsLoading = useRouterState().isLoading;
const [updateDialog, setUpdateDialog] = useState(false); const [updateDialog, setUpdateDialog] = useState(false);
const [updateDialogButton, setUpdateDialogButton] = useState(false); const [updateDialogButton, setUpdateDialogButton] = useState(false);
const [updateInfo, setUpdateInfo] = useState<UpdateManifest | undefined>( const [updateInfo, setUpdateInfo] = useState<UpdateManifest | undefined>(
@@ -107,7 +109,29 @@ export const Route = createRootRouteWithContext<ApiContext>()({
<CssBaseline /> <CssBaseline />
<Settings /> <Settings />
<EasterEgg /> <EasterEgg />
<NProgress isAnimating={isQueryFetching || isMutating} /> <NProgress
isAnimating={isQueryFetching || isMutating || routeIsLoading}
/>
{routeIsLoading && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
style={{
width: "100vw",
height: "100vh",
display: "flex",
justifyContent: "center",
alignItems: "center",
background: "rgb(0 0 0 / 0.35)",
position: "fixed",
zIndex: 10000,
}}
>
<CircularProgress size={72} thickness={2} />
</motion.div>
)}
<Dialog <Dialog
open={updateDialog} open={updateDialog}
fullWidth fullWidth
+24 -1
View File
@@ -4,7 +4,8 @@ import {
getServer, getServer,
} from "@/utils/storage/servers"; } from "@/utils/storage/servers";
import { getUser } from "@/utils/storage/user"; import { getUser } from "@/utils/storage/user";
import { axiosClient } from "@/utils/store/api"; import { axiosClient, useApiInContext } from "@/utils/store/api";
import { getSystemApi } from "@jellyfin/sdk/lib/utils/api/system-api";
import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api";
import { Outlet, createFileRoute, redirect } from "@tanstack/react-router"; import { Outlet, createFileRoute, redirect } from "@tanstack/react-router";
import React from "react"; import React from "react";
@@ -12,6 +13,7 @@ import { Suspense } from "react";
export const Route = createFileRoute("/_api")({ export const Route = createFileRoute("/_api")({
beforeLoad: async ({ context, location }) => { beforeLoad: async ({ context, location }) => {
console.log(context.api);
if (!context.api) { if (!context.api) {
const currentServerId = await getDefaultServer(); const currentServerId = await getDefaultServer();
if (currentServerId) { if (currentServerId) {
@@ -23,6 +25,27 @@ export const Route = createFileRoute("/_api")({
context.createApi(currentServer?.address, undefined); // Creates Api context.createApi(currentServer?.address, undefined); // Creates Api
} }
} }
} else if (context.api) {
try {
await getSystemApi(context.api).getPingSystem(); // Verify server status
} catch (error) {
throw redirect({
to: "/setup/server/error",
search: {
redirect: location.href,
},
});
}
try {
await getUserApi(context.api).getCurrentUser(); // Verify user is able to authenticate
} catch (error) {
throw redirect({
to: "/login/manual",
search: {
redirect: location.href,
},
});
}
} }
}, },
}); });
+1
View File
@@ -25,6 +25,7 @@ import { setBackdrop, useBackdropStore } from "@/utils/store/backdrop";
import CarouselSlide from "@/components/carouselSlide"; import CarouselSlide from "@/components/carouselSlide";
import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice"; import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice";
import { useApiInContext } from "@/utils/store/api";
import { BaseItemKind, ItemFields } from "@jellyfin/sdk/lib/generated-client"; import { BaseItemKind, ItemFields } from "@jellyfin/sdk/lib/generated-client";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
+1 -2
View File
@@ -115,9 +115,8 @@ function ItemDetail() {
queryKey: ["item", id], queryKey: ["item", id],
queryFn: async () => { queryFn: async () => {
const result = await getUserLibraryApi(api).getItem({ const result = await getUserLibraryApi(api).getItem({
userId: user.data.Id, userId: user.data?.Id,
itemId: id, itemId: id,
fields: Object.values(ItemFields),
}); });
return result.data; return result.data;
}, },
+32
View File
@@ -29,3 +29,35 @@
flex: 1 1 0 !important; flex: 1 1 0 !important;
} }
} }
.login {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
&-form {
width: 28em;
display: flex;
flex-direction: column;
justify-content: center;
align-items: stretch;
gap:1em;
&-container{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap:2em;
background: rgb(255 255 255 / 0.05);
padding: 2em;
border-radius: 20px;
border: 1px solid rgb(255 255 255 / 0.1);
&.padded-top {
margin-top: 25vh;
}
}
}
}
+91 -117
View File
@@ -1,5 +1,5 @@
import { queryOptions, useQuery } from "@tanstack/react-query"; import { queryOptions, useMutation, useQuery } from "@tanstack/react-query";
import React, { useLayoutEffect, useState } from "react"; import React, { type FormEvent, useLayoutEffect, useState } from "react";
import { saveUser } from "@/utils/storage/user.js"; import { saveUser } from "@/utils/storage/user.js";
@@ -9,9 +9,11 @@ import {
DialogActions, DialogActions,
DialogContent, DialogContent,
DialogContentText, DialogContentText,
FilledInput,
Grid, Grid,
OutlinedInput, OutlinedInput,
Paper, Paper,
TextField,
Tooltip, Tooltip,
Typography, Typography,
} from "@mui/material"; } from "@mui/material";
@@ -28,16 +30,21 @@ import InputLabel from "@mui/material/InputLabel";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import { AppBarBackOnly } from "@/components/appBar/backOnly.jsx"; import { AppBarBackOnly } from "@/components/appBar/backOnly.jsx";
import { createApi, useApiInContext } from "@/utils/store/api.js"; import { useApiInContext } from "@/utils/store/api.js";
import { getBrandingApi } from "@jellyfin/sdk/lib/utils/api/branding-api"; import { getBrandingApi } from "@jellyfin/sdk/lib/utils/api/branding-api";
import { getQuickConnectApi } from "@jellyfin/sdk/lib/utils/api/quick-connect-api"; import { getQuickConnectApi } from "@jellyfin/sdk/lib/utils/api/quick-connect-api";
import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api"; import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api";
import "./login.scss"; import "./login.scss";
import { queryClient } from "@/main.js";
import { setBackdrop } from "@/utils/store/backdrop.js"; import { setBackdrop } from "@/utils/store/backdrop.js";
import { blue } from "@mui/material/colors"; import { blue } from "@mui/material/colors";
import { createFileRoute, useNavigate } from "@tanstack/react-router"; import {
createFileRoute,
useNavigate,
useRouteContext,
useRouter,
useRouterState,
} from "@tanstack/react-router";
import { redirect } from "@tanstack/react-router"; import { redirect } from "@tanstack/react-router";
export const Route = createFileRoute("/_api/login/manual")({ export const Route = createFileRoute("/_api/login/manual")({
@@ -49,7 +56,11 @@ function UserLoginManual() {
const [quickConnectLoading, setQuickConnectLoading] = useState(-1); const [quickConnectLoading, setQuickConnectLoading] = useState(-1);
const [quickConnectCode, setQuickConnectCode] = useState(""); const [quickConnectCode, setQuickConnectCode] = useState("");
const [rememberMe, setRememberMe] = useState(true); const [rememberMe, setRememberMe] = useState(true);
const api = Route.useRouteContext().api; // console.log(Route.useRouteContext());
const api = useApiInContext((s) => s.api);
const createApi = useApiInContext((s) => s.createApi);
const router = useRouter();
const searchParams = Route.useSearch();
const server = useQuery({ const server = useQuery({
queryKey: ["login", "manual", "serverInfo"], queryKey: ["login", "manual", "serverInfo"],
@@ -61,14 +72,14 @@ function UserLoginManual() {
const navigate = useNavigate(); const navigate = useNavigate();
const { enqueueSnackbar } = useSnackbar(); const { enqueueSnackbar } = useSnackbar();
const [password, setPassword] = useState({ const [username, setUsername] = useState("");
const [password, setPassword] = useState<{
password: string | undefined;
showpass: boolean;
}>({
showpass: false, showpass: false,
password: "",
}); });
const [userName, setUserName] = useState("");
const handleUsername = (event) => {
setUserName(event.target.value);
};
const handlePassword = (prop) => (event) => { const handlePassword = (prop) => (event) => {
setPassword({ setPassword({
@@ -84,33 +95,34 @@ function UserLoginManual() {
}); });
}; };
const authUser = async () => { const handleLoginFn = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
try { try {
const auth = await api.authenticateUserByName( const authenticate = await api.authenticateUserByName(
userName, username,
password.password, password.password,
); );
return auth; createApi(api.basePath, authenticate.data?.AccessToken);
} catch (error) {
enqueueSnackbar("Incorrect Username or Password!", { if (rememberMe) await saveUser(username, authenticate.data.AccessToken);
variant: "error",
router.invalidate().finally(() => {
navigate({ to: searchParams.redirect || "/home", replace: true });
}); });
setLoading(false); } catch (err) {
console.error(error); console.error(err);
enqueueSnackbar(
"Unable to authenticate. Please check your username and password",
{ variant: "error" },
);
} }
return;
}; };
const handleLogin = async () => { const handleLogin = useMutation({
setLoading(true); mutationKey: ["login", "authenticate"],
const user = await authUser(); mutationFn: handleLoginFn,
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) => { const handleCheckRememberMe = (event) => {
setRememberMe(event.target.checked); setRememberMe(event.target.checked);
@@ -211,59 +223,28 @@ function UserLoginManual() {
return ( return (
<> <>
<AppBarBackOnly /> <AppBarBackOnly />
<Container <div className="login scrollY">
maxWidth="xs" <div
sx={{ className={`login-form-container ${
height: "100vh", server.data?.LoginDisclaimer && "padded-top"
display: "flex", }`}
justifyContent: "center",
alignItems: "center",
}}
> >
<Grid
container
spacing={2}
direction="column"
justifyContent="center"
alignItems="center"
sx={{
transition: "opacity 200ms",
width: "100%",
}}
>
<Grid sx={{ marginBottom: "1em" }}>
<Typography variant="h3" color="textPrimary"> <Typography variant="h3" color="textPrimary">
Login Login
</Typography> </Typography>
</Grid> <form className="login-form" onSubmit={(e) => handleLogin.mutate(e)}>
<Grid sx={{ width: "100%", mb: 1 }}> <TextField
<FormControl sx={{ width: "100%" }} variant="outlined">
<InputLabel htmlFor="user-name">Username:</InputLabel>
<OutlinedInput
fullWidth
id="user-name"
type="text"
variant="outlined" variant="outlined"
label="Username:" label="Username"
onChange={handleUsername} onChange={(e) => setUsername(e.currentTarget.value)}
/> />
</FormControl>
</Grid>
<Grid sx={{ width: "100%" }}>
<FormGroup>
<FormControl sx={{ width: "100%" }} variant="outlined"> <FormControl sx={{ width: "100%" }} variant="outlined">
<InputLabel htmlFor="user-password">Password:</InputLabel> <InputLabel htmlFor="user-password">Password:</InputLabel>
<OutlinedInput <OutlinedInput
fullWidth fullWidth
id="user-password" id="user-password"
type={password.showpass ? "text" : "password"} type={password.showpass ? "text" : "password"}
variant="outlined"
onChange={handlePassword("password")} onChange={handlePassword("password")}
onKeyUp={(event) => {
if (event.key === "Enter") {
handleLogin();
}
}}
label="Password:" label="Password:"
endAdornment={ endAdornment={
<InputAdornment position="end"> <InputAdornment position="end">
@@ -294,21 +275,14 @@ function UserLoginManual() {
} }
label="Remember me" label="Remember me"
/> />
</FormGroup>
</Grid>
<div <div
className="flex flex-column" className="flex flex-row"
style={{ width: "100%", gap: "0.4em" }} style={{ width: "100%", gap: "0.8em", flexWrap: "wrap" }}
> >
<LoadingButton <LoadingButton
variant="contained" variant="contained"
endIcon={ type="submit"
<span className="material-symbols-rounded">chevron_right</span> loading={handleLogin.isPending}
}
onClick={handleLogin}
loading={loading}
loadingPosition="end"
size="large"
sx={{ width: "100%" }} sx={{ width: "100%" }}
> >
Login Login
@@ -317,7 +291,7 @@ function UserLoginManual() {
onClick={handleQuickConnect} onClick={handleQuickConnect}
variant="contained" variant="contained"
className="userEventButton" className="userEventButton"
sx={{ width: "100%" }} style={{ flex: 1 }}
loading={quickConnectLoading === 1} loading={quickConnectLoading === 1}
// size="large" // size="large"
> >
@@ -328,12 +302,44 @@ function UserLoginManual() {
variant="contained" variant="contained"
className="userEventButton" className="userEventButton"
// size="large" // size="large"
sx={{ width: "100%" }} style={{ flex: 1 }}
onClick={() => navigate("/servers/list")} onClick={() => navigate("/servers/list")}
> >
Change Server Change Server
</Button> </Button>
</div> </div>
</form>
</div>
{server.isSuccess && server.data.LoginDisclaimer && (
<Paper
elevation={5}
style={{
marginTop: "1em",
padding: "1em",
borderRadius: "15px",
width: "32em",
}}
>
<div
className="flex flex-row flex-align-center"
style={{ gap: "0.5em", marginBottom: "0.5em" }}
>
<span
className="material-symbols-rounded"
style={{
color: blue[700],
"--fill": 1,
}}
>
info
</span>
Notice
</div>
<Typography variant="subtitle2" style={{ opacity: 0.8 }}>
{server.data.LoginDisclaimer}
</Typography>
</Paper>
)}
<Dialog open={Boolean(quickConnectCode)} fullWidth maxWidth="xs"> <Dialog open={Boolean(quickConnectCode)} fullWidth maxWidth="xs">
<DialogContent <DialogContent
style={{ style={{
@@ -410,39 +416,7 @@ function UserLoginManual() {
</Button> </Button>
</DialogActions> </DialogActions>
</Dialog> </Dialog>
<Grid sx={{ width: "100%" }}>
{server.isSuccess && server.data.LoginDisclaimer && (
<Paper
elevation={5}
style={{
marginTop: "1em",
padding: "1em",
borderRadius: "15px",
}}
>
<div
className="flex flex-row flex-align-center"
style={{ gap: "0.5em", marginBottom: "0.5em" }}
>
<span
className="material-symbols-rounded"
style={{
color: blue[700],
"--fill": 1,
}}
>
info
</span>
Notice
</div> </div>
<Typography variant="subtitle2" style={{ opacity: 0.8 }}>
{server.data.LoginDisclaimer}
</Typography>
</Paper>
)}
</Grid>
</Grid>
</Container>
</> </>
); );
} }
+1 -3
View File
@@ -59,7 +59,7 @@ import { useBackdropStore } from "@/utils/store/backdrop";
import IconLink from "@/components/iconLink"; import IconLink from "@/components/iconLink";
import EpisodeSkeleton from "@/components/skeleton/episode"; import EpisodeSkeleton from "@/components/skeleton/episode";
import { createFileRoute } from "@tanstack/react-router"; import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { Link } from "@tanstack/react-router"; import { Link } from "@tanstack/react-router";
function TabPanel(props) { function TabPanel(props) {
@@ -963,7 +963,6 @@ function SeriesTitlePage() {
) : ( ) : (
episodes.data.Items.map((episode, index) => { episodes.data.Items.map((episode, index) => {
return ( return (
<>
<motion.div <motion.div
key={episode.Id} key={episode.Id}
onClick={() => navigate(`/episode/${episode.Id}`)} onClick={() => navigate(`/episode/${episode.Id}`)}
@@ -1111,7 +1110,6 @@ function SeriesTitlePage() {
/> />
</div> </div>
</motion.div> </motion.div>
</>
); );
}) })
)} )}
+14 -66
View File
@@ -15,7 +15,12 @@ import {
CircularProgress, CircularProgress,
Typography, Typography,
} from "@mui/material"; } from "@mui/material";
import { Outlet, createFileRoute, useNavigate } from "@tanstack/react-router"; import {
Outlet,
createFileRoute,
redirect,
useNavigate,
} from "@tanstack/react-router";
import axios from "axios"; import axios from "axios";
import { AnimatePresence, motion } from "framer-motion"; import { AnimatePresence, motion } from "framer-motion";
import * as React from "react"; import * as React from "react";
@@ -29,79 +34,22 @@ type LoaderData = {
}; };
export const Route = createFileRoute("/")({ export const Route = createFileRoute("/")({
component: Index,
errorComponent: (error) => { errorComponent: (error) => {
console.error(error.error); console.error(error.error);
}, },
beforeLoad: async ({ context, navigate }) => { beforeLoad: async ({ context, navigate }) => {
const api = context.api;
const serversOnDisk = await getAllServers();
const currentServerId = await getDefaultServer(); const currentServerId = await getDefaultServer();
const currentServer = await getServer(currentServerId); const currentServer = await getServer(currentServerId);
const userOnDisk = await getUser(); const userOnDisk = await getUser();
const createApi = context.createApi; if (currentServerId) {
context.createApi(currentServer?.address, undefined);
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) { if (userOnDisk) {
// setStatus( context.createApi(currentServer?.address, userOnDisk.AccessToken);
// `User found! throw redirect({ to: "/home/" });
// Trying to authenticate user...`, }
// ); throw redirect({ to: "/login/" });
}
createApi(currentServer.address, userOnDisk.AccessToken); throw redirect({ to: "/setup/server/add" });
// 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 <h1>Loading...</h1>;
}
+6
View File
@@ -0,0 +1,6 @@
import { createFileRoute } from "@tanstack/react-router";
import React from "react";
export const Route = createFileRoute("/setup/server/error")({
component: () => <div>Hello /setup/server/error!</div>,
});
+8 -16
View File
@@ -1,5 +1,5 @@
import { type Api, Jellyfin } from "@jellyfin/sdk"; import { type Api, Jellyfin } from "@jellyfin/sdk";
import React, { createContext, useContext, useRef } from "react"; import React, { createContext, useContext, useRef, useState } from "react";
import { type StoreApi, createStore, useStore } from "zustand"; import { type StoreApi, createStore, useStore } from "zustand";
import { version as appVer } from "../../../package.json"; import { version as appVer } from "../../../package.json";
@@ -55,27 +55,19 @@ export const jellyfin = new Jellyfin({
const ApiContext = createContext(null); const ApiContext = createContext(null);
export const ApiProvider = ({ children }) => { export const ApiProvider = ({ children }) => {
const storeRef = useRef<StoreApi<ApiStore>>(); const [store] = useState(() =>
createStore<ApiStore>()((set) => ({
if (!storeRef.current) {
storeRef.current = createStore<ApiStore>()((set) => ({
api: undefined, api: undefined,
deviceId: deviceId, deviceId: deviceId,
jellyfin: jellyfin, jellyfin: jellyfin,
createApi: async (serverAddress, accessToken?) => { createApi: (serverAddress, accessToken?) =>
set((state) => ({ set((state) => ({
...state, ...state,
api: jellyfin.createApi(serverAddress, accessToken, axiosClient), api: jellyfin.createApi(serverAddress, accessToken, axiosClient),
})); })),
await Promise.resolve(); })),
}, )
})); return <ApiContext.Provider value={store}>{children}</ApiContext.Provider>;
}
return (
<ApiContext.Provider value={storeRef.current}>
{children}
</ApiContext.Provider>
);
}; };
export function useApiInContext<T>(selector?: (state: ApiStore) => T) { export function useApiInContext<T>(selector?: (state: ApiStore) => T) {