Skip to content

armgit / ente

Public Imported from GitHub
0

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

Rework

Manav Rathid84c42e5c189
diff --git a/web/apps/cast/src/services/render.ts b/web/apps/cast/src/services/render.ts
index 4cb5b7d11c..d989946332 100644
--- a/web/apps/cast/src/services/render.ts
+++ b/web/apps/cast/src/services/render.ts
@@ -150,11 +150,14 @@ export const imageURLGenerator = async function* (castData: CastData) {
*
* @param castToken A token used both for authentication, and also identifying
* the collection corresponding to the cast session.
+ *
+ * @returns All the files in the collection in an arbitrary order. Since we are
+ * anyways going to be shuffling these files, the order has no bearing.
*/
export const getRemoteCastCollectionFiles = async (
castToken: string,
): Promise<RemoteEnteFile[]> => {
- const files: RemoteEnteFile[] = [];
+ const filesByID = new Map<number, RemoteEnteFile>();
let sinceTime = 0;
while (true) {
const res = await fetch(
@@ -167,12 +170,12 @@ export const getRemoteCastCollectionFiles = async (
for (const change of diff) {
sinceTime = Math.max(sinceTime, change.updationTime);
if (!change.isDeleted) {
- files.push(change);
+ filesByID.set(change.id, change);
}
}
if (!hasMore) break;
}
- return files;
+ return [...filesByID.values()];
};
const isFileEligible = (file: EnteFile) => {
diff --git a/web/apps/photos/src/components/Collections/CollectionHeader.tsx b/web/apps/photos/src/components/Collections/CollectionHeader.tsx
index 23cdc010c2..5c722ad985 100644
--- a/web/apps/photos/src/components/Collections/CollectionHeader.tsx
+++ b/web/apps/photos/src/components/Collections/CollectionHeader.tsx
@@ -48,10 +48,7 @@ import {
type CollectionSummary,
type CollectionSummaryType,
} from "ente-new/photos/services/collection-summary";
-import {
- clearLocalTrash,
- emptyTrash,
-} from "ente-new/photos/services/collections";
+import { emptyTrash } from "ente-new/photos/services/trash";
import { usePhotosAppContext } from "ente-new/photos/types/context";
import { t } from "i18next";
import { GalleryContext } from "pages/gallery";
@@ -227,7 +224,6 @@ const CollectionOptions: React.FC<CollectionHeaderProps> = ({
const doEmptyTrash = wrap(async () => {
await emptyTrash();
- await clearLocalTrash();
setActiveCollectionID(PseudoCollectionID.all);
});
diff --git a/web/packages/gallery/services/files-db.ts b/web/packages/gallery/services/files-db.ts
index f8c682f890..ef7c028747 100644
--- a/web/packages/gallery/services/files-db.ts
+++ b/web/packages/gallery/services/files-db.ts
@@ -236,3 +236,12 @@ const transformFile = (file: EnteFile & { isDeleted?: unknown }) => {
pubMagicMetadata,
} satisfies EnteFile;
};
+
+/**
+ * A convenience Zod schema for a nullish number, with `null`s being transformed
+ * to `undefined`.
+ *
+ * This is convenient when parsing the various timestamps we keep corresponding
+ * to top level keys in the files DB. Don't use elsewhere!
+ */
+export const LocalTimestamp = z.number().nullish().transform(nullToUndefined);
diff --git a/web/packages/new/photos/services/collections.ts b/web/packages/new/photos/services/collections.ts
index 004ff946e5..2c6cea8045 100644
--- a/web/packages/new/photos/services/collections.ts
+++ b/web/packages/new/photos/services/collections.ts
@@ -119,161 +119,3 @@ export const syncCollections = async () => {
return collections;
};
-const TRASH_TIME = "trash-time";
-
-async function getLastTrashSyncTime() {
- return (await localForage.getItem<number>(TRASH_TIME)) ?? 0;
-}
-
-/**
- * Update our locally saved data about the files and collections in trash by
- * syncing with remote.
- *
- * The sync uses a diff-based mechanism that syncs forward from the last sync
- * time (also persisted).
- *
- * @param collections All the (non-deleted) collections that we know about
- * locally.
- *
- * @param onUpdateTrashFiles A callback invoked when the locally persisted trash
- * items are updated. This can be used for the UI to also update its state. This
- * callback can be invoked multiple times during the sync (once for each batch
- * that gets processed).
- *
- * @param onPruneDeletedFileIDs A callback invoked when files that were
- * previously in trash have now been permanently deleted. This can be used by
- * other subsystems to prune data referring to files that now have been deleted
- * permanently. This callback can be invoked multiple times during the sync
- * (once for each batch that gets processed).
- */
-export async function syncTrash(
- collections: Collection[],
- onUpdateTrashFiles: ((files: EnteFile[]) => void) | undefined,
- onPruneDeletedFileIDs: (deletedFileIDs: Set<number>) => Promise<void>,
-): Promise<void> {
- const trash = await savedTrashItems();
- const sinceTime = await getLastTrashSyncTime();
-
- // Data structures:
- //
- // `collectionKeyByID` is a map from collection ID => collection key.
- //
- // It is prefilled with all the non-deleted collections available locally
- // (`collections`), and all keys of collections that trash items refererred
- // to the last time we synced (`trashItemCollectionKeys`).
- //
- // > See: [Note: Trash item collection keys]
- //
- // As we iterate over the trash items, if we find a collection whose key is
- // not present in the map, then we fetch that collection from remote, add
- // its entry to the map, and also updated the persisted value corresponding
- // to `trashItemCollectionKeys`.
- //
- // When we're done, we use `collectionKeyByID` to derive a filtered list of
- // keys that are still referred to by the current set of trash items, and
- // set this filtered list as the persisted value of
- // `trashItemCollectionKeys`.
-
- const collectionKeyByID = new Map(collections.map((c) => [c.id, c.key]));
- const trashItemCollectionKeys = await savedTrashItemCollectionKeys();
- for (const { id, key } of trashItemCollectionKeys) {
- collectionKeyByID.set(id, key);
- }
-
- let updatedTrash: TrashItem[] = [...trash];
- try {
- let time = sinceTime;
-
- let resp;
- do {
- const token = getToken();
- if (!token) {
- break;
- }
- resp = await HTTPService.get(
- await apiURL("/trash/v2/diff"),
- { sinceTime: time },
- { "X-Auth-Token": token },
- );
- const deletedFileIDs = new Set<number>();
- // #Perf: This can be optimized by running the decryption in parallel
- for (const trashItem of resp.data.diff as RemoteTrashItem[]) {
- const collectionID = trashItem.file.collectionID;
- let collectionKey = collectionKeyByID.get(collectionID);
- if (!collectionKey) {
- // See: [Note: Trash item collection keys]
- const collection = await getCollectionByID(collectionID);
- collectionKey = collection.key;
- collectionKeyByID.set(collectionID, collectionKey);
- trashItemCollectionKeys.push({
- id: collectionID,
- key: collectionKey,
- });
- await saveTrashItemCollectionKeys(trashItemCollectionKeys);
- }
- if (trashItem.isDeleted) {
- deletedFileIDs.add(trashItem.file.id);
- }
- if (!trashItem.isDeleted && !trashItem.isRestored) {
- const decryptedFile = await decryptRemoteFile(
- trashItem.file,
- collectionKey,
- );
- updatedTrash.push({ ...trashItem, file: decryptedFile });
- } else {
- updatedTrash = updatedTrash.filter(
- (item) => item.file.id !== trashItem.file.id,
- );
- }
- }
-
- if (resp.data.diff.length) {
- time = resp.data.diff.slice(-1)[0].updatedAt;
- }
-
- onUpdateTrashFiles?.(getTrashedFiles(updatedTrash));
- if (deletedFileIDs.size > 0) {
- await onPruneDeletedFileIDs(deletedFileIDs);
- }
- await saveTrashItems(updatedTrash);
- await localForage.setItem(TRASH_TIME, time);
- } while (resp.data.hasMore);
- } catch (e) {
- log.error("Get trash files failed", e);
- }
-
- const trashCollectionIDs = new Set(
- updatedTrash.map((item) => item.file.collectionID),
- );
- await saveTrashItemCollectionKeys(
- [...collectionKeyByID.entries()]
- .filter(([id]) => trashCollectionIDs.has(id))
- .map(([id, key]) => ({ id, key })),
- );
-}
-
-export const emptyTrash = async () => {
- try {
- const token = getToken();
- if (!token) {
- return;
- }
- const lastUpdatedAt = await getLastTrashSyncTime();
-
- await HTTPService.post(
- await apiURL("/trash/empty"),
- { lastUpdatedAt },
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- null,
- { "X-Auth-Token": token },
- );
- } catch (e) {
- log.error("empty trash failed", e);
- throw e;
- }
-};
-
-export const clearLocalTrash = async () => {
- await saveTrashItems([]);
-};
diff --git a/web/packages/new/photos/services/photos-fdb.ts b/web/packages/new/photos/services/photos-fdb.ts
index e2f0064d07..bda1a82c50 100644
--- a/web/packages/new/photos/services/photos-fdb.ts
+++ b/web/packages/new/photos/services/photos-fdb.ts
@@ -5,6 +5,7 @@
import {
LocalCollections,
LocalEnteFile,
+ LocalTimestamp,
transformFilesIfNeeded,
} from "ente-gallery/services/files-db";
import { type Collection } from "ente-media/collection";
@@ -194,6 +195,7 @@ export const savedTrashItems = async (): Promise<TrashItem[]> =>
LocalTrashItem.array().parse(
(await localForage.getItem("file-trash")) ?? [],
);
+
/**
* Replace the list of trash items stored in our local database.
*
@@ -202,3 +204,20 @@ export const savedTrashItems = async (): Promise<TrashItem[]> =>
export const saveTrashItems = async (trashItems: TrashItem[]) => {
await localForage.setItem("file-trash", trashItems);
};
+
+/**
+ * Return the updatedAt of the latest trash items we have obtained from remote.
+ *
+ * Use {@link saveTrashLastUpdatedAt} to update the database.
+ */
+export const savedTrashLastUpdatedAt = async (): Promise<number | undefined> =>
+ LocalTimestamp.parse(await localForage.getItem("trash-time"));
+
+/**
+ * Update the updatedAt of the latest trash items we have obtained from remote.
+ *
+ * This is the setter corresponding to {@link savedTrashLastUpdatedAt}.
+ */
+export const saveTrashLastUpdatedAt = async (updatedAt: number) => {
+ await localForage.setItem("trash-time", updatedAt);
+};
diff --git a/web/packages/new/photos/services/sync.ts b/web/packages/new/photos/services/sync.ts
index c242b9db5e..a88cc64d8b 100644
--- a/web/packages/new/photos/services/sync.ts
+++ b/web/packages/new/photos/services/sync.ts
@@ -6,10 +6,7 @@ import {
import type { Collection } from "ente-media/collection";
import type { EnteFile } from "ente-media/file";
import { isHiddenCollection } from "ente-new/photos/services/collection";
-import {
- getAllLatestCollections,
- syncTrash,
-} from "ente-new/photos/services/collections";
+import { getAllLatestCollections } from "ente-new/photos/services/collections";
import { syncFiles } from "ente-new/photos/services/files";
import {
isMLSupported,
@@ -19,6 +16,7 @@ import {
import { searchDataSync } from "ente-new/photos/services/search";
import { syncSettings } from "ente-new/photos/services/settings";
import { splitByPredicate } from "ente-utils/array";
+import { pullTrash } from "./trash";
/**
* Called during a full sync, before doing the collection and file sync.
@@ -144,7 +142,7 @@ export const syncCollectionAndFiles = async (
opts?.onResetHiddenFiles,
opts?.onFetchHiddenFiles,
);
- await syncTrash(
+ await pullTrash(
collections,
opts?.onResetTrashedFiles,
videoPrunePermanentlyDeletedFileIDsIfNeeded,
diff --git a/web/packages/new/photos/services/trash.ts b/web/packages/new/photos/services/trash.ts
index f590dae3af..0fc733da1d 100644
--- a/web/packages/new/photos/services/trash.ts
+++ b/web/packages/new/photos/services/trash.ts
@@ -1,7 +1,22 @@
-import { RemoteEnteFile, type EnteFile } from "ente-media/file";
+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
+import { apiURL } from "ente-base/origins";
+import type { Collection } from "ente-media/collection";
+import {
+ decryptRemoteFile,
+ RemoteEnteFile,
+ type EnteFile,
+} from "ente-media/file";
import { fileCreationTime } from "ente-media/file-metadata";
import { z } from "zod/v4";
-import { savedTrashItems } from "./photos-fdb";
+import { getCollectionByID } from "./collection";
+import {
+ savedTrashItemCollectionKeys,
+ savedTrashItems,
+ savedTrashLastUpdatedAt,
+ saveTrashItemCollectionKeys,
+ saveTrashItems,
+ saveTrashLastUpdatedAt,
+} from "./photos-fdb";
/**
* A trash item indicates a file in trash.
@@ -53,6 +68,177 @@ const RemoteTrashItem = z.looseObject({
export type RemoteTrashItem = z.infer<typeof RemoteTrashItem>;
+/**
+ * Update our locally saved data about the files and collections in trash by
+ * pulling changes from remote.
+ *
+ * This function uses a diff-based mechanism that pulls forward from the
+ * (persisted) latest pulled item's updated at time.
+ *
+ * @param collections All the (non-deleted) collections that we know about
+ * locally.
+ *
+ * @param onUpdateTrashFiles A callback invoked when the locally persisted trash
+ * items are updated. This can be used for the UI to also update its state. This
+ * callback can be invoked multiple times during the pull (once for each batch
+ * that gets pulled and processed).
+ *
+ * @param onPruneDeletedFileIDs A callback invoked when files that were
+ * previously in trash have now been permanently deleted. This can be used by
+ * other subsystems to prune data referring to files that now have been deleted
+ * permanently. This callback can be invoked multiple times during the pull
+ * (once for each batch that gets processed).
+ */
+export async function pullTrash(
+ collections: Collection[],
+ onUpdateTrashFiles: ((files: EnteFile[]) => void) | undefined,
+ onPruneDeletedFileIDs: (deletedFileIDs: Set<number>) => Promise<void>,
+): Promise<void> {
+ // Data structures:
+ //
+ // `collectionKeyByID` is a map from collection ID => collection key.
+ //
+ // It is prefilled with all the non-deleted collections available locally
+ // (`collections`), and all keys of collections that trash items refererred
+ // to the last time we synced (`trashItemCollectionKeys`).
+ //
+ // > See: [Note: Trash item collection keys]
+ //
+ // As we iterate over the trash items, if we find a collection whose key is
+ // not present in the map, then we fetch that collection from remote, add
+ // its entry to the map, and also updated the persisted value corresponding
+ // to `trashItemCollectionKeys`.
+ //
+ // When we're done, we use `collectionKeyByID` to derive a filtered list of
+ // keys that are still referred to by the current set of trash items, and
+ // set this filtered list as the persisted value of
+ // `trashItemCollectionKeys`.
+
+ const collectionKeyByID = new Map(collections.map((c) => [c.id, c.key]));
+ const trashItemCollectionKeys = await savedTrashItemCollectionKeys();
+ for (const { id, key } of trashItemCollectionKeys) {
+ collectionKeyByID.set(id, key);
+ }
+
+ // Trash items, indexed by the file ID of the file they correspond to.
+ const trashItemsByID = new Map(
+ (await savedTrashItems()).map((t) => [t.file.id, t]),
+ );
+ let sinceTime = (await savedTrashLastUpdatedAt()) ?? 0;
+
+ while (true) {
+ const { diff, hasMore } = await getTrashDiff(sinceTime);
+ if (!diff.length) break;
+ // IDs of files that we encounter in this batch that have been
+ // permanently deleted.
+ const deletedFileIDs = new Set<number>();
+ for (const change of diff) {
+ sinceTime = Math.max(sinceTime, change.updatedAt);
+ const fileID = change.file.id;
+ if (change.isDeleted) deletedFileIDs.add(fileID);
+ if (change.isDeleted || change.isRestored) {
+ trashItemsByID.delete(fileID);
+ } else {
+ const collectionID = change.file.collectionID;
+ let collectionKey = collectionKeyByID.get(collectionID);
+ if (!collectionKey) {
+ // See: [Note: Trash item collection keys]
+ const collection = await getCollectionByID(collectionID);
+ collectionKey = collection.key;
+ collectionKeyByID.set(collectionID, collectionKey);
+ trashItemCollectionKeys.push({
+ id: collectionID,
+ key: collectionKey,
+ });
+ await saveTrashItemCollectionKeys(trashItemCollectionKeys);
+ }
+ trashItemsByID.set(fileID, {
+ ...change,
+ file: await decryptRemoteFile(change.file, collectionKey),
+ });
+ }
+ }
+
+ const trashItems = [...trashItemsByID.values()];
+ onUpdateTrashFiles?.(getTrashedFiles(trashItems));
+ await saveTrashItems(trashItems);
+ await saveTrashLastUpdatedAt(sinceTime);
+ if (deletedFileIDs.size) await onPruneDeletedFileIDs(deletedFileIDs);
+ if (!hasMore) break;
+ }
+
+ const trashCollectionIDs = new Set(
+ trashItemsByID.values().map((item) => item.file.collectionID),
+ );
+ await saveTrashItemCollectionKeys(
+ [...collectionKeyByID.entries()]
+ .filter(([id]) => trashCollectionIDs.has(id))
+ .map(([id, key]) => ({ id, key })),
+ );
+}
+
+/**
+ * See {@link FileDiffResponse} for general semantics of diff responses.
+ */
+const TrashDiffResponse = z.object({
+ diff: RemoteTrashItem.array(),
+ hasMore: z.boolean(),
+});
+
+/**
+ * Fetch all trash items that have been created or updated since
+ * {@link sinceTime}.
+ *
+ * Remote only, does not modify local state.
+ *
+ * @param sinceTime The {@link updatedAt} of the most recently updated trash
+ * item we have previously fetched from remote. This serves both as a pagination
+ * mechanish, and a way to fetch a delta diff the next time the client needs to
+ * pull changes from remote.
+ */
+const getTrashDiff = async (sinceTime: number) => {
+ const res = await fetch(
+ await apiURL("/trash/v2/diff", { sinceTime: sinceTime.toString() }),
+ { headers: await authenticatedRequestHeaders() },
+ );
+ ensureOk(res);
+ return TrashDiffResponse.parse(await res.json());
+};
+
+/**
+ * Delete all the items in trash, permanently deleting the files corresponding
+ * to them.
+ *
+ * This updates both remote and our local database.
+ */
+export const emptyTrash = async () => {
+ await postTrashEmpty((await savedTrashLastUpdatedAt()) ?? 0);
+ await saveTrashItems([]);
+};
+
+/**
+ * Delete all the items in trash on remote.
+ *
+ * Remote only, does not modify local state.
+ *
+ * @param lastUpdatedAt The {@link updatedAt} value of the most recent item in
+ * trash for the user that we know about locally. Remote will only delete trash
+ * entries with updatedAt timestamp <= this provided lastUpdatedAt.
+ *
+ * The user's trash is cleaned up in an async manner. This timestamp is used to
+ * ensure that newly trashed files are not deleted due to delay in the async
+ * operation, and that out of sync clients (who have a stale lastUpdatedAt)
+ * do not cause deletion of newer files that they don't know about locally.
+ */
+const postTrashEmpty = async (lastUpdatedAt: number) =>
+ ensureOk(
+ await fetch(await apiURL("/trash/empty"), {
+ method: "POST",
+ headers: await authenticatedRequestHeaders(),
+ body: JSON.stringify({ lastUpdatedAt }),
+ }),
+ );
+
export async function getLocalTrashedFiles() {
return getTrashedFiles(await savedTrashItems());
}