Skip to content

armgit / ente

Public Imported from GitHub
0

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

Trim vendored photos services in albums app

Anand Baburajan7b1b1fa47fc8
diff --git a/web/apps/albums/vendor/ente-new/photos/services/collection-summary.ts b/web/apps/albums/vendor/ente-new/photos/services/collection-summary.ts
index 0ce77e61ca..d2f2a43847 100644
--- a/web/apps/albums/vendor/ente-new/photos/services/collection-summary.ts
+++ b/web/apps/albums/vendor/ente-new/photos/services/collection-summary.ts
@@ -26,234 +26,27 @@ export type CollectionSummaryAttribute =
| "shareePinned";
/**
- * ID of the special {@link CollectionSummary} instances that are not backed by
- * a real {@link Collection}.
+ * ID of pseudo-collections that the public albums UI reuses from the photos app.
*/
export const PseudoCollectionID = {
- /**
- * The "All" section.
- *
- * The "All" section is the default view when the user opens the gallery,
- * showing them all of their unique non-hidden and non-archived files.
- */
all: 0,
- /**
- * A pseudo-collection containing the individually archived files.
- *
- * The archive items is a pseudo-collection consisting of all the files
- * which have been individually archived. It is what gets shown when the
- * user navigates to the "Archive" section.
- */
archiveItems: -1,
- /**
- * Trash.
- *
- * This pseudo-collection contains items that are in the user's trash. Each
- * items corresponds to a file that has been deleted, but has not yet been
- * deleted permanently.
- *
- * As a special case, when the trash pseudo collection is being shown, then
- * the corresponding files array will have {@link EnteTrashFile} items
- * instead of normal {@link EnteFile} ones.
- */
trash: -2,
- /**
- * A placeholder for the uncategorized collection until the real one comes
- * into existence.
- *
- * [Note: Uncategorized placeholder]
- *
- * The user's sole "uncategorized" collection is created on demand the first
- * time we need to move a file out of the last collection it belonged to
- * (yet retain the file).
- *
- * Until the real uncategorized collection comes into existence, we use this
- * dummy placeholder collection as the {@link CollectionSummary} that gets
- * shown if the user navigates to the "Uncategorized" section in the UI.
- */
uncategorizedPlaceholder: -3,
- /**
- * A pseudo-collection containing the individually hidden files.
- *
- * The "Hidden items" is the default pseudo-collection shown in the "Hidden"
- * section. It consists of the files that the user has individually hidden.
- *
- * It is derived by merging all of the user's "default hidden" albums (See:
- * Note: Multiple "default" hidden collections]).
- *
- * In addition to this "Hidden items" pseudo-collection, the "Hidden"
- * section also shows other albums that were hidden.
- */
hiddenItems: -4,
} as const;
/**
- * A massaged version of a collection or a pseudo-collection suitable for being
- * directly shown in the UI.
- *
- * From one perspective, this can be thought of as a
- * "CollectionOrPseudoCollection": a group of files listed together in the UI,
- * with the files coming from a real "collection" or some special "section".
- *
- * - In the first case, the underlying listing will be backed by a
- * {@link Collection},
- *
- * - In the second case the files and other attributes comprising the listing
- * will be determined by the special case-specific rules for that particular
- * pseudo-collection.
- *
- * However, even when this is backed by a corresponding "real"
- * {@link Collection}, it adds some extra attributes that make it easier and
- * more efficient for the UI elements to render this collection summary
- * directly. So from that perspective, this can be also be thought of as a
- * "UICollection".
+ * Minimal collection summary shape required by the vendored viewer sidebars.
*/
export interface CollectionSummary {
- /**
- * The ID of the underlying {@link Collection}, or one of the predefined
- * {@link PseudoCollectionID}s.
- */
id: number;
- /**
- * The primary "UI" type for the collection or pseudo-collection.
- *
- * For newer code consider using {@link attributes} instead.
- */
- type: CollectionSummaryType;
- /**
- * Various UI related attributes of the collection or pseudo-collection.
- *
- * This is meant to replace {@link type} gradually. It defines various
- * ad-hoc "UI" attributes which make it easier and more efficient for the UI
- * elements to render the collection summary in the UI.
- */
attributes: Set<CollectionSummaryAttribute>;
- /**
- * The name of the collection or pseudo-collection surfaced in the UI.
- */
name: string;
- /**
- * The newest file in the collection or pseudo-collection (if any).
- */
- latestFile: EnteFile | undefined;
- /**
- * The file to show as the cover for the collection or pseudo-collection.
- *
- * This can be one of
- * - A file explicitly chosen by the user.
- * - The latest file.
- * - The oldest file (if the user has set a reverse sort on the collection).
- */
coverFile: EnteFile | undefined;
- /**
- * The number of files in the underlying collection, or the number of files
- * computed to belong to the pseudo-collection.
- */
- fileCount: number;
- /**
- * The time (epoch microseconds) when the collection was last updated. For
- * pseudo-collections this will (usually) be the updation time of the latest
- * file that it contains.
- */
- updationTime: number | undefined;
- sortPriority: CollectionSummarySortPriority;
- order?: number;
}
/**
- * Collection summaries, indexed by their IDs.
+ * Collection summaries indexed by collection ID.
*/
export type CollectionSummaries = Map<number, CollectionSummary>;
-
-/**
- * The sort schemes that can be used when we're showing list of collections
- * (e.g. in the collection bar).
- *
- * This is the list of all possible values, see {@link CollectionsSortBy} for
- * the type.
- */
-export const collectionsSortBy = [
- "name-asc",
- "name-desc",
- "creation-time-asc",
- "creation-time-desc",
- "updation-time-asc",
- "updation-time-desc",
-] as const;
-
-/**
- * Type of individual {@link collectionsSortBy} values.
- */
-export type CollectionsSortBy = (typeof collectionsSortBy)[number];
-
-/**
- * An orderable set collection "priorities".
- *
- * Collection summaries that need to appear prior to other collection summaries
- * get assigned a "priority", which is an otherwise arbitrary integer that only
- * serves as a sort priority (higher being prior).
- *
- * All collections in a higher category appear together, and before collections
- * in lower categories. Within each priority, the collections are sorted by the
- * applicable {@link CollectionsSortBy}.
- */
-export const CollectionSummarySortPriority = {
- /**
- * Currently: "All", "Uncategorized", "Hidden items".
- */
- system: 9,
- favorites: 8,
- pinned: 7,
- other: 0,
-} as const;
-
-/**
- * The TypeScript type that restricts the possible values to be one from amongst
- * the {@link CollectionSummarySortCategory} constants.
- */
-export type CollectionSummarySortPriority =
- (typeof CollectionSummarySortPriority)[keyof typeof CollectionSummarySortPriority];
-
-export const haveOnlySystemCollections = (
- collectionSummaries: CollectionSummaries,
-) =>
- [...collectionSummaries.values()].every((cs) =>
- cs.attributes.has("system"),
- );
-
-export const canAddToCollection = ({ attributes }: CollectionSummary) =>
- !attributes.has("system") && !attributes.has("sharedIncomingViewer");
-
-export const canMoveToCollection = ({ attributes }: CollectionSummary) =>
- !attributes.has("system") && !attributes.has("sharedIncoming");
-
-/**
- * Sort an array of collection summaries by the specified sort order.
- *
- * @param collectionSummaries The array of collection summaries to sort
- * @param by The sort order to apply
- * @returns A new sorted array of collection summaries
- */
-export const sortCollectionSummaries = (
- collectionSummaries: CollectionSummary[],
- by: CollectionsSortBy,
-): CollectionSummary[] => {
- return [...collectionSummaries].sort((a, b) => {
- switch (by) {
- case "name-asc":
- return a.name.localeCompare(b.name);
- case "name-desc":
- return b.name.localeCompare(a.name);
- case "creation-time-asc":
- // Oldest first: lower ID = created earlier.
- return a.id - b.id;
- case "creation-time-desc":
- // Newest first: higher ID = created later.
- return b.id - a.id;
- case "updation-time-asc":
- return (a.updationTime ?? 0) - (b.updationTime ?? 0);
- case "updation-time-desc":
- return (b.updationTime ?? 0) - (a.updationTime ?? 0);
- }
- });
-};
diff --git a/web/apps/albums/vendor/ente-new/photos/services/collection.ts b/web/apps/albums/vendor/ente-new/photos/services/collection.ts
index e4af4ee7c3..19cf930c01 100644
--- a/web/apps/albums/vendor/ente-new/photos/services/collection.ts
+++ b/web/apps/albums/vendor/ente-new/photos/services/collection.ts
@@ -1,217 +1,68 @@
-import { ensureLocalUser } from "ente-accounts/services/user";
-import { blobCache } from "ente-base/blob-cache";
import {
- boxSeal,
- boxSealOpen,
- decryptBox,
- encryptBox,
- generateKey,
-} from "ente-base/crypto";
-import { haveWindow } from "ente-base/env";
+ ensureLocalUser,
+ ensureSavedKeyAttributes,
+} from "ente-accounts/services/user";
+import { boxSealOpen, decryptBox, encryptBox } from "ente-base/crypto";
import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
import { apiURL } from "ente-base/origins";
import { ensureMasterKeyFromSession } from "ente-base/session";
-import { groupFilesByCollectionID } from "ente-gallery/utils/file";
import {
- CollectionSubType,
decryptRemoteCollection,
RemoteCollection,
- RemotePublicURL,
type Collection,
- type CollectionNewParticipantRole,
- type CollectionOrder,
- type CollectionPrivateMagicMetadataData,
- type CollectionPublicMagicMetadataData,
- type CollectionShareeMagicMetadataData,
- type CollectionType,
- type PublicURL,
} from "ente-media/collection";
-import {
- decryptRemoteFile,
- FileDiffResponse,
- type EnteFile,
-} from "ente-media/file";
-import { ItemVisibility, metadataHash } from "ente-media/file-metadata";
-import {
- createMagicMetadata,
- encryptMagicMetadata,
- type RemoteMagicMetadata,
-} from "ente-media/magic-metadata";
-import { splitByPredicate } from "ente-utils/array";
+import type { EnteFile } from "ente-media/file";
import { z } from "zod";
-import {
- removeCollectionIDLastSyncTime,
- saveCollectionFiles,
- saveCollectionLastSyncTime,
- saveCollections,
- saveCollectionsUpdationTime,
- savedCollectionFiles,
- savedCollectionLastSyncTime,
- savedCollections,
- savedCollectionsUpdationTime,
-} from "./photos-fdb";
-import { ensureUserKeyPair, getPublicKey } from "./user";
-const uncategorizedCollectionName = "Uncategorized";
-const defaultHiddenCollectionName = ".hidden";
-export const defaultHiddenCollectionUserFacingName = "Hidden";
-const favoritesCollectionName = "Favorites";
const requestBatchSize = 1000;
-interface UpdateMagicMetadataRequest {
+interface CollectionFileItem {
id: number;
- magicMetadata: RemoteMagicMetadata;
+ encryptedKey: string;
+ keyDecryptionNonce: string;
}
-const batched = async <T, U>(
+const CollectionResponse = z.object({ collection: RemoteCollection });
+
+const batched = async <T>(
items: T[],
- op: (batchItems: T[]) => Promise<U>,
-): Promise<U[]> => {
- const result: U[] = [];
+ op: (batchItems: T[]) => Promise<void>,
+): Promise<void> => {
for (let i = 0; i < items.length; i += requestBatchSize) {
- result.push(await op(items.slice(i, i + requestBatchSize)));
+ await op(items.slice(i, i + requestBatchSize));
}
- return result;
};
-/**
- * Create a new album (a collection of type "album") on remote, and return its
- * local representation.
- *
- * Remote only, does not modify local state.
- *
- * @param albumName The name to use for the new album.
- */
-export const createAlbum = (albumName: string) =>
- createCollection(albumName, "album");
-
-/**
- * Create a new quick link collection on remote, and return its local
- * representation.
- *
- * Remote only, does not modify local state.
- *
- * @param name The name to use for the new quick link collection.
- */
-export const createQuickLinkCollection = (name: string) =>
- createCollection(name, "album", {
- subType: CollectionSubType.quicklink,
- visibility: ItemVisibility.visible,
- });
-
-/**
- * Create a new hidden album on remote, and return its local representation.
- *
- * Remote only, does not modify local state.
- *
- * @param albumName The name to use for the new hidden album.
- */
-export const createHiddenAlbum = (albumName: string) =>
- createCollection(albumName, "album", { visibility: ItemVisibility.hidden });
-
-/**
- * Create a new collection on remote, and return its local representation.
- *
- * Remote only, does not modify local state.
- *
- * @param name The name of the new collection.
- *
- * @param type The type of the new collection.
- *
- * @param magicMetadataData Optional metadata to use as the collection's private
- * mutable metadata when creating the new collection.
- */
-const createCollection = async (
- name: string,
- type: CollectionType,
- magicMetadataData?: CollectionPrivateMagicMetadataData,
-): Promise<Collection> => {
- const collectionKey = await generateKey();
- const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =
- await encryptBox(collectionKey, await ensureMasterKeyFromSession());
- const { encryptedData: encryptedName, nonce: nameDecryptionNonce } =
- await encryptBox(new TextEncoder().encode(name), collectionKey);
- const magicMetadata = magicMetadataData
- ? await encryptMagicMetadata(
- createMagicMetadata(magicMetadataData),
- collectionKey,
- )
- : undefined;
-
- const remoteCollection = await postCollections({
- encryptedKey,
- keyDecryptionNonce,
- encryptedName,
- nameDecryptionNonce,
- type,
- ...(magicMetadata && { magicMetadata }),
- });
-
- return decryptRemoteKeyAndCollection(remoteCollection);
+const ensureUserKeyPair = async () => {
+ const { encryptedSecretKey, secretKeyDecryptionNonce, publicKey } =
+ ensureSavedKeyAttributes();
+ const privateKey = await decryptBox(
+ { encryptedData: encryptedSecretKey, nonce: secretKeyDecryptionNonce },
+ await ensureMasterKeyFromSession(),
+ );
+ return { publicKey, privateKey };
};
-/**
- * Given a {@link RemoteCollection}, first obtain its decryption key, and then
- * use that to decrypt and return the collection itself.
- */
-const decryptRemoteKeyAndCollection = async (collection: RemoteCollection) =>
- decryptRemoteCollection(collection, await decryptCollectionKey(collection));
-
-/**
- * Return the decrypted collection key (as a base64 string) for the given
- * {@link RemoteCollection}.
- */
-export const decryptCollectionKey = async (
- collection: RemoteCollection,
+const decryptCollectionKey = async (
+ collection: z.infer<typeof RemoteCollection>,
): Promise<string> => {
const { owner, encryptedKey, keyDecryptionNonce } = collection;
- if (owner.id == ensureLocalUser().id) {
- // The collection key of collections owned by the user is encrypted with
- // the user's master key. The nonce will be present in such cases.
+ if (owner.id === ensureLocalUser().id) {
return decryptBox(
{ encryptedData: encryptedKey, nonce: keyDecryptionNonce! },
await ensureMasterKeyFromSession(),
);
- } else {
- // The collection key of collections shared with the user is encrypted
- // with the user's public key.
- return boxSealOpen(encryptedKey, await ensureUserKeyPair());
}
-};
-/**
- * Zod schema for a remote response containing a single collection.
- */
-const CollectionResponse = z.object({ collection: RemoteCollection });
-
-/**
- * Create a collection on remote with the provided data, and return the new
- * remote collection object returned by remote on success.
- */
-const postCollections = async (
- collectionData: Partial<RemoteCollection>,
-): Promise<RemoteCollection> => {
- const res = await fetch(await apiURL("/collections"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify(collectionData),
- });
- ensureOk(res);
- return CollectionResponse.parse(await res.json()).collection;
+ return boxSealOpen(encryptedKey, await ensureUserKeyPair());
};
+const decryptRemoteKeyAndCollection = async (
+ collection: z.infer<typeof RemoteCollection>,
+) => decryptRemoteCollection(collection, await decryptCollectionKey(collection));
+
/**
- * Fetch a collection from remote by its ID.
- *
- * Remote only, does not use or modify local state.
- *
- * This is not expected to be needed in the normal flow of things, since we
- * fetch collections en masse, and efficiently, using the collection diff
- * requests.
- *
- * @param collectionID The ID of the collection to fetch.
- *
- * @returns The collection obtained from remote after decrypting its contents.
+ * Fetch a collection from remote by its ID and decrypt it for local use.
*/
export const getCollectionByID = async (
collectionID: number,
@@ -224,458 +75,6 @@ export const getCollectionByID = async (
return decryptRemoteKeyAndCollection(collection);
};
-/**
- * Zod schema for a remote response containing a an array of collections.
- */
-const CollectionsResponse = z.object({
- collections: z.array(RemoteCollection),
-});
-
-/**
- * An collection upsert or deletion obtained as a result of
- * {@link getCollections} invocation.
- *
- * Each change either contains the latest data associated with the collection
- * that has been created or updated, or has a flag set to indicate that the
- * corresponding collection has been deleted.
- */
-export interface CollectionChange {
- /**
- * The ID of the collection.
- */
- id: number;
- /**
- * The added or updated collection, or `undefined` for deletions.
- *
- * - This will be set to the (decrypted) collection if it was added or
- * updated on remote.
- *
- * - This will not be set if the corresponding collection was deleted on
- * remote.
- */
- collection?: Collection;
- /**
- * Epoch microseconds denoting when this collection was last changed
- * (created or updated or deleted).
- */
- updationTime: number;
-}
-
-/**
- * Pull the latest collections from remote.
- *
- * This function uses a delta diff, pulling only changes since the timestamp
- * saved by the last pull.
- *
- * @returns the latest list of collections, reflecting both the state in our
- * local database and on remote.
- */
-export const pullCollections = async (): Promise<Collection[]> => {
- const collections = await savedCollections();
- let sinceTime = (await savedCollectionsUpdationTime()) ?? 0;
-
- const changes = await getCollections(sinceTime);
-
- if (!changes.length) return collections;
-
- const collectionsByID = new Map(collections.map((c) => [c.id, c]));
- for (const { id, updationTime, collection } of changes) {
- sinceTime = Math.max(sinceTime, updationTime);
- if (collection) {
- collectionsByID.set(id, collection);
- } else {
- // Collection was deleted on remote.
- await removeCollectionIDLastSyncTime(id);
- collectionsByID.delete(id);
- }
- }
-
- const updatedCollections = [...collectionsByID.values()];
-
- await saveCollections(updatedCollections);
- await saveCollectionsUpdationTime(sinceTime);
-
- return updatedCollections;
-};
-
-/**
- * Fetch all collections that have been added or updated on remote since
- * {@link sinceTime}, with markers for those that have been deleted.
- *
- * @param sinceTime The {@link updationTime} of the latest collection that was
- * fetched in a previous set of changes. This allows us to resume fetching from
- * that point. Pass 0 to fetch from the beginning.
- *
- * @returns An array of {@link CollectionChange}s. It is guaranteed that there
- * will be at most one entry for a given collection in the result array. See:
- * [Note: Diff response will have at most one entry for an id]
- */
-const getCollections = async (
- sinceTime: number,
-): Promise<CollectionChange[]> => {
- const res = await fetch(await apiURL("/collections/v2", { sinceTime }), {
- headers: await authenticatedRequestHeaders(),
- });
- ensureOk(res);
- const { collections } = CollectionsResponse.parse(await res.json());
- return Promise.all(
- collections.map(async (c) => ({
- id: c.id,
- updationTime: c.updationTime,
- collection: c.isDeleted
- ? undefined
- : await decryptRemoteKeyAndCollection(c),
- })),
- );
-};
-
-/**
- * Fetch all files from remote and update our local database.
- *
- * Each time it updates the local database, the {@link onSetCollectionFiles}
- * callback is also invoked to give the caller a chance to bring its own
- * in-memory state up to speed.
- *
- * @param collections The user's collections. These are assumed to be the latest
- * collections on remote (that is, the pull for collections should happen prior
- * to calling this function).
- *
- * @param onSetCollectionFiles An optional callback invoked when the locally
- * saved collection files were replaced by the provided {@link collectionFiles}.
- *
- * The callback is optional because we might be called in a context where we
- * just want to update the local database, and there is no other in-memory state
- * we need to keep in sync.
- *
- * The callback can be invoked multiple times for each pull (once for each batch
- * of changes received, for each collection that was updated).
- *
- * @returns true if one or more files were updated locally, false otherwise.
- */
-export const pullCollectionFiles = async (
- collections: Collection[],
- onSetCollectionFiles: ((files: EnteFile[]) => void) | undefined,
-) => {
- let didUpdateFiles = false;
-
- const savedFiles = await savedCollectionFiles();
-
- // Prune collections files for which we no longer have a collection.
- const collectionIDs = new Set(collections.map((c) => c.id));
- let files = savedFiles.filter((f) => collectionIDs.has(f.collectionID));
-
- // Update both the saved and in-memory files to reflect the pruning.
- if (files.length != savedFiles.length) {
- await saveCollectionFiles(files);
- onSetCollectionFiles?.(files);
- didUpdateFiles = true;
- }
-
- for (const collection of collections) {
- let sinceTime = (await savedCollectionLastSyncTime(collection)) ?? 0;
- if (sinceTime == collection.updationTime) {
- // The updationTime of a collection is guaranteed to be >= the
- // updationTime of any file in the collection.
- continue;
- }
-
- const [thisCollectionFiles, otherFiles] = splitByPredicate(
- files,
- (f) => f.collectionID == collection.id,
- );
-
- const thisCollectionFilesByID = new Map(
- thisCollectionFiles.map((f) => [f.id, f]),
- );
-
- while (true) {
- const { diff, hasMore } = await getCollectionDiff(
- collection.id,
- sinceTime,
- );
- if (!diff.length) break;
-
- for (const change of diff) {
- sinceTime = Math.max(sinceTime, change.updationTime);
- if (change.isDeleted) {
- thisCollectionFilesByID.delete(change.id);
- } else {
- const file = await decryptRemoteFile(
- change,
- collection.key,
- );
- await clearCachedThumbnailIfContentChanged(
- thisCollectionFilesByID.get(change.id),
- file,
- );
- thisCollectionFilesByID.set(change.id, file);
- }
- }
-
- files = otherFiles.concat([...thisCollectionFilesByID.values()]);
-
- await saveCollectionFiles(files);
- await saveCollectionLastSyncTime(collection, sinceTime);
- onSetCollectionFiles?.(files);
- didUpdateFiles = true;
-
- if (!hasMore) break;
- }
-
- // There might be a difference between the latest updation time of a
- // file in the collection, and the latest time of the collection itself,
- // if something about the collection itself changed, not the files in it
- // (e.g. if the collection was renamed).
- //
- // In such cases, advance the sync time to match the collection's update
- // time so we don't do an unnecessary collection diff the next time.
- await saveCollectionLastSyncTime(collection, collection.updationTime);
- }
-
- return didUpdateFiles;
-};
-
-/**
- * Fetch all files in the given collection have been created or updated since
- * {@link sinceTime}.
- *
- * Remote only, does not modify local state.
- *
- * @param collection The ID of the collection whose updates we want to fetch.
- *
- * @param sinceTime The timestamp of most recently update for the collection
- * that we have already pulled. 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 getCollectionDiff = async (collectionID: number, sinceTime: number) => {
- const res = await fetch(
- await apiURL("/collections/v2/diff", { collectionID, sinceTime }),
- { headers: await authenticatedRequestHeaders() },
- );
- ensureOk(res);
- return FileDiffResponse.parse(await res.json());
-};
-
-/**
- * Clear cached thumbnail of an existing file if the thumbnail data has changed.
- *
- * This function in expected to be called when we are processing a collection
- * diff, updating our local state to reflect files that were updated on remote.
- * This is an opportune moment to invalidate any cached thumbnails for files
- * whose thumbnail content has changed.
- *
- * An example of when such invalidation is necessary:
- *
- * 1. Take a photo on mobile, and let it sync via the mobile app to us (web).
- * 2. Edit the photo outside of Ente (e.g. using Apple Photos).
- * 3. When the Ente mobile client next comes into foreground, it'll update the
- * remote thumbnail for the existing file to reflect the changes.
- *
- * @param existingFile The {@link EnteFile} we had in our local database before
- * processing the diff response. Pass `undefined` to indicate that there was no
- * existing file corresponding to {@link updatedFile}; in such a case this
- * function is a no-op.
- *
- * @param updatedFile The update {@link EntneFile} (with the same file ID as the
- * {@link existingFile}) which we got in the diff response.
- */
-const clearCachedThumbnailIfContentChanged = async (
- existingFile: EnteFile | undefined,
- updatedFile: EnteFile,
-) => {
- if (!existingFile) return;
-
- // The hashes of the files differ, which indicates that the change was in
- // the file's contents, not the metadata itself, and thus we should refresh
- // the thumbnail.
- if (
- metadataHash(existingFile.metadata) !=
- metadataHash(updatedFile.metadata)
- ) {
- // This is an infrequent occurrence, so we lazily get the cache.
- const thumbnailCache = await blobCache("thumbs");
- await thumbnailCache.delete(updatedFile.id.toString());
- }
-};
-
-/**
- * Return all collections (both normal and hidden) that are present in our
- * local database.
- */
-export const savedAllCollections = (): Promise<Collection[]> =>
- savedCollections();
-
-/**
- * Return all normal (non-hidden) collections that are present in our local
- * database.
- */
-export const savedNormalCollections = (): Promise<Collection[]> =>
- savedCollections().then(
- (cs) => splitByPredicate(cs, isHiddenCollection)[1],
- );
-
-/**
- * Return all hidden collections that are present in our local database.
- */
-export const savedHiddenCollections = (
- currentUserID?: number,
-): Promise<Collection[]> =>
- savedCollections().then(
- (cs) =>
- splitByPredicate(cs, (c) =>
- isHiddenCollection(c, currentUserID),
- )[0],
- );
-
-/**
- * Return a map of the (user-facing) collection name, indexed by collection ID.
- */
-export const createCollectionNameByID = (collections: Collection[]) =>
- new Map(collections.map((c) => [c.id, collectionUserFacingName(c)]));
-
-/**
- * Return the "user facing" name of the given collection.
- *
- * Usually this is the same as the collection name, but it might be a different
- * string for special collections like default hidden collections.
- */
-export const collectionUserFacingName = (collection: Collection) =>
- isDefaultHiddenCollection(collection)
- ? defaultHiddenCollectionUserFacingName
- : collection.name;
-
-/**
- * A CollectionFileItem represents a file in a API request to add, move or
- * restore files to a particular collection.
- */
-interface CollectionFileItem {
- /**
- * The file's ID.
- */
- id: number;
- /**
- * The file's key (as a base64 string), encrypted with the key of the
- * collection to which it is being added or moved.
- */
- encryptedKey: string;
- /**
- * The nonce (as a base64 string) that was used during the encryption of
- * {@link encryptedKey}.
- */
- keyDecryptionNonce: string;
-}
-
-/**
- * Make a remote request to add the given {@link files} to the given
- * {@link collection}.
- *
- * Remote only, does not modify local state.
- */
-export const addToCollection = async (
- collection: Collection,
- files: EnteFile[],
-) =>
- batched(files, async (batchFiles) => {
- const encryptedFileKeys = await encryptWithCollectionKey(
- collection,
- batchFiles,
- );
- ensureOk(
- await fetch(await apiURL("/collections/add-files"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify({
- collectionID: collection.id,
- files: encryptedFileKeys,
- }),
- }),
- );
- });
-
-/**
- * Make a remote request to restore the given {@link files} to the given
- * {@link collection}.
- *
- * Remote only, does not modify local state.
- */
-export const restoreToCollection = async (
- collection: Collection,
- files: EnteFile[],
-) =>
- batched(files, async (batchFiles) => {
- const encryptedFileKeys = await encryptWithCollectionKey(
- collection,
- batchFiles,
- );
- ensureOk(
- await fetch(await apiURL("/collections/restore-files"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify({
- collectionID: collection.id,
- files: encryptedFileKeys,
- }),
- }),
- );
- });
-
-/**
- * Make a remote request to move the given {@link files} (which may be in
- * different collections) to the given {@link collection}.
- *
- * This is a higher level primitive than {@link moveFromCollection} that first
- * segregates the files into per-collection sets, and then performs
- * {@link moveFromCollection} for each such set.
- *
- * Remote only, does not modify local state.
- */
-export const moveToCollection = async (
- collection: Collection,
- files: EnteFile[],
-) =>
- Promise.all(
- groupFilesByCollectionID(files)
- .entries()
- .filter(([cid]) => cid != collection.id)
- .map(([cid, cf]) => moveFromCollection(cid, collection, cf)),
- );
-
-/**
- * Make a remote request to move the given {@link files} from a collection (as
- * identified by its {@link fromCollectionID}) to the given
- * {@link toCollection}.
- *
- * Remote only, does not modify local state.
- */
-export const moveFromCollection = async (
- fromCollectionID: number,
- toCollection: Collection,
- files: EnteFile[],
-) =>
- batched(files, async (batchFiles) => {
- const encryptedFileKeys = await encryptWithCollectionKey(
- toCollection,
- batchFiles,
- );
- ensureOk(
- await fetch(await apiURL("/collections/move-files"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify({
- fromCollectionID: fromCollectionID,
- toCollectionID: toCollection.id,
- files: encryptedFileKeys,
- }),
- }),
- );
- });
-
-/**
- * Return an array of {@link CollectionFileItem}s, one for each file in
- * {@link files}, containing the corresponding file' ID and keys, but this time
- * encrypted using the key of the given {@link collection}.
- */
const encryptWithCollectionKey = async (
collection: Collection,
files: EnteFile[],
@@ -692,1167 +91,25 @@ const encryptWithCollectionKey = async (
);
/**
- * Make a remote request to move the given {@link files} to trash.
- *
- * @param files The {@link EnteFile}s to move to trash. The API request needs
- * both a file ID and a collection ID, but there should be at most one entry for
- * a particular fileID in this array.
- *
- * Remote only, does not modify local state.
+ * Add existing files to a collection on remote.
*/
-export const moveToTrash = async (files: EnteFile[]) =>
- batched(files, async (batchFiles) =>
- ensureOk(
- await fetch(await apiURL("/files/trash"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify({
- items: batchFiles.map((file) => ({
- fileID: file.id,
- collectionID: file.collectionID,
- })),
- }),
- }),
- ),
- );
-
-/**
- * Make a remote request to delete the given {@link fileIDs} from trash.
- *
- * Remote only, does not modify local state.
- */
-export const deleteFromTrash = async (fileIDs: number[]) =>
- batched(fileIDs, async (batchIDs) =>
- ensureOk(
- await fetch(await apiURL("/trash/delete"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify({ fileIDs: batchIDs }),
- }),
- ),
- );
-
-/**
- * Remove the given files from the specified collection owned by the user.
- *
- * Reads local state but does not modify it. The effects are on remote.
- *
- * @param collection A collection (either owned by the user, or shared with the
- * user).
- *
- * @param files The files to remove from the collection. The files owned by the
- * user will be removed. If the collection is not owned by the user, then any
- * files that are not owned by the user will not be processed (unless the user
- * is an admin of the collection). In such cases, this function will return a
- * count less than the count of the provided files (after having removed what
- * can be removed).
- *
- * @returns The count of files that were processed. This can be less than the
- * count of the provided {@link files} if some files were not processed because
- * because they belong to other users (and {@link collection} also does not
- * belong to the current user, and the user is not an admin).
- *
- * [Note: Removing files from a collection]
- *
- * There are four scenarios
- *
- * own file shared file
- * own collection M R
- * admin in collection R R
- * others collection R not supported
- *
- * M (move) when both collection and file belongs to user
- * R (remove) when only one of them belongs to the user, or user is admin
- *
- * The move operation is not supported across ownership boundaries. The remove
- * operation is only supported across ownership boundaries, but the user should
- * have ownership of either the file or collection (not both), or be an admin.
- *
- * In more detail, the above scenarios can be described this way.
- *
- * 1. Move: If the user owns both the collection and the file they're trying to
- * remove from the collection, then instead of a remove the client needs to
- * move it to a different user owned collection in which it already exists
- * (such a move acts as a remove). If it doesn't exist in any other user
- * owned collection, then move it to the user's "Uncategorized" collection.
- * The intent is that a "remove from collection" should not remove the last
- * copy of a file (thus deleting it).
- *
- * 2. Remove: If the user does not own the file being removed, or owns the file
- * being removed but does not own the collection from which it is being
- * removed, they can remove it from the collection using the POST
- * "/collections/v3/remove-files".
- *
- * 3. Admin remove: If the user is an admin of a collection they don't own, they
- * can remove any file from the collection (including files they don't own).
- *
- * 4. Not supported: Removing a file the user does not own from a collection
- * that the user does not own and is not an admin of.
- *
- * The "remove from collection" primitive is provided to the user both as a UI
- * action (on selecting files in a collection), and as an implicit action if the
- * user chooses the option to "keep files" when deleting a collection.
- *
- * This entire shebang is implemented by the following set of functions:
- *
- * 1. [Public] {@link removeFromCollection} - Handles both own and others
- * collections by delegating to the one of the following functions.
- *
- * 2. [Public] {@link removeFromOwnCollection} - Handles both cases for own
- * collections by delegating to either "Move" or "Remove"
- *
- * 3. [Private] {@link removeFromOthersCollection} - Handles cases for other's
- * collections. If the user is an admin, they can remove all files. Otherwise
- * only the user's own files can be removed.
- *
- * 4. [Private] {@link removeOwnFilesFromOwnCollection} implements the "Move".
- *
- * 5. [Private] {@link removeNonCollectionOwnerFiles} implements the "Remove".
- */
-export const removeFromCollection = async (
- collection: Collection,
- files: EnteFile[],
-): Promise<number> =>
- collection.owner.id == ensureLocalUser().id
- ? removeFromOwnCollection(collection.id, files)
- : removeFromOthersCollection(collection, files);
-
-export const removeFromOwnCollection = async (
- collectionID: number,
- files: EnteFile[],
-) => {
- const userID = ensureLocalUser().id;
- const [userFiles, nonUserFiles] = splitByPredicate(
- files,
- (f) => f.ownerID == userID,
- );
- if (userFiles.length) {
- await removeOwnFilesFromOwnCollection(collectionID, userFiles);
- }
- if (nonUserFiles.length) {
- await removeNonCollectionOwnerFiles(collectionID, nonUserFiles);
- }
- return files.length;
-};
-
-const removeFromOthersCollection = async (
+export const addToCollection = async (
collection: Collection,
files: EnteFile[],
-) => {
- const userID = ensureLocalUser().id;
- // Check if user is an admin of this collection
- const isAdmin =
- collection.sharees.find((s) => s.id == userID)?.role == "ADMIN";
-
- if (isAdmin) {
- // Admins can remove all files from the collection
- if (files.length) {
- await removeNonCollectionOwnerFiles(collection.id, files);
- }
- return files.length;
- }
-
- // Non-admins can only remove their own files
- const [userFiles] = splitByPredicate(files, (f) => f.ownerID == userID);
- if (userFiles.length) {
- await removeNonCollectionOwnerFiles(collection.id, userFiles);
- }
- return userFiles.length;
-};
-
-/**
- * Remove the given user owned files from the given collection also owned by the
- * user, ensuring that at least one user owned instance is retained for them
- * (either in a different user owned collection in which they already existed,
- * or in the user's "Uncategorized" collection as a fallback).
- *
- * Reads local state but does not modify it. The effects are on remote.
- *
- * This is used as a subroutine of [Note: Removing files from a collection].
- */
-const removeOwnFilesFromOwnCollection = async (
- collectionID: number,
- filesToRemove: EnteFile[],
-) => {
- const userID = ensureLocalUser().id;
- const collections = await savedCollections();
- const collectionFiles = await savedCollectionFiles();
-
- const collectionsByID = new Map(collections.map((c) => [c.id, c]));
-
- // This set keeps a running track of file IDs that still need to be removed.
- // It is seeded with the original set of files we were asked to remove.
- const filesToRemoveIDs = new Set(filesToRemove.map((f) => f.id));
- // A predicate that checks if the given file is still pending removal.
- const pendingRemove = (f: EnteFile) => filesToRemoveIDs.has(f.id);
-
- const collectionFilesToRemove = collectionFiles.filter(pendingRemove);
- const groups = groupFilesByCollectionID(collectionFilesToRemove);
- for (const [targetCollectionID, filesInCollection] of groups.entries()) {
- // Ignore the source collection itself.
- if (targetCollectionID == collectionID) continue;
-
- const targetCollection = collectionsByID.get(targetCollectionID)!;
- // We want a copy to exist in at least one other user owned collection.
- if (targetCollection.owner.id != userID) continue;
- // We'll move to uncategorized after the loop (if they still remain).
- if (targetCollection.type == "uncategorized") continue;
-
- const filesInCollectionToRemove =
- filesInCollection.filter(pendingRemove);
- if (!filesInCollectionToRemove.length) continue;
-
- // The file already exists in the target collection, but this acts as
- // "remove" from the source.
- await moveFromCollection(
- collectionID,
- targetCollection,
- filesInCollectionToRemove,
- );
-
- // Mark the files we just moved as been taken care of.
- filesInCollectionToRemove.forEach((f) => filesToRemoveIDs.delete(f.id));
- }
-
- // Any files that were not moved so far, move them to uncategorized,
- // creating uncategorized if needed.
- const remainingFiles = filesToRemove.filter(pendingRemove);
- if (remainingFiles.length) {
- const uncategorizedCollection =
- collections.find((c) => c.type == "uncategorized") ??
- (await createUncategorizedCollection());
-
- await moveFromCollection(
- collectionID,
- uncategorizedCollection,
- remainingFiles,
+): Promise<void> =>
+ batched(files, async (batchFiles) => {
+ const encryptedFileKeys = await encryptWithCollectionKey(
+ collection,
+ batchFiles,
);
- }
-};
-
-/**
- * Remove the provided files from the provided collection on remote.
- *
- * Only files which do not belong to the collection owner can be removed from
- * the collection using this endpoint. That is,
- *
- * - Either the user owns the collection and the all files being removed are
- * owned by somebody else, or
- *
- * - The user owns all the files being removed, but the collection belongs to
- * somebody else.
- *
- * If the collection owner wants to remove files owned by them, then their
- * client should first move those files first to other collections owned by the
- * collection owner.
- *
- * Remote only, does not modify local state.
- *
- * See also: [Note: Removing files from a collection].
- *
- * @param collectionID The ID of collection from which to remove the files.
- *
- * @param files A list of files which do not belong to the user, and which we
- * the user wants to remove from the given collection.
- */
-const removeNonCollectionOwnerFiles = async (
- collectionID: number,
- files: EnteFile[],
-) =>
- batched(files, async (batchFiles) =>
ensureOk(
- await fetch(await apiURL("/collections/v3/remove-files"), {
+ await fetch(await apiURL("/collections/add-files"), {
method: "POST",
headers: await authenticatedRequestHeaders(),
body: JSON.stringify({
- collectionID,
- fileIDs: batchFiles.map((f) => f.id),
+ collectionID: collection.id,
+ files: encryptedFileKeys,
}),
}),
- ),
- );
-
-/**
- * Delete a collection on remote.
- *
- * Reads local state but does not modify it. The effects are on remote.
- *
- * @param collectionID The ID of the collection to delete.
- *
- * @param opts Deletion options. In particular, if {@link keepFiles} is true,
- * then the any of the user's files that only exist in this collection are
- * first moved to another one of the user's collection (or Uncategorized if no
- * such collection exists) before deleting the collection.
- *
- * See: [Note: Removing files from a collection]
- */
-export const deleteCollection = async (
- collectionID: number,
- opts?: { keepFiles?: boolean },
-) => {
- const keepFiles = opts?.keepFiles ?? false;
-
- if (keepFiles) {
- const collectionFiles = await savedCollectionFiles();
- await removeFromOwnCollection(
- collectionID,
- collectionFiles.filter((f) => f.collectionID == collectionID),
- );
- }
-
- ensureOk(
- await fetch(
- await apiURL(`/collections/v3/${collectionID}`, {
- collectionID,
- keepFiles,
- }),
- { method: "DELETE", headers: await authenticatedRequestHeaders() },
- ),
- );
-};
-
-/**
- * Rename a collection on remote.
- *
- * Remote only, does not modify local state.
- *
- * @param collection The collection to rename.
- *
- * @param newName The new name of the collection
- */
-export const renameCollection = async (
- collection: Collection,
- newName: string,
-) => {
- if (collection.magicMetadata?.data.subType == CollectionSubType.quicklink) {
- // Convert quicklinks to a regular collection before giving them a name.
- await updateCollectionPrivateMagicMetadata(collection, {
- subType: CollectionSubType.default,
- });
- }
- const { encryptedData: encryptedName, nonce: nameDecryptionNonce } =
- await encryptBox(new TextEncoder().encode(newName), collection.key);
- await postCollectionsRename({
- collectionID: collection.id,
- encryptedName,
- nameDecryptionNonce,
- });
-};
-
-interface RenameRequest {
- collectionID: number;
- encryptedName: string;
- nameDecryptionNonce: string;
-}
-
-const postCollectionsRename = async (renameRequest: RenameRequest) =>
- ensureOk(
- await fetch(await apiURL("/collections/rename"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify(renameRequest),
- }),
- );
-
-/**
- * Change the visibility (normal, archived, hidden) of a collection on remote.
- *
- * Remote only, does not modify local state.
- *
- * This function works with both collections owned by the user, and collections
- * shared with the user.
- *
- * @param collection The collection whose visibility we want to change.
- *
- * @param visibility The new visibility (normal, archived, hidden).
- */
-export const updateCollectionVisibility = async (
- collection: Collection,
- visibility: ItemVisibility,
-) =>
- collection.owner.id == ensureLocalUser().id
- ? updateCollectionPrivateMagicMetadata(collection, { visibility })
- : updateCollectionShareeMagicMetadata(collection, { visibility });
-
-/**
- * Change the pinned state of a collection on remote.
- *
- * Remote only, does not modify local state.
- *
- * This function works only for collections owned by the user.
- *
- * @param collection The collection whose order we want to change.
- *
- * @param order Whether on not the collection is pinned.
- */
-export const updateCollectionOrder = async (
- collection: Collection,
- order: CollectionOrder,
-) => updateCollectionPrivateMagicMetadata(collection, { order });
-
-/**
- * Change the order (pin/unpin) of a shared collection on remote for the sharee.
- *
- * Remote only, does not modify local state.
- *
- * This function works only for collections shared with the user (not owned).
- *
- * @param collection The shared collection whose order we want to change.
- *
- * @param order Whether on not the collection is pinned by the sharee.
- */
-export const updateShareeCollectionOrder = async (
- collection: Collection,
- order: CollectionOrder,
-) => updateCollectionShareeMagicMetadata(collection, { order });
-
-/**
- * Change the sort order of the files with a collection on remote.
- *
- * Remote only, does not modify local state.
- *
- * This function works only for collections owned by the user.
- *
- * @param collection The collection whose file sort order we want to change.
- *
- * @param asc If true, then the files are sorted ascending (oldest first).
- * Otherwise they are sorted descending (newest first).
- */
-export const updateCollectionSortOrder = async (
- collection: Collection,
- asc: boolean,
-) => updateCollectionPublicMagicMetadata(collection, { asc });
-
-/**
- * Change the cover photo of a collection on remote.
- *
- * Remote only, does not modify local state.
- *
- * This function works only for collections owned by the user.
- *
- * @param collection The collection whose cover we want to change.
- *
- * @param coverID The file ID to set as the cover.
- *
- * Pass `0` to reset to the default cover.
- */
-export const updateCollectionCover = async (
- collection: Collection,
- coverID: number,
-) => updateCollectionPublicMagicMetadata(collection, { coverID });
-
-/**
- * Change the layout type of a collection on remote.
- *
- * Remote only, does not modify local state.
- *
- * This function works only for collections owned by the user.
- *
- * @param collection The collection whose layout we want to change.
- *
- * @param layout The layout type ("masonry", "grouped", "continuous", "trip").
- */
-export const updateCollectionLayout = async (
- collection: Collection,
- layout: string,
-) => updateCollectionPublicMagicMetadata(collection, { layout });
-
-/**
- * Update the private magic metadata of a collection on remote.
- *
- * Remote only, does not modify local state.
- *
- * @param collection The collection whose magic metadata we want to update.
- *
- * The existing magic metadata of this collection is used both to obtain the
- * current magic metadata version, and the existing contents on top of which the
- * updates are applied, so it is imperative that both these values are up to
- * sync with remote otherwise the update will fail.
- *
- * @param updates A non-empty subset of
- * {@link CollectionPrivateMagicMetadataData} entries.
- *
- * See: [Note: Magic metadata data cannot have nullish values]
- */
-const updateCollectionPrivateMagicMetadata = async (
- { id, key, magicMetadata }: Collection,
- updates: CollectionPrivateMagicMetadataData,
-) =>
- putCollectionsMagicMetadata({
- id,
- magicMetadata: await encryptMagicMetadata(
- createMagicMetadata(
- { ...magicMetadata?.data, ...updates },
- magicMetadata?.version,
- ),
- key,
- ),
- });
-
-/**
- * Update the private magic metadata of a single collection on remote.
- */
-const putCollectionsMagicMetadata = async (
- updateRequest: UpdateMagicMetadataRequest,
-) =>
- ensureOk(
- await fetch(await apiURL("/collections/magic-metadata"), {
- method: "PUT",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify(updateRequest),
- }),
- );
-
-/**
- * Update the public magic metadata of a collection on remote.
- *
- * Remote only, does not modify local state.
- *
- * This is a variant of {@link updateCollectionPrivateMagicMetadata} that works
- * with the {@link pubMagicMetadata} of a collection.
- */
-const updateCollectionPublicMagicMetadata = async (
- { id, key, pubMagicMetadata }: Collection,
- updates: CollectionPublicMagicMetadataData,
-) =>
- putCollectionsPublicMagicMetadata({
- id,
- magicMetadata: await encryptMagicMetadata(
- createMagicMetadata(
- { ...pubMagicMetadata?.data, ...updates },
- pubMagicMetadata?.version,
- ),
- key,
- ),
- });
-
-/**
- * Update the public magic metadata of a single collection on remote.
- */
-const putCollectionsPublicMagicMetadata = async (
- updateRequest: UpdateMagicMetadataRequest,
-) =>
- ensureOk(
- await fetch(await apiURL("/collections/public-magic-metadata"), {
- method: "PUT",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify(updateRequest),
- }),
- );
-
-/**
- * Update the per-sharee magic metadata of a collection on remote.
- *
- * Remote only, does not modify local state.
- *
- * This is a variant of {@link updateCollectionPrivateMagicMetadata} that works
- * with the {@link sharedMagicMetadata} of a collection.
- */
-const updateCollectionShareeMagicMetadata = async (
- { id, key, sharedMagicMetadata }: Collection,
- updates: CollectionShareeMagicMetadataData,
-) =>
- putCollectionsShareeMagicMetadata({
- id,
- magicMetadata: await encryptMagicMetadata(
- createMagicMetadata(
- { ...sharedMagicMetadata?.data, ...updates },
- sharedMagicMetadata?.version,
- ),
- key,
- ),
- });
-
-/**
- * Update the sharee magic metadata of a single shared collection on remote.
- */
-const putCollectionsShareeMagicMetadata = async (
- updateRequest: UpdateMagicMetadataRequest,
-) =>
- ensureOk(
- await fetch(await apiURL("/collections/sharee-magic-metadata"), {
- method: "PUT",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify(updateRequest),
- }),
- );
-
-/**
- * Create a new collection of type "favorites" for the user on remote, and
- * return its local representation.
- *
- * Remote only, does not modify local state.
- *
- * Each user can have at most one collection of type "favorites" owned by them.
- * While this function does not enforce the constraint locally, it will fail
- * because remote will enforce the constraint and fail the request when we
- * attempt to create a second collection of type "favorites".
- */
-const createFavoritesCollection = () =>
- createCollection(favoritesCollectionName, "favorites");
-
-/**
- * Create a new collection of type "uncategorized" for the user on remote, and
- * return its local representation.
- *
- * Remote only, does not modify local state.
- *
- * Each user can have at most one collection of type "uncategorized" owned by
- * them. While this function does not enforce the constraint locally, it will
- * fail because remote will enforce the constraint and fail the request when we
- * attempt to create a second collection of type "uncategorized".
- */
-export const createUncategorizedCollection = () =>
- createCollection(uncategorizedCollectionName, "uncategorized");
-
-/**
- * Return the user's own favorites collection if one is found in the local
- * database. Otherwise create a new one and return that.
- *
- * Reads local state but does not modify it. The effects are on remote.
- */
-const savedOrCreateUserFavoritesCollection = async () =>
- (await savedUserFavoritesCollection()) ?? createFavoritesCollection();
-
-/**
- * Return the user's own favorites collection, if any, present in the local
- * database.
- */
-export const savedUserFavoritesCollection = async () => {
- const userID = ensureLocalUser().id;
- const collections = await savedCollections();
- return collections.find(
- (collection) =>
- // See: [Note: User and shared favorites]
- collection.type == "favorites" && collection.owner.id == userID,
- );
-};
-
-/**
- * Mark the provided {@link files} as the user's favorites by adding them to the
- * user's favorites collection.
- *
- * If the user doesn't yet have a favorites collection, it is created.
- *
- * Reads local state but does not modify it. The effects are on remote.
- */
-export const addToFavoritesCollection = async (files: EnteFile[]) =>
- addToCollection(await savedOrCreateUserFavoritesCollection(), files);
-
-export const removeFromFavoritesCollection = async (files: EnteFile[]) =>
- // Non-null assertion because if we get here and a favorites collection does
- // not already exist, then something is wrong.
- removeFromOwnCollection((await savedUserFavoritesCollection())!.id, files);
-
-/**
- * Return the default hidden collection for the user if one is found in the
- * local database. Otherwise create a new one and return that.
- *
- * Reads local state but does not modify it. The effects are on remote.
- */
-const savedOrCreateDefaultHiddenCollection = async () =>
- (await savedDefaultHiddenCollection()) ?? createDefaultHiddenCollection();
-
-/**
- * Return the user's default hidden collection, if any, present in the
- * local database.
- */
-const savedDefaultHiddenCollection = async () =>
- (await savedCollections()).find((collection) =>
- isDefaultHiddenCollection(collection),
- );
-
-/**
- * Create a new collection with hidden visibility on remote, marking it as the
- * default hidden collection, and return its local representation.
- *
- * Remote only, does not modify local state.
- *
- * See also: [Note: Multiple "default" hidden collections].
- */
-const createDefaultHiddenCollection = () =>
- createCollection(defaultHiddenCollectionName, "album", {
- subType: CollectionSubType.defaultHidden,
- visibility: ItemVisibility.hidden,
- });
-
-/**
- * Return true if the provided collection is the default hidden collection.
- *
- * See also: [Note: Multiple "default" hidden collections].
- */
-export const isDefaultHiddenCollection = (collection: Collection) =>
- collection.magicMetadata?.data.subType == CollectionSubType.defaultHidden;
-
-/**
- * Extract the IDs of all the "default" hidden collections.
- *
- * [Note: Multiple "default" hidden collections].
- *
- * Normally, there is only expected to be one such collection. But to provide
- * clients laxity in synchronization, we don't enforce this and instead allow
- * for multiple such default hidden collections to exist.
- */
-export const findDefaultHiddenCollectionIDs = (collections: Collection[]) =>
- new Set<number>(
- collections
- .filter(isDefaultHiddenCollection)
- .map((collection) => collection.id),
- );
-
-/**
- * Return `true` if the given collection is hidden.
- *
- * Hidden collections are those that have their visibility set to hidden for
- * the current user (owner or sharee).
- *
- * In one instance, the isHiddenCollection function is called outside of a window, like
- * for the people tab's review suggestions, this function was trigged from a worker.
- * In that case, since the worker has no access to the localStorage, we need to pass the currentUserID
- * explicitly.
- */
-export const isHiddenCollection = (
- collection: Collection,
- currentUserID?: number,
-) => {
- const userID =
- currentUserID ?? (haveWindow() ? ensureLocalUser().id : undefined);
-
- if (userID === undefined) {
- throw new Error(
- "isHiddenCollection: currentUserID is required outside window context",
- );
- }
- if (collection.owner.id == userID) {
- return (
- collection.magicMetadata?.data.visibility == ItemVisibility.hidden
- );
- }
- return (
- collection.sharedMagicMetadata?.data.visibility == ItemVisibility.hidden
- );
-};
-
-/**
- * Return `true` if the given collection is archived.
- *
- * Archived collections are those that have their visibility set to hidden in the
- * collection's private magic metadata or per-sharee private metadata.
- */
-export const isArchivedCollection = (collection: Collection) =>
- collection.magicMetadata?.data.visibility == ItemVisibility.archived ||
- collection.sharedMagicMetadata?.data.visibility == ItemVisibility.archived;
-
-/**
- * Return `true` if the current user can remove files from all participants in
- * the given collection.
- *
- * This is true if the user is either:
- * - The owner of the collection, or
- * - An admin of the collection
- *
- * This is used to determine if the user can remove files added by other users
- * from a shared collection.
- */
-export const canRemoveFilesFromAllParticipants = (collection: Collection) => {
- const userID = ensureLocalUser().id;
- if (collection.owner.id == userID) return true;
- // Check if the user is an admin of this collection
- const sharee = collection.sharees.find((s) => s.id == userID);
- return sharee?.role == "ADMIN";
-};
-
-/**
- * Hide the provided {@link files} by moving them to the default hidden
- * collection.
- *
- * If the default hidden collection does not already exist, it is created.
- *
- * Reads local state but does not modify it. The effects are on remote.
- */
-export const hideFiles = async (files: EnteFile[]) =>
- moveToCollection(await savedOrCreateDefaultHiddenCollection(), files);
-
-/**
- * Share the provided collection with another Ente user.
- *
- * Remote only, does not modify local state.
- *
- * @param collection The {@link Collection} to share.
- *
- * @param withUserEmail The email of the Ente user with whom to share it.
- *
- * @param role The desired role for the new participant.
- */
-export const shareCollection = async (
- collection: Collection,
- withUserEmail: string,
- role: CollectionNewParticipantRole,
-) => {
- const publicKey = await getPublicKey(withUserEmail);
- const encryptedKey = await boxSeal(collection.key, publicKey);
-
- ensureOk(
- await fetch(await apiURL("/collections/share"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify({
- collectionID: collection.id,
- email: withUserEmail,
- role,
- encryptedKey,
- }),
- }),
- );
-};
-
-/**
- * Stop sharing a collection on remote with the given user.
- *
- * Remote only, does not modify local state.
- *
- * @param collectionID The ID of the collection to stop sharing with the user
- * having the given {@link email}.
- *
- * @param email The email of the Ente user with whom to stop sharing.
- */
-export const unshareCollection = async (collectionID: number, email: string) =>
- ensureOk(
- await fetch(await apiURL("/collections/unshare"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify({ collectionID, email }),
- }),
- );
-
-/**
- * The subset of public URL attributes that can be customized by the user when
- * creating a link.
- */
-export type CreatePublicURLAttributes = Pick<
- Partial<PublicURL>,
- | "enableCollect"
- | "enableJoin"
- | "enableComment"
- | "validTill"
- | "deviceLimit"
->;
-
-/**
- * Create a new public link for the given collection.
- *
- * Remote only, does not modify local state.
- *
- * @param collectionID The ID of the collection for which the public link should
- * be created.
- *
- * @param attributes Optional attributes to set when creating the public link.
- */
-export const createPublicURL = async (
- collectionID: number,
- attributes?: CreatePublicURLAttributes,
-): Promise<PublicURL> => {
- const enableComment = true;
- const res = await fetch(await apiURL("/collections/share-url"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify({ collectionID, enableComment, ...attributes }),
- });
- ensureOk(res);
- return z.object({ result: RemotePublicURL }).parse(await res.json()).result;
-};
-
-/**
- * The subset of public URL attributes that can be updated by the user after the
- * link has already been created.
- */
-export type UpdatePublicURLAttributes = Omit<
- Partial<PublicURL>,
- "url" | "enablePassword"
-> & { disablePassword?: boolean; passHash?: string };
-
-/**
- * Update the attributes of an existing public link for a shared collection.
- *
- * Remote only, does not modify local state.
- *
- * @param collectionID The ID of the collection whose public link to update.
- *
- * @param updates The public link attributes to modify. Only attributes
- * corresponding to entries with non nullish values will be updated, all the
- * other existing attributes will remain unmodified.
- *
- * @returns the updated public URL.
- */
-export const updatePublicURL = async (
- collectionID: number,
- updates: UpdatePublicURLAttributes,
-): Promise<PublicURL> => {
- const res = await fetch(await apiURL("/collections/share-url"), {
- method: "PUT",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify({ collectionID, ...updates }),
- });
- ensureOk(res);
- return z.object({ result: RemotePublicURL }).parse(await res.json()).result;
-};
-
-/**
- * Delete the public link for the collection with given {@link collectionID}.
- *
- * Remote only, does not modify local state.
- */
-export const deleteShareURL = async (collectionID: number) =>
- ensureOk(
- await fetch(await apiURL(`/collections/share-url/${collectionID}`), {
- method: "DELETE",
- headers: await authenticatedRequestHeaders(),
- }),
- );
-
-/**
- * Leave a collection which had previously been shared with the user.
- *
- * Remote only, does not modify local state.
- *
- * @param collectionID The ID of the shared collection to leave.
- */
-export const leaveSharedCollection = async (collectionID: number) =>
- ensureOk(
- await fetch(await apiURL(`/collections/leave/${collectionID}`), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- }),
- );
-
-/**
- * Zod schema for a collection action (used for pending removal actions).
- */
-const CollectionAction = z.object({
- collectionID: z.number(),
- fileID: z.number().nullish(),
-});
-
-type CollectionAction = z.infer<typeof CollectionAction>;
-
-/**
- * Zod schema for the pending removal actions response.
- */
-const PendingRemovalActionsResponse = z.object({
- actions: z.array(CollectionAction).nullish(),
-});
-
-/**
- * Fetch pending removal actions from remote.
- *
- * Remote only, does not modify local state.
- *
- * Pending removal actions indicate files that have been removed from a
- * collection by the owner or an admin, and should be moved to the user's
- * uncategorized collection if they exist locally.
- *
- * @returns A list of {@link CollectionAction} objects representing files that
- * should be moved to uncategorized.
- */
-export const fetchPendingRemovalActions = async (): Promise<
- CollectionAction[]
-> => {
- const res = await fetch(
- await apiURL("/collection-actions/pending-remove"),
- { headers: await authenticatedRequestHeaders() },
- );
- ensureOk(res);
- const { actions } = PendingRemovalActionsResponse.parse(await res.json());
- return actions ?? [];
-};
-
-/**
- * Process pending removal actions by moving affected files to the user's
- * uncategorized collection.
- *
- * This function fetches pending removal actions from remote, identifies which
- * files are affected, and moves them to the uncategorized collection. This
- * ensures that files removed from shared collections by owners/admins are not
- * lost but instead moved to a safe location.
- *
- * @param collections The current list of collections (used to find affected
- * files).
- *
- * Reads local state but does not modify it. The effects are on remote.
- */
-export const movePendingRemovalActionsToUncategorized = async (
- collections: Collection[],
-) => {
- const pendingActions = await fetchPendingRemovalActions();
- if (!pendingActions.length) return;
-
- // Group file IDs by collection ID
- const collectionToFileIDs = new Map<number, Set<number>>();
- for (const action of pendingActions) {
- if (action.fileID == null) continue;
- const fileIDs = collectionToFileIDs.get(action.collectionID);
- if (fileIDs) {
- fileIDs.add(action.fileID);
- } else {
- collectionToFileIDs.set(
- action.collectionID,
- new Set([action.fileID]),
- );
- }
- }
-
- if (!collectionToFileIDs.size) return;
-
- // Get all files from local storage
- const collectionFiles = await savedCollectionFiles();
-
- // Group files by collection ID for efficient lookup
- const filesByCollectionID = groupFilesByCollectionID(collectionFiles);
-
- // Create a map of collection ID to collection for quick lookup
- const collectionByID = new Map(collections.map((c) => [c.id, c]));
-
- // Lazily initialized target collections (only created if needed)
- let uncategorizedCollection: Collection | undefined;
- let defaultHiddenCollection: Collection | undefined;
-
- // Process each collection with pending removal actions
- for (const [
- collectionID,
- pendingFileIDs,
- ] of collectionToFileIDs.entries()) {
- const sourceCollection = collectionByID.get(collectionID);
- const filesInCollection = filesByCollectionID.get(collectionID) ?? [];
- const filesToMove = filesInCollection.filter((file) =>
- pendingFileIDs.has(file.id),
- );
-
- if (!filesToMove.length) continue;
-
- // Determine target collection based on whether source is hidden
- const isSourceHidden =
- sourceCollection && isHiddenCollection(sourceCollection);
-
- let targetCollection: Collection;
- if (isSourceHidden) {
- // Move files from hidden collections to default hidden collection
- if (!defaultHiddenCollection) {
- defaultHiddenCollection =
- collections.find(isDefaultHiddenCollection) ??
- (await createDefaultHiddenCollection());
- }
- targetCollection = defaultHiddenCollection;
- } else {
- // Move files from normal collections to uncategorized
- if (!uncategorizedCollection) {
- uncategorizedCollection =
- collections.find((c) => c.type == "uncategorized") ??
- (await createUncategorizedCollection());
- }
- targetCollection = uncategorizedCollection;
- }
-
- // Move files to target collection (this also removes them from the
- // source collection, which is the primary goal here)
- await moveFromCollection(collectionID, targetCollection, filesToMove);
- }
-};
-
-/**
- * Remove files from the uncategorized collection if they exist in other
- * user-owned albums.
- *
- * This is a cleanup operation that helps users remove duplicates from their
- * uncategorized collection. Files that exist both in uncategorized and in
- * other albums are moved out of uncategorized to one of those albums.
- *
- * Reads local state but does not modify it. The effects are on remote.
- *
- * @param uncategorizedCollection The user's uncategorized collection.
- */
-export const cleanUncategorized = async (
- uncategorizedCollection: Collection,
-): Promise<number> => {
- const userID = ensureLocalUser().id;
- const collections = await savedCollections();
- const collectionFiles = await savedCollectionFiles();
-
- // Get files in the uncategorized collection
- const uncategorizedFiles = collectionFiles.filter(
- (f) => f.collectionID == uncategorizedCollection.id,
- );
-
- if (!uncategorizedFiles.length) return 0;
-
- // Build a map from file ID to the collections it belongs to (excluding
- // uncategorized itself)
- const fileIDToCollectionIDs = new Map<number, number[]>();
- for (const file of collectionFiles) {
- if (file.collectionID == uncategorizedCollection.id) continue;
- const existing = fileIDToCollectionIDs.get(file.id);
- if (existing) {
- existing.push(file.collectionID);
- } else {
- fileIDToCollectionIDs.set(file.id, [file.collectionID]);
- }
- }
-
- // Filter to only user-owned normal collections (not hidden, not shared)
- const userOwnedCollectionIDs = new Set(
- collections
- .filter(
- (c) =>
- c.owner.id == userID &&
- c.type != "uncategorized" &&
- !isHiddenCollection(c),
- )
- .map((c) => c.id),
- );
-
- const collectionsByID = new Map(collections.map((c) => [c.id, c]));
-
- // Find files that exist in other user-owned collections
- const filesToClean = uncategorizedFiles.filter((file) => {
- const otherCollectionIDs = fileIDToCollectionIDs.get(file.id);
- if (!otherCollectionIDs) return false;
- // Check if any of these collections are user-owned normal collections
- return otherCollectionIDs.some((cid) =>
- userOwnedCollectionIDs.has(cid),
);
});
-
- if (!filesToClean.length) return 0;
-
- // Group files by their target collection for efficient batching
- const filesByTargetCollection = new Map<number, EnteFile[]>();
- for (const file of filesToClean) {
- const otherCollectionIDs = fileIDToCollectionIDs.get(file.id)!;
- const targetCollectionID = otherCollectionIDs.find((cid) =>
- userOwnedCollectionIDs.has(cid),
- );
- if (!targetCollectionID) continue;
-
- const existing = filesByTargetCollection.get(targetCollectionID) ?? [];
- existing.push(file);
- filesByTargetCollection.set(targetCollectionID, existing);
- }
-
- // Move files in batches per target collection
- let cleanedCount = 0;
- for (const [targetCollectionID, files] of filesByTargetCollection) {
- const targetCollection = collectionsByID.get(targetCollectionID);
- if (!targetCollection) continue;
-
- // Move files from uncategorized to the target collection.
- // This effectively removes them from uncategorized since they already
- // exist in the target.
- await moveFromCollection(
- uncategorizedCollection.id,
- targetCollection,
- files,
- );
- cleanedCount += files.length;
- }
-
- return cleanedCount;
-};
diff --git a/web/apps/albums/vendor/ente-new/photos/services/photos-fdb.ts b/web/apps/albums/vendor/ente-new/photos/services/photos-fdb.ts
deleted file mode 100644
index 1aaf5b44fc..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/photos-fdb.ts
+++ /dev/null
@@ -1,264 +0,0 @@
-/**
- * @file Photos app specific files DB. See: [Note: Files DB].
- */
-
-import {
- LocalCollections,
- LocalEnteFile,
- localForage,
- LocalTimestamp,
- transformFilesIfNeeded,
-} from "ente-gallery/services/files-db";
-import { type Collection } from "ente-media/collection";
-import { type EnteFile } from "ente-media/file";
-import { z } from "zod";
-
-interface TrashItem {
- file: EnteFile;
- updatedAt: number;
- deleteBy: number;
-}
-
-/**
- * Return all collections present in our local database.
- *
- * This includes both normal (non-hidden) and hidden collections.
- *
- * Use {@link saveCollections} to update the database.
- */
-export const savedCollections = async (): Promise<Collection[]> =>
- LocalCollections.parse((await localForage.getItem("collections")) ?? []);
-
-/**
- * Replace the list of collections stored in our local database.
- *
- * This is the setter corresponding to {@link savedCollections}.
- *
- * This updates the underlying storage of both normal (non-hidden) and hidden
- * collections (the split between normal and hidden is not at the database level
- * but is a filter when they are accessed).
- */
-export const saveCollections = async (collections: Collection[]) => {
- await localForage.setItem("collections", collections);
-};
-
-/**
- * Return the locally persisted {@link updationTime} of the latest collection we
- * have pulled from remote.
- *
- * Use {@link saveCollectionsUpdationTime} to update the saved value.
- */
-export const savedCollectionsUpdationTime = async () =>
- LocalTimestamp.parse(await localForage.getItem("collection-updation-time"));
-
-/**
- * Update the locally persisted timestamp that will be returned by subsequent
- * calls to {@link savedCollectionsUpdationTime}.
- */
-export const saveCollectionsUpdationTime = async (time: number) => {
- await localForage.setItem("collection-updation-time", time);
-};
-
-const TrashItemCollectionKey = z.object({
- /**
- * Collection ID.
- */
- id: z.number(),
- /**
- * Decrypted collection key.
- */
- key: z.string(),
-});
-
-const TrashItemCollectionKeys = TrashItemCollectionKey.array();
-
-export type TrashItemCollectionKey = z.infer<typeof TrashItemCollectionKey>;
-
-/**
- * Return keys of collections (including potentially deleted ones) referred to
- * by trash items present in our local database.
- *
- * Use {@link saveTrashItemCollectionKeys} to update the database.
- *
- * [Note: Trash item collection keys]
- *
- * Trash items are erstwhile files, and like collection files, they need a
- * collection key to decrypt them.
- *
- * However, it is possible that the collection which contained the file was also
- * deleted. Such deleted collections will not be present in the list returned by
- * {@link savedCollections}.
- *
- * So to still be able to access the collection keys in order to process the
- * trash item, we separately save a list of {collectionID, collectionKey} pairs.
- *
- * - This list contains only collectionsIDs for which there is a corresponding
- * local trash item.
- *
- * - During each trash sync, this list is seeded using {@link savedCollections}.
- * Then, whenever we encounter a collection which is not present locally
- * (since it might've been deleted), we fetch it from remote and add an entry
- * for it in {@link savedTrashItemCollectionKeys}.
- *
- * - Once the sync completes, we updated this list to retain only entries that
- * are still referred to by items remaining in the trash.
- */
-export const savedTrashItemCollectionKeys = async (): Promise<
- TrashItemCollectionKey[]
-> =>
- TrashItemCollectionKeys.parse(
- // This key name is not accurate, these are not deleted collections but
- // collections referred to by deleted items (so they can include deleted
- // collections, but not exclusively).
- //
- // But since the use of this key name is localized to this file so we
- // let the original name be.
- (await localForage.getItem("deleted-collection")) ?? [],
- );
-
-/**
- * Replace the list of trash item collection keys stored in our local database.
- *
- * This is the setter corresponding to {@link saveTrashItemCollectionKeys}.
- */
-export const saveTrashItemCollectionKeys = async (
- cks: TrashItemCollectionKey[],
-) => {
- await localForage.setItem("deleted-collection", cks);
-};
-
-/**
- * Return all files present in our local database.
- *
- * These are "collection files", meaning that there might be multiple entries
- * for the same file, one for each collection that the file belongs to. For more
- * details, See: [Note: Collection File].
- *
- * Use {@link saveCollectionFiles} to update the database.
- */
-export const savedCollectionFiles = async (): Promise<EnteFile[]> => {
- // [Note: Avoiding Zod parsing for large DB arrays]
- //
- // Zod can be used to validate that the value we read from the DB is indeed
- // the same as the type we expect, but for potentially very large arrays,
- // this has an overhead that is perhaps not justified when dealing with DB
- // entries we ourselves wrote.
- //
- // For example (as a non-rigorous benchmark) parsing 200k files took one
- // second. Zod is fast, just that these arrays are big and might be accessed
- // frequently, and the schemas are, while not too complicated, non-trivial.
- //
- // As an optimization, we skip the runtime check here and cast. This might
- // not be the most optimal choice in the future, so (a) use it sparingly,
- // and (b) mark all such cases with the title of this note.
- //
- // Note that the cast is happening inside the local forage code since we're
- // passing a type parameter.
- let files = (await localForage.getItem<EnteFile[]>("files")) ?? [];
-
- // Previously hidden files were stored separately. If that key is present,
- // also read those files, and migrate them (save the concatenation to disk
- // and delete the corresponding DB key).
- //
- // This migration was added Jun 2025, v1.7.14-beta (tag: Migration).
- const previousHiddenFiles =
- await localForage.getItem<EnteFile[]>("hidden-files");
- if (previousHiddenFiles) {
- files = files.concat(previousHiddenFiles);
- await saveCollectionFiles(files);
- await localForage.removeItem("hidden-files");
- // While we're cleaning up, also remove this unused field related to
- // hidden collections also being separately stored earlier.
- await localForage.removeItem("hidden-collection-ids");
- }
-
- return transformFilesIfNeeded(files);
-};
-
-/**
- * Replace the list of collection files stored in our local database.
- *
- * This is the setter corresponding to {@link savedCollectionFiles}.
- */
-export const saveCollectionFiles = async (files: EnteFile[]) => {
- await localForage.setItem("files", transformFilesIfNeeded(files));
-};
-
-/**
- * Return the locally persisted "last sync time" for a collection that we have
- * pulled from remote. This can be used to perform a paginated delta pull from
- * the saved time onwards.
- *
- * > Specifically, this is the {@link updationTime} of the latest file from the
- * > {@link collection}, or the the collection itself if it is fully synced.
- *
- * Use {@link saveCollectionLastSyncTime} to update the value saved in the
- * database, and {@link removeCollectionIDLastSyncTime} to remove the saved
- * value from the database.
- */
-export const savedCollectionLastSyncTime = async (collection: Collection) =>
- LocalTimestamp.parse(await localForage.getItem(`${collection.id}-time`));
-
-/**
- * Update the locally persisted timestamp that will be returned by subsequent
- * calls to {@link savedCollectionLastSyncTime}.
- */
-export const saveCollectionLastSyncTime = async (
- collection: Collection,
- time: number,
-) => {
- await localForage.setItem(`${collection.id}-time`, time);
-};
-
-/**
- * Remove the locally persisted timestamp, if any, previously saved for a
- * collection with the given ID using {@link saveCollectionLastSyncTime}.
- */
-export const removeCollectionIDLastSyncTime = async (collectionID: number) => {
- await localForage.removeItem(`${collectionID}-time`);
-};
-
-/**
- * Zod schema for a trash entry saved in our local database.
- */
-const LocalTrashItem = z.looseObject({
- file: LocalEnteFile,
- updatedAt: z.number(),
- deleteBy: z.number(),
-});
-
-/**
- * Return all trash entries present in our local database.
- *
- * Use {@link saveTrashItems} to update the database
- */
-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.
- *
- * This is the setter corresponding to {@link savedTrashItems}.
- */
-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/apps/albums/vendor/ente-new/photos/services/social.ts b/web/apps/albums/vendor/ente-new/photos/services/social.ts
index 2a61427e07..a376de1c52 100644
--- a/web/apps/albums/vendor/ente-new/photos/services/social.ts
+++ b/web/apps/albums/vendor/ente-new/photos/services/social.ts
@@ -64,35 +64,6 @@ export const getUnifiedSocialDiff = async (
return decryptSocialDiff(collectionKey, await res.json());
};
-/**
- * Get album feed - comments and reactions relevant to the current user.
- *
- * This uses a server-side filtered endpoint that only returns:
- * - Comments on files owned by the user (excluding user's own comments)
- * - Replies to user's comments
- * - Reactions on files owned by the user
- * - Reactions on user's comments
- *
- * @param collectionID The ID of the collection.
- * @param collectionKey The decrypted collection key (base64 encoded).
- * @returns Filtered comments and reactions for the user's feed.
- */
-export const getAlbumFeed = async (
- collectionID: number,
- collectionKey: string,
-): Promise<UnifiedSocialDiff> => {
- const res = await fetch(
- await apiURL("/social/album-feed", {
- collectionID,
- sinceTime: 0,
- limit: 1000,
- }),
- { headers: await authenticatedRequestHeaders() },
- );
- ensureOk(res);
- return decryptSocialDiff(collectionKey, await res.json());
-};
-
/**
* Decrypt comments and reactions from the unified diff endpoint response.
*/
diff --git a/web/apps/albums/vendor/ente-new/photos/services/user.ts b/web/apps/albums/vendor/ente-new/photos/services/user.ts
deleted file mode 100644
index 48be703d0b..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/user.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-import { ensureSavedKeyAttributes } from "ente-accounts/services/user";
-import { boxSealOpenBytes, decryptBox } from "ente-base/crypto";
-import type { KeyPair } from "ente-base/crypto/types";
-import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
-import { apiURL } from "ente-base/origins";
-import { ensureMasterKeyFromSession } from "ente-base/session";
-import { nullToUndefined } from "ente-utils/transform";
-import { z } from "zod";
-
-/**
- * Return the public/private keypair of the currently logged in user.
- */
-export const ensureUserKeyPair = async (): Promise<KeyPair> => {
- const { encryptedSecretKey, secretKeyDecryptionNonce, publicKey } =
- ensureSavedKeyAttributes();
- const privateKey = await decryptBox(
- { encryptedData: encryptedSecretKey, nonce: secretKeyDecryptionNonce },
- await ensureMasterKeyFromSession(),
- );
- return { publicKey, privateKey };
-};
-
-/**
- * Fetch the public key from remote for the user (if any) who has registered
- * with remote with the given {@link email}.
- *
- * @returns the base64 encoded public key of the user with {@link email}.
- */
-export const getPublicKey = async (email: string) => {
- const res = await fetch(await apiURL("/users/public-key", { email }), {
- headers: await authenticatedRequestHeaders(),
- });
- ensureOk(res);
- return z.object({ publicKey: z.string() }).parse(await res.json())
- .publicKey;
-};
-
-/**
- * Fetch the two-factor status (whether or not it is enabled) from remote.
- */
-export const get2FAStatus = async () => {
- const res = await fetch(await apiURL("/users/two-factor/status"), {
- headers: await authenticatedRequestHeaders(),
- });
- ensureOk(res);
- return z.object({ status: z.boolean() }).parse(await res.json()).status;
-};
-
-/**
- * Disable two-factor authentication for the current user on remote.
- */
-export const disable2FA = async () =>
- ensureOk(
- await fetch(await apiURL("/users/two-factor/disable"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- }),
- );
-
-const DeleteChallengeResponse = z.object({
- // allowDelete indicates whether the user is allowed to delete their account
- // via app (some special-cased accounts might need to contact support).
- allowDelete: z.boolean(),
- // An encrypted challenge that the client needs to decrypt and provide in
- // the actual account deletion request.
- encryptedChallenge: z.string().nullish().transform(nullToUndefined),
-});
-
-/**
- * Initiate an account deletion by obtaining a delete challenge from remote.
- *
- * Account deletion is a three step process:
- *
- * 1. Client obtains a encrypted challenge from remote by using
- * {@link getAccountDeleteChallenge}.
- *
- * 2. Client asks the user to reverify their password to solve the challenge and
- * obtain the decrypted challenge ({@link decryptDeleteAccountChallenge}).
- *
- * 3. Client performs the account deletion using the solved challenge
- * ({@link deleteAccount}).
- */
-export const getAccountDeleteChallenge = async () => {
- const res = await fetch(await apiURL("/users/delete-challenge"), {
- headers: await authenticatedRequestHeaders(),
- });
- ensureOk(res);
- return DeleteChallengeResponse.parse(await res.json());
-};
-
-/**
- * Decrypt the {@link encryptedChallenge} sent by remote during the delete
- * account flow ({@link getAccountDeleteChallenge}), returning a value that can
- * then directly be passed to the actual delete account request
- * ({@link deleteAccount}).
- */
-export const decryptDeleteAccountChallenge = async (
- encryptedChallenge: string,
-) =>
- new TextDecoder().decode(
- await boxSealOpenBytes(encryptedChallenge, await ensureUserKeyPair()),
- );
-
-/**
- * Delete the logged in user's account on remote.
- *
- * @param challenge Decrypted value of the challenge previously obtained via
- * {@link getAccountDeleteChallenge}. The decryption algorithm is implemented in
- * {@link decryptDeleteAccountChallenge}.
- */
-export const deleteAccount = async (
- challenge: string,
- reason: string,
- feedback: string,
-) =>
- ensureOk(
- await fetch(await apiURL("/users/delete"), {
- method: "DELETE",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify({ challenge, reason, feedback }),
- }),
- );