π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Use uploadItem
Manav Rathi26f6ab046410
diff --git a/web/packages/new/photos/services/ml/bitmap.ts b/web/packages/new/photos/services/ml/bitmap.tsindex 51af826454..3bcbb339ca 100644--- a/web/packages/new/photos/services/ml/bitmap.ts+++ b/web/packages/new/photos/services/ml/bitmap.ts@@ -1,35 +1,91 @@import { FILE_TYPE } from "@/media/file-type";import { decodeLivePhoto } from "@/media/live-photo";+import { basename } from "@/next/file";import { ensure } from "@/utils/ensure";import type { EnteFile } from "../../types/file";import { renderableImageBlob } from "../../utils/file";+import { readStream } from "../../utils/native-stream";import DownloadManager from "../download";+import type { UploadItem } from "../upload/types";+import type { MLWorkerElectron } from "./worker-electron";/**- * Return a {@link ImageBitmap}, using {@link file} if present otherwise- * downloading the source image corresponding to {@link enteFile} from remote.+ * Return a {@link ImageBitmap} that downloads the source image corresponding to+ * {@link enteFile} from remote.** - For images the original is used.* - For live photos the original image component is used.- * - For videos their thumbnail is used.+ * - For videos the thumbnail is used.*/-export const renderableImageBitmap = async (+export const renderableImageBitmap = async (enteFile: EnteFile) => {+ const fileType = enteFile.metadata.fileType;+ let blob: Blob | undefined;+ if (fileType == FILE_TYPE.VIDEO) {+ const thumbnailData = await DownloadManager.getThumbnail(enteFile);+ blob = new Blob([ensure(thumbnailData)]);+ } else {+ blob = await fetchRenderableBlob(enteFile);+ }+ return createImageBitmap(ensure(blob));+};++/**+ * Variant of {@link renderableImageBitmap} that uses the given+ * {@link uploadItem} to construct the image bitmap instead of downloading the+ * original from remote.+ *+ * For videos the thumbnail is still downloaded from remote.+ */+export const renderableUploadItemImageBitmap = async (enteFile: EnteFile,- file?: File | undefined,+ uploadItem: UploadItem,+ electron: MLWorkerElectron,) => {const fileType = enteFile.metadata.fileType;- let blob: Blob;+ let blob: Blob | undefined;if (fileType == FILE_TYPE.VIDEO) {const thumbnailData = await DownloadManager.getThumbnail(enteFile);blob = new Blob([ensure(thumbnailData)]);} else {- blob = ensure(- file- ? await renderableImageBlob(enteFile.metadata.title, file)- : await fetchRenderableBlob(enteFile),+ const file = await readNonVideoUploadItem(uploadItem, electron);+ blob = await renderableImageBlob(enteFile.metadata.title, file);+ }+ return createImageBitmap(ensure(blob));+};++/**+ * Read the given {@link uploadItem} into an in-memory representation.+ *+ * See: [Note: Reading a UploadItem]+ *+ * @param uploadItem An {@link UploadItem} which we are trying to index. The+ * code calling us guarantees that this function will not be called for videos.+ *+ * @returns a web {@link File} that can be used to access the upload item's+ * contents.+ */+const readNonVideoUploadItem = async (+ uploadItem: UploadItem,+ electron: MLWorkerElectron,+): Promise<File> => {+ if (typeof uploadItem == "string" || Array.isArray(uploadItem)) {+ const { response, lastModifiedMs } = await readStream(+ electron,+ uploadItem,);+ const path = typeof uploadItem == "string" ? uploadItem : uploadItem[1];+ // This function will not be called for videos, and for images+ // it is reasonable to read the entire stream into memory here.+ return new File([await response.arrayBuffer()], basename(path), {+ lastModified: lastModifiedMs,+ });+ } else {+ if (uploadItem instanceof File) {+ return uploadItem;+ } else {+ return uploadItem.file;+ }}- return createImageBitmap(blob);};const fetchRenderableBlob = async (enteFile: EnteFile) => {diff --git a/web/packages/new/photos/services/ml/face.ts b/web/packages/new/photos/services/ml/face.tsindex 38ed3b0b60..74eac0059c 100644--- a/web/packages/new/photos/services/ml/face.ts+++ b/web/packages/new/photos/services/ml/face.ts@@ -19,7 +19,11 @@ import {translate,type Matrix as TransformationMatrix,} from "transformation-matrix";-import { renderableImageBitmap } from "./bitmap";+import type { UploadItem } from "../upload/types";+import {+ renderableImageBitmap,+ renderableUploadItemImageBitmap,+} from "./bitmap";import { saveFaceCrops } from "./crop";import {clamp,@@ -212,19 +216,24 @@ export interface Box {** @param enteFile The {@link EnteFile} to index.*- * @param file The contents of {@link enteFile} as a web {@link File}, if- * available. These are used when they are provided, otherwise the file is- * downloaded and decrypted from remote.+ * @param uploadItem If we're called during the upload process, then this will+ * be set to the {@link UploadItem} that was uploaded. This way, we can directly+ * use the on-disk file instead of needing to download the original from remote.+ *+ * @param electron The {@link MLWorkerElectron} instance that allows us to call+ * our Node.js layer for various functionality.** @param userAgent The UA of the client that is doing the indexing (us).*/export const indexFaces = async (enteFile: EnteFile,- file: File | undefined,+ uploadItem: UploadItem | undefined,electron: MLWorkerElectron,userAgent: string,-) => {- const imageBitmap = await renderableImageBitmap(enteFile, file);+): Promise<FaceIndex> => {+ const imageBitmap = uploadItem+ ? await renderableUploadItemImageBitmap(enteFile, uploadItem, electron)+ : await renderableImageBitmap(enteFile);const { width, height } = imageBitmap;const fileID = enteFile.id;diff --git a/web/packages/new/photos/services/ml/worker.ts b/web/packages/new/photos/services/ml/worker.tsindex baadaad921..c1f9f68b2d 100644--- a/web/packages/new/photos/services/ml/worker.ts+++ b/web/packages/new/photos/services/ml/worker.ts@@ -23,6 +23,12 @@ import type { MLWorkerElectron } from "./worker-electron";const idleDurationStart = 5; /* 5 seconds */const idleDurationMax = 16 * 60; /* 16 minutes */+/** An entry in the liveQ maintained by the worker */+interface LiveQItem {+ enteFile: EnteFile;+ uploadItem: UploadItem;+}+/*** Run operations related to machine learning (e.g. indexing) in a Web Worker.*@@ -49,7 +55,7 @@ export class MLWorker {private electron: MLWorkerElectron | undefined;private userAgent: string | undefined;private shouldSync = false;- private liveQ: { enteFile: EnteFile; uploadItem: UploadItem }[] = [];+ private liveQ: LiveQItem[] = [];private state: "idle" | "pull" | "indexing" = "idle";private idleTimeout: ReturnType<typeof setTimeout> | undefined;private idleDuration = idleDurationStart; /* unit: seconds */@@ -159,7 +165,7 @@ export class MLWorker {return;}- const liveQ = this.liveQ.map((i) => i.enteFile);+ const liveQ = this.liveQ;this.liveQ = [];this.state = "indexing";const allSuccess = await indexNextBatch(@@ -208,7 +214,7 @@ const pull = pullFaceEmbeddings;* things pending to process, so we should chug along at full speed.*/const indexNextBatch = async (- liveQ: EnteFile[],+ liveQ: LiveQItem[],electron: MLWorkerElectron,userAgent: string,) => {@@ -219,16 +225,23 @@ const indexNextBatch = async (const userID = ensure(await getKVN("userID"));- const files =+ // Use the liveQ if present, otherwise get the next batch to backfill.+ const items =liveQ.length > 0? liveQ- : await syncWithLocalFilesAndGetFilesToIndex(userID, 200);- if (files.length == 0) return false;+ : await syncWithLocalFilesAndGetFilesToIndex(userID, 200).then(+ (fs) =>+ fs.map((f) => ({ enteFile: f, uploadItem: undefined })),+ );++ // Nothing to do.+ if (items.length == 0) return false;+ // Index, keeping track if any of the items failed.let allSuccess = true;- for (const file of files) {+ for (const { enteFile, uploadItem } of items) {try {- await index(file, undefined, electron, userAgent);+ await index(enteFile, uploadItem, electron, userAgent);// Possibly unnecessary, but let us drain the microtask queue.await wait(0);} catch {@@ -236,6 +249,7 @@ const indexNextBatch = async (}}+ // Return true if nothing failed.return allSuccess;};@@ -278,7 +292,7 @@ const syncWithLocalFilesAndGetFilesToIndex = async (** @param enteFile The {@link EnteFile} to index.*- * @param file If the file is one which is being uploaded from the current+ * @param uploadItem If the file is one which is being uploaded from the current* client, then we will also have access to the file's content. In such* cases, pass a web {@link File} object to use that its data directly for* face indexing. If this is not provided, then the file's contents will be@@ -288,7 +302,7 @@ const syncWithLocalFilesAndGetFilesToIndex = async (*/export const index = async (enteFile: EnteFile,- file: File | undefined,+ uploadItem: UploadItem | undefined,electron: MLWorkerElectron,userAgent: string,) => {@@ -297,7 +311,7 @@ export const index = async (let faceIndex: FaceIndex;try {- faceIndex = await indexFaces(enteFile, file, electron, userAgent);+ faceIndex = await indexFaces(enteFile, uploadItem, electron, userAgent);} catch (e) {// Mark indexing as having failed only if the indexing itself// failed, not if there were subsequent failures (like when tryingdiff --git a/web/packages/new/photos/utils/native-stream.ts b/web/packages/new/photos/utils/native-stream.tsindex 9c38897367..70b052b4c1 100644--- a/web/packages/new/photos/utils/native-stream.ts+++ b/web/packages/new/photos/utils/native-stream.ts@@ -7,6 +7,7 @@*/import type { Electron, ZipItem } from "@/next/types/ipc";+import type { MLWorkerElectron } from "../services/ml/worker-electron";/*** Stream the given file or zip entry from the user's local file system.@@ -16,7 +17,8 @@ import type { Electron, ZipItem } from "@/next/types/ipc";* See: [Note: IPC streams].** To avoid accidentally invoking it in a non-desktop app context, it requires- * the {@link Electron} object as a parameter (even though it doesn't use it).+ * the {@link Electron} (or a functionally similar) object as a parameter (even+ * though it doesn't use it).** @param pathOrZipItem Either the path on the file on the user's local file* system whose contents we want to stream. Or a tuple containing the path to a@@ -34,7 +36,7 @@ import type { Electron, ZipItem } from "@/next/types/ipc";* reading, expressed as epoch milliseconds.*/export const readStream = async (- _: Electron,+ _: Electron | MLWorkerElectron,pathOrZipItem: string | ZipItem,): Promise<{ response: Response; size: number; lastModifiedMs: number }> => {let url: URL;diff --git a/web/packages/next/file.ts b/web/packages/next/file.tsindex bd2c043930..f56dbc1ccd 100644--- a/web/packages/next/file.ts+++ b/web/packages/next/file.ts@@ -59,8 +59,10 @@ export const fileNameFromComponents = (components: FileNameComponents) =>*/export const basename = (path: string) => {const pathComponents = path.split("/");- for (let i = pathComponents.length - 1; i >= 0; i--)- if (pathComponents[i] !== "") return pathComponents[i];+ for (let i = pathComponents.length - 1; i >= 0; i--) {+ const component = pathComponents[i];+ if (component && component.length > 0) return component;+ }return path;};