Skip to content

armgit / ente

Public Imported from GitHub
0

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

fix(favorites):fixing-favoriting-shared-files

Aswin Asoka3e99c3ed1e2
diff --git a/web/packages/gallery/components/viewer/FileViewer.tsx b/web/packages/gallery/components/viewer/FileViewer.tsx
index 715fe76ac6..44fd882482 100644
--- a/web/packages/gallery/components/viewer/FileViewer.tsx
+++ b/web/packages/gallery/components/viewer/FileViewer.tsx
@@ -40,7 +40,11 @@ import {
type FileInfoProps,
} from "ente-gallery/components/FileInfo";
import type { Collection } from "ente-media/collection";
-import { fileFileName, ItemVisibility } from "ente-media/file-metadata";
+import {
+ fileFileName,
+ ItemVisibility,
+ metadataHash,
+} from "ente-media/file-metadata";
import { FileType } from "ente-media/file-type";
import type { EnteFile } from "ente-media/file.js";
import { isHEICExtension, needsJPEGConversion } from "ente-media/formats";
@@ -1207,22 +1211,26 @@ export const FileViewer: React.FC<FileViewerProps> = ({
: undefined;
}, [onSaveEditedImageCopy, handleClose]);
+ const userID = user?.id;
+ const haveUser = userID != undefined;
+ const canShowFavorite =
+ haveUser &&
+ !!favoriteFileIDs &&
+ !!pendingFavoriteUpdates &&
+ !!onToggleFavorite &&
+ !isInTrashSection &&
+ !isInHiddenSection;
+
const handleAnnotate = useCallback(
(file: EnteFile, itemData: ItemData): FileViewerAnnotatedFile => {
const fileID = file.id;
- const isOwnFile = file.ownerID == user?.id;
+ const isOwnFile = file.ownerID == userID;
+ const canFavoriteFile =
+ canShowFavorite && (isOwnFile || !!metadataHash(file.metadata));
const canModify =
isOwnFile && !isInTrashSection && !isInHiddenSection;
- const showFavorite =
- !!user &&
- !!favoriteFileIDs &&
- !!pendingFavoriteUpdates &&
- !!onToggleFavorite &&
- !isInTrashSection &&
- !isInHiddenSection;
-
const showArchive = canModify;
const showDelete =
@@ -1237,7 +1245,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({
const showDownload = (() => {
if (disableDownload) return undefined;
if (!onDownload) return undefined;
- if (user) {
+ if (haveUser) {
// Logged in users see the download option in the more menu.
return "menu";
} else {
@@ -1261,7 +1269,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({
const annotation: FileViewerFileAnnotation = {
fileID,
isOwnFile,
- showFavorite,
+ showFavorite: canFavoriteFile,
showDownload,
showDelete,
showArchive,
@@ -1274,14 +1282,13 @@ export const FileViewer: React.FC<FileViewerProps> = ({
return annotatedFile;
},
[
- user,
+ userID,
+ haveUser,
disableDownload,
isInIncomingSharedCollection,
isInTrashSection,
isInHiddenSection,
- favoriteFileIDs,
- pendingFavoriteUpdates,
- onToggleFavorite,
+ canShowFavorite,
onDownload,
handleEditImage,
handleConfirmDelete,
@@ -1306,8 +1313,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({
: undefined;
}, [onSelectPerson, handleClose]);
- const haveUser = !!user;
-
// Determine if social buttons (like, comment) should be shown.
const showSocialButtons = useMemo(() => {
if (!haveUser) return false;
diff --git a/web/packages/new/photos/components/gallery/reducer.ts b/web/packages/new/photos/components/gallery/reducer.ts
index c746a1bd52..ab1b09bb86 100644
--- a/web/packages/new/photos/components/gallery/reducer.ts
+++ b/web/packages/new/photos/components/gallery/reducer.ts
@@ -325,15 +325,18 @@ export interface GalleryState {
* user action) that have already been made to applied to remote, but whose
* effects on remote have not yet been synced back to our local DB.
*
- * Each entry is keyed by file ID and includes the favorite status (`true`
- * if it belongs to the user's favorites, false otherwise) which should be
- * used instead of what we get from our local DB.
+ * Each entry is keyed by file ID for owned files, and by hash/type for
+ * non-owned shared files. This keeps equivalent shared-file updates
+ * last-writer-wins before the next remote pull.
*
* The next time a remote pull completes, we clear this map since thereafter
* just deriving {@link favoriteFileIDs} from our local files would reflect
* the correct state on remote too.
*/
- unsyncedFavoriteUpdates: Map<number, UnsyncedFavoriteUpdate>;
+ unsyncedFavoriteUpdates: Map<
+ UnsyncedFavoriteUpdateKey,
+ UnsyncedFavoriteUpdate
+ >;
/**
* File (IDs) for which there is currently an in-flight archive / unarchive
* operation.
@@ -889,7 +892,11 @@ const galleryReducer: React.Reducer<GalleryState, GalleryAction> = (
action.file.ownerID == state.user!.id
? undefined
: favoriteFileHashAndTypeKey(action.file);
- unsyncedFavoriteUpdates.set(action.file.id, {
+ if (action.file.ownerID != state.user!.id && !fileHashAndTypeKey) {
+ return state;
+ }
+ const updateKey = fileHashAndTypeKey ?? action.file.id;
+ unsyncedFavoriteUpdates.set(updateKey, {
fileID: action.file.id,
fileHashAndTypeKey,
isFavorite: action.isFavorite,
@@ -1343,6 +1350,8 @@ interface UnsyncedFavoriteUpdate {
isFavorite: boolean;
}
+type UnsyncedFavoriteUpdateKey = number | string;
+
const favoriteFileHashAndTypeKey = (file: EnteFile) => {
const hash = metadataHash(file.metadata);
return hash ? `${hash}:${file.metadata.fileType}` : undefined;
diff --git a/web/packages/new/photos/services/collection.ts b/web/packages/new/photos/services/collection.ts
index 541dd55588..b370d9be21 100644
--- a/web/packages/new/photos/services/collection.ts
+++ b/web/packages/new/photos/services/collection.ts
@@ -776,6 +776,50 @@ const userOwnedEquivalentFilesByHashAndType = (
return equivalents;
};
+
+interface AddOrCopyToCollectionResult {
+ addedFiles: EnteFile[];
+}
+
+const newAddOrCopyToCollectionResult = (): AddOrCopyToCollectionResult => ({
+ addedFiles: [],
+});
+
+// Bridges favorite undo before the remote add/copy has been pulled into local DB.
+const pendingFavoriteFilesByHashAndType = new Map<string, EnteFile>();
+let pendingUserFavoritesCollection: Collection | undefined;
+
+const rememberPendingFavoriteFiles = (
+ sourceFiles: EnteFile[],
+ favoriteFiles: EnteFile[],
+ userID: number,
+) => {
+ const favoriteFilesByHashAndType = userOwnedEquivalentFilesByHashAndType(
+ favoriteFiles,
+ userID,
+ );
+
+ for (const sourceFile of sourceFiles) {
+ if (sourceFile.ownerID == userID) continue;
+
+ const key = hashAndTypeKey(sourceFile);
+ const favoriteFile = key
+ ? favoriteFilesByHashAndType.get(key)
+ : undefined;
+ if (key && favoriteFile) {
+ pendingFavoriteFilesByHashAndType.set(key, favoriteFile);
+ }
+ }
+};
+
+const forgetPendingFavoriteFiles = (files: EnteFile[], userID: number) => {
+ for (const file of files) {
+ if (file.ownerID == userID) continue;
+
+ const key = hashAndTypeKey(file);
+ if (key) pendingFavoriteFilesByHashAndType.delete(key);
+ }
+};
/**
*
* @param dstCollection
@@ -928,7 +972,8 @@ export const addOrCopyToCollection = async (
dstCollection: Collection,
files: EnteFile[],
) => {
- if (!files.length) return;
+ const result = newAddOrCopyToCollectionResult();
+ if (!files.length) return result;
/**
* The user who is adding the files to the dstCollection must be
@@ -968,7 +1013,7 @@ export const addOrCopyToCollection = async (
// If all the files, already exists then,
// we have nothing pending so returning.
- if (!filesMissingFromDestination.length) return;
+ if (!filesMissingFromDestination.length) return result;
/**
* Files which are owned by the current user and not owned
@@ -990,11 +1035,12 @@ export const addOrCopyToCollection = async (
if (ownedFiles.length) {
await addToCollection(dstCollection, ownedFiles);
ownedFiles.forEach((file) => destinationFileIDs.add(file.id));
+ result.addedFiles.push(...ownedFiles);
}
// If there are no files which are owned but by others
// then skipping the rest of the process.
- if (!otherOwnedFiles.length) return;
+ if (!otherOwnedFiles.length) return result;
/**
* Say if user A uploaded a file X to a shared album and you
@@ -1064,9 +1110,10 @@ export const addOrCopyToCollection = async (
if (reusableOwnedFiles.length) {
await addToCollection(dstCollection, reusableOwnedFiles);
reusableOwnedFiles.forEach((file) => destinationFileIDs.add(file.id));
+ result.addedFiles.push(...reusableOwnedFiles);
}
- if (!filesToCopy.length) return;
+ if (!filesToCopy.length) return result;
/**
* To directly upload to a collection, the currentUser must be the
@@ -1098,8 +1145,13 @@ export const addOrCopyToCollection = async (
filesToAddAfterCopy.forEach((file) =>
destinationFileIDs.add(file.id),
);
+ result.addedFiles.push(...filesToAddAfterCopy);
}
+ } else {
+ result.addedFiles.push(...copiedFiles);
}
+
+ return result;
};
/**
@@ -1743,19 +1795,25 @@ export const createUncategorizedCollection = () =>
* Reads local state but does not modify it. The effects are on remote.
*/
const savedOrCreateUserFavoritesCollection = async () =>
- (await savedUserFavoritesCollection()) ?? createFavoritesCollection();
+ (await savedUserFavoritesCollection()) ??
+ (pendingUserFavoritesCollection = await createFavoritesCollection());
/**
- * Return the user's own favorites collection, if any, present in the local
- * database.
+ * Return the user's own favorites collection if present in the local database,
+ * or one created during this session before the next remote pull.
*/
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,
+ return (
+ collections.find(
+ (collection) =>
+ // See: [Note: User and shared favorites]
+ collection.type == "favorites" && collection.owner.id == userID,
+ ) ??
+ (pendingUserFavoritesCollection?.owner.id == userID
+ ? pendingUserFavoritesCollection
+ : undefined)
);
};
@@ -1767,10 +1825,24 @@ export const savedUserFavoritesCollection = async () => {
*
* Reads local state but does not modify it. The effects are on remote.
*/
-export const addToFavoritesCollection = async (files: EnteFile[]) =>
- addOrCopyToCollection(await savedOrCreateUserFavoritesCollection(), files);
+export const addToFavoritesCollection = async (files: EnteFile[]) => {
+ const userID = ensureLocalUser().id;
+ const hashlessSharedFile = files.find(
+ (file) => file.ownerID != userID && !hashAndTypeKey(file),
+ );
+ if (hashlessSharedFile) {
+ throw new Error("Cannot favorite shared files without metadata hash");
+ }
+
+ const result = await addOrCopyToCollection(
+ await savedOrCreateUserFavoritesCollection(),
+ files,
+ );
+ rememberPendingFavoriteFiles(files, result.addedFiles, userID);
+};
export const removeFromFavoritesCollection = async (files: EnteFile[]) => {
+ const userID = ensureLocalUser().id;
const favoritesCollection = await savedUserFavoritesCollection();
if (!favoritesCollection) {
throw new Error("Favorites collection does not exist");
@@ -1786,6 +1858,7 @@ export const removeFromFavoritesCollection = async (files: EnteFile[]) => {
favoritesCollection.id,
uniqueFilesByID(resolvedFiles),
);
+ forgetPendingFavoriteFiles(files, userID);
};
const resolveFavoritesFilesForRemoval = async (
@@ -1800,18 +1873,22 @@ const resolveFavoritesFilesForRemoval = async (
userID,
);
- return files.flatMap((file) => {
+ return files.map((file) => {
if (
file.ownerID != userID &&
file.collectionID != favoritesCollection.id
) {
const key = hashAndTypeKey(file);
const favoriteFile = key
- ? favoriteFilesByHashAndType.get(key)
+ ? (favoriteFilesByHashAndType.get(key) ??
+ pendingFavoriteFilesByHashAndType.get(key))
: undefined;
- return favoriteFile ? [favoriteFile] : [];
+ if (!favoriteFile) {
+ throw new Error("Could not resolve favorite file for removal");
+ }
+ return favoriteFile;
}
- return [file];
+ return file;
});
};