Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add periodic refresh for comments, likes, and public feed sidebars

Anand Baburajan8fcb02fd62d2
diff --git a/web/packages/base/components/utils/hooks.ts b/web/packages/base/components/utils/hooks.ts
index 4515cd7ad7..f89e7abc1d 100644
--- a/web/packages/base/components/utils/hooks.ts
+++ b/web/packages/base/components/utils/hooks.ts
@@ -1,5 +1,5 @@
import { useMediaQuery, useTheme } from "@mui/material";
-import { useCallback, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
/**
* Return true if the screen width is classified as a small size. This is often
@@ -50,3 +50,30 @@ export const useClipboardCopy = (
return [copied, handleCopyLink];
};
+
+/**
+ * A hook that runs a callback at a specified interval.
+ *
+ * @param callback The function to call on each interval tick.
+ * @param delay The interval in milliseconds, or null to pause the interval.
+ */
+export const useInterval = (
+ callback: () => void,
+ delay: number | null,
+): void => {
+ const savedCallback = useRef(callback);
+
+ // Remember the latest callback
+ useEffect(() => {
+ savedCallback.current = callback;
+ }, [callback]);
+
+ // Set up the interval
+ useEffect(() => {
+ if (delay === null) return;
+
+ const tick = () => savedCallback.current();
+ const id = setInterval(tick, delay);
+ return () => clearInterval(id);
+ }, [delay]);
+};
diff --git a/web/packages/gallery/components/viewer/CommentsSidebar.tsx b/web/packages/gallery/components/viewer/CommentsSidebar.tsx
index baf36a95f3..3355acc852 100644
--- a/web/packages/gallery/components/viewer/CommentsSidebar.tsx
+++ b/web/packages/gallery/components/viewer/CommentsSidebar.tsx
@@ -504,6 +504,7 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
const [hasAnonIdentity, setHasAnonIdentity] = useState(false);
const [loading, setLoading] = useState(false);
const [sending, setSending] = useState(false);
+ const hasLoadedRef = useRef(false);
const inputRef = useRef<HTMLInputElement>(null);
const commentsContainerRef = useRef<HTMLDivElement>(null);
// Ref to preserve isLiked state during context menu close animation
@@ -544,10 +545,11 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
}
}, [replyingTo]);
- // Reset highlight tracking when sidebar closes
+ // Reset tracking refs when sidebar closes
useEffect(() => {
if (!open) {
hasScrolledToHighlightRef.current = false;
+ hasLoadedRef.current = false;
}
}, [open]);
@@ -770,7 +772,11 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
const loadComments = useCallback(() => {
if (!file || !open || !prefetchedComments) return;
- setLoading(true);
+ // Only show loading spinner on initial load, not during polling refresh
+ const isInitialLoad = !hasLoadedRef.current;
+ if (isInitialLoad) {
+ setLoading(true);
+ }
try {
// Use prefetched data
@@ -820,7 +826,10 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({
} catch (e) {
log.error("Failed to load comments", e);
} finally {
- setLoading(false);
+ if (isInitialLoad) {
+ hasLoadedRef.current = true;
+ setLoading(false);
+ }
}
}, [
file,
diff --git a/web/packages/gallery/components/viewer/FileViewer.tsx b/web/packages/gallery/components/viewer/FileViewer.tsx
index 8bb5d9a9b2..66766e2f60 100644
--- a/web/packages/gallery/components/viewer/FileViewer.tsx
+++ b/web/packages/gallery/components/viewer/FileViewer.tsx
@@ -26,7 +26,7 @@ import { TitledMiniDialog } from "ente-base/components/MiniDialog";
import { DialogCloseIconButton } from "ente-base/components/mui/DialogCloseIconButton";
import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";
import { LoadingButton } from "ente-base/components/mui/LoadingButton";
-import { useIsSmallWidth } from "ente-base/components/utils/hooks";
+import { useInterval, useIsSmallWidth } from "ente-base/components/utils/hooks";
import { type ModalVisibilityProps } from "ente-base/components/utils/modal";
import { useBaseContext } from "ente-base/context";
import { lowercaseExtension } from "ente-base/file-name";
@@ -509,6 +509,20 @@ export const FileViewer: React.FC<FileViewerProps> = ({
fileNormalCollectionIDsRef.current = fileNormalCollectionIDs;
}, [fileNormalCollectionIDs]);
+ // Cache for collection keys to avoid refetching during polling
+ const collectionCacheRef = useRef<
+ Map<
+ number,
+ {
+ key: string;
+ ownerID: number;
+ ownerEmail?: string;
+ sharees: { id: number; email?: string }[];
+ hasPublicURLs: boolean;
+ }
+ >
+ >(new Map());
+
// Track whether we've already opened the initial sidebar for this open
const hasOpenedInitialSidebarRef = useRef(false);
@@ -1981,6 +1995,18 @@ export const FileViewer: React.FC<FileViewerProps> = ({
const collection =
await getCollectionByID(collectionId);
+ // Cache collection data for polling refresh
+ collectionCacheRef.current.set(collectionId, {
+ key: collection.key,
+ ownerID: collection.owner.id,
+ ownerEmail: collection.owner.email,
+ sharees: collection.sharees.map((s) => ({
+ id: s.id,
+ email: s.email,
+ })),
+ hasPublicURLs: collection.publicURLs.length > 0,
+ });
+
// Build user ID to email map from collection owner and sharees
if (collection.owner.email) {
newUserIDToEmail.set(
@@ -2200,6 +2226,213 @@ export const FileViewer: React.FC<FileViewerProps> = ({
}
}, [fileComments, files, open]);
+ // Polling interval for refreshing social data (5 seconds)
+ const SOCIAL_REFRESH_INTERVAL_MS = 5_000;
+
+ // Refresh social data for logged-in users (uses cached collection keys)
+ const refreshSocialData = useCallback(async () => {
+ if (!activeFileID) return;
+
+ const isGalleryView = !activeCollectionID || activeCollectionID === 0;
+ const shouldFetch =
+ showSocialButtons ||
+ (isGalleryView && isFileInSharedCollection(activeFileID));
+ if (!shouldFetch) return;
+
+ try {
+ const commentsMap = new Map<number, Comment[]>();
+ const reactionsMap = new Map<number, UnifiedReaction[]>();
+ const newAnonUserNames = new Map<string, string>();
+
+ const collectionIDs = isGalleryView
+ ? (fileNormalCollectionIDs?.get(activeFileID) ?? [])
+ : [activeCollectionID];
+
+ for (const collectionId of collectionIDs) {
+ // Use cached collection data (populated during initial fetch)
+ const cached = collectionCacheRef.current.get(collectionId);
+ if (!cached) continue; // Skip if not in cache
+
+ try {
+ const { comments, reactions } = await getUnifiedSocialDiff(
+ collectionId,
+ activeFileID,
+ cached.key,
+ );
+
+ commentsMap.set(collectionId, comments);
+ reactionsMap.set(collectionId, reactions);
+
+ if (cached.hasPublicURLs) {
+ try {
+ const anonProfiles = await getAnonProfiles(
+ collectionId,
+ cached.key,
+ );
+ for (const [anonUserID, userName] of anonProfiles) {
+ newAnonUserNames.set(anonUserID, userName);
+ }
+ } catch {
+ // Ignore
+ }
+ }
+ } catch {
+ // Skip failed collections
+ }
+ }
+
+ setFileComments((prev) => {
+ const next = new Map(prev);
+ next.set(activeFileID, commentsMap);
+ return next;
+ });
+
+ setAllReactions((prev) => {
+ const next = new Map(prev);
+ next.set(activeFileID, reactionsMap);
+ return next;
+ });
+
+ setAnonUserNames((prev) => {
+ const next = new Map(prev);
+ for (const [id, name] of newAnonUserNames) {
+ next.set(id, name);
+ }
+ return next;
+ });
+ } catch (e) {
+ log.error("Failed to refresh social data", e);
+ }
+ }, [
+ activeFileID,
+ activeCollectionID,
+ fileNormalCollectionIDs,
+ showSocialButtons,
+ isFileInSharedCollection,
+ ]);
+
+ // Refresh social data for public albums
+ const refreshPublicSocialData = useCallback(async () => {
+ if (
+ !activeFileID ||
+ !publicAlbumsCredentials ||
+ !collectionKey ||
+ !enableComment
+ )
+ return;
+
+ const file = files.find((f) => f.id === activeFileID);
+ if (!file) return;
+
+ try {
+ const { comments, reactions } = await getPublicSocialDiff(
+ publicAlbumsCredentials,
+ activeFileID,
+ collectionKey,
+ );
+
+ const commentsForFile: Comment[] = comments.map((c) => ({
+ id: c.id,
+ collectionID: c.collectionID,
+ fileID: c.fileID,
+ parentCommentID: c.parentCommentID,
+ userID: c.userID,
+ anonUserID: c.anonUserID,
+ text: c.text,
+ isDeleted: c.isDeleted,
+ createdAt: c.createdAt,
+ updatedAt: c.updatedAt,
+ }));
+
+ const commentsMap = new Map<number, Comment[]>();
+ commentsMap.set(file.collectionID, commentsForFile);
+
+ setFileComments((prev) => {
+ const next = new Map(prev);
+ next.set(activeFileID, commentsMap);
+ return next;
+ });
+
+ const unifiedReactions: UnifiedReaction[] = reactions.map((r) => ({
+ id: r.id,
+ collectionID: file.collectionID,
+ fileID: r.fileID,
+ commentID: r.commentID,
+ reactionType: r.reactionType,
+ userID: r.userID,
+ anonUserID: r.anonUserID,
+ isDeleted: r.isDeleted,
+ createdAt: r.createdAt,
+ updatedAt: r.updatedAt,
+ }));
+
+ const reactionsMap = new Map<number, UnifiedReaction[]>();
+ reactionsMap.set(file.collectionID, unifiedReactions);
+
+ setAllReactions((prev) => {
+ const next = new Map(prev);
+ next.set(activeFileID, reactionsMap);
+ return next;
+ });
+
+ try {
+ const anonProfiles = await getPublicAnonProfiles(
+ publicAlbumsCredentials,
+ collectionKey,
+ );
+ setAnonUserNames((prev) => {
+ const next = new Map(prev);
+ for (const [id, name] of anonProfiles) {
+ next.set(id, name);
+ }
+ return next;
+ });
+ } catch {
+ // Ignore
+ }
+
+ try {
+ const participantEmails =
+ await getPublicParticipantsMaskedEmails(
+ publicAlbumsCredentials,
+ );
+ setUserIDToEmail((prev) => {
+ const next = new Map(prev);
+ for (const [id, email] of participantEmails) {
+ next.set(id, email);
+ }
+ return next;
+ });
+ } catch {
+ // Ignore
+ }
+ } catch (e) {
+ log.error("Failed to refresh public social data", e);
+ }
+ }, [
+ activeFileID,
+ publicAlbumsCredentials,
+ collectionKey,
+ enableComment,
+ files,
+ ]);
+
+ // Poll for social data when comments or likes sidebar is open (logged-in users)
+ useInterval(
+ refreshSocialData,
+ (openComments || openLikes) && !publicAlbumsCredentials
+ ? SOCIAL_REFRESH_INTERVAL_MS
+ : null,
+ );
+
+ // Poll for social data when comments or likes sidebar is open (public albums)
+ useInterval(
+ refreshPublicSocialData,
+ (openComments || openLikes) && publicAlbumsCredentials
+ ? SOCIAL_REFRESH_INTERVAL_MS
+ : null,
+ );
+
useEffect(() => {
if (open) {
// We're open. Create psRef. This will show the file viewer dialog.
diff --git a/web/packages/gallery/components/viewer/PublicFeedSidebar.tsx b/web/packages/gallery/components/viewer/PublicFeedSidebar.tsx
index 6569cf96b1..fb5e5ff5e3 100644
--- a/web/packages/gallery/components/viewer/PublicFeedSidebar.tsx
+++ b/web/packages/gallery/components/viewer/PublicFeedSidebar.tsx
@@ -10,6 +10,7 @@ import {
Typography,
} from "@mui/material";
import { useColorScheme } from "@mui/material/styles";
+import { useInterval } from "ente-base/components/utils/hooks";
import { type ModalVisibilityProps } from "ente-base/components/utils/modal";
import type { PublicAlbumsCredentials } from "ente-base/http";
import log from "ente-base/log";
@@ -25,7 +26,7 @@ import {
type PublicFeedReaction,
} from "ente-new/albums/services/public-reaction";
import { t } from "i18next";
-import React, { useEffect, useMemo, useState } from "react";
+import React, { useCallback, useEffect, useMemo, useState } from "react";
// =============================================================================
// Icons
@@ -716,36 +717,40 @@ export const PublicFeedSidebar: React.FC<PublicFeedSidebarProps> = ({
}
}, [open, comments, reactions, files]);
- // Fetch social data when sidebar opens
+ // Polling interval for refreshing feed data (5 seconds)
+ const FEED_REFRESH_INTERVAL_MS = 5_000;
+
+ // Fetch social data (used for both initial load and periodic refresh)
+ const fetchSocialData = useCallback(async () => {
+ try {
+ const [feedData, anonProfiles, participantEmails] =
+ await Promise.all([
+ getPublicAlbumFeed(credentials, collectionKey),
+ getPublicAnonProfiles(credentials, collectionKey),
+ getPublicParticipantsMaskedEmails(credentials),
+ ]);
+ setComments(feedData.comments);
+ setReactions(feedData.reactions);
+ setAnonUserNames(anonProfiles);
+ setMaskedEmails(participantEmails);
+ } catch (e) {
+ log.error("Failed to fetch public album feed", e);
+ }
+ }, [credentials, collectionKey]);
+
+ // Initial fetch when sidebar opens
useEffect(() => {
- const fetchSocialData = async () => {
- if (!open) return;
-
- setIsLoading(true);
- try {
- const [feedData, anonProfiles, participantEmails] =
- await Promise.all([
- getPublicAlbumFeed(credentials, collectionKey),
- getPublicAnonProfiles(credentials, collectionKey),
- getPublicParticipantsMaskedEmails(credentials),
- ]);
- setComments(feedData.comments);
- setReactions(feedData.reactions);
- setAnonUserNames(anonProfiles);
- setMaskedEmails(participantEmails);
- } catch (e) {
- log.error("Failed to fetch public album feed", e);
- setComments([]);
- setReactions([]);
- setAnonUserNames(new Map());
- setMaskedEmails(new Map());
- } finally {
- setIsLoading(false);
- }
- };
+ if (!open) return;
+
+ setIsLoading(true);
+ void fetchSocialData().finally(() => setIsLoading(false));
+ }, [open, fetchSocialData]);
- void fetchSocialData();
- }, [open, credentials, collectionKey]);
+ // Periodic refresh while sidebar is open
+ useInterval(
+ fetchSocialData,
+ open && !isLoading ? FEED_REFRESH_INTERVAL_MS : null,
+ );
const feedItems = useMemo(
() =>
diff --git a/web/packages/gallery/components/viewer/photoswipe.ts b/web/packages/gallery/components/viewer/photoswipe.ts
index c8f517e865..2d227a6320 100644
--- a/web/packages/gallery/components/viewer/photoswipe.ts
+++ b/web/packages/gallery/components/viewer/photoswipe.ts
@@ -1190,6 +1190,8 @@ export class FileViewerPhotoSwipe {
}
const af = currentAnnotatedFile();
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
+ if (!af) return; // Guard against undefined during initialization
const isLiked = delegate.isLiked(af);
// Show fill (green) if liked, show outline (white) if not liked
@@ -1209,6 +1211,8 @@ export class FileViewerPhotoSwipe {
}
const af = currentAnnotatedFile();
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
+ if (!af) return; // Guard against undefined during initialization
const count = delegate.getCommentCount(af);
commentCountElement.textContent = String(count);
};