feat: handle login from deeplink

This commit is contained in:
Zamitto 2024-06-16 13:58:24 -03:00
parent 55c214eae6
commit 32566e5dfc
17 changed files with 243 additions and 62 deletions

View File

@ -229,6 +229,10 @@
"amount_hours": "{{amount}} hours",
"amount_minutes": "{{amount}} minutes",
"play_time": "Played for {{amount}}",
"last_time_played": "Last played {{period}}"
"last_time_played": "Last played {{period}}",
"sign_out": "Sign out",
"activity": "Recent Activity",
"games": "Games",
"total_play_time": "Total playtime: {{amount}}"
}
}

View File

@ -230,6 +230,10 @@
"amount_hours": "{{amount}} horas",
"amount_minutes": "{{amount}} minutos",
"play_time": "Jogado por {{amount}}",
"last_time_played": "Jogou {{period}}"
"last_time_played": "Jogou {{period}}",
"sign_out": "Sair da conta",
"activity": "Atividade Recente",
"games": "Jogos",
"total_play_time": "Tempo total de jogo: {{amount}}"
}
}

View File

@ -0,0 +1,17 @@
import { userAuthRepository } from "@main/repository";
import { registerEvent } from "../register-event";
import { HydraApi } from "@main/services/hydra-api";
import { WindowManager } from "@main/services";
const signout = async (_event: Electron.IpcMainInvokeEvent): Promise<void> => {
await Promise.all([
userAuthRepository.delete({ id: 1 }),
HydraApi.post("/auth/logout"),
]).finally(() => {
if (WindowManager.mainWindow) {
WindowManager.mainWindow.webContents.send("on-signout");
}
});
};
registerEvent("signout", signout);

View File

@ -40,7 +40,8 @@ import "./download-sources/validate-download-source";
import "./download-sources/add-download-source";
import "./download-sources/remove-download-source";
import "./download-sources/sync-download-sources";
import "./profile/get-user-profile";
import "./auth/signout";
import "./user/get-user";
import "./profile/get-me";
ipcMain.handle("ping", () => "pong");

View File

@ -5,7 +5,7 @@ import { UserProfile } from "@types";
import { convertSteamGameToCatalogueEntry } from "../helpers/search-games";
import { getSteamAppAsset } from "@main/helpers";
const getUserProfile = async (
const getUser = async (
_event: Electron.IpcMainInvokeEvent,
username: string
): Promise<UserProfile | null> => {
@ -53,4 +53,4 @@ const getUserProfile = async (
}
};
registerEvent("getUserProfile", getUserProfile);
registerEvent("getUser", getUser);

View File

@ -7,6 +7,7 @@ import { DownloadManager, logger, WindowManager } from "@main/services";
import { dataSource } from "@main/data-source";
import * as resources from "@locales";
import { userPreferencesRepository } from "@main/repository";
import { HydraApi } from "./services/hydra-api";
const { autoUpdater } = updater;
@ -71,7 +72,7 @@ app.on("browser-window-created", (_, window) => {
optimizer.watchWindowShortcuts(window);
});
app.on("second-instance", (_event, commandLine) => {
app.on("second-instance", async (_event, commandLine) => {
// Someone tried to run a second instance, we should focus our window.
if (WindowManager.mainWindow) {
if (WindowManager.mainWindow.isMinimized())
@ -83,7 +84,14 @@ app.on("second-instance", (_event, commandLine) => {
}
const [, path] = commandLine.pop()?.split("://") ?? [];
if (path) WindowManager.redirect(path);
if (path) {
if (path.startsWith("auth")) {
//hydralauncher://auth?payload=responsedaapiembase64
await HydraApi.handleExternalAuth(path.split("=")[1]);
} else {
WindowManager.redirect(path);
}
}
});
app.on("open-url", (_event, url) => {

View File

@ -1,5 +1,6 @@
import { userAuthRepository } from "@main/repository";
import axios, { AxiosError, AxiosInstance } from "axios";
import { WindowManager } from "./window-manager";
export class HydraApi {
private static instance: AxiosInstance;
@ -16,6 +17,38 @@ export class HydraApi {
return this.userAuth.authToken !== "";
}
static async handleExternalAuth(auth: string) {
const decodedBase64 = atob(auth);
const jsonData = JSON.parse(decodedBase64);
const { accessToken, expiresIn, refreshToken } = jsonData;
const now = new Date();
const tokenExpirationTimestamp =
now.getTime() + expiresIn - this.EXPIRATION_OFFSET_IN_MS;
this.userAuth = {
authToken: accessToken,
refreshToken: refreshToken,
expirationTimestamp: tokenExpirationTimestamp,
};
await userAuthRepository.upsert(
{
id: 1,
accessToken,
tokenExpirationTimestamp,
refreshToken,
},
["id"]
);
if (WindowManager.mainWindow) {
WindowManager.mainWindow.webContents.send("on-signin");
}
}
static async setupApi() {
this.instance = axios.create({
baseURL: import.meta.env.MAIN_VITE_API_URL,
@ -33,6 +66,8 @@ export class HydraApi {
}
private static async revalidateAccessTokenIfExpired() {
if (!this.userAuth.authToken) throw new Error("user is not logged in");
const now = new Date();
if (this.userAuth.expirationTimestamp < now.getTime()) {
try {
@ -64,15 +99,11 @@ export class HydraApi {
this.userAuth.authToken = "";
this.userAuth.expirationTimestamp = 0;
userAuthRepository.upsert(
{
id: 1,
accessToken: "",
refreshToken: "",
tokenExpirationTimestamp: 0,
},
["id"]
);
if (WindowManager.mainWindow) {
WindowManager.mainWindow.webContents.send("on-signout");
}
userAuthRepository.delete({ id: 1 });
}
throw err;

View File

@ -128,7 +128,21 @@ contextBridge.exposeInMainWorld("electron", {
restartAndInstallUpdate: () => ipcRenderer.invoke("restartAndInstallUpdate"),
/* Profile */
getUserProfile: (username: string) =>
ipcRenderer.invoke("getUserProfile", username),
getMe: () => ipcRenderer.invoke("getMe"),
/* User */
getUser: (username: string) => ipcRenderer.invoke("getUser", username),
/* Auth */
signout: () => ipcRenderer.invoke("signout"),
onSignIn: (cb: () => void) => {
const listener = (_event: Electron.IpcRendererEvent) => cb();
ipcRenderer.on("on-signin", listener);
return () => ipcRenderer.removeListener("on-signin", listener);
},
onSignOut: (cb: () => void) => {
const listener = (_event: Electron.IpcRendererEvent) => cb();
ipcRenderer.on("on-signout", listener);
return () => ipcRenderer.removeListener("on-signout", listener);
},
});

View File

@ -1,38 +1,25 @@
import { useEffect, useState } from "react";
import { useContext } from "react";
import { useNavigate } from "react-router-dom";
import { type UserProfile } from "@types";
import * as styles from "./sidebar.css";
import { PersonIcon } from "@primer/octicons-react";
import { userAuthContext } from "@renderer/context/user-auth/user-auth.context";
import * as styles from "./sidebar.css";
export function SidebarProfile() {
const navigate = useNavigate();
const [userProfile, setUserProfile] = useState<UserProfile | null>(null);
const [isUserProfileLoading, setIsUserProfileLoading] = useState(true);
const { userAuth, isLoading } = useContext(userAuthContext);
const handleClickProfile = () => {
navigate(`/user/${userProfile!.id}`);
navigate(`/user/${userAuth!.id}`);
};
const handleClickLogin = () => {
window.electron.openExternal("https://losbroxas.org");
};
useEffect(() => {
setIsUserProfileLoading(true);
window.electron.isUserLoggedIn().then(async (isLoggedIn) => {
if (isLoggedIn) {
const userProfile = await window.electron.getMe();
setUserProfile(userProfile);
}
if (isLoading) return null;
setIsUserProfileLoading(false);
});
}, []);
if (isUserProfileLoading) return null;
if (userProfile == null) {
if (userAuth == null) {
return (
<>
<button
@ -60,11 +47,11 @@ export function SidebarProfile() {
onClick={handleClickProfile}
>
<div className={styles.profileAvatar}>
{userProfile.profileImageUrl ? (
{userAuth.profileImageUrl ? (
<img
className={styles.profileAvatar}
src={userProfile.profileImageUrl}
alt={userProfile.displayName}
src={userAuth.profileImageUrl}
alt={userAuth.displayName}
/>
) : (
<PersonIcon />
@ -72,7 +59,7 @@ export function SidebarProfile() {
</div>
<div className={styles.profileButtonInformation}>
<p style={{ fontWeight: "bold" }}>{userProfile.displayName}</p>
<p style={{ fontWeight: "bold" }}>{userAuth.displayName}</p>
</div>
</button>
</>

View File

@ -14,6 +14,7 @@ import { buildGameDetailsPath } from "@renderer/helpers";
import SteamLogo from "@renderer/assets/steam-logo.svg?react";
import { SidebarProfile } from "./sidebar-profile";
import { UserAuthContextProvider } from "@renderer/context/user-auth/user-auth.context";
const SIDEBAR_MIN_WIDTH = 200;
const SIDEBAR_INITIAL_WIDTH = 250;
@ -154,7 +155,9 @@ export function Sidebar() {
maxWidth: sidebarWidth,
}}
>
<SidebarProfile />
<UserAuthContextProvider>
<SidebarProfile />
</UserAuthContextProvider>
<div
className={styles.content({

View File

@ -0,0 +1,73 @@
import { createContext, useEffect, useState } from "react";
import { UserAuthContext } from "./user-auth.context.types";
import { UserAuth } from "@types";
export const userAuthContext = createContext<UserAuthContext>({
userAuth: null,
isLoading: false,
signout: async () => {},
updateMe: async () => {},
});
const { Provider } = userAuthContext;
export const { Consumer: UserAuthContextConsumer } = userAuthContext;
export interface UserAuthContextProps {
children: React.ReactNode;
}
export function UserAuthContextProvider({ children }: UserAuthContextProps) {
const [userAuth, setUserAuth] = useState<UserAuth | null>(null);
const [isLoading, setIsLoading] = useState(false);
const updateMe = () => {
setIsLoading(true);
return window.electron
.getMe()
.then((user) => {
setUserAuth(user);
})
.finally(() => {
setIsLoading(false);
});
};
useEffect(() => {
updateMe();
}, []);
useEffect(() => {
const listeners = [
window.electron.onSignIn(() => {
updateMe();
}),
window.electron.onSignOut(() => {
setUserAuth(null);
}),
];
return () => {
listeners.forEach((unsubscribe) => unsubscribe());
};
}, []);
const signout = () => {
return window.electron.signout().finally(() => {
setUserAuth(null);
});
};
return (
<Provider
value={{
userAuth,
signout,
updateMe,
isLoading,
}}
>
{children}
</Provider>
);
}

View File

@ -0,0 +1,8 @@
import { UserAuth } from "@types";
export interface UserAuthContext {
userAuth: UserAuth | null;
isLoading: boolean;
updateMe: () => Promise<void>;
signout: () => Promise<void>;
}

View File

@ -112,8 +112,15 @@ declare global {
checkForUpdates: () => Promise<boolean>;
restartAndInstallUpdate: () => Promise<void>;
/* Authg */
signout: () => Promise<void>;
onSignIn: (cb: () => void) => () => Electron.IpcRenderer;
onSignOut: (cb: () => void) => () => Electron.IpcRenderer;
/* User */
getUser: (username: string) => Promise<UserProfile | null>;
/* Profile */
getUserProfile: (username: string) => Promise<UserProfile | null>;
getMe: () => Promise<UserProfile | null>;
}

View File

@ -2,7 +2,7 @@ import { ProfileGame, UserProfile } from "@types";
import cn from "classnames";
import * as styles from "./user.css";
import { SPACING_UNIT, vars } from "@renderer/theme.css";
import { useMemo } from "react";
import { useContext, useMemo } from "react";
import { useTranslation } from "react-i18next";
import SteamLogo from "@renderer/assets/steam-logo.svg?react";
import { useDate } from "@renderer/hooks";
@ -10,6 +10,7 @@ import { useNavigate } from "react-router-dom";
import { buildGameDetailsPath } from "@renderer/helpers";
import { PersonIcon } from "@primer/octicons-react";
import { Button } from "@renderer/components";
import { userAuthContext } from "@renderer/context/user-auth/user-auth.context";
const MAX_MINUTES_TO_SHOW_IN_PLAYTIME = 120;
export interface ProfileContentProps {
@ -19,6 +20,8 @@ export interface ProfileContentProps {
export const UserContent = ({ userProfile }: ProfileContentProps) => {
const { t, i18n } = useTranslation("user_profile");
const { userAuth, signout } = useContext(userAuthContext);
const navigate = useNavigate();
const numberFormatter = useMemo(() => {
@ -50,6 +53,11 @@ export const UserContent = ({ userProfile }: ProfileContentProps) => {
navigate(buildGameDetailsPath(game));
};
const handleSignout = async () => {
await signout();
navigate("/");
};
return (
<>
<section
@ -72,15 +80,19 @@ export const UserContent = ({ userProfile }: ProfileContentProps) => {
<h2 style={{ fontWeight: "bold" }}>{userProfile.displayName}</h2>
</div>
<div style={{ flex: 1, display: "flex", justifyContent: "end" }}>
<Button theme="danger">Sair da conta</Button>
</div>
{userAuth && userAuth.id == userProfile.id && (
<div style={{ flex: 1, display: "flex", justifyContent: "end" }}>
<Button theme="danger" onClick={handleSignout}>
{t("sign_out")}
</Button>
</div>
)}
</section>
<div className={styles.profileContent}>
<div className={styles.profileGameSection}>
<div>
<h2>Atividade</h2>
<h2>{t("activity")}</h2>
</div>
<div
style={{
@ -130,7 +142,7 @@ export const UserContent = ({ userProfile }: ProfileContentProps) => {
gap: `${SPACING_UNIT * 2}px`,
}}
>
<h2>Games</h2>
<h2>{t("games")}</h2>
<div
style={{
@ -143,7 +155,7 @@ export const UserContent = ({ userProfile }: ProfileContentProps) => {
{userProfile.libraryGames.length}
</h3>
</div>
<small>Tempo total de jogo: {formatPlayTime()}</small>
<small>{t("total_play_time", { amount: formatPlayTime() })}</small>
<div
style={{
display: "grid",

View File

@ -5,7 +5,10 @@ export const UserSkeleton = () => {
return (
<>
<Skeleton className={styles.profileHeaderSkeleton} />
<Skeleton width={135} />
<div className={styles.profileContent}>
<Skeleton height={140} style={{ flex: 1 }} />
<Skeleton width={300} className={styles.contentSidebar} />
</div>
</>
);
};

View File

@ -8,6 +8,7 @@ import { UserContent } from "./user-content";
import { SkeletonTheme } from "react-loading-skeleton";
import { vars } from "@renderer/theme.css";
import * as styles from "./user.css";
import { UserAuthContextProvider } from "@renderer/context/user-auth/user-auth.context";
export const User = () => {
const { username } = useParams();
@ -16,7 +17,7 @@ export const User = () => {
const dispatch = useAppDispatch();
useEffect(() => {
window.electron.getUserProfile(username!).then((userProfile) => {
window.electron.getUser(username!).then((userProfile) => {
if (userProfile) {
dispatch(setHeaderTitle(userProfile.displayName));
setUserProfile(userProfile);
@ -25,14 +26,16 @@ export const User = () => {
}, [dispatch, username]);
return (
<SkeletonTheme baseColor={vars.color.background} highlightColor="#444">
<div className={styles.wrapper}>
{userProfile ? (
<UserContent userProfile={userProfile} />
) : (
<UserSkeleton />
)}
</div>
</SkeletonTheme>
<UserAuthContextProvider>
<SkeletonTheme baseColor={vars.color.background} highlightColor="#444">
<div className={styles.wrapper}>
{userProfile ? (
<UserContent userProfile={userProfile} />
) : (
<UserSkeleton />
)}
</div>
</SkeletonTheme>
</UserAuthContextProvider>
);
};

View File

@ -244,6 +244,12 @@ export interface RealDebridUser {
expiration: string;
}
export interface UserAuth {
id: string;
displayName: string;
profileImageUrl: string | null;
}
export interface UserProfile {
id: string;
displayName: string;