π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
create separate photoList page for dedupe
Abhinav6ac91607f98a
diff --git a/apps/photos/src/components/PhotoFrame.tsx b/apps/photos/src/components/PhotoFrame.tsxindex de0a032361..c4f689f1b9 100644--- a/apps/photos/src/components/PhotoFrame.tsx+++ b/apps/photos/src/components/PhotoFrame.tsx@@ -8,7 +8,6 @@ import AutoSizer from 'react-virtualized-auto-sizer';import PhotoViewer from 'components/PhotoViewer';import { TRASH_SECTION } from 'constants/collection';import { updateFileMsrcProps, updateFileSrcProps } from 'utils/photoFrame';-import { PhotoList } from './PhotoList';import { MergedSourceURL, SelectedState } from 'types/gallery';import PublicCollectionDownloadManager from 'services/publicCollectionDownloadManager';import { PublicCollectionGalleryContext } from 'utils/publicCollectionGallery';@@ -19,6 +18,10 @@ import PhotoSwipe from 'photoswipe';import useMemoSingleThreaded from '@ente/shared/hooks/useMemoSingleThreaded';import { getPlayableVideo } from 'utils/file';import { FILE_TYPE } from 'constants/file';+import { PHOTOS_PAGES } from '@ente/shared/constants/pages';+import { PhotoList } from './PhotoList';+import { DedupePhotoList } from './PhotoList/dedupe';+import { Duplicate } from 'services/deduplicationService';const Container = styled('div')`display: block;@@ -36,7 +39,12 @@ const Container = styled('div')`const PHOTOSWIPE_HASH_SUFFIX = '&opened';interface Props {+ page:+ | PHOTOS_PAGES.GALLERY+ | PHOTOS_PAGES.DEDUPLICATE+ | PHOTOS_PAGES.SHARED_ALBUMS;files: EnteFile[];+ duplicates?: Duplicate[];syncWithRemote: () => Promise<void>;favItemIds?: Set<number>;setSelected: (@@ -55,6 +63,8 @@ interface Props {}const PhotoFrame = ({+ page,+ duplicates,files,syncWithRemote,favItemIds,@@ -605,16 +615,27 @@ const PhotoFrame = ({return (<Container><AutoSizer>- {({ height, width }) => (- <PhotoList- width={width}- height={height}- getThumbnail={getThumbnail}- displayFiles={displayFiles}- activeCollectionID={activeCollectionID}- showAppDownloadBanner={showAppDownloadBanner}- />- )}+ {({ height, width }) =>+ page === PHOTOS_PAGES.DEDUPLICATE ? (+ <DedupePhotoList+ width={width}+ height={height}+ getThumbnail={getThumbnail}+ duplicates={duplicates}+ activeCollectionID={activeCollectionID}+ showAppDownloadBanner={showAppDownloadBanner}+ />+ ) : (+ <PhotoList+ width={width}+ height={height}+ getThumbnail={getThumbnail}+ displayFiles={displayFiles}+ activeCollectionID={activeCollectionID}+ showAppDownloadBanner={showAppDownloadBanner}+ />+ )+ }</AutoSizer><PhotoViewerisOpen={open}diff --git a/apps/photos/src/components/PhotoList/dedupe.tsx b/apps/photos/src/components/PhotoList/dedupe.tsxnew file mode 100644index 0000000000..94cadb802b--- /dev/null+++ b/apps/photos/src/components/PhotoList/dedupe.tsx@@ -0,0 +1,355 @@+import React, { useRef, useEffect, useState } from 'react';+import {+ VariableSizeList as List,+ ListChildComponentProps,+ areEqual,+} from 'react-window';+import { Box, styled } from '@mui/material';+import { EnteFile } from 'types/file';+import {+ IMAGE_CONTAINER_MAX_HEIGHT,+ MIN_COLUMNS,+ DATE_CONTAINER_HEIGHT,+ GAP_BTW_TILES,+ SPACE_BTW_DATES,+ SIZE_AND_COUNT_CONTAINER_HEIGHT,+ IMAGE_CONTAINER_MAX_WIDTH,+} from 'constants/gallery';+import { convertBytesToHumanReadable } from '@ente/shared/utils/size';+import { FlexWrapper } from '@ente/shared/components/Container';+import { t } from 'i18next';+import memoize from 'memoize-one';+import { Duplicate } from 'services/deduplicationService';++export enum ITEM_TYPE {+ TIME = 'TIME',+ FILE = 'FILE',+ SIZE_AND_COUNT = 'SIZE_AND_COUNT',+ HEADER = 'HEADER',+ FOOTER = 'FOOTER',+ MARKETING_FOOTER = 'MARKETING_FOOTER',+ OTHER = 'OTHER',+}++export interface TimeStampListItem {+ itemType: ITEM_TYPE;+ items?: EnteFile[];+ itemStartIndex?: number;+ date?: string;+ dates?: {+ date: string;+ span: number;+ }[];+ groups?: number[];+ item?: any;+ id?: string;+ height?: number;+ fileSize?: number;+ fileCount?: number;+}++const ListItem = styled('div')`+ display: flex;+ justify-content: center;+`;++const getTemplateColumns = (+ columns: number,+ shrinkRatio: number,+ groups?: number[]+): string => {+ if (groups) {+ // need to confirm why this was there+ // const sum = groups.reduce((acc, item) => acc + item, 0);+ // if (sum < columns) {+ // groups[groups.length - 1] += columns - sum;+ // }+ return groups+ .map(+ (x) =>+ `repeat(${x}, ${IMAGE_CONTAINER_MAX_WIDTH * shrinkRatio}px)`+ )+ .join(` ${SPACE_BTW_DATES}px `);+ } else {+ return `repeat(${columns},${+ IMAGE_CONTAINER_MAX_WIDTH * shrinkRatio+ }px)`;+ }+};++function getFractionFittableColumns(width: number): number {+ return (+ (width - 2 * getGapFromScreenEdge(width) + GAP_BTW_TILES) /+ (IMAGE_CONTAINER_MAX_WIDTH + GAP_BTW_TILES)+ );+}++function getGapFromScreenEdge(width: number) {+ if (width > MIN_COLUMNS * IMAGE_CONTAINER_MAX_WIDTH) {+ return 24;+ } else {+ return 4;+ }+}++function getShrinkRatio(width: number, columns: number) {+ return (+ (width -+ 2 * getGapFromScreenEdge(width) -+ (columns - 1) * GAP_BTW_TILES) /+ (columns * IMAGE_CONTAINER_MAX_WIDTH)+ );+}++const ListContainer = styled(Box)<{+ columns: number;+ shrinkRatio: number;+ groups?: number[];+}>`+ display: grid;+ grid-template-columns: ${({ columns, shrinkRatio, groups }) =>+ getTemplateColumns(columns, shrinkRatio, groups)};+ grid-column-gap: ${GAP_BTW_TILES}px;+ width: 100%;+ color: #fff;+ padding: 0 24px;+ @media (max-width: ${IMAGE_CONTAINER_MAX_WIDTH * MIN_COLUMNS}px) {+ padding: 0 4px;+ }+`;++const ListItemContainer = styled(FlexWrapper)<{ span: number }>`+ grid-column: span ${(props) => props.span};+`;++const DateContainer = styled(ListItemContainer)`+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ height: ${DATE_CONTAINER_HEIGHT}px;+ color: ${({ theme }) => theme.colors.text.muted};+`;++const SizeAndCountContainer = styled(DateContainer)`+ margin-top: 1rem;+ height: ${SIZE_AND_COUNT_CONTAINER_HEIGHT}px;+`;++interface Props {+ height: number;+ width: number;+ duplicates: Duplicate[];+ showAppDownloadBanner: boolean;+ getThumbnail: (+ file: EnteFile,+ index: number,+ isScrolling?: boolean+ ) => JSX.Element;+ activeCollectionID: number;+}++interface ItemData {+ timeStampList: TimeStampListItem[];+ columns: number;+ shrinkRatio: number;+ renderListItem: (+ timeStampListItem: TimeStampListItem,+ isScrolling?: boolean+ ) => JSX.Element;+}++const createItemData = memoize(+ (+ timeStampList: TimeStampListItem[],+ columns: number,+ shrinkRatio: number,+ renderListItem: (+ timeStampListItem: TimeStampListItem,+ isScrolling?: boolean+ ) => JSX.Element+ ): ItemData => ({+ timeStampList,+ columns,+ shrinkRatio,+ renderListItem,+ })+);+const PhotoListRow = React.memo(+ ({+ index,+ style,+ isScrolling,+ data,+ }: ListChildComponentProps<ItemData>) => {+ const { timeStampList, columns, shrinkRatio, renderListItem } = data;+ return (+ <ListItem style={style}>+ <ListContainer+ columns={columns}+ shrinkRatio={shrinkRatio}+ groups={timeStampList[index].groups}>+ {renderListItem(timeStampList[index], isScrolling)}+ </ListContainer>+ </ListItem>+ );+ },+ areEqual+);++const getTimeStampListFromDuplicates = (duplicates: Duplicate[]) => {+ const timeStampList: TimeStampListItem[] = [];+ for (let index = 0; index < duplicates.length; index++) {+ const dupes = duplicates[index];+ timeStampList.push({+ itemType: ITEM_TYPE.SIZE_AND_COUNT,+ fileSize: dupes.size,+ fileCount: dupes.files.length,+ });+ timeStampList.push({+ itemType: ITEM_TYPE.FILE,+ items: dupes.files,+ itemStartIndex: index,+ });+ }+ return timeStampList;+};++export function DedupePhotoList({+ height,+ width,+ duplicates,+ getThumbnail,+ activeCollectionID,+}: Props) {+ const [timeStampList, setTimeStampList] = useState<TimeStampListItem[]>([]);+ const refreshInProgress = useRef(false);+ const shouldRefresh = useRef(false);+ const listRef = useRef(null);++ const fittableColumns = getFractionFittableColumns(width);+ let columns = Math.floor(fittableColumns);++ if (columns < MIN_COLUMNS) {+ columns = MIN_COLUMNS;+ }+ const shrinkRatio = getShrinkRatio(width, columns);+ const listItemHeight =+ IMAGE_CONTAINER_MAX_HEIGHT * shrinkRatio + GAP_BTW_TILES;++ const refreshList = () => {+ listRef.current?.resetAfterIndex(0);+ };++ useEffect(() => {+ const main = () => {+ if (refreshInProgress.current) {+ shouldRefresh.current = true;+ return;+ }+ refreshInProgress.current = true;+ const timeStampList = getTimeStampListFromDuplicates(duplicates);+ setTimeStampList(timeStampList);+ refreshInProgress.current = false;+ if (shouldRefresh.current) {+ shouldRefresh.current = false;+ setTimeout(main, 0);+ }+ };+ main();+ }, [width, height, duplicates]);++ useEffect(() => {+ refreshList();+ }, [timeStampList]);++ const getItemSize = (timeStampList) => (index) => {+ switch (timeStampList[index].itemType) {+ case ITEM_TYPE.TIME:+ return DATE_CONTAINER_HEIGHT;+ case ITEM_TYPE.SIZE_AND_COUNT:+ return SIZE_AND_COUNT_CONTAINER_HEIGHT;+ case ITEM_TYPE.FILE:+ return listItemHeight;+ default:+ return timeStampList[index].height;+ }+ };++ const generateKey = (index) => {+ switch (timeStampList[index].itemType) {+ case ITEM_TYPE.FILE:+ return `${timeStampList[index].items[0].id}-${+ timeStampList[index].items.slice(-1)[0].id+ }`;+ default:+ return `${timeStampList[index].id}-${index}`;+ }+ };++ const renderListItem = (+ listItem: TimeStampListItem,+ isScrolling: boolean+ ) => {+ switch (listItem.itemType) {+ case ITEM_TYPE.SIZE_AND_COUNT:+ return (+ <SizeAndCountContainer span={columns}>+ {listItem.fileCount} {t('FILES')},{' '}+ {convertBytesToHumanReadable(listItem.fileSize || 0)}{' '}+ {t('EACH')}+ </SizeAndCountContainer>+ );+ case ITEM_TYPE.FILE: {+ const ret = listItem.items.map((item, idx) =>+ getThumbnail(+ item,+ listItem.itemStartIndex + idx,+ isScrolling+ )+ );+ if (listItem.groups) {+ let sum = 0;+ for (let i = 0; i < listItem.groups.length - 1; i++) {+ sum = sum + listItem.groups[i];+ ret.splice(+ sum,+ 0,+ <div key={`${listItem.items[0].id}-gap-${i}`} />+ );+ sum += 1;+ }+ }+ return ret;+ }+ default:+ return listItem.item;+ }+ };++ if (!timeStampList?.length) {+ return <></>;+ }++ const itemData = createItemData(+ timeStampList,+ columns,+ shrinkRatio,+ renderListItem+ );++ return (+ <List+ key={`${activeCollectionID}`}+ itemData={itemData}+ ref={listRef}+ itemSize={getItemSize(timeStampList)}+ height={height}+ width={width}+ itemCount={timeStampList.length}+ itemKey={generateKey}+ overscanCount={3}+ useIsScrolling>+ {PhotoListRow}+ </List>+ );+}diff --git a/apps/photos/src/components/PhotoList.tsx b/apps/photos/src/components/PhotoList/index.tsxsimilarity index 100%rename from apps/photos/src/components/PhotoList.tsxrename to apps/photos/src/components/PhotoList/index.tsxdiff --git a/apps/photos/src/pages/deduplicate/index.tsx b/apps/photos/src/pages/deduplicate/index.tsxindex f4369682a6..16bbc02597 100644--- a/apps/photos/src/pages/deduplicate/index.tsx+++ b/apps/photos/src/pages/deduplicate/index.tsx@@ -5,11 +5,11 @@ import { ALL_SECTION } from 'constants/collection';import { AppContext } from 'pages/_app';import { createContext, useContext, useEffect, useState } from 'react';import {- getDuplicateFiles,- clubDuplicatesByTime,+ getDuplicates,+ deClubDuplicatesWithDifferentTime,+ Duplicate,} from 'services/deduplicationService';import { syncFiles, trashFiles } from 'services/fileService';-import { EnteFile } from 'types/file';import { SelectedState } from 'types/gallery';import { ApiError } from '@ente/shared/error';@@ -43,7 +43,7 @@ export const Info = styled('div')`export default function Deduplicate() {const { setDialogMessage, startLoading, finishLoading, showNavBar } =useContext(AppContext);- const [duplicateFiles, setDuplicateFiles] = useState<EnteFile[]>(null);+ const [duplicates, setDuplicates] = useState<Duplicate[]>(null);const [clubSameTimeFilesOnly, setClubSameTimeFilesOnly] = useState(false);const [fileSizeMap, setFileSizeMap] = useState(new Map<number, number>());const [collectionNameMap, setCollectionNameMap] = useState(@@ -71,6 +71,12 @@ export default function Deduplicate() {syncWithRemote();}, [clubSameTimeFilesOnly]);+ const duplicateFiles = useMemoSingleThreaded(() => {+ return (duplicates ?? []).reduce((acc, dupe) => {+ return [...acc, ...dupe.files];+ }, []);+ }, [duplicates]);+const fileToCollectionsMap = useMemoSingleThreaded(() => {return constructFileToCollectionMap(duplicateFiles);}, [duplicateFiles]);@@ -84,16 +90,14 @@ export default function Deduplicate() {}setCollectionNameMap(collectionNameMap);const files = await syncFiles('normal', collections, () => null);- let duplicates = await getDuplicateFiles(files, collectionNameMap);+ let duplicateFiles = await getDuplicates(files, collectionNameMap);if (clubSameTimeFilesOnly) {- duplicates = clubDuplicatesByTime(duplicates);+ duplicateFiles = deClubDuplicatesWithDifferentTime(duplicateFiles);}const currFileSizeMap = new Map<number, number>();- let allDuplicateFiles: EnteFile[] = [];let toSelectFileIDs: number[] = [];let count = 0;- for (const dupe of duplicates) {- allDuplicateFiles = [...allDuplicateFiles, ...dupe.files];+ for (const dupe of duplicateFiles) {// select all except first filetoSelectFileIDs = [...toSelectFileIDs,@@ -105,7 +109,7 @@ export default function Deduplicate() {currFileSizeMap.set(file.id, dupe.size);}}- setDuplicateFiles(allDuplicateFiles);+ setDuplicates(duplicateFiles);setFileSizeMap(currFileSizeMap);const selectedFiles = {count: count,@@ -153,7 +157,7 @@ export default function Deduplicate() {setSelected({ count: 0, collectionID: 0, ownCount: 0 });};- if (!duplicateFiles) {+ if (!duplicates) {return (<VerticallyCentered><EnteSpinner />@@ -171,7 +175,7 @@ export default function Deduplicate() {fileSizeMap,isOnDeduplicatePage: true,}}>- {duplicateFiles.length > 0 && (+ {duplicates.length > 0 && (<Info>{t('DEDUPLICATE_BASED_ON', {context: clubSameTimeFilesOnly@@ -180,7 +184,7 @@ export default function Deduplicate() {})}</Info>)}- {duplicateFiles.length === 0 ? (+ {duplicates.length === 0 ? (<VerticallyCentered><Typography variant="large" color="text.muted">{t('NO_DUPLICATES_FOUND')}@@ -188,7 +192,9 @@ export default function Deduplicate() {</VerticallyCentered>) : (<PhotoFrame+ page={PAGES.DEDUPLICATE}files={duplicateFiles}+ duplicates={duplicates}syncWithRemote={syncWithRemote}setSelected={setSelected}selected={selected}diff --git a/apps/photos/src/pages/gallery/index.tsx b/apps/photos/src/pages/gallery/index.tsxindex 1eeb3e165b..22b4c8e2b3 100644--- a/apps/photos/src/pages/gallery/index.tsx+++ b/apps/photos/src/pages/gallery/index.tsx@@ -1096,6 +1096,7 @@ export default function Gallery() {<GalleryEmptyState openUploader={openUploader} />) : (<PhotoFrame+ page={PAGES.GALLERY}files={filteredData}syncWithRemote={syncWithRemote}favItemIds={favItemIds}diff --git a/apps/photos/src/pages/shared-albums/index.tsx b/apps/photos/src/pages/shared-albums/index.tsxindex 22b37fc818..1131d69ea8 100644--- a/apps/photos/src/pages/shared-albums/index.tsx+++ b/apps/photos/src/pages/shared-albums/index.tsx@@ -463,6 +463,7 @@ export default function PublicCollectionGallery() {openUploader={openUploader}/><PhotoFrame+ page={PAGES.SHARED_ALBUMS}files={publicFiles}syncWithRemote={syncWithRemote}setSelected={() => null}diff --git a/apps/photos/src/services/deduplicationService.ts b/apps/photos/src/services/deduplicationService.tsindex 137e30a26b..0203343caa 100644--- a/apps/photos/src/services/deduplicationService.ts+++ b/apps/photos/src/services/deduplicationService.ts@@ -16,12 +16,12 @@ interface DuplicatesResponse {}>;}-interface DuplicateFiles {+export interface Duplicate {files: EnteFile[];size: number;}-export async function getDuplicateFiles(+export async function getDuplicates(files: EnteFile[],collectionNameMap: Map<number, string>) {@@ -33,7 +33,7 @@ export async function getDuplicateFiles(fileMap.set(file.id, file);}- let result: DuplicateFiles[] = [];+ let result: Duplicate[] = [];for (const dupe of dupes) {let duplicateFiles: EnteFile[] = [];@@ -64,8 +64,8 @@ export async function getDuplicateFiles(}}-function getDupesGroupedBySameFileHashes(dupe: DuplicateFiles) {- const result: DuplicateFiles[] = [];+function getDupesGroupedBySameFileHashes(dupe: Duplicate) {+ const result: Duplicate[] = [];const fileWithHashes: EnteFile[] = [];const fileWithoutHashes: EnteFile[] = [];@@ -95,8 +95,8 @@ function getDupesGroupedBySameFileHashes(dupe: DuplicateFiles) {return result;}-function groupDupesByFileHashes(dupe: DuplicateFiles) {- const result: DuplicateFiles[] = [];+function groupDupesByFileHashes(dupe: Duplicate) {+ const result: Duplicate[] = [];const filesSortedByFileHash = dupe.files.map((file) => {@@ -141,8 +141,8 @@ function groupDupesByFileHashes(dupe: DuplicateFiles) {return result;}-export function clubDuplicatesByTime(dupes: DuplicateFiles[]) {- const result: DuplicateFiles[] = [];+export function deClubDuplicatesWithDifferentTime(dupes: Duplicate[]) {+ const result: Duplicate[] = [];for (const dupe of dupes) {let files: EnteFile[] = [];const creationTimeCounter = new Map<number, number>();