refactor: improve server add process

This commit is contained in:
Prayag Prajapati committed 2024-12-10 23:06:50 +05:30
1 parent 7d2659f32b
commit af8dec5844
8 files changed
+279 -138

No files matched your search

+135
View File
@@ -0,0 +1,135 @@
import { setServer } from "@/utils/storage/servers";
import { jellyfin } from "@/utils/store/api";
import { LoadingButton } from "@mui/lab";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
TextField,
} from "@mui/material";
import { useMutation } from "@tanstack/react-query";
import { enqueueSnackbar } from "notistack";
import React, { useState } from "react";
type AddServerDialogProps = {
open: boolean;
setAddServerDialog: (value: boolean) => void;
sideEffect?: () => Promise<unknown>;
hideBackdrop?: boolean;
};
export default function AddServerDialog(props: AddServerDialogProps) {
const { open, setAddServerDialog, sideEffect, hideBackdrop } = props;
const [serverIp, setServerIp] = useState("");
const addServer = useMutation({
mutationKey: ["add-server"],
mutationFn: async () => {
const servers =
await jellyfin.discovery.getRecommendedServerCandidates(serverIp);
const bestServer = jellyfin.discovery.findBestServer(servers);
return bestServer;
},
onSuccess: async (bestServer) => {
if (bestServer) {
await setServer(bestServer.systemInfo?.Id ?? "", bestServer);
setAddServerDialog(false);
enqueueSnackbar(
"Client added successfully. You might need to refresh client list.",
{
variant: "success",
},
);
if (sideEffect) {
await sideEffect();
}
}
},
onError: (err) => {
console.error(err);
enqueueSnackbar(`${err}`, { variant: "error" });
enqueueSnackbar("Something went wrong", { variant: "error" });
},
onSettled: async (bestServer) => {
if (!bestServer) {
enqueueSnackbar("Provided server address is not a Jellyfin server.", {
variant: "error",
});
}
},
});
return (
<Dialog
open={open}
hideBackdrop={Boolean(hideBackdrop)}
fullWidth
maxWidth="sm"
disableScrollLock={true}
>
<DialogTitle variant="h4" align="center" mb={1}>
Add Server
</DialogTitle>
<DialogContent className="settings-server-add">
<TextField
variant="filled"
label="Address"
fullWidth
onChange={(e) => setServerIp(e.target.value)}
/>
</DialogContent>
<DialogActions
style={{
alignItems: "center",
justifyContent: "center",
padding: "1em",
gap: "1em",
}}
>
<Button
variant="contained"
startIcon={
<span
className="material-symbols-rounded"
style={{
marginRight: "0.25em",
fontVariationSettings:
'"FILL" 1, "wght" 300, "GRAD" 25, "opsz" 40',
}}
>
cancel
</span>
}
color="error"
onClick={() => setAddServerDialog(false)}
>
Close
</Button>
{/* @ts-ignore */}
<LoadingButton
startIcon={
<span
className="material-symbols-rounded"
style={{
marginRight: "0.25em",
fontVariationSettings:
'"FILL" 1, "wght" 300, "GRAD" 25, "opsz" 40',
}}
>
add_circle
</span>
}
variant="contained"
loading={addServer.isPending}
loadingPosition="start"
onClick={addServer.mutate}
color="success"
>
Add
</LoadingButton>
</DialogActions>
</Dialog>
);
}
+14 -9
View File
@@ -1,17 +1,20 @@
import AppBar from "@mui/material/AppBar"; import AppBar from "@mui/material/AppBar";
import IconButton from "@mui/material/IconButton"; import IconButton from "@mui/material/IconButton";
import Toolbar from "@mui/material/Toolbar"; import Toolbar from "@mui/material/Toolbar";
import { useRouter } from "@tanstack/react-router"; import { useLocation, useRouter } from "@tanstack/react-router";
import React from "react"; import React from "react";
import QuickConnectButton from "../buttons/quickConnectButton"; import QuickConnectButton from "../buttons/quickConnectButton";
export default function AppBarBackOnly() { export default function AppBarBackOnly() {
const { history } = useRouter(); const { history } = useRouter();
const location = useLocation();
const handleBack = () => { const handleBack = () => {
history.go(-1); history.go(-1);
}; };
const hideQuickConnect = location.pathname === "/setup/server/list";
return ( return (
<AppBar elevation={0} color="transparent" position="fixed"> <AppBar elevation={0} color="transparent" position="fixed">
<Toolbar> <Toolbar>
@@ -27,14 +30,16 @@ export default function AppBarBackOnly() {
> >
<span className="material-symbols-rounded">arrow_back</span> <span className="material-symbols-rounded">arrow_back</span>
</IconButton> </IconButton>
<QuickConnectButton {!hideQuickConnect && (
sx={{ <QuickConnectButton
marginLeft: "auto", sx={{
flex: "none !important", marginLeft: "auto",
borderRadius: "10px", flex: "none !important",
}} borderRadius: "10px",
color="secondary" }}
/> color="secondary"
/>
)}
</Toolbar> </Toolbar>
</AppBar> </AppBar>
); );
+10 -14
View File
@@ -21,7 +21,7 @@ import { skipToken, useMutation, useQuery } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router"; import { useNavigate } from "@tanstack/react-router";
import { writeText } from "@tauri-apps/plugin-clipboard-manager"; import { writeText } from "@tauri-apps/plugin-clipboard-manager";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import React, { useState } from "react"; import React, { useCallback, useState } from "react";
const Transition = React.forwardRef(function Transition( const Transition = React.forwardRef(function Transition(
props: TransitionProps & { props: TransitionProps & {
@@ -141,7 +141,13 @@ const QuickConnectButton = (props: LoadingButtonProps) => {
}, },
}); });
const handleQuickConnectClose = useCallback(() => {
setQuickConnectCode(null);
setCheckForQuickConnect(false);
initQuickConnect.reset();
checkQuickConnectStatus.reset();
}, []);
useInterval( useInterval(
() => { () => {
if (quickConnectSecret) { if (quickConnectSecret) {
@@ -175,12 +181,7 @@ const QuickConnectButton = (props: LoadingButtonProps) => {
</LoadingButton> </LoadingButton>
<Dialog <Dialog
open={Boolean(quickConnectCode)} open={Boolean(quickConnectCode)}
onClose={() => { onClose={handleQuickConnectClose}
setQuickConnectCode(null);
setCheckForQuickConnect(false);
initQuickConnect.reset();
checkQuickConnectStatus.reset();
}}
fullWidth fullWidth
maxWidth="xs" maxWidth="xs"
TransitionComponent={Transition} TransitionComponent={Transition}
@@ -249,12 +250,7 @@ const QuickConnectButton = (props: LoadingButtonProps) => {
} }
label="Remember device" label="Remember device"
/> />
<Button <Button variant="contained" onClick={handleQuickConnectClose}>
variant="contained"
onClick={() => {
setQuickConnectCode(null);
}}
>
Close Close
</Button> </Button>
</DialogActions> </DialogActions>
+2 -2
View File
@@ -204,12 +204,12 @@ function UserLoginManual() {
</div> </div>
{server.isSuccess && server.data?.LoginDisclaimer && ( {server.isSuccess && server.data?.LoginDisclaimer && (
<Paper <Paper
elevation={5} elevation={0}
style={{ style={{
marginTop: "1em", marginTop: "1em",
padding: "1em", padding: "1em",
borderRadius: "15px", borderRadius: "15px",
width: "32em", width: "28em",
}} }}
> >
<div <div
+11 -2
View File
@@ -1036,7 +1036,13 @@ function VideoPlayer() {
{playing ? "pause" : "play_arrow"} {playing ? "pause" : "play_arrow"}
</span> </span>
</IconButton> </IconButton>
<IconButton onClick={handleNextChapter}> <IconButton
disabled={
(item?.Chapters?.[item.Chapters?.length - 1]
?.StartPositionTicks ?? 0) <= progress
}
onClick={handleNextChapter}
>
<span className="material-symbols-rounded fill"> <span className="material-symbols-rounded fill">
last_page last_page
</span> </span>
@@ -1114,7 +1120,10 @@ function VideoPlayer() {
</span> </span>
</IconButton> </IconButton>
<QueueButton /> <QueueButton />
<IconButton onClick={handleShowChapterList}> <IconButton
disabled={item?.Chapters?.length === 0}
onClick={handleShowChapterList}
>
<span className="material-symbols-rounded">list</span> <span className="material-symbols-rounded">list</span>
</IconButton> </IconButton>
<Menu <Menu
+67 -86
View File
@@ -1,11 +1,9 @@
import React, { useState } from "react"; import React, { type FormEvent, useState } from "react";
import { setDefaultServer, setServer } from "@/utils/storage/servers"; import { setDefaultServer, setServer } from "@/utils/storage/servers";
import LoadingButton from "@mui/lab/LoadingButton"; import LoadingButton from "@mui/lab/LoadingButton";
import Container from "@mui/material/Container";
import Grid from "@mui/material/Grid"; import Grid from "@mui/material/Grid";
import LinearProgress from "@mui/material/LinearProgress";
import TextField from "@mui/material/TextField"; import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
@@ -28,17 +26,18 @@ function ServerSetup() {
const { enqueueSnackbar } = useSnackbar(); const { enqueueSnackbar } = useSnackbar();
const navigate = useNavigate({ from: "/setup/server/add" }); const navigate = useNavigate();
const checkServer = useMutation({ const checkServer = useMutation({
mutationFn: async () => { mutationFn: async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const servers = const servers =
await jellyfin.discovery.getRecommendedServerCandidates(serverIp); await jellyfin.discovery.getRecommendedServerCandidates(serverIp);
const bestServer = jellyfin.discovery.findBestServer(servers); const bestServer = jellyfin.discovery.findBestServer(servers);
return bestServer; return bestServer;
}, },
onSuccess: (bestServer) => { onSuccess: (bestServer) => {
if (bestServer) { if (bestServer?.systemInfo?.Id) {
createApi(bestServer.address, undefined); createApi(bestServer.address, undefined);
setDefaultServer(bestServer.systemInfo?.Id); setDefaultServer(bestServer.systemInfo?.Id);
@@ -48,12 +47,12 @@ function ServerSetup() {
variant: "success", variant: "success",
}); });
navigate({ to: "/login" }); navigate({ to: "/login", replace: true });
} }
}, },
onError: (err) => { onError: (err) => {
console.error(err); console.error(err);
enqueueSnackbar(`${err}`, { variant: "error" }); enqueueSnackbar(`${JSON.stringify(err)}`, { variant: "error" });
enqueueSnackbar("Something went wrong", { variant: "error" }); enqueueSnackbar("Something went wrong", { variant: "error" });
}, },
onSettled: (bestServer) => { onSettled: (bestServer) => {
@@ -67,87 +66,69 @@ function ServerSetup() {
}); });
return ( return (
<> <div
<LinearProgress className={"centered serverContainer flex flex-column flex-center"}
style={{
opacity: checkServer.isPending ? "0.5" : "1",
transition: "opacity 350ms",
width: "40vw",
}}
>
<div style={{ marginBottom: "1em" }}>
<Typography variant="h3">Add Server</Typography>
</div>
<form
onSubmit={(e) => checkServer.mutate(e)}
className="flex flex-column"
style={{ gap: "1em", width: "100%" }}
>
<TextField
className="textbox"
label="Server Address:"
variant="outlined"
// inputRef={serverIp}
onChange={(event) => {
setServerIp(event.target.value);
}}
/>
<LoadingButton
variant="contained"
sx={{ width: "100%" }}
size="large"
loading={checkServer.isPending}
endIcon={
<span className="material-symbols-rounded">chevron_right</span>
}
loadingPosition="end"
type="submit"
>
Add Server
</LoadingButton>
</form>
<Grid
item
xl={5}
md={6}
sx={{ sx={{
position: "fixed", width: "100%",
top: 0, display: "flex",
left: 0, alignItems: "center",
right: 0, gap: 1,
opacity: checkServer.isPending ? 1 : 0, opacity: 0.6,
transition: "opacity 350ms",
}}
/>
<Container
maxWidth="sm"
className={"centered serverContainer"}
style={{
opacity: checkServer.isPending ? "0.5" : "1",
transition: "opacity 350ms",
}} }}
> >
<Grid <span
container className="material-symbols-rounded"
spacing={2} style={{
direction="column" color: yellow[700],
justifyContent="center" }}
alignItems="center"
> >
<Grid item xl={5} md={6} sx={{ marginBottom: "1em" }}> info
<Typography variant="h3">Add Server</Typography> </span>
</Grid> <Typography variant="subtitle1">
<Grid item xl={5} md={6} sx={{ width: "100%" }}> Example: https://demo.jellyfin.org/stable
<TextField </Typography>
className="textbox" </Grid>
label="Server Address:" </div>
variant="outlined"
// inputRef={serverIp}
onChange={(event) => {
setServerIp(event.target.value);
}}
/>
</Grid>
<Grid item xl={5} md={6} sx={{ width: "100%" }}>
<LoadingButton
variant="contained"
sx={{ width: "100%" }}
size="large"
loading={checkServer.isPending}
endIcon={
<span className="material-symbols-rounded">chevron_right</span>
}
loadingPosition="end"
onClick={checkServer.mutate}
>
Add Server
</LoadingButton>
</Grid>
<Grid
item
xl={5}
md={6}
sx={{
width: "100%",
display: "flex",
alignItems: "center",
gap: 1,
opacity: 0.6,
}}
>
<span
className="material-symbols-rounded"
style={{
color: yellow[700],
}}
>
info
</span>
<Typography variant="subtitle1">
Example: https://demo.jellyfin.org/stable
</Typography>
</Grid>
</Grid>
</Container>
</>
); );
} }
+36 -24
View File
@@ -8,17 +8,23 @@ import { red } from "@mui/material/colors";
import AppBarBackOnly from "@/components/appBar/backOnly"; import AppBarBackOnly from "@/components/appBar/backOnly";
import { import {
type ServerInfo,
delServer, delServer,
getAllServers, getAllServers,
getDefaultServer, getDefaultServer,
setDefaultServer, setDefaultServer,
} from "@/utils/storage/servers"; } from "@/utils/storage/servers";
import { delUser } from "@/utils/storage/user"; import { delUser } from "@/utils/storage/user";
import { setBackdrop } from "@/utils/store/backdrop"; import { useBackdropStore } from "@/utils/store/backdrop";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { createFileRoute, useNavigate } from "@tanstack/react-router"; import {
createFileRoute,
useNavigate,
useRouter,
} from "@tanstack/react-router";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import "./serverList.scss"; import "./serverList.scss";
import AddServerDialog from "@/components/addServerDialog";
import { useApiInContext } from "@/utils/store/api"; import { useApiInContext } from "@/utils/store/api";
export const Route = createFileRoute("/setup/server/list")({ export const Route = createFileRoute("/setup/server/list")({
@@ -27,8 +33,8 @@ export const Route = createFileRoute("/setup/server/list")({
function ServerList() { function ServerList() {
const navigate = useNavigate(); const navigate = useNavigate();
const [serverState, setServerState] = useState(null);
const { enqueueSnackbar } = useSnackbar(); const { enqueueSnackbar } = useSnackbar();
const router = useRouter();
const createApi = useApiInContext((s) => s.createApi); const createApi = useApiInContext((s) => s.createApi);
@@ -45,12 +51,12 @@ function ServerList() {
}); });
const handleServerChange = useMutation({ const handleServerChange = useMutation({
mutationFn: async () => { mutationFn: async (server: ServerInfo) => {
await delUser(); await delUser();
await setDefaultServer(serverState.id); await setDefaultServer(server.id);
queryClient.clear(); queryClient.clear();
await defaultServer.refetch(); await defaultServer.refetch();
createApi(serverState.address, undefined); createApi(server.address, undefined);
queryClient.removeQueries(); queryClient.removeQueries();
}, },
onSuccess: async () => { onSuccess: async () => {
@@ -64,19 +70,21 @@ function ServerList() {
}, },
}); });
const handleDelete = async (server) => { const handleDelete = async (server: ServerInfo) => {
await delServer(server.id); await delServer(server.id);
if (server.id === defaultServer.data) { if (server.id === defaultServer.data) {
await delUser(); await delUser();
await servers.refetch(); await servers.refetch();
if (servers.length > 1) { if ((servers.data?.length ?? 0) > 1) {
setDefaultServer(servers.data?.[0].id); if (servers.data?.[0].id) {
createApi(servers.data?.[0].address, undefined); setDefaultServer(servers.data?.[0].id);
createApi(servers.data?.[0].address, undefined);
}
} else { } else {
await setDefaultServer(null); await setDefaultServer(null);
// TODO: reset api in context here await router.invalidate();
} }
queryClient.removeQueries(); queryClient.removeQueries();
navigate({ to: "/" }); navigate({ to: "/" });
@@ -87,10 +95,14 @@ function ServerList() {
await defaultServer.refetch(); await defaultServer.refetch();
}; };
const setBackdrop = useBackdropStore((state) => state.setBackdrop);
useLayoutEffect(() => { useLayoutEffect(() => {
setBackdrop("", ""); setBackdrop("", "");
}, []); }, []);
const [addServerDialog, setAddServerDialog] = useState(false);
return ( return (
<div className="server-list"> <div className="server-list">
<AppBarBackOnly /> <AppBarBackOnly />
@@ -110,15 +122,20 @@ function ServerList() {
style={{ style={{
fontSize: "1.64em", fontSize: "1.64em",
}} }}
onClick={() => navigate({ to: "/setup/server/add" })} onClick={() => setAddServerDialog(true)}
> >
<div className="material-symbols-rounded">add</div> <div className="material-symbols-rounded">add</div>
</IconButton> </IconButton>
<AddServerDialog
open={addServerDialog}
sideEffect={() => servers.refetch()}
setAddServerDialog={setAddServerDialog}
/>
</div> </div>
<Paper className="server-list-container"> <Paper className="server-list-container">
{servers.isSuccess && {servers.isSuccess &&
servers.data.map((server, index) => ( servers.data.map((server) => (
<div key={index} className="server-list-item"> <div key={server.id} className="server-list-item">
<div className="material-symbols-rounded server-list-item-icon"> <div className="material-symbols-rounded server-list-item-icon">
dns dns
</div> </div>
@@ -131,15 +148,11 @@ function ServerList() {
alignItems: "center", alignItems: "center",
}} }}
> >
{server.systemInfo.ServerName} {server.systemInfo?.ServerName}
{server.id === defaultServer.data && ( {server.id === defaultServer.data && (
<Chip <Chip
label={ label={
<Typography <Typography variant="caption" fontWeight={700}>
variant="caption"
fontWeight={600}
fontFamily="JetBrains Mono Variable"
>
Current Current
</Typography> </Typography>
} }
@@ -148,7 +161,7 @@ function ServerList() {
ml: 2, ml: 2,
width: "5.4em", width: "5.4em",
}} }}
size="medium" size="small"
/> />
)} )}
</Typography> </Typography>
@@ -168,7 +181,7 @@ function ServerList() {
}} }}
fontWeight={300} fontWeight={300}
> >
Version: {server.systemInfo.Version} Version: {server.systemInfo?.Version}
</Typography> </Typography>
</div> </div>
<div className="server-list-item-buttons"> <div className="server-list-item-buttons">
@@ -177,8 +190,7 @@ function ServerList() {
fontSize: "1.64em", fontSize: "1.64em",
}} }}
onClick={() => { onClick={() => {
setServerState(server); handleServerChange.mutate(server);
handleServerChange.mutate();
}} }}
disabled={handleServerChange.isPending} disabled={handleServerChange.isPending}
> >
+4 -1
View File
@@ -15,7 +15,10 @@ const store = await load(".servers.dat", { autoSave: true });
/** /**
* Set server in .servers.dat * Set server in .servers.dat
*/ */
export const setServer = async (serverId: string, serverInfo: ServerInfo) => { export const setServer = async (
serverId: string,
serverInfo: RecommendedServerInfo,
) => {
const servers = await getAllServers(); const servers = await getAllServers();
const newServers = servers.filter((server) => server.id !== serverId); const newServers = servers.filter((server) => server.id !== serverId);