Skip to content

armgit / ente

Public Imported from GitHub
0

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

locker-web: fail folder drops early on upload limits

Neeraj Gupta66cc96037e4d
diff --git a/web/apps/locker/src/components/lockerPage/useLockerActions.tsx b/web/apps/locker/src/components/lockerPage/useLockerActions.tsx
index 54c49e9ba0..d17ebf5883 100644
--- a/web/apps/locker/src/components/lockerPage/useLockerActions.tsx
+++ b/web/apps/locker/src/components/lockerPage/useLockerActions.tsx
@@ -26,6 +26,12 @@ import {
uploadLockerFile,
type LockerUploadProgress,
} from "services/remote";
+import {
+ lockerUploadAllowance,
+ LOCKER_MAX_FILE_SIZE_BYTES,
+ type LockerUploadLimitState,
+ type LockerUploadPreflightFailure,
+} from "services/locker-limits";
import type {
LockerCollection,
LockerItem,
@@ -106,34 +112,160 @@ const uploadCandidateFromFile = (
suggestedCollectionNames: collectionNamesFromRelativePath(relativePath),
});
-const uploadCandidatesFromEntry = async (
- entry: FileSystemEntry,
- parentPath = "",
-): Promise<LockerUploadCandidate[]> => {
- if (entry.isFile) {
- const file = await fileFromEntry(entry as FileSystemFileEntry);
- const relativePath = parentPath
- ? `${parentPath}/${file.name}`
- : file.name;
- return [uploadCandidateFromFile(file, relativePath)];
+const droppedUploadCandidateKey = (file: File, relativePath?: string) =>
+ `${relativePath ?? file.name}:${file.size}:${file.lastModified}`;
+
+interface DropUploadScanOptions {
+ remainingFileCount: number;
+ freeStorage: number;
+}
+
+interface DropUploadScanResult {
+ items: LockerUploadCandidate[];
+ preflightFailure?: LockerUploadPreflightFailure;
+}
+
+type PendingDroppedNode =
+ | {
+ type: "entry";
+ entry: FileSystemEntry;
+ parentPath: string;
+ }
+ | {
+ type: "file";
+ file: File;
+ relativePath: string;
+ };
+
+const collectUploadCandidatesFromDrop = async (
+ droppedItems: DragDataTransferItem[],
+ fallbackFiles: File[],
+ options: DropUploadScanOptions,
+): Promise<DropUploadScanResult> => {
+ const items: LockerUploadCandidate[] = [];
+ const pendingNodes: PendingDroppedNode[] = [];
+ const seenUploadCandidateKeys = new Set<string>();
+ let scannedNonEmptyFileCount = 0;
+ let scannedTotalSize = 0;
+
+ const addFile = (
+ file: File,
+ relativePath: string,
+ ): LockerUploadPreflightFailure | undefined => {
+ if (file.size === 0) {
+ return undefined;
+ }
+
+ const dedupeKey = droppedUploadCandidateKey(file, relativePath);
+ if (seenUploadCandidateKeys.has(dedupeKey)) {
+ return undefined;
+ }
+ seenUploadCandidateKeys.add(dedupeKey);
+
+ if (file.size > LOCKER_MAX_FILE_SIZE_BYTES) {
+ return { reason: "fileTooLarge", fileName: file.name };
+ }
+
+ scannedNonEmptyFileCount += 1;
+ if (scannedNonEmptyFileCount > options.remainingFileCount) {
+ return { reason: "fileCountLimit" };
+ }
+
+ scannedTotalSize += file.size;
+ if (scannedTotalSize > options.freeStorage) {
+ return { reason: "storageLimit" };
+ }
+
+ items.push(uploadCandidateFromFile(file, relativePath));
+ return undefined;
+ };
+
+ for (let index = droppedItems.length - 1; index >= 0; index -= 1) {
+ const item = droppedItems[index]!;
+ if (item.kind !== "file") {
+ continue;
+ }
+
+ const getAsEntry = item.webkitGetAsEntry;
+ const entry =
+ typeof getAsEntry === "function" ? getAsEntry.call(item) : null;
+ if (entry) {
+ pendingNodes.push({
+ type: "entry",
+ entry,
+ parentPath: "",
+ });
+ continue;
+ }
+
+ const file = item.getAsFile();
+ if (file) {
+ pendingNodes.push({
+ type: "file",
+ file,
+ relativePath: file.webkitRelativePath || file.name,
+ });
+ }
}
- if (entry.isDirectory) {
- const directoryPath = parentPath
- ? `${parentPath}/${entry.name}`
- : entry.name;
- const entries = await readDirectoryEntries(
- entry as FileSystemDirectoryEntry,
- );
- const items = await Promise.all(
- entries.map((childEntry) =>
- uploadCandidatesFromEntry(childEntry, directoryPath),
- ),
- );
- return items.flat();
+ if (pendingNodes.length === 0) {
+ for (const file of fallbackFiles) {
+ const preflightFailure = addFile(
+ file,
+ file.webkitRelativePath || file.name,
+ );
+ if (preflightFailure) {
+ return { items, preflightFailure };
+ }
+ }
+ return { items };
}
- return [];
+ while (pendingNodes.length > 0) {
+ const node = pendingNodes.pop()!;
+
+ if (node.type === "file") {
+ const preflightFailure = addFile(node.file, node.relativePath);
+ if (preflightFailure) {
+ return { items, preflightFailure };
+ }
+ continue;
+ }
+
+ if (node.entry.isFile) {
+ const file = await fileFromEntry(node.entry as FileSystemFileEntry);
+ const relativePath = node.parentPath
+ ? `${node.parentPath}/${file.name}`
+ : file.name;
+ const preflightFailure = addFile(file, relativePath);
+ if (preflightFailure) {
+ return { items, preflightFailure };
+ }
+ continue;
+ }
+
+ if (node.entry.isDirectory) {
+ const directoryPath = node.parentPath
+ ? `${node.parentPath}/${node.entry.name}`
+ : node.entry.name;
+ const directoryEntries = await readDirectoryEntries(
+ node.entry as FileSystemDirectoryEntry,
+ );
+ for (
+ let index = directoryEntries.length - 1;
+ index >= 0;
+ index -= 1
+ ) {
+ pendingNodes.push({
+ type: "entry",
+ entry: directoryEntries[index]!,
+ parentPath: directoryPath,
+ });
+ }
+ }
+ }
+
+ return { items };
};
const collectionIDsForItemMutation = (
@@ -155,6 +287,13 @@ interface UseLockerActionsProps {
masterKey?: string;
selectedCollectionID: number | null;
routerPathname: string;
+ ensureUploadLimitState: () => Promise<
+ | {
+ isProductionEndpoint: boolean;
+ userDetails: LockerUploadLimitState;
+ }
+ | undefined
+ >;
refreshData: (masterKey?: string) => Promise<void>;
navigateHome: () => void;
removeCollectionFromState: (collectionID: number) => void;
@@ -164,6 +303,7 @@ interface UseLockerActionsProps {
export const useLockerActions = ({
collections,
+ ensureUploadLimitState,
masterKey,
selectedCollectionID,
routerPathname,
@@ -257,6 +397,22 @@ export const useLockerActions = ({
const visibleDeleteCollectionDialog =
deleteCollectionDialog ?? deleteCollectionDialogRef.current;
+ const uploadPreflightFailureMessage = useCallback(
+ (failure: LockerUploadPreflightFailure) => {
+ switch (failure.reason) {
+ case "fileCountLimit":
+ return t("uploadFileCountLimitErrorBody");
+ case "fileTooLarge":
+ return t("uploadFileTooLargeErrorBody", {
+ fileName: failure.fileName ?? "",
+ });
+ case "storageLimit":
+ return t("uploadStorageLimitErrorBody");
+ }
+ },
+ [],
+ );
+
const refreshCollectionsAfterMutation = useCallback(async () => {
await new Promise((resolve) =>
setTimeout(resolve, COLLECTION_MUTATION_REFRESH_DELAY_MS),
@@ -666,60 +822,49 @@ export const useLockerActions = ({
dragDepthRef.current = 0;
setIsDragActive(false);
- const droppedItems = Array.from(
- event.dataTransfer.items,
- ) as DragDataTransferItem[];
- const entryItems = (
- await Promise.all(
- droppedItems
- .filter((item) => item.kind === "file")
- .map(async (item) => {
- const getAsEntry = item.webkitGetAsEntry;
- const entry =
- typeof getAsEntry === "function"
- ? getAsEntry.call(item)
- : null;
- if (!entry) {
- const file = item.getAsFile();
- return file
- ? [
- uploadCandidateFromFile(
- file,
- file.webkitRelativePath ||
- file.name,
- ),
- ]
- : [];
- }
- return uploadCandidatesFromEntry(entry);
- }),
- )
- ).flat();
-
- const droppedItemsList =
- entryItems.length > 0
- ? entryItems
- : Array.from(event.dataTransfer.files).map((file) =>
- uploadCandidateFromFile(
- file,
- file.webkitRelativePath || file.name,
- ),
- );
- const uniqueItems = droppedItemsList.filter(
- (item, index, items) =>
- items.findIndex(
- (candidate) =>
- (candidate.relativePath ?? candidate.file.name) ===
- (item.relativePath ?? item.file.name) &&
- candidate.file.size === item.file.size &&
- candidate.file.lastModified ===
- item.file.lastModified,
- ) === index,
- );
+ try {
+ const uploadLimitState = await ensureUploadLimitState();
+ if (!uploadLimitState) {
+ setToast(t("generic_error_retry"));
+ return;
+ }
+
+ const allowance = lockerUploadAllowance(
+ uploadLimitState.userDetails,
+ uploadLimitState.isProductionEndpoint,
+ );
+ const droppedItems = Array.from(
+ event.dataTransfer.items,
+ ) as DragDataTransferItem[];
+ const scanResult = await collectUploadCandidatesFromDrop(
+ droppedItems,
+ Array.from(event.dataTransfer.files),
+ {
+ remainingFileCount: allowance.remainingFileCount,
+ freeStorage: allowance.freeStorage,
+ },
+ );
- openUploadDialogForItems(uniqueItems);
+ if (scanResult.preflightFailure) {
+ setToast(
+ uploadPreflightFailureMessage(
+ scanResult.preflightFailure,
+ ),
+ );
+ return;
+ }
+
+ openUploadDialogForItems(scanResult.items);
+ } catch (error) {
+ log.error("Failed to process dropped Locker files", error);
+ setToast(t("generic_error_retry"));
+ }
},
- [openUploadDialogForItems],
+ [
+ ensureUploadLimitState,
+ openUploadDialogForItems,
+ uploadPreflightFailureMessage,
+ ],
);
const handleRenameCollection = useCallback(
diff --git a/web/apps/locker/src/pages/locker.tsx b/web/apps/locker/src/pages/locker.tsx
index f6016e1678..6b7adfb9a0 100644
--- a/web/apps/locker/src/pages/locker.tsx
+++ b/web/apps/locker/src/pages/locker.tsx
@@ -97,6 +97,7 @@ export const LockerPage: React.FC = () => {
visibleDeleteCollectionDialog,
} = useLockerActions({
collections,
+ ensureUploadLimitState,
masterKey,
selectedCollectionID,
routerPathname: router.pathname,
diff --git a/web/apps/locker/src/services/locker-limits.ts b/web/apps/locker/src/services/locker-limits.ts
index 53d889721f..10377a4186 100644
--- a/web/apps/locker/src/services/locker-limits.ts
+++ b/web/apps/locker/src/services/locker-limits.ts
@@ -32,6 +32,13 @@ export interface LockerUploadLimitState {
lockerFamilyFileCount?: number;
}
+export interface LockerUploadAllowance {
+ maxFileCount: number;
+ currentFileCount: number;
+ remainingFileCount: number;
+ freeStorage: number;
+}
+
export type LockerUploadPreflightFailureReason =
| "fileCountLimit"
| "fileTooLarge"
@@ -42,6 +49,30 @@ export interface LockerUploadPreflightFailure {
fileName?: string;
}
+export const lockerUploadAllowance = (
+ userDetails: LockerUploadLimitState,
+ isProductionEndpoint: boolean,
+): LockerUploadAllowance => {
+ const maxFileCount = effectiveLockerFileLimit(
+ userDetails.lockerFileLimit,
+ isProductionEndpoint,
+ );
+ const currentFileCount =
+ userDetails.isPartOfFamily &&
+ typeof userDetails.lockerFamilyFileCount === "number"
+ ? userDetails.lockerFamilyFileCount
+ : userDetails.fileCount;
+
+ return {
+ maxFileCount,
+ currentFileCount,
+ remainingFileCount: Math.max(maxFileCount - currentFileCount, 0),
+ freeStorage:
+ Math.max(userDetails.storageLimit - userDetails.usage, 0) +
+ LOCKER_STORAGE_BUFFER_BYTES,
+ };
+};
+
export const validateLockerUploadBatch = (
files: File[],
userDetails: LockerUploadLimitState | undefined,
@@ -58,24 +89,13 @@ export const validateLockerUploadBatch = (
return null;
}
- const maxFileCount = effectiveLockerFileLimit(
- userDetails.lockerFileLimit,
- isProductionEndpoint,
- );
- const currentFileCount =
- userDetails.isPartOfFamily &&
- typeof userDetails.lockerFamilyFileCount === "number"
- ? userDetails.lockerFamilyFileCount
- : userDetails.fileCount;
- if (currentFileCount + files.length > maxFileCount) {
+ const allowance = lockerUploadAllowance(userDetails, isProductionEndpoint);
+ if (files.length > allowance.remainingFileCount) {
return { reason: "fileCountLimit" };
}
- const freeStorage =
- Math.max(userDetails.storageLimit - userDetails.usage, 0) +
- LOCKER_STORAGE_BUFFER_BYTES;
const totalUploadSize = files.reduce((total, file) => total + file.size, 0);
- if (totalUploadSize > freeStorage) {
+ if (totalUploadSize > allowance.freeStorage) {
return { reason: "storageLimit" };
}