Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Switch to prettier defaults

Manav Rathic1bf19321158
diff --git a/.github/.prettierrc.json b/.github/.prettierrc.json
deleted file mode 100644
index 0a02bcefda..0000000000
--- a/.github/.prettierrc.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "tabWidth": 4
-}
diff --git a/.prettierrc.json b/.prettierrc.json
index 81f1f4839c..f657075f0c 100644
--- a/.prettierrc.json
+++ b/.prettierrc.json
@@ -1,6 +1,4 @@
{
"tabWidth": 4,
- "trailingComma": "es5",
- "singleQuote": true,
- "bracketSameLine": true
+ "plugins": ["prettier-plugin-organize-imports"]
}
diff --git a/apps/accounts/.eslintrc.js b/apps/accounts/.eslintrc.js
index 7ddcebe961..b1c4c2e168 100644
--- a/apps/accounts/.eslintrc.js
+++ b/apps/accounts/.eslintrc.js
@@ -3,11 +3,11 @@ module.exports = {
// This is required here to ensure desktop picks the right eslint config, where this app is
// packaged as a submodule.
root: true,
- extends: ['@ente/eslint-config'],
- parser: '@typescript-eslint/parser',
+ extends: ["@ente/eslint-config"],
+ parser: "@typescript-eslint/parser",
parserOptions: {
tsconfigRootDir: __dirname,
- project: './tsconfig.json',
+ project: "./tsconfig.json",
},
- ignorePatterns: ['.eslintrc.js', 'out'],
+ ignorePatterns: [".eslintrc.js", "out"],
};
diff --git a/apps/accounts/next.config.js b/apps/accounts/next.config.js
index 9efbf75616..cffaafdd31 100644
--- a/apps/accounts/next.config.js
+++ b/apps/accounts/next.config.js
@@ -1,4 +1,4 @@
-const nextConfigBase = require('@/next/next.config.base.js');
+const nextConfigBase = require("@/next/next.config.base.js");
module.exports = {
...nextConfigBase,
diff --git a/apps/accounts/sentry.client.config.ts b/apps/accounts/sentry.client.config.ts
index 8223fcd906..c43273663f 100644
--- a/apps/accounts/sentry.client.config.ts
+++ b/apps/accounts/sentry.client.config.ts
@@ -1,3 +1,3 @@
-import { initSentry } from '@ente/shared/sentry/config/sentry.config.base';
+import { initSentry } from "@ente/shared/sentry/config/sentry.config.base";
-initSentry('https://[email protected]/5');
+initSentry("https://[email protected]/5");
diff --git a/apps/accounts/src/pages/_app.tsx b/apps/accounts/src/pages/_app.tsx
index 6461ef51e6..03d675a2f1 100644
--- a/apps/accounts/src/pages/_app.tsx
+++ b/apps/accounts/src/pages/_app.tsx
@@ -1,27 +1,27 @@
-import { CacheProvider } from '@emotion/react';
-import { APPS, APP_TITLES } from '@ente/shared/apps/constants';
-import { EnteAppProps } from '@ente/shared/apps/types';
-import { Overlay } from '@ente/shared/components/Container';
-import DialogBoxV2 from '@ente/shared/components/DialogBoxV2';
+import { setupI18n } from "@/ui/i18n";
+import { CacheProvider } from "@emotion/react";
+import { APPS, APP_TITLES } from "@ente/shared/apps/constants";
+import { EnteAppProps } from "@ente/shared/apps/types";
+import { Overlay } from "@ente/shared/components/Container";
+import DialogBoxV2 from "@ente/shared/components/DialogBoxV2";
import {
DialogBoxAttributesV2,
SetDialogBoxAttributesV2,
-} from '@ente/shared/components/DialogBoxV2/types';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import AppNavbar from '@ente/shared/components/Navbar/app';
-import { useLocalState } from '@ente/shared/hooks/useLocalState';
-import { setupI18n } from '@/ui/i18n';
-import HTTPService from '@ente/shared/network/HTTPService';
-import { LS_KEYS, getData } from '@ente/shared/storage/localStorage';
-import { getTheme } from '@ente/shared/themes';
-import { THEME_COLOR } from '@ente/shared/themes/constants';
-import createEmotionCache from '@ente/shared/themes/createEmotionCache';
-import { CssBaseline, useMediaQuery } from '@mui/material';
-import { ThemeProvider } from '@mui/material/styles';
-import Head from 'next/head';
-import { useRouter } from 'next/router';
-import { createContext, useEffect, useState } from 'react';
-import 'styles/global.css';
+} from "@ente/shared/components/DialogBoxV2/types";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import AppNavbar from "@ente/shared/components/Navbar/app";
+import { useLocalState } from "@ente/shared/hooks/useLocalState";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
+import { getTheme } from "@ente/shared/themes";
+import { THEME_COLOR } from "@ente/shared/themes/constants";
+import createEmotionCache from "@ente/shared/themes/createEmotionCache";
+import { CssBaseline, useMediaQuery } from "@mui/material";
+import { ThemeProvider } from "@mui/material/styles";
+import Head from "next/head";
+import { useRouter } from "next/router";
+import { createContext, useEffect, useState } from "react";
+import "styles/global.css";
interface AppContextProps {
isMobile: boolean;
@@ -50,7 +50,7 @@ export default function App(props: EnteAppProps) {
const showNavBar = (show: boolean) => setShowNavBar(show);
- const isMobile = useMediaQuery('(max-width:428px)');
+ const isMobile = useMediaQuery("(max-width:428px)");
const router = useRouter();
@@ -70,14 +70,14 @@ export default function App(props: EnteAppProps) {
const pkg = getData(LS_KEYS.CLIENT_PACKAGE);
if (!pkg) return;
HTTPService.setHeaders({
- 'X-Client-Package': pkg.name,
+ "X-Client-Package": pkg.name,
});
};
useEffect(() => {
- router.events.on('routeChangeComplete', setupPackageName);
+ router.events.on("routeChangeComplete", setupPackageName);
return () => {
- router.events.off('routeChangeComplete', setupPackageName);
+ router.events.off("routeChangeComplete", setupPackageName);
};
}, [router.events]);
@@ -111,17 +111,19 @@ export default function App(props: EnteAppProps) {
showNavBar,
setDialogBoxAttributesV2:
setDialogBoxAttributesV2 as any,
- }}>
+ }}
+ >
{!isI18nReady && (
<Overlay
sx={(theme) => ({
- display: 'flex',
- justifyContent: 'center',
- alignItems: 'center',
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
zIndex: 2000,
backgroundColor: (theme as any).colors
.background.base,
- })}>
+ })}
+ >
<EnteSpinner />
</Overlay>
)}
diff --git a/apps/accounts/src/pages/_document.tsx b/apps/accounts/src/pages/_document.tsx
index c3686b6be9..09d4d57823 100644
--- a/apps/accounts/src/pages/_document.tsx
+++ b/apps/accounts/src/pages/_document.tsx
@@ -1,6 +1,6 @@
import DocumentPage, {
EnteDocumentProps,
-} from '@ente/shared/next/pages/_document';
+} from "@ente/shared/next/pages/_document";
export default function Document(props: EnteDocumentProps) {
return <DocumentPage {...props} />;
diff --git a/apps/accounts/src/pages/account-handoff.tsx b/apps/accounts/src/pages/account-handoff.tsx
index 48d4ee2aeb..fcb363960b 100644
--- a/apps/accounts/src/pages/account-handoff.tsx
+++ b/apps/accounts/src/pages/account-handoff.tsx
@@ -1,11 +1,11 @@
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { ACCOUNTS_PAGES } from '@ente/shared/constants/pages';
-import HTTPService from '@ente/shared/network/HTTPService';
-import { logError } from '@ente/shared/sentry';
-import { LS_KEYS, getData, setData } from '@ente/shared/storage/localStorage';
-import { useRouter } from 'next/router';
-import { useEffect } from 'react';
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import { ACCOUNTS_PAGES } from "@ente/shared/constants/pages";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { logError } from "@ente/shared/sentry";
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
+import { useRouter } from "next/router";
+import { useEffect } from "react";
const AccountHandoff = () => {
const router = useRouter();
@@ -16,26 +16,26 @@ const AccountHandoff = () => {
router.push(ACCOUNTS_PAGES.PASSKEYS);
} catch (e) {
- logError(e, 'Failed to deserialize and set passed user data');
+ logError(e, "Failed to deserialize and set passed user data");
router.push(ACCOUNTS_PAGES.LOGIN);
}
};
const getClientPackageName = () => {
const urlParams = new URLSearchParams(window.location.search);
- const pkg = urlParams.get('package');
+ const pkg = urlParams.get("package");
if (!pkg) return;
setData(LS_KEYS.CLIENT_PACKAGE, { name: pkg });
HTTPService.setHeaders({
- 'X-Client-Package': pkg,
+ "X-Client-Package": pkg,
});
};
const extractAccountsToken = () => {
const urlParams = new URLSearchParams(window.location.search);
- const token = urlParams.get('token');
+ const token = urlParams.get("token");
if (!token) {
- throw new Error('token not found');
+ throw new Error("token not found");
}
const user = getData(LS_KEYS.USER) || {};
diff --git a/apps/accounts/src/pages/credentials/index.tsx b/apps/accounts/src/pages/credentials/index.tsx
index 57a99c9b02..453a61315e 100644
--- a/apps/accounts/src/pages/credentials/index.tsx
+++ b/apps/accounts/src/pages/credentials/index.tsx
@@ -1,8 +1,8 @@
-import CredentialPage from '@ente/accounts/pages/credentials';
-import { useRouter } from 'next/router';
-import { AppContext } from '../_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import CredentialPage from "@ente/accounts/pages/credentials";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { useContext } from "react";
+import { AppContext } from "../_app";
export default function Credential() {
const appContext = useContext(AppContext);
diff --git a/apps/accounts/src/pages/generate/index.tsx b/apps/accounts/src/pages/generate/index.tsx
index 54a2c2a771..84d8f52278 100644
--- a/apps/accounts/src/pages/generate/index.tsx
+++ b/apps/accounts/src/pages/generate/index.tsx
@@ -1,8 +1,8 @@
-import GeneratePage from '@ente/accounts/pages/generate';
-import { APPS } from '@ente/shared/apps/constants';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
+import GeneratePage from "@ente/accounts/pages/generate";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Generate() {
const appContext = useContext(AppContext);
diff --git a/apps/accounts/src/pages/index.tsx b/apps/accounts/src/pages/index.tsx
index 86fa118264..f9538e05db 100644
--- a/apps/accounts/src/pages/index.tsx
+++ b/apps/accounts/src/pages/index.tsx
@@ -1,11 +1,11 @@
-import { useRouter } from 'next/router';
-import { useEffect } from 'react';
+import { useRouter } from "next/router";
+import { useEffect } from "react";
const Index = () => {
const router = useRouter();
useEffect(() => {
- router.push('/login');
+ router.push("/login");
}, []);
return <></>;
};
diff --git a/apps/accounts/src/pages/login/index.tsx b/apps/accounts/src/pages/login/index.tsx
index b7ca4b504a..a6ca13492c 100644
--- a/apps/accounts/src/pages/login/index.tsx
+++ b/apps/accounts/src/pages/login/index.tsx
@@ -1,8 +1,8 @@
-import LoginPage from '@ente/accounts/pages/login';
-import { useRouter } from 'next/router';
-import { AppContext } from '../_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import LoginPage from "@ente/accounts/pages/login";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { useContext } from "react";
+import { AppContext } from "../_app";
export default function Login() {
const appContext = useContext(AppContext);
diff --git a/apps/accounts/src/pages/passkeys/DeletePasskeyModal.tsx b/apps/accounts/src/pages/passkeys/DeletePasskeyModal.tsx
index 97e2253d9d..f0feb0dbd6 100644
--- a/apps/accounts/src/pages/passkeys/DeletePasskeyModal.tsx
+++ b/apps/accounts/src/pages/passkeys/DeletePasskeyModal.tsx
@@ -1,11 +1,11 @@
-import DialogBoxV2 from '@ente/shared/components/DialogBoxV2';
-import EnteButton from '@ente/shared/components/EnteButton';
-import { Button, Stack, Typography } from '@mui/material';
-import { AppContext } from 'pages/_app';
-import { useContext, useState } from 'react';
-import { deletePasskey } from 'services/passkeysService';
-import { PasskeysContext } from '.';
-import { t } from 'i18next';
+import DialogBoxV2 from "@ente/shared/components/DialogBoxV2";
+import EnteButton from "@ente/shared/components/EnteButton";
+import { Button, Stack, Typography } from "@mui/material";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext, useState } from "react";
+import { deletePasskey } from "services/passkeysService";
+import { PasskeysContext } from ".";
interface IProps {
open: boolean;
@@ -41,27 +41,30 @@ const DeletePasskeyModal = (props: IProps) => {
onClose={props.onClose}
fullScreen={isMobile}
attributes={{
- title: t('DELETE_PASSKEY'),
+ title: t("DELETE_PASSKEY"),
secondary: {
action: props.onClose,
- text: t('CANCEL'),
+ text: t("CANCEL"),
},
- }}>
- <Stack spacing={'8px'}>
- <Typography>{t('DELETE_PASSKEY_CONFIRMATION')}</Typography>
+ }}
+ >
+ <Stack spacing={"8px"}>
+ <Typography>{t("DELETE_PASSKEY_CONFIRMATION")}</Typography>
<EnteButton
type="submit"
size="large"
color="critical"
loading={loading}
- onClick={doDelete}>
- {t('DELETE')}
+ onClick={doDelete}
+ >
+ {t("DELETE")}
</EnteButton>
<Button
size="large"
- color={'secondary'}
- onClick={props.onClose}>
- {t('CANCEL')}
+ color={"secondary"}
+ onClick={props.onClose}
+ >
+ {t("CANCEL")}
</Button>
</Stack>
</DialogBoxV2>
diff --git a/apps/accounts/src/pages/passkeys/ManagePasskeyDrawer.tsx b/apps/accounts/src/pages/passkeys/ManagePasskeyDrawer.tsx
index 89b7e41b34..4e98748755 100644
--- a/apps/accounts/src/pages/passkeys/ManagePasskeyDrawer.tsx
+++ b/apps/accounts/src/pages/passkeys/ManagePasskeyDrawer.tsx
@@ -1,19 +1,19 @@
-import { EnteDrawer } from '@ente/shared/components/EnteDrawer';
-import { PasskeysContext } from '.';
-import { Stack } from '@mui/material';
-import Titlebar from '@ente/shared/components/Titlebar';
-import { MenuItemGroup } from '@ente/shared/components/Menu/MenuItemGroup';
-import { EnteMenuItem } from '@ente/shared/components/Menu/EnteMenuItem';
-import { useContext, useState } from 'react';
-import EditIcon from '@mui/icons-material/Edit';
-import DeleteIcon from '@mui/icons-material/Delete';
-import MenuItemDivider from '@ente/shared/components/Menu/MenuItemDivider';
-import DeletePasskeyModal from './DeletePasskeyModal';
-import RenamePasskeyModal from './RenamePasskeyModal';
-import InfoItem from '@ente/shared/components/Info/InfoItem';
-import CalendarTodayIcon from '@mui/icons-material/CalendarToday';
-import { formatDateTimeFull } from '@ente/shared/time/format';
-import { t } from 'i18next';
+import { EnteDrawer } from "@ente/shared/components/EnteDrawer";
+import InfoItem from "@ente/shared/components/Info/InfoItem";
+import { EnteMenuItem } from "@ente/shared/components/Menu/EnteMenuItem";
+import MenuItemDivider from "@ente/shared/components/Menu/MenuItemDivider";
+import { MenuItemGroup } from "@ente/shared/components/Menu/MenuItemGroup";
+import Titlebar from "@ente/shared/components/Titlebar";
+import { formatDateTimeFull } from "@ente/shared/time/format";
+import CalendarTodayIcon from "@mui/icons-material/CalendarToday";
+import DeleteIcon from "@mui/icons-material/Delete";
+import EditIcon from "@mui/icons-material/Edit";
+import { Stack } from "@mui/material";
+import { t } from "i18next";
+import { useContext, useState } from "react";
+import { PasskeysContext } from ".";
+import DeletePasskeyModal from "./DeletePasskeyModal";
+import RenamePasskeyModal from "./RenamePasskeyModal";
interface IProps {
open: boolean;
@@ -33,10 +33,11 @@ const ManagePasskeyDrawer = (props: IProps) => {
open={props.open}
onClose={() => {
setShowPasskeyDrawer(false);
- }}>
+ }}
+ >
{selectedPasskey && (
<>
- <Stack spacing={'4px'} py={'12px'}>
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={() => {
setShowPasskeyDrawer(false);
@@ -48,11 +49,11 @@ const ManagePasskeyDrawer = (props: IProps) => {
/>
<InfoItem
icon={<CalendarTodayIcon />}
- title={t('CREATED_AT')}
+ title={t("CREATED_AT")}
caption={
`${formatDateTimeFull(
- selectedPasskey.createdAt / 1000
- )}` || ''
+ selectedPasskey.createdAt / 1000,
+ )}` || ""
}
loading={!selectedPasskey}
hideEditOption
@@ -63,7 +64,7 @@ const ManagePasskeyDrawer = (props: IProps) => {
setShowRenamePasskeyModal(true);
}}
startIcon={<EditIcon />}
- label={'Rename Passkey'}
+ label={"Rename Passkey"}
/>
<MenuItemDivider />
<EnteMenuItem
@@ -71,7 +72,7 @@ const ManagePasskeyDrawer = (props: IProps) => {
setShowDeletePasskeyModal(true);
}}
startIcon={<DeleteIcon />}
- label={'Delete Passkey'}
+ label={"Delete Passkey"}
color="critical"
/>
</MenuItemGroup>
diff --git a/apps/accounts/src/pages/passkeys/PasskeyListItem.tsx b/apps/accounts/src/pages/passkeys/PasskeyListItem.tsx
index ba216ab24f..d38a22044d 100644
--- a/apps/accounts/src/pages/passkeys/PasskeyListItem.tsx
+++ b/apps/accounts/src/pages/passkeys/PasskeyListItem.tsx
@@ -1,9 +1,9 @@
-import { EnteMenuItem } from '@ente/shared/components/Menu/EnteMenuItem';
-import { Passkey } from 'types/passkey';
-import ChevronRightIcon from '@mui/icons-material/ChevronRight';
-import { useContext } from 'react';
-import { PasskeysContext } from '.';
-import KeyIcon from '@mui/icons-material/Key';
+import { EnteMenuItem } from "@ente/shared/components/Menu/EnteMenuItem";
+import ChevronRightIcon from "@mui/icons-material/ChevronRight";
+import KeyIcon from "@mui/icons-material/Key";
+import { useContext } from "react";
+import { Passkey } from "types/passkey";
+import { PasskeysContext } from ".";
interface IProps {
passkey: Passkey;
diff --git a/apps/accounts/src/pages/passkeys/PasskeysList.tsx b/apps/accounts/src/pages/passkeys/PasskeysList.tsx
index 84a501a003..fd2c1538bb 100644
--- a/apps/accounts/src/pages/passkeys/PasskeysList.tsx
+++ b/apps/accounts/src/pages/passkeys/PasskeysList.tsx
@@ -1,8 +1,8 @@
-import { MenuItemGroup } from '@ente/shared/components/Menu/MenuItemGroup';
-import { Passkey } from 'types/passkey';
-import PasskeyListItem from './PasskeyListItem';
-import MenuItemDivider from '@ente/shared/components/Menu/MenuItemDivider';
-import { Fragment } from 'react';
+import MenuItemDivider from "@ente/shared/components/Menu/MenuItemDivider";
+import { MenuItemGroup } from "@ente/shared/components/Menu/MenuItemGroup";
+import { Fragment } from "react";
+import { Passkey } from "types/passkey";
+import PasskeyListItem from "./PasskeyListItem";
interface IProps {
passkeys: Passkey[];
diff --git a/apps/accounts/src/pages/passkeys/RenamePasskeyModal.tsx b/apps/accounts/src/pages/passkeys/RenamePasskeyModal.tsx
index 7d1fe47f0c..ad4f4a2f55 100644
--- a/apps/accounts/src/pages/passkeys/RenamePasskeyModal.tsx
+++ b/apps/accounts/src/pages/passkeys/RenamePasskeyModal.tsx
@@ -1,10 +1,10 @@
-import DialogBoxV2 from '@ente/shared/components/DialogBoxV2';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { PasskeysContext } from '.';
-import SingleInputForm from '@ente/shared/components/SingleInputForm';
-import { t } from 'i18next';
-import { renamePasskey } from 'services/passkeysService';
+import DialogBoxV2 from "@ente/shared/components/DialogBoxV2";
+import SingleInputForm from "@ente/shared/components/SingleInputForm";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
+import { renamePasskey } from "services/passkeysService";
+import { PasskeysContext } from ".";
interface IProps {
open: boolean;
@@ -34,17 +34,18 @@ const RenamePasskeyModal = (props: IProps) => {
onClose={props.onClose}
fullScreen={isMobile}
attributes={{
- title: t('RENAME_PASSKEY'),
+ title: t("RENAME_PASSKEY"),
secondary: {
action: props.onClose,
- text: t('CANCEL'),
+ text: t("CANCEL"),
},
- }}>
+ }}
+ >
<SingleInputForm
initialValue={selectedPasskey?.friendlyName}
callback={onSubmit}
- placeholder={t('ENTER_PASSKEY_NAME')}
- buttonText={t('RENAME')}
+ placeholder={t("ENTER_PASSKEY_NAME")}
+ buttonText={t("RENAME")}
fieldType="text"
secondaryButtonAction={props.onClose}
submitButtonProps={{ sx: { mt: 1, mb: 2 } }}
diff --git a/apps/accounts/src/pages/passkeys/finish.tsx b/apps/accounts/src/pages/passkeys/finish.tsx
index 708b69228d..11f03ee5c2 100644
--- a/apps/accounts/src/pages/passkeys/finish.tsx
+++ b/apps/accounts/src/pages/passkeys/finish.tsx
@@ -1,4 +1,4 @@
-import PasskeysFinishPage from '@ente/accounts/pages/passkeys/finish';
+import PasskeysFinishPage from "@ente/accounts/pages/passkeys/finish";
const PasskeysFinish = () => {
return <PasskeysFinishPage />;
};
diff --git a/apps/accounts/src/pages/passkeys/flow/index.tsx b/apps/accounts/src/pages/passkeys/flow/index.tsx
index 8134e17468..61c56a97cf 100644
--- a/apps/accounts/src/pages/passkeys/flow/index.tsx
+++ b/apps/accounts/src/pages/passkeys/flow/index.tsx
@@ -1,25 +1,25 @@
-import { APPS, CLIENT_PACKAGE_NAMES } from '@ente/shared/apps/constants';
+import { APPS, CLIENT_PACKAGE_NAMES } from "@ente/shared/apps/constants";
import {
CenteredFlex,
VerticallyCentered,
-} from '@ente/shared/components/Container';
-import EnteButton from '@ente/shared/components/EnteButton';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import FormPaper from '@ente/shared/components/Form/FormPaper';
-import HTTPService from '@ente/shared/network/HTTPService';
-import { logError } from '@ente/shared/sentry';
-import { LS_KEYS, setData } from '@ente/shared/storage/localStorage';
-import InfoIcon from '@mui/icons-material/Info';
-import { Box, Typography } from '@mui/material';
-import { t } from 'i18next';
-import _sodium from 'libsodium-wrappers';
-import Image from 'next/image';
-import { useEffect, useState } from 'react';
+} from "@ente/shared/components/Container";
+import EnteButton from "@ente/shared/components/EnteButton";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import FormPaper from "@ente/shared/components/Form/FormPaper";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { logError } from "@ente/shared/sentry";
+import { LS_KEYS, setData } from "@ente/shared/storage/localStorage";
+import InfoIcon from "@mui/icons-material/Info";
+import { Box, Typography } from "@mui/material";
+import { t } from "i18next";
+import _sodium from "libsodium-wrappers";
+import Image from "next/image";
+import { useEffect, useState } from "react";
import {
BeginPasskeyAuthenticationResponse,
beginPasskeyAuthentication,
finishPasskeyAuthentication,
-} from 'services/passkeysService';
+} from "services/passkeysService";
const PasskeysFlow = () => {
const [errored, setErrored] = useState(false);
@@ -32,18 +32,18 @@ const PasskeysFlow = () => {
const searchParams = new URLSearchParams(window.location.search);
// get redirect from the query params
- const redirect = searchParams.get('redirect') as string;
+ const redirect = searchParams.get("redirect") as string;
const redirectURL = new URL(redirect);
- if (process.env.NEXT_PUBLIC_DISABLE_REDIRECT_CHECK !== 'true') {
+ if (process.env.NEXT_PUBLIC_DISABLE_REDIRECT_CHECK !== "true") {
if (
- redirect !== '' &&
+ redirect !== "" &&
!(
- redirectURL.host.endsWith('.ente.io') ||
- redirectURL.host.endsWith('bada-frame.pages.dev')
+ redirectURL.host.endsWith(".ente.io") ||
+ redirectURL.host.endsWith("bada-frame.pages.dev")
) &&
- redirectURL.protocol !== 'ente:' &&
- redirectURL.protocol !== 'enteauth:'
+ redirectURL.protocol !== "ente:" &&
+ redirectURL.protocol !== "enteauth:"
) {
setInvalidInfo(true);
setLoading(false);
@@ -52,19 +52,19 @@ const PasskeysFlow = () => {
}
let pkg = CLIENT_PACKAGE_NAMES.get(APPS.PHOTOS);
- if (redirectURL.protocol === 'enteauth:') {
+ if (redirectURL.protocol === "enteauth:") {
pkg = CLIENT_PACKAGE_NAMES.get(APPS.AUTH);
- } else if (redirectURL.hostname.startsWith('accounts')) {
+ } else if (redirectURL.hostname.startsWith("accounts")) {
pkg = CLIENT_PACKAGE_NAMES.get(APPS.ACCOUNTS);
}
setData(LS_KEYS.CLIENT_PACKAGE, { name: pkg });
HTTPService.setHeaders({
- 'X-Client-Package': pkg,
+ "X-Client-Package": pkg,
});
// get passkeySessionID from the query params
- const passkeySessionID = searchParams.get('passkeySessionID') as string;
+ const passkeySessionID = searchParams.get("passkeySessionID") as string;
setLoading(true);
@@ -100,7 +100,7 @@ const PasskeysFlow = () => {
if (!credential) {
if (!isWebAuthnSupported()) {
- alert('WebAuthn is not supported in this browser');
+ alert("WebAuthn is not supported in this browser");
}
setErrored(true);
return;
@@ -114,7 +114,7 @@ const PasskeysFlow = () => {
finishData = await finishAuthentication(
credential,
passkeySessionID,
- beginData.ceremonySessionID
+ beginData.ceremonySessionID,
);
} catch (e) {
logError(e, "Couldn't finish passkey authentication");
@@ -142,28 +142,28 @@ const PasskeysFlow = () => {
const getCredential = async (
publicKey: any,
- timeoutMillis: number = 60000 // Default timeout of 60 seconds
+ timeoutMillis: number = 60000, // Default timeout of 60 seconds
): Promise<Credential | null> => {
publicKey.challenge = _sodium.from_base64(
publicKey.challenge,
- _sodium.base64_variants.URLSAFE_NO_PADDING
+ _sodium.base64_variants.URLSAFE_NO_PADDING,
);
publicKey.allowCredentials?.forEach(function (listItem: any) {
listItem.id = _sodium.from_base64(
listItem.id,
- _sodium.base64_variants.URLSAFE_NO_PADDING
+ _sodium.base64_variants.URLSAFE_NO_PADDING,
);
// note: we are orverwriting the transports array with all possible values.
// This is because the browser will only prompt the user for the transport that is available.
// Warning: In case of invalid transport value, the webauthn will fail on Safari & iOS browsers
- listItem.transports = ['usb', 'nfc', 'ble', 'internal'];
+ listItem.transports = ["usb", "nfc", "ble", "internal"];
});
publicKey.timeout = timeoutMillis;
const publicKeyCredentialCreationOptions: CredentialRequestOptions = {
publicKey: publicKey,
};
const credential = await navigator.credentials.get(
- publicKeyCredentialCreationOptions
+ publicKeyCredentialCreationOptions,
);
return credential;
};
@@ -171,12 +171,12 @@ const PasskeysFlow = () => {
const finishAuthentication = async (
credential: Credential,
sessionId: string,
- ceremonySessionId: string
+ ceremonySessionId: string,
) => {
const data = await finishPasskeyAuthentication(
credential,
sessionId,
- ceremonySessionId
+ ceremonySessionId,
);
return data;
};
@@ -199,18 +199,20 @@ const PasskeysFlow = () => {
display="flex"
justifyContent="center"
alignItems="center"
- height="100%">
+ height="100%"
+ >
<Box maxWidth="30rem">
<FormPaper
style={{
- padding: '1rem',
- }}>
+ padding: "1rem",
+ }}
+ >
<InfoIcon />
<Typography fontWeight="bold" variant="h1">
- {t('PASSKEY_LOGIN_FAILED')}
+ {t("PASSKEY_LOGIN_FAILED")}
</Typography>
<Typography marginTop="1rem">
- {t('PASSKEY_LOGIN_URL_INVALID')}
+ {t("PASSKEY_LOGIN_URL_INVALID")}
</Typography>
</FormPaper>
</Box>
@@ -224,18 +226,20 @@ const PasskeysFlow = () => {
display="flex"
justifyContent="center"
alignItems="center"
- height="100%">
+ height="100%"
+ >
<Box maxWidth="30rem">
<FormPaper
style={{
- padding: '1rem',
- }}>
+ padding: "1rem",
+ }}
+ >
<InfoIcon />
<Typography fontWeight="bold" variant="h1">
- {t('PASSKEY_LOGIN_FAILED')}
+ {t("PASSKEY_LOGIN_FAILED")}
</Typography>
<Typography marginTop="1rem">
- {t('PASSKEY_LOGIN_ERRORED')}
+ {t("PASSKEY_LOGIN_ERRORED")}
</Typography>
<EnteButton
onClick={() => {
@@ -244,12 +248,13 @@ const PasskeysFlow = () => {
}}
fullWidth
style={{
- marginTop: '1rem',
+ marginTop: "1rem",
}}
color="primary"
type="button"
- variant="contained">
- {t('TRY_AGAIN')}
+ variant="contained"
+ >
+ {t("TRY_AGAIN")}
</EnteButton>
</FormPaper>
</Box>
@@ -263,18 +268,20 @@ const PasskeysFlow = () => {
display="flex"
justifyContent="center"
alignItems="center"
- height="100%">
+ height="100%"
+ >
<Box maxWidth="30rem">
<FormPaper
style={{
- padding: '1rem',
- }}>
+ padding: "1rem",
+ }}
+ >
<InfoIcon />
<Typography fontWeight="bold" variant="h1">
- {t('LOGIN_WITH_PASSKEY')}
+ {t("LOGIN_WITH_PASSKEY")}
</Typography>
<Typography marginTop="1rem">
- {t('PASSKEY_FOLLOW_THE_STEPS_FROM_YOUR_BROWSER')}
+ {t("PASSKEY_FOLLOW_THE_STEPS_FROM_YOUR_BROWSER")}
</Typography>
<CenteredFlex marginTop="1rem">
<Image
diff --git a/apps/accounts/src/pages/passkeys/index.tsx b/apps/accounts/src/pages/passkeys/index.tsx
index 23161e315c..f41d8e3f28 100644
--- a/apps/accounts/src/pages/passkeys/index.tsx
+++ b/apps/accounts/src/pages/passkeys/index.tsx
@@ -1,14 +1,14 @@
-import { CenteredFlex } from '@ente/shared/components/Container';
-import FormPaper from '@ente/shared/components/Form/FormPaper';
-import SingleInputForm from '@ente/shared/components/SingleInputForm';
-import { ACCOUNTS_PAGES } from '@ente/shared/constants/pages';
-import { logError } from '@ente/shared/sentry';
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
-import { Box, Typography } from '@mui/material';
-import { t } from 'i18next';
-import _sodium from 'libsodium-wrappers';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
+import { CenteredFlex } from "@ente/shared/components/Container";
+import FormPaper from "@ente/shared/components/Form/FormPaper";
+import SingleInputForm from "@ente/shared/components/SingleInputForm";
+import { ACCOUNTS_PAGES } from "@ente/shared/constants/pages";
+import { logError } from "@ente/shared/sentry";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
+import { Box, Typography } from "@mui/material";
+import { t } from "i18next";
+import _sodium from "libsodium-wrappers";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
import {
Dispatch,
SetStateAction,
@@ -16,15 +16,15 @@ import {
useContext,
useEffect,
useState,
-} from 'react';
-import { Passkey } from 'types/passkey';
+} from "react";
+import { Passkey } from "types/passkey";
import {
finishPasskeyRegistration,
getPasskeyRegistrationOptions,
getPasskeys,
-} from '../../services/passkeysService';
-import ManagePasskeyDrawer from './ManagePasskeyDrawer';
-import PasskeysList from './PasskeysList';
+} from "../../services/passkeysService";
+import ManagePasskeyDrawer from "./ManagePasskeyDrawer";
+import PasskeysList from "./PasskeysList";
export const PasskeysContext = createContext(
{} as {
@@ -32,14 +32,14 @@ export const PasskeysContext = createContext(
setSelectedPasskey: Dispatch<SetStateAction<Passkey | null>>;
setShowPasskeyDrawer: Dispatch<SetStateAction<boolean>>;
refreshPasskeys: () => void;
- }
+ },
);
const Passkeys = () => {
const { showNavBar } = useContext(AppContext);
const [selectedPasskey, setSelectedPasskey] = useState<Passkey | null>(
- null
+ null,
);
const [showPasskeyDrawer, setShowPasskeyDrawer] = useState(false);
@@ -69,7 +69,7 @@ const Passkeys = () => {
const handleSubmit = async (
inputValue: string,
setFieldError: (errorMessage: string) => void,
- resetForm: (nextState?: unknown) => void
+ resetForm: (nextState?: unknown) => void,
) => {
let response: {
options: {
@@ -81,7 +81,7 @@ const Passkeys = () => {
try {
response = await getPasskeyRegistrationOptions();
} catch {
- setFieldError('Failed to begin registration');
+ setFieldError("Failed to begin registration");
return;
}
@@ -90,12 +90,12 @@ const Passkeys = () => {
options.publicKey.challenge = _sodium.from_base64(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
- options.publicKey.challenge
+ options.publicKey.challenge,
);
options.publicKey.user.id = _sodium.from_base64(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
- options.publicKey.user.id
+ options.publicKey.user.id,
);
// create new credential
@@ -104,8 +104,8 @@ const Passkeys = () => {
try {
newCredential = await navigator.credentials.create(options);
} catch (e) {
- logError(e, 'Error creating credential');
- setFieldError('Failed to create credential');
+ logError(e, "Error creating credential");
+ setFieldError("Failed to create credential");
return;
}
@@ -113,10 +113,10 @@ const Passkeys = () => {
await finishPasskeyRegistration(
inputValue,
newCredential,
- response.sessionID
+ response.sessionID,
);
} catch {
- setFieldError('Failed to finish registration');
+ setFieldError("Failed to finish registration");
return;
}
@@ -132,21 +132,23 @@ const Passkeys = () => {
setSelectedPasskey,
setShowPasskeyDrawer,
refreshPasskeys: init,
- }}>
+ }}
+ >
<CenteredFlex>
<Box maxWidth="20rem">
<Box marginBottom="1rem">
- <Typography>{t('PASSKEYS_DESCRIPTION')}</Typography>
+ <Typography>{t("PASSKEYS_DESCRIPTION")}</Typography>
</Box>
<FormPaper
style={{
- padding: '1rem',
- }}>
+ padding: "1rem",
+ }}
+ >
<SingleInputForm
fieldType="text"
- placeholder={t('ENTER_PASSKEY_NAME')}
- buttonText={t('ADD_PASSKEY')}
- initialValue={''}
+ placeholder={t("ENTER_PASSKEY_NAME")}
+ buttonText={t("ADD_PASSKEY")}
+ initialValue={""}
callback={handleSubmit}
submitButtonProps={{
sx: {
diff --git a/apps/accounts/src/pages/recover/index.tsx b/apps/accounts/src/pages/recover/index.tsx
index 976791015e..6f718a207f 100644
--- a/apps/accounts/src/pages/recover/index.tsx
+++ b/apps/accounts/src/pages/recover/index.tsx
@@ -1,8 +1,8 @@
-import RecoverPage from '@ente/accounts/pages/recover';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import RecoverPage from "@ente/accounts/pages/recover";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Recover() {
const appContext = useContext(AppContext);
diff --git a/apps/accounts/src/pages/signup/index.tsx b/apps/accounts/src/pages/signup/index.tsx
index ead1cc5c85..1e0f576a67 100644
--- a/apps/accounts/src/pages/signup/index.tsx
+++ b/apps/accounts/src/pages/signup/index.tsx
@@ -1,8 +1,8 @@
-import SignupPage from '@ente/accounts/pages/signup';
-import { APPS } from '@ente/shared/apps/constants';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
+import SignupPage from "@ente/accounts/pages/signup";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Sigup() {
const appContext = useContext(AppContext);
diff --git a/apps/accounts/src/pages/two-factor/recover/index.tsx b/apps/accounts/src/pages/two-factor/recover/index.tsx
index 39055fe43f..e6b2036faf 100644
--- a/apps/accounts/src/pages/two-factor/recover/index.tsx
+++ b/apps/accounts/src/pages/two-factor/recover/index.tsx
@@ -1,8 +1,8 @@
-import TwoFactorRecoverPage from '@ente/accounts/pages/two-factor/recover';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import TwoFactorRecoverPage from "@ente/accounts/pages/two-factor/recover";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function TwoFactorRecover() {
const appContext = useContext(AppContext);
diff --git a/apps/accounts/src/pages/two-factor/setup/index.tsx b/apps/accounts/src/pages/two-factor/setup/index.tsx
index 849b2f78ba..f1b0e8f76d 100644
--- a/apps/accounts/src/pages/two-factor/setup/index.tsx
+++ b/apps/accounts/src/pages/two-factor/setup/index.tsx
@@ -1,8 +1,8 @@
-import TwoFactorSetupPage from '@ente/accounts/pages/two-factor/setup';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import TwoFactorSetupPage from "@ente/accounts/pages/two-factor/setup";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function TwoFactorSetup() {
const appContext = useContext(AppContext);
diff --git a/apps/accounts/src/pages/two-factor/verify/index.tsx b/apps/accounts/src/pages/two-factor/verify/index.tsx
index dbb01bdada..b17882d3bb 100644
--- a/apps/accounts/src/pages/two-factor/verify/index.tsx
+++ b/apps/accounts/src/pages/two-factor/verify/index.tsx
@@ -1,8 +1,8 @@
-import TwoFactorVerifyPage from '@ente/accounts/pages/two-factor/verify';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import TwoFactorVerifyPage from "@ente/accounts/pages/two-factor/verify";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function TwoFactorVerify() {
const appContext = useContext(AppContext);
diff --git a/apps/accounts/src/pages/verify/index.tsx b/apps/accounts/src/pages/verify/index.tsx
index 54f1081d9b..467419d0aa 100644
--- a/apps/accounts/src/pages/verify/index.tsx
+++ b/apps/accounts/src/pages/verify/index.tsx
@@ -1,8 +1,8 @@
-import VerifyPage from '@ente/accounts/pages/verify';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import VerifyPage from "@ente/accounts/pages/verify";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Verify() {
const appContext = useContext(AppContext);
diff --git a/apps/accounts/src/services/passkeysService.ts b/apps/accounts/src/services/passkeysService.ts
index 277312640c..ecc6ad406c 100644
--- a/apps/accounts/src/services/passkeysService.ts
+++ b/apps/accounts/src/services/passkeysService.ts
@@ -1,8 +1,8 @@
-import HTTPService from '@ente/shared/network/HTTPService';
-import { getEndpoint } from '@ente/shared/network/api';
-import { logError } from '@ente/shared/sentry';
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
-import _sodium from 'libsodium-wrappers';
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getEndpoint } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
+import _sodium from "libsodium-wrappers";
const ENDPOINT = getEndpoint();
export const getPasskeys = async () => {
@@ -12,11 +12,11 @@ export const getPasskeys = async () => {
const response = await HTTPService.get(
`${ENDPOINT}/passkeys`,
{},
- { 'X-Auth-Token': token }
+ { "X-Auth-Token": token },
);
return await response.data;
} catch (e) {
- logError(e, 'get passkeys failed');
+ logError(e, "get passkeys failed");
throw e;
}
};
@@ -29,11 +29,11 @@ export const renamePasskey = async (id: string, name: string) => {
`${ENDPOINT}/passkeys/${id}`,
{},
{ friendlyName: name },
- { 'X-Auth-Token': token }
+ { "X-Auth-Token": token },
);
return await response.data;
} catch (e) {
- logError(e, 'rename passkey failed');
+ logError(e, "rename passkey failed");
throw e;
}
};
@@ -46,11 +46,11 @@ export const deletePasskey = async (id: string) => {
`${ENDPOINT}/passkeys/${id}`,
{},
{},
- { 'X-Auth-Token': token }
+ { "X-Auth-Token": token },
);
return await response.data;
} catch (e) {
- logError(e, 'delete passkey failed');
+ logError(e, "delete passkey failed");
throw e;
}
};
@@ -63,12 +63,12 @@ export const getPasskeyRegistrationOptions = async () => {
`${ENDPOINT}/passkeys/registration/begin`,
{},
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
return await response.data;
} catch (e) {
- logError(e, 'get passkey registration options failed');
+ logError(e, "get passkey registration options failed");
throw e;
}
};
@@ -76,20 +76,20 @@ export const getPasskeyRegistrationOptions = async () => {
export const finishPasskeyRegistration = async (
friendlyName: string,
credential: Credential,
- sessionId: string
+ sessionId: string,
) => {
try {
const attestationObjectB64 = _sodium.to_base64(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
new Uint8Array(credential.response.attestationObject),
- _sodium.base64_variants.URLSAFE_NO_PADDING
+ _sodium.base64_variants.URLSAFE_NO_PADDING,
);
const clientDataJSONB64 = _sodium.to_base64(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
new Uint8Array(credential.response.clientDataJSON),
- _sodium.base64_variants.URLSAFE_NO_PADDING
+ _sodium.base64_variants.URLSAFE_NO_PADDING,
);
const token = getToken();
@@ -111,12 +111,12 @@ export const finishPasskeyRegistration = async (
sessionID: sessionId,
},
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
return await response.data;
} catch (e) {
- logError(e, 'finish passkey registration failed');
+ logError(e, "finish passkey registration failed");
throw e;
}
};
@@ -130,19 +130,19 @@ interface Options {
}
export const beginPasskeyAuthentication = async (
- sessionId: string
+ sessionId: string,
): Promise<BeginPasskeyAuthenticationResponse> => {
try {
const data = await HTTPService.post(
`${ENDPOINT}/users/two-factor/passkeys/begin`,
{
sessionID: sessionId,
- }
+ },
);
return data.data;
} catch (e) {
- logError(e, 'begin passkey authentication failed');
+ logError(e, "begin passkey authentication failed");
throw e;
}
};
@@ -150,7 +150,7 @@ export const beginPasskeyAuthentication = async (
export const finishPasskeyAuthentication = async (
credential: Credential,
sessionId: string,
- ceremonySessionId: string
+ ceremonySessionId: string,
) => {
try {
const data = await HTTPService.post(
@@ -164,37 +164,37 @@ export const finishPasskeyAuthentication = async (
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
new Uint8Array(credential.response.authenticatorData),
- _sodium.base64_variants.URLSAFE_NO_PADDING
+ _sodium.base64_variants.URLSAFE_NO_PADDING,
),
clientDataJSON: _sodium.to_base64(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
new Uint8Array(credential.response.clientDataJSON),
- _sodium.base64_variants.URLSAFE_NO_PADDING
+ _sodium.base64_variants.URLSAFE_NO_PADDING,
),
signature: _sodium.to_base64(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
new Uint8Array(credential.response.signature),
- _sodium.base64_variants.URLSAFE_NO_PADDING
+ _sodium.base64_variants.URLSAFE_NO_PADDING,
),
userHandle: _sodium.to_base64(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
new Uint8Array(credential.response.userHandle),
- _sodium.base64_variants.URLSAFE_NO_PADDING
+ _sodium.base64_variants.URLSAFE_NO_PADDING,
),
},
},
{
sessionID: sessionId,
ceremonySessionID: ceremonySessionId,
- }
+ },
);
return data.data;
} catch (e) {
- logError(e, 'finish passkey authentication failed');
+ logError(e, "finish passkey authentication failed");
throw e;
}
};
diff --git a/apps/accounts/src/styles/global.css b/apps/accounts/src/styles/global.css
index 5f8cd275ca..0ea6c125da 100644
--- a/apps/accounts/src/styles/global.css
+++ b/apps/accounts/src/styles/global.css
@@ -1,39 +1,39 @@
/* inter-regular - latin */
@font-face {
- font-family: 'Inter';
+ font-family: "Inter";
font-style: normal;
font-weight: 400;
src:
- local(''),
- url('/fonts/inter-v11-latin-500.woff2') format('woff2'),
+ local(""),
+ url("/fonts/inter-v11-latin-500.woff2") format("woff2"),
/* Chrome 26+, Opera 23+, Firefox 39+ */
- url('/fonts/inter-v11-latin-500.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
+ url("/fonts/inter-v11-latin-500.woff") format("woff"); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
font-display: swap; /*https://web.dev/font-display/?utm_source=lighthouse&utm_medium=devtools#how-to-avoid-showing-invisible-text*/
}
/* inter-600 - latin */
@font-face {
- font-family: 'Inter';
+ font-family: "Inter";
font-style: normal;
font-weight: 700;
src:
- local(''),
- url('/fonts/inter-v11-latin-600.woff2') format('woff2'),
+ local(""),
+ url("/fonts/inter-v11-latin-600.woff2") format("woff2"),
/* Chrome 26+, Opera 23+, Firefox 39+ */
- url('/fonts/inter-v11-latin-600.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
+ url("/fonts/inter-v11-latin-600.woff") format("woff"); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
font-display: swap;
}
/* inter-800 - latin */
@font-face {
- font-family: 'Inter';
+ font-family: "Inter";
font-style: normal;
font-weight: 900;
src:
- local(''),
- url('/fonts/inter-v11-latin-800.woff2') format('woff2'),
+ local(""),
+ url("/fonts/inter-v11-latin-800.woff2") format("woff2"),
/* Chrome 26+, Opera 23+, Firefox 39+ */
- url('/fonts/inter-v11-latin-800.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
+ url("/fonts/inter-v11-latin-800.woff") format("woff"); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
font-display: swap;
}
diff --git a/apps/auth/.eslintrc.js b/apps/auth/.eslintrc.js
index 7ddcebe961..b1c4c2e168 100644
--- a/apps/auth/.eslintrc.js
+++ b/apps/auth/.eslintrc.js
@@ -3,11 +3,11 @@ module.exports = {
// This is required here to ensure desktop picks the right eslint config, where this app is
// packaged as a submodule.
root: true,
- extends: ['@ente/eslint-config'],
- parser: '@typescript-eslint/parser',
+ extends: ["@ente/eslint-config"],
+ parser: "@typescript-eslint/parser",
parserOptions: {
tsconfigRootDir: __dirname,
- project: './tsconfig.json',
+ project: "./tsconfig.json",
},
- ignorePatterns: ['.eslintrc.js', 'out'],
+ ignorePatterns: [".eslintrc.js", "out"],
};
diff --git a/apps/auth/next.config.js b/apps/auth/next.config.js
index 57e1c5c8b5..eea88bf938 100644
--- a/apps/auth/next.config.js
+++ b/apps/auth/next.config.js
@@ -1,3 +1,3 @@
-const nextConfigBase = require('@/next/next.config.base.js');
+const nextConfigBase = require("@/next/next.config.base.js");
module.exports = nextConfigBase;
diff --git a/apps/auth/sentry.client.config.ts b/apps/auth/sentry.client.config.ts
index 2ff5f43457..373718e8eb 100644
--- a/apps/auth/sentry.client.config.ts
+++ b/apps/auth/sentry.client.config.ts
@@ -1,3 +1,3 @@
-import { initSentry } from '@ente/shared/sentry/config/sentry.config.base';
+import { initSentry } from "@ente/shared/sentry/config/sentry.config.base";
-initSentry('https://[email protected]/8');
+initSentry("https://[email protected]/8");
diff --git a/apps/auth/src/components/AuthFooter.tsx b/apps/auth/src/components/AuthFooter.tsx
index 56a5a328f9..0d3a750588 100644
--- a/apps/auth/src/components/AuthFooter.tsx
+++ b/apps/auth/src/components/AuthFooter.tsx
@@ -1,18 +1,19 @@
-import { Button } from '@mui/material';
-import { t } from 'i18next';
+import { Button } from "@mui/material";
+import { t } from "i18next";
export const AuthFooter = () => {
return (
<div
style={{
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- justifyContent: 'center',
- }}>
- <p>{t('AUTH_DOWNLOAD_MOBILE_APP')}</p>
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ justifyContent: "center",
+ }}
+ >
+ <p>{t("AUTH_DOWNLOAD_MOBILE_APP")}</p>
<a href="https://github.com/ente-io/auth#-download" download>
- <Button color="accent">{t('DOWNLOAD')}</Button>
+ <Button color="accent">{t("DOWNLOAD")}</Button>
</a>
</div>
);
diff --git a/apps/auth/src/components/Navbar.tsx b/apps/auth/src/components/Navbar.tsx
index 59505efe0e..293d7fc16a 100644
--- a/apps/auth/src/components/Navbar.tsx
+++ b/apps/auth/src/components/Navbar.tsx
@@ -1,31 +1,33 @@
-import { HorizontalFlex } from '@ente/shared/components/Container';
-import NavbarBase from '@ente/shared/components/Navbar/base';
-import React from 'react';
-import { t } from 'i18next';
-import { logoutUser } from '@ente/accounts/services/user';
-import { EnteLogo } from '@ente/shared/components/EnteLogo';
-import OverflowMenu from '@ente/shared/components/OverflowMenu/menu';
-import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';
-import MoreHoriz from '@mui/icons-material/MoreHoriz';
-import LogoutOutlined from '@mui/icons-material/LogoutOutlined';
-import { AppContext } from 'pages/_app';
+import { logoutUser } from "@ente/accounts/services/user";
+import { HorizontalFlex } from "@ente/shared/components/Container";
+import { EnteLogo } from "@ente/shared/components/EnteLogo";
+import NavbarBase from "@ente/shared/components/Navbar/base";
+import OverflowMenu from "@ente/shared/components/OverflowMenu/menu";
+import { OverflowMenuOption } from "@ente/shared/components/OverflowMenu/option";
+import LogoutOutlined from "@mui/icons-material/LogoutOutlined";
+import MoreHoriz from "@mui/icons-material/MoreHoriz";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import React from "react";
export default function AuthNavbar() {
const { isMobile } = React.useContext(AppContext);
return (
<NavbarBase isMobile={isMobile}>
- <HorizontalFlex flex={1} justifyContent={'center'}>
+ <HorizontalFlex flex={1} justifyContent={"center"}>
<EnteLogo />
</HorizontalFlex>
- <HorizontalFlex position={'absolute'} right="24px">
+ <HorizontalFlex position={"absolute"} right="24px">
<OverflowMenu
- ariaControls={'auth-options'}
- triggerButtonIcon={<MoreHoriz />}>
+ ariaControls={"auth-options"}
+ triggerButtonIcon={<MoreHoriz />}
+ >
<OverflowMenuOption
color="critical"
startIcon={<LogoutOutlined />}
- onClick={logoutUser}>
- {t('LOGOUT')}
+ onClick={logoutUser}
+ >
+ {t("LOGOUT")}
</OverflowMenuOption>
</OverflowMenu>
</HorizontalFlex>
diff --git a/apps/auth/src/components/OTPDisplay.tsx b/apps/auth/src/components/OTPDisplay.tsx
index d8920c7c36..38de665aa6 100644
--- a/apps/auth/src/components/OTPDisplay.tsx
+++ b/apps/auth/src/components/OTPDisplay.tsx
@@ -1,98 +1,107 @@
-import React, { useState, useEffect } from 'react';
-import { TOTP, HOTP } from 'otpauth';
-import { Code } from 'types/code';
-import TimerProgress from './TimerProgress';
-import { t } from 'i18next';
-import { ButtonBase, Snackbar } from '@mui/material';
+import { ButtonBase, Snackbar } from "@mui/material";
+import { t } from "i18next";
+import { HOTP, TOTP } from "otpauth";
+import { useEffect, useState } from "react";
+import { Code } from "types/code";
+import TimerProgress from "./TimerProgress";
const TOTPDisplay = ({ issuer, account, code, nextCode, period }) => {
return (
<div
style={{
- backgroundColor: 'rgba(40, 40, 40, 0.6)',
- borderRadius: '4px',
- overflow: 'hidden',
- }}>
+ backgroundColor: "rgba(40, 40, 40, 0.6)",
+ borderRadius: "4px",
+ overflow: "hidden",
+ }}
+ >
<TimerProgress period={period ?? Code.defaultPeriod} />
<div
style={{
- padding: '12px 20px 0px 20px',
- display: 'flex',
- alignItems: 'flex-start',
- minWidth: '320px',
- minHeight: '120px',
- justifyContent: 'space-between',
- }}>
+ padding: "12px 20px 0px 20px",
+ display: "flex",
+ alignItems: "flex-start",
+ minWidth: "320px",
+ minHeight: "120px",
+ justifyContent: "space-between",
+ }}
+ >
<div
style={{
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'flex-start',
- minWidth: '200px',
- }}>
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "flex-start",
+ minWidth: "200px",
+ }}
+ >
<p
style={{
- fontWeight: 'bold',
- margin: '0px',
- fontSize: '14px',
- textAlign: 'left',
- }}>
+ fontWeight: "bold",
+ margin: "0px",
+ fontSize: "14px",
+ textAlign: "left",
+ }}
+ >
{issuer}
</p>
<p
style={{
- marginTop: '0px',
- marginBottom: '8px',
- textAlign: 'left',
- fontSize: '12px',
- maxWidth: '200px',
- minHeight: '16px',
- color: 'grey',
- }}>
+ marginTop: "0px",
+ marginBottom: "8px",
+ textAlign: "left",
+ fontSize: "12px",
+ maxWidth: "200px",
+ minHeight: "16px",
+ color: "grey",
+ }}
+ >
{account}
</p>
<p
style={{
- margin: '0px',
- marginBottom: '1rem',
- fontSize: '24px',
- fontWeight: 'bold',
- textAlign: 'left',
- }}>
+ margin: "0px",
+ marginBottom: "1rem",
+ fontSize: "24px",
+ fontWeight: "bold",
+ textAlign: "left",
+ }}
+ >
{code}
</p>
</div>
<div style={{ flex: 1 }} />
<div
style={{
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'flex-end',
- minWidth: '120px',
- textAlign: 'right',
- marginTop: 'auto',
- marginBottom: '1rem',
- }}>
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "flex-end",
+ minWidth: "120px",
+ textAlign: "right",
+ marginTop: "auto",
+ marginBottom: "1rem",
+ }}
+ >
<p
style={{
- fontWeight: 'bold',
- marginBottom: '0px',
- fontSize: '10px',
- marginTop: 'auto',
- textAlign: 'right',
- color: 'grey',
- }}>
- {t('AUTH_NEXT')}
+ fontWeight: "bold",
+ marginBottom: "0px",
+ fontSize: "10px",
+ marginTop: "auto",
+ textAlign: "right",
+ color: "grey",
+ }}
+ >
+ {t("AUTH_NEXT")}
</p>
<p
style={{
- fontSize: '14px',
- fontWeight: 'bold',
- marginBottom: '0px',
- marginTop: 'auto',
- textAlign: 'right',
- color: 'grey',
- }}>
+ fontSize: "14px",
+ fontWeight: "bold",
+ marginBottom: "0px",
+ marginTop: "auto",
+ textAlign: "right",
+ color: "grey",
+ }}
+ >
{nextCode}
</p>
</div>
@@ -111,7 +120,7 @@ function BadCodeInfo({ codeInfo, codeErr }) {
<div>
{showRawData ? (
<div onClick={() => setShowRawData(false)}>
- {codeInfo.rawData ?? 'no raw data'}
+ {codeInfo.rawData ?? "no raw data"}
</div>
) : (
<div onClick={() => setShowRawData(true)}>Show rawData</div>
@@ -127,15 +136,15 @@ interface OTPDisplayProps {
const OTPDisplay = (props: OTPDisplayProps) => {
const { codeInfo } = props;
- const [code, setCode] = useState('');
- const [nextCode, setNextCode] = useState('');
- const [codeErr, setCodeErr] = useState('');
+ const [code, setCode] = useState("");
+ const [nextCode, setNextCode] = useState("");
+ const [codeErr, setCodeErr] = useState("");
const [hasCopied, setHasCopied] = useState(false);
const generateCodes = () => {
try {
const currentTime = new Date().getTime();
- if (codeInfo.type.toLowerCase() === 'totp') {
+ if (codeInfo.type.toLowerCase() === "totp") {
const totp = new TOTP({
secret: codeInfo.secret,
algorithm: codeInfo.algorithm ?? Code.defaultAlgo,
@@ -146,9 +155,9 @@ const OTPDisplay = (props: OTPDisplayProps) => {
setNextCode(
totp.generate({
timestamp: currentTime + codeInfo.period * 1000,
- })
+ }),
);
- } else if (codeInfo.type.toLowerCase() === 'hotp') {
+ } else if (codeInfo.type.toLowerCase() === "hotp") {
const hotp = new HOTP({
secret: codeInfo.secret,
counter: 0,
@@ -184,8 +193,8 @@ const OTPDisplay = (props: OTPDisplayProps) => {
// we need to call generateCodes() once before the interval loop
// to set the initial code and nextCode
generateCodes();
- codeType.toLowerCase() === 'totp' ||
- codeType.toLowerCase() === 'hotp'
+ codeType.toLowerCase() === "totp" ||
+ codeType.toLowerCase() === "hotp"
? setInterval(() => {
generateCodes();
}, codePeriodInMs)
@@ -198,13 +207,14 @@ const OTPDisplay = (props: OTPDisplayProps) => {
}, [codeInfo]);
return (
- <div style={{ padding: '8px' }}>
- {codeErr === '' ? (
+ <div style={{ padding: "8px" }}>
+ {codeErr === "" ? (
<ButtonBase
component="div"
onClick={() => {
copyCode();
- }}>
+ }}
+ >
<TOTPDisplay
period={codeInfo.period}
issuer={codeInfo.issuer}
diff --git a/apps/auth/src/components/TimerProgress.tsx b/apps/auth/src/components/TimerProgress.tsx
index 110048dc33..d1f3726f66 100644
--- a/apps/auth/src/components/TimerProgress.tsx
+++ b/apps/auth/src/components/TimerProgress.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect } from 'react';
+import { useEffect, useState } from "react";
const TimerProgress = ({ period }) => {
const [progress, setProgress] = useState(0);
@@ -24,14 +24,14 @@ const TimerProgress = ({ period }) => {
return () => clearInterval(ticker);
}, []);
- const color = progress > 0.4 ? 'green' : 'orange';
+ const color = progress > 0.4 ? "green" : "orange";
return (
<div
style={{
- borderTopLeftRadius: '3px',
+ borderTopLeftRadius: "3px",
width: `${progress * 100}%`,
- height: '3px',
+ height: "3px",
backgroundColor: color,
}}
/>
diff --git a/apps/auth/src/pages/404.tsx b/apps/auth/src/pages/404.tsx
index 6d10e4dfb5..edb4ae7f75 100644
--- a/apps/auth/src/pages/404.tsx
+++ b/apps/auth/src/pages/404.tsx
@@ -1,8 +1,8 @@
-import NotFoundPage from '@ente/shared/next/pages/404';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import { APPS } from "@ente/shared/apps/constants";
+import NotFoundPage from "@ente/shared/next/pages/404";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function NotFound() {
const appContext = useContext(AppContext);
diff --git a/apps/auth/src/pages/_app.tsx b/apps/auth/src/pages/_app.tsx
index b25fb2511c..156f2e4554 100644
--- a/apps/auth/src/pages/_app.tsx
+++ b/apps/auth/src/pages/_app.tsx
@@ -1,42 +1,42 @@
-import React, { createContext, useEffect, useRef, useState } from 'react';
-import AppNavbar from '@ente/shared/components/Navbar/app';
-import { t } from 'i18next';
-
-import { useRouter } from 'next/router';
-import { Overlay } from '@ente/shared/components/Container';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { LS_KEYS } from '@ente/shared/storage/localStorage';
-import HTTPService from '@ente/shared/network/HTTPService';
-import Head from 'next/head';
-import LoadingBar from 'react-top-loading-bar';
-import DialogBoxV2 from '@ente/shared/components/DialogBoxV2';
-import { ThemeProvider } from '@mui/material/styles';
-import { MessageContainer } from '@ente/shared/components/MessageContainer';
-import { CssBaseline, useMediaQuery } from '@mui/material';
+import AppNavbar from "@ente/shared/components/Navbar/app";
+import { t } from "i18next";
+import { createContext, useEffect, useRef, useState } from "react";
+
+import { Overlay } from "@ente/shared/components/Container";
+import DialogBoxV2 from "@ente/shared/components/DialogBoxV2";
import {
DialogBoxAttributesV2,
SetDialogBoxAttributesV2,
-} from '@ente/shared/components/DialogBoxV2/types';
+} from "@ente/shared/components/DialogBoxV2/types";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import { MessageContainer } from "@ente/shared/components/MessageContainer";
import {
clearLogsIfLocalStorageLimitExceeded,
logStartupMessage,
-} from '@ente/shared/logging/web';
-
-import { CacheProvider } from '@emotion/react';
+} from "@ente/shared/logging/web";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { LS_KEYS } from "@ente/shared/storage/localStorage";
+import { CssBaseline, useMediaQuery } from "@mui/material";
+import { ThemeProvider } from "@mui/material/styles";
+import Head from "next/head";
+import { useRouter } from "next/router";
+import LoadingBar from "react-top-loading-bar";
+
+import { setupI18n } from "@/ui/i18n";
+import { CacheProvider } from "@emotion/react";
import {
APP_TITLES,
APPS,
CLIENT_PACKAGE_NAMES,
-} from '@ente/shared/apps/constants';
-import { EnteAppProps } from '@ente/shared/apps/types';
-import createEmotionCache from '@ente/shared/themes/createEmotionCache';
-import { THEME_COLOR } from '@ente/shared/themes/constants';
-import { SetTheme } from '@ente/shared/themes/types';
-import { setupI18n } from '@/ui/i18n';
-import { useLocalState } from '@ente/shared/hooks/useLocalState';
-import { PHOTOS_PAGES as PAGES } from '@ente/shared/constants/pages';
-import { getTheme } from '@ente/shared/themes';
-import '../../public/css/global.css';
+} from "@ente/shared/apps/constants";
+import { EnteAppProps } from "@ente/shared/apps/types";
+import { PHOTOS_PAGES as PAGES } from "@ente/shared/constants/pages";
+import { useLocalState } from "@ente/shared/hooks/useLocalState";
+import { getTheme } from "@ente/shared/themes";
+import { THEME_COLOR } from "@ente/shared/themes/constants";
+import createEmotionCache from "@ente/shared/themes/createEmotionCache";
+import { SetTheme } from "@ente/shared/themes/types";
+import "../../public/css/global.css";
type AppContextType = {
showNavBar: (show: boolean) => void;
@@ -64,7 +64,7 @@ export default function App(props: EnteAppProps) {
const [isI18nReady, setIsI18nReady] = useState<boolean>(false);
const [loading, setLoading] = useState(false);
const [offline, setOffline] = useState(
- typeof window !== 'undefined' && !window.navigator.onLine
+ typeof window !== "undefined" && !window.navigator.onLine,
);
const [showNavbar, setShowNavBar] = useState(false);
const isLoadingBarRunning = useRef(false);
@@ -72,10 +72,10 @@ export default function App(props: EnteAppProps) {
const [dialogBoxAttributeV2, setDialogBoxAttributesV2] =
useState<DialogBoxAttributesV2>();
const [dialogBoxV2View, setDialogBoxV2View] = useState(false);
- const isMobile = useMediaQuery('(max-width:428px)');
+ const isMobile = useMediaQuery("(max-width:428px)");
const [themeColor, setThemeColor] = useLocalState(
LS_KEYS.THEME,
- THEME_COLOR.DARK
+ THEME_COLOR.DARK,
);
useEffect(() => {
@@ -83,7 +83,7 @@ export default function App(props: EnteAppProps) {
setupI18n().finally(() => setIsI18nReady(true));
// set client package name in headers
HTTPService.setHeaders({
- 'X-Client-Package': CLIENT_PACKAGE_NAMES.get(APPS.AUTH),
+ "X-Client-Package": CLIENT_PACKAGE_NAMES.get(APPS.AUTH),
});
// setup logging
clearLogsIfLocalStorageLimitExceeded();
@@ -96,31 +96,31 @@ export default function App(props: EnteAppProps) {
useEffect(() => {
if (isI18nReady) {
console.log(
- `%c${t('CONSOLE_WARNING_STOP')}`,
- 'color: red; font-size: 52px;'
+ `%c${t("CONSOLE_WARNING_STOP")}`,
+ "color: red; font-size: 52px;",
);
- console.log(`%c${t('CONSOLE_WARNING_DESC')}`, 'font-size: 20px;');
+ console.log(`%c${t("CONSOLE_WARNING_DESC")}`, "font-size: 20px;");
}
}, [isI18nReady]);
useEffect(() => {
- router.events.on('routeChangeStart', (url: string) => {
- const newPathname = url.split('?')[0] as PAGES;
+ router.events.on("routeChangeStart", (url: string) => {
+ const newPathname = url.split("?")[0] as PAGES;
if (window.location.pathname !== newPathname) {
setLoading(true);
}
});
- router.events.on('routeChangeComplete', () => {
+ router.events.on("routeChangeComplete", () => {
setLoading(false);
});
- window.addEventListener('online', setUserOnline);
- window.addEventListener('offline', setUserOffline);
+ window.addEventListener("online", setUserOnline);
+ window.addEventListener("offline", setUserOffline);
return () => {
- window.removeEventListener('online', setUserOnline);
- window.removeEventListener('offline', setUserOffline);
+ window.removeEventListener("online", setUserOnline);
+ window.removeEventListener("offline", setUserOffline);
};
}, []);
@@ -145,9 +145,9 @@ export default function App(props: EnteAppProps) {
const somethingWentWrong = () =>
setDialogBoxAttributesV2({
- title: t('ERROR'),
- close: { variant: 'critical' },
- content: t('UNKNOWN_ERROR'),
+ title: t("ERROR"),
+ close: { variant: "critical" },
+ content: t("UNKNOWN_ERROR"),
});
return (
@@ -155,7 +155,7 @@ export default function App(props: EnteAppProps) {
<Head>
<title>
{isI18nReady
- ? t('TITLE', { context: APPS.AUTH })
+ ? t("TITLE", { context: APPS.AUTH })
: APP_TITLES.get(APPS.AUTH)}
</title>
<meta
@@ -168,7 +168,7 @@ export default function App(props: EnteAppProps) {
<CssBaseline enableColorScheme />
{showNavbar && <AppNavbar isMobile={isMobile} />}
<MessageContainer>
- {offline && t('OFFLINE_MSG')}
+ {offline && t("OFFLINE_MSG")}
</MessageContainer>
<LoadingBar color="#51cd7c" ref={loadingBar} />
@@ -190,16 +190,18 @@ export default function App(props: EnteAppProps) {
setThemeColor,
somethingWentWrong,
setDialogBoxAttributesV2,
- }}>
+ }}
+ >
{(loading || !isI18nReady) && (
<Overlay
sx={(theme) => ({
- display: 'flex',
- justifyContent: 'center',
- alignItems: 'center',
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
zIndex: 2000,
backgroundColor: theme.colors.background.base,
- })}>
+ })}
+ >
<EnteSpinner />
</Overlay>
)}
diff --git a/apps/auth/src/pages/_document.tsx b/apps/auth/src/pages/_document.tsx
index c3686b6be9..09d4d57823 100644
--- a/apps/auth/src/pages/_document.tsx
+++ b/apps/auth/src/pages/_document.tsx
@@ -1,6 +1,6 @@
import DocumentPage, {
EnteDocumentProps,
-} from '@ente/shared/next/pages/_document';
+} from "@ente/shared/next/pages/_document";
export default function Document(props: EnteDocumentProps) {
return <DocumentPage {...props} />;
diff --git a/apps/auth/src/pages/_error.tsx b/apps/auth/src/pages/_error.tsx
index 6c068e34b8..bf1bb89be3 100644
--- a/apps/auth/src/pages/_error.tsx
+++ b/apps/auth/src/pages/_error.tsx
@@ -1,8 +1,8 @@
-import ErrorPage from '@ente/shared/next/pages/_error';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import { APPS } from "@ente/shared/apps/constants";
+import ErrorPage from "@ente/shared/next/pages/_error";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Error() {
const appContext = useContext(AppContext);
diff --git a/apps/auth/src/pages/auth/index.tsx b/apps/auth/src/pages/auth/index.tsx
index f3be089d8c..6d8bbecc20 100644
--- a/apps/auth/src/pages/auth/index.tsx
+++ b/apps/auth/src/pages/auth/index.tsx
@@ -1,24 +1,24 @@
-import React, { useContext, useEffect, useState } from 'react';
-import OTPDisplay from 'components/OTPDisplay';
-import { getAuthCodes } from 'services';
-import { CustomError } from '@ente/shared/error';
-import { AUTH_PAGES as PAGES } from '@ente/shared/constants/pages';
-import { useRouter } from 'next/router';
-import { AuthFooter } from 'components/AuthFooter';
-import { AppContext } from 'pages/_app';
-import { TextField } from '@mui/material';
-import AuthNavbar from 'components/Navbar';
-import { t } from 'i18next';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import { AUTH_PAGES as PAGES } from "@ente/shared/constants/pages";
+import { CustomError } from "@ente/shared/error";
+import InMemoryStore, { MS_KEYS } from "@ente/shared/storage/InMemoryStore";
+import { TextField } from "@mui/material";
+import { AuthFooter } from "components/AuthFooter";
+import AuthNavbar from "components/Navbar";
+import OTPDisplay from "components/OTPDisplay";
+import { t } from "i18next";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext, useEffect, useState } from "react";
+import { getAuthCodes } from "services";
const AuthenticatorCodesPage = () => {
const appContext = useContext(AppContext);
const router = useRouter();
const [codes, setCodes] = useState([]);
const [hasFetched, setHasFetched] = useState(false);
- const [searchTerm, setSearchTerm] = useState('');
+ const [searchTerm, setSearchTerm] = useState("");
useEffect(() => {
const fetchCodes = async () => {
@@ -41,12 +41,12 @@ const AuthenticatorCodesPage = () => {
const filteredCodes = codes.filter(
(secret) =>
- (secret.issuer ?? '')
+ (secret.issuer ?? "")
.toLowerCase()
.includes(searchTerm.toLowerCase()) ||
- (secret.account ?? '')
+ (secret.account ?? "")
.toLowerCase()
- .includes(searchTerm.toLowerCase())
+ .includes(searchTerm.toLowerCase()),
);
if (!hasFetched) {
@@ -64,47 +64,50 @@ const AuthenticatorCodesPage = () => {
<AuthNavbar />
<div
style={{
- maxWidth: '800px',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- justifyContent: 'center',
- margin: '0 auto',
- }}>
- <div style={{ marginBottom: '1rem' }} />
+ maxWidth: "800px",
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ justifyContent: "center",
+ margin: "0 auto",
+ }}
+ >
+ <div style={{ marginBottom: "1rem" }} />
{filteredCodes.length === 0 && searchTerm.length === 0 ? (
<></>
) : (
<TextField
id="search"
name="search"
- label={t('SEARCH')}
+ label={t("SEARCH")}
onChange={(e) => setSearchTerm(e.target.value)}
variant="filled"
- style={{ width: '350px' }}
+ style={{ width: "350px" }}
value={searchTerm}
autoFocus
/>
)}
- <div style={{ marginBottom: '1rem' }} />
+ <div style={{ marginBottom: "1rem" }} />
<div
style={{
- display: 'flex',
- flexDirection: 'row',
- flexWrap: 'wrap',
- justifyContent: 'center',
- }}>
+ display: "flex",
+ flexDirection: "row",
+ flexWrap: "wrap",
+ justifyContent: "center",
+ }}
+ >
{filteredCodes.length === 0 ? (
<div
style={{
- alignItems: 'center',
- display: 'flex',
- textAlign: 'center',
- marginTop: '32px',
- }}>
+ alignItems: "center",
+ display: "flex",
+ textAlign: "center",
+ marginTop: "32px",
+ }}
+ >
{searchTerm.length !== 0 ? (
- <p>{t('NO_RESULTS')}</p>
+ <p>{t("NO_RESULTS")}</p>
) : (
<div />
)}
@@ -115,9 +118,9 @@ const AuthenticatorCodesPage = () => {
))
)}
</div>
- <div style={{ marginBottom: '2rem' }} />
+ <div style={{ marginBottom: "2rem" }} />
<AuthFooter />
- <div style={{ marginBottom: '4rem' }} />
+ <div style={{ marginBottom: "4rem" }} />
</div>
<style jsx>{`
@media (min-width: 800px) {
diff --git a/apps/auth/src/pages/change-email/index.tsx b/apps/auth/src/pages/change-email/index.tsx
index 77f60e1b5a..3bd1e89aba 100644
--- a/apps/auth/src/pages/change-email/index.tsx
+++ b/apps/auth/src/pages/change-email/index.tsx
@@ -1,8 +1,8 @@
-import ChangeEmailPage from '@ente/accounts/pages/change-email';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import ChangeEmailPage from "@ente/accounts/pages/change-email";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function ChangeEmail() {
const appContext = useContext(AppContext);
diff --git a/apps/auth/src/pages/change-password/index.tsx b/apps/auth/src/pages/change-password/index.tsx
index 71f0f3f2f4..5677487557 100644
--- a/apps/auth/src/pages/change-password/index.tsx
+++ b/apps/auth/src/pages/change-password/index.tsx
@@ -1,8 +1,8 @@
-import ChangePasswordPage from '@ente/accounts/pages/change-password';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import ChangePasswordPage from "@ente/accounts/pages/change-password";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function ChangePassword() {
const appContext = useContext(AppContext);
diff --git a/apps/auth/src/pages/credentials/index.tsx b/apps/auth/src/pages/credentials/index.tsx
index 3e78bb0417..c73a220890 100644
--- a/apps/auth/src/pages/credentials/index.tsx
+++ b/apps/auth/src/pages/credentials/index.tsx
@@ -1,8 +1,8 @@
-import CredentialPage from '@ente/accounts/pages/credentials';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import CredentialPage from "@ente/accounts/pages/credentials";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Credential() {
const appContext = useContext(AppContext);
diff --git a/apps/auth/src/pages/generate/index.tsx b/apps/auth/src/pages/generate/index.tsx
index 0b42789595..fe488e0c2d 100644
--- a/apps/auth/src/pages/generate/index.tsx
+++ b/apps/auth/src/pages/generate/index.tsx
@@ -1,8 +1,8 @@
-import GeneratePage from '@ente/accounts/pages/generate';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import GeneratePage from "@ente/accounts/pages/generate";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Generate() {
const appContext = useContext(AppContext);
diff --git a/apps/auth/src/pages/index.tsx b/apps/auth/src/pages/index.tsx
index 0c8fbb53fb..09b22fe49d 100644
--- a/apps/auth/src/pages/index.tsx
+++ b/apps/auth/src/pages/index.tsx
@@ -1,6 +1,6 @@
-import { PHOTOS_PAGES as PAGES } from '@ente/shared/constants/pages';
-import { useRouter } from 'next/router';
-import { useEffect } from 'react';
+import { PHOTOS_PAGES as PAGES } from "@ente/shared/constants/pages";
+import { useRouter } from "next/router";
+import { useEffect } from "react";
const IndexPage = () => {
const router = useRouter();
diff --git a/apps/auth/src/pages/login/index.tsx b/apps/auth/src/pages/login/index.tsx
index e503fec3da..434a315572 100644
--- a/apps/auth/src/pages/login/index.tsx
+++ b/apps/auth/src/pages/login/index.tsx
@@ -1,8 +1,8 @@
-import LoginPage from '@ente/accounts/pages/login';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import LoginPage from "@ente/accounts/pages/login";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Login() {
const appContext = useContext(AppContext);
diff --git a/apps/auth/src/pages/recover/index.tsx b/apps/auth/src/pages/recover/index.tsx
index 4e8380bee5..9629de5d6c 100644
--- a/apps/auth/src/pages/recover/index.tsx
+++ b/apps/auth/src/pages/recover/index.tsx
@@ -1,8 +1,8 @@
-import RecoverPage from '@ente/accounts/pages/recover';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import RecoverPage from "@ente/accounts/pages/recover";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Recover() {
const appContext = useContext(AppContext);
diff --git a/apps/auth/src/pages/signup/index.tsx b/apps/auth/src/pages/signup/index.tsx
index 8f8405fc31..b7cbccd972 100644
--- a/apps/auth/src/pages/signup/index.tsx
+++ b/apps/auth/src/pages/signup/index.tsx
@@ -1,8 +1,8 @@
-import SignupPage from '@ente/accounts/pages/signup';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import SignupPage from "@ente/accounts/pages/signup";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Sigup() {
const appContext = useContext(AppContext);
diff --git a/apps/auth/src/pages/two-factor/recover/index.tsx b/apps/auth/src/pages/two-factor/recover/index.tsx
index 9a1c529e17..965a777554 100644
--- a/apps/auth/src/pages/two-factor/recover/index.tsx
+++ b/apps/auth/src/pages/two-factor/recover/index.tsx
@@ -1,8 +1,8 @@
-import TwoFactorRecoverPage from '@ente/accounts/pages/two-factor/recover';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import TwoFactorRecoverPage from "@ente/accounts/pages/two-factor/recover";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function TwoFactorRecover() {
const appContext = useContext(AppContext);
diff --git a/apps/auth/src/pages/two-factor/setup/index.tsx b/apps/auth/src/pages/two-factor/setup/index.tsx
index 32f4d28b49..4a027ded6b 100644
--- a/apps/auth/src/pages/two-factor/setup/index.tsx
+++ b/apps/auth/src/pages/two-factor/setup/index.tsx
@@ -1,8 +1,8 @@
-import TwoFactorSetupPage from '@ente/accounts/pages/two-factor/setup';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import TwoFactorSetupPage from "@ente/accounts/pages/two-factor/setup";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function TwoFactorSetup() {
const appContext = useContext(AppContext);
diff --git a/apps/auth/src/pages/two-factor/verify/index.tsx b/apps/auth/src/pages/two-factor/verify/index.tsx
index c72c764c67..1c90e49a8a 100644
--- a/apps/auth/src/pages/two-factor/verify/index.tsx
+++ b/apps/auth/src/pages/two-factor/verify/index.tsx
@@ -1,8 +1,8 @@
-import TwoFactorVerifyPage from '@ente/accounts/pages/two-factor/verify';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import TwoFactorVerifyPage from "@ente/accounts/pages/two-factor/verify";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function TwoFactorVerify() {
const appContext = useContext(AppContext);
diff --git a/apps/auth/src/pages/verify/index.tsx b/apps/auth/src/pages/verify/index.tsx
index 2554ed6314..ff3317cab6 100644
--- a/apps/auth/src/pages/verify/index.tsx
+++ b/apps/auth/src/pages/verify/index.tsx
@@ -1,8 +1,8 @@
-import VerifyPage from '@ente/accounts/pages/verify';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import VerifyPage from "@ente/accounts/pages/verify";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Verify() {
const appContext = useContext(AppContext);
diff --git a/apps/auth/src/services/index.ts b/apps/auth/src/services/index.ts
index e9160dd807..893ddfb66f 100644
--- a/apps/auth/src/services/index.ts
+++ b/apps/auth/src/services/index.ts
@@ -1,13 +1,13 @@
-import { HttpStatusCode } from 'axios';
-import HTTPService from '@ente/shared/network/HTTPService';
-import { AuthEntity, AuthKey } from 'types/api';
-import { Code } from 'types/code';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { getEndpoint } from '@ente/shared/network/api';
-import { getActualKey } from '@ente/shared/user';
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
-import { ApiError, CustomError } from '@ente/shared/error';
-import { logError } from '@ente/shared/sentry';
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { ApiError, CustomError } from "@ente/shared/error";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getEndpoint } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
+import { getActualKey } from "@ente/shared/user";
+import { HttpStatusCode } from "axios";
+import { AuthEntity, AuthKey } from "types/api";
+import { Code } from "types/code";
const ENDPOINT = getEndpoint();
export const getAuthCodes = async (): Promise<Code[]> => {
@@ -18,7 +18,7 @@ export const getAuthCodes = async (): Promise<Code[]> => {
const authenticatorKey = await cryptoWorker.decryptB64(
authKeyData.encryptedKey,
authKeyData.header,
- masterKey
+ masterKey,
);
// always fetch all data from server for now
const authEntity: AuthEntity[] = await getDiff(0);
@@ -31,21 +31,21 @@ export const getAuthCodes = async (): Promise<Code[]> => {
await cryptoWorker.decryptMetadata(
entity.encryptedData,
entity.header,
- authenticatorKey
+ authenticatorKey,
);
return Code.fromRawData(entity.id, decryptedCode);
} catch (e) {
logError(
- Error('failed to parse code'),
- 'codeId = ' + entity.id
+ Error("failed to parse code"),
+ "codeId = " + entity.id,
);
return null;
}
- })
+ }),
);
// Remove null and undefined values
const filteredAuthCodes = authCodes.filter(
- (f) => f !== null && f !== undefined
+ (f) => f !== null && f !== undefined,
);
filteredAuthCodes.sort((a, b) => {
if (a.issuer && b.issuer) {
@@ -62,7 +62,7 @@ export const getAuthCodes = async (): Promise<Code[]> => {
return filteredAuthCodes;
} catch (e) {
if (e.message !== CustomError.AUTH_KEY_NOT_FOUND) {
- logError(e, 'get authenticator entities failed');
+ logError(e, "get authenticator entities failed");
}
throw e;
}
@@ -74,8 +74,8 @@ export const getAuthKey = async (): Promise<AuthKey> => {
`${ENDPOINT}/authenticator/key`,
{},
{
- 'X-Auth-Token': getToken(),
- }
+ "X-Auth-Token": getToken(),
+ },
);
return resp.data;
} catch (e) {
@@ -85,7 +85,7 @@ export const getAuthKey = async (): Promise<AuthKey> => {
) {
throw Error(CustomError.AUTH_KEY_NOT_FOUND);
} else {
- logError(e, 'Get key failed');
+ logError(e, "Get key failed");
throw e;
}
}
@@ -94,7 +94,7 @@ export const getAuthKey = async (): Promise<AuthKey> => {
// return a promise which resolves to list of AuthEnitity
export const getDiff = async (
sinceTime: number,
- limit = 2500
+ limit = 2500,
): Promise<AuthEntity[]> => {
try {
const resp = await HTTPService.get(
@@ -104,12 +104,12 @@ export const getDiff = async (
limit,
},
{
- 'X-Auth-Token': getToken(),
- }
+ "X-Auth-Token": getToken(),
+ },
);
return resp.data.diff;
} catch (e) {
- logError(e, 'Get diff failed');
+ logError(e, "Get diff failed");
throw e;
}
};
diff --git a/apps/auth/src/types/code.ts b/apps/auth/src/types/code.ts
index 70f3c6ef2f..d61a2dcd68 100644
--- a/apps/auth/src/types/code.ts
+++ b/apps/auth/src/types/code.ts
@@ -1,18 +1,18 @@
-import { URI } from 'vscode-uri';
+import { URI } from "vscode-uri";
-type Type = 'totp' | 'TOTP' | 'hotp' | 'HOTP';
+type Type = "totp" | "TOTP" | "hotp" | "HOTP";
type AlgorithmType =
- | 'sha1'
- | 'SHA1'
- | 'sha256'
- | 'SHA256'
- | 'sha512'
- | 'SHA512';
+ | "sha1"
+ | "SHA1"
+ | "sha256"
+ | "SHA256"
+ | "sha512"
+ | "SHA512";
export class Code {
static readonly defaultDigits = 6;
- static readonly defaultAlgo = 'sha1';
+ static readonly defaultAlgo = "sha1";
static readonly defaultPeriod = 30;
// id for the corresponding auth entity
@@ -35,7 +35,7 @@ export class Code {
algorithm: AlgorithmType,
type: Type,
rawData?: string,
- id?: string
+ id?: string,
) {
this.account = account;
this.issuer = issuer;
@@ -50,36 +50,36 @@ export class Code {
static fromRawData(id: string, rawData: string): Code {
let santizedRawData = rawData
- .replace(/\+/g, '%2B')
- .replace(/:/g, '%3A')
- .replaceAll('\r', '');
+ .replace(/\+/g, "%2B")
+ .replace(/:/g, "%3A")
+ .replaceAll("\r", "");
if (santizedRawData.startsWith('"')) {
santizedRawData = santizedRawData.substring(1);
}
if (santizedRawData.endsWith('"')) {
santizedRawData = santizedRawData.substring(
0,
- santizedRawData.length - 1
+ santizedRawData.length - 1,
);
}
const uriParams = {};
const searchParamsString =
- decodeURIComponent(santizedRawData).split('?')[1];
- searchParamsString.split('&').forEach((pair) => {
- const [key, value] = pair.split('=');
+ decodeURIComponent(santizedRawData).split("?")[1];
+ searchParamsString.split("&").forEach((pair) => {
+ const [key, value] = pair.split("=");
uriParams[key] = value;
});
const uri = URI.parse(santizedRawData);
let uriPath = decodeURIComponent(uri.path);
if (
- uriPath.startsWith('/otpauth://') ||
- uriPath.startsWith('otpauth://')
+ uriPath.startsWith("/otpauth://") ||
+ uriPath.startsWith("otpauth://")
) {
- uriPath = uriPath.split('otpauth://')[1];
- } else if (uriPath.startsWith('otpauth%3A//')) {
- uriPath = uriPath.split('otpauth%3A//')[1];
+ uriPath = uriPath.split("otpauth://")[1];
+ } else if (uriPath.startsWith("otpauth%3A//")) {
+ uriPath = uriPath.split("otpauth%3A//")[1];
}
return new Code(
@@ -91,54 +91,54 @@ export class Code {
Code._getAlgorithm(uriParams),
Code._getType(uriPath),
rawData,
- id
+ id,
);
}
private static _getAccount(uriPath: string): string {
try {
const path = decodeURIComponent(uriPath);
- if (path.includes(':')) {
- return path.split(':')[1];
- } else if (path.includes('/')) {
- return path.split('/')[1];
+ if (path.includes(":")) {
+ return path.split(":")[1];
+ } else if (path.includes("/")) {
+ return path.split("/")[1];
}
} catch (e) {
- return '';
+ return "";
}
}
private static _getIssuer(
uriPath: string,
- uriParams: { get?: any }
+ uriParams: { get?: any },
): string {
try {
- if (uriParams['issuer'] !== undefined) {
- let issuer = uriParams['issuer'];
+ if (uriParams["issuer"] !== undefined) {
+ let issuer = uriParams["issuer"];
// This is to handle bug in the ente auth app
- if (issuer.endsWith('period')) {
+ if (issuer.endsWith("period")) {
issuer = issuer.substring(0, issuer.length - 6);
}
return issuer;
}
let path = decodeURIComponent(uriPath);
- if (path.startsWith('totp/') || path.startsWith('hotp/')) {
+ if (path.startsWith("totp/") || path.startsWith("hotp/")) {
path = path.substring(5);
}
- if (path.includes(':')) {
- return path.split(':')[0];
- } else if (path.includes('-')) {
- return path.split('-')[0];
+ if (path.includes(":")) {
+ return path.split(":")[0];
+ } else if (path.includes("-")) {
+ return path.split("-")[0];
}
return path;
} catch (e) {
- return '';
+ return "";
}
}
private static _getDigits(uriParams): number {
try {
- return parseInt(uriParams['digits'], 10) || Code.defaultDigits;
+ return parseInt(uriParams["digits"], 10) || Code.defaultDigits;
} catch (e) {
return Code.defaultDigits;
}
@@ -146,7 +146,7 @@ export class Code {
private static _getPeriod(uriParams): number {
try {
- return parseInt(uriParams['period'], 10) || Code.defaultPeriod;
+ return parseInt(uriParams["period"], 10) || Code.defaultPeriod;
} catch (e) {
return Code.defaultPeriod;
}
@@ -154,29 +154,29 @@ export class Code {
private static _getAlgorithm(uriParams): AlgorithmType {
try {
- const algorithm = uriParams['algorithm'].toLowerCase();
- if (algorithm === 'sha256') {
+ const algorithm = uriParams["algorithm"].toLowerCase();
+ if (algorithm === "sha256") {
return algorithm;
- } else if (algorithm === 'sha512') {
+ } else if (algorithm === "sha512") {
return algorithm;
}
} catch (e) {
// nothing
}
- return 'sha1';
+ return "sha1";
}
private static _getType(uriPath: string): Type {
- const oauthType = uriPath.split('/')[0].substring(0);
- if (oauthType.toLowerCase() === 'totp') {
- return 'totp';
- } else if (oauthType.toLowerCase() === 'hotp') {
- return 'hotp';
+ const oauthType = uriPath.split("/")[0].substring(0);
+ if (oauthType.toLowerCase() === "totp") {
+ return "totp";
+ } else if (oauthType.toLowerCase() === "hotp") {
+ return "hotp";
}
throw new Error(`Unsupported format with host ${oauthType}`);
}
static getSanitizedSecret(uriParams): string {
- return uriParams['secret'].replace(/ /g, '').toUpperCase();
+ return uriParams["secret"].replace(/ /g, "").toUpperCase();
}
}
diff --git a/apps/cast/.eslintrc.js b/apps/cast/.eslintrc.js
index 7ddcebe961..b1c4c2e168 100644
--- a/apps/cast/.eslintrc.js
+++ b/apps/cast/.eslintrc.js
@@ -3,11 +3,11 @@ module.exports = {
// This is required here to ensure desktop picks the right eslint config, where this app is
// packaged as a submodule.
root: true,
- extends: ['@ente/eslint-config'],
- parser: '@typescript-eslint/parser',
+ extends: ["@ente/eslint-config"],
+ parser: "@typescript-eslint/parser",
parserOptions: {
tsconfigRootDir: __dirname,
- project: './tsconfig.json',
+ project: "./tsconfig.json",
},
- ignorePatterns: ['.eslintrc.js', 'out'],
+ ignorePatterns: [".eslintrc.js", "out"],
};
diff --git a/apps/cast/next.config.js b/apps/cast/next.config.js
index 57e1c5c8b5..eea88bf938 100644
--- a/apps/cast/next.config.js
+++ b/apps/cast/next.config.js
@@ -1,3 +1,3 @@
-const nextConfigBase = require('@/next/next.config.base.js');
+const nextConfigBase = require("@/next/next.config.base.js");
module.exports = nextConfigBase;
diff --git a/apps/cast/sentry.client.config.ts b/apps/cast/sentry.client.config.ts
index 8223fcd906..c43273663f 100644
--- a/apps/cast/sentry.client.config.ts
+++ b/apps/cast/sentry.client.config.ts
@@ -1,3 +1,3 @@
-import { initSentry } from '@ente/shared/sentry/config/sentry.config.base';
+import { initSentry } from "@ente/shared/sentry/config/sentry.config.base";
-initSentry('https://[email protected]/5');
+initSentry("https://[email protected]/5");
diff --git a/apps/cast/src/components/FilledCircleCheck/index.tsx b/apps/cast/src/components/FilledCircleCheck/index.tsx
index e70f1e3369..cce8c935f7 100644
--- a/apps/cast/src/components/FilledCircleCheck/index.tsx
+++ b/apps/cast/src/components/FilledCircleCheck/index.tsx
@@ -1,5 +1,5 @@
-import { useEffect, useState } from 'react';
-import styles from './FilledCircleCheck.module.scss'; // Import our CSS module
+import { useEffect, useState } from "react";
+import styles from "./FilledCircleCheck.module.scss"; // Import our CSS module
const FilledCircleCheck = () => {
const [animate, setAnimate] = useState(false);
@@ -9,11 +9,12 @@ const FilledCircleCheck = () => {
}, []);
return (
- <div className={`${styles.circle} ${animate ? styles.animate : ''}`}>
+ <div className={`${styles.circle} ${animate ? styles.animate : ""}`}>
<svg
className={styles.checkmark}
xmlns="http://www.w3.org/2000/svg"
- viewBox="0 0 52 52">
+ viewBox="0 0 52 52"
+ >
<circle
className={styles.checkmark__circle}
cx="26"
diff --git a/apps/cast/src/components/LargeType.tsx b/apps/cast/src/components/LargeType.tsx
index b2a2eb9949..bb0728699f 100644
--- a/apps/cast/src/components/LargeType.tsx
+++ b/apps/cast/src/components/LargeType.tsx
@@ -1,58 +1,62 @@
const colourPool = [
- '#87CEFA', // Light Blue
- '#90EE90', // Light Green
- '#F08080', // Light Coral
- '#FFFFE0', // Light Yellow
- '#FFB6C1', // Light Pink
- '#E0FFFF', // Light Cyan
- '#FAFAD2', // Light Goldenrod
- '#87CEFA', // Light Sky Blue
- '#D3D3D3', // Light Gray
- '#B0C4DE', // Light Steel Blue
- '#FFA07A', // Light Salmon
- '#20B2AA', // Light Sea Green
- '#778899', // Light Slate Gray
- '#AFEEEE', // Light Turquoise
- '#7A58C1', // Light Violet
- '#FFA500', // Light Orange
- '#A0522D', // Light Brown
- '#9370DB', // Light Purple
- '#008080', // Light Teal
- '#808000', // Light Olive
+ "#87CEFA", // Light Blue
+ "#90EE90", // Light Green
+ "#F08080", // Light Coral
+ "#FFFFE0", // Light Yellow
+ "#FFB6C1", // Light Pink
+ "#E0FFFF", // Light Cyan
+ "#FAFAD2", // Light Goldenrod
+ "#87CEFA", // Light Sky Blue
+ "#D3D3D3", // Light Gray
+ "#B0C4DE", // Light Steel Blue
+ "#FFA07A", // Light Salmon
+ "#20B2AA", // Light Sea Green
+ "#778899", // Light Slate Gray
+ "#AFEEEE", // Light Turquoise
+ "#7A58C1", // Light Violet
+ "#FFA500", // Light Orange
+ "#A0522D", // Light Brown
+ "#9370DB", // Light Purple
+ "#008080", // Light Teal
+ "#808000", // Light Olive
];
export default function LargeType({ chars }: { chars: string[] }) {
return (
<table
style={{
- fontSize: '4rem',
- fontWeight: 'bold',
- fontFamily: 'monospace',
- display: 'flex',
- position: 'relative',
- }}>
+ fontSize: "4rem",
+ fontWeight: "bold",
+ fontFamily: "monospace",
+ display: "flex",
+ position: "relative",
+ }}
+ >
{chars.map((char, i) => (
<tr
key={i}
style={{
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- padding: '0.5rem',
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ padding: "0.5rem",
// alternating background
- backgroundColor: i % 2 === 0 ? '#2e2e2e' : '#5e5e5e',
- }}>
+ backgroundColor: i % 2 === 0 ? "#2e2e2e" : "#5e5e5e",
+ }}
+ >
<span
style={{
color: colourPool[i % colourPool.length],
lineHeight: 1.2,
- }}>
+ }}
+ >
{char}
</span>
<span
style={{
- fontSize: '1rem',
- }}>
+ fontSize: "1rem",
+ }}
+ >
{i + 1}
</span>
</tr>
diff --git a/apps/cast/src/components/PairedSuccessfullyOverlay.tsx b/apps/cast/src/components/PairedSuccessfullyOverlay.tsx
index 517874b734..845416fedc 100644
--- a/apps/cast/src/components/PairedSuccessfullyOverlay.tsx
+++ b/apps/cast/src/components/PairedSuccessfullyOverlay.tsx
@@ -1,38 +1,42 @@
-import FilledCircleCheck from './FilledCircleCheck';
+import FilledCircleCheck from "./FilledCircleCheck";
export default function PairedSuccessfullyOverlay() {
return (
<div
style={{
- position: 'fixed',
+ position: "fixed",
top: 0,
right: 0,
- height: '100%',
- width: '100%',
- display: 'flex',
- justifyContent: 'center',
- alignItems: 'center',
+ height: "100%",
+ width: "100%",
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
zIndex: 100,
- backgroundColor: 'black',
- }}>
+ backgroundColor: "black",
+ }}
+ >
<div
style={{
- display: 'flex',
- alignItems: 'center',
- flexDirection: 'column',
- textAlign: 'center',
- }}>
+ display: "flex",
+ alignItems: "center",
+ flexDirection: "column",
+ textAlign: "center",
+ }}
+ >
<FilledCircleCheck />
<h2
style={{
marginBottom: 0,
- }}>
+ }}
+ >
Pairing Complete
</h2>
<p
style={{
- lineHeight: '1.5rem',
- }}>
+ lineHeight: "1.5rem",
+ }}
+ >
We're preparing your album.
<br /> This should only take a few seconds.
</p>
diff --git a/apps/cast/src/components/Theatre/PhotoAuditorium.tsx b/apps/cast/src/components/Theatre/PhotoAuditorium.tsx
index c137aec7ff..dc5a18f0b9 100644
--- a/apps/cast/src/components/Theatre/PhotoAuditorium.tsx
+++ b/apps/cast/src/components/Theatre/PhotoAuditorium.tsx
@@ -1,5 +1,5 @@
-import { SlideshowContext } from 'pages/slideshow';
-import { useContext, useEffect, useState } from 'react';
+import { SlideshowContext } from "pages/slideshow";
+import { useContext, useEffect, useState } from "react";
export default function PhotoAuditorium({
url,
@@ -49,38 +49,40 @@ export default function PhotoAuditorium({
return (
<div
style={{
- width: '100vw',
- height: '100vh',
+ width: "100vw",
+ height: "100vh",
backgroundImage: `url(${url})`,
- backgroundSize: 'cover',
- backgroundPosition: 'center',
- backgroundRepeat: 'no-repeat',
- backgroundBlendMode: 'multiply',
- backgroundColor: 'rgba(0, 0, 0, 0.5)',
- }}>
+ backgroundSize: "cover",
+ backgroundPosition: "center",
+ backgroundRepeat: "no-repeat",
+ backgroundBlendMode: "multiply",
+ backgroundColor: "rgba(0, 0, 0, 0.5)",
+ }}
+ >
<div
style={{
- height: '100%',
- width: '100%',
- display: 'flex',
- justifyContent: 'center',
- alignItems: 'center',
- backdropFilter: 'blur(10px)',
- }}>
+ height: "100%",
+ width: "100%",
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ backdropFilter: "blur(10px)",
+ }}
+ >
<img
src={url}
style={{
- maxWidth: '100%',
- maxHeight: '100%',
- display: showPreloadedNextSlide ? 'none' : 'block',
+ maxWidth: "100%",
+ maxHeight: "100%",
+ display: showPreloadedNextSlide ? "none" : "block",
}}
/>
<img
src={nextSlideUrl}
style={{
- maxWidth: '100%',
- maxHeight: '100%',
- display: showPreloadedNextSlide ? 'block' : 'none',
+ maxWidth: "100%",
+ maxHeight: "100%",
+ display: showPreloadedNextSlide ? "block" : "none",
}}
onLoad={() => {
setNextSlidePrerendered(true);
diff --git a/apps/cast/src/components/Theatre/VideoAuditorium.tsx b/apps/cast/src/components/Theatre/VideoAuditorium.tsx
index 230d30312f..2bf5ed4908 100644
--- a/apps/cast/src/components/Theatre/VideoAuditorium.tsx
+++ b/apps/cast/src/components/Theatre/VideoAuditorium.tsx
@@ -1,6 +1,6 @@
-import mime from 'mime-types';
-import { SlideshowContext } from 'pages/slideshow';
-import { useContext, useEffect, useRef } from 'react';
+import mime from "mime-types";
+import { SlideshowContext } from "pages/slideshow";
+import { useContext, useEffect, useRef } from "react";
export default function VideoAuditorium({
name,
@@ -30,22 +30,24 @@ export default function VideoAuditorium({
return (
<div
style={{
- width: '100vw',
- height: '100vh',
- display: 'flex',
- justifyContent: 'center',
- alignItems: 'center',
- }}>
+ width: "100vw",
+ height: "100vh",
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ }}
+ >
<video
ref={videoRef}
autoPlay
controls
style={{
- maxWidth: '100vw',
- maxHeight: '100vh',
+ maxWidth: "100vw",
+ maxHeight: "100vh",
}}
onError={showNextSlide}
- onEnded={showNextSlide}>
+ onEnded={showNextSlide}
+ >
<source src={url} type={mime.lookup(name)} />
</video>
</div>
diff --git a/apps/cast/src/components/Theatre/index.tsx b/apps/cast/src/components/Theatre/index.tsx
index d2c8e6ab4d..f7cac9c544 100644
--- a/apps/cast/src/components/Theatre/index.tsx
+++ b/apps/cast/src/components/Theatre/index.tsx
@@ -1,5 +1,5 @@
-import { FILE_TYPE } from 'constants/file';
-import PhotoAuditorium from './PhotoAuditorium';
+import { FILE_TYPE } from "constants/file";
+import PhotoAuditorium from "./PhotoAuditorium";
// import VideoAuditorium from './VideoAuditorium';
interface fileProp {
diff --git a/apps/cast/src/components/TimerBar.tsx b/apps/cast/src/components/TimerBar.tsx
index 0d0a07e6bd..7f4d021711 100644
--- a/apps/cast/src/components/TimerBar.tsx
+++ b/apps/cast/src/components/TimerBar.tsx
@@ -1,9 +1,9 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useState } from "react";
export default function TimerBar({ percentage }: { percentage: number }) {
- const okColor = '#75C157';
- const warningColor = '#FFC000';
- const lateColor = '#FF0000';
+ const okColor = "#75C157";
+ const warningColor = "#FFC000";
+ const lateColor = "#FF0000";
const [backgroundColor, setBackgroundColor] = useState(okColor);
@@ -21,9 +21,9 @@ export default function TimerBar({ percentage }: { percentage: number }) {
<div
style={{
width: `${percentage}%`, // Set the width based on the time left
- height: '10px', // Same as the border thickness
+ height: "10px", // Same as the border thickness
backgroundColor, // The color of the moving border
- transition: 'width 1s linear', // Smooth transition for the width change
+ transition: "width 1s linear", // Smooth transition for the width change
}}
/>
);
diff --git a/apps/cast/src/constants/apps.ts b/apps/cast/src/constants/apps.ts
index 5d54d176c9..f8c3f96575 100644
--- a/apps/cast/src/constants/apps.ts
+++ b/apps/cast/src/constants/apps.ts
@@ -1,11 +1,11 @@
-import { getAlbumsURL } from '@ente/shared/network/api';
-import { runningInBrowser } from '@ente/shared/platform';
-import { PAGES } from 'constants/pages';
+import { getAlbumsURL } from "@ente/shared/network/api";
+import { runningInBrowser } from "@ente/shared/platform";
+import { PAGES } from "constants/pages";
export enum APPS {
- PHOTOS = 'PHOTOS',
- AUTH = 'AUTH',
- ALBUMS = 'ALBUMS',
+ PHOTOS = "PHOTOS",
+ AUTH = "AUTH",
+ ALBUMS = "ALBUMS",
}
export const ALLOWED_APP_PAGES = new Map([
@@ -29,9 +29,9 @@ export const ALLOWED_APP_PAGES = new Map([
]);
export const CLIENT_PACKAGE_NAMES = new Map([
- [APPS.ALBUMS, 'io.ente.albums.web'],
- [APPS.PHOTOS, 'io.ente.photos.web'],
- [APPS.AUTH, 'io.ente.auth.web'],
+ [APPS.ALBUMS, "io.ente.albums.web"],
+ [APPS.PHOTOS, "io.ente.photos.web"],
+ [APPS.AUTH, "io.ente.auth.web"],
]);
export const getAppNameAndTitle = () => {
@@ -41,9 +41,9 @@ export const getAppNameAndTitle = () => {
const currentURL = new URL(window.location.href);
const albumsURL = new URL(getAlbumsURL());
if (currentURL.origin === albumsURL.origin) {
- return { name: APPS.ALBUMS, title: 'ente Photos' };
+ return { name: APPS.ALBUMS, title: "ente Photos" };
} else {
- return { name: APPS.PHOTOS, title: 'ente Photos' };
+ return { name: APPS.PHOTOS, title: "ente Photos" };
}
};
diff --git a/apps/cast/src/constants/cache.ts b/apps/cast/src/constants/cache.ts
index 80e0fecf19..cf88f63a22 100644
--- a/apps/cast/src/constants/cache.ts
+++ b/apps/cast/src/constants/cache.ts
@@ -1,5 +1,5 @@
export enum CACHES {
- THUMBS = 'thumbs',
- FACE_CROPS = 'face-crops',
- FILES = 'files',
+ THUMBS = "thumbs",
+ FACE_CROPS = "face-crops",
+ FILES = "files",
}
diff --git a/apps/cast/src/constants/collection.ts b/apps/cast/src/constants/collection.ts
index a0c6a90377..cc2c000528 100644
--- a/apps/cast/src/constants/collection.ts
+++ b/apps/cast/src/constants/collection.ts
@@ -3,31 +3,31 @@ export const TRASH_SECTION = -2;
export const DUMMY_UNCATEGORIZED_COLLECTION = -3;
export const HIDDEN_ITEMS_SECTION = -4;
export const ALL_SECTION = 0;
-export const DEFAULT_HIDDEN_COLLECTION_USER_FACING_NAME = 'Hidden';
+export const DEFAULT_HIDDEN_COLLECTION_USER_FACING_NAME = "Hidden";
export enum CollectionType {
- folder = 'folder',
- favorites = 'favorites',
- album = 'album',
- uncategorized = 'uncategorized',
+ folder = "folder",
+ favorites = "favorites",
+ album = "album",
+ uncategorized = "uncategorized",
}
export enum CollectionSummaryType {
- folder = 'folder',
- favorites = 'favorites',
- album = 'album',
- archive = 'archive',
- trash = 'trash',
- uncategorized = 'uncategorized',
- all = 'all',
- outgoingShare = 'outgoingShare',
- incomingShareViewer = 'incomingShareViewer',
- incomingShareCollaborator = 'incomingShareCollaborator',
- sharedOnlyViaLink = 'sharedOnlyViaLink',
- archived = 'archived',
- defaultHidden = 'defaultHidden',
- hiddenItems = 'hiddenItems',
- pinned = 'pinned',
+ folder = "folder",
+ favorites = "favorites",
+ album = "album",
+ archive = "archive",
+ trash = "trash",
+ uncategorized = "uncategorized",
+ all = "all",
+ outgoingShare = "outgoingShare",
+ incomingShareViewer = "incomingShareViewer",
+ incomingShareCollaborator = "incomingShareCollaborator",
+ sharedOnlyViaLink = "sharedOnlyViaLink",
+ archived = "archived",
+ defaultHidden = "defaultHidden",
+ hiddenItems = "hiddenItems",
+ pinned = "pinned",
}
export enum COLLECTION_LIST_SORT_BY {
NAME,
diff --git a/apps/cast/src/constants/ffmpeg.ts b/apps/cast/src/constants/ffmpeg.ts
index 008b09784e..9ecc41eb5e 100644
--- a/apps/cast/src/constants/ffmpeg.ts
+++ b/apps/cast/src/constants/ffmpeg.ts
@@ -1,3 +1,3 @@
-export const INPUT_PATH_PLACEHOLDER = 'INPUT';
-export const FFMPEG_PLACEHOLDER = 'FFMPEG';
-export const OUTPUT_PATH_PLACEHOLDER = 'OUTPUT';
+export const INPUT_PATH_PLACEHOLDER = "INPUT";
+export const FFMPEG_PLACEHOLDER = "FFMPEG";
+export const OUTPUT_PATH_PLACEHOLDER = "OUTPUT";
diff --git a/apps/cast/src/constants/file.ts b/apps/cast/src/constants/file.ts
index c00ec9972a..46065136c9 100644
--- a/apps/cast/src/constants/file.ts
+++ b/apps/cast/src/constants/file.ts
@@ -4,10 +4,10 @@ export const MAX_EDITED_CREATION_TIME = new Date();
export const MAX_EDITED_FILE_NAME_LENGTH = 100;
export const MAX_CAPTION_SIZE = 5000;
-export const TYPE_HEIC = 'heic';
-export const TYPE_HEIF = 'heif';
-export const TYPE_JPEG = 'jpeg';
-export const TYPE_JPG = 'jpg';
+export const TYPE_HEIC = "heic";
+export const TYPE_HEIF = "heif";
+export const TYPE_JPEG = "jpeg";
+export const TYPE_JPG = "jpg";
export enum FILE_TYPE {
IMAGE,
@@ -17,27 +17,27 @@ export enum FILE_TYPE {
}
export const RAW_FORMATS = [
- 'heic',
- 'rw2',
- 'tiff',
- 'arw',
- 'cr3',
- 'cr2',
- 'raf',
- 'nef',
- 'psd',
- 'dng',
- 'tif',
+ "heic",
+ "rw2",
+ "tiff",
+ "arw",
+ "cr3",
+ "cr2",
+ "raf",
+ "nef",
+ "psd",
+ "dng",
+ "tif",
];
export const SUPPORTED_RAW_FORMATS = [
- 'heic',
- 'rw2',
- 'tiff',
- 'arw',
- 'cr3',
- 'cr2',
- 'nef',
- 'psd',
- 'dng',
- 'tif',
+ "heic",
+ "rw2",
+ "tiff",
+ "arw",
+ "cr3",
+ "cr2",
+ "nef",
+ "psd",
+ "dng",
+ "tif",
];
diff --git a/apps/cast/src/constants/gallery.ts b/apps/cast/src/constants/gallery.ts
index 66b7759d69..9865d2e809 100644
--- a/apps/cast/src/constants/gallery.ts
+++ b/apps/cast/src/constants/gallery.ts
@@ -8,8 +8,8 @@ export const SPACE_BTW_DATES = 44;
export const SPACE_BTW_DATES_TO_IMAGE_CONTAINER_WIDTH_RATIO = 0.244;
export enum PLAN_PERIOD {
- MONTH = 'month',
- YEAR = 'year',
+ MONTH = "month",
+ YEAR = "year",
}
export const SYNC_INTERVAL_IN_MICROSECONDS = 1000 * 60 * 5; // 5 minutes
diff --git a/apps/cast/src/constants/pages.ts b/apps/cast/src/constants/pages.ts
index 85b9db0189..af532801d8 100644
--- a/apps/cast/src/constants/pages.ts
+++ b/apps/cast/src/constants/pages.ts
@@ -1,20 +1,20 @@
export enum PAGES {
- CHANGE_EMAIL = '/change-email',
- CHANGE_PASSWORD = '/change-password',
- CREDENTIALS = '/credentials',
- GALLERY = '/gallery',
- GENERATE = '/generate',
- LOGIN = '/login',
- RECOVER = '/recover',
- SIGNUP = '/signup',
- TWO_FACTOR_SETUP = '/two-factor/setup',
- TWO_FACTOR_VERIFY = '/two-factor/verify',
- TWO_FACTOR_RECOVER = '/two-factor/recover',
- VERIFY = '/verify',
- ROOT = '/',
- SHARED_ALBUMS = '/shared-albums',
+ CHANGE_EMAIL = "/change-email",
+ CHANGE_PASSWORD = "/change-password",
+ CREDENTIALS = "/credentials",
+ GALLERY = "/gallery",
+ GENERATE = "/generate",
+ LOGIN = "/login",
+ RECOVER = "/recover",
+ SIGNUP = "/signup",
+ TWO_FACTOR_SETUP = "/two-factor/setup",
+ TWO_FACTOR_VERIFY = "/two-factor/verify",
+ TWO_FACTOR_RECOVER = "/two-factor/recover",
+ VERIFY = "/verify",
+ ROOT = "/",
+ SHARED_ALBUMS = "/shared-albums",
// ML_DEBUG = '/ml-debug',
- DEDUPLICATE = '/deduplicate',
+ DEDUPLICATE = "/deduplicate",
// AUTH page is used to show (auth)enticator codes
- AUTH = '/auth',
+ AUTH = "/auth",
}
diff --git a/apps/cast/src/constants/upload.ts b/apps/cast/src/constants/upload.ts
index dccad9bae6..bc6006e468 100644
--- a/apps/cast/src/constants/upload.ts
+++ b/apps/cast/src/constants/upload.ts
@@ -1,52 +1,52 @@
-import { ENCRYPTION_CHUNK_SIZE } from '@ente/shared/crypto/constants';
-import { FILE_TYPE } from 'constants/file';
+import { ENCRYPTION_CHUNK_SIZE } from "@ente/shared/crypto/constants";
+import { FILE_TYPE } from "constants/file";
import {
FileTypeInfo,
ImportSuggestion,
Location,
ParsedExtractedMetadata,
-} from 'types/upload';
+} from "types/upload";
// list of format that were missed by type-detection for some files.
export const WHITELISTED_FILE_FORMATS: FileTypeInfo[] = [
- { fileType: FILE_TYPE.IMAGE, exactType: 'jpeg', mimeType: 'image/jpeg' },
- { fileType: FILE_TYPE.IMAGE, exactType: 'jpg', mimeType: 'image/jpeg' },
- { fileType: FILE_TYPE.VIDEO, exactType: 'webm', mimeType: 'video/webm' },
- { fileType: FILE_TYPE.VIDEO, exactType: 'mod', mimeType: 'video/mpeg' },
- { fileType: FILE_TYPE.VIDEO, exactType: 'mp4', mimeType: 'video/mp4' },
- { fileType: FILE_TYPE.IMAGE, exactType: 'gif', mimeType: 'image/gif' },
- { fileType: FILE_TYPE.VIDEO, exactType: 'dv', mimeType: 'video/x-dv' },
+ { fileType: FILE_TYPE.IMAGE, exactType: "jpeg", mimeType: "image/jpeg" },
+ { fileType: FILE_TYPE.IMAGE, exactType: "jpg", mimeType: "image/jpeg" },
+ { fileType: FILE_TYPE.VIDEO, exactType: "webm", mimeType: "video/webm" },
+ { fileType: FILE_TYPE.VIDEO, exactType: "mod", mimeType: "video/mpeg" },
+ { fileType: FILE_TYPE.VIDEO, exactType: "mp4", mimeType: "video/mp4" },
+ { fileType: FILE_TYPE.IMAGE, exactType: "gif", mimeType: "image/gif" },
+ { fileType: FILE_TYPE.VIDEO, exactType: "dv", mimeType: "video/x-dv" },
{
fileType: FILE_TYPE.VIDEO,
- exactType: 'wmv',
- mimeType: 'video/x-ms-asf',
+ exactType: "wmv",
+ mimeType: "video/x-ms-asf",
},
{
fileType: FILE_TYPE.VIDEO,
- exactType: 'hevc',
- mimeType: 'video/hevc',
+ exactType: "hevc",
+ mimeType: "video/hevc",
},
{
fileType: FILE_TYPE.IMAGE,
- exactType: 'raf',
- mimeType: 'image/x-fuji-raf',
+ exactType: "raf",
+ mimeType: "image/x-fuji-raf",
},
{
fileType: FILE_TYPE.IMAGE,
- exactType: 'orf',
- mimeType: 'image/x-olympus-orf',
+ exactType: "orf",
+ mimeType: "image/x-olympus-orf",
},
{
fileType: FILE_TYPE.IMAGE,
- exactType: 'crw',
- mimeType: 'image/x-canon-crw',
+ exactType: "crw",
+ mimeType: "image/x-canon-crw",
},
];
-export const KNOWN_NON_MEDIA_FORMATS = ['xmp', 'html', 'txt'];
+export const KNOWN_NON_MEDIA_FORMATS = ["xmp", "html", "txt"];
-export const EXIFLESS_FORMATS = ['gif', 'bmp'];
+export const EXIFLESS_FORMATS = ["gif", "bmp"];
// this is the chunk size of the un-encrypted file which is read and encrypted before uploading it as a single part.
export const MULTIPART_PART_SIZE = 20 * 1024 * 1024;
@@ -54,7 +54,7 @@ export const MULTIPART_PART_SIZE = 20 * 1024 * 1024;
export const FILE_READER_CHUNK_SIZE = ENCRYPTION_CHUNK_SIZE;
export const FILE_CHUNKS_COMBINED_FOR_A_UPLOAD_PART = Math.floor(
- MULTIPART_PART_SIZE / FILE_READER_CHUNK_SIZE
+ MULTIPART_PART_SIZE / FILE_READER_CHUNK_SIZE,
);
export const RANDOM_PERCENTAGE_PROGRESS_FOR_PUT = () => 90 + 10 * Math.random();
@@ -88,9 +88,9 @@ export enum UPLOAD_RESULT {
}
export enum PICKED_UPLOAD_TYPE {
- FILES = 'files',
- FOLDERS = 'folders',
- ZIPS = 'zips',
+ FILES = "files",
+ FOLDERS = "folders",
+ ZIPS = "zips",
}
export const MAX_FILE_SIZE_SUPPORTED = 4 * 1024 * 1024 * 1024; // 4 GB
@@ -107,36 +107,36 @@ export const NULL_EXTRACTED_METADATA: ParsedExtractedMetadata = {
export const A_SEC_IN_MICROSECONDS = 1e6;
export const DEFAULT_IMPORT_SUGGESTION: ImportSuggestion = {
- rootFolderName: '',
+ rootFolderName: "",
hasNestedFolders: false,
hasRootLevelFileWithFolder: false,
};
export const BLACK_THUMBNAIL_BASE64 =
- '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEB' +
- 'AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQ' +
- 'EBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARC' +
- 'ACWASwDAREAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF' +
- 'BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk' +
- '6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztL' +
- 'W2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAA' +
- 'AAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVY' +
- 'nLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImK' +
- 'kpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oAD' +
- 'AMBAAIRAxEAPwD/AD/6ACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA' +
- 'CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg' +
- 'AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKAC' +
- 'gAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo' +
- 'AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg' +
- 'AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg' +
- 'AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA' +
- 'CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA' +
- 'CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoA' +
- 'KACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg' +
- 'AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo' +
- 'AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA' +
- 'CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAK' +
- 'ACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoA' +
- 'KACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo' +
- 'AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo' +
- 'AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgD/9k=';
+ "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEB" +
+ "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQ" +
+ "EBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARC" +
+ "ACWASwDAREAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF" +
+ "BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk" +
+ "6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztL" +
+ "W2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAA" +
+ "AAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVY" +
+ "nLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImK" +
+ "kpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oAD" +
+ "AMBAAIRAxEAPwD/AD/6ACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA" +
+ "CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg" +
+ "AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKAC" +
+ "gAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo" +
+ "AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg" +
+ "AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg" +
+ "AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA" +
+ "CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA" +
+ "CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoA" +
+ "KACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg" +
+ "AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo" +
+ "AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA" +
+ "CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAK" +
+ "ACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoA" +
+ "KACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo" +
+ "AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo" +
+ "AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgD/9k=";
diff --git a/apps/cast/src/constants/urls.ts b/apps/cast/src/constants/urls.ts
index 291704e98f..7ec194dea4 100644
--- a/apps/cast/src/constants/urls.ts
+++ b/apps/cast/src/constants/urls.ts
@@ -1,19 +1,19 @@
-export const ENTE_WEBSITE_LINK = 'https://ente.io';
+export const ENTE_WEBSITE_LINK = "https://ente.io";
-export const ML_BLOG_LINK = 'https://ente.io/blog/desktop-ml-beta';
+export const ML_BLOG_LINK = "https://ente.io/blog/desktop-ml-beta";
export const FACE_SEARCH_PRIVACY_POLICY_LINK =
- 'https://ente.io/privacy#8-biometric-information-privacy-policy';
+ "https://ente.io/privacy#8-biometric-information-privacy-policy";
-export const SUPPORT_EMAIL = '[email protected]';
+export const SUPPORT_EMAIL = "[email protected]";
-export const APP_DOWNLOAD_URL = 'https://ente.io/download/desktop';
+export const APP_DOWNLOAD_URL = "https://ente.io/download/desktop";
-export const FEEDBACK_EMAIL = '[email protected]';
+export const FEEDBACK_EMAIL = "[email protected]";
-export const DELETE_ACCOUNT_EMAIL = '[email protected]';
+export const DELETE_ACCOUNT_EMAIL = "[email protected]";
-export const WEB_ROADMAP_URL = 'https://github.com/ente-io/photos-web/issues';
+export const WEB_ROADMAP_URL = "https://github.com/ente-io/photos-web/issues";
export const DESKTOP_ROADMAP_URL =
- 'https://github.com/ente-io/photos-desktop/issues';
+ "https://github.com/ente-io/photos-desktop/issues";
diff --git a/apps/cast/src/pages/_app.tsx b/apps/cast/src/pages/_app.tsx
index 4d504197be..8874d956d1 100644
--- a/apps/cast/src/pages/_app.tsx
+++ b/apps/cast/src/pages/_app.tsx
@@ -1,9 +1,9 @@
-import type { AppProps } from 'next/app';
-import 'styles/global.css';
-import { ThemeProvider, CssBaseline } from '@mui/material';
-import { getTheme } from '@ente/shared/themes';
-import { THEME_COLOR } from '@ente/shared/themes/constants';
-import { APPS } from '@ente/shared/apps/constants';
+import { APPS } from "@ente/shared/apps/constants";
+import { getTheme } from "@ente/shared/themes";
+import { THEME_COLOR } from "@ente/shared/themes/constants";
+import { CssBaseline, ThemeProvider } from "@mui/material";
+import type { AppProps } from "next/app";
+import "styles/global.css";
export default function App({ Component, pageProps }: AppProps) {
return (
@@ -12,8 +12,9 @@ export default function App({ Component, pageProps }: AppProps) {
<main
style={{
- display: 'contents',
- }}>
+ display: "contents",
+ }}
+ >
<Component {...pageProps} />
</main>
</ThemeProvider>
diff --git a/apps/cast/src/pages/_document.tsx b/apps/cast/src/pages/_document.tsx
index 560edf99e7..b038dc04e7 100644
--- a/apps/cast/src/pages/_document.tsx
+++ b/apps/cast/src/pages/_document.tsx
@@ -1,22 +1,24 @@
-import { Html, Head, Main, NextScript } from 'next/document';
+import { Head, Html, Main, NextScript } from "next/document";
export default function Document() {
return (
<Html
lang="en"
style={{
- height: '100%',
- width: '100%',
- }}>
+ height: "100%",
+ width: "100%",
+ }}
+ >
<Head />
<body
style={{
- height: '100%',
- width: '100%',
+ height: "100%",
+ width: "100%",
margin: 0,
- backgroundColor: 'black',
- color: 'white',
- }}>
+ backgroundColor: "black",
+ color: "white",
+ }}
+ >
<Main />
<NextScript />
</body>
diff --git a/apps/cast/src/pages/index.tsx b/apps/cast/src/pages/index.tsx
index 30da9bf1a4..dcdee782bf 100644
--- a/apps/cast/src/pages/index.tsx
+++ b/apps/cast/src/pages/index.tsx
@@ -1,13 +1,13 @@
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { boxSealOpen, toB64 } from '@ente/shared/crypto/internal/libsodium';
-import { useCastReceiver } from '@ente/shared/hooks/useCastReceiver';
-import { addLogLine } from '@ente/shared/logging';
-import castGateway from '@ente/shared/network/cast';
-import LargeType from 'components/LargeType';
-import _sodium from 'libsodium-wrappers';
-import { useRouter } from 'next/router';
-import { useEffect, useState } from 'react';
-import { storeCastData } from 'services/cast/castService';
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import { boxSealOpen, toB64 } from "@ente/shared/crypto/internal/libsodium";
+import { useCastReceiver } from "@ente/shared/hooks/useCastReceiver";
+import { addLogLine } from "@ente/shared/logging";
+import castGateway from "@ente/shared/network/cast";
+import LargeType from "components/LargeType";
+import _sodium from "libsodium-wrappers";
+import { useRouter } from "next/router";
+import { useEffect, useState } from "react";
+import { storeCastData } from "services/cast/castService";
// Function to generate cryptographically secure digits
const generateSecureData = (length: number): Uint8Array => {
@@ -21,7 +21,7 @@ const generateSecureData = (length: number): Uint8Array => {
};
const convertDataToDecimalString = (data: Uint8Array): string => {
- let decimalString = '';
+ let decimalString = "";
for (let i = 0; i < data.length; i++) {
decimalString += data[i].toString(); // No need to pad, as each value is a single digit
}
@@ -30,8 +30,8 @@ const convertDataToDecimalString = (data: Uint8Array): string => {
export default function PairingMode() {
const [digits, setDigits] = useState<string[]>([]);
- const [publicKeyB64, setPublicKeyB64] = useState('');
- const [privateKeyB64, setPrivateKeyB64] = useState('');
+ const [publicKeyB64, setPublicKeyB64] = useState("");
+ const [privateKeyB64, setPrivateKeyB64] = useState("");
const [codePending, setCodePending] = useState(true);
const [isCastReady, setIsCastReady] = useState(false);
@@ -49,18 +49,18 @@ export default function PairingMode() {
try {
const options = new cast.framework.CastReceiverOptions();
options.customNamespaces = Object.assign({});
- options.customNamespaces['urn:x-cast:pair-request'] =
+ options.customNamespaces["urn:x-cast:pair-request"] =
cast.framework.system.MessageType.JSON;
options.disableIdleTimeout = true;
context.addCustomMessageListener(
- 'urn:x-cast:pair-request',
- messageReceiveHandler
+ "urn:x-cast:pair-request",
+ messageReceiveHandler,
);
context.start(options);
} catch (e) {
- addLogLine(e, 'failed to create cast context');
+ addLogLine(e, "failed to create cast context");
}
setIsCastReady(true);
return () => {
@@ -74,17 +74,17 @@ export default function PairingMode() {
data: any;
}) => {
cast.framework.CastReceiverContext.getInstance().sendCustomMessage(
- 'urn:x-cast:pair-request',
+ "urn:x-cast:pair-request",
message.senderId,
{
- code: digits.join(''),
- }
+ code: digits.join(""),
+ },
);
};
const init = async () => {
const data = generateSecureData(6);
- setDigits(convertDataToDecimalString(data).split(''));
+ setDigits(convertDataToDecimalString(data).split(""));
const keypair = await generateKeyPair();
setPublicKeyB64(await toB64(keypair.publicKey));
setPrivateKeyB64(await toB64(keypair.privateKey));
@@ -105,10 +105,10 @@ export default function PairingMode() {
// see if we were acknowledged on the client.
// the client will send us the encrypted payload using our public key that we advertised.
// then, we can decrypt this and store all the necessary info locally so we can play the collection slideshow.
- let devicePayload = '';
+ let devicePayload = "";
try {
const encDastData = await castGateway.getCastData(
- `${digits.join('')}`
+ `${digits.join("")}`,
);
if (!encDastData) return;
devicePayload = encDastData;
@@ -121,7 +121,7 @@ export default function PairingMode() {
const decryptedPayload = await boxSealOpen(
devicePayload,
publicKeyB64,
- privateKeyB64
+ privateKeyB64,
);
const decryptedPayloadObj = JSON.parse(atob(decryptedPayload));
@@ -133,8 +133,8 @@ export default function PairingMode() {
// hey client, we exist!
try {
await castGateway.registerDevice(
- `${digits.join('')}`,
- publicKeyB64
+ `${digits.join("")}`,
+ publicKeyB64,
);
setCodePending(false);
} catch (e) {
@@ -155,7 +155,7 @@ export default function PairingMode() {
const data = await pollForCastData();
if (!data) return;
storeCastData(data);
- await router.push('/slideshow');
+ await router.push("/slideshow");
}, 1000);
return () => {
@@ -172,30 +172,34 @@ export default function PairingMode() {
<>
<div
style={{
- height: '100%',
- display: 'flex',
- justifyContent: 'center',
- alignItems: 'center',
- }}>
+ height: "100%",
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ }}
+ >
<div
style={{
- textAlign: 'center',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- }}>
+ textAlign: "center",
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ }}
+ >
<img width={150} src="/images/ente.svg" />
<h1
style={{
- fontWeight: 'normal',
- }}>
+ fontWeight: "normal",
+ }}
+ >
Enter this code on <b>ente</b> to pair this TV
</h1>
<div
style={{
- borderRadius: '10px',
- overflow: 'hidden',
- }}>
+ borderRadius: "10px",
+ overflow: "hidden",
+ }}
+ >
{codePending ? (
<EnteSpinner />
) : (
@@ -206,33 +210,36 @@ export default function PairingMode() {
</div>
<p
style={{
- fontSize: '1.2rem',
- }}>
- Visit{' '}
+ fontSize: "1.2rem",
+ }}
+ >
+ Visit{" "}
<a
style={{
- textDecoration: 'none',
- color: '#87CEFA',
- fontWeight: 'bold',
+ textDecoration: "none",
+ color: "#87CEFA",
+ fontWeight: "bold",
}}
href="https://ente.io/cast"
- target="_blank">
+ target="_blank"
+ >
ente.io/cast
- </a>{' '}
+ </a>{" "}
for help
</p>
<div
style={{
- position: 'fixed',
- bottom: '20px',
- right: '20px',
- backgroundColor: 'white',
- display: 'flex',
- justifyContent: 'center',
- alignItems: 'center',
- padding: '10px',
- borderRadius: '10px',
- }}>
+ position: "fixed",
+ bottom: "20px",
+ right: "20px",
+ backgroundColor: "white",
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ padding: "10px",
+ borderRadius: "10px",
+ }}
+ >
<img src="/images/help-qrcode.webp" />
</div>
</div>
diff --git a/apps/cast/src/pages/slideshow.tsx b/apps/cast/src/pages/slideshow.tsx
index e8363cb767..a49d497de0 100644
--- a/apps/cast/src/pages/slideshow.tsx
+++ b/apps/cast/src/pages/slideshow.tsx
@@ -1,17 +1,17 @@
-import { logError } from '@ente/shared/sentry';
-import PairedSuccessfullyOverlay from 'components/PairedSuccessfullyOverlay';
-import Theatre from 'components/Theatre';
-import { FILE_TYPE } from 'constants/file';
-import { useRouter } from 'next/router';
-import { createContext, useEffect, useState } from 'react';
+import { logError } from "@ente/shared/sentry";
+import PairedSuccessfullyOverlay from "components/PairedSuccessfullyOverlay";
+import Theatre from "components/Theatre";
+import { FILE_TYPE } from "constants/file";
+import { useRouter } from "next/router";
+import { createContext, useEffect, useState } from "react";
import {
getCastCollection,
getLocalFiles,
syncPublicFiles,
-} from 'services/cast/castService';
-import { Collection } from 'types/collection';
-import { EnteFile } from 'types/file';
-import { getPreviewableImage, isRawFileFromFileName } from 'utils/file';
+} from "services/cast/castService";
+import { Collection } from "types/collection";
+import { EnteFile } from "types/file";
+import { getPreviewableImage, isRawFileFromFileName } from "utils/file";
export const SlideshowContext = createContext<{
showNextSlide: () => void;
@@ -23,24 +23,24 @@ export default function Slideshow() {
const [collectionFiles, setCollectionFiles] = useState<EnteFile[]>([]);
const [currentFile, setCurrentFile] = useState<EnteFile | undefined>(
- undefined
+ undefined,
);
const [nextFile, setNextFile] = useState<EnteFile | undefined>(undefined);
const [loading, setLoading] = useState(true);
- const [castToken, setCastToken] = useState<string>('');
+ const [castToken, setCastToken] = useState<string>("");
const [castCollection, setCastCollection] = useState<
Collection | undefined
>(undefined);
const syncCastFiles = async (token: string) => {
try {
- const castToken = window.localStorage.getItem('castToken');
+ const castToken = window.localStorage.getItem("castToken");
const requestedCollectionKey =
- window.localStorage.getItem('collectionKey');
+ window.localStorage.getItem("collectionKey");
const collection = await getCastCollection(
castToken,
- requestedCollectionKey
+ requestedCollectionKey,
);
if (
castCollection === undefined ||
@@ -50,22 +50,22 @@ export default function Slideshow() {
await syncPublicFiles(token, collection, () => {});
const files = await getLocalFiles(String(collection.id));
setCollectionFiles(
- files.filter((file) => isFileEligibleForCast(file))
+ files.filter((file) => isFileEligibleForCast(file)),
);
}
} catch (e) {
- logError(e, 'error during sync');
- router.push('/');
+ logError(e, "error during sync");
+ router.push("/");
}
};
const init = async () => {
try {
- const castToken = window.localStorage.getItem('castToken');
+ const castToken = window.localStorage.getItem("castToken");
setCastToken(castToken);
} catch (e) {
- logError(e, 'error during sync');
- router.push('/');
+ logError(e, "error during sync");
+ router.push("/");
}
};
@@ -115,7 +115,7 @@ export default function Slideshow() {
const showNextSlide = () => {
const currentIndex = collectionFiles.findIndex(
- (file) => file.id === currentFile?.id
+ (file) => file.id === currentFile?.id,
);
const nextIndex = (currentIndex + 1) % collectionFiles.length;
@@ -128,7 +128,7 @@ export default function Slideshow() {
setNextFile(nextNextFile);
};
- const [renderableFileURL, setRenderableFileURL] = useState<string>('');
+ const [renderableFileURL, setRenderableFileURL] = useState<string>("");
const getRenderableFileURL = async () => {
if (!currentFile) return;
@@ -143,7 +143,7 @@ export default function Slideshow() {
try {
const blob = await getPreviewableImage(
currentFile as EnteFile,
- castToken
+ castToken,
);
const url = URL.createObjectURL(blob);
diff --git a/apps/cast/src/services/InMemoryStore.ts b/apps/cast/src/services/InMemoryStore.ts
index 82e0155a68..ded73faf05 100644
--- a/apps/cast/src/services/InMemoryStore.ts
+++ b/apps/cast/src/services/InMemoryStore.ts
@@ -1,7 +1,7 @@
export enum MS_KEYS {
- OPT_OUT_OF_CRASH_REPORTS = 'optOutOfCrashReports',
- SRP_CONFIGURE_IN_PROGRESS = 'srpConfigureInProgress',
- REDIRECT_URL = 'redirectUrl',
+ OPT_OUT_OF_CRASH_REPORTS = "optOutOfCrashReports",
+ SRP_CONFIGURE_IN_PROGRESS = "srpConfigureInProgress",
+ REDIRECT_URL = "redirectUrl",
}
type StoreType = Map<Partial<MS_KEYS>, any>;
diff --git a/apps/cast/src/services/cache/cacheStorageFactory.ts b/apps/cast/src/services/cache/cacheStorageFactory.ts
index bb007977c7..fd979e2f9c 100644
--- a/apps/cast/src/services/cache/cacheStorageFactory.ts
+++ b/apps/cast/src/services/cache/cacheStorageFactory.ts
@@ -1,4 +1,4 @@
-import { LimitedCacheStorage } from 'types/cache/index';
+import { LimitedCacheStorage } from "types/cache/index";
// import { ElectronCacheStorage } from 'services/electron/cache';
// import { runningInElectron, runningInWorker } from 'utils/common';
// import { WorkerElectronCacheStorageService } from 'services/workerElectronCache/service';
@@ -25,7 +25,7 @@ class cacheStorageFactory {
export const CacheStorageFactory = new cacheStorageFactory();
function transformBrowserCacheStorageToLimitedCacheStorage(
- caches: CacheStorage
+ caches: CacheStorage,
): LimitedCacheStorage {
return {
async open(cacheName) {
diff --git a/apps/cast/src/services/cache/cacheStorageService.ts b/apps/cast/src/services/cache/cacheStorageService.ts
index 87df2063bf..391aefb552 100644
--- a/apps/cast/src/services/cache/cacheStorageService.ts
+++ b/apps/cast/src/services/cache/cacheStorageService.ts
@@ -1,8 +1,8 @@
-import { logError } from '@ente/shared/sentry';
-import { CacheStorageFactory } from './cacheStorageFactory';
+import { logError } from "@ente/shared/sentry";
+import { CacheStorageFactory } from "./cacheStorageFactory";
-const SecurityError = 'SecurityError';
-const INSECURE_OPERATION = 'The operation is insecure.';
+const SecurityError = "SecurityError";
+const INSECURE_OPERATION = "The operation is insecure.";
async function openCache(cacheName: string) {
try {
return await CacheStorageFactory.getCacheStorage().open(cacheName);
@@ -12,7 +12,7 @@ async function openCache(cacheName: string) {
// no-op
} else {
// log and ignore, we don't want to break the caller flow, when cache is not available
- logError(e, 'openCache failed');
+ logError(e, "openCache failed");
}
}
}
@@ -25,7 +25,7 @@ async function deleteCache(cacheName: string) {
// no-op
} else {
// log and ignore, we don't want to break the caller flow, when cache is not available
- logError(e, 'deleteCache failed');
+ logError(e, "deleteCache failed");
}
}
}
diff --git a/apps/cast/src/services/cast/castService.ts b/apps/cast/src/services/cast/castService.ts
index 755c7878ac..0f8b368a53 100644
--- a/apps/cast/src/services/cast/castService.ts
+++ b/apps/cast/src/services/cast/castService.ts
@@ -1,51 +1,51 @@
-import { getEndpoint } from '@ente/shared/network/api';
-import localForage from '@ente/shared/storage/localForage';
-import HTTPService from '@ente/shared/network/HTTPService';
-import { logError } from '@ente/shared/sentry';
-import { CustomError, parseSharingErrorCodes } from '@ente/shared/error';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { CustomError, parseSharingErrorCodes } from "@ente/shared/error";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getEndpoint } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import localForage from "@ente/shared/storage/localForage";
-import { Collection, CollectionPublicMagicMetadata } from 'types/collection';
-import { EncryptedEnteFile, EnteFile } from 'types/file';
-import { decryptFile, mergeMetadata, sortFiles } from 'utils/file';
+import { Collection, CollectionPublicMagicMetadata } from "types/collection";
+import { EncryptedEnteFile, EnteFile } from "types/file";
+import { decryptFile, mergeMetadata, sortFiles } from "utils/file";
export interface SavedCollectionFiles {
collectionLocalID: string;
files: EnteFile[];
}
const ENDPOINT = getEndpoint();
-const COLLECTION_FILES_TABLE = 'collection-files';
-const COLLECTIONS_TABLE = 'collections';
+const COLLECTION_FILES_TABLE = "collection-files";
+const COLLECTIONS_TABLE = "collections";
const getLastSyncKey = (collectionUID: string) => `${collectionUID}-time`;
export const getLocalFiles = async (
- collectionUID: string
+ collectionUID: string,
): Promise<EnteFile[]> => {
const localSavedcollectionFiles =
(await localForage.getItem<SavedCollectionFiles[]>(
- COLLECTION_FILES_TABLE
+ COLLECTION_FILES_TABLE,
)) || [];
const matchedCollection = localSavedcollectionFiles.find(
- (item) => item.collectionLocalID === collectionUID
+ (item) => item.collectionLocalID === collectionUID,
);
return matchedCollection?.files || [];
};
const savecollectionFiles = async (
collectionUID: string,
- files: EnteFile[]
+ files: EnteFile[],
) => {
const collectionFiles =
(await localForage.getItem<SavedCollectionFiles[]>(
- COLLECTION_FILES_TABLE
+ COLLECTION_FILES_TABLE,
)) || [];
await localForage.setItem(
COLLECTION_FILES_TABLE,
dedupeCollectionFiles([
{ collectionLocalID: collectionUID, files },
...collectionFiles,
- ])
+ ]),
);
};
@@ -55,7 +55,7 @@ export const getLocalCollections = async (collectionKey: string) => {
const collection =
localCollections.find(
(localSavedPublicCollection) =>
- localSavedPublicCollection.key === collectionKey
+ localSavedPublicCollection.key === collectionKey,
) || null;
return collection;
};
@@ -65,7 +65,7 @@ const saveCollection = async (collection: Collection) => {
(await localForage.getItem<Collection[]>(COLLECTIONS_TABLE)) ?? [];
await localForage.setItem(
COLLECTIONS_TABLE,
- dedupeCollections([collection, ...collections])
+ dedupeCollections([collection, ...collections]),
);
};
@@ -105,7 +105,7 @@ const updateSyncTime = async (collectionUID: string, time: number) =>
export const syncPublicFiles = async (
token: string,
collection: Collection,
- setPublicFiles: (files: EnteFile[]) => void
+ setPublicFiles: (files: EnteFile[]) => void,
) => {
try {
let files: EnteFile[] = [];
@@ -123,7 +123,7 @@ export const syncPublicFiles = async (
collection,
lastSyncTime,
files,
- setPublicFiles
+ setPublicFiles,
);
files = [...files, ...fetchedFiles];
@@ -150,14 +150,14 @@ export const syncPublicFiles = async (
setPublicFiles([...sortFiles(mergeMetadata(files), sortAsc)]);
} catch (e) {
const parsedError = parseSharingErrorCodes(e);
- logError(e, 'failed to sync shared collection files');
+ logError(e, "failed to sync shared collection files");
if (parsedError.message === CustomError.TOKEN_EXPIRED) {
throw e;
}
}
return [...sortFiles(mergeMetadata(files), sortAsc)];
} catch (e) {
- logError(e, 'failed to get local or sync shared collection files');
+ logError(e, "failed to get local or sync shared collection files");
throw e;
}
};
@@ -167,7 +167,7 @@ const fetchFiles = async (
collection: Collection,
sinceTime: number,
files: EnteFile[],
- setPublicFiles: (files: EnteFile[]) => void
+ setPublicFiles: (files: EnteFile[]) => void,
): Promise<EnteFile[]> => {
try {
let decryptedFiles: EnteFile[] = [];
@@ -184,9 +184,9 @@ const fetchFiles = async (
sinceTime: time,
},
{
- 'Cache-Control': 'no-cache',
- 'X-Cast-Access-Token': castToken,
- }
+ "Cache-Control": "no-cache",
+ "X-Cast-Access-Token": castToken,
+ },
);
decryptedFiles = [
...decryptedFiles,
@@ -197,7 +197,7 @@ const fetchFiles = async (
} else {
return file;
}
- }) as Promise<EnteFile>[]
+ }) as Promise<EnteFile>[],
)),
];
@@ -208,28 +208,28 @@ const fetchFiles = async (
sortFiles(
mergeMetadata(
[...(files || []), ...decryptedFiles].filter(
- (item) => !item.isDeleted
- )
+ (item) => !item.isDeleted,
+ ),
),
- sortAsc
- )
+ sortAsc,
+ ),
);
} while (resp.data.hasMore);
return decryptedFiles;
} catch (e) {
- logError(e, 'Get cast files failed');
+ logError(e, "Get cast files failed");
throw e;
}
};
export const getCastCollection = async (
castToken: string,
- collectionKey: string
+ collectionKey: string,
): Promise<Collection> => {
try {
const resp = await HTTPService.get(`${ENDPOINT}/cast/info`, null, {
- 'Cache-Control': 'no-cache',
- 'X-Cast-Access-Token': castToken,
+ "Cache-Control": "no-cache",
+ "X-Cast-Access-Token": castToken,
});
const fetchedCollection = resp.data.collection;
@@ -240,7 +240,7 @@ export const getCastCollection = async (
(await cryptoWorker.decryptToUTF8(
fetchedCollection.encryptedName,
fetchedCollection.nameDecryptionNonce,
- collectionKey
+ collectionKey,
)));
let collectionPublicMagicMetadata: CollectionPublicMagicMetadata;
@@ -250,7 +250,7 @@ export const getCastCollection = async (
data: await cryptoWorker.decryptMetadata(
fetchedCollection.pubMagicMetadata.data,
fetchedCollection.pubMagicMetadata.header,
- collectionKey
+ collectionKey,
),
};
}
@@ -264,20 +264,20 @@ export const getCastCollection = async (
await saveCollection(collection);
return collection;
} catch (e) {
- logError(e, 'failed to get cast collection');
+ logError(e, "failed to get cast collection");
throw e;
}
};
export const removeCollection = async (
collectionUID: string,
- collectionKey: string
+ collectionKey: string,
) => {
const collections =
(await localForage.getItem<Collection[]>(COLLECTIONS_TABLE)) || [];
await localForage.setItem(
COLLECTIONS_TABLE,
- collections.filter((collection) => collection.key !== collectionKey)
+ collections.filter((collection) => collection.key !== collectionKey),
);
await removeCollectionFiles(collectionUID);
};
@@ -286,14 +286,14 @@ export const removeCollectionFiles = async (collectionUID: string) => {
await localForage.removeItem(getLastSyncKey(collectionUID));
const collectionFiles =
(await localForage.getItem<SavedCollectionFiles[]>(
- COLLECTION_FILES_TABLE
+ COLLECTION_FILES_TABLE,
)) ?? [];
await localForage.setItem(
COLLECTION_FILES_TABLE,
collectionFiles.filter(
(collectionFiles) =>
- collectionFiles.collectionLocalID !== collectionUID
- )
+ collectionFiles.collectionLocalID !== collectionUID,
+ ),
);
};
diff --git a/apps/cast/src/services/castDownloadManager.ts b/apps/cast/src/services/castDownloadManager.ts
index c1a786c763..b56aec928c 100644
--- a/apps/cast/src/services/castDownloadManager.ts
+++ b/apps/cast/src/services/castDownloadManager.ts
@@ -1,19 +1,19 @@
+import { EnteFile } from "types/file";
import {
+ createTypedObjectURL,
generateStreamFromArrayBuffer,
getRenderableFileURL,
- createTypedObjectURL,
-} from 'utils/file';
-import { EnteFile } from 'types/file';
+} from "utils/file";
-import { FILE_TYPE } from 'constants/file';
-import { CustomError } from '@ente/shared/error';
-import ComlinkCryptoWorker from 'utils/comlink/ComlinkCryptoWorker';
-import { CACHES } from 'constants/cache';
-import { CacheStorageService } from './cache/cacheStorageService';
-import { LimitedCache } from 'types/cache';
-import { getCastFileURL, getCastThumbnailURL } from '@ente/shared/network/api';
-import HTTPService from '@ente/shared/network/HTTPService';
-import { logError } from '@ente/shared/sentry';
+import { CustomError } from "@ente/shared/error";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getCastFileURL, getCastThumbnailURL } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import { CACHES } from "constants/cache";
+import { FILE_TYPE } from "constants/file";
+import { LimitedCache } from "types/cache";
+import ComlinkCryptoWorker from "utils/comlink/ComlinkCryptoWorker";
+import { CacheStorageService } from "./cache/cacheStorageService";
class CastDownloadManager {
private fileObjectURLPromise = new Map<
@@ -33,7 +33,7 @@ class CastDownloadManager {
private async getThumbnailCache() {
try {
const thumbnailCache = await CacheStorageService.open(
- CACHES.THUMBS
+ CACHES.THUMBS,
);
return thumbnailCache;
} catch (e) {
@@ -44,14 +44,14 @@ class CastDownloadManager {
public async getCachedThumbnail(
file: EnteFile,
- thumbnailCache?: LimitedCache
+ thumbnailCache?: LimitedCache,
) {
try {
if (!thumbnailCache) {
thumbnailCache = await this.getThumbnailCache();
}
const cacheResp: Response = await thumbnailCache?.match(
- file.id.toString()
+ file.id.toString(),
);
if (cacheResp) {
@@ -59,7 +59,7 @@ class CastDownloadManager {
}
return null;
} catch (e) {
- logError(e, 'failed to get cached thumbnail');
+ logError(e, "failed to get cached thumbnail");
throw e;
}
}
@@ -71,7 +71,7 @@ class CastDownloadManager {
const thumbnailCache = await this.getThumbnailCache();
const cachedThumb = await this.getCachedThumbnail(
file,
- thumbnailCache
+ thumbnailCache,
);
if (cachedThumb) {
return cachedThumb;
@@ -82,7 +82,7 @@ class CastDownloadManager {
try {
await thumbnailCache?.put(
file.id.toString(),
- new Response(thumbBlob)
+ new Response(thumbBlob),
);
} catch (e) {
// TODO: handle storage full exception.
@@ -95,7 +95,7 @@ class CastDownloadManager {
return await this.thumbnailObjectURLPromise.get(file.id);
} catch (e) {
this.thumbnailObjectURLPromise.delete(file.id);
- logError(e, 'get castDownloadManager preview Failed');
+ logError(e, "get castDownloadManager preview Failed");
throw e;
}
}
@@ -105,18 +105,18 @@ class CastDownloadManager {
getCastThumbnailURL(file.id),
null,
{
- 'X-Cast-Access-Token': castToken,
+ "X-Cast-Access-Token": castToken,
},
- { responseType: 'arraybuffer' }
+ { responseType: "arraybuffer" },
);
- if (typeof resp.data === 'undefined') {
+ if (typeof resp.data === "undefined") {
throw Error(CustomError.REQUEST_FAILED);
}
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
const decrypted = await cryptoWorker.decryptThumbnail(
new Uint8Array(resp.data),
await cryptoWorker.fromB64(file.thumbnail.decryptionHeader),
- file.key
+ file.key,
);
return decrypted;
};
@@ -132,7 +132,7 @@ class CastDownloadManager {
} else {
const fileURL = await createTypedObjectURL(
fileBlob,
- file.metadata.title
+ file.metadata.title,
);
return { converted: [fileURL], original: [fileURL] };
}
@@ -145,7 +145,7 @@ class CastDownloadManager {
return fileURLs;
} catch (e) {
this.fileObjectURLPromise.delete(fileKey);
- logError(e, 'castDownloadManager failed to get file');
+ logError(e, "castDownloadManager failed to get file");
throw e;
}
};
@@ -166,40 +166,40 @@ class CastDownloadManager {
getCastFileURL(file.id),
null,
{
- 'X-Cast-Access-Token': castToken,
+ "X-Cast-Access-Token": castToken,
},
- { responseType: 'arraybuffer' }
+ { responseType: "arraybuffer" },
);
- if (typeof resp.data === 'undefined') {
+ if (typeof resp.data === "undefined") {
throw Error(CustomError.REQUEST_FAILED);
}
const decrypted = await cryptoWorker.decryptFile(
new Uint8Array(resp.data),
await cryptoWorker.fromB64(file.file.decryptionHeader),
- file.key
+ file.key,
);
return generateStreamFromArrayBuffer(decrypted);
}
const resp = await fetch(getCastFileURL(file.id), {
headers: {
- 'X-Cast-Access-Token': castToken,
+ "X-Cast-Access-Token": castToken,
},
});
const reader = resp.body.getReader();
- const contentLength = +resp.headers.get('Content-Length');
+ const contentLength = +resp.headers.get("Content-Length");
let downloadedBytes = 0;
const stream = new ReadableStream({
async start(controller) {
const decryptionHeader = await cryptoWorker.fromB64(
- file.file.decryptionHeader
+ file.file.decryptionHeader,
);
const fileKey = await cryptoWorker.fromB64(file.key);
const { pullState, decryptionChunkSize } =
await cryptoWorker.initChunkDecryption(
decryptionHeader,
- fileKey
+ fileKey,
);
let data = new Uint8Array();
// The following function handles each data chunk
@@ -214,19 +214,19 @@ class CastDownloadManager {
total: contentLength,
});
const buffer = new Uint8Array(
- data.byteLength + value.byteLength
+ data.byteLength + value.byteLength,
);
buffer.set(new Uint8Array(data), 0);
buffer.set(new Uint8Array(value), data.byteLength);
if (buffer.length > decryptionChunkSize) {
const fileData = buffer.slice(
0,
- decryptionChunkSize
+ decryptionChunkSize,
);
const { decryptedData } =
await cryptoWorker.decryptFileChunk(
fileData,
- pullState
+ pullState,
);
controller.enqueue(decryptedData);
data = buffer.slice(decryptionChunkSize);
@@ -239,7 +239,7 @@ class CastDownloadManager {
const { decryptedData } =
await cryptoWorker.decryptFileChunk(
data,
- pullState
+ pullState,
);
controller.enqueue(decryptedData);
data = null;
@@ -262,7 +262,7 @@ class CastDownloadManager {
} else {
this.fileDownloadProgress.set(
fileID,
- Math.round((event.loaded * 100) / event.total)
+ Math.round((event.loaded * 100) / event.total),
);
}
this.progressUpdater(new Map(this.fileDownloadProgress));
diff --git a/apps/cast/src/services/events.ts b/apps/cast/src/services/events.ts
index 670ecac47c..32306fc64d 100644
--- a/apps/cast/src/services/events.ts
+++ b/apps/cast/src/services/events.ts
@@ -1,12 +1,12 @@
-import { EventEmitter } from 'eventemitter3';
+import { EventEmitter } from "eventemitter3";
// When registering event handlers,
// handle errors to avoid unhandled rejection or propagation to emit call
export enum Events {
- LOGOUT = 'logout',
- FILE_UPLOADED = 'fileUploaded',
- LOCAL_FILES_UPDATED = 'localFilesUpdated',
+ LOGOUT = "logout",
+ FILE_UPLOADED = "fileUploaded",
+ LOCAL_FILES_UPDATED = "localFilesUpdated",
}
export const eventBus = new EventEmitter<Events>();
diff --git a/apps/cast/src/services/ffmpeg/ffmpegFactory.ts b/apps/cast/src/services/ffmpeg/ffmpegFactory.ts
index eca7287c60..b3c716d995 100644
--- a/apps/cast/src/services/ffmpeg/ffmpegFactory.ts
+++ b/apps/cast/src/services/ffmpeg/ffmpegFactory.ts
@@ -1,14 +1,14 @@
// import isElectron from 'is-electron';
// import { ElectronFFmpeg } from 'services/electron/ffmpeg';
-import { ElectronFile } from 'types/upload';
-import ComlinkFFmpegWorker from 'utils/comlink/ComlinkFFmpegWorker';
+import { ElectronFile } from "types/upload";
+import ComlinkFFmpegWorker from "utils/comlink/ComlinkFFmpegWorker";
export interface IFFmpeg {
run: (
cmd: string[],
inputFile: File | ElectronFile,
outputFilename: string,
- dontTimeout?: boolean
+ dontTimeout?: boolean,
) => Promise<File | ElectronFile>;
}
diff --git a/apps/cast/src/services/ffmpeg/ffmpegService.ts b/apps/cast/src/services/ffmpeg/ffmpegService.ts
index 4e6a6241fb..85bab9939e 100644
--- a/apps/cast/src/services/ffmpeg/ffmpegService.ts
+++ b/apps/cast/src/services/ffmpeg/ffmpegService.ts
@@ -1,11 +1,11 @@
+import { logError } from "@ente/shared/sentry";
import {
FFMPEG_PLACEHOLDER,
INPUT_PATH_PLACEHOLDER,
OUTPUT_PATH_PLACEHOLDER,
-} from 'constants/ffmpeg';
-import { ElectronFile } from 'types/upload';
-import ffmpegFactory from './ffmpegFactory';
-import { logError } from '@ente/shared/sentry';
+} from "constants/ffmpeg";
+import { ElectronFile } from "types/upload";
+import ffmpegFactory from "./ffmpegFactory";
export async function convertToMP4(file: File | ElectronFile) {
try {
@@ -13,18 +13,18 @@ export async function convertToMP4(file: File | ElectronFile) {
return await ffmpegClient.run(
[
FFMPEG_PLACEHOLDER,
- '-i',
+ "-i",
INPUT_PATH_PLACEHOLDER,
- '-preset',
- 'ultrafast',
+ "-preset",
+ "ultrafast",
OUTPUT_PATH_PLACEHOLDER,
],
file,
- 'output.mp4',
- true
+ "output.mp4",
+ true,
);
} catch (e) {
- logError(e, 'ffmpeg convertToMP4 failed');
+ logError(e, "ffmpeg convertToMP4 failed");
throw e;
}
}
diff --git a/apps/cast/src/services/heicConversionService.ts b/apps/cast/src/services/heicConversionService.ts
index 00f49b7db8..f11a9f4a4e 100644
--- a/apps/cast/src/services/heicConversionService.ts
+++ b/apps/cast/src/services/heicConversionService.ts
@@ -1,12 +1,12 @@
-import { logError } from '@ente/shared/sentry';
-import WasmHEICConverterService from './wasmHeicConverter/wasmHEICConverterService';
+import { logError } from "@ente/shared/sentry";
+import WasmHEICConverterService from "./wasmHeicConverter/wasmHEICConverterService";
class HeicConversionService {
async convert(heicFileData: Blob): Promise<Blob> {
try {
return await WasmHEICConverterService.convert(heicFileData);
} catch (e) {
- logError(e, 'failed to convert heic file');
+ logError(e, "failed to convert heic file");
throw e;
}
}
diff --git a/apps/cast/src/services/livePhotoService.ts b/apps/cast/src/services/livePhotoService.ts
index 613d2861ec..4d96e812cc 100644
--- a/apps/cast/src/services/livePhotoService.ts
+++ b/apps/cast/src/services/livePhotoService.ts
@@ -1,9 +1,9 @@
-import JSZip from 'jszip';
-import { EnteFile } from 'types/file';
+import JSZip from "jszip";
+import { EnteFile } from "types/file";
import {
getFileExtensionWithDot,
getFileNameWithoutExtension,
-} from 'utils/file';
+} from "utils/file";
class LivePhoto {
image: Uint8Array;
@@ -18,14 +18,14 @@ export const decodeLivePhoto = async (file: EnteFile, zipBlob: Blob) => {
const livePhoto = new LivePhoto();
for (const zipFilename in zip.files) {
- if (zipFilename.startsWith('image')) {
+ if (zipFilename.startsWith("image")) {
livePhoto.imageNameTitle =
originalName + getFileExtensionWithDot(zipFilename);
- livePhoto.image = await zip.files[zipFilename].async('uint8array');
- } else if (zipFilename.startsWith('video')) {
+ livePhoto.image = await zip.files[zipFilename].async("uint8array");
+ } else if (zipFilename.startsWith("video")) {
livePhoto.videoNameTitle =
originalName + getFileExtensionWithDot(zipFilename);
- livePhoto.video = await zip.files[zipFilename].async('uint8array');
+ livePhoto.video = await zip.files[zipFilename].async("uint8array");
}
}
return livePhoto;
@@ -34,12 +34,12 @@ export const decodeLivePhoto = async (file: EnteFile, zipBlob: Blob) => {
export const encodeLivePhoto = async (livePhoto: LivePhoto) => {
const zip = new JSZip();
zip.file(
- 'image' + getFileExtensionWithDot(livePhoto.imageNameTitle),
- livePhoto.image
+ "image" + getFileExtensionWithDot(livePhoto.imageNameTitle),
+ livePhoto.image,
);
zip.file(
- 'video' + getFileExtensionWithDot(livePhoto.videoNameTitle),
- livePhoto.video
+ "video" + getFileExtensionWithDot(livePhoto.videoNameTitle),
+ livePhoto.video,
);
- return await zip.generateAsync({ type: 'uint8array' });
+ return await zip.generateAsync({ type: "uint8array" });
};
diff --git a/apps/cast/src/services/queueProcessor.ts b/apps/cast/src/services/queueProcessor.ts
index 97332aaee7..8e70c4a7f6 100644
--- a/apps/cast/src/services/queueProcessor.ts
+++ b/apps/cast/src/services/queueProcessor.ts
@@ -1,4 +1,4 @@
-import { CustomError } from '@ente/shared/error';
+import { CustomError } from "@ente/shared/error";
interface RequestQueueItem {
request: (canceller?: RequestCanceller) => Promise<any>;
@@ -28,11 +28,11 @@ export default class QueueProcessor<T> {
constructor(
private maxParallelProcesses: number,
- private processingStrategy = PROCESSING_STRATEGY.FIFO
+ private processingStrategy = PROCESSING_STRATEGY.FIFO,
) {}
public queueUpRequest(
- request: (canceller?: RequestCanceller) => Promise<T>
+ request: (canceller?: RequestCanceller) => Promise<T>,
) {
const isCanceled: CancellationStatus = { status: false };
const canceller: RequestCanceller = {
diff --git a/apps/cast/src/services/readerService.ts b/apps/cast/src/services/readerService.ts
index 765ea19e13..344fd9f202 100644
--- a/apps/cast/src/services/readerService.ts
+++ b/apps/cast/src/services/readerService.ts
@@ -1,14 +1,14 @@
-import { logError } from '@ente/shared/sentry';
-import { convertBytesToHumanReadable } from '@ente/shared/utils/size';
-import { ElectronFile } from 'types/upload';
+import { logError } from "@ente/shared/sentry";
+import { convertBytesToHumanReadable } from "@ente/shared/utils/size";
+import { ElectronFile } from "types/upload";
export async function getUint8ArrayView(
- file: Blob | ElectronFile
+ file: Blob | ElectronFile,
): Promise<Uint8Array> {
try {
return new Uint8Array(await file.arrayBuffer());
} catch (e) {
- logError(e, 'reading file blob failed', {
+ logError(e, "reading file blob failed", {
fileSize: convertBytesToHumanReadable(file.size),
});
throw e;
@@ -37,7 +37,7 @@ export function getFileStream(file: File, chunkSize: number) {
export async function getElectronFileStream(
file: ElectronFile,
- chunkSize: number
+ chunkSize: number,
) {
const chunkCount = Math.ceil(file.size / chunkSize);
return {
@@ -61,29 +61,29 @@ async function* fileChunkReaderMaker(file: File, chunkSize: number) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function getUint8ArrayViewOld(
reader: FileReader,
- file: Blob
+ file: Blob,
): Promise<Uint8Array> {
return await new Promise((resolve, reject) => {
reader.onabort = () =>
reject(
Error(
`file reading was aborted, file size= ${convertBytesToHumanReadable(
- file.size
- )}`
- )
+ file.size,
+ )}`,
+ ),
);
reader.onerror = () =>
reject(
Error(
`file reading has failed, file size= ${convertBytesToHumanReadable(
- file.size
- )} , reason= ${reader.error}`
- )
+ file.size,
+ )} , reason= ${reader.error}`,
+ ),
);
reader.onload = () => {
// Do whatever you want with the file contents
const result =
- typeof reader.result === 'string'
+ typeof reader.result === "string"
? new TextEncoder().encode(reader.result)
: new Uint8Array(reader.result);
resolve(result);
diff --git a/apps/cast/src/services/typeDetectionService.ts b/apps/cast/src/services/typeDetectionService.ts
index 49191ef20a..c280baf510 100644
--- a/apps/cast/src/services/typeDetectionService.ts
+++ b/apps/cast/src/services/typeDetectionService.ts
@@ -1,26 +1,26 @@
-import { FILE_TYPE } from 'constants/file';
-import { ElectronFile, FileTypeInfo } from 'types/upload';
+import { CustomError } from "@ente/shared/error";
+import { logError } from "@ente/shared/sentry";
+import { convertBytesToHumanReadable } from "@ente/shared/utils/size";
+import { FILE_TYPE } from "constants/file";
import {
- WHITELISTED_FILE_FORMATS,
KNOWN_NON_MEDIA_FORMATS,
-} from 'constants/upload';
-import { CustomError } from '@ente/shared/error';
-import { getFileExtension } from 'utils/file';
-import { logError } from '@ente/shared/sentry';
-import { getUint8ArrayView } from './readerService';
-import FileType, { FileTypeResult } from 'file-type';
-import { convertBytesToHumanReadable } from '@ente/shared/utils/size';
+ WHITELISTED_FILE_FORMATS,
+} from "constants/upload";
+import FileType, { FileTypeResult } from "file-type";
+import { ElectronFile, FileTypeInfo } from "types/upload";
+import { getFileExtension } from "utils/file";
+import { getUint8ArrayView } from "./readerService";
function getFileSize(file: File | ElectronFile) {
return file.size;
}
-const TYPE_VIDEO = 'video';
-const TYPE_IMAGE = 'image';
+const TYPE_VIDEO = "video";
+const TYPE_IMAGE = "image";
const CHUNK_SIZE_FOR_TYPE_DETECTION = 4100;
export async function getFileType(
- receivedFile: File | ElectronFile
+ receivedFile: File | ElectronFile,
): Promise<FileTypeInfo> {
try {
let fileType: FILE_TYPE;
@@ -32,7 +32,7 @@ export async function getFileType(
typeResult = await extractElectronFileType(receivedFile);
}
- const mimTypeParts: string[] = typeResult.mime?.split('/');
+ const mimTypeParts: string[] = typeResult.mime?.split("/");
if (mimTypeParts?.length !== 2) {
throw Error(CustomError.INVALID_MIME_TYPE(typeResult.mime));
@@ -56,7 +56,7 @@ export async function getFileType(
const fileFormat = getFileExtension(receivedFile.name);
const fileSize = convertBytesToHumanReadable(getFileSize(receivedFile));
const whiteListedFormat = WHITELISTED_FILE_FORMATS.find(
- (a) => a.exactType === fileFormat
+ (a) => a.exactType === fileFormat,
);
if (whiteListedFormat) {
return whiteListedFormat;
@@ -65,13 +65,13 @@ export async function getFileType(
throw Error(CustomError.UNSUPPORTED_FILE_FORMAT);
}
if (e.message === CustomError.NON_MEDIA_FILE) {
- logError(e, 'unsupported file format', {
+ logError(e, "unsupported file format", {
fileFormat,
fileSize,
});
throw Error(CustomError.UNSUPPORTED_FILE_FORMAT);
}
- logError(e, 'type detection failed', {
+ logError(e, "type detection failed", {
fileFormat,
fileSize,
});
@@ -96,11 +96,11 @@ async function extractElectronFileType(file: ElectronFile) {
async function getFileTypeFromBuffer(buffer: Uint8Array) {
const result = await FileType.fromBuffer(buffer);
if (!result?.mime) {
- let logableInfo = '';
+ let logableInfo = "";
try {
logableInfo = `result: ${JSON.stringify(result)}`;
} catch (e) {
- logableInfo = 'failed to stringify result';
+ logableInfo = "failed to stringify result";
}
throw Error(`mimetype missing from file type result - ${logableInfo}`);
}
diff --git a/apps/cast/src/services/wasm/ffmpeg.ts b/apps/cast/src/services/wasm/ffmpeg.ts
index bb27ed4db1..ce6f871ed7 100644
--- a/apps/cast/src/services/wasm/ffmpeg.ts
+++ b/apps/cast/src/services/wasm/ffmpeg.ts
@@ -1,14 +1,14 @@
-import { promiseWithTimeout } from '@ente/shared/promise';
-import { createFFmpeg, FFmpeg } from 'ffmpeg-wasm';
-import QueueProcessor from 'services/queueProcessor';
-import { getUint8ArrayView } from 'services/readerService';
-import { logError } from '@ente/shared/sentry';
-import { generateTempName } from 'utils/temp';
-import { addLogLine } from '@ente/shared/logging';
+import { addLogLine } from "@ente/shared/logging";
+import { promiseWithTimeout } from "@ente/shared/promise";
+import { logError } from "@ente/shared/sentry";
+import { createFFmpeg, FFmpeg } from "ffmpeg-wasm";
+import QueueProcessor from "services/queueProcessor";
+import { getUint8ArrayView } from "services/readerService";
+import { generateTempName } from "utils/temp";
-const INPUT_PATH_PLACEHOLDER = 'INPUT';
-const FFMPEG_PLACEHOLDER = 'FFMPEG';
-const OUTPUT_PATH_PLACEHOLDER = 'OUTPUT';
+const INPUT_PATH_PLACEHOLDER = "INPUT";
+const FFMPEG_PLACEHOLDER = "FFMPEG";
+const OUTPUT_PATH_PLACEHOLDER = "OUTPUT";
const FFMPEG_EXECUTION_WAIT_TIME = 30 * 1000;
@@ -19,7 +19,7 @@ export class WasmFFmpeg {
constructor() {
this.ffmpeg = createFFmpeg({
- corePath: '/js/ffmpeg/ffmpeg-core.js',
+ corePath: "/js/ffmpeg/ffmpeg-core.js",
mt: false,
});
@@ -36,7 +36,7 @@ export class WasmFFmpeg {
cmd: string[],
inputFile: File,
outputFileName: string,
- dontTimeout = false
+ dontTimeout = false,
) {
const response = this.ffmpegTaskQueue.queueUpRequest(() => {
if (dontTimeout) {
@@ -44,14 +44,14 @@ export class WasmFFmpeg {
} else {
return promiseWithTimeout<File>(
this.execute(cmd, inputFile, outputFileName),
- FFMPEG_EXECUTION_WAIT_TIME
+ FFMPEG_EXECUTION_WAIT_TIME,
);
}
});
try {
return await response.promise;
} catch (e) {
- logError(e, 'ffmpeg run failed');
+ logError(e, "ffmpeg run failed");
throw e;
}
}
@@ -59,25 +59,25 @@ export class WasmFFmpeg {
private async execute(
cmd: string[],
inputFile: File,
- outputFileName: string
+ outputFileName: string,
) {
let tempInputFilePath: string;
let tempOutputFilePath: string;
try {
await this.ready;
const extension = getFileExtension(inputFile.name);
- const tempNameSuffix = extension ? `input.${extension}` : 'input';
+ const tempNameSuffix = extension ? `input.${extension}` : "input";
tempInputFilePath = `${generateTempName(10, tempNameSuffix)}`;
this.ffmpeg.FS(
- 'writeFile',
+ "writeFile",
tempInputFilePath,
- await getUint8ArrayView(inputFile)
+ await getUint8ArrayView(inputFile),
);
tempOutputFilePath = `${generateTempName(10, outputFileName)}`;
cmd = cmd.map((cmdPart) => {
if (cmdPart === FFMPEG_PLACEHOLDER) {
- return '';
+ return "";
} else if (cmdPart === INPUT_PATH_PLACEHOLDER) {
return tempInputFilePath;
} else if (cmdPart === OUTPUT_PATH_PLACEHOLDER) {
@@ -89,26 +89,26 @@ export class WasmFFmpeg {
addLogLine(`${cmd}`);
await this.ffmpeg.run(...cmd);
return new File(
- [this.ffmpeg.FS('readFile', tempOutputFilePath)],
- outputFileName
+ [this.ffmpeg.FS("readFile", tempOutputFilePath)],
+ outputFileName,
);
} finally {
try {
- this.ffmpeg.FS('unlink', tempInputFilePath);
+ this.ffmpeg.FS("unlink", tempInputFilePath);
} catch (e) {
- logError(e, 'unlink input file failed');
+ logError(e, "unlink input file failed");
}
try {
- this.ffmpeg.FS('unlink', tempOutputFilePath);
+ this.ffmpeg.FS("unlink", tempOutputFilePath);
} catch (e) {
- logError(e, 'unlink output file failed');
+ logError(e, "unlink output file failed");
}
}
}
}
function getFileExtension(filename: string) {
- const lastDotPosition = filename.lastIndexOf('.');
+ const lastDotPosition = filename.lastIndexOf(".");
if (lastDotPosition === -1) return null;
else {
return filename.slice(lastDotPosition + 1);
diff --git a/apps/cast/src/services/wasmHeicConverter/wasmHEICConverterClient.ts b/apps/cast/src/services/wasmHeicConverter/wasmHEICConverterClient.ts
index 0ca183f22e..03b390fb9a 100644
--- a/apps/cast/src/services/wasmHeicConverter/wasmHEICConverterClient.ts
+++ b/apps/cast/src/services/wasmHeicConverter/wasmHEICConverterClient.ts
@@ -1,9 +1,9 @@
-import * as HeicConvert from 'heic-convert';
-import { getUint8ArrayView } from 'services/readerService';
+import * as HeicConvert from "heic-convert";
+import { getUint8ArrayView } from "services/readerService";
export async function convertHEIC(
fileBlob: Blob,
- format: string
+ format: string,
): Promise<Blob> {
const filedata = await getUint8ArrayView(fileBlob);
const result = await HeicConvert({ buffer: filedata, format });
diff --git a/apps/cast/src/services/wasmHeicConverter/wasmHEICConverterService.ts b/apps/cast/src/services/wasmHeicConverter/wasmHEICConverterService.ts
index a17884a9d4..a49d8e4f8c 100644
--- a/apps/cast/src/services/wasmHeicConverter/wasmHEICConverterService.ts
+++ b/apps/cast/src/services/wasmHeicConverter/wasmHEICConverterService.ts
@@ -1,23 +1,23 @@
-import QueueProcessor from 'services/queueProcessor';
-import { retryAsyncFunction } from 'utils/network';
-import { DedicatedConvertWorker } from 'worker/convert.worker';
-import { ComlinkWorker } from 'utils/comlink/comlinkWorker';
-import { getDedicatedConvertWorker } from 'utils/comlink/ComlinkConvertWorker';
-import { logError } from '@ente/shared/sentry';
-import { addLogLine } from '@ente/shared/logging';
-import { convertBytesToHumanReadable } from '@ente/shared/utils/size';
-import { CustomError } from '@ente/shared/error';
+import { CustomError } from "@ente/shared/error";
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import { convertBytesToHumanReadable } from "@ente/shared/utils/size";
+import QueueProcessor from "services/queueProcessor";
+import { getDedicatedConvertWorker } from "utils/comlink/ComlinkConvertWorker";
+import { ComlinkWorker } from "utils/comlink/comlinkWorker";
+import { retryAsyncFunction } from "utils/network";
+import { DedicatedConvertWorker } from "worker/convert.worker";
const WORKER_POOL_SIZE = 2;
const MAX_CONVERSION_IN_PARALLEL = 1;
const WAIT_TIME_BEFORE_NEXT_ATTEMPT_IN_MICROSECONDS = [100, 100];
const WAIT_TIME_IN_MICROSECONDS = 30 * 1000;
const BREATH_TIME_IN_MICROSECONDS = 1000;
-const CONVERT_FORMAT = 'JPEG';
+const CONVERT_FORMAT = "JPEG";
class HEICConverter {
private convertProcessor = new QueueProcessor<Blob>(
- MAX_CONVERSION_IN_PARALLEL
+ MAX_CONVERSION_IN_PARALLEL,
);
private workerPool: ComlinkWorker<typeof DedicatedConvertWorker>[] = [];
private ready: Promise<void>;
@@ -43,22 +43,22 @@ class HEICConverter {
const main = async () => {
try {
const timeout = setTimeout(() => {
- reject(Error('wait time exceeded'));
+ reject(Error("wait time exceeded"));
}, WAIT_TIME_IN_MICROSECONDS);
const startTime = Date.now();
const convertedHEIC =
await worker.convertHEIC(
fileBlob,
- CONVERT_FORMAT
+ CONVERT_FORMAT,
);
addLogLine(
`originalFileSize:${convertBytesToHumanReadable(
- fileBlob?.size
+ fileBlob?.size,
)},convertedFileSize:${convertBytesToHumanReadable(
- convertedHEIC?.size
+ convertedHEIC?.size,
)}, heic conversion time: ${
Date.now() - startTime
- }ms `
+ }ms `,
);
clearTimeout(timeout);
resolve(convertedHEIC);
@@ -67,37 +67,37 @@ class HEICConverter {
}
};
main();
- }
+ },
);
if (!convertedHEIC || convertedHEIC?.size === 0) {
logError(
Error(`converted heic fileSize is Zero`),
- 'converted heic fileSize is Zero',
+ "converted heic fileSize is Zero",
{
originalFileSize: convertBytesToHumanReadable(
- fileBlob?.size ?? 0
+ fileBlob?.size ?? 0,
),
convertedFileSize: convertBytesToHumanReadable(
- convertedHEIC?.size ?? 0
+ convertedHEIC?.size ?? 0,
),
- }
+ },
);
}
await new Promise((resolve) => {
setTimeout(
() => resolve(null),
- BREATH_TIME_IN_MICROSECONDS
+ BREATH_TIME_IN_MICROSECONDS,
);
});
this.workerPool.push(convertWorker);
return convertedHEIC;
} catch (e) {
- logError(e, 'heic conversion failed');
+ logError(e, "heic conversion failed");
convertWorker.terminate();
this.workerPool.push(getDedicatedConvertWorker());
throw e;
}
- }, WAIT_TIME_BEFORE_NEXT_ATTEMPT_IN_MICROSECONDS)
+ }, WAIT_TIME_BEFORE_NEXT_ATTEMPT_IN_MICROSECONDS),
);
try {
return await response.promise;
diff --git a/apps/cast/src/types/collection/index.ts b/apps/cast/src/types/collection/index.ts
index 489c0bddeb..f9ea9ef04b 100644
--- a/apps/cast/src/types/collection/index.ts
+++ b/apps/cast/src/types/collection/index.ts
@@ -1,17 +1,17 @@
-import { EnteFile } from 'types/file';
-import { CollectionSummaryType, CollectionType } from 'constants/collection';
+import { CollectionSummaryType, CollectionType } from "constants/collection";
+import { EnteFile } from "types/file";
import {
EncryptedMagicMetadata,
MagicMetadataCore,
SUB_TYPE,
VISIBILITY_STATE,
-} from 'types/magicMetadata';
+} from "types/magicMetadata";
export enum COLLECTION_ROLE {
- VIEWER = 'VIEWER',
- OWNER = 'OWNER',
- COLLABORATOR = 'COLLABORATOR',
- UNKNOWN = 'UNKNOWN',
+ VIEWER = "VIEWER",
+ OWNER = "OWNER",
+ COLLABORATOR = "COLLABORATOR",
+ UNKNOWN = "UNKNOWN",
}
export interface CollectionUser {
@@ -43,13 +43,13 @@ export interface EncryptedCollection {
export interface Collection
extends Omit<
EncryptedCollection,
- | 'encryptedKey'
- | 'keyDecryptionNonce'
- | 'encryptedName'
- | 'nameDecryptionNonce'
- | 'magicMetadata'
- | 'pubMagicMetadata'
- | 'sharedMagicMetadata'
+ | "encryptedKey"
+ | "keyDecryptionNonce"
+ | "encryptedName"
+ | "nameDecryptionNonce"
+ | "magicMetadata"
+ | "pubMagicMetadata"
+ | "sharedMagicMetadata"
> {
key: string;
name: string;
diff --git a/apps/cast/src/types/file/index.ts b/apps/cast/src/types/file/index.ts
index 7c55a8af2a..1813b5416d 100644
--- a/apps/cast/src/types/file/index.ts
+++ b/apps/cast/src/types/file/index.ts
@@ -2,8 +2,8 @@ import {
EncryptedMagicMetadata,
MagicMetadataCore,
VISIBILITY_STATE,
-} from 'types/magicMetadata';
-import { Metadata } from 'types/upload';
+} from "types/magicMetadata";
+import { Metadata } from "types/upload";
export interface MetadataFileAttributes {
encryptedData: string;
@@ -38,11 +38,11 @@ export interface EncryptedEnteFile {
export interface EnteFile
extends Omit<
EncryptedEnteFile,
- | 'metadata'
- | 'pubMagicMetadata'
- | 'magicMetadata'
- | 'encryptedKey'
- | 'keyDecryptionNonce'
+ | "metadata"
+ | "pubMagicMetadata"
+ | "magicMetadata"
+ | "encryptedKey"
+ | "keyDecryptionNonce"
> {
metadata: Metadata;
magicMetadata: FileMagicMetadata;
diff --git a/apps/cast/src/types/gallery/index.ts b/apps/cast/src/types/gallery/index.ts
index 927340b967..0216825c80 100644
--- a/apps/cast/src/types/gallery/index.ts
+++ b/apps/cast/src/types/gallery/index.ts
@@ -1,9 +1,9 @@
// import { CollectionDownloadProgressAttributes } from 'components/Collections/CollectionDownloadProgress';
// import { CollectionSelectorAttributes } from 'components/Collections/CollectionSelector';
// import { TimeStampListItem } from 'components/PhotoList';
-import { User } from '@ente/shared/user/types';
-import { Collection } from 'types/collection';
-import { EnteFile } from 'types/file';
+import { User } from "@ente/shared/user/types";
+import { Collection } from "types/collection";
+import { EnteFile } from "types/file";
export type SelectedState = {
[k: number]: boolean;
diff --git a/apps/cast/src/types/upload/index.ts b/apps/cast/src/types/upload/index.ts
index 192315ef1f..0d38f6190f 100644
--- a/apps/cast/src/types/upload/index.ts
+++ b/apps/cast/src/types/upload/index.ts
@@ -1,16 +1,16 @@
import {
B64EncryptionResult,
LocalFileAttributes,
-} from '@ente/shared/crypto/types';
-import { FILE_TYPE } from 'constants/file';
-import { Collection } from 'types/collection';
+} from "@ente/shared/crypto/types";
+import { FILE_TYPE } from "constants/file";
+import { Collection } from "types/collection";
import {
- MetadataFileAttributes,
- S3FileAttributes,
FilePublicMagicMetadata,
FilePublicMagicMetadataProps,
-} from 'types/file';
-import { EncryptedMagicMetadata } from 'types/magicMetadata';
+ MetadataFileAttributes,
+ S3FileAttributes,
+} from "types/file";
+import { EncryptedMagicMetadata } from "types/magicMetadata";
export interface DataStream {
stream: ReadableStream<Uint8Array>;
@@ -18,7 +18,7 @@ export interface DataStream {
}
export function isDataStream(object: any): object is DataStream {
- return 'stream' in object;
+ return "stream" in object;
}
export type Logger = (message: string) => void;
@@ -114,7 +114,7 @@ export interface FileInMemory {
}
export interface FileWithMetadata
- extends Omit<FileInMemory, 'hasStaticThumbnail'> {
+ extends Omit<FileInMemory, "hasStaticThumbnail"> {
metadata: Metadata;
localID: number;
pubMagicMetadata: FilePublicMagicMetadata;
diff --git a/apps/cast/src/types/upload/ui.ts b/apps/cast/src/types/upload/ui.ts
index 4283e30a15..bce381213f 100644
--- a/apps/cast/src/types/upload/ui.ts
+++ b/apps/cast/src/types/upload/ui.ts
@@ -1,4 +1,4 @@
-import { UPLOAD_RESULT, UPLOAD_STAGES } from 'constants/upload';
+import { UPLOAD_RESULT, UPLOAD_STAGES } from "constants/upload";
export type FileID = number;
export type FileName = string;
diff --git a/apps/cast/src/utils/collection/index.ts b/apps/cast/src/utils/collection/index.ts
index 54396ab8e2..bd6c2791d0 100644
--- a/apps/cast/src/utils/collection/index.ts
+++ b/apps/cast/src/utils/collection/index.ts
@@ -1,13 +1,13 @@
-import { COLLECTION_ROLE, Collection } from 'types/collection';
+import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
+import { User } from "@ente/shared/user/types";
import {
CollectionSummaryType,
CollectionType,
HIDE_FROM_COLLECTION_BAR_TYPES,
OPTIONS_NOT_HAVING_COLLECTION_TYPES,
-} from 'constants/collection';
-import { SUB_TYPE, VISIBILITY_STATE } from 'types/magicMetadata';
-import { User } from '@ente/shared/user/types';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
+} from "constants/collection";
+import { COLLECTION_ROLE, Collection } from "types/collection";
+import { SUB_TYPE, VISIBILITY_STATE } from "types/magicMetadata";
export enum COLLECTION_OPS_TYPE {
ADD,
@@ -19,7 +19,7 @@ export enum COLLECTION_OPS_TYPE {
export function getSelectedCollection(
collectionID: number,
- collections: Collection[]
+ collections: Collection[],
) {
return collections.find((collection) => collection.id === collectionID);
}
@@ -64,7 +64,7 @@ export const shouldBeShownOnCollectionBar = (type: CollectionSummaryType) => {
export const getUserOwnedCollections = (collections: Collection[]) => {
const user: User = getData(LS_KEYS.USER);
if (!user?.id) {
- throw Error('user missing');
+ throw Error("user missing");
}
return collections.filter((collection) => collection.owner.id === user.id);
};
@@ -103,7 +103,7 @@ export function isSharedOnlyViaLink(collection: Collection) {
export function isValidMoveTarget(
sourceCollectionID: number,
targetCollection: Collection,
- user: User
+ user: User,
) {
return (
sourceCollectionID !== targetCollection.id &&
@@ -116,7 +116,7 @@ export function isValidMoveTarget(
export function isValidReplacementAlbum(
collection: Collection,
user: User,
- wantedCollectionName: string
+ wantedCollectionName: string,
) {
return (
collection.name === wantedCollectionName &&
@@ -129,15 +129,15 @@ export function isValidReplacementAlbum(
}
export function getCollectionNameMap(
- collections: Collection[]
+ collections: Collection[],
): Map<number, string> {
return new Map<number, string>(
- collections.map((collection) => [collection.id, collection.name])
+ collections.map((collection) => [collection.id, collection.name]),
);
}
export function getNonHiddenCollections(
- collections: Collection[]
+ collections: Collection[],
): Collection[] {
return collections.filter((collection) => !isHiddenCollection(collection));
}
diff --git a/apps/cast/src/utils/comlink/ComlinkConvertWorker.ts b/apps/cast/src/utils/comlink/ComlinkConvertWorker.ts
index 2bb90a36ed..dc15136d9f 100644
--- a/apps/cast/src/utils/comlink/ComlinkConvertWorker.ts
+++ b/apps/cast/src/utils/comlink/ComlinkConvertWorker.ts
@@ -1,7 +1,7 @@
-import { Remote } from 'comlink';
-import { DedicatedConvertWorker } from 'worker/convert.worker';
-import { ComlinkWorker } from './comlinkWorker';
-import { runningInBrowser } from '@ente/shared/platform';
+import { runningInBrowser } from "@ente/shared/platform";
+import { Remote } from "comlink";
+import { DedicatedConvertWorker } from "worker/convert.worker";
+import { ComlinkWorker } from "./comlinkWorker";
class ComlinkConvertWorker {
private comlinkWorkerInstance: Remote<DedicatedConvertWorker>;
@@ -20,8 +20,8 @@ export const getDedicatedConvertWorker = () => {
const cryptoComlinkWorker = new ComlinkWorker<
typeof DedicatedConvertWorker
>(
- 'ente-convert-worker',
- new Worker(new URL('worker/convert.worker.ts', import.meta.url))
+ "ente-convert-worker",
+ new Worker(new URL("worker/convert.worker.ts", import.meta.url)),
);
return cryptoComlinkWorker;
}
diff --git a/apps/cast/src/utils/comlink/ComlinkCryptoWorker.ts b/apps/cast/src/utils/comlink/ComlinkCryptoWorker.ts
index 2410d469a8..8c108317e0 100644
--- a/apps/cast/src/utils/comlink/ComlinkCryptoWorker.ts
+++ b/apps/cast/src/utils/comlink/ComlinkCryptoWorker.ts
@@ -1,6 +1,6 @@
-import { Remote } from 'comlink';
-import { DedicatedCryptoWorker } from 'worker/crypto.worker';
-import { ComlinkWorker } from './comlinkWorker';
+import { Remote } from "comlink";
+import { DedicatedCryptoWorker } from "worker/crypto.worker";
+import { ComlinkWorker } from "./comlinkWorker";
class ComlinkCryptoWorker {
private comlinkWorkerInstance: Promise<Remote<DedicatedCryptoWorker>>;
@@ -16,8 +16,8 @@ class ComlinkCryptoWorker {
export const getDedicatedCryptoWorker = () => {
const cryptoComlinkWorker = new ComlinkWorker<typeof DedicatedCryptoWorker>(
- 'ente-crypto-worker',
- new Worker(new URL('worker/crypto.worker.ts', import.meta.url))
+ "ente-crypto-worker",
+ new Worker(new URL("worker/crypto.worker.ts", import.meta.url)),
);
return cryptoComlinkWorker;
};
diff --git a/apps/cast/src/utils/comlink/ComlinkFFmpegWorker.ts b/apps/cast/src/utils/comlink/ComlinkFFmpegWorker.ts
index efc71bf994..77d140bdb8 100644
--- a/apps/cast/src/utils/comlink/ComlinkFFmpegWorker.ts
+++ b/apps/cast/src/utils/comlink/ComlinkFFmpegWorker.ts
@@ -1,6 +1,6 @@
-import { Remote } from 'comlink';
-import { DedicatedFFmpegWorker } from 'worker/ffmpeg.worker';
-import { ComlinkWorker } from './comlinkWorker';
+import { Remote } from "comlink";
+import { DedicatedFFmpegWorker } from "worker/ffmpeg.worker";
+import { ComlinkWorker } from "./comlinkWorker";
class ComlinkFFmpegWorker {
private comlinkWorkerInstance: Promise<Remote<DedicatedFFmpegWorker>>;
@@ -16,8 +16,8 @@ class ComlinkFFmpegWorker {
const getDedicatedFFmpegWorker = () => {
const cryptoComlinkWorker = new ComlinkWorker<typeof DedicatedFFmpegWorker>(
- 'ente-ffmpeg-worker',
- new Worker(new URL('worker/ffmpeg.worker.ts', import.meta.url))
+ "ente-ffmpeg-worker",
+ new Worker(new URL("worker/ffmpeg.worker.ts", import.meta.url)),
);
return cryptoComlinkWorker;
};
diff --git a/apps/cast/src/utils/comlink/comlinkWorker.ts b/apps/cast/src/utils/comlink/comlinkWorker.ts
index f566a3f90f..9c1aacff6b 100644
--- a/apps/cast/src/utils/comlink/comlinkWorker.ts
+++ b/apps/cast/src/utils/comlink/comlinkWorker.ts
@@ -1,5 +1,5 @@
-import { addLocalLog } from '@ente/shared/logging';
-import { Remote, wrap } from 'comlink';
+import { addLocalLog } from "@ente/shared/logging";
+import { Remote, wrap } from "comlink";
// import { WorkerElectronCacheStorageClient } from 'services/workerElectronCache/client';
export class ComlinkWorker<T extends new () => InstanceType<T>> {
@@ -12,7 +12,7 @@ export class ComlinkWorker<T extends new () => InstanceType<T>> {
this.worker = worker;
this.worker.onerror = (errorEvent) => {
- console.error('Got error event from worker', errorEvent);
+ console.error("Got error event from worker", errorEvent);
};
addLocalLog(() => `Initiated ${this.name}`);
const comlink = wrap<T>(this.worker);
diff --git a/apps/cast/src/utils/file/index.ts b/apps/cast/src/utils/file/index.ts
index 409276fb7e..63672c0ef9 100644
--- a/apps/cast/src/utils/file/index.ts
+++ b/apps/cast/src/utils/file/index.ts
@@ -1,34 +1,34 @@
-import { SelectedState } from 'types/gallery';
+import { logError } from "@ente/shared/sentry";
+import {
+ FILE_TYPE,
+ RAW_FORMATS,
+ SUPPORTED_RAW_FORMATS,
+ TYPE_HEIC,
+ TYPE_HEIF,
+} from "constants/file";
+import CastDownloadManager from "services/castDownloadManager";
+import * as ffmpegService from "services/ffmpeg/ffmpegService";
+import heicConversionService from "services/heicConversionService";
+import { decodeLivePhoto } from "services/livePhotoService";
+import { getFileType } from "services/typeDetectionService";
import {
- EnteFile,
EncryptedEnteFile,
+ EnteFile,
FileMagicMetadata,
FilePublicMagicMetadata,
-} from 'types/file';
-import { decodeLivePhoto } from 'services/livePhotoService';
-import { getFileType } from 'services/typeDetectionService';
-import { logError } from '@ente/shared/sentry';
-import {
- TYPE_HEIC,
- TYPE_HEIF,
- FILE_TYPE,
- SUPPORTED_RAW_FORMATS,
- RAW_FORMATS,
-} from 'constants/file';
-import CastDownloadManager from 'services/castDownloadManager';
-import heicConversionService from 'services/heicConversionService';
-import * as ffmpegService from 'services/ffmpeg/ffmpegService';
-import { isArchivedFile } from 'utils/magicMetadata';
-
-import { CustomError } from '@ente/shared/error';
-import ComlinkCryptoWorker from 'utils/comlink/ComlinkCryptoWorker';
-import isElectron from 'is-electron';
-import { isPlaybackPossible } from 'utils/photoFrame';
-import { FileTypeInfo } from 'types/upload';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import { User } from '@ente/shared/user/types';
-import { addLogLine, addLocalLog } from '@ente/shared/logging';
-import { convertBytesToHumanReadable } from '@ente/shared/utils/size';
+} from "types/file";
+import { SelectedState } from "types/gallery";
+import { isArchivedFile } from "utils/magicMetadata";
+
+import { CustomError } from "@ente/shared/error";
+import { addLocalLog, addLogLine } from "@ente/shared/logging";
+import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
+import { User } from "@ente/shared/user/types";
+import { convertBytesToHumanReadable } from "@ente/shared/utils/size";
+import isElectron from "is-electron";
+import { FileTypeInfo } from "types/upload";
+import ComlinkCryptoWorker from "utils/comlink/ComlinkCryptoWorker";
+import { isPlaybackPossible } from "utils/photoFrame";
const WAIT_TIME_IMAGE_CONVERSION = 30 * 1000;
@@ -56,7 +56,7 @@ export function groupFilesBasedOnCollectionID(files: EnteFile[]) {
function getSelectedFileIds(selectedFiles: SelectedState) {
const filesIDs: number[] = [];
for (const [key, val] of Object.entries(selectedFiles)) {
- if (typeof val === 'boolean' && val) {
+ if (typeof val === "boolean" && val) {
filesIDs.push(Number(key));
}
}
@@ -64,7 +64,7 @@ function getSelectedFileIds(selectedFiles: SelectedState) {
}
export function getSelectedFiles(
selected: SelectedState,
- files: EnteFile[]
+ files: EnteFile[],
): EnteFile[] {
const selectedFilesIDs = getSelectedFileIds(selected);
return files.filter((file) => selectedFilesIDs.has(file.id));
@@ -101,7 +101,7 @@ export function sortTrashFiles(files: EnteFile[]) {
export async function decryptFile(
file: EncryptedEnteFile,
- collectionKey: string
+ collectionKey: string,
): Promise<EnteFile> {
try {
const worker = await ComlinkCryptoWorker.getInstance();
@@ -116,12 +116,12 @@ export async function decryptFile(
const fileKey = await worker.decryptB64(
encryptedKey,
keyDecryptionNonce,
- collectionKey
+ collectionKey,
);
const fileMetadata = await worker.decryptMetadata(
metadata.encryptedData,
metadata.decryptionHeader,
- fileKey
+ fileKey,
);
let fileMagicMetadata: FileMagicMetadata;
let filePubMagicMetadata: FilePublicMagicMetadata;
@@ -131,7 +131,7 @@ export async function decryptFile(
data: await worker.decryptMetadata(
magicMetadata.data,
magicMetadata.header,
- fileKey
+ fileKey,
),
};
}
@@ -141,7 +141,7 @@ export async function decryptFile(
data: await worker.decryptMetadata(
pubMagicMetadata.data,
pubMagicMetadata.header,
- fileKey
+ fileKey,
),
};
}
@@ -153,25 +153,25 @@ export async function decryptFile(
pubMagicMetadata: filePubMagicMetadata,
};
} catch (e) {
- logError(e, 'file decryption failed');
+ logError(e, "file decryption failed");
throw e;
}
}
export function getFileNameWithoutExtension(filename: string) {
- const lastDotPosition = filename.lastIndexOf('.');
+ const lastDotPosition = filename.lastIndexOf(".");
if (lastDotPosition === -1) return filename;
else return filename.slice(0, lastDotPosition);
}
export function getFileExtensionWithDot(filename: string) {
- const lastDotPosition = filename.lastIndexOf('.');
- if (lastDotPosition === -1) return '';
+ const lastDotPosition = filename.lastIndexOf(".");
+ if (lastDotPosition === -1) return "";
else return filename.slice(lastDotPosition);
}
export function splitFilenameAndExtension(filename: string): [string, string] {
- const lastDotPosition = filename.lastIndexOf('.');
+ const lastDotPosition = filename.lastIndexOf(".");
if (lastDotPosition === -1) return [filename, null];
else
return [
@@ -198,11 +198,11 @@ export async function getRenderableFileURL(file: EnteFile, fileBlob: Blob) {
case FILE_TYPE.IMAGE: {
const convertedBlob = await getRenderableImage(
file.metadata.title,
- fileBlob
+ fileBlob,
);
const { originalURL, convertedURL } = getFileObjectURLs(
fileBlob,
- convertedBlob
+ convertedBlob,
);
return {
converted: [convertedURL],
@@ -215,11 +215,11 @@ export async function getRenderableFileURL(file: EnteFile, fileBlob: Blob) {
case FILE_TYPE.VIDEO: {
const convertedBlob = await getPlayableVideo(
file.metadata.title,
- fileBlob
+ fileBlob,
);
const { originalURL, convertedURL } = getFileObjectURLs(
fileBlob,
- convertedBlob
+ convertedBlob,
);
return {
converted: [convertedURL],
@@ -229,7 +229,7 @@ export async function getRenderableFileURL(file: EnteFile, fileBlob: Blob) {
default: {
const previewURL = await createTypedObjectURL(
fileBlob,
- file.metadata.title
+ file.metadata.title,
);
return {
converted: [previewURL],
@@ -241,19 +241,19 @@ export async function getRenderableFileURL(file: EnteFile, fileBlob: Blob) {
async function getRenderableLivePhotoURL(
file: EnteFile,
- fileBlob: Blob
+ fileBlob: Blob,
): Promise<{ original: string[]; converted: string[] }> {
const livePhoto = await decodeLivePhoto(file, fileBlob);
const imageBlob = new Blob([livePhoto.image]);
const videoBlob = new Blob([livePhoto.video]);
const convertedImageBlob = await getRenderableImage(
livePhoto.imageNameTitle,
- imageBlob
+ imageBlob,
);
const convertedVideoBlob = await getPlayableVideo(
livePhoto.videoNameTitle,
videoBlob,
- true
+ true,
);
const { originalURL: originalImageURL, convertedURL: convertedImageURL } =
getFileObjectURLs(imageBlob, convertedImageBlob);
@@ -269,11 +269,11 @@ async function getRenderableLivePhotoURL(
export async function getPlayableVideo(
videoNameTitle: string,
videoBlob: Blob,
- forceConvert = false
+ forceConvert = false,
) {
try {
const isPlayable = await isPlaybackPossible(
- URL.createObjectURL(videoBlob)
+ URL.createObjectURL(videoBlob),
);
if (isPlayable && !forceConvert) {
return videoBlob;
@@ -282,18 +282,18 @@ export async function getPlayableVideo(
return null;
}
addLogLine(
- 'video format not supported, converting it name:',
- videoNameTitle
+ "video format not supported, converting it name:",
+ videoNameTitle,
);
const mp4ConvertedVideo = await ffmpegService.convertToMP4(
- new File([videoBlob], videoNameTitle)
+ new File([videoBlob], videoNameTitle),
);
- addLogLine('video successfully converted', videoNameTitle);
+ addLogLine("video successfully converted", videoNameTitle);
return new Blob([await mp4ConvertedVideo.arrayBuffer()]);
}
} catch (e) {
- addLogLine('video conversion failed', videoNameTitle);
- logError(e, 'video conversion failed');
+ addLogLine("video conversion failed", videoNameTitle);
+ logError(e, "video conversion failed");
return null;
}
}
@@ -317,8 +317,8 @@ export async function getRenderableImage(fileName: string, imageBlob: Blob) {
}
addLogLine(
`RawConverter called for ${fileName}-${convertBytesToHumanReadable(
- imageBlob.size
- )}`
+ imageBlob.size,
+ )}`,
);
// convertedImageBlob = await imageProcessor.convertToJPEG(
// imageBlob,
@@ -332,8 +332,8 @@ export async function getRenderableImage(fileName: string, imageBlob: Blob) {
}
addLogLine(
`HEICConverter called for ${fileName}-${convertBytesToHumanReadable(
- imageBlob.size
- )}`
+ imageBlob.size,
+ )}`,
);
convertedImageBlob =
await heicConversionService.convert(imageBlob);
@@ -347,7 +347,7 @@ export async function getRenderableImage(fileName: string, imageBlob: Blob) {
return imageBlob;
}
} catch (e) {
- logError(e, 'get Renderable Image failed', { fileTypeInfo });
+ logError(e, "get Renderable Image failed", { fileTypeInfo });
return null;
}
}
@@ -391,7 +391,7 @@ export function mergeMetadata(files: EnteFile[]): EnteFile[] {
export async function getFileFromURL(fileURL: string) {
const fileBlob = await (await fetch(fileURL)).blob();
- const fileFile = new File([fileBlob], 'temp');
+ const fileFile = new File([fileBlob], "temp");
return fileFile;
}
@@ -424,21 +424,21 @@ export const createTypedObjectURL = async (blob: Blob, fileName: string) => {
export const getUserOwnedFiles = (files: EnteFile[]) => {
const user: User = getData(LS_KEYS.USER);
if (!user?.id) {
- throw Error('user missing');
+ throw Error("user missing");
}
return files.filter((file) => file.ownerID === user.id);
};
// doesn't work on firefox
export const copyFileToClipboard = async (fileUrl: string) => {
- const canvas = document.createElement('canvas');
- const canvasCTX = canvas.getContext('2d');
+ const canvas = document.createElement("canvas");
+ const canvasCTX = canvas.getContext("2d");
const image = new Image();
const blobPromise = new Promise<Blob>((resolve, reject) => {
let timeout: NodeJS.Timeout = null;
try {
- image.setAttribute('src', fileUrl);
+ image.setAttribute("src", fileUrl);
image.onload = () => {
canvas.width = image.width;
canvas.height = image.height;
@@ -447,29 +447,29 @@ export const copyFileToClipboard = async (fileUrl: string) => {
(blob) => {
resolve(blob);
},
- 'image/png',
- 1
+ "image/png",
+ 1,
);
clearTimeout(timeout);
};
} catch (e) {
- void logError(e, 'failed to copy to clipboard');
+ void logError(e, "failed to copy to clipboard");
reject(e);
} finally {
clearTimeout(timeout);
}
timeout = setTimeout(
() => reject(Error(CustomError.WAIT_TIME_EXCEEDED)),
- WAIT_TIME_IMAGE_CONVERSION
+ WAIT_TIME_IMAGE_CONVERSION,
);
});
const { ClipboardItem } = window;
await navigator.clipboard
- .write([new ClipboardItem({ 'image/png': blobPromise })])
- .catch((e) => logError(e, 'failed to copy to clipboard'));
+ .write([new ClipboardItem({ "image/png": blobPromise })])
+ .catch((e) => logError(e, "failed to copy to clipboard"));
};
export function getLatestVersionFiles(files: EnteFile[]) {
@@ -484,13 +484,13 @@ export function getLatestVersionFiles(files: EnteFile[]) {
}
});
return Array.from(latestVersionFiles.values()).filter(
- (file) => !file.isDeleted
+ (file) => !file.isDeleted,
);
}
export function getPersonalFiles(files: EnteFile[], user: User) {
if (!user?.id) {
- throw Error('user missing');
+ throw Error("user missing");
}
return files.filter((file) => file.ownerID === user.id);
}
@@ -531,7 +531,7 @@ export const shouldShowAvatar = (file: EnteFile, user: User) => {
export const getPreviewableImage = async (
file: EnteFile,
- castToken: string
+ castToken: string,
): Promise<Blob> => {
try {
let fileBlob: Blob;
@@ -539,7 +539,7 @@ export const getPreviewableImage = async (
await CastDownloadManager.getCachedOriginalFile(file)[0];
if (!fileURL) {
fileBlob = await new Response(
- await CastDownloadManager.downloadFile(castToken, file)
+ await CastDownloadManager.downloadFile(castToken, file),
).blob();
} else {
fileBlob = await (await fetch(fileURL)).blob();
@@ -550,17 +550,17 @@ export const getPreviewableImage = async (
}
const convertedBlob = await getRenderableImage(
file.metadata.title,
- fileBlob
+ fileBlob,
);
fileBlob = convertedBlob;
const fileType = await getFileType(
- new File([fileBlob], file.metadata.title)
+ new File([fileBlob], file.metadata.title),
);
fileBlob = new Blob([fileBlob], { type: fileType.mimeType });
return fileBlob;
} catch (e) {
- logError(e, 'failed to download file');
+ logError(e, "failed to download file");
}
};
diff --git a/apps/cast/src/utils/file/livePhoto.ts b/apps/cast/src/utils/file/livePhoto.ts
index 92fb311b14..7d687217ce 100644
--- a/apps/cast/src/utils/file/livePhoto.ts
+++ b/apps/cast/src/utils/file/livePhoto.ts
@@ -1,37 +1,37 @@
-import { FILE_TYPE } from 'constants/file';
-import { getFileExtension } from 'utils/file';
+import { FILE_TYPE } from "constants/file";
+import { getFileExtension } from "utils/file";
const IMAGE_EXTENSIONS = [
- 'heic',
- 'heif',
- 'jpeg',
- 'jpg',
- 'png',
- 'gif',
- 'bmp',
- 'tiff',
- 'webp',
+ "heic",
+ "heif",
+ "jpeg",
+ "jpg",
+ "png",
+ "gif",
+ "bmp",
+ "tiff",
+ "webp",
];
const VIDEO_EXTENSIONS = [
- 'mov',
- 'mp4',
- 'm4v',
- 'avi',
- 'wmv',
- 'flv',
- 'mkv',
- 'webm',
- '3gp',
- '3g2',
- 'avi',
- 'ogv',
- 'mpg',
- 'mp',
+ "mov",
+ "mp4",
+ "m4v",
+ "avi",
+ "wmv",
+ "flv",
+ "mkv",
+ "webm",
+ "3gp",
+ "3g2",
+ "avi",
+ "ogv",
+ "mpg",
+ "mp",
];
export function getFileTypeFromExtensionForLivePhotoClustering(
- filename: string
+ filename: string,
) {
const extension = getFileExtension(filename)?.toLowerCase();
if (IMAGE_EXTENSIONS.includes(extension)) {
diff --git a/apps/cast/src/utils/magicMetadata/index.ts b/apps/cast/src/utils/magicMetadata/index.ts
index a650d0a82c..7beb457727 100644
--- a/apps/cast/src/utils/magicMetadata/index.ts
+++ b/apps/cast/src/utils/magicMetadata/index.ts
@@ -1,7 +1,7 @@
-import { Collection } from 'types/collection';
-import { EnteFile } from 'types/file';
-import { MagicMetadataCore, VISIBILITY_STATE } from 'types/magicMetadata';
-import ComlinkCryptoWorker from 'utils/comlink/ComlinkCryptoWorker';
+import { Collection } from "types/collection";
+import { EnteFile } from "types/file";
+import { MagicMetadataCore, VISIBILITY_STATE } from "types/magicMetadata";
+import ComlinkCryptoWorker from "utils/comlink/ComlinkCryptoWorker";
export function isArchivedFile(item: EnteFile): boolean {
if (!item || !item.magicMetadata || !item.magicMetadata.data) {
@@ -33,8 +33,8 @@ export function isPinnedCollection(item: Collection) {
!item ||
!item.magicMetadata ||
!item.magicMetadata.data ||
- typeof item.magicMetadata.data === 'string' ||
- typeof item.magicMetadata.data.order === 'undefined'
+ typeof item.magicMetadata.data === "string" ||
+ typeof item.magicMetadata.data.order === "undefined"
) {
return false;
}
@@ -44,7 +44,7 @@ export function isPinnedCollection(item: Collection) {
export async function updateMagicMetadata<T>(
magicMetadataUpdates: T,
originalMagicMetadata?: MagicMetadataCore<T>,
- decryptionKey?: string
+ decryptionKey?: string,
): Promise<MagicMetadataCore<T>> {
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
@@ -52,11 +52,11 @@ export async function updateMagicMetadata<T>(
originalMagicMetadata = getNewMagicMetadata<T>();
}
- if (typeof originalMagicMetadata?.data === 'string') {
+ if (typeof originalMagicMetadata?.data === "string") {
originalMagicMetadata.data = await cryptoWorker.decryptMetadata(
originalMagicMetadata.data,
originalMagicMetadata.header,
- decryptionKey
+ decryptionKey,
);
}
// copies the existing magic metadata properties of the files and updates the visibility value
@@ -91,7 +91,7 @@ export const getNonEmptyMagicMetadataProps = <T>(magicMetadataProps: T): T => {
return Object.fromEntries(
Object.entries(magicMetadataProps).filter(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
- ([_, v]) => v !== null && v !== undefined
- )
+ ([_, v]) => v !== null && v !== undefined,
+ ),
) as T;
};
diff --git a/apps/cast/src/utils/network/index.ts b/apps/cast/src/utils/network/index.ts
index b0e017dd3c..f7bac98eca 100644
--- a/apps/cast/src/utils/network/index.ts
+++ b/apps/cast/src/utils/network/index.ts
@@ -1,10 +1,10 @@
-import { sleep } from '@ente/shared/sleep';
+import { sleep } from "@ente/shared/sleep";
const waitTimeBeforeNextAttemptInMilliSeconds = [2000, 5000, 10000];
export async function retryAsyncFunction<T>(
request: (abort?: () => void) => Promise<T>,
- waitTimeBeforeNextTry?: number[]
+ waitTimeBeforeNextTry?: number[],
): Promise<T> {
if (!waitTimeBeforeNextTry) {
waitTimeBeforeNextTry = waitTimeBeforeNextAttemptInMilliSeconds;
diff --git a/apps/cast/src/utils/photoFrame/index.ts b/apps/cast/src/utils/photoFrame/index.ts
index 7637898f92..0cb6fc2015 100644
--- a/apps/cast/src/utils/photoFrame/index.ts
+++ b/apps/cast/src/utils/photoFrame/index.ts
@@ -1,7 +1,7 @@
-import { FILE_TYPE } from 'constants/file';
-import { EnteFile } from 'types/file';
-import { MergedSourceURL } from 'types/gallery';
-import { logError } from '@ente/shared/sentry';
+import { logError } from "@ente/shared/sentry";
+import { FILE_TYPE } from "constants/file";
+import { EnteFile } from "types/file";
+import { MergedSourceURL } from "types/gallery";
const WAIT_FOR_VIDEO_PLAYBACK = 1 * 1000;
@@ -11,8 +11,8 @@ export async function isPlaybackPossible(url: string): Promise<boolean> {
resolve(false);
}, WAIT_FOR_VIDEO_PLAYBACK);
- const video = document.createElement('video');
- video.addEventListener('canplay', function () {
+ const video = document.createElement("video");
+ video.addEventListener("canplay", function () {
clearTimeout(t);
video.remove(); // Clean up the video element
// also check for duration > 0 to make sure it is not a broken video
@@ -22,7 +22,7 @@ export async function isPlaybackPossible(url: string): Promise<boolean> {
resolve(false);
}
});
- video.addEventListener('error', function () {
+ video.addEventListener("error", function () {
clearTimeout(t);
video.remove();
resolve(false);
@@ -69,11 +69,11 @@ export function updateFileMsrcProps(file: EnteFile, url: string) {
export async function updateFileSrcProps(
file: EnteFile,
- mergedURL: MergedSourceURL
+ mergedURL: MergedSourceURL,
) {
const urls = {
- original: mergedURL.original.split(','),
- converted: mergedURL.converted.split(','),
+ original: mergedURL.original.split(","),
+ converted: mergedURL.converted.split(","),
};
let originalImageURL;
let originalVideoURL;
@@ -141,7 +141,7 @@ export async function updateFileSrcProps(
} else {
logError(
Error(`unknown file type - ${file.metadata.fileType}`),
- 'Unknown file type'
+ "Unknown file type",
);
file.src = originalURL;
}
diff --git a/apps/cast/src/utils/temp/index.ts b/apps/cast/src/utils/temp/index.ts
index 589c66d55d..984f4abb05 100644
--- a/apps/cast/src/utils/temp/index.ts
+++ b/apps/cast/src/utils/temp/index.ts
@@ -1,13 +1,13 @@
const CHARACTERS =
- 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
export function generateTempName(length: number, suffix: string) {
- let tempName = '';
+ let tempName = "";
const charactersLength = CHARACTERS.length;
for (let i = 0; i < length; i++) {
tempName += CHARACTERS.charAt(
- Math.floor(Math.random() * charactersLength)
+ Math.floor(Math.random() * charactersLength),
);
}
return `${tempName}-${suffix}`;
diff --git a/apps/cast/src/utils/time/format.ts b/apps/cast/src/utils/time/format.ts
index 59caefa807..0e2dc68b52 100644
--- a/apps/cast/src/utils/time/format.ts
+++ b/apps/cast/src/utils/time/format.ts
@@ -1,30 +1,30 @@
-import i18n, { t } from 'i18next';
+import i18n, { t } from "i18next";
const dateTimeFullFormatter1 = new Intl.DateTimeFormat(i18n.language, {
- weekday: 'short',
- month: 'short',
- day: 'numeric',
+ weekday: "short",
+ month: "short",
+ day: "numeric",
});
const dateTimeFullFormatter2 = new Intl.DateTimeFormat(i18n.language, {
- year: 'numeric',
+ year: "numeric",
});
const dateTimeShortFormatter = new Intl.DateTimeFormat(i18n.language, {
- month: 'short',
- day: 'numeric',
- year: 'numeric',
- hour: '2-digit',
- minute: '2-digit',
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
});
const timeFormatter = new Intl.DateTimeFormat(i18n.language, {
- timeStyle: 'short',
+ timeStyle: "short",
});
export function formatDateFull(date: number | Date) {
return [dateTimeFullFormatter1, dateTimeFullFormatter2]
.map((f) => f.format(date))
- .join(' ');
+ .join(" ");
}
export function formatDate(date: number | Date) {
@@ -34,7 +34,7 @@ export function formatDate(date: number | Date) {
return [dateTimeFullFormatter1, dateTimeFormat2]
.filter((f) => !!f)
.map((f) => f.format(date))
- .join(' ');
+ .join(" ");
}
export function formatDateTimeShort(date: number | Date) {
@@ -46,11 +46,11 @@ export function formatTime(date: number | Date) {
}
export function formatDateTimeFull(dateTime: number | Date): string {
- return [formatDateFull(dateTime), t('at'), formatTime(dateTime)].join(' ');
+ return [formatDateFull(dateTime), t("at"), formatTime(dateTime)].join(" ");
}
export function formatDateTime(dateTime: number | Date): string {
- return [formatDate(dateTime), t('at'), formatTime(dateTime)].join(' ');
+ return [formatDate(dateTime), t("at"), formatTime(dateTime)].join(" ");
}
export function formatDateRelative(date: number) {
@@ -63,16 +63,16 @@ export function formatDateRelative(date: number) {
second: 1000,
};
const relativeDateFormat = new Intl.RelativeTimeFormat(i18n.language, {
- localeMatcher: 'best fit',
- numeric: 'always',
- style: 'long',
+ localeMatcher: "best fit",
+ numeric: "always",
+ style: "long",
});
const elapsed = date - Date.now(); // "Math.abs" accounts for both "past" & "future" scenarios
for (const u in units)
- if (Math.abs(elapsed) > units[u] || u === 'second')
+ if (Math.abs(elapsed) > units[u] || u === "second")
return relativeDateFormat.format(
Math.round(elapsed / units[u]),
- u as Intl.RelativeTimeFormatUnit
+ u as Intl.RelativeTimeFormatUnit,
);
}
diff --git a/apps/cast/src/utils/time/index.ts b/apps/cast/src/utils/time/index.ts
index 11331a21bd..592d2c7afc 100644
--- a/apps/cast/src/utils/time/index.ts
+++ b/apps/cast/src/utils/time/index.ts
@@ -53,16 +53,16 @@ export function tryToParseDateTime(dateTime: string): Date {
if (dateComponent.year?.length === 8 && dateComponent.month?.length === 6) {
// the filename has size 8 consecutive and then 6 consecutive digits
// high possibility that the it is a date in format YYYYMMDD-HHMMSS
- const possibleDateTime = dateComponent.year + '-' + dateComponent.month;
+ const possibleDateTime = dateComponent.year + "-" + dateComponent.month;
return parseDateFromFusedDateString(possibleDateTime);
}
return validateAndGetDateFromComponents(
- convertDateComponentToNumber(dateComponent)
+ convertDateComponentToNumber(dateComponent),
);
}
function getDateComponentsFromSymbolJoinedString(
- dateTime: string
+ dateTime: string,
): DateComponent<string> {
const [year, month, day, hour, minute, second] =
dateTime.match(/\d+/g) ?? [];
@@ -71,7 +71,7 @@ function getDateComponentsFromSymbolJoinedString(
}
function validateAndGetDateFromComponents(
- dateComponent: DateComponent<number>
+ dateComponent: DateComponent<number>,
) {
let date = getDateFromComponents(dateComponent);
if (hasTimeValues(dateComponent) && !isTimePartValid(date, dateComponent)) {
@@ -102,7 +102,7 @@ function isDatePartValid(date: Date, dateComponent: DateComponent<number>) {
}
function convertDateComponentToNumber(
- dateComponent: DateComponent<string>
+ dateComponent: DateComponent<string>,
): DateComponent<number> {
return {
year: Number(dateComponent.year),
@@ -130,7 +130,7 @@ function hasTimeValues(dateComponent: DateComponent<number>) {
}
function removeTimeValues(
- dateComponent: DateComponent<number>
+ dateComponent: DateComponent<number>,
): DateComponent<number> {
return { ...dateComponent, hour: 0, minute: 0, second: 0 };
}
diff --git a/apps/cast/src/worker/convert.worker.ts b/apps/cast/src/worker/convert.worker.ts
index 8dae977a91..a805752acf 100644
--- a/apps/cast/src/worker/convert.worker.ts
+++ b/apps/cast/src/worker/convert.worker.ts
@@ -1,5 +1,5 @@
-import * as Comlink from 'comlink';
-import { convertHEIC } from 'services/wasmHeicConverter/wasmHEICConverterClient';
+import * as Comlink from "comlink";
+import { convertHEIC } from "services/wasmHeicConverter/wasmHEICConverterClient";
export class DedicatedConvertWorker {
async convertHEIC(fileBlob: Blob, format: string) {
diff --git a/apps/cast/src/worker/crypto.worker.ts b/apps/cast/src/worker/crypto.worker.ts
index 784c6e4ef2..ac1d52a0d4 100644
--- a/apps/cast/src/worker/crypto.worker.ts
+++ b/apps/cast/src/worker/crypto.worker.ts
@@ -1,6 +1,6 @@
-import * as Comlink from 'comlink';
-import { StateAddress } from 'libsodium-wrappers';
-import * as libsodium from '@ente/shared/crypto/internal/libsodium';
+import * as libsodium from "@ente/shared/crypto/internal/libsodium";
+import * as Comlink from "comlink";
+import { StateAddress } from "libsodium-wrappers";
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
@@ -8,12 +8,12 @@ export class DedicatedCryptoWorker {
async decryptMetadata(
encryptedMetadata: string,
header: string,
- key: string
+ key: string,
) {
const encodedMetadata = await libsodium.decryptChaChaOneShot(
await libsodium.fromB64(encryptedMetadata),
await libsodium.fromB64(header),
- key
+ key,
);
return JSON.parse(textDecoder.decode(encodedMetadata));
}
@@ -21,7 +21,7 @@ export class DedicatedCryptoWorker {
async decryptThumbnail(
fileData: Uint8Array,
header: Uint8Array,
- key: string
+ key: string,
) {
return libsodium.decryptChaChaOneShot(fileData, header, key);
}
@@ -29,15 +29,15 @@ export class DedicatedCryptoWorker {
async decryptEmbedding(
encryptedEmbedding: string,
header: string,
- key: string
+ key: string,
) {
const encodedEmbedding = await libsodium.decryptChaChaOneShot(
await libsodium.fromB64(encryptedEmbedding),
await libsodium.fromB64(header),
- key
+ key,
);
return Float32Array.from(
- JSON.parse(textDecoder.decode(encodedEmbedding))
+ JSON.parse(textDecoder.decode(encodedEmbedding)),
);
}
@@ -66,11 +66,11 @@ export class DedicatedCryptoWorker {
async encryptEmbedding(embedding: Float32Array, key: string) {
const encodedEmbedding = textEncoder.encode(
- JSON.stringify(Array.from(embedding))
+ JSON.stringify(Array.from(embedding)),
);
const { file: encryptEmbedding } = await libsodium.encryptChaChaOneShot(
encodedEmbedding,
- key
+ key,
);
const { encryptedData, ...other } = encryptEmbedding;
return {
@@ -89,7 +89,7 @@ export class DedicatedCryptoWorker {
async encryptFileChunk(
data: Uint8Array,
pushState: StateAddress,
- isFinalChunk: boolean
+ isFinalChunk: boolean,
) {
return libsodium.encryptFileChunk(data, pushState, isFinalChunk);
}
@@ -122,7 +122,7 @@ export class DedicatedCryptoWorker {
passphrase: string,
salt: string,
opsLimit: number,
- memLimit: number
+ memLimit: number,
) {
return libsodium.deriveKey(passphrase, salt, opsLimit, memLimit);
}
@@ -179,7 +179,7 @@ export class DedicatedCryptoWorker {
key: string,
subKeyLength: number,
subKeyID: number,
- context: string
+ context: string,
) {
return libsodium.generateSubKey(key, subKeyLength, subKeyID, context);
}
diff --git a/apps/cast/src/worker/ffmpeg.worker.ts b/apps/cast/src/worker/ffmpeg.worker.ts
index 3c4f4c52e2..d3f503abb9 100644
--- a/apps/cast/src/worker/ffmpeg.worker.ts
+++ b/apps/cast/src/worker/ffmpeg.worker.ts
@@ -1,5 +1,5 @@
-import * as Comlink from 'comlink';
-import { WasmFFmpeg } from 'services/wasm/ffmpeg';
+import * as Comlink from "comlink";
+import { WasmFFmpeg } from "services/wasm/ffmpeg";
export class DedicatedFFmpegWorker {
wasmFFmpeg: WasmFFmpeg;
diff --git a/apps/photos/.eslintrc.js b/apps/photos/.eslintrc.js
index dda1831cb6..fdec1a6b99 100644
--- a/apps/photos/.eslintrc.js
+++ b/apps/photos/.eslintrc.js
@@ -3,11 +3,11 @@ module.exports = {
// This is required here to ensure desktop picks the right eslint config, where this app is
// packaged as a submodule.
root: true,
- extends: ['@ente/eslint-config'],
- parser: '@typescript-eslint/parser',
+ extends: ["@ente/eslint-config"],
+ parser: "@typescript-eslint/parser",
parserOptions: {
tsconfigRootDir: __dirname,
- project: './tsconfig.json',
+ project: "./tsconfig.json",
},
- ignorePatterns: ['.eslintrc.js', 'out', 'thirdparty', 'public'],
+ ignorePatterns: [".eslintrc.js", "out", "thirdparty", "public"],
};
diff --git a/apps/photos/next.config.js b/apps/photos/next.config.js
index 57e1c5c8b5..eea88bf938 100644
--- a/apps/photos/next.config.js
+++ b/apps/photos/next.config.js
@@ -1,3 +1,3 @@
-const nextConfigBase = require('@/next/next.config.base.js');
+const nextConfigBase = require("@/next/next.config.base.js");
module.exports = nextConfigBase;
diff --git a/apps/photos/sentry.client.config.ts b/apps/photos/sentry.client.config.ts
index 8223fcd906..c43273663f 100644
--- a/apps/photos/sentry.client.config.ts
+++ b/apps/photos/sentry.client.config.ts
@@ -1,3 +1,3 @@
-import { initSentry } from '@ente/shared/sentry/config/sentry.config.base';
+import { initSentry } from "@ente/shared/sentry/config/sentry.config.base";
-initSentry('https://[email protected]/5');
+initSentry("https://[email protected]/5");
diff --git a/apps/photos/src/components/AddToCollectionBtn.tsx b/apps/photos/src/components/AddToCollectionBtn.tsx
index 5316923f9a..19409ce516 100644
--- a/apps/photos/src/components/AddToCollectionBtn.tsx
+++ b/apps/photos/src/components/AddToCollectionBtn.tsx
@@ -1,7 +1,6 @@
-import { styled } from '@mui/material';
-import React from 'react';
+import { styled } from "@mui/material";
-const Wrapper = styled('button')`
+const Wrapper = styled("button")`
border: none;
background-color: #51cd7c;
position: fixed;
@@ -25,7 +24,8 @@ export default function AddToCollectionBtn(props) {
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
- strokeLinejoin="round">
+ strokeLinejoin="round"
+ >
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
@@ -36,5 +36,5 @@ export default function AddToCollectionBtn(props) {
AddToCollectionBtn.defaultProps = {
height: 24,
width: 24,
- viewBox: '0 0 24 24',
+ viewBox: "0 0 24 24",
};
diff --git a/apps/photos/src/components/AuthenticateUserModal.tsx b/apps/photos/src/components/AuthenticateUserModal.tsx
index 83cf3e9d2d..7459982bc4 100644
--- a/apps/photos/src/components/AuthenticateUserModal.tsx
+++ b/apps/photos/src/components/AuthenticateUserModal.tsx
@@ -1,14 +1,14 @@
-import React, { useContext, useEffect, useState } from 'react';
+import { useContext, useEffect, useState } from "react";
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import { AppContext } from 'pages/_app';
-import { KeyAttributes, User } from '@ente/shared/user/types';
+import DialogBoxV2 from "@ente/shared/components/DialogBoxV2";
import VerifyMasterPasswordForm, {
VerifyMasterPasswordFormProps,
-} from '@ente/shared/components/VerifyMasterPasswordForm';
-import { logError } from '@ente/shared/sentry';
-import { t } from 'i18next';
-import DialogBoxV2 from '@ente/shared/components/DialogBoxV2';
+} from "@ente/shared/components/VerifyMasterPasswordForm";
+import { logError } from "@ente/shared/sentry";
+import { getData, LS_KEYS } from "@ente/shared/storage/localStorage";
+import { KeyAttributes, User } from "@ente/shared/user/types";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
interface Iprops {
open: boolean;
onClose: () => void;
@@ -26,9 +26,9 @@ export default function AuthenticateUserModal({
const somethingWentWrong = () =>
setDialogMessage({
- title: t('ERROR'),
- close: { variant: 'critical' },
- content: t('UNKNOWN_ERROR'),
+ title: t("ERROR"),
+ close: { variant: "critical" },
+ content: t("UNKNOWN_ERROR"),
});
useEffect(() => {
@@ -36,7 +36,7 @@ export default function AuthenticateUserModal({
try {
const user = getData(LS_KEYS.USER);
if (!user) {
- throw Error('User not found');
+ throw Error("User not found");
}
setUser(user);
const keyAttributes = getData(LS_KEYS.KEY_ATTRIBUTES);
@@ -44,14 +44,14 @@ export default function AuthenticateUserModal({
(!user?.token && !user?.encryptedToken) ||
(keyAttributes && !keyAttributes.memLimit)
) {
- throw Error('User not logged in');
+ throw Error("User not logged in");
} else if (!keyAttributes) {
- throw Error('Key attributes not found');
+ throw Error("Key attributes not found");
} else {
setKeyAttributes(keyAttributes);
}
} catch (e) {
- logError(e, 'AuthenticateUserModal initialization failed');
+ logError(e, "AuthenticateUserModal initialization failed");
onClose();
somethingWentWrong();
}
@@ -59,7 +59,7 @@ export default function AuthenticateUserModal({
main();
}, []);
- const useMasterPassword: VerifyMasterPasswordFormProps['callback'] =
+ const useMasterPassword: VerifyMasterPasswordFormProps["callback"] =
async () => {
onClose();
onAuthenticate();
@@ -69,12 +69,13 @@ export default function AuthenticateUserModal({
<DialogBoxV2
open={open}
onClose={onClose}
- sx={{ position: 'absolute' }}
+ sx={{ position: "absolute" }}
attributes={{
- title: t('PASSWORD'),
- }}>
+ title: t("PASSWORD"),
+ }}
+ >
<VerifyMasterPasswordForm
- buttonText={t('AUTHENTICATE')}
+ buttonText={t("AUTHENTICATE")}
callback={useMasterPassword}
user={user}
keyAttributes={keyAttributes}
diff --git a/apps/photos/src/components/Badge.tsx b/apps/photos/src/components/Badge.tsx
index b1a8703126..a3aca884a1 100644
--- a/apps/photos/src/components/Badge.tsx
+++ b/apps/photos/src/components/Badge.tsx
@@ -1,12 +1,12 @@
-import { Box, styled } from '@mui/material';
-import { CSSProperties } from '@mui/material/styles/createTypography';
+import { Box, styled } from "@mui/material";
+import { CSSProperties } from "@mui/material/styles/createTypography";
export const Badge = styled(Box)(({ theme }) => ({
borderRadius: theme.shape.borderRadius,
- padding: '2px 4px',
+ padding: "2px 4px",
backgroundColor: theme.colors.black.muted,
backdropFilter: `blur(${theme.colors.blur.muted})`,
color: theme.colors.white.base,
- textTransform: 'uppercase',
+ textTransform: "uppercase",
...(theme.typography.tiny as CSSProperties),
}));
diff --git a/apps/photos/src/components/CaptionedText.tsx b/apps/photos/src/components/CaptionedText.tsx
index afc3b156f4..64d6c344d0 100644
--- a/apps/photos/src/components/CaptionedText.tsx
+++ b/apps/photos/src/components/CaptionedText.tsx
@@ -1,39 +1,41 @@
-import { ButtonProps, Typography } from '@mui/material';
-import { VerticallyCenteredFlex } from '@ente/shared/components/Container';
+import { VerticallyCenteredFlex } from "@ente/shared/components/Container";
+import { ButtonProps, Typography } from "@mui/material";
interface Iprops {
mainText: string;
subText?: string;
subIcon?: React.ReactNode;
- color?: ButtonProps['color'];
+ color?: ButtonProps["color"];
}
-const getSubTextColor = (color: ButtonProps['color']) => {
+const getSubTextColor = (color: ButtonProps["color"]) => {
switch (color) {
- case 'critical':
- return 'critical.main';
+ case "critical":
+ return "critical.main";
default:
- return 'text.faint';
+ return "text.faint";
}
};
export const CaptionedText = (props: Iprops) => {
return (
- <VerticallyCenteredFlex gap={'4px'}>
+ <VerticallyCenteredFlex gap={"4px"}>
<Typography> {props.mainText}</Typography>
<Typography variant="small" color={getSubTextColor(props.color)}>
- {'β€’'}
+ {"β€’"}
</Typography>
{props.subText ? (
<Typography
variant="small"
- color={getSubTextColor(props.color)}>
+ color={getSubTextColor(props.color)}
+ >
{props.subText}
</Typography>
) : (
<Typography
variant="small"
- color={getSubTextColor(props.color)}>
+ color={getSubTextColor(props.color)}
+ >
{props.subIcon}
</Typography>
)}
diff --git a/apps/photos/src/components/CheckboxInput.tsx b/apps/photos/src/components/CheckboxInput.tsx
index 7ef2d4a532..7cdc95e3a8 100644
--- a/apps/photos/src/components/CheckboxInput.tsx
+++ b/apps/photos/src/components/CheckboxInput.tsx
@@ -1,10 +1,10 @@
import {
- FormControlLabel,
Checkbox,
+ FormControlLabel,
FormGroup,
Typography,
TypographyProps,
-} from '@mui/material';
+} from "@mui/material";
interface Iprops {
disabled?: boolean;
@@ -21,7 +21,7 @@ export function CheckboxInput({
labelProps,
}: Iprops) {
return (
- <FormGroup sx={{ width: '100%' }}>
+ <FormGroup sx={{ width: "100%" }}>
<FormControlLabel
control={
<Checkbox
diff --git a/apps/photos/src/components/Chip.tsx b/apps/photos/src/components/Chip.tsx
index c7e2695589..0336dc9c34 100644
--- a/apps/photos/src/components/Chip.tsx
+++ b/apps/photos/src/components/Chip.tsx
@@ -1,9 +1,9 @@
-import { Button, ButtonProps, styled } from '@mui/material';
-import { CSSProperties } from '@mui/material/styles/createTypography';
+import { Button, ButtonProps, styled } from "@mui/material";
+import { CSSProperties } from "@mui/material/styles/createTypography";
export const Chip = styled((props: ButtonProps) => (
<Button color="secondary" {...props} />
))(({ theme }) => ({
...(theme.typography.small as CSSProperties),
- padding: '8px',
+ padding: "8px",
}));
diff --git a/apps/photos/src/components/Collections/AllCollections/collectionCard.tsx b/apps/photos/src/components/Collections/AllCollections/collectionCard.tsx
index 68ecf589b5..0e2e30f3ab 100644
--- a/apps/photos/src/components/Collections/AllCollections/collectionCard.tsx
+++ b/apps/photos/src/components/Collections/AllCollections/collectionCard.tsx
@@ -1,9 +1,8 @@
-import { Typography } from '@mui/material';
-import React from 'react';
-import CollectionCard from '../CollectionCard';
-import { CollectionSummary } from 'types/collection';
-import { AllCollectionTile, AllCollectionTileText } from '../styledComponents';
-import { t } from 'i18next';
+import { Typography } from "@mui/material";
+import { t } from "i18next";
+import { CollectionSummary } from "types/collection";
+import CollectionCard from "../CollectionCard";
+import { AllCollectionTile, AllCollectionTileText } from "../styledComponents";
interface Iprops {
collectionSummary: CollectionSummary;
@@ -21,11 +20,12 @@ export default function AllCollectionCard({
collectionTile={AllCollectionTile}
coverFile={collectionSummary.coverFile}
onClick={() => onCollectionClick(collectionSummary.id)}
- isScrolling={isScrolling}>
+ isScrolling={isScrolling}
+ >
<AllCollectionTileText>
<Typography>{collectionSummary.name}</Typography>
<Typography variant="small" color="text.muted">
- {t('photos_count', { count: collectionSummary.fileCount })}
+ {t("photos_count", { count: collectionSummary.fileCount })}
</Typography>
</AllCollectionTileText>
</CollectionCard>
diff --git a/apps/photos/src/components/Collections/AllCollections/content.tsx b/apps/photos/src/components/Collections/AllCollections/content.tsx
index 46570cb1bf..57d9aa7962 100644
--- a/apps/photos/src/components/Collections/AllCollections/content.tsx
+++ b/apps/photos/src/components/Collections/AllCollections/content.tsx
@@ -1,16 +1,16 @@
-import React, { useEffect, useRef, useState } from 'react';
-import { DialogContent } from '@mui/material';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import AllCollectionCard from './collectionCard';
-import { CollectionSummary } from 'types/collection';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import useWindowSize from "@ente/shared/hooks/useWindowSize";
+import { DialogContent } from "@mui/material";
+import memoize from "memoize-one";
+import React, { useEffect, useRef, useState } from "react";
import {
FixedSizeList as List,
ListChildComponentProps,
areEqual,
-} from 'react-window';
-import memoize from 'memoize-one';
-import useWindowSize from '@ente/shared/hooks/useWindowSize';
-import { AllCollectionMobileBreakpoint } from './dialog';
+} from "react-window";
+import { CollectionSummary } from "types/collection";
+import AllCollectionCard from "./collectionCard";
+import { AllCollectionMobileBreakpoint } from "./dialog";
const MobileColumns = 2;
const DesktopColumns = 3;
@@ -18,11 +18,11 @@ const DesktopColumns = 3;
const CollectionRowItemSize = 154;
const getCollectionRowListHeight = (
collectionRowList: CollectionSummary[][],
- windowSize: { height: number; width: number }
+ windowSize: { height: number; width: number },
) =>
Math.min(
collectionRowList.length * CollectionRowItemSize + 32,
- windowSize?.height - 177
+ windowSize?.height - 177,
) || 0;
interface Iprops {
@@ -60,7 +60,7 @@ const AllCollectionRow = React.memo(
const collectionRow = collectionRowList[index];
return (
<div style={style}>
- <FlexWrapper gap={'4px'} padding={'16px'}>
+ <FlexWrapper gap={"4px"} padding={"16px"}>
{collectionRow.map((item: any) => (
<AllCollectionCard
isScrolling={isScrolling}
@@ -73,7 +73,7 @@ const AllCollectionRow = React.memo(
</div>
);
},
- areEqual
+ areEqual,
);
export default function AllCollectionContent({
@@ -131,16 +131,17 @@ export default function AllCollectionContent({
const itemData = createItemData(collectionRowList, onCollectionClick);
return (
- <DialogContent sx={{ '&&': { padding: 0 } }}>
+ <DialogContent sx={{ "&&": { padding: 0 } }}>
<List
height={getCollectionRowListHeight(
collectionRowList,
- windowSize
+ windowSize,
)}
- width={'100%'}
+ width={"100%"}
itemCount={collectionRowList.length}
itemSize={CollectionRowItemSize}
- itemData={itemData}>
+ itemData={itemData}
+ >
{AllCollectionRow}
</List>
</DialogContent>
diff --git a/apps/photos/src/components/Collections/AllCollections/dialog.tsx b/apps/photos/src/components/Collections/AllCollections/dialog.tsx
index 77873e4c9e..6a8bee89a2 100644
--- a/apps/photos/src/components/Collections/AllCollections/dialog.tsx
+++ b/apps/photos/src/components/Collections/AllCollections/dialog.tsx
@@ -1,30 +1,30 @@
-import { Dialog, Slide, styled } from '@mui/material';
-import React from 'react';
-import PropTypes from 'prop-types';
+import { Dialog, Slide, styled } from "@mui/material";
+import PropTypes from "prop-types";
+import React from "react";
export const AllCollectionMobileBreakpoint = 559;
export const AllCollectionDialog = styled(Dialog)<{
- position: 'flex-start' | 'center' | 'flex-end';
+ position: "flex-start" | "center" | "flex-end";
}>(({ theme, position }) => ({
- '& .MuiDialog-container': {
+ "& .MuiDialog-container": {
justifyContent: position,
},
- '& .MuiPaper-root': {
- maxWidth: '494px',
+ "& .MuiPaper-root": {
+ maxWidth: "494px",
},
- '& .MuiDialogTitle-root': {
+ "& .MuiDialogTitle-root": {
padding: theme.spacing(2),
paddingRight: theme.spacing(1),
},
- '& .MuiDialogContent-root': {
+ "& .MuiDialogContent-root": {
padding: theme.spacing(2),
},
[theme.breakpoints.down(AllCollectionMobileBreakpoint)]: {
- '& .MuiPaper-root': {
- width: '324px',
+ "& .MuiPaper-root": {
+ width: "324px",
},
- '& .MuiDialogContent-root': {
+ "& .MuiDialogContent-root": {
padding: 6,
},
},
@@ -35,9 +35,9 @@ AllCollectionDialog.propTypes = {
onClose: PropTypes.func.isRequired,
};
-export const Transition = (direction: 'left' | 'right' | 'up') =>
+export const Transition = (direction: "left" | "right" | "up") =>
React.forwardRef(
(props: { children: React.ReactElement<any, any> }, ref) => {
return <Slide direction={direction} ref={ref} {...props} />;
- }
+ },
);
diff --git a/apps/photos/src/components/Collections/AllCollections/header.tsx b/apps/photos/src/components/Collections/AllCollections/header.tsx
index 57046f176a..edbd178f3a 100644
--- a/apps/photos/src/components/Collections/AllCollections/header.tsx
+++ b/apps/photos/src/components/Collections/AllCollections/header.tsx
@@ -1,13 +1,12 @@
-import React from 'react';
-import { Box, DialogTitle, Stack, Typography } from '@mui/material';
import {
FlexWrapper,
FluidContainer,
IconButtonWithBG,
-} from '@ente/shared/components/Container';
-import CollectionListSortBy from 'components/Collections/CollectionListSortBy';
-import Close from '@mui/icons-material/Close';
-import { t } from 'i18next';
+} from "@ente/shared/components/Container";
+import Close from "@mui/icons-material/Close";
+import { Box, DialogTitle, Stack, Typography } from "@mui/material";
+import CollectionListSortBy from "components/Collections/CollectionListSortBy";
+import { t } from "i18next";
export default function AllCollectionsHeader({
onClose,
@@ -23,11 +22,11 @@ export default function AllCollectionsHeader({
<Box>
<Typography variant="h3">
{isInHiddenSection
- ? t('ALL_HIDDEN_ALBUMS')
- : t('ALL_ALBUMS')}
+ ? t("ALL_HIDDEN_ALBUMS")
+ : t("ALL_ALBUMS")}
</Typography>
- <Typography variant="small" color={'text.muted'}>
- {t('albums', { count: collectionCount })}
+ <Typography variant="small" color={"text.muted"}>
+ {t("albums", { count: collectionCount })}
</Typography>
</Box>
</FluidContainer>
diff --git a/apps/photos/src/components/Collections/AllCollections/index.tsx b/apps/photos/src/components/Collections/AllCollections/index.tsx
index 3aac2c7e83..208062d30c 100644
--- a/apps/photos/src/components/Collections/AllCollections/index.tsx
+++ b/apps/photos/src/components/Collections/AllCollections/index.tsx
@@ -1,14 +1,14 @@
-import React, { useContext } from 'react';
-import Divider from '@mui/material/Divider';
-import { COLLECTION_LIST_SORT_BY } from 'constants/collection';
+import Divider from "@mui/material/Divider";
import {
- Transition,
AllCollectionDialog,
-} from 'components/Collections/AllCollections/dialog';
-import AllCollectionsHeader from './header';
-import { CollectionSummary } from 'types/collection';
-import AllCollectionContent from './content';
-import { AppContext } from 'pages/_app';
+ Transition,
+} from "components/Collections/AllCollections/dialog";
+import { COLLECTION_LIST_SORT_BY } from "constants/collection";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
+import { CollectionSummary } from "types/collection";
+import AllCollectionContent from "./content";
+import AllCollectionsHeader from "./header";
interface Iprops {
open: boolean;
@@ -20,7 +20,7 @@ interface Iprops {
isInHiddenSection: boolean;
}
-const LeftSlideTransition = Transition('up');
+const LeftSlideTransition = Transition("up");
export default function AllCollections(props: Iprops) {
const {
@@ -45,7 +45,8 @@ export default function AllCollections(props: Iprops) {
TransitionComponent={LeftSlideTransition}
onClose={onClose}
open={open}
- fullScreen={isMobile}>
+ fullScreen={isMobile}
+ >
<AllCollectionsHeader
isInHiddenSection={isInHiddenSection}
onClose={onClose}
diff --git a/apps/photos/src/components/Collections/CollectionCard.tsx b/apps/photos/src/components/Collections/CollectionCard.tsx
index 87bb8b64fe..9217f077fd 100644
--- a/apps/photos/src/components/Collections/CollectionCard.tsx
+++ b/apps/photos/src/components/Collections/CollectionCard.tsx
@@ -1,8 +1,10 @@
-import { useState, useEffect } from 'react';
-import downloadManager from 'services/download';
-import { EnteFile } from 'types/file';
-import { StaticThumbnail } from 'components/PlaceholderThumbnails';
-import { LoadingThumbnail } from 'components/PlaceholderThumbnails';
+import {
+ LoadingThumbnail,
+ StaticThumbnail,
+} from "components/PlaceholderThumbnails";
+import { useEffect, useState } from "react";
+import downloadManager from "services/download";
+import { EnteFile } from "types/file";
export default function CollectionCard(props: {
children?: any;
@@ -28,7 +30,7 @@ export default function CollectionCard(props: {
}
const url = await downloadManager.getThumbnailForPreview(
file,
- isScrolling
+ isScrolling,
);
if (url) {
setCoverImageURL(url);
diff --git a/apps/photos/src/components/Collections/CollectionInfo.tsx b/apps/photos/src/components/Collections/CollectionInfo.tsx
index 93edc4cc99..a952687308 100644
--- a/apps/photos/src/components/Collections/CollectionInfo.tsx
+++ b/apps/photos/src/components/Collections/CollectionInfo.tsx
@@ -1,7 +1,7 @@
-import { Box, Typography } from '@mui/material';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import React from 'react';
-import { t } from 'i18next';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import { Box, Typography } from "@mui/material";
+import { t } from "i18next";
+import React from "react";
interface Iprops {
name: string;
fileCount: number;
@@ -15,17 +15,18 @@ export function CollectionInfo({ name, fileCount, endIcon }: Iprops) {
<FlexWrapper>
<Typography variant="small" color="text.muted">
- {t('photos_count', { count: fileCount })}
+ {t("photos_count", { count: fileCount })}
</Typography>
{endIcon && (
<Box
sx={{
svg: {
- fontSize: '17px',
- color: 'text.muted',
+ fontSize: "17px",
+ color: "text.muted",
},
}}
- ml={1.5}>
+ ml={1.5}
+ >
{endIcon}
</Box>
)}
diff --git a/apps/photos/src/components/Collections/CollectionInfoWithOptions.tsx b/apps/photos/src/components/Collections/CollectionInfoWithOptions.tsx
index 3a35111641..405e22c281 100644
--- a/apps/photos/src/components/Collections/CollectionInfoWithOptions.tsx
+++ b/apps/photos/src/components/Collections/CollectionInfoWithOptions.tsx
@@ -1,17 +1,17 @@
-import { CollectionInfo } from './CollectionInfo';
-import React, { Dispatch, SetStateAction } from 'react';
-import { Collection, CollectionSummary } from 'types/collection';
-import CollectionOptions from 'components/Collections/CollectionOptions';
-import { SetCollectionNamerAttributes } from 'components/Collections/CollectionNamer';
-import { SpaceBetweenFlex } from '@ente/shared/components/Container';
-import { CollectionInfoBarWrapper } from './styledComponents';
-import { shouldShowOptions } from 'utils/collection';
-import { CollectionSummaryType } from 'constants/collection';
-import Favorite from '@mui/icons-material/FavoriteRounded';
-import ArchiveOutlined from '@mui/icons-material/ArchiveOutlined';
-import PeopleIcon from '@mui/icons-material/People';
-import LinkIcon from '@mui/icons-material/Link';
-import { SetFilesDownloadProgressAttributesCreator } from 'types/gallery';
+import { SpaceBetweenFlex } from "@ente/shared/components/Container";
+import ArchiveOutlined from "@mui/icons-material/ArchiveOutlined";
+import Favorite from "@mui/icons-material/FavoriteRounded";
+import LinkIcon from "@mui/icons-material/Link";
+import PeopleIcon from "@mui/icons-material/People";
+import { SetCollectionNamerAttributes } from "components/Collections/CollectionNamer";
+import CollectionOptions from "components/Collections/CollectionOptions";
+import { CollectionSummaryType } from "constants/collection";
+import { Dispatch, SetStateAction } from "react";
+import { Collection, CollectionSummary } from "types/collection";
+import { SetFilesDownloadProgressAttributesCreator } from "types/gallery";
+import { shouldShowOptions } from "utils/collection";
+import { CollectionInfo } from "./CollectionInfo";
+import { CollectionInfoBarWrapper } from "./styledComponents";
interface Iprops {
activeCollection: Collection;
diff --git a/apps/photos/src/components/Collections/CollectionListBar/CollectionCard.tsx b/apps/photos/src/components/Collections/CollectionListBar/CollectionCard.tsx
index f221f065e2..a88534fef4 100644
--- a/apps/photos/src/components/Collections/CollectionListBar/CollectionCard.tsx
+++ b/apps/photos/src/components/Collections/CollectionListBar/CollectionCard.tsx
@@ -1,20 +1,19 @@
-import React from 'react';
+import ArchiveIcon from "@mui/icons-material/Archive";
+import Favorite from "@mui/icons-material/FavoriteRounded";
+import LinkIcon from "@mui/icons-material/Link";
+import PeopleIcon from "@mui/icons-material/People";
+import PushPin from "@mui/icons-material/PushPin";
+import { Box } from "@mui/material";
+import TruncateText from "components/TruncateText";
+import { CollectionSummaryType } from "constants/collection";
+import { CollectionSummary } from "types/collection";
+import CollectionCard from "../CollectionCard";
import {
ActiveIndicator,
CollectionBarTile,
CollectionBarTileIcon,
CollectionBarTileText,
-} from '../styledComponents';
-import CollectionCard from '../CollectionCard';
-import TruncateText from 'components/TruncateText';
-import { Box } from '@mui/material';
-import { CollectionSummaryType } from 'constants/collection';
-import Favorite from '@mui/icons-material/FavoriteRounded';
-import ArchiveIcon from '@mui/icons-material/Archive';
-import PeopleIcon from '@mui/icons-material/People';
-import LinkIcon from '@mui/icons-material/Link';
-import { CollectionSummary } from 'types/collection';
-import PushPin from '@mui/icons-material/PushPin';
+} from "../styledComponents";
interface Iprops {
collectionSummary: CollectionSummary;
@@ -33,7 +32,8 @@ const CollectionListBarCard = (props: Iprops) => {
coverFile={collectionSummary.coverFile}
onClick={() => {
onCollectionClick(collectionSummary.id);
- }}>
+ }}
+ >
<CollectionCardText collectionName={collectionSummary.name} />
<CollectionCardIcon collectionType={collectionSummary.type} />
</CollectionCard>
diff --git a/apps/photos/src/components/Collections/CollectionListBar/ScrollButton.tsx b/apps/photos/src/components/Collections/CollectionListBar/ScrollButton.tsx
index 3a7c229e13..a3d2fda192 100644
--- a/apps/photos/src/components/Collections/CollectionListBar/ScrollButton.tsx
+++ b/apps/photos/src/components/Collections/CollectionListBar/ScrollButton.tsx
@@ -1,9 +1,8 @@
-import React from 'react';
-import NavigateNextIcon from '@mui/icons-material/NavigateNext';
-import { SCROLL_DIRECTION } from '@ente/shared/hooks/useComponentScroll';
-import { css, styled } from '@mui/material';
+import { SCROLL_DIRECTION } from "@ente/shared/hooks/useComponentScroll";
+import NavigateNextIcon from "@mui/icons-material/NavigateNext";
+import { css, styled } from "@mui/material";
-const Wrapper = styled('button')<{ direction: SCROLL_DIRECTION }>`
+const Wrapper = styled("button")<{ direction: SCROLL_DIRECTION }>`
position: absolute;
z-index: 2;
top: 7px;
@@ -33,7 +32,7 @@ const Wrapper = styled('button')<{ direction: SCROLL_DIRECTION }>`
& > svg {
${(props) =>
props.direction === SCROLL_DIRECTION.LEFT &&
- 'transform:rotate(180deg);'}
+ "transform:rotate(180deg);"}
border-radius: 50%;
height: 30px;
width: 30px;
diff --git a/apps/photos/src/components/Collections/CollectionListBar/index.tsx b/apps/photos/src/components/Collections/CollectionListBar/index.tsx
index 8faa646275..42e8796471 100644
--- a/apps/photos/src/components/Collections/CollectionListBar/index.tsx
+++ b/apps/photos/src/components/Collections/CollectionListBar/index.tsx
@@ -1,32 +1,32 @@
-import React, { useContext, useEffect } from 'react';
-import { ALL_SECTION, COLLECTION_LIST_SORT_BY } from 'constants/collection';
-import { Box, IconButton, Typography } from '@mui/material';
-import {
- CollectionListBarWrapper,
- CollectionListWrapper,
-} from 'components/Collections/styledComponents';
-import CollectionListBarCard from 'components/Collections/CollectionListBar/CollectionCard';
import {
IconButtonWithBG,
SpaceBetweenFlex,
-} from '@ente/shared/components/Container';
-import ExpandMore from '@mui/icons-material/ExpandMore';
-import { AppContext } from 'pages/_app';
-import { CollectionSummary } from 'types/collection';
-import CollectionListSortBy from '../CollectionListSortBy';
-import { t } from 'i18next';
+} from "@ente/shared/components/Container";
+import useComponentScroll, {
+ SCROLL_DIRECTION,
+} from "@ente/shared/hooks/useComponentScroll";
+import useWindowSize from "@ente/shared/hooks/useWindowSize";
+import ExpandMore from "@mui/icons-material/ExpandMore";
+import { Box, IconButton, Typography } from "@mui/material";
+import CollectionListBarCard from "components/Collections/CollectionListBar/CollectionCard";
+import {
+ CollectionListBarWrapper,
+ CollectionListWrapper,
+} from "components/Collections/styledComponents";
+import { ALL_SECTION, COLLECTION_LIST_SORT_BY } from "constants/collection";
+import { t } from "i18next";
+import memoize from "memoize-one";
+import { AppContext } from "pages/_app";
+import React, { useContext, useEffect } from "react";
+import AutoSizer from "react-virtualized-auto-sizer";
import {
FixedSizeList as List,
ListChildComponentProps,
areEqual,
-} from 'react-window';
-import AutoSizer from 'react-virtualized-auto-sizer';
-import memoize from 'memoize-one';
-import useComponentScroll, {
- SCROLL_DIRECTION,
-} from '@ente/shared/hooks/useComponentScroll';
-import useWindowSize from '@ente/shared/hooks/useWindowSize';
-import ScrollButton from './ScrollButton';
+} from "react-window";
+import { CollectionSummary } from "types/collection";
+import CollectionListSortBy from "../CollectionListSortBy";
+import ScrollButton from "./ScrollButton";
interface IProps {
activeCollectionID?: number;
@@ -51,7 +51,7 @@ const createItemData = memoize(
collectionSummaries,
activeCollectionID,
onCollectionClick,
- })
+ }),
);
const CollectionCardContainer = React.memo(
@@ -78,7 +78,7 @@ const CollectionCardContainer = React.memo(
</div>
);
},
- areEqual
+ areEqual,
);
const getItemKey = (index: number, data: ItemData) => {
@@ -115,9 +115,9 @@ const CollectionListBar = (props: IProps) => {
}
// scroll the active collection into view
const activeCollectionIndex = collectionSummaries.findIndex(
- (item) => item.id === activeCollectionID
+ (item) => item.id === activeCollectionID,
);
- collectionListRef.current.scrollToItem(activeCollectionIndex, 'smart');
+ collectionListRef.current.scrollToItem(activeCollectionIndex, "smart");
}, [activeCollectionID]);
const onCollectionClick = (collectionID?: number) => {
@@ -127,17 +127,17 @@ const CollectionListBar = (props: IProps) => {
const itemData = createItemData(
collectionSummaries,
activeCollectionID,
- onCollectionClick
+ onCollectionClick,
);
return (
<CollectionListBarWrapper>
<SpaceBetweenFlex mb={1}>
<Typography>
- {isInHiddenSection ? t('HIDDEN_ALBUMS') : t('ALBUMS')}
+ {isInHiddenSection ? t("HIDDEN_ALBUMS") : t("ALBUMS")}
</Typography>
{appContext.isMobile && (
- <Box display="flex" alignItems={'center'} gap={1}>
+ <Box display="flex" alignItems={"center"} gap={1}>
<CollectionListSortBy
setSortBy={props.setCollectionListSortBy}
activeSortBy={props.collectionListSortBy}
@@ -169,7 +169,8 @@ const CollectionListBar = (props: IProps) => {
itemKey={getItemKey}
itemCount={collectionSummaries.length}
itemSize={CollectionListBarCardWidth}
- useIsScrolling>
+ useIsScrolling
+ >
{CollectionCardContainer}
</List>
)}
@@ -184,9 +185,10 @@ const CollectionListBar = (props: IProps) => {
{!appContext.isMobile && (
<Box
display="flex"
- alignItems={'center'}
+ alignItems={"center"}
gap={1}
- height={'64px'}>
+ height={"64px"}
+ >
<CollectionListSortBy
setSortBy={props.setCollectionListSortBy}
activeSortBy={props.collectionListSortBy}
diff --git a/apps/photos/src/components/Collections/CollectionListSortBy.tsx b/apps/photos/src/components/Collections/CollectionListSortBy.tsx
index ba794d3ef8..ff3172f52e 100644
--- a/apps/photos/src/components/Collections/CollectionListSortBy.tsx
+++ b/apps/photos/src/components/Collections/CollectionListSortBy.tsx
@@ -1,11 +1,10 @@
-import React from 'react';
-import { COLLECTION_LIST_SORT_BY } from 'constants/collection';
-import SortIcon from '@mui/icons-material/Sort';
-import OverflowMenu from '@ente/shared/components/OverflowMenu/menu';
-import SvgIcon from '@mui/material/SvgIcon';
-import TickIcon from '@mui/icons-material/Done';
-import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';
-import { t } from 'i18next';
+import OverflowMenu from "@ente/shared/components/OverflowMenu/menu";
+import { OverflowMenuOption } from "@ente/shared/components/OverflowMenu/option";
+import TickIcon from "@mui/icons-material/Done";
+import SortIcon from "@mui/icons-material/Sort";
+import SvgIcon from "@mui/material/SvgIcon";
+import { COLLECTION_LIST_SORT_BY } from "constants/collection";
+import { t } from "i18next";
interface CollectionSortProps {
setSortBy: (sortBy: COLLECTION_LIST_SORT_BY) => void;
@@ -26,7 +25,8 @@ const SortByOptionCreator =
onClick={handleClick}
endIcon={
activeSortBy === props.sortBy ? <TickIcon /> : <SvgIcon />
- }>
+ }
+ >
{props.children}
</OverflowMenuOption>
);
@@ -51,17 +51,20 @@ export default function CollectionListSortBy(props: CollectionSortProps) {
background: (theme) =>
!props.disableBG && theme.colors.fill.faint,
},
- }}>
+ }}
+ >
<SortByOption sortBy={COLLECTION_LIST_SORT_BY.NAME}>
- {t('SORT_BY_NAME')}
+ {t("SORT_BY_NAME")}
</SortByOption>
<SortByOption
- sortBy={COLLECTION_LIST_SORT_BY.CREATION_TIME_ASCENDING}>
- {t('SORT_BY_CREATION_TIME_ASCENDING')}
+ sortBy={COLLECTION_LIST_SORT_BY.CREATION_TIME_ASCENDING}
+ >
+ {t("SORT_BY_CREATION_TIME_ASCENDING")}
</SortByOption>
<SortByOption
- sortBy={COLLECTION_LIST_SORT_BY.UPDATION_TIME_DESCENDING}>
- {t('SORT_BY_UPDATION_TIME_DESCENDING')}
+ sortBy={COLLECTION_LIST_SORT_BY.UPDATION_TIME_DESCENDING}
+ >
+ {t("SORT_BY_UPDATION_TIME_DESCENDING")}
</SortByOption>
</OverflowMenu>
);
diff --git a/apps/photos/src/components/Collections/CollectionNamer.tsx b/apps/photos/src/components/Collections/CollectionNamer.tsx
index 48d7f4fb3b..0f7abf99f7 100644
--- a/apps/photos/src/components/Collections/CollectionNamer.tsx
+++ b/apps/photos/src/components/Collections/CollectionNamer.tsx
@@ -1,9 +1,9 @@
-import React from 'react';
+import DialogBoxV2 from "@ente/shared/components/DialogBoxV2";
import SingleInputForm, {
SingleInputFormProps,
-} from '@ente/shared/components/SingleInputForm';
-import { t } from 'i18next';
-import DialogBoxV2 from '@ente/shared/components/DialogBoxV2';
+} from "@ente/shared/components/SingleInputForm";
+import { t } from "i18next";
+import React from "react";
export interface CollectionNamerAttributes {
callback: (name: string) => void;
@@ -26,15 +26,15 @@ export default function CollectionNamer({ attributes, ...props }: Props) {
if (!attributes) {
return <></>;
}
- const onSubmit: SingleInputFormProps['callback'] = async (
+ const onSubmit: SingleInputFormProps["callback"] = async (
albumName,
- setFieldError
+ setFieldError,
) => {
try {
attributes.callback(albumName);
props.onHide();
} catch (e) {
- setFieldError(t('UNKNOWN_ERROR'));
+ setFieldError(t("UNKNOWN_ERROR"));
}
};
@@ -44,12 +44,13 @@ export default function CollectionNamer({ attributes, ...props }: Props) {
onClose={props.onHide}
attributes={{
title: attributes.title,
- }}>
+ }}
+ >
<SingleInputForm
callback={onSubmit}
fieldType="text"
buttonText={attributes.buttonText}
- placeholder={t('ENTER_ALBUM_NAME')}
+ placeholder={t("ENTER_ALBUM_NAME")}
initialValue={attributes.autoFilledName}
submitButtonProps={{ sx: { mt: 1, mb: 2 } }}
secondaryButtonAction={props.onHide}
diff --git a/apps/photos/src/components/Collections/CollectionOptions/AlbumCastDialog.tsx b/apps/photos/src/components/Collections/CollectionOptions/AlbumCastDialog.tsx
index 6219d32c45..f477ae9bf6 100644
--- a/apps/photos/src/components/Collections/CollectionOptions/AlbumCastDialog.tsx
+++ b/apps/photos/src/components/Collections/CollectionOptions/AlbumCastDialog.tsx
@@ -1,20 +1,20 @@
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import DialogBoxV2 from '@ente/shared/components/DialogBoxV2';
-import EnteButton from '@ente/shared/components/EnteButton';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import DialogBoxV2 from "@ente/shared/components/DialogBoxV2";
+import EnteButton from "@ente/shared/components/EnteButton";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
import SingleInputForm, {
SingleInputFormProps,
-} from '@ente/shared/components/SingleInputForm';
-import { boxSeal } from '@ente/shared/crypto/internal/libsodium';
-import { loadSender } from '@ente/shared/hooks/useCastSender';
-import { addLogLine } from '@ente/shared/logging';
-import castGateway from '@ente/shared/network/cast';
-import { logError } from '@ente/shared/sentry';
-import { Typography } from '@mui/material';
-import { t } from 'i18next';
-import { useEffect, useState } from 'react';
-import { Collection } from 'types/collection';
-import { v4 as uuidv4 } from 'uuid';
+} from "@ente/shared/components/SingleInputForm";
+import { boxSeal } from "@ente/shared/crypto/internal/libsodium";
+import { loadSender } from "@ente/shared/hooks/useCastSender";
+import { addLogLine } from "@ente/shared/logging";
+import castGateway from "@ente/shared/network/cast";
+import { logError } from "@ente/shared/sentry";
+import { Typography } from "@mui/material";
+import { t } from "i18next";
+import { useEffect, useState } from "react";
+import { Collection } from "types/collection";
+import { v4 as uuidv4 } from "uuid";
interface Props {
show: boolean;
@@ -23,7 +23,7 @@ interface Props {
}
enum AlbumCastError {
- TV_NOT_FOUND = 'TV_NOT_FOUND',
+ TV_NOT_FOUND = "TV_NOT_FOUND",
}
declare global {
@@ -34,8 +34,8 @@ declare global {
export default function AlbumCastDialog(props: Props) {
const [view, setView] = useState<
- 'choose' | 'auto' | 'pin' | 'auto-cast-error'
- >('choose');
+ "choose" | "auto" | "pin" | "auto-cast-error"
+ >("choose");
const [browserCanCast, setBrowserCanCast] = useState(false);
// Make API call on component mount
@@ -45,9 +45,9 @@ export default function AlbumCastDialog(props: Props) {
setBrowserCanCast(!!window.chrome);
}, []);
- const onSubmit: SingleInputFormProps['callback'] = async (
+ const onSubmit: SingleInputFormProps["callback"] = async (
value,
- setFieldError
+ setFieldError,
) => {
try {
await doCast(value);
@@ -57,10 +57,10 @@ export default function AlbumCastDialog(props: Props) {
let fieldError: string;
switch (error.message) {
case AlbumCastError.TV_NOT_FOUND:
- fieldError = t('TV_NOT_FOUND');
+ fieldError = t("TV_NOT_FOUND");
break;
default:
- fieldError = t('UNKNOWN_ERROR');
+ fieldError = t("UNKNOWN_ERROR");
break;
}
@@ -90,12 +90,12 @@ export default function AlbumCastDialog(props: Props) {
pin,
encryptedPayload,
props.currentCollection.id,
- castToken
+ castToken,
);
};
useEffect(() => {
- if (view === 'auto') {
+ if (view === "auto") {
loadSender().then(async (sender) => {
const { cast } = sender;
@@ -103,13 +103,13 @@ export default function AlbumCastDialog(props: Props) {
try {
await instance.requestSession();
} catch (e) {
- setView('auto-cast-error');
- logError(e, 'Error requesting session');
+ setView("auto-cast-error");
+ logError(e, "Error requesting session");
return;
}
const session = instance.getCurrentSession();
session.addMessageListener(
- 'urn:x-cast:pair-request',
+ "urn:x-cast:pair-request",
(_, message) => {
const data = message;
const obj = JSON.parse(data);
@@ -118,24 +118,24 @@ export default function AlbumCastDialog(props: Props) {
if (code) {
doCast(code)
.then(() => {
- setView('choose');
+ setView("choose");
props.onHide();
})
.catch((e) => {
- setView('auto-cast-error');
- logError(e, 'Error casting to TV');
+ setView("auto-cast-error");
+ logError(e, "Error casting to TV");
});
}
- }
+ },
);
session
- .sendMessage('urn:x-cast:pair-request', {})
+ .sendMessage("urn:x-cast:pair-request", {})
.then(() => {
- addLogLine('Message sent successfully');
+ addLogLine("Message sent successfully");
})
.catch((error) => {
- logError(error, 'Error sending message');
+ logError(error, "Error sending message");
});
});
}
@@ -153,83 +153,89 @@ export default function AlbumCastDialog(props: Props) {
open={props.show}
onClose={props.onHide}
attributes={{
- title: t('CAST_ALBUM_TO_TV'),
- }}>
- {view === 'choose' && (
+ title: t("CAST_ALBUM_TO_TV"),
+ }}
+ >
+ {view === "choose" && (
<>
{browserCanCast && (
<>
- <Typography color={'text.muted'}>
+ <Typography color={"text.muted"}>
{t(
- 'AUTO_CAST_PAIR_REQUIRES_CONNECTION_TO_GOOGLE'
+ "AUTO_CAST_PAIR_REQUIRES_CONNECTION_TO_GOOGLE",
)}
</Typography>
<EnteButton
style={{
- marginBottom: '1rem',
+ marginBottom: "1rem",
}}
onClick={() => {
- setView('auto');
- }}>
- {t('AUTO_CAST_PAIR')}
+ setView("auto");
+ }}
+ >
+ {t("AUTO_CAST_PAIR")}
</EnteButton>
</>
)}
<Typography color="text.muted">
- {t('PAIR_WITH_PIN_WORKS_FOR_ANY_LARGE_SCREEN_DEVICE')}
+ {t("PAIR_WITH_PIN_WORKS_FOR_ANY_LARGE_SCREEN_DEVICE")}
</Typography>
<EnteButton
onClick={() => {
- setView('pin');
- }}>
- {t('PAIR_WITH_PIN')}
+ setView("pin");
+ }}
+ >
+ {t("PAIR_WITH_PIN")}
</EnteButton>
</>
)}
- {view === 'auto' && (
+ {view === "auto" && (
<VerticallyCentered gap="1rem">
<EnteSpinner />
- <Typography>{t('CHOOSE_DEVICE_FROM_BROWSER')}</Typography>
+ <Typography>{t("CHOOSE_DEVICE_FROM_BROWSER")}</Typography>
<EnteButton
variant="text"
onClick={() => {
- setView('choose');
- }}>
- {t('GO_BACK')}
+ setView("choose");
+ }}
+ >
+ {t("GO_BACK")}
</EnteButton>
</VerticallyCentered>
)}
- {view === 'auto-cast-error' && (
+ {view === "auto-cast-error" && (
<VerticallyCentered gap="1rem">
- <Typography>{t('CAST_AUTO_PAIR_FAILED')}</Typography>
+ <Typography>{t("CAST_AUTO_PAIR_FAILED")}</Typography>
<EnteButton
variant="text"
onClick={() => {
- setView('choose');
- }}>
- {t('GO_BACK')}
+ setView("choose");
+ }}
+ >
+ {t("GO_BACK")}
</EnteButton>
</VerticallyCentered>
)}
- {view === 'pin' && (
+ {view === "pin" && (
<>
- <Typography>{t('VISIT_CAST_ENTE_IO')}</Typography>
- <Typography>{t('ENTER_CAST_PIN_CODE')}</Typography>
+ <Typography>{t("VISIT_CAST_ENTE_IO")}</Typography>
+ <Typography>{t("ENTER_CAST_PIN_CODE")}</Typography>
<SingleInputForm
callback={onSubmit}
fieldType="text"
- placeholder={'123456'}
- buttonText={t('PAIR_DEVICE_TO_TV')}
+ placeholder={"123456"}
+ buttonText={t("PAIR_DEVICE_TO_TV")}
submitButtonProps={{ sx: { mt: 1, mb: 2 } }}
/>
<EnteButton
variant="text"
onClick={() => {
- setView('choose');
- }}>
- {t('GO_BACK')}
+ setView("choose");
+ }}
+ >
+ {t("GO_BACK")}
</EnteButton>
</>
)}
diff --git a/apps/photos/src/components/Collections/CollectionOptions/AlbumCollectionOption.tsx b/apps/photos/src/components/Collections/CollectionOptions/AlbumCollectionOption.tsx
index 5c3f4c1ddd..a3ce073ed3 100644
--- a/apps/photos/src/components/Collections/CollectionOptions/AlbumCollectionOption.tsx
+++ b/apps/photos/src/components/Collections/CollectionOptions/AlbumCollectionOption.tsx
@@ -1,19 +1,18 @@
-import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';
-import React from 'react';
+import { OverflowMenuOption } from "@ente/shared/components/OverflowMenu/option";
-import EditIcon from '@mui/icons-material/Edit';
-import PeopleIcon from '@mui/icons-material/People';
-import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
-import { CollectionActions } from '.';
-import Unarchive from '@mui/icons-material/Unarchive';
-import ArchiveOutlined from '@mui/icons-material/ArchiveOutlined';
-import SortIcon from '@mui/icons-material/Sort';
-import { t } from 'i18next';
-import PushPinOutlined from '@mui/icons-material/PushPinOutlined';
-import { UnPinIcon } from 'components/icons/UnPinIcon';
-import VisibilityOffOutlined from '@mui/icons-material/VisibilityOffOutlined';
-import VisibilityOutlined from '@mui/icons-material/VisibilityOutlined';
-import TvIcon from '@mui/icons-material/Tv';
+import ArchiveOutlined from "@mui/icons-material/ArchiveOutlined";
+import DeleteOutlinedIcon from "@mui/icons-material/DeleteOutlined";
+import EditIcon from "@mui/icons-material/Edit";
+import PeopleIcon from "@mui/icons-material/People";
+import PushPinOutlined from "@mui/icons-material/PushPinOutlined";
+import SortIcon from "@mui/icons-material/Sort";
+import TvIcon from "@mui/icons-material/Tv";
+import Unarchive from "@mui/icons-material/Unarchive";
+import VisibilityOffOutlined from "@mui/icons-material/VisibilityOffOutlined";
+import VisibilityOutlined from "@mui/icons-material/VisibilityOutlined";
+import { UnPinIcon } from "components/icons/UnPinIcon";
+import { t } from "i18next";
+import { CollectionActions } from ".";
interface Iprops {
isArchived: boolean;
@@ -21,7 +20,7 @@ interface Iprops {
isHidden: boolean;
handleCollectionAction: (
action: CollectionActions,
- loader?: boolean
+ loader?: boolean,
) => (...args: any[]) => Promise<void>;
}
@@ -36,36 +35,40 @@ export function AlbumCollectionOption({
<OverflowMenuOption
onClick={handleCollectionAction(
CollectionActions.SHOW_RENAME_DIALOG,
- false
+ false,
)}
- startIcon={<EditIcon />}>
- {t('RENAME_COLLECTION')}
+ startIcon={<EditIcon />}
+ >
+ {t("RENAME_COLLECTION")}
</OverflowMenuOption>
<OverflowMenuOption
onClick={handleCollectionAction(
CollectionActions.SHOW_SORT_ORDER_MENU,
- false
+ false,
)}
- startIcon={<SortIcon />}>
- {t('SORT_BY')}
+ startIcon={<SortIcon />}
+ >
+ {t("SORT_BY")}
</OverflowMenuOption>
{isPinned ? (
<OverflowMenuOption
onClick={handleCollectionAction(
CollectionActions.UNPIN,
- false
+ false,
)}
- startIcon={<UnPinIcon />}>
- {t('UNPIN_ALBUM')}
+ startIcon={<UnPinIcon />}
+ >
+ {t("UNPIN_ALBUM")}
</OverflowMenuOption>
) : (
<OverflowMenuOption
onClick={handleCollectionAction(
CollectionActions.PIN,
- false
+ false,
)}
- startIcon={<PushPinOutlined />}>
- {t('PIN_ALBUM')}
+ startIcon={<PushPinOutlined />}
+ >
+ {t("PIN_ALBUM")}
</OverflowMenuOption>
)}
{!isHidden && (
@@ -73,18 +76,20 @@ export function AlbumCollectionOption({
{isArchived ? (
<OverflowMenuOption
onClick={handleCollectionAction(
- CollectionActions.UNARCHIVE
+ CollectionActions.UNARCHIVE,
)}
- startIcon={<Unarchive />}>
- {t('UNARCHIVE_COLLECTION')}
+ startIcon={<Unarchive />}
+ >
+ {t("UNARCHIVE_COLLECTION")}
</OverflowMenuOption>
) : (
<OverflowMenuOption
onClick={handleCollectionAction(
- CollectionActions.ARCHIVE
+ CollectionActions.ARCHIVE,
)}
- startIcon={<ArchiveOutlined />}>
- {t('ARCHIVE_COLLECTION')}
+ startIcon={<ArchiveOutlined />}
+ >
+ {t("ARCHIVE_COLLECTION")}
</OverflowMenuOption>
)}
</>
@@ -93,44 +98,49 @@ export function AlbumCollectionOption({
<OverflowMenuOption
onClick={handleCollectionAction(
CollectionActions.UNHIDE,
- false
+ false,
)}
- startIcon={<VisibilityOutlined />}>
- {t('UNHIDE_COLLECTION')}
+ startIcon={<VisibilityOutlined />}
+ >
+ {t("UNHIDE_COLLECTION")}
</OverflowMenuOption>
) : (
<OverflowMenuOption
onClick={handleCollectionAction(
CollectionActions.HIDE,
- false
+ false,
)}
- startIcon={<VisibilityOffOutlined />}>
- {t('HIDE_COLLECTION')}
+ startIcon={<VisibilityOffOutlined />}
+ >
+ {t("HIDE_COLLECTION")}
</OverflowMenuOption>
)}
<OverflowMenuOption
startIcon={<DeleteOutlinedIcon />}
onClick={handleCollectionAction(
CollectionActions.CONFIRM_DELETE,
- false
- )}>
- {t('DELETE_COLLECTION')}
+ false,
+ )}
+ >
+ {t("DELETE_COLLECTION")}
</OverflowMenuOption>
<OverflowMenuOption
onClick={handleCollectionAction(
CollectionActions.SHOW_SHARE_DIALOG,
- false
+ false,
)}
- startIcon={<PeopleIcon />}>
- {t('SHARE_COLLECTION')}
+ startIcon={<PeopleIcon />}
+ >
+ {t("SHARE_COLLECTION")}
</OverflowMenuOption>
<OverflowMenuOption
startIcon={<TvIcon />}
onClick={handleCollectionAction(
CollectionActions.SHOW_ALBUM_CAST_DIALOG,
- false
- )}>
- {t('CAST_ALBUM_TO_TV')}
+ false,
+ )}
+ >
+ {t("CAST_ALBUM_TO_TV")}
</OverflowMenuOption>
</>
);
diff --git a/apps/photos/src/components/Collections/CollectionOptions/CollectionSortOrderMenu.tsx b/apps/photos/src/components/Collections/CollectionOptions/CollectionSortOrderMenu.tsx
index 251bdf32c0..032bdeaf58 100644
--- a/apps/photos/src/components/Collections/CollectionOptions/CollectionSortOrderMenu.tsx
+++ b/apps/photos/src/components/Collections/CollectionOptions/CollectionSortOrderMenu.tsx
@@ -1,12 +1,12 @@
-import { StyledMenu } from '@ente/shared/components/OverflowMenu/menu';
-import { CollectionActions } from '.';
-import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';
-import { t } from 'i18next';
+import { StyledMenu } from "@ente/shared/components/OverflowMenu/menu";
+import { OverflowMenuOption } from "@ente/shared/components/OverflowMenu/option";
+import { t } from "i18next";
+import { CollectionActions } from ".";
interface Iprops {
handleCollectionAction: (
action: CollectionActions,
- loader?: boolean
+ loader?: boolean,
) => (...args: any[]) => Promise<void>;
overFlowMenuIconRef: React.MutableRefObject<SVGSVGElement>;
collectionSortOrderMenuView: boolean;
@@ -34,27 +34,28 @@ const CollectionSortOrderMenu = ({
};
return (
<StyledMenu
- id={'collection-files-sort'}
+ id={"collection-files-sort"}
anchorEl={overFlowMenuIconRef.current}
open={collectionSortOrderMenuView}
onClose={closeCollectionSortOrderMenu}
MenuListProps={{
disablePadding: true,
- 'aria-labelledby': 'collection-files-sort',
+ "aria-labelledby": "collection-files-sort",
}}
anchorOrigin={{
- vertical: 'bottom',
- horizontal: 'right',
+ vertical: "bottom",
+ horizontal: "right",
}}
transformOrigin={{
- vertical: 'top',
- horizontal: 'right',
- }}>
+ vertical: "top",
+ horizontal: "right",
+ }}
+ >
<OverflowMenuOption onClick={setCollectionSortOrderToDesc}>
- {t('NEWEST_FIRST')}
+ {t("NEWEST_FIRST")}
</OverflowMenuOption>
<OverflowMenuOption onClick={setCollectionSortOrderToAsc}>
- {t('OLDEST_FIRST')}
+ {t("OLDEST_FIRST")}
</OverflowMenuOption>
</StyledMenu>
);
diff --git a/apps/photos/src/components/Collections/CollectionOptions/OnlyDownloadCollectionOption.tsx b/apps/photos/src/components/Collections/CollectionOptions/OnlyDownloadCollectionOption.tsx
index dc4ec52b14..67ab6ecaa0 100644
--- a/apps/photos/src/components/Collections/CollectionOptions/OnlyDownloadCollectionOption.tsx
+++ b/apps/photos/src/components/Collections/CollectionOptions/OnlyDownloadCollectionOption.tsx
@@ -1,14 +1,13 @@
-import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';
-import React from 'react';
+import { OverflowMenuOption } from "@ente/shared/components/OverflowMenu/option";
-import FileDownloadOutlinedIcon from '@mui/icons-material/FileDownloadOutlined';
-import { CollectionActions } from '.';
-import { t } from 'i18next';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import FileDownloadOutlinedIcon from "@mui/icons-material/FileDownloadOutlined";
+import { t } from "i18next";
+import { CollectionActions } from ".";
interface Iprops {
handleCollectionAction: (
action: CollectionActions,
- loader?: boolean
+ loader?: boolean,
) => (...args: any[]) => Promise<void>;
downloadOptionText?: string;
isDownloadInProgress?: boolean;
@@ -16,7 +15,7 @@ interface Iprops {
export function OnlyDownloadCollectionOption({
handleCollectionAction,
- downloadOptionText = t('DOWNLOAD'),
+ downloadOptionText = t("DOWNLOAD"),
isDownloadInProgress,
}: Iprops) {
return (
@@ -25,10 +24,11 @@ export function OnlyDownloadCollectionOption({
!isDownloadInProgress ? (
<FileDownloadOutlinedIcon />
) : (
- <EnteSpinner size="20px" sx={{ cursor: 'not-allowed' }} />
+ <EnteSpinner size="20px" sx={{ cursor: "not-allowed" }} />
)
}
- onClick={handleCollectionAction(CollectionActions.DOWNLOAD, false)}>
+ onClick={handleCollectionAction(CollectionActions.DOWNLOAD, false)}
+ >
{downloadOptionText}
</OverflowMenuOption>
);
diff --git a/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/DownloadQuickOption.tsx b/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/DownloadQuickOption.tsx
index 8e9f918d05..37dd515293 100644
--- a/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/DownloadQuickOption.tsx
+++ b/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/DownloadQuickOption.tsx
@@ -1,13 +1,12 @@
-import { CollectionActions } from '..';
-import React from 'react';
-import FileDownloadOutlinedIcon from '@mui/icons-material/FileDownloadOutlined';
-import { IconButton, Tooltip } from '@mui/material';
-import { CollectionSummaryType } from 'constants/collection';
-import { t } from 'i18next';
+import FileDownloadOutlinedIcon from "@mui/icons-material/FileDownloadOutlined";
+import { IconButton, Tooltip } from "@mui/material";
+import { CollectionSummaryType } from "constants/collection";
+import { t } from "i18next";
+import { CollectionActions } from "..";
interface Iprops {
handleCollectionAction: (
action: CollectionActions,
- loader?: boolean
+ loader?: boolean,
) => (...args: any[]) => Promise<void>;
collectionSummaryType: CollectionSummaryType;
}
@@ -20,20 +19,22 @@ export function DownloadQuickOption({
<Tooltip
title={
collectionSummaryType === CollectionSummaryType.favorites
- ? t('DOWNLOAD_FAVORITES')
+ ? t("DOWNLOAD_FAVORITES")
: collectionSummaryType ===
CollectionSummaryType.uncategorized
- ? t('DOWNLOAD_UNCATEGORIZED')
+ ? t("DOWNLOAD_UNCATEGORIZED")
: collectionSummaryType ===
CollectionSummaryType.hiddenItems
- ? t('DOWNLOAD_HIDDEN_ITEMS')
- : t('DOWNLOAD_COLLECTION')
- }>
+ ? t("DOWNLOAD_HIDDEN_ITEMS")
+ : t("DOWNLOAD_COLLECTION")
+ }
+ >
<IconButton
onClick={handleCollectionAction(
CollectionActions.DOWNLOAD,
- false
- )}>
+ false,
+ )}
+ >
<FileDownloadOutlinedIcon />
</IconButton>
</Tooltip>
diff --git a/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/EmptyTrashQuickOption.tsx b/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/EmptyTrashQuickOption.tsx
index b36d7e58cc..9126cced13 100644
--- a/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/EmptyTrashQuickOption.tsx
+++ b/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/EmptyTrashQuickOption.tsx
@@ -1,24 +1,24 @@
-import { CollectionActions } from '..';
-import React from 'react';
-import { IconButton, Tooltip } from '@mui/material';
-import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
-import { t } from 'i18next';
+import DeleteOutlinedIcon from "@mui/icons-material/DeleteOutlined";
+import { IconButton, Tooltip } from "@mui/material";
+import { t } from "i18next";
+import { CollectionActions } from "..";
interface Iprops {
handleCollectionAction: (
action: CollectionActions,
- loader?: boolean
+ loader?: boolean,
) => (...args: any[]) => Promise<void>;
}
export function EmptyTrashQuickOption({ handleCollectionAction }: Iprops) {
return (
- <Tooltip title={t('EMPTY_TRASH')}>
+ <Tooltip title={t("EMPTY_TRASH")}>
<IconButton
onClick={handleCollectionAction(
CollectionActions.CONFIRM_EMPTY_TRASH,
- false
- )}>
+ false,
+ )}
+ >
<DeleteOutlinedIcon />
</IconButton>
</Tooltip>
diff --git a/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/ShareQuickOption.tsx b/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/ShareQuickOption.tsx
index d539510960..c54dcfd822 100644
--- a/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/ShareQuickOption.tsx
+++ b/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/ShareQuickOption.tsx
@@ -1,14 +1,13 @@
-import { CollectionActions } from '..';
-import React from 'react';
-import PeopleIcon from '@mui/icons-material/People';
-import { IconButton, Tooltip } from '@mui/material';
-import { CollectionSummaryType } from 'constants/collection';
-import { t } from 'i18next';
+import PeopleIcon from "@mui/icons-material/People";
+import { IconButton, Tooltip } from "@mui/material";
+import { CollectionSummaryType } from "constants/collection";
+import { t } from "i18next";
+import { CollectionActions } from "..";
interface Iprops {
handleCollectionAction: (
action: CollectionActions,
- loader?: boolean
+ loader?: boolean,
) => (...args: any[]) => Promise<void>;
collectionSummaryType: CollectionSummaryType;
}
@@ -24,19 +23,21 @@ export function ShareQuickOption({
CollectionSummaryType.incomingShareViewer ||
collectionSummaryType ===
CollectionSummaryType.incomingShareCollaborator
- ? t('SHARING_DETAILS')
+ ? t("SHARING_DETAILS")
: collectionSummaryType ===
CollectionSummaryType.outgoingShare ||
collectionSummaryType ===
CollectionSummaryType.sharedOnlyViaLink
- ? t('MODIFY_SHARING')
- : t('SHARE_COLLECTION')
- }>
+ ? t("MODIFY_SHARING")
+ : t("SHARE_COLLECTION")
+ }
+ >
<IconButton
onClick={handleCollectionAction(
CollectionActions.SHOW_SHARE_DIALOG,
- false
- )}>
+ false,
+ )}
+ >
<PeopleIcon />
</IconButton>
</Tooltip>
diff --git a/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/index.tsx b/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/index.tsx
index 8af5f8c84f..1d240fc0c5 100644
--- a/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/index.tsx
+++ b/apps/photos/src/components/Collections/CollectionOptions/QuickOptions/index.tsx
@@ -1,20 +1,19 @@
-import { CollectionActions } from '..';
-import React from 'react';
-import { CollectionSummaryType } from 'constants/collection';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import { EmptyTrashQuickOption } from './EmptyTrashQuickOption';
-import { DownloadQuickOption } from './DownloadQuickOption';
-import { ShareQuickOption } from './ShareQuickOption';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import { CollectionSummaryType } from "constants/collection";
import {
showDownloadQuickOption,
- showShareQuickOption,
showEmptyTrashQuickOption,
-} from 'utils/collection';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
+ showShareQuickOption,
+} from "utils/collection";
+import { CollectionActions } from "..";
+import { DownloadQuickOption } from "./DownloadQuickOption";
+import { EmptyTrashQuickOption } from "./EmptyTrashQuickOption";
+import { ShareQuickOption } from "./ShareQuickOption";
interface Iprops {
handleCollectionAction: (
action: CollectionActions,
- loader?: boolean
+ loader?: boolean,
) => (...args: any[]) => Promise<void>;
collectionSummaryType: CollectionSummaryType;
isDownloadInProgress: boolean;
@@ -26,7 +25,7 @@ export function QuickOptions({
isDownloadInProgress,
}: Iprops) {
return (
- <FlexWrapper sx={{ gap: '16px' }}>
+ <FlexWrapper sx={{ gap: "16px" }}>
{showEmptyTrashQuickOption(collectionSummaryType) && (
<EmptyTrashQuickOption
handleCollectionAction={handleCollectionAction}
@@ -39,7 +38,7 @@ export function QuickOptions({
collectionSummaryType={collectionSummaryType}
/>
) : (
- <EnteSpinner size="20px" sx={{ cursor: 'not-allowed' }} />
+ <EnteSpinner size="20px" sx={{ cursor: "not-allowed" }} />
))}
{showShareQuickOption(collectionSummaryType) && (
<ShareQuickOption
diff --git a/apps/photos/src/components/Collections/CollectionOptions/SharedCollectionOption.tsx b/apps/photos/src/components/Collections/CollectionOptions/SharedCollectionOption.tsx
index 40f1fbf2c1..b6c131e5d6 100644
--- a/apps/photos/src/components/Collections/CollectionOptions/SharedCollectionOption.tsx
+++ b/apps/photos/src/components/Collections/CollectionOptions/SharedCollectionOption.tsx
@@ -1,16 +1,15 @@
-import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';
-import React from 'react';
-import LogoutIcon from '@mui/icons-material/Logout';
-import { CollectionActions } from '.';
-import { t } from 'i18next';
-import Unarchive from '@mui/icons-material/Unarchive';
-import ArchiveOutlined from '@mui/icons-material/ArchiveOutlined';
+import { OverflowMenuOption } from "@ente/shared/components/OverflowMenu/option";
+import ArchiveOutlined from "@mui/icons-material/ArchiveOutlined";
+import LogoutIcon from "@mui/icons-material/Logout";
+import Unarchive from "@mui/icons-material/Unarchive";
+import { t } from "i18next";
+import { CollectionActions } from ".";
interface Iprops {
isArchived: boolean;
handleCollectionAction: (
action: CollectionActions,
- loader?: boolean
+ loader?: boolean,
) => (...args: any[]) => Promise<void>;
}
@@ -23,25 +22,28 @@ export function SharedCollectionOption({
{isArchived ? (
<OverflowMenuOption
onClick={handleCollectionAction(
- CollectionActions.UNARCHIVE
+ CollectionActions.UNARCHIVE,
)}
- startIcon={<Unarchive />}>
- {t('UNARCHIVE_COLLECTION')}
+ startIcon={<Unarchive />}
+ >
+ {t("UNARCHIVE_COLLECTION")}
</OverflowMenuOption>
) : (
<OverflowMenuOption
onClick={handleCollectionAction(CollectionActions.ARCHIVE)}
- startIcon={<ArchiveOutlined />}>
- {t('ARCHIVE_COLLECTION')}
+ startIcon={<ArchiveOutlined />}
+ >
+ {t("ARCHIVE_COLLECTION")}
</OverflowMenuOption>
)}
<OverflowMenuOption
startIcon={<LogoutIcon />}
onClick={handleCollectionAction(
CollectionActions.CONFIRM_LEAVE_SHARED_ALBUM,
- false
- )}>
- {t('LEAVE_ALBUM')}
+ false,
+ )}
+ >
+ {t("LEAVE_ALBUM")}
</OverflowMenuOption>
</>
);
diff --git a/apps/photos/src/components/Collections/CollectionOptions/TrashCollectionOption.tsx b/apps/photos/src/components/Collections/CollectionOptions/TrashCollectionOption.tsx
index 2c0fedd147..b7f383b87e 100644
--- a/apps/photos/src/components/Collections/CollectionOptions/TrashCollectionOption.tsx
+++ b/apps/photos/src/components/Collections/CollectionOptions/TrashCollectionOption.tsx
@@ -1,14 +1,13 @@
-import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';
-import React from 'react';
+import { OverflowMenuOption } from "@ente/shared/components/OverflowMenu/option";
-import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
-import { CollectionActions } from '.';
-import { t } from 'i18next';
+import DeleteOutlinedIcon from "@mui/icons-material/DeleteOutlined";
+import { t } from "i18next";
+import { CollectionActions } from ".";
interface Iprops {
handleCollectionAction: (
action: CollectionActions,
- loader?: boolean
+ loader?: boolean,
) => (...args: any[]) => Promise<void>;
}
@@ -19,9 +18,10 @@ export function TrashCollectionOption({ handleCollectionAction }: Iprops) {
startIcon={<DeleteOutlinedIcon />}
onClick={handleCollectionAction(
CollectionActions.CONFIRM_EMPTY_TRASH,
- false
- )}>
- {t('EMPTY_TRASH')}
+ false,
+ )}
+ >
+ {t("EMPTY_TRASH")}
</OverflowMenuOption>
);
}
diff --git a/apps/photos/src/components/Collections/CollectionOptions/index.tsx b/apps/photos/src/components/Collections/CollectionOptions/index.tsx
index 4b6b7a7ccd..f39f73b9cf 100644
--- a/apps/photos/src/components/Collections/CollectionOptions/index.tsx
+++ b/apps/photos/src/components/Collections/CollectionOptions/index.tsx
@@ -1,13 +1,23 @@
-import { AlbumCollectionOption } from './AlbumCollectionOption';
-import React, {
- Dispatch,
- SetStateAction,
- useContext,
- useRef,
- useState,
-} from 'react';
-import * as CollectionAPI from 'services/collectionService';
-import * as TrashService from 'services/trashService';
+import { HorizontalFlex } from "@ente/shared/components/Container";
+import OverflowMenu from "@ente/shared/components/OverflowMenu/menu";
+import { logError } from "@ente/shared/sentry";
+import MoreHoriz from "@mui/icons-material/MoreHoriz";
+import { Box } from "@mui/material";
+import {
+ ALL_SECTION,
+ CollectionSummaryType,
+ HIDDEN_ITEMS_SECTION,
+} from "constants/collection";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { GalleryContext } from "pages/gallery";
+import { Dispatch, SetStateAction, useContext, useRef, useState } from "react";
+import { Trans } from "react-i18next";
+import * as CollectionAPI from "services/collectionService";
+import * as TrashService from "services/trashService";
+import { Collection } from "types/collection";
+import { SetFilesDownloadProgressAttributesCreator } from "types/gallery";
+import { VISIBILITY_STATE } from "types/magicMetadata";
import {
changeCollectionOrder,
changeCollectionSortOrder,
@@ -15,31 +25,15 @@ import {
downloadCollectionHelper,
downloadDefaultHiddenCollectionHelper,
isHiddenCollection,
-} from 'utils/collection';
-import { SetCollectionNamerAttributes } from '../CollectionNamer';
-import { Collection } from 'types/collection';
-import { isArchivedCollection, isPinnedCollection } from 'utils/magicMetadata';
-import { GalleryContext } from 'pages/gallery';
-import { logError } from '@ente/shared/sentry';
-import { VISIBILITY_STATE } from 'types/magicMetadata';
-import { AppContext } from 'pages/_app';
-import OverflowMenu from '@ente/shared/components/OverflowMenu/menu';
-import {
- ALL_SECTION,
- CollectionSummaryType,
- HIDDEN_ITEMS_SECTION,
-} from 'constants/collection';
-import { TrashCollectionOption } from './TrashCollectionOption';
-import { SharedCollectionOption } from './SharedCollectionOption';
-import { OnlyDownloadCollectionOption } from './OnlyDownloadCollectionOption';
-import { QuickOptions } from './QuickOptions';
-import MoreHoriz from '@mui/icons-material/MoreHoriz';
-import { HorizontalFlex } from '@ente/shared/components/Container';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
-import { Box } from '@mui/material';
-import CollectionSortOrderMenu from './CollectionSortOrderMenu';
-import { SetFilesDownloadProgressAttributesCreator } from 'types/gallery';
+} from "utils/collection";
+import { isArchivedCollection, isPinnedCollection } from "utils/magicMetadata";
+import { SetCollectionNamerAttributes } from "../CollectionNamer";
+import { AlbumCollectionOption } from "./AlbumCollectionOption";
+import CollectionSortOrderMenu from "./CollectionSortOrderMenu";
+import { OnlyDownloadCollectionOption } from "./OnlyDownloadCollectionOption";
+import { QuickOptions } from "./QuickOptions";
+import { SharedCollectionOption } from "./SharedCollectionOption";
+import { TrashCollectionOption } from "./TrashCollectionOption";
interface CollectionOptionsProps {
setCollectionNamerAttributes: SetCollectionNamerAttributes;
@@ -103,7 +97,7 @@ const CollectionOptions = (props: CollectionOptionsProps) => {
const handleCollectionAction = (
action: CollectionActions,
- loader = true
+ loader = true,
) => {
let callback: Function;
switch (action) {
@@ -170,8 +164,8 @@ const CollectionOptions = (props: CollectionOptionsProps) => {
default:
logError(
- Error('invalid collection action '),
- 'handleCollectionAction failed'
+ Error("invalid collection action "),
+ "handleCollectionAction failed",
);
{
action;
@@ -182,11 +176,11 @@ const CollectionOptions = (props: CollectionOptionsProps) => {
loader && startLoading();
await callback(...args);
} catch (e) {
- logError(e, 'collection action failed', { action });
+ logError(e, "collection action failed", { action });
setDialogMessage({
- title: t('ERROR'),
- content: t('UNKNOWN_ERROR'),
- close: { variant: 'critical' },
+ title: t("ERROR"),
+ content: t("UNKNOWN_ERROR"),
+ close: { variant: "critical" },
});
} finally {
syncWithRemote(false, true);
@@ -237,21 +231,21 @@ const CollectionOptions = (props: CollectionOptionsProps) => {
setFilesDownloadProgressAttributesCreator(
activeCollection.name,
HIDDEN_ITEMS_SECTION,
- true
+ true,
);
downloadDefaultHiddenCollectionHelper(
- setFilesDownloadProgressAttributes
+ setFilesDownloadProgressAttributes,
);
} else {
const setFilesDownloadProgressAttributes =
setFilesDownloadProgressAttributesCreator(
activeCollection.name,
activeCollection.id,
- isHiddenCollection(activeCollection)
+ isHiddenCollection(activeCollection),
);
downloadCollectionHelper(
activeCollection.id,
- setFilesDownloadProgressAttributes
+ setFilesDownloadProgressAttributes,
);
}
};
@@ -264,8 +258,8 @@ const CollectionOptions = (props: CollectionOptionsProps) => {
const showRenameCollectionModal = () => {
setCollectionNamerAttributes({
- title: t('RENAME_COLLECTION'),
- buttonText: t('RENAME'),
+ title: t("RENAME_COLLECTION"),
+ buttonText: t("RENAME"),
autoFilledName: activeCollection.name,
callback: handleCollectionAction(CollectionActions.RENAME),
});
@@ -273,61 +267,61 @@ const CollectionOptions = (props: CollectionOptionsProps) => {
const confirmDeleteCollection = () => {
setDialogMessage({
- title: t('DELETE_COLLECTION_TITLE'),
+ title: t("DELETE_COLLECTION_TITLE"),
content: (
<Trans
- i18nKey={'DELETE_COLLECTION_MESSAGE'}
+ i18nKey={"DELETE_COLLECTION_MESSAGE"}
components={{
- a: <Box component={'span'} color="text.base" />,
+ a: <Box component={"span"} color="text.base" />,
}}
/>
),
proceed: {
- text: t('DELETE_PHOTOS'),
+ text: t("DELETE_PHOTOS"),
action: handleCollectionAction(
- CollectionActions.DELETE_WITH_FILES
+ CollectionActions.DELETE_WITH_FILES,
),
- variant: 'critical',
+ variant: "critical",
},
secondary: {
- text: t('KEEP_PHOTOS'),
+ text: t("KEEP_PHOTOS"),
action: handleCollectionAction(
- CollectionActions.DELETE_BUT_KEEP_FILES
+ CollectionActions.DELETE_BUT_KEEP_FILES,
),
- variant: 'primary',
+ variant: "primary",
},
close: {
- text: t('CANCEL'),
+ text: t("CANCEL"),
},
});
};
const confirmEmptyTrash = () =>
setDialogMessage({
- title: t('EMPTY_TRASH_TITLE'),
- content: t('EMPTY_TRASH_MESSAGE'),
+ title: t("EMPTY_TRASH_TITLE"),
+ content: t("EMPTY_TRASH_MESSAGE"),
proceed: {
action: handleCollectionAction(CollectionActions.EMPTY_TRASH),
- text: t('EMPTY_TRASH'),
- variant: 'critical',
+ text: t("EMPTY_TRASH"),
+ variant: "critical",
},
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
});
const confirmLeaveSharedAlbum = () => {
setDialogMessage({
- title: t('LEAVE_SHARED_ALBUM_TITLE'),
- content: t('LEAVE_SHARED_ALBUM_MESSAGE'),
+ title: t("LEAVE_SHARED_ALBUM_TITLE"),
+ content: t("LEAVE_SHARED_ALBUM_MESSAGE"),
proceed: {
- text: t('LEAVE_SHARED_ALBUM'),
+ text: t("LEAVE_SHARED_ALBUM"),
action: handleCollectionAction(
- CollectionActions.LEAVE_SHARED_ALBUM
+ CollectionActions.LEAVE_SHARED_ALBUM,
),
- variant: 'critical',
+ variant: "critical",
},
close: {
- text: t('CANCEL'),
+ text: t("CANCEL"),
},
});
};
@@ -347,20 +341,20 @@ const CollectionOptions = (props: CollectionOptionsProps) => {
const hideAlbum = async () => {
await changeCollectionVisibility(
activeCollection,
- VISIBILITY_STATE.HIDDEN
+ VISIBILITY_STATE.HIDDEN,
);
setActiveCollectionID(ALL_SECTION);
};
const unHideAlbum = async () => {
await changeCollectionVisibility(
activeCollection,
- VISIBILITY_STATE.VISIBLE
+ VISIBILITY_STATE.VISIBLE,
);
setActiveCollectionID(HIDDEN_ITEMS_SECTION);
};
return (
- <HorizontalFlex sx={{ display: 'inline-flex', gap: '16px' }}>
+ <HorizontalFlex sx={{ display: "inline-flex", gap: "16px" }}>
<QuickOptions
handleCollectionAction={handleCollectionAction}
collectionSummaryType={collectionSummaryType}
@@ -368,8 +362,9 @@ const CollectionOptions = (props: CollectionOptionsProps) => {
/>
<OverflowMenu
- ariaControls={'collection-options'}
- triggerButtonIcon={<MoreHoriz ref={overFlowMenuIconRef} />}>
+ ariaControls={"collection-options"}
+ triggerButtonIcon={<MoreHoriz ref={overFlowMenuIconRef} />}
+ >
{collectionSummaryType === CollectionSummaryType.trash ? (
<TrashCollectionOption
handleCollectionAction={handleCollectionAction}
@@ -379,19 +374,19 @@ const CollectionOptions = (props: CollectionOptionsProps) => {
<OnlyDownloadCollectionOption
isDownloadInProgress={isActiveCollectionDownloadInProgress()}
handleCollectionAction={handleCollectionAction}
- downloadOptionText={t('DOWNLOAD_FAVORITES')}
+ downloadOptionText={t("DOWNLOAD_FAVORITES")}
/>
) : collectionSummaryType ===
CollectionSummaryType.uncategorized ? (
<OnlyDownloadCollectionOption
handleCollectionAction={handleCollectionAction}
- downloadOptionText={t('DOWNLOAD_UNCATEGORIZED')}
+ downloadOptionText={t("DOWNLOAD_UNCATEGORIZED")}
/>
) : collectionSummaryType ===
CollectionSummaryType.hiddenItems ? (
<OnlyDownloadCollectionOption
handleCollectionAction={handleCollectionAction}
- downloadOptionText={t('DOWNLOAD_HIDDEN_ITEMS')}
+ downloadOptionText={t("DOWNLOAD_HIDDEN_ITEMS")}
/>
) : collectionSummaryType ===
CollectionSummaryType.incomingShareViewer ||
diff --git a/apps/photos/src/components/Collections/CollectionSelector/AddCollectionButton.tsx b/apps/photos/src/components/Collections/CollectionSelector/AddCollectionButton.tsx
index 4ec1dfd84a..87e698361d 100644
--- a/apps/photos/src/components/Collections/CollectionSelector/AddCollectionButton.tsx
+++ b/apps/photos/src/components/Collections/CollectionSelector/AddCollectionButton.tsx
@@ -1,12 +1,11 @@
-import CollectionCard from 'components/Collections/CollectionCard';
+import { CenteredFlex, Overlay } from "@ente/shared/components/Container";
+import { styled } from "@mui/material";
+import CollectionCard from "components/Collections/CollectionCard";
import {
AllCollectionTile,
AllCollectionTileText,
-} from 'components/Collections/styledComponents';
-import React from 'react';
-import { styled } from '@mui/material';
-import { CenteredFlex, Overlay } from '@ente/shared/components/Container';
-import { t } from 'i18next';
+} from "components/Collections/styledComponents";
+import { t } from "i18next";
const ImageContainer = styled(Overlay)`
display: flex;
@@ -22,9 +21,10 @@ export default function AddCollectionButton({ showNextModal }: Iprops) {
<CollectionCard
collectionTile={AllCollectionTile}
onClick={() => showNextModal()}
- coverFile={null}>
+ coverFile={null}
+ >
<AllCollectionTileText>
- {t('CREATE_COLLECTION')}
+ {t("CREATE_COLLECTION")}
</AllCollectionTileText>
<ImageContainer>
<CenteredFlex>+</CenteredFlex>
diff --git a/apps/photos/src/components/Collections/CollectionSelector/CollectionCard.tsx b/apps/photos/src/components/Collections/CollectionSelector/CollectionCard.tsx
index dbb29b3de6..e591227745 100644
--- a/apps/photos/src/components/Collections/CollectionSelector/CollectionCard.tsx
+++ b/apps/photos/src/components/Collections/CollectionSelector/CollectionCard.tsx
@@ -1,8 +1,7 @@
-import { Typography } from '@mui/material';
-import React from 'react';
-import CollectionCard from '../CollectionCard';
-import { CollectionSummary } from 'types/collection';
-import { AllCollectionTile, AllCollectionTileText } from '../styledComponents';
+import { Typography } from "@mui/material";
+import { CollectionSummary } from "types/collection";
+import CollectionCard from "../CollectionCard";
+import { AllCollectionTile, AllCollectionTileText } from "../styledComponents";
interface Iprops {
collectionSummary: CollectionSummary;
@@ -17,7 +16,8 @@ export default function CollectionSelectorCard({
<CollectionCard
collectionTile={AllCollectionTile}
coverFile={collectionSummary.coverFile}
- onClick={() => onCollectionClick(collectionSummary.id)}>
+ onClick={() => onCollectionClick(collectionSummary.id)}
+ >
<AllCollectionTileText>
<Typography>{collectionSummary.name}</Typography>
</AllCollectionTileText>
diff --git a/apps/photos/src/components/Collections/CollectionSelector/index.tsx b/apps/photos/src/components/Collections/CollectionSelector/index.tsx
index 8f80c5ed6d..b9ea88639f 100644
--- a/apps/photos/src/components/Collections/CollectionSelector/index.tsx
+++ b/apps/photos/src/components/Collections/CollectionSelector/index.tsx
@@ -1,28 +1,28 @@
-import React, { useContext, useEffect, useState } from 'react';
-import {
- Collection,
- CollectionSummaries,
- CollectionSummary,
-} from 'types/collection';
-import DialogTitleWithCloseButton from '@ente/shared/components/DialogBox/TitleWithCloseButton';
-import { AppContext } from 'pages/_app';
-import { AllCollectionDialog } from 'components/Collections/AllCollections/dialog';
-import { DialogContent } from '@mui/material';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import CollectionSelectorCard from './CollectionCard';
-import AddCollectionButton from './AddCollectionButton';
-import { CollectionSelectorIntent } from 'types/gallery';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import DialogTitleWithCloseButton from "@ente/shared/components/DialogBox/TitleWithCloseButton";
+import { DialogContent } from "@mui/material";
+import { AllCollectionDialog } from "components/Collections/AllCollections/dialog";
import {
COLLECTION_SORT_ORDER,
CollectionSummaryType,
DUMMY_UNCATEGORIZED_COLLECTION,
-} from 'constants/collection';
-import { t } from 'i18next';
-import { createUnCategorizedCollection } from 'services/collectionService';
+} from "constants/collection";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext, useEffect, useState } from "react";
+import { createUnCategorizedCollection } from "services/collectionService";
+import {
+ Collection,
+ CollectionSummaries,
+ CollectionSummary,
+} from "types/collection";
+import { CollectionSelectorIntent } from "types/gallery";
import {
isAddToAllowedCollection,
isMoveToAllowedCollection,
-} from 'utils/collection';
+} from "utils/collection";
+import AddCollectionButton from "./AddCollectionButton";
+import CollectionSelectorCard from "./CollectionCard";
export interface CollectionSelectorAttributes {
callback: (collection: Collection) => void;
@@ -126,23 +126,24 @@ function CollectionSelector({
onClose={onUserTriggeredClose}
open={props.open}
position="center"
- fullScreen={appContext.isMobile}>
+ fullScreen={appContext.isMobile}
+ >
<DialogTitleWithCloseButton onClose={onUserTriggeredClose}>
{attributes.intent === CollectionSelectorIntent.upload
- ? t('UPLOAD_TO_COLLECTION')
+ ? t("UPLOAD_TO_COLLECTION")
: attributes.intent === CollectionSelectorIntent.add
- ? t('ADD_TO_COLLECTION')
+ ? t("ADD_TO_COLLECTION")
: attributes.intent === CollectionSelectorIntent.move
- ? t('MOVE_TO_COLLECTION')
+ ? t("MOVE_TO_COLLECTION")
: attributes.intent === CollectionSelectorIntent.restore
- ? t('RESTORE_TO_COLLECTION')
+ ? t("RESTORE_TO_COLLECTION")
: attributes.intent ===
CollectionSelectorIntent.unhide
- ? t('UNHIDE_TO_COLLECTION')
- : t('SELECT_COLLECTION')}
+ ? t("UNHIDE_TO_COLLECTION")
+ : t("SELECT_COLLECTION")}
</DialogTitleWithCloseButton>
- <DialogContent sx={{ '&&&': { padding: 0 } }}>
- <FlexWrapper flexWrap="wrap" gap={'4px'} padding={'16px'}>
+ <DialogContent sx={{ "&&&": { padding: 0 } }}>
+ <FlexWrapper flexWrap="wrap" gap={"4px"} padding={"16px"}>
<AddCollectionButton
showNextModal={attributes.showNextModal}
/>
diff --git a/apps/photos/src/components/Collections/CollectionShare/container.tsx b/apps/photos/src/components/Collections/CollectionShare/container.tsx
index 9e704a7dd7..143d9a0273 100644
--- a/apps/photos/src/components/Collections/CollectionShare/container.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/container.tsx
@@ -1,20 +1,20 @@
-import { Dialog, styled } from '@mui/material';
-import PropTypes from 'prop-types';
+import { Dialog, styled } from "@mui/material";
+import PropTypes from "prop-types";
export const CollectionShareContainer = styled(Dialog)(({ theme }) => ({
- '& .MuiDialog-container': {
- justifyContent: 'flex-end',
+ "& .MuiDialog-container": {
+ justifyContent: "flex-end",
},
- '& .MuiPaper-root': {
- width: '414px',
+ "& .MuiPaper-root": {
+ width: "414px",
},
- '& .MuiDialog-paperFullScreen': {
- maxWidth: '100%',
+ "& .MuiDialog-paperFullScreen": {
+ maxWidth: "100%",
},
- '& .MuiDialogTitle-root': {
+ "& .MuiDialogTitle-root": {
padding: theme.spacing(4, 3, 3, 4),
},
- '& .MuiDialogContent-root': {
+ "& .MuiDialogContent-root": {
padding: theme.spacing(3, 4),
},
}));
diff --git a/apps/photos/src/components/Collections/CollectionShare/emailShare/AddParticipant.tsx b/apps/photos/src/components/Collections/CollectionShare/emailShare/AddParticipant.tsx
index 94b356612f..05437ada00 100644
--- a/apps/photos/src/components/Collections/CollectionShare/emailShare/AddParticipant.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/emailShare/AddParticipant.tsx
@@ -1,17 +1,16 @@
-import { Stack } from '@mui/material';
-import { COLLECTION_ROLE, Collection } from 'types/collection';
-import { EnteDrawer } from 'components/EnteDrawer';
-import { t } from 'i18next';
-import { DialogProps } from '@mui/material';
-import Titlebar from 'components/Titlebar';
+import { DialogProps, Stack } from "@mui/material";
+import { EnteDrawer } from "components/EnteDrawer";
+import Titlebar from "components/Titlebar";
+import { t } from "i18next";
+import { COLLECTION_ROLE, Collection } from "types/collection";
-import { GalleryContext } from 'pages/gallery';
-import { useContext, useMemo } from 'react';
-import { shareCollection } from 'services/collectionService';
-import { handleSharingErrors } from 'utils/error/ui';
+import { GalleryContext } from "pages/gallery";
+import { useContext, useMemo } from "react";
+import { shareCollection } from "services/collectionService";
+import { handleSharingErrors } from "utils/error/ui";
import AddParticipantForm, {
AddParticipantFormProps,
-} from './AddParticipantForm';
+} from "./AddParticipantForm";
interface Iprops {
collection: Collection;
@@ -34,12 +33,12 @@ export default function AddParticipant({
() =>
emailList.filter(
(email) =>
- !collection.sharees?.find((value) => value.email === email)
+ !collection.sharees?.find((value) => value.email === email),
),
- [emailList, collection.sharees]
+ [emailList, collection.sharees],
);
- const collectionShare: AddParticipantFormProps['callback'] = async ({
+ const collectionShare: AddParticipantFormProps["callback"] = async ({
email,
emails,
}) => {
@@ -47,11 +46,11 @@ export default function AddParticipant({
// and already shared
if (email) {
if (email === user.email) {
- throw new Error(t('SHARE_WITH_SELF'));
+ throw new Error(t("SHARE_WITH_SELF"));
} else if (
collection?.sharees?.find((value) => value.email === email)
) {
- throw new Error(t('ALREADY_SHARED', { email: email }));
+ throw new Error(t("ALREADY_SHARED", { email: email }));
}
// set emails to array of one email
emails = [email];
@@ -79,8 +78,8 @@ export default function AddParticipant({
onRootClose();
};
- const handleDrawerClose: DialogProps['onClose'] = (_, reason) => {
- if (reason === 'backdropClick') {
+ const handleDrawerClose: DialogProps["onClose"] = (_, reason) => {
+ if (reason === "backdropClick") {
handleRootClose();
} else {
onClose();
@@ -90,13 +89,13 @@ export default function AddParticipant({
return (
<>
<EnteDrawer anchor="right" open={open} onClose={handleDrawerClose}>
- <Stack spacing={'4px'} py={'12px'}>
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={onClose}
title={
type === COLLECTION_ROLE.VIEWER
- ? t('ADD_VIEWERS')
- : t('ADD_COLLABORATORS')
+ ? t("ADD_VIEWERS")
+ : t("ADD_COLLABORATORS")
}
onRootClose={handleRootClose}
caption={collection.name}
@@ -105,15 +104,15 @@ export default function AddParticipant({
onClose={onClose}
callback={collectionShare}
optionsList={nonSharedEmails}
- placeholder={t('ENTER_EMAIL')}
+ placeholder={t("ENTER_EMAIL")}
fieldType="email"
buttonText={
type === COLLECTION_ROLE.VIEWER
- ? t('ADD_VIEWERS')
- : t('ADD_COLLABORATORS')
+ ? t("ADD_VIEWERS")
+ : t("ADD_COLLABORATORS")
}
submitButtonProps={{
- size: 'large',
+ size: "large",
sx: { mt: 1, mb: 2 },
}}
disableAutoFocus
diff --git a/apps/photos/src/components/Collections/CollectionShare/emailShare/AddParticipantForm.tsx b/apps/photos/src/components/Collections/CollectionShare/emailShare/AddParticipantForm.tsx
index f4e3cd639f..55daa1edcf 100644
--- a/apps/photos/src/components/Collections/CollectionShare/emailShare/AddParticipantForm.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/emailShare/AddParticipantForm.tsx
@@ -1,17 +1,17 @@
-import React, { useMemo, useState } from 'react';
-import { Formik, FormikHelpers } from 'formik';
-import * as Yup from 'yup';
-import SubmitButton from '@ente/shared/components/SubmitButton';
-import TextField from '@mui/material/TextField';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import { Button, FormHelperText, Stack } from '@mui/material';
-import { t } from 'i18next';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import MenuItemDivider from 'components/Menu/MenuItemDivider';
-import MenuSectionTitle from 'components/Menu/MenuSectionTitle';
-import Avatar from 'components/pages/gallery/Avatar';
-import DoneIcon from '@mui/icons-material/Done';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import SubmitButton from "@ente/shared/components/SubmitButton";
+import DoneIcon from "@mui/icons-material/Done";
+import { Button, FormHelperText, Stack } from "@mui/material";
+import TextField from "@mui/material/TextField";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import MenuItemDivider from "components/Menu/MenuItemDivider";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import MenuSectionTitle from "components/Menu/MenuSectionTitle";
+import Avatar from "components/pages/gallery/Avatar";
+import { Formik, FormikHelpers } from "formik";
+import { t } from "i18next";
+import { useMemo, useState } from "react";
+import * as Yup from "yup";
interface formValues {
inputValue: string;
@@ -19,7 +19,7 @@ interface formValues {
}
export interface AddParticipantFormProps {
callback: (props: { email?: string; emails?: string[] }) => Promise<void>;
- fieldType: 'text' | 'email' | 'password';
+ fieldType: "text" | "email" | "password";
placeholder: string;
buttonText: string;
submitButtonProps?: any;
@@ -44,11 +44,11 @@ export default function AddParticipantForm(props: AddParticipantFormProps) {
const submitForm = async (
values: formValues,
- { setFieldError, resetForm }: FormikHelpers<formValues>
+ { setFieldError, resetForm }: FormikHelpers<formValues>,
) => {
try {
SetLoading(true);
- if (values.inputValue !== '') {
+ if (values.inputValue !== "") {
await props.callback({ email: values.inputValue });
} else if (values.selectedOptions.length !== 0) {
await props.callback({ emails: values.selectedOptions });
@@ -57,38 +57,39 @@ export default function AddParticipantForm(props: AddParticipantFormProps) {
props.onClose();
resetForm();
} catch (e) {
- setFieldError('inputValue', e?.message);
+ setFieldError("inputValue", e?.message);
SetLoading(false);
}
};
const validationSchema = useMemo(() => {
switch (props.fieldType) {
- case 'text':
+ case "text":
return Yup.object().shape({
- inputValue: Yup.string().required(t('REQUIRED')),
+ inputValue: Yup.string().required(t("REQUIRED")),
});
- case 'email':
+ case "email":
return Yup.object().shape({
- inputValue: Yup.string().email(t('EMAIL_ERROR')),
+ inputValue: Yup.string().email(t("EMAIL_ERROR")),
});
}
}, [props.fieldType]);
const handleInputFieldClick = (setFieldValue) => {
- setFieldValue('selectedOptions', []);
+ setFieldValue("selectedOptions", []);
};
return (
<Formik<formValues>
initialValues={{
- inputValue: props.initialValue ?? '',
+ inputValue: props.initialValue ?? "",
selectedOptions: [],
}}
onSubmit={submitForm}
validationSchema={validationSchema}
validateOnChange={false}
- validateOnBlur={false}>
+ validateOnBlur={false}
+ >
{({
values,
errors,
@@ -97,17 +98,17 @@ export default function AddParticipantForm(props: AddParticipantFormProps) {
setFieldValue,
}) => (
<form noValidate onSubmit={handleSubmit}>
- <Stack spacing={'24px'} py={'20px'} px={'12px'}>
+ <Stack spacing={"24px"} py={"20px"} px={"12px"}>
{props.hiddenPreInput}
<Stack>
- <MenuSectionTitle title={t('ADD_NEW_EMAIL')} />
+ <MenuSectionTitle title={t("ADD_NEW_EMAIL")} />
<TextField
sx={{ marginTop: 0 }}
hiddenLabel={props.hiddenLabel}
fullWidth
type={props.fieldType}
id={props.fieldType}
- onChange={handleChange('inputValue')}
+ onChange={handleChange("inputValue")}
onClick={() =>
handleInputFieldClick(setFieldValue)
}
@@ -127,7 +128,7 @@ export default function AddParticipantForm(props: AddParticipantFormProps) {
{props.optionsList.length > 0 && (
<Stack>
<MenuSectionTitle
- title={t('OR_ADD_EXISTING')}
+ title={t("OR_ADD_EXISTING")}
/>
<MenuItemGroup>
{props.optionsList.map((item, index) => (
@@ -138,26 +139,26 @@ export default function AddParticipantForm(props: AddParticipantFormProps) {
onClick={() => {
if (
values.selectedOptions.includes(
- item
+ item,
)
) {
setFieldValue(
- 'selectedOptions',
+ "selectedOptions",
values.selectedOptions.filter(
(
- selectedOption
+ selectedOption,
) =>
selectedOption !==
- item
- )
+ item,
+ ),
);
} else {
setFieldValue(
- 'selectedOptions',
+ "selectedOptions",
[
...values.selectedOptions,
item,
- ]
+ ],
);
}
}}
@@ -167,7 +168,7 @@ export default function AddParticipantForm(props: AddParticipantFormProps) {
}
endIcon={
values.selectedOptions.includes(
- item
+ item,
) ? (
<DoneIcon />
) : null
@@ -184,43 +185,44 @@ export default function AddParticipantForm(props: AddParticipantFormProps) {
<FormHelperText
sx={{
- position: 'relative',
- top: errors.inputValue ? '-22px' : '0',
- float: 'right',
- padding: '0 8px',
- }}>
+ position: "relative",
+ top: errors.inputValue ? "-22px" : "0",
+ float: "right",
+ padding: "0 8px",
+ }}
+ >
{props.caption}
</FormHelperText>
{props.hiddenPostInput}
</Stack>
<FlexWrapper
- px={'8px'}
- justifyContent={'center'}
- flexWrap={
- props.blockButton ? 'wrap-reverse' : 'nowrap'
- }>
- <Stack direction={'column'} px={'8px'} width={'100%'}>
+ px={"8px"}
+ justifyContent={"center"}
+ flexWrap={props.blockButton ? "wrap-reverse" : "nowrap"}
+ >
+ <Stack direction={"column"} px={"8px"} width={"100%"}>
{props.secondaryButtonAction && (
<Button
onClick={props.secondaryButtonAction}
size="large"
color="secondary"
sx={{
- '&&&': {
+ "&&&": {
mt: !props.blockButton ? 2 : 0.5,
mb: !props.blockButton ? 4 : 0,
mr: !props.blockButton ? 1 : 0,
...buttonSx,
},
}}
- {...restSubmitButtonProps}>
- {t('CANCEL')}
+ {...restSubmitButtonProps}
+ >
+ {t("CANCEL")}
</Button>
)}
<SubmitButton
sx={{
- '&&&': {
+ "&&&": {
mt: 2,
...buttonSx,
},
diff --git a/apps/photos/src/components/Collections/CollectionShare/emailShare/ManageEmailShare.tsx b/apps/photos/src/components/Collections/CollectionShare/emailShare/ManageEmailShare.tsx
index fab3d09b85..a032a90694 100644
--- a/apps/photos/src/components/Collections/CollectionShare/emailShare/ManageEmailShare.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/emailShare/ManageEmailShare.tsx
@@ -1,26 +1,24 @@
-import { Stack } from '@mui/material';
-import { COLLECTION_ROLE, Collection, CollectionUser } from 'types/collection';
-import { EnteDrawer } from 'components/EnteDrawer';
-import { t } from 'i18next';
-import { DialogProps } from '@mui/material';
-import Titlebar from 'components/Titlebar';
-import { useContext, useState } from 'react';
-import { AppContext } from 'pages/_app';
-import { GalleryContext } from 'pages/gallery';
-import { unshareCollection } from 'services/collectionService';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import Avatar from 'components/pages/gallery/Avatar';
-import MenuSectionTitle from 'components/Menu/MenuSectionTitle';
-import AdminPanelSettingsIcon from '@mui/icons-material/AdminPanelSettings';
-import ModeEditIcon from '@mui/icons-material/ModeEdit';
-import MenuItemDivider from 'components/Menu/MenuItemDivider';
-import ChevronRightIcon from '@mui/icons-material/ChevronRight';
-import ManageParticipant from './ManageParticipant';
-import AddParticipant from './AddParticipant';
-import { useRef } from 'react';
-import Add from '@mui/icons-material/Add';
-import Photo from '@mui/icons-material/Photo';
+import Add from "@mui/icons-material/Add";
+import AdminPanelSettingsIcon from "@mui/icons-material/AdminPanelSettings";
+import ChevronRightIcon from "@mui/icons-material/ChevronRight";
+import ModeEditIcon from "@mui/icons-material/ModeEdit";
+import Photo from "@mui/icons-material/Photo";
+import { DialogProps, Stack } from "@mui/material";
+import { EnteDrawer } from "components/EnteDrawer";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import MenuItemDivider from "components/Menu/MenuItemDivider";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import MenuSectionTitle from "components/Menu/MenuSectionTitle";
+import Titlebar from "components/Titlebar";
+import Avatar from "components/pages/gallery/Avatar";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { GalleryContext } from "pages/gallery";
+import { useContext, useRef, useState } from "react";
+import { unshareCollection } from "services/collectionService";
+import { COLLECTION_ROLE, Collection, CollectionUser } from "types/collection";
+import AddParticipant from "./AddParticipant";
+import ManageParticipant from "./ManageParticipant";
interface Iprops {
collection: Collection;
@@ -66,8 +64,8 @@ export default function ManageEmailShare({
onClose();
onRootClose();
};
- const handleDrawerClose: DialogProps['onClose'] = (_, reason) => {
- if (reason === 'backdropClick') {
+ const handleDrawerClose: DialogProps["onClose"] = (_, reason) => {
+ if (reason === "backdropClick") {
handleRootClose();
} else {
onClose();
@@ -102,7 +100,7 @@ export default function ManageEmailShare({
const openManageParticipant = (email) => {
selectedParticipant.current = collection.sharees.find(
- (sharee) => sharee.email === email
+ (sharee) => sharee.email === email,
);
setManageParticipantView(true);
};
@@ -113,40 +111,40 @@ export default function ManageEmailShare({
return (
<>
<EnteDrawer anchor="right" open={open} onClose={handleDrawerClose}>
- <Stack spacing={'4px'} py={'12px'}>
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={onClose}
title={collection.name}
onRootClose={handleRootClose}
- caption={t('participants', {
+ caption={t("participants", {
count: peopleCount,
})}
/>
- <Stack py={'20px'} px={'12px'} spacing={'24px'}>
+ <Stack py={"20px"} px={"12px"} spacing={"24px"}>
<Stack>
<MenuSectionTitle
- title={t('OWNER')}
+ title={t("OWNER")}
icon={<AdminPanelSettingsIcon />}
/>
<MenuItemGroup>
<EnteMenuItem
fontWeight="normal"
onClick={() => {}}
- label={isOwner ? t('YOU') : ownerEmail}
+ label={isOwner ? t("YOU") : ownerEmail}
startIcon={<Avatar email={ownerEmail} />}
/>
</MenuItemGroup>
</Stack>
<Stack>
<MenuSectionTitle
- title={t('COLLABORATORS')}
+ title={t("COLLABORATORS")}
icon={<ModeEditIcon />}
/>
<MenuItemGroup>
{collaborators.map((item) => (
<>
<EnteMenuItem
- fontWeight={'normal'}
+ fontWeight={"normal"}
key={item}
onClick={() =>
openManageParticipant(item)
@@ -164,22 +162,22 @@ export default function ManageEmailShare({
onClick={openAddCollab}
label={
collaborators?.length
- ? t('ADD_MORE')
- : t('ADD_COLLABORATORS')
+ ? t("ADD_MORE")
+ : t("ADD_COLLABORATORS")
}
/>
</MenuItemGroup>
</Stack>
<Stack>
<MenuSectionTitle
- title={t('VIEWERS')}
+ title={t("VIEWERS")}
icon={<Photo />}
/>
<MenuItemGroup>
{viewers.map((item) => (
<>
<EnteMenuItem
- fontWeight={'normal'}
+ fontWeight={"normal"}
key={item}
onClick={() =>
openManageParticipant(item)
@@ -194,12 +192,12 @@ export default function ManageEmailShare({
))}
<EnteMenuItem
startIcon={<Add />}
- fontWeight={'bold'}
+ fontWeight={"bold"}
onClick={openAddViewer}
label={
viewers?.length
- ? t('ADD_MORE')
- : t('ADD_VIEWERS')
+ ? t("ADD_MORE")
+ : t("ADD_VIEWERS")
}
/>
</MenuItemGroup>
diff --git a/apps/photos/src/components/Collections/CollectionShare/emailShare/ManageParticipant.tsx b/apps/photos/src/components/Collections/CollectionShare/emailShare/ManageParticipant.tsx
index b66b040ae1..e47edd5915 100644
--- a/apps/photos/src/components/Collections/CollectionShare/emailShare/ManageParticipant.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/emailShare/ManageParticipant.tsx
@@ -1,23 +1,22 @@
-import { Stack, Typography } from '@mui/material';
-import React, { useContext } from 'react';
-import { Collection, CollectionUser } from 'types/collection';
-import { EnteDrawer } from 'components/EnteDrawer';
-import { t } from 'i18next';
-import { DialogProps } from '@mui/material';
-import Titlebar from 'components/Titlebar';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import ModeEditIcon from '@mui/icons-material/ModeEdit';
-import PhotoIcon from '@mui/icons-material/Photo';
-import MenuItemDivider from 'components/Menu/MenuItemDivider';
-import BlockIcon from '@mui/icons-material/Block';
-import DoneIcon from '@mui/icons-material/Done';
-import { handleSharingErrors } from 'utils/error/ui';
-import { logError } from '@ente/shared/sentry';
-import { shareCollection } from 'services/collectionService';
-import { GalleryContext } from 'pages/gallery';
-import { AppContext } from 'pages/_app';
-import { Trans } from 'react-i18next';
+import { logError } from "@ente/shared/sentry";
+import BlockIcon from "@mui/icons-material/Block";
+import DoneIcon from "@mui/icons-material/Done";
+import ModeEditIcon from "@mui/icons-material/ModeEdit";
+import PhotoIcon from "@mui/icons-material/Photo";
+import { DialogProps, Stack, Typography } from "@mui/material";
+import { EnteDrawer } from "components/EnteDrawer";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import MenuItemDivider from "components/Menu/MenuItemDivider";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import Titlebar from "components/Titlebar";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { GalleryContext } from "pages/gallery";
+import { useContext } from "react";
+import { Trans } from "react-i18next";
+import { shareCollection } from "services/collectionService";
+import { Collection, CollectionUser } from "types/collection";
+import { handleSharingErrors } from "utils/error/ui";
interface Iprops {
open: boolean;
@@ -39,8 +38,8 @@ export default function ManageParticipant({
const galleryContext = useContext(GalleryContext);
const appContext = useContext(AppContext);
- const handleDrawerClose: DialogProps['onClose'] = (_, reason) => {
- if (reason === 'backdropClick') {
+ const handleDrawerClose: DialogProps["onClose"] = (_, reason) => {
+ if (reason === "backdropClick") {
onRootClose();
} else {
onClose();
@@ -73,7 +72,7 @@ export default function ManageParticipant({
let contentText;
let buttonText;
- if (newRole === 'VIEWER') {
+ if (newRole === "VIEWER") {
contentText = (
<Trans
i18nKey="CHANGE_PERMISSIONS_TO_VIEWER"
@@ -83,31 +82,31 @@ export default function ManageParticipant({
/>
);
- buttonText = t('CONVERT_TO_VIEWER');
- } else if (newRole === 'COLLABORATOR') {
+ buttonText = t("CONVERT_TO_VIEWER");
+ } else if (newRole === "COLLABORATOR") {
contentText = t(`CHANGE_PERMISSIONS_TO_COLLABORATOR`, {
selectedEmail: selectedEmail,
});
- buttonText = t('CONVERT_TO_COLLABORATOR');
+ buttonText = t("CONVERT_TO_COLLABORATOR");
}
appContext.setDialogMessage({
- title: t('CHANGE_PERMISSION'),
+ title: t("CHANGE_PERMISSION"),
content: contentText,
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
proceed: {
text: buttonText,
action: () => {
updateCollectionRole(selectedEmail, newRole);
},
- variant: 'critical',
+ variant: "critical",
},
});
};
const removeParticipant = () => {
appContext.setDialogMessage({
- title: t('REMOVE_PARTICIPANT'),
+ title: t("REMOVE_PARTICIPANT"),
content: (
<Trans
i18nKey="REMOVE_PARTICIPANT_MESSAGE"
@@ -116,13 +115,13 @@ export default function ManageParticipant({
}}
/>
),
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
proceed: {
- text: t('CONFIRM_REMOVE'),
+ text: t("CONFIRM_REMOVE"),
action: () => {
handleClick();
},
- variant: 'critical',
+ variant: "critical",
},
});
};
@@ -134,44 +133,45 @@ export default function ManageParticipant({
return (
<>
<EnteDrawer anchor="right" open={open} onClose={handleDrawerClose}>
- <Stack spacing={'4px'} py={'12px'}>
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={onClose}
- title={t('MANAGE')}
+ title={t("MANAGE")}
onRootClose={onRootClose}
caption={selectedParticipant.email}
/>
- <Stack py={'20px'} px={'8px'} spacing={'32px'}>
+ <Stack py={"20px"} px={"8px"} spacing={"32px"}>
<Stack>
<Typography
color="text.muted"
variant="small"
- padding={1}>
- {t('ADDED_AS')}
+ padding={1}
+ >
+ {t("ADDED_AS")}
</Typography>
<MenuItemGroup>
<EnteMenuItem
fontWeight="normal"
- onClick={handleRoleChange('COLLABORATOR')}
- label={'Collaborator'}
+ onClick={handleRoleChange("COLLABORATOR")}
+ label={"Collaborator"}
startIcon={<ModeEditIcon />}
endIcon={
selectedParticipant.role ===
- 'COLLABORATOR' && <DoneIcon />
+ "COLLABORATOR" && <DoneIcon />
}
/>
<MenuItemDivider hasIcon />
<EnteMenuItem
fontWeight="normal"
- onClick={handleRoleChange('VIEWER')}
- label={'Viewer'}
+ onClick={handleRoleChange("VIEWER")}
+ label={"Viewer"}
startIcon={<PhotoIcon />}
endIcon={
selectedParticipant.role ===
- 'VIEWER' && <DoneIcon />
+ "VIEWER" && <DoneIcon />
}
/>
</MenuItemGroup>
@@ -179,16 +179,18 @@ export default function ManageParticipant({
<Typography
color="text.muted"
variant="small"
- padding={1}>
- {t('COLLABORATOR_RIGHTS')}
+ padding={1}
+ >
+ {t("COLLABORATOR_RIGHTS")}
</Typography>
- <Stack py={'30px'}>
+ <Stack py={"30px"}>
<Typography
color="text.muted"
variant="small"
- padding={1}>
- {t('REMOVE_PARTICIPANT_HEAD')}
+ padding={1}
+ >
+ {t("REMOVE_PARTICIPANT_HEAD")}
</Typography>
<MenuItemGroup>
@@ -196,7 +198,7 @@ export default function ManageParticipant({
color="critical"
fontWeight="normal"
onClick={removeParticipant}
- label={'Remove'}
+ label={"Remove"}
startIcon={<BlockIcon />}
/>
</MenuItemGroup>
diff --git a/apps/photos/src/components/Collections/CollectionShare/emailShare/index.tsx b/apps/photos/src/components/Collections/CollectionShare/emailShare/index.tsx
index 0f72ad6740..203e7c1f33 100644
--- a/apps/photos/src/components/Collections/CollectionShare/emailShare/index.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/emailShare/index.tsx
@@ -1,18 +1,18 @@
-import React, { useRef, useState } from 'react';
-import { COLLECTION_ROLE, Collection } from 'types/collection';
+import { useRef, useState } from "react";
+import { COLLECTION_ROLE, Collection } from "types/collection";
-import { Stack } from '@mui/material';
-import MenuSectionTitle from 'components/Menu/MenuSectionTitle';
-import { t } from 'i18next';
-import Workspaces from '@mui/icons-material/Workspaces';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import MenuItemDivider from 'components/Menu/MenuItemDivider';
-import AddIcon from '@mui/icons-material/Add';
-import AddParticipant from './AddParticipant';
-import ManageEmailShare from './ManageEmailShare';
-import AvatarGroup from 'components/pages/gallery/AvatarGroup';
-import ChevronRight from '@mui/icons-material/ChevronRight';
+import AddIcon from "@mui/icons-material/Add";
+import ChevronRight from "@mui/icons-material/ChevronRight";
+import Workspaces from "@mui/icons-material/Workspaces";
+import { Stack } from "@mui/material";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import MenuItemDivider from "components/Menu/MenuItemDivider";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import MenuSectionTitle from "components/Menu/MenuSectionTitle";
+import AvatarGroup from "components/pages/gallery/AvatarGroup";
+import { t } from "i18next";
+import AddParticipant from "./AddParticipant";
+import ManageEmailShare from "./ManageEmailShare";
export default function EmailShare({
collection,
@@ -48,7 +48,7 @@ export default function EmailShare({
<>
<Stack>
<MenuSectionTitle
- title={t('shared_with_people', {
+ title={t("shared_with_people", {
count: collection.sharees?.length ?? 0,
})}
icon={<Workspaces />}
@@ -57,7 +57,7 @@ export default function EmailShare({
{collection.sharees.length > 0 ? (
<>
<EnteMenuItem
- fontWeight={'normal'}
+ fontWeight={"normal"}
startIcon={
<AvatarGroup sharees={collection.sharees} />
}
@@ -75,13 +75,13 @@ export default function EmailShare({
<EnteMenuItem
startIcon={<AddIcon />}
onClick={openAddViewer}
- label={t('ADD_VIEWERS')}
+ label={t("ADD_VIEWERS")}
/>
<MenuItemDivider hasIcon />
<EnteMenuItem
startIcon={<AddIcon />}
onClick={openAddCollab}
- label={t('ADD_COLLABORATORS')}
+ label={t("ADD_COLLABORATORS")}
/>
</MenuItemGroup>
</Stack>
diff --git a/apps/photos/src/components/Collections/CollectionShare/index.tsx b/apps/photos/src/components/Collections/CollectionShare/index.tsx
index c2d3559cac..22de9b55e8 100644
--- a/apps/photos/src/components/Collections/CollectionShare/index.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/index.tsx
@@ -1,12 +1,12 @@
-import { Collection, CollectionSummary } from 'types/collection';
-import { EnteDrawer } from 'components/EnteDrawer';
-import PublicShare from './publicShare';
-import { t } from 'i18next';
-import { DialogProps, Stack } from '@mui/material';
-import Titlebar from 'components/Titlebar';
-import EmailShare from './emailShare';
-import { CollectionSummaryType } from 'constants/collection';
-import SharingDetails from './sharingDetails';
+import { DialogProps, Stack } from "@mui/material";
+import { EnteDrawer } from "components/EnteDrawer";
+import Titlebar from "components/Titlebar";
+import { CollectionSummaryType } from "constants/collection";
+import { t } from "i18next";
+import { Collection, CollectionSummary } from "types/collection";
+import EmailShare from "./emailShare";
+import PublicShare from "./publicShare";
+import SharingDetails from "./sharingDetails";
interface Props {
open: boolean;
@@ -19,8 +19,8 @@ function CollectionShare({ collectionSummary, ...props }: Props) {
const handleRootClose = () => {
props.onClose();
};
- const handleDrawerClose: DialogProps['onClose'] = (_, reason) => {
- if (reason === 'backdropClick') {
+ const handleDrawerClose: DialogProps["onClose"] = (_, reason) => {
+ if (reason === "backdropClick") {
handleRootClose();
} else {
props.onClose();
@@ -38,23 +38,24 @@ function CollectionShare({ collectionSummary, ...props }: Props) {
onClose={handleDrawerClose}
slotProps={{
backdrop: {
- sx: { '&&&': { backgroundColor: 'transparent' } },
+ sx: { "&&&": { backgroundColor: "transparent" } },
},
- }}>
- <Stack spacing={'4px'} py={'12px'}>
+ }}
+ >
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={props.onClose}
title={
type ===
CollectionSummaryType.incomingShareCollaborator ||
type === CollectionSummaryType.incomingShareViewer
- ? t('SHARING_DETAILS')
- : t('SHARE_COLLECTION')
+ ? t("SHARING_DETAILS")
+ : t("SHARE_COLLECTION")
}
onRootClose={handleRootClose}
caption={props.collection.name}
/>
- <Stack py={'20px'} px={'8px'} gap={'24px'}>
+ <Stack py={"20px"} px={"8px"} gap={"24px"}>
{type === CollectionSummaryType.incomingShareCollaborator ||
type === CollectionSummaryType.incomingShareViewer ? (
<SharingDetails
diff --git a/apps/photos/src/components/Collections/CollectionShare/publicShare/EnablePublicShareOptions.tsx b/apps/photos/src/components/Collections/CollectionShare/publicShare/EnablePublicShareOptions.tsx
index f1ce79b760..5d148769ba 100644
--- a/apps/photos/src/components/Collections/CollectionShare/publicShare/EnablePublicShareOptions.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/publicShare/EnablePublicShareOptions.tsx
@@ -1,25 +1,25 @@
-import { Stack, Typography } from '@mui/material';
-import { GalleryContext } from 'pages/gallery';
-import React, { useContext, useState } from 'react';
-import { t } from 'i18next';
+import DownloadSharp from "@mui/icons-material/DownloadSharp";
+import LinkIcon from "@mui/icons-material/Link";
+import PublicIcon from "@mui/icons-material/Public";
+import { Stack, Typography } from "@mui/material";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import MenuItemDivider from "components/Menu/MenuItemDivider";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import MenuSectionTitle from "components/Menu/MenuSectionTitle";
+import { t } from "i18next";
+import { GalleryContext } from "pages/gallery";
+import { useContext, useState } from "react";
import {
createShareableURL,
updateShareableURL,
-} from 'services/collectionService';
-import { Collection, PublicURL } from 'types/collection';
-import { handleSharingErrors } from 'utils/error/ui';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import PublicIcon from '@mui/icons-material/Public';
+} from "services/collectionService";
+import { Collection, PublicURL } from "types/collection";
+import { handleSharingErrors } from "utils/error/ui";
interface Iprops {
collection: Collection;
setPublicShareProp: (value: PublicURL) => void;
setCopyLinkModalView: (value: boolean) => void;
}
-import LinkIcon from '@mui/icons-material/Link';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import MenuSectionTitle from 'components/Menu/MenuSectionTitle';
-import MenuItemDivider from 'components/Menu/MenuItemDivider';
-import DownloadSharp from '@mui/icons-material/DownloadSharp';
export default function EnablePublicShareOptions({
collection,
@@ -68,30 +68,31 @@ export default function EnablePublicShareOptions({
return (
<Stack>
<MenuSectionTitle
- title={t('LINK_SHARE_TITLE')}
+ title={t("LINK_SHARE_TITLE")}
icon={<PublicIcon />}
/>
<MenuItemGroup>
<EnteMenuItem
- label={t('CREATE_PUBLIC_SHARING')}
+ label={t("CREATE_PUBLIC_SHARING")}
startIcon={<LinkIcon />}
onClick={createSharableURLHelper}
/>
<MenuItemDivider hasIcon />
<EnteMenuItem
- label={t('COLLECT_PHOTOS')}
+ label={t("COLLECT_PHOTOS")}
startIcon={<DownloadSharp />}
onClick={createCollectPhotoShareableURLHelper}
/>
</MenuItemGroup>
{sharableLinkError && (
<Typography
- textAlign={'center'}
+ textAlign={"center"}
variant="small"
sx={{
color: (theme) => theme.colors.danger.A700,
mt: 0.5,
- }}>
+ }}
+ >
{sharableLinkError}
</Typography>
)}
diff --git a/apps/photos/src/components/Collections/CollectionShare/publicShare/copyLinkModal.tsx b/apps/photos/src/components/Collections/CollectionShare/publicShare/copyLinkModal.tsx
index bba72f933f..1a7067cdb7 100644
--- a/apps/photos/src/components/Collections/CollectionShare/publicShare/copyLinkModal.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/publicShare/copyLinkModal.tsx
@@ -1,14 +1,14 @@
-import DialogBoxBase from '@ente/shared/components/DialogBox/base';
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import DialogBoxBase from "@ente/shared/components/DialogBox/base";
+import Check from "@mui/icons-material/Check";
import {
- DialogActions,
+ Box,
Button,
- Typography,
+ DialogActions,
DialogContent,
- Box,
-} from '@mui/material';
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import Check from '@mui/icons-material/Check';
-import { t } from 'i18next';
+ Typography,
+} from "@mui/material";
+import { t } from "i18next";
interface Iprops {
open: boolean;
onClose: () => void;
@@ -26,31 +26,33 @@ export default function CopyLinkModal({
open={open}
onClose={onClose}
disablePortal
- BackdropProps={{ sx: { position: 'absolute' } }}
- sx={{ position: 'absolute' }}
+ BackdropProps={{ sx: { position: "absolute" } }}
+ sx={{ position: "absolute" }}
PaperProps={{
sx: { p: 1 },
- }}>
+ }}
+ >
<DialogContent>
<VerticallyCentered>
- <Typography fontWeight={'bold'}>
- {t('PUBLIC_LINK_CREATED')}
+ <Typography fontWeight={"bold"}>
+ {t("PUBLIC_LINK_CREATED")}
</Typography>
<Box pt={2}>
- <Check sx={{ fontSize: '48px' }} />
+ <Check sx={{ fontSize: "48px" }} />
</Box>
</VerticallyCentered>
</DialogContent>
<DialogActions>
- <Button onClick={handleCancel} color="secondary" size={'large'}>
- {t('DONE')}
+ <Button onClick={handleCancel} color="secondary" size={"large"}>
+ {t("DONE")}
</Button>
<Button
onClick={copyToClipboardHelper}
- size={'large'}
+ size={"large"}
color="primary"
- autoFocus>
- {t('COPY_LINK')}
+ autoFocus
+ >
+ {t("COPY_LINK")}
</Button>
</DialogActions>
</DialogBoxBase>
diff --git a/apps/photos/src/components/Collections/CollectionShare/publicShare/index.tsx b/apps/photos/src/components/Collections/CollectionShare/publicShare/index.tsx
index d8bad69392..e71f482cf6 100644
--- a/apps/photos/src/components/Collections/CollectionShare/publicShare/index.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/publicShare/index.tsx
@@ -1,9 +1,9 @@
-import React, { useEffect, useState } from 'react';
-import { Collection, PublicURL } from 'types/collection';
-import { appendCollectionKeyToShareURL } from 'utils/collection';
-import EnablePublicShareOptions from './EnablePublicShareOptions';
-import CopyLinkModal from './copyLinkModal';
-import ManagePublicShare from './managePublicShare';
+import { useEffect, useState } from "react";
+import { Collection, PublicURL } from "types/collection";
+import { appendCollectionKeyToShareURL } from "utils/collection";
+import EnablePublicShareOptions from "./EnablePublicShareOptions";
+import CopyLinkModal from "./copyLinkModal";
+import ManagePublicShare from "./managePublicShare";
export default function PublicShare({
collection,
@@ -26,7 +26,7 @@ export default function PublicShare({
if (publicShareProp) {
const url = appendCollectionKeyToShareURL(
publicShareProp.url,
- collection.key
+ collection.key,
);
setPublicShareUrl(url);
} else {
diff --git a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/deviceLimit.tsx b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/deviceLimit.tsx
index 6e33a90f34..1576a6f3a2 100644
--- a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/deviceLimit.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/deviceLimit.tsx
@@ -1,14 +1,14 @@
-import ChevronRight from '@mui/icons-material/ChevronRight';
-import { DialogProps, Stack } from '@mui/material';
-import { EnteDrawer } from 'components/EnteDrawer';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import Titlebar from 'components/Titlebar';
-import { t } from 'i18next';
-import React, { useMemo, useState } from 'react';
-import { Collection, PublicURL, UpdatePublicURL } from 'types/collection';
-import { getDeviceLimitOptions } from 'utils/collection';
-import MenuItemDivider from 'components/Menu/MenuItemDivider';
+import ChevronRight from "@mui/icons-material/ChevronRight";
+import { DialogProps, Stack } from "@mui/material";
+import { EnteDrawer } from "components/EnteDrawer";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import MenuItemDivider from "components/Menu/MenuItemDivider";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import Titlebar from "components/Titlebar";
+import { t } from "i18next";
+import { useMemo, useState } from "react";
+import { Collection, PublicURL, UpdatePublicURL } from "types/collection";
+import { getDeviceLimitOptions } from "utils/collection";
interface Iprops {
publicShareProp: PublicURL;
@@ -43,8 +43,8 @@ export function ManageDeviceLimit({
setIsChangeDeviceLimitVisible(false);
};
- const handleDrawerClose: DialogProps['onClose'] = (_, reason) => {
- if (reason === 'backdropClick') {
+ const handleDrawerClose: DialogProps["onClose"] = (_, reason) => {
+ if (reason === "backdropClick") {
onRootClose();
} else {
closeDeviceLimitChangeModal();
@@ -54,11 +54,11 @@ export function ManageDeviceLimit({
return (
<>
<EnteMenuItem
- label={t('LINK_DEVICE_LIMIT')}
+ label={t("LINK_DEVICE_LIMIT")}
variant="captioned"
subText={
publicShareProp.deviceLimit === 0
- ? t('NO_DEVICE_LIMIT')
+ ? t("NO_DEVICE_LIMIT")
: publicShareProp.deviceLimit.toString()
}
onClick={openDeviceLimitChangeModalView}
@@ -68,14 +68,15 @@ export function ManageDeviceLimit({
<EnteDrawer
anchor="right"
open={isChangeDeviceLimitVisible}
- onClose={handleDrawerClose}>
- <Stack spacing={'4px'} py={'12px'}>
+ onClose={handleDrawerClose}
+ >
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={closeDeviceLimitChangeModal}
- title={t('LINK_DEVICE_LIMIT')}
+ title={t("LINK_DEVICE_LIMIT")}
onRootClose={onRootClose}
/>
- <Stack py={'20px'} px={'8px'} spacing={'32px'}>
+ <Stack py={"20px"} px={"8px"} spacing={"32px"}>
<MenuItemGroup>
{deviceLimitOptions.map((item, index) => (
<>
@@ -83,7 +84,7 @@ export function ManageDeviceLimit({
fontWeight="normal"
key={item.label}
onClick={changeDeviceLimitValue(
- item.value
+ item.value,
)}
label={item.label}
/>
diff --git a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/downloadAccess.tsx b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/downloadAccess.tsx
index e2a54c6a8d..9636874480 100644
--- a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/downloadAccess.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/downloadAccess.tsx
@@ -1,9 +1,9 @@
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import { AppContext } from 'pages/_app';
-import React, { useContext } from 'react';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
-import { PublicURL, Collection, UpdatePublicURL } from 'types/collection';
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
+import { Trans } from "react-i18next";
+import { Collection, PublicURL, UpdatePublicURL } from "types/collection";
interface Iprops {
publicShareProp: PublicURL;
collection: Collection;
@@ -30,17 +30,17 @@ export function ManageDownloadAccess({
const disableFileDownload = () => {
appContext.setDialogMessage({
- title: t('DISABLE_FILE_DOWNLOAD'),
- content: <Trans i18nKey={'DISABLE_FILE_DOWNLOAD_MESSAGE'} />,
- close: { text: t('CANCEL') },
+ title: t("DISABLE_FILE_DOWNLOAD"),
+ content: <Trans i18nKey={"DISABLE_FILE_DOWNLOAD_MESSAGE"} />,
+ close: { text: t("CANCEL") },
proceed: {
- text: t('DISABLE'),
+ text: t("DISABLE"),
action: () =>
updatePublicShareURLHelper({
collectionID: collection.id,
enableDownload: false,
}),
- variant: 'critical',
+ variant: "critical",
},
});
};
@@ -49,7 +49,7 @@ export function ManageDownloadAccess({
checked={publicShareProp?.enableDownload ?? true}
onClick={handleFileDownloadSetting}
variant="toggle"
- label={t('FILE_DOWNLOAD')}
+ label={t("FILE_DOWNLOAD")}
/>
);
}
diff --git a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/index.tsx b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/index.tsx
index 48a6b3d623..a4ba9ec914 100644
--- a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/index.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/index.tsx
@@ -1,27 +1,26 @@
-import { ManageLinkPassword } from './linkPassword';
-import { ManageDeviceLimit } from './deviceLimit';
-import { ManageLinkExpiry } from './linkExpiry';
-import { Stack, Typography } from '@mui/material';
-import { GalleryContext } from 'pages/gallery';
-import React, { useContext, useState } from 'react';
+import ContentCopyIcon from "@mui/icons-material/ContentCopy";
+import RemoveCircleOutline from "@mui/icons-material/RemoveCircleOutline";
+import { DialogProps, Stack, Typography } from "@mui/material";
+import { EnteDrawer } from "components/EnteDrawer";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import MenuItemDivider from "components/Menu/MenuItemDivider";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import Titlebar from "components/Titlebar";
+import { t } from "i18next";
+import { GalleryContext } from "pages/gallery";
+import { useContext, useState } from "react";
import {
deleteShareableURL,
updateShareableURL,
-} from 'services/collectionService';
-import { Collection, PublicURL, UpdatePublicURL } from 'types/collection';
-import { ManageDownloadAccess } from './downloadAccess';
-import { handleSharingErrors } from 'utils/error/ui';
-import { SetPublicShareProp } from 'types/publicCollection';
-import { ManagePublicCollect } from './publicCollect';
-import { EnteDrawer } from 'components/EnteDrawer';
-import RemoveCircleOutline from '@mui/icons-material/RemoveCircleOutline';
-import ContentCopyIcon from '@mui/icons-material/ContentCopy';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import { t } from 'i18next';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import { DialogProps } from '@mui/material';
-import Titlebar from 'components/Titlebar';
-import MenuItemDivider from 'components/Menu/MenuItemDivider';
+} from "services/collectionService";
+import { Collection, PublicURL, UpdatePublicURL } from "types/collection";
+import { SetPublicShareProp } from "types/publicCollection";
+import { handleSharingErrors } from "utils/error/ui";
+import { ManageDeviceLimit } from "./deviceLimit";
+import { ManageDownloadAccess } from "./downloadAccess";
+import { ManageLinkExpiry } from "./linkExpiry";
+import { ManageLinkPassword } from "./linkPassword";
+import { ManagePublicCollect } from "./publicCollect";
interface Iprops {
publicShareProp: PublicURL;
@@ -42,8 +41,8 @@ export default function ManagePublicShareOptions({
onRootClose,
publicShareUrl,
}: Iprops) {
- const handleDrawerClose: DialogProps['onClose'] = (_, reason) => {
- if (reason === 'backdropClick') {
+ const handleDrawerClose: DialogProps["onClose"] = (_, reason) => {
+ if (reason === "backdropClick") {
onRootClose();
} else {
onClose();
@@ -86,13 +85,13 @@ export default function ManagePublicShareOptions({
return (
<>
<EnteDrawer anchor="right" open={open} onClose={handleDrawerClose}>
- <Stack spacing={'4px'} py={'12px'}>
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={onClose}
- title={t('SHARE_COLLECTION')}
+ title={t("SHARE_COLLECTION")}
onRootClose={onRootClose}
/>
- <Stack py={'20px'} px={'8px'} spacing={'32px'}>
+ <Stack py={"20px"} px={"8px"} spacing={"32px"}>
<Stack spacing={3}>
<ManagePublicCollect
collection={collection}
@@ -139,9 +138,9 @@ export default function ManagePublicShareOptions({
<EnteMenuItem
startIcon={<ContentCopyIcon />}
onClick={copyToClipboardHelper(
- publicShareUrl
+ publicShareUrl,
)}
- label={t('COPY_LINK')}
+ label={t("COPY_LINK")}
/>
</MenuItemGroup>
<MenuItemGroup>
@@ -149,18 +148,19 @@ export default function ManagePublicShareOptions({
color="critical"
startIcon={<RemoveCircleOutline />}
onClick={disablePublicSharing}
- label={t('REMOVE_LINK')}
+ label={t("REMOVE_LINK")}
/>
</MenuItemGroup>
</Stack>
{sharableLinkError && (
<Typography
- textAlign={'center'}
+ textAlign={"center"}
variant="small"
sx={{
color: (theme) => theme.colors.danger.A700,
mt: 0.5,
- }}>
+ }}
+ >
{sharableLinkError}
</Typography>
)}
diff --git a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/linkExpiry.tsx b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/linkExpiry.tsx
index 6ad2fabefe..1ea31c8512 100644
--- a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/linkExpiry.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/linkExpiry.tsx
@@ -1,16 +1,16 @@
-import ChevronRight from '@mui/icons-material/ChevronRight';
-import { DialogProps, Stack } from '@mui/material';
-import { EnteDrawer } from 'components/EnteDrawer';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import React, { useMemo, useState } from 'react';
-import { PublicURL, Collection, UpdatePublicURL } from 'types/collection';
-import { shareExpiryOptions } from 'utils/collection';
-import { t } from 'i18next';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import { formatDateTime } from '@ente/shared/time/format';
-import Titlebar from 'components/Titlebar';
-import MenuItemDivider from 'components/Menu/MenuItemDivider';
-import { isLinkExpired } from '../managePublicShare';
+import { formatDateTime } from "@ente/shared/time/format";
+import ChevronRight from "@mui/icons-material/ChevronRight";
+import { DialogProps, Stack } from "@mui/material";
+import { EnteDrawer } from "components/EnteDrawer";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import MenuItemDivider from "components/Menu/MenuItemDivider";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import Titlebar from "components/Titlebar";
+import { t } from "i18next";
+import { useMemo, useState } from "react";
+import { Collection, PublicURL, UpdatePublicURL } from "types/collection";
+import { shareExpiryOptions } from "utils/collection";
+import { isLinkExpired } from "../managePublicShare";
interface Iprops {
publicShareProp: PublicURL;
@@ -49,8 +49,8 @@ export function ManageLinkExpiry({
setShareExpiryOptionsModalView(false);
};
- const handleDrawerClose: DialogProps['onClose'] = (_, reason) => {
- if (reason === 'backdropClick') {
+ const handleDrawerClose: DialogProps["onClose"] = (_, reason) => {
+ if (reason === "backdropClick") {
onRootClose();
} else {
closeShareExpiryOptionsModalView();
@@ -64,34 +64,35 @@ export function ManageLinkExpiry({
onClick={openShareExpiryOptionsModalView}
endIcon={<ChevronRight />}
variant="captioned"
- label={t('LINK_EXPIRY')}
+ label={t("LINK_EXPIRY")}
color={
isLinkExpired(publicShareProp?.validTill)
- ? 'critical'
- : 'primary'
+ ? "critical"
+ : "primary"
}
subText={
isLinkExpired(publicShareProp?.validTill)
- ? t('LINK_EXPIRED')
+ ? t("LINK_EXPIRED")
: publicShareProp?.validTill
? formatDateTime(
- publicShareProp?.validTill / 1000
+ publicShareProp?.validTill / 1000,
)
- : t('NEVER')
+ : t("NEVER")
}
/>
</MenuItemGroup>
<EnteDrawer
anchor="right"
open={shareExpiryOptionsModalView}
- onClose={handleDrawerClose}>
- <Stack spacing={'4px'} py={'12px'}>
+ onClose={handleDrawerClose}
+ >
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={closeShareExpiryOptionsModalView}
- title={t('LINK_EXPIRY')}
+ title={t("LINK_EXPIRY")}
onRootClose={onRootClose}
/>
- <Stack py={'20px'} px={'8px'} spacing={'32px'}>
+ <Stack py={"20px"} px={"8px"} spacing={"32px"}>
<MenuItemGroup>
{shareExpireOption.map((item, index) => (
<>
@@ -99,7 +100,7 @@ export function ManageLinkExpiry({
fontWeight="normal"
key={item.value()}
onClick={changeShareExpiryValue(
- item.value()
+ item.value(),
)}
label={item.label}
/>
diff --git a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/linkPassword/index.tsx b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/linkPassword/index.tsx
index f47d435b8e..2ef311c96f 100644
--- a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/linkPassword/index.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/linkPassword/index.tsx
@@ -1,9 +1,9 @@
-import { AppContext } from 'pages/_app';
-import React, { useContext, useState } from 'react';
-import { PublicURL, Collection, UpdatePublicURL } from 'types/collection';
-import { PublicLinkSetPassword } from './setPassword';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import { t } from 'i18next';
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext, useState } from "react";
+import { Collection, PublicURL, UpdatePublicURL } from "types/collection";
+import { PublicLinkSetPassword } from "./setPassword";
interface Iprops {
publicShareProp: PublicURL;
@@ -31,17 +31,17 @@ export function ManageLinkPassword({
const confirmDisablePublicUrlPassword = async () => {
appContext.setDialogMessage({
- title: t('DISABLE_PASSWORD'),
- content: t('DISABLE_PASSWORD_MESSAGE'),
- close: { text: t('CANCEL') },
+ title: t("DISABLE_PASSWORD"),
+ content: t("DISABLE_PASSWORD_MESSAGE"),
+ close: { text: t("CANCEL") },
proceed: {
- text: t('DISABLE'),
+ text: t("DISABLE"),
action: () =>
updatePublicShareURLHelper({
collectionID: collection.id,
disablePassword: true,
}),
- variant: 'critical',
+ variant: "critical",
},
});
};
@@ -49,7 +49,7 @@ export function ManageLinkPassword({
return (
<>
<EnteMenuItem
- label={t('LINK_PASSWORD_LOCK')}
+ label={t("LINK_PASSWORD_LOCK")}
onClick={handlePasswordChangeSetting}
checked={!!publicShareProp?.passwordEnabled}
variant="toggle"
diff --git a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/linkPassword/setPassword.tsx b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/linkPassword/setPassword.tsx
index ed165bdbae..349e41d7bf 100644
--- a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/linkPassword/setPassword.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/linkPassword/setPassword.tsx
@@ -1,10 +1,9 @@
-import { Dialog, Stack, Typography } from '@mui/material';
import SingleInputForm, {
SingleInputFormProps,
-} from '@ente/shared/components/SingleInputForm';
-import React from 'react';
-import { t } from 'i18next';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
+} from "@ente/shared/components/SingleInputForm";
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { Dialog, Stack, Typography } from "@mui/material";
+import { t } from "i18next";
export function PublicLinkSetPassword({
open,
@@ -14,16 +13,16 @@ export function PublicLinkSetPassword({
updatePublicShareURLHelper,
setChangePasswordView,
}) {
- const savePassword: SingleInputFormProps['callback'] = async (
+ const savePassword: SingleInputFormProps["callback"] = async (
passphrase,
- setFieldError
+ setFieldError,
) => {
if (passphrase && passphrase.trim().length >= 1) {
await enablePublicUrlPassword(passphrase);
setChangePasswordView(false);
publicShareProp.passwordEnabled = true;
} else {
- setFieldError('can not be empty');
+ setFieldError("can not be empty");
}
};
@@ -45,17 +44,18 @@ export function PublicLinkSetPassword({
open={open}
onClose={onClose}
disablePortal
- BackdropProps={{ sx: { position: 'absolute' } }}
- sx={{ position: 'absolute' }}
- PaperProps={{ sx: { p: 1 } }}>
+ BackdropProps={{ sx: { position: "absolute" } }}
+ sx={{ position: "absolute" }}
+ PaperProps={{ sx: { p: 1 } }}
+ >
<Stack spacing={3} p={1.5}>
- <Typography variant="h3" px={1} py={0.5} fontWeight={'bold'}>
- {t('PASSWORD_LOCK')}
+ <Typography variant="h3" px={1} py={0.5} fontWeight={"bold"}>
+ {t("PASSWORD_LOCK")}
</Typography>
<SingleInputForm
callback={savePassword}
- placeholder={t('RETURN_PASSPHRASE_HINT')}
- buttonText={t('LOCK')}
+ placeholder={t("RETURN_PASSPHRASE_HINT")}
+ buttonText={t("LOCK")}
fieldType="password"
secondaryButtonAction={onClose}
submitButtonProps={{ sx: { mt: 1, mb: 2 } }}
diff --git a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/publicCollect.tsx b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/publicCollect.tsx
index b663e94f39..4216189cbc 100644
--- a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/publicCollect.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/publicCollect.tsx
@@ -1,10 +1,9 @@
-import { Stack } from '@mui/material';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import React from 'react';
-import { t } from 'i18next';
-import { PublicURL, Collection, UpdatePublicURL } from 'types/collection';
-import MenuSectionTitle from 'components/Menu/MenuSectionTitle';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
+import { Stack } from "@mui/material";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import MenuSectionTitle from "components/Menu/MenuSectionTitle";
+import { t } from "i18next";
+import { Collection, PublicURL, UpdatePublicURL } from "types/collection";
interface Iprops {
publicShareProp: PublicURL;
@@ -31,10 +30,10 @@ export function ManagePublicCollect({
onClick={handleFileDownloadSetting}
variant="toggle"
checked={publicShareProp?.enableCollect}
- label={t('PUBLIC_COLLECT')}
+ label={t("PUBLIC_COLLECT")}
/>
</MenuItemGroup>
- <MenuSectionTitle title={t('PUBLIC_COLLECT_SUBTEXT')} />
+ <MenuSectionTitle title={t("PUBLIC_COLLECT_SUBTEXT")} />
</Stack>
);
}
diff --git a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/selectComponents/LabelWithDivider.tsx b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/selectComponents/LabelWithDivider.tsx
index f7d9b6b73e..c76d2ed512 100644
--- a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/selectComponents/LabelWithDivider.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/selectComponents/LabelWithDivider.tsx
@@ -1,5 +1,4 @@
-import React from 'react';
-import { Box, Typography, Divider } from '@mui/material';
+import { Box, Divider, Typography } from "@mui/material";
export function LabelWithDivider({ data }) {
return (
@@ -7,7 +6,7 @@ export function LabelWithDivider({ data }) {
<Box className="main" px={3} py={1}>
<Typography>{data.label}</Typography>
</Box>
- <Divider sx={{ borderColor: 'stroke.fainter' }} />
+ <Divider sx={{ borderColor: "stroke.fainter" }} />
</>
);
}
diff --git a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/selectComponents/OptionWithDivider.tsx b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/selectComponents/OptionWithDivider.tsx
index eed09d4f29..cc147cc91e 100644
--- a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/selectComponents/OptionWithDivider.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/selectComponents/OptionWithDivider.tsx
@@ -1,6 +1,5 @@
-import React from 'react';
-import { LabelWithDivider } from './LabelWithDivider';
-import { components } from 'react-select';
+import { components } from "react-select";
+import { LabelWithDivider } from "./LabelWithDivider";
const { Option } = components;
diff --git a/apps/photos/src/components/Collections/CollectionShare/publicShare/managePublicShare.tsx b/apps/photos/src/components/Collections/CollectionShare/publicShare/managePublicShare.tsx
index 40b1d70d1c..df39a5135f 100644
--- a/apps/photos/src/components/Collections/CollectionShare/publicShare/managePublicShare.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/publicShare/managePublicShare.tsx
@@ -1,17 +1,17 @@
-import { Stack, Typography } from '@mui/material';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import MenuItemDivider from 'components/Menu/MenuItemDivider';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import { Collection, PublicURL } from 'types/collection';
-import ManagePublicShareOptions from './manage';
-import PublicIcon from '@mui/icons-material/Public';
-import ContentCopyIcon from '@mui/icons-material/ContentCopyOutlined';
-import ChevronRightIcon from '@mui/icons-material/ChevronRight';
-import { SetPublicShareProp } from 'types/publicCollection';
-import LinkIcon from '@mui/icons-material/Link';
-import { useState } from 'react';
-import { t } from 'i18next';
-import ErrorOutlineIcon from '@mui/icons-material/ErrorOutline';
+import ChevronRightIcon from "@mui/icons-material/ChevronRight";
+import ContentCopyIcon from "@mui/icons-material/ContentCopyOutlined";
+import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline";
+import LinkIcon from "@mui/icons-material/Link";
+import PublicIcon from "@mui/icons-material/Public";
+import { Stack, Typography } from "@mui/material";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import MenuItemDivider from "components/Menu/MenuItemDivider";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import { t } from "i18next";
+import { useState } from "react";
+import { Collection, PublicURL } from "types/collection";
+import { SetPublicShareProp } from "types/publicCollection";
+import ManagePublicShareOptions from "./manage";
export const isLinkExpired = (validTill: number) => {
return validTill && validTill < Date.now() * 1000;
@@ -41,7 +41,7 @@ export default function ManagePublicShare({
<Stack>
<Typography color="text.muted" variant="small" padding={1}>
<PublicIcon style={{ fontSize: 17, marginRight: 8 }} />
- {t('PUBLIC_LINK_ENABLED')}
+ {t("PUBLIC_LINK_ENABLED")}
</Typography>
<MenuItemGroup>
{isLinkExpired(publicShareProp.validTill) ? (
@@ -50,14 +50,14 @@ export default function ManagePublicShare({
startIcon={<ErrorOutlineIcon />}
color="critical"
onClick={openManageShare}
- label={t('LINK_EXPIRED')}
+ label={t("LINK_EXPIRED")}
/>
) : (
<EnteMenuItem
startIcon={<ContentCopyIcon />}
onClick={copyToClipboardHelper}
disabled={isLinkExpired(publicShareProp.validTill)}
- label={t('COPY_LINK')}
+ label={t("COPY_LINK")}
/>
)}
@@ -66,7 +66,7 @@ export default function ManagePublicShare({
startIcon={<LinkIcon />}
endIcon={<ChevronRightIcon />}
onClick={openManageShare}
- label={t('MANAGE_LINK')}
+ label={t("MANAGE_LINK")}
/>
</MenuItemGroup>
</Stack>
diff --git a/apps/photos/src/components/Collections/CollectionShare/publicShare/switch.tsx b/apps/photos/src/components/Collections/CollectionShare/publicShare/switch.tsx
index 535ad175e2..bb738a9e9b 100644
--- a/apps/photos/src/components/Collections/CollectionShare/publicShare/switch.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/publicShare/switch.tsx
@@ -1,6 +1,4 @@
-import React from 'react';
-import { SwitchProps, Switch } from '@mui/material';
-import { styled } from '@mui/material';
+import { Switch, SwitchProps, styled } from "@mui/material";
const PublicShareSwitch = styled((props: SwitchProps) => (
<Switch
focusVisibleClassName=".Mui-focusVisible"
@@ -11,50 +9,50 @@ const PublicShareSwitch = styled((props: SwitchProps) => (
width: 40,
height: 24,
padding: 0,
- '& .MuiSwitch-switchBase': {
+ "& .MuiSwitch-switchBase": {
padding: 0,
margin: 2,
- transitionDuration: '300ms',
- '&.Mui-checked': {
- transform: 'translateX(16px)',
- color: '#fff',
- '& + .MuiSwitch-track': {
+ transitionDuration: "300ms",
+ "&.Mui-checked": {
+ transform: "translateX(16px)",
+ color: "#fff",
+ "& + .MuiSwitch-track": {
backgroundColor:
- theme.palette.mode === 'dark' ? '#2ECA45' : '#65C466',
+ theme.palette.mode === "dark" ? "#2ECA45" : "#65C466",
opacity: 1,
border: 0,
},
- '&.Mui-disabled + .MuiSwitch-track': {
+ "&.Mui-disabled + .MuiSwitch-track": {
opacity: 0.5,
},
},
- '&.Mui-focusVisible .MuiSwitch-thumb': {
- color: '#33cf4d',
- border: '6px solid #fff',
+ "&.Mui-focusVisible .MuiSwitch-thumb": {
+ color: "#33cf4d",
+ border: "6px solid #fff",
},
- '&.Mui-disabled .MuiSwitch-thumb': {
+ "&.Mui-disabled .MuiSwitch-thumb": {
color:
- theme.palette.mode === 'light'
+ theme.palette.mode === "light"
? theme.palette.grey[100]
: theme.palette.grey[600],
},
- '&.Mui-disabled + .MuiSwitch-track': {
- opacity: theme.palette.mode === 'light' ? 0.7 : 0.3,
+ "&.Mui-disabled + .MuiSwitch-track": {
+ opacity: theme.palette.mode === "light" ? 0.7 : 0.3,
},
},
- '& .MuiSwitch-thumb': {
- boxSizing: 'border-box',
+ "& .MuiSwitch-thumb": {
+ boxSizing: "border-box",
width: 20,
height: 20,
},
- '& .MuiSwitch-track': {
+ "& .MuiSwitch-track": {
borderRadius: 22 / 2,
backgroundColor:
- theme.palette.mode === 'light'
- ? '#E9E9EA'
+ theme.palette.mode === "light"
+ ? "#E9E9EA"
: theme.colors.fill.muted,
opacity: 1,
- transition: theme.transitions.create(['background-color'], {
+ transition: theme.transitions.create(["background-color"], {
duration: 500,
}),
},
diff --git a/apps/photos/src/components/Collections/CollectionShare/sharingDetails.tsx b/apps/photos/src/components/Collections/CollectionShare/sharingDetails.tsx
index 4ffb23203c..9fcf289b4f 100644
--- a/apps/photos/src/components/Collections/CollectionShare/sharingDetails.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/sharingDetails.tsx
@@ -1,17 +1,17 @@
-import { Stack } from '@mui/material';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import MenuItemDivider from 'components/Menu/MenuItemDivider';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import MenuSectionTitle from 'components/Menu/MenuSectionTitle';
-import { t } from 'i18next';
-import AdminPanelSettingsIcon from '@mui/icons-material/AdminPanelSettings';
-import { COLLECTION_ROLE } from 'types/collection';
-import { GalleryContext } from 'pages/gallery';
-import { useContext } from 'react';
-import Avatar from 'components/pages/gallery/Avatar';
-import ModeEditIcon from '@mui/icons-material/ModeEdit';
-import { CollectionSummaryType } from 'constants/collection';
-import Photo from '@mui/icons-material/Photo';
+import AdminPanelSettingsIcon from "@mui/icons-material/AdminPanelSettings";
+import ModeEditIcon from "@mui/icons-material/ModeEdit";
+import Photo from "@mui/icons-material/Photo";
+import { Stack } from "@mui/material";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import MenuItemDivider from "components/Menu/MenuItemDivider";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import MenuSectionTitle from "components/Menu/MenuSectionTitle";
+import Avatar from "components/pages/gallery/Avatar";
+import { CollectionSummaryType } from "constants/collection";
+import { t } from "i18next";
+import { GalleryContext } from "pages/gallery";
+import { useContext } from "react";
+import { COLLECTION_ROLE } from "types/collection";
export default function SharingDetails({ collection, type }) {
const galleryContext = useContext(GalleryContext);
@@ -38,14 +38,14 @@ export default function SharingDetails({ collection, type }) {
<>
<Stack>
<MenuSectionTitle
- title={t('OWNER')}
+ title={t("OWNER")}
icon={<AdminPanelSettingsIcon />}
/>
<MenuItemGroup>
<EnteMenuItem
fontWeight="normal"
onClick={() => {}}
- label={isOwner ? t('YOU') : ownerEmail}
+ label={isOwner ? t("YOU") : ownerEmail}
startIcon={<Avatar email={ownerEmail} />}
/>
</MenuItemGroup>
@@ -54,7 +54,7 @@ export default function SharingDetails({ collection, type }) {
collaborators?.length > 0 && (
<Stack>
<MenuSectionTitle
- title={t('COLLABORATORS')}
+ title={t("COLLABORATORS")}
icon={<ModeEditIcon />}
/>
<MenuItemGroup>
@@ -64,7 +64,7 @@ export default function SharingDetails({ collection, type }) {
fontWeight="normal"
key={item}
onClick={() => {}}
- label={isMe(item) ? t('YOU') : item}
+ label={isMe(item) ? t("YOU") : item}
startIcon={<Avatar email={item} />}
/>
{index !== collaborators.length - 1 && (
@@ -77,7 +77,7 @@ export default function SharingDetails({ collection, type }) {
)}
{viewers?.length > 0 && (
<Stack>
- <MenuSectionTitle title={t('VIEWERS')} icon={<Photo />} />
+ <MenuSectionTitle title={t("VIEWERS")} icon={<Photo />} />
<MenuItemGroup>
{viewers.map((item, index) => (
<>
@@ -85,7 +85,7 @@ export default function SharingDetails({ collection, type }) {
fontWeight="normal"
key={item}
onClick={() => {}}
- label={isMe(item) ? t('YOU') : item}
+ label={isMe(item) ? t("YOU") : item}
startIcon={<Avatar email={item} />}
/>
{index !== viewers.length - 1 && (
diff --git a/apps/photos/src/components/Collections/CollectionShare/styledComponents.tsx b/apps/photos/src/components/Collections/CollectionShare/styledComponents.tsx
index 014f355703..344484f254 100644
--- a/apps/photos/src/components/Collections/CollectionShare/styledComponents.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/styledComponents.tsx
@@ -1,13 +1,13 @@
-import { styled } from '@mui/material';
-export const ManageSectionLabel = styled('summary')(
+import { styled } from "@mui/material";
+export const ManageSectionLabel = styled("summary")(
({ theme }) => `
text-align: center;
margin-bottom:${theme.spacing(1)};
-`
+`,
);
-export const ManageSectionOptions = styled('section')(
+export const ManageSectionOptions = styled("section")(
({ theme }) => `
margin-bottom:${theme.spacing(4)};
-`
+`,
);
diff --git a/apps/photos/src/components/Collections/index.tsx b/apps/photos/src/components/Collections/index.tsx
index 67d919cd5c..c16d56ee52 100644
--- a/apps/photos/src/components/Collections/index.tsx
+++ b/apps/photos/src/components/Collections/index.tsx
@@ -1,27 +1,27 @@
-import { Collection, CollectionSummaries } from 'types/collection';
-import CollectionListBar from 'components/Collections/CollectionListBar';
-import { useCallback, useEffect, useMemo, useState } from 'react';
-import AllCollections from 'components/Collections/AllCollections';
-import CollectionInfoWithOptions from 'components/Collections/CollectionInfoWithOptions';
-import { ALL_SECTION, COLLECTION_LIST_SORT_BY } from 'constants/collection';
-import CollectionShare from 'components/Collections/CollectionShare';
-import { SetCollectionNamerAttributes } from 'components/Collections/CollectionNamer';
-import { ITEM_TYPE, TimeStampListItem } from 'components/PhotoList';
+import { useLocalState } from "@ente/shared/hooks/useLocalState";
+import { LS_KEYS } from "@ente/shared/storage/localStorage";
+import AllCollections from "components/Collections/AllCollections";
+import CollectionInfoWithOptions from "components/Collections/CollectionInfoWithOptions";
+import CollectionListBar from "components/Collections/CollectionListBar";
+import { SetCollectionNamerAttributes } from "components/Collections/CollectionNamer";
+import CollectionShare from "components/Collections/CollectionShare";
+import { ITEM_TYPE, TimeStampListItem } from "components/PhotoList";
+import { ALL_SECTION, COLLECTION_LIST_SORT_BY } from "constants/collection";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { sortCollectionSummaries } from "services/collectionService";
+import { Collection, CollectionSummaries } from "types/collection";
+import { SetFilesDownloadProgressAttributesCreator } from "types/gallery";
import {
hasNonSystemCollections,
isSystemCollection,
shouldBeShownOnCollectionBar,
-} from 'utils/collection';
-import { useLocalState } from '@ente/shared/hooks/useLocalState';
-import { sortCollectionSummaries } from 'services/collectionService';
-import { LS_KEYS } from '@ente/shared/storage/localStorage';
+} from "utils/collection";
import {
FilesDownloadProgressAttributes,
isFilesDownloadCancelled,
isFilesDownloadCompleted,
-} from '../FilesDownloadProgress';
-import { SetFilesDownloadProgressAttributesCreator } from 'types/gallery';
-import AlbumCastDialog from './CollectionOptions/AlbumCastDialog';
+} from "../FilesDownloadProgress";
+import AlbumCastDialog from "./CollectionOptions/AlbumCastDialog";
interface Iprops {
activeCollection: Collection;
@@ -61,13 +61,13 @@ export default function Collections(props: Iprops) {
const [collectionListSortBy, setCollectionListSortBy] =
useLocalState<COLLECTION_LIST_SORT_BY>(
LS_KEYS.COLLECTION_SORT_BY,
- COLLECTION_LIST_SORT_BY.UPDATION_TIME_DESCENDING
+ COLLECTION_LIST_SORT_BY.UPDATION_TIME_DESCENDING,
);
const toShowCollectionSummaries = useMemo(
() =>
isInHiddenSection ? hiddenCollectionSummaries : collectionSummaries,
- [isInHiddenSection, hiddenCollectionSummaries, collectionSummaries]
+ [isInHiddenSection, hiddenCollectionSummaries, collectionSummaries],
);
const shouldBeHidden = useMemo(
@@ -75,21 +75,21 @@ export default function Collections(props: Iprops) {
isInSearchMode ||
(!hasNonSystemCollections(toShowCollectionSummaries) &&
activeCollectionID === ALL_SECTION),
- [isInSearchMode, toShowCollectionSummaries, activeCollectionID]
+ [isInSearchMode, toShowCollectionSummaries, activeCollectionID],
);
const sortedCollectionSummaries = useMemo(
() =>
sortCollectionSummaries(
[...toShowCollectionSummaries.values()],
- collectionListSortBy
+ collectionListSortBy,
),
- [collectionListSortBy, toShowCollectionSummaries]
+ [collectionListSortBy, toShowCollectionSummaries],
);
const isActiveCollectionDownloadInProgress = useCallback(() => {
const attributes = filesDownloadProgressAttributesList.find(
- (attr) => attr.collectionID === activeCollectionID
+ (attr) => attr.collectionID === activeCollectionID,
);
return (
attributes &&
@@ -106,7 +106,7 @@ export default function Collections(props: Iprops) {
item: (
<CollectionInfoWithOptions
collectionSummary={toShowCollectionSummaries.get(
- activeCollectionID
+ activeCollectionID,
)}
activeCollection={activeCollection}
setCollectionNamerAttributes={setCollectionNamerAttributes}
@@ -149,7 +149,7 @@ export default function Collections(props: Iprops) {
activeCollectionID={activeCollectionID}
setActiveCollectionID={setActiveCollectionID}
collectionSummaries={sortedCollectionSummaries.filter((x) =>
- shouldBeShownOnCollectionBar(x.type)
+ shouldBeShownOnCollectionBar(x.type),
)}
showAllCollections={openAllCollections}
setCollectionListSortBy={setCollectionListSortBy}
@@ -160,7 +160,7 @@ export default function Collections(props: Iprops) {
open={allCollectionView}
onClose={closeAllCollections}
collectionSummaries={sortedCollectionSummaries.filter(
- (x) => !isSystemCollection(x.type)
+ (x) => !isSystemCollection(x.type),
)}
setActiveCollectionID={setActiveCollectionID}
setCollectionListSortBy={setCollectionListSortBy}
@@ -170,7 +170,7 @@ export default function Collections(props: Iprops) {
<CollectionShare
collectionSummary={toShowCollectionSummaries.get(
- activeCollectionID
+ activeCollectionID,
)}
open={collectionShareModalView}
onClose={closeCollectionShare}
diff --git a/apps/photos/src/components/Collections/styledComponents.ts b/apps/photos/src/components/Collections/styledComponents.ts
index 08e73c298a..2b64e081a2 100644
--- a/apps/photos/src/components/Collections/styledComponents.ts
+++ b/apps/photos/src/components/Collections/styledComponents.ts
@@ -1,7 +1,6 @@
-import { Box } from '@mui/material';
-import { styled } from '@mui/material';
-import { Overlay } from '@ente/shared/components/Container';
-import { IMAGE_CONTAINER_MAX_WIDTH, MIN_COLUMNS } from 'constants/gallery';
+import { Overlay } from "@ente/shared/components/Container";
+import { Box, styled } from "@mui/material";
+import { IMAGE_CONTAINER_MAX_WIDTH, MIN_COLUMNS } from "constants/gallery";
export const CollectionListWrapper = styled(Box)`
position: relative;
overflow: hidden;
@@ -23,7 +22,7 @@ export const CollectionInfoBarWrapper = styled(Box)`
margin-bottom: 12px;
`;
-export const ScrollContainer = styled('div')`
+export const ScrollContainer = styled("div")`
width: 100%;
height: 120px;
overflow: auto;
@@ -32,7 +31,7 @@ export const ScrollContainer = styled('div')`
gap: 4px;
`;
-export const CollectionTile = styled('div')`
+export const CollectionTile = styled("div")`
display: flex;
position: relative;
border-radius: 4px;
@@ -47,7 +46,7 @@ export const CollectionTile = styled('div')`
user-select: none;
`;
-export const ActiveIndicator = styled('div')`
+export const ActiveIndicator = styled("div")`
height: 3px;
background-color: ${({ theme }) => theme.palette.primary.main};
margin-top: 18px;
diff --git a/apps/photos/src/components/DeleteAccountModal.tsx b/apps/photos/src/components/DeleteAccountModal.tsx
index 79690ecac6..87cfe64bd6 100644
--- a/apps/photos/src/components/DeleteAccountModal.tsx
+++ b/apps/photos/src/components/DeleteAccountModal.tsx
@@ -1,22 +1,22 @@
-import { Button, Link, Stack } from '@mui/material';
-import { AppContext } from 'pages/_app';
-import { useContext, useEffect, useRef, useState } from 'react';
-import { preloadImage, initiateEmail } from 'utils/common';
-import { deleteAccount, getAccountDeleteChallenge } from 'services/userService';
-import { logError } from '@ente/shared/sentry';
-import { decryptDeleteAccountChallenge } from 'utils/crypto';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
-import { DELETE_ACCOUNT_EMAIL } from '@ente/shared/constants/urls';
-import DialogBoxV2 from '@ente/shared/components/DialogBoxV2';
-import * as Yup from 'yup';
-import { Formik, FormikHelpers } from 'formik';
-import DropdownInput, { DropdownOption } from './DropdownInput';
-import MultilineInput from './MultilineInput';
-import { CheckboxInput } from './CheckboxInput';
-import EnteButton from '@ente/shared/components/EnteButton';
-import { GalleryContext } from 'pages/gallery';
-import { logoutUser } from '@ente/accounts/services/user';
+import { logoutUser } from "@ente/accounts/services/user";
+import DialogBoxV2 from "@ente/shared/components/DialogBoxV2";
+import EnteButton from "@ente/shared/components/EnteButton";
+import { DELETE_ACCOUNT_EMAIL } from "@ente/shared/constants/urls";
+import { logError } from "@ente/shared/sentry";
+import { Button, Link, Stack } from "@mui/material";
+import { Formik, FormikHelpers } from "formik";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { GalleryContext } from "pages/gallery";
+import { useContext, useEffect, useRef, useState } from "react";
+import { Trans } from "react-i18next";
+import { deleteAccount, getAccountDeleteChallenge } from "services/userService";
+import { initiateEmail, preloadImage } from "utils/common";
+import { decryptDeleteAccountChallenge } from "utils/crypto";
+import * as Yup from "yup";
+import { CheckboxInput } from "./CheckboxInput";
+import DropdownInput, { DropdownOption } from "./DropdownInput";
+import MultilineInput from "./MultilineInput";
interface Iprops {
onClose: () => void;
@@ -30,8 +30,8 @@ interface FormValues {
enum DELETE_REASON {
MISSING_FEATURE = "It's missing a key feature that I need",
- BROKEN_BEHAVIOR = 'The app or a certain feature does not behave as I think it should',
- FOUND_ANOTHER_SERVICE = 'I found another service that I like better',
+ BROKEN_BEHAVIOR = "The app or a certain feature does not behave as I think it should",
+ FOUND_ANOTHER_SERVICE = "I found another service that I like better",
NOT_LISTED = "My reason isn't listed",
}
@@ -52,19 +52,19 @@ const DeleteAccountModal = ({ open, onClose }: Iprops) => {
const reasonAndFeedbackRef = useRef<{ reason: string; feedback: string }>();
useEffect(() => {
- preloadImage('/images/delete-account');
+ preloadImage("/images/delete-account");
}, []);
const somethingWentWrong = () =>
setDialogBoxAttributesV2({
- title: t('ERROR'),
- close: { variant: 'critical' },
- content: t('UNKNOWN_ERROR'),
+ title: t("ERROR"),
+ close: { variant: "critical" },
+ content: t("UNKNOWN_ERROR"),
});
const initiateDelete = async (
{ reason, feedback }: FormValues,
- { setFieldError }: FormikHelpers<FormValues>
+ { setFieldError }: FormikHelpers<FormValues>,
) => {
try {
feedback = feedback.trim();
@@ -72,12 +72,12 @@ const DeleteAccountModal = ({ open, onClose }: Iprops) => {
switch (reason) {
case DELETE_REASON.FOUND_ANOTHER_SERVICE:
setFieldError(
- 'feedback',
- t('FEEDBACK_REQUIRED_FOUND_ANOTHER_SERVICE')
+ "feedback",
+ t("FEEDBACK_REQUIRED_FOUND_ANOTHER_SERVICE"),
);
break;
default:
- setFieldError('feedback', t('FEEDBACK_REQUIRED'));
+ setFieldError("feedback", t("FEEDBACK_REQUIRED"));
}
return;
}
@@ -92,7 +92,7 @@ const DeleteAccountModal = ({ open, onClose }: Iprops) => {
askToMailForDeletion();
}
} catch (e) {
- logError(e, 'Error while initiating account deletion');
+ logError(e, "Error while initiating account deletion");
somethingWentWrong();
} finally {
setLoading(false);
@@ -101,20 +101,20 @@ const DeleteAccountModal = ({ open, onClose }: Iprops) => {
const confirmAccountDeletion = () => {
setDialogBoxAttributesV2({
- title: t('DELETE_ACCOUNT'),
+ title: t("DELETE_ACCOUNT"),
content: <Trans i18nKey="CONFIRM_ACCOUNT_DELETION_MESSAGE" />,
proceed: {
- text: t('DELETE'),
+ text: t("DELETE"),
action: solveChallengeAndDeleteAccount,
- variant: 'critical',
+ variant: "critical",
},
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
});
};
const askToMailForDeletion = () => {
setDialogBoxAttributesV2({
- title: t('DELETE_ACCOUNT'),
+ title: t("DELETE_ACCOUNT"),
content: (
<Trans
i18nKey="DELETE_ACCOUNT_MESSAGE"
@@ -125,29 +125,29 @@ const DeleteAccountModal = ({ open, onClose }: Iprops) => {
/>
),
proceed: {
- text: t('DELETE'),
+ text: t("DELETE"),
action: () => {
- initiateEmail('[email protected]');
+ initiateEmail("[email protected]");
},
- variant: 'critical',
+ variant: "critical",
},
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
});
};
const solveChallengeAndDeleteAccount = async (
- setLoading: (value: boolean) => void
+ setLoading: (value: boolean) => void,
) => {
try {
setLoading(true);
const decryptedChallenge = await decryptDeleteAccountChallenge(
- deleteAccountChallenge.current
+ deleteAccountChallenge.current,
);
const { reason, feedback } = reasonAndFeedbackRef.current;
await deleteAccount(decryptedChallenge, reason, feedback);
logoutUser();
} catch (e) {
- logError(e, 'solveChallengeAndDeleteAccount failed');
+ logError(e, "solveChallengeAndDeleteAccount failed");
somethingWentWrong();
} finally {
setLoading(false);
@@ -162,23 +162,25 @@ const DeleteAccountModal = ({ open, onClose }: Iprops) => {
onClose={onClose}
fullScreen={isMobile}
attributes={{
- title: t('DELETE_ACCOUNT'),
+ title: t("DELETE_ACCOUNT"),
secondary: {
action: onClose,
- text: t('CANCEL'),
+ text: t("CANCEL"),
},
- }}>
+ }}
+ >
<Formik<FormValues>
initialValues={{
- reason: '',
- feedback: '',
+ reason: "",
+ feedback: "",
}}
validationSchema={Yup.object().shape({
- reason: Yup.string().required(t('REQUIRED')),
+ reason: Yup.string().required(t("REQUIRED")),
})}
validateOnChange={false}
validateOnBlur={false}
- onSubmit={initiateDelete}>
+ onSubmit={initiateDelete}
+ >
{({
values,
errors,
@@ -186,50 +188,52 @@ const DeleteAccountModal = ({ open, onClose }: Iprops) => {
handleSubmit,
}): JSX.Element => (
<form noValidate onSubmit={handleSubmit}>
- <Stack spacing={'24px'}>
+ <Stack spacing={"24px"}>
<DropdownInput
options={getReasonOptions()}
- label={t('DELETE_ACCOUNT_REASON_LABEL')}
+ label={t("DELETE_ACCOUNT_REASON_LABEL")}
placeholder={t(
- 'DELETE_ACCOUNT_REASON_PLACEHOLDER'
+ "DELETE_ACCOUNT_REASON_PLACEHOLDER",
)}
selected={values.reason}
- setSelected={handleChange('reason')}
- messageProps={{ color: 'critical.main' }}
+ setSelected={handleChange("reason")}
+ messageProps={{ color: "critical.main" }}
message={errors.reason}
/>
<MultilineInput
- label={t('DELETE_ACCOUNT_FEEDBACK_LABEL')}
+ label={t("DELETE_ACCOUNT_FEEDBACK_LABEL")}
placeholder={t(
- 'DELETE_ACCOUNT_FEEDBACK_PLACEHOLDER'
+ "DELETE_ACCOUNT_FEEDBACK_PLACEHOLDER",
)}
value={values.feedback}
- onChange={handleChange('feedback')}
+ onChange={handleChange("feedback")}
message={errors.feedback}
- messageProps={{ color: 'critical.main' }}
+ messageProps={{ color: "critical.main" }}
rowCount={3}
/>
<CheckboxInput
checked={acceptDataDeletion}
onChange={setAcceptDataDeletion}
label={t(
- 'CONFIRM_DELETE_ACCOUNT_CHECKBOX_LABEL'
+ "CONFIRM_DELETE_ACCOUNT_CHECKBOX_LABEL",
)}
/>
- <Stack spacing={'8px'}>
+ <Stack spacing={"8px"}>
<EnteButton
type="submit"
size="large"
color="critical"
disabled={!acceptDataDeletion}
- loading={loading}>
- {t('CONFIRM_DELETE_ACCOUNT')}
+ loading={loading}
+ >
+ {t("CONFIRM_DELETE_ACCOUNT")}
</EnteButton>
<Button
size="large"
- color={'secondary'}
- onClick={onClose}>
- {t('CANCEL')}
+ color={"secondary"}
+ onClick={onClose}
+ >
+ {t("CANCEL")}
</Button>
</Stack>
</Stack>
diff --git a/apps/photos/src/components/Directory/changeOption.tsx b/apps/photos/src/components/Directory/changeOption.tsx
index fbac4c198b..f846e9ba9d 100644
--- a/apps/photos/src/components/Directory/changeOption.tsx
+++ b/apps/photos/src/components/Directory/changeOption.tsx
@@ -1,8 +1,8 @@
-import OverflowMenu from '@ente/shared/components/OverflowMenu/menu';
-import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';
-import MoreHoriz from '@mui/icons-material/MoreHoriz';
-import { t } from 'i18next';
-import FolderIcon from '@mui/icons-material/Folder';
+import OverflowMenu from "@ente/shared/components/OverflowMenu/menu";
+import { OverflowMenuOption } from "@ente/shared/components/OverflowMenu/option";
+import FolderIcon from "@mui/icons-material/Folder";
+import MoreHoriz from "@mui/icons-material/MoreHoriz";
+import { t } from "i18next";
export default function ChangeDirectoryOption({
changeExportDirectory: changeDirectory,
@@ -14,12 +14,14 @@ export default function ChangeDirectoryOption({
ml: 1,
},
}}
- ariaControls={'export-option'}
- triggerButtonIcon={<MoreHoriz />}>
+ ariaControls={"export-option"}
+ triggerButtonIcon={<MoreHoriz />}
+ >
<OverflowMenuOption
onClick={changeDirectory}
- startIcon={<FolderIcon />}>
- {t('CHANGE_FOLDER')}
+ startIcon={<FolderIcon />}
+ >
+ {t("CHANGE_FOLDER")}
</OverflowMenuOption>
</OverflowMenu>
);
diff --git a/apps/photos/src/components/Directory/index.tsx b/apps/photos/src/components/Directory/index.tsx
index e097197887..a872027718 100644
--- a/apps/photos/src/components/Directory/index.tsx
+++ b/apps/photos/src/components/Directory/index.tsx
@@ -1,8 +1,8 @@
-import { styled } from '@mui/material/styles';
-import LinkButton from '@ente/shared/components/LinkButton';
-import { Tooltip } from '@mui/material';
-import ElectronAPIs from '@ente/shared/electron';
-import { logError } from '@ente/shared/sentry';
+import LinkButton from "@ente/shared/components/LinkButton";
+import ElectronAPIs from "@ente/shared/electron";
+import { logError } from "@ente/shared/sentry";
+import { Tooltip } from "@mui/material";
+import { styled } from "@mui/material/styles";
const DirectoryPathContainer = styled(LinkButton)(
({ width }) => `
@@ -13,7 +13,7 @@ const DirectoryPathContainer = styled(LinkButton)(
/* Beginning of string */
direction: rtl;
text-align: left;
-`
+`,
);
export const DirectoryPath = ({ width, path }) => {
@@ -21,7 +21,7 @@ export const DirectoryPath = ({ width, path }) => {
try {
await ElectronAPIs.openDirectory(path);
} catch (e) {
- logError(e, 'openDirectory failed');
+ logError(e, "openDirectory failed");
}
};
return (
diff --git a/apps/photos/src/components/DropdownInput.tsx b/apps/photos/src/components/DropdownInput.tsx
index 6702550366..76f9e74230 100644
--- a/apps/photos/src/components/DropdownInput.tsx
+++ b/apps/photos/src/components/DropdownInput.tsx
@@ -1,4 +1,4 @@
-import ExpandMore from '@mui/icons-material/ExpandMore';
+import ExpandMore from "@mui/icons-material/ExpandMore";
import {
Box,
MenuItem,
@@ -7,7 +7,7 @@ import {
Stack,
Typography,
TypographyProps,
-} from '@mui/material';
+} from "@mui/material";
export interface DropdownOption<T> {
label: string;
@@ -36,7 +36,7 @@ export default function DropdownInput<T extends string>({
messageProps,
}: Iprops<T>) {
return (
- <Stack spacing={'4px'}>
+ <Stack spacing={"4px"}>
<Typography {...labelProps}>{label}</Typography>
<Select
IconComponent={ExpandMore}
@@ -54,11 +54,11 @@ export default function DropdownInput<T extends string>({
MenuListProps: {
sx: (theme) => ({
backgroundColor: theme.colors.background.elevated2,
- '.MuiMenuItem-root ': {
+ ".MuiMenuItem-root ": {
color: theme.colors.text.faint,
- whiteSpace: 'normal',
+ whiteSpace: "normal",
},
- '&&& > .Mui-selected': {
+ "&&& > .Mui-selected": {
background: theme.colors.background.elevated2,
color: theme.colors.text.base,
},
@@ -66,28 +66,28 @@ export default function DropdownInput<T extends string>({
},
}}
sx={(theme) => ({
- '::before , ::after': {
- borderBottom: 'none !important',
+ "::before , ::after": {
+ borderBottom: "none !important",
},
- '.MuiInput-root': {
+ ".MuiInput-root": {
background: theme.colors.fill.faint,
- borderRadius: '8px',
+ borderRadius: "8px",
},
- '.MuiSelect-select': {
+ ".MuiSelect-select": {
background: theme.colors.fill.faint,
- borderRadius: '8px',
+ borderRadius: "8px",
},
- '&&& .MuiSelect-select': {
- p: '12px 36px 12px 16px',
+ "&&& .MuiSelect-select": {
+ p: "12px 36px 12px 16px",
},
- '.MuiSelect-icon': {
- mr: '12px',
+ ".MuiSelect-icon": {
+ mr: "12px",
color: theme.colors.stroke.muted,
},
})}
renderValue={(selected) => {
return !selected?.length ? (
- <Box color={'text.muted'}>{placeholder ?? ''}</Box>
+ <Box color={"text.muted"}>{placeholder ?? ""}</Box>
) : (
options.find((o) => o.value === selected).label
);
@@ -95,17 +95,19 @@ export default function DropdownInput<T extends string>({
value={selected}
onChange={(event: SelectChangeEvent) => {
setSelected(event.target.value as T);
- }}>
+ }}
+ >
{options.map((option, index) => (
<MenuItem
key={option.label}
divider={index !== options.length - 1}
value={option.value}
sx={{
- px: '16px',
- py: '14px',
+ px: "16px",
+ py: "14px",
color: (theme) => theme.palette.primary.main,
- }}>
+ }}
+ >
{option.label}
</MenuItem>
))}
@@ -113,9 +115,10 @@ export default function DropdownInput<T extends string>({
{message && (
<Typography
variant="small"
- px={'8px'}
- color={'text.muted'}
- {...messageProps}>
+ px={"8px"}
+ color={"text.muted"}
+ {...messageProps}
+ >
{message}
</Typography>
)}
diff --git a/apps/photos/src/components/EnteDateTimePicker.tsx b/apps/photos/src/components/EnteDateTimePicker.tsx
index d5c3249033..ee5426ebcc 100644
--- a/apps/photos/src/components/EnteDateTimePicker.tsx
+++ b/apps/photos/src/components/EnteDateTimePicker.tsx
@@ -1,14 +1,14 @@
-import React, { useState } from 'react';
+import { useState } from "react";
-import {
- MIN_EDITED_CREATION_TIME,
- MAX_EDITED_CREATION_TIME,
-} from 'constants/file';
import {
LocalizationProvider,
MobileDateTimePicker,
-} from '@mui/x-date-pickers';
-import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
+} from "@mui/x-date-pickers";
+import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
+import {
+ MAX_EDITED_CREATION_TIME,
+ MIN_EDITED_CREATION_TIME,
+} from "constants/file";
interface Props {
initialValue?: Date;
@@ -45,17 +45,17 @@ const EnteDateTimePicker = ({
onAccept={onSubmit}
DialogProps={{
sx: {
- zIndex: '1502',
- '.MuiPickersToolbar-penIconButton': {
- display: 'none',
+ zIndex: "1502",
+ ".MuiPickersToolbar-penIconButton": {
+ display: "none",
},
- '.MuiDialog-paper': { width: '320px' },
- '.MuiClockPicker-root': {
- position: 'relative',
- minHeight: '292px',
+ ".MuiDialog-paper": { width: "320px" },
+ ".MuiClockPicker-root": {
+ position: "relative",
+ minHeight: "292px",
},
- '.PrivatePickersSlideTransition-root': {
- minHeight: '200px',
+ ".PrivatePickersSlideTransition-root": {
+ minHeight: "200px",
},
},
}}
diff --git a/apps/photos/src/components/EnteDrawer.tsx b/apps/photos/src/components/EnteDrawer.tsx
index beacae98a0..e6fc35bb15 100644
--- a/apps/photos/src/components/EnteDrawer.tsx
+++ b/apps/photos/src/components/EnteDrawer.tsx
@@ -1,10 +1,10 @@
-import { Drawer, styled } from '@mui/material';
+import { Drawer, styled } from "@mui/material";
export const EnteDrawer = styled(Drawer)(({ theme }) => ({
- '& .MuiPaper-root': {
- maxWidth: '375px',
- width: '100%',
- scrollbarWidth: 'thin',
+ "& .MuiPaper-root": {
+ maxWidth: "375px",
+ width: "100%",
+ scrollbarWidth: "thin",
padding: theme.spacing(1),
},
}));
diff --git a/apps/photos/src/components/EnteSpinner.tsx b/apps/photos/src/components/EnteSpinner.tsx
index 366d38cfb7..8a5d0a2896 100644
--- a/apps/photos/src/components/EnteSpinner.tsx
+++ b/apps/photos/src/components/EnteSpinner.tsx
@@ -1,6 +1,6 @@
import CircularProgress, {
CircularProgressProps,
-} from '@mui/material/CircularProgress';
+} from "@mui/material/CircularProgress";
export default function EnteSpinner(props: CircularProgressProps) {
return <CircularProgress color="accent" size={32} {...props} />;
diff --git a/apps/photos/src/components/ExportFinished.tsx b/apps/photos/src/components/ExportFinished.tsx
index 5e321fefa2..43ba027578 100644
--- a/apps/photos/src/components/ExportFinished.tsx
+++ b/apps/photos/src/components/ExportFinished.tsx
@@ -1,18 +1,18 @@
+import { SpaceBetweenFlex } from "@ente/shared/components/Container";
+import { formatDateTime } from "@ente/shared/time/format";
import {
Button,
DialogActions,
DialogContent,
Stack,
Typography,
-} from '@mui/material';
-import { t } from 'i18next';
-import { formatDateTime } from '@ente/shared/time/format';
-import { SpaceBetweenFlex } from '@ente/shared/components/Container';
-import { formatNumber } from 'utils/number/format';
-import ExportPendingList from './ExportPendingList';
-import { useState } from 'react';
-import LinkButton from './pages/gallery/LinkButton';
-import { EnteFile } from 'types/file';
+} from "@mui/material";
+import { t } from "i18next";
+import { useState } from "react";
+import { EnteFile } from "types/file";
+import { formatNumber } from "utils/number/format";
+import ExportPendingList from "./ExportPendingList";
+import LinkButton from "./pages/gallery/LinkButton";
interface Props {
pendingExports: EnteFile[];
@@ -37,9 +37,9 @@ export default function ExportFinished(props: Props) {
<>
<DialogContent>
<Stack pr={2}>
- <SpaceBetweenFlex minHeight={'48px'}>
- <Typography color={'text.muted'}>
- {t('PENDING_ITEMS')}
+ <SpaceBetweenFlex minHeight={"48px"}>
+ <Typography color={"text.muted"}>
+ {t("PENDING_ITEMS")}
</Typography>
{props.pendingExports.length ? (
<LinkButton onClick={openPendingFileList}>
@@ -51,27 +51,28 @@ export default function ExportFinished(props: Props) {
</Typography>
)}
</SpaceBetweenFlex>
- <SpaceBetweenFlex minHeight={'48px'}>
+ <SpaceBetweenFlex minHeight={"48px"}>
<Typography color="text.muted">
- {t('LAST_EXPORT_TIME')}
+ {t("LAST_EXPORT_TIME")}
</Typography>
<Typography>
{props.lastExportTime
? formatDateTime(props.lastExportTime)
- : t('NEVER')}
+ : t("NEVER")}
</Typography>
</SpaceBetweenFlex>
</Stack>
</DialogContent>
<DialogActions>
<Button color="secondary" size="large" onClick={props.onHide}>
- {t('CLOSE')}
+ {t("CLOSE")}
</Button>
<Button
size="large"
color="primary"
- onClick={props.startExport}>
- {t('EXPORT_AGAIN')}
+ onClick={props.startExport}
+ >
+ {t("EXPORT_AGAIN")}
</Button>
</DialogActions>
<ExportPendingList
diff --git a/apps/photos/src/components/ExportInProgress.tsx b/apps/photos/src/components/ExportInProgress.tsx
index 3c9a34201d..3324be5c41 100644
--- a/apps/photos/src/components/ExportInProgress.tsx
+++ b/apps/photos/src/components/ExportInProgress.tsx
@@ -1,22 +1,21 @@
-import React from 'react';
-import { ExportProgress } from 'types/export';
+import {
+ FlexWrapper,
+ VerticallyCentered,
+} from "@ente/shared/components/Container";
import {
Box,
Button,
DialogActions,
DialogContent,
styled,
-} from '@mui/material';
-import { ExportStage } from 'constants/export';
-import {
- VerticallyCentered,
- FlexWrapper,
-} from '@ente/shared/components/Container';
-import { ProgressBar } from 'react-bootstrap';
-import { t } from 'i18next';
-import { Trans } from 'react-i18next';
+} from "@mui/material";
+import { ExportStage } from "constants/export";
+import { t } from "i18next";
+import { ProgressBar } from "react-bootstrap";
+import { Trans } from "react-i18next";
+import { ExportProgress } from "types/export";
-export const ComfySpan = styled('span')`
+export const ComfySpan = styled("span")`
padding: 0 0.5rem;
word-spacing: 1rem;
color: #ddd;
@@ -45,21 +44,21 @@ export default function ExportInProgress(props: Props) {
<VerticallyCentered>
<Box mb={1.5}>
{props.exportStage === ExportStage.STARTING ? (
- t('EXPORT_STARTING')
+ t("EXPORT_STARTING")
) : props.exportStage === ExportStage.MIGRATION ? (
- t('MIGRATING_EXPORT')
+ t("MIGRATING_EXPORT")
) : props.exportStage ===
ExportStage.RENAMING_COLLECTION_FOLDERS ? (
- t('RENAMING_COLLECTION_FOLDERS')
+ t("RENAMING_COLLECTION_FOLDERS")
) : props.exportStage ===
ExportStage.TRASHING_DELETED_FILES ? (
- t('TRASHING_DELETED_FILES')
+ t("TRASHING_DELETED_FILES")
) : props.exportStage ===
ExportStage.TRASHING_DELETED_COLLECTIONS ? (
- t('TRASHING_DELETED_COLLECTIONS')
+ t("TRASHING_DELETED_COLLECTIONS")
) : (
<Trans
- i18nKey={'EXPORT_PROGRESS'}
+ i18nKey={"EXPORT_PROGRESS"}
components={{
a: <ComfySpan />,
}}
@@ -71,7 +70,7 @@ export default function ExportInProgress(props: Props) {
</Box>
<FlexWrapper px={1}>
<ProgressBar
- style={{ width: '100%' }}
+ style={{ width: "100%" }}
now={
showIndeterminateProgress()
? 100
@@ -79,7 +78,7 @@ export default function ExportInProgress(props: Props) {
((props.exportProgress.success +
props.exportProgress.failed) *
100) /
- props.exportProgress.total
+ props.exportProgress.total,
)
}
animated
@@ -92,14 +91,16 @@ export default function ExportInProgress(props: Props) {
<Button
color="secondary"
size="large"
- onClick={props.closeExportDialog}>
- {t('CLOSE')}
+ onClick={props.closeExportDialog}
+ >
+ {t("CLOSE")}
</Button>
<Button
size="large"
color="critical"
- onClick={props.stopExport}>
- {t('STOP_EXPORT')}
+ onClick={props.stopExport}
+ >
+ {t("STOP_EXPORT")}
</Button>
</DialogActions>
</>
diff --git a/apps/photos/src/components/ExportInit.tsx b/apps/photos/src/components/ExportInit.tsx
index 7eaab63f88..c2ac42bde8 100644
--- a/apps/photos/src/components/ExportInit.tsx
+++ b/apps/photos/src/components/ExportInit.tsx
@@ -1,6 +1,5 @@
-import { Button, DialogActions, DialogContent } from '@mui/material';
-import React from 'react';
-import { t } from 'i18next';
+import { Button, DialogActions, DialogContent } from "@mui/material";
+import { t } from "i18next";
interface Props {
startExport: () => void;
@@ -10,7 +9,7 @@ export default function ExportInit({ startExport }: Props) {
<DialogContent>
<DialogActions>
<Button size="large" color="accent" onClick={startExport}>
- {t('START')}
+ {t("START")}
</Button>
</DialogActions>
</DialogContent>
diff --git a/apps/photos/src/components/ExportModal.tsx b/apps/photos/src/components/ExportModal.tsx
index f4ee6fd85a..142c00743d 100644
--- a/apps/photos/src/components/ExportModal.tsx
+++ b/apps/photos/src/components/ExportModal.tsx
@@ -1,7 +1,11 @@
-import isElectron from 'is-electron';
-import { useEffect, useState, useContext } from 'react';
-import exportService from 'services/export';
-import { ExportProgress, ExportSettings } from 'types/export';
+import {
+ SpaceBetweenFlex,
+ VerticallyCenteredFlex,
+} from "@ente/shared/components/Container";
+import DialogTitleWithCloseButton from "@ente/shared/components/DialogBox/TitleWithCloseButton";
+import { CustomError } from "@ente/shared/error";
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
import {
Box,
Button,
@@ -10,25 +14,21 @@ import {
Divider,
Switch,
Typography,
-} from '@mui/material';
-import { logError } from '@ente/shared/sentry';
-import {
- SpaceBetweenFlex,
- VerticallyCenteredFlex,
-} from '@ente/shared/components/Container';
-import ExportFinished from './ExportFinished';
-import ExportInit from './ExportInit';
-import ExportInProgress from './ExportInProgress';
-import { ExportStage } from 'constants/export';
-import DialogTitleWithCloseButton from '@ente/shared/components/DialogBox/TitleWithCloseButton';
-import { AppContext } from 'pages/_app';
-import { getExportDirectoryDoesNotExistMessage } from 'utils/ui';
-import { t } from 'i18next';
-import { CustomError } from '@ente/shared/error';
-import { addLogLine } from '@ente/shared/logging';
-import { EnteFile } from 'types/file';
-import ChangeDirectoryOption from './Directory/changeOption';
-import { DirectoryPath } from './Directory';
+} from "@mui/material";
+import { ExportStage } from "constants/export";
+import { t } from "i18next";
+import isElectron from "is-electron";
+import { AppContext } from "pages/_app";
+import { useContext, useEffect, useState } from "react";
+import exportService from "services/export";
+import { ExportProgress, ExportSettings } from "types/export";
+import { EnteFile } from "types/file";
+import { getExportDirectoryDoesNotExistMessage } from "utils/ui";
+import { DirectoryPath } from "./Directory";
+import ChangeDirectoryOption from "./Directory/changeOption";
+import ExportFinished from "./ExportFinished";
+import ExportInProgress from "./ExportInProgress";
+import ExportInit from "./ExportInit";
interface Props {
show: boolean;
@@ -38,7 +38,7 @@ interface Props {
export default function ExportModal(props: Props) {
const appContext = useContext(AppContext);
const [exportStage, setExportStage] = useState(ExportStage.INIT);
- const [exportFolder, setExportFolder] = useState('');
+ const [exportFolder, setExportFolder] = useState("");
const [continuousExport, setContinuousExport] = useState(false);
const [exportProgress, setExportProgress] = useState<ExportProgress>({
success: 0,
@@ -68,7 +68,7 @@ export default function ExportModal(props: Props) {
setContinuousExport(exportSettings?.continuousExport ?? false);
void syncExportRecord(exportSettings?.folder);
} catch (e) {
- logError(e, 'export on mount useEffect failed');
+ logError(e, "export on mount useEffect failed");
}
}, []);
@@ -101,7 +101,7 @@ export default function ExportModal(props: Props) {
const verifyExportFolderExists = () => {
if (!exportService.exportFolderExists(exportFolder)) {
appContext.setDialogMessage(
- getExportDirectoryDoesNotExistMessage()
+ getExportDirectoryDoesNotExistMessage(),
);
throw Error(CustomError.EXPORT_FOLDER_DOES_NOT_EXIST);
}
@@ -123,7 +123,7 @@ export default function ExportModal(props: Props) {
setPendingExports(pendingExports);
} catch (e) {
if (e.message !== CustomError.EXPORT_FOLDER_DOES_NOT_EXIST) {
- logError(e, 'syncExportRecord failed');
+ logError(e, "syncExportRecord failed");
}
}
};
@@ -140,7 +140,7 @@ export default function ExportModal(props: Props) {
void syncExportRecord(newFolder);
} catch (e) {
if (e.message !== CustomError.SELECT_FOLDER_ABORTED) {
- logError(e, 'handleChangeExportDirectoryClick failed');
+ logError(e, "handleChangeExportDirectoryClick failed");
}
}
};
@@ -156,7 +156,7 @@ export default function ExportModal(props: Props) {
}
updateContinuousExport(newContinuousExport);
} catch (e) {
- logError(e, 'onContinuousExportChange failed');
+ logError(e, "onContinuousExportChange failed");
}
};
@@ -166,7 +166,7 @@ export default function ExportModal(props: Props) {
await exportService.scheduleExport();
} catch (e) {
if (e.message !== CustomError.EXPORT_FOLDER_DOES_NOT_EXIST) {
- logError(e, 'scheduleExport failed');
+ logError(e, "scheduleExport failed");
}
}
};
@@ -178,7 +178,7 @@ export default function ExportModal(props: Props) {
return (
<Dialog open={props.show} onClose={props.onHide} maxWidth="xs">
<DialogTitleWithCloseButton onClose={props.onHide}>
- {t('EXPORT_DATA')}
+ {t("EXPORT_DATA")}
</DialogTitleWithCloseButton>
<DialogContent>
<ExportDirectory
@@ -208,14 +208,14 @@ export default function ExportModal(props: Props) {
function ExportDirectory({ exportFolder, changeExportDirectory, exportStage }) {
return (
- <SpaceBetweenFlex minHeight={'48px'}>
- <Typography color="text.muted" mr={'16px'}>
- {t('DESTINATION')}
+ <SpaceBetweenFlex minHeight={"48px"}>
+ <Typography color="text.muted" mr={"16px"}>
+ {t("DESTINATION")}
</Typography>
<>
{!exportFolder ? (
- <Button color={'accent'} onClick={changeExportDirectory}>
- {t('SELECT_FOLDER')}
+ <Button color={"accent"} onClick={changeExportDirectory}>
+ {t("SELECT_FOLDER")}
</Button>
) : (
<VerticallyCenteredFlex>
@@ -226,7 +226,7 @@ function ExportDirectory({ exportFolder, changeExportDirectory, exportStage }) {
changeExportDirectory={changeExportDirectory}
/>
) : (
- <Box sx={{ width: '16px' }} />
+ <Box sx={{ width: "16px" }} />
)}
</VerticallyCenteredFlex>
)}
@@ -237,8 +237,8 @@ function ExportDirectory({ exportFolder, changeExportDirectory, exportStage }) {
function ContinuousExport({ continuousExport, toggleContinuousExport }) {
return (
- <SpaceBetweenFlex minHeight={'48px'}>
- <Typography color="text.muted">{t('CONTINUOUS_EXPORT')}</Typography>
+ <SpaceBetweenFlex minHeight={"48px"}>
+ <Typography color="text.muted">{t("CONTINUOUS_EXPORT")}</Typography>
<Box>
<Switch
color="accent"
diff --git a/apps/photos/src/components/ExportPendingList.tsx b/apps/photos/src/components/ExportPendingList.tsx
index 087b767f2c..93aa850787 100644
--- a/apps/photos/src/components/ExportPendingList.tsx
+++ b/apps/photos/src/components/ExportPendingList.tsx
@@ -1,11 +1,11 @@
-import { EnteFile } from 'types/file';
-import ItemList from 'components/ItemList';
-import DialogBoxV2 from '@ente/shared/components/DialogBoxV2';
-import { t } from 'i18next';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import CollectionCard from './Collections/CollectionCard';
-import { ResultPreviewTile } from './Collections/styledComponents';
-import { Box, styled } from '@mui/material';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import DialogBoxV2 from "@ente/shared/components/DialogBoxV2";
+import { Box, styled } from "@mui/material";
+import ItemList from "components/ItemList";
+import { t } from "i18next";
+import { EnteFile } from "types/file";
+import CollectionCard from "./Collections/CollectionCard";
+import { ResultPreviewTile } from "./Collections/styledComponents";
interface Iprops {
isOpen: boolean;
@@ -14,7 +14,7 @@ interface Iprops {
pendingExports: EnteFile[];
}
-export const ItemContainer = styled('div')`
+export const ItemContainer = styled("div")`
position: relative;
top: 5px;
display: inline-block;
@@ -28,7 +28,7 @@ const ExportPendingList = (props: Iprops) => {
const renderListItem = (file: EnteFile) => {
return (
<FlexWrapper>
- <Box sx={{ marginRight: '8px' }}>
+ <Box sx={{ marginRight: "8px" }}>
<CollectionCard
key={file.id}
coverFile={file}
@@ -60,15 +60,16 @@ const ExportPendingList = (props: Iprops) => {
open={props.isOpen}
onClose={props.onClose}
PaperProps={{
- sx: { maxWidth: '444px' },
+ sx: { maxWidth: "444px" },
}}
attributes={{
- title: t('PENDING_ITEMS'),
+ title: t("PENDING_ITEMS"),
close: {
action: props.onClose,
- text: t('CLOSE'),
+ text: t("CLOSE"),
},
- }}>
+ }}
+ >
<ItemList
maxHeight={240}
itemSize={50}
diff --git a/apps/photos/src/components/FilesDownloadProgress.tsx b/apps/photos/src/components/FilesDownloadProgress.tsx
index a55ca113ba..8999de3706 100644
--- a/apps/photos/src/components/FilesDownloadProgress.tsx
+++ b/apps/photos/src/components/FilesDownloadProgress.tsx
@@ -1,10 +1,10 @@
-import Notification from 'components/Notification';
-import { t } from 'i18next';
-import isElectron from 'is-electron';
-import { AppContext } from 'pages/_app';
-import { GalleryContext } from 'pages/gallery';
-import { useContext } from 'react';
-import ElectronAPIs from '@ente/shared/electron';
+import ElectronAPIs from "@ente/shared/electron";
+import Notification from "components/Notification";
+import { t } from "i18next";
+import isElectron from "is-electron";
+import { AppContext } from "pages/_app";
+import { GalleryContext } from "pages/gallery";
+import { useContext } from "react";
export interface FilesDownloadProgressAttributes {
id: number;
@@ -24,13 +24,13 @@ interface FilesDownloadProgressProps {
}
export const isFilesDownloadStarted = (
- attributes: FilesDownloadProgressAttributes
+ attributes: FilesDownloadProgressAttributes,
) => {
return attributes && attributes.total > 0;
};
export const isFilesDownloadCompleted = (
- attributes: FilesDownloadProgressAttributes
+ attributes: FilesDownloadProgressAttributes,
) => {
return (
attributes &&
@@ -39,7 +39,7 @@ export const isFilesDownloadCompleted = (
};
export const isFilesDownloadCompletedWithErrors = (
- attributes: FilesDownloadProgressAttributes
+ attributes: FilesDownloadProgressAttributes,
) => {
return (
attributes &&
@@ -49,7 +49,7 @@ export const isFilesDownloadCompletedWithErrors = (
};
export const isFilesDownloadCancelled = (
- attributes: FilesDownloadProgressAttributes
+ attributes: FilesDownloadProgressAttributes,
) => {
return attributes && attributes.canceller?.signal?.aborted;
};
@@ -70,22 +70,22 @@ export const FilesDownloadProgress: React.FC<FilesDownloadProgressProps> = ({
};
const confirmCancelUpload = (
- attributes: FilesDownloadProgressAttributes
+ attributes: FilesDownloadProgressAttributes,
) => {
appContext.setDialogMessage({
- title: t('STOP_DOWNLOADS_HEADER'),
- content: t('STOP_ALL_DOWNLOADS_MESSAGE'),
+ title: t("STOP_DOWNLOADS_HEADER"),
+ content: t("STOP_ALL_DOWNLOADS_MESSAGE"),
proceed: {
- text: t('YES_STOP_DOWNLOADS'),
- variant: 'critical',
+ text: t("YES_STOP_DOWNLOADS"),
+ variant: "critical",
action: () => {
attributes?.canceller.abort();
onClose(attributes.id);
},
},
close: {
- text: t('NO'),
- variant: 'secondary',
+ text: t("NO"),
+ variant: "secondary",
action: () => {},
},
});
@@ -107,7 +107,7 @@ export const FilesDownloadProgress: React.FC<FilesDownloadProgressProps> = ({
if (attributes.isHidden) {
galleryContext.openHiddenSection(() => {
galleryContext.setActiveCollectionID(
- attributes.collectionID
+ attributes.collectionID,
);
});
} else {
@@ -123,7 +123,7 @@ export const FilesDownloadProgress: React.FC<FilesDownloadProgressProps> = ({
key={attributes.id}
horizontal="left"
sx={{
- '&&': { bottom: `${index * 80 + 20}px` },
+ "&&": { bottom: `${index * 80 + 20}px` },
zIndex: 1600,
}}
open={isFilesDownloadStarted(attributes)}
@@ -131,18 +131,18 @@ export const FilesDownloadProgress: React.FC<FilesDownloadProgressProps> = ({
keepOpenOnClick
attributes={{
variant: isFilesDownloadCompletedWithErrors(attributes)
- ? 'critical'
- : 'secondary',
+ ? "critical"
+ : "secondary",
title: isFilesDownloadCompletedWithErrors(attributes)
- ? t('DOWNLOAD_FAILED')
+ ? t("DOWNLOAD_FAILED")
: isFilesDownloadCompleted(attributes)
? t(`DOWNLOAD_COMPLETE`)
- : t('DOWNLOADING_COLLECTION', {
+ : t("DOWNLOADING_COLLECTION", {
name: attributes.folderName,
}),
caption: isFilesDownloadCompleted(attributes)
? attributes.folderName
- : t('DOWNLOAD_PROGRESS', {
+ : t("DOWNLOAD_PROGRESS", {
progress: {
current:
attributes.success +
diff --git a/apps/photos/src/components/FixCreationTime/footer.tsx b/apps/photos/src/components/FixCreationTime/footer.tsx
index 69f26cd878..61c6f572de 100644
--- a/apps/photos/src/components/FixCreationTime/footer.tsx
+++ b/apps/photos/src/components/FixCreationTime/footer.tsx
@@ -1,7 +1,6 @@
-import React from 'react';
-import { Button } from 'react-bootstrap';
-import { t } from 'i18next';
-import { FIX_STATE } from '.';
+import { t } from "i18next";
+import { Button } from "react-bootstrap";
+import { FIX_STATE } from ".";
export default function FixCreationTimeFooter({
fixState,
@@ -12,40 +11,44 @@ export default function FixCreationTimeFooter({
fixState !== FIX_STATE.RUNNING && (
<div
style={{
- width: '100%',
- display: 'flex',
- marginTop: '30px',
- justifyContent: 'space-around',
- }}>
+ width: "100%",
+ display: "flex",
+ marginTop: "30px",
+ justifyContent: "space-around",
+ }}
+ >
{(fixState === FIX_STATE.NOT_STARTED ||
fixState === FIX_STATE.COMPLETED_WITH_ERRORS) && (
<Button
block
- variant={'outline-secondary'}
+ variant={"outline-secondary"}
onClick={() => {
props.hide();
- }}>
- {t('CANCEL')}
+ }}
+ >
+ {t("CANCEL")}
</Button>
)}
{fixState === FIX_STATE.COMPLETED && (
<Button
block
- variant={'outline-secondary'}
- onClick={props.hide}>
- {t('CLOSE')}
+ variant={"outline-secondary"}
+ onClick={props.hide}
+ >
+ {t("CLOSE")}
</Button>
)}
{(fixState === FIX_STATE.NOT_STARTED ||
fixState === FIX_STATE.COMPLETED_WITH_ERRORS) && (
<>
- <div style={{ width: '30px' }} />
+ <div style={{ width: "30px" }} />
<Button
block
- variant={'outline-success'}
- onClick={startFix}>
- {t('FIX_CREATION_TIME')}
+ variant={"outline-success"}
+ onClick={startFix}
+ >
+ {t("FIX_CREATION_TIME")}
</Button>
</>
)}
diff --git a/apps/photos/src/components/FixCreationTime/index.tsx b/apps/photos/src/components/FixCreationTime/index.tsx
index 786d9e0393..fd4022e197 100644
--- a/apps/photos/src/components/FixCreationTime/index.tsx
+++ b/apps/photos/src/components/FixCreationTime/index.tsx
@@ -1,14 +1,14 @@
-import DialogBox from '@ente/shared/components/DialogBox/';
-import React, { useContext, useEffect, useState } from 'react';
-import { updateCreationTimeWithExif } from 'services/updateCreationTimeWithExif';
-import { GalleryContext } from 'pages/gallery';
-import { EnteFile } from 'types/file';
-import FixCreationTimeRunning from './running';
-import FixCreationTimeFooter from './footer';
-import { Formik } from 'formik';
+import DialogBox from "@ente/shared/components/DialogBox/";
+import { Formik } from "formik";
+import { GalleryContext } from "pages/gallery";
+import { useContext, useEffect, useState } from "react";
+import { updateCreationTimeWithExif } from "services/updateCreationTimeWithExif";
+import { EnteFile } from "types/file";
+import FixCreationTimeFooter from "./footer";
+import FixCreationTimeRunning from "./running";
-import FixCreationTimeOptions from './options';
-import { t } from 'i18next';
+import { t } from "i18next";
+import FixCreationTimeOptions from "./options";
export interface FixCreationTimeAttributes {
files: EnteFile[];
}
@@ -42,13 +42,13 @@ function Message({ fixState }: { fixState: FIX_STATE }) {
let message = null;
switch (fixState) {
case FIX_STATE.NOT_STARTED:
- message = t('UPDATE_CREATION_TIME_NOT_STARTED');
+ message = t("UPDATE_CREATION_TIME_NOT_STARTED");
break;
case FIX_STATE.COMPLETED:
- message = t('UPDATE_CREATION_TIME_COMPLETED');
+ message = t("UPDATE_CREATION_TIME_COMPLETED");
break;
case FIX_STATE.COMPLETED_WITH_ERRORS:
- message = t('UPDATE_CREATION_TIME_COMPLETED_WITH_ERROR');
+ message = t("UPDATE_CREATION_TIME_COMPLETED_WITH_ERROR");
break;
}
return message ? <div>{message}</div> : <></>;
@@ -76,7 +76,7 @@ export default function FixCreationTime(props: Props) {
props.attributes.files,
option,
customTime,
- setProgressTracker
+ setProgressTracker,
);
if (!completedWithoutError) {
setFixState(FIX_STATE.COMPLETED);
@@ -100,19 +100,21 @@ export default function FixCreationTime(props: Props) {
attributes={{
title:
fixState === FIX_STATE.RUNNING
- ? t('FIX_CREATION_TIME_IN_PROGRESS')
- : t('FIX_CREATION_TIME'),
+ ? t("FIX_CREATION_TIME_IN_PROGRESS")
+ : t("FIX_CREATION_TIME"),
nonClosable: true,
- }}>
+ }}
+ >
<div
style={{
- marginBottom: '10px',
- display: 'flex',
- flexDirection: 'column',
+ marginBottom: "10px",
+ display: "flex",
+ flexDirection: "column",
...(fixState === FIX_STATE.RUNNING
- ? { alignItems: 'center' }
+ ? { alignItems: "center" }
: {}),
- }}>
+ }}
+ >
<Message fixState={fixState} />
{fixState === FIX_STATE.RUNNING && (
@@ -124,13 +126,14 @@ export default function FixCreationTime(props: Props) {
customTime: new Date(),
}}
validateOnBlur={false}
- onSubmit={onSubmit}>
+ onSubmit={onSubmit}
+ >
{({ values, handleChange, handleSubmit }) => (
<>
{(fixState === FIX_STATE.NOT_STARTED ||
fixState ===
FIX_STATE.COMPLETED_WITH_ERRORS) && (
- <div style={{ marginTop: '10px' }}>
+ <div style={{ marginTop: "10px" }}>
<FixCreationTimeOptions
handleChange={handleChange}
values={values}
diff --git a/apps/photos/src/components/FixCreationTime/options.tsx b/apps/photos/src/components/FixCreationTime/options.tsx
index 99ab8bbdcc..880ea0539c 100644
--- a/apps/photos/src/components/FixCreationTime/options.tsx
+++ b/apps/photos/src/components/FixCreationTime/options.tsx
@@ -1,9 +1,9 @@
-import React, { ChangeEvent } from 'react';
-import { FIX_OPTIONS } from '.';
-import { Form } from 'react-bootstrap';
-import EnteDateTimePicker from 'components/EnteDateTimePicker';
-import { Row, Value } from '@ente/shared/components/Container';
-import { t } from 'i18next';
+import { Row, Value } from "@ente/shared/components/Container";
+import EnteDateTimePicker from "components/EnteDateTimePicker";
+import { t } from "i18next";
+import { ChangeEvent } from "react";
+import { Form } from "react-bootstrap";
+import { FIX_OPTIONS } from ".";
const Option = ({
value,
@@ -19,9 +19,10 @@ const Option = ({
<Form.Check
name="group1"
style={{
- margin: '5px 0',
- color: value !== Number(selected) ? '#aaa' : '#fff',
- }}>
+ margin: "5px 0",
+ color: value !== Number(selected) ? "#aaa" : "#fff",
+ }}
+ >
<Form.Check.Input
id={value.toString()}
type="radio"
@@ -30,8 +31,9 @@ const Option = ({
onChange={onChange}
/>
<Form.Check.Label
- style={{ cursor: 'pointer' }}
- htmlFor={value.toString()}>
+ style={{ cursor: "pointer" }}
+ htmlFor={value.toString()}
+ >
{label}
</Form.Check.Label>
</Form.Check>
@@ -40,36 +42,36 @@ const Option = ({
export default function FixCreationTimeOptions({ handleChange, values }) {
return (
<Form noValidate>
- <Row style={{ margin: '0' }}>
+ <Row style={{ margin: "0" }}>
<Option
value={FIX_OPTIONS.DATE_TIME_ORIGINAL}
- onChange={handleChange('option')}
- label={t('DATE_TIME_ORIGINAL')}
+ onChange={handleChange("option")}
+ label={t("DATE_TIME_ORIGINAL")}
selected={Number(values.option)}
/>
</Row>
- <Row style={{ margin: '0' }}>
+ <Row style={{ margin: "0" }}>
<Option
value={FIX_OPTIONS.DATE_TIME_DIGITIZED}
- onChange={handleChange('option')}
- label={t('DATE_TIME_DIGITIZED')}
+ onChange={handleChange("option")}
+ label={t("DATE_TIME_DIGITIZED")}
selected={Number(values.option)}
/>
</Row>
- <Row style={{ margin: '0' }}>
+ <Row style={{ margin: "0" }}>
<Option
value={FIX_OPTIONS.METADATA_DATE}
- onChange={handleChange('option')}
- label={t('METADATA_DATE')}
+ onChange={handleChange("option")}
+ label={t("METADATA_DATE")}
selected={Number(values.option)}
/>
</Row>
- <Row style={{ margin: '0' }}>
+ <Row style={{ margin: "0" }}>
<Value width="50%">
<Option
value={FIX_OPTIONS.CUSTOM_TIME}
- onChange={handleChange('option')}
- label={t('CUSTOM_TIME')}
+ onChange={handleChange("option")}
+ label={t("CUSTOM_TIME")}
selected={Number(values.option)}
/>
</Value>
@@ -77,7 +79,7 @@ export default function FixCreationTimeOptions({ handleChange, values }) {
<Value width="40%">
<EnteDateTimePicker
onSubmit={(x: Date) =>
- handleChange('customTime')(x.toUTCString())
+ handleChange("customTime")(x.toUTCString())
}
/>
</Value>
diff --git a/apps/photos/src/components/FixCreationTime/running.tsx b/apps/photos/src/components/FixCreationTime/running.tsx
index e7103ede3d..dbceb6c127 100644
--- a/apps/photos/src/components/FixCreationTime/running.tsx
+++ b/apps/photos/src/components/FixCreationTime/running.tsx
@@ -1,30 +1,30 @@
-import { ComfySpan } from 'components/ExportInProgress';
-import React from 'react';
-import { ProgressBar } from 'react-bootstrap';
-import { t } from 'i18next';
+import { ComfySpan } from "components/ExportInProgress";
+import { t } from "i18next";
+import { ProgressBar } from "react-bootstrap";
export default function FixCreationTimeRunning({ progressTracker }) {
return (
<>
- <div style={{ marginBottom: '10px' }}>
+ <div style={{ marginBottom: "10px" }}>
<ComfySpan>
- {' '}
- {progressTracker.current} / {progressTracker.total}{' '}
- </ComfySpan>{' '}
- <span style={{ marginLeft: '10px' }}>
- {' '}
- {t('CREATION_TIME_UPDATED')}
+ {" "}
+ {progressTracker.current} / {progressTracker.total}{" "}
+ </ComfySpan>{" "}
+ <span style={{ marginLeft: "10px" }}>
+ {" "}
+ {t("CREATION_TIME_UPDATED")}
</span>
</div>
<div
style={{
- width: '100%',
- marginTop: '10px',
- marginBottom: '20px',
- }}>
+ width: "100%",
+ marginTop: "10px",
+ marginBottom: "20px",
+ }}
+ >
<ProgressBar
now={Math.round(
- (progressTracker.current * 100) / progressTracker.total
+ (progressTracker.current * 100) / progressTracker.total,
)}
animated={true}
variant="upload-progress-bar"
diff --git a/apps/photos/src/components/FixLargeThumbnail.tsx b/apps/photos/src/components/FixLargeThumbnail.tsx
index 6818ee668a..e62fafda3e 100644
--- a/apps/photos/src/components/FixLargeThumbnail.tsx
+++ b/apps/photos/src/components/FixLargeThumbnail.tsx
@@ -1,14 +1,14 @@
-import DialogBox from '@ente/shared/components/DialogBox/';
-import React, { useEffect, useState } from 'react';
-import { ProgressBar, Button } from 'react-bootstrap';
-import { ComfySpan } from './ExportInProgress';
+import DialogBox from "@ente/shared/components/DialogBox/";
+import { logError } from "@ente/shared/sentry";
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
+import { t } from "i18next";
+import React, { useEffect, useState } from "react";
+import { Button, ProgressBar } from "react-bootstrap";
import {
getLargeThumbnailFiles,
replaceThumbnail,
-} from 'services/migrateThumbnailService';
-import { getData, LS_KEYS, setData } from '@ente/shared/storage/localStorage';
-import { logError } from '@ente/shared/sentry';
-import { t } from 'i18next';
+} from "services/migrateThumbnailService";
+import { ComfySpan } from "./ExportInProgress";
export type SetProgressTracker = React.Dispatch<
React.SetStateAction<{
@@ -34,20 +34,20 @@ function Message({ fixState }: { fixState: FIX_STATE }) {
switch (fixState) {
case FIX_STATE.NOT_STARTED:
case FIX_STATE.FIX_LATER:
- message = t('REPLACE_THUMBNAIL_NOT_STARTED');
+ message = t("REPLACE_THUMBNAIL_NOT_STARTED");
break;
case FIX_STATE.COMPLETED:
- message = t('REPLACE_THUMBNAIL_COMPLETED');
+ message = t("REPLACE_THUMBNAIL_COMPLETED");
break;
case FIX_STATE.NOOP:
- message = t('REPLACE_THUMBNAIL_NOOP');
+ message = t("REPLACE_THUMBNAIL_NOOP");
break;
case FIX_STATE.COMPLETED_WITH_ERRORS:
- message = t('REPLACE_THUMBNAIL_COMPLETED_WITH_ERROR');
+ message = t("REPLACE_THUMBNAIL_COMPLETED_WITH_ERROR");
break;
}
return message ? (
- <div style={{ marginBottom: '30px' }}>{message}</div>
+ <div style={{ marginBottom: "30px" }}>{message}</div>
) : (
<></>
);
@@ -59,7 +59,7 @@ export default function FixLargeThumbnails(props: Props) {
total: 0,
});
const [largeThumbnailFiles, setLargeThumbnailFiles] = useState<number[]>(
- []
+ [],
);
const init = (): FIX_STATE => {
@@ -95,7 +95,7 @@ export default function FixLargeThumbnails(props: Props) {
largeThumbnailFiles.length > 0
) {
updateFixState(FIX_STATE.NOT_STARTED);
- logError(Error(), 'large thumbnail files left after migration');
+ logError(Error(), "large thumbnail files left after migration");
}
if (largeThumbnailFiles.length === 0 && fixState !== FIX_STATE.NOOP) {
updateFixState(FIX_STATE.NOOP);
@@ -118,14 +118,14 @@ export default function FixLargeThumbnails(props: Props) {
const completedWithError = await replaceThumbnail(
setProgressTracker,
new Set(
- newlyFetchedLargeThumbnailFiles ?? largeThumbnailFiles ?? []
- )
+ newlyFetchedLargeThumbnailFiles ?? largeThumbnailFiles ?? [],
+ ),
);
- if (typeof completedWithError !== 'undefined') {
+ if (typeof completedWithError !== "undefined") {
updateFixState(
completedWithError
? FIX_STATE.COMPLETED_WITH_ERRORS
- : FIX_STATE.COMPLETED
+ : FIX_STATE.COMPLETED,
);
}
await fetchLargeThumbnail();
@@ -140,41 +140,44 @@ export default function FixLargeThumbnails(props: Props) {
open={props.isOpen}
onClose={props.hide}
attributes={{
- title: t('COMPRESS_THUMBNAILS'),
- }}>
+ title: t("COMPRESS_THUMBNAILS"),
+ }}
+ >
<div
style={{
- marginBottom: '20px',
- padding: '0 5%',
- display: 'flex',
- alignItems: 'center',
- flexDirection: 'column',
- }}>
+ marginBottom: "20px",
+ padding: "0 5%",
+ display: "flex",
+ alignItems: "center",
+ flexDirection: "column",
+ }}
+ >
<Message fixState={fixState} />
{fixState === FIX_STATE.RUNNING && (
<>
- <div style={{ marginBottom: '10px' }}>
+ <div style={{ marginBottom: "10px" }}>
<ComfySpan>
- {' '}
- {progressTracker.current} /{' '}
- {progressTracker.total}{' '}
- </ComfySpan>{' '}
- <span style={{ marginLeft: '10px' }}>
- {' '}
- {t('THUMBNAIL_REPLACED')}
+ {" "}
+ {progressTracker.current} /{" "}
+ {progressTracker.total}{" "}
+ </ComfySpan>{" "}
+ <span style={{ marginLeft: "10px" }}>
+ {" "}
+ {t("THUMBNAIL_REPLACED")}
</span>
</div>
<div
style={{
- width: '100%',
- marginTop: '10px',
- marginBottom: '20px',
- }}>
+ width: "100%",
+ marginTop: "10px",
+ marginBottom: "20px",
+ }}
+ >
<ProgressBar
now={Math.round(
(progressTracker.current * 100) /
- progressTracker.total
+ progressTracker.total,
)}
animated={true}
variant="upload-progress-bar"
@@ -184,40 +187,44 @@ export default function FixLargeThumbnails(props: Props) {
)}
<div
style={{
- width: '100%',
- display: 'flex',
- justifyContent: 'space-around',
- }}>
+ width: "100%",
+ display: "flex",
+ justifyContent: "space-around",
+ }}
+ >
{fixState === FIX_STATE.NOT_STARTED ||
fixState === FIX_STATE.FIX_LATER ? (
<Button
block
- variant={'outline-secondary'}
+ variant={"outline-secondary"}
onClick={() => {
updateFixState(FIX_STATE.FIX_LATER);
props.hide();
- }}>
- {t('FIX_THUMBNAIL_LATER')}
+ }}
+ >
+ {t("FIX_THUMBNAIL_LATER")}
</Button>
) : (
<Button
block
- variant={'outline-secondary'}
- onClick={props.hide}>
- {t('CLOSE')}
+ variant={"outline-secondary"}
+ onClick={props.hide}
+ >
+ {t("CLOSE")}
</Button>
)}
{(fixState === FIX_STATE.NOT_STARTED ||
fixState === FIX_STATE.FIX_LATER ||
fixState === FIX_STATE.COMPLETED_WITH_ERRORS) && (
<>
- <div style={{ width: '30px' }} />
+ <div style={{ width: "30px" }} />
<Button
block
- variant={'outline-success'}
- onClick={() => startFix()}>
- {t('FIX_THUMBNAIL')}
+ variant={"outline-success"}
+ onClick={() => startFix()}
+ >
+ {t("FIX_THUMBNAIL")}
</Button>
</>
)}
diff --git a/apps/photos/src/components/FullScreenDropZone.tsx b/apps/photos/src/components/FullScreenDropZone.tsx
index 2cd72260ce..8e6a564b71 100644
--- a/apps/photos/src/components/FullScreenDropZone.tsx
+++ b/apps/photos/src/components/FullScreenDropZone.tsx
@@ -1,21 +1,21 @@
-import React, { useEffect, useState, useContext } from 'react';
-import { styled } from '@mui/material';
-import CloseIcon from '@mui/icons-material/Close';
-import { AppContext } from 'pages/_app';
-import { t } from 'i18next';
+import CloseIcon from "@mui/icons-material/Close";
+import { styled } from "@mui/material";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import React, { useContext, useEffect, useState } from "react";
-const CloseButtonWrapper = styled('div')`
+const CloseButtonWrapper = styled("div")`
position: absolute;
top: 10px;
right: 10px;
cursor: pointer;
`;
-const DropDiv = styled('div')`
+const DropDiv = styled("div")`
flex: 1;
display: flex;
flex-direction: column;
`;
-const Overlay = styled('div')`
+const Overlay = styled("div")`
border-width: 8px;
left: 0;
top: 0;
@@ -49,8 +49,8 @@ export default function FullScreenDropZone(props: Props) {
const onDragLeave = () => setIsDragActive(false);
useEffect(() => {
- window.addEventListener('keydown', (event) => {
- if (event.code === 'Escape') {
+ window.addEventListener("keydown", (event) => {
+ if (event.code === "Escape") {
onDragLeave();
}
});
@@ -70,9 +70,9 @@ export default function FullScreenDropZone(props: Props) {
}
};
- addEventListener('drop', handleWatchFolderDrop);
+ addEventListener("drop", handleWatchFolderDrop);
return () => {
- removeEventListener('drop', handleWatchFolderDrop);
+ removeEventListener("drop", handleWatchFolderDrop);
};
}, [appContext.watchFolderView]);
@@ -80,15 +80,16 @@ export default function FullScreenDropZone(props: Props) {
<DropDiv
{...props.getDragAndDropRootProps({
onDragEnter,
- })}>
+ })}
+ >
{isDragActive && (
<Overlay onDrop={onDragLeave} onDragLeave={onDragLeave}>
<CloseButtonWrapper onClick={onDragLeave}>
<CloseIcon />
</CloseButtonWrapper>
{appContext.watchFolderView
- ? t('WATCH_FOLDER_DROPZONE_MESSAGE')
- : t('UPLOAD_DROPZONE_MESSAGE')}
+ ? t("WATCH_FOLDER_DROPZONE_MESSAGE")
+ : t("UPLOAD_DROPZONE_MESSAGE")}
</Overlay>
)}
{props.children}
diff --git a/apps/photos/src/components/GalleryEmptyState.tsx b/apps/photos/src/components/GalleryEmptyState.tsx
index 2d07740e91..399871782a 100644
--- a/apps/photos/src/components/GalleryEmptyState.tsx
+++ b/apps/photos/src/components/GalleryEmptyState.tsx
@@ -1,16 +1,15 @@
-import { Button, Stack, styled, Typography } from '@mui/material';
import {
- VerticallyCentered,
FlexWrapper,
-} from '@ente/shared/components/Container';
-import { Box } from '@mui/material';
-import uploadManager from 'services/upload/uploadManager';
-import AddPhotoAlternateIcon from '@mui/icons-material/AddPhotoAlternateOutlined';
-import FolderIcon from '@mui/icons-material/FolderOutlined';
-import { UploadTypeSelectorIntent } from 'types/gallery';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
-import { EnteLogo } from '@ente/shared/components/EnteLogo';
+ VerticallyCentered,
+} from "@ente/shared/components/Container";
+import { EnteLogo } from "@ente/shared/components/EnteLogo";
+import AddPhotoAlternateIcon from "@mui/icons-material/AddPhotoAlternateOutlined";
+import FolderIcon from "@mui/icons-material/FolderOutlined";
+import { Box, Button, Stack, Typography, styled } from "@mui/material";
+import { t } from "i18next";
+import { Trans } from "react-i18next";
+import uploadManager from "services/upload/uploadManager";
+import { UploadTypeSelectorIntent } from "types/gallery";
const Wrapper = styled(Box)`
display: flex;
@@ -18,7 +17,7 @@ const Wrapper = styled(Box)`
align-items: center;
text-align: center;
`;
-const NonDraggableImage = styled('img')`
+const NonDraggableImage = styled("img")`
pointer-events: none;
`;
@@ -27,11 +26,12 @@ export default function GalleryEmptyState({ openUploader }) {
<Wrapper>
<Stack
sx={{
- flex: 'none',
+ flex: "none",
pt: 1.5,
pb: 1.5,
- }}>
- <VerticallyCentered sx={{ flex: 'none' }}>
+ }}
+ >
+ <VerticallyCentered sx={{ flex: "none" }}>
<Typography variant="h3" color="text.muted" mb={1}>
<Trans
i18nKey="WELCOME_TO_ENTE_HEADING"
@@ -39,11 +39,11 @@ export default function GalleryEmptyState({ openUploader }) {
/>
</Typography>
<Typography variant="h2">
- {t('WELCOME_TO_ENTE_SUBHEADING')}
+ {t("WELCOME_TO_ENTE_SUBHEADING")}
</Typography>
</VerticallyCentered>
<Typography mt={3.5} color="text.muted">
- {t('WHERE_YOUR_BEST_PHOTOS_LIVE')}
+ {t("WHERE_YOUR_BEST_PHOTOS_LIVE")}
</Typography>
</Stack>
<NonDraggableImage
@@ -58,7 +58,7 @@ export default function GalleryEmptyState({ openUploader }) {
style={{
cursor:
!uploadManager.shouldAllowNewUpload() &&
- 'not-allowed',
+ "not-allowed",
}}
color="accent"
onClick={() =>
@@ -70,17 +70,18 @@ export default function GalleryEmptyState({ openUploader }) {
p: 1,
width: 320,
borderRadius: 0.5,
- }}>
+ }}
+ >
<FlexWrapper sx={{ gap: 1 }} justifyContent="center">
<AddPhotoAlternateIcon />
- {t('UPLOAD_FIRST_PHOTO')}
+ {t("UPLOAD_FIRST_PHOTO")}
</FlexWrapper>
</Button>
<Button
style={{
cursor:
!uploadManager.shouldAllowNewUpload() &&
- 'not-allowed',
+ "not-allowed",
}}
onClick={() =>
openUploader(UploadTypeSelectorIntent.import)
@@ -91,10 +92,11 @@ export default function GalleryEmptyState({ openUploader }) {
p: 1,
width: 320,
borderRadius: 0.5,
- }}>
+ }}
+ >
<FlexWrapper sx={{ gap: 1 }} justifyContent="center">
<FolderIcon />
- {t('IMPORT_YOUR_FOLDERS')}
+ {t("IMPORT_YOUR_FOLDERS")}
</FlexWrapper>
</Button>
</VerticallyCentered>
diff --git a/apps/photos/src/components/ItemList.tsx b/apps/photos/src/components/ItemList.tsx
index 8186e72956..613bf58c3c 100644
--- a/apps/photos/src/components/ItemList.tsx
+++ b/apps/photos/src/components/ItemList.tsx
@@ -1,12 +1,12 @@
-import { Box, Tooltip } from '@mui/material';
-import React, { ReactElement } from 'react';
+import { Box, Tooltip } from "@mui/material";
+import memoize from "memoize-one";
+import React, { ReactElement } from "react";
import {
FixedSizeList as List,
ListChildComponentProps,
ListItemKeySelector,
areEqual,
-} from 'react-window';
-import memoize from 'memoize-one';
+} from "react-window";
export interface ItemListProps<T> {
items: T[];
@@ -26,7 +26,7 @@ interface ItemData<T> {
const createItemData: <T>(
renderListItem: (item: T) => JSX.Element,
getItemTitle: (item: T) => string,
- items: T[]
+ items: T[],
) => ItemData<T> = memoize((renderListItem, getItemTitle, items) => ({
renderListItem,
getItemTitle,
@@ -45,7 +45,7 @@ const Row: <T>({
<Tooltip
PopperProps={{
sx: {
- '.MuiTooltip-tooltip.MuiTooltip-tooltip.MuiTooltip-tooltip':
+ ".MuiTooltip-tooltip.MuiTooltip-tooltip.MuiTooltip-tooltip":
{
marginTop: 0,
},
@@ -54,19 +54,20 @@ const Row: <T>({
title={getItemTitle(items[index])}
placement="bottom-start"
enterDelay={300}
- enterNextDelay={100}>
+ enterNextDelay={100}
+ >
<div style={style}>{renderListItem(items[index])}</div>
</Tooltip>
);
},
- areEqual
+ areEqual,
);
export default function ItemList<T>(props: ItemListProps<T>) {
const itemData = createItemData(
props.renderListItem,
props.getItemTitle,
- props.items
+ props.items,
);
const getItemKey: ListItemKeySelector<ItemData<T>> = (index, data) => {
@@ -80,12 +81,13 @@ export default function ItemList<T>(props: ItemListProps<T>) {
itemData={itemData}
height={Math.min(
props.itemSize * props.items.length,
- props.maxHeight
+ props.maxHeight,
)}
- width={'100%'}
+ width={"100%"}
itemSize={props.itemSize}
itemCount={props.items.length}
- itemKey={getItemKey}>
+ itemKey={getItemKey}
+ >
{Row}
</List>
</Box>
diff --git a/apps/photos/src/components/LoadingOverlay.tsx b/apps/photos/src/components/LoadingOverlay.tsx
index 3d75a18480..90869c91ae 100644
--- a/apps/photos/src/components/LoadingOverlay.tsx
+++ b/apps/photos/src/components/LoadingOverlay.tsx
@@ -1,5 +1,5 @@
-import { styled } from '@mui/material';
-export const LoadingOverlay = styled('div')`
+import { styled } from "@mui/material";
+export const LoadingOverlay = styled("div")`
left: 0;
top: 0;
outline: none;
diff --git a/apps/photos/src/components/MachineLearning/ImageViews.tsx b/apps/photos/src/components/MachineLearning/ImageViews.tsx
index 4f9f4344b1..34cbbb8d4b 100644
--- a/apps/photos/src/components/MachineLearning/ImageViews.tsx
+++ b/apps/photos/src/components/MachineLearning/ImageViews.tsx
@@ -1,22 +1,22 @@
-import React, { useState, useEffect } from 'react';
-import { Skeleton, styled } from '@mui/material';
+import { Skeleton, styled } from "@mui/material";
+import { useEffect, useState } from "react";
-import { imageBitmapToBlob } from 'utils/image';
-import { logError } from '@ente/shared/sentry';
-import { cached } from '@ente/shared/storage/cacheStorage/helpers';
-import machineLearningService from 'services/machineLearning/machineLearningService';
-import { LS_KEYS, getData } from '@ente/shared/storage/localStorage';
-import { User } from '@ente/shared/user/types';
-import { addLogLine } from '@ente/shared/logging';
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import { cached } from "@ente/shared/storage/cacheStorage/helpers";
+import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
+import { User } from "@ente/shared/user/types";
+import machineLearningService from "services/machineLearning/machineLearningService";
+import { imageBitmapToBlob } from "utils/image";
-export const FaceCropsRow = styled('div')`
+export const FaceCropsRow = styled("div")`
& > img {
width: 256px;
height: 256px;
}
`;
-export const FaceImagesRow = styled('div')`
+export const FaceImagesRow = styled("div")`
& > img {
width: 112px;
height: 112px;
@@ -45,27 +45,27 @@ export function ImageCacheView(props: {
async () => {
try {
addLogLine(
- 'ImageCacheView: regenerate face crop',
- props.faceID
+ "ImageCacheView: regenerate face crop",
+ props.faceID,
);
return machineLearningService.regenerateFaceCrop(
user.token,
user.id,
- props.faceID
+ props.faceID,
);
} catch (e) {
logError(
e,
- 'ImageCacheView: regenerate face crop failed'
+ "ImageCacheView: regenerate face crop failed",
);
}
- }
+ },
);
}
!didCancel && setImageBlob(blob);
} catch (e) {
- logError(e, 'ImageCacheView useEffect failed');
+ logError(e, "ImageCacheView useEffect failed");
}
}
loadImage();
@@ -113,9 +113,9 @@ export function ImageBlobView(props: { blob: Blob }) {
setImgUrl(props.blob && URL.createObjectURL(props.blob));
} catch (e) {
console.error(
- 'ImageBlobView: can not create object url for blob: ',
+ "ImageBlobView: can not create object url for blob: ",
props.blob,
- e
+ e,
);
}
}, [props.blob]);
diff --git a/apps/photos/src/components/MachineLearning/MLFileDebugView.tsx b/apps/photos/src/components/MachineLearning/MLFileDebugView.tsx
index 4538be5f07..a6c96476b7 100644
--- a/apps/photos/src/components/MachineLearning/MLFileDebugView.tsx
+++ b/apps/photos/src/components/MachineLearning/MLFileDebugView.tsx
@@ -1,22 +1,22 @@
-import React, { useEffect, useRef, useState } from 'react';
-import '@tensorflow/tfjs-backend-webgl';
-import '@tensorflow/tfjs-backend-cpu';
-import arcfaceAlignmentService from 'services/machineLearning/arcfaceAlignmentService';
-import arcfaceCropService from 'services/machineLearning/arcfaceCropService';
-import blazeFaceDetectionService from 'services/machineLearning/blazeFaceDetectionService';
-import { AlignedFace, FaceCrop, ObjectDetection } from 'types/machineLearning';
-import { getMLSyncConfig } from 'utils/machineLearning/config';
+import { addLogLine } from "@ente/shared/logging";
+import "@tensorflow/tfjs-backend-cpu";
+import "@tensorflow/tfjs-backend-webgl";
+import { DEFAULT_ML_SYNC_CONFIG } from "constants/mlConfig";
+import { useEffect, useRef, useState } from "react";
+import arcfaceAlignmentService from "services/machineLearning/arcfaceAlignmentService";
+import arcfaceCropService from "services/machineLearning/arcfaceCropService";
+import blazeFaceDetectionService from "services/machineLearning/blazeFaceDetectionService";
+import imageSceneService from "services/machineLearning/imageSceneService";
+import ssdMobileNetV2Service from "services/machineLearning/ssdMobileNetV2Service";
+import { AlignedFace, FaceCrop, ObjectDetection } from "types/machineLearning";
+import { getMLSyncConfig } from "utils/machineLearning/config";
import {
getAlignedFaceBox,
ibExtractFaceImage,
ibExtractFaceImageUsingTransform,
-} from 'utils/machineLearning/faceAlign';
-import { ibExtractFaceImageFromCrop } from 'utils/machineLearning/faceCrop';
-import { FaceCropsRow, FaceImagesRow, ImageBitmapView } from './ImageViews';
-import ssdMobileNetV2Service from 'services/machineLearning/ssdMobileNetV2Service';
-import { DEFAULT_ML_SYNC_CONFIG } from 'constants/mlConfig';
-import imageSceneService from 'services/machineLearning/imageSceneService';
-import { addLogLine } from '@ente/shared/logging';
+} from "utils/machineLearning/faceAlign";
+import { ibExtractFaceImageFromCrop } from "utils/machineLearning/faceCrop";
+import { FaceCropsRow, FaceImagesRow, ImageBitmapView } from "./ImageViews";
interface MLFileDebugViewProps {
file: File;
@@ -24,34 +24,34 @@ interface MLFileDebugViewProps {
function drawFaceDetection(face: AlignedFace, ctx: CanvasRenderingContext2D) {
const pointSize = Math.ceil(
- Math.max(ctx.canvas.width / 512, face.detection.box.width / 32)
+ Math.max(ctx.canvas.width / 512, face.detection.box.width / 32),
);
ctx.save();
- ctx.strokeStyle = 'rgba(255, 0, 0, 0.8)';
+ ctx.strokeStyle = "rgba(255, 0, 0, 0.8)";
ctx.lineWidth = pointSize;
ctx.strokeRect(
face.detection.box.x,
face.detection.box.y,
face.detection.box.width,
- face.detection.box.height
+ face.detection.box.height,
);
ctx.restore();
ctx.save();
- ctx.strokeStyle = 'rgba(0, 255, 0, 0.8)';
+ ctx.strokeStyle = "rgba(0, 255, 0, 0.8)";
ctx.lineWidth = Math.round(pointSize * 1.5);
const alignedBox = getAlignedFaceBox(face.alignment);
ctx.strokeRect(
alignedBox.x,
alignedBox.y,
alignedBox.width,
- alignedBox.height
+ alignedBox.height,
);
ctx.restore();
ctx.save();
- ctx.fillStyle = 'rgba(0, 0, 255, 0.8)';
+ ctx.fillStyle = "rgba(0, 0, 255, 0.8)";
face.detection.landmarks.forEach((l) => {
ctx.beginPath();
ctx.arc(l.x, l.y, pointSize, 0, Math.PI * 2, true);
@@ -61,18 +61,18 @@ function drawFaceDetection(face: AlignedFace, ctx: CanvasRenderingContext2D) {
}
function drawBbox(object: ObjectDetection, ctx: CanvasRenderingContext2D) {
- ctx.font = '100px Arial';
+ ctx.font = "100px Arial";
ctx.save();
ctx.restore();
ctx.rect(...object.bbox);
ctx.lineWidth = 10;
- ctx.strokeStyle = 'green';
- ctx.fillStyle = 'green';
+ ctx.strokeStyle = "green";
+ ctx.fillStyle = "green";
ctx.stroke();
ctx.fillText(
- object.score.toFixed(3) + ' ' + object.class,
+ object.score.toFixed(3) + " " + object.class,
object.bbox[0],
- object.bbox[1] > 10 ? object.bbox[1] - 5 : 10
+ object.bbox[1] > 10 ? object.bbox[1] - 5 : 10,
);
}
@@ -93,28 +93,28 @@ export default function MLFileDebugView(props: MLFileDebugViewProps) {
const imageBitmap = await createImageBitmap(props.file);
const faceDetections =
await blazeFaceDetectionService.detectFaces(imageBitmap);
- addLogLine('detectedFaces: ', faceDetections.length);
+ addLogLine("detectedFaces: ", faceDetections.length);
const objectDetections = await ssdMobileNetV2Service.detectObjects(
imageBitmap,
DEFAULT_ML_SYNC_CONFIG.objectDetection.maxNumBoxes,
- DEFAULT_ML_SYNC_CONFIG.objectDetection.minScore
+ DEFAULT_ML_SYNC_CONFIG.objectDetection.minScore,
);
- addLogLine('detectedObjects: ', JSON.stringify(objectDetections));
+ addLogLine("detectedObjects: ", JSON.stringify(objectDetections));
const sceneDetections = await imageSceneService.detectScenes(
imageBitmap,
- DEFAULT_ML_SYNC_CONFIG.sceneDetection.minScore
+ DEFAULT_ML_SYNC_CONFIG.sceneDetection.minScore,
);
- addLogLine('detectedScenes: ', JSON.stringify(sceneDetections));
+ addLogLine("detectedScenes: ", JSON.stringify(sceneDetections));
const mlSyncConfig = await getMLSyncConfig();
const faceCropPromises = faceDetections.map(async (faceDetection) =>
arcfaceCropService.getFaceCrop(
imageBitmap,
faceDetection,
- mlSyncConfig.faceCrop
- )
+ mlSyncConfig.faceCrop,
+ ),
);
const faceCrops = await Promise.all(faceCropPromises);
@@ -122,14 +122,14 @@ export default function MLFileDebugView(props: MLFileDebugViewProps) {
setFaceCrops(faceCrops);
const faceAlignments = faceDetections.map((detection) =>
- arcfaceAlignmentService.getFaceAlignment(detection)
+ arcfaceAlignmentService.getFaceAlignment(detection),
);
- addLogLine('alignedFaces: ', JSON.stringify(faceAlignments));
+ addLogLine("alignedFaces: ", JSON.stringify(faceAlignments));
const canvas: HTMLCanvasElement = canvasRef.current;
canvas.width = imageBitmap.width;
canvas.height = imageBitmap.height;
- const ctx = canvas.getContext('2d');
+ const ctx = canvas.getContext("2d");
if (didCancel) return;
ctx.drawImage(imageBitmap, 0, 0);
const alignedFaces = faceAlignments.map((alignment, i) => {
@@ -139,7 +139,7 @@ export default function MLFileDebugView(props: MLFileDebugViewProps) {
} as AlignedFace;
});
alignedFaces.forEach((alignedFace) =>
- drawFaceDetection(alignedFace, ctx)
+ drawFaceDetection(alignedFace, ctx),
);
objectDetections.forEach((object) => drawBbox(object, ctx));
@@ -149,23 +149,23 @@ export default function MLFileDebugView(props: MLFileDebugViewProps) {
return ibExtractFaceImageFromCrop(
faceCrops[i],
face.alignment,
- 112
+ 112,
);
- })
+ }),
);
const facesUsingImage = await Promise.all(
alignedFaces.map((face) => {
return ibExtractFaceImage(imageBitmap, face.alignment, 112);
- })
+ }),
);
const facesUsingTransform = await Promise.all(
alignedFaces.map((face) => {
return ibExtractFaceImageUsingTransform(
imageBitmap,
face.alignment,
- 112
+ 112,
);
- })
+ }),
);
if (didCancel) return;
@@ -188,7 +188,7 @@ export default function MLFileDebugView(props: MLFileDebugViewProps) {
ref={canvasRef}
width={0}
height={0}
- style={{ maxWidth: '100%' }}
+ style={{ maxWidth: "100%" }}
/>
<p></p>
<div>Face Crops:</div>
@@ -196,7 +196,8 @@ export default function MLFileDebugView(props: MLFileDebugViewProps) {
{faceCrops?.map((faceCrop, i) => (
<ImageBitmapView
key={i}
- image={faceCrop.image}></ImageBitmapView>
+ image={faceCrop.image}
+ ></ImageBitmapView>
))}
</FaceCropsRow>
diff --git a/apps/photos/src/components/MachineLearning/MLSearchSettings/enableFaceSearch.tsx b/apps/photos/src/components/MachineLearning/MLSearchSettings/enableFaceSearch.tsx
index 778271718e..4691446396 100644
--- a/apps/photos/src/components/MachineLearning/MLSearchSettings/enableFaceSearch.tsx
+++ b/apps/photos/src/components/MachineLearning/MLSearchSettings/enableFaceSearch.tsx
@@ -1,19 +1,19 @@
+import { FACE_SEARCH_PRIVACY_POLICY_LINK } from "@ente/shared/constants/urls";
import {
- Stack,
Button,
- FormGroup,
Checkbox,
- FormControlLabel,
DialogProps,
- Typography,
+ FormControlLabel,
+ FormGroup,
Link,
-} from '@mui/material';
-import { EnteDrawer } from 'components/EnteDrawer';
-import Titlebar from 'components/Titlebar';
-import { FACE_SEARCH_PRIVACY_POLICY_LINK } from '@ente/shared/constants/urls';
-import { useEffect, useState } from 'react';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
+ Stack,
+ Typography,
+} from "@mui/material";
+import { EnteDrawer } from "components/EnteDrawer";
+import Titlebar from "components/Titlebar";
+import { t } from "i18next";
+import { useEffect, useState } from "react";
+import { Trans } from "react-i18next";
export default function EnableFaceSearch({
open,
onClose,
@@ -31,8 +31,8 @@ export default function EnableFaceSearch({
onRootClose();
};
- const handleDrawerClose: DialogProps['onClose'] = (_, reason) => {
- if (reason === 'backdropClick') {
+ const handleDrawerClose: DialogProps["onClose"] = (_, reason) => {
+ if (reason === "backdropClick") {
handleRootClose();
} else {
onClose();
@@ -44,37 +44,38 @@ export default function EnableFaceSearch({
open={open}
onClose={handleDrawerClose}
BackdropProps={{
- sx: { '&&&': { backgroundColor: 'transparent' } },
- }}>
- <Stack spacing={'4px'} py={'12px'}>
+ sx: { "&&&": { backgroundColor: "transparent" } },
+ }}
+ >
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={onClose}
- title={t('ENABLE_FACE_SEARCH_TITLE')}
+ title={t("ENABLE_FACE_SEARCH_TITLE")}
onRootClose={handleRootClose}
/>
- <Stack py={'20px'} px={'8px'} spacing={'32px'}>
- <Typography color="text.muted" px={'8px'}>
+ <Stack py={"20px"} px={"8px"} spacing={"32px"}>
+ <Typography color="text.muted" px={"8px"}>
<Trans
- i18nKey={'ENABLE_FACE_SEARCH_DESCRIPTION'}
+ i18nKey={"ENABLE_FACE_SEARCH_DESCRIPTION"}
components={{
a: (
<Link
- target={'_blank'}
+ target={"_blank"}
href={FACE_SEARCH_PRIVACY_POLICY_LINK}
underline="always"
sx={{
- color: 'inherit',
- textDecorationColor: 'inherit',
+ color: "inherit",
+ textDecorationColor: "inherit",
}}
/>
),
}}
/>
</Typography>
- <FormGroup sx={{ width: '100%' }}>
+ <FormGroup sx={{ width: "100%" }}>
<FormControlLabel
sx={{
- color: 'text.muted',
+ color: "text.muted",
ml: 0,
mt: 2,
}}
@@ -87,22 +88,24 @@ export default function EnableFaceSearch({
}
/>
}
- label={t('FACE_SEARCH_CONFIRMATION')}
+ label={t("FACE_SEARCH_CONFIRMATION")}
/>
</FormGroup>
- <Stack px={'8px'} spacing={'8px'}>
+ <Stack px={"8px"} spacing={"8px"}>
<Button
- color={'accent'}
+ color={"accent"}
size="large"
disabled={!acceptTerms}
- onClick={enableFaceSearch}>
- {t('ENABLE_FACE_SEARCH')}
+ onClick={enableFaceSearch}
+ >
+ {t("ENABLE_FACE_SEARCH")}
</Button>
<Button
- color={'secondary'}
+ color={"secondary"}
size="large"
- onClick={onClose}>
- {t('CANCEL')}
+ onClick={onClose}
+ >
+ {t("CANCEL")}
</Button>
</Stack>
</Stack>
diff --git a/apps/photos/src/components/MachineLearning/MLSearchSettings/enableMLSearch.tsx b/apps/photos/src/components/MachineLearning/MLSearchSettings/enableMLSearch.tsx
index 0d654b8412..9abed5a231 100644
--- a/apps/photos/src/components/MachineLearning/MLSearchSettings/enableMLSearch.tsx
+++ b/apps/photos/src/components/MachineLearning/MLSearchSettings/enableMLSearch.tsx
@@ -1,9 +1,9 @@
-import { Stack, Box, Button, Typography } from '@mui/material';
-import Titlebar from 'components/Titlebar';
-import { ML_BLOG_LINK } from '@ente/shared/constants/urls';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
-import { openLink } from 'utils/common';
+import { ML_BLOG_LINK } from "@ente/shared/constants/urls";
+import { Box, Button, Stack, Typography } from "@mui/material";
+import Titlebar from "components/Titlebar";
+import { t } from "i18next";
+import { Trans } from "react-i18next";
+import { openLink } from "utils/common";
export default function EnableMLSearch({
onClose,
@@ -11,31 +11,33 @@ export default function EnableMLSearch({
onRootClose,
}) {
return (
- <Stack spacing={'4px'} py={'12px'}>
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={onClose}
- title={t('ML_SEARCH')}
+ title={t("ML_SEARCH")}
onRootClose={onRootClose}
/>
- <Stack py={'20px'} px={'8px'} spacing={'32px'}>
- <Box px={'8px'}>
- {' '}
+ <Stack py={"20px"} px={"8px"} spacing={"32px"}>
+ <Box px={"8px"}>
+ {" "}
<Typography color="text.muted">
- <Trans i18nKey={'ENABLE_ML_SEARCH_DESCRIPTION'} />
+ <Trans i18nKey={"ENABLE_ML_SEARCH_DESCRIPTION"} />
</Typography>
</Box>
- <Stack px={'8px'} spacing={'8px'}>
+ <Stack px={"8px"} spacing={"8px"}>
<Button
- color={'accent'}
+ color={"accent"}
size="large"
- onClick={enableMlSearch}>
- {t('ENABLE')}
+ onClick={enableMlSearch}
+ >
+ {t("ENABLE")}
</Button>
<Button
- color={'secondary'}
+ color={"secondary"}
size="large"
- onClick={() => openLink(ML_BLOG_LINK, true)}>
- {t('ML_MORE_DETAILS')}
+ onClick={() => openLink(ML_BLOG_LINK, true)}
+ >
+ {t("ML_MORE_DETAILS")}
</Button>
</Stack>
</Stack>
diff --git a/apps/photos/src/components/MachineLearning/MLSearchSettings/index.tsx b/apps/photos/src/components/MachineLearning/MLSearchSettings/index.tsx
index 0953496e5b..b1da26a659 100644
--- a/apps/photos/src/components/MachineLearning/MLSearchSettings/index.tsx
+++ b/apps/photos/src/components/MachineLearning/MLSearchSettings/index.tsx
@@ -1,17 +1,17 @@
-import { Box, DialogProps, Typography } from '@mui/material';
-import { EnteDrawer } from 'components/EnteDrawer';
-import { AppContext } from 'pages/_app';
-import { useContext, useState } from 'react';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
+import { logError } from "@ente/shared/sentry";
+import { Box, DialogProps, Typography } from "@mui/material";
+import { EnteDrawer } from "components/EnteDrawer";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext, useState } from "react";
+import { Trans } from "react-i18next";
import {
getFaceSearchEnabledStatus,
updateFaceSearchEnabledStatus,
-} from 'services/userService';
-import { logError } from '@ente/shared/sentry';
-import EnableFaceSearch from './enableFaceSearch';
-import EnableMLSearch from './enableMLSearch';
-import ManageMLSearch from './manageMLSearch';
+} from "services/userService";
+import EnableFaceSearch from "./enableFaceSearch";
+import EnableMLSearch from "./enableMLSearch";
+import ManageMLSearch from "./manageMLSearch";
const MLSearchSettings = ({ open, onClose, onRootClose }) => {
const {
@@ -41,7 +41,7 @@ const MLSearchSettings = ({ open, onClose, onRootClose }) => {
updateMlSearchEnabled(true);
}
} catch (e) {
- logError(e, 'Enable ML search failed');
+ logError(e, "Enable ML search failed");
somethingWentWrong();
}
};
@@ -54,7 +54,7 @@ const MLSearchSettings = ({ open, onClose, onRootClose }) => {
closeEnableFaceSearch();
finishLoading();
} catch (e) {
- logError(e, 'Enable face search failed');
+ logError(e, "Enable face search failed");
somethingWentWrong();
}
};
@@ -64,7 +64,7 @@ const MLSearchSettings = ({ open, onClose, onRootClose }) => {
await updateMlSearchEnabled(false);
onClose();
} catch (e) {
- logError(e, 'Disable ML search failed');
+ logError(e, "Disable ML search failed");
somethingWentWrong();
}
};
@@ -76,23 +76,23 @@ const MLSearchSettings = ({ open, onClose, onRootClose }) => {
await disableMlSearch();
finishLoading();
} catch (e) {
- logError(e, 'Disable face search failed');
+ logError(e, "Disable face search failed");
somethingWentWrong();
}
};
const confirmDisableFaceSearch = () => {
setDialogMessage({
- title: t('DISABLE_FACE_SEARCH_TITLE'),
+ title: t("DISABLE_FACE_SEARCH_TITLE"),
content: (
<Typography>
- <Trans i18nKey={'DISABLE_FACE_SEARCH_DESCRIPTION'} />
+ <Trans i18nKey={"DISABLE_FACE_SEARCH_DESCRIPTION"} />
</Typography>
),
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
proceed: {
- variant: 'primary',
- text: t('DISABLE_FACE_SEARCH'),
+ variant: "primary",
+ text: t("DISABLE_FACE_SEARCH"),
action: disableFaceSearch,
},
});
@@ -103,8 +103,8 @@ const MLSearchSettings = ({ open, onClose, onRootClose }) => {
onRootClose();
};
- const handleDrawerClose: DialogProps['onClose'] = (_, reason) => {
- if (reason === 'backdropClick') {
+ const handleDrawerClose: DialogProps["onClose"] = (_, reason) => {
+ if (reason === "backdropClick") {
handleRootClose();
} else {
onClose();
@@ -119,8 +119,9 @@ const MLSearchSettings = ({ open, onClose, onRootClose }) => {
open={open}
onClose={handleDrawerClose}
BackdropProps={{
- sx: { '&&&': { backgroundColor: 'transparent' } },
- }}>
+ sx: { "&&&": { backgroundColor: "transparent" } },
+ }}
+ >
{mlSearchEnabled ? (
<ManageMLSearch
onClose={onClose}
diff --git a/apps/photos/src/components/MachineLearning/MLSearchSettings/manageMLSearch.tsx b/apps/photos/src/components/MachineLearning/MLSearchSettings/manageMLSearch.tsx
index acc416aeb8..15dacd7b25 100644
--- a/apps/photos/src/components/MachineLearning/MLSearchSettings/manageMLSearch.tsx
+++ b/apps/photos/src/components/MachineLearning/MLSearchSettings/manageMLSearch.tsx
@@ -1,8 +1,8 @@
-import { Stack, Box } from '@mui/material';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import Titlebar from 'components/Titlebar';
-import { t } from 'i18next';
+import { Box, Stack } from "@mui/material";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import Titlebar from "components/Titlebar";
+import { t } from "i18next";
export default function ManageMLSearch({
onClose,
@@ -11,24 +11,24 @@ export default function ManageMLSearch({
onRootClose,
}) {
return (
- <Stack spacing={'4px'} py={'12px'}>
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={onClose}
- title={t('ML_SEARCH')}
+ title={t("ML_SEARCH")}
onRootClose={onRootClose}
/>
- <Box px={'16px'}>
- <Stack py={'20px'} spacing={'24px'}>
+ <Box px={"16px"}>
+ <Stack py={"20px"} spacing={"24px"}>
<MenuItemGroup>
<EnteMenuItem
onClick={disableMlSearch}
- label={t('DISABLE_BETA')}
+ label={t("DISABLE_BETA")}
/>
</MenuItemGroup>
<MenuItemGroup>
<EnteMenuItem
onClick={handleDisableFaceSearch}
- label={t('DISABLE_FACE_SEARCH')}
+ label={t("DISABLE_FACE_SEARCH")}
/>
</MenuItemGroup>
</Stack>
diff --git a/apps/photos/src/components/MachineLearning/MLServiceFileInfoButton.tsx b/apps/photos/src/components/MachineLearning/MLServiceFileInfoButton.tsx
index 6aaf2095c2..8146e239de 100644
--- a/apps/photos/src/components/MachineLearning/MLServiceFileInfoButton.tsx
+++ b/apps/photos/src/components/MachineLearning/MLServiceFileInfoButton.tsx
@@ -1,8 +1,8 @@
-import React, { useState } from 'react';
-import { Button, Spinner } from 'react-bootstrap';
-import { EnteFile } from 'types/file';
-import { getToken, getUserID } from '@ente/shared/storage/localStorage/helpers';
-import mlService from '../../services/machineLearning/machineLearningService';
+import { getToken, getUserID } from "@ente/shared/storage/localStorage/helpers";
+import { useState } from "react";
+import { Button, Spinner } from "react-bootstrap";
+import { EnteFile } from "types/file";
+import mlService from "../../services/machineLearning/machineLearningService";
function MLServiceFileInfoButton({
file,
@@ -30,22 +30,24 @@ function MLServiceFileInfoButton({
return (
<div
style={{
- marginTop: '18px',
- }}>
+ marginTop: "18px",
+ }}
+ >
<Button
onClick={runMLService}
disabled={mlServiceRunning}
- variant={mlServiceRunning ? 'secondary' : 'primary'}>
+ variant={mlServiceRunning ? "secondary" : "primary"}
+ >
{!mlServiceRunning ? (
- 'Run ML Service'
+ "Run ML Service"
) : (
<>
- ML Service Running{' '}
+ ML Service Running{" "}
<Spinner
animation="border"
size="sm"
style={{
- marginLeft: '5px',
+ marginLeft: "5px",
}}
/>
</>
diff --git a/apps/photos/src/components/MachineLearning/ObjectList.tsx b/apps/photos/src/components/MachineLearning/ObjectList.tsx
index 8051cae668..f22ccc06f8 100644
--- a/apps/photos/src/components/MachineLearning/ObjectList.tsx
+++ b/apps/photos/src/components/MachineLearning/ObjectList.tsx
@@ -1,10 +1,10 @@
-import Box from '@mui/material/Box';
-import { Chip } from 'components/Chip';
-import { Legend } from 'components/PhotoViewer/styledComponents/Legend';
-import React, { useState, useEffect } from 'react';
-import { t } from 'i18next';
-import { EnteFile } from 'types/file';
-import mlIDbStorage from 'utils/storage/mlIDbStorage';
+import Box from "@mui/material/Box";
+import { Chip } from "components/Chip";
+import { Legend } from "components/PhotoViewer/styledComponents/Legend";
+import { t } from "i18next";
+import { useEffect, useState } from "react";
+import { EnteFile } from "types/file";
+import mlIDbStorage from "utils/storage/mlIDbStorage";
export function ObjectLabelList(props: {
file: EnteFile;
@@ -18,8 +18,8 @@ export function ObjectLabelList(props: {
const uniqueObjectNames = [
...new Set(
(objects.get(props.file.id) ?? []).map(
- (object) => object.detection.class
- )
+ (object) => object.detection.class,
+ ),
),
];
!didCancel && setObjects(uniqueObjectNames);
@@ -34,13 +34,14 @@ export function ObjectLabelList(props: {
return (
<div>
- <Legend sx={{ pb: 1, display: 'block' }}>{t('OBJECTS')}</Legend>
+ <Legend sx={{ pb: 1, display: "block" }}>{t("OBJECTS")}</Legend>
<Box
- display={'flex'}
+ display={"flex"}
gap={1}
flexWrap="wrap"
- justifyContent={'flex-start'}
- alignItems={'flex-start'}>
+ justifyContent={"flex-start"}
+ alignItems={"flex-start"}
+ >
{objects.map((object) => (
<Chip key={object}>{object}</Chip>
))}
diff --git a/apps/photos/src/components/MachineLearning/PeopleList.tsx b/apps/photos/src/components/MachineLearning/PeopleList.tsx
index 3c7b3a97b0..fe7d323bbf 100644
--- a/apps/photos/src/components/MachineLearning/PeopleList.tsx
+++ b/apps/photos/src/components/MachineLearning/PeopleList.tsx
@@ -1,20 +1,20 @@
-import React, { useState, useEffect } from 'react';
-import { Face, Person } from 'types/machineLearning';
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import { CACHES } from "@ente/shared/storage/cacheStorage/constants";
+import { styled } from "@mui/material";
+import { Legend } from "components/PhotoViewer/styledComponents/Legend";
+import { t } from "i18next";
+import React, { useEffect, useState } from "react";
+import { EnteFile } from "types/file";
+import { Face, Person } from "types/machineLearning";
import {
getAllPeople,
getPeopleList,
getUnidentifiedFaces,
-} from 'utils/machineLearning';
-import { styled } from '@mui/material';
-import { EnteFile } from 'types/file';
-import { ImageCacheView } from './ImageViews';
-import { CACHES } from '@ente/shared/storage/cacheStorage/constants';
-import { Legend } from 'components/PhotoViewer/styledComponents/Legend';
-import { addLogLine } from '@ente/shared/logging';
-import { logError } from '@ente/shared/sentry';
-import { t } from 'i18next';
-
-const FaceChipContainer = styled('div')`
+} from "utils/machineLearning";
+import { ImageCacheView } from "./ImageViews";
+
+const FaceChipContainer = styled("div")`
display: flex;
flex-wrap: wrap;
justify-content: center;
@@ -24,14 +24,14 @@ const FaceChipContainer = styled('div')`
overflow: auto;
`;
-const FaceChip = styled('div')<{ clickable?: boolean }>`
+const FaceChip = styled("div")<{ clickable?: boolean }>`
width: 112px;
height: 112px;
margin: 5px;
border-radius: 50%;
overflow: hidden;
position: relative;
- cursor: ${({ clickable }) => (clickable ? 'pointer' : 'normal')};
+ cursor: ${({ clickable }) => (clickable ? "pointer" : "normal")};
& > img {
width: 100%;
height: 100%;
@@ -54,14 +54,16 @@ export const PeopleList = React.memo((props: PeopleListProps) => {
props.maxRows && {
maxHeight: props.maxRows * 122 + 28,
}
- }>
+ }
+ >
{props.people.map((person, index) => (
<FaceChip
key={person.id}
clickable={!!props.onSelect}
onClick={() =>
props.onSelect && props.onSelect(person, index)
- }>
+ }
+ >
<ImageCacheView
url={person.displayImageUrl}
cacheName={CACHES.FACE_CROPS}
@@ -85,11 +87,11 @@ export function PhotoPeopleList(props: PhotoPeopleListProps) {
let didCancel = false;
async function updateFaceImages() {
- addLogLine('calling getPeopleList');
+ addLogLine("calling getPeopleList");
const startTime = Date.now();
const people = await getPeopleList(props.file);
- addLogLine('getPeopleList', Date.now() - startTime, 'ms');
- addLogLine('getPeopleList done, didCancel: ', didCancel);
+ addLogLine("getPeopleList", Date.now() - startTime, "ms");
+ addLogLine("getPeopleList done, didCancel: ", didCancel);
!didCancel && setPeople(people);
}
@@ -104,7 +106,7 @@ export function PhotoPeopleList(props: PhotoPeopleListProps) {
return (
<div>
- <Legend>{t('PEOPLE')}</Legend>
+ <Legend>{t("PEOPLE")}</Legend>
<PeopleList people={people} onSelect={props.onSelect}></PeopleList>
</div>
);
@@ -128,7 +130,7 @@ export function AllPeopleList(props: AllPeopleListProps) {
}
!didCancel && setPeople(people);
} catch (e) {
- logError(e, 'updateFaceImages failed');
+ logError(e, "updateFaceImages failed");
}
}
updateFaceImages();
@@ -166,7 +168,7 @@ export function UnidentifiedFaces(props: {
return (
<>
<div>
- <Legend>{t('UNIDENTIFIED_FACES')}</Legend>
+ <Legend>{t("UNIDENTIFIED_FACES")}</Legend>
</div>
<FaceChipContainer>
{faces &&
diff --git a/apps/photos/src/components/MachineLearning/TFJSImage.tsx b/apps/photos/src/components/MachineLearning/TFJSImage.tsx
index 88cad04d81..84e2618130 100644
--- a/apps/photos/src/components/MachineLearning/TFJSImage.tsx
+++ b/apps/photos/src/components/MachineLearning/TFJSImage.tsx
@@ -1,6 +1,6 @@
-import React, { useEffect, useRef } from 'react';
-import * as tf from '@tensorflow/tfjs-core';
-import { FaceImage } from 'types/machineLearning';
+import * as tf from "@tensorflow/tfjs-core";
+import { useEffect, useRef } from "react";
+import { FaceImage } from "types/machineLearning";
interface FaceImageProps {
faceImage: FaceImage;
@@ -33,7 +33,7 @@ export default function TFJSImage(props: FaceImageProps) {
ref={canvasRef}
width={112}
height={112}
- style={{ display: 'inline' }}
+ style={{ display: "inline" }}
/>
);
}
diff --git a/apps/photos/src/components/MemberSubscriptionManage.tsx b/apps/photos/src/components/MemberSubscriptionManage.tsx
index 74612c4ef9..b9da0e6a0a 100644
--- a/apps/photos/src/components/MemberSubscriptionManage.tsx
+++ b/apps/photos/src/components/MemberSubscriptionManage.tsx
@@ -1,21 +1,21 @@
-import { Box, Button, Dialog, DialogContent, Typography } from '@mui/material';
import {
- VerticallyCentered,
FlexWrapper,
-} from '@ente/shared/components/Container';
-import { AppContext } from 'pages/_app';
-import React, { useContext, useEffect } from 'react';
-import billingService from 'services/billingService';
-import { getFamilyPlanAdmin } from 'utils/user/family';
-import { preloadImage } from 'utils/common';
-import DialogTitleWithCloseButton from '@ente/shared/components/DialogBox/TitleWithCloseButton';
-import { t } from 'i18next';
+ VerticallyCentered,
+} from "@ente/shared/components/Container";
+import DialogTitleWithCloseButton from "@ente/shared/components/DialogBox/TitleWithCloseButton";
+import { Box, Button, Dialog, DialogContent, Typography } from "@mui/material";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext, useEffect } from "react";
+import billingService from "services/billingService";
+import { preloadImage } from "utils/common";
+import { getFamilyPlanAdmin } from "utils/user/family";
export function MemberSubscriptionManage({ open, userDetails, onClose }) {
const { setDialogMessage, isMobile } = useContext(AppContext);
useEffect(() => {
- preloadImage('/images/family-plan');
+ preloadImage("/images/family-plan");
}, []);
async function onLeaveFamilyClick() {
@@ -23,23 +23,23 @@ export function MemberSubscriptionManage({ open, userDetails, onClose }) {
await billingService.leaveFamily();
} catch (e) {
setDialogMessage({
- title: t('ERROR'),
- close: { variant: 'critical' },
- content: t('UNKNOWN_ERROR'),
+ title: t("ERROR"),
+ close: { variant: "critical" },
+ content: t("UNKNOWN_ERROR"),
});
}
}
const confirmLeaveFamily = () =>
setDialogMessage({
- title: t('LEAVE_FAMILY_PLAN}'),
- content: t('LEAVE_FAMILY_CONFIRM'),
+ title: t("LEAVE_FAMILY_PLAN}"),
+ content: t("LEAVE_FAMILY_CONFIRM"),
proceed: {
- text: t('LEAVE'),
+ text: t("LEAVE"),
action: onLeaveFamilyClick,
- variant: 'critical',
+ variant: "critical",
},
close: {
- text: t('CANCEL'),
+ text: t("CANCEL"),
},
});
@@ -53,18 +53,19 @@ export function MemberSubscriptionManage({ open, userDetails, onClose }) {
open={open}
onClose={onClose}
maxWidth="xs"
- fullScreen={isMobile}>
+ fullScreen={isMobile}
+ >
<DialogTitleWithCloseButton onClose={onClose}>
- <Typography variant="h3" fontWeight={'bold'}>
- {t('SUBSCRIPTION')}
+ <Typography variant="h3" fontWeight={"bold"}>
+ {t("SUBSCRIPTION")}
</Typography>
- <Typography color={'text.muted'}>{t('FAMILY_PLAN')}</Typography>
+ <Typography color={"text.muted"}>{t("FAMILY_PLAN")}</Typography>
</DialogTitleWithCloseButton>
<DialogContent>
<VerticallyCentered>
<Box mb={4}>
<Typography color="text.muted">
- {t('FAMILY_SUBSCRIPTION_INFO')}
+ {t("FAMILY_SUBSCRIPTION_INFO")}
</Typography>
<Typography>
{getFamilyPlanAdmin(userDetails.familyData)?.email}
@@ -82,8 +83,9 @@ export function MemberSubscriptionManage({ open, userDetails, onClose }) {
size="large"
variant="outlined"
color="critical"
- onClick={confirmLeaveFamily}>
- {t('LEAVE_FAMILY_PLAN')}
+ onClick={confirmLeaveFamily}
+ >
+ {t("LEAVE_FAMILY_PLAN")}
</Button>
</FlexWrapper>
</VerticallyCentered>
diff --git a/apps/photos/src/components/Menu/EnteMenuItem.tsx b/apps/photos/src/components/Menu/EnteMenuItem.tsx
index e437ef50ea..21a9889afa 100644
--- a/apps/photos/src/components/Menu/EnteMenuItem.tsx
+++ b/apps/photos/src/components/Menu/EnteMenuItem.tsx
@@ -1,30 +1,30 @@
import {
- MenuItem,
- ButtonProps,
+ SpaceBetweenFlex,
+ VerticallyCenteredFlex,
+} from "@ente/shared/components/Container";
+import {
Box,
+ ButtonProps,
+ MenuItem,
Typography,
TypographyProps,
-} from '@mui/material';
-import { CaptionedText } from 'components/CaptionedText';
-import PublicShareSwitch from 'components/Collections/CollectionShare/publicShare/switch';
-import {
- SpaceBetweenFlex,
- VerticallyCenteredFlex,
-} from '@ente/shared/components/Container';
-import React from 'react';
-import ChangeDirectoryOption from 'components/Directory/changeOption';
+} from "@mui/material";
+import { CaptionedText } from "components/CaptionedText";
+import PublicShareSwitch from "components/Collections/CollectionShare/publicShare/switch";
+import ChangeDirectoryOption from "components/Directory/changeOption";
+import React from "react";
interface Iprops {
onClick: () => void;
- color?: ButtonProps['color'];
+ color?: ButtonProps["color"];
variant?:
- | 'primary'
- | 'captioned'
- | 'toggle'
- | 'secondary'
- | 'mini'
- | 'path';
- fontWeight?: TypographyProps['fontWeight'];
+ | "primary"
+ | "captioned"
+ | "toggle"
+ | "secondary"
+ | "mini"
+ | "path";
+ fontWeight?: TypographyProps["fontWeight"];
startIcon?: React.ReactNode;
endIcon?: React.ReactNode;
label?: string;
@@ -36,27 +36,27 @@ interface Iprops {
}
export function EnteMenuItem({
onClick,
- color = 'primary',
+ color = "primary",
startIcon,
endIcon,
label,
subText,
subIcon,
checked,
- variant = 'primary',
- fontWeight = 'bold',
+ variant = "primary",
+ fontWeight = "bold",
labelComponent,
disabled = false,
}: Iprops) {
const handleButtonClick = () => {
- if (variant === 'path' || variant === 'toggle') {
+ if (variant === "path" || variant === "toggle") {
return;
}
onClick();
};
const handleIconClick = () => {
- if (variant !== 'path' && variant !== 'toggle') {
+ if (variant !== "path" && variant !== "toggle") {
return;
}
onClick();
@@ -67,36 +67,37 @@ export function EnteMenuItem({
disabled={disabled}
onClick={handleButtonClick}
sx={{
- width: '100%',
+ width: "100%",
color: (theme) =>
- variant !== 'captioned' && theme.palette[color].main,
- ...(variant !== 'secondary' &&
- variant !== 'mini' && {
+ variant !== "captioned" && theme.palette[color].main,
+ ...(variant !== "secondary" &&
+ variant !== "mini" && {
backgroundColor: (theme) => theme.colors.fill.faint,
}),
- '&:hover': {
+ "&:hover": {
backgroundColor: (theme) => theme.colors.fill.faintPressed,
},
- '& .MuiSvgIcon-root': {
- fontSize: '20px',
+ "& .MuiSvgIcon-root": {
+ fontSize: "20px",
},
p: 0,
- borderRadius: '4px',
- }}>
- <SpaceBetweenFlex sx={{ pl: '16px', pr: '12px' }}>
- <VerticallyCenteredFlex sx={{ py: '14px' }} gap={'10px'}>
+ borderRadius: "4px",
+ }}
+ >
+ <SpaceBetweenFlex sx={{ pl: "16px", pr: "12px" }}>
+ <VerticallyCenteredFlex sx={{ py: "14px" }} gap={"10px"}>
{startIcon && startIcon}
- <Box px={'2px'}>
+ <Box px={"2px"}>
{labelComponent ? (
labelComponent
- ) : variant === 'captioned' ? (
+ ) : variant === "captioned" ? (
<CaptionedText
color={color}
mainText={label}
subText={subText}
subIcon={subIcon}
/>
- ) : variant === 'mini' ? (
+ ) : variant === "mini" ? (
<Typography variant="mini" color="text.muted">
{label}
</Typography>
@@ -107,15 +108,15 @@ export function EnteMenuItem({
)}
</Box>
</VerticallyCenteredFlex>
- <VerticallyCenteredFlex gap={'4px'}>
+ <VerticallyCenteredFlex gap={"4px"}>
{endIcon && endIcon}
- {variant === 'toggle' && (
+ {variant === "toggle" && (
<PublicShareSwitch
checked={checked}
onClick={handleIconClick}
/>
)}
- {variant === 'path' && (
+ {variant === "path" && (
<ChangeDirectoryOption
changeExportDirectory={handleIconClick}
/>
diff --git a/apps/photos/src/components/Menu/MenuItemDivider.tsx b/apps/photos/src/components/Menu/MenuItemDivider.tsx
index 37237dbd74..da3b309a2b 100644
--- a/apps/photos/src/components/Menu/MenuItemDivider.tsx
+++ b/apps/photos/src/components/Menu/MenuItemDivider.tsx
@@ -1,4 +1,4 @@
-import { Divider } from '@mui/material';
+import { Divider } from "@mui/material";
interface Iprops {
hasIcon?: boolean;
}
@@ -6,9 +6,9 @@ export default function MenuItemDivider({ hasIcon = false }: Iprops) {
return (
<Divider
sx={{
- '&&&': {
+ "&&&": {
my: 0,
- ml: hasIcon ? '48px' : '16px',
+ ml: hasIcon ? "48px" : "16px",
},
}}
/>
diff --git a/apps/photos/src/components/Menu/MenuItemGroup.tsx b/apps/photos/src/components/Menu/MenuItemGroup.tsx
index ad137c2d27..0b80262b5f 100644
--- a/apps/photos/src/components/Menu/MenuItemGroup.tsx
+++ b/apps/photos/src/components/Menu/MenuItemGroup.tsx
@@ -1,6 +1,6 @@
-import { styled } from '@mui/material';
+import { styled } from "@mui/material";
-export const MenuItemGroup = styled('div')(
+export const MenuItemGroup = styled("div")(
({ theme }) => `
& > .MuiMenuItem-root{
border-radius: 8px;
@@ -16,5 +16,5 @@ export const MenuItemGroup = styled('div')(
}
background-color: ${theme.colors.fill.faint};
border-radius: 8px;
-`
+`,
);
diff --git a/apps/photos/src/components/Menu/MenuSectionTitle.tsx b/apps/photos/src/components/Menu/MenuSectionTitle.tsx
index 76ead8d894..5c07b8d92b 100644
--- a/apps/photos/src/components/Menu/MenuSectionTitle.tsx
+++ b/apps/photos/src/components/Menu/MenuSectionTitle.tsx
@@ -1,5 +1,5 @@
-import { Typography } from '@mui/material';
-import { VerticallyCenteredFlex } from '@ente/shared/components/Container';
+import { VerticallyCenteredFlex } from "@ente/shared/components/Container";
+import { Typography } from "@mui/material";
interface Iprops {
title: string;
@@ -10,14 +10,15 @@ export default function MenuSectionTitle({ title, icon }: Iprops) {
return (
<VerticallyCenteredFlex
px="8px"
- py={'6px'}
- gap={'8px'}
+ py={"6px"}
+ gap={"8px"}
sx={{
- '& > svg': {
- fontSize: '17px',
+ "& > svg": {
+ fontSize: "17px",
color: (theme) => theme.colors.stroke.muted,
},
- }}>
+ }}
+ >
{icon && icon}
<Typography variant="small" color="text.muted">
{title}
diff --git a/apps/photos/src/components/MultilineInput.tsx b/apps/photos/src/components/MultilineInput.tsx
index cb847f3427..acf657e37e 100644
--- a/apps/photos/src/components/MultilineInput.tsx
+++ b/apps/photos/src/components/MultilineInput.tsx
@@ -1,4 +1,4 @@
-import { Stack, TextField, Typography, TypographyProps } from '@mui/material';
+import { Stack, TextField, Typography, TypographyProps } from "@mui/material";
interface Iprops {
label: string;
@@ -22,7 +22,7 @@ export default function MultilineInput({
onChange,
}: Iprops) {
return (
- <Stack spacing={'4px'}>
+ <Stack spacing={"4px"}>
<Typography {...labelProps}>{label}</Typography>
<TextField
variant="standard"
@@ -32,22 +32,23 @@ export default function MultilineInput({
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
sx={(theme) => ({
- border: '1px solid',
+ border: "1px solid",
borderColor: theme.colors.stroke.faint,
- borderRadius: '8px',
- padding: '12px',
- '.MuiInputBase-formControl': {
- '::before, ::after': {
- borderBottom: 'none !important',
+ borderRadius: "8px",
+ padding: "12px",
+ ".MuiInputBase-formControl": {
+ "::before, ::after": {
+ borderBottom: "none !important",
},
},
})}
/>
<Typography
- px={'8px'}
+ px={"8px"}
variant="small"
color="text.secondary"
- {...messageProps}>
+ {...messageProps}
+ >
{message}
</Typography>
</Stack>
diff --git a/apps/photos/src/components/Notification.tsx b/apps/photos/src/components/Notification.tsx
index 466471a9b3..f000d229ec 100644
--- a/apps/photos/src/components/Notification.tsx
+++ b/apps/photos/src/components/Notification.tsx
@@ -1,4 +1,4 @@
-import CloseIcon from '@mui/icons-material/Close';
+import CloseIcon from "@mui/icons-material/Close";
import {
Box,
Button,
@@ -8,19 +8,19 @@ import {
SxProps,
Theme,
Typography,
-} from '@mui/material';
-import { NotificationAttributes } from 'types/Notification';
+} from "@mui/material";
+import { NotificationAttributes } from "types/Notification";
-import InfoIcon from '@mui/icons-material/InfoOutlined';
-import { IconButtonWithBG } from '@ente/shared/components/Container';
+import { IconButtonWithBG } from "@ente/shared/components/Container";
+import InfoIcon from "@mui/icons-material/InfoOutlined";
interface Iprops {
open: boolean;
onClose: () => void;
keepOpenOnClick?: boolean;
attributes: NotificationAttributes;
- horizontal?: 'left' | 'right';
- vertical?: 'top' | 'bottom';
+ horizontal?: "left" | "right";
+ vertical?: "top" | "bottom";
sx?: SxProps<Theme>;
}
@@ -37,7 +37,7 @@ export default function Notification({
return <></>;
}
- const handleClose: ButtonProps['onClick'] = (event) => {
+ const handleClose: ButtonProps["onClick"] = (event) => {
onClose();
event.stopPropagation();
};
@@ -52,33 +52,37 @@ export default function Notification({
<Snackbar
open={open}
anchorOrigin={{
- horizontal: horizontal ?? 'right',
- vertical: vertical ?? 'bottom',
+ horizontal: horizontal ?? "right",
+ vertical: vertical ?? "bottom",
}}
- sx={{ width: '320px', backgroundColor: '#000', ...sx }}>
+ sx={{ width: "320px", backgroundColor: "#000", ...sx }}
+ >
<Button
color={attributes.variant}
onClick={handleClick}
sx={{
- textAlign: 'left',
- flex: '1',
+ textAlign: "left",
+ flex: "1",
padding: (theme) => theme.spacing(1.5, 2),
- borderRadius: '8px',
- }}>
+ borderRadius: "8px",
+ }}
+ >
<Stack
- flex={'1'}
+ flex={"1"}
spacing={2}
direction="row"
- alignItems={'center'}>
- <Box sx={{ svg: { fontSize: '36px' } }}>
+ alignItems={"center"}
+ >
+ <Box sx={{ svg: { fontSize: "36px" } }}>
{attributes.startIcon ?? <InfoIcon />}
</Box>
<Stack
- direction={'column'}
+ direction={"column"}
spacing={0.5}
flex={1}
- textAlign="left">
+ textAlign="left"
+ >
{attributes.subtext && (
<Typography variant="small">
{attributes.subtext}
@@ -104,7 +108,8 @@ export default function Notification({
{attributes.endIcon ? (
<IconButtonWithBG
onClick={attributes.onClick}
- sx={{ fontSize: '36px' }}>
+ sx={{ fontSize: "36px" }}
+ >
{attributes?.endIcon}
</IconButtonWithBG>
) : (
diff --git a/apps/photos/src/components/PhotoFrame.tsx b/apps/photos/src/components/PhotoFrame.tsx
index 0097a1eba1..835bdeb3a4 100644
--- a/apps/photos/src/components/PhotoFrame.tsx
+++ b/apps/photos/src/components/PhotoFrame.tsx
@@ -1,33 +1,33 @@
-import { GalleryContext } from 'pages/gallery';
-import PreviewCard from './pages/gallery/PreviewCard';
-import { useContext, useEffect, useState } from 'react';
-import { EnteFile } from 'types/file';
-import { styled } from '@mui/material';
+import { PHOTOS_PAGES } from "@ente/shared/constants/pages";
+import { CustomError } from "@ente/shared/error";
+import useMemoSingleThreaded from "@ente/shared/hooks/useMemoSingleThreaded";
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import { styled } from "@mui/material";
+import PhotoViewer from "components/PhotoViewer";
+import { TRASH_SECTION } from "constants/collection";
+import { FILE_TYPE } from "constants/file";
+import { useRouter } from "next/router";
+import { GalleryContext } from "pages/gallery";
+import PhotoSwipe from "photoswipe";
+import { useContext, useEffect, useState } from "react";
+import AutoSizer from "react-virtualized-auto-sizer";
+import { Duplicate } from "services/deduplicationService";
import DownloadManager, {
LivePhotoSourceURL,
SourceURLs,
-} from 'services/download';
-import AutoSizer from 'react-virtualized-auto-sizer';
-import PhotoViewer from 'components/PhotoViewer';
-import { TRASH_SECTION } from 'constants/collection';
-import { updateFileMsrcProps, updateFileSrcProps } from 'utils/photoFrame';
+} from "services/download";
+import { EnteFile } from "types/file";
import {
SelectedState,
SetFilesDownloadProgressAttributesCreator,
-} from 'types/gallery';
-import { useRouter } from 'next/router';
-import { logError } from '@ente/shared/sentry';
-import { addLogLine } from '@ente/shared/logging';
-import PhotoSwipe from 'photoswipe';
-import useMemoSingleThreaded from '@ente/shared/hooks/useMemoSingleThreaded';
-import { FILE_TYPE } from 'constants/file';
-import { PHOTOS_PAGES } from '@ente/shared/constants/pages';
-import { PhotoList } from './PhotoList';
-import { DedupePhotoList } from './PhotoList/dedupe';
-import { Duplicate } from 'services/deduplicationService';
-import { CustomError } from '@ente/shared/error';
-
-const Container = styled('div')`
+} from "types/gallery";
+import { updateFileMsrcProps, updateFileSrcProps } from "utils/photoFrame";
+import { PhotoList } from "./PhotoList";
+import { DedupePhotoList } from "./PhotoList/dedupe";
+import PreviewCard from "./pages/gallery/PreviewCard";
+
+const Container = styled("div")`
display: block;
flex: 1;
width: 100%;
@@ -40,7 +40,7 @@ const Container = styled('div')`
}
`;
-const PHOTOSWIPE_HASH_SUFFIX = '&opened';
+const PHOTOSWIPE_HASH_SUFFIX = "&opened";
interface Props {
page:
@@ -52,7 +52,7 @@ interface Props {
syncWithRemote: () => Promise<void>;
favItemIds?: Set<number>;
setSelected: (
- selected: SelectedState | ((selected: SelectedState) => SelectedState)
+ selected: SelectedState | ((selected: SelectedState) => SelectedState),
) => void;
selected: SelectedState;
tempDeletedFileIds?: Set<number>;
@@ -117,7 +117,7 @@ const PhotoFrame = ({
useEffect(() => {
const currentURL = new URL(window.location.href);
- const end = currentURL.hash.lastIndexOf('&');
+ const end = currentURL.hash.lastIndexOf("&");
const hash = currentURL.hash.slice(1, end !== -1 ? end : undefined);
if (open) {
router.push({
@@ -132,23 +132,23 @@ const PhotoFrame = ({
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Shift') {
+ if (e.key === "Shift") {
setIsShiftKeyPressed(true);
}
};
const handleKeyUp = (e: KeyboardEvent) => {
- if (e.key === 'Shift') {
+ if (e.key === "Shift") {
setIsShiftKeyPressed(false);
}
};
- document.addEventListener('keydown', handleKeyDown, false);
- document.addEventListener('keyup', handleKeyUp, false);
+ document.addEventListener("keydown", handleKeyDown, false);
+ document.addEventListener("keyup", handleKeyUp, false);
- router.events.on('hashChangeComplete', (url: string) => {
- const start = url.indexOf('#');
+ router.events.on("hashChangeComplete", (url: string) => {
+ const start = url.indexOf("#");
const hash = url.slice(start !== -1 ? start : url.length);
const shouldPhotoSwipeBeOpened = hash.endsWith(
- PHOTOSWIPE_HASH_SUFFIX
+ PHOTOSWIPE_HASH_SUFFIX,
);
if (shouldPhotoSwipeBeOpened) {
setIsPhotoSwipeOpen?.(true);
@@ -160,8 +160,8 @@ const PhotoFrame = ({
});
return () => {
- document.removeEventListener('keydown', handleKeyDown, false);
- document.removeEventListener('keyup', handleKeyUp, false);
+ document.removeEventListener("keydown", handleKeyDown, false);
+ document.removeEventListener("keyup", handleKeyUp, false);
};
}, []);
@@ -181,7 +181,7 @@ const PhotoFrame = ({
// this is to prevent outdated updateURL call from updating the wrong file
if (file.id !== id) {
addLogLine(
- `[${id}]PhotoSwipe: updateURL: file id mismatch: ${file.id} !== ${id}`
+ `[${id}]PhotoSwipe: updateURL: file id mismatch: ${file.id} !== ${id}`,
);
throw Error(CustomError.UPDATE_URL_FILE_ID_MISMATCH);
}
@@ -195,13 +195,13 @@ const PhotoFrame = ({
index: number,
id: number,
srcURLs: SourceURLs,
- forceUpdate?: boolean
+ forceUpdate?: boolean,
) => {
const file = displayFiles[index];
// this is to prevent outdate updateSrcURL call from updating the wrong file
if (file.id !== id) {
addLogLine(
- `[${id}]PhotoSwipe: updateSrcURL: file id mismatch: ${file.id}`
+ `[${id}]PhotoSwipe: updateSrcURL: file id mismatch: ${file.id}`,
);
throw Error(CustomError.UPDATE_URL_FILE_ID_MISMATCH);
}
@@ -230,7 +230,7 @@ const PhotoFrame = ({
const handleSelect =
(id: number, isOwnFile: boolean, index?: number) =>
(checked: boolean) => {
- if (typeof index !== 'undefined') {
+ if (typeof index !== "undefined") {
if (checked) {
setRangeStart(index);
} else {
@@ -278,7 +278,7 @@ const PhotoFrame = ({
};
const handleRangeSelect = (index: number) => () => {
- if (typeof rangeStart !== 'undefined' && rangeStart !== index) {
+ if (typeof rangeStart !== "undefined" && rangeStart !== index) {
const direction =
(index - rangeStart) / Math.abs(index - rangeStart);
let checked = true;
@@ -296,20 +296,20 @@ const PhotoFrame = ({
) {
handleSelect(
displayFiles[i].id,
- displayFiles[i].ownerID === galleryContext.user?.id
+ displayFiles[i].ownerID === galleryContext.user?.id,
)(!checked);
}
handleSelect(
displayFiles[index].id,
displayFiles[index].ownerID === galleryContext.user?.id,
- index
+ index,
)(!checked);
}
};
const getThumbnail = (
item: EnteFile,
index: number,
- isScrolling: boolean
+ isScrolling: boolean,
) => (
<PreviewCard
key={`tile-${item.id}-selected-${selected[item.id] ?? false}`}
@@ -320,7 +320,7 @@ const PhotoFrame = ({
onSelect={handleSelect(
item.id,
item.ownerID === galleryContext.user?.id,
- index
+ index,
)}
selected={
selected.collectionID === activeCollectionID &&
@@ -342,21 +342,21 @@ const PhotoFrame = ({
const getSlideData = async (
instance: PhotoSwipe<PhotoSwipe.Options>,
index: number,
- item: EnteFile
+ item: EnteFile,
) => {
addLogLine(
`[${
item.id
}] getSlideData called for thumbnail:${!!item.msrc} sourceLoaded:${
item.isSourceLoaded
- } fetching:${fetching[item.id]}`
+ } fetching:${fetching[item.id]}`,
);
if (!item.msrc) {
try {
if (thumbFetching[item.id]) {
addLogLine(
- `[${item.id}] thumb download already in progress`
+ `[${item.id}] thumb download already in progress`,
);
return;
}
@@ -368,7 +368,7 @@ const PhotoFrame = ({
addLogLine(
`[${
item.id
- }] calling invalidateCurrItems for thumbnail msrc :${!!item.msrc}`
+ }] calling invalidateCurrItems for thumbnail msrc :${!!item.msrc}`,
);
instance.invalidateCurrItems();
if ((instance as any).isOpen()) {
@@ -378,13 +378,13 @@ const PhotoFrame = ({
if (e.message !== CustomError.URL_ALREADY_SET) {
logError(
e,
- 'updating photoswipe after msrc url update failed'
+ "updating photoswipe after msrc url update failed",
);
}
// ignore
}
} catch (e) {
- logError(e, 'getSlideData failed get msrc url failed');
+ logError(e, "getSlideData failed get msrc url failed");
thumbFetching[item.id] = false;
}
}
@@ -415,12 +415,12 @@ const PhotoFrame = ({
url: imageURL,
isOriginal: false,
isRenderable: !!imageURL,
- type: 'normal',
+ type: "normal",
};
try {
await updateSrcURL(index, item.id, dummyImgSrcUrl);
addLogLine(
- `[${item.id}] calling invalidateCurrItems for live photo imgSrc, source loaded :${item.isSourceLoaded}`
+ `[${item.id}] calling invalidateCurrItems for live photo imgSrc, source loaded :${item.isSourceLoaded}`,
);
instance.invalidateCurrItems();
if ((instance as any).isOpen()) {
@@ -430,7 +430,7 @@ const PhotoFrame = ({
if (e.message !== CustomError.URL_ALREADY_SET) {
logError(
e,
- 'updating photoswipe after for live photo imgSrc update failed'
+ "updating photoswipe after for live photo imgSrc update failed",
);
}
}
@@ -444,17 +444,17 @@ const PhotoFrame = ({
url: { video: videoURL, image: imageURL },
isOriginal: false,
isRenderable: !!videoURL,
- type: 'livePhoto',
+ type: "livePhoto",
};
try {
await updateSrcURL(
index,
item.id,
loadedLivePhotoSrcURL,
- true
+ true,
);
addLogLine(
- `[${item.id}] calling invalidateCurrItems for live photo complete, source loaded :${item.isSourceLoaded}`
+ `[${item.id}] calling invalidateCurrItems for live photo complete, source loaded :${item.isSourceLoaded}`,
);
instance.invalidateCurrItems();
if ((instance as any).isOpen()) {
@@ -464,7 +464,7 @@ const PhotoFrame = ({
if (e.message !== CustomError.URL_ALREADY_SET) {
logError(
e,
- 'updating photoswipe for live photo complete update failed'
+ "updating photoswipe for live photo complete update failed",
);
}
}
@@ -472,7 +472,7 @@ const PhotoFrame = ({
try {
await updateSrcURL(index, item.id, srcURLs);
addLogLine(
- `[${item.id}] calling invalidateCurrItems for src, source loaded :${item.isSourceLoaded}`
+ `[${item.id}] calling invalidateCurrItems for src, source loaded :${item.isSourceLoaded}`,
);
instance.invalidateCurrItems();
if ((instance as any).isOpen()) {
@@ -482,13 +482,13 @@ const PhotoFrame = ({
if (e.message !== CustomError.URL_ALREADY_SET) {
logError(
e,
- 'updating photoswipe after src url update failed'
+ "updating photoswipe after src url update failed",
);
}
}
}
} catch (e) {
- logError(e, 'getSlideData failed get src url failed');
+ logError(e, "getSlideData failed get src url failed");
fetching[item.id] = false;
// no-op
}
@@ -497,7 +497,7 @@ const PhotoFrame = ({
const getConvertedItem = async (
instance: PhotoSwipe<PhotoSwipe.Options>,
index: number,
- item: EnteFile
+ item: EnteFile,
) => {
if (
item.metadata.fileType !== FILE_TYPE.VIDEO &&
@@ -505,14 +505,14 @@ const PhotoFrame = ({
) {
logError(
new Error(),
- 'getConvertedVideo called for non video file'
+ "getConvertedVideo called for non video file",
);
return;
}
if (item.conversionFailed) {
logError(
new Error(),
- 'getConvertedVideo called for file that conversion failed'
+ "getConvertedVideo called for file that conversion failed",
);
return;
}
@@ -521,7 +521,7 @@ const PhotoFrame = ({
addLogLine(
`[${
item.id
- }] calling invalidateCurrItems for thumbnail msrc :${!!item.msrc}`
+ }] calling invalidateCurrItems for thumbnail msrc :${!!item.msrc}`,
);
instance.invalidateCurrItems();
if ((instance as any).isOpen()) {
@@ -529,13 +529,13 @@ const PhotoFrame = ({
}
} catch (e) {
if (e.message !== CustomError.URL_ALREADY_SET) {
- logError(e, 'updating photoswipe after msrc url update failed');
+ logError(e, "updating photoswipe after msrc url update failed");
}
// ignore
}
try {
addLogLine(
- `[${item.id}] new file getConvertedVideo request- ${item.metadata.title}}`
+ `[${item.id}] new file getConvertedVideo request- ${item.metadata.title}}`,
);
fetching[item.id] = true;
@@ -544,7 +544,7 @@ const PhotoFrame = ({
try {
await updateSrcURL(index, item.id, srcURL, true);
addLogLine(
- `[${item.id}] calling invalidateCurrItems for src, source loaded :${item.isSourceLoaded}`
+ `[${item.id}] calling invalidateCurrItems for src, source loaded :${item.isSourceLoaded}`,
);
instance.invalidateCurrItems();
if ((instance as any).isOpen()) {
@@ -554,13 +554,13 @@ const PhotoFrame = ({
if (e.message !== CustomError.URL_ALREADY_SET) {
logError(
e,
- 'updating photoswipe after src url update failed'
+ "updating photoswipe after src url update failed",
);
}
throw e;
}
} catch (e) {
- logError(e, 'getConvertedVideo failed get src url failed');
+ logError(e, "getConvertedVideo failed get src url failed");
fetching[item.id] = false;
// no-op
}
diff --git a/apps/photos/src/components/PhotoList/dedupe.tsx b/apps/photos/src/components/PhotoList/dedupe.tsx
index df1980b7f6..8562b1ffb5 100644
--- a/apps/photos/src/components/PhotoList/dedupe.tsx
+++ b/apps/photos/src/components/PhotoList/dedupe.tsx
@@ -1,34 +1,34 @@
-import React, { useRef, useEffect, useState, useMemo } from 'react';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import { convertBytesToHumanReadable } from "@ente/shared/utils/size";
+import { Box, styled } from "@mui/material";
import {
- VariableSizeList as List,
- ListChildComponentProps,
- areEqual,
-} from 'react-window';
-import { Box, styled } from '@mui/material';
-import { EnteFile } from 'types/file';
-import {
- IMAGE_CONTAINER_MAX_HEIGHT,
- MIN_COLUMNS,
DATE_CONTAINER_HEIGHT,
GAP_BTW_TILES,
- SPACE_BTW_DATES,
- SIZE_AND_COUNT_CONTAINER_HEIGHT,
+ IMAGE_CONTAINER_MAX_HEIGHT,
IMAGE_CONTAINER_MAX_WIDTH,
-} from 'constants/gallery';
-import { convertBytesToHumanReadable } from '@ente/shared/utils/size';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import { t } from 'i18next';
-import memoize from 'memoize-one';
-import { Duplicate } from 'services/deduplicationService';
+ MIN_COLUMNS,
+ SIZE_AND_COUNT_CONTAINER_HEIGHT,
+ SPACE_BTW_DATES,
+} from "constants/gallery";
+import { t } from "i18next";
+import memoize from "memoize-one";
+import React, { useEffect, useMemo, useRef, useState } from "react";
+import {
+ VariableSizeList as List,
+ ListChildComponentProps,
+ areEqual,
+} from "react-window";
+import { Duplicate } from "services/deduplicationService";
+import { EnteFile } from "types/file";
export enum ITEM_TYPE {
- TIME = 'TIME',
- FILE = 'FILE',
- SIZE_AND_COUNT = 'SIZE_AND_COUNT',
- HEADER = 'HEADER',
- FOOTER = 'FOOTER',
- MARKETING_FOOTER = 'MARKETING_FOOTER',
- OTHER = 'OTHER',
+ TIME = "TIME",
+ FILE = "FILE",
+ SIZE_AND_COUNT = "SIZE_AND_COUNT",
+ HEADER = "HEADER",
+ FOOTER = "FOOTER",
+ MARKETING_FOOTER = "MARKETING_FOOTER",
+ OTHER = "OTHER",
}
export interface TimeStampListItem {
@@ -48,7 +48,7 @@ export interface TimeStampListItem {
fileCount?: number;
}
-const ListItem = styled('div')`
+const ListItem = styled("div")`
display: flex;
justify-content: center;
`;
@@ -56,7 +56,7 @@ const ListItem = styled('div')`
const getTemplateColumns = (
columns: number,
shrinkRatio: number,
- groups?: number[]
+ groups?: number[],
): string => {
if (groups) {
// need to confirm why this was there
@@ -67,7 +67,7 @@ const getTemplateColumns = (
return groups
.map(
(x) =>
- `repeat(${x}, ${IMAGE_CONTAINER_MAX_WIDTH * shrinkRatio}px)`
+ `repeat(${x}, ${IMAGE_CONTAINER_MAX_WIDTH * shrinkRatio}px)`,
)
.join(` ${SPACE_BTW_DATES}px `);
} else {
@@ -143,7 +143,7 @@ interface Props {
getThumbnail: (
file: EnteFile,
index: number,
- isScrolling?: boolean
+ isScrolling?: boolean,
) => JSX.Element;
activeCollectionID: number;
}
@@ -154,7 +154,7 @@ interface ItemData {
shrinkRatio: number;
renderListItem: (
timeStampListItem: TimeStampListItem,
- isScrolling?: boolean
+ isScrolling?: boolean,
) => JSX.Element;
}
@@ -165,14 +165,14 @@ const createItemData = memoize(
shrinkRatio: number,
renderListItem: (
timeStampListItem: TimeStampListItem,
- isScrolling?: boolean
- ) => JSX.Element
+ isScrolling?: boolean,
+ ) => JSX.Element,
): ItemData => ({
timeStampList,
columns,
shrinkRatio,
renderListItem,
- })
+ }),
);
const PhotoListRow = React.memo(
({
@@ -187,13 +187,14 @@ const PhotoListRow = React.memo(
<ListContainer
columns={columns}
shrinkRatio={shrinkRatio}
- groups={timeStampList[index].groups}>
+ groups={timeStampList[index].groups}
+ >
{renderListItem(timeStampList[index], isScrolling)}
</ListContainer>
</ListItem>
);
},
- areEqual
+ areEqual,
);
const getTimeStampListFromDuplicates = (duplicates: Duplicate[], columns) => {
@@ -256,7 +257,7 @@ export function DedupePhotoList({
refreshInProgress.current = true;
const timeStampList = getTimeStampListFromDuplicates(
duplicates,
- columns
+ columns,
);
setTimeStampList(timeStampList);
refreshInProgress.current = false;
@@ -298,15 +299,15 @@ export function DedupePhotoList({
const renderListItem = (
listItem: TimeStampListItem,
- isScrolling: boolean
+ isScrolling: boolean,
) => {
switch (listItem.itemType) {
case ITEM_TYPE.SIZE_AND_COUNT:
return (
<SizeAndCountContainer span={columns}>
- {listItem.fileCount} {t('FILES')},{' '}
- {convertBytesToHumanReadable(listItem.fileSize || 0)}{' '}
- {t('EACH')}
+ {listItem.fileCount} {t("FILES")},{" "}
+ {convertBytesToHumanReadable(listItem.fileSize || 0)}{" "}
+ {t("EACH")}
</SizeAndCountContainer>
);
case ITEM_TYPE.FILE: {
@@ -314,8 +315,8 @@ export function DedupePhotoList({
getThumbnail(
item,
listItem.itemStartIndex + idx,
- isScrolling
- )
+ isScrolling,
+ ),
);
if (listItem.groups) {
let sum = 0;
@@ -324,7 +325,7 @@ export function DedupePhotoList({
ret.splice(
sum,
0,
- <div key={`${listItem.items[0].id}-gap-${i}`} />
+ <div key={`${listItem.items[0].id}-gap-${i}`} />,
);
sum += 1;
}
@@ -344,7 +345,7 @@ export function DedupePhotoList({
timeStampList,
columns,
shrinkRatio,
- renderListItem
+ renderListItem,
);
return (
@@ -358,7 +359,8 @@ export function DedupePhotoList({
itemCount={timeStampList.length}
itemKey={generateKey}
overscanCount={3}
- useIsScrolling>
+ useIsScrolling
+ >
{PhotoListRow}
</List>
);
diff --git a/apps/photos/src/components/PhotoList/index.tsx b/apps/photos/src/components/PhotoList/index.tsx
index 2eec5a66ff..4d0624215a 100644
--- a/apps/photos/src/components/PhotoList/index.tsx
+++ b/apps/photos/src/components/PhotoList/index.tsx
@@ -1,31 +1,30 @@
-import React, { useRef, useEffect, useContext, useState } from 'react';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import { ENTE_WEBSITE_LINK } from "@ente/shared/constants/urls";
+import { formatDate } from "@ente/shared/time/format";
+import { convertBytesToHumanReadable } from "@ente/shared/utils/size";
+import { Box, Link, Typography, styled } from "@mui/material";
import {
- VariableSizeList as List,
- ListChildComponentProps,
- areEqual,
-} from 'react-window';
-import { Box, Link, styled } from '@mui/material';
-import { EnteFile } from 'types/file';
-import {
- IMAGE_CONTAINER_MAX_HEIGHT,
- MIN_COLUMNS,
DATE_CONTAINER_HEIGHT,
GAP_BTW_TILES,
- SPACE_BTW_DATES,
+ IMAGE_CONTAINER_MAX_HEIGHT,
+ IMAGE_CONTAINER_MAX_WIDTH,
+ MIN_COLUMNS,
SIZE_AND_COUNT_CONTAINER_HEIGHT,
+ SPACE_BTW_DATES,
SPACE_BTW_DATES_TO_IMAGE_CONTAINER_WIDTH_RATIO,
- IMAGE_CONTAINER_MAX_WIDTH,
-} from 'constants/gallery';
-import { PublicCollectionGalleryContext } from 'utils/publicCollectionGallery';
-import { ENTE_WEBSITE_LINK } from '@ente/shared/constants/urls';
-import { convertBytesToHumanReadable } from '@ente/shared/utils/size';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import { Typography } from '@mui/material';
-import { GalleryContext } from 'pages/gallery';
-import { formatDate } from '@ente/shared/time/format';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
-import memoize from 'memoize-one';
+} from "constants/gallery";
+import { t } from "i18next";
+import memoize from "memoize-one";
+import { GalleryContext } from "pages/gallery";
+import React, { useContext, useEffect, useRef, useState } from "react";
+import { Trans } from "react-i18next";
+import {
+ VariableSizeList as List,
+ ListChildComponentProps,
+ areEqual,
+} from "react-window";
+import { EnteFile } from "types/file";
+import { PublicCollectionGalleryContext } from "utils/publicCollectionGallery";
const A_DAY = 24 * 60 * 60 * 1000;
const FOOTER_HEIGHT = 90;
@@ -33,13 +32,13 @@ const ALBUM_FOOTER_HEIGHT = 75;
const ALBUM_FOOTER_HEIGHT_WITH_REFERRAL = 113;
export enum ITEM_TYPE {
- TIME = 'TIME',
- FILE = 'FILE',
- SIZE_AND_COUNT = 'SIZE_AND_COUNT',
- HEADER = 'HEADER',
- FOOTER = 'FOOTER',
- MARKETING_FOOTER = 'MARKETING_FOOTER',
- OTHER = 'OTHER',
+ TIME = "TIME",
+ FILE = "FILE",
+ SIZE_AND_COUNT = "SIZE_AND_COUNT",
+ HEADER = "HEADER",
+ FOOTER = "FOOTER",
+ MARKETING_FOOTER = "MARKETING_FOOTER",
+ OTHER = "OTHER",
}
export interface TimeStampListItem {
@@ -59,7 +58,7 @@ export interface TimeStampListItem {
fileCount?: number;
}
-const ListItem = styled('div')`
+const ListItem = styled("div")`
display: flex;
justify-content: center;
`;
@@ -67,7 +66,7 @@ const ListItem = styled('div')`
const getTemplateColumns = (
columns: number,
shrinkRatio: number,
- groups?: number[]
+ groups?: number[],
): string => {
if (groups) {
// need to confirm why this was there
@@ -78,7 +77,7 @@ const getTemplateColumns = (
return groups
.map(
(x) =>
- `repeat(${x}, ${IMAGE_CONTAINER_MAX_WIDTH * shrinkRatio}px)`
+ `repeat(${x}, ${IMAGE_CONTAINER_MAX_WIDTH * shrinkRatio}px)`,
)
.join(` ${SPACE_BTW_DATES}px `);
} else {
@@ -163,7 +162,7 @@ const AlbumFooterContainer = styled(ListItemContainer)<{
hasReferral: boolean;
}>`
margin-top: 48px;
- margin-bottom: ${({ hasReferral }) => (!hasReferral ? `10px` : '0px')};
+ margin-bottom: ${({ hasReferral }) => (!hasReferral ? `10px` : "0px")};
text-align: center;
justify-content: center;
`;
@@ -194,7 +193,7 @@ interface Props {
getThumbnail: (
file: EnteFile,
index: number,
- isScrolling?: boolean
+ isScrolling?: boolean,
) => JSX.Element;
activeCollectionID: number;
}
@@ -205,7 +204,7 @@ interface ItemData {
shrinkRatio: number;
renderListItem: (
timeStampListItem: TimeStampListItem,
- isScrolling?: boolean
+ isScrolling?: boolean,
) => JSX.Element;
}
@@ -216,14 +215,14 @@ const createItemData = memoize(
shrinkRatio: number,
renderListItem: (
timeStampListItem: TimeStampListItem,
- isScrolling?: boolean
- ) => JSX.Element
+ isScrolling?: boolean,
+ ) => JSX.Element,
): ItemData => ({
timeStampList,
columns,
shrinkRatio,
renderListItem,
- })
+ }),
);
const PhotoListRow = React.memo(
({
@@ -238,13 +237,14 @@ const PhotoListRow = React.memo(
<ListContainer
columns={columns}
shrinkRatio={shrinkRatio}
- groups={timeStampList[index].groups}>
+ groups={timeStampList[index].groups}
+ >
{renderListItem(timeStampList[index], isScrolling)}
</ListContainer>
</ListItem>
);
},
- areEqual
+ areEqual,
);
export function PhotoList({
@@ -257,7 +257,7 @@ export function PhotoList({
}: Props) {
const galleryContext = useContext(GalleryContext);
const publicCollectionGalleryContext = useContext(
- PublicCollectionGalleryContext
+ PublicCollectionGalleryContext,
);
const [timeStampList, setTimeStampList] = useState<TimeStampListItem[]>([]);
@@ -292,13 +292,13 @@ export function PhotoList({
if (galleryContext.photoListHeader) {
timeStampList.push(
- getPhotoListHeader(galleryContext.photoListHeader)
+ getPhotoListHeader(galleryContext.photoListHeader),
);
} else if (publicCollectionGalleryContext.photoListHeader) {
timeStampList.push(
getPhotoListHeader(
- publicCollectionGalleryContext.photoListHeader
- )
+ publicCollectionGalleryContext.photoListHeader,
+ ),
);
}
if (galleryContext.isClipSearchResult) {
@@ -318,8 +318,8 @@ export function PhotoList({
if (publicCollectionGalleryContext.photoListFooter) {
timeStampList.push(
getPhotoListFooter(
- publicCollectionGalleryContext.photoListFooter
- )
+ publicCollectionGalleryContext.photoListFooter,
+ ),
);
}
timeStampList.push(getAlbumsFooter());
@@ -362,7 +362,7 @@ export function PhotoList({
} else if (publicCollectionGalleryContext.photoListHeader) {
return [
getPhotoListHeader(
- publicCollectionGalleryContext.photoListHeader
+ publicCollectionGalleryContext.photoListHeader,
),
...timeStampList,
];
@@ -390,7 +390,7 @@ export function PhotoList({
return [
...timeStampList,
getPhotoListFooter(
- publicCollectionGalleryContext.photoListFooter
+ publicCollectionGalleryContext.photoListFooter,
),
getAlbumsFooter(),
];
@@ -419,7 +419,7 @@ export function PhotoList({
!currentDate ||
!isSameDay(
new Date(item.metadata.creationTime / 1000),
- new Date(currentDate)
+ new Date(currentDate),
)
) {
currentDate = item.metadata.creationTime / 1000;
@@ -427,12 +427,12 @@ export function PhotoList({
timeStampList.push({
itemType: ITEM_TYPE.TIME,
date: isSameDay(new Date(currentDate), new Date())
- ? t('TODAY')
+ ? t("TODAY")
: isSameDay(
new Date(currentDate),
- new Date(Date.now() - A_DAY)
+ new Date(Date.now() - A_DAY),
)
- ? t('YESTERDAY')
+ ? t("YESTERDAY")
: formatDate(currentDate),
id: currentDate.toString(),
});
@@ -508,10 +508,10 @@ export function PhotoList({
itemType: ITEM_TYPE.OTHER,
item: (
<NothingContainer span={columns}>
- <div>{t('NOTHING_HERE')}</div>
+ <div>{t("NOTHING_HERE")}</div>
</NothingContainer>
),
- id: 'empty-list-banner',
+ id: "empty-list-banner",
height: height - 48,
};
};
@@ -550,7 +550,7 @@ export function PhotoList({
<FooterContainer span={columns}>
<Typography variant="small">
<Trans
- i18nKey={'INSTALL_MOBILE_APP'}
+ i18nKey={"INSTALL_MOBILE_APP"}
components={{
a: (
<Link
@@ -583,23 +583,25 @@ export function PhotoList({
item: (
<AlbumFooterContainer
span={columns}
- hasReferral={!!publicCollectionGalleryContext.referralCode}>
- <Box width={'100%'}>
- <Typography variant="small" display={'block'}>
- {t('SHARED_USING')}{' '}
+ hasReferral={!!publicCollectionGalleryContext.referralCode}
+ >
+ <Box width={"100%"}>
+ <Typography variant="small" display={"block"}>
+ {t("SHARED_USING")}{" "}
<Link target="_blank" href={ENTE_WEBSITE_LINK}>
- {t('ENTE_IO')}
+ {t("ENTE_IO")}
</Link>
</Typography>
{publicCollectionGalleryContext.referralCode ? (
<FullStretchContainer>
<Typography
sx={{
- marginTop: '12px',
- padding: '8px',
- }}>
+ marginTop: "12px",
+ padding: "8px",
+ }}
+ >
<Trans
- i18nKey={'SHARING_REFERRAL_CODE'}
+ i18nKey={"SHARING_REFERRAL_CODE"}
values={{
referralCode:
publicCollectionGalleryContext.referralCode,
@@ -622,7 +624,7 @@ export function PhotoList({
*/
const mergeTimeStampList = (
items: TimeStampListItem[],
- columns: number
+ columns: number,
): TimeStampListItem[] => {
const newList: TimeStampListItem[] = [];
let index = 0;
@@ -641,7 +643,7 @@ export function PhotoList({
items[index + 1].items.length +
Math.ceil(
newList[newIndex].dates.length *
- SPACE_BTW_DATES_TO_IMAGE_CONTAINER_WIDTH_RATIO
+ SPACE_BTW_DATES_TO_IMAGE_CONTAINER_WIDTH_RATIO,
) <=
columns
) {
@@ -722,7 +724,7 @@ export function PhotoList({
const renderListItem = (
listItem: TimeStampListItem,
- isScrolling: boolean
+ isScrolling: boolean,
) => {
switch (listItem.itemType) {
case ITEM_TYPE.TIME:
@@ -743,9 +745,9 @@ export function PhotoList({
case ITEM_TYPE.SIZE_AND_COUNT:
return (
<SizeAndCountContainer span={columns}>
- {listItem.fileCount} {t('FILES')},{' '}
- {convertBytesToHumanReadable(listItem.fileSize || 0)}{' '}
- {t('EACH')}
+ {listItem.fileCount} {t("FILES")},{" "}
+ {convertBytesToHumanReadable(listItem.fileSize || 0)}{" "}
+ {t("EACH")}
</SizeAndCountContainer>
);
case ITEM_TYPE.FILE: {
@@ -753,8 +755,8 @@ export function PhotoList({
getThumbnail(
item,
listItem.itemStartIndex + idx,
- isScrolling
- )
+ isScrolling,
+ ),
);
if (listItem.groups) {
let sum = 0;
@@ -763,7 +765,7 @@ export function PhotoList({
ret.splice(
sum,
0,
- <div key={`${listItem.items[0].id}-gap-${i}`} />
+ <div key={`${listItem.items[0].id}-gap-${i}`} />,
);
sum += 1;
}
@@ -783,7 +785,7 @@ export function PhotoList({
timeStampList,
columns,
shrinkRatio,
- renderListItem
+ renderListItem,
);
return (
@@ -797,7 +799,8 @@ export function PhotoList({
itemCount={timeStampList.length}
itemKey={generateKey}
overscanCount={3}
- useIsScrolling>
+ useIsScrolling
+ >
{PhotoListRow}
</List>
);
diff --git a/apps/photos/src/components/PhotoViewer/FileInfo/ExifData.tsx b/apps/photos/src/components/PhotoViewer/FileInfo/ExifData.tsx
index d6d704db6d..ee45df5d0a 100644
--- a/apps/photos/src/components/PhotoViewer/FileInfo/ExifData.tsx
+++ b/apps/photos/src/components/PhotoViewer/FileInfo/ExifData.tsx
@@ -1,12 +1,10 @@
-import React from 'react';
-
-import { Stack, styled, Typography } from '@mui/material';
-import { FileInfoSidebar } from '.';
-import Titlebar from 'components/Titlebar';
-import { Box } from '@mui/system';
-import CopyButton from '@ente/shared/components/CodeBlock/CopyButton';
-import { formatDateTimeFull } from '@ente/shared/time/format';
-import { t } from 'i18next';
+import CopyButton from "@ente/shared/components/CodeBlock/CopyButton";
+import { formatDateTimeFull } from "@ente/shared/time/format";
+import { Stack, styled, Typography } from "@mui/material";
+import { Box } from "@mui/system";
+import Titlebar from "components/Titlebar";
+import { t } from "i18next";
+import { FileInfoSidebar } from ".";
const ExifItem = styled(Box)`
padding-left: 8px;
@@ -18,8 +16,8 @@ const ExifItem = styled(Box)`
function parseExifValue(value: any) {
switch (typeof value) {
- case 'string':
- case 'number':
+ case "string":
+ case "number":
return value;
default:
if (value instanceof Date) {
@@ -53,13 +51,13 @@ export function ExifData(props: {
<FileInfoSidebar open={open} onClose={onClose}>
<Titlebar
onClose={onClose}
- title={t('EXIF')}
+ title={t("EXIF")}
caption={filename}
onRootClose={handleRootClose}
actionButton={
<CopyButton
code={JSON.stringify(exif)}
- color={'secondary'}
+ color={"secondary"}
/>
}
/>
@@ -71,22 +69,24 @@ export function ExifData(props: {
<ExifItem key={key}>
<Typography
variant="small"
- color={'text.muted'}>
+ color={"text.muted"}
+ >
{key}
</Typography>
<Typography
sx={{
- width: '100%',
- textOverflow: 'ellipsis',
- whiteSpace: 'nowrap',
- overflow: 'hidden',
- }}>
+ width: "100%",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ overflow: "hidden",
+ }}
+ >
{parseExifValue(value)}
</Typography>
</ExifItem>
) : (
<></>
- )
+ ),
)}
</Stack>
</FileInfoSidebar>
diff --git a/apps/photos/src/components/PhotoViewer/FileInfo/FileNameEditDialog.tsx b/apps/photos/src/components/PhotoViewer/FileInfo/FileNameEditDialog.tsx
index 6514060cb4..214b120f10 100644
--- a/apps/photos/src/components/PhotoViewer/FileInfo/FileNameEditDialog.tsx
+++ b/apps/photos/src/components/PhotoViewer/FileInfo/FileNameEditDialog.tsx
@@ -1,8 +1,8 @@
+import DialogBoxV2 from "@ente/shared/components/DialogBoxV2";
import SingleInputForm, {
SingleInputFormProps,
-} from '@ente/shared/components/SingleInputForm';
-import { t } from 'i18next';
-import DialogBoxV2 from '@ente/shared/components/DialogBoxV2';
+} from "@ente/shared/components/SingleInputForm";
+import { t } from "i18next";
export const FileNameEditDialog = ({
isInEditMode,
@@ -11,15 +11,15 @@ export const FileNameEditDialog = ({
extension,
saveEdits,
}) => {
- const onSubmit: SingleInputFormProps['callback'] = async (
+ const onSubmit: SingleInputFormProps["callback"] = async (
filename,
- setFieldError
+ setFieldError,
) => {
try {
await saveEdits(filename);
closeEditMode();
} catch (e) {
- setFieldError(t('UNKNOWN_ERROR'));
+ setFieldError(t("UNKNOWN_ERROR"));
}
};
return (
@@ -28,13 +28,14 @@ export const FileNameEditDialog = ({
open={isInEditMode}
onClose={closeEditMode}
attributes={{
- title: t('RENAME_FILE'),
- }}>
+ title: t("RENAME_FILE"),
+ }}
+ >
<SingleInputForm
initialValue={filename}
callback={onSubmit}
- placeholder={t('ENTER_FILE_NAME')}
- buttonText={t('RENAME')}
+ placeholder={t("ENTER_FILE_NAME")}
+ buttonText={t("RENAME")}
fieldType="text"
caption={extension}
secondaryButtonAction={closeEditMode}
diff --git a/apps/photos/src/components/PhotoViewer/FileInfo/InfoItem.tsx b/apps/photos/src/components/PhotoViewer/FileInfo/InfoItem.tsx
index 4f85e9fcd0..3cc9f5d35c 100644
--- a/apps/photos/src/components/PhotoViewer/FileInfo/InfoItem.tsx
+++ b/apps/photos/src/components/PhotoViewer/FileInfo/InfoItem.tsx
@@ -1,8 +1,7 @@
-import Edit from '@mui/icons-material/Edit';
-import { Box, IconButton, Typography } from '@mui/material';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import React from 'react';
-import { SmallLoadingSpinner } from '../styledComponents/SmallLoadingSpinner';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import Edit from "@mui/icons-material/Edit";
+import { Box, IconButton, Typography } from "@mui/material";
+import { SmallLoadingSpinner } from "../styledComponents/SmallLoadingSpinner";
interface Iprops {
icon: JSX.Element;
@@ -27,11 +26,12 @@ export default function InfoItem({
}: Iprops): JSX.Element {
return (
<FlexWrapper justifyContent="space-between">
- <Box display={'flex'} alignItems="flex-start" gap={0.5} pr={1}>
+ <Box display={"flex"} alignItems="flex-start" gap={0.5} pr={1}>
<IconButton
color="secondary"
- sx={{ '&&': { cursor: 'default', m: 0.5 } }}
- disableRipple>
+ sx={{ "&&": { cursor: "default", m: 0.5 } }}
+ disableRipple
+ >
{icon}
</IconButton>
<Box py={0.5}>
@@ -39,7 +39,7 @@ export default function InfoItem({
children
) : (
<>
- <Typography sx={{ wordBreak: 'break-all' }}>
+ <Typography sx={{ wordBreak: "break-all" }}>
{title}
</Typography>
<Typography variant="small" color="text.muted">
diff --git a/apps/photos/src/components/PhotoViewer/FileInfo/MapBox.tsx b/apps/photos/src/components/PhotoViewer/FileInfo/MapBox.tsx
index 5014c721ad..ab732d8b4f 100644
--- a/apps/photos/src/components/PhotoViewer/FileInfo/MapBox.tsx
+++ b/apps/photos/src/components/PhotoViewer/FileInfo/MapBox.tsx
@@ -1,22 +1,22 @@
-import { useEffect, useRef } from 'react';
-import { styled } from '@mui/material';
-import { runningInBrowser } from 'utils/common';
-import { MapButton } from './MapButton';
+import { styled } from "@mui/material";
+import { useEffect, useRef } from "react";
+import { runningInBrowser } from "utils/common";
+import { MapButton } from "./MapButton";
-import 'leaflet/dist/leaflet.css';
-import 'leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.webpack.css'; // Re-uses images from ~leaflet package
-import { t } from 'i18next';
-runningInBrowser() && require('leaflet-defaulticon-compatibility');
+import { t } from "i18next";
+import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.webpack.css"; // Re-uses images from ~leaflet package
+import "leaflet/dist/leaflet.css";
+runningInBrowser() && require("leaflet-defaulticon-compatibility");
const L = runningInBrowser()
- ? (require('leaflet') as typeof import('leaflet'))
+ ? (require("leaflet") as typeof import("leaflet"))
: null;
-const LAYER_TILE_URL = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
+const LAYER_TILE_URL = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";
const LAYER_TILE_ATTRIBUTION =
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';
const ZOOM_LEVEL = 16;
-const MapBoxContainer = styled('div')`
+const MapBoxContainer = styled("div")`
height: 200px;
width: 100%;
`;
@@ -69,8 +69,8 @@ const MapBox: React.FC<MapBoxProps> = ({
) : (
<MapBoxEnableContainer>
<MapButton onClick={openUpdateMapConfirmationDialog}>
- {' '}
- {t('ENABLE_MAP')}
+ {" "}
+ {t("ENABLE_MAP")}
</MapButton>
</MapBoxEnableContainer>
);
diff --git a/apps/photos/src/components/PhotoViewer/FileInfo/MapButton.tsx b/apps/photos/src/components/PhotoViewer/FileInfo/MapButton.tsx
index 8fa2da647b..12b6651992 100644
--- a/apps/photos/src/components/PhotoViewer/FileInfo/MapButton.tsx
+++ b/apps/photos/src/components/PhotoViewer/FileInfo/MapButton.tsx
@@ -1,9 +1,9 @@
-import { Button, ButtonProps, styled } from '@mui/material';
-import { CSSProperties } from '@mui/material/styles/createTypography';
+import { Button, ButtonProps, styled } from "@mui/material";
+import { CSSProperties } from "@mui/material/styles/createTypography";
export const MapButton = styled((props: ButtonProps) => (
<Button color="secondary" {...props} />
))(({ theme }) => ({
...(theme.typography.small as CSSProperties),
- padding: '8px',
+ padding: "8px",
}));
diff --git a/apps/photos/src/components/PhotoViewer/FileInfo/RenderCaption.tsx b/apps/photos/src/components/PhotoViewer/FileInfo/RenderCaption.tsx
index 2c5c039c20..76f4d5ca90 100644
--- a/apps/photos/src/components/PhotoViewer/FileInfo/RenderCaption.tsx
+++ b/apps/photos/src/components/PhotoViewer/FileInfo/RenderCaption.tsx
@@ -1,16 +1,16 @@
-import React, { useState } from 'react';
-import { EnteFile } from 'types/file';
-import { changeCaption, updateExistingFilePubMetadata } from 'utils/file';
-import { logError } from '@ente/shared/sentry';
-import { Box, IconButton, TextField } from '@mui/material';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import { MAX_CAPTION_SIZE } from 'constants/file';
-import { Formik } from 'formik';
-import { SmallLoadingSpinner } from '../styledComponents/SmallLoadingSpinner';
-import * as Yup from 'yup';
-import Close from '@mui/icons-material/Close';
-import Done from '@mui/icons-material/Done';
-import { t } from 'i18next';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import { logError } from "@ente/shared/sentry";
+import Close from "@mui/icons-material/Close";
+import Done from "@mui/icons-material/Done";
+import { Box, IconButton, TextField } from "@mui/material";
+import { MAX_CAPTION_SIZE } from "constants/file";
+import { Formik } from "formik";
+import { t } from "i18next";
+import { useState } from "react";
+import { EnteFile } from "types/file";
+import { changeCaption, updateExistingFilePubMetadata } from "utils/file";
+import * as Yup from "yup";
+import { SmallLoadingSpinner } from "../styledComponents/SmallLoadingSpinner";
interface formValues {
caption: string;
@@ -28,7 +28,7 @@ export function RenderCaption({
refreshPhotoswipe: () => void;
}) {
const [caption, setCaption] = useState(
- file?.pubMagicMetadata?.data.caption
+ file?.pubMagicMetadata?.data.caption,
);
const [loading, setLoading] = useState(false);
@@ -48,7 +48,7 @@ export function RenderCaption({
scheduleUpdate();
}
} catch (e) {
- logError(e, 'failed to update caption');
+ logError(e, "failed to update caption");
}
};
@@ -70,11 +70,12 @@ export function RenderCaption({
validationSchema={Yup.object().shape({
caption: Yup.string().max(
MAX_CAPTION_SIZE,
- t('CAPTION_CHARACTER_LIMIT')
+ t("CAPTION_CHARACTER_LIMIT"),
),
})}
validateOnBlur={false}
- onSubmit={onSubmit}>
+ onSubmit={onSubmit}
+ >
{({
values,
errors,
@@ -90,15 +91,15 @@ export function RenderCaption({
name="caption"
type="text"
multiline
- placeholder={t('CAPTION_PLACEHOLDER')}
+ placeholder={t("CAPTION_PLACEHOLDER")}
value={values.caption}
- onChange={handleChange('caption')}
+ onChange={handleChange("caption")}
error={Boolean(errors.caption)}
helperText={errors.caption}
disabled={loading || shouldDisableEdits}
/>
{values.caption !== caption && (
- <FlexWrapper justifyContent={'flex-end'}>
+ <FlexWrapper justifyContent={"flex-end"}>
<IconButton type="submit" disabled={loading}>
{loading ? (
<SmallLoadingSpinner />
@@ -109,11 +110,12 @@ export function RenderCaption({
<IconButton
onClick={() =>
resetForm({
- values: { caption: caption ?? '' },
+ values: { caption: caption ?? "" },
touched: { caption: false },
})
}
- disabled={loading}>
+ disabled={loading}
+ >
<Close />
</IconButton>
</FlexWrapper>
diff --git a/apps/photos/src/components/PhotoViewer/FileInfo/RenderCreationTime.tsx b/apps/photos/src/components/PhotoViewer/FileInfo/RenderCreationTime.tsx
index 69fb9a520d..123eb88004 100644
--- a/apps/photos/src/components/PhotoViewer/FileInfo/RenderCreationTime.tsx
+++ b/apps/photos/src/components/PhotoViewer/FileInfo/RenderCreationTime.tsx
@@ -1,15 +1,15 @@
-import React, { useState } from 'react';
-import { EnteFile } from 'types/file';
-import CalendarTodayIcon from '@mui/icons-material/CalendarToday';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import { logError } from "@ente/shared/sentry";
+import { formatDate, formatTime } from "@ente/shared/time/format";
+import CalendarTodayIcon from "@mui/icons-material/CalendarToday";
+import EnteDateTimePicker from "components/EnteDateTimePicker";
+import { useState } from "react";
+import { EnteFile } from "types/file";
import {
changeFileCreationTime,
updateExistingFilePubMetadata,
-} from 'utils/file';
-import { formatDate, formatTime } from '@ente/shared/time/format';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import { logError } from '@ente/shared/sentry';
-import EnteDateTimePicker from 'components/EnteDateTimePicker';
-import InfoItem from './InfoItem';
+} from "utils/file";
+import InfoItem from "./InfoItem";
export function RenderCreationTime({
shouldDisableEdits,
@@ -38,13 +38,13 @@ export function RenderCreationTime({
}
const updatedFile = await changeFileCreationTime(
file,
- unixTimeInMicroSec
+ unixTimeInMicroSec,
);
updateExistingFilePubMetadata(file, updatedFile);
scheduleUpdate();
}
} catch (e) {
- logError(e, 'failed to update creationTime');
+ logError(e, "failed to update creationTime");
} finally {
closeEditMode();
setLoading(false);
diff --git a/apps/photos/src/components/PhotoViewer/FileInfo/RenderFileName.tsx b/apps/photos/src/components/PhotoViewer/FileInfo/RenderFileName.tsx
index 21bd5cbb41..e5761d5c31 100644
--- a/apps/photos/src/components/PhotoViewer/FileInfo/RenderFileName.tsx
+++ b/apps/photos/src/components/PhotoViewer/FileInfo/RenderFileName.tsx
@@ -1,31 +1,31 @@
-import React, { useEffect, useState } from 'react';
-import { EnteFile } from 'types/file';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import { logError } from "@ente/shared/sentry";
+import PhotoOutlined from "@mui/icons-material/PhotoOutlined";
+import VideocamOutlined from "@mui/icons-material/VideocamOutlined";
+import Box from "@mui/material/Box";
+import { FILE_TYPE } from "constants/file";
+import { useEffect, useState } from "react";
+import { EnteFile } from "types/file";
+import { makeHumanReadableStorage } from "utils/billing";
import {
changeFileName,
splitFilenameAndExtension,
updateExistingFilePubMetadata,
-} from 'utils/file';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import { logError } from '@ente/shared/sentry';
-import { FILE_TYPE } from 'constants/file';
-import InfoItem from './InfoItem';
-import { makeHumanReadableStorage } from 'utils/billing';
-import Box from '@mui/material/Box';
-import { FileNameEditDialog } from './FileNameEditDialog';
-import VideocamOutlined from '@mui/icons-material/VideocamOutlined';
-import PhotoOutlined from '@mui/icons-material/PhotoOutlined';
+} from "utils/file";
+import { FileNameEditDialog } from "./FileNameEditDialog";
+import InfoItem from "./InfoItem";
const getFileTitle = (filename, extension) => {
if (extension) {
- return filename + '.' + extension;
+ return filename + "." + extension;
} else {
return filename;
}
};
const getCaption = (file: EnteFile, parsedExifData) => {
- const megaPixels = parsedExifData?.['megaPixels'];
- const resolution = parsedExifData?.['resolution'];
+ const megaPixels = parsedExifData?.["megaPixels"];
+ const resolution = parsedExifData?.["resolution"];
const fileSize = file.info?.fileSize;
const captionParts = [];
@@ -66,7 +66,7 @@ export function RenderFileName({
useEffect(() => {
const [filename, extension] = splitFilenameAndExtension(
- file.metadata.title
+ file.metadata.title,
);
setFilename(filename);
setExtension(extension);
@@ -86,7 +86,7 @@ export function RenderFileName({
scheduleUpdate();
}
} catch (e) {
- logError(e, 'failed to update file name');
+ logError(e, "failed to update file name");
throw e;
}
};
diff --git a/apps/photos/src/components/PhotoViewer/FileInfo/index.tsx b/apps/photos/src/components/PhotoViewer/FileInfo/index.tsx
index a936081222..df2da85b75 100644
--- a/apps/photos/src/components/PhotoViewer/FileInfo/index.tsx
+++ b/apps/photos/src/components/PhotoViewer/FileInfo/index.tsx
@@ -1,49 +1,49 @@
-import React, { useContext, useEffect, useMemo, useState } from 'react';
-import { RenderFileName } from './RenderFileName';
-import { RenderCreationTime } from './RenderCreationTime';
-import { Box, DialogProps, Link, Stack, styled } from '@mui/material';
-import { getEXIFLocation } from 'services/upload/exifService';
-import { RenderCaption } from './RenderCaption';
-import CopyButton from '@ente/shared/components/CodeBlock/CopyButton';
-import { formatDate, formatTime } from '@ente/shared/time/format';
-import Titlebar from 'components/Titlebar';
-import MapBox from './MapBox';
-import InfoItem from './InfoItem';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { EnteFile } from 'types/file';
-import { Chip } from 'components/Chip';
-import LinkButton from 'components/pages/gallery/LinkButton';
-import { ExifData } from './ExifData';
-import { EnteDrawer } from 'components/EnteDrawer';
-import CameraOutlined from '@mui/icons-material/CameraOutlined';
-import LocationOnOutlined from '@mui/icons-material/LocationOnOutlined';
-import TextSnippetOutlined from '@mui/icons-material/TextSnippetOutlined';
-import FolderOutlined from '@mui/icons-material/FolderOutlined';
-import BackupOutlined from '@mui/icons-material/BackupOutlined';
+import CopyButton from "@ente/shared/components/CodeBlock/CopyButton";
+import { FlexWrapper } from "@ente/shared/components/Container";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import { formatDate, formatTime } from "@ente/shared/time/format";
+import BackupOutlined from "@mui/icons-material/BackupOutlined";
+import CameraOutlined from "@mui/icons-material/CameraOutlined";
+import FolderOutlined from "@mui/icons-material/FolderOutlined";
+import LocationOnOutlined from "@mui/icons-material/LocationOnOutlined";
+import TextSnippetOutlined from "@mui/icons-material/TextSnippetOutlined";
+import { Box, DialogProps, Link, Stack, styled } from "@mui/material";
+import { Chip } from "components/Chip";
+import { EnteDrawer } from "components/EnteDrawer";
+import Titlebar from "components/Titlebar";
+import LinkButton from "components/pages/gallery/LinkButton";
+import { useContext, useEffect, useMemo, useState } from "react";
+import { getEXIFLocation } from "services/upload/exifService";
+import { EnteFile } from "types/file";
+import { ExifData } from "./ExifData";
+import InfoItem from "./InfoItem";
+import MapBox from "./MapBox";
+import { RenderCaption } from "./RenderCaption";
+import { RenderCreationTime } from "./RenderCreationTime";
+import { RenderFileName } from "./RenderFileName";
import {
PhotoPeopleList,
UnidentifiedFaces,
-} from 'components/MachineLearning/PeopleList';
+} from "components/MachineLearning/PeopleList";
-import { ObjectLabelList } from 'components/MachineLearning/ObjectList';
+import { ObjectLabelList } from "components/MachineLearning/ObjectList";
// import MLServiceFileInfoButton from 'components/MachineLearning/MLServiceFileInfoButton';
-import { AppContext } from 'pages/_app';
-import { t } from 'i18next';
-import { GalleryContext } from 'pages/gallery';
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { GalleryContext } from "pages/gallery";
+import { PublicCollectionGalleryContext } from "utils/publicCollectionGallery";
import {
getMapDisableConfirmationDialog,
getMapEnableConfirmationDialog,
-} from 'utils/ui';
-import { PublicCollectionGalleryContext } from 'utils/publicCollectionGallery';
+} from "utils/ui";
export const FileInfoSidebar = styled((props: DialogProps) => (
<EnteDrawer {...props} anchor="right" />
))({
zIndex: 1501,
- '& .MuiPaper-root': {
+ "& .MuiPaper-root": {
padding: 8,
},
});
@@ -69,9 +69,9 @@ function BasicDeviceCamera({
}) {
return (
<FlexWrapper gap={1}>
- <Box>{parsedExifData['fNumber']}</Box>
- <Box>{parsedExifData['exposureTime']}</Box>
- <Box>{parsedExifData['ISO']}</Box>
+ <Box>{parsedExifData["fNumber"]}</Box>
+ <Box>{parsedExifData["exposureTime"]}</Box>
+ <Box>{parsedExifData["ISO"]}</Box>
</FlexWrapper>
);
}
@@ -99,7 +99,7 @@ export function FileInfo({
const appContext = useContext(AppContext);
const galleryContext = useContext(GalleryContext);
const publicCollectionGalleryContext = useContext(
- PublicCollectionGalleryContext
+ PublicCollectionGalleryContext,
);
const [parsedExifData, setParsedExifData] = useState<Record<string, any>>();
@@ -140,35 +140,35 @@ export function FileInfo({
return;
}
const parsedExifData = {};
- if (exif['fNumber']) {
- parsedExifData['fNumber'] = `f/${Math.ceil(exif['FNumber'])}`;
- } else if (exif['ApertureValue'] && exif['FocalLength']) {
- parsedExifData['fNumber'] = `f/${Math.ceil(
- exif['FocalLength'] / exif['ApertureValue']
+ if (exif["fNumber"]) {
+ parsedExifData["fNumber"] = `f/${Math.ceil(exif["FNumber"])}`;
+ } else if (exif["ApertureValue"] && exif["FocalLength"]) {
+ parsedExifData["fNumber"] = `f/${Math.ceil(
+ exif["FocalLength"] / exif["ApertureValue"],
)}`;
}
- const imageWidth = exif['ImageWidth'] ?? exif['ExifImageWidth'];
- const imageHeight = exif['ImageHeight'] ?? exif['ExifImageHeight'];
+ const imageWidth = exif["ImageWidth"] ?? exif["ExifImageWidth"];
+ const imageHeight = exif["ImageHeight"] ?? exif["ExifImageHeight"];
if (imageWidth && imageHeight) {
- parsedExifData['resolution'] = `${imageWidth} x ${imageHeight}`;
+ parsedExifData["resolution"] = `${imageWidth} x ${imageHeight}`;
const megaPixels = Math.round((imageWidth * imageHeight) / 1000000);
if (megaPixels) {
- parsedExifData['megaPixels'] = `${Math.round(
- (imageWidth * imageHeight) / 1000000
+ parsedExifData["megaPixels"] = `${Math.round(
+ (imageWidth * imageHeight) / 1000000,
)}MP`;
}
}
- if (exif['Make'] && exif['Model']) {
- parsedExifData['takenOnDevice'] =
- `${exif['Make']} ${exif['Model']}`;
+ if (exif["Make"] && exif["Model"]) {
+ parsedExifData["takenOnDevice"] =
+ `${exif["Make"]} ${exif["Model"]}`;
}
- if (exif['ExposureTime']) {
- parsedExifData['exposureTime'] = `1/${
- 1 / parseFloat(exif['ExposureTime'])
+ if (exif["ExposureTime"]) {
+ parsedExifData["exposureTime"] = `1/${
+ 1 / parseFloat(exif["ExposureTime"])
}`;
}
- if (exif['ISO']) {
- parsedExifData['ISO'] = `ISO${exif['ISO']}`;
+ if (exif["ISO"]) {
+ parsedExifData["ISO"] = `ISO${exif["ISO"]}`;
}
setParsedExifData(parsedExifData);
}, [exif]);
@@ -185,21 +185,21 @@ export function FileInfo({
const openEnableMapConfirmationDialog = () =>
appContext.setDialogBoxAttributesV2(
getMapEnableConfirmationDialog(() =>
- appContext.updateMapEnabled(true)
- )
+ appContext.updateMapEnabled(true),
+ ),
);
const openDisableMapConfirmationDialog = () =>
appContext.setDialogBoxAttributesV2(
getMapDisableConfirmationDialog(() =>
- appContext.updateMapEnabled(false)
- )
+ appContext.updateMapEnabled(false),
+ ),
);
return (
<FileInfoSidebar open={showInfo} onClose={handleCloseInfo}>
- <Titlebar onClose={handleCloseInfo} title={t('INFO')} backIsClose />
- <Stack pt={1} pb={3} spacing={'20px'}>
+ <Titlebar onClose={handleCloseInfo} title={t("INFO")} backIsClose />
+ <Stack pt={1} pb={3} spacing={"20px"}>
<RenderCaption
shouldDisableEdits={shouldDisableEdits}
file={file}
@@ -219,10 +219,10 @@ export function FileInfo({
file={file}
scheduleUpdate={scheduleUpdate}
/>
- {parsedExifData && parsedExifData['takenOnDevice'] && (
+ {parsedExifData && parsedExifData["takenOnDevice"] && (
<InfoItem
icon={<CameraOutlined />}
- title={parsedExifData['takenOnDevice']}
+ title={parsedExifData["takenOnDevice"]}
caption={
<BasicDeviceCamera
parsedExifData={parsedExifData}
@@ -236,15 +236,16 @@ export function FileInfo({
<>
<InfoItem
icon={<LocationOnOutlined />}
- title={t('LOCATION')}
+ title={t("LOCATION")}
caption={
!appContext.mapEnabled ||
publicCollectionGalleryContext.accessedThroughSharedURL ? (
<Link
href={getOpenStreetMapLink(location)}
target="_blank"
- sx={{ fontWeight: 'bold' }}>
- {t('SHOW_ON_MAP')}
+ sx={{ fontWeight: "bold" }}
+ >
+ {t("SHOW_ON_MAP")}
</Link>
) : (
<LinkButton
@@ -252,11 +253,12 @@ export function FileInfo({
openDisableMapConfirmationDialog
}
sx={{
- textDecoration: 'none',
- color: 'text.muted',
- fontWeight: 'bold',
- }}>
- {t('DISABLE_MAP')}
+ textDecoration: "none",
+ color: "text.muted",
+ fontWeight: "bold",
+ }}
+ >
+ {t("DISABLE_MAP")}
</LinkButton>
)
}
@@ -281,22 +283,23 @@ export function FileInfo({
)}
<InfoItem
icon={<TextSnippetOutlined />}
- title={t('DETAILS')}
+ title={t("DETAILS")}
caption={
- typeof exif === 'undefined' ? (
+ typeof exif === "undefined" ? (
<EnteSpinner size={11.33} />
) : exif !== null ? (
<LinkButton
onClick={openExif}
sx={{
- textDecoration: 'none',
- color: 'text.muted',
- fontWeight: 'bold',
- }}>
- {t('VIEW_EXIF')}
+ textDecoration: "none",
+ color: "text.muted",
+ fontWeight: "bold",
+ }}
+ >
+ {t("VIEW_EXIF")}
</LinkButton>
) : (
- t('NO_EXIF')
+ t("NO_EXIF")
)
}
hideEditOption
@@ -310,22 +313,24 @@ export function FileInfo({
{showCollectionChips && (
<InfoItem icon={<FolderOutlined />} hideEditOption>
<Box
- display={'flex'}
+ display={"flex"}
gap={1}
flexWrap="wrap"
- justifyContent={'flex-start'}
- alignItems={'flex-start'}>
+ justifyContent={"flex-start"}
+ alignItems={"flex-start"}
+ >
{fileToCollectionsMap
?.get(file.id)
?.filter((collectionID) =>
- collectionNameMap.has(collectionID)
+ collectionNameMap.has(collectionID),
)
?.map((collectionID) => (
<Chip
key={collectionID}
onClick={() =>
onCollectionChipClick(collectionID)
- }>
+ }
+ >
{collectionNameMap.get(collectionID)}
</Chip>
))}
diff --git a/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/ColoursMenu.tsx b/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/ColoursMenu.tsx
index 07a423eb04..2b294f9e2e 100644
--- a/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/ColoursMenu.tsx
+++ b/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/ColoursMenu.tsx
@@ -1,9 +1,9 @@
-import { Dispatch, SetStateAction } from 'react';
-import MenuSectionTitle from 'components/Menu/MenuSectionTitle';
-import { Box, Slider } from '@mui/material';
-import { t } from 'i18next';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
+import { Box, Slider } from "@mui/material";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import MenuSectionTitle from "components/Menu/MenuSectionTitle";
+import { t } from "i18next";
+import { Dispatch, SetStateAction } from "react";
interface IProps {
brightness: number;
@@ -21,8 +21,8 @@ interface IProps {
const ColoursMenu = (props: IProps) => {
return (
<>
- <Box px={'8px'}>
- <MenuSectionTitle title={t('BRIGHTNESS')} />
+ <Box px={"8px"}>
+ <MenuSectionTitle title={t("BRIGHTNESS")} />
<Slider
min={0}
max={200}
@@ -33,14 +33,14 @@ const ColoursMenu = (props: IProps) => {
marks={[
{
value: 100,
- label: '100%',
+ label: "100%",
},
]}
onChange={(_, value) => {
props.setBrightness(value as number);
}}
/>
- <MenuSectionTitle title={t('CONTRAST')} />
+ <MenuSectionTitle title={t("CONTRAST")} />
<Slider
min={0}
max={200}
@@ -54,11 +54,11 @@ const ColoursMenu = (props: IProps) => {
marks={[
{
value: 100,
- label: '100%',
+ label: "100%",
},
]}
/>
- <MenuSectionTitle title={t('BLUR')} />
+ <MenuSectionTitle title={t("BLUR")} />
<Slider
min={0}
max={10}
@@ -70,7 +70,7 @@ const ColoursMenu = (props: IProps) => {
props.setBlur(value as number);
}}
/>
- <MenuSectionTitle title={t('SATURATION')} />
+ <MenuSectionTitle title={t("SATURATION")} />
<Slider
min={0}
max={200}
@@ -84,19 +84,20 @@ const ColoursMenu = (props: IProps) => {
marks={[
{
value: 100,
- label: '100%',
+ label: "100%",
},
]}
/>
</Box>
<MenuItemGroup
style={{
- marginBottom: '0.5rem',
- }}>
+ marginBottom: "0.5rem",
+ }}
+ >
<EnteMenuItem
variant="toggle"
checked={props.invert}
- label={t('INVERT_COLORS')}
+ label={t("INVERT_COLORS")}
onClick={() => {
props.setInvert(!props.invert);
}}
diff --git a/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/CropMenu.tsx b/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/CropMenu.tsx
index 1d07dea1e8..6b84aee657 100644
--- a/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/CropMenu.tsx
+++ b/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/CropMenu.tsx
@@ -1,12 +1,11 @@
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import MenuSectionTitle from 'components/Menu/MenuSectionTitle';
-import { useContext } from 'react';
-import { ImageEditorOverlayContext } from './';
-import { CropBoxProps } from './';
-import type { MutableRefObject } from 'react';
-import { t } from 'i18next';
-import CropIcon from '@mui/icons-material/Crop';
+import CropIcon from "@mui/icons-material/Crop";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import MenuSectionTitle from "components/Menu/MenuSectionTitle";
+import { t } from "i18next";
+import type { MutableRefObject } from "react";
+import { useContext } from "react";
+import { CropBoxProps, ImageEditorOverlayContext } from "./";
interface IProps {
previewScale: number;
@@ -21,9 +20,9 @@ export const cropRegionOfCanvas = (
topLeftY: number,
bottomRightX: number,
bottomRightY: number,
- scale: number = 1
+ scale: number = 1,
) => {
- const context = canvas.getContext('2d');
+ const context = canvas.getContext("2d");
if (!context || !canvas) return;
context.imageSmoothingEnabled = false;
@@ -47,14 +46,14 @@ export const cropRegionOfCanvas = (
0,
0,
width,
- height
+ height,
);
};
};
export const getCropRegionArgs = (
cropBoxEle: HTMLDivElement,
- canvasEle: HTMLCanvasElement
+ canvasEle: HTMLCanvasElement,
) => {
// get the bounding rectangle of the crop box
const cropBoxRect = cropBoxEle.getBoundingClientRect();
@@ -92,11 +91,12 @@ const CropMenu = (props: IProps) => {
return (
<>
- <MenuSectionTitle title={t('FREEHAND')} />
+ <MenuSectionTitle title={t("FREEHAND")} />
<MenuItemGroup
style={{
- marginBottom: '0.5rem',
- }}>
+ marginBottom: "0.5rem",
+ }}
+ >
<EnteMenuItem
disabled={canvasLoading}
startIcon={<CropIcon />}
@@ -106,7 +106,7 @@ const CropMenu = (props: IProps) => {
const { x1, x2, y1, y2 } = getCropRegionArgs(
props.cropBoxRef.current,
- canvasRef.current
+ canvasRef.current,
);
setCanvasLoading(true);
setTransformationPerformed(true);
@@ -116,14 +116,14 @@ const CropMenu = (props: IProps) => {
x1 / props.previewScale,
y1 / props.previewScale,
x2 / props.previewScale,
- y2 / props.previewScale
+ y2 / props.previewScale,
);
props.resetCropBox();
setCanvasLoading(false);
- setCurrentTab('transform');
+ setCurrentTab("transform");
}}
- label={t('APPLY_CROP')}
+ label={t("APPLY_CROP")}
/>
</MenuItemGroup>
</>
diff --git a/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/FreehandCropRegion.tsx b/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/FreehandCropRegion.tsx
index 6c7249bbcf..5d308c31b4 100644
--- a/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/FreehandCropRegion.tsx
+++ b/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/FreehandCropRegion.tsx
@@ -1,20 +1,20 @@
-import { CropBoxProps } from './';
-import type { Ref, Dispatch, SetStateAction, CSSProperties } from 'react';
-import { forwardRef } from 'react';
+import type { CSSProperties, Dispatch, Ref, SetStateAction } from "react";
+import { forwardRef } from "react";
+import { CropBoxProps } from "./";
const handleStyle: CSSProperties = {
- position: 'absolute',
- height: '10px',
- width: '10px',
- backgroundColor: 'white',
- border: '1px solid black',
+ position: "absolute",
+ height: "10px",
+ width: "10px",
+ backgroundColor: "white",
+ border: "1px solid black",
};
const seHandleStyle: CSSProperties = {
...handleStyle,
- right: '-5px',
- bottom: '-5px',
- cursor: 'se-resize',
+ right: "-5px",
+ bottom: "-5px",
+ cursor: "se-resize",
};
interface IProps {
@@ -29,78 +29,84 @@ const FreehandCropRegion = forwardRef(
{/* Top overlay */}
<div
style={{
- position: 'absolute',
+ position: "absolute",
top: 0,
left: 0,
right: 0,
- height: props.cropBox.y + 'px', // height up to the top of the crop box
- backgroundColor: 'rgba(0,0,0,0.5)',
- pointerEvents: 'none',
- }}></div>
+ height: props.cropBox.y + "px", // height up to the top of the crop box
+ backgroundColor: "rgba(0,0,0,0.5)",
+ pointerEvents: "none",
+ }}
+ ></div>
{/* Bottom overlay */}
<div
style={{
- position: 'absolute',
+ position: "absolute",
bottom: 0,
left: 0,
right: 0,
height: `calc(100% - ${
props.cropBox.y + props.cropBox.height
}px)`, // height from the bottom of the crop box to the bottom of the canvas
- backgroundColor: 'rgba(0,0,0,0.5)',
- pointerEvents: 'none',
- }}></div>
+ backgroundColor: "rgba(0,0,0,0.5)",
+ pointerEvents: "none",
+ }}
+ ></div>
{/* Left overlay */}
<div
style={{
- position: 'absolute',
- top: props.cropBox.y + 'px',
+ position: "absolute",
+ top: props.cropBox.y + "px",
left: 0,
- width: props.cropBox.x + 'px', // width up to the left side of the crop box
- height: props.cropBox.height + 'px', // same height as the crop box
- backgroundColor: 'rgba(0,0,0,0.5)',
- pointerEvents: 'none',
- }}></div>
+ width: props.cropBox.x + "px", // width up to the left side of the crop box
+ height: props.cropBox.height + "px", // same height as the crop box
+ backgroundColor: "rgba(0,0,0,0.5)",
+ pointerEvents: "none",
+ }}
+ ></div>
{/* Right overlay */}
<div
style={{
- position: 'absolute',
- top: props.cropBox.y + 'px',
+ position: "absolute",
+ top: props.cropBox.y + "px",
right: 0,
width: `calc(100% - ${
props.cropBox.x + props.cropBox.width
}px)`, // width from the right side of the crop box to the right side of the canvas
- height: props.cropBox.height + 'px', // same height as the crop box
- backgroundColor: 'rgba(0,0,0,0.5)',
- pointerEvents: 'none',
- }}></div>
+ height: props.cropBox.height + "px", // same height as the crop box
+ backgroundColor: "rgba(0,0,0,0.5)",
+ pointerEvents: "none",
+ }}
+ ></div>
<div
style={{
- display: 'grid',
- position: 'absolute',
- left: props.cropBox.x + 'px',
- top: props.cropBox.y + 'px',
- width: props.cropBox.width + 'px',
- height: props.cropBox.height + 'px',
- border: '1px solid white',
- gridTemplateColumns: '1fr 1fr 1fr',
- gridTemplateRows: '1fr 1fr 1fr',
- gap: '0px',
+ display: "grid",
+ position: "absolute",
+ left: props.cropBox.x + "px",
+ top: props.cropBox.y + "px",
+ width: props.cropBox.width + "px",
+ height: props.cropBox.height + "px",
+ border: "1px solid white",
+ gridTemplateColumns: "1fr 1fr 1fr",
+ gridTemplateRows: "1fr 1fr 1fr",
+ gap: "0px",
zIndex: 30, // make sure the crop box is above the overlays
}}
- ref={ref}>
+ ref={ref}
+ >
{Array.from({ length: 9 }).map((_, index) => (
<div
key={index}
style={{
- border: '1px solid white',
- boxSizing: 'border-box',
- pointerEvents: 'none',
- }}></div>
+ border: "1px solid white",
+ boxSizing: "border-box",
+ pointerEvents: "none",
+ }}
+ ></div>
))}
<div
@@ -108,11 +114,12 @@ const FreehandCropRegion = forwardRef(
onMouseDown={(e) => {
e.preventDefault();
props.setIsDragging(true);
- }}></div>
+ }}
+ ></div>
</div>
</>
);
- }
+ },
);
export default FreehandCropRegion;
diff --git a/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/TransformMenu.tsx b/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/TransformMenu.tsx
index 831dc4a70d..aa096d8a4c 100644
--- a/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/TransformMenu.tsx
+++ b/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/TransformMenu.tsx
@@ -1,17 +1,17 @@
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import MenuSectionTitle from 'components/Menu/MenuSectionTitle';
-import { Fragment, useContext } from 'react';
-import { ImageEditorOverlayContext } from '.';
-import CropSquareIcon from '@mui/icons-material/CropSquare';
-import Crop169Icon from '@mui/icons-material/Crop169';
-import Crop32Icon from '@mui/icons-material/Crop32';
-import RotateLeftIcon from '@mui/icons-material/RotateLeft';
-import RotateRightIcon from '@mui/icons-material/RotateRight';
-import FlipIcon from '@mui/icons-material/Flip';
-import MenuItemDivider from 'components/Menu/MenuItemDivider';
-import { t } from 'i18next';
-import { logError } from '@ente/shared/sentry';
+import { logError } from "@ente/shared/sentry";
+import Crop169Icon from "@mui/icons-material/Crop169";
+import Crop32Icon from "@mui/icons-material/Crop32";
+import CropSquareIcon from "@mui/icons-material/CropSquare";
+import FlipIcon from "@mui/icons-material/Flip";
+import RotateLeftIcon from "@mui/icons-material/RotateLeft";
+import RotateRightIcon from "@mui/icons-material/RotateRight";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import MenuItemDivider from "components/Menu/MenuItemDivider";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import MenuSectionTitle from "components/Menu/MenuSectionTitle";
+import { t } from "i18next";
+import { Fragment, useContext } from "react";
+import { ImageEditorOverlayContext } from ".";
const PRESET_ASPECT_RATIOS = [
{
@@ -44,9 +44,9 @@ const TransformMenu = () => {
const cropCanvas = (
canvas: HTMLCanvasElement,
widthRatio: number,
- heightRatio: number
+ heightRatio: number,
) => {
- const context = canvas.getContext('2d');
+ const context = canvas.getContext("2d");
const aspectRatio = widthRatio / heightRatio;
@@ -85,16 +85,16 @@ const TransformMenu = () => {
0,
0,
newWidth,
- newHeight
+ newHeight,
);
};
};
const flipCanvas = (
canvas: HTMLCanvasElement,
- direction: 'vertical' | 'horizontal'
+ direction: "vertical" | "horizontal",
) => {
- const context = canvas.getContext('2d');
+ const context = canvas.getContext("2d");
if (!context || !canvas) return;
context.resetTransform();
context.imageSmoothingEnabled = false;
@@ -106,7 +106,7 @@ const TransformMenu = () => {
context.save();
- if (direction === 'horizontal') {
+ if (direction === "horizontal") {
context.translate(canvas.width, 0);
context.scale(-1, 1);
} else {
@@ -121,7 +121,7 @@ const TransformMenu = () => {
};
const rotateCanvas = (canvas: HTMLCanvasElement, angle: number) => {
- const context = canvas?.getContext('2d');
+ const context = canvas?.getContext("2d");
if (!context || !canvas) return;
context.imageSmoothingEnabled = false;
@@ -152,7 +152,7 @@ const TransformMenu = () => {
-image.width / 2,
-image.height / 2,
image.width,
- image.height
+ image.height,
);
context.restore();
@@ -167,36 +167,36 @@ const TransformMenu = () => {
cropCanvas(
originalSizeCanvasRef.current,
widthRatio,
- heightRatio
+ heightRatio,
);
setCanvasLoading(false);
setTransformationPerformed(true);
} catch (e) {
- logError(e, 'crop handler failed', {
+ logError(e, "crop handler failed", {
widthRatio,
heightRatio,
});
}
};
- const createRotationHandler = (rotation: 'left' | 'right') => () => {
+ const createRotationHandler = (rotation: "left" | "right") => () => {
try {
setCanvasLoading(true);
- rotateCanvas(canvasRef.current, rotation === 'left' ? -90 : 90);
+ rotateCanvas(canvasRef.current, rotation === "left" ? -90 : 90);
rotateCanvas(
originalSizeCanvasRef.current,
- rotation === 'left' ? -90 : 90
+ rotation === "left" ? -90 : 90,
);
setCanvasLoading(false);
setTransformationPerformed(true);
} catch (e) {
- logError(e, 'rotation handler failed', {
+ logError(e, "rotation handler failed", {
rotation,
});
}
};
const createFlipCanvasHandler =
- (direction: 'vertical' | 'horizontal') => () => {
+ (direction: "vertical" | "horizontal") => () => {
try {
setCanvasLoading(true);
flipCanvas(canvasRef.current, direction);
@@ -204,7 +204,7 @@ const TransformMenu = () => {
setCanvasLoading(false);
setTransformationPerformed(true);
} catch (e) {
- logError(e, 'flip handler failed', {
+ logError(e, "flip handler failed", {
direction,
});
}
@@ -212,22 +212,24 @@ const TransformMenu = () => {
return (
<>
- <MenuSectionTitle title={t('ASPECT_RATIO')} />
+ <MenuSectionTitle title={t("ASPECT_RATIO")} />
<MenuItemGroup
style={{
- marginBottom: '0.5rem',
- }}>
+ marginBottom: "0.5rem",
+ }}
+ >
<EnteMenuItem
disabled={canvasLoading}
startIcon={<CropSquareIcon />}
onClick={createCropHandler(1, 1)}
- label={t('SQUARE') + ' (1:1)'}
+ label={t("SQUARE") + " (1:1)"}
/>
</MenuItemGroup>
<MenuItemGroup
style={{
- marginBottom: '1rem',
- }}>
+ marginBottom: "1rem",
+ }}
+ >
{PRESET_ASPECT_RATIOS.map((ratio, index) => (
<Fragment key={index}>
<EnteMenuItem
@@ -235,7 +237,7 @@ const TransformMenu = () => {
startIcon={ratio.icon}
onClick={createCropHandler(
ratio.width,
- ratio.height
+ ratio.height,
)}
label={`${ratio.width}:${ratio.height}`}
/>
@@ -247,8 +249,9 @@ const TransformMenu = () => {
</MenuItemGroup>
<MenuItemGroup
style={{
- marginBottom: '1rem',
- }}>
+ marginBottom: "1rem",
+ }}
+ >
{PRESET_ASPECT_RATIOS.map((ratio, index) => (
<Fragment key={index}>
<EnteMenuItem
@@ -257,7 +260,7 @@ const TransformMenu = () => {
startIcon={ratio.icon}
onClick={createCropHandler(
ratio.height,
- ratio.width
+ ratio.width,
)}
label={`${ratio.height}:${ratio.width}`}
/>
@@ -267,42 +270,44 @@ const TransformMenu = () => {
</Fragment>
))}
</MenuItemGroup>
- <MenuSectionTitle title={t('ROTATION')} />
+ <MenuSectionTitle title={t("ROTATION")} />
<MenuItemGroup
style={{
- marginBottom: '1rem',
- }}>
+ marginBottom: "1rem",
+ }}
+ >
<EnteMenuItem
disabled={canvasLoading}
startIcon={<RotateLeftIcon />}
- onClick={createRotationHandler('left')}
- label={t('ROTATE_LEFT') + ' 90˚'}
+ onClick={createRotationHandler("left")}
+ label={t("ROTATE_LEFT") + " 90˚"}
/>
<MenuItemDivider />
<EnteMenuItem
disabled={canvasLoading}
startIcon={<RotateRightIcon />}
- onClick={createRotationHandler('right')}
- label={t('ROTATE_RIGHT') + ' 90˚'}
+ onClick={createRotationHandler("right")}
+ label={t("ROTATE_RIGHT") + " 90˚"}
/>
</MenuItemGroup>
- <MenuSectionTitle title={t('FLIP')} />
+ <MenuSectionTitle title={t("FLIP")} />
<MenuItemGroup
style={{
- marginBottom: '1rem',
- }}>
+ marginBottom: "1rem",
+ }}
+ >
<EnteMenuItem
disabled={canvasLoading}
startIcon={<FlipIcon />}
- onClick={createFlipCanvasHandler('vertical')}
- label={t('FLIP_VERTICALLY')}
+ onClick={createFlipCanvasHandler("vertical")}
+ label={t("FLIP_VERTICALLY")}
/>
<MenuItemDivider />
<EnteMenuItem
disabled={canvasLoading}
startIcon={<FlipIcon />}
- onClick={createFlipCanvasHandler('horizontal')}
- label={t('FLIP_HORIZONTALLY')}
+ onClick={createFlipCanvasHandler("horizontal")}
+ label={t("FLIP_HORIZONTALLY")}
/>
</MenuItemGroup>
</>
diff --git a/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/index.tsx b/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/index.tsx
index 616c58de80..bf4a186b7f 100644
--- a/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/index.tsx
+++ b/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/index.tsx
@@ -6,51 +6,52 @@ import {
Tab,
Tabs,
Typography,
-} from '@mui/material';
+} from "@mui/material";
import {
- useEffect,
- useRef,
- useState,
- createContext,
Dispatch,
- SetStateAction,
MutableRefObject,
+ SetStateAction,
+ createContext,
useContext,
-} from 'react';
-
-import { EnteFile } from 'types/file';
-import downloadManager from 'services/download';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import CropOriginalIcon from '@mui/icons-material/CropOriginal';
-import MenuSectionTitle from 'components/Menu/MenuSectionTitle';
-import DownloadIcon from '@mui/icons-material/Download';
-import mime from 'mime-types';
-import CloseIcon from '@mui/icons-material/Close';
-import { HorizontalFlex } from '@ente/shared/components/Container';
-import TransformMenu from './TransformMenu';
-import CropMenu from './CropMenu';
-import ColoursMenu from './ColoursMenu';
-import { FileWithCollection } from 'types/upload';
-import uploadManager from 'services/upload/uploadManager';
-import { getLocalCollections } from 'services/collectionService';
-import CloudUploadIcon from '@mui/icons-material/CloudUpload';
-import MenuItemDivider from 'components/Menu/MenuItemDivider';
-import { t } from 'i18next';
-import { EnteDrawer } from 'components/EnteDrawer';
-import ChevronRightIcon from '@mui/icons-material/ChevronRight';
-import MenuIcon from '@mui/icons-material/Menu';
-import { AppContext } from 'pages/_app';
-import { getEditorCloseConfirmationMessage } from 'utils/ui';
-import { logError } from '@ente/shared/sentry';
-import { getFileType } from 'services/typeDetectionService';
-import { downloadUsingAnchor } from '@ente/shared/utils';
-import { CORNER_THRESHOLD, FILTER_DEFAULT_VALUES } from 'constants/photoEditor';
-import FreehandCropRegion from './FreehandCropRegion';
-import EnteButton from '@ente/shared/components/EnteButton';
-import { CenteredFlex } from '@ente/shared/components/Container';
-import CropIcon from '@mui/icons-material/Crop';
-import { cropRegionOfCanvas, getCropRegionArgs } from './CropMenu';
+ useEffect,
+ useRef,
+ useState,
+} from "react";
+
+import {
+ CenteredFlex,
+ HorizontalFlex,
+} from "@ente/shared/components/Container";
+import EnteButton from "@ente/shared/components/EnteButton";
+import { logError } from "@ente/shared/sentry";
+import { downloadUsingAnchor } from "@ente/shared/utils";
+import ChevronRightIcon from "@mui/icons-material/ChevronRight";
+import CloseIcon from "@mui/icons-material/Close";
+import CloudUploadIcon from "@mui/icons-material/CloudUpload";
+import CropIcon from "@mui/icons-material/Crop";
+import CropOriginalIcon from "@mui/icons-material/CropOriginal";
+import DownloadIcon from "@mui/icons-material/Download";
+import MenuIcon from "@mui/icons-material/Menu";
+import { EnteDrawer } from "components/EnteDrawer";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import MenuItemDivider from "components/Menu/MenuItemDivider";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import MenuSectionTitle from "components/Menu/MenuSectionTitle";
+import { CORNER_THRESHOLD, FILTER_DEFAULT_VALUES } from "constants/photoEditor";
+import { t } from "i18next";
+import mime from "mime-types";
+import { AppContext } from "pages/_app";
+import { getLocalCollections } from "services/collectionService";
+import downloadManager from "services/download";
+import { getFileType } from "services/typeDetectionService";
+import uploadManager from "services/upload/uploadManager";
+import { EnteFile } from "types/file";
+import { FileWithCollection } from "types/upload";
+import { getEditorCloseConfirmationMessage } from "utils/ui";
+import ColoursMenu from "./ColoursMenu";
+import CropMenu, { cropRegionOfCanvas, getCropRegionArgs } from "./CropMenu";
+import FreehandCropRegion from "./FreehandCropRegion";
+import TransformMenu from "./TransformMenu";
interface IProps {
file: EnteFile;
@@ -67,15 +68,15 @@ export const ImageEditorOverlayContext = createContext(
setCanvasLoading: Dispatch<SetStateAction<boolean>>;
canvasLoading: boolean;
setCurrentTab: Dispatch<SetStateAction<OperationTab>>;
- }
+ },
);
-type OperationTab = 'crop' | 'transform' | 'colours';
+type OperationTab = "crop" | "transform" | "colours";
const getEditedFileName = (fileName: string) => {
- const fileNameParts = fileName.split('.');
+ const fileNameParts = fileName.split(".");
const extension = fileNameParts.pop();
- const editedFileName = `${fileNameParts.join('.')}-edited.${extension}`;
+ const editedFileName = `${fileNameParts.join(".")}-edited.${extension}`;
return editedFileName;
};
@@ -93,19 +94,19 @@ const ImageEditorOverlay = (props: IProps) => {
const originalSizeCanvasRef = useRef<HTMLCanvasElement | null>(null);
const parentRef = useRef<HTMLDivElement | null>(null);
- const [fileURL, setFileURL] = useState<string>('');
+ const [fileURL, setFileURL] = useState<string>("");
const [currentRotationAngle, setCurrentRotationAngle] = useState(0);
- const [currentTab, setCurrentTab] = useState<OperationTab>('transform');
+ const [currentTab, setCurrentTab] = useState<OperationTab>("transform");
const [brightness, setBrightness] = useState(
- FILTER_DEFAULT_VALUES.brightness
+ FILTER_DEFAULT_VALUES.brightness,
);
const [contrast, setContrast] = useState(FILTER_DEFAULT_VALUES.contrast);
const [blur, setBlur] = useState(FILTER_DEFAULT_VALUES.blur);
const [saturation, setSaturation] = useState(
- FILTER_DEFAULT_VALUES.saturation
+ FILTER_DEFAULT_VALUES.saturation,
);
const [invert, setInvert] = useState(FILTER_DEFAULT_VALUES.invert);
@@ -157,7 +158,7 @@ const ImageEditorOverlay = (props: IProps) => {
};
const handleDragStart = (e) => {
- if (currentTab !== 'crop') return;
+ if (currentTab !== "crop") return;
const rect = cropBoxRef.current.getBoundingClientRect();
const offsetX = e.pageX - rect.left - rect.width / 2;
@@ -199,11 +200,11 @@ const ImageEditorOverlay = (props: IProps) => {
setCropBox((prev) => {
const newWidth = Math.min(
beforeGrowthWidth + dx,
- canvasBounds.width - prev.x + offsetX
+ canvasBounds.width - prev.x + offsetX,
);
const newHeight = Math.min(
beforeGrowthHeight + dy,
- canvasBounds.height - prev.y + offsetY
+ canvasBounds.height - prev.y + offsetY,
);
return {
@@ -220,11 +221,11 @@ const ImageEditorOverlay = (props: IProps) => {
// constrain the new position to the canvas boundaries, accounting for the offset
newX = Math.max(
offsetX,
- Math.min(newX, offsetX + canvasBounds.width - prev.width)
+ Math.min(newX, offsetX + canvasBounds.width - prev.width),
);
newY = Math.max(
offsetY,
- Math.min(newY, offsetY + canvasBounds.height - prev.height)
+ Math.min(newY, offsetY + canvasBounds.height - prev.height),
);
return {
@@ -271,15 +272,15 @@ const ImageEditorOverlay = (props: IProps) => {
contrast !== FILTER_DEFAULT_VALUES.contrast ||
blur !== FILTER_DEFAULT_VALUES.blur ||
saturation !== FILTER_DEFAULT_VALUES.saturation ||
- invert !== FILTER_DEFAULT_VALUES.invert
+ invert !== FILTER_DEFAULT_VALUES.invert,
);
} catch (e) {
- logError(e, 'Error applying filters');
+ logError(e, "Error applying filters");
}
}, [brightness, contrast, blur, saturation, invert, canvasRef, fileURL]);
useEffect(() => {
- if (currentTab !== 'crop') return;
+ if (currentTab !== "crop") return;
resetCropBox();
setShowControlsDrawer(false);
}, [currentTab]);
@@ -294,7 +295,7 @@ const ImageEditorOverlay = (props: IProps) => {
const filterString = `brightness(${brightness}%) contrast(${contrast}%) blur(${blurRadius}px) saturate(${saturation}%) invert(${
invert ? 1 : 0
})`;
- const context = canvas.getContext('2d');
+ const context = canvas.getContext("2d");
context.imageSmoothingEnabled = false;
context.filter = filterString;
@@ -309,7 +310,7 @@ const ImageEditorOverlay = (props: IProps) => {
0,
0,
canvas.width,
- canvas.height
+ canvas.height,
);
context.save();
context.drawImage(
@@ -317,7 +318,7 @@ const ImageEditorOverlay = (props: IProps) => {
0,
0,
canvas.width,
- canvas.height
+ canvas.height,
);
context.restore();
resolve(true);
@@ -328,7 +329,7 @@ const ImageEditorOverlay = (props: IProps) => {
});
}
} catch (e) {
- logError(e, 'Error applying filters');
+ logError(e, "Error applying filters");
throw e;
}
};
@@ -364,11 +365,11 @@ const ImageEditorOverlay = (props: IProps) => {
setCurrentRotationAngle(0);
const img = new Image();
- const ctx = canvasRef.current.getContext('2d');
+ const ctx = canvasRef.current.getContext("2d");
ctx.imageSmoothingEnabled = false;
if (!fileURL) {
const srcURLs = await downloadManager.getFileForPreview(
- props.file
+ props.file,
);
img.src = srcURLs.url as string;
setFileURL(srcURLs.url as string);
@@ -381,7 +382,7 @@ const ImageEditorOverlay = (props: IProps) => {
try {
const scale = Math.min(
parentRef.current.clientWidth / img.width,
- parentRef.current.clientHeight / img.height
+ parentRef.current.clientHeight / img.height,
);
setPreviewCanvasScale(scale);
@@ -396,7 +397,7 @@ const ImageEditorOverlay = (props: IProps) => {
originalSizeCanvasRef.current.height = img.height;
const oSCtx =
- originalSizeCanvasRef.current.getContext('2d');
+ originalSizeCanvasRef.current.getContext("2d");
oSCtx?.drawImage(img, 0, 0, img.width, img.height);
@@ -421,7 +422,7 @@ const ImageEditorOverlay = (props: IProps) => {
};
});
} catch (e) {
- logError(e, 'Error loading canvas');
+ logError(e, "Error loading canvas");
}
};
@@ -440,13 +441,13 @@ const ImageEditorOverlay = (props: IProps) => {
const image = new Image();
image.src = canvas.toDataURL();
- const context = canvas.getContext('2d');
+ const context = canvas.getContext("2d");
if (!context) return;
return new Promise((resolve) => {
canvas.toBlob(resolve, mimeType);
});
} catch (e) {
- logError(e, 'Error exporting canvas to blob');
+ logError(e, "Error exporting canvas to blob");
throw e;
}
};
@@ -454,7 +455,7 @@ const ImageEditorOverlay = (props: IProps) => {
const getEditedFile = async () => {
const blob = await exportCanvasToBlob();
if (!blob) {
- throw Error('no blob');
+ throw Error("no blob");
}
const editedFileName = getEditedFileName(props.file.metadata.title);
const editedFile = new File([blob], editedFileName);
@@ -469,7 +470,7 @@ const ImageEditorOverlay = (props: IProps) => {
const handleCloseWithConfirmation = () => {
if (transformationPerformed || coloursAdjusted) {
appContext.setDialogBoxAttributesV2(
- getEditorCloseConfirmationMessage(handleClose)
+ getEditorCloseConfirmationMessage(handleClose),
);
} else {
handleClose();
@@ -487,11 +488,11 @@ const ImageEditorOverlay = (props: IProps) => {
const editedFile = await getEditedFile();
const fileType = await getFileType(editedFile);
const tempImgURL = URL.createObjectURL(
- new Blob([editedFile], { type: fileType.mimeType })
+ new Blob([editedFile], { type: fileType.mimeType }),
);
downloadUsingAnchor(tempImgURL, editedFile.name);
} catch (e) {
- logError(e, 'Error downloading edited photo');
+ logError(e, "Error downloading edited photo");
}
};
@@ -502,7 +503,7 @@ const ImageEditorOverlay = (props: IProps) => {
const collections = await getLocalCollections();
const collection = collections.find(
- (c) => c.id === props.file.collectionID
+ (c) => c.id === props.file.collectionID,
);
const editedFile = await getEditedFile();
@@ -519,29 +520,32 @@ const ImageEditorOverlay = (props: IProps) => {
props.onClose();
props.closePhotoViewer();
} catch (e) {
- logError(e, 'Error saving copy to ente');
+ logError(e, "Error saving copy to ente");
}
};
return (
<>
<Backdrop
sx={{
- background: '#000',
+ background: "#000",
zIndex: 1600,
- width: '100%',
+ width: "100%",
}}
- open>
+ open
+ >
<Box padding="1rem" width="100%" height="100%">
<HorizontalFlex
- justifyContent={'space-between'}
- alignItems={'center'}>
+ justifyContent={"space-between"}
+ alignItems={"center"}
+ >
<Typography variant="h2" fontWeight="bold">
- {t('PHOTO_EDITOR')}
+ {t("PHOTO_EDITOR")}
</Typography>
<IconButton
onClick={() => {
setShowControlsDrawer(true);
- }}>
+ }}
+ >
<MenuIcon />
</IconButton>
</HorizontalFlex>
@@ -549,20 +553,22 @@ const ImageEditorOverlay = (props: IProps) => {
width="100%"
height="100%"
overflow="hidden"
- boxSizing={'border-box'}
+ boxSizing={"border-box"}
display="flex"
alignItems="center"
justifyContent="center"
position="relative"
onMouseUp={handleDragEnd}
onMouseMove={isDragging ? handleDrag : null}
- onMouseDown={handleDragStart}>
+ onMouseDown={handleDragStart}
+ >
<Box
style={{
- position: 'relative',
- width: '100%',
- height: '100%',
- }}>
+ position: "relative",
+ width: "100%",
+ height: "100%",
+ }}
+ >
<Box
height="90%"
width="100%"
@@ -570,7 +576,8 @@ const ImageEditorOverlay = (props: IProps) => {
display="flex"
alignItems="center"
justifyContent="center"
- position="relative">
+ position="relative"
+ >
{(fileURL === null || canvasLoading) && (
<CircularProgress />
)}
@@ -578,22 +585,22 @@ const ImageEditorOverlay = (props: IProps) => {
<canvas
ref={canvasRef}
style={{
- objectFit: 'contain',
+ objectFit: "contain",
display:
fileURL === null || canvasLoading
- ? 'none'
- : 'block',
- position: 'absolute',
+ ? "none"
+ : "block",
+ position: "absolute",
}}
/>
<canvas
ref={originalSizeCanvasRef}
style={{
- display: 'none',
+ display: "none",
}}
/>
- {currentTab === 'crop' && (
+ {currentTab === "crop" && (
<FreehandCropRegion
cropBox={cropBox}
ref={cropBoxRef}
@@ -601,7 +608,7 @@ const ImageEditorOverlay = (props: IProps) => {
/>
)}
</Box>
- {currentTab === 'crop' && (
+ {currentTab === "crop" && (
<CenteredFlex marginTop="1rem">
<EnteButton
color="accent"
@@ -616,7 +623,7 @@ const ImageEditorOverlay = (props: IProps) => {
const { x1, x2, y1, y2 } =
getCropRegionArgs(
cropBoxRef.current,
- canvasRef.current
+ canvasRef.current,
);
setCanvasLoading(true);
setTransformationPerformed(true);
@@ -625,21 +632,22 @@ const ImageEditorOverlay = (props: IProps) => {
x1,
y1,
x2,
- y2
+ y2,
);
cropRegionOfCanvas(
originalSizeCanvasRef.current,
x1 / previewCanvasScale,
y1 / previewCanvasScale,
x2 / previewCanvasScale,
- y2 / previewCanvasScale
+ y2 / previewCanvasScale,
);
resetCropBox();
setCanvasLoading(false);
- setCurrentTab('transform');
- }}>
- {t('APPLY_CROP')}
+ setCurrentTab("transform");
+ }}
+ >
+ {t("APPLY_CROP")}
</EnteButton>
</CenteredFlex>
)}
@@ -650,12 +658,14 @@ const ImageEditorOverlay = (props: IProps) => {
variant="persistent"
anchor="right"
open={showControlsDrawer}
- onClose={handleCloseWithConfirmation}>
- <HorizontalFlex justifyContent={'space-between'}>
+ onClose={handleCloseWithConfirmation}
+ >
+ <HorizontalFlex justifyContent={"space-between"}>
<IconButton
onClick={() => {
setShowControlsDrawer(false);
- }}>
+ }}
+ >
<ChevronRightIcon />
</IconButton>
<IconButton onClick={handleCloseWithConfirmation}>
@@ -667,28 +677,30 @@ const ImageEditorOverlay = (props: IProps) => {
value={currentTab}
onChange={(_, value) => {
setCurrentTab(value);
- }}>
- <Tab label={t('CROP')} value="crop" />
- <Tab label={t('TRANSFORM')} value="transform" />
+ }}
+ >
+ <Tab label={t("CROP")} value="crop" />
+ <Tab label={t("TRANSFORM")} value="transform" />
<Tab
- label={t('COLORS')}
+ label={t("COLORS")}
value="colours"
disabled={transformationPerformed}
/>
</Tabs>
</HorizontalFlex>
- <MenuSectionTitle title={t('RESET')} />
+ <MenuSectionTitle title={t("RESET")} />
<MenuItemGroup
style={{
- marginBottom: '0.5rem',
- }}>
+ marginBottom: "0.5rem",
+ }}
+ >
<EnteMenuItem
disabled={canvasLoading}
startIcon={<CropOriginalIcon />}
onClick={() => {
loadCanvas();
}}
- label={t('RESTORE_ORIGINAL')}
+ label={t("RESTORE_ORIGINAL")}
/>
</MenuItemGroup>
<ImageEditorOverlayContext.Provider
@@ -699,8 +711,9 @@ const ImageEditorOverlay = (props: IProps) => {
canvasLoading,
setTransformationPerformed,
setCurrentTab,
- }}>
- {currentTab === 'crop' && (
+ }}
+ >
+ {currentTab === "crop" && (
<CropMenu
previewScale={previewCanvasScale}
cropBoxProps={cropBox}
@@ -708,9 +721,9 @@ const ImageEditorOverlay = (props: IProps) => {
resetCropBox={resetCropBox}
/>
)}
- {currentTab === 'transform' && <TransformMenu />}
+ {currentTab === "transform" && <TransformMenu />}
</ImageEditorOverlayContext.Provider>
- {currentTab === 'colours' && (
+ {currentTab === "colours" && (
<ColoursMenu
brightness={brightness}
contrast={contrast}
@@ -724,12 +737,12 @@ const ImageEditorOverlay = (props: IProps) => {
setInvert={setInvert}
/>
)}
- <MenuSectionTitle title={t('EXPORT')} />
+ <MenuSectionTitle title={t("EXPORT")} />
<MenuItemGroup>
<EnteMenuItem
startIcon={<DownloadIcon />}
onClick={downloadEditedPhoto}
- label={t('DOWNLOAD_EDITED')}
+ label={t("DOWNLOAD_EDITED")}
disabled={
!transformationPerformed && !coloursAdjusted
}
@@ -738,7 +751,7 @@ const ImageEditorOverlay = (props: IProps) => {
<EnteMenuItem
startIcon={<CloudUploadIcon />}
onClick={saveCopyToEnte}
- label={t('SAVE_A_COPY_TO_ENTE')}
+ label={t("SAVE_A_COPY_TO_ENTE")}
disabled={
!transformationPerformed && !coloursAdjusted
}
@@ -746,7 +759,7 @@ const ImageEditorOverlay = (props: IProps) => {
</MenuItemGroup>
{!transformationPerformed && !coloursAdjusted && (
<MenuSectionTitle
- title={t('PHOTO_EDIT_REQUIRED_TO_SAVE')}
+ title={t("PHOTO_EDIT_REQUIRED_TO_SAVE")}
/>
)}
</EnteDrawer>
diff --git a/apps/photos/src/components/PhotoViewer/index.tsx b/apps/photos/src/components/PhotoViewer/index.tsx
index 24ed4bbacc..7025421720 100644
--- a/apps/photos/src/components/PhotoViewer/index.tsx
+++ b/apps/photos/src/components/PhotoViewer/index.tsx
@@ -1,64 +1,64 @@
-import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
-import Photoswipe from 'photoswipe';
-import PhotoswipeUIDefault from 'photoswipe/dist/photoswipe-ui-default';
-import classnames from 'classnames';
+import { logError } from "@ente/shared/sentry";
+import classnames from "classnames";
+import Photoswipe from "photoswipe";
+import PhotoswipeUIDefault from "photoswipe/dist/photoswipe-ui-default";
+import { useContext, useEffect, useMemo, useRef, useState } from "react";
import {
addToFavorites,
removeFromFavorites,
-} from 'services/collectionService';
-import { EnteFile } from 'types/file';
+} from "services/collectionService";
+import { EnteFile } from "types/file";
import {
copyFileToClipboard,
+ downloadSingleFile,
getFileExtension,
getFileFromURL,
- isSupportedRawFormat,
isRawFile,
- downloadSingleFile,
-} from 'utils/file';
-import { logError } from '@ente/shared/sentry';
-
-import { FILE_TYPE } from 'constants/file';
-import { isClipboardItemPresent } from 'utils/common';
-import { playVideo, pauseVideo } from 'utils/photoFrame';
-import { PublicCollectionGalleryContext } from 'utils/publicCollectionGallery';
-import { AppContext } from 'pages/_app';
-import { FileInfo } from './FileInfo';
+ isSupportedRawFormat,
+} from "utils/file";
+
+import { FlexWrapper } from "@ente/shared/components/Container";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import { addLocalLog } from "@ente/shared/logging";
+import AlbumOutlined from "@mui/icons-material/AlbumOutlined";
+import ChevronLeft from "@mui/icons-material/ChevronLeft";
+import ChevronRight from "@mui/icons-material/ChevronRight";
+import CloseIcon from "@mui/icons-material/Close";
+import ContentCopy from "@mui/icons-material/ContentCopy";
+import DeleteIcon from "@mui/icons-material/Delete";
+import EditIcon from "@mui/icons-material/Edit";
+import FavoriteBorderIcon from "@mui/icons-material/FavoriteBorderRounded";
+import FavoriteIcon from "@mui/icons-material/FavoriteRounded";
+import DownloadIcon from "@mui/icons-material/FileDownloadOutlined";
+import FullscreenExitOutlinedIcon from "@mui/icons-material/FullscreenExitOutlined";
+import FullscreenOutlinedIcon from "@mui/icons-material/FullscreenOutlined";
+import InfoIcon from "@mui/icons-material/InfoOutlined";
+import ReplayIcon from "@mui/icons-material/Replay";
+import ZoomInOutlinedIcon from "@mui/icons-material/ZoomInOutlined";
+import { Box, Button, styled } from "@mui/material";
+import { FILE_TYPE } from "constants/file";
import {
defaultLivePhotoDefaultOptions,
photoSwipeV4Events,
-} from 'constants/photoViewer';
-import { LivePhotoBtnContainer } from './styledComponents/LivePhotoBtn';
-import DownloadIcon from '@mui/icons-material/FileDownloadOutlined';
-import CloseIcon from '@mui/icons-material/Close';
-import ZoomInOutlinedIcon from '@mui/icons-material/ZoomInOutlined';
-import FullscreenOutlinedIcon from '@mui/icons-material/FullscreenOutlined';
-import InfoIcon from '@mui/icons-material/InfoOutlined';
-import FavoriteIcon from '@mui/icons-material/FavoriteRounded';
-import FavoriteBorderIcon from '@mui/icons-material/FavoriteBorderRounded';
-import FullscreenExitOutlinedIcon from '@mui/icons-material/FullscreenExitOutlined';
-import ChevronRight from '@mui/icons-material/ChevronRight';
-import DeleteIcon from '@mui/icons-material/Delete';
-import { trashFiles } from 'services/fileService';
-import { getTrashFileMessage } from 'utils/ui';
-import { Box, Button, styled } from '@mui/material';
-import { addLocalLog } from '@ente/shared/logging';
-import ContentCopy from '@mui/icons-material/ContentCopy';
-import ChevronLeft from '@mui/icons-material/ChevronLeft';
-import { t } from 'i18next';
-import { getParsedExifData } from 'services/upload/exifService';
-import { getFileType } from 'services/typeDetectionService';
-import { ConversionFailedNotification } from './styledComponents/ConversionFailedNotification';
-import { GalleryContext } from 'pages/gallery';
-import downloadManager, { LoadedLivePhotoSourceURL } from 'services/download';
-import CircularProgressWithLabel from './styledComponents/CircularProgressWithLabel';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import AlbumOutlined from '@mui/icons-material/AlbumOutlined';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import isElectron from 'is-electron';
-import ReplayIcon from '@mui/icons-material/Replay';
-import ImageEditorOverlay from './ImageEditorOverlay';
-import EditIcon from '@mui/icons-material/Edit';
-import { SetFilesDownloadProgressAttributesCreator } from 'types/gallery';
+} from "constants/photoViewer";
+import { t } from "i18next";
+import isElectron from "is-electron";
+import { AppContext } from "pages/_app";
+import { GalleryContext } from "pages/gallery";
+import downloadManager, { LoadedLivePhotoSourceURL } from "services/download";
+import { trashFiles } from "services/fileService";
+import { getFileType } from "services/typeDetectionService";
+import { getParsedExifData } from "services/upload/exifService";
+import { SetFilesDownloadProgressAttributesCreator } from "types/gallery";
+import { isClipboardItemPresent } from "utils/common";
+import { pauseVideo, playVideo } from "utils/photoFrame";
+import { PublicCollectionGalleryContext } from "utils/publicCollectionGallery";
+import { getTrashFileMessage } from "utils/ui";
+import { FileInfo } from "./FileInfo";
+import ImageEditorOverlay from "./ImageEditorOverlay";
+import CircularProgressWithLabel from "./styledComponents/CircularProgressWithLabel";
+import { ConversionFailedNotification } from "./styledComponents/ConversionFailedNotification";
+import { LivePhotoBtnContainer } from "./styledComponents/LivePhotoBtn";
interface PhotoswipeFullscreenAPI {
enter: () => void;
@@ -66,13 +66,13 @@ interface PhotoswipeFullscreenAPI {
isFullscreen: () => boolean;
}
-const CaptionContainer = styled('div')(({ theme }) => ({
+const CaptionContainer = styled("div")(({ theme }) => ({
padding: theme.spacing(2),
- wordBreak: 'break-word',
- textAlign: 'right',
- maxWidth: '375px',
- fontSize: '14px',
- lineHeight: '17px',
+ wordBreak: "break-word",
+ textAlign: "right",
+ maxWidth: "375px",
+ fontSize: "14px",
+ lineHeight: "17px",
backgroundColor: theme.colors.backdrop.faint,
backdropFilter: `blur(${theme.colors.blur.base})`,
}));
@@ -100,7 +100,7 @@ function PhotoViewer(props: Iprops) {
const galleryContext = useContext(GalleryContext);
const appContext = useContext(AppContext);
const publicCollectionGalleryContext = useContext(
- PublicCollectionGalleryContext
+ PublicCollectionGalleryContext,
);
const { isOpen, items } = props;
@@ -116,7 +116,7 @@ function PhotoViewer(props: Iprops) {
}>();
const exifCopy = useRef(null);
const [livePhotoBtnOptions, setLivePhotoBtnOptions] = useState(
- defaultLivePhotoDefaultOptions
+ defaultLivePhotoDefaultOptions,
);
const [isOwnFile, setIsOwnFile] = useState(false);
const [showConvertBtn, setShowConvertBtn] = useState(false);
@@ -173,48 +173,48 @@ function PhotoViewer(props: Iprops) {
return;
}
- addLocalLog(() => 'Event: ' + event.key);
+ addLocalLog(() => "Event: " + event.key);
switch (event.key) {
- case 'i':
- case 'I':
+ case "i":
+ case "I":
setShowInfo(true);
break;
- case 'Backspace':
- case 'Delete':
+ case "Backspace":
+ case "Delete":
confirmTrashFile(photoSwipe?.currItem as EnteFile);
break;
- case 'd':
- case 'D':
+ case "d":
+ case "D":
downloadFileHelper(photoSwipe?.currItem as EnteFile);
break;
- case 'f':
- case 'F':
+ case "f":
+ case "F":
toggleFullscreen(photoSwipe);
break;
- case 'l':
- case 'L':
+ case "l":
+ case "L":
onFavClick(photoSwipe?.currItem as EnteFile);
break;
- case 'ArrowLeft':
- handleArrowClick(event, 'left');
+ case "ArrowLeft":
+ handleArrowClick(event, "left");
break;
- case 'ArrowRight':
- handleArrowClick(event, 'right');
+ case "ArrowRight":
+ handleArrowClick(event, "right");
break;
default:
break;
}
}
- window.addEventListener('keyup', handleKeyUp);
+ window.addEventListener("keyup", handleKeyUp);
if (shouldShowCopyOption) {
- window.addEventListener('copy', handleCopyEvent);
+ window.addEventListener("copy", handleCopyEvent);
}
return () => {
- window.removeEventListener('keyup', handleKeyUp);
+ window.removeEventListener("keyup", handleKeyUp);
if (shouldShowCopyOption) {
- window.removeEventListener('copy', handleCopyEvent);
+ window.removeEventListener("copy", handleCopyEvent);
}
};
}, [isOpen, photoSwipe, showInfo]);
@@ -232,10 +232,10 @@ function PhotoViewer(props: Iprops) {
if (item.metadata.fileType === FILE_TYPE.LIVE_PHOTO) {
const getVideoAndImage = () => {
const video = document.getElementById(
- `live-photo-video-${item.id}`
+ `live-photo-video-${item.id}`,
);
const image = document.getElementById(
- `live-photo-image-${item.id}`
+ `live-photo-image-${item.id}`,
);
return { video, image };
};
@@ -266,19 +266,19 @@ function PhotoViewer(props: Iprops) {
}
const downloadLivePhotoBtn = document.getElementById(
- `download-btn-${item.id}`
+ `download-btn-${item.id}`,
) as HTMLButtonElement;
const downloadFile = () => {
downloadFileHelper(photoSwipe.currItem as unknown as EnteFile);
};
if (downloadLivePhotoBtn) {
- downloadLivePhotoBtn.addEventListener('click', downloadFile);
+ downloadLivePhotoBtn.addEventListener("click", downloadFile);
}
return () => {
if (downloadLivePhotoBtn) {
- downloadLivePhotoBtn.removeEventListener('click', downloadFile);
+ downloadLivePhotoBtn.removeEventListener("click", downloadFile);
}
setLivePhotoBtnOptions(defaultLivePhotoDefaultOptions);
};
@@ -347,7 +347,7 @@ function PhotoViewer(props: Iprops) {
const isSupported =
!isRawFile(extension) || isSupportedRawFormat(extension);
setShowEditButton(
- file.metadata.fileType === FILE_TYPE.IMAGE && isSupported
+ file.metadata.fileType === FILE_TYPE.IMAGE && isSupported,
);
}
@@ -396,29 +396,29 @@ function PhotoViewer(props: Iprops) {
pswpElement.current,
PhotoswipeUIDefault,
items,
- options
+ options,
);
photoSwipeV4Events.forEach((event) => {
const callback = props[event];
- if (callback || event === 'destroy') {
+ if (callback || event === "destroy") {
photoSwipe.listen(event, function (...args) {
if (callback) {
args.unshift(photoSwipe);
callback(...args);
}
- if (event === 'destroy') {
+ if (event === "destroy") {
handleClose();
}
- if (event === 'close') {
+ if (event === "close") {
handleClose();
}
});
}
});
- photoSwipe.listen('beforeChange', () => {
+ photoSwipe.listen("beforeChange", () => {
if (!photoSwipe?.currItem) return;
const currItem = photoSwipe.currItem as EnteFile;
- const videoTags = document.getElementsByTagName('video');
+ const videoTags = document.getElementsByTagName("video");
for (const videoTag of videoTags) {
videoTag.pause();
}
@@ -431,7 +431,7 @@ function PhotoViewer(props: Iprops) {
updateShowEditButton(currItem);
updateShowZoomButton(currItem);
});
- photoSwipe.listen('resize', () => {
+ photoSwipe.listen("resize", () => {
if (!photoSwipe?.currItem) return;
const currItem = photoSwipe.currItem as EnteFile;
updateExif(currItem);
@@ -451,10 +451,10 @@ function PhotoViewer(props: Iprops) {
const handleClose = () => {
const { onClose } = props;
- if (typeof onClose === 'function') {
+ if (typeof onClose === "function") {
onClose(needUpdate.current);
}
- const videoTags = document.getElementsByTagName('video');
+ const videoTags = document.getElementsByTagName("video");
for (const videoTag of videoTags) {
videoTag.pause();
}
@@ -490,7 +490,7 @@ function PhotoViewer(props: Iprops) {
}
needUpdate.current = true;
} catch (e) {
- logError(e, 'onFavClick failed');
+ logError(e, "onFavClick failed");
}
};
@@ -505,7 +505,7 @@ function PhotoViewer(props: Iprops) {
updateItems(props.items.filter((item) => item.id !== file.id));
needUpdate.current = true;
} catch (e) {
- logError(e, 'trashFile failed');
+ logError(e, "trashFile failed");
}
};
@@ -518,7 +518,7 @@ function PhotoViewer(props: Iprops) {
const handleArrowClick = (
e: KeyboardEvent,
- direction: 'left' | 'right'
+ direction: "left" | "right",
) => {
// ignore arrow clicks if the user is typing in a text field
if (
@@ -527,7 +527,7 @@ function PhotoViewer(props: Iprops) {
) {
return;
}
- if (direction === 'left') {
+ if (direction === "left") {
photoSwipe.prev();
} else {
photoSwipe.next();
@@ -556,7 +556,7 @@ function PhotoViewer(props: Iprops) {
}
}
} catch (e) {
- logError(e, 'updateItems failed');
+ logError(e, "updateItems failed");
}
};
@@ -567,7 +567,7 @@ function PhotoViewer(props: Iprops) {
photoSwipe.updateSize(true);
}
} catch (e) {
- logError(e, 'refreshPhotoswipe failed');
+ logError(e, "refreshPhotoswipe failed");
}
};
@@ -582,7 +582,7 @@ function PhotoViewer(props: Iprops) {
if (file.metadata.fileType === FILE_TYPE.IMAGE) {
fileObject = await getFileFromURL(
file.src as string,
- file.metadata.title
+ file.metadata.title,
);
} else {
const url = (file.srcURLs.url as LoadedLivePhotoSourceURL)
@@ -592,7 +592,7 @@ function PhotoViewer(props: Iprops) {
const fileTypeInfo = await getFileType(fileObject);
const exifData = await getParsedExifData(
fileObject,
- fileTypeInfo
+ fileTypeInfo,
);
if (exifExtractionInProgress.current === file.src) {
if (exifData) {
@@ -607,7 +607,7 @@ function PhotoViewer(props: Iprops) {
} catch (e) {
setExif({ key: file.src, value: null });
const fileExtension = getFileExtension(file.metadata.title);
- logError(e, 'checkExifAvailable failed', {
+ logError(e, "checkExifAvailable failed", {
extension: fileExtension,
});
}
@@ -637,7 +637,7 @@ function PhotoViewer(props: Iprops) {
try {
const setSingleFileDownloadProgress =
props.setFilesDownloadProgressAttributesCreator(
- file.metadata.title
+ file.metadata.title,
);
await downloadSingleFile(file, setSingleFileDownloadProgress);
} catch (e) {
@@ -681,7 +681,7 @@ function PhotoViewer(props: Iprops) {
x: photoSwipe.viewportSize.x / 2,
y: photoSwipe.viewportSize.y / 2,
},
- 333
+ 333,
);
} else {
photoSwipe.zoomTo(
@@ -690,7 +690,7 @@ function PhotoViewer(props: Iprops) {
x: photoSwipe.viewportSize.x / 2,
y: photoSwipe.viewportSize.y / 2,
},
- 333
+ 333,
);
}
};
@@ -699,23 +699,24 @@ function PhotoViewer(props: Iprops) {
props.getConvertedItem(
photoSwipe,
photoSwipe.getCurrentIndex(),
- photoSwipe.currItem as EnteFile
+ photoSwipe.currItem as EnteFile,
);
};
const scheduleUpdate = () => (needUpdate.current = true);
const { id } = props;
let { className } = props;
- className = classnames(['pswp', className]).trim();
+ className = classnames(["pswp", className]).trim();
return (
<>
<div
id={id}
className={className}
- tabIndex={Number('-1')}
+ tabIndex={Number("-1")}
role="dialog"
aria-hidden="true"
- ref={pswpElement}>
+ ref={pswpElement}
+ >
<div className="pswp__bg" />
<div className="pswp__scroll-wrap">
{livePhotoBtnOptions.visible && (
@@ -725,9 +726,10 @@ function PhotoViewer(props: Iprops) {
onClick={livePhotoBtnOptions.click}
onMouseEnter={livePhotoBtnOptions.show}
onMouseLeave={livePhotoBtnOptions.hide}
- disabled={livePhotoBtnOptions.loading}>
- <FlexWrapper gap={'4px'}>
- {<AlbumOutlined />} {t('LIVE')}
+ disabled={livePhotoBtnOptions.loading}
+ >
+ <FlexWrapper gap={"4px"}>
+ {<AlbumOutlined />} {t("LIVE")}
</FlexWrapper>
</Button>
</LivePhotoBtnContainer>
@@ -744,17 +746,18 @@ function PhotoViewer(props: Iprops) {
<Box
sx={{
- position: 'absolute',
- top: '10vh',
- right: '2vh',
+ position: "absolute",
+ top: "10vh",
+ right: "2vh",
zIndex: 10,
- }}>
+ }}
+ >
{fileDownloadProgress.has(
- (photoSwipe?.currItem as EnteFile)?.id
+ (photoSwipe?.currItem as EnteFile)?.id,
) ? (
<CircularProgressWithLabel
value={fileDownloadProgress.get(
- (photoSwipe.currItem as EnteFile)?.id
+ (photoSwipe.currItem as EnteFile)?.id,
)}
/>
) : (
@@ -773,44 +776,48 @@ function PhotoViewer(props: Iprops) {
<button
className="pswp__button pswp__button--custom"
- title={t('CLOSE_OPTION')}
- onClick={handleClose}>
+ title={t("CLOSE_OPTION")}
+ onClick={handleClose}
+ >
<CloseIcon />
</button>
{props.enableDownload && (
<button
className="pswp__button pswp__button--custom"
- title={t('DOWNLOAD_OPTION')}
+ title={t("DOWNLOAD_OPTION")}
onClick={() =>
downloadFileHelper(
- photoSwipe.currItem as EnteFile
+ photoSwipe.currItem as EnteFile,
)
- }>
+ }
+ >
<DownloadIcon />
</button>
)}
{props.enableDownload && shouldShowCopyOption && (
<button
className="pswp__button pswp__button--custom"
- title={t('COPY_OPTION')}
+ title={t("COPY_OPTION")}
onClick={() =>
copyToClipboardHelper(
- photoSwipe.currItem as EnteFile
+ photoSwipe.currItem as EnteFile,
)
- }>
+ }
+ >
<ContentCopy fontSize="small" />
</button>
)}
{isOwnFile && !props.isTrashCollection && (
<button
className="pswp__button pswp__button--custom"
- title={t('DELETE_OPTION')}
+ title={t("DELETE_OPTION")}
onClick={() => {
confirmTrashFile(
- photoSwipe?.currItem as EnteFile
+ photoSwipe?.currItem as EnteFile,
);
- }}>
+ }}
+ >
<DeleteIcon />
</button>
)}
@@ -818,7 +825,8 @@ function PhotoViewer(props: Iprops) {
<button
className="pswp__button pswp__button--custom"
onClick={toggleZoomInAndOut}
- title={t('ZOOM_IN_OUT')}>
+ title={t("ZOOM_IN_OUT")}
+ >
<ZoomInOutlinedIcon />
</button>
)}
@@ -827,7 +835,8 @@ function PhotoViewer(props: Iprops) {
onClick={() => {
toggleFullscreen(photoSwipe);
}}
- title={t('TOGGLE_FULLSCREEN')}>
+ title={t("TOGGLE_FULLSCREEN")}
+ >
{!isInFullScreenMode ? (
<FullscreenOutlinedIcon
sx={{ fontSize: 32 }}
@@ -841,8 +850,9 @@ function PhotoViewer(props: Iprops) {
<button
className="pswp__button pswp__button--custom"
- title={t('INFO_OPTION')}
- onClick={handleOpenInfo}>
+ title={t("INFO_OPTION")}
+ onClick={handleOpenInfo}
+ >
<InfoIcon />
</button>
{isOwnFile &&
@@ -852,22 +862,24 @@ function PhotoViewer(props: Iprops) {
{showEditButton && (
<button
className="pswp__button pswp__button--custom"
- onClick={handleOpenEditor}>
+ onClick={handleOpenEditor}
+ >
<EditIcon />
</button>
)}
<button
title={
isFav
- ? t('UNFAVORITE_OPTION')
- : t('FAVORITE_OPTION')
+ ? t("UNFAVORITE_OPTION")
+ : t("FAVORITE_OPTION")
}
className="pswp__button pswp__button--custom"
onClick={() => {
onFavClick(
- photoSwipe?.currItem as EnteFile
+ photoSwipe?.currItem as EnteFile,
);
- }}>
+ }}
+ >
{isFav ? (
<FavoriteIcon />
) : (
@@ -878,9 +890,10 @@ function PhotoViewer(props: Iprops) {
)}
{showConvertBtn && (
<button
- title={t('CONVERT')}
+ title={t("CONVERT")}
className="pswp__button pswp__button--custom"
- onClick={triggerManualConvert}>
+ onClick={triggerManualConvert}
+ >
<ReplayIcon fontSize="small" />
</button>
)}
@@ -888,13 +901,15 @@ function PhotoViewer(props: Iprops) {
</div>
<button
className="pswp__button pswp__button--arrow--left"
- title={t('PREVIOUS')}>
- <ChevronLeft sx={{ pointerEvents: 'none' }} />
+ title={t("PREVIOUS")}
+ >
+ <ChevronLeft sx={{ pointerEvents: "none" }} />
</button>
<button
className="pswp__button pswp__button--arrow--right"
- title={t('NEXT')}>
- <ChevronRight sx={{ pointerEvents: 'none' }} />
+ title={t("NEXT")}
+ >
+ <ChevronRight sx={{ pointerEvents: "none" }} />
</button>
<div className="pswp__caption pswp-custom-caption-container">
<CaptionContainer />
diff --git a/apps/photos/src/components/PhotoViewer/styledComponents/CircularProgressWithLabel.tsx b/apps/photos/src/components/PhotoViewer/styledComponents/CircularProgressWithLabel.tsx
index 4dfe0ce9d3..ba43ba95df 100644
--- a/apps/photos/src/components/PhotoViewer/styledComponents/CircularProgressWithLabel.tsx
+++ b/apps/photos/src/components/PhotoViewer/styledComponents/CircularProgressWithLabel.tsx
@@ -1,29 +1,29 @@
+import { Overlay } from "@ente/shared/components/Container";
import {
- CircularProgressProps,
CircularProgress,
+ CircularProgressProps,
Typography,
-} from '@mui/material';
-import { Overlay } from '@ente/shared/components/Container';
+} from "@mui/material";
function CircularProgressWithLabel(
- props: CircularProgressProps & { value: number }
+ props: CircularProgressProps & { value: number },
) {
return (
<>
<CircularProgress variant="determinate" {...props} color="accent" />
<Overlay
sx={{
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- height: '40px',
- }}>
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ height: "40px",
+ }}
+ >
<Typography
variant="mini"
component="div"
- color="text.secondary">{`${Math.round(
- props.value
- )}%`}</Typography>
+ color="text.secondary"
+ >{`${Math.round(props.value)}%`}</Typography>
</Overlay>
</>
);
diff --git a/apps/photos/src/components/PhotoViewer/styledComponents/ConversionFailedNotification.tsx b/apps/photos/src/components/PhotoViewer/styledComponents/ConversionFailedNotification.tsx
index 4eb5f473f6..fe504d1805 100644
--- a/apps/photos/src/components/PhotoViewer/styledComponents/ConversionFailedNotification.tsx
+++ b/apps/photos/src/components/PhotoViewer/styledComponents/ConversionFailedNotification.tsx
@@ -1,6 +1,5 @@
-import Notification from 'components/Notification';
-import React from 'react';
-import { t } from 'i18next';
+import Notification from "components/Notification";
+import { t } from "i18next";
interface Iprops {
open: boolean;
@@ -18,8 +17,8 @@ export const ConversionFailedNotification = ({
open={open}
onClose={onClose}
attributes={{
- variant: 'secondary',
- subtext: t('CONVERSION_FAILED_NOTIFICATION_MESSAGE'),
+ variant: "secondary",
+ subtext: t("CONVERSION_FAILED_NOTIFICATION_MESSAGE"),
onClick: onClick,
}}
horizontal="right"
diff --git a/apps/photos/src/components/PhotoViewer/styledComponents/Legend.tsx b/apps/photos/src/components/PhotoViewer/styledComponents/Legend.tsx
index a9508a9d6a..bb00f56d91 100644
--- a/apps/photos/src/components/PhotoViewer/styledComponents/Legend.tsx
+++ b/apps/photos/src/components/PhotoViewer/styledComponents/Legend.tsx
@@ -1,5 +1,5 @@
-import { styled } from '@mui/material';
-export const Legend = styled('span')`
+import { styled } from "@mui/material";
+export const Legend = styled("span")`
font-size: 20px;
color: #ddd;
display: inline;
diff --git a/apps/photos/src/components/PhotoViewer/styledComponents/LegendContainer.tsx b/apps/photos/src/components/PhotoViewer/styledComponents/LegendContainer.tsx
index d1af121f83..d0610ed745 100644
--- a/apps/photos/src/components/PhotoViewer/styledComponents/LegendContainer.tsx
+++ b/apps/photos/src/components/PhotoViewer/styledComponents/LegendContainer.tsx
@@ -1,5 +1,5 @@
-import { styled } from '@mui/material';
-export const LegendContainer = styled('div')`
+import { styled } from "@mui/material";
+export const LegendContainer = styled("div")`
display: flex;
justify-content: space-between;
`;
diff --git a/apps/photos/src/components/PhotoViewer/styledComponents/LivePhotoBtn.tsx b/apps/photos/src/components/PhotoViewer/styledComponents/LivePhotoBtn.tsx
index c8624ee973..40de098f5e 100644
--- a/apps/photos/src/components/PhotoViewer/styledComponents/LivePhotoBtn.tsx
+++ b/apps/photos/src/components/PhotoViewer/styledComponents/LivePhotoBtn.tsx
@@ -1,5 +1,5 @@
-import { Paper } from '@mui/material';
-import { styled } from '@mui/material/styles';
+import { Paper } from "@mui/material";
+import { styled } from "@mui/material/styles";
export const LivePhotoBtnContainer = styled(Paper)`
border-radius: 4px;
diff --git a/apps/photos/src/components/PhotoViewer/styledComponents/Pre.tsx b/apps/photos/src/components/PhotoViewer/styledComponents/Pre.tsx
index 320192132c..b088ec9f83 100644
--- a/apps/photos/src/components/PhotoViewer/styledComponents/Pre.tsx
+++ b/apps/photos/src/components/PhotoViewer/styledComponents/Pre.tsx
@@ -1,5 +1,5 @@
-import { styled } from '@mui/material';
-export const Pre = styled('pre')`
+import { styled } from "@mui/material";
+export const Pre = styled("pre")`
color: #aaa;
padding: 7px 15px;
`;
diff --git a/apps/photos/src/components/PhotoViewer/styledComponents/SmallLoadingSpinner.tsx b/apps/photos/src/components/PhotoViewer/styledComponents/SmallLoadingSpinner.tsx
index a73b7c0c8b..2314d3974e 100644
--- a/apps/photos/src/components/PhotoViewer/styledComponents/SmallLoadingSpinner.tsx
+++ b/apps/photos/src/components/PhotoViewer/styledComponents/SmallLoadingSpinner.tsx
@@ -1,11 +1,10 @@
-import React from 'react';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
export const SmallLoadingSpinner = () => (
<EnteSpinner
style={{
- width: '20px',
- height: '20px',
+ width: "20px",
+ height: "20px",
}}
/>
);
diff --git a/apps/photos/src/components/PlaceholderThumbnails.tsx b/apps/photos/src/components/PlaceholderThumbnails.tsx
index 5e002bfa14..caafbdce6f 100644
--- a/apps/photos/src/components/PlaceholderThumbnails.tsx
+++ b/apps/photos/src/components/PlaceholderThumbnails.tsx
@@ -1,8 +1,8 @@
-import PhotoOutlined from '@mui/icons-material/PhotoOutlined';
-import PlayCircleOutlineOutlined from '@mui/icons-material/PlayCircleOutlineOutlined';
-import { styled } from '@mui/material';
-import { FILE_TYPE } from 'constants/file';
-import { Overlay } from '@ente/shared/components/Container';
+import { Overlay } from "@ente/shared/components/Container";
+import PhotoOutlined from "@mui/icons-material/PhotoOutlined";
+import PlayCircleOutlineOutlined from "@mui/icons-material/PlayCircleOutlineOutlined";
+import { styled } from "@mui/material";
+import { FILE_TYPE } from "constants/file";
interface Iprops {
fileType: FILE_TYPE;
@@ -19,15 +19,16 @@ export const StaticThumbnail = (props: Iprops) => {
<CenteredOverlay
sx={(theme) => ({
backgroundColor: theme.colors.fill.faint,
- borderWidth: '1px',
- borderStyle: 'solid',
+ borderWidth: "1px",
+ borderStyle: "solid",
borderColor: theme.colors.stroke.faint,
- borderRadius: '4px',
- '& > svg': {
+ borderRadius: "4px",
+ "& > svg": {
color: theme.colors.stroke.muted,
- fontSize: '50px',
+ fontSize: "50px",
},
- })}>
+ })}
+ >
{props.fileType !== FILE_TYPE.VIDEO ? (
<PhotoOutlined />
) : (
@@ -42,7 +43,7 @@ export const LoadingThumbnail = () => {
<Overlay
sx={(theme) => ({
backgroundColor: theme.colors.fill.faint,
- borderRadius: '4px',
+ borderRadius: "4px",
})}
/>
);
diff --git a/apps/photos/src/components/Search/SearchBar/index.tsx b/apps/photos/src/components/Search/SearchBar/index.tsx
index 2194fb572f..5ba0462107 100644
--- a/apps/photos/src/components/Search/SearchBar/index.tsx
+++ b/apps/photos/src/components/Search/SearchBar/index.tsx
@@ -1,11 +1,10 @@
-import { SearchBarMobile } from './searchBarMobile';
-import React from 'react';
-import { Collection } from 'types/collection';
+import { Collection } from "types/collection";
+import { SearchBarMobile } from "./searchBarMobile";
-import { EnteFile } from 'types/file';
-import { SearchBarWrapper } from './styledComponents';
-import SearchInput from './searchInput';
-import { UpdateSearch } from 'types/search';
+import { EnteFile } from "types/file";
+import { UpdateSearch } from "types/search";
+import SearchInput from "./searchInput";
+import { SearchBarWrapper } from "./styledComponents";
interface Props {
updateSearch: UpdateSearch;
diff --git a/apps/photos/src/components/Search/SearchBar/searchBarMobile.tsx b/apps/photos/src/components/Search/SearchBar/searchBarMobile.tsx
index 0b44772005..466a5ef79e 100644
--- a/apps/photos/src/components/Search/SearchBar/searchBarMobile.tsx
+++ b/apps/photos/src/components/Search/SearchBar/searchBarMobile.tsx
@@ -1,8 +1,7 @@
-import { IconButton } from '@mui/material';
-import { FluidContainer } from '@ente/shared/components/Container';
-import React from 'react';
-import { SearchMobileBox } from './styledComponents';
-import SearchIcon from '@mui/icons-material/Search';
+import { FluidContainer } from "@ente/shared/components/Container";
+import SearchIcon from "@mui/icons-material/Search";
+import { IconButton } from "@mui/material";
+import { SearchMobileBox } from "./styledComponents";
export function SearchBarMobile({ show, showSearchInput }) {
if (!show) {
diff --git a/apps/photos/src/components/Search/SearchBar/searchInput/MenuWithPeople.tsx b/apps/photos/src/components/Search/SearchBar/searchInput/MenuWithPeople.tsx
index 4ff108b83f..1151e202f7 100644
--- a/apps/photos/src/components/Search/SearchBar/searchInput/MenuWithPeople.tsx
+++ b/apps/photos/src/components/Search/SearchBar/searchInput/MenuWithPeople.tsx
@@ -1,24 +1,24 @@
-import { useContext } from 'react';
-import { PeopleList } from 'components/MachineLearning/PeopleList';
-import { IndexStatus } from 'types/machineLearning/ui';
-import { SuggestionType, Suggestion } from 'types/search';
-import { components } from 'react-select';
-import { Row } from '@ente/shared/components/Container';
-import { AppContext } from 'pages/_app';
-import styled from '@mui/styled-engine';
-import { t } from 'i18next';
-import { Box } from '@mui/material';
+import { Row } from "@ente/shared/components/Container";
+import { Box } from "@mui/material";
+import styled from "@mui/styled-engine";
+import { PeopleList } from "components/MachineLearning/PeopleList";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
+import { components } from "react-select";
+import { IndexStatus } from "types/machineLearning/ui";
+import { Suggestion, SuggestionType } from "types/search";
const { Menu } = components;
-const Legend = styled('span')`
+const Legend = styled("span")`
font-size: 20px;
color: #ddd;
display: inline;
padding: 0px 12px;
`;
-const Caption = styled('span')`
+const Caption = styled("span")`
font-size: 12px;
display: inline;
padding: 0px 12px;
@@ -28,12 +28,12 @@ const MenuWithPeople = (props) => {
const appContext = useContext(AppContext);
// addLogLine("props.selectProps.options: ", selectRef);
const peopleSuggestions = props.selectProps.options.filter(
- (o) => o.type === SuggestionType.PERSON
+ (o) => o.type === SuggestionType.PERSON,
);
const people = peopleSuggestions.map((o) => o.value);
const indexStatusSuggestion = props.selectProps.options.filter(
- (o) => o.type === SuggestionType.INDEX_STATUS
+ (o) => o.type === SuggestionType.INDEX_STATUS,
)[0] as Suggestion;
const indexStatus = indexStatusSuggestion?.value as IndexStatus;
@@ -43,7 +43,7 @@ const MenuWithPeople = (props) => {
{((appContext.mlSearchEnabled && indexStatus) ||
(people && people.length > 0)) && (
<Box>
- <Legend>{t('PEOPLE')}</Legend>
+ <Legend>{t("PEOPLE")}</Legend>
</Box>
)}
{appContext.mlSearchEnabled && indexStatus && (
diff --git a/apps/photos/src/components/Search/SearchBar/searchInput/index.tsx b/apps/photos/src/components/Search/SearchBar/searchInput/index.tsx
index c8e9bb2899..90239ea28f 100644
--- a/apps/photos/src/components/Search/SearchBar/searchInput/index.tsx
+++ b/apps/photos/src/components/Search/SearchBar/searchInput/index.tsx
@@ -1,36 +1,36 @@
-import { IconButton } from '@mui/material';
-import pDebounce from 'p-debounce';
-import { AppContext } from 'pages/_app';
-import { useCallback, useContext, useEffect, useRef, useState } from 'react';
+import CloseIcon from "@mui/icons-material/Close";
+import { IconButton } from "@mui/material";
+import { FILE_TYPE } from "constants/file";
+import { t } from "i18next";
+import memoize from "memoize-one";
+import pDebounce from "p-debounce";
+import { AppContext } from "pages/_app";
+import { useCallback, useContext, useEffect, useRef, useState } from "react";
+import { components } from "react-select";
+import AsyncSelect from "react-select/async";
+import { InputActionMeta } from "react-select/src/types";
+import { City } from "services/locationSearchService";
import {
getAutoCompleteSuggestions,
getDefaultOptions,
-} from 'services/searchService';
+} from "services/searchService";
+import { Collection } from "types/collection";
+import { LocationTagData } from "types/entity";
+import { EnteFile } from "types/file";
+import { Person, Thing, WordGroup } from "types/machineLearning";
import {
ClipSearchScores,
DateValue,
Search,
SearchOption,
SuggestionType,
-} from 'types/search';
-import { ValueContainerWithIcon } from './valueContainerWithIcon';
-import { SelectStyles } from '../../../../styles/search';
-import AsyncSelect from 'react-select/async';
-import CloseIcon from '@mui/icons-material/Close';
-import { UpdateSearch } from 'types/search';
-import { EnteFile } from 'types/file';
-import { Collection } from 'types/collection';
-import { OptionWithInfo } from './optionWithInfo';
-import { SearchInputWrapper } from '../styledComponents';
-import MenuWithPeople from './MenuWithPeople';
-import { Person, Thing, WordGroup } from 'types/machineLearning';
-import { t } from 'i18next';
-import memoize from 'memoize-one';
-import { LocationTagData } from 'types/entity';
-import { FILE_TYPE } from 'constants/file';
-import { InputActionMeta } from 'react-select/src/types';
-import { components } from 'react-select';
-import { City } from 'services/locationSearchService';
+ UpdateSearch,
+} from "types/search";
+import { SelectStyles } from "../../../../styles/search";
+import { SearchInputWrapper } from "../styledComponents";
+import MenuWithPeople from "./MenuWithPeople";
+import { OptionWithInfo } from "./optionWithInfo";
+import { ValueContainerWithIcon } from "./valueContainerWithIcon";
interface Iprops {
isOpen: boolean;
@@ -61,12 +61,12 @@ export default function SearchInput(props: Iprops) {
blur();
};
const handleInputChange = (value: string, actionMeta: InputActionMeta) => {
- if (actionMeta.action === 'input-change') {
+ if (actionMeta.action === "input-change") {
setQuery(value);
}
};
const [defaultOptions, setDefaultOptions] = useState([]);
- const [query, setQuery] = useState('');
+ const [query, setQuery] = useState("");
useEffect(() => {
search(value);
@@ -92,16 +92,16 @@ export default function SearchInput(props: Iprops) {
}, 10);
props.setIsOpen(false);
setValue(null);
- setQuery('');
+ setQuery("");
}
};
const getOptions = useCallback(
pDebounce(
getAutoCompleteSuggestions(props.files, props.collections),
- 250
+ 250,
),
- [props.files, props.collections]
+ [props.files, props.collections],
);
const blur = () => {
@@ -135,7 +135,7 @@ export default function SearchInput(props: Iprops) {
case SuggestionType.COLLECTION:
search = { collection: selectedOption.value as number };
setValue(null);
- setQuery('');
+ setQuery("");
break;
case SuggestionType.FILE_NAME:
search = { files: selectedOption.value as number[] };
@@ -180,14 +180,14 @@ export default function SearchInput(props: Iprops) {
selectRef={selectRef}
/>
),
- [setValue, selectRef]
+ [setValue, selectRef],
);
const components = createComponents(
OptionWithInfo,
ValueContainerWithIcon,
MemoizedMenuWithPeople,
- VisibleInput
+ VisibleInput,
);
return (
@@ -196,7 +196,7 @@ export default function SearchInput(props: Iprops) {
ref={selectRef}
value={value}
components={components}
- placeholder={<span>{t('SEARCH_HINT')}</span>}
+ placeholder={<span>{t("SEARCH_HINT")}</span>}
loadOptions={getOptions}
onChange={handleChange}
onFocus={handleOnFocus}
diff --git a/apps/photos/src/components/Search/SearchBar/searchInput/optionWithInfo.tsx b/apps/photos/src/components/Search/SearchBar/searchInput/optionWithInfo.tsx
index 55d02c432f..8e3fd7d842 100644
--- a/apps/photos/src/components/Search/SearchBar/searchInput/optionWithInfo.tsx
+++ b/apps/photos/src/components/Search/SearchBar/searchInput/optionWithInfo.tsx
@@ -1,15 +1,14 @@
-import React from 'react';
-import { SearchOption } from 'types/search';
-import { Box, Divider, Stack, Typography } from '@mui/material';
import {
FreeFlowText,
SpaceBetweenFlex,
-} from '@ente/shared/components/Container';
-import CollectionCard from 'components/Collections/CollectionCard';
-import { ResultPreviewTile } from 'components/Collections/styledComponents';
-import { t } from 'i18next';
+} from "@ente/shared/components/Container";
+import { Box, Divider, Stack, Typography } from "@mui/material";
+import CollectionCard from "components/Collections/CollectionCard";
+import { ResultPreviewTile } from "components/Collections/styledComponents";
+import { t } from "i18next";
+import { SearchOption } from "types/search";
-import { components } from 'react-select';
+import { components } from "react-select";
const { Option } = components;
@@ -30,16 +29,16 @@ const LabelWithInfo = ({ data }: { data: SearchOption }) => {
<SpaceBetweenFlex>
<Box mr={1}>
<FreeFlowText>
- <Typography fontWeight={'bold'}>
+ <Typography fontWeight={"bold"}>
{data.label}
</Typography>
</FreeFlowText>
<Typography color="text.muted">
- {t('photos_count', { count: data.fileCount })}
+ {t("photos_count", { count: data.fileCount })}
</Typography>
</Box>
- <Stack direction={'row'} spacing={1}>
+ <Stack direction={"row"} spacing={1}>
{data.previewFiles.map((file) => (
<CollectionCard
key={file.id}
diff --git a/apps/photos/src/components/Search/SearchBar/searchInput/valueContainerWithIcon.tsx b/apps/photos/src/components/Search/SearchBar/searchInput/valueContainerWithIcon.tsx
index 9ebe3cd580..359885c45f 100644
--- a/apps/photos/src/components/Search/SearchBar/searchInput/valueContainerWithIcon.tsx
+++ b/apps/photos/src/components/Search/SearchBar/searchInput/valueContainerWithIcon.tsx
@@ -1,14 +1,13 @@
-import React from 'react';
-import FolderIcon from '@mui/icons-material/Folder';
-import CalendarIcon from '@mui/icons-material/CalendarMonth';
-import ImageIcon from '@mui/icons-material/Image';
-import LocationIcon from '@mui/icons-material/LocationOn';
-import { components } from 'react-select';
-import { SearchOption, SuggestionType } from 'types/search';
-import SearchIcon from '@mui/icons-material/SearchOutlined';
-import { SelectComponents } from 'react-select/src/components';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import { Box } from '@mui/material';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import CalendarIcon from "@mui/icons-material/CalendarMonth";
+import FolderIcon from "@mui/icons-material/Folder";
+import ImageIcon from "@mui/icons-material/Image";
+import LocationIcon from "@mui/icons-material/LocationOn";
+import SearchIcon from "@mui/icons-material/SearchOutlined";
+import { Box } from "@mui/material";
+import { components } from "react-select";
+import { SelectComponents } from "react-select/src/components";
+import { SearchOption, SuggestionType } from "types/search";
const { ValueContainer } = components;
@@ -31,7 +30,7 @@ const getIconByType = (type: SuggestionType) => {
export const ValueContainerWithIcon: SelectComponents<
SearchOption,
false
->['ValueContainer'] = (props) => (
+>["ValueContainer"] = (props) => (
<ValueContainer {...props}>
<FlexWrapper>
<Box className="icon" mr={1.5} color="stroke.muted">
diff --git a/apps/photos/src/components/Search/SearchBar/styledComponents.tsx b/apps/photos/src/components/Search/SearchBar/styledComponents.tsx
index df1f93d2cc..41d4a0971e 100644
--- a/apps/photos/src/components/Search/SearchBar/styledComponents.tsx
+++ b/apps/photos/src/components/Search/SearchBar/styledComponents.tsx
@@ -2,9 +2,9 @@ import {
CenteredFlex,
FlexWrapper,
FluidContainer,
-} from '@ente/shared/components/Container';
-import { css, styled } from '@mui/material';
-import { IMAGE_CONTAINER_MAX_WIDTH, MIN_COLUMNS } from 'constants/gallery';
+} from "@ente/shared/components/Container";
+import { css, styled } from "@mui/material";
+import { IMAGE_CONTAINER_MAX_WIDTH, MIN_COLUMNS } from "constants/gallery";
export const SearchBarWrapper = styled(FlexWrapper)`
padding: 0 24px;
diff --git a/apps/photos/src/components/Search/SearchResultInfo.tsx b/apps/photos/src/components/Search/SearchResultInfo.tsx
index 68cd422af3..7d99697bf1 100644
--- a/apps/photos/src/components/Search/SearchResultInfo.tsx
+++ b/apps/photos/src/components/Search/SearchResultInfo.tsx
@@ -1,9 +1,8 @@
-import React from 'react';
-import { CollectionInfo } from 'components/Collections/CollectionInfo';
-import { Typography } from '@mui/material';
-import { SearchResultSummary } from 'types/search';
-import { CollectionInfoBarWrapper } from 'components/Collections/styledComponents';
-import { t } from 'i18next';
+import { Typography } from "@mui/material";
+import { CollectionInfo } from "components/Collections/CollectionInfo";
+import { CollectionInfoBarWrapper } from "components/Collections/styledComponents";
+import { t } from "i18next";
+import { SearchResultSummary } from "types/search";
interface Iprops {
searchResultSummary: SearchResultSummary;
@@ -18,7 +17,7 @@ export default function SearchResultInfo({ searchResultSummary }: Iprops) {
return (
<CollectionInfoBarWrapper>
<Typography color="text.muted" variant="large">
- {t('SEARCH_RESULTS')}
+ {t("SEARCH_RESULTS")}
</Typography>
<CollectionInfo name={optionName} fileCount={fileCount} />
</CollectionInfoBarWrapper>
diff --git a/apps/photos/src/components/Search/SearchStatsContainer.tsx b/apps/photos/src/components/Search/SearchStatsContainer.tsx
index 131191cc26..1e088b58f0 100644
--- a/apps/photos/src/components/Search/SearchStatsContainer.tsx
+++ b/apps/photos/src/components/Search/SearchStatsContainer.tsx
@@ -1,12 +1,12 @@
-import { styled } from '@mui/material';
-const SearchStatsContainer = styled('div')(
+import { styled } from "@mui/material";
+const SearchStatsContainer = styled("div")(
({ theme }) => `
display: flex;
justify-content: center;
align-items: center;
color: #979797;
margin: ${theme.spacing(1, 0)};
-`
+`,
);
export default SearchStatsContainer;
diff --git a/apps/photos/src/components/Sidebar/AdvancedSettings.tsx b/apps/photos/src/components/Sidebar/AdvancedSettings.tsx
index cf5a7f27dc..5adc0361d3 100644
--- a/apps/photos/src/components/Sidebar/AdvancedSettings.tsx
+++ b/apps/photos/src/components/Sidebar/AdvancedSettings.tsx
@@ -1,23 +1,22 @@
-import ChevronRight from '@mui/icons-material/ChevronRight';
-import ScienceIcon from '@mui/icons-material/Science';
-import { Box, DialogProps, Stack, Typography } from '@mui/material';
-import { EnteDrawer } from 'components/EnteDrawer';
-import MLSearchSettings from 'components/MachineLearning/MLSearchSettings';
-import MenuSectionTitle from 'components/Menu/MenuSectionTitle';
-import Titlebar from 'components/Titlebar';
-import { useContext, useEffect, useState } from 'react';
-import { t } from 'i18next';
+import ChevronRight from "@mui/icons-material/ChevronRight";
+import ScienceIcon from "@mui/icons-material/Science";
+import { Box, DialogProps, Stack, Typography } from "@mui/material";
+import { EnteDrawer } from "components/EnteDrawer";
+import MLSearchSettings from "components/MachineLearning/MLSearchSettings";
+import MenuSectionTitle from "components/Menu/MenuSectionTitle";
+import Titlebar from "components/Titlebar";
+import { t } from "i18next";
+import { useContext, useEffect, useState } from "react";
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import isElectron from 'is-electron';
-import { logError } from '@ente/shared/sentry';
-import { AppContext } from 'pages/_app';
-import { ClipService } from 'services/clipService';
-import { VerticallyCenteredFlex } from '@ente/shared/components/Container';
-import { ClipExtractionStatus } from 'services/clipService';
-import { formatNumber } from 'utils/number/format';
-import CacheDirectory from './Preferences/CacheDirectory';
+import { VerticallyCenteredFlex } from "@ente/shared/components/Container";
+import { logError } from "@ente/shared/sentry";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import isElectron from "is-electron";
+import { AppContext } from "pages/_app";
+import { ClipExtractionStatus, ClipService } from "services/clipService";
+import { formatNumber } from "utils/number/format";
+import CacheDirectory from "./Preferences/CacheDirectory";
export default function AdvancedSettings({ open, onClose, onRootClose }) {
const appContext = useContext(AppContext);
@@ -31,8 +30,8 @@ export default function AdvancedSettings({ open, onClose, onRootClose }) {
onRootClose();
};
- const handleDrawerClose: DialogProps['onClose'] = (_, reason) => {
- if (reason === 'backdropClick') {
+ const handleDrawerClose: DialogProps["onClose"] = (_, reason) => {
+ if (reason === "backdropClick") {
handleRootClose();
} else {
onClose();
@@ -43,7 +42,7 @@ export default function AdvancedSettings({ open, onClose, onRootClose }) {
try {
appContext.setIsCFProxyDisabled(!appContext.isCFProxyDisabled);
} catch (e) {
- logError(e, 'toggleFasterUpload failed');
+ logError(e, "toggleFasterUpload failed");
}
};
const [indexingStatus, setIndexingStatus] = useState<ClipExtractionStatus>({
@@ -65,30 +64,31 @@ export default function AdvancedSettings({ open, onClose, onRootClose }) {
open={open}
onClose={handleDrawerClose}
BackdropProps={{
- sx: { '&&&': { backgroundColor: 'transparent' } },
- }}>
- <Stack spacing={'4px'} py={'12px'}>
+ sx: { "&&&": { backgroundColor: "transparent" } },
+ }}
+ >
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={onClose}
- title={t('ADVANCED')}
+ title={t("ADVANCED")}
onRootClose={handleRootClose}
/>
- <Box px={'8px'}>
+ <Box px={"8px"}>
<Stack py="20px" spacing="24px">
{isElectron() && (
<>
<CacheDirectory />
<Box>
<MenuSectionTitle
- title={t('LABS')}
+ title={t("LABS")}
icon={<ScienceIcon />}
/>
<MenuItemGroup>
<EnteMenuItem
endIcon={<ChevronRight />}
onClick={openMlSearchSettings}
- label={t('ML_SEARCH')}
+ label={t("ML_SEARCH")}
/>
</MenuItemGroup>
</Box>
@@ -100,41 +100,43 @@ export default function AdvancedSettings({ open, onClose, onRootClose }) {
variant="toggle"
checked={!appContext.isCFProxyDisabled}
onClick={toggleCFProxy}
- label={t('FASTER_UPLOAD')}
+ label={t("FASTER_UPLOAD")}
/>
</MenuItemGroup>
<MenuSectionTitle
- title={t('FASTER_UPLOAD_DESCRIPTION')}
+ title={t("FASTER_UPLOAD_DESCRIPTION")}
/>
</Box>
{isElectron() && (
<Box>
<MenuSectionTitle
- title={t('MAGIC_SEARCH_STATUS')}
+ title={t("MAGIC_SEARCH_STATUS")}
/>
- <Stack py={'12px'} px={'12px'} spacing={'24px'}>
+ <Stack py={"12px"} px={"12px"} spacing={"24px"}>
<VerticallyCenteredFlex
justifyContent="space-between"
- alignItems={'center'}>
+ alignItems={"center"}
+ >
<Typography>
- {t('INDEXED_ITEMS')}
+ {t("INDEXED_ITEMS")}
</Typography>
<Typography>
{formatNumber(
- indexingStatus.indexed
+ indexingStatus.indexed,
)}
</Typography>
</VerticallyCenteredFlex>
<VerticallyCenteredFlex
justifyContent="space-between"
- alignItems={'center'}>
+ alignItems={"center"}
+ >
<Typography>
- {t('PENDING_ITEMS')}
+ {t("PENDING_ITEMS")}
</Typography>
<Typography>
{formatNumber(
- indexingStatus.pending
+ indexingStatus.pending,
)}
</Typography>
</VerticallyCenteredFlex>
diff --git a/apps/photos/src/components/Sidebar/DebugSection.tsx b/apps/photos/src/components/Sidebar/DebugSection.tsx
index c903ef869b..62c038eac6 100644
--- a/apps/photos/src/components/Sidebar/DebugSection.tsx
+++ b/apps/photos/src/components/Sidebar/DebugSection.tsx
@@ -1,21 +1,21 @@
-import { AppContext } from 'pages/_app';
-import React, { useContext, useEffect, useState } from 'react';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext, useEffect, useState } from "react";
+import { Trans } from "react-i18next";
-import { addLogLine } from '@ente/shared/logging';
-import { getDebugLogs } from '@ente/shared/logging/web';
-import isElectron from 'is-electron';
-import ElectronAPIs from '@ente/shared/electron';
-import Typography from '@mui/material/Typography';
-import { isInternalUser } from 'utils/user';
-import { testUpload } from '../../../tests/upload.test';
+import ElectronAPIs from "@ente/shared/electron";
+import { addLogLine } from "@ente/shared/logging";
+import { getDebugLogs } from "@ente/shared/logging/web";
+import { downloadAsFile } from "@ente/shared/utils";
+import Typography from "@mui/material/Typography";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import isElectron from "is-electron";
+import { isInternalUser } from "utils/user";
+import { testUpload } from "../../../tests/upload.test";
import {
testZipFileReading,
testZipWithRootFileReadingTest,
-} from '../../../tests/zip-file-reading.test';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import { downloadAsFile } from '@ente/shared/utils';
+} from "../../../tests/zip-file-reading.test";
export default function DebugSection() {
const appContext = useContext(AppContext);
@@ -33,20 +33,20 @@ export default function DebugSection() {
const confirmLogDownload = () =>
appContext.setDialogMessage({
- title: t('DOWNLOAD_LOGS'),
- content: <Trans i18nKey={'DOWNLOAD_LOGS_MESSAGE'} />,
+ title: t("DOWNLOAD_LOGS"),
+ content: <Trans i18nKey={"DOWNLOAD_LOGS_MESSAGE"} />,
proceed: {
- text: t('DOWNLOAD'),
- variant: 'accent',
+ text: t("DOWNLOAD"),
+ variant: "accent",
action: downloadDebugLogs,
},
close: {
- text: t('CANCEL'),
+ text: t("CANCEL"),
},
});
const downloadDebugLogs = () => {
- addLogLine('exporting logs');
+ addLogLine("exporting logs");
if (isElectron()) {
ElectronAPIs.openLogDirectory();
} else {
@@ -61,14 +61,15 @@ export default function DebugSection() {
<EnteMenuItem
onClick={confirmLogDownload}
variant="mini"
- label={t('DOWNLOAD_UPLOAD_LOGS')}
+ label={t("DOWNLOAD_UPLOAD_LOGS")}
/>
{appVersion && (
<Typography
- py={'14px'}
- px={'16px'}
+ py={"14px"}
+ px={"16px"}
color="text.muted"
- variant="mini">
+ variant="mini"
+ >
{appVersion}
</Typography>
)}
@@ -77,7 +78,7 @@ export default function DebugSection() {
<EnteMenuItem
variant="secondary"
onClick={testUpload}
- label={'Test Upload'}
+ label={"Test Upload"}
/>
<EnteMenuItem
diff --git a/apps/photos/src/components/Sidebar/DisableMap.tsx b/apps/photos/src/components/Sidebar/DisableMap.tsx
index b839c80620..ef793166e7 100644
--- a/apps/photos/src/components/Sidebar/DisableMap.tsx
+++ b/apps/photos/src/components/Sidebar/DisableMap.tsx
@@ -1,31 +1,32 @@
-import { Stack, Box, Button, Typography } from '@mui/material';
-import Titlebar from 'components/Titlebar';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
+import { Box, Button, Stack, Typography } from "@mui/material";
+import Titlebar from "components/Titlebar";
+import { t } from "i18next";
+import { Trans } from "react-i18next";
export default function EnableMap({ onClose, disableMap, onRootClose }) {
return (
- <Stack spacing={'4px'} py={'12px'}>
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={onClose}
- title={t('DISABLE_MAPS')}
+ title={t("DISABLE_MAPS")}
onRootClose={onRootClose}
/>
- <Stack py={'20px'} px={'8px'} spacing={'32px'}>
- <Box px={'8px'}>
+ <Stack py={"20px"} px={"8px"} spacing={"32px"}>
+ <Box px={"8px"}>
<Typography color="text.muted">
- <Trans i18nKey={'DISABLE_MAP_DESCRIPTION'} />
+ <Trans i18nKey={"DISABLE_MAP_DESCRIPTION"} />
</Typography>
</Box>
- <Stack px={'8px'} spacing={'8px'}>
+ <Stack px={"8px"} spacing={"8px"}>
<Button
- color={'critical'}
+ color={"critical"}
size="large"
- onClick={disableMap}>
- {t('DISABLE')}
+ onClick={disableMap}
+ >
+ {t("DISABLE")}
</Button>
- <Button color={'secondary'} size="large" onClick={onClose}>
- {t('CANCEL')}
+ <Button color={"secondary"} size="large" onClick={onClose}>
+ {t("CANCEL")}
</Button>
</Stack>
</Stack>
diff --git a/apps/photos/src/components/Sidebar/EnableMap.tsx b/apps/photos/src/components/Sidebar/EnableMap.tsx
index 73484f2977..868485af0e 100644
--- a/apps/photos/src/components/Sidebar/EnableMap.tsx
+++ b/apps/photos/src/components/Sidebar/EnableMap.tsx
@@ -1,23 +1,23 @@
-import { Stack, Box, Button, Typography, Link } from '@mui/material';
-import Titlebar from 'components/Titlebar';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
+import { Box, Button, Link, Stack, Typography } from "@mui/material";
+import Titlebar from "components/Titlebar";
+import { t } from "i18next";
+import { Trans } from "react-i18next";
-export const OPEN_STREET_MAP_LINK = 'https://www.openstreetmap.org/';
+export const OPEN_STREET_MAP_LINK = "https://www.openstreetmap.org/";
export default function EnableMap({ onClose, enableMap, onRootClose }) {
return (
- <Stack spacing={'4px'} py={'12px'}>
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={onClose}
- title={t('ENABLE_MAPS')}
+ title={t("ENABLE_MAPS")}
onRootClose={onRootClose}
/>
- <Stack py={'20px'} px={'8px'} spacing={'32px'}>
- <Box px={'8px'}>
- {' '}
+ <Stack py={"20px"} px={"8px"} spacing={"32px"}>
+ <Box px={"8px"}>
+ {" "}
<Typography color="text.muted">
<Trans
- i18nKey={'ENABLE_MAP_DESCRIPTION'}
+ i18nKey={"ENABLE_MAP_DESCRIPTION"}
components={{
a: (
<Link
@@ -29,12 +29,12 @@ export default function EnableMap({ onClose, enableMap, onRootClose }) {
/>
</Typography>
</Box>
- <Stack px={'8px'} spacing={'8px'}>
- <Button color={'accent'} size="large" onClick={enableMap}>
- {t('ENABLE')}
+ <Stack px={"8px"} spacing={"8px"}>
+ <Button color={"accent"} size="large" onClick={enableMap}>
+ {t("ENABLE")}
</Button>
- <Button color={'secondary'} size="large" onClick={onClose}>
- {t('CANCEL')}
+ <Button color={"secondary"} size="large" onClick={onClose}>
+ {t("CANCEL")}
</Button>
</Stack>
</Stack>
diff --git a/apps/photos/src/components/Sidebar/ExitSection.tsx b/apps/photos/src/components/Sidebar/ExitSection.tsx
index b5c24a0467..6f9492b779 100644
--- a/apps/photos/src/components/Sidebar/ExitSection.tsx
+++ b/apps/photos/src/components/Sidebar/ExitSection.tsx
@@ -1,10 +1,10 @@
-import React, { useContext, useState } from 'react';
-import { t } from 'i18next';
+import { t } from "i18next";
+import { useContext, useState } from "react";
-import { logoutUser } from '@ente/accounts/services/user';
-import { AppContext } from 'pages/_app';
-import DeleteAccountModal from 'components/DeleteAccountModal';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
+import { logoutUser } from "@ente/accounts/services/user";
+import DeleteAccountModal from "components/DeleteAccountModal";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import { AppContext } from "pages/_app";
export default function ExitSection() {
const { setDialogMessage } = useContext(AppContext);
@@ -16,13 +16,13 @@ export default function ExitSection() {
const confirmLogout = () => {
setDialogMessage({
- title: t('LOGOUT_MESSAGE'),
+ title: t("LOGOUT_MESSAGE"),
proceed: {
- text: t('LOGOUT'),
+ text: t("LOGOUT"),
action: logoutUser,
- variant: 'critical',
+ variant: "critical",
},
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
});
};
@@ -31,14 +31,14 @@ export default function ExitSection() {
<EnteMenuItem
onClick={confirmLogout}
color="critical"
- label={t('LOGOUT')}
+ label={t("LOGOUT")}
variant="secondary"
/>
<EnteMenuItem
onClick={openDeleteAccountModal}
color="critical"
variant="secondary"
- label={t('DELETE_ACCOUNT')}
+ label={t("DELETE_ACCOUNT")}
/>
<DeleteAccountModal
open={deleteAccountModalView}
diff --git a/apps/photos/src/components/Sidebar/Header.tsx b/apps/photos/src/components/Sidebar/Header.tsx
index 40e6f0e700..4adb12fe7c 100644
--- a/apps/photos/src/components/Sidebar/Header.tsx
+++ b/apps/photos/src/components/Sidebar/Header.tsx
@@ -1,8 +1,7 @@
-import { IconButton } from '@mui/material';
-import React from 'react';
-import CloseIcon from '@mui/icons-material/Close';
-import { SpaceBetweenFlex } from '@ente/shared/components/Container';
-import { EnteLogo } from '@ente/shared/components/EnteLogo';
+import { SpaceBetweenFlex } from "@ente/shared/components/Container";
+import { EnteLogo } from "@ente/shared/components/EnteLogo";
+import CloseIcon from "@mui/icons-material/Close";
+import { IconButton } from "@mui/material";
interface IProps {
closeSidebar: () => void;
@@ -15,7 +14,8 @@ export default function HeaderSection({ closeSidebar }: IProps) {
<IconButton
aria-label="close"
onClick={closeSidebar}
- color="secondary">
+ color="secondary"
+ >
<CloseIcon fontSize="small" />
</IconButton>
</SpaceBetweenFlex>
diff --git a/apps/photos/src/components/Sidebar/HelpSection.tsx b/apps/photos/src/components/Sidebar/HelpSection.tsx
index 9fa47c0039..5424ea5654 100644
--- a/apps/photos/src/components/Sidebar/HelpSection.tsx
+++ b/apps/photos/src/components/Sidebar/HelpSection.tsx
@@ -1,20 +1,20 @@
-import { useContext } from 'react';
-import { t } from 'i18next';
+import { t } from "i18next";
+import { useContext } from "react";
-import exportService from 'services/export';
-import isElectron from 'is-electron';
-import { AppContext } from 'pages/_app';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { getDownloadAppMessage } from 'utils/ui';
-import { NoStyleAnchor } from 'components/pages/sharedAlbum/GoToEnte';
-import { openLink } from 'utils/common';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import { Typography } from '@mui/material';
-import { GalleryContext } from 'pages/gallery';
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
import {
DESKTOP_ROADMAP_URL,
WEB_ROADMAP_URL,
-} from '@ente/shared/constants/urls';
+} from "@ente/shared/constants/urls";
+import { Typography } from "@mui/material";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import { NoStyleAnchor } from "components/pages/sharedAlbum/GoToEnte";
+import isElectron from "is-electron";
+import { AppContext } from "pages/_app";
+import { GalleryContext } from "pages/gallery";
+import exportService from "services/export";
+import { openLink } from "utils/common";
+import { getDownloadAppMessage } from "utils/ui";
export default function HelpSection() {
const { setDialogMessage } = useContext(AppContext);
@@ -42,15 +42,15 @@ export default function HelpSection() {
<>
<EnteMenuItem
onClick={openRoadmap}
- label={t('REQUEST_FEATURE')}
+ label={t("REQUEST_FEATURE")}
variant="secondary"
/>
<EnteMenuItem
- onClick={() => openLink('mailto:[email protected]', true)}
+ onClick={() => openLink("mailto:[email protected]", true)}
labelComponent={
<NoStyleAnchor href="mailto:[email protected]">
- <Typography fontWeight={'bold'}>
- {t('SUPPORT')}
+ <Typography fontWeight={"bold"}>
+ {t("SUPPORT")}
</Typography>
</NoStyleAnchor>
}
@@ -58,7 +58,7 @@ export default function HelpSection() {
/>
<EnteMenuItem
onClick={handleExportOpen}
- label={t('EXPORT')}
+ label={t("EXPORT")}
endIcon={
exportService.isExportInProgress() && (
<EnteSpinner size="20px" />
diff --git a/apps/photos/src/components/Sidebar/MapSetting/ModifyMapEnabled.tsx b/apps/photos/src/components/Sidebar/MapSetting/ModifyMapEnabled.tsx
index f878a68ca7..22aa8bbbba 100644
--- a/apps/photos/src/components/Sidebar/MapSetting/ModifyMapEnabled.tsx
+++ b/apps/photos/src/components/Sidebar/MapSetting/ModifyMapEnabled.tsx
@@ -1,10 +1,10 @@
-import { Box, DialogProps } from '@mui/material';
-import { EnteDrawer } from 'components/EnteDrawer';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { logError } from '@ente/shared/sentry';
-import EnableMap from '../EnableMap';
-import DisableMap from '../DisableMap';
+import { logError } from "@ente/shared/sentry";
+import { Box, DialogProps } from "@mui/material";
+import { EnteDrawer } from "components/EnteDrawer";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
+import DisableMap from "../DisableMap";
+import EnableMap from "../EnableMap";
const ModifyMapEnabled = ({ open, onClose, onRootClose, mapEnabled }) => {
const { somethingWentWrong, updateMapEnabled } = useContext(AppContext);
@@ -14,7 +14,7 @@ const ModifyMapEnabled = ({ open, onClose, onRootClose, mapEnabled }) => {
await updateMapEnabled(false);
onClose();
} catch (e) {
- logError(e, 'Disable Map failed');
+ logError(e, "Disable Map failed");
somethingWentWrong();
}
};
@@ -24,7 +24,7 @@ const ModifyMapEnabled = ({ open, onClose, onRootClose, mapEnabled }) => {
await updateMapEnabled(true);
onClose();
} catch (e) {
- logError(e, 'Enable Map failed');
+ logError(e, "Enable Map failed");
somethingWentWrong();
}
};
@@ -34,8 +34,8 @@ const ModifyMapEnabled = ({ open, onClose, onRootClose, mapEnabled }) => {
onRootClose();
};
- const handleDrawerClose: DialogProps['onClose'] = (_, reason) => {
- if (reason === 'backdropClick') {
+ const handleDrawerClose: DialogProps["onClose"] = (_, reason) => {
+ if (reason === "backdropClick") {
handleRootClose();
} else {
onClose();
@@ -51,9 +51,10 @@ const ModifyMapEnabled = ({ open, onClose, onRootClose, mapEnabled }) => {
onClose={handleDrawerClose}
slotProps={{
backdrop: {
- sx: { '&&&': { backgroundColor: 'transparent' } },
+ sx: { "&&&": { backgroundColor: "transparent" } },
},
- }}>
+ }}
+ >
{mapEnabled ? (
<DisableMap
onClose={onClose}
diff --git a/apps/photos/src/components/Sidebar/MapSetting/index.tsx b/apps/photos/src/components/Sidebar/MapSetting/index.tsx
index 2e2e815a3a..5832baca55 100644
--- a/apps/photos/src/components/Sidebar/MapSetting/index.tsx
+++ b/apps/photos/src/components/Sidebar/MapSetting/index.tsx
@@ -1,13 +1,13 @@
-import { Box, DialogProps, Stack } from '@mui/material';
-import { EnteDrawer } from 'components/EnteDrawer';
-import Titlebar from 'components/Titlebar';
-import { useContext, useEffect, useState } from 'react';
-import { t } from 'i18next';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import ModifyMapEnabled from './ModifyMapEnabled';
-import { getMapEnabledStatus } from 'services/userService';
-import { AppContext } from 'pages/_app';
+import { Box, DialogProps, Stack } from "@mui/material";
+import { EnteDrawer } from "components/EnteDrawer";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import Titlebar from "components/Titlebar";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext, useEffect, useState } from "react";
+import { getMapEnabledStatus } from "services/userService";
+import ModifyMapEnabled from "./ModifyMapEnabled";
export default function MapSettings({ open, onClose, onRootClose }) {
const { mapEnabled, updateMapEnabled } = useContext(AppContext);
@@ -32,8 +32,8 @@ export default function MapSettings({ open, onClose, onRootClose }) {
onRootClose();
};
- const handleDrawerClose: DialogProps['onClose'] = (_, reason) => {
- if (reason === 'backdropClick') {
+ const handleDrawerClose: DialogProps["onClose"] = (_, reason) => {
+ if (reason === "backdropClick") {
handleRootClose();
} else {
onClose();
@@ -46,16 +46,17 @@ export default function MapSettings({ open, onClose, onRootClose }) {
open={open}
onClose={handleDrawerClose}
BackdropProps={{
- sx: { '&&&': { backgroundColor: 'transparent' } },
- }}>
- <Stack spacing={'4px'} py={'12px'}>
+ sx: { "&&&": { backgroundColor: "transparent" } },
+ }}
+ >
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={onClose}
- title={t('MAP')}
+ title={t("MAP")}
onRootClose={handleRootClose}
/>
- <Box px={'8px'}>
+ <Box px={"8px"}>
<Stack py="20px" spacing="24px">
<Box>
<MenuItemGroup>
@@ -63,7 +64,7 @@ export default function MapSettings({ open, onClose, onRootClose }) {
onClick={openModifyMapEnabled}
variant="toggle"
checked={mapEnabled}
- label={t('MAP_SETTINGS')}
+ label={t("MAP_SETTINGS")}
/>
</MenuItemGroup>
</Box>
diff --git a/apps/photos/src/components/Sidebar/Preferences/CacheDirectory.tsx b/apps/photos/src/components/Sidebar/Preferences/CacheDirectory.tsx
index b0773ab2f7..be23d9cbb9 100644
--- a/apps/photos/src/components/Sidebar/Preferences/CacheDirectory.tsx
+++ b/apps/photos/src/components/Sidebar/Preferences/CacheDirectory.tsx
@@ -1,15 +1,15 @@
-import ElectronAPIs from '@ente/shared/electron';
-import { addLogLine } from '@ente/shared/logging';
-import { logError } from '@ente/shared/sentry';
-import Box from '@mui/material/Box';
-import { DirectoryPath } from 'components/Directory';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import { MenuItemGroup } from 'components/Menu/MenuItemGroup';
-import MenuSectionTitle from 'components/Menu/MenuSectionTitle';
-import { t } from 'i18next';
-import isElectron from 'is-electron';
-import { useEffect, useState } from 'react';
-import DownloadManager from 'services/download';
+import ElectronAPIs from "@ente/shared/electron";
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import Box from "@mui/material/Box";
+import { DirectoryPath } from "components/Directory";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import { MenuItemGroup } from "components/Menu/MenuItemGroup";
+import MenuSectionTitle from "components/Menu/MenuSectionTitle";
+import { t } from "i18next";
+import isElectron from "is-electron";
+import { useEffect, useState } from "react";
+import DownloadManager from "services/download";
export default function CacheDirectory() {
const [cacheDirectory, setCacheDirectory] = useState(undefined);
@@ -39,13 +39,13 @@ export default function CacheDirectory() {
setCacheDirectory(newFolder);
await DownloadManager.reloadCaches();
} catch (e) {
- logError(e, 'handleCacheDirectoryChange failed');
+ logError(e, "handleCacheDirectoryChange failed");
}
};
return (
<Box>
- <MenuSectionTitle title={t('CACHE_DIRECTORY')} />
+ <MenuSectionTitle title={t("CACHE_DIRECTORY")} />
<MenuItemGroup>
<EnteMenuItem
variant="path"
diff --git a/apps/photos/src/components/Sidebar/Preferences/LanguageSelector.tsx b/apps/photos/src/components/Sidebar/Preferences/LanguageSelector.tsx
index e8f8bf6c28..efcc03a2d9 100644
--- a/apps/photos/src/components/Sidebar/Preferences/LanguageSelector.tsx
+++ b/apps/photos/src/components/Sidebar/Preferences/LanguageSelector.tsx
@@ -1,12 +1,12 @@
-import DropdownInput, { DropdownOption } from 'components/DropdownInput';
-import { t } from 'i18next';
-import { useRouter } from 'next/router';
import {
- type SupportedLocale,
- supportedLocales,
getLocaleInUse,
setLocaleInUse,
-} from '@/ui/i18n';
+ supportedLocales,
+ type SupportedLocale,
+} from "@/ui/i18n";
+import DropdownInput, { DropdownOption } from "components/DropdownInput";
+import { t } from "i18next";
+import { useRouter } from "next/router";
/**
* Human readable name for each supported locale
@@ -15,18 +15,18 @@ import {
*/
export const localeName = (locale: SupportedLocale) => {
switch (locale) {
- case 'en-US':
- return 'English';
- case 'fr-FR':
- return 'FranΓ§ais';
- case 'zh-CN':
- return 'δΈ­ζ–‡';
- case 'nl-NL':
- return 'Nederlands';
- case 'es-ES':
- return 'EspaΓ±ol';
- case 'pt-BR':
- return 'Brazilian Portuguese';
+ case "en-US":
+ return "English";
+ case "fr-FR":
+ return "FranΓ§ais";
+ case "zh-CN":
+ return "δΈ­ζ–‡";
+ case "nl-NL":
+ return "Nederlands";
+ case "es-ES":
+ return "EspaΓ±ol";
+ case "pt-BR":
+ return "Brazilian Portuguese";
}
};
@@ -50,8 +50,8 @@ export const LanguageSelector = () => {
return (
<DropdownInput
options={getLanguageOptions()}
- label={t('LANGUAGE')}
- labelProps={{ color: 'text.muted' }}
+ label={t("LANGUAGE")}
+ labelProps={{ color: "text.muted" }}
selected={locale}
setSelected={updateCurrentLocale}
/>
diff --git a/apps/photos/src/components/Sidebar/Preferences/index.tsx b/apps/photos/src/components/Sidebar/Preferences/index.tsx
index 108cba0552..ec9d61a47e 100644
--- a/apps/photos/src/components/Sidebar/Preferences/index.tsx
+++ b/apps/photos/src/components/Sidebar/Preferences/index.tsx
@@ -1,27 +1,27 @@
-import ChevronRight from '@mui/icons-material/ChevronRight';
-import { Box, DialogProps, Stack } from '@mui/material';
-import { EnteDrawer } from 'components/EnteDrawer';
-import Titlebar from 'components/Titlebar';
-import isElectron from 'is-electron';
-import { useState } from 'react';
-import { t } from 'i18next';
+import ChevronRight from "@mui/icons-material/ChevronRight";
+import { Box, DialogProps, Stack } from "@mui/material";
+import { EnteDrawer } from "components/EnteDrawer";
+import Titlebar from "components/Titlebar";
+import { t } from "i18next";
+import isElectron from "is-electron";
+import { useState } from "react";
-import AdvancedSettings from '../AdvancedSettings';
-import MapSettings from '../MapSetting';
-import { LanguageSelector } from './LanguageSelector';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import { LS_KEYS } from '@ente/shared/storage/localStorage';
-import { useLocalState } from '@ente/shared/hooks/useLocalState';
-import ElectronAPIs from '@ente/shared/electron';
-import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
-import { logError } from '@ente/shared/sentry';
+import ElectronAPIs from "@ente/shared/electron";
+import { useLocalState } from "@ente/shared/hooks/useLocalState";
+import { logError } from "@ente/shared/sentry";
+import InMemoryStore, { MS_KEYS } from "@ente/shared/storage/InMemoryStore";
+import { LS_KEYS } from "@ente/shared/storage/localStorage";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import AdvancedSettings from "../AdvancedSettings";
+import MapSettings from "../MapSetting";
+import { LanguageSelector } from "./LanguageSelector";
export default function Preferences({ open, onClose, onRootClose }) {
const [advancedSettingsView, setAdvancedSettingsView] = useState(false);
const [mapSettingsView, setMapSettingsView] = useState(false);
const [optOutOfCrashReports, setOptOutOfCrashReports] = useLocalState(
LS_KEYS.OPT_OUT_OF_CRASH_REPORTS,
- false
+ false,
);
const openAdvancedSettings = () => setAdvancedSettingsView(true);
@@ -35,8 +35,8 @@ export default function Preferences({ open, onClose, onRootClose }) {
onRootClose();
};
- const handleDrawerClose: DialogProps['onClose'] = (_, reason) => {
- if (reason === 'backdropClick') {
+ const handleDrawerClose: DialogProps["onClose"] = (_, reason) => {
+ if (reason === "backdropClick") {
handleRootClose();
} else {
onClose();
@@ -47,16 +47,16 @@ export default function Preferences({ open, onClose, onRootClose }) {
try {
if (isElectron()) {
await ElectronAPIs.updateOptOutOfCrashReports(
- !optOutOfCrashReports
+ !optOutOfCrashReports,
);
}
setOptOutOfCrashReports(!optOutOfCrashReports);
InMemoryStore.set(
MS_KEYS.OPT_OUT_OF_CRASH_REPORTS,
- !optOutOfCrashReports
+ !optOutOfCrashReports,
);
} catch (e) {
- logError(e, 'toggleOptOutOfCrashReports failed');
+ logError(e, "toggleOptOutOfCrashReports failed");
}
};
@@ -66,33 +66,34 @@ export default function Preferences({ open, onClose, onRootClose }) {
open={open}
onClose={handleDrawerClose}
BackdropProps={{
- sx: { '&&&': { backgroundColor: 'transparent' } },
- }}>
- <Stack spacing={'4px'} py={'12px'}>
+ sx: { "&&&": { backgroundColor: "transparent" } },
+ }}
+ >
+ <Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={onClose}
- title={t('PREFERENCES')}
+ title={t("PREFERENCES")}
onRootClose={handleRootClose}
/>
- <Box px={'8px'}>
+ <Box px={"8px"}>
<Stack py="20px" spacing="24px">
<LanguageSelector />
<EnteMenuItem
variant="toggle"
checked={!optOutOfCrashReports}
onClick={toggleOptOutOfCrashReports}
- label={t('CRASH_REPORTING')}
+ label={t("CRASH_REPORTING")}
/>
<EnteMenuItem
onClick={openMapSettings}
endIcon={<ChevronRight />}
- label={t('MAP')}
+ label={t("MAP")}
/>
<EnteMenuItem
onClick={openAdvancedSettings}
endIcon={<ChevronRight />}
- label={t('ADVANCED')}
+ label={t("ADVANCED")}
/>
</Stack>
</Box>
diff --git a/apps/photos/src/components/Sidebar/ShortcutSection.tsx b/apps/photos/src/components/Sidebar/ShortcutSection.tsx
index 6c32b14d74..dce298844e 100644
--- a/apps/photos/src/components/Sidebar/ShortcutSection.tsx
+++ b/apps/photos/src/components/Sidebar/ShortcutSection.tsx
@@ -1,20 +1,20 @@
-import React, { useContext, useState, useEffect } from 'react';
-import { t } from 'i18next';
+import { t } from "i18next";
+import { useContext, useEffect, useState } from "react";
-import { GalleryContext } from 'pages/gallery';
+import ArchiveOutlined from "@mui/icons-material/ArchiveOutlined";
+import CategoryIcon from "@mui/icons-material/Category";
+import DeleteOutline from "@mui/icons-material/DeleteOutline";
+import LockOutlined from "@mui/icons-material/LockOutlined";
+import VisibilityOff from "@mui/icons-material/VisibilityOff";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
import {
ARCHIVE_SECTION,
DUMMY_UNCATEGORIZED_COLLECTION,
TRASH_SECTION,
-} from 'constants/collection';
-import { CollectionSummaries } from 'types/collection';
-import DeleteOutline from '@mui/icons-material/DeleteOutline';
-import ArchiveOutlined from '@mui/icons-material/ArchiveOutlined';
-import CategoryIcon from '@mui/icons-material/Category';
-import { getUncategorizedCollection } from 'services/collectionService';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import VisibilityOff from '@mui/icons-material/VisibilityOff';
-import LockOutlined from '@mui/icons-material/LockOutlined';
+} from "constants/collection";
+import { GalleryContext } from "pages/gallery";
+import { getUncategorizedCollection } from "services/collectionService";
+import { CollectionSummaries } from "types/collection";
interface Iprops {
closeSidebar: () => void;
collectionSummaries: CollectionSummaries;
@@ -67,7 +67,7 @@ export default function ShortcutSection({
startIcon={<CategoryIcon />}
onClick={openUncategorizedSection}
variant="captioned"
- label={t('UNCATEGORIZED')}
+ label={t("UNCATEGORIZED")}
subText={collectionSummaries
.get(uncategorizedCollectionId)
?.fileCount.toString()}
@@ -76,7 +76,7 @@ export default function ShortcutSection({
startIcon={<ArchiveOutlined />}
onClick={openArchiveSection}
variant="captioned"
- label={t('ARCHIVE_SECTION_NAME')}
+ label={t("ARCHIVE_SECTION_NAME")}
subText={collectionSummaries
.get(ARCHIVE_SECTION)
?.fileCount.toString()}
@@ -85,14 +85,14 @@ export default function ShortcutSection({
startIcon={<VisibilityOff />}
onClick={openHiddenSection}
variant="captioned"
- label={t('HIDDEN')}
+ label={t("HIDDEN")}
subIcon={<LockOutlined />}
/>
<EnteMenuItem
startIcon={<DeleteOutline />}
onClick={openTrashSection}
variant="captioned"
- label={t('TRASH')}
+ label={t("TRASH")}
subText={collectionSummaries
.get(TRASH_SECTION)
?.fileCount.toString()}
diff --git a/apps/photos/src/components/Sidebar/SubscriptionCard/backgroundOverlay.tsx b/apps/photos/src/components/Sidebar/SubscriptionCard/backgroundOverlay.tsx
index 2a7f105bea..eb9c85f510 100644
--- a/apps/photos/src/components/Sidebar/SubscriptionCard/backgroundOverlay.tsx
+++ b/apps/photos/src/components/Sidebar/SubscriptionCard/backgroundOverlay.tsx
@@ -1,8 +1,7 @@
-import React from 'react';
export function BackgroundOverlay() {
return (
<img
- style={{ aspectRatio: '2/1' }}
+ style={{ aspectRatio: "2/1" }}
width="100%"
src="/images/subscription-card-background/1x.png"
srcSet="/images/subscription-card-background/2x.png 2x,
diff --git a/apps/photos/src/components/Sidebar/SubscriptionCard/clickOverlay.tsx b/apps/photos/src/components/Sidebar/SubscriptionCard/clickOverlay.tsx
index 6338b5a1ab..7890558089 100644
--- a/apps/photos/src/components/Sidebar/SubscriptionCard/clickOverlay.tsx
+++ b/apps/photos/src/components/Sidebar/SubscriptionCard/clickOverlay.tsx
@@ -1,13 +1,13 @@
-import ChevronRightIcon from '@mui/icons-material/ChevronRight';
-import { FlexWrapper, Overlay } from '@ente/shared/components/Container';
-import React from 'react';
+import { FlexWrapper, Overlay } from "@ente/shared/components/Container";
+import ChevronRightIcon from "@mui/icons-material/ChevronRight";
export function ClickOverlay({ onClick }) {
return (
<Overlay display="flex">
<FlexWrapper
onClick={onClick}
- justifyContent={'flex-end'}
- sx={{ cursor: 'pointer' }}>
+ justifyContent={"flex-end"}
+ sx={{ cursor: "pointer" }}
+ >
<ChevronRightIcon />
</FlexWrapper>
</Overlay>
diff --git a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/index.tsx b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/index.tsx
index 14cd231fe0..77776745dc 100644
--- a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/index.tsx
+++ b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/index.tsx
@@ -1,8 +1,8 @@
-import React, { useMemo } from 'react';
-import { UserDetails } from 'types/user';
-import { isPartOfFamily } from 'utils/user/family';
-import StorageSection from '../storageSection';
-import { FamilyUsageSection } from './usageSection';
+import { useMemo } from "react";
+import { UserDetails } from "types/user";
+import { isPartOfFamily } from "utils/user/family";
+import StorageSection from "../storageSection";
+import { FamilyUsageSection } from "./usageSection";
interface Iprops {
userDetails: UserDetails;
@@ -12,7 +12,7 @@ export function FamilySubscriptionCardContent({ userDetails }: Iprops) {
if (isPartOfFamily(userDetails.familyData)) {
return userDetails.familyData.members.reduce(
(sum, currentMember) => sum + currentMember.usage,
- 0
+ 0,
);
} else {
return userDetails.usage;
diff --git a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/usageSection/index.tsx b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/usageSection/index.tsx
index bfe92729d4..4c0b1904f2 100644
--- a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/usageSection/index.tsx
+++ b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/usageSection/index.tsx
@@ -1,9 +1,8 @@
-import { Legend } from './legend';
-import { FamilyUsageProgressBar } from './progressBar';
-import { Box, Stack, Typography } from '@mui/material';
-import { SpaceBetweenFlex } from '@ente/shared/components/Container';
-import React from 'react';
-import { t } from 'i18next';
+import { SpaceBetweenFlex } from "@ente/shared/components/Container";
+import { Box, Stack, Typography } from "@mui/material";
+import { t } from "i18next";
+import { Legend } from "./legend";
+import { FamilyUsageProgressBar } from "./progressBar";
interface Iprops {
userUsage: number;
@@ -28,13 +27,14 @@ export function FamilyUsageSection({
<SpaceBetweenFlex
sx={{
marginTop: 1.5,
- }}>
- <Stack direction={'row'} spacing={1.5}>
- <Legend label={t('YOU')} color="text.base" />
- <Legend label={t('FAMILY')} color="text.muted" />
+ }}
+ >
+ <Stack direction={"row"} spacing={1.5}>
+ <Legend label={t("YOU")} color="text.base" />
+ <Legend label={t("FAMILY")} color="text.muted" />
</Stack>
- <Typography variant="mini" fontWeight={'bold'}>
- {t('photos_count', { count: fileCount ?? 0 })}
+ <Typography variant="mini" fontWeight={"bold"}>
+ {t("photos_count", { count: fileCount ?? 0 })}
</Typography>
</SpaceBetweenFlex>
</Box>
diff --git a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/usageSection/legend.tsx b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/usageSection/legend.tsx
index 442a73ed76..6caaa2374d 100644
--- a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/usageSection/legend.tsx
+++ b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/usageSection/legend.tsx
@@ -1,7 +1,6 @@
-import { Typography } from '@mui/material';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import React from 'react';
-import { LegendIndicator } from '../../../styledComponents';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import { Typography } from "@mui/material";
+import { LegendIndicator } from "../../../styledComponents";
interface Iprops {
label: string;
@@ -11,7 +10,7 @@ export function Legend({ label, color }: Iprops) {
return (
<FlexWrapper>
<LegendIndicator sx={{ color }} />
- <Typography variant="mini" fontWeight={'bold'}>
+ <Typography variant="mini" fontWeight={"bold"}>
{label}
</Typography>
</FlexWrapper>
diff --git a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/usageSection/progressBar.tsx b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/usageSection/progressBar.tsx
index 57a3c8bd90..ab28b5b8f1 100644
--- a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/usageSection/progressBar.tsx
+++ b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/family/usageSection/progressBar.tsx
@@ -1,6 +1,5 @@
-import { Box } from '@mui/material';
-import React from 'react';
-import { Progressbar } from '../../../styledComponents';
+import { Box } from "@mui/material";
+import { Progressbar } from "../../../styledComponents";
interface Iprops {
userUsage: number;
totalUsage: number;
@@ -13,20 +12,20 @@ export function FamilyUsageProgressBar({
totalStorage,
}: Iprops) {
return (
- <Box position={'relative'} width="100%">
+ <Box position={"relative"} width="100%">
<Progressbar
- sx={{ backgroundColor: 'transparent' }}
+ sx={{ backgroundColor: "transparent" }}
value={Math.min((userUsage * 100) / totalStorage, 100)}
/>
<Progressbar
sx={{
- position: 'absolute',
+ position: "absolute",
top: 0,
zIndex: 1,
- '.MuiLinearProgress-bar ': {
- backgroundColor: 'text.muted',
+ ".MuiLinearProgress-bar ": {
+ backgroundColor: "text.muted",
},
- width: '100%',
+ width: "100%",
}}
value={Math.min((totalUsage * 100) / totalStorage, 100)}
/>
diff --git a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/index.tsx b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/index.tsx
index 8f86627f26..238058534c 100644
--- a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/index.tsx
+++ b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/index.tsx
@@ -1,9 +1,8 @@
-import { IndividualSubscriptionCardContent } from './individual';
-import { FamilySubscriptionCardContent } from './family';
-import React from 'react';
-import { hasNonAdminFamilyMembers } from 'utils/user/family';
-import { Overlay, SpaceBetweenFlex } from '@ente/shared/components/Container';
-import { UserDetails } from 'types/user';
+import { Overlay, SpaceBetweenFlex } from "@ente/shared/components/Container";
+import { UserDetails } from "types/user";
+import { hasNonAdminFamilyMembers } from "utils/user/family";
+import { FamilySubscriptionCardContent } from "./family";
+import { IndividualSubscriptionCardContent } from "./individual";
interface Iprops {
userDetails: UserDetails;
@@ -13,9 +12,10 @@ export function SubscriptionCardContentOverlay({ userDetails }: Iprops) {
return (
<Overlay>
<SpaceBetweenFlex
- height={'100%'}
- flexDirection={'column'}
- padding={'20px 16px'}>
+ height={"100%"}
+ flexDirection={"column"}
+ padding={"20px 16px"}
+ >
{hasNonAdminFamilyMembers(userDetails.familyData) ? (
<FamilySubscriptionCardContent userDetails={userDetails} />
) : (
diff --git a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/individual/index.tsx b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/individual/index.tsx
index 6a8f9a70eb..9bdc3292c1 100644
--- a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/individual/index.tsx
+++ b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/individual/index.tsx
@@ -1,7 +1,6 @@
-import React from 'react';
-import { UserDetails } from 'types/user';
-import StorageSection from '../storageSection';
-import { IndividualUsageSection } from './usageSection';
+import { UserDetails } from "types/user";
+import StorageSection from "../storageSection";
+import { IndividualUsageSection } from "./usageSection";
interface Iprops {
userDetails: UserDetails;
diff --git a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/individual/usageSection.tsx b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/individual/usageSection.tsx
index 54fd5d56ca..4b0ce31b04 100644
--- a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/individual/usageSection.tsx
+++ b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/individual/usageSection.tsx
@@ -1,10 +1,9 @@
-import { Box, Typography } from '@mui/material';
-import { SpaceBetweenFlex } from '@ente/shared/components/Container';
-import React from 'react';
-import { makeHumanReadableStorage } from 'utils/billing';
-import { t } from 'i18next';
+import { SpaceBetweenFlex } from "@ente/shared/components/Container";
+import { Box, Typography } from "@mui/material";
+import { t } from "i18next";
+import { makeHumanReadableStorage } from "utils/billing";
-import { Progressbar } from '../../styledComponents';
+import { Progressbar } from "../../styledComponents";
interface Iprops {
usage: number;
@@ -18,12 +17,13 @@ export function IndividualUsageSection({ usage, storage, fileCount }: Iprops) {
<SpaceBetweenFlex
sx={{
marginTop: 1.5,
- }}>
+ }}
+ >
<Typography variant="mini">{`${makeHumanReadableStorage(
- storage - usage
- )} ${t('FREE')}`}</Typography>
- <Typography variant="mini" fontWeight={'bold'}>
- {t('photos_count', { count: fileCount ?? 0 })}
+ storage - usage,
+ )} ${t("FREE")}`}</Typography>
+ <Typography variant="mini" fontWeight={"bold"}>
+ {t("photos_count", { count: fileCount ?? 0 })}
</Typography>
</SpaceBetweenFlex>
</Box>
diff --git a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/storageSection.tsx b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/storageSection.tsx
index b26232246a..6143044f0d 100644
--- a/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/storageSection.tsx
+++ b/apps/photos/src/components/Sidebar/SubscriptionCard/contentOverlay/storageSection.tsx
@@ -1,7 +1,6 @@
-import { Box, styled, Typography } from '@mui/material';
-import React from 'react';
-import { convertBytesToGBs, makeHumanReadableStorage } from 'utils/billing';
-import { t } from 'i18next';
+import { Box, styled, Typography } from "@mui/material";
+import { t } from "i18next";
+import { convertBytesToGBs, makeHumanReadableStorage } from "utils/billing";
const MobileSmallBox = styled(Box)`
display: none;
@@ -23,25 +22,27 @@ interface Iprops {
export default function StorageSection({ usage, storage }: Iprops) {
return (
<Box width="100%">
- <Typography variant="small" color={'text.muted'}>
- {t('STORAGE')}
+ <Typography variant="small" color={"text.muted"}>
+ {t("STORAGE")}
</Typography>
<DefaultBox>
<Typography
- fontWeight={'bold'}
- sx={{ fontSize: '24px', lineHeight: '30px' }}>
+ fontWeight={"bold"}
+ sx={{ fontSize: "24px", lineHeight: "30px" }}
+ >
{`${makeHumanReadableStorage(usage, { roundUp: true })} ${t(
- 'OF'
- )} ${makeHumanReadableStorage(storage)} ${t('USED')}`}
+ "OF",
+ )} ${makeHumanReadableStorage(storage)} ${t("USED")}`}
</Typography>
</DefaultBox>
<MobileSmallBox>
<Typography
- fontWeight={'bold'}
- sx={{ fontSize: '24px', lineHeight: '30px' }}>
+ fontWeight={"bold"}
+ sx={{ fontSize: "24px", lineHeight: "30px" }}
+ >
{`${convertBytesToGBs(usage)} / ${convertBytesToGBs(
- storage
- )} ${t('GB')} ${t('USED')}`}
+ storage,
+ )} ${t("GB")} ${t("USED")}`}
</Typography>
</MobileSmallBox>
</Box>
diff --git a/apps/photos/src/components/Sidebar/SubscriptionCard/index.tsx b/apps/photos/src/components/Sidebar/SubscriptionCard/index.tsx
index 21ce85caab..848792817a 100644
--- a/apps/photos/src/components/Sidebar/SubscriptionCard/index.tsx
+++ b/apps/photos/src/components/Sidebar/SubscriptionCard/index.tsx
@@ -1,10 +1,9 @@
-import { BackgroundOverlay } from './backgroundOverlay';
-import { ClickOverlay } from './clickOverlay';
-import React from 'react';
-import { Box, Skeleton } from '@mui/material';
-import { UserDetails } from 'types/user';
+import { Box, Skeleton } from "@mui/material";
+import { UserDetails } from "types/user";
+import { BackgroundOverlay } from "./backgroundOverlay";
+import { ClickOverlay } from "./clickOverlay";
-import { SubscriptionCardContentOverlay } from './contentOverlay';
+import { SubscriptionCardContentOverlay } from "./contentOverlay";
const SUBSCRIPTION_CARD_SIZE = 152;
@@ -20,7 +19,7 @@ export default function SubscriptionCard({ userDetails, onClick }: Iprops) {
animation="wave"
variant="rectangular"
height={SUBSCRIPTION_CARD_SIZE}
- sx={{ borderRadius: '8px' }}
+ sx={{ borderRadius: "8px" }}
/>
);
}
diff --git a/apps/photos/src/components/Sidebar/SubscriptionCard/styledComponents.tsx b/apps/photos/src/components/Sidebar/SubscriptionCard/styledComponents.tsx
index 74eb7bb7ed..4d0a15e9d6 100644
--- a/apps/photos/src/components/Sidebar/SubscriptionCard/styledComponents.tsx
+++ b/apps/photos/src/components/Sidebar/SubscriptionCard/styledComponents.tsx
@@ -1,16 +1,16 @@
-import { LinearProgress, styled } from '@mui/material';
-import { DotSeparator } from '../styledComponents';
+import { LinearProgress, styled } from "@mui/material";
+import { DotSeparator } from "../styledComponents";
export const Progressbar = styled(LinearProgress)(() => ({
- '.MuiLinearProgress-bar': {
- borderRadius: '2px',
+ ".MuiLinearProgress-bar": {
+ borderRadius: "2px",
},
- borderRadius: '2px',
- backgroundColor: 'rgba(255, 255, 255, 0.2)',
+ borderRadius: "2px",
+ backgroundColor: "rgba(255, 255, 255, 0.2)",
}));
Progressbar.defaultProps = {
- variant: 'determinate',
+ variant: "determinate",
};
export const LegendIndicator = styled(DotSeparator)`
diff --git a/apps/photos/src/components/Sidebar/SubscriptionStatus/index.tsx b/apps/photos/src/components/Sidebar/SubscriptionStatus/index.tsx
index 40f02bd1d0..b127c15973 100644
--- a/apps/photos/src/components/Sidebar/SubscriptionStatus/index.tsx
+++ b/apps/photos/src/components/Sidebar/SubscriptionStatus/index.tsx
@@ -1,23 +1,23 @@
-import { GalleryContext } from 'pages/gallery';
-import React, { MouseEventHandler, useContext, useMemo } from 'react';
+import Box from "@mui/material/Box";
+import { t } from "i18next";
+import { GalleryContext } from "pages/gallery";
+import { MouseEventHandler, useContext, useMemo } from "react";
+import { Trans } from "react-i18next";
+import { UserDetails } from "types/user";
import {
+ hasAddOnBonus,
+ hasExceededStorageQuota,
hasPaidSubscription,
+ hasStripeSubscription,
isOnFreePlan,
- hasExceededStorageQuota,
isSubscriptionActive,
isSubscriptionCancelled,
- hasStripeSubscription,
- hasAddOnBonus,
-} from 'utils/billing';
-import Box from '@mui/material/Box';
-import { UserDetails } from 'types/user';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
+} from "utils/billing";
-import { Typography } from '@mui/material';
-import billingService from 'services/billingService';
-import { isPartOfFamily, isFamilyAdmin } from 'utils/user/family';
-import LinkButton from 'components/pages/gallery/LinkButton';
+import { Typography } from "@mui/material";
+import LinkButton from "components/pages/gallery/LinkButton";
+import billingService from "services/billingService";
+import { isFamilyAdmin, isPartOfFamily } from "utils/user/family";
export default function SubscriptionStatus({
userDetails,
@@ -75,27 +75,27 @@ export default function SubscriptionStatus({
if (isOnFreePlan(userDetails.subscription)) {
messages.push(
<Trans
- i18nKey={'FREE_SUBSCRIPTION_INFO'}
+ i18nKey={"FREE_SUBSCRIPTION_INFO"}
values={{
date: userDetails.subscription?.expiryTime,
}}
- />
+ />,
);
} else if (isSubscriptionCancelled(userDetails.subscription)) {
messages.push(
- t('RENEWAL_CANCELLED_SUBSCRIPTION_INFO', {
+ t("RENEWAL_CANCELLED_SUBSCRIPTION_INFO", {
date: userDetails.subscription?.expiryTime,
- })
+ }),
);
}
} else {
messages.push(
<Trans
- i18nKey={'SUBSCRIPTION_EXPIRED_MESSAGE'}
+ i18nKey={"SUBSCRIPTION_EXPIRED_MESSAGE"}
components={{
a: <LinkButton onClick={handleClick} />,
}}
- />
+ />,
);
}
}
@@ -103,11 +103,11 @@ export default function SubscriptionStatus({
if (hasExceededStorageQuota(userDetails) && messages.length === 0) {
messages.push(
<Trans
- i18nKey={'STORAGE_QUOTA_EXCEEDED_SUBSCRIPTION_INFO'}
+ i18nKey={"STORAGE_QUOTA_EXCEEDED_SUBSCRIPTION_INFO"}
components={{
a: <LinkButton onClick={handleClick} />,
}}
- />
+ />,
);
}
@@ -115,9 +115,10 @@ export default function SubscriptionStatus({
<Box px={1} pt={0.5}>
<Typography
variant="small"
- color={'text.muted'}
+ color={"text.muted"}
onClick={handleClick && handleClick}
- sx={{ cursor: handleClick && 'pointer' }}>
+ sx={{ cursor: handleClick && "pointer" }}
+ >
{messages}
</Typography>
</Box>
diff --git a/apps/photos/src/components/Sidebar/UtilitySection.tsx b/apps/photos/src/components/Sidebar/UtilitySection.tsx
index 299a802b9d..3acd0326a6 100644
--- a/apps/photos/src/components/Sidebar/UtilitySection.tsx
+++ b/apps/photos/src/components/Sidebar/UtilitySection.tsx
@@ -1,28 +1,28 @@
-import { t } from 'i18next';
-import { useContext, useState } from 'react';
+import { t } from "i18next";
+import { useContext, useState } from "react";
// import FixLargeThumbnails from 'components/FixLargeThumbnail';
-import RecoveryKey from '@ente/shared/components/RecoveryKey';
+import RecoveryKey from "@ente/shared/components/RecoveryKey";
import {
ACCOUNTS_PAGES,
PHOTOS_PAGES as PAGES,
-} from '@ente/shared/constants/pages';
-import TwoFactorModal from 'components/TwoFactor/Modal';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
+} from "@ente/shared/constants/pages";
+import TwoFactorModal from "components/TwoFactor/Modal";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
// import mlIDbStorage from 'utils/storage/mlIDbStorage';
-import { APPS, CLIENT_PACKAGE_NAMES } from '@ente/shared/apps/constants';
-import ThemeSwitcher from '@ente/shared/components/ThemeSwitcher';
-import { getAccountsURL } from '@ente/shared/network/api';
-import { logError } from '@ente/shared/sentry';
-import { THEME_COLOR } from '@ente/shared/themes/constants';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import WatchFolder from 'components/WatchFolder';
-import isElectron from 'is-electron';
-import { getAccountsToken } from 'services/userService';
-import { getDownloadAppMessage } from 'utils/ui';
-import { isInternalUser } from 'utils/user';
-import Preferences from './Preferences';
+import { APPS, CLIENT_PACKAGE_NAMES } from "@ente/shared/apps/constants";
+import ThemeSwitcher from "@ente/shared/components/ThemeSwitcher";
+import { getAccountsURL } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import { THEME_COLOR } from "@ente/shared/themes/constants";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import WatchFolder from "components/WatchFolder";
+import isElectron from "is-electron";
+import { getAccountsToken } from "services/userService";
+import { getDownloadAppMessage } from "utils/ui";
+import { isInternalUser } from "utils/user";
+import Preferences from "./Preferences";
export default function UtilitySection({ closeSidebar }) {
const router = useRouter();
@@ -77,10 +77,10 @@ export default function UtilitySection({ closeSidebar }) {
window.location.href = `${getAccountsURL()}${
ACCOUNTS_PAGES.ACCOUNT_HANDOFF
}?package=${CLIENT_PACKAGE_NAMES.get(
- APPS.PHOTOS
+ APPS.PHOTOS,
)}&token=${accountsToken}`;
} catch (e) {
- logError(e, 'failed to redirect to accounts page');
+ logError(e, "failed to redirect to accounts page");
}
};
@@ -88,16 +88,16 @@ export default function UtilitySection({ closeSidebar }) {
const somethingWentWrong = () =>
setDialogMessage({
- title: t('ERROR'),
- content: t('RECOVER_KEY_GENERATION_FAILED'),
- close: { variant: 'critical' },
+ title: t("ERROR"),
+ content: t("RECOVER_KEY_GENERATION_FAILED"),
+ close: { variant: "critical" },
});
const toggleTheme = () => {
setThemeColor((themeColor) =>
themeColor === THEME_COLOR.DARK
? THEME_COLOR.LIGHT
- : THEME_COLOR.DARK
+ : THEME_COLOR.DARK,
);
};
@@ -107,19 +107,19 @@ export default function UtilitySection({ closeSidebar }) {
<EnteMenuItem
onClick={openWatchFolder}
variant="secondary"
- label={t('WATCH_FOLDERS')}
+ label={t("WATCH_FOLDERS")}
/>
)}
<EnteMenuItem
variant="secondary"
onClick={openRecoveryKeyModal}
- label={t('RECOVERY_KEY')}
+ label={t("RECOVERY_KEY")}
/>
{isInternalUser() && (
<EnteMenuItem
onClick={toggleTheme}
variant="secondary"
- label={t('CHOSE_THEME')}
+ label={t("CHOSE_THEME")}
endIcon={
<ThemeSwitcher
themeColor={themeColor}
@@ -131,37 +131,37 @@ export default function UtilitySection({ closeSidebar }) {
<EnteMenuItem
variant="secondary"
onClick={openTwoFactorModal}
- label={t('TWO_FACTOR')}
+ label={t("TWO_FACTOR")}
/>
<EnteMenuItem
variant="secondary"
onClick={redirectToAccountsPage}
- label={t('PASSKEYS')}
+ label={t("PASSKEYS")}
/>
<EnteMenuItem
variant="secondary"
onClick={redirectToChangePasswordPage}
- label={t('CHANGE_PASSWORD')}
+ label={t("CHANGE_PASSWORD")}
/>
<EnteMenuItem
variant="secondary"
onClick={redirectToChangeEmailPage}
- label={t('CHANGE_EMAIL')}
+ label={t("CHANGE_EMAIL")}
/>
<EnteMenuItem
variant="secondary"
onClick={redirectToDeduplicatePage}
- label={t('DEDUPLICATE_FILES')}
+ label={t("DEDUPLICATE_FILES")}
/>
<EnteMenuItem
variant="secondary"
onClick={openPreferencesOptions}
- label={t('PREFERENCES')}
+ label={t("PREFERENCES")}
/>
<RecoveryKey
appContext={appContext}
diff --git a/apps/photos/src/components/Sidebar/index.tsx b/apps/photos/src/components/Sidebar/index.tsx
index f58b415578..a93eb23876 100644
--- a/apps/photos/src/components/Sidebar/index.tsx
+++ b/apps/photos/src/components/Sidebar/index.tsx
@@ -1,15 +1,13 @@
-import React from 'react';
-
-import ShortcutSection from './ShortcutSection';
-import UtilitySection from './UtilitySection';
-import HelpSection from './HelpSection';
-import ExitSection from './ExitSection';
-import DebugSection from './DebugSection';
-import { DrawerSidebar } from './styledComponents';
-import HeaderSection from './Header';
-import { CollectionSummaries } from 'types/collection';
-import UserDetailsSection from './userDetailsSection';
-import { Divider, Stack } from '@mui/material';
+import { Divider, Stack } from "@mui/material";
+import { CollectionSummaries } from "types/collection";
+import DebugSection from "./DebugSection";
+import ExitSection from "./ExitSection";
+import HeaderSection from "./Header";
+import HelpSection from "./HelpSection";
+import ShortcutSection from "./ShortcutSection";
+import UtilitySection from "./UtilitySection";
+import { DrawerSidebar } from "./styledComponents";
+import UserDetailsSection from "./userDetailsSection";
interface Iprops {
collectionSummaries: CollectionSummaries;
diff --git a/apps/photos/src/components/Sidebar/styledComponents.tsx b/apps/photos/src/components/Sidebar/styledComponents.tsx
index 15c11f83f0..d2b2f6b2b9 100644
--- a/apps/photos/src/components/Sidebar/styledComponents.tsx
+++ b/apps/photos/src/components/Sidebar/styledComponents.tsx
@@ -1,14 +1,14 @@
-import { styled } from '@mui/material';
-import CircleIcon from '@mui/icons-material/Circle';
-import { EnteDrawer } from 'components/EnteDrawer';
+import CircleIcon from "@mui/icons-material/Circle";
+import { styled } from "@mui/material";
+import { EnteDrawer } from "components/EnteDrawer";
export const DrawerSidebar = styled(EnteDrawer)(({ theme }) => ({
- '& .MuiPaper-root': {
+ "& .MuiPaper-root": {
padding: theme.spacing(1.5),
},
}));
-DrawerSidebar.defaultProps = { anchor: 'left' };
+DrawerSidebar.defaultProps = { anchor: "left" };
export const DotSeparator = styled(CircleIcon)`
font-size: 4px;
diff --git a/apps/photos/src/components/Sidebar/userDetailsSection.tsx b/apps/photos/src/components/Sidebar/userDetailsSection.tsx
index cb552de575..d2cf556fa9 100644
--- a/apps/photos/src/components/Sidebar/userDetailsSection.tsx
+++ b/apps/photos/src/components/Sidebar/userDetailsSection.tsx
@@ -1,21 +1,21 @@
-import React, { useContext, useEffect, useMemo, useState } from 'react';
-import SubscriptionCard from './SubscriptionCard';
-import { getUserDetailsV2 } from 'services/userService';
-import { UserDetails } from 'types/user';
-import { getData, LS_KEYS, setData } from '@ente/shared/storage/localStorage';
-import { useLocalState } from '@ente/shared/hooks/useLocalState';
-import Typography from '@mui/material/Typography';
-import SubscriptionStatus from './SubscriptionStatus';
-import { Box, Skeleton } from '@mui/material';
-import { MemberSubscriptionManage } from '../MemberSubscriptionManage';
-import { GalleryContext } from 'pages/gallery';
-import { isFamilyAdmin, isPartOfFamily } from 'utils/user/family';
+import { useLocalState } from "@ente/shared/hooks/useLocalState";
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
+import { Box, Skeleton } from "@mui/material";
+import Typography from "@mui/material/Typography";
+import { GalleryContext } from "pages/gallery";
+import { useContext, useEffect, useMemo, useState } from "react";
+import { getUserDetailsV2 } from "services/userService";
+import { UserDetails } from "types/user";
+import { isFamilyAdmin, isPartOfFamily } from "utils/user/family";
+import { MemberSubscriptionManage } from "../MemberSubscriptionManage";
+import SubscriptionCard from "./SubscriptionCard";
+import SubscriptionStatus from "./SubscriptionStatus";
export default function UserDetailsSection({ sidebarView }) {
const galleryContext = useContext(GalleryContext);
const [userDetails, setUserDetails] = useLocalState<UserDetails>(
- LS_KEYS.USER_DETAILS
+ LS_KEYS.USER_DETAILS,
);
const [memberSubscriptionManageView, setMemberSubscriptionManageView] =
useState(false);
@@ -47,7 +47,7 @@ export default function UserDetailsSection({ sidebarView }) {
userDetails &&
isPartOfFamily(userDetails.familyData) &&
!isFamilyAdmin(userDetails.familyData),
- [userDetails]
+ [userDetails],
);
const handleSubscriptionCardClick = isMemberSubscription
diff --git a/apps/photos/src/components/Titlebar.tsx b/apps/photos/src/components/Titlebar.tsx
index 7abe3a31bd..ed9089f4c2 100644
--- a/apps/photos/src/components/Titlebar.tsx
+++ b/apps/photos/src/components/Titlebar.tsx
@@ -1,8 +1,7 @@
-import Close from '@mui/icons-material/Close';
-import ArrowBack from '@mui/icons-material/ArrowBack';
-import { Box, IconButton, Typography } from '@mui/material';
-import React from 'react';
-import { FlexWrapper } from '@ente/shared/components/Container';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import ArrowBack from "@mui/icons-material/ArrowBack";
+import Close from "@mui/icons-material/Close";
+import { Box, IconButton, Typography } from "@mui/material";
interface Iprops {
title: string;
@@ -25,30 +24,33 @@ export default function Titlebar({
<>
<FlexWrapper
height={48}
- alignItems={'center'}
- justifyContent="space-between">
+ alignItems={"center"}
+ justifyContent="space-between"
+ >
<IconButton
onClick={onClose}
- color={backIsClose ? 'secondary' : 'primary'}>
+ color={backIsClose ? "secondary" : "primary"}
+ >
{backIsClose ? <Close /> : <ArrowBack />}
</IconButton>
- <Box display={'flex'} gap="4px">
+ <Box display={"flex"} gap="4px">
{actionButton && actionButton}
{!backIsClose && (
- <IconButton onClick={onRootClose} color={'secondary'}>
+ <IconButton onClick={onRootClose} color={"secondary"}>
<Close />
</IconButton>
)}
</Box>
</FlexWrapper>
<Box py={0.5} px={2}>
- <Typography variant="h3" fontWeight={'bold'}>
+ <Typography variant="h3" fontWeight={"bold"}>
{title}
</Typography>
<Typography
variant="small"
color="text.muted"
- sx={{ wordBreak: 'break-all', minHeight: '17px' }}>
+ sx={{ wordBreak: "break-all", minHeight: "17px" }}
+ >
{caption}
</Typography>
</Box>
diff --git a/apps/photos/src/components/TruncateText.tsx b/apps/photos/src/components/TruncateText.tsx
index 7625232d65..3d34972157 100644
--- a/apps/photos/src/components/TruncateText.tsx
+++ b/apps/photos/src/components/TruncateText.tsx
@@ -1,6 +1,5 @@
-import Tooltip from '@mui/material/Tooltip';
-import React from 'react';
-import { Box, styled, Typography } from '@mui/material';
+import { Box, styled, Typography } from "@mui/material";
+import Tooltip from "@mui/material/Tooltip";
const Ellipse = styled(Typography)`
overflow: hidden;
@@ -14,8 +13,8 @@ const Ellipse = styled(Typography)`
export default function TruncateText({ text }) {
return (
<Tooltip title={text}>
- <Box height={'2.1em'} overflow="hidden">
- <Ellipse variant="small" sx={{ wordBreak: 'break-word' }}>
+ <Box height={"2.1em"} overflow="hidden">
+ <Ellipse variant="small" sx={{ wordBreak: "break-word" }}>
{text}
</Ellipse>
</Box>
diff --git a/apps/photos/src/components/TwoFactor/Modal/Manage.tsx b/apps/photos/src/components/TwoFactor/Modal/Manage.tsx
index 0464b8179d..f9d9a23c97 100644
--- a/apps/photos/src/components/TwoFactor/Modal/Manage.tsx
+++ b/apps/photos/src/components/TwoFactor/Modal/Manage.tsx
@@ -1,12 +1,12 @@
-import React, { useContext } from 'react';
-import { t } from 'i18next';
+import { t } from "i18next";
+import { useContext } from "react";
-import { AppContext } from 'pages/_app';
-import { PHOTOS_PAGES as PAGES } from '@ente/shared/constants/pages';
-import router from 'next/router';
-import { disableTwoFactor } from '@ente/accounts/api/user';
-import { setData, LS_KEYS, getData } from '@ente/shared/storage/localStorage';
-import { Button, Grid } from '@mui/material';
+import { disableTwoFactor } from "@ente/accounts/api/user";
+import { PHOTOS_PAGES as PAGES } from "@ente/shared/constants/pages";
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
+import { Button, Grid } from "@mui/material";
+import router from "next/router";
+import { AppContext } from "pages/_app";
interface Iprops {
closeDialog: () => void;
@@ -18,13 +18,13 @@ export default function TwoFactorModalManageSection(props: Iprops) {
const warnTwoFactorDisable = async () => {
setDialogMessage({
- title: t('DISABLE_TWO_FACTOR'),
+ title: t("DISABLE_TWO_FACTOR"),
- content: t('DISABLE_TWO_FACTOR_MESSAGE'),
- close: { text: t('CANCEL') },
+ content: t("DISABLE_TWO_FACTOR_MESSAGE"),
+ close: { text: t("CANCEL") },
proceed: {
- variant: 'critical',
- text: t('DISABLE'),
+ variant: "critical",
+ text: t("DISABLE"),
action: twoFactorDisable,
},
});
@@ -40,7 +40,7 @@ export default function TwoFactorModalManageSection(props: Iprops) {
closeDialog();
} catch (e) {
setDialogMessage({
- title: t('TWO_FACTOR_DISABLE_FAILED'),
+ title: t("TWO_FACTOR_DISABLE_FAILED"),
close: {},
});
}
@@ -48,13 +48,13 @@ export default function TwoFactorModalManageSection(props: Iprops) {
const warnTwoFactorReconfigure = async () => {
setDialogMessage({
- title: t('UPDATE_TWO_FACTOR'),
+ title: t("UPDATE_TWO_FACTOR"),
- content: t('UPDATE_TWO_FACTOR_MESSAGE'),
- close: { text: t('CANCEL') },
+ content: t("UPDATE_TWO_FACTOR_MESSAGE"),
+ close: { text: t("CANCEL") },
proceed: {
- variant: 'accent',
- text: t('UPDATE'),
+ variant: "accent",
+ text: t("UPDATE"),
action: reconfigureTwoFactor,
},
});
@@ -72,16 +72,18 @@ export default function TwoFactorModalManageSection(props: Iprops) {
rowSpacing={1}
container
alignItems="center"
- justifyContent="center">
+ justifyContent="center"
+ >
<Grid item sm={9} xs={12}>
- {t('UPDATE_TWO_FACTOR_LABEL')}
+ {t("UPDATE_TWO_FACTOR_LABEL")}
</Grid>
<Grid item sm={3} xs={12}>
<Button
- color={'accent'}
+ color={"accent"}
onClick={warnTwoFactorReconfigure}
- size="large">
- {t('RECONFIGURE')}
+ size="large"
+ >
+ {t("RECONFIGURE")}
</Button>
</Grid>
</Grid>
@@ -89,17 +91,19 @@ export default function TwoFactorModalManageSection(props: Iprops) {
rowSpacing={1}
container
alignItems="center"
- justifyContent="center">
+ justifyContent="center"
+ >
<Grid item sm={9} xs={12}>
- {t('DISABLE_TWO_FACTOR_LABEL')}{' '}
+ {t("DISABLE_TWO_FACTOR_LABEL")}{" "}
</Grid>
<Grid item sm={3} xs={12}>
<Button
color="critical"
onClick={warnTwoFactorDisable}
- size="large">
- {t('DISABLE')}
+ size="large"
+ >
+ {t("DISABLE")}
</Button>
</Grid>
</Grid>
diff --git a/apps/photos/src/components/TwoFactor/Modal/Setup.tsx b/apps/photos/src/components/TwoFactor/Modal/Setup.tsx
index 4112f1c06f..dbe724b469 100644
--- a/apps/photos/src/components/TwoFactor/Modal/Setup.tsx
+++ b/apps/photos/src/components/TwoFactor/Modal/Setup.tsx
@@ -1,11 +1,10 @@
-import React from 'react';
-import LockIcon from '@mui/icons-material/Lock';
-import { PHOTOS_PAGES as PAGES } from '@ente/shared/constants/pages';
-import { useRouter } from 'next/router';
-import { t } from 'i18next';
+import { PHOTOS_PAGES as PAGES } from "@ente/shared/constants/pages";
+import LockIcon from "@mui/icons-material/Lock";
+import { t } from "i18next";
+import { useRouter } from "next/router";
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import { Button, Typography } from '@mui/material';
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import { Button, Typography } from "@mui/material";
interface Iprops {
closeDialog: () => void;
@@ -21,13 +20,14 @@ export default function TwoFactorModalSetupSection({ closeDialog }: Iprops) {
return (
<VerticallyCentered sx={{ mb: 2 }}>
<LockIcon sx={{ fontSize: (theme) => theme.spacing(5), mb: 2 }} />
- <Typography mb={4}>{t('TWO_FACTOR_INFO')}</Typography>
+ <Typography mb={4}>{t("TWO_FACTOR_INFO")}</Typography>
<Button
variant="contained"
color="accent"
size="large"
- onClick={redirectToTwoFactorSetup}>
- {t('ENABLE_TWO_FACTOR')}
+ onClick={redirectToTwoFactorSetup}
+ >
+ {t("ENABLE_TWO_FACTOR")}
</Button>
</VerticallyCentered>
);
diff --git a/apps/photos/src/components/TwoFactor/Modal/index.tsx b/apps/photos/src/components/TwoFactor/Modal/index.tsx
index c343f53b54..d4c5ebc3c7 100644
--- a/apps/photos/src/components/TwoFactor/Modal/index.tsx
+++ b/apps/photos/src/components/TwoFactor/Modal/index.tsx
@@ -1,16 +1,16 @@
-import { useEffect, useState } from 'react';
-import { getTwoFactorStatus } from 'services/userService';
-import { SetLoading } from 'types/gallery';
-import { getData, LS_KEYS, setData } from '@ente/shared/storage/localStorage';
-import { t } from 'i18next';
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
+import { t } from "i18next";
+import { useEffect, useState } from "react";
+import { getTwoFactorStatus } from "services/userService";
+import { SetLoading } from "types/gallery";
-import TwoFactorModalSetupSection from './Setup';
-import TwoFactorModalManageSection from './Manage';
-import { Dialog, DialogContent, styled } from '@mui/material';
-import DialogTitleWithCloseButton from '@ente/shared/components/DialogBox/TitleWithCloseButton';
+import DialogTitleWithCloseButton from "@ente/shared/components/DialogBox/TitleWithCloseButton";
+import { Dialog, DialogContent, styled } from "@mui/material";
+import TwoFactorModalManageSection from "./Manage";
+import TwoFactorModalSetupSection from "./Setup";
const TwoFactorDialog = styled(Dialog)(({ theme }) => ({
- '& .MuiDialogContent-root': {
+ "& .MuiDialogContent-root": {
padding: theme.spacing(2, 4),
},
}));
@@ -53,7 +53,7 @@ function TwoFactorModal(props: Props) {
return (
<TwoFactorDialog maxWidth="xs" open={props.show} onClose={props.onHide}>
<DialogTitleWithCloseButton onClose={props.onHide}>
- {t('TWO_FACTOR_AUTHENTICATION')}
+ {t("TWO_FACTOR_AUTHENTICATION")}
</DialogTitleWithCloseButton>
<DialogContent sx={{ px: 4 }}>
{isTwoFactorEnabled ? (
diff --git a/apps/photos/src/components/Upload/UploadButton.tsx b/apps/photos/src/components/Upload/UploadButton.tsx
index 7f9fba74bb..1b6842f027 100644
--- a/apps/photos/src/components/Upload/UploadButton.tsx
+++ b/apps/photos/src/components/Upload/UploadButton.tsx
@@ -1,13 +1,11 @@
-import React from 'react';
-import { ButtonProps, IconButton, styled } from '@mui/material';
-import FileUploadOutlinedIcon from '@mui/icons-material/FileUploadOutlined';
-import { Button } from '@mui/material';
-import { t } from 'i18next';
+import FileUploadOutlinedIcon from "@mui/icons-material/FileUploadOutlined";
+import { Button, ButtonProps, IconButton, styled } from "@mui/material";
+import { t } from "i18next";
-import uploadManager from 'services/upload/uploadManager';
-import { UploadTypeSelectorIntent } from 'types/gallery';
+import uploadManager from "services/upload/uploadManager";
+import { UploadTypeSelectorIntent } from "types/gallery";
-const Wrapper = styled('div')<{ $disableShrink: boolean }>`
+const Wrapper = styled("div")<{ $disableShrink: boolean }>`
display: flex;
align-items: center;
justify-content: center;
@@ -31,7 +29,7 @@ const Wrapper = styled('div')<{ $disableShrink: boolean }>`
interface Iprops {
openUploader: (intent?: UploadTypeSelectorIntent) => void;
text?: string;
- color?: ButtonProps['color'];
+ color?: ButtonProps["color"];
disableShrink?: boolean;
icon?: JSX.Element;
}
@@ -48,22 +46,25 @@ function UploadButton({
<Wrapper
$disableShrink={disableShrink}
style={{
- cursor: !uploadManager.shouldAllowNewUpload() && 'not-allowed',
- }}>
+ cursor: !uploadManager.shouldAllowNewUpload() && "not-allowed",
+ }}
+ >
<Button
- sx={{ whiteSpace: 'nowrap' }}
+ sx={{ whiteSpace: "nowrap" }}
onClick={onClickHandler}
disabled={!uploadManager.shouldAllowNewUpload()}
className="desktop-button"
- color={color ?? 'secondary'}
- startIcon={icon ?? <FileUploadOutlinedIcon />}>
- {text ?? t('UPLOAD')}
+ color={color ?? "secondary"}
+ startIcon={icon ?? <FileUploadOutlinedIcon />}
+ >
+ {text ?? t("UPLOAD")}
</Button>
<IconButton
onClick={onClickHandler}
disabled={!uploadManager.shouldAllowNewUpload()}
- className="mobile-button">
+ className="mobile-button"
+ >
{icon ?? <FileUploadOutlinedIcon />}
</IconButton>
</Wrapper>
diff --git a/apps/photos/src/components/Upload/UploadProgress/dialog.tsx b/apps/photos/src/components/Upload/UploadProgress/dialog.tsx
index 8593525fea..aa01477752 100644
--- a/apps/photos/src/components/Upload/UploadProgress/dialog.tsx
+++ b/apps/photos/src/components/Upload/UploadProgress/dialog.tsx
@@ -1,21 +1,21 @@
-import { Dialog, DialogContent, Link } from '@mui/material';
-import { t } from 'i18next';
+import { Dialog, DialogContent, Link } from "@mui/material";
+import { t } from "i18next";
-import { UPLOAD_STAGES, UPLOAD_RESULT } from 'constants/upload';
-import React, { useContext, useEffect, useState } from 'react';
-import { UploadProgressFooter } from './footer';
-import { UploadProgressHeader } from './header';
-import { InProgressSection } from './inProgressSection';
-import { ResultSection } from './resultSection';
-import { NotUploadSectionHeader } from './styledComponents';
-import UploadProgressContext from 'contexts/uploadProgress';
-import { dialogCloseHandler } from '@ente/shared/components/DialogBox/TitleWithCloseButton';
-import { APP_DOWNLOAD_URL } from '@ente/shared/constants/urls';
-import { Trans } from 'react-i18next';
+import { dialogCloseHandler } from "@ente/shared/components/DialogBox/TitleWithCloseButton";
+import { APP_DOWNLOAD_URL } from "@ente/shared/constants/urls";
+import { UPLOAD_RESULT, UPLOAD_STAGES } from "constants/upload";
+import UploadProgressContext from "contexts/uploadProgress";
+import { useContext, useEffect, useState } from "react";
+import { Trans } from "react-i18next";
+import { UploadProgressFooter } from "./footer";
+import { UploadProgressHeader } from "./header";
+import { InProgressSection } from "./inProgressSection";
+import { ResultSection } from "./resultSection";
+import { NotUploadSectionHeader } from "./styledComponents";
export function UploadProgressDialog() {
const { open, onClose, uploadStage, finishedUploads } = useContext(
- UploadProgressContext
+ UploadProgressContext,
);
const [hasUnUploadedFiles, setHasUnUploadedFiles] = useState(false);
@@ -44,7 +44,7 @@ export function UploadProgressDialog() {
{(uploadStage === UPLOAD_STAGES.UPLOADING ||
uploadStage === UPLOAD_STAGES.FINISH ||
uploadStage === UPLOAD_STAGES.EXTRACTING_METADATA) && (
- <DialogContent sx={{ '&&&': { px: 0 } }}>
+ <DialogContent sx={{ "&&&": { px: 0 } }}>
{(uploadStage === UPLOAD_STAGES.UPLOADING ||
uploadStage === UPLOAD_STAGES.EXTRACTING_METADATA) && (
<InProgressSection />
@@ -54,33 +54,33 @@ export function UploadProgressDialog() {
<>
<ResultSection
uploadResult={UPLOAD_RESULT.UPLOADED}
- sectionTitle={t('SUCCESSFUL_UPLOADS')}
+ sectionTitle={t("SUCCESSFUL_UPLOADS")}
/>
<ResultSection
uploadResult={
UPLOAD_RESULT.UPLOADED_WITH_STATIC_THUMBNAIL
}
sectionTitle={t(
- 'THUMBNAIL_GENERATION_FAILED_UPLOADS'
+ "THUMBNAIL_GENERATION_FAILED_UPLOADS",
)}
sectionInfo={t(
- 'THUMBNAIL_GENERATION_FAILED_INFO'
+ "THUMBNAIL_GENERATION_FAILED_INFO",
)}
/>
{uploadStage === UPLOAD_STAGES.FINISH &&
hasUnUploadedFiles && (
<NotUploadSectionHeader>
- {t('FILE_NOT_UPLOADED_LIST')}
+ {t("FILE_NOT_UPLOADED_LIST")}
</NotUploadSectionHeader>
)}
<ResultSection
uploadResult={UPLOAD_RESULT.BLOCKED}
- sectionTitle={t('BLOCKED_UPLOADS')}
+ sectionTitle={t("BLOCKED_UPLOADS")}
sectionInfo={
<Trans
- i18nKey={'ETAGS_BLOCKED'}
+ i18nKey={"ETAGS_BLOCKED"}
components={{
a: (
<Link
@@ -94,33 +94,33 @@ export function UploadProgressDialog() {
/>
<ResultSection
uploadResult={UPLOAD_RESULT.FAILED}
- sectionTitle={t('FAILED_UPLOADS')}
+ sectionTitle={t("FAILED_UPLOADS")}
/>
<ResultSection
uploadResult={UPLOAD_RESULT.ALREADY_UPLOADED}
- sectionTitle={t('SKIPPED_FILES')}
- sectionInfo={t('SKIPPED_INFO')}
+ sectionTitle={t("SKIPPED_FILES")}
+ sectionInfo={t("SKIPPED_INFO")}
/>
<ResultSection
uploadResult={
UPLOAD_RESULT.LARGER_THAN_AVAILABLE_STORAGE
}
sectionTitle={t(
- 'LARGER_THAN_AVAILABLE_STORAGE_UPLOADS'
+ "LARGER_THAN_AVAILABLE_STORAGE_UPLOADS",
)}
sectionInfo={t(
- 'LARGER_THAN_AVAILABLE_STORAGE_INFO'
+ "LARGER_THAN_AVAILABLE_STORAGE_INFO",
)}
/>
<ResultSection
uploadResult={UPLOAD_RESULT.UNSUPPORTED}
- sectionTitle={t('UNSUPPORTED_FILES')}
- sectionInfo={t('UNSUPPORTED_INFO')}
+ sectionTitle={t("UNSUPPORTED_FILES")}
+ sectionInfo={t("UNSUPPORTED_INFO")}
/>
<ResultSection
uploadResult={UPLOAD_RESULT.TOO_LARGE}
- sectionTitle={t('TOO_LARGE_UPLOADS')}
- sectionInfo={t('TOO_LARGE_INFO')}
+ sectionTitle={t("TOO_LARGE_UPLOADS")}
+ sectionInfo={t("TOO_LARGE_INFO")}
/>
</>
)}
diff --git a/apps/photos/src/components/Upload/UploadProgress/footer.tsx b/apps/photos/src/components/Upload/UploadProgress/footer.tsx
index cc45eb0c98..5a5bebd201 100644
--- a/apps/photos/src/components/Upload/UploadProgress/footer.tsx
+++ b/apps/photos/src/components/Upload/UploadProgress/footer.tsx
@@ -1,13 +1,13 @@
-import { Button, DialogActions } from '@mui/material';
-import { UPLOAD_STAGES, UPLOAD_RESULT } from 'constants/upload';
-import React, { useContext } from 'react';
-import { t } from 'i18next';
+import { Button, DialogActions } from "@mui/material";
+import { UPLOAD_RESULT, UPLOAD_STAGES } from "constants/upload";
+import { t } from "i18next";
+import { useContext } from "react";
-import UploadProgressContext from 'contexts/uploadProgress';
+import UploadProgressContext from "contexts/uploadProgress";
export function UploadProgressFooter() {
const { uploadStage, finishedUploads, retryFailed, onClose } = useContext(
- UploadProgressContext
+ UploadProgressContext,
);
return (
@@ -16,11 +16,11 @@ export function UploadProgressFooter() {
(finishedUploads?.get(UPLOAD_RESULT.FAILED)?.length > 0 ||
finishedUploads?.get(UPLOAD_RESULT.BLOCKED)?.length > 0 ? (
<Button variant="contained" fullWidth onClick={retryFailed}>
- {t('RETRY_FAILED')}
+ {t("RETRY_FAILED")}
</Button>
) : (
<Button variant="contained" fullWidth onClick={onClose}>
- {t('CLOSE')}
+ {t("CLOSE")}
</Button>
))}
</DialogActions>
diff --git a/apps/photos/src/components/Upload/UploadProgress/header.tsx b/apps/photos/src/components/Upload/UploadProgress/header.tsx
index 430790c89b..709c776a1d 100644
--- a/apps/photos/src/components/Upload/UploadProgress/header.tsx
+++ b/apps/photos/src/components/Upload/UploadProgress/header.tsx
@@ -1,6 +1,5 @@
-import React from 'react';
-import { UploadProgressBar } from './progressBar';
-import { UploadProgressTitle } from './title';
+import { UploadProgressBar } from "./progressBar";
+import { UploadProgressTitle } from "./title";
export function UploadProgressHeader() {
return (
diff --git a/apps/photos/src/components/Upload/UploadProgress/inProgressSection.tsx b/apps/photos/src/components/Upload/UploadProgress/inProgressSection.tsx
index 7186368047..128e280abb 100644
--- a/apps/photos/src/components/Upload/UploadProgress/inProgressSection.tsx
+++ b/apps/photos/src/components/Upload/UploadProgress/inProgressSection.tsx
@@ -1,18 +1,18 @@
-import React, { useContext } from 'react';
-import ItemList from 'components/ItemList';
-import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
-import { InProgressItemContainer } from './styledComponents';
+import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
+import ItemList from "components/ItemList";
+import UploadProgressContext from "contexts/uploadProgress";
+import { t } from "i18next";
+import { useContext } from "react";
import {
SectionInfo,
UploadProgressSection,
UploadProgressSectionContent,
UploadProgressSectionTitle,
-} from './section';
-import UploadProgressContext from 'contexts/uploadProgress';
-import { t } from 'i18next';
+} from "./section";
+import { InProgressItemContainer } from "./styledComponents";
-import { UPLOAD_STAGES } from 'constants/upload';
-import { CaptionedText } from 'components/CaptionedText';
+import { CaptionedText } from "components/CaptionedText";
+import { UPLOAD_STAGES } from "constants/upload";
export const InProgressSection = () => {
const { inProgressUploads, hasLivePhotos, uploadFileNames, uploadStage } =
@@ -25,7 +25,7 @@ export const InProgressSection = () => {
<span>{uploadFileNames.get(localFileID)}</span>
{uploadStage === UPLOAD_STAGES.UPLOADING && (
<>
- {' '}
+ {" "}
<span className="separator">{`-`}</span>
<span>{`${progress}%`}</span>
</>
@@ -48,15 +48,15 @@ export const InProgressSection = () => {
<CaptionedText
mainText={
uploadStage === UPLOAD_STAGES.EXTRACTING_METADATA
- ? t('INPROGRESS_METADATA_EXTRACTION')
- : t('INPROGRESS_UPLOADS')
+ ? t("INPROGRESS_METADATA_EXTRACTION")
+ : t("INPROGRESS_UPLOADS")
}
subText={String(inProgressUploads?.length ?? 0)}
/>
</UploadProgressSectionTitle>
<UploadProgressSectionContent>
{hasLivePhotos && (
- <SectionInfo>{t('LIVE_PHOTOS_DETECTED')}</SectionInfo>
+ <SectionInfo>{t("LIVE_PHOTOS_DETECTED")}</SectionInfo>
)}
<ItemList
items={fileList}
diff --git a/apps/photos/src/components/Upload/UploadProgress/index.tsx b/apps/photos/src/components/Upload/UploadProgress/index.tsx
index 641e22f533..8f16ef2d98 100644
--- a/apps/photos/src/components/Upload/UploadProgress/index.tsx
+++ b/apps/photos/src/components/Upload/UploadProgress/index.tsx
@@ -1,18 +1,18 @@
-import { UploadProgressDialog } from './dialog';
-import { MinimizedUploadProgress } from './minimized';
-import React, { useContext, useEffect, useState } from 'react';
+import { useContext, useEffect, useState } from "react";
+import { UploadProgressDialog } from "./dialog";
+import { MinimizedUploadProgress } from "./minimized";
-import { t } from 'i18next';
+import { t } from "i18next";
-import { UPLOAD_STAGES } from 'constants/upload';
-import { AppContext } from 'pages/_app';
+import { UPLOAD_STAGES } from "constants/upload";
+import UploadProgressContext from "contexts/uploadProgress";
+import { AppContext } from "pages/_app";
import {
- UploadFileNames,
- UploadCounter,
- SegregatedFinishedUploads,
InProgressUpload,
-} from 'types/upload/ui';
-import UploadProgressContext from 'contexts/uploadProgress';
+ SegregatedFinishedUploads,
+ UploadCounter,
+ UploadFileNames,
+} from "types/upload/ui";
interface Props {
open: boolean;
@@ -51,16 +51,16 @@ export default function UploadProgress({
function confirmCancelUpload() {
appContext.setDialogMessage({
- title: t('STOP_UPLOADS_HEADER'),
- content: t('STOP_ALL_UPLOADS_MESSAGE'),
+ title: t("STOP_UPLOADS_HEADER"),
+ content: t("STOP_ALL_UPLOADS_MESSAGE"),
proceed: {
- text: t('YES_STOP_UPLOADS'),
- variant: 'critical',
+ text: t("YES_STOP_UPLOADS"),
+ variant: "critical",
action: props.cancelUploads,
},
close: {
- text: t('NO'),
- variant: 'secondary',
+ text: t("NO"),
+ variant: "secondary",
action: () => {},
},
});
@@ -93,7 +93,8 @@ export default function UploadProgress({
hasLivePhotos,
expanded,
setExpanded,
- }}>
+ }}
+ >
{expanded ? <UploadProgressDialog /> : <MinimizedUploadProgress />}
</UploadProgressContext.Provider>
);
diff --git a/apps/photos/src/components/Upload/UploadProgress/minimized.tsx b/apps/photos/src/components/Upload/UploadProgress/minimized.tsx
index 1d860083ff..659a58bcde 100644
--- a/apps/photos/src/components/Upload/UploadProgress/minimized.tsx
+++ b/apps/photos/src/components/Upload/UploadProgress/minimized.tsx
@@ -1,18 +1,19 @@
-import { Snackbar, Paper } from '@mui/material';
-import React from 'react';
-import { UploadProgressHeader } from './header';
+import { Paper, Snackbar } from "@mui/material";
+import { UploadProgressHeader } from "./header";
export function MinimizedUploadProgress() {
return (
<Snackbar
open
anchorOrigin={{
- horizontal: 'right',
- vertical: 'bottom',
- }}>
+ horizontal: "right",
+ vertical: "bottom",
+ }}
+ >
<Paper
sx={{
- width: '360px',
- }}>
+ width: "360px",
+ }}
+ >
<UploadProgressHeader />
</Paper>
</Snackbar>
diff --git a/apps/photos/src/components/Upload/UploadProgress/progressBar.tsx b/apps/photos/src/components/Upload/UploadProgress/progressBar.tsx
index 43684eda61..6173829d7e 100644
--- a/apps/photos/src/components/Upload/UploadProgress/progressBar.tsx
+++ b/apps/photos/src/components/Upload/UploadProgress/progressBar.tsx
@@ -1,7 +1,7 @@
-import React, { useContext } from 'react';
-import { LinearProgress, Divider, Box } from '@mui/material';
-import { UPLOAD_STAGES } from 'constants/upload';
-import UploadProgressContext from 'contexts/uploadProgress';
+import { Box, Divider, LinearProgress } from "@mui/material";
+import { UPLOAD_STAGES } from "constants/upload";
+import UploadProgressContext from "contexts/uploadProgress";
+import { useContext } from "react";
export function UploadProgressBar() {
const { uploadStage, percentComplete } = useContext(UploadProgressContext);
@@ -13,8 +13,8 @@ export function UploadProgressBar() {
<>
<LinearProgress
sx={{
- height: '2px',
- backgroundColor: 'transparent',
+ height: "2px",
+ backgroundColor: "transparent",
}}
variant="determinate"
value={percentComplete}
diff --git a/apps/photos/src/components/Upload/UploadProgress/resultSection.tsx b/apps/photos/src/components/Upload/UploadProgress/resultSection.tsx
index 6149458b01..1be6ca8317 100644
--- a/apps/photos/src/components/Upload/UploadProgress/resultSection.tsx
+++ b/apps/photos/src/components/Upload/UploadProgress/resultSection.tsx
@@ -1,16 +1,16 @@
-import { useContext } from 'react';
-import ItemList from 'components/ItemList';
-import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
-import { ResultItemContainer } from './styledComponents';
-import { UPLOAD_RESULT } from 'constants/upload';
+import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
+import { CaptionedText } from "components/CaptionedText";
+import ItemList from "components/ItemList";
+import { UPLOAD_RESULT } from "constants/upload";
+import UploadProgressContext from "contexts/uploadProgress";
+import { useContext } from "react";
import {
SectionInfo,
UploadProgressSection,
UploadProgressSectionContent,
UploadProgressSectionTitle,
-} from './section';
-import UploadProgressContext from 'contexts/uploadProgress';
-import { CaptionedText } from 'components/CaptionedText';
+} from "./section";
+import { ResultItemContainer } from "./styledComponents";
export interface ResultSectionProps {
uploadResult: UPLOAD_RESULT;
@@ -19,7 +19,7 @@ export interface ResultSectionProps {
}
export const ResultSection = (props: ResultSectionProps) => {
const { finishedUploads, uploadFileNames } = useContext(
- UploadProgressContext
+ UploadProgressContext,
);
const fileList = finishedUploads.get(props.uploadResult);
diff --git a/apps/photos/src/components/Upload/UploadProgress/section.tsx b/apps/photos/src/components/Upload/UploadProgress/section.tsx
index 878c681de0..ebb4120824 100644
--- a/apps/photos/src/components/Upload/UploadProgress/section.tsx
+++ b/apps/photos/src/components/Upload/UploadProgress/section.tsx
@@ -1,34 +1,33 @@
-import { styled } from '@mui/material';
-import MuiAccordion, { AccordionProps } from '@mui/material/Accordion';
-import MuiAccordionSummary from '@mui/material/AccordionSummary';
-import MuiAccordionDetails from '@mui/material/AccordionDetails';
-import { Typography, TypographyProps } from '@mui/material';
+import { Typography, TypographyProps, styled } from "@mui/material";
+import MuiAccordion, { AccordionProps } from "@mui/material/Accordion";
+import MuiAccordionDetails from "@mui/material/AccordionDetails";
+import MuiAccordionSummary from "@mui/material/AccordionSummary";
export const UploadProgressSection = styled((props: AccordionProps) => (
<MuiAccordion disableGutters elevation={0} square {...props} />
))(({ theme }) => ({
borderTop: `1px solid ${theme.palette.divider}`,
- '&:last-child': {
+ "&:last-child": {
borderBottom: `1px solid ${theme.palette.divider}`,
},
- '&:before': {
- display: 'none',
+ "&:before": {
+ display: "none",
},
}));
export const UploadProgressSectionTitle = styled(MuiAccordionSummary)(() => ({
- backgroundColor: 'rgba(255, 255, 255, .05)',
+ backgroundColor: "rgba(255, 255, 255, .05)",
}));
export const UploadProgressSectionContent = styled(MuiAccordionDetails)(
({ theme }) => ({
padding: theme.spacing(2),
- })
+ }),
);
export const SectionInfo = (props: TypographyProps) => (
<Typography
- color={'text.muted'}
+ color={"text.muted"}
variant="small"
{...props}
sx={{ mb: 1 }}
diff --git a/apps/photos/src/components/Upload/UploadProgress/styledComponents.tsx b/apps/photos/src/components/Upload/UploadProgress/styledComponents.tsx
index c595a1dbcc..0eb28e144b 100644
--- a/apps/photos/src/components/Upload/UploadProgress/styledComponents.tsx
+++ b/apps/photos/src/components/Upload/UploadProgress/styledComponents.tsx
@@ -1,14 +1,14 @@
-import { styled } from '@mui/material';
-export const NotUploadSectionHeader = styled('div')(
+import { styled } from "@mui/material";
+export const NotUploadSectionHeader = styled("div")(
({ theme }) => `
text-align: center;
color: ${theme.colors.danger.A700};
border-bottom: 1px solid ${theme.colors.danger.A700};
margin:${theme.spacing(3, 2, 1)}
-`
+`,
);
-export const InProgressItemContainer = styled('div')`
+export const InProgressItemContainer = styled("div")`
display: inline-block;
& > span {
display: inline-block;
@@ -26,7 +26,7 @@ export const InProgressItemContainer = styled('div')`
}
`;
-export const ResultItemContainer = styled('div')`
+export const ResultItemContainer = styled("div")`
position: relative;
top: 5px;
display: inline-block;
diff --git a/apps/photos/src/components/Upload/UploadProgress/title.tsx b/apps/photos/src/components/Upload/UploadProgress/title.tsx
index e46b14e8c4..1b97b9b437 100644
--- a/apps/photos/src/components/Upload/UploadProgress/title.tsx
+++ b/apps/photos/src/components/Upload/UploadProgress/title.tsx
@@ -1,21 +1,21 @@
-import React, { useContext } from 'react';
-import Close from '@mui/icons-material/Close';
-import { DialogTitle, Box, Typography, Stack } from '@mui/material';
import {
IconButtonWithBG,
SpaceBetweenFlex,
-} from '@ente/shared/components/Container';
-import { UPLOAD_STAGES } from 'constants/upload';
-import { t } from 'i18next';
+} from "@ente/shared/components/Container";
+import Close from "@mui/icons-material/Close";
+import { Box, DialogTitle, Stack, Typography } from "@mui/material";
+import { UPLOAD_STAGES } from "constants/upload";
+import { t } from "i18next";
+import { useContext } from "react";
-import UploadProgressContext from 'contexts/uploadProgress';
-import UnfoldLessIcon from '@mui/icons-material/UnfoldLess';
-import UnfoldMoreIcon from '@mui/icons-material/UnfoldMore';
+import UnfoldLessIcon from "@mui/icons-material/UnfoldLess";
+import UnfoldMoreIcon from "@mui/icons-material/UnfoldMore";
+import UploadProgressContext from "contexts/uploadProgress";
const UploadProgressTitleText = ({ expanded }) => {
return (
- <Typography variant={expanded ? 'h2' : 'h3'}>
- {t('FILE_UPLOAD')}
+ <Typography variant={expanded ? "h2" : "h3"}>
+ {t("FILE_UPLOAD")}
</Typography>
);
};
@@ -24,7 +24,7 @@ function UploadProgressSubtitleText() {
const { uploadStage, uploadCounter } = useContext(UploadProgressContext);
return (
- <Typography color="text.muted" marginTop={'4px'}>
+ <Typography color="text.muted" marginTop={"4px"}>
{uploadStage === UPLOAD_STAGES.UPLOADING
? t(`UPLOAD_STAGE_MESSAGE.${uploadStage}`, { uploadCounter })
: uploadStage === UPLOAD_STAGES.EXTRACTING_METADATA
@@ -36,7 +36,7 @@ function UploadProgressSubtitleText() {
export function UploadProgressTitle() {
const { setExpanded, onClose, expanded } = useContext(
- UploadProgressContext
+ UploadProgressContext,
);
const toggleExpanded = () => setExpanded((expanded) => !expanded);
@@ -48,7 +48,7 @@ export function UploadProgressTitle() {
<UploadProgressSubtitleText />
</Box>
<Box>
- <Stack direction={'row'} spacing={1}>
+ <Stack direction={"row"} spacing={1}>
<IconButtonWithBG onClick={toggleExpanded}>
{expanded ? <UnfoldLessIcon /> : <UnfoldMoreIcon />}
</IconButtonWithBG>
diff --git a/apps/photos/src/components/Upload/UploadStrategyChoiceModal.tsx b/apps/photos/src/components/Upload/UploadStrategyChoiceModal.tsx
index b27ec5c584..4e773a3a82 100644
--- a/apps/photos/src/components/Upload/UploadStrategyChoiceModal.tsx
+++ b/apps/photos/src/components/Upload/UploadStrategyChoiceModal.tsx
@@ -1,13 +1,12 @@
-import { Button, Dialog, DialogContent, Typography } from '@mui/material';
import {
CenteredFlex,
SpaceBetweenFlex,
-} from '@ente/shared/components/Container';
+} from "@ente/shared/components/Container";
import DialogTitleWithCloseButton, {
dialogCloseHandler,
-} from '@ente/shared/components/DialogBox/TitleWithCloseButton';
-import React from 'react';
-import { t } from 'i18next';
+} from "@ente/shared/components/DialogBox/TitleWithCloseButton";
+import { Button, Dialog, DialogContent, Typography } from "@mui/material";
+import { t } from "i18next";
interface Props {
uploadToMultipleCollection: () => void;
@@ -27,12 +26,12 @@ function UploadStrategyChoiceModal({
return (
<Dialog open={props.open} onClose={handleClose}>
<DialogTitleWithCloseButton onClose={handleClose}>
- {t('MULTI_FOLDER_UPLOAD')}
+ {t("MULTI_FOLDER_UPLOAD")}
</DialogTitleWithCloseButton>
<DialogContent>
<CenteredFlex mb={1}>
<Typography color="text.muted">
- {t('UPLOAD_STRATEGY_CHOICE')}
+ {t("UPLOAD_STRATEGY_CHOICE")}
</Typography>
</CenteredFlex>
<SpaceBetweenFlex px={2}>
@@ -42,11 +41,12 @@ function UploadStrategyChoiceModal({
onClick={() => {
props.onClose();
uploadToSingleCollection();
- }}>
- {t('UPLOAD_STRATEGY_SINGLE_COLLECTION')}
+ }}
+ >
+ {t("UPLOAD_STRATEGY_SINGLE_COLLECTION")}
</Button>
- <strong>{t('OR')}</strong>
+ <strong>{t("OR")}</strong>
<Button
size="medium"
@@ -54,8 +54,9 @@ function UploadStrategyChoiceModal({
onClick={() => {
props.onClose();
uploadToMultipleCollection();
- }}>
- {t('UPLOAD_STRATEGY_COLLECTION_PER_FOLDER')}
+ }}
+ >
+ {t("UPLOAD_STRATEGY_COLLECTION_PER_FOLDER")}
</Button>
</SpaceBetweenFlex>
</DialogContent>
diff --git a/apps/photos/src/components/Upload/UploadTypeSelector/index.tsx b/apps/photos/src/components/Upload/UploadTypeSelector/index.tsx
index 56b8e11c38..c1e8fdfdfe 100644
--- a/apps/photos/src/components/Upload/UploadTypeSelector/index.tsx
+++ b/apps/photos/src/components/Upload/UploadTypeSelector/index.tsx
@@ -1,18 +1,18 @@
-import React, { useContext, useEffect, useRef } from 'react';
-import { t } from 'i18next';
+import { t } from "i18next";
+import { useContext, useEffect, useRef } from "react";
-import { default as FileUploadIcon } from '@mui/icons-material/ImageOutlined';
-import { default as FolderUploadIcon } from '@mui/icons-material/PermMediaOutlined';
-import GoogleIcon from '@mui/icons-material/Google';
import DialogTitleWithCloseButton, {
dialogCloseHandler,
-} from '@ente/shared/components/DialogBox/TitleWithCloseButton';
-import { Box, Dialog, Stack, Typography } from '@mui/material';
-import { PublicCollectionGalleryContext } from 'utils/publicCollectionGallery';
-import { isMobileOrTable } from 'utils/common/deviceDetection';
-import { UploadTypeSelectorIntent } from 'types/gallery';
-import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
-import ChevronRight from '@mui/icons-material/ChevronRight';
+} from "@ente/shared/components/DialogBox/TitleWithCloseButton";
+import ChevronRight from "@mui/icons-material/ChevronRight";
+import GoogleIcon from "@mui/icons-material/Google";
+import { default as FileUploadIcon } from "@mui/icons-material/ImageOutlined";
+import { default as FolderUploadIcon } from "@mui/icons-material/PermMediaOutlined";
+import { Box, Dialog, Stack, Typography } from "@mui/material";
+import { EnteMenuItem } from "components/Menu/EnteMenuItem";
+import { UploadTypeSelectorIntent } from "types/gallery";
+import { isMobileOrTable } from "utils/common/deviceDetection";
+import { PublicCollectionGalleryContext } from "utils/publicCollectionGallery";
interface Iprops {
onClose: () => void;
show: boolean;
@@ -30,7 +30,7 @@ export default function UploadTypeSelector({
uploadTypeSelectorIntent,
}: Iprops) {
const publicCollectionGalleryContext = useContext(
- PublicCollectionGalleryContext
+ PublicCollectionGalleryContext,
);
const directlyShowUploadFiles = useRef(isMobileOrTable());
@@ -50,20 +50,21 @@ export default function UploadTypeSelector({
open={show}
PaperProps={{
sx: (theme) => ({
- maxWidth: '375px',
+ maxWidth: "375px",
p: 1,
[theme.breakpoints.down(360)]: { p: 0 },
}),
}}
- onClose={dialogCloseHandler({ onClose })}>
+ onClose={dialogCloseHandler({ onClose })}
+ >
<DialogTitleWithCloseButton onClose={onClose}>
{uploadTypeSelectorIntent ===
UploadTypeSelectorIntent.collectPhotos
- ? t('SELECT_PHOTOS')
+ ? t("SELECT_PHOTOS")
: uploadTypeSelectorIntent ===
UploadTypeSelectorIntent.import
- ? t('IMPORT')
- : t('UPLOAD')}
+ ? t("IMPORT")
+ : t("UPLOAD")}
</DialogTitleWithCloseButton>
<Box p={1.5} pt={0.5}>
<Stack spacing={0.5}>
@@ -73,14 +74,14 @@ export default function UploadTypeSelector({
onClick={uploadFiles}
startIcon={<FileUploadIcon />}
endIcon={<ChevronRight />}
- label={t('UPLOAD_FILES')}
+ label={t("UPLOAD_FILES")}
/>
)}
<EnteMenuItem
onClick={uploadFolders}
startIcon={<FolderUploadIcon />}
endIcon={<ChevronRight />}
- label={t('UPLOAD_DIRS')}
+ label={t("UPLOAD_DIRS")}
/>
{uploadTypeSelectorIntent !==
@@ -89,12 +90,12 @@ export default function UploadTypeSelector({
onClick={uploadGoogleTakeoutZips}
startIcon={<GoogleIcon />}
endIcon={<ChevronRight />}
- label={t('UPLOAD_GOOGLE_TAKEOUT')}
+ label={t("UPLOAD_GOOGLE_TAKEOUT")}
/>
)}
</Stack>
<Typography p={1.5} pt={4} color="text.muted">
- {t('DRAG_AND_DROP_HINT')}
+ {t("DRAG_AND_DROP_HINT")}
</Typography>
</Box>
</Dialog>
diff --git a/apps/photos/src/components/Upload/Uploader.tsx b/apps/photos/src/components/Upload/Uploader.tsx
index 415841aa4a..8daeda5051 100644
--- a/apps/photos/src/components/Upload/Uploader.tsx
+++ b/apps/photos/src/components/Upload/Uploader.tsx
@@ -1,73 +1,74 @@
-import React, { useContext, useEffect, useRef, useState } from 'react';
+import { useContext, useEffect, useRef, useState } from "react";
-import { getLatestCollections } from 'services/collectionService';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
+import { t } from "i18next";
+import { Trans } from "react-i18next";
+import { getLatestCollections } from "services/collectionService";
-import UploadProgress from './UploadProgress';
+import UploadProgress from "./UploadProgress";
-import UploadStrategyChoiceModal from './UploadStrategyChoiceModal';
-import { SetCollectionNamerAttributes } from '../Collections/CollectionNamer';
+import ElectronAPIs from "@ente/shared/electron";
+import { CustomError } from "@ente/shared/error";
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import DiscFullIcon from "@mui/icons-material/DiscFull";
+import UserNameInputDialog from "components/UserNameInputDialog";
+import {
+ DEFAULT_IMPORT_SUGGESTION,
+ PICKED_UPLOAD_TYPE,
+ UPLOAD_STAGES,
+ UPLOAD_STRATEGY,
+} from "constants/upload";
+import isElectron from "is-electron";
+import { AppContext } from "pages/_app";
+import { GalleryContext } from "pages/gallery";
+import billingService from "services/billingService";
+import ImportService from "services/importService";
+import {
+ getPublicCollectionUID,
+ getPublicCollectionUploaderName,
+ savePublicCollectionUploaderName,
+} from "services/publicCollectionService";
+import uploadManager from "services/upload/uploadManager";
+import watchFolderService from "services/watchFolder/watchFolderService";
+import { NotificationAttributes } from "types/Notification";
+import { Collection } from "types/collection";
import {
CollectionSelectorIntent,
- SetCollections,
SetCollectionSelectorAttributes,
-} from 'types/gallery';
-import { GalleryContext } from 'pages/gallery';
-import { AppContext } from 'pages/_app';
-import { logError } from '@ente/shared/sentry';
-import uploadManager from 'services/upload/uploadManager';
-import ImportService from 'services/importService';
-import isElectron from 'is-electron';
-import { CustomError } from '@ente/shared/error';
-import { Collection } from 'types/collection';
-import { SetLoading, SetFiles } from 'types/gallery';
+ SetCollections,
+ SetFiles,
+ SetLoading,
+ UploadTypeSelectorIntent,
+} from "types/gallery";
import {
- ImportSuggestion,
ElectronFile,
FileWithCollection,
-} from 'types/upload';
-import { isCanvasBlocked } from 'utils/upload/isCanvasBlocked';
-import { downloadApp, waitAndRun } from 'utils/common';
-import watchFolderService from 'services/watchFolder/watchFolderService';
-import DiscFullIcon from '@mui/icons-material/DiscFull';
-import { NotificationAttributes } from 'types/Notification';
+ ImportSuggestion,
+} from "types/upload";
import {
- UploadFileNames,
- UploadCounter,
- SegregatedFinishedUploads,
InProgressUpload,
-} from 'types/upload/ui';
-import {
- DEFAULT_IMPORT_SUGGESTION,
- UPLOAD_STAGES,
- UPLOAD_STRATEGY,
- PICKED_UPLOAD_TYPE,
-} from 'constants/upload';
+ SegregatedFinishedUploads,
+ UploadCounter,
+ UploadFileNames,
+} from "types/upload/ui";
+import { getOrCreateAlbum } from "utils/collection";
+import { downloadApp, waitAndRun } from "utils/common";
+import { PublicCollectionGalleryContext } from "utils/publicCollectionGallery";
import {
getDownloadAppMessage,
getRootLevelFileWithFolderNotAllowMessage,
-} from 'utils/ui';
-import UploadTypeSelector from './UploadTypeSelector';
+} from "utils/ui";
import {
filterOutSystemFiles,
getImportSuggestion,
groupFilesBasedOnParentFolder,
-} from 'utils/upload';
-import billingService from 'services/billingService';
-import { addLogLine } from '@ente/shared/logging';
-import { PublicCollectionGalleryContext } from 'utils/publicCollectionGallery';
-import UserNameInputDialog from 'components/UserNameInputDialog';
-import {
- getPublicCollectionUID,
- getPublicCollectionUploaderName,
- savePublicCollectionUploaderName,
-} from 'services/publicCollectionService';
-import { UploadTypeSelectorIntent } from 'types/gallery';
-import { getOrCreateAlbum } from 'utils/collection';
-import ElectronAPIs from '@ente/shared/electron';
+} from "utils/upload";
+import { isCanvasBlocked } from "utils/upload/isCanvasBlocked";
+import { SetCollectionNamerAttributes } from "../Collections/CollectionNamer";
+import UploadStrategyChoiceModal from "./UploadStrategyChoiceModal";
+import UploadTypeSelector from "./UploadTypeSelector";
-const FIRST_ALBUM_NAME = 'My First Album';
+const FIRST_ALBUM_NAME = "My First Album";
interface Props {
syncWithRemote: (force?: boolean, silent?: boolean) => Promise<void>;
@@ -97,12 +98,12 @@ export default function Uploader(props: Props) {
const appContext = useContext(AppContext);
const galleryContext = useContext(GalleryContext);
const publicCollectionGalleryContext = useContext(
- PublicCollectionGalleryContext
+ PublicCollectionGalleryContext,
);
const [uploadProgressView, setUploadProgressView] = useState(false);
const [uploadStage, setUploadStage] = useState<UPLOAD_STAGES>(
- UPLOAD_STAGES.START
+ UPLOAD_STAGES.START,
);
const [uploadFileNames, setUploadFileNames] = useState<UploadFileNames>();
const [uploadCounter, setUploadCounter] = useState<UploadCounter>({
@@ -121,14 +122,14 @@ export default function Uploader(props: Props) {
const [userNameInputDialogView, setUserNameInputDialogView] =
useState(false);
const [importSuggestion, setImportSuggestion] = useState<ImportSuggestion>(
- DEFAULT_IMPORT_SUGGESTION
+ DEFAULT_IMPORT_SUGGESTION,
);
const [electronFiles, setElectronFiles] = useState<ElectronFile[]>(null);
const [webFiles, setWebFiles] = useState([]);
const toUploadFiles = useRef<File[] | ElectronFile[]>(null);
const isPendingDesktopUpload = useRef(false);
- const pendingDesktopUploadCollectionName = useRef<string>('');
+ const pendingDesktopUploadCollectionName = useRef<string>("");
// This is set when the user choses a type to upload from the upload type selector dialog
const pickedUploadType = useRef<PICKED_UPLOAD_TYPE>(null);
const zipPaths = useRef<string[]>(null);
@@ -173,7 +174,7 @@ export default function Uploader(props: Props) {
},
props.setFiles,
publicCollectionGalleryContext,
- appContext.isCFProxyDisabled
+ appContext.isCFProxyDisabled,
);
if (uploadManager.isUploadRunning()) {
setUploadProgressView(true);
@@ -183,16 +184,16 @@ export default function Uploader(props: Props) {
ImportService.getPendingUploads().then(
({ files: electronFiles, collectionName, type }) => {
addLogLine(
- `found pending desktop upload, resuming uploads`
+ `found pending desktop upload, resuming uploads`,
);
resumeDesktopUpload(type, electronFiles, collectionName);
- }
+ },
);
watchFolderService.init(
setElectronFiles,
setCollectionName,
props.syncWithRemote,
- appContext.setIsFolderSyncRunning
+ appContext.setIsFolderSyncRunning,
);
}
}, [
@@ -232,13 +233,13 @@ export default function Uploader(props: Props) {
// check and parse dropped files which are zip files
let electronFiles = [] as ElectronFile[];
for (const file of props.dragAndDropFiles) {
- if (file.name.endsWith('.zip')) {
+ if (file.name.endsWith(".zip")) {
const zipFiles =
await ElectronAPIs.getElectronFilesFromGoogleZip(
- (file as any).path
+ (file as any).path,
);
addLogLine(
- `zip file - ${file.name} contains ${zipFiles.length} files`
+ `zip file - ${file.name} contains ${zipFiles.length} files`,
);
electronFiles = [...electronFiles, ...zipFiles];
} else {
@@ -251,16 +252,16 @@ export default function Uploader(props: Props) {
// for now patching by type casting first to unknown and then to ElectronFile
// TODO: fix types and remove type cast
electronFiles.push(
- file as unknown as ElectronFile
+ file as unknown as ElectronFile,
);
}
}
addLogLine(
- `uploading dropped files from desktop app - ${electronFiles.length} files found`
+ `uploading dropped files from desktop app - ${electronFiles.length} files found`,
);
setElectronFiles(electronFiles);
} catch (e) {
- logError(e, 'failed to upload desktop dropped files');
+ logError(e, "failed to upload desktop dropped files");
setWebFiles(props.dragAndDropFiles);
}
};
@@ -285,26 +286,26 @@ export default function Uploader(props: Props) {
addLogLine(
`upload request type:${
electronFiles?.length > 0
- ? 'electronFiles'
+ ? "electronFiles"
: webFiles?.length > 0
- ? 'webFiles'
- : 'sharedFiles'
+ ? "webFiles"
+ : "sharedFiles"
} count ${
electronFiles?.length ??
webFiles?.length ??
appContext?.sharedFiles.length
- }`
+ }`,
);
if (uploadManager.isUploadRunning()) {
if (watchFolderService.isUploadRunning()) {
addLogLine(
- 'watchFolder upload was running, pausing it to run user upload'
+ "watchFolder upload was running, pausing it to run user upload",
);
// pause watch folder service on user upload
watchFolderService.pauseRunningSync();
} else {
addLogLine(
- 'an upload is already running, rejecting new upload request'
+ "an upload is already running, rejecting new upload request",
);
// no-op
// a user upload is already in progress
@@ -312,16 +313,16 @@ export default function Uploader(props: Props) {
}
}
if (isCanvasBlocked()) {
- addLogLine('canvas blocked, blocking upload');
+ addLogLine("canvas blocked, blocking upload");
appContext.setDialogMessage({
- title: t('CANVAS_BLOCKED_TITLE'),
+ title: t("CANVAS_BLOCKED_TITLE"),
content: <Trans i18nKey="CANVAS_BLOCKED_MESSAGE" />,
- close: { text: t('CLOSE') },
+ close: { text: t("CLOSE") },
proceed: {
- text: t('DOWNLOAD'),
+ text: t("DOWNLOAD"),
action: downloadApp,
- variant: 'accent',
+ variant: "accent",
},
});
return;
@@ -350,7 +351,7 @@ export default function Uploader(props: Props) {
const importSuggestion = getImportSuggestion(
pickedUploadType.current,
- toUploadFiles.current
+ toUploadFiles.current,
);
setImportSuggestion(importSuggestion);
@@ -358,7 +359,7 @@ export default function Uploader(props: Props) {
importSuggestion,
props.isFirstUpload,
pickedUploadType.current,
- publicCollectionGalleryContext.accessedThroughSharedURL
+ publicCollectionGalleryContext.accessedThroughSharedURL,
);
pickedUploadType.current = null;
props.setLoading(false);
@@ -368,7 +369,7 @@ export default function Uploader(props: Props) {
const resumeDesktopUpload = async (
type: PICKED_UPLOAD_TYPE,
electronFiles: ElectronFile[],
- collectionName: string
+ collectionName: string,
) => {
if (electronFiles && electronFiles?.length > 0) {
isPendingDesktopUpload.current = true;
@@ -387,11 +388,11 @@ export default function Uploader(props: Props) {
const uploadFilesToExistingCollection = async (
collection: Collection,
- uploaderName?: string
+ uploaderName?: string,
) => {
try {
addLogLine(
- `upload file to an existing collection name:${collection.name}, collectionID:${collection.id}`
+ `upload file to an existing collection name:${collection.name}, collectionID:${collection.id}`,
);
await preCollectionCreationAction();
const filesWithCollectionToUpload: FileWithCollection[] =
@@ -403,20 +404,20 @@ export default function Uploader(props: Props) {
await waitInQueueAndUploadFiles(
filesWithCollectionToUpload,
[collection],
- uploaderName
+ uploaderName,
);
} catch (e) {
- logError(e, 'Failed to upload files to existing collections');
+ logError(e, "Failed to upload files to existing collections");
}
};
const uploadFilesToNewCollections = async (
strategy: UPLOAD_STRATEGY,
- collectionName?: string
+ collectionName?: string,
) => {
try {
addLogLine(
- `upload file to an new collections strategy:${strategy} ,collectionName:${collectionName}`
+ `upload file to an new collections strategy:${strategy} ,collectionName:${collectionName}`,
);
await preCollectionCreationAction();
let filesWithCollectionToUpload: FileWithCollection[] = [];
@@ -428,15 +429,15 @@ export default function Uploader(props: Props) {
if (strategy === UPLOAD_STRATEGY.SINGLE_COLLECTION) {
collectionNameToFilesMap.set(
collectionName,
- toUploadFiles.current
+ toUploadFiles.current,
);
} else {
collectionNameToFilesMap = groupFilesBasedOnParentFolder(
- toUploadFiles.current
+ toUploadFiles.current,
);
}
addLogLine(
- `upload collections - [${[...collectionNameToFilesMap.keys()]}]`
+ `upload collections - [${[...collectionNameToFilesMap.keys()]}]`,
);
try {
const existingCollection = await getLatestCollections();
@@ -447,7 +448,7 @@ export default function Uploader(props: Props) {
] of collectionNameToFilesMap) {
const collection = await getOrCreateAlbum(
collectionName,
- existingCollection
+ existingCollection,
);
collections.push(collection);
props.setCollections([
@@ -465,29 +466,29 @@ export default function Uploader(props: Props) {
}
} catch (e) {
closeUploadProgress();
- logError(e, 'Failed to create album');
+ logError(e, "Failed to create album");
appContext.setDialogMessage({
- title: t('ERROR'),
+ title: t("ERROR"),
- close: { variant: 'critical' },
- content: t('CREATE_ALBUM_FAILED'),
+ close: { variant: "critical" },
+ content: t("CREATE_ALBUM_FAILED"),
});
throw e;
}
await waitInQueueAndUploadFiles(
filesWithCollectionToUpload,
- collections
+ collections,
);
toUploadFiles.current = null;
} catch (e) {
- logError(e, 'Failed to upload files to new collections');
+ logError(e, "Failed to upload files to new collections");
}
};
const waitInQueueAndUploadFiles = async (
filesWithCollectionToUploadIn: FileWithCollection[],
collections: Collection[],
- uploaderName?: string
+ uploaderName?: string,
) => {
const currentPromise = currentUploadPromise.current;
currentUploadPromise.current = waitAndRun(
@@ -496,8 +497,8 @@ export default function Uploader(props: Props) {
await uploadFiles(
filesWithCollectionToUploadIn,
collections,
- uploaderName
- )
+ uploaderName,
+ ),
);
await currentUploadPromise.current;
};
@@ -517,10 +518,10 @@ export default function Uploader(props: Props) {
const uploadFiles = async (
filesWithCollectionToUploadIn: FileWithCollection[],
collections: Collection[],
- uploaderName?: string
+ uploaderName?: string,
) => {
try {
- addLogLine('uploadFiles called');
+ addLogLine("uploadFiles called");
preUploadAction();
if (
isElectron() &&
@@ -531,22 +532,22 @@ export default function Uploader(props: Props) {
if (zipPaths.current) {
ElectronAPIs.setToUploadFiles(
PICKED_UPLOAD_TYPE.ZIPS,
- zipPaths.current
+ zipPaths.current,
);
zipPaths.current = null;
}
ElectronAPIs.setToUploadFiles(
PICKED_UPLOAD_TYPE.FILES,
filesWithCollectionToUploadIn.map(
- ({ file }) => (file as ElectronFile).path
- )
+ ({ file }) => (file as ElectronFile).path,
+ ),
);
}
const shouldCloseUploadProgress =
await uploadManager.queueFilesForUpload(
filesWithCollectionToUploadIn,
collections,
- uploaderName
+ uploaderName,
);
if (shouldCloseUploadProgress) {
closeUploadProgress();
@@ -555,7 +556,7 @@ export default function Uploader(props: Props) {
if (watchFolderService.isUploadRunning()) {
await watchFolderService.allFileUploadsDone(
filesWithCollectionToUploadIn,
- collections
+ collections,
);
} else if (watchFolderService.isSyncPaused()) {
// resume the service after user upload is done
@@ -563,7 +564,7 @@ export default function Uploader(props: Props) {
}
}
} catch (err) {
- logError(err, 'failed to upload files');
+ logError(err, "failed to upload files");
showUserFacingError(err.message);
closeUploadProgress();
} finally {
@@ -573,7 +574,7 @@ export default function Uploader(props: Props) {
const retryFailed = async () => {
try {
- addLogLine('user retrying failed upload');
+ addLogLine("user retrying failed upload");
const filesWithCollections =
uploadManager.getFailedFilesWithCollections();
const uploaderName = uploadManager.getUploaderName();
@@ -581,10 +582,10 @@ export default function Uploader(props: Props) {
await uploadManager.queueFilesForUpload(
filesWithCollections.files,
filesWithCollections.collections,
- uploaderName
+ uploaderName,
);
} catch (err) {
- logError(err, 'retry failed files failed');
+ logError(err, "retry failed files failed");
showUserFacingError(err.message);
closeUploadProgress();
} finally {
@@ -599,25 +600,25 @@ export default function Uploader(props: Props) {
return props.showSessionExpiredMessage();
case CustomError.SUBSCRIPTION_EXPIRED:
notification = {
- variant: 'critical',
- subtext: t('SUBSCRIPTION_EXPIRED'),
- message: t('RENEW_NOW'),
+ variant: "critical",
+ subtext: t("SUBSCRIPTION_EXPIRED"),
+ message: t("RENEW_NOW"),
onClick: () => billingService.redirectToCustomerPortal(),
};
break;
case CustomError.STORAGE_QUOTA_EXCEEDED:
notification = {
- variant: 'critical',
- subtext: t('STORAGE_QUOTA_EXCEEDED'),
- message: t('UPGRADE_NOW'),
+ variant: "critical",
+ subtext: t("STORAGE_QUOTA_EXCEEDED"),
+ message: t("UPGRADE_NOW"),
onClick: () => galleryContext.showPlanSelectorModal(),
startIcon: <DiscFullIcon />,
};
break;
default:
notification = {
- variant: 'critical',
- message: t('UNKNOWN_ERROR'),
+ variant: "critical",
+ message: t("UNKNOWN_ERROR"),
onClick: () => null,
};
}
@@ -627,14 +628,14 @@ export default function Uploader(props: Props) {
const uploadToSingleNewCollection = (collectionName: string) => {
uploadFilesToNewCollections(
UPLOAD_STRATEGY.SINGLE_COLLECTION,
- collectionName
+ collectionName,
);
};
const showCollectionCreateModal = (suggestedName: string) => {
props.setCollectionNamerAttributes({
- title: t('CREATE_COLLECTION'),
- buttonText: t('CREATE'),
+ title: t("CREATE_COLLECTION"),
+ buttonText: t("CREATE"),
autoFilledName: suggestedName,
callback: uploadToSingleNewCollection,
});
@@ -644,15 +645,17 @@ export default function Uploader(props: Props) {
importSuggestion: ImportSuggestion,
isFirstUpload: boolean,
pickedUploadType: PICKED_UPLOAD_TYPE,
- accessedThroughSharedURL?: boolean
+ accessedThroughSharedURL?: boolean,
) => {
try {
if (accessedThroughSharedURL) {
addLogLine(
- `uploading files to pulbic collection - ${props.uploadCollection.name} - ${props.uploadCollection.id}`
+ `uploading files to pulbic collection - ${props.uploadCollection.name} - ${props.uploadCollection.id}`,
);
const uploaderName = await getPublicCollectionUploaderName(
- getPublicCollectionUID(publicCollectionGalleryContext.token)
+ getPublicCollectionUID(
+ publicCollectionGalleryContext.token,
+ ),
);
uploaderNameRef.current = uploaderName;
showUserNameInputDialog();
@@ -662,27 +665,27 @@ export default function Uploader(props: Props) {
isPendingDesktopUpload.current = false;
if (pendingDesktopUploadCollectionName.current) {
addLogLine(
- `upload pending files to collection - ${pendingDesktopUploadCollectionName.current}`
+ `upload pending files to collection - ${pendingDesktopUploadCollectionName.current}`,
);
uploadFilesToNewCollections(
UPLOAD_STRATEGY.SINGLE_COLLECTION,
- pendingDesktopUploadCollectionName.current
+ pendingDesktopUploadCollectionName.current,
);
pendingDesktopUploadCollectionName.current = null;
} else {
addLogLine(
- `pending upload - strategy - "multiple collections" `
+ `pending upload - strategy - "multiple collections" `,
);
uploadFilesToNewCollections(
- UPLOAD_STRATEGY.COLLECTION_PER_FOLDER
+ UPLOAD_STRATEGY.COLLECTION_PER_FOLDER,
);
}
return;
}
if (isElectron() && pickedUploadType === PICKED_UPLOAD_TYPE.ZIPS) {
- addLogLine('uploading zip files');
+ addLogLine("uploading zip files");
uploadFilesToNewCollections(
- UPLOAD_STRATEGY.COLLECTION_PER_FOLDER
+ UPLOAD_STRATEGY.COLLECTION_PER_FOLDER,
);
return;
}
@@ -714,7 +717,7 @@ export default function Uploader(props: Props) {
intent: CollectionSelectorIntent.upload,
});
} catch (e) {
- logError(e, 'handleCollectionCreationAndUpload failed');
+ logError(e, "handleCollectionCreationAndUpload failed");
}
};
@@ -732,7 +735,7 @@ export default function Uploader(props: Props) {
}
if (files?.length > 0) {
addLogLine(
- ` desktop upload for type:${type} and fileCount: ${files?.length} requested`
+ ` desktop upload for type:${type} and fileCount: ${files?.length} requested`,
);
setElectronFiles(files);
props.closeUploadTypeSelector();
@@ -768,23 +771,23 @@ export default function Uploader(props: Props) {
const handlePublicUpload = async (
uploaderName: string,
- skipSave?: boolean
+ skipSave?: boolean,
) => {
try {
if (!skipSave) {
savePublicCollectionUploaderName(
getPublicCollectionUID(
- publicCollectionGalleryContext.token
+ publicCollectionGalleryContext.token,
),
- uploaderName
+ uploaderName,
);
}
await uploadFilesToExistingCollection(
props.uploadCollection,
- uploaderName
+ uploaderName,
);
} catch (e) {
- logError(e, 'public upload failed ');
+ logError(e, "public upload failed ");
}
};
@@ -795,7 +798,7 @@ export default function Uploader(props: Props) {
const handleUploadToMultipleCollections = () => {
if (importSuggestion.hasRootLevelFileWithFolder) {
appContext.setDialogMessage(
- getRootLevelFileWithFolderNotAllowMessage()
+ getRootLevelFileWithFolderNotAllowMessage(),
);
return;
}
diff --git a/apps/photos/src/components/UploadSelectorInputs.tsx b/apps/photos/src/components/UploadSelectorInputs.tsx
index 3e754ffd59..1b110d532b 100644
--- a/apps/photos/src/components/UploadSelectorInputs.tsx
+++ b/apps/photos/src/components/UploadSelectorInputs.tsx
@@ -1,5 +1,3 @@
-import React from 'react';
-
export default function UploadSelectorInputs({
getDragAndDropInputProps,
getFileSelectorInputProps,
diff --git a/apps/photos/src/components/UserNameInputDialog.tsx b/apps/photos/src/components/UserNameInputDialog.tsx
index 358387e185..b089cb35d1 100644
--- a/apps/photos/src/components/UserNameInputDialog.tsx
+++ b/apps/photos/src/components/UserNameInputDialog.tsx
@@ -1,9 +1,8 @@
-import React from 'react';
-import DialogBox from '@ente/shared/components/DialogBox/';
-import AutoAwesomeOutlinedIcon from '@mui/icons-material/AutoAwesomeOutlined';
-import { Typography } from '@mui/material';
-import SingleInputForm from '@ente/shared/components/SingleInputForm';
-import { t } from 'i18next';
+import DialogBox from "@ente/shared/components/DialogBox/";
+import SingleInputForm from "@ente/shared/components/SingleInputForm";
+import AutoAwesomeOutlinedIcon from "@mui/icons-material/AutoAwesomeOutlined";
+import { Typography } from "@mui/material";
+import { t } from "i18next";
export default function UserNameInputDialog({
open,
@@ -22,18 +21,19 @@ export default function UserNameInputDialog({
open={open}
onClose={onClose}
attributes={{
- title: t('ENTER_NAME'),
+ title: t("ENTER_NAME"),
icon: <AutoAwesomeOutlinedIcon />,
- }}>
- <Typography color={'text.muted'} pb={1}>
- {t('PUBLIC_UPLOADER_NAME_MESSAGE')}
+ }}
+ >
+ <Typography color={"text.muted"} pb={1}>
+ {t("PUBLIC_UPLOADER_NAME_MESSAGE")}
</Typography>
<SingleInputForm
hiddenLabel
initialValue={uploaderName}
callback={handleSubmit}
- placeholder={t('NAME_PLACEHOLDER')}
- buttonText={t('add_photos', { count: toUploadFilesCount ?? 0 })}
+ placeholder={t("NAME_PLACEHOLDER")}
+ buttonText={t("add_photos", { count: toUploadFilesCount ?? 0 })}
fieldType="text"
blockButton
secondaryButtonAction={onClose}
diff --git a/apps/photos/src/components/WatchFolder/index.tsx b/apps/photos/src/components/WatchFolder/index.tsx
index 0ce5c4be20..71c8b30ff3 100644
--- a/apps/photos/src/components/WatchFolder/index.tsx
+++ b/apps/photos/src/components/WatchFolder/index.tsx
@@ -1,18 +1,17 @@
-import { MappingList } from './mappingList';
-import React, { useContext, useEffect, useState } from 'react';
-import { Button, Dialog, DialogContent, Stack } from '@mui/material';
-import watchFolderService from 'services/watchFolder/watchFolderService';
-import { WatchMapping } from 'types/watchFolder';
-import { AppContext } from 'pages/_app';
-import { t } from 'i18next';
+import { Button, Dialog, DialogContent, Stack } from "@mui/material";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext, useEffect, useState } from "react";
+import watchFolderService from "services/watchFolder/watchFolderService";
+import { WatchMapping } from "types/watchFolder";
+import { MappingList } from "./mappingList";
-import DialogTitleWithCloseButton from '@ente/shared/components/DialogBox/TitleWithCloseButton';
-import UploadStrategyChoiceModal from 'components/Upload/UploadStrategyChoiceModal';
-import { UPLOAD_STRATEGY } from 'constants/upload';
-import { getImportSuggestion } from 'utils/upload';
-import ElectronAPIs from '@ente/shared/electron';
-import { PICKED_UPLOAD_TYPE } from 'constants/upload';
-import isElectron from 'is-electron';
+import DialogTitleWithCloseButton from "@ente/shared/components/DialogBox/TitleWithCloseButton";
+import ElectronAPIs from "@ente/shared/electron";
+import UploadStrategyChoiceModal from "components/Upload/UploadStrategyChoiceModal";
+import { PICKED_UPLOAD_TYPE, UPLOAD_STRATEGY } from "constants/upload";
+import isElectron from "is-electron";
+import { getImportSuggestion } from "utils/upload";
interface Iprops {
open: boolean;
@@ -21,7 +20,7 @@ interface Iprops {
export default function WatchFolder({ open, onClose }: Iprops) {
const [mappings, setMappings] = useState<WatchMapping[]>([]);
- const [inputFolderPath, setInputFolderPath] = useState('');
+ const [inputFolderPath, setInputFolderPath] = useState("");
const [choiceModalOpen, setChoiceModalOpen] = useState(false);
const appContext = useContext(AppContext);
@@ -45,7 +44,7 @@ export default function WatchFolder({ open, onClose }: Iprops) {
const handleFolderDrop = async (folders: FileList) => {
for (let i = 0; i < folders.length; i++) {
const folder: any = folders[i];
- const path = (folder.path as string).replace(/\\/g, '/');
+ const path = (folder.path as string).replace(/\\/g, "/");
if (await watchFolderService.isFolder(path)) {
await addFolderForWatching(path);
}
@@ -57,7 +56,7 @@ export default function WatchFolder({ open, onClose }: Iprops) {
const files = await ElectronAPIs.getDirFiles(path);
const analysisResult = getImportSuggestion(
PICKED_UPLOAD_TYPE.FOLDERS,
- files
+ files,
);
if (analysisResult.hasNestedFolders) {
setChoiceModalOpen(true);
@@ -79,15 +78,15 @@ export default function WatchFolder({ open, onClose }: Iprops) {
const handleAddWatchMapping = async (
uploadStrategy: UPLOAD_STRATEGY,
- folderPath?: string
+ folderPath?: string,
) => {
folderPath = folderPath || inputFolderPath;
await watchFolderService.addWatchMapping(
- folderPath.substring(folderPath.lastIndexOf('/') + 1),
+ folderPath.substring(folderPath.lastIndexOf("/") + 1),
folderPath,
- uploadStrategy
+ uploadStrategy,
);
- setInputFolderPath('');
+ setInputFolderPath("");
setMappings(watchFolderService.getWatchMappings());
};
@@ -113,14 +112,16 @@ export default function WatchFolder({ open, onClose }: Iprops) {
<Dialog
open={open}
onClose={onClose}
- PaperProps={{ sx: { height: '448px', maxWidth: '414px' } }}>
+ PaperProps={{ sx: { height: "448px", maxWidth: "414px" } }}
+ >
<DialogTitleWithCloseButton
onClose={onClose}
- sx={{ '&&&': { padding: '32px 16px 16px 24px' } }}>
- {t('WATCHED_FOLDERS')}
+ sx={{ "&&&": { padding: "32px 16px 16px 24px" } }}
+ >
+ {t("WATCHED_FOLDERS")}
</DialogTitleWithCloseButton>
<DialogContent sx={{ flex: 1 }}>
- <Stack spacing={1} p={1.5} height={'100%'}>
+ <Stack spacing={1} p={1.5} height={"100%"}>
<MappingList
mappings={mappings}
handleRemoveWatchMapping={handleRemoveWatchMapping}
@@ -128,13 +129,15 @@ export default function WatchFolder({ open, onClose }: Iprops) {
<Button
fullWidth
color="accent"
- onClick={handleAddFolderClick}>
+ onClick={handleAddFolderClick}
+ >
<span>+</span>
<span
style={{
- marginLeft: '8px',
- }}></span>
- {t('ADD_FOLDER')}
+ marginLeft: "8px",
+ }}
+ ></span>
+ {t("ADD_FOLDER")}
</Button>
</Stack>
</DialogContent>
diff --git a/apps/photos/src/components/WatchFolder/mappingEntry/entryHeading.tsx b/apps/photos/src/components/WatchFolder/mappingEntry/entryHeading.tsx
index 9034944d75..b34e4277ff 100644
--- a/apps/photos/src/components/WatchFolder/mappingEntry/entryHeading.tsx
+++ b/apps/photos/src/components/WatchFolder/mappingEntry/entryHeading.tsx
@@ -1,9 +1,9 @@
-import React, { useContext } from 'react';
-import { CircularProgress, Typography } from '@mui/material';
-import watchFolderService from 'services/watchFolder/watchFolderService';
-import { AppContext } from 'pages/_app';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import { WatchMapping } from 'types/watchFolder';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import { CircularProgress, Typography } from "@mui/material";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
+import watchFolderService from "services/watchFolder/watchFolderService";
+import { WatchMapping } from "types/watchFolder";
interface Iprops {
mapping: WatchMapping;
diff --git a/apps/photos/src/components/WatchFolder/mappingEntry/index.tsx b/apps/photos/src/components/WatchFolder/mappingEntry/index.tsx
index e5b16a6b10..8193946995 100644
--- a/apps/photos/src/components/WatchFolder/mappingEntry/index.tsx
+++ b/apps/photos/src/components/WatchFolder/mappingEntry/index.tsx
@@ -1,19 +1,19 @@
-import { EntryContainer } from '../styledComponents';
-import React from 'react';
-import { Tooltip, Typography } from '@mui/material';
import {
HorizontalFlex,
SpaceBetweenFlex,
-} from '@ente/shared/components/Container';
-import { WatchMapping } from 'types/watchFolder';
-import { AppContext } from 'pages/_app';
-import FolderOpenIcon from '@mui/icons-material/FolderOpen';
-import FolderCopyOutlinedIcon from '@mui/icons-material/FolderCopyOutlined';
-import { t } from 'i18next';
+} from "@ente/shared/components/Container";
+import FolderCopyOutlinedIcon from "@mui/icons-material/FolderCopyOutlined";
+import FolderOpenIcon from "@mui/icons-material/FolderOpen";
+import { Tooltip, Typography } from "@mui/material";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import React from "react";
+import { WatchMapping } from "types/watchFolder";
+import { EntryContainer } from "../styledComponents";
-import MappingEntryOptions from './mappingEntryOptions';
-import { EntryHeading } from './entryHeading';
-import { UPLOAD_STRATEGY } from 'constants/upload';
+import { UPLOAD_STRATEGY } from "constants/upload";
+import { EntryHeading } from "./entryHeading";
+import MappingEntryOptions from "./mappingEntryOptions";
interface Iprops {
mapping: WatchMapping;
@@ -29,16 +29,16 @@ export function MappingEntry({ mapping, handleRemoveMapping }: Iprops) {
const confirmStopWatching = () => {
appContext.setDialogMessage({
- title: t('STOP_WATCHING_FOLDER'),
- content: t('STOP_WATCHING_DIALOG_MESSAGE'),
+ title: t("STOP_WATCHING_FOLDER"),
+ content: t("STOP_WATCHING_DIALOG_MESSAGE"),
close: {
- text: t('CANCEL'),
- variant: 'secondary',
+ text: t("CANCEL"),
+ variant: "secondary",
},
proceed: {
action: stopWatching,
- text: t('YES_STOP'),
- variant: 'critical',
+ text: t("YES_STOP"),
+ variant: "critical",
},
});
};
@@ -48,11 +48,11 @@ export function MappingEntry({ mapping, handleRemoveMapping }: Iprops) {
<HorizontalFlex>
{mapping &&
mapping.uploadStrategy === UPLOAD_STRATEGY.SINGLE_COLLECTION ? (
- <Tooltip title={t('UPLOADED_TO_SINGLE_COLLECTION')}>
+ <Tooltip title={t("UPLOADED_TO_SINGLE_COLLECTION")}>
<FolderOpenIcon />
</Tooltip>
) : (
- <Tooltip title={t('UPLOADED_TO_SEPARATE_COLLECTIONS')}>
+ <Tooltip title={t("UPLOADED_TO_SEPARATE_COLLECTIONS")}>
<FolderCopyOutlinedIcon />
</Tooltip>
)}
diff --git a/apps/photos/src/components/WatchFolder/mappingEntry/mappingEntryOptions.tsx b/apps/photos/src/components/WatchFolder/mappingEntry/mappingEntryOptions.tsx
index 3b8610f616..4f3cdc56d1 100644
--- a/apps/photos/src/components/WatchFolder/mappingEntry/mappingEntryOptions.tsx
+++ b/apps/photos/src/components/WatchFolder/mappingEntry/mappingEntryOptions.tsx
@@ -1,10 +1,9 @@
-import React from 'react';
-import { t } from 'i18next';
+import { t } from "i18next";
-import DoNotDisturbOutlinedIcon from '@mui/icons-material/DoNotDisturbOutlined';
-import MoreHorizIcon from '@mui/icons-material/MoreHoriz';
-import OverflowMenu from '@ente/shared/components/OverflowMenu/menu';
-import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';
+import OverflowMenu from "@ente/shared/components/OverflowMenu/menu";
+import { OverflowMenuOption } from "@ente/shared/components/OverflowMenu/option";
+import DoNotDisturbOutlinedIcon from "@mui/icons-material/DoNotDisturbOutlined";
+import MoreHorizIcon from "@mui/icons-material/MoreHoriz";
interface Iprops {
confirmStopWatching: () => void;
@@ -19,13 +18,15 @@ export default function MappingEntryOptions({ confirmStopWatching }: Iprops) {
theme.colors.background.elevated2,
},
}}
- ariaControls={'watch-mapping-option'}
- triggerButtonIcon={<MoreHorizIcon />}>
+ ariaControls={"watch-mapping-option"}
+ triggerButtonIcon={<MoreHorizIcon />}
+ >
<OverflowMenuOption
color="critical"
onClick={confirmStopWatching}
- startIcon={<DoNotDisturbOutlinedIcon />}>
- {t('STOP_WATCHING')}
+ startIcon={<DoNotDisturbOutlinedIcon />}
+ >
+ {t("STOP_WATCHING")}
</OverflowMenuOption>
</OverflowMenu>
);
diff --git a/apps/photos/src/components/WatchFolder/mappingList/index.tsx b/apps/photos/src/components/WatchFolder/mappingList/index.tsx
index 940059c7c6..f2c7b781c7 100644
--- a/apps/photos/src/components/WatchFolder/mappingList/index.tsx
+++ b/apps/photos/src/components/WatchFolder/mappingList/index.tsx
@@ -1,8 +1,7 @@
-import React from 'react';
-import { WatchMapping } from 'types/watchFolder';
-import { MappingEntry } from '../mappingEntry';
-import { NoMappingsContent } from './noMappingsContent/noMappingsContent';
-import { MappingsContainer } from '../styledComponents';
+import { WatchMapping } from "types/watchFolder";
+import { MappingEntry } from "../mappingEntry";
+import { MappingsContainer } from "../styledComponents";
+import { NoMappingsContent } from "./noMappingsContent/noMappingsContent";
interface Iprops {
mappings: WatchMapping[];
handleRemoveWatchMapping: (value: WatchMapping) => void;
diff --git a/apps/photos/src/components/WatchFolder/mappingList/noMappingsContent/checkmarkIcon.tsx b/apps/photos/src/components/WatchFolder/mappingList/noMappingsContent/checkmarkIcon.tsx
index 6317363290..aedd79404a 100644
--- a/apps/photos/src/components/WatchFolder/mappingList/noMappingsContent/checkmarkIcon.tsx
+++ b/apps/photos/src/components/WatchFolder/mappingList/noMappingsContent/checkmarkIcon.tsx
@@ -1,13 +1,12 @@
-import React from 'react';
-import CheckIcon from '@mui/icons-material/Check';
+import CheckIcon from "@mui/icons-material/Check";
export function CheckmarkIcon() {
return (
<CheckIcon
fontSize="small"
sx={{
- display: 'inline',
- fontSize: '15px',
+ display: "inline",
+ fontSize: "15px",
color: (theme) => theme.palette.secondary.main,
}}
diff --git a/apps/photos/src/components/WatchFolder/mappingList/noMappingsContent/noMappingsContent.tsx b/apps/photos/src/components/WatchFolder/mappingList/noMappingsContent/noMappingsContent.tsx
index ec29e0a76b..a5af6aff9d 100644
--- a/apps/photos/src/components/WatchFolder/mappingList/noMappingsContent/noMappingsContent.tsx
+++ b/apps/photos/src/components/WatchFolder/mappingList/noMappingsContent/noMappingsContent.tsx
@@ -1,31 +1,30 @@
-import { Stack, Typography } from '@mui/material';
-import React from 'react';
-import { t } from 'i18next';
+import { Stack, Typography } from "@mui/material";
+import { t } from "i18next";
-import { NoMappingsContainer } from '../../styledComponents';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import { CheckmarkIcon } from './checkmarkIcon';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import { NoMappingsContainer } from "../../styledComponents";
+import { CheckmarkIcon } from "./checkmarkIcon";
export function NoMappingsContent() {
return (
<NoMappingsContainer>
<Stack spacing={1}>
- <Typography variant="large" fontWeight={'bold'}>
- {t('NO_FOLDERS_ADDED')}
+ <Typography variant="large" fontWeight={"bold"}>
+ {t("NO_FOLDERS_ADDED")}
</Typography>
- <Typography py={0.5} variant={'small'} color="text.muted">
- {t('FOLDERS_AUTOMATICALLY_MONITORED')}
+ <Typography py={0.5} variant={"small"} color="text.muted">
+ {t("FOLDERS_AUTOMATICALLY_MONITORED")}
</Typography>
- <Typography variant={'small'} color="text.muted">
+ <Typography variant={"small"} color="text.muted">
<FlexWrapper gap={1}>
<CheckmarkIcon />
- {t('UPLOAD_NEW_FILES_TO_ENTE')}
+ {t("UPLOAD_NEW_FILES_TO_ENTE")}
</FlexWrapper>
</Typography>
- <Typography variant={'small'} color="text.muted">
+ <Typography variant={"small"} color="text.muted">
<FlexWrapper gap={1}>
<CheckmarkIcon />
- {t('REMOVE_DELETED_FILES_FROM_ENTE')}
+ {t("REMOVE_DELETED_FILES_FROM_ENTE")}
</FlexWrapper>
</Typography>
</Stack>
diff --git a/apps/photos/src/components/WatchFolder/styledComponents.tsx b/apps/photos/src/components/WatchFolder/styledComponents.tsx
index beac009db4..d507bbaa85 100644
--- a/apps/photos/src/components/WatchFolder/styledComponents.tsx
+++ b/apps/photos/src/components/WatchFolder/styledComponents.tsx
@@ -1,23 +1,23 @@
-import { Box } from '@mui/material';
-import { styled } from '@mui/material/styles';
-import { VerticallyCentered } from '@ente/shared/components/Container';
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import { Box } from "@mui/material";
+import { styled } from "@mui/material/styles";
export const MappingsContainer = styled(Box)(() => ({
- height: '278px',
- overflow: 'auto',
- '&::-webkit-scrollbar': {
- width: '4px',
+ height: "278px",
+ overflow: "auto",
+ "&::-webkit-scrollbar": {
+ width: "4px",
},
}));
export const NoMappingsContainer = styled(VerticallyCentered)({
- textAlign: 'left',
- alignItems: 'flex-start',
- marginBottom: '32px',
+ textAlign: "left",
+ alignItems: "flex-start",
+ marginBottom: "32px",
});
export const EntryContainer = styled(Box)({
- marginLeft: '12px',
- marginRight: '6px',
- marginBottom: '12px',
+ marginLeft: "12px",
+ marginRight: "6px",
+ marginBottom: "12px",
});
diff --git a/apps/photos/src/components/icons/ObjectIcon.tsx b/apps/photos/src/components/icons/ObjectIcon.tsx
index 466b5a46f8..9971cd395a 100644
--- a/apps/photos/src/components/icons/ObjectIcon.tsx
+++ b/apps/photos/src/components/icons/ObjectIcon.tsx
@@ -1,12 +1,11 @@
-import React from 'react';
-
export default function ObjectIcon(props) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
height={props.height}
viewBox={props.viewBox}
- width={props.width}>
+ width={props.width}
+ >
<path d="M11.499 12.03v11.971l-10.5-5.603v-11.835l10.5 5.467zm11.501 6.368l-10.501 5.602v-11.968l10.501-5.404v11.77zm-16.889-15.186l10.609 5.524-4.719 2.428-10.473-5.453 4.583-2.499zm16.362 2.563l-4.664 2.4-10.641-5.54 4.831-2.635 10.474 5.775z" />
</svg>
);
@@ -15,5 +14,5 @@ export default function ObjectIcon(props) {
ObjectIcon.defaultProps = {
height: 20,
width: 20,
- viewBox: '0 0 24 24',
+ viewBox: "0 0 24 24",
};
diff --git a/apps/photos/src/components/icons/TextIcon.tsx b/apps/photos/src/components/icons/TextIcon.tsx
index d273354f0b..62d37fbe28 100644
--- a/apps/photos/src/components/icons/TextIcon.tsx
+++ b/apps/photos/src/components/icons/TextIcon.tsx
@@ -1,12 +1,11 @@
-import React from 'react';
-
export default function TextIcon(props) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
height={props.height}
viewBox={props.viewBox}
- width={props.width}>
+ width={props.width}
+ >
<path d="M22 0h-20v6h1.999c0-1.174.397-3 2.001-3h4v16.874c0 1.174-.825 2.126-2 2.126h-1v2h9.999v-2h-.999c-1.174 0-2-.952-2-2.126v-16.874h4c1.649 0 2.02 1.826 2.02 3h1.98v-6z" />
</svg>
);
@@ -15,5 +14,5 @@ export default function TextIcon(props) {
TextIcon.defaultProps = {
height: 16,
width: 16,
- viewBox: '0 0 28 28',
+ viewBox: "0 0 28 28",
};
diff --git a/apps/photos/src/components/icons/UnPinIcon.tsx b/apps/photos/src/components/icons/UnPinIcon.tsx
index 9bf28639f7..da50e0a1a0 100644
--- a/apps/photos/src/components/icons/UnPinIcon.tsx
+++ b/apps/photos/src/components/icons/UnPinIcon.tsx
@@ -1,4 +1,4 @@
-import SvgIcon from '@mui/material/SvgIcon';
+import SvgIcon from "@mui/material/SvgIcon";
export const UnPinIcon = (props) => {
return (
@@ -8,7 +8,8 @@ export const UnPinIcon = (props) => {
viewBox="0 -960 960 960"
shape-rendering="geometricPrecision"
text-rendering="geometricPrecision"
- {...props}>
+ {...props}
+ >
<defs>
<linearGradient
id="eNi9tomYy273-fill"
@@ -18,7 +19,8 @@ export const UnPinIcon = (props) => {
y2="0.5"
spreadMethod="pad"
gradientUnits="objectBoundingBox"
- gradientTransform="translate(0 0)">
+ gradientTransform="translate(0 0)"
+ >
<stop
id="eNi9tomYy273-fill-0"
offset="100%"
diff --git a/apps/photos/src/components/ml-debug/index.tsx b/apps/photos/src/components/ml-debug/index.tsx
index 3e7cb71f22..a5b53a6847 100644
--- a/apps/photos/src/components/ml-debug/index.tsx
+++ b/apps/photos/src/components/ml-debug/index.tsx
@@ -1,4 +1,3 @@
-import React from 'react';
// import dynamic from 'next/dynamic';
// const MLDebugWithNoSSR = dynamic(
diff --git a/apps/photos/src/components/pages/dedupe/SelectedFileOptions.tsx b/apps/photos/src/components/pages/dedupe/SelectedFileOptions.tsx
index d4b7709e09..fad14f1649 100644
--- a/apps/photos/src/components/pages/dedupe/SelectedFileOptions.tsx
+++ b/apps/photos/src/components/pages/dedupe/SelectedFileOptions.tsx
@@ -1,14 +1,14 @@
-import { FluidContainer } from '@ente/shared/components/Container';
-import { SelectionBar } from '@ente/shared/components/Navbar/SelectionBar';
-import { useContext } from 'react';
-import { Box, IconButton, Tooltip } from '@mui/material';
-import { AppContext } from 'pages/_app';
-import CloseIcon from '@mui/icons-material/Close';
-import BackButton from '@mui/icons-material/ArrowBackOutlined';
-import DeleteIcon from '@mui/icons-material/Delete';
-import { getTrashFilesMessage } from 'utils/ui';
-import { t } from 'i18next';
-import { formatNumber } from 'utils/number/format';
+import { FluidContainer } from "@ente/shared/components/Container";
+import { SelectionBar } from "@ente/shared/components/Navbar/SelectionBar";
+import BackButton from "@mui/icons-material/ArrowBackOutlined";
+import CloseIcon from "@mui/icons-material/Close";
+import DeleteIcon from "@mui/icons-material/Delete";
+import { Box, IconButton, Tooltip } from "@mui/material";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
+import { formatNumber } from "utils/number/format";
+import { getTrashFilesMessage } from "utils/ui";
interface IProps {
deleteFileHelper: () => void;
@@ -41,10 +41,10 @@ export default function DeduplicateOptions({
</IconButton>
)}
<Box ml={1.5}>
- {formatNumber(count)} {t('SELECTED')}
+ {formatNumber(count)} {t("SELECTED")}
</Box>
</FluidContainer>
- <Tooltip title={t('DELETE')}>
+ <Tooltip title={t("DELETE")}>
<IconButton onClick={trashHandler}>
<DeleteIcon />
</IconButton>
diff --git a/apps/photos/src/components/pages/gallery/Avatar.tsx b/apps/photos/src/components/pages/gallery/Avatar.tsx
index 323508dd76..d3bbcb6df7 100644
--- a/apps/photos/src/components/pages/gallery/Avatar.tsx
+++ b/apps/photos/src/components/pages/gallery/Avatar.tsx
@@ -1,9 +1,9 @@
-import React, { useState, useContext, useLayoutEffect } from 'react';
-import { EnteFile } from 'types/file';
-import { GalleryContext } from 'pages/gallery';
-import { styled } from '@mui/material';
-import { useTheme } from '@mui/material/styles';
-import { logError } from '@ente/shared/sentry';
+import { logError } from "@ente/shared/sentry";
+import { styled } from "@mui/material";
+import { useTheme } from "@mui/material/styles";
+import { GalleryContext } from "pages/gallery";
+import React, { useContext, useLayoutEffect, useState } from "react";
+import { EnteFile } from "types/file";
interface AvatarProps {
file?: EnteFile;
@@ -11,9 +11,9 @@ interface AvatarProps {
opacity?: number;
}
-const PUBLIC_COLLECTED_FILES_AVATAR_COLOR_CODE = '#000000';
+const PUBLIC_COLLECTED_FILES_AVATAR_COLOR_CODE = "#000000";
-const AvatarBase = styled('div')<{
+const AvatarBase = styled("div")<{
colorCode: string;
size: number;
opacity: number;
@@ -21,7 +21,7 @@ const AvatarBase = styled('div')<{
width: ${({ size }) => `${size}px`};
height: ${({ size }) => `${size}px`};
background-color: ${({ colorCode, opacity }) =>
- `${colorCode}${opacity === 100 ? '' : opacity ?? 95}`};
+ `${colorCode}${opacity === 100 ? "" : opacity ?? 95}`};
border-radius: 50%;
display: flex;
justify-content: center;
@@ -35,8 +35,8 @@ const Avatar: React.FC<AvatarProps> = ({ file, email, opacity }) => {
const { userIDToEmailMap, user } = useContext(GalleryContext);
const theme = useTheme();
- const [colorCode, setColorCode] = useState('');
- const [userLetter, setUserLetter] = useState('');
+ const [colorCode, setColorCode] = useState("");
+ const [userLetter, setUserLetter] = useState("");
useLayoutEffect(() => {
try {
@@ -47,7 +47,7 @@ const Avatar: React.FC<AvatarProps> = ({ file, email, opacity }) => {
// getting email from in-memory id-email map
const email = userIDToEmailMap.get(file.ownerID);
if (!email) {
- logError(Error(), 'email not found in userIDToEmailMap');
+ logError(Error(), "email not found in userIDToEmailMap");
return;
}
const colorIndex =
@@ -60,7 +60,7 @@ const Avatar: React.FC<AvatarProps> = ({ file, email, opacity }) => {
if (!uploaderName) {
logError(
Error(),
- 'uploaderName not found in file.pubMagicMetadata.data'
+ "uploaderName not found in file.pubMagicMetadata.data",
);
return;
}
@@ -68,7 +68,7 @@ const Avatar: React.FC<AvatarProps> = ({ file, email, opacity }) => {
setColorCode(PUBLIC_COLLECTED_FILES_AVATAR_COLOR_CODE);
}
} catch (err) {
- logError(err, 'AvatarIcon.tsx - useLayoutEffect file failed');
+ logError(err, "AvatarIcon.tsx - useLayoutEffect file failed");
}
}, [file]);
@@ -84,7 +84,7 @@ const Avatar: React.FC<AvatarProps> = ({ file, email, opacity }) => {
}
const id = Array.from(userIDToEmailMap.keys()).find(
- (key) => userIDToEmailMap.get(key) === email
+ (key) => userIDToEmailMap.get(key) === email,
);
if (!id) {
logError(Error(), `ID not found for email: ${email}`);
@@ -95,7 +95,7 @@ const Avatar: React.FC<AvatarProps> = ({ file, email, opacity }) => {
setUserLetter(email[0].toUpperCase());
setColorCode(colorCode);
} catch (err) {
- logError(err, 'AvatarIcon.tsx - useLayoutEffect email failed');
+ logError(err, "AvatarIcon.tsx - useLayoutEffect email failed");
}
}, [email]);
diff --git a/apps/photos/src/components/pages/gallery/AvatarGroup.tsx b/apps/photos/src/components/pages/gallery/AvatarGroup.tsx
index 84021a356f..df733fdded 100644
--- a/apps/photos/src/components/pages/gallery/AvatarGroup.tsx
+++ b/apps/photos/src/components/pages/gallery/AvatarGroup.tsx
@@ -1,31 +1,31 @@
-import { styled } from '@mui/material';
-import NumberAvatar from '@mui/material/Avatar';
-import Avatar from './Avatar';
-import { Collection } from 'types/collection';
+import { styled } from "@mui/material";
+import NumberAvatar from "@mui/material/Avatar";
+import { Collection } from "types/collection";
+import Avatar from "./Avatar";
-const AvatarContainer = styled('div')({
- position: 'relative',
- display: 'flex',
- alignItems: 'center',
+const AvatarContainer = styled("div")({
+ position: "relative",
+ display: "flex",
+ alignItems: "center",
marginLeft: -5,
});
-const AvatarContainerOuter = styled('div')({
- position: 'relative',
- display: 'flex',
- alignItems: 'center',
+const AvatarContainerOuter = styled("div")({
+ position: "relative",
+ display: "flex",
+ alignItems: "center",
marginLeft: 8,
});
const AvatarCounter = styled(NumberAvatar)({
height: 20,
width: 20,
fontSize: 10,
- color: '#fff',
+ color: "#fff",
});
const SHAREE_AVATAR_LIMIT = 6;
-const AvatarGroup = ({ sharees }: { sharees: Collection['sharees'] }) => {
+const AvatarGroup = ({ sharees }: { sharees: Collection["sharees"] }) => {
const hasShareesOverLimit = sharees?.length > SHAREE_AVATAR_LIMIT;
const countOfShareesOverLimit = sharees?.length - SHAREE_AVATAR_LIMIT;
diff --git a/apps/photos/src/components/pages/gallery/LinkButton.tsx b/apps/photos/src/components/pages/gallery/LinkButton.tsx
index ea8e7901ee..79578ddb70 100644
--- a/apps/photos/src/components/pages/gallery/LinkButton.tsx
+++ b/apps/photos/src/components/pages/gallery/LinkButton.tsx
@@ -1,5 +1,5 @@
-import { ButtonProps, Link, LinkProps } from '@mui/material';
-import React, { FC } from 'react';
+import { ButtonProps, Link, LinkProps } from "@mui/material";
+import React, { FC } from "react";
export type LinkButtonProps = React.PropsWithChildren<{
onClick: () => void;
@@ -7,7 +7,7 @@ export type LinkButtonProps = React.PropsWithChildren<{
style?: React.CSSProperties;
}>;
-const LinkButton: FC<LinkProps<'button', { color?: ButtonProps['color'] }>> = ({
+const LinkButton: FC<LinkProps<"button", { color?: ButtonProps["color"] }>> = ({
children,
sx,
color,
@@ -17,17 +17,18 @@ const LinkButton: FC<LinkProps<'button', { color?: ButtonProps['color'] }>> = ({
<Link
component="button"
sx={{
- color: 'text.base',
- textDecoration: 'underline rgba(255, 255, 255, 0.4)',
+ color: "text.base",
+ textDecoration: "underline rgba(255, 255, 255, 0.4)",
paddingBottom: 0.5,
- '&:hover': {
+ "&:hover": {
color: `${color}.main`,
textDecoration: `underline `,
textDecorationColor: `${color}.main`,
},
...sx,
}}
- {...props}>
+ {...props}
+ >
{children}
</Link>
);
diff --git a/apps/photos/src/components/pages/gallery/Navbar.tsx b/apps/photos/src/components/pages/gallery/Navbar.tsx
index b873f0777e..4a710faa81 100644
--- a/apps/photos/src/components/pages/gallery/Navbar.tsx
+++ b/apps/photos/src/components/pages/gallery/Navbar.tsx
@@ -1,16 +1,16 @@
-import React from 'react';
-import NavbarBase from '@ente/shared/components/Navbar/base';
-import SidebarToggler from '@ente/shared/components/Navbar/SidebarToggler';
-import SearchBar from 'components/Search/SearchBar';
-import { Collection } from 'types/collection';
-import { EnteFile } from 'types/file';
-import { UpdateSearch } from 'types/search';
-import UploadButton from 'components/Upload/UploadButton';
-import { IconButton, Typography } from '@mui/material';
-import ArrowBack from '@mui/icons-material/ArrowBack';
-import { FlexWrapper, HorizontalFlex } from '@ente/shared/components/Container';
-import { t } from 'i18next';
-import { AppContext } from 'pages/_app';
+import { FlexWrapper, HorizontalFlex } from "@ente/shared/components/Container";
+import SidebarToggler from "@ente/shared/components/Navbar/SidebarToggler";
+import NavbarBase from "@ente/shared/components/Navbar/base";
+import ArrowBack from "@mui/icons-material/ArrowBack";
+import { IconButton, Typography } from "@mui/material";
+import SearchBar from "components/Search/SearchBar";
+import UploadButton from "components/Upload/UploadButton";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import React from "react";
+import { Collection } from "types/collection";
+import { EnteFile } from "types/file";
+import { UpdateSearch } from "types/search";
interface Iprops {
openSidebar: () => void;
@@ -38,20 +38,22 @@ export function GalleryNavbar({
const appContext = React.useContext(AppContext);
return (
<NavbarBase
- sx={{ background: 'transparent', position: 'absolute' }}
- isMobile={appContext.isMobile}>
+ sx={{ background: "transparent", position: "absolute" }}
+ isMobile={appContext.isMobile}
+ >
{isInHiddenSection ? (
<HorizontalFlex
- gap={'24px'}
+ gap={"24px"}
sx={{
- width: '100%',
+ width: "100%",
background: (theme) => theme.palette.background.default,
- }}>
+ }}
+ >
<IconButton onClick={exitHiddenSection}>
<ArrowBack />
</IconButton>
<FlexWrapper>
- <Typography>{t('HIDDEN')}</Typography>
+ <Typography>{t("HIDDEN")}</Typography>
</FlexWrapper>
</HorizontalFlex>
) : (
diff --git a/apps/photos/src/components/pages/gallery/OptionIcon.tsx b/apps/photos/src/components/pages/gallery/OptionIcon.tsx
index 4269d09639..0d7d3e8124 100644
--- a/apps/photos/src/components/pages/gallery/OptionIcon.tsx
+++ b/apps/photos/src/components/pages/gallery/OptionIcon.tsx
@@ -1,6 +1,5 @@
-import React from 'react';
-import { styled } from '@mui/material';
-export const OptionIconWrapper = styled('div')`
+import { styled } from "@mui/material";
+export const OptionIconWrapper = styled("div")`
display: inline-block;
opacity: 0;
font-weight: bold;
@@ -15,13 +14,15 @@ const OptionIcon = ({ onClick }: Props) => (
onClick();
e.stopPropagation();
}}
- style={{ marginBottom: '2px' }}>
+ style={{ marginBottom: "2px" }}
+ >
<svg
xmlns="http://www.w3.org/2000/svg"
height="20px"
width="24px"
viewBox="0 0 24 24"
- fill="#000000">
+ fill="#000000"
+ >
<path d="M0 0h24v24H0V0z" fill="none" />
<path
fill="#666"
diff --git a/apps/photos/src/components/pages/gallery/PlanSelector/card/free.tsx b/apps/photos/src/components/pages/gallery/PlanSelector/card/free.tsx
index 0e81557b3d..a2ac1090b7 100644
--- a/apps/photos/src/components/pages/gallery/PlanSelector/card/free.tsx
+++ b/apps/photos/src/components/pages/gallery/PlanSelector/card/free.tsx
@@ -1,13 +1,12 @@
-import { Stack } from '@mui/material';
-import Box from '@mui/material/Box';
-import Typography from '@mui/material/Typography';
-import React from 'react';
-import { t } from 'i18next';
-import { PeriodToggler } from '../periodToggler';
-import Plans from '../plans';
-import { hasAddOnBonus } from 'utils/billing';
-import { BFAddOnRow } from '../plans/BfAddOnRow';
-import { ManageSubscription } from '../manageSubscription';
+import { Stack } from "@mui/material";
+import Box from "@mui/material/Box";
+import Typography from "@mui/material/Typography";
+import { t } from "i18next";
+import { hasAddOnBonus } from "utils/billing";
+import { ManageSubscription } from "../manageSubscription";
+import { PeriodToggler } from "../periodToggler";
+import Plans from "../plans";
+import { BFAddOnRow } from "../plans/BfAddOnRow";
export default function FreeSubscriptionPlanSelectorCard({
plans,
@@ -21,8 +20,8 @@ export default function FreeSubscriptionPlanSelectorCard({
}) {
return (
<>
- <Typography variant="h3" fontWeight={'bold'}>
- {t('CHOOSE_PLAN')}
+ <Typography variant="h3" fontWeight={"bold"}>
+ {t("CHOOSE_PLAN")}
</Typography>
<Box>
@@ -33,7 +32,7 @@ export default function FreeSubscriptionPlanSelectorCard({
togglePeriod={togglePeriod}
/>
<Typography variant="small" mt={0.5} color="text.muted">
- {t('TWO_MONTHS_FREE')}
+ {t("TWO_MONTHS_FREE")}
</Typography>
</Box>
<Plans
diff --git a/apps/photos/src/components/pages/gallery/PlanSelector/card/index.tsx b/apps/photos/src/components/pages/gallery/PlanSelector/card/index.tsx
index e76e2f9332..7bafa04037 100644
--- a/apps/photos/src/components/pages/gallery/PlanSelector/card/index.tsx
+++ b/apps/photos/src/components/pages/gallery/PlanSelector/card/index.tsx
@@ -1,34 +1,34 @@
-import React, { useContext, useEffect, useMemo, useState } from 'react';
-import { Plan } from 'types/billing';
+import { SUPPORT_EMAIL } from "@ente/shared/constants/urls";
+import { useLocalState } from "@ente/shared/hooks/useLocalState";
+import { logError } from "@ente/shared/sentry";
+import { LS_KEYS } from "@ente/shared/storage/localStorage";
+import { Link, Stack } from "@mui/material";
+import { PLAN_PERIOD } from "constants/gallery";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { GalleryContext } from "pages/gallery";
+import { useContext, useEffect, useMemo, useState } from "react";
+import { Trans } from "react-i18next";
+import billingService from "services/billingService";
+import { Plan } from "types/billing";
+import { SetLoading } from "types/gallery";
import {
- isUserSubscribedPlan,
- isSubscriptionCancelled,
- updateSubscription,
- hasStripeSubscription,
- isOnFreePlan,
- planForSubscription,
- hasMobileSubscription,
getLocalUserSubscription,
+ hasMobileSubscription,
hasPaidSubscription,
+ hasStripeSubscription,
+ isOnFreePlan,
isSubscriptionActive,
-} from 'utils/billing';
-import { reverseString } from 'utils/common';
-import { GalleryContext } from 'pages/gallery';
-import billingService from 'services/billingService';
-import { SetLoading } from 'types/gallery';
-import { logError } from '@ente/shared/sentry';
-import { AppContext } from 'pages/_app';
-import { Link, Stack } from '@mui/material';
-import { useLocalState } from '@ente/shared/hooks/useLocalState';
-import { LS_KEYS } from '@ente/shared/storage/localStorage';
-import { getLocalUserDetails } from 'utils/user';
-import { PLAN_PERIOD } from 'constants/gallery';
-import FreeSubscriptionPlanSelectorCard from './free';
-import PaidSubscriptionPlanSelectorCard from './paid';
-import { isPartOfFamily, getTotalFamilyUsage } from 'utils/user/family';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
-import { SUPPORT_EMAIL } from '@ente/shared/constants/urls';
+ isSubscriptionCancelled,
+ isUserSubscribedPlan,
+ planForSubscription,
+ updateSubscription,
+} from "utils/billing";
+import { reverseString } from "utils/common";
+import { getLocalUserDetails } from "utils/user";
+import { getTotalFamilyUsage, isPartOfFamily } from "utils/user/family";
+import FreeSubscriptionPlanSelectorCard from "./free";
+import PaidSubscriptionPlanSelectorCard from "./paid";
interface Props {
closeModal: any;
@@ -40,7 +40,7 @@ function PlanSelectorCard(props: Props) {
const [plans, setPlans] = useLocalState<Plan[]>(LS_KEYS.PLANS);
const [planPeriod, setPlanPeriod] = useState<PLAN_PERIOD>(
- subscription?.period || PLAN_PERIOD.MONTH
+ subscription?.period || PLAN_PERIOD.MONTH,
);
const galleryContext = useContext(GalleryContext);
const appContext = useContext(AppContext);
@@ -66,7 +66,7 @@ function PlanSelectorCard(props: Props) {
setPlanPeriod((prevPeriod) =>
prevPeriod === PLAN_PERIOD.MONTH
? PLAN_PERIOD.YEAR
- : PLAN_PERIOD.MONTH
+ : PLAN_PERIOD.MONTH,
);
};
function onReopenClick() {
@@ -81,7 +81,7 @@ function PlanSelectorCard(props: Props) {
if (isSubscriptionActive(subscription)) {
const planNotListed =
plans.filter((plan) =>
- isUserSubscribedPlan(plan, subscription)
+ isUserSubscribedPlan(plan, subscription),
).length === 0;
if (
subscription &&
@@ -93,15 +93,15 @@ function PlanSelectorCard(props: Props) {
}
setPlans(plans);
} catch (e) {
- logError(e, 'plan selector modal open failed');
+ logError(e, "plan selector modal open failed");
props.closeModal();
appContext.setDialogMessage({
- title: t('OPEN_PLAN_SELECTOR_MODAL_FAILED'),
- content: t('UNKNOWN_ERROR'),
- close: { text: t('CLOSE'), variant: 'secondary' },
+ title: t("OPEN_PLAN_SELECTOR_MODAL_FAILED"),
+ content: t("UNKNOWN_ERROR"),
+ close: { text: t("CLOSE"), variant: "secondary" },
proceed: {
- text: t('REOPEN_PLAN_SELECTOR_MODAL'),
- variant: 'accent',
+ text: t("REOPEN_PLAN_SELECTOR_MODAL"),
+ variant: "accent",
action: onReopenClick,
},
});
@@ -123,49 +123,49 @@ function PlanSelectorCard(props: Props) {
} catch (e) {
props.setLoading(false);
appContext.setDialogMessage({
- title: t('ERROR'),
- content: t('SUBSCRIPTION_PURCHASE_FAILED'),
- close: { variant: 'critical' },
+ title: t("ERROR"),
+ content: t("SUBSCRIPTION_PURCHASE_FAILED"),
+ close: { variant: "critical" },
});
}
} else if (hasStripeSubscription(subscription)) {
appContext.setDialogMessage({
- title: `${t('CONFIRM')} ${reverseString(
- t('UPDATE_SUBSCRIPTION')
+ title: `${t("CONFIRM")} ${reverseString(
+ t("UPDATE_SUBSCRIPTION"),
)}`,
- content: t('UPDATE_SUBSCRIPTION_MESSAGE'),
+ content: t("UPDATE_SUBSCRIPTION_MESSAGE"),
proceed: {
- text: t('UPDATE_SUBSCRIPTION'),
+ text: t("UPDATE_SUBSCRIPTION"),
action: updateSubscription.bind(
null,
plan,
appContext.setDialogMessage,
props.setLoading,
- props.closeModal
+ props.closeModal,
),
- variant: 'accent',
+ variant: "accent",
},
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
});
} else if (hasMobileSubscription(subscription)) {
appContext.setDialogMessage({
- title: t('CANCEL_SUBSCRIPTION_ON_MOBILE'),
- content: t('CANCEL_SUBSCRIPTION_ON_MOBILE_MESSAGE'),
- close: { variant: 'secondary' },
+ title: t("CANCEL_SUBSCRIPTION_ON_MOBILE"),
+ content: t("CANCEL_SUBSCRIPTION_ON_MOBILE_MESSAGE"),
+ close: { variant: "secondary" },
});
} else {
appContext.setDialogMessage({
- title: t('MANAGE_PLAN'),
+ title: t("MANAGE_PLAN"),
content: (
<Trans
- i18nKey={'MAIL_TO_MANAGE_SUBSCRIPTION'}
+ i18nKey={"MAIL_TO_MANAGE_SUBSCRIPTION"}
components={{
a: <Link href={`mailto:${SUPPORT_EMAIL}`} />,
}}
values={{ emailID: SUPPORT_EMAIL }}
/>
),
- close: { variant: 'secondary' },
+ close: { variant: "secondary" },
});
}
}
diff --git a/apps/photos/src/components/pages/gallery/PlanSelector/card/paid.tsx b/apps/photos/src/components/pages/gallery/PlanSelector/card/paid.tsx
index 111d4b6a27..4ef76a491f 100644
--- a/apps/photos/src/components/pages/gallery/PlanSelector/card/paid.tsx
+++ b/apps/photos/src/components/pages/gallery/PlanSelector/card/paid.tsx
@@ -1,20 +1,19 @@
-import Close from '@mui/icons-material/Close';
-import { IconButton, Stack } from '@mui/material';
-import Box from '@mui/material/Box';
-import Typography from '@mui/material/Typography';
-import { SpaceBetweenFlex } from '@ente/shared/components/Container';
-import React from 'react';
-import { t } from 'i18next';
+import { SpaceBetweenFlex } from "@ente/shared/components/Container";
+import Close from "@mui/icons-material/Close";
+import { IconButton, Stack } from "@mui/material";
+import Box from "@mui/material/Box";
+import Typography from "@mui/material/Typography";
+import { t } from "i18next";
+import { Trans } from "react-i18next";
import {
convertBytesToGBs,
hasAddOnBonus,
isSubscriptionCancelled,
-} from 'utils/billing';
-import { ManageSubscription } from '../manageSubscription';
-import { PeriodToggler } from '../periodToggler';
-import Plans from '../plans';
-import { Trans } from 'react-i18next';
-import { BFAddOnRow } from '../plans/BfAddOnRow';
+} from "utils/billing";
+import { ManageSubscription } from "../manageSubscription";
+import { PeriodToggler } from "../periodToggler";
+import Plans from "../plans";
+import { BFAddOnRow } from "../plans/BfAddOnRow";
export default function PaidSubscriptionPlanSelectorCard({
plans,
@@ -32,12 +31,12 @@ export default function PaidSubscriptionPlanSelectorCard({
<Box pl={1.5} py={0.5}>
<SpaceBetweenFlex>
<Box>
- <Typography variant="h3" fontWeight={'bold'}>
- {t('SUBSCRIPTION')}
+ <Typography variant="h3" fontWeight={"bold"}>
+ {t("SUBSCRIPTION")}
</Typography>
- <Typography variant="small" color={'text.muted'}>
- {convertBytesToGBs(subscription.storage, 2)}{' '}
- {t('GB')}
+ <Typography variant="small" color={"text.muted"}>
+ {convertBytesToGBs(subscription.storage, 2)}{" "}
+ {t("GB")}
</Typography>
</Box>
<IconButton onClick={closeModal} color="secondary">
@@ -47,11 +46,11 @@ export default function PaidSubscriptionPlanSelectorCard({
</Box>
<Box px={1.5}>
- <Typography color={'text.muted'} fontWeight={'bold'}>
+ <Typography color={"text.muted"} fontWeight={"bold"}>
<Trans
i18nKey="CURRENT_USAGE"
values={{
- usage: `${convertBytesToGBs(usage, 2)} ${t('GB')}`,
+ usage: `${convertBytesToGBs(usage, 2)} ${t("GB")}`,
}}
/>
</Typography>
@@ -62,14 +61,15 @@ export default function PaidSubscriptionPlanSelectorCard({
spacing={3}
border={(theme) => `1px solid ${theme.palette.divider}`}
p={1.5}
- borderRadius={(theme) => `${theme.shape.borderRadius}px`}>
+ borderRadius={(theme) => `${theme.shape.borderRadius}px`}
+ >
<Box>
<PeriodToggler
planPeriod={planPeriod}
togglePeriod={togglePeriod}
/>
<Typography variant="small" mt={0.5} color="text.muted">
- {t('TWO_MONTHS_FREE')}
+ {t("TWO_MONTHS_FREE")}
</Typography>
</Box>
<Plans
@@ -83,12 +83,12 @@ export default function PaidSubscriptionPlanSelectorCard({
</Stack>
<Box py={1} px={1.5}>
- <Typography color={'text.muted'}>
+ <Typography color={"text.muted"}>
{!isSubscriptionCancelled(subscription)
- ? t('RENEWAL_ACTIVE_SUBSCRIPTION_STATUS', {
+ ? t("RENEWAL_ACTIVE_SUBSCRIPTION_STATUS", {
date: subscription.expiryTime,
})
- : t('RENEWAL_CANCELLED_SUBSCRIPTION_STATUS', {
+ : t("RENEWAL_CANCELLED_SUBSCRIPTION_STATUS", {
date: subscription.expiryTime,
})}
</Typography>
diff --git a/apps/photos/src/components/pages/gallery/PlanSelector/index.tsx b/apps/photos/src/components/pages/gallery/PlanSelector/index.tsx
index 0230a28781..20ad04d019 100644
--- a/apps/photos/src/components/pages/gallery/PlanSelector/index.tsx
+++ b/apps/photos/src/components/pages/gallery/PlanSelector/index.tsx
@@ -1,8 +1,8 @@
-import React, { useContext } from 'react';
-import { SetLoading } from 'types/gallery';
-import { AppContext } from 'pages/_app';
-import { Dialog } from '@mui/material';
-import PlanSelectorCard from './card';
+import { Dialog } from "@mui/material";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
+import { SetLoading } from "types/gallery";
+import PlanSelectorCard from "./card";
interface Props {
modalView: boolean;
@@ -23,11 +23,12 @@ function PlanSelector(props: Props) {
onClose={props.closeModal}
PaperProps={{
sx: (theme) => ({
- width: '391px',
+ width: "391px",
p: 1,
[theme.breakpoints.down(360)]: { p: 0 },
}),
- }}>
+ }}
+ >
<PlanSelectorCard
closeModal={props.closeModal}
setLoading={props.setLoading}
diff --git a/apps/photos/src/components/pages/gallery/PlanSelector/manageSubscription/button.tsx b/apps/photos/src/components/pages/gallery/PlanSelector/manageSubscription/button.tsx
index 724b92abc0..f1aca561ff 100644
--- a/apps/photos/src/components/pages/gallery/PlanSelector/manageSubscription/button.tsx
+++ b/apps/photos/src/components/pages/gallery/PlanSelector/manageSubscription/button.tsx
@@ -1,6 +1,6 @@
-import ChevronRight from '@mui/icons-material/ChevronRight';
-import { Button, ButtonProps } from '@mui/material';
-import { FluidContainer } from '@ente/shared/components/Container';
+import { FluidContainer } from "@ente/shared/components/Container";
+import ChevronRight from "@mui/icons-material/ChevronRight";
+import { Button, ButtonProps } from "@mui/material";
const ManageSubscriptionButton = ({ children, ...props }: ButtonProps) => (
<Button size="large" endIcon={<ChevronRight />} {...props}>
diff --git a/apps/photos/src/components/pages/gallery/PlanSelector/manageSubscription/index.tsx b/apps/photos/src/components/pages/gallery/PlanSelector/manageSubscription/index.tsx
index 31b34ce162..f05d1540bd 100644
--- a/apps/photos/src/components/pages/gallery/PlanSelector/manageSubscription/index.tsx
+++ b/apps/photos/src/components/pages/gallery/PlanSelector/manageSubscription/index.tsx
@@ -1,21 +1,21 @@
-import { Stack } from '@mui/material';
-import { AppContext } from 'pages/_app';
-import React, { useContext } from 'react';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
-import { Subscription } from 'types/billing';
-import { SetLoading } from 'types/gallery';
+import { Stack } from "@mui/material";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
+import { Trans } from "react-i18next";
+import { Subscription } from "types/billing";
+import { SetLoading } from "types/gallery";
+import { BonusData } from "types/user";
import {
activateSubscription,
cancelSubscription,
- updatePaymentMethod,
- manageFamilyMethod,
+ hasAddOnBonus,
hasStripeSubscription,
isSubscriptionCancelled,
- hasAddOnBonus,
-} from 'utils/billing';
-import ManageSubscriptionButton from './button';
-import { BonusData } from 'types/user';
+ manageFamilyMethod,
+ updatePaymentMethod,
+} from "utils/billing";
+import ManageSubscriptionButton from "./button";
interface Iprops {
subscription: Subscription;
@@ -46,8 +46,9 @@ export function ManageSubscription({
)}
<ManageSubscriptionButton
color="secondary"
- onClick={openFamilyPortal}>
- {t('MANAGE_FAMILY_PORTAL')}
+ onClick={openFamilyPortal}
+ >
+ {t("MANAGE_FAMILY_PORTAL")}
</ManageSubscriptionButton>
</Stack>
);
@@ -63,70 +64,73 @@ function StripeSubscriptionOptions({
const confirmReactivation = () =>
appContext.setDialogMessage({
- title: t('REACTIVATE_SUBSCRIPTION'),
- content: t('REACTIVATE_SUBSCRIPTION_MESSAGE', {
+ title: t("REACTIVATE_SUBSCRIPTION"),
+ content: t("REACTIVATE_SUBSCRIPTION_MESSAGE", {
date: subscription.expiryTime,
}),
proceed: {
- text: t('REACTIVATE_SUBSCRIPTION'),
+ text: t("REACTIVATE_SUBSCRIPTION"),
action: activateSubscription.bind(
null,
appContext.setDialogMessage,
closeModal,
- setLoading
+ setLoading,
),
- variant: 'accent',
+ variant: "accent",
},
close: {
- text: t('CANCEL'),
+ text: t("CANCEL"),
},
});
const confirmCancel = () =>
appContext.setDialogMessage({
- title: t('CANCEL_SUBSCRIPTION'),
+ title: t("CANCEL_SUBSCRIPTION"),
content: hasAddOnBonus(bonusData) ? (
- <Trans i18nKey={'CANCEL_SUBSCRIPTION_WITH_ADDON_MESSAGE'} />
+ <Trans i18nKey={"CANCEL_SUBSCRIPTION_WITH_ADDON_MESSAGE"} />
) : (
- <Trans i18nKey={'CANCEL_SUBSCRIPTION_MESSAGE'} />
+ <Trans i18nKey={"CANCEL_SUBSCRIPTION_MESSAGE"} />
),
proceed: {
- text: t('CANCEL_SUBSCRIPTION'),
+ text: t("CANCEL_SUBSCRIPTION"),
action: cancelSubscription.bind(
null,
appContext.setDialogMessage,
closeModal,
- setLoading
+ setLoading,
),
- variant: 'critical',
+ variant: "critical",
},
close: {
- text: t('NEVERMIND'),
+ text: t("NEVERMIND"),
},
});
const openManagementPortal = updatePaymentMethod.bind(
null,
appContext.setDialogMessage,
- setLoading
+ setLoading,
);
return (
<>
{isSubscriptionCancelled(subscription) ? (
<ManageSubscriptionButton
color="secondary"
- onClick={confirmReactivation}>
- {t('REACTIVATE_SUBSCRIPTION')}
+ onClick={confirmReactivation}
+ >
+ {t("REACTIVATE_SUBSCRIPTION")}
</ManageSubscriptionButton>
) : (
<ManageSubscriptionButton
color="secondary"
- onClick={confirmCancel}>
- {t('CANCEL_SUBSCRIPTION')}
+ onClick={confirmCancel}
+ >
+ {t("CANCEL_SUBSCRIPTION")}
</ManageSubscriptionButton>
)}
<ManageSubscriptionButton
color="secondary"
- onClick={openManagementPortal}>
- {t('MANAGEMENT_PORTAL')}
+ onClick={openManagementPortal}
+ >
+ {t("MANAGEMENT_PORTAL")}
</ManageSubscriptionButton>
</>
);
diff --git a/apps/photos/src/components/pages/gallery/PlanSelector/periodToggler.tsx b/apps/photos/src/components/pages/gallery/PlanSelector/periodToggler.tsx
index cfe12ff169..1faf74b343 100644
--- a/apps/photos/src/components/pages/gallery/PlanSelector/periodToggler.tsx
+++ b/apps/photos/src/components/pages/gallery/PlanSelector/periodToggler.tsx
@@ -1,24 +1,23 @@
-import { styled, ToggleButton, ToggleButtonGroup } from '@mui/material';
-import { PLAN_PERIOD } from 'constants/gallery';
-import React from 'react';
-import { t } from 'i18next';
+import { styled, ToggleButton, ToggleButtonGroup } from "@mui/material";
+import { PLAN_PERIOD } from "constants/gallery";
+import { t } from "i18next";
const CustomToggleButton = styled(ToggleButton)(({ theme }) => ({
- textTransform: 'none',
- padding: '12px 16px',
- borderRadius: '4px',
+ textTransform: "none",
+ padding: "12px 16px",
+ borderRadius: "4px",
backgroundColor: theme.colors.fill.faint,
border: `1px solid transparent`,
color: theme.colors.text.faint,
- '&.Mui-selected': {
+ "&.Mui-selected": {
backgroundColor: theme.colors.accent.A500,
color: theme.colors.text.base,
},
- '&.Mui-selected:hover': {
+ "&.Mui-selected:hover": {
backgroundColor: theme.colors.accent.A500,
color: theme.colors.text.base,
},
- width: '97.433px',
+ width: "97.433px",
}));
export function PeriodToggler({ planPeriod, togglePeriod }) {
@@ -33,12 +32,13 @@ export function PeriodToggler({ planPeriod, togglePeriod }) {
value={planPeriod}
exclusive
onChange={handleChange}
- color="primary">
+ color="primary"
+ >
<CustomToggleButton value={PLAN_PERIOD.MONTH}>
- {t('MONTHLY')}
+ {t("MONTHLY")}
</CustomToggleButton>
<CustomToggleButton value={PLAN_PERIOD.YEAR}>
- {t('YEARLY')}
+ {t("YEARLY")}
</CustomToggleButton>
</ToggleButtonGroup>
);
diff --git a/apps/photos/src/components/pages/gallery/PlanSelector/plans/BfAddOnRow.tsx b/apps/photos/src/components/pages/gallery/PlanSelector/plans/BfAddOnRow.tsx
index 46584cde7d..8b0ce7bd5f 100644
--- a/apps/photos/src/components/pages/gallery/PlanSelector/plans/BfAddOnRow.tsx
+++ b/apps/photos/src/components/pages/gallery/PlanSelector/plans/BfAddOnRow.tsx
@@ -1,32 +1,31 @@
-import { Box, styled, Typography } from '@mui/material';
-import { SpaceBetweenFlex } from '@ente/shared/components/Container';
-import React from 'react';
+import { SpaceBetweenFlex } from "@ente/shared/components/Container";
+import { Box, styled, Typography } from "@mui/material";
-import { Trans } from 'react-i18next';
-import { makeHumanReadableStorage } from 'utils/billing';
+import { Trans } from "react-i18next";
+import { makeHumanReadableStorage } from "utils/billing";
const RowContainer = styled(SpaceBetweenFlex)(({ theme }) => ({
// gap: theme.spacing(1.5),
padding: theme.spacing(1, 0),
- cursor: 'pointer',
- '&:hover .endIcon': {
- backgroundColor: 'rgba(255,255,255,0.08)',
+ cursor: "pointer",
+ "&:hover .endIcon": {
+ backgroundColor: "rgba(255,255,255,0.08)",
},
}));
export function BFAddOnRow({ bonusData, closeModal }) {
return (
<>
{bonusData.storageBonuses.map((bonus) => {
- if (bonus.type.startsWith('ADD_ON')) {
+ if (bonus.type.startsWith("ADD_ON")) {
return (
<RowContainer key={bonus.id} onClick={closeModal}>
<Box>
<Typography color="text.muted">
<Trans
- i18nKey={'ADD_ON_AVAILABLE_TILL'}
+ i18nKey={"ADD_ON_AVAILABLE_TILL"}
values={{
storage: makeHumanReadableStorage(
- bonus.storage
+ bonus.storage,
),
date: bonus.validTill,
}}
diff --git a/apps/photos/src/components/pages/gallery/PlanSelector/plans/FreePlanRow.tsx b/apps/photos/src/components/pages/gallery/PlanSelector/plans/FreePlanRow.tsx
index 06e4ae40b0..f3651e12d4 100644
--- a/apps/photos/src/components/pages/gallery/PlanSelector/plans/FreePlanRow.tsx
+++ b/apps/photos/src/components/pages/gallery/PlanSelector/plans/FreePlanRow.tsx
@@ -1,27 +1,26 @@
-import ArrowForward from '@mui/icons-material/ArrowForward';
-import { Box, IconButton, styled, Typography } from '@mui/material';
-import { SpaceBetweenFlex } from '@ente/shared/components/Container';
-import React from 'react';
-import { t } from 'i18next';
+import { SpaceBetweenFlex } from "@ente/shared/components/Container";
+import ArrowForward from "@mui/icons-material/ArrowForward";
+import { Box, IconButton, styled, Typography } from "@mui/material";
+import { t } from "i18next";
const RowContainer = styled(SpaceBetweenFlex)(({ theme }) => ({
gap: theme.spacing(1.5),
padding: theme.spacing(1.5, 1),
- cursor: 'pointer',
- '&:hover .endIcon': {
- backgroundColor: 'rgba(255,255,255,0.08)',
+ cursor: "pointer",
+ "&:hover .endIcon": {
+ backgroundColor: "rgba(255,255,255,0.08)",
},
}));
export function FreePlanRow({ closeModal }) {
return (
<RowContainer onClick={closeModal}>
<Box>
- <Typography> {t('FREE_PLAN_OPTION_LABEL')}</Typography>
+ <Typography> {t("FREE_PLAN_OPTION_LABEL")}</Typography>
<Typography variant="small" color="text.muted">
- {t('FREE_PLAN_DESCRIPTION')}
+ {t("FREE_PLAN_DESCRIPTION")}
</Typography>
</Box>
- <IconButton className={'endIcon'}>
+ <IconButton className={"endIcon"}>
<ArrowForward />
</IconButton>
</RowContainer>
diff --git a/apps/photos/src/components/pages/gallery/PlanSelector/plans/button.tsx b/apps/photos/src/components/pages/gallery/PlanSelector/plans/button.tsx
index fa5d5c0fb0..d599c486b3 100644
--- a/apps/photos/src/components/pages/gallery/PlanSelector/plans/button.tsx
+++ b/apps/photos/src/components/pages/gallery/PlanSelector/plans/button.tsx
@@ -1,9 +1,8 @@
-import ChevronRight from '@mui/icons-material/ChevronRight';
-import Done from '@mui/icons-material/Done';
-import { Box, Button } from '@mui/material';
-import { SpaceBetweenFlex } from '@ente/shared/components/Container';
-import React from 'react';
-import { t } from 'i18next';
+import { SpaceBetweenFlex } from "@ente/shared/components/Container";
+import ChevronRight from "@mui/icons-material/ChevronRight";
+import Done from "@mui/icons-material/Done";
+import { Box, Button } from "@mui/material";
+import { t } from "i18next";
export function PlanIconButton({
current,
onClick,
@@ -28,16 +27,17 @@ function CurrentPlanTileButton() {
color="accent"
disabled={true}
sx={(theme) => ({
- '&&': {
+ "&&": {
color: theme.colors.accent.A500,
borderColor: theme.colors.accent.A500,
},
})}
fullWidth
onClick={() => null}
- variant={'outlined'}>
+ variant={"outlined"}
+ >
<SpaceBetweenFlex>
- {t('ACTIVE')}
+ {t("ACTIVE")}
<Done />
</SpaceBetweenFlex>
</Button>
@@ -53,9 +53,10 @@ function NormalPlanTileButton({ onClick }) {
})}
fullWidth
onClick={onClick}
- variant={'contained'}>
+ variant={"contained"}
+ >
<SpaceBetweenFlex>
- {t('SUBSCRIBE')}
+ {t("SUBSCRIBE")}
<ChevronRight />
</SpaceBetweenFlex>
</Button>
diff --git a/apps/photos/src/components/pages/gallery/PlanSelector/plans/index.tsx b/apps/photos/src/components/pages/gallery/PlanSelector/plans/index.tsx
index e68b4fddc1..ed1a666edb 100644
--- a/apps/photos/src/components/pages/gallery/PlanSelector/plans/index.tsx
+++ b/apps/photos/src/components/pages/gallery/PlanSelector/plans/index.tsx
@@ -1,16 +1,15 @@
-import { FreePlanRow } from './FreePlanRow';
-import { Stack } from '@mui/material';
-import React from 'react';
+import { Stack } from "@mui/material";
+import { PLAN_PERIOD } from "constants/gallery";
+import { Plan, Subscription } from "types/billing";
+import { BonusData } from "types/user";
import {
hasAddOnBonus,
hasPaidSubscription,
isPopularPlan,
isUserSubscribedPlan,
-} from 'utils/billing';
-import { PlanRow } from './planRow';
-import { Plan, Subscription } from 'types/billing';
-import { PLAN_PERIOD } from 'constants/gallery';
-import { BonusData } from 'types/user';
+} from "utils/billing";
+import { FreePlanRow } from "./FreePlanRow";
+import { PlanRow } from "./planRow";
interface Iprops {
plans: Plan[];
diff --git a/apps/photos/src/components/pages/gallery/PlanSelector/plans/planRow.tsx b/apps/photos/src/components/pages/gallery/PlanSelector/plans/planRow.tsx
index b05557c695..6363caee4d 100644
--- a/apps/photos/src/components/pages/gallery/PlanSelector/plans/planRow.tsx
+++ b/apps/photos/src/components/pages/gallery/PlanSelector/plans/planRow.tsx
@@ -1,17 +1,16 @@
-import { Box, Button, ButtonProps, styled, Typography } from '@mui/material';
-import React from 'react';
+import { FlexWrapper, FluidContainer } from "@ente/shared/components/Container";
+import ArrowForward from "@mui/icons-material/ArrowForward";
+import Done from "@mui/icons-material/Done";
+import { Box, Button, ButtonProps, Typography, styled } from "@mui/material";
+import { Badge } from "components/Badge";
+import { PLAN_PERIOD } from "constants/gallery";
+import { t } from "i18next";
+import { Plan, Subscription } from "types/billing";
import {
- isUserSubscribedPlan,
convertBytesToGBs,
hasPaidSubscription,
-} from 'utils/billing';
-import { FlexWrapper, FluidContainer } from '@ente/shared/components/Container';
-import ArrowForward from '@mui/icons-material/ArrowForward';
-import { PLAN_PERIOD } from 'constants/gallery';
-import Done from '@mui/icons-material/Done';
-import { Plan, Subscription } from 'types/billing';
-import { Badge } from 'components/Badge';
-import { t } from 'i18next';
+ isUserSubscribedPlan,
+} from "utils/billing";
interface Iprops {
plan: Plan;
@@ -23,7 +22,7 @@ interface Iprops {
const PlanRowContainer = styled(FlexWrapper)(() => ({
background:
- 'linear-gradient(268.22deg, rgba(256, 256, 256, 0.08) -3.72%, rgba(256, 256, 256, 0) 85.73%)',
+ "linear-gradient(268.22deg, rgba(256, 256, 256, 0.08) -3.72%, rgba(256, 256, 256, 0) 85.73%)",
}));
const TopAlignedFluidContainer = styled(FluidContainer)`
@@ -33,8 +32,8 @@ const TopAlignedFluidContainer = styled(FluidContainer)`
const DisabledPlanButton = styled((props: ButtonProps) => (
<Button disabled endIcon={<Done />} {...props} />
))(({ theme }) => ({
- '&.Mui-disabled': {
- backgroundColor: 'transparent',
+ "&.Mui-disabled": {
+ backgroundColor: "transparent",
color: theme.colors.text.base,
},
}));
@@ -42,11 +41,11 @@ const DisabledPlanButton = styled((props: ButtonProps) => (
const ActivePlanButton = styled((props: ButtonProps) => (
<Button color="accent" {...props} endIcon={<ArrowForward />} />
))(() => ({
- '.MuiButton-endIcon': {
- transition: 'transform .2s ease-in-out',
+ ".MuiButton-endIcon": {
+ transition: "transform .2s ease-in-out",
},
- '&:hover .MuiButton-endIcon': {
- transform: 'translateX(4px)',
+ "&:hover .MuiButton-endIcon": {
+ transform: "translateX(4px)",
},
}));
@@ -66,36 +65,37 @@ export function PlanRow({
return (
<PlanRowContainer>
<TopAlignedFluidContainer>
- <Typography variant="h1" fontWeight={'bold'}>
+ <Typography variant="h1" fontWeight={"bold"}>
{convertBytesToGBs(plan.storage)}
</Typography>
- <FlexWrapper flexWrap={'wrap'} gap={1}>
+ <FlexWrapper flexWrap={"wrap"} gap={1}>
<Typography variant="h3" color="text.muted">
- {t('GB')}
+ {t("GB")}
</Typography>
{popular && !hasPaidSubscription(subscription) && (
- <Badge>{t('POPULAR')}</Badge>
+ <Badge>{t("POPULAR")}</Badge>
)}
</FlexWrapper>
</TopAlignedFluidContainer>
<Box width="136px">
<PlanButton
sx={{
- justifyContent: 'flex-end',
+ justifyContent: "flex-end",
borderTopLeftRadius: 0,
borderBottomLeftRadius: 0,
}}
size="large"
- onClick={handleClick}>
- <Box textAlign={'right'}>
- <Typography fontWeight={'bold'} variant="large">
- {plan.price}{' '}
- </Typography>{' '}
+ onClick={handleClick}
+ >
+ <Box textAlign={"right"}>
+ <Typography fontWeight={"bold"} variant="large">
+ {plan.price}{" "}
+ </Typography>{" "}
<Typography color="text.muted" variant="small">
{`/ ${
plan.period === PLAN_PERIOD.MONTH
- ? t('MONTH_SHORT')
- : t('YEAR')
+ ? t("MONTH_SHORT")
+ : t("YEAR")
}`}
</Typography>
</Box>
diff --git a/apps/photos/src/components/pages/gallery/PlanSelector/plans/planTile.tsx b/apps/photos/src/components/pages/gallery/PlanSelector/plans/planTile.tsx
index f075143791..de39335284 100644
--- a/apps/photos/src/components/pages/gallery/PlanSelector/plans/planTile.tsx
+++ b/apps/photos/src/components/pages/gallery/PlanSelector/plans/planTile.tsx
@@ -1,41 +1,41 @@
-import { styled } from '@mui/material';
+import { styled } from "@mui/material";
-const PlanTile = styled('div')<{ current: boolean }>(({ theme, current }) => ({
+const PlanTile = styled("div")<{ current: boolean }>(({ theme, current }) => ({
padding: theme.spacing(3),
border: `1px solid ${theme.palette.divider}`,
- '&:hover': {
- backgroundColor: ' rgba(40, 214, 101, 0.11)',
- cursor: 'pointer',
+ "&:hover": {
+ backgroundColor: " rgba(40, 214, 101, 0.11)",
+ cursor: "pointer",
},
...(current && {
borderColor: theme.colors.accent.A500,
- cursor: 'not-allowed',
- '&:hover': { backgroundColor: 'transparent' },
+ cursor: "not-allowed",
+ "&:hover": { backgroundColor: "transparent" },
}),
- width: ' 260px',
- '@media (min-width: 1152px)': {
- '&:first-of-type': {
- borderTopLeftRadius: '8px',
+ width: " 260px",
+ "@media (min-width: 1152px)": {
+ "&:first-of-type": {
+ borderTopLeftRadius: "8px",
},
- '&:last-of-type': {
- borderTopRightRadius: '8px',
+ "&:last-of-type": {
+ borderTopRightRadius: "8px",
},
},
- '@media (max-width: 1151px) and (min-width:551px)': {
- '&:first-of-type': {
- borderTopLeftRadius: '8px',
+ "@media (max-width: 1151px) and (min-width:551px)": {
+ "&:first-of-type": {
+ borderTopLeftRadius: "8px",
},
- '&:nth-of-type(2)': {
- borderTopRightRadius: '8px',
+ "&:nth-of-type(2)": {
+ borderTopRightRadius: "8px",
},
},
- '@media (max-width: 551px)': {
- '&:first-of-type': {
- borderTopLeftRadius: '8px',
- borderTopRightRadius: '8px',
+ "@media (max-width: 551px)": {
+ "&:first-of-type": {
+ borderTopLeftRadius: "8px",
+ borderTopRightRadius: "8px",
},
},
}));
diff --git a/apps/photos/src/components/pages/gallery/PreviewCard.tsx b/apps/photos/src/components/pages/gallery/PreviewCard.tsx
index 582a193c76..1750d30e29 100644
--- a/apps/photos/src/components/pages/gallery/PreviewCard.tsx
+++ b/apps/photos/src/components/pages/gallery/PreviewCard.tsx
@@ -1,25 +1,25 @@
-import React, { useContext, useEffect, useRef, useState } from 'react';
-import { EnteFile } from 'types/file';
-import { Tooltip, styled } from '@mui/material';
-import PlayCircleOutlineOutlinedIcon from '@mui/icons-material/PlayCircleOutlineOutlined';
-import DownloadManager from 'services/download';
-import useLongPress from '@ente/shared/hooks/useLongPress';
-import { GalleryContext } from 'pages/gallery';
-import { GAP_BTW_TILES, IMAGE_CONTAINER_MAX_WIDTH } from 'constants/gallery';
-import { DeduplicateContext } from 'pages/deduplicate';
-import { logError } from '@ente/shared/sentry';
-import { Overlay } from '@ente/shared/components/Container';
-import { TRASH_SECTION } from 'constants/collection';
-import { formatDateRelative } from '@ente/shared/time/format';
+import { Overlay } from "@ente/shared/components/Container";
+import { CustomError } from "@ente/shared/error";
+import useLongPress from "@ente/shared/hooks/useLongPress";
+import { logError } from "@ente/shared/sentry";
+import { formatDateRelative } from "@ente/shared/time/format";
+import AlbumOutlined from "@mui/icons-material/AlbumOutlined";
+import PlayCircleOutlineOutlinedIcon from "@mui/icons-material/PlayCircleOutlineOutlined";
+import { Tooltip, styled } from "@mui/material";
import {
LoadingThumbnail,
StaticThumbnail,
-} from 'components/PlaceholderThumbnails';
-import { FILE_TYPE } from 'constants/file';
-import AlbumOutlined from '@mui/icons-material/AlbumOutlined';
-import Avatar from './Avatar';
-import { shouldShowAvatar } from 'utils/file';
-import { CustomError } from '@ente/shared/error';
+} from "components/PlaceholderThumbnails";
+import { TRASH_SECTION } from "constants/collection";
+import { FILE_TYPE } from "constants/file";
+import { GAP_BTW_TILES, IMAGE_CONTAINER_MAX_WIDTH } from "constants/gallery";
+import { DeduplicateContext } from "pages/deduplicate";
+import { GalleryContext } from "pages/gallery";
+import React, { useContext, useEffect, useRef, useState } from "react";
+import DownloadManager from "services/download";
+import { EnteFile } from "types/file";
+import { shouldShowAvatar } from "utils/file";
+import Avatar from "./Avatar";
interface IProps {
file: EnteFile;
@@ -37,7 +37,7 @@ interface IProps {
showPlaceholder: boolean;
}
-const Check = styled('input')<{ $active: boolean }>`
+const Check = styled("input")<{ $active: boolean }>`
appearance: none;
position: absolute;
z-index: 10;
@@ -50,7 +50,7 @@ const Check = styled('input')<{ $active: boolean }>`
}
&::before {
- content: '';
+ content: "";
width: 16px;
height: 16px;
border: 2px solid #fff;
@@ -66,7 +66,7 @@ const Check = styled('input')<{ $active: boolean }>`
color: #aaa;
}
&::after {
- content: '';
+ content: "";
width: 5px;
height: 10px;
border-right: 2px solid #333;
@@ -80,23 +80,23 @@ const Check = styled('input')<{ $active: boolean }>`
/** checked */
&:checked::before {
- content: '';
+ content: "";
background-color: #51cd7c;
border-color: #51cd7c;
color: #fff;
}
&:checked::after {
- content: '';
+ content: "";
border-right: 2px solid #ddd;
border-bottom: 2px solid #ddd;
}
- ${(props) => props.$active && 'opacity: 0.5 '};
+ ${(props) => props.$active && "opacity: 0.5 "};
&:checked {
opacity: 1 !important;
}
`;
-export const HoverOverlay = styled('div')<{ checked: boolean }>`
+export const HoverOverlay = styled("div")<{ checked: boolean }>`
opacity: 0;
left: 0;
top: 0;
@@ -106,7 +106,7 @@ export const HoverOverlay = styled('div')<{ checked: boolean }>`
position: absolute;
${(props) =>
!props.checked &&
- 'background:linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0))'};
+ "background:linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0))"};
`;
export const AvatarOverlay = styled(Overlay)`
@@ -117,7 +117,7 @@ export const AvatarOverlay = styled(Overlay)`
padding-top: 5px;
`;
-export const InSelectRangeOverLay = styled('div')<{ $active: boolean }>`
+export const InSelectRangeOverLay = styled("div")<{ $active: boolean }>`
opacity: ${(props) => (!props.$active ? 0 : 1)};
left: 0;
top: 0;
@@ -125,10 +125,10 @@ export const InSelectRangeOverLay = styled('div')<{ $active: boolean }>`
height: 100%;
width: 100%;
position: absolute;
- ${(props) => props.$active && 'background:rgba(81, 205, 124, 0.25)'};
+ ${(props) => props.$active && "background:rgba(81, 205, 124, 0.25)"};
`;
-export const FileAndCollectionNameOverlay = styled('div')`
+export const FileAndCollectionNameOverlay = styled("div")`
width: 100%;
bottom: 0;
left: 0;
@@ -152,14 +152,14 @@ export const FileAndCollectionNameOverlay = styled('div')`
position: absolute;
`;
-export const SelectedOverlay = styled('div')<{ selected: boolean }>`
+export const SelectedOverlay = styled("div")<{ selected: boolean }>`
z-index: 5;
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 100%;
- ${(props) => props.selected && 'border: 5px solid #51cd7c;'}
+ ${(props) => props.selected && "border: 5px solid #51cd7c;"}
border-radius: 4px;
`;
@@ -169,7 +169,7 @@ export const FileTypeIndicatorOverlay = styled(Overlay)(
justify-content: flex-end;
align-items: flex-end;
background:${
- theme.palette.mode === 'dark'
+ theme.palette.mode === "dark"
? `linear-gradient(
315deg,
rgba(0, 0, 0, 0.14) 0%,
@@ -184,10 +184,10 @@ export const FileTypeIndicatorOverlay = styled(Overlay)(
`
};
padding: 8px;
-`
+`,
);
-const Cont = styled('div')<{ disabled: boolean }>`
+const Cont = styled("div")<{ disabled: boolean }>`
display: flex;
width: fit-content;
margin-bottom: ${GAP_BTW_TILES}px;
@@ -195,7 +195,7 @@ const Cont = styled('div')<{ disabled: boolean }>`
overflow: hidden;
position: relative;
flex: 1;
- cursor: ${(props) => (props.disabled ? 'not-allowed' : 'pointer')};
+ cursor: ${(props) => (props.disabled ? "not-allowed" : "pointer")};
user-select: none;
& > img {
object-fit: cover;
@@ -206,7 +206,7 @@ const Cont = styled('div')<{ disabled: boolean }>`
}
&:hover {
- input[type='checkbox'] {
+ input[type="checkbox"] {
opacity: 0.5;
}
@@ -261,7 +261,7 @@ export default function PreviewCard(props: IProps) {
const url: string =
await DownloadManager.getThumbnailForPreview(
file,
- props.showPlaceholder
+ props.showPlaceholder,
);
if (!isMounted.current || !url) {
@@ -271,7 +271,7 @@ export default function PreviewCard(props: IProps) {
updateURL(file.id, url);
} catch (e) {
if (e.message !== CustomError.URL_ALREADY_SET) {
- logError(e, 'preview card useEffect failed');
+ logError(e, "preview card useEffect failed");
}
// no-op
}
@@ -311,7 +311,8 @@ export default function PreviewCard(props: IProps) {
onClick={handleClick}
onMouseEnter={handleHover}
disabled={!file?.msrc && !imgSrc}
- {...(selectable ? longPress : {})}>
+ {...(selectable ? longPress : {})}
+ >
{selectable && (
<Check
type="checkbox"
@@ -358,7 +359,7 @@ export default function PreviewCard(props: IProps) {
<p>{file.metadata.title}</p>
<p>
{deduplicateContext.collectionNameMap.get(
- file.collectionID
+ file.collectionID,
)}
</p>
</FileAndCollectionNameOverlay>
@@ -380,8 +381,9 @@ export default function PreviewCard(props: IProps) {
title={`${
file.metadata.title
} - ${deduplicateContext.collectionNameMap.get(
- file.collectionID
- )}`}>
+ file.collectionID,
+ )}`}
+ >
{renderFn()}
</Tooltip>
);
diff --git a/apps/photos/src/components/pages/gallery/SelectedFileOptions.tsx b/apps/photos/src/components/pages/gallery/SelectedFileOptions.tsx
index acde23b0b6..2ed374665f 100644
--- a/apps/photos/src/components/pages/gallery/SelectedFileOptions.tsx
+++ b/apps/photos/src/components/pages/gallery/SelectedFileOptions.tsx
@@ -1,39 +1,39 @@
-import React, { useContext } from 'react';
-import {
- CollectionSelectorIntent,
- SetCollectionSelectorAttributes,
-} from 'types/gallery';
-import { FluidContainer } from '@ente/shared/components/Container';
-import { COLLECTION_OPS_TYPE } from 'utils/collection';
+import { FluidContainer } from "@ente/shared/components/Container";
+import { SelectionBar } from "@ente/shared/components/Navbar/SelectionBar";
+import ClockIcon from "@mui/icons-material/AccessTime";
+import AddIcon from "@mui/icons-material/Add";
+import ArchiveIcon from "@mui/icons-material/ArchiveOutlined";
+import MoveIcon from "@mui/icons-material/ArrowForward";
+import CloseIcon from "@mui/icons-material/Close";
+import DeleteIcon from "@mui/icons-material/Delete";
+import DownloadIcon from "@mui/icons-material/Download";
+import RemoveIcon from "@mui/icons-material/RemoveCircleOutline";
+import RestoreIcon from "@mui/icons-material/Restore";
+import UnArchiveIcon from "@mui/icons-material/Unarchive";
+import VisibilityOffOutlined from "@mui/icons-material/VisibilityOffOutlined";
+import VisibilityOutlined from "@mui/icons-material/VisibilityOutlined";
+import { Box, IconButton, Stack, Tooltip } from "@mui/material";
import {
ALL_SECTION,
ARCHIVE_SECTION,
TRASH_SECTION,
-} from 'constants/collection';
-import { SelectionBar } from '@ente/shared/components/Navbar/SelectionBar';
-import { AppContext } from 'pages/_app';
-import { Box, IconButton, Stack, Tooltip } from '@mui/material';
-import CloseIcon from '@mui/icons-material/Close';
-import RestoreIcon from '@mui/icons-material/Restore';
-import AddIcon from '@mui/icons-material/Add';
-import DeleteIcon from '@mui/icons-material/Delete';
-import ClockIcon from '@mui/icons-material/AccessTime';
-import DownloadIcon from '@mui/icons-material/Download';
-import UnArchiveIcon from '@mui/icons-material/Unarchive';
-import ArchiveIcon from '@mui/icons-material/ArchiveOutlined';
-import MoveIcon from '@mui/icons-material/ArrowForward';
-import RemoveIcon from '@mui/icons-material/RemoveCircleOutline';
-import { getTrashFilesMessage } from 'utils/ui';
-import { t } from 'i18next';
-import { formatNumber } from 'utils/number/format';
-import VisibilityOffOutlined from '@mui/icons-material/VisibilityOffOutlined';
-import VisibilityOutlined from '@mui/icons-material/VisibilityOutlined';
-import { FILE_OPS_TYPE } from 'utils/file';
-import { Collection } from 'types/collection';
+} from "constants/collection";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
+import { Collection } from "types/collection";
+import {
+ CollectionSelectorIntent,
+ SetCollectionSelectorAttributes,
+} from "types/gallery";
+import { COLLECTION_OPS_TYPE } from "utils/collection";
+import { FILE_OPS_TYPE } from "utils/file";
+import { formatNumber } from "utils/number/format";
+import { getTrashFilesMessage } from "utils/ui";
interface Props {
handleCollectionOps: (
- opsType: COLLECTION_OPS_TYPE
+ opsType: COLLECTION_OPS_TYPE,
) => (...args: any[]) => void;
handleFileOps: (opsType: FILE_OPS_TYPE) => (...args: any[]) => void;
showCreateCollectionModal: (opsType: COLLECTION_OPS_TYPE) => () => void;
@@ -77,26 +77,26 @@ const SelectedFileOptions = ({
const trashHandler = () =>
setDialogMessage(
- getTrashFilesMessage(handleFileOps(FILE_OPS_TYPE.TRASH))
+ getTrashFilesMessage(handleFileOps(FILE_OPS_TYPE.TRASH)),
);
const permanentlyDeleteHandler = () =>
setDialogMessage({
- title: t('DELETE_FILES_TITLE'),
- content: t('DELETE_FILES_MESSAGE'),
+ title: t("DELETE_FILES_TITLE"),
+ content: t("DELETE_FILES_MESSAGE"),
proceed: {
action: handleFileOps(FILE_OPS_TYPE.DELETE_PERMANENTLY),
- text: t('DELETE'),
- variant: 'critical',
+ text: t("DELETE"),
+ variant: "critical",
},
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
});
const restoreHandler = () =>
setCollectionSelectorAttributes({
callback: handleCollectionOps(COLLECTION_OPS_TYPE.RESTORE),
showNextModal: showCreateCollectionModal(
- COLLECTION_OPS_TYPE.RESTORE
+ COLLECTION_OPS_TYPE.RESTORE,
),
intent: CollectionSelectorIntent.restore,
});
@@ -104,33 +104,33 @@ const SelectedFileOptions = ({
const removeFromCollectionHandler = () => {
if (ownCount === count) {
setDialogMessage({
- title: t('REMOVE_FROM_COLLECTION'),
- content: t('CONFIRM_SELF_REMOVE_MESSAGE'),
+ title: t("REMOVE_FROM_COLLECTION"),
+ content: t("CONFIRM_SELF_REMOVE_MESSAGE"),
proceed: {
action: () =>
handleCollectionOps(COLLECTION_OPS_TYPE.REMOVE)(
- selectedCollection
+ selectedCollection,
),
- text: t('YES_REMOVE'),
- variant: 'primary',
+ text: t("YES_REMOVE"),
+ variant: "primary",
},
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
});
} else {
setDialogMessage({
- title: t('REMOVE_FROM_COLLECTION'),
- content: t('CONFIRM_SELF_AND_OTHER_REMOVE_MESSAGE'),
+ title: t("REMOVE_FROM_COLLECTION"),
+ content: t("CONFIRM_SELF_AND_OTHER_REMOVE_MESSAGE"),
proceed: {
action: () =>
handleCollectionOps(COLLECTION_OPS_TYPE.REMOVE)(
- selectedCollection
+ selectedCollection,
),
- text: t('YES_REMOVE'),
- variant: 'critical',
+ text: t("YES_REMOVE"),
+ variant: "critical",
},
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
});
}
};
@@ -148,7 +148,7 @@ const SelectedFileOptions = ({
setCollectionSelectorAttributes({
callback: handleCollectionOps(COLLECTION_OPS_TYPE.UNHIDE),
showNextModal: showCreateCollectionModal(
- COLLECTION_OPS_TYPE.UNHIDE
+ COLLECTION_OPS_TYPE.UNHIDE,
),
intent: CollectionSelectorIntent.unhide,
});
@@ -161,44 +161,48 @@ const SelectedFileOptions = ({
<CloseIcon />
</IconButton>
<Box ml={1.5}>
- {formatNumber(count)} {t('SELECTED')}{' '}
+ {formatNumber(count)} {t("SELECTED")}{" "}
{ownCount !== count &&
- `(${formatNumber(ownCount)} ${t('YOURS')})`}
+ `(${formatNumber(ownCount)} ${t("YOURS")})`}
</Box>
</FluidContainer>
<Stack spacing={2} direction="row" mr={2}>
{isInSearchMode ? (
<>
- <Tooltip title={t('FIX_CREATION_TIME')}>
+ <Tooltip title={t("FIX_CREATION_TIME")}>
<IconButton
- onClick={handleFileOps(FILE_OPS_TYPE.FIX_TIME)}>
+ onClick={handleFileOps(FILE_OPS_TYPE.FIX_TIME)}
+ >
<ClockIcon />
</IconButton>
</Tooltip>
- <Tooltip title={t('DOWNLOAD')}>
+ <Tooltip title={t("DOWNLOAD")}>
<IconButton
- onClick={handleFileOps(FILE_OPS_TYPE.DOWNLOAD)}>
+ onClick={handleFileOps(FILE_OPS_TYPE.DOWNLOAD)}
+ >
<DownloadIcon />
</IconButton>
</Tooltip>
- <Tooltip title={t('ADD')}>
+ <Tooltip title={t("ADD")}>
<IconButton onClick={addToCollection}>
<AddIcon />
</IconButton>
</Tooltip>
- <Tooltip title={t('ARCHIVE')}>
+ <Tooltip title={t("ARCHIVE")}>
<IconButton
- onClick={handleFileOps(FILE_OPS_TYPE.ARCHIVE)}>
+ onClick={handleFileOps(FILE_OPS_TYPE.ARCHIVE)}
+ >
<ArchiveIcon />
</IconButton>
</Tooltip>
- <Tooltip title={t('HIDE')}>
+ <Tooltip title={t("HIDE")}>
<IconButton
- onClick={handleFileOps(FILE_OPS_TYPE.HIDE)}>
+ onClick={handleFileOps(FILE_OPS_TYPE.HIDE)}
+ >
<VisibilityOffOutlined />
</IconButton>
</Tooltip>
- <Tooltip title={t('DELETE')}>
+ <Tooltip title={t("DELETE")}>
<IconButton onClick={trashHandler}>
<DeleteIcon />
</IconButton>
@@ -206,12 +210,12 @@ const SelectedFileOptions = ({
</>
) : activeCollectionID === TRASH_SECTION ? (
<>
- <Tooltip title={t('RESTORE')}>
+ <Tooltip title={t("RESTORE")}>
<IconButton onClick={restoreHandler}>
<RestoreIcon />
</IconButton>
</Tooltip>
- <Tooltip title={t('DELETE_PERMANENTLY')}>
+ <Tooltip title={t("DELETE_PERMANENTLY")}>
<IconButton onClick={permanentlyDeleteHandler}>
<DeleteIcon />
</IconButton>
@@ -219,45 +223,48 @@ const SelectedFileOptions = ({
</>
) : isUncategorizedCollection ? (
<>
- <Tooltip title={t('DOWNLOAD')}>
+ <Tooltip title={t("DOWNLOAD")}>
<IconButton
- onClick={handleFileOps(FILE_OPS_TYPE.DOWNLOAD)}>
+ onClick={handleFileOps(FILE_OPS_TYPE.DOWNLOAD)}
+ >
<DownloadIcon />
</IconButton>
</Tooltip>
- <Tooltip title={t('MOVE')}>
+ <Tooltip title={t("MOVE")}>
<IconButton onClick={moveToCollection}>
<MoveIcon />
</IconButton>
</Tooltip>
- <Tooltip title={t('DELETE')}>
+ <Tooltip title={t("DELETE")}>
<IconButton onClick={trashHandler}>
<DeleteIcon />
</IconButton>
</Tooltip>
</>
) : isIncomingSharedCollection ? (
- <Tooltip title={t('DOWNLOAD')}>
+ <Tooltip title={t("DOWNLOAD")}>
<IconButton
- onClick={handleFileOps(FILE_OPS_TYPE.DOWNLOAD)}>
+ onClick={handleFileOps(FILE_OPS_TYPE.DOWNLOAD)}
+ >
<DownloadIcon />
</IconButton>
</Tooltip>
) : isInHiddenSection ? (
<>
- <Tooltip title={t('UNHIDE')}>
+ <Tooltip title={t("UNHIDE")}>
<IconButton onClick={unhideToCollection}>
<VisibilityOutlined />
</IconButton>
</Tooltip>
- <Tooltip title={t('DOWNLOAD')}>
+ <Tooltip title={t("DOWNLOAD")}>
<IconButton
- onClick={handleFileOps(FILE_OPS_TYPE.DOWNLOAD)}>
+ onClick={handleFileOps(FILE_OPS_TYPE.DOWNLOAD)}
+ >
<DownloadIcon />
</IconButton>
</Tooltip>
- <Tooltip title={t('DELETE')}>
+ <Tooltip title={t("DELETE")}>
<IconButton onClick={trashHandler}>
<DeleteIcon />
</IconButton>
@@ -265,39 +272,43 @@ const SelectedFileOptions = ({
</>
) : (
<>
- <Tooltip title={t('FIX_CREATION_TIME')}>
+ <Tooltip title={t("FIX_CREATION_TIME")}>
<IconButton
- onClick={handleFileOps(FILE_OPS_TYPE.FIX_TIME)}>
+ onClick={handleFileOps(FILE_OPS_TYPE.FIX_TIME)}
+ >
<ClockIcon />
</IconButton>
</Tooltip>
- <Tooltip title={t('DOWNLOAD')}>
+ <Tooltip title={t("DOWNLOAD")}>
<IconButton
- onClick={handleFileOps(FILE_OPS_TYPE.DOWNLOAD)}>
+ onClick={handleFileOps(FILE_OPS_TYPE.DOWNLOAD)}
+ >
<DownloadIcon />
</IconButton>
</Tooltip>
- <Tooltip title={t('ADD')}>
+ <Tooltip title={t("ADD")}>
<IconButton onClick={addToCollection}>
<AddIcon />
</IconButton>
</Tooltip>
{activeCollectionID === ARCHIVE_SECTION && (
- <Tooltip title={t('UNARCHIVE')}>
+ <Tooltip title={t("UNARCHIVE")}>
<IconButton
onClick={handleFileOps(
- FILE_OPS_TYPE.UNARCHIVE
- )}>
+ FILE_OPS_TYPE.UNARCHIVE,
+ )}
+ >
<UnArchiveIcon />
</IconButton>
</Tooltip>
)}
{activeCollectionID === ALL_SECTION && (
- <Tooltip title={t('ARCHIVE')}>
+ <Tooltip title={t("ARCHIVE")}>
<IconButton
onClick={handleFileOps(
- FILE_OPS_TYPE.ARCHIVE
- )}>
+ FILE_OPS_TYPE.ARCHIVE,
+ )}
+ >
<ArchiveIcon />
</IconButton>
</Tooltip>
@@ -306,29 +317,31 @@ const SelectedFileOptions = ({
activeCollectionID !== ARCHIVE_SECTION &&
!isFavoriteCollection && (
<>
- <Tooltip title={t('MOVE')}>
+ <Tooltip title={t("MOVE")}>
<IconButton onClick={moveToCollection}>
<MoveIcon />
</IconButton>
</Tooltip>
- <Tooltip title={t('REMOVE')}>
+ <Tooltip title={t("REMOVE")}>
<IconButton
onClick={
removeFromCollectionHandler
- }>
+ }
+ >
<RemoveIcon />
</IconButton>
</Tooltip>
</>
)}
- <Tooltip title={t('HIDE')}>
+ <Tooltip title={t("HIDE")}>
<IconButton
- onClick={handleFileOps(FILE_OPS_TYPE.HIDE)}>
+ onClick={handleFileOps(FILE_OPS_TYPE.HIDE)}
+ >
<VisibilityOffOutlined />
</IconButton>
</Tooltip>
- <Tooltip title={t('DELETE')}>
+ <Tooltip title={t("DELETE")}>
<IconButton onClick={trashHandler}>
<DeleteIcon />
</IconButton>
diff --git a/apps/photos/src/components/pages/sharedAlbum/GoToEnte.tsx b/apps/photos/src/components/pages/sharedAlbum/GoToEnte.tsx
index cc28b52091..bc27bd30c2 100644
--- a/apps/photos/src/components/pages/sharedAlbum/GoToEnte.tsx
+++ b/apps/photos/src/components/pages/sharedAlbum/GoToEnte.tsx
@@ -1,10 +1,10 @@
-import { ENTE_WEBSITE_LINK } from '@ente/shared/constants/urls';
-import React, { useEffect, useState } from 'react';
-import { Button, styled } from '@mui/material';
-import { getDeviceOS, OS } from 'utils/common/deviceDetection';
-import { t } from 'i18next';
+import { ENTE_WEBSITE_LINK } from "@ente/shared/constants/urls";
+import { Button, styled } from "@mui/material";
+import { t } from "i18next";
+import { useEffect, useState } from "react";
+import { OS, getDeviceOS } from "utils/common/deviceDetection";
-export const NoStyleAnchor = styled('a')`
+export const NoStyleAnchor = styled("a")`
color: inherit;
text-decoration: none !important;
&:hover {
@@ -22,9 +22,9 @@ function GoToEnte() {
const getButtonText = (os: OS) => {
if (os === OS.ANDROID || os === OS.IOS) {
- return t('INSTALL');
+ return t("INSTALL");
} else {
- return t('SIGN_UP');
+ return t("SIGN_UP");
}
};
@@ -32,7 +32,8 @@ function GoToEnte() {
<Button
color="accent"
LinkComponent={NoStyleAnchor}
- href={ENTE_WEBSITE_LINK}>
+ href={ENTE_WEBSITE_LINK}
+ >
{getButtonText(os)}
</Button>
);
diff --git a/apps/photos/src/components/pages/sharedAlbum/Navbar.tsx b/apps/photos/src/components/pages/sharedAlbum/Navbar.tsx
index e4e6259262..9bda2093d8 100644
--- a/apps/photos/src/components/pages/sharedAlbum/Navbar.tsx
+++ b/apps/photos/src/components/pages/sharedAlbum/Navbar.tsx
@@ -1,12 +1,12 @@
-import { EnteLinkLogo } from '@ente/shared/components/Navbar/EnteLinkLogo';
-import { FluidContainer } from '@ente/shared/components/Container';
-import NavbarBase from '@ente/shared/components/Navbar/base';
-import UploadButton from 'components/Upload/UploadButton';
-import React, { useContext } from 'react';
-import GoToEnte from './GoToEnte';
-import { t } from 'i18next';
-import AddPhotoAlternateOutlined from '@mui/icons-material/AddPhotoAlternateOutlined';
-import { AppContext } from 'pages/_app';
+import { FluidContainer } from "@ente/shared/components/Container";
+import { EnteLinkLogo } from "@ente/shared/components/Navbar/EnteLinkLogo";
+import NavbarBase from "@ente/shared/components/Navbar/base";
+import AddPhotoAlternateOutlined from "@mui/icons-material/AddPhotoAlternateOutlined";
+import UploadButton from "components/Upload/UploadButton";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
+import GoToEnte from "./GoToEnte";
export default function SharedAlbumNavbar({ showUploadButton, openUploader }) {
const { isMobile } = useContext(AppContext);
@@ -19,7 +19,7 @@ export default function SharedAlbumNavbar({ showUploadButton, openUploader }) {
<UploadButton
openUploader={openUploader}
icon={<AddPhotoAlternateOutlined />}
- text={t('ADD_PHOTOS')}
+ text={t("ADD_PHOTOS")}
/>
) : (
<GoToEnte />
diff --git a/apps/photos/src/components/pages/sharedAlbum/ReportAbuse.tsx b/apps/photos/src/components/pages/sharedAlbum/ReportAbuse.tsx
index a428da0ca5..ba6b0418f6 100644
--- a/apps/photos/src/components/pages/sharedAlbum/ReportAbuse.tsx
+++ b/apps/photos/src/components/pages/sharedAlbum/ReportAbuse.tsx
@@ -1,7 +1,6 @@
-import React from 'react';
-import { Button } from 'react-bootstrap';
-import { styled } from '@mui/material';
-const Container = styled('div')`
+import { styled } from "@mui/material";
+import { Button } from "react-bootstrap";
+const Container = styled("div")`
position: fixed;
bottom: 7%;
right: 2%;
diff --git a/apps/photos/src/components/pages/sharedAlbum/SelectedFileOptions.tsx b/apps/photos/src/components/pages/sharedAlbum/SelectedFileOptions.tsx
index 3e86545f90..35967ec13f 100644
--- a/apps/photos/src/components/pages/sharedAlbum/SelectedFileOptions.tsx
+++ b/apps/photos/src/components/pages/sharedAlbum/SelectedFileOptions.tsx
@@ -1,12 +1,12 @@
-import { useContext } from 'react';
-import { FluidContainer } from '@ente/shared/components/Container';
-import { SelectionBar } from '@ente/shared/components/Navbar/SelectionBar';
-import { AppContext } from 'pages/_app';
-import { Box, IconButton, Stack, Tooltip } from '@mui/material';
-import CloseIcon from '@mui/icons-material/Close';
-import DownloadIcon from '@mui/icons-material/Download';
-import { t } from 'i18next';
-import { formatNumber } from 'utils/number/format';
+import { FluidContainer } from "@ente/shared/components/Container";
+import { SelectionBar } from "@ente/shared/components/Navbar/SelectionBar";
+import CloseIcon from "@mui/icons-material/Close";
+import DownloadIcon from "@mui/icons-material/Download";
+import { Box, IconButton, Stack, Tooltip } from "@mui/material";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
+import { formatNumber } from "utils/number/format";
interface Props {
count: number;
@@ -28,11 +28,11 @@ const SelectedFileOptions = ({
<CloseIcon />
</IconButton>
<Box ml={1.5}>
- {formatNumber(count)} {t('SELECTED')}{' '}
+ {formatNumber(count)} {t("SELECTED")}{" "}
</Box>
</FluidContainer>
<Stack spacing={2} direction="row" mr={2}>
- <Tooltip title={t('DOWNLOAD')}>
+ <Tooltip title={t("DOWNLOAD")}>
<IconButton onClick={downloadFilesHelper}>
<DownloadIcon />
</IconButton>
diff --git a/apps/photos/src/constants/billing.ts b/apps/photos/src/constants/billing.ts
index dfb69a3f9b..f66263eda4 100644
--- a/apps/photos/src/constants/billing.ts
+++ b/apps/photos/src/constants/billing.ts
@@ -1,4 +1,4 @@
-import { getPaymentsURL } from '@ente/shared/network/api';
+import { getPaymentsURL } from "@ente/shared/network/api";
export const getDesktopRedirectURL = () =>
`${getPaymentsURL()}/desktop-redirect`;
diff --git a/apps/photos/src/constants/collection.ts b/apps/photos/src/constants/collection.ts
index a0c6a90377..cc2c000528 100644
--- a/apps/photos/src/constants/collection.ts
+++ b/apps/photos/src/constants/collection.ts
@@ -3,31 +3,31 @@ export const TRASH_SECTION = -2;
export const DUMMY_UNCATEGORIZED_COLLECTION = -3;
export const HIDDEN_ITEMS_SECTION = -4;
export const ALL_SECTION = 0;
-export const DEFAULT_HIDDEN_COLLECTION_USER_FACING_NAME = 'Hidden';
+export const DEFAULT_HIDDEN_COLLECTION_USER_FACING_NAME = "Hidden";
export enum CollectionType {
- folder = 'folder',
- favorites = 'favorites',
- album = 'album',
- uncategorized = 'uncategorized',
+ folder = "folder",
+ favorites = "favorites",
+ album = "album",
+ uncategorized = "uncategorized",
}
export enum CollectionSummaryType {
- folder = 'folder',
- favorites = 'favorites',
- album = 'album',
- archive = 'archive',
- trash = 'trash',
- uncategorized = 'uncategorized',
- all = 'all',
- outgoingShare = 'outgoingShare',
- incomingShareViewer = 'incomingShareViewer',
- incomingShareCollaborator = 'incomingShareCollaborator',
- sharedOnlyViaLink = 'sharedOnlyViaLink',
- archived = 'archived',
- defaultHidden = 'defaultHidden',
- hiddenItems = 'hiddenItems',
- pinned = 'pinned',
+ folder = "folder",
+ favorites = "favorites",
+ album = "album",
+ archive = "archive",
+ trash = "trash",
+ uncategorized = "uncategorized",
+ all = "all",
+ outgoingShare = "outgoingShare",
+ incomingShareViewer = "incomingShareViewer",
+ incomingShareCollaborator = "incomingShareCollaborator",
+ sharedOnlyViaLink = "sharedOnlyViaLink",
+ archived = "archived",
+ defaultHidden = "defaultHidden",
+ hiddenItems = "hiddenItems",
+ pinned = "pinned",
}
export enum COLLECTION_LIST_SORT_BY {
NAME,
diff --git a/apps/photos/src/constants/export.ts b/apps/photos/src/constants/export.ts
index 2b0fc88045..cd6c0c0ee7 100644
--- a/apps/photos/src/constants/export.ts
+++ b/apps/photos/src/constants/export.ts
@@ -1,6 +1,6 @@
-export const ENTE_METADATA_FOLDER = 'metadata';
+export const ENTE_METADATA_FOLDER = "metadata";
-export const ENTE_TRASH_FOLDER = 'Trash';
+export const ENTE_TRASH_FOLDER = "Trash";
export enum ExportStage {
INIT = 0,
diff --git a/apps/photos/src/constants/ffmpeg.ts b/apps/photos/src/constants/ffmpeg.ts
index 008b09784e..9ecc41eb5e 100644
--- a/apps/photos/src/constants/ffmpeg.ts
+++ b/apps/photos/src/constants/ffmpeg.ts
@@ -1,3 +1,3 @@
-export const INPUT_PATH_PLACEHOLDER = 'INPUT';
-export const FFMPEG_PLACEHOLDER = 'FFMPEG';
-export const OUTPUT_PATH_PLACEHOLDER = 'OUTPUT';
+export const INPUT_PATH_PLACEHOLDER = "INPUT";
+export const FFMPEG_PLACEHOLDER = "FFMPEG";
+export const OUTPUT_PATH_PLACEHOLDER = "OUTPUT";
diff --git a/apps/photos/src/constants/file.ts b/apps/photos/src/constants/file.ts
index c00ec9972a..46065136c9 100644
--- a/apps/photos/src/constants/file.ts
+++ b/apps/photos/src/constants/file.ts
@@ -4,10 +4,10 @@ export const MAX_EDITED_CREATION_TIME = new Date();
export const MAX_EDITED_FILE_NAME_LENGTH = 100;
export const MAX_CAPTION_SIZE = 5000;
-export const TYPE_HEIC = 'heic';
-export const TYPE_HEIF = 'heif';
-export const TYPE_JPEG = 'jpeg';
-export const TYPE_JPG = 'jpg';
+export const TYPE_HEIC = "heic";
+export const TYPE_HEIF = "heif";
+export const TYPE_JPEG = "jpeg";
+export const TYPE_JPG = "jpg";
export enum FILE_TYPE {
IMAGE,
@@ -17,27 +17,27 @@ export enum FILE_TYPE {
}
export const RAW_FORMATS = [
- 'heic',
- 'rw2',
- 'tiff',
- 'arw',
- 'cr3',
- 'cr2',
- 'raf',
- 'nef',
- 'psd',
- 'dng',
- 'tif',
+ "heic",
+ "rw2",
+ "tiff",
+ "arw",
+ "cr3",
+ "cr2",
+ "raf",
+ "nef",
+ "psd",
+ "dng",
+ "tif",
];
export const SUPPORTED_RAW_FORMATS = [
- 'heic',
- 'rw2',
- 'tiff',
- 'arw',
- 'cr3',
- 'cr2',
- 'nef',
- 'psd',
- 'dng',
- 'tif',
+ "heic",
+ "rw2",
+ "tiff",
+ "arw",
+ "cr3",
+ "cr2",
+ "nef",
+ "psd",
+ "dng",
+ "tif",
];
diff --git a/apps/photos/src/constants/gallery.ts b/apps/photos/src/constants/gallery.ts
index 66b7759d69..9865d2e809 100644
--- a/apps/photos/src/constants/gallery.ts
+++ b/apps/photos/src/constants/gallery.ts
@@ -8,8 +8,8 @@ export const SPACE_BTW_DATES = 44;
export const SPACE_BTW_DATES_TO_IMAGE_CONTAINER_WIDTH_RATIO = 0.244;
export enum PLAN_PERIOD {
- MONTH = 'month',
- YEAR = 'year',
+ MONTH = "month",
+ YEAR = "year",
}
export const SYNC_INTERVAL_IN_MICROSECONDS = 1000 * 60 * 5; // 5 minutes
diff --git a/apps/photos/src/constants/mlConfig.ts b/apps/photos/src/constants/mlConfig.ts
index 60c763aa40..a1e8d39105 100644
--- a/apps/photos/src/constants/mlConfig.ts
+++ b/apps/photos/src/constants/mlConfig.ts
@@ -1,5 +1,5 @@
-import { JobConfig } from 'types/common/job';
-import { MLSearchConfig, MLSyncConfig } from 'types/machineLearning';
+import { JobConfig } from "types/common/job";
+import { MLSearchConfig, MLSyncConfig } from "types/machineLearning";
export const DEFAULT_ML_SYNC_JOB_CONFIG: JobConfig = {
intervalSec: 5,
@@ -10,46 +10,46 @@ export const DEFAULT_ML_SYNC_JOB_CONFIG: JobConfig = {
export const DEFAULT_ML_SYNC_CONFIG: MLSyncConfig = {
batchSize: 200,
- imageSource: 'Original',
+ imageSource: "Original",
faceDetection: {
- method: 'BlazeFace',
+ method: "BlazeFace",
minFaceSize: 32,
},
faceCrop: {
enabled: true,
- method: 'ArcFace',
+ method: "ArcFace",
padding: 0.25,
maxSize: 256,
blobOptions: {
- type: 'image/jpeg',
+ type: "image/jpeg",
quality: 0.8,
},
},
faceAlignment: {
- method: 'ArcFace',
+ method: "ArcFace",
},
faceEmbedding: {
- method: 'MobileFaceNet',
+ method: "MobileFaceNet",
faceSize: 112,
generateTsne: true,
},
faceClustering: {
- method: 'Hdbscan',
+ method: "Hdbscan",
minClusterSize: 3,
minSamples: 5,
clusterSelectionEpsilon: 0.6,
- clusterSelectionMethod: 'leaf',
+ clusterSelectionMethod: "leaf",
minInputSize: 50,
// maxDistanceInsideCluster: 0.4,
generateDebugInfo: true,
},
objectDetection: {
- method: 'SSDMobileNetV2',
+ method: "SSDMobileNetV2",
maxNumBoxes: 20,
minScore: 0.2,
},
sceneDetection: {
- method: 'ImageScene',
+ method: "ImageScene",
minScore: 0.1,
},
// tsne: {
diff --git a/apps/photos/src/constants/photoViewer.ts b/apps/photos/src/constants/photoViewer.ts
index 1a22dfeae2..b5f3d35d88 100644
--- a/apps/photos/src/constants/photoViewer.ts
+++ b/apps/photos/src/constants/photoViewer.ts
@@ -7,21 +7,21 @@ export const defaultLivePhotoDefaultOptions = {
};
export const photoSwipeV4Events = [
- 'beforeChange',
- 'afterChange',
- 'imageLoadComplete',
- 'resize',
- 'gettingData',
- 'mouseUsed',
- 'initialZoomIn',
- 'initialZoomInEnd',
- 'initialZoomOut',
- 'initialZoomOutEnd',
- 'parseVerticalMargin',
- 'close',
- 'unbindEvents',
- 'destroy',
- 'updateScrollOffset',
- 'preventDragEvent',
- 'shareLinkClick',
+ "beforeChange",
+ "afterChange",
+ "imageLoadComplete",
+ "resize",
+ "gettingData",
+ "mouseUsed",
+ "initialZoomIn",
+ "initialZoomInEnd",
+ "initialZoomOut",
+ "initialZoomOutEnd",
+ "parseVerticalMargin",
+ "close",
+ "unbindEvents",
+ "destroy",
+ "updateScrollOffset",
+ "preventDragEvent",
+ "shareLinkClick",
];
diff --git a/apps/photos/src/constants/publicCollection.ts b/apps/photos/src/constants/publicCollection.ts
index 731e30d5e0..5a1faad755 100644
--- a/apps/photos/src/constants/publicCollection.ts
+++ b/apps/photos/src/constants/publicCollection.ts
@@ -1,4 +1,4 @@
export enum REPORT_REASON {
- COPYRIGHT = 'COPYRIGHT',
- MALICIOUS_CONTENT = 'MALICIOUS_CONTENT',
+ COPYRIGHT = "COPYRIGHT",
+ MALICIOUS_CONTENT = "MALICIOUS_CONTENT",
}
diff --git a/apps/photos/src/constants/redirects.ts b/apps/photos/src/constants/redirects.ts
index d88cca89c0..443a07afc9 100644
--- a/apps/photos/src/constants/redirects.ts
+++ b/apps/photos/src/constants/redirects.ts
@@ -1,10 +1,10 @@
export enum REDIRECTS {
- ROADMAP = 'roadmap',
- FAMILIES = 'families',
+ ROADMAP = "roadmap",
+ FAMILIES = "families",
}
export const getRedirectURL = (redirect: REDIRECTS) => {
- const url = new URL('https://web.ente.io');
- url.searchParams.set('redirect', redirect);
+ const url = new URL("https://web.ente.io");
+ url.searchParams.set("redirect", redirect);
return url.href;
};
diff --git a/apps/photos/src/constants/upload.ts b/apps/photos/src/constants/upload.ts
index 0aff9bdbb0..6d9f63d788 100644
--- a/apps/photos/src/constants/upload.ts
+++ b/apps/photos/src/constants/upload.ts
@@ -1,57 +1,57 @@
-import { ENCRYPTION_CHUNK_SIZE } from '@ente/shared/crypto/constants';
-import { FILE_TYPE } from 'constants/file';
+import { ENCRYPTION_CHUNK_SIZE } from "@ente/shared/crypto/constants";
+import { FILE_TYPE } from "constants/file";
import {
FileTypeInfo,
ImportSuggestion,
Location,
ParsedExtractedMetadata,
-} from 'types/upload';
+} from "types/upload";
// list of format that were missed by type-detection for some files.
export const WHITELISTED_FILE_FORMATS: FileTypeInfo[] = [
- { fileType: FILE_TYPE.IMAGE, exactType: 'jpeg', mimeType: 'image/jpeg' },
- { fileType: FILE_TYPE.IMAGE, exactType: 'jpg', mimeType: 'image/jpeg' },
- { fileType: FILE_TYPE.VIDEO, exactType: 'webm', mimeType: 'video/webm' },
- { fileType: FILE_TYPE.VIDEO, exactType: 'mod', mimeType: 'video/mpeg' },
- { fileType: FILE_TYPE.VIDEO, exactType: 'mp4', mimeType: 'video/mp4' },
- { fileType: FILE_TYPE.IMAGE, exactType: 'gif', mimeType: 'image/gif' },
- { fileType: FILE_TYPE.VIDEO, exactType: 'dv', mimeType: 'video/x-dv' },
+ { fileType: FILE_TYPE.IMAGE, exactType: "jpeg", mimeType: "image/jpeg" },
+ { fileType: FILE_TYPE.IMAGE, exactType: "jpg", mimeType: "image/jpeg" },
+ { fileType: FILE_TYPE.VIDEO, exactType: "webm", mimeType: "video/webm" },
+ { fileType: FILE_TYPE.VIDEO, exactType: "mod", mimeType: "video/mpeg" },
+ { fileType: FILE_TYPE.VIDEO, exactType: "mp4", mimeType: "video/mp4" },
+ { fileType: FILE_TYPE.IMAGE, exactType: "gif", mimeType: "image/gif" },
+ { fileType: FILE_TYPE.VIDEO, exactType: "dv", mimeType: "video/x-dv" },
{
fileType: FILE_TYPE.VIDEO,
- exactType: 'wmv',
- mimeType: 'video/x-ms-asf',
+ exactType: "wmv",
+ mimeType: "video/x-ms-asf",
},
{
fileType: FILE_TYPE.VIDEO,
- exactType: 'hevc',
- mimeType: 'video/hevc',
+ exactType: "hevc",
+ mimeType: "video/hevc",
},
{
fileType: FILE_TYPE.IMAGE,
- exactType: 'raf',
- mimeType: 'image/x-fuji-raf',
+ exactType: "raf",
+ mimeType: "image/x-fuji-raf",
},
{
fileType: FILE_TYPE.IMAGE,
- exactType: 'orf',
- mimeType: 'image/x-olympus-orf',
+ exactType: "orf",
+ mimeType: "image/x-olympus-orf",
},
{
fileType: FILE_TYPE.IMAGE,
- exactType: 'crw',
- mimeType: 'image/x-canon-crw',
+ exactType: "crw",
+ mimeType: "image/x-canon-crw",
},
{
fileType: FILE_TYPE.VIDEO,
- exactType: 'mov',
- mimeType: 'video/quicktime',
+ exactType: "mov",
+ mimeType: "video/quicktime",
},
];
-export const KNOWN_NON_MEDIA_FORMATS = ['xmp', 'html', 'txt'];
+export const KNOWN_NON_MEDIA_FORMATS = ["xmp", "html", "txt"];
-export const EXIFLESS_FORMATS = ['gif', 'bmp'];
+export const EXIFLESS_FORMATS = ["gif", "bmp"];
// this is the chunk size of the un-encrypted file which is read and encrypted before uploading it as a single part.
export const MULTIPART_PART_SIZE = 20 * 1024 * 1024;
@@ -59,7 +59,7 @@ export const MULTIPART_PART_SIZE = 20 * 1024 * 1024;
export const FILE_READER_CHUNK_SIZE = ENCRYPTION_CHUNK_SIZE;
export const FILE_CHUNKS_COMBINED_FOR_A_UPLOAD_PART = Math.floor(
- MULTIPART_PART_SIZE / FILE_READER_CHUNK_SIZE
+ MULTIPART_PART_SIZE / FILE_READER_CHUNK_SIZE,
);
export const RANDOM_PERCENTAGE_PROGRESS_FOR_PUT = () => 90 + 10 * Math.random();
@@ -93,9 +93,9 @@ export enum UPLOAD_RESULT {
}
export enum PICKED_UPLOAD_TYPE {
- FILES = 'files',
- FOLDERS = 'folders',
- ZIPS = 'zips',
+ FILES = "files",
+ FOLDERS = "folders",
+ ZIPS = "zips",
}
export const MAX_FILE_SIZE_SUPPORTED = 4 * 1024 * 1024 * 1024; // 4 GB
@@ -112,36 +112,36 @@ export const NULL_EXTRACTED_METADATA: ParsedExtractedMetadata = {
export const A_SEC_IN_MICROSECONDS = 1e6;
export const DEFAULT_IMPORT_SUGGESTION: ImportSuggestion = {
- rootFolderName: '',
+ rootFolderName: "",
hasNestedFolders: false,
hasRootLevelFileWithFolder: false,
};
export const BLACK_THUMBNAIL_BASE64 =
- '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEB' +
- 'AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQ' +
- 'EBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARC' +
- 'ACWASwDAREAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF' +
- 'BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk' +
- '6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztL' +
- 'W2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAA' +
- 'AAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVY' +
- 'nLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImK' +
- 'kpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oAD' +
- 'AMBAAIRAxEAPwD/AD/6ACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA' +
- 'CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg' +
- 'AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKAC' +
- 'gAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo' +
- 'AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg' +
- 'AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg' +
- 'AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA' +
- 'CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA' +
- 'CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoA' +
- 'KACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg' +
- 'AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo' +
- 'AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA' +
- 'CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAK' +
- 'ACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoA' +
- 'KACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo' +
- 'AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo' +
- 'AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgD/9k=';
+ "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEB" +
+ "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQ" +
+ "EBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARC" +
+ "ACWASwDAREAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF" +
+ "BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk" +
+ "6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztL" +
+ "W2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAA" +
+ "AAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVY" +
+ "nLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImK" +
+ "kpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oAD" +
+ "AMBAAIRAxEAPwD/AD/6ACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA" +
+ "CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg" +
+ "AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKAC" +
+ "gAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo" +
+ "AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg" +
+ "AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg" +
+ "AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA" +
+ "CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA" +
+ "CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoA" +
+ "KACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg" +
+ "AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo" +
+ "AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA" +
+ "CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAK" +
+ "ACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoA" +
+ "KACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo" +
+ "AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo" +
+ "AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgD/9k=";
diff --git a/apps/photos/src/contexts/uploadProgress.tsx b/apps/photos/src/contexts/uploadProgress.tsx
index a7096f0956..fe5f733b86 100644
--- a/apps/photos/src/contexts/uploadProgress.tsx
+++ b/apps/photos/src/contexts/uploadProgress.tsx
@@ -1,11 +1,11 @@
-import { UPLOAD_STAGES } from 'constants/upload';
-import { createContext } from 'react';
+import { UPLOAD_STAGES } from "constants/upload";
+import { createContext } from "react";
import {
- UploadCounter,
InProgressUpload,
- UploadFileNames,
SegregatedFinishedUploads,
-} from 'types/upload/ui';
+ UploadCounter,
+ UploadFileNames,
+} from "types/upload/ui";
interface UploadProgressContextType {
open: boolean;
@@ -36,7 +36,7 @@ const defaultUploadProgressContext: UploadProgressContextType = {
setExpanded: () => null,
};
const UploadProgressContext = createContext<UploadProgressContextType>(
- defaultUploadProgressContext
+ defaultUploadProgressContext,
);
export default UploadProgressContext;
diff --git a/apps/photos/src/pages/404.tsx b/apps/photos/src/pages/404.tsx
index 6d10e4dfb5..edb4ae7f75 100644
--- a/apps/photos/src/pages/404.tsx
+++ b/apps/photos/src/pages/404.tsx
@@ -1,8 +1,8 @@
-import NotFoundPage from '@ente/shared/next/pages/404';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import { APPS } from "@ente/shared/apps/constants";
+import NotFoundPage from "@ente/shared/next/pages/404";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function NotFound() {
const appContext = useContext(AppContext);
diff --git a/apps/photos/src/pages/_app.tsx b/apps/photos/src/pages/_app.tsx
index 39cfbb3def..5d246c0550 100644
--- a/apps/photos/src/pages/_app.tsx
+++ b/apps/photos/src/pages/_app.tsx
@@ -1,84 +1,84 @@
-import React, { createContext, useEffect, useRef, useState } from 'react';
-import AppNavbar from '@ente/shared/components/Navbar/app';
-import { t } from 'i18next';
-
-import { useRouter } from 'next/router';
-import { Overlay } from '@ente/shared/components/Container';
-import 'bootstrap/dist/css/bootstrap.min.css';
-import 'photoswipe/dist/photoswipe.css';
-import 'styles/global.css';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { logError } from '@ente/shared/sentry';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import HTTPService from '@ente/shared/network/HTTPService';
-import Head from 'next/head';
-import { eventBus, Events } from '@ente/shared/events';
-import mlWorkManager from 'services/machineLearning/mlWorkManager';
+import AppNavbar from "@ente/shared/components/Navbar/app";
+import { t } from "i18next";
+import { createContext, useEffect, useRef, useState } from "react";
+
+import { setupI18n } from "@/ui/i18n";
+import { CacheProvider } from "@emotion/react";
import {
- getMLSearchConfig,
- updateMLSearchConfig,
-} from 'utils/machineLearning/config';
-import LoadingBar from 'react-top-loading-bar';
-import DialogBox from '@ente/shared/components/DialogBox';
-import DialogBoxV2 from '@ente/shared/components/DialogBoxV2';
-import { ThemeProvider } from '@mui/material/styles';
-import { MessageContainer } from '@ente/shared/components/MessageContainer';
-import { CssBaseline, useMediaQuery } from '@mui/material';
+ APP_TITLES,
+ APPS,
+ CLIENT_PACKAGE_NAMES,
+} from "@ente/shared/apps/constants";
+import { EnteAppProps } from "@ente/shared/apps/types";
+import { Overlay } from "@ente/shared/components/Container";
+import DialogBox from "@ente/shared/components/DialogBox";
import {
- SetDialogBoxAttributes,
DialogBoxAttributes,
-} from '@ente/shared/components/DialogBox/types';
+ SetDialogBoxAttributes,
+} from "@ente/shared/components/DialogBox/types";
+import DialogBoxV2 from "@ente/shared/components/DialogBoxV2";
import {
DialogBoxAttributesV2,
SetDialogBoxAttributesV2,
-} from '@ente/shared/components/DialogBoxV2/types';
-import {
- getFamilyPortalRedirectURL,
- getRoadmapRedirectURL,
- updateMapEnabledStatus,
-} from 'services/userService';
-import { CustomError } from '@ente/shared/error';
-import { addLogLine } from '@ente/shared/logging';
+} from "@ente/shared/components/DialogBoxV2/types";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import { MessageContainer } from "@ente/shared/components/MessageContainer";
+import { PHOTOS_PAGES as PAGES } from "@ente/shared/constants/pages";
+import ElectronAPIs from "@ente/shared/electron";
+import { AppUpdateInfo } from "@ente/shared/electron/types";
+import { CustomError } from "@ente/shared/error";
+import { eventBus, Events } from "@ente/shared/events";
+import { useLocalState } from "@ente/shared/hooks/useLocalState";
+import { addLogLine } from "@ente/shared/logging";
import {
clearLogsIfLocalStorageLimitExceeded,
logStartupMessage,
-} from '@ente/shared/logging/web';
-import isElectron from 'is-electron';
-import ElectronAPIs from '@ente/shared/electron';
+} from "@ente/shared/logging/web";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { logError } from "@ente/shared/sentry";
+import { getData, LS_KEYS } from "@ente/shared/storage/localStorage";
import {
- getUpdateAvailableForDownloadMessage,
- getUpdateReadyToInstallMessage,
-} from 'utils/ui';
-import Notification from 'components/Notification';
+ getLocalMapEnabled,
+ getToken,
+ setLocalMapEnabled,
+} from "@ente/shared/storage/localStorage/helpers";
+import { getTheme } from "@ente/shared/themes";
+import { THEME_COLOR } from "@ente/shared/themes/constants";
+import createEmotionCache from "@ente/shared/themes/createEmotionCache";
+import { SetTheme } from "@ente/shared/themes/types";
+import ArrowForward from "@mui/icons-material/ArrowForward";
+import { CssBaseline, useMediaQuery } from "@mui/material";
+import { ThemeProvider } from "@mui/material/styles";
+import "bootstrap/dist/css/bootstrap.min.css";
+import Notification from "components/Notification";
+import { REDIRECTS } from "constants/redirects";
+import isElectron from "is-electron";
+import Head from "next/head";
+import { useRouter } from "next/router";
+import "photoswipe/dist/photoswipe.css";
+import LoadingBar from "react-top-loading-bar";
+import DownloadManager from "services/download";
+import exportService from "services/export";
+import mlWorkManager from "services/machineLearning/mlWorkManager";
+import {
+ getFamilyPortalRedirectURL,
+ getRoadmapRedirectURL,
+ updateMapEnabledStatus,
+} from "services/userService";
+import "styles/global.css";
import {
NotificationAttributes,
SetNotificationAttributes,
-} from 'types/Notification';
-import ArrowForward from '@mui/icons-material/ArrowForward';
-import { CacheProvider } from '@emotion/react';
+} from "types/Notification";
+import { isExportInProgress } from "utils/export";
import {
- APP_TITLES,
- APPS,
- CLIENT_PACKAGE_NAMES,
-} from '@ente/shared/apps/constants';
-import exportService from 'services/export';
-import { REDIRECTS } from 'constants/redirects';
+ getMLSearchConfig,
+ updateMLSearchConfig,
+} from "utils/machineLearning/config";
import {
- getLocalMapEnabled,
- getToken,
- setLocalMapEnabled,
-} from '@ente/shared/storage/localStorage/helpers';
-import { isExportInProgress } from 'utils/export';
-import { EnteAppProps } from '@ente/shared/apps/types';
-import createEmotionCache from '@ente/shared/themes/createEmotionCache';
-import { THEME_COLOR } from '@ente/shared/themes/constants';
-import { SetTheme } from '@ente/shared/themes/types';
-import { setupI18n } from '@/ui/i18n';
-import { useLocalState } from '@ente/shared/hooks/useLocalState';
-import { PHOTOS_PAGES as PAGES } from '@ente/shared/constants/pages';
-import { getTheme } from '@ente/shared/themes';
-import { AppUpdateInfo } from '@ente/shared/electron/types';
-import DownloadManager from 'services/download';
+ getUpdateAvailableForDownloadMessage,
+ getUpdateReadyToInstallMessage,
+} from "utils/ui";
const redirectMap = new Map([
[REDIRECTS.ROADMAP, getRoadmapRedirectURL],
@@ -128,7 +128,7 @@ export default function App(props: EnteAppProps) {
const [isI18nReady, setIsI18nReady] = useState<boolean>(false);
const [loading, setLoading] = useState(false);
const [offline, setOffline] = useState(
- typeof window !== 'undefined' && !window.navigator.onLine
+ typeof window !== "undefined" && !window.navigator.onLine,
);
const [showNavbar, setShowNavBar] = useState(false);
const [sharedFiles, setSharedFiles] = useState<File[]>(null);
@@ -146,18 +146,18 @@ export default function App(props: EnteAppProps) {
const [isFolderSyncRunning, setIsFolderSyncRunning] = useState(false);
const [watchFolderView, setWatchFolderView] = useState(false);
const [watchFolderFiles, setWatchFolderFiles] = useState<FileList>(null);
- const isMobile = useMediaQuery('(max-width:428px)');
+ const isMobile = useMediaQuery("(max-width:428px)");
const [notificationView, setNotificationView] = useState(false);
const closeNotification = () => setNotificationView(false);
const [notificationAttributes, setNotificationAttributes] =
useState<NotificationAttributes>(null);
const [themeColor, setThemeColor] = useLocalState(
LS_KEYS.THEME,
- THEME_COLOR.DARK
+ THEME_COLOR.DARK,
);
const [isCFProxyDisabled, setIsCFProxyDisabled] = useLocalState(
LS_KEYS.CF_PROXY_DISABLED,
- false
+ false,
);
useEffect(() => {
@@ -165,7 +165,7 @@ export default function App(props: EnteAppProps) {
setupI18n().finally(() => setIsI18nReady(true));
// set client package name in headers
HTTPService.setHeaders({
- 'X-Client-Package': CLIENT_PACKAGE_NAMES.get(APPS.PHOTOS),
+ "X-Client-Package": CLIENT_PACKAGE_NAMES.get(APPS.PHOTOS),
});
// setup logging
clearLogsIfLocalStorageLimitExceeded();
@@ -177,16 +177,18 @@ export default function App(props: EnteAppProps) {
const showUpdateDialog = (updateInfo: AppUpdateInfo) => {
if (updateInfo.autoUpdatable) {
setDialogMessage(
- getUpdateReadyToInstallMessage(updateInfo)
+ getUpdateReadyToInstallMessage(updateInfo),
);
} else {
setNotificationAttributes({
endIcon: <ArrowForward />,
- variant: 'secondary',
- message: t('UPDATE_AVAILABLE'),
+ variant: "secondary",
+ message: t("UPDATE_AVAILABLE"),
onClick: () =>
setDialogMessage(
- getUpdateAvailableForDownloadMessage(updateInfo)
+ getUpdateAvailableForDownloadMessage(
+ updateInfo,
+ ),
),
});
}
@@ -205,7 +207,7 @@ export default function App(props: EnteAppProps) {
setMlSearchEnabled(mlSearchConfig.enabled);
mlWorkManager.setMlSearchEnabled(mlSearchConfig.enabled);
} catch (e) {
- logError(e, 'Error while loading mlSearchEnabled');
+ logError(e, "Error while loading mlSearchEnabled");
}
};
loadMlSearchState();
@@ -215,7 +217,7 @@ export default function App(props: EnteAppProps) {
mlWorkManager.setMlSearchEnabled(false);
});
} catch (e) {
- logError(e, 'Error while subscribing to logout event');
+ logError(e, "Error while subscribing to logout event");
}
}, []);
@@ -229,11 +231,11 @@ export default function App(props: EnteAppProps) {
}
const initExport = async () => {
try {
- addLogLine('init export');
+ addLogLine("init export");
const token = getToken();
if (!token) {
addLogLine(
- 'User not logged in, not starting export continuous sync job'
+ "User not logged in, not starting export continuous sync job",
);
return;
}
@@ -243,17 +245,17 @@ export default function App(props: EnteAppProps) {
return;
}
const exportRecord = await exportService.getExportRecord(
- exportSettings.folder
+ exportSettings.folder,
);
if (exportSettings.continuousExport) {
exportService.enableContinuousExport();
}
if (isExportInProgress(exportRecord.stage)) {
- addLogLine('export was in progress, resuming');
+ addLogLine("export was in progress, resuming");
exportService.scheduleExport();
}
} catch (e) {
- logError(e, 'init export failed');
+ logError(e, "init export failed");
}
};
initExport();
@@ -262,7 +264,7 @@ export default function App(props: EnteAppProps) {
exportService.disableContinuousExport();
});
} catch (e) {
- logError(e, 'Error while subscribing to logout event');
+ logError(e, "Error while subscribing to logout event");
}
}, []);
@@ -273,10 +275,10 @@ export default function App(props: EnteAppProps) {
useEffect(() => {
if (isI18nReady) {
console.log(
- `%c${t('CONSOLE_WARNING_STOP')}`,
- 'color: red; font-size: 52px;'
+ `%c${t("CONSOLE_WARNING_STOP")}`,
+ "color: red; font-size: 52px;",
);
- console.log(`%c${t('CONSOLE_WARNING_DESC')}`, 'font-size: 20px;');
+ console.log(`%c${t("CONSOLE_WARNING_DESC")}`, "font-size: 20px;");
}
}, [isI18nReady]);
@@ -284,19 +286,19 @@ export default function App(props: EnteAppProps) {
const redirectTo = async (redirect) => {
if (
redirectMap.has(redirect) &&
- typeof redirectMap.get(redirect) === 'function'
+ typeof redirectMap.get(redirect) === "function"
) {
const redirectAction = redirectMap.get(redirect);
window.location.href = await redirectAction();
} else {
- logError(CustomError.BAD_REQUEST, 'invalid redirection', {
+ logError(CustomError.BAD_REQUEST, "invalid redirection", {
redirect,
});
}
};
const query = new URLSearchParams(window.location.search);
- const redirectName = query.get('redirect');
+ const redirectName = query.get("redirect");
if (redirectName) {
const user = getData(LS_KEYS.USER);
if (user?.token) {
@@ -306,8 +308,8 @@ export default function App(props: EnteAppProps) {
}
}
- router.events.on('routeChangeStart', (url: string) => {
- const newPathname = url.split('?')[0] as PAGES;
+ router.events.on("routeChangeStart", (url: string) => {
+ const newPathname = url.split("?")[0] as PAGES;
if (window.location.pathname !== newPathname) {
setLoading(true);
}
@@ -319,21 +321,21 @@ export default function App(props: EnteAppProps) {
// https://github.com/vercel/next.js/issues/2476#issuecomment-573460710
// eslint-disable-next-line no-throw-literal
- throw 'Aborting route change, redirection in process....';
+ throw "Aborting route change, redirection in process....";
}
}
});
- router.events.on('routeChangeComplete', () => {
+ router.events.on("routeChangeComplete", () => {
setLoading(false);
});
- window.addEventListener('online', setUserOnline);
- window.addEventListener('offline', setUserOffline);
+ window.addEventListener("online", setUserOnline);
+ window.addEventListener("offline", setUserOffline);
return () => {
- window.removeEventListener('online', setUserOnline);
- window.removeEventListener('offline', setUserOffline);
+ window.removeEventListener("online", setUserOnline);
+ window.removeEventListener("offline", setUserOffline);
};
}, [redirectName]);
@@ -358,7 +360,7 @@ export default function App(props: EnteAppProps) {
setMlSearchEnabled(enabled);
mlWorkManager.setMlSearchEnabled(enabled);
} catch (e) {
- logError(e, 'Error while updating mlSearchEnabled');
+ logError(e, "Error while updating mlSearchEnabled");
}
};
@@ -368,7 +370,7 @@ export default function App(props: EnteAppProps) {
setLocalMapEnabled(enabled);
setMapEnabled(enabled);
} catch (e) {
- logError(e, 'Error while updating mapEnabled');
+ logError(e, "Error while updating mapEnabled");
}
};
@@ -388,9 +390,9 @@ export default function App(props: EnteAppProps) {
const somethingWentWrong = () =>
setDialogMessage({
- title: t('ERROR'),
- close: { variant: 'critical' },
- content: t('UNKNOWN_ERROR'),
+ title: t("ERROR"),
+ close: { variant: "critical" },
+ content: t("UNKNOWN_ERROR"),
});
return (
@@ -398,7 +400,7 @@ export default function App(props: EnteAppProps) {
<Head>
<title>
{isI18nReady
- ? t('TITLE', { context: APPS.PHOTOS })
+ ? t("TITLE", { context: APPS.PHOTOS })
: APP_TITLES.get(APPS.PHOTOS)}
</title>
<meta
@@ -411,18 +413,18 @@ export default function App(props: EnteAppProps) {
<CssBaseline enableColorScheme />
{showNavbar && <AppNavbar isMobile={isMobile} />}
<MessageContainer>
- {offline && t('OFFLINE_MSG')}
+ {offline && t("OFFLINE_MSG")}
</MessageContainer>
{sharedFiles &&
- (router.pathname === '/gallery' ? (
+ (router.pathname === "/gallery" ? (
<MessageContainer>
- {t('files_to_be_uploaded', {
+ {t("files_to_be_uploaded", {
count: sharedFiles.length,
})}
</MessageContainer>
) : (
<MessageContainer>
- {t('login_to_upload_files', {
+ {t("login_to_upload_files", {
count: sharedFiles.length,
})}
</MessageContainer>
@@ -475,16 +477,18 @@ export default function App(props: EnteAppProps) {
updateMapEnabled,
isCFProxyDisabled,
setIsCFProxyDisabled,
- }}>
+ }}
+ >
{(loading || !isI18nReady) && (
<Overlay
sx={(theme) => ({
- display: 'flex',
- justifyContent: 'center',
- alignItems: 'center',
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
zIndex: 2000,
backgroundColor: theme.colors.background.base,
- })}>
+ })}
+ >
<EnteSpinner />
</Overlay>
)}
diff --git a/apps/photos/src/pages/_document.tsx b/apps/photos/src/pages/_document.tsx
index c3686b6be9..09d4d57823 100644
--- a/apps/photos/src/pages/_document.tsx
+++ b/apps/photos/src/pages/_document.tsx
@@ -1,6 +1,6 @@
import DocumentPage, {
EnteDocumentProps,
-} from '@ente/shared/next/pages/_document';
+} from "@ente/shared/next/pages/_document";
export default function Document(props: EnteDocumentProps) {
return <DocumentPage {...props} />;
diff --git a/apps/photos/src/pages/_error.tsx b/apps/photos/src/pages/_error.tsx
index 6c068e34b8..bf1bb89be3 100644
--- a/apps/photos/src/pages/_error.tsx
+++ b/apps/photos/src/pages/_error.tsx
@@ -1,8 +1,8 @@
-import ErrorPage from '@ente/shared/next/pages/_error';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import { APPS } from "@ente/shared/apps/constants";
+import ErrorPage from "@ente/shared/next/pages/_error";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Error() {
const appContext = useContext(AppContext);
diff --git a/apps/photos/src/pages/change-email/index.tsx b/apps/photos/src/pages/change-email/index.tsx
index b5df67d450..bb4c111dcc 100644
--- a/apps/photos/src/pages/change-email/index.tsx
+++ b/apps/photos/src/pages/change-email/index.tsx
@@ -1,8 +1,8 @@
-import ChangeEmailPage from '@ente/accounts/pages/change-email';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import ChangeEmailPage from "@ente/accounts/pages/change-email";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function ChangeEmail() {
const appContext = useContext(AppContext);
diff --git a/apps/photos/src/pages/change-password/index.tsx b/apps/photos/src/pages/change-password/index.tsx
index c71844119a..33e44c9389 100644
--- a/apps/photos/src/pages/change-password/index.tsx
+++ b/apps/photos/src/pages/change-password/index.tsx
@@ -1,8 +1,8 @@
-import ChangePasswordPage from '@ente/accounts/pages/change-password';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import ChangePasswordPage from "@ente/accounts/pages/change-password";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function ChangePassword() {
const appContext = useContext(AppContext);
diff --git a/apps/photos/src/pages/credentials/index.tsx b/apps/photos/src/pages/credentials/index.tsx
index 2155c5cc12..6e66120743 100644
--- a/apps/photos/src/pages/credentials/index.tsx
+++ b/apps/photos/src/pages/credentials/index.tsx
@@ -1,8 +1,8 @@
-import CredentialPage from '@ente/accounts/pages/credentials';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import CredentialPage from "@ente/accounts/pages/credentials";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Credential() {
const appContext = useContext(AppContext);
diff --git a/apps/photos/src/pages/deduplicate/index.tsx b/apps/photos/src/pages/deduplicate/index.tsx
index 8618490d4d..cbd297f78c 100644
--- a/apps/photos/src/pages/deduplicate/index.tsx
+++ b/apps/photos/src/pages/deduplicate/index.tsx
@@ -1,41 +1,40 @@
-import { t } from 'i18next';
-
-import PhotoFrame from 'components/PhotoFrame';
-import { ALL_SECTION } from 'constants/collection';
-import { AppContext } from 'pages/_app';
-import { createContext, useContext, useEffect, useState } from 'react';
-import { getDuplicates, Duplicate } from 'services/deduplicationService';
-import { getLocalFiles, syncFiles, trashFiles } from 'services/fileService';
-import { SelectedState } from 'types/gallery';
-
-import { ApiError } from '@ente/shared/error';
-import { constructFileToCollectionMap, getSelectedFiles } from 'utils/file';
-import {
- DeduplicateContextType,
- DefaultDeduplicateContext,
-} from 'types/deduplicate';
-import Router from 'next/router';
-import DeduplicateOptions from 'components/pages/dedupe/SelectedFileOptions';
-import { PHOTOS_PAGES as PAGES } from '@ente/shared/constants/pages';
-import router from 'next/router';
-import { getKey, SESSION_KEYS } from '@ente/shared/storage/sessionStorage';
-import { styled } from '@mui/material';
+import { t } from "i18next";
+
+import PhotoFrame from "components/PhotoFrame";
+import { ALL_SECTION } from "constants/collection";
+import { AppContext } from "pages/_app";
+import { createContext, useContext, useEffect, useState } from "react";
+import { Duplicate, getDuplicates } from "services/deduplicationService";
+import { getLocalFiles, syncFiles, trashFiles } from "services/fileService";
+import { SelectedState } from "types/gallery";
+
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import { PHOTOS_PAGES as PAGES } from "@ente/shared/constants/pages";
+import { ApiError } from "@ente/shared/error";
+import useMemoSingleThreaded from "@ente/shared/hooks/useMemoSingleThreaded";
+import InMemoryStore, { MS_KEYS } from "@ente/shared/storage/InMemoryStore";
+import { SESSION_KEYS, getKey } from "@ente/shared/storage/sessionStorage";
+import { styled } from "@mui/material";
+import Typography from "@mui/material/Typography";
+import { HttpStatusCode } from "axios";
+import DeduplicateOptions from "components/pages/dedupe/SelectedFileOptions";
+import { default as Router, default as router } from "next/router";
import {
getAllLatestCollections,
getLocalCollections,
-} from 'services/collectionService';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import Typography from '@mui/material/Typography';
-import useMemoSingleThreaded from '@ente/shared/hooks/useMemoSingleThreaded';
-import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
-import { HttpStatusCode } from 'axios';
-import { syncTrash } from 'services/trashService';
+} from "services/collectionService";
+import { syncTrash } from "services/trashService";
+import {
+ DeduplicateContextType,
+ DefaultDeduplicateContext,
+} from "types/deduplicate";
+import { constructFileToCollectionMap, getSelectedFiles } from "utils/file";
export const DeduplicateContext = createContext<DeduplicateContextType>(
- DefaultDeduplicateContext
+ DefaultDeduplicateContext,
);
-export const Info = styled('div')`
+export const Info = styled("div")`
padding: 24px;
font-size: 18px;
`;
@@ -45,7 +44,7 @@ export default function Deduplicate() {
useContext(AppContext);
const [duplicates, setDuplicates] = useState<Duplicate[]>(null);
const [collectionNameMap, setCollectionNameMap] = useState(
- new Map<number, string>()
+ new Map<number, string>(),
);
const [selected, setSelected] = useState<SelectedState>({
count: 0,
@@ -131,7 +130,7 @@ export default function Deduplicate() {
// there in an ad-hoc manner. For now, this fixes the issue with the
// UI not updating if the user deletes only some of the duplicates.
const collections = await getAllLatestCollections();
- await syncFiles('normal', collections, () => {});
+ await syncFiles("normal", collections, () => {});
await syncTrash(collections, () => {});
} catch (e) {
if (
@@ -139,17 +138,17 @@ export default function Deduplicate() {
e.httpStatusCode === HttpStatusCode.Forbidden
) {
setDialogMessage({
- title: t('ERROR'),
+ title: t("ERROR"),
- close: { variant: 'critical' },
- content: t('NOT_FILE_OWNER'),
+ close: { variant: "critical" },
+ content: t("NOT_FILE_OWNER"),
});
} else {
setDialogMessage({
- title: t('ERROR'),
+ title: t("ERROR"),
- close: { variant: 'critical' },
- content: t('UNKNOWN_ERROR'),
+ close: { variant: "critical" },
+ content: t("UNKNOWN_ERROR"),
});
}
} finally {
@@ -176,14 +175,15 @@ export default function Deduplicate() {
...DefaultDeduplicateContext,
collectionNameMap,
isOnDeduplicatePage: true,
- }}>
+ }}
+ >
{duplicateFiles.length > 0 && (
- <Info>{t('DEDUPLICATE_BASED_ON_SIZE')}</Info>
+ <Info>{t("DEDUPLICATE_BASED_ON_SIZE")}</Info>
)}
{duplicateFiles.length === 0 ? (
<VerticallyCentered>
<Typography variant="large" color="text.muted">
- {t('NO_DUPLICATES_FOUND')}
+ {t("NO_DUPLICATES_FOUND")}
</Typography>
</VerticallyCentered>
) : (
diff --git a/apps/photos/src/pages/gallery/index.tsx b/apps/photos/src/pages/gallery/index.tsx
index e3bf2d15d8..dc043a7daa 100644
--- a/apps/photos/src/pages/gallery/index.tsx
+++ b/apps/photos/src/pages/gallery/index.tsx
@@ -1,3 +1,11 @@
+import {
+ SESSION_KEYS,
+ clearKeys,
+ getKey,
+} from "@ente/shared/storage/sessionStorage";
+import { Typography, styled } from "@mui/material";
+import { t } from "i18next";
+import { useRouter } from "next/router";
import {
createContext,
useContext,
@@ -5,47 +13,43 @@ import {
useMemo,
useRef,
useState,
-} from 'react';
-import { useRouter } from 'next/router';
-import {
- clearKeys,
- getKey,
- SESSION_KEYS,
-} from '@ente/shared/storage/sessionStorage';
-import { getLocalFiles, syncFiles } from 'services/fileService';
-import { styled, Typography } from '@mui/material';
+} from "react";
import {
- getAllLatestCollections,
- getFavItemIds,
+ constructEmailList,
createAlbum,
+ getAllLatestCollections,
+ getAllLocalCollections,
getCollectionSummaries,
- constructEmailList,
- getSectionSummaries,
+ getFavItemIds,
getHiddenItemsSummary,
- getAllLocalCollections,
-} from 'services/collectionService';
-import { t } from 'i18next';
+ getSectionSummaries,
+} from "services/collectionService";
+import { getLocalFiles, syncFiles } from "services/fileService";
-import { checkSubscriptionPurchase } from 'utils/billing';
+import { checkSubscriptionPurchase } from "utils/billing";
-import FullScreenDropZone from 'components/FullScreenDropZone';
-import Sidebar from 'components/Sidebar';
-import { mergeMaps, preloadImage } from 'utils/common';
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
import {
isFirstLogin,
justSignedUp,
setIsFirstLogin,
setJustSignedUp,
-} from '@ente/shared/storage/localStorage/helpers';
+} from "@ente/shared/storage/localStorage/helpers";
+import CollectionSelector, {
+ CollectionSelectorAttributes,
+} from "components/Collections/CollectionSelector";
+import FullScreenDropZone from "components/FullScreenDropZone";
+import { LoadingOverlay } from "components/LoadingOverlay";
+import PhotoFrame from "components/PhotoFrame";
+import Sidebar from "components/Sidebar";
+import SelectedFileOptions from "components/pages/gallery/SelectedFileOptions";
+import { useDropzone } from "react-dropzone";
import {
isTokenValid,
syncMapEnabled,
validateKey,
-} from 'services/userService';
-import { useDropzone } from 'react-dropzone';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { LoadingOverlay } from 'components/LoadingOverlay';
-import PhotoFrame from 'components/PhotoFrame';
+} from "services/userService";
+import { mergeMaps, preloadImage } from "utils/common";
import {
FILE_OPS_TYPE,
constructFileToCollectionMap,
@@ -54,93 +58,89 @@ import {
handleFileOps,
mergeMetadata,
sortFiles,
-} from 'utils/file';
-import SelectedFileOptions from 'components/pages/gallery/SelectedFileOptions';
-import CollectionSelector, {
- CollectionSelectorAttributes,
-} from 'components/Collections/CollectionSelector';
+} from "utils/file";
+import { PHOTOS_PAGES as PAGES } from "@ente/shared/constants/pages";
+import { CustomError } from "@ente/shared/error";
+import { logError } from "@ente/shared/sentry";
import CollectionNamer, {
CollectionNamerAttributes,
-} from 'components/Collections/CollectionNamer';
-import PlanSelector from 'components/pages/gallery/PlanSelector';
-import Uploader from 'components/Upload/Uploader';
+} from "components/Collections/CollectionNamer";
+import Uploader from "components/Upload/Uploader";
+import PlanSelector from "components/pages/gallery/PlanSelector";
import {
ALL_SECTION,
ARCHIVE_SECTION,
CollectionSummaryType,
- HIDDEN_ITEMS_SECTION,
DUMMY_UNCATEGORIZED_COLLECTION,
+ HIDDEN_ITEMS_SECTION,
TRASH_SECTION,
-} from 'constants/collection';
-import { AppContext } from 'pages/_app';
-import { CustomError } from '@ente/shared/error';
-import { PHOTOS_PAGES as PAGES } from '@ente/shared/constants/pages';
+} from "constants/collection";
+import { AppContext } from "pages/_app";
+import { getLocalTrashedFiles, syncTrash } from "services/trashService";
import {
COLLECTION_OPS_TYPE,
- handleCollectionOps,
+ constructCollectionNameMap,
getArchivedCollections,
+ getDefaultHiddenCollectionIDs,
+ getSelectedCollection,
+ handleCollectionOps,
hasNonSystemCollections,
splitNormalAndHiddenCollections,
- constructCollectionNameMap,
- getSelectedCollection,
- getDefaultHiddenCollectionIDs,
-} from 'utils/collection';
-import { logError } from '@ente/shared/sentry';
-import { getLocalTrashedFiles, syncTrash } from 'services/trashService';
-
+} from "utils/collection";
+
+import { APPS } from "@ente/shared/apps/constants";
+import { CenteredFlex } from "@ente/shared/components/Container";
+import ElectronAPIs from "@ente/shared/electron";
+import useEffectSingleThreaded from "@ente/shared/hooks/useEffectSingleThreaded";
+import useFileInput from "@ente/shared/hooks/useFileInput";
+import useMemoSingleThreaded from "@ente/shared/hooks/useMemoSingleThreaded";
+import InMemoryStore, { MS_KEYS } from "@ente/shared/storage/InMemoryStore";
+import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
+import { User } from "@ente/shared/user/types";
+import AuthenticateUserModal from "components/AuthenticateUserModal";
+import Collections from "components/Collections";
+import ExportModal from "components/ExportModal";
+import {
+ FilesDownloadProgress,
+ FilesDownloadProgressAttributes,
+} from "components/FilesDownloadProgress";
import FixCreationTime, {
FixCreationTimeAttributes,
-} from 'components/FixCreationTime';
-import { Collection, CollectionSummaries } from 'types/collection';
-import { EnteFile } from 'types/file';
+} from "components/FixCreationTime";
+import GalleryEmptyState from "components/GalleryEmptyState";
+import { ITEM_TYPE, TimeStampListItem } from "components/PhotoList";
+import SearchResultInfo from "components/Search/SearchResultInfo";
+import UploadInputs from "components/UploadSelectorInputs";
+import { GalleryNavbar } from "components/pages/gallery/Navbar";
+import { SYNC_INTERVAL_IN_MICROSECONDS } from "constants/gallery";
+import isElectron from "is-electron";
+import { ClipService } from "services/clipService";
+import { constructUserIDToEmailMap } from "services/collectionService";
+import downloadManager from "services/download";
+import { syncEmbeddings } from "services/embeddingService";
+import { syncEntities } from "services/entityService";
+import locationSearchService from "services/locationSearchService";
+import uploadManager from "services/upload/uploadManager";
+import { Collection, CollectionSummaries } from "types/collection";
+import { EnteFile } from "types/file";
import {
GalleryContextType,
SelectedState,
SetFilesDownloadProgressAttributes,
SetFilesDownloadProgressAttributesCreator,
UploadTypeSelectorIntent,
-} from 'types/gallery';
-import Collections from 'components/Collections';
-import { GalleryNavbar } from 'components/pages/gallery/Navbar';
-import { Search, SearchResultSummary, UpdateSearch } from 'types/search';
-import SearchResultInfo from 'components/Search/SearchResultInfo';
-import { ITEM_TYPE, TimeStampListItem } from 'components/PhotoList';
-import UploadInputs from 'components/UploadSelectorInputs';
-import useFileInput from '@ente/shared/hooks/useFileInput';
-import { User } from '@ente/shared/user/types';
-import { FamilyData } from 'types/user';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import { CenteredFlex } from '@ente/shared/components/Container';
-import { checkConnectivity } from 'utils/common';
-import { SYNC_INTERVAL_IN_MICROSECONDS } from 'constants/gallery';
-import ElectronAPIs from '@ente/shared/electron';
-import uploadManager from 'services/upload/uploadManager';
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
-import ExportModal from 'components/ExportModal';
-import GalleryEmptyState from 'components/GalleryEmptyState';
-import AuthenticateUserModal from 'components/AuthenticateUserModal';
-import useMemoSingleThreaded from '@ente/shared/hooks/useMemoSingleThreaded';
-import { isArchivedFile } from 'utils/magicMetadata';
-import { getSessionExpiredMessage } from 'utils/ui';
-import { syncEntities } from 'services/entityService';
-import { constructUserIDToEmailMap } from 'services/collectionService';
-import { getLocalFamilyData } from 'utils/user/family';
-import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
-import { syncEmbeddings } from 'services/embeddingService';
-import { ClipService } from 'services/clipService';
-import isElectron from 'is-electron';
-import downloadManager from 'services/download';
-import { APPS } from '@ente/shared/apps/constants';
-import {
- FilesDownloadProgress,
- FilesDownloadProgressAttributes,
-} from 'components/FilesDownloadProgress';
-import locationSearchService from 'services/locationSearchService';
-import ComlinkSearchWorker from 'utils/comlink/ComlinkSearchWorker';
-import useEffectSingleThreaded from '@ente/shared/hooks/useEffectSingleThreaded';
-
-export const DeadCenter = styled('div')`
+} from "types/gallery";
+import { Search, SearchResultSummary, UpdateSearch } from "types/search";
+import { FamilyData } from "types/user";
+import ComlinkSearchWorker from "utils/comlink/ComlinkSearchWorker";
+import { checkConnectivity } from "utils/common";
+import { isArchivedFile } from "utils/magicMetadata";
+import { getSessionExpiredMessage } from "utils/ui";
+import { getLocalFamilyData } from "utils/user/family";
+
+export const DeadCenter = styled("div")`
flex: 1;
display: flex;
justify-content: center;
@@ -166,7 +166,7 @@ const defaultGalleryContext: GalleryContextType = {
};
export const GalleryContext = createContext<GalleryContextType>(
- defaultGalleryContext
+ defaultGalleryContext,
);
export default function Gallery() {
@@ -235,10 +235,10 @@ export default function Gallery() {
const resync = useRef<{ force: boolean; silent: boolean }>();
// tempDeletedFileIds and tempHiddenFileIds are used to keep track of files that are deleted/hidden in the current session but not yet synced with the server.
const [tempDeletedFileIds, setTempDeletedFileIds] = useState<Set<number>>(
- new Set<number>()
+ new Set<number>(),
);
const [tempHiddenFileIds, setTempHiddenFileIds] = useState<Set<number>>(
- new Set<number>()
+ new Set<number>(),
);
const { startLoading, finishLoading, setDialogMessage, ...appContext } =
useContext(AppContext);
@@ -252,7 +252,7 @@ export default function Gallery() {
const [activeCollectionID, setActiveCollectionID] =
useState<number>(undefined);
const [hiddenFileIds, setHiddenFileIds] = useState<Set<number>>(
- new Set<number>()
+ new Set<number>(),
);
const [fixCreationTimeView, setFixCreationTimeView] = useState(false);
const [fixCreationTimeAttributes, setFixCreationTimeAttributes] =
@@ -266,7 +266,7 @@ export default function Gallery() {
const [uploadTypeSelectorView, setUploadTypeSelectorView] = useState(false);
const [uploadTypeSelectorIntent, setUploadTypeSelectorIntent] =
useState<UploadTypeSelectorIntent>(
- UploadTypeSelectorIntent.normalUpload
+ UploadTypeSelectorIntent.normalUpload,
);
const [sidebarView, setSidebarView] = useState(false);
@@ -297,8 +297,8 @@ export default function Gallery() {
setFilesDownloadProgressAttributesList,
] = useState<FilesDownloadProgressAttributes[]>([]);
- const openHiddenSection: GalleryContextType['openHiddenSection'] = (
- callback
+ const openHiddenSection: GalleryContextType["openHiddenSection"] = (
+ callback,
) => {
authenticateUser(() => {
setIsInHiddenSection(true);
@@ -319,7 +319,7 @@ export default function Gallery() {
router.push(PAGES.ROOT);
return;
}
- preloadImage('/images/subscription-card-background');
+ preloadImage("/images/subscription-card-background");
const main = async () => {
const valid = await validateKey();
if (!valid) {
@@ -337,10 +337,10 @@ export default function Gallery() {
const user = getData(LS_KEYS.USER);
const familyData = getLocalFamilyData();
const files = sortFiles(
- mergeMetadata(await getLocalFiles('normal'))
+ mergeMetadata(await getLocalFiles("normal")),
);
const hiddenFiles = sortFiles(
- mergeMetadata(await getLocalFiles('hidden'))
+ mergeMetadata(await getLocalFiles("hidden")),
);
const collections = await getAllLocalCollections();
const { normalCollections, hiddenCollections } =
@@ -384,7 +384,7 @@ export default function Gallery() {
const searchWorker = await ComlinkSearchWorker.getInstance();
await searchWorker.setFiles(files);
},
- [files]
+ [files],
);
useEffect(() => {
@@ -397,7 +397,7 @@ export default function Gallery() {
hiddenCollections,
files,
trashedFiles,
- hiddenFiles
+ hiddenFiles,
);
}, [
collections,
@@ -436,20 +436,20 @@ export default function Gallery() {
}, [fixCreationTimeAttributes]);
useEffect(() => {
- if (typeof activeCollectionID === 'undefined' || !router.isReady) {
+ if (typeof activeCollectionID === "undefined" || !router.isReady) {
return;
}
- let collectionURL = '';
+ let collectionURL = "";
if (activeCollectionID !== ALL_SECTION) {
- collectionURL += '?collection=';
+ collectionURL += "?collection=";
if (activeCollectionID === ARCHIVE_SECTION) {
- collectionURL += t('ARCHIVE_SECTION_NAME');
+ collectionURL += t("ARCHIVE_SECTION_NAME");
} else if (activeCollectionID === TRASH_SECTION) {
- collectionURL += t('TRASH');
+ collectionURL += t("TRASH");
} else if (activeCollectionID === DUMMY_UNCATEGORIZED_COLLECTION) {
- collectionURL += t('UNCATEGORIZED');
+ collectionURL += t("UNCATEGORIZED");
} else if (activeCollectionID === HIDDEN_ITEMS_SECTION) {
- collectionURL += t('HIDDEN_ITEMS_SECTION_NAME');
+ collectionURL += t("HIDDEN_ITEMS_SECTION_NAME");
} else {
collectionURL += activeCollectionID;
}
@@ -464,7 +464,7 @@ export default function Gallery() {
checkSubscriptionPurchase(
setDialogMessage,
router,
- setBlockingLoad
+ setBlockingLoad,
);
}
}, [router.isReady]);
@@ -488,7 +488,7 @@ export default function Gallery() {
return null;
}
return [...collections, ...hiddenCollections].find(
- (collection) => collection.id === activeCollectionID
+ (collection) => collection.id === activeCollectionID,
);
}, [collections, activeCollectionID]);
@@ -573,7 +573,7 @@ export default function Gallery() {
} else {
return false;
}
- })
+ }),
);
}
if (search?.clip) {
@@ -699,8 +699,8 @@ export default function Gallery() {
await splitNormalAndHiddenCollections(collections);
setCollections(normalCollections);
setHiddenCollections(hiddenCollections);
- await syncFiles('normal', normalCollections, setFiles);
- await syncFiles('hidden', hiddenCollections, setHiddenFiles);
+ await syncFiles("normal", normalCollections, setFiles);
+ await syncFiles("hidden", hiddenCollections, setHiddenFiles);
await syncTrash(collections, setTrashedFiles);
await syncEntities();
await syncMapEnabled();
@@ -720,7 +720,7 @@ export default function Gallery() {
case CustomError.NO_INTERNET_CONNECTION:
break;
default:
- logError(e, 'syncWithRemote failed');
+ logError(e, "syncWithRemote failed");
}
} finally {
setTempDeletedFileIds(new Set());
@@ -738,19 +738,19 @@ export default function Gallery() {
const setupSelectAllKeyBoardShortcutHandler = () => {
const handleKeyUp = (e: KeyboardEvent) => {
switch (e.key) {
- case 'Escape':
+ case "Escape":
keyboardShortcutHandlerRef.current.clearSelection();
break;
- case 'a':
+ case "a":
if (e.ctrlKey || e.metaKey) {
keyboardShortcutHandlerRef.current.selectAll(e);
}
break;
}
};
- document.addEventListener('keydown', handleKeyUp);
+ document.addEventListener("keydown", handleKeyUp);
return () => {
- document.removeEventListener('keydown', handleKeyUp);
+ document.removeEventListener("keydown", handleKeyUp);
};
};
@@ -760,7 +760,7 @@ export default function Gallery() {
hiddenCollections: Collection[],
files: EnteFile[],
trashedFiles: EnteFile[],
- hiddenFiles: EnteFile[]
+ hiddenFiles: EnteFile[],
) => {
const favItemIds = await getFavItemIds(files);
setFavItemIds(favItemIds);
@@ -774,28 +774,28 @@ export default function Gallery() {
const collectionSummaries = getCollectionSummaries(
user,
collections,
- files
+ files,
);
const sectionSummaries = getSectionSummaries(
files,
trashedFiles,
- archivedCollections
+ archivedCollections,
);
const hiddenCollectionSummaries = getCollectionSummaries(
user,
hiddenCollections,
- hiddenFiles
+ hiddenFiles,
);
const hiddenItemsSummaries = getHiddenItemsSummary(
hiddenFiles,
- hiddenCollections
+ hiddenCollections,
);
hiddenCollectionSummaries.set(
HIDDEN_ITEMS_SECTION,
- hiddenItemsSummaries
+ hiddenItemsSummaries,
);
setCollectionSummaries(
- mergeMaps(collectionSummaries, sectionSummaries)
+ mergeMaps(collectionSummaries, sectionSummaries),
);
setHiddenCollectionSummaries(hiddenCollectionSummaries);
};
@@ -811,12 +811,12 @@ export default function Gallery() {
setFilesDownloadProgressAttributesList((prev) => {
const attributes = prev?.find((attr) => attr.id === id);
const updatedAttributes =
- typeof value === 'function'
+ typeof value === "function"
? value(attributes)
: { ...attributes, ...value };
const updatedAttributesList = attributes
? prev.map((attr) =>
- attr.id === id ? updatedAttributes : attr
+ attr.id === id ? updatedAttributes : attr,
)
: [...prev, updatedAttributes];
@@ -847,14 +847,14 @@ export default function Gallery() {
ops === COLLECTION_OPS_TYPE.REMOVE
? selectedFiles
: selectedFiles.filter(
- (file) => file.ownerID === user.id
+ (file) => file.ownerID === user.id,
);
if (toProcessFiles.length > 0) {
await handleCollectionOps(
ops,
collection,
toProcessFiles,
- selected.collectionID
+ selected.collectionID,
);
}
if (selected?.ownCount === filteredData?.length) {
@@ -872,12 +872,12 @@ export default function Gallery() {
clearSelection();
await syncWithRemote(false, true);
} catch (e) {
- logError(e, 'collection ops failed', { ops });
+ logError(e, "collection ops failed", { ops });
setDialogMessage({
- title: t('ERROR'),
+ title: t("ERROR"),
- close: { variant: 'critical' },
- content: t('UNKNOWN_ERROR'),
+ close: { variant: "critical" },
+ content: t("UNKNOWN_ERROR"),
});
} finally {
finishLoading();
@@ -890,7 +890,7 @@ export default function Gallery() {
// passing files here instead of filteredData for hide ops because we want to move all files copies to hidden collection
const selectedFiles = getSelectedFiles(
selected,
- ops === FILE_OPS_TYPE.HIDE ? files : filteredData
+ ops === FILE_OPS_TYPE.HIDE ? files : filteredData,
);
const toProcessFiles =
ops === FILE_OPS_TYPE.DOWNLOAD
@@ -903,7 +903,7 @@ export default function Gallery() {
setTempDeletedFileIds,
setTempHiddenFileIds,
setFixCreationTimeAttributes,
- setFilesDownloadProgressAttributesCreator
+ setFilesDownloadProgressAttributesCreator,
);
}
if (
@@ -917,12 +917,12 @@ export default function Gallery() {
clearSelection();
await syncWithRemote(false, true);
} catch (e) {
- logError(e, 'file ops failed', { ops });
+ logError(e, "file ops failed", { ops });
setDialogMessage({
- title: t('ERROR'),
+ title: t("ERROR"),
- close: { variant: 'critical' },
- content: t('UNKNOWN_ERROR'),
+ close: { variant: "critical" },
+ content: t("UNKNOWN_ERROR"),
});
} finally {
finishLoading();
@@ -936,12 +936,12 @@ export default function Gallery() {
const collection = await createAlbum(collectionName);
await collectionOpsHelper(ops)(collection);
} catch (e) {
- logError(e, 'create and collection ops failed', { ops });
+ logError(e, "create and collection ops failed", { ops });
setDialogMessage({
- title: t('ERROR'),
+ title: t("ERROR"),
- close: { variant: 'critical' },
- content: t('UNKNOWN_ERROR'),
+ close: { variant: "critical" },
+ content: t("UNKNOWN_ERROR"),
});
} finally {
finishLoading();
@@ -949,9 +949,9 @@ export default function Gallery() {
};
return () =>
setCollectionNamerAttributes({
- title: t('CREATE_COLLECTION'),
- buttonText: t('CREATE'),
- autoFilledName: '',
+ title: t("CREATE_COLLECTION"),
+ buttonText: t("CREATE"),
+ autoFilledName: "",
callback,
});
};
@@ -1013,9 +1013,11 @@ export default function Gallery() {
emailList,
openHiddenSection,
isClipSearchResult,
- }}>
+ }}
+ >
<FullScreenDropZone
- getDragAndDropRootProps={getDragAndDropRootProps}>
+ getDragAndDropRootProps={getDragAndDropRootProps}
+ >
<UploadInputs
getDragAndDropInputProps={getDragAndDropInputProps}
getFileSelectorInputProps={getFileSelectorInputProps}
@@ -1029,7 +1031,7 @@ export default function Gallery() {
{isFirstLoad && (
<CenteredFlex>
<Typography color="text.muted" variant="small">
- {t('INITIAL_LOAD_DELAY_WARNING')}
+ {t("INITIAL_LOAD_DELAY_WARNING")}
</Typography>
</CenteredFlex>
)}
@@ -1096,18 +1098,18 @@ export default function Gallery() {
syncWithRemote={syncWithRemote}
showCollectionSelector={setCollectionSelectorView.bind(
null,
- true
+ true,
)}
closeUploadTypeSelector={setUploadTypeSelectorView.bind(
null,
- false
+ false,
)}
setCollectionSelectorAttributes={
setCollectionSelectorAttributes
}
closeCollectionSelector={setCollectionSelectorView.bind(
null,
- false
+ false,
)}
uploadTypeSelectorIntent={uploadTypeSelectorIntent}
setLoading={setBlockingLoad}
@@ -1178,7 +1180,7 @@ export default function Gallery() {
activeCollectionID={activeCollectionID}
selectedCollection={getSelectedCollection(
selected.collectionID,
- collections
+ collections,
)}
isFavoriteCollection={
collectionSummaries.get(activeCollectionID)
diff --git a/apps/photos/src/pages/generate/index.tsx b/apps/photos/src/pages/generate/index.tsx
index e18500a7a2..79a9007efc 100644
--- a/apps/photos/src/pages/generate/index.tsx
+++ b/apps/photos/src/pages/generate/index.tsx
@@ -1,8 +1,8 @@
-import GeneratePage from '@ente/accounts/pages/generate';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import GeneratePage from "@ente/accounts/pages/generate";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Generate() {
const appContext = useContext(AppContext);
diff --git a/apps/photos/src/pages/index.tsx b/apps/photos/src/pages/index.tsx
index 98f528e3ff..9aa3500ecf 100644
--- a/apps/photos/src/pages/index.tsx
+++ b/apps/photos/src/pages/index.tsx
@@ -1,27 +1,27 @@
-import React, { useContext, useEffect, useState } from 'react';
-import Carousel from 'react-bootstrap/Carousel';
-import { styled, Button, Typography, TypographyProps } from '@mui/material';
-import { AppContext } from './_app';
-import Login from '@ente/accounts/components/Login';
-import { useRouter } from 'next/router';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import SignUp from '@ente/accounts/components/SignUp';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { t } from 'i18next';
+import Login from "@ente/accounts/components/Login";
+import SignUp from "@ente/accounts/components/SignUp";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import { getData, LS_KEYS } from "@ente/shared/storage/localStorage";
+import { Button, styled, Typography, TypographyProps } from "@mui/material";
+import { t } from "i18next";
+import { useRouter } from "next/router";
+import { useContext, useEffect, useState } from "react";
+import Carousel from "react-bootstrap/Carousel";
+import { AppContext } from "./_app";
-import localForage from '@ente/shared/storage/localForage';
-import { logError } from '@ente/shared/sentry';
-import { PHOTOS_PAGES as PAGES } from '@ente/shared/constants/pages';
-import { EnteLogo } from '@ente/shared/components/EnteLogo';
-import isElectron from 'is-electron';
-import ElectronAPIs from '@ente/shared/electron';
-import { saveKeyInSessionStore } from '@ente/shared/crypto/helpers';
-import { getKey, SESSION_KEYS } from '@ente/shared/storage/sessionStorage';
-import { getAlbumsURL } from '@ente/shared/network/api';
-import { Trans } from 'react-i18next';
-import { APPS } from '@ente/shared/apps/constants';
+import { APPS } from "@ente/shared/apps/constants";
+import { EnteLogo } from "@ente/shared/components/EnteLogo";
+import { PHOTOS_PAGES as PAGES } from "@ente/shared/constants/pages";
+import { saveKeyInSessionStore } from "@ente/shared/crypto/helpers";
+import ElectronAPIs from "@ente/shared/electron";
+import { getAlbumsURL } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import localForage from "@ente/shared/storage/localForage";
+import { getKey, SESSION_KEYS } from "@ente/shared/storage/sessionStorage";
+import isElectron from "is-electron";
+import { Trans } from "react-i18next";
-const Container = styled('div')`
+const Container = styled("div")`
display: flex;
flex: 1;
align-items: center;
@@ -33,7 +33,7 @@ const Container = styled('div')`
}
`;
-const SlideContainer = styled('div')`
+const SlideContainer = styled("div")`
flex: 1;
display: flex;
flex-direction: column;
@@ -46,7 +46,7 @@ const SlideContainer = styled('div')`
}
`;
-const DesktopBox = styled('div')`
+const DesktopBox = styled("div")`
flex: 1;
height: 100%;
padding: 10px;
@@ -60,7 +60,7 @@ const DesktopBox = styled('div')`
}
`;
-const MobileBox = styled('div')`
+const MobileBox = styled("div")`
display: none;
@media (max-width: 1024px) {
@@ -73,21 +73,21 @@ const MobileBox = styled('div')`
}
`;
-const SideBox = styled('div')`
+const SideBox = styled("div")`
display: flex;
flex-direction: column;
min-width: 320px;
`;
const TextContainer = (props: TypographyProps) => (
- <Typography color={'text.muted'} mt={2} mb={3} {...props} />
+ <Typography color={"text.muted"} mt={2} mb={3} {...props} />
);
const FeatureText = (props: TypographyProps) => (
<Typography variant="h3" mt={4} {...props} />
);
-const Img = styled('img')`
+const Img = styled("img")`
height: 250px;
object-fit: contain;
@@ -118,7 +118,7 @@ export default function LandingPage() {
}, []);
const handleAlbumsRedirect = async (currentURL: URL) => {
- const end = currentURL.hash.lastIndexOf('&');
+ const end = currentURL.hash.lastIndexOf("&");
const hash = currentURL.hash.slice(1, end !== -1 ? end : undefined);
await router.replace({
pathname: PAGES.SHARED_ALBUMS,
@@ -135,13 +135,13 @@ export default function LandingPage() {
try {
key = await ElectronAPIs.getEncryptionKey();
} catch (e) {
- logError(e, 'getEncryptionKey failed');
+ logError(e, "getEncryptionKey failed");
}
if (key) {
await saveKeyInSessionStore(
SESSION_KEYS.ENCRYPTION_KEY,
key,
- true
+ true,
);
}
}
@@ -166,12 +166,12 @@ export default function LandingPage() {
try {
await localForage.ready();
} catch (e) {
- logError(e, 'usage in incognito mode tried');
+ logError(e, "usage in incognito mode tried");
appContext.setDialogMessage({
- title: t('LOCAL_STORAGE_NOT_ACCESSIBLE'),
+ title: t("LOCAL_STORAGE_NOT_ACCESSIBLE"),
nonClosable: true,
- content: t('LOCAL_STORAGE_NOT_ACCESSIBLE_MESSAGE'),
+ content: t("LOCAL_STORAGE_NOT_ACCESSIBLE_MESSAGE"),
});
} finally {
setLoading(false);
@@ -200,10 +200,10 @@ export default function LandingPage() {
/images/onboarding-lock/3x.png 3x"
/>
<FeatureText>
- <Trans i18nKey={'HERO_SLIDE_1_TITLE'} />
+ <Trans i18nKey={"HERO_SLIDE_1_TITLE"} />
</FeatureText>
<TextContainer>
- {t('HERO_SLIDE_1')}
+ {t("HERO_SLIDE_1")}
</TextContainer>
</Carousel.Item>
<Carousel.Item>
@@ -213,10 +213,10 @@ export default function LandingPage() {
/images/onboarding-safe/3x.png 3x"
/>
<FeatureText>
- <Trans i18nKey={'HERO_SLIDE_2_TITLE'} />
+ <Trans i18nKey={"HERO_SLIDE_2_TITLE"} />
</FeatureText>
<TextContainer>
- {t('HERO_SLIDE_2')}
+ {t("HERO_SLIDE_2")}
</TextContainer>
</Carousel.Item>
<Carousel.Item>
@@ -226,10 +226,10 @@ export default function LandingPage() {
/images/onboarding-sync/3x.png 3x"
/>
<FeatureText>
- <Trans i18nKey={'HERO_SLIDE_3_TITLE'} />
+ <Trans i18nKey={"HERO_SLIDE_3_TITLE"} />
</FeatureText>
<TextContainer>
- {t('HERO_SLIDE_3')}
+ {t("HERO_SLIDE_3")}
</TextContainer>
</Carousel.Item>
</Carousel>
@@ -238,11 +238,12 @@ export default function LandingPage() {
<Button
color="accent"
size="large"
- onClick={redirectToSignupPage}>
- {t('NEW_USER')}
+ onClick={redirectToSignupPage}
+ >
+ {t("NEW_USER")}
</Button>
<Button size="large" onClick={redirectToLoginPage}>
- {t('EXISTING_USER')}
+ {t("EXISTING_USER")}
</Button>
</MobileBox>
<DesktopBox>
diff --git a/apps/photos/src/pages/login/index.tsx b/apps/photos/src/pages/login/index.tsx
index e1519da1f4..8709af06c1 100644
--- a/apps/photos/src/pages/login/index.tsx
+++ b/apps/photos/src/pages/login/index.tsx
@@ -1,8 +1,8 @@
-import LoginPage from '@ente/accounts/pages/login';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import LoginPage from "@ente/accounts/pages/login";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Login() {
const appContext = useContext(AppContext);
diff --git a/apps/photos/src/pages/passkeys/finish/index.tsx b/apps/photos/src/pages/passkeys/finish/index.tsx
index 07f3b0430e..289f351de9 100644
--- a/apps/photos/src/pages/passkeys/finish/index.tsx
+++ b/apps/photos/src/pages/passkeys/finish/index.tsx
@@ -1,4 +1,4 @@
-import PasskeysFinishPage from '@ente/accounts/pages/passkeys/finish';
+import PasskeysFinishPage from "@ente/accounts/pages/passkeys/finish";
const PasskeysFinish = () => {
return (
diff --git a/apps/photos/src/pages/recover/index.tsx b/apps/photos/src/pages/recover/index.tsx
index 93a05b8bca..b3e16175f6 100644
--- a/apps/photos/src/pages/recover/index.tsx
+++ b/apps/photos/src/pages/recover/index.tsx
@@ -1,8 +1,8 @@
-import RecoverPage from '@ente/accounts/pages/recover';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import RecoverPage from "@ente/accounts/pages/recover";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Recover() {
const appContext = useContext(AppContext);
diff --git a/apps/photos/src/pages/shared-albums/index.tsx b/apps/photos/src/pages/shared-albums/index.tsx
index 4a916e6af3..5056f77eb9 100644
--- a/apps/photos/src/pages/shared-albums/index.tsx
+++ b/apps/photos/src/pages/shared-albums/index.tsx
@@ -1,6 +1,14 @@
-import { ALL_SECTION } from 'constants/collection';
-import PhotoFrame from 'components/PhotoFrame';
-import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
+import {
+ CenteredFlex,
+ SpaceBetweenFlex,
+ VerticallyCentered,
+} from "@ente/shared/components/Container";
+import { CustomError, parseSharingErrorCodes } from "@ente/shared/error";
+import PhotoFrame from "components/PhotoFrame";
+import { ALL_SECTION } from "constants/collection";
+import { t } from "i18next";
+import { AppContext } from "pages/_app";
+import { useContext, useEffect, useMemo, useRef, useState } from "react";
import {
getLocalPublicCollection,
getLocalPublicCollectionPassword,
@@ -13,69 +21,61 @@ import {
savePublicCollectionPassword,
syncPublicFiles,
verifyPublicCollectionPassword,
-} from 'services/publicCollectionService';
-import { Collection } from 'types/collection';
-import { EnteFile } from 'types/file';
+} from "services/publicCollectionService";
+import { Collection } from "types/collection";
+import { EnteFile } from "types/file";
import {
downloadSelectedFiles,
getSelectedFiles,
mergeMetadata,
sortFiles,
-} from 'utils/file';
-import { AppContext } from 'pages/_app';
-import { PublicCollectionGalleryContext } from 'utils/publicCollectionGallery';
-import { CustomError, parseSharingErrorCodes } from '@ente/shared/error';
-import {
- VerticallyCentered,
- CenteredFlex,
- SpaceBetweenFlex,
-} from '@ente/shared/components/Container';
-import { t } from 'i18next';
+} from "utils/file";
+import { PublicCollectionGalleryContext } from "utils/publicCollectionGallery";
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { PHOTOS_PAGES as PAGES } from '@ente/shared/constants/pages';
-import { useRouter } from 'next/router';
+import { logoutUser } from "@ente/accounts/services/user";
+import { APPS } from "@ente/shared/apps/constants";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import FormPaper from "@ente/shared/components/Form/FormPaper";
+import FormPaperTitle from "@ente/shared/components/Form/FormPaper/Title";
+import OverflowMenu from "@ente/shared/components/OverflowMenu/menu";
+import { OverflowMenuOption } from "@ente/shared/components/OverflowMenu/option";
import SingleInputForm, {
SingleInputFormProps,
-} from '@ente/shared/components/SingleInputForm';
-import { logError } from '@ente/shared/sentry';
-import SharedAlbumNavbar from 'components/pages/sharedAlbum/Navbar';
-import { CollectionInfo } from 'components/Collections/CollectionInfo';
-import { CollectionInfoBarWrapper } from 'components/Collections/styledComponents';
-import { ITEM_TYPE, TimeStampListItem } from 'components/PhotoList';
-import FormPaper from '@ente/shared/components/Form/FormPaper';
-import FormPaperTitle from '@ente/shared/components/Form/FormPaper/Title';
-import Typography from '@mui/material/Typography';
-import Uploader from 'components/Upload/Uploader';
-import { LoadingOverlay } from 'components/LoadingOverlay';
-import FullScreenDropZone from 'components/FullScreenDropZone';
-import useFileInput from '@ente/shared/hooks/useFileInput';
-import { useDropzone } from 'react-dropzone';
-import UploadSelectorInputs from 'components/UploadSelectorInputs';
-import { logoutUser } from '@ente/accounts/services/user';
-import UploadButton from 'components/Upload/UploadButton';
-import bs58 from 'bs58';
-import AddPhotoAlternateOutlined from '@mui/icons-material/AddPhotoAlternateOutlined';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
+} from "@ente/shared/components/SingleInputForm";
+import { PHOTOS_PAGES as PAGES } from "@ente/shared/constants/pages";
+import { ENTE_WEBSITE_LINK } from "@ente/shared/constants/urls";
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import useFileInput from "@ente/shared/hooks/useFileInput";
+import { logError } from "@ente/shared/sentry";
+import AddPhotoAlternateOutlined from "@mui/icons-material/AddPhotoAlternateOutlined";
+import FileDownloadOutlinedIcon from "@mui/icons-material/FileDownloadOutlined";
+import MoreHoriz from "@mui/icons-material/MoreHoriz";
+import Typography from "@mui/material/Typography";
+import bs58 from "bs58";
+import { CollectionInfo } from "components/Collections/CollectionInfo";
+import { CollectionInfoBarWrapper } from "components/Collections/styledComponents";
+import {
+ FilesDownloadProgress,
+ FilesDownloadProgressAttributes,
+} from "components/FilesDownloadProgress";
+import FullScreenDropZone from "components/FullScreenDropZone";
+import { LoadingOverlay } from "components/LoadingOverlay";
+import { ITEM_TYPE, TimeStampListItem } from "components/PhotoList";
+import UploadButton from "components/Upload/UploadButton";
+import Uploader from "components/Upload/Uploader";
+import UploadSelectorInputs from "components/UploadSelectorInputs";
+import SharedAlbumNavbar from "components/pages/sharedAlbum/Navbar";
+import SelectedFileOptions from "components/pages/sharedAlbum/SelectedFileOptions";
+import { useRouter } from "next/router";
+import { useDropzone } from "react-dropzone";
+import downloadManager from "services/download";
import {
SelectedState,
SetFilesDownloadProgressAttributes,
SetFilesDownloadProgressAttributesCreator,
UploadTypeSelectorIntent,
-} from 'types/gallery';
-import FileDownloadOutlinedIcon from '@mui/icons-material/FileDownloadOutlined';
-import MoreHoriz from '@mui/icons-material/MoreHoriz';
-import OverflowMenu from '@ente/shared/components/OverflowMenu/menu';
-import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';
-import { ENTE_WEBSITE_LINK } from '@ente/shared/constants/urls';
-import { APPS } from '@ente/shared/apps/constants';
-import downloadManager from 'services/download';
-import {
- FilesDownloadProgress,
- FilesDownloadProgressAttributes,
-} from 'components/FilesDownloadProgress';
-import { downloadCollectionFiles, isHiddenCollection } from 'utils/collection';
-import SelectedFileOptions from 'components/pages/sharedAlbum/SelectedFileOptions';
+} from "types/gallery";
+import { downloadCollectionFiles, isHiddenCollection } from "utils/collection";
export default function PublicCollectionGallery() {
const token = useRef<string>(null);
@@ -83,7 +83,7 @@ export default function PublicCollectionGallery() {
const passwordJWTToken = useRef<string>(null);
const collectionKey = useRef<string>(null);
const url = useRef<string>(null);
- const referralCode = useRef<string>('');
+ const referralCode = useRef<string>("");
const [publicFiles, setPublicFiles] = useState<EnteFile[]>(null);
const [publicCollection, setPublicCollection] = useState<Collection>(null);
const [errorMessage, setErrorMessage] = useState<string>(null);
@@ -144,12 +144,12 @@ export default function PublicCollectionGallery() {
setFilesDownloadProgressAttributesList((prev) => {
const attributes = prev?.find((attr) => attr.id === id);
const updatedAttributes =
- typeof value === 'function'
+ typeof value === "function"
? value(attributes)
: { ...attributes, ...value };
const updatedAttributesList = attributes
? prev.map((attr) =>
- attr.id === id ? updatedAttributes : attr
+ attr.id === id ? updatedAttributes : attr,
)
: [...prev, updatedAttributes];
@@ -180,14 +180,14 @@ export default function PublicCollectionGallery() {
const showPublicLinkExpiredMessage = () =>
appContext.setDialogMessage({
- title: t('LINK_EXPIRED'),
- content: t('LINK_EXPIRED_MESSAGE'),
+ title: t("LINK_EXPIRED"),
+ content: t("LINK_EXPIRED_MESSAGE"),
nonClosable: true,
proceed: {
- text: t('LOGIN'),
+ text: t("LOGIN"),
action: logoutUser,
- variant: 'accent',
+ variant: "accent",
},
});
@@ -207,7 +207,7 @@ export default function PublicCollectionGallery() {
},
{
shallow: true,
- }
+ },
);
}
const main = async () => {
@@ -218,7 +218,7 @@ export default function PublicCollectionGallery() {
url.current = window.location.href;
const currentURL = new URL(url.current);
- const t = currentURL.searchParams.get('t');
+ const t = currentURL.searchParams.get("t");
const ck = currentURL.hash.slice(1);
if (!t && !ck) {
window.location.href = ENTE_WEBSITE_LINK;
@@ -236,7 +236,7 @@ export default function PublicCollectionGallery() {
collectionKey.current = dck;
url.current = window.location.href;
const localCollection = await getLocalPublicCollection(
- collectionKey.current
+ collectionKey.current,
);
if (localCollection) {
referralCode.current = await getReferralCode();
@@ -250,14 +250,14 @@ export default function PublicCollectionGallery() {
const localFiles = await getLocalPublicFiles(collectionUID);
const localPublicFiles = sortFiles(
mergeMetadata(localFiles),
- sortAsc
+ sortAsc,
);
setPublicFiles(localPublicFiles);
passwordJWTToken.current =
await getLocalPublicCollectionPassword(collectionUID);
downloadManager.updateToken(
token.current,
- passwordJWTToken.current
+ passwordJWTToken.current,
);
}
await syncWithRemote();
@@ -272,7 +272,7 @@ export default function PublicCollectionGallery() {
const downloadEnabled = useMemo(
() => publicCollection?.publicURLs?.[0]?.enableDownload ?? true,
- [publicCollection]
+ [publicCollection],
);
const downloadAllFiles = async () => {
@@ -284,15 +284,15 @@ export default function PublicCollectionGallery() {
setFilesDownloadProgressAttributesCreator(
publicCollection.name,
publicCollection.id,
- isHiddenCollection(publicCollection)
+ isHiddenCollection(publicCollection),
);
await downloadCollectionFiles(
publicCollection.name,
publicFiles,
- setFilesDownloadProgressAttributes
+ setFilesDownloadProgressAttributes,
);
} catch (e) {
- logError(e, 'failed to downloads shared album all files');
+ logError(e, "failed to downloads shared album all files");
}
};
@@ -309,12 +309,14 @@ export default function PublicCollectionGallery() {
/>
{downloadEnabled ? (
<OverflowMenu
- ariaControls={'collection-options'}
- triggerButtonIcon={<MoreHoriz />}>
+ ariaControls={"collection-options"}
+ triggerButtonIcon={<MoreHoriz />}
+ >
<OverflowMenuOption
startIcon={<FileDownloadOutlinedIcon />}
- onClick={downloadAllFiles}>
- {t('DOWNLOAD_COLLECTION')}
+ onClick={downloadAllFiles}
+ >
+ {t("DOWNLOAD_COLLECTION")}
</OverflowMenuOption>
</OverflowMenu>
) : (
@@ -332,11 +334,11 @@ export default function PublicCollectionGallery() {
if (publicCollection?.publicURLs?.[0]?.enableCollect) {
setPhotoListFooter({
item: (
- <CenteredFlex sx={{ marginTop: '56px' }}>
+ <CenteredFlex sx={{ marginTop: "56px" }}>
<UploadButton
disableShrink
openUploader={openUploader}
- text={t('ADD_MORE_PHOTOS')}
+ text={t("ADD_MORE_PHOTOS")}
color="accent"
icon={<AddPhotoAlternateOutlined />}
/>
@@ -357,7 +359,7 @@ export default function PublicCollectionGallery() {
setLoading(true);
const [collection, userReferralCode] = await getPublicCollection(
token.current,
- collectionKey.current
+ collectionKey.current,
);
referralCode.current = userReferralCode;
@@ -381,7 +383,7 @@ export default function PublicCollectionGallery() {
token.current,
passwordJWTToken.current,
collection,
- setPublicFiles
+ setPublicFiles,
);
} catch (e) {
const parsedError = parseSharingErrorCodes(e);
@@ -403,19 +405,19 @@ export default function PublicCollectionGallery() {
) {
setErrorMessage(
parsedError.message === CustomError.TOO_MANY_REQUESTS
- ? t('LINK_TOO_MANY_REQUESTS')
- : t('LINK_EXPIRED_MESSAGE')
+ ? t("LINK_TOO_MANY_REQUESTS")
+ : t("LINK_EXPIRED_MESSAGE"),
);
// share has been disabled
// local cache should be cleared
removePublicCollectionWithFiles(
collectionUID,
- collectionKey.current
+ collectionKey.current,
);
setPublicCollection(null);
setPublicFiles(null);
} else {
- logError(e, 'failed to sync public album with remote');
+ logError(e, "failed to sync public album with remote");
}
} finally {
appContext.finishLoading();
@@ -423,9 +425,9 @@ export default function PublicCollectionGallery() {
}
};
- const verifyLinkPassword: SingleInputFormProps['callback'] = async (
+ const verifyLinkPassword: SingleInputFormProps["callback"] = async (
password,
- setFieldError
+ setFieldError,
) => {
try {
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
@@ -436,29 +438,29 @@ export default function PublicCollectionGallery() {
password,
publicUrl.nonce,
publicUrl.opsLimit,
- publicUrl.memLimit
+ publicUrl.memLimit,
);
} catch (e) {
- logError(e, 'failed to derive key for verifyLinkPassword');
- setFieldError(`${t('UNKNOWN_ERROR')} ${e.message}`);
+ logError(e, "failed to derive key for verifyLinkPassword");
+ setFieldError(`${t("UNKNOWN_ERROR")} ${e.message}`);
return;
}
const collectionUID = getPublicCollectionUID(token.current);
try {
const jwtToken = await verifyPublicCollectionPassword(
token.current,
- hashedPassword
+ hashedPassword,
);
passwordJWTToken.current = jwtToken;
downloadManager.updateToken(
token.current,
- passwordJWTToken.current
+ passwordJWTToken.current,
);
await savePublicCollectionPassword(collectionUID, jwtToken);
} catch (e) {
const parsedError = parseSharingErrorCodes(e);
if (parsedError.message === CustomError.TOKEN_EXPIRED) {
- setFieldError(t('INCORRECT_PASSPHRASE'));
+ setFieldError(t("INCORRECT_PASSPHRASE"));
return;
}
throw e;
@@ -466,8 +468,8 @@ export default function PublicCollectionGallery() {
await syncWithRemote();
appContext.finishLoading();
} catch (e) {
- logError(e, 'failed to verifyLinkPassword');
- setFieldError(`${t('UNKNOWN_ERROR')} ${e.message}`);
+ logError(e, "failed to verifyLinkPassword");
+ setFieldError(`${t("UNKNOWN_ERROR")} ${e.message}`);
}
};
@@ -487,14 +489,14 @@ export default function PublicCollectionGallery() {
return (
<VerticallyCentered>
<FormPaper>
- <FormPaperTitle>{t('PASSWORD')}</FormPaperTitle>
- <Typography color={'text.muted'} mb={2} variant="small">
- {t('LINK_PASSWORD')}
+ <FormPaperTitle>{t("PASSWORD")}</FormPaperTitle>
+ <Typography color={"text.muted"} mb={2} variant="small">
+ {t("LINK_PASSWORD")}
</Typography>
<SingleInputForm
callback={verifyLinkPassword}
- placeholder={t('RETURN_PASSPHRASE_HINT')}
- buttonText={t('UNLOCK')}
+ placeholder={t("RETURN_PASSPHRASE_HINT")}
+ buttonText={t("UNLOCK")}
fieldType="password"
/>
</FormPaper>
@@ -502,7 +504,7 @@ export default function PublicCollectionGallery() {
);
}
if (!publicFiles) {
- return <VerticallyCentered>{t('NOT_FOUND')}</VerticallyCentered>;
+ return <VerticallyCentered>{t("NOT_FOUND")}</VerticallyCentered>;
}
}
@@ -518,15 +520,15 @@ export default function PublicCollectionGallery() {
const selectedFiles = getSelectedFiles(selected, publicFiles);
const setFilesDownloadProgressAttributes =
setFilesDownloadProgressAttributesCreator(
- `${selectedFiles.length} ${t('FILES')}`
+ `${selectedFiles.length} ${t("FILES")}`,
);
await downloadSelectedFiles(
selectedFiles,
- setFilesDownloadProgressAttributes
+ setFilesDownloadProgressAttributes,
);
clearSelection();
} catch (e) {
- logError(e, 'failed to download selected files');
+ logError(e, "failed to download selected files");
}
};
@@ -539,9 +541,11 @@ export default function PublicCollectionGallery() {
accessedThroughSharedURL: true,
photoListHeader,
photoListFooter,
- }}>
+ }}
+ >
<FullScreenDropZone
- getDragAndDropRootProps={getDragAndDropRootProps}>
+ getDragAndDropRootProps={getDragAndDropRootProps}
+ >
<UploadSelectorInputs
getDragAndDropInputProps={getDragAndDropInputProps}
getFileSelectorInputProps={getFileSelectorInputProps}
diff --git a/apps/photos/src/pages/signup/index.tsx b/apps/photos/src/pages/signup/index.tsx
index 9213b3a67d..7c0409a029 100644
--- a/apps/photos/src/pages/signup/index.tsx
+++ b/apps/photos/src/pages/signup/index.tsx
@@ -1,8 +1,8 @@
-import SignupPage from '@ente/accounts/pages/signup';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import SignupPage from "@ente/accounts/pages/signup";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Sigup() {
const appContext = useContext(AppContext);
diff --git a/apps/photos/src/pages/two-factor/recover/index.tsx b/apps/photos/src/pages/two-factor/recover/index.tsx
index 99635303c0..dcfb6fc15c 100644
--- a/apps/photos/src/pages/two-factor/recover/index.tsx
+++ b/apps/photos/src/pages/two-factor/recover/index.tsx
@@ -1,8 +1,8 @@
-import TwoFactorRecoverPage from '@ente/accounts/pages/two-factor/recover';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import TwoFactorRecoverPage from "@ente/accounts/pages/two-factor/recover";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function TwoFactorRecover() {
const appContext = useContext(AppContext);
diff --git a/apps/photos/src/pages/two-factor/setup/index.tsx b/apps/photos/src/pages/two-factor/setup/index.tsx
index aac9c9a249..b357018eee 100644
--- a/apps/photos/src/pages/two-factor/setup/index.tsx
+++ b/apps/photos/src/pages/two-factor/setup/index.tsx
@@ -1,8 +1,8 @@
-import TwoFactorSetupPage from '@ente/accounts/pages/two-factor/setup';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import TwoFactorSetupPage from "@ente/accounts/pages/two-factor/setup";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function TwoFactorSetup() {
const appContext = useContext(AppContext);
diff --git a/apps/photos/src/pages/two-factor/verify/index.tsx b/apps/photos/src/pages/two-factor/verify/index.tsx
index 1684d804e2..a618528212 100644
--- a/apps/photos/src/pages/two-factor/verify/index.tsx
+++ b/apps/photos/src/pages/two-factor/verify/index.tsx
@@ -1,8 +1,8 @@
-import TwoFactorVerifyPage from '@ente/accounts/pages/two-factor/verify';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import TwoFactorVerifyPage from "@ente/accounts/pages/two-factor/verify";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function TwoFactorVerify() {
const appContext = useContext(AppContext);
diff --git a/apps/photos/src/pages/verify/index.tsx b/apps/photos/src/pages/verify/index.tsx
index 2eceb26d89..9eeb6db60b 100644
--- a/apps/photos/src/pages/verify/index.tsx
+++ b/apps/photos/src/pages/verify/index.tsx
@@ -1,8 +1,8 @@
-import VerifyPage from '@ente/accounts/pages/verify';
-import { useRouter } from 'next/router';
-import { AppContext } from 'pages/_app';
-import { useContext } from 'react';
-import { APPS } from '@ente/shared/apps/constants';
+import VerifyPage from "@ente/accounts/pages/verify";
+import { APPS } from "@ente/shared/apps/constants";
+import { useRouter } from "next/router";
+import { AppContext } from "pages/_app";
+import { useContext } from "react";
export default function Verify() {
const appContext = useContext(AppContext);
diff --git a/apps/photos/src/services/billingService.ts b/apps/photos/src/services/billingService.ts
index ac70df9bdc..a9af851b28 100644
--- a/apps/photos/src/services/billingService.ts
+++ b/apps/photos/src/services/billingService.ts
@@ -1,22 +1,22 @@
-import { getEndpoint, getPaymentsURL } from '@ente/shared/network/api';
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getEndpoint, getPaymentsURL } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
import {
- setData,
LS_KEYS,
removeData,
-} from '@ente/shared/storage/localStorage';
-import HTTPService from '@ente/shared/network/HTTPService';
-import { logError } from '@ente/shared/sentry';
-import { getPaymentToken } from './userService';
-import { Plan, Subscription } from 'types/billing';
-import isElectron from 'is-electron';
-import { getDesktopRedirectURL } from 'constants/billing';
+ setData,
+} from "@ente/shared/storage/localStorage";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
+import { getDesktopRedirectURL } from "constants/billing";
+import isElectron from "is-electron";
+import { Plan, Subscription } from "types/billing";
+import { getPaymentToken } from "./userService";
const ENDPOINT = getEndpoint();
enum PaymentActionType {
- Buy = 'buy',
- Update = 'update',
+ Buy = "buy",
+ Update = "update",
}
class billingService {
@@ -26,21 +26,21 @@ class billingService {
let response;
if (!token) {
response = await HTTPService.get(
- `${ENDPOINT}/billing/plans/v2`
+ `${ENDPOINT}/billing/plans/v2`,
);
} else {
response = await HTTPService.get(
`${ENDPOINT}/billing/user-plans`,
null,
{
- 'X-Auth-Token': getToken(),
- }
+ "X-Auth-Token": getToken(),
+ },
);
}
const { plans } = response.data;
return plans;
} catch (e) {
- logError(e, 'failed to get plans');
+ logError(e, "failed to get plans");
}
}
@@ -50,8 +50,8 @@ class billingService {
`${ENDPOINT}/billing/subscription`,
null,
{
- 'X-Auth-Token': getToken(),
- }
+ "X-Auth-Token": getToken(),
+ },
);
const { subscription } = response.data;
setData(LS_KEYS.SUBSCRIPTION, subscription);
@@ -66,10 +66,10 @@ class billingService {
await this.redirectToPayments(
paymentToken,
productID,
- PaymentActionType.Buy
+ PaymentActionType.Buy,
);
} catch (e) {
- logError(e, 'unable to buy subscription');
+ logError(e, "unable to buy subscription");
throw e;
}
}
@@ -80,10 +80,10 @@ class billingService {
await this.redirectToPayments(
paymentToken,
productID,
- PaymentActionType.Update
+ PaymentActionType.Update,
);
} catch (e) {
- logError(e, 'subscription update failed');
+ logError(e, "subscription update failed");
throw e;
}
}
@@ -95,13 +95,13 @@ class billingService {
null,
null,
{
- 'X-Auth-Token': getToken(),
- }
+ "X-Auth-Token": getToken(),
+ },
);
const { subscription } = response.data;
setData(LS_KEYS.SUBSCRIPTION, subscription);
} catch (e) {
- logError(e, 'subscription cancel failed');
+ logError(e, "subscription cancel failed");
throw e;
}
}
@@ -113,19 +113,19 @@ class billingService {
null,
null,
{
- 'X-Auth-Token': getToken(),
- }
+ "X-Auth-Token": getToken(),
+ },
);
const { subscription } = response.data;
setData(LS_KEYS.SUBSCRIPTION, subscription);
} catch (e) {
- logError(e, 'failed to activate subscription');
+ logError(e, "failed to activate subscription");
throw e;
}
}
public async verifySubscription(
- sessionID: string = null
+ sessionID: string = null,
): Promise<Subscription> {
try {
const token = getToken();
@@ -135,20 +135,20 @@ class billingService {
const response = await HTTPService.post(
`${ENDPOINT}/billing/verify-subscription`,
{
- paymentProvider: 'stripe',
+ paymentProvider: "stripe",
productID: null,
verificationData: sessionID,
},
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
const { subscription } = response.data;
setData(LS_KEYS.SUBSCRIPTION, subscription);
return subscription;
} catch (err) {
- logError(err, 'Error while verifying subscription');
+ logError(err, "Error while verifying subscription");
throw err;
}
}
@@ -159,11 +159,11 @@ class billingService {
}
try {
await HTTPService.delete(`${ENDPOINT}/family/leave`, null, null, {
- 'X-Auth-Token': getToken(),
+ "X-Auth-Token": getToken(),
});
removeData(LS_KEYS.FAMILY_DATA);
} catch (e) {
- logError(e, '/family/leave failed');
+ logError(e, "/family/leave failed");
throw e;
}
}
@@ -171,13 +171,13 @@ class billingService {
public async redirectToPayments(
paymentToken: string,
productID: string,
- action: string
+ action: string,
) {
try {
const redirectURL = this.getRedirectURL();
window.location.href = `${getPaymentsURL()}?productID=${productID}&paymentToken=${paymentToken}&action=${action}&redirectURL=${redirectURL}`;
} catch (e) {
- logError(e, 'unable to get payments url');
+ logError(e, "unable to get payments url");
throw e;
}
}
@@ -189,12 +189,12 @@ class billingService {
`${ENDPOINT}/billing/stripe/customer-portal`,
{ redirectURL },
{
- 'X-Auth-Token': getToken(),
- }
+ "X-Auth-Token": getToken(),
+ },
);
window.location.href = response.data.url;
} catch (e) {
- logError(e, 'unable to get customer portal url');
+ logError(e, "unable to get customer portal url");
throw e;
}
}
diff --git a/apps/photos/src/services/clipService.ts b/apps/photos/src/services/clipService.ts
index b4f7bbb37b..71cc17131f 100644
--- a/apps/photos/src/services/clipService.ts
+++ b/apps/photos/src/services/clipService.ts
@@ -1,19 +1,19 @@
-import { putEmbedding, getLocalEmbeddings } from './embeddingService';
-import { getAllLocalFiles, getLocalFiles } from './fileService';
-import downloadManager from './download';
-import { logError } from '@ente/shared/sentry';
-import { addLogLine } from '@ente/shared/logging';
-import { Events, eventBus } from '@ente/shared/events';
-import PQueue from 'p-queue';
-import { EnteFile } from 'types/file';
-import ElectronAPIs from '@ente/shared/electron';
-import { CustomError } from '@ente/shared/error';
-import { LS_KEYS, getData } from '@ente/shared/storage/localStorage';
-import { getPersonalFiles } from 'utils/file';
-import { FILE_TYPE } from 'constants/file';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { Embedding, Model } from 'types/embedding';
-import isElectron from 'is-electron';
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import ElectronAPIs from "@ente/shared/electron";
+import { CustomError } from "@ente/shared/error";
+import { Events, eventBus } from "@ente/shared/events";
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
+import { FILE_TYPE } from "constants/file";
+import isElectron from "is-electron";
+import PQueue from "p-queue";
+import { Embedding, Model } from "types/embedding";
+import { EnteFile } from "types/file";
+import { getPersonalFiles } from "utils/file";
+import downloadManager from "./download";
+import { getLocalEmbeddings, putEmbedding } from "./embeddingService";
+import { getAllLocalFiles, getLocalFiles } from "./fileService";
const CLIP_EMBEDDING_LENGTH = 512;
@@ -63,36 +63,36 @@ class ClipServiceImpl {
return;
}
if (this.onFileUploadedHandler) {
- addLogLine('file upload listener already setup');
+ addLogLine("file upload listener already setup");
return;
}
- addLogLine('setting up file upload listener');
+ addLogLine("setting up file upload listener");
this.onFileUploadedHandler = (args) => {
this.runLocalFileClipExtraction(args);
};
eventBus.on(Events.FILE_UPLOADED, this.onFileUploadedHandler, this);
- addLogLine('setup file upload listener successfully');
+ addLogLine("setup file upload listener successfully");
} catch (e) {
- logError(e, 'failed to setup clip service');
+ logError(e, "failed to setup clip service");
}
};
removeOnFileUploadListener = async () => {
try {
if (!this.onFileUploadedHandler) {
- addLogLine('file upload listener already removed');
+ addLogLine("file upload listener already removed");
return;
}
- addLogLine('removing file upload listener');
+ addLogLine("removing file upload listener");
eventBus.removeListener(
Events.FILE_UPLOADED,
this.onFileUploadedHandler,
- this
+ this,
);
this.onFileUploadedHandler = null;
- addLogLine('removed file upload listener successfully');
+ addLogLine("removed file upload listener successfully");
} catch (e) {
- logError(e, 'failed to remove clip service');
+ logError(e, "failed to remove clip service");
}
};
@@ -107,7 +107,7 @@ class ClipServiceImpl {
}
return this.clipExtractionStatus;
} catch (e) {
- logError(e, 'failed to get clip indexing status');
+ logError(e, "failed to get clip indexing status");
}
};
@@ -117,18 +117,18 @@ class ClipServiceImpl {
};
scheduleImageEmbeddingExtraction = async (
- model: Model = Model.ONNX_CLIP
+ model: Model = Model.ONNX_CLIP,
) => {
try {
if (this.embeddingExtractionInProgress) {
addLogLine(
- 'clip embedding extraction already in progress, scheduling re-run'
+ "clip embedding extraction already in progress, scheduling re-run",
);
this.reRunNeeded = true;
return;
} else {
addLogLine(
- 'clip embedding extraction not in progress, starting clip embedding extraction'
+ "clip embedding extraction not in progress, starting clip embedding extraction",
);
}
const canceller = new AbortController();
@@ -139,23 +139,23 @@ class ClipServiceImpl {
this.embeddingExtractionInProgress = null;
if (!canceller.signal.aborted && this.reRunNeeded) {
this.reRunNeeded = false;
- addLogLine('re-running clip embedding extraction');
+ addLogLine("re-running clip embedding extraction");
setTimeout(
() => this.scheduleImageEmbeddingExtraction(),
- 0
+ 0,
);
}
}
} catch (e) {
if (e.message !== CustomError.REQUEST_CANCELLED) {
- logError(e, 'failed to schedule clip embedding extraction');
+ logError(e, "failed to schedule clip embedding extraction");
}
}
};
getTextEmbedding = async (
text: string,
- model: Model = Model.ONNX_CLIP
+ model: Model = Model.ONNX_CLIP,
): Promise<Float32Array> => {
try {
return ElectronAPIs.computeTextEmbedding(model, text);
@@ -163,19 +163,19 @@ class ClipServiceImpl {
if (e?.message?.includes(CustomError.UNSUPPORTED_PLATFORM)) {
this.unsupportedPlatform = true;
}
- logError(e, 'failed to compute text embedding');
+ logError(e, "failed to compute text embedding");
throw e;
}
};
private runClipEmbeddingExtraction = async (
canceller: AbortController,
- model: Model
+ model: Model,
) => {
try {
if (this.unsupportedPlatform) {
addLogLine(
- `skipping clip embedding extraction, platform unsupported`
+ `skipping clip embedding extraction, platform unsupported`,
);
return;
}
@@ -187,23 +187,23 @@ class ClipServiceImpl {
const existingEmbeddings = await getLocalEmbeddings(model);
const pendingFiles = await getNonClipEmbeddingExtractedFiles(
localFiles,
- existingEmbeddings
+ existingEmbeddings,
);
this.updateClipEmbeddingExtractionStatus({
indexed: existingEmbeddings.length,
pending: pendingFiles.length,
});
if (pendingFiles.length === 0) {
- addLogLine('no clip embedding extraction needed, all done');
+ addLogLine("no clip embedding extraction needed, all done");
return;
}
addLogLine(
- `starting clip embedding extraction for ${pendingFiles.length} files`
+ `starting clip embedding extraction for ${pendingFiles.length} files`,
);
for (const file of pendingFiles) {
try {
addLogLine(
- `extracting clip embedding for file: ${file.metadata.title} fileID: ${file.id}`
+ `extracting clip embedding for file: ${file.metadata.title} fileID: ${file.id}`,
);
if (canceller.signal.aborted) {
throw Error(CustomError.REQUEST_CANCELLED);
@@ -211,22 +211,22 @@ class ClipServiceImpl {
const embeddingData =
await this.extractFileClipImageEmbedding(model, file);
addLogLine(
- `successfully extracted clip embedding for file: ${file.metadata.title} fileID: ${file.id} embedding length: ${embeddingData?.length}`
+ `successfully extracted clip embedding for file: ${file.metadata.title} fileID: ${file.id} embedding length: ${embeddingData?.length}`,
);
await this.encryptAndUploadEmbedding(
model,
file,
- embeddingData
+ embeddingData,
);
this.onSuccessStatusUpdater();
addLogLine(
- `successfully put clip embedding to server for file: ${file.metadata.title} fileID: ${file.id}`
+ `successfully put clip embedding to server for file: ${file.metadata.title} fileID: ${file.id}`,
);
} catch (e) {
if (e?.message !== CustomError.REQUEST_CANCELLED) {
logError(
e,
- 'failed to extract clip embedding for file'
+ "failed to extract clip embedding for file",
);
}
if (
@@ -244,7 +244,7 @@ class ClipServiceImpl {
}
} catch (e) {
if (e.message !== CustomError.REQUEST_CANCELLED) {
- logError(e, 'failed to extract clip embedding');
+ logError(e, "failed to extract clip embedding");
}
throw e;
}
@@ -255,52 +255,52 @@ class ClipServiceImpl {
enteFile: EnteFile;
localFile: globalThis.File;
},
- model: Model = Model.ONNX_CLIP
+ model: Model = Model.ONNX_CLIP,
) {
const { enteFile, localFile } = arg;
addLogLine(
`clip embedding extraction onFileUploadedHandler file: ${enteFile.metadata.title} fileID: ${enteFile.id}`,
- enteFile.id
+ enteFile.id,
);
if (enteFile.metadata.fileType === FILE_TYPE.VIDEO) {
addLogLine(
- `skipping video file for clip embedding extraction file: ${enteFile.metadata.title} fileID: ${enteFile.id}`
+ `skipping video file for clip embedding extraction file: ${enteFile.metadata.title} fileID: ${enteFile.id}`,
);
return;
}
- const extension = enteFile.metadata.title.split('.').pop();
- if (!extension || !['jpg', 'jpeg'].includes(extension)) {
+ const extension = enteFile.metadata.title.split(".").pop();
+ if (!extension || !["jpg", "jpeg"].includes(extension)) {
addLogLine(
- `skipping non jpg file for clip embedding extraction file: ${enteFile.metadata.title} fileID: ${enteFile.id}`
+ `skipping non jpg file for clip embedding extraction file: ${enteFile.metadata.title} fileID: ${enteFile.id}`,
);
return;
}
addLogLine(
- `queuing up for local clip embedding extraction for file: ${enteFile.metadata.title} fileID: ${enteFile.id}`
+ `queuing up for local clip embedding extraction for file: ${enteFile.metadata.title} fileID: ${enteFile.id}`,
);
try {
await this.liveEmbeddingExtractionQueue.add(async () => {
const embedding = await this.extractLocalFileClipImageEmbedding(
model,
- localFile
+ localFile,
);
await this.encryptAndUploadEmbedding(
model,
enteFile,
- embedding
+ embedding,
);
});
addLogLine(
- `successfully extracted clip embedding for file: ${enteFile.metadata.title} fileID: ${enteFile.id}`
+ `successfully extracted clip embedding for file: ${enteFile.metadata.title} fileID: ${enteFile.id}`,
);
} catch (e) {
- logError(e, 'Failed in ML onFileUploadedHandler');
+ logError(e, "Failed in ML onFileUploadedHandler");
}
}
private extractLocalFileClipImageEmbedding = async (
model: Model,
- localFile: File
+ localFile: File,
) => {
const file = await localFile
.arrayBuffer()
@@ -312,18 +312,18 @@ class ClipServiceImpl {
private encryptAndUploadEmbedding = async (
model: Model,
file: EnteFile,
- embeddingData: Float32Array
+ embeddingData: Float32Array,
) => {
if (embeddingData?.length !== CLIP_EMBEDDING_LENGTH) {
throw Error(
- `invalid length embedding data length: ${embeddingData?.length}`
+ `invalid length embedding data length: ${embeddingData?.length}`,
);
}
const comlinkCryptoWorker = await ComlinkCryptoWorker.getInstance();
const { file: encryptedEmbeddingData } =
await comlinkCryptoWorker.encryptEmbedding(embeddingData, file.key);
addLogLine(
- `putting clip embedding to server for file: ${file.metadata.title} fileID: ${file.id}`
+ `putting clip embedding to server for file: ${file.metadata.title} fileID: ${file.id}`,
);
await putEmbedding({
fileID: file.id,
@@ -342,12 +342,12 @@ class ClipServiceImpl {
private extractFileClipImageEmbedding = async (
model: Model,
- file: EnteFile
+ file: EnteFile,
) => {
const thumb = await downloadManager.getThumbnail(file);
const embedding = await ElectronAPIs.computeImageEmbedding(
model,
- thumb
+ thumb,
);
return embedding;
};
@@ -364,11 +364,11 @@ export const ClipService = new ClipServiceImpl();
const getNonClipEmbeddingExtractedFiles = async (
files: EnteFile[],
- existingEmbeddings: Embedding[]
+ existingEmbeddings: Embedding[],
) => {
const existingEmbeddingFileIds = new Set<number>();
existingEmbeddings.forEach((embedding) =>
- existingEmbeddingFileIds.add(embedding.fileID)
+ existingEmbeddingFileIds.add(embedding.fileID),
);
const idSet = new Set<number>();
return files.filter((file) => {
@@ -385,10 +385,10 @@ const getNonClipEmbeddingExtractedFiles = async (
export const computeClipMatchScore = async (
imageEmbedding: Float32Array,
- textEmbedding: Float32Array
+ textEmbedding: Float32Array,
) => {
if (imageEmbedding.length !== textEmbedding.length) {
- throw Error('imageEmbedding and textEmbedding length mismatch');
+ throw Error("imageEmbedding and textEmbedding length mismatch");
}
let score = 0;
let imageNormalization = 0;
@@ -411,7 +411,7 @@ export const computeClipMatchScore = async (
};
const getClipExtractionStatus = async (
- model: Model = Model.ONNX_CLIP
+ model: Model = Model.ONNX_CLIP,
): Promise<ClipExtractionStatus> => {
const user = getData(LS_KEYS.USER);
if (!user) {
@@ -421,7 +421,7 @@ const getClipExtractionStatus = async (
const localFiles = getPersonalFiles(await getLocalFiles(), user);
const pendingFiles = await getNonClipEmbeddingExtractedFiles(
localFiles,
- allEmbeddings
+ allEmbeddings,
);
return {
indexed: allEmbeddings.length,
diff --git a/apps/photos/src/services/collectionService.ts b/apps/photos/src/services/collectionService.ts
index a249656dad..7a9a251ef7 100644
--- a/apps/photos/src/services/collectionService.ts
+++ b/apps/photos/src/services/collectionService.ts
@@ -1,94 +1,97 @@
-import { getEndpoint } from '@ente/shared/network/api';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import localForage from '@ente/shared/storage/localForage';
-
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
-import { getActualKey } from '@ente/shared/user';
-import { getPublicKey } from './userService';
-import HTTPService from '@ente/shared/network/HTTPService';
-import { EnteFile } from 'types/file';
-import { logError } from '@ente/shared/sentry';
-import { CustomError } from '@ente/shared/error';
+import { getEndpoint } from "@ente/shared/network/api";
+import localForage from "@ente/shared/storage/localForage";
+import { getData, LS_KEYS } from "@ente/shared/storage/localStorage";
+
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { CustomError } from "@ente/shared/error";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { logError } from "@ente/shared/sentry";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
+import { getActualKey } from "@ente/shared/user";
+import { User } from "@ente/shared/user/types";
+import { REQUEST_BATCH_SIZE } from "constants/api";
import {
- sortFiles,
- groupFilesBasedOnCollectionID,
- getUniqueFiles,
-} from 'utils/file';
+ ALL_SECTION,
+ ARCHIVE_SECTION,
+ COLLECTION_LIST_SORT_BY,
+ COLLECTION_SORT_ORDER,
+ CollectionSummaryType,
+ CollectionType,
+ DUMMY_UNCATEGORIZED_COLLECTION,
+ HIDDEN_ITEMS_SECTION,
+ TRASH_SECTION,
+} from "constants/collection";
+import { t } from "i18next";
import {
- Collection,
- CollectionToFileMap,
AddToCollectionRequest,
- MoveToCollectionRequest,
- EncryptedFileKey,
- CreatePublicAccessTokenRequest,
- PublicURL,
- UpdatePublicURL,
- CollectionSummaries,
- CollectionSummary,
+ Collection,
CollectionFilesCount,
- EncryptedCollection,
CollectionMagicMetadata,
CollectionMagicMetadataProps,
CollectionPublicMagicMetadata,
- RemoveFromCollectionRequest,
CollectionShareeMagicMetadata,
-} from 'types/collection';
+ CollectionSummaries,
+ CollectionSummary,
+ CollectionToFileMap,
+ CreatePublicAccessTokenRequest,
+ EncryptedCollection,
+ EncryptedFileKey,
+ MoveToCollectionRequest,
+ PublicURL,
+ RemoveFromCollectionRequest,
+ UpdatePublicURL,
+} from "types/collection";
+import { EnteFile } from "types/file";
import {
- COLLECTION_LIST_SORT_BY,
- CollectionType,
- ARCHIVE_SECTION,
- TRASH_SECTION,
- COLLECTION_SORT_ORDER,
- ALL_SECTION,
- CollectionSummaryType,
- DUMMY_UNCATEGORIZED_COLLECTION,
- HIDDEN_ITEMS_SECTION,
-} from 'constants/collection';
-import { SUB_TYPE, UpdateMagicMetadataRequest } from 'types/magicMetadata';
+ EncryptedMagicMetadata,
+ SUB_TYPE,
+ UpdateMagicMetadataRequest,
+ VISIBILITY_STATE,
+} from "types/magicMetadata";
+import { FamilyData } from "types/user";
+import {
+ changeCollectionSubType,
+ getHiddenCollections,
+ getNonHiddenCollections,
+ isDefaultHiddenCollection,
+ isHiddenCollection,
+ isIncomingCollabShare,
+ isIncomingShare,
+ isOutgoingShare,
+ isQuickLinkCollection,
+ isSharedOnlyViaLink,
+ isValidMoveTarget,
+} from "utils/collection";
+import { batch } from "utils/common";
+import {
+ getUniqueFiles,
+ groupFilesBasedOnCollectionID,
+ sortFiles,
+} from "utils/file";
import {
isArchivedCollection,
isArchivedFile,
isPinnedCollection,
updateMagicMetadata,
-} from 'utils/magicMetadata';
-import { User } from '@ente/shared/user/types';
-import { FamilyData } from 'types/user';
-import {
- isQuickLinkCollection,
- isOutgoingShare,
- isSharedOnlyViaLink,
- isValidMoveTarget,
- isHiddenCollection,
- getNonHiddenCollections,
- changeCollectionSubType,
- isIncomingCollabShare,
- isIncomingShare,
- isDefaultHiddenCollection,
- getHiddenCollections,
-} from 'utils/collection';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { getLocalFiles } from './fileService';
-import { REQUEST_BATCH_SIZE } from 'constants/api';
-import { batch } from 'utils/common';
-import { t } from 'i18next';
-import { EncryptedMagicMetadata } from 'types/magicMetadata';
-import { VISIBILITY_STATE } from 'types/magicMetadata';
+} from "utils/magicMetadata";
+import { getLocalFiles } from "./fileService";
+import { getPublicKey } from "./userService";
const ENDPOINT = getEndpoint();
-const COLLECTION_TABLE = 'collections';
-const COLLECTION_UPDATION_TIME = 'collection-updation-time';
-const HIDDEN_COLLECTION_IDS = 'hidden-collection-ids';
+const COLLECTION_TABLE = "collections";
+const COLLECTION_UPDATION_TIME = "collection-updation-time";
+const HIDDEN_COLLECTION_IDS = "hidden-collection-ids";
-const UNCATEGORIZED_COLLECTION_NAME = 'Uncategorized';
-export const HIDDEN_COLLECTION_NAME = '.hidden';
-const FAVORITE_COLLECTION_NAME = 'Favorites';
+const UNCATEGORIZED_COLLECTION_NAME = "Uncategorized";
+export const HIDDEN_COLLECTION_NAME = ".hidden";
+const FAVORITE_COLLECTION_NAME = "Favorites";
export const getCollectionLastSyncTime = async (collection: Collection) =>
(await localForage.getItem<number>(`${collection.id}-time`)) ?? 0;
export const setCollectionLastSyncTime = async (
collection: Collection,
- time: number
+ time: number,
) => await localForage.setItem<number>(`${collection.id}-time`, time);
export const removeCollectionLastSyncTime = async (collection: Collection) =>
@@ -96,7 +99,7 @@ export const removeCollectionLastSyncTime = async (collection: Collection) =>
const getCollectionWithSecrets = async (
collection: EncryptedCollection,
- masterKey: string
+ masterKey: string,
): Promise<Collection> => {
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
const userID = getData(LS_KEYS.USER).id;
@@ -105,19 +108,19 @@ const getCollectionWithSecrets = async (
collectionKey = await cryptoWorker.decryptB64(
collection.encryptedKey,
collection.keyDecryptionNonce,
- masterKey
+ masterKey,
);
} else {
const keyAttributes = getData(LS_KEYS.KEY_ATTRIBUTES);
const secretKey = await cryptoWorker.decryptB64(
keyAttributes.encryptedSecretKey,
keyAttributes.secretKeyDecryptionNonce,
- masterKey
+ masterKey,
);
collectionKey = await cryptoWorker.boxSealOpen(
collection.encryptedKey,
keyAttributes.publicKey,
- secretKey
+ secretKey,
);
}
const collectionName =
@@ -125,7 +128,7 @@ const getCollectionWithSecrets = async (
(await cryptoWorker.decryptToUTF8(
collection.encryptedName,
collection.nameDecryptionNonce,
- collectionKey
+ collectionKey,
));
let collectionMagicMetadata: CollectionMagicMetadata;
@@ -135,7 +138,7 @@ const getCollectionWithSecrets = async (
data: await cryptoWorker.decryptMetadata(
collection.magicMetadata.data,
collection.magicMetadata.header,
- collectionKey
+ collectionKey,
),
};
}
@@ -146,7 +149,7 @@ const getCollectionWithSecrets = async (
data: await cryptoWorker.decryptMetadata(
collection.pubMagicMetadata.data,
collection.pubMagicMetadata.header,
- collectionKey
+ collectionKey,
),
};
}
@@ -158,7 +161,7 @@ const getCollectionWithSecrets = async (
data: await cryptoWorker.decryptMetadata(
collection.sharedMagicMetadata.data,
collection.sharedMagicMetadata.header,
- collectionKey
+ collectionKey,
),
};
}
@@ -176,7 +179,7 @@ const getCollectionWithSecrets = async (
const getCollections = async (
token: string,
sinceTime: number,
- key: string
+ key: string,
): Promise<Collection[]> => {
try {
const resp = await HTTPService.get(
@@ -184,7 +187,7 @@ const getCollections = async (
{
sinceTime,
},
- { 'X-Auth-Token': token }
+ { "X-Auth-Token": token },
);
const decryptedCollections: Collection[] = await Promise.all(
resp.data.collections.map(
@@ -200,25 +203,25 @@ const getCollections = async (
});
return collection;
}
- }
- )
+ },
+ ),
);
// only allow deleted or collection with key, filtering out collection whose decryption failed
const collections = decryptedCollections.filter(
- (collection) => collection.isDeleted || collection.key
+ (collection) => collection.isDeleted || collection.key,
);
return collections;
} catch (e) {
- logError(e, 'getCollections failed');
+ logError(e, "getCollections failed");
throw e;
}
};
export const getLocalCollections = async (
- type: 'normal' | 'hidden' = 'normal'
+ type: "normal" | "hidden" = "normal",
): Promise<Collection[]> => {
const collections = await getAllLocalCollections();
- return type === 'normal'
+ return type === "normal"
? getNonHiddenCollections(collections)
: getHiddenCollections(collections);
};
@@ -236,10 +239,10 @@ export const getHiddenCollectionIDs = async (): Promise<number[]> =>
(await localForage.getItem<number[]>(HIDDEN_COLLECTION_IDS)) ?? [];
export const getLatestCollections = async (
- type: 'normal' | 'hidden' = 'normal'
+ type: "normal" | "hidden" = "normal",
): Promise<Collection[]> => {
const collections = await getAllLatestCollections();
- return type === 'normal'
+ return type === "normal"
? getNonHiddenCollections(collections)
: getHiddenCollections(collections);
};
@@ -297,7 +300,7 @@ export const syncCollections = async () => {
collections.push(collection);
lastCollectionUpdationTime = Math.max(
lastCollectionUpdationTime,
- collection.updationTime
+ collection.updationTime,
);
}
@@ -308,17 +311,17 @@ export const syncCollections = async () => {
await localForage.setItem(COLLECTION_TABLE, collections);
await localForage.setItem(
COLLECTION_UPDATION_TIME,
- lastCollectionUpdationTime
+ lastCollectionUpdationTime,
);
await localForage.setItem(
HIDDEN_COLLECTION_IDS,
- updatedHiddenCollectionIDs
+ updatedHiddenCollectionIDs,
);
return collections;
};
export const getCollection = async (
- collectionID: number
+ collectionID: number,
): Promise<Collection> => {
try {
const token = getToken();
@@ -328,22 +331,22 @@ export const getCollection = async (
const resp = await HTTPService.get(
`${ENDPOINT}/collections/${collectionID}`,
null,
- { 'X-Auth-Token': token }
+ { "X-Auth-Token": token },
);
const key = await getActualKey();
const collectionWithSecrets = await getCollectionWithSecrets(
resp.data?.collection,
- key
+ key,
);
return collectionWithSecrets;
} catch (e) {
- logError(e, 'failed to get collection');
+ logError(e, "failed to get collection");
throw e;
}
};
export const getCollectionLatestFiles = (
- files: EnteFile[]
+ files: EnteFile[],
): CollectionToFileMap => {
const latestFiles = new Map<number, EnteFile>();
@@ -357,7 +360,7 @@ export const getCollectionLatestFiles = (
export const getCollectionCoverFiles = (
files: EnteFile[],
- collections: Collection[]
+ collections: Collection[],
): CollectionToFileMap => {
const collectionIDToFileMap = groupFilesBasedOnCollectionID(files);
@@ -369,9 +372,9 @@ export const getCollectionCoverFiles = (
return;
}
const coverID = collection.pubMagicMetadata?.data?.coverID;
- if (typeof coverID === 'number' && coverID > 0) {
+ if (typeof coverID === "number" && coverID > 0) {
const coverFile = collectionFiles.find(
- (file) => file.id === coverID
+ (file) => file.id === coverID,
);
if (coverFile) {
coverFiles.set(collection.id, coverFile);
@@ -381,7 +384,7 @@ export const getCollectionCoverFiles = (
if (collection.pubMagicMetadata?.data?.asc) {
coverFiles.set(
collection.id,
- collectionFiles[collectionFiles.length - 1]
+ collectionFiles[collectionFiles.length - 1],
);
} else {
coverFiles.set(collection.id, collectionFiles[0]);
@@ -391,7 +394,7 @@ export const getCollectionCoverFiles = (
};
export const getFavItemIds = async (
- files: EnteFile[]
+ files: EnteFile[],
): Promise<Set<number>> => {
const favCollection = await getFavCollection();
if (!favCollection) return new Set();
@@ -399,7 +402,7 @@ export const getFavItemIds = async (
return new Set(
files
.filter((file) => file.collectionID === favCollection.id)
- .map((file): number => file.id)
+ .map((file): number => file.id),
);
};
@@ -410,7 +413,7 @@ export const createAlbum = (albumName: string) => {
const createCollection = async (
collectionName: string,
type: CollectionType,
- magicMetadataProps?: CollectionMagicMetadataProps
+ magicMetadataProps?: CollectionMagicMetadataProps,
): Promise<Collection> => {
try {
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
@@ -427,7 +430,7 @@ const createCollection = async (
const { file: encryptedMagicMetadataProps } =
await cryptoWorker.encryptMetadata(
magicMetadataProps,
- collectionKey
+ collectionKey,
);
encryptedMagicMetadata = {
@@ -455,29 +458,29 @@ const createCollection = async (
const createdCollection = await postCollection(newCollection, token);
const decryptedCreatedCollection = await getCollectionWithSecrets(
createdCollection,
- encryptionKey
+ encryptionKey,
);
return decryptedCreatedCollection;
} catch (e) {
- logError(e, 'create collection failed');
+ logError(e, "create collection failed");
throw e;
}
};
const postCollection = async (
collectionData: EncryptedCollection,
- token: string
+ token: string,
): Promise<EncryptedCollection> => {
try {
const response = await HTTPService.post(
`${ENDPOINT}/collections`,
collectionData,
null,
- { 'X-Auth-Token': token }
+ { "X-Auth-Token": token },
);
return response.data.collection;
} catch (e) {
- logError(e, 'post Collection failed ');
+ logError(e, "post Collection failed ");
}
};
@@ -493,7 +496,7 @@ export const addToFavorites = async (file: EnteFile) => {
}
await addToCollection(favCollection, [file]);
} catch (e) {
- logError(e, 'failed to add to favorite');
+ logError(e, "failed to add to favorite");
}
};
@@ -505,13 +508,13 @@ export const removeFromFavorites = async (file: EnteFile) => {
}
await removeFromCollection(favCollection.id, [file]);
} catch (e) {
- logError(e, 'remove from favorite failed');
+ logError(e, "remove from favorite failed");
}
};
export const addToCollection = async (
collection: Collection,
- files: EnteFile[]
+ files: EnteFile[],
) => {
try {
const token = getToken();
@@ -529,19 +532,19 @@ export const addToCollection = async (
requestBody,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
}
} catch (e) {
- logError(e, 'Add to collection Failed ');
+ logError(e, "Add to collection Failed ");
throw e;
}
};
export const restoreToCollection = async (
collection: Collection,
- files: EnteFile[]
+ files: EnteFile[],
) => {
try {
const token = getToken();
@@ -559,19 +562,19 @@ export const restoreToCollection = async (
requestBody,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
}
} catch (e) {
- logError(e, 'restore to collection Failed ');
+ logError(e, "restore to collection Failed ");
throw e;
}
};
export const moveToCollection = async (
fromCollectionID: number,
toCollection: Collection,
- files: EnteFile[]
+ files: EnteFile[],
) => {
try {
const token = getToken();
@@ -590,26 +593,26 @@ export const moveToCollection = async (
requestBody,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
}
} catch (e) {
- logError(e, 'move to collection Failed ');
+ logError(e, "move to collection Failed ");
throw e;
}
};
const encryptWithNewCollectionKey = async (
newCollection: Collection,
- files: EnteFile[]
+ files: EnteFile[],
): Promise<EncryptedFileKey[]> => {
const fileKeysEncryptedWithNewCollection: EncryptedFileKey[] = [];
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
for (const file of files) {
const newEncryptedKey = await cryptoWorker.encryptToB64(
file.key,
- newCollection.key
+ newCollection.key,
);
const encryptedKey = newEncryptedKey.encryptedData;
const keyDecryptionNonce = newEncryptedKey.nonce;
@@ -625,7 +628,7 @@ const encryptWithNewCollectionKey = async (
export const removeFromCollection = async (
collectionID: number,
toRemoveFiles: EnteFile[],
- allFiles?: EnteFile[]
+ allFiles?: EnteFile[],
) => {
try {
const user: User = getData(LS_KEYS.USER);
@@ -646,7 +649,7 @@ export const removeFromCollection = async (
await removeUserFiles(collectionID, userFiles, allFiles);
}
} catch (e) {
- logError(e, 'remove from collection failed ');
+ logError(e, "remove from collection failed ");
throw e;
}
};
@@ -654,7 +657,7 @@ export const removeFromCollection = async (
export const removeUserFiles = async (
sourceCollectionID: number,
toRemoveFiles: EnteFile[],
- allFiles?: EnteFile[]
+ allFiles?: EnteFile[],
) => {
try {
if (!allFiles) {
@@ -665,7 +668,7 @@ export const removeUserFiles = async (
return toRemoveFilesIds.has(f.id);
});
const groupiedFiles = groupFilesBasedOnCollectionID(
- toRemoveFilesCopiesInOtherCollections
+ toRemoveFilesCopiesInOtherCollections,
);
const collections = await getLocalCollections();
@@ -692,11 +695,11 @@ export const removeUserFiles = async (
await moveToCollection(
sourceCollectionID,
targetCollection,
- toMoveFiles
+ toMoveFiles,
);
}
const leftFiles = toRemoveFiles.filter((f) =>
- toRemoveFilesIds.has(f.id)
+ toRemoveFilesIds.has(f.id),
);
if (leftFiles.length === 0) {
@@ -709,17 +712,17 @@ export const removeUserFiles = async (
await moveToCollection(
sourceCollectionID,
uncategorizedCollection,
- leftFiles
+ leftFiles,
);
} catch (e) {
- logError(e, 'remove user files failed ');
+ logError(e, "remove user files failed ");
throw e;
}
};
export const removeNonUserFiles = async (
collectionID: number,
- nonUserFiles: EnteFile[]
+ nonUserFiles: EnteFile[],
) => {
try {
const fileIDs = nonUserFiles.map((f) => f.id);
@@ -735,18 +738,18 @@ export const removeNonUserFiles = async (
`${ENDPOINT}/collections/v3/remove-files`,
request,
null,
- { 'X-Auth-Token': token }
+ { "X-Auth-Token": token },
);
}
} catch (e) {
- logError(e, 'remove non user files failed ');
+ logError(e, "remove non user files failed ");
throw e;
}
};
export const deleteCollection = async (
collectionID: number,
- keepFiles: boolean
+ keepFiles: boolean,
) => {
try {
if (keepFiles) {
@@ -762,10 +765,10 @@ export const deleteCollection = async (
`${ENDPOINT}/collections/v3/${collectionID}`,
null,
{ collectionID, keepFiles },
- { 'X-Auth-Token': token }
+ { "X-Auth-Token": token },
);
} catch (e) {
- logError(e, 'delete collection failed ');
+ logError(e, "delete collection failed ");
throw e;
}
};
@@ -778,17 +781,17 @@ export const leaveSharedAlbum = async (collectionID: number) => {
`${ENDPOINT}/collections/leave/${collectionID}`,
null,
null,
- { 'X-Auth-Token': token }
+ { "X-Auth-Token": token },
);
} catch (e) {
- logError(e, 'leave shared album failed ');
+ logError(e, "leave shared album failed ");
throw e;
}
};
export const updateCollectionMagicMetadata = async (
collection: Collection,
- updatedMagicMetadata: CollectionMagicMetadata
+ updatedMagicMetadata: CollectionMagicMetadata,
) => {
const token = getToken();
if (!token) {
@@ -799,7 +802,7 @@ export const updateCollectionMagicMetadata = async (
const { file: encryptedMagicMetadata } = await cryptoWorker.encryptMetadata(
updatedMagicMetadata.data,
- collection.key
+ collection.key,
);
const reqBody: UpdateMagicMetadataRequest = {
@@ -817,8 +820,8 @@ export const updateCollectionMagicMetadata = async (
reqBody,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
const updatedCollection: Collection = {
...collection,
@@ -832,7 +835,7 @@ export const updateCollectionMagicMetadata = async (
export const updateSharedCollectionMagicMetadata = async (
collection: Collection,
- updatedMagicMetadata: CollectionMagicMetadata
+ updatedMagicMetadata: CollectionMagicMetadata,
) => {
const token = getToken();
if (!token) {
@@ -843,7 +846,7 @@ export const updateSharedCollectionMagicMetadata = async (
const { file: encryptedMagicMetadata } = await cryptoWorker.encryptMetadata(
updatedMagicMetadata.data,
- collection.key
+ collection.key,
);
const reqBody: UpdateMagicMetadataRequest = {
@@ -861,8 +864,8 @@ export const updateSharedCollectionMagicMetadata = async (
reqBody,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
const updatedCollection: Collection = {
...collection,
@@ -876,7 +879,7 @@ export const updateSharedCollectionMagicMetadata = async (
export const updatePublicCollectionMagicMetadata = async (
collection: Collection,
- updatedPublicMagicMetadata: CollectionPublicMagicMetadata
+ updatedPublicMagicMetadata: CollectionPublicMagicMetadata,
) => {
const token = getToken();
if (!token) {
@@ -887,7 +890,7 @@ export const updatePublicCollectionMagicMetadata = async (
const { file: encryptedMagicMetadata } = await cryptoWorker.encryptMetadata(
updatedPublicMagicMetadata.data,
- collection.key
+ collection.key,
);
const reqBody: UpdateMagicMetadataRequest = {
@@ -905,8 +908,8 @@ export const updatePublicCollectionMagicMetadata = async (
reqBody,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
const updatedCollection: Collection = {
...collection,
@@ -920,7 +923,7 @@ export const updatePublicCollectionMagicMetadata = async (
export const renameCollection = async (
collection: Collection,
- newCollectionName: string
+ newCollectionName: string,
) => {
if (isQuickLinkCollection(collection)) {
// Convert quick link collection to normal collection on rename
@@ -940,15 +943,15 @@ export const renameCollection = async (
collectionRenameRequest,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
};
export const shareCollection = async (
collection: Collection,
withUserEmail: string,
- role: string
+ role: string,
) => {
try {
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
@@ -956,7 +959,7 @@ export const shareCollection = async (
const publicKey: string = await getPublicKey(withUserEmail);
const encryptedKey = await cryptoWorker.boxSeal(
collection.key,
- publicKey
+ publicKey,
);
const shareCollectionRequest = {
collectionID: collection.id,
@@ -969,18 +972,18 @@ export const shareCollection = async (
shareCollectionRequest,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
} catch (e) {
- logError(e, 'share collection failed ');
+ logError(e, "share collection failed ");
throw e;
}
};
export const unshareCollection = async (
collection: Collection,
- withUserEmail: string
+ withUserEmail: string,
) => {
try {
const token = getToken();
@@ -993,11 +996,11 @@ export const unshareCollection = async (
shareCollectionRequest,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
} catch (e) {
- logError(e, 'unshare collection failed ');
+ logError(e, "unshare collection failed ");
}
};
@@ -1015,12 +1018,12 @@ export const createShareableURL = async (collection: Collection) => {
createPublicAccessTokenRequest,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
return resp.data.result as PublicURL;
} catch (e) {
- logError(e, 'createShareableURL failed ');
+ logError(e, "createShareableURL failed ");
throw e;
}
};
@@ -1036,17 +1039,17 @@ export const deleteShareableURL = async (collection: Collection) => {
null,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
} catch (e) {
- logError(e, 'deleteShareableURL failed ');
+ logError(e, "deleteShareableURL failed ");
throw e;
}
};
export const updateShareableURL = async (
- request: UpdatePublicURL
+ request: UpdatePublicURL,
): Promise<PublicURL> => {
try {
const token = getToken();
@@ -1058,12 +1061,12 @@ export const updateShareableURL = async (
request,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
return res.data.result as PublicURL;
} catch (e) {
- logError(e, 'updateShareableURL failed ');
+ logError(e, "updateShareableURL failed ");
throw e;
}
};
@@ -1079,20 +1082,20 @@ export const getFavCollection = async () => {
export const getNonEmptyCollections = (
collections: Collection[],
- files: EnteFile[]
+ files: EnteFile[],
) => {
const nonEmptyCollectionsIds = new Set<number>();
for (const file of files) {
nonEmptyCollectionsIds.add(file.collectionID);
}
return collections.filter((collection) =>
- nonEmptyCollectionsIds.has(collection.id)
+ nonEmptyCollectionsIds.has(collection.id),
);
};
export function sortCollectionSummaries(
collectionSummaries: CollectionSummary[],
- sortBy: COLLECTION_LIST_SORT_BY
+ sortBy: COLLECTION_LIST_SORT_BY,
) {
return collectionSummaries
.sort((a, b) => {
@@ -1112,7 +1115,7 @@ export function sortCollectionSummaries(
.sort(
(a, b) =>
COLLECTION_SORT_ORDER.get(a.type) -
- COLLECTION_SORT_ORDER.get(b.type)
+ COLLECTION_SORT_ORDER.get(b.type),
);
}
@@ -1134,7 +1137,7 @@ function compareCollectionsLatestFile(first: EnteFile, second: EnteFile) {
export function getCollectionSummaries(
user: User,
collections: Collection[],
- files: EnteFile[]
+ files: EnteFile[],
): CollectionSummaries {
const collectionSummaries: CollectionSummaries = new Map();
const collectionLatestFiles = getCollectionLatestFiles(files);
@@ -1176,9 +1179,9 @@ export function getCollectionSummaries(
let CollectionSummaryItemName: string;
if (type === CollectionSummaryType.uncategorized) {
- CollectionSummaryItemName = t('UNCATEGORIZED');
+ CollectionSummaryItemName = t("UNCATEGORIZED");
} else if (type === CollectionSummaryType.favorites) {
- CollectionSummaryItemName = t('FAVORITES');
+ CollectionSummaryItemName = t("FAVORITES");
} else {
CollectionSummaryItemName = collection.name;
}
@@ -1198,7 +1201,7 @@ export function getCollectionSummaries(
if (!hasUncategorizedCollection) {
collectionSummaries.set(
DUMMY_UNCATEGORIZED_COLLECTION,
- getDummyUncategorizedCollectionSummary()
+ getDummyUncategorizedCollectionSummary(),
);
}
@@ -1217,16 +1220,16 @@ function getCollectionsFileCount(files: EnteFile[]): CollectionFilesCount {
export function getSectionSummaries(
files: EnteFile[],
trashedFiles: EnteFile[],
- archivedCollections: Set<number>
+ archivedCollections: Set<number>,
): CollectionSummaries {
const collectionSummaries: CollectionSummaries = new Map();
collectionSummaries.set(
ALL_SECTION,
- getAllSectionSummary(files, archivedCollections)
+ getAllSectionSummary(files, archivedCollections),
);
collectionSummaries.set(
TRASH_SECTION,
- getTrashedCollectionSummary(trashedFiles)
+ getTrashedCollectionSummary(trashedFiles),
);
collectionSummaries.set(ARCHIVE_SECTION, getArchivedSectionSummary(files));
@@ -1235,15 +1238,15 @@ export function getSectionSummaries(
function getAllSectionSummary(
files: EnteFile[],
- archivedCollections: Set<number>
+ archivedCollections: Set<number>,
): CollectionSummary {
const allSectionFiles = getAllSectionVisibleFiles(
files,
- archivedCollections
+ archivedCollections,
);
return {
id: ALL_SECTION,
- name: t('ALL_SECTION_NAME'),
+ name: t("ALL_SECTION_NAME"),
type: CollectionSummaryType.all,
coverFile: allSectionFiles?.[0],
latestFile: allSectionFiles?.[0],
@@ -1254,7 +1257,7 @@ function getAllSectionSummary(
function getAllSectionVisibleFiles(
files: EnteFile[],
- archivedCollections: Set<number>
+ archivedCollections: Set<number>,
): EnteFile[] {
const allSectionVisibleFiles = getUniqueFiles(
files.filter((file) => {
@@ -1265,7 +1268,7 @@ function getAllSectionVisibleFiles(
return false;
}
return true;
- })
+ }),
);
return allSectionVisibleFiles;
}
@@ -1273,7 +1276,7 @@ function getAllSectionVisibleFiles(
export function getDummyUncategorizedCollectionSummary(): CollectionSummary {
return {
id: DUMMY_UNCATEGORIZED_COLLECTION,
- name: t('UNCATEGORIZED'),
+ name: t("UNCATEGORIZED"),
type: CollectionSummaryType.uncategorized,
latestFile: null,
coverFile: null,
@@ -1283,14 +1286,14 @@ export function getDummyUncategorizedCollectionSummary(): CollectionSummary {
}
export function getArchivedSectionSummary(
- files: EnteFile[]
+ files: EnteFile[],
): CollectionSummary {
const archivedFiles = getUniqueFiles(
- files.filter((file) => isArchivedFile(file))
+ files.filter((file) => isArchivedFile(file)),
);
return {
id: ARCHIVE_SECTION,
- name: t('ARCHIVE_SECTION_NAME'),
+ name: t("ARCHIVE_SECTION_NAME"),
type: CollectionSummaryType.archive,
coverFile: null,
latestFile: archivedFiles?.[0],
@@ -1301,21 +1304,21 @@ export function getArchivedSectionSummary(
export function getHiddenItemsSummary(
hiddenFiles: EnteFile[],
- hiddenCollections: Collection[]
+ hiddenCollections: Collection[],
): CollectionSummary {
const defaultHiddenCollectionIds = new Set(
hiddenCollections
.filter((collection) => isDefaultHiddenCollection(collection))
- .map((collection) => collection.id)
+ .map((collection) => collection.id),
);
const hiddenItems = getUniqueFiles(
hiddenFiles.filter((file) =>
- defaultHiddenCollectionIds.has(file.collectionID)
- )
+ defaultHiddenCollectionIds.has(file.collectionID),
+ ),
);
return {
id: HIDDEN_ITEMS_SECTION,
- name: t('HIDDEN_ITEMS'),
+ name: t("HIDDEN_ITEMS"),
type: CollectionSummaryType.hiddenItems,
coverFile: hiddenItems?.[0],
latestFile: hiddenItems?.[0],
@@ -1325,11 +1328,11 @@ export function getHiddenItemsSummary(
}
export function getTrashedCollectionSummary(
- trashedFiles: EnteFile[]
+ trashedFiles: EnteFile[],
): CollectionSummary {
return {
id: TRASH_SECTION,
- name: t('TRASH'),
+ name: t("TRASH"),
type: CollectionSummaryType.trash,
coverFile: null,
latestFile: trashedFiles?.[0],
@@ -1339,13 +1342,13 @@ export function getTrashedCollectionSummary(
}
export async function getUncategorizedCollection(
- collections?: Collection[]
+ collections?: Collection[],
): Promise<Collection> {
if (!collections) {
collections = await getLocalCollections();
}
const uncategorizedCollection = collections.find(
- (collection) => collection.type === CollectionType.uncategorized
+ (collection) => collection.type === CollectionType.uncategorized,
);
return uncategorizedCollection;
@@ -1354,14 +1357,14 @@ export async function getUncategorizedCollection(
export function createUnCategorizedCollection() {
return createCollection(
UNCATEGORIZED_COLLECTION_NAME,
- CollectionType.uncategorized
+ CollectionType.uncategorized,
);
}
export async function getDefaultHiddenCollection(): Promise<Collection> {
- const collections = await getLocalCollections('hidden');
+ const collections = await getLocalCollections("hidden");
const hiddenCollection = collections.find((collection) =>
- isDefaultHiddenCollection(collection)
+ isDefaultHiddenCollection(collection),
);
return hiddenCollection;
@@ -1389,14 +1392,14 @@ export async function moveToHiddenCollection(files: EnteFile[]) {
await moveToCollection(collectionID, hiddenCollection, files);
}
} catch (e) {
- logError(e, 'move to hidden collection failed ');
+ logError(e, "move to hidden collection failed ");
throw e;
}
}
export async function unhideToCollection(
collection: Collection,
- files: EnteFile[]
+ files: EnteFile[],
) {
try {
const groupiedFiles = groupFilesBasedOnCollectionID(files);
@@ -1408,14 +1411,14 @@ export async function unhideToCollection(
await moveToCollection(collectionID, collection, files);
}
} catch (e) {
- logError(e, 'unhide to collection failed ');
+ logError(e, "unhide to collection failed ");
throw e;
}
}
export const constructUserIDToEmailMap = (
user: User,
- collections: Collection[]
+ collections: Collection[],
): Map<number, string> => {
try {
const userIDToEmailMap = new Map<number, string>();
@@ -1433,7 +1436,7 @@ export const constructUserIDToEmailMap = (
});
return userIDToEmailMap;
} catch (e) {
- logError('Error Mapping UserId to email:', e);
+ logError("Error Mapping UserId to email:", e);
return new Map<number, string>();
}
};
@@ -1441,7 +1444,7 @@ export const constructUserIDToEmailMap = (
export const constructEmailList = (
user: User,
collections: Collection[],
- familyData: FamilyData
+ familyData: FamilyData,
): string[] => {
const emails = collections
.map((item) => {
diff --git a/apps/photos/src/services/deduplicationService.ts b/apps/photos/src/services/deduplicationService.ts
index 4daeccd510..e261f8e771 100644
--- a/apps/photos/src/services/deduplicationService.ts
+++ b/apps/photos/src/services/deduplicationService.ts
@@ -1,11 +1,11 @@
-import { FILE_TYPE } from 'constants/file';
-import { EnteFile } from 'types/file';
-import { Metadata } from 'types/upload';
-import { getEndpoint } from '@ente/shared/network/api';
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
-import { logError } from '@ente/shared/sentry';
-import { hasFileHash } from 'utils/upload';
-import HTTPService from '@ente/shared/network/HTTPService';
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getEndpoint } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
+import { FILE_TYPE } from "constants/file";
+import { EnteFile } from "types/file";
+import { Metadata } from "types/upload";
+import { hasFileHash } from "utils/upload";
const ENDPOINT = getEndpoint();
@@ -23,7 +23,7 @@ export interface Duplicate {
export async function getDuplicates(
files: EnteFile[],
- collectionNameMap: Map<number, string>
+ collectionNameMap: Map<number, string>,
) {
try {
const ascDupes = await fetchDuplicateFileIDs();
@@ -48,7 +48,7 @@ export async function getDuplicates(
}
duplicateFiles = await sortDuplicateFiles(
duplicateFiles,
- collectionNameMap
+ collectionNameMap,
);
if (duplicateFiles.length > 1) {
@@ -64,7 +64,7 @@ export async function getDuplicates(
return result;
} catch (e) {
- logError(e, 'failed to get duplicate files');
+ logError(e, "failed to get duplicate files");
}
}
@@ -86,7 +86,7 @@ function getDupesGroupedBySameFileHashes(dupe: Duplicate) {
...groupDupesByFileHashes({
files: fileWithHashes,
size: dupe.size,
- })
+ }),
);
}
@@ -121,7 +121,7 @@ function groupDupesByFileHashes(dupe: Duplicate) {
if (
areFileHashesSame(
filesSortedByFileHash[i - 1].file.metadata,
- filesSortedByFileHash[i].file.metadata
+ filesSortedByFileHash[i].file.metadata,
)
) {
sameHashFiles.push(filesSortedByFileHash[i].file);
@@ -151,18 +151,18 @@ async function fetchDuplicateFileIDs() {
`${ENDPOINT}/files/duplicates`,
null,
{
- 'X-Auth-Token': getToken(),
- }
+ "X-Auth-Token": getToken(),
+ },
);
return (response.data as DuplicatesResponse).duplicates;
} catch (e) {
- logError(e, 'failed to fetch duplicate file IDs');
+ logError(e, "failed to fetch duplicate file IDs");
}
}
async function sortDuplicateFiles(
files: EnteFile[],
- collectionNameMap: Map<number, string>
+ collectionNameMap: Map<number, string>,
) {
return files.sort((firstFile, secondFile) => {
const firstCollectionName = collectionNameMap
diff --git a/apps/photos/src/services/download/clients/photos.ts b/apps/photos/src/services/download/clients/photos.ts
index 415219f56f..11666041de 100644
--- a/apps/photos/src/services/download/clients/photos.ts
+++ b/apps/photos/src/services/download/clients/photos.ts
@@ -1,14 +1,14 @@
-import HTTPService from '@ente/shared/network/HTTPService';
-import { getFileURL, getThumbnailURL } from '@ente/shared/network/api';
-import { EnteFile } from 'types/file';
-import { DownloadClient } from 'services/download';
-import { CustomError } from '@ente/shared/error';
-import { retryAsyncFunction } from 'utils/network';
+import { CustomError } from "@ente/shared/error";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getFileURL, getThumbnailURL } from "@ente/shared/network/api";
+import { DownloadClient } from "services/download";
+import { EnteFile } from "types/file";
+import { retryAsyncFunction } from "utils/network";
export class PhotosDownloadClient implements DownloadClient {
constructor(
private token: string,
- private timeout: number
+ private timeout: number,
) {}
updateTokens(token: string) {
this.token = token;
@@ -26,11 +26,11 @@ export class PhotosDownloadClient implements DownloadClient {
HTTPService.get(
getThumbnailURL(file.id),
null,
- { 'X-Auth-Token': this.token },
- { responseType: 'arraybuffer', timeout: this.timeout }
- )
+ { "X-Auth-Token": this.token },
+ { responseType: "arraybuffer", timeout: this.timeout },
+ ),
);
- if (typeof resp.data === 'undefined') {
+ if (typeof resp.data === "undefined") {
throw Error(CustomError.REQUEST_FAILED);
}
return new Uint8Array(resp.data);
@@ -38,7 +38,7 @@ export class PhotosDownloadClient implements DownloadClient {
async downloadFile(
file: EnteFile,
- onDownloadProgress: (event: { loaded: number; total: number }) => void
+ onDownloadProgress: (event: { loaded: number; total: number }) => void,
): Promise<Uint8Array> {
if (!this.token) {
throw Error(CustomError.TOKEN_MISSING);
@@ -47,15 +47,15 @@ export class PhotosDownloadClient implements DownloadClient {
HTTPService.get(
getFileURL(file.id),
null,
- { 'X-Auth-Token': this.token },
+ { "X-Auth-Token": this.token },
{
- responseType: 'arraybuffer',
+ responseType: "arraybuffer",
timeout: this.timeout,
onDownloadProgress,
- }
- )
+ },
+ ),
);
- if (typeof resp.data === 'undefined') {
+ if (typeof resp.data === "undefined") {
throw Error(CustomError.REQUEST_FAILED);
}
return new Uint8Array(resp.data);
@@ -68,9 +68,9 @@ export class PhotosDownloadClient implements DownloadClient {
return retryAsyncFunction(() =>
fetch(getFileURL(file.id), {
headers: {
- 'X-Auth-Token': this.token,
+ "X-Auth-Token": this.token,
},
- })
+ }),
);
}
}
diff --git a/apps/photos/src/services/download/clients/publicAlbums.ts b/apps/photos/src/services/download/clients/publicAlbums.ts
index f21ec71a5a..f3412595ce 100644
--- a/apps/photos/src/services/download/clients/publicAlbums.ts
+++ b/apps/photos/src/services/download/clients/publicAlbums.ts
@@ -1,18 +1,18 @@
-import HTTPService from '@ente/shared/network/HTTPService';
+import { CustomError } from "@ente/shared/error";
+import HTTPService from "@ente/shared/network/HTTPService";
import {
getPublicCollectionFileURL,
getPublicCollectionThumbnailURL,
-} from '@ente/shared/network/api';
-import { EnteFile } from 'types/file';
-import { DownloadClient } from 'services/download';
-import { CustomError } from '@ente/shared/error';
-import { retryAsyncFunction } from 'utils/network';
+} from "@ente/shared/network/api";
+import { DownloadClient } from "services/download";
+import { EnteFile } from "types/file";
+import { retryAsyncFunction } from "utils/network";
export class PublicAlbumsDownloadClient implements DownloadClient {
constructor(
private token: string,
private passwordToken: string,
- private timeout: number
+ private timeout: number,
) {}
updateTokens(token: string, passwordToken: string) {
@@ -32,15 +32,15 @@ export class PublicAlbumsDownloadClient implements DownloadClient {
getPublicCollectionThumbnailURL(file.id),
null,
{
- 'X-Auth-Access-Token': this.token,
+ "X-Auth-Access-Token": this.token,
...(this.passwordToken && {
- 'X-Auth-Access-Token-JWT': this.passwordToken,
+ "X-Auth-Access-Token-JWT": this.passwordToken,
}),
},
- { responseType: 'arraybuffer' }
+ { responseType: "arraybuffer" },
);
- if (typeof resp.data === 'undefined') {
+ if (typeof resp.data === "undefined") {
throw Error(CustomError.REQUEST_FAILED);
}
return new Uint8Array(resp.data);
@@ -48,7 +48,7 @@ export class PublicAlbumsDownloadClient implements DownloadClient {
downloadFile = async (
file: EnteFile,
- onDownloadProgress: (event: { loaded: number; total: number }) => void
+ onDownloadProgress: (event: { loaded: number; total: number }) => void,
) => {
if (!this.token) {
throw Error(CustomError.TOKEN_MISSING);
@@ -58,20 +58,20 @@ export class PublicAlbumsDownloadClient implements DownloadClient {
getPublicCollectionFileURL(file.id),
null,
{
- 'X-Auth-Access-Token': this.token,
+ "X-Auth-Access-Token": this.token,
...(this.passwordToken && {
- 'X-Auth-Access-Token-JWT': this.passwordToken,
+ "X-Auth-Access-Token-JWT": this.passwordToken,
}),
},
{
- responseType: 'arraybuffer',
+ responseType: "arraybuffer",
timeout: this.timeout,
onDownloadProgress,
- }
- )
+ },
+ ),
);
- if (typeof resp.data === 'undefined') {
+ if (typeof resp.data === "undefined") {
throw Error(CustomError.REQUEST_FAILED);
}
return new Uint8Array(resp.data);
@@ -84,12 +84,12 @@ export class PublicAlbumsDownloadClient implements DownloadClient {
return retryAsyncFunction(() =>
fetch(getPublicCollectionFileURL(file.id), {
headers: {
- 'X-Auth-Access-Token': this.token,
+ "X-Auth-Access-Token": this.token,
...(this.passwordToken && {
- 'X-Auth-Access-Token-JWT': this.passwordToken,
+ "X-Auth-Access-Token-JWT": this.passwordToken,
}),
},
- })
+ }),
);
}
}
diff --git a/apps/photos/src/services/download/index.ts b/apps/photos/src/services/download/index.ts
index 42b2cea16e..3d71ed8ad1 100644
--- a/apps/photos/src/services/download/index.ts
+++ b/apps/photos/src/services/download/index.ts
@@ -1,25 +1,25 @@
+import { EnteFile } from "types/file";
import {
generateStreamFromArrayBuffer,
getRenderableFileURL,
-} from 'utils/file';
-import { EnteFile } from 'types/file';
-
-import { logError } from '@ente/shared/sentry';
-import { FILE_TYPE } from 'constants/file';
-import { CustomError } from '@ente/shared/error';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { CacheStorageService } from '@ente/shared/storage/cacheStorage';
-import { CACHES } from '@ente/shared/storage/cacheStorage/constants';
-import { Remote } from 'comlink';
-import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
-import { LimitedCache } from '@ente/shared/storage/cacheStorage/types';
-import { addLogLine } from '@ente/shared/logging';
-import { APPS } from '@ente/shared/apps/constants';
-import { PhotosDownloadClient } from './clients/photos';
-import { PublicAlbumsDownloadClient } from './clients/publicAlbums';
-import isElectron from 'is-electron';
-import { isInternalUser } from 'utils/user';
-import { Events, eventBus } from '@ente/shared/events';
+} from "utils/file";
+
+import { APPS } from "@ente/shared/apps/constants";
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { DedicatedCryptoWorker } from "@ente/shared/crypto/internal/crypto.worker";
+import { CustomError } from "@ente/shared/error";
+import { Events, eventBus } from "@ente/shared/events";
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import { CacheStorageService } from "@ente/shared/storage/cacheStorage";
+import { CACHES } from "@ente/shared/storage/cacheStorage/constants";
+import { LimitedCache } from "@ente/shared/storage/cacheStorage/types";
+import { Remote } from "comlink";
+import { FILE_TYPE } from "constants/file";
+import isElectron from "is-electron";
+import { isInternalUser } from "utils/user";
+import { PhotosDownloadClient } from "./clients/photos";
+import { PublicAlbumsDownloadClient } from "./clients/publicAlbums";
export type LivePhotoSourceURL = {
image: () => Promise<string>;
@@ -35,7 +35,7 @@ export type SourceURLs = {
url: string | LivePhotoSourceURL | LoadedLivePhotoSourceURL;
isOriginal: boolean;
isRenderable: boolean;
- type: 'normal' | 'livePhoto';
+ type: "normal" | "livePhoto";
};
export type OnDownloadProgress = (event: {
@@ -48,11 +48,11 @@ export interface DownloadClient {
updateTimeout: (timeout: number) => void;
downloadThumbnail: (
file: EnteFile,
- timeout?: number
+ timeout?: number,
) => Promise<Uint8Array>;
downloadFile: (
file: EnteFile,
- onDownloadProgress: OnDownloadProgress
+ onDownloadProgress: OnDownloadProgress,
) => Promise<Uint8Array>;
downloadFileStream: (file: EnteFile) => Promise<Response>;
}
@@ -78,11 +78,11 @@ class DownloadManagerImpl {
async init(
app: APPS,
tokens?: { token: string; passwordToken?: string } | { token: string },
- timeout?: number
+ timeout?: number,
) {
try {
if (this.ready) {
- addLogLine('DownloadManager already initialized');
+ addLogLine("DownloadManager already initialized");
return;
}
this.downloadClient = createDownloadClient(app, tokens, timeout);
@@ -92,14 +92,14 @@ class DownloadManagerImpl {
this.ready = true;
eventBus.on(Events.LOGOUT, this.logoutHandler.bind(this), this);
} catch (e) {
- logError(e, 'DownloadManager init failed');
+ logError(e, "DownloadManager init failed");
throw e;
}
}
private async logoutHandler() {
try {
- addLogLine('downloadManger logoutHandler started');
+ addLogLine("downloadManger logoutHandler started");
this.ready = false;
this.cryptoWorker = null;
this.downloadClient = null;
@@ -108,9 +108,9 @@ class DownloadManagerImpl {
this.thumbnailObjectURLPromises.clear();
this.fileDownloadProgress.clear();
this.progressUpdater = () => {};
- addLogLine('downloadManager logoutHandler completed');
+ addLogLine("downloadManager logoutHandler completed");
} catch (e) {
- logError(e, 'downloadManager logoutHandler failed');
+ logError(e, "downloadManager logoutHandler failed");
}
}
@@ -138,14 +138,14 @@ class DownloadManagerImpl {
private async getCachedThumbnail(fileID: number) {
try {
const cacheResp: Response = await this.thumbnailCache?.match(
- fileID.toString()
+ fileID.toString(),
);
if (cacheResp) {
return new Uint8Array(await cacheResp.arrayBuffer());
}
} catch (e) {
- logError(e, 'failed to get cached thumbnail');
+ logError(e, "failed to get cached thumbnail");
throw e;
}
}
@@ -156,11 +156,11 @@ class DownloadManagerImpl {
}
const cacheResp: Response = await this.diskFileCache?.match(
file.id.toString(),
- { sizeInBytes: file.info?.fileSize }
+ { sizeInBytes: file.info?.fileSize },
);
return cacheResp?.clone();
} catch (e) {
- logError(e, 'failed to get cached file');
+ logError(e, "failed to get cached file");
throw e;
}
}
@@ -170,7 +170,7 @@ class DownloadManagerImpl {
const decrypted = await this.cryptoWorker.decryptThumbnail(
encrypted,
await this.cryptoWorker.fromB64(file.thumbnail.decryptionHeader),
- file.key
+ file.key,
);
return decrypted;
};
@@ -192,12 +192,12 @@ class DownloadManagerImpl {
this.thumbnailCache
?.put(file.id.toString(), new Response(thumb))
.catch((e) => {
- logError(e, 'thumb cache put failed');
+ logError(e, "thumb cache put failed");
// TODO: handle storage full exception.
});
return thumb;
} catch (e) {
- logError(e, 'getThumbnail failed');
+ logError(e, "getThumbnail failed");
throw e;
}
}
@@ -210,7 +210,7 @@ class DownloadManagerImpl {
if (!this.thumbnailObjectURLPromises.has(file.id)) {
const thumbPromise = this.getThumbnail(file, localOnly);
const thumbURLPromise = thumbPromise.then(
- (thumb) => thumb && URL.createObjectURL(new Blob([thumb]))
+ (thumb) => thumb && URL.createObjectURL(new Blob([thumb])),
);
this.thumbnailObjectURLPromises.set(file.id, thumbURLPromise);
}
@@ -222,14 +222,14 @@ class DownloadManagerImpl {
return thumb;
} catch (e) {
this.thumbnailObjectURLPromises.delete(file.id);
- logError(e, 'get DownloadManager preview Failed');
+ logError(e, "get DownloadManager preview Failed");
throw e;
}
}
getFileForPreview = async (
file: EnteFile,
- forceConvert = false
+ forceConvert = false,
): Promise<SourceURLs> => {
try {
if (!this.ready) {
@@ -237,7 +237,7 @@ class DownloadManagerImpl {
}
const getFileForPreviewPromise = async () => {
const fileBlob = await new Response(
- await this.getFile(file, true)
+ await this.getFile(file, true),
).blob();
const { url: originalFileURL } =
await this.fileObjectURLPromises.get(file.id);
@@ -246,28 +246,28 @@ class DownloadManagerImpl {
file,
fileBlob,
originalFileURL as string,
- forceConvert
+ forceConvert,
);
return converted;
};
if (forceConvert || !this.fileConversionPromises.has(file.id)) {
this.fileConversionPromises.set(
file.id,
- getFileForPreviewPromise()
+ getFileForPreviewPromise(),
);
}
const fileURLs = await this.fileConversionPromises.get(file.id);
return fileURLs;
} catch (e) {
this.fileConversionPromises.delete(file.id);
- logError(e, 'download manager getFileForPreview Failed');
+ logError(e, "download manager getFileForPreview Failed");
throw e;
}
};
async getFile(
file: EnteFile,
- cacheInMemory = false
+ cacheInMemory = false,
): Promise<ReadableStream<Uint8Array>> {
try {
if (!this.ready) {
@@ -280,7 +280,7 @@ class DownloadManagerImpl {
url: URL.createObjectURL(fileBlob),
isOriginal: true,
isRenderable: false,
- type: 'normal',
+ type: "normal",
};
};
if (!this.fileObjectURLPromises.has(file.id)) {
@@ -298,19 +298,19 @@ class DownloadManagerImpl {
}
} catch (e) {
this.fileObjectURLPromises.delete(file.id);
- logError(e, 'download manager getFile Failed');
+ logError(e, "download manager getFile Failed");
throw e;
}
}
private async downloadFile(
- file: EnteFile
+ file: EnteFile,
): Promise<ReadableStream<Uint8Array>> {
try {
addLogLine(`download attempted for fileID:${file.id}`);
const onDownloadProgress = this.trackDownloadProgress(
file.id,
- file.info?.fileSize
+ file.info?.fileSize,
);
if (
file.metadata.fileType === FILE_TYPE.IMAGE ||
@@ -321,14 +321,14 @@ class DownloadManagerImpl {
encrypted = new Response(
await this.downloadClient.downloadFile(
file,
- onDownloadProgress
- )
+ onDownloadProgress,
+ ),
);
if (this.diskFileCache) {
this.diskFileCache
.put(file.id.toString(), encrypted.clone())
.catch((e) => {
- logError(e, 'file cache put failed');
+ logError(e, "file cache put failed");
// TODO: handle storage full exception.
});
}
@@ -338,14 +338,14 @@ class DownloadManagerImpl {
const decrypted = await this.cryptoWorker.decryptFile(
new Uint8Array(await encrypted.arrayBuffer()),
await this.cryptoWorker.fromB64(
- file.file.decryptionHeader
+ file.file.decryptionHeader,
),
- file.key
+ file.key,
);
return generateStreamFromArrayBuffer(decrypted);
} catch (e) {
if (e.message === CustomError.PROCESSING_FAILED) {
- logError(e, 'Failed to process file', {
+ logError(e, "Failed to process file", {
fileID: file.id,
fromMobile:
!!file.metadata.localID ||
@@ -353,7 +353,7 @@ class DownloadManagerImpl {
!!file.metadata.version,
});
addLogLine(
- `Failed to process file with fileID:${file.id}, localID: ${file.metadata.localID}, version: ${file.metadata.version}, deviceFolder:${file.metadata.deviceFolder} with error: ${e.message}`
+ `Failed to process file with fileID:${file.id}, localID: ${file.metadata.localID}, version: ${file.metadata.version}, deviceFolder:${file.metadata.deviceFolder} with error: ${e.message}`,
);
}
throw e;
@@ -367,13 +367,13 @@ class DownloadManagerImpl {
this.diskFileCache
.put(file.id.toString(), resp.clone())
.catch((e) => {
- logError(e, 'file cache put failed');
+ logError(e, "file cache put failed");
});
}
}
const reader = resp.body.getReader();
- const contentLength = +resp.headers.get('Content-Length') ?? 0;
+ const contentLength = +resp.headers.get("Content-Length") ?? 0;
let downloadedBytes = 0;
const stream = new ReadableStream({
@@ -381,15 +381,15 @@ class DownloadManagerImpl {
try {
const decryptionHeader =
await this.cryptoWorker.fromB64(
- file.file.decryptionHeader
+ file.file.decryptionHeader,
);
const fileKey = await this.cryptoWorker.fromB64(
- file.key
+ file.key,
);
const { pullState, decryptionChunkSize } =
await this.cryptoWorker.initChunkDecryption(
decryptionHeader,
- fileKey
+ fileKey,
);
let data = new Uint8Array();
// The following function handles each data chunk
@@ -405,32 +405,32 @@ class DownloadManagerImpl {
total: contentLength,
});
const buffer = new Uint8Array(
- data.byteLength + value.byteLength
+ data.byteLength + value.byteLength,
);
buffer.set(new Uint8Array(data), 0);
buffer.set(
new Uint8Array(value),
- data.byteLength
+ data.byteLength,
);
if (
buffer.length > decryptionChunkSize
) {
const fileData = buffer.slice(
0,
- decryptionChunkSize
+ decryptionChunkSize,
);
try {
const { decryptedData } =
await this.cryptoWorker.decryptFileChunk(
fileData,
- pullState
+ pullState,
);
controller.enqueue(
- decryptedData
+ decryptedData,
);
data =
buffer.slice(
- decryptionChunkSize
+ decryptionChunkSize,
);
} catch (e) {
if (
@@ -439,7 +439,7 @@ class DownloadManagerImpl {
) {
logError(
e,
- 'Failed to process file',
+ "Failed to process file",
{
fileID: file.id,
fromMobile:
@@ -449,10 +449,10 @@ class DownloadManagerImpl {
.deviceFolder ||
!!file.metadata
.version,
- }
+ },
);
addLogLine(
- `Failed to process file ${file.id} from localID: ${file.metadata.localID} version: ${file.metadata.version} deviceFolder:${file.metadata.deviceFolder} with error: ${e.message}`
+ `Failed to process file ${file.id} from localID: ${file.metadata.localID} version: ${file.metadata.version} deviceFolder:${file.metadata.deviceFolder} with error: ${e.message}`,
);
}
throw e;
@@ -467,10 +467,10 @@ class DownloadManagerImpl {
const { decryptedData } =
await this.cryptoWorker.decryptFileChunk(
data,
- pullState
+ pullState,
);
controller.enqueue(
- decryptedData
+ decryptedData,
);
data = null;
} catch (e) {
@@ -480,7 +480,7 @@ class DownloadManagerImpl {
) {
logError(
e,
- 'Failed to process file',
+ "Failed to process file",
{
fileID: file.id,
fromMobile:
@@ -490,10 +490,10 @@ class DownloadManagerImpl {
.deviceFolder ||
!!file.metadata
.version,
- }
+ },
);
addLogLine(
- `Failed to process file ${file.id} from localID: ${file.metadata.localID} version: ${file.metadata.version} deviceFolder:${file.metadata.deviceFolder} with error: ${e.message}`
+ `Failed to process file ${file.id} from localID: ${file.metadata.localID} version: ${file.metadata.version} deviceFolder:${file.metadata.deviceFolder} with error: ${e.message}`,
);
}
throw e;
@@ -502,7 +502,7 @@ class DownloadManagerImpl {
controller.close();
}
} catch (e) {
- logError(e, 'Failed to process file chunk');
+ logError(e, "Failed to process file chunk");
controller.error(e);
}
});
@@ -510,14 +510,14 @@ class DownloadManagerImpl {
push();
} catch (e) {
- logError(e, 'Failed to process file stream');
+ logError(e, "Failed to process file stream");
controller.error(e);
}
},
});
return stream;
} catch (e) {
- logError(e, 'Failed to download file');
+ logError(e, "Failed to download file");
throw e;
}
}
@@ -535,7 +535,7 @@ class DownloadManagerImpl {
} else {
this.fileDownloadProgress.set(
fileID,
- Math.round((event.loaded * 100) / event.total)
+ Math.round((event.loaded * 100) / event.total),
);
}
this.progressUpdater(new Map(this.fileDownloadProgress));
@@ -556,7 +556,7 @@ async function openThumbnailCache() {
try {
return await CacheStorageService.open(CACHES.THUMBS);
} catch (e) {
- logError(e, 'Failed to open thumbnail cache');
+ logError(e, "Failed to open thumbnail cache");
if (isInternalUser()) {
throw e;
} else {
@@ -572,7 +572,7 @@ async function openDiskFileCache() {
}
return await CacheStorageService.open(CACHES.FILES, FILE_CACHE_LIMIT);
} catch (e) {
- logError(e, 'Failed to open file cache');
+ logError(e, "Failed to open file cache");
if (isInternalUser()) {
throw e;
} else {
@@ -584,7 +584,7 @@ async function openDiskFileCache() {
function createDownloadClient(
app: APPS,
tokens?: { token: string; passwordToken?: string } | { token: string },
- timeout?: number
+ timeout?: number,
): DownloadClient {
if (!timeout) {
timeout = 300000; // 5 minute
diff --git a/apps/photos/src/services/embeddingService.ts b/apps/photos/src/services/embeddingService.ts
index fd01430a66..68d065aeca 100644
--- a/apps/photos/src/services/embeddingService.ts
+++ b/apps/photos/src/services/embeddingService.ts
@@ -1,31 +1,31 @@
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { CustomError } from "@ente/shared/error";
+import { addLogLine } from "@ente/shared/logging";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getEndpoint } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import localForage from "@ente/shared/storage/localForage";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
import {
Embedding,
EncryptedEmbedding,
GetEmbeddingDiffResponse,
Model,
PutEmbeddingRequest,
-} from 'types/embedding';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { getEndpoint } from '@ente/shared/network/api';
-import { addLogLine } from '@ente/shared/logging';
-import { logError } from '@ente/shared/sentry';
-import localForage from '@ente/shared/storage/localForage';
-import { getAllLocalFiles } from './fileService';
-import HTTPService from '@ente/shared/network/HTTPService';
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
-import { getLatestVersionEmbeddings } from 'utils/embedding';
-import { getLocalTrashedFiles } from './trashService';
-import { getLocalCollections } from './collectionService';
-import { CustomError } from '@ente/shared/error';
-import { EnteFile } from 'types/file';
+} from "types/embedding";
+import { EnteFile } from "types/file";
+import { getLatestVersionEmbeddings } from "utils/embedding";
+import { getLocalCollections } from "./collectionService";
+import { getAllLocalFiles } from "./fileService";
+import { getLocalTrashedFiles } from "./trashService";
const ENDPOINT = getEndpoint();
const DIFF_LIMIT = 500;
-const EMBEDDINGS_TABLE_V1 = 'embeddings';
-const EMBEDDINGS_TABLE = 'embeddings_v2';
-const EMBEDDING_SYNC_TIME_TABLE = 'embedding_sync_time';
+const EMBEDDINGS_TABLE_V1 = "embeddings";
+const EMBEDDINGS_TABLE = "embeddings_v2";
+const EMBEDDING_SYNC_TIME_TABLE = "embedding_sync_time";
export const getAllLocalEmbeddings = async () => {
const embeddings: Array<Embedding> =
@@ -47,7 +47,7 @@ export const getLocalEmbeddings = async (model: Model) => {
const getModelEmbeddingSyncTime = async (model: Model) => {
return (
(await localForage.getItem<number>(
- `${model}-${EMBEDDING_SYNC_TIME_TABLE}`
+ `${model}-${EMBEDDING_SYNC_TIME_TABLE}`,
)) ?? 0
);
};
@@ -60,7 +60,7 @@ export const syncEmbeddings = async (models: Model[] = [Model.ONNX_CLIP]) => {
try {
let allEmbeddings = await getAllLocalEmbeddings();
const localFiles = await getAllLocalFiles();
- const hiddenAlbums = await getLocalCollections('hidden');
+ const hiddenAlbums = await getLocalCollections("hidden");
const localTrashFiles = await getLocalTrashedFiles();
const fileIdToKeyMap = new Map<number, string>();
const allLocalFiles = [...localFiles, ...localTrashFiles];
@@ -72,7 +72,7 @@ export const syncEmbeddings = async (models: Model[] = [Model.ONNX_CLIP]) => {
for (const model of models) {
let modelLastSinceTime = await getModelEmbeddingSyncTime(model);
addLogLine(
- `Syncing ${model} model's embeddings sinceTime: ${modelLastSinceTime}`
+ `Syncing ${model} model's embeddings sinceTime: ${modelLastSinceTime}`,
);
let response: GetEmbeddingDiffResponse;
do {
@@ -91,7 +91,7 @@ export const syncEmbeddings = async (models: Model[] = [Model.ONNX_CLIP]) => {
const worker =
await ComlinkCryptoWorker.getInstance();
const fileKey = fileIdToKeyMap.get(
- embedding.fileID
+ embedding.fileID,
);
if (!fileKey) {
throw Error(CustomError.FILE_NOT_FOUND);
@@ -99,7 +99,7 @@ export const syncEmbeddings = async (models: Model[] = [Model.ONNX_CLIP]) => {
const decryptedData = await worker.decryptEmbedding(
encryptedEmbedding,
decryptionHeader,
- fileIdToKeyMap.get(embedding.fileID)
+ fileIdToKeyMap.get(embedding.fileID),
);
return {
@@ -117,11 +117,11 @@ export const syncEmbeddings = async (models: Model[] = [Model.ONNX_CLIP]) => {
}
logError(
e,
- 'decryptEmbedding failed for file',
- info
+ "decryptEmbedding failed for file",
+ info,
);
}
- })
+ }),
);
allEmbeddings = getLatestVersionEmbeddings([
...allEmbeddings,
@@ -133,18 +133,18 @@ export const syncEmbeddings = async (models: Model[] = [Model.ONNX_CLIP]) => {
await localForage.setItem(EMBEDDINGS_TABLE, allEmbeddings);
await setModelEmbeddingSyncTime(model, modelLastSinceTime);
addLogLine(
- `Syncing embeddings syncedEmbeddingsCount: ${allEmbeddings.length}`
+ `Syncing embeddings syncedEmbeddingsCount: ${allEmbeddings.length}`,
);
} while (response.diff.length === DIFF_LIMIT);
}
} catch (e) {
- logError(e, 'Sync embeddings failed');
+ logError(e, "Sync embeddings failed");
}
};
export const getEmbeddingsDiff = async (
sinceTime: number,
- model: Model
+ model: Model,
): Promise<GetEmbeddingDiffResponse> => {
try {
const token = getToken();
@@ -159,18 +159,18 @@ export const getEmbeddingsDiff = async (
model,
},
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
return await response.data;
} catch (e) {
- logError(e, 'get embeddings diff failed');
+ logError(e, "get embeddings diff failed");
throw e;
}
};
export const putEmbedding = async (
- putEmbeddingReq: PutEmbeddingRequest
+ putEmbeddingReq: PutEmbeddingRequest,
): Promise<EncryptedEmbedding> => {
try {
const token = getToken();
@@ -182,19 +182,19 @@ export const putEmbedding = async (
putEmbeddingReq,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
return resp.data;
} catch (e) {
- logError(e, 'put embedding failed');
+ logError(e, "put embedding failed");
throw e;
}
};
export const cleanupDeletedEmbeddings = async (
allLocalFiles: EnteFile[],
- allLocalEmbeddings: Embedding[]
+ allLocalEmbeddings: Embedding[],
) => {
const activeFileIds = new Set<number>();
allLocalFiles.forEach((file) => {
@@ -202,11 +202,11 @@ export const cleanupDeletedEmbeddings = async (
});
const remainingEmbeddings = allLocalEmbeddings.filter((embedding) =>
- activeFileIds.has(embedding.fileID)
+ activeFileIds.has(embedding.fileID),
);
if (allLocalEmbeddings.length !== remainingEmbeddings.length) {
addLogLine(
- `cleanupDeletedEmbeddings embeddingsCount: ${allLocalEmbeddings.length} remainingEmbeddingsCount: ${remainingEmbeddings.length}`
+ `cleanupDeletedEmbeddings embeddingsCount: ${allLocalEmbeddings.length} remainingEmbeddingsCount: ${remainingEmbeddings.length}`,
);
await localForage.setItem(EMBEDDINGS_TABLE, remainingEmbeddings);
}
diff --git a/apps/photos/src/services/entityService.ts b/apps/photos/src/services/entityService.ts
index 2a6e35ad7b..64ead657e0 100644
--- a/apps/photos/src/services/entityService.ts
+++ b/apps/photos/src/services/entityService.ts
@@ -1,35 +1,35 @@
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
-import localForage from '@ente/shared/storage/localForage';
-import HTTPService from '@ente/shared/network/HTTPService';
-import { getEndpoint } from '@ente/shared/network/api';
-import { logError } from '@ente/shared/sentry';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { getActualKey } from '@ente/shared/user';
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { addLogLine } from "@ente/shared/logging";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getEndpoint } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import localForage from "@ente/shared/storage/localForage";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
+import { getActualKey } from "@ente/shared/user";
import {
- EntityType,
- Entity,
+ EncryptedEntity,
EncryptedEntityKey,
+ Entity,
EntityKey,
EntitySyncDiffResponse,
- EncryptedEntity,
-} from 'types/entity';
-import { getLatestVersionEntities } from 'utils/entity';
-import { addLogLine } from '@ente/shared/logging';
+ EntityType,
+} from "types/entity";
+import { getLatestVersionEntities } from "utils/entity";
const ENDPOINT = getEndpoint();
const DIFF_LIMIT = 500;
const ENTITY_TABLES: Record<EntityType, string> = {
- [EntityType.LOCATION_TAG]: 'location_tags',
+ [EntityType.LOCATION_TAG]: "location_tags",
};
const ENTITY_KEY_TABLES: Record<EntityType, string> = {
- [EntityType.LOCATION_TAG]: 'location_tags_key',
+ [EntityType.LOCATION_TAG]: "location_tags_key",
};
const ENTITY_SYNC_TIME_TABLES: Record<EntityType, string> = {
- [EntityType.LOCATION_TAG]: 'location_tags_time',
+ [EntityType.LOCATION_TAG]: "location_tags_time",
};
const getLocalEntity = async <T>(type: EntityType) => {
@@ -66,8 +66,8 @@ const getEntityKey = async (type: EntityType) => {
type,
},
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
const encryptedEntityKey: EncryptedEntityKey = resp.data;
const worker = await ComlinkCryptoWorker.getInstance();
@@ -76,13 +76,13 @@ const getEntityKey = async (type: EntityType) => {
const decryptedData = await worker.decryptB64(
encryptedKey,
header,
- masterKey
+ masterKey,
);
const decryptedEntityKey: EntityKey = { data: decryptedData, ...rest };
localForage.setItem(ENTITY_KEY_TABLES[type], decryptedEntityKey);
return decryptedEntityKey;
} catch (e) {
- logError(e, 'Get entity key failed');
+ logError(e, "Get entity key failed");
throw e;
}
};
@@ -92,7 +92,7 @@ export const getLatestEntities = async <T>(type: EntityType) => {
await syncEntity<T>(type);
return await getLocalEntity<T>(type);
} catch (e) {
- logError(e, 'Sync entities failed');
+ logError(e, "Sync entities failed");
throw e;
}
};
@@ -101,7 +101,7 @@ export const syncEntities = async () => {
try {
await syncEntity(EntityType.LOCATION_TAG);
} catch (e) {
- logError(e, 'Sync entities failed');
+ logError(e, "Sync entities failed");
throw e;
}
};
@@ -110,7 +110,7 @@ const syncEntity = async <T>(type: EntityType): Promise<Entity<T>> => {
try {
let entities = await getLocalEntity(type);
addLogLine(
- `Syncing ${type} entities localEntitiesCount: ${entities.length}`
+ `Syncing ${type} entities localEntitiesCount: ${entities.length}`,
);
let syncTime = await getEntityLastSyncTime(type);
addLogLine(`Syncing ${type} entities syncTime: ${syncTime}`);
@@ -134,13 +134,13 @@ const syncEntity = async <T>(type: EntityType): Promise<Entity<T>> => {
const decryptedData = await worker.decryptMetadata(
encryptedData,
header,
- entityKey.data
+ entityKey.data,
);
return {
...rest,
data: decryptedData,
};
- })
+ }),
);
entities = getLatestVersionEntities([
@@ -149,7 +149,7 @@ const syncEntity = async <T>(type: EntityType): Promise<Entity<T>> => {
]);
const nonDeletedEntities = entities.filter(
- (entity) => !entity.isDeleted
+ (entity) => !entity.isDeleted,
);
if (response.diff.length) {
@@ -158,17 +158,17 @@ const syncEntity = async <T>(type: EntityType): Promise<Entity<T>> => {
await localForage.setItem(ENTITY_TABLES[type], nonDeletedEntities);
await localForage.setItem(ENTITY_SYNC_TIME_TABLES[type], syncTime);
addLogLine(
- `Syncing ${type} entities syncedEntitiesCount: ${nonDeletedEntities.length}`
+ `Syncing ${type} entities syncedEntitiesCount: ${nonDeletedEntities.length}`,
);
} while (response.diff.length === DIFF_LIMIT);
} catch (e) {
- logError(e, 'Sync entity failed');
+ logError(e, "Sync entity failed");
}
};
const getEntityDiff = async (
type: EntityType,
- time: number
+ time: number,
): Promise<EntitySyncDiffResponse> => {
try {
const token = getToken();
@@ -183,13 +183,13 @@ const getEntityDiff = async (
limit: DIFF_LIMIT,
},
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
return resp.data;
} catch (e) {
- logError(e, 'Get entity diff failed');
+ logError(e, "Get entity diff failed");
throw e;
}
};
diff --git a/apps/photos/src/services/export/index.ts b/apps/photos/src/services/export/index.ts
index 0d55227a65..7190b5b934 100644
--- a/apps/photos/src/services/export/index.ts
+++ b/apps/photos/src/services/export/index.ts
@@ -1,70 +1,70 @@
-import { sleep } from 'utils/common';
+import { logError } from "@ente/shared/sentry";
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
+import { EnteFile } from "types/file";
+import { sleep } from "utils/common";
import {
- getUnExportedFiles,
- getGoogleLikeMetadataFile,
- getExportRecordFileUID,
- getUniqueCollectionExportName,
- getUniqueFileExportName,
- getFileMetadataExportPath,
- getFileExportPath,
- getRenamedExportedCollections,
- getDeletedExportedFiles,
convertCollectionIDExportNameObjectToMap,
convertFileIDExportNameObjectToMap,
+ getCollectionExportPath,
+ getCollectionExportedFiles,
+ getCollectionIDFromFileUID,
getDeletedExportedCollections,
- getTrashedFileExportPath,
+ getDeletedExportedFiles,
+ getExportRecordFileUID,
+ getFileExportPath,
+ getFileMetadataExportPath,
+ getGoogleLikeMetadataFile,
+ getLivePhotoExportName,
getMetadataFileExportPath,
- getCollectionExportedFiles,
- getCollectionExportPath,
getMetadataFolderExportPath,
- getLivePhotoExportName,
+ getRenamedExportedCollections,
+ getTrashedFileExportPath,
+ getUnExportedFiles,
+ getUniqueCollectionExportName,
+ getUniqueFileExportName,
isLivePhotoExportName,
parseLivePhotoExportName,
- getCollectionIDFromFileUID,
-} from 'utils/export';
-import { logError } from '@ente/shared/sentry';
-import { getData, LS_KEYS, setData } from '@ente/shared/storage/localStorage';
-import { getAllLocalCollections } from '../collectionService';
-import downloadManager from '../download';
-import { getAllLocalFiles } from '../fileService';
-import { EnteFile } from 'types/file';
-
-import { decodeLivePhoto } from '../livePhotoService';
+} from "utils/export";
+import { getAllLocalCollections } from "../collectionService";
+import downloadManager from "../download";
+import { getAllLocalFiles } from "../fileService";
+
import {
generateStreamFromArrayBuffer,
getPersonalFiles,
getUpdatedEXIFFileForDownload,
mergeMetadata,
-} from 'utils/file';
-
-import QueueProcessor, {
- CancellationStatus,
- RequestCanceller,
-} from '../queueProcessor';
-import { Collection } from 'types/collection';
+} from "utils/file";
+import { decodeLivePhoto } from "../livePhotoService";
+
+import ElectronAPIs from "@ente/shared/electron";
+import { CustomError } from "@ente/shared/error";
+import { Events, eventBus } from "@ente/shared/events";
+import { addLogLine } from "@ente/shared/logging";
+import { User } from "@ente/shared/user/types";
+import { ExportStage } from "constants/export";
+import { FILE_TYPE } from "constants/file";
+import { Collection } from "types/collection";
import {
ExportProgress,
ExportRecord,
ExportSettings,
ExportUIUpdaters,
-} from 'types/export';
-import { User } from '@ente/shared/user/types';
-import { FILE_TYPE } from 'constants/file';
-import { ExportStage } from 'constants/export';
-import { CustomError } from '@ente/shared/error';
-import { addLogLine } from '@ente/shared/logging';
-import { eventBus, Events } from '@ente/shared/events';
+} from "types/export";
import {
constructCollectionNameMap,
getCollectionUserFacingName,
getNonEmptyPersonalCollections,
-} from 'utils/collection';
-import { migrateExport } from './migration';
-import ElectronAPIs from '@ente/shared/electron';
+} from "utils/collection";
+import QueueProcessor, {
+ CancellationStatus,
+ RequestCanceller,
+} from "../queueProcessor";
+import { migrateExport } from "./migration";
-const EXPORT_RECORD_FILE_NAME = 'export_status.json';
+const EXPORT_RECORD_FILE_NAME = "export_status.json";
-export const ENTE_EXPORT_DIRECTORY = 'ente Photos';
+export const ENTE_EXPORT_DIRECTORY = "ente Photos";
export const NULL_EXPORT_RECORD: ExportRecord = {
version: 3,
@@ -102,7 +102,7 @@ class ExportService {
this.exportSettings = exportSettings;
return exportSettings;
} catch (e) {
- logError(e, 'getExportSettings failed');
+ logError(e, "getExportSettings failed");
throw e;
}
}
@@ -114,7 +114,7 @@ class ExportService {
this.exportSettings = newSettings;
setData(LS_KEYS.EXPORT, newSettings);
} catch (e) {
- logError(e, 'updateExportSettings failed');
+ logError(e, "updateExportSettings failed");
throw e;
}
}
@@ -122,14 +122,14 @@ class ExportService {
async runMigration(
exportDir: string,
exportRecord: ExportRecord,
- updateProgress: (progress: ExportProgress) => void
+ updateProgress: (progress: ExportProgress) => void,
) {
try {
- addLogLine('running migration');
+ addLogLine("running migration");
await migrateExport(exportDir, exportRecord, updateProgress);
- addLogLine('migration completed');
+ addLogLine("migration completed");
} catch (e) {
- logError(e, 'migration failed');
+ logError(e, "migration failed");
throw e;
}
}
@@ -169,7 +169,7 @@ class ExportService {
return newExportDir;
} catch (e) {
if (e.message !== CustomError.SELECT_FOLDER_ABORTED) {
- logError(e, 'changeExportDirectory failed');
+ logError(e, "changeExportDirectory failed");
}
throw e;
}
@@ -178,20 +178,20 @@ class ExportService {
enableContinuousExport() {
try {
if (this.continuousExportEventHandler) {
- addLogLine('continuous export already enabled');
+ addLogLine("continuous export already enabled");
return;
}
- addLogLine('enabling continuous export');
+ addLogLine("enabling continuous export");
this.continuousExportEventHandler = () => {
this.scheduleExport();
};
this.continuousExportEventHandler();
eventBus.addListener(
Events.LOCAL_FILES_UPDATED,
- this.continuousExportEventHandler
+ this.continuousExportEventHandler,
);
} catch (e) {
- logError(e, 'failed to enableContinuousExport ');
+ logError(e, "failed to enableContinuousExport ");
throw e;
}
}
@@ -199,23 +199,23 @@ class ExportService {
disableContinuousExport() {
try {
if (!this.continuousExportEventHandler) {
- addLogLine('continuous export already disabled');
+ addLogLine("continuous export already disabled");
return;
}
- addLogLine('disabling continuous export');
+ addLogLine("disabling continuous export");
eventBus.removeListener(
Events.LOCAL_FILES_UPDATED,
- this.continuousExportEventHandler
+ this.continuousExportEventHandler,
);
this.continuousExportEventHandler = null;
} catch (e) {
- logError(e, 'failed to disableContinuousExport');
+ logError(e, "failed to disableContinuousExport");
throw e;
}
}
getPendingExports = async (
- exportRecord: ExportRecord
+ exportRecord: ExportRecord,
): Promise<EnteFile[]> => {
try {
const user: User = getData(LS_KEYS.USER);
@@ -225,21 +225,21 @@ class ExportService {
collections.map((collection) => [
collection.id,
collection.owner.id,
- ])
+ ]),
);
const userPersonalFiles = getPersonalFiles(
files,
user,
- collectionIdToOwnerIDMap
+ collectionIdToOwnerIDMap,
);
const unExportedFiles = getUnExportedFiles(
userPersonalFiles,
- exportRecord
+ exportRecord,
);
return unExportedFiles;
} catch (e) {
- logError(e, 'getUpdateFileLists failed');
+ logError(e, "getUpdateFileLists failed");
throw e;
}
};
@@ -251,7 +251,7 @@ class ExportService {
await this.runMigration(
exportFolder,
exportRecord,
- this.updateExportProgress.bind(this)
+ this.updateExportProgress.bind(this),
);
await this.updateExportStage(ExportStage.STARTING);
}
@@ -271,30 +271,30 @@ class ExportService {
const pendingExports = await this.getPendingExports(exportRecord);
this.uiUpdater.setPendingExports(pendingExports);
} catch (e) {
- logError(e, 'postExport failed');
+ logError(e, "postExport failed");
}
}
async stopRunningExport() {
try {
- addLogLine('user requested export cancellation');
+ addLogLine("user requested export cancellation");
this.exportInProgress.exec();
this.exportInProgress = null;
this.reRunNeeded = false;
await this.postExport();
} catch (e) {
- logError(e, 'stopRunningExport failed');
+ logError(e, "stopRunningExport failed");
}
}
scheduleExport = async () => {
try {
if (this.exportInProgress) {
- addLogLine('export in progress, scheduling re-run');
+ addLogLine("export in progress, scheduling re-run");
this.reRunNeeded = true;
return;
} else {
- addLogLine('export not in progress, starting export');
+ addLogLine("export not in progress, starting export");
}
const isCanceled: CancellationStatus = { status: false };
@@ -307,22 +307,22 @@ class ExportService {
try {
const exportFolder = this.getExportSettings()?.folder;
await this.preExport(exportFolder);
- addLogLine('export started');
+ addLogLine("export started");
await this.runExport(exportFolder, isCanceled);
- addLogLine('export completed');
+ addLogLine("export completed");
} finally {
if (isCanceled.status) {
- addLogLine('export cancellation done');
+ addLogLine("export cancellation done");
if (!this.exportInProgress) {
await this.postExport();
}
} else {
await this.postExport();
- addLogLine('resetting export in progress after completion');
+ addLogLine("resetting export in progress after completion");
this.exportInProgress = null;
if (this.reRunNeeded) {
this.reRunNeeded = false;
- addLogLine('re-running export');
+ addLogLine("re-running export");
setTimeout(() => this.scheduleExport(), 0);
}
}
@@ -332,14 +332,14 @@ class ExportService {
e.message !== CustomError.EXPORT_FOLDER_DOES_NOT_EXIST &&
e.message !== CustomError.EXPORT_STOPPED
) {
- logError(e, 'scheduleExport failed');
+ logError(e, "scheduleExport failed");
}
}
};
private async runExport(
exportFolder: string,
- isCanceled: CancellationStatus
+ isCanceled: CancellationStatus,
) {
try {
const user: User = getData(LS_KEYS.USER);
@@ -349,49 +349,49 @@ class ExportService {
collections.map((collection) => [
collection.id,
collection.owner.id,
- ])
+ ]),
);
const personalFiles = getPersonalFiles(
files,
user,
- collectionIdToOwnerIDMap
+ collectionIdToOwnerIDMap,
);
const nonEmptyPersonalCollections = getNonEmptyPersonalCollections(
collections,
personalFiles,
- user
+ user,
);
const exportRecord = await this.getExportRecord(exportFolder);
const collectionIDExportNameMap =
convertCollectionIDExportNameObjectToMap(
- exportRecord.collectionExportNames
+ exportRecord.collectionExportNames,
);
const collectionIDNameMap = constructCollectionNameMap(
- nonEmptyPersonalCollections
+ nonEmptyPersonalCollections,
);
const renamedCollections = getRenamedExportedCollections(
nonEmptyPersonalCollections,
- exportRecord
+ exportRecord,
);
const removedFileUIDs = getDeletedExportedFiles(
personalFiles,
- exportRecord
+ exportRecord,
);
const filesToExport = getUnExportedFiles(
personalFiles,
- exportRecord
+ exportRecord,
);
const deletedExportedCollections = getDeletedExportedCollections(
nonEmptyPersonalCollections,
- exportRecord
+ exportRecord,
);
addLogLine(
- `personal files:${personalFiles.length} unexported files: ${filesToExport.length}, deleted exported files: ${removedFileUIDs.length}, renamed collections: ${renamedCollections.length}, deleted collections: ${deletedExportedCollections.length}`
+ `personal files:${personalFiles.length} unexported files: ${filesToExport.length}, deleted exported files: ${removedFileUIDs.length}, renamed collections: ${renamedCollections.length}, deleted collections: ${deletedExportedCollections.length}`,
);
let success = 0;
let failed = 0;
@@ -421,7 +421,7 @@ class ExportService {
exportFolder,
collectionIDExportNameMap,
renamedCollections,
- isCanceled
+ isCanceled,
);
}
@@ -432,7 +432,7 @@ class ExportService {
exportFolder,
collectionIDExportNameMap,
removedFileUIDs,
- isCanceled
+ isCanceled,
);
}
if (filesToExport?.length > 0) {
@@ -445,20 +445,20 @@ class ExportService {
exportFolder,
incrementSuccess,
incrementFailed,
- isCanceled
+ isCanceled,
);
}
if (deletedExportedCollections?.length > 0) {
this.updateExportStage(
- ExportStage.TRASHING_DELETED_COLLECTIONS
+ ExportStage.TRASHING_DELETED_COLLECTIONS,
);
addLogLine(
- `removing ${deletedExportedCollections.length} collections`
+ `removing ${deletedExportedCollections.length} collections`,
);
await this.collectionRemover(
deletedExportedCollections,
exportFolder,
- isCanceled
+ isCanceled,
);
}
} catch (e) {
@@ -466,7 +466,7 @@ class ExportService {
e.message !== CustomError.EXPORT_FOLDER_DOES_NOT_EXIST &&
e.message !== CustomError.EXPORT_STOPPED
) {
- logError(e, 'runExport failed');
+ logError(e, "runExport failed");
}
throw e;
}
@@ -476,7 +476,7 @@ class ExportService {
exportFolder: string,
collectionIDExportNameMap: Map<number, string>,
renamedCollections: Collection[],
- isCanceled: CancellationStatus
+ isCanceled: CancellationStatus,
) {
try {
for (const collection of renamedCollections) {
@@ -489,53 +489,53 @@ class ExportService {
collectionIDExportNameMap.get(collection.id);
const oldCollectionExportPath = getCollectionExportPath(
exportFolder,
- oldCollectionExportName
+ oldCollectionExportName,
);
const newCollectionExportName =
getUniqueCollectionExportName(
exportFolder,
- getCollectionUserFacingName(collection)
+ getCollectionUserFacingName(collection),
);
addLogLine(
- `renaming collection with id ${collection.id} from ${oldCollectionExportName} to ${newCollectionExportName}`
+ `renaming collection with id ${collection.id} from ${oldCollectionExportName} to ${newCollectionExportName}`,
);
const newCollectionExportPath = getCollectionExportPath(
exportFolder,
- newCollectionExportName
+ newCollectionExportName,
);
await this.addCollectionExportedRecord(
exportFolder,
collection.id,
- newCollectionExportName
+ newCollectionExportName,
);
collectionIDExportNameMap.set(
collection.id,
- newCollectionExportName
+ newCollectionExportName,
);
try {
await ElectronAPIs.rename(
oldCollectionExportPath,
- newCollectionExportPath
+ newCollectionExportPath,
);
} catch (e) {
await this.addCollectionExportedRecord(
exportFolder,
collection.id,
- oldCollectionExportName
+ oldCollectionExportName,
);
collectionIDExportNameMap.set(
collection.id,
- oldCollectionExportName
+ oldCollectionExportName,
);
throw e;
}
addLogLine(
- `renaming collection with id ${collection.id} from ${oldCollectionExportName} to ${newCollectionExportName} successful`
+ `renaming collection with id ${collection.id} from ${oldCollectionExportName} to ${newCollectionExportName} successful`,
);
} catch (e) {
- logError(e, 'collectionRenamer failed a collection');
+ logError(e, "collectionRenamer failed a collection");
if (
e.message ===
CustomError.UPDATE_EXPORTED_RECORD_FAILED ||
@@ -552,7 +552,7 @@ class ExportService {
e.message !== CustomError.EXPORT_FOLDER_DOES_NOT_EXIST &&
e.message !== CustomError.EXPORT_STOPPED
) {
- logError(e, 'collectionRenamer failed');
+ logError(e, "collectionRenamer failed");
}
throw e;
}
@@ -561,13 +561,13 @@ class ExportService {
async collectionRemover(
deletedExportedCollectionIDs: number[],
exportFolder: string,
- isCanceled: CancellationStatus
+ isCanceled: CancellationStatus,
) {
try {
const exportRecord = await this.getExportRecord(exportFolder);
const collectionIDPathMap =
convertCollectionIDExportNameObjectToMap(
- exportRecord.collectionExportNames
+ exportRecord.collectionExportNames,
);
for (const collectionID of deletedExportedCollectionIDs) {
try {
@@ -576,32 +576,32 @@ class ExportService {
}
this.verifyExportFolderExists(exportFolder);
addLogLine(
- `removing collection with id ${collectionID} from export folder`
+ `removing collection with id ${collectionID} from export folder`,
);
const collectionExportName =
collectionIDPathMap.get(collectionID);
// verify that the all exported files from the collection has been removed
const collectionExportedFiles = getCollectionExportedFiles(
exportRecord,
- collectionID
+ collectionID,
);
if (collectionExportedFiles.length > 0) {
throw new Error(
- "collection is not empty, can't remove"
+ "collection is not empty, can't remove",
);
}
const collectionExportPath = getCollectionExportPath(
exportFolder,
- collectionExportName
+ collectionExportName,
);
await this.removeCollectionExportedRecord(
exportFolder,
- collectionID
+ collectionID,
);
try {
// delete the collection metadata folder
await ElectronAPIs.deleteFolder(
- getMetadataFolderExportPath(collectionExportPath)
+ getMetadataFolderExportPath(collectionExportPath),
);
// delete the collection folder
await ElectronAPIs.deleteFolder(collectionExportPath);
@@ -609,15 +609,15 @@ class ExportService {
await this.addCollectionExportedRecord(
exportFolder,
collectionID,
- collectionExportName
+ collectionExportName,
);
throw e;
}
addLogLine(
- `removing collection with id ${collectionID} from export folder successful`
+ `removing collection with id ${collectionID} from export folder successful`,
);
} catch (e) {
- logError(e, 'collectionRemover failed a collection');
+ logError(e, "collectionRemover failed a collection");
if (
e.message ===
CustomError.UPDATE_EXPORTED_RECORD_FAILED ||
@@ -634,7 +634,7 @@ class ExportService {
e.message !== CustomError.EXPORT_FOLDER_DOES_NOT_EXIST &&
e.message !== CustomError.EXPORT_STOPPED
) {
- logError(e, 'collectionRemover failed');
+ logError(e, "collectionRemover failed");
}
throw e;
}
@@ -647,7 +647,7 @@ class ExportService {
exportDir: string,
incrementSuccess: () => void,
incrementFailed: () => void,
- isCanceled: CancellationStatus
+ isCanceled: CancellationStatus,
): Promise<void> {
try {
for (const file of files) {
@@ -655,8 +655,8 @@ class ExportService {
`exporting file ${file.metadata.title} with id ${
file.id
} from collection ${collectionIDNameMap.get(
- file.collectionID
- )}`
+ file.collectionID,
+ )}`,
);
if (isCanceled.status) {
throw Error(CustomError.EXPORT_STOPPED);
@@ -664,51 +664,51 @@ class ExportService {
try {
this.verifyExportFolderExists(exportDir);
let collectionExportName = collectionIDFolderNameMap.get(
- file.collectionID
+ file.collectionID,
);
if (!collectionExportName) {
collectionExportName =
await this.createNewCollectionExport(
exportDir,
file.collectionID,
- collectionIDNameMap
+ collectionIDNameMap,
);
await this.addCollectionExportedRecord(
exportDir,
file.collectionID,
- collectionExportName
+ collectionExportName,
);
collectionIDFolderNameMap.set(
file.collectionID,
- collectionExportName
+ collectionExportName,
);
}
const collectionExportPath = getCollectionExportPath(
exportDir,
- collectionExportName
+ collectionExportName,
);
await ElectronAPIs.checkExistsAndCreateDir(
- collectionExportPath
+ collectionExportPath,
);
await ElectronAPIs.checkExistsAndCreateDir(
- getMetadataFolderExportPath(collectionExportPath)
+ getMetadataFolderExportPath(collectionExportPath),
);
await this.downloadAndSave(
exportDir,
collectionExportPath,
- file
+ file,
);
incrementSuccess();
addLogLine(
`exporting file ${file.metadata.title} with id ${
file.id
} from collection ${collectionIDNameMap.get(
- file.collectionID
- )} successful`
+ file.collectionID,
+ )} successful`,
);
} catch (e) {
incrementFailed();
- logError(e, 'export failed for a file');
+ logError(e, "export failed for a file");
if (
e.message ===
CustomError.UPDATE_EXPORTED_RECORD_FAILED ||
@@ -725,7 +725,7 @@ class ExportService {
e.message !== CustomError.EXPORT_FOLDER_DOES_NOT_EXIST &&
e.message !== CustomError.EXPORT_STOPPED
) {
- logError(e, 'fileExporter failed');
+ logError(e, "fileExporter failed");
}
throw e;
}
@@ -735,12 +735,12 @@ class ExportService {
exportDir: string,
collectionIDExportNameMap: Map<number, string>,
removedFileUIDs: string[],
- isCanceled: CancellationStatus
+ isCanceled: CancellationStatus,
): Promise<void> {
try {
const exportRecord = await this.getExportRecord(exportDir);
const fileIDExportNameMap = convertFileIDExportNameObjectToMap(
- exportRecord.fileExportNames
+ exportRecord.fileExportNames,
);
for (const fileUID of removedFileUIDs) {
this.verifyExportFolderExists(exportDir);
@@ -753,7 +753,7 @@ class ExportService {
const collectionID = getCollectionIDFromFileUID(fileUID);
const collectionExportPath = getCollectionExportPath(
exportDir,
- collectionIDExportNameMap.get(collectionID)
+ collectionIDExportNameMap.get(collectionID),
);
await this.removeFileExportedRecord(exportDir, fileUID);
try {
@@ -764,18 +764,18 @@ class ExportService {
} = parseLivePhotoExportName(fileExportName);
const imageExportPath = getFileExportPath(
collectionExportPath,
- imageExportName
+ imageExportName,
);
addLogLine(
- `moving image file ${imageExportPath} to trash folder`
+ `moving image file ${imageExportPath} to trash folder`,
);
if (this.exists(imageExportPath)) {
await ElectronAPIs.moveFile(
imageExportPath,
getTrashedFileExportPath(
exportDir,
- imageExportPath
- )
+ imageExportPath,
+ ),
);
}
@@ -787,25 +787,25 @@ class ExportService {
imageMetadataFileExportPath,
getTrashedFileExportPath(
exportDir,
- imageMetadataFileExportPath
- )
+ imageMetadataFileExportPath,
+ ),
);
}
const videoExportPath = getFileExportPath(
collectionExportPath,
- videoExportName
+ videoExportName,
);
addLogLine(
- `moving video file ${videoExportPath} to trash folder`
+ `moving video file ${videoExportPath} to trash folder`,
);
if (this.exists(videoExportPath)) {
await ElectronAPIs.moveFile(
videoExportPath,
getTrashedFileExportPath(
exportDir,
- videoExportPath
- )
+ videoExportPath,
+ ),
);
}
const videoMetadataFileExportPath =
@@ -815,26 +815,26 @@ class ExportService {
videoMetadataFileExportPath,
getTrashedFileExportPath(
exportDir,
- videoMetadataFileExportPath
- )
+ videoMetadataFileExportPath,
+ ),
);
}
} else {
const fileExportPath = getFileExportPath(
collectionExportPath,
- fileExportName
+ fileExportName,
);
const trashedFilePath = getTrashedFileExportPath(
exportDir,
- fileExportPath
+ fileExportPath,
);
addLogLine(
- `moving file ${fileExportPath} to ${trashedFilePath} trash folder`
+ `moving file ${fileExportPath} to ${trashedFilePath} trash folder`,
);
if (this.exists(fileExportPath)) {
await ElectronAPIs.moveFile(
fileExportPath,
- trashedFilePath
+ trashedFilePath,
);
}
const metadataFileExportPath =
@@ -844,8 +844,8 @@ class ExportService {
metadataFileExportPath,
getTrashedFileExportPath(
exportDir,
- metadataFileExportPath
- )
+ metadataFileExportPath,
+ ),
);
}
}
@@ -853,13 +853,13 @@ class ExportService {
await this.addFileExportedRecord(
exportDir,
fileUID,
- fileExportName
+ fileExportName,
);
throw e;
}
addLogLine(`trashing file with id ${fileUID} successful`);
} catch (e) {
- logError(e, 'trashing failed for a file');
+ logError(e, "trashing failed for a file");
if (
e.message ===
CustomError.UPDATE_EXPORTED_RECORD_FAILED ||
@@ -876,7 +876,7 @@ class ExportService {
e.message !== CustomError.EXPORT_FOLDER_DOES_NOT_EXIST &&
e.message !== CustomError.EXPORT_STOPPED
) {
- logError(e, 'fileTrasher failed');
+ logError(e, "fileTrasher failed");
}
throw e;
}
@@ -885,7 +885,7 @@ class ExportService {
async addFileExportedRecord(
folder: string,
fileUID: string,
- fileExportName: string
+ fileExportName: string,
) {
try {
const exportRecord = await this.getExportRecord(folder);
@@ -899,7 +899,7 @@ class ExportService {
await this.updateExportRecord(folder, exportRecord);
} catch (e) {
if (e.message !== CustomError.EXPORT_FOLDER_DOES_NOT_EXIST) {
- logError(e, 'addFileExportedRecord failed');
+ logError(e, "addFileExportedRecord failed");
}
throw e;
}
@@ -908,7 +908,7 @@ class ExportService {
async addCollectionExportedRecord(
folder: string,
collectionID: number,
- collectionExportName: string
+ collectionExportName: string,
) {
try {
const exportRecord = await this.getExportRecord(folder);
@@ -923,7 +923,7 @@ class ExportService {
await this.updateExportRecord(folder, exportRecord);
} catch (e) {
if (e.message !== CustomError.EXPORT_FOLDER_DOES_NOT_EXIST) {
- logError(e, 'addCollectionExportedRecord failed');
+ logError(e, "addCollectionExportedRecord failed");
}
throw e;
}
@@ -935,14 +935,14 @@ class ExportService {
exportRecord.collectionExportNames = Object.fromEntries(
Object.entries(exportRecord.collectionExportNames).filter(
- ([key]) => key !== collectionID.toString()
- )
+ ([key]) => key !== collectionID.toString(),
+ ),
);
await this.updateExportRecord(folder, exportRecord);
} catch (e) {
if (e.message !== CustomError.EXPORT_FOLDER_DOES_NOT_EXIST) {
- logError(e, 'removeCollectionExportedRecord failed');
+ logError(e, "removeCollectionExportedRecord failed");
}
throw e;
}
@@ -953,13 +953,13 @@ class ExportService {
const exportRecord = await this.getExportRecord(folder);
exportRecord.fileExportNames = Object.fromEntries(
Object.entries(exportRecord.fileExportNames).filter(
- ([key]) => key !== fileUID
- )
+ ([key]) => key !== fileUID,
+ ),
);
await this.updateExportRecord(folder, exportRecord);
} catch (e) {
if (e.message !== CustomError.EXPORT_FOLDER_DOES_NOT_EXIST) {
- logError(e, 'removeFileExportedRecord failed');
+ logError(e, "removeFileExportedRecord failed");
}
throw e;
}
@@ -967,28 +967,28 @@ class ExportService {
async updateExportRecord(folder: string, newData: Partial<ExportRecord>) {
const response = this.exportRecordUpdater.queueUpRequest(() =>
- this.updateExportRecordHelper(folder, newData)
+ this.updateExportRecordHelper(folder, newData),
);
return response.promise;
}
async updateExportRecordHelper(
folder: string,
- newData: Partial<ExportRecord>
+ newData: Partial<ExportRecord>,
) {
try {
const exportRecord = await this.getExportRecord(folder);
const newRecord: ExportRecord = { ...exportRecord, ...newData };
await ElectronAPIs.saveFileToDisk(
`${folder}/${EXPORT_RECORD_FILE_NAME}`,
- JSON.stringify(newRecord, null, 2)
+ JSON.stringify(newRecord, null, 2),
);
return newRecord;
} catch (e) {
if (e.message === CustomError.EXPORT_FOLDER_DOES_NOT_EXIST) {
throw e;
}
- logError(e, 'error updating Export Record');
+ logError(e, "error updating Export Record");
throw Error(CustomError.UPDATE_EXPORTED_RECORD_FAILED);
}
}
@@ -1016,7 +1016,7 @@ class ExportService {
return await this.getExportRecord(folder, false);
}
if (e.message !== CustomError.EXPORT_FOLDER_DOES_NOT_EXIST) {
- logError(e, 'export Record JSON parsing failed');
+ logError(e, "export Record JSON parsing failed");
}
throw e;
}
@@ -1025,21 +1025,21 @@ class ExportService {
async createNewCollectionExport(
exportFolder: string,
collectionID: number,
- collectionIDNameMap: Map<number, string>
+ collectionIDNameMap: Map<number, string>,
) {
this.verifyExportFolderExists(exportFolder);
const collectionName = collectionIDNameMap.get(collectionID);
const collectionExportName = getUniqueCollectionExportName(
exportFolder,
- collectionName
+ collectionName,
);
const collectionExportPath = getCollectionExportPath(
exportFolder,
- collectionExportName
+ collectionExportName,
);
await ElectronAPIs.checkExistsAndCreateDir(collectionExportPath);
await ElectronAPIs.checkExistsAndCreateDir(
- getMetadataFolderExportPath(collectionExportPath)
+ getMetadataFolderExportPath(collectionExportPath),
);
return collectionExportName;
@@ -1048,7 +1048,7 @@ class ExportService {
async downloadAndSave(
exportDir: string,
collectionExportPath: string,
- file: EnteFile
+ file: EnteFile,
): Promise<void> {
try {
const fileUID = getExportRecordFileUID(file);
@@ -1059,7 +1059,7 @@ class ExportService {
const updatedFileStream = await getUpdatedEXIFFileForDownload(
this.fileReader,
file,
- originalFileStream
+ originalFileStream,
);
if (file.metadata.fileType === FILE_TYPE.LIVE_PHOTO) {
await this.exportLivePhoto(
@@ -1067,27 +1067,27 @@ class ExportService {
fileUID,
collectionExportPath,
updatedFileStream,
- file
+ file,
);
} else {
const fileExportName = getUniqueFileExportName(
collectionExportPath,
- file.metadata.title
+ file.metadata.title,
);
await this.addFileExportedRecord(
exportDir,
fileUID,
- fileExportName
+ fileExportName,
);
try {
await this.saveMetadataFile(
collectionExportPath,
fileExportName,
- file
+ file,
);
await ElectronAPIs.saveStreamToDisk(
getFileExportPath(collectionExportPath, fileExportName),
- updatedFileStream
+ updatedFileStream,
);
} catch (e) {
await this.removeFileExportedRecord(exportDir, fileUID);
@@ -1095,7 +1095,7 @@ class ExportService {
}
}
} catch (e) {
- logError(e, 'download and save failed');
+ logError(e, "download and save failed");
throw e;
}
}
@@ -1105,53 +1105,53 @@ class ExportService {
fileUID: string,
collectionExportPath: string,
fileStream: ReadableStream<any>,
- file: EnteFile
+ file: EnteFile,
) {
const fileBlob = await new Response(fileStream).blob();
const livePhoto = await decodeLivePhoto(file, fileBlob);
const imageExportName = getUniqueFileExportName(
collectionExportPath,
- livePhoto.imageNameTitle
+ livePhoto.imageNameTitle,
);
const videoExportName = getUniqueFileExportName(
collectionExportPath,
- livePhoto.videoNameTitle
+ livePhoto.videoNameTitle,
);
const livePhotoExportName = getLivePhotoExportName(
imageExportName,
- videoExportName
+ videoExportName,
);
await this.addFileExportedRecord(
exportDir,
fileUID,
- livePhotoExportName
+ livePhotoExportName,
);
try {
const imageStream = generateStreamFromArrayBuffer(livePhoto.image);
await this.saveMetadataFile(
collectionExportPath,
imageExportName,
- file
+ file,
);
await ElectronAPIs.saveStreamToDisk(
getFileExportPath(collectionExportPath, imageExportName),
- imageStream
+ imageStream,
);
const videoStream = generateStreamFromArrayBuffer(livePhoto.video);
await this.saveMetadataFile(
collectionExportPath,
videoExportName,
- file
+ file,
);
try {
await ElectronAPIs.saveStreamToDisk(
getFileExportPath(collectionExportPath, videoExportName),
- videoStream
+ videoStream,
);
} catch (e) {
ElectronAPIs.deleteFile(
- getFileExportPath(collectionExportPath, imageExportName)
+ getFileExportPath(collectionExportPath, imageExportName),
);
throw e;
}
@@ -1164,11 +1164,11 @@ class ExportService {
private async saveMetadataFile(
collectionExportPath: string,
fileExportName: string,
- file: EnteFile
+ file: EnteFile,
) {
await ElectronAPIs.saveFileToDisk(
getFileMetadataExportPath(collectionExportPath, fileExportName),
- getGoogleLikeMetadataFile(fileExportName, file)
+ getGoogleLikeMetadataFile(fileExportName, file),
);
}
@@ -1199,7 +1199,7 @@ class ExportService {
}
} catch (e) {
if (e.message !== CustomError.EXPORT_FOLDER_DOES_NOT_EXIST) {
- logError(e, 'verifyExportFolderExists failed');
+ logError(e, "verifyExportFolderExists failed");
}
throw e;
}
@@ -1209,7 +1209,7 @@ class ExportService {
const exportRecord: ExportRecord = NULL_EXPORT_RECORD;
await ElectronAPIs.saveFileToDisk(
exportRecordJSONPath,
- JSON.stringify(exportRecord, null, 2)
+ JSON.stringify(exportRecord, null, 2),
);
return exportRecord;
};
diff --git a/apps/photos/src/services/export/migration.ts b/apps/photos/src/services/export/migration.ts
index dd86313a8f..327f42f777 100644
--- a/apps/photos/src/services/export/migration.ts
+++ b/apps/photos/src/services/export/migration.ts
@@ -1,113 +1,113 @@
-import { getLocalCollections } from 'services/collectionService';
-import { getAllLocalFiles } from 'services/fileService';
+import { addLocalLog, addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
+import { User } from "@ente/shared/user/types";
+import { FILE_TYPE } from "constants/file";
+import { getLocalCollections } from "services/collectionService";
+import downloadManager from "services/download";
+import { getAllLocalFiles } from "services/fileService";
+import { decodeLivePhoto } from "services/livePhotoService";
+import { Collection } from "types/collection";
import {
+ CollectionExportNames,
+ ExportProgress,
+ ExportRecord,
+ ExportRecordV0,
ExportRecordV1,
ExportRecordV2,
- ExportRecord,
FileExportNames,
- ExportRecordV0,
- CollectionExportNames,
- ExportProgress,
-} from 'types/export';
-import { EnteFile } from 'types/file';
-import { User } from '@ente/shared/user/types';
-import { getNonEmptyPersonalCollections } from 'utils/collection';
+} from "types/export";
+import { EnteFile } from "types/file";
+import { getNonEmptyPersonalCollections } from "utils/collection";
+import { sleep } from "utils/common";
import {
getCollectionExportPath,
getCollectionIDFromFileUID,
getExportRecordFileUID,
getLivePhotoExportName,
getMetadataFolderExportPath,
-} from 'utils/export';
+} from "utils/export";
import {
- getIDBasedSortedFiles,
- getPersonalFiles,
- mergeMetadata,
-} from 'utils/file';
-import { addLocalLog, addLogLine } from '@ente/shared/logging';
-import { logError } from '@ente/shared/sentry';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import exportService from './index';
-import { Collection } from 'types/collection';
-import {
- getExportedFiles,
convertCollectionIDFolderPathObjectToMap,
- getUniqueFileExportNameForMigration,
+ getExportedFiles,
+ getFileMetadataSavePath,
+ getFileSavePath,
getOldCollectionFolderPath,
+ getOldFileMetadataSavePath,
+ getOldFileSavePath,
getUniqueCollectionFolderPath,
+ getUniqueFileExportNameForMigration,
getUniqueFileSaveName,
- getOldFileSavePath,
- getOldFileMetadataSavePath,
- getFileMetadataSavePath,
- getFileSavePath,
-} from 'utils/export/migration';
-import { FILE_TYPE } from 'constants/file';
-import { decodeLivePhoto } from 'services/livePhotoService';
-import downloadManager from 'services/download';
-import { sleep } from 'utils/common';
+} from "utils/export/migration";
+import {
+ getIDBasedSortedFiles,
+ getPersonalFiles,
+ mergeMetadata,
+} from "utils/file";
+import exportService from "./index";
export async function migrateExport(
exportDir: string,
exportRecord: ExportRecordV1 | ExportRecordV2 | ExportRecord,
- updateProgress: (progress: ExportProgress) => void
+ updateProgress: (progress: ExportProgress) => void,
) {
try {
addLogLine(`current export version: ${exportRecord.version}`);
if (exportRecord.version === 0) {
- addLogLine('migrating export to version 1');
+ addLogLine("migrating export to version 1");
await migrationV0ToV1(exportDir, exportRecord as ExportRecordV0);
exportRecord = await exportService.updateExportRecord(exportDir, {
version: 1,
});
- addLogLine('migration to version 1 complete');
+ addLogLine("migration to version 1 complete");
}
if (exportRecord.version === 1) {
- addLogLine('migrating export to version 2');
+ addLogLine("migrating export to version 2");
await migrationV1ToV2(exportRecord as ExportRecordV1, exportDir);
exportRecord = await exportService.updateExportRecord(exportDir, {
version: 2,
});
- addLogLine('migration to version 2 complete');
+ addLogLine("migration to version 2 complete");
}
if (exportRecord.version === 2) {
- addLogLine('migrating export to version 3');
+ addLogLine("migrating export to version 3");
await migrationV2ToV3(
exportDir,
exportRecord as ExportRecordV2,
- updateProgress
+ updateProgress,
);
exportRecord = await exportService.updateExportRecord(exportDir, {
version: 3,
});
- addLogLine('migration to version 3 complete');
+ addLogLine("migration to version 3 complete");
}
if (exportRecord.version === 3) {
- addLogLine('migrating export to version 4');
+ addLogLine("migrating export to version 4");
await migrationV3ToV4(exportDir, exportRecord as ExportRecord);
exportRecord = await exportService.updateExportRecord(exportDir, {
version: 4,
});
- addLogLine('migration to version 4 complete');
+ addLogLine("migration to version 4 complete");
}
if (exportRecord.version === 4) {
- addLogLine('migrating export to version 5');
+ addLogLine("migrating export to version 5");
await migrationV4ToV5(exportDir, exportRecord as ExportRecord);
exportRecord = await exportService.updateExportRecord(exportDir, {
version: 5,
});
- addLogLine('migration to version 5 complete');
+ addLogLine("migration to version 5 complete");
}
addLogLine(`Record at latest version`);
} catch (e) {
- logError(e, 'export record migration failed');
+ logError(e, "export record migration failed");
throw e;
}
}
async function migrationV0ToV1(
exportDir: string,
- exportRecord: ExportRecordV0
+ exportRecord: ExportRecordV0,
) {
if (!exportRecord?.exportedFiles) {
return;
@@ -117,27 +117,27 @@ async function migrationV0ToV1(
const localFiles = mergeMetadata(await getAllLocalFiles());
const localCollections = await getLocalCollections();
const personalFiles = getIDBasedSortedFiles(
- getPersonalFiles(localFiles, user)
+ getPersonalFiles(localFiles, user),
);
const nonEmptyPersonalCollections = getNonEmptyPersonalCollections(
localCollections,
personalFiles,
- user
+ user,
);
await migrateCollectionFolders(
nonEmptyPersonalCollections,
exportDir,
- collectionIDPathMap
+ collectionIDPathMap,
);
await migrateFiles(
getExportedFiles(personalFiles, exportRecord),
- collectionIDPathMap
+ collectionIDPathMap,
);
}
async function migrationV1ToV2(
exportRecord: ExportRecordV1,
- exportDir: string
+ exportDir: string,
) {
await removeDeprecatedExportRecordProperties(exportRecord, exportDir);
}
@@ -145,7 +145,7 @@ async function migrationV1ToV2(
async function migrationV2ToV3(
exportDir: string,
exportRecord: ExportRecordV2,
- updateProgress: (progress: ExportProgress) => void
+ updateProgress: (progress: ExportProgress) => void,
) {
if (!exportRecord?.exportedFiles) {
return;
@@ -153,7 +153,7 @@ async function migrationV2ToV3(
const user: User = getData(LS_KEYS.USER);
const localFiles = mergeMetadata(await getAllLocalFiles());
const personalFiles = getIDBasedSortedFiles(
- getPersonalFiles(localFiles, user)
+ getPersonalFiles(localFiles, user),
);
const collectionExportNames =
@@ -162,7 +162,7 @@ async function migrationV2ToV3(
const fileExportNames = await getFileExportNamesFromExportedFiles(
exportRecord,
getExportedFiles(personalFiles, exportRecord),
- updateProgress
+ updateProgress,
);
exportRecord.exportedCollectionPaths = undefined;
@@ -201,17 +201,17 @@ async function migrationV4ToV5(exportDir: string, exportRecord: ExportRecord) {
async function migrateCollectionFolders(
collections: Collection[],
exportDir: string,
- collectionIDPathMap: Map<number, string>
+ collectionIDPathMap: Map<number, string>,
) {
for (const collection of collections) {
const oldCollectionExportPath = getOldCollectionFolderPath(
exportDir,
collection.id,
- collection.name
+ collection.name,
);
const newCollectionExportPath = getUniqueCollectionFolderPath(
exportDir,
- collection.name
+ collection.name,
);
collectionIDPathMap.set(collection.id, newCollectionExportPath);
if (!exportService.exists(oldCollectionExportPath)) {
@@ -219,12 +219,12 @@ async function migrateCollectionFolders(
}
await exportService.rename(
oldCollectionExportPath,
- newCollectionExportPath
+ newCollectionExportPath,
);
await addCollectionExportedRecordV1(
exportDir,
collection.id,
- newCollectionExportPath
+ newCollectionExportPath,
);
}
}
@@ -235,30 +235,30 @@ async function migrateCollectionFolders(
*/
async function migrateFiles(
files: EnteFile[],
- collectionIDPathMap: Map<number, string>
+ collectionIDPathMap: Map<number, string>,
) {
for (const file of files) {
const oldFileSavePath = getOldFileSavePath(
collectionIDPathMap.get(file.collectionID),
- file
+ file,
);
const oldFileMetadataSavePath = getOldFileMetadataSavePath(
collectionIDPathMap.get(file.collectionID),
- file
+ file,
);
const newFileSaveName = getUniqueFileSaveName(
collectionIDPathMap.get(file.collectionID),
- file.metadata.title
+ file.metadata.title,
);
const newFileSavePath = getFileSavePath(
collectionIDPathMap.get(file.collectionID),
- newFileSaveName
+ newFileSaveName,
);
const newFileMetadataSavePath = getFileMetadataSavePath(
collectionIDPathMap.get(file.collectionID),
- newFileSaveName
+ newFileSaveName,
);
if (!exportService.exists(oldFileSavePath)) {
continue;
@@ -266,14 +266,14 @@ async function migrateFiles(
await exportService.rename(oldFileSavePath, newFileSavePath);
await exportService.rename(
oldFileMetadataSavePath,
- newFileMetadataSavePath
+ newFileMetadataSavePath,
);
}
}
async function removeDeprecatedExportRecordProperties(
exportRecord: ExportRecordV1,
- exportDir: string
+ exportDir: string,
) {
if (exportRecord?.queuedFiles) {
exportRecord.queuedFiles = undefined;
@@ -288,7 +288,7 @@ async function removeDeprecatedExportRecordProperties(
}
async function getCollectionExportNamesFromExportedCollectionPaths(
- exportRecord: ExportRecordV2
+ exportRecord: ExportRecordV2,
): Promise<CollectionExportNames> {
if (!exportRecord.exportedCollectionPaths) {
return;
@@ -297,11 +297,11 @@ async function getCollectionExportNamesFromExportedCollectionPaths(
Object.entries(exportRecord.exportedCollectionPaths).map(
([key, exportedCollectionPath]) => {
const exportedCollectionName = exportedCollectionPath
- .split('/')
+ .split("/")
.pop();
return [key, exportedCollectionName];
- }
- )
+ },
+ ),
);
return exportedCollectionNames;
}
@@ -316,19 +316,19 @@ async function getCollectionExportNamesFromExportedCollectionPaths(
async function getFileExportNamesFromExportedFiles(
exportRecord: ExportRecordV2,
exportedFiles: EnteFile[],
- updateProgress: (progress: ExportProgress) => void
+ updateProgress: (progress: ExportProgress) => void,
): Promise<FileExportNames> {
if (!exportedFiles.length) {
return;
}
addLogLine(
- 'updating exported files to exported file paths property',
- `got ${exportedFiles.length} files`
+ "updating exported files to exported file paths property",
+ `got ${exportedFiles.length} files`,
);
let exportedFileNames: FileExportNames;
const usedFilePaths = new Map<string, Set<string>>();
const exportedCollectionPaths = convertCollectionIDFolderPathObjectToMap(
- exportRecord.exportedCollectionPaths
+ exportRecord.exportedCollectionPaths,
);
let success = 0;
for (const file of exportedFiles) {
@@ -336,7 +336,7 @@ async function getFileExportNamesFromExportedFiles(
const collectionPath = exportedCollectionPaths.get(file.collectionID);
addLocalLog(
() =>
- `collection path for ${file.collectionID} is ${collectionPath}`
+ `collection path for ${file.collectionID} is ${collectionPath}`,
);
let fileExportName: string;
/*
@@ -349,27 +349,27 @@ async function getFileExportNamesFromExportedFiles(
const imageExportName = getUniqueFileExportNameForMigration(
collectionPath,
livePhoto.imageNameTitle,
- usedFilePaths
+ usedFilePaths,
);
const videoExportName = getUniqueFileExportNameForMigration(
collectionPath,
livePhoto.videoNameTitle,
- usedFilePaths
+ usedFilePaths,
);
fileExportName = getLivePhotoExportName(
imageExportName,
- videoExportName
+ videoExportName,
);
} else {
fileExportName = getUniqueFileExportNameForMigration(
collectionPath,
file.metadata.title,
- usedFilePaths
+ usedFilePaths,
);
}
addLocalLog(
() =>
- `file export name for ${file.metadata.title} is ${fileExportName}`
+ `file export name for ${file.metadata.title} is ${fileExportName}`,
);
exportedFileNames = {
...exportedFileNames,
@@ -385,17 +385,17 @@ async function getFileExportNamesFromExportedFiles(
}
function reMigrateCollectionExportNames(
- exportRecord: ExportRecord
+ exportRecord: ExportRecord,
): CollectionExportNames {
const exportedCollectionNames = Object.fromEntries(
Object.entries(exportRecord.collectionExportNames).map(
([key, exportedCollectionPath]) => {
const exportedCollectionName = exportedCollectionPath
- .split('/')
+ .split("/")
.pop();
return [key, exportedCollectionName];
- }
- )
+ },
+ ),
);
return exportedCollectionNames;
}
@@ -403,11 +403,11 @@ function reMigrateCollectionExportNames(
async function addCollectionExportedRecordV1(
folder: string,
collectionID: number,
- collectionExportPath: string
+ collectionExportPath: string,
) {
try {
const exportRecord = (await exportService.getExportRecord(
- folder
+ folder,
)) as unknown as ExportRecordV1;
if (!exportRecord?.exportedCollectionPaths) {
exportRecord.exportedCollectionPaths = {};
@@ -419,50 +419,50 @@ async function addCollectionExportedRecordV1(
await exportService.updateExportRecord(folder, exportRecord);
} catch (e) {
- logError(e, 'addCollectionExportedRecord failed');
+ logError(e, "addCollectionExportedRecord failed");
throw e;
}
}
async function removeCollectionExportMissingMetadataFolder(
exportDir: string,
- exportRecord: ExportRecord
+ exportRecord: ExportRecord,
) {
if (!exportRecord?.collectionExportNames) {
return;
}
const properlyExportedCollections = Object.entries(
- exportRecord.collectionExportNames
+ exportRecord.collectionExportNames,
)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.filter(([_, collectionExportName]) =>
exportService.exists(
getMetadataFolderExportPath(
- getCollectionExportPath(exportDir, collectionExportName)
- )
- )
+ getCollectionExportPath(exportDir, collectionExportName),
+ ),
+ ),
);
const properlyExportedCollectionIDs = properlyExportedCollections.map(
- ([collectionID]) => collectionID
+ ([collectionID]) => collectionID,
);
const properlyExportedFiles = Object.entries(
- exportRecord.fileExportNames
+ exportRecord.fileExportNames,
).filter(([fileUID]) =>
properlyExportedCollectionIDs.includes(
- getCollectionIDFromFileUID(fileUID).toString()
- )
+ getCollectionIDFromFileUID(fileUID).toString(),
+ ),
);
const updatedExportRecord: ExportRecord = {
...exportRecord,
collectionExportNames: Object.fromEntries(
- properlyExportedCollections
+ properlyExportedCollections,
) as CollectionExportNames,
fileExportNames: Object.fromEntries(
- properlyExportedFiles
+ properlyExportedFiles,
) as FileExportNames,
};
await exportService.updateExportRecord(exportDir, updatedExportRecord);
diff --git a/apps/photos/src/services/ffmpeg/ffmpegFactory.ts b/apps/photos/src/services/ffmpeg/ffmpegFactory.ts
index 1fa408c119..040f15047b 100644
--- a/apps/photos/src/services/ffmpeg/ffmpegFactory.ts
+++ b/apps/photos/src/services/ffmpeg/ffmpegFactory.ts
@@ -1,14 +1,14 @@
-import ElectronAPIs from '@ente/shared/electron';
-import isElectron from 'is-electron';
-import { ElectronFile } from 'types/upload';
-import ComlinkFFmpegWorker from 'utils/comlink/ComlinkFFmpegWorker';
+import ElectronAPIs from "@ente/shared/electron";
+import isElectron from "is-electron";
+import { ElectronFile } from "types/upload";
+import ComlinkFFmpegWorker from "utils/comlink/ComlinkFFmpegWorker";
export interface IFFmpeg {
run: (
cmd: string[],
inputFile: File | ElectronFile,
outputFilename: string,
- dontTimeout?: boolean
+ dontTimeout?: boolean,
) => Promise<File | ElectronFile>;
}
@@ -23,7 +23,7 @@ class FFmpegFactory {
cmd,
inputFile,
outputFilename,
- dontTimeout
+ dontTimeout,
);
},
};
diff --git a/apps/photos/src/services/ffmpeg/ffmpegService.ts b/apps/photos/src/services/ffmpeg/ffmpegService.ts
index edfa65a2aa..f6addc1347 100644
--- a/apps/photos/src/services/ffmpeg/ffmpegService.ts
+++ b/apps/photos/src/services/ffmpeg/ffmpegService.ts
@@ -1,15 +1,15 @@
+import { logError } from "@ente/shared/sentry";
import {
FFMPEG_PLACEHOLDER,
INPUT_PATH_PLACEHOLDER,
OUTPUT_PATH_PLACEHOLDER,
-} from 'constants/ffmpeg';
-import { ElectronFile } from 'types/upload';
-import { parseFFmpegExtractedMetadata } from 'utils/ffmpeg';
-import { logError } from '@ente/shared/sentry';
-import ffmpegFactory from './ffmpegFactory';
+} from "constants/ffmpeg";
+import { ElectronFile } from "types/upload";
+import { parseFFmpegExtractedMetadata } from "utils/ffmpeg";
+import ffmpegFactory from "./ffmpegFactory";
export async function generateVideoThumbnail(
- file: File | ElectronFile
+ file: File | ElectronFile,
): Promise<File | ElectronFile> {
try {
let seekTime = 1;
@@ -19,18 +19,18 @@ export async function generateVideoThumbnail(
return await ffmpegClient.run(
[
FFMPEG_PLACEHOLDER,
- '-i',
+ "-i",
INPUT_PATH_PLACEHOLDER,
- '-ss',
+ "-ss",
`00:00:0${seekTime}`,
- '-vframes',
- '1',
- '-vf',
- 'scale=-1:720',
+ "-vframes",
+ "1",
+ "-vf",
+ "scale=-1:720",
OUTPUT_PATH_PLACEHOLDER,
],
file,
- 'thumb.jpeg'
+ "thumb.jpeg",
);
} catch (e) {
if (seekTime === 0) {
@@ -40,7 +40,7 @@ export async function generateVideoThumbnail(
seekTime--;
}
} catch (e) {
- logError(e, 'ffmpeg generateVideoThumbnail failed');
+ logError(e, "ffmpeg generateVideoThumbnail failed");
throw e;
}
}
@@ -55,24 +55,24 @@ export async function extractVideoMetadata(file: File | ElectronFile) {
const metadata = await ffmpegClient.run(
[
FFMPEG_PLACEHOLDER,
- '-i',
+ "-i",
INPUT_PATH_PLACEHOLDER,
- '-c',
- 'copy',
- '-map_metadata',
- '0',
- '-f',
- 'ffmetadata',
+ "-c",
+ "copy",
+ "-map_metadata",
+ "0",
+ "-f",
+ "ffmetadata",
OUTPUT_PATH_PLACEHOLDER,
],
file,
- `metadata.txt`
+ `metadata.txt`,
);
return parseFFmpegExtractedMetadata(
- new Uint8Array(await metadata.arrayBuffer())
+ new Uint8Array(await metadata.arrayBuffer()),
);
} catch (e) {
- logError(e, 'ffmpeg extractVideoMetadata failed');
+ logError(e, "ffmpeg extractVideoMetadata failed");
throw e;
}
}
@@ -83,18 +83,18 @@ export async function convertToMP4(file: File | ElectronFile) {
return await ffmpegClient.run(
[
FFMPEG_PLACEHOLDER,
- '-i',
+ "-i",
INPUT_PATH_PLACEHOLDER,
- '-preset',
- 'ultrafast',
+ "-preset",
+ "ultrafast",
OUTPUT_PATH_PLACEHOLDER,
],
file,
- 'output.mp4',
- true
+ "output.mp4",
+ true,
);
} catch (e) {
- logError(e, 'ffmpeg convertToMP4 failed');
+ logError(e, "ffmpeg convertToMP4 failed");
throw e;
}
}
diff --git a/apps/photos/src/services/fileService.ts b/apps/photos/src/services/fileService.ts
index d5c664abad..62d5e309eb 100644
--- a/apps/photos/src/services/fileService.ts
+++ b/apps/photos/src/services/fileService.ts
@@ -1,80 +1,80 @@
-import { getEndpoint } from '@ente/shared/network/api';
-import localForage from '@ente/shared/storage/localForage';
+import { getEndpoint } from "@ente/shared/network/api";
+import localForage from "@ente/shared/storage/localForage";
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
-import { Collection } from 'types/collection';
-import HTTPService from '@ente/shared/network/HTTPService';
-import { logError } from '@ente/shared/sentry';
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { Events, eventBus } from "@ente/shared/events";
+import { addLogLine } from "@ente/shared/logging";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { logError } from "@ente/shared/sentry";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
+import { REQUEST_BATCH_SIZE } from "constants/api";
+import { Collection } from "types/collection";
+import {
+ EncryptedEnteFile,
+ EnteFile,
+ FileWithUpdatedMagicMetadata,
+ FileWithUpdatedPublicMagicMetadata,
+ TrashRequest,
+} from "types/file";
+import { SetFiles } from "types/gallery";
+import { BulkUpdateMagicMetadataRequest } from "types/magicMetadata";
+import { batch } from "utils/common";
import {
decryptFile,
getLatestVersionFiles,
mergeMetadata,
sortFiles,
-} from 'utils/file';
-import { eventBus, Events } from '@ente/shared/events';
-import {
- EnteFile,
- EncryptedEnteFile,
- TrashRequest,
- FileWithUpdatedMagicMetadata,
- FileWithUpdatedPublicMagicMetadata,
-} from 'types/file';
-import { SetFiles } from 'types/gallery';
-import { BulkUpdateMagicMetadataRequest } from 'types/magicMetadata';
-import { addLogLine } from '@ente/shared/logging';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
+} from "utils/file";
import {
getCollectionLastSyncTime,
setCollectionLastSyncTime,
-} from './collectionService';
-import { REQUEST_BATCH_SIZE } from 'constants/api';
-import { batch } from 'utils/common';
+} from "./collectionService";
const ENDPOINT = getEndpoint();
-const FILES_TABLE = 'files';
-const HIDDEN_FILES_TABLE = 'hidden-files';
+const FILES_TABLE = "files";
+const HIDDEN_FILES_TABLE = "hidden-files";
-export const getLocalFiles = async (type: 'normal' | 'hidden' = 'normal') => {
- const tableName = type === 'normal' ? FILES_TABLE : HIDDEN_FILES_TABLE;
+export const getLocalFiles = async (type: "normal" | "hidden" = "normal") => {
+ const tableName = type === "normal" ? FILES_TABLE : HIDDEN_FILES_TABLE;
const files: Array<EnteFile> =
(await localForage.getItem<EnteFile[]>(tableName)) || [];
return files;
};
-const setLocalFiles = async (type: 'normal' | 'hidden', files: EnteFile[]) => {
+const setLocalFiles = async (type: "normal" | "hidden", files: EnteFile[]) => {
try {
- const tableName = type === 'normal' ? FILES_TABLE : HIDDEN_FILES_TABLE;
+ const tableName = type === "normal" ? FILES_TABLE : HIDDEN_FILES_TABLE;
await localForage.setItem(tableName, files);
try {
eventBus.emit(Events.LOCAL_FILES_UPDATED);
} catch (e) {
- logError(e, 'Error in localFileUpdated handlers');
+ logError(e, "Error in localFileUpdated handlers");
}
} catch (e1) {
try {
const storageEstimate = await navigator.storage.estimate();
- logError(e1, 'failed to save files to indexedDB', {
+ logError(e1, "failed to save files to indexedDB", {
storageEstimate,
});
addLogLine(`storage estimate ${JSON.stringify(storageEstimate)}`);
} catch (e2) {
- logError(e1, 'failed to save files to indexedDB');
- logError(e2, 'failed to get storage stats');
+ logError(e1, "failed to save files to indexedDB");
+ logError(e2, "failed to get storage stats");
}
throw e1;
}
};
export const getAllLocalFiles = async () => {
- const normalFiles = await getLocalFiles('normal');
- const hiddenFiles = await getLocalFiles('hidden');
+ const normalFiles = await getLocalFiles("normal");
+ const hiddenFiles = await getLocalFiles("hidden");
return [...normalFiles, ...hiddenFiles];
};
export const syncFiles = async (
- type: 'normal' | 'hidden',
+ type: "normal" | "hidden",
collections: Collection[],
- setFiles: SetFiles
+ setFiles: SetFiles,
) => {
const localFiles = await getLocalFiles(type);
let files = await removeDeletedCollectionFiles(collections, localFiles);
@@ -102,7 +102,7 @@ export const syncFiles = async (
export const getFiles = async (
collection: Collection,
sinceTime: number,
- setFiles: SetFiles
+ setFiles: SetFiles,
): Promise<EnteFile[]> => {
try {
let decryptedFiles: EnteFile[] = [];
@@ -120,8 +120,8 @@ export const getFiles = async (
sinceTime: time,
},
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
const newDecryptedFilesBatch = await Promise.all(
@@ -131,7 +131,7 @@ export const getFiles = async (
} else {
return file;
}
- }) as Promise<EnteFile>[]
+ }) as Promise<EnteFile>[],
);
decryptedFiles = [...decryptedFiles, ...newDecryptedFilesBatch];
@@ -141,9 +141,9 @@ export const getFiles = async (
getLatestVersionFiles([
...(files || []),
...decryptedFiles,
- ])
- )
- )
+ ]),
+ ),
+ ),
);
if (resp.data.diff.length) {
time = resp.data.diff.slice(-1)[0].updationTime;
@@ -151,14 +151,14 @@ export const getFiles = async (
} while (resp.data.hasMore);
return decryptedFiles;
} catch (e) {
- logError(e, 'Get files failed');
+ logError(e, "Get files failed");
throw e;
}
};
const removeDeletedCollectionFiles = async (
collections: Collection[],
- files: EnteFile[]
+ files: EnteFile[],
) => {
const syncedCollectionIds = new Set<number>();
for (const collection of collections) {
@@ -187,12 +187,12 @@ export const trashFiles = async (filesToTrash: EnteFile[]) => {
trashRequest,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
}
} catch (e) {
- logError(e, 'trash file failed');
+ logError(e, "trash file failed");
throw e;
}
};
@@ -211,18 +211,18 @@ export const deleteFromTrash = async (filesToDelete: number[]) => {
{ fileIDs: batch },
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
}
} catch (e) {
- logError(e, 'deleteFromTrash failed');
+ logError(e, "deleteFromTrash failed");
throw e;
}
};
export const updateFileMagicMetadata = async (
- fileWithUpdatedMagicMetadataList: FileWithUpdatedMagicMetadata[]
+ fileWithUpdatedMagicMetadataList: FileWithUpdatedMagicMetadata[],
) => {
const token = getToken();
if (!token) {
@@ -237,7 +237,7 @@ export const updateFileMagicMetadata = async (
const { file: encryptedMagicMetadata } =
await cryptoWorker.encryptMetadata(
updatedMagicMetadata.data,
- file.key
+ file.key,
);
reqBody.metadataList.push({
id: file.id,
@@ -250,7 +250,7 @@ export const updateFileMagicMetadata = async (
});
}
await HTTPService.put(`${ENDPOINT}/files/magic-metadata`, reqBody, null, {
- 'X-Auth-Token': token,
+ "X-Auth-Token": token,
});
return fileWithUpdatedMagicMetadataList.map(
({ file, updatedMagicMetadata }): EnteFile => ({
@@ -259,12 +259,12 @@ export const updateFileMagicMetadata = async (
...updatedMagicMetadata,
version: updatedMagicMetadata.version + 1,
},
- })
+ }),
);
};
export const updateFilePublicMagicMetadata = async (
- fileWithUpdatedPublicMagicMetadataList: FileWithUpdatedPublicMagicMetadata[]
+ fileWithUpdatedPublicMagicMetadataList: FileWithUpdatedPublicMagicMetadata[],
): Promise<EnteFile[]> => {
const token = getToken();
if (!token) {
@@ -279,7 +279,7 @@ export const updateFilePublicMagicMetadata = async (
const { file: encryptedPubMagicMetadata } =
await cryptoWorker.encryptMetadata(
updatePublicMagicMetadata.data,
- file.key
+ file.key,
);
reqBody.metadataList.push({
id: file.id,
@@ -296,8 +296,8 @@ export const updateFilePublicMagicMetadata = async (
reqBody,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
return fileWithUpdatedPublicMagicMetadataList.map(
({ file, updatedPublicMagicMetadata }): EnteFile => ({
@@ -306,6 +306,6 @@ export const updateFilePublicMagicMetadata = async (
...updatedPublicMagicMetadata,
version: updatedPublicMagicMetadata.version + 1,
},
- })
+ }),
);
};
diff --git a/apps/photos/src/services/heicConversionService.ts b/apps/photos/src/services/heicConversionService.ts
index 00f49b7db8..f11a9f4a4e 100644
--- a/apps/photos/src/services/heicConversionService.ts
+++ b/apps/photos/src/services/heicConversionService.ts
@@ -1,12 +1,12 @@
-import { logError } from '@ente/shared/sentry';
-import WasmHEICConverterService from './wasmHeicConverter/wasmHEICConverterService';
+import { logError } from "@ente/shared/sentry";
+import WasmHEICConverterService from "./wasmHeicConverter/wasmHEICConverterService";
class HeicConversionService {
async convert(heicFileData: Blob): Promise<Blob> {
try {
return await WasmHEICConverterService.convert(heicFileData);
} catch (e) {
- logError(e, 'failed to convert heic file');
+ logError(e, "failed to convert heic file");
throw e;
}
}
diff --git a/apps/photos/src/services/imageProcessor.ts b/apps/photos/src/services/imageProcessor.ts
index b12597be7e..ac67c54ec4 100644
--- a/apps/photos/src/services/imageProcessor.ts
+++ b/apps/photos/src/services/imageProcessor.ts
@@ -1,10 +1,10 @@
-import ElectronAPIs from '@ente/shared/electron';
-import { addLogLine } from '@ente/shared/logging';
-import { logError } from '@ente/shared/sentry';
-import { ElectronFile } from 'types/upload';
-import { CustomError } from '@ente/shared/error';
-import { convertBytesToHumanReadable } from '@ente/shared/utils/size';
-import { WorkerSafeElectronService } from '@ente/shared/electron/service';
+import ElectronAPIs from "@ente/shared/electron";
+import { WorkerSafeElectronService } from "@ente/shared/electron/service";
+import { CustomError } from "@ente/shared/error";
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import { convertBytesToHumanReadable } from "@ente/shared/utils/size";
+import { ElectronFile } from "types/upload";
class ElectronImageProcessorService {
async convertToJPEG(fileBlob: Blob, filename: string): Promise<Blob> {
@@ -14,14 +14,14 @@ class ElectronImageProcessorService {
const convertedFileData =
await WorkerSafeElectronService.convertToJPEG(
inputFileData,
- filename
+ filename,
);
addLogLine(
`originalFileSize:${convertBytesToHumanReadable(
- fileBlob?.size
+ fileBlob?.size,
)},convertedFileSize:${convertBytesToHumanReadable(
- convertedFileData?.length
- )}, native conversion time: ${Date.now() - startTime}ms `
+ convertedFileData?.length,
+ )}, native conversion time: ${Date.now() - startTime}ms `,
);
return new Blob([convertedFileData]);
} catch (e) {
@@ -29,7 +29,7 @@ class ElectronImageProcessorService {
e.message !==
CustomError.WINDOWS_NATIVE_IMAGE_PROCESSING_NOT_SUPPORTED
) {
- logError(e, 'failed to convert to jpeg natively');
+ logError(e, "failed to convert to jpeg natively");
}
throw e;
}
@@ -38,23 +38,23 @@ class ElectronImageProcessorService {
async generateImageThumbnail(
inputFile: File | ElectronFile,
maxDimension: number,
- maxSize: number
+ maxSize: number,
): Promise<Uint8Array> {
try {
const startTime = Date.now();
const thumb = await ElectronAPIs.generateImageThumbnail(
inputFile,
maxDimension,
- maxSize
+ maxSize,
);
addLogLine(
`originalFileSize:${convertBytesToHumanReadable(
- inputFile?.size
+ inputFile?.size,
)},thumbFileSize:${convertBytesToHumanReadable(
- thumb?.length
+ thumb?.length,
)}, native thumbnail generation time: ${
Date.now() - startTime
- }ms `
+ }ms `,
);
return thumb;
} catch (e) {
@@ -62,7 +62,7 @@ class ElectronImageProcessorService {
e.message !==
CustomError.WINDOWS_NATIVE_IMAGE_PROCESSING_NOT_SUPPORTED
) {
- logError(e, 'failed to generate image thumbnail natively');
+ logError(e, "failed to generate image thumbnail natively");
}
throw e;
}
diff --git a/apps/photos/src/services/importService.ts b/apps/photos/src/services/importService.ts
index 328aec4bb4..2b99686d0b 100644
--- a/apps/photos/src/services/importService.ts
+++ b/apps/photos/src/services/importService.ts
@@ -1,8 +1,8 @@
-import { PICKED_UPLOAD_TYPE } from 'constants/upload';
-import { Collection } from 'types/collection';
-import { ElectronFile, FileWithCollection } from 'types/upload';
-import { logError } from '@ente/shared/sentry';
-import ElectronAPIs from '@ente/shared/electron';
+import ElectronAPIs from "@ente/shared/electron";
+import { logError } from "@ente/shared/sentry";
+import { PICKED_UPLOAD_TYPE } from "constants/upload";
+import { Collection } from "types/collection";
+import { ElectronFile, FileWithCollection } from "types/upload";
interface PendingUploads {
files: ElectronFile[];
@@ -17,10 +17,10 @@ class ImportService {
(await ElectronAPIs.getPendingUploads()) as PendingUploads;
return pendingUploads;
} catch (e) {
- if (e?.message?.includes('ENOENT: no such file or directory')) {
+ if (e?.message?.includes("ENOENT: no such file or directory")) {
// ignore
} else {
- logError(e, 'failed to getPendingUploads ');
+ logError(e, "failed to getPendingUploads ");
}
return { files: [], collectionName: null, type: null };
}
@@ -51,7 +51,7 @@ class ImportService {
(fileWithCollection.livePhotoAssets.image as ElectronFile)
.path,
(fileWithCollection.livePhotoAssets.video as ElectronFile)
- .path
+ .path,
);
} else {
filePaths.push((fileWithCollection.file as ElectronFile).path);
diff --git a/apps/photos/src/services/livePhotoService.ts b/apps/photos/src/services/livePhotoService.ts
index 613d2861ec..4d96e812cc 100644
--- a/apps/photos/src/services/livePhotoService.ts
+++ b/apps/photos/src/services/livePhotoService.ts
@@ -1,9 +1,9 @@
-import JSZip from 'jszip';
-import { EnteFile } from 'types/file';
+import JSZip from "jszip";
+import { EnteFile } from "types/file";
import {
getFileExtensionWithDot,
getFileNameWithoutExtension,
-} from 'utils/file';
+} from "utils/file";
class LivePhoto {
image: Uint8Array;
@@ -18,14 +18,14 @@ export const decodeLivePhoto = async (file: EnteFile, zipBlob: Blob) => {
const livePhoto = new LivePhoto();
for (const zipFilename in zip.files) {
- if (zipFilename.startsWith('image')) {
+ if (zipFilename.startsWith("image")) {
livePhoto.imageNameTitle =
originalName + getFileExtensionWithDot(zipFilename);
- livePhoto.image = await zip.files[zipFilename].async('uint8array');
- } else if (zipFilename.startsWith('video')) {
+ livePhoto.image = await zip.files[zipFilename].async("uint8array");
+ } else if (zipFilename.startsWith("video")) {
livePhoto.videoNameTitle =
originalName + getFileExtensionWithDot(zipFilename);
- livePhoto.video = await zip.files[zipFilename].async('uint8array');
+ livePhoto.video = await zip.files[zipFilename].async("uint8array");
}
}
return livePhoto;
@@ -34,12 +34,12 @@ export const decodeLivePhoto = async (file: EnteFile, zipBlob: Blob) => {
export const encodeLivePhoto = async (livePhoto: LivePhoto) => {
const zip = new JSZip();
zip.file(
- 'image' + getFileExtensionWithDot(livePhoto.imageNameTitle),
- livePhoto.image
+ "image" + getFileExtensionWithDot(livePhoto.imageNameTitle),
+ livePhoto.image,
);
zip.file(
- 'video' + getFileExtensionWithDot(livePhoto.videoNameTitle),
- livePhoto.video
+ "video" + getFileExtensionWithDot(livePhoto.videoNameTitle),
+ livePhoto.video,
);
- return await zip.generateAsync({ type: 'uint8array' });
+ return await zip.generateAsync({ type: "uint8array" });
};
diff --git a/apps/photos/src/services/locationSearchService.ts b/apps/photos/src/services/locationSearchService.ts
index eebe44fac8..a77557dee2 100644
--- a/apps/photos/src/services/locationSearchService.ts
+++ b/apps/photos/src/services/locationSearchService.ts
@@ -1,7 +1,7 @@
-import { CITIES_URL } from '@ente/shared/constants/urls';
-import { logError } from '@ente/shared/sentry';
-import { LocationTagData } from 'types/entity';
-import { Location } from 'types/upload';
+import { CITIES_URL } from "@ente/shared/constants/urls";
+import { logError } from "@ente/shared/sentry";
+import { LocationTagData } from "types/entity";
+import { Location } from "types/upload";
export interface City {
city: string;
@@ -24,12 +24,12 @@ class LocationSearchService {
}
this.citiesPromise = fetch(CITIES_URL).then((response) => {
return response.json().then((data) => {
- this.cities = data['data'];
+ this.cities = data["data"];
});
});
await this.citiesPromise;
} catch (e) {
- logError(e, 'LocationSearchService loadCities failed');
+ logError(e, "LocationSearchService loadCities failed");
this.citiesPromise = null;
}
}
@@ -46,7 +46,7 @@ class LocationSearchService {
.startsWith(searchTerm.toLowerCase());
});
} catch (e) {
- logError(e, 'LocationSearchService searchCities failed');
+ logError(e, "LocationSearchService searchCities failed");
throw e;
}
}
@@ -56,12 +56,12 @@ export default new LocationSearchService();
export function isInsideLocationTag(
location: Location,
- locationTag: LocationTagData
+ locationTag: LocationTagData,
) {
return isLocationCloseToPoint(
location,
locationTag.centerPoint,
- locationTag.radius
+ locationTag.radius,
);
}
@@ -69,14 +69,14 @@ export function isInsideCity(location: Location, city: City) {
return isLocationCloseToPoint(
{ latitude: city.lat, longitude: city.lng },
location,
- DEFAULT_CITY_RADIUS
+ DEFAULT_CITY_RADIUS,
);
}
function isLocationCloseToPoint(
centerPoint: Location,
location: Location,
- radius: number
+ radius: number,
) {
const a = (radius * _scaleFactor(centerPoint.latitude)) / KMS_PER_DEGREE;
const b = radius / KMS_PER_DEGREE;
diff --git a/apps/photos/src/services/machineLearning/arcfaceAlignmentService.ts b/apps/photos/src/services/machineLearning/arcfaceAlignmentService.ts
index 3386edaef2..99063b3f25 100644
--- a/apps/photos/src/services/machineLearning/arcfaceAlignmentService.ts
+++ b/apps/photos/src/services/machineLearning/arcfaceAlignmentService.ts
@@ -4,15 +4,15 @@ import {
FaceAlignmentService,
FaceDetection,
Versioned,
-} from 'types/machineLearning';
-import { getArcfaceAlignment } from 'utils/machineLearning/faceAlign';
+} from "types/machineLearning";
+import { getArcfaceAlignment } from "utils/machineLearning/faceAlign";
class ArcfaceAlignmentService implements FaceAlignmentService {
public method: Versioned<FaceAlignmentMethod>;
constructor() {
this.method = {
- value: 'ArcFace',
+ value: "ArcFace",
version: 1,
};
}
diff --git a/apps/photos/src/services/machineLearning/arcfaceCropService.ts b/apps/photos/src/services/machineLearning/arcfaceCropService.ts
index ab93becd2a..cb6ccd0298 100644
--- a/apps/photos/src/services/machineLearning/arcfaceCropService.ts
+++ b/apps/photos/src/services/machineLearning/arcfaceCropService.ts
@@ -5,16 +5,16 @@ import {
FaceCropService,
FaceDetection,
Versioned,
-} from 'types/machineLearning';
-import { getArcfaceAlignment } from 'utils/machineLearning/faceAlign';
-import { getFaceCrop } from 'utils/machineLearning/faceCrop';
+} from "types/machineLearning";
+import { getArcfaceAlignment } from "utils/machineLearning/faceAlign";
+import { getFaceCrop } from "utils/machineLearning/faceCrop";
class ArcFaceCropService implements FaceCropService {
public method: Versioned<FaceCropMethod>;
constructor() {
this.method = {
- value: 'ArcFace',
+ value: "ArcFace",
version: 1,
};
}
@@ -22,7 +22,7 @@ class ArcFaceCropService implements FaceCropService {
public async getFaceCrop(
imageBitmap: ImageBitmap,
faceDetection: FaceDetection,
- config: FaceCropConfig
+ config: FaceCropConfig,
): Promise<FaceCrop> {
const alignedFace = getArcfaceAlignment(faceDetection);
const faceCrop = getFaceCrop(imageBitmap, alignedFace, config);
diff --git a/apps/photos/src/services/machineLearning/blazeFaceDetectionService.ts b/apps/photos/src/services/machineLearning/blazeFaceDetectionService.ts
index 97a16976eb..2a82efb0a2 100644
--- a/apps/photos/src/services/machineLearning/blazeFaceDetectionService.ts
+++ b/apps/photos/src/services/machineLearning/blazeFaceDetectionService.ts
@@ -1,39 +1,39 @@
+import { addLogLine } from "@ente/shared/logging";
+import { GraphModel } from "@tensorflow/tfjs-converter";
+import * as tf from "@tensorflow/tfjs-core";
import {
load as blazeFaceLoad,
BlazeFaceModel,
NormalizedFace,
-} from 'blazeface-back';
-import * as tf from '@tensorflow/tfjs-core';
-import { GraphModel } from '@tensorflow/tfjs-converter';
+} from "blazeface-back";
+import {
+ BLAZEFACE_FACE_SIZE,
+ BLAZEFACE_INPUT_SIZE,
+ BLAZEFACE_IOU_THRESHOLD,
+ BLAZEFACE_MAX_FACES,
+ BLAZEFACE_PASS1_SCORE_THRESHOLD,
+ BLAZEFACE_SCORE_THRESHOLD,
+ MAX_FACE_DISTANCE_PERCENT,
+} from "constants/mlConfig";
import {
FaceDetection,
FaceDetectionMethod,
FaceDetectionService,
Versioned,
-} from 'types/machineLearning';
-import { Box, Point } from '../../../thirdparty/face-api/classes';
-import { addPadding, crop, resizeToSquare } from 'utils/image';
-import {
- computeTransformToBox,
- transformBox,
- transformPoints,
-} from 'utils/machineLearning/transform';
-import { enlargeBox, newBox, normFaceBox } from 'utils/machineLearning';
+} from "types/machineLearning";
+import { addPadding, crop, resizeToSquare } from "utils/image";
+import { enlargeBox, newBox, normFaceBox } from "utils/machineLearning";
import {
getNearestDetection,
removeDuplicateDetections,
transformPaddedToImage,
-} from 'utils/machineLearning/faceDetection';
+} from "utils/machineLearning/faceDetection";
import {
- BLAZEFACE_FACE_SIZE,
- BLAZEFACE_INPUT_SIZE,
- BLAZEFACE_IOU_THRESHOLD,
- BLAZEFACE_MAX_FACES,
- BLAZEFACE_PASS1_SCORE_THRESHOLD,
- BLAZEFACE_SCORE_THRESHOLD,
- MAX_FACE_DISTANCE_PERCENT,
-} from 'constants/mlConfig';
-import { addLogLine } from '@ente/shared/logging';
+ computeTransformToBox,
+ transformBox,
+ transformPoints,
+} from "utils/machineLearning/transform";
+import { Box, Point } from "../../../thirdparty/face-api/classes";
class BlazeFaceDetectionService implements FaceDetectionService {
private blazeFaceModel: Promise<BlazeFaceModel>;
@@ -45,7 +45,7 @@ class BlazeFaceDetectionService implements FaceDetectionService {
public constructor(desiredFaceSize: number = BLAZEFACE_FACE_SIZE) {
this.method = {
- value: 'BlazeFace',
+ value: "BlazeFace",
version: 1,
};
this.desiredFaceSize = desiredFaceSize;
@@ -56,15 +56,15 @@ class BlazeFaceDetectionService implements FaceDetectionService {
maxFaces: BLAZEFACE_MAX_FACES,
scoreThreshold: BLAZEFACE_PASS1_SCORE_THRESHOLD,
iouThreshold: BLAZEFACE_IOU_THRESHOLD,
- modelUrl: '/models/blazeface/back/model.json',
+ modelUrl: "/models/blazeface/back/model.json",
inputHeight: BLAZEFACE_INPUT_SIZE,
inputWidth: BLAZEFACE_INPUT_SIZE,
});
addLogLine(
- 'loaded blazeFaceModel: ',
+ "loaded blazeFaceModel: ",
// await this.blazeFaceModel,
// eslint-disable-next-line @typescript-eslint/await-thenable
- await tf.getBackend()
+ await tf.getBackend(),
);
}
@@ -168,7 +168,7 @@ class BlazeFaceDetectionService implements FaceDetectionService {
}
private async estimateFaces(
- imageBitmap: ImageBitmap
+ imageBitmap: ImageBitmap,
): Promise<Array<FaceDetection>> {
const resized = resizeToSquare(imageBitmap, BLAZEFACE_INPUT_SIZE);
const tfImage = tf.browser.fromPixels(resized.image);
@@ -185,7 +185,7 @@ class BlazeFaceDetectionService implements FaceDetectionService {
const faceDetections: Array<FaceDetection> = faces?.map((f) => {
const box = transformBox(normFaceBox(f), transform);
const normLandmarks = (f.landmarks as number[][])?.map(
- (l) => new Point(l[0], l[1])
+ (l) => new Point(l[0], l[1]),
);
const landmarks = transformPoints(normLandmarks, transform);
return {
@@ -200,7 +200,7 @@ class BlazeFaceDetectionService implements FaceDetectionService {
}
public async detectFaces(
- imageBitmap: ImageBitmap
+ imageBitmap: ImageBitmap,
): Promise<Array<FaceDetection>> {
const maxFaceDistance = imageBitmap.width * MAX_FACE_DISTANCE_PERCENT;
const pass1Detections = await this.estimateFaces(imageBitmap);
@@ -212,21 +212,21 @@ class BlazeFaceDetectionService implements FaceDetectionService {
const faceImage = crop(
imageBitmap,
imageBox,
- BLAZEFACE_INPUT_SIZE / 2
+ BLAZEFACE_INPUT_SIZE / 2,
);
const paddedImage = addPadding(faceImage, 0.5);
const paddedBox = enlargeBox(imageBox, 2);
const pass2Detections = await this.estimateFaces(paddedImage);
pass2Detections?.forEach((d) =>
- transformPaddedToImage(d, faceImage, imageBox, paddedBox)
+ transformPaddedToImage(d, faceImage, imageBox, paddedBox),
);
let selected = pass2Detections?.[0];
if (pass2Detections?.length > 1) {
// addLogLine('2nd pass >1 face', pass2Detections.length);
selected = getNearestDetection(
pass1Detection,
- pass2Detections
+ pass2Detections,
// maxFaceDistance
);
}
diff --git a/apps/photos/src/services/machineLearning/clusteringService.ts b/apps/photos/src/services/machineLearning/clusteringService.ts
index d513b7cafc..d4c0b4ea1d 100644
--- a/apps/photos/src/services/machineLearning/clusteringService.ts
+++ b/apps/photos/src/services/machineLearning/clusteringService.ts
@@ -1,4 +1,6 @@
-import { DBSCAN, OPTICS, KMEANS } from 'density-clustering';
+import { DBSCAN, KMEANS, OPTICS } from "density-clustering";
+import { Hdbscan } from "hdbscan";
+import { HdbscanInput } from "hdbscan/dist/types";
import {
ClusteringConfig,
ClusteringInput,
@@ -6,9 +8,7 @@ import {
ClusteringResults,
HdbscanResults,
Versioned,
-} from 'types/machineLearning';
-import { Hdbscan } from 'hdbscan';
-import { HdbscanInput } from 'hdbscan/dist/types';
+} from "types/machineLearning";
class ClusteringService {
private dbscan: DBSCAN;
@@ -24,7 +24,7 @@ class ClusteringService {
public clusterUsingDBSCAN(
dataset: Array<Array<number>>,
epsilon: number = 1.0,
- minPts: number = 2
+ minPts: number = 2,
): ClusteringResults {
// addLogLine("distanceFunction", DBSCAN._);
const clusters = this.dbscan.run(dataset, epsilon, minPts);
@@ -35,7 +35,7 @@ class ClusteringService {
public clusterUsingOPTICS(
dataset: Array<Array<number>>,
epsilon: number = 1.0,
- minPts: number = 2
+ minPts: number = 2,
) {
const clusters = this.optics.run(dataset, epsilon, minPts);
return { clusters, noise: [] };
@@ -43,7 +43,7 @@ class ClusteringService {
public clusterUsingKMEANS(
dataset: Array<Array<number>>,
- numClusters: number = 5
+ numClusters: number = 5,
) {
const clusters = this.kmeans.run(dataset, numClusters);
return { clusters, noise: [] };
@@ -51,7 +51,7 @@ class ClusteringService {
public clusterUsingHdbscan(hdbscanInput: HdbscanInput): HdbscanResults {
if (hdbscanInput.input.length < 10) {
- throw Error('too few samples to run Hdbscan');
+ throw Error("too few samples to run Hdbscan");
}
const hdbscan = new Hdbscan(hdbscanInput);
@@ -65,22 +65,22 @@ class ClusteringService {
public cluster(
method: Versioned<ClusteringMethod>,
input: ClusteringInput,
- config: ClusteringConfig
+ config: ClusteringConfig,
) {
- if (method.value === 'Hdbscan') {
+ if (method.value === "Hdbscan") {
return this.clusterUsingHdbscan({
input,
minClusterSize: config.minClusterSize,
debug: config.generateDebugInfo,
});
- } else if (method.value === 'Dbscan') {
+ } else if (method.value === "Dbscan") {
return this.clusterUsingDBSCAN(
input,
config.maxDistanceInsideCluster,
- config.minClusterSize
+ config.minClusterSize,
);
} else {
- throw Error('Unknown clustering method: ' + method.value);
+ throw Error("Unknown clustering method: " + method.value);
}
}
}
diff --git a/apps/photos/src/services/machineLearning/dbscanClusteringService.ts b/apps/photos/src/services/machineLearning/dbscanClusteringService.ts
index 55af4858af..b2343bdd5b 100644
--- a/apps/photos/src/services/machineLearning/dbscanClusteringService.ts
+++ b/apps/photos/src/services/machineLearning/dbscanClusteringService.ts
@@ -1,4 +1,4 @@
-import { DBSCAN } from 'density-clustering';
+import { DBSCAN } from "density-clustering";
import {
ClusteringConfig,
ClusteringInput,
@@ -6,28 +6,28 @@ import {
ClusteringService,
HdbscanResults,
Versioned,
-} from 'types/machineLearning';
+} from "types/machineLearning";
class DbscanClusteringService implements ClusteringService {
public method: Versioned<ClusteringMethod>;
constructor() {
this.method = {
- value: 'Dbscan',
+ value: "Dbscan",
version: 1,
};
}
public async cluster(
input: ClusteringInput,
- config: ClusteringConfig
+ config: ClusteringConfig,
): Promise<HdbscanResults> {
// addLogLine('Clustering input: ', input);
const dbscan = new DBSCAN();
const clusters = dbscan.run(
input,
config.clusterSelectionEpsilon,
- config.minClusterSize
+ config.minClusterSize,
);
const noise = dbscan.noise;
return { clusters, noise };
diff --git a/apps/photos/src/services/machineLearning/faceService.ts b/apps/photos/src/services/machineLearning/faceService.ts
index b4f78d1cef..1355ca494f 100644
--- a/apps/photos/src/services/machineLearning/faceService.ts
+++ b/apps/photos/src/services/machineLearning/faceService.ts
@@ -1,33 +1,33 @@
+import { addLogLine } from "@ente/shared/logging";
import {
- MLSyncContext,
- MLSyncFileContext,
DetectedFace,
Face,
-} from 'types/machineLearning';
-import { addLogLine } from '@ente/shared/logging';
+ MLSyncContext,
+ MLSyncFileContext,
+} from "types/machineLearning";
+import { imageBitmapToBlob } from "utils/image";
import {
- isDifferentOrOld,
- getFaceId,
areFaceIdsSame,
extractFaceImages,
+ getFaceId,
getLocalFile,
getOriginalImageBitmap,
-} from 'utils/machineLearning';
-import { storeFaceCrop } from 'utils/machineLearning/faceCrop';
-import mlIDbStorage from 'utils/storage/mlIDbStorage';
-import ReaderService from './readerService';
-import { imageBitmapToBlob } from 'utils/image';
+ isDifferentOrOld,
+} from "utils/machineLearning";
+import { storeFaceCrop } from "utils/machineLearning/faceCrop";
+import mlIDbStorage from "utils/storage/mlIDbStorage";
+import ReaderService from "./readerService";
class FaceService {
async syncFileFaceDetections(
syncContext: MLSyncContext,
- fileContext: MLSyncFileContext
+ fileContext: MLSyncFileContext,
) {
const { oldMlFile, newMlFile } = fileContext;
if (
!isDifferentOrOld(
oldMlFile?.faceDetectionMethod,
- syncContext.faceDetectionService.method
+ syncContext.faceDetectionService.method,
) &&
oldMlFile?.imageSource === syncContext.config.imageSource
) {
@@ -47,7 +47,7 @@ class FaceService {
fileContext.newDetection = true;
const imageBitmap = await ReaderService.getImageBitmap(
syncContext,
- fileContext
+ fileContext,
);
const faceDetections =
await syncContext.faceDetectionService.detectFaces(imageBitmap);
@@ -66,12 +66,12 @@ class FaceService {
// ?.filter((f) =>
// f.box.width > syncContext.config.faceDetection.minFaceSize
// );
- addLogLine('[MLService] Detected Faces: ', newMlFile.faces?.length);
+ addLogLine("[MLService] Detected Faces: ", newMlFile.faces?.length);
}
async syncFileFaceCrops(
syncContext: MLSyncContext,
- fileContext: MLSyncFileContext
+ fileContext: MLSyncFileContext,
) {
const { oldMlFile, newMlFile } = fileContext;
if (
@@ -79,7 +79,7 @@ class FaceService {
!fileContext.newDetection &&
!isDifferentOrOld(
oldMlFile?.faceCropMethod,
- syncContext.faceCropService.method
+ syncContext.faceCropService.method,
) &&
areFaceIdsSame(newMlFile.faces, oldMlFile?.faces)
) {
@@ -92,7 +92,7 @@ class FaceService {
const imageBitmap = await ReaderService.getImageBitmap(
syncContext,
- fileContext
+ fileContext,
);
newMlFile.faceCropMethod = syncContext.faceCropService.method;
@@ -103,14 +103,14 @@ class FaceService {
async syncFileFaceAlignments(
syncContext: MLSyncContext,
- fileContext: MLSyncFileContext
+ fileContext: MLSyncFileContext,
) {
const { oldMlFile, newMlFile } = fileContext;
if (
!fileContext.newDetection &&
!isDifferentOrOld(
oldMlFile?.faceAlignmentMethod,
- syncContext.faceAlignmentService.method
+ syncContext.faceAlignmentService.method,
) &&
areFaceIdsSame(newMlFile.faces, oldMlFile?.faces)
) {
@@ -125,23 +125,23 @@ class FaceService {
fileContext.newAlignment = true;
for (const face of newMlFile.faces) {
face.alignment = syncContext.faceAlignmentService.getFaceAlignment(
- face.detection
+ face.detection,
);
}
- addLogLine('[MLService] alignedFaces: ', newMlFile.faces?.length);
+ addLogLine("[MLService] alignedFaces: ", newMlFile.faces?.length);
// addLogLine('4 TF Memory stats: ',JSON.stringify(tf.memory()));
}
async syncFileFaceEmbeddings(
syncContext: MLSyncContext,
- fileContext: MLSyncFileContext
+ fileContext: MLSyncFileContext,
) {
const { oldMlFile, newMlFile } = fileContext;
if (
!fileContext.newAlignment &&
!isDifferentOrOld(
oldMlFile?.faceEmbeddingMethod,
- syncContext.faceEmbeddingService.method
+ syncContext.faceEmbeddingService.method,
) &&
areFaceIdsSame(newMlFile.faces, oldMlFile?.faces)
) {
@@ -158,34 +158,34 @@ class FaceService {
// (await this.getImageBitmap(syncContext, fileContext));
const faceImages = await extractFaceImages(
newMlFile.faces,
- syncContext.faceEmbeddingService.faceSize
+ syncContext.faceEmbeddingService.faceSize,
);
const embeddings =
await syncContext.faceEmbeddingService.getFaceEmbeddings(
- faceImages
+ faceImages,
);
faceImages.forEach((faceImage) => faceImage.close());
newMlFile.faces.forEach((f, i) => (f.embedding = embeddings[i]));
- addLogLine('[MLService] facesWithEmbeddings: ', newMlFile.faces.length);
+ addLogLine("[MLService] facesWithEmbeddings: ", newMlFile.faces.length);
// addLogLine('5 TF Memory stats: ',JSON.stringify(tf.memory()));
}
async saveFaceCrop(
imageBitmap: ImageBitmap,
face: Face,
- syncContext: MLSyncContext
+ syncContext: MLSyncContext,
) {
const faceCrop = await syncContext.faceCropService.getFaceCrop(
imageBitmap,
face.detection,
- syncContext.config.faceCrop
+ syncContext.config.faceCrop,
);
face.crop = await storeFaceCrop(
face.id,
faceCrop,
- syncContext.config.faceCrop.blobOptions
+ syncContext.config.faceCrop.blobOptions,
);
const blob = await imageBitmapToBlob(faceCrop.image);
faceCrop.image.close();
@@ -203,7 +203,7 @@ class FaceService {
public async runFaceClustering(
syncContext: MLSyncContext,
- allFaces: Array<Face>
+ allFaces: Array<Face>,
) {
// await this.init();
@@ -211,23 +211,23 @@ class FaceService {
if (!allFaces || allFaces.length < clusteringConfig.minInputSize) {
addLogLine(
- '[MLService] Too few faces to cluster, not running clustering: ',
- allFaces.length
+ "[MLService] Too few faces to cluster, not running clustering: ",
+ allFaces.length,
);
return;
}
- addLogLine('Running clustering allFaces: ', allFaces.length);
+ addLogLine("Running clustering allFaces: ", allFaces.length);
syncContext.mlLibraryData.faceClusteringResults =
await syncContext.faceClusteringService.cluster(
allFaces.map((f) => Array.from(f.embedding)),
- syncContext.config.faceClustering
+ syncContext.config.faceClustering,
);
syncContext.mlLibraryData.faceClusteringMethod =
syncContext.faceClusteringService.method;
addLogLine(
- '[MLService] Got face clustering results: ',
- JSON.stringify(syncContext.mlLibraryData.faceClusteringResults)
+ "[MLService] Got face clustering results: ",
+ JSON.stringify(syncContext.mlLibraryData.faceClusteringResults),
);
// syncContext.faceClustersWithNoise = {
@@ -242,12 +242,12 @@ class FaceService {
public async regenerateFaceCrop(
syncContext: MLSyncContext,
- faceID: string
+ faceID: string,
) {
- const fileID = Number(faceID.split('-')[0]);
+ const fileID = Number(faceID.split("-")[0]);
const personFace = await mlIDbStorage.getFace(fileID, faceID);
if (!personFace) {
- throw Error('Face not found');
+ throw Error("Face not found");
}
const file = await getLocalFile(personFace.fileId);
diff --git a/apps/photos/src/services/machineLearning/hdbscanClusteringService.ts b/apps/photos/src/services/machineLearning/hdbscanClusteringService.ts
index 0a4f6a2f30..da7808d45d 100644
--- a/apps/photos/src/services/machineLearning/hdbscanClusteringService.ts
+++ b/apps/photos/src/services/machineLearning/hdbscanClusteringService.ts
@@ -1,4 +1,4 @@
-import { Hdbscan } from 'hdbscan';
+import { Hdbscan } from "hdbscan";
import {
ClusteringConfig,
ClusteringInput,
@@ -6,21 +6,21 @@ import {
ClusteringService,
HdbscanResults,
Versioned,
-} from 'types/machineLearning';
+} from "types/machineLearning";
class HdbscanClusteringService implements ClusteringService {
public method: Versioned<ClusteringMethod>;
constructor() {
this.method = {
- value: 'Hdbscan',
+ value: "Hdbscan",
version: 1,
};
}
public async cluster(
input: ClusteringInput,
- config: ClusteringConfig
+ config: ClusteringConfig,
): Promise<HdbscanResults> {
// addLogLine('Clustering input: ', input);
const hdbscan = new Hdbscan({
diff --git a/apps/photos/src/services/machineLearning/imageSceneService.ts b/apps/photos/src/services/machineLearning/imageSceneService.ts
index ac23218bcc..65438a5b92 100644
--- a/apps/photos/src/services/machineLearning/imageSceneService.ts
+++ b/apps/photos/src/services/machineLearning/imageSceneService.ts
@@ -1,14 +1,14 @@
-import * as tf from '@tensorflow/tfjs-core';
-import * as tfjsConverter from '@tensorflow/tfjs-converter';
+import { addLogLine } from "@ente/shared/logging";
+import * as tfjsConverter from "@tensorflow/tfjs-converter";
+import * as tf from "@tensorflow/tfjs-core";
+import { SCENE_DETECTION_IMAGE_SIZE } from "constants/mlConfig";
import {
ObjectDetection,
SceneDetectionMethod,
SceneDetectionService,
Versioned,
-} from 'types/machineLearning';
-import { SCENE_DETECTION_IMAGE_SIZE } from 'constants/mlConfig';
-import { resizeToSquare } from 'utils/image';
-import { addLogLine } from '@ente/shared/logging';
+} from "types/machineLearning";
+import { resizeToSquare } from "utils/image";
class ImageScene implements SceneDetectionService {
method: Versioned<SceneDetectionMethod>;
@@ -19,29 +19,29 @@ class ImageScene implements SceneDetectionService {
public constructor() {
this.method = {
- value: 'ImageScene',
+ value: "ImageScene",
version: 1,
};
this.workerID = Math.round(Math.random() * 1000);
}
private async init() {
- addLogLine(`[${this.workerID}]`, 'ImageScene init called');
+ addLogLine(`[${this.workerID}]`, "ImageScene init called");
if (this.model) {
return;
}
this.sceneMap = await (
- await fetch('/models/imagescene/sceneMap.json')
+ await fetch("/models/imagescene/sceneMap.json")
).json();
this.model = await tfjsConverter.loadGraphModel(
- '/models/imagescene/model.json'
+ "/models/imagescene/model.json",
);
addLogLine(
`[${this.workerID}]`,
- 'loaded ImageScene model',
- tf.getBackend()
+ "loaded ImageScene model",
+ tf.getBackend(),
);
tf.tidy(() => {
@@ -54,7 +54,7 @@ class ImageScene implements SceneDetectionService {
private async getImageSceneModel() {
addLogLine(
`[${this.workerID}]`,
- 'ImageScene getImageSceneModel called'
+ "ImageScene getImageSceneModel called",
);
if (!this.ready) {
this.ready = this.init();
@@ -70,7 +70,7 @@ class ImageScene implements SceneDetectionService {
const output = tf.tidy(() => {
const tfImage = tf.browser.fromPixels(resized.image);
- const input = tf.expandDims(tf.cast(tfImage, 'float32'));
+ const input = tf.expandDims(tf.cast(tfImage, "float32"));
const output = model.predict(input) as tf.Tensor;
return output;
});
@@ -82,7 +82,7 @@ class ImageScene implements SceneDetectionService {
data,
minScore,
image.width,
- image.height
+ image.height,
);
return scenes;
@@ -92,7 +92,7 @@ class ImageScene implements SceneDetectionService {
outputData: Float32Array,
minScore: number,
width: number,
- height: number
+ height: number,
): ObjectDetection[] {
const scenes = [];
for (let i = 0; i < outputData.length; i++) {
diff --git a/apps/photos/src/services/machineLearning/machineLearningFactory.ts b/apps/photos/src/services/machineLearning/machineLearningFactory.ts
index c684da73b7..d397a60ad0 100644
--- a/apps/photos/src/services/machineLearning/machineLearningFactory.ts
+++ b/apps/photos/src/services/machineLearning/machineLearningFactory.ts
@@ -1,6 +1,12 @@
-import PQueue from 'p-queue';
-import { EnteFile } from 'types/file';
+import { getDedicatedCryptoWorker } from "@ente/shared/crypto";
+import { DedicatedCryptoWorker } from "@ente/shared/crypto/internal/crypto.worker";
+import { addLogLine } from "@ente/shared/logging";
+import { ComlinkWorker } from "@ente/shared/worker/comlinkWorker";
+import PQueue from "p-queue";
+import { EnteFile } from "types/file";
import {
+ ClusteringMethod,
+ ClusteringService,
Face,
FaceAlignmentMethod,
FaceAlignmentService,
@@ -10,114 +16,108 @@ import {
FaceDetectionService,
FaceEmbeddingMethod,
FaceEmbeddingService,
+ MLLibraryData,
MLSyncConfig,
MLSyncContext,
- ClusteringMethod,
- ClusteringService,
- MLLibraryData,
- ObjectDetectionService,
ObjectDetectionMethod,
- SceneDetectionService,
+ ObjectDetectionService,
SceneDetectionMethod,
-} from 'types/machineLearning';
-import { getConcurrency } from 'utils/common/concurrency';
-import { logQueueStats } from 'utils/machineLearning';
-import arcfaceAlignmentService from './arcfaceAlignmentService';
-import arcfaceCropService from './arcfaceCropService';
-import hdbscanClusteringService from './hdbscanClusteringService';
-import blazeFaceDetectionService from './blazeFaceDetectionService';
-import mobileFaceNetEmbeddingService from './mobileFaceNetEmbeddingService';
-import dbscanClusteringService from './dbscanClusteringService';
-import ssdMobileNetV2Service from './ssdMobileNetV2Service';
-import imageSceneService from './imageSceneService';
-import { getDedicatedCryptoWorker } from '@ente/shared/crypto';
-import { ComlinkWorker } from '@ente/shared/worker/comlinkWorker';
-import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
-import { addLogLine } from '@ente/shared/logging';
+ SceneDetectionService,
+} from "types/machineLearning";
+import { getConcurrency } from "utils/common/concurrency";
+import { logQueueStats } from "utils/machineLearning";
+import arcfaceAlignmentService from "./arcfaceAlignmentService";
+import arcfaceCropService from "./arcfaceCropService";
+import blazeFaceDetectionService from "./blazeFaceDetectionService";
+import dbscanClusteringService from "./dbscanClusteringService";
+import hdbscanClusteringService from "./hdbscanClusteringService";
+import imageSceneService from "./imageSceneService";
+import mobileFaceNetEmbeddingService from "./mobileFaceNetEmbeddingService";
+import ssdMobileNetV2Service from "./ssdMobileNetV2Service";
export class MLFactory {
public static getFaceDetectionService(
- method: FaceDetectionMethod
+ method: FaceDetectionMethod,
): FaceDetectionService {
- if (method === 'BlazeFace') {
+ if (method === "BlazeFace") {
return blazeFaceDetectionService;
}
- throw Error('Unknon face detection method: ' + method);
+ throw Error("Unknon face detection method: " + method);
}
public static getObjectDetectionService(
- method: ObjectDetectionMethod
+ method: ObjectDetectionMethod,
): ObjectDetectionService {
- if (method === 'SSDMobileNetV2') {
+ if (method === "SSDMobileNetV2") {
return ssdMobileNetV2Service;
}
- throw Error('Unknown object detection method: ' + method);
+ throw Error("Unknown object detection method: " + method);
}
public static getSceneDetectionService(
- method: SceneDetectionMethod
+ method: SceneDetectionMethod,
): SceneDetectionService {
- if (method === 'ImageScene') {
+ if (method === "ImageScene") {
return imageSceneService;
}
- throw Error('Unknown scene detection method: ' + method);
+ throw Error("Unknown scene detection method: " + method);
}
public static getFaceCropService(method: FaceCropMethod) {
- if (method === 'ArcFace') {
+ if (method === "ArcFace") {
return arcfaceCropService;
}
- throw Error('Unknon face crop method: ' + method);
+ throw Error("Unknon face crop method: " + method);
}
public static getFaceAlignmentService(
- method: FaceAlignmentMethod
+ method: FaceAlignmentMethod,
): FaceAlignmentService {
- if (method === 'ArcFace') {
+ if (method === "ArcFace") {
return arcfaceAlignmentService;
}
- throw Error('Unknon face alignment method: ' + method);
+ throw Error("Unknon face alignment method: " + method);
}
public static getFaceEmbeddingService(
- method: FaceEmbeddingMethod
+ method: FaceEmbeddingMethod,
): FaceEmbeddingService {
- if (method === 'MobileFaceNet') {
+ if (method === "MobileFaceNet") {
return mobileFaceNetEmbeddingService;
}
- throw Error('Unknon face embedding method: ' + method);
+ throw Error("Unknon face embedding method: " + method);
}
public static getClusteringService(
- method: ClusteringMethod
+ method: ClusteringMethod,
): ClusteringService {
- if (method === 'Hdbscan') {
+ if (method === "Hdbscan") {
return hdbscanClusteringService;
}
- if (method === 'Dbscan') {
+ if (method === "Dbscan") {
return dbscanClusteringService;
}
- throw Error('Unknon clustering method: ' + method);
+ throw Error("Unknon clustering method: " + method);
}
public static getMLSyncContext(
token: string,
userID: number,
config: MLSyncConfig,
- shouldUpdateMLVersion: boolean = true
+ shouldUpdateMLVersion: boolean = true,
) {
return new LocalMLSyncContext(
token,
userID,
config,
- shouldUpdateMLVersion
+ shouldUpdateMLVersion,
);
}
}
@@ -162,7 +162,7 @@ export class LocalMLSyncContext implements MLSyncContext {
userID: number,
config: MLSyncConfig,
shouldUpdateMLVersion: boolean = true,
- concurrency?: number
+ concurrency?: number,
) {
this.token = token;
this.userID = userID;
@@ -170,26 +170,26 @@ export class LocalMLSyncContext implements MLSyncContext {
this.shouldUpdateMLVersion = shouldUpdateMLVersion;
this.faceDetectionService = MLFactory.getFaceDetectionService(
- this.config.faceDetection.method
+ this.config.faceDetection.method,
);
this.faceCropService = MLFactory.getFaceCropService(
- this.config.faceCrop.method
+ this.config.faceCrop.method,
);
this.faceAlignmentService = MLFactory.getFaceAlignmentService(
- this.config.faceAlignment.method
+ this.config.faceAlignment.method,
);
this.faceEmbeddingService = MLFactory.getFaceEmbeddingService(
- this.config.faceEmbedding.method
+ this.config.faceEmbedding.method,
);
this.faceClusteringService = MLFactory.getClusteringService(
- this.config.faceClustering.method
+ this.config.faceClustering.method,
);
this.objectDetectionService = MLFactory.getObjectDetectionService(
- this.config.objectDetection.method
+ this.config.objectDetection.method,
);
this.sceneDetectionService = MLFactory.getSceneDetectionService(
- this.config.sceneDetection.method
+ this.config.sceneDetection.method,
);
this.outOfSyncFiles = [];
@@ -198,11 +198,11 @@ export class LocalMLSyncContext implements MLSyncContext {
this.concurrency = concurrency || getConcurrency();
- addLogLine('Using concurrency: ', this.concurrency);
+ addLogLine("Using concurrency: ", this.concurrency);
// timeout is added on downloads
// timeout on queue will keep the operation open till worker is terminated
this.syncQueue = new PQueue({ concurrency: this.concurrency });
- logQueueStats(this.syncQueue, 'sync');
+ logQueueStats(this.syncQueue, "sync");
// this.downloadQueue = new PQueue({ concurrency: 1 });
// logQueueStats(this.downloadQueue, 'download');
diff --git a/apps/photos/src/services/machineLearning/machineLearningService.ts b/apps/photos/src/services/machineLearning/machineLearningService.ts
index 390b950928..c95effc763 100644
--- a/apps/photos/src/services/machineLearning/machineLearningService.ts
+++ b/apps/photos/src/services/machineLearning/machineLearningService.ts
@@ -1,9 +1,9 @@
-import { getLocalFiles } from 'services/fileService';
-import { EnteFile } from 'types/file';
+import { getLocalFiles } from "services/fileService";
+import { EnteFile } from "types/file";
-import * as tf from '@tensorflow/tfjs-core';
-import '@tensorflow/tfjs-backend-webgl';
-import '@tensorflow/tfjs-backend-cpu';
+import "@tensorflow/tfjs-backend-cpu";
+import "@tensorflow/tfjs-backend-webgl";
+import * as tf from "@tensorflow/tfjs-core";
// import '@tensorflow/tfjs-backend-wasm';
// import { setWasmPaths } from '@tensorflow/tfjs-backend-wasm';
// import '@tensorflow/tfjs-backend-cpu';
@@ -13,7 +13,7 @@ import {
MLSyncContext,
MLSyncFileContext,
MLSyncResult,
-} from 'types/machineLearning';
+} from "types/machineLearning";
// import { toTSNE } from 'utils/machineLearning/visualization';
// import {
@@ -21,20 +21,20 @@ import {
// mlFilesStore
// } from 'utils/storage/mlStorage';
// import { getAllFacesFromMap } from 'utils/machineLearning';
-import { MLFactory } from './machineLearningFactory';
-import mlIDbStorage from 'utils/storage/mlIDbStorage';
-import { getMLSyncConfig } from 'utils/machineLearning/config';
-import { CustomError, parseUploadErrorCodes } from '@ente/shared/error';
-import { MAX_ML_SYNC_ERROR_COUNT } from 'constants/mlConfig';
-import FaceService from './faceService';
-import PeopleService from './peopleService';
-import ObjectService from './objectService';
+import { CustomError, parseUploadErrorCodes } from "@ente/shared/error";
+import { MAX_ML_SYNC_ERROR_COUNT } from "constants/mlConfig";
+import { getMLSyncConfig } from "utils/machineLearning/config";
+import mlIDbStorage from "utils/storage/mlIDbStorage";
+import FaceService from "./faceService";
+import { MLFactory } from "./machineLearningFactory";
+import ObjectService from "./objectService";
+import PeopleService from "./peopleService";
// import TextService from './textService';
-import ReaderService from './readerService';
-import { logError } from '@ente/shared/sentry';
-import { addLogLine } from '@ente/shared/logging';
-import downloadManager from 'services/download';
-import { APPS } from '@ente/shared/apps/constants';
+import { APPS } from "@ente/shared/apps/constants";
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import downloadManager from "services/download";
+import ReaderService from "./readerService";
class MachineLearningService {
private initialized = false;
@@ -60,7 +60,7 @@ class MachineLearningService {
public async sync(token: string, userID: number): Promise<MLSyncResult> {
if (!token) {
- throw Error('Token needed by ml service to sync file');
+ throw Error("Token needed by ml service to sync file");
}
await downloadManager.init(APPS.PHOTOS, { token });
@@ -111,7 +111,7 @@ class MachineLearningService {
// addLogLine('[MLService] sync results: ', mlSyncResult);
// await syncContext.dispose();
- addLogLine('Final TF Memory stats: ', JSON.stringify(tf.memory()));
+ addLogLine("Final TF Memory stats: ", JSON.stringify(tf.memory()));
return mlSyncResult;
}
@@ -119,7 +119,7 @@ class MachineLearningService {
public async regenerateFaceCrop(
token: string,
userID: number,
- faceID: string
+ faceID: string,
) {
await downloadManager.init(APPS.PHOTOS, { token });
const syncContext = await this.getSyncContext(token, userID);
@@ -139,11 +139,11 @@ class MachineLearningService {
const localFiles = await getLocalFiles();
const personalFiles = localFiles.filter(
- (f) => f.ownerID === syncContext.userID
+ (f) => f.ownerID === syncContext.userID,
);
syncContext.localFilesMap = new Map<number, EnteFile>();
personalFiles.forEach((f) =>
- syncContext.localFilesMap.set(f.id, f)
+ syncContext.localFilesMap.set(f.id, f),
);
}
@@ -155,7 +155,7 @@ class MachineLearningService {
const localFilesMap = await this.getLocalFilesMap(syncContext);
const db = await mlIDbStorage.db;
- const tx = db.transaction('files', 'readwrite');
+ const tx = db.transaction("files", "readwrite");
const mlFileIdsArr = await mlIDbStorage.getAllFileIdsForUpdate(tx);
const mlFileIds = new Set<number>();
mlFileIdsArr.forEach((mlFileId) => mlFileIds.add(mlFileId));
@@ -169,7 +169,7 @@ class MachineLearningService {
let updated = false;
if (newFileIds.length > 0) {
- addLogLine('newFiles: ', newFileIds.length);
+ addLogLine("newFiles: ", newFileIds.length);
const newFiles = newFileIds.map((fileId) => this.newMlData(fileId));
await mlIDbStorage.putAllFiles(newFiles, tx);
updated = true;
@@ -183,7 +183,7 @@ class MachineLearningService {
}
if (removedFileIds.length > 0) {
- addLogLine('removedFiles: ', removedFileIds.length);
+ addLogLine("removedFiles: ", removedFileIds.length);
await mlIDbStorage.removeAllFiles(removedFileIds, tx);
updated = true;
}
@@ -192,10 +192,10 @@ class MachineLearningService {
if (updated) {
// TODO: should do in same transaction
- await mlIDbStorage.incrementIndexVersion('files');
+ await mlIDbStorage.incrementIndexVersion("files");
}
- addLogLine('syncLocalFiles', Date.now() - startTime, 'ms');
+ addLogLine("syncLocalFiles", Date.now() - startTime, "ms");
}
// TODO: not required if ml data is stored as field inside ente file object
@@ -227,23 +227,23 @@ class MachineLearningService {
const fileIds = await mlIDbStorage.getFileIds(
syncContext.config.batchSize,
syncContext.config.mlVersion,
- MAX_ML_SYNC_ERROR_COUNT
+ MAX_ML_SYNC_ERROR_COUNT,
);
- addLogLine('fileIds: ', JSON.stringify(fileIds));
+ addLogLine("fileIds: ", JSON.stringify(fileIds));
const localFilesMap = await this.getLocalFilesMap(syncContext);
syncContext.outOfSyncFiles = fileIds.map((fileId) =>
- localFilesMap.get(fileId)
+ localFilesMap.get(fileId),
);
- addLogLine('getOutOfSyncFiles', Date.now() - startTime, 'ms');
+ addLogLine("getOutOfSyncFiles", Date.now() - startTime, "ms");
}
// TODO: optimize, use indexdb indexes, move facecrops to cache to reduce io
// remove, already done
private async getUniqueOutOfSyncFilesNoIdx(
syncContext: MLSyncContext,
- files: EnteFile[]
+ files: EnteFile[],
) {
const limit = syncContext.config.batchSize;
const mlVersion = syncContext.config.mlVersion;
@@ -289,57 +289,57 @@ class MachineLearningService {
(outOfSyncfile) => async () => {
await this.syncFileWithErrorHandler(
syncContext,
- outOfSyncfile
+ outOfSyncfile,
);
// TODO: just store file and faces count in syncContext
- }
+ },
);
- syncContext.syncQueue.on('error', () => {
+ syncContext.syncQueue.on("error", () => {
syncContext.syncQueue.clear();
});
await syncContext.syncQueue.addAll(functions);
} catch (error) {
- console.error('Error in sync job: ', error);
+ console.error("Error in sync job: ", error);
syncContext.error = error;
}
await syncContext.syncQueue.onIdle();
- addLogLine('allFaces: ', syncContext.nSyncedFaces);
+ addLogLine("allFaces: ", syncContext.nSyncedFaces);
// TODO: In case syncJob has to use multiple ml workers
// do in same transaction with each file update
// or keep in files store itself
- await mlIDbStorage.incrementIndexVersion('files');
+ await mlIDbStorage.incrementIndexVersion("files");
// await this.disposeMLModels();
}
private async getSyncContext(token: string, userID: number) {
if (!this.syncContext) {
- addLogLine('Creating syncContext');
+ addLogLine("Creating syncContext");
this.syncContext = getMLSyncConfig().then((mlSyncConfig) =>
- MLFactory.getMLSyncContext(token, userID, mlSyncConfig, true)
+ MLFactory.getMLSyncContext(token, userID, mlSyncConfig, true),
);
} else {
- addLogLine('reusing existing syncContext');
+ addLogLine("reusing existing syncContext");
}
return this.syncContext;
}
private async getLocalSyncContext(token: string, userID: number) {
if (!this.localSyncContext) {
- addLogLine('Creating localSyncContext');
+ addLogLine("Creating localSyncContext");
this.localSyncContext = getMLSyncConfig().then((mlSyncConfig) =>
- MLFactory.getMLSyncContext(token, userID, mlSyncConfig, false)
+ MLFactory.getMLSyncContext(token, userID, mlSyncConfig, false),
);
} else {
- addLogLine('reusing existing localSyncContext');
+ addLogLine("reusing existing localSyncContext");
}
return this.localSyncContext;
}
public async closeLocalSyncContext() {
if (this.localSyncContext) {
- addLogLine('Closing localSyncContext');
+ addLogLine("Closing localSyncContext");
const syncContext = await this.localSyncContext;
await syncContext.dispose();
this.localSyncContext = undefined;
@@ -351,7 +351,7 @@ class MachineLearningService {
userID: number,
enteFile: EnteFile,
localFile?: globalThis.File,
- textDetectionTimeoutIndex?: number
+ textDetectionTimeoutIndex?: number,
): Promise<MlFileData | Error> {
const syncContext = await this.getLocalSyncContext(token, userID);
@@ -360,7 +360,7 @@ class MachineLearningService {
syncContext,
enteFile,
localFile,
- textDetectionTimeoutIndex
+ textDetectionTimeoutIndex,
);
if (syncContext.nSyncedFiles >= syncContext.config.batchSize) {
@@ -369,7 +369,7 @@ class MachineLearningService {
// await syncContext.dispose();
return mlFileData;
} catch (e) {
- console.error('Error while syncing local file: ', enteFile.id, e);
+ console.error("Error while syncing local file: ", enteFile.id, e);
return e;
}
}
@@ -378,29 +378,29 @@ class MachineLearningService {
syncContext: MLSyncContext,
enteFile: EnteFile,
localFile?: globalThis.File,
- textDetectionTimeoutIndex?: number
+ textDetectionTimeoutIndex?: number,
): Promise<MlFileData> {
try {
const mlFileData = await this.syncFile(
syncContext,
enteFile,
localFile,
- textDetectionTimeoutIndex
+ textDetectionTimeoutIndex,
);
syncContext.nSyncedFaces += mlFileData.faces?.length || 0;
syncContext.nSyncedFiles += 1;
return mlFileData;
} catch (e) {
- logError(e, 'ML syncFile failed');
+ logError(e, "ML syncFile failed");
let error = e;
console.error(
- 'Error in ml sync, fileId: ',
+ "Error in ml sync, fileId: ",
enteFile.id,
- 'name: ',
+ "name: ",
enteFile.metadata.title,
- error
+ error,
);
- if ('status' in error) {
+ if ("status" in error) {
const parsedMessage = parseUploadErrorCodes(error);
error = parsedMessage;
}
@@ -417,7 +417,7 @@ class MachineLearningService {
await this.persistMLFileSyncError(syncContext, enteFile, error);
syncContext.nSyncedFiles += 1;
} finally {
- addLogLine('TF Memory stats: ', JSON.stringify(tf.memory()));
+ addLogLine("TF Memory stats: ", JSON.stringify(tf.memory()));
}
}
@@ -426,7 +426,7 @@ class MachineLearningService {
enteFile: EnteFile,
localFile?: globalThis.File,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
- textDetectionTimeoutIndex?: number
+ textDetectionTimeoutIndex?: number,
) {
const fileContext: MLSyncFileContext = { enteFile, localFile };
const oldMlFile =
@@ -457,7 +457,7 @@ class MachineLearningService {
this.syncFaceDetections(syncContext, fileContext),
ObjectService.syncFileObjectDetections(
syncContext,
- fileContext
+ fileContext,
),
// TextService.syncFileTextDetections(
// syncContext,
@@ -469,7 +469,7 @@ class MachineLearningService {
newMlFile.lastErrorMessage = undefined;
await this.persistMLFileData(syncContext, newMlFile);
} catch (e) {
- logError(e, 'ml detection failed');
+ logError(e, "ml detection failed");
newMlFile.mlVersion = oldMlFile.mlVersion;
throw e;
} finally {
@@ -494,7 +494,7 @@ class MachineLearningService {
await tf.ready();
- addLogLine('01 TF Memory stats: ', JSON.stringify(tf.memory()));
+ addLogLine("01 TF Memory stats: ", JSON.stringify(tf.memory()));
// await tfjsFaceDetectionService.init();
// // addLogLine('02 TF Memory stats: ',JSON.stringify(tf.memory()));
// await this.faceLandmarkService.init();
@@ -524,7 +524,7 @@ class MachineLearningService {
private async persistMLFileData(
syncContext: MLSyncContext,
- mlFileData: MlFileData
+ mlFileData: MlFileData,
) {
// return mlFilesStore.setItem(mlFileData.fileId.toString(), mlFileData);
mlIDbStorage.putFile(mlFileData);
@@ -533,7 +533,7 @@ class MachineLearningService {
private async persistMLFileSyncError(
syncContext: MLSyncContext,
enteFile: EnteFile,
- e: Error
+ e: Error,
) {
try {
await mlIDbStorage.upsertFileInTx(enteFile.id, (mlFileData) => {
@@ -547,7 +547,7 @@ class MachineLearningService {
});
} catch (e) {
// TODO: logError or stop sync job after most of the requests are failed
- console.error('Error while storing ml sync error', e);
+ console.error("Error while storing ml sync error", e);
}
}
@@ -587,7 +587,7 @@ class MachineLearningService {
private async syncFaceDetections(
syncContext: MLSyncContext,
- fileContext: MLSyncFileContext
+ fileContext: MLSyncFileContext,
) {
const { newMlFile } = fileContext;
const startTime = Date.now();
@@ -603,7 +603,7 @@ class MachineLearningService {
addLogLine(
`face detection time taken ${fileContext.enteFile.id}`,
Date.now() - startTime,
- 'ms'
+ "ms",
);
}
}
diff --git a/apps/photos/src/services/machineLearning/mlSyncJob.ts b/apps/photos/src/services/machineLearning/mlSyncJob.ts
index a538e7682a..d041b976fb 100644
--- a/apps/photos/src/services/machineLearning/mlSyncJob.ts
+++ b/apps/photos/src/services/machineLearning/mlSyncJob.ts
@@ -1,6 +1,6 @@
-import { SimpleJob } from 'utils/common/job';
-import { MLSyncResult } from 'types/machineLearning';
-import { JobResult } from 'types/common/job';
+import { JobResult } from "types/common/job";
+import { MLSyncResult } from "types/machineLearning";
+import { SimpleJob } from "utils/common/job";
export interface MLSyncJobResult extends JobResult {
mlSyncResult: MLSyncResult;
diff --git a/apps/photos/src/services/machineLearning/mlWorkManager.ts b/apps/photos/src/services/machineLearning/mlWorkManager.ts
index a01b28b147..41d7b346cf 100644
--- a/apps/photos/src/services/machineLearning/mlWorkManager.ts
+++ b/apps/photos/src/services/machineLearning/mlWorkManager.ts
@@ -1,18 +1,18 @@
-import debounce from 'debounce';
-import PQueue from 'p-queue';
-import { eventBus, Events } from '@ente/shared/events';
-import { EnteFile } from 'types/file';
-import { FILE_TYPE } from 'constants/file';
-import { getToken, getUserID } from '@ente/shared/storage/localStorage/helpers';
-import { logQueueStats } from 'utils/machineLearning';
-import { getMLSyncJobConfig } from 'utils/machineLearning/config';
-import { logError } from '@ente/shared/sentry';
-import mlIDbStorage from 'utils/storage/mlIDbStorage';
-import { MLSyncJobResult, MLSyncJob } from './mlSyncJob';
-import { ComlinkWorker } from '@ente/shared/worker/comlinkWorker';
-import { DedicatedMLWorker } from 'worker/ml.worker';
-import { getDedicatedMLWorker } from 'utils/comlink/ComlinkMLWorker';
-import { addLogLine } from '@ente/shared/logging';
+import { eventBus, Events } from "@ente/shared/events";
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import { getToken, getUserID } from "@ente/shared/storage/localStorage/helpers";
+import { ComlinkWorker } from "@ente/shared/worker/comlinkWorker";
+import { FILE_TYPE } from "constants/file";
+import debounce from "debounce";
+import PQueue from "p-queue";
+import { EnteFile } from "types/file";
+import { getDedicatedMLWorker } from "utils/comlink/ComlinkMLWorker";
+import { logQueueStats } from "utils/machineLearning";
+import { getMLSyncJobConfig } from "utils/machineLearning/config";
+import mlIDbStorage from "utils/storage/mlIDbStorage";
+import { DedicatedMLWorker } from "worker/ml.worker";
+import { MLSyncJob, MLSyncJobResult } from "./mlSyncJob";
const LIVE_SYNC_IDLE_DEBOUNCE_SEC = 30;
const LIVE_SYNC_QUEUE_TIMEOUT_SEC = 300;
@@ -41,36 +41,36 @@ class MLWorkManager {
eventBus.on(Events.LOGOUT, this.logoutHandler.bind(this), this);
this.debouncedLiveSyncIdle = debounce(
() => this.onLiveSyncIdle(),
- LIVE_SYNC_IDLE_DEBOUNCE_SEC * 1000
+ LIVE_SYNC_IDLE_DEBOUNCE_SEC * 1000,
);
this.debouncedFilesUpdated = debounce(
() => this.mlSearchEnabled && this.localFilesUpdatedHandler(),
- LOCAL_FILES_UPDATED_DEBOUNCE_SEC * 1000
+ LOCAL_FILES_UPDATED_DEBOUNCE_SEC * 1000,
);
}
public async setMlSearchEnabled(enabled: boolean) {
if (!this.mlSearchEnabled && enabled) {
- addLogLine('Enabling MLWorkManager');
+ addLogLine("Enabling MLWorkManager");
this.mlSearchEnabled = true;
- logQueueStats(this.liveSyncQueue, 'livesync');
- this.liveSyncQueue.on('idle', this.debouncedLiveSyncIdle, this);
+ logQueueStats(this.liveSyncQueue, "livesync");
+ this.liveSyncQueue.on("idle", this.debouncedLiveSyncIdle, this);
eventBus.on(
Events.FILE_UPLOADED,
this.fileUploadedHandler.bind(this),
- this
+ this,
);
eventBus.on(
Events.LOCAL_FILES_UPDATED,
this.debouncedFilesUpdated,
- this
+ this,
);
await this.startSyncJob();
} else if (this.mlSearchEnabled && !enabled) {
- addLogLine('Disabling MLWorkManager');
+ addLogLine("Disabling MLWorkManager");
this.mlSearchEnabled = false;
this.liveSyncQueue.removeAllListeners();
@@ -78,12 +78,12 @@ class MLWorkManager {
eventBus.removeListener(
Events.FILE_UPLOADED,
this.fileUploadedHandler.bind(this),
- this
+ this,
);
eventBus.removeListener(
Events.LOCAL_FILES_UPDATED,
this.debouncedFilesUpdated,
- this
+ this,
);
this.stopSyncJob();
@@ -92,23 +92,23 @@ class MLWorkManager {
// Handlers
private async appStartHandler() {
- addLogLine('appStartHandler');
+ addLogLine("appStartHandler");
try {
this.startSyncJob();
} catch (e) {
- logError(e, 'Failed in ML appStart Handler');
+ logError(e, "Failed in ML appStart Handler");
}
}
private async logoutHandler() {
- addLogLine('logoutHandler');
+ addLogLine("logoutHandler");
try {
this.stopSyncJob();
this.mlSyncJob = undefined;
await this.terminateLiveSyncWorker();
await mlIDbStorage.clearMLDB();
} catch (e) {
- logError(e, 'Failed in ML logout Handler');
+ logError(e, "Failed in ML logout Handler");
}
}
@@ -119,29 +119,29 @@ class MLWorkManager {
if (!this.mlSearchEnabled) {
return;
}
- addLogLine('fileUploadedHandler: ', arg.enteFile.id);
+ addLogLine("fileUploadedHandler: ", arg.enteFile.id);
if (arg.enteFile.metadata.fileType !== FILE_TYPE.IMAGE) {
- addLogLine('Skipping non image file for local file processing');
+ addLogLine("Skipping non image file for local file processing");
return;
}
try {
await this.syncLocalFile(arg.enteFile, arg.localFile);
} catch (error) {
- console.error('Error in syncLocalFile: ', arg.enteFile.id, error);
+ console.error("Error in syncLocalFile: ", arg.enteFile.id, error);
this.liveSyncQueue.clear();
// logError(e, 'Failed in ML fileUploaded Handler');
}
}
private async localFilesUpdatedHandler() {
- addLogLine('Local files updated');
+ addLogLine("Local files updated");
this.startSyncJob();
}
// Live Sync
private async getLiveSyncWorker() {
if (!this.liveSyncWorker) {
- this.liveSyncWorker = getDedicatedMLWorker('ml-sync-live');
+ this.liveSyncWorker = getDedicatedMLWorker("ml-sync-live");
}
return await this.liveSyncWorker.remote;
@@ -156,8 +156,8 @@ class MLWorkManager {
await liveSyncWorker.closeLocalSyncContext();
} catch (error) {
console.error(
- 'Error while closing local sync context, terminating worker',
- error
+ "Error while closing local sync context, terminating worker",
+ error,
);
}
this.liveSyncWorker?.terminate();
@@ -165,7 +165,7 @@ class MLWorkManager {
}
private async onLiveSyncIdle() {
- addLogLine('Live sync idle');
+ addLogLine("Live sync idle");
await this.terminateLiveSyncWorker();
this.mlSearchEnabled && this.startSyncJob();
}
@@ -180,17 +180,17 @@ class MLWorkManager {
});
// @ts-expect-error "TODO: Fix ML related type errors"
- if ('message' in result) {
+ if ("message" in result) {
// TODO: redirect/refresh to gallery in case of session_expired
// may not be required as uploader should anyways take care of this
- console.error('Error while syncing local file: ', result);
+ console.error("Error while syncing local file: ", result);
}
}
// Sync Job
private async getSyncJobWorker() {
if (!this.syncJobWorker) {
- this.syncJobWorker = getDedicatedMLWorker('ml-sync-job');
+ this.syncJobWorker = getDedicatedMLWorker("ml-sync-job");
}
return await this.syncJobWorker.remote;
@@ -207,7 +207,7 @@ class MLWorkManager {
// currently worker chunk itself is not loaded when network is not there
if (!navigator.onLine) {
addLogLine(
- 'Skipping ml-sync job run as not connected to internet.'
+ "Skipping ml-sync job run as not connected to internet.",
);
return {
shouldBackoff: true,
@@ -227,46 +227,46 @@ class MLWorkManager {
!!mlSyncResult.error || mlSyncResult.nOutOfSyncFiles < 1,
mlSyncResult,
};
- addLogLine('ML Sync Job result: ', JSON.stringify(jobResult));
+ addLogLine("ML Sync Job result: ", JSON.stringify(jobResult));
// TODO: redirect/refresh to gallery in case of session_expired, stop ml sync job
return jobResult;
} catch (e) {
- logError(e, 'Failed to run MLSync Job');
+ logError(e, "Failed to run MLSync Job");
}
}
public async startSyncJob() {
try {
- addLogLine('MLWorkManager.startSyncJob');
+ addLogLine("MLWorkManager.startSyncJob");
if (!this.mlSearchEnabled) {
- addLogLine('ML Search disabled, not starting ml sync job');
+ addLogLine("ML Search disabled, not starting ml sync job");
return;
}
if (!getToken()) {
- addLogLine('User not logged in, not starting ml sync job');
+ addLogLine("User not logged in, not starting ml sync job");
return;
}
const mlSyncJobConfig = await getMLSyncJobConfig();
if (!this.mlSyncJob) {
this.mlSyncJob = new MLSyncJob(mlSyncJobConfig, () =>
- this.runMLSyncJob()
+ this.runMLSyncJob(),
);
}
this.mlSyncJob.start();
} catch (e) {
- logError(e, 'Failed to start MLSync Job');
+ logError(e, "Failed to start MLSync Job");
}
}
public stopSyncJob(terminateWorker: boolean = true) {
try {
- addLogLine('MLWorkManager.stopSyncJob');
+ addLogLine("MLWorkManager.stopSyncJob");
this.mlSyncJob?.stop();
terminateWorker && this.terminateSyncJobWorker();
} catch (e) {
- logError(e, 'Failed to stop MLSync Job');
+ logError(e, "Failed to stop MLSync Job");
}
}
}
diff --git a/apps/photos/src/services/machineLearning/mobileFaceNetEmbeddingService.ts b/apps/photos/src/services/machineLearning/mobileFaceNetEmbeddingService.ts
index 439c403418..52eabbd8ea 100644
--- a/apps/photos/src/services/machineLearning/mobileFaceNetEmbeddingService.ts
+++ b/apps/photos/src/services/machineLearning/mobileFaceNetEmbeddingService.ts
@@ -1,15 +1,15 @@
-import * as tf from '@tensorflow/tfjs-core';
-import { TFLiteModel } from '@tensorflow/tfjs-tflite';
-import { MOBILEFACENET_FACE_SIZE } from 'constants/mlConfig';
-import PQueue from 'p-queue';
+import { addLogLine } from "@ente/shared/logging";
+import * as tf from "@tensorflow/tfjs-core";
+import { TFLiteModel } from "@tensorflow/tfjs-tflite";
+import { MOBILEFACENET_FACE_SIZE } from "constants/mlConfig";
+import PQueue from "p-queue";
import {
FaceEmbedding,
FaceEmbeddingMethod,
FaceEmbeddingService,
Versioned,
-} from 'types/machineLearning';
-import { addLogLine } from '@ente/shared/logging';
-import { imageBitmapsToTensor4D } from 'utils/machineLearning';
+} from "types/machineLearning";
+import { imageBitmapsToTensor4D } from "utils/machineLearning";
class MobileFaceNetEmbeddingService implements FaceEmbeddingService {
public method: Versioned<FaceEmbeddingMethod>;
@@ -20,7 +20,7 @@ class MobileFaceNetEmbeddingService implements FaceEmbeddingService {
public constructor(faceSize: number = MOBILEFACENET_FACE_SIZE) {
this.method = {
- value: 'MobileFaceNet',
+ value: "MobileFaceNet",
version: 2,
};
this.faceSize = faceSize;
@@ -30,14 +30,14 @@ class MobileFaceNetEmbeddingService implements FaceEmbeddingService {
private async init() {
// TODO: can also create new instance per new syncContext
- const tflite = await import('@tensorflow/tfjs-tflite');
- tflite.setWasmPath('/js/tflite/');
+ const tflite = await import("@tensorflow/tfjs-tflite");
+ tflite.setWasmPath("/js/tflite/");
this.mobileFaceNetModel = tflite.loadTFLiteModel(
- '/models/mobilefacenet/mobilefacenet.tflite'
+ "/models/mobilefacenet/mobilefacenet.tflite",
);
- addLogLine('loaded mobileFaceNetModel: ', tf.getBackend());
+ addLogLine("loaded mobileFaceNetModel: ", tf.getBackend());
}
private async getMobileFaceNetModel() {
@@ -50,7 +50,7 @@ class MobileFaceNetEmbeddingService implements FaceEmbeddingService {
public getFaceEmbeddingTF(
faceTensor: tf.Tensor4D,
- mobileFaceNetModel: TFLiteModel
+ mobileFaceNetModel: TFLiteModel,
): tf.Tensor2D {
return tf.tidy(() => {
const normalizedFace = tf.sub(tf.div(faceTensor, 127.5), 1.0);
@@ -60,7 +60,7 @@ class MobileFaceNetEmbeddingService implements FaceEmbeddingService {
// Do not use this, use getFaceEmbedding which calls this through serialqueue
private async getFaceEmbeddingNoQueue(
- faceImage: ImageBitmap
+ faceImage: ImageBitmap,
): Promise<FaceEmbedding> {
const mobileFaceNetModel = await this.getMobileFaceNetModel();
@@ -68,7 +68,7 @@ class MobileFaceNetEmbeddingService implements FaceEmbeddingService {
const faceTensor = imageBitmapsToTensor4D([faceImage]);
const embeddingsTensor = this.getFaceEmbeddingTF(
faceTensor,
- mobileFaceNetModel
+ mobileFaceNetModel,
);
return tf.squeeze(embeddingsTensor, [0]);
});
@@ -82,19 +82,19 @@ class MobileFaceNetEmbeddingService implements FaceEmbeddingService {
// TODO: TFLiteModel seems to not work concurrenly,
// remove serialqueue if that is not the case
private async getFaceEmbedding(
- faceImage: ImageBitmap
+ faceImage: ImageBitmap,
): Promise<FaceEmbedding> {
// @ts-expect-error "TODO: Fix ML related type errors"
return this.serialQueue.add(() =>
- this.getFaceEmbeddingNoQueue(faceImage)
+ this.getFaceEmbeddingNoQueue(faceImage),
);
}
public async getFaceEmbeddings(
- faceImages: Array<ImageBitmap>
+ faceImages: Array<ImageBitmap>,
): Promise<Array<FaceEmbedding>> {
return Promise.all(
- faceImages.map((faceImage) => this.getFaceEmbedding(faceImage))
+ faceImages.map((faceImage) => this.getFaceEmbedding(faceImage)),
);
}
diff --git a/apps/photos/src/services/machineLearning/objectService.ts b/apps/photos/src/services/machineLearning/objectService.ts
index 263a1b7901..c9eee28877 100644
--- a/apps/photos/src/services/machineLearning/objectService.ts
+++ b/apps/photos/src/services/machineLearning/objectService.ts
@@ -1,33 +1,33 @@
+import { addLogLine } from "@ente/shared/logging";
import {
+ DetectedObject,
MLSyncContext,
MLSyncFileContext,
- DetectedObject,
Thing,
-} from 'types/machineLearning';
-import { addLogLine } from '@ente/shared/logging';
+} from "types/machineLearning";
import {
- isDifferentOrOld,
- getObjectId,
getAllObjectsFromMap,
-} from 'utils/machineLearning';
-import mlIDbStorage from 'utils/storage/mlIDbStorage';
-import ReaderService from './readerService';
+ getObjectId,
+ isDifferentOrOld,
+} from "utils/machineLearning";
+import mlIDbStorage from "utils/storage/mlIDbStorage";
+import ReaderService from "./readerService";
class ObjectService {
async syncFileObjectDetections(
syncContext: MLSyncContext,
- fileContext: MLSyncFileContext
+ fileContext: MLSyncFileContext,
) {
const startTime = Date.now();
const { oldMlFile, newMlFile } = fileContext;
if (
!isDifferentOrOld(
oldMlFile?.objectDetectionMethod,
- syncContext.objectDetectionService.method
+ syncContext.objectDetectionService.method,
) &&
!isDifferentOrOld(
oldMlFile?.sceneDetectionMethod,
- syncContext.sceneDetectionService.method
+ syncContext.sceneDetectionService.method,
) &&
oldMlFile?.imageSource === syncContext.config.imageSource
) {
@@ -47,19 +47,19 @@ class ObjectService {
fileContext.newDetection = true;
const imageBitmap = await ReaderService.getImageBitmap(
syncContext,
- fileContext
+ fileContext,
);
const objectDetections =
await syncContext.objectDetectionService.detectObjects(
imageBitmap,
syncContext.config.objectDetection.maxNumBoxes,
- syncContext.config.objectDetection.minScore
+ syncContext.config.objectDetection.minScore,
);
objectDetections.push(
...(await syncContext.sceneDetectionService.detectScenes(
imageBitmap,
- syncContext.config.sceneDetection.minScore
- ))
+ syncContext.config.sceneDetection.minScore,
+ )),
);
// addLogLine('3 TF Memory stats: ',JSON.stringify(tf.memory()));
// TODO: reenable faces filtering based on width
@@ -80,10 +80,10 @@ class ObjectService {
addLogLine(
`object detection time taken ${fileContext.enteFile.id}`,
Date.now() - startTime,
- 'ms'
+ "ms",
);
- addLogLine('[MLService] Detected Objects: ', newMlFile.objects?.length);
+ addLogLine("[MLService] Detected Objects: ", newMlFile.objects?.length);
}
async getAllSyncedObjectsMap(syncContext: MLSyncContext) {
@@ -114,11 +114,11 @@ class ObjectService {
}
async syncThingsIndex(syncContext: MLSyncContext) {
- const filesVersion = await mlIDbStorage.getIndexVersion('files');
- addLogLine('things', await mlIDbStorage.getIndexVersion('things'));
- if (filesVersion <= (await mlIDbStorage.getIndexVersion('things'))) {
+ const filesVersion = await mlIDbStorage.getIndexVersion("files");
+ addLogLine("things", await mlIDbStorage.getIndexVersion("things"));
+ if (filesVersion <= (await mlIDbStorage.getIndexVersion("things"))) {
addLogLine(
- '[MLService] Skipping people index as already synced to latest version'
+ "[MLService] Skipping people index as already synced to latest version",
);
return;
}
@@ -135,7 +135,7 @@ class ObjectService {
await mlIDbStorage.putThing(thing);
}
- await mlIDbStorage.setIndexVersion('things', filesVersion);
+ await mlIDbStorage.setIndexVersion("things", filesVersion);
}
async getAllThings() {
diff --git a/apps/photos/src/services/machineLearning/peopleService.ts b/apps/photos/src/services/machineLearning/peopleService.ts
index e89e51e298..d5a4708075 100644
--- a/apps/photos/src/services/machineLearning/peopleService.ts
+++ b/apps/photos/src/services/machineLearning/peopleService.ts
@@ -1,27 +1,27 @@
-import { Face, MLSyncContext, Person } from 'types/machineLearning';
-import { addLogLine } from '@ente/shared/logging';
+import { addLogLine } from "@ente/shared/logging";
+import { Face, MLSyncContext, Person } from "types/machineLearning";
import {
- isDifferentOrOld,
+ findFirstIfSorted,
getAllFacesFromMap,
getLocalFile,
- findFirstIfSorted,
getOriginalImageBitmap,
-} from 'utils/machineLearning';
-import mlIDbStorage from 'utils/storage/mlIDbStorage';
-import FaceService from './faceService';
+ isDifferentOrOld,
+} from "utils/machineLearning";
+import mlIDbStorage from "utils/storage/mlIDbStorage";
+import FaceService from "./faceService";
class PeopleService {
async syncPeopleIndex(syncContext: MLSyncContext) {
- const filesVersion = await mlIDbStorage.getIndexVersion('files');
+ const filesVersion = await mlIDbStorage.getIndexVersion("files");
if (
- filesVersion <= (await mlIDbStorage.getIndexVersion('people')) &&
+ filesVersion <= (await mlIDbStorage.getIndexVersion("people")) &&
!isDifferentOrOld(
syncContext.mlLibraryData?.faceClusteringMethod,
- syncContext.faceClusteringService.method
+ syncContext.faceClusteringService.method,
)
) {
addLogLine(
- '[MLService] Skipping people index as already synced to latest version'
+ "[MLService] Skipping people index as already synced to latest version",
);
return;
}
@@ -35,13 +35,13 @@ class PeopleService {
await FaceService.runFaceClustering(syncContext, allFaces);
await this.syncPeopleFromClusters(syncContext, allFacesMap, allFaces);
- await mlIDbStorage.setIndexVersion('people', filesVersion);
+ await mlIDbStorage.setIndexVersion("people", filesVersion);
}
private async syncPeopleFromClusters(
syncContext: MLSyncContext,
allFacesMap: Map<number, Array<Face>>,
- allFaces: Array<Face>
+ allFaces: Array<Face>,
) {
const clusters =
syncContext.mlLibraryData.faceClusteringResults?.clusters;
@@ -59,7 +59,7 @@ class PeopleService {
// TODO: take default display face from last leaves of hdbscan clusters
const personFace = findFirstIfSorted(
faces,
- (a, b) => b.detection.probability - a.detection.probability
+ (a, b) => b.detection.probability - a.detection.probability,
);
if (personFace && !personFace.crop?.imageUrl) {
@@ -68,7 +68,7 @@ class PeopleService {
await FaceService.saveFaceCrop(
imageBitmap,
personFace,
- syncContext
+ syncContext,
);
}
diff --git a/apps/photos/src/services/machineLearning/readerService.ts b/apps/photos/src/services/machineLearning/readerService.ts
index 7b6534bc0c..d141cf057e 100644
--- a/apps/photos/src/services/machineLearning/readerService.ts
+++ b/apps/photos/src/services/machineLearning/readerService.ts
@@ -1,16 +1,16 @@
-import { FILE_TYPE } from 'constants/file';
-import { MLSyncContext, MLSyncFileContext } from 'types/machineLearning';
+import { logError } from "@ente/shared/sentry";
+import { FILE_TYPE } from "constants/file";
+import { MLSyncContext, MLSyncFileContext } from "types/machineLearning";
import {
getLocalFileImageBitmap,
getOriginalImageBitmap,
getThumbnailImageBitmap,
-} from 'utils/machineLearning';
-import { logError } from '@ente/shared/sentry';
+} from "utils/machineLearning";
class ReaderService {
async getImageBitmap(
syncContext: MLSyncContext,
- fileContext: MLSyncFileContext
+ fileContext: MLSyncFileContext,
) {
try {
if (fileContext.imageBitmap) {
@@ -22,25 +22,25 @@ class ReaderService {
fileContext.enteFile.metadata.fileType !== FILE_TYPE.IMAGE
) {
throw new Error(
- 'Local file of only image type is supported'
+ "Local file of only image type is supported",
);
}
fileContext.imageBitmap = await getLocalFileImageBitmap(
fileContext.enteFile,
- fileContext.localFile
+ fileContext.localFile,
);
} else if (
- syncContext.config.imageSource === 'Original' &&
+ syncContext.config.imageSource === "Original" &&
[FILE_TYPE.IMAGE, FILE_TYPE.LIVE_PHOTO].includes(
- fileContext.enteFile.metadata.fileType
+ fileContext.enteFile.metadata.fileType,
)
) {
fileContext.imageBitmap = await getOriginalImageBitmap(
- fileContext.enteFile
+ fileContext.enteFile,
);
} else {
fileContext.imageBitmap = await getThumbnailImageBitmap(
- fileContext.enteFile
+ fileContext.enteFile,
);
}
@@ -51,7 +51,7 @@ class ReaderService {
return fileContext.imageBitmap;
} catch (e) {
- logError(e, 'failed to create image bitmap');
+ logError(e, "failed to create image bitmap");
throw e;
}
}
diff --git a/apps/photos/src/services/machineLearning/ssdMobileNetV2Service.ts b/apps/photos/src/services/machineLearning/ssdMobileNetV2Service.ts
index 83bb327a16..4adde77071 100644
--- a/apps/photos/src/services/machineLearning/ssdMobileNetV2Service.ts
+++ b/apps/photos/src/services/machineLearning/ssdMobileNetV2Service.ts
@@ -1,15 +1,15 @@
-import * as tf from '@tensorflow/tfjs-core';
+import * as tf from "@tensorflow/tfjs-core";
import {
ObjectDetection,
ObjectDetectionMethod,
ObjectDetectionService,
Versioned,
-} from 'types/machineLearning';
+} from "types/machineLearning";
-import * as SSDMobileNet from '@tensorflow-models/coco-ssd';
-import { resizeToSquare } from 'utils/image';
-import { OBJECT_DETECTION_IMAGE_SIZE } from 'constants/mlConfig';
-import { addLogLine } from '@ente/shared/logging';
+import { addLogLine } from "@ente/shared/logging";
+import * as SSDMobileNet from "@tensorflow-models/coco-ssd";
+import { OBJECT_DETECTION_IMAGE_SIZE } from "constants/mlConfig";
+import { resizeToSquare } from "utils/image";
class SSDMobileNetV2 implements ObjectDetectionService {
private ssdMobileNetV2Model: SSDMobileNet.ObjectDetection;
@@ -18,17 +18,17 @@ class SSDMobileNetV2 implements ObjectDetectionService {
public constructor() {
this.method = {
- value: 'SSDMobileNetV2',
+ value: "SSDMobileNetV2",
version: 1,
};
}
private async init() {
this.ssdMobileNetV2Model = await SSDMobileNet.load({
- base: 'mobilenet_v2',
- modelUrl: '/models/ssdmobilenet/model.json',
+ base: "mobilenet_v2",
+ modelUrl: "/models/ssdmobilenet/model.json",
});
- addLogLine('loaded ssdMobileNetV2Model', tf.getBackend());
+ addLogLine("loaded ssdMobileNetV2Model", tf.getBackend());
}
private async getSSDMobileNetV2Model() {
@@ -42,7 +42,7 @@ class SSDMobileNetV2 implements ObjectDetectionService {
public async detectObjects(
image: ImageBitmap,
maxNumberBoxes: number,
- minScore: number
+ minScore: number,
): Promise<ObjectDetection[]> {
const ssdMobileNetV2Model = await this.getSSDMobileNetV2Model();
const resized = resizeToSquare(image, OBJECT_DETECTION_IMAGE_SIZE);
@@ -50,7 +50,7 @@ class SSDMobileNetV2 implements ObjectDetectionService {
const detections = await ssdMobileNetV2Model.detect(
tfImage,
maxNumberBoxes,
- minScore
+ minScore,
);
tfImage.dispose();
return detections;
diff --git a/apps/photos/src/services/migrateThumbnailService.ts b/apps/photos/src/services/migrateThumbnailService.ts
index b716fd1965..ad83f4e4bc 100644
--- a/apps/photos/src/services/migrateThumbnailService.ts
+++ b/apps/photos/src/services/migrateThumbnailService.ts
@@ -1,19 +1,19 @@
-import downloadManager from 'services/download';
-import { getLocalFiles } from 'services/fileService';
-import { generateThumbnail } from 'services/upload/thumbnailService';
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
-import { logError } from '@ente/shared/sentry';
-import { getEndpoint } from '@ente/shared/network/api';
-import HTTPService from '@ente/shared/network/HTTPService';
-import uploadHttpClient from 'services/upload/uploadHttpClient';
-import { SetProgressTracker } from 'components/FixLargeThumbnail';
-import { getFileType } from 'services/typeDetectionService';
-import { getLocalTrashedFiles } from './trashService';
-import { UploadURL } from 'types/upload';
-import { S3FileAttributes } from 'types/file';
-import { Remote } from 'comlink';
-import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { DedicatedCryptoWorker } from "@ente/shared/crypto/internal/crypto.worker";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getEndpoint } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
+import { Remote } from "comlink";
+import { SetProgressTracker } from "components/FixLargeThumbnail";
+import downloadManager from "services/download";
+import { getLocalFiles } from "services/fileService";
+import { getFileType } from "services/typeDetectionService";
+import { generateThumbnail } from "services/upload/thumbnailService";
+import uploadHttpClient from "services/upload/uploadHttpClient";
+import { S3FileAttributes } from "types/file";
+import { UploadURL } from "types/upload";
+import { getLocalTrashedFiles } from "./trashService";
const ENDPOINT = getEndpoint();
const REPLACE_THUMBNAIL_THRESHOLD = 500 * 1024; // 500KB
@@ -29,18 +29,18 @@ export async function getLargeThumbnailFiles() {
threshold: REPLACE_THUMBNAIL_THRESHOLD,
},
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
return resp.data.largeThumbnailFiles as number[];
} catch (e) {
- logError(e, 'failed to get large thumbnail files');
+ logError(e, "failed to get large thumbnail files");
throw e;
}
}
export async function replaceThumbnail(
setProgressTracker: SetProgressTracker,
- largeThumbnailFileIDs: Set<number>
+ largeThumbnailFileIDs: Set<number>,
) {
let completedWithError = false;
try {
@@ -48,10 +48,10 @@ export async function replaceThumbnail(
const files = await getLocalFiles();
const trashFiles = await getLocalTrashedFiles();
const largeThumbnailFiles = [...files, ...trashFiles].filter((file) =>
- largeThumbnailFileIDs.has(file.id)
+ largeThumbnailFileIDs.has(file.id),
);
if (largeThumbnailFileIDs.size !== largeThumbnailFiles.length) {
- logError(Error(), 'all large thumbnail files not found locally');
+ logError(Error(), "all large thumbnail files not found locally");
}
if (largeThumbnailFiles.length === 0) {
return completedWithError;
@@ -60,7 +60,7 @@ export async function replaceThumbnail(
const uploadURLs: UploadURL[] = [];
await uploadHttpClient.fetchUploadURLs(
largeThumbnailFiles.length,
- uploadURLs
+ uploadURLs,
);
for (const [idx, file] of largeThumbnailFiles.entries()) {
try {
@@ -72,27 +72,27 @@ export async function replaceThumbnail(
await downloadManager.getThumbnail(file);
const dummyImageFile = new File(
[originalThumbnail],
- file.metadata.title
+ file.metadata.title,
);
const fileTypeInfo = await getFileType(dummyImageFile);
const { thumbnail: newThumbnail } = await generateThumbnail(
dummyImageFile,
- fileTypeInfo
+ fileTypeInfo,
);
const newUploadedThumbnail = await uploadThumbnail(
cryptoWorker,
file.key,
newThumbnail,
- uploadURLs.pop()
+ uploadURLs.pop(),
);
await updateThumbnail(file.id, newUploadedThumbnail);
} catch (e) {
- logError(e, 'failed to replace a thumbnail');
+ logError(e, "failed to replace a thumbnail");
completedWithError = true;
}
}
} catch (e) {
- logError(e, 'replace Thumbnail function failed');
+ logError(e, "replace Thumbnail function failed");
completedWithError = true;
}
return completedWithError;
@@ -102,16 +102,16 @@ export async function uploadThumbnail(
worker: Remote<DedicatedCryptoWorker>,
fileKey: string,
updatedThumbnail: Uint8Array,
- uploadURL: UploadURL
+ uploadURL: UploadURL,
): Promise<S3FileAttributes> {
const { file: encryptedThumbnail } = await worker.encryptThumbnail(
updatedThumbnail,
- fileKey
+ fileKey,
);
const thumbnailObjectKey = await uploadHttpClient.putFile(
uploadURL,
encryptedThumbnail.encryptedData,
- () => {}
+ () => {},
);
return {
@@ -122,7 +122,7 @@ export async function uploadThumbnail(
export async function updateThumbnail(
fileID: number,
- newThumbnail: S3FileAttributes
+ newThumbnail: S3FileAttributes,
) {
try {
const token = getToken();
@@ -137,11 +137,11 @@ export async function updateThumbnail(
},
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
} catch (e) {
- logError(e, 'failed to update thumbnail');
+ logError(e, "failed to update thumbnail");
throw e;
}
}
diff --git a/apps/photos/src/services/publicCollectionService.ts b/apps/photos/src/services/publicCollectionService.ts
index a5377a4e22..353281f662 100644
--- a/apps/photos/src/services/publicCollectionService.ts
+++ b/apps/photos/src/services/publicCollectionService.ts
@@ -1,23 +1,23 @@
-import { getEndpoint } from '@ente/shared/network/api';
-import localForage from '@ente/shared/storage/localForage';
-import { Collection, CollectionPublicMagicMetadata } from 'types/collection';
-import HTTPService from '@ente/shared/network/HTTPService';
-import { logError } from '@ente/shared/sentry';
-import { decryptFile, mergeMetadata, sortFiles } from 'utils/file';
-import { EncryptedEnteFile, EnteFile } from 'types/file';
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { CustomError, parseSharingErrorCodes } from "@ente/shared/error";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getEndpoint } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import localForage from "@ente/shared/storage/localForage";
+import { REPORT_REASON } from "constants/publicCollection";
+import { Collection, CollectionPublicMagicMetadata } from "types/collection";
+import { EncryptedEnteFile, EnteFile } from "types/file";
import {
AbuseReportDetails,
AbuseReportRequest,
LocalSavedPublicCollectionFiles,
-} from 'types/publicCollection';
-import { REPORT_REASON } from 'constants/publicCollection';
-import { CustomError, parseSharingErrorCodes } from '@ente/shared/error';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
+} from "types/publicCollection";
+import { decryptFile, mergeMetadata, sortFiles } from "utils/file";
const ENDPOINT = getEndpoint();
-const PUBLIC_COLLECTION_FILES_TABLE = 'public-collection-files';
-const PUBLIC_COLLECTIONS_TABLE = 'public-collections';
-const PUBLIC_REFERRAL_CODE = 'public-referral-code';
+const PUBLIC_COLLECTION_FILES_TABLE = "public-collection-files";
+const PUBLIC_COLLECTIONS_TABLE = "public-collections";
+const PUBLIC_REFERRAL_CODE = "public-referral-code";
export const getPublicCollectionUID = (token: string) => `${token}`;
@@ -32,27 +32,27 @@ const getPublicCollectionUploaderNameKey = (collectionUID: string) =>
export const getPublicCollectionUploaderName = async (collectionUID: string) =>
await localForage.getItem<string>(
- getPublicCollectionUploaderNameKey(collectionUID)
+ getPublicCollectionUploaderNameKey(collectionUID),
);
export const savePublicCollectionUploaderName = async (
collectionUID: string,
- uploaderName: string
+ uploaderName: string,
) =>
await localForage.setItem(
getPublicCollectionUploaderNameKey(collectionUID),
- uploaderName
+ uploaderName,
);
export const getLocalPublicFiles = async (collectionUID: string) => {
const localSavedPublicCollectionFiles =
(
(await localForage.getItem<LocalSavedPublicCollectionFiles[]>(
- PUBLIC_COLLECTION_FILES_TABLE
+ PUBLIC_COLLECTION_FILES_TABLE,
)) || []
).find(
(localSavedPublicCollectionFiles) =>
- localSavedPublicCollectionFiles.collectionUID === collectionUID
+ localSavedPublicCollectionFiles.collectionUID === collectionUID,
) ||
({
collectionUID: null,
@@ -62,38 +62,38 @@ export const getLocalPublicFiles = async (collectionUID: string) => {
};
export const savePublicCollectionFiles = async (
collectionUID: string,
- files: EnteFile[]
+ files: EnteFile[],
) => {
const publicCollectionFiles =
(await localForage.getItem<LocalSavedPublicCollectionFiles[]>(
- PUBLIC_COLLECTION_FILES_TABLE
+ PUBLIC_COLLECTION_FILES_TABLE,
)) || [];
await localForage.setItem(
PUBLIC_COLLECTION_FILES_TABLE,
dedupeCollectionFiles([
{ collectionUID, files },
...publicCollectionFiles,
- ])
+ ]),
);
};
export const getLocalPublicCollectionPassword = async (
- collectionUID: string
+ collectionUID: string,
): Promise<string> => {
return (
(await localForage.getItem<string>(
- getPublicCollectionPasswordKey(collectionUID)
- )) || ''
+ getPublicCollectionPasswordKey(collectionUID),
+ )) || ""
);
};
export const savePublicCollectionPassword = async (
collectionUID: string,
- passToken: string
+ passToken: string,
): Promise<string> => {
return await localForage.setItem<string>(
getPublicCollectionPasswordKey(collectionUID),
- passToken
+ passToken,
);
};
@@ -104,7 +104,7 @@ export const getLocalPublicCollection = async (collectionKey: string) => {
const publicCollection =
localCollections.find(
(localSavedPublicCollection) =>
- localSavedPublicCollection.key === collectionKey
+ localSavedPublicCollection.key === collectionKey,
) || null;
return publicCollection;
};
@@ -115,7 +115,7 @@ export const savePublicCollection = async (collection: Collection) => {
[];
await localForage.setItem(
PUBLIC_COLLECTIONS_TABLE,
- dedupeCollections([collection, ...publicCollections])
+ dedupeCollections([collection, ...publicCollections]),
);
};
@@ -143,7 +143,7 @@ const dedupeCollections = (collections: Collection[]) => {
};
const dedupeCollectionFiles = (
- collectionFiles: LocalSavedPublicCollectionFiles[]
+ collectionFiles: LocalSavedPublicCollectionFiles[],
) => {
const keySet = new Set([]);
return collectionFiles.filter(({ collectionUID }) => {
@@ -158,23 +158,23 @@ const dedupeCollectionFiles = (
const getPublicCollectionLastSyncTime = async (collectionUID: string) =>
(await localForage.getItem<number>(
- getPublicCollectionLastSyncTimeKey(collectionUID)
+ getPublicCollectionLastSyncTimeKey(collectionUID),
)) ?? 0;
const savePublicCollectionLastSyncTime = async (
collectionUID: string,
- time: number
+ time: number,
) =>
await localForage.setItem(
getPublicCollectionLastSyncTimeKey(collectionUID),
- time
+ time,
);
export const syncPublicFiles = async (
token: string,
passwordToken: string,
collection: Collection,
- setPublicFiles: (files: EnteFile[]) => void
+ setPublicFiles: (files: EnteFile[]) => void,
) => {
try {
let files: EnteFile[] = [];
@@ -198,7 +198,7 @@ export const syncPublicFiles = async (
collection,
lastSyncTime,
files,
- setPublicFiles
+ setPublicFiles,
);
files = [...files, ...fetchedFiles];
@@ -223,19 +223,19 @@ export const syncPublicFiles = async (
await savePublicCollectionFiles(collectionUID, files);
await savePublicCollectionLastSyncTime(
collectionUID,
- collection.updationTime
+ collection.updationTime,
);
setPublicFiles([...sortFiles(mergeMetadata(files), sortAsc)]);
} catch (e) {
const parsedError = parseSharingErrorCodes(e);
- logError(e, 'failed to sync shared collection files');
+ logError(e, "failed to sync shared collection files");
if (parsedError.message === CustomError.TOKEN_EXPIRED) {
throw e;
}
}
return [...sortFiles(mergeMetadata(files), sortAsc)];
} catch (e) {
- logError(e, 'failed to get local or sync shared collection files');
+ logError(e, "failed to get local or sync shared collection files");
throw e;
}
};
@@ -246,7 +246,7 @@ const getPublicFiles = async (
collection: Collection,
sinceTime: number,
files: EnteFile[],
- setPublicFiles: (files: EnteFile[]) => void
+ setPublicFiles: (files: EnteFile[]) => void,
): Promise<EnteFile[]> => {
try {
let decryptedFiles: EnteFile[] = [];
@@ -263,12 +263,12 @@ const getPublicFiles = async (
sinceTime: time,
},
{
- 'Cache-Control': 'no-cache',
- 'X-Auth-Access-Token': token,
+ "Cache-Control": "no-cache",
+ "X-Auth-Access-Token": token,
...(passwordToken && {
- 'X-Auth-Access-Token-JWT': passwordToken,
+ "X-Auth-Access-Token-JWT": passwordToken,
}),
- }
+ },
);
decryptedFiles = [
...decryptedFiles,
@@ -279,7 +279,7 @@ const getPublicFiles = async (
} else {
return file;
}
- }) as Promise<EnteFile>[]
+ }) as Promise<EnteFile>[],
)),
];
@@ -290,23 +290,23 @@ const getPublicFiles = async (
sortFiles(
mergeMetadata(
[...(files || []), ...decryptedFiles].filter(
- (item) => !item.isDeleted
- )
+ (item) => !item.isDeleted,
+ ),
),
- sortAsc
- )
+ sortAsc,
+ ),
);
} while (resp.data.hasMore);
return decryptedFiles;
} catch (e) {
- logError(e, 'Get public files failed');
+ logError(e, "Get public files failed");
throw e;
}
};
export const getPublicCollection = async (
token: string,
- collectionKey: string
+ collectionKey: string,
): Promise<[Collection, string]> => {
try {
if (!token) {
@@ -315,10 +315,10 @@ export const getPublicCollection = async (
const resp = await HTTPService.get(
`${ENDPOINT}/public-collection/info`,
null,
- { 'Cache-Control': 'no-cache', 'X-Auth-Access-Token': token }
+ { "Cache-Control": "no-cache", "X-Auth-Access-Token": token },
);
const fetchedCollection = resp.data.collection;
- const referralCode = resp.data.referralCode ?? '';
+ const referralCode = resp.data.referralCode ?? "";
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
@@ -327,7 +327,7 @@ export const getPublicCollection = async (
(await cryptoWorker.decryptToUTF8(
fetchedCollection.encryptedName,
fetchedCollection.nameDecryptionNonce,
- collectionKey
+ collectionKey,
)));
let collectionPublicMagicMetadata: CollectionPublicMagicMetadata;
@@ -337,7 +337,7 @@ export const getPublicCollection = async (
data: await cryptoWorker.decryptMetadata(
fetchedCollection.pubMagicMetadata.data,
fetchedCollection.pubMagicMetadata.header,
- collectionKey
+ collectionKey,
),
};
}
@@ -352,26 +352,26 @@ export const getPublicCollection = async (
await saveReferralCode(referralCode);
return [collection, referralCode];
} catch (e) {
- logError(e, 'failed to get public collection');
+ logError(e, "failed to get public collection");
throw e;
}
};
export const verifyPublicCollectionPassword = async (
token: string,
- passwordHash: string
+ passwordHash: string,
): Promise<string> => {
try {
const resp = await HTTPService.post(
`${ENDPOINT}/public-collection/verify-password`,
{ passHash: passwordHash },
null,
- { 'Cache-Control': 'no-cache', 'X-Auth-Access-Token': token }
+ { "Cache-Control": "no-cache", "X-Auth-Access-Token": token },
);
const jwtToken = resp.data.jwtToken;
return jwtToken;
} catch (e) {
- logError(e, 'failed to verify public collection password');
+ logError(e, "failed to verify public collection password");
throw e;
}
};
@@ -380,7 +380,7 @@ export const reportAbuse = async (
token: string,
url: string,
reason: REPORT_REASON,
- details: AbuseReportDetails
+ details: AbuseReportDetails,
) => {
try {
if (!token) {
@@ -392,17 +392,17 @@ export const reportAbuse = async (
`${ENDPOINT}/public-collection/report-abuse`,
abuseReportRequest,
null,
- { 'X-Auth-Access-Token': token }
+ { "X-Auth-Access-Token": token },
);
} catch (e) {
- logError(e, 'failed to post abuse report');
+ logError(e, "failed to post abuse report");
throw e;
}
};
export const removePublicCollectionWithFiles = async (
collectionUID: string,
- collectionKey: string
+ collectionKey: string,
) => {
const publicCollections =
(await localForage.getItem<Collection[]>(PUBLIC_COLLECTIONS_TABLE)) ||
@@ -410,8 +410,8 @@ export const removePublicCollectionWithFiles = async (
await localForage.setItem(
PUBLIC_COLLECTIONS_TABLE,
publicCollections.filter(
- (collection) => collection.key !== collectionKey
- )
+ (collection) => collection.key !== collectionKey,
+ ),
);
await removePublicFiles(collectionUID);
};
@@ -419,17 +419,18 @@ export const removePublicCollectionWithFiles = async (
export const removePublicFiles = async (collectionUID: string) => {
await localForage.removeItem(getPublicCollectionPasswordKey(collectionUID));
await localForage.removeItem(
- getPublicCollectionLastSyncTimeKey(collectionUID)
+ getPublicCollectionLastSyncTimeKey(collectionUID),
);
const publicCollectionFiles =
(await localForage.getItem<LocalSavedPublicCollectionFiles[]>(
- PUBLIC_COLLECTION_FILES_TABLE
+ PUBLIC_COLLECTION_FILES_TABLE,
)) ?? [];
await localForage.setItem(
PUBLIC_COLLECTION_FILES_TABLE,
publicCollectionFiles.filter(
- (collectionFiles) => collectionFiles.collectionUID !== collectionUID
- )
+ (collectionFiles) =>
+ collectionFiles.collectionUID !== collectionUID,
+ ),
);
};
diff --git a/apps/photos/src/services/queueProcessor.ts b/apps/photos/src/services/queueProcessor.ts
index 97332aaee7..8e70c4a7f6 100644
--- a/apps/photos/src/services/queueProcessor.ts
+++ b/apps/photos/src/services/queueProcessor.ts
@@ -1,4 +1,4 @@
-import { CustomError } from '@ente/shared/error';
+import { CustomError } from "@ente/shared/error";
interface RequestQueueItem {
request: (canceller?: RequestCanceller) => Promise<any>;
@@ -28,11 +28,11 @@ export default class QueueProcessor<T> {
constructor(
private maxParallelProcesses: number,
- private processingStrategy = PROCESSING_STRATEGY.FIFO
+ private processingStrategy = PROCESSING_STRATEGY.FIFO,
) {}
public queueUpRequest(
- request: (canceller?: RequestCanceller) => Promise<T>
+ request: (canceller?: RequestCanceller) => Promise<T>,
) {
const isCanceled: CancellationStatus = { status: false };
const canceller: RequestCanceller = {
diff --git a/apps/photos/src/services/readerService.ts b/apps/photos/src/services/readerService.ts
index 4238fdf2a1..344fd9f202 100644
--- a/apps/photos/src/services/readerService.ts
+++ b/apps/photos/src/services/readerService.ts
@@ -1,14 +1,14 @@
-import { ElectronFile } from 'types/upload';
-import { convertBytesToHumanReadable } from '@ente/shared/utils/size';
-import { logError } from '@ente/shared/sentry';
+import { logError } from "@ente/shared/sentry";
+import { convertBytesToHumanReadable } from "@ente/shared/utils/size";
+import { ElectronFile } from "types/upload";
export async function getUint8ArrayView(
- file: Blob | ElectronFile
+ file: Blob | ElectronFile,
): Promise<Uint8Array> {
try {
return new Uint8Array(await file.arrayBuffer());
} catch (e) {
- logError(e, 'reading file blob failed', {
+ logError(e, "reading file blob failed", {
fileSize: convertBytesToHumanReadable(file.size),
});
throw e;
@@ -37,7 +37,7 @@ export function getFileStream(file: File, chunkSize: number) {
export async function getElectronFileStream(
file: ElectronFile,
- chunkSize: number
+ chunkSize: number,
) {
const chunkCount = Math.ceil(file.size / chunkSize);
return {
@@ -61,29 +61,29 @@ async function* fileChunkReaderMaker(file: File, chunkSize: number) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function getUint8ArrayViewOld(
reader: FileReader,
- file: Blob
+ file: Blob,
): Promise<Uint8Array> {
return await new Promise((resolve, reject) => {
reader.onabort = () =>
reject(
Error(
`file reading was aborted, file size= ${convertBytesToHumanReadable(
- file.size
- )}`
- )
+ file.size,
+ )}`,
+ ),
);
reader.onerror = () =>
reject(
Error(
`file reading has failed, file size= ${convertBytesToHumanReadable(
- file.size
- )} , reason= ${reader.error}`
- )
+ file.size,
+ )} , reason= ${reader.error}`,
+ ),
);
reader.onload = () => {
// Do whatever you want with the file contents
const result =
- typeof reader.result === 'string'
+ typeof reader.result === "string"
? new TextEncoder().encode(reader.result)
: new Uint8Array(reader.result);
resolve(result);
diff --git a/apps/photos/src/services/searchService.ts b/apps/photos/src/services/searchService.ts
index 34f2b95419..0b6d3a5fbd 100644
--- a/apps/photos/src/services/searchService.ts
+++ b/apps/photos/src/services/searchService.ts
@@ -1,36 +1,36 @@
-import * as chrono from 'chrono-node';
-import { getAllPeople } from 'utils/machineLearning';
-import { t } from 'i18next';
-
-import mlIDbStorage from 'utils/storage/mlIDbStorage';
-import { getMLSyncConfig } from 'utils/machineLearning/config';
-import { Collection } from 'types/collection';
-import { EnteFile } from 'types/file';
-import { logError } from '@ente/shared/sentry';
+import * as chrono from "chrono-node";
+import { t } from "i18next";
+import { getAllPeople } from "utils/machineLearning";
+
+import { CustomError } from "@ente/shared/error";
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import { FILE_TYPE } from "constants/file";
+import { Collection } from "types/collection";
+import { Model } from "types/embedding";
+import { EntityType, LocationTag, LocationTagData } from "types/entity";
+import { EnteFile } from "types/file";
+import { Person, Thing } from "types/machineLearning";
import {
+ ClipSearchScores,
DateValue,
Search,
SearchOption,
Suggestion,
SuggestionType,
- ClipSearchScores,
-} from 'types/search';
-import ObjectService from './machineLearning/objectService';
-import { getFormattedDate } from 'utils/search';
-import { Person, Thing } from 'types/machineLearning';
-import { getUniqueFiles } from 'utils/file';
-import { getLatestEntities } from './entityService';
-import { LocationTag, LocationTagData, EntityType } from 'types/entity';
-import { addLogLine } from '@ente/shared/logging';
-import { FILE_TYPE } from 'constants/file';
-import { ClipService, computeClipMatchScore } from './clipService';
-import { CustomError } from '@ente/shared/error';
-import { Model } from 'types/embedding';
-import { getLocalEmbeddings } from './embeddingService';
-import locationSearchService, { City } from './locationSearchService';
-import ComlinkSearchWorker from 'utils/comlink/ComlinkSearchWorker';
-
-const DIGITS = new Set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']);
+} from "types/search";
+import ComlinkSearchWorker from "utils/comlink/ComlinkSearchWorker";
+import { getUniqueFiles } from "utils/file";
+import { getMLSyncConfig } from "utils/machineLearning/config";
+import { getFormattedDate } from "utils/search";
+import mlIDbStorage from "utils/storage/mlIDbStorage";
+import { ClipService, computeClipMatchScore } from "./clipService";
+import { getLocalEmbeddings } from "./embeddingService";
+import { getLatestEntities } from "./entityService";
+import locationSearchService, { City } from "./locationSearchService";
+import ObjectService from "./machineLearning/objectService";
+
+const DIGITS = new Set(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]);
const CLIP_SCORE_THRESHOLD = 0.23;
@@ -64,20 +64,20 @@ export const getAutoCompleteSuggestions =
return convertSuggestionsToOptions(suggestions);
} catch (e) {
- logError(e, 'getAutoCompleteSuggestions failed');
+ logError(e, "getAutoCompleteSuggestions failed");
return [];
}
};
async function convertSuggestionsToOptions(
- suggestions: Suggestion[]
+ suggestions: Suggestion[],
): Promise<SearchOption[]> {
const searchWorker = await ComlinkSearchWorker.getInstance();
const previewImageAppendedOptions: SearchOption[] = [];
for (const suggestion of suggestions) {
const searchQuery = convertSuggestionToSearchQuery(suggestion);
const resultFiles = getUniqueFiles(
- await searchWorker.search(searchQuery)
+ await searchWorker.search(searchQuery),
);
if (searchQuery?.clip) {
resultFiles.sort((a, b) => {
@@ -99,49 +99,49 @@ async function convertSuggestionsToOptions(
function getFileTypeSuggestion(searchPhrase: string): Suggestion[] {
return [
{
- label: t('IMAGE'),
+ label: t("IMAGE"),
value: FILE_TYPE.IMAGE,
type: SuggestionType.FILE_TYPE,
},
{
- label: t('VIDEO'),
+ label: t("VIDEO"),
value: FILE_TYPE.VIDEO,
type: SuggestionType.FILE_TYPE,
},
{
- label: t('LIVE_PHOTO'),
+ label: t("LIVE_PHOTO"),
value: FILE_TYPE.LIVE_PHOTO,
type: SuggestionType.FILE_TYPE,
},
].filter((suggestion) =>
- suggestion.label.toLowerCase().includes(searchPhrase)
+ suggestion.label.toLowerCase().includes(searchPhrase),
);
}
function getHolidaySuggestion(searchPhrase: string): Suggestion[] {
return [
{
- label: t('CHRISTMAS'),
+ label: t("CHRISTMAS"),
value: { month: 11, date: 25 },
type: SuggestionType.DATE,
},
{
- label: t('CHRISTMAS_EVE'),
+ label: t("CHRISTMAS_EVE"),
value: { month: 11, date: 24 },
type: SuggestionType.DATE,
},
{
- label: t('NEW_YEAR'),
+ label: t("NEW_YEAR"),
value: { month: 0, date: 1 },
type: SuggestionType.DATE,
},
{
- label: t('NEW_YEAR_EVE'),
+ label: t("NEW_YEAR_EVE"),
value: { month: 11, date: 31 },
type: SuggestionType.DATE,
},
].filter((suggestion) =>
- suggestion.label.toLowerCase().includes(searchPhrase)
+ suggestion.label.toLowerCase().includes(searchPhrase),
);
}
@@ -159,7 +159,7 @@ function getYearSuggestion(searchPhrase: string): Suggestion[] {
];
}
} catch (e) {
- logError(e, 'getYearSuggestion failed');
+ logError(e, "getYearSuggestion failed");
}
}
return [];
@@ -175,7 +175,7 @@ export async function getAllPeopleSuggestion(): Promise<Array<Suggestion>> {
hide: true,
}));
} catch (e) {
- logError(e, 'getAllPeopleSuggestion failed');
+ logError(e, "getAllPeopleSuggestion failed");
return [];
}
}
@@ -187,15 +187,15 @@ export async function getIndexStatusSuggestion(): Promise<Suggestion> {
let label;
if (!indexStatus.localFilesSynced) {
- label = t('INDEXING_SCHEDULED');
+ label = t("INDEXING_SCHEDULED");
} else if (indexStatus.outOfSyncFilesExists) {
- label = t('ANALYZING_PHOTOS', {
+ label = t("ANALYZING_PHOTOS", {
indexStatus,
});
} else if (!indexStatus.peopleIndexSynced) {
- label = t('INDEXING_PEOPLE', { indexStatus });
+ label = t("INDEXING_PEOPLE", { indexStatus });
} else {
- label = t('INDEXING_DONE', { indexStatus });
+ label = t("INDEXING_DONE", { indexStatus });
}
return {
@@ -205,7 +205,7 @@ export async function getIndexStatusSuggestion(): Promise<Suggestion> {
hide: true,
};
} catch (e) {
- logError(e, 'getIndexStatusSuggestion failed');
+ logError(e, "getIndexStatusSuggestion failed");
}
}
@@ -221,7 +221,7 @@ function getDateSuggestion(searchPhrase: string): Suggestion[] {
function getCollectionSuggestion(
searchPhrase: string,
- collections: Collection[]
+ collections: Collection[],
): Suggestion[] {
const collectionResults = searchCollection(searchPhrase, collections);
@@ -231,13 +231,13 @@ function getCollectionSuggestion(
type: SuggestionType.COLLECTION,
value: searchResult.id,
label: searchResult.name,
- }) as Suggestion
+ }) as Suggestion,
);
}
function getFileNameSuggestion(
searchPhrase: string,
- files: EnteFile[]
+ files: EnteFile[],
): Suggestion {
const matchedFiles = searchFilesByName(searchPhrase, files);
return {
@@ -249,7 +249,7 @@ function getFileNameSuggestion(
function getFileCaptionSuggestion(
searchPhrase: string,
- files: EnteFile[]
+ files: EnteFile[],
): Suggestion {
const matchedFiles = searchFilesByCaption(searchPhrase, files);
return {
@@ -267,17 +267,17 @@ async function getLocationSuggestions(searchPhrase: string) {
type: SuggestionType.LOCATION,
value: locationTag.data,
label: locationTag.data.name,
- }) as Suggestion
+ }) as Suggestion,
);
const locationTagNames = new Set(
- locationTagSuggestions.map((result) => result.label)
+ locationTagSuggestions.map((result) => result.label),
);
const citySearchResults =
await locationSearchService.searchCities(searchPhrase);
const nonConflictingCityResult = citySearchResults.filter(
- (city) => !locationTagNames.has(city.city)
+ (city) => !locationTagNames.has(city.city),
);
const citySearchSuggestions = nonConflictingCityResult.map(
@@ -286,7 +286,7 @@ async function getLocationSuggestions(searchPhrase: string) {
type: SuggestionType.CITY,
value: city,
label: city.city,
- }) as Suggestion
+ }) as Suggestion,
);
return [...locationTagSuggestions, ...citySearchSuggestions];
@@ -301,7 +301,7 @@ async function getThingSuggestion(searchPhrase: string): Promise<Suggestion[]> {
type: SuggestionType.THING,
value: searchResult,
label: searchResult.name,
- }) as Suggestion
+ }) as Suggestion,
);
}
@@ -319,7 +319,7 @@ async function getClipSuggestion(searchPhrase: string): Promise<Suggestion> {
};
} catch (e) {
if (!e.message?.includes(CustomError.MODEL_DOWNLOAD_PENDING)) {
- logError(e, 'getClipSuggestion failed');
+ logError(e, "getClipSuggestion failed");
}
return null;
}
@@ -327,16 +327,16 @@ async function getClipSuggestion(searchPhrase: string): Promise<Suggestion> {
function searchCollection(
searchPhrase: string,
- collections: Collection[]
+ collections: Collection[],
): Collection[] {
return collections.filter((collection) =>
- collection.name.toLowerCase().includes(searchPhrase)
+ collection.name.toLowerCase().includes(searchPhrase),
);
}
function searchFilesByName(searchPhrase: string, files: EnteFile[]) {
return files.filter((file) =>
- file.metadata.title.toLowerCase().includes(searchPhrase)
+ file.metadata.title.toLowerCase().includes(searchPhrase),
);
}
@@ -346,7 +346,7 @@ function searchFilesByCaption(searchPhrase: string, files: EnteFile[]) {
file.pubMagicMetadata &&
file.pubMagicMetadata.data.caption
?.toLowerCase()
- .includes(searchPhrase)
+ .includes(searchPhrase),
);
}
@@ -359,7 +359,7 @@ function parseHumanDate(humanDate: string): DateValue[] {
{ date: date.getDate(), month: date.getMonth() },
];
let reverse = false;
- humanDate.split('').forEach((c) => {
+ humanDate.split("").forEach((c) => {
if (DIGITS.has(c)) {
reverse = true;
}
@@ -377,14 +377,14 @@ function parseHumanDate(humanDate: string): DateValue[] {
async function searchLocationTag(searchPhrase: string): Promise<LocationTag[]> {
const locationTags = await getLatestEntities<LocationTagData>(
- EntityType.LOCATION_TAG
+ EntityType.LOCATION_TAG,
);
const matchedLocationTags = locationTags.filter((locationTag) =>
- locationTag.data.name.toLowerCase().includes(searchPhrase)
+ locationTag.data.name.toLowerCase().includes(searchPhrase),
);
if (matchedLocationTags.length > 0) {
addLogLine(
- `Found ${matchedLocationTags.length} location tags for search phrase`
+ `Found ${matchedLocationTags.length} location tags for search phrase`,
);
}
return matchedLocationTags;
@@ -393,7 +393,7 @@ async function searchLocationTag(searchPhrase: string): Promise<LocationTag[]> {
async function searchThing(searchPhrase: string) {
const things = await ObjectService.getAllThings();
return things.filter((thing) =>
- thing.name.toLocaleLowerCase().includes(searchPhrase)
+ thing.name.toLocaleLowerCase().includes(searchPhrase),
);
}
@@ -408,12 +408,12 @@ async function searchClip(searchPhrase: string): Promise<ClipSearchScores> {
imageEmbedding.fileID,
await computeClipMatchScore(
imageEmbedding.embedding,
- textEmbedding
+ textEmbedding,
),
- ]
- )
+ ],
+ ),
)
- ).filter(([, score]) => score >= CLIP_SCORE_THRESHOLD)
+ ).filter(([, score]) => score >= CLIP_SCORE_THRESHOLD),
);
return clipSearchResult;
diff --git a/apps/photos/src/services/trashService.ts b/apps/photos/src/services/trashService.ts
index 84dcc33761..5137bbdd59 100644
--- a/apps/photos/src/services/trashService.ts
+++ b/apps/photos/src/services/trashService.ts
@@ -1,20 +1,20 @@
-import { SetFiles } from 'types/gallery';
-import { Collection } from 'types/collection';
-import { getEndpoint } from '@ente/shared/network/api';
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
-import { decryptFile, sortTrashFiles } from 'utils/file';
-import { logError } from '@ente/shared/sentry';
-import localForage from '@ente/shared/storage/localForage';
-import { getCollection } from './collectionService';
-
-import HTTPService from '@ente/shared/network/HTTPService';
-import { EncryptedTrashItem, Trash } from 'types/trash';
-import { EnteFile } from 'types/file';
-import { mergeMetadata } from 'utils/file';
-
-const TRASH = 'file-trash';
-const TRASH_TIME = 'trash-time';
-const DELETED_COLLECTION = 'deleted-collection';
+import { getEndpoint } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import localForage from "@ente/shared/storage/localForage";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
+import { Collection } from "types/collection";
+import { SetFiles } from "types/gallery";
+import { decryptFile, sortTrashFiles } from "utils/file";
+import { getCollection } from "./collectionService";
+
+import HTTPService from "@ente/shared/network/HTTPService";
+import { EnteFile } from "types/file";
+import { EncryptedTrashItem, Trash } from "types/trash";
+import { mergeMetadata } from "utils/file";
+
+const TRASH = "file-trash";
+const TRASH_TIME = "trash-time";
+const DELETED_COLLECTION = "deleted-collection";
const ENDPOINT = getEndpoint();
@@ -31,7 +31,7 @@ export async function getLocalDeletedCollections() {
const trashedCollections: Array<Collection> =
(await localForage.getItem<Collection[]>(DELETED_COLLECTION)) || [];
const nonUndefinedCollections = trashedCollections.filter(
- (collection) => !!collection
+ (collection) => !!collection,
);
if (nonUndefinedCollections.length !== trashedCollections.length) {
await localForage.setItem(DELETED_COLLECTION, nonUndefinedCollections);
@@ -42,10 +42,10 @@ export async function getLocalDeletedCollections() {
export async function cleanTrashCollections(fileTrash: Trash) {
const trashedCollections = await getLocalDeletedCollections();
const neededTrashCollections = new Set<number>(
- fileTrash.map((item) => item.file.collectionID)
+ fileTrash.map((item) => item.file.collectionID),
);
const filterCollections = trashedCollections.filter((item) =>
- neededTrashCollections.has(item.id)
+ neededTrashCollections.has(item.id),
);
await localForage.setItem(DELETED_COLLECTION, filterCollections);
}
@@ -55,12 +55,12 @@ async function getLastSyncTime() {
}
export async function syncTrash(
collections: Collection[],
- setTrashedFiles: SetFiles
+ setTrashedFiles: SetFiles,
): Promise<void> {
const trash = await getLocalTrash();
collections = [...collections, ...(await getLocalDeletedCollections())];
const collectionMap = new Map<number, Collection>(
- collections.map((collection) => [collection.id, collection])
+ collections.map((collection) => [collection.id, collection]),
);
if (!getToken()) {
return;
@@ -71,7 +71,7 @@ export async function syncTrash(
collectionMap,
lastSyncTime,
setTrashedFiles,
- trash
+ trash,
);
cleanTrashCollections(updatedTrash);
}
@@ -80,7 +80,7 @@ export const updateTrash = async (
collections: Map<number, Collection>,
sinceTime: number,
setTrashedFiles: SetFiles,
- currentTrash: Trash
+ currentTrash: Trash,
): Promise<Trash> => {
try {
let updatedTrash: Trash = [...currentTrash];
@@ -98,8 +98,8 @@ export const updateTrash = async (
sinceTime: time,
},
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
// #Perf: This can be optimized by running the decryption in parallel
for (const trashItem of resp.data.diff as EncryptedTrashItem[]) {
@@ -115,12 +115,12 @@ export const updateTrash = async (
if (!trashItem.isDeleted && !trashItem.isRestored) {
const decryptedFile = await decryptFile(
trashItem.file,
- collection.key
+ collection.key,
);
updatedTrash.push({ ...trashItem, file: decryptedFile });
} else {
updatedTrash = updatedTrash.filter(
- (item) => item.file.id !== trashItem.file.id
+ (item) => item.file.id !== trashItem.file.id,
);
}
}
@@ -135,7 +135,7 @@ export const updateTrash = async (
} while (resp.data.hasMore);
return updatedTrash;
} catch (e) {
- logError(e, 'Get trash files failed');
+ logError(e, "Get trash files failed");
}
return currentTrash;
};
@@ -148,8 +148,8 @@ export function getTrashedFiles(trash: Trash): EnteFile[] {
updationTime: trashedFile.updatedAt,
deleteBy: trashedFile.deleteBy,
isTrashed: true,
- }))
- )
+ })),
+ ),
);
}
@@ -166,11 +166,11 @@ export const emptyTrash = async () => {
{ lastUpdatedAt },
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
} catch (e) {
- logError(e, 'empty trash failed');
+ logError(e, "empty trash failed");
throw e;
}
};
diff --git a/apps/photos/src/services/typeDetectionService.ts b/apps/photos/src/services/typeDetectionService.ts
index 237daa7690..cfa36a037e 100644
--- a/apps/photos/src/services/typeDetectionService.ts
+++ b/apps/photos/src/services/typeDetectionService.ts
@@ -1,23 +1,23 @@
-import { FILE_TYPE } from 'constants/file';
-import { ElectronFile, FileTypeInfo } from 'types/upload';
+import { CustomError } from "@ente/shared/error";
+import { logError } from "@ente/shared/sentry";
+import { convertBytesToHumanReadable } from "@ente/shared/utils/size";
+import { FILE_TYPE } from "constants/file";
import {
- WHITELISTED_FILE_FORMATS,
KNOWN_NON_MEDIA_FORMATS,
-} from 'constants/upload';
-import { CustomError } from '@ente/shared/error';
-import { getFileExtension } from 'utils/file';
-import { logError } from '@ente/shared/sentry';
-import { getUint8ArrayView } from './readerService';
-import FileType, { FileTypeResult } from 'file-type';
-import { getFileSize } from './upload/fileService';
-import { convertBytesToHumanReadable } from '@ente/shared/utils/size';
+ WHITELISTED_FILE_FORMATS,
+} from "constants/upload";
+import FileType, { FileTypeResult } from "file-type";
+import { ElectronFile, FileTypeInfo } from "types/upload";
+import { getFileExtension } from "utils/file";
+import { getUint8ArrayView } from "./readerService";
+import { getFileSize } from "./upload/fileService";
-const TYPE_VIDEO = 'video';
-const TYPE_IMAGE = 'image';
+const TYPE_VIDEO = "video";
+const TYPE_IMAGE = "image";
const CHUNK_SIZE_FOR_TYPE_DETECTION = 4100;
export async function getFileType(
- receivedFile: File | ElectronFile
+ receivedFile: File | ElectronFile,
): Promise<FileTypeInfo> {
try {
let fileType: FILE_TYPE;
@@ -29,7 +29,7 @@ export async function getFileType(
typeResult = await extractElectronFileType(receivedFile);
}
- const mimTypeParts: string[] = typeResult.mime?.split('/');
+ const mimTypeParts: string[] = typeResult.mime?.split("/");
if (mimTypeParts?.length !== 2) {
throw Error(CustomError.INVALID_MIME_TYPE(typeResult.mime));
@@ -53,7 +53,7 @@ export async function getFileType(
const fileFormat = getFileExtension(receivedFile.name);
const fileSize = convertBytesToHumanReadable(getFileSize(receivedFile));
const whiteListedFormat = WHITELISTED_FILE_FORMATS.find(
- (a) => a.exactType === fileFormat
+ (a) => a.exactType === fileFormat,
);
if (whiteListedFormat) {
return whiteListedFormat;
@@ -62,13 +62,13 @@ export async function getFileType(
throw Error(CustomError.UNSUPPORTED_FILE_FORMAT);
}
if (e.message === CustomError.NON_MEDIA_FILE) {
- logError(e, 'unsupported file format', {
+ logError(e, "unsupported file format", {
fileFormat,
fileSize,
});
throw Error(CustomError.UNSUPPORTED_FILE_FORMAT);
}
- logError(e, 'type detection failed', {
+ logError(e, "type detection failed", {
fileFormat,
fileSize,
});
@@ -93,11 +93,11 @@ async function extractElectronFileType(file: ElectronFile) {
async function getFileTypeFromBuffer(buffer: Uint8Array) {
const result = await FileType.fromBuffer(buffer);
if (!result?.mime) {
- let logableInfo = '';
+ let logableInfo = "";
try {
logableInfo = `result: ${JSON.stringify(result)}`;
} catch (e) {
- logableInfo = 'failed to stringify result';
+ logableInfo = "failed to stringify result";
}
throw Error(`mimetype missing from file type result - ${logableInfo}`);
}
diff --git a/apps/photos/src/services/updateCreationTimeWithExif.ts b/apps/photos/src/services/updateCreationTimeWithExif.ts
index 751e132cef..4cc4cc3d6a 100644
--- a/apps/photos/src/services/updateCreationTimeWithExif.ts
+++ b/apps/photos/src/services/updateCreationTimeWithExif.ts
@@ -1,31 +1,31 @@
-import { FIX_OPTIONS } from 'components/FixCreationTime';
-import { SetProgressTracker } from 'components/FixLargeThumbnail';
+import { logError } from "@ente/shared/sentry";
+import { FIX_OPTIONS } from "components/FixCreationTime";
+import { SetProgressTracker } from "components/FixLargeThumbnail";
+import { EnteFile } from "types/file";
import {
changeFileCreationTime,
updateExistingFilePubMetadata,
-} from 'utils/file';
-import { logError } from '@ente/shared/sentry';
-import downloadManager from './download';
-import { EnteFile } from 'types/file';
+} from "utils/file";
+import downloadManager from "./download";
-import { getParsedExifData } from './upload/exifService';
-import { getFileType } from 'services/typeDetectionService';
-import { FILE_TYPE } from 'constants/file';
-import { validateAndGetCreationUnixTimeInMicroSeconds } from '@ente/shared/time';
+import { validateAndGetCreationUnixTimeInMicroSeconds } from "@ente/shared/time";
+import { FILE_TYPE } from "constants/file";
+import { getFileType } from "services/typeDetectionService";
+import { getParsedExifData } from "./upload/exifService";
const EXIF_TIME_TAGS = [
- 'DateTimeOriginal',
- 'CreateDate',
- 'ModifyDate',
- 'DateCreated',
- 'MetadataDate',
+ "DateTimeOriginal",
+ "CreateDate",
+ "ModifyDate",
+ "DateCreated",
+ "MetadataDate",
];
export async function updateCreationTimeWithExif(
filesToBeUpdated: EnteFile[],
fixOption: FIX_OPTIONS,
customTime: Date,
- setProgressTracker: SetProgressTracker
+ setProgressTracker: SetProgressTracker,
) {
let completedWithError = false;
try {
@@ -46,32 +46,32 @@ export async function updateCreationTimeWithExif(
const fileBlob = await new Response(fileStream).blob();
const fileObject = new File(
[fileBlob],
- file.metadata.title
+ file.metadata.title,
);
const fileTypeInfo = await getFileType(fileObject);
const exifData = await getParsedExifData(
fileObject,
fileTypeInfo,
- EXIF_TIME_TAGS
+ EXIF_TIME_TAGS,
);
if (fixOption === FIX_OPTIONS.DATE_TIME_ORIGINAL) {
correctCreationTime =
validateAndGetCreationUnixTimeInMicroSeconds(
exifData?.DateTimeOriginal ??
- exifData?.DateCreated
+ exifData?.DateCreated,
);
} else if (fixOption === FIX_OPTIONS.DATE_TIME_DIGITIZED) {
correctCreationTime =
validateAndGetCreationUnixTimeInMicroSeconds(
- exifData?.CreateDate
+ exifData?.CreateDate,
);
} else if (fixOption === FIX_OPTIONS.METADATA_DATE) {
correctCreationTime =
validateAndGetCreationUnixTimeInMicroSeconds(
- exifData?.MetadataDate
+ exifData?.MetadataDate,
);
} else {
- throw new Error('Invalid fix option');
+ throw new Error("Invalid fix option");
}
}
if (
@@ -80,12 +80,12 @@ export async function updateCreationTimeWithExif(
) {
const updatedFile = await changeFileCreationTime(
file,
- correctCreationTime
+ correctCreationTime,
);
updateExistingFilePubMetadata(file, updatedFile);
}
} catch (e) {
- logError(e, 'failed to updated a CreationTime With Exif');
+ logError(e, "failed to updated a CreationTime With Exif");
completedWithError = true;
} finally {
setProgressTracker({
@@ -95,7 +95,7 @@ export async function updateCreationTimeWithExif(
}
}
} catch (e) {
- logError(e, 'update CreationTime With Exif failed');
+ logError(e, "update CreationTime With Exif failed");
completedWithError = true;
}
return completedWithError;
diff --git a/apps/photos/src/services/upload/encryptionService.ts b/apps/photos/src/services/upload/encryptionService.ts
index 3cd4b7d8f8..90f100c9fb 100644
--- a/apps/photos/src/services/upload/encryptionService.ts
+++ b/apps/photos/src/services/upload/encryptionService.ts
@@ -1,11 +1,11 @@
-import { Remote } from 'comlink';
-import { EncryptionResult } from '@ente/shared/crypto/types';
-import { DataStream, isDataStream } from 'types/upload';
-import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
+import { DedicatedCryptoWorker } from "@ente/shared/crypto/internal/crypto.worker";
+import { EncryptionResult } from "@ente/shared/crypto/types";
+import { Remote } from "comlink";
+import { DataStream, isDataStream } from "types/upload";
async function encryptFileStream(
worker: Remote<DedicatedCryptoWorker>,
- fileData: DataStream
+ fileData: DataStream,
) {
const { stream, chunkCount } = fileData;
const fileStreamReader = stream.getReader();
@@ -18,7 +18,7 @@ async function encryptFileStream(
const encryptedFileChunk = await worker.encryptFileChunk(
value,
pushState,
- ref.pullCount === chunkCount
+ ref.pullCount === chunkCount,
);
controller.enqueue(encryptedFileChunk);
if (ref.pullCount === chunkCount) {
@@ -38,7 +38,7 @@ async function encryptFileStream(
export async function encryptFiledata(
worker: Remote<DedicatedCryptoWorker>,
- filedata: Uint8Array | DataStream
+ filedata: Uint8Array | DataStream,
): Promise<EncryptionResult<Uint8Array | DataStream>> {
return isDataStream(filedata)
? await encryptFileStream(worker, filedata)
diff --git a/apps/photos/src/services/upload/exifService.ts b/apps/photos/src/services/upload/exifService.ts
index 743cc715c4..7fffb473b9 100644
--- a/apps/photos/src/services/upload/exifService.ts
+++ b/apps/photos/src/services/upload/exifService.ts
@@ -1,13 +1,12 @@
-import { EXIFLESS_FORMATS, NULL_LOCATION } from 'constants/upload';
-import { Location } from 'types/upload';
-import exifr from 'exifr';
-import piexif from 'piexifjs';
-import { FileTypeInfo } from 'types/upload';
-import { logError } from '@ente/shared/sentry';
-import { validateAndGetCreationUnixTimeInMicroSeconds } from '@ente/shared/time';
-import { CustomError } from '@ente/shared/error';
+import { CustomError } from "@ente/shared/error";
+import { logError } from "@ente/shared/sentry";
+import { validateAndGetCreationUnixTimeInMicroSeconds } from "@ente/shared/time";
+import { EXIFLESS_FORMATS, NULL_LOCATION } from "constants/upload";
+import exifr from "exifr";
+import piexif from "piexifjs";
+import { FileTypeInfo, Location } from "types/upload";
-const EXIFR_UNSUPPORTED_FILE_FORMAT_MESSAGE = 'Unknown file format';
+const EXIFR_UNSUPPORTED_FILE_FORMAT_MESSAGE = "Unknown file format";
type ParsedEXIFData = Record<string, any> &
Partial<{
@@ -40,7 +39,7 @@ type RawEXIFData = Record<string, any> &
export async function getParsedExifData(
receivedFile: File,
fileTypeInfo: FileTypeInfo,
- tags?: string[]
+ tags?: string[],
): Promise<ParsedEXIFData> {
try {
if (EXIFLESS_FORMATS.includes(fileTypeInfo.exactType)) {
@@ -60,17 +59,19 @@ export async function getParsedExifData(
}
const filteredExifData = tags
? Object.fromEntries(
- Object.entries(exifData).filter(([key]) => tags.includes(key))
+ Object.entries(exifData).filter(([key]) =>
+ tags.includes(key),
+ ),
)
: exifData;
return parseExifData(filteredExifData);
} catch (e) {
if (e.message === EXIFR_UNSUPPORTED_FILE_FORMAT_MESSAGE) {
- logError(e, 'exif library unsupported format', {
+ logError(e, "exif library unsupported format", {
fileType: fileTypeInfo.exactType,
});
} else {
- logError(e, 'get parsed exif data failed', {
+ logError(e, "get parsed exif data failed", {
fileType: fileTypeInfo.exactType,
});
throw e;
@@ -117,57 +118,57 @@ function parseExifData(exifData: RawEXIFData): ParsedEXIFData {
exifData.GPSLatitude,
exifData.GPSLatitudeRef,
exifData.GPSLongitude,
- exifData.GPSLongitudeRef
+ exifData.GPSLongitudeRef,
);
parsedExif.latitude = parsedLocation.latitude;
parsedExif.longitude = parsedLocation.longitude;
}
if (ImageWidth && ImageHeight) {
- if (typeof ImageWidth === 'number' && typeof ImageHeight === 'number') {
+ if (typeof ImageWidth === "number" && typeof ImageHeight === "number") {
parsedExif.imageWidth = ImageWidth;
parsedExif.imageHeight = ImageHeight;
} else {
logError(
- new Error('ImageWidth or ImageHeight is not a number'),
- 'Image dimension parsing failed',
+ new Error("ImageWidth or ImageHeight is not a number"),
+ "Image dimension parsing failed",
{
ImageWidth,
ImageHeight,
- }
+ },
);
}
} else if (ExifImageWidth && ExifImageHeight) {
if (
- typeof ExifImageWidth === 'number' &&
- typeof ExifImageHeight === 'number'
+ typeof ExifImageWidth === "number" &&
+ typeof ExifImageHeight === "number"
) {
parsedExif.imageWidth = ExifImageWidth;
parsedExif.imageHeight = ExifImageHeight;
} else {
logError(
- new Error('ExifImageWidth or ExifImageHeight is not a number'),
- 'Image dimension parsing failed',
+ new Error("ExifImageWidth or ExifImageHeight is not a number"),
+ "Image dimension parsing failed",
{
ExifImageWidth,
ExifImageHeight,
- }
+ },
);
}
} else if (PixelXDimension && PixelYDimension) {
if (
- typeof PixelXDimension === 'number' &&
- typeof PixelYDimension === 'number'
+ typeof PixelXDimension === "number" &&
+ typeof PixelYDimension === "number"
) {
parsedExif.imageWidth = PixelXDimension;
parsedExif.imageHeight = PixelYDimension;
} else {
logError(
- new Error('PixelXDimension or PixelYDimension is not a number'),
- 'Image dimension parsing failed',
+ new Error("PixelXDimension or PixelYDimension is not a number"),
+ "Image dimension parsing failed",
{
PixelXDimension,
PixelYDimension,
- }
+ },
);
}
}
@@ -176,7 +177,7 @@ function parseExifData(exifData: RawEXIFData): ParsedEXIFData {
function parseEXIFDate(dateTimeString: string) {
try {
- if (typeof dateTimeString !== 'string' || dateTimeString === '') {
+ if (typeof dateTimeString !== "string" || dateTimeString === "") {
throw Error(CustomError.NOT_A_DATE);
}
@@ -201,22 +202,22 @@ function parseEXIFDate(dateTimeString: string) {
.map(Number);
if (
- typeof year === 'undefined' ||
+ typeof year === "undefined" ||
Number.isNaN(year) ||
- typeof month === 'undefined' ||
+ typeof month === "undefined" ||
Number.isNaN(month) ||
- typeof day === 'undefined' ||
+ typeof day === "undefined" ||
Number.isNaN(day)
) {
throw Error(CustomError.NOT_A_DATE);
}
let date: Date;
if (
- typeof hour === 'undefined' ||
+ typeof hour === "undefined" ||
Number.isNaN(hour) ||
- typeof minute === 'undefined' ||
+ typeof minute === "undefined" ||
Number.isNaN(minute) ||
- typeof second === 'undefined' ||
+ typeof second === "undefined" ||
Number.isNaN(second)
) {
date = new Date(year, month - 1, day);
@@ -228,7 +229,7 @@ function parseEXIFDate(dateTimeString: string) {
}
return date;
} catch (e) {
- logError(e, 'parseEXIFDate failed', {
+ logError(e, "parseEXIFDate failed", {
dateTimeString,
});
return null;
@@ -239,7 +240,7 @@ export function parseEXIFLocation(
gpsLatitude: number[],
gpsLatitudeRef: string,
gpsLongitude: number[],
- gpsLongitudeRef: string
+ gpsLongitudeRef: string,
) {
try {
if (
@@ -254,17 +255,17 @@ export function parseEXIFLocation(
gpsLatitude[0],
gpsLatitude[1],
gpsLatitude[2],
- gpsLatitudeRef
+ gpsLatitudeRef,
);
const longitude = convertDMSToDD(
gpsLongitude[0],
gpsLongitude[1],
gpsLongitude[2],
- gpsLongitudeRef
+ gpsLongitudeRef,
);
return { latitude, longitude };
} catch (e) {
- logError(e, 'parseEXIFLocation failed', {
+ logError(e, "parseEXIFLocation failed", {
gpsLatitude,
gpsLatitudeRef,
gpsLongitude,
@@ -278,10 +279,10 @@ function convertDMSToDD(
degrees: number,
minutes: number,
seconds: number,
- direction: string
+ direction: string,
) {
let dd = degrees + minutes / 60 + seconds / (60 * 60);
- if (direction === 'S' || direction === 'W') dd *= -1;
+ if (direction === "S" || direction === "W") dd *= -1;
return dd;
}
@@ -311,25 +312,25 @@ export function getEXIFTime(exifData: ParsedEXIFData): number {
export async function updateFileCreationDateInEXIF(
reader: FileReader,
fileBlob: Blob,
- updatedDate: Date
+ updatedDate: Date,
) {
try {
let imageDataURL = await convertImageToDataURL(reader, fileBlob);
imageDataURL =
- 'data:image/jpeg;base64' +
- imageDataURL.slice(imageDataURL.indexOf(','));
+ "data:image/jpeg;base64" +
+ imageDataURL.slice(imageDataURL.indexOf(","));
const exifObj = piexif.load(imageDataURL);
- if (!exifObj['Exif']) {
- exifObj['Exif'] = {};
+ if (!exifObj["Exif"]) {
+ exifObj["Exif"] = {};
}
- exifObj['Exif'][piexif.ExifIFD.DateTimeOriginal] =
+ exifObj["Exif"][piexif.ExifIFD.DateTimeOriginal] =
convertToExifDateFormat(updatedDate);
const exifBytes = piexif.dump(exifObj);
const exifInsertedFile = piexif.insert(exifBytes, imageDataURL);
return dataURIToBlob(exifInsertedFile);
} catch (e) {
- logError(e, 'updateFileModifyDateInEXIF failed');
+ logError(e, "updateFileModifyDateInEXIF failed");
return fileBlob;
}
}
@@ -345,10 +346,10 @@ async function convertImageToDataURL(reader: FileReader, blob: Blob) {
function dataURIToBlob(dataURI: string) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
- const byteString = atob(dataURI.split(',')[1]);
+ const byteString = atob(dataURI.split(",")[1]);
// separate out the mime component
- const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
+ const mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];
// write the bytes of the string to an ArrayBuffer
const ab = new ArrayBuffer(byteString.length);
diff --git a/apps/photos/src/services/upload/fileService.ts b/apps/photos/src/services/upload/fileService.ts
index ddeeb0ea0e..d9f402df45 100644
--- a/apps/photos/src/services/upload/fileService.ts
+++ b/apps/photos/src/services/upload/fileService.ts
@@ -1,35 +1,35 @@
-import { MULTIPART_PART_SIZE, FILE_READER_CHUNK_SIZE } from 'constants/upload';
+import { addLogLine } from "@ente/shared/logging";
+import { getFileNameSize } from "@ente/shared/logging/web";
+import { logError } from "@ente/shared/sentry";
+import { FILE_READER_CHUNK_SIZE, MULTIPART_PART_SIZE } from "constants/upload";
import {
- FileTypeInfo,
- FileInMemory,
- EncryptedFile,
- FileWithMetadata,
- ParsedMetadataJSONMap,
DataStream,
ElectronFile,
+ EncryptedFile,
ExtractMetadataResult,
+ FileInMemory,
+ FileTypeInfo,
+ FileWithMetadata,
ParsedMetadataJSON,
-} from 'types/upload';
-import { logError } from '@ente/shared/sentry';
-import { addLogLine } from '@ente/shared/logging';
-import { getFileNameSize } from '@ente/shared/logging/web';
+ ParsedMetadataJSONMap,
+} from "types/upload";
-import { encryptFiledata } from './encryptionService';
+import { DedicatedCryptoWorker } from "@ente/shared/crypto/internal/crypto.worker";
+import { Remote } from "comlink";
+import { EncryptedMagicMetadata } from "types/magicMetadata";
+import {
+ getElectronFileStream,
+ getFileStream,
+ getUint8ArrayView,
+} from "../readerService";
+import { encryptFiledata } from "./encryptionService";
import {
MAX_FILE_NAME_LENGTH_GOOGLE_EXPORT,
extractMetadata,
getClippedMetadataJSONMapKeyForFile,
getMetadataJSONMapKeyForFile,
-} from './metadataService';
-import {
- getFileStream,
- getElectronFileStream,
- getUint8ArrayView,
-} from '../readerService';
-import { generateThumbnail } from './thumbnailService';
-import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
-import { Remote } from 'comlink';
-import { EncryptedMagicMetadata } from 'types/magicMetadata';
+} from "./metadataService";
+import { generateThumbnail } from "./thumbnailService";
export function getFileSize(file: File | ElectronFile) {
return file.size;
@@ -41,11 +41,11 @@ export function getFilename(file: File | ElectronFile) {
export async function readFile(
fileTypeInfo: FileTypeInfo,
- rawFile: File | ElectronFile
+ rawFile: File | ElectronFile,
): Promise<FileInMemory> {
const { thumbnail, hasStaticThumbnail } = await generateThumbnail(
rawFile,
- fileTypeInfo
+ fileTypeInfo,
);
addLogLine(`reading file data ${getFileNameSize(rawFile)} `);
let filedata: Uint8Array | DataStream;
@@ -53,7 +53,7 @@ export async function readFile(
if (rawFile.size > MULTIPART_PART_SIZE) {
filedata = await getElectronFileStream(
rawFile,
- FILE_READER_CHUNK_SIZE
+ FILE_READER_CHUNK_SIZE,
);
} else {
filedata = await getUint8ArrayView(rawFile);
@@ -78,7 +78,7 @@ export async function extractFileMetadata(
parsedMetadataJSONMap: ParsedMetadataJSONMap,
collectionID: number,
fileTypeInfo: FileTypeInfo,
- rawFile: File | ElectronFile
+ rawFile: File | ElectronFile,
): Promise<ExtractMetadataResult> {
let key = getMetadataJSONMapKeyForFile(collectionID, rawFile.name);
let googleMetadata: ParsedMetadataJSON = parsedMetadataJSONMap.get(key);
@@ -91,7 +91,7 @@ export async function extractFileMetadata(
const { metadata, publicMagicMetadata } = await extractMetadata(
worker,
rawFile,
- fileTypeInfo
+ fileTypeInfo,
);
for (const [key, value] of Object.entries(googleMetadata ?? {})) {
@@ -106,21 +106,21 @@ export async function extractFileMetadata(
export async function encryptFile(
worker: Remote<DedicatedCryptoWorker>,
file: FileWithMetadata,
- encryptionKey: string
+ encryptionKey: string,
): Promise<EncryptedFile> {
try {
const { key: fileKey, file: encryptedFiledata } = await encryptFiledata(
worker,
- file.filedata
+ file.filedata,
);
const { file: encryptedThumbnail } = await worker.encryptThumbnail(
file.thumbnail,
- fileKey
+ fileKey,
);
const { file: encryptedMetadata } = await worker.encryptMetadata(
file.metadata,
- fileKey
+ fileKey,
);
let encryptedPubMagicMetadata: EncryptedMagicMetadata;
@@ -128,7 +128,7 @@ export async function encryptFile(
const { file: encryptedPubMagicMetadataData } =
await worker.encryptMetadata(
file.pubMagicMetadata.data,
- fileKey
+ fileKey,
);
encryptedPubMagicMetadata = {
version: file.pubMagicMetadata.version,
@@ -152,7 +152,7 @@ export async function encryptFile(
};
return result;
} catch (e) {
- logError(e, 'Error encrypting files');
+ logError(e, "Error encrypting files");
throw e;
}
}
diff --git a/apps/photos/src/services/upload/hashService.tsx b/apps/photos/src/services/upload/hashService.tsx
index 4f3a0602a9..17e1346b21 100644
--- a/apps/photos/src/services/upload/hashService.tsx
+++ b/apps/photos/src/services/upload/hashService.tsx
@@ -1,16 +1,16 @@
-import { Remote } from 'comlink';
-import { FILE_READER_CHUNK_SIZE } from 'constants/upload';
-import { getFileStream, getElectronFileStream } from 'services/readerService';
-import { ElectronFile, DataStream } from 'types/upload';
-import { CustomError } from '@ente/shared/error';
-import { addLogLine } from '@ente/shared/logging';
-import { getFileNameSize } from '@ente/shared/logging/web';
-import { logError } from '@ente/shared/sentry';
-import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
+import { DedicatedCryptoWorker } from "@ente/shared/crypto/internal/crypto.worker";
+import { CustomError } from "@ente/shared/error";
+import { addLogLine } from "@ente/shared/logging";
+import { getFileNameSize } from "@ente/shared/logging/web";
+import { logError } from "@ente/shared/sentry";
+import { Remote } from "comlink";
+import { FILE_READER_CHUNK_SIZE } from "constants/upload";
+import { getElectronFileStream, getFileStream } from "services/readerService";
+import { DataStream, ElectronFile } from "types/upload";
export async function getFileHash(
worker: Remote<DedicatedCryptoWorker>,
- file: File | ElectronFile
+ file: File | ElectronFile,
) {
try {
addLogLine(`getFileHash called for ${getFileNameSize(file)}`);
@@ -20,7 +20,7 @@ export async function getFileHash(
} else {
filedata = await getElectronFileStream(
file,
- FILE_READER_CHUNK_SIZE
+ FILE_READER_CHUNK_SIZE,
);
}
const hashState = await worker.initChunkHashing();
@@ -39,13 +39,13 @@ export async function getFileHash(
}
const hash = await worker.completeChunkHashing(hashState);
addLogLine(
- `file hashing completed successfully ${getFileNameSize(file)}`
+ `file hashing completed successfully ${getFileNameSize(file)}`,
);
return hash;
} catch (e) {
- logError(e, 'getFileHash failed');
+ logError(e, "getFileHash failed");
addLogLine(
- `file hashing failed ${getFileNameSize(file)} ,${e.message} `
+ `file hashing failed ${getFileNameSize(file)} ,${e.message} `,
);
}
}
diff --git a/apps/photos/src/services/upload/livePhotoService.ts b/apps/photos/src/services/upload/livePhotoService.ts
index 6749959f48..52fbc93d86 100644
--- a/apps/photos/src/services/upload/livePhotoService.ts
+++ b/apps/photos/src/services/upload/livePhotoService.ts
@@ -1,31 +1,31 @@
-import { FILE_TYPE } from 'constants/file';
-import { LIVE_PHOTO_ASSET_SIZE_LIMIT } from 'constants/upload';
-import { encodeLivePhoto } from 'services/livePhotoService';
-import { getFileType } from 'services/typeDetectionService';
+import { DedicatedCryptoWorker } from "@ente/shared/crypto/internal/crypto.worker";
+import { CustomError } from "@ente/shared/error";
+import { logError } from "@ente/shared/sentry";
+import { Remote } from "comlink";
+import { FILE_TYPE } from "constants/file";
+import { LIVE_PHOTO_ASSET_SIZE_LIMIT } from "constants/upload";
+import { encodeLivePhoto } from "services/livePhotoService";
+import { getFileType } from "services/typeDetectionService";
import {
ElectronFile,
+ ExtractMetadataResult,
FileTypeInfo,
FileWithCollection,
LivePhotoAssets,
ParsedMetadataJSONMap,
- ExtractMetadataResult,
-} from 'types/upload';
-import { CustomError } from '@ente/shared/error';
-import { getFileTypeFromExtensionForLivePhotoClustering } from 'utils/file/livePhoto';
+} from "types/upload";
import {
- splitFilenameAndExtension,
- isImageOrVideo,
getFileExtensionWithDot,
getFileNameWithoutExtension,
-} from 'utils/file';
-import { logError } from '@ente/shared/sentry';
-import { getUint8ArrayView } from '../readerService';
-import { extractFileMetadata } from './fileService';
-import { getFileHash } from './hashService';
-import { generateThumbnail } from './thumbnailService';
-import uploadCancelService from './uploadCancelService';
-import { Remote } from 'comlink';
-import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
+ isImageOrVideo,
+ splitFilenameAndExtension,
+} from "utils/file";
+import { getFileTypeFromExtensionForLivePhotoClustering } from "utils/file/livePhoto";
+import { getUint8ArrayView } from "../readerService";
+import { extractFileMetadata } from "./fileService";
+import { getFileHash } from "./hashService";
+import { generateThumbnail } from "./thumbnailService";
+import uploadCancelService from "./uploadCancelService";
interface LivePhotoIdentifier {
collectionID: number;
@@ -34,13 +34,13 @@ interface LivePhotoIdentifier {
size: number;
}
-const UNDERSCORE_THREE = '_3';
+const UNDERSCORE_THREE = "_3";
// Note: The icloud-photos-downloader library appends _HVEC to the end of the filename in case of live photos
// https://github.com/icloud-photos-downloader/icloud_photos_downloader
-const UNDERSCORE_HEVC = '_HVEC';
+const UNDERSCORE_HEVC = "_HVEC";
export async function getLivePhotoFileType(
- livePhotoAssets: LivePhotoAssets
+ livePhotoAssets: LivePhotoAssets,
): Promise<FileTypeInfo> {
const imageFileTypeInfo = await getFileType(livePhotoAssets.image);
const videoFileTypeInfo = await getFileType(livePhotoAssets.video);
@@ -57,7 +57,7 @@ export async function extractLivePhotoMetadata(
parsedMetadataJSONMap: ParsedMetadataJSONMap,
collectionID: number,
fileTypeInfo: FileTypeInfo,
- livePhotoAssets: LivePhotoAssets
+ livePhotoAssets: LivePhotoAssets,
): Promise<ExtractMetadataResult> {
const imageFileTypeInfo: FileTypeInfo = {
fileType: FILE_TYPE.IMAGE,
@@ -71,7 +71,7 @@ export async function extractLivePhotoMetadata(
parsedMetadataJSONMap,
collectionID,
imageFileTypeInfo,
- livePhotoAssets.image
+ livePhotoAssets.image,
);
const videoHash = await getFileHash(worker, livePhotoAssets.video);
return {
@@ -97,14 +97,14 @@ export function getLivePhotoName(livePhotoAssets: LivePhotoAssets) {
export async function readLivePhoto(
fileTypeInfo: FileTypeInfo,
- livePhotoAssets: LivePhotoAssets
+ livePhotoAssets: LivePhotoAssets,
) {
const { thumbnail, hasStaticThumbnail } = await generateThumbnail(
livePhotoAssets.image,
{
exactType: fileTypeInfo.imageType,
fileType: FILE_TYPE.IMAGE,
- }
+ },
);
const image = await getUint8ArrayView(livePhotoAssets.image);
@@ -129,14 +129,14 @@ export async function clusterLivePhotoFiles(mediaFiles: FileWithCollection[]) {
mediaFiles
.sort((firstMediaFile, secondMediaFile) =>
splitFilenameAndExtension(
- firstMediaFile.file.name
+ firstMediaFile.file.name,
)[0].localeCompare(
- splitFilenameAndExtension(secondMediaFile.file.name)[0]
- )
+ splitFilenameAndExtension(secondMediaFile.file.name)[0],
+ ),
)
.sort(
(firstMediaFile, secondMediaFile) =>
- firstMediaFile.collectionID - secondMediaFile.collectionID
+ firstMediaFile.collectionID - secondMediaFile.collectionID,
);
let index = 0;
while (index < mediaFiles.length - 1) {
@@ -147,11 +147,11 @@ export async function clusterLivePhotoFiles(mediaFiles: FileWithCollection[]) {
const secondMediaFile = mediaFiles[index + 1];
const firstFileType =
getFileTypeFromExtensionForLivePhotoClustering(
- firstMediaFile.file.name
+ firstMediaFile.file.name,
);
const secondFileType =
getFileTypeFromExtensionForLivePhotoClustering(
- secondMediaFile.file.name
+ secondMediaFile.file.name,
);
const firstFileIdentifier: LivePhotoIdentifier = {
collectionID: firstMediaFile.collectionID,
@@ -168,7 +168,7 @@ export async function clusterLivePhotoFiles(mediaFiles: FileWithCollection[]) {
if (
areFilesLivePhotoAssets(
firstFileIdentifier,
- secondFileIdentifier
+ secondFileIdentifier,
)
) {
let imageFile: File | ElectronFile;
@@ -213,7 +213,7 @@ export async function clusterLivePhotoFiles(mediaFiles: FileWithCollection[]) {
if (e.message === CustomError.UPLOAD_CANCELLED) {
throw e;
} else {
- logError(e, 'failed to cluster live photo');
+ logError(e, "failed to cluster live photo");
throw e;
}
}
@@ -221,7 +221,7 @@ export async function clusterLivePhotoFiles(mediaFiles: FileWithCollection[]) {
function areFilesLivePhotoAssets(
firstFileIdentifier: LivePhotoIdentifier,
- secondFileIdentifier: LivePhotoIdentifier
+ secondFileIdentifier: LivePhotoIdentifier,
) {
const haveSameCollectionID =
firstFileIdentifier.collectionID === secondFileIdentifier.collectionID;
@@ -235,18 +235,18 @@ function areFilesLivePhotoAssets(
getFileNameWithoutExtension(firstFileIdentifier.name),
// Note: The Google Live Photo image file can have video extension appended as suffix, passing that to removePotentialLivePhotoSuffix to remove it
// Example: IMG_20210630_0001.mp4.jpg (Google Live Photo image file)
- getFileExtensionWithDot(secondFileIdentifier.name)
+ getFileExtensionWithDot(secondFileIdentifier.name),
);
secondFileNameWithoutSuffix = removePotentialLivePhotoSuffix(
- getFileNameWithoutExtension(secondFileIdentifier.name)
+ getFileNameWithoutExtension(secondFileIdentifier.name),
);
} else {
firstFileNameWithoutSuffix = removePotentialLivePhotoSuffix(
- getFileNameWithoutExtension(firstFileIdentifier.name)
+ getFileNameWithoutExtension(firstFileIdentifier.name),
);
secondFileNameWithoutSuffix = removePotentialLivePhotoSuffix(
getFileNameWithoutExtension(secondFileIdentifier.name),
- getFileExtensionWithDot(firstFileIdentifier.name)
+ getFileExtensionWithDot(firstFileIdentifier.name),
);
}
if (
@@ -273,7 +273,7 @@ function areFilesLivePhotoAssets(
firstFileIdentifier.size,
secondFileIdentifier.size,
],
- }
+ },
);
}
}
@@ -282,7 +282,7 @@ function areFilesLivePhotoAssets(
function removePotentialLivePhotoSuffix(
filenameWithoutExtension: string,
- suffix?: string
+ suffix?: string,
) {
let presentSuffix: string;
if (filenameWithoutExtension.endsWith(UNDERSCORE_THREE)) {
diff --git a/apps/photos/src/services/upload/magicMetadataService.ts b/apps/photos/src/services/upload/magicMetadataService.ts
index 1fff0ffcc3..f56b31c439 100644
--- a/apps/photos/src/services/upload/magicMetadataService.ts
+++ b/apps/photos/src/services/upload/magicMetadataService.ts
@@ -1,17 +1,17 @@
import {
- FilePublicMagicMetadataProps,
FilePublicMagicMetadata,
-} from 'types/file';
+ FilePublicMagicMetadataProps,
+} from "types/file";
import {
getNonEmptyMagicMetadataProps,
updateMagicMetadata,
-} from 'utils/magicMetadata';
+} from "utils/magicMetadata";
export async function constructPublicMagicMetadata(
- publicMagicMetadataProps: FilePublicMagicMetadataProps
+ publicMagicMetadataProps: FilePublicMagicMetadataProps,
): Promise<FilePublicMagicMetadata> {
const nonEmptyPublicMagicMetadataProps = getNonEmptyMagicMetadataProps(
- publicMagicMetadataProps
+ publicMagicMetadataProps,
);
if (Object.values(nonEmptyPublicMagicMetadataProps)?.length === 0) {
diff --git a/apps/photos/src/services/upload/metadataService.ts b/apps/photos/src/services/upload/metadataService.ts
index 035842c6ec..f51ca15c2f 100644
--- a/apps/photos/src/services/upload/metadataService.ts
+++ b/apps/photos/src/services/upload/metadataService.ts
@@ -1,27 +1,27 @@
-import { FILE_TYPE } from 'constants/file';
-import { logError } from '@ente/shared/sentry';
-import { getEXIFLocation, getEXIFTime, getParsedExifData } from './exifService';
-import {
- Metadata,
- ParsedMetadataJSON,
- Location,
- FileTypeInfo,
- ParsedExtractedMetadata,
- ElectronFile,
- ExtractMetadataResult as ExtractMetadataResult,
-} from 'types/upload';
-import { NULL_EXTRACTED_METADATA, NULL_LOCATION } from 'constants/upload';
-import { getVideoMetadata } from './videoMetadataService';
+import { DedicatedCryptoWorker } from "@ente/shared/crypto/internal/crypto.worker";
+import { logError } from "@ente/shared/sentry";
import {
parseDateFromFusedDateString,
- validateAndGetCreationUnixTimeInMicroSeconds,
tryToParseDateTime,
-} from '@ente/shared/time';
-import { getFileHash } from './hashService';
-import { Remote } from 'comlink';
-import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
-import { FilePublicMagicMetadataProps } from 'types/file';
-import { splitFilenameAndExtension } from 'utils/file';
+ validateAndGetCreationUnixTimeInMicroSeconds,
+} from "@ente/shared/time";
+import { Remote } from "comlink";
+import { FILE_TYPE } from "constants/file";
+import { NULL_EXTRACTED_METADATA, NULL_LOCATION } from "constants/upload";
+import { FilePublicMagicMetadataProps } from "types/file";
+import {
+ ElectronFile,
+ ExtractMetadataResult,
+ FileTypeInfo,
+ Location,
+ Metadata,
+ ParsedExtractedMetadata,
+ ParsedMetadataJSON,
+} from "types/upload";
+import { splitFilenameAndExtension } from "utils/file";
+import { getEXIFLocation, getEXIFTime, getParsedExifData } from "./exifService";
+import { getFileHash } from "./hashService";
+import { getVideoMetadata } from "./videoMetadataService";
const NULL_PARSED_METADATA_JSON: ParsedMetadataJSON = {
creationTime: null,
@@ -30,21 +30,21 @@ const NULL_PARSED_METADATA_JSON: ParsedMetadataJSON = {
};
const EXIF_TAGS_NEEDED = [
- 'DateTimeOriginal',
- 'CreateDate',
- 'ModifyDate',
- 'GPSLatitude',
- 'GPSLongitude',
- 'GPSLatitudeRef',
- 'GPSLongitudeRef',
- 'DateCreated',
- 'ExifImageWidth',
- 'ExifImageHeight',
- 'ImageWidth',
- 'ImageHeight',
- 'PixelXDimension',
- 'PixelYDimension',
- 'MetadataDate',
+ "DateTimeOriginal",
+ "CreateDate",
+ "ModifyDate",
+ "GPSLatitude",
+ "GPSLongitude",
+ "GPSLatitudeRef",
+ "GPSLongitudeRef",
+ "DateCreated",
+ "ExifImageWidth",
+ "ExifImageHeight",
+ "ImageWidth",
+ "ImageHeight",
+ "PixelXDimension",
+ "PixelYDimension",
+ "MetadataDate",
];
export const MAX_FILE_NAME_LENGTH_GOOGLE_EXPORT = 46;
@@ -52,7 +52,7 @@ export const MAX_FILE_NAME_LENGTH_GOOGLE_EXPORT = 46;
export async function extractMetadata(
worker: Remote<DedicatedCryptoWorker>,
receivedFile: File | ElectronFile,
- fileTypeInfo: FileTypeInfo
+ fileTypeInfo: FileTypeInfo,
): Promise<ExtractMetadataResult> {
let extractedMetadata: ParsedExtractedMetadata = NULL_EXTRACTED_METADATA;
if (fileTypeInfo.fileType === FILE_TYPE.IMAGE) {
@@ -83,7 +83,7 @@ export async function extractMetadata(
export async function getImageMetadata(
receivedFile: File | ElectronFile,
- fileTypeInfo: FileTypeInfo
+ fileTypeInfo: FileTypeInfo,
): Promise<ParsedExtractedMetadata> {
let imageMetadata = NULL_EXTRACTED_METADATA;
try {
@@ -93,13 +93,13 @@ export async function getImageMetadata(
receivedFile.name,
{
lastModified: receivedFile.lastModified,
- }
+ },
);
}
const exifData = await getParsedExifData(
receivedFile,
fileTypeInfo,
- EXIF_TAGS_NEEDED
+ EXIF_TAGS_NEEDED,
);
imageMetadata = {
@@ -109,21 +109,21 @@ export async function getImageMetadata(
height: exifData?.imageHeight ?? null,
};
} catch (e) {
- logError(e, 'getExifData failed');
+ logError(e, "getExifData failed");
}
return imageMetadata;
}
export const getMetadataJSONMapKeyForJSON = (
collectionID: number,
- jsonFileName: string
+ jsonFileName: string,
) => {
- let title = jsonFileName.slice(0, -1 * '.json'.length);
+ let title = jsonFileName.slice(0, -1 * ".json".length);
const endsWithNumberedSuffixWithBrackets = title.match(/\(\d+\)$/);
if (endsWithNumberedSuffixWithBrackets) {
title = title.slice(
0,
- -1 * endsWithNumberedSuffixWithBrackets[0].length
+ -1 * endsWithNumberedSuffixWithBrackets[0].length,
);
const [name, extension] = splitFilenameAndExtension(title);
return `${collectionID}-${name}${endsWithNumberedSuffixWithBrackets[0]}.${extension}`;
@@ -135,17 +135,17 @@ export const getMetadataJSONMapKeyForJSON = (
// so we need to use the clipped file name to get the metadataJSON file
export const getClippedMetadataJSONMapKeyForFile = (
collectionID: number,
- fileName: string
+ fileName: string,
) => {
return `${collectionID}-${fileName.slice(
0,
- MAX_FILE_NAME_LENGTH_GOOGLE_EXPORT
+ MAX_FILE_NAME_LENGTH_GOOGLE_EXPORT,
)}`;
};
export const getMetadataJSONMapKeyForFile = (
collectionID: number,
- fileName: string
+ fileName: string,
) => {
return `${collectionID}-${getFileOriginalName(fileName)}`;
};
@@ -155,7 +155,7 @@ export async function parseMetadataJSON(receivedFile: File | ElectronFile) {
if (!(receivedFile instanceof File)) {
receivedFile = new File(
[await receivedFile.blob()],
- receivedFile.name
+ receivedFile.name,
);
}
const metadataJSON: object = JSON.parse(await receivedFile.text());
@@ -167,38 +167,38 @@ export async function parseMetadataJSON(receivedFile: File | ElectronFile) {
}
if (
- metadataJSON['photoTakenTime'] &&
- metadataJSON['photoTakenTime']['timestamp']
+ metadataJSON["photoTakenTime"] &&
+ metadataJSON["photoTakenTime"]["timestamp"]
) {
parsedMetadataJSON.creationTime =
- metadataJSON['photoTakenTime']['timestamp'] * 1000000;
+ metadataJSON["photoTakenTime"]["timestamp"] * 1000000;
} else if (
- metadataJSON['creationTime'] &&
- metadataJSON['creationTime']['timestamp']
+ metadataJSON["creationTime"] &&
+ metadataJSON["creationTime"]["timestamp"]
) {
parsedMetadataJSON.creationTime =
- metadataJSON['creationTime']['timestamp'] * 1000000;
+ metadataJSON["creationTime"]["timestamp"] * 1000000;
}
if (
- metadataJSON['modificationTime'] &&
- metadataJSON['modificationTime']['timestamp']
+ metadataJSON["modificationTime"] &&
+ metadataJSON["modificationTime"]["timestamp"]
) {
parsedMetadataJSON.modificationTime =
- metadataJSON['modificationTime']['timestamp'] * 1000000;
+ metadataJSON["modificationTime"]["timestamp"] * 1000000;
}
let locationData: Location = NULL_LOCATION;
if (
- metadataJSON['geoData'] &&
- (metadataJSON['geoData']['latitude'] !== 0.0 ||
- metadataJSON['geoData']['longitude'] !== 0.0)
+ metadataJSON["geoData"] &&
+ (metadataJSON["geoData"]["latitude"] !== 0.0 ||
+ metadataJSON["geoData"]["longitude"] !== 0.0)
) {
- locationData = metadataJSON['geoData'];
+ locationData = metadataJSON["geoData"];
} else if (
- metadataJSON['geoDataExif'] &&
- (metadataJSON['geoDataExif']['latitude'] !== 0.0 ||
- metadataJSON['geoDataExif']['longitude'] !== 0.0)
+ metadataJSON["geoDataExif"] &&
+ (metadataJSON["geoDataExif"]["latitude"] !== 0.0 ||
+ metadataJSON["geoDataExif"]["longitude"] !== 0.0)
) {
- locationData = metadataJSON['geoDataExif'];
+ locationData = metadataJSON["geoDataExif"];
}
if (locationData !== null) {
parsedMetadataJSON.latitude = locationData.latitude;
@@ -206,7 +206,7 @@ export async function parseMetadataJSON(receivedFile: File | ElectronFile) {
}
return parsedMetadataJSON;
} catch (e) {
- logError(e, 'parseMetadataJSON failed');
+ logError(e, "parseMetadataJSON failed");
// ignore
}
}
@@ -216,17 +216,17 @@ export function extractDateFromFileName(filename: string): number {
try {
filename = filename.trim();
let parsedDate: Date;
- if (filename.startsWith('IMG-') || filename.startsWith('VID-')) {
+ if (filename.startsWith("IMG-") || filename.startsWith("VID-")) {
// Whatsapp media files
// sample name IMG-20171218-WA0028.jpg
- parsedDate = parseDateFromFusedDateString(filename.split('-')[1]);
- } else if (filename.startsWith('Screenshot_')) {
+ parsedDate = parseDateFromFusedDateString(filename.split("-")[1]);
+ } else if (filename.startsWith("Screenshot_")) {
// Screenshots on droid
// sample name Screenshot_20181227-152914.jpg
parsedDate = parseDateFromFusedDateString(
- filename.replaceAll('Screenshot_', '')
+ filename.replaceAll("Screenshot_", ""),
);
- } else if (filename.startsWith('signal-')) {
+ } else if (filename.startsWith("signal-")) {
// signal images
// sample name :signal-2018-08-21-100217.jpg
const dateString = convertSignalNameToFusedDateString(filename);
@@ -237,17 +237,17 @@ export function extractDateFromFileName(filename: string): number {
}
return validateAndGetCreationUnixTimeInMicroSeconds(parsedDate);
} catch (e) {
- logError(e, 'failed to extract date From FileName ');
+ logError(e, "failed to extract date From FileName ");
return null;
}
}
function convertSignalNameToFusedDateString(filename: string) {
- const dateStringParts = filename.split('-');
+ const dateStringParts = filename.split("-");
return `${dateStringParts[1]}${dateStringParts[2]}${dateStringParts[3]}-${dateStringParts[4]}`;
}
-const EDITED_FILE_SUFFIX = '-edited';
+const EDITED_FILE_SUFFIX = "-edited";
/*
Get the original file name for edited file to associate it to original file's metadataJSON file
@@ -262,13 +262,13 @@ function getFileOriginalName(fileName: string) {
if (isEditedFile) {
originalName = nameWithoutExtension.slice(
0,
- -1 * EDITED_FILE_SUFFIX.length
+ -1 * EDITED_FILE_SUFFIX.length,
);
} else {
originalName = nameWithoutExtension;
}
if (extension) {
- originalName += '.' + extension;
+ originalName += "." + extension;
}
return originalName;
}
diff --git a/apps/photos/src/services/upload/multiPartUploadService.ts b/apps/photos/src/services/upload/multiPartUploadService.ts
index 8ab800b279..1b4442710f 100644
--- a/apps/photos/src/services/upload/multiPartUploadService.ts
+++ b/apps/photos/src/services/upload/multiPartUploadService.ts
@@ -1,14 +1,14 @@
+import { CustomError } from "@ente/shared/error";
import {
FILE_CHUNKS_COMBINED_FOR_A_UPLOAD_PART,
RANDOM_PERCENTAGE_PROGRESS_FOR_PUT,
-} from 'constants/upload';
-import UIService from './uiService';
-import UploadHttpClient from './uploadHttpClient';
-import * as convert from 'xml-js';
-import { CustomError } from '@ente/shared/error';
-import { DataStream, Logger, MultipartUploadURLs } from 'types/upload';
-import uploadCancelService from './uploadCancelService';
-import uploadService from './uploadService';
+} from "constants/upload";
+import { DataStream, Logger, MultipartUploadURLs } from "types/upload";
+import * as convert from "xml-js";
+import UIService from "./uiService";
+import uploadCancelService from "./uploadCancelService";
+import UploadHttpClient from "./uploadHttpClient";
+import uploadService from "./uploadService";
interface PartEtag {
PartNumber: number;
@@ -17,14 +17,14 @@ interface PartEtag {
function calculatePartCount(chunkCount: number) {
const partCount = Math.ceil(
- chunkCount / FILE_CHUNKS_COMBINED_FOR_A_UPLOAD_PART
+ chunkCount / FILE_CHUNKS_COMBINED_FOR_A_UPLOAD_PART,
);
return partCount;
}
export async function uploadStreamUsingMultipart(
logger: Logger,
fileLocalID: number,
- dataStream: DataStream
+ dataStream: DataStream,
) {
const uploadPartCount = calculatePartCount(dataStream.chunkCount);
logger(`fetching ${uploadPartCount} urls for multipart upload`);
@@ -37,7 +37,7 @@ export async function uploadStreamUsingMultipart(
multipartUploadURLs,
dataStream.stream,
fileLocalID,
- uploadPartCount
+ uploadPartCount,
);
return fileObjectKey;
}
@@ -47,7 +47,7 @@ export async function uploadStreamInParts(
multipartUploadURLs: MultipartUploadURLs,
dataStream: ReadableStream<Uint8Array>,
fileLocalID: number,
- uploadPartCount: number
+ uploadPartCount: number,
) {
const streamReader = dataStream.getReader();
const percentPerPart = getRandomProgressPerPartUpload(uploadPartCount);
@@ -64,20 +64,20 @@ export async function uploadStreamInParts(
const progressTracker = UIService.trackUploadProgress(
fileLocalID,
percentPerPart,
- index
+ index,
);
let eTag = null;
if (!uploadService.getIsCFUploadProxyDisabled()) {
eTag = await UploadHttpClient.putFilePartV2(
fileUploadURL,
uploadChunk,
- progressTracker
+ progressTracker,
);
} else {
eTag = await UploadHttpClient.putFilePart(
fileUploadURL,
uploadChunk,
- progressTracker
+ progressTracker,
);
}
partEtags.push({ PartNumber: index + 1, ETag: eTag });
@@ -100,7 +100,7 @@ function getRandomProgressPerPartUpload(uploadPartCount: number) {
}
async function combineChunksToFormUploadPart(
- streamReader: ReadableStreamDefaultReader<Uint8Array>
+ streamReader: ReadableStreamDefaultReader<Uint8Array>,
) {
const combinedChunks = [];
for (let i = 0; i < FILE_CHUNKS_COMBINED_FOR_A_UPLOAD_PART; i++) {
@@ -117,12 +117,12 @@ async function combineChunksToFormUploadPart(
async function completeMultipartUpload(
partEtags: PartEtag[],
- completeURL: string
+ completeURL: string,
) {
const options = { compact: true, ignoreComment: true, spaces: 4 };
const body = convert.js2xml(
{ CompleteMultipartUpload: { Part: partEtags } },
- options
+ options,
);
if (!uploadService.getIsCFUploadProxyDisabled()) {
await UploadHttpClient.completeMultipartUploadV2(completeURL, body);
diff --git a/apps/photos/src/services/upload/publicUploadHttpClient.ts b/apps/photos/src/services/upload/publicUploadHttpClient.ts
index 70fff0b1b8..3144d78934 100644
--- a/apps/photos/src/services/upload/publicUploadHttpClient.ts
+++ b/apps/photos/src/services/upload/publicUploadHttpClient.ts
@@ -1,10 +1,10 @@
-import HTTPService from '@ente/shared/network/HTTPService';
-import { getEndpoint } from '@ente/shared/network/api';
-import { logError } from '@ente/shared/sentry';
-import { EnteFile } from 'types/file';
-import { CustomError, handleUploadError } from '@ente/shared/error';
-import { UploadFile, UploadURL, MultipartUploadURLs } from 'types/upload';
-import { retryHTTPCall } from 'utils/upload/uploadRetrier';
+import { CustomError, handleUploadError } from "@ente/shared/error";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getEndpoint } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import { EnteFile } from "types/file";
+import { MultipartUploadURLs, UploadFile, UploadURL } from "types/upload";
+import { retryHTTPCall } from "utils/upload/uploadRetrier";
const ENDPOINT = getEndpoint();
@@ -16,7 +16,7 @@ class PublicUploadHttpClient {
async uploadFile(
uploadFile: UploadFile,
token: string,
- passwordToken: string
+ passwordToken: string,
): Promise<EnteFile> {
try {
if (!token) {
@@ -29,17 +29,17 @@ class PublicUploadHttpClient {
uploadFile,
null,
{
- 'X-Auth-Access-Token': token,
+ "X-Auth-Access-Token": token,
...(passwordToken && {
- 'X-Auth-Access-Token-JWT': passwordToken,
+ "X-Auth-Access-Token-JWT": passwordToken,
}),
- }
+ },
),
- handleUploadError
+ handleUploadError,
);
return response.data;
} catch (e) {
- logError(e, 'upload public File Failed');
+ logError(e, "upload public File Failed");
throw e;
}
}
@@ -48,7 +48,7 @@ class PublicUploadHttpClient {
count: number,
urlStore: UploadURL[],
token: string,
- passwordToken: string
+ passwordToken: string,
): Promise<void> {
try {
if (!this.uploadURLFetchInProgress) {
@@ -62,14 +62,14 @@ class PublicUploadHttpClient {
count: Math.min(MAX_URL_REQUESTS, count * 2),
},
{
- 'X-Auth-Access-Token': token,
+ "X-Auth-Access-Token": token,
...(passwordToken && {
- 'X-Auth-Access-Token-JWT': passwordToken,
+ "X-Auth-Access-Token-JWT": passwordToken,
}),
- }
+ },
);
const response = await this.uploadURLFetchInProgress;
- for (const url of response.data['urls']) {
+ for (const url of response.data["urls"]) {
urlStore.push(url);
}
} finally {
@@ -78,7 +78,7 @@ class PublicUploadHttpClient {
}
return this.uploadURLFetchInProgress;
} catch (e) {
- logError(e, 'fetch public upload-url failed ');
+ logError(e, "fetch public upload-url failed ");
throw e;
}
}
@@ -86,7 +86,7 @@ class PublicUploadHttpClient {
async fetchMultipartUploadURLs(
count: number,
token: string,
- passwordToken: string
+ passwordToken: string,
): Promise<MultipartUploadURLs> {
try {
if (!token) {
@@ -98,16 +98,16 @@ class PublicUploadHttpClient {
count,
},
{
- 'X-Auth-Access-Token': token,
+ "X-Auth-Access-Token": token,
...(passwordToken && {
- 'X-Auth-Access-Token-JWT': passwordToken,
+ "X-Auth-Access-Token-JWT": passwordToken,
}),
- }
+ },
);
- return response.data['urls'];
+ return response.data["urls"];
} catch (e) {
- logError(e, 'fetch public multipart-upload-url failed');
+ logError(e, "fetch public multipart-upload-url failed");
throw e;
}
}
diff --git a/apps/photos/src/services/upload/thumbnailService.ts b/apps/photos/src/services/upload/thumbnailService.ts
index 5d6422bf47..8b1cf7a617 100644
--- a/apps/photos/src/services/upload/thumbnailService.ts
+++ b/apps/photos/src/services/upload/thumbnailService.ts
@@ -1,17 +1,17 @@
-import { FILE_TYPE } from 'constants/file';
-import { CustomError, errorWithContext } from '@ente/shared/error';
-import { logError } from '@ente/shared/sentry';
-import { BLACK_THUMBNAIL_BASE64 } from 'constants/upload';
-import * as FFmpegService from 'services/ffmpeg/ffmpegService';
-import { convertBytesToHumanReadable } from '@ente/shared/utils/size';
-import { ElectronFile, FileTypeInfo } from 'types/upload';
-import { getUint8ArrayView } from '../readerService';
-import { addLogLine } from '@ente/shared/logging';
-import { getFileNameSize } from '@ente/shared/logging/web';
-import HeicConversionService from 'services/heicConversionService';
-import { isFileHEIC } from 'utils/file';
-import isElectron from 'is-electron';
-import imageProcessor from 'services/imageProcessor';
+import { CustomError, errorWithContext } from "@ente/shared/error";
+import { addLogLine } from "@ente/shared/logging";
+import { getFileNameSize } from "@ente/shared/logging/web";
+import { logError } from "@ente/shared/sentry";
+import { convertBytesToHumanReadable } from "@ente/shared/utils/size";
+import { FILE_TYPE } from "constants/file";
+import { BLACK_THUMBNAIL_BASE64 } from "constants/upload";
+import isElectron from "is-electron";
+import * as FFmpegService from "services/ffmpeg/ffmpegService";
+import HeicConversionService from "services/heicConversionService";
+import imageProcessor from "services/imageProcessor";
+import { ElectronFile, FileTypeInfo } from "types/upload";
+import { isFileHEIC } from "utils/file";
+import { getUint8ArrayView } from "../readerService";
const MAX_THUMBNAIL_DIMENSION = 720;
const MIN_COMPRESSION_PERCENTAGE_SIZE_DIFF = 10;
@@ -28,7 +28,7 @@ interface Dimension {
export async function generateThumbnail(
file: File | ElectronFile,
- fileTypeInfo: FileTypeInfo
+ fileTypeInfo: FileTypeInfo,
): Promise<{ thumbnail: Uint8Array; hasStaticThumbnail: boolean }> {
try {
addLogLine(`generating thumbnail for ${getFileNameSize(file)}`);
@@ -42,54 +42,54 @@ export async function generateThumbnail(
}
if (thumbnail.length > 1.5 * MAX_THUMBNAIL_SIZE) {
logError(
- Error('thumbnail_too_large'),
- 'thumbnail greater than max limit',
+ Error("thumbnail_too_large"),
+ "thumbnail greater than max limit",
{
thumbnailSize: convertBytesToHumanReadable(
- thumbnail.length
+ thumbnail.length,
),
fileSize: convertBytesToHumanReadable(file.size),
fileType: fileTypeInfo.exactType,
- }
+ },
);
}
if (thumbnail.length === 0) {
- throw Error('EMPTY THUMBNAIL');
+ throw Error("EMPTY THUMBNAIL");
}
addLogLine(
- `thumbnail successfully generated ${getFileNameSize(file)}`
+ `thumbnail successfully generated ${getFileNameSize(file)}`,
);
} catch (e) {
- logError(e, 'uploading static thumbnail', {
+ logError(e, "uploading static thumbnail", {
fileFormat: fileTypeInfo.exactType,
});
addLogLine(
`thumbnail generation failed ${getFileNameSize(file)} error: ${
e.message
- }`
+ }`,
);
thumbnail = Uint8Array.from(atob(BLACK_THUMBNAIL_BASE64), (c) =>
- c.charCodeAt(0)
+ c.charCodeAt(0),
);
hasStaticThumbnail = true;
}
return { thumbnail, hasStaticThumbnail };
} catch (e) {
- logError(e, 'Error generating static thumbnail');
+ logError(e, "Error generating static thumbnail");
throw e;
}
}
async function generateImageThumbnail(
file: File | ElectronFile,
- fileTypeInfo: FileTypeInfo
+ fileTypeInfo: FileTypeInfo,
) {
if (isElectron()) {
try {
return await imageProcessor.generateImageThumbnail(
file,
MAX_THUMBNAIL_DIMENSION,
- MAX_THUMBNAIL_SIZE
+ MAX_THUMBNAIL_SIZE,
);
} catch (e) {
return await generateImageThumbnailUsingCanvas(file, fileTypeInfo);
@@ -101,10 +101,10 @@ async function generateImageThumbnail(
export async function generateImageThumbnailUsingCanvas(
file: File | ElectronFile,
- fileTypeInfo: FileTypeInfo
+ fileTypeInfo: FileTypeInfo,
) {
- const canvas = document.createElement('canvas');
- const canvasCTX = canvas.getContext('2d');
+ const canvas = document.createElement("canvas");
+ const canvasCTX = canvas.getContext("2d");
let imageURL = null;
let timeout = null;
@@ -112,7 +112,7 @@ export async function generateImageThumbnailUsingCanvas(
if (isHEIC) {
addLogLine(`HEICConverter called for ${getFileNameSize(file)}`);
const convertedBlob = await HeicConversionService.convert(
- new Blob([await file.arrayBuffer()])
+ new Blob([await file.arrayBuffer()]),
);
file = new File([convertedBlob], file.name);
addLogLine(`${getFileNameSize(file)} successfully converted`);
@@ -120,7 +120,7 @@ export async function generateImageThumbnailUsingCanvas(
let image = new Image();
imageURL = URL.createObjectURL(new Blob([await file.arrayBuffer()]));
await new Promise((resolve, reject) => {
- image.setAttribute('src', imageURL);
+ image.setAttribute("src", imageURL);
image.onload = () => {
try {
URL.revokeObjectURL(imageURL);
@@ -130,7 +130,7 @@ export async function generateImageThumbnailUsingCanvas(
};
const thumbnailDimension = calculateThumbnailDimension(
imageDimension,
- MAX_THUMBNAIL_DIMENSION
+ MAX_THUMBNAIL_DIMENSION,
);
canvas.width = thumbnailDimension.width;
canvas.height = thumbnailDimension.height;
@@ -139,7 +139,7 @@ export async function generateImageThumbnailUsingCanvas(
0,
0,
thumbnailDimension.width,
- thumbnailDimension.height
+ thumbnailDimension.height,
);
image = null;
clearTimeout(timeout);
@@ -147,14 +147,14 @@ export async function generateImageThumbnailUsingCanvas(
} catch (e) {
const err = errorWithContext(
e,
- `${CustomError.THUMBNAIL_GENERATION_FAILED} err: ${e}`
+ `${CustomError.THUMBNAIL_GENERATION_FAILED} err: ${e}`,
);
reject(err);
}
};
timeout = setTimeout(
() => reject(Error(CustomError.WAIT_TIME_EXCEEDED)),
- WAIT_TIME_THUMBNAIL_GENERATION
+ WAIT_TIME_THUMBNAIL_GENERATION,
);
});
const thumbnailBlob = await getCompressedThumbnailBlobFromCanvas(canvas);
@@ -163,26 +163,26 @@ export async function generateImageThumbnailUsingCanvas(
async function generateVideoThumbnail(
file: File | ElectronFile,
- fileTypeInfo: FileTypeInfo
+ fileTypeInfo: FileTypeInfo,
) {
let thumbnail: Uint8Array;
try {
addLogLine(
- `ffmpeg generateThumbnail called for ${getFileNameSize(file)}`
+ `ffmpeg generateThumbnail called for ${getFileNameSize(file)}`,
);
const thumbnail = await FFmpegService.generateVideoThumbnail(file);
addLogLine(
- `ffmpeg thumbnail successfully generated ${getFileNameSize(file)}`
+ `ffmpeg thumbnail successfully generated ${getFileNameSize(file)}`,
);
return await getUint8ArrayView(thumbnail);
} catch (e) {
addLogLine(
`ffmpeg thumbnail generated failed ${getFileNameSize(
- file
- )} error: ${e.message}`
+ file,
+ )} error: ${e.message}`,
);
- logError(e, 'failed to generate thumbnail using ffmpeg', {
+ logError(e, "failed to generate thumbnail using ffmpeg", {
fileFormat: fileTypeInfo.exactType,
});
thumbnail = await generateVideoThumbnailUsingCanvas(file);
@@ -191,24 +191,24 @@ async function generateVideoThumbnail(
}
export async function generateVideoThumbnailUsingCanvas(
- file: File | ElectronFile
+ file: File | ElectronFile,
) {
- const canvas = document.createElement('canvas');
- const canvasCTX = canvas.getContext('2d');
+ const canvas = document.createElement("canvas");
+ const canvasCTX = canvas.getContext("2d");
let timeout = null;
let videoURL = null;
- let video = document.createElement('video');
+ let video = document.createElement("video");
videoURL = URL.createObjectURL(new Blob([await file.arrayBuffer()]));
await new Promise((resolve, reject) => {
- video.preload = 'metadata';
+ video.preload = "metadata";
video.src = videoURL;
- video.addEventListener('loadeddata', function () {
+ video.addEventListener("loadeddata", function () {
try {
URL.revokeObjectURL(videoURL);
if (!video) {
- throw Error('video load failed');
+ throw Error("video load failed");
}
const videoDimension = {
width: video.videoWidth,
@@ -216,7 +216,7 @@ export async function generateVideoThumbnailUsingCanvas(
};
const thumbnailDimension = calculateThumbnailDimension(
videoDimension,
- MAX_THUMBNAIL_DIMENSION
+ MAX_THUMBNAIL_DIMENSION,
);
canvas.width = thumbnailDimension.width;
canvas.height = thumbnailDimension.height;
@@ -225,14 +225,14 @@ export async function generateVideoThumbnailUsingCanvas(
0,
0,
thumbnailDimension.width,
- thumbnailDimension.height
+ thumbnailDimension.height,
);
video = null;
clearTimeout(timeout);
resolve(null);
} catch (e) {
const err = Error(
- `${CustomError.THUMBNAIL_GENERATION_FAILED} err: ${e}`
+ `${CustomError.THUMBNAIL_GENERATION_FAILED} err: ${e}`,
);
logError(e, CustomError.THUMBNAIL_GENERATION_FAILED);
reject(err);
@@ -240,7 +240,7 @@ export async function generateVideoThumbnailUsingCanvas(
});
timeout = setTimeout(
() => reject(Error(CustomError.WAIT_TIME_EXCEEDED)),
- WAIT_TIME_THUMBNAIL_GENERATION
+ WAIT_TIME_THUMBNAIL_GENERATION,
);
});
const thumbnailBlob = await getCompressedThumbnailBlobFromCanvas(canvas);
@@ -261,8 +261,8 @@ async function getCompressedThumbnailBlobFromCanvas(canvas: HTMLCanvasElement) {
function (blob) {
resolve(blob);
},
- 'image/jpeg',
- quality
+ "image/jpeg",
+ quality,
);
});
thumbnailBlob = thumbnailBlob ?? new Blob([]);
@@ -279,7 +279,7 @@ async function getCompressedThumbnailBlobFromCanvas(canvas: HTMLCanvasElement) {
function percentageSizeDiff(
newThumbnailSize: number,
- oldThumbnailSize: number
+ oldThumbnailSize: number,
) {
return ((oldThumbnailSize - newThumbnailSize) * 100) / oldThumbnailSize;
}
@@ -288,7 +288,7 @@ function percentageSizeDiff(
// returns {0,0} for invalid inputs
function calculateThumbnailDimension(
originalDimension: Dimension,
- maxDimension: number
+ maxDimension: number,
): Dimension {
if (originalDimension.height === 0 || originalDimension.width === 0) {
return { width: 0, height: 0 };
diff --git a/apps/photos/src/services/upload/uiService.ts b/apps/photos/src/services/upload/uiService.ts
index 74ed8b8b8e..13dd780019 100644
--- a/apps/photos/src/services/upload/uiService.ts
+++ b/apps/photos/src/services/upload/uiService.ts
@@ -1,18 +1,18 @@
-import { Canceler } from 'axios';
+import { CustomError } from "@ente/shared/error";
+import { Canceler } from "axios";
import {
- UPLOAD_RESULT,
RANDOM_PERCENTAGE_PROGRESS_FOR_PUT,
+ UPLOAD_RESULT,
UPLOAD_STAGES,
-} from 'constants/upload';
+} from "constants/upload";
import {
FinishedUploads,
InProgressUpload,
InProgressUploads,
ProgressUpdater,
SegregatedFinishedUploads,
-} from 'types/upload/ui';
-import { CustomError } from '@ente/shared/error';
-import uploadCancelService from './uploadCancelService';
+} from "types/upload/ui";
+import uploadCancelService from "./uploadCancelService";
const REQUEST_TIMEOUT_TIME = 30 * 1000; // 30 sec;
class UIService {
@@ -42,10 +42,10 @@ class UIService {
total: this.totalFilesCount,
});
this.progressUpdater.setInProgressUploads(
- convertInProgressUploadsToList(this.inProgressUploads)
+ convertInProgressUploadsToList(this.inProgressUploads),
);
this.progressUpdater.setFinishedUploads(
- segregatedFinishedUploadsToList(this.finishedUploads)
+ segregatedFinishedUploadsToList(this.finishedUploads),
);
}
@@ -104,7 +104,7 @@ class UIService {
hasFilesInResultList() {
const finishedUploadsList = segregatedFinishedUploadsToList(
- this.finishedUploads
+ this.finishedUploads,
);
for (const x of finishedUploadsList.values()) {
if (x.length > 0) {
@@ -141,17 +141,17 @@ class UIService {
setPercentComplete(percentComplete);
setInProgressUploads(
- convertInProgressUploadsToList(this.inProgressUploads)
+ convertInProgressUploadsToList(this.inProgressUploads),
);
setFinishedUploads(
- segregatedFinishedUploadsToList(this.finishedUploads)
+ segregatedFinishedUploadsToList(this.finishedUploads),
);
}
trackUploadProgress(
fileLocalID: number,
percentPerPart = RANDOM_PERCENTAGE_PROGRESS_FOR_PUT(),
- index = 0
+ index = 0,
) {
const cancel: { exec: Canceler } = { exec: () => {} };
const cancelTimedOutRequest = () =>
@@ -175,10 +175,10 @@ class UIService {
Math.min(
Math.round(
percentPerPart * index +
- (percentPerPart * event.loaded) / event.total
+ (percentPerPart * event.loaded) / event.total,
),
- 98
- )
+ 98,
+ ),
);
this.updateProgressBarUI();
if (event.loaded === event.total) {
@@ -202,7 +202,7 @@ function convertInProgressUploadsToList(inProgressUploads) {
({
localFileID,
progress,
- }) as InProgressUpload
+ }) as InProgressUpload,
);
}
diff --git a/apps/photos/src/services/upload/uploadHttpClient.ts b/apps/photos/src/services/upload/uploadHttpClient.ts
index 4c6cb507d8..3855562dd3 100644
--- a/apps/photos/src/services/upload/uploadHttpClient.ts
+++ b/apps/photos/src/services/upload/uploadHttpClient.ts
@@ -1,11 +1,11 @@
-import HTTPService from '@ente/shared/network/HTTPService';
-import { getEndpoint, getUploadEndpoint } from '@ente/shared/network/api';
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
-import { logError } from '@ente/shared/sentry';
-import { EnteFile } from 'types/file';
-import { CustomError, handleUploadError } from '@ente/shared/error';
-import { UploadFile, UploadURL, MultipartUploadURLs } from 'types/upload';
-import { retryHTTPCall } from 'utils/upload/uploadRetrier';
+import { CustomError, handleUploadError } from "@ente/shared/error";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getEndpoint, getUploadEndpoint } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
+import { EnteFile } from "types/file";
+import { MultipartUploadURLs, UploadFile, UploadURL } from "types/upload";
+import { retryHTTPCall } from "utils/upload/uploadRetrier";
const ENDPOINT = getEndpoint();
const UPLOAD_ENDPOINT = getUploadEndpoint();
@@ -24,13 +24,13 @@ class UploadHttpClient {
const response = await retryHTTPCall(
() =>
HTTPService.post(`${ENDPOINT}/files`, uploadFile, null, {
- 'X-Auth-Token': token,
+ "X-Auth-Token": token,
}),
- handleUploadError
+ handleUploadError,
);
return response.data;
} catch (e) {
- logError(e, 'upload Files Failed');
+ logError(e, "upload Files Failed");
throw e;
}
}
@@ -48,10 +48,10 @@ class UploadHttpClient {
{
count: Math.min(MAX_URL_REQUESTS, count * 2),
},
- { 'X-Auth-Token': token }
+ { "X-Auth-Token": token },
);
const response = await this.uploadURLFetchInProgress;
- for (const url of response.data['urls']) {
+ for (const url of response.data["urls"]) {
urlStore.push(url);
}
} finally {
@@ -60,13 +60,13 @@ class UploadHttpClient {
}
return this.uploadURLFetchInProgress;
} catch (e) {
- logError(e, 'fetch upload-url failed ');
+ logError(e, "fetch upload-url failed ");
throw e;
}
}
async fetchMultipartUploadURLs(
- count: number
+ count: number,
): Promise<MultipartUploadURLs> {
try {
const token = getToken();
@@ -78,12 +78,12 @@ class UploadHttpClient {
{
count,
},
- { 'X-Auth-Token': token }
+ { "X-Auth-Token": token },
);
- return response.data['urls'];
+ return response.data["urls"];
} catch (e) {
- logError(e, 'fetch multipart-upload-url failed');
+ logError(e, "fetch multipart-upload-url failed");
throw e;
}
}
@@ -91,7 +91,7 @@ class UploadHttpClient {
async putFile(
fileUploadURL: UploadURL,
file: Uint8Array,
- progressTracker
+ progressTracker,
): Promise<string> {
try {
await retryHTTPCall(
@@ -101,14 +101,14 @@ class UploadHttpClient {
file,
null,
null,
- progressTracker
+ progressTracker,
),
- handleUploadError
+ handleUploadError,
);
return fileUploadURL.objectKey;
} catch (e) {
if (e.message !== CustomError.UPLOAD_CANCELLED) {
- logError(e, 'putFile to dataStore failed ');
+ logError(e, "putFile to dataStore failed ");
}
throw e;
}
@@ -117,7 +117,7 @@ class UploadHttpClient {
async putFileV2(
fileUploadURL: UploadURL,
file: Uint8Array,
- progressTracker
+ progressTracker,
): Promise<string> {
try {
await retryHTTPCall(() =>
@@ -126,15 +126,15 @@ class UploadHttpClient {
file,
null,
{
- 'UPLOAD-URL': fileUploadURL.url,
+ "UPLOAD-URL": fileUploadURL.url,
},
- progressTracker
- )
+ progressTracker,
+ ),
);
return fileUploadURL.objectKey;
} catch (e) {
if (e.message !== CustomError.UPLOAD_CANCELLED) {
- logError(e, 'putFile to dataStore failed ');
+ logError(e, "putFile to dataStore failed ");
}
throw e;
}
@@ -143,7 +143,7 @@ class UploadHttpClient {
async putFilePart(
partUploadURL: string,
filePart: Uint8Array,
- progressTracker
+ progressTracker,
) {
try {
const response = await retryHTTPCall(async () => {
@@ -152,11 +152,11 @@ class UploadHttpClient {
filePart,
null,
null,
- progressTracker
+ progressTracker,
);
if (!resp?.headers?.etag) {
const err = Error(CustomError.ETAG_MISSING);
- logError(err, 'putFile in parts failed');
+ logError(err, "putFile in parts failed");
throw err;
}
return resp;
@@ -164,7 +164,7 @@ class UploadHttpClient {
return response.headers.etag as string;
} catch (e) {
if (e.message !== CustomError.UPLOAD_CANCELLED) {
- logError(e, 'put filePart failed');
+ logError(e, "put filePart failed");
}
throw e;
}
@@ -173,7 +173,7 @@ class UploadHttpClient {
async putFilePartV2(
partUploadURL: string,
filePart: Uint8Array,
- progressTracker
+ progressTracker,
) {
try {
const response = await retryHTTPCall(async () => {
@@ -182,13 +182,13 @@ class UploadHttpClient {
filePart,
null,
{
- 'UPLOAD-URL': partUploadURL,
+ "UPLOAD-URL": partUploadURL,
},
- progressTracker
+ progressTracker,
);
if (!resp?.data?.etag) {
const err = Error(CustomError.ETAG_MISSING);
- logError(err, 'putFile in parts failed');
+ logError(err, "putFile in parts failed");
throw err;
}
return resp;
@@ -196,7 +196,7 @@ class UploadHttpClient {
return response.data.etag as string;
} catch (e) {
if (e.message !== CustomError.UPLOAD_CANCELLED) {
- logError(e, 'put filePart failed');
+ logError(e, "put filePart failed");
}
throw e;
}
@@ -206,11 +206,11 @@ class UploadHttpClient {
try {
await retryHTTPCall(() =>
HTTPService.post(completeURL, reqBody, null, {
- 'content-type': 'text/xml',
- })
+ "content-type": "text/xml",
+ }),
);
} catch (e) {
- logError(e, 'put file in parts failed');
+ logError(e, "put file in parts failed");
throw e;
}
}
@@ -223,13 +223,13 @@ class UploadHttpClient {
reqBody,
null,
{
- 'content-type': 'text/xml',
- 'UPLOAD-URL': completeURL,
- }
- )
+ "content-type": "text/xml",
+ "UPLOAD-URL": completeURL,
+ },
+ ),
);
} catch (e) {
- logError(e, 'put file in parts failed');
+ logError(e, "put file in parts failed");
throw e;
}
}
diff --git a/apps/photos/src/services/upload/uploadManager.ts b/apps/photos/src/services/upload/uploadManager.ts
index f53759277e..734ae7bcb1 100644
--- a/apps/photos/src/services/upload/uploadManager.ts
+++ b/apps/photos/src/services/upload/uploadManager.ts
@@ -1,45 +1,47 @@
-import { getLocalFiles } from '../fileService';
-import { SetFiles } from 'types/gallery';
-import { sortFiles, decryptFile, getUserOwnedFiles } from 'utils/file';
-import { logError } from '@ente/shared/sentry';
-import { parseMetadataJSON } from './metadataService';
-import { getMetadataJSONMapKeyForJSON } from './metadataService';
-import {
- areFileWithCollectionsSame,
- segregateMetadataAndMediaFiles,
-} from 'utils/upload';
-import uploader from './uploader';
-import UIService from './uiService';
-import UploadService from './uploadService';
-import { eventBus, Events } from '@ente/shared/events';
-import { CustomError } from '@ente/shared/error';
-import { Collection } from 'types/collection';
-import { EncryptedEnteFile, EnteFile } from 'types/file';
+import { CustomError } from "@ente/shared/error";
+import { Events, eventBus } from "@ente/shared/events";
+import { logError } from "@ente/shared/sentry";
+import { Collection } from "types/collection";
+import { EncryptedEnteFile, EnteFile } from "types/file";
+import { SetFiles } from "types/gallery";
import {
FileWithCollection,
ParsedMetadataJSON,
ParsedMetadataJSONMap,
PublicUploadProps,
-} from 'types/upload';
-
-import { UPLOAD_RESULT, UPLOAD_STAGES } from 'constants/upload';
-import uiService from './uiService';
-import { addLogLine } from '@ente/shared/logging';
-import { getFileNameSize } from '@ente/shared/logging/web';
-import isElectron from 'is-electron';
-import ImportService from 'services/importService';
-import watchFolderService from 'services/watchFolder/watchFolderService';
-import { ProgressUpdater } from 'types/upload/ui';
-import uploadCancelService from './uploadCancelService';
-import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
-import { ComlinkWorker } from '@ente/shared/worker/comlinkWorker';
-import { Remote } from 'comlink';
+} from "types/upload";
+import { decryptFile, getUserOwnedFiles, sortFiles } from "utils/file";
+import {
+ areFileWithCollectionsSame,
+ segregateMetadataAndMediaFiles,
+} from "utils/upload";
+import { getLocalFiles } from "../fileService";
+import {
+ getMetadataJSONMapKeyForJSON,
+ parseMetadataJSON,
+} from "./metadataService";
+import UIService from "./uiService";
+import UploadService from "./uploadService";
+import uploader from "./uploader";
+
+import { getDedicatedCryptoWorker } from "@ente/shared/crypto";
+import { DedicatedCryptoWorker } from "@ente/shared/crypto/internal/crypto.worker";
+import { addLogLine } from "@ente/shared/logging";
+import { getFileNameSize } from "@ente/shared/logging/web";
+import { ComlinkWorker } from "@ente/shared/worker/comlinkWorker";
+import { Remote } from "comlink";
+import { UPLOAD_RESULT, UPLOAD_STAGES } from "constants/upload";
+import isElectron from "is-electron";
+import ImportService from "services/importService";
import {
getLocalPublicFiles,
getPublicCollectionUID,
-} from 'services/publicCollectionService';
-import { getDedicatedCryptoWorker } from '@ente/shared/crypto';
-import { getDisableCFUploadProxyFlag } from 'services/userService';
+} from "services/publicCollectionService";
+import { getDisableCFUploadProxyFlag } from "services/userService";
+import watchFolderService from "services/watchFolder/watchFolderService";
+import { ProgressUpdater } from "types/upload/ui";
+import uiService from "./uiService";
+import uploadCancelService from "./uploadCancelService";
const MAX_CONCURRENT_UPLOADS = 4;
@@ -62,7 +64,7 @@ class UploadManager {
progressUpdater: ProgressUpdater,
setFiles: SetFiles,
publicCollectProps: PublicUploadProps,
- isCFUploadProxyDisabled: boolean
+ isCFUploadProxyDisabled: boolean,
) {
UIService.init(progressUpdater);
const remoteIsCFUploadProxyDisabled =
@@ -102,20 +104,20 @@ class UploadManager {
async updateExistingFilesAndCollections(collections: Collection[]) {
if (this.publicUploadProps.accessedThroughSharedURL) {
this.existingFiles = await getLocalPublicFiles(
- getPublicCollectionUID(this.publicUploadProps.token)
+ getPublicCollectionUID(this.publicUploadProps.token),
);
} else {
this.existingFiles = getUserOwnedFiles(await getLocalFiles());
}
this.collections = new Map(
- collections.map((collection) => [collection.id, collection])
+ collections.map((collection) => [collection.id, collection]),
);
}
public async queueFilesForUpload(
filesWithCollectionToUploadIn: FileWithCollection[],
collections: Collection[],
- uploaderName?: string
+ uploaderName?: string,
) {
try {
if (this.uploadInProgress) {
@@ -125,15 +127,15 @@ class UploadManager {
await this.updateExistingFilesAndCollections(collections);
this.uploaderName = uploaderName;
addLogLine(
- `received ${filesWithCollectionToUploadIn.length} files to upload`
+ `received ${filesWithCollectionToUploadIn.length} files to upload`,
);
uiService.setFilenames(
new Map<number, string>(
filesWithCollectionToUploadIn.map((mediaFile) => [
mediaFile.localID,
UploadService.getAssetName(mediaFile),
- ])
- )
+ ]),
+ ),
);
const { metadataJSONFiles, mediaFiles } =
segregateMetadataAndMediaFiles(filesWithCollectionToUploadIn);
@@ -141,12 +143,12 @@ class UploadManager {
addLogLine(`has ${mediaFiles.length} media files`);
if (metadataJSONFiles.length) {
UIService.setUploadStage(
- UPLOAD_STAGES.READING_GOOGLE_METADATA_FILES
+ UPLOAD_STAGES.READING_GOOGLE_METADATA_FILES,
);
await this.parseMetadataJSONFiles(metadataJSONFiles);
UploadService.setParsedMetadataJSONMap(
- this.parsedMetadataJSONMap
+ this.parsedMetadataJSONMap,
);
}
if (mediaFiles.length) {
@@ -157,19 +159,19 @@ class UploadManager {
addLogLine(
`got live photos: ${
mediaFiles.length !== analysedMediaFiles.length
- }`
+ }`,
);
uiService.setFilenames(
new Map<number, string>(
analysedMediaFiles.map((mediaFile) => [
mediaFile.localID,
UploadService.getAssetName(mediaFile),
- ])
- )
+ ]),
+ ),
);
UIService.setHasLivePhoto(
- mediaFiles.length !== analysedMediaFiles.length
+ mediaFiles.length !== analysedMediaFiles.length,
);
await this.uploadMediaFiles(analysedMediaFiles);
@@ -181,7 +183,7 @@ class UploadManager {
ImportService.cancelRemainingUploads();
}
} else {
- logError(e, 'uploading failed with error');
+ logError(e, "uploading failed with error");
throw e;
}
} finally {
@@ -198,7 +200,7 @@ class UploadManager {
return false;
}
} catch (e) {
- logError(e, ' failed to return shouldCloseProgressBar');
+ logError(e, " failed to return shouldCloseProgressBar");
return false;
}
}
@@ -215,7 +217,7 @@ class UploadManager {
throw Error(CustomError.UPLOAD_CANCELLED);
}
addLogLine(
- `parsing metadata json file ${getFileNameSize(file)}`
+ `parsing metadata json file ${getFileNameSize(file)}`,
);
const parsedMetadataJSON = await parseMetadataJSON(file);
@@ -223,34 +225,34 @@ class UploadManager {
this.parsedMetadataJSONMap.set(
getMetadataJSONMapKeyForJSON(
collectionID,
- file.name
+ file.name,
),
- parsedMetadataJSON && { ...parsedMetadataJSON }
+ parsedMetadataJSON && { ...parsedMetadataJSON },
);
UIService.increaseFileUploaded();
}
addLogLine(
`successfully parsed metadata json file ${getFileNameSize(
- file
- )}`
+ file,
+ )}`,
);
} catch (e) {
if (e.message === CustomError.UPLOAD_CANCELLED) {
throw e;
} else {
// and don't break for subsequent files just log and move on
- logError(e, 'parsing failed for a file');
+ logError(e, "parsing failed for a file");
addLogLine(
`failed to parse metadata json file ${getFileNameSize(
- file
- )} error: ${e.message}`
+ file,
+ )} error: ${e.message}`,
);
}
}
}
} catch (e) {
if (e.message !== CustomError.UPLOAD_CANCELLED) {
- logError(e, 'error seeding MetadataMap');
+ logError(e, "error seeding MetadataMap");
}
throw e;
}
@@ -296,18 +298,18 @@ class UploadManager {
worker,
this.existingFiles,
fileWithCollection,
- this.uploaderName
+ this.uploaderName,
);
const finalUploadResult = await this.postUploadTask(
fileUploadResult,
uploadedFile,
- fileWithCollection
+ fileWithCollection,
);
UIService.moveFileToResultList(
fileWithCollection.localID,
- finalUploadResult
+ finalUploadResult,
);
UIService.increaseFileUploaded();
UploadService.reducePendingUploadCount();
@@ -317,12 +319,12 @@ class UploadManager {
async postUploadTask(
fileUploadResult: UPLOAD_RESULT,
uploadedFile: EncryptedEnteFile | EnteFile | null,
- fileWithCollection: FileWithCollection
+ fileWithCollection: FileWithCollection,
) {
try {
let decryptedFile: EnteFile;
addLogLine(
- `post upload action -> fileUploadResult: ${fileUploadResult} uploadedFile present ${!!uploadedFile}`
+ `post upload action -> fileUploadResult: ${fileUploadResult} uploadedFile present ${!!uploadedFile}`,
);
this.updateElectronRemainingFiles(fileWithCollection);
switch (fileUploadResult) {
@@ -341,7 +343,7 @@ class UploadManager {
case UPLOAD_RESULT.UPLOADED_WITH_STATIC_THUMBNAIL:
decryptedFile = await decryptFile(
uploadedFile as EncryptedEnteFile,
- fileWithCollection.collection.key
+ fileWithCollection.collection.key,
);
break;
case UPLOAD_RESULT.UNSUPPORTED:
@@ -349,7 +351,7 @@ class UploadManager {
// no-op
break;
default:
- throw Error('Invalid Upload Result' + fileUploadResult);
+ throw Error("Invalid Upload Result" + fileUploadResult);
}
if (
[
@@ -366,18 +368,18 @@ class UploadManager {
fileWithCollection.livePhotoAssets.image,
});
} catch (e) {
- logError(e, 'Error in fileUploaded handlers');
+ logError(e, "Error in fileUploaded handlers");
}
this.updateExistingFiles(decryptedFile);
}
await this.watchFolderCallback(
fileUploadResult,
fileWithCollection,
- uploadedFile as EncryptedEnteFile
+ uploadedFile as EncryptedEnteFile,
);
return fileUploadResult;
} catch (e) {
- logError(e, 'failed to do post file upload action');
+ logError(e, "failed to do post file upload action");
return UPLOAD_RESULT.FAILED;
}
}
@@ -385,19 +387,19 @@ class UploadManager {
private async watchFolderCallback(
fileUploadResult: UPLOAD_RESULT,
fileWithCollection: FileWithCollection,
- uploadedFile: EncryptedEnteFile
+ uploadedFile: EncryptedEnteFile,
) {
if (isElectron()) {
await watchFolderService.onFileUpload(
fileUploadResult,
fileWithCollection,
- uploadedFile
+ uploadedFile,
);
}
}
public cancelRunningUpload() {
- addLogLine('user cancelled running upload');
+ addLogLine("user cancelled running upload");
UIService.setUploadStage(UPLOAD_STAGES.CANCELLING);
uploadCancelService.requestUploadCancelation();
}
@@ -426,11 +428,11 @@ class UploadManager {
}
private updateElectronRemainingFiles(
- fileWithCollection: FileWithCollection
+ fileWithCollection: FileWithCollection,
) {
if (isElectron()) {
this.remainingFiles = this.remainingFiles.filter(
- (file) => !areFileWithCollectionsSame(file, fileWithCollection)
+ (file) => !areFileWithCollectionsSame(file, fileWithCollection),
);
ImportService.updatePendingUploads(this.remainingFiles);
}
diff --git a/apps/photos/src/services/upload/uploadService.ts b/apps/photos/src/services/upload/uploadService.ts
index 8a6219f327..0228bc541d 100644
--- a/apps/photos/src/services/upload/uploadService.ts
+++ b/apps/photos/src/services/upload/uploadService.ts
@@ -1,9 +1,10 @@
-import { Collection } from 'types/collection';
-import { logError } from '@ente/shared/sentry';
-import UploadHttpClient from './uploadHttpClient';
-import { extractFileMetadata, getFilename } from './fileService';
-import { getFileType } from '../typeDetectionService';
-import { CustomError, handleUploadError } from '@ente/shared/error';
+import { DedicatedCryptoWorker } from "@ente/shared/crypto/internal/crypto.worker";
+import { B64EncryptionResult } from "@ente/shared/crypto/types";
+import { CustomError, handleUploadError } from "@ente/shared/error";
+import { logError } from "@ente/shared/sentry";
+import { Remote } from "comlink";
+import { Collection } from "types/collection";
+import { FilePublicMagicMetadataProps } from "types/file";
import {
BackupedFile,
EncryptedFile,
@@ -11,7 +12,6 @@ import {
FileTypeInfo,
FileWithCollection,
FileWithMetadata,
- isDataStream,
Logger,
ParsedMetadataJSON,
ParsedMetadataJSONMap,
@@ -20,7 +20,16 @@ import {
UploadAsset,
UploadFile,
UploadURL,
-} from 'types/upload';
+ isDataStream,
+} from "types/upload";
+import { getFileType } from "../typeDetectionService";
+import {
+ encryptFile,
+ extractFileMetadata,
+ getFileSize,
+ getFilename,
+ readFile,
+} from "./fileService";
import {
clusterLivePhotoFiles,
extractLivePhotoMetadata,
@@ -28,16 +37,12 @@ import {
getLivePhotoName,
getLivePhotoSize,
readLivePhoto,
-} from './livePhotoService';
-import { encryptFile, getFileSize, readFile } from './fileService';
-import { uploadStreamUsingMultipart } from './multiPartUploadService';
-import UIService from './uiService';
-import { Remote } from 'comlink';
-import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
-import publicUploadHttpClient from './publicUploadHttpClient';
-import { constructPublicMagicMetadata } from './magicMetadataService';
-import { FilePublicMagicMetadataProps } from 'types/file';
-import { B64EncryptionResult } from '@ente/shared/crypto/types';
+} from "./livePhotoService";
+import { constructPublicMagicMetadata } from "./magicMetadataService";
+import { uploadStreamUsingMultipart } from "./multiPartUploadService";
+import publicUploadHttpClient from "./publicUploadHttpClient";
+import UIService from "./uiService";
+import UploadHttpClient from "./uploadHttpClient";
class UploadService {
private uploadURLs: UploadURL[] = [];
@@ -56,7 +61,7 @@ class UploadService {
init(
publicUploadProps: PublicUploadProps,
- isCFUploadProxyDisabled: boolean
+ isCFUploadProxyDisabled: boolean,
) {
this.publicUploadProps = publicUploadProps;
this.isCFUploadProxyDisabled = isCFUploadProxyDisabled;
@@ -107,7 +112,7 @@ class UploadService {
async readAsset(
fileTypeInfo: FileTypeInfo,
- { isLivePhoto, file, livePhotoAssets }: UploadAsset
+ { isLivePhoto, file, livePhotoAssets }: UploadAsset,
) {
return isLivePhoto
? await readLivePhoto(fileTypeInfo, livePhotoAssets)
@@ -118,7 +123,7 @@ class UploadService {
worker: Remote<DedicatedCryptoWorker>,
{ isLivePhoto, file, livePhotoAssets }: UploadAsset,
collectionID: number,
- fileTypeInfo: FileTypeInfo
+ fileTypeInfo: FileTypeInfo,
): Promise<ExtractMetadataResult> {
return isLivePhoto
? extractLivePhotoMetadata(
@@ -126,14 +131,14 @@ class UploadService {
this.parsedMetadataJSONMap,
collectionID,
fileTypeInfo,
- livePhotoAssets
+ livePhotoAssets,
)
: await extractFileMetadata(
worker,
this.parsedMetadataJSONMap,
collectionID,
fileTypeInfo,
- file
+ file,
);
}
@@ -142,7 +147,7 @@ class UploadService {
}
constructPublicMagicMetadata(
- publicMagicMetadataProps: FilePublicMagicMetadataProps
+ publicMagicMetadataProps: FilePublicMagicMetadataProps,
) {
return constructPublicMagicMetadata(publicMagicMetadataProps);
}
@@ -150,66 +155,66 @@ class UploadService {
async encryptAsset(
worker: Remote<DedicatedCryptoWorker>,
file: FileWithMetadata,
- encryptionKey: string
+ encryptionKey: string,
): Promise<EncryptedFile> {
return encryptFile(worker, file, encryptionKey);
}
async uploadToBucket(
logger: Logger,
- file: ProcessedFile
+ file: ProcessedFile,
): Promise<BackupedFile> {
try {
let fileObjectKey: string = null;
- logger('uploading file to bucket');
+ logger("uploading file to bucket");
if (isDataStream(file.file.encryptedData)) {
- logger('uploading using multipart');
+ logger("uploading using multipart");
fileObjectKey = await uploadStreamUsingMultipart(
logger,
file.localID,
- file.file.encryptedData
+ file.file.encryptedData,
);
- logger('uploading using multipart done');
+ logger("uploading using multipart done");
} else {
- logger('uploading using single part');
+ logger("uploading using single part");
const progressTracker = UIService.trackUploadProgress(
- file.localID
+ file.localID,
);
const fileUploadURL = await this.getUploadURL();
if (!this.isCFUploadProxyDisabled) {
- logger('uploading using cf proxy');
+ logger("uploading using cf proxy");
fileObjectKey = await UploadHttpClient.putFileV2(
fileUploadURL,
file.file.encryptedData as Uint8Array,
- progressTracker
+ progressTracker,
);
} else {
- logger('uploading directly to s3');
+ logger("uploading directly to s3");
fileObjectKey = await UploadHttpClient.putFile(
fileUploadURL,
file.file.encryptedData as Uint8Array,
- progressTracker
+ progressTracker,
);
}
- logger('uploading using single part done');
+ logger("uploading using single part done");
}
- logger('uploading thumbnail to bucket');
+ logger("uploading thumbnail to bucket");
const thumbnailUploadURL = await this.getUploadURL();
let thumbnailObjectKey: string = null;
if (!this.isCFUploadProxyDisabled) {
thumbnailObjectKey = await UploadHttpClient.putFileV2(
thumbnailUploadURL,
file.thumbnail.encryptedData,
- null
+ null,
);
} else {
thumbnailObjectKey = await UploadHttpClient.putFile(
thumbnailUploadURL,
file.thumbnail.encryptedData,
- null
+ null,
);
}
- logger('uploading thumbnail to bucket done');
+ logger("uploading thumbnail to bucket done");
const backupedFile: BackupedFile = {
file: {
@@ -226,7 +231,7 @@ class UploadService {
return backupedFile;
} catch (e) {
if (e.message !== CustomError.UPLOAD_CANCELLED) {
- logError(e, 'error uploading to bucket');
+ logError(e, "error uploading to bucket");
}
throw e;
}
@@ -235,7 +240,7 @@ class UploadService {
getUploadFile(
collection: Collection,
backupedFile: BackupedFile,
- fileKey: B64EncryptionResult
+ fileKey: B64EncryptionResult,
): UploadFile {
const uploadFile: UploadFile = {
collectionID: collection.id,
@@ -259,7 +264,7 @@ class UploadService {
await this.fetchUploadURLs();
// checking for any subscription related errors
} catch (e) {
- logError(e, 'prefetch uploadURL failed');
+ logError(e, "prefetch uploadURL failed");
handleUploadError(e);
}
}
@@ -269,7 +274,7 @@ class UploadService {
return publicUploadHttpClient.uploadFile(
uploadFile,
this.publicUploadProps.token,
- this.publicUploadProps.passwordToken
+ this.publicUploadProps.passwordToken,
);
} else {
return UploadHttpClient.uploadFile(uploadFile);
@@ -282,12 +287,12 @@ class UploadService {
this.pendingUploadCount,
this.uploadURLs,
this.publicUploadProps.token,
- this.publicUploadProps.passwordToken
+ this.publicUploadProps.passwordToken,
);
} else {
await UploadHttpClient.fetchUploadURLs(
this.pendingUploadCount,
- this.uploadURLs
+ this.uploadURLs,
);
}
}
@@ -297,7 +302,7 @@ class UploadService {
return await publicUploadHttpClient.fetchMultipartUploadURLs(
count,
this.publicUploadProps.token,
- this.publicUploadProps.passwordToken
+ this.publicUploadProps.passwordToken,
);
} else {
return await UploadHttpClient.fetchMultipartUploadURLs(count);
diff --git a/apps/photos/src/services/upload/uploader.ts b/apps/photos/src/services/upload/uploader.ts
index 2969da6098..2e073e2429 100644
--- a/apps/photos/src/services/upload/uploader.ts
+++ b/apps/photos/src/services/upload/uploader.ts
@@ -1,26 +1,28 @@
-import { EnteFile } from 'types/file';
-import { handleUploadError, CustomError } from '@ente/shared/error';
-import { logError } from '@ente/shared/sentry';
-import { findMatchingExistingFiles } from 'utils/upload';
-import UIService from './uiService';
-import UploadService from './uploadService';
-import { UPLOAD_RESULT, MAX_FILE_SIZE_SUPPORTED } from 'constants/upload';
+import { DedicatedCryptoWorker } from "@ente/shared/crypto/internal/crypto.worker";
+import { CustomError, handleUploadError } from "@ente/shared/error";
+import { addLocalLog, addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import { convertBytesToHumanReadable } from "@ente/shared/utils/size";
+import { Remote } from "comlink";
+import { MAX_FILE_SIZE_SUPPORTED, UPLOAD_RESULT } from "constants/upload";
+import { addToCollection } from "services/collectionService";
+import { EnteFile } from "types/file";
import {
- FileWithCollection,
BackupedFile,
- UploadFile,
- FileWithMetadata,
FileTypeInfo,
+ FileWithCollection,
+ FileWithMetadata,
Logger,
-} from 'types/upload';
-import { addLocalLog, addLogLine } from '@ente/shared/logging';
-import { convertBytesToHumanReadable } from '@ente/shared/utils/size';
-import { sleep } from 'utils/common';
-import { addToCollection } from 'services/collectionService';
-import uploadCancelService from './uploadCancelService';
-import { Remote } from 'comlink';
-import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
-import uploadService from './uploadService';
+ UploadFile,
+} from "types/upload";
+import { sleep } from "utils/common";
+import { findMatchingExistingFiles } from "utils/upload";
+import UIService from "./uiService";
+import uploadCancelService from "./uploadCancelService";
+import {
+ default as UploadService,
+ default as uploadService,
+} from "./uploadService";
interface UploadResponse {
fileUploadResult: UPLOAD_RESULT;
@@ -31,11 +33,11 @@ export default async function uploader(
worker: Remote<DedicatedCryptoWorker>,
existingFiles: EnteFile[],
fileWithCollection: FileWithCollection,
- uploaderName: string
+ uploaderName: string,
): Promise<UploadResponse> {
const { collection, localID, ...uploadAsset } = fileWithCollection;
const fileNameSize = `${UploadService.getAssetName(
- fileWithCollection
+ fileWithCollection,
)}_${convertBytesToHumanReadable(UploadService.getAssetSize(uploadAsset))}`;
addLogLine(`uploader called for ${fileNameSize}`);
@@ -51,7 +53,7 @@ export default async function uploader(
addLogLine(`getting filetype for ${fileNameSize}`);
fileTypeInfo = await UploadService.getAssetFileType(uploadAsset);
addLogLine(
- `got filetype for ${fileNameSize} - ${JSON.stringify(fileTypeInfo)}`
+ `got filetype for ${fileNameSize} - ${JSON.stringify(fileTypeInfo)}`,
);
addLogLine(`extracting metadata ${fileNameSize}`);
@@ -60,18 +62,18 @@ export default async function uploader(
worker,
uploadAsset,
collection.id,
- fileTypeInfo
+ fileTypeInfo,
);
const matchingExistingFiles = findMatchingExistingFiles(
existingFiles,
- metadata
+ metadata,
);
addLocalLog(
() =>
`matchedFileList: ${matchingExistingFiles
.map((f) => `${f.id}-${f.metadata.title}`)
- .join(',')}`
+ .join(",")}`,
);
if (matchingExistingFiles?.length) {
const matchingExistingFilesCollectionIDs =
@@ -79,15 +81,15 @@ export default async function uploader(
addLocalLog(
() =>
`matched file collectionIDs:${matchingExistingFilesCollectionIDs}
- and collectionID:${collection.id}`
+ and collectionID:${collection.id}`,
);
if (matchingExistingFilesCollectionIDs.includes(collection.id)) {
addLogLine(
- `file already present in the collection , skipped upload for ${fileNameSize}`
+ `file already present in the collection , skipped upload for ${fileNameSize}`,
);
const sameCollectionMatchingExistingFile =
matchingExistingFiles.find(
- (f) => f.collectionID === collection.id
+ (f) => f.collectionID === collection.id,
);
return {
fileUploadResult: UPLOAD_RESULT.ALREADY_UPLOADED,
@@ -95,7 +97,7 @@ export default async function uploader(
};
} else {
addLogLine(
- `same file in ${matchingExistingFilesCollectionIDs.length} collection found for ${fileNameSize} ,adding symlink`
+ `same file in ${matchingExistingFilesCollectionIDs.length} collection found for ${fileNameSize} ,adding symlink`,
);
// any of the matching file can used to add a symlink
const resultFile = Object.assign({}, matchingExistingFiles[0]);
@@ -139,7 +141,7 @@ export default async function uploader(
const encryptedFile = await UploadService.encryptAsset(
worker,
fileWithMetadata,
- collection.key
+ collection.key,
);
if (uploadCancelService.isUploadCancelationRequested()) {
@@ -151,13 +153,13 @@ export default async function uploader(
};
const backupedFile: BackupedFile = await UploadService.uploadToBucket(
logger,
- encryptedFile.file
+ encryptedFile.file,
);
const uploadFile: UploadFile = UploadService.getUploadFile(
collection,
backupedFile,
- encryptedFile.fileKey
+ encryptedFile.fileKey,
);
addLogLine(`uploading file to server ${fileNameSize}`);
@@ -177,7 +179,7 @@ export default async function uploader(
e.message !== CustomError.UPLOAD_CANCELLED &&
e.message !== CustomError.UNSUPPORTED_FILE_FORMAT
) {
- logError(e, 'file upload failed', {
+ logError(e, "file upload failed", {
fileFormat: fileTypeInfo?.exactType,
fileSize: convertBytesToHumanReadable(fileSize),
});
diff --git a/apps/photos/src/services/upload/videoMetadataService.ts b/apps/photos/src/services/upload/videoMetadataService.ts
index eec87883f7..f23ab21fde 100644
--- a/apps/photos/src/services/upload/videoMetadataService.ts
+++ b/apps/photos/src/services/upload/videoMetadataService.ts
@@ -1,9 +1,9 @@
-import { NULL_EXTRACTED_METADATA } from 'constants/upload';
-import * as ffmpegService from 'services/ffmpeg/ffmpegService';
-import { ElectronFile } from 'types/upload';
-import { logError } from '@ente/shared/sentry';
-import { addLogLine } from '@ente/shared/logging';
-import { getFileNameSize } from '@ente/shared/logging/web';
+import { addLogLine } from "@ente/shared/logging";
+import { getFileNameSize } from "@ente/shared/logging/web";
+import { logError } from "@ente/shared/sentry";
+import { NULL_EXTRACTED_METADATA } from "constants/upload";
+import * as ffmpegService from "services/ffmpeg/ffmpegService";
+import { ElectronFile } from "types/upload";
export async function getVideoMetadata(file: File | ElectronFile) {
let videoMetadata = NULL_EXTRACTED_METADATA;
@@ -11,14 +11,14 @@ export async function getVideoMetadata(file: File | ElectronFile) {
addLogLine(`getVideoMetadata called for ${getFileNameSize(file)}`);
videoMetadata = await ffmpegService.extractVideoMetadata(file);
addLogLine(
- `videoMetadata successfully extracted ${getFileNameSize(file)}`
+ `videoMetadata successfully extracted ${getFileNameSize(file)}`,
);
} catch (e) {
- logError(e, 'failed to get video metadata');
+ logError(e, "failed to get video metadata");
addLogLine(
`videoMetadata extracted failed ${getFileNameSize(file)} ,${
e.message
- } `
+ } `,
);
}
diff --git a/apps/photos/src/services/userService.ts b/apps/photos/src/services/userService.ts
index 063208beb2..4a2c6a9d4a 100644
--- a/apps/photos/src/services/userService.ts
+++ b/apps/photos/src/services/userService.ts
@@ -1,28 +1,28 @@
-import { putAttributes } from '@ente/accounts/api/user';
-import { logoutUser } from '@ente/accounts/services/user';
-import { getRecoveryKey } from '@ente/shared/crypto/helpers';
-import { ApiError } from '@ente/shared/error';
-import HTTPService from '@ente/shared/network/HTTPService';
-import { getEndpoint, getFamilyPortalURL } from '@ente/shared/network/api';
-import { logError } from '@ente/shared/sentry';
-import localForage from '@ente/shared/storage/localForage';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
+import { putAttributes } from "@ente/accounts/api/user";
+import { logoutUser } from "@ente/accounts/services/user";
+import { getRecoveryKey } from "@ente/shared/crypto/helpers";
+import { ApiError } from "@ente/shared/error";
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getEndpoint, getFamilyPortalURL } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import localForage from "@ente/shared/storage/localForage";
+import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
import {
getToken,
setLocalMapEnabled,
-} from '@ente/shared/storage/localStorage/helpers';
-import { AxiosResponse, HttpStatusCode } from 'axios';
+} from "@ente/shared/storage/localStorage/helpers";
+import { AxiosResponse, HttpStatusCode } from "axios";
import {
DeleteChallengeResponse,
GetFeatureFlagResponse,
GetRemoteStoreValueResponse,
UserDetails,
-} from 'types/user';
-import { getLocalFamilyData, isPartOfFamily } from 'utils/user/family';
+} from "types/user";
+import { getLocalFamilyData, isPartOfFamily } from "utils/user/family";
const ENDPOINT = getEndpoint();
-const HAS_SET_KEYS = 'hasSetKeys';
+const HAS_SET_KEYS = "hasSetKeys";
export const getPublicKey = async (email: string) => {
const token = getToken();
@@ -31,8 +31,8 @@ export const getPublicKey = async (email: string) => {
`${ENDPOINT}/users/public-key`,
{ email },
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
return resp.data.publicKey;
};
@@ -44,10 +44,10 @@ export const getPaymentToken = async () => {
`${ENDPOINT}/users/payment-token`,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
- return resp.data['paymentToken'];
+ return resp.data["paymentToken"];
};
export const getFamiliesToken = async () => {
@@ -58,12 +58,12 @@ export const getFamiliesToken = async () => {
`${ENDPOINT}/users/families-token`,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
- return resp.data['familiesToken'];
+ return resp.data["familiesToken"];
} catch (e) {
- logError(e, 'failed to get family token');
+ logError(e, "failed to get family token");
throw e;
}
};
@@ -76,12 +76,12 @@ export const getAccountsToken = async () => {
`${ENDPOINT}/users/accounts-token`,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
- return resp.data['accountsToken'];
+ return resp.data["accountsToken"];
} catch (e) {
- logError(e, 'failed to get accounts token');
+ logError(e, "failed to get accounts token");
throw e;
}
};
@@ -94,12 +94,12 @@ export const getRoadmapRedirectURL = async () => {
`${ENDPOINT}/users/roadmap/v2`,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
- return resp.data['url'];
+ return resp.data["url"];
} catch (e) {
- logError(e, 'failed to get roadmap url');
+ logError(e, "failed to get roadmap url");
throw e;
}
};
@@ -114,29 +114,29 @@ export const isTokenValid = async (token: string) => {
`${ENDPOINT}/users/session-validity/v2`,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
try {
if (resp.data[HAS_SET_KEYS] === undefined) {
- throw Error('resp.data.hasSetKey undefined');
+ throw Error("resp.data.hasSetKey undefined");
}
- if (!resp.data['hasSetKeys']) {
+ if (!resp.data["hasSetKeys"]) {
try {
await putAttributes(
token,
- getData(LS_KEYS.ORIGINAL_KEY_ATTRIBUTES)
+ getData(LS_KEYS.ORIGINAL_KEY_ATTRIBUTES),
);
} catch (e) {
- logError(e, 'put attribute failed');
+ logError(e, "put attribute failed");
}
}
} catch (e) {
- logError(e, 'hasSetKeys not set in session validity response');
+ logError(e, "hasSetKeys not set in session validity response");
}
return true;
} catch (e) {
- logError(e, 'session-validity api call failed');
+ logError(e, "session-validity api call failed");
if (
e instanceof ApiError &&
e.httpStatusCode === HttpStatusCode.Unauthorized
@@ -153,10 +153,10 @@ export const getTwoFactorStatus = async () => {
`${ENDPOINT}/users/two-factor/status`,
null,
{
- 'X-Auth-Token': getToken(),
- }
+ "X-Auth-Token": getToken(),
+ },
);
- return resp.data['status'];
+ return resp.data["status"];
};
export const getUserDetailsV2 = async (): Promise<UserDetails> => {
@@ -167,12 +167,12 @@ export const getUserDetailsV2 = async (): Promise<UserDetails> => {
`${ENDPOINT}/users/details/v2`,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
return resp.data;
} catch (e) {
- logError(e, 'failed to get user details v2');
+ logError(e, "failed to get user details v2");
throw e;
}
};
@@ -185,7 +185,7 @@ export const getFamilyPortalRedirectURL = async () => {
window.location.origin
}/gallery`;
} catch (e) {
- logError(e, 'unable to generate to family portal URL');
+ logError(e, "unable to generate to family portal URL");
throw e;
}
};
@@ -198,12 +198,12 @@ export const getAccountDeleteChallenge = async () => {
`${ENDPOINT}/users/delete-challenge`,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
return resp.data as DeleteChallengeResponse;
} catch (e) {
- logError(e, 'failed to get account delete challenge');
+ logError(e, "failed to get account delete challenge");
throw e;
}
};
@@ -211,7 +211,7 @@ export const getAccountDeleteChallenge = async () => {
export const deleteAccount = async (
challenge: string,
reason: string,
- feedback: string
+ feedback: string,
) => {
try {
const token = getToken();
@@ -224,11 +224,11 @@ export const deleteAccount = async (
{ challenge, reason, feedback },
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
} catch (e) {
- logError(e, 'deleteAccount api call failed');
+ logError(e, "deleteAccount api call failed");
throw e;
}
};
@@ -253,16 +253,16 @@ export const getFaceSearchEnabledStatus = async () => {
await HTTPService.get(
`${ENDPOINT}/remote-store`,
{
- key: 'faceSearchEnabled',
+ key: "faceSearchEnabled",
defaultValue: false,
},
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
- return resp.data.value === 'true';
+ return resp.data.value === "true";
} catch (e) {
- logError(e, 'failed to get face search enabled status');
+ logError(e, "failed to get face search enabled status");
throw e;
}
};
@@ -273,16 +273,16 @@ export const updateFaceSearchEnabledStatus = async (newStatus: boolean) => {
await HTTPService.post(
`${ENDPOINT}/remote-store/update`,
{
- key: 'faceSearchEnabled',
+ key: "faceSearchEnabled",
value: newStatus.toString(),
},
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
} catch (e) {
- logError(e, 'failed to update face search enabled status');
+ logError(e, "failed to update face search enabled status");
throw e;
}
};
@@ -292,7 +292,7 @@ export const syncMapEnabled = async () => {
const status = await getMapEnabledStatus();
setLocalMapEnabled(status);
} catch (e) {
- logError(e, 'failed to sync map enabled status');
+ logError(e, "failed to sync map enabled status");
throw e;
}
};
@@ -304,16 +304,16 @@ export const getMapEnabledStatus = async () => {
await HTTPService.get(
`${ENDPOINT}/remote-store`,
{
- key: 'mapEnabled',
+ key: "mapEnabled",
defaultValue: false,
},
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
- return resp.data.value === 'true';
+ return resp.data.value === "true";
} catch (e) {
- logError(e, 'failed to get map enabled status');
+ logError(e, "failed to get map enabled status");
throw e;
}
};
@@ -324,30 +324,30 @@ export const updateMapEnabledStatus = async (newStatus: boolean) => {
await HTTPService.post(
`${ENDPOINT}/remote-store/update`,
{
- key: 'mapEnabled',
+ key: "mapEnabled",
value: newStatus.toString(),
},
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
} catch (e) {
- logError(e, 'failed to update map enabled status');
+ logError(e, "failed to update map enabled status");
throw e;
}
};
export async function getDisableCFUploadProxyFlag(): Promise<boolean> {
- if (process.env.NEXT_PUBLIC_ENTE_DIRECT_UPLOAD === 'true') return true;
+ if (process.env.NEXT_PUBLIC_ENTE_DIRECT_UPLOAD === "true") return true;
try {
const featureFlags = (
- await fetch('https://static.ente.io/feature_flags.json')
+ await fetch("https://static.ente.io/feature_flags.json")
).json() as GetFeatureFlagResponse;
return featureFlags.disableCFUploadProxy;
} catch (e) {
- logError(e, 'failed to get feature flags');
+ logError(e, "failed to get feature flags");
return false;
}
}
diff --git a/apps/photos/src/services/wasm/ffmpeg.ts b/apps/photos/src/services/wasm/ffmpeg.ts
index a5b7219f85..93413e5811 100644
--- a/apps/photos/src/services/wasm/ffmpeg.ts
+++ b/apps/photos/src/services/wasm/ffmpeg.ts
@@ -1,14 +1,14 @@
-import { createFFmpeg, FFmpeg } from 'ffmpeg-wasm';
-import QueueProcessor from 'services/queueProcessor';
-import { getUint8ArrayView } from 'services/readerService';
-import { promiseWithTimeout } from 'utils/common';
-import { addLogLine } from '@ente/shared/logging';
-import { logError } from '@ente/shared/sentry';
-import { generateTempName } from 'utils/temp';
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import { createFFmpeg, FFmpeg } from "ffmpeg-wasm";
+import QueueProcessor from "services/queueProcessor";
+import { getUint8ArrayView } from "services/readerService";
+import { promiseWithTimeout } from "utils/common";
+import { generateTempName } from "utils/temp";
-const INPUT_PATH_PLACEHOLDER = 'INPUT';
-const FFMPEG_PLACEHOLDER = 'FFMPEG';
-const OUTPUT_PATH_PLACEHOLDER = 'OUTPUT';
+const INPUT_PATH_PLACEHOLDER = "INPUT";
+const FFMPEG_PLACEHOLDER = "FFMPEG";
+const OUTPUT_PATH_PLACEHOLDER = "OUTPUT";
const FFMPEG_EXECUTION_WAIT_TIME = 30 * 1000;
@@ -19,7 +19,7 @@ export class WasmFFmpeg {
constructor() {
this.ffmpeg = createFFmpeg({
- corePath: '/js/ffmpeg/ffmpeg-core.js',
+ corePath: "/js/ffmpeg/ffmpeg-core.js",
mt: false,
});
@@ -36,7 +36,7 @@ export class WasmFFmpeg {
cmd: string[],
inputFile: File,
outputFileName: string,
- dontTimeout = false
+ dontTimeout = false,
) {
const response = this.ffmpegTaskQueue.queueUpRequest(() => {
if (dontTimeout) {
@@ -44,14 +44,14 @@ export class WasmFFmpeg {
} else {
return promiseWithTimeout<File>(
this.execute(cmd, inputFile, outputFileName),
- FFMPEG_EXECUTION_WAIT_TIME
+ FFMPEG_EXECUTION_WAIT_TIME,
);
}
});
try {
return await response.promise;
} catch (e) {
- logError(e, 'ffmpeg run failed');
+ logError(e, "ffmpeg run failed");
throw e;
}
}
@@ -59,25 +59,25 @@ export class WasmFFmpeg {
private async execute(
cmd: string[],
inputFile: File,
- outputFileName: string
+ outputFileName: string,
) {
let tempInputFilePath: string;
let tempOutputFilePath: string;
try {
await this.ready;
const extension = getFileExtension(inputFile.name);
- const tempNameSuffix = extension ? `input.${extension}` : 'input';
+ const tempNameSuffix = extension ? `input.${extension}` : "input";
tempInputFilePath = `${generateTempName(10, tempNameSuffix)}`;
this.ffmpeg.FS(
- 'writeFile',
+ "writeFile",
tempInputFilePath,
- await getUint8ArrayView(inputFile)
+ await getUint8ArrayView(inputFile),
);
tempOutputFilePath = `${generateTempName(10, outputFileName)}`;
cmd = cmd.map((cmdPart) => {
if (cmdPart === FFMPEG_PLACEHOLDER) {
- return '';
+ return "";
} else if (cmdPart === INPUT_PATH_PLACEHOLDER) {
return tempInputFilePath;
} else if (cmdPart === OUTPUT_PATH_PLACEHOLDER) {
@@ -89,26 +89,26 @@ export class WasmFFmpeg {
addLogLine(`${cmd}`);
await this.ffmpeg.run(...cmd);
return new File(
- [this.ffmpeg.FS('readFile', tempOutputFilePath)],
- outputFileName
+ [this.ffmpeg.FS("readFile", tempOutputFilePath)],
+ outputFileName,
);
} finally {
try {
- this.ffmpeg.FS('unlink', tempInputFilePath);
+ this.ffmpeg.FS("unlink", tempInputFilePath);
} catch (e) {
- logError(e, 'unlink input file failed');
+ logError(e, "unlink input file failed");
}
try {
- this.ffmpeg.FS('unlink', tempOutputFilePath);
+ this.ffmpeg.FS("unlink", tempOutputFilePath);
} catch (e) {
- logError(e, 'unlink output file failed');
+ logError(e, "unlink output file failed");
}
}
}
}
function getFileExtension(filename: string) {
- const lastDotPosition = filename.lastIndexOf('.');
+ const lastDotPosition = filename.lastIndexOf(".");
if (lastDotPosition === -1) return null;
else {
return filename.slice(lastDotPosition + 1);
diff --git a/apps/photos/src/services/wasmHeicConverter/wasmHEICConverterClient.ts b/apps/photos/src/services/wasmHeicConverter/wasmHEICConverterClient.ts
index 0ca183f22e..03b390fb9a 100644
--- a/apps/photos/src/services/wasmHeicConverter/wasmHEICConverterClient.ts
+++ b/apps/photos/src/services/wasmHeicConverter/wasmHEICConverterClient.ts
@@ -1,9 +1,9 @@
-import * as HeicConvert from 'heic-convert';
-import { getUint8ArrayView } from 'services/readerService';
+import * as HeicConvert from "heic-convert";
+import { getUint8ArrayView } from "services/readerService";
export async function convertHEIC(
fileBlob: Blob,
- format: string
+ format: string,
): Promise<Blob> {
const filedata = await getUint8ArrayView(fileBlob);
const result = await HeicConvert({ buffer: filedata, format });
diff --git a/apps/photos/src/services/wasmHeicConverter/wasmHEICConverterService.ts b/apps/photos/src/services/wasmHeicConverter/wasmHEICConverterService.ts
index 2e2617f407..4ace3064aa 100644
--- a/apps/photos/src/services/wasmHeicConverter/wasmHEICConverterService.ts
+++ b/apps/photos/src/services/wasmHeicConverter/wasmHEICConverterService.ts
@@ -1,23 +1,23 @@
-import QueueProcessor from 'services/queueProcessor';
-import { CustomError } from '@ente/shared/error';
-import { retryAsyncFunction } from 'utils/network';
-import { logError } from '@ente/shared/sentry';
-import { addLogLine } from '@ente/shared/logging';
-import { DedicatedConvertWorker } from 'worker/convert.worker';
-import { ComlinkWorker } from '@ente/shared/worker/comlinkWorker';
-import { convertBytesToHumanReadable } from '@ente/shared/utils/size';
-import { getDedicatedConvertWorker } from 'utils/comlink/ComlinkConvertWorker';
+import { CustomError } from "@ente/shared/error";
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import { convertBytesToHumanReadable } from "@ente/shared/utils/size";
+import { ComlinkWorker } from "@ente/shared/worker/comlinkWorker";
+import QueueProcessor from "services/queueProcessor";
+import { getDedicatedConvertWorker } from "utils/comlink/ComlinkConvertWorker";
+import { retryAsyncFunction } from "utils/network";
+import { DedicatedConvertWorker } from "worker/convert.worker";
const WORKER_POOL_SIZE = 2;
const MAX_CONVERSION_IN_PARALLEL = 1;
const WAIT_TIME_BEFORE_NEXT_ATTEMPT_IN_MICROSECONDS = [100, 100];
const WAIT_TIME_IN_MICROSECONDS = 30 * 1000;
const BREATH_TIME_IN_MICROSECONDS = 1000;
-const CONVERT_FORMAT = 'JPEG';
+const CONVERT_FORMAT = "JPEG";
class HEICConverter {
private convertProcessor = new QueueProcessor<Blob>(
- MAX_CONVERSION_IN_PARALLEL
+ MAX_CONVERSION_IN_PARALLEL,
);
private workerPool: ComlinkWorker<typeof DedicatedConvertWorker>[] = [];
private ready: Promise<void>;
@@ -43,22 +43,22 @@ class HEICConverter {
const main = async () => {
try {
const timeout = setTimeout(() => {
- reject(Error('wait time exceeded'));
+ reject(Error("wait time exceeded"));
}, WAIT_TIME_IN_MICROSECONDS);
const startTime = Date.now();
const convertedHEIC =
await worker.convertHEIC(
fileBlob,
- CONVERT_FORMAT
+ CONVERT_FORMAT,
);
addLogLine(
`originalFileSize:${convertBytesToHumanReadable(
- fileBlob?.size
+ fileBlob?.size,
)},convertedFileSize:${convertBytesToHumanReadable(
- convertedHEIC?.size
+ convertedHEIC?.size,
)}, heic conversion time: ${
Date.now() - startTime
- }ms `
+ }ms `,
);
clearTimeout(timeout);
resolve(convertedHEIC);
@@ -67,37 +67,37 @@ class HEICConverter {
}
};
main();
- }
+ },
);
if (!convertedHEIC || convertedHEIC?.size === 0) {
logError(
Error(`converted heic fileSize is Zero`),
- 'converted heic fileSize is Zero',
+ "converted heic fileSize is Zero",
{
originalFileSize: convertBytesToHumanReadable(
- fileBlob?.size ?? 0
+ fileBlob?.size ?? 0,
),
convertedFileSize: convertBytesToHumanReadable(
- convertedHEIC?.size ?? 0
+ convertedHEIC?.size ?? 0,
),
- }
+ },
);
}
await new Promise((resolve) => {
setTimeout(
() => resolve(null),
- BREATH_TIME_IN_MICROSECONDS
+ BREATH_TIME_IN_MICROSECONDS,
);
});
this.workerPool.push(convertWorker);
return convertedHEIC;
} catch (e) {
- logError(e, 'heic conversion failed');
+ logError(e, "heic conversion failed");
convertWorker.terminate();
this.workerPool.push(getDedicatedConvertWorker());
throw e;
}
- }, WAIT_TIME_BEFORE_NEXT_ATTEMPT_IN_MICROSECONDS)
+ }, WAIT_TIME_BEFORE_NEXT_ATTEMPT_IN_MICROSECONDS),
);
try {
return await response.promise;
diff --git a/apps/photos/src/services/watchFolder/utils.ts b/apps/photos/src/services/watchFolder/utils.ts
index bce90a2c80..bd6ceb853c 100644
--- a/apps/photos/src/services/watchFolder/utils.ts
+++ b/apps/photos/src/services/watchFolder/utils.ts
@@ -1,5 +1,5 @@
export const getParentFolderName = (filePath: string) => {
- const folderPath = filePath.substring(0, filePath.lastIndexOf('/'));
- const folderName = folderPath.substring(folderPath.lastIndexOf('/') + 1);
+ const folderPath = filePath.substring(0, filePath.lastIndexOf("/"));
+ const folderName = folderPath.substring(folderPath.lastIndexOf("/") + 1);
return folderName;
};
diff --git a/apps/photos/src/services/watchFolder/watchFolderEventHandlers.ts b/apps/photos/src/services/watchFolder/watchFolderEventHandlers.ts
index b0a0f3c1a2..d1d8faa725 100644
--- a/apps/photos/src/services/watchFolder/watchFolderEventHandlers.ts
+++ b/apps/photos/src/services/watchFolder/watchFolderEventHandlers.ts
@@ -1,8 +1,8 @@
-import { ElectronFile } from 'types/upload';
-import { EventQueueItem } from 'types/watchFolder';
-import { addLogLine } from '@ente/shared/logging';
-import { logError } from '@ente/shared/sentry';
-import watchFolderService from './watchFolderService';
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import { ElectronFile } from "types/upload";
+import { EventQueueItem } from "types/watchFolder";
+import watchFolderService from "./watchFolderService";
export async function diskFileAddedCallback(file: ElectronFile) {
try {
@@ -16,17 +16,17 @@ export async function diskFileAddedCallback(file: ElectronFile) {
const { collectionName, folderPath } = collectionNameAndFolderPath;
const event: EventQueueItem = {
- type: 'upload',
+ type: "upload",
collectionName,
folderPath,
files: [file],
};
watchFolderService.pushEvent(event);
addLogLine(
- `added (upload) to event queue, collectionName:${event.collectionName} folderPath:${event.folderPath}, filesCount: ${event.files.length}`
+ `added (upload) to event queue, collectionName:${event.collectionName} folderPath:${event.folderPath}, filesCount: ${event.files.length}`,
);
} catch (e) {
- logError(e, 'error while calling diskFileAddedCallback');
+ logError(e, "error while calling diskFileAddedCallback");
}
}
@@ -42,17 +42,17 @@ export async function diskFileRemovedCallback(filePath: string) {
const { collectionName, folderPath } = collectionNameAndFolderPath;
const event: EventQueueItem = {
- type: 'trash',
+ type: "trash",
collectionName,
folderPath,
paths: [filePath],
};
watchFolderService.pushEvent(event);
addLogLine(
- `added (trash) to event queue collectionName:${event.collectionName} folderPath:${event.folderPath} , pathsCount: ${event.paths.length}`
+ `added (trash) to event queue collectionName:${event.collectionName} folderPath:${event.folderPath} , pathsCount: ${event.paths.length}`,
);
} catch (e) {
- logError(e, 'error while calling diskFileRemovedCallback');
+ logError(e, "error while calling diskFileRemovedCallback");
}
}
@@ -60,7 +60,7 @@ export async function diskFolderRemovedCallback(folderPath: string) {
try {
const mappings = watchFolderService.getWatchMappings();
const mapping = mappings.find(
- (mapping) => mapping.folderPath === folderPath
+ (mapping) => mapping.folderPath === folderPath,
);
if (!mapping) {
addLogLine(`folder not found in mappings, ${folderPath}`);
@@ -69,6 +69,6 @@ export async function diskFolderRemovedCallback(folderPath: string) {
watchFolderService.pushTrashedDir(folderPath);
addLogLine(`added trashedDir, ${folderPath}`);
} catch (e) {
- logError(e, 'error while calling diskFolderRemovedCallback');
+ logError(e, "error while calling diskFolderRemovedCallback");
}
}
diff --git a/apps/photos/src/services/watchFolder/watchFolderService.ts b/apps/photos/src/services/watchFolder/watchFolderService.ts
index f692923461..ea298c7f50 100644
--- a/apps/photos/src/services/watchFolder/watchFolderService.ts
+++ b/apps/photos/src/services/watchFolder/watchFolderService.ts
@@ -1,27 +1,27 @@
-import { Collection } from 'types/collection';
-import { EncryptedEnteFile } from 'types/file';
-import { ElectronFile, FileWithCollection } from 'types/upload';
-import { removeFromCollection } from '../collectionService';
-import { getLocalFiles } from '../fileService';
-import { logError } from '@ente/shared/sentry';
+import ElectronAPIs from "@ente/shared/electron";
+import { addLocalLog, addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import { UPLOAD_RESULT, UPLOAD_STRATEGY } from "constants/upload";
+import debounce from "debounce";
+import uploadManager from "services/upload/uploadManager";
+import { Collection } from "types/collection";
+import { EncryptedEnteFile } from "types/file";
+import { ElectronFile, FileWithCollection } from "types/upload";
import {
EventQueueItem,
WatchMapping,
WatchMappingSyncedFile,
-} from 'types/watchFolder';
-import debounce from 'debounce';
+} from "types/watchFolder";
+import { groupFilesBasedOnCollectionID } from "utils/file";
+import { getValidFilesToUpload } from "utils/watch";
+import { removeFromCollection } from "../collectionService";
+import { getLocalFiles } from "../fileService";
+import { getParentFolderName } from "./utils";
import {
diskFileAddedCallback,
diskFileRemovedCallback,
diskFolderRemovedCallback,
-} from './watchFolderEventHandlers';
-import { getParentFolderName } from './utils';
-import { UPLOAD_RESULT, UPLOAD_STRATEGY } from 'constants/upload';
-import uploadManager from 'services/upload/uploadManager';
-import { addLocalLog, addLogLine } from '@ente/shared/logging';
-import { getValidFilesToUpload } from 'utils/watch';
-import { groupFilesBasedOnCollectionID } from 'utils/file';
-import ElectronAPIs from '@ente/shared/electron';
+} from "./watchFolderEventHandlers";
class watchFolderService {
private eventQueue: EventQueueItem[] = [];
@@ -55,7 +55,7 @@ class watchFolderService {
setElectronFiles: (files: ElectronFile[]) => void,
setCollectionName: (collectionName: string) => void,
syncWithRemote: () => void,
- setWatchFolderServiceIsRunning: (isRunning: boolean) => void
+ setWatchFolderServiceIsRunning: (isRunning: boolean) => void,
) {
try {
this.setElectronFiles = setElectronFiles;
@@ -66,7 +66,7 @@ class watchFolderService {
this.setupWatcherFunctions();
await this.getAndSyncDiffOfFiles();
} catch (e) {
- logError(e, 'error while initializing watch service');
+ logError(e, "error while initializing watch service");
}
}
@@ -90,7 +90,7 @@ class watchFolderService {
this.trashDiffOfFiles(mapping, filesOnDisk);
}
} catch (e) {
- logError(e, 'error while getting and syncing diff of files');
+ logError(e, "error while getting and syncing diff of files");
}
}
@@ -100,17 +100,17 @@ class watchFolderService {
private uploadDiffOfFiles(
mapping: WatchMapping,
- filesOnDisk: ElectronFile[]
+ filesOnDisk: ElectronFile[],
) {
const filesToUpload = getValidFilesToUpload(filesOnDisk, mapping);
if (filesToUpload.length > 0) {
for (const file of filesToUpload) {
const event: EventQueueItem = {
- type: 'upload',
+ type: "upload",
collectionName: this.getCollectionNameForMapping(
mapping,
- file.path
+ file.path,
),
folderPath: mapping.folderPath,
files: [file],
@@ -122,21 +122,21 @@ class watchFolderService {
private trashDiffOfFiles(
mapping: WatchMapping,
- filesOnDisk: ElectronFile[]
+ filesOnDisk: ElectronFile[],
) {
const filesToRemove = mapping.syncedFiles.filter((file) => {
return !filesOnDisk.find(
- (electronFile) => electronFile.path === file.path
+ (electronFile) => electronFile.path === file.path,
);
});
if (filesToRemove.length > 0) {
for (const file of filesToRemove) {
const event: EventQueueItem = {
- type: 'trash',
+ type: "trash",
collectionName: this.getCollectionNameForMapping(
mapping,
- file.path
+ file.path,
),
folderPath: mapping.folderPath,
paths: [file.path],
@@ -147,12 +147,12 @@ class watchFolderService {
}
private async filterOutDeletedMappings(
- mappings: WatchMapping[]
+ mappings: WatchMapping[],
): Promise<WatchMapping[]> {
const notDeletedMappings = [];
for (const mapping of mappings) {
const mappingExists = await ElectronAPIs.isFolder(
- mapping.folderPath
+ mapping.folderPath,
);
if (!mappingExists) {
ElectronAPIs.removeWatchMapping(mapping.folderPath);
@@ -176,24 +176,24 @@ class watchFolderService {
ElectronAPIs.registerWatcherFunctions(
diskFileAddedCallback,
diskFileRemovedCallback,
- diskFolderRemovedCallback
+ diskFolderRemovedCallback,
);
}
async addWatchMapping(
rootFolderName: string,
folderPath: string,
- uploadStrategy: UPLOAD_STRATEGY
+ uploadStrategy: UPLOAD_STRATEGY,
) {
try {
await ElectronAPIs.addWatchMapping(
rootFolderName,
folderPath,
- uploadStrategy
+ uploadStrategy,
);
this.getAndSyncDiffOfFiles();
} catch (e) {
- logError(e, 'error while adding watch mapping');
+ logError(e, "error while adding watch mapping");
}
}
@@ -201,7 +201,7 @@ class watchFolderService {
try {
await ElectronAPIs.removeWatchMapping(folderPath);
} catch (e) {
- logError(e, 'error while removing watch mapping');
+ logError(e, "error while removing watch mapping");
}
}
@@ -209,7 +209,7 @@ class watchFolderService {
try {
return ElectronAPIs.getWatchMappings() ?? [];
} catch (e) {
- logError(e, 'error while getting watch mappings');
+ logError(e, "error while getting watch mappings");
return [];
}
return [];
@@ -232,19 +232,19 @@ class watchFolderService {
const event = this.clubSameCollectionEvents();
addLogLine(
- `running event type:${event.type} collectionName:${event.collectionName} folderPath:${event.folderPath} , fileCount:${event.files?.length} pathsCount: ${event.paths?.length}`
+ `running event type:${event.type} collectionName:${event.collectionName} folderPath:${event.folderPath} , fileCount:${event.files?.length} pathsCount: ${event.paths?.length}`,
);
const mappings = this.getWatchMappings();
const mapping = mappings.find(
- (mapping) => mapping.folderPath === event.folderPath
+ (mapping) => mapping.folderPath === event.folderPath,
);
if (!mapping) {
- throw Error('no Mapping found for event');
+ throw Error("no Mapping found for event");
}
addLogLine(
- `mapping for event rootFolder: ${mapping.rootFolderName} folderPath: ${mapping.folderPath} uploadStrategy: ${mapping.uploadStrategy} syncedFilesCount: ${mapping.syncedFiles.length} ignoredFilesCount ${mapping.ignoredFiles.length}`
+ `mapping for event rootFolder: ${mapping.rootFolderName} folderPath: ${mapping.folderPath} uploadStrategy: ${mapping.uploadStrategy} syncedFilesCount: ${mapping.syncedFiles.length} ignoredFilesCount ${mapping.ignoredFiles.length}`,
);
- if (event.type === 'upload') {
+ if (event.type === "upload") {
event.files = getValidFilesToUpload(event.files, mapping);
addLogLine(`valid files count: ${event.files?.length}`);
if (event.files.length === 0) {
@@ -255,7 +255,7 @@ class watchFolderService {
this.currentlySyncedMapping = mapping;
this.setIsEventRunning(true);
- if (event.type === 'upload') {
+ if (event.type === "upload") {
this.processUploadEvent();
} else {
await this.processTrashEvent();
@@ -263,7 +263,7 @@ class watchFolderService {
setTimeout(() => this.runNextEvent(), 0);
}
} catch (e) {
- logError(e, 'runNextEvent failed');
+ logError(e, "runNextEvent failed");
}
}
@@ -274,14 +274,14 @@ class watchFolderService {
this.setCollectionName(this.currentEvent.collectionName);
this.setElectronFiles(this.currentEvent.files);
} catch (e) {
- logError(e, 'error while running next upload');
+ logError(e, "error while running next upload");
}
}
async onFileUpload(
fileUploadResult: UPLOAD_RESULT,
fileWithCollection: FileWithCollection,
- file: EncryptedEnteFile
+ file: EncryptedEnteFile,
) {
addLocalLog(() => `onFileUpload called`);
if (!this.isUploadRunning()) {
@@ -299,36 +299,36 @@ class watchFolderService {
this.filePathToUploadedFileIDMap.set(
(fileWithCollection.livePhotoAssets.image as ElectronFile)
.path,
- file
+ file,
);
this.filePathToUploadedFileIDMap.set(
(fileWithCollection.livePhotoAssets.video as ElectronFile)
.path,
- file
+ file,
);
} else {
this.filePathToUploadedFileIDMap.set(
(fileWithCollection.file as ElectronFile).path,
- file
+ file,
);
}
} else if (
[UPLOAD_RESULT.UNSUPPORTED, UPLOAD_RESULT.TOO_LARGE].includes(
- fileUploadResult
+ fileUploadResult,
)
) {
if (fileWithCollection.isLivePhoto) {
this.unUploadableFilePaths.add(
(fileWithCollection.livePhotoAssets.image as ElectronFile)
- .path
+ .path,
);
this.unUploadableFilePaths.add(
(fileWithCollection.livePhotoAssets.video as ElectronFile)
- .path
+ .path,
);
} else {
this.unUploadableFilePaths.add(
- (fileWithCollection.file as ElectronFile).path
+ (fileWithCollection.file as ElectronFile).path,
);
}
}
@@ -336,23 +336,23 @@ class watchFolderService {
async allFileUploadsDone(
filesWithCollection: FileWithCollection[],
- collections: Collection[]
+ collections: Collection[],
) {
try {
addLocalLog(
() =>
`allFileUploadsDone,${JSON.stringify(
- filesWithCollection
- )} ${JSON.stringify(collections)}`
+ filesWithCollection,
+ )} ${JSON.stringify(collections)}`,
);
const collection = collections.find(
(collection) =>
- collection.id === filesWithCollection[0].collectionID
+ collection.id === filesWithCollection[0].collectionID,
);
addLocalLog(() => `got collection ${!!collection}`);
addLocalLog(
() =>
- `${this.isEventRunning} ${this.currentEvent.collectionName} ${collection?.name}`
+ `${this.isEventRunning} ${this.currentEvent.collectionName} ${collection?.name}`,
);
if (
!this.isEventRunning ||
@@ -361,14 +361,14 @@ class watchFolderService {
return;
}
- const syncedFiles: WatchMapping['syncedFiles'] = [];
- const ignoredFiles: WatchMapping['ignoredFiles'] = [];
+ const syncedFiles: WatchMapping["syncedFiles"] = [];
+ const ignoredFiles: WatchMapping["ignoredFiles"] = [];
for (const fileWithCollection of filesWithCollection) {
this.handleUploadedFile(
fileWithCollection,
syncedFiles,
- ignoredFiles
+ ignoredFiles,
);
}
@@ -382,7 +382,7 @@ class watchFolderService {
];
ElectronAPIs.updateWatchMappingSyncedFiles(
this.currentlySyncedMapping.folderPath,
- this.currentlySyncedMapping.syncedFiles
+ this.currentlySyncedMapping.syncedFiles,
);
}
if (ignoredFiles.length > 0) {
@@ -392,13 +392,13 @@ class watchFolderService {
];
ElectronAPIs.updateWatchMappingIgnoredFiles(
this.currentlySyncedMapping.folderPath,
- this.currentlySyncedMapping.ignoredFiles
+ this.currentlySyncedMapping.ignoredFiles,
);
}
this.runPostUploadsAction();
} catch (e) {
- logError(e, 'error while running all file uploads done');
+ logError(e, "error while running all file uploads done");
}
}
@@ -410,8 +410,8 @@ class watchFolderService {
private handleUploadedFile(
fileWithCollection: FileWithCollection,
- syncedFiles: WatchMapping['syncedFiles'],
- ignoredFiles: WatchMapping['ignoredFiles']
+ syncedFiles: WatchMapping["syncedFiles"],
+ ignoredFiles: WatchMapping["ignoredFiles"],
) {
if (fileWithCollection.isLivePhoto) {
const imagePath = (
@@ -446,10 +446,10 @@ class watchFolderService {
addLocalLog(
() =>
`added image ${JSON.stringify(
- imageFile
+ imageFile,
)} and video file ${JSON.stringify(
- videoFile
- )} to uploadedFiles`
+ videoFile,
+ )} to uploadedFiles`,
);
} else if (
this.unUploadableFilePaths.has(imagePath) &&
@@ -459,7 +459,7 @@ class watchFolderService {
ignoredFiles.push(videoPath);
addLocalLog(
() =>
- `added image ${imagePath} and video file ${videoPath} to rejectedFiles`
+ `added image ${imagePath} and video file ${videoPath} to rejectedFiles`,
);
}
this.filePathToUploadedFileIDMap.delete(imagePath);
@@ -496,25 +496,25 @@ class watchFolderService {
const filePathsToRemove = new Set(paths);
const files = this.currentlySyncedMapping.syncedFiles.filter(
- (file) => filePathsToRemove.has(file.path)
+ (file) => filePathsToRemove.has(file.path),
);
await this.trashByIDs(files);
this.currentlySyncedMapping.syncedFiles =
this.currentlySyncedMapping.syncedFiles.filter(
- (file) => !filePathsToRemove.has(file.path)
+ (file) => !filePathsToRemove.has(file.path),
);
ElectronAPIs.updateWatchMappingSyncedFiles(
this.currentlySyncedMapping.folderPath,
- this.currentlySyncedMapping.syncedFiles
+ this.currentlySyncedMapping.syncedFiles,
);
} catch (e) {
- logError(e, 'error while running next trash');
+ logError(e, "error while running next trash");
}
}
- private async trashByIDs(toTrashFiles: WatchMapping['syncedFiles']) {
+ private async trashByIDs(toTrashFiles: WatchMapping["syncedFiles"]) {
try {
const files = await getLocalFiles();
const toTrashFilesMap = new Map<number, WatchMappingSyncedFile>();
@@ -540,7 +540,7 @@ class watchFolderService {
}
this.syncWithRemote();
} catch (e) {
- logError(e, 'error while trashing by IDs');
+ logError(e, "error while trashing by IDs");
}
}
@@ -555,7 +555,7 @@ class watchFolderService {
private ignoreFileEventsFromTrashedDir(trashingDir: string) {
this.eventQueue = this.eventQueue.filter((event) =>
- event.paths.every((path) => !path.startsWith(trashingDir))
+ event.paths.every((path) => !path.startsWith(trashingDir)),
);
}
@@ -567,7 +567,7 @@ class watchFolderService {
(mapping) =>
filePath.length > mapping.folderPath.length &&
filePath.startsWith(mapping.folderPath) &&
- filePath[mapping.folderPath.length] === '/'
+ filePath[mapping.folderPath.length] === "/",
);
if (!mapping) {
@@ -577,18 +577,18 @@ class watchFolderService {
return {
collectionName: this.getCollectionNameForMapping(
mapping,
- filePath
+ filePath,
),
folderPath: mapping.folderPath,
};
} catch (e) {
- logError(e, 'error while getting collection name');
+ logError(e, "error while getting collection name");
}
}
private getCollectionNameForMapping(
mapping: WatchMapping,
- filePath: string
+ filePath: string,
) {
return mapping.uploadStrategy === UPLOAD_STRATEGY.COLLECTION_PER_FOLDER
? getParentFolderName(filePath)
@@ -600,7 +600,7 @@ class watchFolderService {
const folderPath = await ElectronAPIs.selectDirectory();
return folderPath;
} catch (e) {
- logError(e, 'error while selecting folder');
+ logError(e, "error while selecting folder");
}
}
@@ -613,7 +613,7 @@ class watchFolderService {
event.collectionName === this.eventQueue[0].collectionName &&
event.type === this.eventQueue[0].type
) {
- if (event.type === 'trash') {
+ if (event.type === "trash") {
event.paths = [...event.paths, ...this.eventQueue[0].paths];
} else {
event.files = [...event.files, ...this.eventQueue[0].files];
@@ -628,7 +628,7 @@ class watchFolderService {
const isFolder = await ElectronAPIs.isFolder(folderPath);
return isFolder;
} catch (e) {
- logError(e, 'error while checking if folder exists');
+ logError(e, "error while checking if folder exists");
}
}
diff --git a/apps/photos/src/styles/dropdown.ts b/apps/photos/src/styles/dropdown.ts
index be7b96280e..9feb9f94bc 100644
--- a/apps/photos/src/styles/dropdown.ts
+++ b/apps/photos/src/styles/dropdown.ts
@@ -1,20 +1,20 @@
-import { SelectStyles } from './search';
+import { SelectStyles } from "./search";
export const DropdownStyle = {
...SelectStyles,
dropdownIndicator: (style) => ({
...style,
- margin: '0px',
+ margin: "0px",
}),
singleValue: (style) => ({
...style,
- color: '#d1d1d1',
- width: '240px',
+ color: "#d1d1d1",
+ width: "240px",
}),
control: (style, { isFocused }) => ({
...style,
...SelectStyles.control(style, { isFocused }),
- minWidth: '240px',
- paddingLeft: '8px',
+ minWidth: "240px",
+ paddingLeft: "8px",
}),
};
diff --git a/apps/photos/src/styles/global.css b/apps/photos/src/styles/global.css
index a48b4c089b..91c08ddcf7 100644
--- a/apps/photos/src/styles/global.css
+++ b/apps/photos/src/styles/global.css
@@ -1,39 +1,39 @@
/* inter-regular - latin */
@font-face {
- font-family: 'Inter';
+ font-family: "Inter";
font-style: normal;
font-weight: 400;
src:
- local(''),
- url('/fonts/inter-v11-latin-500.woff2') format('woff2'),
+ local(""),
+ url("/fonts/inter-v11-latin-500.woff2") format("woff2"),
/* Chrome 26+, Opera 23+, Firefox 39+ */
- url('/fonts/inter-v11-latin-500.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
+ url("/fonts/inter-v11-latin-500.woff") format("woff"); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
font-display: swap; /*https://web.dev/font-display/?utm_source=lighthouse&utm_medium=devtools#how-to-avoid-showing-invisible-text*/
}
/* inter-600 - latin */
@font-face {
- font-family: 'Inter';
+ font-family: "Inter";
font-style: normal;
font-weight: 700;
src:
- local(''),
- url('/fonts/inter-v11-latin-600.woff2') format('woff2'),
+ local(""),
+ url("/fonts/inter-v11-latin-600.woff2") format("woff2"),
/* Chrome 26+, Opera 23+, Firefox 39+ */
- url('/fonts/inter-v11-latin-600.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
+ url("/fonts/inter-v11-latin-600.woff") format("woff"); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
font-display: swap;
}
/* inter-800 - latin */
@font-face {
- font-family: 'Inter';
+ font-family: "Inter";
font-style: normal;
font-weight: 900;
src:
- local(''),
- url('/fonts/inter-v11-latin-800.woff2') format('woff2'),
+ local(""),
+ url("/fonts/inter-v11-latin-800.woff2") format("woff2"),
/* Chrome 26+, Opera 23+, Firefox 39+ */
- url('/fonts/inter-v11-latin-800.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
+ url("/fonts/inter-v11-latin-800.woff") format("woff"); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
font-display: swap;
}
diff --git a/apps/photos/src/styles/linkExpiry.tsx b/apps/photos/src/styles/linkExpiry.tsx
index 6f5e15243c..852569ae1e 100644
--- a/apps/photos/src/styles/linkExpiry.tsx
+++ b/apps/photos/src/styles/linkExpiry.tsx
@@ -1,11 +1,11 @@
-import { DropdownStyle } from './dropdown';
+import { DropdownStyle } from "./dropdown";
export const linkExpiryStyle = {
...DropdownStyle,
placeholder: (style) => ({
...style,
- color: '#d1d1d1',
- width: '100%',
- textAlign: 'center',
+ color: "#d1d1d1",
+ width: "100%",
+ textAlign: "center",
}),
};
diff --git a/apps/photos/src/styles/search.ts b/apps/photos/src/styles/search.ts
index 65bbf894e8..1127595fb7 100644
--- a/apps/photos/src/styles/search.ts
+++ b/apps/photos/src/styles/search.ts
@@ -5,61 +5,61 @@ export const SelectStyles = {
}),
control: (style, { isFocused }) => ({
...style,
- backgroundColor: 'rgba(255, 255, 255, 0.1)',
+ backgroundColor: "rgba(255, 255, 255, 0.1)",
- borderColor: isFocused ? '#1dba54' : 'transparent',
- boxShadow: 'none',
- ':hover': {
- borderColor: '#1dba54',
- cursor: 'text',
+ borderColor: isFocused ? "#1dba54" : "transparent",
+ boxShadow: "none",
+ ":hover": {
+ borderColor: "#1dba54",
+ cursor: "text",
},
}),
input: (style) => ({
...style,
- color: '#fff',
+ color: "#fff",
}),
menu: (style) => ({
...style,
- marginTop: '1px',
- backgroundColor: '#1b1b1b',
+ marginTop: "1px",
+ backgroundColor: "#1b1b1b",
}),
option: (style, { isFocused }) => ({
...style,
padding: 0,
- backgroundColor: 'transparent !important',
- '& :hover': {
- cursor: 'pointer',
+ backgroundColor: "transparent !important",
+ "& :hover": {
+ cursor: "pointer",
},
- '& .main': {
- backgroundColor: isFocused && '#202020',
+ "& .main": {
+ backgroundColor: isFocused && "#202020",
},
- '&:last-child .MuiDivider-root': {
- display: 'none',
+ "&:last-child .MuiDivider-root": {
+ display: "none",
},
}),
dropdownIndicator: (style) => ({
...style,
- display: 'none',
+ display: "none",
}),
indicatorSeparator: (style) => ({
...style,
- display: 'none',
+ display: "none",
}),
clearIndicator: (style) => ({
...style,
- display: 'none',
+ display: "none",
}),
singleValue: (style) => ({
...style,
- backgroundColor: 'transparent',
- color: '#d1d1d1',
- marginLeft: '36px',
+ backgroundColor: "transparent",
+ color: "#d1d1d1",
+ marginLeft: "36px",
}),
placeholder: (style) => ({
...style,
- color: 'rgba(255, 255, 255, 0.7)',
- wordSpacing: '2px',
- whiteSpace: 'nowrap',
- marginLeft: '40px',
+ color: "rgba(255, 255, 255, 0.7)",
+ wordSpacing: "2px",
+ whiteSpace: "nowrap",
+ marginLeft: "40px",
}),
};
diff --git a/apps/photos/src/types/Notification/index.tsx b/apps/photos/src/types/Notification/index.tsx
index 6fd190ad35..b38fff9537 100644
--- a/apps/photos/src/types/Notification/index.tsx
+++ b/apps/photos/src/types/Notification/index.tsx
@@ -1,5 +1,5 @@
-import { ButtonProps } from '@mui/material/Button';
-import { ReactNode } from 'react';
+import { ButtonProps } from "@mui/material/Button";
+import { ReactNode } from "react";
export type NotificationAttributes =
| MessageSubTextNotificationAttributes
@@ -7,7 +7,7 @@ export type NotificationAttributes =
interface MessageSubTextNotificationAttributes {
startIcon?: ReactNode;
- variant: ButtonProps['color'];
+ variant: ButtonProps["color"];
message?: JSX.Element | string;
subtext?: JSX.Element | string;
title?: never;
@@ -18,7 +18,7 @@ interface MessageSubTextNotificationAttributes {
interface TitleCaptionNotificationAttributes {
startIcon?: ReactNode;
- variant: ButtonProps['color'];
+ variant: ButtonProps["color"];
title?: JSX.Element | string;
caption?: JSX.Element | string;
message?: never;
diff --git a/apps/photos/src/types/billing/index.ts b/apps/photos/src/types/billing/index.ts
index c72096bfb9..b2058948bc 100644
--- a/apps/photos/src/types/billing/index.ts
+++ b/apps/photos/src/types/billing/index.ts
@@ -1,4 +1,4 @@
-import { PLAN_PERIOD } from 'constants/gallery';
+import { PLAN_PERIOD } from "constants/gallery";
export interface Subscription {
id: number;
diff --git a/apps/photos/src/types/collection/index.ts b/apps/photos/src/types/collection/index.ts
index 068575a43f..91b96281c7 100644
--- a/apps/photos/src/types/collection/index.ts
+++ b/apps/photos/src/types/collection/index.ts
@@ -1,17 +1,17 @@
-import { EnteFile } from 'types/file';
-import { CollectionSummaryType, CollectionType } from 'constants/collection';
+import { CollectionSummaryType, CollectionType } from "constants/collection";
+import { EnteFile } from "types/file";
import {
EncryptedMagicMetadata,
MagicMetadataCore,
SUB_TYPE,
VISIBILITY_STATE,
-} from 'types/magicMetadata';
+} from "types/magicMetadata";
export enum COLLECTION_ROLE {
- VIEWER = 'VIEWER',
- OWNER = 'OWNER',
- COLLABORATOR = 'COLLABORATOR',
- UNKNOWN = 'UNKNOWN',
+ VIEWER = "VIEWER",
+ OWNER = "OWNER",
+ COLLABORATOR = "COLLABORATOR",
+ UNKNOWN = "UNKNOWN",
}
export interface CollectionUser {
@@ -43,13 +43,13 @@ export interface EncryptedCollection {
export interface Collection
extends Omit<
EncryptedCollection,
- | 'encryptedKey'
- | 'keyDecryptionNonce'
- | 'encryptedName'
- | 'nameDecryptionNonce'
- | 'magicMetadata'
- | 'pubMagicMetadata'
- | 'sharedMagicMetadata'
+ | "encryptedKey"
+ | "keyDecryptionNonce"
+ | "encryptedName"
+ | "nameDecryptionNonce"
+ | "magicMetadata"
+ | "pubMagicMetadata"
+ | "sharedMagicMetadata"
> {
key: string;
name: string;
diff --git a/apps/photos/src/types/common/job.ts b/apps/photos/src/types/common/job.ts
index d9136b6387..fe42e4aaf2 100644
--- a/apps/photos/src/types/common/job.ts
+++ b/apps/photos/src/types/common/job.ts
@@ -1,4 +1,4 @@
-export type JobState = 'Scheduled' | 'Running' | 'NotScheduled';
+export type JobState = "Scheduled" | "Running" | "NotScheduled";
export interface JobConfig {
intervalSec: number;
diff --git a/apps/photos/src/types/embedding.tsx b/apps/photos/src/types/embedding.tsx
index ad523e3a6c..3626e0fadb 100644
--- a/apps/photos/src/types/embedding.tsx
+++ b/apps/photos/src/types/embedding.tsx
@@ -1,6 +1,6 @@
export enum Model {
- GGML_CLIP = 'ggml-clip',
- ONNX_CLIP = 'onnx-clip',
+ GGML_CLIP = "ggml-clip",
+ ONNX_CLIP = "onnx-clip",
}
export interface EncryptedEmbedding {
@@ -14,7 +14,7 @@ export interface EncryptedEmbedding {
export interface Embedding
extends Omit<
EncryptedEmbedding,
- 'encryptedEmbedding' | 'decryptionHeader'
+ "encryptedEmbedding" | "decryptionHeader"
> {
embedding: Float32Array;
}
diff --git a/apps/photos/src/types/entity.ts b/apps/photos/src/types/entity.ts
index 7252c3767b..9580bf3332 100644
--- a/apps/photos/src/types/entity.ts
+++ b/apps/photos/src/types/entity.ts
@@ -1,7 +1,7 @@
-import { Location } from 'types/upload';
+import { Location } from "types/upload";
export enum EntityType {
- LOCATION_TAG = 'location',
+ LOCATION_TAG = "location",
}
export interface EncryptedEntityKey {
@@ -13,7 +13,7 @@ export interface EncryptedEntityKey {
}
export interface EntityKey
- extends Omit<EncryptedEntityKey, 'encryptedKey' | 'header'> {
+ extends Omit<EncryptedEntityKey, "encryptedKey" | "header"> {
data: string;
}
@@ -38,7 +38,7 @@ export interface LocationTagData {
export type LocationTag = Entity<LocationTagData>;
export interface Entity<T>
- extends Omit<EncryptedEntity, 'encryptedData' | 'header'> {
+ extends Omit<EncryptedEntity, "encryptedData" | "header"> {
data: T;
}
diff --git a/apps/photos/src/types/export/index.ts b/apps/photos/src/types/export/index.ts
index b52042bf79..ce85f32fd1 100644
--- a/apps/photos/src/types/export/index.ts
+++ b/apps/photos/src/types/export/index.ts
@@ -1,5 +1,5 @@
-import { ExportStage } from 'constants/export';
-import { EnteFile } from 'types/file';
+import { ExportStage } from "constants/export";
+import { EnteFile } from "types/file";
export interface ExportProgress {
success: number;
diff --git a/apps/photos/src/types/file/index.ts b/apps/photos/src/types/file/index.ts
index 8e24db033c..2991e1f8b0 100644
--- a/apps/photos/src/types/file/index.ts
+++ b/apps/photos/src/types/file/index.ts
@@ -1,10 +1,10 @@
-import { SourceURLs } from 'services/download';
+import { SourceURLs } from "services/download";
import {
EncryptedMagicMetadata,
MagicMetadataCore,
VISIBILITY_STATE,
-} from 'types/magicMetadata';
-import { Metadata } from 'types/upload';
+} from "types/magicMetadata";
+import { Metadata } from "types/upload";
export interface MetadataFileAttributes {
encryptedData: string;
@@ -39,11 +39,11 @@ export interface EncryptedEnteFile {
export interface EnteFile
extends Omit<
EncryptedEnteFile,
- | 'metadata'
- | 'pubMagicMetadata'
- | 'magicMetadata'
- | 'encryptedKey'
- | 'keyDecryptionNonce'
+ | "metadata"
+ | "pubMagicMetadata"
+ | "magicMetadata"
+ | "encryptedKey"
+ | "keyDecryptionNonce"
> {
metadata: Metadata;
magicMetadata: FileMagicMetadata;
diff --git a/apps/photos/src/types/gallery/index.ts b/apps/photos/src/types/gallery/index.ts
index f128a15368..a2e77f0b6c 100644
--- a/apps/photos/src/types/gallery/index.ts
+++ b/apps/photos/src/types/gallery/index.ts
@@ -1,9 +1,9 @@
-import { FilesDownloadProgressAttributes } from 'components/FilesDownloadProgress';
-import { CollectionSelectorAttributes } from 'components/Collections/CollectionSelector';
-import { TimeStampListItem } from 'components/PhotoList';
-import { Collection } from 'types/collection';
-import { EnteFile } from 'types/file';
-import { User } from '@ente/shared/user/types';
+import { User } from "@ente/shared/user/types";
+import { CollectionSelectorAttributes } from "components/Collections/CollectionSelector";
+import { FilesDownloadProgressAttributes } from "components/FilesDownloadProgress";
+import { TimeStampListItem } from "components/PhotoList";
+import { Collection } from "types/collection";
+import { EnteFile } from "types/file";
export type SelectedState = {
[k: number]: boolean;
@@ -21,14 +21,14 @@ export type SetFilesDownloadProgressAttributes = (
value:
| Partial<FilesDownloadProgressAttributes>
| ((
- prev: FilesDownloadProgressAttributes
- ) => FilesDownloadProgressAttributes)
+ prev: FilesDownloadProgressAttributes,
+ ) => FilesDownloadProgressAttributes),
) => void;
export type SetFilesDownloadProgressAttributesCreator = (
folderName: string,
collectionID?: number,
- isHidden?: boolean
+ isHidden?: boolean,
) => SetFilesDownloadProgressAttributes;
export type MergedSourceURL = {
diff --git a/apps/photos/src/types/machineLearning/index.ts b/apps/photos/src/types/machineLearning/index.ts
index fc061ca5da..64cf8f2f41 100644
--- a/apps/photos/src/types/machineLearning/index.ts
+++ b/apps/photos/src/types/machineLearning/index.ts
@@ -1,4 +1,4 @@
-import * as tf from '@tensorflow/tfjs-core';
+import * as tf from "@tensorflow/tfjs-core";
// import {
// FaceDetection,
@@ -6,13 +6,13 @@ import * as tf from '@tensorflow/tfjs-core';
// WithFaceDescriptor,
// WithFaceLandmarks,
// } from 'face-api.js';
-import { DebugInfo } from 'hdbscan';
-import PQueue from 'p-queue';
+import { DebugInfo } from "hdbscan";
+import PQueue from "p-queue";
// import { Point as D3Point, RawNodeDatum } from 'react-d3-tree/lib/types/common';
-import { EnteFile } from 'types/file';
-import { Dimensions } from 'types/image';
-import { Box, Point } from '../../../thirdparty/face-api/classes';
+import { EnteFile } from "types/file";
+import { Dimensions } from "types/image";
+import { Box, Point } from "../../../thirdparty/face-api/classes";
export interface MLSyncResult {
nOutOfSyncFiles: number;
@@ -87,24 +87,24 @@ export interface NearestCluster {
export declare type Landmark = Point;
-export declare type ImageType = 'Original' | 'Preview';
+export declare type ImageType = "Original" | "Preview";
-export declare type FaceDetectionMethod = 'BlazeFace' | 'FaceApiSSD';
+export declare type FaceDetectionMethod = "BlazeFace" | "FaceApiSSD";
-export declare type ObjectDetectionMethod = 'SSDMobileNetV2';
+export declare type ObjectDetectionMethod = "SSDMobileNetV2";
-export declare type SceneDetectionMethod = 'ImageScene';
+export declare type SceneDetectionMethod = "ImageScene";
-export declare type FaceCropMethod = 'ArcFace';
+export declare type FaceCropMethod = "ArcFace";
export declare type FaceAlignmentMethod =
- | 'ArcFace'
- | 'FaceApiDlib'
- | 'RotatedFaceApiDlib';
+ | "ArcFace"
+ | "FaceApiDlib"
+ | "RotatedFaceApiDlib";
-export declare type FaceEmbeddingMethod = 'MobileFaceNet' | 'FaceApiDlib';
+export declare type FaceEmbeddingMethod = "MobileFaceNet" | "FaceApiDlib";
-export declare type ClusteringMethod = 'Hdbscan' | 'Dbscan';
+export declare type ClusteringMethod = "Hdbscan" | "Dbscan";
export class AlignedBox {
box: Box;
@@ -262,7 +262,7 @@ export interface FaceEmbeddingConfig {
export interface FaceClusteringConfig extends ClusteringConfig {}
-export declare type TSNEMetric = 'euclidean' | 'manhattan';
+export declare type TSNEMetric = "euclidean" | "manhattan";
export interface TSNEConfig {
samples: number;
@@ -345,7 +345,7 @@ export interface MLLibraryData {
faceClustersWithNoise?: FacesClustersWithNoise;
}
-export declare type MLIndex = 'files' | 'people';
+export declare type MLIndex = "files" | "people";
export interface FaceDetectionService {
method: Versioned<FaceDetectionMethod>;
@@ -360,7 +360,7 @@ export interface ObjectDetectionService {
detectObjects(
image: ImageBitmap,
maxNumBoxes: number,
- minScore: number
+ minScore: number,
): Promise<ObjectDetection[]>;
dispose(): Promise<void>;
}
@@ -370,7 +370,7 @@ export interface SceneDetectionService {
// init(): Promise<void>;
detectScenes(
image: ImageBitmap,
- minScore: number
+ minScore: number,
): Promise<ObjectDetection[]>;
}
@@ -380,7 +380,7 @@ export interface FaceCropService {
getFaceCrop(
imageBitmap: ImageBitmap,
face: FaceDetection,
- config: FaceCropConfig
+ config: FaceCropConfig,
): Promise<FaceCrop>;
}
@@ -394,7 +394,7 @@ export interface FaceEmbeddingService {
faceSize: number;
// init(): Promise<void>;
getFaceEmbeddings(
- faceImages: Array<ImageBitmap>
+ faceImages: Array<ImageBitmap>,
): Promise<Array<FaceEmbedding>>;
dispose(): Promise<void>;
}
@@ -404,7 +404,7 @@ export interface ClusteringService {
cluster(
input: ClusteringInput,
- config: ClusteringConfig
+ config: ClusteringConfig,
): Promise<ClusteringResults>;
}
@@ -413,7 +413,7 @@ export interface ClusteringConfig {
minClusterSize: number;
minSamples?: number;
clusterSelectionEpsilon?: number;
- clusterSelectionMethod?: 'eom' | 'leaf';
+ clusterSelectionMethod?: "eom" | "leaf";
maxDistanceInsideCluster?: number;
minInputSize?: number;
generateDebugInfo?: boolean;
@@ -428,7 +428,7 @@ export interface MachineLearningWorker {
token: string,
userID: number,
enteFile: EnteFile,
- localFile: globalThis.File
+ localFile: globalThis.File,
): Promise<MlFileData | Error>;
sync(token: string, userID: number): Promise<MLSyncResult>;
diff --git a/apps/photos/src/types/publicCollection/index.ts b/apps/photos/src/types/publicCollection/index.ts
index dca173904a..7e3203e774 100644
--- a/apps/photos/src/types/publicCollection/index.ts
+++ b/apps/photos/src/types/publicCollection/index.ts
@@ -1,7 +1,7 @@
-import { TimeStampListItem } from 'components/PhotoList';
-import { REPORT_REASON } from 'constants/publicCollection';
-import { PublicURL } from 'types/collection';
-import { EnteFile } from 'types/file';
+import { TimeStampListItem } from "components/PhotoList";
+import { REPORT_REASON } from "constants/publicCollection";
+import { PublicURL } from "types/collection";
+import { EnteFile } from "types/file";
export interface PublicCollectionGalleryContextType {
token: string;
diff --git a/apps/photos/src/types/search/index.ts b/apps/photos/src/types/search/index.ts
index 2e6c94f48a..5976db2a30 100644
--- a/apps/photos/src/types/search/index.ts
+++ b/apps/photos/src/types/search/index.ts
@@ -1,23 +1,23 @@
-import { Person, Thing, WordGroup } from 'types/machineLearning';
-import { IndexStatus } from 'types/machineLearning/ui';
-import { EnteFile } from 'types/file';
-import { LocationTagData } from 'types/entity';
-import { FILE_TYPE } from 'constants/file';
-import { City } from 'services/locationSearchService';
+import { FILE_TYPE } from "constants/file";
+import { City } from "services/locationSearchService";
+import { LocationTagData } from "types/entity";
+import { EnteFile } from "types/file";
+import { Person, Thing, WordGroup } from "types/machineLearning";
+import { IndexStatus } from "types/machineLearning/ui";
export enum SuggestionType {
- DATE = 'DATE',
- LOCATION = 'LOCATION',
- COLLECTION = 'COLLECTION',
- FILE_NAME = 'FILE_NAME',
- PERSON = 'PERSON',
- INDEX_STATUS = 'INDEX_STATUS',
- THING = 'THING',
- TEXT = 'TEXT',
- FILE_CAPTION = 'FILE_CAPTION',
- FILE_TYPE = 'FILE_TYPE',
- CLIP = 'CLIP',
- CITY = 'CITY',
+ DATE = "DATE",
+ LOCATION = "LOCATION",
+ COLLECTION = "COLLECTION",
+ FILE_NAME = "FILE_NAME",
+ PERSON = "PERSON",
+ INDEX_STATUS = "INDEX_STATUS",
+ THING = "THING",
+ TEXT = "TEXT",
+ FILE_CAPTION = "FILE_CAPTION",
+ FILE_TYPE = "FILE_TYPE",
+ CLIP = "CLIP",
+ CITY = "CITY",
}
export interface DateValue {
@@ -68,7 +68,7 @@ export interface SearchOption extends Suggestion {
export type UpdateSearch = (
search: Search,
- summary: SearchResultSummary
+ summary: SearchResultSummary,
) => void;
export type ClipSearchScores = Map<number, number>;
diff --git a/apps/photos/src/types/trash/index.ts b/apps/photos/src/types/trash/index.ts
index 48de52a217..d7e231c1a9 100644
--- a/apps/photos/src/types/trash/index.ts
+++ b/apps/photos/src/types/trash/index.ts
@@ -1,6 +1,6 @@
-import { EncryptedEnteFile, EnteFile } from 'types/file';
+import { EncryptedEnteFile, EnteFile } from "types/file";
-export interface TrashItem extends Omit<EncryptedTrashItem, 'file'> {
+export interface TrashItem extends Omit<EncryptedTrashItem, "file"> {
file: EnteFile;
}
diff --git a/apps/photos/src/types/upload/index.ts b/apps/photos/src/types/upload/index.ts
index 8ba1e957bc..0d38f6190f 100644
--- a/apps/photos/src/types/upload/index.ts
+++ b/apps/photos/src/types/upload/index.ts
@@ -1,16 +1,16 @@
-import { FILE_TYPE } from 'constants/file';
-import { Collection } from 'types/collection';
import {
B64EncryptionResult,
LocalFileAttributes,
-} from '@ente/shared/crypto/types';
+} from "@ente/shared/crypto/types";
+import { FILE_TYPE } from "constants/file";
+import { Collection } from "types/collection";
import {
- MetadataFileAttributes,
- S3FileAttributes,
FilePublicMagicMetadata,
FilePublicMagicMetadataProps,
-} from 'types/file';
-import { EncryptedMagicMetadata } from 'types/magicMetadata';
+ MetadataFileAttributes,
+ S3FileAttributes,
+} from "types/file";
+import { EncryptedMagicMetadata } from "types/magicMetadata";
export interface DataStream {
stream: ReadableStream<Uint8Array>;
@@ -18,7 +18,7 @@ export interface DataStream {
}
export function isDataStream(object: any): object is DataStream {
- return 'stream' in object;
+ return "stream" in object;
}
export type Logger = (message: string) => void;
@@ -114,7 +114,7 @@ export interface FileInMemory {
}
export interface FileWithMetadata
- extends Omit<FileInMemory, 'hasStaticThumbnail'> {
+ extends Omit<FileInMemory, "hasStaticThumbnail"> {
metadata: Metadata;
localID: number;
pubMagicMetadata: FilePublicMagicMetadata;
diff --git a/apps/photos/src/types/upload/ui.ts b/apps/photos/src/types/upload/ui.ts
index 4283e30a15..bce381213f 100644
--- a/apps/photos/src/types/upload/ui.ts
+++ b/apps/photos/src/types/upload/ui.ts
@@ -1,4 +1,4 @@
-import { UPLOAD_RESULT, UPLOAD_STAGES } from 'constants/upload';
+import { UPLOAD_RESULT, UPLOAD_STAGES } from "constants/upload";
export type FileID = number;
export type FileName = string;
diff --git a/apps/photos/src/types/user/index.ts b/apps/photos/src/types/user/index.ts
index a187ceddd9..2b6c4ff45e 100644
--- a/apps/photos/src/types/user/index.ts
+++ b/apps/photos/src/types/user/index.ts
@@ -1,4 +1,4 @@
-import { Subscription } from 'types/billing';
+import { Subscription } from "types/billing";
export interface FamilyMember {
email: string;
diff --git a/apps/photos/src/types/watchFolder/index.ts b/apps/photos/src/types/watchFolder/index.ts
index e03897b105..bd55704de9 100644
--- a/apps/photos/src/types/watchFolder/index.ts
+++ b/apps/photos/src/types/watchFolder/index.ts
@@ -1,5 +1,5 @@
-import { UPLOAD_STRATEGY } from 'constants/upload';
-import { ElectronFile } from 'types/upload';
+import { UPLOAD_STRATEGY } from "constants/upload";
+import { ElectronFile } from "types/upload";
export interface WatchMappingSyncedFile {
path: string;
@@ -16,7 +16,7 @@ export interface WatchMapping {
}
export interface EventQueueItem {
- type: 'upload' | 'trash';
+ type: "upload" | "trash";
folderPath: string;
collectionName?: string;
paths?: string[];
diff --git a/apps/photos/src/utils/billing/index.ts b/apps/photos/src/utils/billing/index.ts
index b970d70082..5b8ee5dd09 100644
--- a/apps/photos/src/utils/billing/index.ts
+++ b/apps/photos/src/utils/billing/index.ts
@@ -1,37 +1,37 @@
-import { t } from 'i18next';
-
-import billingService from 'services/billingService';
-import { Plan, Subscription } from 'types/billing';
-import { NextRouter } from 'next/router';
-import { SetLoading } from 'types/gallery';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import { logError } from '@ente/shared/sentry';
-import { SetDialogBoxAttributes } from '@ente/shared/components/DialogBox/types';
-import { openLink } from 'utils/common';
-import { isPartOfFamily, getTotalFamilyUsage } from 'utils/user/family';
-import { BonusData, UserDetails } from 'types/user';
-import { getSubscriptionPurchaseSuccessMessage } from 'utils/ui';
-import { getRedirectURL, REDIRECTS } from 'constants/redirects';
-
-const PAYMENT_PROVIDER_STRIPE = 'stripe';
-const PAYMENT_PROVIDER_APPSTORE = 'appstore';
-const PAYMENT_PROVIDER_PLAYSTORE = 'playstore';
-const FREE_PLAN = 'free';
+import { t } from "i18next";
+
+import { SetDialogBoxAttributes } from "@ente/shared/components/DialogBox/types";
+import { logError } from "@ente/shared/sentry";
+import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
+import { REDIRECTS, getRedirectURL } from "constants/redirects";
+import { NextRouter } from "next/router";
+import billingService from "services/billingService";
+import { Plan, Subscription } from "types/billing";
+import { SetLoading } from "types/gallery";
+import { BonusData, UserDetails } from "types/user";
+import { openLink } from "utils/common";
+import { getSubscriptionPurchaseSuccessMessage } from "utils/ui";
+import { getTotalFamilyUsage, isPartOfFamily } from "utils/user/family";
+
+const PAYMENT_PROVIDER_STRIPE = "stripe";
+const PAYMENT_PROVIDER_APPSTORE = "appstore";
+const PAYMENT_PROVIDER_PLAYSTORE = "playstore";
+const FREE_PLAN = "free";
enum FAILURE_REASON {
- AUTHENTICATION_FAILED = 'authentication_failed',
- REQUIRE_PAYMENT_METHOD = 'requires_payment_method',
- STRIPE_ERROR = 'stripe_error',
- CANCELED = 'canceled',
- SERVER_ERROR = 'server_error',
+ AUTHENTICATION_FAILED = "authentication_failed",
+ REQUIRE_PAYMENT_METHOD = "requires_payment_method",
+ STRIPE_ERROR = "stripe_error",
+ CANCELED = "canceled",
+ SERVER_ERROR = "server_error",
}
enum RESPONSE_STATUS {
- success = 'success',
- fail = 'fail',
+ success = "success",
+ fail = "fail",
}
-const StorageUnits = ['B', 'KB', 'MB', 'GB', 'TB'];
+const StorageUnits = ["B", "KB", "MB", "GB", "TB"];
const ONE_GB = 1024 * 1024 * 1024;
@@ -41,17 +41,17 @@ export function convertBytesToGBs(bytes: number, precision = 0): string {
export function makeHumanReadableStorage(
bytes: number,
- { roundUp } = { roundUp: false }
+ { roundUp } = { roundUp: false },
): string {
if (bytes <= 0) {
- return `0 ${t('STORAGE_UNITS.MB')}`;
+ return `0 ${t("STORAGE_UNITS.MB")}`;
}
const i = Math.floor(Math.log(bytes) / Math.log(1024));
let quantity = bytes / Math.pow(1024, i);
let unit = StorageUnits[i];
- if (quantity > 100 && unit !== 'GB') {
+ if (quantity > 100 && unit !== "GB") {
quantity /= 1024;
unit = StorageUnits[i + 1];
}
@@ -102,7 +102,7 @@ export function hasAddOnBonus(bonusData?: BonusData) {
bonusData.storageBonuses &&
bonusData.storageBonuses.length > 0 &&
bonusData.storageBonuses.some((bonus) =>
- bonus.type.startsWith('ADD_ON')
+ bonus.type.startsWith("ADD_ON"),
)
);
}
@@ -159,16 +159,16 @@ export async function updateSubscription(
plan: Plan,
setDialogMessage: SetDialogBoxAttributes,
setLoading: SetLoading,
- closePlanSelectorModal: () => null
+ closePlanSelectorModal: () => null,
) {
try {
setLoading(true);
await billingService.updateSubscription(plan.stripeID);
} catch (err) {
setDialogMessage({
- title: t('ERROR'),
- content: t('SUBSCRIPTION_UPDATE_FAILED'),
- close: { variant: 'critical' },
+ title: t("ERROR"),
+ content: t("SUBSCRIPTION_UPDATE_FAILED"),
+ close: { variant: "critical" },
});
} finally {
setLoading(false);
@@ -179,21 +179,21 @@ export async function updateSubscription(
export async function cancelSubscription(
setDialogMessage: SetDialogBoxAttributes,
closePlanSelectorModal: () => void,
- setLoading: SetLoading
+ setLoading: SetLoading,
) {
try {
setLoading(true);
await billingService.cancelSubscription();
setDialogMessage({
- title: t('SUCCESS'),
- content: t('SUBSCRIPTION_CANCEL_SUCCESS'),
- close: { variant: 'accent' },
+ title: t("SUCCESS"),
+ content: t("SUBSCRIPTION_CANCEL_SUCCESS"),
+ close: { variant: "accent" },
});
} catch (e) {
setDialogMessage({
- title: t('ERROR'),
- content: t('SUBSCRIPTION_CANCEL_FAILED'),
- close: { variant: 'critical' },
+ title: t("ERROR"),
+ content: t("SUBSCRIPTION_CANCEL_FAILED"),
+ close: { variant: "critical" },
});
} finally {
closePlanSelectorModal();
@@ -204,21 +204,21 @@ export async function cancelSubscription(
export async function activateSubscription(
setDialogMessage: SetDialogBoxAttributes,
closePlanSelectorModal: () => void,
- setLoading: SetLoading
+ setLoading: SetLoading,
) {
try {
setLoading(true);
await billingService.activateSubscription();
setDialogMessage({
- title: t('SUCCESS'),
- content: t('SUBSCRIPTION_ACTIVATE_SUCCESS'),
- close: { variant: 'accent' },
+ title: t("SUCCESS"),
+ content: t("SUBSCRIPTION_ACTIVATE_SUCCESS"),
+ close: { variant: "accent" },
});
} catch (e) {
setDialogMessage({
- title: t('ERROR'),
- content: t('SUBSCRIPTION_ACTIVATE_FAILED'),
- close: { variant: 'critical' },
+ title: t("ERROR"),
+ content: t("SUBSCRIPTION_ACTIVATE_FAILED"),
+ close: { variant: "critical" },
});
} finally {
closePlanSelectorModal();
@@ -228,7 +228,7 @@ export async function activateSubscription(
export async function updatePaymentMethod(
setDialogMessage: SetDialogBoxAttributes,
- setLoading: SetLoading
+ setLoading: SetLoading,
) {
try {
setLoading(true);
@@ -236,27 +236,27 @@ export async function updatePaymentMethod(
} catch (error) {
setLoading(false);
setDialogMessage({
- title: t('ERROR'),
- content: t('UNKNOWN_ERROR'),
- close: { variant: 'critical' },
+ title: t("ERROR"),
+ content: t("UNKNOWN_ERROR"),
+ close: { variant: "critical" },
});
}
}
export async function manageFamilyMethod(
setDialogMessage: SetDialogBoxAttributes,
- setLoading: SetLoading
+ setLoading: SetLoading,
) {
try {
setLoading(true);
const familyPortalRedirectURL = getRedirectURL(REDIRECTS.FAMILIES);
openLink(familyPortalRedirectURL, true);
} catch (error) {
- logError(error, 'failed to redirect to family portal');
+ logError(error, "failed to redirect to family portal");
setDialogMessage({
- title: t('ERROR'),
- content: t('UNKNOWN_ERROR'),
- close: { variant: 'critical' },
+ title: t("ERROR"),
+ content: t("UNKNOWN_ERROR"),
+ close: { variant: "critical" },
});
} finally {
setLoading(false);
@@ -266,7 +266,7 @@ export async function manageFamilyMethod(
export async function checkSubscriptionPurchase(
setDialogMessage: SetDialogBoxAttributes,
router: NextRouter,
- setLoading: SetLoading
+ setLoading: SetLoading,
) {
const { session_id: sessionId, status, reason } = router.query ?? {};
try {
@@ -275,15 +275,15 @@ export async function checkSubscriptionPurchase(
} else if (status === RESPONSE_STATUS.success) {
try {
const subscription = await billingService.verifySubscription(
- sessionId as string
+ sessionId as string,
);
setDialogMessage(
- getSubscriptionPurchaseSuccessMessage(subscription)
+ getSubscriptionPurchaseSuccessMessage(subscription),
);
} catch (e) {
setDialogMessage({
- title: t('ERROR'),
- content: t('SUBSCRIPTION_VERIFICATION_ERROR'),
+ title: t("ERROR"),
+ content: t("SUBSCRIPTION_VERIFICATION_ERROR"),
close: {},
});
}
@@ -296,60 +296,60 @@ export async function checkSubscriptionPurchase(
function handleFailureReason(
reason: string,
setDialogMessage: SetDialogBoxAttributes,
- setLoading: SetLoading
+ setLoading: SetLoading,
): void {
- logError(Error(reason), 'subscription purchase failed');
+ logError(Error(reason), "subscription purchase failed");
switch (reason) {
case FAILURE_REASON.CANCELED:
setDialogMessage({
- title: t('MESSAGE'),
- content: t('SUBSCRIPTION_PURCHASE_CANCELLED'),
- close: { variant: 'critical' },
+ title: t("MESSAGE"),
+ content: t("SUBSCRIPTION_PURCHASE_CANCELLED"),
+ close: { variant: "critical" },
});
break;
case FAILURE_REASON.REQUIRE_PAYMENT_METHOD:
setDialogMessage({
- title: t('UPDATE_PAYMENT_METHOD'),
- content: t('UPDATE_PAYMENT_METHOD_MESSAGE'),
+ title: t("UPDATE_PAYMENT_METHOD"),
+ content: t("UPDATE_PAYMENT_METHOD_MESSAGE"),
proceed: {
- text: t('UPDATE_PAYMENT_METHOD'),
- variant: 'accent',
+ text: t("UPDATE_PAYMENT_METHOD"),
+ variant: "accent",
action: updatePaymentMethod.bind(
null,
setDialogMessage,
- setLoading
+ setLoading,
),
},
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
});
break;
case FAILURE_REASON.AUTHENTICATION_FAILED:
setDialogMessage({
- title: t('UPDATE_PAYMENT_METHOD'),
- content: t('STRIPE_AUTHENTICATION_FAILED'),
+ title: t("UPDATE_PAYMENT_METHOD"),
+ content: t("STRIPE_AUTHENTICATION_FAILED"),
proceed: {
- text: t('UPDATE_PAYMENT_METHOD'),
- variant: 'accent',
+ text: t("UPDATE_PAYMENT_METHOD"),
+ variant: "accent",
action: updatePaymentMethod.bind(
null,
setDialogMessage,
- setLoading
+ setLoading,
),
},
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
});
break;
default:
setDialogMessage({
- title: t('ERROR'),
- content: t('SUBSCRIPTION_PURCHASE_FAILED'),
- close: { variant: 'critical' },
+ title: t("ERROR"),
+ content: t("SUBSCRIPTION_PURCHASE_FAILED"),
+ close: { variant: "critical" },
});
}
}
diff --git a/apps/photos/src/utils/collection/index.ts b/apps/photos/src/utils/collection/index.ts
index 2c50e99345..4b4b347fee 100644
--- a/apps/photos/src/utils/collection/index.ts
+++ b/apps/photos/src/utils/collection/index.ts
@@ -1,3 +1,24 @@
+import ElectronAPIs from "@ente/shared/electron";
+import { CustomError } from "@ente/shared/error";
+import { addLogLine } from "@ente/shared/logging";
+import { getAlbumsURL } from "@ente/shared/network/api";
+import { logError } from "@ente/shared/sentry";
+import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
+import { getUnixTimeInMicroSecondsWithDelta } from "@ente/shared/time";
+import { User } from "@ente/shared/user/types";
+import bs58 from "bs58";
+import {
+ ADD_TO_NOT_ALLOWED_COLLECTION,
+ CollectionSummaryType,
+ CollectionType,
+ DEFAULT_HIDDEN_COLLECTION_USER_FACING_NAME,
+ HIDE_FROM_COLLECTION_BAR_TYPES,
+ MOVE_TO_NOT_ALLOWED_COLLECTION,
+ OPTIONS_NOT_HAVING_COLLECTION_TYPES,
+ SYSTEM_COLLECTION_TYPES,
+} from "constants/collection";
+import { t } from "i18next";
+import isElectron from "is-electron";
import {
addToCollection,
createAlbum,
@@ -11,46 +32,25 @@ import {
updateCollectionMagicMetadata,
updatePublicCollectionMagicMetadata,
updateSharedCollectionMagicMetadata,
-} from 'services/collectionService';
-import { downloadFilesWithProgress } from 'utils/file';
-import { getAllLocalFiles, getLocalFiles } from 'services/fileService';
-import { EnteFile } from 'types/file';
-import { CustomError } from '@ente/shared/error';
-import { User } from '@ente/shared/user/types';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import { logError } from '@ente/shared/sentry';
+} from "services/collectionService";
+import exportService from "services/export";
+import { getAllLocalFiles, getLocalFiles } from "services/fileService";
import {
COLLECTION_ROLE,
Collection,
CollectionMagicMetadataProps,
CollectionPublicMagicMetadataProps,
CollectionSummaries,
-} from 'types/collection';
-import {
- CollectionSummaryType,
- CollectionType,
- HIDE_FROM_COLLECTION_BAR_TYPES,
- OPTIONS_NOT_HAVING_COLLECTION_TYPES,
- SYSTEM_COLLECTION_TYPES,
- MOVE_TO_NOT_ALLOWED_COLLECTION,
- ADD_TO_NOT_ALLOWED_COLLECTION,
- DEFAULT_HIDDEN_COLLECTION_USER_FACING_NAME,
-} from 'constants/collection';
-import { getUnixTimeInMicroSecondsWithDelta } from '@ente/shared/time';
-import { SUB_TYPE, VISIBILITY_STATE } from 'types/magicMetadata';
-import { isArchivedCollection, updateMagicMetadata } from 'utils/magicMetadata';
-import { getAlbumsURL } from '@ente/shared/network/api';
-import bs58 from 'bs58';
-import { t } from 'i18next';
-import isElectron from 'is-electron';
-import { SetFilesDownloadProgressAttributes } from 'types/gallery';
-import ElectronAPIs from '@ente/shared/electron';
+} from "types/collection";
+import { EnteFile } from "types/file";
+import { SetFilesDownloadProgressAttributes } from "types/gallery";
+import { SUB_TYPE, VISIBILITY_STATE } from "types/magicMetadata";
import {
getCollectionExportPath,
getUniqueCollectionExportName,
-} from 'utils/export';
-import exportService from 'services/export';
-import { addLogLine } from '@ente/shared/logging';
+} from "utils/export";
+import { downloadFilesWithProgress } from "utils/file";
+import { isArchivedCollection, updateMagicMetadata } from "utils/magicMetadata";
export enum COLLECTION_OPS_TYPE {
ADD,
@@ -63,7 +63,7 @@ export async function handleCollectionOps(
type: COLLECTION_OPS_TYPE,
collection: Collection,
selectedFiles: EnteFile[],
- selectedCollectionID: number
+ selectedCollectionID: number,
) {
switch (type) {
case COLLECTION_OPS_TYPE.ADD:
@@ -73,7 +73,7 @@ export async function handleCollectionOps(
await moveToCollection(
selectedCollectionID,
collection,
- selectedFiles
+ selectedFiles,
);
break;
case COLLECTION_OPS_TYPE.REMOVE:
@@ -92,62 +92,62 @@ export async function handleCollectionOps(
export function getSelectedCollection(
collectionID: number,
- collections: Collection[]
+ collections: Collection[],
) {
return collections.find((collection) => collection.id === collectionID);
}
export async function downloadCollectionHelper(
collectionID: number,
- setFilesDownloadProgressAttributes: SetFilesDownloadProgressAttributes
+ setFilesDownloadProgressAttributes: SetFilesDownloadProgressAttributes,
) {
try {
const allFiles = await getAllLocalFiles();
const collectionFiles = allFiles.filter(
- (file) => file.collectionID === collectionID
+ (file) => file.collectionID === collectionID,
);
const allCollections = await getAllLocalCollections();
const collection = allCollections.find(
- (collection) => collection.id === collectionID
+ (collection) => collection.id === collectionID,
);
if (!collection) {
- throw Error('collection not found');
+ throw Error("collection not found");
}
await downloadCollectionFiles(
collection.name,
collectionFiles,
- setFilesDownloadProgressAttributes
+ setFilesDownloadProgressAttributes,
);
} catch (e) {
- logError(e, 'download collection failed ');
+ logError(e, "download collection failed ");
}
}
export async function downloadDefaultHiddenCollectionHelper(
- setFilesDownloadProgressAttributes: SetFilesDownloadProgressAttributes
+ setFilesDownloadProgressAttributes: SetFilesDownloadProgressAttributes,
) {
try {
- const hiddenCollections = await getLocalCollections('hidden');
+ const hiddenCollections = await getLocalCollections("hidden");
const defaultHiddenCollectionsIds =
getDefaultHiddenCollectionIDs(hiddenCollections);
- const hiddenFiles = await getLocalFiles('hidden');
+ const hiddenFiles = await getLocalFiles("hidden");
const defaultHiddenCollectionFiles = hiddenFiles.filter((file) =>
- defaultHiddenCollectionsIds.has(file.collectionID)
+ defaultHiddenCollectionsIds.has(file.collectionID),
);
await downloadCollectionFiles(
DEFAULT_HIDDEN_COLLECTION_USER_FACING_NAME,
defaultHiddenCollectionFiles,
- setFilesDownloadProgressAttributes
+ setFilesDownloadProgressAttributes,
);
} catch (e) {
- logError(e, 'download hidden files failed ');
+ logError(e, "download hidden files failed ");
}
}
export async function downloadCollectionFiles(
collectionName: string,
collectionFiles: EnteFile[],
- setFilesDownloadProgressAttributes: SetFilesDownloadProgressAttributes
+ setFilesDownloadProgressAttributes: SetFilesDownloadProgressAttributes,
) {
if (!collectionFiles.length) {
return;
@@ -160,27 +160,27 @@ export async function downloadCollectionFiles(
}
downloadDirPath = await createCollectionDownloadFolder(
selectedDir,
- collectionName
+ collectionName,
);
}
await downloadFilesWithProgress(
collectionFiles,
downloadDirPath,
- setFilesDownloadProgressAttributes
+ setFilesDownloadProgressAttributes,
);
}
async function createCollectionDownloadFolder(
downloadDirPath: string,
- collectionName: string
+ collectionName: string,
) {
const collectionDownloadName = getUniqueCollectionExportName(
downloadDirPath,
- collectionName
+ collectionName,
);
const collectionDownloadPath = getCollectionExportPath(
downloadDirPath,
- collectionDownloadName
+ collectionDownloadName,
);
await exportService.checkExistsAndCreateDir(collectionDownloadPath);
return collectionDownloadPath;
@@ -188,7 +188,7 @@ async function createCollectionDownloadFolder(
export function appendCollectionKeyToShareURL(
url: string,
- collectionKey: string
+ collectionKey: string,
) {
if (!url) {
return null;
@@ -201,13 +201,13 @@ export function appendCollectionKeyToShareURL(
sharableURL.host = albumsURL.host;
sharableURL.pathname = albumsURL.pathname;
- const bytes = Buffer.from(collectionKey, 'base64');
+ const bytes = Buffer.from(collectionKey, "base64");
sharableURL.hash = bs58.encode(bytes);
return sharableURL.href;
}
const _intSelectOption = (i: number) => {
- const label = i === 0 ? t('NO_DEVICE_LIMIT') : i.toString();
+ const label = i === 0 ? t("NO_DEVICE_LIMIT") : i.toString();
return { label, value: i };
};
@@ -216,32 +216,32 @@ export function getDeviceLimitOptions() {
}
export const shareExpiryOptions = () => [
- { label: t('NEVER'), value: () => 0 },
+ { label: t("NEVER"), value: () => 0 },
{
- label: t('AFTER_TIME.HOUR'),
+ label: t("AFTER_TIME.HOUR"),
value: () => getUnixTimeInMicroSecondsWithDelta({ hours: 1 }),
},
{
- label: t('AFTER_TIME.DAY'),
+ label: t("AFTER_TIME.DAY"),
value: () => getUnixTimeInMicroSecondsWithDelta({ days: 1 }),
},
{
- label: t('AFTER_TIME.WEEK'),
+ label: t("AFTER_TIME.WEEK"),
value: () => getUnixTimeInMicroSecondsWithDelta({ days: 7 }),
},
{
- label: t('AFTER_TIME.MONTH'),
+ label: t("AFTER_TIME.MONTH"),
value: () => getUnixTimeInMicroSecondsWithDelta({ months: 1 }),
},
{
- label: t('AFTER_TIME.YEAR'),
+ label: t("AFTER_TIME.YEAR"),
value: () => getUnixTimeInMicroSecondsWithDelta({ years: 1 }),
},
];
export const changeCollectionVisibility = async (
collection: Collection,
- visibility: VISIBILITY_STATE
+ visibility: VISIBILITY_STATE,
) => {
try {
const updatedMagicMetadataProps: CollectionMagicMetadataProps = {
@@ -253,33 +253,33 @@ export const changeCollectionVisibility = async (
const updatedMagicMetadata = await updateMagicMetadata(
updatedMagicMetadataProps,
collection.magicMetadata,
- collection.key
+ collection.key,
);
await updateCollectionMagicMetadata(
collection,
- updatedMagicMetadata
+ updatedMagicMetadata,
);
} else {
const updatedMagicMetadata = await updateMagicMetadata(
updatedMagicMetadataProps,
collection.sharedMagicMetadata,
- collection.key
+ collection.key,
);
await updateSharedCollectionMagicMetadata(
collection,
- updatedMagicMetadata
+ updatedMagicMetadata,
);
}
} catch (e) {
- logError(e, 'change collection visibility failed');
+ logError(e, "change collection visibility failed");
throw e;
}
};
export const changeCollectionSortOrder = async (
collection: Collection,
- asc: boolean
+ asc: boolean,
) => {
try {
const updatedPublicMagicMetadataProps: CollectionPublicMagicMetadataProps =
@@ -290,21 +290,21 @@ export const changeCollectionSortOrder = async (
const updatedPubMagicMetadata = await updateMagicMetadata(
updatedPublicMagicMetadataProps,
collection.pubMagicMetadata,
- collection.key
+ collection.key,
);
await updatePublicCollectionMagicMetadata(
collection,
- updatedPubMagicMetadata
+ updatedPubMagicMetadata,
);
} catch (e) {
- logError(e, 'change collection sort order failed');
+ logError(e, "change collection sort order failed");
}
};
export const changeCollectionOrder = async (
collection: Collection,
- order: number
+ order: number,
) => {
try {
const updatedMagicMetadataProps: CollectionMagicMetadataProps = {
@@ -314,18 +314,18 @@ export const changeCollectionOrder = async (
const updatedMagicMetadata = await updateMagicMetadata(
updatedMagicMetadataProps,
collection.magicMetadata,
- collection.key
+ collection.key,
);
await updateCollectionMagicMetadata(collection, updatedMagicMetadata);
} catch (e) {
- logError(e, 'change collection order failed');
+ logError(e, "change collection order failed");
}
};
export const changeCollectionSubType = async (
collection: Collection,
- subType: SUB_TYPE
+ subType: SUB_TYPE,
) => {
try {
const updatedMagicMetadataProps: CollectionMagicMetadataProps = {
@@ -335,11 +335,11 @@ export const changeCollectionSubType = async (
const updatedMagicMetadata = await updateMagicMetadata(
updatedMagicMetadataProps,
collection.magicMetadata,
- collection.key
+ collection.key,
);
await updateCollectionMagicMetadata(collection, updatedMagicMetadata);
} catch (e) {
- logError(e, 'change collection subType failed');
+ logError(e, "change collection subType failed");
throw e;
}
};
@@ -348,7 +348,7 @@ export const getArchivedCollections = (collections: Collection[]) => {
return new Set<number>(
collections
.filter(isArchivedCollection)
- .map((collection) => collection.id)
+ .map((collection) => collection.id),
);
};
@@ -356,12 +356,12 @@ export const getDefaultHiddenCollectionIDs = (collections: Collection[]) => {
return new Set<number>(
collections
.filter(isDefaultHiddenCollection)
- .map((collection) => collection.id)
+ .map((collection) => collection.id),
);
};
export const hasNonSystemCollections = (
- collectionSummaries: CollectionSummaries
+ collectionSummaries: CollectionSummaries,
) => {
for (const collectionSummary of collectionSummaries.values()) {
if (!isSystemCollection(collectionSummary.type)) return true;
@@ -421,7 +421,7 @@ export const shouldBeShownOnCollectionBar = (type: CollectionSummaryType) => {
export const getUserOwnedCollections = (collections: Collection[]) => {
const user: User = getData(LS_KEYS.USER);
if (!user?.id) {
- throw Error('user missing');
+ throw Error("user missing");
}
return collections.filter((collection) => collection.owner.id === user.id);
};
@@ -460,7 +460,7 @@ export function isSharedOnlyViaLink(collection: Collection) {
export function isValidMoveTarget(
sourceCollectionID: number,
targetCollection: Collection,
- user: User
+ user: User,
) {
return (
sourceCollectionID !== targetCollection.id &&
@@ -473,7 +473,7 @@ export function isValidMoveTarget(
export function isValidReplacementAlbum(
collection: Collection,
user: User,
- wantedCollectionName: string
+ wantedCollectionName: string,
) {
return (
collection.name === wantedCollectionName &&
@@ -487,33 +487,33 @@ export function isValidReplacementAlbum(
}
export function getCollectionNameMap(
- collections: Collection[]
+ collections: Collection[],
): Map<number, string> {
return new Map<number, string>(
- collections.map((collection) => [collection.id, collection.name])
+ collections.map((collection) => [collection.id, collection.name]),
);
}
export function getNonEmptyPersonalCollections(
collections: Collection[],
personalFiles: EnteFile[],
- user: User
+ user: User,
): Collection[] {
if (!user?.id) {
- throw Error('user missing');
+ throw Error("user missing");
}
const nonEmptyCollections = getNonEmptyCollections(
collections,
- personalFiles
+ personalFiles,
);
const personalCollections = nonEmptyCollections.filter(
- (collection) => collection.owner.id === user?.id
+ (collection) => collection.owner.id === user?.id,
);
return personalCollections;
}
export function getNonHiddenCollections(
- collections: Collection[]
+ collections: Collection[],
): Collection[] {
return collections.filter((collection) => !isHiddenCollection(collection));
}
@@ -523,7 +523,7 @@ export function getHiddenCollections(collections: Collection[]): Collection[] {
}
export async function splitNormalAndHiddenCollections(
- collections: Collection[]
+ collections: Collection[],
): Promise<{
normalCollections: Collection[];
hiddenCollections: Collection[];
@@ -541,13 +541,13 @@ export async function splitNormalAndHiddenCollections(
}
export function constructCollectionNameMap(
- collections: Collection[]
+ collections: Collection[],
): Map<number, string> {
return new Map<number, string>(
(collections ?? []).map((collection) => [
collection.id,
getCollectionUserFacingName(collection),
- ])
+ ]),
);
}
@@ -560,16 +560,16 @@ export const getCollectionUserFacingName = (collection: Collection) => {
export const getOrCreateAlbum = async (
albumName: string,
- existingCollections: Collection[]
+ existingCollections: Collection[],
) => {
const user: User = getData(LS_KEYS.USER);
if (!user?.id) {
- throw Error('user missing');
+ throw Error("user missing");
}
for (const collection of existingCollections) {
if (isValidReplacementAlbum(collection, user, albumName)) {
addLogLine(
- `Found existing album ${albumName} with id ${collection.id}`
+ `Found existing album ${albumName} with id ${collection.id}`,
);
return collection;
}
diff --git a/apps/photos/src/utils/comlink/ComlinkConvertWorker.ts b/apps/photos/src/utils/comlink/ComlinkConvertWorker.ts
index 93dd312f3b..3dc0341607 100644
--- a/apps/photos/src/utils/comlink/ComlinkConvertWorker.ts
+++ b/apps/photos/src/utils/comlink/ComlinkConvertWorker.ts
@@ -1,7 +1,7 @@
-import { Remote } from 'comlink';
-import { runningInBrowser } from 'utils/common';
-import { DedicatedConvertWorker } from 'worker/convert.worker';
-import { ComlinkWorker } from '@ente/shared/worker/comlinkWorker';
+import { ComlinkWorker } from "@ente/shared/worker/comlinkWorker";
+import { Remote } from "comlink";
+import { runningInBrowser } from "utils/common";
+import { DedicatedConvertWorker } from "worker/convert.worker";
class ComlinkConvertWorker {
private comlinkWorkerInstance: Remote<DedicatedConvertWorker>;
@@ -20,8 +20,8 @@ export const getDedicatedConvertWorker = () => {
const cryptoComlinkWorker = new ComlinkWorker<
typeof DedicatedConvertWorker
>(
- 'ente-convert-worker',
- new Worker(new URL('worker/convert.worker.ts', import.meta.url))
+ "ente-convert-worker",
+ new Worker(new URL("worker/convert.worker.ts", import.meta.url)),
);
return cryptoComlinkWorker;
}
diff --git a/apps/photos/src/utils/comlink/ComlinkFFmpegWorker.ts b/apps/photos/src/utils/comlink/ComlinkFFmpegWorker.ts
index 3593c29310..48e638d7f7 100644
--- a/apps/photos/src/utils/comlink/ComlinkFFmpegWorker.ts
+++ b/apps/photos/src/utils/comlink/ComlinkFFmpegWorker.ts
@@ -1,6 +1,6 @@
-import { Remote } from 'comlink';
-import { DedicatedFFmpegWorker } from 'worker/ffmpeg.worker';
-import { ComlinkWorker } from '@ente/shared/worker/comlinkWorker';
+import { ComlinkWorker } from "@ente/shared/worker/comlinkWorker";
+import { Remote } from "comlink";
+import { DedicatedFFmpegWorker } from "worker/ffmpeg.worker";
class ComlinkFFmpegWorker {
private comlinkWorkerInstance: Promise<Remote<DedicatedFFmpegWorker>>;
@@ -16,8 +16,8 @@ class ComlinkFFmpegWorker {
const getDedicatedFFmpegWorker = () => {
const cryptoComlinkWorker = new ComlinkWorker<typeof DedicatedFFmpegWorker>(
- 'ente-ffmpeg-worker',
- new Worker(new URL('worker/ffmpeg.worker.ts', import.meta.url))
+ "ente-ffmpeg-worker",
+ new Worker(new URL("worker/ffmpeg.worker.ts", import.meta.url)),
);
return cryptoComlinkWorker;
};
diff --git a/apps/photos/src/utils/comlink/ComlinkMLWorker.ts b/apps/photos/src/utils/comlink/ComlinkMLWorker.ts
index 0931792fd0..f61754c6bb 100644
--- a/apps/photos/src/utils/comlink/ComlinkMLWorker.ts
+++ b/apps/photos/src/utils/comlink/ComlinkMLWorker.ts
@@ -1,12 +1,12 @@
-import { runningInBrowser } from 'utils/common';
-import { DedicatedMLWorker } from 'worker/ml.worker';
-import { ComlinkWorker } from '@ente/shared/worker/comlinkWorker';
+import { ComlinkWorker } from "@ente/shared/worker/comlinkWorker";
+import { runningInBrowser } from "utils/common";
+import { DedicatedMLWorker } from "worker/ml.worker";
export const getDedicatedMLWorker = (name: string) => {
if (runningInBrowser()) {
const cryptoComlinkWorker = new ComlinkWorker<typeof DedicatedMLWorker>(
- name ?? 'ente-ml-worker',
- new Worker(new URL('worker/ml.worker.ts', import.meta.url))
+ name ?? "ente-ml-worker",
+ new Worker(new URL("worker/ml.worker.ts", import.meta.url)),
);
return cryptoComlinkWorker;
}
diff --git a/apps/photos/src/utils/comlink/ComlinkSearchWorker.ts b/apps/photos/src/utils/comlink/ComlinkSearchWorker.ts
index e2b79152ea..971f12338d 100644
--- a/apps/photos/src/utils/comlink/ComlinkSearchWorker.ts
+++ b/apps/photos/src/utils/comlink/ComlinkSearchWorker.ts
@@ -1,7 +1,7 @@
-import { Remote } from 'comlink';
-import { runningInBrowser } from 'utils/common';
-import { ComlinkWorker } from '@ente/shared/worker/comlinkWorker';
-import { DedicatedSearchWorker } from 'worker/search.worker';
+import { ComlinkWorker } from "@ente/shared/worker/comlinkWorker";
+import { Remote } from "comlink";
+import { runningInBrowser } from "utils/common";
+import { DedicatedSearchWorker } from "worker/search.worker";
class ComlinkSearchWorker {
private comlinkWorkerInstance: Remote<DedicatedSearchWorker>;
@@ -20,8 +20,8 @@ export const getDedicatedSearchWorker = () => {
const cryptoComlinkWorker = new ComlinkWorker<
typeof DedicatedSearchWorker
>(
- 'ente-search-worker',
- new Worker(new URL('worker/search.worker.ts', import.meta.url))
+ "ente-search-worker",
+ new Worker(new URL("worker/search.worker.ts", import.meta.url)),
);
return cryptoComlinkWorker;
}
diff --git a/apps/photos/src/utils/common/concurrency.ts b/apps/photos/src/utils/common/concurrency.ts
index eb963e3920..bba75f0097 100644
--- a/apps/photos/src/utils/common/concurrency.ts
+++ b/apps/photos/src/utils/common/concurrency.ts
@@ -1,4 +1,4 @@
-import { runningInBrowser } from '.';
+import { runningInBrowser } from ".";
export const getConcurrency = () =>
runningInBrowser() &&
diff --git a/apps/photos/src/utils/common/deviceDetection.ts b/apps/photos/src/utils/common/deviceDetection.ts
index e9aca75d78..7ce55bba7d 100644
--- a/apps/photos/src/utils/common/deviceDetection.ts
+++ b/apps/photos/src/utils/common/deviceDetection.ts
@@ -1,11 +1,11 @@
export enum OS {
- WP = 'wp',
- ANDROID = 'android',
- IOS = 'ios',
- UNKNOWN = 'unknown',
- WINDOWS = 'windows',
- MAC = 'mac',
- LINUX = 'linux',
+ WP = "wp",
+ ANDROID = "android",
+ IOS = "ios",
+ UNKNOWN = "unknown",
+ WINDOWS = "windows",
+ MAC = "mac",
+ LINUX = "linux",
}
declare global {
@@ -16,10 +16,10 @@ declare global {
}
export const getDeviceOS = () => {
- let userAgent = '';
+ let userAgent = "";
if (
- typeof window !== 'undefined' &&
- typeof window.navigator !== 'undefined'
+ typeof window !== "undefined" &&
+ typeof window.navigator !== "undefined"
) {
userAgent = navigator.userAgent || navigator.vendor || window.opera;
}
@@ -38,14 +38,14 @@ export const getDeviceOS = () => {
}
// credit: https://github.com/MikeKovarik/platform-detect/blob/master/os.mjs
- if (userAgent.includes('Windows')) {
+ if (userAgent.includes("Windows")) {
return OS.WINDOWS;
}
- if (userAgent.includes('Macintosh')) {
+ if (userAgent.includes("Macintosh")) {
return OS.MAC;
}
// Linux must be last
- if (userAgent.includes('Linux')) {
+ if (userAgent.includes("Linux")) {
return OS.LINUX;
}
@@ -57,10 +57,10 @@ export const isMobileOrTable = () => {
(function (a) {
if (
/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(
- a
+ a,
) ||
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(
- a.substr(0, 4)
+ a.substr(0, 4),
)
)
check = true;
diff --git a/apps/photos/src/utils/common/index.ts b/apps/photos/src/utils/common/index.ts
index 72cf592216..efc9a35536 100644
--- a/apps/photos/src/utils/common/index.ts
+++ b/apps/photos/src/utils/common/index.ts
@@ -1,6 +1,6 @@
-import { CustomError } from '@ente/shared/error';
-import isElectron from 'is-electron';
-import { APP_DOWNLOAD_URL } from '@ente/shared/constants/urls';
+import { APP_DOWNLOAD_URL } from "@ente/shared/constants/urls";
+import { CustomError } from "@ente/shared/error";
+import isElectron from "is-electron";
export function checkConnectivity() {
if (navigator.onLine) {
@@ -10,11 +10,11 @@ export function checkConnectivity() {
}
export function runningInBrowser() {
- return typeof window !== 'undefined';
+ return typeof window !== "undefined";
}
export function runningInWorker() {
- return typeof importScripts === 'function';
+ return typeof importScripts === "function";
}
export function runningInElectron() {
@@ -23,28 +23,28 @@ export function runningInElectron() {
export function runningInChrome(includeMobile: boolean) {
try {
- const userAgentData = navigator['userAgentData'];
+ const userAgentData = navigator["userAgentData"];
const chromeBrand = userAgentData?.brands?.filter(
- (b) => b.brand === 'Google Chrome' || b.brand === 'Chromium'
+ (b) => b.brand === "Google Chrome" || b.brand === "Chromium",
)?.[0];
return chromeBrand && (includeMobile || userAgentData.mobile === false);
} catch (error) {
- console.error('Error in runningInChrome: ', error);
+ console.error("Error in runningInChrome: ", error);
return false;
}
}
export function offscreenCanvasSupported() {
- return !(typeof OffscreenCanvas === 'undefined');
+ return !(typeof OffscreenCanvas === "undefined");
}
export function webglSupported() {
try {
- const canvas = document.createElement('canvas');
- const gl = canvas.getContext('webgl');
+ const canvas = document.createElement("canvas");
+ const gl = canvas.getContext("webgl");
return gl && gl instanceof WebGLRenderingContext;
} catch (error) {
- console.error('Error in webglSupported: ', error);
+ console.error("Error in webglSupported: ", error);
return false;
}
}
@@ -61,25 +61,25 @@ export function downloadApp() {
export function reverseString(title: string) {
return title
- ?.split(' ')
+ ?.split(" ")
.reduce((reversedString, currWord) => `${currWord} ${reversedString}`);
}
export function initiateEmail(email: string) {
- const a = document.createElement('a');
- a.href = 'mailto:' + email;
- a.rel = 'noreferrer noopener';
+ const a = document.createElement("a");
+ a.href = "mailto:" + email;
+ a.rel = "noreferrer noopener";
a.click();
}
export const promiseWithTimeout = async <T>(
request: Promise<T>,
- timeout: number
+ timeout: number,
): Promise<T> => {
const timeoutRef = { current: null };
const rejectOnTimeout = new Promise<null>((_, reject) => {
timeoutRef.current = setTimeout(
() => reject(Error(CustomError.WAIT_TIME_EXCEEDED)),
- timeout
+ timeout,
);
});
const requestWithTimeOutCancellation = async () => {
@@ -98,21 +98,21 @@ export const preloadImage = (imgBasePath: string) => {
for (let i = 1; i <= 3; i++) {
srcSet.push(`${imgBasePath}/${i}x.png ${i}x`);
}
- new Image().srcset = srcSet.join(',');
+ new Image().srcset = srcSet.join(",");
};
export function openLink(href: string, newTab?: boolean) {
- const a = document.createElement('a');
+ const a = document.createElement("a");
a.href = href;
if (newTab) {
- a.target = '_blank';
+ a.target = "_blank";
}
- a.rel = 'noreferrer noopener';
+ a.rel = "noreferrer noopener";
a.click();
}
export async function waitAndRun(
waitPromise: Promise<void>,
- task: () => Promise<void>
+ task: () => Promise<void>,
) {
if (waitPromise && isPromise(waitPromise)) {
await waitPromise;
@@ -121,7 +121,7 @@ export async function waitAndRun(
}
function isPromise(p: any) {
- if (typeof p === 'object' && typeof p.then === 'function') {
+ if (typeof p === "object" && typeof p.then === "function") {
return true;
}
@@ -129,7 +129,7 @@ function isPromise(p: any) {
}
export function isClipboardItemPresent() {
- return typeof ClipboardItem !== 'undefined';
+ return typeof ClipboardItem !== "undefined";
}
export function batch<T>(arr: T[], batchSize: number): T[][] {
diff --git a/apps/photos/src/utils/common/job.ts b/apps/photos/src/utils/common/job.ts
index f0515fbde6..7bc37afb40 100644
--- a/apps/photos/src/utils/common/job.ts
+++ b/apps/photos/src/utils/common/job.ts
@@ -1,5 +1,5 @@
-import { JobResult, JobConfig, JobState } from 'types/common/job';
-import { addLogLine } from '@ente/shared/logging';
+import { addLogLine } from "@ente/shared/logging";
+import { JobConfig, JobResult, JobState } from "types/common/job";
export class SimpleJob<R extends JobResult> {
private config: JobConfig;
@@ -12,7 +12,7 @@ export class SimpleJob<R extends JobResult> {
constructor(config: JobConfig, runCallback: () => Promise<R>) {
this.config = config;
this.runCallback = runCallback;
- this.state = 'NotScheduled';
+ this.state = "NotScheduled";
this.stopped = true;
this.intervalSec = this.config.intervalSec;
}
@@ -24,45 +24,45 @@ export class SimpleJob<R extends JobResult> {
public start() {
this.stopped = false;
this.resetInterval();
- if (this.state !== 'Running') {
+ if (this.state !== "Running") {
this.scheduleNext();
} else {
- addLogLine('Job already running, not scheduling');
+ addLogLine("Job already running, not scheduling");
}
}
private scheduleNext() {
- if (this.state === 'Scheduled' || this.nextTimeoutId) {
+ if (this.state === "Scheduled" || this.nextTimeoutId) {
this.clearScheduled();
}
this.nextTimeoutId = setTimeout(
() => this.run(),
- this.intervalSec * 1000
+ this.intervalSec * 1000,
);
- this.state = 'Scheduled';
- addLogLine('Scheduled next job after: ', this.intervalSec);
+ this.state = "Scheduled";
+ addLogLine("Scheduled next job after: ", this.intervalSec);
}
async run() {
this.nextTimeoutId = undefined;
- this.state = 'Running';
+ this.state = "Running";
try {
const jobResult = await this.runCallback();
if (jobResult.shouldBackoff) {
this.intervalSec = Math.min(
this.config.maxItervalSec,
- this.intervalSec * this.config.backoffMultiplier
+ this.intervalSec * this.config.backoffMultiplier,
);
} else {
this.resetInterval();
}
- addLogLine('Job completed');
+ addLogLine("Job completed");
} catch (e) {
- console.error('Error while running Job: ', e);
+ console.error("Error while running Job: ", e);
} finally {
- this.state = 'NotScheduled';
+ this.state = "NotScheduled";
!this.stopped && this.scheduleNext();
}
}
@@ -76,7 +76,7 @@ export class SimpleJob<R extends JobResult> {
private clearScheduled() {
clearTimeout(this.nextTimeoutId);
this.nextTimeoutId = undefined;
- this.state = 'NotScheduled';
- addLogLine('Cleared next job');
+ this.state = "NotScheduled";
+ addLogLine("Cleared next job");
}
}
diff --git a/apps/photos/src/utils/common/promiseTimeout.ts b/apps/photos/src/utils/common/promiseTimeout.ts
index 230e55e0e8..bf5a79e2a4 100644
--- a/apps/photos/src/utils/common/promiseTimeout.ts
+++ b/apps/photos/src/utils/common/promiseTimeout.ts
@@ -1,14 +1,14 @@
-import { CustomError } from '@ente/shared/error';
+import { CustomError } from "@ente/shared/error";
export const promiseWithTimeout = async (
request: Promise<any>,
- timeout: number
+ timeout: number,
) => {
const timeoutRef = { current: null };
const rejectOnTimeout = new Promise((_, reject) => {
timeoutRef.current = setTimeout(
() => reject(Error(CustomError.WAIT_TIME_EXCEEDED)),
- timeout
+ timeout,
);
});
return await Promise.race([
diff --git a/apps/photos/src/utils/crypto/index.ts b/apps/photos/src/utils/crypto/index.ts
index 469f781694..21a296110e 100644
--- a/apps/photos/src/utils/crypto/index.ts
+++ b/apps/photos/src/utils/crypto/index.ts
@@ -1,9 +1,9 @@
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import { getActualKey } from '@ente/shared/user';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { getData, LS_KEYS } from "@ente/shared/storage/localStorage";
+import { getActualKey } from "@ente/shared/user";
export async function decryptDeleteAccountChallenge(
- encryptedChallenge: string
+ encryptedChallenge: string,
) {
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
const masterKey = await getActualKey();
@@ -11,12 +11,12 @@ export async function decryptDeleteAccountChallenge(
const secretKey = await cryptoWorker.decryptB64(
keyAttributes.encryptedSecretKey,
keyAttributes.secretKeyDecryptionNonce,
- masterKey
+ masterKey,
);
const b64DecryptedChallenge = await cryptoWorker.boxSealOpen(
encryptedChallenge,
keyAttributes.publicKey,
- secretKey
+ secretKey,
);
const utf8DecryptedChallenge = atob(b64DecryptedChallenge);
return utf8DecryptedChallenge;
diff --git a/apps/photos/src/utils/embedding.ts b/apps/photos/src/utils/embedding.ts
index bc7e4d2470..dde04fd8bd 100644
--- a/apps/photos/src/utils/embedding.ts
+++ b/apps/photos/src/utils/embedding.ts
@@ -1,4 +1,4 @@
-import { Embedding } from 'types/embedding';
+import { Embedding } from "types/embedding";
export const getLatestVersionEmbeddings = (embeddings: Embedding[]) => {
const latestVersionEntities = new Map<number, Embedding>();
diff --git a/apps/photos/src/utils/entity.ts b/apps/photos/src/utils/entity.ts
index ad8ff96493..7d8ad28b3c 100644
--- a/apps/photos/src/utils/entity.ts
+++ b/apps/photos/src/utils/entity.ts
@@ -1,4 +1,4 @@
-import { Entity } from 'types/entity';
+import { Entity } from "types/entity";
export const getLatestVersionEntities = <T>(entities: Entity<T>[]) => {
const latestVersionEntities = new Map<string, Entity<T>>();
diff --git a/apps/photos/src/utils/error/ui.ts b/apps/photos/src/utils/error/ui.ts
index 3fb20cece1..fd7f09c0e8 100644
--- a/apps/photos/src/utils/error/ui.ts
+++ b/apps/photos/src/utils/error/ui.ts
@@ -1,22 +1,22 @@
-import { t } from 'i18next';
+import { t } from "i18next";
-import { parseSharingErrorCodes, CustomError } from '@ente/shared/error';
+import { CustomError, parseSharingErrorCodes } from "@ente/shared/error";
export const handleSharingErrors = (error) => {
const parsedError = parseSharingErrorCodes(error);
- let errorMessage = '';
+ let errorMessage = "";
switch (parsedError.message) {
case CustomError.BAD_REQUEST:
- errorMessage = t('SHARING_BAD_REQUEST_ERROR');
+ errorMessage = t("SHARING_BAD_REQUEST_ERROR");
break;
case CustomError.SUBSCRIPTION_NEEDED:
- errorMessage = t('SHARING_DISABLED_FOR_FREE_ACCOUNTS');
+ errorMessage = t("SHARING_DISABLED_FOR_FREE_ACCOUNTS");
break;
case CustomError.NOT_FOUND:
- errorMessage = t('USER_DOES_NOT_EXIST');
+ errorMessage = t("USER_DOES_NOT_EXIST");
break;
default:
- errorMessage = `${t('UNKNOWN_ERROR')} ${parsedError.message}`;
+ errorMessage = `${t("UNKNOWN_ERROR")} ${parsedError.message}`;
}
return errorMessage;
};
diff --git a/apps/photos/src/utils/export/index.ts b/apps/photos/src/utils/export/index.ts
index 4228ff5428..35dfcf4ccd 100644
--- a/apps/photos/src/utils/export/index.ts
+++ b/apps/photos/src/utils/export/index.ts
@@ -1,64 +1,64 @@
-import { Collection } from 'types/collection';
-import exportService from 'services/export';
+import exportService from "services/export";
+import { Collection } from "types/collection";
import {
- ExportRecord,
CollectionExportNames,
+ ExportRecord,
FileExportNames,
-} from 'types/export';
+} from "types/export";
-import { EnteFile } from 'types/file';
+import { EnteFile } from "types/file";
-import { Metadata } from 'types/upload';
-import { splitFilenameAndExtension } from 'utils/file';
+import { formatDateTimeShort } from "@ente/shared/time/format";
import {
ENTE_METADATA_FOLDER,
ENTE_TRASH_FOLDER,
ExportStage,
-} from 'constants/export';
-import sanitize from 'sanitize-filename';
-import { formatDateTimeShort } from '@ente/shared/time/format';
-import { getCollectionUserFacingName } from 'utils/collection';
+} from "constants/export";
+import sanitize from "sanitize-filename";
+import { Metadata } from "types/upload";
+import { getCollectionUserFacingName } from "utils/collection";
+import { splitFilenameAndExtension } from "utils/file";
export const getExportRecordFileUID = (file: EnteFile) =>
`${file.id}_${file.collectionID}_${file.updationTime}`;
export const getCollectionIDFromFileUID = (fileUID: string) =>
- Number(fileUID.split('_')[1]);
+ Number(fileUID.split("_")[1]);
export const convertCollectionIDExportNameObjectToMap = (
- collectionExportNames: CollectionExportNames
+ collectionExportNames: CollectionExportNames,
): Map<number, string> => {
return new Map<number, string>(
Object.entries(collectionExportNames ?? {}).map((e) => {
return [Number(e[0]), String(e[1])];
- })
+ }),
);
};
export const convertFileIDExportNameObjectToMap = (
- fileExportNames: FileExportNames
+ fileExportNames: FileExportNames,
): Map<string, string> => {
return new Map<string, string>(
Object.entries(fileExportNames ?? {}).map((e) => {
return [String(e[0]), String(e[1])];
- })
+ }),
);
};
export const getRenamedExportedCollections = (
collections: Collection[],
- exportRecord: ExportRecord
+ exportRecord: ExportRecord,
) => {
if (!exportRecord?.collectionExportNames) {
return [];
}
const collectionIDExportNameMap = convertCollectionIDExportNameObjectToMap(
- exportRecord.collectionExportNames
+ exportRecord.collectionExportNames,
);
const renamedCollections = collections.filter((collection) => {
if (collectionIDExportNameMap.has(collection.id)) {
const currentExportName = collectionIDExportNameMap.get(
- collection.id
+ collection.id,
);
const collectionExportName =
@@ -69,7 +69,7 @@ export const getRenamedExportedCollections = (
}
const hasNumberedSuffix = currentExportName.match(/\(\d+\)$/);
const currentExportNameWithoutNumberedSuffix = hasNumberedSuffix
- ? currentExportName.replace(/\(\d+\)$/, '')
+ ? currentExportName.replace(/\(\d+\)$/, "")
: currentExportName;
return (
@@ -83,16 +83,16 @@ export const getRenamedExportedCollections = (
export const getDeletedExportedCollections = (
collections: Collection[],
- exportRecord: ExportRecord
+ exportRecord: ExportRecord,
) => {
if (!exportRecord?.collectionExportNames) {
return [];
}
const presentCollections = new Set(
- collections.map((collection) => collection.id)
+ collections.map((collection) => collection.id),
);
const deletedExportedCollections = Object.keys(
- exportRecord?.collectionExportNames
+ exportRecord?.collectionExportNames,
)
.map(Number)
.filter((collectionID) => {
@@ -106,7 +106,7 @@ export const getDeletedExportedCollections = (
export const getUnExportedFiles = (
allFiles: EnteFile[],
- exportRecord: ExportRecord
+ exportRecord: ExportRecord,
) => {
if (!exportRecord?.fileExportNames) {
return allFiles;
@@ -123,16 +123,16 @@ export const getUnExportedFiles = (
export const getDeletedExportedFiles = (
allFiles: EnteFile[],
- exportRecord: ExportRecord
+ exportRecord: ExportRecord,
): string[] => {
if (!exportRecord?.fileExportNames) {
return [];
}
const presentFileUIDs = new Set(
- allFiles?.map((file) => getExportRecordFileUID(file))
+ allFiles?.map((file) => getExportRecordFileUID(file)),
);
const deletedExportedFiles = Object.keys(
- exportRecord?.fileExportNames
+ exportRecord?.fileExportNames,
).filter((fileUID) => {
if (!presentFileUIDs.has(fileUID)) {
return true;
@@ -144,15 +144,15 @@ export const getDeletedExportedFiles = (
export const getCollectionExportedFiles = (
exportRecord: ExportRecord,
- collectionID: number
+ collectionID: number,
): string[] => {
if (!exportRecord?.fileExportNames) {
return [];
}
const collectionExportedFiles = Object.keys(
- exportRecord?.fileExportNames
+ exportRecord?.fileExportNames,
).filter((fileUID) => {
- const fileCollectionID = Number(fileUID.split('_')[1]);
+ const fileCollectionID = Number(fileUID.split("_")[1]);
if (fileCollectionID === collectionID) {
return true;
} else {
@@ -164,12 +164,12 @@ export const getCollectionExportedFiles = (
export const getGoogleLikeMetadataFile = (
fileExportName: string,
- file: EnteFile
+ file: EnteFile,
) => {
const metadata: Metadata = file.metadata;
const creationTime = Math.floor(metadata.creationTime / 1000000);
const modificationTime = Math.floor(
- (metadata.modificationTime ?? metadata.creationTime) / 1000000
+ (metadata.modificationTime ?? metadata.creationTime) / 1000000,
);
const captionValue: string = file?.pubMagicMetadata?.data?.caption;
return JSON.stringify(
@@ -190,22 +190,22 @@ export const getGoogleLikeMetadataFile = (
},
},
null,
- 2
+ 2,
);
};
export const sanitizeName = (name: string) =>
- sanitize(name, { replacement: '_' });
+ sanitize(name, { replacement: "_" });
export const getUniqueCollectionExportName = (
dir: string,
- collectionName: string
+ collectionName: string,
): string => {
let collectionExportName = sanitizeName(collectionName);
let count = 1;
while (
exportService.exists(
- getCollectionExportPath(dir, collectionExportName)
+ getCollectionExportPath(dir, collectionExportName),
) ||
collectionExportName === ENTE_TRASH_FOLDER
) {
@@ -220,13 +220,13 @@ export const getMetadataFolderExportPath = (collectionExportPath: string) =>
export const getUniqueFileExportName = (
collectionExportPath: string,
- filename: string
+ filename: string,
) => {
let fileExportName = sanitizeName(filename);
let count = 1;
while (
exportService.exists(
- getFileExportPath(collectionExportPath, fileExportName)
+ getFileExportPath(collectionExportPath, fileExportName),
)
) {
const filenameParts = splitFilenameAndExtension(sanitizeName(filename));
@@ -242,21 +242,21 @@ export const getUniqueFileExportName = (
export const getFileMetadataExportPath = (
collectionExportPath: string,
- fileExportName: string
+ fileExportName: string,
) => `${collectionExportPath}/${ENTE_METADATA_FOLDER}/${fileExportName}.json`;
export const getCollectionExportPath = (
exportFolder: string,
- collectionExportName: string
+ collectionExportName: string,
) => `${exportFolder}/${collectionExportName}`;
export const getFileExportPath = (
collectionExportPath: string,
- fileExportName: string
+ fileExportName: string,
) => `${collectionExportPath}/${fileExportName}`;
export const getTrashedFileExportPath = (exportDir: string, path: string) => {
- const fileRelativePath = path.replace(`${exportDir}/`, '');
+ const fileRelativePath = path.replace(`${exportDir}/`, "");
let trashedFilePath = `${exportDir}/${ENTE_TRASH_FOLDER}/${fileRelativePath}`;
let count = 1;
while (exportService.exists(trashedFilePath)) {
@@ -275,14 +275,14 @@ export const getTrashedFileExportPath = (exportDir: string, path: string) => {
// then metadata path is /home/user/Ente/Export/Collection1/ENTE_METADATA_FOLDER/1.jpg.json
export const getMetadataFileExportPath = (filePath: string) => {
// extract filename and collection folder path
- const filename = filePath.split('/').pop();
- const collectionExportPath = filePath.replace(`/${filename}`, '');
+ const filename = filePath.split("/").pop();
+ const collectionExportPath = filePath.replace(`/${filename}`, "");
return `${collectionExportPath}/${ENTE_METADATA_FOLDER}/${filename}.json`;
};
export const getLivePhotoExportName = (
imageExportName: string,
- videoExportName: string
+ videoExportName: string,
) =>
JSON.stringify({
image: imageExportName,
@@ -299,7 +299,7 @@ export const isLivePhotoExportName = (exportName: string) => {
};
export const parseLivePhotoExportName = (
- livePhotoExportName: string
+ livePhotoExportName: string,
): { image: string; video: string } => {
const { image, video } = JSON.parse(livePhotoExportName);
return { image, video };
diff --git a/apps/photos/src/utils/export/migration.ts b/apps/photos/src/utils/export/migration.ts
index 83850683cb..254b016daa 100644
--- a/apps/photos/src/utils/export/migration.ts
+++ b/apps/photos/src/utils/export/migration.ts
@@ -1,28 +1,28 @@
-import { ENTE_METADATA_FOLDER } from 'constants/export';
+import { ENTE_METADATA_FOLDER } from "constants/export";
+import exportService from "services/export";
import {
ExportedCollectionPaths,
ExportRecordV0,
ExportRecordV1,
ExportRecordV2,
-} from 'types/export';
-import { EnteFile } from 'types/file';
-import { splitFilenameAndExtension } from 'utils/ffmpeg';
-import { getExportRecordFileUID, sanitizeName } from '.';
-import exportService from 'services/export';
+} from "types/export";
+import { EnteFile } from "types/file";
+import { splitFilenameAndExtension } from "utils/ffmpeg";
+import { getExportRecordFileUID, sanitizeName } from ".";
export const convertCollectionIDFolderPathObjectToMap = (
- exportedCollectionPaths: ExportedCollectionPaths
+ exportedCollectionPaths: ExportedCollectionPaths,
): Map<number, string> => {
return new Map<number, string>(
Object.entries(exportedCollectionPaths ?? {}).map((e) => {
return [Number(e[0]), String(e[1])];
- })
+ }),
);
};
export const getExportedFiles = (
allFiles: EnteFile[],
- exportRecord: ExportRecordV0 | ExportRecordV1 | ExportRecordV2
+ exportRecord: ExportRecordV0 | ExportRecordV1 | ExportRecordV2,
) => {
if (!exportRecord?.exportedFiles) {
return [];
@@ -39,17 +39,17 @@ export const getExportedFiles = (
};
export const oldSanitizeName = (name: string) =>
- name.replaceAll('/', '_').replaceAll(' ', '_');
+ name.replaceAll("/", "_").replaceAll(" ", "_");
export const getUniqueCollectionFolderPath = (
dir: string,
- collectionName: string
+ collectionName: string,
): string => {
let collectionFolderPath = `${dir}/${sanitizeName(collectionName)}`;
let count = 1;
while (exportService.exists(collectionFolderPath)) {
collectionFolderPath = `${dir}/${sanitizeName(
- collectionName
+ collectionName,
)}(${count})`;
count++;
}
@@ -61,7 +61,7 @@ export const getMetadataFolderPath = (collectionFolderPath: string) =>
export const getUniqueFileSaveName = (
collectionPath: string,
- filename: string
+ filename: string,
) => {
let fileSaveName = sanitizeName(filename);
let count = 1;
@@ -84,31 +84,31 @@ export const getOldFileSaveName = (filename: string, fileID: number) =>
export const getFileMetadataSavePath = (
collectionFolderPath: string,
- fileSaveName: string
+ fileSaveName: string,
) => `${collectionFolderPath}/${ENTE_METADATA_FOLDER}/${fileSaveName}.json`;
export const getFileSavePath = (
collectionFolderPath: string,
- fileSaveName: string
+ fileSaveName: string,
) => `${collectionFolderPath}/${fileSaveName}`;
export const getOldCollectionFolderPath = (
dir: string,
collectionID: number,
- collectionName: string
+ collectionName: string,
) => `${dir}/${collectionID}_${oldSanitizeName(collectionName)}`;
export const getOldFileSavePath = (
collectionFolderPath: string,
- file: EnteFile
+ file: EnteFile,
) =>
`${collectionFolderPath}/${file.id}_${oldSanitizeName(
- file.metadata.title
+ file.metadata.title,
)}`;
export const getOldFileMetadataSavePath = (
collectionFolderPath: string,
- file: EnteFile
+ file: EnteFile,
) =>
`${collectionFolderPath}/${ENTE_METADATA_FOLDER}/${
file.id
@@ -117,7 +117,7 @@ export const getOldFileMetadataSavePath = (
export const getUniqueFileExportNameForMigration = (
collectionPath: string,
filename: string,
- usedFilePaths: Map<string, Set<string>>
+ usedFilePaths: Map<string, Set<string>>,
) => {
let fileExportName = sanitizeName(filename);
let count = 1;
diff --git a/apps/photos/src/utils/ffmpeg/index.ts b/apps/photos/src/utils/ffmpeg/index.ts
index 46d13af3ac..1b3445976a 100644
--- a/apps/photos/src/utils/ffmpeg/index.ts
+++ b/apps/photos/src/utils/ffmpeg/index.ts
@@ -1,36 +1,36 @@
-import { NULL_LOCATION } from 'constants/upload';
-import { ParsedExtractedMetadata } from 'types/upload';
-import { validateAndGetCreationUnixTimeInMicroSeconds } from '@ente/shared/time';
+import { validateAndGetCreationUnixTimeInMicroSeconds } from "@ente/shared/time";
+import { NULL_LOCATION } from "constants/upload";
+import { ParsedExtractedMetadata } from "types/upload";
enum MetadataTags {
- CREATION_TIME = 'creation_time',
- APPLE_CONTENT_IDENTIFIER = 'com.apple.quicktime.content.identifier',
- APPLE_LIVE_PHOTO_IDENTIFIER = 'com.apple.quicktime.live-photo.auto',
- APPLE_CREATION_DATE = 'com.apple.quicktime.creationdate',
- APPLE_LOCATION_ISO = 'com.apple.quicktime.location.ISO6709',
- LOCATION = 'location',
+ CREATION_TIME = "creation_time",
+ APPLE_CONTENT_IDENTIFIER = "com.apple.quicktime.content.identifier",
+ APPLE_LIVE_PHOTO_IDENTIFIER = "com.apple.quicktime.live-photo.auto",
+ APPLE_CREATION_DATE = "com.apple.quicktime.creationdate",
+ APPLE_LOCATION_ISO = "com.apple.quicktime.location.ISO6709",
+ LOCATION = "location",
}
export function parseFFmpegExtractedMetadata(encodedMetadata: Uint8Array) {
const metadataString = new TextDecoder().decode(encodedMetadata);
- const metadataPropertyArray = metadataString.split('\n');
+ const metadataPropertyArray = metadataString.split("\n");
const metadataKeyValueArray = metadataPropertyArray.map((property) =>
- property.split('=')
+ property.split("="),
);
const validKeyValuePairs = metadataKeyValueArray.filter(
- (keyValueArray) => keyValueArray.length === 2
+ (keyValueArray) => keyValueArray.length === 2,
) as Array<[string, string]>;
const metadataMap = Object.fromEntries(validKeyValuePairs);
const location = parseAppleISOLocation(
metadataMap[MetadataTags.APPLE_LOCATION_ISO] ??
- metadataMap[MetadataTags.LOCATION]
+ metadataMap[MetadataTags.LOCATION],
);
const creationTime = parseCreationTime(
metadataMap[MetadataTags.APPLE_CREATION_DATE] ??
- metadataMap[MetadataTags.CREATION_TIME]
+ metadataMap[MetadataTags.CREATION_TIME],
);
const parsedMetadata: ParsedExtractedMetadata = {
creationTime,
@@ -60,14 +60,14 @@ function parseCreationTime(creationTime: string) {
let dateTime = null;
if (creationTime) {
dateTime = validateAndGetCreationUnixTimeInMicroSeconds(
- new Date(creationTime)
+ new Date(creationTime),
);
}
return dateTime;
}
export function splitFilenameAndExtension(filename: string): [string, string] {
- const lastDotPosition = filename.lastIndexOf('.');
+ const lastDotPosition = filename.lastIndexOf(".");
if (lastDotPosition === -1) return [filename, null];
else
return [
diff --git a/apps/photos/src/utils/file/index.ts b/apps/photos/src/utils/file/index.ts
index 48f7e4f2af..576ccd3361 100644
--- a/apps/photos/src/utils/file/index.ts
+++ b/apps/photos/src/utils/file/index.ts
@@ -1,62 +1,64 @@
+import { logError } from "@ente/shared/sentry";
+import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
+import { User } from "@ente/shared/user/types";
import {
- SelectedState,
- SetFilesDownloadProgressAttributes,
- SetFilesDownloadProgressAttributesCreator,
-} from 'types/gallery';
+ FILE_TYPE,
+ RAW_FORMATS,
+ SUPPORTED_RAW_FORMATS,
+ TYPE_HEIC,
+ TYPE_HEIF,
+ TYPE_JPEG,
+ TYPE_JPG,
+} from "constants/file";
+import DownloadManager, {
+ LivePhotoSourceURL,
+ SourceURLs,
+} from "services/download";
+import * as ffmpegService from "services/ffmpeg/ffmpegService";
+import heicConversionService from "services/heicConversionService";
+import { decodeLivePhoto } from "services/livePhotoService";
+import { getFileType } from "services/typeDetectionService";
+import { updateFileCreationDateInEXIF } from "services/upload/exifService";
import {
- EnteFile,
EncryptedEnteFile,
- FileWithUpdatedMagicMetadata,
+ EnteFile,
FileMagicMetadata,
FileMagicMetadataProps,
FilePublicMagicMetadata,
FilePublicMagicMetadataProps,
-} from 'types/file';
-import { decodeLivePhoto } from 'services/livePhotoService';
-import { getFileType } from 'services/typeDetectionService';
-import DownloadManager, {
- LivePhotoSourceURL,
- SourceURLs,
-} from 'services/download';
-import { logError } from '@ente/shared/sentry';
-import { User } from '@ente/shared/user/types';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import { updateFileCreationDateInEXIF } from 'services/upload/exifService';
+ FileWithUpdatedMagicMetadata,
+} from "types/file";
import {
- TYPE_JPEG,
- TYPE_JPG,
- TYPE_HEIC,
- TYPE_HEIF,
- FILE_TYPE,
- SUPPORTED_RAW_FORMATS,
- RAW_FORMATS,
-} from 'constants/file';
-import heicConversionService from 'services/heicConversionService';
-import * as ffmpegService from 'services/ffmpeg/ffmpegService';
-import { VISIBILITY_STATE } from 'types/magicMetadata';
-import { isArchivedFile, updateMagicMetadata } from 'utils/magicMetadata';
-
-import { addLocalLog, addLogLine } from '@ente/shared/logging';
-import { CustomError } from '@ente/shared/error';
-import { convertBytesToHumanReadable } from '@ente/shared/utils/size';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
+ SelectedState,
+ SetFilesDownloadProgressAttributes,
+ SetFilesDownloadProgressAttributesCreator,
+} from "types/gallery";
+import { VISIBILITY_STATE } from "types/magicMetadata";
+import { isArchivedFile, updateMagicMetadata } from "utils/magicMetadata";
+
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { CustomError } from "@ente/shared/error";
+import { addLocalLog, addLogLine } from "@ente/shared/logging";
+import { convertBytesToHumanReadable } from "@ente/shared/utils/size";
+import isElectron from "is-electron";
+import { moveToHiddenCollection } from "services/collectionService";
import {
deleteFromTrash,
trashFiles,
updateFileMagicMetadata,
updateFilePublicMagicMetadata,
-} from 'services/fileService';
-import isElectron from 'is-electron';
-import { isPlaybackPossible } from 'utils/photoFrame';
-import { FileTypeInfo } from 'types/upload';
-import { moveToHiddenCollection } from 'services/collectionService';
-
-import ElectronFSService from '@ente/shared/electron';
-import { getFileExportPath, getUniqueFileExportName } from 'utils/export';
-import imageProcessor from 'services/imageProcessor';
-import ElectronAPIs from '@ente/shared/electron';
-import { downloadUsingAnchor } from '@ente/shared/utils';
-import { t } from 'i18next';
+} from "services/fileService";
+import { FileTypeInfo } from "types/upload";
+import { isPlaybackPossible } from "utils/photoFrame";
+
+import {
+ default as ElectronAPIs,
+ default as ElectronFSService,
+} from "@ente/shared/electron";
+import { downloadUsingAnchor } from "@ente/shared/utils";
+import { t } from "i18next";
+import imageProcessor from "services/imageProcessor";
+import { getFileExportPath, getUniqueFileExportName } from "utils/export";
const WAIT_TIME_IMAGE_CONVERSION = 30 * 1000;
@@ -73,7 +75,7 @@ export enum FILE_OPS_TYPE {
export async function getUpdatedEXIFFileForDownload(
fileReader: FileReader,
file: EnteFile,
- fileStream: ReadableStream<Uint8Array>
+ fileStream: ReadableStream<Uint8Array>,
): Promise<ReadableStream<Uint8Array>> {
const extension = getFileExtension(file.metadata.title);
if (
@@ -85,7 +87,7 @@ export async function getUpdatedEXIFFileForDownload(
const updatedFileBlob = await updateFileCreationDateInEXIF(
fileReader,
fileBlob,
- new Date(file.pubMagicMetadata.data.editedTime / 1000)
+ new Date(file.pubMagicMetadata.data.editedTime / 1000),
);
return updatedFileBlob.stream();
} else {
@@ -97,39 +99,39 @@ export async function downloadFile(file: EnteFile) {
try {
const fileReader = new FileReader();
let fileBlob = await new Response(
- await DownloadManager.getFile(file)
+ await DownloadManager.getFile(file),
).blob();
if (file.metadata.fileType === FILE_TYPE.LIVE_PHOTO) {
const livePhoto = await decodeLivePhoto(file, fileBlob);
const image = new File([livePhoto.image], livePhoto.imageNameTitle);
const imageType = await getFileType(image);
const tempImageURL = URL.createObjectURL(
- new Blob([livePhoto.image], { type: imageType.mimeType })
+ new Blob([livePhoto.image], { type: imageType.mimeType }),
);
const video = new File([livePhoto.video], livePhoto.videoNameTitle);
const videoType = await getFileType(video);
const tempVideoURL = URL.createObjectURL(
- new Blob([livePhoto.video], { type: videoType.mimeType })
+ new Blob([livePhoto.video], { type: videoType.mimeType }),
);
downloadUsingAnchor(tempImageURL, livePhoto.imageNameTitle);
downloadUsingAnchor(tempVideoURL, livePhoto.videoNameTitle);
} else {
const fileType = await getFileType(
- new File([fileBlob], file.metadata.title)
+ new File([fileBlob], file.metadata.title),
);
fileBlob = await new Response(
await getUpdatedEXIFFileForDownload(
fileReader,
file,
- fileBlob.stream()
- )
+ fileBlob.stream(),
+ ),
).blob();
fileBlob = new Blob([fileBlob], { type: fileType.mimeType });
const tempURL = URL.createObjectURL(fileBlob);
downloadUsingAnchor(tempURL, file.metadata.title);
}
} catch (e) {
- logError(e, 'failed to download file');
+ logError(e, "failed to download file");
throw e;
}
}
@@ -148,7 +150,7 @@ export function groupFilesBasedOnCollectionID(files: EnteFile[]) {
function getSelectedFileIds(selectedFiles: SelectedState) {
const filesIDs: number[] = [];
for (const [key, val] of Object.entries(selectedFiles)) {
- if (typeof val === 'boolean' && val) {
+ if (typeof val === "boolean" && val) {
filesIDs.push(Number(key));
}
}
@@ -156,7 +158,7 @@ function getSelectedFileIds(selectedFiles: SelectedState) {
}
export function getSelectedFiles(
selected: SelectedState,
- files: EnteFile[]
+ files: EnteFile[],
): EnteFile[] {
const selectedFilesIDs = getSelectedFileIds(selected);
return files.filter((file) => selectedFilesIDs.has(file.id));
@@ -193,7 +195,7 @@ export function sortTrashFiles(files: EnteFile[]) {
export async function decryptFile(
file: EncryptedEnteFile,
- collectionKey: string
+ collectionKey: string,
): Promise<EnteFile> {
try {
const worker = await ComlinkCryptoWorker.getInstance();
@@ -208,12 +210,12 @@ export async function decryptFile(
const fileKey = await worker.decryptB64(
encryptedKey,
keyDecryptionNonce,
- collectionKey
+ collectionKey,
);
const fileMetadata = await worker.decryptMetadata(
metadata.encryptedData,
metadata.decryptionHeader,
- fileKey
+ fileKey,
);
let fileMagicMetadata: FileMagicMetadata;
let filePubMagicMetadata: FilePublicMagicMetadata;
@@ -223,7 +225,7 @@ export async function decryptFile(
data: await worker.decryptMetadata(
magicMetadata.data,
magicMetadata.header,
- fileKey
+ fileKey,
),
};
}
@@ -233,7 +235,7 @@ export async function decryptFile(
data: await worker.decryptMetadata(
pubMagicMetadata.data,
pubMagicMetadata.header,
- fileKey
+ fileKey,
),
};
}
@@ -245,25 +247,25 @@ export async function decryptFile(
pubMagicMetadata: filePubMagicMetadata,
};
} catch (e) {
- logError(e, 'file decryption failed');
+ logError(e, "file decryption failed");
throw e;
}
}
export function getFileNameWithoutExtension(filename: string) {
- const lastDotPosition = filename.lastIndexOf('.');
+ const lastDotPosition = filename.lastIndexOf(".");
if (lastDotPosition === -1) return filename;
else return filename.slice(0, lastDotPosition);
}
export function getFileExtensionWithDot(filename: string) {
- const lastDotPosition = filename.lastIndexOf('.');
- if (lastDotPosition === -1) return '';
+ const lastDotPosition = filename.lastIndexOf(".");
+ if (lastDotPosition === -1) return "";
else return filename.slice(lastDotPosition);
}
export function splitFilenameAndExtension(filename: string): [string, string] {
- const lastDotPosition = filename.lastIndexOf('.');
+ const lastDotPosition = filename.lastIndexOf(".");
if (lastDotPosition === -1) return [filename, null];
else
return [
@@ -289,19 +291,19 @@ export async function getRenderableFileURL(
file: EnteFile,
fileBlob: Blob,
originalFileURL: string,
- forceConvert: boolean
+ forceConvert: boolean,
): Promise<SourceURLs> {
- let srcURLs: SourceURLs['url'];
+ let srcURLs: SourceURLs["url"];
switch (file.metadata.fileType) {
case FILE_TYPE.IMAGE: {
const convertedBlob = await getRenderableImage(
file.metadata.title,
- fileBlob
+ fileBlob,
);
const convertedURL = getFileObjectURL(
originalFileURL,
fileBlob,
- convertedBlob
+ convertedBlob,
);
srcURLs = convertedURL;
break;
@@ -310,7 +312,7 @@ export async function getRenderableFileURL(
srcURLs = await getRenderableLivePhotoURL(
file,
fileBlob,
- forceConvert
+ forceConvert,
);
break;
}
@@ -318,12 +320,12 @@ export async function getRenderableFileURL(
const convertedBlob = await getPlayableVideo(
file.metadata.title,
fileBlob,
- forceConvert
+ forceConvert,
);
const convertedURL = getFileObjectURL(
originalFileURL,
fileBlob,
- convertedBlob
+ convertedBlob,
);
srcURLs = convertedURL;
break;
@@ -348,15 +350,15 @@ export async function getRenderableFileURL(
file.metadata.fileType !== FILE_TYPE.LIVE_PHOTO && !!srcURLs,
type:
file.metadata.fileType === FILE_TYPE.LIVE_PHOTO
- ? 'livePhoto'
- : 'normal',
+ ? "livePhoto"
+ : "normal",
};
}
async function getRenderableLivePhotoURL(
file: EnteFile,
fileBlob: Blob,
- forceConvert: boolean
+ forceConvert: boolean,
): Promise<LivePhotoSourceURL> {
const livePhoto = await decodeLivePhoto(file, fileBlob);
@@ -365,7 +367,7 @@ async function getRenderableLivePhotoURL(
const imageBlob = new Blob([livePhoto.image]);
const convertedImageBlob = await getRenderableImage(
livePhoto.imageNameTitle,
- imageBlob
+ imageBlob,
);
return URL.createObjectURL(convertedImageBlob);
@@ -383,7 +385,7 @@ async function getRenderableLivePhotoURL(
livePhoto.videoNameTitle,
videoBlob,
forceConvert,
- true
+ true,
);
return URL.createObjectURL(convertedVideoBlob);
} catch (e) {
@@ -402,11 +404,11 @@ export async function getPlayableVideo(
videoNameTitle: string,
videoBlob: Blob,
forceConvert = false,
- runOnWeb = false
+ runOnWeb = false,
) {
try {
const isPlayable = await isPlaybackPossible(
- URL.createObjectURL(videoBlob)
+ URL.createObjectURL(videoBlob),
);
if (isPlayable && !forceConvert) {
return videoBlob;
@@ -415,18 +417,18 @@ export async function getPlayableVideo(
return null;
}
addLogLine(
- 'video format not supported, converting it name:',
- videoNameTitle
+ "video format not supported, converting it name:",
+ videoNameTitle,
);
const mp4ConvertedVideo = await ffmpegService.convertToMP4(
- new File([videoBlob], videoNameTitle)
+ new File([videoBlob], videoNameTitle),
);
- addLogLine('video successfully converted', videoNameTitle);
+ addLogLine("video successfully converted", videoNameTitle);
return new Blob([await mp4ConvertedVideo.arrayBuffer()]);
}
} catch (e) {
- addLogLine('video conversion failed', videoNameTitle);
- logError(e, 'video conversion failed');
+ addLogLine("video conversion failed", videoNameTitle);
+ logError(e, "video conversion failed");
return null;
}
}
@@ -450,12 +452,12 @@ export async function getRenderableImage(fileName: string, imageBlob: Blob) {
}
addLogLine(
`RawConverter called for ${fileName}-${convertBytesToHumanReadable(
- imageBlob.size
- )}`
+ imageBlob.size,
+ )}`,
);
convertedImageBlob = await imageProcessor.convertToJPEG(
imageBlob,
- fileName
+ fileName,
);
addLogLine(`${fileName} successfully converted`);
} catch (e) {
@@ -465,8 +467,8 @@ export async function getRenderableImage(fileName: string, imageBlob: Blob) {
}
addLogLine(
`HEICConverter called for ${fileName}-${convertBytesToHumanReadable(
- imageBlob.size
- )}`
+ imageBlob.size,
+ )}`,
);
convertedImageBlob =
await heicConversionService.convert(imageBlob);
@@ -480,7 +482,7 @@ export async function getRenderableImage(fileName: string, imageBlob: Blob) {
return imageBlob;
}
} catch (e) {
- logError(e, 'get Renderable Image failed', { fileTypeInfo });
+ logError(e, "get Renderable Image failed", { fileTypeInfo });
return null;
}
}
@@ -502,7 +504,7 @@ export function isSupportedRawFormat(exactType: string) {
export async function changeFilesVisibility(
files: EnteFile[],
- visibility: VISIBILITY_STATE
+ visibility: VISIBILITY_STATE,
): Promise<EnteFile[]> {
const fileWithUpdatedMagicMetadataList: FileWithUpdatedMagicMetadata[] = [];
for (const file of files) {
@@ -515,7 +517,7 @@ export async function changeFilesVisibility(
updatedMagicMetadata: await updateMagicMetadata(
updatedMagicMetadataProps,
file.magicMetadata,
- file.key
+ file.key,
),
});
}
@@ -524,7 +526,7 @@ export async function changeFilesVisibility(
export async function changeFileCreationTime(
file: EnteFile,
- editedTime: number
+ editedTime: number,
): Promise<EnteFile> {
const updatedPublicMagicMetadataProps: FilePublicMagicMetadataProps = {
editedTime,
@@ -533,7 +535,7 @@ export async function changeFileCreationTime(
await updateMagicMetadata(
updatedPublicMagicMetadataProps,
file.pubMagicMetadata,
- file.key
+ file.key,
);
const updateResult = await updateFilePublicMagicMetadata([
{ file, updatedPublicMagicMetadata },
@@ -543,7 +545,7 @@ export async function changeFileCreationTime(
export async function changeFileName(
file: EnteFile,
- editedName: string
+ editedName: string,
): Promise<EnteFile> {
const updatedPublicMagicMetadataProps: FilePublicMagicMetadataProps = {
editedName,
@@ -553,7 +555,7 @@ export async function changeFileName(
await updateMagicMetadata(
updatedPublicMagicMetadataProps,
file.pubMagicMetadata,
- file.key
+ file.key,
);
const updateResult = await updateFilePublicMagicMetadata([
{ file, updatedPublicMagicMetadata },
@@ -563,7 +565,7 @@ export async function changeFileName(
export async function changeCaption(
file: EnteFile,
- caption: string
+ caption: string,
): Promise<EnteFile> {
const updatedPublicMagicMetadataProps: FilePublicMagicMetadataProps = {
caption,
@@ -573,7 +575,7 @@ export async function changeCaption(
await updateMagicMetadata(
updatedPublicMagicMetadataProps,
file.pubMagicMetadata,
- file.key
+ file.key,
);
const updateResult = await updateFilePublicMagicMetadata([
{ file, updatedPublicMagicMetadata },
@@ -603,7 +605,7 @@ export function mergeMetadata(files: EnteFile[]): EnteFile[] {
export function updateExistingFilePubMetadata(
existingFile: EnteFile,
- updatedFile: EnteFile
+ updatedFile: EnteFile,
) {
existingFile.pubMagicMetadata = updatedFile.pubMagicMetadata;
existingFile.metadata = mergeMetadata([existingFile])[0].metadata;
@@ -632,7 +634,7 @@ export function getUniqueFiles(files: EnteFile[]) {
export async function downloadFilesWithProgress(
files: EnteFile[],
downloadDirPath: string,
- setFilesDownloadProgressAttributes: SetFilesDownloadProgressAttributes
+ setFilesDownloadProgressAttributes: SetFilesDownloadProgressAttributes,
) {
if (!files.length) {
return;
@@ -666,7 +668,7 @@ export async function downloadFilesWithProgress(
await downloadFilesDesktop(
files,
{ increaseSuccess, increaseFailed, isCancelled },
- downloadDirPath
+ downloadDirPath,
);
} else {
await downloadFiles(files, {
@@ -679,7 +681,7 @@ export async function downloadFilesWithProgress(
export async function downloadSelectedFiles(
files: EnteFile[],
- setFilesDownloadProgressAttributes: SetFilesDownloadProgressAttributes
+ setFilesDownloadProgressAttributes: SetFilesDownloadProgressAttributes,
) {
if (!files.length) {
return;
@@ -694,13 +696,13 @@ export async function downloadSelectedFiles(
await downloadFilesWithProgress(
files,
downloadDirPath,
- setFilesDownloadProgressAttributes
+ setFilesDownloadProgressAttributes,
);
}
export async function downloadSingleFile(
file: EnteFile,
- setFilesDownloadProgressAttributes: SetFilesDownloadProgressAttributes
+ setFilesDownloadProgressAttributes: SetFilesDownloadProgressAttributes,
) {
let downloadDirPath: string;
if (isElectron()) {
@@ -712,7 +714,7 @@ export async function downloadSingleFile(
await downloadFilesWithProgress(
[file],
downloadDirPath,
- setFilesDownloadProgressAttributes
+ setFilesDownloadProgressAttributes,
);
}
@@ -722,7 +724,7 @@ export async function downloadFiles(
increaseSuccess: () => void;
increaseFailed: () => void;
isCancelled: () => boolean;
- }
+ },
) {
for (const file of files) {
try {
@@ -732,7 +734,7 @@ export async function downloadFiles(
await downloadFile(file);
progressBarUpdater?.increaseSuccess();
} catch (e) {
- logError(e, 'download fail for file');
+ logError(e, "download fail for file");
progressBarUpdater?.increaseFailed();
}
}
@@ -745,7 +747,7 @@ export async function downloadFilesDesktop(
increaseFailed: () => void;
isCancelled: () => boolean;
},
- downloadPath: string
+ downloadPath: string,
) {
const fileReader = new FileReader();
for (const file of files) {
@@ -756,7 +758,7 @@ export async function downloadFilesDesktop(
await downloadFileDesktop(fileReader, file, downloadPath);
progressBarUpdater?.increaseSuccess();
} catch (e) {
- logError(e, 'download fail for file');
+ logError(e, "download fail for file");
progressBarUpdater?.increaseFailed();
}
}
@@ -765,15 +767,15 @@ export async function downloadFilesDesktop(
export async function downloadFileDesktop(
fileReader: FileReader,
file: EnteFile,
- downloadPath: string
+ downloadPath: string,
) {
const fileStream = (await DownloadManager.getFile(
- file
+ file,
)) as ReadableStream<Uint8Array>;
const updatedFileStream = await getUpdatedEXIFFileForDownload(
fileReader,
file,
- fileStream
+ fileStream,
);
if (file.metadata.fileType === FILE_TYPE.LIVE_PHOTO) {
@@ -781,37 +783,37 @@ export async function downloadFileDesktop(
const livePhoto = await decodeLivePhoto(file, fileBlob);
const imageExportName = getUniqueFileExportName(
downloadPath,
- livePhoto.imageNameTitle
+ livePhoto.imageNameTitle,
);
const imageStream = generateStreamFromArrayBuffer(livePhoto.image);
await ElectronAPIs.saveStreamToDisk(
getFileExportPath(downloadPath, imageExportName),
- imageStream
+ imageStream,
);
try {
const videoExportName = getUniqueFileExportName(
downloadPath,
- livePhoto.videoNameTitle
+ livePhoto.videoNameTitle,
);
const videoStream = generateStreamFromArrayBuffer(livePhoto.video);
await ElectronAPIs.saveStreamToDisk(
getFileExportPath(downloadPath, videoExportName),
- videoStream
+ videoStream,
);
} catch (e) {
ElectronFSService.deleteFile(
- getFileExportPath(downloadPath, imageExportName)
+ getFileExportPath(downloadPath, imageExportName),
);
throw e;
}
} else {
const fileExportName = getUniqueFileExportName(
downloadPath,
- file.metadata.title
+ file.metadata.title,
);
await ElectronAPIs.saveStreamToDisk(
getFileExportPath(downloadPath, fileExportName),
- updatedFileStream
+ updatedFileStream,
);
}
}
@@ -831,21 +833,21 @@ export const createTypedObjectURL = async (blob: Blob, fileName: string) => {
export const getUserOwnedFiles = (files: EnteFile[]) => {
const user: User = getData(LS_KEYS.USER);
if (!user?.id) {
- throw Error('user missing');
+ throw Error("user missing");
}
return files.filter((file) => file.ownerID === user.id);
};
// doesn't work on firefox
export const copyFileToClipboard = async (fileUrl: string) => {
- const canvas = document.createElement('canvas');
- const canvasCTX = canvas.getContext('2d');
+ const canvas = document.createElement("canvas");
+ const canvasCTX = canvas.getContext("2d");
const image = new Image();
const blobPromise = new Promise<Blob>((resolve, reject) => {
let timeout: NodeJS.Timeout = null;
try {
- image.setAttribute('src', fileUrl);
+ image.setAttribute("src", fileUrl);
image.onload = () => {
canvas.width = image.width;
canvas.height = image.height;
@@ -854,29 +856,29 @@ export const copyFileToClipboard = async (fileUrl: string) => {
(blob) => {
resolve(blob);
},
- 'image/png',
- 1
+ "image/png",
+ 1,
);
clearTimeout(timeout);
};
} catch (e) {
- void logError(e, 'failed to copy to clipboard');
+ void logError(e, "failed to copy to clipboard");
reject(e);
} finally {
clearTimeout(timeout);
}
timeout = setTimeout(
() => reject(Error(CustomError.WAIT_TIME_EXCEEDED)),
- WAIT_TIME_IMAGE_CONVERSION
+ WAIT_TIME_IMAGE_CONVERSION,
);
});
const { ClipboardItem } = window;
await navigator.clipboard
- .write([new ClipboardItem({ 'image/png': blobPromise })])
- .catch((e) => logError(e, 'failed to copy to clipboard'));
+ .write([new ClipboardItem({ "image/png": blobPromise })])
+ .catch((e) => logError(e, "failed to copy to clipboard"));
};
export function getLatestVersionFiles(files: EnteFile[]) {
@@ -891,23 +893,23 @@ export function getLatestVersionFiles(files: EnteFile[]) {
}
});
return Array.from(latestVersionFiles.values()).filter(
- (file) => !file.isDeleted
+ (file) => !file.isDeleted,
);
}
export function getPersonalFiles(
files: EnteFile[],
user: User,
- collectionIdToOwnerIDMap?: Map<number, number>
+ collectionIdToOwnerIDMap?: Map<number, number>,
) {
if (!user?.id) {
- throw Error('user missing');
+ throw Error("user missing");
}
return files.filter(
(file) =>
file.ownerID === user.id &&
(!collectionIdToOwnerIDMap ||
- collectionIdToOwnerIDMap.get(file.collectionID) === user.id)
+ collectionIdToOwnerIDMap.get(file.collectionID) === user.id),
);
}
@@ -949,19 +951,19 @@ export const handleFileOps = async (
ops: FILE_OPS_TYPE,
files: EnteFile[],
setTempDeletedFileIds: (
- tempDeletedFileIds: Set<number> | ((prev: Set<number>) => Set<number>)
+ tempDeletedFileIds: Set<number> | ((prev: Set<number>) => Set<number>),
) => void,
setTempHiddenFileIds: (
- tempHiddenFileIds: Set<number> | ((prev: Set<number>) => Set<number>)
+ tempHiddenFileIds: Set<number> | ((prev: Set<number>) => Set<number>),
) => void,
setFixCreationTimeAttributes: (
fixCreationTimeAttributes:
| {
files: EnteFile[];
}
- | ((prev: { files: EnteFile[] }) => { files: EnteFile[] })
+ | ((prev: { files: EnteFile[] }) => { files: EnteFile[] }),
) => void,
- setFilesDownloadProgressAttributesCreator: SetFilesDownloadProgressAttributesCreator
+ setFilesDownloadProgressAttributesCreator: SetFilesDownloadProgressAttributesCreator,
) => {
switch (ops) {
case FILE_OPS_TYPE.TRASH:
@@ -976,11 +978,11 @@ export const handleFileOps = async (
case FILE_OPS_TYPE.DOWNLOAD: {
const setSelectedFileDownloadProgressAttributes =
setFilesDownloadProgressAttributesCreator(
- `${files.length} ${t('FILES')}`
+ `${files.length} ${t("FILES")}`,
);
await downloadSelectedFiles(
files,
- setSelectedFileDownloadProgressAttributes
+ setSelectedFileDownloadProgressAttributes,
);
break;
}
@@ -1000,8 +1002,8 @@ const deleteFileHelper = async (
selectedFiles: EnteFile[],
permanent: boolean,
setTempDeletedFileIds: (
- tempDeletedFileIds: Set<number> | ((prev: Set<number>) => Set<number>)
- ) => void
+ tempDeletedFileIds: Set<number> | ((prev: Set<number>) => Set<number>),
+ ) => void,
) => {
try {
setTempDeletedFileIds((deletedFileIds) => {
@@ -1022,8 +1024,8 @@ const deleteFileHelper = async (
const hideFilesHelper = async (
selectedFiles: EnteFile[],
setTempHiddenFileIds: (
- tempHiddenFileIds: Set<number> | ((prev: Set<number>) => Set<number>)
- ) => void
+ tempHiddenFileIds: Set<number> | ((prev: Set<number>) => Set<number>),
+ ) => void,
) => {
try {
setTempHiddenFileIds((hiddenFileIds) => {
@@ -1041,7 +1043,7 @@ const fixTimeHelper = async (
selectedFiles: EnteFile[],
setFixCreationTimeAttributes: (fixCreationTimeAttributes: {
files: EnteFile[];
- }) => void
+ }) => void,
) => {
setFixCreationTimeAttributes({ files: selectedFiles });
};
@@ -1049,7 +1051,7 @@ const fixTimeHelper = async (
const getFileObjectURL = (
originalFileURL: string,
originalBlob: Blob,
- convertedBlob: Blob
+ convertedBlob: Blob,
) => {
const convertedURL = convertedBlob
? convertedBlob === originalBlob
diff --git a/apps/photos/src/utils/file/livePhoto.ts b/apps/photos/src/utils/file/livePhoto.ts
index 92fb311b14..7d687217ce 100644
--- a/apps/photos/src/utils/file/livePhoto.ts
+++ b/apps/photos/src/utils/file/livePhoto.ts
@@ -1,37 +1,37 @@
-import { FILE_TYPE } from 'constants/file';
-import { getFileExtension } from 'utils/file';
+import { FILE_TYPE } from "constants/file";
+import { getFileExtension } from "utils/file";
const IMAGE_EXTENSIONS = [
- 'heic',
- 'heif',
- 'jpeg',
- 'jpg',
- 'png',
- 'gif',
- 'bmp',
- 'tiff',
- 'webp',
+ "heic",
+ "heif",
+ "jpeg",
+ "jpg",
+ "png",
+ "gif",
+ "bmp",
+ "tiff",
+ "webp",
];
const VIDEO_EXTENSIONS = [
- 'mov',
- 'mp4',
- 'm4v',
- 'avi',
- 'wmv',
- 'flv',
- 'mkv',
- 'webm',
- '3gp',
- '3g2',
- 'avi',
- 'ogv',
- 'mpg',
- 'mp',
+ "mov",
+ "mp4",
+ "m4v",
+ "avi",
+ "wmv",
+ "flv",
+ "mkv",
+ "webm",
+ "3gp",
+ "3g2",
+ "avi",
+ "ogv",
+ "mpg",
+ "mp",
];
export function getFileTypeFromExtensionForLivePhotoClustering(
- filename: string
+ filename: string,
) {
const extension = getFileExtension(filename)?.toLowerCase();
if (IMAGE_EXTENSIONS.includes(extension)) {
diff --git a/apps/photos/src/utils/image/index.ts b/apps/photos/src/utils/image/index.ts
index d65c3f7ea9..1062b828f9 100644
--- a/apps/photos/src/utils/image/index.ts
+++ b/apps/photos/src/utils/image/index.ts
@@ -1,16 +1,16 @@
// these utils only work in env where OffscreenCanvas is available
-import { BlobOptions, Dimensions } from 'types/image';
-import { enlargeBox } from 'utils/machineLearning';
-import { Box } from '../../../thirdparty/face-api/classes';
+import { BlobOptions, Dimensions } from "types/image";
+import { enlargeBox } from "utils/machineLearning";
+import { Box } from "../../../thirdparty/face-api/classes";
export function resizeToSquare(img: ImageBitmap, size: number) {
const scale = size / Math.max(img.height, img.width);
const width = scale * img.width;
const height = scale * img.height;
const offscreen = new OffscreenCanvas(size, size);
- const ctx = offscreen.getContext('2d');
- ctx.imageSmoothingQuality = 'high';
+ const ctx = offscreen.getContext("2d");
+ ctx.imageSmoothingQuality = "high";
ctx.drawImage(img, 0, 0, width, height);
const resizedImage = offscreen.transferToImageBitmap();
return { image: resizedImage, width, height };
@@ -20,11 +20,11 @@ export function transform(
imageBitmap: ImageBitmap,
affineMat: number[][],
outputWidth: number,
- outputHeight: number
+ outputHeight: number,
) {
const offscreen = new OffscreenCanvas(outputWidth, outputHeight);
- const context = offscreen.getContext('2d');
- context.imageSmoothingQuality = 'high';
+ const context = offscreen.getContext("2d");
+ context.imageSmoothingQuality = "high";
context.transform(
affineMat[0][0],
@@ -32,7 +32,7 @@ export function transform(
affineMat[0][1],
affineMat[1][1],
affineMat[0][2],
- affineMat[1][2]
+ affineMat[1][2],
);
context.drawImage(imageBitmap, 0, 0);
@@ -53,7 +53,7 @@ export function cropWithRotation(
cropBox: Box,
rotation?: number,
maxSize?: Dimensions,
- minSize?: Dimensions
+ minSize?: Dimensions,
) {
const box = cropBox.round();
@@ -61,7 +61,7 @@ export function cropWithRotation(
if (maxSize) {
const minScale = Math.min(
maxSize.width / box.width,
- maxSize.height / box.height
+ maxSize.height / box.height,
);
if (minScale < 1) {
outputSize.width = Math.round(minScale * box.width);
@@ -72,7 +72,7 @@ export function cropWithRotation(
if (minSize) {
const maxScale = Math.max(
minSize.width / box.width,
- minSize.height / box.height
+ minSize.height / box.height,
);
if (maxScale > 1) {
outputSize.width = Math.round(maxScale * box.width);
@@ -83,8 +83,8 @@ export function cropWithRotation(
// addLogLine({ imageBitmap, box, outputSize });
const offscreen = new OffscreenCanvas(outputSize.width, outputSize.height);
- const offscreenCtx = offscreen.getContext('2d');
- offscreenCtx.imageSmoothingQuality = 'high';
+ const offscreenCtx = offscreen.getContext("2d");
+ offscreenCtx.imageSmoothingQuality = "high";
offscreenCtx.translate(outputSize.width / 2, outputSize.height / 2);
rotation && offscreenCtx.rotate(rotation);
@@ -108,7 +108,7 @@ export function cropWithRotation(
enlargedOutputBox.x,
enlargedOutputBox.y,
enlargedOutputBox.width,
- enlargedOutputBox.height
+ enlargedOutputBox.height,
);
return offscreen.transferToImageBitmap();
@@ -119,14 +119,14 @@ export function addPadding(image: ImageBitmap, padding: number) {
const width = scale * image.width;
const height = scale * image.height;
const offscreen = new OffscreenCanvas(width, height);
- const ctx = offscreen.getContext('2d');
+ const ctx = offscreen.getContext("2d");
ctx.imageSmoothingEnabled = false;
ctx.drawImage(
image,
width / 2 - image.width / 2,
height / 2 - image.height / 2,
image.width,
- image.height
+ image.height,
);
return offscreen.transferToImageBitmap();
@@ -134,13 +134,13 @@ export function addPadding(image: ImageBitmap, padding: number) {
export async function imageBitmapToBlob(
imageBitmap: ImageBitmap,
- options?: BlobOptions
+ options?: BlobOptions,
) {
const offscreen = new OffscreenCanvas(
imageBitmap.width,
- imageBitmap.height
+ imageBitmap.height,
);
- offscreen.getContext('2d').drawImage(imageBitmap, 0, 0);
+ offscreen.getContext("2d").drawImage(imageBitmap, 0, 0);
return offscreen.convertToBlob(options);
}
diff --git a/apps/photos/src/utils/machineLearning/clustering.ts b/apps/photos/src/utils/machineLearning/clustering.ts
index 9abd971d24..26d8f803d1 100644
--- a/apps/photos/src/utils/machineLearning/clustering.ts
+++ b/apps/photos/src/utils/machineLearning/clustering.ts
@@ -1,9 +1,7 @@
-import {
- euclidean,
- // TreeNode
-} from 'hdbscan';
+import { euclidean } from "hdbscan";
// import { RawNodeDatum } from 'react-d3-tree/lib/types/common';
// import { f32Average, getAllFacesFromMap } from '.';
+import { addLogLine } from "@ente/shared/logging";
import {
FacesCluster,
// Cluster,
@@ -11,8 +9,7 @@ import {
FaceWithEmbedding,
MLSyncContext,
NearestCluster,
-} from 'types/machineLearning';
-import { addLogLine } from '@ente/shared/logging';
+} from "types/machineLearning";
// import { getAllFacesMap } from 'utils/storage/mlStorage';
// export function getClusterSummary(cluster: Cluster): FaceDescriptor {
@@ -45,14 +42,14 @@ export function updateClusterSummaries(syncContext: MLSyncContext) {
export function getNearestCluster(
syncContext: MLSyncContext,
- noise: FaceWithEmbedding
+ noise: FaceWithEmbedding,
): NearestCluster {
let nearest: FacesCluster = null;
let nearestDist = 100000;
syncContext.mlLibraryData.faceClustersWithNoise.clusters.forEach((c) => {
const dist = euclidean(
Array.from(noise.embedding),
- Array.from(c.summary)
+ Array.from(c.summary),
);
if (dist < nearestDist) {
nearestDist = dist;
@@ -60,7 +57,7 @@ export function getNearestCluster(
}
});
- addLogLine('nearestDist: ', nearestDist);
+ addLogLine("nearestDist: ", nearestDist);
return { cluster: nearest, distance: nearestDist };
}
diff --git a/apps/photos/src/utils/machineLearning/compatibility.ts b/apps/photos/src/utils/machineLearning/compatibility.ts
index 8835dd4dca..47916707dd 100644
--- a/apps/photos/src/utils/machineLearning/compatibility.ts
+++ b/apps/photos/src/utils/machineLearning/compatibility.ts
@@ -2,25 +2,25 @@ import {
offscreenCanvasSupported,
runningInChrome,
webglSupported,
-} from 'utils/common';
+} from "utils/common";
-import isElectron from 'is-electron';
-import { addLogLine } from '@ente/shared/logging';
+import { addLogLine } from "@ente/shared/logging";
+import isElectron from "is-electron";
export function canEnableMlSearch(): boolean {
// check if is chrome or ente desktop
if (!runningInChrome(false) && !isElectron()) {
- addLogLine('Not running in Chrome Desktop or Ente Desktop App');
+ addLogLine("Not running in Chrome Desktop or Ente Desktop App");
return false;
}
if (!offscreenCanvasSupported()) {
- addLogLine('OffscreenCanvas is NOT supported');
+ addLogLine("OffscreenCanvas is NOT supported");
return false;
}
if (!webglSupported()) {
- addLogLine('webgl is NOT supported');
+ addLogLine("webgl is NOT supported");
return false;
}
diff --git a/apps/photos/src/utils/machineLearning/config.ts b/apps/photos/src/utils/machineLearning/config.ts
index a2facd1715..4d2030ca3e 100644
--- a/apps/photos/src/utils/machineLearning/config.ts
+++ b/apps/photos/src/utils/machineLearning/config.ts
@@ -2,19 +2,19 @@ import {
DEFAULT_ML_SEARCH_CONFIG,
DEFAULT_ML_SYNC_CONFIG,
DEFAULT_ML_SYNC_JOB_CONFIG,
-} from 'constants/mlConfig';
-import { JobConfig } from 'types/common/job';
-import { MLSearchConfig, MLSyncConfig } from 'types/machineLearning';
+} from "constants/mlConfig";
+import { JobConfig } from "types/common/job";
+import { MLSearchConfig, MLSyncConfig } from "types/machineLearning";
import mlIDbStorage, {
ML_SEARCH_CONFIG_NAME,
ML_SYNC_CONFIG_NAME,
ML_SYNC_JOB_CONFIG_NAME,
-} from 'utils/storage/mlIDbStorage';
+} from "utils/storage/mlIDbStorage";
export async function getMLSyncJobConfig() {
return mlIDbStorage.getConfig(
ML_SYNC_JOB_CONFIG_NAME,
- DEFAULT_ML_SYNC_JOB_CONFIG
+ DEFAULT_ML_SYNC_JOB_CONFIG,
);
}
@@ -25,7 +25,7 @@ export async function getMLSyncConfig() {
export async function getMLSearchConfig() {
return mlIDbStorage.getConfig(
ML_SEARCH_CONFIG_NAME,
- DEFAULT_ML_SEARCH_CONFIG
+ DEFAULT_ML_SEARCH_CONFIG,
);
}
diff --git a/apps/photos/src/utils/machineLearning/faceAlign.ts b/apps/photos/src/utils/machineLearning/faceAlign.ts
index add8f994cd..392b6b278a 100644
--- a/apps/photos/src/utils/machineLearning/faceAlign.ts
+++ b/apps/photos/src/utils/machineLearning/faceAlign.ts
@@ -1,7 +1,13 @@
-import { FaceAlignment, FaceDetection } from 'types/machineLearning';
-import { Matrix, inverse } from 'ml-matrix';
-import * as tf from '@tensorflow/tfjs-core';
-import { getSimilarityTransformation } from 'similarity-transformation';
+import * as tf from "@tensorflow/tfjs-core";
+import { Matrix, inverse } from "ml-matrix";
+import { getSimilarityTransformation } from "similarity-transformation";
+import { Dimensions } from "types/image";
+import { FaceAlignment, FaceDetection } from "types/machineLearning";
+import {
+ ARCFACE_LANDMARKS,
+ ARCFACE_LANDMARKS_FACE_SIZE,
+} from "types/machineLearning/archface";
+import { cropWithRotation, transform } from "utils/image";
import {
computeRotation,
enlargeBox,
@@ -9,39 +15,33 @@ import {
getBoxCenter,
getBoxCenterPt,
toTensor4D,
-} from '.';
-import { cropWithRotation, transform } from 'utils/image';
-import {
- ARCFACE_LANDMARKS,
- ARCFACE_LANDMARKS_FACE_SIZE,
-} from 'types/machineLearning/archface';
-import { Box, Point } from '../../../thirdparty/face-api/classes';
-import { Dimensions } from 'types/image';
+} from ".";
+import { Box, Point } from "../../../thirdparty/face-api/classes";
export function normalizeLandmarks(
landmarks: Array<[number, number]>,
- faceSize: number
+ faceSize: number,
) {
return landmarks.map((landmark) =>
- landmark.map((p) => p / faceSize)
+ landmark.map((p) => p / faceSize),
) as Array<[number, number]>;
}
export function getFaceAlignmentUsingSimilarityTransform(
faceDetection: FaceDetection,
- alignedLandmarks: Array<[number, number]>
+ alignedLandmarks: Array<[number, number]>,
// alignmentMethod: Versioned<FaceAlignmentMethod>
): FaceAlignment {
const landmarksMat = new Matrix(
faceDetection.landmarks
.map((p) => [p.x, p.y])
- .slice(0, alignedLandmarks.length)
+ .slice(0, alignedLandmarks.length),
).transpose();
const alignedLandmarksMat = new Matrix(alignedLandmarks).transpose();
const simTransform = getSimilarityTransformation(
landmarksMat,
- alignedLandmarksMat
+ alignedLandmarksMat,
);
const RS = Matrix.mul(simTransform.rotation, simTransform.scale);
@@ -59,7 +59,7 @@ export function getFaceAlignmentUsingSimilarityTransform(
const center = new Point(centerMat.get(0, 0), centerMat.get(1, 0));
const rotation = -Math.atan2(
simTransform.rotation.get(0, 1),
- simTransform.rotation.get(0, 0)
+ simTransform.rotation.get(0, 0),
);
// addLogLine({ affineMatrix, meanTranslation, centerMat, center, toMean: simTransform.toMean, fromMean: simTransform.fromMean, size });
@@ -72,18 +72,18 @@ export function getFaceAlignmentUsingSimilarityTransform(
}
export function getArcfaceAlignment(
- faceDetection: FaceDetection
+ faceDetection: FaceDetection,
): FaceAlignment {
return getFaceAlignmentUsingSimilarityTransform(
faceDetection,
- normalizeLandmarks(ARCFACE_LANDMARKS, ARCFACE_LANDMARKS_FACE_SIZE)
+ normalizeLandmarks(ARCFACE_LANDMARKS, ARCFACE_LANDMARKS_FACE_SIZE),
);
}
export function extractFaceImage(
image: tf.Tensor4D,
alignment: FaceAlignment,
- faceSize: number
+ faceSize: number,
) {
const affineMat = new Matrix(alignment.affineMatrix);
@@ -105,10 +105,10 @@ export function extractFaceImage(
const faceImage = tf.image.transform(
image,
projection,
- 'bilinear',
- 'constant',
+ "bilinear",
+ "constant",
0,
- [faceSize, faceSize]
+ [faceSize, faceSize],
);
return faceImage;
});
@@ -117,15 +117,15 @@ export function extractFaceImage(
export function tfExtractFaceImages(
image: tf.Tensor3D | tf.Tensor4D,
alignments: Array<FaceAlignment>,
- faceSize: number
+ faceSize: number,
): tf.Tensor4D {
return tf.tidy(() => {
- const tf4dFloat32Image = toTensor4D(image, 'float32');
+ const tf4dFloat32Image = toTensor4D(image, "float32");
const faceImages = new Array<tf.Tensor3D>(alignments.length);
for (let i = 0; i < alignments.length; i++) {
faceImages[i] = tf.squeeze(
extractFaceImage(tf4dFloat32Image, alignments[i], faceSize),
- [0]
+ [0],
);
}
@@ -145,7 +145,7 @@ export function getAlignedFaceBox(alignment: FaceAlignment) {
export function ibExtractFaceImage(
image: ImageBitmap,
alignment: FaceAlignment,
- faceSize: number
+ faceSize: number,
): ImageBitmap {
const box = getAlignedFaceBox(alignment);
const faceSizeDimentions: Dimensions = {
@@ -157,14 +157,14 @@ export function ibExtractFaceImage(
box,
alignment.rotation,
faceSizeDimentions,
- faceSizeDimentions
+ faceSizeDimentions,
);
}
export function ibExtractFaceImageUsingTransform(
image: ImageBitmap,
alignment: FaceAlignment,
- faceSize: number
+ faceSize: number,
): ImageBitmap {
const scaledMatrix = new Matrix(alignment.affineMatrix)
.mul(faceSize)
@@ -176,21 +176,21 @@ export function ibExtractFaceImageUsingTransform(
export function ibExtractFaceImages(
image: ImageBitmap,
alignments: Array<FaceAlignment>,
- faceSize: number
+ faceSize: number,
): Array<ImageBitmap> {
return alignments.map((alignment) =>
- ibExtractFaceImage(image, alignment, faceSize)
+ ibExtractFaceImage(image, alignment, faceSize),
);
}
export function extractArcfaceAlignedFaceImage(
image: tf.Tensor4D,
faceDetection: FaceDetection,
- faceSize: number
+ faceSize: number,
): tf.Tensor4D {
const alignment = getFaceAlignmentUsingSimilarityTransform(
faceDetection,
- ARCFACE_LANDMARKS
+ ARCFACE_LANDMARKS,
);
return extractFaceImage(image, alignment, faceSize);
@@ -199,19 +199,19 @@ export function extractArcfaceAlignedFaceImage(
export function extractArcfaceAlignedFaceImages(
image: tf.Tensor3D | tf.Tensor4D,
faceDetections: Array<FaceDetection>,
- faceSize: number
+ faceSize: number,
): tf.Tensor4D {
return tf.tidy(() => {
- const tf4dFloat32Image = toTensor4D(image, 'float32');
+ const tf4dFloat32Image = toTensor4D(image, "float32");
const faceImages = new Array<tf.Tensor3D>(faceDetections.length);
for (let i = 0; i < faceDetections.length; i++) {
faceImages[i] = tf.squeeze(
extractArcfaceAlignedFaceImage(
tf4dFloat32Image,
faceDetections[i],
- faceSize
+ faceSize,
),
- [0]
+ [0],
);
}
@@ -227,14 +227,14 @@ const BLAZEFACE_MOUTH_INDEX = 3;
export function getRotatedFaceImage(
image: tf.Tensor3D | tf.Tensor4D,
faceDetection: FaceDetection,
- padding: number = 1.5
+ padding: number = 1.5,
): tf.Tensor4D {
const paddedBox = enlargeBox(faceDetection.box, padding);
// addLogLine("paddedBox", paddedBox);
const landmarkPoints = faceDetection.landmarks;
return tf.tidy(() => {
- const tf4dFloat32Image = toTensor4D(image, 'float32');
+ const tf4dFloat32Image = toTensor4D(image, "float32");
let angle = 0;
const leftEye = landmarkPoints[BLAZEFACE_LEFT_EYE_INDEX];
const rightEye = landmarkPoints[BLAZEFACE_RIGHT_EYE_INDEX];
@@ -242,7 +242,7 @@ export function getRotatedFaceImage(
angle = computeRotation(
landmarkPoints[BLAZEFACE_MOUTH_INDEX],
- foreheadCenter
+ foreheadCenter,
); // landmarkPoints[BLAZEFACE_NOSE_INDEX]
// angle = computeRotation(leftEye, rightEye);
// addLogLine('angle: ', angle);
@@ -261,14 +261,14 @@ export function getRotatedFaceImage(
tf4dFloat32Image,
angle,
0,
- faceCenterNormalized
+ faceCenterNormalized,
);
}
const faceImageTensor = extractFaces(
rotatedImage,
[paddedBox],
- paddedBox.width > 224 ? 448 : 224
+ paddedBox.width > 224 ? 448 : 224,
);
return faceImageTensor;
// return tf.gather(faceImageTensor, 0);
diff --git a/apps/photos/src/utils/machineLearning/faceCrop.ts b/apps/photos/src/utils/machineLearning/faceCrop.ts
index 7cb45f367a..e96f1d2622 100644
--- a/apps/photos/src/utils/machineLearning/faceCrop.ts
+++ b/apps/photos/src/utils/machineLearning/faceCrop.ts
@@ -1,28 +1,28 @@
-import { CACHES } from '@ente/shared/storage/cacheStorage/constants';
-import { CacheStorageService } from '@ente/shared/storage/cacheStorage';
-import { compose, Matrix, scale, translate } from 'transformation-matrix';
-import { BlobOptions, Dimensions } from 'types/image';
+import { addLogLine } from "@ente/shared/logging";
+import { CacheStorageService } from "@ente/shared/storage/cacheStorage";
+import { CACHES } from "@ente/shared/storage/cacheStorage/constants";
+import { getBlobFromCache } from "@ente/shared/storage/cacheStorage/helpers";
+import { compose, Matrix, scale, translate } from "transformation-matrix";
+import { BlobOptions, Dimensions } from "types/image";
import {
AlignedFace,
- FaceCropConfig,
- FaceCrop,
- StoredFaceCrop,
- MlFileData,
FaceAlignment,
+ FaceCrop,
+ FaceCropConfig,
FaceDetection,
-} from 'types/machineLearning';
-import { cropWithRotation, imageBitmapToBlob } from 'utils/image';
-import { addLogLine } from '@ente/shared/logging';
-import { getBlobFromCache } from '@ente/shared/storage/cacheStorage/helpers';
-import { enlargeBox } from '.';
-import { Box } from '../../../thirdparty/face-api/classes';
-import { getAlignedFaceBox } from './faceAlign';
-import { transformBox, transformPoints } from './transform';
+ MlFileData,
+ StoredFaceCrop,
+} from "types/machineLearning";
+import { cropWithRotation, imageBitmapToBlob } from "utils/image";
+import { enlargeBox } from ".";
+import { Box } from "../../../thirdparty/face-api/classes";
+import { getAlignedFaceBox } from "./faceAlign";
+import { transformBox, transformPoints } from "./transform";
export function getFaceCrop(
imageBitmap: ImageBitmap,
alignment: FaceAlignment,
- config: FaceCropConfig
+ config: FaceCropConfig,
): FaceCrop {
const box = getAlignedFaceBox(alignment);
const scaleForPadding = 1 + config.padding * 2;
@@ -41,7 +41,7 @@ export function getFaceCrop(
export async function storeFaceCropForBlob(
faceId: string,
imageBox: Box,
- faceCropBlob: Blob
+ faceCropBlob: Blob,
) {
const faceCropUrl = `/${faceId}`;
const faceCropResponse = new Response(faceCropBlob);
@@ -56,20 +56,20 @@ export async function storeFaceCropForBlob(
export async function storeFaceCrop(
faceId: string,
faceCrop: FaceCrop,
- blobOptions: BlobOptions
+ blobOptions: BlobOptions,
): Promise<StoredFaceCrop> {
const faceCropBlob = await imageBitmapToBlob(faceCrop.image, blobOptions);
return storeFaceCropForBlob(faceId, faceCrop.imageBox, faceCropBlob);
}
export async function getFaceCropBlobFromStorage(
- storedFaceCrop: StoredFaceCrop
+ storedFaceCrop: StoredFaceCrop,
): Promise<Blob> {
return getBlobFromCache(CACHES.FACE_CROPS, storedFaceCrop.imageUrl);
}
export async function getFaceCropFromStorage(
- storedFaceCrop: StoredFaceCrop
+ storedFaceCrop: StoredFaceCrop,
): Promise<FaceCrop> {
const faceCropBlob = await getFaceCropBlobFromStorage(storedFaceCrop);
const faceCropImage = await createImageBitmap(faceCropBlob);
@@ -82,7 +82,7 @@ export async function getFaceCropFromStorage(
export async function removeOldFaceCrops(
oldMLFileData: MlFileData,
- newMLFileData: MlFileData
+ newMLFileData: MlFileData,
) {
const newFaceCropUrls =
newMLFileData?.faces
@@ -95,7 +95,7 @@ export async function removeOldFaceCrops(
?.filter((fc) => fc !== null && fc !== undefined) || [];
const unusedFaceCropUrls = oldFaceCropUrls.filter(
- (oldUrl) => !newFaceCropUrls.includes(oldUrl)
+ (oldUrl) => !newFaceCropUrls.includes(oldUrl),
);
if (!unusedFaceCropUrls || unusedFaceCropUrls.length < 1) {
return;
@@ -105,10 +105,10 @@ export async function removeOldFaceCrops(
}
export async function removeFaceCropUrls(faceCropUrls: Array<string>) {
- addLogLine('Removing face crop urls: ', JSON.stringify(faceCropUrls));
+ addLogLine("Removing face crop urls: ", JSON.stringify(faceCropUrls));
const faceCropCache = await CacheStorageService.open(CACHES.FACE_CROPS);
const urlRemovalPromises = faceCropUrls?.map((url) =>
- faceCropCache.delete(url)
+ faceCropCache.delete(url),
);
return urlRemovalPromises && Promise.all(urlRemovalPromises);
}
@@ -117,12 +117,12 @@ export function extractFaceImageFromCrop(
faceCrop: FaceCrop,
box: Box,
rotation: number,
- faceSize: number
+ faceSize: number,
): ImageBitmap {
const faceCropImage = faceCrop?.image;
let imageBox = faceCrop?.imageBox;
if (!faceCropImage || !imageBox) {
- throw Error('Face crop not present');
+ throw Error("Face crop not present");
}
// TODO: Have better serialization to avoid creating new object manually when calling class methods
@@ -143,7 +143,7 @@ export function extractFaceImageFromCrop(
transformedBox,
rotation,
faceSizeDimentions,
- faceSizeDimentions
+ faceSizeDimentions,
);
return faceImage;
@@ -152,7 +152,7 @@ export function extractFaceImageFromCrop(
export async function ibExtractFaceImageFromCrop(
faceCrop: FaceCrop,
alignment: FaceAlignment,
- faceSize: number
+ faceSize: number,
): Promise<ImageBitmap> {
const box = getAlignedFaceBox(alignment);
@@ -160,20 +160,20 @@ export async function ibExtractFaceImageFromCrop(
faceCrop,
box,
alignment.rotation,
- faceSize
+ faceSize,
);
}
export async function ibExtractFaceImagesFromCrops(
faces: Array<AlignedFace>,
- faceSize: number
+ faceSize: number,
): Promise<Array<ImageBitmap>> {
const faceImagePromises = faces.map(async (alignedFace) => {
const faceCrop = await getFaceCropFromStorage(alignedFace.crop);
return ibExtractFaceImageFromCrop(
faceCrop,
alignedFace.alignment,
- faceSize
+ faceSize,
);
});
return Promise.all(faceImagePromises);
@@ -190,13 +190,13 @@ export function transformFace(faceDetection: FaceDetection, transform: Matrix) {
export function transformToFaceCropDims(
faceCrop: FaceCrop,
- faceDetection: FaceDetection
+ faceDetection: FaceDetection,
) {
const imageBox = new Box(faceCrop.imageBox);
const transform = compose(
scale(faceCrop.image.width / imageBox.width),
- translate(-imageBox.x, -imageBox.y)
+ translate(-imageBox.x, -imageBox.y),
);
return transformFace(faceDetection, transform);
@@ -204,13 +204,13 @@ export function transformToFaceCropDims(
export function transformToImageDims(
faceCrop: FaceCrop,
- faceDetection: FaceDetection
+ faceDetection: FaceDetection,
) {
const imageBox = new Box(faceCrop.imageBox);
const transform = compose(
translate(imageBox.x, imageBox.y),
- scale(imageBox.width / faceCrop.image.width)
+ scale(imageBox.width / faceCrop.image.width),
);
return transformFace(faceDetection, transform);
diff --git a/apps/photos/src/utils/machineLearning/faceDetection.ts b/apps/photos/src/utils/machineLearning/faceDetection.ts
index 33ffcde6ee..a9300539fa 100644
--- a/apps/photos/src/utils/machineLearning/faceDetection.ts
+++ b/apps/photos/src/utils/machineLearning/faceDetection.ts
@@ -1,18 +1,18 @@
-import { getNearestPointIndex, newBox } from '.';
+import { euclidean } from "hdbscan";
+import { FaceDetection } from "types/machineLearning";
+import { getNearestPointIndex, newBox } from ".";
+import { Box, Point } from "../../../thirdparty/face-api/classes";
import {
computeTransformToBox,
transformBox,
transformPoints,
-} from './transform';
-import { Box, Point } from '../../../thirdparty/face-api/classes';
-import { FaceDetection } from 'types/machineLearning';
-import { euclidean } from 'hdbscan';
+} from "./transform";
export function transformPaddedToImage(
detection: FaceDetection,
faceImage: ImageBitmap,
imageBox: Box,
- paddedBox: Box
+ paddedBox: Box,
) {
const inBox = newBox(0, 0, faceImage.width, faceImage.height);
imageBox.x = paddedBox.x;
@@ -38,7 +38,7 @@ export function getDetectionCenter(detection: FaceDetection) {
export function getNearestDetection(
toDetection: FaceDetection,
fromDetections: Array<FaceDetection>,
- maxDistance?: number
+ maxDistance?: number,
) {
const toCenter = getDetectionCenter(toDetection);
const centers = fromDetections.map((d) => getDetectionCenter(d));
@@ -50,7 +50,7 @@ export function getNearestDetection(
// TODO: can also be done through tf.image.nonMaxSuppression
export function removeDuplicateDetections(
detections: Array<FaceDetection>,
- withinDistance: number
+ withinDistance: number,
) {
// console.time('removeDuplicates');
detections.sort((a, b) => b.probability - a.probability);
@@ -68,7 +68,7 @@ export function removeDuplicateDetections(
const centerj = getDetectionCenter(detections[j]);
const dist = euclidean(
[centeri.x, centeri.y],
- [centerj.x, centerj.y]
+ [centerj.x, centerj.y],
);
if (dist <= withinDistance) {
isSelected.set(j, false);
diff --git a/apps/photos/src/utils/machineLearning/index.ts b/apps/photos/src/utils/machineLearning/index.ts
index ad3236b839..d6be9e63fa 100644
--- a/apps/photos/src/utils/machineLearning/index.ts
+++ b/apps/photos/src/utils/machineLearning/index.ts
@@ -1,14 +1,13 @@
-import { NormalizedFace } from 'blazeface-back';
-import * as tf from '@tensorflow/tfjs-core';
-import { BLAZEFACE_FACE_SIZE } from 'constants/mlConfig';
-import { euclidean } from 'hdbscan';
-import PQueue from 'p-queue';
-import DownloadManager from 'services/download';
-import { getLocalFiles } from 'services/fileService';
-import { EnteFile } from 'types/file';
-import { Dimensions } from 'types/image';
+import * as tf from "@tensorflow/tfjs-core";
+import { NormalizedFace } from "blazeface-back";
+import { BLAZEFACE_FACE_SIZE } from "constants/mlConfig";
+import { euclidean } from "hdbscan";
+import PQueue from "p-queue";
+import DownloadManager from "services/download";
+import { getLocalFiles } from "services/fileService";
+import { EnteFile } from "types/file";
+import { Dimensions } from "types/image";
import {
- RealWorldObject,
AlignedFace,
DetectedFace,
DetectedObject,
@@ -16,31 +15,32 @@ import {
FaceImageBlob,
MlFileData,
Person,
+ RealWorldObject,
Versioned,
-} from 'types/machineLearning';
+} from "types/machineLearning";
// import { mlFilesStore, mlPeopleStore } from 'utils/storage/mlStorage';
-import { getRenderableImage } from 'utils/file';
-import { imageBitmapToBlob } from 'utils/image';
-import { cached } from '@ente/shared/storage/cacheStorage/helpers';
-import mlIDbStorage from 'utils/storage/mlIDbStorage';
-import { Box, Point } from '../../../thirdparty/face-api/classes';
+import { addLogLine } from "@ente/shared/logging";
+import { CACHES } from "@ente/shared/storage/cacheStorage/constants";
+import { cached } from "@ente/shared/storage/cacheStorage/helpers";
+import { FILE_TYPE } from "constants/file";
+import { decodeLivePhoto } from "services/livePhotoService";
+import { getRenderableImage } from "utils/file";
+import { imageBitmapToBlob } from "utils/image";
+import mlIDbStorage from "utils/storage/mlIDbStorage";
+import { Box, Point } from "../../../thirdparty/face-api/classes";
import {
getArcfaceAlignment,
ibExtractFaceImage,
ibExtractFaceImages,
-} from './faceAlign';
+} from "./faceAlign";
import {
getFaceCropBlobFromStorage,
ibExtractFaceImagesFromCrops,
-} from './faceCrop';
-import { CACHES } from '@ente/shared/storage/cacheStorage/constants';
-import { FILE_TYPE } from 'constants/file';
-import { decodeLivePhoto } from 'services/livePhotoService';
-import { addLogLine } from '@ente/shared/logging';
+} from "./faceCrop";
export function f32Average(descriptors: Float32Array[]) {
if (descriptors.length < 1) {
- throw Error('f32Average: input size 0');
+ throw Error("f32Average: input size 0");
}
if (descriptors.length === 1) {
@@ -83,7 +83,7 @@ export function isTensor4D(tensor: any): tensor is tf.Tensor4D {
export function toTensor4D(
image: tf.Tensor3D | tf.Tensor4D,
- dtype?: tf.DataType
+ dtype?: tf.DataType,
) {
return tf.tidy(() => {
let reshapedImage: tf.Tensor4D;
@@ -92,7 +92,7 @@ export function toTensor4D(
} else if (isTensor4D(image)) {
reshapedImage = image;
} else {
- throw Error('toTensor4D only supports Tensor3D and Tensor4D input');
+ throw Error("toTensor4D only supports Tensor3D and Tensor4D input");
}
if (dtype) {
reshapedImage = tf.cast(reshapedImage, dtype);
@@ -112,10 +112,10 @@ export function imageBitmapsToTensor4D(imageBitmaps: Array<ImageBitmap>) {
export function extractFaces(
image: tf.Tensor3D | tf.Tensor4D,
facebBoxes: Array<Box>,
- faceSize: number
+ faceSize: number,
) {
return tf.tidy(() => {
- const reshapedImage = toTensor4D(image, 'float32');
+ const reshapedImage = toTensor4D(image, "float32");
const boxes = facebBoxes.map((box) => {
const normalized = box.rescale({
@@ -136,8 +136,8 @@ export function extractFaces(
const faceImagesTensor = tf.image.cropAndResize(
reshapedImage,
boxes,
- tf.fill([boxes.length], 0, 'int32'),
- [faceSize, faceSize]
+ tf.fill([boxes.length], 0, "int32"),
+ [faceSize, faceSize],
);
return faceImagesTensor;
@@ -152,7 +152,7 @@ export function newBoxFromPoints(
left: number,
top: number,
right: number,
- bottom: number
+ bottom: number,
) {
return new Box({ left, top, right, bottom });
}
@@ -162,7 +162,7 @@ export function normFaceBox(face: NormalizedFace) {
face.topLeft[0],
face.topLeft[1],
face.bottomRight[0],
- face.bottomRight[1]
+ face.bottomRight[1],
);
}
@@ -204,7 +204,7 @@ export function getAllFacesFromMap(allFacesMap: Map<number, Array<Face>>) {
}
export function getAllObjectsFromMap(
- allObjectsMap: Map<number, Array<RealWorldObject>>
+ allObjectsMap: Map<number, Array<RealWorldObject>>,
) {
return [...allObjectsMap.values()].flat();
}
@@ -218,7 +218,7 @@ export async function getFaceImage(
face: AlignedFace,
token: string,
faceSize: number = BLAZEFACE_FACE_SIZE,
- file?: EnteFile
+ file?: EnteFile,
): Promise<FaceImageBlob> {
if (!file) {
file = await getLocalFile(face.fileId);
@@ -228,7 +228,7 @@ export async function getFaceImage(
const faceImageBitmap = ibExtractFaceImage(
imageBitmap,
face.alignment,
- faceSize
+ faceSize,
);
const faceImage = imageBitmapToBlob(faceImageBitmap);
faceImageBitmap.close();
@@ -240,7 +240,7 @@ export async function getFaceImage(
export async function extractFaceImages(
faces: Array<AlignedFace>,
faceSize: number,
- image?: ImageBitmap
+ image?: ImageBitmap,
) {
if (faces.length === faces.filter((f) => f.crop).length) {
return ibExtractFaceImagesFromCrops(faces, faceSize);
@@ -249,7 +249,7 @@ export async function extractFaceImages(
return ibExtractFaceImages(image, faceAlignments, faceSize);
} else {
throw Error(
- 'Either face crops or image is required to extract face images'
+ "Either face crops or image is required to extract face images",
);
}
}
@@ -283,12 +283,12 @@ export function getFaceId(detectedFace: DetectedFace, imageDims: Dimensions) {
export function getObjectId(
detectedObject: DetectedObject,
- imageDims: Dimensions
+ imageDims: Dimensions,
) {
const imgDimPoint = new Point(imageDims.width, imageDims.height);
const objectCenterPoint = new Point(
detectedObject.detection.bbox[2] / 2,
- detectedObject.detection.bbox[3] / 2
+ detectedObject.detection.bbox[3] / 2,
);
const gridPt = objectCenterPoint
.mul(new Point(100, 100))
@@ -338,7 +338,7 @@ async function getOriginalConvertedFile(file: EnteFile, queue?: PQueue) {
const livePhoto = await decodeLivePhoto(file, fileBlob);
return await getRenderableImage(
livePhoto.imageNameTitle,
- new Blob([livePhoto.image])
+ new Blob([livePhoto.image]),
);
}
}
@@ -346,7 +346,7 @@ async function getOriginalConvertedFile(file: EnteFile, queue?: PQueue) {
export async function getOriginalImageBitmap(
file: EnteFile,
queue?: PQueue,
- useCache: boolean = false
+ useCache: boolean = false,
) {
let fileBlob;
@@ -357,21 +357,21 @@ export async function getOriginalImageBitmap(
} else {
fileBlob = await getOriginalConvertedFile(file, queue);
}
- addLogLine('[MLService] Got file: ', file.id.toString());
+ addLogLine("[MLService] Got file: ", file.id.toString());
return getImageBlobBitmap(fileBlob);
}
export async function getThumbnailImageBitmap(file: EnteFile) {
const thumb = await DownloadManager.getThumbnail(file);
- addLogLine('[MLService] Got thumbnail: ', file.id.toString());
+ addLogLine("[MLService] Got thumbnail: ", file.id.toString());
return getImageBlobBitmap(new Blob([thumb]));
}
export async function getLocalFileImageBitmap(
enteFile: EnteFile,
- localFile: globalThis.File
+ localFile: globalThis.File,
) {
let fileBlob = localFile as Blob;
fileBlob = await getRenderableImage(enteFile.metadata.title, fileBlob);
@@ -382,9 +382,9 @@ export async function getPeopleList(file: EnteFile): Promise<Array<Person>> {
let startTime = Date.now();
const mlFileData: MlFileData = await mlIDbStorage.getFile(file.id);
addLogLine(
- 'getPeopleList:mlFilesStore:getItem',
+ "getPeopleList:mlFilesStore:getItem",
Date.now() - startTime,
- 'ms'
+ "ms",
);
if (!mlFileData?.faces || mlFileData.faces.length < 1) {
return [];
@@ -399,13 +399,13 @@ export async function getPeopleList(file: EnteFile): Promise<Array<Person>> {
// addLogLine("peopleIds: ", peopleIds);
startTime = Date.now();
const peoplePromises = peopleIds.map(
- (p) => mlIDbStorage.getPerson(p) as Promise<Person>
+ (p) => mlIDbStorage.getPerson(p) as Promise<Person>,
);
const peopleList = await Promise.all(peoplePromises);
addLogLine(
- 'getPeopleList:mlPeopleStore:getItems',
+ "getPeopleList:mlPeopleStore:getItems",
Date.now() - startTime,
- 'ms'
+ "ms",
);
// addLogLine("peopleList: ", peopleList);
@@ -413,17 +413,17 @@ export async function getPeopleList(file: EnteFile): Promise<Array<Person>> {
}
export async function getUnidentifiedFaces(
- file: EnteFile
+ file: EnteFile,
): Promise<Array<Face>> {
const mlFileData: MlFileData = await mlIDbStorage.getFile(file.id);
return mlFileData?.faces?.filter(
- (f) => f.personId === null || f.personId === undefined
+ (f) => f.personId === null || f.personId === undefined,
);
}
export async function getFaceCropBlobs(
- faces: Array<Face>
+ faces: Array<Face>,
): Promise<Array<FaceImageBlob>> {
const faceCrops = faces
.map((f) => f.crop)
@@ -432,7 +432,7 @@ export async function getFaceCropBlobs(
return (
faceCrops &&
Promise.all(
- faceCrops.map((faceCrop) => getFaceCropBlobFromStorage(faceCrop))
+ faceCrops.map((faceCrop) => getFaceCropBlobFromStorage(faceCrop)),
)
);
}
@@ -450,7 +450,7 @@ export async function getAllPeople(limit: number = undefined) {
export function findFirstIfSorted<T>(
elements: Array<T>,
- comparator: (a: T, b: T) => number
+ comparator: (a: T, b: T) => number,
) {
if (!elements || elements.length < 1) {
return;
@@ -469,7 +469,7 @@ export function findFirstIfSorted<T>(
export function isDifferentOrOld(
method: Versioned<string>,
- thanMethod: Versioned<string>
+ thanMethod: Versioned<string>,
) {
return (
!method ||
@@ -496,14 +496,14 @@ export function areFaceIdsSame(ofFaces: Array<Face>, toFaces: Array<Face>) {
}
return primitiveArrayEquals(
ofFaces?.map((f) => f.id),
- toFaces?.map((f) => f.id)
+ toFaces?.map((f) => f.id),
);
}
export function getNearestPointIndex(
toPoint: Point,
fromPoints: Array<Point>,
- maxDistance?: number
+ maxDistance?: number,
) {
const dists = fromPoints.map((point, i) => ({
index: i,
@@ -512,7 +512,7 @@ export function getNearestPointIndex(
}));
const nearest = findFirstIfSorted(
dists,
- (a, b) => Math.abs(a.distance) - Math.abs(b.distance)
+ (a, b) => Math.abs(a.distance) - Math.abs(b.distance),
);
// addLogLine('Nearest dist: ', nearest.distance, maxDistance);
@@ -522,13 +522,13 @@ export function getNearestPointIndex(
}
export function logQueueStats(queue: PQueue, name: string) {
- queue.on('active', () =>
+ queue.on("active", () =>
addLogLine(
- `queuestats: ${name}: Active, Size: ${queue.size} Pending: ${queue.pending}`
- )
+ `queuestats: ${name}: Active, Size: ${queue.size} Pending: ${queue.pending}`,
+ ),
);
- queue.on('idle', () => addLogLine(`queuestats: ${name}: Idle`));
- queue.on('error', (error) =>
- console.error(`queuestats: ${name}: Error, `, error)
+ queue.on("idle", () => addLogLine(`queuestats: ${name}: Idle`));
+ queue.on("error", (error) =>
+ console.error(`queuestats: ${name}: Error, `, error),
);
}
diff --git a/apps/photos/src/utils/machineLearning/migrations.ts b/apps/photos/src/utils/machineLearning/migrations.ts
index af0629b6d7..111fabfc97 100644
--- a/apps/photos/src/utils/machineLearning/migrations.ts
+++ b/apps/photos/src/utils/machineLearning/migrations.ts
@@ -1,9 +1,9 @@
-import { MlFileData, Face } from 'types/machineLearning';
-import { addLogLine } from '@ente/shared/logging';
-import mlIDbStorage from 'utils/storage/mlIDbStorage';
-import { mlFilesStore } from 'utils/storage/mlStorage';
-import { getFaceId } from '.';
-import { storeFaceCropForBlob } from './faceCrop';
+import { addLogLine } from "@ente/shared/logging";
+import { Face, MlFileData } from "types/machineLearning";
+import mlIDbStorage from "utils/storage/mlIDbStorage";
+import { mlFilesStore } from "utils/storage/mlStorage";
+import { getFaceId } from ".";
+import { storeFaceCropForBlob } from "./faceCrop";
// TODO: for migrating existing data, to be removed
export async function migrateExistingFiles() {
@@ -14,14 +14,14 @@ export async function migrateExistingFiles() {
existingFiles.push(mlFileData);
}
});
- addLogLine('existing files: ', existingFiles.length);
+ addLogLine("existing files: ", existingFiles.length);
try {
for (const file of existingFiles) {
await mlIDbStorage.putFile(file);
}
- await mlIDbStorage.setIndexVersion('files', 1);
- addLogLine('migrateExistingFiles done');
+ await mlIDbStorage.setIndexVersion("files", 1);
+ addLogLine("migrateExistingFiles done");
} catch (e) {
console.error(e);
}
@@ -29,25 +29,25 @@ export async function migrateExistingFiles() {
export async function migrateFaceCropsToCache() {
const startTime = Date.now();
- addLogLine('migrateFaceCropsToCache started');
+ addLogLine("migrateFaceCropsToCache started");
const allFiles = await mlIDbStorage.getAllFiles();
const allFilesWithFaces = allFiles.filter(
- (f) => f.faces && f.faces.length > 0
+ (f) => f.faces && f.faces.length > 0,
);
const updatedFacesMap = new Map<number, Array<Face>>();
for (const file of allFilesWithFaces) {
let updated = false;
for (const face of file.faces) {
- if (!face['id']) {
- const faceCropBlob = face.crop['image'];
+ if (!face["id"]) {
+ const faceCropBlob = face.crop["image"];
const faceId = getFaceId(face, file.imageDimensions);
face.crop = await storeFaceCropForBlob(
faceId,
face.crop.imageBox,
- faceCropBlob
+ faceCropBlob,
);
- face['id'] = faceId;
+ face["id"] = faceId;
updated = true;
}
}
@@ -57,21 +57,21 @@ export async function migrateFaceCropsToCache() {
}
if (updatedFacesMap.size > 0) {
- addLogLine('updating face crops: ', updatedFacesMap.size);
+ addLogLine("updating face crops: ", updatedFacesMap.size);
await mlIDbStorage.updateFaces(updatedFacesMap);
} else {
- addLogLine('not updating face crops: ', updatedFacesMap.size);
+ addLogLine("not updating face crops: ", updatedFacesMap.size);
}
- addLogLine('migrateFaceCropsToCache', Date.now() - startTime, 'ms');
+ addLogLine("migrateFaceCropsToCache", Date.now() - startTime, "ms");
}
export async function migrateFaceInterfaceUpdate() {
const startTime = Date.now();
- addLogLine('migrateFaceInterfaceUpdate started');
+ addLogLine("migrateFaceInterfaceUpdate started");
- const faceSchemaVersion = await mlIDbStorage.getIndexVersion('faceSchema');
+ const faceSchemaVersion = await mlIDbStorage.getIndexVersion("faceSchema");
if (faceSchemaVersion) {
- addLogLine('not running migrateFaceInterfaceUpdate');
+ addLogLine("not running migrateFaceInterfaceUpdate");
return;
}
@@ -80,20 +80,20 @@ export async function migrateFaceInterfaceUpdate() {
const updatedFiles = allFiles.map((file) => {
const updatedFaces = file.faces?.map((f) => {
const updatedFace = {
- id: f['faceId'],
+ id: f["faceId"],
fileId: f.fileId,
detection: {
- box: f['box'],
- landmarks: f['landmarks'],
- probability: f['probability'],
+ box: f["box"],
+ landmarks: f["landmarks"],
+ probability: f["probability"],
},
- crop: f['faceCrop'],
+ crop: f["faceCrop"],
alignment: {
- affineMatrix: f['affineMatrix'],
- center: f['center'],
- rotation: f['rotation'],
- size: f['size'],
+ affineMatrix: f["affineMatrix"],
+ center: f["center"],
+ rotation: f["rotation"],
+ size: f["size"],
},
embedding: Float32Array.from(f.embedding),
@@ -107,13 +107,13 @@ export async function migrateFaceInterfaceUpdate() {
const updated: MlFileData = {
fileId: file.fileId,
- faceDetectionMethod: file['detectionMethod'],
+ faceDetectionMethod: file["detectionMethod"],
faceCropMethod: {
- value: 'ArcFace',
+ value: "ArcFace",
version: 1,
},
- faceAlignmentMethod: file['alignmentMethod'],
- faceEmbeddingMethod: file['embeddingMethod'],
+ faceAlignmentMethod: file["alignmentMethod"],
+ faceEmbeddingMethod: file["embeddingMethod"],
faces: updatedFaces,
@@ -127,10 +127,10 @@ export async function migrateFaceInterfaceUpdate() {
return updated;
});
- addLogLine('migrateFaceInterfaceUpdate updating: ', updatedFiles.length);
+ addLogLine("migrateFaceInterfaceUpdate updating: ", updatedFiles.length);
await mlIDbStorage.putAllFilesInTx(updatedFiles);
- await mlIDbStorage.setIndexVersion('faceSchema', 1);
- addLogLine('migrateFaceInterfaceUpdate done');
- addLogLine('migrateFaceInterfaceUpdate', Date.now() - startTime, 'ms');
+ await mlIDbStorage.setIndexVersion("faceSchema", 1);
+ addLogLine("migrateFaceInterfaceUpdate done");
+ addLogLine("migrateFaceInterfaceUpdate", Date.now() - startTime, "ms");
}
diff --git a/apps/photos/src/utils/machineLearning/mldataExport.ts b/apps/photos/src/utils/machineLearning/mldataExport.ts
index ee9e6db503..4cd115e12a 100644
--- a/apps/photos/src/utils/machineLearning/mldataExport.ts
+++ b/apps/photos/src/utils/machineLearning/mldataExport.ts
@@ -1,9 +1,9 @@
-import { MlFileData } from 'types/machineLearning';
-import mlIDbStorage from 'utils/storage/mlIDbStorage';
-import * as zip from '@zip.js/zip.js';
-import { CACHES } from '@ente/shared/storage/cacheStorage/constants';
-import { CacheStorageService } from '@ente/shared/storage/cacheStorage';
-import { addLogLine } from '@ente/shared/logging';
+import { addLogLine } from "@ente/shared/logging";
+import { CacheStorageService } from "@ente/shared/storage/cacheStorage";
+import { CACHES } from "@ente/shared/storage/cacheStorage/constants";
+import * as zip from "@zip.js/zip.js";
+import { MlFileData } from "types/machineLearning";
+import mlIDbStorage from "utils/storage/mlIDbStorage";
class FileSystemWriter extends zip.Writer {
writableStream: FileSystemWritableFileStream;
@@ -38,7 +38,7 @@ class FileReader extends zip.Reader {
public async readUint8Array(
index: number,
- length: number
+ length: number,
): Promise<Uint8Array> {
// addLogLine('zipReader needs data: ', index, length);
const slicedFile = this.file.slice(index, index + length);
@@ -49,10 +49,10 @@ class FileReader extends zip.Reader {
}
export async function exportMlData(
- mlDataZipWritable: FileSystemWritableFileStream
+ mlDataZipWritable: FileSystemWritableFileStream,
) {
const zipWriter = new zip.ZipWriter(
- new FileSystemWriter(mlDataZipWritable)
+ new FileSystemWriter(mlDataZipWritable),
);
try {
@@ -67,7 +67,7 @@ export async function exportMlData(
}
await mlDataZipWritable.close();
- addLogLine('Ml Data Exported');
+ addLogLine("Ml Data Exported");
}
async function exportMlDataToZipWriter(zipWriter: zip.ZipWriter) {
@@ -76,25 +76,25 @@ async function exportMlDataToZipWriter(zipWriter: zip.ZipWriter) {
mlDbData?.library?.data?.faceClusteringResults;
faceClusteringResults && (faceClusteringResults.debugInfo = undefined);
addLogLine(
- 'Exporting ML DB data: ',
+ "Exporting ML DB data: ",
JSON.stringify(Object.keys(mlDbData)),
JSON.stringify(
- Object.keys(mlDbData)?.map((k) => Object.keys(mlDbData[k])?.length)
- )
+ Object.keys(mlDbData)?.map((k) => Object.keys(mlDbData[k])?.length),
+ ),
);
await zipWriter.add(
- 'indexeddb/mldata.json',
- new zip.TextReader(JSON.stringify(mlDbData))
+ "indexeddb/mldata.json",
+ new zip.TextReader(JSON.stringify(mlDbData)),
);
const faceCropCache = await CacheStorageService.open(CACHES.FACE_CROPS);
const files =
- mlDbData['files'] && (Object.values(mlDbData['files']) as MlFileData[]);
+ mlDbData["files"] && (Object.values(mlDbData["files"]) as MlFileData[]);
for (const fileData of files || []) {
for (const face of fileData.faces || []) {
const faceCropUrl = face.crop?.imageUrl;
if (!faceCropUrl) {
- console.error('face crop not found for faceId: ', face.id);
+ console.error("face crop not found for faceId: ", face.id);
continue;
}
const response = await faceCropCache.match(faceCropUrl);
@@ -103,12 +103,12 @@ async function exportMlDataToZipWriter(zipWriter: zip.ZipWriter) {
await zipWriter.add(
`caches/${CACHES.FACE_CROPS}${faceCropUrl}`,
new zip.BlobReader(blob),
- { level: 0 }
+ { level: 0 },
);
} else {
console.error(
- 'face crop cache entry not found for faceCropUrl: ',
- faceCropUrl
+ "face crop cache entry not found for faceCropUrl: ",
+ faceCropUrl,
);
}
}
@@ -123,7 +123,7 @@ export async function importMlData(mlDataZipFile: File) {
await zipReader.close();
}
- addLogLine('ML Data Imported');
+ addLogLine("ML Data Imported");
}
async function importMlDataFromZipReader(zipReader: zip.ZipReader) {
@@ -134,28 +134,28 @@ async function importMlDataFromZipReader(zipReader: zip.ZipReader) {
const faceCropCache = await CacheStorageService.open(CACHES.FACE_CROPS);
let mldataEntry;
for (const entry of zipEntries) {
- if (entry.filename === 'indexeddb/mldata.json') {
+ if (entry.filename === "indexeddb/mldata.json") {
mldataEntry = entry;
} else if (entry.filename.startsWith(faceCropPath)) {
const faceCropUrl = entry.filename.substring(faceCropPath.length);
// addLogLine('importing faceCropUrl: ', faceCropUrl);
const faceCropCacheBlob: Blob = await entry.getData(
- new zip.BlobWriter('image/jpeg')
+ new zip.BlobWriter("image/jpeg"),
);
faceCropCache.put(faceCropUrl, new Response(faceCropCacheBlob));
}
}
const mlDataJsonStr: string = await mldataEntry.getData(
- new zip.TextWriter()
+ new zip.TextWriter(),
);
const mlDbData = JSON.parse(mlDataJsonStr);
addLogLine(
- 'importing ML DB data: ',
+ "importing ML DB data: ",
JSON.stringify(Object.keys(mlDbData)),
JSON.stringify(
- Object.keys(mlDbData)?.map((k) => Object.keys(mlDbData[k])?.length)
- )
+ Object.keys(mlDbData)?.map((k) => Object.keys(mlDbData[k])?.length),
+ ),
);
await mlIDbStorage.putAllMLData(mlDbData);
}
diff --git a/apps/photos/src/utils/machineLearning/transform.ts b/apps/photos/src/utils/machineLearning/transform.ts
index 218cfb8dba..9e900bbe01 100644
--- a/apps/photos/src/utils/machineLearning/transform.ts
+++ b/apps/photos/src/utils/machineLearning/transform.ts
@@ -1,18 +1,18 @@
-import { Box, Point } from '../../../thirdparty/face-api/classes';
-import { newBoxFromPoints } from '.';
+import { newBoxFromPoints } from ".";
+import { Box, Point } from "../../../thirdparty/face-api/classes";
import {
- scale,
- translate,
- compose,
Matrix,
applyToPoint,
-} from 'transformation-matrix';
+ compose,
+ scale,
+ translate,
+} from "transformation-matrix";
export function computeTransformToBox(inBox: Box, toBox: Box): Matrix {
return compose(
translate(toBox.x, toBox.y),
- scale(toBox.width / inBox.width, toBox.height / inBox.height)
+ scale(toBox.width / inBox.width, toBox.height / inBox.height),
);
}
diff --git a/apps/photos/src/utils/magicMetadata/index.ts b/apps/photos/src/utils/magicMetadata/index.ts
index 7ed18f1c00..cce41791e2 100644
--- a/apps/photos/src/utils/magicMetadata/index.ts
+++ b/apps/photos/src/utils/magicMetadata/index.ts
@@ -1,7 +1,7 @@
-import { Collection } from 'types/collection';
-import { EnteFile } from 'types/file';
-import { MagicMetadataCore, VISIBILITY_STATE } from 'types/magicMetadata';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { Collection } from "types/collection";
+import { EnteFile } from "types/file";
+import { MagicMetadataCore, VISIBILITY_STATE } from "types/magicMetadata";
export function isArchivedFile(item: EnteFile): boolean {
if (!item || !item.magicMetadata || !item.magicMetadata.data) {
@@ -33,8 +33,8 @@ export function isPinnedCollection(item: Collection) {
!item ||
!item.magicMetadata ||
!item.magicMetadata.data ||
- typeof item.magicMetadata.data === 'string' ||
- typeof item.magicMetadata.data.order === 'undefined'
+ typeof item.magicMetadata.data === "string" ||
+ typeof item.magicMetadata.data.order === "undefined"
) {
return false;
}
@@ -44,7 +44,7 @@ export function isPinnedCollection(item: Collection) {
export async function updateMagicMetadata<T>(
magicMetadataUpdates: T,
originalMagicMetadata?: MagicMetadataCore<T>,
- decryptionKey?: string
+ decryptionKey?: string,
): Promise<MagicMetadataCore<T>> {
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
@@ -52,11 +52,11 @@ export async function updateMagicMetadata<T>(
originalMagicMetadata = getNewMagicMetadata<T>();
}
- if (typeof originalMagicMetadata?.data === 'string') {
+ if (typeof originalMagicMetadata?.data === "string") {
originalMagicMetadata.data = await cryptoWorker.decryptMetadata(
originalMagicMetadata.data,
originalMagicMetadata.header,
- decryptionKey
+ decryptionKey,
);
}
// copies the existing magic metadata properties of the files and updates the visibility value
@@ -91,7 +91,7 @@ export const getNonEmptyMagicMetadataProps = <T>(magicMetadataProps: T): T => {
return Object.fromEntries(
Object.entries(magicMetadataProps).filter(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
- ([_, v]) => v !== null && v !== undefined
- )
+ ([_, v]) => v !== null && v !== undefined,
+ ),
) as T;
};
diff --git a/apps/photos/src/utils/network/index.ts b/apps/photos/src/utils/network/index.ts
index 832aa841dc..244924c495 100644
--- a/apps/photos/src/utils/network/index.ts
+++ b/apps/photos/src/utils/network/index.ts
@@ -1,10 +1,10 @@
-import { sleep } from 'utils/common';
+import { sleep } from "utils/common";
const waitTimeBeforeNextAttemptInMilliSeconds = [2000, 5000, 10000];
export async function retryAsyncFunction<T>(
request: (abort?: () => void) => Promise<T>,
- waitTimeBeforeNextTry?: number[]
+ waitTimeBeforeNextTry?: number[],
): Promise<T> {
if (!waitTimeBeforeNextTry) {
waitTimeBeforeNextTry = waitTimeBeforeNextAttemptInMilliSeconds;
diff --git a/apps/photos/src/utils/number/format.ts b/apps/photos/src/utils/number/format.ts
index 568a4d6987..0b92ea9777 100644
--- a/apps/photos/src/utils/number/format.ts
+++ b/apps/photos/src/utils/number/format.ts
@@ -1,4 +1,4 @@
-import i18n from 'i18next';
+import i18n from "i18next";
const numberFormatter = new Intl.NumberFormat(i18n.language);
diff --git a/apps/photos/src/utils/photoFrame/index.ts b/apps/photos/src/utils/photoFrame/index.ts
index 57144f523d..6e59524c51 100644
--- a/apps/photos/src/utils/photoFrame/index.ts
+++ b/apps/photos/src/utils/photoFrame/index.ts
@@ -1,7 +1,7 @@
-import { FILE_TYPE } from 'constants/file';
-import { EnteFile } from 'types/file';
-import { logError } from '@ente/shared/sentry';
-import { LivePhotoSourceURL, SourceURLs } from 'services/download';
+import { logError } from "@ente/shared/sentry";
+import { FILE_TYPE } from "constants/file";
+import { LivePhotoSourceURL, SourceURLs } from "services/download";
+import { EnteFile } from "types/file";
const WAIT_FOR_VIDEO_PLAYBACK = 1 * 1000;
@@ -11,8 +11,8 @@ export async function isPlaybackPossible(url: string): Promise<boolean> {
resolve(false);
}, WAIT_FOR_VIDEO_PLAYBACK);
- const video = document.createElement('video');
- video.addEventListener('canplay', function () {
+ const video = document.createElement("video");
+ video.addEventListener("canplay", function () {
clearTimeout(t);
video.remove(); // Clean up the video element
// also check for duration > 0 to make sure it is not a broken video
@@ -22,7 +22,7 @@ export async function isPlaybackPossible(url: string): Promise<boolean> {
resolve(false);
}
});
- video.addEventListener('error', function () {
+ video.addEventListener("error", function () {
clearTimeout(t);
video.remove();
resolve(false);
@@ -72,14 +72,14 @@ export function updateFileMsrcProps(file: EnteFile, url: string) {
export async function updateFileSrcProps(
file: EnteFile,
srcURLs: SourceURLs,
- enableDownload: boolean
+ enableDownload: boolean,
) {
const { url, isRenderable, isOriginal } = srcURLs;
file.w = window.innerWidth;
file.h = window.innerHeight;
file.isSourceLoaded =
file.metadata.fileType === FILE_TYPE.LIVE_PHOTO
- ? srcURLs.type === 'livePhoto'
+ ? srcURLs.type === "livePhoto"
: true;
file.isConverted = !isOriginal;
file.conversionFailed = !isRenderable;
@@ -99,7 +99,7 @@ export async function updateFileSrcProps(
</video>
`;
} else if (file.metadata.fileType === FILE_TYPE.LIVE_PHOTO) {
- if (srcURLs.type === 'normal') {
+ if (srcURLs.type === "normal") {
file.html = `
<div class = 'pswp-item-container'>
<img id = "live-photo-image-${file.id}" src="${url}" onContextMenu="return false;"/>
@@ -124,7 +124,7 @@ export async function updateFileSrcProps(
} else {
logError(
Error(`unknown file type - ${file.metadata.fileType}`),
- 'Unknown file type'
+ "Unknown file type",
);
file.src = url as string;
}
diff --git a/apps/photos/src/utils/publicCollectionGallery/index.ts b/apps/photos/src/utils/publicCollectionGallery/index.ts
index e9d08bbc4e..c038aabb74 100644
--- a/apps/photos/src/utils/publicCollectionGallery/index.ts
+++ b/apps/photos/src/utils/publicCollectionGallery/index.ts
@@ -1,5 +1,5 @@
-import { createContext } from 'react';
-import { PublicCollectionGalleryContextType } from 'types/publicCollection';
+import { createContext } from "react";
+import { PublicCollectionGalleryContextType } from "types/publicCollection";
const defaultPublicCollectionGalleryContext: PublicCollectionGalleryContextType =
{
@@ -13,5 +13,5 @@ const defaultPublicCollectionGalleryContext: PublicCollectionGalleryContextType
export const PublicCollectionGalleryContext =
createContext<PublicCollectionGalleryContextType>(
- defaultPublicCollectionGalleryContext
+ defaultPublicCollectionGalleryContext,
);
diff --git a/apps/photos/src/utils/search/index.ts b/apps/photos/src/utils/search/index.ts
index 6392e48404..392211ca3e 100644
--- a/apps/photos/src/utils/search/index.ts
+++ b/apps/photos/src/utils/search/index.ts
@@ -1,4 +1,4 @@
-import { DateValue } from 'types/search';
+import { DateValue } from "types/search";
export const isSameDayAnyYear =
(baseDate: DateValue) => (compareDate: Date) => {
@@ -19,10 +19,10 @@ export const isSameDayAnyYear =
export function getFormattedDate(date: DateValue) {
const options = {};
- date.date && (options['day'] = 'numeric');
- (date.month || date.month === 0) && (options['month'] = 'long');
- date.year && (options['year'] = 'numeric');
- return new Intl.DateTimeFormat('en-IN', options).format(
- new Date(date.year ?? 1, date.month ?? 1, date.date ?? 1)
+ date.date && (options["day"] = "numeric");
+ (date.month || date.month === 0) && (options["month"] = "long");
+ date.year && (options["year"] = "numeric");
+ return new Intl.DateTimeFormat("en-IN", options).format(
+ new Date(date.year ?? 1, date.month ?? 1, date.date ?? 1),
);
}
diff --git a/apps/photos/src/utils/storage/mlIDbStorage.ts b/apps/photos/src/utils/storage/mlIDbStorage.ts
index 74a0afcdb4..7ee4a5fcf4 100644
--- a/apps/photos/src/utils/storage/mlIDbStorage.ts
+++ b/apps/photos/src/utils/storage/mlIDbStorage.ts
@@ -1,37 +1,37 @@
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
import {
DEFAULT_ML_SEARCH_CONFIG,
DEFAULT_ML_SYNC_CONFIG,
DEFAULT_ML_SYNC_JOB_CONFIG,
MAX_ML_SYNC_ERROR_COUNT,
-} from 'constants/mlConfig';
+} from "constants/mlConfig";
import {
- openDB,
- deleteDB,
DBSchema,
IDBPDatabase,
IDBPTransaction,
StoreNames,
-} from 'idb';
+ deleteDB,
+ openDB,
+} from "idb";
import {
Face,
- MlFileData,
MLLibraryData,
+ MlFileData,
Person,
RealWorldObject,
Thing,
-} from 'types/machineLearning';
-import { IndexStatus } from 'types/machineLearning/ui';
-import { runningInBrowser, runningInElectron } from 'utils/common';
-import { addLogLine } from '@ente/shared/logging';
-import { logError } from '@ente/shared/sentry';
+} from "types/machineLearning";
+import { IndexStatus } from "types/machineLearning/ui";
+import { runningInBrowser, runningInElectron } from "utils/common";
interface Config {}
-export const ML_SYNC_JOB_CONFIG_NAME = 'ml-sync-job';
-export const ML_SYNC_CONFIG_NAME = 'ml-sync';
-export const ML_SEARCH_CONFIG_NAME = 'ml-search';
+export const ML_SYNC_JOB_CONFIG_NAME = "ml-sync-job";
+export const ML_SYNC_CONFIG_NAME = "ml-sync";
+export const ML_SEARCH_CONFIG_NAME = "ml-search";
-const MLDATA_DB_NAME = 'mldata';
+const MLDATA_DB_NAME = "mldata";
interface MLDb extends DBSchema {
files: {
key: number;
@@ -74,65 +74,65 @@ class MLIDbStorage {
private openDB(): Promise<IDBPDatabase<MLDb>> {
return openDB<MLDb>(MLDATA_DB_NAME, 3, {
terminated: async () => {
- console.error('ML Indexed DB terminated');
- logError(new Error(), 'ML Indexed DB terminated');
+ console.error("ML Indexed DB terminated");
+ logError(new Error(), "ML Indexed DB terminated");
this._db = undefined;
// TODO: remove if there is chance of this going into recursion in some case
await this.db;
},
blocked() {
// TODO: make sure we dont allow multiple tabs of app
- console.error('ML Indexed DB blocked');
- logError(new Error(), 'ML Indexed DB blocked');
+ console.error("ML Indexed DB blocked");
+ logError(new Error(), "ML Indexed DB blocked");
},
blocking() {
// TODO: make sure we dont allow multiple tabs of app
- console.error('ML Indexed DB blocking');
- logError(new Error(), 'ML Indexed DB blocking');
+ console.error("ML Indexed DB blocking");
+ logError(new Error(), "ML Indexed DB blocking");
},
async upgrade(db, oldVersion, newVersion, tx) {
if (oldVersion < 1) {
- const filesStore = db.createObjectStore('files', {
- keyPath: 'fileId',
+ const filesStore = db.createObjectStore("files", {
+ keyPath: "fileId",
});
- filesStore.createIndex('mlVersion', [
- 'mlVersion',
- 'errorCount',
+ filesStore.createIndex("mlVersion", [
+ "mlVersion",
+ "errorCount",
]);
- db.createObjectStore('people', {
- keyPath: 'id',
+ db.createObjectStore("people", {
+ keyPath: "id",
});
- db.createObjectStore('things', {
- keyPath: 'id',
+ db.createObjectStore("things", {
+ keyPath: "id",
});
- db.createObjectStore('versions');
+ db.createObjectStore("versions");
- db.createObjectStore('library');
+ db.createObjectStore("library");
}
if (oldVersion < 2) {
// TODO: update configs if version is updated in defaults
- db.createObjectStore('configs');
+ db.createObjectStore("configs");
await tx
- .objectStore('configs')
+ .objectStore("configs")
.add(
DEFAULT_ML_SYNC_JOB_CONFIG,
- ML_SYNC_JOB_CONFIG_NAME
+ ML_SYNC_JOB_CONFIG_NAME,
);
await tx
- .objectStore('configs')
+ .objectStore("configs")
.add(DEFAULT_ML_SYNC_CONFIG, ML_SYNC_CONFIG_NAME);
}
if (oldVersion < 3) {
await tx
- .objectStore('configs')
+ .objectStore("configs")
.add(DEFAULT_ML_SEARCH_CONFIG, ML_SEARCH_CONFIG_NAME);
}
addLogLine(
- `Ml DB upgraded to version: ${newVersion} from version: ${oldVersion}`
+ `Ml DB upgraded to version: ${newVersion} from version: ${oldVersion}`,
);
},
});
@@ -141,7 +141,7 @@ class MLIDbStorage {
public get db(): Promise<IDBPDatabase<MLDb>> {
if (!this._db) {
this._db = this.openDB();
- addLogLine('Opening Ml DB');
+ addLogLine("Opening Ml DB");
}
return this._db;
@@ -151,26 +151,26 @@ class MLIDbStorage {
const db = await this.db;
db.close();
await deleteDB(MLDATA_DB_NAME);
- addLogLine('Cleared Ml DB');
+ addLogLine("Cleared Ml DB");
this._db = undefined;
await this.db;
}
public async getAllFileIds() {
const db = await this.db;
- return db.getAllKeys('files');
+ return db.getAllKeys("files");
}
public async putAllFilesInTx(mlFiles: Array<MlFileData>) {
const db = await this.db;
- const tx = db.transaction('files', 'readwrite');
+ const tx = db.transaction("files", "readwrite");
await Promise.all(mlFiles.map((mlFile) => tx.store.put(mlFile)));
await tx.done;
}
public async removeAllFilesInTx(fileIds: Array<number>) {
const db = await this.db;
- const tx = db.transaction('files', 'readwrite');
+ const tx = db.transaction("files", "readwrite");
await Promise.all(fileIds.map((fileId) => tx.store.delete(fileId)));
await tx.done;
@@ -178,7 +178,7 @@ class MLIDbStorage {
public async newTransaction<
Name extends StoreNames<MLDb>,
- Mode extends IDBTransactionMode = 'readonly',
+ Mode extends IDBTransactionMode = "readonly",
>(storeNames: Name, mode?: Mode) {
const db = await this.db;
return db.transaction(storeNames, mode);
@@ -189,7 +189,7 @@ class MLIDbStorage {
}
public async getAllFileIdsForUpdate(
- tx: IDBPTransaction<MLDb, ['files'], 'readwrite'>
+ tx: IDBPTransaction<MLDb, ["files"], "readwrite">,
) {
return tx.store.getAllKeys();
}
@@ -197,13 +197,13 @@ class MLIDbStorage {
public async getFileIds(
count: number,
limitMlVersion: number,
- maxErrorCount: number
+ maxErrorCount: number,
) {
const db = await this.db;
- const tx = db.transaction('files', 'readonly');
- const index = tx.store.index('mlVersion');
+ const tx = db.transaction("files", "readonly");
+ const index = tx.store.index("mlVersion");
let cursor = await index.openKeyCursor(
- IDBKeyRange.upperBound([limitMlVersion], true)
+ IDBKeyRange.upperBound([limitMlVersion], true),
);
const fileIds: number[] = [];
@@ -223,25 +223,25 @@ class MLIDbStorage {
public async getFile(fileId: number) {
const db = await this.db;
- return db.get('files', fileId);
+ return db.get("files", fileId);
}
public async getAllFiles() {
const db = await this.db;
- return db.getAll('files');
+ return db.getAll("files");
}
public async putFile(mlFile: MlFileData) {
const db = await this.db;
- return db.put('files', mlFile);
+ return db.put("files", mlFile);
}
public async upsertFileInTx(
fileId: number,
- upsert: (mlFile: MlFileData) => MlFileData
+ upsert: (mlFile: MlFileData) => MlFileData,
) {
const db = await this.db;
- const tx = db.transaction('files', 'readwrite');
+ const tx = db.transaction("files", "readwrite");
const existing = await tx.store.get(fileId);
const updated = upsert(existing);
await tx.store.put(updated);
@@ -252,14 +252,14 @@ class MLIDbStorage {
public async putAllFiles(
mlFiles: Array<MlFileData>,
- tx: IDBPTransaction<MLDb, ['files'], 'readwrite'>
+ tx: IDBPTransaction<MLDb, ["files"], "readwrite">,
) {
await Promise.all(mlFiles.map((mlFile) => tx.store.put(mlFile)));
}
public async removeAllFiles(
fileIds: Array<number>,
- tx: IDBPTransaction<MLDb, ['files'], 'readwrite'>
+ tx: IDBPTransaction<MLDb, ["files"], "readwrite">,
) {
await Promise.all(fileIds.map((fileId) => tx.store.delete(fileId)));
}
@@ -273,14 +273,14 @@ class MLIDbStorage {
public async getAllFacesMap() {
const startTime = Date.now();
const db = await this.db;
- const allFiles = await db.getAll('files');
+ const allFiles = await db.getAll("files");
const allFacesMap = new Map<number, Array<Face>>();
allFiles.forEach(
(mlFileData) =>
mlFileData.faces &&
- allFacesMap.set(mlFileData.fileId, mlFileData.faces)
+ allFacesMap.set(mlFileData.fileId, mlFileData.faces),
);
- addLogLine('getAllFacesMap', Date.now() - startTime, 'ms');
+ addLogLine("getAllFacesMap", Date.now() - startTime, "ms");
return allFacesMap;
}
@@ -288,7 +288,7 @@ class MLIDbStorage {
public async updateFaces(allFacesMap: Map<number, Face[]>) {
const startTime = Date.now();
const db = await this.db;
- const tx = db.transaction('files', 'readwrite');
+ const tx = db.transaction("files", "readwrite");
let cursor = await tx.store.openCursor();
while (cursor) {
if (allFacesMap.has(cursor.key)) {
@@ -299,72 +299,72 @@ class MLIDbStorage {
cursor = await cursor.continue();
}
await tx.done;
- addLogLine('updateFaces', Date.now() - startTime, 'ms');
+ addLogLine("updateFaces", Date.now() - startTime, "ms");
}
public async getAllObjectsMap() {
const startTime = Date.now();
const db = await this.db;
- const allFiles = await db.getAll('files');
+ const allFiles = await db.getAll("files");
const allObjectsMap = new Map<number, Array<RealWorldObject>>();
allFiles.forEach(
(mlFileData) =>
mlFileData.objects &&
- allObjectsMap.set(mlFileData.fileId, mlFileData.objects)
+ allObjectsMap.set(mlFileData.fileId, mlFileData.objects),
);
- addLogLine('allObjectsMap', Date.now() - startTime, 'ms');
+ addLogLine("allObjectsMap", Date.now() - startTime, "ms");
return allObjectsMap;
}
public async getPerson(id: number) {
const db = await this.db;
- return db.get('people', id);
+ return db.get("people", id);
}
public async getAllPeople() {
const db = await this.db;
- return db.getAll('people');
+ return db.getAll("people");
}
public async putPerson(person: Person) {
const db = await this.db;
- return db.put('people', person);
+ return db.put("people", person);
}
public async clearAllPeople() {
const db = await this.db;
- return db.clear('people');
+ return db.clear("people");
}
public async getAllThings() {
const db = await this.db;
- return db.getAll('things');
+ return db.getAll("things");
}
public async putThing(thing: Thing) {
const db = await this.db;
- return db.put('things', thing);
+ return db.put("things", thing);
}
public async clearAllThings() {
const db = await this.db;
- return db.clear('things');
+ return db.clear("things");
}
public async getIndexVersion(index: string) {
const db = await this.db;
- return db.get('versions', index);
+ return db.get("versions", index);
}
public async incrementIndexVersion(index: StoreNames<MLDb>) {
- if (index === 'versions') {
- throw new Error('versions store can not be versioned');
+ if (index === "versions") {
+ throw new Error("versions store can not be versioned");
}
const db = await this.db;
- const tx = db.transaction(['versions', index], 'readwrite');
- let version = await tx.objectStore('versions').get(index);
+ const tx = db.transaction(["versions", index], "readwrite");
+ let version = await tx.objectStore("versions").get(index);
version = (version || 0) + 1;
- tx.objectStore('versions').put(version, index);
+ tx.objectStore("versions").put(version, index);
await tx.done;
return version;
@@ -372,22 +372,22 @@ class MLIDbStorage {
public async setIndexVersion(index: string, version: number) {
const db = await this.db;
- return db.put('versions', version, index);
+ return db.put("versions", version, index);
}
public async getLibraryData() {
const db = await this.db;
- return db.get('library', 'data');
+ return db.get("library", "data");
}
public async putLibraryData(data: MLLibraryData) {
const db = await this.db;
- return db.put('library', data, 'data');
+ return db.put("library", data, "data");
}
public async getConfig<T extends Config>(name: string, def: T) {
const db = await this.db;
- const tx = db.transaction('configs', 'readwrite');
+ const tx = db.transaction("configs", "readwrite");
let config = (await tx.store.get(name)) as T;
if (!config) {
config = def;
@@ -400,16 +400,16 @@ class MLIDbStorage {
public async putConfig(name: string, data: Config) {
const db = await this.db;
- return db.put('configs', data, name);
+ return db.put("configs", data, name);
}
public async getIndexStatus(latestMlVersion: number): Promise<IndexStatus> {
const db = await this.db;
- const tx = db.transaction(['files', 'versions'], 'readonly');
- const mlVersionIdx = tx.objectStore('files').index('mlVersion');
+ const tx = db.transaction(["files", "versions"], "readonly");
+ const mlVersionIdx = tx.objectStore("files").index("mlVersion");
let outOfSyncCursor = await mlVersionIdx.openKeyCursor(
- IDBKeyRange.upperBound([latestMlVersion], true)
+ IDBKeyRange.upperBound([latestMlVersion], true),
);
let outOfSyncFilesExists = false;
while (outOfSyncCursor && !outOfSyncFilesExists) {
@@ -423,14 +423,14 @@ class MLIDbStorage {
}
const nSyncedFiles = await mlVersionIdx.count(
- IDBKeyRange.lowerBound([latestMlVersion])
+ IDBKeyRange.lowerBound([latestMlVersion]),
);
const nTotalFiles = await mlVersionIdx.count();
- const filesIndexVersion = await tx.objectStore('versions').get('files');
+ const filesIndexVersion = await tx.objectStore("versions").get("files");
const peopleIndexVersion = await tx
- .objectStore('versions')
- .get('people');
+ .objectStore("versions")
+ .get("people");
const filesIndexVersionExists =
filesIndexVersion !== null && filesIndexVersion !== undefined;
const peopleIndexVersionExists =
@@ -452,7 +452,7 @@ class MLIDbStorage {
// for debug purpose
public async getAllMLData() {
const db = await this.db;
- const tx = db.transaction(db.objectStoreNames, 'readonly');
+ const tx = db.transaction(db.objectStoreNames, "readonly");
const allMLData: any = {};
for (const store of tx.objectStoreNames) {
const keys = await tx.objectStore(store).getAllKeys();
@@ -465,11 +465,11 @@ class MLIDbStorage {
}
await tx.done;
- const files = allMLData['files'];
+ const files = allMLData["files"];
for (const fileId of Object.keys(files)) {
const fileData = files[fileId];
fileData.faces?.forEach(
- (f) => (f.embedding = Array.from(f.embedding))
+ (f) => (f.embedding = Array.from(f.embedding)),
);
}
@@ -479,7 +479,7 @@ class MLIDbStorage {
// for debug purpose, this will overwrite all data
public async putAllMLData(allMLData: Map<string, any>) {
const db = await this.db;
- const tx = db.transaction(db.objectStoreNames, 'readwrite');
+ const tx = db.transaction(db.objectStoreNames, "readwrite");
for (const store of tx.objectStoreNames) {
const records = allMLData[store];
if (!records) {
@@ -487,12 +487,12 @@ class MLIDbStorage {
}
const txStore = tx.objectStore(store);
- if (store === 'files') {
+ if (store === "files") {
const files = records;
for (const fileId of Object.keys(files)) {
const fileData = files[fileId];
fileData.faces?.forEach(
- (f) => (f.embedding = Float32Array.from(f.embedding))
+ (f) => (f.embedding = Float32Array.from(f.embedding)),
);
}
}
diff --git a/apps/photos/src/utils/storage/mlStorage.ts b/apps/photos/src/utils/storage/mlStorage.ts
index ea0807cee8..31fc38fab5 100644
--- a/apps/photos/src/utils/storage/mlStorage.ts
+++ b/apps/photos/src/utils/storage/mlStorage.ts
@@ -1,38 +1,38 @@
-import localForage from 'localforage';
-import { EnteFile } from 'types/file';
+import localForage from "localforage";
+import { EnteFile } from "types/file";
import {
Face,
MlFileData,
MLIndex,
MLSyncContext,
-} from 'types/machineLearning';
+} from "types/machineLearning";
export const mlFilesStore = localForage.createInstance({
driver: localForage.INDEXEDDB,
- name: 'ml-data',
+ name: "ml-data",
version: 1.0,
- storeName: 'files',
+ storeName: "files",
});
export const mlPeopleStore = localForage.createInstance({
driver: localForage.INDEXEDDB,
- name: 'ml-data',
+ name: "ml-data",
version: 1.0,
- storeName: 'people',
+ storeName: "people",
});
export const mlLibraryStore = localForage.createInstance({
driver: localForage.INDEXEDDB,
- name: 'ml-data',
+ name: "ml-data",
version: 1.0,
- storeName: 'library',
+ storeName: "library",
});
export const mlVersionStore = localForage.createInstance({
driver: localForage.INDEXEDDB,
- name: 'ml-data',
+ name: "ml-data",
version: 1.0,
- storeName: 'versions',
+ storeName: "versions",
});
export async function clearMLStorage() {
@@ -48,7 +48,7 @@ export async function getIndexVersion(index: MLIndex): Promise<number> {
export async function setIndexVersion(
index: MLIndex,
- version: number
+ version: number,
): Promise<number> {
await mlVersionStore.setItem(`${index}`, version);
@@ -72,7 +72,7 @@ export async function isVersionOutdated(index: MLIndex, thanIndex: MLIndex) {
export function newMlData(
syncContext: MLSyncContext,
- enteFile: EnteFile
+ enteFile: EnteFile,
): MlFileData {
return {
fileId: enteFile.id,
diff --git a/apps/photos/src/utils/temp/index.ts b/apps/photos/src/utils/temp/index.ts
index 589c66d55d..984f4abb05 100644
--- a/apps/photos/src/utils/temp/index.ts
+++ b/apps/photos/src/utils/temp/index.ts
@@ -1,13 +1,13 @@
const CHARACTERS =
- 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
export function generateTempName(length: number, suffix: string) {
- let tempName = '';
+ let tempName = "";
const charactersLength = CHARACTERS.length;
for (let i = 0; i < length; i++) {
tempName += CHARACTERS.charAt(
- Math.floor(Math.random() * charactersLength)
+ Math.floor(Math.random() * charactersLength),
);
}
return `${tempName}-${suffix}`;
diff --git a/apps/photos/src/utils/ui/index.tsx b/apps/photos/src/utils/ui/index.tsx
index 50a67d056f..1b938fb033 100644
--- a/apps/photos/src/utils/ui/index.tsx
+++ b/apps/photos/src/utils/ui/index.tsx
@@ -1,99 +1,99 @@
-import AutoAwesomeOutlinedIcon from '@mui/icons-material/AutoAwesomeOutlined';
-import { DialogBoxAttributes } from '@ente/shared/components/DialogBox/types';
-import { downloadApp } from 'utils/common';
-import { t } from 'i18next';
+import { DialogBoxAttributes } from "@ente/shared/components/DialogBox/types";
+import AutoAwesomeOutlinedIcon from "@mui/icons-material/AutoAwesomeOutlined";
+import { t } from "i18next";
+import { downloadApp } from "utils/common";
-import ElectronAPIs from '@ente/shared/electron';
-import InfoOutlined from '@mui/icons-material/InfoRounded';
-import { Trans } from 'react-i18next';
-import { Subscription } from 'types/billing';
-import { logoutUser } from '@ente/accounts/services/user';
-import { Link } from '@mui/material';
-import { OPEN_STREET_MAP_LINK } from 'components/Sidebar/EnableMap';
-import { AppUpdateInfo } from '@ente/shared/electron/types';
+import { logoutUser } from "@ente/accounts/services/user";
+import ElectronAPIs from "@ente/shared/electron";
+import { AppUpdateInfo } from "@ente/shared/electron/types";
+import InfoOutlined from "@mui/icons-material/InfoRounded";
+import { Link } from "@mui/material";
+import { OPEN_STREET_MAP_LINK } from "components/Sidebar/EnableMap";
+import { Trans } from "react-i18next";
+import { Subscription } from "types/billing";
export const getDownloadAppMessage = (): DialogBoxAttributes => {
return {
- title: t('DOWNLOAD_APP'),
- content: t('DOWNLOAD_APP_MESSAGE'),
+ title: t("DOWNLOAD_APP"),
+ content: t("DOWNLOAD_APP_MESSAGE"),
proceed: {
- text: t('DOWNLOAD'),
+ text: t("DOWNLOAD"),
action: downloadApp,
- variant: 'accent',
+ variant: "accent",
},
close: {
- text: t('CLOSE'),
+ text: t("CLOSE"),
},
};
};
export const getTrashFilesMessage = (
- deleteFileHelper
+ deleteFileHelper,
): DialogBoxAttributes => ({
- title: t('TRASH_FILES_TITLE'),
- content: t('TRASH_FILES_MESSAGE'),
+ title: t("TRASH_FILES_TITLE"),
+ content: t("TRASH_FILES_MESSAGE"),
proceed: {
action: deleteFileHelper,
- text: t('MOVE_TO_TRASH'),
- variant: 'critical',
+ text: t("MOVE_TO_TRASH"),
+ variant: "critical",
},
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
});
export const getTrashFileMessage = (deleteFileHelper): DialogBoxAttributes => ({
- title: t('TRASH_FILE_TITLE'),
- content: t('TRASH_FILE_MESSAGE'),
+ title: t("TRASH_FILE_TITLE"),
+ content: t("TRASH_FILE_MESSAGE"),
proceed: {
action: deleteFileHelper,
- text: t('MOVE_TO_TRASH'),
- variant: 'critical',
+ text: t("MOVE_TO_TRASH"),
+ variant: "critical",
},
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
});
export const getUpdateReadyToInstallMessage = (
- updateInfo: AppUpdateInfo
+ updateInfo: AppUpdateInfo,
): DialogBoxAttributes => ({
icon: <AutoAwesomeOutlinedIcon />,
- title: t('UPDATE_AVAILABLE'),
- content: t('UPDATE_INSTALLABLE_MESSAGE'),
+ title: t("UPDATE_AVAILABLE"),
+ content: t("UPDATE_INSTALLABLE_MESSAGE"),
proceed: {
action: () => ElectronAPIs.updateAndRestart(),
- text: t('INSTALL_NOW'),
- variant: 'accent',
+ text: t("INSTALL_NOW"),
+ variant: "accent",
},
close: {
- text: t('INSTALL_ON_NEXT_LAUNCH'),
- variant: 'secondary',
+ text: t("INSTALL_ON_NEXT_LAUNCH"),
+ variant: "secondary",
action: () => ElectronAPIs.muteUpdateNotification(updateInfo.version),
},
});
export const getUpdateAvailableForDownloadMessage = (
- updateInfo: AppUpdateInfo
+ updateInfo: AppUpdateInfo,
): DialogBoxAttributes => ({
icon: <AutoAwesomeOutlinedIcon />,
- title: t('UPDATE_AVAILABLE'),
- content: t('UPDATE_AVAILABLE_MESSAGE'),
+ title: t("UPDATE_AVAILABLE"),
+ content: t("UPDATE_AVAILABLE_MESSAGE"),
close: {
- text: t('IGNORE_THIS_VERSION'),
- variant: 'secondary',
+ text: t("IGNORE_THIS_VERSION"),
+ variant: "secondary",
action: () => ElectronAPIs.skipAppUpdate(updateInfo.version),
},
proceed: {
action: downloadApp,
- text: t('DOWNLOAD_AND_INSTALL'),
- variant: 'accent',
+ text: t("DOWNLOAD_AND_INSTALL"),
+ variant: "accent",
},
});
export const getRootLevelFileWithFolderNotAllowMessage =
(): DialogBoxAttributes => ({
icon: <InfoOutlined />,
- title: t('ROOT_LEVEL_FILE_WITH_FOLDER_NOT_ALLOWED'),
+ title: t("ROOT_LEVEL_FILE_WITH_FOLDER_NOT_ALLOWED"),
content: (
<Trans
- i18nKey={'ROOT_LEVEL_FILE_WITH_FOLDER_NOT_ALLOWED_MESSAGE'}
+ i18nKey={"ROOT_LEVEL_FILE_WITH_FOLDER_NOT_ALLOWED_MESSAGE"}
/>
),
close: {},
@@ -101,16 +101,16 @@ export const getRootLevelFileWithFolderNotAllowMessage =
export const getExportDirectoryDoesNotExistMessage =
(): DialogBoxAttributes => ({
- title: t('EXPORT_DIRECTORY_DOES_NOT_EXIST'),
- content: <Trans i18nKey={'EXPORT_DIRECTORY_DOES_NOT_EXIST_MESSAGE'} />,
+ title: t("EXPORT_DIRECTORY_DOES_NOT_EXIST"),
+ content: <Trans i18nKey={"EXPORT_DIRECTORY_DOES_NOT_EXIST_MESSAGE"} />,
close: {},
});
export const getSubscriptionPurchaseSuccessMessage = (
- subscription: Subscription
+ subscription: Subscription,
): DialogBoxAttributes => ({
- title: t('SUBSCRIPTION_PURCHASE_SUCCESS_TITLE'),
- close: { variant: 'accent' },
+ title: t("SUBSCRIPTION_PURCHASE_SUCCESS_TITLE"),
+ close: { variant: "accent" },
content: (
<Trans
i18nKey="SUBSCRIPTION_PURCHASE_SUCCESS"
@@ -120,24 +120,24 @@ export const getSubscriptionPurchaseSuccessMessage = (
});
export const getSessionExpiredMessage = (): DialogBoxAttributes => ({
- title: t('SESSION_EXPIRED'),
- content: t('SESSION_EXPIRED_MESSAGE'),
+ title: t("SESSION_EXPIRED"),
+ content: t("SESSION_EXPIRED_MESSAGE"),
nonClosable: true,
proceed: {
- text: t('LOGIN'),
+ text: t("LOGIN"),
action: logoutUser,
- variant: 'accent',
+ variant: "accent",
},
});
export const getMapEnableConfirmationDialog = (
- enableMapHelper
+ enableMapHelper,
): DialogBoxAttributes => ({
- title: t('ENABLE_MAPS'),
+ title: t("ENABLE_MAPS"),
content: (
<Trans
- i18nKey={'ENABLE_MAP_DESCRIPTION'}
+ i18nKey={"ENABLE_MAP_DESCRIPTION"}
components={{
a: <Link target="_blank" href={OPEN_STREET_MAP_LINK} />,
}}
@@ -145,34 +145,34 @@ export const getMapEnableConfirmationDialog = (
),
proceed: {
action: enableMapHelper,
- text: t('ENABLE'),
- variant: 'accent',
+ text: t("ENABLE"),
+ variant: "accent",
},
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
});
export const getMapDisableConfirmationDialog = (
- disableMapHelper
+ disableMapHelper,
): DialogBoxAttributes => ({
- title: t('DISABLE_MAPS'),
- content: <Trans i18nKey={'DISABLE_MAP_DESCRIPTION'} />,
+ title: t("DISABLE_MAPS"),
+ content: <Trans i18nKey={"DISABLE_MAP_DESCRIPTION"} />,
proceed: {
action: disableMapHelper,
- text: t('DISABLE'),
- variant: 'accent',
+ text: t("DISABLE"),
+ variant: "accent",
},
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
});
export const getEditorCloseConfirmationMessage = (
- doClose: () => void
+ doClose: () => void,
): DialogBoxAttributes => ({
- title: t('CONFIRM_EDITOR_CLOSE_MESSAGE'),
- content: t('CONFIRM_EDITOR_CLOSE_DESCRIPTION'),
+ title: t("CONFIRM_EDITOR_CLOSE_MESSAGE"),
+ content: t("CONFIRM_EDITOR_CLOSE_DESCRIPTION"),
proceed: {
action: doClose,
- text: t('CLOSE'),
- variant: 'critical',
+ text: t("CLOSE"),
+ variant: "critical",
},
- close: { text: t('CANCEL') },
+ close: { text: t("CANCEL") },
});
diff --git a/apps/photos/src/utils/upload/index.ts b/apps/photos/src/utils/upload/index.ts
index cede5776f0..6cce03aa9d 100644
--- a/apps/photos/src/utils/upload/index.ts
+++ b/apps/photos/src/utils/upload/index.ts
@@ -1,25 +1,25 @@
-import {
- ImportSuggestion,
- ElectronFile,
- FileWithCollection,
- Metadata,
-} from 'types/upload';
-import { EnteFile } from 'types/file';
+import { ENTE_METADATA_FOLDER } from "constants/export";
+import { FILE_TYPE } from "constants/file";
import {
A_SEC_IN_MICROSECONDS,
DEFAULT_IMPORT_SUGGESTION,
PICKED_UPLOAD_TYPE,
-} from 'constants/upload';
-import { FILE_TYPE } from 'constants/file';
-import { ENTE_METADATA_FOLDER } from 'constants/export';
-import isElectron from 'is-electron';
+} from "constants/upload";
+import isElectron from "is-electron";
+import { EnteFile } from "types/file";
+import {
+ ElectronFile,
+ FileWithCollection,
+ ImportSuggestion,
+ Metadata,
+} from "types/upload";
-const TYPE_JSON = 'json';
-const DEDUPE_COLLECTION = new Set(['icloud library', 'icloudlibrary']);
+const TYPE_JSON = "json";
+const DEDUPE_COLLECTION = new Set(["icloud library", "icloudlibrary"]);
export function findMatchingExistingFiles(
existingFiles: EnteFile[],
- newFileMetadata: Metadata
+ newFileMetadata: Metadata,
): EnteFile[] {
const matchingFiles: EnteFile[] = [];
for (const existingFile of existingFiles) {
@@ -37,7 +37,7 @@ export function shouldDedupeAcrossCollection(collectionName: string): boolean {
export function areFilesSame(
existingFile: Metadata,
- newFile: Metadata
+ newFile: Metadata,
): boolean {
if (hasFileHash(existingFile) && hasFileHash(newFile)) {
return areFilesWithFileHashSame(existingFile, newFile);
@@ -69,7 +69,7 @@ export function hasFileHash(file: Metadata) {
export function areFilesWithFileHashSame(
existingFile: Metadata,
- newFile: Metadata
+ newFile: Metadata,
): boolean {
if (
existingFile.fileType !== newFile.fileType ||
@@ -88,7 +88,7 @@ export function areFilesWithFileHashSame(
}
export function segregateMetadataAndMediaFiles(
- filesWithCollectionToUpload: FileWithCollection[]
+ filesWithCollectionToUpload: FileWithCollection[],
) {
const metadataJSONFiles: FileWithCollection[] = [];
const mediaFiles: FileWithCollection[] = [];
@@ -105,20 +105,20 @@ export function segregateMetadataAndMediaFiles(
export function areFileWithCollectionsSame(
firstFile: FileWithCollection,
- secondFile: FileWithCollection
+ secondFile: FileWithCollection,
): boolean {
return firstFile.localID === secondFile.localID;
}
export function getImportSuggestion(
uploadType: PICKED_UPLOAD_TYPE,
- toUploadFiles: File[] | ElectronFile[]
+ toUploadFiles: File[] | ElectronFile[],
): ImportSuggestion {
if (isElectron() && uploadType === PICKED_UPLOAD_TYPE.FILES) {
return DEFAULT_IMPORT_SUGGESTION;
}
- const paths: string[] = toUploadFiles.map((file) => file['path']);
+ const paths: string[] = toUploadFiles.map((file) => file["path"]);
const getCharCount = (str: string) => (str.match(/\//g) ?? []).length;
paths.sort((path1, path2) => getCharCount(path1) - getCharCount(path2));
const firstPath = paths[0];
@@ -126,8 +126,8 @@ export function getImportSuggestion(
const L = firstPath.length;
let i = 0;
- const firstFileFolder = firstPath.substring(0, firstPath.lastIndexOf('/'));
- const lastFileFolder = lastPath.substring(0, lastPath.lastIndexOf('/'));
+ const firstFileFolder = firstPath.substring(0, firstPath.lastIndexOf("/"));
+ const lastFileFolder = lastPath.substring(0, lastPath.lastIndexOf("/"));
while (i < L && firstPath.charAt(i) === lastPath.charAt(i)) i++;
let commonPathPrefix = firstPath.substring(0, i);
@@ -135,18 +135,18 @@ export function getImportSuggestion(
if (commonPathPrefix) {
commonPathPrefix = commonPathPrefix.substring(
0,
- commonPathPrefix.lastIndexOf('/')
+ commonPathPrefix.lastIndexOf("/"),
);
if (commonPathPrefix) {
commonPathPrefix = commonPathPrefix.substring(
- commonPathPrefix.lastIndexOf('/') + 1
+ commonPathPrefix.lastIndexOf("/") + 1,
);
}
}
return {
rootFolderName: commonPathPrefix || null,
hasNestedFolders: firstFileFolder !== lastFileFolder,
- hasRootLevelFileWithFolder: firstFileFolder === '',
+ hasRootLevelFileWithFolder: firstFileFolder === "",
};
}
@@ -163,23 +163,23 @@ export function getImportSuggestion(
// b => [e,f,g],
// c => [h, i]]
export function groupFilesBasedOnParentFolder(
- toUploadFiles: File[] | ElectronFile[]
+ toUploadFiles: File[] | ElectronFile[],
) {
const collectionNameToFilesMap = new Map<string, (File | ElectronFile)[]>();
for (const file of toUploadFiles) {
- const filePath = file['path'] as string;
+ const filePath = file["path"] as string;
- let folderPath = filePath.substring(0, filePath.lastIndexOf('/'));
+ let folderPath = filePath.substring(0, filePath.lastIndexOf("/"));
// If the parent folder of a file is "metadata"
// we consider it to be part of the parent folder
// For Eg,For FileList -> [a/x.png, a/metadata/x.png.json]
// they will both we grouped into the collection "a"
// This is cluster the metadata json files in the same collection as the file it is for
if (folderPath.endsWith(ENTE_METADATA_FOLDER)) {
- folderPath = folderPath.substring(0, folderPath.lastIndexOf('/'));
+ folderPath = folderPath.substring(0, folderPath.lastIndexOf("/"));
}
const folderName = folderPath.substring(
- folderPath.lastIndexOf('/') + 1
+ folderPath.lastIndexOf("/") + 1,
);
if (!folderName?.length) {
throw Error("folderName can't be null");
@@ -207,5 +207,5 @@ export function filterOutSystemFiles(files: File[] | ElectronFile[]) {
}
export function isSystemFile(file: File | ElectronFile) {
- return file.name.startsWith('.');
+ return file.name.startsWith(".");
}
diff --git a/apps/photos/src/utils/upload/isCanvasBlocked.ts b/apps/photos/src/utils/upload/isCanvasBlocked.ts
index d637b5de4f..e9f9b5abe4 100644
--- a/apps/photos/src/utils/upload/isCanvasBlocked.ts
+++ b/apps/photos/src/utils/upload/isCanvasBlocked.ts
@@ -10,8 +10,8 @@
export function isCanvasBlocked() {
// create a 1px image data
let blocked = false;
- const canvas = document.createElement('canvas');
- const ctx = canvas.getContext('2d');
+ const canvas = document.createElement("canvas");
+ const ctx = canvas.getContext("2d");
// some blockers just return an undefined ctx. So let's check that first.
if (ctx) {
diff --git a/apps/photos/src/utils/upload/uploadRetrier.ts b/apps/photos/src/utils/upload/uploadRetrier.ts
index e7a48f52c0..2f42ed58f8 100644
--- a/apps/photos/src/utils/upload/uploadRetrier.ts
+++ b/apps/photos/src/utils/upload/uploadRetrier.ts
@@ -1,14 +1,14 @@
-import { sleep } from 'utils/common';
+import { sleep } from "utils/common";
const retrySleepTimeInMilliSeconds = [2000, 5000, 10000];
export async function retryHTTPCall(
func: () => Promise<any>,
- checkForBreakingError?: (error) => void
+ checkForBreakingError?: (error) => void,
): Promise<any> {
const retrier = async (
func: () => Promise<any>,
- attemptNumber: number = 0
+ attemptNumber: number = 0,
) => {
try {
const resp = await func();
diff --git a/apps/photos/src/utils/user/family.ts b/apps/photos/src/utils/user/family.ts
index d5c65f4bb1..4ccc1bcf1a 100644
--- a/apps/photos/src/utils/user/family.ts
+++ b/apps/photos/src/utils/user/family.ts
@@ -1,7 +1,7 @@
-import { User } from '@ente/shared/user/types';
-import { FamilyData, FamilyMember } from 'types/user';
-import { logError } from '@ente/shared/sentry';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
+import { logError } from "@ente/shared/sentry";
+import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
+import { User } from "@ente/shared/user/types";
+import { FamilyData, FamilyMember } from "types/user";
export function getLocalFamilyData(): FamilyData {
return getData(LS_KEYS.FAMILY_DATA);
@@ -10,7 +10,7 @@ export function getLocalFamilyData(): FamilyData {
// isPartOfFamily return true if the current user is part of some family plan
export function isPartOfFamily(familyData: FamilyData): boolean {
return Boolean(
- familyData && familyData.members && familyData.members.length > 0
+ familyData && familyData.members && familyData.members.length > 0,
);
}
@@ -31,9 +31,9 @@ export function getFamilyPlanAdmin(familyData: FamilyData): FamilyMember {
} else {
logError(
Error(
- 'verify user is part of family plan before calling this method'
+ "verify user is part of family plan before calling this method",
),
- 'invalid getFamilyPlanAdmin call'
+ "invalid getFamilyPlanAdmin call",
);
}
}
@@ -41,6 +41,6 @@ export function getFamilyPlanAdmin(familyData: FamilyData): FamilyMember {
export function getTotalFamilyUsage(familyData: FamilyData): number {
return familyData.members.reduce(
(sum, currentMember) => sum + currentMember.usage,
- 0
+ 0,
);
}
diff --git a/apps/photos/src/utils/user/index.ts b/apps/photos/src/utils/user/index.ts
index 78319f7c35..17551014d0 100644
--- a/apps/photos/src/utils/user/index.ts
+++ b/apps/photos/src/utils/user/index.ts
@@ -1,5 +1,5 @@
-import { UserDetails } from 'types/user';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
+import { getData, LS_KEYS } from "@ente/shared/storage/localStorage";
+import { UserDetails } from "types/user";
export function getLocalUserDetails(): UserDetails {
return getData(LS_KEYS.USER_DETAILS)?.value;
@@ -10,6 +10,6 @@ export const isInternalUser = () => {
if (!userEmail) return false;
return (
- userEmail.endsWith('@ente.io') || userEmail === '[email protected]'
+ userEmail.endsWith("@ente.io") || userEmail === "[email protected]"
);
};
diff --git a/apps/photos/src/utils/watch/index.ts b/apps/photos/src/utils/watch/index.ts
index 9e11a1e1df..eb16780ddc 100644
--- a/apps/photos/src/utils/watch/index.ts
+++ b/apps/photos/src/utils/watch/index.ts
@@ -1,6 +1,6 @@
-import { ElectronFile } from 'types/upload';
-import { WatchMapping } from 'types/watchFolder';
-import { isSystemFile } from 'utils/upload';
+import { ElectronFile } from "types/upload";
+import { WatchMapping } from "types/watchFolder";
+import { isSystemFile } from "utils/upload";
function isSyncedOrIgnoredFile(file: ElectronFile, mapping: WatchMapping) {
return (
@@ -11,7 +11,7 @@ function isSyncedOrIgnoredFile(file: ElectronFile, mapping: WatchMapping) {
export function getValidFilesToUpload(
files: ElectronFile[],
- mapping: WatchMapping
+ mapping: WatchMapping,
) {
const uniqueFilePaths = new Set<string>();
return files.filter((file) => {
diff --git a/apps/photos/src/worker/convert.worker.ts b/apps/photos/src/worker/convert.worker.ts
index 8dae977a91..a805752acf 100644
--- a/apps/photos/src/worker/convert.worker.ts
+++ b/apps/photos/src/worker/convert.worker.ts
@@ -1,5 +1,5 @@
-import * as Comlink from 'comlink';
-import { convertHEIC } from 'services/wasmHeicConverter/wasmHEICConverterClient';
+import * as Comlink from "comlink";
+import { convertHEIC } from "services/wasmHeicConverter/wasmHEICConverterClient";
export class DedicatedConvertWorker {
async convertHEIC(fileBlob: Blob, format: string) {
diff --git a/apps/photos/src/worker/ffmpeg.worker.ts b/apps/photos/src/worker/ffmpeg.worker.ts
index 3c4f4c52e2..d3f503abb9 100644
--- a/apps/photos/src/worker/ffmpeg.worker.ts
+++ b/apps/photos/src/worker/ffmpeg.worker.ts
@@ -1,5 +1,5 @@
-import * as Comlink from 'comlink';
-import { WasmFFmpeg } from 'services/wasm/ffmpeg';
+import * as Comlink from "comlink";
+import { WasmFFmpeg } from "services/wasm/ffmpeg";
export class DedicatedFFmpegWorker {
wasmFFmpeg: WasmFFmpeg;
diff --git a/apps/photos/src/worker/ml.worker.ts b/apps/photos/src/worker/ml.worker.ts
index e963ab16e1..a66188d43e 100644
--- a/apps/photos/src/worker/ml.worker.ts
+++ b/apps/photos/src/worker/ml.worker.ts
@@ -1,14 +1,14 @@
-import { expose } from 'comlink';
-import { EnteFile } from 'types/file';
-import mlService from 'services/machineLearning/machineLearningService';
-import { MachineLearningWorker } from 'types/machineLearning';
-import { addLogLine } from '@ente/shared/logging';
+import { addLogLine } from "@ente/shared/logging";
+import { expose } from "comlink";
+import mlService from "services/machineLearning/machineLearningService";
+import { EnteFile } from "types/file";
+import { MachineLearningWorker } from "types/machineLearning";
// import ReverseProxiedElectronCacheStorageProxy from './electronCacheStorageProxy.proxy';
// import { setupResponseComlinkTransferHandler } from 'utils/comlink';
export class DedicatedMLWorker implements MachineLearningWorker {
constructor() {
- addLogLine('DedicatedMLWorker constructor called');
+ addLogLine("DedicatedMLWorker constructor called");
// this.init();
}
@@ -28,7 +28,7 @@ export class DedicatedMLWorker implements MachineLearningWorker {
token: string,
userID: number,
enteFile: EnteFile,
- localFile: globalThis.File
+ localFile: globalThis.File,
) {
return mlService.syncLocalFile(token, userID, enteFile, localFile);
}
@@ -40,7 +40,7 @@ export class DedicatedMLWorker implements MachineLearningWorker {
public async regenerateFaceCrop(
token: string,
userID: number,
- faceID: string
+ faceID: string,
) {
return mlService.regenerateFaceCrop(token, userID, faceID);
}
diff --git a/apps/photos/src/worker/search.worker.ts b/apps/photos/src/worker/search.worker.ts
index f64b5031ae..31852a4169 100644
--- a/apps/photos/src/worker/search.worker.ts
+++ b/apps/photos/src/worker/search.worker.ts
@@ -1,11 +1,11 @@
-import * as Comlink from 'comlink';
+import * as Comlink from "comlink";
import {
- isInsideLocationTag,
isInsideCity,
-} from 'services/locationSearchService';
-import { EnteFile } from 'types/file';
-import { isSameDayAnyYear } from 'utils/search';
-import { Search } from 'types/search';
+ isInsideLocationTag,
+} from "services/locationSearchService";
+import { EnteFile } from "types/file";
+import { Search } from "types/search";
+import { isSameDayAnyYear } from "utils/search";
export class DedicatedSearchWorker {
private files: EnteFile[] = [];
@@ -30,7 +30,7 @@ function isSearchedFile(file: EnteFile, search: Search) {
if (search?.date) {
return isSameDayAnyYear(search.date)(
- new Date(file.metadata.creationTime / 1000)
+ new Date(file.metadata.creationTime / 1000),
);
}
if (search?.location) {
@@ -39,7 +39,7 @@ function isSearchedFile(file: EnteFile, search: Search) {
latitude: file.metadata.latitude,
longitude: file.metadata.longitude,
},
- search.location
+ search.location,
);
}
if (search?.city) {
@@ -48,7 +48,7 @@ function isSearchedFile(file: EnteFile, search: Search) {
latitude: file.metadata.latitude,
longitude: file.metadata.longitude,
},
- search.city
+ search.city,
);
}
if (search?.files) {
@@ -65,10 +65,10 @@ function isSearchedFile(file: EnteFile, search: Search) {
if (search?.text) {
return search.text.files.indexOf(file.id) !== -1;
}
- if (typeof search?.fileType !== 'undefined') {
+ if (typeof search?.fileType !== "undefined") {
return search.fileType === file.metadata.fileType;
}
- if (typeof search?.clip !== 'undefined') {
+ if (typeof search?.clip !== "undefined") {
return search.clip.has(file.id);
}
return false;
diff --git a/apps/photos/tests/upload.test.ts b/apps/photos/tests/upload.test.ts
index 6e2b32431d..dcd16db3c0 100644
--- a/apps/photos/tests/upload.test.ts
+++ b/apps/photos/tests/upload.test.ts
@@ -1,101 +1,101 @@
-import { getLocalFiles } from 'services/fileService';
-import { getLocalCollections } from 'services/collectionService';
-import { getUserDetailsV2 } from 'services/userService';
-import { groupFilesBasedOnCollectionID } from 'utils/file';
-import { FILE_TYPE } from 'constants/file';
-import { tryToParseDateTime } from '@ente/shared/time';
+import { tryToParseDateTime } from "@ente/shared/time";
+import { FILE_TYPE } from "constants/file";
+import { getLocalCollections } from "services/collectionService";
+import { getLocalFiles } from "services/fileService";
import {
MAX_FILE_NAME_LENGTH_GOOGLE_EXPORT,
getClippedMetadataJSONMapKeyForFile,
getMetadataJSONMapKeyForFile,
getMetadataJSONMapKeyForJSON,
-} from 'services/upload/metadataService';
+} from "services/upload/metadataService";
+import { getUserDetailsV2 } from "services/userService";
+import { groupFilesBasedOnCollectionID } from "utils/file";
const DATE_TIME_PARSING_TEST_FILE_NAMES = [
{
- fileName: 'Screenshot_20220807-195908_Firefox',
- expectedDateTime: '2022-08-07 19:59:08',
+ fileName: "Screenshot_20220807-195908_Firefox",
+ expectedDateTime: "2022-08-07 19:59:08",
},
{
- fileName: 'Screenshot_20220507-195908',
- expectedDateTime: '2022-05-07 19:59:08',
+ fileName: "Screenshot_20220507-195908",
+ expectedDateTime: "2022-05-07 19:59:08",
},
{
- fileName: '2022-02-18 16.00.12-DCMX.png',
- expectedDateTime: '2022-02-18 16:00:12',
+ fileName: "2022-02-18 16.00.12-DCMX.png",
+ expectedDateTime: "2022-02-18 16:00:12",
},
{
- fileName: '20221107_231730',
- expectedDateTime: '2022-11-07 23:17:30',
+ fileName: "20221107_231730",
+ expectedDateTime: "2022-11-07 23:17:30",
},
{
- fileName: '2020-11-01 02.31.02',
- expectedDateTime: '2020-11-01 02:31:02',
+ fileName: "2020-11-01 02.31.02",
+ expectedDateTime: "2020-11-01 02:31:02",
},
{
- fileName: 'IMG_20210921_144423',
- expectedDateTime: '2021-09-21 14:44:23',
+ fileName: "IMG_20210921_144423",
+ expectedDateTime: "2021-09-21 14:44:23",
},
{
// we don't parse the time from this format, will improve later
- fileName: '2019-10-31 155703',
- expectedDateTime: '2019-10-31 00:00:00',
- correctExpectedDateTime: '2019-10-31 15:57:03',
+ fileName: "2019-10-31 155703",
+ expectedDateTime: "2019-10-31 00:00:00",
+ correctExpectedDateTime: "2019-10-31 15:57:03",
},
{
- fileName: 'IMG_20210921_144423_783',
- expectedDateTime: '2021-09-21 14:44:23',
+ fileName: "IMG_20210921_144423_783",
+ expectedDateTime: "2021-09-21 14:44:23",
},
{
- fileName: 'Screenshot_2022-06-21-16-51-29-164_newFormat.heic',
- expectedDateTime: '2022-06-21 16:51:29',
+ fileName: "Screenshot_2022-06-21-16-51-29-164_newFormat.heic",
+ expectedDateTime: "2022-06-21 16:51:29",
},
{
fileName:
- 'Screenshot 20221106 211633.com.google.android.apps.nbu.paisa.user.jpg',
- expectedDateTime: '2022-11-06 21:16:33',
+ "Screenshot 20221106 211633.com.google.android.apps.nbu.paisa.user.jpg",
+ expectedDateTime: "2022-11-06 21:16:33",
},
{
- fileName: 'signal-2022-12-17-15-16-04-718.jpg',
- expectedDateTime: '2022-12-17 15:16:04',
+ fileName: "signal-2022-12-17-15-16-04-718.jpg",
+ expectedDateTime: "2022-12-17 15:16:04",
},
];
const DATE_TIME_PARSING_TEST_FILE_NAMES_MUST_FAIL = [
- 'Snapchat-431959199.mp4.',
- 'Snapchat-400000000.mp4',
- 'Snapchat-900000000.mp4',
- 'Snapchat-100-10-20-19-15-12',
+ "Snapchat-431959199.mp4.",
+ "Snapchat-400000000.mp4",
+ "Snapchat-900000000.mp4",
+ "Snapchat-100-10-20-19-15-12",
];
const FILE_NAME_TO_JSON_NAME = [
{
- filename: 'IMG20210211125718-edited.jpg',
- jsonFilename: 'IMG20210211125718.jpg.json',
+ filename: "IMG20210211125718-edited.jpg",
+ jsonFilename: "IMG20210211125718.jpg.json",
},
{
- filename: 'IMG20210211174722.jpg',
- jsonFilename: 'IMG20210211174722.jpg.json',
+ filename: "IMG20210211174722.jpg",
+ jsonFilename: "IMG20210211174722.jpg.json",
},
{
- filename: '21345678901234567890123456789012345678901234567.png',
- jsonFilename: '2134567890123456789012345678901234567890123456.json',
+ filename: "21345678901234567890123456789012345678901234567.png",
+ jsonFilename: "2134567890123456789012345678901234567890123456.json",
},
{
- filename: 'IMG20210211174722(1).jpg',
- jsonFilename: 'IMG20210211174722.jpg(1).json',
+ filename: "IMG20210211174722(1).jpg",
+ jsonFilename: "IMG20210211174722.jpg(1).json",
},
{
- filename: 'IMG2021021(4455)74722(1).jpg',
- jsonFilename: 'IMG2021021(4455)74722.jpg(1).json',
+ filename: "IMG2021021(4455)74722(1).jpg",
+ jsonFilename: "IMG2021021(4455)74722.jpg(1).json",
},
{
- filename: 'IMG2021021.json74722(1).jpg',
- jsonFilename: 'IMG2021021.json74722.jpg(1).json',
+ filename: "IMG2021021.json74722(1).jpg",
+ jsonFilename: "IMG2021021.json74722.jpg(1).json",
},
{
- filename: 'IMG2021021(1)74722(1).jpg',
- jsonFilename: 'IMG2021021(1)74722.jpg(1).json',
+ filename: "IMG2021021(1)74722(1).jpg",
+ jsonFilename: "IMG2021021(1)74722.jpg(1).json",
},
];
@@ -103,12 +103,12 @@ export async function testUpload() {
const jsonPath = process.env.NEXT_PUBLIC_ENTE_TEST_EXPECTED_JSON_PATH;
if (!jsonPath) {
throw Error(
- 'Please specify the NEXT_PUBLIC_ENTE_TEST_EXPECTED_JSON_PATH to run the upload tests'
+ "Please specify the NEXT_PUBLIC_ENTE_TEST_EXPECTED_JSON_PATH to run the upload tests",
);
}
const expectedState = await import(jsonPath);
if (!expectedState) {
- throw Error('upload test failed expectedState missing');
+ throw Error("upload test failed expectedState missing");
}
try {
@@ -129,11 +129,11 @@ export async function testUpload() {
async function totalFileCountCheck(expectedState) {
const userDetails = await getUserDetailsV2();
- if (expectedState['total_file_count'] === userDetails.fileCount) {
- console.log('file count check passed βœ…');
+ if (expectedState["total_file_count"] === userDetails.fileCount) {
+ console.log("file count check passed βœ…");
} else {
throw Error(
- `total file count check failed ❌, expected: ${expectedState['total_file_count']}, got: ${userDetails.fileCount}`
+ `total file count check failed ❌, expected: ${expectedState["total_file_count"]}, got: ${userDetails.fileCount}`,
);
}
}
@@ -142,17 +142,17 @@ async function totalCollectionCountCheck(expectedState) {
const collections = await getLocalCollections();
const files = await getLocalFiles();
const nonEmptyCollectionIds = new Set(
- files.map((file) => file.collectionID)
+ files.map((file) => file.collectionID),
);
const nonEmptyCollections = collections.filter((collection) =>
- nonEmptyCollectionIds.has(collection.id)
+ nonEmptyCollectionIds.has(collection.id),
);
- if (expectedState['collection_count'] === nonEmptyCollections.length) {
- console.log('collection count check passed βœ…');
+ if (expectedState["collection_count"] === nonEmptyCollections.length) {
+ console.log("collection count check passed βœ…");
} else {
throw Error(
`total Collection count check failed ❌
- expected : ${expectedState['collection_count']}, got: ${nonEmptyCollections.length}`
+ expected : ${expectedState["collection_count"]}, got: ${nonEmptyCollections.length}`,
);
}
}
@@ -162,34 +162,34 @@ async function collectionWiseFileCount(expectedState) {
const collections = await getLocalCollections();
const collectionToFilesMap = groupFilesBasedOnCollectionID(files);
const collectionIDToNameMap = new Map(
- collections.map((collection) => [collection.id, collection.name])
+ collections.map((collection) => [collection.id, collection.name]),
);
const collectionNameToFileCount = new Map(
[...collectionToFilesMap.entries()].map(([collectionID, files]) => [
collectionIDToNameMap.get(collectionID),
files.length,
- ])
+ ]),
);
- Object.entries(expectedState['collection_files_count']).forEach(
+ Object.entries(expectedState["collection_files_count"]).forEach(
([collectionName, fileCount]) => {
if (fileCount !== collectionNameToFileCount.get(collectionName)) {
throw Error(
`collectionWiseFileCount check failed ❌
for collection ${collectionName}
expected File count : ${fileCount} , got: ${collectionNameToFileCount.get(
- collectionName
- )}`
+ collectionName,
+ )}`,
);
}
- }
+ },
);
- console.log('collection wise file count check passed βœ…');
+ console.log("collection wise file count check passed βœ…");
}
async function thumbnailGenerationFailedFilesCheck(expectedState) {
const files = await getLocalFiles();
const filesWithStaticThumbnail = files.filter(
- (file) => file.metadata.hasStaticThumbnail
+ (file) => file.metadata.hasStaticThumbnail,
);
const fileIDSet = new Set();
@@ -201,40 +201,40 @@ async function thumbnailGenerationFailedFilesCheck(expectedState) {
fileIDSet.add(file.id);
return true;
}
- }
+ },
);
const fileNamesWithStaticThumbnail = uniqueFilesWithStaticThumbnail.map(
- (file) => file.metadata.title
+ (file) => file.metadata.title,
);
if (
- expectedState['thumbnail_generation_failure']['count'] <
+ expectedState["thumbnail_generation_failure"]["count"] <
uniqueFilesWithStaticThumbnail.length
) {
throw Error(
`thumbnailGenerationFailedFiles Count Check failed ❌
- expected: ${expectedState['thumbnail_generation_failure']['count']}, got: ${uniqueFilesWithStaticThumbnail.length}`
+ expected: ${expectedState["thumbnail_generation_failure"]["count"]}, got: ${uniqueFilesWithStaticThumbnail.length}`,
);
}
fileNamesWithStaticThumbnail.forEach((fileName) => {
if (
- !expectedState['thumbnail_generation_failure']['files'].includes(
- fileName
+ !expectedState["thumbnail_generation_failure"]["files"].includes(
+ fileName,
)
) {
throw Error(
`thumbnailGenerationFailedFiles Check failed ❌
- expected: ${expectedState['thumbnail_generation_failure']['files']}, got: ${fileNamesWithStaticThumbnail}`
+ expected: ${expectedState["thumbnail_generation_failure"]["files"]}, got: ${fileNamesWithStaticThumbnail}`,
);
}
});
- console.log('thumbnail generation failure check passed βœ…');
+ console.log("thumbnail generation failure check passed βœ…");
}
async function livePhotoClubbingCheck(expectedState) {
const files = await getLocalFiles();
const livePhotos = files.filter(
- (file) => file.metadata.fileType === FILE_TYPE.LIVE_PHOTO
+ (file) => file.metadata.fileType === FILE_TYPE.LIVE_PHOTO,
);
const fileIDSet = new Set();
@@ -248,135 +248,135 @@ async function livePhotoClubbingCheck(expectedState) {
});
const livePhotoFileNames = uniqueLivePhotos.map(
- (file) => file.metadata.title
+ (file) => file.metadata.title,
);
- if (expectedState['live_photo']['count'] !== livePhotoFileNames.length) {
+ if (expectedState["live_photo"]["count"] !== livePhotoFileNames.length) {
throw Error(
`livePhotoClubbing Check failed ❌
- expected: ${expectedState['live_photo']['count']}, got: ${livePhotoFileNames.length}`
+ expected: ${expectedState["live_photo"]["count"]}, got: ${livePhotoFileNames.length}`,
);
}
- expectedState['live_photo']['files'].forEach((fileName) => {
+ expectedState["live_photo"]["files"].forEach((fileName) => {
if (!livePhotoFileNames.includes(fileName)) {
throw Error(
`livePhotoClubbing Check failed ❌
- expected: ${expectedState['live_photo']['files']}, got: ${livePhotoFileNames}`
+ expected: ${expectedState["live_photo"]["files"]}, got: ${livePhotoFileNames}`,
);
}
});
- console.log('live-photo clubbing check passed βœ…');
+ console.log("live-photo clubbing check passed βœ…");
}
async function exifDataParsingCheck(expectedState) {
const files = await getLocalFiles();
- Object.entries(expectedState['exif']).map(([fileName, exifValues]) => {
+ Object.entries(expectedState["exif"]).map(([fileName, exifValues]) => {
const matchingFile = files.find(
- (file) => file.metadata.title === fileName
+ (file) => file.metadata.title === fileName,
);
if (!matchingFile) {
throw Error(`exifDataParsingCheck failed , ${fileName} missing`);
}
if (
- exifValues['creation_time'] &&
- exifValues['creation_time'] !== matchingFile.metadata.creationTime
+ exifValues["creation_time"] &&
+ exifValues["creation_time"] !== matchingFile.metadata.creationTime
) {
throw Error(`exifDataParsingCheck failed ❌ ,
for ${fileName}
- expected: ${exifValues['creation_time']} got: ${matchingFile.metadata.creationTime}`);
+ expected: ${exifValues["creation_time"]} got: ${matchingFile.metadata.creationTime}`);
}
if (
- exifValues['location'] &&
+ exifValues["location"] &&
(Math.abs(
- exifValues['location']['latitude'] -
- matchingFile.metadata.latitude
+ exifValues["location"]["latitude"] -
+ matchingFile.metadata.latitude,
) > 1 ||
Math.abs(
- exifValues['location']['longitude'] -
- matchingFile.metadata.longitude
+ exifValues["location"]["longitude"] -
+ matchingFile.metadata.longitude,
) > 1)
) {
throw Error(`exifDataParsingCheck failed ❌ ,
for ${fileName}
- expected: ${JSON.stringify(exifValues['location'])}
+ expected: ${JSON.stringify(exifValues["location"])}
got: [${matchingFile.metadata.latitude},${
matchingFile.metadata.longitude
}]`);
}
});
- console.log('exif data parsing check passed βœ…');
+ console.log("exif data parsing check passed βœ…");
}
async function fileDimensionExtractionCheck(expectedState) {
const files = await getLocalFiles();
- Object.entries(expectedState['file_dimensions']).map(
+ Object.entries(expectedState["file_dimensions"]).map(
([fileName, dimensions]) => {
const matchingFile = files.find(
- (file) => file.metadata.title === fileName
+ (file) => file.metadata.title === fileName,
);
if (!matchingFile) {
throw Error(
- `fileDimensionExtractionCheck failed , ${fileName} missing`
+ `fileDimensionExtractionCheck failed , ${fileName} missing`,
);
}
if (
- dimensions['width'] &&
- dimensions['width'] !== matchingFile.pubMagicMetadata.data.w &&
- dimensions['height'] &&
- dimensions['height'] !== matchingFile.pubMagicMetadata.data.h
+ dimensions["width"] &&
+ dimensions["width"] !== matchingFile.pubMagicMetadata.data.w &&
+ dimensions["height"] &&
+ dimensions["height"] !== matchingFile.pubMagicMetadata.data.h
) {
throw Error(`fileDimensionExtractionCheck failed ❌ ,
for ${fileName}
- expected: ${dimensions['width']} x ${dimensions['height']} got: ${matchingFile.pubMagicMetadata.data.w} x ${matchingFile.pubMagicMetadata.data.h}`);
+ expected: ${dimensions["width"]} x ${dimensions["height"]} got: ${matchingFile.pubMagicMetadata.data.w} x ${matchingFile.pubMagicMetadata.data.h}`);
}
- }
+ },
);
- console.log('file dimension extraction check passed βœ…');
+ console.log("file dimension extraction check passed βœ…");
}
async function googleMetadataReadingCheck(expectedState) {
const files = await getLocalFiles();
- Object.entries(expectedState['google_import']).map(
+ Object.entries(expectedState["google_import"]).map(
([fileName, metadata]) => {
const matchingFile = files.find(
- (file) => file.metadata.title === fileName
+ (file) => file.metadata.title === fileName,
);
if (!matchingFile) {
throw Error(
- `exifDataParsingCheck failed , ${fileName} missing`
+ `exifDataParsingCheck failed , ${fileName} missing`,
);
}
if (
- metadata['creation_time'] &&
- metadata['creation_time'] !== matchingFile.metadata.creationTime
+ metadata["creation_time"] &&
+ metadata["creation_time"] !== matchingFile.metadata.creationTime
) {
throw Error(`googleMetadataJSON reading check failed ❌ ,
for ${fileName}
- expected: ${metadata['creation_time']} got: ${matchingFile.metadata.creationTime}`);
+ expected: ${metadata["creation_time"]} got: ${matchingFile.metadata.creationTime}`);
}
if (
- metadata['location'] &&
+ metadata["location"] &&
(Math.abs(
- metadata['location']['latitude'] -
- matchingFile.metadata.latitude
+ metadata["location"]["latitude"] -
+ matchingFile.metadata.latitude,
) > 1 ||
Math.abs(
- metadata['location']['longitude'] -
- matchingFile.metadata.longitude
+ metadata["location"]["longitude"] -
+ matchingFile.metadata.longitude,
) > 1)
) {
throw Error(`googleMetadataJSON reading check failed ❌ ,
for ${fileName}
expected: ${JSON.stringify(
- metadata['location']
+ metadata["location"],
)}
got: [${matchingFile.metadata.latitude},${
matchingFile.metadata.longitude
}]`);
}
- }
+ },
);
- console.log('googleMetadataJSON reading check passed βœ…');
+ console.log("googleMetadataJSON reading check passed βœ…");
}
function parseDateTimeFromFileNameTest() {
@@ -388,10 +388,10 @@ function parseDateTimeFromFileNameTest() {
throw Error(
`parseDateTimeFromFileNameTest failed ❌ ,
for ${fileName}
- expected: ${expectedDateTime} got: ${formattedDateTime}`
+ expected: ${expectedDateTime} got: ${formattedDateTime}`,
);
}
- }
+ },
);
DATE_TIME_PARSING_TEST_FILE_NAMES_MUST_FAIL.forEach((fileName) => {
const dateTime = tryToParseDateTime(fileName);
@@ -399,18 +399,18 @@ function parseDateTimeFromFileNameTest() {
throw Error(
`parseDateTimeFromFileNameTest failed ❌ ,
for ${fileName}
- expected: null got: ${dateTime}`
+ expected: null got: ${dateTime}`,
);
}
});
- console.log('parseDateTimeFromFileNameTest passed βœ…');
+ console.log("parseDateTimeFromFileNameTest passed βœ…");
}
function mappingFileAndJSONFileCheck() {
FILE_NAME_TO_JSON_NAME.forEach(({ filename, jsonFilename }) => {
const jsonFileNameGeneratedKey = getMetadataJSONMapKeyForJSON(
0,
- jsonFilename
+ jsonFilename,
);
let fileNameGeneratedKey = getMetadataJSONMapKeyForFile(0, filename);
if (
@@ -419,7 +419,7 @@ function mappingFileAndJSONFileCheck() {
) {
fileNameGeneratedKey = getClippedMetadataJSONMapKeyForFile(
0,
- filename
+ filename,
);
}
@@ -427,11 +427,11 @@ function mappingFileAndJSONFileCheck() {
throw Error(
`mappingFileAndJSONFileCheck failed ❌ ,
for ${filename}
- expected: ${jsonFileNameGeneratedKey} got: ${fileNameGeneratedKey}`
+ expected: ${jsonFileNameGeneratedKey} got: ${fileNameGeneratedKey}`,
);
}
});
- console.log('mappingFileAndJSONFileCheck passed βœ…');
+ console.log("mappingFileAndJSONFileCheck passed βœ…");
}
// format: YYYY-MM-DD HH:MM:SS
diff --git a/apps/photos/tests/zip-file-reading.test.ts b/apps/photos/tests/zip-file-reading.test.ts
index 3095a44d0c..0152e58972 100644
--- a/apps/photos/tests/zip-file-reading.test.ts
+++ b/apps/photos/tests/zip-file-reading.test.ts
@@ -1,10 +1,10 @@
-import { DataStream } from 'types/upload';
-import ElectronAPIs from '@ente/shared/electron';
-import { FILE_READER_CHUNK_SIZE, PICKED_UPLOAD_TYPE } from 'constants/upload';
-import { getFileStream, getElectronFileStream } from 'services/readerService';
-import { getFileNameSize } from '@ente/shared/logging/web';
-import isElectron from 'is-electron';
-import { getImportSuggestion } from 'utils/upload';
+import ElectronAPIs from "@ente/shared/electron";
+import { getFileNameSize } from "@ente/shared/logging/web";
+import { FILE_READER_CHUNK_SIZE, PICKED_UPLOAD_TYPE } from "constants/upload";
+import isElectron from "is-electron";
+import { getElectronFileStream, getFileStream } from "services/readerService";
+import { DataStream } from "types/upload";
+import { getImportSuggestion } from "utils/upload";
// This was for used to verify that converting from the browser readable stream
// to the node readable stream correctly handles files that align on the 4 MB
@@ -13,24 +13,24 @@ import { getImportSuggestion } from 'utils/upload';
export const testZipFileReading = async () => {
try {
if (!isElectron()) {
- console.log('testZipFileReading Check is for desktop only');
+ console.log("testZipFileReading Check is for desktop only");
return;
}
if (!process.env.NEXT_PUBLIC_FILE_READING_TEST_ZIP_PATH) {
throw Error(
- 'upload test failed NEXT_PUBLIC_FILE_READING_TEST_ZIP_PATH missing'
+ "upload test failed NEXT_PUBLIC_FILE_READING_TEST_ZIP_PATH missing",
);
}
const files = await ElectronAPIs.getElectronFilesFromGoogleZip(
- process.env.NEXT_PUBLIC_FILE_READING_TEST_ZIP_PATH
+ process.env.NEXT_PUBLIC_FILE_READING_TEST_ZIP_PATH,
);
if (!files?.length) {
throw Error(
`testZipFileReading Check failed ❌
- No files selected`
+ No files selected`,
);
}
- console.log('test zip file reading check started');
+ console.log("test zip file reading check started");
let i = 0;
for (const file of files) {
i++;
@@ -40,7 +40,7 @@ export const testZipFileReading = async () => {
} else {
filedata = await getElectronFileStream(
file,
- FILE_READER_CHUNK_SIZE
+ FILE_READER_CHUNK_SIZE,
);
}
const streamReader = filedata.stream.getReader();
@@ -50,10 +50,10 @@ export const testZipFileReading = async () => {
throw Error(
`testZipFileReading Check failed ❌
${getFileNameSize(
- file
+ file,
)} less than expected chunks, expected: ${
filedata.chunkCount
- }, got ${i - 1}`
+ }, got ${i - 1}`,
);
}
}
@@ -63,15 +63,15 @@ export const testZipFileReading = async () => {
throw Error(
`testZipFileReading Check failed ❌
${getFileNameSize(
- file
+ file,
)} more than expected chunks, expected: ${
filedata.chunkCount
- }`
+ }`,
);
}
console.log(`${i}/${files.length} passed βœ…`);
}
- console.log('test zip file reading check passed βœ…');
+ console.log("test zip file reading check passed βœ…");
} catch (e) {
console.log(e);
}
@@ -82,29 +82,29 @@ export const testZipFileReading = async () => {
export const testZipWithRootFileReadingTest = async () => {
try {
if (!isElectron()) {
- console.log('testZipFileReading Check is for desktop only');
+ console.log("testZipFileReading Check is for desktop only");
return;
}
if (!process.env.NEXT_PUBLIC_ZIP_WITH_ROOT_FILE_PATH) {
throw Error(
- 'upload test failed NEXT_PUBLIC_ZIP_WITH_ROOT_FILE_PATH missing'
+ "upload test failed NEXT_PUBLIC_ZIP_WITH_ROOT_FILE_PATH missing",
);
}
const files = await ElectronAPIs.getElectronFilesFromGoogleZip(
- process.env.NEXT_PUBLIC_ZIP_WITH_ROOT_FILE_PATH
+ process.env.NEXT_PUBLIC_ZIP_WITH_ROOT_FILE_PATH,
);
const importSuggestion = getImportSuggestion(
PICKED_UPLOAD_TYPE.ZIPS,
- files
+ files,
);
if (!importSuggestion.rootFolderName) {
throw Error(
`testZipWithRootFileReadingTest Check failed ❌
- rootFolderName is missing`
+ rootFolderName is missing`,
);
}
- console.log('testZipWithRootFileReadingTest passed βœ…');
+ console.log("testZipWithRootFileReadingTest passed βœ…");
} catch (e) {
console.log(e);
}
diff --git a/packages/accounts/.eslintrc.js b/packages/accounts/.eslintrc.js
index 60466d6e16..556f3b6392 100644
--- a/packages/accounts/.eslintrc.js
+++ b/packages/accounts/.eslintrc.js
@@ -3,11 +3,11 @@ module.exports = {
// This is required here to ensure desktop picks the right eslint config, where this app is
// packaged as a submodule.
root: true,
- extends: ['@ente/eslint-config'],
- parser: '@typescript-eslint/parser',
+ extends: ["@ente/eslint-config"],
+ parser: "@typescript-eslint/parser",
parserOptions: {
tsconfigRootDir: __dirname,
- project: './tsconfig.json',
+ project: "./tsconfig.json",
},
- ignorePatterns: ['.eslintrc.js'],
+ ignorePatterns: [".eslintrc.js"],
};
diff --git a/packages/accounts/api/srp.ts b/packages/accounts/api/srp.ts
index f401e4df54..8a737a0d68 100644
--- a/packages/accounts/api/srp.ts
+++ b/packages/accounts/api/srp.ts
@@ -1,5 +1,5 @@
-import HTTPService from '@ente/shared/network/HTTPService';
-import { getEndpoint } from '@ente/shared/network/api';
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getEndpoint } from "@ente/shared/network/api";
import {
CompleteSRPSetupRequest,
@@ -12,15 +12,15 @@ import {
SetupSRPResponse,
UpdateSRPAndKeysRequest,
UpdateSRPAndKeysResponse,
-} from '@ente/accounts/types/srp';
-import { ApiError, CustomError } from '@ente/shared/error';
-import { HttpStatusCode } from 'axios';
-import { logError } from '@ente/shared/sentry';
+} from "@ente/accounts/types/srp";
+import { ApiError, CustomError } from "@ente/shared/error";
+import { logError } from "@ente/shared/sentry";
+import { HttpStatusCode } from "axios";
const ENDPOINT = getEndpoint();
export const getSRPAttributes = async (
- email: string
+ email: string,
): Promise<SRPAttributes | null> => {
try {
const resp = await HTTPService.get(`${ENDPOINT}/users/srp/attributes`, {
@@ -28,14 +28,14 @@ export const getSRPAttributes = async (
});
return (resp.data as GetSRPAttributesResponse).attributes;
} catch (e) {
- logError(e, 'failed to get SRP attributes');
+ logError(e, "failed to get SRP attributes");
return null;
}
};
export const startSRPSetup = async (
token: string,
- setupSRPRequest: SetupSRPRequest
+ setupSRPRequest: SetupSRPRequest,
): Promise<SetupSRPResponse> => {
try {
const resp = await HTTPService.post(
@@ -43,20 +43,20 @@ export const startSRPSetup = async (
setupSRPRequest,
undefined,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
return resp.data as SetupSRPResponse;
} catch (e) {
- logError(e, 'failed to post SRP attributes');
+ logError(e, "failed to post SRP attributes");
throw e;
}
};
export const completeSRPSetup = async (
token: string,
- completeSRPSetupRequest: CompleteSRPSetupRequest
+ completeSRPSetupRequest: CompleteSRPSetupRequest,
) => {
try {
const resp = await HTTPService.post(
@@ -64,12 +64,12 @@ export const completeSRPSetup = async (
completeSRPSetupRequest,
undefined,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
return resp.data as CompleteSRPSetupResponse;
} catch (e) {
- logError(e, 'failed to complete SRP setup');
+ logError(e, "failed to complete SRP setup");
throw e;
}
};
@@ -81,11 +81,11 @@ export const createSRPSession = async (srpUserID: string, srpA: string) => {
{
srpUserID,
srpA,
- }
+ },
);
return resp.data as CreateSRPSessionResponse;
} catch (e) {
- logError(e, 'createSRPSession failed');
+ logError(e, "createSRPSession failed");
throw e;
}
};
@@ -93,7 +93,7 @@ export const createSRPSession = async (srpUserID: string, srpA: string) => {
export const verifySRPSession = async (
sessionID: string,
srpUserID: string,
- srpM1: string
+ srpM1: string,
) => {
try {
const resp = await HTTPService.post(
@@ -103,11 +103,11 @@ export const verifySRPSession = async (
srpUserID,
srpM1,
},
- undefined
+ undefined,
);
return resp.data as SRPVerificationResponse;
} catch (e) {
- logError(e, 'verifySRPSession failed');
+ logError(e, "verifySRPSession failed");
if (
e instanceof ApiError &&
e.httpStatusCode === HttpStatusCode.Unauthorized
@@ -121,7 +121,7 @@ export const verifySRPSession = async (
export const updateSRPAndKeys = async (
token: string,
- updateSRPAndKeyRequest: UpdateSRPAndKeysRequest
+ updateSRPAndKeyRequest: UpdateSRPAndKeysRequest,
): Promise<UpdateSRPAndKeysResponse> => {
try {
const resp = await HTTPService.post(
@@ -129,12 +129,12 @@ export const updateSRPAndKeys = async (
updateSRPAndKeyRequest,
null,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
return resp.data as UpdateSRPAndKeysResponse;
} catch (e) {
- logError(e, 'updateSRPAndKeys failed');
+ logError(e, "updateSRPAndKeys failed");
throw e;
}
};
diff --git a/packages/accounts/api/user.ts b/packages/accounts/api/user.ts
index 50e266fc4f..def8fa8c4a 100644
--- a/packages/accounts/api/user.ts
+++ b/packages/accounts/api/user.ts
@@ -1,20 +1,20 @@
-import HTTPService from '@ente/shared/network/HTTPService';
-import { getEndpoint } from '@ente/shared/network/api';
+import HTTPService from "@ente/shared/network/HTTPService";
+import { getEndpoint } from "@ente/shared/network/api";
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
-import { KeyAttributes } from '@ente/shared/user/types';
-import { ApiError, CustomError } from '@ente/shared/error';
-import { HttpStatusCode } from 'axios';
import {
- UserVerificationResponse,
+ RecoveryKey,
TwoFactorRecoveryResponse,
- TwoFactorVerificationResponse,
TwoFactorSecret,
- RecoveryKey,
-} from '@ente/accounts/types/user';
-import { B64EncryptionResult } from '@ente/shared/crypto/types';
-import { logError } from '@ente/shared/sentry';
-import { APPS, OTT_CLIENTS } from '@ente/shared/apps/constants';
+ TwoFactorVerificationResponse,
+ UserVerificationResponse,
+} from "@ente/accounts/types/user";
+import { APPS, OTT_CLIENTS } from "@ente/shared/apps/constants";
+import { B64EncryptionResult } from "@ente/shared/crypto/types";
+import { ApiError, CustomError } from "@ente/shared/error";
+import { logError } from "@ente/shared/sentry";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
+import { KeyAttributes } from "@ente/shared/user/types";
+import { HttpStatusCode } from "axios";
const ENDPOINT = getEndpoint();
@@ -26,7 +26,7 @@ export const sendOtt = (appName: APPS, email: string) => {
};
export const verifyOtt = (email: string, ott: string, referral: string) => {
- const cleanedReferral = `web:${referral?.trim() || ''}`;
+ const cleanedReferral = `web:${referral?.trim() || ""}`;
return HTTPService.post(`${ENDPOINT}/users/verify-email`, {
email,
ott,
@@ -40,15 +40,15 @@ export const putAttributes = (token: string, keyAttributes: KeyAttributes) =>
{ keyAttributes },
undefined,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
export const _logout = async () => {
try {
const token = getToken();
await HTTPService.post(`${ENDPOINT}/users/logout`, null, undefined, {
- 'X-Auth-Token': token,
+ "X-Auth-Token": token,
});
} catch (e) {
// ignore if token missing can be triggered during sign up.
@@ -62,7 +62,7 @@ export const _logout = async () => {
) {
return;
}
- logError(e, '/users/logout failed');
+ logError(e, "/users/logout failed");
throw e;
}
};
@@ -74,7 +74,7 @@ export const verifyTwoFactor = async (code: string, sessionID: string) => {
code,
sessionID,
},
- null
+ null,
);
return resp.data as UserVerificationResponse;
};
@@ -103,16 +103,16 @@ export const changeEmail = async (email: string, ott: string) => {
},
null,
{
- 'X-Auth-Token': getToken(),
- }
+ "X-Auth-Token": getToken(),
+ },
);
};
export const sendOTTForEmailChange = async (email: string) => {
await HTTPService.post(`${ENDPOINT}/users/ott`, {
email,
- client: 'web',
- purpose: 'change',
+ client: "web",
+ purpose: "change",
});
};
@@ -122,15 +122,15 @@ export const setupTwoFactor = async () => {
null,
null,
{
- 'X-Auth-Token': getToken(),
- }
+ "X-Auth-Token": getToken(),
+ },
);
return resp.data as TwoFactorSecret;
};
export const enableTwoFactor = async (
code: string,
- recoveryEncryptedTwoFactorSecret: B64EncryptionResult
+ recoveryEncryptedTwoFactorSecret: B64EncryptionResult,
) => {
await HTTPService.post(
`${ENDPOINT}/users/two-factor/enable`,
@@ -143,18 +143,18 @@ export const enableTwoFactor = async (
},
null,
{
- 'X-Auth-Token': getToken(),
- }
+ "X-Auth-Token": getToken(),
+ },
);
};
export const setRecoveryKey = (token: string, recoveryKey: RecoveryKey) =>
HTTPService.put(`${ENDPOINT}/users/recovery-key`, recoveryKey, null, {
- 'X-Auth-Token': token,
+ "X-Auth-Token": token,
});
export const disableTwoFactor = async () => {
await HTTPService.post(`${ENDPOINT}/users/two-factor/disable`, null, null, {
- 'X-Auth-Token': getToken(),
+ "X-Auth-Token": getToken(),
});
};
diff --git a/packages/accounts/components/ChangeEmail.tsx b/packages/accounts/components/ChangeEmail.tsx
index e2055fdb24..42a0d8103e 100644
--- a/packages/accounts/components/ChangeEmail.tsx
+++ b/packages/accounts/components/ChangeEmail.tsx
@@ -1,18 +1,18 @@
-import { Formik, FormikHelpers } from 'formik';
-import React, { useRef, useState } from 'react';
-import * as Yup from 'yup';
-import SubmitButton from '@ente/shared/components/SubmitButton';
-import { changeEmail, sendOTTForEmailChange } from '@ente/accounts/api/user';
-import { getData, LS_KEYS, setData } from '@ente/shared/storage/localStorage';
-import { Alert, Box, TextField } from '@mui/material';
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import LinkButton from '@ente/shared/components/LinkButton';
-import FormPaperFooter from '@ente/shared/components/Form/FormPaper/Footer';
-import { sleep } from '@ente/shared/utils';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
-import { APP_HOMES } from '@ente/shared/apps/constants';
-import { PageProps } from '@ente/shared/apps/types';
+import { changeEmail, sendOTTForEmailChange } from "@ente/accounts/api/user";
+import { APP_HOMES } from "@ente/shared/apps/constants";
+import { PageProps } from "@ente/shared/apps/types";
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import FormPaperFooter from "@ente/shared/components/Form/FormPaper/Footer";
+import LinkButton from "@ente/shared/components/LinkButton";
+import SubmitButton from "@ente/shared/components/SubmitButton";
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
+import { sleep } from "@ente/shared/utils";
+import { Alert, Box, TextField } from "@mui/material";
+import { Formik, FormikHelpers } from "formik";
+import { t } from "i18next";
+import { useRef, useState } from "react";
+import { Trans } from "react-i18next";
+import * as Yup from "yup";
interface formValues {
email: string;
@@ -29,7 +29,7 @@ function ChangeEmailForm({ appName, router }: PageProps) {
const requestOTT = async (
{ email }: formValues,
- { setFieldError }: FormikHelpers<formValues>
+ { setFieldError }: FormikHelpers<formValues>,
) => {
try {
setLoading(true);
@@ -41,14 +41,14 @@ function ChangeEmailForm({ appName, router }: PageProps) {
ottInputRef.current?.focus();
}, 250);
} catch (e) {
- setFieldError('email', t('EMAIl_ALREADY_OWNED'));
+ setFieldError("email", t("EMAIl_ALREADY_OWNED"));
}
setLoading(false);
};
const requestEmailChange = async (
{ email, ott }: formValues,
- { setFieldError }: FormikHelpers<formValues>
+ { setFieldError }: FormikHelpers<formValues>,
) => {
try {
setLoading(true);
@@ -60,7 +60,7 @@ function ChangeEmailForm({ appName, router }: PageProps) {
goToApp();
} catch (e) {
setLoading(false);
- setFieldError('ott', t('INCORRECT_CODE'));
+ setFieldError("ott", t("INCORRECT_CODE"));
}
};
@@ -70,29 +70,31 @@ function ChangeEmailForm({ appName, router }: PageProps) {
return (
<Formik<formValues>
- initialValues={{ email: '' }}
+ initialValues={{ email: "" }}
validationSchema={Yup.object().shape({
email: Yup.string()
- .email(t('EMAIL_ERROR'))
- .required(t('REQUIRED')),
- ott: ottInputVisible && Yup.string().required(t('REQUIRED')),
+ .email(t("EMAIL_ERROR"))
+ .required(t("REQUIRED")),
+ ott: ottInputVisible && Yup.string().required(t("REQUIRED")),
})}
validateOnChange={false}
validateOnBlur={false}
- onSubmit={!ottInputVisible ? requestOTT : requestEmailChange}>
+ onSubmit={!ottInputVisible ? requestOTT : requestEmailChange}
+ >
{({ values, errors, handleChange, handleSubmit }) => (
<>
{showMessage && (
<Alert
color="success"
- onClose={() => setShowMessage(false)}>
+ onClose={() => setShowMessage(false)}
+ >
<Trans
i18nKey="EMAIL_SENT"
components={{
a: (
<Box
color="text.muted"
- component={'span'}
+ component={"span"}
/>
),
}}
@@ -108,9 +110,9 @@ function ChangeEmailForm({ appName, router }: PageProps) {
readOnly: ottInputVisible,
}}
type="email"
- label={t('ENTER_EMAIL')}
+ label={t("ENTER_EMAIL")}
value={values.email}
- onChange={handleChange('email')}
+ onChange={handleChange("email")}
error={Boolean(errors.email)}
helperText={errors.email}
autoFocus
@@ -120,9 +122,9 @@ function ChangeEmailForm({ appName, router }: PageProps) {
<TextField
fullWidth
type="text"
- label={t('ENTER_OTT')}
+ label={t("ENTER_OTT")}
value={values.ott}
- onChange={handleChange('ott')}
+ onChange={handleChange("ott")}
error={Boolean(errors.ott)}
helperText={errors.ott}
disabled={loading}
@@ -134,8 +136,8 @@ function ChangeEmailForm({ appName, router }: PageProps) {
loading={loading}
buttonText={
!ottInputVisible
- ? t('SEND_OTT')
- : t('VERIFY')
+ ? t("SEND_OTT")
+ : t("VERIFY")
}
/>
</VerticallyCentered>
@@ -143,18 +145,18 @@ function ChangeEmailForm({ appName, router }: PageProps) {
<FormPaperFooter
style={{
- justifyContent: ottInputVisible && 'space-between',
- }}>
+ justifyContent: ottInputVisible && "space-between",
+ }}
+ >
{ottInputVisible && (
<LinkButton
- onClick={() =>
- setShowOttInputVisibility(false)
- }>
- {t('CHANGE_EMAIL')}?
+ onClick={() => setShowOttInputVisibility(false)}
+ >
+ {t("CHANGE_EMAIL")}?
</LinkButton>
)}
<LinkButton onClick={goToApp}>
- {t('GO_BACK')}
+ {t("GO_BACK")}
</LinkButton>
</FormPaperFooter>
</>
diff --git a/packages/accounts/components/Login.tsx b/packages/accounts/components/Login.tsx
index c6e095b761..b515cac16e 100644
--- a/packages/accounts/components/Login.tsx
+++ b/packages/accounts/components/Login.tsx
@@ -1,18 +1,18 @@
-import { useRouter } from 'next/router';
-import { getSRPAttributes } from '../api/srp';
-import { sendOtt } from '../api/user';
-import { setData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import { PAGES } from '../constants/pages';
-import FormPaperTitle from '@ente/shared/components/Form/FormPaper/Title';
-import FormPaperFooter from '@ente/shared/components/Form/FormPaper/Footer';
-import LinkButton from '@ente/shared/components/LinkButton';
-import { t } from 'i18next';
-import { addLocalLog } from '@ente/shared/logging';
-import { Input } from '@mui/material';
+import { APPS } from "@ente/shared/apps/constants";
+import FormPaperFooter from "@ente/shared/components/Form/FormPaper/Footer";
+import FormPaperTitle from "@ente/shared/components/Form/FormPaper/Title";
+import LinkButton from "@ente/shared/components/LinkButton";
import SingleInputForm, {
SingleInputFormProps,
-} from '@ente/shared/components/SingleInputForm';
-import { APPS } from '@ente/shared/apps/constants';
+} from "@ente/shared/components/SingleInputForm";
+import { addLocalLog } from "@ente/shared/logging";
+import { LS_KEYS, setData } from "@ente/shared/storage/localStorage";
+import { Input } from "@mui/material";
+import { t } from "i18next";
+import { useRouter } from "next/router";
+import { getSRPAttributes } from "../api/srp";
+import { sendOtt } from "../api/user";
+import { PAGES } from "../constants/pages";
interface LoginProps {
signUp: () => void;
@@ -22,15 +22,15 @@ interface LoginProps {
export default function Login(props: LoginProps) {
const router = useRouter();
- const loginUser: SingleInputFormProps['callback'] = async (
+ const loginUser: SingleInputFormProps["callback"] = async (
email,
- setFieldError
+ setFieldError,
) => {
try {
setData(LS_KEYS.USER, { email });
const srpAttributes = await getSRPAttributes(email);
addLocalLog(
- () => ` srpAttributes: ${JSON.stringify(srpAttributes)}`
+ () => ` srpAttributes: ${JSON.stringify(srpAttributes)}`,
);
if (!srpAttributes || srpAttributes.isEmailMFAEnabled) {
await sendOtt(props.appName, email);
@@ -41,10 +41,10 @@ export default function Login(props: LoginProps) {
}
} catch (e) {
if (e instanceof Error) {
- setFieldError(`${t('UNKNOWN_ERROR')} (reason:${e.message})`);
+ setFieldError(`${t("UNKNOWN_ERROR")} (reason:${e.message})`);
} else {
setFieldError(
- `${t('UNKNOWN_ERROR')} (reason:${JSON.stringify(e)})`
+ `${t("UNKNOWN_ERROR")} (reason:${JSON.stringify(e)})`,
);
}
}
@@ -52,21 +52,21 @@ export default function Login(props: LoginProps) {
return (
<>
- <FormPaperTitle>{t('LOGIN')}</FormPaperTitle>
+ <FormPaperTitle>{t("LOGIN")}</FormPaperTitle>
<SingleInputForm
callback={loginUser}
fieldType="email"
- placeholder={t('ENTER_EMAIL')}
- buttonText={t('LOGIN')}
+ placeholder={t("ENTER_EMAIL")}
+ buttonText={t("LOGIN")}
autoComplete="username"
hiddenPostInput={
- <Input sx={{ display: 'none' }} type="password" value="" />
+ <Input sx={{ display: "none" }} type="password" value="" />
}
/>
<FormPaperFooter>
<LinkButton onClick={props.signUp}>
- {t('NO_ACCOUNT')}
+ {t("NO_ACCOUNT")}
</LinkButton>
</FormPaperFooter>
</>
diff --git a/packages/accounts/components/PasswordStrength.tsx b/packages/accounts/components/PasswordStrength.tsx
index c6841a1f66..f30c6c85e2 100644
--- a/packages/accounts/components/PasswordStrength.tsx
+++ b/packages/accounts/components/PasswordStrength.tsx
@@ -1,9 +1,9 @@
-import { Typography } from '@mui/material';
-import { PasswordStrength } from '@ente/accounts/constants';
-import { useMemo } from 'react';
-import { t } from 'i18next';
-import { estimatePasswordStrength } from '@ente/accounts/utils';
-import { FlexWrapper } from '@ente/shared/components/Container';
+import { PasswordStrength } from "@ente/accounts/constants";
+import { estimatePasswordStrength } from "@ente/accounts/utils";
+import { FlexWrapper } from "@ente/shared/components/Container";
+import { Typography } from "@mui/material";
+import { t } from "i18next";
+import { useMemo } from "react";
export const PasswordStrengthHint = ({
password,
@@ -12,10 +12,10 @@ export const PasswordStrengthHint = ({
}): JSX.Element => {
const passwordStrength = useMemo(
() => estimatePasswordStrength(password),
- [password]
+ [password],
);
return (
- <FlexWrapper mt={'8px'} mb={'4px'}>
+ <FlexWrapper mt={"8px"} mb={"4px"}>
<Typography
variant="small"
sx={(theme) => ({
@@ -26,11 +26,12 @@ export const PasswordStrengthHint = ({
? theme.colors.warning.A500
: theme.colors.accent.A500,
})}
- textAlign={'left'}
- flex={1}>
+ textAlign={"left"}
+ flex={1}
+ >
{password
- ? t('PASSPHRASE_STRENGTH', { context: passwordStrength })
- : ''}
+ ? t("PASSPHRASE_STRENGTH", { context: passwordStrength })
+ : ""}
</Typography>
</FlexWrapper>
);
diff --git a/packages/accounts/components/SetPasswordForm.tsx b/packages/accounts/components/SetPasswordForm.tsx
index 436fd720d5..0c225dc005 100644
--- a/packages/accounts/components/SetPasswordForm.tsx
+++ b/packages/accounts/components/SetPasswordForm.tsx
@@ -1,13 +1,13 @@
-import React, { useState } from 'react';
-import { Formik } from 'formik';
-import * as Yup from 'yup';
-import SubmitButton from '@ente/shared/components/SubmitButton';
-import { Box, Input, TextField, Typography } from '@mui/material';
-import { PasswordStrengthHint } from './PasswordStrength';
-import { isWeakPassword } from '@ente/accounts/utils';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
-import ShowHidePassword from '@ente/shared/components/Form/ShowHidePassword';
+import { isWeakPassword } from "@ente/accounts/utils";
+import ShowHidePassword from "@ente/shared/components/Form/ShowHidePassword";
+import SubmitButton from "@ente/shared/components/SubmitButton";
+import { Box, Input, TextField, Typography } from "@mui/material";
+import { Formik } from "formik";
+import { t } from "i18next";
+import React, { useState } from "react";
+import { Trans } from "react-i18next";
+import * as Yup from "yup";
+import { PasswordStrengthHint } from "./PasswordStrength";
export interface SetPasswordFormProps {
userEmail: string;
@@ -15,8 +15,8 @@ export interface SetPasswordFormProps {
passphrase: string,
setFieldError: (
field: keyof SetPasswordFormValues,
- message: string
- ) => void
+ message: string,
+ ) => void,
) => Promise<void>;
buttonText: string;
}
@@ -33,7 +33,7 @@ function SetPasswordForm(props: SetPasswordFormProps) {
};
const handleMouseDownPassword = (
- event: React.MouseEvent<HTMLButtonElement>
+ event: React.MouseEvent<HTMLButtonElement>,
) => {
event.preventDefault();
};
@@ -45,9 +45,9 @@ function SetPasswordForm(props: SetPasswordFormProps) {
}: {
setFieldError: (
field: keyof SetPasswordFormValues,
- message: string
+ message: string,
) => void;
- }
+ },
) => {
setLoading(true);
try {
@@ -55,10 +55,10 @@ function SetPasswordForm(props: SetPasswordFormProps) {
if (passphrase === confirm) {
await props.callback(passphrase, setFieldError);
} else {
- setFieldError('confirm', t('PASSPHRASE_MATCH_ERROR'));
+ setFieldError("confirm", t("PASSPHRASE_MATCH_ERROR"));
}
} catch (e) {
- setFieldError('confirm', `${t('UNKNOWN_ERROR')} ${e.message}`);
+ setFieldError("confirm", `${t("UNKNOWN_ERROR")} ${e.message}`);
} finally {
setLoading(false);
}
@@ -66,22 +66,23 @@ function SetPasswordForm(props: SetPasswordFormProps) {
return (
<Formik<SetPasswordFormValues>
- initialValues={{ passphrase: '', confirm: '' }}
+ initialValues={{ passphrase: "", confirm: "" }}
validationSchema={Yup.object().shape({
- passphrase: Yup.string().required(t('REQUIRED')),
- confirm: Yup.string().required(t('REQUIRED')),
+ passphrase: Yup.string().required(t("REQUIRED")),
+ confirm: Yup.string().required(t("REQUIRED")),
})}
validateOnChange={false}
validateOnBlur={false}
- onSubmit={onSubmit}>
+ onSubmit={onSubmit}
+ >
{({ values, errors, handleChange, handleSubmit }) => (
<form noValidate onSubmit={handleSubmit}>
<Typography mb={2} color="text.muted" variant="small">
- {t('ENTER_ENC_PASSPHRASE')}
+ {t("ENTER_ENC_PASSPHRASE")}
</Typography>
<Input
- sx={{ display: 'none' }}
+ sx={{ display: "none" }}
name="email"
id="email"
autoComplete="username"
@@ -93,10 +94,10 @@ function SetPasswordForm(props: SetPasswordFormProps) {
name="password"
id="password"
autoComplete="new-password"
- type={showPassword ? 'text' : 'password'}
- label={t('PASSPHRASE_HINT')}
+ type={showPassword ? "text" : "password"}
+ label={t("PASSPHRASE_HINT")}
value={values.passphrase}
- onChange={handleChange('passphrase')}
+ onChange={handleChange("passphrase")}
error={Boolean(errors.passphrase)}
helperText={errors.passphrase}
autoFocus
@@ -121,9 +122,9 @@ function SetPasswordForm(props: SetPasswordFormProps) {
id="confirm-password"
autoComplete="new-password"
type="password"
- label={t('CONFIRM_PASSPHRASE')}
+ label={t("CONFIRM_PASSPHRASE")}
value={values.confirm}
- onChange={handleChange('confirm')}
+ onChange={handleChange("confirm")}
disabled={loading}
error={Boolean(errors.confirm)}
helperText={errors.confirm}
@@ -131,7 +132,7 @@ function SetPasswordForm(props: SetPasswordFormProps) {
<PasswordStrengthHint password={values.passphrase} />
<Typography my={2} variant="small">
- <Trans i18nKey={'PASSPHRASE_DISCLAIMER'} />
+ <Trans i18nKey={"PASSPHRASE_DISCLAIMER"} />
</Typography>
<Box my={4}>
@@ -146,8 +147,9 @@ function SetPasswordForm(props: SetPasswordFormProps) {
textAlign="center"
mt={1}
color="text.muted"
- variant="small">
- {t('KEY_GENERATION_IN_PROGRESS_MESSAGE')}
+ variant="small"
+ >
+ {t("KEY_GENERATION_IN_PROGRESS_MESSAGE")}
</Typography>
)}
</Box>
diff --git a/packages/accounts/components/SignUp.tsx b/packages/accounts/components/SignUp.tsx
index d7e80438e9..b2984f1085 100644
--- a/packages/accounts/components/SignUp.tsx
+++ b/packages/accounts/components/SignUp.tsx
@@ -1,22 +1,31 @@
-import React, { useState } from 'react';
-import { Formik, FormikHelpers } from 'formik';
-import * as Yup from 'yup';
-import { sendOtt } from '@ente/accounts/api/user';
-import { setData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import SubmitButton from '@ente/shared/components/SubmitButton';
+import { sendOtt } from "@ente/accounts/api/user";
+import { isWeakPassword } from "@ente/accounts/utils";
+import { generateKeyAndSRPAttributes } from "@ente/accounts/utils/srp";
+import SubmitButton from "@ente/shared/components/SubmitButton";
import {
generateAndSaveIntermediateKeyAttributes,
saveKeyInSessionStore,
-} from '@ente/shared/crypto/helpers';
-import { isWeakPassword } from '@ente/accounts/utils';
-import { generateKeyAndSRPAttributes } from '@ente/accounts/utils/srp';
+} from "@ente/shared/crypto/helpers";
+import { LS_KEYS, setData } from "@ente/shared/storage/localStorage";
+import { Formik, FormikHelpers } from "formik";
+import React, { useState } from "react";
+import * as Yup from "yup";
+import { PasswordStrengthHint } from "@ente/accounts/components/PasswordStrength";
+import { PAGES } from "@ente/accounts/constants/pages";
+import { APPS } from "@ente/shared/apps/constants";
+import { VerticallyCentered } from "@ente/shared/components//Container";
+import FormPaperFooter from "@ente/shared/components/Form/FormPaper/Footer";
+import FormPaperTitle from "@ente/shared/components/Form/FormPaper/Title";
+import ShowHidePassword from "@ente/shared/components/Form/ShowHidePassword";
+import LinkButton from "@ente/shared/components/LinkButton";
+import { logError } from "@ente/shared/sentry";
import {
setJustSignedUp,
setLocalReferralSource,
-} from '@ente/shared/storage/localStorage/helpers';
-import { SESSION_KEYS } from '@ente/shared/storage/sessionStorage';
-import { PAGES } from '@ente/accounts/constants/pages';
+} from "@ente/shared/storage/localStorage/helpers";
+import { SESSION_KEYS } from "@ente/shared/storage/sessionStorage";
+import InfoOutlined from "@mui/icons-material/InfoOutlined";
import {
Box,
Checkbox,
@@ -28,19 +37,10 @@ import {
TextField,
Tooltip,
Typography,
-} from '@mui/material';
-import FormPaperTitle from '@ente/shared/components/Form/FormPaper/Title';
-import LinkButton from '@ente/shared/components/LinkButton';
-import FormPaperFooter from '@ente/shared/components/Form/FormPaper/Footer';
-import { VerticallyCentered } from '@ente/shared/components//Container';
-import { PasswordStrengthHint } from '@ente/accounts/components/PasswordStrength';
-import { Trans } from 'react-i18next';
-import { t } from 'i18next';
-import ShowHidePassword from '@ente/shared/components/Form/ShowHidePassword';
-import { APPS } from '@ente/shared/apps/constants';
-import { NextRouter } from 'next/router';
-import { logError } from '@ente/shared/sentry';
-import InfoOutlined from '@mui/icons-material/InfoOutlined';
+} from "@mui/material";
+import { t } from "i18next";
+import { NextRouter } from "next/router";
+import { Trans } from "react-i18next";
interface FormValues {
email: string;
@@ -65,18 +65,18 @@ export default function SignUp({ router, appName, login }: SignUpProps) {
};
const handleMouseDownPassword = (
- event: React.MouseEvent<HTMLButtonElement>
+ event: React.MouseEvent<HTMLButtonElement>,
) => {
event.preventDefault();
};
const registerUser = async (
{ email, passphrase, confirm, referral }: FormValues,
- { setFieldError }: FormikHelpers<FormValues>
+ { setFieldError }: FormikHelpers<FormValues>,
) => {
try {
if (passphrase !== confirm) {
- setFieldError('confirm', t('PASSPHRASE_MATCH_ERROR'));
+ setFieldError("confirm", t("PASSPHRASE_MATCH_ERROR"));
return;
}
setLoading(true);
@@ -85,7 +85,7 @@ export default function SignUp({ router, appName, login }: SignUpProps) {
setLocalReferralSource(referral);
await sendOtt(appName, email);
} catch (e) {
- setFieldError('confirm', `${t('UNKNOWN_ERROR')} ${e.message}`);
+ setFieldError("confirm", `${t("UNKNOWN_ERROR")} ${e.message}`);
throw e;
}
try {
@@ -97,45 +97,46 @@ export default function SignUp({ router, appName, login }: SignUpProps) {
await generateAndSaveIntermediateKeyAttributes(
passphrase,
keyAttributes,
- masterKey
+ masterKey,
);
await saveKeyInSessionStore(
SESSION_KEYS.ENCRYPTION_KEY,
- masterKey
+ masterKey,
);
setJustSignedUp(true);
router.push(PAGES.VERIFY);
} catch (e) {
- setFieldError('confirm', t('PASSWORD_GENERATION_FAILED'));
+ setFieldError("confirm", t("PASSWORD_GENERATION_FAILED"));
throw e;
}
} catch (err) {
- logError(err, 'signup failed');
+ logError(err, "signup failed");
}
setLoading(false);
};
return (
<>
- <FormPaperTitle> {t('SIGN_UP')}</FormPaperTitle>
+ <FormPaperTitle> {t("SIGN_UP")}</FormPaperTitle>
<Formik<FormValues>
initialValues={{
- email: '',
- passphrase: '',
- confirm: '',
- referral: '',
+ email: "",
+ passphrase: "",
+ confirm: "",
+ referral: "",
}}
validationSchema={Yup.object().shape({
email: Yup.string()
- .email(t('EMAIL_ERROR'))
- .required(t('REQUIRED')),
- passphrase: Yup.string().required(t('REQUIRED')),
- confirm: Yup.string().required(t('REQUIRED')),
+ .email(t("EMAIL_ERROR"))
+ .required(t("REQUIRED")),
+ passphrase: Yup.string().required(t("REQUIRED")),
+ confirm: Yup.string().required(t("REQUIRED")),
})}
validateOnChange={false}
validateOnBlur={false}
- onSubmit={registerUser}>
+ onSubmit={registerUser}
+ >
{({
values,
errors,
@@ -150,9 +151,9 @@ export default function SignUp({ router, appName, login }: SignUpProps) {
name="email"
autoComplete="username"
type="email"
- label={t('ENTER_EMAIL')}
+ label={t("ENTER_EMAIL")}
value={values.email}
- onChange={handleChange('email')}
+ onChange={handleChange("email")}
error={Boolean(errors.email)}
helperText={errors.email}
autoFocus
@@ -164,10 +165,10 @@ export default function SignUp({ router, appName, login }: SignUpProps) {
id="password"
name="password"
autoComplete="new-password"
- type={showPassword ? 'text' : 'password'}
- label={t('PASSPHRASE_HINT')}
+ type={showPassword ? "text" : "password"}
+ label={t("PASSPHRASE_HINT")}
value={values.passphrase}
- onChange={handleChange('passphrase')}
+ onChange={handleChange("passphrase")}
error={Boolean(errors.passphrase)}
helperText={errors.passphrase}
disabled={loading}
@@ -192,9 +193,9 @@ export default function SignUp({ router, appName, login }: SignUpProps) {
name="confirm-password"
autoComplete="new-password"
type="password"
- label={t('CONFIRM_PASSPHRASE')}
+ label={t("CONFIRM_PASSPHRASE")}
value={values.confirm}
- onChange={handleChange('confirm')}
+ onChange={handleChange("confirm")}
error={Boolean(errors.confirm)}
helperText={errors.confirm}
disabled={loading}
@@ -203,12 +204,13 @@ export default function SignUp({ router, appName, login }: SignUpProps) {
password={values.passphrase}
/>
- <Box sx={{ width: '100%' }}>
+ <Box sx={{ width: "100%" }}>
<Typography
- textAlign={'left'}
+ textAlign={"left"}
color="text.secondary"
- mt={'24px'}>
- {t('REFERRAL_CODE_HINT')}
+ mt={"24px"}
+ >
+ {t("REFERRAL_CODE_HINT")}
</Typography>
<TextField
hiddenLabel
@@ -216,11 +218,13 @@ export default function SignUp({ router, appName, login }: SignUpProps) {
endAdornment: (
<InputAdornment position="end">
<Tooltip
- title={t('REFERRAL_INFO')}>
+ title={t("REFERRAL_INFO")}
+ >
<IconButton
tabIndex={-1}
color="secondary"
- edge={'end'}>
+ edge={"end"}
+ >
<InfoOutlined />
</IconButton>
</Tooltip>
@@ -231,15 +235,15 @@ export default function SignUp({ router, appName, login }: SignUpProps) {
name="referral"
type="text"
value={values.referral}
- onChange={handleChange('referral')}
+ onChange={handleChange("referral")}
error={Boolean(errors.referral)}
disabled={loading}
/>
</Box>
- <FormGroup sx={{ width: '100%' }}>
+ <FormGroup sx={{ width: "100%" }}>
<FormControlLabel
sx={{
- color: 'text.muted',
+ color: "text.muted",
ml: 0,
mt: 2,
mb: 0,
@@ -258,7 +262,7 @@ export default function SignUp({ router, appName, login }: SignUpProps) {
label={
<Typography variant="small">
<Trans
- i18nKey={'TERMS_AND_CONDITIONS'}
+ i18nKey={"TERMS_AND_CONDITIONS"}
components={{
a: (
<Link
@@ -282,7 +286,7 @@ export default function SignUp({ router, appName, login }: SignUpProps) {
<Box mb={4}>
<SubmitButton
sx={{ my: 0 }}
- buttonText={t('CREATE_ACCOUNT')}
+ buttonText={t("CREATE_ACCOUNT")}
loading={loading}
disabled={
!acceptTerms ||
@@ -292,10 +296,11 @@ export default function SignUp({ router, appName, login }: SignUpProps) {
{loading && (
<Typography
mt={1}
- textAlign={'center'}
+ textAlign={"center"}
color="text.muted"
- variant="small">
- {t('KEY_GENERATION_IN_PROGRESS_MESSAGE')}
+ variant="small"
+ >
+ {t("KEY_GENERATION_IN_PROGRESS_MESSAGE")}
</Typography>
)}
</Box>
@@ -304,7 +309,7 @@ export default function SignUp({ router, appName, login }: SignUpProps) {
</Formik>
<FormPaperFooter>
- <LinkButton onClick={login}>{t('ACCOUNT_EXISTS')}</LinkButton>
+ <LinkButton onClick={login}>{t("ACCOUNT_EXISTS")}</LinkButton>
</FormPaperFooter>
</>
);
diff --git a/packages/accounts/components/two-factor/InvalidInputMessage.tsx b/packages/accounts/components/two-factor/InvalidInputMessage.tsx
index 133eebbd25..404d795e34 100644
--- a/packages/accounts/components/two-factor/InvalidInputMessage.tsx
+++ b/packages/accounts/components/two-factor/InvalidInputMessage.tsx
@@ -1,5 +1,5 @@
-import { TypographyProps, Typography } from '@mui/material';
-import { FC } from 'react';
+import { Typography, TypographyProps } from "@mui/material";
+import { FC } from "react";
const InvalidInputMessage: FC<TypographyProps> = (props) => {
return (
@@ -8,7 +8,8 @@ const InvalidInputMessage: FC<TypographyProps> = (props) => {
sx={{
color: (theme) => theme.colors.danger.A700,
}}
- {...props}>
+ {...props}
+ >
{props.children}
</Typography>
);
diff --git a/packages/accounts/components/two-factor/VerifyForm.tsx b/packages/accounts/components/two-factor/VerifyForm.tsx
index 7cfa3ce1db..810a6c010f 100644
--- a/packages/accounts/components/two-factor/VerifyForm.tsx
+++ b/packages/accounts/components/two-factor/VerifyForm.tsx
@@ -1,16 +1,16 @@
-import { Formik, FormikHelpers } from 'formik';
-import { useRef, useState } from 'react';
-import OtpInput from 'react-otp-input';
-import { t } from 'i18next';
+import { Formik, FormikHelpers } from "formik";
+import { t } from "i18next";
+import { useRef, useState } from "react";
+import OtpInput from "react-otp-input";
-import SubmitButton from '@ente/shared/components/SubmitButton';
+import InvalidInputMessage from "@ente/accounts/components/two-factor/InvalidInputMessage";
import {
- VerticallyCentered,
CenteredFlex,
-} from '@ente/shared/components/Container';
-import { Box, Typography } from '@mui/material';
-import InvalidInputMessage from '@ente/accounts/components/two-factor/InvalidInputMessage';
-import { sleep } from '@ente/shared/utils';
+ VerticallyCentered,
+} from "@ente/shared/components/Container";
+import SubmitButton from "@ente/shared/components/SubmitButton";
+import { sleep } from "@ente/shared/utils";
+import { Box, Typography } from "@mui/material";
interface formValues {
otp: string;
@@ -22,7 +22,7 @@ interface Props {
export type VerifyTwoFactorCallback = (
otp: string,
- markSuccessful: () => Promise<void>
+ markSuccessful: () => Promise<void>,
) => Promise<void>;
export default function VerifyTwoFactor(props: Props) {
@@ -38,7 +38,7 @@ export default function VerifyTwoFactor(props: Props) {
const submitForm = async (
{ otp }: formValues,
- { setFieldError, resetForm }: FormikHelpers<formValues>
+ { setFieldError, resetForm }: FormikHelpers<formValues>,
) => {
try {
setWaiting(true);
@@ -48,7 +48,7 @@ export default function VerifyTwoFactor(props: Props) {
for (let i = 0; i < 6; i++) {
otpInputRef.current?.focusPrevInput();
}
- setFieldError('otp', `${t('UNKNOWN_ERROR')} ${e.message}`);
+ setFieldError("otp", `${t("UNKNOWN_ERROR")} ${e.message}`);
}
setWaiting(false);
};
@@ -62,15 +62,16 @@ export default function VerifyTwoFactor(props: Props) {
};
return (
<Formik<formValues>
- initialValues={{ otp: '' }}
+ initialValues={{ otp: "" }}
validateOnChange={false}
validateOnBlur={false}
- onSubmit={submitForm}>
+ onSubmit={submitForm}
+ >
{({ values, errors, handleChange, handleSubmit, submitForm }) => (
<VerticallyCentered>
<form noValidate onSubmit={handleSubmit}>
<Typography mb={2} variant="small" color="text.muted">
- {t('ENTER_TWO_FACTOR_OTP')}
+ {t("ENTER_TWO_FACTOR_OTP")}
</Typography>
<Box my={2}>
<OtpInput
@@ -78,18 +79,18 @@ export default function VerifyTwoFactor(props: Props) {
shouldAutoFocus
value={values.otp}
onChange={onChange(
- handleChange('otp'),
- submitForm
+ handleChange("otp"),
+ submitForm,
)}
numInputs={6}
- separator={'-'}
+ separator={"-"}
isInputNum
- className={'otp-input'}
+ className={"otp-input"}
/>
{errors.otp && (
<CenteredFlex sx={{ mt: 1 }}>
<InvalidInputMessage>
- {t('INCORRECT_CODE')}
+ {t("INCORRECT_CODE")}
</InvalidInputMessage>
</CenteredFlex>
)}
diff --git a/packages/accounts/components/two-factor/setup/ManualMode.tsx b/packages/accounts/components/two-factor/setup/ManualMode.tsx
index 897645b598..05d3b25a3c 100644
--- a/packages/accounts/components/two-factor/setup/ManualMode.tsx
+++ b/packages/accounts/components/two-factor/setup/ManualMode.tsx
@@ -1,9 +1,9 @@
-import { Typography } from '@mui/material';
-import CodeBlock from '@ente/shared/components/CodeBlock';
-import { TwoFactorSecret } from '@ente/accounts/types/user';
-import { t } from 'i18next';
+import { TwoFactorSecret } from "@ente/accounts/types/user";
+import CodeBlock from "@ente/shared/components/CodeBlock";
+import { Typography } from "@mui/material";
+import { t } from "i18next";
-import LinkButton from '@ente/shared/components/LinkButton';
+import LinkButton from "@ente/shared/components/LinkButton";
interface Iprops {
twoFactorSecret: TwoFactorSecret;
@@ -15,10 +15,10 @@ export default function SetupManualMode({
}: Iprops) {
return (
<>
- <Typography>{t('TWO_FACTOR_MANUAL_CODE_INSTRUCTION')}</Typography>
+ <Typography>{t("TWO_FACTOR_MANUAL_CODE_INSTRUCTION")}</Typography>
<CodeBlock code={twoFactorSecret?.secretCode} my={2} />
<LinkButton onClick={changeToQRMode}>
- {t('SCAN_QR_CODE')}
+ {t("SCAN_QR_CODE")}
</LinkButton>
</>
);
diff --git a/packages/accounts/components/two-factor/setup/QRMode.tsx b/packages/accounts/components/two-factor/setup/QRMode.tsx
index 81819c7d89..adfa1dbc16 100644
--- a/packages/accounts/components/two-factor/setup/QRMode.tsx
+++ b/packages/accounts/components/two-factor/setup/QRMode.tsx
@@ -1,11 +1,10 @@
-import React from 'react';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { TwoFactorSecret } from '@ente/accounts/types/user';
-import { t } from 'i18next';
+import { TwoFactorSecret } from "@ente/accounts/types/user";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import { t } from "i18next";
-import { LoadingQRCode, QRCode } from '../styledComponents';
-import { Typography } from '@mui/material';
-import LinkButton from '@ente/shared/components/LinkButton';
+import LinkButton from "@ente/shared/components/LinkButton";
+import { Typography } from "@mui/material";
+import { LoadingQRCode, QRCode } from "../styledComponents";
interface Iprops {
twoFactorSecret: TwoFactorSecret;
@@ -18,7 +17,7 @@ export default function SetupQRMode({
}: Iprops) {
return (
<>
- <Typography>{t('TWO_FACTOR_QR_INSTRUCTION')}</Typography>
+ <Typography>{t("TWO_FACTOR_QR_INSTRUCTION")}</Typography>
{!twoFactorSecret ? (
<LoadingQRCode>
<EnteSpinner />
@@ -29,7 +28,7 @@ export default function SetupQRMode({
/>
)}
<LinkButton onClick={changeToManualMode}>
- {t('ENTER_CODE_MANUALLY')}
+ {t("ENTER_CODE_MANUALLY")}
</LinkButton>
</>
);
diff --git a/packages/accounts/components/two-factor/setup/index.tsx b/packages/accounts/components/two-factor/setup/index.tsx
index c4ff615e07..a9388db83f 100644
--- a/packages/accounts/components/two-factor/setup/index.tsx
+++ b/packages/accounts/components/two-factor/setup/index.tsx
@@ -1,9 +1,9 @@
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import { SetupMode } from '@ente/accounts/pages/two-factor/setup';
-import SetupManualMode from '@ente/accounts/components/two-factor/setup/ManualMode';
-import SetupQRMode from '@ente/accounts/components/two-factor/setup/QRMode';
-import { useState } from 'react';
-import { TwoFactorSecret } from '@ente/accounts/types/user';
+import SetupManualMode from "@ente/accounts/components/two-factor/setup/ManualMode";
+import SetupQRMode from "@ente/accounts/components/two-factor/setup/QRMode";
+import { SetupMode } from "@ente/accounts/pages/two-factor/setup";
+import { TwoFactorSecret } from "@ente/accounts/types/user";
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import { useState } from "react";
interface Iprops {
twoFactorSecret: TwoFactorSecret;
diff --git a/packages/accounts/components/two-factor/styledComponents.ts b/packages/accounts/components/two-factor/styledComponents.ts
index bd5732d5a4..7a9e7fe1c2 100644
--- a/packages/accounts/components/two-factor/styledComponents.ts
+++ b/packages/accounts/components/two-factor/styledComponents.ts
@@ -1,11 +1,11 @@
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import { styled } from '@mui/material';
-export const QRCode = styled('img')(
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import { styled } from "@mui/material";
+export const QRCode = styled("img")(
({ theme }) => `
height: 200px;
width: 200px;
margin: ${theme.spacing(2)};
-`
+`,
);
export const LoadingQRCode = styled(VerticallyCentered)(
@@ -14,5 +14,5 @@ export const LoadingQRCode = styled(VerticallyCentered)(
aspect-ratio:1;
border: 1px solid ${theme.palette.grey.A200};
margin: ${theme.spacing(2)};
- `
+ `,
);
diff --git a/packages/accounts/constants/index.ts b/packages/accounts/constants/index.ts
index 32002386b6..81f63d4771 100644
--- a/packages/accounts/constants/index.ts
+++ b/packages/accounts/constants/index.ts
@@ -1,5 +1,5 @@
export enum PasswordStrength {
- WEAK = 'WEAK',
- MODERATE = 'MODERATE',
- STRONG = 'STRONG',
+ WEAK = "WEAK",
+ MODERATE = "MODERATE",
+ STRONG = "STRONG",
}
diff --git a/packages/accounts/constants/pages.ts b/packages/accounts/constants/pages.ts
index 6afa97862f..b7658c6990 100644
--- a/packages/accounts/constants/pages.ts
+++ b/packages/accounts/constants/pages.ts
@@ -1,15 +1,15 @@
export enum PAGES {
- ROOT = '/',
- CHANGE_EMAIL = '/change-email',
- CHANGE_PASSWORD = '/change-password',
- CREDENTIALS = '/credentials',
- GENERATE = '/generate',
- LOGIN = '/login',
- RECOVER = '/recover',
- SIGNUP = '/signup',
- TWO_FACTOR_SETUP = '/two-factor/setup',
- TWO_FACTOR_VERIFY = '/two-factor/verify',
- TWO_FACTOR_RECOVER = '/two-factor/recover',
- VERIFY = '/verify',
- SHARED_ALBUMS = '/shared-albums',
+ ROOT = "/",
+ CHANGE_EMAIL = "/change-email",
+ CHANGE_PASSWORD = "/change-password",
+ CREDENTIALS = "/credentials",
+ GENERATE = "/generate",
+ LOGIN = "/login",
+ RECOVER = "/recover",
+ SIGNUP = "/signup",
+ TWO_FACTOR_SETUP = "/two-factor/setup",
+ TWO_FACTOR_VERIFY = "/two-factor/verify",
+ TWO_FACTOR_RECOVER = "/two-factor/recover",
+ VERIFY = "/verify",
+ SHARED_ALBUMS = "/shared-albums",
}
diff --git a/packages/accounts/pages/change-email.tsx b/packages/accounts/pages/change-email.tsx
index 04106ecf7a..b9f54ad988 100644
--- a/packages/accounts/pages/change-email.tsx
+++ b/packages/accounts/pages/change-email.tsx
@@ -1,13 +1,13 @@
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import React, { useEffect } from 'react';
-import { t } from 'i18next';
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import { t } from "i18next";
+import { useEffect } from "react";
-import ChangeEmailForm from '@ente/accounts/components/ChangeEmail';
-import { PAGES } from '@ente/accounts/constants/pages';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import FormPaper from '@ente/shared/components/Form/FormPaper';
-import FormPaperTitle from '@ente/shared/components/Form/FormPaper/Title';
-import { PageProps } from '@ente/shared/apps/types';
+import ChangeEmailForm from "@ente/accounts/components/ChangeEmail";
+import { PAGES } from "@ente/accounts/constants/pages";
+import { PageProps } from "@ente/shared/apps/types";
+import FormPaper from "@ente/shared/components/Form/FormPaper";
+import FormPaperTitle from "@ente/shared/components/Form/FormPaper/Title";
+import { getData, LS_KEYS } from "@ente/shared/storage/localStorage";
function ChangeEmailPage({ router, appName, appContext }: PageProps) {
useEffect(() => {
@@ -20,7 +20,7 @@ function ChangeEmailPage({ router, appName, appContext }: PageProps) {
return (
<VerticallyCentered>
<FormPaper>
- <FormPaperTitle>{t('CHANGE_EMAIL')}</FormPaperTitle>
+ <FormPaperTitle>{t("CHANGE_EMAIL")}</FormPaperTitle>
<ChangeEmailForm
router={router}
appName={appName}
diff --git a/packages/accounts/pages/change-password.tsx b/packages/accounts/pages/change-password.tsx
index d717589a8d..3e9860399c 100644
--- a/packages/accounts/pages/change-password.tsx
+++ b/packages/accounts/pages/change-password.tsx
@@ -1,40 +1,40 @@
-import { useState, useEffect } from 'react';
-import { t } from 'i18next';
+import { t } from "i18next";
+import { useEffect, useState } from "react";
-import { getData, LS_KEYS, setData } from '@ente/shared/storage/localStorage';
-import {
- saveKeyInSessionStore,
- generateAndSaveIntermediateKeyAttributes,
- generateLoginSubKey,
-} from '@ente/shared/crypto/helpers';
import {
generateSRPClient,
generateSRPSetupAttributes,
-} from '@ente/accounts/services/srp';
+} from "@ente/accounts/services/srp";
+import {
+ generateAndSaveIntermediateKeyAttributes,
+ generateLoginSubKey,
+ saveKeyInSessionStore,
+} from "@ente/shared/crypto/helpers";
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
-import { getActualKey } from '@ente/shared/user';
-import { startSRPSetup, updateSRPAndKeys } from '@ente/accounts/api/srp';
+import { startSRPSetup, updateSRPAndKeys } from "@ente/accounts/api/srp";
import SetPasswordForm, {
SetPasswordFormProps,
-} from '@ente/accounts/components/SetPasswordForm';
-import { SESSION_KEYS } from '@ente/shared/storage/sessionStorage';
-import { PAGES } from '@ente/accounts/constants/pages';
-import { KEK, KeyAttributes, User } from '@ente/shared/user/types';
-import { UpdatedKey } from '@ente/accounts/types/user';
-
-import LinkButton from '@ente/shared/components/LinkButton';
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import FormPaper from '@ente/shared/components/Form/FormPaper';
-import FormPaperFooter from '@ente/shared/components/Form/FormPaper/Footer';
-import FormPaperTitle from '@ente/shared/components/Form/FormPaper/Title';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { APP_HOMES } from '@ente/shared/apps/constants';
+} from "@ente/accounts/components/SetPasswordForm";
+import { PAGES } from "@ente/accounts/constants/pages";
+import { UpdatedKey } from "@ente/accounts/types/user";
+import { SESSION_KEYS } from "@ente/shared/storage/sessionStorage";
+import { getActualKey } from "@ente/shared/user";
+import { KEK, KeyAttributes, User } from "@ente/shared/user/types";
+
import {
- convertBufferToBase64,
convertBase64ToBuffer,
-} from '@ente/accounts/utils';
-import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
-import { PageProps } from '@ente/shared/apps/types';
+ convertBufferToBase64,
+} from "@ente/accounts/utils";
+import { APP_HOMES } from "@ente/shared/apps/constants";
+import { PageProps } from "@ente/shared/apps/types";
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import FormPaper from "@ente/shared/components/Form/FormPaper";
+import FormPaperFooter from "@ente/shared/components/Form/FormPaper/Footer";
+import FormPaperTitle from "@ente/shared/components/Form/FormPaper/Title";
+import LinkButton from "@ente/shared/components/LinkButton";
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import InMemoryStore, { MS_KEYS } from "@ente/shared/storage/InMemoryStore";
export default function ChangePassword({ appName, router }: PageProps) {
const [token, setToken] = useState<string>();
@@ -51,9 +51,9 @@ export default function ChangePassword({ appName, router }: PageProps) {
}
}, []);
- const onSubmit: SetPasswordFormProps['callback'] = async (
+ const onSubmit: SetPasswordFormProps["callback"] = async (
passphrase,
- setFieldError
+ setFieldError,
) => {
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
const key = await getActualKey();
@@ -63,12 +63,12 @@ export default function ChangePassword({ appName, router }: PageProps) {
try {
kek = await cryptoWorker.deriveSensitiveKey(passphrase, kekSalt);
} catch (e) {
- setFieldError('confirm', t('PASSWORD_GENERATION_FAILED'));
+ setFieldError("confirm", t("PASSWORD_GENERATION_FAILED"));
return;
}
const encryptedKeyAttributes = await cryptoWorker.encryptToB64(
key,
- kek.key
+ kek.key,
);
const updatedKey: UpdatedKey = {
kekSalt,
@@ -86,7 +86,7 @@ export default function ChangePassword({ appName, router }: PageProps) {
const srpClient = await generateSRPClient(
srpSalt,
srpUserID,
- loginSubKey
+ loginSubKey,
);
const srpA = convertBufferToBase64(srpClient.computeA());
@@ -112,7 +112,7 @@ export default function ChangePassword({ appName, router }: PageProps) {
await generateAndSaveIntermediateKeyAttributes(
passphrase,
updatedKeyAttributes,
- key
+ key,
);
await saveKeyInSessionStore(SESSION_KEYS.ENCRYPTION_KEY, key);
@@ -127,16 +127,16 @@ export default function ChangePassword({ appName, router }: PageProps) {
return (
<VerticallyCentered>
<FormPaper>
- <FormPaperTitle>{t('CHANGE_PASSWORD')}</FormPaperTitle>
+ <FormPaperTitle>{t("CHANGE_PASSWORD")}</FormPaperTitle>
<SetPasswordForm
userEmail={user?.email}
callback={onSubmit}
- buttonText={t('CHANGE_PASSWORD')}
+ buttonText={t("CHANGE_PASSWORD")}
/>
{(getData(LS_KEYS.SHOW_BACK_BUTTON)?.value ?? true) && (
<FormPaperFooter>
<LinkButton onClick={router.back}>
- {t('GO_BACK')}
+ {t("GO_BACK")}
</LinkButton>
</FormPaperFooter>
)}
diff --git a/packages/accounts/pages/credentials.tsx b/packages/accounts/pages/credentials.tsx
index 58c5faddb7..50cbc02ca0 100644
--- a/packages/accounts/pages/credentials.tsx
+++ b/packages/accounts/pages/credentials.tsx
@@ -1,58 +1,58 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useState } from "react";
-import { t } from 'i18next';
+import { t } from "i18next";
import {
decryptAndStoreToken,
generateAndSaveIntermediateKeyAttributes,
generateLoginSubKey,
saveKeyInSessionStore,
-} from '@ente/shared/crypto/helpers';
+} from "@ente/shared/crypto/helpers";
import {
+ LS_KEYS,
clearData,
getData,
- LS_KEYS,
setData,
-} from '@ente/shared/storage/localStorage';
+} from "@ente/shared/storage/localStorage";
import {
+ SESSION_KEYS,
getKey,
removeKey,
- SESSION_KEYS,
setKey,
-} from '@ente/shared/storage/sessionStorage';
-import { PAGES } from '../constants/pages';
-import { generateSRPSetupAttributes } from '../services/srp';
-import { logoutUser } from '../services/user';
+} from "@ente/shared/storage/sessionStorage";
+import { PAGES } from "../constants/pages";
+import { generateSRPSetupAttributes } from "../services/srp";
+import { logoutUser } from "../services/user";
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import FormPaper from '@ente/shared/components/Form/FormPaper';
-import FormPaperFooter from '@ente/shared/components/Form/FormPaper/Footer';
-import FormPaperTitle from '@ente/shared/components/Form/FormPaper/Title';
-import LinkButton from '@ente/shared/components/LinkButton';
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import FormPaper from "@ente/shared/components/Form/FormPaper";
+import FormPaperFooter from "@ente/shared/components/Form/FormPaper/Footer";
+import FormPaperTitle from "@ente/shared/components/Form/FormPaper/Title";
+import LinkButton from "@ente/shared/components/LinkButton";
import VerifyMasterPasswordForm, {
VerifyMasterPasswordFormProps,
-} from '@ente/shared/components/VerifyMasterPasswordForm';
-import { getAccountsURL } from '@ente/shared/network/api';
+} from "@ente/shared/components/VerifyMasterPasswordForm";
+import { getAccountsURL } from "@ente/shared/network/api";
import {
isFirstLogin,
setIsFirstLogin,
-} from '@ente/shared/storage/localStorage/helpers';
-import { KeyAttributes, User } from '@ente/shared/user/types';
-import isElectron from 'is-electron';
-import { getSRPAttributes } from '../api/srp';
-import { configureSRP, loginViaSRP } from '../services/srp';
-import { SRPAttributes } from '../types/srp';
+} from "@ente/shared/storage/localStorage/helpers";
+import { KeyAttributes, User } from "@ente/shared/user/types";
+import isElectron from "is-electron";
+import { getSRPAttributes } from "../api/srp";
+import { configureSRP, loginViaSRP } from "../services/srp";
+import { SRPAttributes } from "../types/srp";
// import { APPS, getAppName } from '@ente/shared/apps';
-import { APP_HOMES } from '@ente/shared/apps/constants';
-import { PageProps } from '@ente/shared/apps/types';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { B64EncryptionResult } from '@ente/shared/crypto/types';
-import ElectronAPIs from '@ente/shared/electron';
-import { CustomError } from '@ente/shared/error';
-import { addLocalLog } from '@ente/shared/logging';
-import { logError } from '@ente/shared/sentry';
-import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
+import { APP_HOMES } from "@ente/shared/apps/constants";
+import { PageProps } from "@ente/shared/apps/types";
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { B64EncryptionResult } from "@ente/shared/crypto/types";
+import ElectronAPIs from "@ente/shared/electron";
+import { CustomError } from "@ente/shared/error";
+import { addLocalLog } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import InMemoryStore, { MS_KEYS } from "@ente/shared/storage/InMemoryStore";
export default function Credentials({
appContext,
@@ -76,13 +76,13 @@ export default function Credentials({
try {
key = await ElectronAPIs.getEncryptionKey();
} catch (e) {
- logError(e, 'getEncryptionKey failed');
+ logError(e, "getEncryptionKey failed");
}
if (key) {
await saveKeyInSessionStore(
SESSION_KEYS.ENCRYPTION_KEY,
key,
- true
+ true,
);
}
}
@@ -91,10 +91,10 @@ export default function Credentials({
return;
}
const kekEncryptedAttributes: B64EncryptionResult = getKey(
- SESSION_KEYS.KEY_ENCRYPTION_KEY
+ SESSION_KEYS.KEY_ENCRYPTION_KEY,
);
const keyAttributes: KeyAttributes = getData(
- LS_KEYS.KEY_ATTRIBUTES
+ LS_KEYS.KEY_ATTRIBUTES,
);
if (kekEncryptedAttributes && keyAttributes) {
removeKey(SESSION_KEYS.KEY_ENCRYPTION_KEY);
@@ -102,12 +102,12 @@ export default function Credentials({
const kek = await cryptoWorker.decryptB64(
kekEncryptedAttributes.encryptedData,
kekEncryptedAttributes.nonce,
- kekEncryptedAttributes.key
+ kekEncryptedAttributes.key,
);
const key = await cryptoWorker.decryptB64(
keyAttributes.encryptedKey,
keyAttributes.keyDecryptionNonce,
- kek
+ kek,
);
useMasterPassword(key, kek, keyAttributes);
return;
@@ -126,7 +126,7 @@ export default function Credentials({
}
const srpAttributes: SRPAttributes = getData(
- LS_KEYS.SRP_ATTRIBUTES
+ LS_KEYS.SRP_ATTRIBUTES,
);
if (srpAttributes) {
setSrpAttributes(srpAttributes);
@@ -138,7 +138,7 @@ export default function Credentials({
appContext.showNavBar(true);
}, []);
- const getKeyAttributes: VerifyMasterPasswordFormProps['getKeyAttributes'] =
+ const getKeyAttributes: VerifyMasterPasswordFormProps["getKeyAttributes"] =
async (kek: string) => {
try {
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
@@ -156,7 +156,7 @@ export default function Credentials({
await cryptoWorker.generateKeyAndEncryptToB64(kek);
setKey(
SESSION_KEYS.KEY_ENCRYPTION_KEY,
- sessionKeyAttributes
+ sessionKeyAttributes,
);
const user = getData(LS_KEYS.USER);
setData(LS_KEYS.USER, {
@@ -175,7 +175,7 @@ export default function Credentials({
await cryptoWorker.generateKeyAndEncryptToB64(kek);
setKey(
SESSION_KEYS.KEY_ENCRYPTION_KEY,
- sessionKeyAttributes
+ sessionKeyAttributes,
);
const user = getData(LS_KEYS.USER);
setData(LS_KEYS.USER, {
@@ -199,31 +199,31 @@ export default function Credentials({
}
} catch (e) {
if (e.message !== CustomError.TWO_FACTOR_ENABLED) {
- logError(e, 'getKeyAttributes failed');
+ logError(e, "getKeyAttributes failed");
}
throw e;
}
};
- const useMasterPassword: VerifyMasterPasswordFormProps['callback'] = async (
+ const useMasterPassword: VerifyMasterPasswordFormProps["callback"] = async (
key,
kek,
keyAttributes,
- passphrase
+ passphrase,
) => {
try {
if (isFirstLogin() && passphrase) {
await generateAndSaveIntermediateKeyAttributes(
passphrase,
keyAttributes,
- key
+ key,
);
}
await saveKeyInSessionStore(SESSION_KEYS.ENCRYPTION_KEY, key);
await decryptAndStoreToken(keyAttributes, key);
try {
let srpAttributes: SRPAttributes = getData(
- LS_KEYS.SRP_ATTRIBUTES
+ LS_KEYS.SRP_ATTRIBUTES,
);
if (!srpAttributes) {
srpAttributes = await getSRPAttributes(user.email);
@@ -239,13 +239,13 @@ export default function Credentials({
await configureSRP(srpSetupAttributes);
}
} catch (e) {
- logError(e, 'migrate to srp failed');
+ logError(e, "migrate to srp failed");
}
const redirectURL = InMemoryStore.get(MS_KEYS.REDIRECT_URL);
InMemoryStore.delete(MS_KEYS.REDIRECT_URL);
router.push(redirectURL ?? APP_HOMES.get(appName));
} catch (e) {
- logError(e, 'useMasterPassword failed');
+ logError(e, "useMasterPassword failed");
}
};
@@ -261,23 +261,23 @@ export default function Credentials({
return (
<VerticallyCentered>
- <FormPaper style={{ minWidth: '320px' }}>
- <FormPaperTitle>{t('PASSWORD')}</FormPaperTitle>
+ <FormPaper style={{ minWidth: "320px" }}>
+ <FormPaperTitle>{t("PASSWORD")}</FormPaperTitle>
<VerifyMasterPasswordForm
- buttonText={t('VERIFY_PASSPHRASE')}
+ buttonText={t("VERIFY_PASSPHRASE")}
callback={useMasterPassword}
user={user}
keyAttributes={keyAttributes}
getKeyAttributes={getKeyAttributes}
srpAttributes={srpAttributes}
/>
- <FormPaperFooter style={{ justifyContent: 'space-between' }}>
+ <FormPaperFooter style={{ justifyContent: "space-between" }}>
<LinkButton onClick={redirectToRecoverPage}>
- {t('FORGOT_PASSWORD')}
+ {t("FORGOT_PASSWORD")}
</LinkButton>
<LinkButton onClick={logoutUser}>
- {t('CHANGE_EMAIL')}
+ {t("CHANGE_EMAIL")}
</LinkButton>
</FormPaperFooter>
</FormPaper>
diff --git a/packages/accounts/pages/generate.tsx b/packages/accounts/pages/generate.tsx
index 1b99724ee3..8c4a339f94 100644
--- a/packages/accounts/pages/generate.tsx
+++ b/packages/accounts/pages/generate.tsx
@@ -1,34 +1,34 @@
-import React, { useState, useEffect } from 'react';
-import { t } from 'i18next';
+import { t } from "i18next";
+import { useEffect, useState } from "react";
-import { logoutUser } from '@ente/accounts/services/user';
-import { putAttributes } from '@ente/accounts/api/user';
-import { configureSRP } from '@ente/accounts/services/srp';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import { getKey, SESSION_KEYS } from '@ente/shared/storage/sessionStorage';
+import { putAttributes } from "@ente/accounts/api/user";
+import { configureSRP } from "@ente/accounts/services/srp";
+import { logoutUser } from "@ente/accounts/services/user";
+import { generateKeyAndSRPAttributes } from "@ente/accounts/utils/srp";
import {
- saveKeyInSessionStore,
generateAndSaveIntermediateKeyAttributes,
-} from '@ente/shared/crypto/helpers';
-import { generateKeyAndSRPAttributes } from '@ente/accounts/utils/srp';
+ saveKeyInSessionStore,
+} from "@ente/shared/crypto/helpers";
+import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
+import { SESSION_KEYS, getKey } from "@ente/shared/storage/sessionStorage";
-import SetPasswordForm from '@ente/accounts/components/SetPasswordForm';
+import SetPasswordForm from "@ente/accounts/components/SetPasswordForm";
+import { PAGES } from "@ente/accounts/constants/pages";
+import { APP_HOMES } from "@ente/shared/apps/constants";
+import { PageProps } from "@ente/shared/apps/types";
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import FormPaper from "@ente/shared/components/Form/FormPaper";
+import FormPaperFooter from "@ente/shared/components/Form/FormPaper/Footer";
+import FormTitle from "@ente/shared/components/Form/FormPaper/Title";
+import LinkButton from "@ente/shared/components/LinkButton";
+import RecoveryKey from "@ente/shared/components/RecoveryKey";
+import { logError } from "@ente/shared/sentry";
import {
justSignedUp,
setJustSignedUp,
-} from '@ente/shared/storage/localStorage/helpers';
-import RecoveryKey from '@ente/shared/components/RecoveryKey';
-import { PAGES } from '@ente/accounts/constants/pages';
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { logError } from '@ente/shared/sentry';
-import { KeyAttributes, User } from '@ente/shared/user/types';
-import FormPaper from '@ente/shared/components/Form/FormPaper';
-import FormTitle from '@ente/shared/components/Form/FormPaper/Title';
-import { APP_HOMES } from '@ente/shared/apps/constants';
-import FormPaperFooter from '@ente/shared/components/Form/FormPaper/Footer';
-import LinkButton from '@ente/shared/components/LinkButton';
-import { PageProps } from '@ente/shared/apps/types';
+} from "@ente/shared/storage/localStorage/helpers";
+import { KeyAttributes, User } from "@ente/shared/user/types";
export default function Generate({ router, appContext, appName }: PageProps) {
const [token, setToken] = useState<string>();
@@ -39,7 +39,7 @@ export default function Generate({ router, appContext, appName }: PageProps) {
const main = async () => {
const key: string = getKey(SESSION_KEYS.ENCRYPTION_KEY);
const keyAttributes: KeyAttributes = getData(
- LS_KEYS.ORIGINAL_KEY_ATTRIBUTES
+ LS_KEYS.ORIGINAL_KEY_ATTRIBUTES,
);
const user: User = getData(LS_KEYS.USER);
setUser(user);
@@ -73,14 +73,14 @@ export default function Generate({ router, appContext, appName }: PageProps) {
await generateAndSaveIntermediateKeyAttributes(
passphrase,
keyAttributes,
- masterKey
+ masterKey,
);
await saveKeyInSessionStore(SESSION_KEYS.ENCRYPTION_KEY, masterKey);
setJustSignedUp(true);
setRecoveryModalView(true);
} catch (e) {
- logError(e, 'failed to generate password');
- setFieldError('passphrase', t('PASSWORD_GENERATION_FAILED'));
+ logError(e, "failed to generate password");
+ setFieldError("passphrase", t("PASSWORD_GENERATION_FAILED"));
}
};
@@ -103,15 +103,15 @@ export default function Generate({ router, appContext, appName }: PageProps) {
) : (
<VerticallyCentered>
<FormPaper>
- <FormTitle>{t('SET_PASSPHRASE')}</FormTitle>
+ <FormTitle>{t("SET_PASSPHRASE")}</FormTitle>
<SetPasswordForm
userEmail={user?.email}
callback={onSubmit}
- buttonText={t('SET_PASSPHRASE')}
+ buttonText={t("SET_PASSPHRASE")}
/>
<FormPaperFooter>
<LinkButton onClick={logoutUser}>
- {t('GO_BACK')}
+ {t("GO_BACK")}
</LinkButton>
</FormPaperFooter>
</FormPaper>
diff --git a/packages/accounts/pages/login.tsx b/packages/accounts/pages/login.tsx
index 01c9464b60..9b3ac5c1d8 100644
--- a/packages/accounts/pages/login.tsx
+++ b/packages/accounts/pages/login.tsx
@@ -1,11 +1,11 @@
-import { useState, useEffect } from 'react';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import Login from '../components/Login';
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import { PAGES } from '../constants/pages';
-import FormPaper from '@ente/shared/components/Form/FormPaper';
-import { PageProps } from '@ente/shared/apps/types';
+import { PageProps } from "@ente/shared/apps/types";
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import FormPaper from "@ente/shared/components/Form/FormPaper";
+import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
+import { useEffect, useState } from "react";
+import Login from "../components/Login";
+import { PAGES } from "../constants/pages";
export default function LoginPage({ appContext, router, appName }: PageProps) {
const [loading, setLoading] = useState(true);
diff --git a/packages/accounts/pages/passkeys/finish.tsx b/packages/accounts/pages/passkeys/finish.tsx
index 6bf80eba29..4e85e3e43a 100644
--- a/packages/accounts/pages/passkeys/finish.tsx
+++ b/packages/accounts/pages/passkeys/finish.tsx
@@ -1,10 +1,10 @@
-import { PAGES } from '@ente/accounts/constants/pages';
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
-import { LS_KEYS, getData, setData } from '@ente/shared/storage/localStorage';
-import { useRouter } from 'next/router';
-import { useEffect } from 'react';
+import { PAGES } from "@ente/accounts/constants/pages";
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import InMemoryStore, { MS_KEYS } from "@ente/shared/storage/InMemoryStore";
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
+import { useRouter } from "next/router";
+import { useEffect } from "react";
const PasskeysFinishPage = () => {
const router = useRouter();
@@ -12,7 +12,7 @@ const PasskeysFinishPage = () => {
const init = async () => {
// get response from query params
const searchParams = new URLSearchParams(window.location.search);
- const response = searchParams.get('response');
+ const response = searchParams.get("response");
if (!response) return;
diff --git a/packages/accounts/pages/recover.tsx b/packages/accounts/pages/recover.tsx
index 997e4205df..3c4ad41467 100644
--- a/packages/accounts/pages/recover.tsx
+++ b/packages/accounts/pages/recover.tsx
@@ -1,31 +1,31 @@
-import React, { useEffect, useState } from 'react';
-import { t } from 'i18next';
+import { t } from "i18next";
+import { useEffect, useState } from "react";
-import { getData, LS_KEYS, setData } from '@ente/shared/storage/localStorage';
-import { PAGES } from '@ente/accounts/constants/pages';
+import { sendOtt } from "@ente/accounts/api/user";
+import { PAGES } from "@ente/accounts/constants/pages";
+import { APP_HOMES } from "@ente/shared/apps/constants";
+import { PageProps } from "@ente/shared/apps/types";
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import FormPaper from "@ente/shared/components/Form/FormPaper";
+import FormPaperFooter from "@ente/shared/components/Form/FormPaper/Footer";
+import FormPaperTitle from "@ente/shared/components/Form/FormPaper/Title";
+import LinkButton from "@ente/shared/components/LinkButton";
+import SingleInputForm, {
+ SingleInputFormProps,
+} from "@ente/shared/components/SingleInputForm";
+import ComlinkCryptoWorker from "@ente/shared/crypto";
import {
decryptAndStoreToken,
saveKeyInSessionStore,
-} from '@ente/shared/crypto/helpers';
-import SingleInputForm, {
- SingleInputFormProps,
-} from '@ente/shared/components/SingleInputForm';
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import { getKey, SESSION_KEYS } from '@ente/shared/storage/sessionStorage';
-import { KeyAttributes, User } from '@ente/shared/user/types';
-import FormPaper from '@ente/shared/components/Form/FormPaper';
-import FormPaperTitle from '@ente/shared/components/Form/FormPaper/Title';
-import FormPaperFooter from '@ente/shared/components/Form/FormPaper/Footer';
-import LinkButton from '@ente/shared/components/LinkButton';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { sendOtt } from '@ente/accounts/api/user';
-import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
-import { PageProps } from '@ente/shared/apps/types';
-import { logError } from '@ente/shared/sentry';
-import { APP_HOMES } from '@ente/shared/apps/constants';
-const bip39 = require('bip39');
+} from "@ente/shared/crypto/helpers";
+import { logError } from "@ente/shared/sentry";
+import InMemoryStore, { MS_KEYS } from "@ente/shared/storage/InMemoryStore";
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
+import { SESSION_KEYS, getKey } from "@ente/shared/storage/sessionStorage";
+import { KeyAttributes, User } from "@ente/shared/user/types";
+const bip39 = require("bip39");
// mobile client library only supports english.
-bip39.setDefaultWordlist('english');
+bip39.setDefaultWordlist("english");
export default function Recover({ appContext, router, appName }: PageProps) {
const [keyAttributes, setKeyAttributes] = useState<KeyAttributes>();
@@ -54,21 +54,21 @@ export default function Recover({ appContext, router, appName }: PageProps) {
appContext.showNavBar(true);
}, []);
- const recover: SingleInputFormProps['callback'] = async (
+ const recover: SingleInputFormProps["callback"] = async (
recoveryKey: string,
- setFieldError
+ setFieldError,
) => {
try {
recoveryKey = recoveryKey
.trim()
- .split(' ')
+ .split(" ")
.map((part) => part.trim())
.filter((part) => !!part)
- .join(' ');
+ .join(" ");
// check if user is entering mnemonic recovery key
- if (recoveryKey.indexOf(' ') > 0) {
- if (recoveryKey.split(' ').length !== 24) {
- throw new Error('recovery code should have 24 words');
+ if (recoveryKey.indexOf(" ") > 0) {
+ if (recoveryKey.split(" ").length !== 24) {
+ throw new Error("recovery code should have 24 words");
}
recoveryKey = bip39.mnemonicToEntropy(recoveryKey);
}
@@ -76,7 +76,7 @@ export default function Recover({ appContext, router, appName }: PageProps) {
const masterKey = await cryptoWorker.decryptB64(
keyAttributes.masterKeyEncryptedWithRecoveryKey,
keyAttributes.masterKeyDecryptionNonce,
- await cryptoWorker.fromHex(recoveryKey)
+ await cryptoWorker.fromHex(recoveryKey),
);
await saveKeyInSessionStore(SESSION_KEYS.ENCRYPTION_KEY, masterKey);
await decryptAndStoreToken(keyAttributes, masterKey);
@@ -84,36 +84,36 @@ export default function Recover({ appContext, router, appName }: PageProps) {
setData(LS_KEYS.SHOW_BACK_BUTTON, { value: false });
router.push(PAGES.CHANGE_PASSWORD);
} catch (e) {
- logError(e, 'password recovery failed');
- setFieldError(t('INCORRECT_RECOVERY_KEY'));
+ logError(e, "password recovery failed");
+ setFieldError(t("INCORRECT_RECOVERY_KEY"));
}
};
const showNoRecoveryKeyMessage = () => {
appContext.setDialogBoxAttributesV2({
- title: t('SORRY'),
+ title: t("SORRY"),
close: {},
- content: t('NO_RECOVERY_KEY_MESSAGE'),
+ content: t("NO_RECOVERY_KEY_MESSAGE"),
});
};
return (
<VerticallyCentered>
<FormPaper>
- <FormPaperTitle>{t('RECOVER_ACCOUNT')}</FormPaperTitle>
+ <FormPaperTitle>{t("RECOVER_ACCOUNT")}</FormPaperTitle>
<SingleInputForm
callback={recover}
fieldType="text"
- placeholder={t('RECOVERY_KEY_HINT')}
- buttonText={t('RECOVER')}
+ placeholder={t("RECOVERY_KEY_HINT")}
+ buttonText={t("RECOVER")}
disableAutoComplete
/>
- <FormPaperFooter style={{ justifyContent: 'space-between' }}>
+ <FormPaperFooter style={{ justifyContent: "space-between" }}>
<LinkButton onClick={showNoRecoveryKeyMessage}>
- {t('NO_RECOVERY_KEY')}
+ {t("NO_RECOVERY_KEY")}
</LinkButton>
<LinkButton onClick={router.back}>
- {t('GO_BACK')}
+ {t("GO_BACK")}
</LinkButton>
</FormPaperFooter>
</FormPaper>
diff --git a/packages/accounts/pages/signup.tsx b/packages/accounts/pages/signup.tsx
index 27b7842126..695301c7de 100644
--- a/packages/accounts/pages/signup.tsx
+++ b/packages/accounts/pages/signup.tsx
@@ -1,11 +1,11 @@
-import React, { useState, useEffect } from 'react';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { getData, LS_KEYS } from '@ente/shared//storage/localStorage';
-import SignUp from '@ente/accounts/components/SignUp';
-import { PAGES } from '@ente/accounts/constants/pages';
-import FormPaper from '@ente/shared/components/Form/FormPaper';
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import { PageProps } from '@ente/shared/apps/types';
+import SignUp from "@ente/accounts/components/SignUp";
+import { PAGES } from "@ente/accounts/constants/pages";
+import { LS_KEYS, getData } from "@ente/shared//storage/localStorage";
+import { PageProps } from "@ente/shared/apps/types";
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import FormPaper from "@ente/shared/components/Form/FormPaper";
+import { useEffect, useState } from "react";
export default function SignUpPage({ router, appContext, appName }: PageProps) {
const [loading, setLoading] = useState(true);
diff --git a/packages/accounts/pages/two-factor/recover.tsx b/packages/accounts/pages/two-factor/recover.tsx
index 14e02ca1ff..67bd709e10 100644
--- a/packages/accounts/pages/two-factor/recover.tsx
+++ b/packages/accounts/pages/two-factor/recover.tsx
@@ -1,32 +1,32 @@
-import React, { useEffect, useState } from 'react';
-import { getData, LS_KEYS, setData } from '@ente/shared/storage/localStorage';
+import { VerticallyCentered } from "@ente/shared/components/Container";
import SingleInputForm, {
SingleInputFormProps,
-} from '@ente/shared/components/SingleInputForm';
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import { logError } from '@ente/shared/sentry';
+} from "@ente/shared/components/SingleInputForm";
+import { logError } from "@ente/shared/sentry";
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
+import { useEffect, useState } from "react";
-import { logoutUser } from '@ente/accounts/services/user';
-import { recoverTwoFactor, removeTwoFactor } from '@ente/accounts/api/user';
-import { PAGES } from '@ente/accounts/constants/pages';
-import FormPaper from '@ente/shared/components/Form/FormPaper';
-import FormPaperTitle from '@ente/shared/components/Form/FormPaper/Title';
-import FormPaperFooter from '@ente/shared/components/Form/FormPaper/Footer';
-import LinkButton from '@ente/shared/components/LinkButton';
-import { B64EncryptionResult } from '@ente/shared/crypto/types';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { t } from 'i18next';
-import { Trans } from 'react-i18next';
-import { Link } from '@mui/material';
-import { SUPPORT_EMAIL } from '@ente/shared/constants/urls';
-import { DialogBoxAttributesV2 } from '@ente/shared/components/DialogBoxV2/types';
-import { ApiError } from '@ente/shared/error';
-import { HttpStatusCode } from 'axios';
-import { PageProps } from '@ente/shared/apps/types';
+import { recoverTwoFactor, removeTwoFactor } from "@ente/accounts/api/user";
+import { PAGES } from "@ente/accounts/constants/pages";
+import { logoutUser } from "@ente/accounts/services/user";
+import { PageProps } from "@ente/shared/apps/types";
+import { DialogBoxAttributesV2 } from "@ente/shared/components/DialogBoxV2/types";
+import FormPaper from "@ente/shared/components/Form/FormPaper";
+import FormPaperFooter from "@ente/shared/components/Form/FormPaper/Footer";
+import FormPaperTitle from "@ente/shared/components/Form/FormPaper/Title";
+import LinkButton from "@ente/shared/components/LinkButton";
+import { SUPPORT_EMAIL } from "@ente/shared/constants/urls";
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { B64EncryptionResult } from "@ente/shared/crypto/types";
+import { ApiError } from "@ente/shared/error";
+import { Link } from "@mui/material";
+import { HttpStatusCode } from "axios";
+import { t } from "i18next";
+import { Trans } from "react-i18next";
-const bip39 = require('bip39');
+const bip39 = require("bip39");
// mobile client library only supports english.
-bip39.setDefaultWordlist('english');
+bip39.setDefaultWordlist("english");
export default function Recover({ router, appContext }: PageProps) {
const [encryptedTwoFactorSecret, setEncryptedTwoFactorSecret] =
@@ -53,7 +53,7 @@ export default function Recover({ router, appContext }: PageProps) {
setDoesHaveEncryptedRecoveryKey(!!resp.encryptedSecret);
if (!resp.encryptedSecret) {
showContactSupportDialog({
- text: t('GO_BACK'),
+ text: t("GO_BACK"),
action: router.back,
});
} else {
@@ -70,10 +70,10 @@ export default function Recover({ router, appContext }: PageProps) {
) {
logoutUser();
} else {
- logError(e, 'two factor recovery page setup failed');
+ logError(e, "two factor recovery page setup failed");
setDoesHaveEncryptedRecoveryKey(false);
showContactSupportDialog({
- text: t('GO_BACK'),
+ text: t("GO_BACK"),
action: router.back,
});
}
@@ -82,21 +82,21 @@ export default function Recover({ router, appContext }: PageProps) {
main();
}, []);
- const recover: SingleInputFormProps['callback'] = async (
+ const recover: SingleInputFormProps["callback"] = async (
recoveryKey: string,
- setFieldError
+ setFieldError,
) => {
try {
recoveryKey = recoveryKey
.trim()
- .split(' ')
+ .split(" ")
.map((part) => part.trim())
.filter((part) => !!part)
- .join(' ');
+ .join(" ");
// check if user is entering mnemonic recovery key
- if (recoveryKey.indexOf(' ') > 0) {
- if (recoveryKey.split(' ').length !== 24) {
- throw new Error('recovery code should have 24 words');
+ if (recoveryKey.indexOf(" ") > 0) {
+ if (recoveryKey.split(" ").length !== 24) {
+ throw new Error("recovery code should have 24 words");
}
recoveryKey = bip39.mnemonicToEntropy(recoveryKey);
}
@@ -104,7 +104,7 @@ export default function Recover({ router, appContext }: PageProps) {
const twoFactorSecret = await cryptoWorker.decryptB64(
encryptedTwoFactorSecret.encryptedData,
encryptedTwoFactorSecret.nonce,
- await cryptoWorker.fromHex(recoveryKey)
+ await cryptoWorker.fromHex(recoveryKey),
);
const resp = await removeTwoFactor(sessionID, twoFactorSecret);
const { keyAttributes, encryptedToken, token, id } = resp;
@@ -118,20 +118,20 @@ export default function Recover({ router, appContext }: PageProps) {
setData(LS_KEYS.KEY_ATTRIBUTES, keyAttributes);
router.push(PAGES.CREDENTIALS);
} catch (e) {
- logError(e, 'two factor recovery failed');
- setFieldError(t('INCORRECT_RECOVERY_KEY'));
+ logError(e, "two factor recovery failed");
+ setFieldError(t("INCORRECT_RECOVERY_KEY"));
}
};
const showContactSupportDialog = (
- dialogClose?: DialogBoxAttributesV2['close']
+ dialogClose?: DialogBoxAttributesV2["close"],
) => {
appContext.setDialogBoxAttributesV2({
- title: t('CONTACT_SUPPORT'),
+ title: t("CONTACT_SUPPORT"),
close: dialogClose ?? {},
content: (
<Trans
- i18nKey={'NO_TWO_FACTOR_RECOVERY_KEY_MESSAGE'}
+ i18nKey={"NO_TWO_FACTOR_RECOVERY_KEY_MESSAGE"}
values={{ emailID: SUPPORT_EMAIL }}
components={{
a: <Link href={`mailto:${SUPPORT_EMAIL}`} />,
@@ -148,20 +148,20 @@ export default function Recover({ router, appContext }: PageProps) {
return (
<VerticallyCentered>
<FormPaper>
- <FormPaperTitle>{t('RECOVER_TWO_FACTOR')}</FormPaperTitle>
+ <FormPaperTitle>{t("RECOVER_TWO_FACTOR")}</FormPaperTitle>
<SingleInputForm
callback={recover}
fieldType="text"
- placeholder={t('RECOVERY_KEY_HINT')}
- buttonText={t('RECOVER')}
+ placeholder={t("RECOVERY_KEY_HINT")}
+ buttonText={t("RECOVER")}
disableAutoComplete
/>
- <FormPaperFooter style={{ justifyContent: 'space-between' }}>
+ <FormPaperFooter style={{ justifyContent: "space-between" }}>
<LinkButton onClick={() => showContactSupportDialog()}>
- {t('NO_RECOVERY_KEY')}
+ {t("NO_RECOVERY_KEY")}
</LinkButton>
<LinkButton onClick={router.back}>
- {t('GO_BACK')}
+ {t("GO_BACK")}
</LinkButton>
</FormPaperFooter>
</FormPaper>
diff --git a/packages/accounts/pages/two-factor/setup.tsx b/packages/accounts/pages/two-factor/setup.tsx
index bc12cc0f71..e887c21f2a 100644
--- a/packages/accounts/pages/two-factor/setup.tsx
+++ b/packages/accounts/pages/two-factor/setup.tsx
@@ -1,21 +1,21 @@
-import React, { useEffect, useState } from 'react';
-import { enableTwoFactor, setupTwoFactor } from '@ente/accounts/api/user';
-import { t } from 'i18next';
+import { enableTwoFactor, setupTwoFactor } from "@ente/accounts/api/user";
+import { t } from "i18next";
+import { useEffect, useState } from "react";
-import { VerticallyCentered } from '@ente/shared/components/Container';
import VerifyTwoFactor, {
VerifyTwoFactorCallback,
-} from '@ente/accounts/components/two-factor/VerifyForm';
-import { encryptWithRecoveryKey } from '@ente/shared/crypto/helpers';
-import { setData, LS_KEYS, getData } from '@ente/shared/storage/localStorage';
-import { TwoFactorSecret } from '@ente/accounts/types/user';
-import Card from '@mui/material/Card';
-import { Box, CardContent, Typography } from '@mui/material';
-import { TwoFactorSetup } from '@ente/accounts/components/two-factor/setup';
-import LinkButton from '@ente/shared/components/LinkButton';
-import { PageProps } from '@ente/shared/apps/types';
-import { logError } from '@ente/shared/sentry';
-import { APP_HOMES } from '@ente/shared/apps/constants';
+} from "@ente/accounts/components/two-factor/VerifyForm";
+import { TwoFactorSetup } from "@ente/accounts/components/two-factor/setup";
+import { TwoFactorSecret } from "@ente/accounts/types/user";
+import { APP_HOMES } from "@ente/shared/apps/constants";
+import { PageProps } from "@ente/shared/apps/types";
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import LinkButton from "@ente/shared/components/LinkButton";
+import { encryptWithRecoveryKey } from "@ente/shared/crypto/helpers";
+import { logError } from "@ente/shared/sentry";
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
+import { Box, CardContent, Typography } from "@mui/material";
+import Card from "@mui/material/Card";
export enum SetupMode {
QR_CODE,
@@ -35,7 +35,7 @@ export default function SetupTwoFactor({ router, appName }: PageProps) {
const twoFactorSecret = await setupTwoFactor();
setTwoFactorSecret(twoFactorSecret);
} catch (e) {
- logError(e, 'failed to get two factor setup code');
+ logError(e, "failed to get two factor setup code");
}
};
main();
@@ -43,10 +43,10 @@ export default function SetupTwoFactor({ router, appName }: PageProps) {
const onSubmit: VerifyTwoFactorCallback = async (
otp: string,
- markSuccessful
+ markSuccessful,
) => {
const recoveryEncryptedTwoFactorSecret = await encryptWithRecoveryKey(
- twoFactorSecret.secretCode
+ twoFactorSecret.secretCode,
);
await enableTwoFactor(otp, recoveryEncryptedTwoFactorSecret);
await markSuccessful();
@@ -64,16 +64,16 @@ export default function SetupTwoFactor({ router, appName }: PageProps) {
<VerticallyCentered sx={{ p: 3 }}>
<Box mb={4}>
<Typography variant="h2">
- {t('TWO_FACTOR')}
+ {t("TWO_FACTOR")}
</Typography>
</Box>
<TwoFactorSetup twoFactorSecret={twoFactorSecret} />
<VerifyTwoFactor
onSubmit={onSubmit}
- buttonText={t('ENABLE')}
+ buttonText={t("ENABLE")}
/>
<LinkButton sx={{ mt: 2 }} onClick={router.back}>
- {t('GO_BACK')}
+ {t("GO_BACK")}
</LinkButton>
</VerticallyCentered>
</CardContent>
diff --git a/packages/accounts/pages/two-factor/verify.tsx b/packages/accounts/pages/two-factor/verify.tsx
index ae5d2b1414..c10759f19b 100644
--- a/packages/accounts/pages/two-factor/verify.tsx
+++ b/packages/accounts/pages/two-factor/verify.tsx
@@ -1,26 +1,26 @@
+import { verifyTwoFactor } from "@ente/accounts/api/user";
import VerifyTwoFactor, {
VerifyTwoFactorCallback,
-} from '@ente/accounts/components/two-factor/VerifyForm';
-import { useEffect, useState } from 'react';
-import { logoutUser } from '@ente/accounts/services/user';
-import { verifyTwoFactor } from '@ente/accounts/api/user';
-import { PAGES } from '@ente/accounts/constants/pages';
-import { User } from '@ente/shared/user/types';
-import { setData, LS_KEYS, getData } from '@ente/shared/storage/localStorage';
-import { t } from 'i18next';
+} from "@ente/accounts/components/two-factor/VerifyForm";
+import { PAGES } from "@ente/accounts/constants/pages";
+import { logoutUser } from "@ente/accounts/services/user";
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
+import { User } from "@ente/shared/user/types";
+import { t } from "i18next";
+import { useEffect, useState } from "react";
-import LinkButton from '@ente/shared/components/LinkButton';
-import FormPaper from '@ente/shared/components/Form/FormPaper';
-import FormTitle from '@ente/shared/components/Form/FormPaper/Title';
-import FormPaperFooter from '@ente/shared/components/Form/FormPaper/Footer';
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
-import { ApiError } from '@ente/shared/error';
-import { HttpStatusCode } from 'axios';
-import { PageProps } from '@ente/shared/apps/types';
+import { PageProps } from "@ente/shared/apps/types";
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import FormPaper from "@ente/shared/components/Form/FormPaper";
+import FormPaperFooter from "@ente/shared/components/Form/FormPaper/Footer";
+import FormTitle from "@ente/shared/components/Form/FormPaper/Title";
+import LinkButton from "@ente/shared/components/LinkButton";
+import { ApiError } from "@ente/shared/error";
+import InMemoryStore, { MS_KEYS } from "@ente/shared/storage/InMemoryStore";
+import { HttpStatusCode } from "axios";
export default function TwoFactorVerify({ router }: PageProps) {
- const [sessionID, setSessionID] = useState('');
+ const [sessionID, setSessionID] = useState("");
useEffect(() => {
const main = async () => {
@@ -67,17 +67,18 @@ export default function TwoFactorVerify({ router }: PageProps) {
return (
<VerticallyCentered>
- <FormPaper sx={{ maxWidth: '410px' }}>
- <FormTitle>{t('TWO_FACTOR')}</FormTitle>
- <VerifyTwoFactor onSubmit={onSubmit} buttonText={t('VERIFY')} />
+ <FormPaper sx={{ maxWidth: "410px" }}>
+ <FormTitle>{t("TWO_FACTOR")}</FormTitle>
+ <VerifyTwoFactor onSubmit={onSubmit} buttonText={t("VERIFY")} />
- <FormPaperFooter style={{ justifyContent: 'space-between' }}>
+ <FormPaperFooter style={{ justifyContent: "space-between" }}>
<LinkButton
- onClick={() => router.push(PAGES.TWO_FACTOR_RECOVER)}>
- {t('LOST_DEVICE')}
+ onClick={() => router.push(PAGES.TWO_FACTOR_RECOVER)}
+ >
+ {t("LOST_DEVICE")}
</LinkButton>
<LinkButton onClick={logoutUser}>
- {t('CHANGE_EMAIL')}
+ {t("CHANGE_EMAIL")}
</LinkButton>
</FormPaperFooter>
</FormPaper>
diff --git a/packages/accounts/pages/verify.tsx b/packages/accounts/pages/verify.tsx
index 4bc5402411..6f657d95af 100644
--- a/packages/accounts/pages/verify.tsx
+++ b/packages/accounts/pages/verify.tsx
@@ -1,46 +1,46 @@
-import { t } from 'i18next';
-import { useEffect, useState } from 'react';
-import { Trans } from 'react-i18next';
+import { t } from "i18next";
+import { useEffect, useState } from "react";
+import { Trans } from "react-i18next";
-import { UserVerificationResponse } from '@ente/accounts/types/user';
-import { PageProps } from '@ente/shared/apps/types';
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import FormPaper from '@ente/shared/components/Form/FormPaper';
-import FormPaperFooter from '@ente/shared/components/Form/FormPaper/Footer';
-import FormPaperTitle from '@ente/shared/components/Form/FormPaper/Title';
-import LinkButton from '@ente/shared/components/LinkButton';
+import { UserVerificationResponse } from "@ente/accounts/types/user";
+import { PageProps } from "@ente/shared/apps/types";
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import FormPaper from "@ente/shared/components/Form/FormPaper";
+import FormPaperFooter from "@ente/shared/components/Form/FormPaper/Footer";
+import FormPaperTitle from "@ente/shared/components/Form/FormPaper/Title";
+import LinkButton from "@ente/shared/components/LinkButton";
import SingleInputForm, {
SingleInputFormProps,
-} from '@ente/shared/components/SingleInputForm';
-import { ApiError } from '@ente/shared/error';
-import { getAccountsURL } from '@ente/shared/network/api';
-import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
-import { clearFiles } from '@ente/shared/storage/localForage/helpers';
-import { LS_KEYS, getData, setData } from '@ente/shared/storage/localStorage';
+} from "@ente/shared/components/SingleInputForm";
+import { ApiError } from "@ente/shared/error";
+import { getAccountsURL } from "@ente/shared/network/api";
+import InMemoryStore, { MS_KEYS } from "@ente/shared/storage/InMemoryStore";
+import { clearFiles } from "@ente/shared/storage/localForage/helpers";
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
import {
getLocalReferralSource,
setIsFirstLogin,
-} from '@ente/shared/storage/localStorage/helpers';
-import { clearKeys } from '@ente/shared/storage/sessionStorage';
-import { KeyAttributes, User } from '@ente/shared/user/types';
-import { Box, Typography } from '@mui/material';
-import { HttpStatusCode } from 'axios';
-import { putAttributes, sendOtt, verifyOtt } from '../api/user';
-import { PAGES } from '../constants/pages';
-import { configureSRP } from '../services/srp';
-import { logoutUser } from '../services/user';
-import { SRPSetupAttributes } from '../types/srp';
+} from "@ente/shared/storage/localStorage/helpers";
+import { clearKeys } from "@ente/shared/storage/sessionStorage";
+import { KeyAttributes, User } from "@ente/shared/user/types";
+import { Box, Typography } from "@mui/material";
+import { HttpStatusCode } from "axios";
+import { putAttributes, sendOtt, verifyOtt } from "../api/user";
+import { PAGES } from "../constants/pages";
+import { configureSRP } from "../services/srp";
+import { logoutUser } from "../services/user";
+import { SRPSetupAttributes } from "../types/srp";
export default function VerifyPage({ appContext, router, appName }: PageProps) {
- const [email, setEmail] = useState('');
+ const [email, setEmail] = useState("");
const [resend, setResend] = useState(0);
useEffect(() => {
const main = async () => {
const user: User = getData(LS_KEYS.USER);
const keyAttributes: KeyAttributes = getData(
- LS_KEYS.KEY_ATTRIBUTES
+ LS_KEYS.KEY_ATTRIBUTES,
);
if (!user?.email) {
router.push(PAGES.ROOT);
@@ -57,9 +57,9 @@ export default function VerifyPage({ appContext, router, appName }: PageProps) {
appContext.showNavBar(true);
}, []);
- const onSubmit: SingleInputFormProps['callback'] = async (
+ const onSubmit: SingleInputFormProps["callback"] = async (
ott,
- setFieldError
+ setFieldError,
) => {
try {
const referralSource = getLocalReferralSource();
@@ -108,12 +108,12 @@ export default function VerifyPage({ appContext, router, appName }: PageProps) {
if (getData(LS_KEYS.ORIGINAL_KEY_ATTRIBUTES)) {
await putAttributes(
token,
- getData(LS_KEYS.ORIGINAL_KEY_ATTRIBUTES)
+ getData(LS_KEYS.ORIGINAL_KEY_ATTRIBUTES),
);
}
if (getData(LS_KEYS.SRP_SETUP_ATTRIBUTES)) {
const srpSetupAttributes: SRPSetupAttributes = getData(
- LS_KEYS.SRP_SETUP_ATTRIBUTES
+ LS_KEYS.SRP_SETUP_ATTRIBUTES,
);
await configureSRP(srpSetupAttributes);
}
@@ -132,12 +132,12 @@ export default function VerifyPage({ appContext, router, appName }: PageProps) {
} catch (e) {
if (e instanceof ApiError) {
if (e?.httpStatusCode === HttpStatusCode.Unauthorized) {
- setFieldError(t('INVALID_CODE'));
+ setFieldError(t("INVALID_CODE"));
} else if (e?.httpStatusCode === HttpStatusCode.Gone) {
- setFieldError(t('EXPIRED_CODE'));
+ setFieldError(t("EXPIRED_CODE"));
}
} else {
- setFieldError(`${t('UNKNOWN_ERROR')} ${JSON.stringify(e)}`);
+ setFieldError(`${t("UNKNOWN_ERROR")} ${JSON.stringify(e)}`);
}
}
};
@@ -160,36 +160,36 @@ export default function VerifyPage({ appContext, router, appName }: PageProps) {
return (
<VerticallyCentered>
<FormPaper>
- <FormPaperTitle sx={{ mb: 14, wordBreak: 'break-word' }}>
+ <FormPaperTitle sx={{ mb: 14, wordBreak: "break-word" }}>
<Trans
i18nKey="EMAIL_SENT"
components={{
- a: <Box color="text.muted" component={'span'} />,
+ a: <Box color="text.muted" component={"span"} />,
}}
values={{ email }}
/>
</FormPaperTitle>
- <Typography color={'text.muted'} mb={2} variant="small">
- {t('CHECK_INBOX')}
+ <Typography color={"text.muted"} mb={2} variant="small">
+ {t("CHECK_INBOX")}
</Typography>
<SingleInputForm
fieldType="text"
autoComplete="one-time-code"
- placeholder={t('ENTER_OTT')}
- buttonText={t('VERIFY')}
+ placeholder={t("ENTER_OTT")}
+ buttonText={t("VERIFY")}
callback={onSubmit}
/>
- <FormPaperFooter style={{ justifyContent: 'space-between' }}>
+ <FormPaperFooter style={{ justifyContent: "space-between" }}>
{resend === 0 && (
<LinkButton onClick={resendEmail}>
- {t('RESEND_MAIL')}
+ {t("RESEND_MAIL")}
</LinkButton>
)}
- {resend === 1 && <span>{t('SENDING')}</span>}
- {resend === 2 && <span>{t('SENT')}</span>}
+ {resend === 1 && <span>{t("SENDING")}</span>}
+ {resend === 2 && <span>{t("SENT")}</span>}
<LinkButton onClick={logoutUser}>
- {t('CHANGE_EMAIL')}
+ {t("CHANGE_EMAIL")}
</LinkButton>
</FormPaperFooter>
</FormPaper>
diff --git a/packages/accounts/services/srp.ts b/packages/accounts/services/srp.ts
index 7a4c659261..720080d63b 100644
--- a/packages/accounts/services/srp.ts
+++ b/packages/accounts/services/srp.ts
@@ -1,24 +1,24 @@
-import { SRP, SrpClient } from 'fast-srp-hap';
-
-import { SRPAttributes, SRPSetupAttributes } from '../types/srp';
-
-import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
-import { convertBase64ToBuffer, convertBufferToBase64 } from '../utils';
+import { SRP, SrpClient } from "fast-srp-hap";
+
+import { SRPAttributes, SRPSetupAttributes } from "../types/srp";
+
+import { UserVerificationResponse } from "@ente/accounts/types/user";
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { generateLoginSubKey } from "@ente/shared/crypto/helpers";
+import { addLocalLog } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import InMemoryStore, { MS_KEYS } from "@ente/shared/storage/InMemoryStore";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
+import { v4 as uuidv4 } from "uuid";
import {
completeSRPSetup,
createSRPSession,
startSRPSetup,
verifySRPSession,
-} from '../api/srp';
-import { v4 as uuidv4 } from 'uuid';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { generateLoginSubKey } from '@ente/shared/crypto/helpers';
-import { UserVerificationResponse } from '@ente/accounts/types/user';
-import { logError } from '@ente/shared/sentry';
-import { addLocalLog } from '@ente/shared/logging';
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
+} from "../api/srp";
+import { convertBase64ToBuffer, convertBufferToBase64 } from "../utils";
-const SRP_PARAMS = SRP.params['4096'];
+const SRP_PARAMS = SRP.params["4096"];
export const configureSRP = async ({
srpSalt,
@@ -28,16 +28,16 @@ export const configureSRP = async ({
}: SRPSetupAttributes) => {
try {
const srpConfigureInProgress = InMemoryStore.get(
- MS_KEYS.SRP_CONFIGURE_IN_PROGRESS
+ MS_KEYS.SRP_CONFIGURE_IN_PROGRESS,
);
if (srpConfigureInProgress) {
- throw Error('SRP configure already in progress');
+ throw Error("SRP configure already in progress");
}
InMemoryStore.set(MS_KEYS.SRP_CONFIGURE_IN_PROGRESS, true);
const srpClient = await generateSRPClient(
srpSalt,
srpUserID,
- loginSubKey
+ loginSubKey,
);
const srpA = convertBufferToBase64(srpClient.computeA());
@@ -62,7 +62,7 @@ export const configureSRP = async ({
srpClient.checkM2(convertBase64ToBuffer(srpM2));
} catch (e) {
- logError(e, 'srp configure failed');
+ logError(e, "srp configure failed");
throw e;
} finally {
InMemoryStore.set(MS_KEYS.SRP_CONFIGURE_IN_PROGRESS, false);
@@ -70,7 +70,7 @@ export const configureSRP = async ({
};
export const generateSRPSetupAttributes = async (
- loginSubKey: string
+ loginSubKey: string,
): Promise<SRPSetupAttributes> => {
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
@@ -82,7 +82,7 @@ export const generateSRPSetupAttributes = async (
SRP_PARAMS,
convertBase64ToBuffer(srpSalt),
Buffer.from(srpUserID),
- convertBase64ToBuffer(loginSubKey)
+ convertBase64ToBuffer(loginSubKey),
);
const srpVerifier = convertBufferToBase64(srpVerifierBuffer);
@@ -94,7 +94,7 @@ export const generateSRPSetupAttributes = async (
srpUserID,
srpVerifier,
loginSubKey,
- })}`
+ })}`,
);
return {
@@ -107,19 +107,19 @@ export const generateSRPSetupAttributes = async (
export const loginViaSRP = async (
srpAttributes: SRPAttributes,
- kek: string
+ kek: string,
): Promise<UserVerificationResponse> => {
try {
const loginSubKey = await generateLoginSubKey(kek);
const srpClient = await generateSRPClient(
srpAttributes.srpSalt,
srpAttributes.srpUserID,
- loginSubKey
+ loginSubKey,
);
const srpA = srpClient.computeA();
const { srpB, sessionID } = await createSRPSession(
srpAttributes.srpUserID,
- convertBufferToBase64(srpA)
+ convertBufferToBase64(srpA),
);
srpClient.setB(convertBase64ToBuffer(srpB));
@@ -128,7 +128,7 @@ export const loginViaSRP = async (
const { srpM2, ...rest } = await verifySRPSession(
sessionID,
srpAttributes.srpUserID,
- convertBufferToBase64(m1)
+ convertBufferToBase64(m1),
);
addLocalLog(() => `srp verify session successful,srpM2: ${srpM2}`);
@@ -137,7 +137,7 @@ export const loginViaSRP = async (
addLocalLog(() => `srp server verify successful`);
return rest;
} catch (e) {
- logError(e, 'srp verify failed');
+ logError(e, "srp verify failed");
throw e;
}
};
@@ -149,7 +149,7 @@ export const loginViaSRP = async (
export const generateSRPClient = async (
srpSalt: string,
srpUserID: string,
- loginSubKey: string
+ loginSubKey: string,
) => {
return new Promise<SrpClient>((resolve, reject) => {
SRP.genKey(function (err, secret1) {
@@ -158,7 +158,7 @@ export const generateSRPClient = async (
reject(err);
}
if (!secret1) {
- throw Error('secret1 gen failed');
+ throw Error("secret1 gen failed");
}
const srpClient = new SrpClient(
SRP_PARAMS,
@@ -166,7 +166,7 @@ export const generateSRPClient = async (
Buffer.from(srpUserID),
convertBase64ToBuffer(loginSubKey),
secret1,
- false
+ false,
);
resolve(srpClient);
diff --git a/packages/accounts/services/user.ts b/packages/accounts/services/user.ts
index 2a6b4915ee..4fb56db634 100644
--- a/packages/accounts/services/user.ts
+++ b/packages/accounts/services/user.ts
@@ -1,15 +1,15 @@
-import InMemoryStore from '@ente/shared/storage/InMemoryStore';
-import { _logout } from '../api/user';
-import { PAGES } from '../constants/pages';
-import { clearKeys } from '@ente/shared/storage/sessionStorage';
-import { clearData } from '@ente/shared/storage/localStorage';
-import { deleteAllCache } from '@ente/shared/storage/cacheStorage/helpers';
-import { logError } from '@ente/shared/sentry';
-import { clearFiles } from '@ente/shared/storage/localForage/helpers';
-import router from 'next/router';
-import isElectron from 'is-electron';
-import ElectronAPIs from '@ente/shared/electron';
-import { Events, eventBus } from '@ente/shared/events';
+import ElectronAPIs from "@ente/shared/electron";
+import { Events, eventBus } from "@ente/shared/events";
+import { logError } from "@ente/shared/sentry";
+import InMemoryStore from "@ente/shared/storage/InMemoryStore";
+import { deleteAllCache } from "@ente/shared/storage/cacheStorage/helpers";
+import { clearFiles } from "@ente/shared/storage/localForage/helpers";
+import { clearData } from "@ente/shared/storage/localStorage";
+import { clearKeys } from "@ente/shared/storage/sessionStorage";
+import isElectron from "is-electron";
+import router from "next/router";
+import { _logout } from "../api/user";
+import { PAGES } from "../constants/pages";
export const logoutUser = async () => {
try {
@@ -22,42 +22,42 @@ export const logoutUser = async () => {
InMemoryStore.clear();
} catch (e) {
// ignore
- logError(e, 'clear InMemoryStore failed');
+ logError(e, "clear InMemoryStore failed");
}
try {
clearKeys();
} catch (e) {
- logError(e, 'clearKeys failed');
+ logError(e, "clearKeys failed");
}
try {
clearData();
} catch (e) {
- logError(e, 'clearData failed');
+ logError(e, "clearData failed");
}
try {
await deleteAllCache();
} catch (e) {
- logError(e, 'deleteAllCache failed');
+ logError(e, "deleteAllCache failed");
}
try {
await clearFiles();
} catch (e) {
- logError(e, 'clearFiles failed');
+ logError(e, "clearFiles failed");
}
if (isElectron()) {
try {
ElectronAPIs.clearElectronStore();
} catch (e) {
- logError(e, 'clearElectronStore failed');
+ logError(e, "clearElectronStore failed");
}
}
try {
eventBus.emit(Events.LOGOUT);
} catch (e) {
- logError(e, 'Error in logout handlers');
+ logError(e, "Error in logout handlers");
}
router.push(PAGES.ROOT);
} catch (e) {
- logError(e, 'logoutUser failed');
+ logError(e, "logoutUser failed");
}
};
diff --git a/packages/accounts/types/srp.ts b/packages/accounts/types/srp.ts
index 5051f7feeb..48bd193d99 100644
--- a/packages/accounts/types/srp.ts
+++ b/packages/accounts/types/srp.ts
@@ -1,7 +1,7 @@
import {
UpdatedKey,
UserVerificationResponse,
-} from '@ente/accounts/types/user';
+} from "@ente/accounts/types/user";
export interface SRPAttributes {
srpUserID: string;
diff --git a/packages/accounts/types/user.ts b/packages/accounts/types/user.ts
index fc216194ba..f758c39715 100644
--- a/packages/accounts/types/user.ts
+++ b/packages/accounts/types/user.ts
@@ -1,4 +1,4 @@
-import { KeyAttributes } from '@ente/shared/user/types';
+import { KeyAttributes } from "@ente/shared/user/types";
export interface UserVerificationResponse {
id: number;
diff --git a/packages/accounts/utils/index.ts b/packages/accounts/utils/index.ts
index 4c2bb2545a..60de6611bc 100644
--- a/packages/accounts/utils/index.ts
+++ b/packages/accounts/utils/index.ts
@@ -1,12 +1,12 @@
-import { PasswordStrength } from '@ente/accounts/constants';
-import zxcvbn from 'zxcvbn';
+import { PasswordStrength } from "@ente/accounts/constants";
+import zxcvbn from "zxcvbn";
export const convertBufferToBase64 = (buffer: Buffer) => {
- return buffer.toString('base64');
+ return buffer.toString("base64");
};
export const convertBase64ToBuffer = (base64: string) => {
- return Buffer.from(base64, 'base64');
+ return Buffer.from(base64, "base64");
};
export function estimatePasswordStrength(password: string): PasswordStrength {
diff --git a/packages/accounts/utils/srp.ts b/packages/accounts/utils/srp.ts
index 195b7d7693..7aaceaa2c6 100644
--- a/packages/accounts/utils/srp.ts
+++ b/packages/accounts/utils/srp.ts
@@ -1,8 +1,8 @@
-import { generateLoginSubKey } from '@ente/shared/crypto/helpers';
-import { KeyAttributes } from '@ente/shared/user/types';
-import { generateSRPSetupAttributes } from '../services/srp';
-import { SRPSetupAttributes } from '../types/srp';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { generateLoginSubKey } from "@ente/shared/crypto/helpers";
+import { KeyAttributes } from "@ente/shared/user/types";
+import { generateSRPSetupAttributes } from "../services/srp";
+import { SRPSetupAttributes } from "../types/srp";
export async function generateKeyAndSRPAttributes(passphrase: string): Promise<{
keyAttributes: KeyAttributes;
@@ -17,21 +17,21 @@ export async function generateKeyAndSRPAttributes(passphrase: string): Promise<{
const masterKeyEncryptedWithKek = await cryptoWorker.encryptToB64(
masterKey,
- kek.key
+ kek.key,
);
const masterKeyEncryptedWithRecoveryKey = await cryptoWorker.encryptToB64(
masterKey,
- recoveryKey
+ recoveryKey,
);
const recoveryKeyEncryptedWithMasterKey = await cryptoWorker.encryptToB64(
recoveryKey,
- masterKey
+ masterKey,
);
const keyPair = await cryptoWorker.generateKeyPair();
const encryptedKeyPairAttributes = await cryptoWorker.encryptToB64(
keyPair.privateKey,
- masterKey
+ masterKey,
);
const loginSubKey = await generateLoginSubKey(kek.key);
diff --git a/packages/build-config/.prettierrc.json b/packages/build-config/.prettierrc.json
deleted file mode 100644
index 0a02bcefda..0000000000
--- a/packages/build-config/.prettierrc.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "tabWidth": 4
-}
diff --git a/packages/eslint-config/.eslintrc.js b/packages/eslint-config/.eslintrc.js
index 6ca4594799..fa1fde4acd 100644
--- a/packages/eslint-config/.eslintrc.js
+++ b/packages/eslint-config/.eslintrc.js
@@ -1,9 +1,9 @@
module.exports = {
- extends: ['@ente/eslint-config'],
- parser: '@typescript-eslint/parser',
+ extends: ["@ente/eslint-config"],
+ parser: "@typescript-eslint/parser",
parserOptions: {
tsconfigRootDir: __dirname,
- project: './tsconfig.json',
+ project: "./tsconfig.json",
},
- ignorePatterns: ['.eslintrc.js'],
+ ignorePatterns: [".eslintrc.js"],
};
diff --git a/packages/eslint-config/index.js b/packages/eslint-config/index.js
index b2958e477f..84af2062da 100644
--- a/packages/eslint-config/index.js
+++ b/packages/eslint-config/index.js
@@ -1,68 +1,68 @@
module.exports = {
extends: [
- 'next/core-web-vitals',
- 'eslint:recommended',
- 'plugin:@typescript-eslint/recommended',
- 'plugin:@typescript-eslint/recommended-requiring-type-checking',
- 'prettier',
+ "next/core-web-vitals",
+ "eslint:recommended",
+ "plugin:@typescript-eslint/recommended",
+ "plugin:@typescript-eslint/recommended-requiring-type-checking",
+ "prettier",
],
parserOptions: {
tsconfigRootDir: __dirname,
- project: './tsconfig.json',
+ project: "./tsconfig.json",
},
- plugins: ['@typescript-eslint'],
+ plugins: ["@typescript-eslint"],
rules: {
- indent: 'off',
- 'class-methods-use-this': 'off',
- 'react/prop-types': 'off',
- 'react/display-name': 'off',
- 'react/no-unescaped-entities': 'off',
- 'no-unused-vars': 'off',
- '@typescript-eslint/no-unused-vars': ['error'],
- 'require-jsdoc': 'off',
- 'valid-jsdoc': 'off',
- 'max-len': 'off',
- 'new-cap': 'off',
- 'no-invalid-this': 'off',
- eqeqeq: 'error',
- 'object-curly-spacing': ['error', 'always'],
- 'space-before-function-paren': 'off',
- 'operator-linebreak': [
- 'error',
- 'after',
- { overrides: { '?': 'before', ':': 'before' } },
+ indent: "off",
+ "class-methods-use-this": "off",
+ "react/prop-types": "off",
+ "react/display-name": "off",
+ "react/no-unescaped-entities": "off",
+ "no-unused-vars": "off",
+ "@typescript-eslint/no-unused-vars": ["error"],
+ "require-jsdoc": "off",
+ "valid-jsdoc": "off",
+ "max-len": "off",
+ "new-cap": "off",
+ "no-invalid-this": "off",
+ eqeqeq: "error",
+ "object-curly-spacing": ["error", "always"],
+ "space-before-function-paren": "off",
+ "operator-linebreak": [
+ "error",
+ "after",
+ { overrides: { "?": "before", ":": "before" } },
],
- 'import/no-anonymous-default-export': [
- 'error',
+ "import/no-anonymous-default-export": [
+ "error",
{
allowNew: true,
},
],
- '@typescript-eslint/no-unsafe-member-access': 'off',
- '@typescript-eslint/no-unsafe-return': 'off',
- '@typescript-eslint/no-unsafe-assignment': 'off',
- '@typescript-eslint/no-inferrable-types': 'off',
- '@typescript-eslint/restrict-template-expressions': 'off',
- '@typescript-eslint/ban-types': 'off',
- '@typescript-eslint/no-floating-promises': 'off',
- '@typescript-eslint/no-unsafe-call': 'off',
- '@typescript-eslint/require-await': 'off',
- '@typescript-eslint/restrict-plus-operands': 'off',
- '@typescript-eslint/no-var-requires': 'off',
- '@typescript-eslint/no-empty-interface': 'off',
- '@typescript-eslint/no-misused-promises': 'off',
- '@typescript-eslint/no-empty-function': 'off',
- '@typescript-eslint/explicit-module-boundary-types': 'off',
- '@typescript-eslint/no-explicit-any': 'off',
- '@typescript-eslint/no-unnecessary-type-assertion': 'off',
- 'react-hooks/rules-of-hooks': 'off',
- 'react-hooks/exhaustive-deps': 'off',
- '@next/next/no-img-element': 'off',
- '@typescript-eslint/no-unsafe-argument': 'off',
- 'jsx-a11y/alt-text': 'off',
+ "@typescript-eslint/no-unsafe-member-access": "off",
+ "@typescript-eslint/no-unsafe-return": "off",
+ "@typescript-eslint/no-unsafe-assignment": "off",
+ "@typescript-eslint/no-inferrable-types": "off",
+ "@typescript-eslint/restrict-template-expressions": "off",
+ "@typescript-eslint/ban-types": "off",
+ "@typescript-eslint/no-floating-promises": "off",
+ "@typescript-eslint/no-unsafe-call": "off",
+ "@typescript-eslint/require-await": "off",
+ "@typescript-eslint/restrict-plus-operands": "off",
+ "@typescript-eslint/no-var-requires": "off",
+ "@typescript-eslint/no-empty-interface": "off",
+ "@typescript-eslint/no-misused-promises": "off",
+ "@typescript-eslint/no-empty-function": "off",
+ "@typescript-eslint/explicit-module-boundary-types": "off",
+ "@typescript-eslint/no-explicit-any": "off",
+ "@typescript-eslint/no-unnecessary-type-assertion": "off",
+ "react-hooks/rules-of-hooks": "off",
+ "react-hooks/exhaustive-deps": "off",
+ "@next/next/no-img-element": "off",
+ "@typescript-eslint/no-unsafe-argument": "off",
+ "jsx-a11y/alt-text": "off",
// Temporarily turn these off to allow existing code.
// TODO (MR): Remove me (and those above).
- '@typescript-eslint/no-unsafe-enum-comparison': 'off',
- '@typescript-eslint/no-base-to-string': 'off',
+ "@typescript-eslint/no-unsafe-enum-comparison": "off",
+ "@typescript-eslint/no-base-to-string": "off",
},
};
diff --git a/packages/next/.prettierrc.json b/packages/next/.prettierrc.json
deleted file mode 100644
index 0a02bcefda..0000000000
--- a/packages/next/.prettierrc.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "tabWidth": 4
-}
diff --git a/packages/shared/.eslintrc.js b/packages/shared/.eslintrc.js
index 60466d6e16..556f3b6392 100644
--- a/packages/shared/.eslintrc.js
+++ b/packages/shared/.eslintrc.js
@@ -3,11 +3,11 @@ module.exports = {
// This is required here to ensure desktop picks the right eslint config, where this app is
// packaged as a submodule.
root: true,
- extends: ['@ente/eslint-config'],
- parser: '@typescript-eslint/parser',
+ extends: ["@ente/eslint-config"],
+ parser: "@typescript-eslint/parser",
parserOptions: {
tsconfigRootDir: __dirname,
- project: './tsconfig.json',
+ project: "./tsconfig.json",
},
- ignorePatterns: ['.eslintrc.js'],
+ ignorePatterns: [".eslintrc.js"],
};
diff --git a/packages/shared/apps/constants.ts b/packages/shared/apps/constants.ts
index 3e3ecbf87b..d35a5e8c47 100644
--- a/packages/shared/apps/constants.ts
+++ b/packages/shared/apps/constants.ts
@@ -1,34 +1,34 @@
-import { ACCOUNTS_PAGES, AUTH_PAGES, PHOTOS_PAGES } from '../constants/pages';
+import { ACCOUNTS_PAGES, AUTH_PAGES, PHOTOS_PAGES } from "../constants/pages";
export enum APPS {
- PHOTOS = 'PHOTOS',
- AUTH = 'AUTH',
- ALBUMS = 'ALBUMS',
- ACCOUNTS = 'ACCOUNTS',
+ PHOTOS = "PHOTOS",
+ AUTH = "AUTH",
+ ALBUMS = "ALBUMS",
+ ACCOUNTS = "ACCOUNTS",
}
export const CLIENT_PACKAGE_NAMES = new Map([
- [APPS.ALBUMS, 'io.ente.albums.web'],
- [APPS.PHOTOS, 'io.ente.photos.web'],
- [APPS.AUTH, 'io.ente.auth.web'],
- [APPS.ACCOUNTS, 'io.ente.accounts.web'],
+ [APPS.ALBUMS, "io.ente.albums.web"],
+ [APPS.PHOTOS, "io.ente.photos.web"],
+ [APPS.AUTH, "io.ente.auth.web"],
+ [APPS.ACCOUNTS, "io.ente.accounts.web"],
]);
export const APP_TITLES = new Map([
- [APPS.ALBUMS, 'Ente Albums'],
- [APPS.PHOTOS, 'Ente Photos'],
- [APPS.AUTH, 'Ente Auth'],
- [APPS.ACCOUNTS, 'Ente Accounts'],
+ [APPS.ALBUMS, "Ente Albums"],
+ [APPS.PHOTOS, "Ente Photos"],
+ [APPS.AUTH, "Ente Auth"],
+ [APPS.ACCOUNTS, "Ente Accounts"],
]);
export const APP_HOMES = new Map([
- [APPS.ALBUMS, '/'],
+ [APPS.ALBUMS, "/"],
[APPS.PHOTOS, PHOTOS_PAGES.GALLERY],
[APPS.AUTH, AUTH_PAGES.AUTH],
[APPS.ACCOUNTS, ACCOUNTS_PAGES.PASSKEYS],
]);
export const OTT_CLIENTS = new Map([
- [APPS.PHOTOS, 'web'],
- [APPS.AUTH, 'totp'],
+ [APPS.PHOTOS, "web"],
+ [APPS.AUTH, "totp"],
]);
diff --git a/packages/shared/apps/types.ts b/packages/shared/apps/types.ts
index c952e5397d..da5451311e 100644
--- a/packages/shared/apps/types.ts
+++ b/packages/shared/apps/types.ts
@@ -1,8 +1,8 @@
-import { NextRouter } from 'next/router';
-import { APPS } from './constants';
-import { SetDialogBoxAttributesV2 } from '@ente/shared/components/DialogBoxV2/types';
-import { EmotionCache } from '@emotion/react';
-import { AppProps } from 'next/app';
+import { EmotionCache } from "@emotion/react";
+import { SetDialogBoxAttributesV2 } from "@ente/shared/components/DialogBoxV2/types";
+import { AppProps } from "next/app";
+import { NextRouter } from "next/router";
+import { APPS } from "./constants";
export interface EnteAppProps extends AppProps {
emotionCache?: EmotionCache;
diff --git a/packages/shared/components/CaptionedText.tsx b/packages/shared/components/CaptionedText.tsx
index afc3b156f4..64d6c344d0 100644
--- a/packages/shared/components/CaptionedText.tsx
+++ b/packages/shared/components/CaptionedText.tsx
@@ -1,39 +1,41 @@
-import { ButtonProps, Typography } from '@mui/material';
-import { VerticallyCenteredFlex } from '@ente/shared/components/Container';
+import { VerticallyCenteredFlex } from "@ente/shared/components/Container";
+import { ButtonProps, Typography } from "@mui/material";
interface Iprops {
mainText: string;
subText?: string;
subIcon?: React.ReactNode;
- color?: ButtonProps['color'];
+ color?: ButtonProps["color"];
}
-const getSubTextColor = (color: ButtonProps['color']) => {
+const getSubTextColor = (color: ButtonProps["color"]) => {
switch (color) {
- case 'critical':
- return 'critical.main';
+ case "critical":
+ return "critical.main";
default:
- return 'text.faint';
+ return "text.faint";
}
};
export const CaptionedText = (props: Iprops) => {
return (
- <VerticallyCenteredFlex gap={'4px'}>
+ <VerticallyCenteredFlex gap={"4px"}>
<Typography> {props.mainText}</Typography>
<Typography variant="small" color={getSubTextColor(props.color)}>
- {'β€’'}
+ {"β€’"}
</Typography>
{props.subText ? (
<Typography
variant="small"
- color={getSubTextColor(props.color)}>
+ color={getSubTextColor(props.color)}
+ >
{props.subText}
</Typography>
) : (
<Typography
variant="small"
- color={getSubTextColor(props.color)}>
+ color={getSubTextColor(props.color)}
+ >
{props.subIcon}
</Typography>
)}
diff --git a/packages/shared/components/CodeBlock/CopyButton.tsx b/packages/shared/components/CodeBlock/CopyButton.tsx
index 608933459b..3130b6b576 100644
--- a/packages/shared/components/CodeBlock/CopyButton.tsx
+++ b/packages/shared/components/CodeBlock/CopyButton.tsx
@@ -1,13 +1,13 @@
-import React, { useState } from 'react';
-import DoneIcon from '@mui/icons-material/Done';
-import ContentCopyIcon from '@mui/icons-material/ContentCopy';
+import ContentCopyIcon from "@mui/icons-material/ContentCopy";
+import DoneIcon from "@mui/icons-material/Done";
import {
IconButton,
IconButtonProps,
SvgIconProps,
Tooltip,
-} from '@mui/material';
-import { t } from 'i18next';
+} from "@mui/material";
+import { t } from "i18next";
+import { useState } from "react";
export default function CopyButton({
code,
@@ -15,8 +15,8 @@ export default function CopyButton({
size,
}: {
code: string;
- color?: IconButtonProps['color'];
- size?: SvgIconProps['fontSize'];
+ color?: IconButtonProps["color"];
+ size?: SvgIconProps["fontSize"];
}) {
const [copied, setCopied] = useState<boolean>(false);
@@ -29,13 +29,14 @@ export default function CopyButton({
<Tooltip
arrow
open={copied}
- title={t('COPIED')}
- PopperProps={{ sx: { zIndex: 2000 } }}>
+ title={t("COPIED")}
+ PopperProps={{ sx: { zIndex: 2000 } }}
+ >
<IconButton onClick={copyToClipboardHelper(code)} color={color}>
{copied ? (
- <DoneIcon fontSize={size ?? 'small'} />
+ <DoneIcon fontSize={size ?? "small"} />
) : (
- <ContentCopyIcon fontSize={size ?? 'small'} />
+ <ContentCopyIcon fontSize={size ?? "small"} />
)}
</IconButton>
</Tooltip>
diff --git a/packages/shared/components/CodeBlock/index.tsx b/packages/shared/components/CodeBlock/index.tsx
index fc8c5b68ba..bce79de156 100644
--- a/packages/shared/components/CodeBlock/index.tsx
+++ b/packages/shared/components/CodeBlock/index.tsx
@@ -1,20 +1,20 @@
-import { FreeFlowText } from '@ente/shared/components/Container';
-import React from 'react';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { Wrapper, CodeWrapper, CopyButtonWrapper } from './styledComponents';
-import CopyButton from './CopyButton';
-import { BoxProps } from '@mui/material';
+import { FreeFlowText } from "@ente/shared/components/Container";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
+import { BoxProps } from "@mui/material";
+import React from "react";
+import CopyButton from "./CopyButton";
+import { CodeWrapper, CopyButtonWrapper, Wrapper } from "./styledComponents";
type Iprops = React.PropsWithChildren<{
code: string;
- wordBreak?: 'normal' | 'break-all' | 'keep-all' | 'break-word';
+ wordBreak?: "normal" | "break-all" | "keep-all" | "break-word";
}>;
export default function CodeBlock({
code,
wordBreak,
...props
-}: BoxProps<'div', Iprops>) {
+}: BoxProps<"div", Iprops>) {
if (!code) {
return (
<Wrapper>
diff --git a/packages/shared/components/CodeBlock/styledComponents.tsx b/packages/shared/components/CodeBlock/styledComponents.tsx
index 17b0b45ae2..48923c21dc 100644
--- a/packages/shared/components/CodeBlock/styledComponents.tsx
+++ b/packages/shared/components/CodeBlock/styledComponents.tsx
@@ -1,5 +1,5 @@
-import { CenteredFlex } from '@ente/shared/components/Container';
-import { Box, styled } from '@mui/material';
+import { CenteredFlex } from "@ente/shared/components/Container";
+import { Box, styled } from "@mui/material";
export const Wrapper = styled(CenteredFlex)`
position: relative;
background: ${({ theme }) => theme.colors.accent.A700};
@@ -13,7 +13,7 @@ export const CopyButtonWrapper = styled(Box)`
margin-top: ${({ theme }) => theme.spacing(1)};
`;
-export const CodeWrapper = styled('div')`
+export const CodeWrapper = styled("div")`
padding: 16px 36px 16px 16px;
border-radius: ${({ theme }) => theme.shape.borderRadius}px;
`;
diff --git a/packages/shared/components/Collections/CollectionShare/publicShare/switch.tsx b/packages/shared/components/Collections/CollectionShare/publicShare/switch.tsx
index 535ad175e2..bb738a9e9b 100644
--- a/packages/shared/components/Collections/CollectionShare/publicShare/switch.tsx
+++ b/packages/shared/components/Collections/CollectionShare/publicShare/switch.tsx
@@ -1,6 +1,4 @@
-import React from 'react';
-import { SwitchProps, Switch } from '@mui/material';
-import { styled } from '@mui/material';
+import { Switch, SwitchProps, styled } from "@mui/material";
const PublicShareSwitch = styled((props: SwitchProps) => (
<Switch
focusVisibleClassName=".Mui-focusVisible"
@@ -11,50 +9,50 @@ const PublicShareSwitch = styled((props: SwitchProps) => (
width: 40,
height: 24,
padding: 0,
- '& .MuiSwitch-switchBase': {
+ "& .MuiSwitch-switchBase": {
padding: 0,
margin: 2,
- transitionDuration: '300ms',
- '&.Mui-checked': {
- transform: 'translateX(16px)',
- color: '#fff',
- '& + .MuiSwitch-track': {
+ transitionDuration: "300ms",
+ "&.Mui-checked": {
+ transform: "translateX(16px)",
+ color: "#fff",
+ "& + .MuiSwitch-track": {
backgroundColor:
- theme.palette.mode === 'dark' ? '#2ECA45' : '#65C466',
+ theme.palette.mode === "dark" ? "#2ECA45" : "#65C466",
opacity: 1,
border: 0,
},
- '&.Mui-disabled + .MuiSwitch-track': {
+ "&.Mui-disabled + .MuiSwitch-track": {
opacity: 0.5,
},
},
- '&.Mui-focusVisible .MuiSwitch-thumb': {
- color: '#33cf4d',
- border: '6px solid #fff',
+ "&.Mui-focusVisible .MuiSwitch-thumb": {
+ color: "#33cf4d",
+ border: "6px solid #fff",
},
- '&.Mui-disabled .MuiSwitch-thumb': {
+ "&.Mui-disabled .MuiSwitch-thumb": {
color:
- theme.palette.mode === 'light'
+ theme.palette.mode === "light"
? theme.palette.grey[100]
: theme.palette.grey[600],
},
- '&.Mui-disabled + .MuiSwitch-track': {
- opacity: theme.palette.mode === 'light' ? 0.7 : 0.3,
+ "&.Mui-disabled + .MuiSwitch-track": {
+ opacity: theme.palette.mode === "light" ? 0.7 : 0.3,
},
},
- '& .MuiSwitch-thumb': {
- boxSizing: 'border-box',
+ "& .MuiSwitch-thumb": {
+ boxSizing: "border-box",
width: 20,
height: 20,
},
- '& .MuiSwitch-track': {
+ "& .MuiSwitch-track": {
borderRadius: 22 / 2,
backgroundColor:
- theme.palette.mode === 'light'
- ? '#E9E9EA'
+ theme.palette.mode === "light"
+ ? "#E9E9EA"
: theme.colors.fill.muted,
opacity: 1,
- transition: theme.transitions.create(['background-color'], {
+ transition: theme.transitions.create(["background-color"], {
duration: 500,
}),
},
diff --git a/packages/shared/components/Container.tsx b/packages/shared/components/Container.tsx
index f3c399db12..517e058b5a 100644
--- a/packages/shared/components/Container.tsx
+++ b/packages/shared/components/Container.tsx
@@ -1,5 +1,4 @@
-import { Box, IconButton } from '@mui/material';
-import { styled } from '@mui/material';
+import { Box, IconButton, styled } from "@mui/material";
export const VerticallyCentered = styled(Box)`
flex: 1;
@@ -11,7 +10,7 @@ export const VerticallyCentered = styled(Box)`
overflow: auto;
`;
-export const Row = styled('div')`
+export const Row = styled("div")`
min-height: 32px;
display: flex;
align-items: center;
@@ -19,11 +18,11 @@ export const Row = styled('div')`
flex: 1;
`;
-export const Value = styled('div')<{ width?: string }>`
+export const Value = styled("div")<{ width?: string }>`
display: flex;
justify-content: flex-start;
align-items: center;
- width: ${(props) => props.width ?? '30%'};
+ width: ${(props) => props.width ?? "30%"};
`;
export const FlexWrapper = styled(Box)`
@@ -32,7 +31,7 @@ export const FlexWrapper = styled(Box)`
align-items: center;
`;
-export const FreeFlowText = styled('div')`
+export const FreeFlowText = styled("div")`
word-break: break-word;
min-width: 30%;
text-align: left;
@@ -63,14 +62,14 @@ export const IconButtonWithBG = styled(IconButton)(({ theme }) => ({
}));
export const HorizontalFlex = styled(Box)({
- display: 'flex',
+ display: "flex",
});
export const VerticalFlex = styled(HorizontalFlex)({
- flexDirection: 'column',
+ flexDirection: "column",
});
export const VerticallyCenteredFlex = styled(HorizontalFlex)({
- alignItems: 'center',
- display: 'flex',
+ alignItems: "center",
+ display: "flex",
});
diff --git a/packages/shared/components/DialogBox/DialogIcon.tsx b/packages/shared/components/DialogBox/DialogIcon.tsx
index 1a9c275e68..006b7cfeb2 100644
--- a/packages/shared/components/DialogBox/DialogIcon.tsx
+++ b/packages/shared/components/DialogBox/DialogIcon.tsx
@@ -1,5 +1,5 @@
-import { Box } from '@mui/material';
-import React from 'react';
+import { Box } from "@mui/material";
+import React from "react";
export default function DialogIcon({ icon }: { icon: React.ReactNode }) {
return (
@@ -7,11 +7,12 @@ export default function DialogIcon({ icon }: { icon: React.ReactNode }) {
className="DialogIcon"
sx={{
svg: {
- width: '48px',
- height: '48px',
+ width: "48px",
+ height: "48px",
},
- color: 'stroke.muted',
- }}>
+ color: "stroke.muted",
+ }}
+ >
{icon}
</Box>
);
diff --git a/packages/shared/components/DialogBox/TitleWithCloseButton.tsx b/packages/shared/components/DialogBox/TitleWithCloseButton.tsx
index c3457ebc6a..6a3bee18df 100644
--- a/packages/shared/components/DialogBox/TitleWithCloseButton.tsx
+++ b/packages/shared/components/DialogBox/TitleWithCloseButton.tsx
@@ -1,12 +1,11 @@
-import React from 'react';
+import { SpaceBetweenFlex } from "@ente/shared/components/Container";
+import CloseIcon from "@mui/icons-material/Close";
import {
DialogProps,
DialogTitle,
IconButton,
Typography,
-} from '@mui/material';
-import CloseIcon from '@mui/icons-material/Close';
-import { SpaceBetweenFlex } from '@ente/shared/components/Container';
+} from "@mui/material";
const DialogTitleWithCloseButton = (props) => {
const { children, onClose, ...other } = props;
@@ -14,15 +13,16 @@ const DialogTitleWithCloseButton = (props) => {
return (
<DialogTitle {...other}>
<SpaceBetweenFlex>
- <Typography variant="h3" fontWeight={'bold'}>
+ <Typography variant="h3" fontWeight={"bold"}>
{children}
</Typography>
{onClose && (
<IconButton
aria-label="close"
onClick={onClose}
- sx={{ float: 'right' }}
- color="secondary">
+ sx={{ float: "right" }}
+ color="secondary"
+ >
<CloseIcon />
</IconButton>
)}
@@ -42,11 +42,11 @@ export const dialogCloseHandler =
staticBackdrop?: boolean;
nonClosable?: boolean;
onClose: () => void;
- }): DialogProps['onClose'] =>
+ }): DialogProps["onClose"] =>
(_, reason) => {
if (nonClosable) {
// no-op
- } else if (staticBackdrop && reason === 'backdropClick') {
+ } else if (staticBackdrop && reason === "backdropClick") {
// no-op
} else {
onClose();
diff --git a/packages/shared/components/DialogBox/base.tsx b/packages/shared/components/DialogBox/base.tsx
index 159dad9619..86495da5e9 100644
--- a/packages/shared/components/DialogBox/base.tsx
+++ b/packages/shared/components/DialogBox/base.tsx
@@ -1,38 +1,38 @@
-import { Dialog, styled } from '@mui/material';
+import { Dialog, styled } from "@mui/material";
const DialogBoxBase = styled(Dialog)(({ theme }) => ({
- '& .MuiDialog-paper': {
+ "& .MuiDialog-paper": {
padding: theme.spacing(1, 1.5),
- maxWidth: '346px',
+ maxWidth: "346px",
},
- '& .DialogIcon': {
+ "& .DialogIcon": {
padding: theme.spacing(2),
paddingBottom: theme.spacing(1),
},
- '& .MuiDialogTitle-root': {
+ "& .MuiDialogTitle-root": {
padding: theme.spacing(2),
paddingBottom: theme.spacing(1),
},
- '& .MuiDialogContent-root': {
+ "& .MuiDialogContent-root": {
padding: theme.spacing(2),
},
- '.DialogIcon + .MuiDialogTitle-root': {
+ ".DialogIcon + .MuiDialogTitle-root": {
paddingTop: 0,
},
- '.MuiDialogTitle-root + .MuiDialogContent-root': {
+ ".MuiDialogTitle-root + .MuiDialogContent-root": {
paddingTop: 0,
},
- '.MuiDialogTitle-root + .MuiDialogActions-root': {
+ ".MuiDialogTitle-root + .MuiDialogActions-root": {
paddingTop: theme.spacing(3),
},
- '& .MuiDialogActions-root': {
- flexWrap: 'wrap-reverse',
+ "& .MuiDialogActions-root": {
+ flexWrap: "wrap-reverse",
},
- '& .MuiButton-root': {
+ "& .MuiButton-root": {
margin: `${theme.spacing(0.5, 0)} !important`,
},
}));
diff --git a/packages/shared/components/DialogBox/index.tsx b/packages/shared/components/DialogBox/index.tsx
index 23a04992cf..133c2233c4 100644
--- a/packages/shared/components/DialogBox/index.tsx
+++ b/packages/shared/components/DialogBox/index.tsx
@@ -1,4 +1,3 @@
-import React from 'react';
import {
Breakpoint,
Button,
@@ -6,17 +5,18 @@ import {
DialogContent,
DialogProps,
Typography,
-} from '@mui/material';
+} from "@mui/material";
+import { t } from "i18next";
+import React from "react";
+import DialogIcon from "./DialogIcon";
import DialogTitleWithCloseButton, {
dialogCloseHandler,
-} from './TitleWithCloseButton';
-import DialogBoxBase from './base';
-import { DialogBoxAttributes } from './types';
-import DialogIcon from './DialogIcon';
-import { t } from 'i18next';
+} from "./TitleWithCloseButton";
+import DialogBoxBase from "./base";
+import { DialogBoxAttributes } from "./types";
type IProps = React.PropsWithChildren<
- Omit<DialogProps, 'onClose' | 'maxSize'> & {
+ Omit<DialogProps, "onClose" | "maxSize"> & {
onClose: () => void;
attributes: DialogBoxAttributes;
size?: Breakpoint;
@@ -48,7 +48,8 @@ export default function DialogBox({
open={open}
maxWidth={size}
onClose={handleClose}
- {...props}>
+ {...props}
+ >
{attributes.icon && <DialogIcon icon={attributes.icon} />}
{attributes.title && (
<DialogTitleWithCloseButton
@@ -56,7 +57,8 @@ export default function DialogBox({
titleCloseButton &&
!attributes.nonClosable &&
handleClose
- }>
+ }
+ >
{attributes.title}
</DialogTitleWithCloseButton>
)}
@@ -75,13 +77,14 @@ export default function DialogBox({
{attributes.close && (
<Button
size="large"
- color={attributes.close?.variant ?? 'secondary'}
+ color={attributes.close?.variant ?? "secondary"}
onClick={() => {
attributes.close.action &&
attributes.close?.action();
onClose();
- }}>
- {attributes.close?.text ?? t('OK')}
+ }}
+ >
+ {attributes.close?.text ?? t("OK")}
</Button>
)}
{attributes.proceed && (
@@ -92,7 +95,8 @@ export default function DialogBox({
attributes.proceed.action();
onClose();
}}
- disabled={attributes.proceed.disabled}>
+ disabled={attributes.proceed.disabled}
+ >
{attributes.proceed.text}
</Button>
)}
@@ -104,7 +108,8 @@ export default function DialogBox({
attributes.secondary.action();
onClose();
}}
- disabled={attributes.secondary.disabled}>
+ disabled={attributes.secondary.disabled}
+ >
{attributes.secondary.text}
</Button>
)}
diff --git a/packages/shared/components/DialogBox/types.ts b/packages/shared/components/DialogBox/types.ts
index 3637574209..6d076fd5ab 100644
--- a/packages/shared/components/DialogBox/types.ts
+++ b/packages/shared/components/DialogBox/types.ts
@@ -1,4 +1,4 @@
-import { ButtonProps } from '@mui/material';
+import { ButtonProps } from "@mui/material";
export interface DialogBoxAttributes {
icon?: React.ReactNode;
@@ -8,19 +8,19 @@ export interface DialogBoxAttributes {
content?: any;
close?: {
text?: string;
- variant?: ButtonProps['color'];
+ variant?: ButtonProps["color"];
action?: () => void;
};
proceed?: {
text: string;
action: () => void;
- variant?: ButtonProps['color'];
+ variant?: ButtonProps["color"];
disabled?: boolean;
};
secondary?: {
text: string;
action: () => void;
- variant: ButtonProps['color'];
+ variant: ButtonProps["color"];
disabled?: boolean;
};
}
diff --git a/packages/shared/components/DialogBoxV2/index.tsx b/packages/shared/components/DialogBoxV2/index.tsx
index 18bcea87d4..ced595c0ec 100644
--- a/packages/shared/components/DialogBoxV2/index.tsx
+++ b/packages/shared/components/DialogBoxV2/index.tsx
@@ -1,4 +1,5 @@
-import React, { useState } from 'react';
+import { dialogCloseHandler } from "@ente/shared/components/DialogBox/TitleWithCloseButton";
+import EnteButton from "@ente/shared/components/EnteButton";
import {
Box,
Button,
@@ -6,14 +7,13 @@ import {
DialogProps,
Stack,
Typography,
-} from '@mui/material';
-import { t } from 'i18next';
-import { dialogCloseHandler } from '@ente/shared/components/DialogBox/TitleWithCloseButton';
-import { DialogBoxAttributesV2 } from './types';
-import EnteButton from '@ente/shared/components/EnteButton';
+} from "@mui/material";
+import { t } from "i18next";
+import React, { useState } from "react";
+import { DialogBoxAttributesV2 } from "./types";
type IProps = React.PropsWithChildren<
- Omit<DialogProps, 'onClose'> & {
+ Omit<DialogProps, "onClose"> & {
onClose: () => void;
attributes: DialogBoxAttributesV2;
}
@@ -46,26 +46,28 @@ export default function DialogBoxV2({
PaperProps={{
...PaperProps,
sx: {
- padding: '8px 12px',
- maxWidth: '360px',
+ padding: "8px 12px",
+ maxWidth: "360px",
...PaperProps?.sx,
},
}}
- {...rest}>
- <Stack spacing={'36px'} p={'16px'}>
- <Stack spacing={'19px'}>
+ {...rest}
+ >
+ <Stack spacing={"36px"} p={"16px"}>
+ <Stack spacing={"19px"}>
{attributes.icon && (
<Box
sx={{
- '& > svg': {
- fontSize: '32px',
+ "& > svg": {
+ fontSize: "32px",
},
- }}>
+ }}
+ >
{attributes.icon}
</Box>
)}
{attributes.title && (
- <Typography variant="large" fontWeight={'bold'}>
+ <Typography variant="large" fontWeight={"bold"}>
{attributes.title}
</Typography>
)}
@@ -80,13 +82,14 @@ export default function DialogBoxV2({
attributes.close ||
attributes.buttons?.length) && (
<Stack
- spacing={'8px'}
+ spacing={"8px"}
direction={
- attributes.buttonDirection === 'row'
- ? 'row-reverse'
- : 'column'
+ attributes.buttonDirection === "row"
+ ? "row-reverse"
+ : "column"
}
- flex={1}>
+ flex={1}
+ >
{attributes.proceed && (
<EnteButton
loading={loading}
@@ -97,20 +100,22 @@ export default function DialogBoxV2({
onClose();
}}
- disabled={attributes.proceed.disabled}>
+ disabled={attributes.proceed.disabled}
+ >
{attributes.proceed.text}
</EnteButton>
)}
{attributes.close && (
<Button
size="large"
- color={attributes.close?.variant ?? 'secondary'}
+ color={attributes.close?.variant ?? "secondary"}
onClick={() => {
attributes.close.action &&
attributes.close?.action();
onClose();
- }}>
- {attributes.close?.text ?? t('OK')}
+ }}
+ >
+ {attributes.close?.text ?? t("OK")}
</Button>
)}
{attributes.buttons &&
@@ -123,7 +128,8 @@ export default function DialogBoxV2({
b.action();
onClose();
}}
- disabled={b.disabled}>
+ disabled={b.disabled}
+ >
{b.text}
</Button>
))}
diff --git a/packages/shared/components/DialogBoxV2/types.ts b/packages/shared/components/DialogBoxV2/types.ts
index 424e0fb762..939b7e58c0 100644
--- a/packages/shared/components/DialogBoxV2/types.ts
+++ b/packages/shared/components/DialogBoxV2/types.ts
@@ -1,4 +1,4 @@
-import { ButtonProps } from '@mui/material';
+import { ButtonProps } from "@mui/material";
export interface DialogBoxAttributesV2 {
icon?: React.ReactNode;
@@ -8,28 +8,28 @@ export interface DialogBoxAttributesV2 {
content?: any;
close?: {
text?: string;
- variant?: ButtonProps['color'];
+ variant?: ButtonProps["color"];
action?: () => void;
};
proceed?: {
text: string;
action: (setLoading?: (value: boolean) => void) => void | Promise<void>;
- variant?: ButtonProps['color'];
+ variant?: ButtonProps["color"];
disabled?: boolean;
};
secondary?: {
text: string;
action: () => void;
- variant?: ButtonProps['color'];
+ variant?: ButtonProps["color"];
disabled?: boolean;
};
buttons?: {
text: string;
action: () => void;
- variant: ButtonProps['color'];
+ variant: ButtonProps["color"];
disabled?: boolean;
}[];
- buttonDirection?: 'row' | 'column';
+ buttonDirection?: "row" | "column";
}
export type SetDialogBoxAttributesV2 = React.Dispatch<
diff --git a/packages/shared/components/Directory/changeOption.tsx b/packages/shared/components/Directory/changeOption.tsx
index fbac4c198b..f846e9ba9d 100644
--- a/packages/shared/components/Directory/changeOption.tsx
+++ b/packages/shared/components/Directory/changeOption.tsx
@@ -1,8 +1,8 @@
-import OverflowMenu from '@ente/shared/components/OverflowMenu/menu';
-import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';
-import MoreHoriz from '@mui/icons-material/MoreHoriz';
-import { t } from 'i18next';
-import FolderIcon from '@mui/icons-material/Folder';
+import OverflowMenu from "@ente/shared/components/OverflowMenu/menu";
+import { OverflowMenuOption } from "@ente/shared/components/OverflowMenu/option";
+import FolderIcon from "@mui/icons-material/Folder";
+import MoreHoriz from "@mui/icons-material/MoreHoriz";
+import { t } from "i18next";
export default function ChangeDirectoryOption({
changeExportDirectory: changeDirectory,
@@ -14,12 +14,14 @@ export default function ChangeDirectoryOption({
ml: 1,
},
}}
- ariaControls={'export-option'}
- triggerButtonIcon={<MoreHoriz />}>
+ ariaControls={"export-option"}
+ triggerButtonIcon={<MoreHoriz />}
+ >
<OverflowMenuOption
onClick={changeDirectory}
- startIcon={<FolderIcon />}>
- {t('CHANGE_FOLDER')}
+ startIcon={<FolderIcon />}
+ >
+ {t("CHANGE_FOLDER")}
</OverflowMenuOption>
</OverflowMenu>
);
diff --git a/packages/shared/components/Directory/index.tsx b/packages/shared/components/Directory/index.tsx
index e097197887..a872027718 100644
--- a/packages/shared/components/Directory/index.tsx
+++ b/packages/shared/components/Directory/index.tsx
@@ -1,8 +1,8 @@
-import { styled } from '@mui/material/styles';
-import LinkButton from '@ente/shared/components/LinkButton';
-import { Tooltip } from '@mui/material';
-import ElectronAPIs from '@ente/shared/electron';
-import { logError } from '@ente/shared/sentry';
+import LinkButton from "@ente/shared/components/LinkButton";
+import ElectronAPIs from "@ente/shared/electron";
+import { logError } from "@ente/shared/sentry";
+import { Tooltip } from "@mui/material";
+import { styled } from "@mui/material/styles";
const DirectoryPathContainer = styled(LinkButton)(
({ width }) => `
@@ -13,7 +13,7 @@ const DirectoryPathContainer = styled(LinkButton)(
/* Beginning of string */
direction: rtl;
text-align: left;
-`
+`,
);
export const DirectoryPath = ({ width, path }) => {
@@ -21,7 +21,7 @@ export const DirectoryPath = ({ width, path }) => {
try {
await ElectronAPIs.openDirectory(path);
} catch (e) {
- logError(e, 'openDirectory failed');
+ logError(e, "openDirectory failed");
}
};
return (
diff --git a/packages/shared/components/EnteButton.tsx b/packages/shared/components/EnteButton.tsx
index b684198fc6..a77c9202b5 100644
--- a/packages/shared/components/EnteButton.tsx
+++ b/packages/shared/components/EnteButton.tsx
@@ -1,10 +1,10 @@
-import Done from '@mui/icons-material/Done';
+import Done from "@mui/icons-material/Done";
import {
Button,
ButtonProps,
CircularProgress,
PaletteColor,
-} from '@mui/material';
+} from "@mui/material";
interface Iprops extends ButtonProps {
loading?: boolean;
@@ -25,7 +25,7 @@ export default function EnteButton({
sx={{
...sx,
...((loading || success) && {
- '&.Mui-disabled': (theme) => ({
+ "&.Mui-disabled": (theme) => ({
backgroundColor: (
theme.palette[props.color] as PaletteColor
).main,
@@ -34,9 +34,10 @@ export default function EnteButton({
}),
}),
}}
- {...props}>
+ {...props}
+ >
{loading ? (
- <CircularProgress size={20} sx={{ color: 'inherit' }} />
+ <CircularProgress size={20} sx={{ color: "inherit" }} />
) : success ? (
<Done sx={{ fontSize: 20 }} />
) : (
diff --git a/packages/shared/components/EnteDrawer.tsx b/packages/shared/components/EnteDrawer.tsx
index beacae98a0..e6fc35bb15 100644
--- a/packages/shared/components/EnteDrawer.tsx
+++ b/packages/shared/components/EnteDrawer.tsx
@@ -1,10 +1,10 @@
-import { Drawer, styled } from '@mui/material';
+import { Drawer, styled } from "@mui/material";
export const EnteDrawer = styled(Drawer)(({ theme }) => ({
- '& .MuiPaper-root': {
- maxWidth: '375px',
- width: '100%',
- scrollbarWidth: 'thin',
+ "& .MuiPaper-root": {
+ maxWidth: "375px",
+ width: "100%",
+ scrollbarWidth: "thin",
padding: theme.spacing(1),
},
}));
diff --git a/packages/shared/components/EnteLogo.tsx b/packages/shared/components/EnteLogo.tsx
index 425efed345..a22be3f5ef 100644
--- a/packages/shared/components/EnteLogo.tsx
+++ b/packages/shared/components/EnteLogo.tsx
@@ -1,7 +1,6 @@
-import React from 'react';
-import { styled } from '@mui/material';
+import { styled } from "@mui/material";
-const LogoImage = styled('img')`
+const LogoImage = styled("img")`
margin: 3px 0;
pointer-events: none;
`;
diff --git a/packages/shared/components/EnteSpinner.tsx b/packages/shared/components/EnteSpinner.tsx
index 366d38cfb7..8a5d0a2896 100644
--- a/packages/shared/components/EnteSpinner.tsx
+++ b/packages/shared/components/EnteSpinner.tsx
@@ -1,6 +1,6 @@
import CircularProgress, {
CircularProgressProps,
-} from '@mui/material/CircularProgress';
+} from "@mui/material/CircularProgress";
export default function EnteSpinner(props: CircularProgressProps) {
return <CircularProgress color="accent" size={32} {...props} />;
diff --git a/packages/shared/components/Form/FormPaper/Footer.tsx b/packages/shared/components/Form/FormPaper/Footer.tsx
index 90226b99b3..99ca08ddb6 100644
--- a/packages/shared/components/Form/FormPaper/Footer.tsx
+++ b/packages/shared/components/Form/FormPaper/Footer.tsx
@@ -1,18 +1,19 @@
-import { FC } from 'react';
-import { BoxProps, Divider } from '@mui/material';
-import { VerticallyCentered } from '@ente/shared/components/Container';
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import { BoxProps, Divider } from "@mui/material";
+import { FC } from "react";
const FormPaperFooter: FC<BoxProps> = ({ sx, style, ...props }) => {
return (
<>
<Divider />
<VerticallyCentered
- style={{ flexDirection: 'row', ...style }}
+ style={{ flexDirection: "row", ...style }}
sx={{
mt: 3,
...sx,
}}
- {...props}>
+ {...props}
+ >
{props.children}
</VerticallyCentered>
</>
diff --git a/packages/shared/components/Form/FormPaper/Title.tsx b/packages/shared/components/Form/FormPaper/Title.tsx
index 521f5d907f..c9aaf0875a 100644
--- a/packages/shared/components/Form/FormPaper/Title.tsx
+++ b/packages/shared/components/Form/FormPaper/Title.tsx
@@ -1,5 +1,5 @@
-import { FC } from 'react';
-import { Typography, TypographyProps } from '@mui/material';
+import { Typography, TypographyProps } from "@mui/material";
+import { FC } from "react";
const FormPaperTitle: FC<TypographyProps> = ({ sx, ...props }) => {
return (
diff --git a/packages/shared/components/Form/FormPaper/index.tsx b/packages/shared/components/Form/FormPaper/index.tsx
index 32f2ad21a7..5f1eb2d786 100644
--- a/packages/shared/components/Form/FormPaper/index.tsx
+++ b/packages/shared/components/Form/FormPaper/index.tsx
@@ -1,9 +1,9 @@
-import { Paper, styled } from '@mui/material';
+import { Paper, styled } from "@mui/material";
const FormPaper = styled(Paper)(({ theme }) => ({
padding: theme.spacing(4, 2),
- maxWidth: '360px',
- width: '100%',
- textAlign: 'left',
+ maxWidth: "360px",
+ width: "100%",
+ textAlign: "left",
}));
export default FormPaper;
diff --git a/packages/shared/components/Form/ShowHidePassword.tsx b/packages/shared/components/Form/ShowHidePassword.tsx
index 0aa5ed6489..0f3a7d3b5c 100644
--- a/packages/shared/components/Form/ShowHidePassword.tsx
+++ b/packages/shared/components/Form/ShowHidePassword.tsx
@@ -1,13 +1,13 @@
-import React from 'react';
-import { IconButton, InputAdornment } from '@mui/material';
-import VisibilityIcon from '@mui/icons-material/Visibility';
-import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
+import VisibilityIcon from "@mui/icons-material/Visibility";
+import VisibilityOffIcon from "@mui/icons-material/VisibilityOff";
+import { IconButton, InputAdornment } from "@mui/material";
+import React from "react";
interface Iprops {
showPassword: boolean;
handleClickShowPassword: () => void;
handleMouseDownPassword: (
- event: React.MouseEvent<HTMLButtonElement>
+ event: React.MouseEvent<HTMLButtonElement>,
) => void;
}
const ShowHidePassword = ({
@@ -22,7 +22,8 @@ const ShowHidePassword = ({
aria-label="toggle password visibility"
onClick={handleClickShowPassword}
onMouseDown={handleMouseDownPassword}
- edge="end">
+ edge="end"
+ >
{showPassword ? <VisibilityOffIcon /> : <VisibilityIcon />}
</IconButton>
</InputAdornment>
diff --git a/packages/shared/components/Info/InfoItem.tsx b/packages/shared/components/Info/InfoItem.tsx
index 4f85e9fcd0..3cc9f5d35c 100644
--- a/packages/shared/components/Info/InfoItem.tsx
+++ b/packages/shared/components/Info/InfoItem.tsx
@@ -1,8 +1,7 @@
-import Edit from '@mui/icons-material/Edit';
-import { Box, IconButton, Typography } from '@mui/material';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import React from 'react';
-import { SmallLoadingSpinner } from '../styledComponents/SmallLoadingSpinner';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import Edit from "@mui/icons-material/Edit";
+import { Box, IconButton, Typography } from "@mui/material";
+import { SmallLoadingSpinner } from "../styledComponents/SmallLoadingSpinner";
interface Iprops {
icon: JSX.Element;
@@ -27,11 +26,12 @@ export default function InfoItem({
}: Iprops): JSX.Element {
return (
<FlexWrapper justifyContent="space-between">
- <Box display={'flex'} alignItems="flex-start" gap={0.5} pr={1}>
+ <Box display={"flex"} alignItems="flex-start" gap={0.5} pr={1}>
<IconButton
color="secondary"
- sx={{ '&&': { cursor: 'default', m: 0.5 } }}
- disableRipple>
+ sx={{ "&&": { cursor: "default", m: 0.5 } }}
+ disableRipple
+ >
{icon}
</IconButton>
<Box py={0.5}>
@@ -39,7 +39,7 @@ export default function InfoItem({
children
) : (
<>
- <Typography sx={{ wordBreak: 'break-all' }}>
+ <Typography sx={{ wordBreak: "break-all" }}>
{title}
</Typography>
<Typography variant="small" color="text.muted">
diff --git a/packages/shared/components/LinkButton.tsx b/packages/shared/components/LinkButton.tsx
index ea8e7901ee..79578ddb70 100644
--- a/packages/shared/components/LinkButton.tsx
+++ b/packages/shared/components/LinkButton.tsx
@@ -1,5 +1,5 @@
-import { ButtonProps, Link, LinkProps } from '@mui/material';
-import React, { FC } from 'react';
+import { ButtonProps, Link, LinkProps } from "@mui/material";
+import React, { FC } from "react";
export type LinkButtonProps = React.PropsWithChildren<{
onClick: () => void;
@@ -7,7 +7,7 @@ export type LinkButtonProps = React.PropsWithChildren<{
style?: React.CSSProperties;
}>;
-const LinkButton: FC<LinkProps<'button', { color?: ButtonProps['color'] }>> = ({
+const LinkButton: FC<LinkProps<"button", { color?: ButtonProps["color"] }>> = ({
children,
sx,
color,
@@ -17,17 +17,18 @@ const LinkButton: FC<LinkProps<'button', { color?: ButtonProps['color'] }>> = ({
<Link
component="button"
sx={{
- color: 'text.base',
- textDecoration: 'underline rgba(255, 255, 255, 0.4)',
+ color: "text.base",
+ textDecoration: "underline rgba(255, 255, 255, 0.4)",
paddingBottom: 0.5,
- '&:hover': {
+ "&:hover": {
color: `${color}.main`,
textDecoration: `underline `,
textDecorationColor: `${color}.main`,
},
...sx,
}}
- {...props}>
+ {...props}
+ >
{children}
</Link>
);
diff --git a/packages/shared/components/Menu/EnteMenuItem.tsx b/packages/shared/components/Menu/EnteMenuItem.tsx
index d9e25d9e77..a3b6cb7b8d 100644
--- a/packages/shared/components/Menu/EnteMenuItem.tsx
+++ b/packages/shared/components/Menu/EnteMenuItem.tsx
@@ -1,30 +1,30 @@
import {
- MenuItem,
- ButtonProps,
+ SpaceBetweenFlex,
+ VerticallyCenteredFlex,
+} from "@ente/shared/components/Container";
+import {
Box,
+ ButtonProps,
+ MenuItem,
Typography,
TypographyProps,
-} from '@mui/material';
-import { CaptionedText } from '../CaptionedText';
-import PublicShareSwitch from '../Collections/CollectionShare/publicShare/switch';
-import {
- SpaceBetweenFlex,
- VerticallyCenteredFlex,
-} from '@ente/shared/components/Container';
-import React from 'react';
-import ChangeDirectoryOption from '../Directory/changeOption';
+} from "@mui/material";
+import React from "react";
+import { CaptionedText } from "../CaptionedText";
+import PublicShareSwitch from "../Collections/CollectionShare/publicShare/switch";
+import ChangeDirectoryOption from "../Directory/changeOption";
interface Iprops {
onClick: () => void;
- color?: ButtonProps['color'];
+ color?: ButtonProps["color"];
variant?:
- | 'primary'
- | 'captioned'
- | 'toggle'
- | 'secondary'
- | 'mini'
- | 'path';
- fontWeight?: TypographyProps['fontWeight'];
+ | "primary"
+ | "captioned"
+ | "toggle"
+ | "secondary"
+ | "mini"
+ | "path";
+ fontWeight?: TypographyProps["fontWeight"];
startIcon?: React.ReactNode;
endIcon?: React.ReactNode;
label?: string;
@@ -36,27 +36,27 @@ interface Iprops {
}
export function EnteMenuItem({
onClick,
- color = 'primary',
+ color = "primary",
startIcon,
endIcon,
label,
subText,
subIcon,
checked,
- variant = 'primary',
- fontWeight = 'bold',
+ variant = "primary",
+ fontWeight = "bold",
labelComponent,
disabled = false,
}: Iprops) {
const handleButtonClick = () => {
- if (variant === 'path' || variant === 'toggle') {
+ if (variant === "path" || variant === "toggle") {
return;
}
onClick();
};
const handleIconClick = () => {
- if (variant !== 'path' && variant !== 'toggle') {
+ if (variant !== "path" && variant !== "toggle") {
return;
}
onClick();
@@ -67,36 +67,37 @@ export function EnteMenuItem({
disabled={disabled}
onClick={handleButtonClick}
sx={{
- width: '100%',
+ width: "100%",
color: (theme) =>
- variant !== 'captioned' && theme.palette[color].main,
- ...(variant !== 'secondary' &&
- variant !== 'mini' && {
+ variant !== "captioned" && theme.palette[color].main,
+ ...(variant !== "secondary" &&
+ variant !== "mini" && {
backgroundColor: (theme) => theme.colors.fill.faint,
}),
- '&:hover': {
+ "&:hover": {
backgroundColor: (theme) => theme.colors.fill.faintPressed,
},
- '& .MuiSvgIcon-root': {
- fontSize: '20px',
+ "& .MuiSvgIcon-root": {
+ fontSize: "20px",
},
p: 0,
- borderRadius: '4px',
- }}>
- <SpaceBetweenFlex sx={{ pl: '16px', pr: '12px' }}>
- <VerticallyCenteredFlex sx={{ py: '14px' }} gap={'10px'}>
+ borderRadius: "4px",
+ }}
+ >
+ <SpaceBetweenFlex sx={{ pl: "16px", pr: "12px" }}>
+ <VerticallyCenteredFlex sx={{ py: "14px" }} gap={"10px"}>
{startIcon && startIcon}
- <Box px={'2px'}>
+ <Box px={"2px"}>
{labelComponent ? (
labelComponent
- ) : variant === 'captioned' ? (
+ ) : variant === "captioned" ? (
<CaptionedText
color={color}
mainText={label}
subText={subText}
subIcon={subIcon}
/>
- ) : variant === 'mini' ? (
+ ) : variant === "mini" ? (
<Typography variant="mini" color="text.muted">
{label}
</Typography>
@@ -107,15 +108,15 @@ export function EnteMenuItem({
)}
</Box>
</VerticallyCenteredFlex>
- <VerticallyCenteredFlex gap={'4px'}>
+ <VerticallyCenteredFlex gap={"4px"}>
{endIcon && endIcon}
- {variant === 'toggle' && (
+ {variant === "toggle" && (
<PublicShareSwitch
checked={checked}
onClick={handleIconClick}
/>
)}
- {variant === 'path' && (
+ {variant === "path" && (
<ChangeDirectoryOption
changeExportDirectory={handleIconClick}
/>
diff --git a/packages/shared/components/Menu/MenuItemDivider.tsx b/packages/shared/components/Menu/MenuItemDivider.tsx
index 37237dbd74..da3b309a2b 100644
--- a/packages/shared/components/Menu/MenuItemDivider.tsx
+++ b/packages/shared/components/Menu/MenuItemDivider.tsx
@@ -1,4 +1,4 @@
-import { Divider } from '@mui/material';
+import { Divider } from "@mui/material";
interface Iprops {
hasIcon?: boolean;
}
@@ -6,9 +6,9 @@ export default function MenuItemDivider({ hasIcon = false }: Iprops) {
return (
<Divider
sx={{
- '&&&': {
+ "&&&": {
my: 0,
- ml: hasIcon ? '48px' : '16px',
+ ml: hasIcon ? "48px" : "16px",
},
}}
/>
diff --git a/packages/shared/components/Menu/MenuItemGroup.tsx b/packages/shared/components/Menu/MenuItemGroup.tsx
index ad137c2d27..0b80262b5f 100644
--- a/packages/shared/components/Menu/MenuItemGroup.tsx
+++ b/packages/shared/components/Menu/MenuItemGroup.tsx
@@ -1,6 +1,6 @@
-import { styled } from '@mui/material';
+import { styled } from "@mui/material";
-export const MenuItemGroup = styled('div')(
+export const MenuItemGroup = styled("div")(
({ theme }) => `
& > .MuiMenuItem-root{
border-radius: 8px;
@@ -16,5 +16,5 @@ export const MenuItemGroup = styled('div')(
}
background-color: ${theme.colors.fill.faint};
border-radius: 8px;
-`
+`,
);
diff --git a/packages/shared/components/Menu/MenuSectionTitle.tsx b/packages/shared/components/Menu/MenuSectionTitle.tsx
index 76ead8d894..5c07b8d92b 100644
--- a/packages/shared/components/Menu/MenuSectionTitle.tsx
+++ b/packages/shared/components/Menu/MenuSectionTitle.tsx
@@ -1,5 +1,5 @@
-import { Typography } from '@mui/material';
-import { VerticallyCenteredFlex } from '@ente/shared/components/Container';
+import { VerticallyCenteredFlex } from "@ente/shared/components/Container";
+import { Typography } from "@mui/material";
interface Iprops {
title: string;
@@ -10,14 +10,15 @@ export default function MenuSectionTitle({ title, icon }: Iprops) {
return (
<VerticallyCenteredFlex
px="8px"
- py={'6px'}
- gap={'8px'}
+ py={"6px"}
+ gap={"8px"}
sx={{
- '& > svg': {
- fontSize: '17px',
+ "& > svg": {
+ fontSize: "17px",
color: (theme) => theme.colors.stroke.muted,
},
- }}>
+ }}
+ >
{icon && icon}
<Typography variant="small" color="text.muted">
{title}
diff --git a/packages/shared/components/MessageContainer.tsx b/packages/shared/components/MessageContainer.tsx
index 978aa507cb..8bb413e798 100644
--- a/packages/shared/components/MessageContainer.tsx
+++ b/packages/shared/components/MessageContainer.tsx
@@ -1,5 +1,5 @@
-import { styled } from '@mui/material';
-export const MessageContainer = styled('div')`
+import { styled } from "@mui/material";
+export const MessageContainer = styled("div")`
background-color: #111;
padding: 0;
font-size: 14px;
diff --git a/packages/shared/components/Navbar/EnteLinkLogo.tsx b/packages/shared/components/Navbar/EnteLinkLogo.tsx
index 557510337b..726b8d57d9 100644
--- a/packages/shared/components/Navbar/EnteLinkLogo.tsx
+++ b/packages/shared/components/Navbar/EnteLinkLogo.tsx
@@ -1,20 +1,21 @@
-import { Box } from '@mui/material';
-import Ente from '../../components/icons/ente';
-import Link from 'next/link';
-import { ENTE_WEBSITE_LINK } from '@ente/shared/constants/urls';
+import { ENTE_WEBSITE_LINK } from "@ente/shared/constants/urls";
+import { Box } from "@mui/material";
+import Link from "next/link";
+import Ente from "../../components/icons/ente";
export function EnteLinkLogo() {
return (
<Link href={ENTE_WEBSITE_LINK}>
<Box
sx={(theme) => ({
- ':hover': {
- cursor: 'pointer',
+ ":hover": {
+ cursor: "pointer",
svg: {
fill: theme.colors.text.faint,
},
},
- })}>
+ })}
+ >
<Ente />
</Box>
</Link>
diff --git a/packages/shared/components/Navbar/SelectionBar.tsx b/packages/shared/components/Navbar/SelectionBar.tsx
index 19d552aaf7..6473e1f601 100644
--- a/packages/shared/components/Navbar/SelectionBar.tsx
+++ b/packages/shared/components/Navbar/SelectionBar.tsx
@@ -1,5 +1,5 @@
-import NavbarBase from './base';
-import { styled } from '@mui/material';
+import { styled } from "@mui/material";
+import NavbarBase from "./base";
export const SelectionBar = styled(NavbarBase)`
position: fixed;
z-index: 12;
diff --git a/packages/shared/components/Navbar/SidebarToggler.tsx b/packages/shared/components/Navbar/SidebarToggler.tsx
index 475e18dd31..84355d5499 100644
--- a/packages/shared/components/Navbar/SidebarToggler.tsx
+++ b/packages/shared/components/Navbar/SidebarToggler.tsx
@@ -1,5 +1,5 @@
-import MenuIcon from '@mui/icons-material/Menu';
-import IconButton from '@mui/material/IconButton';
+import MenuIcon from "@mui/icons-material/Menu";
+import IconButton from "@mui/material/IconButton";
interface Iprops {
openSidebar: () => void;
diff --git a/packages/shared/components/Navbar/app.tsx b/packages/shared/components/Navbar/app.tsx
index 24cc8a8989..2169560f77 100644
--- a/packages/shared/components/Navbar/app.tsx
+++ b/packages/shared/components/Navbar/app.tsx
@@ -1,6 +1,6 @@
-import { EnteLogo } from '../EnteLogo';
-import { CenteredFlex } from '../../components/Container';
-import NavbarBase from './base';
+import { CenteredFlex } from "../../components/Container";
+import { EnteLogo } from "../EnteLogo";
+import NavbarBase from "./base";
export default function AppNavbar({ isMobile }) {
return (
diff --git a/packages/shared/components/Navbar/base.tsx b/packages/shared/components/Navbar/base.tsx
index 689e07a677..101506cfd0 100644
--- a/packages/shared/components/Navbar/base.tsx
+++ b/packages/shared/components/Navbar/base.tsx
@@ -1,5 +1,5 @@
-import { FlexWrapper } from '../../components/Container';
-import { styled } from '@mui/material';
+import { styled } from "@mui/material";
+import { FlexWrapper } from "../../components/Container";
const NavbarBase = styled(FlexWrapper)<{ isMobile: boolean }>`
min-height: 64px;
position: sticky;
diff --git a/packages/shared/components/OverflowMenu/context.tsx b/packages/shared/components/OverflowMenu/context.tsx
index 7bc4df9b5a..5d09cd5a07 100644
--- a/packages/shared/components/OverflowMenu/context.tsx
+++ b/packages/shared/components/OverflowMenu/context.tsx
@@ -1,4 +1,4 @@
-import { createContext } from 'react';
+import { createContext } from "react";
export const OverflowMenuContext = createContext({
close: () => null,
diff --git a/packages/shared/components/OverflowMenu/menu.tsx b/packages/shared/components/OverflowMenu/menu.tsx
index 0a847c99c9..ea0880eb1b 100644
--- a/packages/shared/components/OverflowMenu/menu.tsx
+++ b/packages/shared/components/OverflowMenu/menu.tsx
@@ -1,7 +1,7 @@
-import React, { useState } from 'react';
-import Menu from '@mui/material/Menu';
-import { IconButton, PaperProps, styled } from '@mui/material';
-import { OverflowMenuContext } from './context';
+import { IconButton, PaperProps, styled } from "@mui/material";
+import Menu from "@mui/material/Menu";
+import React, { useState } from "react";
+import { OverflowMenuContext } from "./context";
export interface Iprops {
triggerButtonIcon: React.ReactNode;
@@ -39,8 +39,9 @@ export default function OverflowMenu({
onClick={(event) => setSortByEl(event.currentTarget)}
aria-controls={sortByEl ? ariaControls : undefined}
aria-haspopup="true"
- aria-expanded={sortByEl ? 'true' : undefined}
- {...triggerButtonProps}>
+ aria-expanded={sortByEl ? "true" : undefined}
+ {...triggerButtonProps}
+ >
{triggerButtonIcon}
</IconButton>
<StyledMenu
@@ -50,17 +51,18 @@ export default function OverflowMenu({
onClose={handleClose}
MenuListProps={{
disablePadding: true,
- 'aria-labelledby': ariaControls,
+ "aria-labelledby": ariaControls,
}}
PaperProps={menuPaperProps}
anchorOrigin={{
- vertical: 'bottom',
- horizontal: 'right',
+ vertical: "bottom",
+ horizontal: "right",
}}
transformOrigin={{
- vertical: 'top',
- horizontal: 'right',
- }}>
+ vertical: "top",
+ horizontal: "right",
+ }}
+ >
{children}
</StyledMenu>
</OverflowMenuContext.Provider>
diff --git a/packages/shared/components/OverflowMenu/option.tsx b/packages/shared/components/OverflowMenu/option.tsx
index 0c126fe409..eafb59d139 100644
--- a/packages/shared/components/OverflowMenu/option.tsx
+++ b/packages/shared/components/OverflowMenu/option.tsx
@@ -1,11 +1,11 @@
-import { MenuItem, ButtonProps, Typography, Box } from '@mui/material';
-import { FluidContainer } from '@ente/shared/components/Container';
-import { OverflowMenuContext } from './context';
-import React, { useContext } from 'react';
+import { FluidContainer } from "@ente/shared/components/Container";
+import { Box, ButtonProps, MenuItem, Typography } from "@mui/material";
+import React, { useContext } from "react";
+import { OverflowMenuContext } from "./context";
interface Iprops {
onClick: () => void;
- color?: ButtonProps['color'];
+ color?: ButtonProps["color"];
startIcon?: React.ReactNode;
endIcon?: React.ReactNode;
keepOpenAfterClick?: boolean;
@@ -13,7 +13,7 @@ interface Iprops {
}
export function OverflowMenuOption({
onClick,
- color = 'primary',
+ color = "primary",
startIcon,
endIcon,
keepOpenAfterClick,
@@ -34,17 +34,19 @@ export function OverflowMenuOption({
minWidth: 220,
color: (theme) => theme.palette[color].main,
padding: 1.5,
- '& .MuiSvgIcon-root': {
- fontSize: '20px',
+ "& .MuiSvgIcon-root": {
+ fontSize: "20px",
},
- }}>
+ }}
+ >
<FluidContainer>
{startIcon && (
<Box
sx={{
padding: 0,
marginRight: 1.5,
- }}>
+ }}
+ >
{startIcon}
</Box>
)}
@@ -55,7 +57,8 @@ export function OverflowMenuOption({
sx={{
padding: 0,
marginLeft: 1,
- }}>
+ }}
+ >
{endIcon}
</Box>
)}
diff --git a/packages/shared/components/RecoveryKey/index.tsx b/packages/shared/components/RecoveryKey/index.tsx
index ab8073d047..be34a95f40 100644
--- a/packages/shared/components/RecoveryKey/index.tsx
+++ b/packages/shared/components/RecoveryKey/index.tsx
@@ -1,27 +1,27 @@
-import React, { useEffect, useState } from 'react';
-import { downloadAsFile } from '@ente/shared/utils';
-import { getRecoveryKey } from '@ente/shared/crypto/helpers';
-import CodeBlock from '@ente/shared/components/CodeBlock';
+import { PageProps } from "@ente/shared/apps/types";
+import CodeBlock from "@ente/shared/components/CodeBlock";
+import DialogTitleWithCloseButton from "@ente/shared/components/DialogBox/TitleWithCloseButton";
+import { getRecoveryKey } from "@ente/shared/crypto/helpers";
+import { downloadAsFile } from "@ente/shared/utils";
import {
Button,
Dialog,
DialogActions,
DialogContent,
Typography,
-} from '@mui/material';
-import * as bip39 from 'bip39';
-import { DashedBorderWrapper } from './styledComponents';
-import DialogTitleWithCloseButton from '@ente/shared/components/DialogBox/TitleWithCloseButton';
-import { t } from 'i18next';
-import { PageProps } from '@ente/shared/apps/types';
+} from "@mui/material";
+import * as bip39 from "bip39";
+import { t } from "i18next";
+import { useEffect, useState } from "react";
+import { DashedBorderWrapper } from "./styledComponents";
// mobile client library only supports english.
-bip39.setDefaultWordlist('english');
+bip39.setDefaultWordlist("english");
-const RECOVERY_KEY_FILE_NAME = 'ente-recovery-key.txt';
+const RECOVERY_KEY_FILE_NAME = "ente-recovery-key.txt";
interface Props {
- appContext: PageProps['appContext'];
+ appContext: PageProps["appContext"];
show: boolean;
onHide: () => void;
somethingWentWrong: any;
@@ -56,25 +56,26 @@ function RecoveryKey({ somethingWentWrong, appContext, ...props }: Props) {
fullScreen={appContext.isMobile}
open={props.show}
onClose={props.onHide}
- maxWidth="xs">
+ maxWidth="xs"
+ >
<DialogTitleWithCloseButton onClose={props.onHide}>
- {t('RECOVERY_KEY')}
+ {t("RECOVERY_KEY")}
</DialogTitleWithCloseButton>
<DialogContent>
- <Typography mb={3}>{t('RECOVERY_KEY_DESCRIPTION')}</Typography>
+ <Typography mb={3}>{t("RECOVERY_KEY_DESCRIPTION")}</Typography>
<DashedBorderWrapper>
<CodeBlock code={recoveryKey} />
<Typography m={2}>
- {t('KEY_NOT_STORED_DISCLAIMER')}
+ {t("KEY_NOT_STORED_DISCLAIMER")}
</Typography>
</DashedBorderWrapper>
</DialogContent>
<DialogActions>
<Button color="secondary" size="large" onClick={props.onHide}>
- {t('SAVE_LATER')}
+ {t("SAVE_LATER")}
</Button>
<Button color="accent" size="large" onClick={onSaveClick}>
- {t('SAVE')}
+ {t("SAVE")}
</Button>
</DialogActions>
</Dialog>
diff --git a/packages/shared/components/RecoveryKey/styledComponents.tsx b/packages/shared/components/RecoveryKey/styledComponents.tsx
index 291965eddc..944001ebeb 100644
--- a/packages/shared/components/RecoveryKey/styledComponents.tsx
+++ b/packages/shared/components/RecoveryKey/styledComponents.tsx
@@ -1,4 +1,4 @@
-import { Box, styled } from '@mui/material';
+import { Box, styled } from "@mui/material";
export const DashedBorderWrapper = styled(Box)(({ theme }) => ({
border: `1px dashed ${theme.palette.grey.A400}`,
diff --git a/packages/shared/components/SingleInputForm.tsx b/packages/shared/components/SingleInputForm.tsx
index 88a2b2dc33..3422eebdbe 100644
--- a/packages/shared/components/SingleInputForm.tsx
+++ b/packages/shared/components/SingleInputForm.tsx
@@ -1,12 +1,12 @@
-import React, { useMemo, useState } from 'react';
-import { Formik, FormikHelpers, FormikState } from 'formik';
-import * as Yup from 'yup';
-import SubmitButton from './SubmitButton';
-import TextField from '@mui/material/TextField';
-import ShowHidePassword from '@ente/shared/components/Form/ShowHidePassword';
-import { FlexWrapper } from '@ente/shared/components/Container';
-import { Button, FormHelperText } from '@mui/material';
-import { t } from 'i18next';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import ShowHidePassword from "@ente/shared/components/Form/ShowHidePassword";
+import { Button, FormHelperText } from "@mui/material";
+import TextField from "@mui/material/TextField";
+import { Formik, FormikHelpers, FormikState } from "formik";
+import { t } from "i18next";
+import React, { useMemo, useState } from "react";
+import * as Yup from "yup";
+import SubmitButton from "./SubmitButton";
interface formValues {
inputValue: string;
@@ -15,9 +15,9 @@ export interface SingleInputFormProps {
callback: (
inputValue: string,
setFieldError: (errorMessage: string) => void,
- resetForm: (nextState?: Partial<FormikState<formValues>>) => void
+ resetForm: (nextState?: Partial<FormikState<formValues>>) => void,
) => Promise<void>;
- fieldType: 'text' | 'email' | 'password';
+ fieldType: "text" | "email" | "password";
placeholder: string;
buttonText: string;
submitButtonProps?: any;
@@ -42,13 +42,13 @@ export default function SingleInputForm(props: SingleInputFormProps) {
const submitForm = async (
values: formValues,
- { setFieldError, resetForm }: FormikHelpers<formValues>
+ { setFieldError, resetForm }: FormikHelpers<formValues>,
) => {
SetLoading(true);
await props.callback(
values.inputValue,
- (message) => setFieldError('inputValue', message),
- resetForm
+ (message) => setFieldError("inputValue", message),
+ resetForm,
);
SetLoading(false);
};
@@ -58,37 +58,38 @@ export default function SingleInputForm(props: SingleInputFormProps) {
};
const handleMouseDownPassword = (
- event: React.MouseEvent<HTMLButtonElement>
+ event: React.MouseEvent<HTMLButtonElement>,
) => {
event.preventDefault();
};
const validationSchema = useMemo(() => {
switch (props.fieldType) {
- case 'text':
+ case "text":
return Yup.object().shape({
- inputValue: Yup.string().required(t('REQUIRED')),
+ inputValue: Yup.string().required(t("REQUIRED")),
});
- case 'password':
+ case "password":
return Yup.object().shape({
- inputValue: Yup.string().required(t('REQUIRED')),
+ inputValue: Yup.string().required(t("REQUIRED")),
});
- case 'email':
+ case "email":
return Yup.object().shape({
inputValue: Yup.string()
- .email(t('EMAIL_ERROR'))
- .required(t('REQUIRED')),
+ .email(t("EMAIL_ERROR"))
+ .required(t("REQUIRED")),
});
}
}, [props.fieldType]);
return (
<Formik<formValues>
- initialValues={{ inputValue: props.initialValue ?? '' }}
+ initialValues={{ inputValue: props.initialValue ?? "" }}
onSubmit={submitForm}
validationSchema={validationSchema}
validateOnChange={false}
- validateOnBlur={false}>
+ validateOnBlur={false}
+ >
{({ values, errors, handleChange, handleSubmit }) => (
<form noValidate onSubmit={handleSubmit}>
{props.hiddenPreInput}
@@ -96,14 +97,14 @@ export default function SingleInputForm(props: SingleInputFormProps) {
hiddenLabel={props.hiddenLabel}
variant="filled"
fullWidth
- type={showPassword ? 'text' : props.fieldType}
+ type={showPassword ? "text" : props.fieldType}
id={props.fieldType}
name={props.fieldType}
{...(props.hiddenLabel
? { placeholder: props.placeholder }
: { label: props.placeholder })}
value={values.inputValue}
- onChange={handleChange('inputValue')}
+ onChange={handleChange("inputValue")}
error={Boolean(errors.inputValue)}
helperText={errors.inputValue}
disabled={loading}
@@ -112,10 +113,10 @@ export default function SingleInputForm(props: SingleInputFormProps) {
InputProps={{
autoComplete:
props.disableAutoComplete ||
- props.fieldType === 'password'
- ? 'off'
- : 'on',
- endAdornment: props.fieldType === 'password' && (
+ props.fieldType === "password"
+ ? "off"
+ : "on",
+ endAdornment: props.fieldType === "password" && (
<ShowHidePassword
showPassword={showPassword}
handleClickShowPassword={
@@ -130,39 +131,40 @@ export default function SingleInputForm(props: SingleInputFormProps) {
/>
<FormHelperText
sx={{
- position: 'relative',
- top: errors.inputValue ? '-22px' : '0',
- float: 'right',
- padding: '0 8px',
- }}>
+ position: "relative",
+ top: errors.inputValue ? "-22px" : "0",
+ float: "right",
+ padding: "0 8px",
+ }}
+ >
{props.caption}
</FormHelperText>
{props.hiddenPostInput}
<FlexWrapper
- justifyContent={'flex-end'}
- flexWrap={
- props.blockButton ? 'wrap-reverse' : 'nowrap'
- }>
+ justifyContent={"flex-end"}
+ flexWrap={props.blockButton ? "wrap-reverse" : "nowrap"}
+ >
{props.secondaryButtonAction && (
<Button
onClick={props.secondaryButtonAction}
size="large"
color="secondary"
sx={{
- '&&&': {
+ "&&&": {
mt: !props.blockButton ? 2 : 0.5,
mb: !props.blockButton ? 4 : 0,
mr: !props.blockButton ? 1 : 0,
...buttonSx,
},
}}
- {...restSubmitButtonProps}>
- {t('CANCEL')}
+ {...restSubmitButtonProps}
+ >
+ {t("CANCEL")}
</Button>
)}
<SubmitButton
sx={{
- '&&&': {
+ "&&&": {
mt: 2,
...buttonSx,
},
diff --git a/packages/shared/components/SubmitButton.tsx b/packages/shared/components/SubmitButton.tsx
index 52a51c936a..8d87645bc7 100644
--- a/packages/shared/components/SubmitButton.tsx
+++ b/packages/shared/components/SubmitButton.tsx
@@ -1,6 +1,6 @@
-import Done from '@mui/icons-material/Done';
-import { Button, ButtonProps, CircularProgress } from '@mui/material';
-import { FC } from 'react';
+import Done from "@mui/icons-material/Done";
+import { Button, ButtonProps, CircularProgress } from "@mui/material";
+import { FC } from "react";
export interface SubmitButtonProps {
loading: boolean;
@@ -9,7 +9,7 @@ export interface SubmitButtonProps {
disabled?: boolean;
success?: boolean;
}
-const SubmitButton: FC<ButtonProps<'button', SubmitButtonProps>> = ({
+const SubmitButton: FC<ButtonProps<"button", SubmitButtonProps>> = ({
loading,
buttonText,
disabled,
@@ -28,7 +28,7 @@ const SubmitButton: FC<ButtonProps<'button', SubmitButtonProps>> = ({
my: 4,
...(loading
? {
- '&.Mui-disabled': {
+ "&.Mui-disabled": {
backgroundColor: (theme) =>
theme.colors.accent.A500,
color: (theme) => theme.colors.text.base,
@@ -37,7 +37,8 @@ const SubmitButton: FC<ButtonProps<'button', SubmitButtonProps>> = ({
: {}),
...sx,
}}
- {...props}>
+ {...props}
+ >
{loading ? (
<CircularProgress size={20} />
) : success ? (
diff --git a/packages/shared/components/ThemeSwitcher.tsx b/packages/shared/components/ThemeSwitcher.tsx
index 1d091c6910..121d2e2330 100644
--- a/packages/shared/components/ThemeSwitcher.tsx
+++ b/packages/shared/components/ThemeSwitcher.tsx
@@ -1,8 +1,7 @@
-import { ToggleButton, ToggleButtonGroup } from '@mui/material';
-import React from 'react';
-import DarkModeIcon from '@mui/icons-material/DarkMode';
-import LightModeIcon from '@mui/icons-material/LightMode';
-import { THEME_COLOR } from '@ente/shared/themes/constants';
+import { THEME_COLOR } from "@ente/shared/themes/constants";
+import DarkModeIcon from "@mui/icons-material/DarkMode";
+import LightModeIcon from "@mui/icons-material/LightMode";
+import { ToggleButton, ToggleButtonGroup } from "@mui/material";
interface Iprops {
themeColor: THEME_COLOR;
setThemeColor: (theme: THEME_COLOR) => void;
@@ -19,7 +18,8 @@ export default function ThemeSwitcher({ themeColor, setThemeColor }: Iprops) {
size="small"
value={themeColor}
exclusive
- onChange={handleChange}>
+ onChange={handleChange}
+ >
<ToggleButton value={THEME_COLOR.LIGHT}>
<LightModeIcon />
</ToggleButton>
diff --git a/packages/shared/components/Titlebar.tsx b/packages/shared/components/Titlebar.tsx
index 16d4c8f50e..ed9089f4c2 100644
--- a/packages/shared/components/Titlebar.tsx
+++ b/packages/shared/components/Titlebar.tsx
@@ -1,7 +1,7 @@
-import Close from '@mui/icons-material/Close';
-import ArrowBack from '@mui/icons-material/ArrowBack';
-import { Box, IconButton, Typography } from '@mui/material';
-import { FlexWrapper } from '@ente/shared/components/Container';
+import { FlexWrapper } from "@ente/shared/components/Container";
+import ArrowBack from "@mui/icons-material/ArrowBack";
+import Close from "@mui/icons-material/Close";
+import { Box, IconButton, Typography } from "@mui/material";
interface Iprops {
title: string;
@@ -24,30 +24,33 @@ export default function Titlebar({
<>
<FlexWrapper
height={48}
- alignItems={'center'}
- justifyContent="space-between">
+ alignItems={"center"}
+ justifyContent="space-between"
+ >
<IconButton
onClick={onClose}
- color={backIsClose ? 'secondary' : 'primary'}>
+ color={backIsClose ? "secondary" : "primary"}
+ >
{backIsClose ? <Close /> : <ArrowBack />}
</IconButton>
- <Box display={'flex'} gap="4px">
+ <Box display={"flex"} gap="4px">
{actionButton && actionButton}
{!backIsClose && (
- <IconButton onClick={onRootClose} color={'secondary'}>
+ <IconButton onClick={onRootClose} color={"secondary"}>
<Close />
</IconButton>
)}
</Box>
</FlexWrapper>
<Box py={0.5} px={2}>
- <Typography variant="h3" fontWeight={'bold'}>
+ <Typography variant="h3" fontWeight={"bold"}>
{title}
</Typography>
<Typography
variant="small"
color="text.muted"
- sx={{ wordBreak: 'break-all', minHeight: '17px' }}>
+ sx={{ wordBreak: "break-all", minHeight: "17px" }}
+ >
{caption}
</Typography>
</Box>
diff --git a/packages/shared/components/VerifyMasterPasswordForm.tsx b/packages/shared/components/VerifyMasterPasswordForm.tsx
index d23727db43..5865d949fd 100644
--- a/packages/shared/components/VerifyMasterPasswordForm.tsx
+++ b/packages/shared/components/VerifyMasterPasswordForm.tsx
@@ -1,15 +1,15 @@
+import { logError } from "@ente/shared/sentry";
import SingleInputForm, {
SingleInputFormProps,
-} from '../components/SingleInputForm';
-import { logError } from '@ente/shared/sentry';
+} from "../components/SingleInputForm";
-import { CustomError } from '../error';
+import { CustomError } from "../error";
-import { ButtonProps, Input } from '@mui/material';
-import { KeyAttributes, User } from '../user/types';
-import { SRPAttributes } from '@ente/accounts/types/srp';
-import ComlinkCryptoWorker from '../crypto';
-import { t } from 'i18next';
+import { SRPAttributes } from "@ente/accounts/types/srp";
+import { ButtonProps, Input } from "@mui/material";
+import { t } from "i18next";
+import ComlinkCryptoWorker from "../crypto";
+import { KeyAttributes, User } from "../user/types";
export interface VerifyMasterPasswordFormProps {
user: User;
@@ -18,7 +18,7 @@ export interface VerifyMasterPasswordFormProps {
key: string,
kek: string,
keyAttributes: KeyAttributes,
- passphrase?: string
+ passphrase?: string,
) => void;
buttonText: string;
submitButtonProps?: ButtonProps;
@@ -35,9 +35,9 @@ export default function VerifyMasterPasswordForm({
submitButtonProps,
getKeyAttributes,
}: VerifyMasterPasswordFormProps) {
- const verifyPassphrase: SingleInputFormProps['callback'] = async (
+ const verifyPassphrase: SingleInputFormProps["callback"] = async (
passphrase,
- setFieldError
+ setFieldError,
) => {
try {
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
@@ -48,21 +48,21 @@ export default function VerifyMasterPasswordForm({
passphrase,
srpAttributes.kekSalt,
srpAttributes.opsLimit,
- srpAttributes.memLimit
+ srpAttributes.memLimit,
);
} else {
kek = await cryptoWorker.deriveKey(
passphrase,
keyAttributes.kekSalt,
keyAttributes.opsLimit,
- keyAttributes.memLimit
+ keyAttributes.memLimit,
);
}
} catch (e) {
- logError(e, 'failed to derive key');
+ logError(e, "failed to derive key");
throw Error(CustomError.WEAK_DEVICE);
}
- if (!keyAttributes && typeof getKeyAttributes === 'function') {
+ if (!keyAttributes && typeof getKeyAttributes === "function") {
keyAttributes = await getKeyAttributes(kek);
}
if (!keyAttributes) {
@@ -72,11 +72,11 @@ export default function VerifyMasterPasswordForm({
const key = await cryptoWorker.decryptB64(
keyAttributes.encryptedKey,
keyAttributes.keyDecryptionNonce,
- kek
+ kek,
);
callback(key, kek, keyAttributes, passphrase);
} catch (e) {
- logError(e, 'user entered a wrong password');
+ logError(e, "user entered a wrong password");
throw Error(CustomError.INCORRECT_PASSWORD);
}
} catch (e) {
@@ -85,16 +85,16 @@ export default function VerifyMasterPasswordForm({
// two factor enabled, user has been redirected to two factor page
return;
}
- logError(e, 'failed to verify passphrase');
+ logError(e, "failed to verify passphrase");
switch (e.message) {
case CustomError.WEAK_DEVICE:
- setFieldError(t('WEAK_DEVICE'));
+ setFieldError(t("WEAK_DEVICE"));
break;
case CustomError.INCORRECT_PASSWORD:
- setFieldError(t('INCORRECT_PASSPHRASE'));
+ setFieldError(t("INCORRECT_PASSPHRASE"));
break;
default:
- setFieldError(`${t('UNKNOWN_ERROR')} ${e.message}`);
+ setFieldError(`${t("UNKNOWN_ERROR")} ${e.message}`);
}
}
}
@@ -103,12 +103,12 @@ export default function VerifyMasterPasswordForm({
return (
<SingleInputForm
callback={verifyPassphrase}
- placeholder={t('RETURN_PASSPHRASE_HINT')}
+ placeholder={t("RETURN_PASSPHRASE_HINT")}
buttonText={buttonText}
submitButtonProps={submitButtonProps}
hiddenPreInput={
<Input
- sx={{ display: 'none' }}
+ sx={{ display: "none" }}
id="email"
name="email"
autoComplete="username"
@@ -116,7 +116,7 @@ export default function VerifyMasterPasswordForm({
value={user?.email}
/>
}
- autoComplete={'current-password'}
+ autoComplete={"current-password"}
fieldType="password"
/>
);
diff --git a/packages/shared/components/icons/ente.tsx b/packages/shared/components/icons/ente.tsx
index 9a8e0afbf5..f2feedbb49 100644
--- a/packages/shared/components/icons/ente.tsx
+++ b/packages/shared/components/icons/ente.tsx
@@ -1,5 +1,3 @@
-import React from 'react';
-
export default function Ente() {
return (
<svg
@@ -7,7 +5,8 @@ export default function Ente() {
height="26"
viewBox="0 0 43 13"
fill="#fff"
- xmlns="http://www.w3.org/2000/svg">
+ xmlns="http://www.w3.org/2000/svg"
+ >
<path d="M6.102 12.144C4.998 12.144 4.026 11.928 3.186 11.496C2.358 11.064 1.716 10.476 1.26 9.732C0.804 8.976 0.576 8.118 0.576 7.158C0.576 6.186 0.798 5.328 1.242 4.584C1.698 3.828 2.316 3.24 3.096 2.82C3.876 2.388 4.758 2.172 5.742 2.172C6.69 2.172 7.542 2.376 8.298 2.784C9.066 3.18 9.672 3.756 10.116 4.512C10.56 5.256 10.782 6.15 10.782 7.194C10.782 7.302 10.776 7.428 10.764 7.572C10.752 7.704 10.74 7.83 10.728 7.95H2.862V6.312H9.252L8.172 6.798C8.172 6.294 8.07 5.856 7.866 5.484C7.662 5.112 7.38 4.824 7.02 4.62C6.66 4.404 6.24 4.296 5.76 4.296C5.28 4.296 4.854 4.404 4.482 4.62C4.122 4.824 3.84 5.118 3.636 5.502C3.432 5.874 3.33 6.318 3.33 6.834V7.266C3.33 7.794 3.444 8.262 3.672 8.67C3.912 9.066 4.242 9.372 4.662 9.588C5.094 9.792 5.598 9.894 6.174 9.894C6.69 9.894 7.14 9.816 7.524 9.66C7.92 9.504 8.28 9.27 8.604 8.958L10.098 10.578C9.654 11.082 9.096 11.472 8.424 11.748C7.752 12.012 6.978 12.144 6.102 12.144ZM18.5375 2.172C19.3055 2.172 19.9895 2.328 20.5895 2.64C21.2015 2.94 21.6815 3.408 22.0295 4.044C22.3775 4.668 22.5515 5.472 22.5515 6.456V12H19.7435V6.888C19.7435 6.108 19.5695 5.532 19.2215 5.16C18.8855 4.788 18.4055 4.602 17.7815 4.602C17.3375 4.602 16.9355 4.698 16.5755 4.89C16.2275 5.07 15.9515 5.352 15.7475 5.736C15.5555 6.12 15.4595 6.612 15.4595 7.212V12H12.6515V2.316H15.3335V4.998L14.8295 4.188C15.1775 3.54 15.6755 3.042 16.3235 2.694C16.9715 2.346 17.7095 2.172 18.5375 2.172ZM29.0568 12.144C27.9168 12.144 27.0288 11.856 26.3928 11.28C25.7568 10.692 25.4388 9.822 25.4388 8.67V0.174H28.2468V8.634C28.2468 9.042 28.3548 9.36 28.5708 9.588C28.7868 9.804 29.0808 9.912 29.4528 9.912C29.8968 9.912 30.2748 9.792 30.5868 9.552L31.3428 11.532C31.0548 11.736 30.7068 11.892 30.2988 12C29.9028 12.096 29.4888 12.144 29.0568 12.144ZM23.9448 4.692V2.532H30.6588V4.692H23.9448ZM37.4262 12.144C36.3222 12.144 35.3502 11.928 34.5102 11.496C33.6822 11.064 33.0402 10.476 32.5842 9.732C32.1282 8.976 31.9002 8.118 31.9002 7.158C31.9002 6.186 32.1222 5.328 32.5662 4.584C33.0222 3.828 33.6402 3.24 34.4202 2.82C35.2002 2.388 36.0822 2.172 37.0662 2.172C38.0142 2.172 38.8662 2.376 39.6222 2.784C40.3902 3.18 40.9962 3.756 41.4402 4.512C41.8842 5.256 42.1062 6.15 42.1062 7.194C42.1062 7.302 42.1002 7.428 42.0882 7.572C42.0762 7.704 42.0642 7.83 42.0522 7.95H34.1862V6.312H40.5762L39.4962 6.798C39.4962 6.294 39.3942 5.856 39.1902 5.484C38.9862 5.112 38.7042 4.824 38.3442 4.62C37.9842 4.404 37.5642 4.296 37.0842 4.296C36.6042 4.296 36.1782 4.404 35.8062 4.62C35.4462 4.824 35.1642 5.118 34.9602 5.502C34.7562 5.874 34.6542 6.318 34.6542 6.834V7.266C34.6542 7.794 34.7682 8.262 34.9962 8.67C35.2362 9.066 35.5662 9.372 35.9862 9.588C36.4182 9.792 36.9222 9.894 37.4982 9.894C38.0142 9.894 38.4642 9.816 38.8482 9.66C39.2442 9.504 39.6042 9.27 39.9282 8.958L41.4222 10.578C40.9782 11.082 40.4202 11.472 39.7482 11.748C39.0762 12.012 38.3022 12.144 37.4262 12.144Z" />
</svg>
);
diff --git a/packages/shared/components/styledComponents/SmallLoadingSpinner.tsx b/packages/shared/components/styledComponents/SmallLoadingSpinner.tsx
index a73b7c0c8b..2314d3974e 100644
--- a/packages/shared/components/styledComponents/SmallLoadingSpinner.tsx
+++ b/packages/shared/components/styledComponents/SmallLoadingSpinner.tsx
@@ -1,11 +1,10 @@
-import React from 'react';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
export const SmallLoadingSpinner = () => (
<EnteSpinner
style={{
- width: '20px',
- height: '20px',
+ width: "20px",
+ height: "20px",
}}
/>
);
diff --git a/packages/shared/constants/pages.tsx b/packages/shared/constants/pages.tsx
index cc6e4ed925..c2e01d794c 100644
--- a/packages/shared/constants/pages.tsx
+++ b/packages/shared/constants/pages.tsx
@@ -1,50 +1,50 @@
export enum PHOTOS_PAGES {
- CHANGE_EMAIL = '/change-email',
- CHANGE_PASSWORD = '/change-password',
- CREDENTIALS = '/credentials',
- GALLERY = '/gallery',
- GENERATE = '/generate',
- LOGIN = '/login',
- RECOVER = '/recover',
- SIGNUP = '/signup',
- TWO_FACTOR_SETUP = '/two-factor/setup',
- TWO_FACTOR_VERIFY = '/two-factor/verify',
- TWO_FACTOR_RECOVER = '/two-factor/recover',
- VERIFY = '/verify',
- ROOT = '/',
- SHARED_ALBUMS = '/shared-albums',
+ CHANGE_EMAIL = "/change-email",
+ CHANGE_PASSWORD = "/change-password",
+ CREDENTIALS = "/credentials",
+ GALLERY = "/gallery",
+ GENERATE = "/generate",
+ LOGIN = "/login",
+ RECOVER = "/recover",
+ SIGNUP = "/signup",
+ TWO_FACTOR_SETUP = "/two-factor/setup",
+ TWO_FACTOR_VERIFY = "/two-factor/verify",
+ TWO_FACTOR_RECOVER = "/two-factor/recover",
+ VERIFY = "/verify",
+ ROOT = "/",
+ SHARED_ALBUMS = "/shared-albums",
// ML_DEBUG = '/ml-debug',
- DEDUPLICATE = '/deduplicate',
+ DEDUPLICATE = "/deduplicate",
}
export enum AUTH_PAGES {
- CHANGE_EMAIL = '/change-email',
- CHANGE_PASSWORD = '/change-password',
- CREDENTIALS = '/credentials',
- GALLERY = '/gallery',
- GENERATE = '/generate',
- LOGIN = '/login',
- RECOVER = '/recover',
- SIGNUP = '/signup',
- TWO_FACTOR_SETUP = '/two-factor/setup',
- TWO_FACTOR_VERIFY = '/two-factor/verify',
- TWO_FACTOR_RECOVER = '/two-factor/recover',
- VERIFY = '/verify',
- ROOT = '/',
- AUTH = '/auth',
+ CHANGE_EMAIL = "/change-email",
+ CHANGE_PASSWORD = "/change-password",
+ CREDENTIALS = "/credentials",
+ GALLERY = "/gallery",
+ GENERATE = "/generate",
+ LOGIN = "/login",
+ RECOVER = "/recover",
+ SIGNUP = "/signup",
+ TWO_FACTOR_SETUP = "/two-factor/setup",
+ TWO_FACTOR_VERIFY = "/two-factor/verify",
+ TWO_FACTOR_RECOVER = "/two-factor/recover",
+ VERIFY = "/verify",
+ ROOT = "/",
+ AUTH = "/auth",
}
export enum ACCOUNTS_PAGES {
- CREDENTIALS = '/credentials',
- LOGIN = '/login',
- RECOVER = '/recover',
- SIGNUP = '/signup',
- TWO_FACTOR_SETUP = '/two-factor/setup',
- TWO_FACTOR_VERIFY = '/two-factor/verify',
- TWO_FACTOR_RECOVER = '/two-factor/recover',
- VERIFY = '/verify',
- ROOT = '/',
- PASSKEYS = '/passkeys',
- ACCOUNT_HANDOFF = '/account-handoff',
- GENERATE = '/generate',
+ CREDENTIALS = "/credentials",
+ LOGIN = "/login",
+ RECOVER = "/recover",
+ SIGNUP = "/signup",
+ TWO_FACTOR_SETUP = "/two-factor/setup",
+ TWO_FACTOR_VERIFY = "/two-factor/verify",
+ TWO_FACTOR_RECOVER = "/two-factor/recover",
+ VERIFY = "/verify",
+ ROOT = "/",
+ PASSKEYS = "/passkeys",
+ ACCOUNT_HANDOFF = "/account-handoff",
+ GENERATE = "/generate",
}
diff --git a/packages/shared/constants/urls.ts b/packages/shared/constants/urls.ts
index 122785cf59..7c771836d3 100644
--- a/packages/shared/constants/urls.ts
+++ b/packages/shared/constants/urls.ts
@@ -1,21 +1,21 @@
-export const ENTE_WEBSITE_LINK = 'https://ente.io';
+export const ENTE_WEBSITE_LINK = "https://ente.io";
-export const ML_BLOG_LINK = 'https://ente.io/blog/desktop-ml-beta';
+export const ML_BLOG_LINK = "https://ente.io/blog/desktop-ml-beta";
export const FACE_SEARCH_PRIVACY_POLICY_LINK =
- 'https://ente.io/privacy#8-biometric-information-privacy-policy';
+ "https://ente.io/privacy#8-biometric-information-privacy-policy";
-export const SUPPORT_EMAIL = '[email protected]';
+export const SUPPORT_EMAIL = "[email protected]";
-export const APP_DOWNLOAD_URL = 'https://ente.io/download/desktop';
+export const APP_DOWNLOAD_URL = "https://ente.io/download/desktop";
-export const FEEDBACK_EMAIL = '[email protected]';
+export const FEEDBACK_EMAIL = "[email protected]";
-export const DELETE_ACCOUNT_EMAIL = '[email protected]';
+export const DELETE_ACCOUNT_EMAIL = "[email protected]";
-export const WEB_ROADMAP_URL = 'https://github.com/ente-io/photos-web/issues';
+export const WEB_ROADMAP_URL = "https://github.com/ente-io/photos-web/issues";
export const DESKTOP_ROADMAP_URL =
- 'https://github.com/ente-io/photos-desktop/issues';
+ "https://github.com/ente-io/photos-desktop/issues";
-export const CITIES_URL = 'https://static.ente.io/world_cities.json';
+export const CITIES_URL = "https://static.ente.io/world_cities.json";
diff --git a/packages/shared/crypto/helpers.ts b/packages/shared/crypto/helpers.ts
index 20c67f321b..a29dc465f5 100644
--- a/packages/shared/crypto/helpers.ts
+++ b/packages/shared/crypto/helpers.ts
@@ -1,23 +1,23 @@
-import ComlinkCryptoWorker from '.';
-import { LS_KEYS, getData, setData } from '@ente/shared/storage/localStorage';
-import { getToken } from '@ente/shared/storage/localStorage/helpers';
-import { SESSION_KEYS, setKey } from '@ente/shared/storage/sessionStorage';
-import { getActualKey } from '@ente/shared/user';
-import { KeyAttributes } from '@ente/shared/user/types';
-import { setRecoveryKey } from '@ente/accounts/api/user';
-import { logError } from '@ente/shared/sentry';
-import isElectron from 'is-electron';
-import ElectronAPIs from '../electron';
-import { addLogLine } from '../logging';
+import { setRecoveryKey } from "@ente/accounts/api/user";
+import { logError } from "@ente/shared/sentry";
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
+import { getToken } from "@ente/shared/storage/localStorage/helpers";
+import { SESSION_KEYS, setKey } from "@ente/shared/storage/sessionStorage";
+import { getActualKey } from "@ente/shared/user";
+import { KeyAttributes } from "@ente/shared/user/types";
+import isElectron from "is-electron";
+import ComlinkCryptoWorker from ".";
+import ElectronAPIs from "../electron";
+import { addLogLine } from "../logging";
const LOGIN_SUB_KEY_LENGTH = 32;
const LOGIN_SUB_KEY_ID = 1;
-const LOGIN_SUB_KEY_CONTEXT = 'loginctx';
+const LOGIN_SUB_KEY_CONTEXT = "loginctx";
const LOGIN_SUB_KEY_BYTE_LENGTH = 16;
export async function decryptAndStoreToken(
keyAttributes: KeyAttributes,
- masterKey: string
+ masterKey: string,
) {
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
const user = getData(LS_KEYS.USER);
@@ -27,15 +27,15 @@ export async function decryptAndStoreToken(
const secretKey = await cryptoWorker.decryptB64(
keyAttributes.encryptedSecretKey,
keyAttributes.secretKeyDecryptionNonce,
- masterKey
+ masterKey,
);
const urlUnsafeB64DecryptedToken = await cryptoWorker.boxSealOpen(
encryptedToken,
keyAttributes.publicKey,
- secretKey
+ secretKey,
);
const decryptedTokenBytes = await cryptoWorker.fromB64(
- urlUnsafeB64DecryptedToken
+ urlUnsafeB64DecryptedToken,
);
decryptedToken = await cryptoWorker.toURLSafeB64(decryptedTokenBytes);
setData(LS_KEYS.USER, {
@@ -53,17 +53,17 @@ export async function decryptAndStoreToken(
export async function generateAndSaveIntermediateKeyAttributes(
passphrase: string,
existingKeyAttributes: KeyAttributes,
- key: string
+ key: string,
): Promise<KeyAttributes> {
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
const intermediateKekSalt = await cryptoWorker.generateSaltToDeriveKey();
const intermediateKek = await cryptoWorker.deriveInteractiveKey(
passphrase,
- intermediateKekSalt
+ intermediateKekSalt,
);
const encryptedKeyAttributes = await cryptoWorker.encryptToB64(
key,
- intermediateKek.key
+ intermediateKek.key,
);
const intermediateKeyAttributes = Object.assign(existingKeyAttributes, {
@@ -83,13 +83,13 @@ export const generateLoginSubKey = async (kek: string) => {
kek,
LOGIN_SUB_KEY_LENGTH,
LOGIN_SUB_KEY_ID,
- LOGIN_SUB_KEY_CONTEXT
+ LOGIN_SUB_KEY_CONTEXT,
);
const kekSubKey = await cryptoWorker.fromB64(kekSubKeyString);
// use first 16 bytes of generated kekSubKey as loginSubKey
const loginSubKey = await cryptoWorker.toB64(
- kekSubKey.slice(0, LOGIN_SUB_KEY_BYTE_LENGTH)
+ kekSubKey.slice(0, LOGIN_SUB_KEY_BYTE_LENGTH),
);
return loginSubKey;
@@ -98,13 +98,13 @@ export const generateLoginSubKey = async (kek: string) => {
export const saveKeyInSessionStore = async (
keyType: SESSION_KEYS,
key: string,
- fromDesktop?: boolean
+ fromDesktop?: boolean,
) => {
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
const sessionKeyAttributes =
await cryptoWorker.generateKeyAndEncryptToB64(key);
setKey(keyType, sessionKeyAttributes);
- addLogLine('fromDesktop', fromDesktop);
+ addLogLine("fromDesktop", fromDesktop);
if (
isElectron() &&
!fromDesktop &&
@@ -137,7 +137,7 @@ export const getRecoveryKey = async () => {
recoveryKey = await cryptoWorker.decryptB64(
recoveryKeyEncryptedWithMasterKey,
recoveryKeyDecryptionNonce,
- masterKey
+ masterKey,
);
} else {
recoveryKey = await createNewRecoveryKey();
@@ -146,7 +146,7 @@ export const getRecoveryKey = async () => {
return recoveryKey;
} catch (e) {
console.log(e);
- logError(e, 'getRecoveryKey failed');
+ logError(e, "getRecoveryKey failed");
throw e;
}
};
@@ -162,11 +162,11 @@ async function createNewRecoveryKey() {
const recoveryKey = await cryptoWorker.generateEncryptionKey();
const encryptedMasterKey = await cryptoWorker.encryptToB64(
masterKey,
- recoveryKey
+ recoveryKey,
);
const encryptedRecoveryKey = await cryptoWorker.encryptToB64(
recoveryKey,
- masterKey
+ masterKey,
);
const recoveryKeyAttributes = {
masterKeyEncryptedWithRecoveryKey: encryptedMasterKey.encryptedData,
@@ -178,7 +178,7 @@ async function createNewRecoveryKey() {
const updatedKeyAttributes = Object.assign(
existingAttributes,
- recoveryKeyAttributes
+ recoveryKeyAttributes,
);
setData(LS_KEYS.KEY_ATTRIBUTES, updatedKeyAttributes);
diff --git a/packages/shared/crypto/index.ts b/packages/shared/crypto/index.ts
index 9f27997097..838e781e99 100644
--- a/packages/shared/crypto/index.ts
+++ b/packages/shared/crypto/index.ts
@@ -1,6 +1,6 @@
-import { Remote } from 'comlink';
-import { DedicatedCryptoWorker } from './internal/crypto.worker';
-import { ComlinkWorker } from '../worker/comlinkWorker';
+import { Remote } from "comlink";
+import { ComlinkWorker } from "../worker/comlinkWorker";
+import { DedicatedCryptoWorker } from "./internal/crypto.worker";
class ComlinkCryptoWorker {
private comlinkWorkerInstance:
@@ -18,8 +18,8 @@ class ComlinkCryptoWorker {
export const getDedicatedCryptoWorker = () => {
const cryptoComlinkWorker = new ComlinkWorker<typeof DedicatedCryptoWorker>(
- 'ente-crypto-worker',
- new Worker(new URL('internal/crypto.worker.ts', import.meta.url))
+ "ente-crypto-worker",
+ new Worker(new URL("internal/crypto.worker.ts", import.meta.url)),
);
return cryptoComlinkWorker;
};
diff --git a/packages/shared/crypto/internal/crypto.worker.ts b/packages/shared/crypto/internal/crypto.worker.ts
index 784c6e4ef2..ac1d52a0d4 100644
--- a/packages/shared/crypto/internal/crypto.worker.ts
+++ b/packages/shared/crypto/internal/crypto.worker.ts
@@ -1,6 +1,6 @@
-import * as Comlink from 'comlink';
-import { StateAddress } from 'libsodium-wrappers';
-import * as libsodium from '@ente/shared/crypto/internal/libsodium';
+import * as libsodium from "@ente/shared/crypto/internal/libsodium";
+import * as Comlink from "comlink";
+import { StateAddress } from "libsodium-wrappers";
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
@@ -8,12 +8,12 @@ export class DedicatedCryptoWorker {
async decryptMetadata(
encryptedMetadata: string,
header: string,
- key: string
+ key: string,
) {
const encodedMetadata = await libsodium.decryptChaChaOneShot(
await libsodium.fromB64(encryptedMetadata),
await libsodium.fromB64(header),
- key
+ key,
);
return JSON.parse(textDecoder.decode(encodedMetadata));
}
@@ -21,7 +21,7 @@ export class DedicatedCryptoWorker {
async decryptThumbnail(
fileData: Uint8Array,
header: Uint8Array,
- key: string
+ key: string,
) {
return libsodium.decryptChaChaOneShot(fileData, header, key);
}
@@ -29,15 +29,15 @@ export class DedicatedCryptoWorker {
async decryptEmbedding(
encryptedEmbedding: string,
header: string,
- key: string
+ key: string,
) {
const encodedEmbedding = await libsodium.decryptChaChaOneShot(
await libsodium.fromB64(encryptedEmbedding),
await libsodium.fromB64(header),
- key
+ key,
);
return Float32Array.from(
- JSON.parse(textDecoder.decode(encodedEmbedding))
+ JSON.parse(textDecoder.decode(encodedEmbedding)),
);
}
@@ -66,11 +66,11 @@ export class DedicatedCryptoWorker {
async encryptEmbedding(embedding: Float32Array, key: string) {
const encodedEmbedding = textEncoder.encode(
- JSON.stringify(Array.from(embedding))
+ JSON.stringify(Array.from(embedding)),
);
const { file: encryptEmbedding } = await libsodium.encryptChaChaOneShot(
encodedEmbedding,
- key
+ key,
);
const { encryptedData, ...other } = encryptEmbedding;
return {
@@ -89,7 +89,7 @@ export class DedicatedCryptoWorker {
async encryptFileChunk(
data: Uint8Array,
pushState: StateAddress,
- isFinalChunk: boolean
+ isFinalChunk: boolean,
) {
return libsodium.encryptFileChunk(data, pushState, isFinalChunk);
}
@@ -122,7 +122,7 @@ export class DedicatedCryptoWorker {
passphrase: string,
salt: string,
opsLimit: number,
- memLimit: number
+ memLimit: number,
) {
return libsodium.deriveKey(passphrase, salt, opsLimit, memLimit);
}
@@ -179,7 +179,7 @@ export class DedicatedCryptoWorker {
key: string,
subKeyLength: number,
subKeyID: number,
- context: string
+ context: string,
) {
return libsodium.generateSubKey(key, subKeyLength, subKeyID, context);
}
diff --git a/packages/shared/crypto/internal/libsodium.ts b/packages/shared/crypto/internal/libsodium.ts
index de7e2f9c7e..8940bcb60a 100644
--- a/packages/shared/crypto/internal/libsodium.ts
+++ b/packages/shared/crypto/internal/libsodium.ts
@@ -1,22 +1,22 @@
-import sodium, { StateAddress } from 'libsodium-wrappers';
-import { ENCRYPTION_CHUNK_SIZE } from '../constants';
-import { B64EncryptionResult } from '../types';
-import { CustomError } from '@ente/shared/error';
+import { CustomError } from "@ente/shared/error";
+import sodium, { StateAddress } from "libsodium-wrappers";
+import { ENCRYPTION_CHUNK_SIZE } from "../constants";
+import { B64EncryptionResult } from "../types";
export async function decryptChaChaOneShot(
data: Uint8Array,
header: Uint8Array,
- key: string
+ key: string,
) {
await sodium.ready;
const pullState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(
header,
- await fromB64(key)
+ await fromB64(key),
);
const pullResult = sodium.crypto_secretstream_xchacha20poly1305_pull(
pullState,
data,
- null
+ null,
);
return pullResult.message;
}
@@ -24,12 +24,12 @@ export async function decryptChaChaOneShot(
export async function decryptChaCha(
data: Uint8Array,
header: Uint8Array,
- key: string
+ key: string,
) {
await sodium.ready;
const pullState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(
header,
- await fromB64(key)
+ await fromB64(key),
);
const decryptionChunkSize =
ENCRYPTION_CHUNK_SIZE +
@@ -45,7 +45,7 @@ export async function decryptChaCha(
const buffer = data.slice(bytesRead, bytesRead + chunkSize);
const pullResult = sodium.crypto_secretstream_xchacha20poly1305_pull(
pullState,
- buffer
+ buffer,
);
if (!pullResult.message) {
throw new Error(CustomError.PROCESSING_FAILED);
@@ -63,7 +63,7 @@ export async function initChunkDecryption(header: Uint8Array, key: Uint8Array) {
await sodium.ready;
const pullState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(
header,
- key
+ key,
);
const decryptionChunkSize =
ENCRYPTION_CHUNK_SIZE +
@@ -74,12 +74,12 @@ export async function initChunkDecryption(header: Uint8Array, key: Uint8Array) {
export async function decryptFileChunk(
data: Uint8Array,
- pullState: StateAddress
+ pullState: StateAddress,
) {
await sodium.ready;
const pullResult = sodium.crypto_secretstream_xchacha20poly1305_pull(
pullState,
- data
+ data,
);
if (!pullResult.message) {
throw new Error(CustomError.PROCESSING_FAILED);
@@ -100,7 +100,7 @@ export async function encryptChaChaOneShot(data: Uint8Array, key: string) {
pushState,
data,
null,
- sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
+ sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL,
);
return {
key: await toB64(uintkey),
@@ -138,7 +138,7 @@ export async function encryptChaCha(data: Uint8Array) {
pushState,
buffer,
null,
- tag
+ tag,
);
for (let index = 0; index < pushResult.length; index++) {
encryptedData.push(pushResult[index]);
@@ -169,7 +169,7 @@ export async function initChunkEncryption() {
export async function encryptFileChunk(
data: Uint8Array,
pushState: sodium.StateAddress,
- isFinalChunk: boolean
+ isFinalChunk: boolean,
) {
await sodium.ready;
const tag = isFinalChunk
@@ -179,7 +179,7 @@ export async function encryptFileChunk(
pushState,
data,
null,
- tag
+ tag,
);
return pushResult;
@@ -211,7 +211,7 @@ export async function decryptB64(data: string, nonce: string, key: string) {
const decrypted = await decrypt(
await fromB64(data),
await fromB64(nonce),
- await fromB64(key)
+ await fromB64(key),
);
return await toB64(decrypted);
@@ -222,7 +222,7 @@ export async function decryptToUTF8(data: string, nonce: string, key: string) {
const decrypted = await decrypt(
await fromB64(data),
await fromB64(nonce),
- await fromB64(key)
+ await fromB64(key),
);
return sodium.to_string(decrypted);
@@ -248,14 +248,14 @@ export async function initChunkHashing() {
await sodium.ready;
const hashState = sodium.crypto_generichash_init(
null,
- sodium.crypto_generichash_BYTES_MAX
+ sodium.crypto_generichash_BYTES_MAX,
);
return hashState;
}
export async function hashFileChunk(
hashState: sodium.StateAddress,
- chunk: Uint8Array
+ chunk: Uint8Array,
) {
await sodium.ready;
sodium.crypto_generichash_update(hashState, chunk);
@@ -265,7 +265,7 @@ export async function completeChunkHashing(hashState: sodium.StateAddress) {
await sodium.ready;
const hash = sodium.crypto_generichash_final(
hashState,
- sodium.crypto_generichash_BYTES_MAX
+ sodium.crypto_generichash_BYTES_MAX,
);
const hashString = toB64(hash);
return hashString;
@@ -275,7 +275,7 @@ export async function deriveKey(
passphrase: string,
salt: string,
opsLimit: number,
- memLimit: number
+ memLimit: number,
) {
await sodium.ready;
return await toB64(
@@ -285,8 +285,8 @@ export async function deriveKey(
await fromB64(salt),
opsLimit,
memLimit,
- sodium.crypto_pwhash_ALG_ARGON2ID13
- )
+ sodium.crypto_pwhash_ALG_ARGON2ID13,
+ ),
);
}
@@ -319,8 +319,8 @@ export async function deriveInteractiveKey(passphrase: string, salt: string) {
await fromB64(salt),
sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE,
sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE,
- sodium.crypto_pwhash_ALG_ARGON2ID13
- )
+ sodium.crypto_pwhash_ALG_ARGON2ID13,
+ ),
);
return {
key,
@@ -351,22 +351,22 @@ export async function generateKeyPair() {
export async function boxSealOpen(
input: string,
publicKey: string,
- secretKey: string
+ secretKey: string,
) {
await sodium.ready;
return await toB64(
sodium.crypto_box_seal_open(
await fromB64(input),
await fromB64(publicKey),
- await fromB64(secretKey)
- )
+ await fromB64(secretKey),
+ ),
);
}
export async function boxSeal(input: string, publicKey: string) {
await sodium.ready;
return await toB64(
- sodium.crypto_box_seal(await fromB64(input), await fromB64(publicKey))
+ sodium.crypto_box_seal(await fromB64(input), await fromB64(publicKey)),
);
}
@@ -374,7 +374,7 @@ export async function generateSubKey(
key: string,
subKeyLength: number,
subKeyID: number,
- context: string
+ context: string,
) {
await sodium.ready;
return await toB64(
@@ -382,8 +382,8 @@ export async function generateSubKey(
subKeyLength,
subKeyID,
context,
- await fromB64(key)
- )
+ await fromB64(key),
+ ),
);
}
diff --git a/packages/shared/crypto/types.ts b/packages/shared/crypto/types.ts
index 111533095a..2eeea70272 100644
--- a/packages/shared/crypto/types.ts
+++ b/packages/shared/crypto/types.ts
@@ -1,4 +1,4 @@
-import { DataStream } from '@ente/shared/upload/types';
+import { DataStream } from "@ente/shared/upload/types";
export interface LocalFileAttributes<
T extends string | Uint8Array | DataStream,
diff --git a/packages/shared/electron/index.ts b/packages/shared/electron/index.ts
index 33624a2ed4..38e38e3a40 100644
--- a/packages/shared/electron/index.ts
+++ b/packages/shared/electron/index.ts
@@ -1,5 +1,5 @@
-import { ElectronAPIsType } from './types';
+import { ElectronAPIsType } from "./types";
-const ElectronAPIs: ElectronAPIsType = globalThis['ElectronAPIs'];
+const ElectronAPIs: ElectronAPIsType = globalThis["ElectronAPIs"];
export default ElectronAPIs;
diff --git a/packages/shared/electron/service.ts b/packages/shared/electron/service.ts
index dfa63eaec3..2f00b42f45 100644
--- a/packages/shared/electron/service.ts
+++ b/packages/shared/electron/service.ts
@@ -1,22 +1,22 @@
-import * as Comlink from 'comlink';
-import { LimitedCache } from '@ente/shared/storage/cacheStorage/types';
+import { runningInWorker } from "@ente/shared/platform";
+import { LimitedCache } from "@ente/shared/storage/cacheStorage/types";
+import * as Comlink from "comlink";
+import { wrap } from "comlink";
+import { ElectronAPIsType } from "./types";
import {
ProxiedWorkerLimitedCache,
WorkerSafeElectronClient,
-} from './worker/client';
-import { wrap } from 'comlink';
-import { deserializeToResponse, serializeResponse } from './worker/utils/proxy';
-import { runningInWorker } from '@ente/shared/platform';
-import { ElectronAPIsType } from './types';
+} from "./worker/client";
+import { deserializeToResponse, serializeResponse } from "./worker/utils/proxy";
export interface LimitedElectronAPIs
extends Pick<
ElectronAPIsType,
- | 'openDiskCache'
- | 'deleteDiskCache'
- | 'getSentryUserID'
- | 'convertToJPEG'
- | 'logToDisk'
+ | "openDiskCache"
+ | "deleteDiskCache"
+ | "getSentryUserID"
+ | "convertToJPEG"
+ | "logToDisk"
> {}
class WorkerSafeElectronServiceImpl implements LimitedElectronAPIs {
@@ -42,7 +42,7 @@ class WorkerSafeElectronServiceImpl implements LimitedElectronAPIs {
await this.ready;
const cache = await this.proxiedElectron.openDiskCache(
cacheName,
- cacheLimitInBytes
+ cacheLimitInBytes,
);
return {
match: transformMatch(cache.match.bind(cache)),
@@ -62,7 +62,7 @@ class WorkerSafeElectronServiceImpl implements LimitedElectronAPIs {
}
async convertToJPEG(
inputFileData: Uint8Array,
- filename: string
+ filename: string,
): Promise<Uint8Array> {
await this.ready;
return this.proxiedElectron.convertToJPEG(inputFileData, filename);
@@ -76,16 +76,16 @@ class WorkerSafeElectronServiceImpl implements LimitedElectronAPIs {
export const WorkerSafeElectronService = new WorkerSafeElectronServiceImpl();
function transformMatch(
- fn: ProxiedWorkerLimitedCache['match']
-): LimitedCache['match'] {
+ fn: ProxiedWorkerLimitedCache["match"],
+): LimitedCache["match"] {
return async (key: string, options) => {
return deserializeToResponse(await fn(key, options));
};
}
function transformPut(
- fn: ProxiedWorkerLimitedCache['put']
-): LimitedCache['put'] {
+ fn: ProxiedWorkerLimitedCache["put"],
+): LimitedCache["put"] {
return async (key: string, data: Response) => {
fn(key, await serializeResponse(data));
};
diff --git a/packages/shared/electron/types.ts b/packages/shared/electron/types.ts
index affb99faaf..df5829ab05 100644
--- a/packages/shared/electron/types.ts
+++ b/packages/shared/electron/types.ts
@@ -1,6 +1,6 @@
-import { LimitedCache } from '@ente/shared/storage/cacheStorage/types';
-import { ElectronFile } from '@ente/shared/upload/types';
-import { WatchMapping } from '@ente/shared/watchFolder/types';
+import { LimitedCache } from "@ente/shared/storage/cacheStorage/types";
+import { ElectronFile } from "@ente/shared/upload/types";
+import { WatchMapping } from "@ente/shared/watchFolder/types";
export interface AppUpdateInfo {
autoUpdatable: boolean;
@@ -8,8 +8,8 @@ export interface AppUpdateInfo {
}
export enum Model {
- GGML_CLIP = 'ggml-clip',
- ONNX_CLIP = 'onnx-clip',
+ GGML_CLIP = "ggml-clip",
+ ONNX_CLIP = "onnx-clip",
}
export interface ElectronAPIsType {
@@ -17,7 +17,7 @@ export interface ElectronAPIsType {
checkExistsAndCreateDir: (dirPath: string) => Promise<void>;
saveStreamToDisk: (
path: string,
- fileStream: ReadableStream<any>
+ fileStream: ReadableStream<any>,
) => Promise<void>;
saveFileToDisk: (path: string, file: any) => Promise<void>;
selectDirectory: () => Promise<string>;
@@ -36,29 +36,29 @@ export interface ElectronAPIsType {
files: ElectronFile[];
}>;
getElectronFilesFromGoogleZip: (
- filePath: string
+ filePath: string,
) => Promise<ElectronFile[]>;
setToUploadCollection: (collectionName: string) => void;
getDirFiles: (dirPath: string) => Promise<ElectronFile[]>;
getWatchMappings: () => WatchMapping[];
updateWatchMappingSyncedFiles: (
folderPath: string,
- files: WatchMapping['syncedFiles']
+ files: WatchMapping["syncedFiles"],
) => void;
updateWatchMappingIgnoredFiles: (
folderPath: string,
- files: WatchMapping['ignoredFiles']
+ files: WatchMapping["ignoredFiles"],
) => void;
addWatchMapping: (
collectionName: string,
folderPath: string,
- uploadStrategy: number
+ uploadStrategy: number,
) => Promise<void>;
removeWatchMapping: (folderPath: string) => Promise<void>;
registerWatcherFunctions: (
addFile: (file: ElectronFile) => Promise<void>,
removeFile: (path: string) => Promise<void>,
- removeFolder: (folderPath: string) => Promise<void>
+ removeFolder: (folderPath: string) => Promise<void>,
) => void;
isFolder: (dirPath: string) => Promise<boolean>;
clearElectronStore: () => void;
@@ -66,17 +66,17 @@ export interface ElectronAPIsType {
getEncryptionKey: () => Promise<string>;
openDiskCache: (
cacheName: string,
- cacheLimitInBytes?: number
+ cacheLimitInBytes?: number,
) => Promise<LimitedCache>;
deleteDiskCache: (cacheName: string) => Promise<boolean>;
logToDisk: (msg: string) => void;
convertToJPEG: (
fileData: Uint8Array,
- filename: string
+ filename: string,
) => Promise<Uint8Array>;
openLogDirectory: () => void;
registerUpdateEventListener: (
- showUpdateDialog: (updateInfo: AppUpdateInfo) => void
+ showUpdateDialog: (updateInfo: AppUpdateInfo) => void,
) => void;
updateAndRestart: () => void;
skipAppUpdate: (version: string) => void;
@@ -86,13 +86,13 @@ export interface ElectronAPIsType {
cmd: string[],
inputFile: File | ElectronFile,
outputFileName: string,
- dontTimeout?: boolean
+ dontTimeout?: boolean,
) => Promise<File>;
muteUpdateNotification: (version: string) => void;
generateImageThumbnail: (
inputFile: File | ElectronFile,
maxDimension: number,
- maxSize: number
+ maxSize: number,
) => Promise<Uint8Array>;
logRendererProcessMemoryUsage: (message: string) => Promise<void>;
registerForegroundEventListener: (onForeground: () => void) => void;
@@ -104,10 +104,10 @@ export interface ElectronAPIsType {
updateOptOutOfCrashReports: (optOut: boolean) => Promise<void>;
computeImageEmbedding: (
model: Model,
- imageData: Uint8Array
+ imageData: Uint8Array,
) => Promise<Float32Array>;
computeTextEmbedding: (model: Model, text: string) => Promise<Float32Array>;
- getPlatform: () => Promise<'mac' | 'windows' | 'linux'>;
+ getPlatform: () => Promise<"mac" | "windows" | "linux">;
setCustomCacheDirectory: (directory: string) => Promise<void>;
getCacheDirectory: () => Promise<string>;
}
diff --git a/packages/shared/electron/worker/client.ts b/packages/shared/electron/worker/client.ts
index c1e09b8888..12b34a4e78 100644
--- a/packages/shared/electron/worker/client.ts
+++ b/packages/shared/electron/worker/client.ts
@@ -1,25 +1,25 @@
-import * as Comlink from 'comlink';
-import { LimitedCache } from '@ente/shared/storage/cacheStorage/types';
-import { serializeResponse, deserializeToResponse } from './utils/proxy';
-import ElectronAPIs from '@ente/shared/electron';
+import ElectronAPIs from "@ente/shared/electron";
+import { LimitedCache } from "@ente/shared/storage/cacheStorage/types";
+import * as Comlink from "comlink";
+import { deserializeToResponse, serializeResponse } from "./utils/proxy";
export interface ProxiedLimitedElectronAPIs {
openDiskCache: (
cacheName: string,
- cacheLimitInBytes?: number
+ cacheLimitInBytes?: number,
) => Promise<ProxiedWorkerLimitedCache>;
deleteDiskCache: (cacheName: string) => Promise<boolean>;
getSentryUserID: () => Promise<string>;
convertToJPEG: (
inputFileData: Uint8Array,
- filename: string
+ filename: string,
) => Promise<Uint8Array>;
logToDisk: (message: string) => void;
}
export interface ProxiedWorkerLimitedCache {
match: (
key: string,
- options?: { sizeInBytes?: number }
+ options?: { sizeInBytes?: number },
) => Promise<ArrayBuffer>;
put: (key: string, data: ArrayBuffer) => Promise<void>;
delete: (key: string) => Promise<boolean>;
@@ -29,7 +29,7 @@ export class WorkerSafeElectronClient implements ProxiedLimitedElectronAPIs {
async openDiskCache(cacheName: string, cacheLimitInBytes?: number) {
const cache = await ElectronAPIs.openDiskCache(
cacheName,
- cacheLimitInBytes
+ cacheLimitInBytes,
);
return Comlink.proxy({
match: Comlink.proxy(transformMatch(cache.match.bind(cache))),
@@ -48,7 +48,7 @@ export class WorkerSafeElectronClient implements ProxiedLimitedElectronAPIs {
async convertToJPEG(
inputFileData: Uint8Array,
- filename: string
+ filename: string,
): Promise<Uint8Array> {
return await ElectronAPIs.convertToJPEG(inputFileData, filename);
}
@@ -58,16 +58,16 @@ export class WorkerSafeElectronClient implements ProxiedLimitedElectronAPIs {
}
function transformMatch(
- fn: LimitedCache['match']
-): ProxiedWorkerLimitedCache['match'] {
+ fn: LimitedCache["match"],
+): ProxiedWorkerLimitedCache["match"] {
return async (key: string, options: { sizeInBytes?: number }) => {
return serializeResponse(await fn(key, options));
};
}
function transformPut(
- fn: LimitedCache['put']
-): ProxiedWorkerLimitedCache['put'] {
+ fn: LimitedCache["put"],
+): ProxiedWorkerLimitedCache["put"] {
return async (key: string, data: ArrayBuffer) => {
fn(key, deserializeToResponse(data));
};
diff --git a/packages/shared/electron/worker/utils/transferHandler.ts b/packages/shared/electron/worker/utils/transferHandler.ts
index 81de379e2a..77a7e61a9e 100644
--- a/packages/shared/electron/worker/utils/transferHandler.ts
+++ b/packages/shared/electron/worker/utils/transferHandler.ts
@@ -1,4 +1,4 @@
-import * as Comlink from 'comlink';
+import * as Comlink from "comlink";
// didn't work kept for reference, so that can try to make it work later in future hopefully
export function setupResponseObjectTransferHandler() {
@@ -7,5 +7,5 @@ export function setupResponseObjectTransferHandler() {
serialize: (response: Response) => [response.arrayBuffer() as any, []],
deserialize: (arrayBuffer: ArrayBuffer) => new Response(arrayBuffer),
};
- return Comlink.transferHandlers.set('RESPONSE', transferHandler);
+ return Comlink.transferHandlers.set("RESPONSE", transferHandler);
}
diff --git a/packages/shared/error/index.ts b/packages/shared/error/index.ts
index ca3f969a16..0463c96103 100644
--- a/packages/shared/error/index.ts
+++ b/packages/shared/error/index.ts
@@ -1,4 +1,4 @@
-import { HttpStatusCode } from 'axios';
+import { HttpStatusCode } from "axios";
export interface ApiErrorResponse {
code: string;
@@ -11,88 +11,88 @@ export class ApiError extends Error {
constructor(message: string, errCode: string, httpStatus: number) {
super(message);
- this.name = 'ApiError';
+ this.name = "ApiError";
this.errCode = errCode;
this.httpStatusCode = httpStatus;
}
}
export function isApiErrorResponse(object: any): object is ApiErrorResponse {
- return object && 'code' in object && 'message' in object;
+ return object && "code" in object && "message" in object;
}
export const CustomError = {
- THUMBNAIL_GENERATION_FAILED: 'thumbnail generation failed',
- VIDEO_PLAYBACK_FAILED: 'video playback failed',
- ETAG_MISSING: 'no header/etag present in response body',
- KEY_MISSING: 'encrypted key missing from localStorage',
- FAILED_TO_LOAD_WEB_WORKER: 'failed to load web worker',
- CHUNK_MORE_THAN_EXPECTED: 'chunks more than expected',
- CHUNK_LESS_THAN_EXPECTED: 'chunks less than expected',
- UNSUPPORTED_FILE_FORMAT: 'unsupported file format',
- FILE_TOO_LARGE: 'file too large',
- SUBSCRIPTION_EXPIRED: 'subscription expired',
- STORAGE_QUOTA_EXCEEDED: 'storage quota exceeded',
- SESSION_EXPIRED: 'session expired',
+ THUMBNAIL_GENERATION_FAILED: "thumbnail generation failed",
+ VIDEO_PLAYBACK_FAILED: "video playback failed",
+ ETAG_MISSING: "no header/etag present in response body",
+ KEY_MISSING: "encrypted key missing from localStorage",
+ FAILED_TO_LOAD_WEB_WORKER: "failed to load web worker",
+ CHUNK_MORE_THAN_EXPECTED: "chunks more than expected",
+ CHUNK_LESS_THAN_EXPECTED: "chunks less than expected",
+ UNSUPPORTED_FILE_FORMAT: "unsupported file format",
+ FILE_TOO_LARGE: "file too large",
+ SUBSCRIPTION_EXPIRED: "subscription expired",
+ STORAGE_QUOTA_EXCEEDED: "storage quota exceeded",
+ SESSION_EXPIRED: "session expired",
INVALID_MIME_TYPE: (type: string) => `invalid mime type -${type}`,
- SIGNUP_FAILED: 'signup failed',
- FAV_COLLECTION_MISSING: 'favorite collection missing',
- INVALID_COLLECTION_OPERATION: 'invalid collection operation',
+ SIGNUP_FAILED: "signup failed",
+ FAV_COLLECTION_MISSING: "favorite collection missing",
+ INVALID_COLLECTION_OPERATION: "invalid collection operation",
TO_MOVE_FILES_FROM_MULTIPLE_COLLECTIONS:
- 'to move files from multiple collections',
- WAIT_TIME_EXCEEDED: 'operation wait time exceeded',
- REQUEST_CANCELLED: 'request canceled',
- REQUEST_FAILED: 'request failed',
- TOKEN_EXPIRED: 'token expired',
- TOKEN_MISSING: 'token missing',
- TOO_MANY_REQUESTS: 'too many requests',
- BAD_REQUEST: 'bad request',
- SUBSCRIPTION_NEEDED: 'subscription not present',
- NOT_FOUND: 'not found ',
- NO_METADATA: 'no metadata',
- TOO_LARGE_LIVE_PHOTO_ASSETS: 'too large live photo assets',
- NOT_A_DATE: 'not a date',
- NOT_A_LOCATION: 'not a location',
- FILE_ID_NOT_FOUND: 'file with id not found',
- WEAK_DEVICE: 'password decryption failed on the device',
- INCORRECT_PASSWORD: 'incorrect password',
- UPLOAD_CANCELLED: 'upload cancelled',
- REQUEST_TIMEOUT: 'request taking too long',
+ "to move files from multiple collections",
+ WAIT_TIME_EXCEEDED: "operation wait time exceeded",
+ REQUEST_CANCELLED: "request canceled",
+ REQUEST_FAILED: "request failed",
+ TOKEN_EXPIRED: "token expired",
+ TOKEN_MISSING: "token missing",
+ TOO_MANY_REQUESTS: "too many requests",
+ BAD_REQUEST: "bad request",
+ SUBSCRIPTION_NEEDED: "subscription not present",
+ NOT_FOUND: "not found ",
+ NO_METADATA: "no metadata",
+ TOO_LARGE_LIVE_PHOTO_ASSETS: "too large live photo assets",
+ NOT_A_DATE: "not a date",
+ NOT_A_LOCATION: "not a location",
+ FILE_ID_NOT_FOUND: "file with id not found",
+ WEAK_DEVICE: "password decryption failed on the device",
+ INCORRECT_PASSWORD: "incorrect password",
+ UPLOAD_CANCELLED: "upload cancelled",
+ REQUEST_TIMEOUT: "request taking too long",
HIDDEN_COLLECTION_SYNC_FILE_ATTEMPTED:
- 'hidden collection sync file attempted',
- UNKNOWN_ERROR: 'Something went wrong, please try again',
+ "hidden collection sync file attempted",
+ UNKNOWN_ERROR: "Something went wrong, please try again",
TYPE_DETECTION_FAILED: (fileFormat: string) =>
`type detection failed ${fileFormat}`,
WINDOWS_NATIVE_IMAGE_PROCESSING_NOT_SUPPORTED:
- 'Windows native image processing is not supported',
- NETWORK_ERROR: 'Network Error',
- NOT_FILE_OWNER: 'not file owner',
- UPDATE_EXPORTED_RECORD_FAILED: 'update file exported record failed',
- EXPORT_STOPPED: 'export stopped',
- NO_EXPORT_FOLDER_SELECTED: 'no export folder selected',
- EXPORT_FOLDER_DOES_NOT_EXIST: 'export folder does not exist',
- NO_INTERNET_CONNECTION: 'no internet connection',
- AUTH_KEY_NOT_FOUND: 'auth key not found',
- EXIF_DATA_NOT_FOUND: 'exif data not found',
- SELECT_FOLDER_ABORTED: 'select folder aborted',
- NON_MEDIA_FILE: 'non media file',
- NOT_AVAILABLE_ON_WEB: 'not available on web',
- UNSUPPORTED_RAW_FORMAT: 'unsupported raw format',
- NON_PREVIEWABLE_FILE: 'non previewable file',
- PROCESSING_FAILED: 'processing failed',
- EXPORT_RECORD_JSON_PARSING_FAILED: 'export record json parsing failed',
- TWO_FACTOR_ENABLED: 'two factor enabled',
- PASSKEYS_TWO_FACTOR_ENABLED: 'passkeys two factor enabled',
- CLIENT_ERROR: 'client error',
- ServerError: 'server error',
- FILE_NOT_FOUND: 'file not found',
- UNSUPPORTED_PLATFORM: 'Unsupported platform',
+ "Windows native image processing is not supported",
+ NETWORK_ERROR: "Network Error",
+ NOT_FILE_OWNER: "not file owner",
+ UPDATE_EXPORTED_RECORD_FAILED: "update file exported record failed",
+ EXPORT_STOPPED: "export stopped",
+ NO_EXPORT_FOLDER_SELECTED: "no export folder selected",
+ EXPORT_FOLDER_DOES_NOT_EXIST: "export folder does not exist",
+ NO_INTERNET_CONNECTION: "no internet connection",
+ AUTH_KEY_NOT_FOUND: "auth key not found",
+ EXIF_DATA_NOT_FOUND: "exif data not found",
+ SELECT_FOLDER_ABORTED: "select folder aborted",
+ NON_MEDIA_FILE: "non media file",
+ NOT_AVAILABLE_ON_WEB: "not available on web",
+ UNSUPPORTED_RAW_FORMAT: "unsupported raw format",
+ NON_PREVIEWABLE_FILE: "non previewable file",
+ PROCESSING_FAILED: "processing failed",
+ EXPORT_RECORD_JSON_PARSING_FAILED: "export record json parsing failed",
+ TWO_FACTOR_ENABLED: "two factor enabled",
+ PASSKEYS_TWO_FACTOR_ENABLED: "passkeys two factor enabled",
+ CLIENT_ERROR: "client error",
+ ServerError: "server error",
+ FILE_NOT_FOUND: "file not found",
+ UNSUPPORTED_PLATFORM: "Unsupported platform",
MODEL_DOWNLOAD_PENDING:
- 'Model download pending, skipping clip search request',
- DOWNLOAD_MANAGER_NOT_READY: 'Download manager not initialized',
- UPDATE_URL_FILE_ID_MISMATCH: 'update url file id mismatch',
- URL_ALREADY_SET: 'url already set',
- FILE_CONVERSION_FAILED: 'file conversion failed',
+ "Model download pending, skipping clip search request",
+ DOWNLOAD_MANAGER_NOT_READY: "Download manager not initialized",
+ UPDATE_URL_FILE_ID_MISMATCH: "update url file id mismatch",
+ URL_ALREADY_SET: "url already set",
+ FILE_CONVERSION_FAILED: "file conversion failed",
};
export function handleUploadError(error: any): Error {
@@ -112,8 +112,8 @@ export function handleUploadError(error: any): Error {
export function errorWithContext(originalError: Error, context: string) {
const errorWithContext = new Error(context);
errorWithContext.stack =
- errorWithContext.stack?.split('\n').slice(2, 4).join('\n') +
- '\n' +
+ errorWithContext.stack?.split("\n").slice(2, 4).join("\n") +
+ "\n" +
originalError.stack;
return errorWithContext;
}
diff --git a/packages/shared/events/index.ts b/packages/shared/events/index.ts
index 670ecac47c..32306fc64d 100644
--- a/packages/shared/events/index.ts
+++ b/packages/shared/events/index.ts
@@ -1,12 +1,12 @@
-import { EventEmitter } from 'eventemitter3';
+import { EventEmitter } from "eventemitter3";
// When registering event handlers,
// handle errors to avoid unhandled rejection or propagation to emit call
export enum Events {
- LOGOUT = 'logout',
- FILE_UPLOADED = 'fileUploaded',
- LOCAL_FILES_UPDATED = 'localFilesUpdated',
+ LOGOUT = "logout",
+ FILE_UPLOADED = "fileUploaded",
+ LOCAL_FILES_UPDATED = "localFilesUpdated",
}
export const eventBus = new EventEmitter<Events>();
diff --git a/packages/shared/hooks/useCastReceiver.tsx b/packages/shared/hooks/useCastReceiver.tsx
index 1301939e14..176b968824 100644
--- a/packages/shared/hooks/useCastReceiver.tsx
+++ b/packages/shared/hooks/useCastReceiver.tsx
@@ -1,6 +1,6 @@
declare const cast: any;
-import { useEffect, useState } from 'react';
+import { useEffect, useState } from "react";
type Receiver = {
cast: typeof cast;
@@ -12,11 +12,11 @@ const load = (() => {
return () => {
if (promise === null) {
promise = new Promise((resolve) => {
- const script = document.createElement('script');
+ const script = document.createElement("script");
script.src =
- 'https://www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js';
+ "https://www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js";
- script.addEventListener('load', () => {
+ script.addEventListener("load", () => {
resolve({
cast,
});
diff --git a/packages/shared/hooks/useCastSender.tsx b/packages/shared/hooks/useCastSender.tsx
index 88e0b73efb..0f3c6a316b 100644
--- a/packages/shared/hooks/useCastSender.tsx
+++ b/packages/shared/hooks/useCastSender.tsx
@@ -7,7 +7,7 @@ declare global {
}
}
-import { useEffect, useState } from 'react';
+import { useEffect, useState } from "react";
type Sender = {
chrome: typeof chrome;
@@ -20,13 +20,13 @@ export const loadSender = (() => {
return () => {
if (promise === null) {
promise = new Promise((resolve) => {
- const script = document.createElement('script');
+ const script = document.createElement("script");
script.src =
- 'https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1';
+ "https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1";
window.__onGCastApiAvailable = (isAvailable) => {
if (isAvailable) {
cast.framework.CastContext.getInstance().setOptions({
- receiverApplicationId: 'F5BCEC64',
+ receiverApplicationId: "F5BCEC64",
autoJoinPolicy:
chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED,
});
@@ -49,7 +49,7 @@ export const useCastSender = () => {
{
chrome: null,
cast: null,
- }
+ },
);
useEffect(() => {
diff --git a/packages/shared/hooks/useComponentScroll.tsx b/packages/shared/hooks/useComponentScroll.tsx
index d4dd5b26dc..9cdf264559 100644
--- a/packages/shared/hooks/useComponentScroll.tsx
+++ b/packages/shared/hooks/useComponentScroll.tsx
@@ -1,4 +1,4 @@
-import { useRef, useState, useEffect } from 'react';
+import { useEffect, useRef, useState } from "react";
export enum SCROLL_DIRECTION {
LEFT = -1,
@@ -31,15 +31,15 @@ export default function useComponentScroll({
return;
}
// Add event listener
- componentRef.current?.addEventListener('scroll', updateScrollObj);
+ componentRef.current?.addEventListener("scroll", updateScrollObj);
// Call handler right away so state gets updated with initial window size
updateScrollObj();
// Remove event listener on cleanup
return () =>
componentRef.current?.removeEventListener(
- 'resize',
- updateScrollObj
+ "resize",
+ updateScrollObj,
);
}, [componentRef.current]);
diff --git a/packages/shared/hooks/useEffectSingleThreaded.tsx b/packages/shared/hooks/useEffectSingleThreaded.tsx
index 3bdebed5a0..d6db9c1e21 100644
--- a/packages/shared/hooks/useEffectSingleThreaded.tsx
+++ b/packages/shared/hooks/useEffectSingleThreaded.tsx
@@ -1,12 +1,12 @@
-import { useEffect, useRef } from 'react';
-import { isPromise } from '../utils';
+import { useEffect, useRef } from "react";
+import { isPromise } from "../utils";
// useEffectSingleThreaded is a useEffect that will only run one at a time, and will
// caches the latest deps of requests that come in while it is running, and will
// run that after the current run is complete.
export default function useEffectSingleThreaded(
fn: (deps) => void | Promise<void>,
- deps: any[]
+ deps: any[],
): void {
const updateInProgress = useRef(false);
const nextRequestDepsRef = useRef<any[]>(null);
diff --git a/packages/shared/hooks/useFileInput.tsx b/packages/shared/hooks/useFileInput.tsx
index 25b72b6f5a..b357d918ee 100644
--- a/packages/shared/hooks/useFileInput.tsx
+++ b/packages/shared/hooks/useFileInput.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useRef, useState } from 'react';
+import { useCallback, useRef, useState } from "react";
export interface FileWithPath extends File {
readonly path?: string;
@@ -16,11 +16,11 @@ export default function useFileInput({ directory }: { directory?: boolean }) {
}, []);
const handleChange: React.ChangeEventHandler<HTMLInputElement> = async (
- event
+ event,
) => {
if (!!event.target && !!event.target.files) {
const files = [...event.target.files].map((file) =>
- toFileWithPath(file)
+ toFileWithPath(file),
);
setSelectedFiles(files);
}
@@ -28,14 +28,14 @@ export default function useFileInput({ directory }: { directory?: boolean }) {
const getInputProps = useCallback(
() => ({
- type: 'file',
+ type: "file",
multiple: true,
- style: { display: 'none' },
- ...(directory ? { directory: '', webkitdirectory: '' } : {}),
+ style: { display: "none" },
+ ...(directory ? { directory: "", webkitdirectory: "" } : {}),
ref: inputRef,
onChange: handleChange,
}),
- []
+ [],
);
return {
@@ -47,14 +47,14 @@ export default function useFileInput({ directory }: { directory?: boolean }) {
// https://github.com/react-dropzone/file-selector/blob/master/src/file.ts#L88
export function toFileWithPath(file: File, path?: string): FileWithPath {
- if (typeof (file as any).path !== 'string') {
+ if (typeof (file as any).path !== "string") {
// on electron, path is already set to the absolute path
const { webkitRelativePath } = file;
- Object.defineProperty(file, 'path', {
+ Object.defineProperty(file, "path", {
value:
- typeof path === 'string'
+ typeof path === "string"
? path
- : typeof webkitRelativePath === 'string' && // If <input webkitdirectory> is set,
+ : typeof webkitRelativePath === "string" && // If <input webkitdirectory> is set,
// the File will have a {webkitRelativePath} property
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory
webkitRelativePath.length > 0
diff --git a/packages/shared/hooks/useLocalState.tsx b/packages/shared/hooks/useLocalState.tsx
index 98565c525b..1424fec7f7 100644
--- a/packages/shared/hooks/useLocalState.tsx
+++ b/packages/shared/hooks/useLocalState.tsx
@@ -1,21 +1,21 @@
-import { Dispatch, SetStateAction, useEffect, useState } from 'react';
-import { getData, LS_KEYS, setData } from '@ente/shared/storage/localStorage';
+import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
+import { Dispatch, SetStateAction, useEffect, useState } from "react";
export function useLocalState<T>(
key: LS_KEYS,
- initialValue?: T
+ initialValue?: T,
): [T, Dispatch<SetStateAction<T>>] {
const [value, setValue] = useState<T>(initialValue);
useEffect(() => {
const { value } = getData(key) ?? {};
- if (typeof value !== 'undefined') {
+ if (typeof value !== "undefined") {
setValue(value);
}
}, []);
useEffect(() => {
- if (typeof value !== 'undefined') {
+ if (typeof value !== "undefined") {
setData(key, { value });
}
}, [value]);
diff --git a/packages/shared/hooks/useLongPress.ts b/packages/shared/hooks/useLongPress.ts
index 66e823e77f..a42b72f92d 100644
--- a/packages/shared/hooks/useLongPress.ts
+++ b/packages/shared/hooks/useLongPress.ts
@@ -1,5 +1,5 @@
// https://stackoverflow.com/a/54749871/2760968
-import { useState, useEffect } from 'react';
+import { useEffect, useState } from "react";
export default function useLongPress(callback: () => void, ms = 300) {
const [startLongPress, setStartLongPress] = useState(false);
diff --git a/packages/shared/hooks/useMemoSingleThreaded.tsx b/packages/shared/hooks/useMemoSingleThreaded.tsx
index c8a75a85f1..ada7d54812 100644
--- a/packages/shared/hooks/useMemoSingleThreaded.tsx
+++ b/packages/shared/hooks/useMemoSingleThreaded.tsx
@@ -1,8 +1,8 @@
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useRef, useState } from "react";
export default function useMemoSingleThreaded<T>(
fn: () => T | Promise<T>,
- deps: any[]
+ deps: any[],
): T {
const [result, setResult] = useState<T>(null);
const updateInProgress = useRef(false);
@@ -34,5 +34,5 @@ export default function useMemoSingleThreaded<T>(
}
function isPromise<T>(obj: T | Promise<T>): obj is Promise<T> {
- return obj && typeof (obj as any).then === 'function';
+ return obj && typeof (obj as any).then === "function";
}
diff --git a/packages/shared/hooks/useWindowSize.tsx b/packages/shared/hooks/useWindowSize.tsx
index e1b514f433..c86a3e1f18 100644
--- a/packages/shared/hooks/useWindowSize.tsx
+++ b/packages/shared/hooks/useWindowSize.tsx
@@ -1,5 +1,5 @@
// https://usehooks.com/useWindowSize/
-import { useState, useEffect } from 'react';
+import { useEffect, useState } from "react";
// Hook
export default function useWindowSize() {
@@ -24,13 +24,13 @@ export default function useWindowSize() {
}
// Add event listener
- window.addEventListener('resize', handleResize);
+ window.addEventListener("resize", handleResize);
// Call handler right away so state gets updated with initial window size
handleResize();
// Remove event listener on cleanup
- return () => window.removeEventListener('resize', handleResize);
+ return () => window.removeEventListener("resize", handleResize);
}, []); // Empty array ensures that effect is only run on mount
return windowSize;
diff --git a/packages/shared/logging/index.ts b/packages/shared/logging/index.ts
index 2592500a43..c7c793dbfe 100644
--- a/packages/shared/logging/index.ts
+++ b/packages/shared/logging/index.ts
@@ -1,8 +1,8 @@
-import isElectron from 'is-electron';
-import { logError } from '@ente/shared/sentry';
-import { formatLog, logWeb } from './web';
-import { WorkerSafeElectronService } from '../electron/service';
-import { isDevBuild } from '@/utils/env';
+import { isDevBuild } from "@/utils/env";
+import { logError } from "@ente/shared/sentry";
+import isElectron from "is-electron";
+import { WorkerSafeElectronService } from "../electron/service";
+import { formatLog, logWeb } from "./web";
export const MAX_LOG_SIZE = 5 * 1024 * 1024; // 5MB
export const MAX_LOG_LINES = 1000;
@@ -12,7 +12,7 @@ export function addLogLine(
...optionalParams: (string | number | boolean)[]
) {
try {
- const completeLog = [log, ...optionalParams].join(' ');
+ const completeLog = [log, ...optionalParams].join(" ");
if (isDevBuild) {
console.log(completeLog);
}
@@ -22,7 +22,7 @@ export function addLogLine(
logWeb(completeLog);
}
} catch (e) {
- logError(e, 'failed to addLogLine', undefined, true);
+ logError(e, "failed to addLogLine", undefined, true);
// ignore
}
}
@@ -33,7 +33,7 @@ export const addLocalLog = (getLog: () => string) => {
formatLog({
logLine: getLog(),
timestamp: Date.now(),
- })
+ }),
);
}
};
diff --git a/packages/shared/logging/web.ts b/packages/shared/logging/web.ts
index 13eb5a1827..e0c36dc89a 100644
--- a/packages/shared/logging/web.ts
+++ b/packages/shared/logging/web.ts
@@ -1,17 +1,17 @@
-import { convertBytesToHumanReadable } from '../utils/size';
-import { formatDateTimeShort } from '../time/format';
-import { logError } from '@ente/shared/sentry';
+import { isDevBuild } from "@/utils/env";
+import { logError } from "@ente/shared/sentry";
import {
getData,
LS_KEYS,
removeData,
setData,
-} from '@ente/shared/storage/localStorage';
-import { ElectronFile } from '../upload/types';
-import { addLogLine } from '.';
-import { getSentryUserID } from '../sentry/utils';
-import type { User } from '../user/types';
-import { isDevBuild } from '@/utils/env';
+} from "@ente/shared/storage/localStorage";
+import { addLogLine } from ".";
+import { getSentryUserID } from "../sentry/utils";
+import { formatDateTimeShort } from "../time/format";
+import { ElectronFile } from "../upload/types";
+import type { User } from "../user/types";
+import { convertBytesToHumanReadable } from "../utils/size";
export const MAX_LOG_SIZE = 5 * 1024 * 1024; // 5MB
export const MAX_LOG_LINES = 1000;
@@ -31,9 +31,9 @@ export function logWeb(logLine: string) {
logs.push(log);
setLogs(logs);
} catch (e) {
- if (e.name === 'QuotaExceededError') {
+ if (e.name === "QuotaExceededError") {
deleteLogs();
- logWeb('logs cleared');
+ logWeb("logs cleared");
}
}
}
@@ -52,7 +52,7 @@ export const clearLogsIfLocalStorageLimitExceeded = () => {
const logSize = getStringSize(logs);
if (logSize > MAX_LOG_SIZE) {
deleteLogs();
- logWeb('Logs cleared due to size limit exceeded');
+ logWeb("Logs cleared due to size limit exceeded");
} else {
try {
logWeb(`app started`);
@@ -64,9 +64,9 @@ export const clearLogsIfLocalStorageLimitExceeded = () => {
} catch (e) {
logError(
e,
- 'failed to clearLogsIfLocalStorageLimitExceeded',
+ "failed to clearLogsIfLocalStorageLimitExceeded",
undefined,
- true
+ true,
);
}
};
@@ -76,7 +76,7 @@ export const logStartupMessage = async (appId: string) => {
const appIdL = appId.toLowerCase();
const userID = (getData(LS_KEYS.USER) as User)?.id;
const sentryID = await getSentryUserID();
- const buildId = isDevBuild ? 'dev' : `git ${process.env.GIT_SHA}`;
+ const buildId = isDevBuild ? "dev" : `git ${process.env.GIT_SHA}`;
addLogLine(`ente-${appIdL}-web ${buildId} uid ${userID} sid ${sentryID}`);
};
@@ -102,5 +102,5 @@ export function formatLog(log: Log) {
}
function combineLogLines(logs: Log[]) {
- return logs.map(formatLog).join('\n');
+ return logs.map(formatLog).join("\n");
}
diff --git a/packages/shared/network/HTTPService.ts b/packages/shared/network/HTTPService.ts
index 4a7f5f1494..ce60537ee9 100644
--- a/packages/shared/network/HTTPService.ts
+++ b/packages/shared/network/HTTPService.ts
@@ -1,8 +1,8 @@
-import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
-import { addLogLine } from '@ente/shared/logging';
-import { logError } from '@ente/shared/sentry';
+import { addLogLine } from "@ente/shared/logging";
+import { logError } from "@ente/shared/sentry";
+import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
-import { ApiError, CustomError, isApiErrorResponse } from '../error';
+import { ApiError, CustomError, isApiErrorResponse } from "../error";
interface IHTTPHeaders {
[headerKey: string]: any;
@@ -28,10 +28,10 @@ class HTTPService {
// that falls out of the range of 2xx
if (isApiErrorResponse(response.data)) {
const responseData = response.data;
- logError(error, 'HTTP Service Error', {
+ logError(error, "HTTP Service Error", {
url: config.url,
method: config.method,
- xRequestId: response.headers['x-request-id'],
+ xRequestId: response.headers["x-request-id"],
httpStatus: response.status,
errMessage: responseData.message,
errCode: responseData.code,
@@ -39,28 +39,28 @@ class HTTPService {
apiError = new ApiError(
responseData.message,
responseData.code,
- response.status
+ response.status,
);
} else {
if (response.status >= 400 && response.status < 500) {
apiError = new ApiError(
CustomError.CLIENT_ERROR,
- '',
- response.status
+ "",
+ response.status,
);
} else {
apiError = new ApiError(
CustomError.ServerError,
- '',
- response.status
+ "",
+ response.status,
);
}
}
- logError(apiError, 'HTTP Service Error', {
+ logError(apiError, "HTTP Service Error", {
url: config.url,
method: config.method,
- cfRay: response.headers['cf-ray'],
- xRequestId: response.headers['x-request-id'],
+ cfRay: response.headers["cf-ray"],
+ xRequestId: response.headers["x-request-id"],
httpStatus: response.status,
});
throw apiError;
@@ -69,21 +69,21 @@ class HTTPService {
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
addLogLine(
- 'request failed- no response',
+ "request failed- no response",
`url: ${config.url}`,
- `method: ${config.method}`
+ `method: ${config.method}`,
);
return Promise.reject(error);
} else {
// Something happened in setting up the request that triggered an Error
addLogLine(
- 'request failed- axios error',
+ "request failed- axios error",
`url: ${config.url}`,
- `method: ${config.method}`
+ `method: ${config.method}`,
);
return Promise.reject(error);
}
- }
+ },
);
}
@@ -91,7 +91,7 @@ class HTTPService {
* header object to be append to all api calls.
*/
private headers: IHTTPHeaders = {
- 'content-type': 'application/json',
+ "content-type": "application/json",
};
/**
@@ -143,7 +143,7 @@ class HTTPService {
};
if (customConfig?.cancel) {
config.cancelToken = new axios.CancelToken(
- (c) => (customConfig.cancel.exec = c)
+ (c) => (customConfig.cancel.exec = c),
);
}
return await axios({ ...config, ...customConfig });
@@ -156,16 +156,16 @@ class HTTPService {
url: string,
params?: IQueryPrams,
headers?: IHTTPHeaders,
- customConfig?: any
+ customConfig?: any,
) {
return this.request(
{
headers,
- method: 'GET',
+ method: "GET",
params,
url,
},
- customConfig
+ customConfig,
);
}
@@ -177,17 +177,17 @@ class HTTPService {
data?: any,
params?: IQueryPrams,
headers?: IHTTPHeaders,
- customConfig?: any
+ customConfig?: any,
) {
return this.request(
{
data,
headers,
- method: 'POST',
+ method: "POST",
params,
url,
},
- customConfig
+ customConfig,
);
}
@@ -199,17 +199,17 @@ class HTTPService {
data?: any,
params?: IQueryPrams,
headers?: IHTTPHeaders,
- customConfig?: any
+ customConfig?: any,
) {
return this.request(
{
data,
headers,
- method: 'PATCH',
+ method: "PATCH",
params,
url,
},
- customConfig
+ customConfig,
);
}
@@ -221,17 +221,17 @@ class HTTPService {
data: any,
params?: IQueryPrams,
headers?: IHTTPHeaders,
- customConfig?: any
+ customConfig?: any,
) {
return this.request(
{
data,
headers,
- method: 'PUT',
+ method: "PUT",
params,
url,
},
- customConfig
+ customConfig,
);
}
@@ -243,17 +243,17 @@ class HTTPService {
data: any,
params?: IQueryPrams,
headers?: IHTTPHeaders,
- customConfig?: any
+ customConfig?: any,
) {
return this.request(
{
data,
headers,
- method: 'DELETE',
+ method: "DELETE",
params,
url,
},
- customConfig
+ customConfig,
);
}
}
diff --git a/packages/shared/network/api.ts b/packages/shared/network/api.ts
index e6f62b2c0e..6417157dd5 100644
--- a/packages/shared/network/api.ts
+++ b/packages/shared/network/api.ts
@@ -3,7 +3,7 @@ export const getEndpoint = () => {
if (endpoint) {
return endpoint;
}
- return 'https://api.ente.io';
+ return "https://api.ente.io";
};
export const getFileURL = (id: number) => {
diff --git a/packages/shared/network/cast.ts b/packages/shared/network/cast.ts
index e3e37583fe..82ba61af22 100644
--- a/packages/shared/network/cast.ts
+++ b/packages/shared/network/cast.ts
@@ -1,8 +1,8 @@
-import { ApiError } from '../error';
-import { logError } from '../sentry';
-import { getToken } from '../storage/localStorage/helpers';
-import HTTPService from './HTTPService';
-import { getEndpoint } from './api';
+import { ApiError } from "../error";
+import { logError } from "../sentry";
+import { getToken } from "../storage/localStorage/helpers";
+import HTTPService from "./HTTPService";
+import { getEndpoint } from "./api";
class CastGateway {
constructor() {}
@@ -11,10 +11,10 @@ class CastGateway {
let resp;
try {
resp = await HTTPService.get(
- `${getEndpoint()}/cast/cast-data/${code}`
+ `${getEndpoint()}/cast/cast-data/${code}`,
);
} catch (e) {
- logError(e, 'failed to getCastData');
+ logError(e, "failed to getCastData");
throw e;
}
return resp.data.encCastData;
@@ -24,15 +24,15 @@ class CastGateway {
try {
const token = getToken();
await HTTPService.delete(
- getEndpoint() + '/cast/revoke-all-tokens/',
+ getEndpoint() + "/cast/revoke-all-tokens/",
undefined,
undefined,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
} catch (e) {
- logError(e, 'removeAllTokens failed');
+ logError(e, "removeAllTokens failed");
// swallow error
}
}
@@ -45,21 +45,21 @@ class CastGateway {
`${getEndpoint()}/cast/device-info/${code}`,
undefined,
{
- 'X-Auth-Token': token,
- }
+ "X-Auth-Token": token,
+ },
);
} catch (e) {
if (e instanceof ApiError && e.httpStatusCode === 404) {
- return '';
+ return "";
}
- logError(e, 'failed to getPublicKey');
+ logError(e, "failed to getPublicKey");
throw e;
}
return resp.data.publicKey;
}
public async registerDevice(code: string, publicKey: string) {
- await HTTPService.post(getEndpoint() + '/cast/device-info/', {
+ await HTTPService.post(getEndpoint() + "/cast/device-info/", {
deviceCode: `${code}`,
publicKey: publicKey,
});
@@ -69,11 +69,11 @@ class CastGateway {
code: string,
castPayload: string,
collectionID: number,
- castToken: string
+ castToken: string,
) {
const token = getToken();
await HTTPService.post(
- getEndpoint() + '/cast/cast-data/',
+ getEndpoint() + "/cast/cast-data/",
{
deviceCode: `${code}`,
encPayload: castPayload,
@@ -81,7 +81,7 @@ class CastGateway {
castToken: castToken,
},
undefined,
- { 'X-Auth-Token': token }
+ { "X-Auth-Token": token },
);
}
}
diff --git a/packages/shared/next/pages/404.tsx b/packages/shared/next/pages/404.tsx
index b5fe170f7a..7cc4a6ff09 100644
--- a/packages/shared/next/pages/404.tsx
+++ b/packages/shared/next/pages/404.tsx
@@ -1,9 +1,9 @@
-import { VerticallyCentered } from '@ente/shared/components/Container';
-import React, { useEffect, useState } from 'react';
-import { t } from 'i18next';
+import { VerticallyCentered } from "@ente/shared/components/Container";
+import { t } from "i18next";
+import { useEffect, useState } from "react";
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
-import { PageProps } from '@ente/shared/apps/types';
+import { PageProps } from "@ente/shared/apps/types";
+import EnteSpinner from "@ente/shared/components/EnteSpinner";
export default function NotFound({ appContext }: PageProps) {
const [loading, setLoading] = useState(true);
@@ -13,7 +13,7 @@ export default function NotFound({ appContext }: PageProps) {
}, []);
return (
<VerticallyCentered>
- {loading ? <EnteSpinner /> : t('NOT_FOUND')}
+ {loading ? <EnteSpinner /> : t("NOT_FOUND")}
</VerticallyCentered>
);
}
diff --git a/packages/shared/next/pages/_document.tsx b/packages/shared/next/pages/_document.tsx
index d95f7b4255..1bae450686 100644
--- a/packages/shared/next/pages/_document.tsx
+++ b/packages/shared/next/pages/_document.tsx
@@ -1,17 +1,17 @@
-import React from 'react';
import Document, {
- Html,
+ DocumentContext,
+ DocumentProps,
Head,
+ Html,
Main,
NextScript,
- DocumentProps,
- DocumentContext,
-} from 'next/document';
+} from "next/document";
+import React from "react";
-import createEmotionServer from '@emotion/server/create-instance';
-import { AppType } from 'next/app';
-import createEmotionCache from '@ente/shared/themes/createEmotionCache';
-import { EnteAppProps } from '@ente/shared/apps/types';
+import createEmotionServer from "@emotion/server/create-instance";
+import { EnteAppProps } from "@ente/shared/apps/types";
+import createEmotionCache from "@ente/shared/themes/createEmotionCache";
+import { AppType } from "next/app";
export interface EnteDocumentProps extends DocumentProps {
emotionStyleTags: JSX.Element[];
@@ -76,7 +76,7 @@ EnteDocument.getInitialProps = async (ctx: DocumentContext) => {
enhanceApp: (
App: React.ComponentType<
React.ComponentProps<AppType> & EnteAppProps
- >
+ >,
) =>
function EnhanceApp(props) {
return <App emotionCache={cache} {...props} />;
@@ -89,7 +89,7 @@ EnteDocument.getInitialProps = async (ctx: DocumentContext) => {
const emotionStyles = extractCriticalToChunks(initialProps.html);
const emotionStyleTags = emotionStyles.styles.map((style) => (
<style
- data-emotion={`${style.key} ${style.ids.join(' ')}`}
+ data-emotion={`${style.key} ${style.ids.join(" ")}`}
key={style.key}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: style.css }}
diff --git a/packages/shared/next/pages/_error.tsx b/packages/shared/next/pages/_error.tsx
index 9160c65cf7..c0fc2e39f2 100644
--- a/packages/shared/next/pages/_error.tsx
+++ b/packages/shared/next/pages/_error.tsx
@@ -1,5 +1,5 @@
-import * as Sentry from '@sentry/nextjs';
-import NextErrorComponent from 'next/error';
+import * as Sentry from "@sentry/nextjs";
+import NextErrorComponent from "next/error";
const CustomErrorComponent = (props) => (
<NextErrorComponent statusCode={props.statusCode} />
diff --git a/packages/shared/next/utils/headers.js b/packages/shared/next/utils/headers.js
index 181b7c1474..2c4536fe71 100644
--- a/packages/shared/next/utils/headers.js
+++ b/packages/shared/next/utils/headers.js
@@ -1,40 +1,40 @@
module.exports = {
WEB_SECURITY_HEADERS: {
- 'Strict-Transport-Security': ' max-age=63072000',
- 'X-Content-Type-Options': 'nosniff',
- 'X-Download-Options': 'noopen',
- 'X-Frame-Options': 'deny',
- 'X-XSS-Protection': '1; mode=block',
- 'Referrer-Policy': 'same-origin',
+ "Strict-Transport-Security": " max-age=63072000",
+ "X-Content-Type-Options": "nosniff",
+ "X-Download-Options": "noopen",
+ "X-Frame-Options": "deny",
+ "X-XSS-Protection": "1; mode=block",
+ "Referrer-Policy": "same-origin",
},
CSP_DIRECTIVES: {
// self is safe enough
- 'default-src': "'self'",
+ "default-src": "'self'",
// data to allow two factor qr code
- 'img-src': "'self' blob: data: https://*.openstreetmap.org",
- 'media-src': "'self' blob:",
- 'manifest-src': "'self'",
- 'style-src': "'self' 'unsafe-inline'",
- 'font-src ': "'self'; script-src 'self' 'unsafe-eval' blob:",
- 'connect-src':
+ "img-src": "'self' blob: data: https://*.openstreetmap.org",
+ "media-src": "'self' blob:",
+ "manifest-src": "'self'",
+ "style-src": "'self' 'unsafe-inline'",
+ "font-src ": "'self'; script-src 'self' 'unsafe-eval' blob:",
+ "connect-src":
"'self' https://*.ente.io http://localhost:8080 data: blob: https://ente-prod-eu.s3.eu-central-003.backblazeb2.com https://ente-prod-v3.s3.eu-central-2.wasabisys.com/ https://ente-staging-eu.s3.eu-central-003.backblazeb2.com/ ws://localhost:3000/",
- 'base-uri ': "'self'",
+ "base-uri ": "'self'",
// to allow worker
- 'child-src': "'self' blob:",
- 'object-src': "'none'",
- 'frame-ancestors': " 'none'",
- 'form-action': "'none'",
- 'report-uri': ' https://csp-reporter.ente.io/local',
- 'report-to': ' https://csp-reporter.ente.io/local',
+ "child-src": "'self' blob:",
+ "object-src": "'none'",
+ "frame-ancestors": " 'none'",
+ "form-action": "'none'",
+ "report-uri": " https://csp-reporter.ente.io/local",
+ "report-to": " https://csp-reporter.ente.io/local",
},
- ALL_ROUTES: '/(.*)',
+ ALL_ROUTES: "/(.*)",
buildCSPHeader: (directives) => ({
- 'Content-Security-Policy-Report-Only': Object.entries(
- directives
- ).reduce((acc, [key, value]) => acc + `${key} ${value};`, ''),
+ "Content-Security-Policy-Report-Only": Object.entries(
+ directives,
+ ).reduce((acc, [key, value]) => acc + `${key} ${value};`, ""),
}),
convertToNextHeaderFormat: (headers) =>
diff --git a/packages/shared/platform/index.ts b/packages/shared/platform/index.ts
index 60148c482a..a7a63dd6f4 100644
--- a/packages/shared/platform/index.ts
+++ b/packages/shared/platform/index.ts
@@ -1,11 +1,11 @@
-import isElectron from 'is-electron';
+import isElectron from "is-electron";
export function runningInBrowser() {
- return typeof window !== 'undefined';
+ return typeof window !== "undefined";
}
export function runningInWorker() {
- return typeof importScripts === 'function';
+ return typeof importScripts === "function";
}
export function runningInElectron() {
diff --git a/packages/shared/promise/index.ts b/packages/shared/promise/index.ts
index 849f18d94f..c2434ea594 100644
--- a/packages/shared/promise/index.ts
+++ b/packages/shared/promise/index.ts
@@ -1,14 +1,14 @@
-import { CustomError } from '../error';
+import { CustomError } from "../error";
export const promiseWithTimeout = async <T>(
request: Promise<T>,
- timeout: number
+ timeout: number,
): Promise<T> => {
const timeoutRef = { current: null };
const rejectOnTimeout = new Promise<null>((_, reject) => {
timeoutRef.current = setTimeout(
() => reject(Error(CustomError.WAIT_TIME_EXCEEDED)),
- timeout
+ timeout,
);
});
const requestWithTimeOutCancellation = async () => {
diff --git a/packages/shared/sentry/config/sentry.config.base.ts b/packages/shared/sentry/config/sentry.config.base.ts
index c15798f01d..d37572de69 100644
--- a/packages/shared/sentry/config/sentry.config.base.ts
+++ b/packages/shared/sentry/config/sentry.config.base.ts
@@ -1,8 +1,8 @@
-import * as Sentry from '@sentry/nextjs';
-import { getSentryUserID } from '@ente/shared/sentry/utils';
-import { runningInBrowser } from '@ente/shared/platform';
-import { getHasOptedOutOfCrashReports } from '@ente/shared/storage/localStorage/helpers';
-import { isDevBuild } from '@/utils/env';
+import { isDevBuild } from "@/utils/env";
+import { runningInBrowser } from "@ente/shared/platform";
+import { getSentryUserID } from "@ente/shared/sentry/utils";
+import { getHasOptedOutOfCrashReports } from "@ente/shared/storage/localStorage/helpers";
+import * as Sentry from "@sentry/nextjs";
export const initSentry = async (dsn: string) => {
// Don't initialize Sentry for dev builds
@@ -16,17 +16,17 @@ export const initSentry = async (dsn: string) => {
release: process.env.GIT_SHA,
attachStacktrace: true,
autoSessionTracking: false,
- tunnel: 'https://sentry-reporter.ente.io',
+ tunnel: "https://sentry-reporter.ente.io",
beforeSend(event) {
event.request = event.request || {};
const currentURL = new URL(document.location.href);
- currentURL.hash = '';
+ currentURL.hash = "";
event.request.url = currentURL.href;
return event;
},
integrations: function (i) {
return i.filter(function (i) {
- return i.name !== 'Breadcrumbs';
+ return i.name !== "Breadcrumbs";
});
},
});
diff --git a/packages/shared/sentry/index.ts b/packages/shared/sentry/index.ts
index 154b3b36d2..9279c1134f 100644
--- a/packages/shared/sentry/index.ts
+++ b/packages/shared/sentry/index.ts
@@ -1,18 +1,18 @@
-import * as Sentry from '@sentry/nextjs';
-import { addLocalLog, addLogLine } from '@ente/shared/logging';
+import { ApiError, errorWithContext } from "@ente/shared/error";
+import { addLocalLog, addLogLine } from "@ente/shared/logging";
import {
getSentryUserID,
isErrorUnnecessaryForSentry,
-} from '@ente/shared/sentry/utils';
-import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
-import { getHasOptedOutOfCrashReports } from '@ente/shared/storage/localStorage/helpers';
-import { ApiError, errorWithContext } from '@ente/shared/error';
+} from "@ente/shared/sentry/utils";
+import InMemoryStore, { MS_KEYS } from "@ente/shared/storage/InMemoryStore";
+import { getHasOptedOutOfCrashReports } from "@ente/shared/storage/localStorage/helpers";
+import * as Sentry from "@sentry/nextjs";
export const logError = async (
error: any,
msg: string,
info?: Record<string, unknown>,
- skipAddLogLine = false
+ skipAddLogLine = false,
) => {
const err = errorWithContext(error, msg);
if (!skipAddLogLine) {
@@ -20,14 +20,14 @@ export const logError = async (
addLogLine(`error: ${error?.name} ${error?.message}
msg: ${msg} errorCode: ${JSON.stringify(error?.errCode)}
httpStatusCode: ${JSON.stringify(error?.httpStatusCode)} ${
- info ? `info: ${JSON.stringify(info)}` : ''
+ info ? `info: ${JSON.stringify(info)}` : ""
}
${error?.stack}`);
} else {
addLogLine(
`error: ${error?.name} ${error?.message}
- msg: ${msg} ${info ? `info: ${JSON.stringify(info)}` : ''}
- ${error?.stack}`
+ msg: ${msg} ${info ? `info: ${JSON.stringify(info)}` : ""}
+ ${error?.stack}`,
);
}
}
@@ -35,7 +35,7 @@ export const logError = async (
const optedOutOfCrashReports = getHasOptedOutOfCrashReports();
InMemoryStore.set(
MS_KEYS.OPT_OUT_OF_CRASH_REPORTS,
- optedOutOfCrashReports
+ optedOutOfCrashReports,
);
}
if (InMemoryStore.get(MS_KEYS.OPT_OUT_OF_CRASH_REPORTS)) {
@@ -47,7 +47,7 @@ export const logError = async (
}
Sentry.captureException(err, {
- level: 'info',
+ level: "info",
user: { id: await getSentryUserID() },
contexts: {
...(info && {
diff --git a/packages/shared/sentry/utils.ts b/packages/shared/sentry/utils.ts
index bd2dfcc899..258db570eb 100644
--- a/packages/shared/sentry/utils.ts
+++ b/packages/shared/sentry/utils.ts
@@ -1,11 +1,11 @@
-import { WorkerSafeElectronService } from '@ente/shared/electron/service';
+import { WorkerSafeElectronService } from "@ente/shared/electron/service";
import {
getLocalSentryUserID,
setLocalSentryUserID,
-} from '@ente/shared/storage/localStorage/helpers';
-import isElectron from 'is-electron';
-import { ApiError } from '../error';
-import { HttpStatusCode } from 'axios';
+} from "@ente/shared/storage/localStorage/helpers";
+import { HttpStatusCode } from "axios";
+import isElectron from "is-electron";
+import { ApiError } from "../error";
export async function getSentryUserID() {
if (isElectron()) {
@@ -21,20 +21,20 @@ export async function getSentryUserID() {
}
function makeID(length) {
- let result = '';
+ let result = "";
const characters =
- 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(
- Math.floor(Math.random() * charactersLength)
+ Math.floor(Math.random() * charactersLength),
);
}
return result;
}
export function isErrorUnnecessaryForSentry(error: any) {
- if (error?.message?.includes('Network Error')) {
+ if (error?.message?.includes("Network Error")) {
return true;
} else if (
error instanceof ApiError &&
diff --git a/packages/shared/storage/InMemoryStore.ts b/packages/shared/storage/InMemoryStore.ts
index 82e0155a68..ded73faf05 100644
--- a/packages/shared/storage/InMemoryStore.ts
+++ b/packages/shared/storage/InMemoryStore.ts
@@ -1,7 +1,7 @@
export enum MS_KEYS {
- OPT_OUT_OF_CRASH_REPORTS = 'optOutOfCrashReports',
- SRP_CONFIGURE_IN_PROGRESS = 'srpConfigureInProgress',
- REDIRECT_URL = 'redirectUrl',
+ OPT_OUT_OF_CRASH_REPORTS = "optOutOfCrashReports",
+ SRP_CONFIGURE_IN_PROGRESS = "srpConfigureInProgress",
+ REDIRECT_URL = "redirectUrl",
}
type StoreType = Map<Partial<MS_KEYS>, any>;
diff --git a/packages/shared/storage/cacheStorage/constants.ts b/packages/shared/storage/cacheStorage/constants.ts
index 80e0fecf19..cf88f63a22 100644
--- a/packages/shared/storage/cacheStorage/constants.ts
+++ b/packages/shared/storage/cacheStorage/constants.ts
@@ -1,5 +1,5 @@
export enum CACHES {
- THUMBS = 'thumbs',
- FACE_CROPS = 'face-crops',
- FILES = 'files',
+ THUMBS = "thumbs",
+ FACE_CROPS = "face-crops",
+ FILES = "files",
}
diff --git a/packages/shared/storage/cacheStorage/factory.ts b/packages/shared/storage/cacheStorage/factory.ts
index 2f0ec2ed16..bc4f681a12 100644
--- a/packages/shared/storage/cacheStorage/factory.ts
+++ b/packages/shared/storage/cacheStorage/factory.ts
@@ -1,6 +1,6 @@
-import { LimitedCacheStorage } from './types';
-import { runningInElectron } from '@ente/shared/platform';
-import { WorkerSafeElectronService } from '@ente/shared/electron/service';
+import { WorkerSafeElectronService } from "@ente/shared/electron/service";
+import { runningInElectron } from "@ente/shared/platform";
+import { LimitedCacheStorage } from "./types";
class cacheStorageFactory {
getCacheStorage(): LimitedCacheStorage {
if (runningInElectron()) {
@@ -8,7 +8,7 @@ class cacheStorageFactory {
open(cacheName, cacheLimitInBytes?: number) {
return WorkerSafeElectronService.openDiskCache(
cacheName,
- cacheLimitInBytes
+ cacheLimitInBytes,
);
},
delete(cacheName) {
@@ -24,7 +24,7 @@ class cacheStorageFactory {
export const CacheStorageFactory = new cacheStorageFactory();
function transformBrowserCacheStorageToLimitedCacheStorage(
- caches: CacheStorage
+ caches: CacheStorage,
): LimitedCacheStorage {
return {
async open(cacheName) {
diff --git a/packages/shared/storage/cacheStorage/helpers.ts b/packages/shared/storage/cacheStorage/helpers.ts
index 7ae1026845..b95929106a 100644
--- a/packages/shared/storage/cacheStorage/helpers.ts
+++ b/packages/shared/storage/cacheStorage/helpers.ts
@@ -1,12 +1,12 @@
-import { CACHES } from './constants';
-import { CacheStorageService } from '.';
-import { logError } from '@ente/shared/sentry';
-import { LimitedCache } from './types';
+import { logError } from "@ente/shared/sentry";
+import { CacheStorageService } from ".";
+import { CACHES } from "./constants";
+import { LimitedCache } from "./types";
export async function cached(
cacheName: string,
id: string,
- get: () => Promise<Blob>
+ get: () => Promise<Blob>,
): Promise<Blob> {
const cache = await CacheStorageService.open(cacheName);
const cacheResponse = await cache.match(id);
@@ -21,7 +21,7 @@ export async function cached(
await cache.put(id, new Response(result));
} catch (e) {
// TODO: handle storage full exception.
- console.error('Error while storing file to cache: ', id);
+ console.error("Error while storing file to cache: ", id);
}
}
@@ -32,7 +32,7 @@ let thumbCache: LimitedCache;
export async function getBlobFromCache(
cacheName: string,
- url: string
+ url: string,
): Promise<Blob> {
if (!thumbCache) {
thumbCache = await CacheStorageService.open(cacheName);
@@ -50,6 +50,6 @@ export async function deleteAllCache() {
await CacheStorageService.delete(CACHES.FACE_CROPS);
await CacheStorageService.delete(CACHES.FILES);
} catch (e) {
- logError(e, 'deleteAllCache failed'); // log and ignore
+ logError(e, "deleteAllCache failed"); // log and ignore
}
}
diff --git a/packages/shared/storage/cacheStorage/index.ts b/packages/shared/storage/cacheStorage/index.ts
index 4a38bd93f7..9271ae7f50 100644
--- a/packages/shared/storage/cacheStorage/index.ts
+++ b/packages/shared/storage/cacheStorage/index.ts
@@ -1,13 +1,13 @@
-import { logError } from '@ente/shared/sentry';
-import { CacheStorageFactory } from './factory';
+import { logError } from "@ente/shared/sentry";
+import { CacheStorageFactory } from "./factory";
-const SecurityError = 'SecurityError';
-const INSECURE_OPERATION = 'The operation is insecure.';
+const SecurityError = "SecurityError";
+const INSECURE_OPERATION = "The operation is insecure.";
async function openCache(cacheName: string, cacheLimit?: number) {
try {
return await CacheStorageFactory.getCacheStorage().open(
cacheName,
- cacheLimit
+ cacheLimit,
);
} catch (e) {
// ignoring insecure operation error, as it is thrown in incognito mode in firefox
@@ -15,7 +15,7 @@ async function openCache(cacheName: string, cacheLimit?: number) {
// no-op
} else {
// log and ignore, we don't want to break the caller flow, when cache is not available
- logError(e, 'openCache failed');
+ logError(e, "openCache failed");
}
}
}
@@ -28,7 +28,7 @@ async function deleteCache(cacheName: string) {
// no-op
} else {
// log and ignore, we don't want to break the caller flow, when cache is not available
- logError(e, 'deleteCache failed');
+ logError(e, "deleteCache failed");
}
}
}
diff --git a/packages/shared/storage/cacheStorage/types.ts b/packages/shared/storage/cacheStorage/types.ts
index dc87a70d58..d520559224 100644
--- a/packages/shared/storage/cacheStorage/types.ts
+++ b/packages/shared/storage/cacheStorage/types.ts
@@ -1,7 +1,7 @@
export interface LimitedCacheStorage {
open: (
cacheName: string,
- cacheLimitInBytes?: number
+ cacheLimitInBytes?: number,
) => Promise<LimitedCache>;
delete: (cacheName: string) => Promise<boolean>;
}
@@ -9,7 +9,7 @@ export interface LimitedCacheStorage {
export interface LimitedCache {
match: (
key: string,
- options?: { sizeInBytes?: number }
+ options?: { sizeInBytes?: number },
) => Promise<Response>;
put: (key: string, data: Response) => Promise<void>;
delete: (key: string) => Promise<boolean>;
diff --git a/packages/shared/storage/localForage/helpers.ts b/packages/shared/storage/localForage/helpers.ts
index 69bda598b0..913b9f52f9 100644
--- a/packages/shared/storage/localForage/helpers.ts
+++ b/packages/shared/storage/localForage/helpers.ts
@@ -1,4 +1,4 @@
-import localForage from '.';
+import localForage from ".";
export const clearFiles = async () => {
await localForage.clear();
diff --git a/packages/shared/storage/localForage/index.ts b/packages/shared/storage/localForage/index.ts
index 170d5eb7ac..9ddf80d99e 100644
--- a/packages/shared/storage/localForage/index.ts
+++ b/packages/shared/storage/localForage/index.ts
@@ -1,12 +1,12 @@
-import { runningInBrowser } from '../../platform';
+import { runningInBrowser } from "../../platform";
-import localForage from 'localforage';
+import localForage from "localforage";
if (runningInBrowser()) {
localForage.config({
- name: 'ente-files',
+ name: "ente-files",
version: 1.0,
- storeName: 'files',
+ storeName: "files",
});
}
diff --git a/packages/shared/storage/localStorage/helpers.ts b/packages/shared/storage/localStorage/helpers.ts
index d1e8d50dc3..d8092a56a4 100644
--- a/packages/shared/storage/localStorage/helpers.ts
+++ b/packages/shared/storage/localStorage/helpers.ts
@@ -1,4 +1,4 @@
-import { LS_KEYS, getData, setData } from '.';
+import { LS_KEYS, getData, setData } from ".";
export const getToken = (): string => {
const token = getData(LS_KEYS.USER)?.token;
diff --git a/packages/shared/storage/localStorage/index.ts b/packages/shared/storage/localStorage/index.ts
index 17ecf2c125..e40b644577 100644
--- a/packages/shared/storage/localStorage/index.ts
+++ b/packages/shared/storage/localStorage/index.ts
@@ -1,46 +1,46 @@
-import { logError } from '@ente/shared/sentry';
+import { logError } from "@ente/shared/sentry";
export enum LS_KEYS {
- USER = 'user',
- SESSION = 'session',
- KEY_ATTRIBUTES = 'keyAttributes',
- ORIGINAL_KEY_ATTRIBUTES = 'originalKeyAttributes',
- SUBSCRIPTION = 'subscription',
- FAMILY_DATA = 'familyData',
- PLANS = 'plans',
- IS_FIRST_LOGIN = 'isFirstLogin',
- JUST_SIGNED_UP = 'justSignedUp',
- SHOW_BACK_BUTTON = 'showBackButton',
- EXPORT = 'export',
- AnonymizedUserID = 'anonymizedUserID',
- THUMBNAIL_FIX_STATE = 'thumbnailFixState',
- LIVE_PHOTO_INFO_SHOWN_COUNT = 'livePhotoInfoShownCount',
- LOGS = 'logs',
- USER_DETAILS = 'userDetails',
- COLLECTION_SORT_BY = 'collectionSortBy',
- THEME = 'theme',
- WAIT_TIME = 'waitTime',
- API_ENDPOINT = 'apiEndpoint',
+ USER = "user",
+ SESSION = "session",
+ KEY_ATTRIBUTES = "keyAttributes",
+ ORIGINAL_KEY_ATTRIBUTES = "originalKeyAttributes",
+ SUBSCRIPTION = "subscription",
+ FAMILY_DATA = "familyData",
+ PLANS = "plans",
+ IS_FIRST_LOGIN = "isFirstLogin",
+ JUST_SIGNED_UP = "justSignedUp",
+ SHOW_BACK_BUTTON = "showBackButton",
+ EXPORT = "export",
+ AnonymizedUserID = "anonymizedUserID",
+ THUMBNAIL_FIX_STATE = "thumbnailFixState",
+ LIVE_PHOTO_INFO_SHOWN_COUNT = "livePhotoInfoShownCount",
+ LOGS = "logs",
+ USER_DETAILS = "userDetails",
+ COLLECTION_SORT_BY = "collectionSortBy",
+ THEME = "theme",
+ WAIT_TIME = "waitTime",
+ API_ENDPOINT = "apiEndpoint",
// Moved to the new wrapper @/utils/local-storage
// LOCALE = 'locale',
- MAP_ENABLED = 'mapEnabled',
- SRP_SETUP_ATTRIBUTES = 'srpSetupAttributes',
- SRP_ATTRIBUTES = 'srpAttributes',
- OPT_OUT_OF_CRASH_REPORTS = 'optOutOfCrashReports',
- CF_PROXY_DISABLED = 'cfProxyDisabled',
- REFERRAL_SOURCE = 'referralSource',
- CLIENT_PACKAGE = 'clientPackage',
+ MAP_ENABLED = "mapEnabled",
+ SRP_SETUP_ATTRIBUTES = "srpSetupAttributes",
+ SRP_ATTRIBUTES = "srpAttributes",
+ OPT_OUT_OF_CRASH_REPORTS = "optOutOfCrashReports",
+ CF_PROXY_DISABLED = "cfProxyDisabled",
+ REFERRAL_SOURCE = "referralSource",
+ CLIENT_PACKAGE = "clientPackage",
}
export const setData = (key: LS_KEYS, value: object) => {
- if (typeof localStorage === 'undefined') {
+ if (typeof localStorage === "undefined") {
return null;
}
localStorage.setItem(key, JSON.stringify(value));
};
export const removeData = (key: LS_KEYS) => {
- if (typeof localStorage === 'undefined') {
+ if (typeof localStorage === "undefined") {
return null;
}
localStorage.removeItem(key);
@@ -49,22 +49,22 @@ export const removeData = (key: LS_KEYS) => {
export const getData = (key: LS_KEYS) => {
try {
if (
- typeof localStorage === 'undefined' ||
- typeof key === 'undefined' ||
- typeof localStorage.getItem(key) === 'undefined' ||
- localStorage.getItem(key) === 'undefined'
+ typeof localStorage === "undefined" ||
+ typeof key === "undefined" ||
+ typeof localStorage.getItem(key) === "undefined" ||
+ localStorage.getItem(key) === "undefined"
) {
return null;
}
const data = localStorage.getItem(key);
return data && JSON.parse(data);
} catch (e) {
- logError(e, 'Failed to Parse JSON for key ' + key);
+ logError(e, "Failed to Parse JSON for key " + key);
}
};
export const clearData = () => {
- if (typeof localStorage === 'undefined') {
+ if (typeof localStorage === "undefined") {
return null;
}
localStorage.clear();
diff --git a/packages/shared/storage/sessionStorage/index.ts b/packages/shared/storage/sessionStorage/index.ts
index 4e83e9046a..bbd531d71f 100644
--- a/packages/shared/storage/sessionStorage/index.ts
+++ b/packages/shared/storage/sessionStorage/index.ts
@@ -1,17 +1,17 @@
export enum SESSION_KEYS {
- ENCRYPTION_KEY = 'encryptionKey',
- KEY_ENCRYPTION_KEY = 'keyEncryptionKey',
+ ENCRYPTION_KEY = "encryptionKey",
+ KEY_ENCRYPTION_KEY = "keyEncryptionKey",
}
export const setKey = (key: SESSION_KEYS, value: object) => {
- if (typeof sessionStorage === 'undefined') {
+ if (typeof sessionStorage === "undefined") {
return null;
}
sessionStorage.setItem(key, JSON.stringify(value));
};
export const getKey = (key: SESSION_KEYS) => {
- if (typeof sessionStorage === 'undefined') {
+ if (typeof sessionStorage === "undefined") {
return null;
}
const value = sessionStorage.getItem(key);
@@ -19,14 +19,14 @@ export const getKey = (key: SESSION_KEYS) => {
};
export const removeKey = (key: SESSION_KEYS) => {
- if (typeof sessionStorage === 'undefined') {
+ if (typeof sessionStorage === "undefined") {
return null;
}
sessionStorage.removeItem(key);
};
export const clearKeys = () => {
- if (typeof sessionStorage === 'undefined') {
+ if (typeof sessionStorage === "undefined") {
return null;
}
sessionStorage.clear();
diff --git a/packages/shared/themes/colors/dark.ts b/packages/shared/themes/colors/dark.ts
index 48937bd2a5..05ae67047a 100644
--- a/packages/shared/themes/colors/dark.ts
+++ b/packages/shared/themes/colors/dark.ts
@@ -1,34 +1,34 @@
-import { FixedColors, ThemeColorsOptions } from '@mui/material';
+import { FixedColors, ThemeColorsOptions } from "@mui/material";
const darkThemeColors: Omit<ThemeColorsOptions, keyof FixedColors> = {
background: {
- base: '#000000',
- elevated: '#1b1b1b',
- elevated2: '#252525',
+ base: "#000000",
+ elevated: "#1b1b1b",
+ elevated2: "#252525",
},
backdrop: {
- base: 'rgba(0, 0, 0, 0.90)',
- muted: 'rgba(0, 0, 0, 0.65)',
- faint: 'rgba(0, 0, 0,0.20)',
+ base: "rgba(0, 0, 0, 0.90)",
+ muted: "rgba(0, 0, 0, 0.65)",
+ faint: "rgba(0, 0, 0,0.20)",
},
text: {
- base: '#fff',
- muted: 'rgba(255, 255, 255, 0.70)',
- faint: 'rgba(255, 255, 255, 0.50)',
+ base: "#fff",
+ muted: "rgba(255, 255, 255, 0.70)",
+ faint: "rgba(255, 255, 255, 0.50)",
},
fill: {
- base: '#fff',
- muted: 'rgba(255, 255, 255, 0.16)',
- faint: 'rgba(255, 255, 255, 0.12)',
- basePressed: 'rgba(255, 255, 255, 0.90)',
- faintPressed: 'rgba(255, 255, 255, 0.06)',
- strong: 'rgba(255, 255, 255, 0.32)',
+ base: "#fff",
+ muted: "rgba(255, 255, 255, 0.16)",
+ faint: "rgba(255, 255, 255, 0.12)",
+ basePressed: "rgba(255, 255, 255, 0.90)",
+ faintPressed: "rgba(255, 255, 255, 0.06)",
+ strong: "rgba(255, 255, 255, 0.32)",
},
stroke: {
- base: '#ffffff',
- muted: 'rgba(255,255,255,0.24)',
- faint: 'rgba(255,255,255,0.16)',
- fainter: 'rgba(255,255,255,0.08)',
+ base: "#ffffff",
+ muted: "rgba(255,255,255,0.24)",
+ faint: "rgba(255,255,255,0.16)",
+ fainter: "rgba(255,255,255,0.08)",
},
shadows: {
@@ -37,7 +37,7 @@ const darkThemeColors: Omit<ThemeColorsOptions, keyof FixedColors> = {
x: 0,
y: 2,
blur: 12,
- color: 'rgba(0, 0, 0, 0.75)',
+ color: "rgba(0, 0, 0, 0.75)",
},
],
menu: [
@@ -45,13 +45,13 @@ const darkThemeColors: Omit<ThemeColorsOptions, keyof FixedColors> = {
x: 0,
y: 0,
blur: 6,
- color: 'rgba(0, 0, 0, 0.50)',
+ color: "rgba(0, 0, 0, 0.50)",
},
{
x: 0,
y: 3,
blur: 6,
- color: 'rgba(0, 0, 0, 0.25)',
+ color: "rgba(0, 0, 0, 0.25)",
},
],
button: [
@@ -59,34 +59,34 @@ const darkThemeColors: Omit<ThemeColorsOptions, keyof FixedColors> = {
x: 0,
y: 4,
blur: 4,
- color: 'rgba(0, 0, 0, 0.75)',
+ color: "rgba(0, 0, 0, 0.75)",
},
],
},
avatarColors: [
- '#76549A',
- '#DF7861',
- '#94B49F',
- '#87A2FB',
- '#C689C6',
- '#937DC2',
- '#325288',
- '#85B4E0',
- '#C1A3A3',
- '#E1A059',
- '#426165',
- '#6B77B2',
- '#957FEF',
- '#DD9DE2',
- '#82AB8B',
- '#9BBBE8',
- '#8FBEBE',
- '#8AC3A1',
- '#A8B0F2',
- '#B0C695',
- '#E99AAD',
- '#D18484',
- '#78B5A7',
+ "#76549A",
+ "#DF7861",
+ "#94B49F",
+ "#87A2FB",
+ "#C689C6",
+ "#937DC2",
+ "#325288",
+ "#85B4E0",
+ "#C1A3A3",
+ "#E1A059",
+ "#426165",
+ "#6B77B2",
+ "#957FEF",
+ "#DD9DE2",
+ "#82AB8B",
+ "#9BBBE8",
+ "#8FBEBE",
+ "#8AC3A1",
+ "#A8B0F2",
+ "#B0C695",
+ "#E99AAD",
+ "#D18484",
+ "#78B5A7",
],
};
diff --git a/packages/shared/themes/colors/fixed.ts b/packages/shared/themes/colors/fixed.ts
index bc523cdfb0..aeef14ba79 100644
--- a/packages/shared/themes/colors/fixed.ts
+++ b/packages/shared/themes/colors/fixed.ts
@@ -1,8 +1,8 @@
-import { FixedColors, ThemeColorsOptions } from '@mui/material';
-import { APPS } from '@ente/shared/apps/constants';
+import { APPS } from "@ente/shared/apps/constants";
+import { FixedColors, ThemeColorsOptions } from "@mui/material";
export const getFixesColors = (
- appName: APPS
+ appName: APPS,
): Pick<ThemeColorsOptions, keyof FixedColors> => {
switch (appName) {
case APPS.AUTH:
@@ -21,19 +21,19 @@ export const getFixesColors = (
const commonFixedColors: Partial<Pick<ThemeColorsOptions, keyof FixedColors>> =
{
accent: {
- A700: '#00B33C',
- A500: '#1DB954',
- A400: '#26CB5F',
- A300: '#01DE4D',
+ A700: "#00B33C",
+ A500: "#1DB954",
+ A400: "#26CB5F",
+ A300: "#01DE4D",
},
warning: {
- A500: '#FFC247',
+ A500: "#FFC247",
},
danger: {
- A800: '#F53434',
- A700: '#EA3F3F',
- A500: '#FF6565',
- A400: '#FF6F6F',
+ A800: "#F53434",
+ A700: "#EA3F3F",
+ A500: "#FF6565",
+ A400: "#FF6F6F",
},
blur: {
base: 96,
@@ -41,20 +41,20 @@ const commonFixedColors: Partial<Pick<ThemeColorsOptions, keyof FixedColors>> =
faint: 24,
},
- white: { base: '#fff', muted: 'rgba(255, 255, 255, 0.48)' },
- black: { base: '#000', muted: 'rgba(0, 0, 0, 0.65)' },
+ white: { base: "#fff", muted: "rgba(255, 255, 255, 0.48)" },
+ black: { base: "#000", muted: "rgba(0, 0, 0, 0.65)" },
};
const authAccentColor = {
- A700: 'rgb(164, 0, 182)',
- A500: 'rgb(150, 13, 214)',
- A400: 'rgb(122, 41, 193)',
- A300: 'rgb(152, 77, 244)',
+ A700: "rgb(164, 0, 182)",
+ A500: "rgb(150, 13, 214)",
+ A400: "rgb(122, 41, 193)",
+ A300: "rgb(152, 77, 244)",
};
const photosAccentColor = {
- A700: '#00B33C',
- A500: '#1DB954',
- A400: '#26CB5F',
- A300: '#01DE4D',
+ A700: "#00B33C",
+ A500: "#1DB954",
+ A400: "#26CB5F",
+ A300: "#01DE4D",
};
diff --git a/packages/shared/themes/colors/index.ts b/packages/shared/themes/colors/index.ts
index d8e4705cb9..76d7936306 100644
--- a/packages/shared/themes/colors/index.ts
+++ b/packages/shared/themes/colors/index.ts
@@ -1,13 +1,13 @@
-import { ThemeColorsOptions } from '@mui/material';
-import { THEME_COLOR } from '../constants';
-import darkThemeColors from './dark';
-import lightThemeColors from './light';
-import { APPS } from '@ente/shared/apps/constants';
-import { getFixesColors } from './fixed';
+import { APPS } from "@ente/shared/apps/constants";
+import { ThemeColorsOptions } from "@mui/material";
+import { THEME_COLOR } from "../constants";
+import darkThemeColors from "./dark";
+import { getFixesColors } from "./fixed";
+import lightThemeColors from "./light";
export const getColors = (
themeColor: THEME_COLOR,
- appName: APPS
+ appName: APPS,
): ThemeColorsOptions => {
switch (themeColor) {
case THEME_COLOR.LIGHT:
diff --git a/packages/shared/themes/colors/light.ts b/packages/shared/themes/colors/light.ts
index 621d4ab883..98a1d9c87b 100644
--- a/packages/shared/themes/colors/light.ts
+++ b/packages/shared/themes/colors/light.ts
@@ -1,50 +1,50 @@
-import { FixedColors, ThemeColorsOptions } from '@mui/material';
+import { FixedColors, ThemeColorsOptions } from "@mui/material";
const lightThemeColors: Omit<ThemeColorsOptions, keyof FixedColors> = {
background: {
- base: '#fff',
- elevated: '#fff',
- elevated2: 'rgba(153, 153, 153, 0.04)',
+ base: "#fff",
+ elevated: "#fff",
+ elevated2: "rgba(153, 153, 153, 0.04)",
},
backdrop: {
- base: 'rgba(255, 255, 255, 0.92)',
- muted: 'rgba(255, 255, 255, 0.75)',
- faint: 'rgba(255, 255, 255, 0.30)',
+ base: "rgba(255, 255, 255, 0.92)",
+ muted: "rgba(255, 255, 255, 0.75)",
+ faint: "rgba(255, 255, 255, 0.30)",
},
text: {
- base: '#000',
- muted: 'rgba(0, 0, 0, 0.60)',
- faint: 'rgba(0, 0, 0, 0.50)',
+ base: "#000",
+ muted: "rgba(0, 0, 0, 0.60)",
+ faint: "rgba(0, 0, 0, 0.50)",
},
fill: {
- base: '#000',
- muted: 'rgba(0, 0, 0, 0.12)',
- faint: 'rgba(0, 0, 0, 0.04)',
- basePressed: 'rgba(0, 0, 0, 0.87))',
- faintPressed: 'rgba(0, 0, 0, 0.08)',
- strong: 'rgba(0, 0, 0, 0.24)',
+ base: "#000",
+ muted: "rgba(0, 0, 0, 0.12)",
+ faint: "rgba(0, 0, 0, 0.04)",
+ basePressed: "rgba(0, 0, 0, 0.87))",
+ faintPressed: "rgba(0, 0, 0, 0.08)",
+ strong: "rgba(0, 0, 0, 0.24)",
},
stroke: {
- base: '#000',
- muted: 'rgba(0, 0, 0, 0.24)',
- faint: 'rgba(0, 0, 0, 0.12)',
- fainter: 'rgba(0, 0, 0, 0.06)',
+ base: "#000",
+ muted: "rgba(0, 0, 0, 0.24)",
+ faint: "rgba(0, 0, 0, 0.12)",
+ fainter: "rgba(0, 0, 0, 0.06)",
},
shadows: {
- float: [{ x: 0, y: 0, blur: 10, color: 'rgba(0, 0, 0, 0.25)' }],
+ float: [{ x: 0, y: 0, blur: 10, color: "rgba(0, 0, 0, 0.25)" }],
menu: [
{
x: 0,
y: 0,
blur: 6,
- color: 'rgba(0, 0, 0, 0.16)',
+ color: "rgba(0, 0, 0, 0.16)",
},
{
x: 0,
y: 3,
blur: 6,
- color: 'rgba(0, 0, 0, 0.12)',
+ color: "rgba(0, 0, 0, 0.12)",
},
],
button: [
@@ -52,34 +52,34 @@ const lightThemeColors: Omit<ThemeColorsOptions, keyof FixedColors> = {
x: 0,
y: 4,
blur: 4,
- color: 'rgba(0, 0, 0, 0.25)',
+ color: "rgba(0, 0, 0, 0.25)",
},
],
},
avatarColors: [
- '#76549A',
- '#DF7861',
- '#94B49F',
- '#87A2FB',
- '#C689C6',
- '#937DC2',
- '#325288',
- '#85B4E0',
- '#C1A3A3',
- '#E1A059',
- '#426165',
- '#6B77B2',
- '#957FEF',
- '#DD9DE2',
- '#82AB8B',
- '#9BBBE8',
- '#8FBEBE',
- '#8AC3A1',
- '#A8B0F2',
- '#B0C695',
- '#E99AAD',
- '#D18484',
- '#78B5A7',
+ "#76549A",
+ "#DF7861",
+ "#94B49F",
+ "#87A2FB",
+ "#C689C6",
+ "#937DC2",
+ "#325288",
+ "#85B4E0",
+ "#C1A3A3",
+ "#E1A059",
+ "#426165",
+ "#6B77B2",
+ "#957FEF",
+ "#DD9DE2",
+ "#82AB8B",
+ "#9BBBE8",
+ "#8FBEBE",
+ "#8AC3A1",
+ "#A8B0F2",
+ "#B0C695",
+ "#E99AAD",
+ "#D18484",
+ "#78B5A7",
],
};
diff --git a/packages/shared/themes/components.ts b/packages/shared/themes/components.ts
index f5570fcf5c..10e122fe28 100644
--- a/packages/shared/themes/components.ts
+++ b/packages/shared/themes/components.ts
@@ -1,17 +1,17 @@
-import { Shadow, ThemeColorsOptions } from '@mui/material';
-import { Components } from '@mui/material/styles/components';
-import { TypographyOptions } from '@mui/material/styles/createTypography';
+import { Shadow, ThemeColorsOptions } from "@mui/material";
+import { Components } from "@mui/material/styles/components";
+import { TypographyOptions } from "@mui/material/styles/createTypography";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export const getComponents = (
colors: ThemeColorsOptions,
- typography: TypographyOptions
+ typography: TypographyOptions,
): Components => ({
MuiCssBaseline: {
styleOverrides: {
body: {
fontFamily: typography.fontFamily,
- letterSpacing: '-0.011em',
+ letterSpacing: "-0.011em",
},
strong: { fontWeight: 700 },
},
@@ -19,13 +19,13 @@ export const getComponents = (
MuiTypography: {
defaultProps: {
- variant: 'body',
+ variant: "body",
variantMapping: {
- large: 'p',
- body: 'p',
- small: 'p',
- mini: 'p',
- tiny: 'p',
+ large: "p",
+ body: "p",
+ small: "p",
+ mini: "p",
+ tiny: "p",
},
},
},
@@ -33,7 +33,7 @@ export const getComponents = (
MuiDrawer: {
styleOverrides: {
root: {
- '.MuiBackdrop-root': {
+ ".MuiBackdrop-root": {
backgroundColor: colors.backdrop.faint,
},
},
@@ -42,44 +42,44 @@ export const getComponents = (
MuiDialog: {
styleOverrides: {
root: {
- '.MuiBackdrop-root': {
+ ".MuiBackdrop-root": {
backgroundColor: colors.backdrop.faint,
},
- '& .MuiDialog-paper': {
+ "& .MuiDialog-paper": {
filter: getDropShadowStyle(colors.shadows.float),
},
- '& .MuiDialogTitle-root': {
- padding: '16px',
+ "& .MuiDialogTitle-root": {
+ padding: "16px",
},
- '& .MuiDialogContent-root': {
- padding: '16px',
- overflowY: 'overlay',
+ "& .MuiDialogContent-root": {
+ padding: "16px",
+ overflowY: "overlay",
},
- '& .MuiDialogActions-root': {
- padding: '16px',
+ "& .MuiDialogActions-root": {
+ padding: "16px",
},
- '.MuiDialogTitle-root + .MuiDialogContent-root': {
- paddingTop: '16px',
+ ".MuiDialogTitle-root + .MuiDialogContent-root": {
+ paddingTop: "16px",
},
},
},
defaultProps: {
fullWidth: true,
- maxWidth: 'sm',
+ maxWidth: "sm",
},
},
MuiPaper: {
- styleOverrides: { root: { backgroundImage: 'none' } },
+ styleOverrides: { root: { backgroundImage: "none" } },
},
MuiLink: {
defaultProps: {
color: colors.accent.A500,
- underline: 'none',
+ underline: "none",
},
styleOverrides: {
root: {
- '&:hover': {
- underline: 'always',
+ "&:hover": {
+ underline: "always",
color: colors.accent.A500,
},
},
@@ -88,40 +88,40 @@ export const getComponents = (
MuiButton: {
defaultProps: {
- variant: 'contained',
+ variant: "contained",
},
styleOverrides: {
root: {
- padding: '12px 16px',
- borderRadius: '4px',
- textTransform: 'none',
- fontWeight: 'bold',
+ padding: "12px 16px",
+ borderRadius: "4px",
+ textTransform: "none",
+ fontWeight: "bold",
fontSize: typography.body.fontSize,
lineHeight: typography.body.lineHeight,
},
startIcon: {
- marginRight: '12px',
- '&& >svg': {
- fontSize: '20px',
+ marginRight: "12px",
+ "&& >svg": {
+ fontSize: "20px",
},
},
endIcon: {
- marginLeft: '12px',
- '&& >svg': {
- fontSize: '20px',
+ marginLeft: "12px",
+ "&& >svg": {
+ fontSize: "20px",
},
},
sizeLarge: {
- width: '100%',
+ width: "100%",
},
},
},
MuiInputBase: {
styleOverrides: {
formControl: {
- borderRadius: '8px',
- '::before': {
- borderBottom: 'none !important',
+ borderRadius: "8px",
+ "::before": {
+ borderBottom: "none !important",
},
},
},
@@ -129,21 +129,21 @@ export const getComponents = (
MuiFilledInput: {
styleOverrides: {
input: {
- '&:autofill': {
- boxShadow: '#c7fd4f',
+ "&:autofill": {
+ boxShadow: "#c7fd4f",
},
},
},
},
MuiTextField: {
defaultProps: {
- variant: 'filled',
- margin: 'dense',
+ variant: "filled",
+ margin: "dense",
},
styleOverrides: {
root: {
- '& .MuiInputAdornment-root': {
- marginRight: '8px',
+ "& .MuiInputAdornment-root": {
+ marginRight: "8px",
},
},
},
@@ -160,14 +160,14 @@ export const getComponents = (
styleOverrides: {
root: ({ ownerState }) => ({
...getIconColor(ownerState, colors),
- padding: '12px',
+ padding: "12px",
}),
},
},
MuiSnackbar: {
styleOverrides: {
root: {
- borderRadius: '8px',
+ borderRadius: "8px",
},
},
},
@@ -175,7 +175,7 @@ export const getComponents = (
styleOverrides: {
root: {
'&:has(> div[style*="opacity: 0"])': {
- pointerEvents: 'none',
+ pointerEvents: "none",
},
},
},
@@ -184,7 +184,7 @@ export const getComponents = (
styleOverrides: {
// don't reduce opacity of disabled items
root: {
- '&.Mui-disabled': {
+ "&.Mui-disabled": {
opacity: 1,
},
},
@@ -196,18 +196,18 @@ const getDropShadowStyle = (shadows: Shadow[]) => {
return shadows
.map(
(shadow) =>
- `drop-shadow(${shadow.x}px ${shadow.y}px ${shadow.blur}px ${shadow.color})`
+ `drop-shadow(${shadow.x}px ${shadow.y}px ${shadow.blur}px ${shadow.color})`,
)
- .join(' ');
+ .join(" ");
};
function getIconColor(ownerState, colors: ThemeColorsOptions) {
switch (ownerState.color) {
- case 'primary':
+ case "primary":
return {
color: colors.stroke.base,
};
- case 'secondary':
+ case "secondary":
return {
color: colors.stroke.muted,
};
diff --git a/packages/shared/themes/constants.ts b/packages/shared/themes/constants.ts
index df83635142..70e42f235d 100644
--- a/packages/shared/themes/constants.ts
+++ b/packages/shared/themes/constants.ts
@@ -1,4 +1,4 @@
export enum THEME_COLOR {
- LIGHT = 'light',
- DARK = 'dark',
+ LIGHT = "light",
+ DARK = "dark",
}
diff --git a/packages/shared/themes/createEmotionCache.ts b/packages/shared/themes/createEmotionCache.ts
index 1bd96f8500..216e285f6c 100644
--- a/packages/shared/themes/createEmotionCache.ts
+++ b/packages/shared/themes/createEmotionCache.ts
@@ -1,6 +1,6 @@
-import createCache from '@emotion/cache';
+import createCache from "@emotion/cache";
-const isBrowser = typeof document !== 'undefined';
+const isBrowser = typeof document !== "undefined";
// On the client side, Create a meta tag at the top of the <head> and set it as insertionPoint.
// This assures that MUI styles are loaded first.
@@ -10,10 +10,10 @@ export default function createEmotionCache() {
if (isBrowser) {
const emotionInsertionPoint = document.querySelector<HTMLMetaElement>(
- 'meta[name="emotion-insertion-point"]'
+ 'meta[name="emotion-insertion-point"]',
);
insertionPoint = emotionInsertionPoint ?? undefined;
}
- return createCache({ key: 'mui-style', insertionPoint });
+ return createCache({ key: "mui-style", insertionPoint });
}
diff --git a/packages/shared/themes/index.ts b/packages/shared/themes/index.ts
index ef79241657..bedaa706e0 100644
--- a/packages/shared/themes/index.ts
+++ b/packages/shared/themes/index.ts
@@ -1,10 +1,10 @@
-import { createTheme } from '@mui/material';
-import { THEME_COLOR } from './constants';
-import { getColors } from './colors';
-import { getComponents } from './components';
-import { getPallette } from './palette';
-import { typography } from './typography';
-import { APPS } from '@ente/shared/apps/constants';
+import { APPS } from "@ente/shared/apps/constants";
+import { createTheme } from "@mui/material";
+import { getColors } from "./colors";
+import { getComponents } from "./components";
+import { THEME_COLOR } from "./constants";
+import { getPallette } from "./palette";
+import { typography } from "./typography";
export const getTheme = (themeColor: THEME_COLOR, appName: APPS) => {
const colors = getColors(themeColor, appName);
diff --git a/packages/shared/themes/mui-theme.d.ts b/packages/shared/themes/mui-theme.d.ts
index be03a6d0c2..97d2066125 100644
--- a/packages/shared/themes/mui-theme.d.ts
+++ b/packages/shared/themes/mui-theme.d.ts
@@ -1,7 +1,7 @@
-import { PaletteColor, PaletteColorOptions } from '@mui/material';
-import React from 'react';
+import { PaletteColor, PaletteColorOptions } from "@mui/material";
+import React from "react";
-declare module '@mui/material/styles' {
+declare module "@mui/material/styles" {
interface Theme {
colors: ThemeColors;
}
@@ -42,7 +42,7 @@ declare module '@mui/material/styles' {
}
}
-declare module '@mui/material/Typography' {
+declare module "@mui/material/Typography" {
interface TypographyPropsVariantOverrides {
large: true;
body: true;
@@ -62,7 +62,7 @@ declare module '@mui/material/Typography' {
}
}
-declare module '@mui/material/Button' {
+declare module "@mui/material/Button" {
interface ButtonPropsColorOverrides {
accent: true;
critical: true;
@@ -72,26 +72,26 @@ declare module '@mui/material/Button' {
warning: false;
}
}
-declare module '@mui/material/Checkbox' {
+declare module "@mui/material/Checkbox" {
interface CheckboxPropsColorOverrides {
accent: true;
critical: true;
}
}
-declare module '@mui/material/Switch' {
+declare module "@mui/material/Switch" {
interface SwitchPropsColorOverrides {
accent: true;
}
}
-declare module '@mui/material/SvgIcon' {
+declare module "@mui/material/SvgIcon" {
interface SvgIconPropsColorOverrides {
accent: true;
}
}
-declare module '@mui/material/CircularProgress' {
+declare module "@mui/material/CircularProgress" {
interface CircularProgressPropsColorOverrides {
accent: true;
}
@@ -101,7 +101,7 @@ declare module '@mui/material/CircularProgress' {
// Custom Interfaces
// =================================================
-declare module '@mui/material/styles' {
+declare module "@mui/material/styles" {
interface ThemeColors {
background: BackgroundType;
backdrop: Strength;
@@ -113,8 +113,8 @@ declare module '@mui/material/styles' {
warning: ColorStrength;
danger: ColorStrength;
blur: BlurStrength;
- white: Omit<Strength, 'faint'>;
- black: Omit<Strength, 'faint'>;
+ white: Omit<Strength, "faint">;
+ black: Omit<Strength, "faint">;
avatarColors: AvatarColors;
}
@@ -129,8 +129,8 @@ declare module '@mui/material/styles' {
warning?: Partial<ColorStrength>;
danger?: Partial<ColorStrength>;
blur?: Partial<BlurStrength>;
- white?: Partial<Omit<Strength, 'faint'>>;
- black?: Partial<Omit<Strength, 'faint'>>;
+ white?: Partial<Omit<Strength, "faint">>;
+ black?: Partial<Omit<Strength, "faint">>;
avatarColors?: Partial<AvatarColors>;
}
diff --git a/packages/shared/themes/palette/index.tsx b/packages/shared/themes/palette/index.tsx
index db89766648..e17ec80ea3 100644
--- a/packages/shared/themes/palette/index.tsx
+++ b/packages/shared/themes/palette/index.tsx
@@ -1,29 +1,29 @@
-import { PaletteOptions, ThemeColorsOptions } from '@mui/material';
-import { THEME_COLOR } from '../constants';
+import { PaletteOptions, ThemeColorsOptions } from "@mui/material";
+import { THEME_COLOR } from "../constants";
export const getPallette = (
themeColor: THEME_COLOR,
- colors: ThemeColorsOptions
+ colors: ThemeColorsOptions,
): PaletteOptions => {
const paletteOptions = getPalletteOptions(themeColor, colors);
switch (themeColor) {
case THEME_COLOR.LIGHT:
- return { mode: 'light', ...paletteOptions };
+ return { mode: "light", ...paletteOptions };
default:
- return { mode: 'dark', ...paletteOptions };
+ return { mode: "dark", ...paletteOptions };
}
};
export const getPalletteOptions = (
themeColor: THEME_COLOR,
- colors: ThemeColorsOptions
+ colors: ThemeColorsOptions,
): PaletteOptions => {
return {
primary: {
main: colors.fill.base,
dark: colors.fill.basePressed,
contrastText:
- themeColor === 'dark' ? colors.black.base : colors.white.base,
+ themeColor === "dark" ? colors.black.base : colors.white.base,
},
secondary: {
main: colors.fill.faint,
diff --git a/packages/shared/themes/types.ts b/packages/shared/themes/types.ts
index 10d2c989a8..7b89964292 100644
--- a/packages/shared/themes/types.ts
+++ b/packages/shared/themes/types.ts
@@ -1,3 +1,3 @@
-import { THEME_COLOR } from './constants';
+import { THEME_COLOR } from "./constants";
export type SetTheme = React.Dispatch<React.SetStateAction<THEME_COLOR>>;
diff --git a/packages/shared/themes/typography.ts b/packages/shared/themes/typography.ts
index 20c5a8b8cf..4a7a7f0952 100644
--- a/packages/shared/themes/typography.ts
+++ b/packages/shared/themes/typography.ts
@@ -1,37 +1,37 @@
-import { TypographyOptions } from '@mui/material/styles/createTypography';
+import { TypographyOptions } from "@mui/material/styles/createTypography";
export const typography: TypographyOptions = {
h1: {
- fontSize: '48px',
- lineHeight: '58px',
+ fontSize: "48px",
+ lineHeight: "58px",
},
h2: {
- fontSize: '32px',
- lineHeight: '39px',
+ fontSize: "32px",
+ lineHeight: "39px",
},
h3: {
- fontSize: '24px',
- lineHeight: '29px',
+ fontSize: "24px",
+ lineHeight: "29px",
},
large: {
- fontSize: '18px',
- lineHeight: '22px',
+ fontSize: "18px",
+ lineHeight: "22px",
},
body: {
- fontSize: '16px',
- lineHeight: '20px',
+ fontSize: "16px",
+ lineHeight: "20px",
},
small: {
- fontSize: '14px',
- lineHeight: '17px',
+ fontSize: "14px",
+ lineHeight: "17px",
},
mini: {
- fontSize: '12px',
- lineHeight: '15px',
+ fontSize: "12px",
+ lineHeight: "15px",
},
tiny: {
- fontSize: '10px',
- lineHeight: '12px',
+ fontSize: "10px",
+ lineHeight: "12px",
},
- fontFamily: ['Inter', 'sans-serif'].join(','),
+ fontFamily: ["Inter", "sans-serif"].join(","),
};
diff --git a/packages/shared/time/format.ts b/packages/shared/time/format.ts
index 59caefa807..0e2dc68b52 100644
--- a/packages/shared/time/format.ts
+++ b/packages/shared/time/format.ts
@@ -1,30 +1,30 @@
-import i18n, { t } from 'i18next';
+import i18n, { t } from "i18next";
const dateTimeFullFormatter1 = new Intl.DateTimeFormat(i18n.language, {
- weekday: 'short',
- month: 'short',
- day: 'numeric',
+ weekday: "short",
+ month: "short",
+ day: "numeric",
});
const dateTimeFullFormatter2 = new Intl.DateTimeFormat(i18n.language, {
- year: 'numeric',
+ year: "numeric",
});
const dateTimeShortFormatter = new Intl.DateTimeFormat(i18n.language, {
- month: 'short',
- day: 'numeric',
- year: 'numeric',
- hour: '2-digit',
- minute: '2-digit',
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
});
const timeFormatter = new Intl.DateTimeFormat(i18n.language, {
- timeStyle: 'short',
+ timeStyle: "short",
});
export function formatDateFull(date: number | Date) {
return [dateTimeFullFormatter1, dateTimeFullFormatter2]
.map((f) => f.format(date))
- .join(' ');
+ .join(" ");
}
export function formatDate(date: number | Date) {
@@ -34,7 +34,7 @@ export function formatDate(date: number | Date) {
return [dateTimeFullFormatter1, dateTimeFormat2]
.filter((f) => !!f)
.map((f) => f.format(date))
- .join(' ');
+ .join(" ");
}
export function formatDateTimeShort(date: number | Date) {
@@ -46,11 +46,11 @@ export function formatTime(date: number | Date) {
}
export function formatDateTimeFull(dateTime: number | Date): string {
- return [formatDateFull(dateTime), t('at'), formatTime(dateTime)].join(' ');
+ return [formatDateFull(dateTime), t("at"), formatTime(dateTime)].join(" ");
}
export function formatDateTime(dateTime: number | Date): string {
- return [formatDate(dateTime), t('at'), formatTime(dateTime)].join(' ');
+ return [formatDate(dateTime), t("at"), formatTime(dateTime)].join(" ");
}
export function formatDateRelative(date: number) {
@@ -63,16 +63,16 @@ export function formatDateRelative(date: number) {
second: 1000,
};
const relativeDateFormat = new Intl.RelativeTimeFormat(i18n.language, {
- localeMatcher: 'best fit',
- numeric: 'always',
- style: 'long',
+ localeMatcher: "best fit",
+ numeric: "always",
+ style: "long",
});
const elapsed = date - Date.now(); // "Math.abs" accounts for both "past" & "future" scenarios
for (const u in units)
- if (Math.abs(elapsed) > units[u] || u === 'second')
+ if (Math.abs(elapsed) > units[u] || u === "second")
return relativeDateFormat.format(
Math.round(elapsed / units[u]),
- u as Intl.RelativeTimeFormatUnit
+ u as Intl.RelativeTimeFormatUnit,
);
}
diff --git a/packages/shared/time/index.ts b/packages/shared/time/index.ts
index a3b07b2130..d98bc411be 100644
--- a/packages/shared/time/index.ts
+++ b/packages/shared/time/index.ts
@@ -96,16 +96,16 @@ export function tryToParseDateTime(dateTime: string): Date {
if (dateComponent.year?.length === 8 && dateComponent.month?.length === 6) {
// the filename has size 8 consecutive and then 6 consecutive digits
// high possibility that the it is a date in format YYYYMMDD-HHMMSS
- const possibleDateTime = dateComponent.year + '-' + dateComponent.month;
+ const possibleDateTime = dateComponent.year + "-" + dateComponent.month;
return parseDateFromFusedDateString(possibleDateTime);
}
return validateAndGetDateFromComponents(
- convertDateComponentToNumber(dateComponent)
+ convertDateComponentToNumber(dateComponent),
);
}
function getDateComponentsFromSymbolJoinedString(
- dateTime: string
+ dateTime: string,
): DateComponent<string> {
const [year, month, day, hour, minute, second] =
dateTime.match(/\d+/g) ?? [];
@@ -115,7 +115,7 @@ function getDateComponentsFromSymbolJoinedString(
function validateAndGetDateFromComponents(
dateComponent: DateComponent<number>,
- options = { minYear: 1990, maxYear: currentYear + 1 }
+ options = { minYear: 1990, maxYear: currentYear + 1 },
) {
let date = getDateFromComponents(dateComponent);
if (hasTimeValues(dateComponent) && !isTimePartValid(date, dateComponent)) {
@@ -152,7 +152,7 @@ function isDatePartValid(date: Date, dateComponent: DateComponent<number>) {
}
function convertDateComponentToNumber(
- dateComponent: DateComponent<string>
+ dateComponent: DateComponent<string>,
): DateComponent<number> {
return {
year: Number(dateComponent.year),
@@ -180,7 +180,7 @@ function hasTimeValues(dateComponent: DateComponent<number>) {
}
function removeTimeValues(
- dateComponent: DateComponent<number>
+ dateComponent: DateComponent<number>,
): DateComponent<number> {
return { ...dateComponent, hour: 0, minute: 0, second: 0 };
}
diff --git a/packages/shared/user/index.ts b/packages/shared/user/index.ts
index 3e6ddc394d..877f7c97ee 100644
--- a/packages/shared/user/index.ts
+++ b/packages/shared/user/index.ts
@@ -1,19 +1,19 @@
-import { B64EncryptionResult } from '@ente/shared/crypto/types';
-import { CustomError } from '@ente/shared/error';
-import { getKey, SESSION_KEYS } from '@ente/shared/storage/sessionStorage';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
+import ComlinkCryptoWorker from "@ente/shared/crypto";
+import { B64EncryptionResult } from "@ente/shared/crypto/types";
+import { CustomError } from "@ente/shared/error";
+import { getKey, SESSION_KEYS } from "@ente/shared/storage/sessionStorage";
export const getActualKey = async () => {
try {
const encryptionKeyAttributes: B64EncryptionResult = getKey(
- SESSION_KEYS.ENCRYPTION_KEY
+ SESSION_KEYS.ENCRYPTION_KEY,
);
const cryptoWorker = await ComlinkCryptoWorker.getInstance();
const key = await cryptoWorker.decryptB64(
encryptionKeyAttributes.encryptedData,
encryptionKeyAttributes.nonce,
- encryptionKeyAttributes.key
+ encryptionKeyAttributes.key,
);
return key;
} catch (e) {
diff --git a/packages/shared/utils/index.ts b/packages/shared/utils/index.ts
index d65ef43800..1e14b35add 100644
--- a/packages/shared/utils/index.ts
+++ b/packages/shared/utils/index.ts
@@ -6,15 +6,15 @@ export async function sleep(time: number) {
export function downloadAsFile(filename: string, content: string) {
const file = new Blob([content], {
- type: 'text/plain',
+ type: "text/plain",
});
const fileURL = URL.createObjectURL(file);
downloadUsingAnchor(fileURL, filename);
}
export function downloadUsingAnchor(link: string, name: string) {
- const a = document.createElement('a');
- a.style.display = 'none';
+ const a = document.createElement("a");
+ a.style.display = "none";
a.href = link;
a.download = name;
document.body.appendChild(a);
@@ -24,5 +24,5 @@ export function downloadUsingAnchor(link: string, name: string) {
}
export function isPromise<T>(obj: T | Promise<T>): obj is Promise<T> {
- return obj && typeof (obj as any).then === 'function';
+ return obj && typeof (obj as any).then === "function";
}
diff --git a/packages/shared/utils/size.ts b/packages/shared/utils/size.ts
index e1b6b33e48..80ee3906da 100644
--- a/packages/shared/utils/size.ts
+++ b/packages/shared/utils/size.ts
@@ -1,12 +1,12 @@
export function convertBytesToHumanReadable(
bytes: number,
- precision = 2
+ precision = 2,
): string {
if (bytes === 0 || isNaN(bytes)) {
- return '0 MB';
+ return "0 MB";
}
const i = Math.floor(Math.log(bytes) / Math.log(1024));
- const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
- return (bytes / Math.pow(1024, i)).toFixed(precision) + ' ' + sizes[i];
+ const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
+ return (bytes / Math.pow(1024, i)).toFixed(precision) + " " + sizes[i];
}
diff --git a/packages/shared/watchFolder/types.ts b/packages/shared/watchFolder/types.ts
index 8f16ffb390..bea23247ab 100644
--- a/packages/shared/watchFolder/types.ts
+++ b/packages/shared/watchFolder/types.ts
@@ -1,5 +1,5 @@
-import { UPLOAD_STRATEGY } from '@ente/shared/upload/constants';
-import { ElectronFile } from '@ente/shared/upload/types';
+import { UPLOAD_STRATEGY } from "@ente/shared/upload/constants";
+import { ElectronFile } from "@ente/shared/upload/types";
export interface WatchMappingSyncedFile {
path: string;
@@ -16,7 +16,7 @@ export interface WatchMapping {
}
export interface EventQueueItem {
- type: 'upload' | 'trash';
+ type: "upload" | "trash";
folderPath: string;
collectionName?: string;
paths?: string[];
diff --git a/packages/shared/worker/comlinkWorker.ts b/packages/shared/worker/comlinkWorker.ts
index 0148bee0ae..49a1abf943 100644
--- a/packages/shared/worker/comlinkWorker.ts
+++ b/packages/shared/worker/comlinkWorker.ts
@@ -1,7 +1,7 @@
-import { expose, Remote, wrap } from 'comlink';
-import { WorkerSafeElectronClient } from '@ente/shared/electron/worker/client';
-import { addLocalLog } from '@ente/shared/logging';
-import { logError } from '../sentry';
+import { WorkerSafeElectronClient } from "@ente/shared/electron/worker/client";
+import { addLocalLog } from "@ente/shared/logging";
+import { expose, Remote, wrap } from "comlink";
+import { logError } from "../sentry";
export class ComlinkWorker<T extends new () => InstanceType<T>> {
public remote: Promise<Remote<InstanceType<T>>>;
@@ -13,7 +13,7 @@ export class ComlinkWorker<T extends new () => InstanceType<T>> {
this.worker = worker;
this.worker.onerror = (errorEvent) => {
- logError(Error(errorEvent.message), 'Got error event from worker', {
+ logError(Error(errorEvent.message), "Got error event from worker", {
errorEvent: JSON.stringify(errorEvent),
name: this.name,
});
diff --git a/packages/ui/.prettierrc.json b/packages/ui/.prettierrc.json
deleted file mode 100644
index 0a02bcefda..0000000000
--- a/packages/ui/.prettierrc.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "tabWidth": 4
-}
diff --git a/packages/ui/i18n.ts b/packages/ui/i18n.ts
index 29906fdda6..04986fc632 100644
--- a/packages/ui/i18n.ts
+++ b/packages/ui/i18n.ts
@@ -1,16 +1,16 @@
-import i18n from "i18next";
-import { initReactI18next } from "react-i18next";
-import Backend from "i18next-http-backend";
import { isDevBuild } from "@/utils/env";
-import { getUserLocales } from "get-user-locale";
-import { includes } from "@/utils/type-guards";
import {
getLSString,
- setLSString,
removeLSString,
+ setLSString,
} from "@/utils/local-storage";
-import { object, string } from "yup";
import { logError } from "@/utils/logging";
+import { includes } from "@/utils/type-guards";
+import { getUserLocales } from "get-user-locale";
+import i18n from "i18next";
+import Backend from "i18next-http-backend";
+import { initReactI18next } from "react-i18next";
+import { object, string } from "yup";
/**
* List of all {@link SupportedLocale}s.
diff --git a/packages/utils/.prettierrc.json b/packages/utils/.prettierrc.json
deleted file mode 100644
index f657075f0c..0000000000
--- a/packages/utils/.prettierrc.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "tabWidth": 4,
- "plugins": ["prettier-plugin-organize-imports"]
-}