π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Trim albums vendor export and utils copies
Anand Baburajan6d80fcd27869
diff --git a/web/apps/albums/vendor/ente-gallery/export-dirs.ts b/web/apps/albums/vendor/ente-gallery/export-dirs.tsindex 40229741ed..d96b23ba28 100644--- a/web/apps/albums/vendor/ente-gallery/export-dirs.ts+++ b/web/apps/albums/vendor/ente-gallery/export-dirs.ts@@ -1,11 +1,5 @@/**- * Name of the directory in which we put our metadata when exporting to the file- * system.+ * Name of the directory in which we keep metadata sidecar files for exports and+ * uploads.*/export const exportMetadataDirectoryName = "metadata";--/**- * Name of the directory in which we keep trash items when deleting files that- * have been exported to the local disk previously.- */-export const exportTrashDirectoryName = "Trash";diff --git a/web/apps/albums/vendor/ente-gallery/services/ffmpeg/index.ts b/web/apps/albums/vendor/ente-gallery/services/ffmpeg/index.tsindex 8c7817ee4e..e7ea66c925 100644--- a/web/apps/albums/vendor/ente-gallery/services/ffmpeg/index.ts+++ b/web/apps/albums/vendor/ente-gallery/services/ffmpeg/index.ts@@ -298,7 +298,7 @@ export const determineVideoDuration = async (export const convertToMP4 = async (blob: Blob): Promise<Blob | Uint8Array> => {const electron = globalThis.electron;if (electron) {- return convertToMP4Native(electron, blob);+ return convertToMP4Native(blob);} else {const command = [ffmpegPathPlaceholder,@@ -312,11 +312,9 @@ export const convertToMP4 = async (blob: Blob): Promise<Blob | Uint8Array> => {}};-const convertToMP4Native = async (electron: Electron, blob: Blob) => {- const token = await initiateConvertToMP4(electron, blob);- const mp4Blob = await readVideoStream(electron, token).then((res) =>- res.blob(),- );- await videoStreamDone(electron, token);+const convertToMP4Native = async (blob: Blob) => {+ const token = await initiateConvertToMP4(blob);+ const mp4Blob = await readVideoStream(token).then((res) => res.blob());+ await videoStreamDone(token);return mp4Blob;};diff --git a/web/apps/albums/vendor/ente-gallery/services/save.ts b/web/apps/albums/vendor/ente-gallery/services/save.tsindex ea65cbf8f6..910d0fd823 100644--- a/web/apps/albums/vendor/ente-gallery/services/save.ts+++ b/web/apps/albums/vendor/ente-gallery/services/save.ts@@ -4,10 +4,7 @@ import { joinPath, nameAndExtension } from "ente-base/file-name";import log from "ente-base/log";import { type Electron } from "ente-base/types/ipc";import { saveAsFileAndRevokeObjectURL } from "ente-base/utils/web";-import {- exportMetadataDirectoryName,- exportTrashDirectoryName,-} from "ente-gallery/export-dirs";+import { exportMetadataDirectoryName } from "ente-gallery/export-dirs";import { downloadManager } from "ente-gallery/services/download";import { writeStream } from "ente-gallery/utils/native-stream";import type { EnteFile } from "ente-media/file";@@ -40,10 +37,7 @@ const safeDirectoryName = async (name: string,exists: (path: string) => Promise<boolean>,): Promise<string> => {- const specialDirectoryNames = [- exportTrashDirectoryName,- exportMetadataDirectoryName,- ];+ const specialDirectoryNames = [exportMetadataDirectoryName];let result = sanitizeFilename(name);let count = 1;@@ -789,7 +783,7 @@ const saveFileDesktop = async (const writeStreamToFile = (exportName: string,stream: ReadableStream<Uint8Array> | null,- ) => writeStream(electron, joinPath(directoryPath, exportName), stream);+ ) => writeStream(joinPath(directoryPath, exportName), stream);const stream = await downloadManager.fileStream(file);const fileName = fileFileName(file);diff --git a/web/apps/albums/vendor/ente-gallery/services/upload/metadata-json.ts b/web/apps/albums/vendor/ente-gallery/services/upload/metadata-json.tsindex e54cb19d9c..c664cd340b 100644--- a/web/apps/albums/vendor/ente-gallery/services/upload/metadata-json.ts+++ b/web/apps/albums/vendor/ente-gallery/services/upload/metadata-json.ts@@ -200,7 +200,7 @@ const uploadItemText = async (uploadItem: UploadItem) => {} else if (typeof uploadItem == "string") {return await ensureElectron().fs.readTextFile(uploadItem);} else if (Array.isArray(uploadItem)) {- const { response } = await readStream(ensureElectron(), uploadItem);+ const { response } = await readStream(uploadItem);return await response.text();} else {return await uploadItem.file.text();diff --git a/web/apps/albums/vendor/ente-gallery/services/upload/upload-service.ts b/web/apps/albums/vendor/ente-gallery/services/upload/upload-service.tsindex bdada5d2ae..19255579a4 100644--- a/web/apps/albums/vendor/ente-gallery/services/upload/upload-service.ts+++ b/web/apps/albums/vendor/ente-gallery/services/upload/upload-service.ts@@ -978,7 +978,7 @@ const readUploadItem = async (uploadItem: UploadItem): Promise<FileStream> => {response,size,lastModifiedMs: lm,- } = await readStream(ensureElectron(), uploadItem);+ } = await readStream(uploadItem);underlyingStream = response.body!;fileSize = size;lastModifiedMs = lm;@@ -1316,7 +1316,7 @@ const tryExtractImageMetadata = async (// The library we use for extracting Exif from images, ExifReader,// doesn't support streams. But unlike videos, for images it is// reasonable to read the entire stream into memory here.- const { response } = await readStream(ensureElectron(), uploadItem);+ const { response } = await readStream(uploadItem);const path = typeof uploadItem == "string" ? uploadItem : uploadItem[1];const opts = lastModifiedMs ? { lastModified: lastModifiedMs } : {};file = new File([await response.arrayBuffer()], basename(path), opts);diff --git a/web/apps/albums/vendor/ente-gallery/utils/avatar-colors.ts b/web/apps/albums/vendor/ente-gallery/utils/avatar-colors.tsindex a8d672e931..e7c231a6a6 100644--- a/web/apps/albums/vendor/ente-gallery/utils/avatar-colors.ts+++ b/web/apps/albums/vendor/ente-gallery/utils/avatar-colors.ts@@ -4,7 +4,7 @@* These colors are used to give users a consistent colored avatar* based on their identifier (email or user ID).*/-export const avatarColors = [+const avatarColors = ["#76549A", // Purple"#DF7861", // Coral"#94B49F", // Sage greendiff --git a/web/apps/albums/vendor/ente-gallery/utils/file.ts b/web/apps/albums/vendor/ente-gallery/utils/file.tsindex ec3807c265..2602198c36 100644--- a/web/apps/albums/vendor/ente-gallery/utils/file.ts+++ b/web/apps/albums/vendor/ente-gallery/utils/file.ts@@ -27,49 +27,3 @@ export const sortFiles = (files: EnteFile[], sortAsc = false) => {: factor * (bt - at);});};--/**- * [Note: Collection file]- *- * File IDs themselves are unique across all the files for the user (in fact,- * they're unique across all the files in an Ente instance).- *- * However, we can have multiple entries for the same file ID in our local- * database and/or remote responses because the unit of account is not file, but- * a "Collection File" β a collection and file pair.- *- * For example, if the same file is symlinked into two collections, then we will- * have two "Collection File" entries for it, both with the same file ID, but- * with different collection IDs.- *- * This function returns files such that only one of these entries is returned.- * The entry that is returned is arbitrary in general, this function just picks- * the first one for each unique file ID.- *- * If this function is invoked on a list on which {@link sortFiles} has already- * been called, which by default sorts such that the newest file is first, then- * this function's behaviour would be to return the newest file from among- * multiple files with the same ID but different collections.- */-export const uniqueFilesByID = (files: EnteFile[]) => {- const seen = new Set<number>();- return files.filter(({ id }) => {- if (seen.has(id)) return false;- seen.add(id);- return true;- });-};--/**- * Segment the given {@link files} into lists indexed by their collection ID.- *- * Order is preserved.- */-export const groupFilesByCollectionID = (files: EnteFile[]) =>- files.reduce((result, file) => {- const id = file.collectionID;- let cfs = result.get(id);- if (!cfs) result.set(id, (cfs = []));- cfs.push(file);- return result;- }, new Map<number, EnteFile[]>());diff --git a/web/apps/albums/vendor/ente-gallery/utils/native-stream.ts b/web/apps/albums/vendor/ente-gallery/utils/native-stream.tsindex edf8c83d66..32b4186972 100644--- a/web/apps/albums/vendor/ente-gallery/utils/native-stream.ts+++ b/web/apps/albums/vendor/ente-gallery/utils/native-stream.ts@@ -6,9 +6,7 @@* See: [Note: IPC streams].*/-import type { Electron, ElectronMLWorker, ZipItem } from "ente-base/types/ipc";-import { z } from "zod";-import type { FileSystemUploadItem } from "../services/upload";+import type { ZipItem } from "ente-base/types/ipc";/*** Stream the given file or zip entry from the user's local file system.@@ -17,10 +15,6 @@ import type { FileSystemUploadItem } from "../services/upload";* "stream://" protocol handler exposed by our custom code in the Node.js layer.* See: [Note: IPC streams].*- * To avoid accidentally invoking it in a non-desktop app context, it requires- * the {@link Electron} (or a functionally similar) object as a parameter (even- * though it doesn't need or 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* zip file and the name of the entry within it.@@ -37,7 +31,6 @@ import type { FileSystemUploadItem } from "../services/upload";* reading, expressed as epoch milliseconds.*/export const readStream = async (- _: Electron | ElectronMLWorker,pathOrZipItem: string | ZipItem,): Promise<{ response: Response; size: number; lastModifiedMs: number }> => {let url: URL;@@ -81,15 +74,11 @@ const readNumericHeader = (res: Response, key: string) => {* "stream://" protocol handler exposed by our custom code in the Node.js layer.* 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).- ** @param path The path on the local machine where to write the file to.** @param stream The stream which should be written into the file.*/export const writeStream = async (- _: Electron,path: string,stream: ReadableStream | null,) => {@@ -98,9 +87,9 @@ export const writeStream = async (// The duplex parameter needs to be set to 'half' when streaming requests.//- // Currently browsers, and specifically in our case, since this code runs- // only within our desktop (Electron) app, Chromium, don't support 'full'- // duplex mode (i.e. streaming both the request and the response).+ // Currently browsers, and specifically in our case, the desktop Chromium+ // runtime, don't support 'full' duplex mode (i.e. streaming both the+ // request and the response).// https://developer.chrome.com/docs/capabilities/web-apis/fetch-streaming-requestsconst req = new Request(url, {// GET can't have a body@@ -129,9 +118,6 @@ export const writeStream = async (** This is a variant of {@link writeStream} tailored for the conversion to MP4.*- * @param _ An {@link Electron} instance, witness to the fact that we're running- * in the context of the desktop app. It is otherwise not used.- ** @param video A {@link Blob} containing the video to convert.** @returns a token that can then be passed to {@link readVideoStream} to@@ -140,10 +126,7 @@ export const writeStream = async (** See: [Note: Convert to MP4].*/-export const initiateConvertToMP4 = async (- _: Electron,- video: Blob,-): Promise<string> => {+export const initiateConvertToMP4 = async (video: Blob): Promise<string> => {const url = "stream://video?op=convert-to-mp4";const res = await fetch(url, { method: "POST", body: video });if (!res.ok)@@ -151,126 +134,16 @@ export const initiateConvertToMP4 = async (return res.text();};-const GenerateHLSResult = z.object({- /**- * A token that can be used to passed to {@link readVideoStream} to retrieve- * the generated HLS playlist.- */- playlistToken: z.string(),- /**- * The dimensions (width and height in pixels) of the generated video stream.- */- dimensions: z.object({ width: z.number(), height: z.number() }),- /**- * The size (in bytes) of the file containing the encrypted video segments.- */- videoSize: z.number(),- /**- * The ID of the uploaded encrypted video segment file on the remote bucket.- */- videoObjectID: z.string(),-});--export type GenerateHLSResult = z.infer<typeof GenerateHLSResult>;--/**- * Initate the generation of a HLS stream, streaming the source video contents- * to the node side.- *- * This is a variant of {@link writeStream} tailored for the HLS generation. It- * is similar to {@link initiateConvertToMP4}, but also supports streaming- * {@link FileSystemUploadItem}s and {@link ReadableStream}s.- *- * @param _ An {@link Electron} instance, witness to the fact that we're running- * in the context of the desktop app. It is otherwise not used.- *- * @param video The video to convert.- *- * - If we're called during the upload process, then this will be set to the- * {@link FileSystemUploadItem} that was uploaded. This way, we can directly- * use the on-disk file instead of needing to download the original from- * remote.- *- * - Otherwise it should be a {@link ReadableStream} of the video contents.- *- * @param fileID The ID of the {@link EnteFile} for which we're generating the- * HLS.- *- * @param fetchURL The fully resolved API URL for obtaining the pre-signed URLs- * to which the video segment file should be uploaded.- *- * @param authToken The user's auth token (for making the request to- * {@link fetchURL}).- *- * @returns a token that can be used to retrieve the generated HLS playlist, and- * metadata about the generated video (See {@link GenerateHLSResult}).- *- * In case the video is such that it doesn't require a separate stream to be- * generated (e.g. it is a small video using an already compatible codec), then- * this function will return `undefined`.- *- * See: [Note: Preview variant of videos].- */-export const initiateGenerateHLS = async (- _: Electron,- video: FileSystemUploadItem | ReadableStream,- fileID: number,- fetchURL: string,- authToken: string,-): Promise<GenerateHLSResult | undefined> => {- const params = new URLSearchParams({- op: "generate-hls",- fileID: fileID.toString(),- fetchURL,- authToken,- });-- let body: ReadableStream | null;- if (video instanceof ReadableStream) {- body = video;- } else {- // video is a DesktopUploadItem- body = null;- if (typeof video == "string") {- // Path to a regular file on the user's file system.- params.set("path", video);- } else if (Array.isArray(video)) {- // Path within a zip file on the user's file system.- const [zipPath, entryName] = video;- params.set("zipPath", zipPath);- params.set("entryName", entryName);- } else {- // A File with a path. Use the path.- params.set("path", video.path);- }- }-- const url = `stream://video?${params.toString()}`;- const res = await fetch(url, {- method: "POST",- // @ts-expect-error See: [Note: duplex param required for stream body]- duplex: "half",- body,- });- if (!res.ok)- throw new Error(`Failed to write stream to ${url}: HTTP ${res.status}`);-- if (res.status == 204) return undefined;-- return GenerateHLSResult.parse(await res.json());-};-/*** Variant of {@link readStream} tailored for video conversion.** @param token A token obtained from a video conversion operation like- * {@link initiateConvertToMP4} or {@link initiateGenerateHLS}.+ * {@link initiateConvertToMP4}.** @returns a Response that contains the data associated with the provided* token.*/export const readVideoStream = async (- _: Electron,token: string,): Promise<Response> => {const params = new URLSearchParams({ token });@@ -292,7 +165,6 @@ export const readVideoStream = async (* done reading the response, so it can dispose any temporary resources.*/export const videoStreamDone = async (- _: Electron,token: string,): Promise<void> => {// The value for `done` is arbitrary, only its presence matters.diff --git a/web/apps/albums/vendor/ente-gallery/utils/native-worker.ts b/web/apps/albums/vendor/ente-gallery/utils/native-worker.tsdeleted file mode 100644index e168ac4bbe..0000000000--- a/web/apps/albums/vendor/ente-gallery/utils/native-worker.ts+++ /dev/null@@ -1,33 +0,0 @@-import type { Electron, UtilityProcessType } from "ente-base/types/ipc";--/**- * Obtain a port from the Node.js layer that can be used to communicate with the- * native utility process of type {@link type}.- */-export const createUtilityProcess = (- electron: Electron,- type: UtilityProcessType,-): Promise<MessagePort> => {- // The main process will do its thing, and send back the port it created to- // us by sending an message on the "utilityProcessPort/<type>" channel via- // the postMessage API. This roundabout way is needed because MessagePorts- // cannot be transferred via the usual send/invoke pattern.-- const portEvent = `utilityProcessPort/${type}`;-- const port = new Promise<MessagePort>((resolve) => {- const l = ({ source, data, ports }: MessageEvent) => {- // The source check verifies that the message is coming from our own- // preload script. The data is the message that was posted.- if (source == window && data == portEvent) {- window.removeEventListener("message", l);- resolve(ports[0]!);- }- };- window.addEventListener("message", l);- });-- electron.triggerCreateUtilityProcess(type);-- return port;-};diff --git a/web/apps/albums/vendor/ente-gallery/utils/units.ts b/web/apps/albums/vendor/ente-gallery/utils/units.tsindex 229ec2ab9d..a5961212e5 100644--- a/web/apps/albums/vendor/ente-gallery/utils/units.ts+++ b/web/apps/albums/vendor/ente-gallery/utils/units.ts@@ -8,15 +8,6 @@ import { t } from "i18next";*/const units = ["b", "kb", "mb", "gb", "tb"];-/**- * Convert the given number of {@link bytes} to their equivalent GB string with- * {@link precision}.- *- * The returned string does not have the GB suffix.- */-export const bytesInGB = (bytes: number, precision = 0): string =>- (bytes / (1024 * 1024 * 1024)).toFixed(precision);-/*** Convert the given number of {@link bytes} to a user visible string in an* appropriately sized unit.@@ -38,63 +29,3 @@ export function formattedByteSize(bytes: number, precision = 2): string {return `${quantity.toFixed(precision)} ${t(`storage_unit.${unit}`)}`;}--interface FormattedStorageByteSizeOptions {- /**- * If `true` then round up the fractional quantity we obtain when dividing- * the number of bytes by the number of bytes in the unit that got chosen.- *- * The default behaviour is to take the ceiling.- */- round?: boolean;-}--/**- * Convert the given number of storage {@link bytes} to a user visible string in- * an appropriately sized unit.- *- * This differs from {@link formattedByteSize} in that while- * {@link formattedByteSize} is meant for arbitrary byte sizes, this function- * has a few additional beautification heuristics that we want to apply when- * displaying the "storage size" (in different contexts) as opposed to, say, a- * generic "file size".- *- * @param options {@link FormattedStorageByteSizeOptions}.- *- * @return A user visible string, including the localized unit suffix.- */-export const formattedStorageByteSize = (- bytes: number,- options?: FormattedStorageByteSizeOptions,-): string => {- if (bytes <= 0) return `0 ${t("storage_unit.mb")}`;-- const i = Math.min(- Math.floor(Math.log(bytes) / Math.log(1024)),- units.length - 1,- );-- let quantity = bytes / Math.pow(1024, i);- let unit = units[i];-- // Round up bytes, KBs and MBs to the bigger unit whenever they'll come of- // as more than 0.1.- if (quantity > 100 && i < units.length - 2) {- quantity /= 1024;- unit = units[i + 1];- }-- quantity = Number(quantity.toFixed(1));-- // Truncate or round storage sizes to trim off unnecessary and potentially- // obscuring precision when they are larger that 10 GB.- if (bytes >= 10 * 1024 * 1024 * 1024 /* 10 GB */) {- if (options?.round) {- quantity = Math.ceil(quantity);- } else {- quantity = Math.round(quantity);- }- }-- return `${quantity} ${t(`storage_unit.${unit}`)}`;-};