Skip to content

armgit / ente

Public Imported from GitHub
0

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

refractor(locker):update-collection-services-and-membership-logics

Aswin Asok087dcfec1d9c
diff --git a/web/apps/locker/src/components/locker/LockerPage.tsx b/web/apps/locker/src/components/locker/LockerPage.tsx
index 05b24a00fd..935844ac47 100644
--- a/web/apps/locker/src/components/locker/LockerPage.tsx
+++ b/web/apps/locker/src/components/locker/LockerPage.tsx
@@ -15,7 +15,7 @@ import { LockerNavbar } from "@/components/LockerNavbar";
import { LockerSidebar } from "@/components/sidebar/LockerSidebar";
import { LockerConfirmDialog } from "@/components/ui/LockerConfirmDialog";
import { useSetupLockerI18n } from "@/i18n/locker";
-import { fetchCollectionSharees } from "@/services/remote";
+import { fetchCollectionSharees } from "@/services/collection-sharing";
import { lockerColorSx } from "@/styles/tokens";
import { PlusSignIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
diff --git a/web/apps/locker/src/components/locker/use-collection-actions.ts b/web/apps/locker/src/components/locker/use-collection-actions.ts
index 887f073bee..75fc986371 100644
--- a/web/apps/locker/src/components/locker/use-collection-actions.ts
+++ b/web/apps/locker/src/components/locker/use-collection-actions.ts
@@ -1,12 +1,14 @@
+import { deleteCollectionKeepingFiles } from "@/services/collection-membership";
import {
- createCollection as createCollectionAPI,
- deleteCollection as deleteCollectionAPI,
- deleteCollectionKeepingFiles,
leaveCollection as leaveCollectionAPI,
- renameCollection as renameCollectionAPI,
shareCollection as shareCollectionAPI,
unshareCollection as unshareCollectionAPI,
-} from "@/services/remote";
+} from "@/services/collection-sharing";
+import {
+ createCollection as createCollectionAPI,
+ deleteCollection as deleteCollectionAPI,
+ renameCollection as renameCollectionAPI,
+} from "@/services/collections";
import type { LockerCollection } from "@/types";
import { isCollectionOwner } from "@/types";
import { savedLocalUser } from "ente-accounts/services/accounts-db";
diff --git a/web/apps/locker/src/components/locker/use-item-actions.tsx b/web/apps/locker/src/components/locker/use-item-actions.tsx
index a2a211ca05..72a788b176 100644
--- a/web/apps/locker/src/components/locker/use-item-actions.tsx
+++ b/web/apps/locker/src/components/locker/use-item-actions.tsx
@@ -1,10 +1,10 @@
+import { updateItemCollections } from "@/services/collection-membership";
import {
createInfoItem,
setItemImportant,
trashFiles,
updateFileItem,
updateInfoItem,
- updateItemCollections,
} from "@/services/remote";
import type { LockerCollection, LockerItem, LockerItemType } from "@/types";
import { getItemTitle } from "@/types";
diff --git a/web/apps/locker/src/services/remote-collection-mutations.ts b/web/apps/locker/src/services/collection-membership.ts
similarity index 60%
rename from web/apps/locker/src/services/remote-collection-mutations.ts
rename to web/apps/locker/src/services/collection-membership.ts
index 2b9b9c1b0e..0c597d8e80 100644
--- a/web/apps/locker/src/services/remote-collection-mutations.ts
+++ b/web/apps/locker/src/services/collection-membership.ts
@@ -1,4 +1,15 @@
import type { LockerCollection } from "@/types";
+import { ensureLocalUser } from "ente-accounts/services/user";
+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
+import { apiURL } from "ente-base/origins";
+import { decryptBox, encryptBox } from "ente-locker-wasm";
+import { deleteCollection, ensureUncategorizedCollection } from "./collections";
+import {
+ getCollectionIDsForFile,
+ getCollectionRecord,
+ getEncryptedFileRecord,
+} from "./locker-cache";
+import { decryptCollectionKey } from "./sync/decrypt";
interface CollectionRecordLike {
id: number;
@@ -277,3 +288,181 @@ export const deleteCollectionKeepingFilesWithDeps = async (
await removeFilesFromCollection(collectionID, fileIDsToRemove);
};
+
+export const updateItemCollections = async (
+ fileID: number,
+ collectionIDs: number[],
+ masterKey: string,
+): Promise<void> => {
+ await updateItemCollectionsWithDeps(fileID, collectionIDs, {
+ currentUserID: ensureLocalUser().id,
+ masterKey,
+ deps: createCollectionMutationDeps(),
+ });
+};
+
+export const addFileToCollections = async (
+ fileID: number,
+ fileKey: string,
+ targetCollectionIDs: number[],
+): Promise<void> => {
+ for (const targetCollectionID of targetCollectionIDs) {
+ const collectionRecord = getCollectionRecord(targetCollectionID);
+ if (!collectionRecord) {
+ throw new Error(`Collection ${targetCollectionID} not in cache`);
+ }
+
+ const collectionKey = await decryptCollectionKey(collectionRecord);
+ const encryptedFileKey = await encryptBox(fileKey, collectionKey);
+
+ const res = await fetch(await apiURL("/collections/add-files"), {
+ method: "POST",
+ headers: {
+ ...(await authenticatedRequestHeaders()),
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ collectionID: targetCollectionID,
+ files: [
+ {
+ id: fileID,
+ encryptedKey: encryptedFileKey.encryptedData,
+ keyDecryptionNonce: encryptedFileKey.nonce,
+ },
+ ],
+ }),
+ });
+ ensureOk(res);
+ }
+};
+
+const COLLECTION_MUTATION_BATCH_SIZE = 100;
+
+const batchValues = <T>(
+ values: T[],
+ batchSize = COLLECTION_MUTATION_BATCH_SIZE,
+) => {
+ const batches: T[][] = [];
+ for (let i = 0; i < values.length; i += batchSize) {
+ batches.push(values.slice(i, i + batchSize));
+ }
+ return batches;
+};
+
+const decryptFileKeyForCollection = async (
+ fileID: number,
+ collectionID: number,
+): Promise<string> => {
+ const fileRecord = getEncryptedFileRecord(fileID, collectionID);
+ if (!fileRecord) {
+ throw new Error(
+ `File ${fileID} not in cache for collection ${collectionID}`,
+ );
+ }
+
+ const collectionRecord = getCollectionRecord(collectionID);
+ if (!collectionRecord) {
+ throw new Error(`Collection ${collectionID} not in cache`);
+ }
+
+ const collectionKey = await decryptCollectionKey(collectionRecord);
+ return await decryptBox(
+ {
+ encryptedData: fileRecord.encryptedKey,
+ nonce: fileRecord.keyDecryptionNonce,
+ },
+ collectionKey,
+ );
+};
+
+const buildEncryptedFileMoveItem = async (
+ fileID: number,
+ fromCollectionID: number,
+ toCollectionID: number,
+): Promise<EncryptedCollectionFileItem> => {
+ const fileKey = await decryptFileKeyForCollection(fileID, fromCollectionID);
+ const targetCollectionRecord = getCollectionRecord(toCollectionID);
+ if (!targetCollectionRecord) {
+ throw new Error(`Collection ${toCollectionID} not in cache`);
+ }
+ const targetCollectionKey = await decryptCollectionKey(
+ targetCollectionRecord,
+ );
+ const encryptedFileKey = await encryptBox(fileKey, targetCollectionKey);
+
+ return {
+ id: fileID,
+ encryptedKey: encryptedFileKey.encryptedData,
+ keyDecryptionNonce: encryptedFileKey.nonce,
+ };
+};
+
+const removeFilesFromCollection = async (
+ collectionID: number,
+ fileIDs: number[],
+): Promise<void> => {
+ if (fileIDs.length === 0) {
+ return;
+ }
+
+ for (const fileIDBatch of batchValues(fileIDs)) {
+ const res = await fetch(await apiURL("/collections/v3/remove-files"), {
+ method: "POST",
+ headers: {
+ ...(await authenticatedRequestHeaders()),
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ collectionID, fileIDs: fileIDBatch }),
+ });
+ ensureOk(res);
+ }
+};
+
+const moveFilesBetweenCollections = async (
+ fromCollectionID: number,
+ toCollectionID: number,
+ files: EncryptedCollectionFileItem[],
+): Promise<void> => {
+ if (files.length === 0) {
+ return;
+ }
+
+ for (const fileBatch of batchValues(files)) {
+ const res = await fetch(await apiURL("/collections/move-files"), {
+ method: "POST",
+ headers: {
+ ...(await authenticatedRequestHeaders()),
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ fromCollectionID,
+ toCollectionID,
+ files: fileBatch,
+ }),
+ });
+ ensureOk(res);
+ }
+};
+
+export const createCollectionMutationDeps = () => ({
+ getCollectionIDsForFile,
+ getCollectionRecord,
+ ensureUncategorizedCollection,
+ decryptFileKeyForCollection,
+ buildEncryptedFileMoveItem,
+ removeFilesFromCollection,
+ moveFilesBetweenCollections,
+ addFileToCollections,
+});
+
+export const deleteCollectionKeepingFiles = async (
+ collection: LockerCollection,
+ masterKey: string,
+): Promise<void> => {
+ await deleteCollectionKeepingFilesWithDeps(collection, {
+ currentUserID: ensureLocalUser().id,
+ masterKey,
+ deps: createCollectionMutationDeps(),
+ });
+ await deleteCollection(collection.id, { keepFiles: true });
+};
diff --git a/web/apps/locker/src/services/remote-collection-sharing.ts b/web/apps/locker/src/services/collection-sharing.ts
similarity index 91%
rename from web/apps/locker/src/services/remote-collection-sharing.ts
rename to web/apps/locker/src/services/collection-sharing.ts
index 2790447703..9772099224 100644
--- a/web/apps/locker/src/services/remote-collection-sharing.ts
+++ b/web/apps/locker/src/services/collection-sharing.ts
@@ -81,3 +81,11 @@ export const unshareCollection = async (
ensureOk(res);
return parseAndCacheSharees(collectionID, await res.json());
};
+
+export const leaveCollection = async (collectionID: number): Promise<void> => {
+ const res = await fetch(
+ await apiURL(`/collections/leave/${collectionID}`),
+ { method: "POST", headers: await authenticatedRequestHeaders() },
+ );
+ ensureOk(res);
+};
diff --git a/web/apps/locker/src/services/remote-collections.ts b/web/apps/locker/src/services/collections.ts
similarity index 100%
rename from web/apps/locker/src/services/remote-collections.ts
rename to web/apps/locker/src/services/collections.ts
diff --git a/web/apps/locker/src/services/remote.ts b/web/apps/locker/src/services/remote.ts
index 923d530383..b5502fde5f 100644
--- a/web/apps/locker/src/services/remote.ts
+++ b/web/apps/locker/src/services/remote.ts
@@ -1,4 +1,4 @@
-import type { LockerCollection, LockerItem, LockerItemType } from "@/types";
+import type { LockerItem, LockerItemType } from "@/types";
import { ensureLocalUser } from "ente-accounts/services/user";
import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
import log from "ente-base/log";
@@ -10,6 +10,15 @@ import {
encryptBox,
generateKey,
} from "ente-locker-wasm";
+import {
+ addFileToCollections,
+ createCollectionMutationDeps,
+ updateItemCollectionsWithDeps,
+} from "./collection-membership";
+import {
+ ensureFavoritesCollection,
+ ensureUncategorizedCollection,
+} from "./collections";
import {
findCollectionByType,
getCollectionIDsForFile,
@@ -17,16 +26,6 @@ import {
getEncryptedFileRecord,
updateCachedPubMagicMetadata,
} from "./locker-cache";
-import {
- deleteCollectionKeepingFilesWithDeps,
- type EncryptedCollectionFileItem,
- updateItemCollectionsWithDeps,
-} from "./remote-collection-mutations";
-import {
- deleteCollection,
- ensureFavoritesCollection,
- ensureUncategorizedCollection,
-} from "./remote-collections";
import { RemoteIDResponseSchema } from "./remote-types";
import {
type LockerUploadProgress,
@@ -38,13 +37,21 @@ import {
loadPersistedLockerState,
syncLockerState,
} from "./sync/sync";
+export {
+ deleteCollectionKeepingFiles,
+ updateItemCollections,
+} from "./collection-membership";
export {
fetchCollectionSharees,
+ leaveCollection,
shareCollection,
unshareCollection,
-} from "./remote-collection-sharing";
-export { createCollection, renameCollection } from "./remote-collections";
-export { deleteCollection };
+} from "./collection-sharing";
+export {
+ createCollection,
+ deleteCollection,
+ renameCollection,
+} from "./collections";
export { downloadLockerFile } from "./download";
export {
@@ -257,18 +264,6 @@ const updateItemMetadata = async (
});
};
-export const updateItemCollections = async (
- fileID: number,
- collectionIDs: number[],
- masterKey: string,
-): Promise<void> => {
- await updateItemCollectionsWithDeps(fileID, collectionIDs, {
- currentUserID: ensureLocalUser().id,
- masterKey,
- deps: createCollectionMutationDeps(),
- });
-};
-
export const trashFiles = async (
fileIDs: number[],
collectionID: number,
@@ -312,160 +307,6 @@ export const emptyTrash = async (lastUpdatedAt: number): Promise<void> => {
ensureOk(res);
};
-const addFileToCollections = async (
- fileID: number,
- fileKey: string,
- targetCollectionIDs: number[],
-): Promise<void> => {
- for (const targetCollectionID of targetCollectionIDs) {
- const collectionRecord = getCollectionRecord(targetCollectionID);
- if (!collectionRecord) {
- throw new Error(`Collection ${targetCollectionID} not in cache`);
- }
-
- const collectionKey = await decryptCollectionKey(collectionRecord);
- const encryptedFileKey = await encryptBox(fileKey, collectionKey);
-
- const res = await fetch(await apiURL("/collections/add-files"), {
- method: "POST",
- headers: {
- ...(await authenticatedRequestHeaders()),
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- collectionID: targetCollectionID,
- files: [
- {
- id: fileID,
- encryptedKey: encryptedFileKey.encryptedData,
- keyDecryptionNonce: encryptedFileKey.nonce,
- },
- ],
- }),
- });
- ensureOk(res);
- }
-};
-
-const COLLECTION_MUTATION_BATCH_SIZE = 100;
-
-const batchValues = <T>(
- values: T[],
- batchSize = COLLECTION_MUTATION_BATCH_SIZE,
-) => {
- const batches: T[][] = [];
- for (let i = 0; i < values.length; i += batchSize) {
- batches.push(values.slice(i, i + batchSize));
- }
- return batches;
-};
-
-const decryptFileKeyForCollection = async (
- fileID: number,
- collectionID: number,
-): Promise<string> => {
- const fileRecord = getEncryptedFileRecord(fileID, collectionID);
- if (!fileRecord) {
- throw new Error(
- `File ${fileID} not in cache for collection ${collectionID}`,
- );
- }
-
- const collectionRecord = getCollectionRecord(collectionID);
- if (!collectionRecord) {
- throw new Error(`Collection ${collectionID} not in cache`);
- }
-
- const collectionKey = await decryptCollectionKey(collectionRecord);
- return await decryptBox(
- {
- encryptedData: fileRecord.encryptedKey,
- nonce: fileRecord.keyDecryptionNonce,
- },
- collectionKey,
- );
-};
-
-const buildEncryptedFileMoveItem = async (
- fileID: number,
- fromCollectionID: number,
- toCollectionID: number,
-): Promise<EncryptedCollectionFileItem> => {
- const fileKey = await decryptFileKeyForCollection(fileID, fromCollectionID);
- const targetCollectionRecord = getCollectionRecord(toCollectionID);
- if (!targetCollectionRecord) {
- throw new Error(`Collection ${toCollectionID} not in cache`);
- }
- const targetCollectionKey = await decryptCollectionKey(
- targetCollectionRecord,
- );
- const encryptedFileKey = await encryptBox(fileKey, targetCollectionKey);
-
- return {
- id: fileID,
- encryptedKey: encryptedFileKey.encryptedData,
- keyDecryptionNonce: encryptedFileKey.nonce,
- };
-};
-
-const removeFilesFromCollection = async (
- collectionID: number,
- fileIDs: number[],
-): Promise<void> => {
- if (fileIDs.length === 0) {
- return;
- }
-
- for (const fileIDBatch of batchValues(fileIDs)) {
- const res = await fetch(await apiURL("/collections/v3/remove-files"), {
- method: "POST",
- headers: {
- ...(await authenticatedRequestHeaders()),
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ collectionID, fileIDs: fileIDBatch }),
- });
- ensureOk(res);
- }
-};
-
-const moveFilesBetweenCollections = async (
- fromCollectionID: number,
- toCollectionID: number,
- files: EncryptedCollectionFileItem[],
-): Promise<void> => {
- if (files.length === 0) {
- return;
- }
-
- for (const fileBatch of batchValues(files)) {
- const res = await fetch(await apiURL("/collections/move-files"), {
- method: "POST",
- headers: {
- ...(await authenticatedRequestHeaders()),
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- fromCollectionID,
- toCollectionID,
- files: fileBatch,
- }),
- });
- ensureOk(res);
- }
-};
-
-const createCollectionMutationDeps = () => ({
- getCollectionIDsForFile,
- getCollectionRecord,
- ensureUncategorizedCollection,
- decryptFileKeyForCollection,
- buildEncryptedFileMoveItem,
- removeFilesFromCollection,
- moveFilesBetweenCollections,
- addFileToCollections,
-});
-
export const restoreFromTrash = async (
items: Pick<LockerItem, "id" | "collectionID">[],
targetCollectionID: number,
@@ -554,26 +395,6 @@ export const restoreFromTrash = async (
ensureOk(res);
};
-export const deleteCollectionKeepingFiles = async (
- collection: LockerCollection,
- masterKey: string,
-): Promise<void> => {
- await deleteCollectionKeepingFilesWithDeps(collection, {
- currentUserID: ensureLocalUser().id,
- masterKey,
- deps: createCollectionMutationDeps(),
- });
- await deleteCollection(collection.id, { keepFiles: true });
-};
-
-export const leaveCollection = async (collectionID: number): Promise<void> => {
- const res = await fetch(
- await apiURL(`/collections/leave/${collectionID}`),
- { method: "POST", headers: await authenticatedRequestHeaders() },
- );
- ensureOk(res);
-};
-
export const setItemImportant = async (
fileID: number,
shouldBeImportant: boolean,
diff --git a/web/apps/locker/tests/collection-membership.test.ts b/web/apps/locker/tests/collection-membership.test.ts
new file mode 100644
index 0000000000..79e8a5c0c9
--- /dev/null
+++ b/web/apps/locker/tests/collection-membership.test.ts
@@ -0,0 +1,258 @@
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import {
+ deleteCollectionKeepingFiles,
+ updateItemCollections,
+} from "../src/services/collection-membership";
+import {
+ replaceLockerCache,
+ type EncryptedCollectionRecord,
+ type EncryptedFileRecord,
+} from "../src/services/locker-cache";
+import type { LockerCollection, LockerItem } from "../src/types";
+
+vi.mock("ente-accounts/services/user", () => ({
+ ensureLocalUser: () => ({ id: 1 }),
+}));
+vi.mock("ente-base/http", () => ({
+ authenticatedRequestHeaders: () => ({ "X-Auth-Token": "test" }),
+ ensureOk: (response: Response) => {
+ if (!response.ok) throw new Error("Request failed");
+ },
+}));
+vi.mock("ente-base/origins", () => ({
+ apiURL: (path: string, params?: Record<string, unknown>) =>
+ params
+ ? `${path}?${new URLSearchParams(Object.entries(params).map(([key, value]) => [key, String(value)]))}`
+ : path,
+}));
+vi.mock("ente-base/log", () => ({ default: {} }));
+vi.mock("../src/services/authenticated-session", () => ({}));
+vi.mock("ente-locker-wasm", () => ({
+ decryptBox: () => "file-key",
+ encryptBox: (_fileKey: string, collectionKey: string) => ({
+ encryptedData: `encrypted-for-${collectionKey}`,
+ nonce: "nonce",
+ }),
+}));
+vi.mock("../src/services/sync/decrypt", () => ({
+ decryptCollectionKey: (record: EncryptedCollectionRecord) =>
+ `collection-${record.id}`,
+}));
+vi.mock("../src/services/sync/sync", () => ({}));
+
+const fetchMock = vi.fn<typeof fetch>();
+const collection = (
+ id: number,
+ ownerID = 1,
+ type = "folder",
+): EncryptedCollectionRecord => ({
+ id,
+ ownerID,
+ type,
+ encryptedKey: "key",
+ keyDecryptionNonce: "nonce",
+ encryptedName: undefined,
+ nameDecryptionNonce: undefined,
+ isDeleted: false,
+ updationTime: 0,
+});
+const file = (id: number, collectionID: number): EncryptedFileRecord => ({
+ id,
+ collectionID,
+ encryptedKey: "key",
+ keyDecryptionNonce: "nonce",
+ fileDecryptionHeader: "header",
+ hasObject: true,
+ metadata: { encryptedData: "data", decryptionHeader: "header" },
+ updationTime: 0,
+});
+const item = (id: number, ownerID = 1): LockerItem => ({
+ id,
+ ownerID,
+ type: "file",
+ data: { name: "File" },
+ collectionID: 1,
+ collectionIDs: [1, 2],
+});
+const source = (items: LockerItem[]): LockerCollection => ({
+ id: 1,
+ name: "Source",
+ owner: { id: 1 },
+ sharees: [],
+ items,
+ type: "folder",
+ isShared: false,
+});
+const seed = (ids = [10], sharedSource = false) =>
+ replaceLockerCache({
+ collections: new Map([
+ [1, collection(1, sharedSource ? 2 : 1)],
+ [2, collection(2)],
+ [3, collection(3)],
+ [9, collection(9, 1, "uncategorized")],
+ ]),
+ files: new Map(
+ ids.map((id) => [
+ id,
+ new Map([
+ [1, file(id, 1)],
+ [2, file(id, 2)],
+ ]),
+ ]),
+ ),
+ });
+const requests = () =>
+ fetchMock.mock.calls.map(([url, options]) => ({
+ url,
+ method: options?.method,
+ body:
+ typeof options?.body === "string"
+ ? (JSON.parse(options.body) as Record<string, unknown>)
+ : undefined,
+ }));
+beforeEach(() => {
+ vi.clearAllMocks();
+ fetchMock
+ .mockReset()
+ .mockImplementation(() =>
+ Promise.resolve(new Response(null, { status: 200 })),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ seed();
+});
+afterEach(() => vi.unstubAllGlobals());
+
+test("membership updates deduplicate targets and add before moving the removed owned membership", async () => {
+ await updateItemCollections(10, [2, 3, 3], "master-key");
+ expect(requests()).toEqual([
+ {
+ url: "/collections/add-files",
+ method: "POST",
+ body: {
+ collectionID: 3,
+ files: [
+ {
+ id: 10,
+ encryptedKey: "encrypted-for-collection-3",
+ keyDecryptionNonce: "nonce",
+ },
+ ],
+ },
+ },
+ {
+ url: "/collections/move-files",
+ method: "POST",
+ body: {
+ fromCollectionID: 1,
+ toCollectionID: 2,
+ files: [
+ {
+ id: 10,
+ encryptedKey: "encrypted-for-collection-2",
+ keyDecryptionNonce: "nonce",
+ },
+ ],
+ },
+ },
+ ]);
+});
+
+test("removing a shared membership detaches it without moving the file", async () => {
+ seed([10], true);
+ await updateItemCollections(10, [2], "master-key");
+ expect(requests()).toEqual([
+ {
+ url: "/collections/v3/remove-files",
+ method: "POST",
+ body: { collectionID: 1, fileIDs: [10] },
+ },
+ ]);
+});
+
+test("a failed addition leaves existing memberships untouched", async () => {
+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 500 }));
+ await expect(updateItemCollections(10, [3], "master-key")).rejects.toThrow(
+ "Request failed",
+ );
+ expect(requests().map((request) => request.url)).toEqual([
+ "/collections/add-files",
+ ]);
+});
+
+test("an empty target selection falls back to Uncategorized before removing current memberships", async () => {
+ await updateItemCollections(10, [], "master-key");
+ expect(requests().map((request) => request.body)).toEqual([
+ {
+ collectionID: 9,
+ files: [
+ {
+ id: 10,
+ encryptedKey: "encrypted-for-collection-9",
+ keyDecryptionNonce: "nonce",
+ },
+ ],
+ },
+ {
+ fromCollectionID: 1,
+ toCollectionID: 9,
+ files: [
+ {
+ id: 10,
+ encryptedKey: "encrypted-for-collection-9",
+ keyDecryptionNonce: "nonce",
+ },
+ ],
+ },
+ {
+ fromCollectionID: 2,
+ toCollectionID: 9,
+ files: [
+ {
+ id: 10,
+ encryptedKey: "encrypted-for-collection-9",
+ keyDecryptionNonce: "nonce",
+ },
+ ],
+ },
+ ]);
+});
+
+test("keeping files batches owned moves, detaches other owners' files, then deletes the collection", async () => {
+ const ids = Array.from({ length: 101 }, (_, i) => i + 10);
+ seed(ids);
+ await deleteCollectionKeepingFiles(
+ source([...ids.map((id) => item(id)), item(200, 2)]),
+ "master-key",
+ );
+ const calls = requests();
+ expect(calls.map((call) => call.url)).toEqual([
+ "/collections/move-files",
+ "/collections/move-files",
+ "/collections/v3/remove-files",
+ "/collections/v3/1?collectionID=1&keepFiles=true",
+ ]);
+ expect(calls[0]?.body).toMatchObject({
+ fromCollectionID: 1,
+ toCollectionID: 2,
+ });
+ expect(calls[0]?.body?.files).toHaveLength(100);
+ expect(calls[1]?.body?.files).toEqual([
+ {
+ id: 110,
+ encryptedKey: "encrypted-for-collection-2",
+ keyDecryptionNonce: "nonce",
+ },
+ ]);
+ expect(calls[2]?.body).toEqual({ collectionID: 1, fileIDs: [200] });
+ expect(calls[3]?.method).toBe("DELETE");
+});
+
+test("a failed move prevents the final collection deletion", async () => {
+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 500 }));
+ await expect(
+ deleteCollectionKeepingFiles(source([item(10)]), "master-key"),
+ ).rejects.toThrow("Request failed");
+ expect(requests().map((request) => request.url)).toEqual([
+ "/collections/move-files",
+ ]);
+});