Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add anonymous reactions support for public albums

Anand Baburajan562c4f2e8caa
diff --git a/web/apps/photos/src/components/FileListWithViewer.tsx b/web/apps/photos/src/components/FileListWithViewer.tsx
index 43631ee744..39c2f6a6f5 100644
--- a/web/apps/photos/src/components/FileListWithViewer.tsx
+++ b/web/apps/photos/src/components/FileListWithViewer.tsx
@@ -125,6 +125,8 @@ export type FileListWithViewerProps = {
| "onFileVisibilityUpdate"
| "onSelectCollection"
| "onSelectPerson"
+ | "publicAlbumsCredentials"
+ | "collectionKey"
>;
/**
@@ -176,6 +178,8 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({
pendingFileSidebar,
pendingHighlightCommentID,
onPendingNavigationConsumed,
+ publicAlbumsCredentials,
+ collectionKey,
}) => {
const [openFileViewer, setOpenFileViewer] = useState(false);
const [currentIndex, setCurrentIndex] = useState(0);
@@ -371,6 +375,8 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({
onFileVisibilityUpdate,
onSelectCollection,
onSelectPerson,
+ publicAlbumsCredentials,
+ collectionKey,
}}
onTriggerRemotePull={handleTriggerRemotePull}
onDownload={handleDownload}
diff --git a/web/apps/photos/src/components/TripLayout/index.tsx b/web/apps/photos/src/components/TripLayout/index.tsx
index 6cece0d676..4d31451ef8 100644
--- a/web/apps/photos/src/components/TripLayout/index.tsx
+++ b/web/apps/photos/src/components/TripLayout/index.tsx
@@ -514,6 +514,8 @@ export const TripLayout: React.FC<TripLayoutProps> = ({
onVisualFeedback={() => {
// No-op: Trip viewer is read-only and doesn't need visual feedback
}}
+ publicAlbumsCredentials={credentials?.current}
+ collectionKey={collectionKey}
/>
{/* Download progress notifications */}
diff --git a/web/apps/photos/src/pages/shared-albums.tsx b/web/apps/photos/src/pages/shared-albums.tsx
index c3b9ce8f52..bee78da9c0 100644
--- a/web/apps/photos/src/pages/shared-albums.tsx
+++ b/web/apps/photos/src/pages/shared-albums.tsx
@@ -589,6 +589,8 @@ export default function PublicCollectionGallery() {
onRemotePull={publicAlbumsRemotePull}
onVisualFeedback={handleVisualFeedback}
onAddSaveGroup={onAddSaveGroup}
+ publicAlbumsCredentials={credentials.current}
+ collectionKey={collectionKey.current}
/>
</>
)}
diff --git a/web/packages/gallery/components/viewer/FileViewer.tsx b/web/packages/gallery/components/viewer/FileViewer.tsx
index b7d1d0122a..b71eb4cf55 100644
--- a/web/packages/gallery/components/viewer/FileViewer.tsx
+++ b/web/packages/gallery/components/viewer/FileViewer.tsx
@@ -30,6 +30,7 @@ import { useIsSmallWidth } from "ente-base/components/utils/hooks";
import { type ModalVisibilityProps } from "ente-base/components/utils/modal";
import { useBaseContext } from "ente-base/context";
import { lowercaseExtension } from "ente-base/file-name";
+import type { PublicAlbumsCredentials } from "ente-base/http";
import { formattedListJoin, ut } from "ente-base/i18n";
import log from "ente-base/log";
import {
@@ -42,6 +43,13 @@ import { fileFileName, ItemVisibility } 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";
+import {
+ addPublicReaction,
+ createAnonIdentity,
+ deletePublicReaction,
+ getPublicFileReactions,
+ getStoredAnonIdentity,
+} from "ente-new/albums/services/public-reaction";
import {
ImageEditorOverlay,
type ImageEditorOverlayProps,
@@ -319,6 +327,16 @@ export type FileViewerProps = ModalVisibilityProps & {
* The ID of the currently active collection, if any (e.g., when viewing an album).
*/
activeCollectionID?: number;
+ /**
+ * Public album credentials for anonymous reactions/comments.
+ * Required when viewing a public album (no logged in user).
+ */
+ publicAlbumsCredentials?: PublicAlbumsCredentials;
+ /**
+ * The decrypted collection key (base64 encoded) for encrypting reactions.
+ * Required when viewing a public album (no logged in user).
+ */
+ collectionKey?: string;
} & Pick<
FileInfoProps,
"collectionNameByID" | "onSelectCollection" | "onSelectPerson"
@@ -358,6 +376,8 @@ export const FileViewer: React.FC<FileViewerProps> = ({
onSaveEditedImageCopy,
onAddFileToCollection,
activeCollectionID,
+ publicAlbumsCredentials,
+ collectionKey,
}) => {
const { onGenericError } = useBaseContext();
@@ -482,18 +502,31 @@ export const FileViewer: React.FC<FileViewerProps> = ({
const fileReactionsMap = allReactionsRef.current.get(fileId);
if (!fileReactionsMap) return [];
+ // Get stored anonymous identity for public album users
+ const storedAnonIdentity = getStoredAnonIdentity();
+
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,
- );
+ const userFileReaction = reactions.find((r) => {
+ if (
+ r.commentID ||
+ r.fileID !== fileId ||
+ r.reactionType !== "green_heart"
+ )
+ return false;
+ // Check for logged-in user
+ if (user?.id && r.userID === user.id) return true;
+ // Check for anonymous user
+ if (
+ storedAnonIdentity &&
+ r.anonUserID === storedAnonIdentity.anonUserID
+ )
+ return true;
+ return false;
+ });
if (userFileReaction) {
userReactions.push({
collectionId,
@@ -654,7 +687,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({
activeAnnotatedFileRef.current = activeAnnotatedFile;
// Called when the like button (heart) is clicked.
- // - If public album (has ?t=): show PublicLikeModal
+ // - If public album (has ?t=): toggle like (unlike if already liked, else show modal)
// - If gallery view: show album selector (like) OR unlike selector/direct delete
// - If collection view: toggle like in that collection
const handleLikeClick = useCallback(() => {
@@ -665,8 +698,112 @@ export const FileViewer: React.FC<FileViewerProps> = ({
const isPublicAlbum = searchParams.has("t");
if (isPublicAlbum) {
- // Public album - show public like modal
- setOpenPublicLikeModal(true);
+ const file = activeAnnotatedFileRef.current?.file;
+ if (!file || !publicAlbumsCredentials) {
+ setOpenPublicLikeModal(true);
+ return;
+ }
+
+ const fileId = file.id;
+ const collectionId = file.collectionID;
+ const storedAnonIdentity = getStoredAnonIdentity();
+
+ // Check if already liked by current anon user
+ const fileReactionsMap = allReactionsRef.current.get(fileId);
+ const collectionReactions =
+ fileReactionsMap?.get(collectionId) ?? [];
+ const existingReaction = collectionReactions.find(
+ (r) =>
+ r.reactionType === "green_heart" &&
+ storedAnonIdentity &&
+ r.anonUserID === storedAnonIdentity.anonUserID,
+ );
+
+ if (existingReaction) {
+ // Already liked - unlike (delete reaction)
+ void (async () => {
+ try {
+ await deletePublicReaction(
+ publicAlbumsCredentials,
+ existingReaction.id,
+ );
+ log.info(
+ `Deleted public reaction: ${existingReaction.id}`,
+ );
+
+ // Update local state
+ setAllReactions((prev) => {
+ const next = new Map(prev);
+ const fileReactionsMap = new Map(
+ prev.get(fileId) ?? new Map(),
+ );
+ const updatedReactions = (
+ fileReactionsMap.get(collectionId) ?? []
+ ).filter(
+ (r: UnifiedReaction) =>
+ r.id !== existingReaction.id,
+ );
+ fileReactionsMap.set(
+ collectionId,
+ updatedReactions,
+ );
+ next.set(fileId, fileReactionsMap);
+ return next;
+ });
+ } catch (e) {
+ log.error("Failed to delete public reaction", e);
+ }
+ })();
+ } else if (storedAnonIdentity) {
+ // Has identity but not liked - add reaction directly
+ void (async () => {
+ try {
+ if (!collectionKey) {
+ log.error(
+ "Missing collection key for public reaction",
+ );
+ return;
+ }
+ const reactionId = await addPublicReaction(
+ publicAlbumsCredentials,
+ fileId,
+ "green_heart",
+ collectionKey,
+ );
+
+ // Update local state
+ setAllReactions((prev) => {
+ const next = new Map(prev);
+ 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: 0,
+ anonUserID: storedAnonIdentity.anonUserID,
+ isDeleted: false,
+ createdAt: Date.now() * 1000,
+ updatedAt: Date.now() * 1000,
+ },
+ ]);
+ next.set(fileId, fileReactionsMap);
+ return next;
+ });
+ } catch (e) {
+ log.error("Failed to add public reaction", e);
+ }
+ })();
+ } else {
+ // No identity - show modal to get name
+ setOpenPublicLikeModal(true);
+ }
return;
}
@@ -851,7 +988,13 @@ export const FileViewer: React.FC<FileViewerProps> = ({
})();
}
}
- }, [activeCollectionID, getUserFileReactions, user?.id]);
+ }, [
+ activeCollectionID,
+ getUserFileReactions,
+ user?.id,
+ publicAlbumsCredentials,
+ collectionKey,
+ ]);
const handleLikeAlbumSelectorClose = useCallback(
() => setOpenLikeAlbumSelector(false),
@@ -1041,12 +1184,91 @@ export const FileViewer: React.FC<FileViewerProps> = ({
[],
);
- const handleAddNameSubmit = useCallback((name: string) => {
- // TODO: Implement like with name when API is available
- console.log("Like with name:", name);
- setOpenAddNameModal(false);
- setOpenLikes(true);
- }, []);
+ const handleAddNameSubmit = useCallback(
+ (name: string) => {
+ const file = activeAnnotatedFileRef.current?.file;
+ if (!file || !publicAlbumsCredentials || !collectionKey) {
+ log.error(
+ "Missing file, credentials, or collection key for public reaction",
+ );
+ setOpenAddNameModal(false);
+ return;
+ }
+
+ const fileId = file.id;
+ // Use file.collectionID for public albums since activeCollectionID is a pseudo ID (0)
+ const collectionId =
+ activeCollectionID && activeCollectionID > 0
+ ? activeCollectionID
+ : file.collectionID;
+
+ void (async () => {
+ try {
+ // Check if we already have an anon identity, otherwise create one
+ let identity = getStoredAnonIdentity();
+ if (!identity) {
+ identity = await createAnonIdentity(
+ publicAlbumsCredentials,
+ name,
+ collectionKey,
+ );
+ log.info(
+ `Created anonymous identity: ${identity.anonUserID}`,
+ );
+ }
+
+ // Add the public reaction
+ const reactionId = await addPublicReaction(
+ publicAlbumsCredentials,
+ fileId,
+ "green_heart",
+ collectionKey,
+ identity,
+ );
+
+ // Update local state
+ setAllReactions((prev) => {
+ const next = new Map(prev);
+ 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",
+ // Use a special userID for anonymous users (derived from anonUserID)
+ userID: 0,
+ anonUserID: identity.anonUserID,
+ isDeleted: false,
+ createdAt: Date.now() * 1000,
+ updatedAt: Date.now() * 1000,
+ },
+ ]);
+ next.set(fileId, fileReactionsMap);
+ return next;
+ });
+
+ setOpenAddNameModal(false);
+ setOpenLikes(true);
+ } catch (e) {
+ log.error("Failed to add public reaction", e);
+ onGenericError(e);
+ setOpenAddNameModal(false);
+ }
+ })();
+ },
+ [
+ activeCollectionID,
+ publicAlbumsCredentials,
+ collectionKey,
+ onGenericError,
+ ],
+ );
// Callback invoked when the download action is triggered by activating the
// download button in the PhotoSwipe bar.
@@ -1323,14 +1545,25 @@ export const FileViewer: React.FC<FileViewerProps> = ({
// Get the set of liked album IDs from allReactions
const fileReactionsMap = allReactions.get(file.id);
const likedAlbumIDs = new Set<number>();
+
+ // Get stored anonymous identity for public album users
+ const storedAnonIdentity = getStoredAnonIdentity();
+
if (fileReactionsMap) {
for (const [collectionId, reactions] of fileReactionsMap) {
- const hasUserLike = reactions.some(
- (r) =>
- !r.commentID &&
- r.reactionType === "green_heart" &&
- r.userID === user?.id,
- );
+ const hasUserLike = reactions.some((r) => {
+ if (r.commentID || r.reactionType !== "green_heart")
+ return false;
+ // Check for logged-in user
+ if (user?.id && r.userID === user.id) return true;
+ // Check for anonymous user
+ if (
+ storedAnonIdentity &&
+ r.anonUserID === storedAnonIdentity.anonUserID
+ )
+ return true;
+ return false;
+ });
if (hasUserLike) {
likedAlbumIDs.add(collectionId);
}
@@ -1383,14 +1616,24 @@ export const FileViewer: React.FC<FileViewerProps> = ({
const fileReactionsMap = allReactions.get(file.id);
if (!fileReactionsMap) return false;
+ // Get stored anonymous identity for public album users
+ const storedAnonIdentity = getStoredAnonIdentity();
+
// 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,
- );
+ const hasUserLike = reactions.some((r) => {
+ if (r.commentID || r.reactionType !== "green_heart")
+ return false;
+ // Check for logged-in user
+ if (user?.id && r.userID === user.id) return true;
+ // Check for anonymous user
+ if (
+ storedAnonIdentity &&
+ r.anonUserID === storedAnonIdentity.anonUserID
+ )
+ return true;
+ return false;
+ });
if (hasUserLike) return true;
}
return false;
@@ -1761,6 +2004,57 @@ export const FileViewer: React.FC<FileViewerProps> = ({
isFileInSharedCollection,
]);
+ // Fetch reactions for public albums (when viewing as anonymous user).
+ useEffect(() => {
+ if (
+ !open ||
+ !activeFileID ||
+ !publicAlbumsCredentials ||
+ !collectionKey
+ )
+ return;
+
+ const file = files.find((f) => f.id === activeFileID);
+ if (!file) return;
+
+ void (async () => {
+ try {
+ const reactions = await getPublicFileReactions(
+ publicAlbumsCredentials,
+ activeFileID,
+ collectionKey,
+ );
+
+ // Convert PublicReaction to UnifiedReaction format
+ const unifiedReactions: UnifiedReaction[] = reactions.map(
+ (r) => ({
+ id: r.id,
+ collectionID: file.collectionID,
+ fileID: r.fileID,
+ commentID: r.commentID,
+ reactionType: r.reactionType,
+ userID: r.userID,
+ anonUserID: r.anonUserID,
+ isDeleted: r.isDeleted,
+ createdAt: r.createdAt,
+ updatedAt: r.updatedAt,
+ }),
+ );
+
+ const reactionsMap = new Map<number, UnifiedReaction[]>();
+ reactionsMap.set(file.collectionID, unifiedReactions);
+
+ setAllReactions((prev) => {
+ const next = new Map(prev);
+ next.set(activeFileID, reactionsMap);
+ return next;
+ });
+ } catch (e) {
+ log.error("Failed to fetch public reactions", e);
+ }
+ })();
+ }, [open, activeFileID, publicAlbumsCredentials, collectionKey, files]);
+
// Refresh comment count when fileComments changes.
useEffect(() => {
if (open && files.length) {
diff --git a/web/packages/gallery/components/viewer/LikesSidebar.tsx b/web/packages/gallery/components/viewer/LikesSidebar.tsx
index ae15ddccea..d41e1860b6 100644
--- a/web/packages/gallery/components/viewer/LikesSidebar.tsx
+++ b/web/packages/gallery/components/viewer/LikesSidebar.tsx
@@ -14,6 +14,7 @@ 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 { getStoredAnonIdentity } from "ente-new/albums/services/public-reaction";
import type { CollectionSummaries } from "ente-new/photos/services/collection-summary";
import { type UnifiedReaction } from "ente-new/photos/services/social";
import React, {
@@ -71,6 +72,7 @@ const HeartFilledIcon: React.FC = () => (
interface Liker {
id: string;
userID: number;
+ anonUserID?: string;
userName: string;
/** The actual email for avatar color, even when userName is "You". */
email: string;
@@ -159,6 +161,13 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({
const fileCollectionIDs = useMemo(() => {
if (!file) return [];
const allCollectionIDs = fileNormalCollectionIDs?.get(file.id) ?? [];
+
+ // If no collection IDs from fileNormalCollectionIDs (e.g., public album),
+ // use the file's collection ID directly
+ if (allCollectionIDs.length === 0) {
+ return [file.collectionID];
+ }
+
// Filter to only include shared collections
return allCollectionIDs.filter((id) =>
collectionSummaries?.get(id)?.attributes.has("shared"),
@@ -209,16 +218,42 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({
if (!selectedCollectionInfo) return [];
const reactions =
reactionsByCollection.get(selectedCollectionInfo.id) ?? [];
+
+ // Get stored anonymous identity to check if current anon user
+ const storedAnonIdentity = getStoredAnonIdentity();
+
return reactions
.filter((r) => r.reactionType === "green_heart")
.map((r) => {
- const email =
- prefetchedUserIDToEmail?.get(r.userID) ??
- `User ${r.userID}`;
+ // Check if this is an anonymous user
+ const isAnonymous =
+ r.anonUserID || r.userID === 0 || r.userID === -1;
+
+ // Check if this is the current user (logged-in or anonymous)
+ const isCurrentUser = r.userID === currentUserID;
+ const isCurrentAnonUser =
+ storedAnonIdentity &&
+ r.anonUserID === storedAnonIdentity.anonUserID;
+
+ let email: string;
+ let userName: string;
+
+ if (isAnonymous) {
+ email = r.anonUserID ?? "anonymous";
+ userName =
+ isCurrentAnonUser ? "You" : `Anonymous ${r.anonUserID?.slice(-4) ?? ""}`;
+ } else {
+ email =
+ prefetchedUserIDToEmail?.get(r.userID) ??
+ `User ${r.userID}`;
+ userName = isCurrentUser ? "You" : email;
+ }
+
return {
id: r.id,
userID: r.userID,
- userName: r.userID === currentUserID ? "You" : email,
+ anonUserID: r.anonUserID,
+ userName,
email,
};
});
diff --git a/web/packages/new/albums/services/public-reaction.ts b/web/packages/new/albums/services/public-reaction.ts
new file mode 100644
index 0000000000..ac0b5962b1
--- /dev/null
+++ b/web/packages/new/albums/services/public-reaction.ts
@@ -0,0 +1,292 @@
+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";
+
+/**
+ * Fixed length for padded reaction types.
+ * All reactions are padded to this length before encryption to prevent
+ * length-based analysis of the ciphertext.
+ * Max emoji name is ~70 chars, so 100 provides a safe buffer.
+ */
+const paddedReactionLength = 100;
+
+/**
+ * Pad a reaction type to a fixed length using null bytes.
+ */
+const padReaction = (reactionType: string): string =>
+ reactionType.padEnd(paddedReactionLength, "\0");
+
+/**
+ * Remove null byte padding from a decrypted reaction type.
+ */
+const unpadReaction = (paddedReaction: string): string =>
+ paddedReaction.replace(/\0+$/, "");
+
+/**
+ * Anonymous user identity returned when creating an anon identity.
+ */
+export interface AnonIdentity {
+ anonUserID: string;
+ token: string;
+ expiresAt: number;
+}
+
+/**
+ * Storage key for anonymous identity in local storage.
+ */
+const ANON_IDENTITY_STORAGE_KEY = "ente_anon_identity";
+
+/**
+ * Get the stored anonymous identity from local storage, if any.
+ */
+export const getStoredAnonIdentity = (): AnonIdentity | undefined => {
+ if (typeof window === "undefined") return undefined;
+ const stored = localStorage.getItem(ANON_IDENTITY_STORAGE_KEY);
+ if (!stored) return undefined;
+ try {
+ return JSON.parse(stored) as AnonIdentity;
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * Store the anonymous identity in local storage.
+ */
+export const storeAnonIdentity = (identity: AnonIdentity): void => {
+ if (typeof window === "undefined") return;
+ localStorage.setItem(ANON_IDENTITY_STORAGE_KEY, JSON.stringify(identity));
+};
+
+/**
+ * Clear the stored anonymous identity from local storage.
+ */
+export const clearAnonIdentity = (): void => {
+ if (typeof window === "undefined") return;
+ localStorage.removeItem(ANON_IDENTITY_STORAGE_KEY);
+};
+
+/**
+ * Create an anonymous identity for a public album.
+ *
+ * The server will return a unique anonymous user ID and a token that can be
+ * used to authenticate future requests (reactions, comments) from this
+ * anonymous user.
+ *
+ * @param credentials Public album credentials (access token).
+ * @param userName The name entered by the user.
+ * @param collectionKey The decrypted collection key (base64 encoded).
+ * @returns The anonymous identity containing anonUserID and token.
+ */
+export const createAnonIdentity = async (
+ credentials: PublicAlbumsCredentials,
+ userName: string,
+ collectionKey: string,
+): Promise<AnonIdentity> => {
+ // Encrypt the user name using the collection key
+ const { encryptedData: cipher, nonce } = await encryptBox(
+ new TextEncoder().encode(JSON.stringify({ userName })),
+ collectionKey,
+ );
+
+ const res = await fetch(await apiURL("/public-collection/anon-identity"), {
+ method: "POST",
+ headers: {
+ ...authenticatedPublicAlbumsRequestHeaders(credentials),
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ cipher, nonce }),
+ });
+ ensureOk(res);
+ const identity = AnonIdentityResponse.parse(await res.json());
+
+ // Store the identity for future use
+ storeAnonIdentity(identity);
+
+ return identity;
+};
+
+const AnonIdentityResponse = z.object({
+ anonUserID: z.string(),
+ token: z.string(),
+ expiresAt: z.number(),
+});
+
+/**
+ * Add a reaction to a file in a public album (as an anonymous user).
+ *
+ * @param credentials Public album credentials (access token).
+ * @param fileID The ID of the file 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 addPublicReaction = async (
+ credentials: PublicAlbumsCredentials,
+ fileID: number,
+ reactionType: string,
+ collectionKey: string,
+ anonIdentity?: AnonIdentity,
+): Promise<string> => {
+ const identity = anonIdentity ?? getStoredAnonIdentity();
+ 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({
+ fileID,
+ 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).
+ *
+ * @param credentials Public album credentials (access token).
+ * @param reactionID The ID of the reaction to delete.
+ * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.
+ */
+export const deletePublicReaction = async (
+ credentials: PublicAlbumsCredentials,
+ reactionID: string,
+ anonIdentity?: AnonIdentity,
+): Promise<void> => {
+ const identity = anonIdentity ?? getStoredAnonIdentity();
+ if (!identity) {
+ throw new Error("No anonymous identity available");
+ }
+
+ const res = await fetch(
+ await apiURL(`/public-collection/reactions/${reactionID}`),
+ {
+ method: "DELETE",
+ headers: {
+ ...authenticatedPublicAlbumsRequestHeaders(credentials),
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ anonUserID: identity.anonUserID,
+ anonToken: identity.token,
+ }),
+ },
+ );
+ ensureOk(res);
+};
+
+const UpsertReactionResponse = z.object({ id: z.string() });
+
+/**
+ * A decrypted public reaction.
+ */
+export interface PublicReaction {
+ id: string;
+ fileID: number;
+ commentID?: string;
+ reactionType: string;
+ userID: number;
+ anonUserID?: string;
+ isDeleted: boolean;
+ createdAt: number;
+ updatedAt: number;
+}
+
+/**
+ * Get reactions for a file in a public album.
+ *
+ * @param credentials Public album credentials (access token).
+ * @param fileID The ID of the file to get reactions for.
+ * @param collectionKey The decrypted collection key (base64 encoded).
+ * @returns Array of decrypted reactions for the file.
+ */
+export const getPublicFileReactions = async (
+ credentials: PublicAlbumsCredentials,
+ fileID: number,
+ collectionKey: string,
+): Promise<PublicReaction[]> => {
+ const res = await fetch(
+ await apiURL("/public-collection/reactions/diff", {
+ fileID,
+ sinceTime: 0,
+ limit: 100,
+ }),
+ {
+ headers: authenticatedPublicAlbumsRequestHeaders(credentials),
+ },
+ );
+ ensureOk(res);
+ const { reactions } = GetPublicReactionsResponse.parse(await res.json());
+
+ const decryptedReactions: PublicReaction[] = [];
+ for (const reaction of 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)),
+ ),
+ );
+ decryptedReactions.push({
+ id: reaction.id,
+ fileID: reaction.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 decryptedReactions;
+};
+
+const RemotePublicReaction = z.object({
+ id: z.string(),
+ collectionID: z.number(),
+ fileID: z.number(),
+ 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 GetPublicReactionsResponse = z.object({
+ reactions: z.array(RemotePublicReaction),
+ hasMore: z.boolean(),
+});