Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

Fix collection deletion behavior

Vishnu Mohandas9eac01ec017e
diff --git a/web/apps/locker/src/locales/en-US/translation.json b/web/apps/locker/src/locales/en-US/translation.json
index ca3beba2d3..885384868b 100644
--- a/web/apps/locker/src/locales/en-US/translation.json
+++ b/web/apps/locker/src/locales/en-US/translation.json
@@ -28,9 +28,13 @@
"enterCollectionName": "Enter collection name",
"renameCollection": "Rename",
"deleteCollection": "Delete",
+ "deleteCollectionTitle": "Delete collection",
"deleteCollectionConfirmation": "Are you sure you want to delete \"{{collectionName}}\"?",
+ "deleteCollectionDialogBody": "{{collectionName}} will be deleted permanently.",
+ "deleteCollectionFromEverywhere": "Also delete items from everywhere",
"collectionDeletedSuccessfully": "Collection deleted successfully",
"collectionRenamedSuccessfully": "Collection renamed successfully",
+ "collectionNotFoundError": "Collection not found",
"noCollections": "No collections",
"noCollectionsAvailableForSelection": "No collections available",
"noItemsMatchSelectedFilters": "No items match the selected filters",
@@ -88,6 +92,8 @@
"dropToSaveToLocker": "Drop to save to Locker",
"create": "Create",
"cancel": "Cancel",
+ "areYouSure": "Are you sure?",
+ "yesDeleteCollection": "Yes, delete collection",
"upload": "Upload",
"close": "Close",
"logout": "Logout",
diff --git a/web/apps/locker/src/locales/fr-FR/translation.json b/web/apps/locker/src/locales/fr-FR/translation.json
index 9e4dc9f0f3..a587c0d86f 100644
--- a/web/apps/locker/src/locales/fr-FR/translation.json
+++ b/web/apps/locker/src/locales/fr-FR/translation.json
@@ -24,9 +24,13 @@
"enterCollectionName": "Saisis le nom de la collection",
"renameCollection": "Renommer",
"deleteCollection": "Supprimer",
+ "deleteCollectionTitle": "Supprimer la collection",
"deleteCollectionConfirmation": "Es-tu sur de vouloir supprimer \"{{collectionName}}\" ?",
+ "deleteCollectionDialogBody": "{{collectionName}} sera supprimee definitivement.",
+ "deleteCollectionFromEverywhere": "Supprimer aussi les elements de partout",
"collectionDeletedSuccessfully": "Collection supprimee avec succes",
"collectionRenamedSuccessfully": "Collection renommee avec succes",
+ "collectionNotFoundError": "Collection introuvable",
"noCollections": "Aucune collection",
"noCollectionsAvailableForSelection": "Aucune collection disponible",
"noItemsMatchSelectedFilters": "Aucun element ne correspond aux filtres selectionnes",
@@ -70,6 +74,8 @@
"dropToSaveToLocker": "Depose pour enregistrer dans Locker",
"create": "Créer",
"cancel": "Annuler",
+ "areYouSure": "Etes-vous sur ?",
+ "yesDeleteCollection": "Oui, supprimer la collection",
"upload": "Televerser",
"close": "Fermer",
"logout": "Déconnexion",
diff --git a/web/apps/locker/src/locales/ja-JP/translation.json b/web/apps/locker/src/locales/ja-JP/translation.json
index c39333c439..5dc3681d2f 100644
--- a/web/apps/locker/src/locales/ja-JP/translation.json
+++ b/web/apps/locker/src/locales/ja-JP/translation.json
@@ -28,9 +28,13 @@
"enterCollectionName": "コレクション名を入力",
"renameCollection": "名前を変更",
"deleteCollection": "削除",
+ "deleteCollectionTitle": "コレクションを削除",
"deleteCollectionConfirmation": "「{{collectionName}}」を削除してもよろしいですか?",
+ "deleteCollectionDialogBody": "{{collectionName}} は完全に削除されます。",
+ "deleteCollectionFromEverywhere": "他のすべての場所からも項目を削除する",
"collectionDeletedSuccessfully": "コレクションが正常に削除されました",
"collectionRenamedSuccessfully": "コレクションの名前が正常に変更されました",
+ "collectionNotFoundError": "コレクションが見つかりません",
"noCollections": "コレクションがありません",
"noCollectionsAvailableForSelection": "利用可能なコレクションがありません",
"noItemsMatchSelectedFilters": "選択したフィルターに一致するアイテムがありません",
@@ -75,6 +79,8 @@
"dropToSaveToLocker": "ドロップしてLockerに保存",
"create": "作成",
"cancel": "キャンセル",
+ "areYouSure": "よろしいですか?",
+ "yesDeleteCollection": "はい、コレクションを削除します",
"uploadFileCountLimitErrorBodyWithUpgrade": "ファイル数の上限に達しました。<cta>アップグレード</cta>して有料プランをご利用ください。",
"upload": "アップロード",
"close": "閉じる",
diff --git a/web/apps/locker/src/pages/locker.tsx b/web/apps/locker/src/pages/locker.tsx
index a629a4b73d..67a2f481e5 100644
--- a/web/apps/locker/src/pages/locker.tsx
+++ b/web/apps/locker/src/pages/locker.tsx
@@ -1,9 +1,22 @@
import AddIcon from "@mui/icons-material/Add";
import CloudUploadOutlinedIcon from "@mui/icons-material/CloudUploadOutlined";
-import { Box, Button, Fab, Snackbar, Stack, Typography } from "@mui/material";
+import {
+ Box,
+ Button,
+ Checkbox,
+ Dialog,
+ DialogContent,
+ DialogTitle,
+ Fab,
+ FormControlLabel,
+ Snackbar,
+ Stack,
+ Typography,
+} from "@mui/material";
import { CreateItemDialog } from "components/CreateItemDialog";
import { ItemList } from "components/ItemList";
import { LockerCollectionShareDrawer } from "components/LockerCollectionShareDrawer";
+import { lockerDialogPaperSx } from "components/lockerDialogStyles";
import { LockerNavbar, LockerUnstableToast } from "components/LockerNavbar";
import { LockerSidebar } from "components/LockerSidebar";
import { sessionExpiredDialogAttributes } from "ente-accounts-rs/components/utils/dialog";
@@ -11,6 +24,8 @@ import { savedLocalUser } from "ente-accounts-rs/services/accounts-db";
import { stashRedirect } from "ente-accounts-rs/services/redirect";
import { masterKeyFromSession } from "ente-accounts-rs/services/session-storage";
import { LoadingIndicator } from "ente-base/components/loaders";
+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";
+import { LoadingButton } from "ente-base/components/mui/LoadingButton";
import { useBaseContext } from "ente-base/context";
import {
authenticatedRequestHeaders,
@@ -247,6 +262,12 @@ export const LockerPage: React.FC = () => {
data: Record<string, unknown>;
collectionID: number;
} | null>(null);
+ const [deleteCollectionDialog, setDeleteCollectionDialog] = useState<{
+ collectionID: number;
+ deleteFromEverywhere: boolean;
+ loading: boolean;
+ error: string | null;
+ } | null>(null);
// Toast state
const [toast, setToast] = useState<string | null>(null);
@@ -434,6 +455,12 @@ export const LockerPage: React.FC = () => {
void router.push("/", undefined, { shallow: true });
}, [router]);
+ const removeCollectionFromState = useCallback((collectionID: number) => {
+ setCollections((current) =>
+ current.filter((collection) => collection.id !== collectionID),
+ );
+ }, []);
+
const handleNavigateBack = useCallback(() => {
setSidebarOpen(false);
@@ -886,53 +913,91 @@ export const LockerPage: React.FC = () => {
const collection = collections.find(
(candidate) => candidate.id === collectionID,
);
- const collectionName = collection?.name ?? "";
- const shouldNavigateHome =
- router.pathname === "/collection" &&
- selectedCollectionID === collectionID;
- showMiniDialog({
- title: t("deleteCollection"),
- message: t("deleteCollectionConfirmation", { collectionName }),
- continue: {
- text: t("delete"),
- color: "critical",
- action: async () => {
- if (!collection) {
- throw new Error("Collection not found");
- }
-
- if (collection.items.length > 0) {
- if (!masterKey) {
- throw new Error("Missing master key");
- }
+ if (!collection) {
+ throw new Error("Collection not found");
+ }
- await deleteCollectionKeepingFiles(
- collection,
- masterKey,
- );
- } else {
- await deleteCollectionAPI(collectionID);
- }
- if (shouldNavigateHome) {
- navigateHome();
- }
- await refreshData();
- setToast(t("collectionDeletedSuccessfully"));
- },
- },
+ setDeleteCollectionDialog({
+ collectionID,
+ deleteFromEverywhere: false,
+ loading: false,
+ error: null,
});
},
- [
- collections,
- masterKey,
- navigateHome,
- refreshData,
- router.pathname,
- selectedCollectionID,
- showMiniDialog,
- ],
+ [collections],
);
+ const handleConfirmDeleteCollection = useCallback(async () => {
+ if (!deleteCollectionDialog) {
+ return;
+ }
+
+ const collection = collections.find(
+ (candidate) => candidate.id === deleteCollectionDialog.collectionID,
+ );
+ if (!collection) {
+ setDeleteCollectionDialog((current) =>
+ current
+ ? { ...current, error: t("collectionNotFoundError") }
+ : current,
+ );
+ return;
+ }
+
+ const shouldNavigateHome =
+ router.pathname === "/collection" &&
+ selectedCollectionID === collection.id;
+
+ setDeleteCollectionDialog((current) =>
+ current ? { ...current, loading: true, error: null } : current,
+ );
+
+ try {
+ if (deleteCollectionDialog.deleteFromEverywhere) {
+ await deleteCollectionAPI(collection.id);
+ } else if (collection.items.length > 0) {
+ if (!masterKey) {
+ throw new Error("Missing master key");
+ }
+
+ await deleteCollectionKeepingFiles(collection, masterKey);
+ } else {
+ await deleteCollectionAPI(collection.id, { keepFiles: true });
+ }
+
+ if (shouldNavigateHome) {
+ navigateHome();
+ }
+ removeCollectionFromState(collection.id);
+ await refreshData();
+ setToast(t("collectionDeletedSuccessfully"));
+ setDeleteCollectionDialog(null);
+ } catch (error) {
+ log.error("Failed to delete collection", error);
+ setDeleteCollectionDialog((current) =>
+ current
+ ? {
+ ...current,
+ loading: false,
+ error:
+ error instanceof Error
+ ? error.message
+ : t("failedToDeleteCollection"),
+ }
+ : current,
+ );
+ }
+ }, [
+ collections,
+ deleteCollectionDialog,
+ masterKey,
+ navigateHome,
+ removeCollectionFromState,
+ refreshData,
+ router.pathname,
+ selectedCollectionID,
+ ]);
+
const handleOpenShareCollection = useCallback(
(collection: LockerCollection) => {
setShareCollectionID(collection.id);
@@ -1089,6 +1154,102 @@ export const LockerPage: React.FC = () => {
onUnshareCollection={handleUnshareCollection}
onRefreshSharees={fetchCollectionSharees}
/>
+ <Dialog
+ open={deleteCollectionDialog !== null}
+ onClose={() => {
+ if (!deleteCollectionDialog?.loading) {
+ setDeleteCollectionDialog(null);
+ }
+ }}
+ fullWidth
+ maxWidth="xs"
+ slotProps={{
+ paper: {
+ sx: {
+ ...lockerDialogPaperSx,
+ width: "min(100%, 420px)",
+ },
+ },
+ }}
+ >
+ <DialogTitle sx={{ pb: 1 }}>
+ {t("deleteCollectionTitle")}
+ </DialogTitle>
+ <DialogContent>
+ <Stack sx={{ gap: 2.25 }}>
+ <Typography sx={{ color: "text.muted" }}>
+ {t("deleteCollectionDialogBody", {
+ collectionName:
+ collections.find(
+ (candidate) =>
+ candidate.id ===
+ deleteCollectionDialog?.collectionID,
+ )?.name ?? "",
+ })}
+ </Typography>
+ {(collections.find(
+ (candidate) =>
+ candidate.id ===
+ deleteCollectionDialog?.collectionID,
+ )?.items.length ?? 0) > 0 && (
+ <FormControlLabel
+ control={
+ <Checkbox
+ checked={
+ deleteCollectionDialog?.deleteFromEverywhere ??
+ false
+ }
+ disabled={
+ deleteCollectionDialog?.loading
+ }
+ onChange={(event) =>
+ setDeleteCollectionDialog(
+ (current) =>
+ current
+ ? {
+ ...current,
+ deleteFromEverywhere:
+ event.target
+ .checked,
+ }
+ : current,
+ )
+ }
+ />
+ }
+ label={t("deleteCollectionFromEverywhere")}
+ sx={{ alignItems: "center", m: 0 }}
+ />
+ )}
+ {deleteCollectionDialog?.error && (
+ <Typography
+ variant="small"
+ sx={{ color: "critical.main" }}
+ >
+ {deleteCollectionDialog.error}
+ </Typography>
+ )}
+ <Stack direction="row" sx={{ gap: 1 }}>
+ <FocusVisibleButton
+ fullWidth
+ color="secondary"
+ disabled={deleteCollectionDialog?.loading}
+ onClick={() => setDeleteCollectionDialog(null)}
+ >
+ {t("cancel")}
+ </FocusVisibleButton>
+ <LoadingButton
+ fullWidth
+ color="critical"
+ loading={deleteCollectionDialog?.loading}
+ onClick={() => void handleConfirmDeleteCollection()}
+ >
+ {t("delete")}
+ </LoadingButton>
+ </Stack>
+ </Stack>
+ </DialogContent>
+ </Dialog>
{!isTrashView && (
<Fab
diff --git a/web/apps/locker/src/services/remote.ts b/web/apps/locker/src/services/remote.ts
index 28b4c5ece6..87a07c7aac 100644
--- a/web/apps/locker/src/services/remote.ts
+++ b/web/apps/locker/src/services/remote.ts
@@ -237,6 +237,11 @@ const getEncryptedFileRecord = (
const getAllEncryptedFileRecords = (): EncryptedFileRecord[] =>
[...encryptedFiles.values()].flatMap((records) => [...records.values()]);
+const getCollectionIDsForFile = (fileID: number): number[] => {
+ const records = encryptedFiles.get(fileID);
+ return records ? [...records.keys()] : [];
+};
+
const describeCryptoError = (e: unknown): string => {
if (typeof e === "object" && e && "code" in e) {
const code = typeof e.code === "string" ? e.code : "unknown";
@@ -1716,6 +1721,7 @@ export const restoreFromTrash = async (
export const createCollection = async (
name: string,
masterKey: string,
+ type = "folder",
): Promise<number> => {
// Generate collection key
const collectionKey = await generateKey();
@@ -1738,7 +1744,7 @@ export const createCollection = async (
keyDecryptionNonce: encryptedKey.nonce,
encryptedName: encryptedName.encryptedData,
nameDecryptionNonce: encryptedName.nonce,
- type: "folder",
+ type,
}),
});
ensureOk(res);
@@ -1746,6 +1752,27 @@ export const createCollection = async (
return data.collection.id;
};
+const ensureUncategorizedCollection = async (masterKey: string) => {
+ let uncategorizedCollection = [...encryptedCollections.values()].find(
+ (candidate) => candidate.type === "uncategorized",
+ );
+ if (uncategorizedCollection) {
+ return uncategorizedCollection;
+ }
+
+ await createCollection("Uncategorized", masterKey, "uncategorized");
+ await fetchLockerData(masterKey);
+
+ uncategorizedCollection = [...encryptedCollections.values()].find(
+ (candidate) => candidate.type === "uncategorized",
+ );
+ if (!uncategorizedCollection) {
+ throw new Error("Failed to create Uncategorized collection");
+ }
+
+ return uncategorizedCollection;
+};
+
/**
* Rename a collection.
*
@@ -1812,12 +1839,7 @@ export const deleteCollectionKeepingFiles = async (
): Promise<void> => {
const collectionID = collection.id;
const currentUserID = ensureLocalUser().id;
- const uncategorizedCollection = [...encryptedCollections.values()].find(
- (candidate) => candidate.type === "uncategorized",
- );
- if (!uncategorizedCollection) {
- throw new Error("Uncategorized collection not found in cache");
- }
+ let uncategorizedCollection: EncryptedCollectionRecord | undefined;
const fileIDsToRemove: number[] = [];
const filesToMoveByTargetCollectionID = new Map<
@@ -1833,7 +1855,7 @@ export const deleteCollectionKeepingFiles = async (
continue;
}
- const otherOwnedCollectionIDs = item.collectionIDs.filter(
+ const otherOwnedCollectionIDs = getCollectionIDsForFile(item.id).filter(
(itemCollectionID) => {
if (itemCollectionID === collectionID) {
return false;
@@ -1849,8 +1871,16 @@ export const deleteCollectionKeepingFiles = async (
},
);
+ if (otherOwnedCollectionIDs.length === 0 && !uncategorizedCollection) {
+ uncategorizedCollection =
+ await ensureUncategorizedCollection(masterKey);
+ }
+
const targetCollectionID =
- otherOwnedCollectionIDs[0] ?? uncategorizedCollection.id;
+ otherOwnedCollectionIDs[0] ?? uncategorizedCollection?.id;
+ if (!targetCollectionID) {
+ throw new Error("Failed to resolve target collection");
+ }
const fileKey = await decryptFileKeyForCollection(
item.id,
collectionID,