chore(app): cleanup main files

This commit is contained in:
DanCodes committed 2024-01-09 13:18:54 +00:00
1 parent 5bb89c1b08
commit d3b367b948
15 files changed
+427 -408

No files matched your search

+3 -1
View File
@@ -9,5 +9,7 @@
}, },
"[json]": { "[json]": {
"editor.defaultFormatter": "biomejs.biome" "editor.defaultFormatter": "biomejs.biome"
} },
"rust-analyzer.linkedProjects": ["./src-tauri/Cargo.toml"],
"typescript.tsdk": "node_modules/typescript/lib"
} }
+23 -17
View File
@@ -1,19 +1,25 @@
{ {
"$schema": "https://biomejs.dev/schemas/1.5.0/schema.json", "$schema": "https://biomejs.dev/schemas/1.5.0/schema.json",
"organizeImports": { "organizeImports": {
"enabled": true "enabled": true
}, },
"linter": { "linter": {
"enabled": true, "enabled": true,
"rules": { "rules": {
"recommended": true, "recommended": true,
"style": { "style": {
"noNonNullAssertion": "off" "noNonNullAssertion": "off"
} }
} }
}, },
"files": { "files": {
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.js", "*.json"], "include": [
"ignoreUnknown": true "src/**/*.ts",
} "src/**/*.tsx",
"src/**/*.jsx",
"src/**/*.js",
"*.json"
],
"ignoreUnknown": true
}
} }
+1 -1
View File
@@ -18,7 +18,7 @@ tauri-build = { version = "1.5.1", features = [] }
log = "^0.4.20" log = "^0.4.20"
serde_json = "1.0" serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.5.4", features = [ "updater", "http-all", "devtools", "process-exit", "process-relaunch", "shell-all", "window-set-fullscreen", "http-all"] } tauri = { version = "1.5.4", features = [ "path-all", "updater", "http-all", "devtools", "process-exit", "process-relaunch", "shell-all", "window-set-fullscreen", "http-all"] }
tauri-plugin-store = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" } tauri-plugin-store = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" }
tauri-plugin-localhost = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" } tauri-plugin-localhost = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" }
tauri-plugin-log = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1", features = ["colored"] } tauri-plugin-log = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1", features = ["colored"] }
+3
View File
@@ -28,6 +28,9 @@
"all": true, "all": true,
"request": true, "request": true,
"scope": ["http://**", "http://*", "https://**", "https://*"] "scope": ["http://**", "http://*", "https://**", "https://*"]
},
"path": {
"all": true
} }
}, },
"bundle": { "bundle": {
+227 -341
View File
@@ -1,7 +1,5 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import useKonami from "react-use-konami";
import { ThemeProvider } from "@mui/material/styles"; import { ThemeProvider } from "@mui/material/styles";
import { AnimatePresence, motion } from "framer-motion"; import { AnimatePresence, motion } from "framer-motion";
import { SnackbarProvider } from "notistack"; import { SnackbarProvider } from "notistack";
@@ -20,8 +18,6 @@ import {
installUpdate, installUpdate,
} from "@tauri-apps/api/updater"; } from "@tauri-apps/api/updater";
import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api";
// Theming // Theming
import CssBaseline from "@mui/material/CssBaseline"; import CssBaseline from "@mui/material/CssBaseline";
import "./styles/global.scss"; import "./styles/global.scss";
@@ -52,7 +48,7 @@ import FavoritePage from "./routes/favorite/index.jsx";
import Home from "./routes/home"; import Home from "./routes/home";
import ItemDetail from "./routes/item"; import ItemDetail from "./routes/item";
import LibraryView from "./routes/library"; import LibraryView from "./routes/library";
import { LoginWithImage, UserLogin, UserLoginManual } from "./routes/login"; import { LoginRoute, LoginWithImage, UserLogin, UserLoginManual } from "./routes/login";
import PersonTitlePage from "./routes/person/index.jsx"; import PersonTitlePage from "./routes/person/index.jsx";
import { VideoPlayer } from "./routes/player/videoPlayer.jsx"; import { VideoPlayer } from "./routes/player/videoPlayer.jsx";
import PlaylistTitlePage from "./routes/playlist/index.jsx"; import PlaylistTitlePage from "./routes/playlist/index.jsx";
@@ -93,7 +89,6 @@ import { ErrorNotice } from "./components/notices/errorNotice/errorNotice.jsx";
import AudioPlayer from "./components/playback/audioPlayer/index.jsx"; import AudioPlayer from "./components/playback/audioPlayer/index.jsx";
// Utils // Utils
import { useApi } from "./utils/store/api";
import { useAudioPlayback } from "./utils/store/audioPlayback.js"; import { useAudioPlayback } from "./utils/store/audioPlayback.js";
import { useBackdropStore } from "./utils/store/backdrop.js"; import { useBackdropStore } from "./utils/store/backdrop.js";
import { useCentralStore } from "./utils/store/central.js"; import { useCentralStore } from "./utils/store/central.js";
@@ -101,45 +96,12 @@ import { usePlaybackDataLoadStore } from "./utils/store/playback.js";
// 3rd Party // 3rd Party
import { CircularProgress } from "@mui/material"; import { CircularProgress } from "@mui/material";
import { useQuery } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import { ErrorBoundary } from "react-error-boundary"; import { ErrorBoundary } from "react-error-boundary";
import { EasterEgg } from "./components/utils/easterEgg.jsx";
const LoginRoute = () => { import { useKonamiEasterEgg } from "./utils/misc/konami";
const navigate = useNavigate(); import { handleRelaunch } from "./utils/misc/relaunch";
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 (
<div
style={{
position: "fixed",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
}}
>
<CircularProgress size={72} thickness={1.4} />
</div>
);
};
// const anim = { // const anim = {
// initial: { // initial: {
@@ -173,71 +135,35 @@ const LoginRoute = () => {
// ); // );
// }; // };
// const unlisten = await onUpdaterEvent(({ error, status }) => {
// // This will log all updater events, including status updates and errors.
// console.log("Updater event", error, status);
// });
// // you need to call unlisten if your handler goes out of scope, for example if the component is unmounted.
// unlisten();
function App() { function App() {
const [audioPlayerVisible] = useAudioPlayback((state) => [state.display]);
const [easterEgg, setEasterEgg] = useKonamiEasterEgg();
const { enqueueSnackbar } = useSnackbar();
const [initialRoute] = useCentralStore((state) => [state.initialRoute]);
const [backdropUrl, backdropId] = useBackdropStore((state) => [
state.backdropUrl,
state.backdropId,
]);
const [playbackDataLoading] = usePlaybackDataLoadStore((state) => [ const [playbackDataLoading] = usePlaybackDataLoadStore((state) => [
state.isPending, state.isPending,
]); ]);
const handleRelaunch = async (_event: unknown, reason?: string) => {
if (reason && reason === "backdropClick") {
return;
}
await relaunch();
};
const location = useLocation(); 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<UpdateManifest | undefined>(
undefined,
);
// biome-ignore lint/correctness/useExhaustiveDependencies: this dependency is required // biome-ignore lint/correctness/useExhaustiveDependencies: this dependency is required
useEffect(() => { useEffect(() => {
window.scrollTo(0, 0); window.scrollTo(0, 0);
}, [location.key]); }, [location.key]);
const [audioPlayerVisible] = useAudioPlayback((state) => [state.display]);
const [backdropUrl, backdropId] = useBackdropStore((state) => [
state.backdropUrl,
state.backdropId,
]);
const [backdropLoading, setBackdropLoading] = useState(true);
const [easterEgg, setEasterEgg] = useState(false);
const sixtyNine = () => {
setEasterEgg(true);
};
useKonami(sixtyNine, {
code: [
"ArrowUp",
"ArrowUp",
"ArrowDown",
"ArrowDown",
"ArrowLeft",
"ArrowRight",
"ArrowLeft",
"ArrowRight",
"b",
"a",
],
});
const { enqueueSnackbar } = useSnackbar();
const [updateDialog, setUpdateDialog] = useState(false);
const [updateInfo, setUpdateInfo] = useState<UpdateManifest | undefined>(
undefined,
);
const [updateDialogButton, setUpdateDialogButton] = useState(false);
useEffect(() => { useEffect(() => {
async function checkForUpdates() { async function checkForUpdates() {
try { try {
@@ -246,26 +172,16 @@ function App() {
if (shouldUpdate) { if (shouldUpdate) {
setUpdateInfo(manifest); setUpdateInfo(manifest);
setUpdateDialog(true); setUpdateDialog(true);
// You could show a dialog asking the user if they want to install the update here.
console.log(`Update found : ${manifest?.version}, ${manifest?.date}`); console.log(`Update found : ${manifest?.version}, ${manifest?.date}`);
// Install the update. This will also restart the app on Windows!
// await installUpdate();
// On macOS and Linux you will need to restart the app manually.
// You could use this step to display another confirmation dialog.
// await relaunch();
} }
} catch (error) { } catch (error) {
console.error(error); console.error(error);
} }
} }
checkForUpdates(); checkForUpdates();
}, []); });
const [initialRoute] = useCentralStore((state) => [state.initialRoute]);
const navigate = useNavigate();
if (!initialRoute) { if (!initialRoute) {
return ( return (
<div <div
@@ -280,250 +196,220 @@ function App() {
</div> </div>
); );
} }
if (initialRoute) {
return ( return (
<SnackbarProvider maxSnack={5}> <SnackbarProvider maxSnack={5}>
<ThemeProvider theme={theme}> <ThemeProvider theme={theme}>
{playbackDataLoading && ( {playbackDataLoading && (
<LinearProgress <LinearProgress
sx={{ sx={{
position: "fixed", position: "fixed",
top: 0, top: 0,
left: 0, left: 0,
right: 0, right: 0,
width: "100vw", width: "100vw",
zIndex: 100000, zIndex: 100000,
}} }}
/> />
)} )}
<Dialog <Dialog
// open={true} // open={true}
open={updateDialog} open={updateDialog}
// onClose={} // onClose={}
// maxWidth="md" // maxWidth="md"
fullWidth fullWidth
> >
{updateInfo !== undefined && ( {updateInfo !== undefined && (
<> <>
<DialogTitle> <DialogTitle>
Update Available! Update Available!
<Typography <Typography
style={{
opacity: "0.5",
}}
>
v{updateInfo.version}
</Typography>
</DialogTitle>
<DialogContent dividers>
<DialogContentText>
<Markdown>{updateInfo.body}</Markdown>
</DialogContentText>
</DialogContent>
<DialogActions
style={{ style={{
padding: "1em", opacity: "0.5",
}} }}
> >
<IconButton disabled={updateDialogButton}> v{updateInfo.version}
<SvgIcon> </Typography>
<svg </DialogTitle>
xmlns="http://www.w3.org/2000/svg" <DialogContent dividers>
width="16" <DialogContentText>
height="16" <Markdown>{updateInfo.body}</Markdown>
fill="currentColor" </DialogContentText>
viewBox="0 0 16 16" </DialogContent>
> <DialogActions
<title>Update</title> style={{
<path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.012 8.012 0 0 0 16 8c0-4.42-3.58-8-8-8" /> padding: "1em",
</svg> }}
</SvgIcon> >
</IconButton> <IconButton disabled={updateDialogButton}>
<Button <SvgIcon>
size="large" <svg
color="error" xmlns="http://www.w3.org/2000/svg"
variant="outlined" width="16"
disabled={updateDialogButton} height="16"
onClick={() => setUpdateDialog(false)} fill="currentColor"
> viewBox="0 0 16 16"
close >
</Button> <title>Update</title>
<LoadingButton <path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.012 8.012 0 0 0 16 8c0-4.42-3.58-8-8-8" />
size="large" </svg>
color="success" </SvgIcon>
variant="contained" </IconButton>
loading={updateDialogButton} <Button
loadingIndicator="Updating..." size="large"
onClick={async () => { color="error"
setUpdateDialogButton(true); variant="outlined"
await installUpdate(); disabled={updateDialogButton}
enqueueSnackbar( onClick={() => setUpdateDialog(false)}
"Update has been installed! You need to relaunch JellyPlayer.", >
{ close
variant: "success", </Button>
}, <LoadingButton
); size="large"
await relaunch(); color="success"
}} variant="contained"
> loading={updateDialogButton}
Update loadingIndicator="Updating..."
</LoadingButton> onClick={async () => {
</DialogActions> setUpdateDialogButton(true);
</> await installUpdate();
)} enqueueSnackbar(
</Dialog> "Update has been installed! You need to relaunch JellyPlayer.",
<Dialog {
open={easterEgg} variant: "success",
onClose={() => setEasterEgg(false)} },
sx={{ );
background: "black", await relaunch();
}} }}
> >
<iframe Update
width="560" </LoadingButton>
height="315" </DialogActions>
src="https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1&disablekb=1" </>
title="EasterEgg" )}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" </Dialog>
/> <EasterEgg />
</Dialog>
<Slide direction="up" in={easterEgg} mountOnEnter unmountOnExit> {/* Show Dialog if server not reachable */}
<img
src="https://i.gifer.com/PYh.gif" <div className="app-backdrop-container">
width={320} <AnimatePresence>
height={320} <motion.img
alt="nyan cat gif" key={backdropId}
src={backdropUrl}
alt=""
className="app-backdrop"
initial={{
opacity: 0,
}}
animate={{
opacity: backdropLoading ? 0 : 0.6,
}}
exit={{
opacity: 0,
}}
transition={{
duration: 0.8,
ease: "easeInOut",
}}
onLoadCapture={() => {
setBackdropLoading(true);
}}
onLoad={() => {
setBackdropLoading(false);
}}
loading="eager"
style={{ style={{
zIndex: "99999999", transition: "opacity 0.8s",
position: "fixed",
bottom: 0,
left: 0,
objectFit: "cover",
}} }}
/> />
</Slide> </AnimatePresence>
</div>
{/* Show Dialog if server not reachable */} <div
className={audioPlayerVisible ? "audio-playing" : ""}
<div className="app-backdrop-container"> style={{
<AnimatePresence> display: "flex",
<motion.img width: "100vw",
key={backdropId} transition: "padding 250ms",
src={backdropUrl} }}
alt="" >
className="app-backdrop" <CssBaseline />
initial={{ {/* <SideMenu /> */}
opacity: 0, <AppBar />
}} <AudioPlayer key={audioPlayerVisible} />
animate={{ <ErrorBoundary FallbackComponent={ErrorNotice}>
opacity: backdropLoading ? 0 : 0.6, <Routes location={location}>
}} {/* <Route
exit={{
opacity: 0,
}}
transition={{
duration: 0.8,
ease: "easeInOut",
}}
onLoadCapture={() => {
setBackdropLoading(true);
}}
onLoad={() => {
setBackdropLoading(false);
}}
loading="eager"
style={{
transition: "opacity 0.8s",
}}
/>
</AnimatePresence>
</div>
<div
className={audioPlayerVisible ? "audio-playing" : ""}
style={{
display: "flex",
width: "100vw",
transition: "padding 250ms",
}}
>
<CssBaseline />
{/* <SideMenu /> */}
<AppBar />
<AudioPlayer key={audioPlayerVisible} />
<ErrorBoundary FallbackComponent={ErrorNotice}>
<Routes location={location}>
{/* <Route
// key={location.key} // key={location.key}
element={<AnimationWrapper />} element={<AnimationWrapper />}
> */} > */}
<Route path="/" element={<Navigate to={initialRoute} />} /> <Route path="/" element={<Navigate to={initialRoute} />} />
<Route <Route
path="/error" path="/error"
element={ element={
<Dialog <Dialog
open open
onClose={handleRelaunch} onClose={handleRelaunch}
aria-labelledby="alert-dialog-text" aria-labelledby="alert-dialog-text"
aria-describedby="alert-dialog-desc" aria-describedby="alert-dialog-desc"
maxWidth="md" maxWidth="md"
> >
<DialogTitle id="alert-dialog-text"> <DialogTitle id="alert-dialog-text">
Unable to reach server Unable to reach server
</DialogTitle> </DialogTitle>
<DialogContent> <DialogContent>
<DialogContentText id="alert-dialog-desc"> <DialogContentText id="alert-dialog-desc">
Unable to connect to the jellyfin server. Unable to connect to the jellyfin server.
</DialogContentText> </DialogContentText>
</DialogContent> </DialogContent>
<DialogActions> <DialogActions>
<Button onClick={() => navigate("/servers/list")}> <Button onClick={() => navigate("/servers/list")}>
Change Server Change Server
</Button> </Button>
<Button variant="outlined" onClick={handleRelaunch}> <Button variant="outlined" onClick={handleRelaunch}>
Restart JellyPlayer Restart JellyPlayer
</Button> </Button>
</DialogActions> </DialogActions>
</Dialog> </Dialog>
} }
/> />
<Route path="/login/index" element={<LoginRoute />} /> <Route path="/login/index" element={<LoginRoute />} />
<Route path="/home" element={<Home />} /> <Route path="/home" element={<Home />} />
<Route path="/setup/server" element={<ServerSetup />} /> <Route path="/setup/server" element={<ServerSetup />} />
<Route path="/servers/list" element={<ServerList />} /> <Route path="/servers/list" element={<ServerList />} />
<Route <Route
path="/login/withImg/:userName/:userId/" path="/login/withImg/:userName/:userId/"
element={<LoginWithImage />} element={<LoginWithImage />}
/> />
<Route path="/login/users" element={<UserLogin />} /> <Route path="/login/users" element={<UserLogin />} />
<Route path="/login/manual" element={<UserLoginManual />} /> <Route path="/login/manual" element={<UserLoginManual />} />
<Route path="/library/:id" element={<LibraryView />} /> <Route path="/library/:id" element={<LibraryView />} />
<Route path="/item/:id" element={<ItemDetail />} /> <Route path="/item/:id" element={<ItemDetail />} />
<Route <Route
path="/musicalbum/:id" path="/musicalbum/:id"
element={<MusicAlbumTitlePage />} element={<MusicAlbumTitlePage />}
errorElement={<div>Error</div>} errorElement={<div>Error</div>}
/> />
<Route path="/artist/:id" element={<ArtistTitlePage />} /> <Route path="/artist/:id" element={<ArtistTitlePage />} />
<Route path="/boxset/:id" element={<BoxSetTitlePage />} /> <Route path="/boxset/:id" element={<BoxSetTitlePage />} />
<Route path="/episode/:id" element={<EpisodeTitlePage />} /> <Route path="/episode/:id" element={<EpisodeTitlePage />} />
<Route path="/person/:id" element={<PersonTitlePage />} /> <Route path="/person/:id" element={<PersonTitlePage />} />
<Route path="/playlist/:id" element={<PlaylistTitlePage />} /> <Route path="/playlist/:id" element={<PlaylistTitlePage />} />
<Route path="/series/:id" element={<SeriesTitlePage />} /> <Route path="/series/:id" element={<SeriesTitlePage />} />
<Route path="/search" element={<SearchPage />} /> <Route path="/search" element={<SearchPage />} />
<Route path="/favorite" element={<FavoritePage />} /> <Route path="/favorite" element={<FavoritePage />} />
<Route path="/settings" element={<Settings />} /> <Route path="/settings" element={<Settings />} />
<Route path="/about" element={<About />} /> <Route path="/about" element={<About />} />
<Route path="/player" element={<VideoPlayer />} /> <Route path="/player" element={<VideoPlayer />} />
{/* </Route> */} {/* </Route> */}
</Routes> </Routes>
</ErrorBoundary> </ErrorBoundary>
</div> </div>
<ReactQueryDevtools buttonPosition="bottom-left" /> <ReactQueryDevtools buttonPosition="bottom-left" />
</ThemeProvider> </ThemeProvider>
</SnackbarProvider> </SnackbarProvider>
); );
}
} }
export default App; export default App;
Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

+44
View File
@@ -0,0 +1,44 @@
import React from "react";
import { Dialog, Slide } from "@mui/material";
import { useKonamiEasterEgg } from "../../utils/misc/konami";
export const EasterEgg = () => {
const [easterEgg, setEasterEgg] = useKonamiEasterEgg();
return (
<>
<Dialog
open={easterEgg}
onClose={() => setEasterEgg(false)}
sx={{
background: "black",
}}
>
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1&disablekb=1"
title="EasterEgg"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
/>
</Dialog>
<Slide direction="up" in={easterEgg} mountOnEnter unmountOnExit>
<img
src="https://i.gifer.com/PYh.gif"
loading="lazy"
width={320}
height={320}
alt="nyan cat gif"
style={{
zIndex: "99999999",
position: "fixed",
bottom: 0,
left: 0,
objectFit: "cover",
}}
/>
</Slide>
</>
);
};
-2
View File
@@ -1,5 +1,3 @@
import { EventEmitter as eventEmitter } from "events"; import { EventEmitter as eventEmitter } from "events";
// const eventEmitter = require("events");
export const EventEmitter = new eventEmitter(); export const EventEmitter = new eventEmitter();
+47 -38
View File
@@ -1,12 +1,10 @@
import React from "react"; import { Api } from "@jellyfin/sdk";
import ReactDOM from "react-dom/client";
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { enqueueSnackbar } from "notistack"; import { enqueueSnackbar } from "notistack";
import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App";
import { import {
delServer, delServer,
getAllServers, getAllServers,
@@ -14,7 +12,7 @@ import {
getServer, getServer,
setDefaultServer, setDefaultServer,
} from "./utils/storage/servers"; } from "./utils/storage/servers";
import { delUser, getUser } from "./utils/storage/user"; import { UserStore, delUser, getUser } from "./utils/storage/user";
import { createApi, useApi } from "./utils/store/api"; import { createApi, useApi } from "./utils/store/api";
import { setInitialRoute } from "./utils/store/central"; import { setInitialRoute } from "./utils/store/central";
@@ -30,10 +28,38 @@ const queryClient = new QueryClient({
}, },
}); });
const handleAuthError = async () => {
await delUser();
setInitialRoute("/login/index");
};
const authenticateUser = async (address: string, api: Api, user: UserStore["user"]) => {
try {
const auth = await api.authenticateUserByName(
user.Name,
user.Password
);
if (auth.status !== 200 || !auth.data.AccessToken) {
enqueueSnackbar("Incorrect Username or Password!", {
variant: "error",
});
handleAuthError();
} else {
createApi(address, auth.data.AccessToken);
setInitialRoute("/home");
}
} catch (error) {
console.error(error);
setInitialRoute("/error");
}
};
const init = async () => { const init = async () => {
const defaultServerOnDisk = await getDefaultServer(); const defaultServerOnDisk = await getDefaultServer();
if (defaultServerOnDisk) { if (defaultServerOnDisk) {
// This will be defined as we have a default server
const defaultServerInfo = await getServer(defaultServerOnDisk); const defaultServerInfo = await getServer(defaultServerOnDisk);
if (!defaultServerInfo) { if (!defaultServerInfo) {
@@ -42,40 +68,27 @@ const init = async () => {
const servers = await getAllServers(); const servers = await getAllServers();
if (servers.length > 0) { setInitialRoute(servers.length > 0 ? "/servers/list" : "/setup/server");
setInitialRoute("/servers/list");
} else {
setInitialRoute("/setup/server");
}
return; return;
} }
const userOnDisk = await getUser(); const userOnDisk = await getUser();
createApi(defaultServerInfo.address, ""); createApi(defaultServerInfo.address, "");
if (userOnDisk) { if (userOnDisk) {
try { try {
// Api is created with empty token, so we can authenticate const authApi = useApi.getState().api;
const auth = await useApi
.getState()
.api!.authenticateUserByName(userOnDisk.Name, userOnDisk.Password);
if (auth.status !== 200 || !auth.data.AccessToken) { if (!authApi) {
enqueueSnackbar("Incorrect Username or Password!", { handleAuthError();
variant: "error", return;
});
await delUser();
setInitialRoute("/login/index");
} else {
createApi(defaultServerInfo.address, auth.data.AccessToken);
setInitialRoute("/home");
} }
await authenticateUser(defaultServerInfo.address, authApi, userOnDisk);
} catch (error) { } catch (error) {
console.error(error); console.error(error);
setInitialRoute("/error"); handleAuthError();
} }
} else { } else {
setInitialRoute("/login/index"); setInitialRoute("/login/index");
@@ -84,7 +97,8 @@ const init = async () => {
setInitialRoute("/setup/server"); setInitialRoute("/setup/server");
} }
}; };
init();
await init();
ReactDOM.createRoot(document.getElementById("root")!).render( ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode> <React.StrictMode>
@@ -93,12 +107,7 @@ ReactDOM.createRoot(document.getElementById("root")!).render(
<App /> <App />
</Router> </Router>
</QueryClientProvider> </QueryClientProvider>
</React.StrictMode>, </React.StrictMode>
); );
document.addEventListener("DOMContentLoaded", () => { document.querySelector(".app-loading")!.setAttribute("style", "display:none");
// This will wait for the window to load, but you could
// run this function on whatever trigger you want
console.info("Initial render complete");
document.querySelector(".app-loading")?.setAttribute("style", "display:none");
});
+36 -3
View File
@@ -1,4 +1,3 @@
import { useMutation, useQuery } from "@tanstack/react-query"; import { useMutation, useQuery } from "@tanstack/react-query";
import React, { useState } from "react"; import React, { useState } from "react";
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
@@ -39,6 +38,41 @@ import { ErrorNotice } from "../../components/notices/errorNotice/errorNotice.js
import { useApi } from "../../utils/store/api"; import { useApi } from "../../utils/store/api";
import "./login.module.scss"; import "./login.module.scss";
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 (
<div
style={{
position: "fixed",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
}}
>
<CircularProgress size={72} thickness={1.4} />
</div>
);
};
export const LoginWithImage = () => { export const LoginWithImage = () => {
const { userName, userId } = useParams(); const { userName, userId } = useParams();
@@ -281,7 +315,7 @@ export const UserLogin = () => {
{users.data.map((item, index) => { {users.data.map((item, index) => {
return ( return (
<Grid <Grid
key={index} key={item.Id}
flexShrink={0} flexShrink={0}
flexGrow={1} flexGrow={1}
xs={1} xs={1}
@@ -289,7 +323,6 @@ export const UserLogin = () => {
md={1} md={1}
> >
<Card <Card
key={index}
cardTitle={item.Name} cardTitle={item.Name}
item={item} item={item}
disableOverlay disableOverlay
+26
View File
@@ -0,0 +1,26 @@
import { useState } from "react";
import useKonami from "react-use-konami";
export const useKonamiEasterEgg = () => {
const [easterEgg, setEasterEgg] = useState(false);
const sixtyNine = () => {
setEasterEgg(true);
};
useKonami(sixtyNine, {
code: [
"ArrowUp",
"ArrowUp",
"ArrowDown",
"ArrowDown",
"ArrowLeft",
"ArrowRight",
"ArrowLeft",
"ArrowRight",
"b",
"a",
],
});
return [easterEgg, setEasterEgg] as const;
};
+8
View File
@@ -0,0 +1,8 @@
import { relaunch } from "@tauri-apps/api/process";
export const handleRelaunch = async (_event: unknown, reason?: string) => {
if (reason && reason === "backdropClick") {
return;
}
await relaunch();
};
+5 -3
View File
@@ -1,6 +1,6 @@
import { appLocalDataDir, join } from "@tauri-apps/api/path";
import { Store } from "tauri-plugin-store-api"; import { Store } from "tauri-plugin-store-api";
// TODO: Add encryption to user data
export interface UserStore { export interface UserStore {
user: { user: {
Name: string; Name: string;
@@ -8,7 +8,8 @@ export interface UserStore {
}; };
} }
const user = new Store(".user.dat"); const base = await appLocalDataDir();
const user = new Store(await join(base, ".user.dat"));
/** /**
* Set User details to .user.dat * Set User details to .user.dat
@@ -16,8 +17,9 @@ const user = new Store(".user.dat");
const saveUser = async (userName: string, userPassword?: string) => { const saveUser = async (userName: string, userPassword?: string) => {
user.set("user", { user.set("user", {
Name: userName, Name: userName,
Password: userPassword || "", Password: userPassword,
}); });
await user.save(); await user.save();
}; };
+3 -1
View File
@@ -9,7 +9,9 @@ import { v4 as uuidv4 } from "uuid";
export const axiosClient = axios.create({ export const axiosClient = axios.create({
adapter: axiosTauriApiAdapter, adapter: axiosTauriApiAdapter,
headers: { "Access-Control-Allow-Origin": "*" }, headers: {
"Access-Control-Allow-Origin": "*",
},
timeout: 60000, timeout: 60000,
}); });
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "es5", // Specify ECMAScript target version "target": "ESNext", // Specify ECMAScript target version
"lib": [ "lib": [
"dom", "dom",
"dom.iterable", "dom.iterable",