Skip to content

armgit / ente

Public Imported from GitHub
0

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

Use direct state updates instead of refetching for comments and reactions

Anand Baburajanc50a439e60c1
diff --git a/web/packages/gallery/components/viewer/CommentsSidebar.tsx b/web/packages/gallery/components/viewer/CommentsSidebar.tsx
index c8cddf8224..c7d44fcfe9 100644
--- a/web/packages/gallery/components/viewer/CommentsSidebar.tsx
+++ b/web/packages/gallery/components/viewer/CommentsSidebar.tsx
@@ -26,8 +26,8 @@ import {
import {
addCommentReaction,
deleteReaction,
- getCommentReactions,
} from "ente-new/photos/services/reaction";
+import { type UnifiedReaction } from "ente-new/photos/services/social";
import { t } from "i18next";
import React, {
useCallback,
@@ -331,15 +331,33 @@ export interface CommentsSidebarProps extends ModalVisibilityProps {
*/
currentUserID?: number;
/**
- * Pre-fetched comments by collection ID. If provided, the sidebar will use
- * these instead of making its own API requests.
+ * Pre-fetched comments by collection ID.
*/
prefetchedComments?: Map<number, Comment[]>;
/**
- * Called when comments are modified (added or deleted). The parent should
- * refresh its comments data to stay in sync.
+ * Pre-fetched reactions by collection ID (includes both file and comment reactions).
*/
- onCommentsUpdate?: () => void;
+ prefetchedReactions?: Map<number, UnifiedReaction[]>;
+ /**
+ * Called when a comment is successfully added. The parent should update its
+ * comments state to include this new comment.
+ */
+ onCommentAdded?: (comment: Comment) => void;
+ /**
+ * Called when a comment is successfully deleted. The parent should update its
+ * comments state to mark this comment as deleted.
+ */
+ onCommentDeleted?: (collectionID: number, commentID: string) => void;
+ /**
+ * Called when a comment reaction is added. The parent should update its
+ * reactions state to include this new reaction.
+ */
+ onCommentReactionAdded?: (reaction: UnifiedReaction) => void;
+ /**
+ * Called when a comment reaction is deleted. The parent should update its
+ * reactions state to remove this reaction.
+ */
+ onCommentReactionDeleted?: (collectionID: number, reactionID: string) => void;
}
/**
@@ -359,7 +377,11 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
collectionSummaries,
currentUserID,
prefetchedComments,
- onCommentsUpdate,
+ prefetchedReactions,
+ onCommentAdded,
+ onCommentDeleted,
+ onCommentReactionAdded,
+ onCommentReactionDeleted,
}) => {
const [commentText, setCommentText] = useState("");
const [replyingTo, setReplyingTo] = useState<Comment | null>(null);
@@ -401,6 +423,11 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
new Map(),
);
+ // All reactions by collection: collectionID -> reactions array
+ const [reactionsByCollection, setReactionsByCollection] = useState<
+ Map<number, UnifiedReaction[]>
+ >(new Map());
+
// Focus input when replying to a comment
useEffect(() => {
if (replyingTo && inputRef.current) {
@@ -458,29 +485,26 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
sortedCollectionsInfo,
]);
- // Load comments from prefetched data and fetch collection info for user emails.
+ // Load comments and reactions from prefetched data.
const loadComments = useCallback(async () => {
if (!file || !open || !prefetchedComments) return;
setLoading(true);
- const newCommentsByCollection = new Map<number, Comment[]>();
const newUserIDToEmail = new Map<number, string>();
try {
- // Copy prefetched comments
- for (const [collectionID, comments] of prefetchedComments) {
- newCommentsByCollection.set(collectionID, comments);
- }
-
- // Fetch collection info for user emails
+ // Determine which collections to process
const collectionIDsToFetch =
hasCollectionContext && activeCollectionID
? [activeCollectionID]
: fileCollectionIDs;
+ // Fetch collection info for user emails (lightweight call)
for (const collectionID of collectionIDsToFetch) {
try {
const collection = await getCollectionByID(collectionID);
+
+ // Build user ID to email mapping
if (collection.owner.email) {
newUserIDToEmail.set(
collection.owner.id,
@@ -497,16 +521,19 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
}
}
+ // Use prefetched data
+ setCommentsByCollection(prefetchedComments);
+ setReactionsByCollection(prefetchedReactions ?? new Map());
+
// Set comments for the currently selected collection
if (hasCollectionContext && activeCollectionID) {
- const activeComments =
- newCommentsByCollection.get(activeCollectionID) ?? [];
+ const activeComments = prefetchedComments.get(activeCollectionID) ?? [];
setComments(activeComments);
} else {
// For gallery view, find collection with most comments and set initial selection
let maxCount = -1;
let bestCollectionID: number | undefined;
- for (const [collectionID, collectionComments] of newCommentsByCollection) {
+ for (const [collectionID, collectionComments] of prefetchedComments) {
const count = collectionComments.filter((c) => !c.isDeleted).length;
if (count > maxCount) {
maxCount = count;
@@ -515,11 +542,10 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
}
if (bestCollectionID !== undefined) {
setSelectedCollectionID(bestCollectionID);
- setComments(newCommentsByCollection.get(bestCollectionID) ?? []);
+ setComments(prefetchedComments.get(bestCollectionID) ?? []);
}
}
- setCommentsByCollection(newCommentsByCollection);
setUserIDToEmail(newUserIDToEmail);
} catch (e) {
log.error("Failed to load comments", e);
@@ -530,6 +556,7 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
file,
open,
prefetchedComments,
+ prefetchedReactions,
hasCollectionContext,
activeCollectionID,
fileCollectionIDs,
@@ -620,54 +647,32 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
};
}, [open, collectionsInfo]);
- // Fetch liked state for comments
+ // Build liked comments map from reactions when selected collection changes
useEffect(() => {
- if (!open || comments.length === 0 || !selectedCollectionInfo) {
+ if (!open || !selectedCollectionInfo) {
+ setLikedComments(new Map());
return;
}
- let didCancel = false;
+ const reactions = reactionsByCollection.get(selectedCollectionInfo.id);
+ if (!reactions) {
+ setLikedComments(new Map());
+ return;
+ }
- const fetchLikedComments = async () => {
- const newLikedComments = new Map<string, string>();
- try {
- const collection = await getCollectionByID(
- selectedCollectionInfo.id,
- );
- for (const comment of comments) {
- if (comment.isDeleted) continue;
- try {
- const reactions = await getCommentReactions(
- selectedCollectionInfo.id,
- comment.id,
- collection.key,
- );
- const userReaction = reactions.find(
- (r) =>
- r.reactionType === "green_heart" &&
- r.userID === currentUserID,
- );
- if (userReaction && !didCancel) {
- newLikedComments.set(comment.id, userReaction.id);
- }
- } catch {
- // Skip comments that fail to fetch reactions
- }
- }
- if (!didCancel) {
- setLikedComments(newLikedComments);
- }
- } catch (e) {
- log.warn("Failed to fetch comment reactions", e);
+ // Find comment reactions that are likes from the current user
+ const newLikedComments = new Map<string, string>();
+ for (const reaction of reactions) {
+ if (
+ reaction.commentID &&
+ reaction.reactionType === "green_heart" &&
+ reaction.userID === currentUserID
+ ) {
+ newLikedComments.set(reaction.commentID, reaction.id);
}
- };
-
- void fetchLikedComments();
-
- return () => {
- didCancel = true;
- };
- }, [open, comments, selectedCollectionInfo, currentUserID]);
+ }
+ setLikedComments(newLikedComments);
+ }, [open, selectedCollectionInfo, reactionsByCollection, currentUserID]);
// Check if this is a public album (has ?t=... in URL)
const isPublicAlbum =
@@ -711,8 +716,8 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
parentCommentID: replyingTo?.id,
isDeleted: false,
userID: currentUserID ?? 0,
- createdAt: Date.now(),
- updatedAt: Date.now(),
+ createdAt: Date.now() * 1000, // Microseconds to match server format
+ updatedAt: Date.now() * 1000,
};
setComments((prev) => [...prev, newComment]);
setCommentsByCollection((prev) => {
@@ -725,8 +730,8 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
setCommentText("");
setReplyingTo(null);
- // Notify parent to refresh comments
- onCommentsUpdate?.();
+ // Notify parent to update its comments state
+ onCommentAdded?.(newComment);
// Scroll to bottom after adding comment
setTimeout(() => {
@@ -751,8 +756,8 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
parentCommentID: replyingTo?.id,
isDeleted: false,
userID: currentUserID ?? 0,
- createdAt: Date.now(),
- updatedAt: Date.now(),
+ createdAt: Date.now() * 1000, // Microseconds to match server format
+ updatedAt: Date.now() * 1000,
};
setComments((prev) => [...prev, newComment]);
setCommentText("");
@@ -833,6 +838,21 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
next.delete(targetComment.id);
return next;
});
+ // Update reactionsByCollection
+ setReactionsByCollection((prev) => {
+ const next = new Map(prev);
+ const reactions = next.get(selectedCollectionInfo.id) ?? [];
+ next.set(
+ selectedCollectionInfo.id,
+ reactions.filter((r) => r.id !== existingReactionID),
+ );
+ return next;
+ });
+ // Notify parent to update its reactions state
+ onCommentReactionDeleted?.(
+ selectedCollectionInfo.id,
+ existingReactionID,
+ );
} else {
// Like - add a reaction
const reactionID = await addCommentReaction(
@@ -841,11 +861,33 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
"green_heart",
collection.key,
);
+ const newReaction: UnifiedReaction = {
+ id: reactionID,
+ collectionID: selectedCollectionInfo.id,
+ commentID: targetComment.id,
+ reactionType: "green_heart",
+ userID: currentUserID ?? 0,
+ isDeleted: false,
+ createdAt: Date.now() * 1000,
+ updatedAt: Date.now() * 1000,
+ };
setLikedComments((prev) => {
const next = new Map(prev);
next.set(targetComment.id, reactionID);
return next;
});
+ // Update reactionsByCollection
+ setReactionsByCollection((prev) => {
+ const next = new Map(prev);
+ const reactions = next.get(selectedCollectionInfo.id) ?? [];
+ next.set(selectedCollectionInfo.id, [
+ ...reactions,
+ newReaction,
+ ]);
+ return next;
+ });
+ // Notify parent to update its reactions state
+ onCommentReactionAdded?.(newReaction);
}
} catch (e) {
log.error("Failed to toggle comment like", e);
@@ -881,8 +923,11 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
return next;
});
- // Notify parent to refresh comments
- onCommentsUpdate?.();
+ // Notify parent to update its comments state
+ onCommentDeleted?.(
+ targetComment.collectionID,
+ targetComment.id,
+ );
} catch (e) {
log.error("Failed to delete comment", e);
}
diff --git a/web/packages/gallery/components/viewer/FileViewer.tsx b/web/packages/gallery/components/viewer/FileViewer.tsx
index f522996ce2..9292cd2327 100644
--- a/web/packages/gallery/components/viewer/FileViewer.tsx
+++ b/web/packages/gallery/components/viewer/FileViewer.tsx
@@ -48,15 +48,12 @@ import {
} from "ente-new/photos/components/ImageEditorOverlay";
import { getCollectionByID } from "ente-new/photos/services/collection";
import type { CollectionSummaries } from "ente-new/photos/services/collection-summary";
+import { type Comment } from "ente-new/photos/services/comment";
+import { addReaction, deleteReaction } from "ente-new/photos/services/reaction";
import {
- getFileComments,
- type Comment,
-} from "ente-new/photos/services/comment";
-import {
- addReaction,
- deleteReaction,
- getFileReactions,
-} from "ente-new/photos/services/reaction";
+ getUnifiedSocialDiff,
+ type UnifiedReaction,
+} from "ente-new/photos/services/social";
import { t } from "i18next";
import React, {
useCallback,
@@ -403,17 +400,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({
const [isFullscreen, setIsFullscreen] = useState(false);
- // Map of file ID to array of reactions (collectionId + reactionId) for the current user.
- // For gallery view, we track reactions across all collections.
- // For collection view, we only track the reaction in that collection.
- interface FileReaction {
- collectionId: number;
- reactionId: string;
- }
- const [fileReactions, setFileReactions] = useState<
- Map<number, FileReaction[]>
- >(new Map());
-
// Map of file ID to map of collection ID to array of comments.
// For gallery view, we fetch comments from all collections.
// For collection view, we only fetch comments from that collection.
@@ -421,12 +407,51 @@ export const FileViewer: React.FC<FileViewerProps> = ({
Map<number, Map<number, Comment[]>>
>(new Map());
+ // Map of file ID to map of collection ID to array of all reactions.
+ // Includes both file reactions and comment reactions.
+ const [allReactions, setAllReactions] = useState<
+ Map<number, Map<number, UnifiedReaction[]>>
+ >(new Map());
+
// Ref for fileComments to use in callbacks
const fileCommentsRef = useRef(fileComments);
useEffect(() => {
fileCommentsRef.current = fileComments;
}, [fileComments]);
+ // Ref for allReactions to use in callbacks
+ const allReactionsRef = useRef(allReactions);
+ useEffect(() => {
+ allReactionsRef.current = allReactions;
+ }, [allReactions]);
+
+ // Helper to get current user's file reactions from allReactions
+ const getUserFileReactions = useCallback(
+ (fileId: number): { collectionId: number; reactionId: string }[] => {
+ const fileReactionsMap = allReactionsRef.current.get(fileId);
+ if (!fileReactionsMap) return [];
+
+ const userReactions: { collectionId: number; reactionId: string }[] = [];
+ for (const [collectionId, reactions] of fileReactionsMap) {
+ const userFileReaction = reactions.find(
+ (r) =>
+ !r.commentID &&
+ r.fileID === fileId &&
+ r.reactionType === "green_heart" &&
+ r.userID === user?.id,
+ );
+ if (userFileReaction) {
+ userReactions.push({
+ collectionId,
+ reactionId: userFileReaction.id,
+ });
+ }
+ }
+ return userReactions;
+ },
+ [user?.id],
+ );
+
// If `true`, then we need to trigger a pull from remote when we close.
const [, setNeedsRemotePull] = useState(false);
@@ -472,55 +497,99 @@ export const FileViewer: React.FC<FileViewerProps> = ({
const handleCommentsClose = useCallback(() => setOpenComments(false), []);
- // Re-fetch comments for the current file after a comment is added or deleted
- const handleCommentsUpdate = useCallback(() => {
- const fileID = activeAnnotatedFile?.file.id;
- if (!fileID) return;
-
- const isGalleryView = !activeCollectionID || activeCollectionID === 0;
+ // Handle a new comment being added
+ const handleCommentAdded = useCallback(
+ (comment: Comment) => {
+ const fileID = comment.fileID;
+ if (!fileID) return;
+
+ setFileComments((prev) => {
+ const next = new Map(prev);
+ const fileCommentsMap = new Map(prev.get(fileID) ?? new Map());
+ const collectionComments =
+ fileCommentsMap.get(comment.collectionID) ?? [];
+ fileCommentsMap.set(comment.collectionID, [
+ ...collectionComments,
+ comment,
+ ]);
+ next.set(fileID, fileCommentsMap);
+ return next;
+ });
+ },
+ [],
+ );
- void (async () => {
- try {
- const commentsMap = new Map<number, Comment[]>();
+ // Handle a comment being deleted
+ const handleCommentDeleted = useCallback(
+ (collectionID: number, commentID: string) => {
+ const fileID = activeAnnotatedFile?.file.id;
+ if (!fileID) return;
+
+ setFileComments((prev) => {
+ const next = new Map(prev);
+ const fileCommentsMap = prev.get(fileID);
+ if (fileCommentsMap) {
+ const updatedMap = new Map(fileCommentsMap);
+ const collectionComments = updatedMap.get(collectionID) ?? [];
+ updatedMap.set(
+ collectionID,
+ collectionComments.map((c) =>
+ c.id === commentID ? { ...c, isDeleted: true } : c,
+ ),
+ );
+ next.set(fileID, updatedMap);
+ }
+ return next;
+ });
+ },
+ [activeAnnotatedFile],
+ );
- if (isGalleryView) {
- const collectionIDs =
- fileNormalCollectionIDs?.get(fileID) ?? [];
+ // Handle a comment reaction being added
+ const handleCommentReactionAdded = useCallback(
+ (reaction: UnifiedReaction) => {
+ const fileID = activeAnnotatedFile?.file.id;
+ if (!fileID) return;
+
+ setAllReactions((prev) => {
+ const next = new Map(prev);
+ const fileReactionsMap = new Map(prev.get(fileID) ?? new Map());
+ const collectionReactions =
+ fileReactionsMap.get(reaction.collectionID) ?? [];
+ fileReactionsMap.set(reaction.collectionID, [
+ ...collectionReactions,
+ reaction,
+ ]);
+ next.set(fileID, fileReactionsMap);
+ return next;
+ });
+ },
+ [activeAnnotatedFile],
+ );
- for (const collectionId of collectionIDs) {
- try {
- const collection =
- await getCollectionByID(collectionId);
- const comments = await getFileComments(
- collectionId,
- fileID,
- collection.key,
- );
- commentsMap.set(collectionId, comments);
- } catch {
- // Skip collections that fail to fetch
- }
- }
- } else {
- const collection = await getCollectionByID(activeCollectionID);
- const comments = await getFileComments(
- activeCollectionID,
- fileID,
- collection.key,
+ // Handle a comment reaction being deleted
+ const handleCommentReactionDeleted = useCallback(
+ (collectionID: number, reactionID: string) => {
+ const fileID = activeAnnotatedFile?.file.id;
+ if (!fileID) return;
+
+ setAllReactions((prev) => {
+ const next = new Map(prev);
+ const fileReactionsMap = prev.get(fileID);
+ if (fileReactionsMap) {
+ const updatedMap = new Map(fileReactionsMap);
+ const collectionReactions = updatedMap.get(collectionID) ?? [];
+ updatedMap.set(
+ collectionID,
+ collectionReactions.filter((r) => r.id !== reactionID),
);
- commentsMap.set(activeCollectionID, comments);
+ next.set(fileID, updatedMap);
}
-
- setFileComments((prev) => {
- const next = new Map(prev);
- next.set(fileID, commentsMap);
- return next;
- });
- } catch (e) {
- log.error("Failed to refresh comments", e);
- }
- })();
- }, [activeAnnotatedFile, activeCollectionID, fileNormalCollectionIDs]);
+ return next;
+ });
+ },
+ [activeAnnotatedFile],
+ );
const handleViewLikes = useCallback(() => setOpenLikes(true), []);
@@ -531,9 +600,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({
const activeAnnotatedFileRef = useRef(activeAnnotatedFile);
activeAnnotatedFileRef.current = activeAnnotatedFile;
- const fileReactionsRef = useRef(fileReactions);
- fileReactionsRef.current = fileReactions;
-
// Called when the like button (heart) is clicked.
// - If public album (has ?t=): show PublicLikeModal
// - If gallery view: show album selector (like) OR unlike selector/direct delete
@@ -555,7 +621,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({
if (!file) return;
const fileId = file.id;
- const reactions = fileReactionsRef.current.get(fileId) ?? [];
+ const reactions = getUserFileReactions(fileId);
const isGalleryView = !activeCollectionID || activeCollectionID === 0;
if (isGalleryView) {
@@ -578,11 +644,24 @@ export const FileViewer: React.FC<FileViewerProps> = ({
collection.key,
);
log.info(`Added reaction: ${reactionId}`);
- setFileReactions((prev) => {
+ setAllReactions((prev) => {
const next = new Map(prev);
- next.set(fileId, [
- { collectionId, reactionId },
+ const fileReactionsMap = new Map(prev.get(fileId) ?? new Map());
+ const collectionReactions = fileReactionsMap.get(collectionId) ?? [];
+ fileReactionsMap.set(collectionId, [
+ ...collectionReactions,
+ {
+ id: reactionId,
+ collectionID: collectionId,
+ fileID: fileId,
+ reactionType: "green_heart",
+ userID: user?.id ?? 0,
+ isDeleted: false,
+ createdAt: Date.now() * 1000,
+ updatedAt: Date.now() * 1000,
+ },
]);
+ next.set(fileId, fileReactionsMap);
return next;
});
} catch (e) {
@@ -597,15 +676,29 @@ export const FileViewer: React.FC<FileViewerProps> = ({
// Liked in one or more collections - unlike from all
void (async () => {
try {
+ const deletedReactionIds = new Set<string>();
for (const reaction of reactions) {
await deleteReaction(reaction.reactionId);
+ deletedReactionIds.add(reaction.reactionId);
log.info(
`Deleted reaction: ${reaction.reactionId}`,
);
}
- setFileReactions((prev) => {
+ setAllReactions((prev) => {
const next = new Map(prev);
- next.delete(fileId);
+ const fileReactionsMap = prev.get(fileId);
+ if (fileReactionsMap) {
+ const updatedMap = new Map(fileReactionsMap);
+ for (const [collectionId, collectionReactions] of updatedMap) {
+ updatedMap.set(
+ collectionId,
+ collectionReactions.filter(
+ (r) => !deletedReactionIds.has(r.id),
+ ),
+ );
+ }
+ next.set(fileId, updatedMap);
+ }
return next;
});
} catch (e) {
@@ -627,17 +720,19 @@ export const FileViewer: React.FC<FileViewerProps> = ({
log.info(
`Deleted reaction: ${existingReaction.reactionId}`,
);
- setFileReactions((prev) => {
+ setAllReactions((prev) => {
const next = new Map(prev);
- const updated = (prev.get(fileId) ?? []).filter(
- (r) =>
- r.reactionId !==
- existingReaction.reactionId,
- );
- if (updated.length > 0) {
- next.set(fileId, updated);
- } else {
- next.delete(fileId);
+ const fileReactionsMap = prev.get(fileId);
+ if (fileReactionsMap) {
+ const updatedMap = new Map(fileReactionsMap);
+ const collectionReactions = updatedMap.get(activeCollectionID) ?? [];
+ updatedMap.set(
+ activeCollectionID,
+ collectionReactions.filter(
+ (r) => r.id !== existingReaction.reactionId,
+ ),
+ );
+ next.set(fileId, updatedMap);
}
return next;
});
@@ -658,16 +753,24 @@ export const FileViewer: React.FC<FileViewerProps> = ({
collection.key,
);
log.info(`Added reaction: ${reactionId}`);
- setFileReactions((prev) => {
+ setAllReactions((prev) => {
const next = new Map(prev);
- const existing = prev.get(fileId) ?? [];
- next.set(fileId, [
- ...existing,
+ const fileReactionsMap = new Map(prev.get(fileId) ?? new Map());
+ const collectionReactions = fileReactionsMap.get(activeCollectionID) ?? [];
+ fileReactionsMap.set(activeCollectionID, [
+ ...collectionReactions,
{
- collectionId: activeCollectionID,
- reactionId,
+ id: reactionId,
+ collectionID: activeCollectionID,
+ fileID: fileId,
+ reactionType: "green_heart",
+ userID: user?.id ?? 0,
+ isDeleted: false,
+ createdAt: Date.now() * 1000,
+ updatedAt: Date.now() * 1000,
},
]);
+ next.set(fileId, fileReactionsMap);
return next;
});
} catch (e) {
@@ -676,7 +779,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({
})();
}
}
- }, [activeCollectionID, fileNormalCollectionIDs]);
+ }, [activeCollectionID, fileNormalCollectionIDs, getUserFileReactions, user?.id]);
const handleLikeAlbumSelectorClose = useCallback(
() => setOpenLikeAlbumSelector(false),
@@ -692,7 +795,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({
if (isCurrentlyLiked) {
// Unlike - delete the reaction
- const reactions = fileReactionsRef.current.get(fileId) ?? [];
+ const reactions = getUserFileReactions(fileId);
const reactionToDelete = reactions.find(
(r) => r.collectionId === albumId,
);
@@ -704,17 +807,19 @@ export const FileViewer: React.FC<FileViewerProps> = ({
log.info(
`Deleted reaction: ${reactionToDelete.reactionId}`,
);
- setFileReactions((prev) => {
+ setAllReactions((prev) => {
const next = new Map(prev);
- const updated = (prev.get(fileId) ?? []).filter(
- (r) =>
- r.reactionId !==
- reactionToDelete.reactionId,
- );
- if (updated.length > 0) {
- next.set(fileId, updated);
- } else {
- next.delete(fileId);
+ const fileReactionsMap = prev.get(fileId);
+ if (fileReactionsMap) {
+ const updatedMap = new Map(fileReactionsMap);
+ const collectionReactions = updatedMap.get(albumId) ?? [];
+ updatedMap.set(
+ albumId,
+ collectionReactions.filter(
+ (r) => r.id !== reactionToDelete.reactionId,
+ ),
+ );
+ next.set(fileId, updatedMap);
}
return next;
});
@@ -735,13 +840,24 @@ export const FileViewer: React.FC<FileViewerProps> = ({
collection.key,
);
log.info(`Added reaction: ${reactionId}`);
- setFileReactions((prev) => {
+ setAllReactions((prev) => {
const next = new Map(prev);
- const existing = prev.get(fileId) ?? [];
- next.set(fileId, [
- ...existing,
- { collectionId: albumId, reactionId },
+ const fileReactionsMap = new Map(prev.get(fileId) ?? new Map());
+ const collectionReactions = fileReactionsMap.get(albumId) ?? [];
+ fileReactionsMap.set(albumId, [
+ ...collectionReactions,
+ {
+ id: reactionId,
+ collectionID: albumId,
+ fileID: fileId,
+ reactionType: "green_heart",
+ userID: user?.id ?? 0,
+ isDeleted: false,
+ createdAt: Date.now() * 1000,
+ updatedAt: Date.now() * 1000,
+ },
]);
+ next.set(fileId, fileReactionsMap);
return next;
});
} catch (e) {
@@ -751,7 +867,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({
}
// Don't close - user might want to toggle more albums
},
- [],
+ [getUserFileReactions, user?.id],
);
const handleLikeAll = useCallback(() => {
@@ -760,7 +876,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({
const fileId = file.id;
const collectionIDs = fileNormalCollectionIDs?.get(fileId) ?? [];
- const existingReactions = fileReactionsRef.current.get(fileId) ?? [];
+ const existingReactions = getUserFileReactions(fileId);
const likedCollectionIDs = new Set(
existingReactions.map((r) => r.collectionId),
);
@@ -787,10 +903,26 @@ export const FileViewer: React.FC<FileViewerProps> = ({
log.info(`Added reaction: ${reactionId}`);
newReactions.push({ collectionId, reactionId });
}
- setFileReactions((prev) => {
+ setAllReactions((prev) => {
const next = new Map(prev);
- const existing = prev.get(fileId) ?? [];
- next.set(fileId, [...existing, ...newReactions]);
+ const fileReactionsMap = new Map(prev.get(fileId) ?? new Map());
+ for (const { collectionId, reactionId } of newReactions) {
+ const collectionReactions = fileReactionsMap.get(collectionId) ?? [];
+ fileReactionsMap.set(collectionId, [
+ ...collectionReactions,
+ {
+ id: reactionId,
+ collectionID: collectionId,
+ fileID: fileId,
+ reactionType: "green_heart",
+ userID: user?.id ?? 0,
+ isDeleted: false,
+ createdAt: Date.now() * 1000,
+ updatedAt: Date.now() * 1000,
+ },
+ ]);
+ }
+ next.set(fileId, fileReactionsMap);
return next;
});
} catch (e) {
@@ -798,7 +930,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({
}
})();
setOpenLikeAlbumSelector(false);
- }, [fileNormalCollectionIDs]);
+ }, [fileNormalCollectionIDs, getUserFileReactions, user?.id]);
const handlePublicLikeModalClose = useCallback(
() => setOpenPublicLikeModal(false),
@@ -1042,16 +1174,30 @@ export const FileViewer: React.FC<FileViewerProps> = ({
name: collectionNameByID?.get(id) ?? `Album ${id}`,
}));
- // Get the set of liked album IDs
- const reactions = fileReactions.get(file.id) ?? [];
- const likedAlbumIDs = new Set(reactions.map((r) => r.collectionId));
+ // Get the set of liked album IDs from allReactions
+ const fileReactionsMap = allReactions.get(file.id);
+ const likedAlbumIDs = new Set<number>();
+ if (fileReactionsMap) {
+ for (const [collectionId, reactions] of fileReactionsMap) {
+ const hasUserLike = reactions.some(
+ (r) =>
+ !r.commentID &&
+ r.reactionType === "green_heart" &&
+ r.userID === user?.id,
+ );
+ if (hasUserLike) {
+ likedAlbumIDs.add(collectionId);
+ }
+ }
+ }
return { allAlbumsForFile, likedAlbumIDs };
}, [
activeAnnotatedFile,
collectionNameByID,
fileNormalCollectionIDs,
- fileReactions,
+ allReactions,
+ user?.id,
]);
const getFiles = useCallback(() => files, [files]);
@@ -1087,10 +1233,22 @@ export const FileViewer: React.FC<FileViewerProps> = ({
const isLiked = useCallback(
({ file }: FileViewerAnnotatedFile) => {
- const reactions = fileReactions.get(file.id);
- return reactions !== undefined && reactions.length > 0;
+ const fileReactionsMap = allReactions.get(file.id);
+ if (!fileReactionsMap) return false;
+
+ // Check if user has liked this file in any collection
+ for (const reactions of fileReactionsMap.values()) {
+ const hasUserLike = reactions.some(
+ (r) =>
+ !r.commentID &&
+ r.reactionType === "green_heart" &&
+ r.userID === user?.id,
+ );
+ if (hasUserLike) return true;
+ }
+ return false;
},
- [fileReactions],
+ [allReactions, user?.id],
);
const getCommentCount = useCallback(
@@ -1348,148 +1506,43 @@ export const FileViewer: React.FC<FileViewerProps> = ({
}
}, [favoriteFileIDs, pendingFavoriteUpdates, files, open]);
- // Refresh like button when fileReactions changes.
+ // Refresh like button when allReactions changes.
useEffect(() => {
if (open && files.length) {
psRef.current?.refreshCurrentSlideLikeButtonIfNeeded();
}
- }, [fileReactions, files, open]);
+ }, [allReactions, files, open]);
- // Fetch reactions for the current file when it changes.
- // Track by file ID to avoid re-fetching when activeAnnotatedFile object changes identity.
+ // Fetch comments and reactions for the current file using unified endpoint.
const activeFileID = activeAnnotatedFile?.file.id;
useEffect(() => {
if (!open || !activeFileID) return;
const isGalleryView = !activeCollectionID || activeCollectionID === 0;
- void (async () => {
- try {
- if (isGalleryView) {
- // Gallery view: check ALL collections the file belongs to
- const collectionIDs =
- fileNormalCollectionIDs?.get(activeFileID) ?? [];
- const foundReactions: FileReaction[] = [];
-
- for (const collectionId of collectionIDs) {
- try {
- const collection =
- await getCollectionByID(collectionId);
- const reactions = await getFileReactions(
- collectionId,
- activeFileID,
- collection.key,
- );
- const userReaction = reactions.find(
- (r) =>
- r.reactionType === "green_heart" &&
- r.userID === user?.id,
- );
- if (userReaction) {
- foundReactions.push({
- collectionId,
- reactionId: userReaction.id,
- });
- }
- } catch {
- // Skip collections that fail to fetch
- }
- }
-
- setFileReactions((prev) => {
- const next = new Map(prev);
- if (foundReactions.length > 0) {
- next.set(activeFileID, foundReactions);
- } else {
- next.delete(activeFileID);
- }
- return next;
- });
- } else {
- // Collection view: check only the active collection
- const collection =
- await getCollectionByID(activeCollectionID);
- const reactions = await getFileReactions(
- activeCollectionID,
- activeFileID,
- collection.key,
- );
- const userReaction = reactions.find(
- (r) =>
- r.reactionType === "green_heart" &&
- r.userID === user?.id,
- );
- setFileReactions((prev) => {
- const next = new Map(prev);
- if (userReaction) {
- next.set(activeFileID, [
- {
- collectionId: activeCollectionID,
- reactionId: userReaction.id,
- },
- ]);
- } else {
- next.delete(activeFileID);
- }
- return next;
- });
- }
- } catch (e) {
- log.error("Failed to fetch reactions", e);
- setFileReactions((prev) => {
- const next = new Map(prev);
- next.delete(activeFileID);
- return next;
- });
- }
- })();
- }, [
- open,
- activeFileID,
- activeCollectionID,
- fileNormalCollectionIDs,
- user?.id,
- ]);
-
- // Fetch comments for the current file when it changes.
- useEffect(() => {
- if (!open || !activeFileID) return;
-
- const isGalleryView = !activeCollectionID || activeCollectionID === 0;
-
void (async () => {
try {
const commentsMap = new Map<number, Comment[]>();
+ const reactionsMap = new Map<number, UnifiedReaction[]>();
- if (isGalleryView) {
- // Gallery view: fetch from ALL collections the file belongs to
- const collectionIDs =
- fileNormalCollectionIDs?.get(activeFileID) ?? [];
+ const collectionIDs = isGalleryView
+ ? (fileNormalCollectionIDs?.get(activeFileID) ?? [])
+ : [activeCollectionID];
- for (const collectionId of collectionIDs) {
- try {
- const collection =
- await getCollectionByID(collectionId);
- const comments = await getFileComments(
- collectionId,
- activeFileID,
- collection.key,
- );
- commentsMap.set(collectionId, comments);
- } catch {
- // Skip collections that fail to fetch
- }
+ for (const collectionId of collectionIDs) {
+ try {
+ const collection = await getCollectionByID(collectionId);
+ const { comments, reactions } = await getUnifiedSocialDiff(
+ collectionId,
+ activeFileID,
+ collection.key,
+ );
+
+ commentsMap.set(collectionId, comments);
+ reactionsMap.set(collectionId, reactions);
+ } catch {
+ // Skip collections that fail to fetch
}
- } else {
- // Collection view: fetch only from the active collection
- const collection =
- await getCollectionByID(activeCollectionID);
- const comments = await getFileComments(
- activeCollectionID,
- activeFileID,
- collection.key,
- );
- commentsMap.set(activeCollectionID, comments);
}
setFileComments((prev) => {
@@ -1497,13 +1550,24 @@ export const FileViewer: React.FC<FileViewerProps> = ({
next.set(activeFileID, commentsMap);
return next;
});
+
+ setAllReactions((prev) => {
+ const next = new Map(prev);
+ next.set(activeFileID, reactionsMap);
+ return next;
+ });
} catch (e) {
- log.error("Failed to fetch comments", e);
+ log.error("Failed to fetch social data", e);
setFileComments((prev) => {
const next = new Map(prev);
next.delete(activeFileID);
return next;
});
+ setAllReactions((prev) => {
+ const next = new Map(prev);
+ next.delete(activeFileID);
+ return next;
+ });
}
})();
}, [open, activeFileID, activeCollectionID, fileNormalCollectionIDs]);
@@ -1619,10 +1683,12 @@ export const FileViewer: React.FC<FileViewerProps> = ({
fileNormalCollectionIDs={fileNormalCollectionIDs}
collectionSummaries={collectionSummaries}
currentUserID={user?.id}
- prefetchedComments={fileComments.get(
- activeAnnotatedFile.file.id,
- )}
- onCommentsUpdate={handleCommentsUpdate}
+ prefetchedComments={fileComments.get(activeAnnotatedFile.file.id)}
+ prefetchedReactions={allReactions.get(activeAnnotatedFile.file.id)}
+ onCommentAdded={handleCommentAdded}
+ onCommentDeleted={handleCommentDeleted}
+ onCommentReactionAdded={handleCommentReactionAdded}
+ onCommentReactionDeleted={handleCommentReactionDeleted}
/>
<LikesSidebar
open={openLikes}
@@ -1631,6 +1697,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({
activeCollectionID={activeCollectionID}
fileNormalCollectionIDs={fileNormalCollectionIDs}
collectionSummaries={collectionSummaries}
+ prefetchedReactions={allReactions.get(activeAnnotatedFile.file.id)}
/>
<LikeAlbumSelectorModal
open={openLikeAlbumSelector}
diff --git a/web/packages/gallery/components/viewer/LikesSidebar.tsx b/web/packages/gallery/components/viewer/LikesSidebar.tsx
index 4f8b928043..7fdc51dd91 100644
--- a/web/packages/gallery/components/viewer/LikesSidebar.tsx
+++ b/web/packages/gallery/components/viewer/LikesSidebar.tsx
@@ -15,11 +15,8 @@ import { downloadManager } from "ente-gallery/services/download";
import type { EnteFile } from "ente-media/file";
import { getCollectionByID } from "ente-new/photos/services/collection";
import type { CollectionSummaries } from "ente-new/photos/services/collection-summary";
-import {
- getFileReactions,
- type Reaction,
-} from "ente-new/photos/services/reaction";
-import React, { useCallback, useEffect, useMemo, useState } from "react";
+import { type UnifiedReaction } from "ente-new/photos/services/social";
+import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
// =============================================================================
// Icons
@@ -100,6 +97,10 @@ export interface LikesSidebarProps extends ModalVisibilityProps {
* Collection summaries indexed by their IDs.
*/
collectionSummaries?: CollectionSummaries;
+ /**
+ * Pre-fetched reactions by collection ID (includes both file and comment reactions).
+ */
+ prefetchedReactions?: Map<number, UnifiedReaction[]>;
}
/**
@@ -112,13 +113,14 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({
activeCollectionID,
fileNormalCollectionIDs,
collectionSummaries,
+ prefetchedReactions,
}) => {
const [loading, setLoading] = useState(false);
const [collectionDropdownOpen, setCollectionDropdownOpen] = useState(false);
// Reactions grouped by collection: collectionID -> reactions
const [reactionsByCollection, setReactionsByCollection] = useState<
- Map<number, Reaction[]>
+ Map<number, UnifiedReaction[]>
>(new Map());
// User ID to email mapping built from fetched collections
@@ -163,19 +165,26 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({
});
}, [fileCollectionIDs, collectionSummaries, reactionsByCollection]);
+ // Collections sorted by like count (descending) for dropdown
+ const sortedCollectionsInfo = useMemo(() => {
+ return [...collectionsInfo].sort((a, b) => b.likeCount - a.likeCount);
+ }, [collectionsInfo]);
+
// Currently selected collection info
const selectedCollectionInfo = useMemo(() => {
const targetID = hasCollectionContext
? activeCollectionID
: selectedCollectionID;
return (
- collectionsInfo.find((c) => c.id === targetID) ?? collectionsInfo[0]
+ collectionsInfo.find((c) => c.id === targetID) ??
+ sortedCollectionsInfo[0]
);
}, [
hasCollectionContext,
activeCollectionID,
selectedCollectionID,
collectionsInfo,
+ sortedCollectionsInfo,
]);
// Get likers for the selected collection
@@ -192,105 +201,119 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({
}));
}, [selectedCollectionInfo, reactionsByCollection, userIDToEmail]);
- // Fetch reactions when the sidebar opens or file changes
- const fetchReactions = useCallback(async () => {
- if (!file || !open) return;
+ // Load reactions from prefetched data
+ const loadReactions = useCallback(async () => {
+ if (!file || !open || !prefetchedReactions) return;
setLoading(true);
- const newReactionsByCollection = new Map<number, Reaction[]>();
const newUserIDToEmail = new Map<number, string>();
try {
- if (hasCollectionContext && activeCollectionID) {
- // Collection view: only fetch for the active collection
- const collection = await getCollectionByID(activeCollectionID);
-
- // Build user ID to email map from collection owner and sharees
- if (collection.owner.email) {
- newUserIDToEmail.set(
- collection.owner.id,
- collection.owner.email,
- );
- }
- for (const sharee of collection.sharees) {
- if (sharee.email) {
- newUserIDToEmail.set(sharee.id, sharee.email);
+ // Determine which collections to process
+ const collectionIDsToFetch =
+ hasCollectionContext && activeCollectionID
+ ? [activeCollectionID]
+ : fileCollectionIDs;
+
+ // Fetch collection info for user emails (lightweight call)
+ for (const collectionID of collectionIDsToFetch) {
+ try {
+ const collection = await getCollectionByID(collectionID);
+
+ // Build user ID to email map from collection owner and sharees
+ if (collection.owner.email) {
+ newUserIDToEmail.set(
+ collection.owner.id,
+ collection.owner.email,
+ );
}
- }
-
- const reactions = await getFileReactions(
- activeCollectionID,
- file.id,
- collection.key,
- );
- newReactionsByCollection.set(activeCollectionID, reactions);
- } else {
- // Gallery view: fetch for all collections the file belongs to
- for (const collectionID of fileCollectionIDs) {
- try {
- const collection =
- await getCollectionByID(collectionID);
-
- // Build user ID to email map from collection owner and sharees
- if (collection.owner.email) {
- newUserIDToEmail.set(
- collection.owner.id,
- collection.owner.email,
- );
+ for (const sharee of collection.sharees) {
+ if (sharee.email) {
+ newUserIDToEmail.set(sharee.id, sharee.email);
}
- for (const sharee of collection.sharees) {
- if (sharee.email) {
- newUserIDToEmail.set(sharee.id, sharee.email);
- }
- }
-
- const reactions = await getFileReactions(
- collectionID,
- file.id,
- collection.key,
- );
- newReactionsByCollection.set(collectionID, reactions);
- } catch (e) {
- log.error(
- `Failed to fetch reactions for collection ${collectionID}`,
- e,
- );
}
+ } catch {
+ // Skip collections that fail to fetch
}
}
- setReactionsByCollection(newReactionsByCollection);
+
+ // Use prefetched reactions (filter to only file reactions, not comment reactions)
+ const filteredReactions = new Map<number, UnifiedReaction[]>();
+ for (const [collectionID, reactions] of prefetchedReactions) {
+ const fileReactions = reactions.filter(
+ (r) => !r.commentID && r.fileID === file.id,
+ );
+ filteredReactions.set(collectionID, fileReactions);
+ }
+
+ setReactionsByCollection(filteredReactions);
setUserIDToEmail(newUserIDToEmail);
} catch (e) {
- log.error("Failed to fetch reactions", e);
+ log.error("Failed to load reactions", e);
} finally {
setLoading(false);
}
}, [
file,
open,
+ prefetchedReactions,
hasCollectionContext,
activeCollectionID,
fileCollectionIDs,
]);
- // Fetch reactions when the sidebar opens
+ // Track previous open state to detect when sidebar opens
+ const prevOpenRef = useRef(false);
+
+ // Load reactions and set initial selection when the sidebar opens
useEffect(() => {
- if (open) {
- void fetchReactions();
+ if (open && !prevOpenRef.current) {
+ // Sidebar just opened - load reactions and set initial selection
+ void loadReactions();
+
+ // Set initial selection to album with most likes (gallery view only)
+ if (
+ !hasCollectionContext &&
+ prefetchedReactions &&
+ prefetchedReactions.size > 0
+ ) {
+ let maxCount = -1;
+ let bestCollectionID: number | undefined;
+ for (const [collectionID, reactions] of prefetchedReactions) {
+ const count = reactions.filter(
+ (r) =>
+ !r.commentID &&
+ r.fileID === file?.id &&
+ r.reactionType === "green_heart",
+ ).length;
+ if (count > maxCount) {
+ maxCount = count;
+ bestCollectionID = collectionID;
+ }
+ }
+ if (bestCollectionID !== undefined) {
+ setSelectedCollectionID(bestCollectionID);
+ }
+ }
}
- }, [open, fetchReactions]);
+ prevOpenRef.current = open;
+ }, [open, loadReactions, hasCollectionContext, prefetchedReactions, file?.id]);
- // Set initial selected collection when file collection IDs are available
+ // Update local state when prefetchedReactions changes (e.g., like/unlike from heart button)
useEffect(() => {
- if (
- open &&
- !hasCollectionContext &&
- selectedCollectionID === undefined &&
- fileCollectionIDs.length > 0
- ) {
- setSelectedCollectionID(fileCollectionIDs[0]);
+ if (!open || !file || !prefetchedReactions) return;
+
+ // Filter to only file reactions (not comment reactions)
+ const filteredReactions = new Map<number, UnifiedReaction[]>();
+ for (const [collectionID, reactions] of prefetchedReactions) {
+ const fileReactions = reactions.filter(
+ (r) => !r.commentID && r.fileID === file.id,
+ );
+ filteredReactions.set(collectionID, fileReactions);
}
- }, [open, hasCollectionContext, selectedCollectionID, fileCollectionIDs]);
+
+ setReactionsByCollection(filteredReactions);
+ }, [open, file, prefetchedReactions]);
// Fetch thumbnails for each collection's cover file
useEffect(() => {
@@ -413,7 +436,7 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({
</CollectionDropdownButton>
{collectionDropdownOpen && (
<CollectionDropdownMenu>
- {collectionsInfo.map((collection) => (
+ {sortedCollectionsInfo.map((collection) => (
<CollectionDropdownItem
key={collection.id}
onClick={() =>
diff --git a/web/packages/new/photos/services/social.ts b/web/packages/new/photos/services/social.ts
new file mode 100644
index 0000000000..23bb56e571
--- /dev/null
+++ b/web/packages/new/photos/services/social.ts
@@ -0,0 +1,180 @@
+import { decryptBox } from "ente-base/crypto";
+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
+import { apiURL } from "ente-base/origins";
+import { z } from "zod";
+import type { Comment, CommentData } from "./comment";
+
+/**
+ * Remove null byte padding from a decrypted reaction type.
+ */
+const unpadReaction = (paddedReaction: string): string =>
+ paddedReaction.replace(/\0+$/, "");
+
+/**
+ * A decrypted reaction from the unified diff endpoint.
+ */
+export interface UnifiedReaction {
+ id: string;
+ collectionID: number;
+ fileID?: number;
+ commentID?: string;
+ reactionType: string;
+ userID: number;
+ anonUserID?: string;
+ isDeleted: boolean;
+ createdAt: number;
+ updatedAt: number;
+}
+
+/**
+ * Result from the unified social diff endpoint.
+ */
+export interface UnifiedSocialDiff {
+ comments: Comment[];
+ reactions: UnifiedReaction[];
+ hasMoreComments: boolean;
+ hasMoreReactions: boolean;
+}
+
+/**
+ * Get comments and reactions for a file in a single request.
+ *
+ * @param collectionID The ID of the collection containing the file.
+ * @param fileID The ID of the file to get social data for.
+ * @param collectionKey The decrypted collection key (base64 encoded).
+ * @returns Comments and reactions for the file.
+ */
+export const getUnifiedSocialDiff = async (
+ collectionID: number,
+ fileID: number,
+ collectionKey: string,
+): Promise<UnifiedSocialDiff> => {
+ const res = await fetch(
+ await apiURL("/social/diff", {
+ collectionID,
+ fileID,
+ sinceTime: 0,
+ limit: 1000,
+ }),
+ { headers: await authenticatedRequestHeaders() },
+ );
+ ensureOk(res);
+ const data = UnifiedDiffResponse.parse(await res.json());
+
+ // Decrypt comments
+ const comments: Comment[] = [];
+ for (const comment of data.comments) {
+ if (comment.isDeleted || !comment.cipher || !comment.nonce) {
+ comments.push({
+ id: comment.id,
+ collectionID: comment.collectionID,
+ fileID: comment.fileID ?? undefined,
+ parentCommentID: comment.parentCommentID ?? undefined,
+ userID: comment.userID,
+ anonUserID: comment.anonUserID ?? undefined,
+ encData: { text: "", userName: "" },
+ isDeleted: comment.isDeleted,
+ createdAt: comment.createdAt,
+ updatedAt: comment.updatedAt,
+ });
+ continue;
+ }
+ try {
+ const decryptedB64 = await decryptBox(
+ { encryptedData: comment.cipher, nonce: comment.nonce },
+ collectionKey,
+ );
+ const decryptedStr = new TextDecoder().decode(
+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),
+ );
+ const encData = JSON.parse(decryptedStr) as CommentData;
+ comments.push({
+ id: comment.id,
+ collectionID: comment.collectionID,
+ fileID: comment.fileID ?? undefined,
+ parentCommentID: comment.parentCommentID ?? undefined,
+ userID: comment.userID,
+ anonUserID: comment.anonUserID ?? undefined,
+ encData,
+ isDeleted: comment.isDeleted,
+ createdAt: comment.createdAt,
+ updatedAt: comment.updatedAt,
+ });
+ } catch {
+ // Skip comments that fail to decrypt
+ }
+ }
+
+ // Decrypt reactions
+ const reactions: UnifiedReaction[] = [];
+ for (const reaction of data.reactions) {
+ if (reaction.isDeleted || !reaction.cipher || !reaction.nonce) continue;
+ try {
+ const decryptedB64 = await decryptBox(
+ { encryptedData: reaction.cipher, nonce: reaction.nonce },
+ collectionKey,
+ );
+ const reactionType = unpadReaction(
+ new TextDecoder().decode(
+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),
+ ),
+ );
+ reactions.push({
+ id: reaction.id,
+ collectionID: reaction.collectionID,
+ fileID: reaction.fileID ?? undefined,
+ commentID: reaction.commentID ?? undefined,
+ reactionType,
+ userID: reaction.userID,
+ anonUserID: reaction.anonUserID ?? undefined,
+ isDeleted: reaction.isDeleted,
+ createdAt: reaction.createdAt,
+ updatedAt: reaction.updatedAt,
+ });
+ } catch {
+ // Skip reactions that fail to decrypt
+ }
+ }
+
+ return {
+ comments,
+ reactions,
+ hasMoreComments: data.hasMoreComments,
+ hasMoreReactions: data.hasMoreReactions,
+ };
+};
+
+const RemoteComment = z.object({
+ id: z.string(),
+ collectionID: z.number(),
+ fileID: z.number().nullish(),
+ parentCommentID: z.string().nullish(),
+ userID: z.number(),
+ anonUserID: z.string().nullish(),
+ cipher: z.string().nullish(),
+ nonce: z.string().nullish(),
+ isDeleted: z.boolean(),
+ createdAt: z.number(),
+ updatedAt: z.number(),
+});
+
+const RemoteReaction = z.object({
+ id: z.string(),
+ collectionID: z.number(),
+ fileID: z.number().nullish(),
+ commentID: z.string().nullish(),
+ userID: z.number(),
+ anonUserID: z.string().nullish(),
+ cipher: z.string().nullish(),
+ nonce: z.string().nullish(),
+ isDeleted: z.boolean(),
+ createdAt: z.number(),
+ updatedAt: z.number(),
+});
+
+const UnifiedDiffResponse = z.object({
+ comments: z.array(RemoteComment),
+ reactions: z.array(RemoteReaction),
+ hasMoreComments: z.boolean(),
+ hasMoreReactions: z.boolean(),
+});