π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Remove old
Manav Rathi2f5c966892b1
diff --git a/web/apps/photos/src/services/embeddingService.ts b/web/apps/photos/src/services/embeddingService.tsdeleted file mode 100644index ca1e0dd8a9..0000000000--- a/web/apps/photos/src/services/embeddingService.ts+++ /dev/null@@ -1,352 +0,0 @@-import {- getAllLocalFiles,- getLocalTrashedFiles,-} from "@/new/photos/services/files";-import type { EmbeddingModel } from "@/new/photos/services/ml/embedding";-import type { FaceIndex } from "@/new/photos/services/ml/face";-import { EnteFile } from "@/new/photos/types/file";-import { inWorker } from "@/next/env";-import log from "@/next/log";-import { apiURL } from "@/next/origins";-import { workerBridge } from "@/next/worker/worker-bridge";-import ComlinkCryptoWorker from "@ente/shared/crypto";-import { CustomError } from "@ente/shared/error";-import HTTPService from "@ente/shared/network/HTTPService";-import localForage from "@ente/shared/storage/localForage";-import { getToken } from "@ente/shared/storage/localStorage/helpers";-import type {- Embedding,- EncryptedEmbedding,- GetEmbeddingDiffResponse,- PutEmbeddingRequest,-} from "types/embedding";-import { getLocalCollections } from "./collectionService";--type FileML = FaceIndex & {- updatedAt: number;-};-const DIFF_LIMIT = 500;--/** Local storage key suffix for embedding sync times */-const embeddingSyncTimeLSKeySuffix = "embedding_sync_time";-/** Local storage key for CLIP embeddings. */-const clipEmbeddingsLSKey = "embeddings_v2";-const FILE_EMBEDING_TABLE = "file_embeddings";--/** Return all CLIP embeddings that we have available locally. */-export const localCLIPEmbeddings = async () =>- (await storedCLIPEmbeddings()).filter(({ model }) => model === "onnx-clip");--const storedCLIPEmbeddings = async () => {- const embeddings: Array<Embedding> =- await localForage.getItem<Embedding[]>(clipEmbeddingsLSKey);- if (!embeddings) {- // Migrate- await localForage.removeItem("embeddings");- await localForage.removeItem("embedding_sync_time");- await localForage.setItem(clipEmbeddingsLSKey, []);- return [];- }- return embeddings;-};--export const getFileMLEmbeddings = async (): Promise<FileML[]> => {- const embeddings: Array<FileML> =- await localForage.getItem<FileML[]>(FILE_EMBEDING_TABLE);- if (!embeddings) {- return [];- }- return embeddings;-};--const getModelEmbeddingSyncTime = async (model: EmbeddingModel) => {- return (- (await localForage.getItem<number>(- `${model}-${embeddingSyncTimeLSKeySuffix}`,- )) ?? 0- );-};--const setModelEmbeddingSyncTime = async (- model: EmbeddingModel,- time: number,-) => {- await localForage.setItem(`${model}-${embeddingSyncTimeLSKeySuffix}`, time);-};--/**- * Fetch new CLIP embeddings with the server and save them locally. Also prune- * local embeddings for any files no longer exist locally.- */-export const syncCLIPEmbeddings = async () => {- const model: EmbeddingModel = "onnx-clip";- try {- let allEmbeddings = await storedCLIPEmbeddings();- const localFiles = await getAllLocalFiles();- const hiddenAlbums = await getLocalCollections("hidden");- const localTrashFiles = await getLocalTrashedFiles();- const fileIdToKeyMap = new Map<number, string>();- const allLocalFiles = [...localFiles, ...localTrashFiles];- allLocalFiles.forEach((file) => {- fileIdToKeyMap.set(file.id, file.key);- });- await cleanupDeletedEmbeddings(- allLocalFiles,- allEmbeddings,- clipEmbeddingsLSKey,- );- log.info(`Syncing embeddings localCount: ${allEmbeddings.length}`);-- let modelLastSinceTime = await getModelEmbeddingSyncTime(model);- log.info(- `Syncing ${model} model's embeddings sinceTime: ${modelLastSinceTime}`,- );- let response: GetEmbeddingDiffResponse;- do {- response = await getEmbeddingsDiff(modelLastSinceTime, model);- if (!response.diff?.length) {- return;- }- // Note: in rare cases we might get a diff entry for an embedding- // corresponding to a file which has been deleted (but whose- // embedding is enqueued for deletion). Client should expect such a- // scenario (all it has to do is just ignore them).- 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(CustomError.FILE_NOT_FOUND);- }- const decryptedData = await worker.decryptEmbedding(- encryptedEmbedding,- decryptionHeader,- fileIdToKeyMap.get(embedding.fileID),- );-- return {- ...rest,- embedding: decryptedData,- } as Embedding;- } catch (e) {- let hasHiddenAlbums = false;- if (e.message === CustomError.FILE_NOT_FOUND) {- hasHiddenAlbums = hiddenAlbums?.length > 0;- }- log.error(- `decryptEmbedding failed for file (hasHiddenAlbums: ${hasHiddenAlbums})`,- e,- );- }- }),- );- allEmbeddings = getLatestVersionEmbeddings([- ...allEmbeddings,- ...newEmbeddings,- ]);- modelLastSinceTime = response.diff.reduce(- (max, { updatedAt }) => Math.max(max, updatedAt),- modelLastSinceTime,- );- await localForage.setItem(clipEmbeddingsLSKey, allEmbeddings);- await setModelEmbeddingSyncTime(model, modelLastSinceTime);- log.info(- `Syncing embeddings syncedEmbeddingsCount: ${allEmbeddings.length}`,- );- } while (response.diff.length > 0);- } catch (e) {- log.error("Sync embeddings failed", e);- }-};--export const syncFaceEmbeddings = async () => {- const model: EmbeddingModel = "file-ml-clip-face";- try {- let allEmbeddings: FileML[] = await getFileMLEmbeddings();- const localFiles = await getAllLocalFiles();- const hiddenAlbums = await getLocalCollections("hidden");- const localTrashFiles = await getLocalTrashedFiles();- const fileIdToKeyMap = new Map<number, string>();- const allLocalFiles = [...localFiles, ...localTrashFiles];- allLocalFiles.forEach((file) => {- fileIdToKeyMap.set(file.id, file.key);- });- await cleanupDeletedEmbeddings(- allLocalFiles,- allEmbeddings,- FILE_EMBEDING_TABLE,- );- log.info(`Syncing embeddings localCount: ${allEmbeddings.length}`);-- let modelLastSinceTime = await getModelEmbeddingSyncTime(model);- log.info(- `Syncing ${model} model's embeddings sinceTime: ${modelLastSinceTime}`,- );- let response: GetEmbeddingDiffResponse;- do {- response = await getEmbeddingsDiff(modelLastSinceTime, model);- if (!response.diff?.length) {- return;- }- const newEmbeddings = await Promise.all(- response.diff.map(async (embedding) => {- try {- const worker = await ComlinkCryptoWorker.getInstance();- const fileKey = fileIdToKeyMap.get(embedding.fileID);- if (!fileKey) {- throw Error(CustomError.FILE_NOT_FOUND);- }- const decryptedData = await worker.decryptMetadata(- embedding.encryptedEmbedding,- embedding.decryptionHeader,- fileIdToKeyMap.get(embedding.fileID),- );-- return {- ...decryptedData,- updatedAt: embedding.updatedAt,- } as unknown as FileML;- } catch (e) {- let hasHiddenAlbums = false;- if (e.message === CustomError.FILE_NOT_FOUND) {- hasHiddenAlbums = hiddenAlbums?.length > 0;- }- log.error(- `decryptEmbedding failed for file (hasHiddenAlbums: ${hasHiddenAlbums})`,- e,- );- }- }),- );- allEmbeddings = getLatestVersionFileEmbeddings([- ...allEmbeddings,- ...newEmbeddings,- ]);- modelLastSinceTime = response.diff.reduce(- (max, { updatedAt }) => Math.max(max, updatedAt),- modelLastSinceTime,- );- await localForage.setItem(FILE_EMBEDING_TABLE, allEmbeddings);- await setModelEmbeddingSyncTime(model, modelLastSinceTime);- log.info(- `Syncing embeddings syncedEmbeddingsCount: ${allEmbeddings.length}`,- );- } while (response.diff.length > 0);- } catch (e) {- log.error("Sync embeddings failed", e);- }-};--const getLatestVersionEmbeddings = (embeddings: Embedding[]) => {- const latestVersionEntities = new Map<number, Embedding>();- embeddings.forEach((embedding) => {- if (!embedding?.fileID) {- return;- }- const existingEmbeddings = latestVersionEntities.get(embedding.fileID);- if (- !existingEmbeddings ||- existingEmbeddings.updatedAt < embedding.updatedAt- ) {- latestVersionEntities.set(embedding.fileID, embedding);- }- });- return Array.from(latestVersionEntities.values());-};--const getLatestVersionFileEmbeddings = (embeddings: FileML[]) => {- const latestVersionEntities = new Map<number, FileML>();- embeddings.forEach((embedding) => {- if (!embedding?.fileID) {- return;- }- const existingEmbeddings = latestVersionEntities.get(embedding.fileID);- if (- !existingEmbeddings ||- existingEmbeddings.updatedAt < embedding.updatedAt- ) {- latestVersionEntities.set(embedding.fileID, embedding);- }- });- return Array.from(latestVersionEntities.values());-};--export const getEmbeddingsDiff = async (- sinceTime: number,- model: EmbeddingModel,-): Promise<GetEmbeddingDiffResponse> => {- try {- const token = getToken();- if (!token) {- return;- }- const response = await HTTPService.get(- await apiURL("/embeddings/diff"),- {- sinceTime,- limit: DIFF_LIMIT,- model,- },- {- "X-Auth-Token": token,- },- );- return await response.data;- } catch (e) {- log.error("get embeddings diff failed", e);- throw e;- }-};--export const putEmbedding = async (- putEmbeddingReq: PutEmbeddingRequest,-): Promise<EncryptedEmbedding> => {- try {- const token = inWorker()- ? await workerBridge.getAuthToken()- : getToken();- if (!token) {- log.info("putEmbedding failed: token not found");- throw Error(CustomError.TOKEN_MISSING);- }- const resp = await HTTPService.put(- await apiURL("/embeddings"),- putEmbeddingReq,- null,- {- "X-Auth-Token": token,- },- );- return resp.data;- } catch (e) {- log.error("put embedding failed", e);- throw e;- }-};--export const cleanupDeletedEmbeddings = async (- allLocalFiles: EnteFile[],- allLocalEmbeddings: Embedding[] | FileML[],- tableName: string,-) => {- const activeFileIds = new Set<number>();- allLocalFiles.forEach((file) => {- activeFileIds.add(file.id);- });-- const remainingEmbeddings = allLocalEmbeddings.filter((embedding) =>- activeFileIds.has(embedding.fileID),- );- if (allLocalEmbeddings.length !== remainingEmbeddings.length) {- log.info(- `cleanupDeletedEmbeddings embeddingsCount: ${allLocalEmbeddings.length} remainingEmbeddingsCount: ${remainingEmbeddings.length}`,- );- await localForage.setItem(tableName, remainingEmbeddings);- }-};diff --git a/web/apps/photos/src/types/embedding.tsx b/web/apps/photos/src/types/embedding.tsxdeleted file mode 100644index 6499a1b7d7..0000000000--- a/web/apps/photos/src/types/embedding.tsx+++ /dev/null@@ -1,29 +0,0 @@-import type { EmbeddingModel } from "@/new/photos/services/ml/embedding";--export interface EncryptedEmbedding {- fileID: number;- /** @see {@link EmbeddingModel} */- model: string;- encryptedEmbedding: string;- decryptionHeader: string;- updatedAt: number;-}--export interface Embedding- extends Omit<- EncryptedEmbedding,- "encryptedEmbedding" | "decryptionHeader"- > {- embedding?: Float32Array;-}--export interface GetEmbeddingDiffResponse {- diff: EncryptedEmbedding[];-}--export interface PutEmbeddingRequest {- fileID: number;- model: EmbeddingModel;- encryptedEmbedding: string;- decryptionHeader: string;-}diff --git a/web/packages/new/photos/services/ml/db.ts b/web/packages/new/photos/services/ml/db.tsindex 1ba61b9a10..7de44f4628 100644--- a/web/packages/new/photos/services/ml/db.ts+++ b/web/packages/new/photos/services/ml/db.ts@@ -1,4 +1,5 @@import log from "@/next/log";+import localForage from "@ente/shared/storage/localForage";import { deleteDB, openDB, type DBSchema } from "idb";import type { CLIPIndex } from "./clip";import type { EmbeddingModel } from "./embedding";@@ -136,6 +137,19 @@ const deleteLegacyDB = () => {// This code was added June 2024 (v1.7.1-rc) and can be removed once clients// have migrated over.void deleteDB("mldata");++ // Delete the legacy CLIP (mostly) related keys from LocalForage.+ //+ // This code was added July 2024 (v1.7.2-rc) and can be removed once+ // sufficient clients have migrated over (tag: Migration).+ void Promise.all([+ localForage.removeItem("embeddings"),+ localForage.removeItem("embedding_sync_time"),+ localForage.removeItem("embeddings_v2"),+ localForage.removeItem("file_embeddings"),+ localForage.removeItem("onnx-clip-embedding_sync_time"),+ localForage.removeItem("file-ml-clip-face-embedding_sync_time"),+ ]);};/**diff --git a/web/packages/new/photos/services/ml/embedding.ts b/web/packages/new/photos/services/ml/embedding.tsindex 7685f0fb7c..5c07b9e375 100644--- a/web/packages/new/photos/services/ml/embedding.ts+++ b/web/packages/new/photos/services/ml/embedding.ts@@ -49,7 +49,7 @@ import { faceIndexingVersion, type FaceIndex } from "./face";* "model" (i.e "type") field to create a new universe of embeddings.*/export type EmbeddingModel =- | "onnx-clip" /* CLIP (text) embeddings */+ | "onnx-clip" /* CLIP embeddings */| "file-ml-clip-face" /* Face embeddings */;const RemoteEmbedding = z.object({diff --git a/web/packages/next/origins.ts b/web/packages/next/origins.tsindex 13937f42c0..874c0a6aec 100644--- a/web/packages/next/origins.ts+++ b/web/packages/next/origins.ts@@ -38,8 +38,8 @@ export const apiURL = async (path: string) => (await apiOrigin()) + path;export const customAPIOrigin = async () => {let origin = await getKV("apiOrigin");if (!origin && !inWorker()) {- // TODO: Migration of apiOrigin from local storage to indexed DB- // Remove me after a bit (27 June 2024).+ // TODO: Migration of apiOrigin from local storage to indexed DB. Added+ // 27 June 2024, 1.7.2-rc. Remove me after a bit (tag: Migration).const legacyOrigin = localStorage.getItem("apiOrigin");if (legacyOrigin !== null) {origin = legacyOrigin;diff --git a/web/packages/next/worker/comlink-worker.ts b/web/packages/next/worker/comlink-worker.tsindex c9b8879695..bfc49064c8 100644--- a/web/packages/next/worker/comlink-worker.ts+++ b/web/packages/next/worker/comlink-worker.ts@@ -1,7 +1,6 @@import { ensureElectron } from "@/next/electron";import log, { logToDisk } from "@/next/log";import { expose, wrap, type Remote } from "comlink";-import { ensureLocalUser } from "../local-user";/*** A minimal wrapper for a web {@link Worker}, proxying a class of type T.@@ -62,13 +61,12 @@ export class ComlinkWorker<T extends new () => InstanceType<T>> {** Not all workers need access to all these functions, and this can indeed be* done in a more fine-grained, per-worker, manner if needed. For now, since it- * is a motley bunch, we just inject them all to all workers.+ * is just a couple, we just inject them all to all workers.*/const workerBridge = {- // Needed by all workers (likely, not necessarily).+ // Needed by all workers (likely, but not necessarily).logToDisk,- // Needed by MLWorker.- getAuthToken: () => ensureLocalUser().token,+ // Needed by ML worker.convertToJPEG: (imageData: Uint8Array) =>ensureElectron().convertToJPEG(imageData),};diff --git a/web/packages/shared/error/index.ts b/web/packages/shared/error/index.tsindex b3f16fa648..cdaf30e549 100644--- a/web/packages/shared/error/index.ts+++ b/web/packages/shared/error/index.ts@@ -70,7 +70,6 @@ export const CustomError = {TWO_FACTOR_ENABLED: "two factor enabled",CLIENT_ERROR: "client error",ServerError: "server error",- FILE_NOT_FOUND: "file not found",UPDATE_URL_FILE_ID_MISMATCH: "update url file id mismatch",URL_ALREADY_SET: "url already set",FILE_CONVERSION_FAILED: "file conversion failed",