π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
remove context thumb and file cache and remove use of mergedURLs
Abhinav33b85d6a8dae
diff --git a/apps/photos/src/components/Collections/CollectionCard.tsx b/apps/photos/src/components/Collections/CollectionCard.tsxindex 62c4efb6a6..e4a1d2f0fb 100644--- a/apps/photos/src/components/Collections/CollectionCard.tsx+++ b/apps/photos/src/components/Collections/CollectionCard.tsx@@ -1,11 +1,8 @@-import React from 'react';-import { GalleryContext } from 'pages/gallery';-import { useState, useContext, useEffect } from 'react';+import { useState, useEffect } from 'react';import downloadManager from 'services/downloadManager';import { EnteFile } from 'types/file';import { StaticThumbnail } from 'components/PlaceholderThumbnails';import { LoadingThumbnail } from 'components/PlaceholderThumbnails';-import { PublicCollectionGalleryContext } from 'utils/publicCollectionGallery';export default function CollectionCard(props: {children?: any;@@ -23,28 +20,14 @@ export default function CollectionCard(props: {} = props;const [coverImageURL, setCoverImageURL] = useState(null);- const galleryContext = useContext(GalleryContext);- const publicCollectionGalleryContext = useContext(- PublicCollectionGalleryContext- );-- const thumbsStore = publicCollectionGalleryContext?.accessedThroughSharedURL- ? publicCollectionGalleryContext.thumbs- : galleryContext.thumbs;useEffect(() => {const main = async () => {if (!file) {return;}- if (!thumbsStore.has(file.id)) {- if (isScrolling) {- return;- }- const url = await downloadManager.getThumbnailForPreview(file);- thumbsStore.set(file.id, url);- }- setCoverImageURL(thumbsStore.get(file.id));+ const url = await downloadManager.getThumbnailForPreview(file);+ setCoverImageURL(url);};main();}, [file, isScrolling]);diff --git a/apps/photos/src/components/PhotoFrame.tsx b/apps/photos/src/components/PhotoFrame.tsxindex 118faea309..61dd802709 100644--- a/apps/photos/src/components/PhotoFrame.tsx+++ b/apps/photos/src/components/PhotoFrame.tsx@@ -3,20 +3,19 @@ import PreviewCard from './pages/gallery/PreviewCard';import { useContext, useEffect, useState } from 'react';import { EnteFile } from 'types/file';import { styled } from '@mui/material';-import DownloadManager from 'services/downloadManager';+import DownloadManager, { SourceURLs } from 'services/downloadManager';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 { SelectedState } from 'types/gallery';import { PublicCollectionGalleryContext } from 'utils/publicCollectionGallery';import { useRouter } from 'next/router';import { logError } from '@ente/shared/sentry';import { addLogLine } from '@ente/shared/logging';import PhotoSwipe from 'photoswipe';import useMemoSingleThreaded from '@ente/shared/hooks/useMemoSingleThreaded';-import { getPlayableVideo } from 'utils/file';import { FILE_TYPE } from 'constants/file';const Container = styled('div')`@@ -81,14 +80,6 @@ const PhotoFrame = ({const [isShiftKeyPressed, setIsShiftKeyPressed] = useState(false);const router = useRouter();- const thumbsStore = publicCollectionGalleryContext?.accessedThroughSharedURL- ? publicCollectionGalleryContext.thumbs- : galleryContext.thumbs;-- const filesStore = publicCollectionGalleryContext?.accessedThroughSharedURL- ? publicCollectionGalleryContext.files- : galleryContext.files;-const displayFiles = useMemoSingleThreaded(() => {return files.map((item) => {const filteredItem = {@@ -97,16 +88,16 @@ const PhotoFrame = ({h: window.innerHeight,title: item.pubMagicMetadata?.data.caption,};- try {- if (thumbsStore.has(item.id)) {- updateFileMsrcProps(filteredItem, thumbsStore.get(item.id));- }- if (filesStore.has(item.id)) {- updateFileSrcProps(filteredItem, filesStore.get(item.id));- }- } catch (e) {- logError(e, 'PhotoFrame url prefill failed');- }+ // try {+ // if (thumbsStore.has(item.id)) {+ // updateFileMsrcProps(filteredItem, thumbsStore.get(item.id));+ // }+ // if (filesStore.has(item.id)) {+ // updateFileSrcProps(filteredItem, filesStore.get(item.id));+ // }+ // } catch (e) {+ // logError(e, 'PhotoFrame url prefill failed');+ // }return filteredItem;});}, [files]);@@ -203,7 +194,7 @@ const PhotoFrame = ({const updateSrcURL = async (index: number,id: number,- mergedSrcURL: MergedSourceURL,+ srcURLs: SourceURLs,forceUpdate?: boolean) => {const file = displayFiles[index];@@ -238,7 +229,7 @@ const PhotoFrame = ({return;}- await updateFileSrcProps(file, mergedSrcURL);+ await updateFileSrcProps(file, srcURLs);};const handleClose = (needUpdate) => {@@ -423,27 +414,10 @@ const PhotoFrame = ({try {addLogLine(`[${item.id}] new file src request`);fetching[item.id] = true;- let srcURL: MergedSourceURL;- if (filesStore.has(item.id)) {- addLogLine(- `[${item.id}] gallery context cache hit, using cached file`- );- srcURL = filesStore.get(item.id);- } else {- addLogLine(- `[${item.id}] gallery context cache miss, calling downloadManager to get file`- );- const downloadedURL = await DownloadManager.getFileForPreview(- item- );- const mergedURL: MergedSourceURL = {- original: downloadedURL.original.join(','),- converted: downloadedURL.converted.join(','),- };- filesStore.set(item.id, mergedURL);- srcURL = mergedURL;- }- await updateSrcURL(index, item.id, srcURL);++ const srcURLs = await DownloadManager.getFileForPreview(item);++ await updateSrcURL(index, item.id, srcURLs);try {addLogLine(@@ -506,44 +480,8 @@ const PhotoFrame = ({`[${item.id}] new file getConvertedVideo request- ${item.metadata.title}}`);fetching[item.id] = true;- if (!filesStore.has(item.id)) {- addLogLine(- `[${item.id}] getConvertedVideo called for file that is not downloaded`- );- logError(- new Error(),- 'getConvertedVideo called for file that is not downloaded'- );- // this should never happen, convert video button should not be visible if file is not downloaded- return;- }-- const srcURL = filesStore.get(item.id);- let originalVideoURL;- if (item.metadata.fileType === FILE_TYPE.VIDEO) {- originalVideoURL = srcURL.original;- } else {- originalVideoURL = srcURL.original.split(',')[1];- }- const playableVideo = await getPlayableVideo(- item.metadata.title,- await (await fetch(originalVideoURL)).blob(),- true- );- const convertedVideoURL = playableVideo- ? URL.createObjectURL(playableVideo)- : '';- if (item.metadata.fileType === FILE_TYPE.VIDEO) {- srcURL.converted = convertedVideoURL;- } else {- const prvConvertedImageURL = srcURL.converted.split(',')[0];- srcURL.converted = [- prvConvertedImageURL,- convertedVideoURL,- ].join(',');- }- filesStore.set(item.id, srcURL);+ const srcURL = await DownloadManager.getFileForPreview(item, true);await updateSrcURL(index, item.id, srcURL, true);diff --git a/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/index.tsx b/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/index.tsxindex 5c22889619..fbce6c71d9 100644--- a/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/index.tsx+++ b/apps/photos/src/components/PhotoViewer/ImageEditorOverlay/index.tsx@@ -210,14 +210,13 @@ const ImageEditorOverlay = (props: IProps) => {const ctx = canvasRef.current.getContext('2d');ctx.imageSmoothingEnabled = false;if (!fileURL) {- const { converted } = await downloadManager.getFileForPreview(+ const srcURLs = await downloadManager.getFileForPreview(props.file);- img.src = converted[0];- setFileURL(converted[0]);- } else {- img.src = fileURL;+ img.src = srcURLs.url as string;+ setFileURL(fileURL);}+ img.src = fileURL;await new Promise((resolve, reject) => {img.onload = () => {diff --git a/apps/photos/src/pages/gallery/index.tsx b/apps/photos/src/pages/gallery/index.tsxindex 0c0b853ae6..ed832f085d 100644--- a/apps/photos/src/pages/gallery/index.tsx+++ b/apps/photos/src/pages/gallery/index.tsx@@ -142,8 +142,6 @@ export const DeadCenter = styled('div')``;const defaultGalleryContext: GalleryContextType = {- thumbs: new Map(),- files: new Map(),showPlanSelectorModal: () => null,setActiveCollectionID: () => null,syncWithRemote: () => null,diff --git a/apps/photos/src/pages/shared-albums/index.tsx b/apps/photos/src/pages/shared-albums/index.tsxindex 775f799910..ca0ee46c18 100644--- a/apps/photos/src/pages/shared-albums/index.tsx+++ b/apps/photos/src/pages/shared-albums/index.tsx@@ -61,9 +61,6 @@ import { ENTE_WEBSITE_LINK } from '@ente/shared/constants/urls';import { APPS } from '@ente/shared/apps/constants';import downloadManager from 'services/downloadManager';-const defaultThumbStore = new Map();-const defaultFileStore = new Map();-export default function PublicCollectionGallery() {const token = useRef<string>(null);// passwordJWTToken refers to the jwt token which is used for album protected by password.@@ -447,8 +444,6 @@ export default function PublicCollectionGallery() {accessedThroughSharedURL: true,photoListHeader,photoListFooter,- thumbs: defaultThumbStore,- files: defaultFileStore,}}><FullScreenDropZonegetDragAndDropRootProps={getDragAndDropRootProps}>diff --git a/apps/photos/src/services/downloadManager.ts b/apps/photos/src/services/downloadManager.tsindex d49cb8b72a..54b62cd5e4 100644--- a/apps/photos/src/services/downloadManager.ts+++ b/apps/photos/src/services/downloadManager.ts@@ -19,8 +19,14 @@ import { PhotosDownloadClient } from './downloadManagerClients/photos';import { PublicAlbumsDownloadClient } from './downloadManagerClients/publicAlbums';export type SourceURLs = {- original: string[];- converted: string[];+ url:+ | {+ image: string;+ video: string;+ }+ | string;+ isOriginal: boolean;+ isRenderable: boolean;};export type OnDownloadProgress = (event: {@@ -48,6 +54,7 @@ class DownloadManager {private cryptoWorker: Remote<DedicatedCryptoWorker>;private fileObjectURLPromises = new Map<number, Promise<SourceURLs>>();+ private fileConversionPromises = new Map<number, Promise<SourceURLs>>();private thumbnailObjectURLPromises = new Map<number, Promise<string>>();private fileDownloadProgress = new Map<number, number>();@@ -142,28 +149,75 @@ class DownloadManager {}}- getFileForPreview = async (file: EnteFile): Promise<SourceURLs> => {+ getFileForPreview = async (+ file: EnteFile,+ forceConvert = false+ ): Promise<SourceURLs> => {try {- const getFilePromise = async () => {- const fileStream = await this.downloadFile(file);- const fileBlob = await new Response(fileStream).blob();- return await getRenderableFileURL(file, fileBlob);+ const getFileForPreviewPromise = async () => {+ const fileBlob = await new Response(+ await this.getFile(file, true)+ ).blob();+ const fileOriginalURL = URL.createObjectURL(fileBlob);++ const converted = await getRenderableFileURL(+ file,+ fileBlob,+ fileOriginalURL as string,+ forceConvert+ );+ return converted;};- if (!this.fileObjectURLPromises.get(file.id)) {- const fileURLs = getFilePromise() as Promise<SourceURLs>;- this.fileObjectURLPromises.set(file.id, fileURLs);+ if (!this.fileConversionPromises.has(file.id)) {+ const fileURLs =+ getFileForPreviewPromise() as Promise<SourceURLs>;+ this.fileConversionPromises.set(file.id, fileURLs);}- const fileURLs = await this.fileObjectURLPromises.get(file.id);+ const fileURLs = await this.fileConversionPromises.get(file.id);return fileURLs;} catch (e) {this.fileObjectURLPromises.delete(file.id);- logError(e, 'download manager Failed to get File');+ logError(e, 'download manager getFileForPreview Failed');throw e;}};- getFile(file: EnteFile) {- return this.downloadFile(file);+ async getFile(+ file: EnteFile,+ useCache = false+ ): Promise<ReadableStream<Uint8Array>> {+ try {+ if (!useCache) {+ return await this.downloadFile(file);+ }+ const getFilePromise = async (): Promise<SourceURLs> => {+ const fileStream = await this.downloadFile(file);+ const fileBlob = await new Response(fileStream).blob();+ return {+ url: URL.createObjectURL(fileBlob),+ isOriginal: true,+ isRenderable: false,+ };+ };++ if (this.fileObjectURLPromises.has(file.id)) {+ const fileURLs = await this.fileObjectURLPromises.get(file.id);+ if (fileURLs.isOriginal) {+ const fileStream = (await fetch(fileURLs.url as string))+ .body;+ return fileStream;+ } else {+ return await this.downloadFile(file);+ }+ } else {+ const fileURLs = getFilePromise();+ this.fileObjectURLPromises.set(file.id, fileURLs);+ }+ } catch (e) {+ this.fileObjectURLPromises.delete(file.id);+ logError(e, 'download manager getFile Failed');+ throw e;+ }}private async downloadFile(diff --git a/apps/photos/src/types/gallery/index.ts b/apps/photos/src/types/gallery/index.tsindex 84892026c5..f7f4fef274 100644--- a/apps/photos/src/types/gallery/index.ts+++ b/apps/photos/src/types/gallery/index.ts@@ -31,8 +31,6 @@ export enum UploadTypeSelectorIntent {collectPhotos,}export type GalleryContextType = {- thumbs: Map<number, string>;- files: Map<number, MergedSourceURL>;showPlanSelectorModal: () => void;setActiveCollectionID: (collectionID: number) => void;syncWithRemote: (force?: boolean, silent?: boolean) => Promise<void>;diff --git a/apps/photos/src/types/publicCollection/index.ts b/apps/photos/src/types/publicCollection/index.tsindex 3c82475cac..dca173904a 100644--- a/apps/photos/src/types/publicCollection/index.ts+++ b/apps/photos/src/types/publicCollection/index.ts@@ -2,7 +2,6 @@ import { TimeStampListItem } from 'components/PhotoList';import { REPORT_REASON } from 'constants/publicCollection';import { PublicURL } from 'types/collection';import { EnteFile } from 'types/file';-import { MergedSourceURL } from 'types/gallery';export interface PublicCollectionGalleryContextType {token: string;@@ -11,8 +10,6 @@ export interface PublicCollectionGalleryContextType {accessedThroughSharedURL: boolean;photoListHeader: TimeStampListItem;photoListFooter: TimeStampListItem;- thumbs: Map<number, string>;- files: Map<number, MergedSourceURL>;}export interface LocalSavedPublicCollectionFiles {diff --git a/apps/photos/src/utils/file/index.ts b/apps/photos/src/utils/file/index.tsindex 8007f93361..ca1ac22f54 100644--- a/apps/photos/src/utils/file/index.ts+++ b/apps/photos/src/utils/file/index.ts@@ -10,7 +10,7 @@ import {} from 'types/file';import { decodeLivePhoto } from 'services/livePhotoService';import { getFileType } from 'services/typeDetectionService';-import DownloadManager from 'services/downloadManager';+import DownloadManager, { SourceURLs } from 'services/downloadManager';import { logError } from '@ente/shared/sentry';import { User } from '@ente/shared/user/types';import { getData, LS_KEYS } from '@ente/shared/storage/localStorage';@@ -277,56 +277,74 @@ export function generateStreamFromArrayBuffer(data: Uint8Array) {});}-export async function getRenderableFileURL(file: EnteFile, fileBlob: Blob) {+export async function getRenderableFileURL(+ file: EnteFile,+ fileBlob: Blob,+ fileOriginalURL: string,+ forceConvert: boolean+): Promise<SourceURLs> {+ let srcURLs: SourceURLs['url'];switch (file.metadata.fileType) {case FILE_TYPE.IMAGE: {const convertedBlob = await getRenderableImage(file.metadata.title,fileBlob);- const { originalURL, convertedURL } = getFileObjectURLs(+ const convertedURL = getFileObjectURLs(+ fileOriginalURL,fileBlob,convertedBlob);- return {- converted: [convertedURL],- original: [originalURL],- };+ srcURLs = convertedURL;+ break;}case FILE_TYPE.LIVE_PHOTO: {- return await getRenderableLivePhotoURL(file, fileBlob);+ srcURLs = await getRenderableLivePhotoURL(+ file,+ fileBlob,+ forceConvert+ );+ break;}case FILE_TYPE.VIDEO: {const convertedBlob = await getPlayableVideo(file.metadata.title,- fileBlob+ fileBlob,+ forceConvert);- const { originalURL, convertedURL } = getFileObjectURLs(+ const convertedURL = getFileObjectURLs(+ fileOriginalURL,fileBlob,convertedBlob);- return {- converted: [convertedURL],- original: [originalURL],- };+ srcURLs = convertedURL;+ break;}default: {- const previewURL = await createTypedObjectURL(- fileBlob,- file.metadata.title- );- return {- converted: [previewURL],- original: [previewURL],- };+ srcURLs = fileOriginalURL;+ break;}}++ let isOriginal = false;+ if (file.metadata.fileType === FILE_TYPE.LIVE_PHOTO) {+ isOriginal = false;+ } else {+ isOriginal = (srcURLs as string) === (fileOriginalURL as string);+ }++ return {+ url: srcURLs,+ isOriginal,+ isRenderable: !!srcURLs,+ };}async function getRenderableLivePhotoURL(file: EnteFile,- fileBlob: Blob-): Promise<{ original: string[]; converted: string[] }> {+ fileBlob: Blob,+ forceConvert: boolean+): Promise<{ image: string; video: string }> {const livePhoto = await decodeLivePhoto(file, fileBlob);const imageBlob = new Blob([livePhoto.image]);const videoBlob = new Blob([livePhoto.video]);@@ -337,16 +355,14 @@ async function getRenderableLivePhotoURL(const convertedVideoBlob = await getPlayableVideo(livePhoto.videoNameTitle,videoBlob,- true+ forceConvert);- const { originalURL: originalImageURL, convertedURL: convertedImageURL } =- getFileObjectURLs(imageBlob, convertedImageBlob);+ const convertedImageURL = URL.createObjectURL(convertedImageBlob);+ const convertedVideoURL = URL.createObjectURL(convertedVideoBlob);- const { originalURL: originalVideoURL, convertedURL: convertedVideoURL } =- getFileObjectURLs(videoBlob, convertedVideoBlob);return {- converted: [convertedImageURL, convertedVideoURL],- original: [originalImageURL, originalVideoURL],+ image: convertedImageURL,+ video: convertedVideoURL,};}@@ -632,7 +648,9 @@ export async function downloadFileDesktop(file: EnteFile,downloadPath: string) {- const fileStream = await DownloadManager.getFile(file);+ const fileStream = (await DownloadManager.getFile(+ file+ )) as ReadableStream<Uint8Array>;const updatedFileStream = await getUpdatedEXIFFileForDownload(fileReader,file,@@ -900,12 +918,15 @@ const fixTimeHelper = async (setFixCreationTimeAttributes({ files: selectedFiles });};-const getFileObjectURLs = (originalBlob: Blob, convertedBlob: Blob) => {- const originalURL = URL.createObjectURL(originalBlob);+const getFileObjectURLs = (+ originalFileURL: string,+ originalBlob: Blob,+ convertedBlob: Blob+) => {const convertedURL = convertedBlob? convertedBlob === originalBlob- ? originalURL+ ? originalFileURL: URL.createObjectURL(convertedBlob): null;- return { originalURL, convertedURL };+ return convertedURL;};diff --git a/apps/photos/src/utils/photoFrame/index.ts b/apps/photos/src/utils/photoFrame/index.tsindex 7637898f92..0a303e3294 100644--- a/apps/photos/src/utils/photoFrame/index.ts+++ b/apps/photos/src/utils/photoFrame/index.ts@@ -1,7 +1,7 @@import { FILE_TYPE } from 'constants/file';import { EnteFile } from 'types/file';-import { MergedSourceURL } from 'types/gallery';import { logError } from '@ente/shared/sentry';+import { SourceURLs } from 'services/downloadManager';const WAIT_FOR_VIDEO_PLAYBACK = 1 * 1000;@@ -67,82 +67,40 @@ export function updateFileMsrcProps(file: EnteFile, url: string) {}}-export async function updateFileSrcProps(- file: EnteFile,- mergedURL: MergedSourceURL-) {- const urls = {- original: mergedURL.original.split(','),- converted: mergedURL.converted.split(','),- };- let originalImageURL;- let originalVideoURL;- let convertedImageURL;- let convertedVideoURL;- let originalURL;- let isConverted;- let conversionFailed;- if (file.metadata.fileType === FILE_TYPE.LIVE_PHOTO) {- [originalImageURL, originalVideoURL] = urls.original;- [convertedImageURL, convertedVideoURL] = urls.converted;- isConverted =- originalVideoURL !== convertedVideoURL ||- originalImageURL !== convertedImageURL;- conversionFailed = !convertedVideoURL || !convertedImageURL;- } else if (file.metadata.fileType === FILE_TYPE.VIDEO) {- [originalVideoURL] = urls.original;- [convertedVideoURL] = urls.converted;- isConverted = originalVideoURL !== convertedVideoURL;- conversionFailed = !convertedVideoURL;- } else if (file.metadata.fileType === FILE_TYPE.IMAGE) {- [originalImageURL] = urls.original;- [convertedImageURL] = urls.converted;- isConverted = originalImageURL !== convertedImageURL;- conversionFailed = !convertedImageURL;- } else {- [originalURL] = urls.original;- isConverted = false;- conversionFailed = false;- }-- const isPlayable = !isConverted || (isConverted && !conversionFailed);-- file.w = window.innerWidth;- file.h = window.innerHeight;- file.isSourceLoaded = true;- file.originalImageURL = originalImageURL;- file.originalVideoURL = originalVideoURL;- file.isConverted = isConverted;- file.conversionFailed = conversionFailed;-- if (!isPlayable) {+export async function updateFileSrcProps(file: EnteFile, srcURLs: SourceURLs) {+ const { url, isRenderable } = srcURLs;+ if (!isRenderable) {return;}if (file.metadata.fileType === FILE_TYPE.VIDEO) {file.html = `<video controls onContextMenu="return false;">- <source src="${convertedVideoURL}" />+ <source src="${url}" />Your browser does not support the video tag.</video>`;} else if (file.metadata.fileType === FILE_TYPE.LIVE_PHOTO) {+ const { image: imageURL, video: videoURL } = url as {+ image: string;+ video: string;+ };file.html = `<div class = 'pswp-item-container'>- <img id = "live-photo-image-${file.id}" src="${convertedImageURL}" onContextMenu="return false;"/>+ <img id = "live-photo-image-${file.id}" src="${imageURL}" onContextMenu="return false;"/><video id = "live-photo-video-${file.id}" loop muted onContextMenu="return false;">- <source src="${convertedVideoURL}" />+ <source src="${videoURL}" />Your browser does not support the video tag.</video></div>`;} else if (file.metadata.fileType === FILE_TYPE.IMAGE) {- file.src = convertedImageURL;+ file.src = url as string;} else {logError(Error(`unknown file type - ${file.metadata.fileType}`),'Unknown file type');- file.src = originalURL;+ file.src = url as string;}}diff --git a/apps/photos/src/utils/publicCollectionGallery/index.ts b/apps/photos/src/utils/publicCollectionGallery/index.tsindex f6f26f433d..e9d08bbc4e 100644--- a/apps/photos/src/utils/publicCollectionGallery/index.ts+++ b/apps/photos/src/utils/publicCollectionGallery/index.ts@@ -9,8 +9,6 @@ const defaultPublicCollectionGalleryContext: PublicCollectionGalleryContextTypeaccessedThroughSharedURL: false,photoListHeader: null,photoListFooter: null,- files: new Map(),- thumbs: new Map(),};export const PublicCollectionGalleryContext =