π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Prune albums vendor gallery services
Anand Baburajan1bf9fffff891
diff --git a/web/apps/albums/vendor/ente-gallery/services/convert.ts b/web/apps/albums/vendor/ente-gallery/services/convert.tsindex 5568f7d19b..0983120797 100644--- a/web/apps/albums/vendor/ente-gallery/services/convert.ts+++ b/web/apps/albums/vendor/ente-gallery/services/convert.ts@@ -1,9 +1,7 @@-import { isDesktop } from "ente-base/app";import { lowercaseExtension } from "ente-base/file-name";import log from "ente-base/log";-import { workerBridge } from "ente-base/worker/worker-bridge";import type { EnteFile } from "ente-media/file";-import { FileType, KnownFileTypeInfos } from "ente-media/file-type";+import { KnownFileTypeInfos } from "ente-media/file-type";import { isHEICExtension, needsJPEGConversion } from "ente-media/formats";import { heicToJPEG } from "ente-media/heic-convert";import { detectFileTypeInfo } from "../utils/detect-type";@@ -28,14 +26,10 @@ import { convertToMP4 } from "./ffmpeg";* likely cannot render, continue. Otherwise return the imageBlob that was* passed in (after setting its MIME type).*- * 3. If we're running in our desktop app and this MIME type is something our- * desktop app can natively convert to a JPEG (using ffmpeg), do that and- * return the resultant JPEG blob.- *- * 4. If this is an HEIC file and the browser does not have native HEIC support,+ * 3. If this is an HEIC file and the browser does not have native HEIC support,* then use our (Wasm) HEIC converter and return the resultant JPEG blob.*- * 5. Otherwise return the original (with the MIME type if we were able to+ * 4. Otherwise return the original (with the MIME type if we were able to* deduce one).** In will catch all errors and return the original in those cases.@@ -52,26 +46,7 @@ export const renderableImageBlob = async (if (needsJPEGConversion(extension)) {log.debug(() => [`Converting ${fileName} to JPEG`, fileTypeInfo]);- // If we're running in our desktop app, see if our Node.js layer can- // convert this into a JPEG using native tools.-- if (isDesktop) {- try {- return await nativeConvertToJPEG(imageBlob);- } catch (e) {- log.error("Native conversion to JPEG failed", e);- }- }-- // If the previous step failed, or if native JPEG conversion is not- // available on this platform, for HEIC/HEIF files we can fallback- // to our web HEIC converter.-if (isHEICExtension(extension)) {- // But first, check if the browser already knows how to natively- // render HEICs, e.g. Safari 17+. In such cases not only is the- // Wasm conversion unnecessary, the native hardware accelerated- // support will also be _much_ faster.if (mimeType == "image/heic" && (await isHEICSupported())) {log.debug(() => `Using native HEIC support for ${fileName}`,@@ -105,27 +80,6 @@ export const renderableImageBlob = async (}};-/**- * Convert {@link imageBlob} to a JPEG blob.- *- * The presumption is that method used by our desktop app for converting to JPEG- * should be able to handle files with all extensions for which- * {@link needsJPEGConversion} returns true.- */-const nativeConvertToJPEG = async (imageBlob: Blob) => {- const startTime = Date.now();- const imageData = new Uint8Array(await imageBlob.arrayBuffer());- const electron = globalThis.electron;- // If we're running in a worker, we need to reroute the request back to- // the main thread since workers don't have access to the `window` (and- // thus, to the `window.electron`) object.- const jpegData = electron- ? await electron.convertToJPEG(imageData)- : await workerBridge!.convertToJPEG(imageData);- log.debug(() => `Native JPEG conversion took ${Date.now() - startTime} ms`);- return new Blob([jpegData], { type: "image/jpeg" });-};-let _isHEICSupported: Promise<boolean> | undefined;/**@@ -168,16 +122,11 @@ const testHEICDataURL =* 1. If the browser thinks it can play the video, then return the an object URL* created by directly using the provided {@link videoBlob}.*- * 2. Otherwise try to convert using FFmpeg. This conversion always happens on- * the desktop app, but in the browser the conversion only happens for short- * videos since the Wasm FFmpeg implementation is much slower.+ * 2. Otherwise try to convert using FFmpeg, but only for short videos since+ * the Wasm FFmpeg implementation is much slower.** 3. On errors, return the original (as would've happened for step 1).*- * A special case if for FileType.livePhoto on Linux in the desktop app, where- * the conversion always happens to workaround the audio only playback in that- * specific scenario.- ** @param file The {@link EnteFile} with which this video is associated.** @param videoFileName The name of the video.@@ -188,7 +137,7 @@ const testHEICDataURL =* {@link videoBlob}.*/export const playableVideoURL = async (- file: EnteFile,+ _file: EnteFile,videoFileName: string,videoBlob: Blob,): Promise<string> => {@@ -224,47 +173,8 @@ export const playableVideoURL = async (const videoObjectURL = URL.createObjectURL(typedBlob);const isPlayable = await isPlaybackPossible(videoObjectURL);- let shouldConvert = false;-- if (isPlayable) {- // The browser thinks it can play this video.- //- // But it is not a guarantee. In particular, a problematic case is when- // for a particular codec combination, browser can play the audio- // stream, but not the video stream. `isPlaybackPossible` would return- // true, but when the user will hear only audio and not see the video.- //- // For videos themselves, we solve this (and other issues) by providing- // a streaming variant. However it can still happen for live photos.- //- // Unfortunately, I haven't found a way yet of detecting if this- // scenario is going to arise (open a issue if you've found one).- // Fortunately, this particular failure mode has only been reported on- // Linux desktop app (which uses Chromium underneath). So we add a- // special case - if (desktop && livePhoto && linux) then forceConvert.- // Practically this is a reasonable fallback since the video component- // of a live photo is going to be a few seconds only, and the video- // conversion is fast in the desktop app.- if (- isDesktop &&- file.metadata.fileType == FileType.livePhoto &&- // eslint-disable-next-line @typescript-eslint/no-deprecated- navigator.platform.startsWith("Linux")- ) {- shouldConvert = true;- }- } else {- // The browser doesn't think it can play this video, try transcoding.- if (isDesktop) {- // Always on desktop.- shouldConvert = true;- } else {- // Don't try to transcode on the web if the file is too big.- if (videoBlob.size < 100 * 1024 * 1024 /* 100 MB, arbitrary */) {- shouldConvert = true;- }- }- }+ const shouldConvert =+ !isPlayable && videoBlob.size < 100 * 1024 * 1024 /* 100 MB, arbitrary */;if (shouldConvert) {try {diff --git a/web/apps/albums/vendor/ente-gallery/services/download.ts b/web/apps/albums/vendor/ente-gallery/services/download.tsindex 7cfed9c48a..c093f378f2 100644--- a/web/apps/albums/vendor/ente-gallery/services/download.ts+++ b/web/apps/albums/vendor/ente-gallery/services/download.ts@@ -24,12 +24,12 @@ import { playableVideoURL, renderableImageBlob } from "./convert";/*** URL(s) for the original image or video, alongwith with potential conversions- * applied to make it more likely that the browser (or desktop app) will be able- * to render (or play) it.+ * applied to make it more likely that the browser will be able to render (or+ * play) it.** The word "renderable" or "playable" is not a guarantee, but rather a best* effort indicator as we might not always be able to convert all formats to- * something that the browser (or desktop app) can show.+ * something that the browser can show.*/export type RenderableSourceURLs =| {@@ -144,8 +144,7 @@ class DownloadManager {* These are saved as a result of invocation of* {@link renderableSourceURLs}, which goes one step beyond* {@link fileURLPromises}, and also attempts to convert the downloaded file- * into a URL that the browser (or the desktop app) is likely to be able to- * render or play.+ * into a URL that the browser is likely to be able to render or play.** The entries are keyed by file ID.*/diff --git a/web/apps/albums/vendor/ente-gallery/services/ffmpeg/constants.ts b/web/apps/albums/vendor/ente-gallery/services/ffmpeg/constants.tsindex dae03a9976..fb0d762e5b 100644--- a/web/apps/albums/vendor/ente-gallery/services/ffmpeg/constants.ts+++ b/web/apps/albums/vendor/ente-gallery/services/ffmpeg/constants.ts@@ -1,5 +1,3 @@-/* Ditto in the desktop app's code (used by the native FFmpeg invocation). */-export const ffmpegPathPlaceholder = "FFMPEG";export const inputPathPlaceholder = "INPUT";export const outputPathPlaceholder = "OUTPUT";diff --git a/web/apps/albums/vendor/ente-gallery/services/ffmpeg/index.ts b/web/apps/albums/vendor/ente-gallery/services/ffmpeg/index.tsindex e7ea66c925..ceb436f0a1 100644--- a/web/apps/albums/vendor/ente-gallery/services/ffmpeg/index.ts+++ b/web/apps/albums/vendor/ente-gallery/services/ffmpeg/index.ts@@ -1,16 +1,4 @@-import { ensureElectron } from "ente-base/electron";import log from "ente-base/log";-import type { Electron } from "ente-base/types/ipc";-import {- toPathOrZipEntry,- type FileSystemUploadItem,- type UploadItem,-} from "ente-gallery/services/upload";-import {- initiateConvertToMP4,- readVideoStream,- videoStreamDone,-} from "ente-gallery/utils/native-stream";import {parseMetadataDate,type ParsedMetadata,@@ -23,17 +11,7 @@ import {import { determineVideoDurationWeb, ffmpegExecWeb } from "./web";/**- * Generate a thumbnail for the given video using a Wasm FFmpeg running in a web- * worker.- *- * This function is called during upload, when we need to generate thumbnails- * for the new files that the user is adding.- *- * @param blob The input video blob.- *- * @returns JPEG data of the generated thumbnail.- *- * See also {@link generateVideoThumbnailNative}.+ * Generate a thumbnail for the given video using the web FFmpeg worker.*/export const generateVideoThumbnailWeb = async (blob: Blob) =>_generateVideoThumbnail((seekTime: number) =>@@ -44,41 +22,12 @@ const _generateVideoThumbnail = async (thumbnailAtTime: (seekTime: number) => Promise<Uint8Array>,) => {try {- // Try generating thumbnail at seekTime 1 second.return await thumbnailAtTime(1);} catch {- // If that fails, try again at the beginning. If even this throws, let- // it fail.return await thumbnailAtTime(0);}};-/**- * Generate a thumbnail for the given video using a native FFmpeg binary bundled- * with our desktop app.- *- * This function is called during upload, when we need to generate thumbnails- * for the new files that the user is adding.- *- * @param dataOrPath The input video's data or the path to the video on the- * user's local file system. See: [Note: Reading a UploadItem].- *- * @returns JPEG data of the generated thumbnail.- *- * See also {@link generateVideoThumbnailNative}.- */-export const generateVideoThumbnailNative = async (- electron: Electron,- fsUploadItem: FileSystemUploadItem,-) =>- _generateVideoThumbnail((seekTime: number) =>- electron.ffmpegExec(- makeGenThumbnailCommand(seekTime),- toPathOrZipEntry(fsUploadItem),- "jpeg",- ),- );-const makeGenThumbnailCommand = (seekTime: number) => ({default: _makeGenThumbnailCommand(seekTime, false),hdr: _makeGenThumbnailCommand(seekTime, true),@@ -88,22 +37,15 @@ const _makeGenThumbnailCommand = (seekTime: number, forHDR: boolean) => [ffmpegPathPlaceholder,"-i",inputPathPlaceholder,- // Seek to seekTime in the video."-ss",`00:00:0${seekTime}`,- // Take the first frame"-vframes","1",- // Apply a filter to this frame"-vf",[- // Scale it to a maximum height of 720 keeping aspect ratio, ensuring- // that the dimensions are even (subsequent filters require this)."scale=-2:720",forHDR- ? // Apply a tonemap to ensure that thumbnails of HDR videos do- // not look washed out. See: [Note: Tonemapping HDR to HD].- [+ ? ["zscale=transfer=linear","tonemap=tonemap=hable:desat=0","zscale=primaries=709:transfer=709:matrix=709",@@ -116,50 +58,15 @@ const _makeGenThumbnailCommand = (seekTime: number, forHDR: boolean) => [];/**- * Extract metadata from the given video.- *- * When we're running in the context of our desktop app _and_ we're passed an- * upload item that resolves to a path of the user's file system, this uses the- * native FFmpeg bundled with our desktop app. Otherwise it uses a Wasm build of- * FFmpeg running in a web worker.- *- * This function is called during upload, when we need to extract the- * "ffmetadata" of videos that the user is uploading.- *- * @param uploadItem The video item being uploaded.+ * Extract ffmetadata from an uploaded video using the web FFmpeg worker.*/export const extractVideoMetadata = async (- uploadItem: UploadItem,-): Promise<ParsedMetadata> => {- const command = extractVideoMetadataCommand;- return parseFFmpegExtractedMetadata(- uploadItem instanceof File- ? await ffmpegExecWeb(command, uploadItem, "txt")- : await ensureElectron().ffmpegExec(- command,- toPathOrZipEntry(uploadItem),- "txt",- ),+ uploadItem: File,+): Promise<ParsedMetadata> =>+ parseFFmpegExtractedMetadata(+ await ffmpegExecWeb(extractVideoMetadataCommand, uploadItem, "txt"),);-};-/**- * The FFmpeg command to use to extract metadata from videos.- *- * Options:- *- * - `-c [short for codex] copy`- * - copy is the [stream_specifier](ffmpeg.org/ffmpeg.html#Stream-specifiers)- * - copies all the stream without re-encoding- *- * - `-map_metadata`- * - http://ffmpeg.org/ffmpeg.html#Advanced-options (search for map_metadata)- * - copies all stream metadata to the output- *- * - `-f ffmetadata`- * - https://ffmpeg.org/ffmpeg-formats.html#Metadata-2- * - dump metadata from media files into a simple INI-like utf-8 text file- */const extractVideoMetadataCommand = [ffmpegPathPlaceholder,"-i",@@ -173,29 +80,12 @@ const extractVideoMetadataCommand = [outputPathPlaceholder,];-/**- * Convert the output produced by running the FFmpeg- * {@link extractVideoMetadataCommand} into a {@link ParsedMetadata}.- *- * @param ffmpegOutput The bytes containing the output of the FFmpeg command.- */const parseFFmpegExtractedMetadata = (ffmpegOutput: Uint8Array) => {- // The output is a utf8 INI-like text file with key=value pairs interspersed- // with comments and newlines.- //- // https://ffmpeg.org/ffmpeg-formats.html#Metadata-2- //- // On Windows, while I couldn't find it documented anywhere, the generated- // ffmetadata file uses Unix line separators ("\n"). But for the sake of- // extra (albeit possibly unnecessary) safety, handle both \r\n and \n- // separators in the split. See: [Note: ffmpeg newlines]-const lines = new TextDecoder().decode(ffmpegOutput).split(/\r?\n/);const isPair = (xs: string[]): xs is [string, string] => xs.length == 2;const kvPairs = lines.map((property) => property.split("=")).filter(isPair);const kv = new Map(kvPairs);-const result: ParsedMetadata = {};const creationDate =@@ -212,12 +102,6 @@ const parseFFmpegExtractedMetadata = (ffmpegOutput: Uint8Array) => {return result;};-/**- * Parse a location string found in the FFmpeg metadata attributes.- *- * This is meant to parse either the "com.apple.quicktime.location.ISO6709"- * (preferable) or the "location" key (fallback).- */const parseFFMetadataLocation = (s: string | undefined) => {if (!s) return undefined;@@ -236,15 +120,6 @@ const parseFFMetadataLocation = (s: string | undefined) => {return { latitude, longitude };};-/**- * Parse a date/time string found in the FFmpeg metadata attributes.- *- * This is meant to parse either the "com.apple.quicktime.creationdate"- * (preferable) or the "creation_time" key (fallback).- *- * Both of these are expected to be ISO 8601 date/time strings, but we prefer- * "com.apple.quicktime.creationdate" since it includes the time zone offset.- */const parseFFMetadataDate = (s: string | undefined) => {if (!s) return undefined;@@ -254,8 +129,6 @@ const parseFFMetadataDate = (s: string | undefined) => {return undefined;}- // While not strictly required, we retain the same behaviour as the image- // Exif parser of ignoring dates whose epoch is 0.if (!d.timestamp) {log.warn(`Ignoring zero video metadata date string "${s}"`);return undefined;@@ -264,57 +137,17 @@ const parseFFMetadataDate = (s: string | undefined) => {return d;};-/**- * Extract the duration (in seconds) from the given video- *- * This is a sibling of {@link extractVideoMetadata}, except it tries to- * determine the duration of the video. The duration is not part of the- * "ffmetadata", and is instead a property of the video itself.- *- * @param uploadItem The video item being uploaded.- *- * @return the duration of the video in seconds (a floating point number).- */-export const determineVideoDuration = async (- uploadItem: UploadItem,-): Promise<number> =>- uploadItem instanceof File- ? determineVideoDurationWeb(uploadItem)- : ensureElectron().ffmpegDetermineVideoDuration(- toPathOrZipEntry(uploadItem),- );+export const determineVideoDuration = async (uploadItem: File): Promise<number> =>+ determineVideoDurationWeb(uploadItem);-/**- * Convert a video from a format that is not supported in the browser to MP4.- *- * This function is called when the user views a video or a live photo, and we- * want to play it back. The idea is to convert it to MP4 which has much more- * universal support in browsers.- *- * @param blob The video blob.- *- * @returns The mp4 video blob.- */export const convertToMP4 = async (blob: Blob): Promise<Blob | Uint8Array> => {- const electron = globalThis.electron;- if (electron) {- return convertToMP4Native(blob);- } else {- const command = [- ffmpegPathPlaceholder,- "-i",- inputPathPlaceholder,- "-preset",- "ultrafast",- outputPathPlaceholder,- ];- return ffmpegExecWeb(command, blob, "mp4");- }-};--const convertToMP4Native = async (blob: Blob) => {- const token = await initiateConvertToMP4(blob);- const mp4Blob = await readVideoStream(token).then((res) => res.blob());- await videoStreamDone(token);- return mp4Blob;+ const command = [+ ffmpegPathPlaceholder,+ "-i",+ inputPathPlaceholder,+ "-preset",+ "ultrafast",+ outputPathPlaceholder,+ ];+ return ffmpegExecWeb(command, blob, "mp4");};diff --git a/web/apps/albums/vendor/ente-gallery/services/ffmpeg/web.ts b/web/apps/albums/vendor/ente-gallery/services/ffmpeg/web.tsindex f49a7f3201..f92c16bd98 100644--- a/web/apps/albums/vendor/ente-gallery/services/ffmpeg/web.ts+++ b/web/apps/albums/vendor/ente-gallery/services/ffmpeg/web.ts@@ -2,7 +2,6 @@ import { FFFSType, FFmpeg } from "@ffmpeg/ffmpeg";import { joinPath } from "ente-base/file-name";import { newID } from "ente-base/id";import log from "ente-base/log";-import type { FFmpegCommand } from "ente-base/types/ipc";import { PromiseQueue } from "ente-utils/promise";import { z } from "zod";import {@@ -11,6 +10,8 @@ import {outputPathPlaceholder,} from "./constants";+type FFmpegCommand = string[] | { default: string[]; hdr: string[] };+/** Lazily initialized and loaded FFmpeg instance. */let _ffmpeg: Promise<FFmpeg> | undefined;@@ -37,12 +38,6 @@ const createFFmpeg = async () => {/*** Run the given FFmpeg command using a Wasm FFmpeg running in a web worker.*- * This is a sibling of {@link ffmpegExec} exposed by the desktop app in- * `ipc.ts`. As a rough ballpark, currently the native FFmpeg integration in the- * desktop app is 10-20x faster than the Wasm one.- *- * See: [Note: FFmpeg in Electron].- ** @param command The FFmpeg command to execute.** @param blob The input blob on which to run the command.@@ -204,9 +199,7 @@ const FFProbeOutputIsHDR = z.object({});/**- * A variant of the {@link isHDRVideo} function in the desktop app source (see- * `ffmpeg.ts`), except here we have access to ffprobe and can use that instead- * of parsing the ffmpeg stderr.+ * Determine whether the mounted video likely contains HDR transfer metadata.** See: [Note: Alternative FFmpeg command for HDR videos]*diff --git a/web/apps/albums/vendor/ente-gallery/services/file-data.ts b/web/apps/albums/vendor/ente-gallery/services/file-data.tsindex 3d7165c277..c25e0924bd 100644--- a/web/apps/albums/vendor/ente-gallery/services/file-data.ts+++ b/web/apps/albums/vendor/ente-gallery/services/file-data.ts@@ -1,14 +1,10 @@-import { encryptBlob } from "ente-base/crypto";-import type { EncryptedBlobB64 } from "ente-base/crypto/types";import {authenticatedPublicAlbumsRequestHeaders,authenticatedRequestHeaders,ensureOk,- retryEnsuringHTTPOk,type PublicAlbumsCredentials,} from "ente-base/http";import { apiURL } from "ente-base/origins";-import type { EnteFile } from "ente-media/file";import { nullToUndefined } from "ente-utils/transform";import { z } from "zod";@@ -74,44 +70,7 @@ const RemoteFileData = z.object({type RemoteFileData = z.infer<typeof RemoteFileData>;/**- * Fetch file data of a particular type for the given list of files.- *- * @param type The {@link FileDataType} which we want.- *- * @param fileIDs The ids of the files for which we want the file data.- *- * @returns a list of {@link RemoteFileData} items for the files which had file- * data for the given type, and that remote was able to successfully retrieve.- *- * The order of this list is arbitrary, and the caller should use the- * {@link fileID} present within the {@link RemoteFileData} to associate an item- * in the result back to a file instead of relying on the order or count of- * items in the result.- *- * In rare cases (issues with the upstream object storage), it is possible for- * remote to not return entries for a particular file even though it has- * associated data of that type. Such skipped entries are mentioned in the- * payload, but we don't parse that information currently since the higher- * levels of our code that use this function handle such rare skips gracefully.- */-export const fetchFilesData = async (- type: FileDataType,- fileIDs: number[],-): Promise<RemoteFileData[]> => {- const res = await fetch(await apiURL("/files/data/fetch"), {- method: "POST",- headers: await authenticatedRequestHeaders(),- body: JSON.stringify({ type, fileIDs }),- });- ensureOk(res);- return z.object({ data: z.array(RemoteFileData) }).parse(await res.json())- .data;-};--/**- * A variant of {@link fetchFilesData} that fetches data for a single file.- *- * Unlike {@link fetchFilesData}, this uses a HTTP GET request.+ * Fetch file data of a particular type for a single file.** Returns `undefined` if no file data of the given type has been uploaded for* this file yet (e.g. if type was "vid_preview", this would indicate that a@@ -158,160 +117,6 @@ export const fetchFileData = async (return z.object({ data: RemoteFileData }).parse(await res.json()).data;};-/**- * An entry in the response to the `/files/data/status-diff`. The actual- * structure has more fields, there are just the fields we are interested in.- */-const RemoteFDStatus = z.object({- /**- * The ID of the file whose file data we're querying.- */- fileID: z.number(),- /**- * Expected to be one of {@link FileDataType}- */- type: z.string(),- /**- * `true` if the file data has been deleted.- *- * This can be true in the in-progress partial deletion case, which the file- * data deletion has been processed but the file deletion has not yet been- * processed.- */- isDeleted: z.boolean(),- /**- * The epoch microseconds when this file data entry was added or updated.- */- updatedAt: z.number(),-});--/**- * A paginated part of the result set sent by remote during- * {@link syncUpdatedFileDataFileIDs}.- */-export interface UpdatedFileDataFileIDsPage {- /**- * The IDs of files for which a file data entry has been created or updated.- */- fileIDs: Set<number>;- /**- * The latest updatedAt (epoch microseconds) time obtained from remote in- * this batch being fetched (from amongst all of the files in the batch, not- * just those that were filtered to be part of {@link fileIDs}).- */- lastUpdatedAt: number;-}--/**- * Fetch the IDs of files for which new file data entries of the given- * {@link type} have been created or updated since the given {@link sinceTime}.- *- * The interaction with remote is paginated, with the {@link onPage} callback- * being called as each page of new data is received.- *- * @param type The {@link FileDataType} for which we want to check for creation- * or updates.- *- * @param lastUpdatedAt Epoch microseconds. This is used to ask remote to- * provide us only entries whose {@link updatedAt} is more than the given value.- * Set this to zero to start from the beginning.- *- * @param onPage A callback invoked for each page of results received from- * remote. It is passed the fileIDs received in the batch under consideration,- * and the largest of the updated time for all entries (irrespective of- * {@link type}) in that batch.- *- * ----- *- * [Note: Pruning stale status-diff entries]- *- * Unlike other "diff" APIs, the diff API used here won't return tombstone- * entries for deleted files. This is not a problem because there are no current- * cases where existing playlists or ML indexes get deleted (unless the- * underlying file is deleted). See: [Note: Caching HLS playlist data].- *- * Note that the "/files/data/status-diff" includes entries for files that are- * in trash. This means that, while not a practical problem (because it's just- * numeric ids), the number of fileIDs we store locally can grow unbounded as- * files move to trash and then get deleted. So to prune them, we also add a- * hook to the /trash/v2/diff processing, and prune any locally saved file IDs- * which have been deleted from trash.- */-export const syncUpdatedFileDataFileIDs = async (- type: FileDataType,- lastUpdatedAt: number,- onPage: (page: UpdatedFileDataFileIDsPage) => Promise<void>,-): Promise<void> => {- while (true) {- const res = await fetch(await apiURL("/files/data/status-diff"), {- method: "POST",- headers: await authenticatedRequestHeaders(),- body: JSON.stringify({ lastUpdatedAt }),- });- ensureOk(res);- const diff = z- .object({ diff: RemoteFDStatus.array().nullish() })- .parse(await res.json()).diff;- if (diff?.length) {- const fileIDs = new Set<number>();- for (const fd of diff) {- lastUpdatedAt = Math.max(lastUpdatedAt, fd.updatedAt);- // While we could prune isDeleted entries here, we can also rely- // on the pruning that happens when the trash gets synced. See:- // [Note: Pruning stale status-diff entries]- if (fd.type == type && !fd.isDeleted) {- fileIDs.add(fd.fileID);- }- }- await onPage({ fileIDs, lastUpdatedAt });- } else {- break;- }- }-};--/**- * Upload file data associated with the given file to remote.- *- * This function will save or update the given data as the latest file data of- * {@link type} associated with the given {@link file}. The data will be- * end-to-end encrypted using the given {@link file}'s key before uploading.- *- * @param file {@link EnteFile} which this data is associated with.- *- * @param type The {@link FileDataType} which we are uploading.- *- * @param data The binary data to upload. The exact contents of the data are- * {@link type} specific.- *- * @param lastUpdatedAt The {@link updatedAt} of the {@link RemoteFileData}- * which we are updating, or 0 to indicate a new entity.- */-export const putFileData = async (- file: EnteFile,- type: FileDataType,- data: Uint8Array,- lastUpdatedAt: number,-) => {- const { encryptedData, decryptionHeader } = await encryptBlob(- data,- file.key,- );-- const res = await fetch(await apiURL("/files/data"), {- method: "PUT",- headers: await authenticatedRequestHeaders(),- body: JSON.stringify({- fileID: file.id,- type,- encryptedData,- decryptionHeader,- lastUpdatedAt,- }),- });- ensureOk(res);-};-/*** Fetch the preview file data the given file.*@@ -378,51 +183,3 @@ export const fetchFilePreviewData = async (ensureOk(res);return z.object({ url: z.string() }).parse(await res.json()).url;};--/**- * Update the video data associated with the given file to remote.- *- * Video data refers to two things:- *- * - The encrypted HLS playlist ("file data" of type "vid_preview").- *- * - The object ID of an (already uploaded) "file preview data" file containing- * the video segments.- *- * This function is similar to {@link putFileData}, except it will save (or- * update) both the playlist, and the reference to its associated segment file,- * associated with the given {@link file}. The playlist data will be end-to-end- * encrypted using the given {@link file}'s key before uploading.- *- * @param file {@link EnteFile} which this data is associated with.- *- * @param encryptedPlaylist The encrypted playlist data (along with the nonce- * used during encryption).- *- * @param objectID Object ID of an already uploaded "file preview data" (see- * {@link getFilePreviewDataUploadURL}).- *- * @param objectSize The size (in bytes) of the file corresponding to- * {@link objectID}.- */-export const putVideoData = async (- file: EnteFile,- encryptedPlaylist: EncryptedBlobB64,- objectID: string,- objectSize: number,-) =>- retryEnsuringHTTPOk(- async () =>- fetch(await apiURL("/files/video-data"), {- method: "PUT",- headers: await authenticatedRequestHeaders(),- body: JSON.stringify({- fileID: file.id,- objectID,- objectSize,- playlist: encryptedPlaylist.encryptedData,- playlistHeader: encryptedPlaylist.decryptionHeader,- }),- }),- { retryProfile: "background" },- );diff --git a/web/apps/albums/vendor/ente-gallery/services/files-db.ts b/web/apps/albums/vendor/ente-gallery/services/files-db.tsindex 755863e7bb..5fd423b059 100644--- a/web/apps/albums/vendor/ente-gallery/services/files-db.ts+++ b/web/apps/albums/vendor/ente-gallery/services/files-db.ts@@ -46,7 +46,6 @@*/import { haveWindow } from "ente-base/env";-import log from "ente-base/log";import {CollectionPrivateMagicMetadataData,CollectionPublicMagicMetadataData,@@ -87,30 +86,6 @@ if (haveWindow()) {*/export { localForage };-/**- * Return `true` if we can access IndexedDB.- *- * This is used as a pre-flight check, to notify the user if they're using a- * browser or extension that is preventing the app from using IndexedDB (which- * is necessary for local storage of collections and files metadata).- */-export const canAccessIndexedDB = async () => {- try {- await localForage.ready();- return true;- } catch (e) {- log.error("IndexDB is not accessible", e);- return false;- }-};--/**- * Clear any data stored in files DB.- *- * This is meant to be called during the logout sequence.- */-export const clearFilesDB = () => localForage.clear();-/*** Return a Zod schema suitable for being used with the various magic metadata* fields of a file or a collection.@@ -187,7 +162,7 @@ export const LocalCollections = z.array(LocalCollection);* This is similar to {@link RemoteEnteFile}, but it differs in that it contains* the decrypted values instead of the encrypted data and nonce pairs.*/-export const LocalEnteFile = z.looseObject({+const LocalEnteFile = z.looseObject({id: z.number(),collectionID: z.number(),ownerID: z.number(),diff --git a/web/apps/albums/vendor/ente-gallery/services/save.ts b/web/apps/albums/vendor/ente-gallery/services/save.tsindex 910d0fd823..fef6a15cc3 100644--- a/web/apps/albums/vendor/ente-gallery/services/save.ts+++ b/web/apps/albums/vendor/ente-gallery/services/save.ts@@ -1,18 +1,13 @@import { assertionFailed } from "ente-base/assert";-import { suppressMainWindowBlurForTrustedPrompt } from "ente-base/electron";-import { joinPath, nameAndExtension } from "ente-base/file-name";+import { 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 } 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";import { fileFileName } from "ente-media/file-metadata";import { FileType } from "ente-media/file-type";import { decodeLivePhoto } from "ente-media/live-photo";import JSZip from "jszip";-import sanitize from "sanitize-filename";import type {AddSaveGroup,UpdateSaveGroup,@@ -30,43 +25,6 @@ interface DownloadLimits {let cachedLimits: DownloadLimits | undefined;-const sanitizeFilename = (s: string) => sanitize(s, { replacement: "_" });--const safeDirectoryName = async (- directoryPath: string,- name: string,- exists: (path: string) => Promise<boolean>,-): Promise<string> => {- const specialDirectoryNames = [exportMetadataDirectoryName];-- let result = sanitizeFilename(name);- let count = 1;- while (- (await exists(joinPath(directoryPath, result))) ||- specialDirectoryNames.includes(result)- ) {- result = `${sanitizeFilename(name)}(${count})`;- count++;- }- return result;-};--const safeFileName = async (- directoryPath: string,- name: string,- exists: (path: string) => Promise<boolean>,-) => {- let result = sanitizeFilename(name);- let count = 1;- while (await exists(joinPath(directoryPath, result))) {- const [fn, ext] = nameAndExtension(sanitizeFilename(name));- if (ext) result = `${fn}(${count}).${ext}`;- else result = `${fn}(${count})`;- count++;- }- return result;-};-/*** Get download limits for the current device.*@@ -114,10 +72,7 @@ const shouldIncludeZipNumber = (/*** Save the given {@link files} to the user's device.*- * If we're running in the context of the web app, the files will be saved to- * the user's download folder. If we're running in the context of our desktop- * app, the user will be prompted to select a directory on their file system and- * the files will be saved therein.+ * Files are saved to the browser's download destination.** @param files The files to save.*@@ -144,10 +99,6 @@ export const downloadAndSaveFiles = (* files that belong to a collection. Otherwise, it broadly behaves similarly;* see that method's documentation for more details.*- * When running in the context of the desktop app, instead of saving the files- * in the directory selected by the user, files are saved in a directory with- * the same name as the collection.- ** @param isHiddenCollectionSummary `true` if the collection is associated with* a "hidden" collection or pseudo-collection in the app. Only relevant when* running in the context of the photos app, can be `undefined` otherwise.@@ -175,12 +126,10 @@ const downloadAndSave = async (files: EnteFile[],title: string,onAddSaveGroup: AddSaveGroup,- collectionSummaryName?: string,+ _collectionSummaryName?: string,collectionSummaryID?: number,isHiddenCollectionSummary?: boolean,) => {- const electron = globalThis.electron;-const total = files.length;if (!files.length) {// Nothing to download.@@ -188,28 +137,11 @@ const downloadAndSave = async (return;}- let downloadDirPath: string | undefined;- if (electron) {- suppressMainWindowBlurForTrustedPrompt();- downloadDirPath = await electron.selectDirectory();- if (!downloadDirPath) {- // The user cancelled on the directory selection dialog.- return;- }- if (collectionSummaryName) {- downloadDirPath = await mkdirCollectionDownloadFolder(- electron,- downloadDirPath,- collectionSummaryName,- );- }- }-+ const downloadDirPath: string | undefined = undefined;const shouldZipOnWeb =- !electron &&- (files.length > 1 ||- (files.length === 1 &&- files[0]?.metadata.fileType === FileType.livePhoto));+ files.length > 1 ||+ (files.length === 1 &&+ files[0]?.metadata.fileType === FileType.livePhoto);const includeZipNumber =shouldZipOnWeb &&shouldIncludeZipNumber(files, getDownloadLimits().maxZipSize);@@ -223,40 +155,6 @@ const downloadAndSave = async (// retry creates Part 6+ instead of starting over at Part 1).let nextZipBatchIndex = 1;- const downloadFilesDesktop = async (- filesToDownload: EnteFile[],- resetFailedCount = false,- ) => {- if (!filesToDownload.length || isDownloading) return;- if (!electron || !downloadDirPath) return;-- isDownloading = true;- if (resetFailedCount) {- updateSaveGroup((g) => ({ ...g, failed: 0 }));- }- failedFiles.length = 0;-- try {- for (const file of filesToDownload) {- if (canceller.signal.aborted) break;- try {- await saveFileDesktop(electron, file, downloadDirPath);- updateSaveGroup((g) => ({ ...g, success: g.success + 1 }));- } catch (e) {- log.error("File download failed", e);- failedFiles.push(file);- updateSaveGroup((g) => ({ ...g, failed: g.failed + 1 }));- }- }-- if (!failedFiles.length) {- updateSaveGroup((g) => ({ ...g, retry: undefined }));- }- } finally {- isDownloading = false;- }- };-const downloadFilesWeb = async (filesToDownload: EnteFile[],resetFailedCount = false,@@ -344,12 +242,10 @@ const downloadAndSave = async (}};- const downloadFiles = electron ? downloadFilesDesktop : downloadFilesWeb;-const retry = () => {if (!failedFiles.length || isDownloading || canceller.signal.aborted)return;- void downloadFiles([...failedFiles], true);+ void downloadFilesWeb([...failedFiles], true);};updateSaveGroup = onAddSaveGroup({@@ -363,7 +259,7 @@ const downloadAndSave = async (retry,});- await downloadFiles(files);+ await downloadFilesWeb(files);};/**@@ -727,82 +623,3 @@ const saveAsZip = async (window.removeEventListener("online", handleOnline);}};--/**- * Create a new directory on the user's file system with the same name as the- * provided {@link collectionName} under the provided {@link downloadDirPath},- * and return the full path to the created directory.- *- * This function can be used only when running in the context of our desktop- * app, and so such requires an {@link Electron} instance as the witness.- */-const mkdirCollectionDownloadFolder = async (- { fs }: Electron,- downloadDirPath: string,- collectionName: string,-) => {- const collectionDownloadName = await safeDirectoryName(- downloadDirPath,- collectionName,- fs.exists,- );- const collectionDownloadPath = joinPath(- downloadDirPath,- collectionDownloadName,- );- await fs.mkdirIfNeeded(collectionDownloadPath);- return collectionDownloadPath;-};--/**- * Save a file to the given {@link directoryPath} using native filesystem APIs.- *- * This is a sibling of {@link saveAsFile} for use when we are running in the- * context of our desktop app. Unlike the browser, the desktop app can use- * native file system APIs to efficiently write the files on disk without- * needing to prompt the user for each write.- *- * @param electron An {@link Electron} instance, a witness to the fact that- * we're running in the desktop app.- *- * @param file The {@link EnteFile} whose contents we want to save to the user's- * file system.- *- * @param directoryPath The file system directory in which to save the file.- */-const saveFileDesktop = async (- electron: Electron,- file: EnteFile,- directoryPath: string,-) => {- const fs = electron.fs;-- const createExportName = (fileName: string) =>- safeFileName(directoryPath, fileName, fs.exists);-- const writeStreamToFile = (- exportName: string,- stream: ReadableStream<Uint8Array> | null,- ) => writeStream(joinPath(directoryPath, exportName), stream);-- const stream = await downloadManager.fileStream(file);- const fileName = fileFileName(file);-- if (file.metadata.fileType == FileType.livePhoto) {- const { imageFileName, imageData, videoFileName, videoData } =- await decodeLivePhoto(fileName, await new Response(stream).blob());- const imageExportName = await createExportName(imageFileName);- await writeStreamToFile(imageExportName, new Response(imageData).body);- try {- await writeStreamToFile(- await createExportName(videoFileName),- new Response(videoData).body,- );- } catch (e) {- await fs.rm(joinPath(directoryPath, imageExportName));- throw e;- }- } else {- await writeStreamToFile(await createExportName(fileName), stream);- }-};diff --git a/web/apps/albums/vendor/ente-gallery/services/share.ts b/web/apps/albums/vendor/ente-gallery/services/share.tsindex 3f37ff4bbd..144d8dfb12 100644--- a/web/apps/albums/vendor/ente-gallery/services/share.ts+++ b/web/apps/albums/vendor/ente-gallery/services/share.ts@@ -1,44 +1,11 @@import bs58 from "bs58";-import { fromB64, fromHex, toB64 } from "ente-base/crypto";--/**- * Add the collection key as the hash to the given URL.- *- * The hash fragment is a client side component and is not accessible to remote- * servers. The collection key is base-58 encoded and set as the hash in public- * URLs of shared albums.- *- * Use {@link extractCollectionKeyFromShareURL} to get back the collection key.-- * @param url The base URL for the public album.-- * @param collectionKey The base-64 encoded string representation of the- * collection key for the public album.- *- * @returns A URL that includes the base-58 encoded collection key as the hash- * fragment.- */-export const appendCollectionKeyToShareURL = async (- url: string,- collectionKey: string,-) => {- const sharableURL = new URL(url);-- const bytes = await fromB64(collectionKey);- sharableURL.hash = bs58.encode(bytes);- return sharableURL.href;-};+import { fromHex, toB64 } from "ente-base/crypto";/*** Extract the collection key from a public URL.*- * This is the inverse of {@link appendCollectionKeyToShareURL}, returning the- * base64 string representation of the collection key.- *- * collection key (bytes)- * => appendCollectionKeytoShareURL (base 64 => base 58)- * => URL hash => extractCollectionKeyBytesFromShareURL (base 58 => base 64)- * => collection key (bytes).+ * Public album URLs encode the collection key in the hash as base-58.+ * Legacy links might still carry the older hex encoding.*/export const extractCollectionKeyFromShareURL = async (url: URL) => {const ck = url.hash.slice(1);diff --git a/web/apps/albums/vendor/ente-gallery/services/upload/index.ts b/web/apps/albums/vendor/ente-gallery/services/upload/index.tsindex ba01db45ab..3d8c052f41 100644--- a/web/apps/albums/vendor/ente-gallery/services/upload/index.ts+++ b/web/apps/albums/vendor/ente-gallery/services/upload/index.ts@@ -1,184 +1,29 @@import { basename, dirname } from "ente-base/file-name";import log from "ente-base/log";import { customAPIOrigin } from "ente-base/origins";-import type { ZipItem } from "ente-base/types/ipc";import { exportMetadataDirectoryName } from "ente-gallery/export-dirs";import type { Collection } from "ente-media/collection";import type { EnteFile } from "ente-media/file";import { nullToUndefined } from "ente-utils/transform";import { z } from "zod";-/**- * Internal in-memory state shared by the functions in this module.- *- * This entire object will be reset on logout.- */class UploadState {- /**- * `true` if the workers should be disabled for uploads.- */shouldDisableCFUploadProxy = false;- /**- * `true` if uploads should include checksum metadata.- */checksumProtectedUploadsEnabled = false;}-/** State shared by the functions in this module. See {@link UploadState}. */let _state = new UploadState();/**- * Reset any internal state maintained by the module.- *- * This is primarily meant as a way for stateful apps (e.g. photos) to clear any- * user specific state on logout.- */-export const resetUploadState = () => {- _state = new UploadState();-};--/**- * An item to upload is one of the following:- *- * 1. [web | desktop] A file drag-and-dropped or selected by the user when we- * are running in a web browser. This is the {@link File} case. There is one- * special case when this can also happen when running in the context of our- * desktop app - when the user edits an existing image.- *- * 2. [desktop] A file drag-and-dropped or selected by the user when we are- * running in the context of our desktop app. In such cases, we also have the- * absolute path of the file in the user's local file system. This is the- * {@link FileAndPath} case.- *- * 3. [desktop] A file path programmatically requested by the desktop app. For- * example, we might be resuming a previously interrupted upload after an app- * restart (thus we no longer have access to the {@link File} from case 2).- * Or we could be uploading a file this is in one of the folders the user has- * asked us to watch for changes. This is the `string` case.- *- * 4. [desktop] A file within a zip file on the user's local file system. This- * too is only possible when we are running in the context of our desktop- * app. The user might have drag-and-dropped or selected a zip file, or it- * might be a zip file that they'd previously selected but we now are- * resuming an interrupted upload of. Either ways, what we have is a tuple- * containing the (path to zip file, and the name of an entry within that zip- * file). This is the {@link ZipItem} case.- *- * Case 1 is possible both when we're running in the web app and desktop app- * (that said, usually it only happens for the web app; it'll only happen in- * desktop in the special case when editing an image).- *- * Case 2, 3 and 4 are only possible when we're running in the desktop app.- *- * Also see: [Note: Reading a UploadItem].- */-export type UploadItem = File | FileAndPath | string | ZipItem;--/**- * When we are running in the context of our desktop app, we have access to the- * absolute path of {@link File} objects. This convenience type clubs these two- * bits of information, saving us the need to query the path again and again- * using the {@link getPathForFile} method of {@link Electron}.- */-export interface FileAndPath {- file: File;- path: string;-}--/**- * The cases of {@link UploadItem} that apply when we're running in the context- * of our desktop app, and the item that was uploaded has an associated file on- * the user's file system with a known path.- *- * See also {@link TimestampedFileSystemUploadItem}.- */-export type FileSystemUploadItem = Exclude<UploadItem, File>;--/**- * A {@link FileSystemUploadItem} augmented with the last modified time of the- * corresponding file on disk.- *- * By keeping the last modified time, we can use it as a test of whether or not- * the file on disk was modified since it was uploaded. Such an ability is- * useful for tasks where there can be a arbitrary delay between when the file- * was uploaded and when the file gets processed.- *- * See {@link toTimestampedDesktopUploadItem} for converting a- * {@link FileSystemUploadItem} into a {@link TimestampedFileSystemUploadItem}- * when running in the context of the desktop app.+ * The public albums uploader only handles browser-provided Files.*/-export interface TimestampedFileSystemUploadItem {- /**- * Information about the file system file which was uploaded to Ente.- */- fsUploadItem: FileSystemUploadItem;- /**- * The last modified time (epoch milliseconds) of the file system file.- */- lastModifiedMs: number;-}+export type UploadItem = File;/**- * An "path prefix"-like opaque string which can be used to disambiguate- * distinct source {@link UploadItem}s with the same name that are meant to be- * uploaded to the same destination Ente album.- *- * Th documentation of {@link UploadItem} describes the four cases that an- * {@link UploadItem} can be. For each of these, we augment an- * {@link UploadItem} with a prefix ("dirname") derived from its best "path":- *- * - Relative path or name in the case of web {@link File}s.- *- * - Absolute path in the case of desktop {@link File} or path or- * {@link FileAndPath}.- *- * - Path within the zip file for desktop {@link ZipItem}s.- *- * Thus, this path should not be treated as an address that can be used to- * retrieve the upload item, but rather as extra context that can help us- * distinguish between items by their relative or path prefix when their file- * names are the same and they're being uploaded to the same album.- *- * Consider the following hierarchy:- *- * Foo/2017/Album1/1.png- * Foo/2017/Album1/1.png.json- *- * Foo/2020/Album1/1.png- * Foo/2020/Album1/1.png.json- *- * If user uploads `Foo`, irrespective of if they select the "root" or "parent"- * option {@link CollectionMapping} option, when matching the takeout, only the- * Ente album is considered. So it will be undefined which JSON will get used,- * and both PNG files will get the same JSON, not their file system siblings.- *- * In such cases, the path prefix of the item being uploaded can act as extra- * context that can help us disambiguate and pick the sibling. Note how we don't- * need the path prefix to be absolute or relative or even addressable, we just- * need it as extra context that can help us disambiguate two items with- * otherwise the same name and that are destined for the same Ente album.- *- * So for our example, the path prefixes will be- *- * Foo/2017/Album1/1.png "Foo/2017/Album1"- * Foo/2017/Album1/1.png.json "Foo/2017/Album1"- *- * Foo/2020/Album1/1.png "Foo/2020/Album1"- * Foo/2020/Album1/1.png.json "Foo/2020/Album1"- *- * And can thus be used to associate the correct metadata JSON with the- * corresponding {@link UploadItem}.- *- * As a special case, "/metadata" at the end of the path prefix is discarded.- * This allows the metadata JSON written by export to be read back in during- * uploads. See: [Note: Fold "metadata" directory into parent folder].+ * Opaque folder-like context used when matching metadata JSON sidecars.*/export type UploadPathPrefix = string;-/**- * Return the {@link UploadPathPrefix} for the given {@link pathOrName} of an- * item being uploaded.- */export const uploadPathPrefix = (pathOrName: string) => {const folderPath = dirname(pathOrName);if (basename(folderPath) == exportMetadataDirectoryName) {@@ -187,80 +32,11 @@ export const uploadPathPrefix = (pathOrName: string) => {return folderPath;};-export type UploadItemAndPath = [UploadItem, string];--/**- * Group files that are that have the same parent folder into collections.- *- * This is used to segregate the list of {@link UploadItemAndPath}s that we- * obtain when an upload is initiated into per-collection groups when the user- * chooses the "parent" {@link CollectionMapping} option.- *- * For example, if the user selects files have a directory structure like:- *- * a- * / | \- * b j c- * /|\ / \- * e f g h i- *- * The files will grouped into 3 collections:- *- * [- * a => [j],- * b => [e, f, g],- * c => [h, i]- * ]- *- * @param defaultFolderName Optional collection name to use for any rooted files- * that do not have a parent folder. The function will throw if a default is not- * provided and we encounter any such files without a parent.- */-export const groupItemsBasedOnParentFolder = (- uploadItemAndPaths: UploadItemAndPath[],- defaultFolderName: string | undefined,-) => {- const result = new Map<string, UploadItemAndPath[]>();- for (const [uploadItem, pathOrName] of uploadItemAndPaths) {- const folderPath = dirname(pathOrName);- let folderName = basename(folderPath);- // [Note: Fold "metadata" directory into parent folder]- //- // If the parent folder of a file is "metadata" (the directory in which- // the exported JSON files are written), then we consider it to be part- // of the parent folder.- //- // e.g. for the file list- //- // [a/x.png, a/metadata/x.png.json]- //- // we want both to be grouped into the collection "a". This is so that- // we can cluster the metadata JSON files in the same collection as the- // file it is for.- if (folderName == exportMetadataDirectoryName) {- folderName = basename(dirname(folderPath));- }- if (!folderName) {- if (!defaultFolderName)- throw Error(`Leaf file (without default): ${pathOrName}`);- folderName = defaultFolderName;- }- if (!result.has(folderName)) result.set(folderName, []);- result.get(folderName)!.push([uploadItem, pathOrName]);- }- return result;-};-export interface LivePhotoAssets {- image: UploadItem;- video: UploadItem;+ image: File;+ video: File;}-/**- * An upload item with both parts of a live photo clubbed together.- *- * See: [Note: Intermediate file types during upload].- */export interface ClusteredUploadItem {localID: number;collectionID: number;@@ -268,167 +44,13 @@ export interface ClusteredUploadItem {isLivePhoto: boolean;uploadItem?: UploadItem;pathPrefix: UploadPathPrefix | undefined;- // TODO: Tie this to the isLivePhoto flag using a discriminated union.livePhotoAssets?: LivePhotoAssets;}-/**- * The file that we hand off to the uploader. Essentially- * {@link ClusteredUploadItem} with the {@link collection} attached to it.- *- * See: [Note: Intermediate file types during upload].- */export type UploadableUploadItem = ClusteredUploadItem & {collection: Collection;};-/**- * Result of {@link markUploadedAndObtainProcessableItem}; see the documentation- * of that function for the meaning and cases of this type.- */-export type ProcessableUploadItem = File | TimestampedFileSystemUploadItem;--/**- * As the long name suggests, this function does a rather specific thing:- *- * - If we're running in the context of the web app, it will return the- * {@link File} object that best represents the newly uploaded item. For- * images and videos, this'll be the newly uploaded file itself. For live- * photos, this will be the {@link File} object for the image component of the- * live photo.- *- * - If we're running in the context of the desktop app, it will first mark the- * item as having been uploaded in the persistent pending upload list that the- * desktop app keeps (so that they can be resumed on restarts). After this,- * it'll try to convert the item to a {@link TimestampedFileSystemUploadItem}- * if possible, otherwise will return the web {@link File}. As with the web- * case, in case of live photos the image component will be used in these- * transformations.- *- * @param item An {@link ClusteredUploadItem} that was recently uploaded.- */-export const markUploadedAndObtainProcessableItem = async (- item: ClusteredUploadItem,-): Promise<ProcessableUploadItem> => {- const electron = globalThis.electron;- if (!electron) {- const resultItem = item.isLivePhoto- ? item.livePhotoAssets!.image- : item.uploadItem;- if (resultItem instanceof File) {- return resultItem;- } else {- throw new Error(- `Unexpected upload item of type "${typeof resultItem}"`,- );- }- }-- const timestamped = async (- item: FileSystemUploadItem,- t: Promise<number>,- ): Promise<TimestampedFileSystemUploadItem> => ({- fsUploadItem: item,- lastModifiedMs: await t,- });-- if (item.isLivePhoto) {- const [p0, p1] = [- item.livePhotoAssets!.image,- item.livePhotoAssets!.video,- ];- if (Array.isArray(p0) && Array.isArray(p1)) {- return timestamped(p0, electron.markUploadedZipItem(p0, p1));- } else if (typeof p0 == "string" && typeof p1 == "string") {- return timestamped(p0, electron.markUploadedFile(p0, p1));- } else if (- typeof p0 == "object" &&- "path" in p0 &&- typeof p1 == "object" &&- "path" in p1- ) {- return timestamped(p0, electron.markUploadedFile(p0.path, p1.path));- } else {- throw new Error(- "Attempting to mark upload completion of unexpected desktop upload items",- );- }- } else {- const p = item.uploadItem!;- if (Array.isArray(p)) {- return timestamped(p, electron.markUploadedZipItem(p));- } else if (typeof p == "string") {- return timestamped(p, electron.markUploadedFile(p));- } else if (typeof p == "object" && "path" in p) {- return timestamped(p, electron.markUploadedFile(p.path));- } else {- return p;- }- }-};--/**- * Convert an {@link TimestampedFileSystemUploadItem} item back into a- * {@link FileSystemUploadItem} if the underlying file hasn't changed.- *- * While this functionality is not directly related to upload, this function is- * kept here since it is in some sense the inverse of- * {@link markUploadedAndObtainProcessableItem}.- *- * @param item A {@link TimestampedFileSystemUploadItem}.- *- * @param fsStatMtime A function that can be used to perform IPC and obtain the- * last modified time from the node side.- *- * @returns If the last modified time of the file system file pointed to by the- * given {@link item} is the same as what is recorded within the structure, then- * return the wrapped {@link FileSystemUploadItem}, otherwise return- * `undefined`.- *- * In case of any errors, also return `undefined`. This is because errors are- * expected if the underlying file system file was, e.g. renamed or removed- * between the time the file was uploaded and we got around to processing it.- */-export const fileSystemUploadItemIfUnchanged = async (- { fsUploadItem, lastModifiedMs }: TimestampedFileSystemUploadItem,- fsStatMtime: (path: string) => Promise<number>,-): Promise<FileSystemUploadItem | undefined> => {- let path: string;- if (typeof fsUploadItem == "string") {- path = fsUploadItem;- } else if (Array.isArray(fsUploadItem)) {- // The last modified time we recorded was of the zip file that contains- // the entry.- path = fsUploadItem[0];- } else {- path = fsUploadItem.path;- }-- try {- const mtimeMs = await fsStatMtime(path);- if (mtimeMs != lastModifiedMs) {- log.info(- `Not using upload item for path '${path}' since modified times have changed`,- );- return undefined;- }- return fsUploadItem;- } catch (e) {- log.warn(`Could not determine modified time for path '${path}'`, e);- return undefined;- }-};--/**- * For each of cases of {@link UploadItem} that apply when we're running in the- * context of our desktop app, return a value that can be passed to- * {@link Electron} functions over IPC.- */-export const toPathOrZipEntry = (fsUploadItem: FileSystemUploadItem) =>- typeof fsUploadItem == "string" || Array.isArray(fsUploadItem)- ? fsUploadItem- : fsUploadItem.path;-export type UploadPhase =| "preparing"| "readingMetadata"@@ -448,40 +70,9 @@ export type UploadResult =| { type: "uploadedWithStaticThumbnail"; file: EnteFile }| { type: "uploaded"; file: EnteFile };-/**- * Return true to disable the upload of files via Cloudflare Workers.- *- * [Note: Faster uploads via workers]- *- * These workers were introduced as a way of make file uploads faster:- * https://ente.io/blog/tech/making-uploads-faster/- *- * By default, that's the route we take. However, there are multiple reasons why- * this might be disabled.- *- * 1. During development and when self-hosting it we disable them to directly- * upload to the S3-compatible URLs returned by the ente API.- *- * 2. In rare cases, the user might have trouble reaching Cloudflare's network- * from their ISP. In such cases, the user can locally turn this off via- * settings.- *- * 3. There is also the original global toggle that was added when this feature- * was introduced.- *- * This function returns the in-memory value. It is updated when #2 changes (if- * we're running in a context where that makes sense). The #3 remote status is- * obtained once, on app start.- */export const shouldDisableCFUploadProxy = () =>_state.shouldDisableCFUploadProxy;-/**- * Update the in-memory value of {@link shouldDisableCFUploadProxy}.- *- * @param savedPreference An optional user preference that the user has- * expressed to disable the proxy.- */export const updateShouldDisableCFUploadProxy = async (savedPreference?: boolean,) => {@@ -489,29 +80,12 @@ export const updateShouldDisableCFUploadProxy = async (savedPreference || (await computeShouldDisableCFUploadProxy());};-/**- * Return `true` if uploads should include checksum metadata.- */export const areChecksumProtectedUploadsEnabled = () =>_state.checksumProtectedUploadsEnabled;-/**- * Update the in-memory value controlling checksum protected uploads.- */-export const updateChecksumProtectedUploadsEnabled = (enabled: boolean) => {- _state.checksumProtectedUploadsEnabled = enabled;-};-const computeShouldDisableCFUploadProxy = async () => {- // If a custom origin is set, that means we're not running a production- // deployment (maybe we're running locally, or being self-hosted).- //- // In such cases, disable the Cloudflare upload proxy (which won't work for- // self-hosters), and instead just directly use the upload URLs that museum- // gives us.if (await customAPIOrigin()) return true;- // See if the global flag to disable this is set.try {const res = await fetch("https://static.ente.io/feature_flags.json");return (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 c664cd340b..51713b6c4f 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@@ -1,6 +1,5 @@/** @file Dealing with the JSON metadata sidecar files */-import { ensureElectron } from "ente-base/electron";import { nameAndExtension } from "ente-base/file-name";import log from "ente-base/log";import { type Location } from "ente-base/types";@@ -8,7 +7,6 @@ import type {UploadItem,UploadPathPrefix,} from "ente-gallery/services/upload";-import { readStream } from "ente-gallery/utils/native-stream";/*** The data we read from the JSON metadata sidecar files.@@ -194,18 +192,7 @@ export const tryParseTakeoutMetadataJSON = async (}};-const uploadItemText = async (uploadItem: UploadItem) => {- if (uploadItem instanceof File) {- return await uploadItem.text();- } else if (typeof uploadItem == "string") {- return await ensureElectron().fs.readTextFile(uploadItem);- } else if (Array.isArray(uploadItem)) {- const { response } = await readStream(uploadItem);- return await response.text();- } else {- return await uploadItem.file.text();- }-};+const uploadItemText = async (uploadItem: UploadItem) => await uploadItem.text();const parseMetadataJSONText = (text: string) => {const metadataJSON_ = JSON.parse(text) as unknown;diff --git a/web/apps/albums/vendor/ente-gallery/services/upload/remote.ts b/web/apps/albums/vendor/ente-gallery/services/upload/remote.tsindex c211f8f59f..3a6f7ae4f5 100644--- a/web/apps/albums/vendor/ente-gallery/services/upload/remote.ts+++ b/web/apps/albums/vendor/ente-gallery/services/upload/remote.ts@@ -1,6 +1,5 @@import {authenticatedPublicAlbumsRequestHeaders,- authenticatedRequestHeaders,ensureOk,publicRequestHeaders,type HTTPRequestRetrier,@@ -31,51 +30,8 @@ const ObjectUploadURL = z.object({export type ObjectUploadURL = z.infer<typeof ObjectUploadURL>;-const ObjectUploadURLResponse = z.object({ urls: ObjectUploadURL.array() });-/**- * Fetch a fresh list of URLs from remote that can be used to upload objects.- *- * @param countHint An approximate number of objects that we're expecting to- * upload.- *- * @returns A list of pre-signed object URLs that can be used to upload data to- * the S3 bucket. Each URL also has an associated "object key" with which remote- * will refer to the uploaded object after it has been uploaded.- */-export const fetchUploadURLs = async (countHint: number) => {- const count = Math.min(50, countHint * 2);- const res = await fetch(- await apiURL("/files/upload-urls", { count, ts: Date.now() }),- { headers: await authenticatedRequestHeaders() },- );- ensureOk(res);- return ObjectUploadURLResponse.parse(await res.json()).urls;-};--export const fetchUploadURLWithMetadata = async ({- contentLength,- contentMd5,-}: {- contentLength: number;- contentMd5: string;-}) => {- const headers = new Headers(await authenticatedRequestHeaders());- headers.set("Content-Type", "application/json");- const res = await fetch(- await apiURL("/files/upload-url", { ts: Date.now() }),- {- method: "POST",- headers,- body: JSON.stringify({ contentLength, contentMD5: contentMd5 }),- },- );- ensureOk(res);- return ObjectUploadURL.parse(await res.json());-};--/**- * Sibling of {@link fetchUploadURLWithMetadata} for public albums.+ * Fetch a pre-signed URL for uploading a public album file or thumbnail.*/export const fetchPublicAlbumsUploadURLWithMetadata = async ({@@ -100,31 +56,8 @@ export const fetchPublicAlbumsUploadURLWithMetadata = async (return ObjectUploadURL.parse(await res.json());};-export const fetchMultipartUploadURLsWithMetadata = async ({- contentLength,- partLength,- partMd5s,-}: {- contentLength: number;- partLength: number;- partMd5s: string[];-}) => {- const headers = new Headers(await authenticatedRequestHeaders());- headers.set("Content-Type", "application/json");- const res = await fetch(- await apiURL("/files/multipart-upload-url", { ts: Date.now() }),- {- method: "POST",- headers,- body: JSON.stringify({ contentLength, partLength, partMd5s }),- },- );- ensureOk(res);- return MultipartUploadURLs.parse(await res.json());-};-/**- * Sibling of {@link fetchMultipartUploadURLsWithMetadata} for public albums.+ * Fetch multipart upload URLs for a large public album upload.*/export const fetchPublicAlbumsMultipartUploadURLsWithMetadata = async ({@@ -152,25 +85,6 @@ export const fetchPublicAlbumsMultipartUploadURLsWithMetadata = async (return MultipartUploadURLs.parse(await res.json());};-/**- * Sibling of {@link fetchUploadURLs} for public albums.- */-export const fetchPublicAlbumsUploadURLs = async (- countHint: number,- credentials: PublicAlbumsCredentials,-) => {- const count = Math.min(50, countHint * 2);- const res = await fetch(- await apiURL("/public-collection/upload-urls", {- count,- ts: Date.now(),- }),- { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },- );- ensureOk(res);- return ObjectUploadURLResponse.parse(await res.json()).urls;-};-/*** A list of URLs to use for multipart uploads.*@@ -199,49 +113,6 @@ const MultipartUploadURLs = z.object({export type MultipartUploadURLs = z.infer<typeof MultipartUploadURLs>;-const MultipartUploadURLsResponse = z.object({ urls: MultipartUploadURLs });--/**- * Fetch a {@link MultipartUploadURLs} structure from remote that can be used to- * upload a large object by splitting it into {@link uploadPartCount} parts.- *- * See: [Note: Multipart uploads].- *- * @param uploadPartCount The number of parts in which we want to upload the- * object.- *- * @returns A structure ({@link MultipartUploadURLs}) containing pre-signed URLs- * for uploading each part, a completion URL, and the final object key.- */-export const fetchMultipartUploadURLs = async (uploadPartCount: number) => {- const count = uploadPartCount;- const res = await fetch(- await apiURL("/files/multipart-upload-urls", { count, ts: Date.now() }),- { headers: await authenticatedRequestHeaders() },- );- ensureOk(res);- return MultipartUploadURLsResponse.parse(await res.json()).urls;-};--/**- * Sibling of {@link fetchMultipartUploadURLs} for public albums.- */-export const fetchPublicAlbumsMultipartUploadURLs = async (- uploadPartCount: number,- credentials: PublicAlbumsCredentials,-) => {- const count = uploadPartCount;- const res = await fetch(- await apiURL("/public-collection/multipart-upload-urls", {- count,- ts: Date.now(),- }),- { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },- );- ensureOk(res);- return MultipartUploadURLsResponse.parse(await res.json()).urls;-};-/*** Upload a file using a pre-signed URL.*@@ -489,11 +360,7 @@ const createMultipartUploadRequestBody = (** In both cases, the overall flow is roughly like the following:*- * 1. Obtain multiple pre-signed URLs from remote (museum). The specific API- * call will be different (because of the different authentication- * mechanisms) when we're running in the context of the photos app- * ({@link fetchMultipartUploadURLs}) and when we're running in the context- * of the public albums app ({@link fetchPublicAlbumsMultipartUploadURLs}).+ * 1. Obtain metadata-aware pre-signed URLs from the public album upload API.** 2. Break the file to be uploaded into parts, and upload each part using a PUT* request to one of the pre-signed URLs we got in step 1. There are two@@ -603,32 +470,10 @@ export interface UploadedFileObjectAttributes {}/**- * Create a new {@link EnteFile} on remote by providing remote with information- * about the file's contents (objects) that were uploaded, and other metadata- * about the file.- *- * Remote only, does not modify local state.- *- * @returns the newly created {@link EnteFile}.- */-export const postEnteFile = async (- postFileRequest: PostEnteFileRequest,-): Promise<RemoteEnteFile> => {- const res = await fetch(await apiURL("/files"), {- method: "POST",- headers: await authenticatedRequestHeaders(),- body: JSON.stringify(postFileRequest),- });- ensureOk(res);- return RemoteEnteFile.parse(await res.json());-};--/**- * Sibling of {@link postEnteFile} for public albums.+ * Create a new public album file on remote.*/export const postPublicAlbumsEnteFile = async (postFileRequest: PostEnteFileRequest,-credentials: PublicAlbumsCredentials,): Promise<RemoteEnteFile> => {const res = await fetch(await apiURL("/public-collection/file"), {diff --git a/web/apps/albums/vendor/ente-gallery/services/upload/thumbnail.ts b/web/apps/albums/vendor/ente-gallery/services/upload/thumbnail.tsindex c7c645bb36..feaaa40b4d 100644--- a/web/apps/albums/vendor/ente-gallery/services/upload/thumbnail.ts+++ b/web/apps/albums/vendor/ente-gallery/services/upload/thumbnail.ts@@ -1,10 +1,5 @@import log from "ente-base/log";-import { type Electron } from "ente-base/types/ipc";import * as ffmpeg from "ente-gallery/services/ffmpeg";-import {- toPathOrZipEntry,- type FileSystemUploadItem,-} from "ente-gallery/services/upload";import { FileType, type FileTypeInfo } from "ente-media/file-type";import { isHEICExtension } from "ente-media/formats";import { heicToJPEG } from "ente-media/heic-convert";@@ -21,9 +16,9 @@ const maxThumbnailSize = 100 * 1024; // 100 KB** [Note: Rendering arbitrary file types to the canvas needs a timeout]*- * When generating thumbnails on the web (or as a fallback on the desktop app),- * we use an HTML canvas. We take the file's content, a blob, and load it on the- * canvas by creating an image URL for this blob (using `createObjectURL`).+ * When generating thumbnails on the web, we use an HTML canvas. We take the+ * file's content, a blob, and load it on the canvas by creating an image URL+ * for this blob (using `createObjectURL`).** In case when the browser knows how to render images of this type, this works* great. Later we can read off the thumbnail from the (resized) canvas.@@ -173,35 +168,6 @@ export const generateVideoThumbnailUsingCanvas = async (blob: Blob) => {return await compressedJPEGData(canvas);};-/**- * Generate a JPEG thumbnail for the given file or path using native tools.- *- * This function only works when we're running in the context of our desktop- * app, and this dependency is enforced by the need to pass the {@link electron}- * object which we use to perform IPC with the Node.js side of our desktop app.- *- * @param fsUploadItem The image or video file on the user's file system whose- * thumbnail we want to generate.- *- * @param fileTypeInfo The type information for {@link fsUploadItem}.- *- * @return The JPEG data of the generated thumbnail.- *- * See also {@link generateThumbnailWeb}.- */-export const generateThumbnailNative = async (- electron: Electron,- fsUploadItem: FileSystemUploadItem,- fileTypeInfo: FileTypeInfo,-): Promise<Uint8Array> =>- fileTypeInfo.fileType == FileType.image- ? await electron.generateImageThumbnail(- toPathOrZipEntry(fsUploadItem),- maxThumbnailDimension,- maxThumbnailSize,- )- : ffmpeg.generateVideoThumbnailNative(electron, fsUploadItem);-/*** A fallback, black, thumbnail for use in cases where thumbnail generation* fails.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 19255579a4..407346641c 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@@ -4,8 +4,7 @@import type { BytesOrB64 } from "ente-base/crypto/types";import { streamEncryptionChunkSize } from "ente-base/crypto/types";import { type CryptoWorker } from "ente-base/crypto/worker";-import { ensureElectron } from "ente-base/electron";-import { basename, nameAndExtension } from "ente-base/file-name";+import { nameAndExtension } from "ente-base/file-name";import {ensureOk,HTTPError,@@ -23,7 +22,6 @@ import {detectFileTypeInfoFromChunk,isFileTypeNotSupportedError,} from "ente-gallery/utils/detect-type";-import { readStream } from "ente-gallery/utils/native-stream";import { decryptRemoteFile, type EnteFile } from "ente-media/file";import {fileFileName,@@ -39,7 +37,6 @@ import {encryptMagicMetadata,type RemoteMagicMetadata,} from "ente-media/magic-metadata";-import { addToCollection } from "ente-new/photos/services/collection";import { mergeUint8Arrays } from "ente-utils/array";import { ensureInteger, ensureNumber } from "ente-utils/ensure";import {@@ -56,25 +53,18 @@ import { matchJSONMetadata, type ParsedMetadataJSON } from "./metadata-json";import {completeMultipartUpload,completeMultipartUploadViaWorker,- fetchMultipartUploadURLs,- fetchMultipartUploadURLsWithMetadata,fetchPublicAlbumsMultipartUploadURLsWithMetadata,fetchPublicAlbumsUploadURLWithMetadata,- fetchUploadURLs,- fetchUploadURLWithMetadata,- postEnteFile,postPublicAlbumsEnteFile,putFile,putFilePart,putFilePartViaWorker,putFileViaWorker,type MultipartCompletedPart,- type ObjectUploadURL,type PostEnteFileRequest,} from "./remote";import {fallbackThumbnail,- generateThumbnailNative,generateThumbnailWeb,} from "./thumbnail";@@ -129,146 +119,69 @@ const multipartChunksPerPart = 5;/** Upload files to cloud storage */class UploadService {- private uploadURLs: ObjectUploadURL[] = [];- private pendingUploadCount = 0;private publicAlbumsCredentials: PublicAlbumsCredentials | undefined;- private activeUploadURLRefill: Promise<void> | undefined;init(publicAlbumsCredentials: PublicAlbumsCredentials | undefined) {this.publicAlbumsCredentials = publicAlbumsCredentials;}logout() {- this.uploadURLs = [];- this.pendingUploadCount = 0;this.publicAlbumsCredentials = undefined;- this.activeUploadURLRefill = undefined;}- async setFileCount(fileCount: number) {- this.pendingUploadCount = fileCount;- if (- areChecksumProtectedUploadsEnabled() ||- this.publicAlbumsCredentials- ) {- this.uploadURLs = [];- return;- }- await this.refillUploadURLs(); /* prefetch */- }+ async setFileCount(_fileCount: number) {}- reducePendingUploadCount() {- this.pendingUploadCount--;- }+ reducePendingUploadCount() {}async getUploadURL(metadata?: {contentLength: number;contentMd5: string;}) {- if (this.publicAlbumsCredentials) {- if (- metadata &&- metadata.contentLength >= 0 &&- metadata.contentMd5- ) {- return fetchPublicAlbumsUploadURLWithMetadata(- metadata,- this.publicAlbumsCredentials,- );- }- throw new Error("Public uploads require content metadata");+ const credentials = this.publicAlbumsCredentials;+ if (!credentials) {+ throw new Error("Missing public album credentials");}if (- areChecksumProtectedUploadsEnabled() &&- metadata &&- metadata.contentLength >= 0 &&- metadata.contentMd5+ !metadata ||+ metadata.contentLength < 0 ||+ !metadata.contentMd5) {- return fetchUploadURLWithMetadata(metadata);- }- if (this.uploadURLs.length == 0 && this.pendingUploadCount) {- await this.refillUploadURLs();+ throw new Error("Public uploads require content metadata");}- const url = this.uploadURLs.pop();- if (!url) throw new Error("Failed to obtain upload URL");- return url;- }-- private async refillUploadURLs() {try {- if (!this.activeUploadURLRefill) {- this.activeUploadURLRefill = this._refillUploadURLs();- }- await this.activeUploadURLRefill;- } finally {- this.activeUploadURLRefill = undefined;- }-- // Ensure that the upload URLs we have are unique.- //- // Sanity check added when this was a new implementation. Have kept it- // around, but it can be removed too.- if (- this.uploadURLs.length !=- new Set(this.uploadURLs.map((u) => u.url)).size- ) {- throw new Error("Duplicate upload URLs detected");- }- }-- private async _refillUploadURLs() {- if (this.publicAlbumsCredentials) {- throw new Error(- "Public uploads should request metadata upload URLs",+ return await fetchPublicAlbumsUploadURLWithMetadata(+ metadata,+ credentials,);- }- let urls: ObjectUploadURL[];- try {- urls = await fetchUploadURLs(this.pendingUploadCount);} catch (e) {throw translateURLFetchErrorIfNeeded(e);}- urls.forEach((u) => this.uploadURLs.push(u));}async fetchMultipartUploadURLs(- uploadPartCount: number,+ _uploadPartCount: number,metadata?: {contentLength: number;partLength: number;partMd5s: string[];},) {- if (this.publicAlbumsCredentials) {- if (- metadata &&- metadata.contentLength > 0 &&- metadata.partLength > 0 &&- metadata.partMd5s.length > 0- ) {- return fetchPublicAlbumsMultipartUploadURLsWithMetadata(- metadata,- this.publicAlbumsCredentials,- );- }- throw new Error(- "Public multipart uploads require content metadata",- );+ const credentials = this.publicAlbumsCredentials;+ if (!credentials) {+ throw new Error("Missing public album credentials");}if (- metadata &&- areChecksumProtectedUploadsEnabled() &&- metadata.contentLength > 0 &&- metadata.partLength > 0 &&- metadata.partMd5s.length > 0+ !metadata ||+ metadata.contentLength <= 0 ||+ metadata.partLength <= 0 ||+ metadata.partMd5s.length == 0) {- return fetchMultipartUploadURLsWithMetadata(metadata).catch(- (e: unknown) => {- throw translateURLFetchErrorIfNeeded(e);- },- );+ throw new Error("Public multipart uploads require content metadata");}- return fetchMultipartUploadURLs(uploadPartCount).catch((e: unknown) => {+ return fetchPublicAlbumsMultipartUploadURLsWithMetadata(+ metadata,+ credentials,+ ).catch((e: unknown) => {throw translateURLFetchErrorIfNeeded(e);});}@@ -282,12 +195,7 @@ export default uploadService;/*** Return the file name for the given {@link uploadItem}.*/-export const uploadItemFileName = (uploadItem: UploadItem) => {- if (uploadItem instanceof File) return uploadItem.name;- if (typeof uploadItem == "string") return basename(uploadItem);- if (Array.isArray(uploadItem)) return basename(uploadItem[1]);- return uploadItem.file.name;-};+export const uploadItemFileName = (uploadItem: UploadItem) => uploadItem.name;/* -- Various intermediate types used during upload -- */@@ -542,12 +450,7 @@ const removePotentialLivePhotoSuffix = (name: string, suffix?: string) => {* Return the size of the given {@link uploadItem}.*/const uploadItemSize = async (uploadItem: UploadItem): Promise<number> => {- if (uploadItem instanceof File) return uploadItem.size;- if (typeof uploadItem == "string")- return ensureElectron().pathOrZipItemSize(uploadItem);- if (Array.isArray(uploadItem))- return ensureElectron().pathOrZipItemSize(uploadItem);- return uploadItem.file.size;+ return uploadItem.size;};/**@@ -737,11 +640,11 @@ export const upload = async (** When we already have a File object the multiple reads are fine.*- * When we're in the context of our desktop app and have a path, it- * might be possible to optimize further by using `ReadableStream.tee`- * to perform these steps simultaneously. However, that'll require- * restructuring the code so that these steps run in a parallel manner- * (tee will not work for strictly sequential reads of large streams).+ * There might be room to optimize further by using+ * `ReadableStream.tee` to perform these steps simultaneously.+ * However, that'll require restructuring the code so that these steps+ * run in a parallel manner (tee will not work for strictly sequential+ * reads of large streams).*/let assetDetails: ReadAssetDetailsResult;@@ -784,15 +687,12 @@ export const upload = async (const matchInSameCollection = matches.find((f) => f.collectionID == collection.id,);- if (matchInSameCollection) {- return { type: "alreadyUploaded", file: matchInSameCollection };- } else {- // Any of the matching files can be used to add a symlink.- const symlink = Object.assign({}, anyMatch);- symlink.collectionID = collection.id;- await addToCollection(collection, [symlink]);- return { type: "addedSymlink", file: symlink };- }+ // The public albums uploader only writes into the current public+ // collection, and its dedup state is scoped to that collection.+ return {+ type: "alreadyUploaded",+ file: matchInSameCollection ?? anyMatch,+ };}abortIfCancelled();@@ -877,11 +777,6 @@ export const upload = async (* Convert specific HTTP errors during an API call to remote endpoints for* fetching new upload URLs into error with known messages (if applicable).*- * Can be used with the following functions:- *- * - {@link fetchUploadURLs}- * - {@link fetchMultipartUploadURLs}- **/const translateURLFetchErrorIfNeeded = (e: unknown) => {if (e instanceof HTTPError) {@@ -898,100 +793,18 @@ const translateURLFetchErrorIfNeeded = (e: unknown) => {};/**- * Read the given file or path or zip item into an in-memory representation.+ * Read the given file into an in-memory representation.** [Note: Reading a UploadItem]*- * The file can be either a web- * [File](https://developer.mozilla.org/en-US/docs/Web/API/File), the absolute- * path to a file on desk, a combination of these two, or a entry in a zip file- * on the user's local file system.- *- * tl;dr; There are four cases:- *- * 1. web / File- * 2. desktop / File (+ path)- * 3. desktop / path- * 4. desktop / ZipItem- *- * For the when and why, read on.- *- * The code that accesses files (e.g. uplaads) gets invoked in two contexts:- *- * 1. web: the normal mode, when we're running in as a web app in the browser.- *- * 2. desktop: when we're running inside our desktop app.- *- * In the web context, we'll always get a File, since within the browser we- * cannot programmatically construct paths to or arbitrarily access files on the- * user's file system.- *- * > Note that even if we were to somehow have an absolute path at hand, we- * cannot programmatically create such File objects to arbitrary absolute- * paths on user's local file system for security reasons.- *- * So in the web context, this will always be a File we get as a result of an- * explicit user interaction (e.g. drag and drop or using a file selector).- *- * In the desktop context, this can be either a File (+ path), or a path, or an- * entry within a zip file.- *- * 2. If the user provided us this file via some user interaction (say a drag- * and a drop), this'll still be a File. But unlike in the web context, we- * also have access to the full path of this file.- *- * 3. In addition, when running in the desktop app we have the ability to- * initiate programmatic access absolute paths on the user's file system. For- * example, if the user asks us to watch certain folders on their disk for- * changes, we'll be able to pick up new images being added, and in such- * cases, the parameter here will be a path. Another example is when resuming- * an previously interrupted upload - we'll only have the path at hand in- * such cases, not the original File object since the app subsequently- * restarted.- *- * 4. The user might've also initiated an upload of a zip file (or we might be- * resuming one). In such cases we will get a tuple (path to the zip file on- * the local file system, and the name of the entry within that zip file).- *- * Case 3 and 4, when we're provided a path, are simple. We don't have a choice,- * since we cannot still programmatically construct a File object (we can- * construct it on the Node.js layer, but it can't then be transferred over the- * IPC boundary). So all our operations use the path itself.- *- * Case 2 involves a choice on a use-case basis. Neither File nor the path is a- * better choice for all use cases.- *- * > The advantage of the File object is that the browser has already read it- * into memory for us. The disadvantage comes in the case where we need to- * communicate with the native Node.js layer of our desktop app. Since this- * communication happens over IPC, the File's contents need to be serialized- * and copied, which is a bummer for large videos etc.+ * The public albums uploader only deals with browser-provided+ * [File](https://developer.mozilla.org/en-US/docs/Web/API/File) objects.*/const readUploadItem = async (uploadItem: UploadItem): Promise<FileStream> => {- let underlyingStream: ReadableStream;- let file: File | undefined;- let fileSize: number;- let lastModifiedMs: number;-- if (typeof uploadItem == "string" || Array.isArray(uploadItem)) {- const {- response,- size,- lastModifiedMs: lm,- } = await readStream(uploadItem);- underlyingStream = response.body!;- fileSize = size;- lastModifiedMs = lm;- } else {- if (uploadItem instanceof File) {- file = uploadItem;- } else {- file = uploadItem.file;- }- underlyingStream = file.stream();- fileSize = file.size;- lastModifiedMs = file.lastModified;- }+ const file = uploadItem;+ const underlyingStream = file.stream();+ const fileSize = file.size;+ const lastModifiedMs = file.lastModified;const N = streamEncryptionChunkSize;const chunkCount = Math.ceil(fileSize / streamEncryptionChunkSize);@@ -1068,9 +881,8 @@ const readLivePhotoDetails = async ({ image, video }: LivePhotoAssets) => {};/**- * Read the beginning of the given file (or its path), or use its filename as a- * fallback, to determine its MIME type. From that, construct and return a- * {@link FileTypeInfo}.+ * Read the beginning of the given file to determine its MIME type. From that,+ * construct and return a {@link FileTypeInfo}.** While we're at it, also return the size of the file, and its last modified* time (expressed as epoch milliseconds).@@ -1309,25 +1121,10 @@ const extractImageOrVideoMetadata = async (const tryExtractImageMetadata = async (uploadItem: UploadItem,- lastModifiedMs: number | undefined,+ _lastModifiedMs: number | undefined,): Promise<ParsedMetadata | undefined> => {- let file: File;- if (typeof uploadItem == "string" || Array.isArray(uploadItem)) {- // 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(uploadItem);- const path = typeof uploadItem == "string" ? uploadItem : uploadItem[1];- const opts = lastModifiedMs ? { lastModified: lastModifiedMs } : {};- file = new File([await response.arrayBuffer()], basename(path), opts);- } else if (uploadItem instanceof File) {- file = uploadItem;- } else {- file = uploadItem.file;- }-try {- return await extractExif(file);+ return await extractExif(uploadItem);} catch (e) {const fileName = uploadItemFileName(uploadItem);log.error(`Failed to extract image metadata for ${fileName}`, e);@@ -1483,66 +1280,13 @@ const augmentWithThumbnail = async (fileTypeInfo: FileTypeInfo,fileStream: FileStream,): Promise<ThumbnailedFile> => {- let fileData: Uint8Array | undefined;let thumbnail: Uint8Array | undefined;let hasStaticThumbnail = false;- const electron = globalThis.electron;-- // 1. Native thumbnail generation using items's (effective) path.- if (electron && !(uploadItem instanceof File)) {- try {- thumbnail = await generateThumbnailNative(- electron,- uploadItem,- fileTypeInfo,- );- } catch (e) {- log.error("Native thumbnail generation failed", e);- }- }-- if (!thumbnail) {- let blob: Blob | undefined;- if (uploadItem instanceof File) {- // 2. Browser based thumbnail generation for File (blobs).- blob = uploadItem;- } else {- // 3. Browser based thumbnail generation for paths.- //- // We can only get here when we're running in our desktop app (since- // only that works with non-File uploadItems), and the thumbnail- // generation failed.- //- // There are no expected scenarios when this should happen.- //- // The fallback in this case involves reading the entire stream into- // memory, and passing that data across the IPC boundary in a single- // go (i.e. not in a streaming manner). This is risky for videos of- // unbounded sizes, and since anyways we are not expected to come- // here for videos, so we only apply this fallback for images.-- if (fileTypeInfo.fileType == FileType.image) {- const data = await readEntireStream(fileStream.stream);- blob = new Blob([data]);-- // The Readable stream cannot be read twice, so use the data- // directly for subsequent steps.- fileData = data;- } else {- const fileName = uploadItemFileName(uploadItem);- log.warn(- `Not using browser based thumbnail generation fallback for video at path ${fileName}`,- );- }- }-- try {- if (blob)- thumbnail = await generateThumbnailWeb(blob, fileTypeInfo);- } catch (e) {- log.error("Web thumbnail creation failed", e);- }+ try {+ thumbnail = await generateThumbnailWeb(uploadItem, fileTypeInfo);+ } catch (e) {+ log.error("Web thumbnail creation failed", e);}if (!thumbnail) {@@ -1551,7 +1295,7 @@ const augmentWithThumbnail = async (}return {- fileStreamOrData: fileData ?? fileStream,+ fileStreamOrData: fileStream,thumbnail,hasStaticThumbnail,};@@ -1772,7 +1516,6 @@ const uploadToBucket = async (uploadContext,requestRetrier,maxPercent,- checksumEnabled,));} else {const data =@@ -1887,12 +1630,9 @@ const uploadStreamUsingMultipart = async (uploadContext: UploadContext,requestRetrier: HTTPRequestRetrier,maxPercent: number,- checksumEnabled: boolean,) => {const { isCFUploadProxyDisabled, abortIfCancelled, updateUploadProgress } =uploadContext;- const shouldSendPartChecksums =- checksumEnabled || !!uploadContext.publicAlbumsCredentials;const { stream } = dataStream;const streamReader = stream.getReader();@@ -1900,94 +1640,39 @@ const uploadStreamUsingMultipart = async (let uploadPartCount = Math.ceil(dataStream.chunkCount / multipartChunksPerPart,);+ // Public album uploads always request metadata-aware multipart URLs, so we+ // first materialize each part to compute its checksum.+ const parts: Uint8Array[] = [];+ const partMd5s: string[] = [];+ let fileSize = 0;+ while (true) {+ abortIfCancelled();+ const partData = await nextMultipartUploadPart(streamReader);+ if (partData.length === 0) break;+ parts.push(partData);+ fileSize += partData.length;+ partMd5s.push(computeMd5Base64(partData));+ }+ const { done } = await streamReader.read();+ if (!done) throw new Error("More chunks than expected");- if (shouldSendPartChecksums) {- const parts: Uint8Array[] = [];- const partMd5s: string[] = [];- let fileSize = 0;- while (true) {- abortIfCancelled();- const partData = await nextMultipartUploadPart(streamReader);- if (partData.length === 0) break;- parts.push(partData);- fileSize += partData.length;- partMd5s.push(computeMd5Base64(partData));- }- const { done } = await streamReader.read();- if (!done) throw new Error("More chunks than expected");-- uploadPartCount = parts.length;- if (uploadPartCount == 0) {- throw new Error("Multipart upload produced no parts");- }- const firstPartLength = parts[0]?.length ?? 0;- if (firstPartLength == 0) {- throw new Error("Multipart part length missing");- }- const partLength = firstPartLength;-- const multipartUploadURLs =- await uploadService.fetchMultipartUploadURLs(uploadPartCount, {- contentLength: fileSize,- partLength,- partMd5s,- });-- const percentPerPart = maxPercent / uploadPartCount;- const completedParts: MultipartCompletedPart[] = [];- for (const [- index,- partUploadURL,- ] of multipartUploadURLs.partURLs.entries()) {- abortIfCancelled();-- const partNumber = index + 1;- const partData = parts[index];- const checksum = partMd5s[index];- if (!partData || !checksum) {- throw new Error("Multipart checksum part mismatch");- }-- const eTag = !isCFUploadProxyDisabled- ? await putFilePartViaWorker(- partUploadURL,- partData,- requestRetrier,- { contentMd5: checksum },- )- : await putFilePart(partUploadURL, partData, requestRetrier, {- contentMd5: checksum,- });- if (!eTag) throw new Error(eTagMissingErrorMessage);-- updateUploadProgress(fileLocalID, percentPerPart * partNumber);- completedParts.push({ partNumber, eTag });- parts[index] = new Uint8Array(0); // release memory- }-- const completionURL = multipartUploadURLs.completeURL;- if (!isCFUploadProxyDisabled) {- await completeMultipartUploadViaWorker(- completionURL,- completedParts,- requestRetrier,- );- } else {- await completeMultipartUpload(- completionURL,- completedParts,- requestRetrier,- );- }-- return { objectKey: multipartUploadURLs.objectKey, fileSize };+ uploadPartCount = parts.length;+ if (uploadPartCount == 0) {+ throw new Error("Multipart upload produced no parts");+ }+ const partLength = parts[0]?.length ?? 0;+ if (partLength == 0) {+ throw new Error("Multipart part length missing");}const multipartUploadURLs =- await uploadService.fetchMultipartUploadURLs(uploadPartCount);+ await uploadService.fetchMultipartUploadURLs(uploadPartCount, {+ contentLength: fileSize,+ partLength,+ partMd5s,+ });const percentPerPart = maxPercent / uploadPartCount;- let fileSize = 0;const completedParts: MultipartCompletedPart[] = [];for (const [index,@@ -1996,23 +1681,28 @@ const uploadStreamUsingMultipart = async (abortIfCancelled();const partNumber = index + 1;- const partData = await nextMultipartUploadPart(streamReader);- fileSize += partData.length;+ const partData = parts[index];+ const checksum = partMd5s[index];+ if (!partData || !checksum) {+ throw new Error("Multipart checksum part mismatch");+ }const eTag = !isCFUploadProxyDisabled? await putFilePartViaWorker(partUploadURL,partData,requestRetrier,+ { contentMd5: checksum },)- : await putFilePart(partUploadURL, partData, requestRetrier);+ : await putFilePart(partUploadURL, partData, requestRetrier, {+ contentMd5: checksum,+ });if (!eTag) throw new Error(eTagMissingErrorMessage);updateUploadProgress(fileLocalID, percentPerPart * partNumber);completedParts.push({ partNumber, eTag });+ parts[index] = new Uint8Array(0); // release memory}- const { done } = await streamReader.read();- if (!done) throw new Error("More chunks than expected");const completionURL = multipartUploadURLs.completeURL;if (!isCFUploadProxyDisabled) {@@ -2057,14 +1747,14 @@ const createRemoteFile = async (uploadContext: UploadContext,) => {const { publicAlbumsCredentials } = uploadContext;-- return publicAlbumsCredentials- ? retriedPostPublicAlbumsEnteFile(- newFileRequest,- publicAlbumsCredentials,- uploadContext,- )- : retriedPostEnteFile(newFileRequest, uploadContext);+ if (!publicAlbumsCredentials) {+ throw new Error("Missing public album credentials");+ }+ return retriedPostPublicAlbumsEnteFile(+ newFileRequest,+ publicAlbumsCredentials,+ uploadContext,+ );};const retriedPostPublicAlbumsEnteFile = async (@@ -2077,28 +1767,6 @@ const retriedPostPublicAlbumsEnteFile = async (abortIfCancelled();return postPublicAlbumsEnteFile(newFileRequest, credentials);},- {- abortIfNeeded: (e) => {- if (isUploadCancelledError(e)) throw e;- if (e instanceof HTTPError) {- switch (e.res.status) {- case 413:- throw new Error(fileTooLargeErrorMessage);- }- }- },- },- );--const retriedPostEnteFile = async (- newFileRequest: PostEnteFileRequest,- { abortIfCancelled }: UploadContext,-) =>- retryAsyncOperation(- () => {- abortIfCancelled();- return postEnteFile(newFileRequest);- },{abortIfNeeded: (e) => {if (isUploadCancelledError(e)) throw e;