π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Merge branch 'main' into separate-auth-app-v2
Abhinav38720887a467
diff --cc apps/auth/src/components/Navbar.tsxindex 59505efe0e,63415a3809..fd6557c472--- a/apps/auth/src/components/Navbar.tsx+++ b/apps/auth/src/components/Navbar.tsx@@@ -1,19 -1,17 +1,19 @@@-import { HorizontalFlex } from 'components/Container';-import NavbarBase from 'components/Navbar/base';+import { HorizontalFlex } from '@ente/shared/components/Container';+import NavbarBase from '@ente/shared/components/Navbar/base';import React from 'react';import { t } from 'i18next';-import { logoutUser } from 'services/userService';-import { EnteLogo } from 'components/EnteLogo';-import OverflowMenu from 'components/OverflowMenu/menu';-import { OverflowMenuOption } from 'components/OverflowMenu/option';+import { logoutUser } from '@ente/accounts/services/user';+import { EnteLogo } from '@ente/shared/components/EnteLogo';+import OverflowMenu from '@ente/shared/components/OverflowMenu/menu';- import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';++import { OverflowMenuOption } from '@ente/shared/@ente/shared/components/OverflowMenu/option';import MoreHoriz from '@mui/icons-material/MoreHoriz';import LogoutOutlined from '@mui/icons-material/LogoutOutlined';+import { AppContext } from 'pages/_app';export default function AuthNavbar() {+ const { isMobile } = React.useContext(AppContext);return (- <NavbarBase>+ <NavbarBase isMobile={isMobile}><HorizontalFlex flex={1} justifyContent={'center'}><EnteLogo /></HorizontalFlex>diff --cc apps/photos/sentry.client.config.tsindex bc0f9dae36,0000000000..2dc983f533mode 100644,000000..100644--- a/apps/photos/sentry.client.config.ts+++ b/apps/photos/sentry.client.config.ts@@@ -1,3 -1,0 +1,5 @@@+import { setupSentry } from '@ente/shared/sentry/config/sentry.config.base';+- setupSentry();++const DEFAULT_SENTRY_DSN =++ 'https://[email protected]/2';++setupSentry(DEFAULT_SENTRY_DSN);diff --cc apps/photos/src/components/Collections/CollectionListSortBy.tsxindex 3f9bde433b,3f9bde433b..ba794d3ef8--- a/apps/photos/src/components/Collections/CollectionListSortBy.tsx+++ b/apps/photos/src/components/Collections/CollectionListSortBy.tsx@@@ -1,10 -1,10 +1,10 @@@import React from 'react';import { COLLECTION_LIST_SORT_BY } from 'constants/collection';import SortIcon from '@mui/icons-material/Sort';--import OverflowMenu from 'components/OverflowMenu/menu';++import OverflowMenu from '@ente/shared/components/OverflowMenu/menu';import SvgIcon from '@mui/material/SvgIcon';import TickIcon from '@mui/icons-material/Done';--import { OverflowMenuOption } from 'components/OverflowMenu/option';++import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';import { t } from 'i18next';interface CollectionSortProps {diff --cc apps/photos/src/components/Collections/CollectionOptions/AlbumCollectionOption.tsxindex d426c66b87,d426c66b87..d699401630--- a/apps/photos/src/components/Collections/CollectionOptions/AlbumCollectionOption.tsx+++ b/apps/photos/src/components/Collections/CollectionOptions/AlbumCollectionOption.tsx@@@ -1,4 -1,4 +1,4 @@@--import { OverflowMenuOption } from 'components/OverflowMenu/option';++import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';import React from 'react';import EditIcon from '@mui/icons-material/Edit';diff --cc apps/photos/src/components/Collections/CollectionOptions/CollectionSortOrderMenu.tsxindex 465d4843ff,465d4843ff..251bdf32c0--- a/apps/photos/src/components/Collections/CollectionOptions/CollectionSortOrderMenu.tsx+++ b/apps/photos/src/components/Collections/CollectionOptions/CollectionSortOrderMenu.tsx@@@ -1,6 -1,6 +1,6 @@@--import { StyledMenu } from 'components/OverflowMenu/menu';++import { StyledMenu } from '@ente/shared/components/OverflowMenu/menu';import { CollectionActions } from '.';--import { OverflowMenuOption } from 'components/OverflowMenu/option';++import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';import { t } from 'i18next';interface Iprops {diff --cc apps/photos/src/components/Collections/CollectionOptions/OnlyDownloadCollectionOption.tsxindex 04dfa0f47e,1de0e9adad..dc4ec52b14--- a/apps/photos/src/components/Collections/CollectionOptions/OnlyDownloadCollectionOption.tsx+++ b/apps/photos/src/components/Collections/CollectionOptions/OnlyDownloadCollectionOption.tsx@@@ -1,4 -1,4 +1,4 @@@--import { OverflowMenuOption } from 'components/OverflowMenu/option';++import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';import React from 'react';import FileDownloadOutlinedIcon from '@mui/icons-material/FileDownloadOutlined';diff --cc apps/photos/src/components/Collections/CollectionOptions/SharedCollectionOption.tsxindex 7b0fd05f9c,7b0fd05f9c..40f1fbf2c1--- a/apps/photos/src/components/Collections/CollectionOptions/SharedCollectionOption.tsx+++ b/apps/photos/src/components/Collections/CollectionOptions/SharedCollectionOption.tsx@@@ -1,4 -1,4 +1,4 @@@--import { OverflowMenuOption } from 'components/OverflowMenu/option';++import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';import React from 'react';import LogoutIcon from '@mui/icons-material/Logout';import { CollectionActions } from '.';diff --cc apps/photos/src/components/Collections/CollectionOptions/TrashCollectionOption.tsxindex 66e5991d73,66e5991d73..2c0fedd147--- a/apps/photos/src/components/Collections/CollectionOptions/TrashCollectionOption.tsx+++ b/apps/photos/src/components/Collections/CollectionOptions/TrashCollectionOption.tsx@@@ -1,4 -1,4 +1,4 @@@--import { OverflowMenuOption } from 'components/OverflowMenu/option';++import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';import React from 'react';import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';diff --cc apps/photos/src/components/Collections/CollectionOptions/index.tsxindex 180c263125,acd9f16449..14c1f59179--- a/apps/photos/src/components/Collections/CollectionOptions/index.tsx+++ b/apps/photos/src/components/Collections/CollectionOptions/index.tsx@@@ -14,10 -14,10 +14,10 @@@ import { SetCollectionNamerAttributesimport { Collection } from 'types/collection';import { isArchivedCollection, isPinnedCollection } from 'utils/magicMetadata';import { GalleryContext } from 'pages/gallery';-import { logError } from 'utils/sentry';+import { logError } from '@ente/shared/sentry';import { VISIBILITY_STATE } from 'types/magicMetadata';import { AppContext } from 'pages/_app';--import OverflowMenu from 'components/OverflowMenu/menu';++import OverflowMenu from '@ente/shared/components/OverflowMenu/menu';import {ALL_SECTION,CollectionSummaryType,diff --cc apps/photos/src/components/ExportModal.tsxindex 3ae7db2269,ade4aec5be..a1a3935f1e--- a/apps/photos/src/components/ExportModal.tsx+++ b/apps/photos/src/components/ExportModal.tsx@@@ -20,10 -20,10 +20,10 @@@ import ExportInit from './ExportInit'import ExportInProgress from './ExportInProgress';import FolderIcon from '@mui/icons-material/Folder';import { ExportStage } from 'constants/export';-import DialogTitleWithCloseButton from './DialogBox/TitleWithCloseButton';+import DialogTitleWithCloseButton from '@ente/shared/components/DialogBox/TitleWithCloseButton';import MoreHoriz from '@mui/icons-material/MoreHoriz';--import OverflowMenu from './OverflowMenu/menu';--import { OverflowMenuOption } from './OverflowMenu/option';++import OverflowMenu from '@ente/shared/components/OverflowMenu/menu';++import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';import { AppContext } from 'pages/_app';import { getExportDirectoryDoesNotExistMessage } from 'utils/ui';import { t } from 'i18next';diff --cc apps/photos/src/components/Sidebar/AdvancedSettings.tsxindex 323282dd31,2e4ad404b4..a8f5113a0c--- a/apps/photos/src/components/Sidebar/AdvancedSettings.tsx+++ b/apps/photos/src/components/Sidebar/AdvancedSettings.tsx@@@ -10,8 -10,16 +10,16 @@@ import { t } from 'i18next'import { EnteMenuItem } from 'components/Menu/EnteMenuItem';import { MenuItemGroup } from 'components/Menu/MenuItemGroup';+ import isElectron from 'is-electron';-import { logError } from 'utils/sentry';++import { logError } from '@ente/shared/sentry';+ import { AppContext } from 'pages/_app';+ import { ClipService } from 'services/clipService';+ import { VerticallyCenteredFlex } from 'components/Container';+ import { ClipExtractionStatus } from 'services/clipService';+ import { formatNumber } from 'utils/number/format';export default function AdvancedSettings({ open, onClose, onRootClose }) {+ const appContext = useContext(AppContext);const [mlSearchSettingsView, setMlSearchSettingsView] = useState(false);const openMlSearchSettings = () => setMlSearchSettingsView(true);diff --cc apps/photos/src/components/WatchFolder/mappingEntry/mappingEntryOptions.tsxindex f8ae9e633d,f8ae9e633d..3b8610f616--- a/apps/photos/src/components/WatchFolder/mappingEntry/mappingEntryOptions.tsx+++ b/apps/photos/src/components/WatchFolder/mappingEntry/mappingEntryOptions.tsx@@@ -3,8 -3,8 +3,8 @@@ import { t } from 'i18next'import DoNotDisturbOutlinedIcon from '@mui/icons-material/DoNotDisturbOutlined';import MoreHorizIcon from '@mui/icons-material/MoreHoriz';--import OverflowMenu from 'components/OverflowMenu/menu';--import { OverflowMenuOption } from 'components/OverflowMenu/option';++import OverflowMenu from '@ente/shared/components/OverflowMenu/menu';++import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';interface Iprops {confirmStopWatching: () => void;diff --cc apps/photos/src/pages/_app.tsxindex 0c27c5f7d5,106423c5ff..50429a0bc5--- a/apps/photos/src/pages/_app.tsx+++ b/apps/photos/src/pages/_app.tsx@@@ -105,7 -120,9 +105,9 @@@ type AppContextType =themeColor: THEME_COLOR;setThemeColor: SetTheme;somethingWentWrong: () => void;- setDialogBoxAttributesV2: (attributes: DialogBoxAttributesV2) => void;+ setDialogBoxAttributesV2: SetDialogBoxAttributesV2;+ isCFProxyDisabled: boolean;+ setIsCFProxyDisabled: (disabled: boolean) => void;};export const AppContext = createContext<AppContextType>(null);@@@ -150,15 -171,29 +152,19 @@@ export default function App(props: EnteLS_KEYS.THEME,THEME_COLOR.DARK);+ const [isCFProxyDisabled, setIsCFProxyDisabled] = useLocalState(+ LS_KEYS.CF_PROXY_DISABLED,+ false+ );- const { name: appName, title: appTitle } = useMemo(() => {- return getAppNameAndTitle();- }, []);-useEffect(() => {+ //setup i18nsetupI18n().finally(() => setIsI18nReady(true));- }, []);-- useEffect(() => {- if (!appName) {- return;- }+ // set client package name in headersHTTPService.setHeaders({- 'X-Client-Package': CLIENT_PACKAGE_NAMES.get(appName),+ 'X-Client-Package': CLIENT_PACKAGE_NAMES.get(APPS.PHOTOS),});- }, [appName]);-- useEffect(() => {+ // setup loggingclearLogsIfLocalStorageLimitExceeded();const main = async () => {addLogLine(`userID: ${(getData(LS_KEYS.USER) as User)?.id}`);diff --cc apps/photos/src/pages/shared-albums/index.tsxindex 0348e4d5ce,f232be8ef0..e72defbb19--- a/apps/photos/src/pages/shared-albums/index.tsx+++ b/apps/photos/src/pages/shared-albums/index.tsx@@@ -55,8 -55,8 +55,8 @@@ import ComlinkCryptoWorker from 'utils/import { UploadTypeSelectorIntent } from 'types/gallery';import FileDownloadOutlinedIcon from '@mui/icons-material/FileDownloadOutlined';import MoreHoriz from '@mui/icons-material/MoreHoriz';--import OverflowMenu from 'components/OverflowMenu/menu';--import { OverflowMenuOption } from 'components/OverflowMenu/option';++import OverflowMenu from '@ente/shared/components/OverflowMenu/menu';++import { OverflowMenuOption } from '@ente/shared/components/OverflowMenu/option';import { ENTE_WEBSITE_LINK } from 'constants/urls';const defaultThumbStore = new Map();diff --cc apps/photos/src/services/clipService.tsindex 0000000000,0eecdf166b..20e62c0368mode 000000,100644..100644--- a/apps/photos/src/services/clipService.ts+++ b/apps/photos/src/services/clipService.ts@@@ -1,0 -1,391 +1,391 @@@+ import { EnteFile } from 'types/file';+ import {+ putEmbedding,+ getLatestEmbeddings,+ getLocalEmbeddings,+ } from './embeddingService';+ import { getAllLocalFiles, getLocalFiles } from './fileService';+ import { ElectronAPIs } from 'types/electron';+ import downloadManager from './downloadManager';+ import { getToken } from 'utils/common/key';+ import { Embedding, Model } from 'types/embedding';+ import ComlinkCryptoWorker from 'utils/comlink/ComlinkCryptoWorker';-import { logError } from 'utils/sentry';-import { addLogLine } from 'utils/logging';++import { logError } from '@ente/shared/sentry';++import { addLogLine } from '@ente/shared/logging';+ import { CustomError } from 'utils/error';+ import { LS_KEYS, getData } from 'utils/storage/localStorage';+ import { getPersonalFiles } from 'utils/file';+ import isElectron from 'is-electron';+ import { Events, eventBus } from './events';+ import PQueue from 'p-queue';+ import { FILE_TYPE } from 'constants/file';++ const CLIP_EMBEDDING_LENGTH = 512;++ export interface ClipExtractionStatus {+ pending: number;+ indexed: number;+ }++ class ClipServiceImpl {+ private electronAPIs: ElectronAPIs;+ private embeddingExtractionInProgress: AbortController = null;+ private reRunNeeded = false;+ private clipExtractionStatus: ClipExtractionStatus = {+ pending: 0,+ indexed: 0,+ };+ private onUpdateHandler: (status: ClipExtractionStatus) => void = null;+ private liveEmbeddingExtractionQueue: PQueue;+ private onFileUploadedHandler: (arg: {+ enteFile: EnteFile;+ localFile: globalThis.File;+ }) => void = null;++ constructor() {+ this.electronAPIs = globalThis['ElectronAPIs'];+ this.liveEmbeddingExtractionQueue = new PQueue({+ concurrency: 1,+ });+ }++ setupOnFileUploadListener = async () => {+ try {+ const isClipSupported = await this.isClipSupported();+ if (!isClipSupported) {+ return;+ }+ if (this.onFileUploadedHandler) {+ addLogLine('file upload listener already setup');+ return;+ }+ addLogLine('setting up file upload listener');+ this.onFileUploadedHandler = (args) => {+ this.runLocalFileClipExtraction(args);+ };+ eventBus.on(Events.FILE_UPLOADED, this.onFileUploadedHandler, this);+ addLogLine('setup file upload listener successfully');+ } catch (e) {+ logError(e, 'failed to setup clip service');+ }+ };++ removeOnFileUploadListener = async () => {+ try {+ if (!this.onFileUploadedHandler) {+ addLogLine('file upload listener already removed');+ return;+ }+ addLogLine('removing file upload listener');+ eventBus.removeListener(+ Events.FILE_UPLOADED,+ this.onFileUploadedHandler,+ this+ );+ this.onFileUploadedHandler = null;+ addLogLine('removed file upload listener successfully');+ } catch (e) {+ logError(e, 'failed to remove clip service');+ }+ };++ updateIndexStatus = async () => {+ try {+ addLogLine('loading local clip index status');+ this.clipExtractionStatus = await getClipExtractionStatus();+ this.onUpdateHandler(this.clipExtractionStatus);+ addLogLine('loaded local clip index status');+ } catch (e) {+ logError(e, 'failed to load local clip index status');+ }+ };++ isClipSupported = async () => {+ if (!isElectron()) {+ return false;+ }+ const platform = await this.electronAPIs.getPlatform();+ return platform !== 'windows';+ };++ setOnUpdateHandler = (handler: (status: ClipExtractionStatus) => void) => {+ this.onUpdateHandler = handler;+ handler(this.clipExtractionStatus);+ };++ scheduleImageEmbeddingExtraction = async () => {+ try {+ if (this.embeddingExtractionInProgress) {+ addLogLine(+ 'clip embedding extraction already in progress, scheduling re-run'+ );+ this.reRunNeeded = true;+ return;+ } else {+ addLogLine(+ 'clip embedding extraction not in progress, starting clip embedding extraction'+ );+ }+ const canceller = new AbortController();+ this.embeddingExtractionInProgress = canceller;+ try {+ await this.runClipEmbeddingExtraction(canceller);+ } finally {+ this.embeddingExtractionInProgress = null;+ if (!canceller.signal.aborted && this.reRunNeeded) {+ this.reRunNeeded = false;+ addLogLine('re-running clip embedding extraction');+ setTimeout(+ () => this.scheduleImageEmbeddingExtraction(),+ 0+ );+ }+ }+ } catch (e) {+ if (e.message !== CustomError.REQUEST_CANCELLED) {+ logError(e, 'failed to schedule clip embedding extraction');+ }+ }+ };++ getTextEmbedding = async (text: string): Promise<Float32Array> => {+ try {+ return this.electronAPIs.computeTextEmbedding(text);+ } catch (e) {+ logError(e, 'failed to compute text embedding');+ throw e;+ }+ };++ private runClipEmbeddingExtraction = async (canceller: AbortController) => {+ try {+ const user = getData(LS_KEYS.USER);+ if (!user) {+ return;+ }+ const localFiles = getPersonalFiles(await getAllLocalFiles(), user);+ const existingEmbeddings = await getLatestClipImageEmbeddings();+ const pendingFiles = await getNonClipEmbeddingExtractedFiles(+ localFiles,+ existingEmbeddings+ );+ this.updateClipEmbeddingExtractionStatus({+ indexed: existingEmbeddings.length,+ pending: pendingFiles.length,+ });+ if (pendingFiles.length === 0) {+ addLogLine('no clip embedding extraction needed, all done');+ return;+ }+ addLogLine(+ `starting clip embedding extraction for ${pendingFiles.length} files`+ );+ for (const file of pendingFiles) {+ try {+ addLogLine(+ `extracting clip embedding for file: ${file.metadata.title} fileID: ${file.id}`+ );+ if (canceller.signal.aborted) {+ throw Error(CustomError.REQUEST_CANCELLED);+ }+ const embeddingData =+ await this.extractFileClipImageEmbedding(file);+ addLogLine(+ `successfully extracted clip embedding for file: ${file.metadata.title} fileID: ${file.id} embedding length: ${embeddingData?.length}`+ );+ await this.encryptAndUploadEmbedding(file, embeddingData);+ this.onSuccessStatusUpdater();+ addLogLine(+ `successfully put clip embedding to server for file: ${file.metadata.title} fileID: ${file.id}`+ );+ } catch (e) {+ if (e.message !== CustomError.REQUEST_CANCELLED) {+ logError(+ e,+ 'failed to extract clip embedding for file'+ );+ }+ }+ }+ } catch (e) {+ if (e.message !== CustomError.REQUEST_CANCELLED) {+ logError(e, 'failed to extract clip embedding');+ }+ throw e;+ }+ };++ private async runLocalFileClipExtraction(arg: {+ enteFile: EnteFile;+ localFile: globalThis.File;+ }) {+ const { enteFile, localFile } = arg;+ addLogLine(+ `clip embedding extraction onFileUploadedHandler file: ${enteFile.metadata.title} fileID: ${enteFile.id}`,+ enteFile.id+ );+ if (enteFile.metadata.fileType === FILE_TYPE.VIDEO) {+ addLogLine(+ `skipping video file for clip embedding extraction file: ${enteFile.metadata.title} fileID: ${enteFile.id}`+ );+ return;+ }+ try {+ await this.liveEmbeddingExtractionQueue.add(async () => {+ const embedding = await this.extractLocalFileClipImageEmbedding(+ localFile+ );+ await this.encryptAndUploadEmbedding(enteFile, embedding);+ });+ addLogLine(+ `successfully extracted clip embedding for file: ${enteFile.metadata.title} fileID: ${enteFile.id}`+ );+ } catch (e) {+ logError(e, 'Failed in ML onFileUploadedHandler');+ }+ }++ private extractLocalFileClipImageEmbedding = async (localFile: File) => {+ const file = await localFile+ .arrayBuffer()+ .then((buffer) => new Uint8Array(buffer));+ const embedding = await this.electronAPIs.computeImageEmbedding(file);+ return embedding;+ };++ private encryptAndUploadEmbedding = async (+ file: EnteFile,+ embeddingData: Float32Array+ ) => {+ if (embeddingData?.length !== CLIP_EMBEDDING_LENGTH) {+ throw Error(+ `invalid length embedding data length: ${embeddingData?.length}`+ );+ }+ const comlinkCryptoWorker = await ComlinkCryptoWorker.getInstance();+ const { file: encryptedEmbeddingData } =+ await comlinkCryptoWorker.encryptEmbedding(embeddingData, file.key);+ addLogLine(+ `putting clip embedding to server for file: ${file.metadata.title} fileID: ${file.id}`+ );+ await putEmbedding({+ fileID: file.id,+ encryptedEmbedding: encryptedEmbeddingData.encryptedData,+ decryptionHeader: encryptedEmbeddingData.decryptionHeader,+ model: Model.GGML_CLIP,+ });+ };++ updateClipEmbeddingExtractionStatus = (status: ClipExtractionStatus) => {+ this.clipExtractionStatus = status;+ if (this.onUpdateHandler) {+ this.onUpdateHandler(status);+ }+ };++ private extractFileClipImageEmbedding = async (file: EnteFile) => {+ const token = getToken();+ if (!token) {+ return;+ }+ let thumb: Uint8Array;+ const thumbURL = await downloadManager.getCachedThumbnail(file);+ if (thumbURL) {+ thumb = await fetch(thumbURL)+ .then((response) => response.arrayBuffer())+ .then((buffer) => new Uint8Array(buffer));+ } else {+ thumb = await downloadManager.downloadThumb(token, file);+ }+ const embedding = await this.electronAPIs.computeImageEmbedding(thumb);+ return embedding;+ };++ private onSuccessStatusUpdater = () => {+ this.updateClipEmbeddingExtractionStatus({+ pending: this.clipExtractionStatus.pending - 1,+ indexed: this.clipExtractionStatus.indexed + 1,+ });+ };+ }++ export const ClipService = new ClipServiceImpl();++ const getNonClipEmbeddingExtractedFiles = async (+ files: EnteFile[],+ existingEmbeddings: Embedding[]+ ) => {+ const existingEmbeddingFileIds = new Set<number>();+ existingEmbeddings.forEach((embedding) =>+ existingEmbeddingFileIds.add(embedding.fileID)+ );+ const idSet = new Set<number>();+ return files.filter((file) => {+ if (idSet.has(file.id)) {+ return false;+ }+ if (existingEmbeddingFileIds.has(file.id)) {+ return false;+ }+ idSet.add(file.id);+ return true;+ });+ };++ export const getLocalClipImageEmbeddings = async () => {+ const allEmbeddings = await getLocalEmbeddings();+ return allEmbeddings.filter(+ (embedding) => embedding.model === Model.GGML_CLIP+ );+ };++ export const computeClipMatchScore = async (+ imageEmbedding: Float32Array,+ textEmbedding: Float32Array+ ) => {+ if (imageEmbedding.length !== textEmbedding.length) {+ throw Error('imageEmbedding and textEmbedding length mismatch');+ }+ let score = 0;+ let imageNormalization = 0;+ let textNormalization = 0;++ for (let index = 0; index < imageEmbedding.length; index++) {+ imageNormalization += imageEmbedding[index] * imageEmbedding[index];+ textNormalization += textEmbedding[index] * textEmbedding[index];+ }+ for (let index = 0; index < imageEmbedding.length; index++) {+ imageEmbedding[index] =+ imageEmbedding[index] / Math.sqrt(imageNormalization);+ textEmbedding[index] =+ textEmbedding[index] / Math.sqrt(textNormalization);+ }+ for (let index = 0; index < imageEmbedding.length; index++) {+ score += imageEmbedding[index] * textEmbedding[index];+ }+ return score;+ };++ const getLatestClipImageEmbeddings = async () => {+ const allEmbeddings = await getLatestEmbeddings();+ return allEmbeddings.filter(+ (embedding) => embedding.model === Model.GGML_CLIP+ );+ };++ const getClipExtractionStatus = async (): Promise<ClipExtractionStatus> => {+ const user = getData(LS_KEYS.USER);+ if (!user) {+ return;+ }+ const allEmbeddings = await getLocalClipImageEmbeddings();+ const localFiles = getPersonalFiles(await getLocalFiles(), user);+ const pendingFiles = await getNonClipEmbeddingExtractedFiles(+ localFiles,+ allEmbeddings+ );+ return {+ indexed: allEmbeddings.length,+ pending: pendingFiles.length,+ };+ };diff --cc apps/photos/src/services/embeddingService.tsindex 0000000000,c06f5ce933..f0a770b5a7mode 000000,100644..100644--- a/apps/photos/src/services/embeddingService.ts+++ b/apps/photos/src/services/embeddingService.ts@@@ -1,0 -1,172 +1,172 @@@+ import {+ Embedding,+ EncryptedEmbedding,+ GetEmbeddingDiffResponse,+ PutEmbeddingRequest,+ } from 'types/embedding';+ import ComlinkCryptoWorker from 'utils/comlink/ComlinkCryptoWorker';+ import { getEndpoint } from 'utils/common/apiUtil';-import { addLogLine } from 'utils/logging';-import { logError } from 'utils/sentry';++import { addLogLine } from '@ente/shared/logging';++import { logError } from '@ente/shared/sentry';+ import localForage from 'utils/storage/localForage';+ import { getAllLocalFiles } from './fileService';+ import HTTPService from './HTTPService';+ import { getToken } from 'utils/common/key';+ import { getLatestVersionEmbeddings } from 'utils/embedding';+ import { getLocalTrashedFiles } from './trashService';++ const ENDPOINT = getEndpoint();++ const DIFF_LIMIT = 500;++ const EMBEDDINGS_TABLE = 'embeddings';+ const EMBEDDING_SYNC_TIME_TABLE = 'embedding_sync_time';++ export const getLocalEmbeddings = async () => {+ const embeddings: Array<Embedding> =+ (await localForage.getItem<Embedding[]>(EMBEDDINGS_TABLE)) || [];+ return embeddings;+ };++ const getEmbeddingSyncTime = async () => {+ return (await localForage.getItem<number>(EMBEDDING_SYNC_TIME_TABLE)) ?? 0;+ };++ export const getLatestEmbeddings = async () => {+ await syncEmbeddings();+ const embeddings = await getLocalEmbeddings();+ return embeddings;+ };++ export const syncEmbeddings = async () => {+ try {+ let embeddings = await getLocalEmbeddings();+ const localFiles = await getAllLocalFiles();+ const localTrashFiles = await getLocalTrashedFiles();+ const fileIdToKeyMap = new Map<number, string>();+ [...localFiles, ...localTrashFiles].forEach((file) => {+ fileIdToKeyMap.set(file.id, file.key);+ });+ addLogLine(`Syncing embeddings localCount: ${embeddings.length}`);+ let sinceTime = await getEmbeddingSyncTime();+ addLogLine(`Syncing embeddings sinceTime: ${sinceTime}`);+ let response: GetEmbeddingDiffResponse;+ do {+ response = await getEmbeddingsDiff(sinceTime);+ if (!response.diff?.length) {+ return;+ }+ const newEmbeddings = await Promise.all(+ response.diff.map(async (embedding) => {+ try {+ const {+ encryptedEmbedding,+ decryptionHeader,+ ...rest+ } = embedding;+ const worker = await ComlinkCryptoWorker.getInstance();+ const fileKey = fileIdToKeyMap.get(embedding.fileID);+ if (!fileKey) {+ throw Error('File key not found');+ }+ const decryptedData = await worker.decryptEmbedding(+ encryptedEmbedding,+ decryptionHeader,+ fileIdToKeyMap.get(embedding.fileID)+ );++ return {+ ...rest,+ embedding: decryptedData,+ } as Embedding;+ } catch (e) {+ logError(e, 'decryptEmbedding failed for file');+ }+ })+ );+ embeddings = getLatestVersionEmbeddings([+ ...embeddings,+ ...newEmbeddings,+ ]);+ if (response.diff.length) {+ sinceTime = response.diff.slice(-1)[0].updatedAt;+ }+ await localForage.setItem(EMBEDDINGS_TABLE, embeddings);+ await localForage.setItem(EMBEDDING_SYNC_TIME_TABLE, sinceTime);+ addLogLine(+ `Syncing embeddings syncedEmbeddingsCount: ${newEmbeddings.length}`+ );+ } while (response.diff.length === DIFF_LIMIT);+ void cleanupDeletedEmbeddings();+ } catch (e) {+ logError(e, 'Sync embeddings failed');+ }+ };++ export const getEmbeddingsDiff = async (+ sinceTime: number+ ): Promise<GetEmbeddingDiffResponse> => {+ try {+ const token = getToken();+ if (!token) {+ return;+ }+ const response = await HTTPService.get(+ `${ENDPOINT}/embeddings/diff`,+ {+ sinceTime,+ limit: DIFF_LIMIT,+ },+ {+ 'X-Auth-Token': token,+ }+ );+ return await response.data;+ } catch (e) {+ logError(e, 'get embeddings diff failed');+ throw e;+ }+ };++ export const putEmbedding = async (+ putEmbeddingReq: PutEmbeddingRequest+ ): Promise<EncryptedEmbedding> => {+ try {+ const token = getToken();+ if (!token) {+ return;+ }+ const resp = await HTTPService.put(+ `${ENDPOINT}/embeddings`,+ putEmbeddingReq,+ null,+ {+ 'X-Auth-Token': token,+ }+ );+ return resp.data;+ } catch (e) {+ logError(e, 'put embedding failed');+ throw e;+ }+ };++ export const cleanupDeletedEmbeddings = async () => {+ const files = await getAllLocalFiles();+ const trashedFiles = await getLocalTrashedFiles();+ const activeFileIds = new Set<number>();+ [...files, ...trashedFiles].forEach((file) => {+ activeFileIds.add(file.id);+ });+ const embeddings = await getLocalEmbeddings();++ const remainingEmbeddings = embeddings.filter((embedding) =>+ activeFileIds.has(embedding.fileID)+ );+ if (embeddings.length !== remainingEmbeddings.length) {+ addLogLine(+ `cleanupDeletedEmbeddings embeddingsCount: ${embeddings.length} remainingEmbeddingsCount: ${remainingEmbeddings.length}`+ );+ await localForage.setItem(EMBEDDINGS_TABLE, remainingEmbeddings);+ }+ };diff --cc apps/photos/src/services/searchService.tsindex 6610a5a738,434ebd8df9..c19c786e98--- a/apps/photos/src/services/searchService.ts+++ b/apps/photos/src/services/searchService.ts@@@ -24,8 -25,13 +25,13 @@@ import { Person, Thing } from 'types/maimport { getUniqueFiles } from 'utils/file';import { getLatestEntities } from './entityService';import { LocationTag, LocationTagData, EntityType } from 'types/entity';-import { addLogLine } from 'utils/logging';+import { addLogLine } from '@ente/shared/logging';import { FILE_TYPE } from 'constants/file';+ import {+ ClipService,+ computeClipMatchScore,+ getLocalClipImageEmbeddings,+ } from './clipService';const DIGITS = new Set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']);diff --cc packages/accounts/pages/credentials.tsxindex 175df615dc,0000000000..2eccd9e06dmode 100644,000000..100644--- a/packages/accounts/pages/credentials.tsx+++ b/packages/accounts/pages/credentials.tsx@@@ -1,262 -1,0 +1,263 @@@+import { useEffect, useState } from 'react';++import { t } from 'i18next';++import {+ clearData,+ getData,+ LS_KEYS,+ setData,+} from '@ente/shared/storage/localStorage';+import { PAGES } from '../constants/pages';+import {+ SESSION_KEYS,+ getKey,+ removeKey,+ setKey,+} from '@ente/shared/storage/sessionStorage';+import {+ decryptAndStoreToken,+ generateAndSaveIntermediateKeyAttributes,+ generateLoginSubKey,+ saveKeyInSessionStore,+} from '@ente/shared/crypto/helpers';+import { generateSRPSetupAttributes } from '../services/srp';+import { logoutUser } from '../services/user';++import { configureSRP, loginViaSRP } from '../services/srp';+import { getSRPAttributes } from '../api/srp';+import { SRPAttributes } from '../types/srp';++import {+ isFirstLogin,+ setIsFirstLogin,+} from '@ente/shared/storage/localStorage/helpers';+import { KeyAttributes, User } from '@ente/shared/user/types';+import FormPaper from '@ente/shared/components/Form/FormPaper';+import FormPaperTitle from '@ente/shared/components/Form/FormPaper/Title';+import FormPaperFooter from '@ente/shared/components/Form/FormPaper/Footer';+import LinkButton from '@ente/shared/components/LinkButton';+import isElectron from 'is-electron';+import { VerticallyCentered } from '@ente/shared/components/Container';+import EnteSpinner from '@ente/shared/components/EnteSpinner';+import VerifyMasterPasswordForm, {+ VerifyMasterPasswordFormProps,+} from '@ente/shared/components/VerifyMasterPasswordForm';+// import { APPS, getAppName } from '@ente/shared/apps';+import { addLocalLog } from '@ente/shared/logging';+import ComlinkCryptoWorker from '@ente/shared/crypto';+import { B64EncryptionResult } from '@ente/shared/crypto/types';+import { CustomError } from '@ente/shared/error';+import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';+import { PageProps } from '@ente/shared/apps/types';+import { APP_HOMES } from '@ente/shared/apps/constants';+import { logError } from '@ente/shared/sentry';+import ElectronAPIs from '@ente/shared/electron';++export default function Credentials({+ appContext,+ router,+ appName,+}: PageProps) {+ const [srpAttributes, setSrpAttributes] = useState<SRPAttributes>();+ const [keyAttributes, setKeyAttributes] = useState<KeyAttributes>();+ const [user, setUser] = useState<User>();++ useEffect(() => {+ const main = async () => {+ const user: User = getData(LS_KEYS.USER);+ if (!user?.email) {+ router.push(PAGES.ROOT);+ return;+ }+ setUser(user);+ let key = getKey(SESSION_KEYS.ENCRYPTION_KEY);+ if (!key && isElectron()) {+ key = await ElectronAPIs.getEncryptionKey();+ if (key) {+ await saveKeyInSessionStore(+ SESSION_KEYS.ENCRYPTION_KEY,+ key,+ true+ );+ }+ }+ if (key) {+ router.push(APP_HOMES.get(appName));+ return;+ }+ const kekEncryptedAttributes: B64EncryptionResult = getKey(+ SESSION_KEYS.KEY_ENCRYPTION_KEY+ );+ const keyAttributes: KeyAttributes = getData(+ LS_KEYS.KEY_ATTRIBUTES+ );+ if (kekEncryptedAttributes && keyAttributes) {+ removeKey(SESSION_KEYS.KEY_ENCRYPTION_KEY);+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();+ const kek = await cryptoWorker.decryptB64(+ kekEncryptedAttributes.encryptedData,+ kekEncryptedAttributes.nonce,+ kekEncryptedAttributes.key+ );+ const key = await cryptoWorker.decryptB64(+ keyAttributes.encryptedKey,+ keyAttributes.keyDecryptionNonce,+ kek+ );+ useMasterPassword(key, kek, keyAttributes);+ return;+ }+ if (keyAttributes) {+ if (+ (!user?.token && !user?.encryptedToken) ||+ (keyAttributes && !keyAttributes.memLimit)+ ) {+ clearData();+ router.push(PAGES.ROOT);+ return;+ }+ setKeyAttributes(keyAttributes);+ return;+ }++ const srpAttributes: SRPAttributes = getData(+ LS_KEYS.SRP_ATTRIBUTES+ );+ if (srpAttributes) {+ setSrpAttributes(srpAttributes);+ } else {+ router.push(PAGES.ROOT);+ }+ };+ main();+ appContext.showNavBar(true);+ }, []);++ const getKeyAttributes: VerifyMasterPasswordFormProps['getKeyAttributes'] =+ async (kek: string) => {+ try {+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();- const response = await loginViaSRP(srpAttributes, kek);- if (response.twoFactorSessionID) {- const { twoFactorSessionID } = response;++ const {++ keyAttributes,++ encryptedToken,++ token,++ id,++ twoFactorSessionID,++ } = await loginViaSRP(srpAttributes, kek);++ setIsFirstLogin(true);++ if (twoFactorSessionID) {+ const sessionKeyAttributes =+ await cryptoWorker.generateKeyAndEncryptToB64(kek);+ setKey(+ SESSION_KEYS.KEY_ENCRYPTION_KEY,+ sessionKeyAttributes+ );+ const user = getData(LS_KEYS.USER);+ setData(LS_KEYS.USER, {+ ...user,+ twoFactorSessionID,+ isTwoFactorEnabled: true,+ });- setIsFirstLogin(true);+ router.push(PAGES.TWO_FACTOR_VERIFY);+ throw Error(CustomError.TWO_FACTOR_ENABLED);+ } else {- const { token, encryptedToken, id, keyAttributes } =- response;+ const user = getData(LS_KEYS.USER);+ setData(LS_KEYS.USER, {+ ...user,+ token,+ encryptedToken,+ id,+ isTwoFactorEnabled: false,+ });- if (keyAttributes) {- setData(LS_KEYS.KEY_ATTRIBUTES, keyAttributes);- }++ setData(LS_KEYS.KEY_ATTRIBUTES, keyAttributes);+ return keyAttributes;+ }+ } catch (e) {+ if (e.message !== CustomError.TWO_FACTOR_ENABLED) {+ logError(e, 'getKeyAttributes failed');+ }+ throw e;+ }+ };++ const useMasterPassword: VerifyMasterPasswordFormProps['callback'] = async (+ key,+ kek,+ keyAttributes,+ passphrase+ ) => {+ try {+ if (isFirstLogin() && passphrase) {+ await generateAndSaveIntermediateKeyAttributes(+ passphrase,+ keyAttributes,+ key+ );+ }+ await saveKeyInSessionStore(SESSION_KEYS.ENCRYPTION_KEY, key);+ await decryptAndStoreToken(keyAttributes, key);+ try {+ let srpAttributes: SRPAttributes = getData(+ LS_KEYS.SRP_ATTRIBUTES+ );+ if (!srpAttributes) {+ srpAttributes = await getSRPAttributes(user.email);+ if (srpAttributes) {+ setData(LS_KEYS.SRP_ATTRIBUTES, srpAttributes);+ }+ }+ addLocalLog(() => `userSRPSetupPending ${!srpAttributes}`);+ if (!srpAttributes) {+ const loginSubKey = await generateLoginSubKey(kek);+ const srpSetupAttributes = await generateSRPSetupAttributes(+ loginSubKey+ );+ await configureSRP(srpSetupAttributes);+ }+ } catch (e) {+ logError(e, 'migrate to srp failed');+ }+ const redirectURL = InMemoryStore.get(MS_KEYS.REDIRECT_URL);+ InMemoryStore.delete(MS_KEYS.REDIRECT_URL);+ router.push(APP_HOMES.get(redirectURL ?? appName));+ } catch (e) {+ logError(e, 'useMasterPassword failed');+ }+ };++ const redirectToRecoverPage = () => router.push(PAGES.RECOVER);++ if (!keyAttributes && !srpAttributes) {+ return (+ <VerticallyCentered>+ <EnteSpinner />+ </VerticallyCentered>+ );+ }++ return (+ <VerticallyCentered>+ <FormPaper style={{ minWidth: '320px' }}>+ <FormPaperTitle>{t('PASSWORD')}</FormPaperTitle>++ <VerifyMasterPasswordForm+ buttonText={t('VERIFY_PASSPHRASE')}+ callback={useMasterPassword}+ user={user}+ keyAttributes={keyAttributes}+ getKeyAttributes={getKeyAttributes}+ srpAttributes={srpAttributes}+ />+ <FormPaperFooter style={{ justifyContent: 'space-between' }}>+ <LinkButton onClick={redirectToRecoverPage}>+ {t('FORGOT_PASSWORD')}+ </LinkButton>+ <LinkButton onClick={logoutUser}>+ {t('CHANGE_EMAIL')}+ </LinkButton>+ </FormPaperFooter>+ </FormPaper>+ </VerticallyCentered>+ );+}diff --cc packages/shared/storage/localStorage/index.tsindex 3d807d05cc,0000000000..d9a61e9927mode 100644,000000..100644--- a/packages/shared/storage/localStorage/index.ts+++ b/packages/shared/storage/localStorage/index.ts@@@ -1,67 -1,0 +1,68 @@@+import { logError } from '@ente/shared/sentry';++export enum LS_KEYS {+ USER = 'user',+ SESSION = 'session',+ KEY_ATTRIBUTES = 'keyAttributes',+ ORIGINAL_KEY_ATTRIBUTES = 'originalKeyAttributes',+ SUBSCRIPTION = 'subscription',+ FAMILY_DATA = 'familyData',+ PLANS = 'plans',+ IS_FIRST_LOGIN = 'isFirstLogin',+ JUST_SIGNED_UP = 'justSignedUp',+ SHOW_BACK_BUTTON = 'showBackButton',+ EXPORT = 'export',+ AnonymizedUserID = 'anonymizedUserID',+ THUMBNAIL_FIX_STATE = 'thumbnailFixState',+ LIVE_PHOTO_INFO_SHOWN_COUNT = 'livePhotoInfoShownCount',+ LOGS = 'logs',+ USER_DETAILS = 'userDetails',+ COLLECTION_SORT_BY = 'collectionSortBy',+ THEME = 'theme',+ WAIT_TIME = 'waitTime',+ API_ENDPOINT = 'apiEndpoint',+ LOCALE = 'locale',+ MAP_ENABLED = 'mapEnabled',+ SRP_SETUP_ATTRIBUTES = 'srpSetupAttributes',+ SRP_ATTRIBUTES = 'srpAttributes',+ OPT_OUT_OF_CRASH_REPORTS = 'optOutOfCrashReports',++ CF_PROXY_DISABLED = 'cfProxyDisabled',+}++export const setData = (key: LS_KEYS, value: object) => {+ if (typeof localStorage === 'undefined') {+ return null;+ }+ localStorage.setItem(key, JSON.stringify(value));+};++export const removeData = (key: LS_KEYS) => {+ if (typeof localStorage === 'undefined') {+ return null;+ }+ localStorage.removeItem(key);+};++export const getData = (key: LS_KEYS) => {+ try {+ if (+ typeof localStorage === 'undefined' ||+ typeof key === 'undefined' ||+ typeof localStorage.getItem(key) === 'undefined' ||+ localStorage.getItem(key) === 'undefined'+ ) {+ return null;+ }+ const data = localStorage.getItem(key);+ return data && JSON.parse(data);+ } catch (e) {+ logError(e, 'Failed to Parse JSON for key ' + key);+ }+};++export const clearData = () => {+ if (typeof localStorage === 'undefined') {+ return null;+ }+ localStorage.clear();+};