Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add multi-accounts support on android and fix invalid token issues #185

Merged
merged 10 commits into from
Jul 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 49 additions & 4 deletions front/apps/mobile/app/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import { PortalProvider } from "@gorhom/portal";
import { ThemeSelector } from "@kyoo/primitives";
import { NavbarRight, NavbarTitle } from "@kyoo/ui";
import { createQueryClient } from "@kyoo/models";
import { AccountContext, createQueryClient, useAccounts } from "@kyoo/models";
import { QueryClientProvider } from "@tanstack/react-query";
import i18next from "i18next";
import { Stack } from "expo-router";
Expand All @@ -37,8 +37,12 @@ import { useEffect, useState } from "react";
import { useColorScheme } from "react-native";
import { initReactI18next } from "react-i18next";
import { useTheme } from "yoshiki/native";
import { Button, CircularProgress, H1, P, ts } from "@kyoo/primitives";
import { useTranslation } from "react-i18next";
import { View } from "react-native";
import { useYoshiki } from "yoshiki/native";
import { useRouter } from "solito/router";
import "intl-pluralrules";
import { AccountContext, useAccounts } from "./index";

// TODO: use a backend to load jsons.
import en from "../../../translations/en.json";
Expand All @@ -56,6 +60,26 @@ i18next.use(initReactI18next).init({
},
});

export const ConnectionError = ({ error, retry }: { error?: string; retry: () => void }) => {
const { css } = useYoshiki();
const { t } = useTranslation();
const router = useRouter();

return (
<View {...css({ padding: ts(2) })}>
<H1 {...css({ textAlign: "center" })}>{t("errors.connection")}</H1>
<P>{error ?? t("error.unknown")}</P>
<P>{t("errors.connection-tips")}</P>
<Button onPress={retry} text={t("errors.try-again")} {...css({ m: ts(1) })} />
<Button
onPress={() => router.push("/login")}
text={t("errors.re-login")}
{...css({ m: ts(1) })}
/>
</View>
);
};

const ThemedStack = ({ onLayout }: { onLayout?: () => void }) => {
const theme = useTheme();

Expand All @@ -76,14 +100,28 @@ const ThemedStack = ({ onLayout }: { onLayout?: () => void }) => {
);
};

const AuthGuard = ({ selected }: { selected: number | null }) => {
const router = useRouter();

useEffect(() => {
if (selected === null)
router.replace("/login", undefined, {
experimental: { nativeBehavior: "stack-replace", isNestedNavigator: false },
});
}, [selected, router]);
return null;
};

let rendered: boolean = false;

export default function Root() {
const [queryClient] = useState(() => createQueryClient());
const theme = useColorScheme();
const [fontsLoaded] = useFonts({ Poppins_300Light, Poppins_400Regular, Poppins_900Black });
const info = useAccounts();

if (!fontsLoaded || info.type === "loading") return <SplashScreen />;
if (!fontsLoaded || (!rendered && info.type === "loading")) return <SplashScreen />;
rendered = true;
return (
<AccountContext.Provider value={info}>
<QueryClientProvider client={queryClient}>
Expand All @@ -97,7 +135,14 @@ export default function Root() {
}}
>
<PortalProvider>
<ThemedStack />
{info.type === "loading" && <CircularProgress />}
{info.type === "error" && <ConnectionError error={info.error} retry={info.retry} />}
{info.type === "ok" && (
<>
<ThemedStack />
<AuthGuard selected={info.selected} />
</>
)}
</PortalProvider>
</ThemeSelector>
</QueryClientProvider>
Expand Down
85 changes: 3 additions & 82 deletions front/apps/mobile/app/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,86 +18,7 @@
* along with Kyoo. If not, see <https://www.gnu.org/licenses/>.
*/

import { Account, loginFunc } from "@kyoo/models";
import { getSecureItem, setSecureItem } from "@kyoo/models/src/secure-store";
import { Button, CircularProgress, H1, P } from "@kyoo/primitives";
import { Redirect } from "expo-router";
import { createContext, useContext, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { View } from "react-native";
import { useYoshiki } from "yoshiki/native";
import { useRouter } from "solito/router";
import Browse from "./browse";

export const useAccounts = () => {
const [accounts, setAccounts] = useState<Account[] | null>(null);
const [verified, setVerified] = useState<{
status: "ok" | "error" | "loading" | "unverified";
error?: string;
}>({ status: "loading" });
// TODO: Remember the last selected account.
const selected = accounts?.length ? 0 : null;

useEffect(() => {
async function run() {
const accounts = await getSecureItem("accounts");
setAccounts(accounts ? JSON.parse(accounts) : []);
}
run();
}, []);

useEffect(() => {
async function check() {
const selAcc = accounts![selected!];
await setSecureItem("apiUrl", selAcc.apiUrl);
const verif = await loginFunc("refresh", selAcc.refresh_token);
setVerified(verif.ok ? { status: "ok" } : { status: "error", error: verif.error });
}

if (accounts && selected !== null) check();
else setVerified({status: "unverified"});
}, [accounts, selected, verified.status]);

if (accounts === null || verified.status === "loading") return { type: "loading" } as const;
if (verified.status === "error") {
return {
type: "error",
error: verified.error,
retry: () => setVerified({ status: "loading" }),
};
}
return { type: "ok", accounts, selected } as const;
};

export const ConnectionError = ({ error, retry }: { error?: string; retry: () => void }) => {
const { css } = useYoshiki();
const { t } = useTranslation();
const router = useRouter();

return (
<View {...css({ bg: (theme) => theme.colors.red })}>
<H1>{t("error.connection")}</H1>
<P>{error ?? t("error.unknown")}</P>
<P>{t("error.connection-tips")}</P>
<Button onPress={retry} text={t("error.try-again")} />
<Button onPress={() => router.push("/login")} text={t("error.re-login")} />
</View>
);
};

export const AccountContext = createContext<ReturnType<typeof useAccounts>>({ type: "loading" });

let initialRender = true;

const App = () => {
// Using context on the initial one to keep the splashscreen and not show a spinner.
// eslint-disable-next-line react-hooks/rules-of-hooks
const info = initialRender ? useContext(AccountContext) : useAccounts();
initialRender = false;
if (info.type === "loading") return <CircularProgress />
if (info.type === "error") return <ConnectionError error={info.error} retry={info.retry} />;
if (info.selected === null) return <Redirect href="/login" />;
// While there is no home page, show the browse page.
return <Redirect href="/browse" />;
};

export default App;
// While there is no home page, show the browse page.
export default Browse;
2 changes: 2 additions & 0 deletions front/apps/mobile/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,12 @@
"react-dom": "18.2.0",
"react-i18next": "^12.2.0",
"react-native": "0.71.8",
"react-native-mmkv": "^2.10.1",
"react-native-reanimated": "~2.14.4",
"react-native-safe-area-context": "4.5.0",
"react-native-screens": "~3.20.0",
"react-native-svg": "13.4.0",
"react-native-uuid": "^2.0.1",
"react-native-video": "^6.0.0-alpha.5",
"yoshiki": "1.2.2"
},
Expand Down
4 changes: 2 additions & 2 deletions front/apps/web/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { Hydrate, QueryClientProvider } from "@tanstack/react-query";
import { HiddenIfNoJs, SkeletonCss, ThemeSelector } from "@kyoo/primitives";
import { WebTooltip } from "@kyoo/primitives/src/tooltip.web";
import { createQueryClient, fetchQuery, getTokenWJ, QueryIdentifier, QueryPage } from "@kyoo/models";
import { setSecureItemSync } from "@kyoo/models/src/secure-store.web";
import { setSecureItem } from "@kyoo/models/src/secure-store.web";
import { useState } from "react";
import NextApp, { AppContext, type AppProps } from "next/app";
import { Poppins } from "next/font/google";
Expand Down Expand Up @@ -101,7 +101,7 @@ const App = ({ Component, pageProps }: AppProps) => {

// Set the auth from the server (if the token was refreshed during SSR).
if (typeof window !== "undefined" && token)
setSecureItemSync("auth", JSON.stringify(token));
setSecureItem("auth", JSON.stringify(token));

return (
<YoshikiDebug>
Expand Down
2 changes: 1 addition & 1 deletion front/packages/models/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"packageManager": "[email protected]",
"devDependencies": {
"@types/react": "^18.0.28",
"expo-secure-store": "^12.1.1",
"react-native-mmkv": "^2.10.1",
"typescript": "^4.9.5"
},
"peerDependencies": {
Expand Down
85 changes: 85 additions & 0 deletions front/packages/models/src/accounts.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Kyoo - A portable and vast media library solution.
* Copyright (c) Kyoo.
*
* See AUTHORS.md and LICENSE file in the project root for full license information.
*
* Kyoo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Kyoo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Kyoo. If not, see <https://www.gnu.org/licenses/>.
*/

import { getSecureItem, setSecureItem, storage } from "./secure-store";
import { setApiUrl } from "./query";
import { createContext, useEffect, useState } from "react";
import { useMMKVListener } from "react-native-mmkv";
import { Account, loginFunc } from "./login";

export const AccountContext = createContext<ReturnType<typeof useAccounts>>({ type: "loading" });

export const useAccounts = () => {
const [accounts, setAccounts] = useState<Account[]>(JSON.parse(getSecureItem("accounts") ?? "[]"));
const [verified, setVerified] = useState<{
status: "ok" | "error" | "loading" | "unverified";
error?: string;
}>({ status: "loading" });
const [retryCount, setRetryCount] = useState(0);

const sel = getSecureItem("selected");
let [selected, setSelected] = useState<number | null>(
sel ? parseInt(sel) : accounts.length > 0 ? 0 : null,
);
if (selected === null && accounts.length > 0) selected = 0;
if (accounts.length === 0) selected = null;

useEffect(() => {
async function check() {
setVerified({status: "loading"});
const selAcc = accounts![selected!];
setApiUrl(selAcc.apiUrl);
const verif = await loginFunc("refresh", selAcc.refresh_token);
setVerified(verif.ok ? { status: "ok" } : { status: "error", error: verif.error });
}

if (accounts.length && selected !== null) check();
else setVerified({ status: "unverified" });
// Use the length of the array and not the array directly because we don't care if the refresh token changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [accounts.length, selected, retryCount]);

useMMKVListener((key) => {
if (key === "accounts") setAccounts(JSON.parse(getSecureItem("accounts") ?? "[]"));
}, storage);

if (verified.status === "loading") return { type: "loading" } as const;
if (accounts.length && verified.status === "unverified") return { type: "loading" } as const;
if (verified.status === "error") {
return {
type: "error",
error: verified.error,
retry: () => {
setVerified({ status: "loading" });
setRetryCount((x) => x + 1);
},
} as const;
}
return {
type: "ok",
accounts,
selected,
setSelected: (selected: number) => {
setSelected(selected);
setSecureItem("selected", selected.toString());
},
} as const;
};

23 changes: 23 additions & 0 deletions front/packages/models/src/accounts.web.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Kyoo - A portable and vast media library solution.
* Copyright (c) Kyoo.
*
* See AUTHORS.md and LICENSE file in the project root for full license information.
*
* Kyoo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Kyoo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Kyoo. If not, see <https://www.gnu.org/licenses/>.
*/

export const useAccounts = () => {}

export const AccountContext = 0;
1 change: 1 addition & 0 deletions front/packages/models/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
* along with Kyoo. If not, see <https://www.gnu.org/licenses/>.
*/

export * from "./accounts";
export * from "./resources";
export * from "./traits";
export * from "./page";
Expand Down
Loading