Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

Fix collection deletion

vishnukvmdd12e7889cfee
diff --git a/web/apps/locker/src/locales/en-US/translation.json b/web/apps/locker/src/locales/en-US/translation.json
index 6c6c092b79..41a458bc36 100644
--- a/web/apps/locker/src/locales/en-US/translation.json
+++ b/web/apps/locker/src/locales/en-US/translation.json
@@ -26,16 +26,16 @@
"createNewCollection": "Create new collection",
"createCollectionButton": "Create collection",
"enterCollectionName": "Enter collection name",
- "renameCollection": "Rename collection",
- "deleteCollection": "Delete collection",
- "deleteCollectionConfirmation": "Are you sure you want to delete \"{collectionName}\"?",
+ "renameCollection": "Rename",
+ "deleteCollection": "Delete",
+ "deleteCollectionConfirmation": "Are you sure you want to delete \"{{collectionName}}\"?",
"collectionDeletedSuccessfully": "Collection deleted successfully",
"collectionRenamedSuccessfully": "Collection renamed successfully",
"noCollections": "No collections",
"noCollectionsAvailableForSelection": "No collections available",
"noItemsMatchSelectedFilters": "No items match the selected filters",
- "noFilesFoundForQuery": "No items found for \"{query}\"",
- "noCollectionsFoundForQuery": "No collections found for \"{query}\"",
+ "noFilesFoundForQuery": "No items found for \"{{query}}\"",
+ "noCollectionsFoundForQuery": "No collections found for \"{{query}}\"",
"seeAllCollections": "All collections",
"restoreToCollection": "Restore to collection",
"filesRestoredSuccessfully": "{{count, number}} items restored successfully",
@@ -65,7 +65,7 @@
"download": "Download",
"downloading": "Downloading...",
"downloadFailed": "Download failed",
- "copiedToClipboard": "{fieldName} copied to clipboard",
+ "copiedToClipboard": "{{fieldName}} copied to clipboard",
"noteName": "Title",
"noteContent": "Content",
"recordName": "Record name",
@@ -88,7 +88,7 @@
"upload": "Upload",
"close": "Close",
"logout": "Logout",
- "failedToLoadCollections": "Failed to load collections: {error}",
+ "failedToLoadCollections": "Failed to load collections: {{error}}",
"deleteFileConfirmation": "Are you sure you want to delete <strong>{{fileName}}</strong>?",
"allItems": "All Items",
"lockerCollectionsCount": "{{count, number}} collections",
diff --git a/web/apps/locker/src/locales/fr-FR/translation.json b/web/apps/locker/src/locales/fr-FR/translation.json
index e7921f1f39..b238f0dfb4 100644
--- a/web/apps/locker/src/locales/fr-FR/translation.json
+++ b/web/apps/locker/src/locales/fr-FR/translation.json
@@ -22,16 +22,16 @@
"createNewCollection": "Creer une nouvelle collection",
"createCollectionButton": "Creer une collection",
"enterCollectionName": "Saisis le nom de la collection",
- "renameCollection": "Renommer la collection",
- "deleteCollection": "Supprimer la collection",
- "deleteCollectionConfirmation": "Es-tu sur de vouloir supprimer \"{collectionName}\" ?",
+ "renameCollection": "Renommer",
+ "deleteCollection": "Supprimer",
+ "deleteCollectionConfirmation": "Es-tu sur de vouloir supprimer \"{{collectionName}}\" ?",
"collectionDeletedSuccessfully": "Collection supprimee avec succes",
"collectionRenamedSuccessfully": "Collection renommee avec succes",
"noCollections": "Aucune collection",
"noCollectionsAvailableForSelection": "Aucune collection disponible",
"noItemsMatchSelectedFilters": "Aucun element ne correspond aux filtres selectionnes",
- "noFilesFoundForQuery": "Aucun element trouve pour \"{query}\"",
- "noCollectionsFoundForQuery": "Aucune collection trouvee pour \"{query}\"",
+ "noFilesFoundForQuery": "Aucun element trouve pour \"{{query}}\"",
+ "noCollectionsFoundForQuery": "Aucune collection trouvee pour \"{{query}}\"",
"seeAllCollections": "Voir toutes les collections",
"trashIsEmpty": "La corbeille est vide",
"yourTrashIsEmpty": "Ta corbeille est vide",
@@ -50,7 +50,7 @@
"uploadFileTooLargeErrorBody": "Ce fichier depasse la taille maximale de telechargement prise en charge de 10 Go.",
"downloading": "Téléchargement en cours...",
"downloadFailed": "Échec du téléchargement",
- "copiedToClipboard": "{fieldName} copie dans le presse-papiers",
+ "copiedToClipboard": "{{fieldName}} copie dans le presse-papiers",
"noteName": "Titre",
"noteContent": "Contenu",
"recordName": "Nom de l'enregistrement",
@@ -72,7 +72,7 @@
"upload": "Televerser",
"close": "Fermer",
"logout": "Déconnexion",
- "failedToLoadCollections": "Echec du chargement des collections : {error}",
+ "failedToLoadCollections": "Echec du chargement des collections : {{error}}",
"deleteFileConfirmation": "Es-tu sur de vouloir supprimer <strong>{{fileName}}</strong> ?",
"personalNote": "Note",
"saveDocumentTitle": "Document",
diff --git a/web/apps/locker/src/locales/ja-JP/translation.json b/web/apps/locker/src/locales/ja-JP/translation.json
index 914e051ace..c4619b1084 100644
--- a/web/apps/locker/src/locales/ja-JP/translation.json
+++ b/web/apps/locker/src/locales/ja-JP/translation.json
@@ -26,16 +26,16 @@
"createNewCollection": "新しいコレクションを作成",
"createCollectionButton": "コレクションを作成",
"enterCollectionName": "コレクション名を入力",
- "renameCollection": "コレクションの名前を変更",
- "deleteCollection": "コレクションを削除",
- "deleteCollectionConfirmation": "「{collectionName}」を削除してもよろしいですか?",
+ "renameCollection": "名前を変更",
+ "deleteCollection": "削除",
+ "deleteCollectionConfirmation": "「{{collectionName}}」を削除してもよろしいですか?",
"collectionDeletedSuccessfully": "コレクションが正常に削除されました",
"collectionRenamedSuccessfully": "コレクションの名前が正常に変更されました",
"noCollections": "コレクションがありません",
"noCollectionsAvailableForSelection": "利用可能なコレクションがありません",
"noItemsMatchSelectedFilters": "選択したフィルターに一致するアイテムがありません",
- "noFilesFoundForQuery": "「{query}」に一致するアイテムが見つかりません",
- "noCollectionsFoundForQuery": "「{query}」に一致するコレクションが見つかりません",
+ "noFilesFoundForQuery": "「{{query}}」に一致するアイテムが見つかりません",
+ "noCollectionsFoundForQuery": "「{{query}}」に一致するコレクションが見つかりません",
"seeAllCollections": "すべてのコレクションを見る",
"trashIsEmpty": "ゴミ箱は空です",
"yourTrashIsEmpty": "ゴミ箱は空です",
@@ -54,7 +54,7 @@
"uploadFileTooLargeErrorBody": "このファイルはサポートされている最大アップロードサイズ10GBを超えています。",
"downloading": "ダウンロード中…",
"downloadFailed": "ダウンロード失敗",
- "copiedToClipboard": "{fieldName}がクリップボードにコピーされました",
+ "copiedToClipboard": "{{fieldName}}がクリップボードにコピーされました",
"noteName": "タイトル",
"noteContent": "内容",
"recordName": "レコード名",
@@ -77,7 +77,7 @@
"upload": "アップロード",
"close": "閉じる",
"logout": "ログアウト",
- "failedToLoadCollections": "コレクションの読み込みに失敗しました: {error}",
+ "failedToLoadCollections": "コレクションの読み込みに失敗しました: {{error}}",
"deleteFileConfirmation": "<strong>{{fileName}}</strong> を削除してもよろしいですか?",
"document": "ドキュメント",
"thing": "物品",
diff --git a/web/apps/locker/src/pages/locker.tsx b/web/apps/locker/src/pages/locker.tsx
index 00e583d166..1022348779 100644
--- a/web/apps/locker/src/pages/locker.tsx
+++ b/web/apps/locker/src/pages/locker.tsx
@@ -32,6 +32,7 @@ import {
createCollection as createCollectionAPI,
createInfoItem,
deleteCollection as deleteCollectionAPI,
+ deleteCollectionKeepingFiles,
emptyTrash as emptyTrashAPI,
fetchCollectionSharees,
fetchLockerData,
@@ -863,9 +864,13 @@ export const LockerPage: React.FC = () => {
const handleDeleteCollection = useCallback(
(collectionID: number) => {
- const collectionName =
- collections.find((collection) => collection.id === collectionID)
- ?.name ?? "";
+ 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 }),
@@ -873,15 +878,40 @@ export const LockerPage: React.FC = () => {
text: t("delete"),
color: "critical",
action: async () => {
- await deleteCollectionAPI(collectionID);
- navigateHome();
+ if (!collection) {
+ throw new Error("Collection not found");
+ }
+
+ if (collection.items.length > 0) {
+ if (!masterKey) {
+ throw new Error("Missing master key");
+ }
+
+ await deleteCollectionKeepingFiles(
+ collection,
+ masterKey,
+ );
+ } else {
+ await deleteCollectionAPI(collectionID);
+ }
+ if (shouldNavigateHome) {
+ navigateHome();
+ }
await refreshData();
setToast(t("collectionDeletedSuccessfully"));
},
},
});
},
- [collections, navigateHome, refreshData, showMiniDialog],
+ [
+ collections,
+ masterKey,
+ navigateHome,
+ refreshData,
+ router.pathname,
+ selectedCollectionID,
+ showMiniDialog,
+ ],
);
const handleOpenShareCollection = useCallback(
diff --git a/web/apps/locker/src/services/remote.ts b/web/apps/locker/src/services/remote.ts
index ea742fdbe0..53bf514188 100644
--- a/web/apps/locker/src/services/remote.ts
+++ b/web/apps/locker/src/services/remote.ts
@@ -1529,6 +1529,75 @@ const addFileToCollections = async (
}
};
+const decryptFileKeyForCollection = async (
+ fileID: number,
+ collectionID: number,
+ masterKey: string,
+): Promise<string> => {
+ const fileRecord = getEncryptedFileRecord(fileID, collectionID);
+ if (!fileRecord) {
+ throw new Error(
+ `File ${fileID} not in cache for collection ${collectionID}`,
+ );
+ }
+
+ const collectionRecord = encryptedCollections.get(collectionID);
+ if (!collectionRecord) {
+ throw new Error(`Collection ${collectionID} not in cache`);
+ }
+
+ const collectionKey = await decryptCollectionKey(
+ collectionRecord,
+ masterKey,
+ );
+ return await decryptBox(
+ {
+ encryptedData: fileRecord.encryptedKey,
+ nonce: fileRecord.keyDecryptionNonce,
+ },
+ collectionKey,
+ );
+};
+
+const removeFilesFromCollection = async (
+ collectionID: number,
+ fileIDs: number[],
+): Promise<void> => {
+ if (fileIDs.length === 0) {
+ return;
+ }
+
+ const res = await fetch(await apiURL("/collections/v3/remove-files"), {
+ method: "POST",
+ headers: {
+ ...(await authenticatedRequestHeaders()),
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ collectionID, fileIDs }),
+ });
+ ensureOk(res);
+};
+
+const moveFilesBetweenCollections = async (
+ fromCollectionID: number,
+ toCollectionID: number,
+ files: { id: number; encryptedKey: string; keyDecryptionNonce: string }[],
+): Promise<void> => {
+ if (files.length === 0) {
+ return;
+ }
+
+ const res = await fetch(await apiURL("/collections/move-files"), {
+ method: "POST",
+ headers: {
+ ...(await authenticatedRequestHeaders()),
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ fromCollectionID, toCollectionID, files }),
+ });
+ ensureOk(res);
+};
+
/**
* Restore files from trash to a collection.
*
@@ -1723,13 +1792,97 @@ export const renameCollection = async (
* @param collectionID The collection to delete.
*/
export const deleteCollection = async (collectionID: number): Promise<void> => {
- const res = await fetch(await apiURL(`/collections/v3/${collectionID}`), {
- method: "DELETE",
- headers: await authenticatedRequestHeaders(),
- });
+ const res = await fetch(
+ await apiURL(
+ `/collections/v3/${collectionID}?keepFiles=True&collectionID=${collectionID}`,
+ ),
+ { method: "DELETE", headers: await authenticatedRequestHeaders() },
+ );
ensureOk(res);
};
+export const deleteCollectionKeepingFiles = async (
+ collection: LockerCollection,
+ masterKey: string,
+): 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");
+ }
+
+ const fileIDsToRemove: number[] = [];
+ const filesToMoveByTargetCollectionID = new Map<
+ number,
+ { id: number; encryptedKey: string; keyDecryptionNonce: string }[]
+ >();
+
+ for (const item of collection.items) {
+ const isCurrentUserOwned =
+ (item.ownerID ?? currentUserID) === currentUserID;
+ if (!isCurrentUserOwned) {
+ fileIDsToRemove.push(item.id);
+ continue;
+ }
+
+ const otherOwnedCollectionIDs = item.collectionIDs.filter(
+ (itemCollectionID) => {
+ if (itemCollectionID === collectionID) {
+ return false;
+ }
+
+ const targetCollection =
+ encryptedCollections.get(itemCollectionID);
+ return (
+ !!targetCollection &&
+ targetCollection.ownerID === currentUserID &&
+ targetCollection.type !== "uncategorized"
+ );
+ },
+ );
+
+ const targetCollectionID =
+ otherOwnedCollectionIDs[0] ?? uncategorizedCollection.id;
+ const fileKey = await decryptFileKeyForCollection(
+ item.id,
+ collectionID,
+ masterKey,
+ );
+ const targetCollectionRecord =
+ encryptedCollections.get(targetCollectionID);
+ if (!targetCollectionRecord) {
+ throw new Error(`Collection ${targetCollectionID} not in cache`);
+ }
+ const targetCollectionKey = await decryptCollectionKey(
+ targetCollectionRecord,
+ masterKey,
+ );
+ const encryptedFileKey = await encryptBox(fileKey, targetCollectionKey);
+ const filesToMove =
+ filesToMoveByTargetCollectionID.get(targetCollectionID) ?? [];
+ filesToMove.push({
+ id: item.id,
+ encryptedKey: encryptedFileKey.encryptedData,
+ keyDecryptionNonce: encryptedFileKey.nonce,
+ });
+ filesToMoveByTargetCollectionID.set(targetCollectionID, filesToMove);
+ }
+
+ for (const [targetCollectionID, files] of filesToMoveByTargetCollectionID) {
+ await moveFilesBetweenCollections(
+ collectionID,
+ targetCollectionID,
+ files,
+ );
+ }
+
+ await removeFilesFromCollection(collectionID, fileIDsToRemove);
+ await deleteCollection(collectionID);
+};
+
/**
* Fetch the current list of participants for a shared collection.
*/