π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Prune public album comments
Manav Rathi316111f04d6f
diff --git a/web/apps/albums/src/public-album/access/hooks/useJoinAlbum.ts b/web/apps/albums/src/public-album/access/hooks/useJoinAlbum.tsindex f8564c60eb..743b09dcd2 100644--- a/web/apps/albums/src/public-album/access/hooks/useJoinAlbum.ts+++ b/web/apps/albums/src/public-album/access/hooks/useJoinAlbum.ts@@ -4,25 +4,16 @@ import type { Collection } from "ente-media/collection";import type { RefObject } from "react";export interface UseJoinAlbumProps {- /** Collection to join */publicCollection?: Collection;- /** Access token for the public link */accessToken?: string;- /** Collection key from URL (base64 encoded) */collectionKey?: string;- /** Credentials ref for JWT token access */credentials?: RefObject<PublicAlbumsCredentials | undefined>;}export interface UseJoinAlbumReturn {- /** Handler for join album action */handleJoinAlbum: () => void;}-/**- * Custom hook that provides join album logic and handlers.- * Components can use this hook and apply their own button styling.- */export const useJoinAlbum = ({publicCollection,accessToken,diff --git a/web/apps/albums/src/public-album/access/services/extract-collection-key.ts b/web/apps/albums/src/public-album/access/services/extract-collection-key.tsindex 144d8dfb12..8dfbb368d4 100644--- a/web/apps/albums/src/public-album/access/services/extract-collection-key.ts+++ b/web/apps/albums/src/public-album/access/services/extract-collection-key.ts@@ -1,13 +1,8 @@import bs58 from "bs58";import { fromHex, toB64 } from "ente-base/crypto";-/**- * Extract the collection key from a public URL.- *- * Public album URLs encode the collection key in the hash as base-58.- * Legacy links might still carry the older hex encoding.- */export const extractCollectionKeyFromShareURL = async (url: URL) => {const ck = url.hash.slice(1);+ // Legacy links use hex; current links use base58.return ck.length < 50 ? await toB64(bs58.decode(ck)) : await fromHex(ck);};diff --git a/web/apps/albums/src/public-album/access/services/join-public-album-redirect.ts b/web/apps/albums/src/public-album/access/services/join-public-album-redirect.tsindex 30b727aacc..be74007f70 100644--- a/web/apps/albums/src/public-album/access/services/join-public-album-redirect.ts+++ b/web/apps/albums/src/public-album/access/services/join-public-album-redirect.ts@@ -9,9 +9,6 @@ export interface JoinPublicAlbumRedirectProps {credentials?: RefObject<PublicAlbumsCredentials | undefined>;}-/**- * Build the web app redirect URL for joining an album.- */const buildWebRedirectURL = (accessToken: string,collectionId: number,@@ -22,10 +19,6 @@ const buildWebRedirectURL = (return `https://photos.ente.com/?joinAlbum=${accessToken}&collectionId=${collectionId}#${currentHash}${hashSuffix}`;};-/**- * Handle the fallback flow when the native app doesn't open.- * Redirects to web app with all join context in the URL.- */const handleWebFallback = (accessToken: string,collectionId: number,@@ -41,10 +34,6 @@ const handleWebFallback = (window.location.href = redirectURL;};-/**- * Attempt to open the native app via deep link, with fallback to web.- * Returns a cleanup function to clear the timeout if needed.- */const tryDeepLinkWithFallback = (deepLinkURL: string,fallbackFn: () => void | Promise<void>,diff --git a/web/apps/albums/src/public-album/access/services/verify-public-album-password.ts b/web/apps/albums/src/public-album/access/services/verify-public-album-password.tsindex 13fda6f0ab..1c68bcc5a7 100644--- a/web/apps/albums/src/public-album/access/services/verify-public-album-password.ts+++ b/web/apps/albums/src/public-album/access/services/verify-public-album-password.ts@@ -7,10 +7,6 @@ import { apiURL } from "ente-base/origins";import type { PublicURL } from "ente-media/collection";import { z } from "zod";-/**- * Verify the password entered for a password-protected public album and return- * the JWT token needed for subsequent authenticated public-album requests.- */export const verifyPublicAlbumPassword = async (publicURL: PublicURL,password: string,diff --git a/web/apps/albums/src/public-album/access/utils/external-links.ts b/web/apps/albums/src/public-album/access/utils/external-links.tsindex afaf9aef52..3a37b8be76 100644--- a/web/apps/albums/src/public-album/access/utils/external-links.ts+++ b/web/apps/albums/src/public-album/access/utils/external-links.ts@@ -1,4 +1 @@-/**- * Get the destination URL for "Get Ente Photos" actions in public albums.- */export const getEnteURL = (): string => "https://ente.com/get";diff --git a/web/apps/albums/src/public-album/components/FileList.tsx b/web/apps/albums/src/public-album/components/FileList.tsxindex 60cac7ec54..a7eb1cbfd8 100644--- a/web/apps/albums/src/public-album/components/FileList.tsx+++ b/web/apps/albums/src/public-album/components/FileList.tsx@@ -40,99 +40,35 @@ import {type ListChildComponentProps,} from "react-window";-/**- * A component with an explicit height suitable for being plugged in as the- * {@link header} or {@link footer} of the {@link FileList}.- */export interface FileListHeaderOrFooter {- /**- * The component itself.- */component: React.ReactNode;- /**- * The height of the component (in px).- */height: number;- /**- * By default, all items in the {@link FileList}, including headers and- * footers injected using this type, get an inline margin.- *- * Set this property to `true` to omit this default margin, and instead- * have the component extend to the container's edges.- */extendToInlineEdges?: boolean;}-/**- * Data needed to render each row in the variable size list that comprises the- * file list.- */type FileListItem =| {type: "file";- /**- * The height of the row that will render this item.- */height: number;- /**- * Groups of items that are shown in the row.- *- * Each group spans multiple columns (the number of columns being given by- * the length of {@link annotatedFiles} or the {@link span}). Groups are- * separated by gaps.- */groups: {- /**- * The annotated files in this group.- */annotatedFiles: FileListAnnotatedFile[];- /**- * The index of the first annotated file in the component's global list- * of annotated files.- */annotatedFilesStartIndex: number;}[];}| {type: "date";height: number;- groups: {- /**- * The date string to show.- */- date: string;- /**- * The number of columns to span.- */- dateSpan: number;- }[];+ groups: { date: string; dateSpan: number }[];}| {type: "span";height: number;- /**- * The React component that is the rendered representation of the item.- */component: React.ReactNode;extendToInlineEdges?: boolean;};export interface FileListAnnotatedFile {file: EnteFile;- /**- * The date string using with the associated {@link file} should be shown in- * the timeline.- *- * [Note: Timeline date string]- *- * The timeline date string is a formatted date string under which a- * particular file should be grouped in the gallery listing. e.g. "Today",- * "Yesterday", "Fri, 21 Feb" etc.- *- * All files which have the same timelineDateString will be grouped under a- * single section in the gallery listing, prefixed by the timelineDateString- * itself, and a checkbox to select all files on that date.- */timelineDateString: string;}@@ -159,56 +95,22 @@ interface MasonrySourceItem {}export interface FileListProps {- /** The height we should occupy (needed since the list is virtualized). */height: number;- /** The width we should occupy.*/width: number;- /**- * The files to show, annotated with cached precomputed properties that are- * frequently needed by the {@link FileList}.- */annotatedFiles: FileListAnnotatedFile[];- /**- * The visual layout used to render the file listing.- */layout?: "grid" | "masonry";- /**- * An optional component shown before all the items in the list.- *- * It is not sticky, and scrolls along with the content of the list.- */header?: FileListHeaderOrFooter;- /**- * An optional component shown after all the items in the list.- *- * It is not sticky, and scrolls along with the content of the list.- */footer?: FileListHeaderOrFooter;- /**- * If `true`, then the user can select files in the listing by clicking on- * their thumbnails (and other range selection mechanisms).- */enableSelect?: boolean;setSelected: (selected: SelectedState | ((selected: SelectedState) => SelectedState),) => void;selected: SelectedState;- /** A stable key used to reset the virtualized list when the file set changes. */activeCollectionID: number;- /** Optional action shown below the empty list message. */emptyStateAction?: { label: string; onClick: () => void };- /**- * Called when the user activates the thumbnail at the given {@link index}.- *- * This corresponding file would be at the corresponding index of- * {@link annotatedFiles}.- */onItemClick: (index: number) => void;}-/**- * A virtualized list of files, each represented by their thumbnail.- */export const FileList: React.FC<FileListProps> = ({height,width,@@ -224,6 +126,7 @@ export const FileList: React.FC<FileListProps> = ({onItemClick,}) => {const [_items, setItems] = useState<FileListItem[]>([]);+ // Deferring item updates keeps resize work interruptible.const items = useDeferredValue(_items);const [rangeStartIndex, setRangeStartIndex] = useState<number | undefined>(@@ -236,9 +139,6 @@ export const FileList: React.FC<FileListProps> = ({const masonryScrollIdleTimeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);- // Timeline date strings for which all photos have been selected.- //- // See: [Note: Timeline date string]const [checkedTimelineDateStrings, setCheckedTimelineDateStrings] =useState(new Set<string>());const listRef = useRef<VariableSizeList | null>(null);@@ -256,22 +156,12 @@ export const FileList: React.FC<FileListProps> = ({return;}- // Since width and height are dependencies, there might be too many- // updates to the list during a resize. The list computation too, while- // fast, is non-trivial.- //- // To avoid these issues, the we use `useDeferredValue`: if it gets- // another update when processing one, React will restart the background- // rerender from scratch.-let items: FileListItem[] = [];if (header) items.push(asFullSpanFileListItem(header));const { isSmallerLayout, columns } = layoutParams;const fileItemHeight = layoutParams.itemHeight + layoutParams.gap;- // A running counter of files that have been pushed into items, and- // a function to push them (incrementing the counter).let fileIndex = 0;const createFileItem = (splits: FileListAnnotatedFile[][]) =>({@@ -289,8 +179,6 @@ export const FileList: React.FC<FileListProps> = ({const pushItemsFromSplits = (splits: FileListAnnotatedFile[][]) => {if (splits.length > 1) {- // If we get here, the combined number of files across- // splits is less than the number of columns.items.push({height: dateListItemHeight,type: "date",@@ -301,8 +189,6 @@ export const FileList: React.FC<FileListProps> = ({});items.push(createFileItem(splits));} else {- // A single group of files, but the number of such files- // might be more than what fits a single row.items.push({height: dateListItemHeight,type: "date",@@ -329,7 +215,6 @@ export const FileList: React.FC<FileListProps> = ({);const incomingColumns = split.length;- // Check if the files in this split can be added to same row.if (!isSmallerLayout &&filledColumns +@@ -387,7 +272,6 @@ export const FileList: React.FC<FileListProps> = ({]);useEffect(() => {- // Refresh listlistRef.current?.resetAfterIndex(0);}, [items]);@@ -396,28 +280,21 @@ export const FileList: React.FC<FileListProps> = ({(af) => !selected[af.file.id],);- // Get dates of files which were manually unselected.const unselectedDates = new Set(notSelectedFiles.map((af) => af.timelineDateString),);- // Get files which were manually selected.const localSelectedFiles = annotatedFiles.filter((af) => !unselectedDates.has(af.timelineDateString),);- // Get dates of files which were manually selected.const localSelectedDates = new Set(localSelectedFiles.map((af) => af.timelineDateString),);setCheckedTimelineDateStrings((prev) => {const checked = new Set(prev);- // Uncheck the "Select all" checkbox if any of the files on the date- // is unselected.unselectedDates.forEach((date) => checked.delete(date));- // Check the "Select all" checkbox if all of the files on a date are- // selected.localSelectedDates.forEach((date) => checked.add(date));return checked;});@@ -441,7 +318,6 @@ export const FileList: React.FC<FileListProps> = ({}setCheckedTimelineDateStrings(next);- // All files on a checked/unchecked day.const filesOnADay = annotatedFiles.filter((af) => af.timelineDateString === date,);@@ -963,10 +839,6 @@ export const FileList: React.FC<FileListProps> = ({);};-/**- * Return a new array of splits, each split containing {@link annotatedFiles}- * which have the same {@link timelineDateString}.- */const splitByDate = (annotatedFiles: FileListAnnotatedFile[]) =>annotatedFiles.reduce((splits, annotatedFile) => (@@ -1064,7 +936,7 @@ const preferredMobileMasonryRowItemCount = (const secondIsPortrait = secondRatio < 0.9;const thirdIsPortrait = !!third && third.aspectRatio < 0.9;- // Occasionally show one tall portrait in a row to mimic the mobile collage feel.+ // Periodically isolate a tall portrait for the mobile collage layout.if (firstRatio <= 0.62 && rowIndex % 4 === 1) return 1;if (firstIsPortrait && secondIsPortrait && third && thirdIsPortrait) {@@ -1077,11 +949,6 @@ const preferredMobileMasonryRowItemCount = (return 2;};-/**- * For each element of {@link xs}, obtain an array by applying {@link f},- * then obtain a gap element by applying {@link g}. Return a flattened array- * containing all of these, except the trailing gap.- */const intersperseWithGaps = <T, U>(xs: T[],f: (x: T) => U[],@@ -1091,9 +958,6 @@ const intersperseWithGaps = <T, U>(return ys.slice(0, ys.length - 1);};-/**- * A list item container that spans the full width.- */const FullSpanListItem = styled("div")`display: flex;align-items: center;@@ -1156,10 +1020,6 @@ const EmptyStateActionButton = styled(Button)(({ theme }) => ({"& svg": { color: "inherit" },}));-/**- * Convert a {@link FileListHeaderOrFooter} into a {@link FileListItem}- * that spans the entire width available to the row.- */const asFullSpanFileListItem = ({component,...rest@@ -1169,18 +1029,12 @@ const asFullSpanFileListItem = ({component: <FullSpanListItem>{component}</FullSpanListItem>,});-/**- * An grid item, spanning {@link span} columns.- */const GridSpanListItem = styled("div")<{ span: number }>`grid-column: span ${({ span }) => span};display: flex;align-items: center;`;-/**- * The fixed height (in px) of {@link DateListItem}.- */const dateListItemHeight = 48;const DateListItem = styled(GridSpanListItem)(@@ -1427,6 +1281,8 @@ const FileThumbnail_ = styled("div")<{border-radius: 4px;`;+// Safari requires both pseudo-elements to be blocks.+// It also requires ::before to be relatively positioned.const Check = styled("input")<{ $active: boolean }>(({ theme, $active }) => `appearance: none;@@ -1447,19 +1303,19 @@ const Check = styled("input")<{ $active: boolean }>(&::before {content: "";- display: block; /* Critical for Safari */+ display: block;width: 19px;height: 19px;background-color: #ddd;border-radius: 50%;margin: 6px;transition: background-color 0.3s ease, opacity 0.3s ease;- position: relative; /* Important for Safari */+ position: relative;}&::after {content: "";- display: block; /* Critical for Safari */+ display: block;position: absolute;top: 50%;left: 50%;@@ -1472,10 +1328,8 @@ const Check = styled("input")<{ $active: boolean }>(transform-origin: center;}- /* Default state - hide both */visibility: hidden;- /* When $active - show both with reduced opacity */${$active &&`@@ -1484,13 +1338,11 @@ const Check = styled("input")<{ $active: boolean }>(`};- /* Hover state - show both */&:hover {visibility: visible;opacity: 0.7;}- /* Checked state - show both with full opacity and colored */&:checked {visibility: visible;opacity: 1 !important;@@ -1519,10 +1371,6 @@ const HoverOverlay = styled("div")<{ checked: boolean }>`"background:linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0))"};`;-/**- * An overlay with a gradient, showing the file type indicator (e.g. live photo,- * video) at the bottom right.- */const FileTypeIndicatorOverlay = styled(Overlay)`display: flex;justify-content: flex-end;diff --git a/web/apps/albums/src/public-album/components/FileListWithViewer.tsx b/web/apps/albums/src/public-album/components/FileListWithViewer.tsxindex 5aecdb2f6d..7a25beb035 100644--- a/web/apps/albums/src/public-album/components/FileListWithViewer.tsx+++ b/web/apps/albums/src/public-album/components/FileListWithViewer.tsx@@ -22,36 +22,13 @@ import {} from "./FileList";export type FileListWithViewerProps = {- /**- * The list of files to show.- */files: EnteFile[];enableDownload?: boolean;- /**- * If set, the file viewer will open to this file index on mount/update.- * Set to undefined after the navigation is complete.- */pendingFileIndex?: number;- /**- * The sidebar to open when navigating to a file from feed.- */pendingFileSidebar?: FileViewerInitialSidebar;- /**- * The comment ID to highlight when navigating from feed.- */pendingHighlightCommentID?: string;- /**- * Resolved anonymous display names from the feed for the target album.- */pendingAnonUserNames?: Map<string, string>;- /**- * Called after the pending navigation is consumed.- */onPendingNavigationConsumed?: () => void;- /**- * A function that can be used to create a UI notification to track the- * progress of user-initiated download, and to cancel it if needed.- */onAddSaveGroup: AddSaveGroup;} & Pick<FileListProps,@@ -73,11 +50,6 @@ export type FileListWithViewerProps = {| "enableJoin">;-/**- * A list of files (represented by their thumbnails), along with a file viewer- * that opens on activating the thumbnail (and also allows the user to navigate- * through this list of files).- */export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({layout,header,@@ -113,7 +85,6 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({Map<string, string> | undefined>(undefined);- // Handle pending navigation from feed item clicksuseEffect(() => {if (pendingFileIndex !== undefined) {setCurrentIndex(pendingFileIndex);@@ -135,7 +106,6 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({onPendingNavigationConsumed,]);- // Clear initial sidebar state when file viewer closesconst handleCloseFileViewerInternal = useCallback(() => {setInitialSidebar(undefined);setHighlightCommentID(undefined);@@ -228,9 +198,6 @@ const Container = styled("div")`width: 100%;`;-/**- * See: [Note: Timeline date string]- */const fileTimelineDateString = (file: EnteFile) => {const date = fileCreationPhotoDate(file);return isSameDay(date, new Date())diff --git a/web/apps/albums/src/public-album/data/api/public-collection.ts b/web/apps/albums/src/public-album/data/api/public-collection.tsindex b404a67aa2..fad0ba5b62 100644--- a/web/apps/albums/src/public-album/data/api/public-collection.ts+++ b/web/apps/albums/src/public-album/data/api/public-collection.ts@@ -32,28 +32,6 @@ import {savePublicCollectionLastSyncTime,} from "../storage/public-albums-fdb";-/**- * Verify with remote that the password entered by the user is the same as the- * password that was set by the person who shared the public album.- *- * The verification is done on a password hash that we check with remote. If- * they match, remote will provide us with another token that can be used to- * make API calls for this password protected public album.- *- * If they don't match, or if {@link accessToken} itself has expired, then- * remote will return a HTTP 401.- *- * @param publicURL Data about the public album.- *- * @param password The password entered by the user.- *- * @param token The access token to make API requests for a particular public- * album.- *- * @returns A accessTokenJWT.- *- * See [Note: Password token for public albums requests]- */export const verifyPublicAlbumPassword = async (publicURL: PublicURL,password: string,@@ -79,26 +57,6 @@ export const verifyPublicAlbumPassword = async (return z.object({ jwtToken: z.string() }).parse(await res.json()).jwtToken;};-/**- * Fetch a public collection from remote using its access key, decrypt it using- * the provided key, save the collection in our local database for subsequent- * use, and return it.- *- * This function modifies local state.- *- * @param accessToken A public collection access key obtained from the public- * URL path token, or from the legacy "t" query parameter.- *- * The access key serves to both identify the public collection, and also- * authenticate the request. See: [Note: Public album access token].- *- * @param collectionKey The base64 encoded key that can be used to decrypt the- * collection obtained from remote.- *- * The collection key is obtained from the fragment portion of the public URL- * (the fragment is a client side only portion that can be used to have local- * secrets that are not sent by the browser to the server).- */export const pullCollection = async (credentials: PublicAlbumsCredentials,collectionKey: string,@@ -107,6 +65,7 @@ export const pullCollection = async (referralCode: string;linkDeviceToken?: string;}> => {+ // The collection key comes from the URL fragment. Never send it to remote.const {collection: remoteCollection,referralCode,@@ -126,25 +85,9 @@ export const pullCollection = async (const PublicCollectionInfo = z.object({collection: RemoteCollection,- /**- * A referral code of the owner of the public album.- *- * [Note: Public albums referral code]- *- * The information of a public collection contains the referral code of the- * person who shared the album. This allows both the viewer and the sharer- * to gain storage bonus.- */referralCode: z.string(),});-/**- * Fetch information from remote about a public collection using its access key.- *- * Remote only, does not modify local state.- *- * @param accessToken A public collection access key.- */const getPublicCollectionInfo = async (credentials: PublicAlbumsCredentials,) => {@@ -156,54 +99,17 @@ const getPublicCollectionInfo = async (return { ...info, linkDeviceToken: linkDeviceTokenFromResponse(res) };};-/**- * Pull any changes to the files belonging to the given collection, updating our- * local database and also calling the provided callback.- *- * This function modifies local state.- *- * The pull uses a persisted timestamp for the most recent change we've already- * fetched, and will be only fetch the delta of changes since the last pull. The- * files are fetched in a paginated manner, so the provided callback can get- * called multiple times during the pull (one for each page).- *- * @param credentials A public collection access key and an optional password- * unlocked access token JWT. The credentials serve to both identify the- * collection, and authenticate the request.- *- * @param collection The public collection corresponding to the credentials.- *- * This function assumes that collection has already been pulled from remote and- * is at its latest, remote, value. This assumption is used to skip fetching- * files if the collection has not changed on remote (any updates to the files- * will also increase the updation time of the collection that contains them).- *- * @param onSetFiles A callback that is invoked with the consolidated list of- * files after processing each batch of updates.- *- * The provided files are in an arbitrary order, and must be sorted before use.- *- * When called:- * - At least once if there are remote changes to fetch (may be called multiple- * times if changes span multiple pages)- * - Once with cached files if the diff is empty on first iteration (handles- * empty albums on initial load)- * - Not called if collection is already synced and no updates are needed- * (updationTime equals last sync time)- */export const pullPublicCollectionFiles = async (credentials: PublicAlbumsCredentials,collection: Collection,+ // Files passed here have no defined order.onSetFiles: (files: EnteFile[]) => void,) => {const { accessToken } = credentials;let sinceTime = (await savedPublicCollectionLastSyncTime(accessToken)) ?? 0;- // Prior to reaching here, we would've already fetched the latest- // collection. If the updation time of the collection is the same as the- // last sync time, then we know there were no new updates (since updates to- // files also increase the updation time of their containing collection).+ // Remote advances collection.updationTime whenever a file changes.if (sinceTime == collection.updationTime) return;const files = await savedPublicCollectionFiles(accessToken);@@ -216,8 +122,7 @@ export const pullPublicCollectionFiles = async (sinceTime,);if (!diff.length) {- // If the diff is empty on the first iteration, ensure we still- // notify the caller with the cached state (e.g., empty albums)+ // An empty first page must still publish the cached files.if (!callbackInvoked) {onSetFiles(files);}@@ -245,12 +150,6 @@ export const pullPublicCollectionFiles = async (}};-/**- * Fetch the public collection diff to obtain updates to the collection- * (identified by its {@link credentials}) since {@link sinceTime}.- *- * Remote only, does not modify local state.- */const getPublicCollectionDiff = async (credentials: PublicAlbumsCredentials,sinceTime: number,@@ -266,12 +165,6 @@ const getPublicCollectionDiff = async (return FileDiffResponse.parse(await res.json());};-/**- * Remove the files, sync time and accessTokenJWT associated with the given- * collection (identified by its {@link accessToken}).- *- * This function modifies local state.- */export const removePublicCollectionFileData = async (accessToken: string) => {await Promise.all([removePublicCollectionAccessTokenJWT(accessToken),diff --git a/web/apps/albums/src/public-album/data/storage/public-albums-fdb.ts b/web/apps/albums/src/public-album/data/storage/public-albums-fdb.tsindex 18a3dd0cc4..6e101b3749 100644--- a/web/apps/albums/src/public-album/data/storage/public-albums-fdb.ts+++ b/web/apps/albums/src/public-album/data/storage/public-albums-fdb.ts@@ -1,7 +1,3 @@-/**- * @file Public albums app specific files DB. See: [Note: Files DB].- */-import {LocalCollections,LocalEnteFiles,@@ -14,33 +10,14 @@ import type { EnteFile } from "ente-media/file";import { nullToUndefined } from "ente-utils/transform";import { z } from "zod";-/**- * Return all public collections present in our local database.- *- * Use {@link savePublicCollections} to update the database.- */const savedPublicCollections = async (): Promise<Collection[]> =>LocalCollections.parse((await localForage.getItem("public-collections")) ?? [],);-/**- * Replace the list of public collections stored in our local database.- *- * This is the setter corresponding to {@link savedPublicCollections}.- */const savePublicCollections = (collections: Collection[]) =>localForage.setItem("public-collections", collections);-/**- * Return the saved public collection with the given {@link key} if present in- * our local database.- *- * Use {@link savePublicCollection} to save collections in our local database.- *- * @param key The collection key that can be used to identify the public album- * we want from amongst all the locally saved public albums.- */export const savedPublicCollectionByKey = async (collectionKey: string,): Promise<Collection | undefined> =>@@ -48,12 +25,6 @@ export const savedPublicCollectionByKey = async (cs.find((c) => c.key == collectionKey),);-/**- * Save a public collection to our local database.- *- * The collection can later be retrieved using {@link savedPublicCollection}.- * The collection can be removed using {@link removePublicCollection}.- */export const savePublicCollection = async (collection: Collection) => {const collections = await savedPublicCollections();await savePublicCollections([@@ -62,13 +33,6 @@ export const savePublicCollection = async (collection: Collection) => {]);};-/**- * Remove a public collection, identified using its collection key, from our- * local database.- *- * @param key The collection key that can be used to identify the public album- * we want to remove.- */export const removePublicCollectionByKey = async (collectionKey: string) => {const collections = await savedPublicCollections();await savePublicCollections([@@ -76,35 +40,11 @@ export const removePublicCollectionByKey = async (collectionKey: string) => {]);};-/**- * Zod schema for a nullish string, with `null` transformed to `undefined`.- */const LocalString = z.string().nullish().transform(nullToUndefined);-/**- * Return the last saved referral code present in our local database.- *- * See: [Note: Public albums referral code]. A few more details specific to the- * persistence of the referral code:- *- * 1. The public albums app persists only the referral code for the latest- * public album that was fetched.- *- * 2. This saved value can be read by- * {@link savedLastPublicCollectionReferralCode}.- *- * 3. It gets updated as part of {@link publicAlbumsRemotePull}, which writes- * out a new value using {@link saveLastPublicCollectionReferralCode}.- */export const savedLastPublicCollectionReferralCode = async () =>LocalString.parse(await localForage.getItem("public-referral-code"));-/**- * Update the referral code present in our local database.- *- * This is the setter corresponding to- * {@link savedLastPublicCollectionReferralCode}.- */export const saveLastPublicCollectionReferralCode = async (referralCode: string,) => {@@ -112,11 +52,6 @@ export const saveLastPublicCollectionReferralCode = async (};const LocalSavedPublicCollectionFilesEntry = z.object({- /**- * The collection, identified by its access token.- *- * See: [Note: Public album access token]- */collectionUID: z.string(),files: LocalEnteFiles,});@@ -125,15 +60,6 @@ type LocalSavedPublicCollectionFilesEntry = z.infer<typeof LocalSavedPublicCollectionFilesEntry>;-/**- * Return all files for a public collection present in our local database.- *- * Use {@link savePublicCollectionFiles} to update the list of files in the- * database, and {@link removePublicCollectionFiles} to remove them.- *- * @param accessToken The access token that identifies the public album whose- * files we want.- */export const savedPublicCollectionFiles = async (accessToken: string,): Promise<EnteFile[]> => {@@ -143,29 +69,14 @@ export const savedPublicCollectionFiles = async (return transformFilesIfNeeded(entry ? entry.files : []);};-/**- * A convenience routine to read the DB entries for "public-collection-files".- */const pcfEntries = async () => {- // A local alias to avoid the code from looking scary.type ES = LocalSavedPublicCollectionFilesEntry[];- // See: [Note: Avoiding Zod parsing for large DB arrays] for why we use an- // (implied) cast here instead of parsing using the Zod schema.+ // Zod parsing is too slow for these large file arrays.const entries = await localForage.getItem<ES>("public-collection-files");return entries ?? [];};-/**- * Replace the list of files for a public collection in our local database.- *- * This is the setter corresponding to {@link savedPublicCollectionFiles}.- *- * @param accessToken The access token that identifies the public album whose- * files we want to update.- *- * @param files The files to save.- */export const savePublicCollectionFiles = async (accessToken: string,files: EnteFile[],@@ -176,10 +87,6 @@ export const savePublicCollectionFiles = async (]);};-/**- * Remove the list of files, in any, in our local database for the given- * collection (identified by its {@link accessToken}).- */export const removePublicCollectionFiles = async (accessToken: string,): Promise<void> => {@@ -188,27 +95,11 @@ export const removePublicCollectionFiles = async (]);};-/**- * Return the locally persisted "last sync time" for a public collection that we- * have pulled from remote. This can be used to perform a paginated delta pull- * from the saved time onwards.- *- * Use {@link savePublic CollectionLastSyncTime} to update the value saved in- * the database, and {@link removePublicCollectionLastSyncTime} to remove the- * saved value from the database.- *- * @param accessToken The access token that identifies the public album whose- * last sync time we want.- */export const savedPublicCollectionLastSyncTime = async (accessToken: string) =>LocalTimestamp.parse(await localForage.getItem(`public-${accessToken}-time`),);-/**- * Update the locally persisted timestamp that will be returned by subsequent- * calls to {@link savedPublicCollectionLastSyncTime}.- */export const savePublicCollectionLastSyncTime = async (accessToken: string,time: number,@@ -216,23 +107,12 @@ export const savePublicCollectionLastSyncTime = async (await localForage.setItem(`public-${accessToken}-time`, time);};-/**- * Remove the locally persisted timestamp, if any, previously saved for a- * collection using {@link savedPublicCollectionLastSyncTime}.- */export const removePublicCollectionLastSyncTime = async (accessToken: string,) => {await localForage.removeItem(`public-${accessToken}-time`);};-/**- * Return the access token JWT, if any, present in our local database for the- * given public collection (as identified by its {@link accessToken}).- *- * Use {@link savePublicCollectionAccessTokenJWT} to save the value, and- * {@link removePublicCollectionAccessTokenJWT} to remove it.- */export const savedPublicCollectionAccessTokenJWT = async (accessToken: string,) =>@@ -240,13 +120,6 @@ export const savedPublicCollectionAccessTokenJWT = async (await localForage.getItem(`public-${accessToken}-passkey`),);-/**- * Update the access token JWT in our local database for the given public- * collection (as identified by its {@link accessToken}).- *- * This is the setter corresponding to- * {@link savedPublicCollectionAccessTokenJWT}.- */export const savePublicCollectionAccessTokenJWT = async (accessToken: string,passwordJWT: string,@@ -254,10 +127,6 @@ export const savePublicCollectionAccessTokenJWT = async (await localForage.setItem(`public-${accessToken}-passkey`, passwordJWT);};-/**- * Remove the access token JWT in our local database for the given public- * collection (as identified by its {@link accessToken}).- */export const removePublicCollectionAccessTokenJWT = async (accessToken: string,) => {@@ -299,37 +168,11 @@ export const removePublicCollectionLinkDeviceToken = async ();};-/**- * Return the previously saved uploader name, if any, present in our local- * database corresponding to a public collection.- *- * Use {@link savePublicCollectionUploaderName} to update the persisted value.- *- * [Note: Public albums uploader name]- *- * Whenever there is an upload to a public album, we ask the person doing the- * upload for their name. This uploader name is attached as part of the public- * magic metadata of the file so that other people know who uploaded the file.- *- * The public albums app also saves this value, keyed by an identifier for the- * public collection, in the local database so that it can prefill it the next- * time there is an upload from the same client.- *- * @param accessToken The access token that identifies the public album whose- * saved uploader name we want.- */export const savedPublicCollectionUploaderName = async (accessToken: string) =>LocalString.parse(await localForage.getItem(`public-${accessToken}-uploaderName`),);-/**- * Update the uploader name present in our local database corresponding to a- * public collection.- *- * This is the setter corresponding to- * {@link savedPublicCollectionUploaderName}.- */export const savePublicCollectionUploaderName = async (accessToken: string,uploaderName: string,diff --git a/web/apps/albums/src/public-album/media/utils/sort-files.ts b/web/apps/albums/src/public-album/media/utils/sort-files.tsindex c56c1af158..ac09375a56 100644--- a/web/apps/albums/src/public-album/media/utils/sort-files.ts+++ b/web/apps/albums/src/public-album/media/utils/sort-files.ts@@ -1,22 +1,7 @@import type { EnteFile } from "ente-media/file";import { fileCreationPhotoSortTime } from "ente-media/file-metadata";-/**- * Sort the given list of {@link EnteFile}s in place.- *- * Like the JavaScript Array#sort, this method modifies the {@link files}- * argument. It sorts {@link files} in place, and then returns a reference to- * the same mutated array.- *- * By default, files are sorted so that the newest one is first. The optional- * {@link sortAsc} flag can be set to `true` to sort them so that the oldest one- * is first.- */export const sortFiles = (files: EnteFile[], sortAsc = false) => {- // Sort based on the local photo creation date shown in the UI.- //- // For files with same creation date, sort based on the time of last- // modification.const factor = sortAsc ? -1 : 1;const sortTimeByFile = new Map<EnteFile, number>();const sortTimeForFile = (file: EnteFile) => {diff --git a/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx b/web/apps/albums/src/public-album/page/PublicAlbumPage.tsxindex f334a6c42d..ed223aa66e 100644--- a/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx+++ b/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx@@ -177,7 +177,6 @@ export default function PublicAlbumPage() {useState(false);const publicFeedSidebarOpenRef = useRef(publicFeedVisibilityProps.open);- // Pending navigation from feed item clickconst [pendingFileNavigation, setPendingFileNavigation] = useState<{fileIndex: number;sidebar?: FileViewerInitialSidebar;@@ -198,26 +197,19 @@ export default function PublicAlbumPage() {}}, []);- /**- * Handle clicks on feed items to navigate to the file and open sidebar.- */const handleFeedItemClick = (info: PublicFeedItemClickInfo) => {if (!publicFiles) return;- // Find the file index in publicFilesconst fileIndex = publicFiles.findIndex((f) => f.id === info.fileID);if (fileIndex === -1) return;- // Close the feed sidebarpublicFeedVisibilityProps.onClose();- // Determine which sidebar to openconst sidebar: FileViewerInitialSidebar =info.type === "liked_photo" || info.type === "liked_video"? "likes": "comments";- // Set navigation statesetPendingFileNavigation({fileIndex,sidebar,@@ -248,11 +240,7 @@ export default function PublicAlbumPage() {cancel: false,});- /**- * Check if we need to redirect Trip albums from custom domains to albums.ente.com- * Returns true if a redirect was initiated, false otherwise.- * Reason: custom domains do not support the Trip layout fully- */+ // Ente-hosted trip albums are only fully supported on albums.ente.com.const checkAndRedirectForTripAlbum = (collection: Collection): boolean => {if (isCustomAPIOrigin ||@@ -279,10 +267,6 @@ export default function PublicAlbumPage() {};useEffect(() => {- /**- * Determine credentials, read the locally cached state, then start- * pulling the latest from remote.- */const main = async () => {let redirectingToWebsite = false;try {@@ -302,7 +286,6 @@ export default function PublicAlbumPage() {]);const ck = await extractCollectionKeyFromShareURL(currentURL);if (!accessToken && !ck) {- // Only redirect to ente.com if this is not a self-hosted instance.if (!isCustomAPIOrigin) {window.location.href = "https://ente.com";redirectingToWebsite = true;@@ -378,10 +361,6 @@ export default function PublicAlbumPage() {}}, [dragAndDropFiles.length, isUploadInProgress, uploadTypeSelectorView]);- /**- * Pull the latest data related to the public album from remote, updating- * both our local database and component state.- */const publicAlbumsRemotePull = useCallback(async () => {const accessToken = credentials.current!.accessToken;showLoadingBar();@@ -425,8 +404,6 @@ export default function PublicAlbumPage() {setIsPasswordProtected(isPasswordProtected);setErrorMessage("");- // Remove the locally cached accessTokenJWT if the sharer has- // disabled password protection on the link.if (!isPasswordProtected && credentials.current?.accessTokenJWT) {credentials.current.accessTokenJWT = undefined;setPublicAlbumsCredentials(credentials.current);@@ -446,16 +423,8 @@ export default function PublicAlbumPage() {),);} catch (e) {- // If we reached the try block and attempted to pull files,- // it means the accessToken itself is very likely valid- // (since the `pullCollection` succeeded just a moment ago).- //- // So a 401 Unauthorized now indicates that the- // accessTokenJWT is no longer valid since the sharer has- // changed the password.- //- // Clear the locally cached accessTokenJWT and ask the user- // to reenter the password.+ // Collection access already succeeded.+ // A 401 here means the password JWT is invalid.if (isHTTP401Error(e)) {credentials.current!.accessTokenJWT = undefined;setPublicAlbumsCredentials(credentials.current);@@ -466,15 +435,6 @@ export default function PublicAlbumPage() {}} catch (e) {const isDeviceLimitExceeded = await isDeviceLimitExceededError(e);- // The 410 Gone or device-limit failure can arise from either the- // collection pull or the files pull since they're part of the- // remote's access token check sequence.- //- // In practice, it almost always will be a consequence of the- // collection pull since it happens first.- //- // The 401 Unauthorized can only arise from the collection pull- // since we already handle that separately for the files pull.if (isHTTPErrorWithStatus(e, 401) ||isHTTPErrorWithStatus(e, 410) ||@@ -492,15 +452,13 @@ export default function PublicAlbumPage() {? t("link_request_limit_exceeded"): t("link_expired_message"),);- // Sharing has been disabled. Clear out local cache.await removePublicCollectionFileData(accessToken);await removePublicCollectionByKey(collectionKey.current!);setPublicCollection(undefined);setPublicFiles(undefined);} else {log.error("Public album remote pull failed", e);- // Don't use the `setErrorMessage`, show a dialog instead,- // because this might be a transient network error.+ // Preserve cached state because this failure may be transient.onGenericError(e);}} finally {@@ -511,7 +469,7 @@ export default function PublicAlbumPage() {}}, [showLoadingBar, hideLoadingBar, onGenericError]);- // See: [Note: Visual feedback to acknowledge user actions]+ // Briefly show the loading bar when an action has no other visible effect.const handleVisualFeedback = useCallback(() => {showLoadingBar();setTimeout(hideLoadingBar, 0);@@ -885,10 +843,6 @@ export default function PublicAlbumPage() {);}-/**- * Sort the given {@link files} using {@link sortFiles}, using the ascending- * ordering preference if specified in the given {@link collection}'s metadata.- */const sortFilesForCollection = (files: EnteFile[], collection?: Collection) =>sortFiles(files, collection?.pubMagicMetadata?.data.asc ?? false);@@ -1022,7 +976,6 @@ const LazyCollectDropZone: React.FC<LazyCollectDropZoneProps> = ({};const EnteLogoLink = styled("a")(({ theme }) => ({- // Remove the excess space at the top.svg: { verticalAlign: "middle" },color: theme.vars.palette.text.base,":hover": { color: theme.vars.palette.accent.main },@@ -1152,24 +1105,10 @@ interface FileListHeaderProps {showMobileMasonryCover: boolean;}-/**- * The fixed height (in px) of {@link FileListHeader}.- */const fileListHeaderHeight = 84;-/**- * The height (in px) of {@link FileListHeader} on mobile.- *- * Keep this fixed so the virtualized list has a stable header row height.- */const fileListHeaderHeightMobile = 132;-/**- * A header shown before the listing of files.- *- * It scrolls along with the content. It has a fixed height,- * {@link fileListHeaderHeight}.- */const FileListHeader: React.FC<FileListHeaderProps> = ({publicCollection,publicFiles,@@ -1712,22 +1651,10 @@ const MobileMasonryCoverTitle = styled(Typography)({overflowWrap: "anywhere",});-/**- * The default height (in px) of {@link FileListFooter}.- */const fileListFooterHeight = 24;-/**- * The compact trailing gap used after the final photo in the mobile masonry- * cover layout.- */const mobileMasonryFileListFooterHeight = thumbnailGap;-/**- * A footer shown after the listing of files.- *- * It scrolls along with the content.- */const FileListFooter: React.FC<{ height: number }> = ({ height }) => (<Box sx={{ height }} />);