Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

sketch 1 wip

Manav Rathi87a1c9417e2a
diff --git a/desktop/src/main/services/ffmpeg-worker.ts b/desktop/src/main/services/ffmpeg-worker.ts
index f3b3cefa04..3d051301e9 100644
--- a/desktop/src/main/services/ffmpeg-worker.ts
+++ b/desktop/src/main/services/ffmpeg-worker.ts
@@ -46,7 +46,7 @@ export interface FFmpegUtilityProcess {
ffmpegGenerateHLSPlaylistAndSegments: (
inputFilePath: string,
outputPathPrefix: string,
- uploadURLs: string[],
+ authToken: string,
) => Promise<FFmpegGenerateHLSPlaylistAndSegmentsResult | undefined>;
ffmpegDetermineVideoDuration: (inputFilePath: string) => Promise<number>;
@@ -233,9 +233,11 @@ export interface FFmpegGenerateHLSPlaylistAndSegmentsResult {
* the user's local file system. This function will write the generated HLS
* playlist and video segments under this prefix.
*
- * @returns The paths to two files on the user's local file system - one
- * containing the generated HLS playlist, and the other containing the
- * transcoded and encrypted video segments that the HLS playlist refers to.
+ * @param authToken A token that can be used to make API request to obtain
+ * pre-signed S3 URLs for uploading the generated video segment file.
+ *
+ * @returns The path to the file on the user's file system containing the
+ * generated HLS playlist, and other metadata about the generated video stream.
*
* If the video is such that it doesn't require stream generation, then this
* function returns `undefined`.
@@ -243,7 +245,7 @@ export interface FFmpegGenerateHLSPlaylistAndSegmentsResult {
const ffmpegGenerateHLSPlaylistAndSegments = async (
inputFilePath: string,
outputPathPrefix: string,
- uploadURLs: string[],
+ authToken: string,
): Promise<FFmpegGenerateHLSPlaylistAndSegmentsResult | undefined> => {
const { isH264, isHDR, bitrate } =
await detectVideoCharacteristics(inputFilePath);
@@ -543,7 +545,7 @@ const ffmpegGenerateHLSPlaylistAndSegments = async (
// the generated .ts file.
videoSize = await fs.stat(videoPath).then((st) => st.size);
- await uploadVideoSegments(videoPath, videoSize, uploadURLs);
+ await uploadVideoSegments(videoPath, videoSize, authToken);
} catch (e) {
log.error("HLS generation failed", e);
await Promise.all([deletePathIgnoringErrors(playlistPath)]);
@@ -818,15 +820,32 @@ const pseudoFFProbeVideo = async (inputFilePath: string) => {
*
* @param videoSize The size in bytes of the file at {@link videoFilePath}.
*
- * @param uploadURLs A pre-signed URL(s) to upload the file. For singular
- * uploads this'll be a singleton array, otherwise will contain multipart URLs
- * and completion URL.
+ * @param authToken The user's auth token (for fetch pre-signed upload URLs).
*/
const uploadVideoSegments = async (
videoFilePath: string,
videoSize: number,
- uploadURLs: string[],
+ authToken: string,
) => {
+
+ // [Note: Passing HLS multipart upload URLs over IPC]
+ //
+ // For IPC convenience, we convert both normal upload URLs (where we have
+ // only a single pre-signed URL) and multipart upload URLs (where we have a
+ // list of pre-signed part upload URLs, and a completion URL) into an array.
+ //
+ // On the desktop side, we can parse the array and treat singleton arrays as
+ // expecting a normal upload, and otherwise split the array into parts and
+ // the completion URL (last item).
+ let objectUploadURLs: string[];
+ if (uploadURLs.url) {
+ objectUploadURLs = [uploadURLs.url];
+ } else if (uploadURLs.partURLs && uploadURLs.completeURL) {
+ objectUploadURLs = [...uploadURLs.partURLs, uploadURLs.completeURL];
+ } else {
+ throw new Error("Malformed upload URLs");
+ }
+
// This can be either a single pre-signed URL (for a normal upload), or a
// list of part upload URLs and a completion URL (for multipart uploads).
//
@@ -851,6 +870,108 @@ const uploadVideoSegments = async (
}
};
+const FilePreviewDataUploadURLResponse = z.object({
+ /**
+ * The objectID with which this uploaded data can be referred to post upload
+ * (e.g. when invoking {@link putVideoData}).
+ */
+ objectID: z.string(),
+ /**
+ * A presigned URL that can be used to upload the file.
+ *
+ * This will be present only if we requested a singular object upload URL.
+ */
+ url: z.string().nullish().transform(nullToUndefined),
+ /**
+ * A list of pre-signed URLs that can be used to upload parts of a multipart
+ * upload of the uploaded data.
+ *
+ * This will be present only if we requested a multipart upload URLs for the
+ * object by setting `isMultiPart` true in the request.
+ */
+ partURLs: z.string().array().nullish().transform(nullToUndefined),
+ /**
+ * A pre-signed URL that can be used to finalize the multipart upload.
+ *
+ * This will be present only if we requested a multipart upload URLs for the
+ * object by setting `isMultiPart` true in the request.
+ */
+ completeURL: z.string().nullish().transform(nullToUndefined),
+});
+
+/**
+ * Obtain a presigned URL(s) that can be used to upload the "file preview data"
+ * of type "vid_preview" (the file containing the encrypted video segments which
+ * the "vid_preview" HLS playlist for the file would refer to).
+ */
+export const getFilePreviewDataUploadURL = async (file: EnteFile) => {
+ // [Note: Estimating number of parts for a vid_preview upload]
+ //
+ // We need to determine the number of parts of a multipart upload that we
+ // will use to upload a vid_preview. However, we do not have the generated
+ // preview file yet - that'll happen later, in the desktop side.
+ //
+ // We could make this API request from the desktop app side, but that will
+ // require reinventing a lot of the wheels in that code.
+ //
+ // So instead, we try to estimate a reasonable number of parts into which
+ // the eventually generated video should be split for a multipart upload.
+ // Some relevant numbers:
+ //
+ // - A part needs to be a minimum 5 MB.
+ //
+ // - During regular file uploads, we use 20 MB parts.
+ //
+ // - If possible, we want to try and keep the part size below 100 MB. This
+ // is not a hard limit, but just a good to have to avoid hitting request
+ // size limits (e.g. see [Note: Multipart uploads]).
+ //
+ // The estimate we use is:
+ //
+ // partCount = (size) => Math.ceil((0.7 * size) / 100)
+ //
+ // That is, if the generated preview file is 70% of the original's size, how
+ // many 100 MB parts will it need.
+ //
+ // In practice, this will is a big overestimate of the generated preview
+ // size, a more typical video preview size will be in the 30% to 60% range.
+ //
+ // The eventual part size will then be:
+ //
+ // partSize = (totalSize, count) => Math.ceil(totalSize / count)
+ //
+ // As an example, for a 200 MB file, we'll estimate partCount of 2, and
+ // suppose the generated file is 50% of the original, then each part size
+ // will be 50 MB.
+ //
+ // As a sanity check of the other extreme, if the generated file is 10% of
+ // the original, we still end up with 10 MB parts.
+ let partCount = 1; // Default is single object upload.
+ const fileSize = file.info?.fileSize; /* bytes */
+ if (fileSize) {
+ const fileSizeMB = fileSize / 1024 / 1024;
+ // For files larger than 100 MB, estimate the number of ~100 MB parts.
+ if (fileSizeMB > 100) {
+ partCount = Math.ceil((0.7 * fileSize) / (100 * 1024));
+ }
+ }
+
+ const params = new URLSearchParams({
+ fileID: `${file.id}`,
+ type: "vid_preview",
+ });
+ if (partCount > 1) {
+ params.set("isMultiPart", "true");
+ params.set("count", partCount.toString());
+ }
+ const url = await apiURL("/files/data/preview-upload-url");
+ const res = await fetch(`${url}?${params.toString()}`, {
+ headers: await authenticatedRequestHeaders(),
+ });
+ ensureOk(res);
+ return FilePreviewDataUploadURLResponse.parse(await res.json());
+};
+
const uploadVideoSegmentsSingle = (
videoFilePath: string,
videoSize: number,
diff --git a/desktop/src/main/stream.ts b/desktop/src/main/stream.ts
index 3cbd332265..81f5e8c204 100644
--- a/desktop/src/main/stream.ts
+++ b/desktop/src/main/stream.ts
@@ -278,9 +278,8 @@ const handleVideoDone = async (token: string) => {
* The difference here is that we the conversion generates two streams^ - one
* for the HLS playlist itself, and one for the file containing the encrypted
* and transcoded video chunks. The video stream we write to the pre-signed
- * object upload URL(s) (provided via {@link params}), and then we return a JSON
- * object containing the token for the playlist, and other metadata for use by
- * the renderer.
+ * object upload URL(s), and then we return a JSON object containing the token
+ * for the playlist, and other metadata for use by the renderer.
*
* ^ if the video doesn't require a stream to be generated (e.g. it is very
* small and already uses a compatible codec) then a HTT 204 is returned and
@@ -290,8 +289,8 @@ const handleGenerateHLSWrite = async (
request: Request,
params: URLSearchParams,
) => {
- const uploadURLs = params.getAll("url");
- if (!uploadURLs.length) throw new Error("Missing upload URL(s)");
+ const authToken = params.get("authToken");
+ if (!authToken) throw new Error("Missing auth token");
let inputItem: Parameters<typeof makeFileForStreamOrPathOrZipItem>[0];
const path = params.get("path");
@@ -325,7 +324,7 @@ const handleGenerateHLSWrite = async (
result = await worker.ffmpegGenerateHLSPlaylistAndSegments(
inputFilePath,
outputFilePathPrefix,
- uploadURLs,
+ authToken,
);
if (!result) {
diff --git a/web/packages/gallery/services/file-data.ts b/web/packages/gallery/services/file-data.ts
index ecc5246456..2fa9f81b27 100644
--- a/web/packages/gallery/services/file-data.ts
+++ b/web/packages/gallery/services/file-data.ts
@@ -377,108 +377,6 @@ export const fetchFilePreviewData = async (
return z.object({ url: z.string() }).parse(await res.json()).url;
};
-const FilePreviewDataUploadURLResponse = z.object({
- /**
- * The objectID with which this uploaded data can be referred to post upload
- * (e.g. when invoking {@link putVideoData}).
- */
- objectID: z.string(),
- /**
- * A presigned URL that can be used to upload the file.
- *
- * This will be present only if we requested a singular object upload URL.
- */
- url: z.string().nullish().transform(nullToUndefined),
- /**
- * A list of pre-signed URLs that can be used to upload parts of a multipart
- * upload of the uploaded data.
- *
- * This will be present only if we requested a multipart upload URLs for the
- * object by setting `isMultiPart` true in the request.
- */
- partURLs: z.string().array().nullish().transform(nullToUndefined),
- /**
- * A pre-signed URL that can be used to finalize the multipart upload.
- *
- * This will be present only if we requested a multipart upload URLs for the
- * object by setting `isMultiPart` true in the request.
- */
- completeURL: z.string().nullish().transform(nullToUndefined),
-});
-
-/**
- * Obtain a presigned URL(s) that can be used to upload the "file preview data"
- * of type "vid_preview" (the file containing the encrypted video segments which
- * the "vid_preview" HLS playlist for the file would refer to).
- */
-export const getFilePreviewDataUploadURL = async (file: EnteFile) => {
- // [Note: Estimating number of parts for a vid_preview upload]
- //
- // We need to determine the number of parts of a multipart upload that we
- // will use to upload a vid_preview. However, we do not have the generated
- // preview file yet - that'll happen later, in the desktop side.
- //
- // We could make this API request from the desktop app side, but that will
- // require reinventing a lot of the wheels in that code.
- //
- // So instead, we try to estimate a reasonable number of parts into which
- // the eventually generated video should be split for a multipart upload.
- // Some relevant numbers:
- //
- // - A part needs to be a minimum 5 MB.
- //
- // - During regular file uploads, we use 20 MB parts.
- //
- // - If possible, we want to try and keep the part size below 100 MB. This
- // is not a hard limit, but just a good to have to avoid hitting request
- // size limits (e.g. see [Note: Multipart uploads]).
- //
- // The estimate we use is:
- //
- // partCount = (size) => Math.ceil((0.7 * size) / 100)
- //
- // That is, if the generated preview file is 70% of the original's size, how
- // many 100 MB parts will it need.
- //
- // In practice, this will is a big overestimate of the generated preview
- // size, a more typical video preview size will be in the 30% to 60% range.
- //
- // The eventual part size will then be:
- //
- // partSize = (totalSize, count) => Math.ceil(totalSize / count)
- //
- // As an example, for a 200 MB file, we'll estimate partCount of 2, and
- // suppose the generated file is 50% of the original, then each part size
- // will be 50 MB.
- //
- // As a sanity check of the other extreme, if the generated file is 10% of
- // the original, we still end up with 10 MB parts.
- let partCount = 1; // Default is single object upload.
- const fileSize = file.info?.fileSize; /* bytes */
- if (fileSize) {
- const fileSizeMB = fileSize / 1024 / 1024;
- // For files larger than 100 MB, estimate the number of ~100 MB parts.
- if (fileSizeMB > 100) {
- partCount = Math.ceil((0.7 * fileSize) / (100 * 1024));
- }
- }
-
- const params = new URLSearchParams({
- fileID: `${file.id}`,
- type: "vid_preview",
- });
- if (partCount > 1) {
- params.set("isMultiPart", "true");
- params.set("count", partCount.toString());
- }
- const url = await apiURL("/files/data/preview-upload-url");
- const res = await fetch(`${url}?${params.toString()}`, {
- headers: await authenticatedRequestHeaders(),
- });
- ensureOk(res);
- return FilePreviewDataUploadURLResponse.parse(await res.json());
-};
-
/**
* Update the video data associated with the given file to remote.
*
diff --git a/web/packages/gallery/services/video.ts b/web/packages/gallery/services/video.ts
index b9babc971b..1360bad816 100644
--- a/web/packages/gallery/services/video.ts
+++ b/web/packages/gallery/services/video.ts
@@ -9,7 +9,7 @@ import {
type PublicAlbumsCredentials,
} from "ente-base/http";
import { getKV, getKVB, getKVN, setKV } from "ente-base/kv";
-import { ensureLocalUser } from "ente-base/local-user";
+import { ensureAuthToken, ensureLocalUser } from "ente-base/local-user";
import log from "ente-base/log";
import { fileLogID, type EnteFile } from "ente-media/file";
import {
@@ -38,7 +38,6 @@ import { downloadManager, isNetworkDownloadError } from "./download";
import {
fetchFileData,
fetchFilePreviewData,
- getFilePreviewDataUploadURL,
putVideoData,
syncUpdatedFileDataFileIDs,
} from "./file-data";
@@ -999,39 +998,33 @@ const processQueueItem = async ({
// duplicate the stream beforehand, which invalidates the point of
// streaming.
//
- // So instead we provide the presigned upload URL to the node side so that
- // it can directly upload the generated video segments.
- const uploadURLs = await getFilePreviewDataUploadURL(file);
-
- const { objectID } = uploadURLs;
-
- // [Note: Passing HLS multipart upload URLs over IPC]
+ // Another mid-way option was to do it partially here - obtain the presigned
+ // upload URLs here (since we already have the rest of the scaffolding to
+ // make API requests), and then provide this pre-signed URL to the node side
+ // so that it can directly upload the generated video segments.
//
- // For IPC convenience, we convert both normal upload URLs (where we have
- // only a single pre-signed URL) and multipart upload URLs (where we have a
- // list of pre-signed part upload URLs, and a completion URL) into an array.
+ // However, that then gets into a issue for multipart uploads since we don't
+ // know the size of the generated HLS video segment file beforehand. We can
+ // try to estimate it, and that is indeed what we started off with, and that
+ // approach worked fine too.
//
- // On the desktop side, we can parse the array and treat singleton arrays as
- // expecting a normal upload, and otherwise split the array into parts and
- // the completion URL (last item).
- let objectUploadURLs: string[];
- if (uploadURLs.url) {
- objectUploadURLs = [uploadURLs.url];
- } else if (uploadURLs.partURLs && uploadURLs.completeURL) {
- objectUploadURLs = [...uploadURLs.partURLs, uploadURLs.completeURL];
- } else {
- throw new Error("Malformed upload URLs");
- }
+ // However, estimates being estimates, it felt better to make things more
+ // deterministic by moving the request for the pre-signed URLs also to the
+ // desktop app side. This also sidesteps the issue of passing along too much
+ // data (the multipart upload URLs) as request params to the desktop app.
+ // There was no specific issue again, it just felt that doing everything in
+ // the desktop app is more simple and straightforward (at the cost of
+ // needing set up of some API request scaffolding on the desktop side).
+ //
+ // We also need to pass the auth token to allow the desktop app to make the
+ // API request.
+ const authToken = await ensureAuthToken();
log.info(`Generate HLS for ${fileLogID(file)} | start`);
let res: GenerateHLSResult | undefined;
try {
- res = await initiateGenerateHLS(
- electron,
- sourceVideo,
- objectUploadURLs,
- );
+ res = await initiateGenerateHLS(electron, sourceVideo, authToken);
} catch (e) {
// Failures during stream generation on the native side are expected to
// happen in two cases:
diff --git a/web/packages/gallery/utils/native-stream.ts b/web/packages/gallery/utils/native-stream.ts
index 304c81bffe..6a4980f19d 100644
--- a/web/packages/gallery/utils/native-stream.ts
+++ b/web/packages/gallery/utils/native-stream.ts
@@ -189,8 +189,8 @@ export type GenerateHLSResult = z.infer<typeof GenerateHLSResult>;
*
* - Otherwise it should be a {@link ReadableStream} of the video contents.
*
- * @param objectUploadURL A presigned URL where the video segments should be
- * uploaded to.
+ * @param authToken The user's auth token (needed to make API requests to obtain
+ * the pre-signed URLs where the video segments should be uploaded to).
*
* @returns a token that can be used to retrieve the generated HLS playlist, and
* metadata about the generated video (its byte size and dimensions). See {@link
@@ -205,10 +205,9 @@ export type GenerateHLSResult = z.infer<typeof GenerateHLSResult>;
export const initiateGenerateHLS = async (
_: Electron,
video: FileSystemUploadItem | ReadableStream,
- objectUploadURLs: string[],
+ authToken: string,
): Promise<GenerateHLSResult | undefined> => {
- const params = new URLSearchParams({ op: "generate-hls" });
- for (const url of objectUploadURLs) params.append("url", url);
+ const params = new URLSearchParams({ op: "generate-hls", authToken });
let body: ReadableStream | null;
if (video instanceof ReadableStream) {