π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[photos][web] Add activity feed to navigation rail (#14300)
Aswin Asok25445215f5b7
diff --git a/web/apps/photos/public/images/feed/empty.png b/web/apps/photos/public/images/feed/empty.pngnew file mode 100644index 0000000000..031c7edd11Binary files /dev/null and b/web/apps/photos/public/images/feed/empty.png differdiff --git a/web/apps/photos/src/components/gallery/hooks/use-gallery-library.ts b/web/apps/photos/src/components/gallery/hooks/use-gallery-library.tsindex d5ea03048b..3238ed9ee8 100644--- a/web/apps/photos/src/components/gallery/hooks/use-gallery-library.ts+++ b/web/apps/photos/src/components/gallery/hooks/use-gallery-library.ts@@ -54,6 +54,7 @@ export const useGalleryLibrary = () => {const [state, dispatch] = useGalleryReducer();const [searchIndexRevision, setSearchIndexRevision] = useState(0);+ const [remotePullRevision, setRemotePullRevision] = useState(0);const [isFirstLoad, setIsFirstLoad] = useState(false);// Pull pipelines mutate the same local DB and reducer state.const remoteFilesPullQueue = useRef(new PromiseQueue<void>());@@ -117,6 +118,7 @@ export const useGalleryLibrary = () => {await prePullFiles();await remoteFilesPull();await postPullFiles(source);+ setRemotePullRevision((revision) => revision + 1);} catch (e) {// A later pull retries transient failures after remote mutations.log.error("Remote pull failed", e);@@ -269,6 +271,7 @@ export const useGalleryLibrary = () => {dispatch,isFirstLoad,searchIndexRevision,+ remotePullRevision,peopleState,remotePull,remoteFilesPull,diff --git a/web/apps/photos/src/components/gallery/navigation/PhotosNavigationShell.tsx b/web/apps/photos/src/components/gallery/navigation/PhotosNavigationShell.tsxindex ec994cc7f5..262f1187d4 100644--- a/web/apps/photos/src/components/gallery/navigation/PhotosNavigationShell.tsx+++ b/web/apps/photos/src/components/gallery/navigation/PhotosNavigationShell.tsx@@ -370,7 +370,11 @@ const NormalNavigationRail = ({color="secondary"aria-label={rail.label()}aria-pressed={selected}- aria-haspopup={mobile ? "dialog" : undefined}+ aria-haspopup={+ mobile && definition.hasNavigation+ ? "dialog"+ : undefined+ }onClick={() => onSelect(id)}sx={{minWidth: 0,diff --git a/web/apps/photos/src/components/gallery/sections/feed/FeedIcons.tsx b/web/apps/photos/src/components/gallery/sections/feed/FeedIcons.tsxnew file mode 100644index 0000000000..0dac23bdf6--- /dev/null+++ b/web/apps/photos/src/components/gallery/sections/feed/FeedIcons.tsx@@ -0,0 +1,65 @@+import type { FeedItemType } from "@/services/feed";+import {+ Add01Icon,+ BubbleChatIcon,+ FavouriteIcon,+ ReplyIcon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { Box } from "@mui/material";++export const FeedActivityIcon = ({ type }: { type: FeedItemType }) => {+ const isReply = type === "reply" || type === "replyLike";+ const commentLike = type === "commentLike" || type === "replyLike";+ return (+ <Box+ aria-hidden+ sx={{+ width: 32,+ height: 32,+ borderRadius: "50%",+ bgcolor: "fill.faint",+ position: "relative",+ display: "grid",+ placeItems: "center",+ flexShrink: 0,+ color: type === "photoLike" ? "accent.main" : "text.base",+ }}+ >+ <HugeiconsIcon+ icon={+ type === "photoLike"+ ? FavouriteIcon+ : type === "sharedPhoto" || type === "sharedCollection"+ ? Add01Icon+ : isReply+ ? ReplyIcon+ : BubbleChatIcon+ }+ size={18}+ strokeWidth={1.8}+ fill={type === "photoLike" ? "currentColor" : "none"}+ />+ {commentLike && (+ <Box+ sx={{+ position: "absolute",+ right: 3,+ bottom: 3,+ width: 10,+ height: 10,+ display: "flex",+ color: "accent.main",+ }}+ >+ <HugeiconsIcon+ icon={FavouriteIcon}+ size={10}+ strokeWidth={1.8}+ fill="currentColor"+ />+ </Box>+ )}+ </Box>+ );+};diff --git a/web/apps/photos/src/components/gallery/sections/feed/FeedItemRow.tsx b/web/apps/photos/src/components/gallery/sections/feed/FeedItemRow.tsxnew file mode 100644index 0000000000..4a01743415--- /dev/null+++ b/web/apps/photos/src/components/gallery/sections/feed/FeedItemRow.tsx@@ -0,0 +1,323 @@+import { feedActorKey, type FeedActor, type FeedItem } from "@/services/feed";+import {+ Avatar,+ Box,+ ButtonBase,+ Stack,+ styled,+ Typography,+} from "@mui/material";+import { useResolvedContactAvatar } from "ente-contacts";+import { getAvatarColor } from "ente-gallery/utils/avatar-colors";+import type { EnteFile } from "ente-media/file";+import { BaseTileButton, ItemCard } from "ente-new/photos/components/Tiles";+import { t } from "i18next";+import { Trans } from "react-i18next";+import { FeedActivityIcon } from "./FeedIcons";++interface Props {+ item: FeedItem;+ emailByUserID: Map<number, string>;+ anonNames: Record<string, string>;+ onOpen: (item: FeedItem, fileID?: number) => void;+ onOpenAlbum: (item: FeedItem) => void;+}++const useActor = (+ actor: FeedActor,+ emails: Map<number, string>,+ anonNames: Record<string, string>,+) => {+ const anonymous = !!actor.anonUserID || actor.userID <= 0;+ const resolved = useResolvedContactAvatar(+ anonymous+ ? {}+ : { userID: actor.userID, email: emails.get(actor.userID) },+ );+ const name = anonymous+ ? (actor.anonUserID && anonNames[actor.anonUserID]) || t("anonymous")+ : resolved.primaryLabel || t("someone");+ return { name, avatarURL: anonymous ? undefined : resolved.avatarURL };+};++export const FeedItemRow = ({+ item,+ emailByUserID,+ anonNames,+ onOpen,+ onOpenAlbum,+}: Props) => {+ const primary = useActor(item.actors[0]!, emailByUserID, anonNames);+ const shared =+ item.type === "sharedPhoto" || item.type === "sharedCollection";+ const others = item.actors.length - 1;+ const action = feedActionKey(item);+ return (+ <Stack+ component="li"+ data-feed-type={item.type}+ sx={{ listStyle: "none", gap: "12px" }}+ >+ <Stack+ direction="row"+ sx={{ alignItems: "flex-start", gap: "12px", minHeight: 73 }}+ >+ <ButtonBase+ onClick={() => (shared ? onOpenAlbum(item) : onOpen(item))}+ sx={{+ flex: 1,+ minWidth: 0,+ display: "block",+ textAlign: "start",+ borderRadius: 1,+ "&.Mui-focusVisible": {+ outline: "2px solid",+ outlineColor: "accent.main",+ outlineOffset: 4,+ },+ }}+ >+ <Stack+ direction="row"+ sx={{ alignItems: "center", gap: "10px", mb: "4px" }}+ >+ <FeedActivityIcon type={item.type} />+ <Stack direction="row">+ {item.actors.slice(0, 2).map((actor, index) => (+ <FeedActorAvatar+ key={feedActorKey(actor)}+ {...{+ actor,+ emailByUserID,+ anonNames,+ index,+ }}+ />+ ))}+ </Stack>+ </Stack>+ <Stack sx={{ pl: "42px", gap: "4px" }}>+ <Stack+ direction="row"+ sx={{+ alignItems: "baseline",+ gap: "4px",+ minWidth: 0,+ }}+ >+ <Typography+ component="span"+ noWrap+ sx={{+ fontSize: 14,+ lineHeight: "18px",+ fontWeight: 600,+ }}+ >+ {primary.name}+ </Typography>+ {others > 0 && (+ <Typography+ component="span"+ sx={{+ flexShrink: 0,+ fontSize: 14,+ lineHeight: "18px",+ color: "text.muted",+ }}+ >+ {t("feed_and_others", { count: others })}+ </Typography>+ )}+ </Stack>+ <Typography+ component="span"+ sx={{+ fontSize: 12,+ fontWeight: 500,+ lineHeight: "18px",+ color: "text.muted",+ overflowWrap: "anywhere",+ }}+ >+ <Trans+ i18nKey={action}+ values={{+ album: item.collectionName,+ count: item.files.length,+ }}+ count={item.files.length}+ components={{ strong: <strong /> }}+ />+ </Typography>+ </Stack>+ </ButtonBase>+ {!shared && item.files[0] && (+ <Box sx={{ width: 66, height: 66, flexShrink: 0 }}>+ <FeedThumbnail+ file={item.files[0]}+ onClick={() => onOpen(item)}+ />+ </Box>+ )}+ </Stack>+ {shared && item.files.length > 0 && (+ <Box+ sx={{ ml: "42px", width: "min(300px, calc(100% - 42px))" }}+ >+ <SharedPhotosGrid+ item={item}+ onOpen={onOpen}+ onOpenAlbum={onOpenAlbum}+ />+ </Box>+ )}+ </Stack>+ );+};++const FeedActorAvatar = ({+ actor,+ emailByUserID,+ anonNames,+ index,+}: {+ actor: FeedActor;+ emailByUserID: Map<number, string>;+ anonNames: Record<string, string>;+ index: number;+}) => {+ const { name, avatarURL } = useActor(actor, emailByUserID, anonNames);+ return (+ <Avatar+ alt=""+ src={avatarURL}+ sx={{+ width: 28,+ height: 28,+ fontSize: 12,+ bgcolor: getAvatarColor(name),+ color: "#fff",+ border: "1.167px solid",+ borderColor: "background.default",+ ml: index ? "-7px" : 0,+ zIndex: 2 - index,+ }}+ >+ {name[0]?.toLocaleUpperCase()}+ </Avatar>+ );+};++const ThumbnailTile = styled(BaseTileButton)({+ width: "100%",+ height: "100%",+ borderRadius: 8,+});+const FeedThumbnail = ({+ file,+ onClick,+}: {+ file: EnteFile;+ onClick: () => void;+}) => (+ <ItemCard coverFile={file} TileComponent={ThumbnailTile} onClick={onClick}>+ <Box+ component="span"+ sx={{+ position: "absolute",+ width: 1,+ height: 1,+ overflow: "hidden",+ clipPath: "inset(50%)",+ }}+ >+ {t("feed_open_file", { title: file.metadata.title })}+ </Box>+ </ItemCard>+);++const SharedPhotosGrid = ({+ item,+ onOpen,+ onOpenAlbum,+}: Pick<Props, "item" | "onOpen" | "onOpenAlbum">) => {+ const files = item.files.slice(0, 4);+ return (+ <Box+ sx={{+ display: "grid",+ gridTemplateColumns: files.length < 3 ? "1fr" : "1fr 1fr",+ gridTemplateRows: files.length === 1 ? "1fr" : "1fr 1fr",+ gap: "2px",+ aspectRatio: "1",+ borderRadius: "12px",+ overflow: "hidden",+ }}+ >+ {files.map((file, index) => (+ <Box+ key={file.id}+ sx={{+ position: "relative",+ minHeight: 0,+ gridColumn:+ files.length === 3 && index === 2+ ? "1 / -1"+ : undefined,+ "& > button": { borderRadius: 0 },+ }}+ >+ <FeedThumbnail+ file={file}+ onClick={() => onOpen(item, file.id)}+ />+ {index === 3 && item.files.length > 4 && (+ <ButtonBase+ onClick={() => onOpenAlbum(item)}+ aria-label={t("feed_open_album", {+ album: item.collectionName,+ })}+ sx={{+ position: "absolute",+ right: 6,+ bottom: 6,+ px: 1,+ py: "4px",+ borderRadius: 10,+ color: "#fff",+ bgcolor: "rgba(0,0,0,0.6)",+ fontSize: 13,+ fontWeight: 600,+ }}+ >+ +{item.files.length - 4}+ </ButtonBase>+ )}+ </Box>+ ))}+ </Box>+ );+};++const feedActionKey = (item: FeedItem) => {+ const own = item.isOwnedByCurrentUser ? "your" : "a";+ const media = item.isVideo ? "video" : "photo";+ const prefix = item.isOwnedByCurrentUser ? "feed_" : "";+ switch (item.type) {+ case "photoLike":+ return `${prefix}liked_${own}_${media}`;+ case "comment":+ return `${prefix}commented_on_${own}_${media}`;+ case "reply":+ return `${prefix}replied_to_${own}_comment`;+ case "commentLike":+ return `${prefix}liked_${own}_comment`;+ case "replyLike":+ return `feed_liked_${own}_reply`;+ case "sharedPhoto":+ return "feed_added_memories";+ case "sharedCollection":+ return "feed_shared_album";+ }+};diff --git a/web/apps/photos/src/components/gallery/sections/feed/FeedSection.tsx b/web/apps/photos/src/components/gallery/sections/feed/FeedSection.tsxnew file mode 100644index 0000000000..455b5662f0--- /dev/null+++ b/web/apps/photos/src/components/gallery/sections/feed/FeedSection.tsx@@ -0,0 +1,335 @@+import type { FeedItem } from "@/services/feed";+import { downloadAndSaveFiles } from "@/services/save";+import { ReloadIcon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import {+ Alert,+ Box,+ Button,+ CircularProgress,+ IconButton,+ Stack,+ Tooltip,+ Typography,+} from "@mui/material";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import { v2SubmitButtonSx } from "ente-base/components/SingleInput.styles";+import { FileViewer } from "ente-gallery/components/viewer/FileViewer";+import type { EnteFile } from "ente-media/file";+import { fileFileName } from "ente-media/file-metadata";+import { usePhotosAppContext } from "ente-new/photos/types/context";+import { t } from "i18next";+import { useEffect, useRef, useState } from "react";+import { GallerySectionLayout } from "../../navigation/GallerySectionLayout";+import { usePhotosNavigation } from "../../navigation/PhotosNavigationContext";+import type { GallerySectionProps } from "../types";+import { FeedItemRow } from "./FeedItemRow";+import { useFeed } from "./use-feed";++interface ViewerTarget {+ item: FeedItem;+ files: EnteFile[];+ initialIndex: number;+ comments: boolean;+}++export const FeedSection = ({+ library,+ operations,+ presentation,+}: GallerySectionProps) => {+ const feed = useFeed(library, operations.onRemotePull);+ const actions = usePhotosNavigation();+ const { setIsFileViewerOpen } = usePhotosAppContext();+ const [viewer, setViewer] = useState<ViewerTarget>();+ const scrollRef = useRef<HTMLDivElement>(null);+ const moreRef = useRef<HTMLDivElement>(null);+ const { hasMore, loadMore, refresh } = feed;+ useEffect(() => {+ const target = moreRef.current;+ if (!target || !hasMore) return;+ const observer = new IntersectionObserver(+ ([entry]) => {+ if (entry?.isIntersecting) loadMore();+ },+ { root: scrollRef.current, rootMargin: "200px" },+ );+ observer.observe(target);+ return () => observer.disconnect();+ }, [hasMore, loadMore, feed.items.length]);+ useEffect(() => () => setIsFileViewerOpen?.(false), [setIsFileViewerOpen]);++ const openAlbum = (item: FeedItem) =>+ actions.selectCollection(item.collectionID);+ const openItem = (item: FeedItem, fileID?: number) => {+ if (item.type === "sharedCollection" && fileID === undefined) {+ openAlbum(item);+ return;+ }+ if (!item.files.length) return;+ setViewer({+ item,+ files: item.files,+ initialIndex: Math.max(+ 0,+ item.files.findIndex((file) => file.id === fileID),+ ),+ comments: ["comment", "reply", "commentLike", "replyLike"].includes(+ item.type,+ ),+ });+ setIsFileViewerOpen?.(true);+ };+ const closeViewer = () => {+ setViewer(undefined);+ setIsFileViewerOpen?.(false);+ feed.refreshSocial();+ };++ return (+ <GallerySectionLayout presentation={presentation} fullBleed>+ <Box+ ref={scrollRef}+ sx={{+ flex: 1,+ minHeight: 0,+ display: "flex",+ flexDirection: "column",+ overflowY: "auto",+ px: { xs: 2, sm: 4.5 },+ py: { xs: 2, md: 4.5 },+ }}+ >+ <Stack+ sx={{+ flex: "1 0 auto",+ width: "100%",+ maxWidth: 600,+ mx: "auto",+ gap: 3,+ }}+ >+ <Stack+ direction="row"+ sx={{+ alignItems: "center",+ justifyContent: "space-between",+ height: 54,+ flexShrink: 0,+ }}+ >+ <Typography+ component="h1"+ sx={{+ fontFamily: '"Outfit Variable", sans-serif',+ fontSize: 24,+ lineHeight: "32px",+ fontWeight: 600,+ }}+ >+ {t("feed")}+ </Typography>+ <Tooltip title={t("refresh")}>+ <span>+ <IconButton+ aria-label={t("refresh")}+ onClick={refresh}+ disabled={feed.refreshing}+ size="small"+ >+ {feed.refreshing ? (+ <CircularProgress+ size={18}+ color="inherit"+ />+ ) : (+ <HugeiconsIcon+ icon={ReloadIcon}+ size={18}+ strokeWidth={1.8}+ />+ )}+ </IconButton>+ </span>+ </Tooltip>+ </Stack>+ {feed.failed && (+ <Alert+ severity="warning"+ action={+ <Button+ color="inherit"+ size="small"+ onClick={refresh}+ >+ {t("retry")}+ </Button>+ }+ >+ {t("feed_refresh_failed")}+ </Alert>+ )}+ {feed.items.length === 0 ? (+ feed.refreshing ? (+ <Stack+ role="status"+ sx={{ alignItems: "center", py: 8, gap: 2 }}+ >+ <CircularProgress size={24} />+ <Typography color="text.muted">+ {t("loading")}+ </Typography>+ </Stack>+ ) : (+ <Stack+ sx={{+ flex: 1,+ alignItems: "center",+ justifyContent: "center",+ textAlign: "center",+ px: 2,+ py: { xs: 6, sm: 8 },+ gap: 3,+ }}+ >+ <Box+ component="img"+ src="/images/feed/empty.png"+ alt=""+ draggable={false}+ sx={{+ width: 240,+ height: "auto",+ maxWidth: "100%",+ }}+ />+ <Stack+ sx={{+ alignItems: "center",+ gap: 1.5,+ maxWidth: 340,+ }}+ >+ <Typography+ component="h2"+ variant="h3"+ sx={{+ fontFamily:+ '"Outfit Variable", sans-serif',+ fontSize: { xs: 28, sm: 32 },+ lineHeight: 1.25,+ color: "text.base",+ }}+ >+ {t("feed_empty_title")}+ </Typography>+ <Typography+ sx={{+ color: "text.muted",+ lineHeight: 1.5,+ }}+ >+ {t("feed_empty_description")}+ </Typography>+ </Stack>+ <FocusVisibleButton+ color="accent"+ sx={[+ v2SubmitButtonSx,+ {+ flex: "none",+ width: 240,+ maxWidth: "100%",+ },+ ]}+ onClick={() =>+ actions.showAlbumOverview("ente")+ }+ >+ {t("share_album")}+ </FocusVisibleButton>+ </Stack>+ )+ ) : (+ <Stack+ component="ul"+ aria-label={t("feed")}+ sx={{ m: 0, p: 0, gap: "24px" }}+ >+ {feed.items.map((item) => (+ <FeedItemRow+ key={item.id}+ item={item}+ emailByUserID={library.emailByUserID}+ anonNames={+ feed.socialByCollection[+ item.collectionID+ ]?.anonNames ?? {}+ }+ onOpen={openItem}+ onOpenAlbum={openAlbum}+ />+ ))}+ </Stack>+ )}+ {feed.hasMore && (+ <Box ref={moreRef} sx={{ textAlign: "center", py: 2 }}>+ <Button onClick={loadMore}>{t("load_more")}</Button>+ </Box>+ )}+ </Stack>+ </Box>+ {viewer && (+ <FileViewer+ open+ onClose={closeViewer}+ files={viewer.files}+ initialIndex={viewer.initialIndex}+ user={library.user}+ activeCollectionID={viewer.item.collectionID}+ initialSidebar={viewer.comments ? "comments" : undefined}+ highlightCommentID={+ viewer.comments ? viewer.item.commentID : undefined+ }+ enableComment+ isCommentsFeatureEnabled+ hasSocialActivity={+ viewer.item.type !== "sharedCollection" &&+ viewer.item.type !== "sharedPhoto"+ }+ isInIncomingSharedCollection={+ library.collections.find(+ (c) => c.id === viewer.item.collectionID,+ )?.owner.id !== library.user!.id+ }+ collectionSummaries={library.normalCollectionSummaries}+ collectionNameByID={library.collectionNameByID}+ fileNormalCollectionIDs={library.fileNormalCollectionIDs}+ fileCollectionIDs={library.fileNormalCollectionIDs}+ hiddenCollectionIDs={library.hiddenCollectionIDs}+ favoriteFileIDs={library.favoriteFileIDs}+ pendingFavoriteUpdates={library.pendingFavoriteUpdates}+ onToggleFavorite={operations.onToggleFavorite}+ onTriggerRemotePull={() =>+ void operations.onRemotePull({+ source: "feed-viewer-action",+ })+ }+ onDownload={(file) =>+ downloadAndSaveFiles(+ [file],+ fileFileName(file),+ operations.onAddSaveGroup,+ )+ }+ onSendLink={operations.onSendLink}+ onAddFileToCollection={operations.onAddFileToCollection}+ onRemoteFilesPull={operations.onRemoteFilesPull}+ onVisualFeedback={operations.onVisualFeedback}+ onSelectCollection={actions.selectCollectionFromViewer}+ onSelectPerson={actions.selectPerson}+ />+ )}+ </GallerySectionLayout>+ );+};diff --git a/web/apps/photos/src/components/gallery/sections/feed/use-feed.ts b/web/apps/photos/src/components/gallery/sections/feed/use-feed.tsnew file mode 100644index 0000000000..ffaded0479--- /dev/null+++ b/web/apps/photos/src/components/gallery/sections/feed/use-feed.ts@@ -0,0 +1,130 @@+import { buildFeedItems, type FeedSocialData } from "@/services/feed";+import { fetchFeedData } from "@/services/feed-fetch";+import log from "ente-base/log";+import {+ useCallback,+ useEffect,+ useEffectEvent,+ useMemo,+ useState,+} from "react";+import type { GallerySectionProps } from "../types";++export const useFeed = (+ library: GallerySectionProps["library"],+ onRemotePull: GallerySectionProps["operations"]["onRemotePull"],+) => {+ const userID = library.user!.id;+ const [socialByCollection, setSocialByCollection] = useState<+ Record<number, FeedSocialData>+ >({});+ const [refreshing, setRefreshing] = useState(true);+ const [syncingLibrary, setSyncingLibrary] = useState(false);+ const [libraryFailed, setLibraryFailed] = useState(false);+ const [failed, setFailed] = useState(false);+ const [revision, setRevision] = useState(0);+ const [limit, setLimit] = useState(50);+ useEffect(() => {+ setLibraryFailed(false);+ }, [library.remotePullRevision]);+ const collections = useMemo(+ () =>+ library.collections.filter(+ (c) => !library.hiddenCollectionIDs.has(c.id),+ ),+ [library.collections, library.hiddenCollectionIDs],+ );++ const collectionIDs = collections+ .map((collection) => collection.id)+ .sort((a, b) => a - b)+ .join(",");+ const fetchSocialData = useEffectEvent((signal: AbortSignal) =>+ fetchFeedData(collections, signal),+ );++ useEffect(() => {+ if (syncingLibrary) return;+ const controller = new AbortController();+ const { signal } = controller;+ void (async () => {+ setRefreshing(true);+ setFailed(false);+ try {+ const result = await fetchSocialData(signal);+ signal.throwIfAborted();+ setSocialByCollection(result.socialByCollection);+ setFailed(result.failed);+ } catch (error) {+ if (signal.aborted) return;+ log.warn("Could not load Feed", error);+ setFailed(true);+ } finally {+ if (!signal.aborted) setRefreshing(false);+ }+ })();+ return () => controller.abort();+ }, [userID, collectionIDs, revision, syncingLibrary]);++ const items = useMemo(+ () =>+ buildFeedItems({+ userID,+ collections,+ files: library.collectionFiles,+ socialByCollection,+ hiddenCollectionIDs: library.hiddenCollectionIDs,+ excludedFileIDs: new Set([+ ...library.hiddenFileIDs,+ ...library.tempHiddenFileIDs,+ ...library.tempDeletedFileIDs,+ ]),+ }),+ [+ userID,+ collections,+ library.collectionFiles,+ library.hiddenCollectionIDs,+ library.hiddenFileIDs,+ library.tempHiddenFileIDs,+ library.tempDeletedFileIDs,+ socialByCollection,+ ],+ );++ const refresh = useCallback(async () => {+ setSyncingLibrary(true);+ setLibraryFailed(false);+ try {+ await onRemotePull({+ silent: true,+ strict: true,+ source: "feed-refresh",+ });+ } catch (error) {+ log.warn("Could not refresh Feed library", error);+ setLibraryFailed(true);+ } finally {+ setRevision((value) => value + 1);+ setSyncingLibrary(false);+ }+ }, [onRemotePull]);+ const refreshSocial = useCallback(+ () => setRevision((value) => value + 1),+ [],+ );+ const loadMore = useCallback(+ () => setLimit((value) => Math.min(500, value + 50)),+ [],+ );+ return {+ items: items.slice(0, limit),+ hasMore: items.length > limit,+ loadMore,+ socialByCollection,+ refreshing: refreshing || syncingLibrary,+ failed: failed || libraryFailed,+ refresh,+ refreshSocial,+ };+};diff --git a/web/apps/photos/src/components/gallery/sections/registry.tsx b/web/apps/photos/src/components/gallery/sections/registry.tsxindex 47ab12988f..b206605f46 100644--- a/web/apps/photos/src/components/gallery/sections/registry.tsx+++ b/web/apps/photos/src/components/gallery/sections/registry.tsx@@ -1,5 +1,6 @@import {DashboardSquare01Icon,+ FavouriteIcon,Link04Icon,Location01Icon,User02Icon,@@ -20,6 +21,7 @@ import { resolveAlbumDestination } from "./albums/album-files";import { AlbumsSection } from "./albums/AlbumsSection";import { DuplicatesView } from "./cleanup/DuplicatesView";import { LargeFilesView } from "./cleanup/LargeFilesView";+import { FeedSection } from "./feed/FeedSection";import { resolveLinksDestination } from "./links/link-selection";import { LinksSection } from "./links/LinksSection";import { resolvePeopleDestination } from "./people/people-files";@@ -129,6 +131,16 @@ const largeFilesView: GallerySectionDefinition["View"] = ({<LargeFilesView onRemoteFilesPull={operations.onRemoteFilesPull} /></GallerySectionLayout>);+const feedSelected: NonNullable<+ NonNullable<GallerySectionDefinition["rail"]>["selected"]+> = (navigation) =>+ !navigation.overlay && navigation.destination.section === "feed";+const feedSelection: NonNullable<+ NonNullable<GallerySectionDefinition["rail"]>["select"]+> = ({ open, closeDrawer }) => {+ closeDrawer();+ open();+};export const gallerySections = {albums: {View: AlbumsSection,@@ -141,6 +153,16 @@ export const gallerySections = {select: albumsSelection,},},+ feed: {+ View: FeedSection,+ hasNavigation: false,+ rail: {+ label: () => t("feed"),+ icon: FavouriteIcon,+ selected: feedSelected,+ select: feedSelection,+ },+ },people: {View: PeopleSection,resolve: resolvePeopleDestination,diff --git a/web/apps/photos/src/components/gallery/sections/types.ts b/web/apps/photos/src/components/gallery/sections/types.tsindex 19731a5034..4c8560b417 100644--- a/web/apps/photos/src/components/gallery/sections/types.ts+++ b/web/apps/photos/src/components/gallery/sections/types.ts@@ -51,6 +51,7 @@ export interface GallerySectionProps {library: Readonly<GalleryState> & {isFirstLoad: boolean;searchIndexRevision: number;+ remotePullRevision: number;};operations: GallerySectionOperations;navigation: GalleryNavigationState & {diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsxindex 16a1f7ea7d..e186c9fd54 100644--- a/web/apps/photos/src/pages/gallery.tsx+++ b/web/apps/photos/src/pages/gallery.tsx@@ -19,7 +19,8 @@ import { useMemo } from "react";const Page: React.FC = () => {const libraryOwner = useGalleryLibrary();- const { state, isFirstLoad, searchIndexRevision } = libraryOwner;+ const { state, isFirstLoad, searchIndexRevision, remotePullRevision } =+ libraryOwner;const { authenticateUser, authenticateUserDialogProps } =useGalleryAuthentication();const navigation = useGalleryNavigation(libraryOwner, authenticateUser);@@ -39,8 +40,13 @@ const Page: React.FC = () => {navigation.showSettings,);const library = useMemo(- () => ({ ...state, isFirstLoad, searchIndexRevision }),- [state, isFirstLoad, searchIndexRevision],+ () => ({+ ...state,+ isFirstLoad,+ searchIndexRevision,+ remotePullRevision,+ }),+ [state, isFirstLoad, searchIndexRevision, remotePullRevision],);const { View } = sectionDefinition(navigation.sectionID);if (!state.user) return <div />;diff --git a/web/apps/photos/src/services/feed-fetch.ts b/web/apps/photos/src/services/feed-fetch.tsnew file mode 100644index 0000000000..7524e72d4e--- /dev/null+++ b/web/apps/photos/src/services/feed-fetch.ts@@ -0,0 +1,87 @@+import log from "ente-base/log";+import type { Collection } from "ente-media/collection";+import {+ getAnonProfiles,+ getSocialUpdates,+ getUnifiedSocialDiff,+} from "ente-new/photos/services/social";+import { emptyFeedSocialData, type FeedSocialData } from "./feed";++export const fetchFeedData = async (+ albums: readonly Collection[],+ signal: AbortSignal,+): Promise<{+ socialByCollection: Record<number, FeedSocialData>;+ failed: boolean;+}> => {+ const updates = await getSocialUpdates(signal);+ const albumsByID = new Map(albums.map((album) => [album.id, album]));+ const socialByCollection: Record<number, FeedSocialData> = {};+ let failed = false;+ const pending = updates.filter((update) =>+ albumsByID.has(update.collectionID),+ );+ let index = 0;+ const worker = async () => {+ while (index < pending.length) {+ signal.throwIfAborted();+ const update = pending[index++]!;+ const album = albumsByID.get(update.collectionID)!;+ const data = emptyFeedSocialData();+ try {+ if (+ (update.commentsUpdatedAt ?? 0) > 0 ||+ (update.reactionsUpdatedAt ?? 0) > 0+ ) {+ let commentsSinceTime = 0;+ let reactionsSinceTime = 0;+ while (true) {+ signal.throwIfAborted();+ const diff = await getUnifiedSocialDiff(+ album.id,+ album.key,+ { commentsSinceTime, reactionsSinceTime, signal },+ );+ data.comments.push(...diff.comments);+ data.reactions.push(...diff.reactions);+ if (!diff.hasMoreComments && !diff.hasMoreReactions)+ break;+ if (+ (diff.hasMoreComments &&+ diff.commentsUpdatedAt <= commentsSinceTime) ||+ (diff.hasMoreReactions &&+ diff.reactionsUpdatedAt <= reactionsSinceTime)+ ) {+ throw new Error(+ "Social pagination cursor did not advance",+ );+ }+ commentsSinceTime = diff.commentsUpdatedAt;+ reactionsSinceTime = diff.reactionsUpdatedAt;+ }+ }+ if ((update.anonProfilesUpdatedAt ?? 0) > 0) {+ try {+ data.anonNames = Object.fromEntries(+ await getAnonProfiles(album.id, album.key, signal),+ );+ } catch (error) {+ signal.throwIfAborted();+ failed = true;+ log.warn("Could not refresh anonymous names", error);+ }+ }+ socialByCollection[album.id] = data;+ } catch (error) {+ signal.throwIfAborted();+ failed = true;+ log.warn("Could not refresh album activity", error);+ }+ }+ };+ await Promise.all(+ Array.from({ length: Math.min(3, pending.length) }, worker),+ );+ signal.throwIfAborted();+ return { socialByCollection, failed };+};diff --git a/web/apps/photos/src/services/feed.ts b/web/apps/photos/src/services/feed.tsnew file mode 100644index 0000000000..95209ab510--- /dev/null+++ b/web/apps/photos/src/services/feed.ts@@ -0,0 +1,258 @@+import type { Collection } from "ente-media/collection";+import type { EnteFile } from "ente-media/file";+import { FileType } from "ente-media/file-type";+import type { Comment } from "ente-new/photos/services/comment";+import type { UnifiedReaction } from "ente-new/photos/services/social";++export type FeedItemType =+ | "photoLike"+ | "comment"+ | "reply"+ | "commentLike"+ | "replyLike"+ | "sharedPhoto"+ | "sharedCollection";++export interface FeedActor {+ userID: number;+ anonUserID?: string;+}++export interface FeedItem {+ id: string;+ type: FeedItemType;+ collectionID: number;+ collectionName: string;+ fileID?: number;+ commentID?: string;+ actors: FeedActor[];+ createdAt: number;+ isOwnedByCurrentUser: boolean;+ isVideo: boolean;+ files: EnteFile[];+}++export interface FeedSocialData {+ comments: Comment[];+ reactions: UnifiedReaction[];+ anonNames: Record<string, string>;+}++export const emptyFeedSocialData = (): FeedSocialData => ({+ comments: [],+ reactions: [],+ anonNames: {},+});++export const feedActorKey = (actor: FeedActor) =>+ actor.anonUserID ? `anonymous:${actor.anonUserID}` : `user:${actor.userID}`;++const additionSessionGap = 10 * 60 * 1_000_000;++export const buildFeedItems = ({+ userID,+ collections,+ files,+ socialByCollection,+ hiddenCollectionIDs,+ excludedFileIDs,+}: {+ userID: number;+ collections: readonly Collection[];+ files: readonly EnteFile[];+ socialByCollection: Readonly<Record<number, FeedSocialData>>;+ hiddenCollectionIDs: ReadonlySet<number>;+ excludedFileIDs: ReadonlySet<number>;+}): FeedItem[] => {+ const albums = new Map(+ collections+ .filter((c) => !hiddenCollectionIDs.has(c.id))+ .map((c) => [c.id, c]),+ );+ const visibleFiles = files.filter(+ (f) => albums.has(f.collectionID) && !excludedFileIDs.has(f.id),+ );+ const fileByKey = new Map(+ visibleFiles.map((f) => [`${f.collectionID}:${f.id}`, f]),+ );+ const items = new Map<string, FeedItem>();++ for (const album of albums.values()) {+ const social = socialByCollection[album.id];+ if (!social) continue;+ const comments = new Map(social.comments.map((c) => [c.id, c]));+ const add = (+ type: FeedItemType,+ group: string | number,+ actor: FeedActor,+ createdAt: number,+ fileID: number | undefined,+ commentID: string | undefined,+ owned: boolean,+ ) => {+ if (actor.userID === userID) return;+ const file = fileByKey.get(`${album.id}:${fileID}`);+ if (!file) return;+ const id = `${type}:${album.id}:${group}`;+ const existing = items.get(id);+ if (existing) {+ if (+ !existing.actors.some(+ (a) => feedActorKey(a) === feedActorKey(actor),+ )+ )+ existing.actors.push(actor);+ } else {+ items.set(id, {+ id,+ type,+ collectionID: album.id,+ collectionName: album.name,+ fileID: file.id,+ commentID,+ actors: [actor],+ createdAt,+ isOwnedByCurrentUser: owned,+ isVideo: file.metadata.fileType === FileType.video,+ files: [file],+ });+ }+ };+ for (const comment of [...comments.values()].sort(+ (a, b) => b.createdAt - a.createdAt,+ )) {+ if (comment.isDeleted) continue;+ const parent = comment.parentCommentID+ ? comments.get(comment.parentCommentID)+ : undefined;+ if (comment.parentCommentID) {+ add(+ "reply",+ comment.parentCommentID,+ comment,+ comment.createdAt,+ comment.fileID ?? parent?.fileID,+ comment.id,+ (parent?.userID ?? comment.parentCommentUserID) === userID,+ );+ } else if (comment.fileID !== undefined) {+ add(+ "comment",+ comment.fileID,+ comment,+ comment.createdAt,+ comment.fileID,+ comment.id,+ fileByKey.get(`${album.id}:${comment.fileID}`)?.ownerID ===+ userID,+ );+ }+ }+ for (const reaction of [...social.reactions].sort(+ (a, b) => b.createdAt - a.createdAt,+ )) {+ if (reaction.isDeleted) continue;+ if (reaction.commentID) {+ const comment = comments.get(reaction.commentID);+ if (!comment || comment.isDeleted) continue;+ add(+ comment.parentCommentID ? "replyLike" : "commentLike",+ comment.id,+ reaction,+ reaction.createdAt,+ comment.fileID,+ comment.id,+ comment.userID === userID,+ );+ } else if (reaction.fileID !== undefined) {+ add(+ "photoLike",+ reaction.fileID,+ reaction,+ reaction.createdAt,+ reaction.fileID,+ undefined,+ fileByKey.get(`${album.id}:${reaction.fileID}`)?.ownerID ===+ userID,+ );+ }+ }+ }++ const initialFiles = new Map<number, EnteFile[]>();+ const sessions = new Map<string, { item: FeedItem; oldestAt: number }>();+ const recentlyAdded = visibleFiles+ .filter((f) => {+ if (f.ownerID === userID || (f.collectionAddedAt ?? 0) <= 0)+ return false;+ const album = albums.get(f.collectionID)!;+ return (+ f.pubMagicMetadata?.data.uploaderName == null ||+ (album.owner.id !== userID &&+ !!album.sharedAt &&+ f.collectionAddedAt! <= album.sharedAt)+ );+ })+ .sort(+ (a, b) =>+ b.collectionAddedAt! - a.collectionAddedAt! || b.id - a.id,+ )+ .slice(0, 1000);+ for (const file of recentlyAdded) {+ const album = albums.get(file.collectionID)!;+ const addedAt = file.collectionAddedAt!;+ if (+ album.owner.id !== userID &&+ album.sharedAt &&+ addedAt <= album.sharedAt+ ) {+ const previews = initialFiles.get(album.id) ?? [];+ if (previews.length < 30) previews.push(file);+ initialFiles.set(album.id, previews);+ continue;+ }+ if (file.pubMagicMetadata?.data.uploaderName != null) continue;+ const group = `${album.id}:${file.ownerID}`;+ const session = sessions.get(group);+ if (session && session.oldestAt - addedAt <= additionSessionGap) {+ session.item.files.push(file);+ session.oldestAt = addedAt;+ } else {+ const item: FeedItem = {+ id: `sharedPhoto:${group}:${addedAt}`,+ type: "sharedPhoto",+ collectionID: album.id,+ collectionName: album.name,+ fileID: file.id,+ actors: [{ userID: file.ownerID }],+ createdAt: addedAt,+ isOwnedByCurrentUser: false,+ isVideo: false,+ files: [file],+ };+ items.set(item.id, item);+ sessions.set(group, { item, oldestAt: addedAt });+ }+ }+ for (const album of albums.values()) {+ if (album.owner.id === userID || !album.sharedAt || album.sharedAt <= 0)+ continue;+ const previews = initialFiles.get(album.id) ?? [];+ const id = `sharedCollection:${album.id}`;+ items.set(id, {+ id,+ type: "sharedCollection",+ collectionID: album.id,+ collectionName: album.name,+ actors: [{ userID: album.owner.id }],+ createdAt: album.sharedAt,+ fileID: previews[0]?.id,+ isOwnedByCurrentUser: false,+ isVideo: false,+ files: previews,+ });+ }+ return [...items.values()]+ .sort((a, b) => b.createdAt - a.createdAt || a.id.localeCompare(b.id))+ .slice(0, 500);+};diff --git a/web/apps/photos/tests/albums-section-summary.test.tsx b/web/apps/photos/tests/albums-section-summary.test.tsxindex 4337520c9b..f115bcbfea 100644--- a/web/apps/photos/tests/albums-section-summary.test.tsx+++ b/web/apps/photos/tests/albums-section-summary.test.tsx@@ -113,7 +113,12 @@ const openAlbum = (const headerSummary = (state: GalleryState, collectionID = 10) => {const props: GallerySectionProps = {- library: { ...state, isFirstLoad: false, searchIndexRevision: 0 },+ library: {+ ...state,+ isFirstLoad: false,+ searchIndexRevision: 0,+ remotePullRevision: 0,+ },operations: {dispatch: vi.fn(),peopleState: undefined,diff --git a/web/apps/photos/tests/feed-fetch.test.ts b/web/apps/photos/tests/feed-fetch.test.tsnew file mode 100644index 0000000000..02ca1bfa6b--- /dev/null+++ b/web/apps/photos/tests/feed-fetch.test.ts@@ -0,0 +1,185 @@+import type { Collection } from "ente-media/collection";+import type { Comment } from "ente-new/photos/services/comment";+import {+ getAnonProfiles,+ getSocialUpdates,+ getUnifiedSocialDiff,+} from "ente-new/photos/services/social";+import { beforeEach, expect, test, vi } from "vitest";+import { fetchFeedData } from "../src/services/feed-fetch";++vi.mock("ente-base/log", () => ({ default: { warn: vi.fn() } }));+vi.mock("ente-new/photos/services/social", () => ({+ getAnonProfiles: vi.fn(),+ getUnifiedSocialDiff: vi.fn(),+ getSocialUpdates: vi.fn(),+}));+const album = { id: 10, key: "album-key" } as Collection;+const record = (id: string, updatedAt: number, isDeleted = false): Comment => ({+ id,+ collectionID: 10,+ fileID: 1,+ userID: 2,+ createdAt: 1,+ updatedAt,+ text: id,+ isDeleted,+});+const diff = (+ overrides: Partial<Awaited<ReturnType<typeof getUnifiedSocialDiff>>> = {},+) => ({+ comments: [],+ reactions: [],+ hasMoreComments: false,+ hasMoreReactions: false,+ commentsUpdatedAt: 0,+ reactionsUpdatedAt: 0,+ ...overrides,+});+const fetchFeed = (signal = new AbortController().signal) =>+ fetchFeedData([album], signal);++beforeEach(() => vi.resetAllMocks());++test("fetches from zero on every refresh and paginates independent cursors", async () => {+ vi.mocked(getSocialUpdates).mockResolvedValue([+ {+ collectionID: 10,+ commentsUpdatedAt: 300,+ reactionsUpdatedAt: 60,+ anonProfilesUpdatedAt: 7,+ },+ ]);+ vi.mocked(getUnifiedSocialDiff)+ .mockResolvedValueOnce(+ diff({+ comments: [record("parent", 200, true), record("new", 210)],+ commentsUpdatedAt: 210,+ reactionsUpdatedAt: 60,+ hasMoreComments: true,+ }),+ )+ .mockResolvedValueOnce(+ diff({+ comments: [record("next", 300)],+ commentsUpdatedAt: 300,+ reactionsUpdatedAt: 60,+ }),+ );+ vi.mocked(getAnonProfiles).mockResolvedValue(new Map([["guest", "Sam"]]));+ const signal = new AbortController().signal;+ const result = await fetchFeed(signal);+ expect(result.failed).toBe(false);+ expect(result.socialByCollection[10]).toEqual({+ comments: [+ record("parent", 200, true),+ record("new", 210),+ record("next", 300),+ ],+ reactions: [],+ anonNames: { guest: "Sam" },+ });+ expect(getUnifiedSocialDiff).toHaveBeenNthCalledWith(1, 10, "album-key", {+ commentsSinceTime: 0,+ reactionsSinceTime: 0,+ signal,+ });+ expect(getUnifiedSocialDiff).toHaveBeenNthCalledWith(2, 10, "album-key", {+ commentsSinceTime: 210,+ reactionsSinceTime: 60,+ signal,+ });+ vi.mocked(getUnifiedSocialDiff).mockResolvedValue(diff());+ await fetchFeed(signal);+ expect(getUnifiedSocialDiff).toHaveBeenNthCalledWith(3, 10, "album-key", {+ commentsSinceTime: 0,+ reactionsSinceTime: 0,+ signal,+ });+});++test("discards an incomplete album when a later page fails", async () => {+ vi.mocked(getSocialUpdates).mockResolvedValue([+ { collectionID: 10, commentsUpdatedAt: 300 },+ ]);+ vi.mocked(getUnifiedSocialDiff)+ .mockResolvedValueOnce(+ diff({+ comments: [record("new", 200)],+ commentsUpdatedAt: 200,+ hasMoreComments: true,+ }),+ )+ .mockRejectedValueOnce(new Error("Offline"));+ const result = await fetchFeed();+ expect(result.failed).toBe(true);+ expect(result.socialByCollection).toEqual({});+});++test("only fetches accessible albums with activity", async () => {+ vi.mocked(getSocialUpdates).mockResolvedValue([+ { collectionID: 10, commentsUpdatedAt: 0 },+ { collectionID: 11, commentsUpdatedAt: 500 },+ ]);+ const result = await fetchFeed();+ expect(getUnifiedSocialDiff).not.toHaveBeenCalled();+ expect(Object.keys(result.socialByCollection)).toEqual(["10"]);+});++test("cancels an obsolete refresh", async () => {+ const controller = new AbortController();+ vi.mocked(getSocialUpdates).mockResolvedValue([+ { collectionID: 10, commentsUpdatedAt: 200 },+ ]);+ vi.mocked(getUnifiedSocialDiff).mockImplementationOnce(() => {+ controller.abort();+ return Promise.resolve(diff({ commentsUpdatedAt: 200 }));+ });+ await expect(fetchFeed(controller.signal)).rejects.toThrow();+});++test("stops pagination when a cursor does not advance", async () => {+ vi.mocked(getSocialUpdates).mockResolvedValue([+ { collectionID: 10, commentsUpdatedAt: 200 },+ ]);+ vi.mocked(getUnifiedSocialDiff).mockResolvedValue(+ diff({ hasMoreComments: true }),+ );+ const result = await fetchFeed();+ expect(result.failed).toBe(true);+ expect(result.socialByCollection).toEqual({});+ expect(getUnifiedSocialDiff).toHaveBeenCalledOnce();+});++test("preserves fetched activity when anonymous profiles fail", async () => {+ vi.mocked(getSocialUpdates).mockResolvedValue([+ {+ collectionID: 10,+ commentsUpdatedAt: 200,+ anonProfilesUpdatedAt: 100,+ },+ ]);+ vi.mocked(getUnifiedSocialDiff).mockResolvedValue(+ diff({ comments: [record("comment", 200)], commentsUpdatedAt: 200 }),+ );+ vi.mocked(getAnonProfiles).mockRejectedValue(new Error("Unavailable"));+ const result = await fetchFeed();+ expect(result.failed).toBe(true);+ expect(result.socialByCollection[10]).toEqual({+ comments: [record("comment", 200)],+ reactions: [],+ anonNames: {},+ });+});++test("still cancels when the anonymous-profile request is aborted", async () => {+ const controller = new AbortController();+ vi.mocked(getSocialUpdates).mockResolvedValue([+ { collectionID: 10, anonProfilesUpdatedAt: 100 },+ ]);+ vi.mocked(getAnonProfiles).mockImplementation(() => {+ controller.abort();+ return Promise.reject(new Error("Aborted"));+ });+ await expect(fetchFeed(controller.signal)).rejects.toThrow();+});diff --git a/web/apps/photos/tests/feed-social-api.test.ts b/web/apps/photos/tests/feed-social-api.test.tsnew file mode 100644index 0000000000..44333e6ea5--- /dev/null+++ b/web/apps/photos/tests/feed-social-api.test.ts@@ -0,0 +1,151 @@+import { decryptBoxBytes } from "ente-base/crypto";+import {+ getSocialUpdates,+ getUnifiedSocialDiff,+} from "ente-new/photos/services/social";+import { afterEach, beforeEach, expect, test, vi } from "vitest";++vi.mock("ente-base/crypto", () => ({ decryptBoxBytes: vi.fn() }));+vi.mock("ente-base/http", () => ({+ authenticatedRequestHeaders: () => Promise.resolve({}),+ ensureOk: (response: Response) => {+ if (!response.ok) throw new Error("Request failed");+ },+}));+vi.mock("ente-base/origins", () => ({+ apiURL: (path: string, params?: Record<string, number>) =>+ Promise.resolve(+ `https://api.ente.io${path}?${new URLSearchParams(Object.entries(params ?? {}).map(([key, value]) => [key, String(value)]))}`,+ ),+}));++const fetchMock = vi.fn<typeof fetch>();+const record = (id: string, updatedAt: number, isDeleted = false) => ({+ id,+ collectionID: 10,+ fileID: 1,+ userID: 2,+ isDeleted,+ createdAt: 1,+ updatedAt,+ cipher: isDeleted ? null : "cipher",+ nonce: isDeleted ? null : "nonce",+});+beforeEach(() => {+ vi.resetAllMocks();+ vi.stubGlobal("fetch", fetchMock);+});+afterEach(() => vi.unstubAllGlobals());++test("Feed and file viewer exclude deleted reactions while raw cursors advance", async () => {+ fetchMock.mockImplementation(() =>+ Promise.resolve(+ Response.json({+ comments: [],+ reactions: [record("deleted", 50, true), record("active", 40)],+ hasMoreComments: false,+ hasMoreReactions: false,+ }),+ ),+ );+ vi.mocked(decryptBoxBytes).mockResolvedValue(+ new TextEncoder().encode("<3\0\0"),+ );+ const signal = new AbortController().signal;+ const result = await getUnifiedSocialDiff(10, "key", {+ commentsSinceTime: 10,+ reactionsSinceTime: 20,+ signal,+ });+ expect(+ result.reactions.map(({ id, isDeleted, reactionType }) => ({+ id,+ isDeleted,+ reactionType,+ })),+ ).toEqual([{ id: "active", isDeleted: false, reactionType: "<3" }]);+ expect(result.commentsUpdatedAt).toBe(10);+ expect(result.reactionsUpdatedAt).toBe(50);+ expect(fetchMock).toHaveBeenCalledWith(+ "https://api.ente.io/social/diff?collectionID=10&commentsSinceTime=10&reactionsSinceTime=20&limit=1000",+ { headers: {}, signal },+ );+ const viewer = await getUnifiedSocialDiff(10, "key", { fileID: 1 });+ expect(viewer.reactions.map(({ id }) => id)).toEqual(["active"]);+ expect(fetchMock).toHaveBeenLastCalledWith(+ "https://api.ente.io/social/diff?collectionID=10&fileID=1&commentsSinceTime=0&reactionsSinceTime=0&limit=1000",+ { headers: {}, signal: undefined },+ );+ expect(decryptBoxBytes).toHaveBeenCalledTimes(2);+});++test("a corrupt record does not stall the pagination cursor", async () => {+ fetchMock.mockResolvedValue(+ Response.json({+ comments: [record("unreadable", 200)],+ reactions: [],+ hasMoreComments: true,+ hasMoreReactions: false,+ }),+ );+ vi.mocked(decryptBoxBytes).mockRejectedValue(+ new Error("Invalid ciphertext"),+ );+ const result = await getUnifiedSocialDiff(10, "key", {+ commentsSinceTime: 0,+ reactionsSinceTime: 50,+ });+ expect(result.comments).toEqual([]);+ expect(result.commentsUpdatedAt).toBe(200);+ expect(result.reactionsUpdatedAt).toBe(50);+ expect(result.hasMoreComments).toBe(true);+});++test("handles a new account with no social update records", async () => {+ fetchMock.mockResolvedValue(Response.json({ updates: null }));+ expect(await getSocialUpdates()).toEqual([]);+});++test("file viewer decrypts comments and replies and preserves deleted parent metadata", async () => {+ fetchMock.mockResolvedValue(+ Response.json({+ comments: [+ { ...record("parent", 100), cipher: "parent-cipher" },+ {+ ...record("reply", 200),+ cipher: "reply-cipher",+ parentCommentID: "parent",+ parentCommentUserID: 2,+ },+ { ...record("deleted-parent", 300, true), userID: 3 },+ ],+ reactions: [],+ hasMoreComments: false,+ hasMoreReactions: false,+ }),+ );+ vi.mocked(decryptBoxBytes).mockImplementation(({ encryptedData }) =>+ Promise.resolve(+ new TextEncoder().encode(+ encryptedData === "parent-cipher"+ ? "Original comment"+ : "Reply text",+ ),+ ),+ );+ const result = await getUnifiedSocialDiff(10, "key", { fileID: 1 });+ expect(result.comments).toMatchObject([+ { id: "parent", fileID: 1, text: "Original comment", isDeleted: false },+ {+ id: "reply",+ fileID: 1,+ text: "Reply text",+ isDeleted: false,+ parentCommentID: "parent",+ parentCommentUserID: 2,+ },+ { id: "deleted-parent", text: "", isDeleted: true, userID: 3 },+ ]);+ expect(result.commentsUpdatedAt).toBe(300);+ expect(decryptBoxBytes).toHaveBeenCalledTimes(2);+});diff --git a/web/apps/photos/tests/feed.test.ts b/web/apps/photos/tests/feed.test.tsnew file mode 100644index 0000000000..75cd7add67--- /dev/null+++ b/web/apps/photos/tests/feed.test.ts@@ -0,0 +1,301 @@+import type { Collection } from "ente-media/collection";+import type { EnteFile } from "ente-media/file";+import { FileType } from "ente-media/file-type";+import type { Comment } from "ente-new/photos/services/comment";+import type { UnifiedReaction } from "ente-new/photos/services/social";+import { describe, expect, test } from "vitest";+import { buildFeedItems, emptyFeedSocialData } from "../src/services/feed";++const album = (id = 10, ownerID = 1, sharedAt?: number): Collection =>+ ({+ id,+ owner: { id: ownerID },+ name: `Album ${id}`,+ sharedAt,+ }) as Collection;+const photo = (id = 1, overrides: Partial<EnteFile> = {}): EnteFile =>+ ({+ id,+ collectionID: 10,+ ownerID: 1,+ metadata: { fileType: FileType.image },+ ...overrides,+ }) as EnteFile;+const comment = (id: string, overrides: Partial<Comment> = {}): Comment => ({+ id,+ collectionID: 10,+ fileID: 1,+ userID: 2,+ text: "Hello",+ isDeleted: false,+ createdAt: 100,+ updatedAt: 100,+ ...overrides,+});+const reaction = (+ id: string,+ overrides: Partial<UnifiedReaction> = {},+): UnifiedReaction => ({ ...comment(id), reactionType: "<3", ...overrides });+const build = (options: Partial<Parameters<typeof buildFeedItems>[0]> = {}) =>+ buildFeedItems({+ userID: 1,+ collections: [album()],+ files: [photo()],+ socialByCollection: {},+ hiddenCollectionIDs: new Set(),+ excludedFileIDs: new Set(),+ ...options,+ });++describe("social Feed grouping", () => {+ test("keeps replies to deleted parents while suppressing the parent's own activity", () => {+ const items = build({+ socialByCollection: {+ 10: {+ ...emptyFeedSocialData(),+ comments: [+ comment("parent", { userID: 1, isDeleted: true }),+ comment("reply", { parentCommentID: "parent" }),+ ],+ reactions: [+ reaction("parent-like", { commentID: "parent" }),+ ],+ },+ },+ });+ expect(items).toHaveLength(1);+ expect(items[0]).toMatchObject({+ type: "reply",+ commentID: "reply",+ isOwnedByCurrentUser: true,+ });+ });+ test("groups newest first, deduplicates actors and excludes own/deleted activity", () => {+ const items = build({+ socialByCollection: {+ 10: {+ ...emptyFeedSocialData(),+ comments: [+ comment("old"),+ comment("new", { userID: 3, createdAt: 200 }),+ comment("repeat", { createdAt: 150 }),+ comment("mine", { userID: 1, createdAt: 400 }),+ comment("deleted", { isDeleted: true, createdAt: 500 }),+ ],+ reactions: [+ reaction("like", { createdAt: 300 }),+ reaction("unliked", {+ isDeleted: true,+ createdAt: 600,+ }),+ reaction("mine", { userID: 1, createdAt: 700 }),+ ],+ },+ },+ });+ expect(items.map((item) => item.type)).toEqual([+ "photoLike",+ "comment",+ ]);+ expect(items[1]).toMatchObject({+ createdAt: 200,+ commentID: "new",+ actors: [{ userID: 3 }, { userID: 2 }],+ isOwnedByCurrentUser: true,+ });+ });++ test("keeps anonymous identities distinct and scopes groups to album membership", () => {+ const social = {+ ...emptyFeedSocialData(),+ reactions: [+ reaction("a", { userID: 0, anonUserID: "a" }),+ reaction("b", { userID: 0, anonUserID: "b" }),+ reaction("repeat-a", { userID: 0, anonUserID: "a" }),+ ],+ };+ const items = build({+ collections: [album(), album(11), album(12)],+ files: [photo(), photo(1, { collectionID: 11 })],+ socialByCollection: { 10: social, 11: social, 12: social },+ });+ expect(items).toHaveLength(2);+ expect(items.map((item) => item.collectionID)).toEqual([10, 11]);+ expect(items[0]!.actors.map((actor) => actor.anonUserID)).toEqual([+ "a",+ "b",+ ]);+ });++ test("classifies replies and likes using the target comment owner and media", () => {+ const items = build({+ files: [+ photo(1, {+ metadata: {+ fileType: FileType.video,+ } as EnteFile["metadata"],+ }),+ ],+ socialByCollection: {+ 10: {+ ...emptyFeedSocialData(),+ comments: [+ comment("parent", { userID: 1 }),+ comment("reply", {+ parentCommentID: "parent",+ createdAt: 200,+ }),+ comment("other-parent", { userID: 3 }),+ ],+ reactions: [+ reaction("parent-like", { commentID: "parent" }),+ reaction("reply-like", { commentID: "reply" }),+ reaction("other-like", { commentID: "other-parent" }),+ ],+ },+ },+ });+ expect(items.find((item) => item.type === "reply")).toMatchObject({+ commentID: "reply",+ isOwnedByCurrentUser: true,+ isVideo: true,+ });+ expect(items.find((item) => item.type === "replyLike")).toMatchObject({+ commentID: "reply",+ isOwnedByCurrentUser: false,+ });+ expect(+ items+ .filter((item) => item.type === "commentLike")+ .map((item) => item.isOwnedByCurrentUser)+ .sort(),+ ).toEqual([false, true]);+ });++ test("never exposes hidden, temporarily removed or inaccessible files", () => {+ const social = {+ ...emptyFeedSocialData(),+ reactions: [reaction("like")],+ };+ expect(+ build({+ socialByCollection: { 10: social },+ hiddenCollectionIDs: new Set([10]),+ }),+ ).toEqual([]);+ expect(+ build({+ socialByCollection: { 10: social },+ excludedFileIDs: new Set([1]),+ }),+ ).toEqual([]);+ expect(+ build({+ socialByCollection: { 10: social },+ files: [photo(1, { collectionID: 11 })],+ }),+ ).toEqual([]);+ });+});++describe("sharing activity", () => {+ const minute = 60 * 1_000_000;+ const added = (id: number, minutes: number, ownerID = 2) =>+ photo(id, { ownerID, collectionAddedAt: minutes * minute });++ test("groups consecutive ten-minute additions by album and uploader", () => {+ const items = build({+ files: [+ added(1, 1),+ added(2, 10),+ added(3, 19),+ added(4, 30),+ added(5, 18, 3),+ ],+ });+ expect(items.map((item) => item.files.map((file) => file.id))).toEqual([+ [4],+ [3, 2, 1],+ [5],+ ]);+ });++ test("uses original album contents as previews, excludes public uploads and keeps old share events", () => {+ const files = [added(1, 1), added(2, 10), added(3, 11), added(4, 12)];+ files[3]!.pubMagicMetadata = {+ version: 1,+ count: 1,+ data: { uploaderName: "Guest" },+ };+ const items = build({+ collections: [album(10, 2, 10 * minute)],+ files,+ });+ expect(items.map((item) => item.type)).toEqual([+ "sharedPhoto",+ "sharedCollection",+ ]);+ expect(items[0]!.files.map((file) => file.id)).toEqual([3]);+ expect(items[1]!.files.map((file) => file.id)).toEqual([2, 1]);+ });++ test("caps previews at thirty and final items at five hundred", () => {+ const previews = build({+ collections: [album(10, 2, 100 * minute)],+ files: Array.from({ length: 40 }, (_, i) => added(i + 1, i + 1)),+ });+ expect(previews[0]!.files).toHaveLength(30);+ const files = Array.from({ length: 501 }, (_, i) => photo(i + 1));+ const items = build({+ files,+ socialByCollection: {+ 10: {+ ...emptyFeedSocialData(),+ reactions: files.map((file) =>+ reaction(String(file.id), {+ fileID: file.id,+ createdAt: file.id,+ }),+ ),+ },+ },+ });+ expect(items).toHaveLength(500);+ expect(items[0]!.fileID).toBe(501);+ expect(items[499]!.fileID).toBe(2);+ });+});++test("excludes public uploads before capping sharing activity", () => {+ const legitimate = photo(1, { ownerID: 2, collectionAddedAt: 1 });+ const publicUploads = Array.from({ length: 1001 }, (_, i) =>+ photo(i + 2, {+ ownerID: 2,+ collectionAddedAt: i + 2,+ pubMagicMetadata: {+ version: 1,+ count: 1,+ data: { uploaderName: "Guest" },+ },+ }),+ );+ const items = build({ files: [legitimate, ...publicUploads] });+ expect(items).toHaveLength(1);+ expect(items[0]!.files).toEqual([legitimate]);+});++test("preserves public uploads already present when an album was shared as previews", () => {+ const file = photo(1, {+ ownerID: 2,+ collectionAddedAt: 1,+ pubMagicMetadata: {+ version: 1,+ count: 1,+ data: { uploaderName: "Guest" },+ },+ });+ const items = build({ collections: [album(10, 2, 2)], files: [file] });+ expect(items).toHaveLength(1);+ expect(items[0]!.type).toBe("sharedCollection");+ expect(items[0]!.files).toEqual([file]);+});diff --git a/web/apps/photos/tests/gallery-sections.test.tsx b/web/apps/photos/tests/gallery-sections.test.tsxindex 98bf21c09c..c710710a0e 100644--- a/web/apps/photos/tests/gallery-sections.test.tsx+++ b/web/apps/photos/tests/gallery-sections.test.tsx@@ -27,6 +27,9 @@ vi.mock("../src/components/gallery/sections/places/PlacesSection", () => ({vi.mock("../src/components/gallery/sections/links/LinksSection", () => ({LinksSection: () => <div>Links</div>,}));+vi.mock("../src/components/gallery/sections/feed/FeedSection", () => ({+ FeedSection: () => <div>Feed</div>,+}));vi.mock("../src/components/gallery/sections/search/SearchSection", () => ({SearchSection: () => <div>Search</div>,}));@@ -77,6 +80,26 @@ const entry = () => ({togglePanel: vi.fn(),});describe("rail entry behavior", () => {+ test("Feed opens directly without a navigation panel on desktop and mobile", () => {+ for (const mobile of [false, true]) {+ const controls = { ...entry(), mobile };+ const definition = sectionDefinition("feed");+ selectRailSection(definition, "feed", controls);+ expect(controls.open).toHaveBeenCalledOnce();+ expect(controls.openPanel).not.toHaveBeenCalled();+ expect(controls.togglePanel).not.toHaveBeenCalled();+ expect(definition.hasNavigation).toBe(false);+ controls.navigation = navigationReducer(initialNavigationState, {+ type: "openSection",+ section: "feed",+ });+ expect(+ definition.rail?.selected?.(controls.navigation, false),+ ).toBe(true);+ selectRailSection(definition, "feed", controls);+ expect(controls.togglePanel).not.toHaveBeenCalled();+ }+ });test("ordinary sections open and repeated selection toggles their panel", () => {const controls = entry();selectRailSection(sectionDefinition("links"), "links", controls);diff --git a/web/apps/photos/tests/gallery-upload-target.test.tsx b/web/apps/photos/tests/gallery-upload-target.test.tsxindex 08f49aaace..778dcf4f3b 100644--- a/web/apps/photos/tests/gallery-upload-target.test.tsx+++ b/web/apps/photos/tests/gallery-upload-target.test.tsx@@ -63,6 +63,7 @@ const uploadTarget = (destination: GalleryDestination) => {{state: { ...initialGalleryState, collections: [collection] },searchIndexRevision: 0,+ remotePullRevision: 0,isFirstLoad: false,dispatch: vi.fn(),peopleState: undefined,diff --git a/web/packages/base/locales/en-US/translation.json b/web/packages/base/locales/en-US/translation.jsonindex 518e670e42..c2d5993c9e 100644--- a/web/packages/base/locales/en-US/translation.json+++ b/web/packages/base/locales/en-US/translation.json@@ -1206,5 +1206,27 @@"auto_lock_5_minutes": "5 minutes","auto_lock_30_minutes": "30 minutes","wrong_unlock_code_one": "You've entered the wrong unlock code {{count}} time.",- "wrong_unlock_code_other": "You've entered the wrong unlock code {{count}} times."+ "wrong_unlock_code_other": "You've entered the wrong unlock code {{count}} times.",+ "feed": "Feed",+ "feed_and_others_one": "and {{count}} other",+ "feed_and_others_other": "and {{count}} others",+ "feed_shared_album": "shared <strong>{{album}}</strong> with you",+ "feed_added_memories_one": "added a memory to <strong>{{album}}</strong>",+ "feed_added_memories_other": "added {{count}} memories to <strong>{{album}}</strong>",+ "feed_open_album": "Open {{album}}",+ "feed_open_file": "Open {{title}}",+ "feed_refresh_failed": "Could not refresh all activity. Please try again.",+ "feed_empty_title": "Share your memories",+ "feed_empty_description": "Loved ones can view, react and add comments, without an account.",+ "feed_liked_your_photo": "liked your photo",+ "feed_commented_on_your_photo": "commented on your photo",+ "feed_liked_your_video": "liked your video",+ "feed_commented_on_your_video": "commented on your video",+ "feed_liked_your_comment": "liked your comment",+ "feed_liked_your_reply": "liked your reply",+ "feed_replied_to_your_comment": "replied to your comment",+ "feed_liked_a_reply": "liked a reply",+ "someone": "Someone",+ "refresh": "Refresh",+ "load_more": "Load more"}diff --git a/web/packages/gallery/components/viewer/FileViewer.tsx b/web/packages/gallery/components/viewer/FileViewer.tsxindex 96340b4cd4..8c2b3cb224 100644--- a/web/packages/gallery/components/viewer/FileViewer.tsx+++ b/web/packages/gallery/components/viewer/FileViewer.tsx@@ -162,6 +162,7 @@ export type FileViewerProps = ModalVisibilityProps & {disableEscapeClose?: boolean;enableComment?: boolean;isCommentsFeatureEnabled?: boolean;+ hasSocialActivity?: boolean;} & Pick<FileInfoProps,"collectionNameByID" | "onSelectCollection" | "onSelectPerson"@@ -204,6 +205,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({shouldCloseOnBrowserBack: shouldCloseOnBrowserBackOverride,disableEscapeClose = false,enableComment = true,+ hasSocialActivity = false,isCommentsFeatureEnabled = true,}) => {const { onGenericError } = useBaseContext();@@ -1055,6 +1057,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({if (!haveUser) return false;if (!enableComment) return false;if (!isCommentsFeatureEnabled) return false;+ if (hasSocialActivity) return true;if (activeCollectionID &&activeCollectionID !== 0 &&@@ -1068,6 +1071,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({}, [haveUser,enableComment,+ hasSocialActivity,isCommentsFeatureEnabled,activeCollectionID,collectionSummaries,@@ -1496,8 +1500,8 @@ export const FileViewer: React.FC<FileViewerProps> = ({const { comments, reactions } =await getUnifiedSocialDiff(collectionId,- activeFileID,collection.key,+ { fileID: activeFileID },);commentsMap.set(collectionId, comments);@@ -1610,8 +1614,8 @@ export const FileViewer: React.FC<FileViewerProps> = ({try {const { comments, reactions } = await getUnifiedSocialDiff(collectionId,- activeFileID,cached.key,+ { fileID: activeFileID },);commentsMap.set(collectionId, comments);diff --git a/web/packages/gallery/services/files-db.ts b/web/packages/gallery/services/files-db.tsindex b32a688cdd..d1fbb2f2f3 100644--- a/web/packages/gallery/services/files-db.ts+++ b/web/packages/gallery/services/files-db.ts@@ -69,6 +69,7 @@ const LocalCollection = z.nullish().transform(nullishToEmpty),updationTime: z.number(),+ sharedAt: z.number().nullish().transform(nullToUndefined),magicMetadata: createMagicMetadataSchema(CollectionPrivateMagicMetadataData,),@@ -107,6 +108,7 @@ export const LocalEnteFile = z.looseObject({thumbnail: RemoteFileObjectAttributes,info: RemoteFileInfo.nullish().transform(nullToUndefined),updationTime: z.number(),+ collectionAddedAt: z.number().nullish().transform(nullToUndefined),metadata: FileMetadata,magicMetadata: createMagicMetadataSchema(FilePrivateMagicMetadataData),pubMagicMetadata: createMagicMetadataSchema(FilePublicMagicMetadataData),diff --git a/web/packages/media/collection.ts b/web/packages/media/collection.tsindex e158546f38..b689200875 100644--- a/web/packages/media/collection.ts+++ b/web/packages/media/collection.ts@@ -20,6 +20,7 @@ export interface Collection {sharees: CollectionUser[];publicURLs: PublicURL[];updationTime: number;+ sharedAt?: number;// Private to the owner; never visible to sharees.magicMetadata?: MagicMetadata<CollectionPrivateMagicMetadataData>;// Visible to everyone with whom the collection is shared.@@ -120,6 +121,7 @@ export const RemoteCollection = z.looseObject({sharees: z.array(RemoteCollectionUser).nullish().transform(nullishToEmpty),publicURLs: z.array(RemotePublicURL).nullish().transform(nullishToEmpty),updationTime: z.number(),+ sharedAt: z.number().nullish().transform(nullToUndefined),isDeleted: z.boolean().nullish().transform(nullToUndefined),magicMetadata: RemoteMagicMetadata.nullish().transform(nullToUndefined),pubMagicMetadata: RemoteMagicMetadata.nullish().transform(nullToUndefined),diff --git a/web/packages/media/file.ts b/web/packages/media/file.tsindex 894866743d..72e1590d7e 100644--- a/web/packages/media/file.ts+++ b/web/packages/media/file.ts@@ -27,6 +27,7 @@ export interface EnteFile {thumbnail: FileObjectAttributes;info?: FileInfo;updationTime: number;+ collectionAddedAt?: number;metadata: FileMetadata;// Private to the owner; never visible to sharees.magicMetadata?: MagicMetadata<FilePrivateMagicMetadataData>;@@ -73,6 +74,7 @@ export const RemoteEnteFile = z.looseObject({thumbnail: RemoteFileObjectAttributes,info: RemoteFileInfo.nullish().transform(nullToUndefined),updationTime: z.number(),+ collectionAddedAt: z.number().nullish().transform(nullToUndefined),isDeleted: z.boolean().nullish().transform(nullToUndefined),metadata: RemoteFileMetadata,magicMetadata: RemoteMagicMetadata.nullish().transform(nullToUndefined),diff --git a/web/packages/new/photos/services/social.ts b/web/packages/new/photos/services/social.tsindex a72fb094b9..26dbaf3c80 100644--- a/web/packages/new/photos/services/social.ts+++ b/web/packages/new/photos/services/social.ts@@ -31,20 +31,42 @@ export interface UnifiedSocialDiff {export const getUnifiedSocialDiff = async (collectionID: number,- fileID: number,collectionKey: string,-): Promise<UnifiedSocialDiff> => {+ {+ fileID,+ commentsSinceTime = 0,+ reactionsSinceTime = 0,+ signal,+ }: {+ fileID?: number;+ commentsSinceTime?: number;+ reactionsSinceTime?: number;+ signal?: AbortSignal;+ } = {},+) => {const res = await fetch(await apiURL("/social/diff", {collectionID,- fileID,- sinceTime: 0,+ ...(fileID === undefined ? {} : { fileID }),+ commentsSinceTime,+ reactionsSinceTime,limit: 1000,}),- { headers: await authenticatedRequestHeaders() },+ { headers: await authenticatedRequestHeaders(), signal },);ensureOk(res);- return decryptSocialDiff(collectionKey, await res.json());+ const data = UnifiedDiffResponse.parse(await res.json());+ return {+ ...(await decryptSocialDiff(collectionKey, data)),+ commentsUpdatedAt: Math.max(+ commentsSinceTime,+ ...data.comments.map((c) => c.updatedAt),+ ),+ reactionsUpdatedAt: Math.max(+ reactionsSinceTime,+ ...data.reactions.map((r) => r.updatedAt),+ ),+ };};const decryptSocialDiff = async (@@ -174,10 +196,11 @@ const UnifiedDiffResponse = z.object({export const getAnonProfiles = async (collectionID: number,collectionKey: string,+ signal?: AbortSignal,): Promise<Map<string, string>> => {const res = await fetch(await apiURL("/social/anon-profiles", { collectionID }),- { headers: await authenticatedRequestHeaders() },+ { headers: await authenticatedRequestHeaders(), signal },);ensureOk(res);const { profiles } = GetAnonProfilesResponse.parse(await res.json());@@ -216,3 +239,26 @@ const GetAnonProfilesResponse = z.object({.nullish().transform((v) => v ?? []),});++const SocialUpdatesResponse = z.object({+ updates: z+ .array(+ z.object({+ collectionID: z.number(),+ commentsUpdatedAt: z.number().nullish(),+ reactionsUpdatedAt: z.number().nullish(),+ anonProfilesUpdatedAt: z.number().nullish(),+ }),+ )+ .nullish()+ .transform((updates) => updates ?? []),+});++export const getSocialUpdates = async (signal?: AbortSignal) => {+ const response = await fetch(+ await apiURL("/comments-reactions/updated-at"),+ { headers: await authenticatedRequestHeaders(), signal },+ );+ ensureOk(response);+ return SocialUpdatesResponse.parse(await response.json()).updates;+};