Skip to content

armgit / ente

Public Imported from GitHub
0

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

Remove non-public social code from albums app

Anand Baburajane867d294cd5a
diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/CommentsSidebar.tsx b/web/apps/albums/vendor/ente-gallery/components/viewer/CommentsSidebar.tsx
index c26add8e5a..3ce8b7dbfb 100644
--- a/web/apps/albums/vendor/ente-gallery/components/viewer/CommentsSidebar.tsx
+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/CommentsSidebar.tsx
@@ -15,7 +15,6 @@ import {
import { type ModalVisibilityProps } from "ente-base/components/utils/modal";
import type { PublicAlbumsCredentials } from "ente-base/http";
import log from "ente-base/log";
-import { isOfficialAlbumsApp } from "ente-base/origins";
import { downloadManager } from "ente-gallery/services/download";
import { getAvatarColor } from "ente-gallery/utils/avatar-colors";
import type { EnteFile } from "ente-media/file";
@@ -29,18 +28,7 @@ import {
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 {
- addComment,
- deleteComment,
- type Comment,
-} from "ente-new/photos/services/comment";
-import {
- addCommentReaction,
- deleteReaction,
-} from "ente-new/photos/services/reaction";
-import { type UnifiedReaction } from "ente-new/photos/services/social";
import i18n, { t } from "i18next";
import React, {
useCallback,
@@ -52,6 +40,7 @@ import React, {
import { AddNameModal } from "./AddNameModal";
import { PublicCommentModal } from "./PublicCommentModal";
import { PublicLikeModal } from "./PublicLikeModal";
+import { type Comment, type UnifiedReaction } from "./social-types";
// =============================================================================
// Icons
@@ -660,8 +649,7 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
return fileNormalCollectionIDs?.get(file.id) ?? [];
}, [file, fileNormalCollectionIDs]);
- // Check if this is a public album
- const isPublicAlbum = isOfficialAlbumsApp || !!publicAlbumsCredentials;
+ const isPublicAlbum = true;
// Build collection info list with comment counts and cover files (shared albums only)
const collectionsInfo = useMemo((): CollectionInfo[] => {
@@ -1014,73 +1002,11 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
const handleSend = async () => {
if (!commentText.trim() || !file || !selectedCollectionInfo) return;
- // For public albums, check if we already have an anon identity
- if (isPublicAlbum) {
- 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 join album
- setShowPublicCommentModal(true);
- }
- return;
- }
-
- // For authenticated users, send via API
- const text = commentText.trim();
- const collectionID = selectedCollectionInfo.id;
-
- setSending(true);
- try {
- const collection = await getCollectionByID(collectionID);
-
- const newCommentID = await addComment(
- collectionID,
- file.id,
- text,
- collection.key,
- replyingTo?.id,
- );
-
- // Add the new comment to local state
- const newComment: Comment = {
- id: newCommentID,
- collectionID,
- 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]);
- 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 comment", e);
- } finally {
- setSending(false);
+ const storedIdentity = getStoredAnonIdentity(selectedCollectionInfo.id);
+ if (storedIdentity && publicAlbumsCredentials && collectionKey) {
+ await sendPublicComment(commentText.trim());
+ } else {
+ setShowPublicCommentModal(true);
}
};
@@ -1326,145 +1252,73 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
const existingReactionID = likedComments.get(targetComment.id);
try {
- if (isPublicAlbum) {
- // Public album - use public APIs
- if (!publicAlbumsCredentials || !collectionKey) {
- log.error(
- "Missing credentials for public album comment like",
- );
- return;
- }
+ if (!publicAlbumsCredentials || !collectionKey) {
+ log.error("Missing credentials for public album comment like");
+ return;
+ }
- const storedIdentity = getStoredAnonIdentity(collectionID);
- if (!storedIdentity) {
- // No identity - show modal to set name
- setPendingCommentLike(targetComment);
- setShowPublicLikeModal(true);
- return;
- }
+ const storedIdentity = getStoredAnonIdentity(collectionID);
+ if (!storedIdentity) {
+ setPendingCommentLike(targetComment);
+ setShowPublicLikeModal(true);
+ return;
+ }
- if (existingReactionID) {
- // Unlike - delete the reaction
- await deletePublicReaction(
- publicAlbumsCredentials,
- collectionID,
- existingReactionID,
- storedIdentity,
- );
- 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,
+ if (existingReactionID) {
+ await deletePublicReaction(
+ publicAlbumsCredentials,
+ collectionID,
+ existingReactionID,
+ storedIdentity,
+ );
+ 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,
- targetComment.id,
- "green_heart",
- collectionKey,
- storedIdentity,
- targetComment.fileID,
+ reactions.filter((r) => r.id !== existingReactionID),
);
- 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);
- }
+ return next;
+ });
+ onCommentReactionDeleted?.(collectionID, existingReactionID);
} else {
- // 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,
- targetComment.fileID,
- );
- 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);
- }
+ const reactionID = await addPublicCommentReaction(
+ publicAlbumsCredentials,
+ collectionID,
+ targetComment.id,
+ "green_heart",
+ collectionKey,
+ storedIdentity,
+ targetComment.fileID,
+ );
+ 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);
}
} catch (e) {
log.error("Failed to toggle comment like", e);
@@ -1487,26 +1341,24 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
break;
case "delete":
try {
- // Use public API for anonymous users in public albums
- if (isPublicAlbum && publicAlbumsCredentials) {
- const storedIdentity = getStoredAnonIdentity(
- selectedCollectionInfo.id,
+ if (!publicAlbumsCredentials) {
+ log.error("Missing credentials for public comment delete");
+ return;
+ }
+
+ const storedIdentity = getStoredAnonIdentity(
+ selectedCollectionInfo.id,
+ );
+ if (storedIdentity) {
+ await deletePublicComment(
+ publicAlbumsCredentials,
+ targetComment.collectionID,
+ targetComment.id,
+ storedIdentity,
);
- if (storedIdentity) {
- await deletePublicComment(
- publicAlbumsCredentials,
- targetComment.collectionID,
- targetComment.id,
- storedIdentity,
- );
- } else {
- log.error(
- "No stored identity for public comment delete",
- );
- return;
- }
} else {
- await deleteComment(targetComment.id);
+ log.error("No stored identity for public comment delete");
+ return;
}
// Update local state
diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/FileViewer.tsx b/web/apps/albums/vendor/ente-gallery/components/viewer/FileViewer.tsx
index ff88cafde3..f061daa09f 100644
--- a/web/apps/albums/vendor/ente-gallery/components/viewer/FileViewer.tsx
+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/FileViewer.tsx
@@ -33,8 +33,6 @@ import {
getPublicSocialDiff,
getStoredAnonIdentity,
} from "ente-new/albums/services/public-reaction";
-import { type Comment } from "ente-new/photos/services/comment";
-import { type UnifiedReaction } from "ente-new/photos/services/social";
import { t } from "i18next";
import React, {
useCallback,
@@ -54,6 +52,7 @@ import {
type FileViewerPhotoSwipeDelegate,
} from "./photoswipe";
import { PublicLikeModal } from "./PublicLikeModal";
+import { type Comment, type UnifiedReaction } from "./social-types";
const fileViewerBackStateKey = "__enteFileViewerBackState";
diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/LikesSidebar.tsx b/web/apps/albums/vendor/ente-gallery/components/viewer/LikesSidebar.tsx
index 05fb404a65..01148c2209 100644
--- a/web/apps/albums/vendor/ente-gallery/components/viewer/LikesSidebar.tsx
+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/LikesSidebar.tsx
@@ -16,7 +16,6 @@ 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 { t } from "i18next";
import React, {
useCallback,
@@ -25,6 +24,7 @@ import React, {
useRef,
useState,
} from "react";
+import { type UnifiedReaction } from "./social-types";
// =============================================================================
// Icons
diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/social-types.ts b/web/apps/albums/vendor/ente-gallery/components/viewer/social-types.ts
new file mode 100644
index 0000000000..02a3e09ba2
--- /dev/null
+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/social-types.ts
@@ -0,0 +1,27 @@
+export interface Comment {
+ id: string;
+ collectionID: number;
+ fileID?: number;
+ parentCommentID?: string;
+ parentCommentUserID?: number;
+ userID: number;
+ anonUserID?: string;
+ text: string;
+ isDeleted: boolean;
+ createdAt: number;
+ updatedAt: number;
+}
+
+export interface UnifiedReaction {
+ id: string;
+ collectionID: number;
+ fileID?: number;
+ commentID?: string;
+ isCommentReply?: boolean;
+ reactionType: string;
+ userID: number;
+ anonUserID?: string;
+ isDeleted: boolean;
+ createdAt: number;
+ updatedAt: number;
+}
diff --git a/web/apps/albums/vendor/ente-new/photos/services/auth-state.ts b/web/apps/albums/vendor/ente-new/photos/services/auth-state.ts
deleted file mode 100644
index 3347aa78aa..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/auth-state.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import { savedAuthToken } from "ente-base/token";
-import { nullToUndefined } from "ente-utils/transform";
-import { z } from "zod";
-
-export interface LocalUser {
- id: number;
- email: string;
- token: string;
- isTwoFactorEnabled?: boolean;
-}
-
-const LocalUser = z.object({
- id: z.number(),
- email: z.string(),
- token: z.string(),
- isTwoFactorEnabled: z.boolean().nullish().transform(nullToUndefined),
-});
-
-export interface KeyAttributes {
- encryptedKey: string;
- keyDecryptionNonce: string;
- kekSalt: string;
- opsLimit: number;
- memLimit: number;
- publicKey: string;
- encryptedSecretKey: string;
- secretKeyDecryptionNonce: string;
- masterKeyEncryptedWithRecoveryKey?: string;
- masterKeyDecryptionNonce?: string;
- recoveryKeyEncryptedWithMasterKey?: string;
- recoveryKeyDecryptionNonce?: string;
-}
-
-const KeyAttributes = z.object({
- kekSalt: z.string(),
- encryptedKey: z.string(),
- keyDecryptionNonce: z.string(),
- publicKey: z.string(),
- encryptedSecretKey: z.string(),
- secretKeyDecryptionNonce: z.string(),
- memLimit: z.number(),
- opsLimit: z.number(),
- masterKeyEncryptedWithRecoveryKey: z
- .string()
- .nullish()
- .transform(nullToUndefined),
- masterKeyDecryptionNonce: z.string().nullish().transform(nullToUndefined),
- recoveryKeyEncryptedWithMasterKey: z
- .string()
- .nullish()
- .transform(nullToUndefined),
- recoveryKeyDecryptionNonce: z.string().nullish().transform(nullToUndefined),
-});
-
-const ensureTokensMatch = async (user: LocalUser | undefined) => {
- if (user?.token !== (await savedAuthToken())) {
- throw new Error("Token mismatch");
- }
-};
-
-const savedLocalUser = (): LocalUser | undefined => {
- const jsonString = localStorage.getItem("user");
- if (!jsonString) return undefined;
-
- const { success, data } = LocalUser.safeParse(JSON.parse(jsonString));
- if (success) void ensureTokensMatch(data);
- return success ? data : undefined;
-};
-
-const savedKeyAttributes = (): KeyAttributes | undefined => {
- const jsonString = localStorage.getItem("keyAttributes");
- if (!jsonString) return undefined;
- return KeyAttributes.parse(JSON.parse(jsonString));
-};
-
-const ensureExpectedLoggedInValue = <T>(value: T | undefined): T => {
- if (!value) throw new Error("Not logged in");
- return value;
-};
-
-export const ensureLocalUser = (): LocalUser =>
- ensureExpectedLoggedInValue(savedLocalUser());
-
-export const ensureSavedKeyAttributes = (): KeyAttributes =>
- ensureExpectedLoggedInValue(savedKeyAttributes());
diff --git a/web/apps/albums/vendor/ente-new/photos/services/collection.ts b/web/apps/albums/vendor/ente-new/photos/services/collection.ts
deleted file mode 100644
index 0eaa6c26a8..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/collection.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-import { ensureLocalUser, ensureSavedKeyAttributes } from "./auth-state";
-import { boxSealOpen, decryptBox, encryptBox } from "ente-base/crypto";
-import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
-import { apiURL } from "ente-base/origins";
-import { ensureMasterKeyFromSession } from "ente-base/session";
-import {
- decryptRemoteCollection,
- RemoteCollection,
- type Collection,
-} from "ente-media/collection";
-import type { EnteFile } from "ente-media/file";
-import { z } from "zod";
-
-const requestBatchSize = 1000;
-
-interface CollectionFileItem {
- id: number;
- encryptedKey: string;
- keyDecryptionNonce: string;
-}
-
-const CollectionResponse = z.object({ collection: RemoteCollection });
-
-const batched = async <T>(
- items: T[],
- op: (batchItems: T[]) => Promise<void>,
-): Promise<void> => {
- for (let i = 0; i < items.length; i += requestBatchSize) {
- await op(items.slice(i, i + requestBatchSize));
- }
-};
-
-const ensureUserKeyPair = async () => {
- const { encryptedSecretKey, secretKeyDecryptionNonce, publicKey } =
- ensureSavedKeyAttributes();
- const privateKey = await decryptBox(
- { encryptedData: encryptedSecretKey, nonce: secretKeyDecryptionNonce },
- await ensureMasterKeyFromSession(),
- );
- return { publicKey, privateKey };
-};
-
-const decryptCollectionKey = async (
- collection: z.infer<typeof RemoteCollection>,
-): Promise<string> => {
- const { owner, encryptedKey, keyDecryptionNonce } = collection;
- if (owner.id === ensureLocalUser().id) {
- return decryptBox(
- { encryptedData: encryptedKey, nonce: keyDecryptionNonce! },
- await ensureMasterKeyFromSession(),
- );
- }
-
- return boxSealOpen(encryptedKey, await ensureUserKeyPair());
-};
-
-const decryptRemoteKeyAndCollection = async (
- collection: z.infer<typeof RemoteCollection>,
-) => decryptRemoteCollection(collection, await decryptCollectionKey(collection));
-
-/**
- * Fetch a collection from remote by its ID and decrypt it for local use.
- */
-export const getCollectionByID = async (
- collectionID: number,
-): Promise<Collection> => {
- const res = await fetch(await apiURL(`/collections/${collectionID}`), {
- headers: await authenticatedRequestHeaders(),
- });
- ensureOk(res);
- const { collection } = CollectionResponse.parse(await res.json());
- return decryptRemoteKeyAndCollection(collection);
-};
-
-const encryptWithCollectionKey = async (
- collection: Collection,
- files: EnteFile[],
-): Promise<CollectionFileItem[]> =>
- Promise.all(
- files.map(async (file) => {
- const box = await encryptBox(file.key, collection.key);
- return {
- id: file.id,
- encryptedKey: box.encryptedData,
- keyDecryptionNonce: box.nonce,
- };
- }),
- );
-
-/**
- * Add existing files to a collection on remote.
- */
-export const addToCollection = async (
- collection: Collection,
- files: EnteFile[],
-): Promise<void> =>
- batched(files, async (batchFiles) => {
- const encryptedFileKeys = await encryptWithCollectionKey(
- collection,
- batchFiles,
- );
- ensureOk(
- await fetch(await apiURL("/collections/add-files"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify({
- collectionID: collection.id,
- files: encryptedFileKeys,
- }),
- }),
- );
- });
diff --git a/web/apps/albums/vendor/ente-new/photos/services/comment.ts b/web/apps/albums/vendor/ente-new/photos/services/comment.ts
deleted file mode 100644
index e6a182acb2..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/comment.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { encryptBox } from "ente-base/crypto";
-import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
-import { apiURL } from "ente-base/origins";
-import { z } from "zod";
-
-/**
- * A decrypted comment.
- */
-export interface Comment {
- id: string;
- collectionID: number;
- fileID?: number;
- parentCommentID?: string;
- /** User ID of the parent comment's author (only in feed responses). */
- parentCommentUserID?: number;
- userID: number;
- anonUserID?: string;
- /** The decrypted comment text. */
- text: string;
- isDeleted: boolean;
- createdAt: number;
- updatedAt: number;
-}
-
-/**
- * Add a comment to a file in a collection.
- *
- * @param collectionID The ID of the collection containing the file.
- * @param fileID The ID of the file to comment on.
- * @param text The comment text to encrypt.
- * @param collectionKey The decrypted collection key (base64 encoded).
- * @param parentCommentID Optional parent comment ID for replies.
- * @returns The ID of the created comment.
- */
-export const addComment = async (
- collectionID: number,
- fileID: number,
- text: string,
- collectionKey: string,
- parentCommentID?: string,
-): Promise<string> => {
- const { encryptedData: cipher, nonce } = await encryptBox(
- new TextEncoder().encode(text),
- collectionKey,
- );
-
- const res = await fetch(await apiURL("/comments"), {
- method: "POST",
- headers: {
- ...(await authenticatedRequestHeaders()),
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- collectionID,
- fileID,
- cipher,
- nonce,
- parentCommentID,
- }),
- });
- ensureOk(res);
- const { id } = CreateCommentResponse.parse(await res.json());
- return id;
-};
-
-/**
- * Delete a comment by its ID.
- *
- * @param commentID The ID of the comment to delete.
- */
-export const deleteComment = async (commentID: string): Promise<void> => {
- const res = await fetch(await apiURL(`/comments/${commentID}`), {
- method: "DELETE",
- headers: await authenticatedRequestHeaders(),
- });
- ensureOk(res);
-};
-
-const CreateCommentResponse = z.object({ id: z.string() });
diff --git a/web/apps/albums/vendor/ente-new/photos/services/reaction.ts b/web/apps/albums/vendor/ente-new/photos/services/reaction.ts
deleted file mode 100644
index b39b769762..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/reaction.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import { encryptBox } from "ente-base/crypto";
-import { authenticatedRequestHeaders, ensureOk } 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");
-
-/**
- * Add a reaction to a file in a collection.
- *
- * @param collectionID The ID of the collection containing the file.
- * @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).
- * @returns The ID of the created reaction.
- */
-export const addReaction = async (
- collectionID: number,
- fileID: number,
- reactionType: string,
- collectionKey: string,
-): Promise<string> => {
- const { encryptedData: cipher, nonce } = await encryptBox(
- new TextEncoder().encode(padReaction(reactionType)),
- collectionKey,
- );
-
- const res = await fetch(await apiURL("/reactions"), {
- method: "PUT",
- headers: {
- ...(await authenticatedRequestHeaders()),
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ collectionID, fileID, cipher, nonce }),
- });
- ensureOk(res);
- const { id } = UpsertReactionResponse.parse(await res.json());
- return id;
-};
-
-/**
- * Add a reaction to a comment in a collection.
- *
- * @param collectionID The ID of the collection containing the comment.
- * @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 fileID Optional file ID, required for file-scoped comments.
- * @returns The ID of the created reaction.
- */
-export const addCommentReaction = async (
- collectionID: number,
- commentID: string,
- reactionType: string,
- collectionKey: string,
- fileID?: number,
-): Promise<string> => {
- const { encryptedData: cipher, nonce } = await encryptBox(
- new TextEncoder().encode(padReaction(reactionType)),
- collectionKey,
- );
-
- const res = await fetch(await apiURL("/reactions"), {
- method: "PUT",
- headers: {
- ...(await authenticatedRequestHeaders()),
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- collectionID,
- commentID,
- fileID,
- cipher,
- nonce,
- }),
- });
- ensureOk(res);
- const { id } = UpsertReactionResponse.parse(await res.json());
- return id;
-};
-
-const UpsertReactionResponse = z.object({ id: z.string() });
-
-/**
- * Delete a reaction by its ID.
- *
- * @param reactionID The ID of the reaction to delete.
- */
-export const deleteReaction = async (reactionID: string): Promise<void> => {
- const res = await fetch(await apiURL(`/reactions/${reactionID}`), {
- method: "DELETE",
- headers: await authenticatedRequestHeaders(),
- });
- ensureOk(res);
-};
diff --git a/web/apps/albums/vendor/ente-new/photos/services/social.ts b/web/apps/albums/vendor/ente-new/photos/services/social.ts
deleted file mode 100644
index a376de1c52..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/social.ts
+++ /dev/null
@@ -1,253 +0,0 @@
-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 } 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;
- /** True if this reaction is on a reply (only in feed responses). */
- isCommentReply?: boolean;
- 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);
- return decryptSocialDiff(collectionKey, await res.json());
-};
-
-/**
- * Decrypt comments and reactions from the unified diff endpoint response.
- */
-const decryptSocialDiff = async (
- collectionKey: string,
- responseJson: unknown,
-): Promise<UnifiedSocialDiff> => {
- const data = UnifiedDiffResponse.parse(responseJson);
-
- // 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,
- parentCommentUserID: comment.parentCommentUserID ?? 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)),
- );
- const decryptedComment = {
- id: comment.id,
- collectionID: comment.collectionID,
- fileID: comment.fileID ?? undefined,
- parentCommentID: comment.parentCommentID ?? undefined,
- parentCommentUserID: comment.parentCommentUserID ?? undefined,
- userID: comment.userID,
- anonUserID: comment.anonUserID ?? undefined,
- text,
- isDeleted: comment.isDeleted,
- createdAt: comment.createdAt,
- updatedAt: comment.updatedAt,
- };
- comments.push(decryptedComment);
- } 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,
- isCommentReply: reaction.isCommentReply ?? 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
- }
- }
-
- const result = {
- comments,
- reactions,
- hasMoreComments: data.hasMoreComments,
- hasMoreReactions: data.hasMoreReactions,
- };
- return result;
-};
-
-const RemoteComment = z.object({
- id: z.string(),
- collectionID: z.number(),
- fileID: z.number().nullish(),
- parentCommentID: z.string().nullish(),
- parentCommentUserID: z.number().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(),
- isCommentReply: z.boolean().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(),
-});
-
-/**
- * Get anonymous user profiles for a collection.
- *
- * @param collectionID The ID of the collection.
- * @param collectionKey The decrypted collection key (base64 encoded).
- * @returns Map of anonUserID to decrypted userName.
- */
-export const getAnonProfiles = async (
- collectionID: number,
- collectionKey: string,
-): Promise<Map<string, string>> => {
- const res = await fetch(
- await apiURL("/social/anon-profiles", { collectionID }),
- { headers: await authenticatedRequestHeaders() },
- );
- ensureOk(res);
- const { profiles } = GetAnonProfilesResponse.parse(await res.json());
-
- const anonUserNames = new Map<string, string>();
- for (const profile of profiles) {
- if (!profile.cipher || !profile.nonce) continue;
- try {
- const decryptedB64 = await decryptBox(
- { encryptedData: profile.cipher, nonce: profile.nonce },
- collectionKey,
- );
- const userName = new TextDecoder().decode(
- Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),
- );
- if (userName) {
- anonUserNames.set(profile.anonUserID, userName);
- }
- } catch {
- // Skip profiles that fail to decrypt
- }
- }
- return anonUserNames;
-};
-
-const RemoteAnonProfile = z.object({
- anonUserID: z.string(),
- collectionID: z.number(),
- cipher: z.string().nullish(),
- nonce: z.string().nullish(),
- createdAt: z.number(),
- updatedAt: z.number(),
-});
-
-const GetAnonProfilesResponse = z.object({
- profiles: z
- .array(RemoteAnonProfile)
- .nullish()
- .transform((v) => v ?? []),
-});