Skip to content

armgit / ente

Public Imported from GitHub
0

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

cleanup complete

Abhinavf199fbac76ce
diff --git a/apps/photos/src/components/AuthenticateUserModal.tsx b/apps/photos/src/components/AuthenticateUserModal.tsx
index 09fb7a96fd..83cf3e9d2d 100644
--- a/apps/photos/src/components/AuthenticateUserModal.tsx
+++ b/apps/photos/src/components/AuthenticateUserModal.tsx
@@ -2,7 +2,7 @@ import React, { useContext, useEffect, useState } from 'react';
import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
import { AppContext } from 'pages/_app';
-import { KeyAttributes, User } from 'types/user';
+import { KeyAttributes, User } from '@ente/shared/user/types';
import VerifyMasterPasswordForm, {
VerifyMasterPasswordFormProps,
} from '@ente/shared/components/VerifyMasterPasswordForm';
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 9c4063ad19..a2bbd4cec5 100644
--- a/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/linkExpiry.tsx
+++ b/apps/photos/src/components/Collections/CollectionShare/publicShare/manage/linkExpiry.tsx
@@ -7,7 +7,7 @@ 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 'utils/time/format';
+import { formatDateTime } from '@ente/shared/time/format';
import Titlebar from 'components/Titlebar';
import MenuItemDivider from 'components/Menu/MenuItemDivider';
import { isLinkExpired } from '../managePublicShare';
diff --git a/apps/photos/src/components/DeleteAccountModal.tsx b/apps/photos/src/components/DeleteAccountModal.tsx
index 79643643b7..79690ecac6 100644
--- a/apps/photos/src/components/DeleteAccountModal.tsx
+++ b/apps/photos/src/components/DeleteAccountModal.tsx
@@ -7,7 +7,7 @@ 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 'constants/urls';
+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';
diff --git a/apps/photos/src/components/ExportFinished.tsx b/apps/photos/src/components/ExportFinished.tsx
index 40944cf7a3..ddc7441a4b 100644
--- a/apps/photos/src/components/ExportFinished.tsx
+++ b/apps/photos/src/components/ExportFinished.tsx
@@ -6,7 +6,7 @@ import {
Typography,
} from '@mui/material';
import { t } from 'i18next';
-import { formatDateTime } from 'utils/time/format';
+import { formatDateTime } from '@ente/shared/time/format';
import { SpaceBetweenFlex } from './Container';
import { formatNumber } from 'utils/number/format';
import ExportPendingList from './ExportPendingList';
diff --git a/apps/photos/src/components/ExportModal.tsx b/apps/photos/src/components/ExportModal.tsx
index a1a3935f1e..fde02145c9 100644
--- a/apps/photos/src/components/ExportModal.tsx
+++ b/apps/photos/src/components/ExportModal.tsx
@@ -28,7 +28,7 @@ import { AppContext } from 'pages/_app';
import { getExportDirectoryDoesNotExistMessage } from 'utils/ui';
import { t } from 'i18next';
import LinkButton from './pages/gallery/LinkButton';
-import { CustomError } from 'utils/error';
+import { CustomError } from '@ente/shared/error';
import { addLogLine } from '@ente/shared/logging';
import { EnteFile } from 'types/file';
diff --git a/apps/photos/src/components/MachineLearning/MLSearchSettings/enableFaceSearch.tsx b/apps/photos/src/components/MachineLearning/MLSearchSettings/enableFaceSearch.tsx
index 7ee0b8b831..778271718e 100644
--- a/apps/photos/src/components/MachineLearning/MLSearchSettings/enableFaceSearch.tsx
+++ b/apps/photos/src/components/MachineLearning/MLSearchSettings/enableFaceSearch.tsx
@@ -10,7 +10,7 @@ import {
} from '@mui/material';
import { EnteDrawer } from 'components/EnteDrawer';
import Titlebar from 'components/Titlebar';
-import { FACE_SEARCH_PRIVACY_POLICY_LINK } from 'constants/urls';
+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';
diff --git a/apps/photos/src/components/MachineLearning/MLSearchSettings/enableMLSearch.tsx b/apps/photos/src/components/MachineLearning/MLSearchSettings/enableMLSearch.tsx
index 9933191c01..0d654b8412 100644
--- a/apps/photos/src/components/MachineLearning/MLSearchSettings/enableMLSearch.tsx
+++ b/apps/photos/src/components/MachineLearning/MLSearchSettings/enableMLSearch.tsx
@@ -1,6 +1,6 @@
import { Stack, Box, Button, Typography } from '@mui/material';
import Titlebar from 'components/Titlebar';
-import { ML_BLOG_LINK } from 'constants/urls';
+import { ML_BLOG_LINK } from '@ente/shared/constants/urls';
import { Trans } from 'react-i18next';
import { t } from 'i18next';
import { openLink } from 'utils/common';
diff --git a/apps/photos/src/components/MachineLearning/MLServiceFileInfoButton.tsx b/apps/photos/src/components/MachineLearning/MLServiceFileInfoButton.tsx
index 0def27ece9..6aaf2095c2 100644
--- a/apps/photos/src/components/MachineLearning/MLServiceFileInfoButton.tsx
+++ b/apps/photos/src/components/MachineLearning/MLServiceFileInfoButton.tsx
@@ -1,7 +1,7 @@
import React, { useState } from 'react';
import { Button, Spinner } from 'react-bootstrap';
import { EnteFile } from 'types/file';
-import { getToken, getUserID } from 'utils/common/key';
+import { getToken, getUserID } from '@ente/shared/storage/localStorage/helpers';
import mlService from '../../services/machineLearning/machineLearningService';
function MLServiceFileInfoButton({
diff --git a/apps/photos/src/components/MachineLearning/MlDebug-disabled.tsx b/apps/photos/src/components/MachineLearning/MlDebug-disabled.tsx
index 19f4e20fbd..9f19af4ae0 100644
--- a/apps/photos/src/components/MachineLearning/MlDebug-disabled.tsx
+++ b/apps/photos/src/components/MachineLearning/MlDebug-disabled.tsx
@@ -43,7 +43,7 @@ export {};
// DEFAULT_ML_SYNC_JOB_CONFIG,
// } from 'constants/machineLearning/config';
// import { exportMlData, importMlData } from 'utils/machineLearning/mldataExport';
-// import { FACE_CROPS_CACHE } from 'constants/cache';
+// import { FACE_CROPS_CACHE } from '@ente/shared/storage/cacheStorage/constants';
// interface TSNEProps {
// mlResult: MLDebugResult;
diff --git a/apps/photos/src/components/MachineLearning/PeopleList.tsx b/apps/photos/src/components/MachineLearning/PeopleList.tsx
index 3348ae31c9..8d2c1d33a7 100644
--- a/apps/photos/src/components/MachineLearning/PeopleList.tsx
+++ b/apps/photos/src/components/MachineLearning/PeopleList.tsx
@@ -8,7 +8,7 @@ import {
import { styled } from '@mui/material';
import { EnteFile } from 'types/file';
import { ImageCacheView } from './ImageViews';
-import { CACHES } from 'constants/cache';
+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';
diff --git a/apps/photos/src/components/PhotoList.tsx b/apps/photos/src/components/PhotoList.tsx
index 7323ab2432..b6114544da 100644
--- a/apps/photos/src/components/PhotoList.tsx
+++ b/apps/photos/src/components/PhotoList.tsx
@@ -17,13 +17,13 @@ import {
IMAGE_CONTAINER_MAX_WIDTH,
} from 'constants/gallery';
import { PublicCollectionGalleryContext } from 'utils/publicCollectionGallery';
-import { ENTE_WEBSITE_LINK } from 'constants/urls';
+import { ENTE_WEBSITE_LINK } from '@ente/shared/constants/urls';
import { convertBytesToHumanReadable } from 'utils/file/size';
import { DeduplicateContext } from 'pages/deduplicate';
import { FlexWrapper } from './Container';
import { Typography } from '@mui/material';
import { GalleryContext } from 'pages/gallery';
-import { formatDate } from 'utils/time/format';
+import { formatDate } from '@ente/shared/time/format';
import { Trans } from 'react-i18next';
import { t } from 'i18next';
import { areFilesWithFileHashSame, hasFileHash } from 'utils/upload';
diff --git a/apps/photos/src/components/PhotoViewer/FileInfo/ExifData.tsx b/apps/photos/src/components/PhotoViewer/FileInfo/ExifData.tsx
index 8aa1b4c74e..d6d704db6d 100644
--- a/apps/photos/src/components/PhotoViewer/FileInfo/ExifData.tsx
+++ b/apps/photos/src/components/PhotoViewer/FileInfo/ExifData.tsx
@@ -5,7 +5,7 @@ import { FileInfoSidebar } from '.';
import Titlebar from 'components/Titlebar';
import { Box } from '@mui/system';
import CopyButton from '@ente/shared/components/CodeBlock/CopyButton';
-import { formatDateTimeFull } from 'utils/time/format';
+import { formatDateTimeFull } from '@ente/shared/time/format';
import { t } from 'i18next';
const ExifItem = styled(Box)`
diff --git a/apps/photos/src/components/PhotoViewer/FileInfo/RenderCreationTime.tsx b/apps/photos/src/components/PhotoViewer/FileInfo/RenderCreationTime.tsx
index f3487f34fa..51c101dc35 100644
--- a/apps/photos/src/components/PhotoViewer/FileInfo/RenderCreationTime.tsx
+++ b/apps/photos/src/components/PhotoViewer/FileInfo/RenderCreationTime.tsx
@@ -5,7 +5,7 @@ import {
changeFileCreationTime,
updateExistingFilePubMetadata,
} from 'utils/file';
-import { formatDate, formatTime } from 'utils/time/format';
+import { formatDate, formatTime } from '@ente/shared/time/format';
import { FlexWrapper } from 'components/Container';
import { logError } from '@ente/shared/sentry';
import EnteDateTimePicker from 'components/EnteDateTimePicker';
diff --git a/apps/photos/src/components/PhotoViewer/FileInfo/index.tsx b/apps/photos/src/components/PhotoViewer/FileInfo/index.tsx
index 8e2a4ac865..0f1e42d219 100644
--- a/apps/photos/src/components/PhotoViewer/FileInfo/index.tsx
+++ b/apps/photos/src/components/PhotoViewer/FileInfo/index.tsx
@@ -5,7 +5,7 @@ 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 'utils/time/format';
+import { formatDate, formatTime } from '@ente/shared/time/format';
import Titlebar from 'components/Titlebar';
import MapBox from './MapBox';
import InfoItem from './InfoItem';
diff --git a/apps/photos/src/components/RecoveryKey/index.tsx b/apps/photos/src/components/RecoveryKey/index.tsx
index d9552ca87e..aed536beb2 100644
--- a/apps/photos/src/components/RecoveryKey/index.tsx
+++ b/apps/photos/src/components/RecoveryKey/index.tsx
@@ -1,6 +1,6 @@
import React, { useContext, useEffect, useState } from 'react';
import { downloadAsFile } from 'utils/file';
-import { getRecoveryKey } from 'utils/crypto';
+import { getRecoveryKey } from '@ente/shared/crypto/helpers';
import CodeBlock from '@ente/shared/components/CodeBlock';
import {
Button,
diff --git a/apps/photos/src/components/Sidebar/HelpSection.tsx b/apps/photos/src/components/Sidebar/HelpSection.tsx
index d3d7ee6e77..9fa47c0039 100644
--- a/apps/photos/src/components/Sidebar/HelpSection.tsx
+++ b/apps/photos/src/components/Sidebar/HelpSection.tsx
@@ -11,7 +11,10 @@ import { openLink } from 'utils/common';
import { EnteMenuItem } from 'components/Menu/EnteMenuItem';
import { Typography } from '@mui/material';
import { GalleryContext } from 'pages/gallery';
-import { DESKTOP_ROADMAP_URL, WEB_ROADMAP_URL } from 'constants/urls';
+import {
+ DESKTOP_ROADMAP_URL,
+ WEB_ROADMAP_URL,
+} from '@ente/shared/constants/urls';
export default function HelpSection() {
const { setDialogMessage } = useContext(AppContext);
diff --git a/apps/photos/src/components/Sidebar/Preferences/index.tsx b/apps/photos/src/components/Sidebar/Preferences/index.tsx
index b3aa562dda..ad158c66ce 100644
--- a/apps/photos/src/components/Sidebar/Preferences/index.tsx
+++ b/apps/photos/src/components/Sidebar/Preferences/index.tsx
@@ -13,7 +13,7 @@ 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 'services/InMemoryStore';
+import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
import { logError } from '@ente/shared/sentry';
export default function Preferences({ open, onClose, onRootClose }) {
diff --git a/apps/photos/src/components/Upload/UploadProgress/dialog.tsx b/apps/photos/src/components/Upload/UploadProgress/dialog.tsx
index 0f5c5bc413..8593525fea 100644
--- a/apps/photos/src/components/Upload/UploadProgress/dialog.tsx
+++ b/apps/photos/src/components/Upload/UploadProgress/dialog.tsx
@@ -10,7 +10,7 @@ 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 'constants/urls';
+import { APP_DOWNLOAD_URL } from '@ente/shared/constants/urls';
import { Trans } from 'react-i18next';
export function UploadProgressDialog() {
diff --git a/apps/photos/src/components/Upload/Uploader.tsx b/apps/photos/src/components/Upload/Uploader.tsx
index 7dc95a720c..ed078551e1 100644
--- a/apps/photos/src/components/Upload/Uploader.tsx
+++ b/apps/photos/src/components/Upload/Uploader.tsx
@@ -19,7 +19,7 @@ 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 'utils/error';
+import { CustomError } from '@ente/shared/error';
import { Collection } from 'types/collection';
import { SetLoading, SetFiles } from 'types/gallery';
import {
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 4528d56701..5be0507b81 100644
--- a/apps/photos/src/components/pages/gallery/PlanSelector/card/index.tsx
+++ b/apps/photos/src/components/pages/gallery/PlanSelector/card/index.tsx
@@ -28,7 +28,7 @@ import PaidSubscriptionPlanSelectorCard from './paid';
import { isPartOfFamily, getTotalFamilyUsage } from 'utils/user/family';
import { Trans } from 'react-i18next';
import { t } from 'i18next';
-import { SUPPORT_EMAIL } from 'constants/urls';
+import { SUPPORT_EMAIL } from '@ente/shared/constants/urls';
interface Props {
closeModal: any;
diff --git a/apps/photos/src/components/pages/gallery/PreviewCard.tsx b/apps/photos/src/components/pages/gallery/PreviewCard.tsx
index 37ec7cd4f4..4231bead2f 100644
--- a/apps/photos/src/components/pages/gallery/PreviewCard.tsx
+++ b/apps/photos/src/components/pages/gallery/PreviewCard.tsx
@@ -12,7 +12,7 @@ import { DeduplicateContext } from 'pages/deduplicate';
import { logError } from '@ente/shared/sentry';
import { Overlay } from 'components/Container';
import { TRASH_SECTION } from 'constants/collection';
-import { formatDateRelative } from 'utils/time/format';
+import { formatDateRelative } from '@ente/shared/time/format';
import {
LoadingThumbnail,
StaticThumbnail,
diff --git a/apps/photos/src/components/pages/sharedAlbum/GoToEnte.tsx b/apps/photos/src/components/pages/sharedAlbum/GoToEnte.tsx
index 0a48db785c..cc28b52091 100644
--- a/apps/photos/src/components/pages/sharedAlbum/GoToEnte.tsx
+++ b/apps/photos/src/components/pages/sharedAlbum/GoToEnte.tsx
@@ -1,4 +1,4 @@
-import { ENTE_WEBSITE_LINK } from 'constants/urls';
+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';
diff --git a/apps/photos/src/constants/billing.ts b/apps/photos/src/constants/billing.ts
index 66883392a9..dfb69a3f9b 100644
--- a/apps/photos/src/constants/billing.ts
+++ b/apps/photos/src/constants/billing.ts
@@ -1,4 +1,4 @@
-import { getPaymentsURL } from 'utils/common/apiUtil';
+import { getPaymentsURL } from '@ente/shared/network/api';
export const getDesktopRedirectURL = () =>
`${getPaymentsURL()}/desktop-redirect`;
diff --git a/apps/photos/src/constants/cache.ts b/apps/photos/src/constants/cache.ts
deleted file mode 100644
index 80e0fecf19..0000000000
--- a/apps/photos/src/constants/cache.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export enum CACHES {
- THUMBS = 'thumbs',
- FACE_CROPS = 'face-crops',
- FILES = 'files',
-}
diff --git a/apps/photos/src/constants/crypto.ts b/apps/photos/src/constants/crypto.ts
deleted file mode 100644
index e39e675030..0000000000
--- a/apps/photos/src/constants/crypto.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export const ENCRYPTION_CHUNK_SIZE = 4 * 1024 * 1024;
-
-export enum PasswordStrength {
- WEAK = 'WEAK',
- MODERATE = 'MODERATE',
- STRONG = 'STRONG',
-}
diff --git a/apps/photos/src/constants/upload.ts b/apps/photos/src/constants/upload.ts
index 1925d5dbd1..dccad9bae6 100644
--- a/apps/photos/src/constants/upload.ts
+++ b/apps/photos/src/constants/upload.ts
@@ -1,4 +1,4 @@
-import { ENCRYPTION_CHUNK_SIZE } from 'constants/crypto';
+import { ENCRYPTION_CHUNK_SIZE } from '@ente/shared/crypto/constants';
import { FILE_TYPE } from 'constants/file';
import {
FileTypeInfo,
diff --git a/apps/photos/src/constants/urls.ts b/apps/photos/src/constants/urls.ts
deleted file mode 100644
index 291704e98f..0000000000
--- a/apps/photos/src/constants/urls.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-export const ENTE_WEBSITE_LINK = 'https://ente.io';
-
-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';
-
-export const SUPPORT_EMAIL = '[email protected]';
-
-export const APP_DOWNLOAD_URL = 'https://ente.io/download/desktop';
-
-export const FEEDBACK_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 DESKTOP_ROADMAP_URL =
- 'https://github.com/ente-io/photos-desktop/issues';
diff --git a/apps/photos/src/pages/404.tsx b/apps/photos/src/pages/404.tsx
index 4eb0ad5121..6d10e4dfb5 100644
--- a/apps/photos/src/pages/404.tsx
+++ b/apps/photos/src/pages/404.tsx
@@ -1,20 +1,17 @@
-import { VerticallyCentered } from 'components/Container';
-import React, { useContext, useEffect, useState } from 'react';
-import { t } from 'i18next';
-
-import { AppContext } from './_app';
-import EnteSpinner from '@ente/shared/components/EnteSpinner';
+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';
export default function NotFound() {
const appContext = useContext(AppContext);
- const [loading, setLoading] = useState(true);
- useEffect(() => {
- appContext.showNavBar(true);
- setLoading(false);
- }, []);
+ const router = useRouter();
return (
- <VerticallyCentered>
- {loading ? <EnteSpinner /> : t('NOT_FOUND')}
- </VerticallyCentered>
+ <NotFoundPage
+ appContext={appContext}
+ router={router}
+ appName={APPS.AUTH}
+ />
);
}
diff --git a/apps/photos/src/pages/_app.tsx b/apps/photos/src/pages/_app.tsx
index f1e4107d81..99a1eef828 100644
--- a/apps/photos/src/pages/_app.tsx
+++ b/apps/photos/src/pages/_app.tsx
@@ -12,7 +12,7 @@ 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 'services/events';
+import { eventBus, Events } from '@ente/shared/events';
import mlWorkManager from 'services/machineLearning/mlWorkManager';
import {
getMLSearchConfig,
diff --git a/apps/photos/src/pages/_document.tsx b/apps/photos/src/pages/_document.tsx
index 97085e2b32..c3686b6be9 100644
--- a/apps/photos/src/pages/_document.tsx
+++ b/apps/photos/src/pages/_document.tsx
@@ -1,110 +1,7 @@
-import React from 'react';
-import Document, {
- Html,
- Head,
- Main,
- NextScript,
- DocumentProps,
- DocumentContext,
-} from 'next/document';
+import DocumentPage, {
+ EnteDocumentProps,
+} from '@ente/shared/next/pages/_document';
-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';
-
-interface EnteDocumentProps extends DocumentProps {
- emotionStyleTags: JSX.Element[];
-}
-
-export default function EnteDocument({ emotionStyleTags }: EnteDocumentProps) {
- return (
- <Html lang="en">
- <Head>
- <meta
- name="description"
- content="ente – end-to-end encrypted cloud with open-source apps"
- />
- <link rel="icon" href="/images/favicon.png" type="image/png" />
- <link rel="manifest" href="manifest.json" />
- <link rel="apple-touch-icon" href="/images/ente/512.png" />
- <meta name="theme-color" content="#111" />
- <link rel="icon" type="image/png" href="/images/favicon.png" />
- <meta name="apple-mobile-web-app-capable" content="yes" />
- <meta
- name="apple-mobile-web-app-status-bar-style"
- content="black"
- />
- {emotionStyleTags}
- </Head>
- <body>
- <Main />
- <NextScript />
- </body>
- </Html>
- );
+export default function Document(props: EnteDocumentProps) {
+ return <DocumentPage {...props} />;
}
-
-// `getInitialProps` belongs to `_document` (instead of `_app`),
-// it's compatible with static-site generation (SSG).
-EnteDocument.getInitialProps = async (ctx: DocumentContext) => {
- // Resolution order
- //
- // On the server:
- // 1. app.getInitialProps
- // 2. page.getInitialProps
- // 3. document.getInitialProps
- // 4. app.render
- // 5. page.render
- // 6. document.render
- //
- // On the server with error:
- // 1. document.getInitialProps
- // 2. app.render
- // 3. page.render
- // 4. document.render
- //
- // On the client
- // 1. app.getInitialProps
- // 2. page.getInitialProps
- // 3. app.render
- // 4. page.render
-
- const originalRenderPage = ctx.renderPage;
-
- // You can consider sharing the same Emotion cache between all the SSR requests to speed up performance.
- // However, be aware that it can have global side effects.
- const cache = createEmotionCache();
- // eslint-disable-next-line @typescript-eslint/unbound-method
- const { extractCriticalToChunks } = createEmotionServer(cache);
-
- ctx.renderPage = () =>
- originalRenderPage({
- enhanceApp: (
- App: React.ComponentType<
- React.ComponentProps<AppType> & EnteAppProps
- >
- ) =>
- function EnhanceApp(props) {
- return <App emotionCache={cache} {...props} />;
- },
- });
-
- const initialProps = await Document.getInitialProps(ctx);
- // This is important. It prevents Emotion to render invalid HTML.
- // See https://github.com/mui/material-ui/issues/26561#issuecomment-855286153
- const emotionStyles = extractCriticalToChunks(initialProps.html);
- const emotionStyleTags = emotionStyles.styles.map((style) => (
- <style
- data-emotion={`${style.key} ${style.ids.join(' ')}`}
- key={style.key}
- // eslint-disable-next-line react/no-danger
- dangerouslySetInnerHTML={{ __html: style.css }}
- />
- ));
-
- return {
- ...initialProps,
- emotionStyleTags,
- };
-};
diff --git a/apps/photos/src/pages/_error.tsx b/apps/photos/src/pages/_error.tsx
index 9160c65cf7..6c068e34b8 100644
--- a/apps/photos/src/pages/_error.tsx
+++ b/apps/photos/src/pages/_error.tsx
@@ -1,17 +1,17 @@
-import * as Sentry from '@sentry/nextjs';
-import NextErrorComponent from 'next/error';
+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';
-const CustomErrorComponent = (props) => (
- <NextErrorComponent statusCode={props.statusCode} />
-);
-
-CustomErrorComponent.getInitialProps = async (contextData) => {
- // In case this is running in a serverless function, await this in order to give Sentry
- // time to send the error before the lambda exits
- await Sentry.captureUnderscoreErrorException(contextData);
-
- // This will contain the status code of the response
- return NextErrorComponent.getInitialProps(contextData);
-};
-
-export default CustomErrorComponent;
+export default function Error() {
+ const appContext = useContext(AppContext);
+ const router = useRouter();
+ return (
+ <ErrorPage
+ appContext={appContext}
+ router={router}
+ appName={APPS.AUTH}
+ />
+ );
+}
diff --git a/apps/photos/src/pages/deduplicate/index.tsx b/apps/photos/src/pages/deduplicate/index.tsx
index 8261aca804..5d8f2de6bc 100644
--- a/apps/photos/src/pages/deduplicate/index.tsx
+++ b/apps/photos/src/pages/deduplicate/index.tsx
@@ -12,7 +12,7 @@ import { syncFiles, trashFiles } from 'services/fileService';
import { EnteFile } from 'types/file';
import { SelectedState } from 'types/gallery';
-import { ApiError } from 'utils/error';
+import { ApiError } from '@ente/shared/error';
import { constructFileToCollectionMap, getSelectedFiles } from 'utils/file';
import {
DeduplicateContextType,
@@ -29,7 +29,7 @@ import EnteSpinner from '@ente/shared/components/EnteSpinner';
import { VerticallyCentered } from 'components/Container';
import Typography from '@mui/material/Typography';
import useMemoSingleThreaded from '@ente/shared/hooks/useMemoSingleThreaded';
-import InMemoryStore, { MS_KEYS } from 'services/InMemoryStore';
+import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
import { HttpStatusCode } from 'axios';
export const DeduplicateContext = createContext<DeduplicateContextType>(
diff --git a/apps/photos/src/pages/gallery/index.tsx b/apps/photos/src/pages/gallery/index.tsx
index d04c826707..bf222ccaf2 100644
--- a/apps/photos/src/pages/gallery/index.tsx
+++ b/apps/photos/src/pages/gallery/index.tsx
@@ -74,7 +74,7 @@ import {
TRASH_SECTION,
} from 'constants/collection';
import { AppContext } from 'pages/_app';
-import { CustomError } from 'utils/error';
+import { CustomError } from '@ente/shared/error';
import { PHOTOS_PAGES as PAGES } from '@ente/shared/constants/pages';
import {
COLLECTION_OPS_TYPE,
@@ -106,14 +106,15 @@ 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 { FamilyData, User } from 'types/user';
+import { User } from '@ente/shared/user/types';
+import { FamilyData } from 'types/user';
import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
import { CenteredFlex } from '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 'utils/common/key';
+import { getToken } from '@ente/shared/storage/localStorage/helpers';
import ExportModal from 'components/ExportModal';
import GalleryEmptyState from 'components/GalleryEmptyState';
import AuthenticateUserModal from 'components/AuthenticateUserModal';
@@ -124,7 +125,7 @@ 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 'services/InMemoryStore';
+import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
import { syncEmbeddings } from 'services/embeddingService';
import { ClipService } from 'services/clipService';
diff --git a/apps/photos/src/pages/index.tsx b/apps/photos/src/pages/index.tsx
index 7ffa532395..08730aef86 100644
--- a/apps/photos/src/pages/index.tsx
+++ b/apps/photos/src/pages/index.tsx
@@ -15,9 +15,9 @@ 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 'utils/crypto';
+import { saveKeyInSessionStore } from '@ente/shared/crypto/helpers';
import { getKey, SESSION_KEYS } from '@ente/shared/storage/sessionStorage';
-import { getAlbumsURL } from 'utils/common/apiUtil';
+import { getAlbumsURL } from '@ente/shared/network/api';
import { Trans } from 'react-i18next';
import { APPS } from '@ente/shared/apps/constants';
diff --git a/apps/photos/src/pages/shared-albums/index.tsx b/apps/photos/src/pages/shared-albums/index.tsx
index e701d1fa7c..8ba0638c9d 100644
--- a/apps/photos/src/pages/shared-albums/index.tsx
+++ b/apps/photos/src/pages/shared-albums/index.tsx
@@ -19,7 +19,7 @@ import { EnteFile } from 'types/file';
import { downloadFile, mergeMetadata, sortFiles } from 'utils/file';
import { AppContext } from 'pages/_app';
import { PublicCollectionGalleryContext } from 'utils/publicCollectionGallery';
-import { CustomError, parseSharingErrorCodes } from 'utils/error';
+import { CustomError, parseSharingErrorCodes } from '@ente/shared/error';
import {
VerticallyCentered,
CenteredFlex,
@@ -57,7 +57,7 @@ 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 'constants/urls';
+import { ENTE_WEBSITE_LINK } from '@ente/shared/constants/urls';
const defaultThumbStore = new Map();
const defaultFileStore = new Map();
diff --git a/apps/photos/src/services/HTTPService.ts b/apps/photos/src/services/HTTPService.ts
deleted file mode 100644
index e6f7945755..0000000000
--- a/apps/photos/src/services/HTTPService.ts
+++ /dev/null
@@ -1,241 +0,0 @@
-import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
-import { addLogLine } from '@ente/shared/logging';
-import { logError } from '@ente/shared/sentry';
-import { ApiError, CustomError, isApiErrorResponse } from 'utils/error';
-
-interface IHTTPHeaders {
- [headerKey: string]: any;
-}
-
-interface IQueryPrams {
- [paramName: string]: any;
-}
-
-/**
- * Service to manage all HTTP calls.
- */
-class HTTPService {
- constructor() {
- axios.interceptors.response.use(
- (response) => Promise.resolve(response),
- (error) => {
- const config = error.config as AxiosRequestConfig;
- if (error.response) {
- const response = error.response as AxiosResponse;
- let apiError: ApiError;
- // The request was made and the server responded with a status code
- // that falls out of the range of 2xx
- if (isApiErrorResponse(response.data)) {
- const responseData = response.data;
- logError(error, 'HTTP Service Error', {
- url: config.url,
- method: config.method,
- xRequestId: response.headers['x-request-id'],
- httpStatus: response.status,
- errMessage: responseData.message,
- errCode: responseData.code,
- });
- apiError = new ApiError(
- responseData.message,
- responseData.code,
- response.status
- );
- } else {
- if (response.status >= 400 && response.status < 500) {
- apiError = new ApiError(
- CustomError.CLIENT_ERROR,
- '',
- response.status
- );
- } else {
- apiError = new ApiError(
- CustomError.ServerError,
- '',
- response.status
- );
- }
- }
- logError(apiError, 'HTTP Service Error', {
- url: config.url,
- method: config.method,
- cfRay: response.headers['cf-ray'],
- xRequestId: response.headers['x-request-id'],
- httpStatus: response.status,
- });
- throw apiError;
- } else if (error.request) {
- // The request was made but no response was received
- // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
- // http.ClientRequest in node.js
- addLogLine(
- 'request failed- no response',
- `url: ${config.url}`,
- `method: ${config.method}`
- );
- return Promise.reject(error);
- } else {
- // Something happened in setting up the request that triggered an Error
- addLogLine(
- 'request failed- axios error',
- `url: ${config.url}`,
- `method: ${config.method}`
- );
- return Promise.reject(error);
- }
- }
- );
- }
-
- /**
- * header object to be append to all api calls.
- */
- private headers: IHTTPHeaders = {
- 'content-type': 'application/json',
- };
-
- /**
- * Sets the headers to the given object.
- */
- public setHeaders(headers: IHTTPHeaders) {
- this.headers = {
- ...this.headers,
- ...headers,
- };
- }
-
- /**
- * Adds a header to list of headers.
- */
- public appendHeader(key: string, value: string) {
- this.headers = {
- ...this.headers,
- [key]: value,
- };
- }
-
- /**
- * Removes the given header.
- */
- public removeHeader(key: string) {
- this.headers[key] = undefined;
- }
-
- /**
- * Returns axios interceptors.
- */
- // eslint-disable-next-line class-methods-use-this
- public getInterceptors() {
- return axios.interceptors;
- }
-
- /**
- * Generic HTTP request.
- * This is done so that developer can use any functionality
- * provided by axios. Here, only the set headers are spread
- * over what was sent in config.
- */
- public async request(config: AxiosRequestConfig, customConfig?: any) {
- // eslint-disable-next-line no-param-reassign
- config.headers = {
- ...this.headers,
- ...config.headers,
- };
- if (customConfig?.cancel) {
- config.cancelToken = new axios.CancelToken(
- (c) => (customConfig.cancel.exec = c)
- );
- }
- return await axios({ ...config, ...customConfig });
- }
-
- /**
- * Get request.
- */
- public get(
- url: string,
- params?: IQueryPrams,
- headers?: IHTTPHeaders,
- customConfig?: any
- ) {
- return this.request(
- {
- headers,
- method: 'GET',
- params,
- url,
- },
- customConfig
- );
- }
-
- /**
- * Post request
- */
- public post(
- url: string,
- data?: any,
- params?: IQueryPrams,
- headers?: IHTTPHeaders,
- customConfig?: any
- ) {
- return this.request(
- {
- data,
- headers,
- method: 'POST',
- params,
- url,
- },
- customConfig
- );
- }
-
- /**
- * Put request
- */
- public put(
- url: string,
- data: any,
- params?: IQueryPrams,
- headers?: IHTTPHeaders,
- customConfig?: any
- ) {
- return this.request(
- {
- data,
- headers,
- method: 'PUT',
- params,
- url,
- },
- customConfig
- );
- }
-
- /**
- * Delete request
- */
- public delete(
- url: string,
- data: any,
- params?: IQueryPrams,
- headers?: IHTTPHeaders,
- customConfig?: any
- ) {
- return this.request(
- {
- data,
- headers,
- method: 'DELETE',
- params,
- url,
- },
- customConfig
- );
- }
-}
-
-// Creates a Singleton Service.
-// This will help me maintain common headers / functionality
-// at a central place.
-export default new HTTPService();
diff --git a/apps/photos/src/services/InMemoryStore.ts b/apps/photos/src/services/InMemoryStore.ts
deleted file mode 100644
index 82e0155a68..0000000000
--- a/apps/photos/src/services/InMemoryStore.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-export enum MS_KEYS {
- OPT_OUT_OF_CRASH_REPORTS = 'optOutOfCrashReports',
- SRP_CONFIGURE_IN_PROGRESS = 'srpConfigureInProgress',
- REDIRECT_URL = 'redirectUrl',
-}
-
-type StoreType = Map<Partial<MS_KEYS>, any>;
-
-class InMemoryStore {
- private store: StoreType = new Map();
-
- get(key: MS_KEYS) {
- return this.store.get(key);
- }
-
- set(key: MS_KEYS, value: any) {
- this.store.set(key, value);
- }
-
- delete(key: MS_KEYS) {
- this.store.delete(key);
- }
-
- has(key: MS_KEYS) {
- return this.store.has(key);
- }
- clear() {
- this.store.clear();
- }
-}
-
-export default new InMemoryStore();
diff --git a/apps/photos/src/services/billingService.ts b/apps/photos/src/services/billingService.ts
index e9f876e82e..ac70df9bdc 100644
--- a/apps/photos/src/services/billingService.ts
+++ b/apps/photos/src/services/billingService.ts
@@ -1,11 +1,11 @@
-import { getEndpoint, getPaymentsURL } from 'utils/common/apiUtil';
-import { getToken } from 'utils/common/key';
+import { getEndpoint, getPaymentsURL } from '@ente/shared/network/api';
+import { getToken } from '@ente/shared/storage/localStorage/helpers';
import {
setData,
LS_KEYS,
removeData,
} from '@ente/shared/storage/localStorage';
-import HTTPService from './HTTPService';
+import HTTPService from '@ente/shared/network/HTTPService';
import { logError } from '@ente/shared/sentry';
import { getPaymentToken } from './userService';
import { Plan, Subscription } from 'types/billing';
diff --git a/apps/photos/src/services/cache/cacheStorageFactory.ts b/apps/photos/src/services/cache/cacheStorageFactory.ts
deleted file mode 100644
index 569206d561..0000000000
--- a/apps/photos/src/services/cache/cacheStorageFactory.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { LimitedCacheStorage } from 'types/cache/index';
-import ElectronAPIs from '@ente/shared/electron';
-import { runningInElectron, runningInWorker } from 'utils/common';
-import { WorkerElectronCacheStorageService } from 'services/workerElectronCache/service';
-
-class cacheStorageFactory {
- workerElectronCacheStorageServiceInstance: WorkerElectronCacheStorageService;
- getCacheStorage(): LimitedCacheStorage {
- if (runningInElectron()) {
- if (runningInWorker()) {
- if (!this.workerElectronCacheStorageServiceInstance) {
- this.workerElectronCacheStorageServiceInstance =
- new WorkerElectronCacheStorageService();
- }
- return this.workerElectronCacheStorageServiceInstance;
- } else {
- return {
- open(cacheName) {
- return ElectronAPIs.openDiskCache(cacheName);
- },
- delete(cacheName) {
- return ElectronAPIs.deleteDiskCache(cacheName);
- },
- };
- }
- } else {
- return transformBrowserCacheStorageToLimitedCacheStorage(caches);
- }
- }
-}
-
-export const CacheStorageFactory = new cacheStorageFactory();
-
-function transformBrowserCacheStorageToLimitedCacheStorage(
- caches: CacheStorage
-): LimitedCacheStorage {
- return {
- async open(cacheName) {
- const cache = await caches.open(cacheName);
- return {
- match: cache.match.bind(cache),
- put: cache.put.bind(cache),
- delete: cache.delete.bind(cache),
- };
- },
- delete: caches.delete.bind(caches),
- };
-}
diff --git a/apps/photos/src/services/cache/cacheStorageService.ts b/apps/photos/src/services/cache/cacheStorageService.ts
deleted file mode 100644
index 87df2063bf..0000000000
--- a/apps/photos/src/services/cache/cacheStorageService.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { logError } from '@ente/shared/sentry';
-import { CacheStorageFactory } from './cacheStorageFactory';
-
-const SecurityError = 'SecurityError';
-const INSECURE_OPERATION = 'The operation is insecure.';
-async function openCache(cacheName: string) {
- try {
- return await CacheStorageFactory.getCacheStorage().open(cacheName);
- } catch (e) {
- // ignoring insecure operation error, as it is thrown in incognito mode in firefox
- if (e.name === SecurityError && e.message === INSECURE_OPERATION) {
- // no-op
- } else {
- // log and ignore, we don't want to break the caller flow, when cache is not available
- logError(e, 'openCache failed');
- }
- }
-}
-async function deleteCache(cacheName: string) {
- try {
- return await CacheStorageFactory.getCacheStorage().delete(cacheName);
- } catch (e) {
- // ignoring insecure operation error, as it is thrown in incognito mode in firefox
- if (e.name === SecurityError && e.message === INSECURE_OPERATION) {
- // no-op
- } else {
- // log and ignore, we don't want to break the caller flow, when cache is not available
- logError(e, 'deleteCache failed');
- }
- }
-}
-
-export const CacheStorageService = { open: openCache, delete: deleteCache };
diff --git a/apps/photos/src/services/clipService.ts b/apps/photos/src/services/clipService.ts
index 2034d5cce0..b125ab350b 100644
--- a/apps/photos/src/services/clipService.ts
+++ b/apps/photos/src/services/clipService.ts
@@ -8,7 +8,7 @@ import downloadManager from './downloadManager';
import { logError } from '@ente/shared/sentry';
import { addLogLine } from '@ente/shared/logging';
import isElectron from 'is-electron';
-import { Events, eventBus } from './events';
+import { Events, eventBus } from '@ente/shared/events';
import PQueue from 'p-queue';
import { EnteFile } from 'types/file';
import ElectronAPIs from '@ente/shared/electron';
diff --git a/apps/photos/src/services/collectionService.ts b/apps/photos/src/services/collectionService.ts
index 46ee68ea8e..a249656dad 100644
--- a/apps/photos/src/services/collectionService.ts
+++ b/apps/photos/src/services/collectionService.ts
@@ -1,13 +1,14 @@
-import { getEndpoint } from 'utils/common/apiUtil';
+import { getEndpoint } from '@ente/shared/network/api';
import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
import localForage from '@ente/shared/storage/localForage';
-import { getActualKey, getToken } from 'utils/common/key';
+import { getToken } from '@ente/shared/storage/localStorage/helpers';
+import { getActualKey } from '@ente/shared/user';
import { getPublicKey } from './userService';
-import HTTPService from './HTTPService';
+import HTTPService from '@ente/shared/network/HTTPService';
import { EnteFile } from 'types/file';
import { logError } from '@ente/shared/sentry';
-import { CustomError } from 'utils/error';
+import { CustomError } from '@ente/shared/error';
import {
sortFiles,
groupFilesBasedOnCollectionID,
@@ -50,7 +51,8 @@ import {
isPinnedCollection,
updateMagicMetadata,
} from 'utils/magicMetadata';
-import { FamilyData, User } from 'types/user';
+import { User } from '@ente/shared/user/types';
+import { FamilyData } from 'types/user';
import {
isQuickLinkCollection,
isOutgoingShare,
diff --git a/apps/photos/src/services/deduplicationService.ts b/apps/photos/src/services/deduplicationService.ts
index b9f1768c2e..137e30a26b 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 'utils/common/apiUtil';
-import { getToken } from 'utils/common/key';
+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 './HTTPService';
+import HTTPService from '@ente/shared/network/HTTPService';
const ENDPOINT = getEndpoint();
diff --git a/apps/photos/src/services/downloadManager.ts b/apps/photos/src/services/downloadManager.ts
index 806df52f3c..fdb4eb3322 100644
--- a/apps/photos/src/services/downloadManager.ts
+++ b/apps/photos/src/services/downloadManager.ts
@@ -1,22 +1,22 @@
-import { getToken } from 'utils/common/key';
-import { getFileURL, getThumbnailURL } from 'utils/common/apiUtil';
+import { getToken } from '@ente/shared/storage/localStorage/helpers';
+import { getFileURL, getThumbnailURL } from '@ente/shared/network/api';
import {
generateStreamFromArrayBuffer,
getRenderableFileURL,
createTypedObjectURL,
} from 'utils/file';
-import HTTPService from './HTTPService';
+import HTTPService from '@ente/shared/network/HTTPService';
import { EnteFile } from 'types/file';
import { logError } from '@ente/shared/sentry';
import { FILE_TYPE } from 'constants/file';
-import { CustomError } from 'utils/error';
+import { CustomError } from '@ente/shared/error';
import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { CacheStorageService } from './cache/cacheStorageService';
-import { CACHES } from 'constants/cache';
+import { CacheStorageService } from '@ente/shared/storage/cacheStorage';
+import { CACHES } from '@ente/shared/storage/cacheStorage/constants';
import { Remote } from 'comlink';
-import { DedicatedCryptoWorker } from 'worker/crypto.worker';
-import { LimitedCache } from 'types/cache';
+import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
+import { LimitedCache } from '@ente/shared/storage/cacheStorage/types';
import { retryAsyncFunction } from 'utils/network';
import { addLogLine } from '@ente/shared/logging';
diff --git a/apps/photos/src/services/embeddingService.ts b/apps/photos/src/services/embeddingService.ts
index 26424cde38..d29746dd12 100644
--- a/apps/photos/src/services/embeddingService.ts
+++ b/apps/photos/src/services/embeddingService.ts
@@ -5,13 +5,13 @@ import {
PutEmbeddingRequest,
} from 'types/embedding';
import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { getEndpoint } from 'utils/common/apiUtil';
+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 './HTTPService';
-import { getToken } from 'utils/common/key';
+import HTTPService from '@ente/shared/network/HTTPService';
+import { getToken } from '@ente/shared/storage/localStorage/helpers';
import { getLatestVersionEmbeddings } from 'utils/embedding';
import { getLocalTrashedFiles } from './trashService';
diff --git a/apps/photos/src/services/entityService.ts b/apps/photos/src/services/entityService.ts
index 9dd078fdf2..2a6e35ad7b 100644
--- a/apps/photos/src/services/entityService.ts
+++ b/apps/photos/src/services/entityService.ts
@@ -1,10 +1,10 @@
-import { getToken } from 'utils/common/key';
+import { getToken } from '@ente/shared/storage/localStorage/helpers';
import localForage from '@ente/shared/storage/localForage';
-import HTTPService from './HTTPService';
-import { getEndpoint } from 'utils/common/apiUtil';
+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 'utils/common/key';
+import { getActualKey } from '@ente/shared/user';
import {
EntityType,
Entity,
diff --git a/apps/photos/src/services/events.ts b/apps/photos/src/services/events.ts
deleted file mode 100644
index 670ecac47c..0000000000
--- a/apps/photos/src/services/events.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-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',
-}
-
-export const eventBus = new EventEmitter<Events>();
diff --git a/apps/photos/src/services/export/index.ts b/apps/photos/src/services/export/index.ts
index fc3142e50d..cc31106703 100644
--- a/apps/photos/src/services/export/index.ts
+++ b/apps/photos/src/services/export/index.ts
@@ -48,12 +48,12 @@ import {
ExportSettings,
ExportUIUpdaters,
} from 'types/export';
-import { User } from 'types/user';
+import { User } from '@ente/shared/user/types';
import { FILE_TYPE } from 'constants/file';
import { ExportStage } from 'constants/export';
-import { CustomError } from 'utils/error';
+import { CustomError } from '@ente/shared/error';
import { addLogLine } from '@ente/shared/logging';
-import { eventBus, Events } from '../events';
+import { eventBus, Events } from '@ente/shared/events';
import {
constructCollectionNameMap,
getCollectionUserFacingName,
diff --git a/apps/photos/src/services/export/migration.ts b/apps/photos/src/services/export/migration.ts
index ca224d9f9e..842e09cde8 100644
--- a/apps/photos/src/services/export/migration.ts
+++ b/apps/photos/src/services/export/migration.ts
@@ -10,7 +10,7 @@ import {
ExportProgress,
} from 'types/export';
import { EnteFile } from 'types/file';
-import { User } from 'types/user';
+import { User } from '@ente/shared/user/types';
import { getNonEmptyPersonalCollections } from 'utils/collection';
import {
getCollectionExportPath,
diff --git a/apps/photos/src/services/fileService.ts b/apps/photos/src/services/fileService.ts
index 1e804172cd..d5c664abad 100644
--- a/apps/photos/src/services/fileService.ts
+++ b/apps/photos/src/services/fileService.ts
@@ -1,9 +1,9 @@
-import { getEndpoint } from 'utils/common/apiUtil';
+import { getEndpoint } from '@ente/shared/network/api';
import localForage from '@ente/shared/storage/localForage';
-import { getToken } from 'utils/common/key';
+import { getToken } from '@ente/shared/storage/localStorage/helpers';
import { Collection } from 'types/collection';
-import HTTPService from './HTTPService';
+import HTTPService from '@ente/shared/network/HTTPService';
import { logError } from '@ente/shared/sentry';
import {
decryptFile,
@@ -11,7 +11,7 @@ import {
mergeMetadata,
sortFiles,
} from 'utils/file';
-import { eventBus, Events } from './events';
+import { eventBus, Events } from '@ente/shared/events';
import {
EnteFile,
EncryptedEnteFile,
diff --git a/apps/photos/src/services/imageProcessor.ts b/apps/photos/src/services/imageProcessor.ts
index 84b78d9013..3a5340233a 100644
--- a/apps/photos/src/services/imageProcessor.ts
+++ b/apps/photos/src/services/imageProcessor.ts
@@ -2,7 +2,7 @@ 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 'utils/error';
+import { CustomError } from '@ente/shared/error';
import { convertBytesToHumanReadable } from 'utils/file/size';
class ElectronImageProcessorService {
diff --git a/apps/photos/src/services/machineLearning/machineLearningFactory.ts b/apps/photos/src/services/machineLearning/machineLearningFactory.ts
index 65ad9c5cb5..c684da73b7 100644
--- a/apps/photos/src/services/machineLearning/machineLearningFactory.ts
+++ b/apps/photos/src/services/machineLearning/machineLearningFactory.ts
@@ -32,7 +32,7 @@ import ssdMobileNetV2Service from './ssdMobileNetV2Service';
import imageSceneService from './imageSceneService';
import { getDedicatedCryptoWorker } from '@ente/shared/crypto';
import { ComlinkWorker } from '@ente/shared/worker/comlinkWorker';
-import { DedicatedCryptoWorker } from 'worker/crypto.worker';
+import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
import { addLogLine } from '@ente/shared/logging';
export class MLFactory {
diff --git a/apps/photos/src/services/machineLearning/machineLearningService.ts b/apps/photos/src/services/machineLearning/machineLearningService.ts
index c28b60f7cd..ffd59144b8 100644
--- a/apps/photos/src/services/machineLearning/machineLearningService.ts
+++ b/apps/photos/src/services/machineLearning/machineLearningService.ts
@@ -24,7 +24,7 @@ import {
import { MLFactory } from './machineLearningFactory';
import mlIDbStorage from 'utils/storage/mlIDbStorage';
import { getMLSyncConfig } from 'utils/machineLearning/config';
-import { CustomError, parseUploadErrorCodes } from 'utils/error';
+import { CustomError, parseUploadErrorCodes } from '@ente/shared/error';
import { MAX_ML_SYNC_ERROR_COUNT } from 'constants/mlConfig';
import FaceService from './faceService';
import PeopleService from './peopleService';
diff --git a/apps/photos/src/services/machineLearning/mlWorkManager.ts b/apps/photos/src/services/machineLearning/mlWorkManager.ts
index b529555d5b..3673744d0c 100644
--- a/apps/photos/src/services/machineLearning/mlWorkManager.ts
+++ b/apps/photos/src/services/machineLearning/mlWorkManager.ts
@@ -1,9 +1,9 @@
import debounce from 'debounce-promise';
import PQueue from 'p-queue';
-import { eventBus, Events } from 'services/events';
+import { eventBus, Events } from '@ente/shared/events';
import { EnteFile } from 'types/file';
import { FILE_TYPE } from 'constants/file';
-import { getToken, getUserID } from 'utils/common/key';
+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';
diff --git a/apps/photos/src/services/migrateThumbnailService.ts b/apps/photos/src/services/migrateThumbnailService.ts
index ed4f27c83b..06830ff749 100644
--- a/apps/photos/src/services/migrateThumbnailService.ts
+++ b/apps/photos/src/services/migrateThumbnailService.ts
@@ -1,10 +1,10 @@
import downloadManager from 'services/downloadManager';
import { getLocalFiles } from 'services/fileService';
import { generateThumbnail } from 'services/upload/thumbnailService';
-import { getToken } from 'utils/common/key';
+import { getToken } from '@ente/shared/storage/localStorage/helpers';
import { logError } from '@ente/shared/sentry';
-import { getEndpoint } from 'utils/common/apiUtil';
-import HTTPService from 'services/HTTPService';
+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';
@@ -12,7 +12,7 @@ import { getLocalTrashedFiles } from './trashService';
import { UploadURL } from 'types/upload';
import { S3FileAttributes } from 'types/file';
import { Remote } from 'comlink';
-import { DedicatedCryptoWorker } from 'worker/crypto.worker';
+import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
import ComlinkCryptoWorker from '@ente/shared/crypto';
const ENDPOINT = getEndpoint();
diff --git a/apps/photos/src/services/publicCollectionDownloadManager.ts b/apps/photos/src/services/publicCollectionDownloadManager.ts
index b1537aeb6d..d1fb1385b8 100644
--- a/apps/photos/src/services/publicCollectionDownloadManager.ts
+++ b/apps/photos/src/services/publicCollectionDownloadManager.ts
@@ -1,22 +1,22 @@
import {
getPublicCollectionFileURL,
getPublicCollectionThumbnailURL,
-} from 'utils/common/apiUtil';
+} from '@ente/shared/network/api';
import {
generateStreamFromArrayBuffer,
getRenderableFileURL,
createTypedObjectURL,
} from 'utils/file';
-import HTTPService from './HTTPService';
+import HTTPService from '@ente/shared/network/HTTPService';
import { EnteFile } from 'types/file';
import { logError } from '@ente/shared/sentry';
import { FILE_TYPE } from 'constants/file';
-import { CustomError } from 'utils/error';
+import { CustomError } from '@ente/shared/error';
import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { CACHES } from 'constants/cache';
-import { CacheStorageService } from './cache/cacheStorageService';
-import { LimitedCache } from 'types/cache';
+import { CACHES } from '@ente/shared/storage/cacheStorage/constants';
+import { CacheStorageService } from '@ente/shared/storage/cacheStorage';
+import { LimitedCache } from '@ente/shared/storage/cacheStorage/types';
class PublicCollectionDownloadManager {
private fileObjectURLPromise = new Map<
diff --git a/apps/photos/src/services/publicCollectionService.ts b/apps/photos/src/services/publicCollectionService.ts
index f4aad91a38..02703e2045 100644
--- a/apps/photos/src/services/publicCollectionService.ts
+++ b/apps/photos/src/services/publicCollectionService.ts
@@ -1,7 +1,7 @@
-import { getEndpoint } from 'utils/common/apiUtil';
+import { getEndpoint } from '@ente/shared/network/api';
import localForage from '@ente/shared/storage/localForage';
import { Collection, CollectionPublicMagicMetadata } from 'types/collection';
-import HTTPService from './HTTPService';
+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';
@@ -11,7 +11,7 @@ import {
LocalSavedPublicCollectionFiles,
} from 'types/publicCollection';
import { REPORT_REASON } from 'constants/publicCollection';
-import { CustomError, parseSharingErrorCodes } from 'utils/error';
+import { CustomError, parseSharingErrorCodes } from '@ente/shared/error';
import ComlinkCryptoWorker from '@ente/shared/crypto';
const ENDPOINT = getEndpoint();
diff --git a/apps/photos/src/services/queueProcessor.ts b/apps/photos/src/services/queueProcessor.ts
index 6071556a15..97332aaee7 100644
--- a/apps/photos/src/services/queueProcessor.ts
+++ b/apps/photos/src/services/queueProcessor.ts
@@ -1,4 +1,4 @@
-import { CustomError } from 'utils/error';
+import { CustomError } from '@ente/shared/error';
interface RequestQueueItem {
request: (canceller?: RequestCanceller) => Promise<any>;
diff --git a/apps/photos/src/services/trashService.ts b/apps/photos/src/services/trashService.ts
index f79dd8d81a..84dcc33761 100644
--- a/apps/photos/src/services/trashService.ts
+++ b/apps/photos/src/services/trashService.ts
@@ -1,13 +1,13 @@
import { SetFiles } from 'types/gallery';
import { Collection } from 'types/collection';
-import { getEndpoint } from 'utils/common/apiUtil';
-import { getToken } from 'utils/common/key';
+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 './HTTPService';
+import HTTPService from '@ente/shared/network/HTTPService';
import { EncryptedTrashItem, Trash } from 'types/trash';
import { EnteFile } from 'types/file';
import { mergeMetadata } from 'utils/file';
diff --git a/apps/photos/src/services/typeDetectionService.ts b/apps/photos/src/services/typeDetectionService.ts
index cca8c430a6..ec5187b77b 100644
--- a/apps/photos/src/services/typeDetectionService.ts
+++ b/apps/photos/src/services/typeDetectionService.ts
@@ -4,7 +4,7 @@ import {
WHITELISTED_FILE_FORMATS,
KNOWN_NON_MEDIA_FORMATS,
} from 'constants/upload';
-import { CustomError } from 'utils/error';
+import { CustomError } from '@ente/shared/error';
import { getFileExtension } from 'utils/file';
import { logError } from '@ente/shared/sentry';
import { getUint8ArrayView } from './readerService';
diff --git a/apps/photos/src/services/updateCreationTimeWithExif.ts b/apps/photos/src/services/updateCreationTimeWithExif.ts
index 2c2f1d2d07..a4945afc5d 100644
--- a/apps/photos/src/services/updateCreationTimeWithExif.ts
+++ b/apps/photos/src/services/updateCreationTimeWithExif.ts
@@ -12,7 +12,7 @@ import { EnteFile } from 'types/file';
import { getParsedExifData } from './upload/exifService';
import { getFileType } from 'services/typeDetectionService';
import { FILE_TYPE } from 'constants/file';
-import { validateAndGetCreationUnixTimeInMicroSeconds } from 'utils/time';
+import { validateAndGetCreationUnixTimeInMicroSeconds } from '@ente/shared/time';
const EXIF_TIME_TAGS = [
'DateTimeOriginal',
diff --git a/apps/photos/src/services/upload/encryptionService.ts b/apps/photos/src/services/upload/encryptionService.ts
index 389deddaad..3cd4b7d8f8 100644
--- a/apps/photos/src/services/upload/encryptionService.ts
+++ b/apps/photos/src/services/upload/encryptionService.ts
@@ -1,7 +1,7 @@
import { Remote } from 'comlink';
-import { EncryptionResult } from 'types/crypto';
+import { EncryptionResult } from '@ente/shared/crypto/types';
import { DataStream, isDataStream } from 'types/upload';
-import { DedicatedCryptoWorker } from 'worker/crypto.worker';
+import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
async function encryptFileStream(
worker: Remote<DedicatedCryptoWorker>,
diff --git a/apps/photos/src/services/upload/exifService.ts b/apps/photos/src/services/upload/exifService.ts
index 92e18747bd..743cc715c4 100644
--- a/apps/photos/src/services/upload/exifService.ts
+++ b/apps/photos/src/services/upload/exifService.ts
@@ -4,8 +4,8 @@ import exifr from 'exifr';
import piexif from 'piexifjs';
import { FileTypeInfo } from 'types/upload';
import { logError } from '@ente/shared/sentry';
-import { validateAndGetCreationUnixTimeInMicroSeconds } from 'utils/time';
-import { CustomError } from 'utils/error';
+import { validateAndGetCreationUnixTimeInMicroSeconds } from '@ente/shared/time';
+import { CustomError } from '@ente/shared/error';
const EXIFR_UNSUPPORTED_FILE_FORMAT_MESSAGE = 'Unknown file format';
diff --git a/apps/photos/src/services/upload/fileService.ts b/apps/photos/src/services/upload/fileService.ts
index f18e72189c..c2bcd15f62 100644
--- a/apps/photos/src/services/upload/fileService.ts
+++ b/apps/photos/src/services/upload/fileService.ts
@@ -22,7 +22,7 @@ import {
getUint8ArrayView,
} from '../readerService';
import { generateThumbnail } from './thumbnailService';
-import { DedicatedCryptoWorker } from 'worker/crypto.worker';
+import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
import { Remote } from 'comlink';
import { EncryptedMagicMetadata } from 'types/magicMetadata';
diff --git a/apps/photos/src/services/upload/hashService.tsx b/apps/photos/src/services/upload/hashService.tsx
index e351b91e87..4f3a0602a9 100644
--- a/apps/photos/src/services/upload/hashService.tsx
+++ b/apps/photos/src/services/upload/hashService.tsx
@@ -2,11 +2,11 @@ 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 'utils/error';
+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 'worker/crypto.worker';
+import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
export async function getFileHash(
worker: Remote<DedicatedCryptoWorker>,
diff --git a/apps/photos/src/services/upload/livePhotoService.ts b/apps/photos/src/services/upload/livePhotoService.ts
index 5c2b237c86..6749959f48 100644
--- a/apps/photos/src/services/upload/livePhotoService.ts
+++ b/apps/photos/src/services/upload/livePhotoService.ts
@@ -10,7 +10,7 @@ import {
ParsedMetadataJSONMap,
ExtractMetadataResult,
} from 'types/upload';
-import { CustomError } from 'utils/error';
+import { CustomError } from '@ente/shared/error';
import { getFileTypeFromExtensionForLivePhotoClustering } from 'utils/file/livePhoto';
import {
splitFilenameAndExtension,
@@ -25,7 +25,7 @@ import { getFileHash } from './hashService';
import { generateThumbnail } from './thumbnailService';
import uploadCancelService from './uploadCancelService';
import { Remote } from 'comlink';
-import { DedicatedCryptoWorker } from 'worker/crypto.worker';
+import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
interface LivePhotoIdentifier {
collectionID: number;
diff --git a/apps/photos/src/services/upload/metadataService.ts b/apps/photos/src/services/upload/metadataService.ts
index 98e419b9b8..8ef875bb25 100644
--- a/apps/photos/src/services/upload/metadataService.ts
+++ b/apps/photos/src/services/upload/metadataService.ts
@@ -16,10 +16,10 @@ import {
parseDateFromFusedDateString,
validateAndGetCreationUnixTimeInMicroSeconds,
tryToParseDateTime,
-} from 'utils/time';
+} from '@ente/shared/time';
import { getFileHash } from './hashService';
import { Remote } from 'comlink';
-import { DedicatedCryptoWorker } from 'worker/crypto.worker';
+import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
import { FilePublicMagicMetadataProps } from 'types/file';
interface ParsedMetadataJSONWithTitle {
diff --git a/apps/photos/src/services/upload/multiPartUploadService.ts b/apps/photos/src/services/upload/multiPartUploadService.ts
index 8d8845f6e8..e0cb89579c 100644
--- a/apps/photos/src/services/upload/multiPartUploadService.ts
+++ b/apps/photos/src/services/upload/multiPartUploadService.ts
@@ -5,7 +5,7 @@ import {
import UIService from './uiService';
import UploadHttpClient from './uploadHttpClient';
import * as convert from 'xml-js';
-import { CustomError } from 'utils/error';
+import { CustomError } from '@ente/shared/error';
import { DataStream, Logger, MultipartUploadURLs } from 'types/upload';
import uploadCancelService from './uploadCancelService';
import uploadService from './uploadService';
diff --git a/apps/photos/src/services/upload/publicUploadHttpClient.ts b/apps/photos/src/services/upload/publicUploadHttpClient.ts
index 7bb7cb2a33..70fff0b1b8 100644
--- a/apps/photos/src/services/upload/publicUploadHttpClient.ts
+++ b/apps/photos/src/services/upload/publicUploadHttpClient.ts
@@ -1,8 +1,8 @@
-import HTTPService from 'services/HTTPService';
-import { getEndpoint } from 'utils/common/apiUtil';
+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 'utils/error';
+import { CustomError, handleUploadError } from '@ente/shared/error';
import { UploadFile, UploadURL, MultipartUploadURLs } from 'types/upload';
import { retryHTTPCall } from 'utils/upload/uploadRetrier';
diff --git a/apps/photos/src/services/upload/thumbnailService.ts b/apps/photos/src/services/upload/thumbnailService.ts
index a63be2b88f..25e5364ae1 100644
--- a/apps/photos/src/services/upload/thumbnailService.ts
+++ b/apps/photos/src/services/upload/thumbnailService.ts
@@ -1,5 +1,5 @@
import { FILE_TYPE } from 'constants/file';
-import { CustomError, errorWithContext } from 'utils/error';
+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';
diff --git a/apps/photos/src/services/upload/uiService.ts b/apps/photos/src/services/upload/uiService.ts
index a26357e0b6..e76bca49c7 100644
--- a/apps/photos/src/services/upload/uiService.ts
+++ b/apps/photos/src/services/upload/uiService.ts
@@ -11,7 +11,7 @@ import {
ProgressUpdater,
SegregatedFinishedUploads,
} from 'types/upload/ui';
-import { CustomError } from 'utils/error';
+import { CustomError } from '@ente/shared/error';
import uploadCancelService from './uploadCancelService';
const REQUEST_TIMEOUT_TIME = 30 * 1000; // 30 sec;
diff --git a/apps/photos/src/services/upload/uploadHttpClient.ts b/apps/photos/src/services/upload/uploadHttpClient.ts
index a436938a66..4c6cb507d8 100644
--- a/apps/photos/src/services/upload/uploadHttpClient.ts
+++ b/apps/photos/src/services/upload/uploadHttpClient.ts
@@ -1,9 +1,9 @@
-import HTTPService from 'services/HTTPService';
-import { getEndpoint, getUploadEndpoint } from 'utils/common/apiUtil';
-import { getToken } from 'utils/common/key';
+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 'utils/error';
+import { CustomError, handleUploadError } from '@ente/shared/error';
import { UploadFile, UploadURL, MultipartUploadURLs } from 'types/upload';
import { retryHTTPCall } from 'utils/upload/uploadRetrier';
diff --git a/apps/photos/src/services/upload/uploadManager.ts b/apps/photos/src/services/upload/uploadManager.ts
index e27b0b5a47..f8a02beb98 100644
--- a/apps/photos/src/services/upload/uploadManager.ts
+++ b/apps/photos/src/services/upload/uploadManager.ts
@@ -10,8 +10,8 @@ import {
import uploader from './uploader';
import UIService from './uiService';
import UploadService from './uploadService';
-import { eventBus, Events } from 'services/events';
-import { CustomError } from 'utils/error';
+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 {
@@ -30,7 +30,7 @@ import ImportService from 'services/importService';
import watchFolderService from 'services/watchFolder/watchFolderService';
import { ProgressUpdater } from 'types/upload/ui';
import uploadCancelService from './uploadCancelService';
-import { DedicatedCryptoWorker } from 'worker/crypto.worker';
+import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
import { ComlinkWorker } from '@ente/shared/worker/comlinkWorker';
import { Remote } from 'comlink';
import {
diff --git a/apps/photos/src/services/upload/uploadService.ts b/apps/photos/src/services/upload/uploadService.ts
index 2cb0676569..8a6219f327 100644
--- a/apps/photos/src/services/upload/uploadService.ts
+++ b/apps/photos/src/services/upload/uploadService.ts
@@ -3,7 +3,7 @@ import { logError } from '@ente/shared/sentry';
import UploadHttpClient from './uploadHttpClient';
import { extractFileMetadata, getFilename } from './fileService';
import { getFileType } from '../typeDetectionService';
-import { CustomError, handleUploadError } from 'utils/error';
+import { CustomError, handleUploadError } from '@ente/shared/error';
import {
BackupedFile,
EncryptedFile,
@@ -33,11 +33,11 @@ import { encryptFile, getFileSize, readFile } from './fileService';
import { uploadStreamUsingMultipart } from './multiPartUploadService';
import UIService from './uiService';
import { Remote } from 'comlink';
-import { DedicatedCryptoWorker } from 'worker/crypto.worker';
+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 'types/crypto';
+import { B64EncryptionResult } from '@ente/shared/crypto/types';
class UploadService {
private uploadURLs: UploadURL[] = [];
diff --git a/apps/photos/src/services/upload/uploader.ts b/apps/photos/src/services/upload/uploader.ts
index b099ee4395..d89a667ebc 100644
--- a/apps/photos/src/services/upload/uploader.ts
+++ b/apps/photos/src/services/upload/uploader.ts
@@ -1,5 +1,5 @@
import { EnteFile } from 'types/file';
-import { handleUploadError, CustomError } from 'utils/error';
+import { handleUploadError, CustomError } from '@ente/shared/error';
import { logError } from '@ente/shared/sentry';
import { findMatchingExistingFiles } from 'utils/upload';
import UIService from './uiService';
@@ -19,7 +19,7 @@ import { sleep } from 'utils/common';
import { addToCollection } from 'services/collectionService';
import uploadCancelService from './uploadCancelService';
import { Remote } from 'comlink';
-import { DedicatedCryptoWorker } from 'worker/crypto.worker';
+import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
import uploadService from './uploadService';
interface UploadResponse {
diff --git a/apps/photos/src/services/userService.ts b/apps/photos/src/services/userService.ts
index 34b90f3611..acf16c5e4e 100644
--- a/apps/photos/src/services/userService.ts
+++ b/apps/photos/src/services/userService.ts
@@ -2,12 +2,12 @@ import {
getEndpoint,
getFamilyPortalURL,
isDevDeployment,
-} from 'utils/common/apiUtil';
+} from '@ente/shared/network/api';
import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
import localForage from '@ente/shared/storage/localForage';
-import { getToken } from 'utils/common/key';
-import HTTPService from './HTTPService';
-import { getRecoveryKey } from 'utils/crypto';
+import { getToken } from '@ente/shared/storage/localStorage/helpers';
+import HTTPService from '@ente/shared/network/HTTPService';
+import { getRecoveryKey } from '@ente/shared/crypto/helpers';
import { logError } from '@ente/shared/sentry';
import {
UserDetails,
@@ -15,7 +15,7 @@ import {
GetRemoteStoreValueResponse,
GetFeatureFlagResponse,
} from 'types/user';
-import { ApiError } from 'utils/error';
+import { ApiError } from '@ente/shared/error';
import { getLocalFamilyData, isPartOfFamily } from 'utils/user/family';
import { AxiosResponse, HttpStatusCode } from 'axios';
import { setLocalMapEnabled } from '@ente/shared/storage/localStorage/helpers';
@@ -143,47 +143,6 @@ export const getTwoFactorStatus = async () => {
return resp.data['status'];
};
-export const _logout = async () => {
- if (!getToken()) return true;
- try {
- await HTTPService.post(`${ENDPOINT}/users/logout`, null, null, {
- 'X-Auth-Token': getToken(),
- });
- return true;
- } catch (e) {
- logError(e, '/users/logout failed');
- return false;
- }
-};
-
-export const sendOTTForEmailChange = async (email: string) => {
- if (!getToken()) {
- return null;
- }
- await HTTPService.post(`${ENDPOINT}/users/ott`, {
- email,
- client: 'web',
- purpose: 'change',
- });
-};
-
-export const changeEmail = async (email: string, ott: string) => {
- if (!getToken()) {
- return null;
- }
- await HTTPService.post(
- `${ENDPOINT}/users/change-email`,
- {
- email,
- ott,
- },
- null,
- {
- 'X-Auth-Token': getToken(),
- }
- );
-};
-
export const getUserDetailsV2 = async (): Promise<UserDetails> => {
try {
const token = getToken();
diff --git a/apps/photos/src/services/wasmHeicConverter/wasmHEICConverterService.ts b/apps/photos/src/services/wasmHeicConverter/wasmHEICConverterService.ts
index f9ce49c502..9f45d8e95a 100644
--- a/apps/photos/src/services/wasmHeicConverter/wasmHEICConverterService.ts
+++ b/apps/photos/src/services/wasmHeicConverter/wasmHEICConverterService.ts
@@ -1,5 +1,5 @@
import QueueProcessor from 'services/queueProcessor';
-import { CustomError } from 'utils/error';
+import { CustomError } from '@ente/shared/error';
import { retryAsyncFunction } from 'utils/network';
import { logError } from '@ente/shared/sentry';
import { addLogLine } from '@ente/shared/logging';
diff --git a/apps/photos/src/services/workerElectronCache/client.ts b/apps/photos/src/services/workerElectronCache/client.ts
deleted file mode 100644
index a4ca1cc322..0000000000
--- a/apps/photos/src/services/workerElectronCache/client.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import ElectronAPIs from '@ente/shared/electron';
-import * as Comlink from 'comlink';
-import {
- LimitedCache,
- ProxiedLimitedCacheStorage,
- ProxiedWorkerLimitedCache,
-} from 'types/cache';
-import {
- serializeResponse,
- deserializeToResponse,
-} from 'utils/workerElectronCache/proxy';
-
-export class WorkerElectronCacheStorageClient
- implements ProxiedLimitedCacheStorage
-{
- async open(cacheName: string) {
- const cache = await ElectronAPIs.openDiskCache(cacheName);
- return Comlink.proxy({
- match: Comlink.proxy(transformMatch(cache.match.bind(cache))),
- put: Comlink.proxy(transformPut(cache.put.bind(cache))),
- delete: Comlink.proxy(cache.delete.bind(cache)),
- });
- }
-
- async delete(cacheName: string) {
- return await ElectronAPIs.deleteDiskCache(cacheName);
- }
-}
-
-function transformMatch(
- fn: LimitedCache['match']
-): ProxiedWorkerLimitedCache['match'] {
- return async (key: string) => {
- return serializeResponse(await fn(key));
- };
-}
-
-function transformPut(
- fn: LimitedCache['put']
-): ProxiedWorkerLimitedCache['put'] {
- return async (key: string, data: ArrayBuffer) => {
- fn(key, deserializeToResponse(data));
- };
-}
diff --git a/apps/photos/src/services/workerElectronCache/service.ts b/apps/photos/src/services/workerElectronCache/service.ts
deleted file mode 100644
index 720115ad78..0000000000
--- a/apps/photos/src/services/workerElectronCache/service.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import * as Comlink from 'comlink';
-import {
- LimitedCache,
- LimitedCacheStorage,
- ProxiedWorkerLimitedCache,
-} from 'types/cache';
-import { WorkerElectronCacheStorageClient } from './client';
-import { wrap } from 'comlink';
-import {
- deserializeToResponse,
- serializeResponse,
-} from 'utils/workerElectronCache/proxy';
-
-export class WorkerElectronCacheStorageService implements LimitedCacheStorage {
- proxiedElectronCacheService: Comlink.Remote<WorkerElectronCacheStorageClient>;
- ready: Promise<any>;
-
- constructor() {
- this.ready = this.init();
- }
- async init() {
- const electronCacheStorageProxy =
- wrap<typeof WorkerElectronCacheStorageClient>(self);
-
- this.proxiedElectronCacheService =
- await new electronCacheStorageProxy();
- }
- async open(cacheName: string) {
- await this.ready;
- const cache = await this.proxiedElectronCacheService.open(cacheName);
- return {
- match: transformMatch(cache.match.bind(cache)),
- put: transformPut(cache.put.bind(cache)),
- delete: cache.delete.bind(cache),
- };
- }
-
- async delete(cacheName: string) {
- await this.ready;
- return await this.proxiedElectronCacheService.delete(cacheName);
- }
-}
-
-function transformMatch(
- fn: ProxiedWorkerLimitedCache['match']
-): LimitedCache['match'] {
- return async (key: string) => {
- return deserializeToResponse(await fn(key));
- };
-}
-
-function transformPut(
- fn: ProxiedWorkerLimitedCache['put']
-): LimitedCache['put'] {
- return async (key: string, data: Response) => {
- fn(key, await serializeResponse(data));
- };
-}
diff --git a/apps/photos/src/types/cache/index.ts b/apps/photos/src/types/cache/index.ts
deleted file mode 100644
index 2920ece105..0000000000
--- a/apps/photos/src/types/cache/index.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-export interface LimitedCacheStorage {
- open: (cacheName: string) => Promise<LimitedCache>;
- delete: (cacheName: string) => Promise<boolean>;
-}
-
-export interface LimitedCache {
- match: (key: string) => Promise<Response>;
- put: (key: string, data: Response) => Promise<void>;
- delete: (key: string) => Promise<boolean>;
-}
-
-export interface ProxiedLimitedCacheStorage {
- open: (cacheName: string) => Promise<ProxiedWorkerLimitedCache>;
- delete: (cacheName: string) => Promise<boolean>;
-}
-export interface ProxiedWorkerLimitedCache {
- match: (key: string) => Promise<ArrayBuffer>;
- put: (key: string, data: ArrayBuffer) => Promise<void>;
- delete: (key: string) => Promise<boolean>;
-}
diff --git a/apps/photos/src/types/crypto/index.ts b/apps/photos/src/types/crypto/index.ts
deleted file mode 100644
index 6b5a64b44a..0000000000
--- a/apps/photos/src/types/crypto/index.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { DataStream } from 'types/upload';
-
-export interface LocalFileAttributes<
- T extends string | Uint8Array | DataStream
-> {
- encryptedData: T;
- decryptionHeader: string;
-}
-
-export interface EncryptionResult<T extends string | Uint8Array | DataStream> {
- file: LocalFileAttributes<T>;
- key: string;
-}
-
-export interface B64EncryptionResult {
- encryptedData: string;
- key: string;
- nonce: string;
-}
diff --git a/apps/photos/src/types/dialogBox/index.ts b/apps/photos/src/types/dialogBox/index.ts
deleted file mode 100644
index dd956cc60a..0000000000
--- a/apps/photos/src/types/dialogBox/index.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { ButtonProps } from '@mui/material';
-
-export interface DialogBoxAttributes {
- icon?: React.ReactNode;
- title?: string;
- staticBackdrop?: boolean;
- nonClosable?: boolean;
- content?: any;
- close?: {
- text?: string;
- variant?: ButtonProps['color'];
- action?: () => void;
- };
- proceed?: {
- text: string;
- action: () => void;
- variant?: ButtonProps['color'];
- disabled?: boolean;
- };
- secondary?: {
- text: string;
- action: () => void;
- variant: ButtonProps['color'];
- disabled?: boolean;
- };
-}
-
-export type SetDialogBoxAttributes = React.Dispatch<
- React.SetStateAction<DialogBoxAttributes>
->;
-
-export interface DialogBoxAttributesV2 {
- icon?: React.ReactNode;
- title?: string;
- staticBackdrop?: boolean;
- nonClosable?: boolean;
- content?: any;
- close?: {
- text?: string;
- variant?: ButtonProps['color'];
- action?: () => void;
- };
- proceed?: {
- text: string;
- action: (setLoading?: (value: boolean) => void) => void | Promise<void>;
- variant?: ButtonProps['color'];
- disabled?: boolean;
- };
- secondary?: {
- text: string;
- action: () => void;
- variant?: ButtonProps['color'];
- disabled?: boolean;
- };
- buttons?: {
- text: string;
- action: () => void;
- variant: ButtonProps['color'];
- disabled?: boolean;
- }[];
- buttonDirection?: 'row' | 'column';
-}
-
-export type SetDialogBoxAttributesV2 = React.Dispatch<
- React.SetStateAction<DialogBoxAttributesV2>
->;
diff --git a/apps/photos/src/types/gallery/index.ts b/apps/photos/src/types/gallery/index.ts
index 6cd5416fcc..84892026c5 100644
--- a/apps/photos/src/types/gallery/index.ts
+++ b/apps/photos/src/types/gallery/index.ts
@@ -3,7 +3,7 @@ import { CollectionSelectorAttributes } from 'components/Collections/CollectionS
import { TimeStampListItem } from 'components/PhotoList';
import { Collection } from 'types/collection';
import { EnteFile } from 'types/file';
-import { User } from 'types/user';
+import { User } from '@ente/shared/user/types';
export type SelectedState = {
[k: number]: boolean;
diff --git a/apps/photos/src/types/upload/index.ts b/apps/photos/src/types/upload/index.ts
index 6c420c77b6..8ba1e957bc 100644
--- a/apps/photos/src/types/upload/index.ts
+++ b/apps/photos/src/types/upload/index.ts
@@ -1,6 +1,9 @@
import { FILE_TYPE } from 'constants/file';
import { Collection } from 'types/collection';
-import { B64EncryptionResult, LocalFileAttributes } from 'types/crypto';
+import {
+ B64EncryptionResult,
+ LocalFileAttributes,
+} from '@ente/shared/crypto/types';
import {
MetadataFileAttributes,
S3FileAttributes,
diff --git a/apps/photos/src/types/user/index.ts b/apps/photos/src/types/user/index.ts
index de2228042e..055c8a18ac 100644
--- a/apps/photos/src/types/user/index.ts
+++ b/apps/photos/src/types/user/index.ts
@@ -1,84 +1,5 @@
import { Subscription } from 'types/billing';
-export interface KeyAttributes {
- kekSalt: string;
- encryptedKey: string;
- keyDecryptionNonce: string;
- opsLimit: number;
- memLimit: number;
- publicKey: string;
- encryptedSecretKey: string;
- secretKeyDecryptionNonce: string;
- masterKeyEncryptedWithRecoveryKey: string;
- masterKeyDecryptionNonce: string;
- recoveryKeyEncryptedWithMasterKey: string;
- recoveryKeyDecryptionNonce: string;
-}
-export interface KEK {
- key: string;
- opsLimit: number;
- memLimit: number;
-}
-
-export interface UpdatedKey {
- kekSalt: string;
- encryptedKey: string;
- keyDecryptionNonce: string;
- memLimit: number;
- opsLimit: number;
-}
-
-export interface UpdateSRPAndKeysRequest {
- srpM1: string;
- setupID: string;
- updatedKeyAttr: UpdatedKey;
-}
-
-export interface UpdateSRPAndKeysResponse {
- srpM2: string;
- setupID: string;
-}
-
-export interface RecoveryKey {
- masterKeyEncryptedWithRecoveryKey: string;
- masterKeyDecryptionNonce: string;
- recoveryKeyEncryptedWithMasterKey: string;
- recoveryKeyDecryptionNonce: string;
-}
-export interface User {
- id: number;
- email: string;
- token: string;
- encryptedToken: string;
- isTwoFactorEnabled: boolean;
- twoFactorSessionID: string;
-}
-export interface UserVerificationResponse {
- id: number;
- keyAttributes?: KeyAttributes;
- encryptedToken?: string;
- token?: string;
- twoFactorSessionID: string;
- srpM2?: string;
-}
-
-export interface TwoFactorVerificationResponse {
- id: number;
- keyAttributes: KeyAttributes;
- encryptedToken?: string;
- token?: string;
-}
-
-export interface TwoFactorSecret {
- secretCode: string;
- qrCode: string;
-}
-
-export interface TwoFactorRecoveryResponse {
- encryptedSecret: string;
- secretDecryptionNonce: string;
-}
-
export interface FamilyMember {
email: string;
usage: number;
diff --git a/apps/photos/src/utils/billing/index.ts b/apps/photos/src/utils/billing/index.ts
index cdb0a4ed0b..37baea6d6e 100644
--- a/apps/photos/src/utils/billing/index.ts
+++ b/apps/photos/src/utils/billing/index.ts
@@ -6,7 +6,7 @@ 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 'types/dialogBox';
+import { SetDialogBoxAttributes } from '@ente/shared/components/DialogBox/types';
import { openLink } from 'utils/common';
import { isPartOfFamily, getTotalFamilyUsage } from 'utils/user/family';
import { UserDetails } from 'types/user';
diff --git a/apps/photos/src/utils/collection/index.ts b/apps/photos/src/utils/collection/index.ts
index 7ba83a1871..2341ed2f4a 100644
--- a/apps/photos/src/utils/collection/index.ts
+++ b/apps/photos/src/utils/collection/index.ts
@@ -15,8 +15,8 @@ import {
import { downloadFiles, downloadFilesDesktop } from 'utils/file';
import { getAllLocalFiles, getLocalFiles } from 'services/fileService';
import { EnteFile } from 'types/file';
-import { CustomError } from 'utils/error';
-import { User } from 'types/user';
+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';
import {
@@ -37,10 +37,10 @@ import {
HIDDEN_ITEMS_SECTION,
DEFAULT_HIDDEN_COLLECTION_USER_FACING_NAME,
} from 'constants/collection';
-import { getUnixTimeInMicroSecondsWithDelta } from 'utils/time';
+import { getUnixTimeInMicroSecondsWithDelta } from '@ente/shared/time';
import { SUB_TYPE, VISIBILITY_STATE } from 'types/magicMetadata';
import { isArchivedCollection, updateMagicMetadata } from 'utils/magicMetadata';
-import { getAlbumsURL } from 'utils/common/apiUtil';
+import { getAlbumsURL } from '@ente/shared/network/api';
import bs58 from 'bs58';
import { t } from 'i18next';
import isElectron from 'is-electron';
diff --git a/apps/photos/src/utils/common/apiUtil.ts b/apps/photos/src/utils/common/apiUtil.ts
deleted file mode 100644
index 6d9ef81c0f..0000000000
--- a/apps/photos/src/utils/common/apiUtil.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-
-export const getEndpoint = () => {
- let endpoint = getData(LS_KEYS.API_ENDPOINT);
- if (endpoint) {
- return endpoint;
- }
- endpoint = process.env.NEXT_PUBLIC_ENTE_ENDPOINT;
- if (isDevDeployment() && endpoint) {
- return endpoint;
- }
- return 'https://api.ente.io';
-};
-
-export const getFileURL = (id: number) => {
- const endpoint = process.env.NEXT_PUBLIC_ENTE_ENDPOINT;
- if (isDevDeployment() && endpoint) {
- return `${endpoint}/files/download/${id}`;
- }
- return `https://files.ente.io/?fileID=${id}`;
-};
-
-export const getPublicCollectionFileURL = (id: number) => {
- const endpoint = process.env.NEXT_PUBLIC_ENTE_ENDPOINT;
- if (isDevDeployment() && endpoint) {
- return `${endpoint}/public-collection/files/download/${id}`;
- }
- return `https://public-albums.ente.io/download/?fileID=${id}`;
-};
-
-export const getThumbnailURL = (id: number) => {
- const endpoint = process.env.NEXT_PUBLIC_ENTE_ENDPOINT;
- if (isDevDeployment() && endpoint) {
- return `${endpoint}/files/preview/${id}`;
- }
- return `https://thumbnails.ente.io/?fileID=${id}`;
-};
-
-export const getPublicCollectionThumbnailURL = (id: number) => {
- const endpoint = process.env.NEXT_PUBLIC_ENTE_ENDPOINT;
- if (isDevDeployment() && endpoint) {
- return `${endpoint}/public-collection/files/preview/${id}`;
- }
- return `https://public-albums.ente.io/preview/?fileID=${id}`;
-};
-
-export const getUploadEndpoint = () => {
- const endpoint = process.env.NEXT_PUBLIC_ENTE_UPLOAD_ENDPOINT;
- if (isDevDeployment() && endpoint) {
- return endpoint;
- }
- return `https://uploader.ente.io`;
-};
-
-export const getPaymentsURL = () => {
- const paymentsURL = process.env.NEXT_PUBLIC_ENTE_PAYMENT_ENDPOINT;
- if (isDevDeployment() && paymentsURL) {
- return paymentsURL;
- }
- return `https://payments.ente.io`;
-};
-
-export const getAlbumsURL = () => {
- const albumsURL = process.env.NEXT_PUBLIC_ENTE_ALBUM_ENDPOINT;
- if (isDevDeployment() && albumsURL) {
- return albumsURL;
- }
- return `https://albums.ente.io`;
-};
-
-// getFamilyPortalURL returns the endpoint for the family dashboard which can be used to
-// create or manage family.
-export const getFamilyPortalURL = () => {
- const familyURL = process.env.NEXT_PUBLIC_ENTE_FAMILY_PORTAL_ENDPOINT;
- if (isDevDeployment() && familyURL) {
- return familyURL;
- }
- return `https://family.ente.io`;
-};
-
-// getAuthenticatorURL returns the endpoint for the authenticator which can be used to
-// view authenticator codes.
-export const getAuthURL = () => {
- const authURL = process.env.NEXT_PUBLIC_ENTE_AUTH_ENDPOINT;
- if (isDevDeployment() && authURL) {
- return authURL;
- }
- return `https://auth.ente.io`;
-};
-
-export const getSentryTunnelURL = () => {
- return `https://sentry-reporter.ente.io`;
-};
-
-/*
-It's a dev deployment (and should use the environment override for endpoints ) in three cases:
-1. when the URL opened is that of the staging web app, or
-2. when the URL opened is that of the staging album app, or
-3. if the app is running locally (hence node_env is development)
-4. if the app is running in test mode
-*/
-export const isDevDeployment = () => {
- if (globalThis?.location) {
- return (
- process.env.NEXT_PUBLIC_ENTE_WEB_ENDPOINT ===
- globalThis.location.origin ||
- process.env.NEXT_PUBLIC_ENTE_ALBUM_ENDPOINT ===
- globalThis.location.origin ||
- process.env.NEXT_PUBLIC_IS_TEST_APP === 'true' ||
- process.env.NODE_ENV === 'development'
- );
- }
-};
diff --git a/apps/photos/src/utils/common/index.ts b/apps/photos/src/utils/common/index.ts
index 0d77a4248b..72cf592216 100644
--- a/apps/photos/src/utils/common/index.ts
+++ b/apps/photos/src/utils/common/index.ts
@@ -1,6 +1,6 @@
-import { CustomError } from 'utils/error';
+import { CustomError } from '@ente/shared/error';
import isElectron from 'is-electron';
-import { APP_DOWNLOAD_URL } from 'constants/urls';
+import { APP_DOWNLOAD_URL } from '@ente/shared/constants/urls';
export function checkConnectivity() {
if (navigator.onLine) {
diff --git a/apps/photos/src/utils/common/key.ts b/apps/photos/src/utils/common/key.ts
deleted file mode 100644
index 74e6a7a749..0000000000
--- a/apps/photos/src/utils/common/key.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { B64EncryptionResult } from 'types/crypto';
-import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
-import { getKey, SESSION_KEYS } from '@ente/shared/storage/sessionStorage';
-import { CustomError } from '../error';
-
-export const getActualKey = async () => {
- try {
- const encryptionKeyAttributes: B64EncryptionResult = getKey(
- SESSION_KEYS.ENCRYPTION_KEY
- );
-
- const cryptoWorker = await ComlinkCryptoWorker.getInstance();
- const key = await cryptoWorker.decryptB64(
- encryptionKeyAttributes.encryptedData,
- encryptionKeyAttributes.nonce,
- encryptionKeyAttributes.key
- );
- return key;
- } catch (e) {
- throw new Error(CustomError.KEY_MISSING);
- }
-};
-
-export const getToken = () => getData(LS_KEYS.USER)?.token;
-export const getUserID = () => getData(LS_KEYS.USER)?.id;
diff --git a/apps/photos/src/utils/common/promiseTimeout.ts b/apps/photos/src/utils/common/promiseTimeout.ts
index 5aa5832a96..230e55e0e8 100644
--- a/apps/photos/src/utils/common/promiseTimeout.ts
+++ b/apps/photos/src/utils/common/promiseTimeout.ts
@@ -1,4 +1,4 @@
-import { CustomError } from 'utils/error';
+import { CustomError } from '@ente/shared/error';
export const promiseWithTimeout = async (
request: Promise<any>,
diff --git a/apps/photos/src/utils/crypto/index.ts b/apps/photos/src/utils/crypto/index.ts
index 31b1e93962..469f781694 100644
--- a/apps/photos/src/utils/crypto/index.ts
+++ b/apps/photos/src/utils/crypto/index.ts
@@ -1,235 +1,6 @@
-import { KeyAttributes, SRPSetupAttributes } from 'types/user';
-import { SESSION_KEYS, setKey } from '@ente/shared/storage/sessionStorage';
-import { getData, LS_KEYS, setData } from '@ente/shared/storage/localStorage';
-import { getActualKey, getToken } from 'utils/common/key';
-import { setRecoveryKey } from '@ente/accounts/api/user';
-import { logError } from '@ente/shared/sentry';
-import isElectron from 'is-electron';
-import ElectronAPIs from '@ente/shared/electron';
-
+import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
+import { getActualKey } from '@ente/shared/user';
import ComlinkCryptoWorker from '@ente/shared/crypto';
-import { PasswordStrength } from 'constants/crypto';
-import zxcvbn from 'zxcvbn';
-import { SRP, SrpClient } from 'fast-srp-hap';
-import { convertBase64ToBuffer, convertBufferToBase64 } from 'utils/user';
-import { v4 as uuidv4 } from 'uuid';
-import { addLocalLog } from '@ente/shared/logging';
-
-const SRP_PARAMS = SRP.params['4096'];
-
-const LOGIN_SUB_KEY_LENGTH = 32;
-const LOGIN_SUB_KEY_ID = 1;
-const LOGIN_SUB_KEY_CONTEXT = 'loginctx';
-const LOGIN_SUB_KEY_BYTE_LENGTH = 16;
-
-export async function generateKeyAndSRPAttributes(passphrase: string): Promise<{
- keyAttributes: KeyAttributes;
- masterKey: string;
- srpSetupAttributes: SRPSetupAttributes;
-}> {
- const cryptoWorker = await ComlinkCryptoWorker.getInstance();
- const masterKey = await cryptoWorker.generateEncryptionKey();
- const recoveryKey = await cryptoWorker.generateEncryptionKey();
- const kekSalt = await cryptoWorker.generateSaltToDeriveKey();
- const kek = await cryptoWorker.deriveSensitiveKey(passphrase, kekSalt);
-
- const masterKeyEncryptedWithKek = await cryptoWorker.encryptToB64(
- masterKey,
- kek.key
- );
- const masterKeyEncryptedWithRecoveryKey = await cryptoWorker.encryptToB64(
- masterKey,
- recoveryKey
- );
- const recoveryKeyEncryptedWithMasterKey = await cryptoWorker.encryptToB64(
- recoveryKey,
- masterKey
- );
-
- const keyPair = await cryptoWorker.generateKeyPair();
- const encryptedKeyPairAttributes = await cryptoWorker.encryptToB64(
- keyPair.privateKey,
- masterKey
- );
-
- const loginSubKey = await generateLoginSubKey(kek.key);
-
- const srpSetupAttributes = await generateSRPSetupAttributes(loginSubKey);
-
- const keyAttributes: KeyAttributes = {
- kekSalt,
- encryptedKey: masterKeyEncryptedWithKek.encryptedData,
- keyDecryptionNonce: masterKeyEncryptedWithKek.nonce,
- publicKey: keyPair.publicKey,
- encryptedSecretKey: encryptedKeyPairAttributes.encryptedData,
- secretKeyDecryptionNonce: encryptedKeyPairAttributes.nonce,
- opsLimit: kek.opsLimit,
- memLimit: kek.memLimit,
- masterKeyEncryptedWithRecoveryKey:
- masterKeyEncryptedWithRecoveryKey.encryptedData,
- masterKeyDecryptionNonce: masterKeyEncryptedWithRecoveryKey.nonce,
- recoveryKeyEncryptedWithMasterKey:
- recoveryKeyEncryptedWithMasterKey.encryptedData,
- recoveryKeyDecryptionNonce: recoveryKeyEncryptedWithMasterKey.nonce,
- };
-
- return {
- keyAttributes,
- masterKey,
- srpSetupAttributes,
- };
-}
-
-// We encrypt the masterKey, with an intermediate key derived from the
-// passphrase (with Interactive mem and ops limits) to avoid saving it to local
-// storage in plain text. This means that on the web user will always have to
-// enter their passphrase to access their masterKey.
-export async function generateAndSaveIntermediateKeyAttributes(
- passphrase: string,
- existingKeyAttributes: KeyAttributes,
- key: string
-): Promise<KeyAttributes> {
- const cryptoWorker = await ComlinkCryptoWorker.getInstance();
- const intermediateKekSalt = await cryptoWorker.generateSaltToDeriveKey();
- const intermediateKek = await cryptoWorker.deriveInteractiveKey(
- passphrase,
- intermediateKekSalt
- );
- const encryptedKeyAttributes = await cryptoWorker.encryptToB64(
- key,
- intermediateKek.key
- );
-
- const intermediateKeyAttributes = Object.assign(existingKeyAttributes, {
- kekSalt: intermediateKekSalt,
- encryptedKey: encryptedKeyAttributes.encryptedData,
- keyDecryptionNonce: encryptedKeyAttributes.nonce,
- opsLimit: intermediateKek.opsLimit,
- memLimit: intermediateKek.memLimit,
- });
- setData(LS_KEYS.KEY_ATTRIBUTES, intermediateKeyAttributes);
- return intermediateKeyAttributes;
-}
-
-export const saveKeyInSessionStore = async (
- keyType: SESSION_KEYS,
- key: string,
- fromDesktop?: boolean
-) => {
- const cryptoWorker = await ComlinkCryptoWorker.getInstance();
- const sessionKeyAttributes = await cryptoWorker.generateKeyAndEncryptToB64(
- key
- );
- setKey(keyType, sessionKeyAttributes);
- if (
- isElectron() &&
- !fromDesktop &&
- keyType === SESSION_KEYS.ENCRYPTION_KEY
- ) {
- ElectronAPIs.setEncryptionKey(key);
- }
-};
-
-export const getRecoveryKey = async () => {
- let recoveryKey: string = null;
- try {
- const cryptoWorker = await ComlinkCryptoWorker.getInstance();
-
- const keyAttributes: KeyAttributes = getData(LS_KEYS.KEY_ATTRIBUTES);
- const {
- recoveryKeyEncryptedWithMasterKey,
- recoveryKeyDecryptionNonce,
- } = keyAttributes;
- const masterKey = await getActualKey();
- if (recoveryKeyEncryptedWithMasterKey) {
- recoveryKey = await cryptoWorker.decryptB64(
- recoveryKeyEncryptedWithMasterKey,
- recoveryKeyDecryptionNonce,
- masterKey
- );
- } else {
- recoveryKey = await createNewRecoveryKey();
- }
- recoveryKey = await cryptoWorker.toHex(recoveryKey);
- return recoveryKey;
- } catch (e) {
- logError(e, 'getRecoveryKey failed');
- throw e;
- }
-};
-
-// Used only for legacy users for whom we did not generate recovery keys during
-// sign up
-async function createNewRecoveryKey() {
- const masterKey = await getActualKey();
- const existingAttributes = getData(LS_KEYS.KEY_ATTRIBUTES);
-
- const cryptoWorker = await ComlinkCryptoWorker.getInstance();
-
- const recoveryKey = await cryptoWorker.generateEncryptionKey();
- const encryptedMasterKey = await cryptoWorker.encryptToB64(
- masterKey,
- recoveryKey
- );
- const encryptedRecoveryKey = await cryptoWorker.encryptToB64(
- recoveryKey,
- masterKey
- );
- const recoveryKeyAttributes = {
- masterKeyEncryptedWithRecoveryKey: encryptedMasterKey.encryptedData,
- masterKeyDecryptionNonce: encryptedMasterKey.nonce,
- recoveryKeyEncryptedWithMasterKey: encryptedRecoveryKey.encryptedData,
- recoveryKeyDecryptionNonce: encryptedRecoveryKey.nonce,
- };
- await setRecoveryKey(getToken(), recoveryKeyAttributes);
-
- const updatedKeyAttributes = Object.assign(
- existingAttributes,
- recoveryKeyAttributes
- );
- setData(LS_KEYS.KEY_ATTRIBUTES, updatedKeyAttributes);
-
- return recoveryKey;
-}
-
-export async function decryptAndStoreToken(
- keyAttributes: KeyAttributes,
- masterKey: string
-) {
- const cryptoWorker = await ComlinkCryptoWorker.getInstance();
- const user = getData(LS_KEYS.USER);
- let decryptedToken = null;
- const { encryptedToken } = user;
- if (encryptedToken && encryptedToken.length > 0) {
- const secretKey = await cryptoWorker.decryptB64(
- keyAttributes.encryptedSecretKey,
- keyAttributes.secretKeyDecryptionNonce,
- masterKey
- );
- const urlUnsafeB64DecryptedToken = await cryptoWorker.boxSealOpen(
- encryptedToken,
- keyAttributes.publicKey,
- secretKey
- );
- const decryptedTokenBytes = await cryptoWorker.fromB64(
- urlUnsafeB64DecryptedToken
- );
- decryptedToken = await cryptoWorker.toURLSafeB64(decryptedTokenBytes);
- setData(LS_KEYS.USER, {
- ...user,
- token: decryptedToken,
- encryptedToken: null,
- });
- }
-}
-
-export async function encryptWithRecoveryKey(key: string) {
- const cryptoWorker = await ComlinkCryptoWorker.getInstance();
- const hexRecoveryKey = await getRecoveryKey();
- const recoveryKey = await cryptoWorker.fromHex(hexRecoveryKey);
- const encryptedKey = await cryptoWorker.encryptToB64(key, recoveryKey);
- return encryptedKey;
-}
export async function decryptDeleteAccountChallenge(
encryptedChallenge: string
@@ -250,117 +21,3 @@ export async function decryptDeleteAccountChallenge(
const utf8DecryptedChallenge = atob(b64DecryptedChallenge);
return utf8DecryptedChallenge;
}
-
-export function estimatePasswordStrength(password: string): PasswordStrength {
- if (!password) {
- return PasswordStrength.WEAK;
- }
-
- const zxcvbnResult = zxcvbn(password);
- if (zxcvbnResult.score < 2) {
- return PasswordStrength.WEAK;
- } else if (zxcvbnResult.score < 3) {
- return PasswordStrength.MODERATE;
- } else {
- return PasswordStrength.STRONG;
- }
-}
-
-export const isWeakPassword = (password: string) => {
- return estimatePasswordStrength(password) === PasswordStrength.WEAK;
-};
-
-export const generateLoginSubKey = async (kek: string) => {
- const cryptoWorker = await ComlinkCryptoWorker.getInstance();
- const kekSubKeyString = await cryptoWorker.generateSubKey(
- kek,
- LOGIN_SUB_KEY_LENGTH,
- LOGIN_SUB_KEY_ID,
- 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)
- );
-
- return loginSubKey;
-};
-
-export const generateSRPSetupAttributes = async (
- loginSubKey: string
-): Promise<SRPSetupAttributes> => {
- const cryptoWorker = await ComlinkCryptoWorker.getInstance();
-
- const srpSalt = await cryptoWorker.generateSaltToDeriveKey();
-
- const srpUserID = uuidv4();
-
- const srpVerifierBuffer = SRP.computeVerifier(
- SRP_PARAMS,
- convertBase64ToBuffer(srpSalt),
- Buffer.from(srpUserID),
- convertBase64ToBuffer(loginSubKey)
- );
-
- const srpVerifier = convertBufferToBase64(srpVerifierBuffer);
-
- addLocalLog(
- () => `SRP setup attributes generated',
- ${JSON.stringify({
- srpSalt,
- srpUserID,
- srpVerifier,
- loginSubKey,
- })}`
- );
-
- return {
- srpUserID,
- srpSalt,
- srpVerifier,
- loginSubKey,
- };
-};
-
-export const computeVerifierHelper = (
- srpSalt: string,
- srpUserID: string,
- loginSubKey: string
-) => {
- const srpVerifierBuffer = SRP.computeVerifier(
- SRP_PARAMS,
- convertBase64ToBuffer(srpSalt),
- Buffer.from(srpUserID),
- convertBase64ToBuffer(loginSubKey)
- );
- return convertBufferToBase64(srpVerifierBuffer);
-};
-export const generateSRPClient = async (
- srpSalt: string,
- srpUserID: string,
- loginSubKey: string
-) => {
- return new Promise<SrpClient>((resolve, reject) => {
- SRP.genKey(function (err, secret1) {
- try {
- if (err) {
- reject(err);
- }
- const srpClient = new SrpClient(
- SRP_PARAMS,
- convertBase64ToBuffer(srpSalt),
- Buffer.from(srpUserID),
- convertBase64ToBuffer(loginSubKey),
- secret1,
- false
- );
-
- resolve(srpClient);
- } catch (e) {
- reject(e);
- }
- });
- });
-};
diff --git a/apps/photos/src/utils/crypto/libsodium.ts b/apps/photos/src/utils/crypto/libsodium.ts
deleted file mode 100644
index 958a2af0b7..0000000000
--- a/apps/photos/src/utils/crypto/libsodium.ts
+++ /dev/null
@@ -1,422 +0,0 @@
-import sodium, { StateAddress } from 'libsodium-wrappers';
-import { ENCRYPTION_CHUNK_SIZE } from 'constants/crypto';
-import { B64EncryptionResult } from 'types/crypto';
-import { CustomError } from 'utils/error';
-
-export async function decryptChaChaOneShot(
- data: Uint8Array,
- header: Uint8Array,
- key: string
-) {
- await sodium.ready;
- const pullState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(
- header,
- await fromB64(key)
- );
- const pullResult = sodium.crypto_secretstream_xchacha20poly1305_pull(
- pullState,
- data,
- null
- );
- return pullResult.message;
-}
-
-export async function decryptChaCha(
- data: Uint8Array,
- header: Uint8Array,
- key: string
-) {
- await sodium.ready;
- const pullState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(
- header,
- await fromB64(key)
- );
- const decryptionChunkSize =
- ENCRYPTION_CHUNK_SIZE +
- sodium.crypto_secretstream_xchacha20poly1305_ABYTES;
- let bytesRead = 0;
- const decryptedData = [];
- let tag = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;
- while (tag !== sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL) {
- let chunkSize = decryptionChunkSize;
- if (bytesRead + chunkSize > data.length) {
- chunkSize = data.length - bytesRead;
- }
- const buffer = data.slice(bytesRead, bytesRead + chunkSize);
- const pullResult = sodium.crypto_secretstream_xchacha20poly1305_pull(
- pullState,
- buffer
- );
- if (!pullResult.message) {
- throw new Error(CustomError.PROCESSING_FAILED);
- }
- for (let index = 0; index < pullResult.message.length; index++) {
- decryptedData.push(pullResult.message[index]);
- }
- tag = pullResult.tag;
- bytesRead += chunkSize;
- }
- return Uint8Array.from(decryptedData);
-}
-
-export async function initChunkDecryption(header: Uint8Array, key: Uint8Array) {
- await sodium.ready;
- const pullState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(
- header,
- key
- );
- const decryptionChunkSize =
- ENCRYPTION_CHUNK_SIZE +
- sodium.crypto_secretstream_xchacha20poly1305_ABYTES;
- const tag = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;
- return { pullState, decryptionChunkSize, tag };
-}
-
-export async function decryptFileChunk(
- data: Uint8Array,
- pullState: StateAddress
-) {
- await sodium.ready;
- const pullResult = sodium.crypto_secretstream_xchacha20poly1305_pull(
- pullState,
- data
- );
- if (!pullResult.message) {
- throw new Error(CustomError.PROCESSING_FAILED);
- }
- const newTag = pullResult.tag;
- return { decryptedData: pullResult.message, newTag };
-}
-
-export async function encryptChaChaOneShot(data: Uint8Array, key: string) {
- await sodium.ready;
-
- const uintkey: Uint8Array = await fromB64(key);
- const initPushResult =
- sodium.crypto_secretstream_xchacha20poly1305_init_push(uintkey);
- const [pushState, header] = [initPushResult.state, initPushResult.header];
-
- const pushResult = sodium.crypto_secretstream_xchacha20poly1305_push(
- pushState,
- data,
- null,
- sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
- );
- return {
- key: await toB64(uintkey),
- file: {
- encryptedData: pushResult,
- decryptionHeader: await toB64(header),
- },
- };
-}
-
-export async function encryptChaCha(data: Uint8Array) {
- await sodium.ready;
-
- const uintkey: Uint8Array =
- sodium.crypto_secretstream_xchacha20poly1305_keygen();
-
- const initPushResult =
- sodium.crypto_secretstream_xchacha20poly1305_init_push(uintkey);
- const [pushState, header] = [initPushResult.state, initPushResult.header];
- let bytesRead = 0;
- let tag = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;
-
- const encryptedData = [];
-
- while (tag !== sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL) {
- let chunkSize = ENCRYPTION_CHUNK_SIZE;
- if (bytesRead + chunkSize >= data.length) {
- chunkSize = data.length - bytesRead;
- tag = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL;
- }
-
- const buffer = data.slice(bytesRead, bytesRead + chunkSize);
- bytesRead += chunkSize;
- const pushResult = sodium.crypto_secretstream_xchacha20poly1305_push(
- pushState,
- buffer,
- null,
- tag
- );
- for (let index = 0; index < pushResult.length; index++) {
- encryptedData.push(pushResult[index]);
- }
- }
- return {
- key: await toB64(uintkey),
- file: {
- encryptedData: new Uint8Array(encryptedData),
- decryptionHeader: await toB64(header),
- },
- };
-}
-
-export async function initChunkEncryption() {
- await sodium.ready;
- const key = sodium.crypto_secretstream_xchacha20poly1305_keygen();
- const initPushResult =
- sodium.crypto_secretstream_xchacha20poly1305_init_push(key);
- const [pushState, header] = [initPushResult.state, initPushResult.header];
- return {
- key: await toB64(key),
- decryptionHeader: await toB64(header),
- pushState,
- };
-}
-
-export async function encryptFileChunk(
- data: Uint8Array,
- pushState: sodium.StateAddress,
- isFinalChunk: boolean
-) {
- await sodium.ready;
- const tag = isFinalChunk
- ? sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
- : sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;
- const pushResult = sodium.crypto_secretstream_xchacha20poly1305_push(
- pushState,
- data,
- null,
- tag
- );
-
- return pushResult;
-}
-export async function encryptToB64(data: string, key: string) {
- await sodium.ready;
- const encrypted = await encrypt(await fromB64(data), await fromB64(key));
-
- return {
- encryptedData: await toB64(encrypted.encryptedData),
- key: await toB64(encrypted.key),
- nonce: await toB64(encrypted.nonce),
- } as B64EncryptionResult;
-}
-
-export async function generateKeyAndEncryptToB64(data: string) {
- await sodium.ready;
- const key = sodium.crypto_secretbox_keygen();
- return await encryptToB64(data, await toB64(key));
-}
-
-export async function encryptUTF8(data: string, key: string) {
- const b64Data = await toB64(await fromUTF8(data));
- return await encryptToB64(b64Data, key);
-}
-
-export async function decryptB64(data: string, nonce: string, key: string) {
- await sodium.ready;
- const decrypted = await decrypt(
- await fromB64(data),
- await fromB64(nonce),
- await fromB64(key)
- );
-
- return await toB64(decrypted);
-}
-
-export async function decryptToUTF8(data: string, nonce: string, key: string) {
- await sodium.ready;
- const decrypted = await decrypt(
- await fromB64(data),
- await fromB64(nonce),
- await fromB64(key)
- );
-
- return sodium.to_string(decrypted);
-}
-
-async function encrypt(data: Uint8Array, key: Uint8Array) {
- await sodium.ready;
- const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
- const encryptedData = sodium.crypto_secretbox_easy(data, nonce, key);
- return {
- encryptedData,
- key,
- nonce,
- };
-}
-
-async function decrypt(data: Uint8Array, nonce: Uint8Array, key: Uint8Array) {
- await sodium.ready;
- return sodium.crypto_secretbox_open_easy(data, nonce, key);
-}
-
-export async function initChunkHashing() {
- await sodium.ready;
- const hashState = sodium.crypto_generichash_init(
- null,
- sodium.crypto_generichash_BYTES_MAX
- );
- return hashState;
-}
-
-export async function hashFileChunk(
- hashState: sodium.StateAddress,
- chunk: Uint8Array
-) {
- await sodium.ready;
- sodium.crypto_generichash_update(hashState, chunk);
-}
-
-export async function completeChunkHashing(hashState: sodium.StateAddress) {
- await sodium.ready;
- const hash = sodium.crypto_generichash_final(
- hashState,
- sodium.crypto_generichash_BYTES_MAX
- );
- const hashString = toB64(hash);
- return hashString;
-}
-
-export async function deriveKey(
- passphrase: string,
- salt: string,
- opsLimit: number,
- memLimit: number
-) {
- await sodium.ready;
- return await toB64(
- sodium.crypto_pwhash(
- sodium.crypto_secretbox_KEYBYTES,
- await fromUTF8(passphrase),
- await fromB64(salt),
- opsLimit,
- memLimit,
- sodium.crypto_pwhash_ALG_ARGON2ID13
- )
- );
-}
-
-export async function deriveSensitiveKey(passphrase: string, salt: string) {
- await sodium.ready;
- const minMemLimit = sodium.crypto_pwhash_MEMLIMIT_MIN;
- let opsLimit = sodium.crypto_pwhash_OPSLIMIT_SENSITIVE;
- let memLimit = sodium.crypto_pwhash_MEMLIMIT_SENSITIVE;
- while (memLimit > minMemLimit) {
- try {
- const key = await deriveKey(passphrase, salt, opsLimit, memLimit);
- return {
- key,
- opsLimit,
- memLimit,
- };
- } catch (e) {
- opsLimit *= 2;
- memLimit /= 2;
- }
- }
-}
-
-export async function deriveInteractiveKey(passphrase: string, salt: string) {
- await sodium.ready;
- const key = await toB64(
- sodium.crypto_pwhash(
- sodium.crypto_secretbox_KEYBYTES,
- await fromUTF8(passphrase),
- await fromB64(salt),
- sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE,
- sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE,
- sodium.crypto_pwhash_ALG_ARGON2ID13
- )
- );
- return {
- key,
- opsLimit: sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE,
- memLimit: sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE,
- };
-}
-
-export async function generateEncryptionKey() {
- await sodium.ready;
- return await toB64(sodium.crypto_kdf_keygen());
-}
-
-export async function generateSaltToDeriveKey() {
- await sodium.ready;
- return await toB64(sodium.randombytes_buf(sodium.crypto_pwhash_SALTBYTES));
-}
-
-export async function generateKeyPair() {
- await sodium.ready;
- const keyPair: sodium.KeyPair = sodium.crypto_box_keypair();
- return {
- privateKey: await toB64(keyPair.privateKey),
- publicKey: await toB64(keyPair.publicKey),
- };
-}
-
-export async function boxSealOpen(
- input: string,
- publicKey: string,
- secretKey: string
-) {
- await sodium.ready;
- return await toB64(
- sodium.crypto_box_seal_open(
- await fromB64(input),
- await fromB64(publicKey),
- 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))
- );
-}
-
-export async function generateSubKey(
- key: string,
- subKeyLength: number,
- subKeyID: number,
- context: string
-) {
- await sodium.ready;
- return await toB64(
- sodium.crypto_kdf_derive_from_key(
- subKeyLength,
- subKeyID,
- context,
- await fromB64(key)
- )
- );
-}
-
-export async function fromB64(input: string) {
- await sodium.ready;
- return sodium.from_base64(input, sodium.base64_variants.ORIGINAL);
-}
-
-export async function toB64(input: Uint8Array) {
- await sodium.ready;
- return sodium.to_base64(input, sodium.base64_variants.ORIGINAL);
-}
-
-export async function toURLSafeB64(input: Uint8Array) {
- await sodium.ready;
- return sodium.to_base64(input, sodium.base64_variants.URLSAFE);
-}
-
-export async function fromUTF8(input: string) {
- await sodium.ready;
- return sodium.from_string(input);
-}
-
-export async function toUTF8(input: string) {
- await sodium.ready;
- return sodium.to_string(await fromB64(input));
-}
-export async function toHex(input: string) {
- await sodium.ready;
- return sodium.to_hex(await fromB64(input));
-}
-
-export async function fromHex(input: string) {
- await sodium.ready;
- return await toB64(sodium.from_hex(input));
-}
diff --git a/apps/photos/src/utils/error/index.ts b/apps/photos/src/utils/error/index.ts
deleted file mode 100644
index 7a109b002c..0000000000
--- a/apps/photos/src/utils/error/index.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-import { HttpStatusCode } from 'axios';
-
-export class ApiErrorResponse {
- code: string;
- message: string;
-}
-export class ApiError extends Error {
- httpStatusCode: number;
- errCode: string;
-
- constructor(message: string, errCode: string, httpStatus: number) {
- super(message);
- 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;
-}
-
-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',
- 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',
- 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',
- HIDDEN_COLLECTION_SYNC_FILE_ATTEMPTED:
- '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',
- CLIENT_ERROR: 'client error',
- ServerError: 'server error',
-};
-
-export function handleUploadError(error): Error {
- const parsedError = parseUploadErrorCodes(error);
-
- // breaking errors
- switch (parsedError.message) {
- case CustomError.SUBSCRIPTION_EXPIRED:
- case CustomError.STORAGE_QUOTA_EXCEEDED:
- case CustomError.SESSION_EXPIRED:
- case CustomError.UPLOAD_CANCELLED:
- throw parsedError;
- }
- return parsedError;
-}
-
-export function errorWithContext(originalError: Error, context: string) {
- const errorWithContext = new Error(context);
- errorWithContext.stack =
- errorWithContext.stack.split('\n').slice(2, 4).join('\n') +
- '\n' +
- originalError.stack;
- return errorWithContext;
-}
-
-export function parseUploadErrorCodes(error) {
- let parsedMessage = null;
- if (error instanceof ApiError) {
- switch (error.httpStatusCode) {
- case HttpStatusCode.PaymentRequired:
- parsedMessage = CustomError.SUBSCRIPTION_EXPIRED;
- break;
- case HttpStatusCode.UpgradeRequired:
- parsedMessage = CustomError.STORAGE_QUOTA_EXCEEDED;
- break;
- case HttpStatusCode.Unauthorized:
- parsedMessage = CustomError.SESSION_EXPIRED;
- break;
- case HttpStatusCode.PayloadTooLarge:
- parsedMessage = CustomError.FILE_TOO_LARGE;
- break;
- default:
- parsedMessage = `${CustomError.UNKNOWN_ERROR} statusCode:${error.httpStatusCode}`;
- }
- } else {
- parsedMessage = error.message;
- }
- return new Error(parsedMessage);
-}
-
-export const parseSharingErrorCodes = (error) => {
- let parsedMessage = null;
- if (error instanceof ApiError) {
- switch (error.httpStatusCode) {
- case HttpStatusCode.BadRequest:
- parsedMessage = CustomError.BAD_REQUEST;
- break;
- case HttpStatusCode.PaymentRequired:
- parsedMessage = CustomError.SUBSCRIPTION_NEEDED;
- break;
- case HttpStatusCode.NotFound:
- parsedMessage = CustomError.NOT_FOUND;
- break;
- case HttpStatusCode.Unauthorized:
- case HttpStatusCode.Gone:
- parsedMessage = CustomError.TOKEN_EXPIRED;
- break;
- case HttpStatusCode.TooManyRequests:
- parsedMessage = CustomError.TOO_MANY_REQUESTS;
- break;
- default:
- parsedMessage = `${CustomError.UNKNOWN_ERROR} statusCode:${error.httpStatusCode}`;
- }
- } else {
- parsedMessage = error.message;
- }
- return new Error(parsedMessage);
-};
diff --git a/apps/photos/src/utils/error/ui.ts b/apps/photos/src/utils/error/ui.ts
index bc237f8db1..3fb20cece1 100644
--- a/apps/photos/src/utils/error/ui.ts
+++ b/apps/photos/src/utils/error/ui.ts
@@ -1,6 +1,6 @@
import { t } from 'i18next';
-import { parseSharingErrorCodes, CustomError } from '.';
+import { parseSharingErrorCodes, CustomError } from '@ente/shared/error';
export const handleSharingErrors = (error) => {
const parsedError = parseSharingErrorCodes(error);
diff --git a/apps/photos/src/utils/export/index.ts b/apps/photos/src/utils/export/index.ts
index 72a12d8ea6..4228ff5428 100644
--- a/apps/photos/src/utils/export/index.ts
+++ b/apps/photos/src/utils/export/index.ts
@@ -16,7 +16,7 @@ import {
ExportStage,
} from 'constants/export';
import sanitize from 'sanitize-filename';
-import { formatDateTimeShort } from 'utils/time/format';
+import { formatDateTimeShort } from '@ente/shared/time/format';
import { getCollectionUserFacingName } from 'utils/collection';
export const getExportRecordFileUID = (file: EnteFile) =>
diff --git a/apps/photos/src/utils/ffmpeg/index.ts b/apps/photos/src/utils/ffmpeg/index.ts
index 9b4354924f..46d13af3ac 100644
--- a/apps/photos/src/utils/ffmpeg/index.ts
+++ b/apps/photos/src/utils/ffmpeg/index.ts
@@ -1,6 +1,6 @@
import { NULL_LOCATION } from 'constants/upload';
import { ParsedExtractedMetadata } from 'types/upload';
-import { validateAndGetCreationUnixTimeInMicroSeconds } from 'utils/time';
+import { validateAndGetCreationUnixTimeInMicroSeconds } from '@ente/shared/time';
enum MetadataTags {
CREATION_TIME = 'creation_time',
diff --git a/apps/photos/src/utils/file/index.ts b/apps/photos/src/utils/file/index.ts
index 1cc030f2ee..7278d1b802 100644
--- a/apps/photos/src/utils/file/index.ts
+++ b/apps/photos/src/utils/file/index.ts
@@ -12,7 +12,7 @@ import { decodeLivePhoto } from 'services/livePhotoService';
import { getFileType } from 'services/typeDetectionService';
import DownloadManager from 'services/downloadManager';
import { logError } from '@ente/shared/sentry';
-import { User } from 'types/user';
+import { User } from '@ente/shared/user/types';
import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
import { updateFileCreationDateInEXIF } from 'services/upload/exifService';
import {
@@ -31,7 +31,7 @@ import { VISIBILITY_STATE } from 'types/magicMetadata';
import { isArchivedFile, updateMagicMetadata } from 'utils/magicMetadata';
import { addLocalLog, addLogLine } from '@ente/shared/logging';
-import { CustomError } from 'utils/error';
+import { CustomError } from '@ente/shared/error';
import { convertBytesToHumanReadable } from './size';
import ComlinkCryptoWorker from '@ente/shared/crypto';
import {
diff --git a/apps/photos/src/utils/machineLearning/faceCrop.ts b/apps/photos/src/utils/machineLearning/faceCrop.ts
index 2e4d4bdc86..7cb45f367a 100644
--- a/apps/photos/src/utils/machineLearning/faceCrop.ts
+++ b/apps/photos/src/utils/machineLearning/faceCrop.ts
@@ -1,5 +1,5 @@
-import { CACHES } from 'constants/cache';
-import { CacheStorageService } from 'services/cache/cacheStorageService';
+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 {
diff --git a/apps/photos/src/utils/machineLearning/index.ts b/apps/photos/src/utils/machineLearning/index.ts
index c18514b393..065f8c00b8 100644
--- a/apps/photos/src/utils/machineLearning/index.ts
+++ b/apps/photos/src/utils/machineLearning/index.ts
@@ -36,12 +36,12 @@ import {
getFaceCropBlobFromStorage,
ibExtractFaceImagesFromCrops,
} from './faceCrop';
-import { CACHES } from 'constants/cache';
+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';
import { Remote } from 'comlink';
-import { DedicatedCryptoWorker } from 'worker/crypto.worker';
+import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';
export function f32Average(descriptors: Float32Array[]) {
if (descriptors.length < 1) {
diff --git a/apps/photos/src/utils/machineLearning/mldataExport.ts b/apps/photos/src/utils/machineLearning/mldataExport.ts
index ba01f5ebe9..ee9e6db503 100644
--- a/apps/photos/src/utils/machineLearning/mldataExport.ts
+++ b/apps/photos/src/utils/machineLearning/mldataExport.ts
@@ -1,8 +1,8 @@
import { MlFileData } from 'types/machineLearning';
import mlIDbStorage from 'utils/storage/mlIDbStorage';
import * as zip from '@zip.js/zip.js';
-import { CACHES } from 'constants/cache';
-import { CacheStorageService } from 'services/cache/cacheStorageService';
+import { CACHES } from '@ente/shared/storage/cacheStorage/constants';
+import { CacheStorageService } from '@ente/shared/storage/cacheStorage';
import { addLogLine } from '@ente/shared/logging';
class FileSystemWriter extends zip.Writer {
diff --git a/apps/photos/src/utils/time/format.ts b/apps/photos/src/utils/time/format.ts
deleted file mode 100644
index 59caefa807..0000000000
--- a/apps/photos/src/utils/time/format.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import i18n, { t } from 'i18next';
-
-const dateTimeFullFormatter1 = new Intl.DateTimeFormat(i18n.language, {
- weekday: 'short',
- month: 'short',
- day: 'numeric',
-});
-
-const dateTimeFullFormatter2 = new Intl.DateTimeFormat(i18n.language, {
- year: 'numeric',
-});
-const dateTimeShortFormatter = new Intl.DateTimeFormat(i18n.language, {
- month: 'short',
- day: 'numeric',
- year: 'numeric',
- hour: '2-digit',
- minute: '2-digit',
-});
-
-const timeFormatter = new Intl.DateTimeFormat(i18n.language, {
- timeStyle: 'short',
-});
-
-export function formatDateFull(date: number | Date) {
- return [dateTimeFullFormatter1, dateTimeFullFormatter2]
- .map((f) => f.format(date))
- .join(' ');
-}
-
-export function formatDate(date: number | Date) {
- const withinYear =
- new Date().getFullYear() === new Date(date).getFullYear();
- const dateTimeFormat2 = !withinYear ? dateTimeFullFormatter2 : null;
- return [dateTimeFullFormatter1, dateTimeFormat2]
- .filter((f) => !!f)
- .map((f) => f.format(date))
- .join(' ');
-}
-
-export function formatDateTimeShort(date: number | Date) {
- return dateTimeShortFormatter.format(date);
-}
-
-export function formatTime(date: number | Date) {
- return timeFormatter.format(date).toUpperCase();
-}
-
-export function formatDateTimeFull(dateTime: number | Date): string {
- return [formatDateFull(dateTime), t('at'), formatTime(dateTime)].join(' ');
-}
-
-export function formatDateTime(dateTime: number | Date): string {
- return [formatDate(dateTime), t('at'), formatTime(dateTime)].join(' ');
-}
-
-export function formatDateRelative(date: number) {
- const units = {
- year: 24 * 60 * 60 * 1000 * 365,
- month: (24 * 60 * 60 * 1000 * 365) / 12,
- day: 24 * 60 * 60 * 1000,
- hour: 60 * 60 * 1000,
- minute: 60 * 1000,
- second: 1000,
- };
- const relativeDateFormat = new Intl.RelativeTimeFormat(i18n.language, {
- 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')
- return relativeDateFormat.format(
- Math.round(elapsed / units[u]),
- u as Intl.RelativeTimeFormatUnit
- );
-}
diff --git a/apps/photos/src/utils/time/index.ts b/apps/photos/src/utils/time/index.ts
deleted file mode 100644
index ab175d6828..0000000000
--- a/apps/photos/src/utils/time/index.ts
+++ /dev/null
@@ -1,177 +0,0 @@
-export interface TimeDelta {
- hours?: number;
- days?: number;
- months?: number;
- years?: number;
-}
-
-interface DateComponent<T = number> {
- year: T;
- month: T;
- day: T;
- hour: T;
- minute: T;
- second: T;
-}
-
-export function getUnixTimeInMicroSecondsWithDelta(delta: TimeDelta): number {
- let currentDate = new Date();
- if (delta?.hours) {
- currentDate = _addHours(currentDate, delta.hours);
- }
- if (delta?.days) {
- currentDate = _addDays(currentDate, delta.days);
- }
- if (delta?.months) {
- currentDate = _addMonth(currentDate, delta.months);
- }
- if (delta?.years) {
- currentDate = _addYears(currentDate, delta.years);
- }
- return currentDate.getTime() * 1000;
-}
-
-export function validateAndGetCreationUnixTimeInMicroSeconds(dateTime: Date) {
- if (!dateTime || isNaN(dateTime.getTime())) {
- return null;
- }
- const unixTime = dateTime.getTime() * 1000;
- //ignoring dateTimeString = "0000:00:00 00:00:00"
- if (unixTime === Date.UTC(0, 0, 0, 0, 0, 0, 0) || unixTime === 0) {
- return null;
- } else if (unixTime > Date.now() * 1000) {
- return null;
- } else {
- return unixTime;
- }
-}
-
-function _addDays(date: Date, days: number): Date {
- const result = new Date(date);
- result.setDate(date.getDate() + days);
- return result;
-}
-
-function _addHours(date: Date, hours: number): Date {
- const result = new Date(date);
- result.setHours(date.getHours() + hours);
- return result;
-}
-
-function _addMonth(date: Date, months: number) {
- const result = new Date(date);
- result.setMonth(date.getMonth() + months);
- return result;
-}
-
-function _addYears(date: Date, years: number) {
- const result = new Date(date);
- result.setFullYear(date.getFullYear() + years);
- return result;
-}
-
-/*
-generates data component for date in format YYYYMMDD-HHMMSS
- */
-export function parseDateFromFusedDateString(dateTime: string) {
- const dateComponent: DateComponent<number> = convertDateComponentToNumber({
- year: dateTime.slice(0, 4),
- month: dateTime.slice(4, 6),
- day: dateTime.slice(6, 8),
- hour: dateTime.slice(9, 11),
- minute: dateTime.slice(11, 13),
- second: dateTime.slice(13, 15),
- });
- return validateAndGetDateFromComponents(dateComponent);
-}
-
-/* sample date format = 2018-08-19 12:34:45
- the date has six symbol separated number values
- which we would extract and use to form the date
- */
-export function tryToParseDateTime(dateTime: string): Date {
- const dateComponent = getDateComponentsFromSymbolJoinedString(dateTime);
- 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;
- return parseDateFromFusedDateString(possibleDateTime);
- }
- return validateAndGetDateFromComponents(
- convertDateComponentToNumber(dateComponent)
- );
-}
-
-function getDateComponentsFromSymbolJoinedString(
- dateTime: string
-): DateComponent<string> {
- const [year, month, day, hour, minute, second] =
- dateTime.match(/\d+/g) ?? [];
-
- return { year, month, day, hour, minute, second };
-}
-
-function validateAndGetDateFromComponents(
- dateComponent: DateComponent<number>
-) {
- let date = getDateFromComponents(dateComponent);
- if (hasTimeValues(dateComponent) && !isTimePartValid(date, dateComponent)) {
- // if the date has time values but they are not valid
- // then we remove the time values and try to validate the date
- date = getDateFromComponents(removeTimeValues(dateComponent));
- }
- if (!isDatePartValid(date, dateComponent)) {
- return null;
- }
- return date;
-}
-
-function isTimePartValid(date: Date, dateComponent: DateComponent<number>) {
- return (
- date.getHours() === dateComponent.hour &&
- date.getMinutes() === dateComponent.minute &&
- date.getSeconds() === dateComponent.second
- );
-}
-
-function isDatePartValid(date: Date, dateComponent: DateComponent<number>) {
- return (
- date.getFullYear() === dateComponent.year &&
- date.getMonth() === dateComponent.month &&
- date.getDate() === dateComponent.day
- );
-}
-
-function convertDateComponentToNumber(
- dateComponent: DateComponent<string>
-): DateComponent<number> {
- return {
- year: Number(dateComponent.year),
- // https://stackoverflow.com/questions/2552483/why-does-the-month-argument-range-from-0-to-11-in-javascripts-date-constructor
- month: Number(dateComponent.month) - 1,
- day: Number(dateComponent.day),
- hour: Number(dateComponent.hour),
- minute: Number(dateComponent.minute),
- second: Number(dateComponent.second),
- };
-}
-
-function getDateFromComponents(dateComponent: DateComponent<number>) {
- const { year, month, day, hour, minute, second } = dateComponent;
- if (hasTimeValues(dateComponent)) {
- return new Date(year, month, day, hour, minute, second);
- } else {
- return new Date(year, month, day);
- }
-}
-
-function hasTimeValues(dateComponent: DateComponent<number>) {
- const { hour, minute, second } = dateComponent;
- return !isNaN(hour) && !isNaN(minute) && !isNaN(second);
-}
-
-function removeTimeValues(
- dateComponent: DateComponent<number>
-): DateComponent<number> {
- return { ...dateComponent, hour: 0, minute: 0, second: 0 };
-}
diff --git a/apps/photos/src/utils/ui/index.tsx b/apps/photos/src/utils/ui/index.tsx
index cd36f02862..50a67d056f 100644
--- a/apps/photos/src/utils/ui/index.tsx
+++ b/apps/photos/src/utils/ui/index.tsx
@@ -1,5 +1,5 @@
import AutoAwesomeOutlinedIcon from '@mui/icons-material/AutoAwesomeOutlined';
-import { DialogBoxAttributes } from 'types/dialogBox';
+import { DialogBoxAttributes } from '@ente/shared/components/DialogBox/types';
import { downloadApp } from 'utils/common';
import { t } from 'i18next';
diff --git a/apps/photos/src/utils/user/family.ts b/apps/photos/src/utils/user/family.ts
index cb0c1691ec..d5c65f4bb1 100644
--- a/apps/photos/src/utils/user/family.ts
+++ b/apps/photos/src/utils/user/family.ts
@@ -1,4 +1,5 @@
-import { FamilyData, FamilyMember, User } from 'types/user';
+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';
diff --git a/apps/photos/src/utils/user/index.ts b/apps/photos/src/utils/user/index.ts
index 35b2a3edba..78319f7c35 100644
--- a/apps/photos/src/utils/user/index.ts
+++ b/apps/photos/src/utils/user/index.ts
@@ -1,34 +1,5 @@
-import isElectron from 'is-electron';
import { UserDetails } from 'types/user';
-import { getData, LS_KEYS, setData } from '@ente/shared/storage/localStorage';
-import ElectronAPIs from '@ente/shared/electron';
-import { Buffer } from 'buffer';
-
-export function makeID(length) {
- let result = '';
- const characters =
- 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
- const charactersLength = characters.length;
- for (let i = 0; i < length; i++) {
- result += characters.charAt(
- Math.floor(Math.random() * charactersLength)
- );
- }
- return result;
-}
-
-export async function getSentryUserID() {
- if (isElectron()) {
- return await ElectronAPIs.getSentryUserID();
- } else {
- let anonymizeUserID = getData(LS_KEYS.AnonymizedUserID)?.id;
- if (!anonymizeUserID) {
- anonymizeUserID = makeID(6);
- setData(LS_KEYS.AnonymizedUserID, { id: anonymizeUserID });
- }
- return anonymizeUserID;
- }
-}
+import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';
export function getLocalUserDetails(): UserDetails {
return getData(LS_KEYS.USER_DETAILS)?.value;
@@ -42,11 +13,3 @@ export const isInternalUser = () => {
userEmail.endsWith('@ente.io') || userEmail === '[email protected]'
);
};
-
-export const convertBufferToBase64 = (buffer: Buffer) => {
- return buffer.toString('base64');
-};
-
-export const convertBase64ToBuffer = (base64: string) => {
- return Buffer.from(base64, 'base64');
-};
diff --git a/apps/photos/src/utils/workerElectronCache/proxy.ts b/apps/photos/src/utils/workerElectronCache/proxy.ts
deleted file mode 100644
index d756cf1ecc..0000000000
--- a/apps/photos/src/utils/workerElectronCache/proxy.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-export function serializeResponse(response: Response) {
- if (response) {
- return response.arrayBuffer();
- }
-}
-
-export function deserializeToResponse(arrayBuffer: ArrayBuffer) {
- if (arrayBuffer) {
- return new Response(arrayBuffer);
- }
-}
diff --git a/apps/photos/src/utils/workerElectronCache/transferHandler.ts b/apps/photos/src/utils/workerElectronCache/transferHandler.ts
deleted file mode 100644
index 81de379e2a..0000000000
--- a/apps/photos/src/utils/workerElectronCache/transferHandler.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-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() {
- const transferHandler: Comlink.TransferHandler<Response, ArrayBuffer> = {
- canHandle: (obj): obj is Response => obj instanceof Response,
- serialize: (response: Response) => [response.arrayBuffer() as any, []],
- deserialize: (arrayBuffer: ArrayBuffer) => new Response(arrayBuffer),
- };
- return Comlink.transferHandlers.set('RESPONSE', transferHandler);
-}
diff --git a/apps/photos/src/worker/crypto.worker.ts b/apps/photos/src/worker/crypto.worker.ts
deleted file mode 100644
index f6c63cc5d4..0000000000
--- a/apps/photos/src/worker/crypto.worker.ts
+++ /dev/null
@@ -1,215 +0,0 @@
-import * as Comlink from 'comlink';
-import { StateAddress } from 'libsodium-wrappers';
-import * as libsodium from 'utils/crypto/libsodium';
-
-const textDecoder = new TextDecoder();
-const textEncoder = new TextEncoder();
-export class DedicatedCryptoWorker {
- async decryptMetadata(
- encryptedMetadata: string,
- header: string,
- key: string
- ) {
- const encodedMetadata = await libsodium.decryptChaChaOneShot(
- await libsodium.fromB64(encryptedMetadata),
- await libsodium.fromB64(header),
- key
- );
- return JSON.parse(textDecoder.decode(encodedMetadata));
- }
-
- async decryptThumbnail(
- fileData: Uint8Array,
- header: Uint8Array,
- key: string
- ) {
- return libsodium.decryptChaChaOneShot(fileData, header, key);
- }
-
- async decryptEmbedding(
- encryptedEmbedding: string,
- header: string,
- key: string
- ) {
- const encodedEmbedding = await libsodium.decryptChaChaOneShot(
- await libsodium.fromB64(encryptedEmbedding),
- await libsodium.fromB64(header),
- key
- );
- return Float32Array.from(
- JSON.parse(textDecoder.decode(encodedEmbedding))
- );
- }
-
- async decryptFile(fileData: Uint8Array, header: Uint8Array, key: string) {
- return libsodium.decryptChaCha(fileData, header, key);
- }
-
- async encryptMetadata(metadata: Object, key: string) {
- const encodedMetadata = textEncoder.encode(JSON.stringify(metadata));
-
- const { file: encryptedMetadata } =
- await libsodium.encryptChaChaOneShot(encodedMetadata, key);
- const { encryptedData, ...other } = encryptedMetadata;
- return {
- file: {
- encryptedData: await libsodium.toB64(encryptedData),
- ...other,
- },
- key,
- };
- }
-
- async encryptThumbnail(fileData: Uint8Array, key: string) {
- return libsodium.encryptChaChaOneShot(fileData, key);
- }
-
- async encryptEmbedding(embedding: Float32Array, key: string) {
- const encodedEmbedding = textEncoder.encode(
- JSON.stringify(Array.from(embedding))
- );
- const { file: encryptEmbedding } = await libsodium.encryptChaChaOneShot(
- encodedEmbedding,
- key
- );
- const { encryptedData, ...other } = encryptEmbedding;
- return {
- file: {
- encryptedData: await libsodium.toB64(encryptedData),
- ...other,
- },
- key,
- };
- }
-
- async encryptFile(fileData: Uint8Array) {
- return libsodium.encryptChaCha(fileData);
- }
-
- async encryptFileChunk(
- data: Uint8Array,
- pushState: StateAddress,
- isFinalChunk: boolean
- ) {
- return libsodium.encryptFileChunk(data, pushState, isFinalChunk);
- }
-
- async initChunkEncryption() {
- return libsodium.initChunkEncryption();
- }
-
- async initChunkDecryption(header: Uint8Array, key: Uint8Array) {
- return libsodium.initChunkDecryption(header, key);
- }
-
- async decryptFileChunk(fileData: Uint8Array, pullState: StateAddress) {
- return libsodium.decryptFileChunk(fileData, pullState);
- }
-
- async initChunkHashing() {
- return libsodium.initChunkHashing();
- }
-
- async hashFileChunk(hashState: StateAddress, chunk: Uint8Array) {
- return libsodium.hashFileChunk(hashState, chunk);
- }
-
- async completeChunkHashing(hashState: StateAddress) {
- return libsodium.completeChunkHashing(hashState);
- }
-
- async deriveKey(
- passphrase: string,
- salt: string,
- opsLimit: number,
- memLimit: number
- ) {
- return libsodium.deriveKey(passphrase, salt, opsLimit, memLimit);
- }
-
- async deriveSensitiveKey(passphrase: string, salt: string) {
- return libsodium.deriveSensitiveKey(passphrase, salt);
- }
-
- async deriveInteractiveKey(passphrase: string, salt: string) {
- return libsodium.deriveInteractiveKey(passphrase, salt);
- }
-
- async decryptB64(data: string, nonce: string, key: string) {
- return libsodium.decryptB64(data, nonce, key);
- }
-
- async decryptToUTF8(data: string, nonce: string, key: string) {
- return libsodium.decryptToUTF8(data, nonce, key);
- }
-
- async encryptToB64(data: string, key: string) {
- return libsodium.encryptToB64(data, key);
- }
-
- async generateKeyAndEncryptToB64(data: string) {
- return libsodium.generateKeyAndEncryptToB64(data);
- }
-
- async encryptUTF8(data: string, key: string) {
- return libsodium.encryptUTF8(data, key);
- }
-
- async generateEncryptionKey() {
- return libsodium.generateEncryptionKey();
- }
-
- async generateSaltToDeriveKey() {
- return libsodium.generateSaltToDeriveKey();
- }
-
- async generateKeyPair() {
- return libsodium.generateKeyPair();
- }
-
- async boxSealOpen(input: string, publicKey: string, secretKey: string) {
- return libsodium.boxSealOpen(input, publicKey, secretKey);
- }
-
- async boxSeal(input: string, publicKey: string) {
- return libsodium.boxSeal(input, publicKey);
- }
-
- async generateSubKey(
- key: string,
- subKeyLength: number,
- subKeyID: number,
- context: string
- ) {
- return libsodium.generateSubKey(key, subKeyLength, subKeyID, context);
- }
-
- async fromUTF8(string: string) {
- return libsodium.fromUTF8(string);
- }
- async toUTF8(data: string) {
- return libsodium.toUTF8(data);
- }
-
- async toB64(data: Uint8Array) {
- return libsodium.toB64(data);
- }
-
- async toURLSafeB64(data: Uint8Array) {
- return libsodium.toURLSafeB64(data);
- }
-
- async fromB64(string: string) {
- return libsodium.fromB64(string);
- }
-
- async toHex(string: string) {
- return libsodium.toHex(string);
- }
-
- async fromHex(string: string) {
- return libsodium.fromHex(string);
- }
-}
-
-Comlink.expose(DedicatedCryptoWorker, self);
diff --git a/apps/photos/tests/upload.test.ts b/apps/photos/tests/upload.test.ts
index eb10e54231..a5ff2263de 100644
--- a/apps/photos/tests/upload.test.ts
+++ b/apps/photos/tests/upload.test.ts
@@ -3,7 +3,7 @@ import { getLocalCollections } from 'services/collectionService';
import { getUserDetailsV2 } from 'services/userService';
import { groupFilesBasedOnCollectionID } from 'utils/file';
import { FILE_TYPE } from 'constants/file';
-import { tryToParseDateTime } from 'utils/time';
+import { tryToParseDateTime } from '@ente/shared/time';
const DATE_TIME_PARSING_TEST_FILE_NAMES = [
{
diff --git a/packages/shared/crypto/internal/libsodium.ts b/packages/shared/crypto/internal/libsodium.ts
index 958a2af0b7..de7e2f9c7e 100644
--- a/packages/shared/crypto/internal/libsodium.ts
+++ b/packages/shared/crypto/internal/libsodium.ts
@@ -1,7 +1,7 @@
import sodium, { StateAddress } from 'libsodium-wrappers';
-import { ENCRYPTION_CHUNK_SIZE } from 'constants/crypto';
-import { B64EncryptionResult } from 'types/crypto';
-import { CustomError } from 'utils/error';
+import { ENCRYPTION_CHUNK_SIZE } from '../constants';
+import { B64EncryptionResult } from '../types';
+import { CustomError } from '@ente/shared/error';
export async function decryptChaChaOneShot(
data: Uint8Array,
diff --git a/packages/shared/crypto/types.ts b/packages/shared/crypto/types.ts
index e591820f08..76cde83b4f 100644
--- a/packages/shared/crypto/types.ts
+++ b/packages/shared/crypto/types.ts
@@ -1,3 +1,17 @@
+import { DataStream } from '@ente/shared/upload/types';
+
+export interface LocalFileAttributes<
+ T extends string | Uint8Array | DataStream
+> {
+ encryptedData: T;
+ decryptionHeader: string;
+}
+
+export interface EncryptionResult<T extends string | Uint8Array | DataStream> {
+ file: LocalFileAttributes<T>;
+ key: string;
+}
+
export interface B64EncryptionResult {
encryptedData: string;
key: string;
diff --git a/packages/shared/storage/localStorage/helpers.ts b/packages/shared/storage/localStorage/helpers.ts
index 58cc9b1a65..fb95d04982 100644
--- a/packages/shared/storage/localStorage/helpers.ts
+++ b/packages/shared/storage/localStorage/helpers.ts
@@ -10,6 +10,8 @@ export const getToken = () => {
return token;
};
+export const getUserID = () => getData(LS_KEYS.USER)?.id;
+
export const isFirstLogin = () =>
getData(LS_KEYS.IS_FIRST_LOGIN)?.status ?? false;
diff --git a/packages/shared/upload/types.ts b/packages/shared/upload/types.ts
index d6f298491e..d9811bef99 100644
--- a/packages/shared/upload/types.ts
+++ b/packages/shared/upload/types.ts
@@ -15,3 +15,8 @@ export interface ElectronFile {
blob: () => Promise<Blob>;
arrayBuffer: () => Promise<Uint8Array>;
}
+
+export interface DataStream {
+ stream: ReadableStream<Uint8Array>;
+ chunkCount: number;
+}