π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add anonymous commenting support for public albums
Anand Baburajanaea251874749
diff --git a/web/packages/gallery/components/viewer/CommentsSidebar.tsx b/web/packages/gallery/components/viewer/CommentsSidebar.tsxindex 5269133c94..d3c14d6d4e 100644--- a/web/packages/gallery/components/viewer/CommentsSidebar.tsx+++ b/web/packages/gallery/components/viewer/CommentsSidebar.tsx@@ -13,10 +13,18 @@ import {Typography,} from "@mui/material";import { type ModalVisibilityProps } from "ente-base/components/utils/modal";+import type { PublicAlbumsCredentials } from "ente-base/http";import log from "ente-base/log";import { downloadManager } from "ente-gallery/services/download";import { getAvatarColor } from "ente-gallery/utils/avatar-colors";import type { EnteFile } from "ente-media/file";+import { addPublicComment } from "ente-new/albums/services/public-comment";+import {+ addPublicCommentReaction,+ createAnonIdentity,+ deletePublicReaction,+ getStoredAnonIdentity,+} from "ente-new/albums/services/public-reaction";import { getCollectionByID } from "ente-new/photos/services/collection";import type { CollectionSummaries } from "ente-new/photos/services/collection-summary";import {@@ -133,6 +141,21 @@ const ChevronDownIcon: React.FC = () => (</svg>);+const PersonIcon: React.FC = () => (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M12 12C14.21 12 16 10.21 16 8C16 5.79 14.21 4 12 4C9.79 4 8 5.79 8 8C8 10.21 9.79 12 12 12ZM12 14C9.33 14 4 15.34 4 18V20H20V18C20 15.34 14.67 14 12 14Z"+ fill="currentColor"+ />+ </svg>+);+// =============================================================================// Types// =============================================================================@@ -192,6 +215,9 @@ interface CommentHeaderProps {userName: string;timestamp: number;avatarSize?: number;+ isMaskedEmail?: boolean;+ /** Key used for computing avatar color (e.g., anonUserID for anonymous users). */+ avatarColorKey?: string;}/**@@ -202,6 +228,8 @@ const CommentHeader: React.FC<CommentHeaderProps> = ({userName,timestamp,avatarSize = 32,+ isMaskedEmail,+ avatarColorKey,}) => (<CommentHeaderContainer><Avatar@@ -209,11 +237,11 @@ const CommentHeader: React.FC<CommentHeaderProps> = ({width: avatarSize,height: avatarSize,fontSize: 14,- bgcolor: getAvatarColor(userName),+ bgcolor: getAvatarColor(avatarColorKey ?? userName),color: "#fff",}}>- {userName[0]?.toUpperCase()}+ {isMaskedEmail ? <PersonIcon /> : userName[0]?.toUpperCase()}</Avatar><UserName>{userName}</UserName><Separator>β’</Separator>@@ -226,6 +254,8 @@ interface QuotedReplyProps {isOwn: boolean;currentUserID?: number;userIDToEmail?: Map<number, string>;+ anonUserNames?: Map<string, string>;+ currentAnonUserID?: string;}/**@@ -236,12 +266,31 @@ const QuotedReply: React.FC<QuotedReplyProps> = ({isOwn,currentUserID,userIDToEmail,+ anonUserNames,+ currentAnonUserID,}) => {- // Get the author name from userID+ // Get the author nameconst getAuthorName = (): string => {+ // Check if this is the current user (logged in or anonymous)if (parentComment.userID === currentUserID) {return "You";}+ if (+ parentComment.anonUserID &&+ parentComment.anonUserID === currentAnonUserID+ ) {+ return "You";+ }++ // For anonymous users, look up in anonUserNames+ if (parentComment.anonUserID) {+ return (+ anonUserNames?.get(parentComment.anonUserID) ??+ `Anonymous ${parentComment.anonUserID.slice(-4)}`+ );+ }++ // For registered users, look up emailconst email = userIDToEmail?.get(parentComment.userID);return email ?? "User";};@@ -381,6 +430,20 @@ export interface CommentsSidebarProps extends ModalVisibilityProps {* If set, the sidebar will scroll to and highlight this comment.*/highlightCommentID?: string;+ /**+ * Public album credentials for anonymous commenting.+ * Required when viewing a public album (no logged in user).+ */+ publicAlbumsCredentials?: PublicAlbumsCredentials;+ /**+ * The decrypted collection key (base64 encoded) for encrypting comments.+ * Required when viewing a public album (no logged in user).+ */+ collectionKey?: string;+ /**+ * Map of anonymous user ID to decrypted user name.+ */+ anonUserNames?: Map<string, string>;}/**@@ -408,6 +471,9 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({onCommentReactionAdded,onCommentReactionDeleted,highlightCommentID,+ publicAlbumsCredentials,+ collectionKey,+ anonUserNames,}) => {const [commentText, setCommentText] = useState("");const [replyingTo, setReplyingTo] = useState<Comment | null>(null);@@ -512,9 +578,7 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({const originalBg = computedStyle.backgroundColor;// Parse the RGB values to create 80% opacity version- const rgbMatch = originalBg.match(- /rgba?\((\d+),\s*(\d+),\s*(\d+)/,- );+ const rgbMatch = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(originalBg);if (!rgbMatch) return;const [, r, g, b] = rgbMatch;@@ -571,8 +635,28 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({return fileNormalCollectionIDs?.get(file.id) ?? [];}, [file, fileNormalCollectionIDs]);+ // Check if this is a public album (has ?t=... in URL)+ const isPublicAlbum =+ typeof window !== "undefined" &&+ new URLSearchParams(window.location.search).has("t");+// Build collection info list with comment counts and cover files (shared albums only)const collectionsInfo = useMemo((): CollectionInfo[] => {+ // For public albums, use the file's collection directly+ if (isPublicAlbum && file) {+ return [+ {+ id: file.collectionID,+ name: "Album",+ commentCount:+ commentsByCollection+ .get(file.collectionID)+ ?.filter((c) => !c.isDeleted).length ?? 0,+ coverFile: file,+ },+ ];+ }+return fileCollectionIDs.filter((collectionID) =>collectionSummaries@@ -591,7 +675,7 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({coverFile: summary?.coverFile,};});- }, [fileCollectionIDs, collectionSummaries, commentsByCollection]);+ }, [isPublicAlbum, file, fileCollectionIDs, collectionSummaries, commentsByCollection]);// Collections sorted by comment count (descending) for dropdownconst sortedCollectionsInfo = useMemo(() => {@@ -814,32 +898,47 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({return;}- // Find comment reactions that are likes from the current user+ // Get stored anon identity for public albums+ const storedIdentity = isPublicAlbum+ ? getStoredAnonIdentity(selectedCollectionInfo.id)+ : undefined;++ // Find comment reactions that are likes from the current user (or anon user)const newLikedComments = new Map<string, string>();for (const reaction of reactions) {if (reaction.commentID &&- reaction.reactionType === "green_heart" &&- reaction.userID === currentUserID+ reaction.reactionType === "green_heart") {- newLikedComments.set(reaction.commentID, reaction.id);+ // Check if this is the current user's reaction+ const isCurrentUserReaction =+ reaction.userID === currentUserID ||+ (storedIdentity &&+ reaction.anonUserID === storedIdentity.anonUserID);+ if (isCurrentUserReaction) {+ newLikedComments.set(reaction.commentID, reaction.id);+ }}}setLikedComments(newLikedComments);- }, [open, selectedCollectionInfo, reactionsByCollection, currentUserID]);-- // Check if this is a public album (has ?t=... in URL)- const isPublicAlbum =- typeof window !== "undefined" &&- new URLSearchParams(window.location.search).has("t");+ }, [open, selectedCollectionInfo, reactionsByCollection, currentUserID, isPublicAlbum]);const handleSend = async () => {if (!commentText.trim() || !file || !selectedCollectionInfo) return;- // For public albums, show the modal instead of directly sending+ // For public albums, check if we already have an anon identityif (isPublicAlbum) {- setPendingComment(commentText.trim());- setShowPublicCommentModal(true);+ const storedIdentity = getStoredAnonIdentity(+ selectedCollectionInfo.id,+ );+ if (storedIdentity && publicAlbumsCredentials && collectionKey) {+ // User already has identity, send directly+ await sendPublicComment(commentText.trim());+ } else {+ // Show modal to choose anonymous or sign in+ setPendingComment(commentText.trim());+ setShowPublicCommentModal(true);+ }return;}@@ -898,28 +997,76 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({}};- const addLocalComment = (text: string) => {- // Used for anonymous comments in public albums- const newComment: Comment = {- id: String(Date.now()),- collectionID: selectedCollectionInfo?.id ?? 0,- fileID: file?.id,- text,- parentCommentID: replyingTo?.id,- isDeleted: false,- userID: currentUserID ?? 0,- createdAt: Date.now() * 1000, // Microseconds to match server format- updatedAt: Date.now() * 1000,- };- setComments((prev) => [...prev, newComment]);- setCommentText("");- setReplyingTo(null);- // Scroll to bottom after adding comment- setTimeout(() => {- if (commentsContainerRef.current) {- commentsContainerRef.current.scrollTop = 0;- }- }, 0);+ /**+ * Send a comment to the public album API using stored anonymous identity.+ */+ const sendPublicComment = async (text: string) => {+ if (+ !file ||+ !selectedCollectionInfo ||+ !publicAlbumsCredentials ||+ !collectionKey+ ) {+ return;+ }++ const collectionID = selectedCollectionInfo.id;+ const storedIdentity = getStoredAnonIdentity(collectionID);+ if (!storedIdentity) {+ log.error("No stored identity for public comment");+ return;+ }++ setSending(true);+ try {+ const newCommentID = await addPublicComment(+ publicAlbumsCredentials,+ collectionID,+ file.id,+ text,+ collectionKey,+ replyingTo?.id,+ storedIdentity,+ );++ // Add the new comment to local state+ const newComment: Comment = {+ id: newCommentID,+ collectionID,+ fileID: file.id,+ text,+ parentCommentID: replyingTo?.id,+ isDeleted: false,+ userID: 0, // Anonymous user+ anonUserID: storedIdentity.anonUserID,+ createdAt: Date.now() * 1000, // Microseconds to match server format+ updatedAt: Date.now() * 1000,+ };+ setComments((prev) => [...prev, newComment]);+ setCommentsByCollection((prev) => {+ const next = new Map(prev);+ const existing = next.get(collectionID) ?? [];+ next.set(collectionID, [...existing, newComment]);+ return next;+ });++ setCommentText("");+ setReplyingTo(null);++ // Notify parent to update its comments state+ onCommentAdded?.(newComment);++ // Scroll to bottom after adding comment+ setTimeout(() => {+ if (commentsContainerRef.current) {+ commentsContainerRef.current.scrollTop = 0;+ }+ }, 0);+ } catch (e) {+ log.error("Failed to add public comment", e);+ } finally {+ setSending(false);+ }};const handleCommentAnonymously = () => {@@ -933,11 +1080,81 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({window.open("https://web.ente.io", "_blank");};- const handleNameSubmit = (_name: string) => {+ const handleNameSubmit = async (name: string) => {setShowAddNameModal(false);- // TODO: Store name via anon profile API- addLocalComment(pendingComment);- setPendingComment("");++ if (+ !file ||+ !selectedCollectionInfo ||+ !publicAlbumsCredentials ||+ !collectionKey+ ) {+ setPendingComment("");+ return;+ }++ const collectionID = selectedCollectionInfo.id;++ setSending(true);+ try {+ // Create anonymous identity with the provided name+ const identity = await createAnonIdentity(+ publicAlbumsCredentials,+ collectionID,+ name,+ collectionKey,+ );++ // Now post the comment using the new identity+ const newCommentID = await addPublicComment(+ publicAlbumsCredentials,+ collectionID,+ file.id,+ pendingComment,+ collectionKey,+ replyingTo?.id,+ identity,+ );++ // Add the new comment to local state+ const newComment: Comment = {+ id: newCommentID,+ collectionID,+ fileID: file.id,+ text: pendingComment,+ parentCommentID: replyingTo?.id,+ isDeleted: false,+ userID: 0, // Anonymous user+ anonUserID: identity.anonUserID,+ createdAt: Date.now() * 1000, // Microseconds to match server format+ updatedAt: Date.now() * 1000,+ };+ setComments((prev) => [...prev, newComment]);+ setCommentsByCollection((prev) => {+ const next = new Map(prev);+ const existing = next.get(collectionID) ?? [];+ next.set(collectionID, [...existing, newComment]);+ return next;+ });++ setCommentText("");+ setReplyingTo(null);++ // Notify parent to update its comments state+ onCommentAdded?.(newComment);++ // Scroll to bottom after adding comment+ setTimeout(() => {+ if (commentsContainerRef.current) {+ commentsContainerRef.current.scrollTop = 0;+ }+ }, 0);+ } catch (e) {+ log.error("Failed to create identity and add comment", e);+ } finally {+ setSending(false);+ setPendingComment("");+ }};const handleReply = (commentToReply: Comment) => {@@ -975,70 +1192,133 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({const handleLikeComment = async (targetComment: Comment) => {if (!selectedCollectionInfo) return;+ const collectionID = selectedCollectionInfo.id;+ const existingReactionID = likedComments.get(targetComment.id);+try {- const collection = await getCollectionByID(- selectedCollectionInfo.id,- );- const existingReactionID = likedComments.get(targetComment.id);-- if (existingReactionID) {- // Unlike - delete the reaction- await deleteReaction(existingReactionID);- setLikedComments((prev) => {- const next = new Map(prev);- 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),+ if (isPublicAlbum) {+ // Public album - use public APIs+ if (!publicAlbumsCredentials || !collectionKey) {+ log.error("Missing credentials for public album comment like");+ return;+ }++ const storedIdentity = getStoredAnonIdentity(collectionID);+ if (!storedIdentity) {+ log.error("No stored identity for public album comment like");+ return;+ }++ if (existingReactionID) {+ // Unlike - delete the reaction+ await deletePublicReaction(+ publicAlbumsCredentials,+ collectionID,+ existingReactionID,+ storedIdentity,);- return next;- });- // Notify parent to update its reactions state- onCommentReactionDeleted?.(- selectedCollectionInfo.id,- existingReactionID,- );+ setLikedComments((prev) => {+ const next = new Map(prev);+ next.delete(targetComment.id);+ return next;+ });+ setReactionsByCollection((prev) => {+ const next = new Map(prev);+ const reactions = next.get(collectionID) ?? [];+ next.set(+ collectionID,+ reactions.filter((r) => r.id !== existingReactionID),+ );+ return next;+ });+ onCommentReactionDeleted?.(collectionID, existingReactionID);+ } else {+ // Like - add a reaction+ const reactionID = await addPublicCommentReaction(+ publicAlbumsCredentials,+ collectionID,+ targetComment.id,+ "green_heart",+ collectionKey,+ storedIdentity,+ );+ const newReaction: UnifiedReaction = {+ id: reactionID,+ collectionID,+ commentID: targetComment.id,+ reactionType: "green_heart",+ userID: 0,+ anonUserID: storedIdentity.anonUserID,+ isDeleted: false,+ createdAt: Date.now() * 1000,+ updatedAt: Date.now() * 1000,+ };+ setLikedComments((prev) => {+ const next = new Map(prev);+ next.set(targetComment.id, reactionID);+ return next;+ });+ setReactionsByCollection((prev) => {+ const next = new Map(prev);+ const reactions = next.get(collectionID) ?? [];+ next.set(collectionID, [...reactions, newReaction]);+ return next;+ });+ onCommentReactionAdded?.(newReaction);+ }} else {- // Like - add a reaction- const reactionID = await addCommentReaction(- selectedCollectionInfo.id,- targetComment.id,- "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);+ // Authenticated user - use regular APIs+ const collection = await getCollectionByID(collectionID);++ if (existingReactionID) {+ // Unlike - delete the reaction+ await deleteReaction(existingReactionID);+ setLikedComments((prev) => {+ const next = new Map(prev);+ next.delete(targetComment.id);+ return next;+ });+ setReactionsByCollection((prev) => {+ const next = new Map(prev);+ const reactions = next.get(collectionID) ?? [];+ next.set(+ collectionID,+ reactions.filter((r) => r.id !== existingReactionID),+ );+ return next;+ });+ onCommentReactionDeleted?.(collectionID, existingReactionID);+ } else {+ // Like - add a reaction+ const reactionID = await addCommentReaction(+ collectionID,+ targetComment.id,+ "green_heart",+ collection.key,+ );+ const newReaction: UnifiedReaction = {+ id: reactionID,+ collectionID,+ 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;+ });+ setReactionsByCollection((prev) => {+ const next = new Map(prev);+ const reactions = next.get(collectionID) ?? [];+ next.set(collectionID, [...reactions, newReaction]);+ return next;+ });+ onCommentReactionAdded?.(newReaction);+ }}} catch (e) {log.error("Failed to toggle comment like", e);@@ -1253,8 +1533,22 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({<EmptyMessage>No comments yet</EmptyMessage>) : (sortedComments.map((comment, index) => {+ // Check if this is the current user's comment+ // For logged-in users, check userID+ // For anonymous users, check anonUserID against stored identity+ const storedIdentity = selectedCollectionInfo+ ? getStoredAnonIdentity(+ selectedCollectionInfo.id,+ )+ : undefined;+ const isCurrentAnonUser = !!(+ storedIdentity &&+ comment.anonUserID === storedIdentity.anonUserID+ );const commentIsOwn =- comment.userID === currentUserID;+ comment.userID === currentUserID ||+ isCurrentAnonUser;+// With column-reverse, visual order is reversed from array order// Visual "above" = higher index, visual "below" = lower indexconst prevComment = sortedComments[index + 1];@@ -1264,14 +1558,21 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({const GROUP_TIME_THRESHOLD = 10 * 60 * 1000 * 1000;// Comments are in same sequence if same user AND within 10 minutes+ // For anon users, also check if they have the same anonUserID+ const isSameUser = (a: Comment, b: Comment) => {+ if (a.anonUserID && b.anonUserID) {+ return a.anonUserID === b.anonUserID;+ }+ return a.userID === b.userID;+ };const isSameSequenceAsPrev =prevComment &&- prevComment.userID === comment.userID &&+ isSameUser(prevComment, comment) &&comment.createdAt - prevComment.createdAt <=GROUP_TIME_THRESHOLD;const isSameSequenceAsNext =nextComment &&- nextComment.userID === comment.userID &&+ isSameUser(nextComment, comment) &&nextComment.createdAt - comment.createdAt <=GROUP_TIME_THRESHOLD;@@ -1289,16 +1590,48 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({const showOwnTimestamp =commentIsOwn && isFirstInSequence;+ // Get the display name, avatar color key, and masked email status for the comment author+ const getCommentAuthorInfo = (): {+ name: string;+ avatarColorKey: string;+ isMaskedEmail: boolean;+ } => {+ // If anonymous user, check anonUserNames map+ if (comment.anonUserID) {+ return {+ name:+ anonUserNames?.get(+ comment.anonUserID,+ ) ??+ `Anonymous ${comment.anonUserID.slice(-4)}`,+ // Use anonUserID for consistent avatar color with LikesSidebar+ avatarColorKey: comment.anonUserID,+ isMaskedEmail: false,+ };+ }+ // For registered users, use email+ const email =+ prefetchedUserIDToEmail?.get(+ comment.userID,+ ) ?? "User";+ return {+ name: email,+ // Use email or userID for avatar color+ avatarColorKey: email !== "User" ? email : String(comment.userID),+ isMaskedEmail: email.startsWith("*"),+ };+ };++ const authorInfo = getCommentAuthorInfo();+return (<Box key={comment.id}>{showHeader && (<CommentHeader- userName={- prefetchedUserIDToEmail?.get(- comment.userID,- ) ?? "User"- }+ userName={authorInfo.name}timestamp={comment.createdAt}+ isMaskedEmail={authorInfo.isMaskedEmail}+ avatarColorKey={authorInfo.avatarColorKey}/>)}{showOwnTimestamp && (@@ -1352,6 +1685,12 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({userIDToEmail={prefetchedUserIDToEmail}+ anonUserNames={+ anonUserNames+ }+ currentAnonUserID={+ storedIdentity?.anonUserID+ }/>)}<CommentText@@ -1460,11 +1799,36 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({})}>Replying to{" "}- {replyingTo.userID === currentUserID- ? "yourself"- : (prefetchedUserIDToEmail?.get(- replyingTo.userID,- ) ?? "User")}+ {(() => {+ // Check for anonymous user+ if (replyingTo.anonUserID) {+ const storedIdentity =+ selectedCollectionInfo+ ? getStoredAnonIdentity(+ selectedCollectionInfo.id,+ )+ : undefined;+ if (+ storedIdentity &&+ replyingTo.anonUserID ===+ storedIdentity.anonUserID+ ) {+ return "yourself";+ }+ return (+ anonUserNames?.get(+ replyingTo.anonUserID,+ ) ?? "User"+ );+ }+ // Regular user+ return replyingTo.userID ===+ currentUserID+ ? "yourself"+ : (prefetchedUserIDToEmail?.get(+ replyingTo.userID,+ ) ?? "User");+ })()}...</Typography><Typographydiff --git a/web/packages/gallery/components/viewer/FeedSidebar.tsx b/web/packages/gallery/components/viewer/FeedSidebar.tsxindex 0bb5faeef8..353a24a96e 100644--- a/web/packages/gallery/components/viewer/FeedSidebar.tsx+++ b/web/packages/gallery/components/viewer/FeedSidebar.tsx@@ -339,8 +339,15 @@ const processFeedItems = (for (const c of comments) {if (c.isDeleted) continue;- // Look up display name from userID- const displayName = users.get(c.userID) ?? "User";+ // Look up display name - check for anonymous users first+ const isAnonymous = !!c.anonUserID;+ const displayName = isAnonymous+ ? getAnonUserName(c.anonUserID)+ : getUserName(c.userID);+ // Use anonUserID for avatar color (consistent with LikesSidebar)+ const avatarColorKey = isAnonymous+ ? (c.anonUserID ?? "anonymous")+ : getUserName(c.userID);// Only show "Replied to your comment" if the parent comment belongs to// the current user. Otherwise show "Commented on your photo".@@ -361,7 +368,7 @@ const processFeedItems = (userID: c.userID,anonUserID: c.anonUserID,userName: displayName,- email: displayName,+ email: avatarColorKey,},});} else {@@ -378,7 +385,7 @@ const processFeedItems = (userID: c.userID,anonUserID: c.anonUserID,userName: displayName,- email: displayName,+ email: avatarColorKey,},});}diff --git a/web/packages/gallery/components/viewer/FileViewer.tsx b/web/packages/gallery/components/viewer/FileViewer.tsxindex 8cc88e4e51..d06b46faa1 100644--- a/web/packages/gallery/components/viewer/FileViewer.tsx+++ b/web/packages/gallery/components/viewer/FileViewer.tsx@@ -48,8 +48,8 @@ import {createAnonIdentity,deletePublicReaction,getPublicAnonProfiles,- getPublicFileReactions,getPublicParticipantsMaskedEmails,+ getPublicSocialDiff,getStoredAnonIdentity,} from "ente-new/albums/services/public-reaction";import {@@ -2050,7 +2050,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({isFileInSharedCollection,]);- // Fetch reactions for public albums (when viewing as anonymous user).+ // Fetch social data (comments + reactions) for public albums (when viewing as anonymous user).useEffect(() => {if (!open ||@@ -2065,12 +2065,36 @@ export const FileViewer: React.FC<FileViewerProps> = ({void (async () => {try {- const reactions = await getPublicFileReactions(+ // Fetch both comments and reactions in a single API call+ const { comments, reactions } = await getPublicSocialDiff(publicAlbumsCredentials,activeFileID,collectionKey,);+ // Convert PublicComment to Comment format+ const commentsForFile: Comment[] = comments.map((c) => ({+ id: c.id,+ collectionID: c.collectionID,+ fileID: c.fileID,+ parentCommentID: c.parentCommentID,+ userID: c.userID,+ anonUserID: c.anonUserID,+ text: c.text,+ isDeleted: c.isDeleted,+ createdAt: c.createdAt,+ updatedAt: c.updatedAt,+ }));++ const commentsMap = new Map<number, Comment[]>();+ commentsMap.set(file.collectionID, commentsForFile);++ setFileComments((prev) => {+ const next = new Map(prev);+ next.set(activeFileID, commentsMap);+ return next;+ });+// Convert PublicReaction to UnifiedReaction formatconst unifiedReactions: UnifiedReaction[] = reactions.map((r) => ({@@ -2130,7 +2154,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({// Ignore participants fetch failures}} catch (e) {- log.error("Failed to fetch public reactions", e);+ log.error("Failed to fetch public social data", e);}})();}, [open, activeFileID, publicAlbumsCredentials, collectionKey, files]);@@ -2264,6 +2288,9 @@ export const FileViewer: React.FC<FileViewerProps> = ({onCommentReactionAdded={handleCommentReactionAdded}onCommentReactionDeleted={handleCommentReactionDeleted}highlightCommentID={highlightCommentID}+ publicAlbumsCredentials={publicAlbumsCredentials}+ collectionKey={collectionKey}+ anonUserNames={anonUserNames}/><LikesSidebaropen={openLikes}diff --git a/web/packages/new/albums/services/public-comment.ts b/web/packages/new/albums/services/public-comment.tsnew file mode 100644index 0000000000..f03590c96a--- /dev/null+++ b/web/packages/new/albums/services/public-comment.ts@@ -0,0 +1,250 @@+import { decryptBox, encryptBox } from "ente-base/crypto";+import {+ authenticatedPublicAlbumsRequestHeaders,+ ensureOk,+ type PublicAlbumsCredentials,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { z } from "zod";+import { type AnonIdentity, getStoredAnonIdentity } from "./public-reaction";++/**+ * A decrypted public comment.+ */+export interface PublicComment {+ id: string;+ collectionID: number;+ fileID?: number;+ parentCommentID?: string;+ userID: number;+ anonUserID?: string;+ /** The decrypted comment text. */+ text: string;+ isDeleted: boolean;+ createdAt: number;+ updatedAt: number;+}++/**+ * Add a comment to a file in a public album (as an anonymous user).+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID for looking up stored identity.+ * @param fileID The ID of the file to comment on.+ * @param text The comment text.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @param parentCommentID Optional parent comment ID for replies.+ * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.+ * @returns The ID of the created comment.+ */+export const addPublicComment = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ fileID: number,+ text: string,+ collectionKey: string,+ parentCommentID?: string,+ anonIdentity?: AnonIdentity,+): Promise<string> => {+ const identity = anonIdentity ?? getStoredAnonIdentity(collectionID);+ if (!identity) {+ throw new Error("No anonymous identity available");+ }++ const { encryptedData: cipher, nonce } = await encryptBox(+ new TextEncoder().encode(text),+ collectionKey,+ );++ const res = await fetch(await apiURL("/public-collection/comments"), {+ method: "POST",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ fileID,+ cipher,+ nonce,+ parentCommentID,+ anonUserID: identity.anonUserID,+ anonToken: identity.token,+ }),+ });+ ensureOk(res);+ const { id } = CreateCommentResponse.parse(await res.json());+ return id;+};++/**+ * Update a comment in a public album (as an anonymous user).+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID for looking up stored identity.+ * @param commentID The ID of the comment to update.+ * @param text The new comment text.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.+ */+export const updatePublicComment = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ commentID: string,+ text: string,+ collectionKey: string,+ anonIdentity?: AnonIdentity,+): Promise<void> => {+ const identity = anonIdentity ?? getStoredAnonIdentity(collectionID);+ if (!identity) {+ throw new Error("No anonymous identity available");+ }++ const { encryptedData: cipher, nonce } = await encryptBox(+ new TextEncoder().encode(text),+ collectionKey,+ );++ const res = await fetch(+ await apiURL(`/public-collection/comments/${commentID}`),+ {+ method: "PATCH",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ cipher,+ nonce,+ anonUserID: identity.anonUserID,+ anonToken: identity.token,+ }),+ },+ );+ ensureOk(res);+};++/**+ * Delete a comment from a public album (as an anonymous user).+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID for looking up stored identity.+ * @param commentID The ID of the comment to delete.+ * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.+ */+export const deletePublicComment = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ commentID: string,+ anonIdentity?: AnonIdentity,+): Promise<void> => {+ const identity = anonIdentity ?? getStoredAnonIdentity(collectionID);+ if (!identity) {+ throw new Error("No anonymous identity available");+ }++ const res = await fetch(+ await apiURL(`/public-collection/comments/${commentID}`),+ {+ method: "DELETE",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ anonUserID: identity.anonUserID,+ anonToken: identity.token,+ }),+ },+ );+ ensureOk(res);+};++/**+ * Get comments for a file in a public album.+ *+ * @param credentials Public album credentials (access token).+ * @param fileID The ID of the file to get comments for.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns Array of decrypted comments for the file.+ */+export const getPublicFileComments = async (+ credentials: PublicAlbumsCredentials,+ fileID: number,+ collectionKey: string,+): Promise<PublicComment[]> => {+ const res = await fetch(+ await apiURL("/public-collection/comments/diff", {+ fileID,+ sinceTime: 0,+ limit: 1000,+ }),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ const { comments } = GetPublicCommentsResponse.parse(await res.json());++ const decryptedComments: PublicComment[] = [];+ for (const comment of comments) {+ // Include deleted comments with empty text+ if (comment.isDeleted || !comment.cipher || !comment.nonce) {+ decryptedComments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text: "",+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ });+ continue;+ }+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: comment.cipher, nonce: comment.nonce },+ collectionKey,+ );+ const text = new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ );+ decryptedComments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text,+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ });+ } catch {+ // Skip comments that fail to decrypt+ }+ }+ return decryptedComments;+};++const CreateCommentResponse = z.object({ id: z.string() });++const RemotePublicComment = 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 GetPublicCommentsResponse = z.object({+ comments: z.array(RemotePublicComment),+ hasMore: z.boolean(),+});diff --git a/web/packages/new/albums/services/public-reaction.ts b/web/packages/new/albums/services/public-reaction.tsindex 46fa85773e..479da64cfb 100644--- a/web/packages/new/albums/services/public-reaction.ts+++ b/web/packages/new/albums/services/public-reaction.ts@@ -186,6 +186,54 @@ export const addPublicReaction = async (return id;};+/**+ * Add a reaction to a comment in a public album (as an anonymous user).+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID for looking up stored identity.+ * @param commentID The ID of the comment to react to.+ * @param reactionType The type of reaction (e.g., "green_heart").+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.+ * @returns The ID of the created reaction.+ */+export const addPublicCommentReaction = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ commentID: string,+ reactionType: string,+ collectionKey: string,+ anonIdentity?: AnonIdentity,+): Promise<string> => {+ const identity = anonIdentity ?? getStoredAnonIdentity(collectionID);+ if (!identity) {+ throw new Error("No anonymous identity available");+ }++ const { encryptedData: cipher, nonce } = await encryptBox(+ new TextEncoder().encode(padReaction(reactionType)),+ collectionKey,+ );++ const res = await fetch(await apiURL("/public-collection/reactions"), {+ method: "POST",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ commentID,+ cipher,+ nonce,+ anonUserID: identity.anonUserID,+ anonToken: identity.token,+ }),+ });+ ensureOk(res);+ const { id } = UpsertReactionResponse.parse(await res.json());+ return id;+};+/*** Delete a reaction from a public album (as an anonymous user).*@@ -258,9 +306,7 @@ export const getPublicFileReactions = async (sinceTime: 0,limit: 100,}),- {- headers: authenticatedPublicAlbumsRequestHeaders(credentials),- },+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },);ensureOk(res);const { reactions } = GetPublicReactionsResponse.parse(await res.json());@@ -335,12 +381,9 @@ export const getPublicAnonProfiles = async (credentials: PublicAlbumsCredentials,collectionKey: string,): Promise<Map<string, string>> => {- const res = await fetch(- await apiURL("/public-collection/anon-profiles"),- {- headers: authenticatedPublicAlbumsRequestHeaders(credentials),- },- );+ const res = await fetch(await apiURL("/public-collection/anon-profiles"), {+ headers: authenticatedPublicAlbumsRequestHeaders(credentials),+ });ensureOk(res);const { profiles } = GetAnonProfilesResponse.parse(await res.json());@@ -401,9 +444,7 @@ export const getPublicParticipantsMaskedEmails = async (): Promise<Map<number, string>> => {const res = await fetch(await apiURL("/public-collection/participants/masked-emails"),- {- headers: authenticatedPublicAlbumsRequestHeaders(credentials),- },+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },);ensureOk(res);const { participants } = GetParticipantsResponse.parse(await res.json());@@ -423,3 +464,154 @@ const RemoteParticipant = z.object({const GetParticipantsResponse = z.object({participants: z.array(RemoteParticipant),});++// =============================================================================+// Unified Social Diff+// =============================================================================++/**+ * A decrypted public comment.+ */+export interface PublicComment {+ id: string;+ collectionID: number;+ fileID?: number;+ parentCommentID?: string;+ userID: number;+ anonUserID?: string;+ text: string;+ isDeleted: boolean;+ createdAt: number;+ updatedAt: number;+}++/**+ * Result of fetching unified social diff.+ */+export interface PublicSocialDiff {+ comments: PublicComment[];+ reactions: PublicReaction[];+}++/**+ * Get both comments and reactions for a file in a public album in a single API call.+ *+ * @param credentials Public album credentials (access token).+ * @param fileID The ID of the file to get social data for.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns Object containing both decrypted comments and reactions.+ */+export const getPublicSocialDiff = async (+ credentials: PublicAlbumsCredentials,+ fileID: number,+ collectionKey: string,+): Promise<PublicSocialDiff> => {+ const res = await fetch(+ await apiURL("/public-collection/social/diff", {+ fileID,+ sinceTime: 0,+ limit: 1000,+ }),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ const data = GetPublicSocialDiffResponse.parse(await res.json());++ // Decrypt comments+ const comments: PublicComment[] = [];+ for (const comment of data.comments) {+ // Include deleted comments with empty text+ 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,+ text: "",+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ });+ continue;+ }+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: comment.cipher, nonce: comment.nonce },+ collectionKey,+ );+ const text = new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ );+ comments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text,+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ });+ } catch {+ // Skip comments that fail to decrypt+ }+ }++ // Decrypt reactions+ const reactions: PublicReaction[] = [];+ for (const reaction of data.reactions) {+ // Skip deleted reactions (they have null cipher/nonce)+ 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,+ fileID: reaction.fileID ?? fileID,+ 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 };+};++const RemotePublicComment = 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 GetPublicSocialDiffResponse = z.object({+ comments: z.array(RemotePublicComment),+ reactions: z.array(RemotePublicReaction),+ hasMoreComments: z.boolean(),+ hasMoreReactions: z.boolean(),+});