Skip to content

armgit / ente

Public Imported from GitHub
0

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

Show progress

vishnukvmd2d24b770af8e
diff --git a/web/apps/locker/src/components/CreateItemDialog.tsx b/web/apps/locker/src/components/CreateItemDialog.tsx
index 961da50d41..d281fe2b58 100644
--- a/web/apps/locker/src/components/CreateItemDialog.tsx
+++ b/web/apps/locker/src/components/CreateItemDialog.tsx
@@ -36,6 +36,7 @@ import React, {
useState,
} from "react";
import { formatLockerMutationError } from "services/locker-errors";
+import type { LockerUploadProgress } from "services/remote";
import type { LockerCollection, LockerItemType } from "types";
import { isCollectionOwner, visibleLockerCollections } from "types";
@@ -94,7 +95,11 @@ interface CreateItemDialogProps {
data: Record<string, unknown>,
collectionID: number,
) => Promise<void>;
- onUploadFile?: (file: File, collectionID: number) => Promise<void>;
+ onUploadProgress?: (
+ file: File,
+ collectionID: number,
+ onProgress: (progress: LockerUploadProgress) => void,
+ ) => Promise<void>;
onCreateCollection?: (name: string) => Promise<number>;
defaultCollectionID?: number | null;
initialFile?: File | null;
@@ -111,7 +116,7 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
onClose,
collections,
onSave,
- onUploadFile,
+ onUploadProgress,
onCreateCollection,
defaultCollectionID,
initialFile,
@@ -141,6 +146,8 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
);
const [showPassword, setShowPassword] = useState(false);
const [selectedFile, setSelectedFile] = useState<File | null>(null);
+ const [uploadProgress, setUploadProgress] =
+ useState<LockerUploadProgress | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const isFileMode = selectedOption === "file";
@@ -181,6 +188,7 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
setShowPassword(false);
setSelectedFile(initialFile ?? null);
setError(null);
+ setUploadProgress(null);
}, [
defaultCollectionID,
editCollectionID,
@@ -214,6 +222,7 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
setError(null);
setShowPassword(false);
setSelectedFile(null);
+ setUploadProgress(null);
onClose();
}, [onClose, saving, uploading]);
@@ -271,14 +280,23 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
}, [formData, handleClose, onSave, selectedCollectionID, selectedType]);
const handleUpload = useCallback(async () => {
- if (!selectedFile || selectedCollectionID === null || !onUploadFile) {
+ if (
+ !selectedFile ||
+ selectedCollectionID === null ||
+ !onUploadProgress
+ ) {
return;
}
setUploading(true);
setError(null);
+ setUploadProgress({ phase: "preparing" });
try {
- await onUploadFile(selectedFile, selectedCollectionID);
+ await onUploadProgress(
+ selectedFile,
+ selectedCollectionID,
+ setUploadProgress,
+ );
handleClose();
} catch (error) {
log.error("Failed to upload Locker file", error);
@@ -286,7 +304,7 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
} finally {
setUploading(false);
}
- }, [handleClose, onUploadFile, selectedCollectionID, selectedFile]);
+ }, [handleClose, onUploadProgress, selectedCollectionID, selectedFile]);
const canSave =
selectedType !== null &&
@@ -397,69 +415,98 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
</ButtonBase>
) : (
<Stack
- direction="row"
sx={{
- alignItems: "center",
- gap: 1.5,
- p: 2,
borderRadius: "12px",
backgroundColor: (theme) =>
theme.vars.palette.fill.faint,
+ overflow: "hidden",
}}
>
- <Box
+ <Stack
+ direction="row"
sx={{
- display: "flex",
alignItems: "center",
- justifyContent: "center",
- width: 48,
- height: 48,
- borderRadius: "12px",
- backgroundColor: lockerItemIconConfig(
- "file",
- selectedFile.name,
- ).backgroundColor,
- flexShrink: 0,
+ gap: 1.5,
+ p: 2,
}}
>
- {lockerItemIcon("file", {
- fileName: selectedFile.name,
- size: 24,
- strokeWidth: 1.9,
- })}
- </Box>
- <Box sx={{ flex: 1, minWidth: 0 }}>
- <Typography variant="body" noWrap>
- {selectedFile.name}
- </Typography>
- <Typography
- variant="small"
- sx={{ color: "text.faint" }}
+ <Box
+ sx={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ width: 48,
+ height: 48,
+ borderRadius: "12px",
+ backgroundColor:
+ lockerItemIconConfig(
+ "file",
+ selectedFile.name,
+ ).backgroundColor,
+ flexShrink: 0,
+ }}
>
- {formatFileSize(selectedFile.size)}
- </Typography>
- </Box>
- <FocusVisibleButton
- size="small"
- color="secondary"
- onClick={() => {
- setSelectedFile(null);
- if (fileInputRef.current) {
- fileInputRef.current.value = "";
+ {lockerItemIcon("file", {
+ fileName: selectedFile.name,
+ size: 24,
+ strokeWidth: 1.9,
+ })}
+ </Box>
+ <Box sx={{ flex: 1, minWidth: 0 }}>
+ <Typography variant="body" noWrap>
+ {selectedFile.name}
+ </Typography>
+ <Typography
+ variant="small"
+ sx={{ color: "text.faint" }}
+ >
+ {formatFileSize(selectedFile.size)}
+ </Typography>
+ </Box>
+ {!uploading && (
+ <FocusVisibleButton
+ size="small"
+ color="secondary"
+ onClick={() => {
+ setSelectedFile(null);
+ if (fileInputRef.current) {
+ fileInputRef.current.value =
+ "";
+ }
+ }}
+ >
+ {t("change")}
+ </FocusVisibleButton>
+ )}
+ </Stack>
+ {uploading && (
+ <LinearProgress
+ variant={
+ uploadProgress?.phase ===
+ "uploading"
+ ? "determinate"
+ : "indeterminate"
}
- }}
- >
- {t("change")}
- </FocusVisibleButton>
+ value={
+ uploadProgress?.phase ===
+ "uploading"
+ ? Math.min(
+ 100,
+ (uploadProgress.loaded /
+ Math.max(
+ uploadProgress.total,
+ 1,
+ )) *
+ 100,
+ )
+ : undefined
+ }
+ sx={{ height: 4, borderRadius: 0 }}
+ />
+ )}
</Stack>
)}
- {uploading && (
- <Box sx={{ width: "100%" }}>
- <LinearProgress />
- </Box>
- )}
-
{!isEditMode && (
<CollectionSelector
collections={displayCollections}
diff --git a/web/apps/locker/src/pages/locker.tsx b/web/apps/locker/src/pages/locker.tsx
index 6cd6af9a94..2a0bf97c90 100644
--- a/web/apps/locker/src/pages/locker.tsx
+++ b/web/apps/locker/src/pages/locker.tsx
@@ -44,6 +44,7 @@ import {
unshareCollection as unshareCollectionAPI,
updateInfoItem,
uploadLockerFile,
+ type LockerUploadProgress,
} from "services/remote";
import type { LockerCollection, LockerItem, LockerItemType } from "types";
import { getItemTitle } from "types";
@@ -411,10 +412,14 @@ export const LockerPage: React.FC = () => {
[masterKey, refreshData],
);
- const handleUploadFile = useCallback(
- async (file: File, collectionID: number) => {
+ const handleUploadFileWithProgress = useCallback(
+ async (
+ file: File,
+ collectionID: number,
+ onProgress: (progress: LockerUploadProgress) => void,
+ ) => {
if (!masterKey) throw new Error("No master key");
- await uploadLockerFile(file, collectionID, masterKey);
+ await uploadLockerFile(file, collectionID, masterKey, onProgress);
await refreshData();
setToast(t("uploadComplete"));
},
@@ -905,7 +910,7 @@ export const LockerPage: React.FC = () => {
onClose={handleCreateDialogClose}
collections={collections}
onSave={handleCreateItem}
- onUploadFile={handleUploadFile}
+ onUploadProgress={handleUploadFileWithProgress}
onCreateCollection={handleCreateCollection}
defaultCollectionID={selectedCollectionID}
initialFile={prefilledUploadFile}
diff --git a/web/apps/locker/src/services/remote.ts b/web/apps/locker/src/services/remote.ts
index c374c10b4f..8d451c7cd3 100644
--- a/web/apps/locker/src/services/remote.ts
+++ b/web/apps/locker/src/services/remote.ts
@@ -1794,6 +1794,11 @@ interface MultipartCompletedPart {
eTag: string;
}
+export type LockerUploadProgress =
+ | { phase: "preparing" }
+ | { phase: "uploading"; loaded: number; total: number }
+ | { phase: "finalizing" };
+
/**
* Request a presigned upload URL from the server.
*
@@ -1853,14 +1858,31 @@ const putFileToS3 = async (
url: string,
data: Uint8Array,
contentMd5: string,
+ onProgress?: (progress: { loaded: number; total?: number }) => void,
): Promise<void> => {
- const res = await fetch(url, {
- method: "PUT",
- headers: {
- "Content-Type": "application/octet-stream",
- "Content-MD5": contentMd5,
- },
- body: data,
+ const res = await new Promise<{
+ ok: boolean;
+ status: number;
+ statusText: string;
+ }>((resolve, reject) => {
+ const request = new XMLHttpRequest();
+ request.open("PUT", url);
+ request.setRequestHeader("Content-Type", "application/octet-stream");
+ request.setRequestHeader("Content-MD5", contentMd5);
+ request.upload.onprogress = (event) => {
+ onProgress?.({
+ loaded: event.loaded,
+ total: event.lengthComputable ? event.total : data.length,
+ });
+ };
+ request.onload = () =>
+ resolve({
+ ok: request.status >= 200 && request.status < 300,
+ status: request.status,
+ statusText: request.statusText,
+ });
+ request.onerror = () => reject(new Error("S3 upload failed"));
+ request.send(data);
});
if (!res.ok) {
throw new Error(`S3 upload failed: ${res.status} ${res.statusText}`);
@@ -1870,13 +1892,14 @@ const putFileToS3 = async (
const uploadSingleObject = async (
data: Uint8Array,
contentMd5: string,
+ onProgress?: (progress: { loaded: number; total?: number }) => void,
): Promise<string> => {
const maxAttempts = 3;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const uploadURL = await fetchUploadURL(data.length, contentMd5);
- await putFileToS3(uploadURL.url, data, contentMd5);
+ await putFileToS3(uploadURL.url, data, contentMd5, onProgress);
return uploadURL.objectKey;
} catch (error) {
if (attempt === maxAttempts) {
@@ -1892,19 +1915,56 @@ const putFilePartToS3 = async (
url: string,
data: Uint8Array,
contentMd5: string,
+ onProgress?: (progress: { loaded: number; total?: number }) => void,
): Promise<string> => {
- const res = await retryEnsuringHTTPOk(() =>
- fetch(url, {
- method: "PUT",
- headers: { ...publicRequestHeaders(), "Content-MD5": contentMd5 },
- body: data,
- }),
- );
- const eTag = res.headers.get("etag");
- if (!eTag) {
- throw new Error("Missing ETag from multipart upload response");
+ const maxAttempts = 3;
+
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ try {
+ const eTag = await new Promise<string | null>((resolve, reject) => {
+ const request = new XMLHttpRequest();
+ request.open("PUT", url);
+ for (const [headerName, headerValue] of Object.entries({
+ ...publicRequestHeaders(),
+ "Content-MD5": contentMd5,
+ })) {
+ request.setRequestHeader(headerName, headerValue);
+ }
+ request.upload.onprogress = (event) => {
+ onProgress?.({
+ loaded: event.loaded,
+ total: event.lengthComputable
+ ? event.total
+ : data.length,
+ });
+ };
+ request.onload = () => {
+ if (request.status < 200 || request.status >= 300) {
+ reject(
+ new Error(
+ `S3 multipart upload failed: ${request.status} ${request.statusText}`,
+ ),
+ );
+ return;
+ }
+ resolve(request.getResponseHeader("etag"));
+ };
+ request.onerror = () =>
+ reject(new Error("S3 multipart upload failed"));
+ request.send(data);
+ });
+ if (!eTag) {
+ throw new Error("Missing ETag from multipart upload response");
+ }
+ return eTag;
+ } catch (error) {
+ if (attempt === maxAttempts) {
+ throw error;
+ }
+ }
}
- return eTag;
+
+ throw new Error("Unreachable multipart upload retry state");
};
const completeMultipartUpload = async (
@@ -1940,6 +2000,31 @@ const mergeUint8Arrays = (chunks: Uint8Array[]): Uint8Array => {
return merged;
};
+const createAggregateUploadProgressReporter = (
+ total: number,
+ onProgress?: (progress: LockerUploadProgress) => void,
+) => {
+ let uploadedBytes = 0;
+
+ return {
+ reportPartProgress: (loaded: number) => {
+ onProgress?.({
+ phase: "uploading",
+ loaded: Math.min(total, uploadedBytes + loaded),
+ total,
+ });
+ },
+ completePart: (partLength: number) => {
+ uploadedBytes += partLength;
+ onProgress?.({
+ phase: "uploading",
+ loaded: Math.min(total, uploadedBytes),
+ total,
+ });
+ },
+ };
+};
+
/**
* Upload a file to Locker with E2E encryption.
*
@@ -1962,7 +2047,10 @@ export const uploadLockerFile = async (
file: File,
collectionID: number,
masterKey: string,
+ onProgress?: (progress: LockerUploadProgress) => void,
): Promise<number> => {
+ onProgress?.({ phase: "preparing" });
+
const plaintextChunkCount = Math.max(
1,
Math.ceil(file.size / STREAM_ENCRYPTION_CHUNK_SIZE),
@@ -2025,6 +2113,10 @@ export const uploadLockerFile = async (
partMd5s,
});
const completedParts: MultipartCompletedPart[] = [];
+ const progressReporter = createAggregateUploadProgressReporter(
+ encryptedFileSize,
+ onProgress,
+ );
for (const [index, partData] of parts.entries()) {
const partUploadURL = multipartUpload.partURLs[index];
@@ -2036,8 +2128,10 @@ export const uploadLockerFile = async (
partUploadURL,
partData,
partMd5,
+ ({ loaded }) => progressReporter.reportPartProgress(loaded),
);
completedParts.push({ partNumber: index + 1, eTag });
+ progressReporter.completePart(partData.length);
parts[index] = new Uint8Array(0);
}
@@ -2077,12 +2171,25 @@ export const uploadLockerFile = async (
encryptedFileObjectKey = await uploadSingleObject(
encryptedFileBytes,
encryptedFileMd5,
+ ({ loaded, total }) =>
+ onProgress?.({
+ phase: "uploading",
+ loaded,
+ total: total ?? encryptedFileBytes.length,
+ }),
);
}
} finally {
streamEncryptor.free();
}
+ onProgress?.({
+ phase: "uploading",
+ loaded: encryptedFileSize,
+ total: encryptedFileSize,
+ });
+ onProgress?.({ phase: "finalizing" });
+
// 3. Encrypt the black placeholder thumbnail with the file key
const encryptedThumb = await encryptFileStreamWithKey(
BLACK_THUMBNAIL_B64,