Skip to content

armgit / ente

Public Imported from GitHub
0

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

Speed up public album thumbnails and viewer

Anand Baburajanebfff4e07264
diff --git a/web/apps/albums/src/gallery/components/viewer/lazy.ts b/web/apps/albums/src/gallery/components/viewer/lazy.ts
index be337d7dee..da76433bb0 100644
--- a/web/apps/albums/src/gallery/components/viewer/lazy.ts
+++ b/web/apps/albums/src/gallery/components/viewer/lazy.ts
@@ -2,15 +2,76 @@ import dynamic from "next/dynamic";
import type { FileViewerProps } from "./FileViewer";
import type { PublicFeedSidebarProps } from "./PublicFeedSidebar";
+const loadFileViewer = () => import("./FileViewer");
+const loadPublicFeedSidebar = () => import("./PublicFeedSidebar");
+
export const LazyFileViewer = dynamic<FileViewerProps>(
- () => import("./FileViewer").then(({ FileViewer }) => FileViewer),
+ () => loadFileViewer().then(({ FileViewer }) => FileViewer),
{ ssr: false },
);
export const LazyPublicFeedSidebar = dynamic<PublicFeedSidebarProps>(
() =>
- import("./PublicFeedSidebar").then(
+ loadPublicFeedSidebar().then(
({ PublicFeedSidebar }) => PublicFeedSidebar,
),
{ ssr: false },
);
+
+let fileViewerPreload: Promise<void> | undefined;
+
+export const preloadFileViewer = () => {
+ if (typeof window === "undefined") {
+ return Promise.resolve();
+ }
+
+ fileViewerPreload ??= loadFileViewer().then(() => undefined);
+ return fileViewerPreload;
+};
+
+export const scheduleFileViewerPreload = () => {
+ if (typeof window === "undefined") {
+ return () => undefined;
+ }
+
+ let isCancelled = false;
+ let idleCallbackID: number | undefined;
+
+ const warmViewer = () => {
+ if (isCancelled) return;
+ void preloadFileViewer();
+ };
+
+ const requestWarmupOnIdle = () => {
+ const requestIdleCallback =
+ "requestIdleCallback" in window
+ ? window.requestIdleCallback.bind(window)
+ : undefined;
+
+ if (requestIdleCallback) {
+ idleCallbackID = requestIdleCallback(warmViewer, {
+ timeout: 1500,
+ });
+ } else {
+ idleCallbackID = window.setTimeout(warmViewer, 0);
+ }
+ };
+
+ requestWarmupOnIdle();
+
+ return () => {
+ isCancelled = true;
+ if (idleCallbackID !== undefined) {
+ const cancelIdleCallback =
+ "cancelIdleCallback" in window
+ ? window.cancelIdleCallback.bind(window)
+ : undefined;
+
+ if (cancelIdleCallback) {
+ cancelIdleCallback(idleCallbackID);
+ } else {
+ window.clearTimeout(idleCallbackID);
+ }
+ }
+ };
+};
diff --git a/web/apps/albums/src/gallery/services/download.ts b/web/apps/albums/src/gallery/services/download.ts
index c093f378f2..43391c316c 100644
--- a/web/apps/albums/src/gallery/services/download.ts
+++ b/web/apps/albums/src/gallery/services/download.ts
@@ -19,6 +19,10 @@ import type { EnteFile } from "ente-media/file";
import { fileFileName } from "ente-media/file-metadata";
import { FileType } from "ente-media/file-type";
import { decodeLivePhoto } from "ente-media/live-photo";
+import {
+ getPublicAlbumsCredentials,
+ setPublicAlbumsCredentials,
+} from "./public-albums-credentials";
import { detectFileTypeInfoFromChunk } from "../utils/detect-type";
import { playableVideoURL, renderableImageBlob } from "./convert";
@@ -104,11 +108,9 @@ export type RenderableSourceURLs =
* be called on logout to reset its internal state.
*/
class DownloadManager {
- /**
- * Credentials that should be used to download files when we're in the
- * context of the public albums app.
- */
- publicAlbumsCredentials: PublicAlbumsCredentials | undefined;
+ get publicAlbumsCredentials() {
+ return getPublicAlbumsCredentials();
+ }
/**
* Local cache for thumbnail blobs.
*
@@ -186,7 +188,7 @@ class DownloadManager {
* Reset the internal state of the download manager.
*/
logout() {
- this.publicAlbumsCredentials = undefined;
+ setPublicAlbumsCredentials(undefined);
this.thumbnailURLPromises.clear();
this.fileURLPromises.clear();
this.renderableSourceURLPromises.clear();
@@ -201,7 +203,7 @@ class DownloadManager {
setPublicAlbumsCredentials(
credentials: PublicAlbumsCredentials | undefined,
) {
- this.publicAlbumsCredentials = credentials;
+ setPublicAlbumsCredentials(credentials);
}
/**
diff --git a/web/apps/albums/src/gallery/services/public-albums-credentials.ts b/web/apps/albums/src/gallery/services/public-albums-credentials.ts
new file mode 100644
index 0000000000..62335cc1c5
--- /dev/null
+++ b/web/apps/albums/src/gallery/services/public-albums-credentials.ts
@@ -0,0 +1,11 @@
+import type { PublicAlbumsCredentials } from "ente-base/http";
+
+let publicAlbumsCredentials: PublicAlbumsCredentials | undefined;
+
+export const getPublicAlbumsCredentials = () => publicAlbumsCredentials;
+
+export const setPublicAlbumsCredentials = (
+ credentials: PublicAlbumsCredentials | undefined,
+) => {
+ publicAlbumsCredentials = credentials;
+};
diff --git a/web/apps/albums/src/gallery/services/thumbnail-crypto.ts b/web/apps/albums/src/gallery/services/thumbnail-crypto.ts
new file mode 100644
index 0000000000..36001fc04f
--- /dev/null
+++ b/web/apps/albums/src/gallery/services/thumbnail-crypto.ts
@@ -0,0 +1,16 @@
+import { ComlinkWorker } from "ente-base/worker/comlink-worker";
+import type { BytesOrB64, EncryptedBlob } from "ente-base/crypto/types";
+import type { ThumbnailCryptoWorker } from "./thumbnail-crypto.worker";
+
+let _comlinkWorker: ComlinkWorker<typeof ThumbnailCryptoWorker> | undefined;
+
+const sharedWorker = () =>
+ (_comlinkWorker ??= new ComlinkWorker<typeof ThumbnailCryptoWorker>(
+ "albums-thumbnail-crypto",
+ new Worker(new URL("thumbnail-crypto.worker.ts", import.meta.url)),
+ )).remote;
+
+export const decryptThumbnailBlobBytes = (
+ blob: EncryptedBlob,
+ key: BytesOrB64,
+) => sharedWorker().then((w) => w.decryptBlobBytes(blob, key));
diff --git a/web/apps/albums/src/gallery/services/thumbnail-crypto.worker.ts b/web/apps/albums/src/gallery/services/thumbnail-crypto.worker.ts
new file mode 100644
index 0000000000..6fca8539ea
--- /dev/null
+++ b/web/apps/albums/src/gallery/services/thumbnail-crypto.worker.ts
@@ -0,0 +1,14 @@
+import { expose } from "comlink";
+import { decryptBlobBytes } from "ente-base/crypto/libsodium";
+import { logUnhandledErrorsAndRejectionsInWorker } from "ente-base/log-web";
+import type { BytesOrB64, EncryptedBlob } from "ente-base/crypto/types";
+
+export class ThumbnailCryptoWorker {
+ decryptBlobBytes(blob: EncryptedBlob, key: BytesOrB64) {
+ return decryptBlobBytes(blob, key);
+ }
+}
+
+expose(ThumbnailCryptoWorker);
+
+logUnhandledErrorsAndRejectionsInWorker();
diff --git a/web/apps/albums/src/gallery/services/thumbnail-manager.ts b/web/apps/albums/src/gallery/services/thumbnail-manager.ts
new file mode 100644
index 0000000000..588bb2993e
--- /dev/null
+++ b/web/apps/albums/src/gallery/services/thumbnail-manager.ts
@@ -0,0 +1,185 @@
+import { blobCache, type BlobCache } from "ente-base/blob-cache";
+import {
+ authenticatedPublicAlbumsRequestHeaders,
+ authenticatedRequestHeaders,
+ publicRequestHeaders,
+ retryEnsuringHTTPOk,
+ type PublicAlbumsCredentials,
+} from "ente-base/http";
+import log from "ente-base/log";
+import { customAPIOrigin } from "ente-base/origins";
+import { ensureAuthToken } from "ente-base/token";
+import type { EnteFile } from "ente-media/file";
+import {
+ getPublicAlbumsCredentials,
+ setPublicAlbumsCredentials,
+} from "./public-albums-credentials";
+import { decryptThumbnailBlobBytes } from "./thumbnail-crypto";
+
+class ThumbnailManager {
+ private thumbnailCache: BlobCache | null | undefined;
+ private thumbnailURLPromises = new Map<number, Promise<string | undefined>>();
+
+ get publicAlbumsCredentials() {
+ return getPublicAlbumsCredentials();
+ }
+
+ setPublicAlbumsCredentials(
+ credentials: PublicAlbumsCredentials | undefined,
+ ) {
+ setPublicAlbumsCredentials(credentials);
+ }
+
+ private async initThumbnailCacheIfNeeded() {
+ if (this.thumbnailCache === undefined) {
+ try {
+ this.thumbnailCache = await blobCache("thumbs");
+ } catch (e) {
+ this.thumbnailCache = null;
+ log.error(
+ "Failed to open thumbnail cache, will continue without it",
+ e,
+ );
+ }
+ }
+ }
+
+ async renderableThumbnailURL(
+ file: EnteFile,
+ cachedOnly = false,
+ ): Promise<string | undefined> {
+ if (!this.thumbnailURLPromises.has(file.id)) {
+ const url = this.thumbnailData(file, cachedOnly).then((data) =>
+ data ? URL.createObjectURL(new Blob([data])) : undefined,
+ );
+ this.thumbnailURLPromises.set(file.id, url);
+ }
+
+ let thumb: string | undefined;
+ try {
+ thumb = await this.thumbnailURLPromises.get(file.id);
+ } catch (e) {
+ this.thumbnailURLPromises.delete(file.id);
+ throw e;
+ }
+
+ if (cachedOnly) return thumb;
+
+ if (!thumb) {
+ this.thumbnailURLPromises.delete(file.id);
+ thumb = await this.renderableThumbnailURL(file);
+ }
+ return thumb;
+ }
+
+ async thumbnailData(file: EnteFile, cachedOnly = false) {
+ await this.initThumbnailCacheIfNeeded();
+
+ const key = file.id.toString();
+ const cached = await this.thumbnailCache?.get(key);
+ if (cached) return new Uint8Array(await cached.arrayBuffer());
+ if (cachedOnly) return undefined;
+
+ const thumb = await this.downloadThumbnail(file);
+ await this.thumbnailCache?.put(key, new Blob([thumb]));
+ return thumb;
+ }
+
+ private downloadThumbnail = async (file: EnteFile) => {
+ const encryptedData = await wrapErrors(() =>
+ this._downloadThumbnail(file),
+ );
+ const decryptionHeader = file.thumbnail.decryptionHeader;
+ return decryptThumbnailBlobBytes(
+ { encryptedData, decryptionHeader },
+ file.key,
+ );
+ };
+
+ private async _downloadThumbnail(file: EnteFile) {
+ if (this.publicAlbumsCredentials) {
+ return publicAlbums_downloadThumbnail(
+ file,
+ this.publicAlbumsCredentials,
+ );
+ } else {
+ return photos_downloadThumbnail(file);
+ }
+ }
+}
+
+export const thumbnailManager = new ThumbnailManager();
+
+class NetworkThumbnailError extends Error {
+ error: unknown;
+
+ constructor(e: unknown) {
+ super(
+ `NetworkThumbnailError: ${e instanceof Error ? e.message : String(e)}`,
+ );
+
+ if (Error.captureStackTrace)
+ Error.captureStackTrace(this, NetworkThumbnailError);
+
+ this.error = e;
+ }
+}
+
+const wrapErrors = <T>(op: () => Promise<T>) =>
+ op().catch((e: unknown) => {
+ throw new NetworkThumbnailError(e);
+ });
+
+const photos_downloadThumbnail = async (file: EnteFile) => {
+ const customOrigin = await customAPIOrigin();
+
+ const getThumbnail = async () => {
+ if (customOrigin) {
+ const token = await ensureAuthToken();
+ const params = new URLSearchParams({ token });
+ return fetch(
+ `${customOrigin}/files/preview/${file.id}?${params.toString()}`,
+ { headers: publicRequestHeaders() },
+ );
+ } else {
+ return fetch(`https://thumbnails.ente.io/?fileID=${file.id}`, {
+ headers: await authenticatedRequestHeaders(),
+ });
+ }
+ };
+
+ const res = await retryEnsuringHTTPOk(getThumbnail);
+ return new Uint8Array(await res.arrayBuffer());
+};
+
+const publicAlbums_downloadThumbnail = async (
+ file: EnteFile,
+ credentials: PublicAlbumsCredentials,
+) => {
+ const customOrigin = await customAPIOrigin();
+
+ const getThumbnail = async () => {
+ if (customOrigin) {
+ const { accessToken, accessTokenJWT } = credentials;
+ const params = new URLSearchParams({
+ accessToken,
+ ...(accessTokenJWT && { accessTokenJWT }),
+ });
+ return fetch(
+ `${customOrigin}/public-collection/files/preview/${file.id}?${params.toString()}`,
+ { headers: publicRequestHeaders() },
+ );
+ } else {
+ return fetch(
+ `https://public-albums.ente.io/preview/?fileID=${file.id}`,
+ {
+ headers:
+ authenticatedPublicAlbumsRequestHeaders(credentials),
+ },
+ );
+ }
+ };
+
+ const res = await retryEnsuringHTTPOk(getThumbnail);
+ return new Uint8Array(await res.arrayBuffer());
+};
diff --git a/web/apps/albums/src/pages/index.tsx b/web/apps/albums/src/pages/index.tsx
index a1a78cbf47..8a19716a06 100644
--- a/web/apps/albums/src/pages/index.tsx
+++ b/web/apps/albums/src/pages/index.tsx
@@ -57,7 +57,7 @@ import {
import { type FileViewerInitialSidebar } from "@/gallery/components/viewer/FileViewer";
import { type PublicFeedItemClickInfo } from "@/gallery/components/viewer/PublicFeedSidebar";
import { LazyPublicFeedSidebar } from "@/gallery/components/viewer/lazy";
-import { downloadManager } from "@/gallery/services/download";
+import { setPublicAlbumsCredentials } from "@/gallery/services/public-albums-credentials";
import { sortFiles } from "@/gallery/utils/file";
import type { Collection } from "ente-media/collection";
import { type EnteFile } from "ente-media/file";
@@ -295,7 +295,7 @@ export default function PublicCollectionGallery() {
await savedPublicCollectionAccessTokenJWT(accessToken);
}
credentials.current = { accessToken, accessTokenJWT };
- downloadManager.setPublicAlbumsCredentials(credentials.current);
+ setPublicAlbumsCredentials(credentials.current);
await publicAlbumsRemotePull();
} finally {
if (
@@ -372,7 +372,7 @@ export default function PublicCollectionGallery() {
// disabled password protection on the link.
if (!isPasswordProtected && credentials.current?.accessTokenJWT) {
credentials.current.accessTokenJWT = undefined;
- downloadManager.setPublicAlbumsCredentials(credentials.current);
+ setPublicAlbumsCredentials(credentials.current);
removePublicCollectionAccessTokenJWT(accessToken);
}
@@ -401,9 +401,7 @@ export default function PublicCollectionGallery() {
// to reenter the password.
if (isHTTP401Error(e)) {
credentials.current!.accessTokenJWT = undefined;
- downloadManager.setPublicAlbumsCredentials(
- credentials.current,
- );
+ setPublicAlbumsCredentials(credentials.current);
} else {
throw e;
}
@@ -499,7 +497,7 @@ export default function PublicCollectionGallery() {
accessToken,
);
credentials.current!.accessTokenJWT = accessTokenJWT;
- downloadManager.setPublicAlbumsCredentials(credentials.current);
+ setPublicAlbumsCredentials(credentials.current);
await savePublicCollectionAccessTokenJWT(
accessToken,
accessTokenJWT,
diff --git a/web/apps/albums/src/public-album/components/FileList.tsx b/web/apps/albums/src/public-album/components/FileList.tsx
index 2e03dfb267..416f15fdd1 100644
--- a/web/apps/albums/src/public-album/components/FileList.tsx
+++ b/web/apps/albums/src/public-album/components/FileList.tsx
@@ -5,7 +5,7 @@ import PlayCircleOutlineOutlinedIcon from "@mui/icons-material/PlayCircleOutline
import { Box, Checkbox, Fab, Typography, styled } from "@mui/material";
import { Overlay } from "ente-base/components/containers";
import log from "ente-base/log";
-import { downloadManager } from "@/gallery/services/download";
+import { thumbnailManager } from "@/gallery/services/thumbnail-manager";
import type { EnteFile } from "ente-media/file";
import { fileDurationString } from "ente-media/file-metadata";
import { FileType } from "ente-media/file-type";
@@ -1301,7 +1301,7 @@ const FileThumbnail: React.FC<FileThumbnailProps> = ({
useEffect(() => {
let didCancel = false;
- void downloadManager
+ void thumbnailManager
.renderableThumbnailURL(file, showPlaceholder)
.then((url) => !didCancel && setImageURL(url))
.catch((e: unknown) => {
diff --git a/web/apps/albums/src/public-album/components/FileListWithViewer.tsx b/web/apps/albums/src/public-album/components/FileListWithViewer.tsx
index 202168d0ed..d447bad93b 100644
--- a/web/apps/albums/src/public-album/components/FileListWithViewer.tsx
+++ b/web/apps/albums/src/public-album/components/FileListWithViewer.tsx
@@ -6,7 +6,10 @@ import {
type FileViewerProps,
type FileViewerInitialSidebar,
} from "@/gallery/components/viewer/FileViewer";
-import { LazyFileViewer } from "@/gallery/components/viewer/lazy";
+import {
+ LazyFileViewer,
+ scheduleFileViewerPreload,
+} from "@/gallery/components/viewer/lazy";
import type { EnteFile } from "ente-media/file";
import { fileCreationTime, fileFileName } from "ente-media/file-metadata";
import { t } from "i18next";
@@ -128,6 +131,11 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({
setOpenFileViewer(false);
}, []);
+ useEffect(() => {
+ if (files.length === 0) return;
+ return scheduleFileViewerPreload();
+ }, [files.length]);
+
const annotatedFiles = useMemo(
(): FileListAnnotatedFile[] =>
files.map((file) => ({
diff --git a/web/apps/albums/src/public-album/components/TripLayout/index.tsx b/web/apps/albums/src/public-album/components/TripLayout/index.tsx
index d2c203cfdf..ff4b6d87f3 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/index.tsx
+++ b/web/apps/albums/src/public-album/components/TripLayout/index.tsx
@@ -12,6 +12,7 @@ import {
import {
LazyFileViewer,
LazyPublicFeedSidebar,
+ scheduleFileViewerPreload,
} from "@/gallery/components/viewer/lazy";
import { type Collection } from "ente-media/collection";
import { type EnteFile } from "ente-media/file";
@@ -264,6 +265,11 @@ export const TripLayout: React.FC<TripLayoutProps> = ({
setIsClient(true);
}, []);
+ useEffect(() => {
+ if (files.length === 0) return;
+ return scheduleFileViewerPreload();
+ }, [files.length]);
+
// Use extracted data processing hooks
useDataProcessing({
files,