π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Cleanup
Manav Rathic66a74d1c705
diff --git a/web/packages/new/photos/services/ml/face.worker.ts b/web/packages/new/photos/services/ml/face.worker.tsdeleted file mode 100644index d313ecfe09..0000000000--- a/web/packages/new/photos/services/ml/face.worker.ts+++ /dev/null@@ -1,33 +0,0 @@-import downloadManager from "@/new/photos/services/download";-import type { EnteFile } from "@/new/photos/types/file";-import { expose } from "comlink";-import mlService from "./machineLearningService";--export class DedicatedMLWorker {- public async closeLocalSyncContext() {- return mlService.closeLocalSyncContext();- }-- public async syncLocalFile(- token: string,- userID: number,- userAgent: string,- enteFile: EnteFile,- localFile: globalThis.File,- ) {- return mlService.syncLocalFile(- token,- userID,- userAgent,- enteFile,- localFile,- );- }-- public async sync(token: string, userID: number, userAgent: string) {- await downloadManager.init(token);- return mlService.sync(token, userID, userAgent);- }-}--expose(DedicatedMLWorker, self);diff --git a/web/packages/new/photos/services/ml/index.ts b/web/packages/new/photos/services/ml/index.tsindex 8d746b3e01..af862b1633 100644--- a/web/packages/new/photos/services/ml/index.ts+++ b/web/packages/new/photos/services/ml/index.ts@@ -1,5 +1,5 @@/**- * @file Main thread interface to {@link MLWorker}.+ * @file Main thread interface to the ML subsystem.*/import { FILE_TYPE } from "@/media/file-type";@@ -7,23 +7,16 @@ import {isBetaUser,isInternalUser,} from "@/new/photos/services/feature-flags";-import {- getAllLocalFiles,- getLocalTrashedFiles,-} from "@/new/photos/services/files";import {clearFaceDB,faceIndex,- indexableFileIDs,indexedAndIndexableCounts,- updateAssumingLocalFiles,} from "@/new/photos/services/ml/db";import type { EnteFile } from "@/new/photos/types/file";import { clientPackageName } from "@/next/app";import { ensureElectron } from "@/next/electron";import log from "@/next/log";import { ComlinkWorker } from "@/next/worker/comlink-worker";-import { ensure } from "@/utils/ensure";import { MLWorker } from "./worker";/**@@ -237,37 +230,3 @@ export const unidentifiedFaceIDs = async (const index = await faceIndex(enteFile.id);return index?.faceEmbedding.faces.map((f) => f.faceID) ?? [];};--/**- * Sync face DB with the local (and potentially indexable) files that we know- * about. Then return the next {@link count} files that still need to be- * indexed.- *- * For specifics of what a "sync" entails, see {@link updateAssumingLocalFiles}.- *- * @param userID Sync only files owned by a {@link userID} with the face DB.- *- * @param count Limit the resulting list of indexable files to {@link count}.- */-// TODO-ML: Move to worker-export const syncWithLocalFilesAndGetFilesToIndex = async (- userID: number,- count: number,-): Promise<EnteFile[]> => {- const isIndexable = (f: EnteFile) => f.ownerID == userID;-- const localFiles = await getAllLocalFiles();- const localFilesByID = new Map(- localFiles.filter(isIndexable).map((f) => [f.id, f]),- );-- const localTrashFileIDs = (await getLocalTrashedFiles()).map((f) => f.id);-- await updateAssumingLocalFiles(- Array.from(localFilesByID.keys()),- localTrashFileIDs,- );-- const fileIDsToIndex = await indexableFileIDs(count);- return fileIDsToIndex.map((id) => ensure(localFilesByID.get(id)));-};diff --git a/web/packages/new/photos/services/ml/machineLearningService.ts b/web/packages/new/photos/services/ml/machineLearningService.tsdeleted file mode 100644index 54c54dcce7..0000000000--- a/web/packages/new/photos/services/ml/machineLearningService.ts+++ /dev/null@@ -1,221 +0,0 @@-import type { EnteFile } from "@/new/photos/types/file";-import log from "@/next/log";-import { CustomError, parseUploadErrorCodes } from "@ente/shared/error";-import PQueue from "p-queue";-import { syncWithLocalFilesAndGetFilesToIndex } from ".";-import { index } from "./worker";--const batchSize = 200;--class MLSyncContext {- public token: string;- public userID: number;- public userAgent: string;-- public localFilesMap: Map<number, EnteFile> | undefined;- public outOfSyncFiles: EnteFile[];- public nSyncedFiles: number;- public error?: unknown;-- public syncQueue: PQueue;-- constructor(token: string, userID: number, userAgent: string) {- this.token = token;- this.userID = userID;- this.userAgent = userAgent;-- this.outOfSyncFiles = [];- this.nSyncedFiles = 0;-- const concurrency = getConcurrency();- this.syncQueue = new PQueue({ concurrency });- }-- public async dispose() {- this.localFilesMap = undefined;- await this.syncQueue.onIdle();- this.syncQueue.removeAllListeners();- }-}--const getConcurrency = () =>- Math.max(2, Math.ceil(navigator.hardwareConcurrency / 2));--class MachineLearningService {- private localSyncContext: Promise<MLSyncContext> | undefined;- private syncContext: Promise<MLSyncContext> | undefined;-- public async sync(- token: string,- userID: number,- userAgent: string,- ): Promise<boolean> {- if (!token) {- throw Error("Token needed by ml service to sync file");- }-- const syncContext = await this.getSyncContext(token, userID, userAgent);-- syncContext.outOfSyncFiles = await syncWithLocalFilesAndGetFilesToIndex(- userID,- batchSize,- );-- if (syncContext.outOfSyncFiles.length > 0) {- await this.syncFiles(syncContext);- }-- const error = syncContext.error;- const nOutOfSyncFiles = syncContext.outOfSyncFiles.length;- return !error && nOutOfSyncFiles > 0;- }-- private async syncFiles(syncContext: MLSyncContext) {- try {- const functions = syncContext.outOfSyncFiles.map(- (outOfSyncfile) => async () => {- await this.syncFileWithErrorHandler(- syncContext,- outOfSyncfile,- );- // TODO: just store file and faces count in syncContext- },- );- syncContext.syncQueue.on("error", () => {- syncContext.syncQueue.clear();- });- await syncContext.syncQueue.addAll(functions);- } catch (error) {- console.error("Error in sync job: ", error);- syncContext.error = error;- }- await syncContext.syncQueue.onIdle();- }-- private async getSyncContext(- token: string,- userID: number,- userAgent: string,- ) {- if (!this.syncContext) {- log.info("Creating syncContext");-- // TODO-ML(MR): Keep as promise for now.- this.syncContext = new Promise((resolve) => {- resolve(new MLSyncContext(token, userID, userAgent));- });- } else {- log.info("reusing existing syncContext");- }- return this.syncContext;- }-- // private async getLocalSyncContext(- // token: string,- // userID: number,- // userAgent: string,- // ) {- // // TODO-ML(MR): This is updating the file ML version. verify.- // if (!this.localSyncContext) {- // log.info("Creating localSyncContext");- // // TODO-ML(MR):- // this.localSyncContext = new Promise((resolve) => {- // resolve(new MLSyncContext(token, userID, userAgent));- // });- // } else {- // log.info("reusing existing localSyncContext");- // }- // return this.localSyncContext;- // }-- public async closeLocalSyncContext() {- if (this.localSyncContext) {- log.info("Closing localSyncContext");- const syncContext = await this.localSyncContext;- await syncContext.dispose();- this.localSyncContext = undefined;- }- }-- public async syncLocalFile(- // eslint-disable-next-line @typescript-eslint/no-unused-vars- _: string,- // token: string,- // eslint-disable-next-line @typescript-eslint/no-unused-vars- __: number,- // userID: number,- // eslint-disable-next-line @typescript-eslint/no-unused-vars- ___: string,- // userAgent: string,- // eslint-disable-next-line @typescript-eslint/no-unused-vars- ____: EnteFile,- // enteFile: EnteFile,- // eslint-disable-next-line @typescript-eslint/no-unused-vars- _____?: globalThis.File,- // localFile?: globalThis.File,- ) {- /* TODO-ML(MR): Currently not used- const syncContext = await this.getLocalSyncContext(- token,- userID,- userAgent,- );-- try {- await this.syncFileWithErrorHandler(- syncContext,- enteFile,- localFile,- );-- if (syncContext.nSyncedFiles >= batchSize) {- await this.closeLocalSyncContext();- }- // await syncContext.dispose();- } catch (e) {- console.error("Error while syncing local file: ", enteFile.id, e);- }- */- }-- private async syncFileWithErrorHandler(- syncContext: MLSyncContext,- enteFile: EnteFile,- localFile?: globalThis.File,- ) {- try {- await this.syncFile(enteFile, localFile, syncContext.userAgent);- syncContext.nSyncedFiles += 1;- } catch (e) {- let error = e;- // eslint-disable-next-line @typescript-eslint/no-explicit-any- if ("status" in (error as any)) {- const parsedMessage = parseUploadErrorCodes(error);- error = parsedMessage;- }- if (error instanceof Error) {- // TODO: throw errors not related to specific file- // sync job run should stop after these errors- // don't persist these errors against file,- // can include indexeddb/cache errors too- switch (error.message) {- case CustomError.SESSION_EXPIRED:- case CustomError.NETWORK_ERROR:- throw error;- }- }-- syncContext.nSyncedFiles += 1;- }- }-- private async syncFile(- enteFile: EnteFile,- file: File | undefined,- userAgent: string,- ) {- await index(enteFile, file, userAgent);- }-}--export default new MachineLearningService();diff --git a/web/packages/new/photos/services/ml/mlWorkManager.ts b/web/packages/new/photos/services/ml/mlWorkManager.tsdeleted file mode 100644index 3487af4da3..0000000000--- a/web/packages/new/photos/services/ml/mlWorkManager.ts+++ /dev/null@@ -1,359 +0,0 @@-import { FILE_TYPE } from "@/media/file-type";-import type { EnteFile } from "@/new/photos/types/file";-import { clientPackageName } from "@/next/app";-import { ensureElectron } from "@/next/electron";-import log from "@/next/log";-import { ComlinkWorker } from "@/next/worker/comlink-worker";-import { wait } from "@/utils/promise";-import { Events, eventBus } from "@ente/shared/events";-import { getToken, getUserID } from "@ente/shared/storage/localStorage/helpers";-import debounce from "debounce";-import PQueue from "p-queue";-import type { DedicatedMLWorker } from "./face.worker";--export type JobState = "Scheduled" | "Running" | "NotScheduled";--const createFaceWebWorker = () =>- new Worker(new URL("face.worker.ts", import.meta.url));--const createFaceComlinkWorker = (name: string) =>- new ComlinkWorker<typeof DedicatedMLWorker>(name, createFaceWebWorker());--export class MLSyncJob {- private runCallback: () => Promise<boolean>;- private state: JobState;- private stopped: boolean;- private intervalSec = 5;- private nextTimeoutId: ReturnType<typeof setTimeout> | undefined;-- constructor(runCallback: () => Promise<boolean>) {- this.runCallback = runCallback;- this.state = "NotScheduled";- this.stopped = true;- this.resetInterval();- }-- public resetInterval() {- this.intervalSec = 5;- }-- public start() {- this.stopped = false;- this.resetInterval();- if (this.state !== "Running") {- this.scheduleNext();- } else {- log.info("Job already running, not scheduling");- }- }-- private scheduleNext() {- if (this.state === "Scheduled" || this.nextTimeoutId) {- this.clearScheduled();- }-- this.nextTimeoutId = setTimeout(- () => this.run(),- this.intervalSec * 1000,- );- this.state = "Scheduled";- log.info("Scheduled next job after: ", this.intervalSec);- }-- async run() {- this.nextTimeoutId = undefined;- this.state = "Running";-- try {- if (await this.runCallback()) {- this.resetInterval();- } else {- this.intervalSec = Math.min(960, this.intervalSec * 2);- }- } catch (e) {- console.error("Error while running Job: ", e);- } finally {- this.state = "NotScheduled";- !this.stopped && this.scheduleNext();- }- }-- // currently client is responsible to terminate running job- public stop() {- this.stopped = true;- this.clearScheduled();- }-- private clearScheduled() {- clearTimeout(this.nextTimeoutId);- this.nextTimeoutId = undefined;- this.state = "NotScheduled";- log.info("Cleared next job");- }-}--class MLWorkManager {- private mlSyncJob: MLSyncJob | undefined;- private syncJobWorker: ComlinkWorker<typeof DedicatedMLWorker> | undefined;-- private debouncedLiveSyncIdle: () => void;- private debouncedFilesUpdated: () => void;-- private liveSyncQueue: PQueue;- private liveSyncWorker: ComlinkWorker<typeof DedicatedMLWorker> | undefined;- private mlSearchEnabled: boolean;-- public isSyncing = false;-- constructor() {- this.liveSyncQueue = new PQueue({- concurrency: 1,- // TODO: temp, remove- timeout: 300 * 1000,- throwOnTimeout: true,- });- this.mlSearchEnabled = false;-- this.debouncedLiveSyncIdle = debounce(- () => void this.onLiveSyncIdle(),- 30 * 1000,- );- this.debouncedFilesUpdated = debounce(- () =>- void (this.mlSearchEnabled && this.localFilesUpdatedHandler()),- 30 * 1000,- );- }-- public isMlSearchEnabled() {- return this.mlSearchEnabled;- }-- public async setMlSearchEnabled(enabled: boolean) {- if (!this.mlSearchEnabled && enabled) {- log.info("Enabling MLWorkManager");- this.mlSearchEnabled = true;-- logQueueStats(this.liveSyncQueue, "livesync");- this.liveSyncQueue.on("idle", this.debouncedLiveSyncIdle, this);-- eventBus.on(- Events.FILE_UPLOADED,- this.fileUploadedHandler.bind(this),- this,- );- eventBus.on(- Events.LOCAL_FILES_UPDATED,- this.debouncedFilesUpdated,- this,- );-- // TODO-ML:- // await this.startSyncJob();- await wait(0);- } else if (this.mlSearchEnabled && !enabled) {- log.info("Disabling MLWorkManager");- this.mlSearchEnabled = false;-- this.liveSyncQueue.removeAllListeners();-- eventBus.removeListener(- Events.FILE_UPLOADED,- this.fileUploadedHandler.bind(this),- this,- );- eventBus.removeListener(- Events.LOCAL_FILES_UPDATED,- this.debouncedFilesUpdated,- this,- );-- this.stopSyncJob();- }- }-- async logout() {- await this.setMlSearchEnabled(false);- this.stopSyncJob();- this.mlSyncJob = undefined;- await this.terminateLiveSyncWorker();- }-- private async fileUploadedHandler(arg: {- enteFile: EnteFile;- localFile: globalThis.File;- }) {- if (!this.mlSearchEnabled) {- return;- }- log.info("fileUploadedHandler: ", arg.enteFile.id);- if (arg.enteFile.metadata.fileType !== FILE_TYPE.IMAGE) {- log.info("Skipping non image file for local file processing");- return;- }- try {- await this.syncLocalFile(arg.enteFile, arg.localFile);- } catch (error) {- console.error("Error in syncLocalFile: ", arg.enteFile.id, error);- this.liveSyncQueue.clear();- // logError(e, 'Failed in ML fileUploaded Handler');- }- }-- private async localFilesUpdatedHandler() {- log.info("Local files updated");- await this.startSyncJob();- }-- // Live Sync- // private async getLiveSyncWorker() {- // if (!this.liveSyncWorker) {- // this.liveSyncWorker = createFaceComlinkWorker("ml-sync-live");- // }-- // return await this.liveSyncWorker.remote;- // }-- private async terminateLiveSyncWorker() {- if (!this.liveSyncWorker) {- return;- }- try {- const liveSyncWorker = await this.liveSyncWorker.remote;- await liveSyncWorker.closeLocalSyncContext();- } catch (error) {- console.error(- "Error while closing local sync context, terminating worker",- error,- );- }- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition- this.liveSyncWorker?.terminate();- this.liveSyncWorker = undefined;- }-- private async onLiveSyncIdle() {- log.info("Live sync idle");- await this.terminateLiveSyncWorker();- await (this.mlSearchEnabled && this.startSyncJob());- }-- // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/require-await- public async syncLocalFile(_: EnteFile, __: globalThis.File) {- return;- /*- TODO-ML(MR): Disable live sync for now- await this.liveSyncQueue.add(async () => {- this.stopSyncJob();- const token = getToken();- const userID = getUserID();- const userAgent = await getUserAgent();- const mlWorker = await this.getLiveSyncWorker();- return mlWorker.syncLocalFile(- token,- userID,- userAgent,- enteFile,- localFile,- );- });- */- }-- // Sync Job- private async getSyncJobWorker() {- if (!this.syncJobWorker) {- this.syncJobWorker = createFaceComlinkWorker("ml-sync-job");- }-- return await this.syncJobWorker.remote;- }-- private terminateSyncJobWorker() {- this.syncJobWorker?.terminate();- this.syncJobWorker = undefined;- }-- /**- * Returns `false` to indicate that either an error occurred, or there are- * not more files to process, or that we cannot currently process files.- *- * Which means that when it returns true, all is well and there are more- * things pending to process, so we should chug along at full speed.- */- private async runMLSyncJob(): Promise<boolean> {- this.isSyncing = true;- try {- // TODO: skipping is not required if we are caching chunks through service worker- // currently worker chunk itself is not loaded when network is not there- if (!navigator.onLine) {- log.info(- "Skipping ml-sync job run as not connected to internet.",- );- return false;- }-- const token = getToken();- const userID = getUserID() as number;- const userAgent = await getUserAgent();- const jobWorkerProxy = await this.getSyncJobWorker();-- return await jobWorkerProxy.sync(token, userID, userAgent);- // this.terminateSyncJobWorker();- // TODO: redirect/refresh to gallery in case of session_expired, stop ml sync job- } catch (e) {- log.error("Failed to run MLSync Job", e);- } finally {- this.isSyncing = false;- }- return false;- }-- // eslint-disable-next-line @typescript-eslint/require-await- public async startSyncJob() {- try {- log.info("MLWorkManager.startSyncJob");- if (!this.mlSearchEnabled) {- log.info("ML Search disabled, not starting ml sync job");- return;- }- if (!getToken()) {- log.info("User not logged in, not starting ml sync job");- return;- }- if (!this.mlSyncJob) {- this.mlSyncJob = new MLSyncJob(() => this.runMLSyncJob());- }- this.mlSyncJob.start();- } catch (e) {- log.error("Failed to start MLSync Job", e);- }- }-- public stopSyncJob() {- try {- log.info("MLWorkManager.stopSyncJob");- this.mlSyncJob?.stop();- this.terminateSyncJobWorker();- } catch (e) {- log.error("Failed to stop MLSync Job", e);- }- }-}--export default new MLWorkManager();--export function logQueueStats(queue: PQueue, name: string) {- queue.on("active", () =>- log.info(- `queuestats: ${name}: Active, Size: ${queue.size} Pending: ${queue.pending}`,- ),- );- queue.on("idle", () => log.info(`queuestats: ${name}: Idle`));- queue.on("error", (error) =>- console.error(`queuestats: ${name}: Error, `, error),- );-}--const getUserAgent = async () =>- `${clientPackageName}/${await ensureElectron().appVersion()}`;diff --git a/web/packages/new/photos/services/ml/worker.ts b/web/packages/new/photos/services/ml/worker.tsindex 0915c20138..c8c5752fa4 100644--- a/web/packages/new/photos/services/ml/worker.ts+++ b/web/packages/new/photos/services/ml/worker.ts@@ -1,5 +1,10 @@import downloadManager from "@/new/photos/services/download";-import { markIndexingFailed, saveFaceIndex } from "@/new/photos/services/ml/db";+import {+ indexableFileIDs,+ markIndexingFailed,+ saveFaceIndex,+ updateAssumingLocalFiles,+} from "@/new/photos/services/ml/db";import type { FaceIndex } from "@/new/photos/services/ml/types";import type { EnteFile } from "@/new/photos/types/file";import { getKVN } from "@/next/kv";@@ -8,8 +13,8 @@ import log from "@/next/log";import { ensure } from "@/utils/ensure";import { wait } from "@/utils/promise";import { expose } from "comlink";-import { syncWithLocalFilesAndGetFilesToIndex } from ".";import { fileLogID } from "../../utils/file";+import { getAllLocalFiles, getLocalTrashedFiles } from "../files";import { pullFaceEmbeddings, putFaceIndex } from "./embedding";import { indexFaces } from "./index-face";@@ -116,7 +121,7 @@ export class MLWorker {this.liveQ.push(file);this.wakeUp();} else {- log.debug(() => "Ignoring liveQ item since liveQ is full");+ log.debug(() => "Ignoring live item since liveQ is full");}}@@ -214,6 +219,39 @@ const indexNextBatch = async (userAgent: string, liveQ: EnteFile[]) => {return allSuccess;};+/**+ * Sync face DB with the local (and potentially indexable) files that we know+ * about. Then return the next {@link count} files that still need to be+ * indexed.+ *+ * For specifics of what a "sync" entails, see {@link updateAssumingLocalFiles}.+ *+ * @param userID Sync only files owned by a {@link userID} with the face DB.+ *+ * @param count Limit the resulting list of indexable files to {@link count}.+ */+const syncWithLocalFilesAndGetFilesToIndex = async (+ userID: number,+ count: number,+): Promise<EnteFile[]> => {+ const isIndexable = (f: EnteFile) => f.ownerID == userID;++ const localFiles = await getAllLocalFiles();+ const localFilesByID = new Map(+ localFiles.filter(isIndexable).map((f) => [f.id, f]),+ );++ const localTrashFileIDs = (await getLocalTrashedFiles()).map((f) => f.id);++ await updateAssumingLocalFiles(+ Array.from(localFilesByID.keys()),+ localTrashFileIDs,+ );++ const fileIDsToIndex = await indexableFileIDs(count);+ return fileIDsToIndex.map((id) => ensure(localFilesByID.get(id)));+};+/*** Index faces in a file, save the persist the results locally, and put them* on remote.diff --git a/web/packages/shared/storage/localStorage/helpers.ts b/web/packages/shared/storage/localStorage/helpers.tsindex 390ea93d92..7f46b680dd 100644--- a/web/packages/shared/storage/localStorage/helpers.ts+++ b/web/packages/shared/storage/localStorage/helpers.ts@@ -5,8 +5,6 @@ export const getToken = (): string => {return token;};-export const getUserID = () => getData(LS_KEYS.USER)?.id;-export const isFirstLogin = () =>getData(LS_KEYS.IS_FIRST_LOGIN)?.status ?? false;