Skip to content

armgit / ente

Public Imported from GitHub
0

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

[web][contacts] add shared contact display integration

Neeraj Gupta6e79e9cc8f4a
diff --git a/web/apps/locker/package.json b/web/apps/locker/package.json
index d5a5961a26..10ed5111a7 100644
--- a/web/apps/locker/package.json
+++ b/web/apps/locker/package.json
@@ -7,6 +7,7 @@
"@hugeicons/react": "^1.1.4",
"ente-accounts-rs": "*",
"ente-base": "*",
+ "ente-contacts-web": "*",
"ente-wasm": "*"
},
"devDependencies": {
diff --git a/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx b/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx
index 0d966e8275..c2210a370c 100644
--- a/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx
+++ b/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx
@@ -21,6 +21,7 @@ import {
} from "ente-base/components/OverflowMenu";
import { SidebarDrawer } from "ente-base/components/mui/SidebarDrawer";
import { useBaseContext } from "ente-base/context";
+import { useResolvedContactAvatar } from "ente-contacts-web";
import { isHTTPErrorWithStatus } from "ente-base/http";
import log from "ente-base/log";
import { t } from "i18next";
@@ -517,7 +518,15 @@ const ParticipantRow: React.FC<{
action?: React.ReactNode;
}> = ({ participant, subtitle, action }) => {
const email = participant.email ?? t("unknownEmail");
- const avatarLetter = email.charAt(0).toUpperCase() || "?";
+ const resolved = useResolvedContactAvatar({
+ userID: participant.id,
+ email: participant.email,
+ });
+ const label = resolved.source === "contact" ? resolved.primaryLabel : email;
+ const initial =
+ resolved.source === "contact"
+ ? resolved.initial
+ : (email.charAt(0).toUpperCase() || "?");
return (
<Stack
@@ -538,12 +547,13 @@ const ParticipantRow: React.FC<{
bgcolor: theme.vars.palette.fill.faintHover,
color: "text.base",
})}
+ src={resolved.avatarURL}
>
- {avatarLetter}
+ {initial}
</Avatar>
<Box sx={{ flex: 1, minWidth: 0 }}>
<Typography variant="body" sx={{ fontWeight: "medium" }} noWrap>
- {email}
+ {label}
</Typography>
{subtitle && (
<Typography
diff --git a/web/apps/locker/src/components/lockerPage/useLockerData.ts b/web/apps/locker/src/components/lockerPage/useLockerData.ts
index 57b6c1fef3..16bcfeff64 100644
--- a/web/apps/locker/src/components/lockerPage/useLockerData.ts
+++ b/web/apps/locker/src/components/lockerPage/useLockerData.ts
@@ -5,12 +5,14 @@ import {
} from "ente-accounts-rs/services/accounts-db";
import { stashRedirect } from "ente-accounts-rs/services/redirect";
import { masterKeyFromSession } from "ente-accounts-rs/services/session-storage";
+import { ensureLocalUser } from "ente-accounts-rs/services/user";
import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";
import {
authenticatedRequestHeaders,
ensureOk,
isHTTP401Error,
} from "ente-base/http";
+import { ensureContactsReady } from "ente-contacts-web";
import log from "ente-base/log";
import { apiURL } from "ente-base/origins";
import { savedAuthToken } from "ente-base/token";
@@ -309,6 +311,15 @@ export const useLockerData = ({
}
setMasterKey(mk);
+ void ensureContactsReady({
+ userID: ensureLocalUser().id,
+ masterKeyB64: mk,
+ }).catch((error: unknown) => {
+ log.warn(
+ "[locker] Failed to warm contacts display cache",
+ error,
+ );
+ });
const persisted = await loadPersistedLockerState(mk);
if (canApplyState() && persisted.hasPersistedState) {
diff --git a/web/apps/photos/package.json b/web/apps/photos/package.json
index 2fa2820de3..f2a7efd695 100644
--- a/web/apps/photos/package.json
+++ b/web/apps/photos/package.json
@@ -9,6 +9,7 @@
"debounce": "^2.2.0",
"ente-accounts": "*",
"ente-base": "*",
+ "ente-contacts-web": "*",
"ente-gallery": "*",
"ente-media": "*",
"ente-new": "*",
diff --git a/web/apps/photos/src/components/Avatar.tsx b/web/apps/photos/src/components/Avatar.tsx
index 05feac15bf..8b46c50659 100644
--- a/web/apps/photos/src/components/Avatar.tsx
+++ b/web/apps/photos/src/components/Avatar.tsx
@@ -2,14 +2,14 @@
/* eslint-disable react-hooks/exhaustive-deps */
import { styled } from "@mui/material";
import type { LocalUser } from "ente-accounts/services/user";
-import log from "ente-base/log";
+import { useResolvedContactAvatar } from "ente-contacts-web";
import { type EnteFile } from "ente-media/file";
import {
avatarBackgroundColor,
avatarBackgroundColorPublicCollectedFile,
avatarTextColor,
} from "ente-new/photos/services/avatar";
-import React, { useLayoutEffect, useState } from "react";
+import React, { useMemo } from "react";
interface AvatarProps {
user?: LocalUser;
@@ -37,6 +37,21 @@ const AvatarBase = styled("div")<{
font-size: ${({ size }) => `${Math.floor(size / 2)}px`};
`;
+const AvatarImage = styled("img")<{
+ size: number;
+ opacity: number | undefined;
+}>`
+ width: ${({ size }) => `${size}px`};
+ height: ${({ size }) => `${size}px`};
+ border-radius: 50%;
+ object-fit: cover;
+ opacity: ${({ opacity }) =>
+ opacity === undefined ? 1 : Math.max(0, Math.min(opacity, 100)) / 100};
+`;
+
+const colorSeedFromEmail = (email: string) =>
+ [...email].reduce((acc, char) => acc + char.charCodeAt(0), 0);
+
const Avatar: React.FC<AvatarProps> = ({
user,
file,
@@ -44,64 +59,63 @@ const Avatar: React.FC<AvatarProps> = ({
opacity,
emailByUserID,
}) => {
- const [colorCode, setColorCode] = useState("");
- const [userLetter, setUserLetter] = useState<string | undefined>("");
+ const isPublicCollectedAvatar =
+ !!file && !!user && file.ownerID === user.id && !!file.pubMagicMetadata;
+ const uploaderName = file?.pubMagicMetadata?.data.uploaderName;
- useLayoutEffect(() => {
- try {
- if (!file) {
- return;
- }
- if (file.ownerID !== user?.id) {
- // getting email from in-memory id-email map
- const email = emailByUserID?.get(file.ownerID);
- if (!email) {
- log.error("email not found in userIDToEmailMap");
- return;
- }
- setUserLetter(email[0]?.toUpperCase());
- setColorCode(avatarBackgroundColor(file.ownerID));
- } else if (file.ownerID === user.id) {
- const uploaderName = file.pubMagicMetadata?.data.uploaderName;
- if (!uploaderName) {
- log.error(
- "uploaderName not found in file.pubMagicMetadata.data",
- );
- return;
- }
- setUserLetter(uploaderName[0]?.toUpperCase());
- setColorCode(avatarBackgroundColorPublicCollectedFile);
- }
- } catch (e) {
- log.error("AvatarIcon.tsx - useLayoutEffect file failed", e);
- }
- }, [file]);
+ const resolvedContact = useResolvedContactAvatar(
+ file && file.ownerID !== user?.id
+ ? {
+ userID: file.ownerID,
+ email: emailByUserID?.get(file.ownerID),
+ }
+ : {
+ email,
+ },
+ );
- useLayoutEffect(() => {
- try {
- if (!email) {
- return;
- }
+ const fallbackEmail = resolvedContact.actualEmail ?? email;
- if (user?.email === email) {
- setUserLetter(email[0]?.toUpperCase());
- setColorCode(avatarBackgroundColorPublicCollectedFile);
- return;
- }
+ const colorCode = useMemo(() => {
+ if (isPublicCollectedAvatar) {
+ return avatarBackgroundColorPublicCollectedFile;
+ }
+ if (file && file.ownerID !== user?.id) {
+ return avatarBackgroundColor(file.ownerID);
+ }
+ if (!fallbackEmail) {
+ return undefined;
+ }
+ if (user?.email === fallbackEmail) {
+ return avatarBackgroundColorPublicCollectedFile;
+ }
+ const matchedID = Array.from(emailByUserID?.keys() ?? []).find(
+ (key) => emailByUserID?.get(key) === fallbackEmail,
+ );
+ return avatarBackgroundColor(
+ matchedID ?? colorSeedFromEmail(fallbackEmail),
+ );
+ }, [emailByUserID, fallbackEmail, file, isPublicCollectedAvatar, user]);
- const id = Array.from(emailByUserID?.keys() ?? []).find(
- (key) => emailByUserID?.get(key) === email,
- );
- if (!id) {
- log.error(`ID not found for email: ${email}`);
- return;
- }
- setUserLetter(email[0]?.toUpperCase());
- setColorCode(avatarBackgroundColor(id));
- } catch (e) {
- log.error("AvatarIcon.tsx - useLayoutEffect email failed", e);
+ const userLetter = useMemo(() => {
+ if (isPublicCollectedAvatar) {
+ return uploaderName?.[0]?.toUpperCase();
+ }
+ if (resolvedContact.source === "contact") {
+ return resolvedContact.initial;
}
- }, [user, email, emailByUserID]);
+ return fallbackEmail?.[0]?.toUpperCase();
+ }, [
+ fallbackEmail,
+ isPublicCollectedAvatar,
+ resolvedContact.initial,
+ resolvedContact.source,
+ uploaderName,
+ ]);
+
+ if (resolvedContact.avatarURL && !isPublicCollectedAvatar) {
+ return <AvatarImage size={18} opacity={opacity} src={resolvedContact.avatarURL} />;
+ }
if (!colorCode || !userLetter) {
return <></>;
diff --git a/web/apps/photos/src/components/Collections/CollectionShare.tsx b/web/apps/photos/src/components/Collections/CollectionShare.tsx
index 9ff9efa81e..254f22e1d0 100644
--- a/web/apps/photos/src/components/Collections/CollectionShare.tsx
+++ b/web/apps/photos/src/components/Collections/CollectionShare.tsx
@@ -21,6 +21,7 @@ import TextField from "@mui/material/TextField";
import Avatar from "components/Avatar";
import { type LocalUser } from "ente-accounts/services/user";
import { LoadingButton } from "ente-base/components/mui/LoadingButton";
+import { useResolvedContactDisplay } from "ente-contacts-web";
import {
SidebarDrawer,
SidebarDrawerTitlebar,
@@ -297,6 +298,67 @@ export const CollectionShare: React.FC<CollectionShareProps> = ({
);
};
+type ResolvedEmailRowCommonProps = Pick<
+ CollectionShareProps,
+ "user" | "emailByUserID"
+> & {
+ email?: string;
+ fallbackLabel?: string;
+};
+
+const ResolvedEmailRowLabel: React.FC<ResolvedEmailRowCommonProps> = ({
+ email,
+ fallbackLabel,
+ user,
+ emailByUserID,
+}) => {
+ const resolved = useResolvedContactDisplay({ email });
+
+ return (
+ <RowLabel
+ startIcon={<Avatar email={email} {...{ user, emailByUserID }} />}
+ label={fallbackLabel ?? resolved.primaryLabel}
+ />
+ );
+};
+
+type ResolvedEmailRowButtonProps = ResolvedEmailRowCommonProps & {
+ disabled?: boolean;
+ onClick?: () => void;
+ endIcon?: React.ReactNode;
+};
+
+const ResolvedEmailRowButton: React.FC<ResolvedEmailRowButtonProps> = ({
+ disabled,
+ email,
+ endIcon,
+ fallbackLabel,
+ onClick,
+ user,
+ emailByUserID,
+}) => {
+ const resolved = useResolvedContactDisplay({ email });
+
+ return (
+ <RowButton
+ fontWeight="regular"
+ disabled={disabled}
+ onClick={onClick ?? (() => undefined)}
+ label={fallbackLabel ?? resolved.primaryLabel}
+ startIcon={<Avatar email={email} {...{ user, emailByUserID }} />}
+ endIcon={endIcon}
+ />
+ );
+};
+
+const ResolvedEmailText: React.FC<{
+ email?: string;
+ fallbackLabel?: string;
+}> = ({ email, fallbackLabel }) => {
+ const resolved = useResolvedContactDisplay({ email });
+ return <>{fallbackLabel ?? resolved.primaryLabel}</>;
+};
+
type SharingDetailsProps = Pick<
CollectionShareProps,
"user" | "collection" | "emailByUserID" | "collectionSummary"
@@ -331,9 +393,6 @@ const SharingDetails: React.FC<SharingDetailsProps> = ({
.map((sharee) => sharee.email)
.filter((email) => email !== undefined);
- const userOrEmail = (email: string) =>
- email == user.email ? t("you") : email;
-
if (!isOwner && isAdmin) {
return (
<Stack>
@@ -341,14 +400,9 @@ const SharingDetails: React.FC<SharingDetailsProps> = ({
{t("owner")}
</RowButtonGroupTitle>
<RowButtonGroup>
- <RowLabel
- startIcon={
- <Avatar
- email={ownerEmail}
- {...{ user, emailByUserID }}
- />
- }
- label={ownerEmail ?? ""}
+ <ResolvedEmailRowLabel
+ email={ownerEmail}
+ {...{ user, emailByUserID }}
/>
</RowButtonGroup>
</Stack>
@@ -362,14 +416,10 @@ const SharingDetails: React.FC<SharingDetailsProps> = ({
{t("owner")}
</RowButtonGroupTitle>
<RowButtonGroup>
- <RowLabel
- startIcon={
- <Avatar
- email={ownerEmail}
- {...{ user, emailByUserID }}
- />
- }
- label={isOwner ? t("you") : (ownerEmail ?? "")}
+ <ResolvedEmailRowLabel
+ email={ownerEmail}
+ fallbackLabel={isOwner ? t("you") : undefined}
+ {...{ user, emailByUserID }}
/>
</RowButtonGroup>
</Stack>
@@ -378,18 +428,18 @@ const SharingDetails: React.FC<SharingDetailsProps> = ({
<RowButtonGroupTitle icon={<AdminPanelSettingsIcon />}>
{t("admins", { defaultValue: "Admins" })}
</RowButtonGroupTitle>
- <RowButtonGroup>
- {admins.map((email, index) => (
- <React.Fragment key={email}>
- <RowLabel
- startIcon={
- <Avatar
- email={email}
- {...{ user, emailByUserID }}
- />
- }
- label={userOrEmail(email)}
- />
+ <RowButtonGroup>
+ {admins.map((email, index) => (
+ <React.Fragment key={email}>
+ <ResolvedEmailRowLabel
+ email={email}
+ fallbackLabel={
+ email == user.email
+ ? t("you")
+ : undefined
+ }
+ {...{ user, emailByUserID }}
+ />
{index != admins.length - 1 && (
<RowButtonDivider />
)}
@@ -407,14 +457,14 @@ const SharingDetails: React.FC<SharingDetailsProps> = ({
<RowButtonGroup>
{collaborators.map((email, index) => (
<React.Fragment key={email}>
- <RowLabel
- startIcon={
- <Avatar
- email={email}
- {...{ user, emailByUserID }}
- />
+ <ResolvedEmailRowLabel
+ email={email}
+ fallbackLabel={
+ email == user.email
+ ? t("you")
+ : undefined
}
- label={userOrEmail(email)}
+ {...{ user, emailByUserID }}
/>
{index != collaborators.length - 1 && (
<RowButtonDivider />
@@ -429,21 +479,21 @@ const SharingDetails: React.FC<SharingDetailsProps> = ({
<RowButtonGroupTitle icon={<Photo />}>
{t("viewers")}
</RowButtonGroupTitle>
- <RowButtonGroup>
- {viewers.map((email, index) => (
- <React.Fragment key={email}>
- <RowLabel
- startIcon={
- <Avatar
- email={email}
- {...{ user, emailByUserID }}
- />
- }
- label={userOrEmail(email)}
- />
- {index != viewers.length - 1 && (
- <RowButtonDivider />
- )}
+ <RowButtonGroup>
+ {viewers.map((email, index) => (
+ <React.Fragment key={email}>
+ <ResolvedEmailRowLabel
+ email={email}
+ fallbackLabel={
+ email == user.email
+ ? t("you")
+ : undefined
+ }
+ {...{ user, emailByUserID }}
+ />
+ {index != viewers.length - 1 && (
+ <RowButtonDivider />
+ )}
</React.Fragment>
))}
</RowButtonGroup>
@@ -526,7 +576,14 @@ const EmailShare: React.FC<EmailShareProps> = ({
}
label={
collection.sharees.length === 1
- ? collection.sharees[0]?.email
+ ? (
+ <ResolvedEmailText
+ email={
+ collection.sharees[0]
+ ?.email
+ }
+ />
+ )
: null
}
endIcon={<ChevronRightIcon />}
@@ -875,16 +932,10 @@ const AddParticipantForm: React.FC<AddParticipantFormProps> = ({
<RowButtonGroup>
{existingEmails.map((email, index) => (
<React.Fragment key={email}>
- <RowButton
- fontWeight="regular"
+ <ResolvedEmailRowButton
+ email={email}
onClick={createToggleEmail(email)}
- label={email}
- startIcon={
- <Avatar
- email={email}
- {...{ user, emailByUserID }}
- />
- }
+ {...{ user, emailByUserID }}
endIcon={
formik.values.selectedEmails.includes(
email,
@@ -1030,18 +1081,14 @@ const ManageEmailShare: React.FC<ManageEmailShareProps> = ({
<RowButtonGroupTitle icon={<AdminPanelSettingsIcon />}>
{t("owner")}
</RowButtonGroupTitle>
- <RowButtonGroup>
- <RowLabel
- startIcon={
- <Avatar
- email={ownerEmail}
- {...{ user, emailByUserID }}
- />
- }
- label={isOwner ? t("you") : (ownerEmail ?? "")}
- />
- </RowButtonGroup>
- </Stack>
+ <RowButtonGroup>
+ <ResolvedEmailRowLabel
+ email={ownerEmail}
+ fallbackLabel={isOwner ? t("you") : undefined}
+ {...{ user, emailByUserID }}
+ />
+ </RowButtonGroup>
+ </Stack>
{(admins.length > 0 || canManageParticipants) && (
<Stack>
<RowButtonGroupTitle
@@ -1056,8 +1103,8 @@ const ManageEmailShare: React.FC<ManageEmailShareProps> = ({
canManageParticipants && !isSelf;
return (
<React.Fragment key={item}>
- <RowButton
- fontWeight="regular"
+ <ResolvedEmailRowButton
+ email={item}
disabled={!canManageThis}
onClick={() => {
if (canManageThis) {
@@ -1066,20 +1113,12 @@ const ManageEmailShare: React.FC<ManageEmailShareProps> = ({
);
}
}}
- label={
+ fallbackLabel={
isSelf
? t("you")
- : (item ?? "")
- }
- startIcon={
- <Avatar
- email={item}
- {...{
- user,
- emailByUserID,
- }}
- />
+ : undefined
}
+ {...{ user, emailByUserID }}
endIcon={
canManageThis ? (
<ChevronRightIcon />
@@ -1120,8 +1159,8 @@ const ManageEmailShare: React.FC<ManageEmailShareProps> = ({
canManageParticipants && item != user.email;
return (
<React.Fragment key={item}>
- <RowButton
- fontWeight="regular"
+ <ResolvedEmailRowButton
+ email={item}
disabled={!canManageThis}
onClick={() => {
if (canManageThis) {
@@ -1130,13 +1169,7 @@ const ManageEmailShare: React.FC<ManageEmailShareProps> = ({
);
}
}}
- label={item}
- startIcon={
- <Avatar
- email={item}
- {...{ user, emailByUserID }}
- />
- }
+ {...{ user, emailByUserID }}
endIcon={
canManageThis ? (
<ChevronRightIcon />
@@ -1174,8 +1207,8 @@ const ManageEmailShare: React.FC<ManageEmailShareProps> = ({
canManageParticipants && item != user.email;
return (
<React.Fragment key={item}>
- <RowButton
- fontWeight="regular"
+ <ResolvedEmailRowButton
+ email={item}
disabled={!canManageThis}
onClick={() => {
if (canManageThis) {
@@ -1184,13 +1217,7 @@ const ManageEmailShare: React.FC<ManageEmailShareProps> = ({
);
}
}}
- label={item}
- startIcon={
- <Avatar
- email={item}
- {...{ user, emailByUserID }}
- />
- }
+ {...{ user, emailByUserID }}
endIcon={
canManageThis ? (
<ChevronRightIcon />
@@ -1354,6 +1381,11 @@ const ManageParticipant: React.FC<ManageParticipantProps> = ({
});
};
+ const participantDisplay = useResolvedContactDisplay({
+ userID: participant?.id,
+ email: participant?.email,
+ });
+
if (!participant) {
return <></>;
}
@@ -1364,7 +1396,7 @@ const ManageParticipant: React.FC<ManageParticipantProps> = ({
{...{ open, onClose }}
onRootClose={handleRootClose}
title={t("manage")}
- caption={participant.email}
+ caption={participantDisplay.primaryLabel}
>
<Stack sx={{ gap: "32px", py: "20px", px: "8px" }}>
<Stack>
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index 892d162a2a..6c7054fb0e 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -49,6 +49,7 @@ import {
haveMasterKeyInSession,
masterKeyFromSession,
} from "ente-base/session";
+import { ensureContactsReady } from "ente-contacts-web";
import { savedAuthToken } from "ente-base/token";
import type { Location } from "ente-base/types";
import { FullScreenDropZone } from "ente-gallery/components/FullScreenDropZone";
@@ -535,6 +536,18 @@ const Page: React.FC = () => {
// Initialize the reducer.
const user = ensureLocalUser();
+ const masterKey = await masterKeyFromSession();
+ if (masterKey) {
+ void ensureContactsReady({
+ userID: user.id,
+ masterKeyB64: masterKey,
+ }).catch((error: unknown) => {
+ log.warn(
+ "[gallery] Failed to warm contacts display cache",
+ error,
+ );
+ });
+ }
const userDetails = await savedUserDetailsOrTriggerPull();
dispatch({
type: "mount",
diff --git a/web/packages/contacts/db.ts b/web/packages/contacts/db.ts
new file mode 100644
index 0000000000..963a1e6353
--- /dev/null
+++ b/web/packages/contacts/db.ts
@@ -0,0 +1,59 @@
+import { getKV, getKVN, setKV } from "ente-base/kv";
+import { z } from "zod";
+import type { ContactDisplayRecord, WrappedRootContactKey } from "./types";
+
+const contactsKey = (sessionKey: string) => `contacts/${sessionKey}/records`;
+const wrappedRootKeyKey = (sessionKey: string) =>
+ `contacts/${sessionKey}/root-key`;
+const sinceTimeKey = (sessionKey: string) => `contacts/${sessionKey}/since-time`;
+
+const ContactDisplayRecordZ = z.object({
+ contactId: z.string(),
+ contactUserId: z.number(),
+ resolvedEmail: z.string().optional(),
+ displayName: z.string().optional(),
+ profilePictureAttachmentID: z.string().optional(),
+ updatedAt: z.number(),
+});
+
+const WrappedRootContactKeyZ = z.object({
+ encryptedKey: z.string(),
+ header: z.string(),
+});
+
+export const savedContactDisplayRecords = async (
+ sessionKey: string,
+): Promise<ContactDisplayRecord[]> =>
+ ContactDisplayRecordZ.array()
+ .parse((await getKV(contactsKey(sessionKey))) ?? [])
+ .map((record) => ({
+ contactId: record.contactId,
+ contactUserId: record.contactUserId,
+ resolvedEmail: record.resolvedEmail,
+ displayName: record.displayName,
+ profilePictureAttachmentID: record.profilePictureAttachmentID,
+ updatedAt: record.updatedAt,
+ }));
+
+export const saveContactDisplayRecords = (
+ sessionKey: string,
+ records: ContactDisplayRecord[],
+) => setKV(contactsKey(sessionKey), records);
+
+export const savedWrappedRootContactKey = async (
+ sessionKey: string,
+): Promise<WrappedRootContactKey | undefined> => {
+ const saved = await getKV(wrappedRootKeyKey(sessionKey));
+ return saved ? WrappedRootContactKeyZ.parse(saved) : undefined;
+};
+
+export const saveWrappedRootContactKey = (
+ sessionKey: string,
+ wrappedRootKey: WrappedRootContactKey,
+) => setKV(wrappedRootKeyKey(sessionKey), wrappedRootKey);
+
+export const savedContactsSinceTime = (sessionKey: string) =>
+ getKVN(sinceTimeKey(sessionKey));
+
+export const saveContactsSinceTime = (sessionKey: string, sinceTime: number) =>
+ setKV(sinceTimeKey(sessionKey), sinceTime);
diff --git a/web/packages/contacts/index.test.ts b/web/packages/contacts/index.test.ts
new file mode 100644
index 0000000000..83eec0d3c2
--- /dev/null
+++ b/web/packages/contacts/index.test.ts
@@ -0,0 +1,269 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { resolveContactDisplayFromSnapshot } from "./resolver";
+import type { ContactsDisplaySnapshot } from "./types";
+
+const makeSnapshot = (): ContactsDisplaySnapshot => ({
+ isHydrated: true,
+ recordsByUserID: new Map([
+ [
+ 101,
+ {
+ contactId: "c_1",
+ contactUserId: 101,
+ resolvedEmail: "[email protected]",
+ displayName: "Set",
+ profilePictureAttachmentID: "a_1",
+ updatedAt: 1,
+ },
+ ],
+ ]),
+ recordsByEmail: new Map([
+ [
+ {
+ contactId: "c_1",
+ contactUserId: 101,
+ resolvedEmail: "[email protected]",
+ displayName: "Set",
+ profilePictureAttachmentID: "a_1",
+ updatedAt: 1,
+ },
+ ],
+ ]),
+ avatarURLsByContactID: new Map(),
+});
+
+describe("resolveContactDisplayFromSnapshot", () => {
+ test("prefers contact name by user id", () => {
+ const resolved = resolveContactDisplayFromSnapshot(makeSnapshot(), {
+ userID: 101,
+ email: "[email protected]",
+ });
+
+ expect(resolved.primaryLabel).toBe("Set");
+ expect(resolved.actualEmail).toBe("[email protected]");
+ expect(resolved.source).toBe("contact");
+ });
+
+ test("falls back to email when no contact exists", () => {
+ const resolved = resolveContactDisplayFromSnapshot(makeSnapshot(), {
+ email: "[email protected]",
+ });
+
+ expect(resolved.primaryLabel).toBe("[email protected]");
+ expect(resolved.actualEmail).toBe("[email protected]");
+ expect(resolved.source).toBe("fallback");
+ });
+
+ test("falls back to Someone when no user or email exists", () => {
+ const resolved = resolveContactDisplayFromSnapshot(makeSnapshot(), {});
+
+ expect(resolved.primaryLabel).toBe("Someone");
+ expect(resolved.initial).toBe("S");
+ expect(resolved.source).toBe("fallback");
+ });
+});
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ vi.useRealTimers();
+});
+
+type SetupOptions = {
+ diff?: object[];
+ getProfilePictureError?: Error;
+ getProfilePictureBytes?: Uint8Array;
+};
+
+const setupContactsModule = async (options: SetupOptions = {}) => {
+ const kv = new Map<string, unknown>();
+ const setKV = vi.fn(async (key: string, value: unknown) => {
+ kv.set(key, JSON.parse(JSON.stringify(value)));
+ });
+ const getKV = vi.fn(async (key: string) => kv.get(key));
+ const getKVN = vi.fn(async (key: string) => {
+ const value = kv.get(key);
+ return typeof value === "number" ? value : undefined;
+ });
+
+ const savedAuthToken = vi.fn(async () => "auth-token-secret");
+ const apiOrigin = vi.fn(async () => "https://api.example");
+ const info = vi.fn();
+ const warn = vi.fn();
+ const error = vi.fn();
+ const update_auth_token = vi.fn();
+ const current_wrapped_root_key = vi.fn(() => ({
+ encryptedKey: "wrapped-root-key",
+ header: "wrapped-header",
+ }));
+
+ const diff =
+ options.diff ??
+ [
+ {
+ id: "ct_1",
+ contactUserId: 101,
+ email: "[email protected]",
+ name: "Set",
+ profilePictureAttachmentID: "ua_1",
+ isDeleted: false,
+ updatedAt: 1,
+ },
+ ];
+
+ const get_diff = vi
+ .fn()
+ .mockResolvedValueOnce(diff)
+ .mockResolvedValueOnce([]);
+ const get_profile_picture = vi.fn(async () => {
+ if (options.getProfilePictureBytes) {
+ return options.getProfilePictureBytes;
+ }
+ throw options.getProfilePictureError ?? new Error("boom");
+ });
+
+ vi.doMock("ente-base/kv", () => ({
+ getKV,
+ getKVN,
+ setKV,
+ }));
+ vi.doMock("ente-base/token", () => ({
+ savedAuthToken,
+ }));
+ vi.doMock("ente-base/origins", () => ({
+ apiOrigin,
+ }));
+ vi.doMock("ente-base/log", () => ({
+ default: { info, warn, error },
+ }));
+ vi.doMock("ente-wasm", () => ({
+ contacts_open_ctx: vi.fn(async () => ({
+ update_auth_token,
+ current_wrapped_root_key,
+ get_diff,
+ get_profile_picture,
+ })),
+ }));
+
+ const contacts = await import("./index");
+
+ return {
+ contacts,
+ setKV,
+ get_diff,
+ get_profile_picture,
+ info,
+ };
+};
+
+describe("ensureContactsReady", () => {
+ test("does not persist auth token or master key in contacts kv", async () => {
+ const { contacts, setKV } = await setupContactsModule();
+
+ await contacts.ensureContactsReady({
+ userID: 101,
+ masterKeyB64: "MASTER_KEY_SHOULD_NOT_PERSIST",
+ });
+
+ const persisted = setKV.mock.calls
+ .map(([key, value]) => `${String(key)}:${JSON.stringify(value)}`)
+ .join("\n");
+
+ expect(persisted).toContain("contacts/");
+ expect(persisted).toContain("wrapped-root-key");
+ expect(persisted).toContain("Set");
+ expect(persisted).not.toContain("MASTER_KEY_SHOULD_NOT_PERSIST");
+ expect(persisted).not.toContain("auth-token-secret");
+
+ const resolved = contacts.resolveContactDisplay({ userID: 101 });
+ expect(resolved.profilePictureAttachmentID).toBe("ua_1");
+ });
+});
+
+describe("profile picture loading", () => {
+ test("negative-caches failed profile picture fetches and logs at info", async () => {
+ const { contacts, get_profile_picture, info } =
+ await setupContactsModule({
+ getProfilePictureError: new Error("network failure"),
+ });
+
+ await contacts.ensureContactsReady({
+ userID: 101,
+ masterKeyB64: "ignored",
+ });
+
+ await contacts.__testing.preloadResolvedContactAvatar({
+ userID: 101,
+ email: "[email protected]",
+ });
+ await contacts.__testing.preloadResolvedContactAvatar({
+ userID: 101,
+ email: "[email protected]",
+ });
+
+ expect(get_profile_picture).toHaveBeenCalledTimes(1);
+ expect(info).toHaveBeenCalledTimes(1);
+ expect(info.mock.calls[0]?.[0]).toContain(
+ "Failed to load contact profile picture for ct_1",
+ );
+ });
+
+ test("uses the inferred image mime type for avatar blobs", async () => {
+ const createObjectURL = vi.fn((_blob: Blob) => "blob:contact");
+ vi.stubGlobal("URL", {
+ createObjectURL,
+ revokeObjectURL: vi.fn(),
+ });
+ const pngBytes = Uint8Array.from([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
+ 0x00, 0x00, 0x00, 0x0d,
+ ]);
+ const { contacts } = await setupContactsModule({
+ getProfilePictureBytes: pngBytes,
+ });
+
+ await contacts.ensureContactsReady({
+ userID: 101,
+ masterKeyB64: "ignored",
+ });
+ await contacts.__testing.preloadResolvedContactAvatar({
+ userID: 101,
+ });
+
+ const blobArg = createObjectURL.mock.calls[0]?.[0] as Blob | undefined;
+ expect(blobArg?.type).toBe("image/png");
+ });
+});
+
+describe("retry after warm-up failure", () => {
+ test("retries with the last ready input after a transient failure", async () => {
+ vi.useFakeTimers();
+ const { contacts, get_diff } = await setupContactsModule();
+ get_diff.mockReset();
+ get_diff
+ .mockRejectedValueOnce(new Error("transient"))
+ .mockResolvedValueOnce([
+ {
+ id: "ct_1",
+ contactUserId: 101,
+ email: "[email protected]",
+ name: "Set",
+ profilePictureAttachmentID: "ua_1",
+ isDeleted: false,
+ updatedAt: 1,
+ },
+ ])
+ .mockResolvedValueOnce([]);
+
+ await expect(
+ contacts.ensureContactsReady({
+ userID: 101,
+ masterKeyB64: "ignored",
+ }),
+ ).rejects.toThrow("transient");
+ await vi.advanceTimersByTimeAsync(5_001);
+
+ expect(get_diff).toHaveBeenCalledTimes(3);
+ });
+});
diff --git a/web/packages/contacts/index.ts b/web/packages/contacts/index.ts
new file mode 100644
index 0000000000..d3aafcd1b0
--- /dev/null
+++ b/web/packages/contacts/index.ts
@@ -0,0 +1,549 @@
+import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
+import log from "ente-base/log";
+import { apiOrigin } from "ente-base/origins";
+import { savedAuthToken } from "ente-base/token";
+import {
+ contacts_open_ctx,
+ type ContactsCtxHandle,
+} from "ente-wasm";
+import {
+ saveContactDisplayRecords,
+ saveContactsSinceTime,
+ saveWrappedRootContactKey,
+ savedContactDisplayRecords,
+ savedContactsSinceTime,
+ savedWrappedRootContactKey,
+} from "./db";
+import {
+ knownEmailOrUndefined,
+ normalizeEmail,
+ resolveContactDisplayFromSnapshot,
+} from "./resolver";
+import type {
+ ContactDisplayRecord,
+ ContactLookup,
+ ContactsDisplaySnapshot,
+ ResolvedContactAvatar,
+ ResolvedContactDisplay,
+ WrappedRootContactKey,
+} from "./types";
+
+const CONTACT_DIFF_LIMIT = 500;
+const AVATAR_FAILURE_TTL_MS = 60_000;
+const READY_RETRY_COOLDOWN_MS = 5_000;
+const CONTACTS_CACHE_SCHEMA_VERSION = 2;
+
+type RemoteContactRecord = {
+ id: string;
+ contactUserId: number | bigint;
+ email?: string | null;
+ name?: string | null;
+ profilePictureAttachmentID?: string | null;
+ profilePictureAttachmentId?: string | null;
+ isDeleted: boolean;
+ updatedAt: number | bigint;
+};
+
+type ContactsReadyInput = {
+ userID: number;
+ masterKeyB64: string;
+};
+
+type ContactsState = {
+ snapshot: ContactsDisplaySnapshot;
+ listeners: Set<() => void>;
+ currentSessionKey: string | undefined;
+ currentAuthToken: string | undefined;
+ ctx: ContactsCtxHandle | undefined;
+ readyPromise: Promise<void> | undefined;
+ contactsByID: Map<string, ContactDisplayRecord>;
+ contactIDByUserID: Map<number, string>;
+ contactIDByEmail: Map<string, string>;
+ avatarURLByContactID: Map<string, string>;
+ avatarLoadsByContactID: Map<string, Promise<void>>;
+ avatarFailureUntilByContactID: Map<string, number>;
+ avatarListenersByContactID: Map<string, Set<() => void>>;
+ lastReadyInput: ContactsReadyInput | undefined;
+ retryTimer: ReturnType<typeof setTimeout> | undefined;
+};
+
+const emptySnapshot = (): ContactsDisplaySnapshot => ({
+ isHydrated: false,
+ recordsByUserID: new Map(),
+ recordsByEmail: new Map(),
+ avatarURLsByContactID: new Map(),
+});
+
+const state: ContactsState = {
+ snapshot: emptySnapshot(),
+ listeners: new Set(),
+ currentSessionKey: undefined,
+ currentAuthToken: undefined,
+ ctx: undefined,
+ readyPromise: undefined,
+ contactsByID: new Map(),
+ contactIDByUserID: new Map(),
+ contactIDByEmail: new Map(),
+ avatarURLByContactID: new Map(),
+ avatarLoadsByContactID: new Map(),
+ avatarFailureUntilByContactID: new Map(),
+ avatarListenersByContactID: new Map(),
+ lastReadyInput: undefined,
+ retryTimer: undefined,
+};
+
+const buildSessionKey = (baseURL: string, userID: number) =>
+ `${encodeURIComponent(baseURL)}:${userID}:v${CONTACTS_CACHE_SCHEMA_VERSION}`;
+
+const emitAvatarURL = (contactID: string) => {
+ const listeners = state.avatarListenersByContactID.get(contactID);
+ if (!listeners) {
+ return;
+ }
+ for (const listener of listeners) {
+ listener();
+ }
+};
+
+const cleanupAvatarURL = (contactID: string, shouldEmit = false) => {
+ const current = state.avatarURLByContactID.get(contactID);
+ if (current) {
+ URL.revokeObjectURL(current);
+ state.avatarURLByContactID.delete(contactID);
+ if (shouldEmit) {
+ emitAvatarURL(contactID);
+ }
+ }
+ state.avatarLoadsByContactID.delete(contactID);
+ state.avatarFailureUntilByContactID.delete(contactID);
+};
+
+const clearInMemoryState = () => {
+ for (const avatarURL of state.avatarURLByContactID.values()) {
+ URL.revokeObjectURL(avatarURL);
+ }
+ state.ctx = undefined;
+ state.currentAuthToken = undefined;
+ state.readyPromise = undefined;
+ state.contactsByID = new Map();
+ state.contactIDByUserID = new Map();
+ state.contactIDByEmail = new Map();
+ state.avatarURLByContactID = new Map();
+ state.avatarLoadsByContactID = new Map();
+ state.avatarFailureUntilByContactID = new Map();
+ if (state.retryTimer) {
+ clearTimeout(state.retryTimer);
+ state.retryTimer = undefined;
+ }
+};
+
+const emitSnapshot = (isHydrated = true) => {
+ state.snapshot = {
+ isHydrated,
+ recordsByUserID: new Map(
+ [...state.contactIDByUserID.entries()]
+ .map(([userID, contactID]) => [
+ userID,
+ state.contactsByID.get(contactID),
+ ])
+ .filter(
+ (entry): entry is [number, ContactDisplayRecord] =>
+ entry[1] !== undefined,
+ ),
+ ),
+ recordsByEmail: new Map(
+ [...state.contactIDByEmail.entries()]
+ .map(([email, contactID]) => [
+ email,
+ state.contactsByID.get(contactID),
+ ])
+ .filter(
+ (entry): entry is [string, ContactDisplayRecord] =>
+ entry[1] !== undefined,
+ ),
+ ),
+ avatarURLsByContactID: new Map(state.avatarURLByContactID),
+ };
+
+ for (const listener of state.listeners) {
+ listener();
+ }
+};
+
+const removeContact = (contactID: string) => {
+ const previous = state.contactsByID.get(contactID);
+ if (!previous) return;
+
+ state.contactsByID.delete(contactID);
+ state.contactIDByUserID.delete(previous.contactUserId);
+ const normalizedEmail = normalizeEmail(previous.resolvedEmail);
+ if (normalizedEmail) {
+ state.contactIDByEmail.delete(normalizedEmail);
+ }
+ cleanupAvatarURL(contactID, true);
+};
+
+const upsertContact = (record: ContactDisplayRecord) => {
+ const previous = state.contactsByID.get(record.contactId);
+ if (previous) {
+ if (previous.contactUserId !== record.contactUserId) {
+ state.contactIDByUserID.delete(previous.contactUserId);
+ }
+ const previousEmail = normalizeEmail(previous.resolvedEmail);
+ const nextEmail = normalizeEmail(record.resolvedEmail);
+ if (previousEmail && previousEmail !== nextEmail) {
+ state.contactIDByEmail.delete(previousEmail);
+ }
+ if (
+ previous.profilePictureAttachmentID !==
+ record.profilePictureAttachmentID
+ ) {
+ cleanupAvatarURL(record.contactId, true);
+ }
+ }
+
+ state.contactsByID.set(record.contactId, record);
+ state.contactIDByUserID.set(record.contactUserId, record.contactId);
+
+ const normalizedEmail = normalizeEmail(record.resolvedEmail);
+ if (normalizedEmail) {
+ state.contactIDByEmail.set(normalizedEmail, record.contactId);
+ }
+};
+
+const contactDisplayRecordFromRemote = (
+ record: RemoteContactRecord,
+): ContactDisplayRecord => ({
+ contactId: record.id,
+ contactUserId: Number(record.contactUserId),
+ resolvedEmail: knownEmailOrUndefined(record.email),
+ displayName: knownEmailOrUndefined(record.name),
+ profilePictureAttachmentID:
+ knownEmailOrUndefined(
+ record.profilePictureAttachmentID ??
+ record.profilePictureAttachmentId,
+ ),
+ updatedAt: Number(record.updatedAt),
+});
+
+export const resolveContactDisplay = (
+ lookup: ContactLookup,
+): ResolvedContactDisplay =>
+ resolveContactDisplayFromSnapshot(state.snapshot, lookup);
+
+export const resolveKnownEmail = (lookup: ContactLookup) =>
+ resolveContactDisplay(lookup).actualEmail;
+
+export const contactsDisplaySubscribe = (onChange: () => void) => {
+ state.listeners.add(onChange);
+ return () => {
+ state.listeners.delete(onChange);
+ };
+};
+
+const subscribeAvatarURL = (contactID: string, onChange: () => void) => {
+ const listeners =
+ state.avatarListenersByContactID.get(contactID) ?? new Set<() => void>();
+ listeners.add(onChange);
+ state.avatarListenersByContactID.set(contactID, listeners);
+ return () => {
+ listeners.delete(onChange);
+ if (listeners.size === 0) {
+ state.avatarListenersByContactID.delete(contactID);
+ }
+ };
+};
+
+const avatarURLSnapshot = (contactID: string | undefined) =>
+ contactID ? state.avatarURLByContactID.get(contactID) : undefined;
+
+export const contactsDisplaySnapshot = () => state.snapshot;
+
+const useContactsSnapshot = () =>
+ useSyncExternalStore(
+ contactsDisplaySubscribe,
+ contactsDisplaySnapshot,
+ contactsDisplaySnapshot,
+ );
+
+const loadLocalSessionState = async (sessionKey: string) => {
+ clearInMemoryState();
+ state.currentSessionKey = sessionKey;
+
+ const savedRecords = await savedContactDisplayRecords(sessionKey);
+ for (const record of savedRecords) {
+ upsertContact(record);
+ }
+
+ emitSnapshot(true);
+};
+
+const syncContacts = async ({
+ sessionKey,
+ baseURL,
+ authToken,
+ userID,
+ masterKeyB64,
+}: ContactsReadyInput & {
+ sessionKey: string;
+ baseURL: string;
+ authToken: string;
+}) => {
+ if (!state.ctx) {
+ state.ctx = await contacts_open_ctx({
+ baseUrl: baseURL,
+ authToken,
+ userId: userID,
+ masterKeyB64,
+ cachedRootKey: await savedWrappedRootContactKey(sessionKey),
+ });
+ const wrappedRootKey =
+ state.ctx.current_wrapped_root_key() as WrappedRootContactKey;
+ await saveWrappedRootContactKey(sessionKey, wrappedRootKey);
+ } else if (state.currentAuthToken !== authToken) {
+ state.ctx.update_auth_token(authToken);
+ }
+
+ if (!state.ctx || state.currentSessionKey !== sessionKey) {
+ return;
+ }
+
+ const ctx = state.ctx;
+ state.currentAuthToken = authToken;
+
+ let sinceTime = (await savedContactsSinceTime(sessionKey)) ?? 0;
+ let didChange = false;
+
+ while (true) {
+ const diff = (await ctx.get_diff(
+ BigInt(sinceTime),
+ CONTACT_DIFF_LIMIT,
+ )) as RemoteContactRecord[];
+ if (state.currentSessionKey !== sessionKey) {
+ return;
+ }
+ if (diff.length === 0) {
+ break;
+ }
+
+ didChange = true;
+ for (const record of diff) {
+ if (record.isDeleted) {
+ removeContact(record.id);
+ } else {
+ upsertContact(contactDisplayRecordFromRemote(record));
+ }
+ sinceTime = Math.max(sinceTime, Number(record.updatedAt));
+ }
+ }
+
+ if (didChange) {
+ if (state.currentSessionKey !== sessionKey) {
+ return;
+ }
+ await saveContactDisplayRecords(
+ sessionKey,
+ [...state.contactsByID.values()],
+ );
+ await saveContactsSinceTime(sessionKey, sinceTime);
+ emitSnapshot(true);
+ }
+};
+
+export const ensureContactsReady = async ({
+ userID,
+ masterKeyB64,
+}: ContactsReadyInput) => {
+ state.lastReadyInput = { userID, masterKeyB64 };
+ const authToken = await savedAuthToken();
+ if (!authToken) {
+ return;
+ }
+
+ const baseURL = await apiOrigin();
+ const sessionKey = buildSessionKey(baseURL, userID);
+
+ if (state.currentSessionKey !== sessionKey) {
+ await loadLocalSessionState(sessionKey);
+ }
+
+ if (state.readyPromise) {
+ return state.readyPromise;
+ }
+
+ state.readyPromise = syncContacts({
+ sessionKey,
+ baseURL,
+ authToken,
+ userID,
+ masterKeyB64,
+ })
+ .then(() => {
+ if (state.retryTimer) {
+ clearTimeout(state.retryTimer);
+ state.retryTimer = undefined;
+ }
+ })
+ .catch((error) => {
+ if (state.retryTimer) {
+ clearTimeout(state.retryTimer);
+ }
+ const retryInput = state.lastReadyInput;
+ state.retryTimer = setTimeout(() => {
+ state.retryTimer = undefined;
+ if (retryInput) {
+ void ensureContactsReady(retryInput).catch(() => undefined);
+ }
+ }, READY_RETRY_COOLDOWN_MS);
+ throw error;
+ })
+ .finally(() => {
+ state.readyPromise = undefined;
+ });
+
+ return state.readyPromise;
+};
+
+const inferImageMimeType = (bytes: Uint8Array) => {
+ if (
+ bytes.length >= 12 &&
+ bytes[0] === 0x52 &&
+ bytes[1] === 0x49 &&
+ bytes[2] === 0x46 &&
+ bytes[3] === 0x46 &&
+ bytes[8] === 0x57 &&
+ bytes[9] === 0x45 &&
+ bytes[10] === 0x42 &&
+ bytes[11] === 0x50
+ ) {
+ return "image/webp";
+ }
+ if (
+ bytes.length >= 8 &&
+ bytes[0] === 0x89 &&
+ bytes[1] === 0x50 &&
+ bytes[2] === 0x4e &&
+ bytes[3] === 0x47 &&
+ bytes[4] === 0x0d &&
+ bytes[5] === 0x0a &&
+ bytes[6] === 0x1a &&
+ bytes[7] === 0x0a
+ ) {
+ return "image/png";
+ }
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
+ return "image/jpeg";
+ }
+ if (
+ bytes.length >= 6 &&
+ bytes[0] === 0x47 &&
+ bytes[1] === 0x49 &&
+ bytes[2] === 0x46 &&
+ bytes[3] === 0x38
+ ) {
+ return "image/gif";
+ }
+ return "application/octet-stream";
+};
+
+const ensureProfilePictureLoaded = async (contactID: string) => {
+ const contact = state.contactsByID.get(contactID);
+ if (!contact?.profilePictureAttachmentID || !state.ctx) {
+ return;
+ }
+
+ if (state.avatarURLByContactID.has(contactID)) {
+ return;
+ }
+
+ const failureUntil = state.avatarFailureUntilByContactID.get(contactID);
+ if (failureUntil && failureUntil > Date.now()) {
+ return;
+ }
+
+ const existingLoad = state.avatarLoadsByContactID.get(contactID);
+ if (existingLoad) {
+ await existingLoad;
+ return;
+ }
+
+ const load = state.ctx
+ .get_profile_picture(contactID)
+ .then((bytes: Uint8Array) => {
+ const blob = new Blob([bytes], {
+ type: inferImageMimeType(bytes),
+ });
+ const url = URL.createObjectURL(blob);
+ cleanupAvatarURL(contactID);
+ state.avatarURLByContactID.set(contactID, url);
+ state.avatarFailureUntilByContactID.delete(contactID);
+ emitAvatarURL(contactID);
+ })
+ .catch((error: unknown) => {
+ state.avatarFailureUntilByContactID.set(
+ contactID,
+ Date.now() + AVATAR_FAILURE_TTL_MS,
+ );
+ log.info(
+ `[contacts] Failed to load contact profile picture for ${contactID}`,
+ error,
+ );
+ })
+ .finally(() => {
+ state.avatarLoadsByContactID.delete(contactID);
+ });
+
+ state.avatarLoadsByContactID.set(contactID, load);
+ await load;
+};
+
+export const __testing = {
+ preloadResolvedContactAvatar: async (lookup: ContactLookup) => {
+ const display = resolveContactDisplay(lookup);
+ if (!display.contactId || !display.profilePictureAttachmentID) {
+ return;
+ }
+ await ensureProfilePictureLoaded(display.contactId);
+ },
+};
+
+export const useResolvedContactDisplay = (lookup: ContactLookup) => {
+ const snapshot = useContactsSnapshot();
+ return useMemo(
+ () => resolveContactDisplayFromSnapshot(snapshot, lookup),
+ [lookup.email, lookup.userID, snapshot],
+ );
+};
+
+export const useResolvedContactAvatar = (
+ lookup: ContactLookup,
+): ResolvedContactAvatar => {
+ const snapshot = useContactsSnapshot();
+ const display = useMemo(
+ () => resolveContactDisplayFromSnapshot(snapshot, lookup),
+ [lookup.email, lookup.userID, snapshot],
+ );
+ const avatarURL = useSyncExternalStore(
+ useCallback(
+ (onChange: () => void) =>
+ display.contactId
+ ? subscribeAvatarURL(display.contactId, onChange)
+ : () => undefined,
+ [display.contactId],
+ ),
+ () => avatarURLSnapshot(display.contactId),
+ () => avatarURLSnapshot(display.contactId),
+ );
+
+ useEffect(() => {
+ if (!display.contactId || !display.profilePictureAttachmentID) {
+ return;
+ }
+ void ensureProfilePictureLoaded(display.contactId);
+ }, [display.contactId, display.profilePictureAttachmentID]);
+
+ return {
+ ...display,
+ avatarURL,
+ };
+};
diff --git a/web/packages/contacts/package.json b/web/packages/contacts/package.json
new file mode 100644
index 0000000000..5dc682f1c3
--- /dev/null
+++ b/web/packages/contacts/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "ente-contacts-web",
+ "version": "0.0.0",
+ "private": true,
+ "main": "./index.ts",
+ "types": "./index.ts",
+ "dependencies": {
+ "ente-base": "*",
+ "ente-wasm": "*",
+ "react": "^19.2.0",
+ "zod": "^4.1.12"
+ },
+ "devDependencies": {
+ "@types/react": "^19.2.2",
+ "ente-build-config": "*",
+ "vitest": "^3.2.4"
+ },
+ "scripts": {
+ "test": "vitest"
+ }
+}
diff --git a/web/packages/contacts/resolver.ts b/web/packages/contacts/resolver.ts
new file mode 100644
index 0000000000..1f8a18ac06
--- /dev/null
+++ b/web/packages/contacts/resolver.ts
@@ -0,0 +1,49 @@
+import type {
+ ContactLookup,
+ ContactsDisplaySnapshot,
+ ResolvedContactDisplay,
+} from "./types";
+
+const SOMEONE_LABEL = "Someone";
+
+export const normalizeEmail = (email?: string | null) => email?.trim().toLowerCase();
+
+export const knownEmailOrUndefined = (email?: string | null) => {
+ const trimmed = email?.trim();
+ return trimmed ? trimmed : undefined;
+};
+
+const contactRecordForLookup = (
+ snapshot: ContactsDisplaySnapshot,
+ lookup: ContactLookup,
+) => {
+ if (lookup.userID !== undefined) {
+ const byUserID = snapshot.recordsByUserID.get(lookup.userID);
+ if (byUserID) return byUserID;
+ }
+
+ const normalizedEmail = normalizeEmail(lookup.email);
+ return normalizedEmail
+ ? snapshot.recordsByEmail.get(normalizedEmail)
+ : undefined;
+};
+
+export const resolveContactDisplayFromSnapshot = (
+ snapshot: ContactsDisplaySnapshot,
+ lookup: ContactLookup,
+): ResolvedContactDisplay => {
+ const matched = contactRecordForLookup(snapshot, lookup);
+ const actualEmail =
+ matched?.resolvedEmail ?? knownEmailOrUndefined(lookup.email);
+ const primaryLabel =
+ matched?.displayName ?? actualEmail ?? SOMEONE_LABEL;
+
+ return {
+ contactId: matched?.contactId,
+ profilePictureAttachmentID: matched?.profilePictureAttachmentID,
+ primaryLabel,
+ actualEmail,
+ initial: primaryLabel[0]?.toUpperCase() ?? "S",
+ source: matched ? "contact" : "fallback",
+ };
+};
diff --git a/web/packages/contacts/tsconfig.json b/web/packages/contacts/tsconfig.json
new file mode 100644
index 0000000000..da0ebfdddb
--- /dev/null
+++ b/web/packages/contacts/tsconfig.json
@@ -0,0 +1,4 @@
+{
+ "extends": "ente-build-config/tsconfig-typecheck.json",
+ "include": [".", "../base/global-electron.d.ts"]
+}
diff --git a/web/packages/contacts/types.ts b/web/packages/contacts/types.ts
new file mode 100644
index 0000000000..489961f215
--- /dev/null
+++ b/web/packages/contacts/types.ts
@@ -0,0 +1,38 @@
+export interface WrappedRootContactKey {
+ encryptedKey: string;
+ header: string;
+}
+
+export interface ContactDisplayRecord {
+ contactId: string;
+ contactUserId: number;
+ resolvedEmail: string | undefined;
+ displayName: string | undefined;
+ profilePictureAttachmentID: string | undefined;
+ updatedAt: number;
+}
+
+export interface ContactLookup {
+ userID?: number;
+ email?: string;
+}
+
+export interface ContactsDisplaySnapshot {
+ isHydrated: boolean;
+ recordsByUserID: ReadonlyMap<number, ContactDisplayRecord>;
+ recordsByEmail: ReadonlyMap<string, ContactDisplayRecord>;
+ avatarURLsByContactID: ReadonlyMap<string, string>;
+}
+
+export interface ResolvedContactDisplay {
+ contactId: string | undefined;
+ profilePictureAttachmentID: string | undefined;
+ primaryLabel: string;
+ actualEmail: string | undefined;
+ initial: string;
+ source: "contact" | "fallback";
+}
+
+export interface ResolvedContactAvatar extends ResolvedContactDisplay {
+ avatarURL: string | undefined;
+}
diff --git a/web/packages/gallery/components/viewer/CommentsSidebar.tsx b/web/packages/gallery/components/viewer/CommentsSidebar.tsx
index b4850dfe3f..5b328870f7 100644
--- a/web/packages/gallery/components/viewer/CommentsSidebar.tsx
+++ b/web/packages/gallery/components/viewer/CommentsSidebar.tsx
@@ -12,6 +12,10 @@ import {
TextField,
Typography,
} from "@mui/material";
+import {
+ useResolvedContactAvatar,
+ useResolvedContactDisplay,
+} from "ente-contacts-web";
import { type ModalVisibilityProps } from "ente-base/components/utils/modal";
import log from "ente-base/log";
import { downloadManager } from "ente-gallery/services/download";
@@ -225,6 +229,9 @@ interface CommentHeaderProps {
isMaskedEmail?: boolean;
/** Key used for computing avatar color (e.g., anonUserID for anonymous users). */
avatarColorKey?: string;
+ userID?: number;
+ email?: string;
+ useContactDisplay?: boolean;
}
/**
@@ -237,24 +244,42 @@ const CommentHeader: React.FC<CommentHeaderProps> = ({
avatarSize = 32,
isMaskedEmail,
avatarColorKey,
-}) => (
- <CommentHeaderContainer>
- <Avatar
- sx={{
- width: avatarSize,
- height: avatarSize,
- fontSize: 14,
- bgcolor: getAvatarColor(avatarColorKey ?? userName),
- color: "#fff",
- }}
- >
- {isMaskedEmail ? <PersonIcon /> : userName[0]?.toUpperCase()}
- </Avatar>
- <UserName>{userName}</UserName>
- <Separator>β€’</Separator>
- <Timestamp>{formatTimeAgo(timestamp)}</Timestamp>
- </CommentHeaderContainer>
-);
+ userID,
+ email,
+ useContactDisplay,
+}) => {
+ const resolved = useResolvedContactAvatar({
+ userID: useContactDisplay ? userID : undefined,
+ email: useContactDisplay ? email : undefined,
+ });
+ const displayName = useContactDisplay ? resolved.primaryLabel : userName;
+
+ return (
+ <CommentHeaderContainer>
+ <Avatar
+ sx={{
+ width: avatarSize,
+ height: avatarSize,
+ fontSize: 14,
+ bgcolor: getAvatarColor(avatarColorKey ?? email ?? userName),
+ color: "#fff",
+ }}
+ src={useContactDisplay ? resolved.avatarURL : undefined}
+ >
+ {isMaskedEmail ? (
+ <PersonIcon />
+ ) : (
+ (useContactDisplay
+ ? resolved.initial
+ : userName[0]?.toUpperCase())
+ )}
+ </Avatar>
+ <UserName>{displayName}</UserName>
+ <Separator>β€’</Separator>
+ <Timestamp>{formatTimeAgo(timestamp)}</Timestamp>
+ </CommentHeaderContainer>
+ );
+};
interface QuotedReplyProps {
parentComment: Comment;
@@ -276,6 +301,18 @@ const QuotedReply: React.FC<QuotedReplyProps> = ({
anonUserNames,
currentAnonUserID,
}) => {
+ const parentEmail = userIDToEmail?.get(parentComment.userID);
+ const shouldResolveParent =
+ currentUserID !== undefined &&
+ parentComment.userID > 0 &&
+ !parentComment.anonUserID &&
+ !!parentEmail &&
+ !parentEmail.startsWith("*");
+ const resolvedParent = useResolvedContactDisplay({
+ userID: shouldResolveParent ? parentComment.userID : undefined,
+ email: shouldResolveParent ? parentEmail : undefined,
+ });
+
// Get the author name
const getAuthorName = (): string => {
// Check if this is the current user (logged in or anonymous)
@@ -298,8 +335,9 @@ const QuotedReply: React.FC<QuotedReplyProps> = ({
}
// For registered users, look up email
- const email = userIDToEmail?.get(parentComment.userID);
- return email ?? t("user");
+ return shouldResolveParent
+ ? resolvedParent.primaryLabel
+ : (parentEmail ?? t("user"));
};
return (
@@ -1305,6 +1343,9 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
name: string;
avatarColorKey: string;
isMaskedEmail: boolean;
+ email?: string;
+ userID?: number;
+ useContactDisplay: boolean;
} => {
// If anonymous user, check anonUserNames map
if (comment.anonUserID) {
@@ -1318,6 +1359,7 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
// Use name for avatar color (varying length like mobile emails)
avatarColorKey: anonName,
isMaskedEmail: false,
+ useContactDisplay: false,
};
}
// For registered users, use email
@@ -1333,6 +1375,11 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
? emailFromMap
: String(comment.userID),
isMaskedEmail: email.startsWith("*"),
+ email: emailFromMap,
+ userID: comment.userID,
+ useContactDisplay:
+ currentUserID !== undefined &&
+ !email.startsWith("*"),
};
};
@@ -1350,6 +1397,11 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
avatarColorKey={
authorInfo.avatarColorKey
}
+ email={authorInfo.email}
+ userID={authorInfo.userID}
+ useContactDisplay={
+ authorInfo.useContactDisplay
+ }
/>
)}
{showOwnTimestamp && (
diff --git a/web/packages/gallery/components/viewer/LikesSidebar.tsx b/web/packages/gallery/components/viewer/LikesSidebar.tsx
index 91b2bf9e47..8846f7ca4b 100644
--- a/web/packages/gallery/components/viewer/LikesSidebar.tsx
+++ b/web/packages/gallery/components/viewer/LikesSidebar.tsx
@@ -9,6 +9,7 @@ import {
styled,
Typography,
} from "@mui/material";
+import { useResolvedContactAvatar } from "ente-contacts-web";
import { type ModalVisibilityProps } from "ente-base/components/utils/modal";
import log from "ente-base/log";
import { downloadManager } from "ente-gallery/services/download";
@@ -95,8 +96,48 @@ interface Liker {
avatarInitial: string;
/** True if this is a registered user with masked email (show person icon). */
isMaskedEmail: boolean;
+ isCurrentUser: boolean;
}
+const LikerRowItem: React.FC<{ liker: Liker }> = ({ liker }) => {
+ const shouldResolveContact =
+ !liker.anonUserID &&
+ liker.userID > 0 &&
+ !liker.isMaskedEmail &&
+ !liker.isCurrentUser;
+ const resolved = useResolvedContactAvatar({
+ userID: shouldResolveContact ? liker.userID : undefined,
+ email: shouldResolveContact ? liker.email : undefined,
+ });
+
+ return (
+ <LikerRow>
+ <Avatar
+ sx={{
+ width: 32,
+ height: 32,
+ fontSize: 14,
+ bgcolor: getAvatarColor(liker.email),
+ color: "#fff",
+ }}
+ src={resolved.avatarURL}
+ >
+ {liker.isMaskedEmail ? (
+ <PersonIcon />
+ ) : (
+ (shouldResolveContact
+ ? resolved.initial
+ : liker.avatarInitial)
+ )}
+ </Avatar>
+ <LikerName>
+ {shouldResolveContact ? resolved.primaryLabel : liker.userName}
+ </LikerName>
+ <HeartFilledIcon />
+ </LikerRow>
+ );
+};
+
/** Collection info for the dropdown. */
interface CollectionInfo {
id: number;
@@ -289,6 +330,7 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({
email,
avatarInitial: actualName[0]?.toUpperCase() ?? "?",
isMaskedEmail,
+ isCurrentUser,
};
});
}, [
@@ -576,25 +618,7 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({
<EmptyMessage>{t("no_likes_yet")}</EmptyMessage>
) : (
likers.map((liker) => (
- <LikerRow key={liker.id}>
- <Avatar
- sx={{
- width: 32,
- height: 32,
- fontSize: 14,
- bgcolor: getAvatarColor(liker.email),
- color: "#fff",
- }}
- >
- {liker.isMaskedEmail ? (
- <PersonIcon />
- ) : (
- liker.avatarInitial
- )}
- </Avatar>
- <LikerName>{liker.userName}</LikerName>
- <HeartFilledIcon />
- </LikerRow>
+ <LikerRowItem key={liker.id} liker={liker} />
))
)}
</LikersContainer>
diff --git a/web/packages/gallery/package.json b/web/packages/gallery/package.json
index a3346ddd5e..a87ba2b04a 100644
--- a/web/packages/gallery/package.json
+++ b/web/packages/gallery/package.json
@@ -8,6 +8,7 @@
"@hugeicons/react": "^1.1.4",
"bs58": "^6.0.0",
"ente-base": "*",
+ "ente-contacts-web": "*",
"ente-utils": "*",
"exifreader": "^4.32.0",
"hls-video-element": "^1.5.8",
diff --git a/web/packages/wasm/Cargo.lock b/web/packages/wasm/Cargo.lock
index 48ed0caf7e..6130185aee 100644
--- a/web/packages/wasm/Cargo.lock
+++ b/web/packages/wasm/Cargo.lock
@@ -303,6 +303,17 @@ dependencies = [
"cfg-if",
]
+[[package]]
+name = "ente-contacts"
+version = "0.0.1"
+dependencies = [
+ "ente-core",
+ "md-5",
+ "serde",
+ "serde_json",
+ "thiserror",
+]
+
[[package]]
name = "ente-core"
version = "0.0.1"
@@ -333,8 +344,10 @@ dependencies = [
name = "ente-wasm"
version = "0.0.1"
dependencies = [
+ "ente-contacts",
"ente-core",
"md-5",
+ "serde",
"serde-wasm-bindgen",
"wasm-bindgen",
"wasm-bindgen-futures",
diff --git a/web/packages/wasm/Cargo.toml b/web/packages/wasm/Cargo.toml
index 38e32136ef..82937d629c 100644
--- a/web/packages/wasm/Cargo.toml
+++ b/web/packages/wasm/Cargo.toml
@@ -7,8 +7,10 @@ edition = "2024"
crate-type = ["cdylib"]
[dependencies]
+ente-contacts = { path = "../../../rust/contacts" }
ente-core = { path = "../../../rust/core", features = ["srp"] }
md-5 = "0.10"
+serde = { version = "1", features = ["derive"] }
serde-wasm-bindgen = "0.6"
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
diff --git a/web/packages/wasm/src/contacts.rs b/web/packages/wasm/src/contacts.rs
new file mode 100644
index 0000000000..dfad4a456d
--- /dev/null
+++ b/web/packages/wasm/src/contacts.rs
@@ -0,0 +1,166 @@
+//! WASM bindings for contacts sync and attachment reads.
+
+use ente_contacts::{
+ ContactsCtx, ContactsError as CoreContactsError, OpenContactsCtxInput, WrappedRootContactKey,
+};
+use ente_core::crypto;
+use serde::{Deserialize, Serialize};
+use serde_wasm_bindgen as swb;
+use wasm_bindgen::prelude::*;
+
+/// Contacts error.
+#[wasm_bindgen]
+pub struct ContactsError {
+ code: String,
+ message: String,
+}
+
+#[wasm_bindgen]
+impl ContactsError {
+ /// Machine-readable error code.
+ #[wasm_bindgen(getter)]
+ pub fn code(&self) -> String {
+ self.code.clone()
+ }
+
+ /// Human-readable error message.
+ #[wasm_bindgen(getter)]
+ pub fn message(&self) -> String {
+ self.message.clone()
+ }
+}
+
+impl From<CoreContactsError> for ContactsError {
+ fn from(e: CoreContactsError) -> Self {
+ let code = match &e {
+ CoreContactsError::Http(_) => "http",
+ CoreContactsError::Crypto(_) => "crypto",
+ CoreContactsError::InvalidInput(_) => "invalid_input",
+ CoreContactsError::MissingEncryptedData => "missing_encrypted_data",
+ CoreContactsError::MissingEncryptedKey => "missing_encrypted_key",
+ CoreContactsError::ProfilePictureNotFound => "profile_picture_not_found",
+ }
+ .to_string();
+
+ Self {
+ code,
+ message: e.to_string(),
+ }
+ }
+}
+
+impl From<swb::Error> for ContactsError {
+ fn from(e: swb::Error) -> Self {
+ Self {
+ code: "serde".to_string(),
+ message: e.to_string(),
+ }
+ }
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct OpenContactsCtxJsInput {
+ base_url: String,
+ auth_token: String,
+ user_id: i64,
+ master_key_b64: String,
+ cached_root_key: Option<WrappedRootContactKey>,
+ user_agent: Option<String>,
+ client_package: Option<String>,
+ client_version: Option<String>,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct ContactRecordJs {
+ id: String,
+ contact_user_id: i64,
+ email: Option<String>,
+ name: Option<String>,
+ birth_date: Option<String>,
+ #[serde(rename = "profilePictureAttachmentID")]
+ profile_picture_attachment_id: Option<String>,
+ is_deleted: bool,
+ created_at: i64,
+ updated_at: i64,
+}
+
+impl From<ente_contacts::ContactRecord> for ContactRecordJs {
+ fn from(value: ente_contacts::ContactRecord) -> Self {
+ Self {
+ id: value.id,
+ contact_user_id: value.contact_user_id,
+ email: value.email,
+ name: value.name,
+ birth_date: value.birth_date,
+ profile_picture_attachment_id: value.profile_picture_attachment_id,
+ is_deleted: value.is_deleted,
+ created_at: value.created_at,
+ updated_at: value.updated_at,
+ }
+ }
+}
+
+/// Open contacts context for web.
+#[wasm_bindgen]
+pub async fn contacts_open_ctx(input: JsValue) -> Result<ContactsCtxHandle, ContactsError> {
+ let input: OpenContactsCtxJsInput = swb::from_value(input)?;
+ let master_key = crypto::decode_b64(&input.master_key_b64).map_err(|e| ContactsError {
+ code: "decode".to_string(),
+ message: e.to_string(),
+ })?;
+
+ let result = ContactsCtx::open(OpenContactsCtxInput {
+ base_url: input.base_url,
+ auth_token: input.auth_token,
+ user_id: input.user_id,
+ master_key,
+ cached_root_key: input.cached_root_key,
+ user_agent: input.user_agent,
+ client_package: input.client_package,
+ client_version: input.client_version,
+ })
+ .await?;
+
+ Ok(ContactsCtxHandle { inner: result.ctx })
+}
+
+/// Handle to an open contacts context.
+#[wasm_bindgen]
+pub struct ContactsCtxHandle {
+ inner: ContactsCtx,
+}
+
+#[wasm_bindgen]
+impl ContactsCtxHandle {
+ /// Update auth token without rebuilding the contacts context.
+ pub fn update_auth_token(&self, auth_token: String) {
+ self.inner.update_auth_token(auth_token);
+ }
+
+ /// Return the wrapped root key currently held by this context.
+ pub fn current_wrapped_root_key(&self) -> Result<JsValue, ContactsError> {
+ swb::to_value(&self.inner.current_wrapped_root_key()).map_err(Into::into)
+ }
+
+ /// Pull a diff page of contacts.
+ pub async fn get_diff(&self, since_time: i64, limit: u16) -> Result<JsValue, ContactsError> {
+ let diff: Vec<ContactRecordJs> = self
+ .inner
+ .get_diff(since_time, limit)
+ .await?
+ .into_iter()
+ .map(Into::into)
+ .collect();
+ swb::to_value(&diff).map_err(Into::into)
+ }
+
+ /// Fetch and decrypt the profile picture bytes for a contact.
+ pub async fn get_profile_picture(&self, contact_id: &str) -> Result<Vec<u8>, ContactsError> {
+ self.inner
+ .get_profile_picture(contact_id)
+ .await
+ .map_err(Into::into)
+ }
+}
diff --git a/web/packages/wasm/src/lib.rs b/web/packages/wasm/src/lib.rs
index 274cfab073..3ba0ce3833 100644
--- a/web/packages/wasm/src/lib.rs
+++ b/web/packages/wasm/src/lib.rs
@@ -1,6 +1,7 @@
//! WASM bindings for Ente web apps.
mod auth;
+mod contacts;
mod crypto;
mod http;
mod urls;